diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 00000000000000..9c7b381540fb0d --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,90 @@ +# Code owners for aurora-silicon/linux. +# +# Every PR is reviewed by Core, Omarchy Mac or Aurora Maintainers; an +# approval from any of the three teams counts everywhere. The '# area:' +# sections only route: they add the area's specialists to the review request +# and give the readiness bot its area: +# labels. Omarchy Mac and Aurora Maintainers are listed first where they +# review first (M1 to M3 platform). Later lines win, as in every CODEOWNERS +# file, so keep all three teams on every area line. +# Routing and labels: https://github.com/aurora-silicon/agent-guidelines/blob/main/docs/MAINTAINER-HANDBOOK.md +# Merge rules: https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/merge-policy.md +# Access tiers: https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/access-tiers.md + +* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers + +# area: platform +/arch/arm64/boot/dts/apple/t8103* @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/arch/arm64/boot/dts/apple/t600* @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/arch/arm64/boot/dts/apple/t8112* @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/arch/arm64/boot/dts/apple/t602* @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/arch/arm64/boot/dts/apple/t8122* @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/arch/arm64/boot/dts/apple/t603* @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/drivers/soc/apple/ @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/drivers/iommu/apple-dart.c @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/drivers/nvme/host/apple.c @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/drivers/spmi/ @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/drivers/watchdog/apple_wdt.c @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/drivers/gpio/gpio-macsmc.c @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core + +# area: bringup +/arch/arm64/boot/dts/apple/t8132* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/arch/arm64/boot/dts/apple/t604* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/arch/arm64/boot/dts/apple/t8140* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/arch/arm64/boot/dts/apple/t8142* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/arch/arm64/boot/dts/apple/t8152* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/arch/arm64/boot/dts/apple/t6050* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers + +# area: gpu +/drivers/gpu/drm/asahi/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @DjDeveloperr +/include/uapi/drm/asahi_drm.h @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @DjDeveloperr +/tools/asahi/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @DjDeveloperr + +# area: display +/drivers/gpu/drm/apple/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/gpu/drm/tiny/appletbdrm.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers + +# area: audio +/sound/soc/apple/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/sound/soc/codecs/tas2764* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/sound/soc/codecs/tas2770* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/sound/soc/codecs/cs42l83* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/sound/soc/codecs/cs42l84* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers + +# area: power +/drivers/pmdomain/apple/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/cpufreq/apple-soc-cpufreq.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/mfd/macsmc.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/power/supply/macsmc-power* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/rtc/rtc-macsmc.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/hwmon/macsmc-hwmon.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers + +# area: usb +/drivers/usb/typec/tipd/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/phy/apple/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/thunderbolt/apple* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers + +# area: media +/drivers/media/platform/apple/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/accel/ane/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers + +# area: wireless +/drivers/net/wireless/broadcom/brcm80211/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/bluetooth/hci_bcm4377.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers + +# area: input +/drivers/input/touchscreen/apple_z2.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/input/misc/macsmc-input.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/hid/hid-apple.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers + +# area: rust +/rust/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers + +# Files whose change affects every user or the release process: an Owner +# reviews them. Keep these last so they win. +# area: release +/.github/ @RyanTheTide @DjDeveloperr +/arch/arm64/configs/aurora_defconfig @RyanTheTide @DjDeveloperr +/RELEASES.md @RyanTheTide @DjDeveloperr +/CONTRIBUTING.md @RyanTheTide @DjDeveloperr +# end-area diff --git a/.github/ISSUE_TEMPLATE/aurora_bug.yml b/.github/ISSUE_TEMPLATE/aurora_bug.yml deleted file mode 100644 index 245aa165168064..00000000000000 --- a/.github/ISSUE_TEMPLATE/aurora_bug.yml +++ /dev/null @@ -1,66 +0,0 @@ -name: Aurora Linux bug -description: Report one reproducible problem with machine, build, and error details. -labels: [bug] -body: - - type: markdown - attributes: - value: | - Search existing issues first. Add evidence for a known bug there and link related issues or code examples. For broad testing, use the test-report form and keep one report per Mac. - See [reporting guidance](https://github.com/omacom/linux-aurora/blob/integration/aurora/CONTRIBUTING.md) and the [roadmap #56](https://github.com/omacom/linux-aurora/issues/56). - Never attach serials, addresses, keys, fingerprints, calibration bytes, raw device trees, per-unit firmware images, or core dumps. Review logs for private data. - - type: textarea - id: environment - attributes: - label: Mac and installed build - description: Exact installed release tag, running kernel, bootloader/package versions, distribution, and any local changes. If boot fails, give what is available. - placeholder: | - Model / board / SoC: MacBook Pro M3 Pro / apple,j516s / apple,t6031 - Installed Aurora tag: - uname -r: - Bootloader and relevant package versions: - Distribution / local patches: - validations: - required: true - - type: textarea - id: firmware - attributes: - label: Both firmware versions and provisioning - description: Read both fields from /proc/device-tree/chosen/. Say unavailable if not accessible. For calibration problems, state provisioning status and whether data came from this Mac; do not upload it. - placeholder: | - asahi,os-fw-version: - asahi,system-fw-version: - Own-Mac provisioning status (if relevant): - validations: - required: true - - type: textarea - id: reproduction - attributes: - label: Reproduction, expected result, and actual result - description: Include the shortest steps, frequency, and last known-good / first bad build if known. For display failures, give dock/display, port, connection type, and mode. - validations: - required: true - - type: textarea - id: session - attributes: - label: Graphics or session details (if relevant) - description: Mesa version and active renderer, GPU profile/opt-in, compositor and lock-screen versions, and relevant app version. For resume, was it locked before authentication, and did the session/compositor restart? For a crash, give executable, signal, and timestamp. - - type: textarea - id: logs - attributes: - label: Relevant error lines - description: Quote literal errors with nearby context. Trim and redact logs; avoid whole journals, dmesg dumps, or core dumps. State if logs could not be collected. - render: text - validations: - required: true - - type: textarea - id: related - attributes: - label: Related issues, pull requests, or code examples - description: Link references and explain which behavior matches. Include any workaround already tried. - - type: textarea - id: untested - attributes: - label: What was not tested - description: For example, no dock available, only one port tested, or no suspend test. A build or module probe alone is not a runtime pass. - validations: - required: true diff --git a/.github/ISSUE_TEMPLATE/aurora_test_report.yml b/.github/ISSUE_TEMPLATE/aurora_test_report.yml deleted file mode 100644 index 8abd593f2bf2ad..00000000000000 --- a/.github/ISSUE_TEMPLATE/aurora_test_report.yml +++ /dev/null @@ -1,57 +0,0 @@ -name: Aurora Linux per-Mac test report -description: Record results for one Mac; append later tests to the same issue. -title: "[board] (Mac model): test results" -labels: [test-report] -body: - - type: markdown - attributes: - value: | - Keep one broad test-report issue per Mac and append later results as comments. Add detailed evidence for known bugs to their existing issues and link them here. - See [reporting guidance](https://github.com/omacom/linux-aurora/blob/integration/aurora/CONTRIBUTING.md) and the [roadmap #56](https://github.com/omacom/linux-aurora/issues/56). - Never attach serials, addresses, keys, fingerprints, calibration bytes, raw device trees, per-unit firmware images, or core dumps. Review logs for private data. - - type: textarea - id: environment - attributes: - label: Mac and installed build - description: Model, board/SoC from /proc/device-tree/compatible, exact installed Aurora tag, uname -r, bootloader/package versions, distribution, and local changes. Say unavailable where necessary. - validations: - required: true - - type: textarea - id: firmware - attributes: - label: Both firmware versions and provisioning - description: Read both fields from /proc/device-tree/chosen/. Report own-Mac provisioning status if relevant, never calibration contents. - placeholder: | - asahi,os-fw-version: - asahi,system-fw-version: - Own-Mac provisioning status (if relevant): - validations: - required: true - - type: textarea - id: results - attributes: - label: Actions and results - description: List pass/fail/not tested per action. Distinguish Touch ID enrolment/verification/after reboot, display coldplug/hotplug and connection/port/mode, and actual Bluetooth/audio operation. A loaded driver or successful compile is not a pass. - placeholder: | - Feature / action | pass, fail, or not tested | details - For failures: steps, frequency, last known-good / first bad build, related bug link. - validations: - required: true - - type: textarea - id: session - attributes: - label: Graphics and session details - description: Mesa version and active renderer, GPU profile/opt-in, compositor/lock-screen versions, and relevant apps. If suspend was tested, was the session locked before authentication, and did it resume or restart? Give executable, signal, and timestamp for crashes. Say not tested or unavailable where appropriate. - - type: textarea - id: logs - attributes: - label: Relevant logs and related reports - description: Literal error lines with nearby context, or no errors observed. Trim and redact logs; avoid whole journals or dmesg dumps. Link canonical bugs, code examples, and earlier results. - render: text - - type: textarea - id: untested - attributes: - label: Untested features and limitations - description: Be explicit about unavailable peripherals, untested ports, firmware combinations, or suspend/crash checks. - validations: - required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 03486756a029cf..00000000000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,8 +0,0 @@ -blank_issues_enabled: true -contact_links: - - name: Reporting guide and existing per-Mac reports - url: https://github.com/omacom/linux-aurora/blob/integration/aurora/CONTRIBUTING.md - about: Check how to report results and append to an existing report for your Mac. - - name: Aurora Linux bug-fix roadmap - url: https://github.com/omacom/linux-aurora/issues/56 - about: Find priorities and canonical issue links before opening a duplicate. diff --git a/.github/scripts/kernel-release-build.sh b/.github/scripts/kernel-release-build.sh new file mode 100755 index 00000000000000..14ef7d4a80606e --- /dev/null +++ b/.github/scripts/kernel-release-build.sh @@ -0,0 +1,154 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0-only +# +# Build the Aurora kernel release artifacts from this tree. +# +# Usage: kernel-release-build.sh +# +# The configuration is the fleet configuration: arch/arm64/configs/aurora_defconfig +# (savedefconfig output of the fleet .config) with arch/arm64/configs/asahi.config +# merged on top, so options added to asahi.config reach the release before +# aurora_defconfig is regenerated. Requires ARCH=arm64 LLVM=1 toolchain in PATH +# (clang/lld, rustc + rust-src, bindgen, pahole). +# +# Modules are signed with the key the build generates (certs/signing_key.pem). +# The private key is deleted at the end and never packaged. + +set -euo pipefail + +O=$(realpath -m "$1") +D=$(realpath -m "$2") +LV=$3 +PKGBASE=$4 +S=$(git rev-parse --show-toplevel) +JOBS=${JOBS:-$(nproc)} + +export ARCH=arm64 LLVM=1 +export KBUILD_BUILD_USER=${KBUILD_BUILD_USER:-aurora} KBUILD_BUILD_HOST=${KBUILD_BUILD_HOST:-github} +export KBUILD_BUILD_TIMESTAMP=${KBUILD_BUILD_TIMESTAMP:-$(git -C "$S" log -1 --format=%cD HEAD)} +# Build number (uname -v '#N') and Arch pkgrel: the source commit's +# committer time in Unix seconds, so every new main commit gets a higher +# package version than the last one (pacman never upgrades between equal +# versions) and a rebuild of the same commit gets the same one. Ten digits +# keep UTS_VERSION within its 64 bytes. +REVISION=${KBUILD_BUILD_VERSION:-$(git -C "$S" log -1 --format=%ct HEAD)} +export KBUILD_BUILD_VERSION=$REVISION + +mk() { make -C "$S" O="$O" LOCALVERSION="$LV" -j"$JOBS" "$@"; } + +mkdir -p "$O" "$D" +rm -f "$O/.config" + +echo "::group::toolchain" +clang --version | head -1 +ld.lld --version | head -1 +rustc --version +bindgen --version +pahole --version +echo "::endgroup::" + +echo "::group::config" +mk aurora_defconfig asahi.config +mk savedefconfig +if cmp -s "$O/defconfig" "$S/arch/arm64/configs/aurora_defconfig"; then + echo "config: identical to aurora_defconfig" +else + echo "::warning::generated config differs from aurora_defconfig (asahi.config or Kconfig changed); regenerate it with savedefconfig" + diff -u "$S/arch/arm64/configs/aurora_defconfig" "$O/defconfig" || true +fi +python3 - "$S/arch/arm64/configs/asahi.config" "$O/.config" <<'PY' +import re, sys +def load(p): + d = {} + for l in open(p): + l = l.strip() + m = re.match(r'^(CONFIG_\w+)=(.*)$', l) + if m: + d[m.group(1)] = m.group(2) + continue + m = re.match(r'^# (CONFIG_\w+) is not set$', l) + if m: + d[m.group(1)] = 'n' + return d +want, have = load(sys.argv[1]), load(sys.argv[2]) +bad = [(k, v, have.get(k, 'n')) for k, v in want.items() if have.get(k, 'n') != v] +print(f"asahi.config requests {len(want)}; mismatches {len(bad)}") +for k, v, h in bad: + print(f"MISMATCH {k}: want {v} got {h}") +sys.exit(1 if bad else 0) +PY +grep -qx 'CONFIG_MODULE_SIG_KEY="certs/signing_key.pem"' "$O/.config" +echo "::endgroup::" + +echo "::group::build" +mk Image.gz modules dtbs +echo "::endgroup::" + +ARCH_RUNTIME= +echo "::group::pacman-pkg" +if command -v makepkg >/dev/null; then + rm -f "$O"/*.pkg.tar.* + # make pacman-pkg takes pkgrel from scripts/build-version, which + # prints .version + 1. + echo $((REVISION - 1)) > "$O/.version" + # Debian/Ubuntu's makepkg.conf defaults to .pkg.tar.gz. + if PKGEXT=.pkg.tar.zst mk PACMAN_PKGBASE="$PKGBASE" PACMAN_EXTRAPACKAGES=headers \ + MAKEPKGOPTS="--nodeps --noconfirm" pacman-pkg; then + runtimes=("$O"/"$PKGBASE"-[0-9]*.pkg.tar.zst) + headers=("$O"/"$PKGBASE"-headers-[0-9]*.pkg.tar.zst) + if [[ ${#runtimes[@]} -ne 1 || ! -f ${runtimes[0]} || + ${#headers[@]} -ne 1 || ! -f ${headers[0]} ]]; then + echo "::error::expected one Arch runtime and one headers package"; exit 1 + fi + ARCH_RUNTIME=${runtimes[0]} + ARCH_HEADERS=${headers[0]} + cp "$ARCH_RUNTIME" "$ARCH_HEADERS" "$D/" + else + echo "::warning::make pacman-pkg failed; release ships without the Arch package" + fi +else + echo "::warning::makepkg not installed; skipping the Arch package" +fi +echo "::endgroup::" + +KREL=$(cat "$O/include/config/kernel.release") +if [[ -n $ARCH_RUNTIME ]]; then + member="usr/lib/modules/$KREL/build" + tar --zstd -xOf "$ARCH_HEADERS" "$member/.config" > "$D/config-$KREL" + tar --zstd -xOf "$ARCH_HEADERS" "$member/System.map" > "$D/System.map-$KREL" + bash "$S/.github/scripts/kernel-release-stage-arch.sh" \ + "$ARCH_RUNTIME" "$KREL" "$D/System.map-$KREL" "$D" +else + M=$O/modroot + rm -rf "$M" + mk INSTALL_MOD_PATH="$M" INSTALL_MOD_STRIP=1 modules_install + rm -f "$M/lib/modules/$KREL/build" "$M/lib/modules/$KREL/source" + + TAR=(tar --sort=name --mtime="$KBUILD_BUILD_TIMESTAMP" --owner=0 --group=0 --numeric-owner) + cp "$O/arch/arm64/boot/Image.gz" "$D/Image-$KREL.gz" + cp "$O/.config" "$D/config-$KREL" + cp "$O/System.map" "$D/System.map-$KREL" + "${TAR[@]}" --zstd -C "$M" -cf "$D/modules-$KREL.tar.zst" "lib/modules/$KREL" + "${TAR[@]}" --zstd -C "$O/arch/arm64/boot/dts" -cf "$D/dtbs-$KREL.tar.zst" \ + $(cd "$O/arch/arm64/boot/dts" && find . -name '*.dtb' | sort) +fi +cp "$O/certs/signing_key.x509" "$D/module-signing-cert-$KREL.der" +git -C "$S" rev-parse HEAD > "$D/source.commit" +echo "$KREL" > "$D/kernel.release" +echo "dtbs: $(cd "$O/arch/arm64/boot/dts" && find . -name '*.dtb' | wc -l)" + +# The private signing key stays on the builder for this run only. +rm -f "$O/certs/signing_key.pem" +for f in "$D"/*.tar.* ; do + # List first: grep -q in a pipeline would end it early and, under + # pipefail, turn a match into a pass. + list=$(tar -tf "$f") || { echo "::error::cannot list $f"; exit 1; } + if grep -q 'signing_key\.pem$' <<<"$list"; then + echo "::error::$f contains the private signing key" + exit 1 + fi +done + +(cd "$D" && sha256sum $(ls | grep -v -x SHA256SUMS) > SHA256SUMS) +cat "$D/SHA256SUMS" +echo "BUILD-OK $KREL" diff --git a/.github/scripts/kernel-release-stage-arch.sh b/.github/scripts/kernel-release-stage-arch.sh new file mode 100755 index 00000000000000..c64836bf28bb1f --- /dev/null +++ b/.github/scripts/kernel-release-stage-arch.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0-only +# Stage standalone release artifacts from the Arch runtime package. + +set -euo pipefail + +package=$(realpath "$1") +release=$2 +system_map=$(realpath "$3") +output=$(realpath "$4") +stage=$(mktemp -d "$output/.arch-runtime.XXXXXX") +trap 'rm -rf -- "$stage"' EXIT + +member="usr/lib/modules/$release" +tar --no-same-owner --zstd -xf "$package" -C "$stage" "$member" +mkdir -p "$stage/lib/modules" +mv "$stage/$member" "$stage/lib/modules/" +runtime="$stage/lib/modules/$release" +mv "$runtime/dtb" "$stage/dtb" +python3 - "$runtime/vmlinuz" <<'PY' | gzip -n > "$output/Image-$release.gz" +import gzip +from pathlib import Path +import struct +import subprocess +import sys + +image = Path(sys.argv[1]).read_bytes() +if image.startswith(b"\x1f\x8b"): + image = gzip.decompress(image) +elif image[:2] == b"MZ" and image[4:8] == b"zimg": + offset, length = struct.unpack_from(" never loaded +# fail loading may fail or hang without failing the run +# warn a kernel warning while loading it does not fail the run +# kunit the suite may fail without failing the run +# Names may be shell globs. Every entry needs a reason. Remove an entry once it +# passes. +skip rcutorture runs torture kthreads until unloaded +skip locktorture runs torture kthreads until unloaded +skip scftorture runs torture kthreads until unloaded +skip rcuscale runs a benchmark until unloaded +skip refscale runs a benchmark until unloaded +skip torture only a library for the torture tests above +skip test_lockup provokes soft/hard lockups on purpose +skip test_vmalloc vmalloc stress test, runs for minutes under emulation +skip speakup_* speech synthesizer drivers; the serial ones wait for a synthesizer on a serial port +fail tcrypt returns -EAGAIN by design after running its tests +fail xusbatm needs vendor/product module parameters +fail ptp_kvm needs the KVM PTP hypervisor service +fail alim7101_wdt probes for an ALi M7101 chipset (-EBUSY without it) +fail dtpm Rockchip SoC power hierarchy, refuses on other machines +fail snd-soc-uda1342 its I2C driver name "uda1342" is already taken by the media uda1342 driver +fail nhc_ghc_* 6LoWPAN GHC compression claims the NHC IDs of the plain nhc_* modules loaded before it +warn serial_ir PC serial-port IR receiver requests a fixed legacy IRQ the virt machine does not have +warn snd-mtpav PC parallel-port MIDI driver requests a fixed legacy IRQ the virt machine does not have +fail ubifs init cannot get the zstd compressor (-ENOENT) in this initramfs; not yet triaged +kunit arm-smmu-v3-kunit-test arm_smmu_v3_invs_test trips UBSAN array-index-out-of-bounds in arm-smmu-v3.c; not yet triaged +kunit amdv1_iommu_test test_map_simple secondary page-table accounting mismatch; not yet triaged +kunit amdgpu_dm_hdcp dm_test_event_cpirq_schedules_property_validate fails; not yet triaged +kunit amdgpu_dm_irq dm_test_dcn10_register_irq_handlers_one_crtc fails; not yet triaged +kunit amdgpu_dm_crtc dm_test_crtc_enable_vblank_ips_restore{,_replay} fault (unexpected DAIF); not yet triaged +kunit binder_alloc binder_alloc_exhaustive_test reports failures; not yet triaged diff --git a/.github/scripts/kernel-smoke-qemu.sh b/.github/scripts/kernel-smoke-qemu.sh new file mode 100755 index 00000000000000..0c20fda7e019d2 --- /dev/null +++ b/.github/scripts/kernel-smoke-qemu.sh @@ -0,0 +1,194 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0-only +# +# Boot a release kernel under QEMU (virt machine) and load every module it ships. +# +# Usage: kernel-smoke-qemu.sh +# +# Loading a KUnit module runs its suites, so this also runs every KUnit suite the +# configuration builds as a module. The Apple drivers find no hardware under +# QEMU and only register themselves; real hardware is covered by the lab gate. +# +# .github/scripts/kernel-smoke-expected.txt lists modules that are not loaded +# (skip) or are known not to load or to fail under QEMU (fail), and KUnit suites +# known to fail (kunit), each with a reason. A module whose init returns -ENODEV +# or -ENXIO (no such device: it probed for hardware QEMU does not have) counts as +# loaded correctly. Anything else that fails to load, hangs, oopses, warns or +# panics fails the run. + +set -euo pipefail + +IMG=$(realpath "$1") +MODS=$(realpath "$2") +BUSYBOX=$(realpath "$3") +OUT=$(realpath -m "$4") +HERE=$(dirname "$(realpath "$0")") +EXPECTED=$HERE/kernel-smoke-expected.txt +QEMU_TIMEOUT=${QEMU_TIMEOUT:-9000} +# Per-module watchdog. Compute-heavy KUnit suites (raid6) need more than two +# minutes under emulation on the hosted ARM runners. +MOD_TIMEOUT=${MOD_TIMEOUT:-300} + +mkdir -p "$OUT" +R=$(mktemp -d "$OUT/initramfs.XXXXXX") +trap 'rm -rf "$R"' EXIT + +# sbin too: request_module() runs /sbin/modprobe. +mkdir -p "$R"/{bin,sbin,usr/bin,usr/sbin,dev,proc,sys,tmp,etc} +install -m 0755 "$BUSYBOX" "$R/bin/busybox" +tar --zstd -xf "$MODS" -C "$R" +KREL=$(ls "$R/lib/modules") +# skip entries may be shell globs (speakup_*); expand them against modules.order. +mapfile -t SKIPPAT < <(awk '$1 == "skip" { print $2 }' "$EXPECTED") +while read -r path; do + m=${path##*/}; m=${m%%.ko*} + for pat in "${SKIPPAT[@]}"; do + # shellcheck disable=SC2053 + if [[ $m == $pat ]]; then echo "$m"; break; fi + done +done < "$R/lib/modules/$KREL/modules.order" > "$R/etc/smoke-skip" +echo "skipping $(wc -l < "$R/etc/smoke-skip") modules" + +cat > "$R/init" < /dev/kmsg + modprobe "\$m" > /tmp/out 2>&1 & + pid=\$!; t=0 + while kill -0 \$pid 2>/dev/null && [ \$t -lt $MOD_TIMEOUT ]; do sleep 1; t=\$((t + 1)); done + if kill -0 \$pid 2>/dev/null; then echo "SMOKE-HANG \$m"; continue; fi + if wait \$pid; then echo "SMOKE-OK \$m" + elif grep -q "No such device" /tmp/out; then echo "SMOKE-NODEV \$m" + else echo "SMOKE-FAIL \$m \$(head -c 300 /tmp/out | tr '\n' ' ')"; fi +done < /lib/modules/\$(uname -r)/modules.order +echo SMOKE-DMESG-BEGIN +dmesg +echo SMOKE-DMESG-END +echo SMOKE-END +poweroff -f +EOF +chmod 0755 "$R/init" + +(cd "$R" && find . | LC_ALL=C sort | cpio -o -H newc --quiet | zstd -T0 -q -3 > "$OUT/initramfs.cpio.zst") +rm -rf "$R"; trap - EXIT + +ACCEL=tcg +if [ -w /dev/kvm ] && [ "$(uname -m)" = aarch64 ]; then ACCEL=kvm; fi +# pauth-impdef: the architected pointer-authentication algorithm is slow to +# emulate, and this kernel signs every return address. +CPU=max,pauth-impdef=on; [ $ACCEL = kvm ] && CPU=host +echo "qemu: accel=$ACCEL kernel=$KREL" +set +e +: > "$OUT/console.log" +timeout -k 10 "$QEMU_TIMEOUT" qemu-system-aarch64 -M virt -accel "$ACCEL" -cpu "$CPU" -smp 4 -m 6G \ + -nographic -no-reboot -nic none -kernel "$IMG" -initrd "$OUT/initramfs.cpio.zst" \ + -append "console=ttyAMA0 earlycon=pl011,0x09000000 rdinit=/init panic=-1 loglevel=4 log_buf_len=128M kunit.enable=1" \ + >> "$OUT/console.log" 2>&1 & +QEMU_PID=$! +trap 'kill -TERM "$QEMU_PID" 2>/dev/null || true' EXIT + +BOOT_DEADLINE=$((SECONDS + 300)) +while kill -0 "$QEMU_PID" 2>/dev/null && ! grep -q '^SMOKE-BEGIN ' "$OUT/console.log"; do + if (( SECONDS >= BOOT_DEADLINE )); then + echo "qemu: smoke init did not start within 300 seconds" + kill -TERM "$QEMU_PID" 2>/dev/null + break + fi + sleep 2 +done +wait "$QEMU_PID" +QRC=$? +trap - EXIT +set -e +echo "qemu exit $QRC" + +python3 - "$OUT/console.log" "$EXPECTED" "$OUT" <<'PY' +import fnmatch, re, sys, json +log, expected, out = sys.argv[1:] +text = open(log, errors='replace').read().replace('\r', '') +exp = {'skip': {}, 'fail': {}, 'warn': {}, 'kunit': {}} +for line in open(expected): + line = line.strip() + if not line or line.startswith('#'): + continue + kind, name, *why = line.split(None, 2) + exp[kind][name] = why[0] if why else '' +def expected(kind, name): + return any(fnmatch.fnmatchcase(name, pat) for pat in exp[kind]) +res = {} +for m in re.finditer(r'^SMOKE-(OK|NODEV|FAIL|HANG|SKIP) (\S+)(.*)$', text, re.M): + res[m.group(2)] = (m.group(1), m.group(3).strip()) +begin = re.search(r'^SMOKE-BEGIN (\S+) (\d+) modules', text, re.M) +ended = re.search(r'^SMOKE-END$', text, re.M) is not None +d = re.search(r'^SMOKE-DMESG-BEGIN$(.*)^SMOKE-DMESG-END$', text, re.M | re.S) +dmesg = d.group(1) if d else text +open(f'{out}/dmesg.txt', 'w').write(dmesg) +strip = lambda l: re.sub(r'^\[\s*[\d.]+\]\s?', '', l) +lines = [strip(l) for l in dmesg.splitlines()] +kunit = {} +for l in lines: + m = re.match(r'^(not ok|ok) \d+ (\S+)(.*)$', l) + if m: + kunit[m.group(2)] = 'SKIP' if '# SKIP' in m.group(3) else ('PASS' if m.group(1) == 'ok' else 'FAIL') +# Kernel warnings, oopses and stalls, attributed to the module being loaded +# (the init writes "smoke-load " to /dev/kmsg before each modprobe). +EVENT = re.compile(r'^(WARNING:|Oops|BUG:|Kernel panic|Unable to handle kernel|INFO: task .* blocked for more than|watchdog: BUG: soft lockup|rcu: INFO: .*detected stall)') +# KUnit modules provoke warnings and KFENCE reports on purpose; for them the +# suite results below are the verdict. +cur, events, kunit_mods = None, [], set() +for l in lines: + m = re.match(r'^smoke-load (\S+)$', l) + if m: + cur = m.group(1) + continue + if l.startswith('KTAP version') and cur: + kunit_mods.add(cur) + if EVENT.search(l): + events.append((cur, l)) +bad_kernel, tolerated, kunit_warn = [], [], 0 +for mod, l in events: + if mod in kunit_mods: + kunit_warn += 1 + elif mod and expected('warn', mod): + tolerated.append(f'{mod}: {l}') + else: + bad_kernel.append(f'{mod}: {l}') +problems = [] +if not begin: + problems.append('kernel did not reach the smoke init') +if not ended: + problems.append('run did not finish (panic, hang or timeout)') +counts = {} +for name, (st, msg) in res.items(): + counts[st] = counts.get(st, 0) + 1 + if st in ('FAIL', 'HANG') and not expected('fail', name): + problems.append(f'module {name}: {st} {msg}') +stale = [n for n in exp['fail'] if res.get(n, ('', ''))[0] == 'OK'] +kfail = [s for s, r in kunit.items() if r == 'FAIL' and not expected('kunit', s)] +problems += [f'KUnit suite {s}: FAIL' for s in kfail] +if bad_kernel: + problems += [f'kernel: {l}' for l in bad_kernel[:40]] +kc = {} +for r in kunit.values(): + kc[r] = kc.get(r, 0) + 1 +summary = {'kernel': begin.group(1) if begin else None, 'modules': int(begin.group(2)) if begin else 0, + 'finished': ended, 'loads': counts, 'kunit_suites': kc, + 'kunit_modules': len(kunit_mods), 'kunit_module_warnings': kunit_warn, + 'stale_expected_failures': stale, 'tolerated_warnings': tolerated, + 'kernel_warnings': bad_kernel[:50], 'problems': problems} +json.dump(summary, open(f'{out}/smoke-summary.json', 'w'), indent=1) +with open(f'{out}/smoke-results.tsv', 'w') as f: + for name, (st, msg) in sorted(res.items()): + f.write(f'{name}\t{st}\t{msg}\n') + for s, r in sorted(kunit.items()): + f.write(f'kunit:{s}\t{r}\t\n') +print(json.dumps({k: v for k, v in summary.items() if k != 'kernel_warnings'}, indent=1)[:6000]) +sys.exit(1 if problems else 0) +PY diff --git a/.github/workflows/apple-build-kunit.yml b/.github/workflows/apple-build-kunit.yml new file mode 100644 index 00000000000000..89bfaff9d8755a --- /dev/null +++ b/.github/workflows/apple-build-kunit.yml @@ -0,0 +1,196 @@ +name: Apple build and KUnit + +# Compiles every Apple driver directory with the configuration a Mac runs +# (arm64 defconfig plus asahi.config, LLVM=1 and Rust), and runs each Apple +# KUnit suite on arm64 QEMU. The suites use synthetic devices and stubbed +# firmware, so no Apple hardware is needed. Suites that have their own +# workflow are not repeated here: sep.kunitconfig (sep-source.yml), +# mt7932.kunitconfig (mt7932-kunit.yml), display.kunitconfig +# (apple-drm-kunit.yml) and .kunitconfig.pmgr-pwrstate +# (pmgr-pwrstate-kunit.yml). + +on: + pull_request: + branches: [main, integration/aurora, aurora-wip] + paths: + - 'arch/arm64/configs/**' + - 'drivers/accel/ane/**' + - 'drivers/gpu/drm/apple/**' + - 'drivers/gpu/drm/asahi/**' + - 'drivers/hid/spi-hid/**' + - 'drivers/iommu/**' + - 'drivers/media/platform/apple/**' + - 'drivers/mfd/**' + - 'drivers/net/wireless/apple/**' + - 'drivers/nvme/host/**' + - 'drivers/nvmem/**' + - 'drivers/pci/controller/**' + - 'drivers/power/**' + - 'drivers/soc/apple/**' + - 'drivers/thunderbolt/**' + - 'fs/splice.c' + - 'include/**' + - 'kernel/sys.c' + - 'mm/**' + - 'rust/**' + - 'security/keys/**' + - 'tools/testing/selftests/drivers/ane/**' + - '**/Kconfig*' + - '**/Makefile' + - '.github/workflows/apple-build-kunit.yml' + # Same paths as pull_request, so an unrelated merge does not start the jobs. + push: + branches: [main, integration/aurora] + paths: + - 'arch/arm64/configs/**' + - 'drivers/accel/ane/**' + - 'drivers/gpu/drm/apple/**' + - 'drivers/gpu/drm/asahi/**' + - 'drivers/hid/spi-hid/**' + - 'drivers/iommu/**' + - 'drivers/media/platform/apple/**' + - 'drivers/mfd/**' + - 'drivers/net/wireless/apple/**' + - 'drivers/nvme/host/**' + - 'drivers/nvmem/**' + - 'drivers/pci/controller/**' + - 'drivers/power/**' + - 'drivers/soc/apple/**' + - 'drivers/thunderbolt/**' + - 'fs/splice.c' + - 'include/**' + - 'kernel/sys.c' + - 'mm/**' + - 'rust/**' + - 'security/keys/**' + - 'tools/testing/selftests/drivers/ane/**' + - '**/Kconfig*' + - '**/Makefile' + - '.github/workflows/apple-build-kunit.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: apple-build-kunit-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +env: + RUST_VERSION: '1.96.0' + LIBCLANG_PATH: /usr/lib/llvm-18/lib + +jobs: + apple-build: + runs-on: ubuntu-24.04 + timeout-minutes: 120 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Install kernel build dependencies + run: | + # Avoid the hosted runner's Azure mirror after repeated DNS failures. + # Keep signed Ubuntu archive/security suites and fail on update errors. + if [ -f /etc/apt/apt-mirrors.txt ]; then + printf '%s\n' 'https://archive.ubuntu.com/ubuntu/' 'https://security.ubuntu.com/ubuntu/' | \ + sudo tee /etc/apt/apt-mirrors.txt >/dev/null + fi + sudo apt-get update -o APT::Update::Error-Mode=any + sudo apt-get install -y clang lld llvm libclang-dev libelf-dev libssl-dev \ + flex bison bc pkg-config make perl + rustup toolchain install "$RUST_VERSION" --profile minimal --component rust-src --no-self-update + echo "RUSTUP_TOOLCHAIN=$RUST_VERSION" >> "$GITHUB_ENV" + - name: Prepare the layout-corrected bindgen + run: python3 tools/aurora-bindgen/build.py + - name: Configure as a Mac runs it + run: | + make LLVM=1 ARCH=arm64 rustavailable + make LLVM=1 ARCH=arm64 defconfig + scripts/kconfig/merge_config.sh -m .config arch/arm64/configs/asahi.config + make LLVM=1 ARCH=arm64 olddefconfig + # A driver that drops out of the configuration would build nothing and pass. + for opt in RUST=y DRM_ASAHI=m DRM_APPLE=m DRM_ACCEL_ANE=m VIDEO_APPLE_AVD=m \ + NVME_APPLE=m APPLE_DART=y PCIE_APPLE=y USB4=m USB4_APPLE_SOC=m \ + SPI_HID_APPLE_OF=m MFD_MACSMC=y MACSMC_POWER=m POWER_RESET_MACSMC=m \ + APPLE_SEP=m KSM=y MM_SUBPAGE=y APPLE_CENTAURI_T6050_WIFI=y; do + grep -qx "CONFIG_$opt" .config || { echo "::error::CONFIG_$opt is not set"; exit 1; } + done + - name: Compile the Apple drivers + run: | + make -j"$(nproc)" LLVM=1 ARCH=arm64 modules_prepare + make -j"$(nproc)" LLVM=1 ARCH=arm64 \ + drivers/accel/ane/ \ + drivers/gpu/drm/apple/ \ + drivers/gpu/drm/asahi/ \ + drivers/hid/spi-hid/ \ + drivers/iommu/ \ + drivers/media/platform/apple/ \ + drivers/mfd/ \ + drivers/net/wireless/apple/ \ + drivers/nvme/host/ \ + drivers/nvmem/ \ + drivers/pci/controller/ \ + drivers/power/ \ + drivers/soc/apple/ \ + drivers/thunderbolt/ \ + fs/splice.o kernel/sys.o mm/ksm.o mm/madvise.o mm/vma_exec.o + + kunit: + name: KUnit ${{ matrix.suite }} + runs-on: ubuntu-24.04 + timeout-minutes: 60 + strategy: + fail-fast: false + max-parallel: 4 + matrix: + include: + # boot.kunitconfig runs the same ANE suites as transport.kunitconfig. + # It also sets UBSAN_SHIFT, and KASAN_INLINE is the default, so it + # covers both. + - { suite: ane-boot, kunitconfig: drivers/accel/ane/boot.kunitconfig } + - { suite: ane-pm, kunitconfig: tools/testing/selftests/drivers/ane/pm.kunitconfig } + - { suite: dcp-fabric, kunitconfig: drivers/gpu/drm/apple/tests/.kunitconfig } + - { suite: dcp-topology, kunitconfig: drivers/gpu/drm/apple/tests/topology.kunitconfig } + - { suite: asahi, kunitconfig: drivers/gpu/drm/asahi/.kunitconfig, rust: true } + - { suite: spi-hid-apple, kunitconfig: drivers/hid/spi-hid/.kunitconfig } + # avd-pm.kunitconfig runs the same AVD suites. PM_SLEEP, which it + # adds, is already on by default on arm64. + - { suite: avd, kunitconfig: drivers/media/platform/apple/avd/tests/.kunitconfig } + - { suite: ave, kunitconfig: drivers/media/platform/apple/ave/.kunitconfig } + - { suite: isp, kunitconfig: drivers/media/platform/apple/isp/.kunitconfig } + - { suite: jpeg, kunitconfig: drivers/media/platform/apple/jpeg/.kunitconfig } + - { suite: prores, kunitconfig: drivers/media/platform/apple/prores/.kunitconfig } + - { suite: scaler, kunitconfig: drivers/media/platform/apple/scaler/.kunitconfig } + - { suite: macsmc, kunitconfig: drivers/mfd/macsmc.kunitconfig } + - { suite: clpc, kunitconfig: drivers/soc/apple/clpc.kunitconfig } + - { suite: apple-spmi-nvmem, kunitconfig: drivers/nvmem/apple-spmi-nvmem.kunitconfig } + - { suite: trusted-keys, kunitconfig: security/keys/trusted-keys/tests/.kunitconfig } + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Install kernel build and QEMU dependencies + run: | + # As sep-source.yml: avoid the hosted runner's Azure mirror. + if [ -f /etc/apt/apt-mirrors.txt ]; then + printf '%s\n' 'https://archive.ubuntu.com/ubuntu/' 'https://security.ubuntu.com/ubuntu/' | \ + sudo tee /etc/apt/apt-mirrors.txt >/dev/null + fi + sudo apt-get update -o APT::Update::Error-Mode=any + sudo apt-get install -y clang lld llvm libclang-dev libelf-dev libssl-dev \ + flex bison bc pkg-config make perl qemu-system-arm + - name: Pin the Rust toolchain and prepare bindgen + if: ${{ matrix.rust }} + run: | + rustup toolchain install "$RUST_VERSION" --profile minimal --component rust-src --no-self-update + echo "RUSTUP_TOOLCHAIN=$RUST_VERSION" >> "$GITHUB_ENV" + python3 tools/aurora-bindgen/build.py + - name: Run ${{ matrix.kunitconfig }} on arm64 QEMU + env: + KUNITCONFIG: ${{ matrix.kunitconfig }} + run: | + ./tools/testing/kunit/kunit.py run --arch=arm64 \ + --make_options LLVM=1 \ + --kunitconfig="$KUNITCONFIG" \ + --jobs="$(nproc)" --timeout=900 diff --git a/.github/workflows/apple-drm-kunit.yml b/.github/workflows/apple-drm-kunit.yml new file mode 100644 index 00000000000000..ef74ebce5dc830 --- /dev/null +++ b/.github/workflows/apple-drm-kunit.yml @@ -0,0 +1,46 @@ +name: Apple DRM KUnit + +# The Apple display driver's KUnit suites behind +# CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST (mode probing, external audio, boot +# loader handoff, ...) on arm64 QEMU. They use fake coprocessors and nodes, +# so they run without a display controller. + +on: + pull_request: + branches: [main] + paths: + - 'drivers/gpu/drm/apple/**' + - '.github/workflows/apple-drm-kunit.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: apple-drm-kunit-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + kunit: + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Install kernel build and QEMU dependencies + run: | + # As sep-source.yml: avoid the hosted runner's Azure mirror. + if [ -f /etc/apt/apt-mirrors.txt ]; then + printf '%s\n' 'https://archive.ubuntu.com/ubuntu/' 'https://security.ubuntu.com/ubuntu/' | \ + sudo tee /etc/apt/apt-mirrors.txt >/dev/null + fi + sudo apt-get update -o APT::Update::Error-Mode=any + sudo apt-get install -y clang lld llvm libelf-dev libssl-dev \ + flex bison bc pkg-config make perl qemu-system-arm + - name: Run the Apple display KUnit suites on arm64 QEMU + run: | + ./tools/testing/kunit/kunit.py run --arch=arm64 \ + --make_options LLVM=1 \ + --kunitconfig=drivers/gpu/drm/apple/tests/display.kunitconfig \ + --jobs="$(nproc)" --timeout=900 diff --git a/.github/workflows/dt-checks.yml b/.github/workflows/dt-checks.yml index e823805e31ea23..a5a24eed980d15 100644 --- a/.github/workflows/dt-checks.yml +++ b/.github/workflows/dt-checks.yml @@ -7,7 +7,7 @@ name: Device tree checks on: pull_request: - branches: [integration/aurora, aurora-wip] + branches: [main] paths: - 'arch/arm64/boot/dts/apple/**' - 'Documentation/devicetree/bindings/**' @@ -15,7 +15,7 @@ on: - 'scripts/dtc/**' - '.github/workflows/dt-checks.yml' push: - branches: [integration/aurora] + branches: [main] paths: - 'arch/arm64/boot/dts/apple/**' - 'Documentation/devicetree/bindings/**' @@ -106,6 +106,16 @@ jobs: --baseline-dtb-dir "$RUNNER_TEMP/dt/out-base/arch/arm64/boot/dts/apple" \ 2>&1 | tee "$RUNNER_TEMP/dt/dart-pd.log" + - name: Sibling drift, base vs head (warnings only) + if: ${{ !cancelled() && steps.dt.outputs.base != '' }} + run: | + set -o pipefail + python3 scripts/dtc/apple-sibling-drift-test.py + python3 scripts/dtc/apple-sibling-drift.py \ + --dtb-dir "$RUNNER_TEMP/dt/out-head/arch/arm64/boot/dts/apple" \ + --baseline-dtb-dir "$RUNNER_TEMP/dt/out-base/arch/arm64/boot/dts/apple" \ + 2>&1 | tee "$RUNNER_TEMP/dt/sibling-drift.log" + - name: Keep the warning lists if: always() uses: actions/upload-artifact@v4 @@ -115,4 +125,5 @@ jobs: ${{ runner.temp }}/dt/*.warn ${{ runner.temp }}/dt/coverage.log ${{ runner.temp }}/dt/dart-pd.log + ${{ runner.temp }}/dt/sibling-drift.log if-no-files-found: ignore diff --git a/.github/workflows/host-tests.yml b/.github/workflows/host-tests.yml index b67a68f3dfce3c..bba2855c0e9fb0 100644 --- a/.github/workflows/host-tests.yml +++ b/.github/workflows/host-tests.yml @@ -8,9 +8,9 @@ name: Host tests on: push: - branches: [integration/aurora, aurora-wip] + branches: [main] pull_request: - branches: [integration/aurora, aurora-wip] + branches: [main] workflow_dispatch: permissions: diff --git a/.github/workflows/kernel-release.yml b/.github/workflows/kernel-release.yml new file mode 100644 index 00000000000000..e145e075336ef9 --- /dev/null +++ b/.github/workflows/kernel-release.yml @@ -0,0 +1,398 @@ +# SPDX-License-Identifier: GPL-2.0-only +# +# Kernel release channels (see RELEASES.md): +# aurora-edge prerelease, rebuilt on every push to main +# aurora-nightly prerelease, daily from main when main moved since the last nightly +# v* immutable stable release, built from a tag on main +# +# A running edge or nightly build always finishes and publishes; a newer one +# waits, and only the newest waiting build is kept. Publishing never runs twice +# at once for a channel and never moves a channel tag backwards. +# +# workflow_dispatch builds without publishing (publish: none) or publishes +# one rolling channel by hand (publish: edge | nightly). Pull requests that +# change the release machinery itself get a build without publishing. +# +# Every build boots under QEMU and loads every module it ships (which also runs +# the KUnit suites built as modules) before anything is published. +# +# The aurora-* channel tags are protected by a ruleset; the publish job moves +# them over SSH with the release deploy key (RELEASE_DEPLOY_KEY, a secret of the +# release environment, which deploys only from main and v* tags), only +# forward and with a lease. Stable releases attach to the v* tag an Owner pushed. +# Every published asset gets a build provenance attestation. +# +# The configuration is the fleet configuration (aurora_defconfig + asahi.config) +# built with the fleet toolchain versions pinned below. Modules are signed with +# a key generated for each run and thrown away afterwards; lab fleet kits are +# signed separately and are not produced here. + +name: kernel-release + +on: + push: + branches: [main] + tags: ['v*'] + pull_request: + branches: [main] + paths: + - '.github/workflows/kernel-release.yml' + - '.github/scripts/kernel-release-build.sh' + - '.github/scripts/kernel-release-stage-arch.sh' + - '.github/scripts/kernel-smoke-qemu.sh' + - '.github/scripts/kernel-smoke-expected.txt' + - 'arch/arm64/configs/aurora_defconfig' + schedule: + - cron: '30 15 * * *' + workflow_dispatch: + inputs: + publish: + description: 'Channel to publish (none = build only)' + type: choice + options: [none, edge, nightly] + default: none + +permissions: + contents: read + +# Pull requests: a new push replaces the running check. Channel builds and +# publishing are serialised per channel in the jobs below. +concurrency: + group: kernel-release-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + LLVM_VERSION: '22.1.6' + LLVM_SHA256: 'b67817634e8e1c2632dfc056af14d61b94f8e6502f4e557560eea227aa22ce37' + RUST_VERSION: '1.97.1' + BINDGEN_VERSION: '0.73.2' + PAHOLE_VERSION: 'v1.31' + +jobs: + plan: + runs-on: ubuntu-24.04-arm + outputs: + channel: ${{ steps.plan.outputs.channel }} + sha: ${{ steps.plan.outputs.sha }} + build: ${{ steps.plan.outputs.build }} + localversion: ${{ steps.plan.outputs.localversion }} + pkgbase: ${{ steps.plan.outputs.pkgbase }} + steps: + - id: plan + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + EVENT: ${{ github.event_name }} + REF: ${{ github.ref }} + REF_NAME: ${{ github.ref_name }} + SHA: ${{ github.event.pull_request.head.sha || github.sha }} + PUBLISH: ${{ inputs.publish }} + run: | + set -euo pipefail + build=true + case "$EVENT:$REF" in + push:refs/heads/main) channel=edge ;; + push:refs/tags/v*) channel=stable ;; + schedule:*) channel=nightly ;; + pull_request:*) channel=none ;; + workflow_dispatch:*) + channel=$PUBLISH + if [ "$channel" != none ] && [ "$REF" != refs/heads/main ]; then + echo "::error::publishing $channel needs a dispatch on main"; exit 1 + fi ;; + *) echo "::error::unexpected trigger $EVENT $REF"; exit 1 ;; + esac + if [ "$channel" = nightly ]; then + sha=$(gh api "repos/$REPO/git/ref/heads/main" -q .object.sha) + # On a missing tag (the first nightly) gh api exits non-zero and + # prints the 404 body on stdout, so keep only a commit id. + last=$(gh api "repos/$REPO/git/ref/tags/aurora-nightly" -q .object.sha 2>/dev/null | grep -xE '[0-9a-f]{40}' || true) + if [ "$EVENT" = schedule ] && [ "$last" = "$sha" ]; then + echo "main is still at the last nightly ($sha); nothing to build" + build=false + fi + else + sha=$SHA + fi + if [ "$channel" = stable ]; then + # A stable tag must be on main, or on a hotfix/ branch (RELEASES.md). + on= + for b in main $(gh api --paginate "repos/$REPO/branches" -q '.[].name | select(startswith("hotfix/"))'); do + status=$(gh api "repos/$REPO/compare/$(jq -rn --arg b "$b" '$b|@uri')...$sha" -q .status) + case "$status" in behind|identical) on=$b; break ;; esac + done + if [ -z "$on" ]; then + echo "::error::$REF_NAME ($sha) is not on main or a hotfix/ branch"; exit 1 + fi + echo "$REF_NAME is on $on" + fi + case "$channel" in + stable) lv="-aurora-${REF_NAME#v}"; pkg=linux-aurora-bin ;; + edge|nightly) lv="-aurora-$channel"; pkg="linux-aurora-$channel-bin" ;; + *) lv=-aurora-ci; pkg=linux-aurora-ci-bin ;; + esac + { + echo "channel=$channel"; echo "sha=$sha"; echo "build=$build" + echo "localversion=$lv"; echo "pkgbase=$pkg" + } | tee -a "$GITHUB_OUTPUT" + + build: + needs: plan + if: needs.plan.outputs.build == 'true' + runs-on: ubuntu-24.04-arm + timeout-minutes: 345 + concurrency: + group: kernel-release-build-${{ (needs.plan.outputs.channel == 'edge' || needs.plan.outputs.channel == 'nightly') && needs.plan.outputs.channel || github.run_id }} + cancel-in-progress: false + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.plan.outputs.sha }} + fetch-depth: 1 + persist-credentials: false + + - name: Free disk space + run: | + sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /usr/local/.ghcup \ + /usr/local/share/boost /opt/hostedtoolcache/CodeQL || true + df -h / "$GITHUB_WORKSPACE" + + - name: Install build dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + bc bison flex libelf-dev libssl-dev libdw-dev zlib1g-dev cmake \ + cpio kmod rsync zstd xz-utils python3 \ + fakeroot libarchive-tools + + - name: Install makepkg (for make pacman-pkg) + continue-on-error: true + # makepkg looks pacman up at start and exits without it. + run: sudo apt-get install -y --no-install-recommends makepkg pacman-package-manager + + - name: Install Rust + run: | + if ! command -v rustup >/dev/null; then + curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + export PATH="$HOME/.cargo/bin:$PATH" + fi + rustup toolchain install "$RUST_VERSION" --profile minimal -c rust-src + rustup default "$RUST_VERSION" + rustc --version + + - name: Restore toolchain cache + id: tc-cache + uses: actions/cache@v4 + with: + path: ~/tc + key: tc-${{ runner.arch }}-llvm${{ env.LLVM_VERSION }}-bindgen${{ env.BINDGEN_VERSION }}-pahole${{ env.PAHOLE_VERSION }}-1 + + - name: Install LLVM, bindgen and pahole + if: steps.tc-cache.outputs.cache-hit != 'true' + run: | + set -euo pipefail + mkdir -p ~/tc + curl -fsSL -o /tmp/llvm.tar.xz \ + "https://github.com/llvm/llvm-project/releases/download/llvmorg-$LLVM_VERSION/LLVM-$LLVM_VERSION-Linux-ARM64.tar.xz" + echo "$LLVM_SHA256 /tmp/llvm.tar.xz" | sha256sum -c - + mkdir -p ~/tc/llvm + tar -xJf /tmp/llvm.tar.xz -C ~/tc/llvm --strip-components=1 + rm /tmp/llvm.tar.xz + git clone -q --depth 1 -b "$PAHOLE_VERSION" --recurse-submodules --shallow-submodules \ + https://git.kernel.org/pub/scm/devel/pahole/pahole.git /tmp/pahole + cmake -S /tmp/pahole -B /tmp/pahole/build -DCMAKE_INSTALL_PREFIX="$HOME/tc/pahole" \ + -D__LIB=lib -DCMAKE_BUILD_TYPE=Release + make -C /tmp/pahole/build -j"$(nproc)" install + LIBCLANG_PATH=~/tc/llvm/lib cargo install --locked --root ~/tc/bindgen \ + bindgen-cli --version "$BINDGEN_VERSION" + + - name: Build + env: + LOCALVERSION: ${{ needs.plan.outputs.localversion }} + PKGBASE: ${{ needs.plan.outputs.pkgbase }} + run: | + set -euo pipefail + export PATH="$HOME/tc/llvm/bin:$HOME/tc/pahole/bin:$HOME/tc/bindgen/bin:$PATH" + export LD_LIBRARY_PATH="$HOME/tc/pahole/lib:$HOME/tc/llvm/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" + export LIBCLANG_PATH="$HOME/tc/llvm/lib" + .github/scripts/kernel-release-build.sh "$RUNNER_TEMP/out" "$RUNNER_TEMP/dist" "$LOCALVERSION" "$PKGBASE" + df -h / + + - uses: actions/upload-artifact@v4 + with: + name: kernel-${{ needs.plan.outputs.channel }}-${{ needs.plan.outputs.sha }} + path: ${{ runner.temp }}/dist/ + retention-days: 7 + compression-level: 0 + + smoke: + needs: [plan, build] + runs-on: ubuntu-26.04-arm + timeout-minutes: 180 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.plan.outputs.sha }} + fetch-depth: 1 + persist-credentials: false + sparse-checkout: .github + + - uses: actions/download-artifact@v4 + with: + name: kernel-${{ needs.plan.outputs.channel }}-${{ needs.plan.outputs.sha }} + path: dist + + - name: Install QEMU + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends qemu-system-arm busybox-static zstd cpio + qemu-system-aarch64 --version + + - name: Boot under QEMU and load every module + run: | + krel=$(cat dist/kernel.release) + gzip -dc "dist/Image-$krel.gz" > Image + .github/scripts/kernel-smoke-qemu.sh Image "dist/modules-$krel.tar.zst" /bin/busybox smoke + + - if: always() + uses: actions/upload-artifact@v4 + with: + name: smoke-${{ needs.plan.outputs.channel }}-${{ needs.plan.outputs.sha }} + path: | + smoke/console.log + smoke/dmesg.txt + smoke/smoke-summary.json + smoke/smoke-results.tsv + retention-days: 14 + + publish: + needs: [plan, build, smoke] + if: needs.plan.outputs.channel != 'none' && needs.plan.outputs.build == 'true' + runs-on: ubuntu-24.04-arm + # The release environment only deploys from main and v* tags and holds + # RELEASE_DEPLOY_KEY, so no other branch's run can read the key. + environment: release + concurrency: + group: kernel-release-publish-${{ needs.plan.outputs.channel }} + cancel-in-progress: false + permissions: + contents: write + id-token: write + attestations: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + CHANNEL: ${{ needs.plan.outputs.channel }} + SHA: ${{ needs.plan.outputs.sha }} + TAG_NAME: ${{ github.ref_name }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + steps: + - uses: actions/download-artifact@v4 + with: + name: kernel-${{ needs.plan.outputs.channel }}-${{ needs.plan.outputs.sha }} + path: dist + + - name: Attest build provenance + uses: actions/attest-build-provenance@v2 + with: + subject-path: 'dist/*' + + - name: Write release notes + run: | + set -euo pipefail + krel=$(cat dist/kernel.release) + cat > notes.md <, never by the + # bare name, which may also be a branch. They only move forward: the + # new commit must contain the tagged one (a rewritten main stops here). + # On a missing tag (a channel's first release) gh api exits non-zero + # and prints the 404 body on stdout, so keep only a commit id. Any + # other API error also leaves old empty; the lease below then expects + # no tag, so the push fails rather than moving an existing one. + old=$(gh api "repos/$GH_REPO/git/ref/tags/$tag" -q .object.sha 2>/dev/null | grep -xE '[0-9a-f]{40}' || true) + if [ -n "$old" ]; then + status=$(gh api "repos/$GH_REPO/compare/$old...$SHA" -q .status) + case "$status" in + ahead|identical) ;; + behind) + echo "$tag is already at a newer commit ($old); not publishing $SHA" + echo "skip=true" >> "$GITHUB_OUTPUT"; exit 0 ;; + *) echo "::error::$tag is at $old, which $SHA does not contain ($status)"; exit 1 ;; + esac + fi + [ "$old" = "$SHA" ] && { echo "$tag already at $SHA"; exit 0; } + # The aurora-* tags are protected by a ruleset that only the release + # deploy key may bypass; GITHUB_TOKEN cannot move them. + if [ -z "$DEPLOY_KEY" ]; then + echo "::error::$tag is protected; add the release deploy key's private half as the RELEASE_DEPLOY_KEY secret (public half: a write deploy key)" + exit 1 + fi + install -m 0700 -d ~/.ssh + trap 'rm -f ~/.ssh/release_key' EXIT + (umask 077; printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/release_key) + # GitHub's published SSH host key. + echo 'github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl' >> ~/.ssh/known_hosts + git init -q tagger + cd tagger + git remote add origin "git@github.com:$GH_REPO.git" + export GIT_SSH_COMMAND="ssh -i $HOME/.ssh/release_key -o IdentitiesOnly=yes" + git fetch -q --depth 1 origin "$SHA" + # The lease makes the push fail if the tag moved since it was read. + git push --force-with-lease="refs/tags/$tag:$old" origin "$SHA:refs/tags/$tag" + + - name: Publish rolling prerelease + if: (needs.plan.outputs.channel == 'edge' || needs.plan.outputs.channel == 'nightly') && steps.tag.outputs.skip != 'true' + run: | + set -euo pipefail + tag="aurora-$CHANNEL" + title="Aurora kernel $CHANNEL ($(cut -c1-12 <<<"$SHA"))" + if gh release view "$tag" >/dev/null 2>&1; then + gh release edit "$tag" --prerelease --title "$title" --notes-file notes.md + gh release upload "$tag" dist/* --clobber + keep=$(cd dist && ls) + gh release view "$tag" --json assets -q '.assets[].name' | while read -r a; do + grep -qxF "$a" <<<"$keep" || gh release delete-asset "$tag" "$a" -y + done + else + gh release create "$tag" dist/* --verify-tag --prerelease --latest=false \ + --title "$title" --notes-file notes.md + fi + gh release view "$tag" --json tagName,isPrerelease,assets -q '{tag: .tagName, prerelease: .isPrerelease, assets: [.assets[].name]}' + + - name: Publish stable release + if: needs.plan.outputs.channel == 'stable' + run: | + set -euo pipefail + # Built as a draft and published once every asset is uploaded, so a + # failed upload leaves only a draft, which the next attempt replaces. + draft=$(gh release view "$TAG_NAME" --json isDraft -q .isDraft 2>/dev/null || echo none) + case "$draft" in + none) ;; + true) gh release delete "$TAG_NAME" -y ;; + *) echo "::error::release $TAG_NAME is already published; stable releases are never rebuilt"; exit 1 ;; + esac + gh release create "$TAG_NAME" dist/* --verify-tag --draft \ + --title "Aurora kernel $TAG_NAME" --notes-file notes.md --generate-notes + gh release edit "$TAG_NAME" --draft=false --latest + gh release view "$TAG_NAME" --json tagName,isPrerelease,assets -q '{tag: .tagName, prerelease: .isPrerelease, assets: [.assets[].name]}' diff --git a/.github/workflows/mt7932-kunit.yml b/.github/workflows/mt7932-kunit.yml index 368ef703704f77..7706d39850b90b 100644 --- a/.github/workflows/mt7932-kunit.yml +++ b/.github/workflows/mt7932-kunit.yml @@ -6,7 +6,7 @@ name: MT7932 KUnit on: pull_request: - branches: [integration/aurora, aurora-wip] + branches: [main] paths: - 'drivers/net/wireless/mediatek/mt7932/**' - 'drivers/pci/controller/pcie-apple*' diff --git a/.github/workflows/pmgr-pwrstate-kunit.yml b/.github/workflows/pmgr-pwrstate-kunit.yml new file mode 100644 index 00000000000000..b6fb9d396cf68d --- /dev/null +++ b/.github/workflows/pmgr-pwrstate-kunit.yml @@ -0,0 +1,46 @@ +name: PMGR power state KUnit + +# The apple-pmgr-pwrstate KUnit suite (power transitions, apple,no-auto-pm, +# consumers, reset controller) on arm64 QEMU. It runs on an emulated +# register, so it needs no PMGR. + +on: + pull_request: + branches: [main] + paths: + - 'drivers/pmdomain/apple/**' + - 'include/linux/soc/apple/**' + - '.github/workflows/pmgr-pwrstate-kunit.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pmgr-pwrstate-kunit-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + kunit: + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Install kernel build and QEMU dependencies + run: | + # As sep-source.yml: avoid the hosted runner's Azure mirror. + if [ -f /etc/apt/apt-mirrors.txt ]; then + printf '%s\n' 'https://archive.ubuntu.com/ubuntu/' 'https://security.ubuntu.com/ubuntu/' | \ + sudo tee /etc/apt/apt-mirrors.txt >/dev/null + fi + sudo apt-get update -o APT::Update::Error-Mode=any + sudo apt-get install -y clang lld llvm libelf-dev libssl-dev \ + flex bison bc pkg-config make perl qemu-system-arm + - name: Run the PMGR power state KUnit suite on arm64 QEMU + run: | + ./tools/testing/kunit/kunit.py run --arch=arm64 \ + --make_options LLVM=1 \ + --kunitconfig=drivers/pmdomain/apple/.kunitconfig.pmgr-pwrstate \ + --jobs="$(nproc)" --timeout=900 diff --git a/.github/workflows/pr-readiness.yml b/.github/workflows/pr-readiness.yml new file mode 100644 index 00000000000000..76d05c7ece5f52 --- /dev/null +++ b/.github/workflows/pr-readiness.yml @@ -0,0 +1,53 @@ +name: pr-readiness + +# Merge-readiness comment and labels on every open pull request. +# The logic lives in aurora-silicon/.github; this file only says when to run. +# Rules: https://github.com/aurora-silicon/agent-guidelines/blob/main/docs/MAINTAINER-HANDBOOK.md + +on: + pull_request_target: + types: [opened, reopened, synchronize, edited, ready_for_review, converted_to_draft, labeled, unlabeled] + pull_request_review: + types: [submitted, dismissed] + issue_comment: + types: [created, edited] + schedule: + - cron: "7,37 * * * *" + workflow_dispatch: + inputs: + pr: + description: Pull request number (empty = every open pull request) + required: false + +permissions: + contents: read + pull-requests: write + issues: write + checks: read + statuses: read + +jobs: + readiness: + # Skipped (no runner used): reviews on pull requests from forks (read-only + # token; the sweep picks those up), bot comments, edits that change + # neither title, body nor base, and labels other than the human holds. + if: >- + github.repository_owner == 'aurora-silicon' && + (github.event.action != 'edited' || github.event_name != 'pull_request_target' || + github.event.changes.body != null || github.event.changes.title != null || + github.event.changes.base != null) && + (!contains(fromJSON('["labeled","unlabeled"]'), github.event.action) || + contains(fromJSON('["hold","blocked","hw-row-ok"]'), github.event.label.name)) && + (github.event_name != 'pull_request_review' || + github.event.pull_request.head.repo.full_name == github.repository) && + (github.event_name != 'issue_comment' || + (github.event.issue.pull_request && github.event.comment.user.type != 'Bot')) + # One group per pull request, on the job so that skipped events never + # enter it: a burst collapses into one pending run, which reads the + # current state anyway. + concurrency: + group: pr-readiness-${{ github.event.pull_request.number || github.event.issue.number || inputs.pr || 'sweep' }} + cancel-in-progress: false + uses: aurora-silicon/.github/.github/workflows/pr-readiness.yml@main + with: + pr: ${{ format('{0}', github.event.pull_request.number || github.event.issue.number || inputs.pr || '') }} diff --git a/.github/workflows/pr-text.yml b/.github/workflows/pr-text.yml new file mode 100644 index 00000000000000..83c942d878045e --- /dev/null +++ b/.github/workflows/pr-text.yml @@ -0,0 +1,20 @@ +name: pr-text + +# 'Tested:' and 'Risk:' lines present, no AI attribution in the PR text. +# Guide: https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/pr-structure.md + +on: + pull_request: + types: [opened, edited, synchronize, reopened, ready_for_review, converted_to_draft] + +permissions: + contents: read + pull-requests: read + +concurrency: + group: pr-text-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + pr-text: + uses: aurora-silicon/.github/.github/workflows/pr-text.yml@main diff --git a/.github/workflows/sep-source.yml b/.github/workflows/sep-source.yml index 3f824af0d4f61c..2b20a7b5df7f96 100644 --- a/.github/workflows/sep-source.yml +++ b/.github/workflows/sep-source.yml @@ -8,6 +8,7 @@ on: - 'tools/aurora-bindgen/**' - 'drivers/soc/apple/**' - 'drivers/pmdomain/apple/pmp-report.c' + - 'include/linux/apple-sep-hdcp.h' - 'include/uapi/linux/apple-sep.h' - 'tools/aurora-sep/**' - 'Kconfig' @@ -36,6 +37,7 @@ jobs: sparse-checkout-cone-mode: false sparse-checkout: | drivers/soc/apple/** + include/linux/apple-sep-hdcp.h include/uapi/linux/apple-sep.h tools/aurora-sep/** - name: Check biometric ioctl ABI sizes @@ -59,6 +61,9 @@ jobs: python3 -O -m unittest tools/aurora-sep/tests/test_store_open_errors.py -v python3 -m unittest tools/aurora-sep/tests/test_identity_preservation.py -v python3 -O -m unittest tools/aurora-sep/tests/test_identity_preservation.py -v + - name: Test capture wiping on rejected reads + run: | + python3 -I tools/aurora-sep/tests/capture-error-wipe/run.py - name: Test selected-policy diagnostics run: | python3 -m unittest tools/aurora-sep/tests/test_diag_policy.py tools/aurora-sep/tests/test_diag_sensor.py -v @@ -72,8 +77,14 @@ jobs: python3 -m unittest tools/aurora-sep/tests/test_policy_window.py -v python3 -m unittest tools/aurora-sep/tests/test_log_ratelimit.py -v python3 -m unittest tools/aurora-sep/tests/test_key_context_cleanup.py -v + python3 -m unittest tools/aurora-sep/tests/test_hdcp_client.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_packaging.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_sep_writes_always_on.py -v + python3 -m unittest discover -s tools/aurora-sep/tests -p test_boot_locks.py -v + python3 -m unittest discover -s tools/aurora-sep/tests -p test_kernel_log_anchor.py -v + python3 -m unittest discover -s tools/aurora-sep/tests -p test_collect_handover.py -v + python3 -m unittest discover -s tools/aurora-sep/tests -p test_touchid_package.py -v + python3 -m unittest discover -s tools/aurora-sep/tests -p test_root_staging.py -v rust-build: runs-on: ubuntu-24.04 @@ -144,6 +155,15 @@ jobs: --make_options LLVM=1 \ --kunitconfig=drivers/soc/apple/sep.kunitconfig \ --jobs="$(nproc)" --timeout=900 'apple_sep*' + - name: Run the Apple AOP KUnit suites on arm64 QEMU + env: + LIBCLANG_PATH: /usr/lib/llvm-18/lib + run: | + ./tools/testing/kunit/kunit.py run --arch=arm64 \ + --build_dir=.kunit-aop \ + --make_options LLVM=1 \ + --kunitconfig=drivers/soc/apple/aop.kunitconfig \ + --jobs="$(nproc)" --timeout=900 'apple_aop*' dwc3-atc-compile: name: DWC3/ATC ${{ matrix.profile }} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000000000..5fea8735806a6b --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,8 @@ +# Agent and contributor rules: linux + +**Rulebook:** follow the Aurora Silicon rulebook, https://github.com/aurora-silicon/agent-guidelines/blob/main/AGENTS.md. It applies to every agent and contributor, whoever runs them. This file adds the repo specifics. + +## Repo notes + +- Default branch: `main`. Open pull requests against it from `feat/`, `fix/` or `wip/` branches. +- Reviews and merges: Core and Omarchy Mac maintainers (https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/access-tiers.md). diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000000000..2745da24849f4c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +Follow https://github.com/aurora-silicon/agent-guidelines/blob/main/AGENTS.md; repo specifics below. + +@AGENTS.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f20ec244cf27c7..8ace18f73cc934 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -79,3 +79,38 @@ or sensitive, say so rather than substituting data from another Mac. For kernel patches, also follow the existing [kernel submission guidance](Documentation/process/submitting-patches.rst). + +## Pull request rules + +See [Aurora Silicon's pull request rules](https://github.com/aurora-silicon/agent-guidelines) +and run the [pre-PR checklist](https://github.com/aurora-silicon/agent-guidelines/blob/main/pre-pr-checklist.md) +before opening a pull request. + +## Contributing code + +`main` is the only branch work lands in. Open every pull request against +`main` from a short-lived branch: + +- `feat/` for new work, `fix/` for fixes. +- `wip/` for work you park without a pull request. It is not merged + from directly; open a `feat/` or `fix/` pull request when it is ready. +- `archive/` holds old branches kept for their history. Do not push to them. +- `feat/-` can also be a topic branch for a large feature that + takes several pull requests: the parts are reviewed as pull requests into + the topic branch, the whole is regression-tested there and lands on `main` + as one pull request, and the topic branch is then deleted. +- `rebase/v` is the single branch for an upstream version upgrade, + and `hotfix/v` a short-lived branch for a stable hotfix (see + [RELEASES.md](RELEASES.md)). + +There are no long-lived release or per-platform branches. The full rules are in +[branching-and-releases](https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/branching-and-releases.md). + +`main` takes changes only through pull requests. The branch rules prevent +direct pushes, force pushes and deletion. Start new work from a fresh branch +off `main`. Retarget any stacked pull requests before their base is merged +and its branch is deleted. + +Releases are cut from `main` on a fixed cadence and never wait for unfinished +work. How the edge, nightly and stable channels are built is in +[RELEASES.md](RELEASES.md). diff --git a/Documentation/ABI/testing/sysfs-class-accel-ane b/Documentation/ABI/testing/sysfs-class-accel-ane index af17b343172387..846b7f2e978a51 100644 --- a/Documentation/ABI/testing/sysfs-class-accel-ane +++ b/Documentation/ABI/testing/sysfs-class-accel-ane @@ -35,14 +35,44 @@ Description: work and are not counted. A submission that completes with an error still completes its begin/complete pair, so the - counter stays balanced. + counter stays balanced. On the H16 and H17 node + (ane_t6021 with a firmware platform, e.g. T6041, + T8140) every EXECUTE that reached the firmware + counts, failed ones included; a request refused + before any firmware traffic (quarantined engine, + invalid buffers) does not. Neither counter resets while the device is bound. + On the H16 and H17 node, resetting the debugfs + execute statistics leaves them alone. - The file exists only when the module parameter - ane.stats / ane_t6021.stats (default 1) is set at - probe. With stats=0 the driver creates no stats files - and the submission hot path skips the counters. + On ane.ko and the H13/H14 ane_t6021 path the file + exists only when the module parameter ane.stats / + ane_t6021.stats (default 1) is set at probe. With + stats=0 the driver creates no stats files and the + submission hot path skips the counters. The H16 and + H17 node creates it with the node, without a + parameter. Users: performance samplers that compute engine utilization and job rate from the two counters. + +What: /sys/class/accel/accel/device/wedged +Date: November 2026 +KernelVersion: 7.3 +Contact: Ryan Murray +Description: + "1" while the Apple Neural Engine refuses requests + until it recovers, "0" otherwise. Mode 0444; the read + takes no lock, so a hung request cannot block it. + + On the H16 and H17 node (ane_t6021 with a firmware + platform, e.g. T6041, T8140) it is 1 while the + firmware session is quarantined: a request hung or + ended with an uncertain outcome, and requests fail + with EIO until a runtime recovery or a system sleep + proves the old firmware gone. A parked or sleeping + engine reads 0: its next request brings it up. + +Users: health checks (aurora-diag) that tell a wedged engine + from an idle one. diff --git a/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats b/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats index f5c8afcc98bbf1..46529772affd6f 100644 --- a/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats +++ b/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats @@ -108,15 +108,20 @@ Description: older than the age limit below or its epoch ended. unsupported is a fixed property of the firmware, taken from the driver's per-firmware match data, and - never changes at runtime: the V25G83 firmware accepts - tag 0x10 but never emits it, and no other record of - it carries the current pstate, so pstate_status - always reads unsupported on G16S. V26A428 reports - its state in other records (see below). + never changes at runtime: T6040 V25G83 (M4 Pro) is + left on Protocol::NONE because it has not been + measured yet, so pstate_status reads unsupported on + T6040. V26A428 and T6041 (25G83) report their state + in other records (see below). utilisation_status is never unsupported on these firmwares. Numeric metrics are printed only while - their capability is valid; otherwise their value is - the string unsupported. + their capability is valid. Otherwise utilisation + values read unsupported; pstate and + achieved_frequency_hz read pstate_status (stale, + unavailable or unsupported), and achieved_frequency_hz + reads unsupported for a valid state with no + frequency in the board's table; busy_ns reads stale + when its total stopped and unsupported otherwise. util_tiler_percent, util_renderer_percent, util_device_percent Unsigned integer percent (0..100), from tag 0x13 @@ -132,7 +137,8 @@ Description: firmware whose match data says it emits tag 0x10 (none of the current G16S/G17P firmwares do). A firmware that reports its state in tags 0x19 and - 0x1b (V26A428) never has tag 0x10 decoded. Words 1 + 0x1b (V26A428 and T6041 25G83) never has tag 0x10 + decoded. Words 1 and 2 form a little-endian u64 firmware timestamp. The first timestamp establishes a baseline. Invalid selectors and backwards timestamps remove pstate @@ -141,21 +147,23 @@ Description: requested_frequency_hz, achieved_frequency_hz, busy_ns, power_mw, temperature_raw - Always unsupported on V25G83 (G16S). No record of it - carries a state, a qualified busy-time duration, a - power unit or a temperature. + Unsupported on T6040 V25G83 (M4 Pro), which is left + on Protocol::NONE because it has not been measured + yet; power_mw and temperature_raw are unsupported on + all G16S/G17P firmwares. - The V26A428 firmware, which the A18 Pro (T8140, G17P) and M5 - run, uses the same snapshot and keys, with these differences: + The V26A428 firmware (A18 Pro T8140 and M5) and T6041 (M4 Max, + 25G83) use the same snapshot and keys, with these + differences: pstate_status, pstate Supported. The firmware reports the performance state in effect in tag 0x1b, words 1 and 3, which must agree: an index into the performance state table, - 1..10 on the A18 Pro, 1..13 on M5. The end of the - interval record before it (tag 0x19, words 1 and 2) - is its firmware timestamp. A report that names state - 0 or a state beyond the table removes pstate + 1..10 on the A18 Pro and T6041, 1..13 on M5. The end + of the interval record before it (tag 0x19, words 1 + and 2) is its firmware timestamp. A report that names + state 0 or a state beyond the table removes pstate validity. While the GPU cores are gated, pstate reads valid 0: the GPU is off. Power-up starts a new epoch, stale until the next report. The driver asks for full @@ -167,27 +175,42 @@ Description: achieved_frequency_hz The frequency of pstate in Hz, while pstate_status is valid, and 0 for state 0. M5: the board's performance - state table. A18 Pro: the device tree operating point - that the state's entry of performance table A names. - Its records do not name the table; at its top state a - sustained FP32 FMA load completes faster than table - B's frequency there allows, so it runs table A. + state table. A18 Pro and T6041: the device tree + operating point that the state's entry of performance + table A names. Their records do not name the table: + on the A18 Pro, at the top state a sustained FP32 FMA + load completes faster than table B's frequency there + allows, so it runs table A; on T6041 both tables map + state 10 to OPP 15 (1578 MHz) and only differ on + mid-states (states 5..9 on 32-core J616C, 6..9 on + 40-core), so those mid-state frequencies are nominal + (taken from table A) until measured by a mid-state + ALU benchmark. busy_ns Cumulative u64 since the driver was bound. The tag - 0x13 records of this firmware carry a timestamp in + 0x13 records of these firmwares carry a timestamp in 24 MHz ticks (words 1 and 2), one every 8 ms on M5 - and every 16 ms on the A18 Pro. Each record credits - the window since the previous record of its epoch at - its device utilisation. A record more than two - periods after the previous one, or with an earlier - timestamp, only starts a new window, so time the GPU - spent gated is never credited, and a load sparser - than one period reads low. MEASURED on T6050 - (J716c): 871 and 863 ms for three 300 ms compute jobs - at full clock (905 and 919 ms of work). MEASURED on - T8140 (J700), 24 traces of GPU stress loads: within - about 20% of the union of the commands' own execution - intervals for loads busy more than half the time. + and T6041 (192000 ticks) and every 16 ms on the A18 + Pro (384000 ticks), and are credited in + that order at their device utilisation, from both + roles and across power epochs. The driver keeps the + timestamp up to which it has credited busy time; a + record at or before it gets nothing, so no interval + is credited twice. A later record credits the window + since that mark when it is at most two periods, and + only its own period after a longer gap, so time the + GPU spent gated is never credited. Records a power + boundary keeps out of the utilisation average (see + below) still count here; suspend, a real epoch + invalidation's discard and quarantine keep them out. + busy_ns reads stale once a statistics ring is + quarantined. MEASURED on T6050 (J716c): 871 and 863 + ms for three 300 ms compute jobs at full clock (905 + and 919 ms of work). MEASURED on T8140 (J700), 24 + traces of GPU stress loads, with windows that ended + at each power epoch: within about 20% of the union + of the commands' own execution intervals for loads + busy more than half the time. requested_frequency_hz, power_mw, temperature_raw Unsupported. @@ -209,15 +232,17 @@ Description: Suspend/resume, restart, statistics-ring quarantine, observed core gating and teardown end validity. After an epoch boundary, each ring's already queued records are discarded before new - baselines are accepted. A quarantined statistics ring disables - both roles' exports until reprobe; a trace-ring error does not. + baselines are accepted; where busy_ns is integrated, those a + power boundary kept out still reach it, as described there. A + quarantined statistics ring disables both roles' exports until + reprobe; a trace-ring error does not. Reads take the device mutex and do not wake the GPU. The firmware_reports debugfs view retains per-role raw packets, counts and host monotonic receive times, plus capability status, - policy, timestamp and diagnostic tick deltas. Tick deltas are - never accumulated as GPU busy time. Firmware role streams are - merged in drain order without deduplication. + policy, timestamp and diagnostic tick deltas. The tag 0x10 tick + deltas are never accumulated as GPU busy time. Firmware role + streams are merged in drain order without deduplication. The diagnostic also identifies the platform device, records the transport-admitted count and last-admission decision per role/tag, and shows suspension, queued-record discard and quarantine state. diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt index 388b32354bede2..53e47260ebbd4f 100644 --- a/Documentation/admin-guide/kernel-parameters.txt +++ b/Documentation/admin-guide/kernel-parameters.txt @@ -553,11 +553,12 @@ Kernel parameters See header of arch/x86/kernel/apm_32.c. apple_keep_idle_nop - [ARM64,EARLY] On T6050 and T8142, keep idle=nop. - These cores idle in WFI by default, and an idle=nop - that the boot loader appends is ignored, because the - kernel preserves the registers WFI loses there. With - this flag idle=nop spins the idle loop as elsewhere. + [ARM64,EARLY] On Apple M4 and later cores, keep + idle=nop. These cores idle in WFI by default, and an + idle=nop that an older boot loader appends is + ignored, because the kernel preserves the registers + WFI loses there. With this flag idle=nop spins the + idle loop as elsewhere. apparmor= [APPARMOR] Disable or enable AppArmor at boot time Format: { "0" | "1" } @@ -7627,14 +7628,6 @@ Kernel parameters See Documentation/admin-guide/mm/transhuge.rst for more details. - thunderbolt.dp_video_counter= - [HW,ARM64] - Format: - Enable diagnostic counter 0 on the DP video path's - host and downstream ingress hops on the right-hand - USB-C route of the Apple M2 Pro and M2 Max laptops. Read counters through Thunderbolt - debugfs. This is a load-time setting. Default: false. - thunderbolt_apple.dp_display= [HW,ARM64] Format: diff --git a/Documentation/admin-guide/sysctl/kernel.rst b/Documentation/admin-guide/sysctl/kernel.rst index ffea61d448ebb1..0b3d35de5fcf30 100644 --- a/Documentation/admin-guide/sysctl/kernel.rst +++ b/Documentation/admin-guide/sysctl/kernel.rst @@ -1328,6 +1328,26 @@ restrict all boosts temporarily by modifying sched_util_clamp_min. As soon as this restriction is lifted, the requested sched_util_clamp_min_rt_default will take effect. +sched_util_clamp_background +=========================== + +Enables/disables automatic utilization capping of SCHED_IDLE tasks on +asymmetric CPU capacity systems (default 1). + +When enabled on a system with asymmetric CPU capacities +(sched_asym_cpucapacity active), the effective uclamp.min and uclamp.max of +non-RT/DL SCHED_IDLE tasks are capped at the capacity of the smallest active +CPU in an asymmetric scheduling domain (derived from arch_scale_cpu_capacity() +whenever scheduling domains are rebuilt). This biases background SCHED_IDLE +work toward efficiency cores and limits frequency scaling when it spills onto +higher-capacity cores, taking precedence over task and cgroup clamp requests +while preserving tighter system defaults. + +Setting this knob to 0 disables the cap. Symmetric systems are unaffected +regardless of the setting. Changes take effect for each task at its next +enqueue; a CPU-bound SCHED_IDLE task that never sleeps retains its previous +effective clamp until it is next enqueued. + seccomp ======= diff --git a/Documentation/devicetree/bindings/arm/apple/apple,pmgr.yaml b/Documentation/devicetree/bindings/arm/apple/apple,pmgr.yaml index 91ae5a3ce1bca0..e2e75a8c29f13e 100644 --- a/Documentation/devicetree/bindings/arm/apple/apple,pmgr.yaml +++ b/Documentation/devicetree/bindings/arm/apple/apple,pmgr.yaml @@ -46,6 +46,7 @@ properties: - apple,t8132-pmgr - apple,t8140-pmgr - apple,t8142-pmgr + - apple,t8152-pmgr - const: apple,t8103-pmgr - const: syscon - const: simple-mfd diff --git a/Documentation/devicetree/bindings/chosen/apple,dcp-rtkit-running.yaml b/Documentation/devicetree/bindings/chosen/apple,dcp-rtkit-running.yaml new file mode 100644 index 00000000000000..38a4dcb4044a5e --- /dev/null +++ b/Documentation/devicetree/bindings/chosen/apple,dcp-rtkit-running.yaml @@ -0,0 +1,37 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/chosen/apple,dcp-rtkit-running.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple DCP RTKit state at the loader hand-off + +maintainers: + - Thomas Glanzmann + +description: + The loader records whether the internal display coprocessor's RTKit was + running when it handed over to the kernel, or whether the loader quiesced + it after a failed display setup. The loader omits this property when it + never started the coprocessor. + +select: + properties: + $nodename: + const: chosen + required: + - $nodename + +properties: + $nodename: + const: chosen + + apple,dcp-rtkit-running: + $ref: /schemas/types.yaml#/definitions/uint32 + enum: [0, 1] + description: + One if the internal DCP's RTKit was running at the hand-off, zero if + the loader quiesced it. + +additionalProperties: true +... diff --git a/Documentation/devicetree/bindings/chosen/linux-enablement-mac,dapf-handoff.yaml b/Documentation/devicetree/bindings/chosen/linux-enablement-mac,dapf-handoff.yaml new file mode 100644 index 00000000000000..e88332b7af2781 --- /dev/null +++ b/Documentation/devicetree/bindings/chosen/linux-enablement-mac,dapf-handoff.yaml @@ -0,0 +1,51 @@ +# SPDX-License-Identifier: (GPL-2.0 OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/chosen/linux-enablement-mac,dapf-handoff.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T8132 DAPF consumer hand-off + +maintainers: + - Diljit Singh + +description: + Board device trees on Apple T8132 Macs describe which ADT consumers need + their DART access protection filters (DAPFs) programmed by the bootloader + before handing control to Linux, and whether a consumer must be powered on + or programmed as halted prior to hand-off. + +select: + properties: + $nodename: + const: chosen + required: + - $nodename + +properties: + $nodename: + const: chosen + + linux-enablement-mac,dapf-handoff: + $ref: /schemas/types.yaml#/definitions/string-array + description: + ADT paths of consumers (for example "/arm-io/aop", "/arm-io/mtp", + "/arm-io/pmp") whose DART access protection filters the bootloader + programs for hand-off to Linux. + + linux-enablement-mac,dapf-power-on-handoff: + $ref: /schemas/types.yaml#/definitions/string-array + description: + Subset of consumers listed in linux-enablement-mac,dapf-handoff that + the bootloader powers on before programming their DAPFs and leaves + powered across hand-off. + + linux-enablement-mac,dapf-halted-handoff: + $ref: /schemas/types.yaml#/definitions/string-array + description: + Subset of consumers listed in linux-enablement-mac,dapf-handoff that + boot firmware leaves halted and unpowered, whose DAPFs the bootloader + programs for a halted consumer so Linux can cold-start them. + +additionalProperties: true +... diff --git a/Documentation/devicetree/bindings/chosen/linux-enablement-mac,disk-boot.yaml b/Documentation/devicetree/bindings/chosen/linux-enablement-mac,disk-boot.yaml new file mode 100644 index 00000000000000..dd6b2669c689b9 --- /dev/null +++ b/Documentation/devicetree/bindings/chosen/linux-enablement-mac,disk-boot.yaml @@ -0,0 +1,35 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/chosen/linux-enablement-mac,disk-boot.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T8132 disk-boot /chosen flag + +maintainers: + - Diljit Singh + +description: + Boolean flag in /chosen carried by Apple T8132 board device trees to + indicate that the board tree targets normal disk-boot hand-off from + the bootloader. + +select: + properties: + $nodename: + const: chosen + required: + - $nodename + +properties: + $nodename: + const: chosen + + linux-enablement-mac,disk-boot: + type: boolean + description: + Indicates that the board device tree targets disk-boot hand-off + on Apple T8132 systems. + +additionalProperties: true +... diff --git a/Documentation/devicetree/bindings/display/apple,dcp-typec-routes.yaml b/Documentation/devicetree/bindings/display/apple,dcp-typec-routes.yaml index 858a09501e4f68..e90412d793f11c 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp-typec-routes.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp-typec-routes.yaml @@ -16,17 +16,25 @@ description: | Each route index N names a typecN PHY and a typecN DP Alt Mode crossbar output on the DCP node. The route's graph endpoint connects to the corresponding - Type-C connector's display port (port@3). Two route endpoints on that port - mean two candidate pipelines; that alone does not imply two tunnel streams. + Type-C connector's display port (port@2 on T6050, port@3 on earlier SoCs). Two + route endpoints on that port mean two candidate pipelines; that alone does not + imply two tunnel streams. For a port wired to both Thunderbolt DP IN adapters, name typecN-dpin0 and typecN-dpin1 crossbar controls on the pipelines that can drive them. Crossbar mux cells 0, 1 and 2 describe the DP PHY, DP IN 0 and DP IN 1 outputs, respectively. The per-port prefix distinguishes multiple ATCs on one DCP. - Dual-stream wiring requires these two named controls and two port@3 - endpoints. It does not describe SoC handshake or retry policy. T6050 host - routers have four DP IN adapters; their crossbars add typecN-dpin2 and - typecN-dpin3 (cells 3 and 4). + Dual-stream wiring requires these two named controls and two endpoints on the + connector's display port. It does not describe SoC handshake or retry policy. + T6050 host routers have four DP IN adapters; their crossbars add typecN-dpin2 + and typecN-dpin3 (cells 3 and 4). + + An empty typec-routes container asks the boot loader to write the routes + from the hardware's own description of its display crossbar: the phys, + crossbar controls, crossbar states, DPTX targets and route nodes below, + and the matching endpoints on each connector's display port (port@2 on + T6050, port@3 on earlier SoCs). Without a boot loader that does, the + processor has no Type-C route. Legacy typecN-usb4 names describe cell 1 on old j414/j416 DTBs. With two port@3 endpoints they retain the existing dual-stream wiring; cell 2 is @@ -39,7 +47,12 @@ select: enum: - apple,dcp - apple,dcpext - typec-routes: true + typec-routes: + anyOf: + - required: [route@0] + - required: [route@1] + - required: [route@2] + - required: [route@3] required: - compatible - typec-routes @@ -181,8 +194,18 @@ examples: - | #include - dcp { + dcp@8dc00000 { compatible = "apple,t6020-dcpext", "apple,dcpext"; + reg = <0x8dc00000 0x4000>, + <0x8c000000 0x4000000>, + <0x8d320000 0x4000>, + <0x8d344000 0x4000>, + <0x8d800000 0x800000>; + reg-names = "coproc", "disp-0", "disp-1", "disp-2", "disp-3"; + mboxes = <&dcpext_mbox>; + mbox-names = "mbox"; + iommus = <&dcpext_dart 5>; + apple,bw-scratch = <&pmgr_dcp 0 4 0x1220>; phys = <&atcphy0 PHY_TYPE_DP>; phy-names = "typec0"; mux-controls = <&atcphy0_xbar 0>, <&atcphy0_xbar 1>, diff --git a/Documentation/devicetree/bindings/display/apple,dcp.yaml b/Documentation/devicetree/bindings/display/apple,dcp.yaml index 9437c59a76d3a0..57616c37cda25a 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp.yaml @@ -34,6 +34,8 @@ properties: - apple,t8112-dcpext - apple,t6000-dcpext - apple,t6020-dcpext + - apple,t6030-dcpext + - apple,t6031-dcpext - apple,t6041-dcpext - apple,t8122-dcpext - apple,t6050-dcpext @@ -92,6 +94,21 @@ properties: - const: mbox - const: secure + apple,secure-mbox: + $ref: /schemas/types.yaml#/definitions/phandle + description: + The coprocessor's secure RTBuddy port, on a machine whose boot loader + hands the display over only to a node with a single mailbox in mboxes. + The driver takes it as the "secure" mailbox. Elsewhere the port is the + second entry of mboxes. + + apple,merged-mode-limit: + type: boolean + description: + The platform's limit on merged modes applies to this external display + coprocessor. A display takes a second coprocessor as its pair only + while one is left for every external display that is present. + iommus: maxItems: 1 @@ -156,9 +173,10 @@ properties: apple,display-power: $ref: /schemas/types.yaml#/definitions/phandle description: - A node whose ps, pwrgate and pmc-dcp registers hold the display power - words this coprocessor's driver writes around a firmware restart, such - as an apple,t8140-display-power node. + A node describing the display power-state words (or PMGR power-domain + chains), power-gate retention words and pmc-dcp counter that this + coprocessor's driver writes around a firmware restart, such as an + apple,t8140-display-power or apple,t6041-display-power node. apple,bw-scratch: $ref: /schemas/types.yaml#/definitions/phandle-array @@ -277,6 +295,50 @@ properties: maxItems: 5 description: Loader-provided firmware ABI version used for IOMFB selection. + apple,rtkit-handoff: + $ref: /schemas/types.yaml#/definitions/string + enum: + - dcp-live-v1 + description: | + Added by a boot stage that negotiated RTKit with this processor and + handed it over running. Such a firmware does not repeat HELLO or its + endpoint map, so the operating system takes over the session as + described by apple,rtkit-version, apple,rtkit-epmap and + apple,rtkit-buffers instead of starting RTKit again. Absent when the + processor was not left running. + + apple,rtkit-version: + $ref: /schemas/types.yaml#/definitions/uint32 + description: RTKit protocol version of the handed-over session. + + apple,rtkit-epmap: + $ref: /schemas/types.yaml#/definitions/uint32-array + minItems: 8 + maxItems: 8 + description: | + Endpoints the firmware advertised for the handed-over session; word i + holds endpoints 32i to 32i + 31. Application endpoints are stopped at + the handover and are started again by the new owner. + + apple,rtkit-buffers: + oneOf: + - type: boolean + - $ref: /schemas/types.yaml#/definitions/uint32-array + minItems: 5 + maxItems: 20 + description: | + The shared buffers of the handed-over session, in groups of five + cells as for other co-processors handed over running: system endpoint + number (1 crashlog, 2 syslog, 4 IOReport, 8 OSLog, each at most once), + device address high cell, device address low cell, size in bytes, and + 1 if the firmware supplied the address (0 if the boot stage allocated + the buffer). The device address is the DART input address. Every + buffer lies inside one of the reserved-memory regions referenced by + memory-region, and that region maps it at the same address through + iommu-addresses, so the mapping survives the IOMMU taking over the + processor's page tables. Those regions are no-map. An empty property + records that the session has no shared buffers. + apple,j613-25g83-dcpext-handoff: $ref: /schemas/types.yaml#/definitions/uint32 const: 1 @@ -298,8 +360,13 @@ properties: apple,t8122-dcpext-firmware-ready: $ref: /schemas/types.yaml#/definitions/uint32 - const: 1 - description: All external firmware reservations were committed by the loader. + enum: [1, 2] + description: + Set by the boot loader on a T8122 external coprocessor whose firmware + it has reserved. 2 is the boot loader's default. 1 is set only when + the owner asked for the coprocessor in the boot loader configuration, + because kernels that share the display DART unconditionally accept 1 + and nothing else. apple,pmp: $ref: /schemas/types.yaml#/definitions/phandle @@ -320,6 +387,14 @@ properties: $ref: /schemas/types.yaml#/definitions/uint32 description: Display coprocessor index on multi-DCP systems. + apple,sleep-host-stop: + type: boolean + description: + The SoC's suspend-to-RAM needs this display coprocessor and the external + ones stopped, and their power domains lowered, by the operating system + before the sleep commit, and the internal one restarted after the wake. + The firmware doesn't take the display down for the sleep itself. + apple,typec-hybrid-first: type: boolean description: @@ -488,6 +563,32 @@ properties: - iommus additionalProperties: false + apple,no-shared-display-dart: + type: boolean + description: + The external coprocessor's display DART must stay out of the display + subsystem's IOMMU domain. Framebuffers are mirrored through the fbdma + child instead, which must be present. + + fbdma: + type: object + description: + The display DART stream an external coprocessor scans framebuffers + through, with the display subsystem's DVA window. + properties: + iommus: + maxItems: 1 + apple,dma-range: + $ref: /schemas/types.yaml#/definitions/uint64-array + description: + Base and size of the display subsystem's DVA window on this stream. + minItems: 2 + maxItems: 2 + required: + - iommus + - apple,dma-range + additionalProperties: false + panel: type: object properties: @@ -576,6 +677,9 @@ required: - mboxes - iommus +dependentRequired: + apple,rtkit-handoff: [ 'apple,rtkit-version', 'apple,rtkit-epmap', 'apple,rtkit-buffers' ] + allOf: - if: not: @@ -593,23 +697,6 @@ allOf: maxItems: 10 items: pattern: '^(dp-xbar|typec[0-9]+(-dpin[01])?)$' - - if: - not: - properties: - compatible: - contains: - enum: ['apple,t6030-dcpext', 'apple,t8132-dcpext', - 'apple,t6050-dcp', 'apple,t6050-dcpext'] - required: - - compatible - then: - properties: - mux-controls: - maxItems: 8 - mux-control-names: - maxItems: 8 - items: - pattern: '^(dp-xbar|typec[0-9]+)$' - if: allOf: - not: @@ -735,6 +822,26 @@ allOf: then: properties: resets: false + - if: + required: + - typec-routes + properties: + typec-routes: + not: + anyOf: + - required: [route@0] + - required: [route@1] + - required: [route@2] + - required: [route@3] + then: + properties: + phys: false + phy-names: false + mux-controls: false + mux-control-names: false + apple,typec-mux-indices: false + apple,typec-dptx-phys: false + apple,dptx-die: false unevaluatedProperties: false diff --git a/Documentation/devicetree/bindings/display/apple,display-subsystem.yaml b/Documentation/devicetree/bindings/display/apple,display-subsystem.yaml index ac106575a96724..2bff1703d7c945 100644 --- a/Documentation/devicetree/bindings/display/apple,display-subsystem.yaml +++ b/Documentation/devicetree/bindings/display/apple,display-subsystem.yaml @@ -19,6 +19,7 @@ properties: - enum: - apple,display-subsystem - apple,t6031-display-subsystem + - apple,t8122-display-subsystem - apple,t8132-display-subsystem - const: apple,t8132-display-diagnostics deprecated: true @@ -50,6 +51,17 @@ properties: type: boolean description: The loader validated the inherited J713 SID0 scanout mapping. + apple,dma-range: + $ref: /schemas/types.yaml#/definitions/uint64-array + minItems: 2 + maxItems: 2 + description: + Common scanout DMA aperture, encoded as a base and nonzero size. Bits + above a DART's address width select the alias the display uses; the + remaining bits are intersected with the window of each referenced DART + stream, so the aperture never extends past any of them. Other consumers + of the same DART retain their own apertures. + required: - compatible - iommus diff --git a/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml b/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml index 7d157451342678..8c484ae685e2d5 100644 --- a/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml +++ b/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml @@ -4,30 +4,102 @@ $id: http://devicetree.org/schemas/display/apple,t8140-display-power.yaml# $schema: http://devicetree.org/meta-schemas/core.yaml# -title: Apple T8140 and T8142 display power words +title: Apple T8103, T6041, T8132, T8140 and T8142 display power words maintainers: - Diljit Singh description: - The words a display coprocessor's driver writes to power its domains off - and on around a restart of its firmware, as macOS does. A display - coprocessor names this node in its apple,display-power property. The words - belong to the power manager and the display block, so no driver binds it. + The words and PMGR power-state chains a display coprocessor's driver writes + to power its domains off and on around a restart of its firmware, as macOS + does. A display coprocessor names this node in its apple,display-power + property. The words belong to the power manager and the display block, so no + driver binds it. properties: compatible: enum: + - apple,t8103-display-power + - apple,t6041-display-power + - apple,t8132-display-power - apple,t8140-display-power - apple,t8142-display-power reg: - minItems: 2 - maxItems: 3 + minItems: 1 + maxItems: 5 reg-names: - minItems: 2 - maxItems: 3 + minItems: 1 + maxItems: 5 + + '#address-cells': + const: 1 + + '#size-cells': + const: 0 + +patternProperties: + '^chain@[0-9]+$': + type: object + description: | + One ordered display power-domain chain for apple,t6041-display-power, + powered down in reg order during suspend-to-RAM. + properties: + reg: + maxItems: 1 + + label: + description: Short name of the display chain (e.g. main, ext0..ext3). + + apple,main-chain: + type: boolean + description: + Marks the internal display chain, which clears the display AXI2AF + bridge and PMC voter on stop and is restarted warm on wake. + + apple,pwrgate-aux: + type: boolean + description: + Selects the pwrgate-aux register window instead of pwrgate for this + chain's power-gate retention words. + + apple,gapf-offset: + $ref: /schemas/types.yaml#/definitions/uint32 + description: + Byte offset of this chain's clock-protection slice within the gapf + register window. + + apple,pwrgate-offsets: + $ref: /schemas/types.yaml#/definitions/uint32-array + minItems: 2 + maxItems: 2 + description: + Byte offsets of the pair of power-gate retention words (A, then B) + within the selected pwrgate window. + + apple,fabric-domain: + $ref: /schemas/types.yaml#/definitions/phandle + description: + Parent fabric PMGR power-state node held manually on while this chain + powers down, then returned to its previous auto-enable state. + + power-domains: + minItems: 3 + maxItems: 16 + description: | + Ordered PMGR power-state nodes for this chain: SYS, FE, CPU, followed + by the chain's child sub-domains in parent-before-child order + (powered off in reverse). + + required: + - reg + - label + - apple,gapf-offset + - apple,pwrgate-offsets + - power-domains + + additionalProperties: false required: - compatible @@ -38,7 +110,51 @@ allOf: - if: properties: compatible: - const: apple,t8140-display-power + const: apple,t8103-display-power + then: + # T8103's display has no retention words and its PMC no count of the coprocessors. + properties: + reg: + items: + - description: the power manager's power state words + reg-names: + items: + - const: ps + - if: + properties: + compatible: + const: apple,t6041-display-power + then: + properties: + reg: + items: + - description: the display PMC voter counter pair + - description: the internal display power gate retention words + - description: the external display power gate retention words + - description: the clock-protection slices for all display chains + - description: the internal display AXI2AF bridge registers + reg-names: + items: + - const: pmc-dcp + - const: pwrgate + - const: pwrgate-aux + - const: gapf + - const: axi2af + required: + - '#address-cells' + - '#size-cells' + else: + properties: + '#address-cells': false + '#size-cells': false + patternProperties: + '^chain@[0-9]+$': false + - if: + properties: + compatible: + enum: + - apple,t8132-display-power + - apple,t8140-display-power then: properties: reg: @@ -70,6 +186,51 @@ allOf: additionalProperties: false examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + display-power@5048a9c14 { + compatible = "apple,t6041-display-power"; + reg = <0x5 0x048a9c14 0x0 0x8>, + <0x5 0x022a1000 0x0 0x100>, + <0x5 0x0282d000 0x0 0x1000>, + <0x5 0x00578000 0x0 0x1000>, + <0x4 0x03000100 0x0 0x10>; + reg-names = "pmc-dcp", "pwrgate", "pwrgate-aux", "gapf", "axi2af"; + #address-cells = <1>; + #size-cells = <0>; + + chain@0 { + reg = <0>; + label = "ext3"; + apple,pwrgate-aux; + apple,gapf-offset = <0x740>; + apple,pwrgate-offsets = <0xfb4 0xfd8>; + power-domains = <&ps_dispext3_sys>, <&ps_dispext3_fe>, + <&ps_dispext3_cpu>, <&ps_dispext3_dbe>, + <&ps_dpext3>, <&ps_dispext3_gp0>, + <&ps_dispext3_gp1>, <&ps_dispext3_gpl>, + <&ps_dispext3_ppp>, <&ps_dispext3_dsc>; + }; + + chain@4 { + reg = <4>; + label = "main"; + apple,main-chain; + apple,gapf-offset = <0x540>; + apple,pwrgate-offsets = <0x1c 0x60>; + apple,fabric-domain = <&ps_fab6_soc>; + power-domains = <&ps_disp_sys>, <&ps_disp_fe>, <&ps_disp_cpu>, + <&ps_disp_spi>, <&ps_disp_spmi>, <&ps_disp_dbe>, + <&ps_disp_dp>, <&ps_disp_gp0>, <&ps_disp_gp1>, + <&ps_disp_gpl>, <&ps_disp_cmb>, <&ps_disp_ppp>, + <&ps_disp_brc>, <&ps_disp_blc>; + }; + }; + }; + - | soc { #address-cells = <2>; diff --git a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml new file mode 100644 index 00000000000000..b25cd3a74cfa04 --- /dev/null +++ b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml @@ -0,0 +1,336 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/display/apple,t8152-dcp-iboot.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T8152 DCP on the iBoot display interface + +maintainers: + - Thomas Glanzmann + +description: | + The Display Coprocessor (DCP) of the Apple T8152 SoC runs RTKit firmware + that offers a small iBoot display interface (disp0-service) next to the + full IOMobileFramebuffer protocol. This binding describes the DCP driven + through that interface, together with the DisplayPort PHY its DPTX port + is routed to. The DCP fetches through its own DART, the display pipe + scans out through another one, which sees each scanout buffer at the same + address. + +properties: + compatible: + const: apple,t8152-dcp-iboot + + apple,afk-active-endpoints: + $ref: /schemas/types.yaml#/definitions/uint32 + maximum: 65535 + description: + Runtime handoff from the bootloader. Bit N records that AFK endpoint + 0x20 + N is running and must acknowledge shutdown before a new session + starts. A zero bit means stopped. The bootloader inserts this only + for controllers whose complete endpoint state it owns, and reserves + the old session's buffers. The driver refuses takeover if absent. + This property must not be hard-coded in a board device tree. + + apple,dp-source: + $ref: /schemas/types.yaml#/definitions/uint32 + maximum: 2 + description: + Display-crossbar UFP endpoint, 0 for DCP, 1 for DCPEXT0, 2 for DCPEXT1. + The driver uses DPTX port zero, whose ATC mux selector is twice this. + + apple,usb-c-ports: + $ref: /schemas/types.yaml#/definitions/phandle + description: + Controller node containing the shared USB-C port children, dp-clock, + aux and aux-ps resources. Each connected port has one controller owner. + + apple,rtkit-wake: + type: boolean + description: + Runtime handoff for an unused DCPEXT whose firmware is loaded, powered, + and awaiting RTKit wake. The loader must reserve its firmware mappings + and buffers and supply apple,afk-active-endpoints. This property must + not be hard-coded in a board tree. An adopted HDMI session is already + running and takes precedence over this unused-controller indication. + + reg: + minItems: 2 + maxItems: 9 + + reg-names: + oneOf: + - items: + - const: coproc + - const: atc + - const: dp-clock + - const: atc-ps + - const: atc-psd + - const: aux + - const: aux-ps + minItems: 5 + description: + DCP coprocessor, ATC DisplayPort PHY (USB-C), the PMGR clock + control of its DisplayPort link, the PMGR power states the PHY + depends on, and optionally the AP DisplayPort AUX controller that + reads the sink's EDID with its PMGR power state + - items: + - const: coproc + - const: phy-core + - const: phy-apb + - const: aux + - const: aux-ps + - const: phy-ps + - const: coproc-ps + - const: coproc-psd + - const: phy-psd + minItems: 7 + description: + DCP coprocessor, the HDMI dptx-phy blocks, the AP + DisplayPort AUX controller that reads the sink's EDID with its + PMGR power state, the PMGR power state of the HDMI PHY, the read + only power state of the DCPEXT CPU, and the PMGR2 PSD service of + the HDMI PHY. The PHY is accessed only once its power states read + powered; with phy-psd it is powered up for a cold HDMI start. + - items: + - const: coproc + - const: coproc-psd + description: + Additional display controller and its PMGR2 PSD admission state; + PHY resources are shared through apple,usb-c-ports. + - items: + - const: coproc + - const: dp-clock + - const: aux + - const: aux-ps + minItems: 2 + description: + DCP coprocessor, the PMGR clock control of the ATC DisplayPort + links (one divider every eight bytes, starting with ATC0), and + optionally the AP DisplayPort AUX controller with its PMGR power + state; the USB-C ports follow as usb-c child nodes + + apple,tunable-pre: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + items: + items: + - description: register offset in the ATC PHY block + - description: mask + - description: value + description: + ATC PHY tunables (ADT ACIOPHY_CMN and CIOPLL_CORE defaults), applied + before the lane crossbar setup when the PHY starts from cold. + + apple,tunable-post: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + items: + items: + - description: register offset in the ATC PHY block + - description: mask + - description: value + description: + ATC PHY tunables (ADT ATC_FABRIC, DPPLL and AUX defaults), applied + after the lane crossbar setup. + + apple,hdmi: + type: boolean + description: + The DCP drives the HDMI port through the dedicated dptx-phy and an + on-board DisplayPort-to-HDMI converter. With apple,usb-c-ports it can + instead claim a USB-C port when the bootloader has not assigned HDMI. + + apple,tunable-phy: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + items: + items: + - description: register offset in the HDMI dptx-phy core block + - description: mask + - description: value + description: + HDMI dptx-phy tunables (ADT dptx-phy asdc and lane-shm-regs groups), + applied when the PHY starts from cold. + + apple,smc: + $ref: /schemas/types.yaml#/definitions/phandle + description: + The SMC that switches the power of the DisplayPort-to-HDMI converter. + + apple,pcon-power: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + items: + items: + - description: SMC key + - description: value, bits 63:32 + - description: value, bits 31:0 + description: + SMC writes, in order, that power the DisplayPort-to-HDMI converter + (ADT dp2hdmi-gpio0 function-dp2hdmi_pwr_en and function-hdmi_pwr_en). + The converter drives the HDMI hot-plug detect line only while it is + powered. + + hpd-gpios: + maxItems: 1 + description: + Hot plug detect line of the connector, if the AP can read it (J873g + HDMI); without it the sink is assumed to stay connected. + + mboxes: + maxItems: 1 + + iommus: + maxItems: 1 + description: DCP DART stream + + power-domains: + maxItems: 1 + description: + The coprocessor's power state, which its firmware runs; the DARTs + follow it. + + scanout: + type: object + additionalProperties: false + description: + The display pipe's scanout stream. Its DART is locked with its own + root, so it is a separate device that sees each scanout buffer at the + DCP's address. + properties: + iommus: + maxItems: 1 + dma-coherent: true + required: + - iommus + + dma-coherent: true + + apple,die: + $ref: /schemas/types.yaml#/definitions/uint32 + description: Die of the DPTX connection target, 0 if absent. + + "#address-cells": + const: 2 + + "#size-cells": + const: 2 + + ranges: true + +patternProperties: + "^usb-c@[0-9a-f]+$": + type: object + additionalProperties: false + description: + A USB-C port whose ATC PHY the DCP can drive. The DCP drives one port + at a time, the one a DisplayPort sink is plugged into. + properties: + reg: + maxItems: 3 + reg-names: + items: + - const: atc + - const: atc-ps + - const: atc-psd + description: + ATC DisplayPort PHY, the PMGR power states it depends on (DP_0, + DP_1 and USB_AON) and its common power domain (PSD) + apple,dfp-endpoint: + $ref: /schemas/types.yaml#/definitions/uint32 + description: The ATC's display-crossbar0 DFP endpoint (ATC instance). + apple,tunable-pre: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + description: As the node's apple,tunable-pre, for this port's PHY. + apple,tunable-post: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + description: As the node's apple,tunable-post, for this port's PHY. + phys: + maxItems: 1 + description: + The port's ATC PHY in DisplayPort use (PHY_TYPE_DP). A DCP powers + it while it drives the PHY, from before its cold start until its + power-down, and keeps it powered for a display the bootloader + started; the PHY driver powers the PHY's domains meanwhile and + keeps it out of USB4. The PHY refuses this while it runs USB4. + mode-switch: + type: boolean + description: + The port's display switch, one per port and shared by all DCPs + that can drive it. The port controller sets the port's + DisplayPort alt mode state, pin assignment and HPD on it; the plug + orientation is the Type-C port's. + port: + $ref: /schemas/graph.yaml#/properties/port + description: + Connects to the display port (port@3) of the port's + usb-c-connector. + dependencies: + mode-switch: [ port ] + required: + - reg + - reg-names + - apple,dfp-endpoint + +required: + - compatible + - reg + - reg-names + - mboxes + - iommus + - scanout + +additionalProperties: false + +examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + display@286e00000 { + compatible = "apple,t8152-dcp-iboot"; + reg = <0x2 0x86e00000 0x0 0x74000>, + <0x4 0x13000000 0x0 0x84000>, + <0x3 0x00020044 0x0 0x1c>, + <0x3 0x082900c0 0x0 0x104>, + <0x3 0x03a13a00 0x0 0xc0>; + reg-names = "coproc", "atc", "dp-clock", "atc-ps", "atc-psd"; + mboxes = <&dcp_mbox>; + iommus = <&dcp_dart 23>; + + scanout { + iommus = <&disp0_dart 0>; + }; + }; + + display@296e00000 { + compatible = "apple,t8152-dcp-iboot"; + reg = <0x2 0x96e00000 0x0 0x74000>, + <0x3 0x00020044 0x0 0x1c>; + reg-names = "coproc", "dp-clock"; + #address-cells = <2>; + #size-cells = <2>; + ranges; + mboxes = <&dcp_mbox>; + iommus = <&dcp_dart 23>; + + scanout { + iommus = <&disp0_dart 0>; + }; + + usb-c@413000000 { + reg = <0x4 0x13000000 0x0 0x84000>, + <0x3 0x082900c0 0x0 0x104>, + <0x3 0x03a13a00 0x0 0xc0>; + reg-names = "atc", "atc-ps", "atc-psd"; + apple,dfp-endpoint = <3>; + phys = <&atc3_phy 6>; + mode-switch; + + port { + endpoint { + remote-endpoint = <&typec3_display>; + }; + }; + }; + }; + }; diff --git a/Documentation/devicetree/bindings/dma/apple,admac.yaml b/Documentation/devicetree/bindings/dma/apple,admac.yaml index d445faceda8633..e472332dc97e73 100644 --- a/Documentation/devicetree/bindings/dma/apple,admac.yaml +++ b/Documentation/devicetree/bindings/dma/apple,admac.yaml @@ -53,6 +53,7 @@ properties: - items: - const: apple,t6041-admac - const: apple,t8132-admac + - const: apple,t8152-admac - items: - const: apple,t6050-admac - const: apple,t8140-admac diff --git a/Documentation/devicetree/bindings/dma/apple,sio.yaml b/Documentation/devicetree/bindings/dma/apple,sio.yaml index 62c517ccff0220..911a2f9e4a2637 100644 --- a/Documentation/devicetree/bindings/dma/apple,sio.yaml +++ b/Documentation/devicetree/bindings/dma/apple,sio.yaml @@ -75,12 +75,17 @@ allOf: reg: minItems: 2 maxItems: 2 + reg-names: + items: + - const: asc + - const: auxiliary clocks: minItems: 3 maxItems: 3 status: const: disabled required: + - reg-names - clocks - status - if: @@ -230,6 +235,14 @@ properties: is done upfront in the loader which can be better suited for keeping up with Apple's firmware changes. + apple,sio-firmware-params-v10: + $ref: /schemas/types.yaml#/definitions/uint32-array + description: + Optional alternative boot parameters for the low-window SIO protocol + 10 layout, using the same key/value format as apple,sio-firmware-params. + The bootloader can supply both lists when the firmware protocol is + only known after the coprocessor starts. + apple,channel-threshold: $ref: /schemas/types.yaml#/definitions/uint32 description: diff --git a/Documentation/devicetree/bindings/gpu/apple,agx.yaml b/Documentation/devicetree/bindings/gpu/apple,agx.yaml index 7794c0e13b9395..1829e74c572871 100644 --- a/Documentation/devicetree/bindings/gpu/apple,agx.yaml +++ b/Documentation/devicetree/bindings/gpu/apple,agx.yaml @@ -25,7 +25,9 @@ properties: - apple,agx-t8140 - apple,agx-t8142 - items: - - const: apple,agx-g17c + - enum: + - apple,agx-g17c + - apple,agx-g17d - const: apple,agx-g17s - items: - const: apple,agx-t8103 @@ -267,12 +269,15 @@ allOf: - if: properties: compatible: - const: apple,agx-g17s + anyOf: + - const: apple,agx-g17s + - contains: + const: apple,agx-g17d then: description: - The M5 Pro GPU uses one MMIO range and two firmware mailbox roles. - Its firmware graph supplies the performance tables, so it has no - operating-point table in the board DT. + The M5 Pro and M5 Ultra GPUs use one MMIO range and two firmware + mailbox roles. Their firmware graph supplies the performance tables, + so they have no operating-point table in the board DT. properties: reg: maxItems: 1 diff --git a/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml b/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml index b0b1dac1225ee3..fe5e0e629458e9 100644 --- a/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml +++ b/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml @@ -69,6 +69,54 @@ properties: apple,no-data-below-millicelsius adds no channel; that child supplies the zone, and its readings below the threshold are left out of it. + apple,soc-die-fan-trip-millicelsius: + maxItems: 1 + description: + Active trip temperature, in millidegrees Celsius, on the macsmc_soc_die + thermal zone for kernel hotspot fan assistance. Intended to be populated + by the boot loader (Aura) from the machine's ADT or SMC rather than + hardcoded in static board .dts files. Requires a single key in + apple,soc-die-keys, apple,soc-die-fan-hysteresis-millicelsius, and + apple,soc-die-fan-hold-ms. Without these properties, hotspot fan + assistance stays off. + + apple,soc-die-fan-hysteresis-millicelsius: + maxItems: 1 + description: + Hysteresis, in millidegrees Celsius, below + apple,soc-die-fan-trip-millicelsius for the macsmc_soc_die active trip + (release temperature is trip minus hysteresis). Intended to be populated + by the boot loader (Aura) from the machine's ADT or SMC rather than + hardcoded in static board .dts files. Must be strictly positive and less + than the trip temperature. + + apple,soc-die-fan-hold-ms: + minimum: 1 + description: + Minimum hold time, in milliseconds, that kernel hotspot fan assistance + keeps fans boosted after the GPU goes idle or the SoC die temperature + falls below the release temperature before returning them to SMC + automatic control. Intended to be populated by the boot loader (Aura) + from the machine's ADT or SMC rather than hardcoded in static board .dts + files. + + apple,soc-die-passive-millicelsius: + maxItems: 1 + description: + Passive trip temperature, in millidegrees Celsius, on the macsmc_soc_die + thermal zone. In-kernel power consumers begin shedding performance at + this temperature. Taken from the machine's ADT. Requires + apple,soc-die-keys and apple,soc-die-hot-millicelsius. + + apple,soc-die-hot-millicelsius: + maxItems: 1 + description: + Hot trip temperature, in millidegrees Celsius, on the macsmc_soc_die + thermal zone. In-kernel power consumers hold their lowest performance + state at this temperature. Taken from the machine's ADT. Must be above + apple,soc-die-passive-millicelsius. The trip reports the event without + shutting the machine down. + apple,thermal-pressure-key: $ref: /schemas/types.yaml#/definitions/string pattern: "^[A-Za-z0-9]{4}$" @@ -90,7 +138,11 @@ properties: const: 1 description: The cell is the zero-based index of a temperature channel, counting - the temperature-* child nodes in order. + the temperature-* child nodes in order. With + apple,discover-temperatures, whose channel indices are not stable, the + only sensor is 1000, the hottest of the apple,soc-die-keys readings. + A thermal zone on it comes in addition to the macsmc_soc_die zone, + which is still registered for the users that look it up by name. "#cooling-cells": const: 3 @@ -151,6 +203,26 @@ patternProperties: $ref: "#/$defs/sensor" unevaluatedProperties: false +dependentRequired: + apple,soc-die-fan-trip-millicelsius: + - apple,soc-die-keys + - apple,soc-die-fan-hysteresis-millicelsius + - apple,soc-die-fan-hold-ms + apple,soc-die-fan-hysteresis-millicelsius: + - apple,soc-die-keys + - apple,soc-die-fan-trip-millicelsius + - apple,soc-die-fan-hold-ms + apple,soc-die-fan-hold-ms: + - apple,soc-die-keys + - apple,soc-die-fan-trip-millicelsius + - apple,soc-die-fan-hysteresis-millicelsius + apple,soc-die-passive-millicelsius: + - apple,soc-die-keys + - apple,soc-die-hot-millicelsius + apple,soc-die-hot-millicelsius: + - apple,soc-die-keys + - apple,soc-die-passive-millicelsius + allOf: - if: required: diff --git a/Documentation/devicetree/bindings/i2c/apple,i2c.yaml b/Documentation/devicetree/bindings/i2c/apple,i2c.yaml index 6c649719118af1..779a9b14c6325f 100644 --- a/Documentation/devicetree/bindings/i2c/apple,i2c.yaml +++ b/Documentation/devicetree/bindings/i2c/apple,i2c.yaml @@ -32,6 +32,7 @@ properties: - apple,t8132-i2c - apple,t8140-i2c - apple,t8142-i2c + - apple,t8152-i2c - const: apple,t8103-i2c - items: - enum: diff --git a/Documentation/devicetree/bindings/iio/imu/apple,aop-motion.yaml b/Documentation/devicetree/bindings/iio/imu/apple,aop-motion.yaml index 2fe2474ee0987d..b682b877c3d7fe 100644 --- a/Documentation/devicetree/bindings/iio/imu/apple,aop-motion.yaml +++ b/Documentation/devicetree/bindings/iio/imu/apple,aop-motion.yaml @@ -26,6 +26,8 @@ properties: - items: - enum: - apple,t6000-aop-accel + - apple,t6030-aop-accel + - apple,t6031-aop-accel - apple,t6041-aop-accel - apple,t8112-aop-accel - apple,t8132-aop-accel @@ -33,6 +35,8 @@ properties: - items: - enum: - apple,t6000-aop-gyro + - apple,t6030-aop-gyro + - apple,t6031-aop-gyro - apple,t6041-aop-gyro - apple,t8112-aop-gyro - apple,t8132-aop-gyro diff --git a/Documentation/devicetree/bindings/iio/light/apple,aop-als.yaml b/Documentation/devicetree/bindings/iio/light/apple,aop-als.yaml index 5113ddb6491fb9..564caa6e649df4 100644 --- a/Documentation/devicetree/bindings/iio/light/apple,aop-als.yaml +++ b/Documentation/devicetree/bindings/iio/light/apple,aop-als.yaml @@ -21,8 +21,10 @@ select: enum: - apple,t6020-aop-als - apple,t6030-aop-als + - apple,t6031-aop-als - apple,t6050-aop-als - apple,t8112-aop-als + - apple,t8122-aop-als - apple,t8142-aop-als required: - compatible @@ -33,8 +35,10 @@ properties: - items: - enum: - apple,t6020-aop-als + - apple,t6031-aop-als - apple,t6050-aop-als - apple,t8112-aop-als + - apple,t8122-aop-als - apple,t8142-aop-als - const: apple,aop-als - items: diff --git a/Documentation/devicetree/bindings/iio/position/apple,aop-las.yaml b/Documentation/devicetree/bindings/iio/position/apple,aop-las.yaml index d3564e453f0c49..0002ff36b4e923 100644 --- a/Documentation/devicetree/bindings/iio/position/apple,aop-las.yaml +++ b/Documentation/devicetree/bindings/iio/position/apple,aop-las.yaml @@ -21,8 +21,10 @@ select: enum: - apple,t6020-aop-las - apple,t6030-aop-las + - apple,t6031-aop-las - apple,t6050-aop-las - apple,t8112-aop-las + - apple,t8122-aop-las - apple,t8142-aop-las required: - compatible @@ -33,8 +35,10 @@ properties: - items: - enum: - apple,t6020-aop-las + - apple,t6031-aop-las - apple,t6050-aop-las - apple,t8112-aop-las + - apple,t8122-aop-las - apple,t8142-aop-las - const: apple,aop-las - items: diff --git a/Documentation/devicetree/bindings/input/apple,dockchannel-hid.yaml b/Documentation/devicetree/bindings/input/apple,dockchannel-hid.yaml index bf82f4dc8b3ee4..4f8da13249512a 100644 --- a/Documentation/devicetree/bindings/input/apple,dockchannel-hid.yaml +++ b/Documentation/devicetree/bindings/input/apple,dockchannel-hid.yaml @@ -168,7 +168,59 @@ properties: power method 2 notifications without controlling an AFE GPIO. Mutually exclusive with apple,afe-reset-gpios on the parent. + apple,touch-states: + type: boolean + description: + The first word of each contact record of the trackpad's standard + report (38-byte header) holds the contact's touch state in its + high byte (start in range, hover, make touch, touching, break + touch, linger, out of range) and in its low byte the path ID under + which the firmware tracks the contact until it leaves the pad. + Only contacts that make or keep touch are then reported, each in + the slot of its path ID. + + apple,palm-debounce: + type: boolean + description: + The controller's palm classes (6 and above) flicker onto fingers + for single reports, so a contact counts as a palm once two + consecutive reports class it as one, whatever its tool area. + + apple,palm-tool-area: + $ref: /schemas/types.yaml#/definitions/uint32-array + description: + Palm rule of a trackpad whose hand classes are 6, 7, 8 and 12, in + units of the record's contact ellipse major axis (10 um). A + contact in a hand class whose axis passes the first value on two + consecutive reports is a palm, and so is a contact on the surface + whose axis passes the second value, whatever its class. The force + of a palm, or of a contact past either value in a hand class, does + not count towards the click the host derives from the contacts' + force. The first value is below the second, and neither is above + 32767, the largest axis the record's signed 16-bit field holds. + items: + - description: Axis that marks a hand-class contact on two + consecutive reports. + maximum: 32767 + - description: Axis wider than any finger, marking a contact on + the surface at once. + maximum: 32767 + allOf: + - if: + required: + - apple,palm-tool-area + then: + properties: + apple,palm-debounce: false + - if: + required: + - compatible + then: + properties: + apple,touch-states: false + apple,palm-debounce: false + apple,palm-tool-area: false - if: required: - apple,firmware-managed-reset diff --git a/Documentation/devicetree/bindings/iommu/apple,dart.yaml b/Documentation/devicetree/bindings/iommu/apple,dart.yaml index 6e7fdf9af5fdd6..252c44db78c4d2 100644 --- a/Documentation/devicetree/bindings/iommu/apple,dart.yaml +++ b/Documentation/devicetree/bindings/iommu/apple,dart.yaml @@ -32,6 +32,10 @@ properties: - apple,t8103-usb4-dart - apple,t8110-dart - apple,t6000-dart + - apple,t8152-dart-gen3 + - apple,t8152-acio-dart + - apple,t8152-pciec-dart + - apple,t8152-avd-dart - items: - const: apple,t8140-ane-dart - const: apple,t8140-dart @@ -70,13 +74,24 @@ properties: normal streams and their exact-RID entries may be adopted by the OS. Other streams and RID entries remain inherited. The documented static SID16 bypass role may be initialized only from a disabled stream with - no valid root; an existing bypass remains unchanged. PIODMA and other + no valid root; an existing bypass remains unless apple,sid16-page + narrows it to one page. PIODMA and other reserved roles are not modified. This does not authorize a controller reset or takeover of active page tables. Both the radio DART and PCI host describe the same two ordinary streams. Error reporting must already be unmasked at admission; the OS preserves the inherited global error-mask policy rather than changing it for these streams. + apple,sid16-page: + $ref: /schemas/types.yaml#/definitions/uint64 + description: > + Physical address of the one 16 KiB page the radio's static SID16 + stream needs to reach. When present, the OS translates SID16 through a + table that maps only this page, identity, instead of keeping its + bypass. It applies only with apple,managed-sids, when the DART is + admitted as the managed radio DART. It must be 16 KiB aligned and below + 2^36. + reg: minItems: 1 items: @@ -87,13 +102,16 @@ properties: fabric filter (GAPF) that protects the power state of the coprocessor CPU behind this DART, cleared to power that CPU down, or the shared PS write-disable register that holds this DART's - bit for the same purpose (T8142) + bit for the same purpose (T8142), or on a T8152 Gen3 DART its + window in the SoC's TLB invalidation aperture (ADT + dart-tlbi-aperture plus tlbi-aperture-offset), which the Gen3 + DARTs share reg-names: minItems: 1 items: - const: dart - - enum: [dapf, gapf, ps-wr-dis, auxiliary] + - enum: [dapf, gapf, ps-wr-dis, auxiliary, tlbi] interrupts: maxItems: 1 @@ -320,6 +338,17 @@ properties: and filtering state without a separate page-table root. Source and destination must differ, and both must exist on the controller. + apple,retain-translation: + type: boolean + description: > + The bootloader hands this DART over translating, with stream page + tables that a co-processor's firmware keeps using, but without setting + the hardware lock. The operating system then treats the DART as locked: + it does not reset it or replace the inherited stream roots, adds its + own mappings only in root entries that are empty at handoff, and on + detach clears only the entries it added. The entries present at handoff + stay owned by the firmware, which may keep using them at any time. + required: - compatible - reg @@ -328,6 +357,7 @@ required: dependencies: apple,gapf-slice-values: [ 'apple,gapf-slice' ] + apple,sid16-page: [ 'apple,managed-sids' ] allOf: - if: @@ -350,6 +380,68 @@ allOf: then: required: - reg-names + - if: + properties: + compatible: + contains: + enum: + - apple,t8152-dart-gen3 + - apple,t8152-acio-dart + - apple,t8152-pciec-dart + - apple,t8152-avd-dart + then: + description: + The T8152 Gen3 DARTs in front of the display coprocessors and their + display pipes belong to the SPTM. The bootloader hands them over + locked, and the operating system only adds page table entries in + root slots that are empty at handoff. Their TLB command register + answers translation queries; a stream is invalidated through the + TLB invalidation aperture instead. The DARTs of the rear USB4 + routers (ACIO NHI streams) and of their PCIe-C tunnels use the same + invalidation aperture, each at its own slot, but start unlocked with + inactive streams and are initialized by the operating system. + The T8152 AVD instance uses the same aperture, starts unlocked with + inactive streams and is initialized after its PSD domain is on. + properties: + reg: + minItems: 2 + reg-names: + items: + - const: dart + - const: tlbi + required: + - reg-names + else: + properties: + reg-names: + minItems: 1 + items: + - const: dart + - enum: [dapf, gapf, ps-wr-dis, auxiliary] + + - if: + properties: + compatible: + contains: + const: apple,t8152-avd-dart + then: + required: + - power-domains + - apple,dma-range + - apple,tunable + + - if: + properties: + compatible: + contains: + enum: + - apple,t8152-acio-dart + - apple,t8152-pciec-dart + then: + # apple,tunable: the bootloader copies it from the ADT (dart-acioN, + # dart-apciecN); a device tree describes these DARTs without one. + required: + - apple,dma-range additionalProperties: false diff --git a/Documentation/devicetree/bindings/iommu/apple,sart.yaml b/Documentation/devicetree/bindings/iommu/apple,sart.yaml index 19ffe1bf167f73..a545bddf78d80a 100644 --- a/Documentation/devicetree/bindings/iommu/apple,sart.yaml +++ b/Documentation/devicetree/bindings/iommu/apple,sart.yaml @@ -26,8 +26,8 @@ description: SART3, first seen in M1 Pro/Max, extends both the address space and filter entry size to 42 bit. - SART4, seen on M5 Ultra (T6050), keeps SART3's entries but moves the - address and size arrays, so it has no SART3 fallback. + SART4, seen on M5 Ultra (T6050) and M6 (T8152), keeps SART3's entries but + moves the address and size arrays, so it has no SART3 fallback. properties: compatible: @@ -49,6 +49,7 @@ properties: - apple,t6050-sart - apple,t8015-sart - apple,t8103-sart + - apple,t8152-sart reg: maxItems: 1 diff --git a/Documentation/devicetree/bindings/mailbox/apple,ascwrap-v6.yaml b/Documentation/devicetree/bindings/mailbox/apple,ascwrap-v6.yaml index 349d6930d07e02..0bf483a096e1ee 100644 --- a/Documentation/devicetree/bindings/mailbox/apple,ascwrap-v6.yaml +++ b/Documentation/devicetree/bindings/mailbox/apple,ascwrap-v6.yaml @@ -24,8 +24,6 @@ properties: - apple,t6040-ascwrap-v6 - apple,t8140-ascwrap-v6 - apple,t8142-ascwrap-v6 - - apple,t6050-ascwrap-v6 - - apple,t6050-x1n1-ascwrap-v6 - apple,t6050-j775d-ascwrap-v6 reg: diff --git a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml index 8afd38261fe30b..7f1dcbfcf79687 100644 --- a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml +++ b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml @@ -27,6 +27,31 @@ properties: masking provided by the interrupt controller. const: apple,t8152-smc-mailbox + - description: + The other T8152 post-office mailboxes. Each coprocessor has its own + window of the same counted-FIFO block as the SMC's. + items: + - enum: + - apple,t8152-ans-mailbox + - apple,t8152-dcp-mailbox + - apple,t8152-mtp-mailbox + - apple,t8152-sep-mailbox + - const: apple,t8152-smc-mailbox + + - description: + T8152 ASC wrapper (v8) mailbox of the AOP, with the counted + FIFOs of the SMC mailbox, described with its send-empty and + recv-not-empty interrupts. + const: apple,t8152-ascwrap-v8-mailbox + + - description: + T8152 ACIO mailbox of a USB4 router's coprocessor, a 0x80 window + with the counted FIFOs of the SMC mailbox, described with its + send-empty and recv-not-empty interrupts. + items: + - const: apple,t8152-cio-mailbox + - const: apple,t8152-smc-mailbox + - description: ASC mailboxes are the most common variant found on the M1 used for example for the display controller, the system management @@ -81,6 +106,7 @@ properties: iop,secure-rtbuddy-proxy. It is polled, with no interrupts described. items: - enum: + - apple,t6050-secure-rtbuddy-proxy - apple,t8140-secure-rtbuddy-proxy - const: apple,secure-rtbuddy-proxy @@ -164,7 +190,9 @@ allOf: properties: compatible: contains: - const: apple,t8152-smc-mailbox + enum: + - apple,t8152-ascwrap-v8-mailbox + - apple,t8152-smc-mailbox then: properties: interrupts: @@ -223,6 +251,7 @@ allOf: - apple,t6021-ane-mailbox - apple,t8112-ane-mailbox - apple,t8140-aop-setup-mailbox + - apple,t8152-ascwrap-v8-mailbox - apple,t8152-smc-mailbox then: properties: @@ -243,6 +272,20 @@ required: additionalProperties: false examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + mailbox@316020300 { + compatible = "apple,t8152-ans-mailbox", "apple,t8152-smc-mailbox"; + reg = <0x3 0x16020300 0x0 0x80>; + interrupts = <1 302 4>, <1 262 4>; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + }; + - | mailbox@77408000 { compatible = "apple,t8103-asc-mailbox", "apple,asc-mailbox-v4"; diff --git a/Documentation/devicetree/bindings/media/apple,avd.yaml b/Documentation/devicetree/bindings/media/apple,avd.yaml index 28944ad86ca1b7..2df00bda8c33b5 100644 --- a/Documentation/devicetree/bindings/media/apple,avd.yaml +++ b/Documentation/devicetree/bindings/media/apple,avd.yaml @@ -131,7 +131,9 @@ allOf: minItems: 1 items: - description: decoder power state - - description: performance floor (PMC rail or PMP device level) held while decoding + - description: > + performance floor (PMC rail or PMP device level) engaged on + demand during high-load decoding power-domain-names: minItems: 1 diff --git a/Documentation/devicetree/bindings/media/apple,prores.yaml b/Documentation/devicetree/bindings/media/apple,prores.yaml index 6d9c2231222c00..fc91dfdfe7ca3d 100644 --- a/Documentation/devicetree/bindings/media/apple,prores.yaml +++ b/Documentation/devicetree/bindings/media/apple,prores.yaml @@ -127,12 +127,22 @@ allOf: minItems: 2 maxItems: 3 + reg-names: + minItems: 2 + items: + - const: core + - const: wrapper + - const: aux + interrupts: maxItems: 1 power-domains: maxItems: 1 + resets: + maxItems: 1 + iommus: minItems: 1 maxItems: 2 diff --git a/Documentation/devicetree/bindings/media/apple,scaler-v23.yaml b/Documentation/devicetree/bindings/media/apple,scaler-v23.yaml index ac3fa521557d51..fdb507eddfba34 100644 --- a/Documentation/devicetree/bindings/media/apple,scaler-v23.yaml +++ b/Documentation/devicetree/bindings/media/apple,scaler-v23.yaml @@ -20,7 +20,9 @@ description: | resources. Each instance has its own DART; an advertised MSRn-DART gate belongs to that DART, rather than the scaler functional domains. Keep the device disabled until its firmware handoff, clocks, - power and reset ownership have been qualified. + power and reset ownership have been qualified. They have been on + T8142, whose firmware core the OS starts from the image the boot + loader pre-loads. properties: compatible: @@ -59,15 +61,11 @@ properties: resets: maxItems: 1 - status: - const: disabled - required: - compatible - reg - interrupts - iommus - - status allOf: - if: @@ -108,4 +106,18 @@ allOf: - power-domains - resets + - if: + properties: + compatible: + contains: + enum: + - apple,t6050-scaler + - apple,t8152-scaler + then: + properties: + status: + const: disabled + required: + - status + additionalProperties: false diff --git a/Documentation/devicetree/bindings/media/apple,t8152-avd.yaml b/Documentation/devicetree/bindings/media/apple,t8152-avd.yaml new file mode 100644 index 00000000000000..585a0a897fed72 --- /dev/null +++ b/Documentation/devicetree/bindings/media/apple,t8152-avd.yaml @@ -0,0 +1,73 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/media/apple,t8152-avd.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T8152 Kopsia video decoder + +maintainers: + - Thomas Glanzmann + +description: + Kopsia is the T8152 stateless video decoder. Its decoder, PIODMA and + auxiliary data streams share a Gen3 DART and a PSD power domain. The host + submits codec programs with the MCU halted and polls decoder status; + the PostOffice mailbox transport is not used by this implementation. + +properties: + compatible: + const: apple,t8152-avd + + reg: + items: + - description: MCU code memory + - description: MCU control registers + - description: Decoder control registers + - description: Decoder wrapper registers + - description: PIODMA registers + + reg-names: + items: + - const: code + - const: mbox + - const: ctrl + - const: wrap + - const: dma + + iommus: + items: + - description: Decoder stream + - description: PIODMA stream + - description: Auxiliary data stream + + power-domains: + maxItems: 1 + +required: + - compatible + - reg + - reg-names + - iommus + - power-domains + +additionalProperties: false + +examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + video-codec@485400000 { + compatible = "apple,t8152-avd"; + reg = <0x4 0x85400000 0x0 0x12000>, + <0x4 0x85500000 0x0 0x4000>, + <0x4 0x85100000 0x0 0x10000>, + <0x4 0x850c0000 0x0 0x4000>, + <0x4 0x85070000 0x0 0x4000>; + reg-names = "code", "mbox", "ctrl", "wrap", "dma"; + iommus = <&avd_dart 0>, <&avd_dart 1>, <&avd_dart 2>; + power-domains = <&ps_avd>; + }; + }; diff --git a/Documentation/devicetree/bindings/mfd/apple,smc.yaml b/Documentation/devicetree/bindings/mfd/apple,smc.yaml index c35e7d0e10faa6..255209498bd596 100644 --- a/Documentation/devicetree/bindings/mfd/apple,smc.yaml +++ b/Documentation/devicetree/bindings/mfd/apple,smc.yaml @@ -51,6 +51,24 @@ properties: mboxes: maxItems: 1 + apple,sleep-wake-type: + type: boolean + description: + The SMC firmware expects the wake type key (WKTP) set to its sleep value + at the sleep commit, and cleared after a full wake. Left at the sleep + value, the SMC treats the time awake as a power nap. + + apple,sleep-pmvc: + $ref: /schemas/types.yaml#/definitions/uint32 + minimum: 0x100 + maximum: 0x1ff + description: + The value written to the SMC's VDD_CIO rail key (pmVC) at the sleep + commit, before the sleep notice. Bit 8 is set, and bit n keeps port n's + CIO rail powered across the sleep. Which rails must stay up depends on + what the SoC's sleep sequence powers on itself. Without the property + pmVC is not written. + gpio: oneOf: - $ref: /schemas/gpio/apple,smc-gpio.yaml @@ -68,6 +86,22 @@ properties: hwmon: $ref: /schemas/hwmon/apple,smc-hwmon.yaml + apple,wake-reasons: + $ref: /schemas/types.yaml#/definitions/uint32-array + minItems: 1 + maxItems: 64 + items: + maximum: 63 + description: | + The bits of the SMC's wake record that have a name on this board, as the + ADT's smc-pmu node numbers them (event_name-bitN). + + apple,wake-reason-names: + $ref: /schemas/types.yaml#/definitions/string-array + minItems: 1 + maxItems: 64 + description: The names of the bits in apple,wake-reasons, in the same order. + additionalProperties: false required: diff --git a/Documentation/devicetree/bindings/net/wireless/apple,centauri.yaml b/Documentation/devicetree/bindings/net/wireless/apple,centauri.yaml index 8d226eec130917..7f064886f055f2 100644 --- a/Documentation/devicetree/bindings/net/wireless/apple,centauri.yaml +++ b/Documentation/devicetree/bindings/net/wireless/apple,centauri.yaml @@ -24,6 +24,11 @@ description: | native driver selects personalized firmware and transport data from its root-board match table rather than the T6050 wire-protocol properties. + On T8142 the root port above function zero may describe the N1's warm + reset with apple,function-warm-reset and apple,warm-reset-writes, as in + pci/apple,pcie.yaml. With both, the native driver restarts a firmware + that stopped; without them it never resets the chip. + properties: compatible: oneOf: diff --git a/Documentation/devicetree/bindings/npu/apple,ane.yaml b/Documentation/devicetree/bindings/npu/apple,ane.yaml index 999599f852d8ac..033bfd15cf9637 100644 --- a/Documentation/devicetree/bindings/npu/apple,ane.yaml +++ b/Documentation/devicetree/bindings/npu/apple,ane.yaml @@ -23,7 +23,10 @@ description: yet established. T8132 has a single H16 engine, two interrupts, six register windows (no second-engine aux-3), and five DAPF records. Its virtual ANE-SYS-V gate resolves to the ANE system domain; ANE-SYS-V-PMP - is a firmware notification gate with no physical PMGR power state. + is a firmware notification gate with no physical PMGR power state. T8122 + has a single H15 engine, one interrupt, three register windows (engine, + pmgr, aux-0), five ANE power domains, five DAPF records, and preloaded + firmware. properties: compatible: @@ -37,6 +40,7 @@ properties: - apple,t6041-ane - apple,t6050-ane - apple,t8112-ane + - apple,t8122-ane - apple,t8132-ane - apple,t8140-ane - apple,t8142-ane @@ -139,12 +143,13 @@ properties: $ref: /schemas/types.yaml#/definitions/uint64-array items: - const: 0x10000000000 - - const: 0x100000c0000 + - enum: [0x100000bc000, 0x100000c0000, 0x100000c8000] description: - Device addresses of the preloaded TEXT and DATA segments. Their sizes - are 0xc0000 and 0x2ac000 bytes respectively. The bootloader supplies - the physical reservations. The device addresses are fixed by the - firmware layout and may be described statically. + Device addresses of the preloaded TEXT and DATA segments. The bootloader + supplies the physical reservations. The device addresses are fixed by the + firmware layout (TEXT at 0x10000000000; DATA at 0x100000bc000 on T8132 + 27.2, 0x100000c0000 on H16/H17 26.x, or 0x100000c8000 on T8122 27.2) and + may be described statically. apple,dapf-ranges: $ref: /schemas/types.yaml#/definitions/uint64-matrix @@ -155,7 +160,7 @@ properties: - description: Physical start address, inclusive - description: Physical end address, inclusive description: - Four (five on T6050 and T8132) DART address protection filter (DAPF) + Four (five on T6050, T8122 and T8132) DART address protection filter (DAPF) ranges, in hardware record order. Each pair contains inclusive 64-bit physical bounds, not a base and length. The same records apply to all three ANE DARTs. Firmware accesses these registers through identity mappings of the @@ -175,7 +180,7 @@ properties: apple,ane-type: $ref: /schemas/types.yaml#/definitions/uint32 - enum: [0x100, 0x110, 0x200] + enum: [0xb0, 0x100, 0x110, 0x200] description: Firmware generation identifier supplied by the bootloader apple,firmware-preloaded: @@ -366,6 +371,33 @@ allOf: - apple,ane-type - apple,firmware-preloaded - apple,dapf-ranges + - if: + properties: + compatible: + const: apple,t8122-ane + then: + properties: + interrupts: + maxItems: 1 + reg: + minItems: 3 + maxItems: 3 + reg-names: + items: + - const: engine + - const: pmgr + - const: aux-0 + power-domains: + minItems: 5 + maxItems: 5 + apple,ane-type: + const: 0xb0 + apple,dapf-ranges: + minItems: 5 + required: + - apple,ane-type + - apple,firmware-preloaded + - apple,dapf-ranges - if: properties: compatible: @@ -388,6 +420,7 @@ allOf: - apple,t8140-ane - apple,t6041-ane - apple,t6050-ane + - apple,t8122-ane - apple,t8142-ane - apple,t8132-ane then: diff --git a/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml b/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml index e983d8baf3837a..13c643012a5577 100644 --- a/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml +++ b/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml @@ -23,6 +23,7 @@ properties: - apple,t8122-nvme-ans2 - const: apple,t8103-nvme-ans2 - const: apple,t8132-nvme-ans2 + - const: apple,t8152-nvme-ans2 - items: - const: apple,t8132-nvme-ans2 - const: apple,t8103-nvme-ans2 @@ -117,6 +118,20 @@ properties: Without it the controller refuses the deep sleep. allOf: + - if: + properties: + compatible: + not: + contains: + enum: + - apple,t6050-nvme-ans2 + - apple,t8152-nvme-ans2 + then: + required: + - resets + - power-domains + - power-domain-names + - if: properties: compatible: @@ -192,10 +207,6 @@ allOf: else: properties: apple,sleep-wake-delay-ms: false - required: - - resets - - power-domains - - power-domain-names required: - compatible diff --git a/Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml b/Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml index fe8b2001f4fa56..6b83a1528da7fc 100644 --- a/Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml +++ b/Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml @@ -21,6 +21,7 @@ properties: - apple,abbey-pmic - apple,baku-pmic - apple,chapel-pmic + - apple,club-pmic - apple,maverick-pmic - apple,mirabeau-pmic - apple,monaco-pmic @@ -28,6 +29,7 @@ properties: - apple,simetra-pmic - apple,stowe-pmic - apple,vale-pmic + - apple,woodcote-pmic - const: apple,spmi-nvmem reg: diff --git a/Documentation/devicetree/bindings/pci/apple,pcie.yaml b/Documentation/devicetree/bindings/pci/apple,pcie.yaml index a9fd4822fd1272..90e0abb33c3c68 100644 --- a/Documentation/devicetree/bindings/pci/apple,pcie.yaml +++ b/Documentation/devicetree/bindings/pci/apple,pcie.yaml @@ -101,6 +101,8 @@ properties: - const: apple,t8103-pciec - const: apple,t6000-pciec - const: apple,t6050-pciec + - const: apple,t8142-pciec + - const: apple,t8152-pciec - items: - const: apple,t8132-pciec - const: apple,t8122-pciec @@ -374,6 +376,8 @@ allOf: contains: enum: - apple,t8132-pciec + - apple,t8142-pciec + - apple,t8152-pciec - apple,t6040-pciec then: required: @@ -501,6 +505,8 @@ allOf: - apple,t6000-pciec - apple,t6040-pciec - apple,t6050-pciec + - apple,t8142-pciec + - apple,t8152-pciec then: properties: reg: @@ -688,22 +694,51 @@ allOf: interrupts: maxItems: 3 else: - properties: - reg: - maxItems: 10 - reg-names: - minItems: 3 - items: - - const: config - - const: rc - - const: port0 - - const: port1 - - const: port2 - - const: port3 - - const: phy0 - - const: phy1 - - const: phy2 - - const: phy3 + if: + properties: + compatible: + contains: + const: apple,t6041-pcie + then: + properties: + reg: + minItems: 10 + maxItems: 15 + reg-names: + minItems: 10 + items: + - const: config + - const: rc + - const: port0 + - const: port1 + - const: port2 + - const: port3 + - const: phy0 + - const: phy1 + - const: phy2 + - const: phy3 + - const: axi2af + - const: cio3pll + - const: clkgen + - const: phy-block + - const: phy-ip + else: + properties: + reg: + maxItems: 10 + reg-names: + minItems: 3 + items: + - const: config + - const: rc + - const: port0 + - const: port1 + - const: port2 + - const: port3 + - const: phy0 + - const: phy1 + - const: phy2 + - const: phy3 patternProperties: "^pci@": properties: diff --git a/Documentation/devicetree/bindings/phy/apple,atcphy.yaml b/Documentation/devicetree/bindings/phy/apple,atcphy.yaml index 41ecaccc8a0aef..1caaf7f6bae0a2 100644 --- a/Documentation/devicetree/bindings/phy/apple,atcphy.yaml +++ b/Documentation/devicetree/bindings/phy/apple,atcphy.yaml @@ -40,6 +40,18 @@ description: > DisplayPort also requires separate bootloader-provided calibration lists for that bank and the common configuration in the lpdptx region. + The T8152 variant is supported as the USB3 PHY of a fixed-USB3 port, see + apple,fixed-usb3, and as the PHY of a Type-C port in USB4/Thunderbolt + ("Converged IO", CIO) mode alone. Its core bank also holds the USB + controller's DARTs. Its power domains are the ATC's PMGR power states and + PSD service the PHY needs, in the order they are powered up. The lanes of + the mode are powered up and the crossbar set between the common-a tunables + and the others. A fixed-USB3 port is described by its core and pipehandler + banks. A Type-C port is described by its core bank alone: its DisplayPort + alternate mode is driven by the display controller, which takes the PHY + through its DisplayPort PHY (PHY_TYPE_DP) and has the PHY's power domains + powered while it drives it, and its USB2 side is left to the bootloader. + allOf: - $ref: /schemas/usb/usb-switch.yaml# - if: @@ -121,33 +133,98 @@ allOf: - const: common-config required: - power-domains + else: + if: + properties: + compatible: + contains: + const: apple,t8152-atcphy + then: + properties: + reg: + minItems: 1 + items: + - description: + PHY core with its power and reset block, which also holds + the USB controller's DARTs + - description: USB3 PIPE interface controls (fixed-USB3 port) + reg-names: + minItems: 1 + items: + - const: core + - const: pipehandler + power-domains: + items: + - description: The ATC's USB_AON power state + - description: The ATC's common PSD service + - description: The ATC's COMMON_DP_0 power state + - description: The ATC's COMMON_DP_1 power state + required: + - power-domains + else: + properties: + reg: + minItems: 5 + items: + - description: Common controls for all PHYs (USB2/3/4, DisplayPort, TBT) + - description: DisplayPort Alternate Mode PHY specific controls + - description: Type-C PHY AXI to Apple Fabric interconnect controls + - description: USB2 PHY specific controls + - description: USB3 PIPE interface controls + - description: Secondary eUSB2 PHY register bank (T8140) + - description: + Power and hibernation control of the USB controller the PHY + serves (T8140). The PHY drives that controller's reset and + takes it through hibernation for a system sleep. + reg-names: + minItems: 5 + items: + - const: core + - const: lpdptx + - const: axi2af + - const: usb2phy + - const: pipehandler + - const: usb2phy-reg + - const: pwrctl + required: + - power-domains + - if: + properties: + compatible: + contains: + const: apple,t8152-atcphy + then: + properties: + "#reset-cells": false + if: + required: + - apple,fixed-usb3 + then: + properties: + mode-switch: false + orientation-switch: false + ports: false + reg: + minItems: 2 + reg-names: + minItems: 2 else: properties: reg: - minItems: 5 - items: - - description: Common controls for all PHYs (USB2/3/4, DisplayPort, TBT) - - description: DisplayPort Alternate Mode PHY specific controls - - description: Type-C PHY AXI to Apple Fabric interconnect controls - - description: USB2 PHY specific controls - - description: USB3 PIPE interface controls - - description: Secondary eUSB2 PHY register bank (T8140) - - description: - Power and hibernation control of the USB controller the PHY - serves (T8140). The PHY drives that controller's reset and - takes it through hibernation for a system sleep. + maxItems: 1 reg-names: - minItems: 5 - items: - - const: core - - const: lpdptx - - const: axi2af - - const: usb2phy - - const: pipehandler - - const: usb2phy-reg - - const: pwrctl + maxItems: 1 required: - - power-domains + - mode-switch + - orientation-switch + - ports + else: + properties: + apple,fixed-usb3: false + power-domains: + maxItems: 1 + required: + - "#reset-cells" - if: properties: compatible: @@ -234,6 +311,7 @@ allOf: - apple,t8122-atcphy - apple,t6030-atcphy - apple,t6031-atcphy + - apple,t8152-atcphy then: required: - orientation-switch @@ -275,6 +353,7 @@ properties: - const: apple,t8132-atcphy - const: apple,t8140-atcphy - const: apple,t8142-atcphy + - const: apple,t8152-atcphy reg: minItems: 1 @@ -294,7 +373,8 @@ properties: orientation-switch: true power-domains: - maxItems: 1 + minItems: 1 + maxItems: 4 phys: maxItems: 1 @@ -323,6 +403,16 @@ properties: $ref: /schemas/graph.yaml#/properties/port description: Incoming endpoint from the USB4/Thunderbolt controller. + apple,fixed-usb3: + type: boolean + description: > + T8152 only. The port's SuperSpeed lanes go straight to a USB3 device or + hub, with no Type-C mux in between, so the PHY runs USB3 on lane 0 from + probe on and ignores mux and orientation changes. It provides only the + USB3 PHY of its USB controller, which is a host, and leaves the + controller's USB2 side and reset to the bootloader. Without it a T8152 + PHY is a Type-C port's, run in CIO mode alone. + apple,dp-alt-mode: type: boolean description: > @@ -521,7 +611,6 @@ required: - reg - reg-names - "#phy-cells" - - "#reset-cells" additionalProperties: false @@ -622,3 +711,48 @@ examples: }; }; }; + + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + phy@383000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x3 0x83000000 0x0 0x84000>, + <0x3 0x82414000 0x0 0x4000>; + reg-names = "core", "pipehandler"; + + #phy-cells = <1>; + apple,fixed-usb3; + power-domains = <&ps_atc2_usb_aon>, <&ps_atc2_common>, + <&ps_atc2_common_dp_0>, <&ps_atc2_common_dp_1>; + /* The bootloader adds the tunables from the ADT. */ + }; + + phy@413000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x4 0x13000000 0x0 0x84000>; + reg-names = "core"; + + #phy-cells = <1>; + orientation-switch; + mode-switch; + power-domains = <&ps_atc3_usb_aon>, <&ps_atc3_common>, + <&ps_atc3_common_dp_0>, <&ps_atc3_common_dp_1>; + /* The bootloader adds the tunables from the ADT. */ + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + endpoint { + remote-endpoint = <&typec3_ss>; + }; + }; + }; + }; + }; diff --git a/Documentation/devicetree/bindings/phy/apple,dptx-phy.yaml b/Documentation/devicetree/bindings/phy/apple,dptx-phy.yaml index 5e48405d80a127..01dc9abadc887a 100644 --- a/Documentation/devicetree/bindings/phy/apple,dptx-phy.yaml +++ b/Documentation/devicetree/bindings/phy/apple,dptx-phy.yaml @@ -24,6 +24,7 @@ select: - apple,t6041-dptx-phy - apple,t6050-dptx-phy - apple,t8122-dptx-phy + - apple,t8132-dptx-phy required: - compatible @@ -36,7 +37,9 @@ properties: - const: apple,dptx-phy - const: apple,t6050-dptx-phy - items: - - const: apple,t6041-dptx-phy + - enum: + - apple,t6041-dptx-phy + - apple,t8132-dptx-phy - const: apple,t6050-dptx-phy reg: @@ -63,7 +66,7 @@ properties: The display crossbar's upstream-facing endpoint that feeds this PHY. patternProperties: - '^apple,(pll-(dcocfg|dtcvreg|dtccal|dcdadj|dlfcfg)|pclkdrv-select)$': + '^apple,(pll-(dcocfg|dtcvreg|dtccal|dcdadj|dlfcfg|rodcoroleakcomp)|pclkdrv-select)$': $ref: /schemas/types.yaml#/definitions/uint32 description: PLL and pixel clock driver settings the PHY is programmed with, as the diff --git a/Documentation/devicetree/bindings/power/apple,pmc.yaml b/Documentation/devicetree/bindings/power/apple,pmc.yaml index 434126bb21506f..9f2d9f1b3eafe1 100644 --- a/Documentation/devicetree/bindings/power/apple,pmc.yaml +++ b/Documentation/devicetree/bindings/power/apple,pmc.yaml @@ -278,6 +278,68 @@ patternProperties: offers on some MacBook Pros. The performance platform profile then tells the SMC (apple,smc) that it is on. + apple,low-power-frequency-max-mhz: + description: + The machine's CPU frequency ceiling in macOS's Low Power mode, in + MHz, as the ADT's cpu-low-power-frequency-max has it. The low-power + platform profile holds the CPU clusters to it, up to the next + frequency of their tables. + + apple,gpu-busy-memory-states: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + description: + The DCS state (first row) and fabric state (second row) for GPU work + the GPU driver reports, by the busy share it reports, below each of + the three apple,gpu-busy-permille shares and at or above the last. + A non-zero top DCS state enables the busy-share ladder; without + these properties, reported GPU work gets the compatible's default + floor. + minItems: 2 + maxItems: 2 + items: + minItems: 4 + maxItems: 4 + items: + maximum: 15 + + apple,gpu-busy-permille: + $ref: /schemas/types.yaml#/definitions/uint32-array + description: + The GPU busy shares, in permille of the time the GPU spends + executing, from which reported GPU work gets the second, third and + top column of apple,gpu-busy-memory-states. + minItems: 3 + maxItems: 3 + items: + maximum: 1000 + + apple,cpu-busy-floor: + $ref: /schemas/types.yaml#/definitions/uint32-array + items: + - description: + DCS state index on the CLPC's DCS rail, 0 for the lowest state + minimum: 0 + maximum: 15 + - description: + Fabric state index on the CLPC's fabric rail, 0 for the lowest + state + minimum: 0 + maximum: 15 + description: + The DCS and fabric state pair a CPU cluster busy in the top quarter + of its frequency range requests on this board outside the low-power + platform profile, taken from the CLPC floor residency macOS shows on + it in its default energy mode. Each index is a 4-bit PMC rail field; + an index above 15, or a cell count other than two, is rejected and + the SoC's table applies. Without the property, or while the + low-power platform profile is active, the SoC's table applies. + + dependentRequired: + apple,gpu-busy-memory-states: + - apple,gpu-busy-permille + apple,gpu-busy-permille: + - apple,gpu-busy-memory-states + required: - compatible - reg diff --git a/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml b/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml index d8c03b0a12702c..999c31c461f2c8 100644 --- a/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml +++ b/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml @@ -25,11 +25,30 @@ allOf: apple,sleep-retained: false apple,sleep-driver-owned: false apple,always-on: false + apple,auto-managed: false apple,min-state: false apple,force-disable: false apple,force-reset: false apple,externally-clocked: false apple,consumer-switched: false + - if: + properties: + compatible: + contains: + const: apple,t8132-pmgr-pwrstate + required: + - compatible + then: + properties: + apple,auto-managed: false + - if: + required: + - apple,auto-managed + then: + properties: + apple,no-auto-pm: false + apple,firmware-owned: false + apple,inherited-on: false - if: required: - apple,consumer-switched @@ -90,6 +109,7 @@ properties: - apple,t8132-pmgr-pwrstate - apple,t8140-pmgr-pwrstate - apple,t8142-pmgr-pwrstate + - apple,t8152-pmgr-pwrstate - const: apple,t8103-pmgr-pwrstate reg: @@ -135,6 +155,18 @@ properties: coprocessors' CPU domains. type: boolean + apple,auto-managed: + description: | + Hardware-managed power domain (such as a DRAM channel slice or memory + fabric) that the boot loader may leave forced on and that must be + switched to hardware automatic power management (auto-enable) early + at boot, before the PMP firmware starts. + + Once switched, the hardware gates the domain by itself and it has no + software-controlled power transitions. On parts where an instance is + fused off, its power-state register reads as off. + type: boolean + apple,sleep-retained: description: A coprocessor keeps running in this domain across system sleep with no @@ -151,11 +183,12 @@ properties: apple,sleep-wakeup-path: description: - A consumer of this domain is stopped by the system sleep's final commit, - after the noirq phase, and stays on the wakeup path until then. The OS - keeps the domain on through system sleep while a device under it is on - the wakeup path, also when the domain was off when the power controller - probed. Other domains are unaffected. + A consumer of this domain can keep running into system sleep, until the + sleep's final commit after the noirq phase or through the whole sleep, + and is then on the wakeup path. The OS keeps the domain on through + system sleep while a device under it is on the wakeup path, also when + the domain was off when the power controller probed. Other domains are + unaffected. type: boolean apple,firmware-owned: diff --git a/Documentation/devicetree/bindings/power/apple,t8152-psd.yaml b/Documentation/devicetree/bindings/power/apple,t8152-psd.yaml new file mode 100644 index 00000000000000..fb5b6afd10a4ac --- /dev/null +++ b/Documentation/devicetree/bindings/power/apple,t8152-psd.yaml @@ -0,0 +1,61 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/power/apple,t8152-psd.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T8152 PMGR2 PSD service + +maintainers: + - Thomas Glanzmann + +description: + On T8152, the video decoder, USB4 routers and their PHYs use PMGR2 PSD + services. The reg property identifies the 0x100-byte register block for + each service. The block contains a target-state request, an acknowledge + bit and the current state (0 powered, 6 cold). Reading the state consumes + the acknowledge. One node describes one service as a power domain. + +allOf: + - $ref: power-domain.yaml# + +properties: + compatible: + const: apple,t8152-psd + + reg: + maxItems: 1 + + '#power-domain-cells': + const: 0 + + label: + description: The service's name, for the power domain. + + apple,always-on: + type: boolean + description: + Keep the service powered. For a service whose consumers cannot yet + restore the state another agent set up in its blocks, such as a PHY + configured by the bootloader. + +required: + - compatible + - reg + - '#power-domain-cells' + +unevaluatedProperties: false + +examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + power-controller@303a13200 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x03a13200 0x0 0x100>; + #power-domain-cells = <0>; + label = "avd"; + }; + }; diff --git a/Documentation/devicetree/bindings/reset/apple,t8103-cio-reset.yaml b/Documentation/devicetree/bindings/reset/apple,t8103-cio-reset.yaml index 3b05fab7e7af1c..f72d6e97577ccd 100644 --- a/Documentation/devicetree/bindings/reset/apple,t8103-cio-reset.yaml +++ b/Documentation/devicetree/bindings/reset/apple,t8103-cio-reset.yaml @@ -38,6 +38,7 @@ properties: - enum: - apple,t8103-cio-reset - apple,t8142-cio-reset + - apple,t8152-cio-reset - apple,t6050-cio-reset - apple,t6000-cio-reset - apple,t6041-cio-reset diff --git a/Documentation/devicetree/bindings/rtc/apple,j700-pmu-rtc.yaml b/Documentation/devicetree/bindings/rtc/apple,j700-pmu-rtc.yaml index e23b6c47b1b5ed..38d4713caa7bb8 100644 --- a/Documentation/devicetree/bindings/rtc/apple,j700-pmu-rtc.yaml +++ b/Documentation/devicetree/bindings/rtc/apple,j700-pmu-rtc.yaml @@ -27,6 +27,14 @@ allOf: then: required: - interrupts + - if: + properties: + compatible: + contains: + const: apple,t8103-pmu-rtc + then: + required: + - apple,rtc-base properties: compatible: @@ -42,9 +50,20 @@ properties: - apple,t8132-pmu-rtc - const: apple,t6041-pmu-rtc - items: - - const: apple,t8122-pmu-rtc + - enum: + - apple,t8103-pmu-rtc + - apple,t8122-pmu-rtc - const: apple,t8112-pmu-rtc + apple,rtc-base: + $ref: /schemas/types.yaml#/definitions/uint32 + maximum: 0xffff + description: + Base address of the RTC register block in the parent PMIC's 16-bit + SPMI register space. Required when a PMU places a shared layout at a + different base (such as Sera on T8103); when omitted, the driver falls + back to the compatible's historical base. + interrupts: maxItems: 1 description: diff --git a/Documentation/devicetree/bindings/soc/apple/apple,aop.yaml b/Documentation/devicetree/bindings/soc/apple/apple,aop.yaml index 32abbb559afc2f..38a87bcdc18dfd 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,aop.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,aop.yaml @@ -20,7 +20,10 @@ select: items: - enum: - apple,t6020-aop + - apple,t6030-aop + - apple,t6031-aop - apple,t8112-aop + - apple,t8122-aop required: - compatible @@ -31,7 +34,10 @@ properties: - apple,t6020-aop - apple,t8112-aop - items: - - const: apple,t8122-aop + - enum: + - apple,t6030-aop + - apple,t6031-aop + - apple,t8122-aop - const: apple,t6020-aop reg: @@ -53,8 +59,8 @@ properties: maxItems: 8 description: The firmware's external code, data and log segments in DRAM, reserved - by the bootloader with their IOVAs in iommu-addresses (T6040, T8122 and - T8132). Absent when the bootloader did not reserve them. + by the bootloader with their IOVAs in iommu-addresses. Absent when + the bootloader did not reserve them. audio: $ref: /schemas/sound/apple,aop-audio.yaml# diff --git a/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml b/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml new file mode 100644 index 00000000000000..48c04851117496 --- /dev/null +++ b/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml @@ -0,0 +1,66 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/soc/apple/apple,clpc.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple SoC host performance controller (standalone) + +maintainers: + - Ryan Murray + +description: + Platform-profile provider for Apple SoCs whose host performance controller + (CLPC) does not sit under a PMC voter block (apple,pmc.yaml). Exposes + low-power, balanced and performance platform profiles and enforces CPU + frequency ceilings (and optional SMC package power targets or High Power + mode) through the shared apple-clpc driver. + +properties: + compatible: + oneOf: + - items: + - enum: + - apple,t8112-clpc + - const: apple,clpc + - const: apple,clpc + + apple,smc: + $ref: /schemas/types.yaml#/definitions/phandle + description: + The SMC, whose package power reading (PHPC) the low-power platform + profile can monitor or target, and which the performance profile tells + about High Power mode on Macs that have it. + + apple,high-power-mode: + type: boolean + description: + The machine has High Power mode, the fan and power headroom macOS + offers on some MacBook Pros. The performance platform profile then + tells the SMC (apple,smc) that it is on. + + apple,low-power-frequency-max-mhz: + description: + The machine's CPU frequency ceiling in macOS's Low Power mode, in + MHz, as the ADT's cpu-low-power-frequency-max has it. The low-power + platform profile holds the CPU clusters to it, up to the next + frequency of their tables. When absent and apple,high-power-mode is + not set, no platform profile is registered. + + apple,low-power-mw: + $ref: /schemas/types.yaml#/definitions/uint32 + description: + Optional package power target in milliwatts (measured from SMC PHPC) + for the low-power platform profile. + +required: + - compatible + +additionalProperties: false + +examples: + - | + performance-controller { + compatible = "apple,t8112-clpc", "apple,clpc"; + apple,smc = <&smc>; + }; diff --git a/Documentation/devicetree/bindings/soc/apple/apple,cluster-pwrgate.yaml b/Documentation/devicetree/bindings/soc/apple/apple,cluster-pwrgate.yaml index 43539cc51a6a37..9c48556c7d68d3 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,cluster-pwrgate.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,cluster-pwrgate.yaml @@ -11,15 +11,16 @@ maintainers: description: | PMGR words whose top bit lets a CPU power down in WFI: one per cluster on - T8132 and T8140, one per core on T6050. A core that PMGR powers on comes up - allowed to, but the boot CPU was started by the boot ROM and only follows its - word, which the boot loader may leave clear. The words are set early in boot, - in the order listed. + T8132, T8140 and T8142, one per core on T6041 and T6050. A core that PMGR + powers on comes up allowed to, but the boot CPU was started by the boot ROM + and only follows its word, which the boot loader may leave clear. The words + are set early in boot, in the order listed. properties: compatible: items: - enum: + - apple,t6041-cluster-pwrgate - apple,t6050-cluster-pwrgate - apple,t8132-cluster-pwrgate - apple,t8140-cluster-pwrgate diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t6041-sleep.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t6041-sleep.yaml new file mode 100644 index 00000000000000..08629278a48727 --- /dev/null +++ b/Documentation/devicetree/bindings/soc/apple/apple,t6041-sleep.yaml @@ -0,0 +1,437 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/soc/apple/apple,t6041-sleep.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T6041 system sleep controls + +maintainers: + - AxxzyWasTaken + +description: | + The registers and PMGR power-state domains a kernel running directly at EL2 + on the M4 Max (T6041) writes to enter and return from suspend-to-RAM and to + power its secondary CPUs off. They belong to several hardware blocks, some of + which other drivers also use, so this node overlaps those drivers' register + ranges and the driver does not claim them. The way back from a sleep is the + boot loader's S2R mailbox, which the boot loader names in /chosen; without it + the driver offers no deep sleep. + +properties: + compatible: + const: apple,t6041-sleep + + reg: + minItems: 40 + maxItems: 40 + + reg-names: + items: + - const: ps-aop + - const: cluster + - const: pwrgate + - const: cpu-start + - const: wdt + - const: aon-misc + - const: commit + - const: clk-mux + - const: ka-pmgr + - const: ka-east + - const: pmc + - const: ptd + - const: perf + - const: wake + - const: amcc0 + - const: amcc1 + - const: amcc2 + - const: amcc3 + - const: amcc4 + - const: amcc5 + - const: amcc6 + - const: amcc7 + - const: dcs0 + - const: dcs1 + - const: dcs2 + - const: dcs3 + - const: dcs4 + - const: dcs5 + - const: dcs6 + - const: dcs7 + - const: axi2af-disp + - const: axi2af-dispext0 + - const: axi2af-dispext1 + - const: axi2af-dispext2 + - const: axi2af-dispext3 + - const: axi2af-ans + - const: axi2af-avd + - const: axi2af-venc0 + - const: axi2af-venc1 + - const: axi2af-jpg + + apple,pinctrl: + $ref: /schemas/types.yaml#/definitions/phandle + description: + The AP pin controller whose pins a deep sleep resets. Its pins are saved + before a sleep and restored on wake. + + apple,pinctrl-skip-pins: + $ref: /schemas/types.yaml#/definitions/uint32-array + description: + Pins of that controller to leave alone across a sleep, neither saved nor + restored. + + apple,apcie: + $ref: /schemas/types.yaml#/definitions/phandle + description: + The PCIe host whose shared registers and tunables the storage + controller's link depends on, and whose GP ports need clock restoration + after deep sleep. Without it or its tunables, deep sleep is refused. + + apple,spmi-buses: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 2 + maxItems: 2 + items: + maxItems: 1 + description: | + The SPMI buses driven around a sleep: nub-spmi0 first (PMU boot stage + and notify mask), then nub-spmi-a0 (notify mask when powered). + + apple,atc-phys: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 4 + maxItems: 4 + items: + maxItems: 1 + description: + The four ATC PHY nodes (atcphy0 through atcphy3) whose axi2af fabric + bridges are disarmed at sleep entry and re-armed on wake. + + apple,wake-enable: + $ref: /schemas/types.yaml#/definitions/uint32-array + minItems: 1 + maxItems: 64 + description: + The AP wake source IDs left unmasked across suspend-to-RAM (ADT + ap-wake-sources). Every other wake source is masked. + + apple,sleep-off-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 1 + maxItems: 256 + items: + maxItems: 1 + description: + PMGR power-state nodes powered off before the sleep commit (sorted + child-before-parent from their DT power-domains edges) and restored to + their pre-commit states on wake. + + apple,atc-off-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 1 + maxItems: 64 + items: + maxItems: 1 + description: + USB-C / ATC PMGR power-state nodes lowered in hardware order after PS + matching and PMC/PTD quiesce, and restored to their pre-commit states on + wake. + + apple,sleep-auto-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 1 + maxItems: 128 + items: + maxItems: 1 + description: + PMGR power-state nodes placed into hardware automatic power management + with auto-state 0 (power gated) before the sleep commit, skipping fused-off + words, and restored on wake. + + apple,sleep-auto-clkgate-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 1 + maxItems: 128 + items: + maxItems: 1 + description: + PMGR power-state nodes placed into hardware automatic power management + with auto-state 4 (clock gated) before the sleep commit, skipping fused-off + words, and restored on wake. + + apple,sleep-auto-active-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 1 + maxItems: 64 + items: + maxItems: 1 + description: + PMGR power-state nodes placed into hardware automatic power management + with auto-state 15 (active) before the sleep commit and restored on wake. + + apple,sleep-keep-on-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 1 + maxItems: 64 + items: + maxItems: 1 + description: + PMGR power-state nodes held manually on (target 15, auto-enable clear) + before the sleep commit and restored on wake. + + apple,cpu-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 16 + maxItems: 16 + items: + maxItems: 1 + description: + PMGR power-state nodes for the 16 CPU cores in ADT CPU ID order + (ecpu_0..3, pcpu0_0..5, pcpu1_0..5), matched before commit and polled off + as secondary CPUs enter deep WFI. + + apple,cpm-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 3 + maxItems: 3 + items: + maxItems: 1 + description: + PMGR power-state nodes for the three cluster power managers in order + (ecpm, pcpm0, pcpm1). + + apple,sep-domain: + $ref: /schemas/types.yaml#/definitions/phandle + description: + PMGR power-state node for SEP, whose DEV_DISABLE bit is set before the + sleep commit and cleared with BUSY polled clear on wake. + + apple,spmi-a0-domain: + $ref: /schemas/types.yaml#/definitions/phandle + description: + PMGR power-state node for nub-spmi-a0, tested before accessing the second + SPMI bus's notify mask register. + + apple,atc-common-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 4 + maxItems: 4 + items: + maxItems: 1 + description: + PMGR power-state nodes for the four ATC common domains (atc0_common + through atc3_common), raised right before the sleep commit. + + apple,atc-fabric-domain: + $ref: /schemas/types.yaml#/definitions/phandle + description: + Parent fabric PMGR power-state node (fab2_soc) raised manually while + bringing up the ATC common domains and returned to auto-enable. + + apple,atc-afi-domain: + $ref: /schemas/types.yaml#/definitions/phandle + description: + AFI fabric PMGR power-state node left in hardware auto-enable after + lowering the ATC power domains. + + apple,apcie-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 8 + maxItems: 8 + items: + maxItems: 1 + description: | + The eight storage and GP PCIe PMGR power-state nodes in order: + ans, apcie_gp, apcie_sys_gp, apcie_st0, apcie_sys_st0, apcie_st1, + apcie_sys_st1, apcie_phy_sw. + + apple,commit-sio-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 2 + maxItems: 2 + items: + maxItems: 1 + description: | + The two SIO PMGR power-state nodes written in the final commit sequence, + in order: sio, sio_cpu. + + apple,commit-periph-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 5 + maxItems: 5 + items: + maxItems: 1 + description: | + The five peripheral PMGR power-state nodes lowered after the PMU boot + stage write in the final commit sequence, in order: i2c6, i2c3, i2c2, + i2c1, spi2. + + apple,axi2af-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 15 + maxItems: 15 + items: + maxItems: 1 + description: | + PMGR power-state nodes paired 1:1 with the 15 AXI2AF fabric bridges in + order: atc0..3_common (0..3), disp_sys (4), dispext0..3_sys (5..8), + ans (9), avd_sys (10), venc0_sys (11), venc1_sys (12), jpg (13), + apcie_sys_gp (14). + + apple,full-part-detect-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 2 + maxItems: 2 + items: + maxItems: 1 + description: | + The two AMCC PMGR power-state nodes (amcc24, amcc28) probed at driver + init to distinguish 24-channel binned parts from 32-channel full parts. + +required: + - compatible + - reg + - reg-names + - apple,pinctrl + - apple,spmi-buses + - apple,wake-enable + - apple,sleep-off-domains + - apple,atc-off-domains + - apple,sleep-auto-domains + - apple,sleep-auto-clkgate-domains + - apple,sleep-auto-active-domains + - apple,sleep-keep-on-domains + - apple,cpu-domains + - apple,cpm-domains + - apple,sep-domain + - apple,spmi-a0-domain + - apple,atc-common-domains + - apple,atc-fabric-domain + - apple,atc-afi-domain + - apple,apcie-domains + - apple,commit-sio-domains + - apple,commit-periph-domains + - apple,axi2af-domains + - apple,full-part-detect-domains + +allOf: + - if: + not: + properties: + status: + const: disabled + required: + - status + then: + required: + - apple,atc-phys + +additionalProperties: false + +examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + sleep-controller@508304000 { + compatible = "apple,t6041-sleep"; + reg = <0x5 0x08304000 0x0 0x4000>, + <0x5 0x02820000 0x0 0x4000>, + <0x5 0x0282c000 0x0 0x4000>, + <0x5 0x02888000 0x0 0x4000>, + <0x5 0x0836c000 0x0 0x4000>, + <0x5 0x08330000 0x0 0x4000>, + <0x5 0x08904000 0x0 0x4>, + <0x5 0x00038000 0x0 0x4000>, + <0x5 0x029dc000 0x0 0x880>, + <0x5 0x022d0000 0x0 0x880>, + <0x5 0x04800000 0x0 0xb0000>, + <0x5 0x003c0000 0x0 0x20000>, + <0x5 0x0020c000 0x0 0x800>, + <0x5 0x08004000 0x0 0x58>, + <0x2 0x20000000 0x0 0x200000>, + <0x2 0x22000000 0x0 0x200000>, + <0x2 0x24000000 0x0 0x200000>, + <0x2 0x26000000 0x0 0x200000>, + <0x2 0x28000000 0x0 0x200000>, + <0x2 0x2a000000 0x0 0x200000>, + <0x2 0x2c000000 0x0 0x200000>, + <0x2 0x2e000000 0x0 0x200000>, + <0x2 0x20200000 0x0 0x601000>, + <0x2 0x22200000 0x0 0x601000>, + <0x2 0x24200000 0x0 0x601000>, + <0x2 0x26200000 0x0 0x601000>, + <0x2 0x28200000 0x0 0x601000>, + <0x2 0x2a200000 0x0 0x601000>, + <0x2 0x2c200000 0x0 0x601000>, + <0x2 0x2e200000 0x0 0x601000>, + <0x4 0x03000100 0x0 0x10>, + <0x3 0xa3000100 0x0 0x10>, + <0x6 0x03000100 0x0 0x10>, + <0x6 0x07000100 0x0 0x10>, + <0x3 0x07000100 0x0 0x10>, + <0x4 0x0b000100 0x0 0x10>, + <0x2 0x80000100 0x0 0x10>, + <0x2 0x82000100 0x0 0x10>, + <0x2 0x84000100 0x0 0x10>, + <0x4 0x86000100 0x0 0x10>; + reg-names = "ps-aop", + "cluster", "pwrgate", "cpu-start", "wdt", + "aon-misc", "commit", "clk-mux", "ka-pmgr", + "ka-east", "pmc", "ptd", "perf", "wake", + "amcc0", "amcc1", "amcc2", "amcc3", + "amcc4", "amcc5", "amcc6", "amcc7", + "dcs0", "dcs1", "dcs2", "dcs3", + "dcs4", "dcs5", "dcs6", "dcs7", + "axi2af-disp", "axi2af-dispext0", + "axi2af-dispext1", "axi2af-dispext2", + "axi2af-dispext3", "axi2af-ans", + "axi2af-avd", "axi2af-venc0", + "axi2af-venc1", "axi2af-jpg"; + apple,pinctrl = <&pinctrl>; + apple,pinctrl-skip-pins = <190 191 192>; + apple,apcie = <&pcie0>; + apple,spmi-buses = <&nub_spmi0>, <&nub_spmi_a0>; + apple,atc-phys = <&atcphy0>, <&atcphy1>, <&atcphy2>, <&atcphy3>; + apple,wake-enable = <13 15 25 27 28 41 44 48 50 51 52 53 55 + 101 106 126 127 128 129 130 131 132 133 + 155 167>; + apple,sleep-off-domains = <&ps_gfx>, <&ps_afr>; + apple,atc-off-domains = <&ps_atc0_phymxwrap>, <&ps_atc0_common>; + apple,sleep-auto-domains = <&ps_fab0_soc>, <&ps_amcc0>; + apple,sleep-auto-clkgate-domains = <&ps_fab3_soc>, <&ps_dcs_00>; + apple,sleep-auto-active-domains = <&ps_fab2_soc>, <&ps_afi>; + apple,sleep-keep-on-domains = <&ps_sio>, <&ps_sio_cpu>; + apple,cpu-domains = <&ps_ecpu_0>, <&ps_ecpu_1>, <&ps_ecpu_2>, + <&ps_ecpu_3>, <&ps_pcpu0_0>, <&ps_pcpu0_1>, + <&ps_pcpu0_2>, <&ps_pcpu0_3>, <&ps_pcpu0_4>, + <&ps_pcpu0_5>, <&ps_pcpu1_0>, <&ps_pcpu1_1>, + <&ps_pcpu1_2>, <&ps_pcpu1_3>, <&ps_pcpu1_4>, + <&ps_pcpu1_5>; + apple,cpm-domains = <&ps_ecpm>, <&ps_pcpm0>, <&ps_pcpm1>; + apple,sep-domain = <&ps_sep>; + apple,spmi-a0-domain = <&ps_nub_spmi_a0>; + apple,atc-common-domains = <&ps_atc0_common>, <&ps_atc1_common>, + <&ps_atc2_common>, <&ps_atc3_common>; + apple,atc-fabric-domain = <&ps_fab2_soc>; + apple,atc-afi-domain = <&ps_afi>; + apple,apcie-domains = <&ps_ans>, <&ps_apcie_gp>, + <&ps_apcie_sys_gp>, <&ps_apcie_st0>, + <&ps_apcie_sys_st0>, <&ps_apcie_st1>, + <&ps_apcie_sys_st1>, <&ps_apcie_phy_sw>; + apple,commit-sio-domains = <&ps_sio>, <&ps_sio_cpu>; + apple,commit-periph-domains = <&ps_i2c6>, <&ps_i2c3>, <&ps_i2c2>, + <&ps_i2c1>, <&ps_spi2>; + apple,axi2af-domains = <&ps_atc0_common>, <&ps_atc1_common>, + <&ps_atc2_common>, <&ps_atc3_common>, + <&ps_disp_sys>, <&ps_dispext0_sys>, + <&ps_dispext1_sys>, <&ps_dispext2_sys>, + <&ps_dispext3_sys>, <&ps_ans>, + <&ps_avd_sys>, <&ps_venc0_sys>, + <&ps_venc1_sys>, <&ps_jpg>, + <&ps_apcie_sys_gp>; + apple,full-part-detect-domains = <&ps_amcc24>, <&ps_amcc28>; + }; + }; diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t6050-sleep.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t6050-sleep.yaml index c32148802bd18b..a8908c524d1ae9 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,t6050-sleep.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,t6050-sleep.yaml @@ -117,10 +117,12 @@ properties: description: The AP pin controller, whose pins a deep sleep resets. apple,pinctrl-skip-pins: - $ref: /schemas/types.yaml#/definitions/uint32-array + oneOf: + - $ref: /schemas/types.yaml#/definitions/uint32-array + - type: boolean description: | Pins neither saved nor restored. From the ADT, set by the bootloader; - without it no pin is saved. + without it no pin is saved. Empty where every pin is saved. apple,sleep-low-pins: $ref: /schemas/types.yaml#/definitions/uint32-array @@ -144,6 +146,14 @@ properties: The GFX die's wake sources left enabled for a sleep. From the ADT, set by the bootloader. + apple,display-method-sleep: + type: boolean + description: | + The display coprocessors take the sleep through their firmware 27 method + table: its sleep call and its swap, the panel's AV and DP services and the + external processors' handling around a sleep. Without it they keep the + method table they had and take the sleep's endpoint transport alone. + apple,clk-gating-boot: $ref: /schemas/types.yaml#/definitions/uint32-matrix items: diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t8140-mcc.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t8140-mcc.yaml index 08f2f7431b6c4c..c976dcca6d9610 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,t8140-mcc.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,t8140-mcc.yaml @@ -111,7 +111,10 @@ allOf: maxItems: 1 description: Devices that take over DMA the bootloader left running. Cache allocation - is enabled only once each of them is bound to its driver. + is enabled only once each of them is bound to its driver. A supplier + that an enabled simple-framebuffer names as its display is scanning out + that boot framebuffer, enabled or not, and is waited for until a + displayed swap of its own has replaced it. required: - compatible diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml index 25228d7c80251c..d83c4e312f20e2 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml @@ -19,16 +19,18 @@ description: | properties: compatible: enum: + - apple,t8103-sleep + - apple,t8122-sleep - apple,t8132-sleep - apple,t8140-sleep - apple,t8142-sleep reg: - minItems: 25 + minItems: 7 maxItems: 41 reg-names: - minItems: 25 + minItems: 7 maxItems: 41 apple,wake-enable: @@ -105,6 +107,63 @@ required: - apple,display-coprocessors allOf: + - if: + properties: + compatible: + contains: + const: apple,t8103-sleep + then: + required: + - apple,wake-enable + - apple,pinctrl + properties: + reg: + minItems: 7 + maxItems: 7 + reg-names: + items: + - const: ps + - const: ps-aon + - const: clk-mux + - const: wake + - const: cpu-start + - const: wdt + - const: spmi + - if: + properties: + compatible: + contains: + const: apple,t8122-sleep + then: + required: + - apple,wake-enable + properties: + reg: + minItems: 21 + maxItems: 21 + reg-names: + items: + - const: ps + - const: pwrgate + - const: cpu-start + - const: cllt + - const: cluster + - const: commit + - const: wdt + - const: spmi + - const: spmi-hpm + - const: wake + - const: ps-aon + - const: mcc-a + - const: mcc-b + - const: mcc-c + - const: mcc-d + - const: apcie-axi + - const: apcie-rc + - const: apcie-clkgen + - const: apcie-phy + - const: apcie-phy-ip + - const: apcie-port0 - if: properties: compatible: diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t8152-aop.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t8152-aop.yaml index 624e29d66f2cf3..bf23db0f389207 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,t8152-aop.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,t8152-aop.yaml @@ -12,9 +12,9 @@ maintainers: description: The Always-On Processor on T8142, T8152 and T6050 runs firmware that the boot loader loads and leaves halted. It owns the audio and sensor services. - The host boots it over its RTKit mailbox, on T8142 together with a - separate setup-port mailbox, and shares buffers through one stream of the - AOP DART. + The host boots it over its RTKit mailbox, using a separate setup-port + mailbox when the firmware's boot protocol requires it, and shares buffers + through one stream of the AOP DART. properties: compatible: @@ -43,6 +43,9 @@ properties: - description: Firmware setup-port transport mbox-names: + description: + Include setup when the firmware uses the setup-port boot protocol. + Omitting setup selects boot over the primary RTKit mailbox alone. minItems: 1 items: - const: mbox diff --git a/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml b/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml index 5a501c66df7675..2247c81c9eb60b 100644 --- a/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml +++ b/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml @@ -14,23 +14,43 @@ description: | calibration handoff determine its availability. It has no independent application-processor register window or interrupt. +# Match on the first compatible only: T6041 and T8132 also list +# apple,t6030-aop-audio as a fallback and are validated by +# apple,t6041-aop-audio.yaml. select: properties: compatible: - contains: - enum: - - apple,t6020-aop-audio - - apple,t8112-aop-audio + minItems: 1 + maxItems: 2 + items: + - enum: + - apple,t6000-aop-audio + - apple,t6020-aop-audio + - apple,t6030-aop-audio + - apple,t6031-aop-audio + - apple,t8103-aop-audio + - apple,t8112-aop-audio + - apple,t8122-aop-audio + additionalItems: true required: - compatible properties: compatible: - items: - - enum: - - apple,t6020-aop-audio - - apple,t8112-aop-audio - - const: apple,aop-audio + oneOf: + - items: + - enum: + - apple,t6000-aop-audio + - apple,t6020-aop-audio + - apple,t8103-aop-audio + - apple,t8112-aop-audio + - const: apple,aop-audio + - const: apple,t6030-aop-audio + - items: + - enum: + - apple,t6031-aop-audio + - apple,t8122-aop-audio + - const: apple,t6030-aop-audio dmas: maxItems: 1 @@ -46,6 +66,10 @@ properties: $ref: /schemas/types.yaml#/definitions/string description: Machine family used for the sound card identity. + apple,no-beamforming: + type: boolean + description: Disable microphone array beamforming on boards without it. + required: - compatible - dmas diff --git a/Documentation/devicetree/bindings/sound/apple,dpaudio.yaml b/Documentation/devicetree/bindings/sound/apple,dpaudio.yaml index a531eb26061286..0cbbf78a0d6b8f 100644 --- a/Documentation/devicetree/bindings/sound/apple,dpaudio.yaml +++ b/Documentation/devicetree/bindings/sound/apple,dpaudio.yaml @@ -72,21 +72,27 @@ additionalProperties: false examples: - | - audio-controller { - compatible = "apple,t8112-dpaudio", "apple,dpaudio"; - dmas = <&sio 0x66>; - dma-names = "tx"; - power-domains = <&ps_dpa1>; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - - endpoint { - remote-endpoint = <&dcpext_audio>; + soc { + #address-cells = <2>; + #size-cells = <2>; + + audio-controller@238334000 { + compatible = "apple,t8112-dpaudio", "apple,dpaudio"; + reg = <0x2 0x38334000 0x0 0x4000>; + dmas = <&sio 0x66>; + dma-names = "tx"; + power-domains = <&ps_dpa1>; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + endpoint { + remote-endpoint = <&dcpext_audio>; + }; }; }; }; diff --git a/Documentation/devicetree/bindings/sound/apple,macaudio.yaml b/Documentation/devicetree/bindings/sound/apple,macaudio.yaml index c9880a39e9b29c..6273f23b03c5f0 100644 --- a/Documentation/devicetree/bindings/sound/apple,macaudio.yaml +++ b/Documentation/devicetree/bindings/sound/apple,macaudio.yaml @@ -46,6 +46,7 @@ properties: - apple,j623-macaudio-jack - apple,j624-macaudio-jack - apple,j700-macaudio + - apple,j704-macaudio - apple,j713-macaudio - apple,j713-macaudio-jack - apple,j714-macaudio @@ -56,6 +57,7 @@ properties: - apple,j813-macaudio - apple,j815-macaudio - apple,j873-macaudio + - apple,k114-macaudio - apple,k116-macaudio - const: apple,macaudio - description: diff --git a/Documentation/devicetree/bindings/sound/apple,t8152-aop-audio.yaml b/Documentation/devicetree/bindings/sound/apple,t8152-aop-audio.yaml index 9c14c3fff2e413..b23e734de92061 100644 --- a/Documentation/devicetree/bindings/sound/apple,t8152-aop-audio.yaml +++ b/Documentation/devicetree/bindings/sound/apple,t8152-aop-audio.yaml @@ -26,6 +26,7 @@ properties: - const: apple,t8142-aop-audio - const: apple,t8152-aop-audio - const: apple,t6050-aop-audio + - const: apple,t8152-aop-audio dmas: minItems: 4 diff --git a/Documentation/devicetree/bindings/spmi/apple,spmi.yaml b/Documentation/devicetree/bindings/spmi/apple,spmi.yaml index 48706095da208b..9f00cf99cf3bb8 100644 --- a/Documentation/devicetree/bindings/spmi/apple,spmi.yaml +++ b/Documentation/devicetree/bindings/spmi/apple,spmi.yaml @@ -13,6 +13,14 @@ description: A SPMI controller present on most Apple SoCs allOf: - $ref: spmi.yaml# + - if: + properties: + compatible: + contains: + const: apple,t8142-spmi + then: + properties: + apple,response-vector: false properties: compatible: @@ -41,6 +49,11 @@ properties: - apple,t8132-spmi - apple,t8140-spmi - const: apple,t8103-spmi + - description: + The gen-4 controller of T8152, with its FIFO registers at 0x200. + items: + - const: apple,t8152-spmi + - const: apple,t8142-spmi reg: minItems: 1 @@ -63,6 +76,19 @@ properties: "#interrupt-cells": const: 2 + apple,response-vector: + $ref: /schemas/types.yaml#/definitions/uint32 + minimum: 64 + maximum: 256 + multipleOf: 64 + description: + Controller vector index for the RX FIFO command-response notification on + gen-1 controllers. Peripheral interrupts occupy vectors 0 through N-1, so + this also gives the peripheral interrupt count. When omitted, the driver + uses the compatible's default (192 for T6000, 256 for other gen-1 + controllers). Not applicable to generation 4 controllers + ("apple,t8142-spmi"). + power-domains: maxItems: 1 diff --git a/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml b/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml index 01592811223d23..70a883b4696fe7 100644 --- a/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml +++ b/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml @@ -30,6 +30,7 @@ properties: oneOf: - const: apple,t8103-usb4-acio - const: apple,t8142-usb4-acio + - const: apple,t8152-usb4-acio - const: apple,t6040-usb4-acio - const: apple,t6050-usb4-acio - items: @@ -52,8 +53,8 @@ properties: PCIe adapter configuration space of the USB4 router. Present where the root complex exposes the adapter separately, so that the tunnel can be configured before a PCIe-C link is brought up. - - description: MxWrap co-processor control registers, on T8132 and T6050 - - description: PCIe router AP firmware registers, on T6050 + - description: MxWrap co-processor control registers, on T8132, T8142 and T6050 + - description: PCIe router AP firmware registers, on T8142 and T6050 reg-names: oneOf: @@ -69,6 +70,14 @@ properties: - const: rc - const: sram - const: cpu + - description: + T8152, whose router CPU is started by a reconfiguration request + through its mailbox and has no window of its own + items: + - const: rc + - const: sram + - const: pcie-adapter + - const: router-ap-fw mboxes: maxItems: 1 @@ -185,8 +194,12 @@ properties: const: 1 ranges: - maxItems: 1 - description: Single 16 MiB MMIO window containing all child registers + minItems: 1 + maxItems: 2 + description: + 16 MiB MMIO window containing the child registers. On T8152 a second + range maps the shared Gen3 DART TLB invalidation aperture for the + router's DART. nonposted-mmio: true @@ -253,12 +266,24 @@ allOf: enum: - apple,t6040-usb4-acio - apple,t8132-usb4-acio + - apple,t8142-usb4-acio + - apple,t8152-usb4-acio then: properties: reg: minItems: 4 reg-names: minItems: 4 + - if: + properties: + compatible: + not: + contains: + const: apple,t8152-usb4-acio + then: + properties: + ranges: + maxItems: 1 - if: properties: compatible: @@ -267,6 +292,8 @@ allOf: - apple,t6040-usb4-acio - apple,t6050-usb4-acio - apple,t8132-usb4-acio + - apple,t8142-usb4-acio + - apple,t8152-usb4-acio then: properties: pinctrl-names: @@ -309,7 +336,29 @@ allOf: properties: power-domains: maxItems: 4 + - if: + properties: + compatible: + not: + contains: + enum: + - apple,t6050-usb4-acio + - apple,t8142-usb4-acio + - apple,t8152-usb4-acio + then: + properties: apple,tunable-router-ap-fw: false + - if: + properties: + compatible: + contains: + const: apple,t8142-usb4-acio + then: + properties: + reg: + minItems: 5 + reg-names: + minItems: 5 additionalProperties: false diff --git a/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-nhi.yaml b/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-nhi.yaml index 28718fed167c5d..c68f883b10d0f9 100644 --- a/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-nhi.yaml +++ b/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-nhi.yaml @@ -22,6 +22,7 @@ properties: oneOf: - const: apple,t8103-usb4-nhi - const: apple,t8142-usb4-nhi + - const: apple,t8152-usb4-nhi - const: apple,t6040-usb4-nhi - const: apple,t6050-usb4-nhi - items: @@ -131,6 +132,7 @@ allOf: contains: enum: - apple,t8142-usb4-nhi + - apple,t8152-usb4-nhi - apple,t6040-usb4-nhi - apple,t6050-usb4-nhi then: @@ -155,6 +157,7 @@ allOf: - apple,t8122-usb4-nhi - apple,t8132-usb4-nhi - apple,t8142-usb4-nhi + - apple,t8152-usb4-nhi - apple,t6040-usb4-nhi - apple,t6050-usb4-nhi then: diff --git a/Documentation/devicetree/bindings/usb/apple,dwc3.yaml b/Documentation/devicetree/bindings/usb/apple,dwc3.yaml index 6612a5370ee36e..6bc0c202dceeca 100644 --- a/Documentation/devicetree/bindings/usb/apple,dwc3.yaml +++ b/Documentation/devicetree/bindings/usb/apple,dwc3.yaml @@ -13,6 +13,12 @@ description: Apple Silicon SoCs use a Synopsys DesignWare DWC3 based controller for each of their Type-C ports. + On T8152 the bootloader can hand a controller over already running, powered + and with the USB2 side of its ATC PHY set up for host mode. Such a controller + is described by its DWC3 core region, as a host. Its PHY reset and power + domain, and on a Type-C port its USB role switch, exist but are left to the + bootloader, so they are optional. + allOf: - $ref: snps,dwc3-common.yaml# - if: @@ -20,11 +26,37 @@ allOf: compatible: not: contains: - const: apple,t8132-dwc3 + enum: + - apple,t8132-dwc3 + - apple,t8152-dwc3 then: required: - power-domains - if: + properties: + compatible: + contains: + const: apple,t8152-dwc3 + then: + properties: + dr_mode: + const: host + required: + - dr_mode + else: + properties: + reg: + minItems: 2 + reg-names: + minItems: 2 + required: + - reg-names + - if: + properties: + compatible: + not: + contains: + const: apple,t8152-dwc3 not: properties: status: @@ -85,9 +117,10 @@ properties: - const: apple,t8103-dwc3 - const: apple,t8103-dwc3 - const: apple,t8132-dwc3 + - const: apple,t8152-dwc3 reg: - minItems: 2 + minItems: 1 items: - description: Core DWC3 region - description: Apple-specific DWC3 region @@ -96,7 +129,7 @@ properties: - description: AUSBC debug block (T6050) reg-names: - minItems: 2 + minItems: 1 items: - const: dwc3-core - const: dwc3-apple @@ -160,7 +193,6 @@ properties: required: - compatible - reg - - reg-names - interrupts - iommus @@ -183,3 +215,18 @@ examples: usb-role-switch; }; + + - | + #include + #include + + usb@82430000 { + compatible = "apple,t8152-dwc3"; + reg = <0x82430000 0xcd00>; + interrupts = ; + iommus = <&dwc3_2_dart_0 0>, <&dwc3_2_dart_1 1>; + dr_mode = "host"; + maximum-speed = "high-speed"; + snps,dis_u2_susphy_quirk; + snps,dis_u3_susphy_quirk; + }; diff --git a/Documentation/devicetree/bindings/usb/apple,sn201202x.yaml b/Documentation/devicetree/bindings/usb/apple,sn201202x.yaml index cc82767a25a517..84ae1f7bf08801 100644 --- a/Documentation/devicetree/bindings/usb/apple,sn201202x.yaml +++ b/Documentation/devicetree/bindings/usb/apple,sn201202x.yaml @@ -18,7 +18,9 @@ description: | The controller can be polled when interrupt resources are not supplied. T8132 omits the register-selection interrupt, so selection is polled while - event, standby and wakeup notifications use interrupts. + event, standby and wakeup notifications use interrupts. The T8152 + controllers work as the T8132 ones do: no register-selection interrupt, and + the payload length of a selected register in register 0x1f. properties: compatible: @@ -27,6 +29,10 @@ properties: - items: - const: apple,t8132-sn201202x - const: apple,sn201202x + - items: + - const: apple,t8152-sn201202x + - const: apple,t8132-sn201202x + - const: apple,sn201202x reg: maxItems: 1 diff --git a/Documentation/devicetree/bindings/usb/ti,tps6598x.yaml b/Documentation/devicetree/bindings/usb/ti,tps6598x.yaml index 2c589e9e712ebd..08ecfa211ad651 100644 --- a/Documentation/devicetree/bindings/usb/ti,tps6598x.yaml +++ b/Documentation/devicetree/bindings/usb/ti,tps6598x.yaml @@ -56,6 +56,12 @@ properties: connector: $ref: /schemas/connector/usb-connector.yaml# + apple,sleep-ssps: + type: boolean + description: + Tell the controller the system's power state (SSPS) around a + firmware-driven suspend, S3 before it and S0 after. + firmware-name: description: | Should contain the name of the default patch binary @@ -91,6 +97,15 @@ allOf: properties: reg: maxItems: 1 + - if: + properties: + compatible: + not: + contains: + const: apple,cd321x + then: + properties: + apple,sleep-ssps: false additionalProperties: false diff --git a/Documentation/devicetree/bindings/vendor-prefixes.yaml b/Documentation/devicetree/bindings/vendor-prefixes.yaml index 4775b267e1f771..7e8a847ea70ab6 100644 --- a/Documentation/devicetree/bindings/vendor-prefixes.yaml +++ b/Documentation/devicetree/bindings/vendor-prefixes.yaml @@ -983,6 +983,8 @@ patternProperties: description: Linutronix GmbH "^linux,.*": description: Linux-specific binding + "^linux-enablement-mac,.*": + description: Aurora Silicon Apple silicon loader hand-off bindings "^linx,.*": description: Linx Technologies "^liontron,.*": diff --git a/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml b/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml index e321ee28733d19..f65a37d504791a 100644 --- a/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml +++ b/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml @@ -11,6 +11,15 @@ maintainers: allOf: - $ref: watchdog.yaml# + - if: + properties: + reg: + minItems: 2 + required: + - reg + then: + required: + - reg-names properties: compatible: @@ -26,6 +35,7 @@ properties: - apple,t8132-wdt - apple,t8140-wdt - apple,t8142-wdt + - apple,t8152-wdt - const: apple,t8103-wdt - items: - enum: @@ -41,7 +51,16 @@ properties: - const: apple,wdt reg: - maxItems: 1 + minItems: 1 + items: + - description: Watchdog timer registers + - description: Simple-reconfig routing register + + reg-names: + minItems: 1 + items: + - const: wdt + - const: reconfig clocks: maxItems: 1 @@ -68,5 +87,17 @@ examples: clocks = <&clk>; interrupts = ; }; + - | + #include + #include + + watchdog@8836c000 { + compatible = "apple,t6050-wdt", "apple,t8103-wdt"; + reg = <0x8836c000 0x4000>, + <0x8833002c 0x4>; + reg-names = "wdt", "reconfig"; + clocks = <&clk>; + interrupts = ; + }; ... diff --git a/Documentation/gpu/asahi-usage-stats.rst b/Documentation/gpu/asahi-usage-stats.rst index c2cda44ce1e459..7905e9e6b50623 100644 --- a/Documentation/gpu/asahi-usage-stats.rst +++ b/Documentation/gpu/asahi-usage-stats.rst @@ -48,10 +48,13 @@ start and end operations. The shared G17 backend runs several commands of one queue at once, so their stages overlap. It charges each engine of a queue the union of that queue's stage intervals (exact, because a queue's stages retire in the order they started), so a queue never counts more than the wall time on one -engine. Queues of one file still add up. The other backends sum their intervals -without merging overlapping commands on the same engine. Missing, zero-start or -reversed intervals are ignored. Failed or cancelled commands do not contribute -incomplete intervals; +engine. Queues of one file still add up on G17. Native G16 executes pipelined +commands and dual-pipe compute across sibling queues of one DRM file, so it +unions overlapping stage intervals per file (``Client::add_union``) to keep each +engine bounded by wall time. The other backends sum their intervals without +merging overlapping commands on the same engine. Missing, zero-start or reversed +intervals are ignored. Failed or cancelled commands do not contribute incomplete +intervals; successful stages that retired before a later failure remain counted. An unexecuted G17 replay contributes only when it eventually retires successfully. There is no submit-to-completion wall-time fallback in the current backends. @@ -62,7 +65,8 @@ cycles, or multiplying time by a sampled/maximum GPU frequency, would give incorrect frequency-weighted utilization. Per-client execution-cycle counters would require a separate hardware measurement source. -On the M5 and the A18 Pro each engine also has the frequency keys:: +On the M5, the A18 Pro and T6041 (M4 Max, 25G83) each engine also has +the frequency keys:: drm-curfreq-compute: 1620000000 Hz drm-maxfreq-compute: 1620000000 Hz @@ -88,9 +92,10 @@ The native backends reuse existing timestamp reads. Classic completion callbacks read two internal cells per stage; commands without application timestamps also execute two existing timestamp microsequence operations per stage. Reading fdinfo loads three counters -and does not traverse queues, wait for fences or access hardware. On the M5 and -the A18 Pro a read also takes the device mutex once and drains the statistics -rings, as a read of ``agx_stats`` does, for the frequency keys. +and does not traverse queues, wait for fences or access hardware. On the M5, +the A18 Pro and T6041 (25G83) a read also takes the device mutex once +and drains the statistics rings, as a read of ``agx_stats`` does, for the +frequency keys. G16S and G17P device utilisation ------------------------------ @@ -133,33 +138,44 @@ ring on powered cores becomes stale rather than fabricating a zero-utilisation sample; only gated cores read as zero. Readers must not convert these percentages into engine nanoseconds or cycles. -Performance state and busy time on V26A428 (A18 Pro and M5) ------------------------------------------------------------ +Performance state and busy time on V26A428 (A18 Pro and M5) and T6041 +--------------------------------------------------------------------- -The V26A428 firmware, which the A18 Pro (T8140, G17P) and the M5 run on the same -backend and decoder, carries more in its statistics ring. ``agx_stats`` reports -there: +The V26A428 firmware (A18 Pro T8140 and M5) and T6041's 25G83 firmware +run on the same backend and decoder and carry more in their statistics ring. +``agx_stats`` reports there: * ``pstate``: the performance state in effect, from the firmware's state reports (tag ``0x1b``, words 1 and 3, which must agree). It is an index into - the performance state table: 1 to 10 on the A18 Pro, 1 to 13 on the M5. The - interval record before a report (tag ``0x19``) gives its firmware timestamp. + the performance state table: 1 to 10 on the A18 Pro and T6041, 1 to 13 on + the M5. The interval record before a report (tag ``0x19``) gives its + firmware timestamp. A report that names state 0 or a state beyond the table is not used. While the cores are gated the GPU is off and ``pstate`` reads a valid 0; power-up starts a new epoch, ``stale`` until the next report. * ``achieved_frequency_hz``: the frequency of that state while ``pstate_status`` is ``valid``, 0 for state 0. The M5 takes it from its - board's table. The A18 Pro takes the device tree operating point that the - state's entry of its performance table A names: its records do not name the - table, but at its top state a sustained FP32 FMA load completes faster than - table B's frequency there allows. + board's table. The A18 Pro and T6041 take the device tree operating point + that the state's entry of their performance table A names: their records do + not name the table; on the A18 Pro, at the top state a sustained FP32 FMA + load completes faster than table B's frequency there allows, while on T6041 + both tables map state 10 to OPP 15 (1578 MHz) and only differ on mid-states + (states 5..9 on 32-core J616C, 6..9 on 40-core), so those mid-state + frequencies are nominal (taken from table A) until measured by a mid-state + ALU benchmark. * ``busy_ns``: the utilisation records carry their own timestamps (words 1 and - 2, 24 MHz ticks), one every 8 ms on the M5 and every 16 ms on the A18 Pro, so - each record closes a window of known length, which is credited at the - record's device utilisation. A record that follows the previous one by more - than two periods, or whose timestamp went back, only starts a new window: - time the GPU spent gated is never credited, and a load sparser than one - period reads low. The total keeps counting across power epochs. + 2, 24 MHz ticks), one every 8 ms on the M5 and T6041 and every 16 ms on the + A18 Pro, so each record closes a window of known length, which is credited at the + record's device utilisation. Records are credited in timestamp order, from + both roles and across power epochs: the driver keeps the timestamp up to + which it has counted, and a record at or before it adds nothing. A record + within two periods of that mark closes the window since it; after a longer + gap it closes only its own period, so time the GPU spent gated is never + credited. Under a frame-paced load the cores gate many times a second, often + with one record per power epoch, so the records a power boundary keeps out of + the utilisation average still count here. Suspend, recovery and quarantine + keep them out, and ``busy_ns`` reads ``stale`` once a statistics ring is + quarantined. The driver asks for full performance while work is in flight, which the firmware takes as a floor for its state. An A18 Pro at work therefore normally @@ -174,8 +190,10 @@ fdinfo's per-client ``drm-engine-*`` counters. Deferred shared power telemetry ------------------------------ -Current pstate and requested/achieved frequency remain unsupported on G16S -(V25G83); V26A428 reports its state in the statistics ring, see above. The +Current pstate and requested/achieved frequency remain unsupported on T6040 +(M4 Pro, V25G83), which is left on ``Protocol::NONE`` because it has not been +measured yet; V26A428 and T6041 (25G83) report their state in the statistics +ring, see above. The shared-power snapshot ABI is not sufficiently specified to implement a read-only reader, which G16S would need, and which would also name the A18 Pro's table directly. For **each** of G16S and G17P, it still needs: diff --git a/Documentation/hwmon/macsmc-hwmon.rst b/Documentation/hwmon/macsmc-hwmon.rst index c4df2eef90fbdc..bb0c502514a50d 100644 --- a/Documentation/hwmon/macsmc-hwmon.rst +++ b/Documentation/hwmon/macsmc-hwmon.rst @@ -38,11 +38,28 @@ shutdown and removal release only fans taken over by such a request; resume does not reapply it. A new target write is required after resume. A kernel thermal policy (the M5 GPU governor) sets the fans through -macsmc_hwmon_fans_request(), as a share of each fan's range, on every fan -whose node names its mode, target, minimum and maximum keys, with or without -apple,fan-manual-control. It uses the same manual mode, leaves fans userspace -holds alone, and its fans return to the SMC at suspend, shutdown and removal -like userspace's. +macsmc_hwmon_fans_request() (every fan whose node names its mode, target, +minimum and maximum keys, with or without apple,fan-manual-control) or +macsmc_hwmon_fans_request_manual() (only fans with apple,fan-manual-control), +as a share of each fan's range. Both use the same manual mode, leave fans +userspace holds alone, and return their fans to the SMC at suspend, shutdown +and removal like userspace's. + +When a board's Devicetree also gives ``apple,soc-die-fan-trip-millicelsius``, +``apple,soc-die-fan-hysteresis-millicelsius`` and ``apple,soc-die-fan-hold-ms`` +beside a single key in ``apple,soc-die-keys``, ``macsmc_soc_die`` is registered +with that active trip and ``macsmc_hwmon_hotspot_assist_policy()`` exposes the +thresholds and hold time to hotspot fan assistance. Without those properties +from the Devicetree, hotspot fan assistance stays off. + +When the Devicetree gives ``apple,soc-die-passive-millicelsius`` and +``apple,soc-die-hot-millicelsius``, ``macsmc_soc_die`` also carries a passive +trip and a hot trip at those temperatures. They describe the machine's SoC die +limits for in-kernel power consumers that read the zone's trips (the GPU +thermal backstop sheds performance from the passive trip and holds its lowest +state at the hot one). The hot trip only reports: the zone has no hot callback +and no critical trip, so it never shuts the machine down. Without both +properties the zone carries no passive or hot trip. SoC die temperatures are described by the ``apple,soc-die-keys`` string list on the hwmon device node. The driver appends these temperature channels after diff --git a/Documentation/iio/aop-sensors.rst b/Documentation/iio/aop-sensors.rst index dd00cb84e2709f..3dcdce2da440fd 100644 --- a/Documentation/iio/aop-sensors.rst +++ b/Documentation/iio/aop-sensors.rst @@ -52,8 +52,14 @@ them; the mapping to the machine's axes is not established yet. A raw read before the first sample returns ``ENODATA``. Both devices have a buffer that takes X, Y and Z together, with an optional -timestamp taken when the report arrives. The reports stop when the system -goes to sleep and start again, with the calibration resent, when it wakes. +timestamp taken when the report arrives. Reports stay off while nobody reads +them: enabling the buffer starts them and disabling it stops them, while direct +sysfs reads start them on demand and stop them again once reads go quiet. A +failed direct-read start backs off for the same idle window so polling clients +cannot hammer a failing service. The calibration packets are sent once at probe +and conservatively again after firmware suspend, hibernation or restore, rather +than on every start or s2idle resume. Around system sleep any active stream is +stopped and restored on wake only if a buffer is still enabled. If both devices bind but every raw read returns ``ENODATA``, check the AOP core's ``nCal`` boot argument for the SoC. The T6040 firmware accepts the diff --git a/Documentation/networking/device_drivers/wifi/mt7932-neo.rst b/Documentation/networking/device_drivers/wifi/mt7932-neo.rst index 3fd4a1c81853e3..236b6e1dfeb647 100644 --- a/Documentation/networking/device_drivers/wifi/mt7932-neo.rst +++ b/Documentation/networking/device_drivers/wifi/mt7932-neo.rst @@ -113,7 +113,8 @@ Station security ---------------- The driver advertises PSK, PSK-SHA256, SAE and OWE with CCMP, plus -BIP-CMAC-128 for management protection. Firmware performs SAE +BIP-CMAC-128 for management protection. PSK also accepts a TKIP group key, +described below. Firmware performs SAE authentication and the four-way handshake and owns PTK, GTK and IGTK; there is no host key-install interface or external-auth exchange. @@ -154,6 +155,20 @@ a host PWE field. Exact PWE policy behavior on 2.4 and 5 GHz still needs qualification. SAE-PK, SAE-EXT-KEY and additional ciphers are not advertised. OWE and 6 GHz support are described below. +TKIP is registered so that WPA2-PSK can join a WPA/WPA2 mixed-mode access point, +which pairs a CCMP unicast key with a TKIP group key. Pairwise TKIP, WPA1, and a +TKIP group key with SAE or OWE are refused. Because TKIP is in the cipher list, +a supplicant may offer a TKIP-only or WPA1 network as selectable; the connect +request then fails with ``-EOPNOTSUPP``. Firmware owns the TKIP group key like +any other. MIC failure reporting and TKIP countermeasures are left to firmware and +have not been verified: firmware runs the four-way handshake, so the host has no +KCK and calling ``cfg80211_michael_mic_failure()`` would do nothing. + +J700 hardware testing joined one mixed-mode router on 2.4 and 5 GHz, and stayed +connected to a hostapd access point through 14 group rekeys at 60 second intervals +with ARP and mDNS still received. DHCP renewal, IPv6 router advertisements and a +commercial access point's own rekey still need qualification. + J700 hardware testing with NetworkManager and wpa_supplicant on a PSK+SAE transition network has confirmed, on 2.4 GHz channel 6 and 5 GHz channel 149: diff --git a/Documentation/process/coding-assistants.rst b/Documentation/process/coding-assistants.rst index 051f0d819f68e4..509dbf23a099bd 100644 --- a/Documentation/process/coding-assistants.rst +++ b/Documentation/process/coding-assistants.rst @@ -40,24 +40,6 @@ is responsible for: * Adding their own Signed-off-by tag to certify the DCO * Taking full responsibility for the contribution -Attribution -=========== - -When AI tools contribute to kernel development, proper attribution -helps track the evolving role of AI in the development process. -Contributions should include an Assisted-by tag in the following format:: - - Assisted-by: LLM [TOOL1] [TOOL2] - -* ``[TOOL1] [TOOL2]`` are optional specialized analysis tools used - (e.g., coccinelle, sparse, smatch, clang-tidy) - -Basic development tools (git, gcc, make, editors) should not be listed. - -Example:: - - Assisted-by: LLM coccinelle sparse - Procedure for finding and fixing bugs ===================================== @@ -82,8 +64,7 @@ these steps: another one. The fix must not add build warnings and must pass the checkpatch.pl checks (see submitting-patches.rst). 6. Commit the working fix with a detailed message describing the problem, the - solution and a Fixes tag. Do not add a Signed-off-by tag, and add an - Assisted-by tag, as described above. + solution and a Fixes tag. Do not add a Signed-off-by tag. 7. Identify the maintainers and lists using scripts/get_maintainer.pl. Documentation/process/security-bugs.rst shows how to do that. 8. Indicate what could not be done. If the fix could not be built or tested, or diff --git a/Documentation/process/submitting-patches.rst b/Documentation/process/submitting-patches.rst index 7ae79452e1b46d..5f4e0156cca786 100644 --- a/Documentation/process/submitting-patches.rst +++ b/Documentation/process/submitting-patches.rst @@ -632,16 +632,6 @@ bugzilla.kernel.org is a public place in this sense, but email addresses used there are private; so do not expose them in tags, unless the person used them in earlier contributions. -Using Assisted-by: ------------------- - -If you used any sort of advanced coding tool in the creation of your patch, -you need to acknowledge that use by adding an Assisted-by tag. Failure to -do so may impede the acceptance of your work. Please see -Documentation/process/coding-assistants.rst for details regarding the -acknowledgment of coding assistants. - - .. _the_canonical_patch_format: The canonical patch format diff --git a/Documentation/translations/it_IT/process/submitting-patches.rst b/Documentation/translations/it_IT/process/submitting-patches.rst index a742610cb0709f..d0e0d6c9ecc2e5 100644 --- a/Documentation/translations/it_IT/process/submitting-patches.rst +++ b/Documentation/translations/it_IT/process/submitting-patches.rst @@ -691,16 +691,6 @@ un luogo pubblico, ma gli indirizzi email usati lì sono privati; quindi non esponeteli nelle etichette, a meno che la persona non li abbia già usati in contributi precedenti. -Usare Assisted-by: -------------------- - -Se avete usato un qualsiasi tipo di strumento di assistenza avanzata alla -scrittura del codice per la creazione della vostra patch, dovete darne atto -aggiungendo un'etichetta Assisted-by. Non farlo può ostacolare -l'accettazione del vostro lavoro. Fate riferimento a -Documentation/process/coding-assistants.rst per i dettagli su come dare -atto dell'uso di assistenti alla scrittura del codice. - .. _it_the_canonical_patch_format: Il formato canonico delle patch diff --git a/GAPS.md b/GAPS.md deleted file mode 100644 index c8d2c7c753261c..00000000000000 --- a/GAPS.md +++ /dev/null @@ -1,1302 +0,0 @@ -# T6040 GPU parity audit - -Audit baseline: `integration/aurora` at -`9cbdd0734d9e`, with GPU integration #463 (`a0a9485847f8`), the -r5 display series (`905dff774561`), camera #462 (`2114ed0c6245`), and the -two r6 display patches. The reconstructed r6 branch is -`wip/j616s-display-r6` at `af0a664046fb`. - -This series repairs regression coverage and a shared KUNIT=m WERROR build defect, -ports GPU-driven memory/fabric demand and PMP voter cooperation using -T6040 data, honors the existing DT idle-delay policy, and closes a compute -release-witness gap across recovery. GPU voltages, firmware features and the submission algorithm remain -unchanged from the reconstructed base. The major -T6040 calibration and image-admission changes requested by this audit are -already in the baseline. Software parity does not establish all-workload benchmark or CTS -parity. The operator has selected g3 as the measured J616s baseline; g4 -retains it and adds the qualified shared ports and diagnostics below. - -## Gap table - -| Gap | Neo behavior | T6040 before this series | After this series | Evidence / remaining gate | -| --- | --- | --- | --- | --- | -| Per-chip leakage and power ceiling | T8140 has its own platform data | #463 requires a versioned DT handoff, finite positive leakage, a power ceiling and the measured core mask; no single-unit fallback | Same runtime behavior | `g17/calibration.rs`, `g17/initdata/v25g83.rs`; #463 commits `a8fb1380b414`, `53877eaebd4b`, `415fd2e6ee2d` | -| Raw OPP count versus logical states | Firmware consumes 11 logical states | 16 raw GPU OPPs; 11 selectors in each A/B map; both end at raw OPP 15; unused handoff slots must be zero | KUnit now uses valid complete maps and checks the final state's second voltage lane | `g17/calibration.rs`; a count of 15 in an ADT property is not evidence for expanding this firmware layout | -| Full clock eligibility | Platform OPPs feed firmware performance tables | DT supplies both cluster voltages and GPU/CS/AFR frequencies; maps and relative-B are checked against the GPU OPP table | Same runtime behavior | `g17/initdata/v25g83.rs`, `g17/fw/initdata/v25g83.rs`; confirm sustained clocks and limiting reasons on hardware | -| DVFS ramp / effort | Full effort on publication, cleared after 16 ms of continuous idle | Same `Firmware::note_submission`, direct-port accounting and race-checked idle clear | Same runtime behavior | `g17/mod.rs`, `g17/port.rs`, `g17/power.rs`; opaque firmware power words are not a documented ramp control | -| GPU-driven fabric/memory floor | #440 uses an activity-following graphics PMGR input | T6040 CPU-only demand; g3 port sampled the firmware-lifetime GFX supplier | g4 uses DT-selected publication/continuous-idle demand, preserving DCS 5/fabric 2 and 32 ms CLPC hold | `clpc.c`, `g17/power.rs`, `g17/port.rs`, T6040 DT; blank-panel release and bandwidth retention require hardware qualification | -| PMP PMC vote cooperation | PMP/CLPC/AP agents enabled | T6040 static voters omit PMP 0 from pre-working-PMP bring-up | Port 772a9d3104ff adds the existing PMP supplier dependency and voter 0 on T6040 DCS/SOC rails | pmc.c and T6040 DT; live votes, idle release and thermal qualification required | -| Idle / off policy | Shared host hold and firmware device-control path | Same host implementation; source documents a 25G83 effective 2 ms off delay and approximately 1 ms wake cost | J616s requests a bounded 16 ms host hold through existing `apple,idle-off-delay-ms`; absent policy retains 2 ms | `g17/power.rs`, `g17/mod.rs`, J616s DT and binding; compare short/long gaps, depth-one latency and idle power | -| Fast-die / PMP | Platform-specific firmware power graph | 25G83 AON table and separate power-state target/release (101/96 C) are already populated; DT enables the GFX suppliers | Same runtime behavior | `g17/fw/initdata/v25g83.rs::POWER_STATE_WORDS`, `g17/initdata/v25g83.rs`, J616s DT; verify clocks with PMP running | -| Periodic preemption | Context-switch timer mask is zero | Same zero mask; two-cluster operand-state allocation differs by hardware layout | Same runtime behavior | `g17/fw/initdata.rs::CONTEXT_SWITCH_TIMER_MASK`, `g17/fw/compute.rs::OperandState`; no evidence supports changing the mask | -| High-priority queues | HIGH / MEDIUM / LOW firmware scheduling profiles | Same scheduling-policy selector and priority work rings | Same runtime behavior | `g17/mod.rs::scheduling_policy`, `g17/fw/channels.rs`, `g17/qos.rs` | -| Timestamp publication | Retains one CPU mapping for each firmware timestamp buffer | Same shared timestamp buffer and completion publication | Host timestamp suite again compiles and executes the production retained-mapping writer | `timestamp.rs`, `mmu.rs::TimestampVmap`, `tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py` | -| Statistics | Drains firmware statistics; no decoded `agx_stats` snapshot | Same; payloads discarded | g4 preserves full per-type/per-role raw snapshots and static-key report tracing | `g17/reports.rs`, `g17/channel.rs`, `g17/trace.*`; achieved-frequency/power decoding remains gated on firmware semantics | -| Firmware startup / registration | Two instances, message acknowledgement, POWER_ON_DONE and MMIO render-pair registration; no lead commands | One merged 25G83 graph, status acknowledgement, no POWER_ON_DONE, no MMIO pair registration; lead commands required | Same runtime behavior | `g17/fw/variant.rs`, `g17/initdata/v25g83.rs`; startup differences are ABI requirements, while MMIO pair registration on 25G83 remains unqualified | -| Queue pointer / restart layout | Producer at +0x40, recovery target at +0x50 | Producer at +0x50, no recovery-target word | Same runtime behavior | `g17/fw/variant.rs::PointerLayout`, `g17/fw/queue.rs`; do not copy another firmware build's offsets | -| Core topology / mapping ownership | One six-core cluster; two firmware roots and fabric bridge | Qualified two-cluster, 20-core layout; reserved firmware tables, one root and no fabric bridge | Same runtime behavior | `hw/t6040.rs`, `hw/t8140.rs`, `g17/mod.rs`; other fused core counts are still refused, and this audit does not expand that admission | -| Alternate loaded image | T8140 uses fixed firmware selection | Both exact T6040 normalized TEXT digests are admitted in one `Build.images` slice | Same runtime behavior | #453 (`26f5eb68dbce`), #463 (`804bba86ca55`), `hw/t6040.rs`, `g17/fw/variant.rs`, `fwid.rs`; unknown images remain refused | -| Submission/completion improvements | #423 shared G17 runtime | #423 is already an ancestor of the baseline; direct compute/render publication, admission domains and completion collection are shared | Same runtime behavior | #423; `g17/runtime.rs`, `g17/runtime/render/direct.rs`, `g17/port.rs`, `g17/completion.rs` | -| G13/G14 `submit.empty` regressions | Neo uses the G17 runtime | G16S uses that same G17 runtime, not the maintained G13/G14 workqueue | Same runtime behavior | `driver.rs`, `file.rs`, `g17/queue/mod.rs`; user-space empty submits may never reach this ioctl; trace and benchmark the paired Mesa stack | -| G13/G14 idle wake regressions | Firmware-specific cost plus shared host overhead | G16S shares common ioctl/GEM/sync infrastructure, but has different firmware, power handling and queue backend | Same runtime behavior | `driver.rs`, `g17/power.rs`; G13/G14 benchmark ratios cannot be transferred to G16S | -| QID capacity | Firmware floor 0; reserve protects dedicated render pairs | 25G83 reserves QIDs 0..31; public queue limit is reduced accordingly | KUnit checks floor 32 in dynamic growth and full logical queue budget tests; host resource runner follows current reserve helper | `g17/kick.rs`, `g17/runtime.rs`, `tools/asahi/g17-resource-tests.py` | -| KUnit / WERROR config matrix | Shared test modules require KUNIT=y | Four G17 test helpers used the broader CONFIG_KUNIT guard and failed WERROR with the shipping KUNIT=m config | Helpers now use CONFIG_KUNIT = "y", matching the Rust macro; config and warning policy unchanged | `rust/macros/kunit.rs`, `g17/kick.rs`, `g17/preparation.rs`, `g17/queue/admission.rs`, `g17/runtime.rs`; verify both KUNIT=m release and KUNIT=y QEMU builds | -| Compute ownership / retained mappings | Recovery and retirement witnesses protect mapping lifetime | Same production queue ownership, source loans, growth rollback and deferred release | Aged-record fallback now requires the original recovery generation; source loans and host negative controls remain | `tools/asahi/g17-capacity-fault-tests.py`, constructor/growth/pool/release-order fixtures | -| Restart and fault classification | Shared recovery handshake plus validated T8140 per-slot keys | Shared handshake uses 25G83 status offsets; `recovery_slot_keys=None` preserves firmware blame when keys are unknown | Bounded generation/slot/progress diagnostics retain unknown ownership; any missing selected key preserves firmware blame | `hw/t6040.rs`, `g17/initdata.rs`, `g17/recovery/attribution.rs`; successful 25G83 fault/restart qualification is still required | -| DART / UAT | Shared mapping ownership and checked page-table borrowing | Shared MMU, with T6040 reserved tables, PoC cleaning, per-page TLBI and native GPU permission quirks | Same runtime behavior | `hw/t6040.rs`, `mmu.rs`, `pgtable.rs`; do not remove coherency or handoff requirements for a benchmark | -| Memory accounting | Creator-attributed committed/resident GEM accounting and capacity admission | Same `memacct::Client`, `File::memory_stats` and shared capacity machinery | Same runtime behavior | `file.rs`, `gem.rs`, `memacct.rs`, `g17/capacity.rs`; verify multi-client high-water and post-close behavior on hardware | -| MCache / few-primitives / ray traversal | Enabled by the 26A428 variant | Disabled by 25G83 variant; source records hangs for few-primitives and stalled ray traversal, while MCache is unqualified | Same runtime behavior | `g17/fw/variant.rs::V25G83`; enabling these requires independent ABI evidence and hardware tests | -| M5 Pro comparison | No M5 Pro hardware configuration exists in this public baseline | No T605x/G17S KMD path to compare | No claim of M5 parity | Pinned public tree contains T6040 and T8140; a licensed public M5 Pro reference is required | -| CTS and Linux/macOS performance ratio | Hardware results belong to their exact kernel/Mesa pair | No result for this candidate | Pending hardware agent | Run gpubench with matching suite, configuration and conditions; review CTS failures and kernel faults before claiming parity | - -## GPU memory demand and interactive latency - -The GFX PMP report entry and PMC performance votes are separate mechanisms. -The existing T6040 `pmp_gfx` soc-device 13 entry follows the powered GPU domain; -`apple_pmp_report_set_state()` publishes a power-state request bit and waits -for its acknowledgement. It does not encode a DCS/fabric performance request. -The GPU firmware owns the PMP's performance demand. Before this series, PMC's -static voter list omitted PMP agent 0, and CLPC lacked a GPU power-state input. -The two existing ports enable PMP agent 0 on T6040's DCS/SOC rails and make -CLPC request the already qualified DCS 5 / fabric 2 floor. G3 incorrectly -used the T6040 supplier lifetime as activity. G4 replaces that input with -DT-selected publication/continuous-idle demand and preserves the existing -32 ms memory-floor release. Prove live -request, enabled-agent and actual-state agreement; supplier binding alone -is not proof of an honoured vote. - -For dispatch latency, G17 now reads the existing `apple,idle-off-delay-ms` DT -policy, validates the existing 2..1000 ms bounds, and starts the existing host -hold with that policy. J616s selects 16 ms, matching the existing effort-idle -interval; other boards without the property retain the native 2 ms behavior. -This avoids power-off across short interactive gaps and releases after real -idle, without changing firmware layout or adding a parameter/platform flag. -KUnit covers absent/valid/invalid policy and repeated depth-one gaps followed -by idle release. A shorter software delay is not itself a measured latency -win: compare actual power transitions, firmware execution, IRQ/retirement and -fence wakeup boundaries. Keep empty CPU fence transfers separate from GPU -round trips and require low-duty/long-idle power acceptance. - -## Remaining 25G83 facts and recovery qualification - -No firmware capability is inferred from another GPU's successful CTS result. -The following are the exact T6040/25G83 facts needed to open the remaining -paths. A reference capture of achieved frequency establishes a target, not -an offset, voltage, descriptor ABI, or Linux residency measurement. - -| Gated path | Exact facts needed for T6040/25G83 | Current evidence and disposition | -| --- | --- | --- | -| Sustained top clock | DT OPP count, both voltage lanes, hardware A/B selector maps, selected logical-state limit; independently decoded achieved frequency or residency, counter units/timebase/wrap, request versus achieved-state semantics and limiting reason under sustained load | Per-chip DT handoff and maps are already mandatory; both maps select the final raw OPP. `max_frequency_khz` is an advertised maximum, not achieved telemetry. G17 `stats_snapshot()` returns None; g4 raw `firmware_reports` and `asahi_g17_report` preserve payloads but establish no decoded residency. Keep voltages/maps unchanged and require a measured Linux load trace. | -| Raw versus logical state count | Meaning of the ADT count properties for this firmware, both SGX map banks and number of entries actually consumed by the 25G83 power tables | Public `HwData25G83`, calibration validation and loader handoff select eleven logical states from sixteen raw OPPs. Do not resize the firmware structure from the ADT property name or discard its unsorted OPPs. Compare actual top selection and achieved clock. | -| DVFS ramp / idle / fast-die | 25G83 meaning and units of ramp/effort controls, idle/off delays, temperature limits and hysteresis; PMP/AP/CLPC request ownership, achieved floors and release under idle and load | Existing shared submission/idle policy, DT suppliers and T6040 power-state graph are enabled. Power-state presence is not proof of load tracking. Require live requests, actual floor release and thermal traces; opaque power words are not tunable parameters. | -| Recovery slot attribution | Exact 25G83 slot-key storage range, lifetime, cache policy and slot stride; key QID/stamp bit fields; slot-mask meanings, progress monitor semantics and association with an actual started render | `recovery_slot_keys=None`; never copy T8140's physical address. Preserve firmware blame. Progress-view reads no longer depend on knowing the key address; bounded diagnostics report unknown ownership explicitly. | -| Recovery table / reason | 25G83 recovery-info offset/extent, valid/guilty/cancelled bits, stamp sequence encoding; reason-code semantics; ordering and reset of records relative to states 1/2/3/0; interrupted-command drain and visibility guarantees | Existing checked 256-entry table and handshake remain unchanged. Reason 3 is treated as page fault by existing attribution. New generation/slot diagnostics aid qualification; missing key evidence cannot clear blame. An aged compute record may no longer substitute for a stamp across recovery. | -| Compute completion / visibility | Exact compute record identity and timestamp fields, stamp write/cache-maintenance order, ring consumption during restart, late/missing-stamp behavior and a release witness for interrupted work | Same-generation 50 ms fallback retained. Crossing recovery now requires a covering stamp for ordinary retirement; quarantine, kill/drain and processor-stop ownership remain. A completion record plus elapsed time after restart is not independent visibility evidence. | -| MMIO pair registration | 25G83 MMIO port addresses and access-power witness; pair registration write order, ACK and coexistence with lead commands/bootstrap QID reservation | Keep disabled. The 26A428 sequence, POWER_ON_DONE message and recovery-target pointer are distinct ABI facts. | -| MCache | 25G83 table-entry format, sizes/alignment, descriptor pointers and enable bits, ownership/coherency rules, partial-render/restart behavior | Keep disabled until a licensed public implementation or independently supplied facts establish the whole contract and tests validate it. | -| Few-primitives | T6040 enable-bit semantics, required auxiliary buffer sizes/registers and partial-store/load/resume handling for all tiling/fragment paths | Keep disabled; previously observed hangs are not grounds to enable it for performance. | -| Ray traversal / preemption | T6040 register program, scratch sizing/alignment by enabled cores/clusters, saved operand-state layout, resume/checkpoint semantics, kill/restart contract, scheduler timer mask and priority profiles | Existing two-by-ten operand layout and priorities retained; periodic timer mask remains zero on both variants. Native traversal remains disabled pending bounded execution/fault/recovery qualification. | -| TLB range operations | T6040 opcode/operand encoding, VA/ASID granules, ordering, completion and negative-translation invalidation across every mapping alias | Existing page TLBI and PoC table cleaning retained. Copying Neo range encoding cannot close a performance gap safely. | -| Large vertex/barrier and tess/geometry faults | Faulting engine/access/VA/VM, exact bound intervals/backings and mapping lifetime; render/compute descriptor identity, TVB/GTP capacities, pass-start/stamp state and recovery reason before acknowledgment | Isolate exact public CTS names with one process and compare kernels with the same Mesa. Buffer size alone does not establish VM-bind, timeout or TVB causality. Retention fix is independently justified, not a claim to have cured a CTS fault. | - -The compute stamp-wait KUnit suite now checks that an aged exact record and -consumed items cannot retire a pre-recovery kick without its stamp, while an -exact/later stamp, busy-ring control and same-generation fallback retain their -expected behavior. Recovery-source tests cover unknown keys, incomplete reads -and page-fault fallback. Diagnostic counters explicitly identify lifetime -stampless totals; they are not a count of commands retired by one restart. - - -## g5 large-target capacity correction - -Public CTS `vulkan-cts-1.4.6.2` uses a 10240-square framebuffer for -`rasterization.primitive_size.points.point_size_10000`. The existing 25G83 -GTP layout appends a sub-buffer of 64 times the tile map after the TPC. -Applying the inherited 32 MiB cache bound to this combined allocation rejects -that valid target with ERANGE, despite its cache and tile record each fitting -their original limits. This is reproducible in the production layout code -without GPU execution. The normalized hardware summary contains ERANGE and -reason-2 recoveries but cannot establish their order or one-to-one association. - -G5 applies the original TPC_MAX to the aligned cache, preserving the original -tile-record bound before allocation or growth. The tile-map bound also caps -the derived auxiliary extent. It changes no firmware buffer-sizing formula, -numeric limit, VA window, generation/retention rule or allocation accounting. -Neo has no auxiliary tail and keeps the same policy. KUnit covers both utile -shapes at the CTS target size, oversized cache/layered-record rejection and -Neo capacity. Fresh and growing targets use the same preflight. Large targets -need their full required metadata through the existing memory/VA mechanisms; -allocation failure still propagates. Hardware execution/readback and post-close -memory/capacity baselines are mandatory acceptance gates. - -The separate 1 MiB vertex/barrier case uses a 256-square target, not a large -framebuffer. Its point count is actual vertex-buffer bytes divided by stride. -It cannot be explained by the large-target capacity guard. Preserve its first -operation/exception, generated sequence and the halted-state TVB/growth/pass -snapshots before choosing a coherence, VM-bind or firmware-timeout fix. The -point-target correction is not a claim that firmware reason 2 is decoded. - -## g5 recovery evidence and host-hop timing - -The shared recovery service previously captured slot keys and monitors at -halted state 1, then called `render_pass_started()` during classification -after acknowledging state 3 to 0. A resumed render could change that pass -state. G5 computes attribution from the state-1 pass snapshot and carries -only that result through the handshake. KUnit drives the real service and -rejects any pass read after the first acknowledgement. Unknown 25G83 keys -still retain firmware blame. This is an independently demonstrated ordering -fix; it does not establish the cause of either deterministic reason-2 fault. - -G5 adds the existing declared TVB state (inventory, page capacity, producer, -consumer, high-water and reset) to the halted snapshot without resetting any -counter. The blamed pair's first four commands include render geometry and -the computed GTP layout, alongside the existing pass/cursor/stamp records. -Pending/active growth and its reply remain visible. The next isolated run -can distinguish exhausted inventory or delayed growth from a pass that never -started; no buffer enlargement or firmware timeout change is justified yet. - -Static-key `asahi_g17_inputs` records compute input conversion entry/result, -source count and publication waits. `asahi_g17_schedule` records enqueue, -inline/fallback, preparation and run boundaries. Together with the existing -publish/complete, DMA-fence and scheduler tracepoints these split host cost -per hop into input resolution, scheduler setup/wait/dispatch and firmware -execution. They make no timing claim until a matched trace is captured. - -The available macOS reference uses 26A428 on T6040 and reports a software -request P10 while hardware residency is 1578 MHz at raw state 14. Linux runs -the admitted 25G83 image. Thus neither a literal P10 conversion nor copying -another firmware's statistics layout proves achieved MHz. The reference -contains aggregate frequency/residency and public DT/calibration facts, -not a Linux 25G83 tag/field decoder. The inspected licensed public G17 source -at `jgoyvaerts/linux` `cc32473a09dd` also has no decoded statistics adapter. -Required input remains a fresh Linux raw report series under labeled idle, -ALU and fill load, and independently established field/timebase/achieved-state -semantics for that exact firmware. No captured raw payload has been promoted -to public implementation data. Achieved clock/power and the CTS cure remain -open; g3's measured memory/latency policy is preserved. - -## g4 shared runtime ports and observability - -The operator has selected g3 as the hardware baseline. This follow-on retains -its CLPC/PMP ports, DT idle hold and recovery-generation release guard. -Individual hardware records remain in the private qualification workspace; -no raw lab capture is a public implementation source. - -| Gap | Public source behavior | T6040 g4 disposition | Qualification | -| --- | --- | --- | --- | -| #504 fragment notification | `de0b22a8370e` selects a render pair on its fragment notification; final retirement still requires both stored stamps | Included for both firmware graphs; KUnit covers each mask bank and unrelated queues | Render-light latency/IRQ rate, growth/partial renders, recovery and CTS | -| #504 tiling first-kick | `5073eac15192` changes the word only for the 26A428 register program | Included unchanged; 25G83 retains 1 on every kick | No T6040 notification-halving claim; requires 25G83 descriptor/notification facts and controlled qualification | -| #496 compute-fault witness | `9a76756bf2d7` uses event 7 words 3/4 as QID/stamp on Neo, with consumed-ring guard | Imported prerequisite, but the existing firmware graph keeps 25G83 event 7 unknown | Exact 25G83 layout, queue identity, stamp semantics and DMA/ring visibility must be established before it can release memory | -| #505 closed-context teardown | `078d744a260c` kills before freeing executed unstamped render graphs, retains firmware-linked work storage, and reuses killed pairs last with QID capacity | Shared safety/retention paths included; compute-fault-driven kill depends on the graph-qualified #496 witness | Closed mixed compute/render faults, acknowledgement ordering, memory pressure and slot/QID reuse; does not claim to cure a live render's first fault | -| #499 long-job sharing | `3db24da5c830` recognizes another published, unobserved long compute job as sharing, without changing numeric renewal bounds | Included in the shared host path; T6040 bounded AS-build classification can use it, while native traversal remains gated | KUnit verifies renewals stop at the existing bound; no claim that this cures a firmware reason-2 render fault or makes skipped traversal CTS pass | -| First fault | Reason and blame alone cannot identify engine progress | At halted state 1, before acknowledgement, g4 logs the blamed pair's stored stamps, free-list balance and up to four commands' pass/cursor snapshots; borrowed pairs are explicitly unavailable | Correlate exact CTS operation and original error with raw event report and snapshots; do not label reason 2 as page fault without semantics | -| Raw firmware statistics | Complete 18-word statistics records already have checked ring geometry | Read-only `firmware_reports` exposes last full sample, count and host monotonic time for each role/type. Static-key `asahi_g17_report` copies trace/statistics/event words before slot return | Match payloads to independently decoded achieved-clock/power/residency and freshness/units; legacy statistics tags are a different ABI | -| Idle memory floor | Neo graphics PMGR follows activity; T6040 GFX is held for firmware lifetime | g4 replaces T6040 PMGR demand with a DT-linked CLPC request, asserted at publication and released by the existing race-checked 16 ms continuous-idle clear; 32 ms CLPC hold remains | Read-only last vote/reason/time, host request and last submission, safe core power/host hold; require blank-panel quiet release and load/release cycles | - -Remaining exact facts for telemetry are the 25G83/26A428 tag-to-layout map, -field width/signedness/endianness, sample/timebase/wrap and freshness, -power units/averaging interval, logical/raw/cluster pstate selection, requested -versus achieved-state semantics, and limiting/thermal reason meanings. Raw -samples and the DT maximum are not MHz. Reads issue no firmware request and -never touch gated core registers. `agx_stats` remains unsupported for decoded -G17 data until those semantics are established. - -For the two deterministic CTS cases, retain the first failing operation before -cleanup, full unnormalized recovery logs, raw event trace, and pre-ack render -snapshots. The large-buffer and extreme-point-size cases can stress tiling, -but neither case name proves a TLB, timeout or TVB cause. No timeout, voltage, -feature-enable or buffer-size guess is included in g4. Multi-queue sync needs -its publish/GPU-span/event/fence timeline; #504's compute control does not -promise to halve that path's latency. - -### T6040 idle-floor release correction - -The PMGR DT explicitly documents that GFX cannot power down while firmware -runs. This is a source-established difference from the Neo CLPC input, so -using GFX as T6040 work demand can never establish idle release. G4 removes -that input on T6040 and adds `apple,clpc` from the GPU consumer to the existing -host performance controller. This is a provider relationship, not a feature -flag or user knob. A requested but unavailable provider defers GPU probe. - -Publication asserts the independent, refcounted request through a leaf lock; -o sleeping callback or allocation runs at submission. Both mutex-backed and -off-lock direct paths are covered. The existing effort clear checks in-flight -work and 16 ms continuous idle, withdraws its flag, then rechecks the direct -submission counter. A racing publisher reasserts demand. The CLPC vote keeps -its existing 32 ms hold; CPU arbitration and Neo's PMGR input are unchanged. -Firmware stop and request destruction clear demand. Provider removal cannot -free storage retained by a late consumer, and a device link orders dependencies. - -CLPC status now shows the last requested floor, reason bits and monotonic -time, plus the host request's activity/update sequence. Actual PMC readback -and write errors remain distinct. Read-only `asahi-g17/power` reports the -existing always-accessible core power witness, host hold, effort and last -publication time, without waking firmware. Generic runtime PM may remain -unsupported because autonomous core gating is firmware-managed; no fictitious -runtime-suspend implementation is enabled. Raw stats still do not decode MHz. - -The production CLPC host suite tests an always-powered supplier with absent, -busy and ended GPU demand, 32 ms hold, CPU coexistence, reason/time and legacy -Neo behavior; removing demand or idle release fails its negative controls. -C KUnit checks actual request lifetime and a late consumer after provider -removal. Hardware acceptance requires a locked/blank panel with publications -observably quiet, release after the hold, then three load/idle cycles and -retention of g3's benchmark gains. An active compositor alone proves neither -quiescence nor a latch. Keep failed measurements and rollback candidates. - -## Source and validation boundaries - -The implementation references are the licensed public Aurora/Asahi kernel and -loader history. Existing Gravity Linux-derived layouts and attribution remain -unchanged. The public Gravity Linux `gravity-m4` reference inspected at -`4fc326f6c25ccceb7515e2635c22e01fde5d3bac` was checked in `g16.rs`, -`g16_runtime.rs` and `g16_power.rs`. Those files do not supply validated -T6040 recovery slot keys; that G16 runtime explicitly leaves compute -non-preemptible. No private implementation, firmware bytes, voltage table or -lab record is included here. - -The build handoff must identify the exact tested source and loader, verify boot -payload checksums, retain r6g rollback, and distinguish CPU/QEMU tests from GPU -execution. Missing J616s measurements are not passing results. - -## Neo KMD improvements on T6040 - -This ledger audits refinements and handling, not just feature parity. It uses -`integration/aurora` at `9cbdd0734d9e186c5f5f5949a21b909d10c2571b` and -`aurora-wip` at `927a4a4480cf90ce8e3b4ab1d1ce58d84bf32fd4`. The conservative -history window starts 2026-09-26 (Neo platform prerequisites), before the public -T8140 firmware interface of 2026-10-03 and hardware bring-up of 2026-10-06. -Committer dates retain rebased older-author changes. The inventory also includes -the complete 105-commit public #171 history, all 65 commits of #423, and the -related PR versions used to identify original contributions and later ports. - -The path log covers `drivers/gpu/drm/asahi`, Apple PMP/PMGR/PMC/CLPC/MCC, -RTKit/mailbox, CPU-frequency/thermal and DART code, related AIC and DRM -scheduler/fence support, Rust DRM interfaces, and Neo DT dependencies. Broad -path/PR neighbors and imported baseline changes are explicitly marked N/A; -they are not represented as measured Neo optimizations. Old/rebased hashes are -listed as encountered aliases of the same subject/class, not asserted to be -byte-identical. The coverage inventory lists 1,551 physical commits (including -imported neighbors and PR-original versions), with 851 distinct subjects; all -65 #423 commits have separate rows. **Active** describes the surviving mechanism on T6040, including -its 7.3 port/refinement, rather than claiming that every historical SHA is an -ancestor. Multi-purpose firmware-introduction records retain their shared -parts while explicitly identifying dormant MCache/native-feature portions. A commit link is its exact diff; the evidence key states the current -reachability/gate. No per-commit speedup is invented from a stack measurement. - -### Applicable ports found by the commit audit - -| Neo mechanism | T6040 in g1 | g2 port and per-chip data | Required acceptance | -| --- | --- | --- | --- | -| #440 GPU-driven CLPC memory/fabric floor | CPU demand only; `gpu_demand=false`, no GPU power-state phandle | `0d63308820ab`: existing GPU-demand mechanism and DT phandle, T6040 DCS 5/fabric 2 and existing 32 ms release; CPU sustain=3 retained | C/R/H/I/P; actual PMGR tracking, floor release, video/browsing and sustained-load power | -| #219 PMP voter cooperation | Static voters 1/3 omit PMP 0 from pre-working-PMP bring-up | `772a9d3104ff`: existing `apple,pmp` supplier dependency, voters 0/1/3, existing T6040 DCS/SOC rail mask; no display rail or voltage change | P/B; PMP bound/ready, live request/honoured floors, idle and thermal behavior | - -Other audited gated paths are listed explicitly below. The T8140 lazy CPU -verification cost is absent on T6040's already-fast-switch profile. MMIO pair -registration, range-only TLB encoding, native RT/few-primitives and optional DCS -cooling cannot be enabled by copying a different firmware/hardware protocol. -The recovery slot-key attribution gate still needs validated 25G83 identity -facts; shared recovery, deadlines and retirement handling remain enabled. - -### Reported measurements and their scope - -These are public PR results, not new J616s measurements. Private qualification -reports were checked for scope and regressions; raw lab records are not copied -here. The older GPU profiling report's cost estimates are not measurements. - -| Evidence | Relevant commits/mechanism | Reported Neo result | J616s confirmation | -| --- | --- | --- | --- | -| [#171](https://github.com/aurora-silicon/linux/pull/171) | Retention, off-lock cleanup, reclaim quiet window and shared lifetime stack | Cold first-submit median 224 to 194–198 us, p99 338 to 295–305 us; menu-launch stalls below 100 ms versus 260–280 ms before quiet-window work. Stack results, not isolated gains. | B/M/C/R, repeated fresh contexts and foreground launch under bounded pressure | -| [#171](https://github.com/aurora-silicon/linux/pull/171) | Completion/recovery isolation | Earlier mixed render/compute lost its device within 2 s; later fixture ran over 568k verified checks in 60 s. Historical 1 ms stamp fallback was subsequently refined to 50 ms. | F/H/T; exact data and fences, peer liveness and no premature mapping release | -| [#423](https://github.com/aurora-silicon/linux/pull/423) | Cumulative scopes and submission stack | Same-boot submit API elapsed roughly 14 to 10 us; throughput stayed near 20 us. Combined candidate C-d64 19.44 us, R-d32 41.48 us, hop 42.12 us; workload/Mesa dependent. | C/R/H; preserve wall-time versus thread-CPU distinction | -| [#423](https://github.com/aurora-silicon/linux/pull/423) | `9bf3039873a1`, completion identity index | Scanner self samples 4.87% to 2.24% at depth 64, 3.16% to 1.93% on hops. CPU profile result. | O/C/H | -| [#423](https://github.com/aurora-silicon/linux/pull/423) | `26446182da3a`, 128-interval validation working set | C-d64 API elapsed 10.06 to 7.46 us; R-d32 12.29 to 8.16 us. Not a thread-CPU clock measurement. | C/R/D with rotating 64 buffers and remap/permission invalidation | -| [#423](https://github.com/aurora-silicon/linux/pull/423) | `b6248acf900c`, private-fence fast status | Submit API median 7.52 to 5.79 us; frontier samples 1.83% to 0.25%; throughput remained near 19.5 us. | C/H/O; errors, foreign inputs and delayed host publication | -| [#440](https://github.com/aurora-silicon/linux/pull/440) | `d69f14f4e4fb`, GPU fabric floor | C-d1 158.9 to 108.2 us; C-d64 19.3 to 14.7 us; R-d32 42.7 to 29.7 us; hop 42.2 to 31.9 us. Same driver/Mesa. | P/C/R/H, compare g1/g2 and keep heavy/idle checks | -| [#219](https://github.com/aurora-silicon/linux/pull/219) | GFX report/PMP vote and PMC enables | Short manual-bit glmark2 build experiment: 1453 with GFX report off to 2199 with it on; 2218 with all interface enables. Single-run 7–10 s experiment, not an isolated final-kernel A/B. | P/R; distinguish reported request, enabled agent and honoured floor | -| [#443](https://github.com/aurora-silicon/linux/pull/443) | Lazy verification and fast switch | C-d2 58.8–59.7 to 46.4–47.3 us; C-d1 107.8–108.4 to 102.6–102.7 us. T8140-specific spin removed. | C/I observation only: T6040 already lacks that spin | -| [#413](https://github.com/aurora-silicon/linux/pull/413) | Existing optional idle hold | The roughly 1.1 ms wake and 1.2–1.4 ms tiny-render-after-gap observations are **M4 Pro**, not Neo measurements. Default 2 ms adds no extended hold. | I at defaults; optional hold is a separate policy experiment | - -The provided current Neo Linux/macOS report has no completed paired Linux -record, so an overall Neo margin is still undefined. Historical PR ratios do -not establish the requested current all-workload margin. Use matched suite, -Mesa, clock/power conditions and repeats. Run only workloads admitted by the -controller; queue depth is not permission for extra process workers. - -### Reachability and gate evidence keys - -| Key | Current source/gate and interpretation | -| --- | --- | -| SHARED — Shared G17 execution | driver.rs selects g17::Gpu for T6040. g17/queue/mod.rs, runtime.rs, port.rs, runtime/render/direct.rs and runtime/render/submit.rs have no T8140-only gate on these mechanisms. The variant supplies QID floor 32, producer +0x50, two-cluster operands and 25G83 lead commands. | -| DRM — Shared DRM/scheduler/fences | G17 queues use job.rs, fence.rs and the common DRM scheduler/syncobj/GPUVM/shmem interfaces. CPU_FREQ and UCLAMP_TASK are enabled in the release config. Private cumulative scopes are advertised on both G17-backend targets at feature bit 29; foreign fences retain generic handling. | -| MEM — Common memory and lifetime | file.rs::memory_stats, gem.rs, memacct.rs, cleanup.rs, pgtable.rs and mmu.rs serve the T6040 G17 backend. Creator accounting, pins, revocable backing, canonical bindings and deferred destruction are not gated to T8140. T6040 keeps its explicit UAT coherency policy. | -| GMEM — Shared retained GPU resources | g17/freelist.rs, context.rs, object.rs, queue/compute.rs and runtime/render/pools.rs retain and reclaim the same resource owners. Allocations use T6040 core-layout sizes and its reduced QID budget; no Neo-only admission branch disables them. | -| REC — Shared recovery and deadlines | g17/recovery.rs, recovery/safety.rs, timeout.rs and runtime/events.rs serve both firmware variants. T6040 uses its status-B base and one firmware role. Exact retirement, interrupted-work failure, withheld-doorbell replay, progress-aware budgets and sticky VM reporting remain active. Current missing-stamp fallback is 50 ms, not the historical 1 ms. | -| POWER — Shared feed/effort/idle code | g17/feed.rs is instantiated for T6040 and derives CPU floors from each discovered policy maximum. g17/mod.rs::note_submission/idle_check and power.rs share effort 1.0 while work streams and a 16 ms idle clear. The existing optional idle hold is available on T6040 but its default 2 ms adds no extended hold. | -| TIMESTAMP — Shared timestamp publication | timestamp.rs::FirmwareBuffer retains a CPU vmap for the buffer lifetime; g17 completion publishes through it before signalling. T6040 uses this shared firmware-buffer path and its 24 MHz timestamp conversion, not a per-command vmap. | -| PRIORITY — Shared firmware priority profiles | g17/mod.rs::scheduling_policy selects HIGH/MEDIUM/LOW profiles for both targets; file.rs checks CAP_SYS_NICE or DRM master for HIGH and refuses REALTIME. Priority work-ring selection and QoS ownership are shared. | -| FW — Per-chip firmware adaptation | hw/t6040.rs selects V25G83. g17/initdata/v25g83.rs supplies one merged root and status acknowledgement, per-chip OPP/calibration input, separate views and no POWER_ON_DONE. Pointer and operand layouts are selected from Config/Variant rather than copied from the two-instance 26A428 graph. MCache is explicitly gated by V25G83.mcache=false; its firmware table/protocol is not part of admitted T6040 support. | -| PMGR — Shared PMGR state handling | pmdomain/apple/pmgr-pwrstate.c binds T6041 states through the t8103-compatible state protocol. BUSY masking, timeout unwind and firmware-owned/no-auto-PM properties apply through DT; no T8140-only register address is copied. | -| PMP — PMP/report per-chip data | soc/apple/pmp.rs and pmdomain/apple/pmp-report.c already contain T6041 match data: 42-bit DMA, version-5 bootargs checks, CoreAnalytics EP7, T6041 report offsets and three fast-die lanes. T6040 DT supplies the bootargs/report entries and CPU effort phandles. T8132/J713-only telemetry policy is excluded separately. | -| PMC — Shared PMC, T6040 rail mask | pmdomain/apple/pmc.c::apple_pmc_probe/agent_enable use T6040 agent stride, DCS maximum 5 and agent_rails=GENMASK(1,0). CPU/CLPC/AP voting already worked. Port 772a9d3104ff adds apple,pmp and static voter 0 after its supplier binds; display rails remain excluded. | -| CLPC — Shared CLPC, T6040 demand data | soc/apple/clpc.c uses T6040 DCS {1,2,5,5}, fabric {0,1,2,2}, sustain=3, 4 ms sampling and 32 ms hold. CPU demand/lifecycle refinements are shared. GPU demand was missing and is enabled by 0d63308820ab with the existing apple,gpu-power-state phandle. | -| GPUFLOOR — Applicable gate ported | Before g2, apple_clpc_hw_t6040.gpu_demand was false and its CLPC DT node had no apple,gpu-power-state. Port 0d63308820ab enables the same mechanism as #440 with T6040 DCS 5/fabric 2, not Neo 4/3. Hardware gain and idle/PMP cooperation remain unqualified. | -| MCC — MCC translated to 16 planes | soc/apple/mcc.c accepts the T6041/T8140-compatible controller; T6040 DT describes 16 planes and its display boot-DMA dependency. The J616s enables this node. Generic partial-enable unwind, lifetime and SLC allocation rules apply with that data. | -| CPU — Shared CPU frequency/limit handling | T6041 CPU nodes bind the t8112 fallback profile. Generic OPP cleanup, fast-switch and PMP effort QoS use its DT frequencies and three effort lanes. No Neo frequency or thermal curve is copied. | -| LAZY — Different CPU verification protocol | The lazy_verify refinements are T8140-only. T6040 binds soc_t8112_info, whose verify_transition is false; policy->fast_switch_possible is already true. It does not pay the T8140 blocking verification loop that these commits remove. Adding lazy verification would not port a missing gain. | -| DART — Related DARTs; native GPU uses UAT | iommu/apple-dart.c common publication/error/resume/stream logic is used by T6041 DARTs where their DT ownership mode selects it. T6040 display mirroring uses its own compatible/data. Native GFX translations use asahi/mmu.rs UAT, so this is related PMP/display robustness, not a claim that Neo DART addresses fit the G16 GPU. | -| RTKIT — Shared RTKit transport/lifetime | G17 Coprocessor uses the Rust RTKit wrapper over soc/apple/rtkit.c. Shared buffer retention, barriers, crash handling, bounded logs and shutdown ownership apply. T6040 supplies its firmware-data crash buffers and one ASC instance; MTP/J713-only adoption is excluded. | -| MBOX — ASCWrap transport, per-chip registers | soc/apple/mailbox.c and rust/kernel/soc/apple/mailbox.rs provide the common queue, IRQ and receiver ownership rules. T6040 binds its ASCWrap-v6 data; its wrapper/VBAR windows and IRQs come from DT. Neo-specific mailbox addresses are not reused. | -| AIC — Shared effective-affinity reporting | irq-apple-aic.c applies AICv2+ reporting to the T6041 AIC3 compatible too. It reports actual effective routing rather than manufacturing CPU migration. Record the IRQ/worker CPU on J616s; no isolated throughput gain is claimed. | -| DISPLAY — Related shared display hardening | Generic apple/dcp.c, parser and AFK lifecycle/bounds fixes are inherited by the reconstructed display stack where those helpers are used. They protect the display consumer of GPU buffers; they are not standalone compute performance claims. | -| OBS — Observability only when selected | Existing G17 tracepoints/diagnostics and first-failure logging are shared. Trace register sampling is conditional on the tracepoint being enabled; disabled tracing is not a new runtime policy or a measured throughput gain. | -| MMIO — Different registration ABI | runtime/render.rs::install_pair returns before registration power holds when V25G83.mmio_pair_registration=false. 25G83 installs from queue configuration and uses lead commands; 26A428 uses MMIO pair registration. Do not add its two control round trips or register writes to the admitted 25G83 protocol. | -| FEW — 25G83 rejects this fast path | V25G83.few_primitives=false; command.rs and feature reporting enforce it. The supported-source comment records a fragment hang with the flag. It is not an applicable refinement of the admitted 25G83 render ABI without new validated facts. | -| RT — RT specialization not admitted | V25G83.ray_traversal=false; command.rs rejects native scratch/intersection programs and get_params omits the feature. Generic watchdog/recovery infrastructure remains shared, but native RT pools/kill guards/RT-specific long-job use are dormant on the admitted 25G83 path. | -| KEY — Missing validated recovery identities | hw/t6040.rs has recovery_slot_keys=None. recovery/attribution.rs falls back to firmware blame when slot identity evidence is incomplete. Neo slot-key addresses must not be invented for 25G83; this specific attribution refinement remains gated pending validated T6040 facts. | -| UAT — Qualified alternate invalidation policy | hw/t6040.rs keeps reserved_tables, clean_tables and page_tlbi=true. mem.rs::tlbi_range takes the page/ASID alternative before its range encoder. The range-only field fix is dormant; per-SoC coherency/ownership support is active. Removing these working firmware-table requirements is not a justified performance port. | -| DCS — Optional cooling actor, no T6040 curve | PMC cooling/IPA paths require #cooling-cells and power-model DT data. J616s does not select them, and the Neo DCS thermal zone was subsequently removed because it throttled unrelated GPU/CPU heat. No T6040 power curve is invented to re-enable that policy. | -| DCSOFF — Already equivalent inactive zone | Neo removed its oscillating DCS thermal zone. J616s has no such zone to remove. Its PMP CPU/GPU limits remain; this does not justify disabling thermal protection. | -| IRQENTRY — DT-selected report context | IRQ-safe report entries are selected by apple,irq-safe for PMGR-parent use. GFX report consumption does not require copying the external-display parent topology; use the actual T6040 entry/consumer hierarchy. | -| STAT — Not the Neo backend | StatsChannel/GpuManager agx_stats decoding belongs to the maintained backend. g17::Gpu::stats_snapshot returns None on both Neo and T6040. It is not a Neo optimization waiting to be ported to G16S. | -| G15 — Different backend/hardware | T6030/T6031/T8122/G15 and M3-only runtime commits do not execute in T6040 g17::Gpu. Their firmware records, generation-specific power policy and native-G15 admission cannot be copied into G16S/25G83. | -| G16 — Different G16 backend/owner ABI | T8132/J713 uses the separate g16 backend and retained-owner PMP/TVM protocol. T6040 is G16S but dispatches to the g17 backend with V25G83, not that G16G runtime. Match/board gates and firmware ownership differ. | -| LEGACY — Maintained G13/G14 path | The workqueue/manager/versioned AGX firmware path is not T6040's G17 backend. G13/G14 automatic preemption, timestamp-copy and old InitData changes are not missing G16S mechanisms. | -| OTHERCHIP — Other CPU/guest hardware | T8142/T8152/T6050-specific transition, ownership or guest-timer data is not selected by T6041 CPU/GPU match data. No unsupported register/profile change is ported. | -| TUNNEL — Other peripheral topology | M1 tunneled PCIe/Thunderbolt recovery is not a Neo native-GPU improvement. T6040 has its own topology; these records are retained for coverage, not presented as a gated G16S optimization. | -| PERIPH — Not a GPU refinement | This scoped-history/PR neighbor concerns NVMe, HID, audio, SEP, USB, RTC or another peripheral, not a Neo native-GPU performance/handling mechanism. No port is implied. | -| BOARD — Neo-specific board route | The literal J700 topology/display source/domain-cell fix is not T6040 board data. Its independent J616s display/PMP/GPU composition is retained; copying a Neo route or physical address would be wrong. | -| RAWDIAG — Superseded raw diagnostics | The raw T8140 PMP DVFS debugfs dump was later removed. Current reporting uses validated per-SoC fields; no new raw interface or platform knob is added. | -| OLDTHERMAL — Superseded thermal policy | The interim J700 SMC CPU policy was removed/replaced by thermal-framework and PMP handling. It is not the policy selected for T6040 and no Neo temperature/power curve is copied. | -| SUPERSEDED — Superseded inside the series | The unconditional-doorbell/unbound-inline policies were refined by later #423 commits; the early disabled-J616s admission was replaced by calibrated #463 enablement. Current code preserves low-pressure probes and defers/coalesces eligible doorbells with explicit release/stall/recovery handling; do not reapply the obsolete intermediate policy. | -| VERIFY — Build/test/documentation only | This record changes tests, descriptions, bindings, layout/build checks or source style rather than a runtime performance mechanism. Its contract is retained where applicable; there is no isolated hardware speedup or new platform behavior to port. | -| MERGE — Integration record | This merge is provenance/composition, not an isolated performance mechanism. Its parent changes are enumerated below, including variant preservation and subsequent fixes; no separate speedup is assigned to a merge. | - -### Hardware measurements referenced by each commit - -All hardware actions require the controller's explicit J616s identity, policy -approval and ownership/session/resource gates. These are a measurement plan, -not permission to bypass them. Pair g1/g2 with the same loader and Mesa and -preserve failed runs, logs and r6g rollback. - -| Code | Measurement | -| --- | --- | -| C | compute.light d1/d2/d64; submit API wall and thread-CPU time, scheduler hops, faults and CPU-frequency/IRQ context; matching Mesa/suite. | -| R | render.light d1/d2/d32 and 8 queues, first render, heavy fill and tiler growth; API p50/p99, throughput and memory high-water. | -| H | same/cross-queue binary and timeline hops; p50/p95/p99, doorbells per command and 100k order/data checks; include eligible and fallback dependencies. | -| I | idle.wake after 2/20/100 ms, default policy, first-frame latency and clocks; 60/120 Hz frame pacing and idle power. Keep optional hold experiments separate. | -| F | controller-approved bounded stall/fault/long-job stress with innocent peers; no wrong data or false successful fence, recovery phase/time, VM errors and post-close reuse. | -| M | multi-client create/close/rearm and approved bounded pressure; committed/resident bytes, retained pools/QIDs, restoration time and leak slope. | -| P | PMP readiness, PMC per-agent requests/honoured floors and CLPC readbacks during GPU-only, mixed CPU/GPU, 90 s heavy load, idle, video and browsing; verify idle release and no sustained thermal regression. | -| T | timestamp/query correctness, 24 MHz conversion, aligned/unaligned publication where supported, buffer-map reuse and query CPU cost. | -| Q | privileged/unprivileged priority admission and concurrent LOW/MEDIUM/HIGH progress, global-priority transition cases and timeout attribution. | -| D | approved bounded VM_BIND/unmap/remap and DART ownership/resume boundaries; CPU cost, invalidation errors and zero unexpected DART/UAT faults. | -| B | exact boot/kernel/loader/Mesa pins, firmware admission, first queue/install, panel/display regression, supplier readiness and rollback. | -| O | existing tracepoints/counters under approved instrumentation; IRQ and event-worker CPU, pass duration, notifications and failure site. Tracing off remains the reference. | -| V | static/build/contract or capability-refusal check; no isolated hardware improvement claimed. | - -### Every commit in #423 - -All 65 entries are retained, including intermediate policies, tests and the -integration merge. Superseded steps are not mistaken for current behavior. - -| Commit | Author | Improvement / record | T6040 after ports — evidence key and changed source | Measurement | -| --- | --- | --- | --- | --- | -| [ad691cd5e9f7](https://github.com/aurora-silicon/linux/commit/ad691cd5e9f76aa9e486d93b560c58d5c8ff88c4) | DjDeveloperr | drm/asahi: publish bound G17 compute work without the admission passes [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/completion.rs` | C,H | -| [1121ae36b8d4](https://github.com/aurora-silicon/linux/commit/1121ae36b8d426be24c41ae360281b5f0709a69d) | DjDeveloperr | drm/asahi: wake G17 render publication when its pair is returned [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | R,H | -| [abd85935bd4d](https://github.com/aurora-silicon/linux/commit/abd85935bd4db7db6be23b8194b1173c9a8988c5) | DjDeveloperr | drm/asahi: clear each G17 compute descriptor only once [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fw/compute.rs` | C,H | -| [3ef3720890f8](https://github.com/aurora-silicon/linux/commit/3ef3720890f8c085f18e4f5e35db6853075b121c) | DjDeveloperr | drm/asahi: retain compute pool backing through pending channel admission [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — GMEM; `drivers/gpu/drm/asahi/g17/capacity.rs` | M,C,R | -| [f35d7ea1b373](https://github.com/aurora-silicon/linux/commit/f35d7ea1b37395a9bc1241d0fafcb698e0c12d46) | DjDeveloperr | dma-buf: stop polling an array after its first pending member [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — DRM; `drivers/dma-buf/dma-fence-array.c` | C,H,M,F | -| [319805fed41b](https://github.com/aurora-silicon/linux/commit/319805fed41bb181db8e90378beaf905f38f6297) | DjDeveloperr | drm/asahi: avoid unbound compute inline attempts on compute-only queues [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — SUPERSEDED; `drivers/gpu/drm/asahi/g17/context.rs` | C,H | -| [5a4822c6fb3d](https://github.com/aurora-silicon/linux/commit/5a4822c6fb3d1fc0a83d9b754b477bf1db35d782) | DjDeveloperr | drm/asahi: preserve low-pressure compute inline probes [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime.rs` | C,H | -| [026065c43526](https://github.com/aurora-silicon/linux/commit/026065c435260844e39d05a182e99b128c5f9b2d) | DjDeveloperr | drm/asahi: submit same-VM compute input waits through firmware [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/capacity.rs` | C,H | -| [89c8873651b7](https://github.com/aurora-silicon/linux/commit/89c8873651b729fdd4e981e87b9d0df0d0ad0017) | DjDeveloperr | drm/asahi: treat a firmware source as complete once its retirement is queued [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/completion.rs` | C,R,H | -| [3ff4f4baa05a](https://github.com/aurora-silicon/linux/commit/3ff4f4baa05a88d5f99d2fee76089cf72b5617a4) | DjDeveloperr | drm/asahi: publish G17 commands from the ioctl at any queue depth [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | C,R,H | -| [a0dfc3c0b5a4](https://github.com/aurora-silicon/linux/commit/a0dfc3c0b5a4fced66119fded07ed141990a9025) | DjDeveloperr | drm/asahi: map G17 compute descriptors cached for the firmware [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [a36e352d8564](https://github.com/aurora-silicon/linux/commit/a36e352d8564947071fef7e11dba709f399cd106) | DjDeveloperr | drm/asahi: size the G17 compute QID budget by open logical queues [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/kick.rs` | C,H | -| [b141ca9b16c3](https://github.com/aurora-silicon/linux/commit/b141ca9b16c33abb26238782cd7c0b751b5f52fe) | DjDeveloperr | drm/asahi: order same-VM render attachment overlaps in firmware [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/completion.rs` | R,H | -| [a475f4f9f1f7](https://github.com/aurora-silicon/linux/commit/a475f4f9f1f721b6636a4147dacbcf9f6224763b) | DjDeveloperr | drm/asahi: map G17 compute command records cached for the firmware [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [ca71e4449b4a](https://github.com/aurora-silicon/linux/commit/ca71e4449b4a23d5f4e0149db76cf5198bfa7e5f) | DjDeveloperr | drm/asahi: stop the G17 compute completion scan once every record is found [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/initdata.rs` | C,H | -| [1cdac9ba0ddd](https://github.com/aurora-silicon/linux/commit/1cdac9ba0dddec96f59eb02a5067ee343aae43f4) | DjDeveloperr | drm/asahi: publish G17 compute into a bound queue without the device mutex [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/context.rs` | C,H | -| [7242bf87efd2](https://github.com/aurora-silicon/linux/commit/7242bf87efd2b3f4f8bf2a31fadb79b3e687f195) | DjDeveloperr | drm/asahi: send a G17 compute queue configuration only when it changes [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [014605a36795](https://github.com/aurora-silicon/linux/commit/014605a3679581351913c3ab137653297f7a0cf7) | DjDeveloperr | drm/asahi: add G17 resource wait domains and use them for queue creation [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/availability.rs` | C,R,H | -| [64f717dcfd1e](https://github.com/aurora-silicon/linux/commit/64f717dcfd1e4aa5856882181f5c2ac040c5ce4e) | DjDeveloperr | drm/asahi: wait for G17 compute capacity on the release that frees it [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/availability.rs` | C,H | -| [327e50fc45b5](https://github.com/aurora-silicon/linux/commit/327e50fc45b57acf1954e8c2d78977198286feb0) | DjDeveloperr | drm/asahi: wait for a G17 compute source only through its completion record [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime.rs` | C,H | -| [6f4d3bbb47c1](https://github.com/aurora-silicon/linux/commit/6f4d3bbb47c1a7b19abef118b41b131440a8f414) | DjDeveloperr | drm/asahi: add G17 command lifecycle tracepoints [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — OBS; `drivers/gpu/drm/asahi/g17/mod.rs` | O,F | -| [e24e3bad9e7d](https://github.com/aurora-silicon/linux/commit/e24e3bad9e7d3c6cf7079d683c9364d619cd3a55) | DjDeveloperr | drm/asahi: ring the G17 compute pipe doorbell for every publication [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — SUPERSEDED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [94c66ecf24e6](https://github.com/aurora-silicon/linux/commit/94c66ecf24e6d931a434914d6a513ee36ff6ffd7) | DjDeveloperr | drm/asahi: map the G17 compute queue graph cached for the firmware [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [db365ecc299f](https://github.com/aurora-silicon/linux/commit/db365ecc299f0663db8a629e70dfdb4d117eb95e) | DjDeveloperr | drm/asahi: wait for G17 render capacity on the release that frees it [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/context.rs` | R,H | -| [06bc290c266a](https://github.com/aurora-silicon/linux/commit/06bc290c266abcb8b0d45f75c3369e231ae8c4a7) | DjDeveloperr | drm/asahi: give the G17 render scheduler the pair's depth as credits [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/job.rs` | R,H | -| [3d1f2047766c](https://github.com/aurora-silicon/linux/commit/3d1f2047766c2d6e8d165a4af2cfe4adc0edd366) | DjDeveloperr | drm/asahi: keep a G17 render free list registered while the firmware is busy [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/freelist.rs` | R,H | -| [b7fa0d482eea](https://github.com/aurora-silicon/linux/commit/b7fa0d482eea670f9004422eaf57703a7ec8d4e5) | DjDeveloperr | drm/asahi: take the G17 device mutex less often to publish a render [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/admission.rs` | R,H | -| [d272a7060d20](https://github.com/aurora-silicon/linux/commit/d272a7060d20a0beb635ca8426c8822b8e823a43) | DjDeveloperr | drm/asahi: publish a G17 render into its pair without the device mutex [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/initdata.rs` | R,H | -| [6428f7fd42fe](https://github.com/aurora-silicon/linux/commit/6428f7fd42fe075981984da569b0fa076f59a127) | DjDeveloperr | drm/asahi: lend a G17 render pair without the identity check first [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime.rs` | R,H | -| [8cf02f589bce](https://github.com/aurora-silicon/linux/commit/8cf02f589bce34b13002cbdf0f3b0361c4a8e66b) | DjDeveloperr | drm/asahi: wait for G17 render admission before run_job [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/admission.rs` | R,H | -| [550fb355e9a3](https://github.com/aurora-silicon/linux/commit/550fb355e9a30c0db9c59fe35a931f1db9c6b5c4) | DjDeveloperr | drm/asahi: trace the G17 core power state at each work doorbell [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — OBS; `drivers/gpu/drm/asahi/g17/mod.rs` | O,F | -| [f381ac9b71eb](https://github.com/aurora-silicon/linux/commit/f381ac9b71ebcb70eb72497ec4115553856a31fc) | DjDeveloperr | drm/asahi: trace G17 host-to-firmware messages [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — OBS; `drivers/gpu/drm/asahi/g17/channel.rs` | O,F | -| [adcd56e02036](https://github.com/aurora-silicon/linux/commit/adcd56e020362664c7bc3af288e1ad812df7b4c7) | DjDeveloperr | drm/asahi: maintain cumulative completion scopes without repeated fence merges [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — DRM; `drivers/gpu/drm/asahi/g17/fence.rs` | C,H,M,F | -| [bcdfdafd80cf](https://github.com/aurora-silicon/linux/commit/bcdfdafd80cf93fadc79df688dd0109b9c4ae8d2) | DjDeveloperr | drm/asahi: test G17 queue budgets with firmware-reserved identities [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/kick.rs` | V | -| [971d4316d91c](https://github.com/aurora-silicon/linux/commit/971d4316d91cce97b92db72c4f29e5155b76d626) | DjDeveloperr | drm/asahi: size cached compute records for every native wait [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [9bf3039873a1](https://github.com/aurora-silicon/linux/commit/9bf3039873a1e241991b5999aceff5610c660ade) | DjDeveloperr | drm/asahi: index pending compute completion identities before reading payloads [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute/retirement.rs` | C,H | -| [26446182da3a](https://github.com/aurora-silicon/linux/commit/26446182da3aa8d98ce799478a025117b021eaba) | DjDeveloperr | drm/asahi: retain a deep working set of validated GPU page ranges [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/validation.rs` | C,R,D | -| [b6248acf900c](https://github.com/aurora-silicon/linux/commit/b6248acf900c1cf30deac52791c2c50d10055d7b) | DjDeveloperr | drm/asahi: avoid locking pending private completion fences [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/job.rs` | C,R,H | -| [b08c81722d89](https://github.com/aurora-silicon/linux/commit/b08c81722d896eee8da9771e99e38e6986a2a806) | DjDeveloperr | drm/asahi: give G17 firmware restarts time to drain long work [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/recovery.rs` | F,Q | -| [f1db16a83586](https://github.com/aurora-silicon/linux/commit/f1db16a83586e4bec596a71e12e0d8b87dd3b16c) | DjDeveloperr | drm/asahi: fail commands a GPU restart interrupted instead of completing them [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/completion.rs` | F,Q | -| [30f85560fd28](https://github.com/aurora-silicon/linux/commit/30f85560fd28ce05151c16eab7a58433d125a81e) | DjDeveloperr | drm/asahi: stop the G17 device on a watchdog storm only without progress [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [2c0abe2d090a](https://github.com/aurora-silicon/linux/commit/2c0abe2d090a9701b13b22d5ac56fb24d87cfe12) | DjDeveloperr | drm/asahi: scan only the G17 compute completion records written since the last pass [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/initdata.rs` | C,H | -| [39bdd5b8e2d5](https://github.com/aurora-silicon/linux/commit/39bdd5b8e2d584fff0d342a71a8945e64c8a9673) | DjDeveloperr | drm/asahi: release pruned G17 frontier entries after the ioctl publishes [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | C,R,H | -| [b41ecb56c077](https://github.com/aurora-silicon/linux/commit/b41ecb56c0775a43b747adaa37661b353651dbff) | DjDeveloperr | drm/asahi: publish both G17 render QoS owners in one pass [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/port.rs` | R,H | -| [b86c445ba282](https://github.com/aurora-silicon/linux/commit/b86c445ba2829f644075ca663217abe65844e8c0) | DjDeveloperr | drm/asahi: stop copying G17 fragment registers to the unused client page [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render/memory.rs` | C,R,H | -| [5a55068193e2](https://github.com/aurora-silicon/linux/commit/5a55068193e213d7115a63f2222ffc304a4ced98) | DjDeveloperr | drm/asahi: read the G17 render work rings once per direct publication [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/port.rs` | R,H | -| [b67018ed5974](https://github.com/aurora-silicon/linux/commit/b67018ed5974069c13c13249834dbc3b84e806ed) | DjDeveloperr | drm/asahi: request the G17 tiling descriptor slot before preparing a render [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render.rs` | R,H | -| [4d0362d0c18d](https://github.com/aurora-silicon/linux/commit/4d0362d0c18d288d3bd520fdfb69c2e7624cf6b0) | DjDeveloperr | drm/asahi: store G17 register arrays without an intermediate copy [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fw/kick.rs` | C,R,H | -| [861b39d948f6](https://github.com/aurora-silicon/linux/commit/861b39d948f6c0588b3646e1246e660b52230e5b) | DjDeveloperr | drm/asahi: also request the G17 queue configuration records early [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render/memory.rs` | C,R,H | -| [66ef051d8bd4](https://github.com/aurora-silicon/linux/commit/66ef051d8bd4e66bdc145eb7fb7a920235a8e668) | DjDeveloperr | drm/asahi: scan only render pool slots for G17 free-list leases [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — GMEM; `drivers/gpu/drm/asahi/g17/runtime/render/pools.rs` | M,C,R | -| [1aec5be232da](https://github.com/aurora-silicon/linux/commit/1aec5be232da7bacbbe38b7f9b22c27906eac8c6) | DjDeveloperr | drm/asahi: omit G17 render queue configurations that only reload the held completion [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render.rs` | R,H | -| [d0df244b8f02](https://github.com/aurora-silicon/linux/commit/d0df244b8f023037bb0f9cc9793f1d0f285cfc87) | DjDeveloperr | drm/asahi: keep one CPU mapping per G17 timestamp buffer [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — TIMESTAMP; `drivers/gpu/drm/asahi/g17/completion.rs` | T,C | -| [3ff8c49c5f12](https://github.com/aurora-silicon/linux/commit/3ff8c49c5f12b908a72e6c076ff0d7336ffddcb8) | DjDeveloperr | drm/asahi: withhold G17 compute doorbells behind two unretired commands [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [b1f5dc6df0ba](https://github.com/aurora-silicon/linux/commit/b1f5dc6df0ba5650c8424027a025db233c6544c4) | DjDeveloperr | drm/asahi: drop G17 compute doorbells that another doorbell announced [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/port.rs` | C,H | -| [d38cce2d8be5](https://github.com/aurora-silicon/linux/commit/d38cce2d8be54bdbc01e90e1a92ef3dd65ac0640) | DjDeveloperr | drm/asahi: announce withheld G17 compute doorbells whenever retirement stalls [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [2d8286101c86](https://github.com/aurora-silicon/linux/commit/2d8286101c8631939cb13ce1b7b14c9041856ca6) | DjDeveloperr | drm/asahi: build the G17 driver without warnings [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | V | -| [9a0ed807e4d3](https://github.com/aurora-silicon/linux/commit/9a0ed807e4d3691a5ea46fce2a2424295f8af6ea) | DjDeveloperr | drm/asahi: renew G17 job deadlines while the GPU keeps retiring work [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/job.rs` | F,Q | -| [afbfbc0b89ca](https://github.com/aurora-silicon/linux/commit/afbfbc0b89ca4779b13cefff5bed0b4036751b2c) | DjDeveloperr | drm/asahi: kill closed G17 contexts only while no other work runs [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs` | F,Q | -| [31279abf0648](https://github.com/aurora-silicon/linux/commit/31279abf0648c00e454b181f01d65b277a32fb90) | DjDeveloperr | drm/asahi: fail G17 render groups a recovery dropped out of order at once [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/render.rs` | F,Q | -| [7012a59ed129](https://github.com/aurora-silicon/linux/commit/7012a59ed129baf969d83a3aa4d90f2a6cb410f2) | DjDeveloperr | drm/asahi: announce withheld G17 compute doorbells after a recovery [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/recovery.rs` | F,Q | -| [8e257af33a6c](https://github.com/aurora-silicon/linux/commit/8e257af33a6c4036ee56bc8a628e733dba2bd525) | DjDeveloperr | drm/asahi: move the G17 cumulative-signals feature to bit 29 [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/sync_output.rs` | C,R,H | -| [76d4e880149e](https://github.com/aurora-silicon/linux/commit/76d4e880149e5592396001f728f7803efb616377) | DjDeveloperr | drm/asahi: build the G17 compute QID budget test against the variant constructor [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/runtime.rs` | V | -| [d0da7e79dc9c](https://github.com/aurora-silicon/linux/commit/d0da7e79dc9c99020d109e95d18256cd5b3d6bc2) | DjDeveloperr | drm/asahi: check the G17 QID floor test against the open-queue compute budget [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/runtime.rs` | V | -| [18b408b7368b](https://github.com/aurora-silicon/linux/commit/18b408b7368b9470c22d92c9afe1991d0fe608ba) | DjDeveloperr | drm/asahi: check the G17 admission churn test against its deadline, not the clock [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/preparation.rs` | V | -| [de1be1b4b5b1](https://github.com/aurora-silicon/linux/commit/de1be1b4b5b110ae60877f77aa1637a920333579) | DjDeveloperr | Merge integration/aurora into fix/g17-recovery-dropped-groups-20261025 [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — MERGE | V | - -### Other Neo and shared-support commits - -Each listed alias has the stated current mechanism/gate. Device-specific data -uses the T6040 counterpart, not literal Neo register/DT values. - -| Commits / encountered aliases | Author | Improvement / record | T6040 after ports — evidence key and changed source | Measurement | -| --- | --- | --- | --- | --- | -| [6a5d96e61fa5](https://github.com/aurora-silicon/linux/commit/6a5d96e61fa52810e709a0b8bb5e9988df78a7d7) | Sasha Finkelstein | cpufreq: apple-soc: Calculate frequency as a 64-bit value | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [a861779b92c2](https://github.com/aurora-silicon/linux/commit/a861779b92c259c0a5ba7ec3fd512ad7bda1b8d4) | Asahi Lina | rust: soc: apple: rtkit: Add Apple RTKit abstraction | Active — RTKIT; `drivers/soc/apple/Kconfig` | B,F | -| [4b42187aef53](https://github.com/aurora-silicon/linux/commit/4b42187aef53c266b472e731e4f8e0a1fe0de3a7) | Janne Grunau | rust: soc: apple: rtkit: Add ASC CPU control register | Active — RTKIT; `rust/kernel/soc/apple/rtkit.rs` | B,F | -| [6a2c57b5a719](https://github.com/aurora-silicon/linux/commit/6a2c57b5a719f7c71fe6252865e4f036f6d27a64) | Sasha Finkelstein | soc: apple: rtkit: Add apple_rtkit_has_endpoint() | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [b7fbb2fde4ea](https://github.com/aurora-silicon/linux/commit/b7fbb2fde4eaa0ac53e46dcb76a835fdc9cd9477) | Sasha Finkelstein | rust: soc: apple: rtkit: Add apple_rtkit_has_endpoint | Active — RTKIT; `rust/kernel/soc/apple/rtkit.rs` | B,F | -| [bba00880a59b](https://github.com/aurora-silicon/linux/commit/bba00880a59b144155716928066b12cc5751dd52) | Sasha Finkelstein | rust: soc: apple: Add Apple mailbox abstractions | Active — MBOX; `drivers/soc/apple/Kconfig` | B,O | -| [883657fe64b3](https://github.com/aurora-silicon/linux/commit/883657fe64b3a62fa36c90666b0a00a4e5093166) | Sasha Finkelstein | soc: apple: Add support for the PMP co-processor | Active — PMP; `drivers/soc/apple/Kconfig` | P,B | -| [fccd1dbe8ba8](https://github.com/aurora-silicon/linux/commit/fccd1dbe8ba820d4d9f5d1a624987e2820035204), [04841b120bbf](https://github.com/aurora-silicon/linux/commit/04841b120bbf7a2fb454cbfa984647e867b64848), [da7aa98b1aae](https://github.com/aurora-silicon/linux/commit/da7aa98b1aae834db5f7f4a8396afc39099d1b2f) | Janne Grunau | fixup! soc: apple: Add support for the PMP co-processor | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [c81971a6c4c7](https://github.com/aurora-silicon/linux/commit/c81971a6c4c706b2f5783653a2df8d79782d4efe) | Asahi Lina | drm/scheduler: Fix UAF in drm_sched_fence_get_timeline_name | Active — DRM; `drivers/gpu/drm/scheduler/sched_entity.c` | C,H,M,F | -| [94bfb56baeeb](https://github.com/aurora-silicon/linux/commit/94bfb56baeeb02bc9c9ce8616aef0bd72a5de3f2) | Asahi Lina | rust: drm: sched: Add GPU scheduler abstraction | Active — DRM; `rust/kernel/drm/mod.rs` | B,M | -| [1340031e447c](https://github.com/aurora-silicon/linux/commit/1340031e447c56ec9d0f8ea7a68436a623fafc91) | Asahi Lina | drm/asahi: Add the Asahi driver for Apple AGX GPUs | Active — MEM; `drivers/gpu/drm/Kconfig` | M,D | -| [af74e2af96bc](https://github.com/aurora-silicon/linux/commit/af74e2af96bc483417f5015f98f4aa54e355851d) | Janne Grunau | drm/asahi: v6.19 probe change | Active — MEM; `drivers/gpu/drm/asahi/driver.rs` | M,D | -| [8c048a0ab849](https://github.com/aurora-silicon/linux/commit/8c048a0ab84971117a5f641ba2185b51e0b12059) | Janne Grunau | drm/asahi: Move unsafe data initialization to driver code | Active — MEM; `drivers/gpu/drm/asahi/driver.rs` | M,D | -| [a95f0620d24c](https://github.com/aurora-silicon/linux/commit/a95f0620d24c456c74d11261e329df054bf70e7b) | Janne Grunau | drm/asahi: RiiR page tables | Active — MEM; `drivers/gpu/drm/asahi/alloc.rs` | M,D | -| [19e9dc7ccb94](https://github.com/aurora-silicon/linux/commit/19e9dc7ccb9499ac3c92e7764edc2312656dc9d5) | Janne Grunau | drm/asahi: Implement ASAHI_BIND_SINGLE_PAGE (mmu/pgtbl) | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [96ce16e432a2](https://github.com/aurora-silicon/linux/commit/96ce16e432a213f7ae185870826697900c9acc60) | Asahi Lina | drm/asahi: pgtable: Add dumper | Active — MEM; `drivers/gpu/drm/asahi/pgtable.rs` | M,D | -| [ad2fb060c5dc](https://github.com/aurora-silicon/linux/commit/ad2fb060c5dcce503bc099062ff54c237b6866d0) | Asahi Lina | drm/asahi: pgtable: Add helpers for decoding PTE perms | Active — MEM; `drivers/gpu/drm/asahi/pgtable.rs` | M,D | -| [7b55670c3a59](https://github.com/aurora-silicon/linux/commit/7b55670c3a59219e37192a1f5771a86217008808) | Janne Grunau | drm/asahi: Copy tyr's mmu/vm/range.rs | Active — MEM; `drivers/gpu/drm/asahi/asahi.rs` | M,D | -| [9d16f582e208](https://github.com/aurora-silicon/linux/commit/9d16f582e2085935f893f99326fbcc0346c998bb) | Janne Grunau | drm/asahi: Switch gpuvm to DRM_GPUVM_IMMEDIATE_MODE | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M,D | -| [829551e64f1a](https://github.com/aurora-silicon/linux/commit/829551e64f1a350adddb71751be16a0243e1b666) | Janne Grunau | drm/asahi: MemFlag change in v6.19 | Active — MEM; `drivers/gpu/drm/asahi/gpu.rs` | M,D | -| [f5b02e71cd67](https://github.com/aurora-silicon/linux/commit/f5b02e71cd671ac4e3ceff54bbd1b25e7f20ae9d) | Janne Grunau | drm/asahi: rtkit pin adaptation | Active — MEM; `drivers/gpu/drm/asahi/gpu.rs` | M,D | -| [4220285e8415](https://github.com/aurora-silicon/linux/commit/4220285e8415cc772736b57f0dface3dcdbbee4f) | Janne Grunau | drm/asahi: select APPLE_PMP_REPORT | Active — PMP; `drivers/gpu/drm/asahi/Kconfig` | P,B | -| [30d957799282](https://github.com/aurora-silicon/linux/commit/30d9577992828e8d2f8345cc4b34a19098ca068c) | Janne Grunau | drm/asahi: Improve VM bind performance for large BOs | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [22e9a0b69598](https://github.com/aurora-silicon/linux/commit/22e9a0b69598bc23e66d72d1e51bd40396966dc1) | Janne Grunau | drm/asahi: `use` formatting annd rename changes | Active — MEM; `drivers/gpu/drm/asahi/driver.rs` | M,D | -| [f014fcba9d71](https://github.com/aurora-silicon/linux/commit/f014fcba9d71972198f28c3d5315605669073bea) | Janne Grunau | drm/asahi: v7.1 Mmio relaxed changes | Active — MEM; `drivers/gpu/drm/asahi/regs.rs` | M,D | -| [20dec7b1eaa9](https://github.com/aurora-silicon/linux/commit/20dec7b1eaa9a31dc67a8216d338bb10a452659d) | DesktopECHO | drm/asahi: Clean up deferred BOs when dropping a VM | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M | -| [e07ff81ee812](https://github.com/aurora-silicon/linux/commit/e07ff81ee812fd84603a498beaa1bb25eb629caa) | Janne Grunau | fixup! rust: soc: apple: rtkit: Add Apple RTKit abstraction | Active — RTKIT; `rust/kernel/soc/apple/rtkit.rs` | B,F | -| [44a01c258b11](https://github.com/aurora-silicon/linux/commit/44a01c258b111368f3c75848553ae1a658f46013) | Janne Grunau | drm/asahi: Adjustment for v7.2 + partial drm-rust v7.3 | Active — MEM; `drivers/gpu/drm/asahi/alloc.rs` | M,D | -| [23b564dd6c09](https://github.com/aurora-silicon/linux/commit/23b564dd6c09982106e2b5cc5ce80c25010c354a) | Janne Grunau | drm/asahi: pgtable: Drop more dev coredump related code | Active — MEM; `drivers/gpu/drm/asahi/pgtable.rs` | M,D | -| [b7f0faf4da36](https://github.com/aurora-silicon/linux/commit/b7f0faf4da367be4a29146f5eb82b795dc2f270d), [afffea42ac29](https://github.com/aurora-silicon/linux/commit/afffea42ac29a1f6f8b3ef3819691c1d7b0a259a) | Hojun Cho | pmdomain: apple: Add missing spin_lock_init | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [0de0a3740a9a](https://github.com/aurora-silicon/linux/commit/0de0a3740a9a26973e7e49ad1cd87981914c457a), [919b934ff719](https://github.com/aurora-silicon/linux/commit/919b934ff7191fa72fab73ecf4ac785dd570c3c3), [ae512e4edf8b](https://github.com/aurora-silicon/linux/commit/ae512e4edf8b96d5eacd79b11fb190837d311b1b) | Ryan Murray | arm64: dts: apple: t8140-pmgr: Add ANS, SPMI, PMP and SMC I2C domains | Active — PMP | P,B | -| [2740578bc68c](https://github.com/aurora-silicon/linux/commit/2740578bc68c410528172a54f9e2e19d35c255d1), [c96a7ffae393](https://github.com/aurora-silicon/linux/commit/c96a7ffae39306507c405d49a3a19927eab289fe), [5578a4e73d10](https://github.com/aurora-silicon/linux/commit/5578a4e73d10d63615ed1eaaf5a7215310df19b8) | Ryan Murray | arm64: dts: apple: t8140: Add CPU frequency scaling | Active translated data — FW | B,P | -| [e7e641d03183](https://github.com/aurora-silicon/linux/commit/e7e641d03183aa76578a1504a4758da6b71c968f), [b58c399f44d7](https://github.com/aurora-silicon/linux/commit/b58c399f44d7499ed62c907efda7b0017f421baf), [f9ec3820d63d](https://github.com/aurora-silicon/linux/commit/f9ec3820d63d57ddb9790ac168a5642efc11f21c) | Ryan Murray | arm64: dts: apple: t8140: Use the Tahiti CPU compatibles and L1 cache sizes | Active translated data — FW | B,P | -| [c702ccc166bb](https://github.com/aurora-silicon/linux/commit/c702ccc166bbe593718a8b4d8a51063e6c5bc102), [f104bb09ce2a](https://github.com/aurora-silicon/linux/commit/f104bb09ce2abf48baa4cf5028b9224141cfdd00), [118ffba5b7b0](https://github.com/aurora-silicon/linux/commit/118ffba5b7b06b9786e24dfab819caa1fb1a2333) | Ryan Murray | arm64: dts: apple: t8140-j700: Enable ANS, SMC and CPU frequency scaling | Active translated data — FW | B,P | -| [5e5d5289f17e](https://github.com/aurora-silicon/linux/commit/5e5d5289f17ede272d495e7e4db117d47c6523a3), [dd366e9d3a8e](https://github.com/aurora-silicon/linux/commit/dd366e9d3a8e05ab209c7ebe1b28413820f018d4) | Marcelo Alcantara | iommu: apple-dart: raise MAX_DARTS_PER_DEVICE to 8 | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [e1817d4152f5](https://github.com/aurora-silicon/linux/commit/e1817d4152f57baca92148c8bbc48fe9b0a8e9f9), [97cdb08431f3](https://github.com/aurora-silicon/linux/commit/97cdb08431f3eef20c2e24c41166bc5dee9e9976), [162b64627bbc](https://github.com/aurora-silicon/linux/commit/162b64627bbcb2fa0ae83cbb6cbf86825ced3e33), [70dfd8f93d3c](https://github.com/aurora-silicon/linux/commit/70dfd8f93d3cac6d6ac7ad26909ca6378fd6a2b4) | Ryan Murray | iommu/apple-dart: Check devm_memremap() for an error pointer | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [f57d90040433](https://github.com/aurora-silicon/linux/commit/f57d9004043387ed6c437ddf0afcfcc1bb49f2fd), [6fa300933bb1](https://github.com/aurora-silicon/linux/commit/6fa300933bb1f05c9a49bddc05f8ea3b42c47d35), [79379798f12f](https://github.com/aurora-silicon/linux/commit/79379798f12fdb32ba79f74b0524cfc4f0170471) | Ryan Murray | iommu/apple-dart: Support T8140 DARTs and firmware-owned stream roots | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [6ec845b2f381](https://github.com/aurora-silicon/linux/commit/6ec845b2f3812090ed39893f8e26999c757950c9), [3bd878053ca7](https://github.com/aurora-silicon/linux/commit/3bd878053ca7aed1e4af56bc14c339b8bddc6d9c), [6898f34ac7bd](https://github.com/aurora-silicon/linux/commit/6898f34ac7bd349ce29b60fb9785168950c5ed69), [fb7b8edf4ee1](https://github.com/aurora-silicon/linux/commit/fb7b8edf4ee19a35c07c1a2c6aa6b8e65c71777b) | DjDeveloperr | arm64: dts: apple: t8140-pmgr: Add the GPU power domains [#171](https://github.com/aurora-silicon/linux/pull/171) | Active translated data — FW | B,P | -| [cc2d03580b0a](https://github.com/aurora-silicon/linux/commit/cc2d03580b0a68ca0f9779adebd646645813d673), [ea4abd222b2f](https://github.com/aurora-silicon/linux/commit/ea4abd222b2fa2473dba79ca4a91a220e8cb20ba), [52fac306b907](https://github.com/aurora-silicon/linux/commit/52fac306b90783087af17af7ba3e2fc6570122e5), [e77d74a6be76](https://github.com/aurora-silicon/linux/commit/e77d74a6be7645e64b9b50bb51713e72a08c9520) | DjDeveloperr | arm64: dts: apple: t8140: Add the GPU [#171](https://github.com/aurora-silicon/linux/pull/171) | Active translated data — FW | B,P | -| [8284bd4d3914](https://github.com/aurora-silicon/linux/commit/8284bd4d3914ce296a83c38753a69b07e1c10a0e), [29b0b3a54664](https://github.com/aurora-silicon/linux/commit/29b0b3a546641438b14da95054ae136540465de8), [54124e3efacb](https://github.com/aurora-silicon/linux/commit/54124e3efacba7ba530e742cb2f297bbdeb719fa), [f4a46cd97b2a](https://github.com/aurora-silicon/linux/commit/f4a46cd97b2a3e70875d76e3cf2b82f3959fd0f5) | DjDeveloperr | arm64: dts: apple: t8140-j700: Enable the GPU [#171](https://github.com/aurora-silicon/linux/pull/171) | Active translated data — FW | B,P | -| [31ee8e23124d](https://github.com/aurora-silicon/linux/commit/31ee8e23124d77700e47cabc0e8645404187fd74), [5b85b301d4ee](https://github.com/aurora-silicon/linux/commit/5b85b301d4ee38256c757299a0c58c4a79a531a7), [727284277d33](https://github.com/aurora-silicon/linux/commit/727284277d335215edd48b5f74a6f4d4e949ff3a), [9c10d7198c8e](https://github.com/aurora-silicon/linux/commit/9c10d7198c8e56b16da35914ffde0eecb6bfb525) | DjDeveloperr | arm64: dts: apple: t8140: describe the GPU mailboxes as ASCWrap v6 [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MBOX | B | -| [dbc9f011ec91](https://github.com/aurora-silicon/linux/commit/dbc9f011ec91fb72089a45487891bfd7c5a8939d), [86fba21bf7c9](https://github.com/aurora-silicon/linux/commit/86fba21bf7c926033306cb2dc5b6d5bcfbbe30ce), [018ab982644a](https://github.com/aurora-silicon/linux/commit/018ab982644a6eff94a6020d8910e9c8c187d6a2) | Ryan Murray | arm64: dts: apple: t8140: Add CPU energy model and thermal sensor cells | Active translated data — FW | B,P | -| [b15c2faba082](https://github.com/aurora-silicon/linux/commit/b15c2faba08274f02bf9a11e0e15eef470017dbd), [d693f725d774](https://github.com/aurora-silicon/linux/commit/d693f725d77422774ae683701732562a84789439), [d69c31212d2b](https://github.com/aurora-silicon/linux/commit/d69c31212d2b93b6396775c7890d5734f962c486) | Ryan Murray | arm64: dts: apple: t8140-j700: Add CPU thermal zones | Active translated data — FW | B,P | -| [25b99e9b6a75](https://github.com/aurora-silicon/linux/commit/25b99e9b6a75a9e783d7b5f04ee60b4f97fe24ed), [1ffe37e7af24](https://github.com/aurora-silicon/linux/commit/1ffe37e7af241fb91ecd7a8d17c946fd0a5d8ecc), [64eff8a46206](https://github.com/aurora-silicon/linux/commit/64eff8a46206613ff354cbeaff49d1354e4c1f52) | Ryan Murray | arm64: dts: apple: t8140: Drop the J700 CPU thermal policy property | Active translated data — FW | B,P | -| [db87f30fa4e7](https://github.com/aurora-silicon/linux/commit/db87f30fa4e7a322d655989316aef41a00fc46e5), [cf7dc9d0474c](https://github.com/aurora-silicon/linux/commit/cf7dc9d0474cc53e3716948365b72bacc848d5e9), [8ba3c01c426a](https://github.com/aurora-silicon/linux/commit/8ba3c01c426a8efd643289689493835c51b8937d) | Ryan Murray | arm64: dts: apple: t8140: Add measured CPU capacity values | Active translated data — FW | B,P | -| [6bb7669702ed](https://github.com/aurora-silicon/linux/commit/6bb7669702edf26c05f2be84f303d0fd612487b2), [2623391b533d](https://github.com/aurora-silicon/linux/commit/2623391b533de7f038408e57e3084a75f765b56c), [3dd2554de0c5](https://github.com/aurora-silicon/linux/commit/3dd2554de0c5b6e9d16a3809186872847987de6a) | Ryan Murray | arm64: dts: apple: enable the PMP fast-die limiter on J700 [#179](https://github.com/aurora-silicon/linux/pull/179) | Active — PMP | P,B | -| [47ed624515f4](https://github.com/aurora-silicon/linux/commit/47ed624515f40f37b39230c3b1b20bb6678c788a), [66988937c0d6](https://github.com/aurora-silicon/linux/commit/66988937c0d62aeb1ed828379cb83bbc68581afc), [39a036ead934](https://github.com/aurora-silicon/linux/commit/39a036ead934c701af76e05eebd72b102810861c) | Ryan Murray | arm64: dts: apple: t8140-j700: enable the PMP nodes once | Active — PMP | P,B | -| [a539d62f765f](https://github.com/aurora-silicon/linux/commit/a539d62f765fb0e8153f2be0fa8fb33058f6df9a), [c1af50661b44](https://github.com/aurora-silicon/linux/commit/c1af50661b44940df0c5747ae7dfca25c871bbcb), [d30b0dfcf358](https://github.com/aurora-silicon/linux/commit/d30b0dfcf35813ce52d935e24e7e6d46349ec3cd) | Ryan Murray | arm64: dts: apple: t8140-j700: Keep the idle E cluster out of its lowest OPP | Active translated data — FW | B,P | -| [fb68b124b886](https://github.com/aurora-silicon/linux/commit/fb68b124b8865e39b72b2387e7f739856f72cc26), [76dd6fb9e643](https://github.com/aurora-silicon/linux/commit/76dd6fb9e643747eb61c3b409c93b1ce2975184e), [2d51c6aada40](https://github.com/aurora-silicon/linux/commit/2d51c6aada40a6c97ae81464eea6935ebf70ba95) | Ryan Murray | arm64: dts: apple: t8140: Describe the memory cache controller | Active — MCC | M,P | -| [5811648de37d](https://github.com/aurora-silicon/linux/commit/5811648de37d1bcd66a5294f44191da8880947b2), [840606faf824](https://github.com/aurora-silicon/linux/commit/840606faf824b4f6ea862f8475e7edaff9af4150), [b5b71dfc50b2](https://github.com/aurora-silicon/linux/commit/b5b71dfc50b2bfbf5800a76c540f878924a678cb), [ed31b37fb032](https://github.com/aurora-silicon/linux/commit/ed31b37fb0327ee7c20961fce2785ed3d4ddb154) | DjDeveloperr | arm64: dts: apple: t8140: describe the PMC and report GFX to the PMP [#212](https://github.com/aurora-silicon/linux/pull/212) [#219](https://github.com/aurora-silicon/linux/pull/219) | Active after port — PMC | P,C,R | -| [15f21cbc0d4b](https://github.com/aurora-silicon/linux/commit/15f21cbc0d4bbbc901454d1e69f53084e1c5dc18), [6cab4decfb66](https://github.com/aurora-silicon/linux/commit/6cab4decfb664524936da59558bc39407b633b9a), [0272b63e30f0](https://github.com/aurora-silicon/linux/commit/0272b63e30f07b8c1a496cb01f5aa74e2cc1ff93) | Ryan Murray | arm64: dts: apple: t8140: keep the GPU on its PMGR state [#219](https://github.com/aurora-silicon/linux/pull/219) | Active translated data — FW | B,P | -| [0a44c956dde2](https://github.com/aurora-silicon/linux/commit/0a44c956dde28aad0bd37b66c6ff5d8096e5676d), [8fa836c5de81](https://github.com/aurora-silicon/linux/commit/8fa836c5de8111ab90d8f2a746526d2cd487afb7), [ae8e780a5b7d](https://github.com/aurora-silicon/linux/commit/ae8e780a5b7dedcb4a31adbd106fb9f9dbff8be0) | Ryan Murray | arm64: dts: apple: t8140: describe the PMC's DCS limit [#219](https://github.com/aurora-silicon/linux/pull/219) | Gated — DCS | P | -| [84eb6b53da34](https://github.com/aurora-silicon/linux/commit/84eb6b53da3453d7c2838bd2a41779e0a9bce181), [f01e1cde7d9f](https://github.com/aurora-silicon/linux/commit/f01e1cde7d9f270e156ee77c6819466757b938f6), [a037985ac960](https://github.com/aurora-silicon/linux/commit/a037985ac9605eb76fe51a05b172b022ac1f0005) | Ryan Murray | arm64: dts: apple: t8140-j700: limit the DCS vote when the die runs hot [#219](https://github.com/aurora-silicon/linux/pull/219) | Gated — DCS | P | -| [4f6bac29d934](https://github.com/aurora-silicon/linux/commit/4f6bac29d9349ced88686239f259ab2747207708), [e10ab48a4590](https://github.com/aurora-silicon/linux/commit/e10ab48a4590c23c664546f524650310222b3a35), [c1bae63595e8](https://github.com/aurora-silicon/linux/commit/c1bae63595e8fc7b18e79664ee6aa6b4536f5d95) | Ryan Murray | arm64: dts: apple: t8140: Keep the GPU power state on across sleep | Active translated data — FW | B,P | -| [01d1be596840](https://github.com/aurora-silicon/linux/commit/01d1be596840358a7258d87fc91d3201a3287313), [8b6371b5500d](https://github.com/aurora-silicon/linux/commit/8b6371b5500d062c00f71d46a0bccbcbed111edd) | Ryan Murray | iommu: apple-dart: Program T8140 and T8142 streams individually | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [2398a03f445e](https://github.com/aurora-silicon/linux/commit/2398a03f445e8f9f65fa9f86748a3deeab3e1b1f), [69c39f85461e](https://github.com/aurora-silicon/linux/commit/69c39f85461e8944dff387eab703c58ea6c6ed49), [1d2904fd3301](https://github.com/aurora-silicon/linux/commit/1d2904fd3301c63620f07c81ae79f2486a81a9a6) | Dj | iommu/apple-dart: defer locked root publication until attach | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [ae5849165749](https://github.com/aurora-silicon/linux/commit/ae58491657494b0f56ec0113a3aa43612648e242), [44c7f32baad0](https://github.com/aurora-silicon/linux/commit/44c7f32baad0511e6f3ae5c2ffdd863eec8e5d23), [dc9d13edb0e5](https://github.com/aurora-silicon/linux/commit/dc9d13edb0e5b18c61d25240ed4ba532afb8d11f) | Acelogic | iommu/apple-dart: accept T8142 firmware slots that mirror Linux mappings | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [1917cbce81cb](https://github.com/aurora-silicon/linux/commit/1917cbce81cb806498b0a5a3f5e636c851255408), [61dfeb8f659d](https://github.com/aurora-silicon/linux/commit/61dfeb8f659d36149d3dc6162d304136b108c5b9), [c361702757bf](https://github.com/aurora-silicon/linux/commit/c361702757bfccb9183ed79be0c6200fb3722e6f) | Ryan Murray | iommu/apple-dart: defer publication until locked roots are known | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [c74dc14619ec](https://github.com/aurora-silicon/linux/commit/c74dc14619ec5467789855d89c0ef224a3655093), [35f59a797e91](https://github.com/aurora-silicon/linux/commit/35f59a797e914308f4ae289e87551ad97997a497), [d957b0bd713b](https://github.com/aurora-silicon/linux/commit/d957b0bd713bbf4617f54f5ed0d274964e9af6c9) | Ryan Murray | iommu/apple-dart: validate software mappings against inherited slots | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [f89a3c873999](https://github.com/aurora-silicon/linux/commit/f89a3c87399911e0faa4f66091b2e7dcc1145825), [64013b9557ab](https://github.com/aurora-silicon/linux/commit/64013b9557abadab17883a7e697f32f32e0c4160), [707f28a4c399](https://github.com/aurora-silicon/linux/commit/707f28a4c399092ba01bd281a3f0b6623f7bb223) | Ryan Murray | iommu/apple-dart: import firmware translations on T8140 | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [99633bd5454e](https://github.com/aurora-silicon/linux/commit/99633bd5454eac0e455812358be63b4f08d78a98), [c29b618f6340](https://github.com/aurora-silicon/linux/commit/c29b618f6340b4ede94747a266f86a844344e769), [ebcff4ba64dd](https://github.com/aurora-silicon/linux/commit/ebcff4ba64dd90983cc8150b0f46fda82b5fb9f0) | Ryan Murray | iommu: apple-dart: retain inherited translations before reservation setup | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [8d2d7790d8d5](https://github.com/aurora-silicon/linux/commit/8d2d7790d8d552f01ce2bf10f922aaccbf7918aa), [dbd410951406](https://github.com/aurora-silicon/linux/commit/dbd4109514067a2ed8140d8138bee68453272f02), [8478ae014201](https://github.com/aurora-silicon/linux/commit/8478ae0142014d170a62df6dd94cc66bd989627b) | Chris Kearney | iommu/apple-dart: restore legacy locked display domain handoff | Active — DART; `drivers/iommu/Kconfig` | D,B | -| [0297adcecc72](https://github.com/aurora-silicon/linux/commit/0297adcecc72a563b5cfb3ca3e483f71422fb77c), [b71446526889](https://github.com/aurora-silicon/linux/commit/b71446526889b27c60461685c3c320b7e123155d), [2bad3dba632f](https://github.com/aurora-silicon/linux/commit/2bad3dba632ff85537392b79255fc527baf01746) | Ryan Murray | iommu: apple-dart: keep inherited firmware translations visible before attach | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [80ce713f5251](https://github.com/aurora-silicon/linux/commit/80ce713f52511abe4d35b35bfac0f10f9072d401), [8ece17f482f1](https://github.com/aurora-silicon/linux/commit/8ece17f482f11da6e81915b98fc8b93ed796504a), [a64a4771b276](https://github.com/aurora-silicon/linux/commit/a64a4771b27602bf5a72b413b6bc9a868892992a) | Ryan Murray | iommu: apple-dart: invalidate T8110 ranges by device DVA [#221](https://github.com/aurora-silicon/linux/pull/221) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [cef9a23aa45e](https://github.com/aurora-silicon/linux/commit/cef9a23aa45e3ac6b352e6c2bd839935374ae351), [253ba9bebf47](https://github.com/aurora-silicon/linux/commit/253ba9bebf470c0d78845103c93b937f2d9cdfb3), [dd5ac6fdffb0](https://github.com/aurora-silicon/linux/commit/dd5ac6fdffb03d048df510198af6e8d53dceb17d) | Ryan Murray | iommu: apple-dart: leave live firmware translations out of invalidates [#221](https://github.com/aurora-silicon/linux/pull/221) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [0a73b0299574](https://github.com/aurora-silicon/linux/commit/0a73b0299574da4c42659024b4a0e8390c36d2d8), [bc6682c215ad](https://github.com/aurora-silicon/linux/commit/bc6682c215adc6febfb86c9fa2ed0fb69657dcc2), [9c512b25f55e](https://github.com/aurora-silicon/linux/commit/9c512b25f55eaf6332b590e5a205ca7d55de12c8) | Ryan Murray | iommu: apple-dart: invalidate client-ranged T8140 streams again [#232](https://github.com/aurora-silicon/linux/pull/232) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [ae812d47ea17](https://github.com/aurora-silicon/linux/commit/ae812d47ea176c9bb0b4ddccc17349fee5afbf1a), [fe15676f6e03](https://github.com/aurora-silicon/linux/commit/fe15676f6e03395f4947cbffb2d49fbee17ea5f9), [4ca4ba380552](https://github.com/aurora-silicon/linux/commit/4ca4ba3805528f5370bbe6bab3d8dbb8f7f9226c) | Ryan Murray | iommu: apple-dart: invalidate four-level T8140 streams by DVA range [#237](https://github.com/aurora-silicon/linux/pull/237) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [a17634424697](https://github.com/aurora-silicon/linux/commit/a17634424697b082221d141ef61d9689460eebf8), [d1a5c65245b8](https://github.com/aurora-silicon/linux/commit/d1a5c65245b87c457a8fc4b4190d440e9bc38b8d) | Sasha Finkelstein | soc: apple: rtkit: Add tracekit endpoint. | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [ff7d81511780](https://github.com/aurora-silicon/linux/commit/ff7d81511780770e944ebe6e66ed56a06b497a31) | Ryan Murray | drm/asahi: Adapt to the Linux 7.3 Rust APIs [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — MEM; `drivers/gpu/drm/asahi/debug.rs` | M,D | -| [588c231eaa54](https://github.com/aurora-silicon/linux/commit/588c231eaa54f4a34872519517fbbcc079b41175) | Ryan Murray | soc: apple: Adapt the Rust SEP, PMP and AOP drivers to Linux 7.3 | Active — PMP; `drivers/soc/apple/aop.rs` | P,B | -| [c025e6cd0615](https://github.com/aurora-silicon/linux/commit/c025e6cd0615e416e0a06ba997e8d9f417a3e185), [af0890cf33cf](https://github.com/aurora-silicon/linux/commit/af0890cf33cf899cf0005daf6138da1dfe573c19) | Ryan Murray | soc: apple: rtkit: Harden syslog buffer handling | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [3a8760c28c33](https://github.com/aurora-silicon/linux/commit/3a8760c28c3341380e105c75bb48e76c895d3f3d), [c01af1b31c52](https://github.com/aurora-silicon/linux/commit/c01af1b31c523b09106c4bed43f8bb7cba65cbfc) | Ryan Murray | soc: apple: rtkit: Keep a live shared buffer on a repeated request | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [495b2f037c28](https://github.com/aurora-silicon/linux/commit/495b2f037c284f4b7b10f54c90a7d34fbf5e99fa), [6b7e37786882](https://github.com/aurora-silicon/linux/commit/6b7e37786882db803e9de1352a2af623044f9237), [1fc9ea993905](https://github.com/aurora-silicon/linux/commit/1fc9ea9939058bc1307565f036506da30dd62908) | Ryan Murray | soc: apple: rtkit: Serialize receiver ownership through teardown | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [335eaeb9b9f1](https://github.com/aurora-silicon/linux/commit/335eaeb9b9f147230f464a140287e820b1d78518), [0593ad398a6e](https://github.com/aurora-silicon/linux/commit/0593ad398a6eb83e2e2ce9dd25bf1fd0768e5bcd) | Ryan Murray | soc: apple: rtkit: Add apple_rtkit_free_retaining_buffers() | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [e796f5fbaf06](https://github.com/aurora-silicon/linux/commit/e796f5fbaf0698b478c43ba6eb15e046c9cc6244), [8527354650e8](https://github.com/aurora-silicon/linux/commit/8527354650e810479ceb0a58417e683b2dee852c) | Ryan Murray | soc: apple: rtkit: Allow streaming-mapped shared buffers | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [9191296f1898](https://github.com/aurora-silicon/linux/commit/9191296f1898d1acf2d0cd500230ae80c9e3e0ca), [88e3c5c07943](https://github.com/aurora-silicon/linux/commit/88e3c5c07943fedf73e45f88b270f8550d7691ae) | Ryan Murray | soc: apple: rtkit: Support adopting a running co-processor | Active — RTKIT; `drivers/soc/apple/rtkit-internal.h` | B,F | -| [1932e1e1b184](https://github.com/aurora-silicon/linux/commit/1932e1e1b18437408e77dcc1d23d6d966b0fdb98), [f232f22bef54](https://github.com/aurora-silicon/linux/commit/f232f22bef54eb6fbd848a1374e49fe91035b397) | Ryan Murray | soc: apple: rtkit: Report crashes of an adopted co-processor | Active — RTKIT; `drivers/soc/apple/rtkit-internal.h` | B,F | -| [b38944203ab0](https://github.com/aurora-silicon/linux/commit/b38944203ab0ad8ec01c26bd67df67455fcc98c3), [4f0416f2c43b](https://github.com/aurora-silicon/linux/commit/4f0416f2c43ba895b3c34a263cf5d0e070095a55), [2768025e0f1d](https://github.com/aurora-silicon/linux/commit/2768025e0f1d9792f84e9fbb99f6c0b155c0a22a), [35b2acbf474d](https://github.com/aurora-silicon/linux/commit/35b2acbf474d8505c3edc1a2749a8d6fbfaf7a09) | Ryan Murray | pmdomain: apple: Print the read-back state on a power state timeout | Active — OBS; `drivers/pmdomain/apple/pmgr-pwrstate.c` | O,F | -| [768a665d0ca1](https://github.com/aurora-silicon/linux/commit/768a665d0ca138d0f2c80029fd1d272c11468e2e), [9c5b8fe6d6d6](https://github.com/aurora-silicon/linux/commit/9c5b8fe6d6d6a93f7c4bbbd14026fd93d5f6aa73), [afe19efeff9c](https://github.com/aurora-silicon/linux/commit/afe19efeff9c466486fb723f7066f86b9a3e71d5), [9dc79fb25c92](https://github.com/aurora-silicon/linux/commit/9dc79fb25c9294bd7a8ecb00acc9bcea379c3d1a) | Ryan Murray | pmdomain: apple: Mask BUSY in power state writes and ratelimit errors | Active — PMGR; `drivers/pmdomain/apple/pmgr-pwrstate.c` | B,F | -| [a6aa625a9b35](https://github.com/aurora-silicon/linux/commit/a6aa625a9b35b96ba4ffc0749d55a0f21fe9e426), [03f4792761f4](https://github.com/aurora-silicon/linux/commit/03f4792761f42c3a4581be4b585a479cfc65bfc3), [f82e88f4049e](https://github.com/aurora-silicon/linux/commit/f82e88f4049ed6ea278717be6d922f8e347aab13), [928641d26be3](https://github.com/aurora-silicon/linux/commit/928641d26be3083dc06c0de072ce99537fa059b7) | DjDeveloperr | soc: apple: rtkit: Support co-processors that place their own buffers [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [e52b589758bd](https://github.com/aurora-silicon/linux/commit/e52b589758bd9c72db728ef41947aadc2d1eec3f), [a8e468104169](https://github.com/aurora-silicon/linux/commit/a8e46810416977c034c45d805c0b504cfdab9a6a), [c07d044a0311](https://github.com/aurora-silicon/linux/commit/c07d044a03117705721c78500bc36489ea34e6c4) | Ryan Murray | soc: apple: rtkit: recognise an initial crash log in adopted sessions | Active — RTKIT; `drivers/soc/apple/rtkit-crashlog.c` | B,F | -| [8420f4272083](https://github.com/aurora-silicon/linux/commit/8420f42720830b9e5bad37647b6eead5303bc566), [352b68249894](https://github.com/aurora-silicon/linux/commit/352b682498947d0062635916a9d6902165ab38b5), [2f434459eb09](https://github.com/aurora-silicon/linux/commit/2f434459eb094edc046cd2ff71f1901302d7ef3d) | Ryan Murray | soc: apple: rtkit: reject an already owned mailbox receiver | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [791f8c37bad3](https://github.com/aurora-silicon/linux/commit/791f8c37bad39ada4186e7db9efb74472ef1670b), [44a668c87df1](https://github.com/aurora-silicon/linux/commit/44a668c87df18147ca0c9ace22e897e4c65b7620), [41e7892e40eb](https://github.com/aurora-silicon/linux/commit/41e7892e40eb21ddb08b2391a7940ed6499daf8d) | Ryan Murray | soc: apple: pmp: use a 42-bit DMA mask on T8140 [#179](https://github.com/aurora-silicon/linux/pull/179) | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [7a9913ea25e2](https://github.com/aurora-silicon/linux/commit/7a9913ea25e2d95d3ebe8f0392fec92979d08728), [493080d07b91](https://github.com/aurora-silicon/linux/commit/493080d07b918a2025fb79ff987d0dc9aeb294fe), [f69f1b76fcb0](https://github.com/aurora-silicon/linux/commit/f69f1b76fcb04e6bd7d7d066654e612be9761af0) | Ryan Murray | pmdomain: apple: pmp-report: expose T8140 fast-die effort [#179](https://github.com/aurora-silicon/linux/pull/179) | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [1a665f53f540](https://github.com/aurora-silicon/linux/commit/1a665f53f540a523d8df2c11d11a824f933b0d14), [8410c0eac2d9](https://github.com/aurora-silicon/linux/commit/8410c0eac2d9419a33c6a8d4a00bd14059f94610), [4f3e0ed14a9c](https://github.com/aurora-silicon/linux/commit/4f3e0ed14a9c280aafb3642619e7335413592e06) | Ryan Murray | pmdomain: apple: drain PMP report users before teardown | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [50b59e9b8f43](https://github.com/aurora-silicon/linux/commit/50b59e9b8f43e49c14a8a5e426f7891ac5f5e8c7), [061cf8fae73f](https://github.com/aurora-silicon/linux/commit/061cf8fae73f12de8d6720602ccac2aec250a20f), [f4ec00ff19db](https://github.com/aurora-silicon/linux/commit/f4ec00ff19dbfdc6d9bdbf03e8d7ec2798502f1a) | Ryan Murray | soc: apple: Enable T8140 system level cache allocation | Active — MCC; `drivers/soc/apple/Kconfig` | M,P | -| [628dbbe941d2](https://github.com/aurora-silicon/linux/commit/628dbbe941d25e5153dc62cb04104f846f3ffc48), [af915d02f5f6](https://github.com/aurora-silicon/linux/commit/af915d02f5f6022114a46e302642e915f9b22a01), [8b7d7f837ff6](https://github.com/aurora-silicon/linux/commit/8b7d7f837ff68f7fa37f6aaae55114bbd15efb43), [132cee4161dc](https://github.com/aurora-silicon/linux/commit/132cee4161dcff4307c55314f2a6189a00e7b0df) | DjDeveloperr | pmdomain: apple: add PMC voter interface driver [#212](https://github.com/aurora-silicon/linux/pull/212) [#219](https://github.com/aurora-silicon/linux/pull/219) | Active after port — PMC; `drivers/pmdomain/apple/Kconfig` | P,C,R | -| [698f429f4256](https://github.com/aurora-silicon/linux/commit/698f429f42566c059e7788e4efd44978a5db33a9), [9e840cf32336](https://github.com/aurora-silicon/linux/commit/9e840cf323360eabdb61223cf73198f4f4f3179d), [6454e02db2a5](https://github.com/aurora-silicon/linux/commit/6454e02db2a562d82adfbc4447ffe093f43dae0a), [5bd867f5c339](https://github.com/aurora-silicon/linux/commit/5bd867f5c33919ed65c81ead1e31595bb6bb91c5) | DjDeveloperr | soc: apple: add host performance controller floors [#212](https://github.com/aurora-silicon/linux/pull/212) [#219](https://github.com/aurora-silicon/linux/pull/219) | Active — CLPC; `drivers/soc/apple/Kconfig` | P,C,R,I | -| [faff1f7acf75](https://github.com/aurora-silicon/linux/commit/faff1f7acf752284972af5d469f91186c1e28552), [1c69f57e2c3e](https://github.com/aurora-silicon/linux/commit/1c69f57e2c3e5ba7cea2db4708242b7b538b15b2), [e736b2a049bf](https://github.com/aurora-silicon/linux/commit/e736b2a049bf708512f845093f712c431c20da3b) | Ryan Murray | pmdomain: apple: pmc: report the honoured floor of each agent [#219](https://github.com/aurora-silicon/linux/pull/219) | Active — PMC; `drivers/pmdomain/apple/pmc.c` | P,C,R | -| [9afc8195e8e2](https://github.com/aurora-silicon/linux/commit/9afc8195e8e2b3b4da25805f0b0c53baac16f1de), [e3f7747b88a3](https://github.com/aurora-silicon/linux/commit/e3f7747b88a38a8f2db51a63b323bb6fe3a25157), [cf8edfc522ce](https://github.com/aurora-silicon/linux/commit/cf8edfc522ce82871acc421119e324b56ab2813f) | Ryan Murray | pmdomain: apple: pmc: limit the DCS rail as a cooling device [#219](https://github.com/aurora-silicon/linux/pull/219) | Gated — DCS; `drivers/pmdomain/apple/pmc.c` | P | -| [c809017f2926](https://github.com/aurora-silicon/linux/commit/c809017f2926613cc9b683189c5e37aa6236c647), [bbbc7f0f2526](https://github.com/aurora-silicon/linux/commit/bbbc7f0f2526501df99e7d40c7a14a5bcb3c168d), [99bf4fc4c39c](https://github.com/aurora-silicon/linux/commit/99bf4fc4c39cbe59493531b7682f0a7eb60ac2e0) | Ryan Murray | pmdomain: apple: build the PMC driver by default [#219](https://github.com/aurora-silicon/linux/pull/219) | Active — PMC; `drivers/pmdomain/apple/Kconfig` | P,C,R | -| [413512c8c6c7](https://github.com/aurora-silicon/linux/commit/413512c8c6c7503e21b2d845b7072f3e67985e80), [afbf48da68ef](https://github.com/aurora-silicon/linux/commit/afbf48da68ef244414db4e174b630cf95ed33bd2), [d0f012d7b92f](https://github.com/aurora-silicon/linux/commit/d0f012d7b92f9967d42c35a70bc09c2b87274c0b) | Ryan Murray | soc: apple: clpc: do not count offline CPUs as busy [#219](https://github.com/aurora-silicon/linux/pull/219) | Active — CLPC; `drivers/soc/apple/clpc.c` | P,C,R,I | -| [a1517450f0d6](https://github.com/aurora-silicon/linux/commit/a1517450f0d6afa99ed5a5f2acbbc46350fdccd5), [a0301cd2e0fb](https://github.com/aurora-silicon/linux/commit/a0301cd2e0fb788836d8ef4d09b397a478891a72), [ddc216cd42cb](https://github.com/aurora-silicon/linux/commit/ddc216cd42cb7c7ebc831d3fafca17df244b280e) | Ryan Murray | soc: apple: clpc: stop waking idle CPUs and release the floor in sleep [#219](https://github.com/aurora-silicon/linux/pull/219) | Active — CLPC; `drivers/soc/apple/clpc.c` | P,C,R,I | -| [17c6097b09dd](https://github.com/aurora-silicon/linux/commit/17c6097b09ddd81a31a618e1d2447c3fdfed87ce), [ebd97e7441ff](https://github.com/aurora-silicon/linux/commit/ebd97e7441ff7ca5f7169f6e2bf550e7fb1438e0), [4f13ab717cb3](https://github.com/aurora-silicon/linux/commit/4f13ab717cb3a5ab19e5c097084ff2c676457f37) | Ryan Murray | pmdomain: apple: pmp-report: keep entry domains bound [#223](https://github.com/aurora-silicon/linux/pull/223) | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [bd2a439af1fe](https://github.com/aurora-silicon/linux/commit/bd2a439af1feefbb19cec4af61a28ae81a7fe479), [6733b19981f1](https://github.com/aurora-silicon/linux/commit/6733b19981f1d70f51264f609582025889e083db), [59540c7f72b3](https://github.com/aurora-silicon/linux/commit/59540c7f72b3721d293fb36cc5fd5bf79e1f47bc) | Ryan Murray | pmdomain: apple: Undo a power state transition that times out | Active — PMGR; `drivers/pmdomain/apple/pmgr-pwrstate.c` | B,F | -| [afa52a4aacd2](https://github.com/aurora-silicon/linux/commit/afa52a4aacd24be61e6963bcfa96a673fcd0f7fd), [b1dadbe56c1a](https://github.com/aurora-silicon/linux/commit/b1dadbe56c1ac98c1687aacd6f9a4ffd45d44802) | Acelogic | soc: apple: rtkit: Allow AP readiness before the IOP power acknowledgement | Active — RTKIT; `drivers/soc/apple/rtkit-helper.c` | B,F | -| [80223777e1c0](https://github.com/aurora-silicon/linux/commit/80223777e1c0fcdd18cdf7dbb693389f18bffe66), [7de139272456](https://github.com/aurora-silicon/linux/commit/7de1392724567cdab869ed7102a23642d6e64320), [b5c2960b4b44](https://github.com/aurora-silicon/linux/commit/b5c2960b4b441fa51b7f0ccdbaa17eae8a9de4bc) | Ryan Murray | soc: apple: rtkit: identify failed boot handshake stages | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [e02a7f13d77d](https://github.com/aurora-silicon/linux/commit/e02a7f13d77d0c450e6e663da89160b8e2e6a9de), [3a165a5f418d](https://github.com/aurora-silicon/linux/commit/3a165a5f418df4ca2445c14657bdc6dbe39bb223), [50a711417171](https://github.com/aurora-silicon/linux/commit/50a711417171e48a07340999bf43bb8c281b14d7) | Eryk Wieliczko | pmdomain: apple: leave firmware-owned power domains untouched | Active — PMGR; `drivers/pmdomain/apple/pmgr-pwrstate.c` | B,F | -| [15a254a94f16](https://github.com/aurora-silicon/linux/commit/15a254a94f1685a5550aec6c99a3270bfb389951), [e271de959b7d](https://github.com/aurora-silicon/linux/commit/e271de959b7de2e436f15415329d175e2e158517) | Ryan Murray | soc: apple: rtkit: Recognise opaque OSLog events 3 to 5 | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [faadb28854ca](https://github.com/aurora-silicon/linux/commit/faadb28854caaf534df60f6d629eca87c963344f), [aa486de92319](https://github.com/aurora-silicon/linux/commit/aa486de923198c933849bb2172f5ddad4f4710b6), [6559da7d50ab](https://github.com/aurora-silicon/linux/commit/6559da7d50ab10da722b3719f447836b12427159), [7810f444ae5a](https://github.com/aurora-silicon/linux/commit/7810f444ae5a403773baf8d4f460e29cb2375cf5) | Ryan Murray | cpufreq: apple-soc: Use related_cpus when removing OPP tables at exit | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [f630f4e6a724](https://github.com/aurora-silicon/linux/commit/f630f4e6a724b62182875eeb75e3559f6304b286), [4df394b4c36b](https://github.com/aurora-silicon/linux/commit/4df394b4c36be04ca63fabae2c630bfdda20188a), [31ce0bec7173](https://github.com/aurora-silicon/linux/commit/31ce0bec7173eb3fbc1067e6dba46c2ca2f4dc8e) | Ryan Murray | cpufreq: apple-soc: Add T8140 support | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [116ec26bc074](https://github.com/aurora-silicon/linux/commit/116ec26bc074456b670823002c81ccffc5fbbecc), [2e97d372534e](https://github.com/aurora-silicon/linux/commit/2e97d372534e73b72b9b36b9debaa3caa9ae5ab6), [b0a02dcbfded](https://github.com/aurora-silicon/linux/commit/b0a02dcbfded7f1485db7f37694712892025a4d9) | Ryan Murray | cpufreq: apple-soc: enforce PMP fast-die limits through QoS [#179](https://github.com/aurora-silicon/linux/pull/179) | Active — PMP; `drivers/cpufreq/apple-soc-cpufreq.c` | P,B | -| [3a1ff1c99f6a](https://github.com/aurora-silicon/linux/commit/3a1ff1c99f6a35163c77f9c2cc5f6b19d4fe6242), [9d74a86460df](https://github.com/aurora-silicon/linux/commit/9d74a86460df995f3522f3267c3f3fa34d79a47e) | Ryan Murray | cpufreq: apple-soc: keep required fallback limits with an older DT | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [1248cb920813](https://github.com/aurora-silicon/linux/commit/1248cb9208135326d9724eb1a83e3c67d25c3664), [a40bdafc42e5](https://github.com/aurora-silicon/linux/commit/a40bdafc42e5dcf8c0c4bc728f883c7e3d48bffe), [a61bca6382a7](https://github.com/aurora-silicon/linux/commit/a61bca6382a765f5b74134dea3b094039f2a15bd) | Ryan Murray | cpufreq: apple-soc: tidy includes and the ->exit() callback [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,P | -| [c52554b353b4](https://github.com/aurora-silicon/linux/commit/c52554b353b4fcecf684ea648e4b1ab5f896b677), [143dc7bec441](https://github.com/aurora-silicon/linux/commit/143dc7bec44131ac467fa21049f2d63c52783d52), [e7d3d687d207](https://github.com/aurora-silicon/linux/commit/e7d3d687d20745259fcb83af83c9ed377ff6a1f3) | Ryan Murray | cpufreq: apple-soc: describe the unmanaged P-state ceiling as data [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,P | -| [e71cc1ccab4e](https://github.com/aurora-silicon/linux/commit/e71cc1ccab4eaefdf63d66104107c9604ab04121), [cd8875cfd1bf](https://github.com/aurora-silicon/linux/commit/cd8875cfd1bfaa80b1b1dbd7e27ea234d129471b), [cfe897d4abac](https://github.com/aurora-silicon/linux/commit/cfe897d4abac70a3d9703ea7f4c082ed89da7a96) | Ryan Murray | rust: soc: apple: rtkit: Add shutdown() and a buffer-retaining drop | Active — RTKIT; `rust/kernel/soc/apple/rtkit.rs` | B,F | -| [10dd5c21ef72](https://github.com/aurora-silicon/linux/commit/10dd5c21ef7211836beaa47f6f3fd3e250d36866), [8779ecb38c89](https://github.com/aurora-silicon/linux/commit/8779ecb38c89c103617c4ea24207fef96472ebc4), [06914e1d4995](https://github.com/aurora-silicon/linux/commit/06914e1d499555a96e0beccccc0b5485051108cd) | Ryan Murray | soc: apple: rtkit: Handle oslog notifications quietly | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [9a4cf171ba9e](https://github.com/aurora-silicon/linux/commit/9a4cf171ba9edabdd0f0f715468d42689791adb7), [aa18e91ac6fc](https://github.com/aurora-silicon/linux/commit/aa18e91ac6fce29dcc8e69aac619fab3fda7ee85), [904945425463](https://github.com/aurora-silicon/linux/commit/904945425463c0450cb19582afeb4b935175ae51), [201afd84ae50](https://github.com/aurora-silicon/linux/commit/201afd84ae50008095068d028af22ecf4c1356c5) | DjDeveloperr | drm/asahi: use const float bit conversion supported by Rust minimum [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/float.rs` | M,D | -| [c9be90533ae0](https://github.com/aurora-silicon/linux/commit/c9be90533ae06ac64dfe5e35b121cf30a1cc37f0), [6b610ee95063](https://github.com/aurora-silicon/linux/commit/6b610ee95063a8d047c1ee49c65ee3599ee24a92), [94b86f96bd9e](https://github.com/aurora-silicon/linux/commit/94b86f96bd9ef2275c99ddf5238374e615b2f510), [12f0a07a6166](https://github.com/aurora-silicon/linux/commit/12f0a07a61666305a1efe1a1f4c4c88a013abafb) | DjDeveloperr | rust: drm: sched: Fix job accounting when cancelling jobs [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `rust/kernel/drm/sched.rs` | C,H,M,F | -| [7ba04b60d2ca](https://github.com/aurora-silicon/linux/commit/7ba04b60d2caf298bb9119b359629feedfec38c5), [43d53c0d4f56](https://github.com/aurora-silicon/linux/commit/43d53c0d4f5660bc6d300e6626d1f9a05d832c79), [15a7eae7964f](https://github.com/aurora-silicon/linux/commit/15a7eae7964f94a16fd273fc3b25a22ad2c27bab), [f8102be460b6](https://github.com/aurora-silicon/linux/commit/f8102be460b66b12af865d6250e73ffc6f99c73a) | DjDeveloperr | rust: drm: sched: Keep the scheduler alive while jobs reference it [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `rust/kernel/drm/sched.rs` | C,H,M,F | -| [d1ebc542fe8e](https://github.com/aurora-silicon/linux/commit/d1ebc542fe8e1082a1c6e311b72d4d6c609c940d), [e4c63b3dbab0](https://github.com/aurora-silicon/linux/commit/e4c63b3dbab04bda2a798b913dd5e46b8799290a), [7d650853ea8e](https://github.com/aurora-silicon/linux/commit/7d650853ea8e5de3f512a36b69f8653014de83b4), [f1f985d57681](https://github.com/aurora-silicon/linux/commit/f1f985d576810c7183ea9bcd1b701cb284927ac6) | DjDeveloperr | rust: drm: sched: Do not stop the scheduler before tearing it down [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `rust/kernel/drm/sched.rs` | C,H,M,F | -| [45ade507d593](https://github.com/aurora-silicon/linux/commit/45ade507d593cb69929a4daf5d1d50159d729126), [1bc200c44668](https://github.com/aurora-silicon/linux/commit/1bc200c446687bc2eb2b6abc19f1d9b5a3ad59ee), [9171e855e6d5](https://github.com/aurora-silicon/linux/commit/9171e855e6d58a12059e265a7e3907f44ffa70a9), [14d7b3c379da](https://github.com/aurora-silicon/linux/commit/14d7b3c379da4c764581d4c34aff495d7346af72) | DjDeveloperr | rust: drm: sched: let drivers handle timeouts without a reset [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `rust/kernel/drm/sched.rs` | C,H,M,F | -| [996d255ea104](https://github.com/aurora-silicon/linux/commit/996d255ea104c999554b5c5584d2b59c6eed3cd9), [59b1e2a30011](https://github.com/aurora-silicon/linux/commit/59b1e2a300116dec7170b0b4a44e4b94a39c372b), [630c43dac20e](https://github.com/aurora-silicon/linux/commit/630c43dac20e9621d3c2cd687c98ab85d51c8b9e), [e0a5c5ad84cb](https://github.com/aurora-silicon/linux/commit/e0a5c5ad84cbc6e48c0194882b8c1c67d72538a8) | DjDeveloperr | drm/asahi: uapi: Add the G17 additions [#171](https://github.com/aurora-silicon/linux/pull/171) | Active translated data — FW; `drivers/gpu/drm/asahi/file.rs` | B,C,R | -| [2f298100e9d5](https://github.com/aurora-silicon/linux/commit/2f298100e9d59b05f3c71d9e27d8079a63a0b6bc), [4a9cf4453a2d](https://github.com/aurora-silicon/linux/commit/4a9cf4453a2d0349848c89bd2028e8e6757263a7), [e46d8cfd391b](https://github.com/aurora-silicon/linux/commit/e46d8cfd391b00b302d5a9ff4608b82c3714c910), [aae9f7d3525f](https://github.com/aurora-silicon/linux/commit/aae9f7d3525f93a7a5b5ae0529f8e85219735d08) | DjDeveloperr | drm/asahi: separate DRM-facing GPU operations from the firmware manager [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/driver.rs` | M,D | -| [3291ed172be2](https://github.com/aurora-silicon/linux/commit/3291ed172be2a63252d34367f8f5d8baebf2e537), [cac96891a49f](https://github.com/aurora-silicon/linux/commit/cac96891a49fd1416cb3bb0f68922cbebb7618c1), [54721b0f0bee](https://github.com/aurora-silicon/linux/commit/54721b0f0bee7be5b3094112ffcfa36e76dec7ed), [7d3ddb6c35e1](https://github.com/aurora-silicon/linux/commit/7d3ddb6c35e1c478f68c78ac8bb8b3ee9d314e58) | DjDeveloperr | drm/asahi: mmu: support per-SoC UAT geometry and user VA range [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M,D | -| [a0ae891ae8a0](https://github.com/aurora-silicon/linux/commit/a0ae891ae8a00e183ddbc753347a7ea2ef26d7dc), [79aa2038d24c](https://github.com/aurora-silicon/linux/commit/79aa2038d24c495775338c6d72b638885e2cd5e1), [49e3d35945c3](https://github.com/aurora-silicon/linux/commit/49e3d35945c397f7af5a6477540e2ee254b3bd76), [5e21536704b5](https://github.com/aurora-silicon/linux/commit/5e21536704b56c38b478516d1f65bdcfef748a17) | DjDeveloperr | drm/asahi: pgtable: track ownership below firmware-shared roots [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [524c57538f14](https://github.com/aurora-silicon/linux/commit/524c57538f142ef38c8b081f5148ffb515e96266), [52ef95b9e763](https://github.com/aurora-silicon/linux/commit/52ef95b9e7635d564449ec08b33a62c6ed26dd12), [87cab74a2498](https://github.com/aurora-silicon/linux/commit/87cab74a2498f5df62f7697786a2743e84125b99), [c0e36ff2a57f](https://github.com/aurora-silicon/linux/commit/c0e36ff2a57f2a461a96b80cebb741f5b76de7ad) | DjDeveloperr | drm/asahi: add the T8140 firmware interface [#171](https://github.com/aurora-silicon/linux/pull/171) | Active translated data; MCache gated by V25G83.mcache=false — FW; `drivers/gpu/drm/asahi/g17/buffer.rs` | B,C,R | -| [ed303abfff0f](https://github.com/aurora-silicon/linux/commit/ed303abfff0fd9e29e8094b828cd3054969bcf97), [0386eb2184a2](https://github.com/aurora-silicon/linux/commit/0386eb2184a268ed6178a6a93a12880806a8022f), [d7d77474e459](https://github.com/aurora-silicon/linux/commit/d7d77474e4590fcd9c1d0e30ab16dc9ca0c73346), [bc4c50abf8ed](https://github.com/aurora-silicon/linux/commit/bc4c50abf8ede16fec7f2a79546a310134b208df) | DjDeveloperr | drm/asahi: request temporary CPU capacity for sustained GPU feeds [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — POWER; `drivers/gpu/drm/asahi/g17/completion.rs` | I,C,R,P | -| [4a77604eb003](https://github.com/aurora-silicon/linux/commit/4a77604eb003ed141f28781769b28953fdabfb1f), [9fdd32f35641](https://github.com/aurora-silicon/linux/commit/9fdd32f3564105f1d012ef20e1c64de912cade1d), [15d553b170f1](https://github.com/aurora-silicon/linux/commit/15d553b170f157558da0343d477c39161f9870f1), [e1e0c5c90faf](https://github.com/aurora-silicon/linux/commit/e1e0c5c90faf0307f95374c83efe3009d58f0bdb) | DjDeveloperr | drm/asahi: observe compute completions without a queue mask [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/events.rs` | C,H | -| [593e44ca35f7](https://github.com/aurora-silicon/linux/commit/593e44ca35f708e48e0d9b9efde35bfe1052ef35), [e32d6efe3891](https://github.com/aurora-silicon/linux/commit/e32d6efe3891821dce2e6c0e27219ed676ea4f2f), [7dcd8d1467e2](https://github.com/aurora-silicon/linux/commit/7dcd8d1467e2bc1e90eeb04489d4ab7b392351e8), [0c69741cdc26](https://github.com/aurora-silicon/linux/commit/0c69741cdc26f2dbb26754e87f1b53db1f4bed38) | DjDeveloperr | drm/asahi: avoid repeated submission bookkeeping [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | C,R,H | -| [0ee6827563de](https://github.com/aurora-silicon/linux/commit/0ee6827563deb2e2519534dd938334c90606fb33), [ce33535500cc](https://github.com/aurora-silicon/linux/commit/ce33535500cc78ed2f6695050ce21487902806bc), [ffa3234a92d7](https://github.com/aurora-silicon/linux/commit/ffa3234a92d789514f3e6b05213f417454b73639), [e0d2761bd854](https://github.com/aurora-silicon/linux/commit/e0d2761bd854136076d642b614c9b6078699243e) | DjDeveloperr | drm/asahi: settle unpublished jobs discarded by entity teardown [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/job.rs` | C,R,H | -| [7eb278622690](https://github.com/aurora-silicon/linux/commit/7eb27862269055d524de513e380572b59171a390), [aa659e9a3710](https://github.com/aurora-silicon/linux/commit/aa659e9a3710765dc87d06e50227bdd8476cbd72), [0a72b08543fd](https://github.com/aurora-silicon/linux/commit/0a72b08543fdec99aa8117c8b4983eeee9b8c856), [d41b760af0bc](https://github.com/aurora-silicon/linux/commit/d41b760af0bcc10744b4145cfdbc19dab7625e8e) | DjDeveloperr | drm/asahi: reserve completion capacity for global compute replay [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [06c4e4a3193e](https://github.com/aurora-silicon/linux/commit/06c4e4a3193e5b0630e343d9730cad097471440a), [1a53f784e14f](https://github.com/aurora-silicon/linux/commit/1a53f784e14f219a44f5faa7a33947c3f4dedcb1), [945285b800d3](https://github.com/aurora-silicon/linux/commit/945285b800d30fcc9a60461b70249b96b4c053ad), [868c80c92152](https://github.com/aurora-silicon/linux/commit/868c80c921527154df5e73a271583a4b0b63fdeb) | DjDeveloperr | drm/asahi: filter compute completion identities before payload reads [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/initdata.rs` | C,H | -| [304da56f2b1b](https://github.com/aurora-silicon/linux/commit/304da56f2b1b927ac837671897273835eeccb91b), [dc74efcea722](https://github.com/aurora-silicon/linux/commit/dc74efcea72275420878d60c358b3af182006eef), [513f7568ad7e](https://github.com/aurora-silicon/linux/commit/513f7568ad7eb30b97ac1309f37bbb3a11229409), [f61c86ab2830](https://github.com/aurora-silicon/linux/commit/f61c86ab28302e46cba8fbdbaa8339aaa4e17b40) | DjDeveloperr | drm/asahi: sample opening counters at the polling deadline [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — REC; `drivers/gpu/drm/asahi/g17/mod.rs` | F,Q | -| [d012beaabd09](https://github.com/aurora-silicon/linux/commit/d012beaabd0985acd8fa07a5e605f9d0c5b50590), [ff5769e16bea](https://github.com/aurora-silicon/linux/commit/ff5769e16bea501f52ff724effb309f107da39e9), [26ba1aa06add](https://github.com/aurora-silicon/linux/commit/26ba1aa06add76aa7e97a843d752fe0d08afd617), [99dd8deec12f](https://github.com/aurora-silicon/linux/commit/99dd8deec12fe28abb844854059bce6a87764199) | DjDeveloperr | drm/asahi: commit canonical binding metadata with each user mapping [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M,D | -| [fef7f56d2bb3](https://github.com/aurora-silicon/linux/commit/fef7f56d2bb33e5bb627a6dc8872b271a5c504cd), [6753db1b2896](https://github.com/aurora-silicon/linux/commit/6753db1b289605b5cc007a8dd8912d948897f86b), [906cacc20dfc](https://github.com/aurora-silicon/linux/commit/906cacc20dfcccb95c6ba7809f8d3ccac4624791), [11b50b74597c](https://github.com/aurora-silicon/linux/commit/11b50b74597c2c3e1f5687d5db50ce0eaa103c21) | DjDeveloperr | drm/asahi: order canonical object invalidation with mapping removal [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M,D | -| [31b8abbea796](https://github.com/aurora-silicon/linux/commit/31b8abbea79664748c2e8a17745bda9e82b119d0), [477cea7fca6e](https://github.com/aurora-silicon/linux/commit/477cea7fca6eab5f5460c2c5e2459fa9cf6e1fa4), [eb1d380fc62d](https://github.com/aurora-silicon/linux/commit/eb1d380fc62d3f8febbcf3a19d173eca44e49f19), [f594e2be7f49](https://github.com/aurora-silicon/linux/commit/f594e2be7f492d0cb4fdbdf5197122418f330036) | DjDeveloperr | drm/asahi: advertise G17 queue and input-sync capabilities [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | C,R,H | -| [ee8060be8a84](https://github.com/aurora-silicon/linux/commit/ee8060be8a84b43d483ac9d4f76d51f1f5a5e35c), [80c1cad754d8](https://github.com/aurora-silicon/linux/commit/80c1cad754d8711b46ece6be4d7e00c6fd27b6df), [4810fcc3be49](https://github.com/aurora-silicon/linux/commit/4810fcc3be491f1eaa0c78a183c800d08fecbc1d), [98783a0fc38d](https://github.com/aurora-silicon/linux/commit/98783a0fc38dbac9eecb4164ed6c090e3adf591d) | DjDeveloperr | drm/asahi: acquire event records after observing their producer [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/channel.rs` | C,R,H | -| [eaebe2b1f691](https://github.com/aurora-silicon/linux/commit/eaebe2b1f691e89c991bafee6013b2e0d0b5070d), [63c2157467ec](https://github.com/aurora-silicon/linux/commit/63c2157467ec2530afd39ac823a75b74c5d210c9), [7703d07ccd6d](https://github.com/aurora-silicon/linux/commit/7703d07ccd6dbb8c50cbd993a325e0d6a61cad33), [267dc9ba9ea8](https://github.com/aurora-silicon/linux/commit/267dc9ba9ea8e068a3d9d0683a58b72a51291ece) | DjDeveloperr | drm/asahi: discard partial G17 mappings when binding fails [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [7f498ba60f1a](https://github.com/aurora-silicon/linux/commit/7f498ba60f1a44401e434975d8d9433f57212539), [56d0e6d6c8b3](https://github.com/aurora-silicon/linux/commit/56d0e6d6c8b340a20cab5869ab6c516170614aa4), [bdfbf517e1fb](https://github.com/aurora-silicon/linux/commit/bdfbf517e1fb478c202e1531a8a084dc7557d4c5), [9f204371cd61](https://github.com/aurora-silicon/linux/commit/9f204371cd6118ecaa4635b76a763e6c4d53b728) | DjDeveloperr | drm/asahi: reuse the reserved output fence for submitted work [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fence.rs` | C,R,H | -| [1c200975b7c1](https://github.com/aurora-silicon/linux/commit/1c200975b7c1ccbe890e6bdeb097fb9c5d59bfac), [7c55851883a6](https://github.com/aurora-silicon/linux/commit/7c55851883a670690b2e354802b0e265c0430930), [c97c4be0ce4e](https://github.com/aurora-silicon/linux/commit/c97c4be0ce4e1a265fa915b9ec4e634a7db2c3af), [fa771fbd7629](https://github.com/aurora-silicon/linux/commit/fa771fbd7629800795268b560e9e2ff1b0cb806c) | DjDeveloperr | drm/asahi: wake render growth when its prerequisites become ready [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/events.rs` | R,H | -| [3b92fcd8c068](https://github.com/aurora-silicon/linux/commit/3b92fcd8c068445739b69393a29c7ee7de0bc5b4), [7d4176528d08](https://github.com/aurora-silicon/linux/commit/7d4176528d08bba02e84e23f43b006a7fdbda51f), [4fe42ca7a853](https://github.com/aurora-silicon/linux/commit/4fe42ca7a85341ec777ca2f19e5ed0eb8fdafa82), [956a8e2fd2dd](https://github.com/aurora-silicon/linux/commit/956a8e2fd2ddcb7e9dc596796b79f62b4e017c55) | DjDeveloperr | drm/asahi: skip frontier scans without a cross-engine prefix [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | C,R,H | -| [cc1601720b58](https://github.com/aurora-silicon/linux/commit/cc1601720b58ceedb0a76606922d7a554da13e17), [63a3c2d02dac](https://github.com/aurora-silicon/linux/commit/63a3c2d02dac4acb23d299c6a00d096f04bf5520), [75ea155f8b2e](https://github.com/aurora-silicon/linux/commit/75ea155f8b2ed4da38c39179a9a653fec0eb1c37), [5026a187d811](https://github.com/aurora-silicon/linux/commit/5026a187d811c441374d11c71a3fa0df58e118fd) | DjDeveloperr | drm/asahi: track CPU feed requests through policy lifetime [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — POWER; `drivers/gpu/drm/asahi/g17/feed.rs` | I,C,R,P | -| [848b36596112](https://github.com/aurora-silicon/linux/commit/848b36596112673711945126a51efd79d0cfa625), [547707b268e9](https://github.com/aurora-silicon/linux/commit/547707b268e96ecff8cadbc6f8b78652ab52d0ba), [a23fed471fe1](https://github.com/aurora-silicon/linux/commit/a23fed471fe1d97b7d75c738cb63d045ad434754), [c42fd8c45c3a](https://github.com/aurora-silicon/linux/commit/c42fd8c45c3a20ed2ec94c40bf5fbcf782220e7c) | DjDeveloperr | drm/asahi: bound dependency scans to the ordered command prefix [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | C,R,H | -| [7a205aa6b8eb](https://github.com/aurora-silicon/linux/commit/7a205aa6b8eb17488b9882f49beece4f24b49030), [b1087fb75ab1](https://github.com/aurora-silicon/linux/commit/b1087fb75ab153f2cb017c3a08922ece0da18ca7), [b42e20b3a8d3](https://github.com/aurora-silicon/linux/commit/b42e20b3a8d3e03bdf184be067a0149ed6fbee79), [e4d41aaa9c0c](https://github.com/aurora-silicon/linux/commit/e4d41aaa9c0cdd145d5d07fe0b3d0eb209bf0879) | DjDeveloperr | drm/asahi: wait for host timestamp writes in compute prefixes [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — TIMESTAMP; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | T,C | -| [23e316ffe7e5](https://github.com/aurora-silicon/linux/commit/23e316ffe7e5a3fa108eb271778222bdc7f21ee0), [2a2aff37cd8e](https://github.com/aurora-silicon/linux/commit/2a2aff37cd8e3771dea46ebdc3e45dc7b4415b4c), [55df4049246b](https://github.com/aurora-silicon/linux/commit/55df4049246b6da9482b15411e173a11cc7f04e8), [81d324022d0f](https://github.com/aurora-silicon/linux/commit/81d324022d0f97346639b06a6abaa8b86d480ead) | DjDeveloperr | drm/asahi: release successful submission work-state ownership [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/completion.rs` | C,R,H | -| [18ef3a813070](https://github.com/aurora-silicon/linux/commit/18ef3a813070620821371e437d1557a1dd1c79cf), [cfe7880a5d16](https://github.com/aurora-silicon/linux/commit/cfe7880a5d167059b871475fbc5abe60248fcf3f), [1660e75c7e3c](https://github.com/aurora-silicon/linux/commit/1660e75c7e3ccb4b906662db275d6c5ccaebd452), [e0f7410fd5b3](https://github.com/aurora-silicon/linux/commit/e0f7410fd5b368d06ab17d802720f9d76e12880c) | DjDeveloperr | drm/asahi: preserve exact historical command prefixes [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/command.rs` | C,R,H | -| [5c02e806d300](https://github.com/aurora-silicon/linux/commit/5c02e806d3004d2bb01706362298d8a6802e7433), [6507ba3ca670](https://github.com/aurora-silicon/linux/commit/6507ba3ca670d34720c6c8bfea44836b8228772b), [c7986b27e066](https://github.com/aurora-silicon/linux/commit/c7986b27e066b3d3b4fd81e95b6e174cd6c21807), [fbfb5d96f25e](https://github.com/aurora-silicon/linux/commit/fbfb5d96f25efbf2b1571ca635b195e0ad4a54be) | DjDeveloperr | drm/asahi: bring the cleanroom driver up on Neo hardware [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/buffer.rs` | C,R,H | -| [d0b66e8a8778](https://github.com/aurora-silicon/linux/commit/d0b66e8a877898097d40a380483c09e6be471532), [5fa0b934070c](https://github.com/aurora-silicon/linux/commit/5fa0b934070c615c3c745f5759d2fb7f90eaee09), [01d0b0bed7a7](https://github.com/aurora-silicon/linux/commit/01d0b0bed7a763fa775654a0a115c01f38b34584), [66af386568f7](https://github.com/aurora-silicon/linux/commit/66af386568f748d2499be3e3587ce1e7ca0ae9cd) | Ryan Murray | drm/asahi: report live GEM object accounting [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/asahi.rs` | M,D | -| [722064f1be0d](https://github.com/aurora-silicon/linux/commit/722064f1be0d171bc5d496cca352f2db6285c6c0), [f313fc4bd1a1](https://github.com/aurora-silicon/linux/commit/f313fc4bd1a1c91bad6657f7a136cc7b0f88dbe4), [2c076e0de6fe](https://github.com/aurora-silicon/linux/commit/2c076e0de6fe0a0a38a2041b02d5b9e75347375a), [f7fcc50568b9](https://github.com/aurora-silicon/linux/commit/f7fcc50568b9467f241a425b20b92ff1de10f641) | Ryan Murray | drm/asahi: port j700 queue accounting and compute recovery isolation [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — REC; `drivers/gpu/drm/asahi/g17/context.rs` | F,Q | -| [b1e288fb887d](https://github.com/aurora-silicon/linux/commit/b1e288fb887dc74d1b428d478493c6c568d3b02d), [b3b17a139f25](https://github.com/aurora-silicon/linux/commit/b3b17a139f25e8164dfdfe31d7a0c03fc2a4fa85), [2d84d7470c0f](https://github.com/aurora-silicon/linux/commit/2d84d7470c0f0d60c11c9df9e9665ee6a6a2bf71), [3c65418ee698](https://github.com/aurora-silicon/linux/commit/3c65418ee698735d33f299fe208aa8c22ff310a4) | DjDeveloperr | drm/asahi: account once per compute queue transition [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [4273fb6241bb](https://github.com/aurora-silicon/linux/commit/4273fb6241bb6f9083dd8feb263fee0924fffa94), [fa2e76747a7f](https://github.com/aurora-silicon/linux/commit/fa2e76747a7f3e264fc9c8dfaaa616627cf4e70f), [2ebb1eb92796](https://github.com/aurora-silicon/linux/commit/2ebb1eb927960a96456df1369294d3d6e392a591), [982df2dcc66e](https://github.com/aurora-silicon/linux/commit/982df2dcc66e2cb2012df476c4325c8fce016dda) | DjDeveloperr | drm: carry shared GPUVM and scheduler interfaces used by the G17 review [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `drivers/gpu/drm/drm_gpuvm.c` | C,H,M,F | -| [c163a8df57f9](https://github.com/aurora-silicon/linux/commit/c163a8df57f986f9cb2f3c3275a1dd2b627d7dba), [751ee0b363e7](https://github.com/aurora-silicon/linux/commit/751ee0b363e7d2733cb452989b6c5fcca182f087), [84f4e1fd0eaf](https://github.com/aurora-silicon/linux/commit/84f4e1fd0eaf13c985e6535d2906b68f1c519947), [ca389fba9b6c](https://github.com/aurora-silicon/linux/commit/ca389fba9b6c7c9354c2f765fe81c5ef5f069f3b) | DjDeveloperr | drm/asahi: correct reviewed lifetime, failure and submission paths [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — RTKIT; `drivers/gpu/drm/asahi/g17/channel.rs` | B,F | -| [3a61b700f19d](https://github.com/aurora-silicon/linux/commit/3a61b700f19d1b2a63017c02359a0eb30360c496), [d297d20ba207](https://github.com/aurora-silicon/linux/commit/d297d20ba207abd5b9c4d7b80aa370dd5a379a4f), [ceb8f96ba823](https://github.com/aurora-silicon/linux/commit/ceb8f96ba8232067893d3956bcc4c335bda7e268), [d9b7b82975e2](https://github.com/aurora-silicon/linux/commit/d9b7b82975e2dad4b9a5941ade2f4debadd61c6c) | DjDeveloperr | drm/asahi: order render timestamp publication independently of GPU retirement [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — TIMESTAMP; `drivers/gpu/drm/asahi/g17/completion.rs` | T,C | -| [0f89327272be](https://github.com/aurora-silicon/linux/commit/0f89327272be80ecf44b643c4198614255024367), [212a7b2ccc2d](https://github.com/aurora-silicon/linux/commit/212a7b2ccc2d7a972478f4feed4c19d77cf7e01d), [3bf578fd8958](https://github.com/aurora-silicon/linux/commit/3bf578fd8958a40af5ab8b3ea892749a1dc5b4bf), [e22376a0ca67](https://github.com/aurora-silicon/linux/commit/e22376a0ca679b5359fdef009b2479616619677b) | DjDeveloperr | drm/sched: separate Rust job timeout state from submission state [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `drivers/gpu/drm/asahi/g17/job.rs` | C,H,M,F | -| [ca7ec4ac8767](https://github.com/aurora-silicon/linux/commit/ca7ec4ac8767714b3a4c28a8bc4e3121e5a346bf), [3810bcb5e35c](https://github.com/aurora-silicon/linux/commit/3810bcb5e35cb34abd3e80d5998c94ddc747cb34), [20560fe15a23](https://github.com/aurora-silicon/linux/commit/20560fe15a23c2dd8db188a074e245c20bcf9858), [3e464649d372](https://github.com/aurora-silicon/linux/commit/3e464649d37234b0f47dfe3c22d3f73cbb6ef45b) | DjDeveloperr | drm/asahi: observe completed render work before a deferred VM failure [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/render/submit.rs` | R,H | -| [6a57525c17e8](https://github.com/aurora-silicon/linux/commit/6a57525c17e8cdf0fcb5965e367c8bca29f6a2f4), [7b30ae9dd4eb](https://github.com/aurora-silicon/linux/commit/7b30ae9dd4eb5a5da852deae9709ef4c10ac09c8), [d20cdd0dba5a](https://github.com/aurora-silicon/linux/commit/d20cdd0dba5a51899ea79cb8ac2df9e14cd3cd8a), [83cf9f5ad0ba](https://github.com/aurora-silicon/linux/commit/83cf9f5ad0baf71001cc0aa9c25c83f27f4a219a) | DjDeveloperr | drm/asahi: publish child page tables before linking them [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/pgtable.rs` | M,D | -| [c6754b181576](https://github.com/aurora-silicon/linux/commit/c6754b181576b5fb5467f9735e7abe4451271681), [03f169480b45](https://github.com/aurora-silicon/linux/commit/03f169480b452a052c707ddc07b36c2be478d645), [da35a7e8b950](https://github.com/aurora-silicon/linux/commit/da35a7e8b9502f0afb30feac9aa41b03b0b7d080), [b321f0e70539](https://github.com/aurora-silicon/linux/commit/b321f0e7053949d9144028d0a465a4f03eb6cc83) | DjDeveloperr | drm/asahi: retire deferred mapping cleanup without allocating [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `drivers/gpu/drm/asahi/mmu.rs` | C,H,M,F | -| [26b6f8056c9a](https://github.com/aurora-silicon/linux/commit/26b6f8056c9a913656c75753e1d719f5771a2496), [85b9304050b9](https://github.com/aurora-silicon/linux/commit/85b9304050b9331ed8206ab69532c1bb42fe9582), [982da05e5f83](https://github.com/aurora-silicon/linux/commit/982da05e5f831a54800a778df91464ab6d6372b2), [7d57556a8962](https://github.com/aurora-silicon/linux/commit/7d57556a8962dd49aadbb24af772ee5240b8c1c1) | DjDeveloperr | drm/asahi: keep compute timestamps outside shared queue aliases [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — TIMESTAMP; `drivers/gpu/drm/asahi/g17/completion.rs` | T,C | -| [a244ed25307c](https://github.com/aurora-silicon/linux/commit/a244ed25307c3d03df0a57def5fffa80d19209fa), [ee1b5a0211c1](https://github.com/aurora-silicon/linux/commit/ee1b5a0211c14b5a799304948bd91fbfebaed35c), [733634bcb0c4](https://github.com/aurora-silicon/linux/commit/733634bcb0c4de6e9885878dc8b1aad744353c83), [e3cfe6674874](https://github.com/aurora-silicon/linux/commit/e3cfe66748744b6aadf6b863b57818adb0721cdd) | DjDeveloperr | drm/shmem-helper: add revocable CPU mappings and idle backing release [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `drivers/gpu/drm/asahi/gem.rs` | C,H,M,F | -| [9afbd440e531](https://github.com/aurora-silicon/linux/commit/9afbd440e5316ca0831289cd5dec955003554737), [97bab816b9d2](https://github.com/aurora-silicon/linux/commit/97bab816b9d20dc0b7433baf2077bc2225d9e36a), [449bb6888c6f](https://github.com/aurora-silicon/linux/commit/449bb6888c6feeb79e6390cfe00dd7d4d58b6261), [e2b08ebbcadc](https://github.com/aurora-silicon/linux/commit/e2b08ebbcadc3a9ebe2733140e1a88c62af87ba1) | DjDeveloperr | drm/asahi: reclaim idle private VM backing under memory pressure [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M,D | -| [18e1bce60e1a](https://github.com/aurora-silicon/linux/commit/18e1bce60e1a82f3872012d13fe6f5b51684eb38), [babe2ba0c5a6](https://github.com/aurora-silicon/linux/commit/babe2ba0c5a68f0d3b81085736f52f57f32cbbfe), [717d6fe9e152](https://github.com/aurora-silicon/linux/commit/717d6fe9e152af9bdda4a73a81151145cb2681ca), [e82b27902f91](https://github.com/aurora-silicon/linux/commit/e82b27902f91d8c833395a966366d0ffc30769c3) | DjDeveloperr | drm/asahi: free a closed context's render pool once its release is consumed [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/context.rs` | M,C,R | -| [177e22791d7c](https://github.com/aurora-silicon/linux/commit/177e22791d7cfecb3b6c6b6315adf674ef1c9b30), [431b18cf9072](https://github.com/aurora-silicon/linux/commit/431b18cf9072a8618cbab77cfcbde3952cdb5623), [20a55bacd2fb](https://github.com/aurora-silicon/linux/commit/20a55bacd2fb91e52b6bb5cbb3e88e5218b2f726), [fa210660c43c](https://github.com/aurora-silicon/linux/commit/fa210660c43c1e8ffc4c0705792febb70c29e779) | DjDeveloperr | drm/asahi: hold idle descent for every first render pair install [#171](https://github.com/aurora-silicon/linux/pull/171) | Gated — MMIO; `drivers/gpu/drm/asahi/g17/runtime/render.rs` | B,I | -| [06175c4cc1bc](https://github.com/aurora-silicon/linux/commit/06175c4cc1bccd44765a75a70278fedb27ed9fe5), [2f10cc462301](https://github.com/aurora-silicon/linux/commit/2f10cc462301b9d1a1e64bd31468268d90a5d96d), [e94491e80ac1](https://github.com/aurora-silicon/linux/commit/e94491e80ac12de2fb9b741739b560ab17ecbb34), [d7715ebbd2d3](https://github.com/aurora-silicon/linux/commit/d7715ebbd2d3397958f08442d096a2476d32cb6a) | DjDeveloperr | drm/asahi: add GEM_MADVISE and purge advised objects under memory pressure [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `drivers/gpu/drm/asahi/driver.rs` | C,H,M,F | -| [f338bb052975](https://github.com/aurora-silicon/linux/commit/f338bb05297509f7b87714c5727fb99a8fea373a), [c2e8f1ce84f1](https://github.com/aurora-silicon/linux/commit/c2e8f1ce84f1f72a14e6395fa5246a133211432c), [85271d321506](https://github.com/aurora-silicon/linux/commit/85271d321506ec35cc7e6a82665649e7fd2e4f8c), [c8c442ae6a83](https://github.com/aurora-silicon/linux/commit/c8c442ae6a83502a90fca56d1b8e08e669ce03cb) | DjDeveloperr | drm/asahi: drop the sysfs object and queue-slot counters [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/g17/context.rs` | M,D | -| [3bb318ea84a1](https://github.com/aurora-silicon/linux/commit/3bb318ea84a1cd2d7661948b347270c8eaf71931), [8b1bcc708f82](https://github.com/aurora-silicon/linux/commit/8b1bcc708f820baa04c2998acf8513a0146d59cf), [ed235501b653](https://github.com/aurora-silicon/linux/commit/ed235501b6531eb218d3b058bab11a807ae17713), [152092e32a7f](https://github.com/aurora-silicon/linux/commit/152092e32a7fd7a7b3a96b8e45be7db78934b7d8) | DjDeveloperr | drm/asahi: drop the stalled scheduler-release warning [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/teardown.rs` | C,R,H | -| [110dd19ab7e0](https://github.com/aurora-silicon/linux/commit/110dd19ab7e0263538c8301f903471b1700eac12), [815912e331c3](https://github.com/aurora-silicon/linux/commit/815912e331c32ab6468a108ab34c6b26d60faecb), [9d8357e27590](https://github.com/aurora-silicon/linux/commit/9d8357e275907651adbb7022b812f789ece7d040), [24ce1bcdd8eb](https://github.com/aurora-silicon/linux/commit/24ce1bcdd8ebf0f8664c043a639c0201286f94e5) | DjDeveloperr | drm/asahi: build constant firmware objects from word tables [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fw/initdata.rs` | C,R,H | -| [b5a72b8cb8a5](https://github.com/aurora-silicon/linux/commit/b5a72b8cb8a581d84a4c35c2b4ecc11cd50fabfb), [cea457b72a30](https://github.com/aurora-silicon/linux/commit/cea457b72a308addcffbef0555408e3c2f021c7b), [8e98d0432927](https://github.com/aurora-silicon/linux/commit/8e98d0432927d780061fcc55516769f3d830291f), [7e317cd1218e](https://github.com/aurora-silicon/linux/commit/7e317cd1218e5461124fbfc8db7dd72e71253f8e) | DjDeveloperr | drm/asahi: grow the scheduler-release table instead of failing a close [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/teardown.rs` | C,R,H | -| [8afbe186d27a](https://github.com/aurora-silicon/linux/commit/8afbe186d27aab81bc71008838387799f1d9d4df), [c4f9aff1f720](https://github.com/aurora-silicon/linux/commit/c4f9aff1f720075ed3b059e6d82a5d8be5663768), [be6a3b5d938f](https://github.com/aurora-silicon/linux/commit/be6a3b5d938f2c51ef5b6d60990dcefd64cb677f), [18dbc2de6f21](https://github.com/aurora-silicon/linux/commit/18dbc2de6f21c92c49ffafce39a38c8d6439a5b5) | DjDeveloperr | drm/asahi: add a render flag for passes with at most four known primitives [#171](https://github.com/aurora-silicon/linux/pull/171) | Gated — FEW; `drivers/gpu/drm/asahi/g17/command.rs` | R | -| [7d34f2f65865](https://github.com/aurora-silicon/linux/commit/7d34f2f658658c1fd829700f2e14211a1b150ccd), [b1ec7881bf69](https://github.com/aurora-silicon/linux/commit/b1ec7881bf69ab6b1678761dec5552b28aa414e1), [3318d3e23f8e](https://github.com/aurora-silicon/linux/commit/3318d3e23f8e49a5721f9e2da0eea674eece1d2e), [c00f3a06ed2d](https://github.com/aurora-silicon/linux/commit/c00f3a06ed2d0400a5ec210c856f3a382971f033) | DjDeveloperr | drm/asahi: add a render flag that orders only the fragment stage on barriers [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/command.rs` | R,H | -| [e2b1485ec599](https://github.com/aurora-silicon/linux/commit/e2b1485ec599011654ac1f6ccc4dc78350b50566), [763771c2f3d0](https://github.com/aurora-silicon/linux/commit/763771c2f3d0613ecacaeb20d1cfd21809ead7d5), [0751d1c543c9](https://github.com/aurora-silicon/linux/commit/0751d1c543c933f65ec2ce2606d5effd25206721), [64820e0cb952](https://github.com/aurora-silicon/linux/commit/64820e0cb952592fff5708712a4b4766a8a12f4c) | DjDeveloperr | drm/asahi: give back the USC backing of idle retained compute queues [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — POWER; `drivers/gpu/drm/asahi/g17/freelist.rs` | I,C,R,P | -| [6825b2e8b6f7](https://github.com/aurora-silicon/linux/commit/6825b2e8b6f7d51be5f21a46821541ae8828c6e5), [9e693050e446](https://github.com/aurora-silicon/linux/commit/9e693050e44633bcf0503ec5b864a292d513b563), [ffbf4b465de9](https://github.com/aurora-silicon/linux/commit/ffbf4b465de966c4a5bf3b2e2881fd5678f98bfa), [3db48c0ac600](https://github.com/aurora-silicon/linux/commit/3db48c0ac600b5e919c4d2713dbd84e9b12b4ec4) | DjDeveloperr | drm/asahi: drop an exited owner's context from idle retained compute queues [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — POWER; `drivers/gpu/drm/asahi/g17/context.rs` | I,C,R,P | -| [dbea31c253f3](https://github.com/aurora-silicon/linux/commit/dbea31c253f3d1845a4998abed2db88177e82d54), [e85d3c35771a](https://github.com/aurora-silicon/linux/commit/e85d3c35771a27fc3721f13d572c2538e898837f), [9964d01e50ad](https://github.com/aurora-silicon/linux/commit/9964d01e50add98a41985adc69ace3bc5dc867f1), [5427403e7135](https://github.com/aurora-silicon/linux/commit/5427403e7135dd886ee52a78d73639bd5a2ccb17) | DjDeveloperr | drm/asahi: keep reclaim away from VMs that are in use or were just restored [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/mmu/lifetime.rs` | M,D | -| [34de15489113](https://github.com/aurora-silicon/linux/commit/34de15489113f71dd93695681d735afaddef10db), [c5fdbf93b7c8](https://github.com/aurora-silicon/linux/commit/c5fdbf93b7c8280dd1d266df8b4298b6b5c0645c), [5eb07ab2539b](https://github.com/aurora-silicon/linux/commit/5eb07ab2539bf7628366644c96a4742c934b9a78), [1c62cd0853b6](https://github.com/aurora-silicon/linux/commit/1c62cd0853b670104424bcfddeee7f7d9279304e) | DjDeveloperr | drm/asahi: count bindings and VM creation as reclaim activity [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/mmu/lifetime.rs` | M,D | -| [9bca711b6542](https://github.com/aurora-silicon/linux/commit/9bca711b65427b7dc0c384e6de2a783cde6e0160), [84e172f23883](https://github.com/aurora-silicon/linux/commit/84e172f23883c27a8eb0cdc85fa81de9c8879eb1), [3202a8b8912f](https://github.com/aurora-silicon/linux/commit/3202a8b8912f39ff7b7c06acc5fd604d5d0c4769), [dec3bc9eb622](https://github.com/aurora-silicon/linux/commit/dec3bc9eb622df05eca30716834c35506ee31f9f) | DjDeveloperr | drm/asahi: set the idle-VM reclaim quiet window to 2000 ms [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/mmu/residency.rs` | M,D | -| [f1018934472b](https://github.com/aurora-silicon/linux/commit/f1018934472b655ba44f1fcbfa2f3be2fdedb1fd), [d2046dcecf61](https://github.com/aurora-silicon/linux/commit/d2046dcecf61aceec6af3d013da811e147e3c410), [4963fa334b24](https://github.com/aurora-silicon/linux/commit/4963fa334b2439a0fc831ee3a5a8db008712a307), [1c1abce16316](https://github.com/aurora-silicon/linux/commit/1c1abce16316282e15f5e471b8ef0b5a33acc038) | DjDeveloperr | drm/asahi: release the VM status mirror object when the VM handle closes [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/g17/status.rs` | M,D | -| [cc0e08ecbe61](https://github.com/aurora-silicon/linux/commit/cc0e08ecbe61eae09d5be1619a0e6373888f7d02), [503bc0e39d66](https://github.com/aurora-silicon/linux/commit/503bc0e39d665ac97ac53e0b78b2851ca61d2242), [8057982690f1](https://github.com/aurora-silicon/linux/commit/8057982690f1f1954a83f62382873a8baf03bb8e), [6af79e6e57ef](https://github.com/aurora-silicon/linux/commit/6af79e6e57ef80d2b93d4c428956ec6cdfb11a3a) | DjDeveloperr | drm/asahi: unmap detached compute owners and free vacated pools off-lock [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/freelist.rs` | M,C,R | -| [90e691e8fe49](https://github.com/aurora-silicon/linux/commit/90e691e8fe49fa13756b6a64d22074c6e4e4a6cb), [b00ba3dcbfeb](https://github.com/aurora-silicon/linux/commit/b00ba3dcbfebf63d761a8018109bef6067a2cf8b), [6f6bef1b9fd7](https://github.com/aurora-silicon/linux/commit/6f6bef1b9fd7c46f0885eea0ece01a811e08c7d1), [0b4bd1537cc7](https://github.com/aurora-silicon/linux/commit/0b4bd1537cc71a1796b976c05cdab24e76549303) | DjDeveloperr | drm/asahi: retire a compute command on its record when its stamp never follows [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [f227c7671c0f](https://github.com/aurora-silicon/linux/commit/f227c7671c0fa54ab73b1477aaf6bbc482e29b8b), [2ceb94e6a1a7](https://github.com/aurora-silicon/linux/commit/2ceb94e6a1a7939d520401fcbb0f41ce5ce9f47a), [e978503f0047](https://github.com/aurora-silicon/linux/commit/e978503f00475864733aefc433d758f0254f401f), [f647d69cc504](https://github.com/aurora-silicon/linux/commit/f647d69cc5043bf1d3389c8e250e78935e5afa24) | DjDeveloperr | drm/asahi: log the first GPU work failure reported to each G17 VM [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — OBS; `drivers/gpu/drm/asahi/g17/status.rs` | O,F | -| [0685cf3905b7](https://github.com/aurora-silicon/linux/commit/0685cf3905b73081560c7c1adc28f76efda774fa), [e8e17790b150](https://github.com/aurora-silicon/linux/commit/e8e17790b150da70debb5e9a1c31027883ad90d3), [85ab080b193f](https://github.com/aurora-silicon/linux/commit/85ab080b193fa481276ebcb9393a93b25024384f), [c8ea00a9ed62](https://github.com/aurora-silicon/linux/commit/c8ea00a9ed621e2e5c7c84461091fda3a9b7cb7b) | DjDeveloperr | drm/asahi: name the completion path in the first-failure log line [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — OBS; `drivers/gpu/drm/asahi/g17/completion.rs` | O,F | -| [ef4fa278cd1a](https://github.com/aurora-silicon/linux/commit/ef4fa278cd1abc81d229ec5853175c35537a962c), [bbbbb8aba0a3](https://github.com/aurora-silicon/linux/commit/bbbbb8aba0a3a08da0b31f31dd0fa1655089c2b0), [ec743d4d34f8](https://github.com/aurora-silicon/linux/commit/ec743d4d34f89fa2ea639801062c957f807c54aa), [5d2a444327af](https://github.com/aurora-silicon/linux/commit/5d2a444327afc38543beb78a252e23661e4d4ecc) | DjDeveloperr | drm/asahi: use one monotonic clock helper across the G17 runtime [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | C,R,H | -| [860e86da2994](https://github.com/aurora-silicon/linux/commit/860e86da2994a4584ba5ce013c5ef5d79cbda111), [bca35f80a993](https://github.com/aurora-silicon/linux/commit/bca35f80a99330132651e21c61f4d0e5da583cd9), [388a083cca9a](https://github.com/aurora-silicon/linux/commit/388a083cca9a1ff7b98f14dc0e598a63494e7d89), [6850c91310a9](https://github.com/aurora-silicon/linux/commit/6850c91310a913b5ff9646261250e62b129f4ce8) | DjDeveloperr | drm/asahi: grow the scheduler-release table silently [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/teardown.rs` | C,R,H | -| [3cd28842a502](https://github.com/aurora-silicon/linux/commit/3cd28842a502864d73cbfeb7018d6f6e2e00dcdc), [033ec9a3b717](https://github.com/aurora-silicon/linux/commit/033ec9a3b71756814007305dfaf437f3e26c1195), [0c8194353943](https://github.com/aurora-silicon/linux/commit/0c8194353943469158f8651c5ec51723e130afa3), [e60f49eede0e](https://github.com/aurora-silicon/linux/commit/e60f49eede0ecf38cb206c4f59ff832b2aacc1d6) | DjDeveloperr | drm/asahi: give back the descriptor ring of vacated compute queues [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | M,C,R | -| [5a98c966960a](https://github.com/aurora-silicon/linux/commit/5a98c966960a4310f741538fea1fc04724acffdb), [c9c1859181ab](https://github.com/aurora-silicon/linux/commit/c9c1859181ab17b15b76c74dc36ef00ad7cac96e), [75535b36cc0e](https://github.com/aurora-silicon/linux/commit/75535b36cc0ea75d394b20e11b993bf22e1efe20), [5d630414e13f](https://github.com/aurora-silicon/linux/commit/5d630414e13f4e017628430820fff73a86e97de9) | DjDeveloperr | drm/asahi: return killed compute queues to service with fresh backing [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | M,C,R | -| [6cae1d77a10a](https://github.com/aurora-silicon/linux/commit/6cae1d77a10aee3e2cd7f52c92eb62b957f6e7ff), [b138b1c78a0e](https://github.com/aurora-silicon/linux/commit/b138b1c78a0ebbba6cef6b3976fc39bfd8b1e3d4), [4457298833f1](https://github.com/aurora-silicon/linux/commit/4457298833f1001a90c15d9277dee87ad6e11927), [16822976f9d3](https://github.com/aurora-silicon/linux/commit/16822976f9d375ddbdc788d968077a15660be5d7) | DjDeveloperr | drm/asahi: give back the render pool backing of evicted idle clients [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/g17/context.rs` | M,D | -| [8d77b4f20652](https://github.com/aurora-silicon/linux/commit/8d77b4f20652f18c7fb4e6ae9184eb88ab7e779e), [39c1fc51692c](https://github.com/aurora-silicon/linux/commit/39c1fc51692c3bfcb37c274ce84dfe812bceaaae), [7e8fe19766fd](https://github.com/aurora-silicon/linux/commit/7e8fe19766fd1b895120a8e7bd5fe78f7aca2a7c), [bff3853f260b](https://github.com/aurora-silicon/linux/commit/bff3853f260b02bdd9605bc6690905cb70aca29f) | DjDeveloperr | drm/asahi: carry a scheduling profile from DRM queue priority to firmware [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — PRIORITY; `drivers/gpu/drm/asahi/g17/context.rs` | Q | -| [a15128aa41ec](https://github.com/aurora-silicon/linux/commit/a15128aa41ecb760c5669ec03d8ffee55213bd6c), [87744d8c30b2](https://github.com/aurora-silicon/linux/commit/87744d8c30b28d86a4cc2c45b2e5009b730ed6b4), [fe676c6f4915](https://github.com/aurora-silicon/linux/commit/fe676c6f4915ec15bb3ea0880101eb5b29cfc255), [009b0fb93ba3](https://github.com/aurora-silicon/linux/commit/009b0fb93ba35380563055aa8bc725f36c505262) | DjDeveloperr | drm/asahi: drop two defensive clippy allowances in the VM binding paths [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [1567322c2517](https://github.com/aurora-silicon/linux/commit/1567322c251710c365592380a195ceb22979d781), [408df60b8f35](https://github.com/aurora-silicon/linux/commit/408df60b8f35a1f510750df51f5e46bfb51d51a4), [3d1be9ce9669](https://github.com/aurora-silicon/linux/commit/3d1be9ce966988190d72dcad1d0fa4dd1b9204c9), [410d8f80e9ab](https://github.com/aurora-silicon/linux/commit/410d8f80e9ab6b405d7f918901fcbe883bb2d9b2) | DjDeveloperr | drm/asahi: build the G17 boot objects region by region [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/initdata.rs` | C,R,H | -| [0e3bd3afd897](https://github.com/aurora-silicon/linux/commit/0e3bd3afd897637d7c42d54c8ca9adc25e5a691c), [2fa38fc95677](https://github.com/aurora-silicon/linux/commit/2fa38fc956777c4e357d44db60d1b7aafaac273f), [456e6601e69d](https://github.com/aurora-silicon/linux/commit/456e6601e69d15067bcccde93498fd58e22977a1), [f5bd61786e3b](https://github.com/aurora-silicon/linux/commit/f5bd61786e3b537fd811f0ea27d2ec33874232b0) | DjDeveloperr | drm/asahi: split the G17 render pair install paths out of build_render_pair [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs` | R,H | -| [fe926de1f191](https://github.com/aurora-silicon/linux/commit/fe926de1f191b798b49cbe57e36dfba0e0cc4ac7), [e89e97a5241c](https://github.com/aurora-silicon/linux/commit/e89e97a5241cd22b95cb60304f1e2426698c45af), [ef1251b62428](https://github.com/aurora-silicon/linux/commit/ef1251b62428a647c7ed4311cc6223ca1c8fc80a), [e0fa28b70ca9](https://github.com/aurora-silicon/linux/commit/e0fa28b70ca92d7942809827a7cff7e230d68826) | DjDeveloperr | drm/asahi: split the G17 render publication into preflight, barriers and announce [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render.rs` | R,H | -| [311b9ea8bf83](https://github.com/aurora-silicon/linux/commit/311b9ea8bf835bc7a53866f34b8520ffdc17ef01), [1235a9ee13fe](https://github.com/aurora-silicon/linux/commit/1235a9ee13fe9ed0bf846970e5f5cf9a3049e290), [f76a38f8511f](https://github.com/aurora-silicon/linux/commit/f76a38f8511fd9df3d53e30b899a780c17353d28), [74bc2f09ab74](https://github.com/aurora-silicon/linux/commit/74bc2f09ab74832be661557cacf374ee5fff11d7) | DjDeveloperr | drm/asahi: split the G17 compute publication preflight and queue configuration [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [f22f4cfb5b97](https://github.com/aurora-silicon/linux/commit/f22f4cfb5b97b17cf49e7ca9feb877313156f246), [74e91a7f9ad5](https://github.com/aurora-silicon/linux/commit/74e91a7f9ad5d2f61bd5846713e27838c6f5324a), [49e9337b68a4](https://github.com/aurora-silicon/linux/commit/49e9337b68a41b5f9a3a26d8d72e8b0eecc16844), [5ad7b191f7e6](https://github.com/aurora-silicon/linux/commit/5ad7b191f7e698e3ef140163c6ecf15d3e57ff85) | DjDeveloperr | drm/asahi: size the compute descriptor ring to the kicks that can be in flight [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | M,C,R | -| [bb5149df6a74](https://github.com/aurora-silicon/linux/commit/bb5149df6a74ead7da49be6953c63f4033229ff3), [9d92af630ad2](https://github.com/aurora-silicon/linux/commit/9d92af630ad2f55fe898d653e29c363c131ee4e3), [6d54c0fd885c](https://github.com/aurora-silicon/linux/commit/6d54c0fd885ceded70867de874f27987fc8f69b4), [5f6490414a68](https://github.com/aurora-silicon/linux/commit/5f6490414a683eef149ba6de38cbc27ba62f9a26) | DjDeveloperr | drm/asahi: pack G17 tiler heap blocks contiguously in their backing [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/buffer.rs` | M,C,R | -| [46c70ecebde4](https://github.com/aurora-silicon/linux/commit/46c70ecebde4be2fbd3e82e8311946a156504bf1), [f024202d33e8](https://github.com/aurora-silicon/linux/commit/f024202d33e8832b01e0cff6006fbb9e2b1178a3), [29ff1f70b488](https://github.com/aurora-silicon/linux/commit/29ff1f70b4880e79a8b980adc4d44d4eacb7c7e1), [d2a2c2fa97b9](https://github.com/aurora-silicon/linux/commit/d2a2c2fa97b994595209843720ad78b99b93f16a) | DjDeveloperr | drm/asahi: allocate only the G17 boot pool blocks that are used [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/initdata.rs` | M,C,R | -| [56b8769a1364](https://github.com/aurora-silicon/linux/commit/56b8769a1364bc6c46ab48463afa203a5aec92bb), [614f11f2eb30](https://github.com/aurora-silicon/linux/commit/614f11f2eb30471e02d42f7eab08e9bf4ec4cd41), [c304acb009f0](https://github.com/aurora-silicon/linux/commit/c304acb009f0264d1485596f651495d66efb0fec), [272955b009fe](https://github.com/aurora-silicon/linux/commit/272955b009fe844d4d06361365f166d75b6b451b) | DjDeveloperr | drm/asahi: give back idle G17 tiler heap growth beyond recent use [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — POWER; `drivers/gpu/drm/asahi/g17/buffer.rs` | I,C,R,P | -| [3434c1aab8a6](https://github.com/aurora-silicon/linux/commit/3434c1aab8a6c5d305198347040b8237c4bdce06), [35fe32db0e80](https://github.com/aurora-silicon/linux/commit/35fe32db0e806643f201fc6871095da0e68cfaf8), [1464c4bb1ade](https://github.com/aurora-silicon/linux/commit/1464c4bb1ade2f3fe0625eb93776b26a7f91db96), [c01af7a9e73c](https://github.com/aurora-silicon/linux/commit/c01af7a9e73c789c6a9f98547585a7048927af30) | DjDeveloperr | drm/asahi: give back warm G17 compute pools after ten idle seconds | Active — POWER; `drivers/gpu/drm/asahi/g17/runtime.rs` | I,C,R,P | -| [43a409830c67](https://github.com/aurora-silicon/linux/commit/43a409830c673f190213d2643d50f7500bbf69ab), [882abd400823](https://github.com/aurora-silicon/linux/commit/882abd400823eedce71e3def3c17a3143cd7318b), [57e6637d9f08](https://github.com/aurora-silicon/linux/commit/57e6637d9f087775ee87dcab22dd6c4bb0d4f685), [2d7de7690cc0](https://github.com/aurora-silicon/linux/commit/2d7de7690cc0f9c8d3a74b08c33999593b720aac) | DjDeveloperr | drm/asahi: keep compaction away from GEM pages held for the GPU | Active — MEM; `drivers/gpu/drm/asahi/gem.rs` | M,D | -| [dd109eec40ac](https://github.com/aurora-silicon/linux/commit/dd109eec40ace8e09c436eed1997e302e2b26842), [8bc791526797](https://github.com/aurora-silicon/linux/commit/8bc791526797872caece1891ed792e69dce48438), [76b1755a0610](https://github.com/aurora-silicon/linux/commit/76b1755a06109a66416af0282ec8310dc8a3292b), [6dd0f73fd3b2](https://github.com/aurora-silicon/linux/commit/6dd0f73fd3b2bade5415b31346aadeb2f38d446e) | DjDeveloperr | drm/asahi: complete page-table stores before GPU TLB invalidation | Active — MEM; `drivers/gpu/drm/asahi/g17/kick.rs` | M,D | -| [bec1201676a6](https://github.com/aurora-silicon/linux/commit/bec1201676a6f3b073e8d93791d8c9c7e6c99d7f), [36b80077e7c4](https://github.com/aurora-silicon/linux/commit/36b80077e7c45c57469f9d8cd6ba3e0aa6007cd6), [91e15ed8e7a6](https://github.com/aurora-silicon/linux/commit/91e15ed8e7a681ca293f94e337f59563cd03879d), [019ad857ddfa](https://github.com/aurora-silicon/linux/commit/019ad857ddfa08ed2473eae34db5b8b8d98b068e) | DjDeveloperr | drm/asahi: remove tiler-shrink diagnostic logging | Active — OBS; `drivers/gpu/drm/asahi/g17/buffer.rs` | O,F | -| [692752fb7bf6](https://github.com/aurora-silicon/linux/commit/692752fb7bf60c9e5f83e80dba56779fa48961c1), [3f6a8c31626f](https://github.com/aurora-silicon/linux/commit/3f6a8c31626fc077dbfcea147cd6e30cb28c5e70), [27178c4e373a](https://github.com/aurora-silicon/linux/commit/27178c4e373a23ba1015647f774a3102265c1b27), [d128b5e48465](https://github.com/aurora-silicon/linux/commit/d128b5e484658066c82504df550f6f13abcbd1cc) | DjDeveloperr | drm/asahi: reuse the render state mapping for auxiliary framebuffers | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render/memory.rs` | R,H | -| [a2e5af9f5f03](https://github.com/aurora-silicon/linux/commit/a2e5af9f5f0334dbcdd069cc2944f11313f5d67c), [54101717e1de](https://github.com/aurora-silicon/linux/commit/54101717e1dee1b6fd64f32ae8888ec8429b821e), [c0e47197c71c](https://github.com/aurora-silicon/linux/commit/c0e47197c71c80b57974130a06386e101bbdc7ee) | Ryan Murray | drm/asahi: allocate imported and dumb GEM objects as asahi objects | Active — MEM; `drivers/gpu/drm/asahi/gem.rs` | M,D | -| [c29c639e0934](https://github.com/aurora-silicon/linux/commit/c29c639e09349ce24a2bf768c33476e2e27b2512), [c3a21491589b](https://github.com/aurora-silicon/linux/commit/c3a21491589bb62b2279867805b8e87fd2629e4d), [f2760d2f42ec](https://github.com/aurora-silicon/linux/commit/f2760d2f42ec4ede63abb18918ef4abeb4b3de35) | Dj | drm/asahi: preserve TA prefix dependencies across render pairs | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render.rs` | R,H | -| [7598420667b6](https://github.com/aurora-silicon/linux/commit/7598420667b6be8788d768316e4218ff3c3fc1ff), [d2f283ac0589](https://github.com/aurora-silicon/linux/commit/d2f283ac058952ea84da562a7f6e6a911ebf879a), [1af8de012d22](https://github.com/aurora-silicon/linux/commit/1af8de012d2221144395f900729619b5065b14fd) | Dj | drm/asahi: provision G17P ray traversal pools from Gen1 SCS demand | Gated — RT; `drivers/gpu/drm/asahi/g17/command.rs` | F | -| [e864801fe49c](https://github.com/aurora-silicon/linux/commit/e864801fe49c9dc6d1fd6e4d1b6c2a607e672f71), [a075a1fab446](https://github.com/aurora-silicon/linux/commit/a075a1fab446a49270d387274f7793d3e9ee6560), [6ffb2dc7a658](https://github.com/aurora-silicon/linux/commit/6ffb2dc7a658e2e6bcaf48a75461b8d7e84549bf) | DjDeveloperr | drm/asahi: recycle settled quarantined G17 compute queues [#305](https://github.com/aurora-silicon/linux/pull/305) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [ae76590d6ea0](https://github.com/aurora-silicon/linux/commit/ae76590d6ea0313a4741fdce5025f6c336eaf90c), [b9fd334a9c96](https://github.com/aurora-silicon/linux/commit/b9fd334a9c96f58640e0ef6ce2010749b85e7c4f), [8ad79fc25869](https://github.com/aurora-silicon/linux/commit/8ad79fc25869a9a5cd36262cc8a702b4327cf437) | DjDeveloperr | drm/asahi: g17: replay render groups firmware retired without executing [#307](https://github.com/aurora-silicon/linux/pull/307) | Active — REC; `drivers/gpu/drm/asahi/g17/job.rs` | F,Q | -| [41786756b43d](https://github.com/aurora-silicon/linux/commit/41786756b43da732fa85c6ac3e23a33e3baa9335), [0a2cdd456013](https://github.com/aurora-silicon/linux/commit/0a2cdd456013347efd1bc2a73d79e291d2d77fbc), [167852510065](https://github.com/aurora-silicon/linux/commit/1678525100652694b0aaee977ea2012b487d6a51) | DjDeveloperr | drm/asahi: g17: never kill compute commands with ray traversal scratch [#308](https://github.com/aurora-silicon/linux/pull/308) | Gated — RT; `drivers/gpu/drm/asahi/g17/queue/compute/exit.rs` | F | -| [d3f4f5dd1b59](https://github.com/aurora-silicon/linux/commit/d3f4f5dd1b592ba925f469133ebac876a101ddb7), [ec3aa2ff51b8](https://github.com/aurora-silicon/linux/commit/ec3aa2ff51b8ad6f9f39c70bf563866ee81baecb), [48b2631fdaab](https://github.com/aurora-silicon/linux/commit/48b2631fdaab66dc7bd850b3006c0f85a73aba0e) | DjDeveloperr | drm/asahi: g17: ray queries in render stages [#309](https://github.com/aurora-silicon/linux/pull/309) | Gated — RT; `drivers/gpu/drm/asahi/g17/command.rs` | F | -| [079f81d5a637](https://github.com/aurora-silicon/linux/commit/079f81d5a637e459a33e8f75a97b91f2454f1499), [2d1fcbe1a980](https://github.com/aurora-silicon/linux/commit/2d1fcbe1a9808f52f2427e4c1237b2b0eba7b7fb), [03426fb46c9c](https://github.com/aurora-silicon/linux/commit/03426fb46c9ce29e5b58db52cfefd09fac156fea) | Ryan Murray | soc: apple: mailbox, rtkit: Allow holding received messages | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [a98bb5de4b2e](https://github.com/aurora-silicon/linux/commit/a98bb5de4b2e6dd5d54150008bd322f97c8dbd0d), [c623f821fdfa](https://github.com/aurora-silicon/linux/commit/c623f821fdfaada5df34d2a79fcc4586b0d7323b), [23b2b6f4a1c9](https://github.com/aurora-silicon/linux/commit/23b2b6f4a1c93dbc90768e271c92bc914e5d676f) | Ryan Murray | soc: apple: pmp: log tunables the boot loader does not provide at debug level [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [689592f3219f](https://github.com/aurora-silicon/linux/commit/689592f3219f4733c038cdf72e5a911084d22521), [bc1d13129d6d](https://github.com/aurora-silicon/linux/commit/bc1d13129d6d88ee93515eb547967d87170e5da3), [f80758084279](https://github.com/aurora-silicon/linux/commit/f80758084279064eb1c60e6bfa56f7649bb86a4d) | Ryan Murray | iommu: apple-dart: Demote informational probe messages to debug [#314](https://github.com/aurora-silicon/linux/pull/314) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [e28469b8a38e](https://github.com/aurora-silicon/linux/commit/e28469b8a38e4102fd5c5b877bf51439fc00fca3), [00baae48e464](https://github.com/aurora-silicon/linux/commit/00baae48e464c44cb754d52552d3bd1f431d52f7) | Ryan Murray | iommu: apple-dart: Invalidate every stream in a domain bitmap | Active — DART; `drivers/iommu/Kconfig` | D,B | -| [aade7be0a12a](https://github.com/aurora-silicon/linux/commit/aade7be0a12a38ae8bb276fac80df27eaea97e32), [b13ede3059b0](https://github.com/aurora-silicon/linux/commit/b13ede3059b0bc51bca6033e405606e525ec2259), [4cf2113dc363](https://github.com/aurora-silicon/linux/commit/4cf2113dc36329544edc54b09dc775c5888c3975) | Ryan Murray | soc: apple: mcc: factor out disabling and flushing planes [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — MCC; `drivers/soc/apple/mcc.c` | M,P | -| [ef010a009b3f](https://github.com/aurora-silicon/linux/commit/ef010a009b3ffb15af9794ed37083d1ad2c4facb), [0cba4dd60674](https://github.com/aurora-silicon/linux/commit/0cba4dd60674aa9ded2c27eaae1ff7bf4f1e243e), [8bf158a74ea7](https://github.com/aurora-silicon/linux/commit/8bf158a74ea7e2a5a7e42082fc882d3508119a09) | Ryan Murray | soc: apple: mcc: disable the planes already enabled when enabling fails [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — MCC; `drivers/soc/apple/mcc.c` | M,P | -| [a099186592d6](https://github.com/aurora-silicon/linux/commit/a099186592d6aa010ab7da6d71c7c88d1801345d), [e46e30ff7457](https://github.com/aurora-silicon/linux/commit/e46e30ff7457d01b6e9cb97e8d7a5b0fd8fe20e6), [4653ef5a873f](https://github.com/aurora-silicon/linux/commit/4653ef5a873f16c68a1e9e9080a41395628ca9d4) | Ryan Murray | pmdomain: apple: pmc: undo a partial agent enable [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — PMC; `drivers/pmdomain/apple/pmc.c` | P,C,R | -| [49bb592b9e9f](https://github.com/aurora-silicon/linux/commit/49bb592b9e9f626d06af3296172be8d3aa99a320), [43f4894e7c18](https://github.com/aurora-silicon/linux/commit/43f4894e7c18a46f5e379dd994f0fbd5def67ed7), [a86e8e5637c0](https://github.com/aurora-silicon/linux/commit/a86e8e5637c07504ca09b7bfa5639492af065d8c) | Ryan Murray | pmdomain: apple: pmc: restore the AP's own DCS vote when a limit is lifted [#317](https://github.com/aurora-silicon/linux/pull/317) | Gated — DCS; `drivers/pmdomain/apple/Kconfig` | P | -| [75984fc70c8f](https://github.com/aurora-silicon/linux/commit/75984fc70c8f252d96910dad4cd8635f4977b74f), [6351fe2e5e29](https://github.com/aurora-silicon/linux/commit/6351fe2e5e29f4447d997214d785f10885ef7538), [dba445e67326](https://github.com/aurora-silicon/linux/commit/dba445e6732685313e036e73dc2753c7ed8cbcb6) | Ryan Murray | soc: apple: clpc: remove the debugfs override of the floor [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — CLPC; `drivers/soc/apple/clpc.c` | P,C,R,I | -| [9e4e936ed101](https://github.com/aurora-silicon/linux/commit/9e4e936ed10105188f37f3f8b2c27042e2e2ec58), [c47472a2343b](https://github.com/aurora-silicon/linux/commit/c47472a2343b6c35235e48db178cf76ae94c1f73), [9dfd51203aa8](https://github.com/aurora-silicon/linux/commit/9dfd51203aa80ce8867d98ba03c79fbb283039c2) | Ryan Murray | soc: apple: clpc: make the demand policy per-SoC data, drop the GPU input [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — CLPC; `drivers/soc/apple/clpc.c` | P,C,R,I | -| [64290b216821](https://github.com/aurora-silicon/linux/commit/64290b21682151a3eb4c93d5f666d07f56aae87c), [d19ce09e3508](https://github.com/aurora-silicon/linux/commit/d19ce09e35089ec81bcc82f55198498901df10ac), [10e182579152](https://github.com/aurora-silicon/linux/commit/10e1825791523747c5f0d4ac44570fe4418ff586) | Ryan Murray | pmdomain: apple: pmgr-pwrstate: log always-on domains left off at info level [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — PMGR; `drivers/pmdomain/apple/pmgr-pwrstate.c` | B,F | -| [57dafd4b412f](https://github.com/aurora-silicon/linux/commit/57dafd4b412f8b49be5362a98503be11138cd388), [f86db4089cee](https://github.com/aurora-silicon/linux/commit/f86db4089cee44d2f54de73f60aa32c8a07ffd3a), [1ef9c2113ecd](https://github.com/aurora-silicon/linux/commit/1ef9c2113ecdf2851908e4bd9793876d92152d27) | Ryan Murray | soc: apple: rtkit: Do not warn when buffers are retained on purpose [#314](https://github.com/aurora-silicon/linux/pull/314) | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [5ebe92d17a32](https://github.com/aurora-silicon/linux/commit/5ebe92d17a32112b13e74553bab5b0e0b7c0e147), [7b29e7caccc4](https://github.com/aurora-silicon/linux/commit/7b29e7caccc4896949b0dff4dd8caf7c5fa3f0c0), [9779b2457e8f](https://github.com/aurora-silicon/linux/commit/9779b2457e8f13b0f257964570c9883f079e65f6) | Ryan Murray | pmdomain: apple: pmc: keep the DCS limit state when the rail enable fails [#345](https://github.com/aurora-silicon/linux/pull/345) | Gated — DCS; `drivers/pmdomain/apple/pmc.c` | P | -| [962dacdbb6ad](https://github.com/aurora-silicon/linux/commit/962dacdbb6ad38d9fc723d9f8ea3b3d8dee0e6a9), [4209657d7d94](https://github.com/aurora-silicon/linux/commit/4209657d7d948671c9872e1cbb53f66774793607), [1c797d3eb5cb](https://github.com/aurora-silicon/linux/commit/1c797d3eb5cb79f7e80696b4d7c93800172771c0) | Ryan Murray | cpufreq: apple-soc: say why a cluster with verified transitions fails init [#345](https://github.com/aurora-silicon/linux/pull/345) | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [854b2e6ec82e](https://github.com/aurora-silicon/linux/commit/854b2e6ec82ea030f3dcfd8ff024393019dd3818), [5a02a0cd2865](https://github.com/aurora-silicon/linux/commit/5a02a0cd28651e4eb3f2eede40af991d8d265a51), [13857139ed46](https://github.com/aurora-silicon/linux/commit/13857139ed4643ef532281808bc8035ad64c9a10) | Ryan Murray | soc: apple: mcc: print the boot DMA device before dropping its node [#345](https://github.com/aurora-silicon/linux/pull/345) | Active — MCC; `drivers/soc/apple/mcc.c` | M,P | -| [e157c990ad98](https://github.com/aurora-silicon/linux/commit/e157c990ad98e3008b552e45d0c85448f95e4266), [ec4fc264985c](https://github.com/aurora-silicon/linux/commit/ec4fc264985c5505be71434f96cc949d0037801f), [0b65493ccd0f](https://github.com/aurora-silicon/linux/commit/0b65493ccd0f4a779e592258032cb40ce03d1a1c) | Ryan Murray | pmdomain: apple: pmgr-pwrstate: tidy the rate-limited error messages [#345](https://github.com/aurora-silicon/linux/pull/345) | Active — PMGR; `drivers/pmdomain/apple/pmgr-pwrstate.c` | B,F | -| [3a9f56606ec3](https://github.com/aurora-silicon/linux/commit/3a9f56606ec3001c7cd7df137cf49a6ae2db0157), [3762bb8f345d](https://github.com/aurora-silicon/linux/commit/3762bb8f345de262f1efca74de864457a3adc9aa), [a516c3f7c3f8](https://github.com/aurora-silicon/linux/commit/a516c3f7c3f85aeb05efe5e3aff5b7890c7d022c) | Ryan Murray | iommu: apple-dart: Invalidate every DART even if a TLB sync step fails [#345](https://github.com/aurora-silicon/linux/pull/345) | Active — DART; `drivers/iommu/apple-dart-test.c` | D,B | -| [8a2875a6789d](https://github.com/aurora-silicon/linux/commit/8a2875a6789d2a4f1452beafd50e4de134b30683), [0f997e1c9354](https://github.com/aurora-silicon/linux/commit/0f997e1c9354b9aa18c7ae13cdf61328b1f50d9d), [df5213734e31](https://github.com/aurora-silicon/linux/commit/df5213734e31c372fc36a2375539e4d69b5f815a) | Ryan Murray | soc: apple: rtkit: Only parse an initial crash log in inherited sessions [#345](https://github.com/aurora-silicon/linux/pull/345) | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [d6caa25b65d2](https://github.com/aurora-silicon/linux/commit/d6caa25b65d2ca7fc7315ee568e0cbd250a9593c), [f501cf5f491d](https://github.com/aurora-silicon/linux/commit/f501cf5f491da7527d71b86cd164e094aac050fd), [82494bf5c6b0](https://github.com/aurora-silicon/linux/commit/82494bf5c6b07739782eeac837b9f6a96c70ca36) | Ryan Murray | iommu/apple-dart: Do not reset a DART that kept its state across sleep [#336](https://github.com/aurora-silicon/linux/pull/336) | Active — DART; `drivers/iommu/apple-dart-test.c` | D,B | -| [91d9f93cf842](https://github.com/aurora-silicon/linux/commit/91d9f93cf842a892913e7ce56218ddc27292a6c1), [dc02d89a1465](https://github.com/aurora-silicon/linux/commit/dc02d89a1465719e6ab3b3a5e31dbea08e1a8f68), [39bc76211b30](https://github.com/aurora-silicon/linux/commit/39bc76211b30ca23b29eb740ffdf0ae8cf2ed5d3) | Ryan Murray | iommu/apple-dart: Keep a retained DART in bypass from being reset [#336](https://github.com/aurora-silicon/linux/pull/336) | Active — DART; `drivers/iommu/apple-dart-test.c` | D,B | -| [b6b28c111cff](https://github.com/aurora-silicon/linux/commit/b6b28c111cff20b5312fee34ca544ce6f7fd00a5), [469fd41db0a3](https://github.com/aurora-silicon/linux/commit/469fd41db0a33df014d0523648c5e1f052895c9a), [d9fc21447419](https://github.com/aurora-silicon/linux/commit/d9fc214474191909db140a5ba565a014819bd6de) | Ryan Murray | iommu/apple-dart: Restore the translations when the reset on resume fails [#336](https://github.com/aurora-silicon/linux/pull/336) | Active — DART; `drivers/iommu/apple-dart-test.c` | D,B | -| [4bfe19d0ad80](https://github.com/aurora-silicon/linux/commit/4bfe19d0ad8042e95b784fe2e439e15c8f869ac5), [cd1ff978d660](https://github.com/aurora-silicon/linux/commit/cd1ff978d6600a354b93fd829d9c9588715c44f1), [43c7fc8f82a6](https://github.com/aurora-silicon/linux/commit/43c7fc8f82a65f2e3807f41f03421df2b27ed3de) | Ryan Murray | irqchip/apple-aic: Allow interrupts to wake the system | Active — AIC; `drivers/irqchip/irq-apple-aic.c` | O,C,I | -| [345f6329c88b](https://github.com/aurora-silicon/linux/commit/345f6329c88b1ea97ecf1c373bc573a9c20947e7), [eee098196369](https://github.com/aurora-silicon/linux/commit/eee098196369f3a2aebe4f99333c53d538caa1c5) | Ryan Murray | drm/asahi: queue background work on system_dfl_wq | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | C,R,H | -| [e04141b6136c](https://github.com/aurora-silicon/linux/commit/e04141b6136c63f61679eda781cabe349297d58e), [a741120e3ca0](https://github.com/aurora-silicon/linux/commit/a741120e3ca0d349dffab6cc32086935ecb98d81) | Chris Kearney | soc: apple: validate PMP boot arguments before patching | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [8a74c2db9581](https://github.com/aurora-silicon/linux/commit/8a74c2db9581fd106dc90be11fb1a1e075bf07fa), [d67dbeedca63](https://github.com/aurora-silicon/linux/commit/d67dbeedca63d1389fb5754d419fffae0c678155) | Chris Kearney | soc: apple: bound PMP arguments by the mapped SRAM size | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [6c53c0ff9715](https://github.com/aurora-silicon/linux/commit/6c53c0ff9715f055de8af928ed57277f1f0f30a2), [687f1c4f2190](https://github.com/aurora-silicon/linux/commit/687f1c4f21906c698f38c29c467f4aa74425509e) | Eryk Wieliczko | soc: apple: acknowledge serialized PMP device power commands | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [5a68774e87a8](https://github.com/aurora-silicon/linux/commit/5a68774e87a8baa711c211757b709966b2193be5), [fefec69b9fca](https://github.com/aurora-silicon/linux/commit/fefec69b9fca69f98a026a4dbdf9bde89b64544b) | Chris Kearney | soc: apple: retry unsent RTKit endpoint starts once | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [dc7d0b49a07d](https://github.com/aurora-silicon/linux/commit/dc7d0b49a07df88aab2ee9cbb3fae17db8694f2b), [5bd0a91f565c](https://github.com/aurora-silicon/linux/commit/5bd0a91f565cf815b9f999b3e704edba2563aac8) | Marius Gehrmann | soc: apple: rtkit: Honour apple,sync-syslog-ack | Active — RTKIT; `drivers/soc/apple/rtkit-internal.h` | B,F | -| [d67d380d1519](https://github.com/aurora-silicon/linux/commit/d67d380d1519babe4b9d080830e31bca56da4d8f), [9d0290148561](https://github.com/aurora-silicon/linux/commit/9d029014856181eb6190324b8300d82590ab2e8b) | Chris Kearney | soc: apple: rtkit: cap the kdebug buffer, and take a late completion | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [1369d18b4ec7](https://github.com/aurora-silicon/linux/commit/1369d18b4ec7bf0a631bc68fbdf7d894f2a4c542), [0d9ac5799dd4](https://github.com/aurora-silicon/linux/commit/0d9ac5799dd4dffe26513b100e93930bb3833a53) | Eryk Wieliczko | soc: apple: acknowledge OSLog progress in negotiated and inherited sessions | Active — RTKIT; `drivers/soc/apple/rtkit-internal.h` | B,F | -| [e47d06ceb56f](https://github.com/aurora-silicon/linux/commit/e47d06ceb56fd73444f3e17954f961dce5edfdcf), [47e137e98667](https://github.com/aurora-silicon/linux/commit/47e137e986675ca44843155e66b731c167932749) | Chris Kearney | iommu/apple-dart: reserve retained firmware tables and root slots | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [e663049674c8](https://github.com/aurora-silicon/linux/commit/e663049674c81f6818a88b594f029d0bf9f45ccc), [058d2b7355cf](https://github.com/aurora-silicon/linux/commit/058d2b7355cffe72dad9053486a26ae2822d51a2) | DjDeveloperr | soc: apple: finish the merge of DART, QSPI and SMC hwmon | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [d97a27e94fd8](https://github.com/aurora-silicon/linux/commit/d97a27e94fd8967ce1c3846dcc71628a8b39db36), [6dbfbcb21eb0](https://github.com/aurora-silicon/linux/commit/6dbfbcb21eb09d07ae59037a1ceca8cc3500841f) | Eryk Wieliczko | drm/asahi: validate GEM size before page rounding | Active — MEM; `drivers/gpu/drm/asahi/gem.rs` | M,D | -| [6d457ae0a70c](https://github.com/aurora-silicon/linux/commit/6d457ae0a70c583dc760d05ac552829d7370060f), [b038d2767d6e](https://github.com/aurora-silicon/linux/commit/b038d2767d6e08c0dae43c87da89dfd77d719f7c) | Chris Kearney | arm64: dts: apple: t8140: drop the t6000 fallback from the GFX report | Active translated data — FW | B,P | -| [496040e469aa](https://github.com/aurora-silicon/linux/commit/496040e469aa1ea3457c89cbd677d9f964614cca), [17bf156987c5](https://github.com/aurora-silicon/linux/commit/17bf156987c5f7be583bd5efc86430b1055efc36) | Chris Kearney | pmdomain: apple: pmp-report: match T8140 report entries by compatible | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [e033fe71b24d](https://github.com/aurora-silicon/linux/commit/e033fe71b24da2b2aabc90b9c5faa5bd0f497d9f), [5f7925d83ca6](https://github.com/aurora-silicon/linux/commit/5f7925d83ca680ba7760dbd16b9e0cb61029161a) | Chris Kearney | drm/asahi: keep the range TLBI base address in its field | Gated — UAT; `drivers/gpu/drm/asahi/mem.rs` | D | -| [6582e3d5ef6f](https://github.com/aurora-silicon/linux/commit/6582e3d5ef6f47ff7e0a11d3fffa47f15ef22a44), [f7132eb38e81](https://github.com/aurora-silicon/linux/commit/f7132eb38e81e5af14711b3da87aa6cf96b3ba98) | Ryan Murray | iommu: apple-dart: Factor out the DT DMA window parse | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [fc7981e78871](https://github.com/aurora-silicon/linux/commit/fc7981e78871a2ec91b38835bc84e03611b4e860), [ff11ec1083af](https://github.com/aurora-silicon/linux/commit/ff11ec1083af04c76c1d91fcebc78333681cf519) | Chris Kearney | pmdomain: apple: validate PMP startup tables before seeding | Active — PMP; `drivers/pmdomain/apple/.kunitconfig.apple-pmp` | P,B | -| [4c673adf2c11](https://github.com/aurora-silicon/linux/commit/4c673adf2c110c8264da8b0130eaf181fd6bd560), [782906a65540](https://github.com/aurora-silicon/linux/commit/782906a65540c569f6afa8b49b8c6ac22c9e8dc5) | Ryan Murray | pmdomain: apple: pmp-report: select OF_DYNAMIC | Active — PMP; `drivers/pmdomain/apple/Kconfig` | P,B | -| [f78d7690bfd2](https://github.com/aurora-silicon/linux/commit/f78d7690bfd2d927462c7af34242d6476a0cf59c), [a41d634596e5](https://github.com/aurora-silicon/linux/commit/a41d634596e536031e719b5ea8a3082220e8ec61) | Ryan Murray | drm/asahi: mmu: preallocate enough GPUVAs to unmap across two mappings | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [10fc7af5e0b8](https://github.com/aurora-silicon/linux/commit/10fc7af5e0b897112afaa5fc9ab791f241244969), [755ac9ed1425](https://github.com/aurora-silicon/linux/commit/755ac9ed142576a6e27da54a39b68290e861b34b) | DjDeveloperr | drm/asahi: g17: move the G17P UAPI past the M3 and J613 numbers | Active translated data — FW; `drivers/gpu/drm/asahi/g17/command.rs` | B,C,R | -| [6d5b51d6e818](https://github.com/aurora-silicon/linux/commit/6d5b51d6e818fc0b8915b43a030854d6d96ff330), [62aae2f0f8cb](https://github.com/aurora-silicon/linux/commit/62aae2f0f8cb52a40b2cf4ea21212ad2badd267c) | Ryan Murray | drm/asahi: uapi: use integration/aurora's wording | Active translated data — FW | B,C,R | -| [ff25cb1691ff](https://github.com/aurora-silicon/linux/commit/ff25cb1691ffa6e285dbcb014992e3838f4ad6fe) | Ryan Murray | drm/asahi: Adapt the lifetime and module-ownership changes to Linux 7.3 [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — DRM; `drivers/gpu/drm/asahi/g17/job.rs` | C,H,M,F | -| [2348e8c3acd2](https://github.com/aurora-silicon/linux/commit/2348e8c3acd2920ca583d801645e8387fd80c7f2) | Ryan Murray | drm/asahi: regs: Hold the G17 SGX mapping as a DevresIoMem [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — MEM; `drivers/gpu/drm/asahi/regs.rs` | M,D | -| [d4128b7c28ce](https://github.com/aurora-silicon/linux/commit/d4128b7c28ce177d227ff5488145e8eedd970610) | Ryan Murray | drm/asahi: make SG backing leases revocable [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — DRM; `drivers/gpu/drm/asahi/gem.rs` | C,H,M,F | -| [464cb2e30ae3](https://github.com/aurora-silicon/linux/commit/464cb2e30ae395d13723d161f2aef41066dbb79d) | Ryan Murray | drm/asahi: attribute GPU memory to its creator and limit it [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — MEM; `drivers/gpu/drm/asahi/asahi_core.rs` | M,D | -| [47f408da5996](https://github.com/aurora-silicon/linux/commit/47f408da5996da161de66282da83550bf436450e) | Ryan Murray | drm/asahi: clean up Clippy diagnostics in Aurora additions [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — OBS; `drivers/gpu/drm/asahi/g17/command.rs` | O,F | -| [e44a6b59f5d2](https://github.com/aurora-silicon/linux/commit/e44a6b59f5d248ee1a026b9dbb6dbd244e35a1d7) | Ryan Murray | soc: apple: pmp: use lossless command and bootargs conversions | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [761626d47af3](https://github.com/aurora-silicon/linux/commit/761626d47af3eb6da3ff8c998373646349aa7169) | Ryan Murray | drm/apple: quiet routine H17P external run-mode syslog records | Active — DISPLAY; `drivers/gpu/drm/apple/Makefile` | B | -| [ac38eb0f57a1](https://github.com/aurora-silicon/linux/commit/ac38eb0f57a17f59eb2ce8158df1fb81aeff2955) | Ryan Murray | drm/asahi: g17: wait for a compute command's stamp before releasing it [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [1e3b9caebc7b](https://github.com/aurora-silicon/linux/commit/1e3b9caebc7b1924acc3643222ff95b85e62bdb7) | Ryan Murray | drm/asahi: memacct: Read the module parameters by value on Linux 7.3 [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — MEM; `drivers/gpu/drm/asahi/memacct.rs` | M,D | -| [db2943a27f88](https://github.com/aurora-silicon/linux/commit/db2943a27f88dcd011ae97498cbf2250a4245463) | Jonathan Goyvaerts | soc: apple: rtkit: Log unknown oslog messages at debug level | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [1797c344df7f](https://github.com/aurora-silicon/linux/commit/1797c344df7f7631b2f9be7c9be1a55d8852b164) | Jonathan Goyvaerts | pmdomain: apple: pmp-report: Add T6040 support [#374](https://github.com/aurora-silicon/linux/pull/374) | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [927c31856676](https://github.com/aurora-silicon/linux/commit/927c318566760e7b4845d36904022c38271b925d) | Jonathan Goyvaerts | soc: apple: pmp: Add T6040 support [#374](https://github.com/aurora-silicon/linux/pull/374) | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [7fcc7fd38c43](https://github.com/aurora-silicon/linux/commit/7fcc7fd38c43b6aa64ea2270dcd32cdd57d19f37) | Ryan Murray | drm/asahi: carry G17 admission prerequisites to 7.3 [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — MEM; `drivers/gpu/drm/asahi/g17/freelist.rs` | M,D | -| [c9f72dc51116](https://github.com/aurora-silicon/linux/commit/c9f72dc51116c12b3aa840185eee5a45f4b298b5) | Ryan Murray | drm/asahi: carry G17 pool-release recovery and stamp-wait fixup to 7.3 [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [10e9da2303fc](https://github.com/aurora-silicon/linux/commit/10e9da2303fc79dc205989075855350020bf115b) | Ryan Murray | drm/asahi: hand abandoned compute growth back to witness settlement [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — SHARED; `drivers/gpu/drm/asahi/g17/freelist.rs` | C,H | -| [e933ad436de0](https://github.com/aurora-silicon/linux/commit/e933ad436de06981d95e9de6ce5626f4ba99e6ff) | Ryan Murray | drm/asahi: borrow the compute pool mutably for header replacement [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — GMEM; `drivers/gpu/drm/asahi/g17/freelist.rs` | M,C,R | -| [04358c1ebe86](https://github.com/aurora-silicon/linux/commit/04358c1ebe86cfbfdc926cfb41ff3e3549248279) | Ryan Murray | drm/asahi: hold failed growth reservations until aliases have gone [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime.rs` | C,R,H | -| [d765e50ada90](https://github.com/aurora-silicon/linux/commit/d765e50ada90e7f00a4ad608c9ff027d0a07a82a) | Ryan Murray | drm/asahi: drop tentative growth aliases before returning a fresh QID [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime.rs` | C,R,H | -| [780956abdb5f](https://github.com/aurora-silicon/linux/commit/780956abdb5fe59c76ca7343bc7f19770df658dd) | Ryan Murray | drm/asahi: compose shared capacity admission with accepted recovery port [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — MEM; `drivers/gpu/drm/asahi/g17/buffer.rs` | M,D | -| [b52bd36805e0](https://github.com/aurora-silicon/linux/commit/b52bd36805e0c35bac5c8255aae8cfad7cce5dd7) | Ryan Murray | drm/asahi: give native ray-query jobs a bounded execution allowance [#377](https://github.com/aurora-silicon/linux/pull/377) | Gated — RT; `drivers/gpu/drm/asahi/g17/job.rs` | F | -| [a5bc25b2ce19](https://github.com/aurora-silicon/linux/commit/a5bc25b2ce1997452676894fc8c9b401c7396e6c) | Ryan Murray | drm/asahi: cover render helpers and AS builds with bounded execution [#377](https://github.com/aurora-silicon/linux/pull/377) | Gated — RT; `drivers/gpu/drm/asahi/g17/command.rs` | F | -| [9827b6bb277a](https://github.com/aurora-silicon/linux/commit/9827b6bb277af5912490229f6fe56d3c575dafe3) | Ryan Murray | drm/asahi: bound repeated timeout recovery and G17 mailbox stalls [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — MBOX; `drivers/gpu/drm/asahi/g17/dependency.rs` | B,O | -| [c314dbb5bd42](https://github.com/aurora-silicon/linux/commit/c314dbb5bd4284697bd065db87eb038021b18125) | Ryan Murray | drm/asahi: expire background pool-release and render-replay polls [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [6c2d17ff4079](https://github.com/aurora-silicon/linux/commit/6c2d17ff40796899d7190580cabaeea749c73d0a) | Ryan Murray | drm/sched: initialise free_guilty in drm_sched_init() [#381](https://github.com/aurora-silicon/linux/pull/381) | Active — DRM; `drivers/gpu/drm/scheduler/sched_main.c` | C,H,M,F | -| [0d1871c3cfde](https://github.com/aurora-silicon/linux/commit/0d1871c3cfde9cc45b8bc244dde4775dbf4e05c6) | Ryan Murray | rust: drm: sched: zero the scheduler before drm_sched_init() [#381](https://github.com/aurora-silicon/linux/pull/381) | Active — DRM; `rust/kernel/drm/sched.rs` | C,H,M,F | -| [24399672582c](https://github.com/aurora-silicon/linux/commit/24399672582c155df35cadf8cb81a3397958f9e2) | Ryan Murray | drm/asahi: retry G17 retained compute publication pressure [#382](https://github.com/aurora-silicon/linux/pull/382) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [5ae95851753d](https://github.com/aurora-silicon/linux/commit/5ae95851753d377e13b7e3ac9012452a7fdaccc9) | Jonathan Goyvaerts | pmdomain: apple: pmc: Add the T6040 voter interface [#385](https://github.com/aurora-silicon/linux/pull/385) | Active — PMC; `drivers/pmdomain/apple/pmc-test.c` | P,C,R | -| [7bbd2ad37554](https://github.com/aurora-silicon/linux/commit/7bbd2ad375543683c070aca6487fae75a79fc747) | Jonathan Goyvaerts | soc: apple: clpc: Add the T6040 demand table [#385](https://github.com/aurora-silicon/linux/pull/385) | Active — CLPC; `drivers/soc/apple/clpc.c` | P,C,R,I | -| [b3765bd38ecb](https://github.com/aurora-silicon/linux/commit/b3765bd38ecbfaa5368b760c9d908964abf8c7a5) | Jonathan Goyvaerts | soc: apple: mcc: Allow up to 16 cache planes [#385](https://github.com/aurora-silicon/linux/pull/385) | Active — MCC; `drivers/soc/apple/Kconfig` | M,P | -| [f236c33daca6](https://github.com/aurora-silicon/linux/commit/f236c33daca696a326bd652799bd189ac2b6421f) | Jonathan Goyvaerts | soc: apple: clpc: Request a state only after sustained load [#385](https://github.com/aurora-silicon/linux/pull/385) | Active — CLPC; `drivers/soc/apple/clpc.c` | P,C,R,I | -| [32960bbd0e9c](https://github.com/aurora-silicon/linux/commit/32960bbd0e9cf24931f18d25131eef24f74f3d31) | Jonathan Goyvaerts | iommu/apple-dart: Mirror the firmware's display mappings on T6040 [#386](https://github.com/aurora-silicon/linux/pull/386) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [833c6ed10ffc](https://github.com/aurora-silicon/linux/commit/833c6ed10ffc2ac2d38b7bbb0d85dcc2b8e171df) | DjDeveloperr | drm/asahi: reduce minimum G17 target record backing [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — MEM; `drivers/gpu/drm/asahi/hw/t8140.rs` | M,D | -| [145361fdc90e](https://github.com/aurora-silicon/linux/commit/145361fdc90e82f4bddf6234ec46d0e023f41f86) | DjDeveloperr | drm/asahi: order G17 queue owner changes after scheduler releases [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,R,H | -| [1d478ee6c06b](https://github.com/aurora-silicon/linux/commit/1d478ee6c06b56b48782d08b693d9aa9e5c43435) | DjDeveloperr | drm/asahi: keep G17 render kick ring storage for the life of the device [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — SHARED; `drivers/gpu/drm/asahi/g17/kick.rs` | R,H | -| [7304ddbf6d4d](https://github.com/aurora-silicon/linux/commit/7304ddbf6d4d47b7976efcd20623524c9c53b0b1) | DjDeveloperr | drm/asahi: keep G17 render capacity waits from stopping the runtime [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — SHARED; `drivers/gpu/drm/asahi/g17/freelist.rs` | R,H | -| [72d57c0b9ac9](https://github.com/aurora-silicon/linux/commit/72d57c0b9ac9b8d5fcd58c59eebfa7f9c605399c) | DjDeveloperr | drm/asahi: wait for G17 contexts of closing queues at queue creation [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — REC; `drivers/gpu/drm/asahi/g17/capacity.rs` | F,Q | -| [a4351b50cd8d](https://github.com/aurora-silicon/linux/commit/a4351b50cd8d6f194bb71252acf9c9e2cf636db4) | DjDeveloperr | drm/asahi: keep G17 publication waits out of the submit ioctl [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — SHARED; `drivers/gpu/drm/asahi/g17/completion.rs` | C,R,H | -| [c556dacd085b](https://github.com/aurora-silicon/linux/commit/c556dacd085b148da86b47792dc34d14f02ace86) | DjDeveloperr | drm/asahi: rerun the G17 event pass for completions missed while a pair is borrowed [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/render.rs` | C,R,H | -| [8744e9417249](https://github.com/aurora-silicon/linux/commit/8744e9417249175511480765dbcc99f0a09c0fb9) | DjDeveloperr | drm/asahi: reuse G17 compute timestamp pages within a context [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — TIMESTAMP; `drivers/gpu/drm/asahi/g17/completion.rs` | T,C | -| [6f7faeecea0e](https://github.com/aurora-silicon/linux/commit/6f7faeecea0eccc8ee317ba163867df339d54fa5) | Jonathan Goyvaerts | drm/asahi: g17: do not advertise soft faults [#391](https://github.com/aurora-silicon/linux/pull/391) | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | C,R,H | -| [b0912f542fd0](https://github.com/aurora-silicon/linux/commit/b0912f542fd0655f10631977a8c63abc51a85ada) | Jonathan Goyvaerts | drm/asahi: g17: reread a torn borrowed render snapshot [#391](https://github.com/aurora-silicon/linux/pull/391) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render/retirement.rs` | R,H | -| [30ea4b130473](https://github.com/aurora-silicon/linux/commit/30ea4b13047377972cb75b78a4cbe5885cf46d1d) | Jonathan Goyvaerts | drm/asahi: g17: do not fail a blamed render that attribution cleared [#391](https://github.com/aurora-silicon/linux/pull/391) | Gated — KEY; `drivers/gpu/drm/asahi/g17/recovery.rs` | F | -| [e3d8d1b2fc1f](https://github.com/aurora-silicon/linux/commit/e3d8d1b2fc1feada69ec028203f727f642a150ac) | Jonathan Goyvaerts | drm/asahi: g17: skip already-signalled successful input fences [#391](https://github.com/aurora-silicon/linux/pull/391) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | C,R,H | -| [2321a1bc6ea6](https://github.com/aurora-silicon/linux/commit/2321a1bc6ea6c8a62a275685c0542a293c9b5438) | Jonathan Goyvaerts | drm/asahi: allow HIGH queue priority with CAP_SYS_NICE or DRM master [#391](https://github.com/aurora-silicon/linux/pull/391) | Active — DRM; `drivers/gpu/drm/asahi/g17/mod.rs` | B,M | -| [77a2bbe1a951](https://github.com/aurora-silicon/linux/commit/77a2bbe1a9512960e8c9ba17b466b2c9ab51fb5f) | Ryan Murray | soc: apple: rtkit: Keep warning about unknown oslog messages | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [b2adcfc94046](https://github.com/aurora-silicon/linux/commit/b2adcfc94046a10a989c6fd61fdb1bf7131ef78a) | Ryan Murray | drm/asahi: fail large G17 backing population without direct reclaim [#397](https://github.com/aurora-silicon/linux/pull/397) | Active — DRM; `drivers/gpu/drm/asahi/file.rs` | C,H,M,F | -| [632e4676500b](https://github.com/aurora-silicon/linux/commit/632e4676500bab6fd88817b1cf767afb1bf5da52) | Ryan Murray | drm/asahi: expose memory admission capacities in GET_PARAMS [#397](https://github.com/aurora-silicon/linux/pull/397) | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M,D | -| [ffe8011a479c](https://github.com/aurora-silicon/linux/commit/ffe8011a479ccd74dde747225c9baf67e2a02ba6) | Chris Kearney | drm/asahi: g15: reject errored input dependencies before publication [#395](https://github.com/aurora-silicon/linux/pull/395) | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | C,R,H | -| [faef7fd12e22](https://github.com/aurora-silicon/linux/commit/faef7fd12e22a4d56873b91981d412fd981cfd21) | Chris Kearney | drm/asahi: expose the inherited-error policy only for native G15 [#395](https://github.com/aurora-silicon/linux/pull/395) | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | C,R,H | -| [8736001f2b13](https://github.com/aurora-silicon/linux/commit/8736001f2b130a9e477fdef7d1db45f31591bfec) | Eryk Wieliczko | pmdomain: apple: pmgr-pwrstate: Honour apple,no-auto-pm [#395](https://github.com/aurora-silicon/linux/pull/395) | Active — PMGR; `drivers/pmdomain/apple/pmgr-pwrstate.c` | B,F | -| [2aff1b95c550](https://github.com/aurora-silicon/linux/commit/2aff1b95c55039846beb6451c737154254aa3ae0) | Eryk Wieliczko | soc: apple: rtkit: describe and adopt retained system buffers | Active — RTKIT; `drivers/soc/apple/rtkit-internal.h` | B,F | -| [71500694f45b](https://github.com/aurora-silicon/linux/commit/71500694f45b1fd27b05c9ed030b2cc803fb0f2f) | Eryk Wieliczko | drm/asahi: share tracked VM lifetime and native query support [#400](https://github.com/aurora-silicon/linux/pull/400) | Active — MEM; `drivers/gpu/drm/asahi/g17/completion.rs` | M,D | -| [444c52644826](https://github.com/aurora-silicon/linux/commit/444c52644826e99eecf65e9f643744c9e380bca9) | Ryan Murray | soc: apple: pmp: Keep power commands after an unhandled message on other boards | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [76c60f146885](https://github.com/aurora-silicon/linux/commit/76c60f1468853b4d28e3fed6e9c207c8a2f28410) | Ryan Murray | iommu/apple-dart: Map retained DARTs non-posted like every other DART [#400](https://github.com/aurora-silicon/linux/pull/400) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [d5df65ffcf66](https://github.com/aurora-silicon/linux/commit/d5df65ffcf66e54d9f23de05635512a2cf0ad41d) | Jonathan Goyvaerts | soc: apple: rtkit: add apple_rtkit_resume_idle() | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [f82267ce1172](https://github.com/aurora-silicon/linux/commit/f82267ce117278fb915879abbbd0f355286cecf3) | Jonathan Goyvaerts | soc: apple: rtkit: resume the AP power state before the IOP's | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [e772e7f87659](https://github.com/aurora-silicon/linux/commit/e772e7f87659243ab7b94c2b5bb77ab485dc1128) | DjDeveloperr | iommu/apple-dart: accept mirrored pages in handed-off firmware slots [#404](https://github.com/aurora-silicon/linux/pull/404) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [ff5c39ae1782](https://github.com/aurora-silicon/linux/commit/ff5c39ae1782cd1d826eddf48e0b08b1b2af61eb) | DjDeveloperr | iommu/apple-dart: keep stream invalidates out of handed-off slots [#404](https://github.com/aurora-silicon/linux/pull/404) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [c2bace5bb285](https://github.com/aurora-silicon/linux/commit/c2bace5bb28512471318d71abd5073b2bc7e2af1) | Ryan Murray | soc: apple: pmp: start endpoint 7 on every T6041 PMP [#402](https://github.com/aurora-silicon/linux/pull/402) | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [2d8c0fe879e2](https://github.com/aurora-silicon/linux/commit/2d8c0fe879e26583b62655534a3aba86b1dfc80f) | Jonathan Goyvaerts | drm/asahi: mmu: make the secondary root of PublishedRoots optional [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — MEM; `drivers/gpu/drm/asahi/g17/mod.rs` | M,D | -| [40507bad232c](https://github.com/aurora-silicon/linux/commit/40507bad232c7539f3c7c2540bac818a7aa90f26) | Jonathan Goyvaerts | drm/asahi: g17: support a single firmware coprocessor [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — SHARED; `drivers/gpu/drm/asahi/g17/event.rs` | C,R,H | -| [750dd1a8e590](https://github.com/aurora-silicon/linux/commit/750dd1a8e5902e4e7478ce9213278b2131b63266) | Jonathan Goyvaerts | drm/asahi: g17: describe the firmware build in a variant table [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data; MCache gated by V25G83.mcache=false — FW; `drivers/gpu/drm/asahi/g17/command.rs` | B,C,R | -| [9038ef8d328c](https://github.com/aurora-silicon/linux/commit/9038ef8d328cef14e038513ccaf55dc03869006b) | Jonathan Goyvaerts | drm/asahi: g17: take the per-SoC tables from Config [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/initdata.rs` | B,C,R | -| [24d1e5f4d8d3](https://github.com/aurora-silicon/linux/commit/24d1e5f4d8d31dd320048546cd53230a61203a9f) | Jonathan Goyvaerts | drm/asahi: g17: operating points with one voltage per cluster [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fw/initdata.rs` | C,R,H | -| [1ef423a08b3c](https://github.com/aurora-silicon/linux/commit/1ef423a08b3cbc81856afbe3c5854ac25b0893b6) | Jonathan Goyvaerts | drm/asahi: g17: register windows with several instances [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fw/initdata.rs` | C,R,H | -| [f23df96e697b](https://github.com/aurora-silicon/linux/commit/f23df96e697bc05a47029efd4fe786f900b08a83) | Jonathan Goyvaerts | drm/asahi: g17: let the variant choose the init acknowledgement [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/variant.rs` | B,C,R | -| [39e990b44482](https://github.com/aurora-silicon/linux/commit/39e990b44482f46fb6bed6c3b7eb2413e0f0331a) | Jonathan Goyvaerts | drm/asahi: mmu: firmware tables in no-map reserved memory [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — MEM; `drivers/gpu/drm/asahi/g17/mod.rs` | M,D | -| [54eccc50cc77](https://github.com/aurora-silicon/linux/commit/54eccc50cc770bdbe9306be4337c548f399e2eb8) | Jonathan Goyvaerts | drm/asahi: mmu: per-SoC UAT cache, TLB and handoff policy [#420](https://github.com/aurora-silicon/linux/pull/420) | Gated — UAT; `drivers/gpu/drm/asahi/mem.rs` | D | -| [abb36e8aa320](https://github.com/aurora-silicon/linux/commit/abb36e8aa3203f4cb28c1b2498d636617d01111d) | Jonathan Goyvaerts | drm/asahi: g17: 25G83 initialization layout [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/initdata.rs` | B,C,R | -| [0d9efa515188](https://github.com/aurora-silicon/linux/commit/0d9efa515188d93cd775e240b20bf4ad29a258c8) | Jonathan Goyvaerts | drm/asahi: g17: render lead commands for the 25G83 firmware [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/buffer.rs` | B,C,R | -| [f8dc19862078](https://github.com/aurora-silicon/linux/commit/f8dc19862078a7ad72cd3e10fe22052a02609e76) | Jonathan Goyvaerts | drm/asahi: g17: 25G83 render and compute commands [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/buffer/target.rs` | B,C,R | -| [20e51646e036](https://github.com/aurora-silicon/linux/commit/20e51646e036432fa9498a24e5330b8d02068612) | Jonathan Goyvaerts | drm/asahi: g17: add the T6040 (M4 Pro) [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/variant.rs` | B,C,R | -| [244f347d7dee](https://github.com/aurora-silicon/linux/commit/244f347d7deedb8a67eda1f0175ce001a5e7509c) | Jonathan Goyvaerts | soc: apple: rtkit: drop apple_rtkit_resume_idle() | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [a214e242a034](https://github.com/aurora-silicon/linux/commit/a214e242a03404fc7324ff0efdc595a6b37a53c5) | Jonathan Goyvaerts | drm/asahi: g17: bounded cross-VM grace for render timeouts [#413](https://github.com/aurora-silicon/linux/pull/413) | Active — REC; `drivers/gpu/drm/asahi/g17/job.rs` | F,Q | -| [24349f4a4593](https://github.com/aurora-silicon/linux/commit/24349f4a4593fa4e02ce731f5e73a228aa27aed8) | Jonathan Goyvaerts | drm/asahi: g17: retire abandoned spared renders without failing clients [#413](https://github.com/aurora-silicon/linux/pull/413) | Active — REC; `drivers/gpu/drm/asahi/g17/completion.rs` | F,Q | -| [9af21ada7212](https://github.com/aurora-silicon/linux/commit/9af21ada7212737042705f3081d153332516a182) | Jonathan Goyvaerts | drm/asahi: g17: spare innocent renders once the cross-VM grace runs out [#413](https://github.com/aurora-silicon/linux/pull/413) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/backend.rs` | R,H | -| [29f38d83f6a6](https://github.com/aurora-silicon/linux/commit/29f38d83f6a6208d4ff3c4187042b3b0b476d242) | Jonathan Goyvaerts | drm/asahi: g17: keep a VM usable behind its spared render quarantine [#413](https://github.com/aurora-silicon/linux/pull/413) | Active — REC; `drivers/gpu/drm/asahi/g17/completion.rs` | F,Q | -| [c71f1177e773](https://github.com/aurora-silicon/linux/commit/c71f1177e7730db49e9a7ec9cdf150a0feeb05ab) | Jonathan Goyvaerts | drm/asahi: g17: hold the GPU powered for idle_off_delay_ms after work [#413](https://github.com/aurora-silicon/linux/pull/413) | Active — POWER; `drivers/gpu/drm/asahi/g17/mod.rs` | I,C,R,P | -| [645b4e55cf16](https://github.com/aurora-silicon/linux/commit/645b4e55cf16c1cedffba87258bdaafd5b15dcd8) | Jonathan Goyvaerts | drm/asahi: g17: replay every render group firmware dropped unexecuted [#413](https://github.com/aurora-silicon/linux/pull/413) | Active — REC; `drivers/gpu/drm/asahi/g17/completion.rs` | F,Q | -| [94e719a0cec2](https://github.com/aurora-silicon/linux/commit/94e719a0cec2a65502ce5413d2ee9a105c1cc8d9) | Ryan Murray | drm/asahi: g17: never replay a render group a recovery blamed [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — REC; `drivers/gpu/drm/asahi/g17/completion.rs` | F,Q | -| [1054f6763014](https://github.com/aurora-silicon/linux/commit/1054f6763014fe4b4032a08ae7ccce721be4d385) | Ryan Murray | drm/asahi: g17: fix the render timeout head and replay documentation [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/render.rs` | F,Q | -| [45ac35fa2796](https://github.com/aurora-silicon/linux/commit/45ac35fa279642f98ea7326144716755fb3a39a2) | Ryan Murray | drm/asahi: g17: move the fw-data crash log mapping to its own file [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — SHARED; `drivers/gpu/drm/asahi/g17/data_segment.rs` | C,R,H | -| [fd21bf6faed6](https://github.com/aurora-silicon/linux/commit/fd21bf6faed6f978223e61444424ee918c199838) | Ryan Murray | drm/asahi: g17: take the core-layout buffers from Config [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/compute.rs` | B,C,R | -| [c0b9fbfa9fb0](https://github.com/aurora-silicon/linux/commit/c0b9fbfa9fb048d5bc67ffb9e17168b686b1962d) | Ryan Murray | drm/asahi: g17: check the voltage cells of the GPU operating points [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/initdata.rs` | B,C,R | -| [1c5a2ef5783a](https://github.com/aurora-silicon/linux/commit/1c5a2ef5783a565e6b27da871d30e4e637e1ce69) | Ryan Murray | drm/asahi: g17: accept only the two host words of a pointer block [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/queue.rs` | B,C,R | -| [df6b70b85cbf](https://github.com/aurora-silicon/linux/commit/df6b70b85cbfada36604f511b9ba8da21b13eb7d) | Ryan Murray | drm/asahi: g17: pass the fragment ID to the barrier unchanged [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fw/queue.rs` | C,R,H | -| [496a59f89601](https://github.com/aurora-silicon/linux/commit/496a59f8960191dc511b92328b13ccc7e31ad1ff) | Ryan Murray | drm/asahi: g17: do not spare a timeout behind work that already failed [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [fc1a16b4722c](https://github.com/aurora-silicon/linux/commit/fc1a16b4722ce9a9eb6b77fc0af4163873cacc9e) | Ryan Murray | drm/asahi: g17: name the blocking work in the watchdog lines [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — OBS; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | O,F | -| [894ec76dc892](https://github.com/aurora-silicon/linux/commit/894ec76dc89219caae27f9d6845521337b16e8bf) | Ryan Murray | drm/asahi: g17: treat a torn render sample in the timeout fallback as no proof [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/render.rs` | F,Q | -| [7d167e382f40](https://github.com/aurora-silicon/linux/commit/7d167e382f40542b25ffceb596d0982ee002b7ca) | Ryan Murray | drm/asahi: g17: fail the dropped successors of an exhausted render replay [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/render.rs` | F,Q | -| [5ee97891f61f](https://github.com/aurora-silicon/linux/commit/5ee97891f61f552c8c1d677db50725c413fb3ed7) | Ryan Murray | drm/asahi: g17: retire finished renders before attributing a render timeout [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — REC; `drivers/gpu/drm/asahi/g17/runtime/backend.rs` | F,Q | -| [25f4c6c3ab18](https://github.com/aurora-silicon/linux/commit/25f4c6c3ab18f329ba2af41b102c30d53e361ae6) | Ryan Murray | thermal: apple: Describe the PMP policy KUnit test module [#417](https://github.com/aurora-silicon/linux/pull/417) | Active — PMP; `drivers/thermal/apple-pmp-policy-test.c` | P,B | -| [b9a8f3938f3d](https://github.com/aurora-silicon/linux/commit/b9a8f3938f3daf5926b7c86204113f6730aec136) | Ryan Murray | drm/asahi: g17: pass the queue count to Pool::new() in the fault admission test [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — GMEM; `drivers/gpu/drm/asahi/g17/queue/admission.rs` | M,C,R | -| [bec833e0bc58](https://github.com/aurora-silicon/linux/commit/bec833e0bc581f74744265f0613832e8291db0cc) | Jonathan Goyvaerts | drm/asahi: pgtable: check the struct page of a table outside the reserved regions [#427](https://github.com/aurora-silicon/linux/pull/427) | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [a335c77de52a](https://github.com/aurora-silicon/linux/commit/a335c77de52a274029bb4e42f96d6afde5712a2f) | Jonathan Goyvaerts | drm/asahi: identify the T6040 GPU firmware by its loaded text [#428](https://github.com/aurora-silicon/linux/pull/428) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/variant.rs` | B,C,R | -| [d69f14f4e4fb](https://github.com/aurora-silicon/linux/commit/d69f14f4e4fbe9af21b70ee5c1b3ff9125c7a9cf) | DjDeveloperr | soc: apple: clpc: raise the T8140 fabric floor for GPU work [#440](https://github.com/aurora-silicon/linux/pull/440) | Active after port; 0d63308820ab — GPUFLOOR; `drivers/soc/apple/clpc.c` | P,C,R,H,I | -| [d1468a5f9a50](https://github.com/aurora-silicon/linux/commit/d1468a5f9a50a23cf741f56d83e6690441b90482) | Ryan | drm/asahi: gpu: drop the unused module_parameters import [#395](https://github.com/aurora-silicon/linux/pull/395) | Active — MEM; `drivers/gpu/drm/asahi/gpu.rs` | M,D | -| [26f5eb68dbce](https://github.com/aurora-silicon/linux/commit/26f5eb68dbce039de470b789d754d2ec3541c15e) | Ryan Murray | drm/asahi: admit the alternate T6040 loaded 25G83 image [#453](https://github.com/aurora-silicon/linux/pull/453) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/variant.rs` | B,C,R | -| [88aebfe0c656](https://github.com/aurora-silicon/linux/commit/88aebfe0c656676c530faa8f85df8d7b69a7ddb0) | DjDeveloperr | irqchip/apple-aic: Report the effective affinity of AICv2+ IRQs [#447](https://github.com/aurora-silicon/linux/pull/447) | Active — AIC; `drivers/irqchip/irq-apple-aic.c` | O,C,I | -| [eb346c1a25d8](https://github.com/aurora-silicon/linux/commit/eb346c1a25d813a1411a34fafc7d4bdee418e0d4), [42a176b951d9](https://github.com/aurora-silicon/linux/commit/42a176b951d90e746e33d27d6eb06a1773579afe) | Haoxiang Li | cpufreq: apple-soc: Fix OPP table cleanup | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [ae37f03d4163](https://github.com/aurora-silicon/linux/commit/ae37f03d4163df8143b2144e742916b91bf90654) | Ryan Murray | thermal: apple-smc-cpu: Add the J700 CPU thermal policy [#22](https://github.com/aurora-silicon/linux/pull/22) | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [583b9fa52fbf](https://github.com/aurora-silicon/linux/commit/583b9fa52fbf6a47f150736ad4a1aaa0d616ac02), [a8872354b695](https://github.com/aurora-silicon/linux/commit/a8872354b695a066ac6411791a691f26fcde55bf) | Oliver Lukschander | pmdomain: apple: pmp-report: initialize the report lock [#56](https://github.com/aurora-silicon/linux/pull/56) | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [8ca5289bec3a](https://github.com/aurora-silicon/linux/commit/8ca5289bec3a2b6f3629c9df516b357778273a72) | Joshua Warren | drm/asahi: connect the snapshot pointer to the C sysfs static [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Active; carried/refined form — MEM; `drivers/gpu/drm/asahi/gpu.rs` | M,D | -| [628bf1df4312](https://github.com/aurora-silicon/linux/commit/628bf1df43123ead994b028fd7b82a209e67aa30), [983575d7b492](https://github.com/aurora-silicon/linux/commit/983575d7b492f6824401cd21fe02278812211e27) | Ryan Murray | drm/asahi: initialize driver data before claiming destructor ownership [#171](https://github.com/aurora-silicon/linux/pull/171) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Active; carried/refined form — MEM; `drivers/gpu/drm/asahi/driver.rs` | M,B | -| [b10d60ce3916](https://github.com/aurora-silicon/linux/commit/b10d60ce3916c44dfb19b1f1b197bdca40bbac34) | Ryan Murray | drm/asahi: retain two-phase data ownership with stats registration [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Active; carried/refined form — MEM; `drivers/gpu/drm/asahi/driver.rs` | M,B | -| [9266541b8d35](https://github.com/aurora-silicon/linux/commit/9266541b8d35c1cd7146eec9a9b31b39fb7f29cc) | Ryan Murray | treewide: describe hardware behaviour in comments [#233](https://github.com/aurora-silicon/linux/pull/233) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Active; carried/refined form — MBOX; `drivers/gpu/drm/asahi/g17/buffer.rs` | B,O | -| [8533f072dc30](https://github.com/aurora-silicon/linux/commit/8533f072dc30e076206631f68f41fb4f8d7512a7) | Janne Grunau | iommu: apple-dart: Support specifying the DMA aperture in the DT | Active; carried/refined form — DART; `drivers/iommu/apple-dart.c` | D,B | -| [a9e24ae824ec](https://github.com/aurora-silicon/linux/commit/a9e24ae824ec205cf90f3545b0125631adf1326a) | Ryan Murray | merge: retain the 7.3 implementations where older ports duplicate them [#470](https://github.com/aurora-silicon/linux/pull/470) | Active; carried/refined form — PMGR; `drivers/bluetooth/hci_bcm4377.c` | B,F | -| [00248157ec1f](https://github.com/aurora-silicon/linux/commit/00248157ec1fc4e6369cd26cb8304bb56df7415d), [b2258cfadd69](https://github.com/aurora-silicon/linux/commit/b2258cfadd697cbe10c1e29b54f512c8f297bbe6) | Joshua Warren | soc: apple: mailbox: Make the send-empty IRQ optional (poll TX) | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [00e21c12c05a](https://github.com/aurora-silicon/linux/commit/00e21c12c05af1d540a2dc256a8cea3d17d63edc) | Lyude Paul | rust: drm: gem: Add export() callback | Active — DRM; `drivers/gpu/drm/nova/gem.rs` | C,H,M,F | -| [03329eff23bd](https://github.com/aurora-silicon/linux/commit/03329eff23bd3a72bdcfa09a3b98d0ac15107e6e), [35b057e57222](https://github.com/aurora-silicon/linux/commit/35b057e572224c39f79367df9e7c464f1822d15a), [e68c60f81285](https://github.com/aurora-silicon/linux/commit/e68c60f81285248fb50578f268343b06a6452a67) | DjDeveloperr | rust: drm: gpuvm: add non-blocking private mapping traversal [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `rust/kernel/drm/gpuvm.rs` | C,H,M,F | -| [033943b2b6ed](https://github.com/aurora-silicon/linux/commit/033943b2b6edb176aaebffa917e2273c3bf8f625) | Ryan Murray | drm: apple: parser: cap the number of timing modes [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/parser.c` | B | -| [08e4dd7596c9](https://github.com/aurora-silicon/linux/commit/08e4dd7596c91cdb5b761a0d272e40d75320306b), [29db1d8ab517](https://github.com/aurora-silicon/linux/commit/29db1d8ab517933c2e0114fb3c6bf9beda5417aa), [437f51c11728](https://github.com/aurora-silicon/linux/commit/437f51c11728f3183b0c17af6264547e44a60c26) | Ryan Murray | soc: apple: synchronize the ASCWrap mailbox provider with j700 [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [0db024825eb1](https://github.com/aurora-silicon/linux/commit/0db024825eb15d5ffd51ae6bb6b71ea4899ff3c2) | Ryan Murray | rust: drm: update shmem KUnit fixtures for the 7.2 file API | Active — DRM; `rust/kernel/drm/gem/shmem.rs` | C,H,M,F | -| [17f9a8193f55](https://github.com/aurora-silicon/linux/commit/17f9a8193f553f12afb69a14c849e12889842e8b) | Ryan Murray | rust: drm: gem: shmem: leave an imported object's SG table to the attachment | Active — DRM; `rust/kernel/drm/gem/shmem.rs` | C,H,M,F | -| [1f6c1fbb7057](https://github.com/aurora-silicon/linux/commit/1f6c1fbb7057db9206dce7187cfd3ec73233cd67) | Ryan Murray | drm/apple: dcp: Release the fixed display route with the device [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/dcp.c` | B | -| [29a2e2acec42](https://github.com/aurora-silicon/linux/commit/29a2e2acec42f8361d72bfd9506e3a0527afaf40) | DjDeveloperr | sched/core: add scoped utilization floors for kernel waiters [#171](https://github.com/aurora-silicon/linux/pull/171) | Active; carried/refined form — DRM | C,H,M,F | -| [29a913a5c222](https://github.com/aurora-silicon/linux/commit/29a913a5c222f2bec2ecae62a4dc4af223e5962d) | Jonathan Goyvaerts | soc: apple: mailbox: support the T6040 ASCWrap v6 [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [2b59aed7191c](https://github.com/aurora-silicon/linux/commit/2b59aed7191cccf0f6239e50e9a165f49b649529) | Ryan Murray | drm/asahi: avoid fence locks when pruning G17 frontiers [#201](https://github.com/aurora-silicon/linux/pull/201) | Active; carried/refined form — SHARED; `drivers/gpu/drm/asahi/g17/fence.rs` | C,R,H | -| [2dc22a191a5c](https://github.com/aurora-silicon/linux/commit/2dc22a191a5cf3109fb18dcfda0fec94bd4df18b), [a45a44cc6e2b](https://github.com/aurora-silicon/linux/commit/a45a44cc6e2b6bbdb189debda045a2174d07e039) | Ryan Murray | rust: drm: gem: shmem: let drivers allocate the objects the core creates | Active — DRM; `rust/kernel/drm/gem/mod.rs` | C,H,M,F | -| [32418c60d4cd](https://github.com/aurora-silicon/linux/commit/32418c60d4cdd6b37e2e9c7e88c7e299d473cf19) | Ryan Murray | drm/apple: dcp: Do not hold the mailbox of an unbound DCP for sleep [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/dcp.c` | B | -| [351fc1af825c](https://github.com/aurora-silicon/linux/commit/351fc1af825c49264de7e171a983d2c0c83f1601) | Ryan Murray | dt-bindings: power: apple,pmc: describe the DCS limit [#219](https://github.com/aurora-silicon/linux/pull/219) | Gated — DCS | P | -| [3b9a0383f589](https://github.com/aurora-silicon/linux/commit/3b9a0383f589ebaaa5bcd5c3242e294d6051f0e0) | Janne Grunau | FIXME: drm/gpuvm: Add DRM_GPUVA_REPEAT flag and logic | Active — DRM; `rust/kernel/drm/gpuvm/sm_ops.rs` | C,H,M,F | -| [3c102dba66df](https://github.com/aurora-silicon/linux/commit/3c102dba66df1119625c11c80dca301fb308563c) | Asahi Lina | rust: drm: mm: Add DRM MM Range Allocator abstraction | Active — DRM; `rust/kernel/drm/mm.rs` | C,H,M,F | -| [3d0c9c889919](https://github.com/aurora-silicon/linux/commit/3d0c9c8899198a8ad6d0d0241283ba04d2286fd7) | Ryan Murray | drm: apple: parser: bound the timing catalog allocation [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/parser.c` | B | -| [3d3fe96509d1](https://github.com/aurora-silicon/linux/commit/3d3fe96509d102770f72ce5f7829baa3c0f7d1ce), [df2e3cd3b778](https://github.com/aurora-silicon/linux/commit/df2e3cd3b77882ec523b42184d05596e60094072) | Ryan Murray | rust: soc: apple: mailbox: Fix receiver teardown and expose the device | Active — MBOX; `rust/kernel/soc/apple/mailbox.rs` | B,O | -| [3fd71b22d86c](https://github.com/aurora-silicon/linux/commit/3fd71b22d86c3e2397ed1da8a15123053d46a423), [536484539477](https://github.com/aurora-silicon/linux/commit/53648453947771b7ca24a61a585bffdbe1853242) | Ryan Murray | soc: apple: mailbox: Add T8140 ASC and AOP setup mailboxes | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [43fc98be783b](https://github.com/aurora-silicon/linux/commit/43fc98be783b0e9833242c1d8d111b49366b134b), [7c99d8debcc5](https://github.com/aurora-silicon/linux/commit/7c99d8debcc54ebf3f76ede14ced9b845db18215), [b0cc4eeb554a](https://github.com/aurora-silicon/linux/commit/b0cc4eeb554a74c2db220e35ceb14955142a79ed) | DjDeveloperr | drm/syncobj: apply expiring capacity hints during blocking waits [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `drivers/gpu/drm/drm_syncobj.c` | C,H,M,F | -| [4a577fcddddb](https://github.com/aurora-silicon/linux/commit/4a577fcddddbefec7d13bfd4ae3503893602d29b) | DjDeveloperr | rust: expose the DRM duplicate-reservation flag used by GPUVM [#171](https://github.com/aurora-silicon/linux/pull/171) | Active; carried/refined form — DRM | B,M | -| [4aa16bb5021e](https://github.com/aurora-silicon/linux/commit/4aa16bb5021e427507e15a9a48848d0484a4f3d6) | Eryk Wieliczko | rust: expose fence and DRM lifecycle helpers for native GPU backends | Active — DRM; `rust/kernel/dma_fence.rs` | C,H,M,F | -| [4f7a3272df96](https://github.com/aurora-silicon/linux/commit/4f7a3272df9627d98bc11a7da0c8189ca4aba196) | DjDeveloperr | drm/shmem-helper: populate revocable CPU mappings one page at a time [#171](https://github.com/aurora-silicon/linux/pull/171) | Active; carried/refined form — DRM; `drivers/gpu/drm/drm_gem_shmem_helper.c` | C,H,M,F | -| [5443fc6aeb7a](https://github.com/aurora-silicon/linux/commit/5443fc6aeb7a0fc574805b8b0b1513bbd02dcab4) | Ryan Murray | soc: apple: mailbox: only include reachable KUnit tests | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [5611637f6851](https://github.com/aurora-silicon/linux/commit/5611637f685115048c64231e7ac729f23ab20001), [5eff5323da02](https://github.com/aurora-silicon/linux/commit/5eff5323da0282c8fb9adfc57acdc9217e6d7995) | Ryan Murray | soc: apple: mailbox: drain only a present send-empty IRQ | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [56920e3e6752](https://github.com/aurora-silicon/linux/commit/56920e3e675230ced9a2ccab81bb7e9aa9c2ccf0) | Janne Grunau | rust: drm: gpuvm: Add sm_can_merge_flags | Active — DRM; `rust/kernel/drm/gpuvm/mod.rs` | C,H,M,F | -| [6154ed6d0f41](https://github.com/aurora-silicon/linux/commit/6154ed6d0f410dd69cbb3e218981b6dc549ac5df) | Janne Grunau | rust: drm: file: Use Registered device in DriverFile::open trait | Active — DRM; `drivers/gpu/drm/nova/file.rs` | C,H,M,F | -| [63d3b0f41939](https://github.com/aurora-silicon/linux/commit/63d3b0f419399d027c865d4ccffa12e3617a73b8) | Ryan Murray | drm: apple: afk: factor the receive bounds check into a helper [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/afk.c` | B | -| [6740c25f03c1](https://github.com/aurora-silicon/linux/commit/6740c25f03c1f552b0bdc0ad5b02926d96dd99ad) | Ryan Murray | drm/asahi: Log G17 firmware recovery causes before acknowledgement [#200](https://github.com/aurora-silicon/linux/pull/200) | Active; carried/refined form — OBS; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | O,F | -| [6803b9328c48](https://github.com/aurora-silicon/linux/commit/6803b9328c483c492e0a26fadf0a7cd03a5fe7cc) | Janne Grunau | rust: drm: gpuvm: GpuVa flags and REPEAT logic | Active — DRM; `rust/kernel/drm/gpuvm/sm_ops.rs` | C,H,M,F | -| [6a127c6ff62c](https://github.com/aurora-silicon/linux/commit/6a127c6ff62cde78267225a7094cda2771504c28) | Janne Grunau | rust: drm: file: Add as_raw() | Active — DRM; `drivers/gpu/drm/nova/file.rs` | C,H,M,F | -| [6db05cf4b231](https://github.com/aurora-silicon/linux/commit/6db05cf4b231f020020f31a479bd45ccff83520f) | DjDeveloperr | drm/shmem-helper: index fault pages by object offset [#171](https://github.com/aurora-silicon/linux/pull/171) | Active; carried/refined form — DRM; `drivers/gpu/drm/drm_gem_shmem_helper.c` | C,H,M,F | -| [70d9b6f64ee7](https://github.com/aurora-silicon/linux/commit/70d9b6f64ee76e9da96b752ee3933e2d0a66af0b) | Ryan Murray | drm: apple: free property dictionaries the connector does not keep [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/connector.c` | B | -| [72c42b6ddae6](https://github.com/aurora-silicon/linux/commit/72c42b6ddae68c8c58c5f5d720fda5079ae24302) | Janne Grunau | rust: drm: driver: Add feature flags used by asahi | Active — DRM; `rust/kernel/drm/device.rs` | C,H,M,F | -| [765577e012da](https://github.com/aurora-silicon/linux/commit/765577e012da1ee83e6eb56029bdbb9f1f799dce) | Ryan Murray | drm/apple: dptxep: Remove call counters and tidy tunnel comments [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/dptxep.c` | B | -| [77a9ab842a02](https://github.com/aurora-silicon/linux/commit/77a9ab842a02e980873a2298caa4dfe8d56faaff) | Ryan Murray | rust: drm: gpuvm: do not leak the VM when exec_lock() fails | Active — DRM; `rust/kernel/drm/gpuvm/mod.rs` | C,H,M,F | -| [7a155e383d2d](https://github.com/aurora-silicon/linux/commit/7a155e383d2d8e70fd76075ffb7427f4c7a3c326), [c98d2b872a2b](https://github.com/aurora-silicon/linux/commit/c98d2b872a2b02241ce4a34d9fe6841cd32b38c3) | Ryan Murray | soc: apple: mailbox: Keep the send-empty IRQ enable balanced | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [7c57598ac57c](https://github.com/aurora-silicon/linux/commit/7c57598ac57cb7804a9f2e89d0975e2005985b96) | Janne Grunau | rust: drm: gem: Support locking gpuva.lock | Active — DRM; `rust/kernel/drm/gem/mod.rs` | C,H,M,F | -| [7dce231ad73d](https://github.com/aurora-silicon/linux/commit/7dce231ad73d98e102b4b9e0b362cbab21750854) | DjDeveloperr | drm/syncobj: skip wait hint lookup for ineligible waits [#171](https://github.com/aurora-silicon/linux/pull/171) | Active; carried/refined form — DRM; `drivers/gpu/drm/drm_syncobj.c` | C,H,M,F | -| [7ed160b9b5f2](https://github.com/aurora-silicon/linux/commit/7ed160b9b5f28df712e98088d4368188b2e28072), [c7df21582810](https://github.com/aurora-silicon/linux/commit/c7df2158281045e6fa9bfa6b7c170910f1089d2e) | Ryan Murray | soc: apple: mailbox: Tidy T8140 comments and resume error logging [#314](https://github.com/aurora-silicon/linux/pull/314) | Active — OBS; `drivers/soc/apple/mailbox.c` | O,F | -| [887533ef3bd8](https://github.com/aurora-silicon/linux/commit/887533ef3bd88de5ec05f93be23d2fefd3570cb5) | Ryan Murray | rust: drm: gem: shmem: wait for backing release instead of failing a lease | Active — DRM; `rust/kernel/drm/gem/shmem.rs` | C,H,M,F | -| [8cdeb29b542a](https://github.com/aurora-silicon/linux/commit/8cdeb29b542af3cd5ffb3b535330ad4fd67b97a7) | Janne Grunau | HACK: rust: drm: gem: shmem: Make VMap.ptr pub | Active — DRM; `rust/kernel/drm/gem/shmem.rs` | C,H,M,F | -| [9142d428cb69](https://github.com/aurora-silicon/linux/commit/9142d428cb6956aeb36ffebabe42e1a5c2396c2c) | Ryan Murray | drm: apple: afk: bound received queue entries without 32-bit wrap [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/afk.c` | B | -| [92d02170df1e](https://github.com/aurora-silicon/linux/commit/92d02170df1ecf2273d13ba63c0cedbb891996d3) | Jonathan Goyvaerts | arm64: dts: apple: t6040: Add the GPU [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW | B,P | -| [9429b186dc3e](https://github.com/aurora-silicon/linux/commit/9429b186dc3edb6658bcdd02e451a5cb1c5f0844) | Ryan Murray | rust: drm: report client memory in fdinfo | Active — DRM; `rust/kernel/drm/device.rs` | C,H,M,F | -| [9523159a7288](https://github.com/aurora-silicon/linux/commit/9523159a72886c5169e7bfd566de9c0aa545ba85) | Ryan Murray | soc: apple: clpc: drop the syscon select and the GPU from Kconfig [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — CLPC; `drivers/soc/apple/Kconfig` | P,C,R,I | -| [a3828ea8a63d](https://github.com/aurora-silicon/linux/commit/a3828ea8a63d2488f2080dd1f4f6ce8ebd133623) | Asahi Lina | rust: drm: syncobj: Add DRM Sync Object abstraction | Active — DRM; `rust/kernel/drm/mod.rs` | B,M | -| [a6f8817ebbf6](https://github.com/aurora-silicon/linux/commit/a6f8817ebbf6c420aee66897f717ab4e94a4a717) | Ryan Murray | drm/asahi: Reuse fully retired guilty G17 compute queues [#200](https://github.com/aurora-silicon/linux/pull/200) | Active; carried/refined form — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [b147e1f460b5](https://github.com/aurora-silicon/linux/commit/b147e1f460b56e398bc085b2457b1ba163cf4505) | Jonathan Goyvaerts | arm64: dts: apple: t6040-j616s: Add the gpu alias [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW | B,P | -| [b1f7d09dcf33](https://github.com/aurora-silicon/linux/commit/b1f7d09dcf33e3bb06e81d846783b698d604be5b) | Ryan Murray | drm/apple: dcp: Initialise the start completion before checking RTKit [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/dcp.c` | B | -| [b965be95b07f](https://github.com/aurora-silicon/linux/commit/b965be95b07f46ef0be02f47a3a02017d912e4cc) | Asahi Lina | rust: drm: gpuvm: Add part of the asahi downstream gpuvm abstractions | Active — DRM; `rust/kernel/drm/gpuvm/mod.rs` | B,M | -| [ba69d4dde975](https://github.com/aurora-silicon/linux/commit/ba69d4dde9751976c323055ef683d76febf82a2b) | Ryan Murray | drm: apple: afk: validate the receive write pointer and bound a drain [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/afk.c` | B | -| [c0e5730f8058](https://github.com/aurora-silicon/linux/commit/c0e5730f8058f14c8fdeb5cd96213e57822f7bbb) | Ryan Murray | drm/apple: dcp: Tidy RTKit start-up logging [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/dcp.c` | B | -| [c4722f38cdcc](https://github.com/aurora-silicon/linux/commit/c4722f38cdccca6dbbbc446dfa2d715ab96e9554) | Ryan Murray | arm64: dts: apple: t6040: Do not claim the GPU's PMP report entry at boot [#402](https://github.com/aurora-silicon/linux/pull/402) | Active — PMP | P,B | -| [cd71c1e7ff90](https://github.com/aurora-silicon/linux/commit/cd71c1e7ff901c3c35492ebe5b8bebb0702e5480) | Jonathan Goyvaerts | arm64: dts: apple: t6040-j616s: describe the GPU firmware text segment [#428](https://github.com/aurora-silicon/linux/pull/428) | Active translated data — FW | B,P | -| [d50642d23a7e](https://github.com/aurora-silicon/linux/commit/d50642d23a7edb9ace6837d6471981e84d0d4ef6) | Ryan Murray | iommu: apple-dart: Fix the KUnit test after deferred root publication [#314](https://github.com/aurora-silicon/linux/pull/314) | Active; carried/refined form — DART; `drivers/iommu/apple-dart-test.c` | D,B | -| [d6799a78db13](https://github.com/aurora-silicon/linux/commit/d6799a78db13ad06a2f26b66aad97c7e7626714d) | Ryan Murray | drm/apple: dcp: Initialise work items at probe [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/dcp.c` | B | -| [d8b45282c1e7](https://github.com/aurora-silicon/linux/commit/d8b45282c1e70cb4b947d2aadfb2636fd4ee763a) | Lyude Paul | rust: drm: gem: Add BaseObject::prime_export() | Active — DRM; `rust/kernel/drm/gem/mod.rs` | C,H,M,F | -| [defdcb801774](https://github.com/aurora-silicon/linux/commit/defdcb8017744fe0aa57061ed304e793935b52bc) | Ryan Murray | soc: apple: build the CLPC floors by default [#219](https://github.com/aurora-silicon/linux/pull/219) | Active; carried/refined form — CLPC; `drivers/soc/apple/Kconfig` | P,C,R,I | -| [e1468f83c1da](https://github.com/aurora-silicon/linux/commit/e1468f83c1daf236b69c6868a3a05a9d6f994f9b) | Janne Grunau | rust: drm: gem: Add missing trailing '//' for kernel vertical style | Active — DRM; `rust/kernel/drm/gem/mod.rs` | C,H,M,F | -| [e6d369606edf](https://github.com/aurora-silicon/linux/commit/e6d369606edff3c24dc3b1f5dda036cc77a8887c) | Ryan Murray | drm/shmem: revoke CPU PFNs before releasing purge backing [#171](https://github.com/aurora-silicon/linux/pull/171) | Active; carried/refined form — DRM; `drivers/gpu/drm/drm_gem_shmem_helper.c` | C,H,M,F | -| [f0a8afc04957](https://github.com/aurora-silicon/linux/commit/f0a8afc0495743e502fc860fa2bc0fc96e95b22a) | Sami Tolvanen | rust: drm: add a registration guard for the Normal device context | Active — DRM; `rust/kernel/drm/device.rs` | C,H,M,F | -| [fd2a0321db11](https://github.com/aurora-silicon/linux/commit/fd2a0321db11572ac201663697c83c9330ef65a3) | DjDeveloperr | driver core: track devres node membership for direct removal [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — DRM; `drivers/base/base.h` | B,M | - -### N/A, superseded, other-backend and imported-neighbor records - -These scoped candidates are included to make exclusions reviewable. A shared -path query or an omnibus PR is not evidence of a Neo performance improvement. - -| Commits / encountered aliases | Author | Improvement / record | T6040 after ports — evidence key and changed source | Measurement | -| --- | --- | --- | --- | --- | -| [4f772d2c2d6c](https://github.com/aurora-silicon/linux/commit/4f772d2c2d6cb336d4df08ae6c554b8387510c20) | Janne Grunau | drm/asahi: initdata: Fold GlobalsSub struct into Globals | Not applicable — LEGACY; `drivers/gpu/drm/asahi/fw/initdata.rs` | V | -| [532ac90e08af](https://github.com/aurora-silicon/linux/commit/532ac90e08affc3bbcf59e273e00f1573b7a05d0) | Janne Grunau | drm/asahi: Avoid variable/field ref shadowing in pin-init | Not applicable — LEGACY; `drivers/gpu/drm/asahi/initdata.rs` | V | -| [253d85ab9854](https://github.com/aurora-silicon/linux/commit/253d85ab98543f838ecc6be70edb7a43d966d505) | Sasha Finkelstein | drm/asahi: starlight-debug | Not applicable — LEGACY; `drivers/gpu/drm/asahi/gpu.rs` | V | -| [83526ea43d4f](https://github.com/aurora-silicon/linux/commit/83526ea43d4fffdb10a3dff36a37a587ffaa6c14) | Janne Grunau | drm/asahi: workqueue: Drop completed work items | Not applicable — LEGACY; `drivers/gpu/drm/asahi/workqueue.rs` | V | -| [b1e32124e9e9](https://github.com/aurora-silicon/linux/commit/b1e32124e9e94ebd3e1345eb54f687fcfbfee509) | Janne Grunau | drm/asahi: rustfmt | Not applicable — VERIFY; `drivers/gpu/drm/asahi/mmu.rs` | V | -| [8508e5105997](https://github.com/aurora-silicon/linux/commit/8508e5105997a43be75e8a3ffe0c3d8ddc00155c), [e092d51bc9d7](https://github.com/aurora-silicon/linux/commit/e092d51bc9d773f7058fe578515c5f915c0adf2c) | Yureka Lilian | pmdomain: add pmp-report offsets for t6030,t8122 | Not applicable — G15; `drivers/pmdomain/apple/pmp-report.c` | V | -| [357978884c89](https://github.com/aurora-silicon/linux/commit/357978884c895e5fc35af84fed8adf0583bc3353), [a89f7da611ad](https://github.com/aurora-silicon/linux/commit/a89f7da611ade4b9d5f40dd45fe5b41d059e3399) | Yureka Lilian | arm64: dts: apple: add minimal MacBook Neo device tree | Not applicable — PERIPH | V | -| [dfe1431f40cf](https://github.com/aurora-silicon/linux/commit/dfe1431f40cf15ec4aebd1864b4c69707b3c43c2), [b796a047ec25](https://github.com/aurora-silicon/linux/commit/b796a047ec253074e2cd6b5f38a8f19949b50271), [9359ea48b718](https://github.com/aurora-silicon/linux/commit/9359ea48b7184cdee39b7c76b5f0d4a923807cf3) | Ryan Murray | arm64: dts: apple: Add T8140/J700 device trees with audio and camera | Not applicable — PERIPH | V | -| [0d31fa4418ec](https://github.com/aurora-silicon/linux/commit/0d31fa4418ec7c18ab984d6cfb0c4d10b80a0af1), [bffb1ed450d5](https://github.com/aurora-silicon/linux/commit/bffb1ed450d58d0c19f9e312c8b0c2314b9f1c53), [d575cca893bc](https://github.com/aurora-silicon/linux/commit/d575cca893bce9bedb5375be6bb8c209991faec6) | Ryan Murray | arm64: dts: apple: t8140: Add SPMI controller and PMIC NVMEM cells | Not applicable — PERIPH | V | -| [780ab337fd92](https://github.com/aurora-silicon/linux/commit/780ab337fd92e4511f4e4ee698820ae15d007cbc), [368b5343b9f7](https://github.com/aurora-silicon/linux/commit/368b5343b9f7c69683ee5a0c5239a6f96e8177fd), [c3874394cec6](https://github.com/aurora-silicon/linux/commit/c3874394cec613afc6b5c8615eae5cdd013e558c) | Ryan Murray | arm64: dts: apple: t8140: Add SMC node | Not applicable — PERIPH | V | -| [53296a0f9b6e](https://github.com/aurora-silicon/linux/commit/53296a0f9b6eae07ebce8a55c8b16309d87b2656), [985ee0213ef3](https://github.com/aurora-silicon/linux/commit/985ee0213ef3154c4d8c9763157f9620a7ce0243), [b8850ad18ff8](https://github.com/aurora-silicon/linux/commit/b8850ad18ff8d0a489c810fdafece6b8349f8694) | Ryan Murray | arm64: dts: apple: t8140: Add ANS2 NVMe controller | Not applicable — PERIPH | V | -| [4767bc0b221c](https://github.com/aurora-silicon/linux/commit/4767bc0b221cce5fb0c20dbacffe6f6bca7bc4a0), [5b9145de86c1](https://github.com/aurora-silicon/linux/commit/5b9145de86c13364ed3b9d465334674e7dc87083), [0b9461d4be5a](https://github.com/aurora-silicon/linux/commit/0b9461d4be5a77c0c74138900b8b92a7e193f8bb) | Ryan Murray | arm64: dts: apple: t8140-j700: Name the ALS calibration file | Not applicable — PERIPH | V | -| [2b45c6011879](https://github.com/aurora-silicon/linux/commit/2b45c601187962fca0b9289fdb1408e36ef5f838), [613b821cb4bb](https://github.com/aurora-silicon/linux/commit/613b821cb4bb48ccb999f75c4d5815f094f095be), [aefc56975b57](https://github.com/aurora-silicon/linux/commit/aefc56975b57d0e07a4a3e92d7e7af85f0a45cb4) | Ryan Murray | arm64: dts: apple: t8140-pmgr: Add ATC0 and nub SPMI A0 power domains | Not applicable — PERIPH | V | -| [e5992bd6f02c](https://github.com/aurora-silicon/linux/commit/e5992bd6f02c42e2e7404be54a41d8acaf685bb4), [dc6bc1f1613f](https://github.com/aurora-silicon/linux/commit/dc6bc1f1613f7e836b9514f40c07cb424622fca1), [0e335bcc4a79](https://github.com/aurora-silicon/linux/commit/0e335bcc4a799cc546ff5a6e9d5cdde644a53eea) | Ryan Murray | arm64: dts: apple: t8140: Add the MTP coprocessor and DockChannel HID nodes | Not applicable — PERIPH | V | -| [601fe7359e94](https://github.com/aurora-silicon/linux/commit/601fe7359e94f9f527487f2d1725cbfad8ea1ff2), [2d6ae0d0f507](https://github.com/aurora-silicon/linux/commit/2d6ae0d0f5073b6e29cb970926855de13d24a770), [895980a58c46](https://github.com/aurora-silicon/linux/commit/895980a58c46a6a1ec2a4e2bb2d5b9e815d4b349) | Ryan Murray | arm64: dts: apple: t8140: Add the USB-C controller, ATC PHY and SPMI A0 bus | Not applicable — PERIPH | V | -| [addbb17c2a81](https://github.com/aurora-silicon/linux/commit/addbb17c2a810bcaa1d68f6f9bc8e7fb401a508a), [7d1387799cba](https://github.com/aurora-silicon/linux/commit/7d1387799cba4442ba7ea99a95a962535cf26fc2), [7ded6b918bd3](https://github.com/aurora-silicon/linux/commit/7ded6b918bd3436fa2dc81b8b65f336bbe66ae85) | Ryan Murray | arm64: dts: apple: t8140-j700: Enable the keyboard and trackpad | Not applicable — PERIPH | V | -| [70f40a78d8ea](https://github.com/aurora-silicon/linux/commit/70f40a78d8ea8db8b300d3d084b4228b3e172f19), [c94e793fea2a](https://github.com/aurora-silicon/linux/commit/c94e793fea2ad398c3aade3d3649ebc377189ec2), [b8f170b9347b](https://github.com/aurora-silicon/linux/commit/b8f170b9347ba943a11a30f6642a9532758965e4) | Ryan Murray | arm64: dts: apple: t8140-j700: Enable the USB-C ports | Not applicable — PERIPH | V | -| [ea013658bf93](https://github.com/aurora-silicon/linux/commit/ea013658bf93d944617d01034cd7a5a3ece105a8), [e5a7b83611cc](https://github.com/aurora-silicon/linux/commit/e5a7b83611ccc434923524ea7bfb27f4e9c2a2ec), [09b788437876](https://github.com/aurora-silicon/linux/commit/09b788437876d50bf0d13d0d8cf7bfe9487a934b) | Ryan Murray | arm64: dts: apple: t8140-j700: Enable the USB DARTs | Not applicable — PERIPH | V | -| [a97766963d24](https://github.com/aurora-silicon/linux/commit/a97766963d247d039cd76be83fd896b895e1ad2b), [e499013c56ad](https://github.com/aurora-silicon/linux/commit/e499013c56ad475dd45866c64e28dd33f95235c3), [d880e057bc1e](https://github.com/aurora-silicon/linux/commit/d880e057bc1e250d54a0b7dc2db23928f802a1d0) | Ryan Murray | arm64: dts: apple: t8140: Add the SMC RTC | Not applicable — PERIPH | V | -| [50e24690d43e](https://github.com/aurora-silicon/linux/commit/50e24690d43e525c1b2b217aa828a18e4c6503b9), [21ab6edf3da3](https://github.com/aurora-silicon/linux/commit/21ab6edf3da3111ed771155a9dbd2c83118cd0dc), [e90d32748ea7](https://github.com/aurora-silicon/linux/commit/e90d32748ea7857d242afc714365949e9ad86a3b) | Ryan Murray | arm64: dts: apple: t8140-j700: Describe the remaining SMC temperatures | Not applicable — PERIPH | V | -| [2cb796ddf423](https://github.com/aurora-silicon/linux/commit/2cb796ddf423b6d76e9d2ab1231f0b48ddbc2614), [e8d16b77d690](https://github.com/aurora-silicon/linux/commit/e8d16b77d6901f18a468d3d1b636990aa97f89cd), [23b613dfe8e7](https://github.com/aurora-silicon/linux/commit/23b613dfe8e757e1b599dc7cdfb7f9717687dc21) | Ryan Murray | arm64: dts: apple: t8140-j700: Describe the SMC current, power and voltage rails | Not applicable — PERIPH | V | -| [0cd1a28f2113](https://github.com/aurora-silicon/linux/commit/0cd1a28f2113c72a53052fb2733c2aced2f54476), [c2845ec53a91](https://github.com/aurora-silicon/linux/commit/c2845ec53a915dcadc4e68bbd59f97ca0764ddd6) | DjDeveloperr | iommu: apple-dart: support tunneled PCIe-C DMA aliases | Not applicable — TUNNEL; `drivers/iommu/Kconfig` | V | -| [6ff009379755](https://github.com/aurora-silicon/linux/commit/6ff00937975526780a22aa763211ba612f042997), [ee60f6cdcff8](https://github.com/aurora-silicon/linux/commit/ee60f6cdcff8561bff5ec48b10ba2a536a23ed9f) | DjDeveloperr | iommu: apple-dart: support retained PCIe-C tunnel domains | Not applicable — TUNNEL; `drivers/iommu/apple-dart.c` | V | -| [05ae2b2dfc28](https://github.com/aurora-silicon/linux/commit/05ae2b2dfc2853d7ae0f797d6299661e957116f3), [5987e8a08203](https://github.com/aurora-silicon/linux/commit/5987e8a08203974fe539aed3ce2de8ad5a3990a7) | Ryan Murray | arm64: dts: apple: t8140: Describe observed behaviour, not other implementations | Not applicable — VERIFY | V | -| [61f979fc1825](https://github.com/aurora-silicon/linux/commit/61f979fc18256a03db72933dde7f356a44f31eb2), [bf3cb50f012f](https://github.com/aurora-silicon/linux/commit/bf3cb50f012f9ecaeb465e861d8e896e580a69a0), [4fa6c2b053a6](https://github.com/aurora-silicon/linux/commit/4fa6c2b053a65088ca20641480fd9ed8da55716e) | Ace | arm64: dts: apple: Add diagnostic J700 PCIe root-port topology | Not applicable — PERIPH | V | -| [c309c0ebb058](https://github.com/aurora-silicon/linux/commit/c309c0ebb058bf6cd1df2503d121ace539448ecc), [5a4974fde407](https://github.com/aurora-silicon/linux/commit/5a4974fde40748a151a4c23c0df730f1148bc2df) | Ace | arm64: dts: apple: t8140-j700: enable bounded PCIe endpoint bootstrap and enumeration | Not applicable — PERIPH | V | -| [56e442c7cbbe](https://github.com/aurora-silicon/linux/commit/56e442c7cbbe49c2613a5209fbcf772e90bec10e), [716b60de9620](https://github.com/aurora-silicon/linux/commit/716b60de96207e43d3c06eeb9c424f147a5d16a3), [8a03c5341e27](https://github.com/aurora-silicon/linux/commit/8a03c5341e27e9066e15f924e88aa44f848b5294) | DjDeveloperr | arm64: dts: apple: enable AVD on T8140 | Not applicable — PERIPH | V | -| [2b9ef0954320](https://github.com/aurora-silicon/linux/commit/2b9ef0954320320edbee5b75e742176aef3ee8b3), [6f57627a710e](https://github.com/aurora-silicon/linux/commit/6f57627a710e655f30ec73ece845d18c52663d78), [4088c3b1854c](https://github.com/aurora-silicon/linux/commit/4088c3b1854cdbaf106d8bfe72510551bf9fd43c) | Ryan Murray | arm64: dts: apple: t8140: add disabled display power domains | Not applicable — PERIPH | V | -| [7e14b8e9e9a2](https://github.com/aurora-silicon/linux/commit/7e14b8e9e9a2bcb983725fc9a0cb3c016a5ed12b), [1b05c65c4276](https://github.com/aurora-silicon/linux/commit/1b05c65c42763d955c7ca69ef849d6bf5fac7355), [004200ec1cc8](https://github.com/aurora-silicon/linux/commit/004200ec1cc8005fa692d797d2c5fb009ec9e05a) | Ryan Murray | arm64: dts: apple: t8140: add disabled internal display DARTs | Not applicable — PERIPH | V | -| [d7de8bb51e4f](https://github.com/aurora-silicon/linux/commit/d7de8bb51e4f654b1c1d33c8cabd3290a9e231ea), [0c29d4d4a4ea](https://github.com/aurora-silicon/linux/commit/0c29d4d4a4ea28e024596f605676dc0d1d1e3ba0), [d2f162f6d7c2](https://github.com/aurora-silicon/linux/commit/d2f162f6d7c24ed783657112086f7b56e1fb0cbe) | Ryan Murray | arm64: dts: apple: t8140: add disabled external display DARTs | Not applicable — PERIPH | V | -| [7a28ede30a1f](https://github.com/aurora-silicon/linux/commit/7a28ede30a1ff3894d8f2407ba657d51e8d9bd95), [042b2a224bf6](https://github.com/aurora-silicon/linux/commit/042b2a224bf671bacb56b6e5345b3eb399c7ec02), [aec8cb1999f7](https://github.com/aurora-silicon/linux/commit/aec8cb1999f731bbe1895509dbcc6e2fed977348) | Ryan Murray | arm64: dts: apple: t8140: Add the SEP, its DART and mailbox, and SPI2 | Not applicable — PERIPH | V | -| [07029412ae8d](https://github.com/aurora-silicon/linux/commit/07029412ae8d5832c1323d3eeb8a08b09f7b5be0), [1eb7bfe18b01](https://github.com/aurora-silicon/linux/commit/1eb7bfe18b01c0a088dd8e25a72ee5af3a09531a), [29987787b923](https://github.com/aurora-silicon/linux/commit/29987787b9238b15b41b92da87e5fcbf8a571e8c) | Ryan Murray | arm64: dts: apple: t8140-j700: Enable the SEP and the Touch ID sensor | Not applicable — PERIPH | V | -| [7d84216f74e8](https://github.com/aurora-silicon/linux/commit/7d84216f74e8e9e5827eabc9f173524ce5520c9b), [6049af950206](https://github.com/aurora-silicon/linux/commit/6049af950206644d95b8cd3ca11fe0722ff71257), [52f1ba512244](https://github.com/aurora-silicon/linux/commit/52f1ba51224431d256250c69784e1996f6ee63cc) | Acelogic | arm64: dts: apple: wire the J700 AVE encoder | Not applicable — PERIPH | V | -| [5f1fbb7bd670](https://github.com/aurora-silicon/linux/commit/5f1fbb7bd670ca8a26c303594f9ed54535e51f02), [519558a43644](https://github.com/aurora-silicon/linux/commit/519558a43644d79c2cc15135554748ffe6fadc81), [f898b116beaa](https://github.com/aurora-silicon/linux/commit/f898b116beaaab7add264a0f074b21743875d3ae) | Ryan Murray | arm64: dts: apple: Describe additional T8140 peripheral power states | Not applicable — PERIPH | V | -| [555932c62f03](https://github.com/aurora-silicon/linux/commit/555932c62f03ec2833c5db9b39e2d2dc956501cb), [ed2ef28706b7](https://github.com/aurora-silicon/linux/commit/ed2ef28706b7c2ed13aef2f90eb7191b4e34338e), [f75a1041fca4](https://github.com/aurora-silicon/linux/commit/f75a1041fca487774f29b133f736296f4d73a4e3) | Ryan Murray | arm64: dts: apple: Wire up remaining supported J700 peripherals | Not applicable — PERIPH | V | -| [a3d7465380ff](https://github.com/aurora-silicon/linux/commit/a3d7465380ffbf5f9cb4eddb550fabfdd71d3a17), [49fdcbcee4f4](https://github.com/aurora-silicon/linux/commit/49fdcbcee4f4569e6b65f7912e05502a38299743) | Ryan Murray | arm64: dts: apple: describe the J700 PMU alarm function | Not applicable — PERIPH | V | -| [d810cb82e82d](https://github.com/aurora-silicon/linux/commit/d810cb82e82de69013754b6031d00a83a6d15e41), [4e0543ee6caf](https://github.com/aurora-silicon/linux/commit/4e0543ee6cafb4250aaf332f894773412b86dfe2), [b9a339703e95](https://github.com/aurora-silicon/linux/commit/b9a339703e95a6a65e0e4515caa4c4f6afb0d9ce) | Ryan Murray | arm64: dts: apple: describe the disabled T8140 Neural Engine | Not applicable — PERIPH | V | -| [19f7cbdd84fe](https://github.com/aurora-silicon/linux/commit/19f7cbdd84fef12ca56aad9b654b46465cc2e198), [6b57d5423048](https://github.com/aurora-silicon/linux/commit/6b57d5423048ac4c70cd99d7473494ac3d37b2db), [93bc234385f5](https://github.com/aurora-silicon/linux/commit/93bc234385f5bf51b276e9d2e5abe8280e2ff92c) | Ryan Murray | arm64: dts: apple: t8140: Leave display coprocessor power to firmware | Not applicable — PERIPH | V | -| [0f5548d142b1](https://github.com/aurora-silicon/linux/commit/0f5548d142b1d73c44d270c91d5c359272dae499), [7c3c5ee5a070](https://github.com/aurora-silicon/linux/commit/7c3c5ee5a0702bb5b9f0ae4cde6b837cbafa3485), [9e6acbbd21ba](https://github.com/aurora-silicon/linux/commit/9e6acbbd21ba92409dd4f24074532b0bad997792) | Ryan Murray | arm64: dts: apple: t8140: Describe the internal display coprocessor | Not applicable — PERIPH | V | -| [100ff1ebedd3](https://github.com/aurora-silicon/linux/commit/100ff1ebedd337758a4ff3ba3fd3f2f46a9f5be9), [45ae8211efea](https://github.com/aurora-silicon/linux/commit/45ae8211efeafe3bff64b569370942c5218f1fec), [061370b4c70f](https://github.com/aurora-silicon/linux/commit/061370b4c70fd888ea6dc520a8988208f4aebca8) | Ryan Murray | arm64: dts: apple: t8140: Hand the J700 panel over to the DCP | Not applicable — PERIPH | V | -| [29f8091fe351](https://github.com/aurora-silicon/linux/commit/29f8091fe351a0cdb781cf18ac5748ca15feca42), [4f3906d225f4](https://github.com/aurora-silicon/linux/commit/4f3906d225f44739df672ac0b76715407f52e586), [a7fa3d8fbf56](https://github.com/aurora-silicon/linux/commit/a7fa3d8fbf5690df6553896a4f984b8cdc8069c2) | Ryan Murray | arm64: dts: apple: t8140: describe each power state once | Not applicable — PERIPH | V | -| [89c54797ae77](https://github.com/aurora-silicon/linux/commit/89c54797ae77fea8e8878a68e0b56f382cfb0409), [07969983cb1e](https://github.com/aurora-silicon/linux/commit/07969983cb1edefaec1b4b0aabb2307b0b14dacd), [953220ab6d74](https://github.com/aurora-silicon/linux/commit/953220ab6d748bd05db3854f374b701696f6c795) | Ryan Murray | arm64: dts: apple: t8140: describe the external display DARTs once | Not applicable — PERIPH | V | -| [55a5beb425ae](https://github.com/aurora-silicon/linux/commit/55a5beb425ae7c901851c2185e3219d8c0348fcb), [f0234a79d172](https://github.com/aurora-silicon/linux/commit/f0234a79d172479cb7dbcdb713daa5739ad87f74), [c80113dfaab9](https://github.com/aurora-silicon/linux/commit/c80113dfaab9e985b9f617bfde06c481fd17376c) | Ryan Murray | arm64: dts: apple: t8140-j700: give the two RTCs fixed numbers | Not applicable — PERIPH | V | -| [9e1fb240e1df](https://github.com/aurora-silicon/linux/commit/9e1fb240e1df4064a9232007daa5c8797dfbcda4), [19e2b5adfe69](https://github.com/aurora-silicon/linux/commit/19e2b5adfe6905ab2f3fff6ad1a12801d711c607), [ea044d49c76c](https://github.com/aurora-silicon/linux/commit/ea044d49c76c18079848672c2779c7521a6b8fc3) | Ryan Murray | arm64: dts: apple: t8140: Keep the GPIO power state on for the SEP | Not applicable — PERIPH | V | -| [4334bbd7162a](https://github.com/aurora-silicon/linux/commit/4334bbd7162af085ed1c8c7b63859bed8c6646ef), [f1c076a9bf8a](https://github.com/aurora-silicon/linux/commit/f1c076a9bf8a850bec0140fb3e91a9607aadcf4e), [30812f491575](https://github.com/aurora-silicon/linux/commit/30812f491575ede27e5be059fd6afc4e985166f1) | DjDeveloperr | arm64: dts: apple: t8140-j700: keep the DCS rail out of thermal control | Not applicable — DCSOFF | P,R | -| [baacaf604632](https://github.com/aurora-silicon/linux/commit/baacaf60463212b2270f0ad0b50cdabe4e27ab6d), [071651bd5c30](https://github.com/aurora-silicon/linux/commit/071651bd5c30330ecb9980c3c1f2cc4e2f04d1a6), [40a9c929c55f](https://github.com/aurora-silicon/linux/commit/40a9c929c55f2b13c39e732fc2ae3f10e1506634) | Ryan Murray | arm64: dts: apple: describe disabled J700 external resources | Not applicable — PERIPH | V | -| [13af1cb29b95](https://github.com/aurora-silicon/linux/commit/13af1cb29b95b1fc260870868d3c54a596cc483d), [f284458cdfc3](https://github.com/aurora-silicon/linux/commit/f284458cdfc33d2746bb4ede9174adc3afaa2f7f) | Ryan Murray | arm64: dts: apple: t8140: describe the external binding the display master recognizes | Not applicable — PERIPH | V | -| [a7f9b86ea187](https://github.com/aurora-silicon/linux/commit/a7f9b86ea18778f313b73cd174debe54e4dbc09c), [cffe838aca8e](https://github.com/aurora-silicon/linux/commit/cffe838aca8e275526730bd6f3fee5ebcaec0c47), [205a56d33cb0](https://github.com/aurora-silicon/linux/commit/205a56d33cb07184d7dfe17ab8aba0996cff3efe) | Ryan Murray | arm64: dts: apple: retain the inherited external display supply | Not applicable — PERIPH | V | -| [328dacb9d1ad](https://github.com/aurora-silicon/linux/commit/328dacb9d1adcbc1be84e8dae660c72bc12a3005), [3d16013f9795](https://github.com/aurora-silicon/linux/commit/3d16013f979572f7f7f6d1573f2af739e8ac25b4), [2e6003f6db07](https://github.com/aurora-silicon/linux/commit/2e6003f6db07b0e0a6b2bf2b977753bee47556b0) | Ryan Murray | arm64: dts: apple: add an explicit external display trial tree | Not applicable — PERIPH | V | -| [6b82a41053b8](https://github.com/aurora-silicon/linux/commit/6b82a41053b87c8bd0917f72f71778293aa7f276), [70cce5cd20ef](https://github.com/aurora-silicon/linux/commit/70cce5cd20efb8a71d49563b45481c32e0de23a6), [0a0d25f4a99b](https://github.com/aurora-silicon/linux/commit/0a0d25f4a99b66a08a2ab4a22314782aaad7b3e2) | DjDeveloperr | arm64: dts: apple: t8140-j700: drive the SPI NOR on a single data line | Not applicable — PERIPH | V | -| [d56b7ce044f2](https://github.com/aurora-silicon/linux/commit/d56b7ce044f274b153a3b1f9192d3fd4c7cb2d85), [df94160d7567](https://github.com/aurora-silicon/linux/commit/df94160d756756e14d4bc818fe0652bcdb9adc30) | DjDeveloperr | arm64: dts: apple: t8140-j700: enable the validated external display profile by default | Not applicable — PERIPH | V | -| [f9e24b02bc85](https://github.com/aurora-silicon/linux/commit/f9e24b02bc8547acba1453cf462f0f210e707ba7), [be5f3162c985](https://github.com/aurora-silicon/linux/commit/be5f3162c9854d6b5ea8ca9e8f29f764b2c6251b) | Eryk Wieliczko | arm64: dts: apple: t8140: mark firmware-owned power domains | Not applicable — PERIPH | V | -| [7df682a70733](https://github.com/aurora-silicon/linux/commit/7df682a707337025aad3c093252ea7f8504e8345), [b0714e8783f6](https://github.com/aurora-silicon/linux/commit/b0714e8783f685f213c15890c7942c1c03d6c1e3) | Chris Kearney | PCI: apple: enumerate Thunderbolt PCIe on t8103 | Not applicable — LEGACY; `drivers/iommu/apple-dart.c` | V | -| [4c02ff022799](https://github.com/aurora-silicon/linux/commit/4c02ff022799be8aef47108a61671a6a6cd86038), [b388a175a612](https://github.com/aurora-silicon/linux/commit/b388a175a612be6c5d10056c6a10a7219030272d) | Chris Kearney | PCI: apple: finish tunneled IOMMU commands before the port clock stops | Not applicable — TUNNEL; `drivers/iommu/apple-dart.c` | V | -| [9e8a900fee27](https://github.com/aurora-silicon/linux/commit/9e8a900fee275872aa1019df27a4944b73c8940a), [a2b13c1f0369](https://github.com/aurora-silicon/linux/commit/a2b13c1f03696ae69101c8ed51b8901d32dffcd4), [5a7b76f31c3a](https://github.com/aurora-silicon/linux/commit/5a7b76f31c3a8ccdc48fd586e5b646fa0c49499d) | Chris Kearney | iommu/apple-dart: enforce command gating during tunnel teardown | Not applicable — TUNNEL; `drivers/iommu/apple-dart-test.c` | V | -| [39e90a052954](https://github.com/aurora-silicon/linux/commit/39e90a052954d1305a45ca0065eda42ec4aff639), [d15623fd3261](https://github.com/aurora-silicon/linux/commit/d15623fd32614870a9eb62d25afdd823a39bcde7), [65e3e0ed688a](https://github.com/aurora-silicon/linux/commit/65e3e0ed688a5a933a60d92ca79b6136c357b876) | Chris Kearney | iommu/apple-dart: report tunnel command-resume failures | Not applicable — TUNNEL; `drivers/iommu/apple-dart-test.c` | V | -| [3a94483e259c](https://github.com/aurora-silicon/linux/commit/3a94483e259cbc8d0aab638eaa4af5b72c4db6e6), [6e0c3cdf7855](https://github.com/aurora-silicon/linux/commit/6e0c3cdf78550987513b0d4c15ffec90b442b787), [64dfa24ca989](https://github.com/aurora-silicon/linux/commit/64dfa24ca989fec06367a7199164a70de7d99e35) | Chris Kearney | PCI: apple: describe tunneled PM ordering by Linux dependencies | Not applicable — TUNNEL; `drivers/iommu/apple-dart.c` | V | -| [5d4dd51e2769](https://github.com/aurora-silicon/linux/commit/5d4dd51e27695b5d9570e56b050e3574dfc1fd38), [e7292daedcaa](https://github.com/aurora-silicon/linux/commit/e7292daedcaa2186e5b8b484343dc3ec239b2805), [615be505e22c](https://github.com/aurora-silicon/linux/commit/615be505e22c592c1a87c193b22c58dc4c064840) | Chris Kearney | thunderbolt: restore M1 tunneled PCIe state and recover late link loss | Not applicable — TUNNEL; `drivers/iommu/apple-dart-test.c` | V | -| [95caa2cf7ac7](https://github.com/aurora-silicon/linux/commit/95caa2cf7ac7244080527b90da0d43ec917e1513), [92f33b680514](https://github.com/aurora-silicon/linux/commit/92f33b6805149c955b543a6e2c29f88c42886f6d), [fc559d251fca](https://github.com/aurora-silicon/linux/commit/fc559d251fcac7e904607a36fb4b17770e29f239) | Acelogic | irqchip/apple-aic: use architectural guest timer masks on T8142 | Not applicable — OTHERCHIP; `drivers/irqchip/irq-apple-aic.c` | V | -| [4d1bcf62c1af](https://github.com/aurora-silicon/linux/commit/4d1bcf62c1af6fa29a32e94d821f4174098cbd29), [4ae1f9604a1a](https://github.com/aurora-silicon/linux/commit/4ae1f9604a1aa503dd1b452578bf694dbadaca25), [40bc3b97c1d6](https://github.com/aurora-silicon/linux/commit/40bc3b97c1d6a75ff5f8af9bc75322388a5381e1) | DjDeveloperr | soc: apple: rtkit-helper: adopt a running T8140 MTP session | Not applicable — PERIPH; `drivers/soc/apple/rtkit-helper.c` | V | -| [ad7993e04cd2](https://github.com/aurora-silicon/linux/commit/ad7993e04cd2e39c4fe011740268a537868bb8c0), [58a792863c4f](https://github.com/aurora-silicon/linux/commit/58a792863c4fdd79342e5e83ece8f652993084ab), [80cabfefcdc5](https://github.com/aurora-silicon/linux/commit/80cabfefcdc52036a7902268ff42f2a9370fe5c2) | Acelogic | cpufreq: apple: Add bounded T8152 E and P/M performance domains | Not applicable — OTHERCHIP; `drivers/cpufreq/apple-soc-cpufreq.c` | V | -| [81aefe80b586](https://github.com/aurora-silicon/linux/commit/81aefe80b586fa545b20eb90090202cde51718e7), [48f073156423](https://github.com/aurora-silicon/linux/commit/48f0731564236dc79c43bbcdadf6b05cfd807e8a), [296dbb45adff](https://github.com/aurora-silicon/linux/commit/296dbb45adff8654c6f1f8029e7b6b567f990e0b) | Acelogic | cpufreq: apple: add T8142 command-state transitions | Not applicable — OTHERCHIP; `drivers/cpufreq/apple-soc-cpufreq.c` | V | -| [4c3405d11d29](https://github.com/aurora-silicon/linux/commit/4c3405d11d29ec8a49a14bdc546cef4411153b32), [b08be27ef235](https://github.com/aurora-silicon/linux/commit/b08be27ef235dfedb3d18cf4a91a821be8a7effc) | Ryan Murray | cpufreq: apple: retain the unmanaged P-state ceiling on T8152 | Not applicable — OTHERCHIP; `drivers/cpufreq/apple-soc-cpufreq.c` | V | -| [24f4a32e8ec9](https://github.com/aurora-silicon/linux/commit/24f4a32e8ec9438b198e7ca97658154bcaedc6f7), [129471fc83b8](https://github.com/aurora-silicon/linux/commit/129471fc83b89e08275048a812779583ef197a93), [c0bd8b9fec16](https://github.com/aurora-silicon/linux/commit/c0bd8b9fec163274b9e6056ae94fe54d53b565fb), [b4ee9bd8d923](https://github.com/aurora-silicon/linux/commit/b4ee9bd8d923949b19cc22484262670948cafc57) | DjDeveloperr | drm/asahi: clarify the opening polling budget [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/mod.rs` | V | -| [52f6e8610625](https://github.com/aurora-silicon/linux/commit/52f6e86106255b26e84671649c5f4acb0f434cde), [840488b0b60d](https://github.com/aurora-silicon/linux/commit/840488b0b60d3162e92f050cc59a2b3967036544), [66631bc63295](https://github.com/aurora-silicon/linux/commit/66631bc632956bb7dfd1b4fb44e48ae90a10140e), [d0aadc1e99e6](https://github.com/aurora-silicon/linux/commit/d0aadc1e99e6f11a54bbca5ee685d7c015866789) | DjDeveloperr | drm/asahi: describe the G17 word tables without their generation history [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/fw/initdata.rs` | V | -| [1c771d73ac6c](https://github.com/aurora-silicon/linux/commit/1c771d73ac6c5e953be9582f1b74ccb358e6322d), [d24b1a49853f](https://github.com/aurora-silicon/linux/commit/d24b1a49853fe6949b44790761678cd2d38e623e), [a6e06b47b49d](https://github.com/aurora-silicon/linux/commit/a6e06b47b49d2666a53b5bc45ba8e0fa22e74944) | Joshua Warren | drm/asahi: Add stats_export module parameter | Not applicable — STAT; `drivers/gpu/drm/asahi/Makefile` | T | -| [3f096100f658](https://github.com/aurora-silicon/linux/commit/3f096100f658c1563dafaa0f0ca8b77ea2a87fe3), [f436b4da5480](https://github.com/aurora-silicon/linux/commit/f436b4da5480140e5ba95d68e46f1e7dd7615db8) | Ryan Murray | drm/asahi: tie stats registration to a per-device snapshot owner | Not applicable — STAT; `drivers/gpu/drm/asahi/g17/mod.rs` | T | -| [fd13851e08b6](https://github.com/aurora-silicon/linux/commit/fd13851e08b689661332ee823ad65eafd4418c1a), [c91a9274e4b2](https://github.com/aurora-silicon/linux/commit/c91a9274e4b2736d5589826b07c8dc54c0e35055) | Ryan Murray | drm/asahi: describe the G17 tiler-heap shrink policy in hardware terms | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/buffer.rs` | V | -| [af5c7b24a0e5](https://github.com/aurora-silicon/linux/commit/af5c7b24a0e5932026c8cbab8633f2563bf761ba), [f0ec35d78e5a](https://github.com/aurora-silicon/linux/commit/f0ec35d78e5adf9988c1bc71418d0a764c8d4ba3), [337b14463d50](https://github.com/aurora-silicon/linux/commit/337b14463d5010296efb0b17dfaa11b8f7601aae) | Ryan Murray | arm64: dts: apple: t8140: Fold the trailing soc override into the soc node [#314](https://github.com/aurora-silicon/linux/pull/314) | Not applicable — PERIPH | V | -| [3cd89c634a60](https://github.com/aurora-silicon/linux/commit/3cd89c634a60071014683a27d497e46b8e2e2fc5), [f5ba7b6ee41c](https://github.com/aurora-silicon/linux/commit/f5ba7b6ee41ca4545745bfcc312fdbc0abf3e491), [6f1b4ab6f2f0](https://github.com/aurora-silicon/linux/commit/6f1b4ab6f2f036dedd104b83df774d6284ecab74) | Ryan Murray | arm64: dts: apple: t8140: Tidy the mailbox and pinctrl comments [#314](https://github.com/aurora-silicon/linux/pull/314) | Not applicable — PERIPH | V | -| [553e961d56c9](https://github.com/aurora-silicon/linux/commit/553e961d56c9ecbf6d58561c98468496955ad1d3), [38dd24cdc5a3](https://github.com/aurora-silicon/linux/commit/38dd24cdc5a3e13555afcac85f28d8ca3fc77a8e), [742366203cc8](https://github.com/aurora-silicon/linux/commit/742366203cc8a1f9356d82a43d52e2cb6fa97621) | Ryan Murray | pmdomain: apple: pmp-report: remove the raw DVFS debugfs dump [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — RAWDIAG; `drivers/pmdomain/apple/pmp-report.c` | O | -| [d04cbb892d26](https://github.com/aurora-silicon/linux/commit/d04cbb892d26dca250de4ff6f8c6cde5446682fb), [34754dd5bf3b](https://github.com/aurora-silicon/linux/commit/34754dd5bf3bd3d21b3409b6768af8b8fa38a045), [21c1d3f21ac4](https://github.com/aurora-silicon/linux/commit/21c1d3f21ac49f4223993ed1beefca1d6d6e89cd) | Ryan Murray | arm64: dts: apple: t8140: state why PMGR domains off at boot are always-on [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — PERIPH | V | -| [c3760b2f1cbd](https://github.com/aurora-silicon/linux/commit/c3760b2f1cbd4e17586ced9ac0d9ae7e8fe7d024), [732facd15036](https://github.com/aurora-silicon/linux/commit/732facd1503659e30fb096e0276e2efcdfa41ed7), [0d1799c7c179](https://github.com/aurora-silicon/linux/commit/0d1799c7c179d3b6e914eeaee59da7529e824565) | Ryan Murray | arm64: dts: apple: t8140-j700: trim measurement notes from comments [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — PERIPH | V | -| [ac9e0f78ef56](https://github.com/aurora-silicon/linux/commit/ac9e0f78ef560ef9d7a5c5655c7253e938b08d71), [f2928aa2ef66](https://github.com/aurora-silicon/linux/commit/f2928aa2ef662ff9045367ee9910a62a0f0b4e4b) | Ryan Murray | pmdomain: apple: pmc: Test partial enables and probe unwind | Not applicable — VERIFY; `drivers/pmdomain/apple/pmc-test.c` | V | -| [e8e0eae211f9](https://github.com/aurora-silicon/linux/commit/e8e0eae211f9d97ad777522ac8bf0c331ebf20f8), [a20499ed1321](https://github.com/aurora-silicon/linux/commit/a20499ed1321d5e5054d0f3dfd3f3a622e2938be) | Ryan Murray | soc: apple: mcc: Test partial allocation enable and cache handoff | Not applicable — VERIFY; `drivers/soc/apple/Kconfig` | V | -| [f2669637e7a6](https://github.com/aurora-silicon/linux/commit/f2669637e7a6c7e24f8eac823097156728ce64a8), [e3d59133d7a7](https://github.com/aurora-silicon/linux/commit/e3d59133d7a793ac15e3fa7328d11dafff8d8c92), [d6094473be4c](https://github.com/aurora-silicon/linux/commit/d6094473be4ceae69e8385ffb03891a22c60c3e4) | Ryan Murray | soc: apple: rtkit-helper: Terminate log messages [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/soc/apple/rtkit-helper.c` | V | -| [8a83508a3870](https://github.com/aurora-silicon/linux/commit/8a83508a3870e8dd8d15ade42c759ed1be8fc9c1), [bee2492c2bac](https://github.com/aurora-silicon/linux/commit/bee2492c2bac7c4cf6022cffadd92b1e4fae2f54), [0afefd991028](https://github.com/aurora-silicon/linux/commit/0afefd9910288c1783a2756c4240dfc80ee8470f) | Ryan Murray | iommu: apple-dart: Return IOMEM_ERR_PTR() from the tunneled MMIO helper [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — TUNNEL; `drivers/iommu/apple-dart.c` | V | -| [d970f88dd819](https://github.com/aurora-silicon/linux/commit/d970f88dd819b24905808cac119647625e382303), [6b8a1244cb2c](https://github.com/aurora-silicon/linux/commit/6b8a1244cb2c8e0da6290fe794fb442b5cb9404e), [27da3a5d53ca](https://github.com/aurora-silicon/linux/commit/27da3a5d53ca11f2aeff4916d25f40308c378a07) | Eryk Wieliczko | arm64: dts: apple: t8140-j700: give the boot framebuffer its panel | Not applicable — PERIPH | V | -| [8a9127fdd1f5](https://github.com/aurora-silicon/linux/commit/8a9127fdd1f54bfe2913e7996073a994eb41ff04), [8feaf5d2fa71](https://github.com/aurora-silicon/linux/commit/8feaf5d2fa714a11984b1eeafd5dd2e076ec4af6), [748b2a25f2ca](https://github.com/aurora-silicon/linux/commit/748b2a25f2ca960017eef868e2323a27e07f0fe2) | Ryan Murray | drm/asahi: clean up the statistics Rust style | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [c987a1793e75](https://github.com/aurora-silicon/linux/commit/c987a1793e759da730ff84384a601d9d96d916d3), [37b3b1f7de85](https://github.com/aurora-silicon/linux/commit/37b3b1f7de8547eca29a4414465b5b4d705d413d) | Chris Kearney | drm/apple: wait for T6030 RTKit callbacks before a DCP is freed | Not applicable — G15; `drivers/gpu/drm/apple/dcp.c` | V | -| [9639e3803ffb](https://github.com/aurora-silicon/linux/commit/9639e3803ffb7f73c58dbbacad17a6e40b7596ac), [346fd6083ab2](https://github.com/aurora-silicon/linux/commit/346fd6083ab2d45a079fe512c6b3e68affd4cc6f) | Ryan Murray | drm/asahi: free completed commands on system_dfl_wq | Not applicable — LEGACY; `drivers/gpu/drm/asahi/workqueue.rs` | V | -| [3e6775c52948](https://github.com/aurora-silicon/linux/commit/3e6775c52948793951b618817b3715eec5f91924), [b9527e10b2b6](https://github.com/aurora-silicon/linux/commit/b9527e10b2b683dff7d4b718e9af6f93fb0a005f) | Ryan Murray | arm64: add an isolated T8140 graphics and power profile | Not applicable — PERIPH | V | -| [7f40cd79f058](https://github.com/aurora-silicon/linux/commit/7f40cd79f0582c4ca1abbad36f1e923d8163779f), [58db6bfedcec](https://github.com/aurora-silicon/linux/commit/58db6bfedcec7cb4a2be3843c5d3665b4680553e) | Chris Kearney | soc: apple: test every PMP integer replacement width | Not applicable — VERIFY; `drivers/soc/apple/pmp_bootargs.rs` | V | -| [0a1f130cd042](https://github.com/aurora-silicon/linux/commit/0a1f130cd0427037fc94a4ad39e54a3c66d5dbac), [f11518fc495d](https://github.com/aurora-silicon/linux/commit/f11518fc495d51dc3c5d8f67cc10d7cb02a4d739) | Eryk Wieliczko | pmdomain: apple: add the GFX TVM gate | Not applicable — G16; `drivers/pmdomain/apple/Makefile` | V | -| [4e7c8a74e4a5](https://github.com/aurora-silicon/linux/commit/4e7c8a74e4a5ef03a1d06b5cd73f01c68b75a63d), [fe7d063e4cee](https://github.com/aurora-silicon/linux/commit/fe7d063e4cee437b5196c438f9f19a6ad7e22afc) | Satya Benson | pmdomain: apple: gfx-tvm: accept the T8122 | Not applicable — G15; `drivers/pmdomain/apple/gfx-tvm.c` | V | -| [460c0a77ca86](https://github.com/aurora-silicon/linux/commit/460c0a77ca860aef48d7ed449d65a878cffab9ed), [c8aed729e9bf](https://github.com/aurora-silicon/linux/commit/c8aed729e9bf8d23f0adabff999aa16d34201d76) | Joshua Warren | gpu: let the firmware preempt compute work on G14X | Not applicable — LEGACY; `drivers/gpu/drm/asahi/asahi_core.rs` | V | -| [80797e4f1b2b](https://github.com/aurora-silicon/linux/commit/80797e4f1b2bbde71964ea2253553d2c2dbbe379), [9c7ab8b412a5](https://github.com/aurora-silicon/linux/commit/9c7ab8b412a50123bf7dbc642368aa7f930d2d41) | Ryan Murray | drm/asahi: gate compile-only M3 backends before resource setup | Not applicable — G15; `drivers/gpu/drm/asahi/asahi_core.rs` | V | -| [700bfca794e5](https://github.com/aurora-silicon/linux/commit/700bfca794e50093c6e4d2b4231aca6252451a41), [860d185ccc57](https://github.com/aurora-silicon/linux/commit/860d185ccc575a47df4962cb1cf32da8f27ff35f) | Chris Kearney | drm/asahi: add the M3 (G15S) GPU runtime (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_compute_layout.rs` | V | -| [01680f395e55](https://github.com/aurora-silicon/linux/commit/01680f395e557e93b331ad510fbf255e6622c2a0), [a846942e367d](https://github.com/aurora-silicon/linux/commit/a846942e367dade6002d2d456ae6249c50d04d39) | Eryk Wieliczko | drm/asahi: share M3 M4 host retirement accounting (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/agx_host_progress.rs` | V | -| [9593d5f2498f](https://github.com/aurora-silicon/linux/commit/9593d5f2498f3243100c828cc7bbf7ecdaddb861), [4bcb6f1acab4](https://github.com/aurora-silicon/linux/commit/4bcb6f1acab42a1772bf62aaae00c5fb1f6007cd) | Eryk Wieliczko | drm/asahi: account M3 GEM and coherent firmware backing lifetimes (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/agx_memory_stats.rs` | V | -| [bba3fa8f4562](https://github.com/aurora-silicon/linux/commit/bba3fa8f4562761864f8f57b1a461bcd50ec3d64), [3e963ea31aca](https://github.com/aurora-silicon/linux/commit/3e963ea31acaad3e4a78dc137f12339fa8ebb5ee) | Chris Kearney | drm/asahi: expose bounded native retirement timing snapshots (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/agx_timing_stats.rs` | V | -| [6d24d16ce24c](https://github.com/aurora-silicon/linux/commit/6d24d16ce24c8af1902191781e1255807ccd8aae), [1324a0258bb0](https://github.com/aurora-silicon/linux/commit/1324a0258bb0d0987993a3c34c2a74b0f2093cce) | Chris Kearney | drm/asahi: expose host-tracked pending GPU activity separately from completions (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/agx_host_progress.rs` | V | -| [a4bbcd4baf93](https://github.com/aurora-silicon/linux/commit/a4bbcd4baf933a15e5bc75b2c7c5603d8b1b6998), [8faa4de3948b](https://github.com/aurora-silicon/linux/commit/8faa4de3948b0795c068eeeb0456a6a7dfc45077) | Chris Kearney | drm/asahi: avoid repeated activity fences while GPU work is pending (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/agx_host_progress.rs` | V | -| [2397ac8a0861](https://github.com/aurora-silicon/linux/commit/2397ac8a086119bba90f6fc0d8d430e035d27f30), [b62d349e0fc6](https://github.com/aurora-silicon/linux/commit/b62d349e0fc6e160b9dabd167166a2d87ecfdbce) | Eryk Wieliczko | drm/asahi: remove M3 lifetime submission cap with wrapping wire stamps (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_timeline.rs` | V | -| [ce78a5b0c517](https://github.com/aurora-silicon/linux/commit/ce78a5b0c5173dbb9b5d7d0017488c43a07f222f), [578aa862e357](https://github.com/aurora-silicon/linux/commit/578aa862e357f0f61e18dc8e26181eeb5c0b9d7b) | Eryk Wieliczko | drm/asahi: preserve nonzero M3 stamps and dependencies through rollover (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_timeline.rs` | V | -| [646db65b2128](https://github.com/aurora-silicon/linux/commit/646db65b212826a29bd969332760722077926d61), [1d6a90b4117f](https://github.com/aurora-silicon/linux/commit/1d6a90b4117fe9cb84aa7863f491d18d37fcf0c5) | Chris Kearney | drm/asahi: remove unused backend helpers and narrow layout visibility (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_compute_storage.rs` | V | -| [a91573de916a](https://github.com/aurora-silicon/linux/commit/a91573de916a12ddc980c75d977567e57725e449), [f939d03f703f](https://github.com/aurora-silicon/linux/commit/f939d03f703fe760f413a87d435769b3aa970d21) | Chris Kearney | treewide: apple: reword M3 comments and messages as plain technical statements (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_compute_sequence.rs` | V | -| [997a7dba8158](https://github.com/aurora-silicon/linux/commit/997a7dba81582c94d1bdcc26aaae6031a486390c), [262009a6c7f9](https://github.com/aurora-silicon/linux/commit/262009a6c7f9dc7b6ca4abb158b669870a6180c5) | Chris Kearney | drm/asahi: select M3 runtime configuration per SoC (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_init_storage.rs` | V | -| [a8065eb937ce](https://github.com/aurora-silicon/linux/commit/a8065eb937cee67032a68207827419c515e52e11), [d16a8c32954b](https://github.com/aurora-silicon/linux/commit/d16a8c32954b412bb3bf9f61a7c48a68dc9303b1) | Chris Kearney | drm/asahi: m3: derive runtime IO maps from IO mappings (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_init_storage.rs` | V | -| [c3d978ed0793](https://github.com/aurora-silicon/linux/commit/c3d978ed0793058248d9994e868f5c1043cc18f7), [7f04f81b5a19](https://github.com/aurora-silicon/linux/commit/7f04f81b5a191b8ff9b1a3d454656af3993b47be) | Satya Benson | drm/asahi: m3: size render TPC and preemption storage by cluster count (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_pass_layout.rs` | V | -| [4287d2b5166b](https://github.com/aurora-silicon/linux/commit/4287d2b5166bb92f791ae652dba8361cfc732aeb), [d94dcc88b26c](https://github.com/aurora-silicon/linux/commit/d94dcc88b26ca0e964b5298ee1298ed068cbf6eb) | Satya Benson | drm/asahi: m3: publish queued packets from the completion worker (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [6046b500e687](https://github.com/aurora-silicon/linux/commit/6046b500e6872cfe56d53cb65e9b0619cb1f066c), [6787ae6d5717](https://github.com/aurora-silicon/linux/commit/6787ae6d57170ef75c454f6f744d4c4d557cb9a7) | Satya Benson | drm/asahi: m3: bound overlapping render batches to free pass slots (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [4ea0ea7df543](https://github.com/aurora-silicon/linux/commit/4ea0ea7df5437fad2829ec8eb68be6e9f3544591), [ce9df27fd4b6](https://github.com/aurora-silicon/linux/commit/ce9df27fd4b67bd47194655b57efecdec2321081) | Satya Benson | drm/asahi: m3: budget render coalescing by measured per-VM GPU time (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [b877dfb7e3e8](https://github.com/aurora-silicon/linux/commit/b877dfb7e3e89e31fef97057c68581660b6f256e), [d57591e332b4](https://github.com/aurora-silicon/linux/commit/d57591e332b49cafc12aaf8af77845525dda760b) | Chris Kearney | drm/asahi: m3: compare waiting urgency with the active render batch (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [f9ede2dda5dd](https://github.com/aurora-silicon/linux/commit/f9ede2dda5dd7a0fa8ce0e1143724e7be01b31a0), [7c912ffa2635](https://github.com/aurora-silicon/linux/commit/7c912ffa2635dd08673a43c09442a143a39b624d) | Chris Kearney | drm/asahi: retain full firmware-log payloads and use ring entry sizes (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_init_layout.rs` | V | -| [02e89516c254](https://github.com/aurora-silicon/linux/commit/02e89516c254d55b4ae686ccae460af8ddd30901), [e2bbe50fc3fd](https://github.com/aurora-silicon/linux/commit/e2bbe50fc3fd42e5dfbd74e5aff9181af86bb096) | Chris Kearney | drm/asahi: keep firmware-log payload clear of render counter pages (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_init_storage.rs` | V | -| [eb1dec967643](https://github.com/aurora-silicon/linux/commit/eb1dec967643c6b4fbbd528812befd07434951d8), [11896702843e](https://github.com/aurora-silicon/linux/commit/11896702843eb979e00beb871090800d9c53a4e0) | Chris Kearney | drm/asahi: coalesce eligible T6030 render completion stamp flushes (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [407c4ba9d5c8](https://github.com/aurora-silicon/linux/commit/407c4ba9d5c8f14292a7ba75afdc929475a0e40c), [7feec149fdc7](https://github.com/aurora-silicon/linux/commit/7feec149fdc7795ff82698683c86dc4b3a2a486b) | Chris Kearney | drm/asahi: order opt-in T6030 mixed batches with firmware barriers (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [d8c059ddae69](https://github.com/aurora-silicon/linux/commit/d8c059ddae697f618e0b70b4b2ddee103ba9a1eb), [0377e6c2e9ad](https://github.com/aurora-silicon/linux/commit/0377e6c2e9ad549130015a52de84c0c24e47a343) | Chris Kearney | drm/asahi: make T6030 internal render measurements optional (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [ad54cf1de60e](https://github.com/aurora-silicon/linux/commit/ad54cf1de60ea638b0ab96e80d9bea7d7fc726ea), [cd13ef870e00](https://github.com/aurora-silicon/linux/commit/cd13ef870e00dd86aed1b582b393c6a697bec326) | Chris Kearney | drm/asahi: use stage-specific render sequence length fields (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_command_layout.rs` | V | -| [16fef343da41](https://github.com/aurora-silicon/linux/commit/16fef343da414828fe4098a566951945838bb370), [689764765782](https://github.com/aurora-silicon/linux/commit/68976476578273e77d0d5f05f77f437f610dbee8) | Chris Kearney | drm/asahi: add bounded T6030 active power-state sampling (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_active_power.rs` | V | -| [019434491afe](https://github.com/aurora-silicon/linux/commit/019434491afe2cd57bc001515778d9412c9b0747), [cd09499b2a78](https://github.com/aurora-silicon/linux/commit/cd09499b2a78ce5e0ca1b628af94403c56467256) | Chris Kearney | drm/asahi: add opt-in T6030 consistent performance requests (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_active_power.rs` | V | -| [b09e6d9fca33](https://github.com/aurora-silicon/linux/commit/b09e6d9fca33c554a597774f1a6cd4c4ca54622b), [263fd8538d83](https://github.com/aurora-silicon/linux/commit/263fd8538d83cca3809589da9b78cb1d982c0a21) | Chris Kearney | drm/asahi: refresh an opt-in T6030 busy performance request (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_consistent_perf.rs` | V | -| [9bc784357fe8](https://github.com/aurora-silicon/linux/commit/9bc784357fe8affe0875fb911be88ac953ca30db), [db732ce1f244](https://github.com/aurora-silicon/linux/commit/db732ce1f24488887872abc3b61b45de95285252) | Chris Kearney | drm/asahi: add an opt-in T6030 Globals debug-word clear (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_globals_debug.rs` | V | -| [02bde1b70c31](https://github.com/aurora-silicon/linux/commit/02bde1b70c312f6d4d964c7a2b1737be0de5a909), [651fbc49524d](https://github.com/aurora-silicon/linux/commit/651fbc49524d677ff86766dd2d85bb1bbf6ab3eb) | Chris Kearney | drm/asahi: m3: groundwork for more than two clusters and T6031 tables (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_pass_layout.rs` | V | -| [0f47fbf31934](https://github.com/aurora-silicon/linux/commit/0f47fbf31934d0b1684b5412e235315304687d4a), [783f9478d373](https://github.com/aurora-silicon/linux/commit/783f9478d3737cfae945aad01e02e9dea30c2249) | Chris Kearney | drm/asahi: reject unsupported command fields on the M1/M2 queue path | Not applicable — LEGACY; `drivers/gpu/drm/asahi/queue/mod.rs` | V | -| [1de2dbd89acb](https://github.com/aurora-silicon/linux/commit/1de2dbd89acb80f37aec08fa897374dfebe56b10), [294e9f9ebfb4](https://github.com/aurora-silicon/linux/commit/294e9f9ebfb42dbc77a85f635b5bfabaa9315003) | Chris Kearney | drm/asahi: excise unbound G16 and G17 runtimes (M3-only split: TA/3D command encoders) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/agx_render.rs` | V | -| [fd1a2a3d4e60](https://github.com/aurora-silicon/linux/commit/fd1a2a3d4e60ce3f3965d2a47d1904ce3a6ed158), [e91bc024eef8](https://github.com/aurora-silicon/linux/commit/e91bc024eef8a6fde320f7fa062a034a2fe0bccb) | Eryk Wieliczko | drm/asahi: carry validated M3 depth compression bindings | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_fragment_command.rs` | V | -| [bc0a841680f3](https://github.com/aurora-silicon/linux/commit/bc0a841680f3b36193e83e18c339d269d142de03), [2c301fab2412](https://github.com/aurora-silicon/linux/commit/2c301fab241280c36f20c57d7d240ff0f48ad88f) | garymeyerca | drm/asahi: gate T8122 G15G identity before startup | Not applicable — G15; `drivers/gpu/drm/asahi/m3/mod.rs` | V | -| [e10c013299bf](https://github.com/aurora-silicon/linux/commit/e10c013299bf639ca0c8f08574150970e381f203), [be90c110d9df](https://github.com/aurora-silicon/linux/commit/be90c110d9dfcae3918efad4ba9a3d5015bb5bf4) | Chris Kearney | drm/asahi: select M3 runtime configuration per SoC | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_soc.rs` | V | -| [ed90e7bfde51](https://github.com/aurora-silicon/linux/commit/ed90e7bfde5160c20b1e4165f577e874e60fc102), [a6b472702f24](https://github.com/aurora-silicon/linux/commit/a6b472702f24666ee52febc1c2eb93bf21c8d44a) | Satya Benson | drm/asahi: m3: T8122: the G15G compute register list | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_compute_layout.rs` | V | -| [278d0abfc612](https://github.com/aurora-silicon/linux/commit/278d0abfc6128a83aa00d9181bdf2c716b608c89), [7949c0d6139c](https://github.com/aurora-silicon/linux/commit/7949c0d6139c53f8e016cd773744386407a8c9cf) | Satya Benson | drm/asahi: m3: T8122: the G15G TA and 3D register lists | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_fragment_command.rs` | V | -| [7231c0beb83e](https://github.com/aurora-silicon/linux/commit/7231c0beb83ec1976716d28456e09df3e159f2e5), [bfd3e0bf0bbc](https://github.com/aurora-silicon/linux/commit/bfd3e0bf0bbc64ee99213b4b5b3824b588411bba) | Satya Benson | drm/asahi: m3: T8122: the runtime HwDataB words | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_soc.rs` | V | -| [6ad35705d81d](https://github.com/aurora-silicon/linux/commit/6ad35705d81dd1e65f8ef9e1f4136a0080ead760), [f6e58511c69a](https://github.com/aurora-silicon/linux/commit/f6e58511c69ae5cdef73b3ba0d87de8de9a74e01) | Chris Kearney | drm/asahi: m3: T8122: the remaining runtime InitData words | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_soc.rs` | V | -| [2a8cdd0ce1d4](https://github.com/aurora-silicon/linux/commit/2a8cdd0ce1d4a8ceef673922b9517e4780996a0c), [d109a5c9e597](https://github.com/aurora-silicon/linux/commit/d109a5c9e59768669f2d1750ab1abd4560a42e28) | Chris Kearney | drm/asahi: coalesce eligible T6030 render completion stamp flushes | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_fragment_command.rs` | V | -| [bb1f75a18b32](https://github.com/aurora-silicon/linux/commit/bb1f75a18b3265ab5e4a06e424df43ed0371c002), [d4dba3df31cf](https://github.com/aurora-silicon/linux/commit/d4dba3df31cff8f96ddeafad6a4b2709fe942d62) | Chris Kearney | drm/asahi: use stage-specific render sequence length fields | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_fragment_command.rs` | V | -| [1e8f813be7c6](https://github.com/aurora-silicon/linux/commit/1e8f813be7c681b558ffcd501ea278d6848099f4), [3d7945cbbd0f](https://github.com/aurora-silicon/linux/commit/3d7945cbbd0f9dd9d7806c402e70a53815c30738) | Satya Benson | drm/asahi: m3: T8122: write the HwDataA +0x418c block on 14.8.3 | Not applicable — G15; `drivers/gpu/drm/asahi/m3/mod.rs` | V | -| [8730d3dce2b7](https://github.com/aurora-silicon/linux/commit/8730d3dce2b7e8d9f05ad437c4cf89169e0c5b78), [453d66a437b0](https://github.com/aurora-silicon/linux/commit/453d66a437b02027ad0b6fb194242dd29bb0d31d) | Chris Kearney | pmdomain: apple: pmp-report: add the T6031 report | Not applicable — G15; `drivers/pmdomain/apple/pmp-report-test.c` | V | -| [a66386d03830](https://github.com/aurora-silicon/linux/commit/a66386d03830555c976850001c12644921b0a028), [a8e5d3a57a0e](https://github.com/aurora-silicon/linux/commit/a8e5d3a57a0e19360cffa4dc04ae500ba832e0ea) | Marius Gehrmann | pmdomain: apple: pmp-report: Request T8122 devices by soc-device record | Not applicable — G15; `drivers/pmdomain/apple/pmp-report-test.c` | V | -| [3b9bb4563bb8](https://github.com/aurora-silicon/linux/commit/3b9bb4563bb8b9f16761fe5842ff3bb6a09d8661), [c7bbd7faf778](https://github.com/aurora-silicon/linux/commit/c7bbd7faf778be8ab87515e81caf06571e527ad8) | Chris Kearney | pmdomain: apple: pmp-report: start a handed-over T8122 or T6031 PMP | Not applicable — G15; `drivers/pmdomain/apple/pmp-report.c` | V | -| [3157c614a661](https://github.com/aurora-silicon/linux/commit/3157c614a66119b47100a6a8ac1ad9232bacbf81), [2b115cc04222](https://github.com/aurora-silicon/linux/commit/2b115cc04222553f4bcde86a70f5a2f9c8f5d086) | Ryan Murray | pmdomain: apple: pmp-report: document a failed PMP start and its recovery | Not applicable — VERIFY; `drivers/pmdomain/apple/Kconfig` | V | -| [c332c6fbd56a](https://github.com/aurora-silicon/linux/commit/c332c6fbd56adddb1f6d5635b4010a940c780e7e), [54b90aaf82e9](https://github.com/aurora-silicon/linux/commit/54b90aaf82e9aa7241747d747a5e79c46841a2dd) | Ryan Murray | pmdomain: apple: pmp-report: add KUnit fault injection for the PMP start | Not applicable — VERIFY; `drivers/pmdomain/apple/.kunitconfig.apple-pmp-start` | V | -| [7d101f700326](https://github.com/aurora-silicon/linux/commit/7d101f7003268e2e459ed86b07c9bc3ec5a000f2), [ac234af7c851](https://github.com/aurora-silicon/linux/commit/ac234af7c851e08e6da06a4dffeb912786611ed8) | Chris Kearney | drm/asahi: uapi: add the M3 (G15S) runtime numbers | Not applicable — G15 | V | -| [70f4bebd69b0](https://github.com/aurora-silicon/linux/commit/70f4bebd69b070d37022bca55228879bb7ec4e32), [577249de3221](https://github.com/aurora-silicon/linux/commit/577249de322139ceb84aea9daffcf54d437da52b) | Eryk Wieliczko | drm/asahi: uapi: add the J613 25G83 runtime numbers | Not applicable — G15 | V | -| [f3de3ac043ac](https://github.com/aurora-silicon/linux/commit/f3de3ac043acd22bf4ded712f2999b5693d824ae), [744d0129b6c0](https://github.com/aurora-silicon/linux/commit/744d0129b6c008708c2d9d019ca0a95ee1c04874) | Ryan Murray | drm/asahi: reject timestamp copies on M1 and M2 | Not applicable — LEGACY; `drivers/gpu/drm/asahi/queue/mod.rs` | V | -| [d2cdf2ff6b35](https://github.com/aurora-silicon/linux/commit/d2cdf2ff6b353a72f5f33239a4a7f2b7d87e8cf4), [1e52a05edada](https://github.com/aurora-silicon/linux/commit/1e52a05edadad288cfc17120f37c721f506abcd5) | Chris Kearney | gpu: preserve compute overrides and limit automatic preemption to M2 Max | Not applicable — LEGACY; `drivers/gpu/drm/asahi/asahi_core.rs` | V | -| [a22a6bfc2fa0](https://github.com/aurora-silicon/linux/commit/a22a6bfc2fa049f249effd677a512d682870b171) | Ryan Murray | rust: drm: document Aurora ownership and simplify pointer conversions | Not applicable — VERIFY; `rust/kernel/drm/gpuvm/mod.rs` | V | -| [e8f94ff7af1c](https://github.com/aurora-silicon/linux/commit/e8f94ff7af1cd4104091ac851109fdae946aa585) | Ryan Murray | arm64: dts: apple: j700: Use the raw xHCI SuperSpeed port number | Not applicable — PERIPH | V | -| [58d75c388d55](https://github.com/aurora-silicon/linux/commit/58d75c388d55030f432e93f42ff8871ffe9390f3) | Chris Kearney | soc: apple: opt native T6030 GPUs into the admitted PMP supplier [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/pmdomain/apple/pmp-report.c` | V | -| [19538d922267](https://github.com/aurora-silicon/linux/commit/19538d9222679bc5ff3f17da845a10f60591e82c) | Chris Kearney | pmdomain: apple: read readiness from the passive T6030 report [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/pmdomain/apple/pmp-report.c` | V | -| [1633fb96515e](https://github.com/aurora-silicon/linux/commit/1633fb96515e3b733a0e3514e17f841ef344ab4c) | Eryk Wieliczko | drm/asahi: g15: Add the UAPI glue and register the G15 generation [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [4d6d40767ae2](https://github.com/aurora-silicon/linux/commit/4d6d40767ae2a1cdbb697d3471dbb2c4a7ef9f9d) | Naeem Malik | drm/asahi: g15: Add the T6031 (M3 Max, G15C) configuration row [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [99a4031d5828](https://github.com/aurora-silicon/linux/commit/99a4031d58282e9d2d0f9211b3ba50547d4fc643) | Naeem Malik | drm/asahi: g15: Pin the J516C GPU firmware build [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/hw/t6031.rs` | V | -| [4abf7048277d](https://github.com/aurora-silicon/linux/commit/4abf7048277dd6ec8364811002adeafe326046d6) | Naeem Malik | drm/asahi: g15: Build the J516C initdata from its board images [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board.rs` | V | -| [5fc412af6085](https://github.com/aurora-silicon/linux/commit/5fc412af608586b6beb6a567544f3440f42fe7eb) | Naeem Malik | drm/asahi: g15: Encode compute commands with the G15C register values [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/hw/t6031.rs` | V | -| [377ce9d4f32a](https://github.com/aurora-silicon/linux/commit/377ce9d4f32a42a3b87e0885f48777140c4a2488) | Naeem Malik | drm/asahi: g15: Admit and map UAT regions that are reserved System RAM [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [3a5c855a7219](https://github.com/aurora-silicon/linux/commit/3a5c855a7219aaf45d18a3449bfd4a263ed781c2) | Naeem Malik | drm/asahi: g15: Accept the J516C 14.8 GPU firmware build [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/hw/t6031.rs` | V | -| [f0d7c15b4769](https://github.com/aurora-silicon/linux/commit/f0d7c15b47696e3bbf168f1c8bce9c4817ea28da) | DjDeveloperr | drm/asahi: g15: Reject a scissor base that overflows the address space [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/command.rs` | V | -| [2510cc337f15](https://github.com/aurora-silicon/linux/commit/2510cc337f1551b53e9de38b5c69d6d365e373f3) | DjDeveloperr | drm/asahi: g15: Do not fail a published prefix on a group allocation failure [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/engine.rs` | V | -| [5a592f22b23a](https://github.com/aurora-silicon/linux/commit/5a592f22b23a83ec106b50d5f9ec88f9d885e980) | DjDeveloperr | drm/asahi: g15: Release a closed VM's state when its handle goes [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/mod.rs` | V | -| [e2b962c42e40](https://github.com/aurora-silicon/linux/commit/e2b962c42e40c5ee92b81495436c11b5832d056c) | DjDeveloperr | drm/asahi: g15: Release the power hold and the PMP vote when a start fails early [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/boot.rs` | V | -| [c4d01d363c1d](https://github.com/aurora-silicon/linux/commit/c4d01d363c1d25c33fee168114f369288e24e55d) | DjDeveloperr | drm/asahi: g15: Only mark used pass slots dirty on release [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/slots.rs` | V | -| [35bbcb1bca7a](https://github.com/aurora-silicon/linux/commit/35bbcb1bca7a9dac71f9785aed900d4cf6665d9f) | DjDeveloperr | tools/asahi: Drop the removed T6031 knobs from the M3 runtime tests [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/glue.c` | V | -| [f6da2c8fd38a](https://github.com/aurora-silicon/linux/commit/f6da2c8fd38a75723a7569ff6046d08572900559) | Chris Kearney | drm/asahi-m3: adapt the native G15 driver to the 7.2 driver core and DRM device API [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [42f91c2f9eae](https://github.com/aurora-silicon/linux/commit/42f91c2f9eae615bc12335e37f2016ec09398f63) | Naeem Malik | drm/asahi: g15: Say what to report when the GPU firmware build is unknown [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/identity.rs` | V | -| [f3b867b04c1a](https://github.com/aurora-silicon/linux/commit/f3b867b04c1a50f46d034844754e39f8031ffae3) | Naeem Malik | drm/asahi: g15: Move the board template fill into a core-only submodule [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board.rs` | V | -| [7375309d764f](https://github.com/aurora-silicon/linux/commit/7375309d764f899d8eb4328e30447ec2959efa02) | Naeem Malik | drm/asahi: g15: t6031: Build Globals and Power from the device tree [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board.rs` | V | -| [b840b9944ad9](https://github.com/aurora-silicon/linux/commit/b840b9944ad9e171cf5b13b4e0e0fe8d018778c9) | Naeem Malik | drm/asahi: g15: board: Review fixes for the device-tree Globals and Power [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board/words.rs` | V | -| [3f02f6c358ab](https://github.com/aurora-silicon/linux/commit/3f02f6c358abd1630f1342cbd4dbca755c78023c) | Naeem Malik | drm/asahi: g15: t6031: Build the hardware record from the device tree [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [f1f5a81b756f](https://github.com/aurora-silicon/linux/commit/f1f5a81b756f99b30baefcd967a924167b2a0c12) | Naeem Malik | drm/asahi: t6031: take the idle standby time from the GPU node [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/hw.rs` | V | -| [de646267a725](https://github.com/aurora-silicon/linux/commit/de646267a725f94ea67864c2695eb1082f60dc33) | Chris Kearney | drm/asahi: g15: t6031: refuse board-data values that do not fit in u32 [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [a9a0e4be0546](https://github.com/aurora-silicon/linux/commit/a9a0e4be0546ee7876924cee8e3478727f89cb41) | Chris Kearney | selftests: asahi-g15: run the T6031 board-data and firmware-lookup tests [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board/record.rs` | V | -| [0b06992d812c](https://github.com/aurora-silicon/linux/commit/0b06992d812ce75667740514a5a472fc8d0e091b) | Chris Kearney | drm/asahi: g15: t6031: test that no GPU node value panics the record builder [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board/record.rs` | V | -| [68b780fc7ced](https://github.com/aurora-silicon/linux/commit/68b780fc7ced9e39a5d4573993564ebda26f3649) | Naeem Malik | drm/asahi: g15: Read back the GPU's performance state in debugfs [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board.rs` | V | -| [cd970562fa97](https://github.com/aurora-silicon/linux/commit/cd970562fa979059c6dea0e7f0a7f9df63c3b1c7) | Naeem Malik | drm/asahi: g15: t6031: Leave the 42 record words the firmware does not need zero [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board/record.rs` | V | -| [2a0319927108](https://github.com/aurora-silicon/linux/commit/2a0319927108ee823a82bb1884d2cc6512b515bb) | Chris Kearney | drm/asahi: g15: m3: complete the stats record loads before consuming them [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/channel.rs` | V | -| [73047c7ee59e](https://github.com/aurora-silicon/linux/commit/73047c7ee59e45b8d16e8ec308fb15683caefc6e) | Naeem Malik | drm/asahi: g15: Seed the compute UMA freelist with every pool [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/fw/graph.rs` | V | -| [345f1d8467a4](https://github.com/aurora-silicon/linux/commit/345f1d8467a46f679eb2f2fc2852adb844911033) | Naeem Malik | drm/asahi: g15: Leave PB growth requests unanswered after two refusals at the maximum [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/params.rs` | V | -| [bd0201fad2e0](https://github.com/aurora-silicon/linux/commit/bd0201fad2e02429de6e265c51a223e4209920fe) | Naeem Malik | drm/asahi: g15: Keep PB blocks above the firmware's growth maximum for partial renders [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/params.rs` | V | -| [ff0d1cd692b8](https://github.com/aurora-silicon/linux/commit/ff0d1cd692b838934972a646fa7d1411c54b4864) | Naeem Malik | drm/asahi: g15: Map a 512 MiB parameter buffer heap [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/fw/buffer.rs` | V | -| [e1cdc12eeb97](https://github.com/aurora-silicon/linux/commit/e1cdc12eeb97fc9f4da88343054e6a964e8d2e40) | Chris Kearney | drm/asahi: g15: m3: keep every PB ledger below the block list's K [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/pools.rs` | V | -| [b1adafb49e1c](https://github.com/aurora-silicon/linux/commit/b1adafb49e1c49b71221f7c069dde6045ccce32c) | Chris Kearney | drm/asahi: g15: m3: say what a PB refusal does and size the heap right [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/fw/buffer.rs` | V | -| [3ea5cb6af82b](https://github.com/aurora-silicon/linux/commit/3ea5cb6af82bda7fca665b0902b22275ae02d996) | Chris Kearney | drm/asahi: g15: m3: check firmware-object backing geometry with checked arithmetic [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/object.rs` | V | -| [1eced02cd6c3](https://github.com/aurora-silicon/linux/commit/1eced02cd6c3efe9c43cfc9cf0993ee427e849b9) | Chris Kearney | drm/asahi: g15: m3: map the PB backing into each VM when it first runs [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/engine.rs` | V | -| [73b9ade12e01](https://github.com/aurora-silicon/linux/commit/73b9ade12e0123ef2168abd7eb4969d6865622a3) | Chris Kearney | drm/asahi: g15: m3: back the PB on demand, before an answer posts it [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/pools.rs` | V | -| [716d2fbe9254](https://github.com/aurora-silicon/linux/commit/716d2fbe9254f5ba13a8bd6a6ac687f5904a2f8a) | Chris Kearney | drm/asahi: adapt retained-G15 hooks to the maintained shared APIs [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/file.rs` | V | -| [a4000925920a](https://github.com/aurora-silicon/linux/commit/a4000925920a0e338e0bfa2b726f3b4de90b8cd7) | Chris Kearney | drm/asahi: port the native G15 adapter onto maintained DRM registration [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/Kconfig` | V | -| [23ae3eaf8377](https://github.com/aurora-silicon/linux/commit/23ae3eaf8377dbbd5c51541d77fb4a542fdb384b) | Chris Kearney | drm/asahi: g15: allocate driver data before touching firmware [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/mod.rs` | V | -| [a8289266db94](https://github.com/aurora-silicon/linux/commit/a8289266db94cf7069ab26420bd9d6b60a92dce6) | Chris Kearney | drm/asahi: g15: defer firmware start until module registration completes [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/asahi_core.rs` | V | -| [bc962412f16e](https://github.com/aurora-silicon/linux/commit/bc962412f16e1ca6d93ababf971c68011294c5e3) | Chris Kearney | drm/asahi: g15: make maintained loader contracts independent of SF profiles [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [6c6f0e62156c](https://github.com/aurora-silicon/linux/commit/6c6f0e62156cd9e35f5db47af226dd9821a26b0f) | Chris Kearney | drm/asahi: use the native private wire in G15 command consumers [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/boot.rs` | V | -| [627c501db65e](https://github.com/aurora-silicon/linux/commit/627c501db65ed9bbe22e853f37f247dc579db4af) | Chris Kearney | drm/asahi: isolate the native G15 command ABI behind a private facade [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/wire.rs` | V | -| [9d5c0ee71512](https://github.com/aurora-silicon/linux/commit/9d5c0ee715129fda8cbb8a1420315cf6a7d25cc4) | Chris Kearney | drm/asahi: g15: bound device-wide live logical queue capacity [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/mod.rs` | V | -| [4f6aba6a3598](https://github.com/aurora-silicon/linux/commit/4f6aba6a35980bf152ce5803d7bb5940a2cb11a2) | Chris Kearney | pmdomain: apple: pmgr-pwrstate: Test apple,no-auto-pm on power on and off [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — VERIFY; `drivers/pmdomain/apple/Kconfig` | V | -| [b9d3cf70f1e8](https://github.com/aurora-silicon/linux/commit/b9d3cf70f1e8b488a9ad032dadad7cbe432e164c) | Chris Kearney | drm/asahi: export a T6030 module alias for the native G15 driver [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/mod.rs` | V | -| [af2c5c09ba9f](https://github.com/aurora-silicon/linux/commit/af2c5c09ba9fae7fbf9f165fc6aad73e9aadce0b) | Chris K | pmdomain: apple: restore gated T6030 managed PMP startup [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/pmdomain/apple/pmp-report.c` | V | -| [2a182741b7f7](https://github.com/aurora-silicon/linux/commit/2a182741b7f7d80a7a743eafbf57bd9dbca3c6b4) | Chris Kearney | test: exercise the actual T6030 halted-PMP consumer graph [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/pmdomain/apple/Kconfig` | V | -| [70f41a7944ee](https://github.com/aurora-silicon/linux/commit/70f41a7944eeaf9afdd63f9246ebc5bc41df23f1) | Chris Kearney | drm/apple: admit T6030 G15 only after native display registration [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/apple/apple_drv.c` | V | -| [9632ccd283f9](https://github.com/aurora-silicon/linux/commit/9632ccd283f96ad98321238b6da4718b62f7671a) | Chris Kearney | drm/asahi: require a callable native display provider for G15 [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/Kconfig` | V | -| [e9d92ce6a5c2](https://github.com/aurora-silicon/linux/commit/e9d92ce6a5c27b36266de99d252db029476cb3f1) | Chris Kearney | drm/asahi: retain live G15 storage after allocation failures [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/boot.rs` | V | -| [fc13d05b1db9](https://github.com/aurora-silicon/linux/commit/fc13d05b1db9515fa9481d1362ff530fbeb01ca4) | DjDeveloperr | drm/asahi: g15: adapt the native G15 backend to the Linux 7.3 Rust APIs [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/boot.rs` | V | -| [0ffd22188c3d](https://github.com/aurora-silicon/linux/commit/0ffd22188c3dbb2e8bb2df216ee8e03d71e14bfb) | Ryan Murray | drm/asahi: Keep refusing HIGH queue priority on G13 and G14 [#399](https://github.com/aurora-silicon/linux/pull/399) | Not applicable — LEGACY; `drivers/gpu/drm/asahi/file.rs` | V | -| [1fac0605f061](https://github.com/aurora-silicon/linux/commit/1fac0605f061ce757917781940a5e0aec1225019) | Eryk Wieliczko | soc: apple: rtkit-helper: preserve the inherited J713 input session | Not applicable — G16; `drivers/soc/apple/rtkit-helper.c` | V | -| [751b9e08ca3d](https://github.com/aurora-silicon/linux/commit/751b9e08ca3d8fa673927984d45b22697cc26edf) | Eryk Wieliczko | iommu: apple-dart: retain J713 input and radio ownership [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/iommu/apple-dart.c` | V | -| [939a993d46dd](https://github.com/aurora-silicon/linux/commit/939a993d46dd36392155cc05f692472d2d1c881e) | Eryk Wieliczko | pmdomain: apple: pmc: support T8132 floor requests [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/pmdomain/apple/pmc-test.c` | V | -| [c26dfe75ac9b](https://github.com/aurora-silicon/linux/commit/c26dfe75ac9be0fb75dfe937a15246b4e12bc84a) | Eryk Wieliczko | soc: apple: clpc: retain qualified T8132 memory floors | Not applicable — G16; `drivers/soc/apple/clpc.c` | V | -| [15e0eb00b83b](https://github.com/aurora-silicon/linux/commit/15e0eb00b83b783d7fca9720530942020722cd6a) | Eryk Wieliczko | soc: apple: mcc: support the T8132 memory controller | Not applicable — G16; `drivers/soc/apple/mcc.c` | V | -| [df3e4970e686](https://github.com/aurora-silicon/linux/commit/df3e4970e68677d56eca3e9e9608c338abe52cdd) | Eryk Wieliczko | soc: apple: pmp: publish owner-managed T8132 telemetry [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/pmdomain/apple/pmp-report.c` | V | -| [f1b75932e61d](https://github.com/aurora-silicon/linux/commit/f1b75932e61d7d193801a7f22ea628cb94d9dd56) | Eryk Wieliczko | cpufreq: apple: track T8132 thermal ownership per policy | Not applicable — G16; `drivers/cpufreq/apple-soc-cpufreq.c` | V | -| [1e23ae3aee82](https://github.com/aurora-silicon/linux/commit/1e23ae3aee824c65cbb6d3c94780e44a2e3fc6c2) | Eryk Wieliczko | thermal: apple: add the J713 PMP CPU policy [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/thermal/Kconfig` | V | -| [332eea1e9005](https://github.com/aurora-silicon/linux/commit/332eea1e9005b0cf731a16695c9c87c34e8f13aa) | Eryk Wieliczko | arm64: apple: activate J713 with its PMGR ownership policy [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/pmdomain/apple/pmgr-pwrstate.c` | V | -| [3949e3640d94](https://github.com/aurora-silicon/linux/commit/3949e3640d94d2b5434c84e9e1f6d7b81f650b70) | Eryk Wieliczko | arm64: apple: enable qualified J713 SuperSpeed host support [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/phy/apple/atc.c` | V | -| [0877cd766126](https://github.com/aurora-silicon/linux/commit/0877cd766126503ad02cc11565b85be37517a62c) | Eryk Wieliczko | arm64: apple: enable J713 Bluetooth with scoped radio DMA [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/bluetooth/hci_bcm4377.c` | V | -| [1ae4d49f3592](https://github.com/aurora-silicon/linux/commit/1ae4d49f35921f356d831da974c43dd5fb67f5d7) | Eryk Wieliczko | soc: apple: expose retained PMP display and GPU ownership [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/pmdomain/apple/pmp-report.c` | V | -| [a5f2ee806da2](https://github.com/aurora-silicon/linux/commit/a5f2ee806da2931b10d69044e4a40609d4924201) | Eryk Wieliczko | thermal: apple: integrate J713 measured-rail GPU budgets [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/thermal/Kconfig` | V | -| [52d846f6b8d3](https://github.com/aurora-silicon/linux/commit/52d846f6b8d3664ea6135a660c0b3ece39937209) | Eryk Wieliczko | iommu/apple-dart: adopt J713 display streams with retained ownership [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/iommu/Kconfig` | V | -| [24f67337c9d5](https://github.com/aurora-silicon/linux/commit/24f67337c9d586100ca4a4f438e83310644c1903) | Eryk Wieliczko | drm/asahi: add the T8132 G16 firmware backend [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/gpu/drm/asahi/Kconfig` | V | -| [fb96882f6cb4](https://github.com/aurora-silicon/linux/commit/fb96882f6cb4ce464fcf3f8b3f27f0c3eba891ed) | Ryan Murray | soc: apple: rtkit-helper: Keep serving buffer requests on T8140 adopted sessions | Not applicable — PERIPH; `drivers/soc/apple/rtkit-helper.c` | V | -| [4d88194af46e](https://github.com/aurora-silicon/linux/commit/4d88194af46e4eec12e57c3e7ff8bbcf7ac5b856) | Ryan Murray | pmdomain: apple: pmgr-pwrstate: Honour apple,inherited-on only on T8132 [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/pmdomain/apple/pmgr-pwrstate.c` | V | -| [d14b566cc309](https://github.com/aurora-silicon/linux/commit/d14b566cc309cf6840199c6394dc8f5f75f82f54) | Ryan Murray | drm/asahi: g17: describe the 25G83 barrier and parameter block plainly [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/buffer/target.rs` | V | -| [f0f00dca4b09](https://github.com/aurora-silicon/linux/commit/f0f00dca4b09c9caf6f379928827e0d10451c66b) | Ryan Murray | drm/asahi: mem: document that page-by-page invalidation is global [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/mem.rs` | V | -| [8eacef90ff89](https://github.com/aurora-silicon/linux/commit/8eacef90ff8952b6fc75a85cb20abce488bcd4ed) | Erik Bourget | drm/asahi: g16: accept the 8-core J713 loaded 25G83 image [#442](https://github.com/aurora-silicon/linux/pull/442) | Not applicable — G16; `drivers/gpu/drm/asahi/g16/hw.rs` | V | -| [da42c7cf4fc8](https://github.com/aurora-silicon/linux/commit/da42c7cf4fc83e68261f1c238b2a3b870f94a128) | Ryan Murray | drm/asahi: test shared firmware identity normalization [#428](https://github.com/aurora-silicon/linux/pull/428) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/fwid.rs` | V | -| [b11a5e9e8cd8](https://github.com/aurora-silicon/linux/commit/b11a5e9e8cd83d4ac3ac40bc620de254b095c75d) | DjDeveloperr | cpufreq: apple: verify T8140 transitions on the next request [#443](https://github.com/aurora-silicon/linux/pull/443) | Not applicable — LAZY; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I | -| [e2a2d8ecbb24](https://github.com/aurora-silicon/linux/commit/e2a2d8ecbb24146ff61e1649ff503f234e846b30) | DjDeveloperr | cpufreq: apple: verify T8140 fast-switch requests from a timer [#443](https://github.com/aurora-silicon/linux/pull/443) | Not applicable — LAZY; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I | -| [b7ea3ca9de07](https://github.com/aurora-silicon/linux/commit/b7ea3ca9de073d66f0e031013b7853c3e5702479) | DjDeveloperr | cpufreq: apple: settle T8140 lazy requests before suspend [#443](https://github.com/aurora-silicon/linux/pull/443) | Not applicable — LAZY; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I | -| [6f5d208b4ce0](https://github.com/aurora-silicon/linux/commit/6f5d208b4ce01ff8cfea04fa21f14ac9a7cb610c) | DjDeveloperr | cpufreq: apple: apply a lowered T8140 fast die limit at once [#443](https://github.com/aurora-silicon/linux/pull/443) | Not applicable — LAZY; `drivers/cpufreq/apple-soc-cpufreq.c` | P | -| [b884471f5b13](https://github.com/aurora-silicon/linux/commit/b884471f5b13e62de9105bb0f06362fe01663a75) | Ryan Murray | thermal: apple-smc-cpu-thermal: walk the OPP table by die temperature | Not applicable — OLDTHERMAL; `drivers/thermal/apple-smc-cpu-thermal.c` | P | -| [ca1dab3dde89](https://github.com/aurora-silicon/linux/commit/ca1dab3dde89c57cc0b111fd096478241e6565e5) | Ryan Murray | cpufreq: apple-soc: Drop the SMC CPU thermal policy hooks | Not applicable — OLDTHERMAL; `drivers/cpufreq/apple-soc-cpufreq.c` | P | -| [52006c8e0bc5](https://github.com/aurora-silicon/linux/commit/52006c8e0bc5750331643c2f36ebad06ef300079) | Ryan Murray | thermal: Remove the Apple SMC CPU thermal policy [#43](https://github.com/aurora-silicon/linux/pull/43) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — OLDTHERMAL; `drivers/thermal/Kconfig` | P | -| [1ce75ee9e797](https://github.com/aurora-silicon/linux/commit/1ce75ee9e797c296f742abf955764fa00b77e03d) | Ryan Murray | treewide: apple: t8140: Describe observed behaviour, not other implementations | Not applicable — VERIFY; `drivers/media/platform/apple/isp/isp-cam.c` | V | -| [3b0af1da96c2](https://github.com/aurora-silicon/linux/commit/3b0af1da96c28777073ebf99d65f1498a5f9fe94) | Ace | PCI: apple: enable bounded J700 endpoint bootstrap and enumeration | Not applicable — PERIPH; `drivers/pci/controller/Kconfig` | V | -| [e179042ff067](https://github.com/aurora-silicon/linux/commit/e179042ff0673c4b5adc749cb0fc3fcb0f909106) | Acelogic | HID: dockchannel: support firmware-managed M5 trackpad power | Not applicable — OTHERCHIP; `drivers/hid/dockchannel-hid/dockchannel-hid.c` | V | -| [f19bcf1a1e37](https://github.com/aurora-silicon/linux/commit/f19bcf1a1e373fb5bae2c9a5a0153d7820b13645) | Joshua Warren | drm/asahi: stats: Add StatsSnapshot and firmware-stats decoder [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/stats.rs` | T | -| [72d21d654534](https://github.com/aurora-silicon/linux/commit/72d21d654534decaecc58af0f8fc813064e6f500) | Joshua Warren | drm/asahi: Wire StatsSnapshot into StatsChannel and GpuManager [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [e8c789f9f77b](https://github.com/aurora-silicon/linux/commit/e8c789f9f77baf73f21857ca29a527930ed12aab) | Joshua Warren | drm/asahi: Add sysfs shim for agx_stats [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/Makefile` | T | -| [1b02b0b40af3](https://github.com/aurora-silicon/linux/commit/1b02b0b40af3822e16b5842e21964be40a42025f) | Joshua Warren | drm/asahi: Register agx_stats sysfs file on probe and unregister on drop [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/driver.rs` | T | -| [742f54c4855d](https://github.com/aurora-silicon/linux/commit/742f54c4855d0e3b4db54da4663d421f63d1165a) | Joshua Warren | drm/asahi: count completed submissions in agx_stats jobs [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/gpu.rs` | T | -| [bbfb96f309c8](https://github.com/aurora-silicon/linux/commit/bbfb96f309c8dd264540281469bba6c4a48ee789) | Joshua Warren | drm/asahi: link the sysfs shim into the driver module correctly [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/Makefile` | T | -| [01d19b8a4f55](https://github.com/aurora-silicon/linux/commit/01d19b8a4f55bb202b5c9d85a36996a90537602c) | Joshua Warren | drm/asahi: propagate the stats snapshot allocation result [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/gpu.rs` | T | -| [91c24dc11b09](https://github.com/aurora-silicon/linux/commit/91c24dc11b093be4868234ac2e00eed670d1e741) | Joshua Warren | drm/asahi: decode the stats messages where StatsMsg is nameable [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [dbc8b48aeb06](https://github.com/aurora-silicon/linux/commit/dbc8b48aeb06f85c9e7f9b63be9db7afef074580) | Joshua Warren | drm/asahi: qualify the versioned StatsMsg variant patterns [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [4189501b643f](https://github.com/aurora-silicon/linux/commit/4189501b643f404faa0ea37fc3bb379226300aa9) | Joshua Warren | drm/asahi: fix the agx_stats readout layout and the off-arm string [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/driver.rs` | T | -| [0b923fb29c84](https://github.com/aurora-silicon/linux/commit/0b923fb29c840b9bb675ba8ad9e81c513903b516) | Joshua Warren | drm/asahi: integrate utilization-weighted time into agx_stats busy_ns [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [9250872b1f33](https://github.com/aurora-silicon/linux/commit/9250872b1f33f357c01ccd3bf79be7835fc5c982) | Joshua Warren | drm/asahi: convert stats timestamps from base-clock ticks to ns [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [993288b37ec4](https://github.com/aurora-silicon/linux/commit/993288b37ec4368bbf2debbbd73124d8a2652410) | Joshua Warren | drm/asahi: split the tick window to avoid 128-bit division [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [9aebc2952fb5](https://github.com/aurora-silicon/linux/commit/9aebc2952fb51f6b0b9c03222109fe7f0ac107c2) | Ryan Murray | arm64: dts: apple: retain the T8140 P-cluster domain cells [#179](https://github.com/aurora-silicon/linux/pull/179) | Not applicable — BOARD | B | -| [e3163ca622d6](https://github.com/aurora-silicon/linux/commit/e3163ca622d6c55979d963929edbdf47f2c4c38c) | Ryan Murray | soc: apple: expose the T8140 PMP DVFS report for diagnosis [#182](https://github.com/aurora-silicon/linux/pull/182) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — RAWDIAG; `drivers/pmdomain/apple/pmp-report.c` | O | -| [14e101ee2b8b](https://github.com/aurora-silicon/linux/commit/14e101ee2b8b599cf627015368e16ff8b3d2b95f) | Ryan Murray | cpufreq: apple: retain the unmanaged T8152 P-state ceiling | Not applicable — OTHERCHIP; `drivers/cpufreq/apple-soc-cpufreq.c` | V | -| [19d6664ea33a](https://github.com/aurora-silicon/linux/commit/19d6664ea33affcceef42d5deef488ce1ba7d50d) | Ryan Murray | arm64: dts: apple: retain a single J700 PMP alias | Not applicable — BOARD | B | -| [98038492dc48](https://github.com/aurora-silicon/linux/commit/98038492dc481d784c76fb2c52f3dd030dfad8f5) | Ryan Murray | drm: apple: recognize the T8140 external binding in the display master | Not applicable — BOARD; `drivers/gpu/drm/apple/apple_drv.c` | B | -| [78fc11047efa](https://github.com/aurora-silicon/linux/commit/78fc11047efa814a238113c46b4bb07aa7d641fb) | Ryan Murray | arm64: dts: apple: give the external J700 trial its firmware DMA window | Not applicable — PERIPH | V | -| [bc3b8aaa560f](https://github.com/aurora-silicon/linux/commit/bc3b8aaa560f23e069a7ea2d774645ea5fec39cc) | Ryan Murray | arm64: dts: apple: select the second external DCP source on J700 | Not applicable — PERIPH | V | -| [d08fd52e1619](https://github.com/aurora-silicon/linux/commit/d08fd52e161953a481a464716dd68aae85338044) | DjDeveloperr | drm/apple: enable the validated J700 external display profile by default | Not applicable — BOARD; `drivers/gpu/drm/apple/dcp-external-bw.h` | B | -| [01c8fe5e98f4](https://github.com/aurora-silicon/linux/commit/01c8fe5e98f4ab8805957ca3206d6d46a65b62e7) | Ryan Murray | soc: apple: aop: Do not overrun unread entries in the transmit ring [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/soc/apple/aop.rs` | V | -| [02694d65655b](https://github.com/aurora-silicon/linux/commit/02694d65655baae0536d47beef4f0356145069f4) | Ryan Murray | spi: apple-qspi: Resume the controller even if its reset fails [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/spi/spi-apple-qspi.c` | V | -| [033fa5e3c095](https://github.com/aurora-silicon/linux/commit/033fa5e3c0959f772e8464a25b8b93773f39b5b9) | Ryan Murray | soc: apple: aop: Accept a transmit entry at a write pointer of zero [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/soc/apple/aop_ring.rs` | V | -| [0790f8a546fe](https://github.com/aurora-silicon/linux/commit/0790f8a546fea7ae46871d857643568c1b3c0c64) | Ryan Murray | hwmon: macsmc: drop the check for the undefined apple,cpu-thermal-policy [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — PERIPH; `drivers/hwmon/macsmc-hwmon.c` | V | -| [0943ae25f9bd](https://github.com/aurora-silicon/linux/commit/0943ae25f9bd82917a7a4813962d624d22056fd3) | Ryan Murray | HID: dockchannel-hid: Reject unaligned packet lengths before checksumming [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/hid/dockchannel-hid/dockchannel-hid-parser-test.c` | V | -| [0c55425a8157](https://github.com/aurora-silicon/linux/commit/0c55425a8157326aa0bafd20a1c30a0f34af8650) | Ryan Murray | dt-bindings: gpu: apple,agx: Require three cells in apple,firmware-version [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — VERIFY | V | -| [152cc6b4d737](https://github.com/aurora-silicon/linux/commit/152cc6b4d737c3523b56d1c4b0b4cd3928e514b5) | Ryan Murray | spi: apple-qspi: Do not print a banner on probe [#314](https://github.com/aurora-silicon/linux/pull/314) | Not applicable — PERIPH; `drivers/spi/spi-apple-qspi.c` | V | -| [1baee970e0a9](https://github.com/aurora-silicon/linux/commit/1baee970e0a9d5bf0343f72eed61badfc5918159) | Jonathan Goyvaerts | dt-bindings: mailbox: apple,ascwrap-v6: Add the T6040 [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — VERIFY | V | -| [1df5bd529669](https://github.com/aurora-silicon/linux/commit/1df5bd529669987e8804b6ab38dbd1d5175f508d) | Ryan Murray | HID: dockchannel-hid: Test MTP message bounds with KUnit [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY; `drivers/hid/dockchannel-hid/Kconfig` | V | -| [1f7383d5a281](https://github.com/aurora-silicon/linux/commit/1f7383d5a2811b99a9f2950581ec392837bfc469) | DjDeveloperr | rust: check generated layouts and provide corrected private bindgen [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — VERIFY | V | -| [232faf36664c](https://github.com/aurora-silicon/linux/commit/232faf36664c7e23aa9950bc3019dbf6ba534ee8) | Ryan Murray | HID: dockchannel-hid: Keep parser tests in the subsystem menu [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/hid/dockchannel-hid/Kconfig` | V | -| [2d5c7b6bc705](https://github.com/aurora-silicon/linux/commit/2d5c7b6bc705f0ba8eef8f3d1ea23a53d4248eba) | Ryan Murray | ASoC: apple: t8140-aop-audio: Refuse card names that do not fit [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH | V | -| [3006ca1a3835](https://github.com/aurora-silicon/linux/commit/3006ca1a383525a092ad1cbe9c268786292a32de) | Ryan Murray | mfd: macsmc: Test key and fixed-width readers with KUnit [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY; `drivers/mfd/Kconfig` | V | -| [3024185f2efa](https://github.com/aurora-silicon/linux/commit/3024185f2efa34c4ea8ac9eebebf06b921795f0b), [aaea0b3a4fcf](https://github.com/aurora-silicon/linux/commit/aaea0b3a4fcf5cb371b735c6b595a2919a6a4d07) | DjDeveloperr | dt-bindings: power: add Apple PMC voter interface [#212](https://github.com/aurora-silicon/linux/pull/212) [#219](https://github.com/aurora-silicon/linux/pull/219) | Not applicable — VERIFY | V | -| [3132675b256e](https://github.com/aurora-silicon/linux/commit/3132675b256e07ad782280c42c853c63f6d18ef1) | Ryan Murray | selftests: apple-dcp: Run the queue recovery control through the RX drain [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY | V | -| [315f6dc9944d](https://github.com/aurora-silicon/linux/commit/315f6dc9944de65990476dae34079d3e1313d605) | Chris Kearney | soc: apple: mailbox: match the T8122 GPU mailbox without the v4 fallback | Not applicable — G15; `drivers/soc/apple/mailbox.c` | V | -| [3407efe83df6](https://github.com/aurora-silicon/linux/commit/3407efe83df680534e10c0e66ffa36b75cae69ba) | Jonathan Goyvaerts | dt-bindings: soc: apple,t8140-mcc: Add the T6040 MCC [#385](https://github.com/aurora-silicon/linux/pull/385) | Not applicable — VERIFY | V | -| [35d6b26e5c9d](https://github.com/aurora-silicon/linux/commit/35d6b26e5c9d8bf22ce6284bf0594084ffd2dcdf) | Ryan Murray | soc: apple: aop: Test that a wrapped entry is refused below the read pointer [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY; `drivers/soc/apple/aop_ring.rs` | V | -| [4b8d29e13da6](https://github.com/aurora-silicon/linux/commit/4b8d29e13da638bf7ba7f532844c5e368505bf20) | Jonathan Goyvaerts | dt-bindings: gpu: apple,agx: allow a fw-text region on the T6040 [#428](https://github.com/aurora-silicon/linux/pull/428) | Not applicable — VERIFY | V | -| [4c5aad430f62](https://github.com/aurora-silicon/linux/commit/4c5aad430f6283d1d6b3b961a87d1629b397f22f) | DjDeveloperr | dt-bindings: mailbox: apple,mailbox: Add the T8140 GPU mailboxes [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — VERIFY | V | -| [543ac70dce46](https://github.com/aurora-silicon/linux/commit/543ac70dce46b749f1a446cb80d4e63cf08949cd) | Ryan Murray | drm: apple: parser: add KUnit tests for malformed dictionaries [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY; `drivers/gpu/drm/apple/Makefile` | V | -| [5b62d0c81387](https://github.com/aurora-silicon/linux/commit/5b62d0c81387e8d0d68f2a88244eeb7a618f9ec1) | Ryan Murray | mfd: macsmc: Preserve the key output on lookup failure [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/mfd/macsmc.c` | V | -| [5e03e15dae17](https://github.com/aurora-silicon/linux/commit/5e03e15dae1740326b41df4777a5ee4b7502c02e), [94f215eaa642](https://github.com/aurora-silicon/linux/commit/94f215eaa6424e8f077f1447e78e35b3ebeb6542) | DjDeveloperr | dt-bindings: power: apple,t8140-pmp-report: describe report entries [#212](https://github.com/aurora-silicon/linux/pull/212) [#219](https://github.com/aurora-silicon/linux/pull/219) | Not applicable — VERIFY | V | -| [66db357bd614](https://github.com/aurora-silicon/linux/commit/66db357bd614c7f8e25dab080574c31dab6c0ed2) | Ryan Murray | tools/asahi: measure CPU cost of small render submissions [#201](https://github.com/aurora-silicon/linux/pull/201) | Not applicable — VERIFY | V | -| [6e2835ae7bd6](https://github.com/aurora-silicon/linux/commit/6e2835ae7bd6d16570464106bdfb740b6fed27c4) | Naeem Malik | soc: apple: mailbox: match the T6031 GPU mailbox without the v4 fallback | Not applicable — G15; `drivers/soc/apple/mailbox.c` | V | -| [712530b9753f](https://github.com/aurora-silicon/linux/commit/712530b9753fd8692b31382b3e9c6aaaa720ffe0) | Ryan Murray | gpio: macsmc: tidy the J700 pcIO helpers [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/gpio/gpio-macsmc.c` | V | -| [7a6e327251cc](https://github.com/aurora-silicon/linux/commit/7a6e327251cc51d0a483483f0b81dda99a811791) | Ryan Murray | soc: apple: aop: Validate the receive ring before taking entries [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/soc/apple/aop.rs` | V | -| [807cb8976697](https://github.com/aurora-silicon/linux/commit/807cb8976697ff272433278b272444ced7e91d57) | Ryan Murray | hwmon: macsmc: account for temperature channels in one helper [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — PERIPH; `drivers/hwmon/macsmc-hwmon.c` | V | -| [83039e319faf](https://github.com/aurora-silicon/linux/commit/83039e319faf3e49ceabc424c7c69180ac997dfd) | Ryan Murray | dt-bindings: apple: use the canonical SPDX form in PMP, PMC and report bindings [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — VERIFY | V | -| [87314d48cc08](https://github.com/aurora-silicon/linux/commit/87314d48cc080bcf535291dc636f1ec6164a06f9) | Ryan Murray | drm/apple: Test firmware message bounds with KUnit [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY; `drivers/gpu/drm/apple/Kconfig` | V | -| [910327707f85](https://github.com/aurora-silicon/linux/commit/910327707f852c060b5ada81e64a2a4563cb64b4) | Ryan Murray | ASoC: apple: Test T8140 AOP producer reports with KUnit [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY | V | -| [95b26591a1c4](https://github.com/aurora-silicon/linux/commit/95b26591a1c4b446656c3bc8a257a17792917a78) | Ryan Murray | spi: apple: Reword the hardware CS delay comment [#314](https://github.com/aurora-silicon/linux/pull/314) | Not applicable — VERIFY; `drivers/spi/spi-apple.c` | V | -| [966e777fd568](https://github.com/aurora-silicon/linux/commit/966e777fd568565b88c5f8ba4acb36463ae31e47) | Ryan Murray | MAINTAINERS: keep T8140 PMP coverage under Aurora [#179](https://github.com/aurora-silicon/linux/pull/179) | Not applicable — VERIFY | V | -| [a1f9aabbe6a9](https://github.com/aurora-silicon/linux/commit/a1f9aabbe6a9771a4dbf3259bc808713f0daac46) | Ryan Murray | dt-bindings: apple: describe PMP fast-die reporting on T8140 [#179](https://github.com/aurora-silicon/linux/pull/179) | Not applicable — VERIFY | V | -| [a239464d233d](https://github.com/aurora-silicon/linux/commit/a239464d233d2e94b89dea159f298b70e015b6a6) | Ryan Murray | kunit: Add an Apple firmware parser test configuration [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY | V | -| [a27007e6ace3](https://github.com/aurora-silicon/linux/commit/a27007e6ace3815d11c340c25a3ee90cfb2981b0) | Ryan Murray | HID: dockchannel: Log routine interface set-up at debug level [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/hid/dockchannel-hid/dockchannel-hid.c` | V | -| [a494d618f5a9](https://github.com/aurora-silicon/linux/commit/a494d618f5a9af40ae466166176ae36476b4638a) | Ryan Murray | mfd: macsmc: Hold the mutex while decoding key metadata [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/mfd/macsmc.c` | V | -| [b8f892b79561](https://github.com/aurora-silicon/linux/commit/b8f892b79561ea085c0ab2e44368f873f15b9183) | Ryan Murray | soc: apple: aop: Decode ring entry headers without pointer casts [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/soc/apple/aop.rs` | V | -| [ba6eb20e2ed9](https://github.com/aurora-silicon/linux/commit/ba6eb20e2ed9065a2925d0f16ae030acfaeceefe) | Ryan Murray | soc: apple: mailbox: Describe the ASCWrap v6 CPU start and stop in hardware terms | Not applicable — VERIFY; `drivers/soc/apple/mailbox.c` | V | -| [bc7394673cbe](https://github.com/aurora-silicon/linux/commit/bc7394673cbed4ef22971a49926be6070a7312be) | DjDeveloperr | tools: preserve bindgen recipe validation across Python modes [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — VERIFY | V | -| [bd7739d6232e](https://github.com/aurora-silicon/linux/commit/bd7739d6232e818ef7cf30acbcc50d24723e061c) | Ryan Murray | mfd: macsmc: Reject short fixed-width replies [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/mfd/macsmc.c` | V | -| [c49ab96deb3c](https://github.com/aurora-silicon/linux/commit/c49ab96deb3c378015d1db27bf2122c837fd3bc0) | DjDeveloperr | dt-bindings: gpu: apple,agx: Add apple,agx-t8140 [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — VERIFY | V | -| [c9c779d6a2ba](https://github.com/aurora-silicon/linux/commit/c9c779d6a2bae406a9d48b7f733b16fd253730c7) | Jonathan Goyvaerts | dt-bindings: soc: apple,pmp: Add the T6040 PMP [#374](https://github.com/aurora-silicon/linux/pull/374) | Not applicable — VERIFY | V | -| [cbd157ef2a12](https://github.com/aurora-silicon/linux/commit/cbd157ef2a12a46e3caf5367de912a525d8d4874) | Ryan Murray | hwmon: macsmc: keep the channel of a temperature sensor that fails to set up [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — PERIPH; `drivers/hwmon/Kconfig` | V | -| [cf4ce5f41f4b](https://github.com/aurora-silicon/linux/commit/cf4ce5f41f4b86c4084b49ec6585377e16fd53b7) | Chris Kearney | thunderbolt, phy, soc: apple: T6030 USB4/Thunderbolt, Type-C and DP tunnel support | Not applicable — G15; `drivers/iommu/of_iommu.c` | V | -| [d36196335065](https://github.com/aurora-silicon/linux/commit/d36196335065346ef57a323e483002151670320c) | Ryan Murray | arm64: dts: apple: t6040-j616s: Keep the GPU disabled [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — SUPERSEDED | B | -| [d717a601430a](https://github.com/aurora-silicon/linux/commit/d717a601430aea6711ffc7486f5edb16ca7e7f66) | Jonathan Goyvaerts | dt-bindings: gpu: apple,agx: Add apple,agx-t6040 [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — VERIFY | V | -| [d90daf04de84](https://github.com/aurora-silicon/linux/commit/d90daf04de8431f70eed8b590a532f38a6249095) | Ryan Murray | media: apple: isp: Do not trust the batch count when a batch fails [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/media/platform/apple/isp/isp-v4l2.c` | V | -| [d9aface7ea85](https://github.com/aurora-silicon/linux/commit/d9aface7ea8533965e33476631c8dbc44dfeb439) | Ryan Murray | HID: dockchannel: Build the protocol KUnit test only with the driver [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/hid/dockchannel-hid/Kconfig` | V | -| [e65283c42678](https://github.com/aurora-silicon/linux/commit/e65283c426783b12298f72896ef6f0dc33c4222c) | Ryan Murray | ASoC: apple: t8140-aop-audio: Let power request sequences wrap [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH | V | -| [e666e50ccfe8](https://github.com/aurora-silicon/linux/commit/e666e50ccfe8c58e8fa72bdf7ef6bedffec6551a) | Ryan Murray | rtc: macsmc: correct the comment on the whole-second offset [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — PERIPH; `drivers/rtc/rtc-macsmc.c` | V | -| [e99a6adbeba7](https://github.com/aurora-silicon/linux/commit/e99a6adbeba77b7ed032ef61f864afb3da8fe3a9) | Ryan Murray | dt-bindings: hwmon: apple,smc-hwmon: drop apple,cpu-thermal-policy [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — VERIFY | V | -| [ec34fb1f2835](https://github.com/aurora-silicon/linux/commit/ec34fb1f2835b291f978bd091ed73347cba7ceae) | Ryan Murray | mfd: macsmc: Reject out-of-range key indices [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/mfd/macsmc.c` | V | -| [ed0925cdf091](https://github.com/aurora-silicon/linux/commit/ed0925cdf091083ba1efee97bbb288e9c331f812) | Ryan Murray | spi: apple-qspi: Restore the controller configuration after system sleep [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/spi/spi-apple-qspi.c` | V | -| [ee6f48ce60bd](https://github.com/aurora-silicon/linux/commit/ee6f48ce60bdf68d596c4bedd31e35f55cd6bb03) | Ryan Murray | MAINTAINERS: Cover Apple firmware parser tests [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY | V | -| [f3324e0de0e2](https://github.com/aurora-silicon/linux/commit/f3324e0de0e26bd43df402001c2e3f0f16821520) | Jonathan Goyvaerts | dt-bindings: power: apple,pmc: Add the T6040 PMC and CLPC [#385](https://github.com/aurora-silicon/linux/pull/385) | Not applicable — VERIFY | V | -| [f52e01d6925d](https://github.com/aurora-silicon/linux/commit/f52e01d6925de5022176c5038ff13cc9ad17559b) | Ryan Murray | dt-bindings: gpu: apple,agx: Match the T8140 register layout [#314](https://github.com/aurora-silicon/linux/pull/314) | Not applicable — VERIFY | V | -| [fdd138bbc722](https://github.com/aurora-silicon/linux/commit/fdd138bbc7228b8b1a232268e2a02cc126b24d95) | Ryan Murray | hwmon: macsmc: move the module help text back to its option [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/hwmon/Kconfig` | V | -| [fec5e40ebade](https://github.com/aurora-silicon/linux/commit/fec5e40ebade9f7cf3684acfbb9d603d5b82127a) | Jonathan Goyvaerts | dt-bindings: power: apple,t8140-pmp-report: Add the T6040 aperture [#374](https://github.com/aurora-silicon/linux/pull/374) | Not applicable — VERIFY | V | -| [ff3ebdbad58c](https://github.com/aurora-silicon/linux/commit/ff3ebdbad58c1c50dadbf9cecd7f67aada516dc1) | Ryan Murray | nvme-apple: Reword two post-M4 handoff comments [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY; `drivers/nvme/host/apple.c` | V | - -### Merge/provenance records - -Parent mechanisms are listed above; no isolated speedup is assigned here. - -| Commits / encountered aliases | Author | Improvement / record | T6040 after ports — evidence key and changed source | Measurement | -| --- | --- | --- | --- | --- | -| [00463d1d4031](https://github.com/aurora-silicon/linux/commit/00463d1d40317155246a13573aeab60ff773b51b), [f566e6098c67](https://github.com/aurora-silicon/linux/commit/f566e6098c676566b02a191eb58e5783fa7bf0b6) | Janne Grunau | Merge branch 'bits/010-soc' into asahi-wip | Not applicable — MERGE | V | -| [80390ef034fc](https://github.com/aurora-silicon/linux/commit/80390ef034fcfaf212674bc53b0a91e596409bcf), [5e35a79dac7f](https://github.com/aurora-silicon/linux/commit/5e35a79dac7f0958af6bd3ae9ea4517d22769cb2) | Janne Grunau | Merge branch 'bits/020-dart' into asahi-wip | Not applicable — MERGE | V | -| [4eea6c6d47ba](https://github.com/aurora-silicon/linux/commit/4eea6c6d47bab3a334b9c1633279c4392e2a4de7), [57710743dc8c](https://github.com/aurora-silicon/linux/commit/57710743dc8c0e9286115f38ad19a298cd36cc50) | Janne Grunau | Merge branch 'bits/030-misc' into asahi-wip | Not applicable — MERGE | V | -| [59f7e8be4e3b](https://github.com/aurora-silicon/linux/commit/59f7e8be4e3b693a96a1dd3b2355aa65dd784b0e), [466efd223bbf](https://github.com/aurora-silicon/linux/commit/466efd223bbf43f9e0f4f7065c67d6d4e97fc04c) | Janne Grunau | Merge branch 'bits/090-spi-hid' into asahi-wip | Not applicable — MERGE | V | -| [2871ed01752e](https://github.com/aurora-silicon/linux/commit/2871ed01752ef74924608f23b5edd7927ae4b71c), [f55090a2d12a](https://github.com/aurora-silicon/linux/commit/f55090a2d12a6fd3dad485a7621392b8f508f8a8) | Janne Grunau | Merge branch 'bits/190-rust' into asahi-wip | Not applicable — MERGE | V | -| [cd36abb1e1d2](https://github.com/aurora-silicon/linux/commit/cd36abb1e1d2bcead322aedaed3cab7cbbab5d4b), [3f3dfd6ef171](https://github.com/aurora-silicon/linux/commit/3f3dfd6ef171f4c3801e1bd8b7c880774e17f1ad) | Janne Grunau | Merge branch 'bits/210-gpu' into asahi-wip | Not applicable — MERGE | V | -| [d6c7409e354f](https://github.com/aurora-silicon/linux/commit/d6c7409e354fee96c74a0aa68c5cbd0cdc0b8d92), [39b401626267](https://github.com/aurora-silicon/linux/commit/39b4016262672c0f87d7e5af835f42b9632dcc6c) | Janne Grunau | Merge branch 'bits/250-aop' into asahi-wip | Not applicable — MERGE | V | -| [072195f87df8](https://github.com/aurora-silicon/linux/commit/072195f87df8ca94580cf5ca0d9a801e5bd217e4), [11ee430b3cf2](https://github.com/aurora-silicon/linux/commit/11ee430b3cf20a6611bea0462335f0ae975a40d7) | Janne Grunau | Merge branch 'bits/500-backports' into asahi-wip | Not applicable — MERGE | V | -| [fe8324184dd8](https://github.com/aurora-silicon/linux/commit/fe8324184dd8c6d3b09a532a9cb6a533c561a324) | Ryan Murray | Merge tag 'v7.3' into unified-7.3/base | Not applicable — MERGE | V | -| [cb8e5e495b88](https://github.com/aurora-silicon/linux/commit/cb8e5e495b88f638c22782136a8721a4f26f4346) | Ryan Murray | Merge branch 'unified/bits/010-soc' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [6de20e534e47](https://github.com/aurora-silicon/linux/commit/6de20e534e473dd9efd9e14c727883df6036d60b) | Ryan Murray | Merge branch 'unified/bits/020-dart' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [15fe1cbe72df](https://github.com/aurora-silicon/linux/commit/15fe1cbe72df8d8eb79b2dec500e58bbc5f57647) | Ryan Murray | Merge branch 'unified/bits/060-power-thermal' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [939cccf33380](https://github.com/aurora-silicon/linux/commit/939cccf333802c32a319f0ddb4b0d01c85aab990) | Ryan Murray | Merge branch 'unified/bits/070-audio' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [2409e9da1efb](https://github.com/aurora-silicon/linux/commit/2409e9da1efb9494fc9437ce9f3bd909c0f7dd36) | Ryan Murray | Merge branch 'unified/bits/100-sep' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [2bc8aa67f178](https://github.com/aurora-silicon/linux/commit/2bc8aa67f17817c22c6bacaecd7ecf4df8e8c63d) | Ryan Murray | Merge branch 'unified/bits/200-dcp' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [c00586c09e2b](https://github.com/aurora-silicon/linux/commit/c00586c09e2bab26f92ddd5b943cbcc66c047ff5) | Ryan Murray | Merge branch 'unified/bits/210-gpu' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [14ca49f98175](https://github.com/aurora-silicon/linux/commit/14ca49f98175b54c37fa16af766e11f163d3a80f) | Ryan Murray | Merge branch 'unified-7.3/bits/010-soc' into unified-7.3/canonical | Not applicable — MERGE | V | -| [665a5ca84508](https://github.com/aurora-silicon/linux/commit/665a5ca845081049335f69d0bf27c66c90898b7b) | Ryan Murray | Merge branch 'unified-7.3/bits/020-dart' into unified-7.3/canonical | Not applicable — MERGE | V | -| [c217f4f47bf0](https://github.com/aurora-silicon/linux/commit/c217f4f47bf003c8fb39400d1af8179b552c497e) | Ryan Murray | Merge branch 'unified-7.3/bits/060-power-thermal' into unified-7.3/canonical | Not applicable — MERGE | V | -| [5bdd6c5b2c80](https://github.com/aurora-silicon/linux/commit/5bdd6c5b2c80a6f16c8835a57a5d56d26af67839) | Ryan Murray | Merge branch 'unified-7.3/bits/070-audio' into unified-7.3/canonical | Not applicable — MERGE | V | -| [f3c8cf25dd5d](https://github.com/aurora-silicon/linux/commit/f3c8cf25dd5d01f3871267c1b77df343dbef045d) | Ryan Murray | Merge branch 'unified-7.3/bits/100-sep' into unified-7.3/canonical | Not applicable — MERGE | V | -| [c15790e20e01](https://github.com/aurora-silicon/linux/commit/c15790e20e01e8562e0b54a00bee8a8ef9ded84b) | Ryan Murray | Merge branch 'unified-7.3/bits/200-dcp' into unified-7.3/canonical | Not applicable — MERGE | V | -| [ea36d4240e40](https://github.com/aurora-silicon/linux/commit/ea36d4240e40fc7607d568a8fa56f1fa5cf01c03) | Ryan Murray | Merge branch 'unified-7.3/bits/210-gpu' into unified-7.3/canonical | Not applicable — MERGE | V | -| [94141d397eae](https://github.com/aurora-silicon/linux/commit/94141d397eaede2ba95eab7279f4bc18f75bb9d1) | Ryan | Merge pull request #374 from jgoyvaerts/m4pro/pmp-t6041 | Not applicable — MERGE | V | -| [4e5eea54ce7e](https://github.com/aurora-silicon/linux/commit/4e5eea54ce7e1c9d21867d81c5e5672e1cbd1c34) | Ryan | Merge pull request #368 from jgoyvaerts/m4pro/small-fixes | Not applicable — MERGE | V | -| [815438428a9e](https://github.com/aurora-silicon/linux/commit/815438428a9e45f0facbb10c4f9bd77047ef7282) | Ryan | Merge pull request #385 from jgoyvaerts/m4pro/pmc-clpc-mcc-t6040 | Not applicable — MERGE | V | -| [49273fd6921c](https://github.com/aurora-silicon/linux/commit/49273fd6921c9b39101cd1ee8c8d2f2ca0153440) | Ryan | Merge pull request #386 from jgoyvaerts/m4pro/apple-dart-t6040 | Not applicable — MERGE | V | -| [50a912fe81fc](https://github.com/aurora-silicon/linux/commit/50a912fe81fcdbd770d231db8eda856a1678c194) | Ryan | Merge pull request #391 from jgoyvaerts/m4pro/g17-generic | Not applicable — MERGE | V | -| [311471f73e99](https://github.com/aurora-silicon/linux/commit/311471f73e9919764bfb24acfe7eeb7c5230795a) | Ryan | Merge pull request #402 from aurora-silicon/j616s/pmp-ep7-20261024 | Not applicable — MERGE | V | -| [1aa2857509d5](https://github.com/aurora-silicon/linux/commit/1aa2857509d50f7f787541280aba7b274721919c) | Ryan | Merge pull request #403 from aurora-silicon/j616s/usb-20261023 | Not applicable — MERGE | V | -| [04231230fd76](https://github.com/aurora-silicon/linux/commit/04231230fd76fadd12a8b44707159f37f0e498b1), [e9a9b647d0f3](https://github.com/aurora-silicon/linux/commit/e9a9b647d0f36e222f16de732f78f2d77ea2d661), [b9a73d410ff4](https://github.com/aurora-silicon/linux/commit/b9a73d410ff48c65624c9283c634b4d06f4dfc6a), [4433181e4eb6](https://github.com/aurora-silicon/linux/commit/4433181e4eb649033f07751001fbb72621752647) | Jonathan Goyvaerts, Ryan Murray | Merge integration/aurora into the T6040 GPU series [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — MERGE | V | -| [2a868cf22d90](https://github.com/aurora-silicon/linux/commit/2a868cf22d90f0de72b2ad3c339b93460fdb9927) | Ryan | Merge pull request #413 from jgoyvaerts/m4pro/g17-robustness | Not applicable — MERGE | V | -| [2e9e457c922d](https://github.com/aurora-silicon/linux/commit/2e9e457c922d799dcc27975ff6f5d114d2719f3f) | Ryan | Merge pull request #418 from aurora-silicon/ryan/g17-innocent-clients-413 | Not applicable — MERGE | V | -| [127df1be31af](https://github.com/aurora-silicon/linux/commit/127df1be31af90613079dcedaeaf0a2aa9ae7d10) | Ryan Murray | Merge integration/aurora into aurora-wip-sync-177 | Not applicable — MERGE | V | -| [e5dad6df06f6](https://github.com/aurora-silicon/linux/commit/e5dad6df06f66b944037770e81e6a481a0b8302f), [d1b62dc403c6](https://github.com/aurora-silicon/linux/commit/d1b62dc403c6f9ed534850f204f069befca149f1) | Ryan Murray | Merge integration/aurora into m4pro/g17-t6040-text-identity [#428](https://github.com/aurora-silicon/linux/pull/428) | Not applicable — MERGE | V | -| [a1b269f79e35](https://github.com/aurora-silicon/linux/commit/a1b269f79e35844660892b9779adb2f68abc38b7) | Ryan | Merge pull request #395: sync omacom #177 (G15, T6030 dock, platform fixes) onto 7.3 | Not applicable — MERGE | V | -| [8bc8f12e95ed](https://github.com/aurora-silicon/linux/commit/8bc8f12e95edbbd5b7d5431973eb1f08c872e87c) | Ryan | Merge pull request #427 from jgoyvaerts/m4pro/asahi-pgtable-checked-borrow | Not applicable — MERGE | V | -| [18012befd69c](https://github.com/aurora-silicon/linux/commit/18012befd69ceed9892c28291132ebd4c05a6076) | Ryan | Merge pull request #428 from jgoyvaerts/m4pro/g17-t6040-text-identity | Not applicable — MERGE | V | -| [41ef596ab373](https://github.com/aurora-silicon/linux/commit/41ef596ab3731ef695fcce2fdfb666bc47da21b7) | Dj | Merge pull request #443 from aurora-silicon/fix/t8140-cpufreq-lazy-verify-20261025 | Not applicable — MERGE | V | -| [af80fbe9094b](https://github.com/aurora-silicon/linux/commit/af80fbe9094b631c5d734883bd259ad0925e88ba) | Dj | Merge pull request #447 from aurora-silicon/fix/aic2-effective-affinity-20261025 | Not applicable — MERGE | V | -| [67fdc27bdadb](https://github.com/aurora-silicon/linux/commit/67fdc27bdadb58520839376a2b85d1265c3fa78f), [b4e5e4cff710](https://github.com/aurora-silicon/linux/commit/b4e5e4cff710c9961a05d4ba6c16f0f8c47c3776) | Chris Kearney | Merge current aurora-wip into the combined Thunderbolt series | Not applicable — MERGE | V | -| [99a554596d0a](https://github.com/aurora-silicon/linux/commit/99a554596d0a4960120b78f9a09ab30ffd4d0fc1) | Chris Kearney | Merge aurora-wip 3bb0a6104a11 into tb-dp-tunnel-t8103 | Not applicable — MERGE | V | -| [5b55206ca89b](https://github.com/aurora-silicon/linux/commit/5b55206ca89bbeb8bb54a208a9b9a36b80d6360b) | Acelogic | Merge M5 CPU support while retaining per-chip frequency safeguards | Not applicable — MERGE | V | -| [95f70d759093](https://github.com/aurora-silicon/linux/commit/95f70d7590935fdfb63c889d73598996dbf6c695) | Ryan Murray | Merge pull request #172 from aurora-silicon/j700-dcp-foundation | Not applicable — MERGE | V | -| [b37df4bdd552](https://github.com/aurora-silicon/linux/commit/b37df4bdd552dca6fa180e7826d0ec22b5e264f4) | Ryan Murray | Merge pull request #8 from iconidentify/tb-dp-tunnel-t8103 | Not applicable — MERGE | V | -| [c9a55efdff8f](https://github.com/aurora-silicon/linux/commit/c9a55efdff8f9505114fab2c89e934ce363e9b3b) | Ryan Murray | Merge pull request #42 from aurora-silicon/feat/sep-neo-rebase | Not applicable — MERGE | V | -| [026b4131cf05](https://github.com/aurora-silicon/linux/commit/026b4131cf0506b0974e6a0ad0b13cfa15f80cc6) | Ryan Murray | Merge pull request #43 from aurora-silicon/feat/j700-thermal-framework-v2 | Not applicable — MERGE | V | -| [e9c631c62252](https://github.com/aurora-silicon/linux/commit/e9c631c6225261125aae251b6a0b743e0663ed37) | Ryan Murray | Merge pull request #46 from aurora-silicon/fix/j414s-dual-dock-dp | Not applicable — MERGE | V | -| [b8fef4b5b0b5](https://github.com/aurora-silicon/linux/commit/b8fef4b5b0b5d1ed5401db1249fc230fc9ce3f60) | Ryan Murray | Merge pull request #156 from aurora-silicon/codex/neo-ave-bringup | Not applicable — MERGE | V | -| [527179cf0856](https://github.com/aurora-silicon/linux/commit/527179cf085663164d17e4d8e8abf2c3e33b5070) | Ryan Murray | Merge pull request #168 from joshuaswarren/agent/jw16-agx-stats4 | Not applicable — MERGE | V | -| [918c0ff6270c](https://github.com/aurora-silicon/linux/commit/918c0ff6270c673e67067453a2e727b5f3e26331) | Ryan Murray | Merge pull request #55 from aurora-silicon/t8140-cpu-capacity | Not applicable — MERGE | V | -| [db4752825c93](https://github.com/aurora-silicon/linux/commit/db4752825c935257fb77f6b8aacf3b4ee003e9fa) | Ryan Murray | Merge pull request #174 from aurora-silicon/j700/t8140-dt-complete | Not applicable — MERGE | V | -| [d8ad51f6b8c8](https://github.com/aurora-silicon/linux/commit/d8ad51f6b8c809444fe4e3f1ef0a1ebb3ba6af5e) | Ryan Murray | Merge pull request #179 from aurora-silicon/j700/pmp-mcc-thermal | Not applicable — MERGE | V | -| [5de43d36cd52](https://github.com/aurora-silicon/linux/commit/5de43d36cd520eaf5df6fc16d047ee413ac54968) | Ryan Murray | Merge pull request #181 from aurora-silicon/j700/t8140-ane-topology | Not applicable — MERGE | V | -| [564976d8e4a6](https://github.com/aurora-silicon/linux/commit/564976d8e4a60dd64a4dc77b2b82f2a0f25f3f45) | Ryan Murray | Merge pull request #182 from aurora-silicon/j700/mcc-telemetry | Not applicable — MERGE | V | -| [4f3a64e7baa9](https://github.com/aurora-silicon/linux/commit/4f3a64e7baa91c6616ae955695e8a5c847dff968) | Ryan | Merge pull request #215 from aurora-silicon/j700/t8140-slc-allocation | Not applicable — MERGE | V | -| [ccedac0c6a30](https://github.com/aurora-silicon/linux/commit/ccedac0c6a30b11b9b1926522a98d4079c9acbf1) | Ryan | Merge pull request #221 from aurora-silicon/j700/display-handoff-race | Not applicable — MERGE | V | -| [123c0d909a8a](https://github.com/aurora-silicon/linux/commit/123c0d909a8af07363e3e885691f0e9feb10c9bc) | Ryan | Merge pull request #223 from aurora-silicon/apple/sashiko-pmp-entry-unbind | Not applicable — MERGE | V | -| [1702229de78f](https://github.com/aurora-silicon/linux/commit/1702229de78f1acd92808b228034839fb7e6c0bc) | Ryan | Merge pull request #232 from aurora-silicon/j700/aop-dart-invalidate | Not applicable — MERGE | V | -| [5c06b1998b8e](https://github.com/aurora-silicon/linux/commit/5c06b1998b8eefdf785b5320a6f8cec31f8da29a) | Ryan | Merge pull request #272 from aurora-silicon/j700/pmgr-failed-power-on | Not applicable — MERGE | V | -| [92ad2a772af8](https://github.com/aurora-silicon/linux/commit/92ad2a772af82a81fc3c73c915a48b9b611db55b) | Ryan Murray | Merge public J700 DP Alt qualification stack into current aurora-wip | Not applicable — MERGE | V | -| [f5afac94ca29](https://github.com/aurora-silicon/linux/commit/f5afac94ca2999c858fb61ebab0bf4b4c168fc6d) | Ryan Murray | drm/apple: compose lean J700 display and automatic recovery candidate | Not applicable — MERGE | V | -| [08e0d0a90be3](https://github.com/aurora-silicon/linux/commit/08e0d0a90be3bb6d777cc1a285ba22bfce12a4d9) | Ryan Murray | drm/apple: integrate reviewed fixed-host lifecycle and scoped boot fixes | Not applicable — MERGE | V | -| [47c99edf4878](https://github.com/aurora-silicon/linux/commit/47c99edf48782ec6078624f579108e243f8cbb4c) | Ryan | Merge pull request #342 from aurora-silicon/cleanup/rust-clippy-20261017 | Not applicable — MERGE | V | -| [3abf4a56b59e](https://github.com/aurora-silicon/linux/commit/3abf4a56b59e323026f9a6e2fe9a0d4307c251d5) | Ryan | Merge pull request #345 from aurora-silicon/fix/harden-all-20261017 | Not applicable — MERGE | V | -| [c20b9d96ba77](https://github.com/aurora-silicon/linux/commit/c20b9d96ba77da9a32c751ab0e63f283d10eea4a) | Ryan Murray | Merge branch 'integration/aurora' into aurora-wip | Not applicable — MERGE | V | -| [8080772b8377](https://github.com/aurora-silicon/linux/commit/8080772b83773a6ca224718de3fdb8bddc1b8511) | Ryan Murray | Merge branch 'integration/aurora' at a1b269f7 into aurora-wip | Not applicable — MERGE | V | -| [42c59170fe98](https://github.com/aurora-silicon/linux/commit/42c59170fe98eb0266c4ca5ea5e1abd0cbac97aa) | Ryan Murray | Merge integration/aurora at 3b77f0f9 into aurora-wip | Not applicable — MERGE | V | -| [1a3c5ca41f8f](https://github.com/aurora-silicon/linux/commit/1a3c5ca41f8f0215a355625ad7c4d456c78f2802) | Ryan Murray | Merge branch 'unified-7.3/bits/170-usb' into unified-7.3/canonical | Not applicable — MERGE | V | -| [2e1656f93c27](https://github.com/aurora-silicon/linux/commit/2e1656f93c27f76171fa265dadcb5ba019bce421) | Ryan Murray | Merge pull request #65 from joshuaswarren/ane-dt-polltx-aurora | Not applicable — MERGE | V | -| [9dbd46baf1b2](https://github.com/aurora-silicon/linux/commit/9dbd46baf1b289a30b5f9be6c4b5f6341135d7ce) | Ryan | Merge pull request #198 from aurora-silicon/fix/pr171-review [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — MERGE | V | -| [f1f334c2ec72](https://github.com/aurora-silicon/linux/commit/f1f334c2ec724b8c96f534a561df9480aa4310ee) | Ryan Murray | Merge branch 'backlog/kunit-parsers-fixes-20261017' into backlog/harden-all-20261017 [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — MERGE | V | - -### Public measured follow-ups outside the audited branch heads - -[#464](https://github.com/aurora-silicon/linux/pull/464), -[#468](https://github.com/aurora-silicon/linux/pull/468) and -[#494](https://github.com/aurora-silicon/linux/pull/494) were also read. Their -heads are not in either pinned branch snapshot; they are not silently counted -as inherited or qualified ports. They remain separate proposals for review: - -- #464 limits the T8140 GPU floor to streams and yields to PMP demand. Its - reported video power is 5.151 to 4.975 W, with light-submit gains retained. - Check the same video/browsing/heavy-load failure modes on g2, including actual - T6040 PMP voter behavior, before accepting its unconditional powered floor. -- #468 reports 7409 to 4625 doorbells in a traced hop, slow hops 19.6% to 13.9%, - and C-d64 13.89 to 13.11 us. Its shared compute-doorbell mechanism would need - no T6040 feature gate; it is an additional unmerged source dependency. -- #494 reports event passes 8.2 to 6.2 us and submit.empty d2 1.78 to 1.69 us. - Its shared event housekeeping change is another unmerged source dependency; - it is not evidence that the audited branches already provide those gains. - -No register, voltage, slot-key address, power curve, module parameter or new -platform option is invented to close an evidence gap. Applicability of dormant -25G83-specific feature/identity paths must come from validated facts; successful -compilation is not that qualification. diff --git a/MAINTAINERS b/MAINTAINERS index 5c8fc89e51d008..514c10af8203ef 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2093,6 +2093,7 @@ F: drivers/soc/apple/pmp.rs F: include/linux/mt7932.h F: include/linux/soc/apple/pmp-report.h F: Documentation/devicetree/bindings/chosen/apple,dcp-rtkit-quiesced.yaml +F: Documentation/devicetree/bindings/chosen/apple,dcp-rtkit-running.yaml F: Documentation/devicetree/bindings/chosen/aurora,ctxr-exec-window.yaml F: Documentation/devicetree/bindings/display/apple,dcp.yaml F: Documentation/devicetree/bindings/display/apple,display-subsystem.yaml @@ -2150,6 +2151,15 @@ F: tools/testing/kunit/configs/mt7932.config F: tools/testing/selftests/drivers/apple/aop-las.py F: tools/testing/selftests/drivers/gpu/apple-dcp/ +APPLE T8152 DCP DISPLAY DRIVER (IBOOT INTERFACE) +M: Thomas Glanzmann +L: dri-devel@lists.freedesktop.org +S: Maintained +F: Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml +F: drivers/gpu/drm/apple/iboot_drm.c +F: drivers/gpu/drm/apple/iomfb_iboot.* +F: drivers/gpu/drm/apple/t8152_* + APPLETALK NETWORK LAYER L: netdev@vger.kernel.org S: Obsolete @@ -2699,6 +2709,7 @@ F: Documentation/devicetree/bindings/dma/apple,sio.yaml F: Documentation/devicetree/bindings/sound/apple,* F: Documentation/devicetree/bindings/sound/cirrus,cs42l84.yaml F: Documentation/devicetree/bindings/sound/trivial-codec.yaml +F: drivers/dma/apple-sio-msg-test.c F: drivers/dma/apple-sio-probe-test.c F: drivers/dma/apple-sio-probe-test.dtso F: drivers/dma/apple-sio-t6030-test.dtso @@ -2774,6 +2785,8 @@ F: Documentation/hwmon/macsmc-hwmon.rst F: Documentation/power/apple-s2idle.rst F: arch/arm64/boot/dts/apple/ F: drivers/bluetooth/hci_bcm4377.c +F: drivers/bluetooth/hci_bcm4377_test.c +F: tools/asahi/bcm4377-completion-tests.py F: tools/asahi/bcm4377-sleep-config-tests.* F: drivers/clk/clk-apple-nco.c F: drivers/cpufreq/apple-soc-cpufreq.c @@ -2801,7 +2814,9 @@ F: drivers/nfc/.kunitconfig F: drivers/nfc/apple-stockholm*.c F: drivers/nvme/host/apple.c F: drivers/nvmem/apple-efuses.c +F: drivers/nvmem/apple-spmi-nvmem-test.c F: drivers/nvmem/apple-spmi-nvmem.c +F: drivers/nvmem/apple-spmi-nvmem.kunitconfig F: drivers/phy/apple/ F: drivers/phy/apple/.kunitconfig.apple-atc F: drivers/pinctrl/pinctrl-apple-gpio.c @@ -2879,6 +2894,7 @@ S: Maintained W: https://aurora-silicon.github.io F: Documentation/devicetree/bindings/media/apple,scaler.yaml F: drivers/media/platform/apple/scaler/ +F: tools/media/apple-scaler/ ARM/ARTPEC MACHINE SUPPORT M: Jesper Nilsson @@ -25635,6 +25651,7 @@ S: Maintained F: drivers/base/property.c F: drivers/base/swnode.c F: drivers/base/test/swnode-devlink-test.c +F: drivers/base/test/swnode-managed-test.c F: include/linux/fwnode.h F: include/linux/property.h diff --git a/README b/README index 010c587224224b..d4019c83f8eef3 100644 --- a/README +++ b/README @@ -1,3 +1,17 @@ +Aurora Silicon +============== + +This tree is the Aurora Silicon kernel for Apple silicon Macs. Work lands on +the `main` branch through pull requests (see CONTRIBUTING.md). RELEASES.md +describes the three GitHub Release channels and when they become available. + +* stable: a `v*` release (https://github.com/aurora-silicon/linux/releases/latest) +* nightly: the `aurora-nightly` prerelease, rebuilt daily when main moved +* edge: the `aurora-edge` prerelease, rebuilt on every push to main + +The release workflow introduces the shared configuration. Once it lands, +build that configuration locally with `make aurora_defconfig asahi.config`. + Linux kernel ============ diff --git a/RELEASES.md b/RELEASES.md new file mode 100644 index 00000000000000..452b986dca79ef --- /dev/null +++ b/RELEASES.md @@ -0,0 +1,102 @@ +# Aurora kernel releases + +This repository has one long-lived branch, `main`. Changes land through pull +requests. [Linux PR 3064](https://github.com/aurora-silicon/linux/pull/3064) +introduces the release workflow and shared kernel configuration. Each channel +becomes available after its first successful publication. + +The organisation-wide rules (branch names, who may tag, the merge gate) are in +[branching-and-releases](https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/branching-and-releases.md); +this file adds the kernel build details. + +## Channels + +| Channel | Where | Built when | Changes? | +| --- | --- | --- | --- | +| stable | the GitHub Release for a `v*` tag, e.g. [`releases/latest`](https://github.com/aurora-silicon/linux/releases/latest) | a `v*` tag is pushed on a `main` commit | never: a stable release is not rebuilt or edited | +| nightly | prerelease tag [`aurora-nightly`](https://github.com/aurora-silicon/linux/releases/tag/aurora-nightly) | once a day, if `main` moved since the last nightly | tag and assets replaced each night | +| edge | prerelease tag [`aurora-edge`](https://github.com/aurora-silicon/linux/releases/tag/aurora-edge) | every push to `main`; a running build always finishes and only the newest waiting push is built next | tag and assets replaced on every build | + +Each release body names its exact source commit, and every asset carries a +build provenance attestation from `kernel-release.yml` +(`gh attestation verify --repo aurora-silicon/linux`). `edge` is +for testing what just merged; `nightly` is the candidate pool for the next +stable tag; `stable` is what distributions ship by default. + +## What a release contains + +For kernel release `` (also in the `kernel.release` asset): + +- `Image-.gz`: the arm64 kernel image +- `modules-.tar.zst`: the `lib/modules/` tree, modules signed +- `dtbs-.tar.zst`: all device trees built by the configuration +- `config-`, `System.map-` +- `module-signing-cert-.der`: the certificate the modules are signed with +- `linux-aurora*-bin-*.pkg.tar.zst`: Arch Linux packages from `make pacman-pkg` +- `source.commit`, `SHA256SUMS` + +The configuration is the fleet configuration: `make aurora_defconfig asahi.config` +(`arch/arm64/configs/aurora_defconfig` plus `asahi.config`), built with the +toolchain versions pinned in the workflow. + +Each build signs its modules with a key generated for that build and deletes +the private key afterwards. Our lab fleet kits are signed separately and are +not published here. + +## Cutting a stable release + +Stable releases are time-boxed. On the release cadence: + +1. Take the commit the current `aurora-nightly` was built from (it is in the + release body), once it has passed the + [lab regression gate](https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/branching-and-releases.md#4-cutting-a-stable-release): + it boots and passes on every gate Mac with no new failures compared with the + previous stable release. The gate looks for regressions only; missing + features do not block a tag. +2. An Owner tags it and pushes the tag (only Owners create `v*` tags, and + nobody moves or deletes one): + + ```sh + git tag -a v0.2.0 -m 'Aurora v0.2.0' + git push origin v0.2.0 + ``` + +3. The workflow builds it and publishes the release with generated notes. + +Versions are `X.Y.Z`: Y goes up for a regular release, Z for a hotfix, and a +new upstream base is at least a minor bump. + +Unfinished work remains in its pull request for a later release. The workflow +accepts stable tags on `main` and the hotfix branches described below. Stable +releases must remain immutable. + +## Hotfixes + +Only a boot failure, data loss, a security problem or a risk of hardware damage +in a stable release justifies a hotfix. Everything else is fixed forward on +`main` and ships in the next release. + +1. Branch `hotfix/v` from the stable tag, fix it there and tag + `v` on that branch. The tag builds and publishes like any stable + release. +2. Forward-port the same commits to `main` through a pull request; each + forward-ported commit carries a `Forward-port: ` trailer naming the + hotfix commit. +3. Delete the hotfix branch once the forward-port is merged. + +Hotfix tags are the one case where a stable tag is not on `main`; the +workflow accepts them only from a `hotfix/` branch. + +## Upstream stable updates + +Upstream stable point releases for the current base (for example 7.3.y) are +merged into `main` weekly through a pull request, and at once when they carry +security fixes. + +## Kernel version upgrades + +Moving to a new upstream version (for example 7.4) happens on one branch, +`rebase/v7.4`, opened as a pull request into `main`. It is built and +fleet-tested like any other change and merged when it passes. `main` is never +rebased in place, and nobody stacks other work on the rebase branch; only fixes +needed for the rebase itself go there. diff --git a/arch/arm64/boot/dts/apple/Makefile b/arch/arm64/boot/dts/apple/Makefile index 25b14626c655b7..256662c18acd6f 100644 --- a/arch/arm64/boot/dts/apple/Makefile +++ b/arch/arm64/boot/dts/apple/Makefile @@ -116,6 +116,7 @@ dtb-$(CONFIG_ARCH_APPLE) += t8112-j413.dtb dtb-$(CONFIG_ARCH_APPLE) += t8112-j413-fw27.dtb dtb-$(CONFIG_ARCH_APPLE) += t8112-j415.dtb dtb-$(CONFIG_ARCH_APPLE) += t8112-j473.dtb +dtb-$(CONFIG_ARCH_APPLE) += t8112-j473-fw27.dtb dtb-$(CONFIG_ARCH_APPLE) += t8112-j493.dtb dtb-$(CONFIG_ARCH_APPLE) += t8122-j433.dtb dtb-$(CONFIG_ARCH_APPLE) += t8122-j434.dtb diff --git a/arch/arm64/boot/dts/apple/t6001-aux-spmi.dtsi b/arch/arm64/boot/dts/apple/t6001-aux-spmi.dtsi index 563c2abd706f88..92ddad6eed9c97 100644 --- a/arch/arm64/boot/dts/apple/t6001-aux-spmi.dtsi +++ b/arch/arm64/boot/dts/apple/t6001-aux-spmi.dtsi @@ -1,20 +1,12 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT -/* Disabled auxiliary SPMI resources; primary polled PMIC access is retained. */ +/* + * Disabled auxiliary SPMI resources; primary polled PMIC access is retained. + * T6001 has the T6000 set plus CLVR SPMI buses 3 and 4. + */ -&{/soc} { - primary_spmi_monitor: spmi-monitor@2920a0e00 { - compatible = "apple,t6000-spmi-monitor", "apple,spmi-monitor"; - reg = <0x2 0x920a0e00 0x0 0x100>, - <0x2 0x920a0400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - apple,controller = <&nub_spmi0>; - interrupt-controller; - #interrupt-cells = <2>; - #address-cells = <0>; - status = "okay"; - }; +#include "t6000-aux-spmi.dtsi" +&{/soc} { clvr_spmi3: spmi@28e519100 { compatible = "apple,t6000-spmi", "apple,spmi"; reg = <0x2 0x8e519100 0x0 0x100>, @@ -53,124 +45,3 @@ }; }; }; - -&pmic1 { - battery_monitor: battery-monitor { - compatible = "apple,t6000-battery-monitor", "apple,battery-monitor"; - interrupt-parent = <&primary_spmi_monitor>; - interrupts = <62 IRQ_TYPE_NONE>; - status = "disabled"; - }; -}; - -&nub_spmi1 { - reg = <0x2 0x920a9300 0x0 0x100>, - <0x2 0x920a8e00 0x0 0x100>, - <0x2 0x920a8400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - interrupt-controller; - #interrupt-cells = <2>; - pmic@e { - compatible = "apple,maverick-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - status = "disabled"; - }; - spmi-device@d { - compatible = "apple,t6000-viper-spmi", "apple,viper-spmi"; - reg = <0xd SPMI_USID>; - status = "disabled"; - }; -}; - -&clvr_spmi0 { - reg = <0x2 0x8e501100 0x0 0x100>, - <0x2 0x8e500e00 0x0 0x100>, - <0x2 0x8e500400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - interrupt-controller; - #interrupt-cells = <2>; - pmic@f { - compatible = "apple,monaco-pmic", "apple,spmi-nvmem"; - reg = <0xf SPMI_USID>; - read-only; - status = "disabled"; - }; -}; - -&clvr_spmi1 { - reg = <0x2 0x8e509100 0x0 0x100>, - <0x2 0x8e508e00 0x0 0x100>, - <0x2 0x8e508400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - interrupt-controller; - #interrupt-cells = <2>; - pmic@f { - compatible = "apple,monaco-pmic", "apple,spmi-nvmem"; - reg = <0xf SPMI_USID>; - read-only; - status = "disabled"; - }; -}; - -&clvr_spmi2 { - reg = <0x2 0x8e511100 0x0 0x100>, - <0x2 0x8e510e00 0x0 0x100>, - <0x2 0x8e510400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - interrupt-controller; - #interrupt-cells = <2>; - pmic@f { - compatible = "apple,monaco-pmic", "apple,spmi-nvmem"; - reg = <0xf SPMI_USID>; - read-only; - status = "disabled"; - }; -}; - -&aop_spmi0 { - reg = <0x2 0x93829300 0x0 0x100>, - <0x2 0x93828e00 0x0 0x100>, - <0x2 0x93828400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - interrupt-controller; - #interrupt-cells = <2>; - spmi-device@e { - compatible = "apple,t6000-wifibt-pmu", "apple,radio-pmu"; - reg = <0xe SPMI_USID>; - status = "disabled"; - }; - spmi-device@f { - compatible = "apple,t6000-uwb-pmu", "apple,radio-pmu"; - reg = <0xf SPMI_USID>; - status = "disabled"; - }; -}; - -&aop_spmi1 { - reg = <0x2 0x9382d300 0x0 0x100>, - <0x2 0x9382ce00 0x0 0x100>, - <0x2 0x9382c400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - interrupt-controller; - #interrupt-cells = <2>; - stockholm: nfc@c { - compatible = "apple,t6000-stockholm-spmi", "apple,stockholm-spmi"; - reg = <0xc SPMI_USID>; - interrupt-parent = <&aop_spmi1>; - interrupts = <160 IRQ_TYPE_NONE>, - <161 IRQ_TYPE_NONE>, - <162 IRQ_TYPE_NONE>, - <163 IRQ_TYPE_NONE>, - <164 IRQ_TYPE_NONE>, - <165 IRQ_TYPE_NONE>, - <166 IRQ_TYPE_NONE>; - status = "disabled"; - }; -}; diff --git a/arch/arm64/boot/dts/apple/t600x-j314-j316.dtsi b/arch/arm64/boot/dts/apple/t600x-j314-j316.dtsi index f9bb3d9d034975..0d249725947b01 100644 --- a/arch/arm64/boot/dts/apple/t600x-j314-j316.dtsi +++ b/arch/arm64/boot/dts/apple/t600x-j314-j316.dtsi @@ -57,13 +57,6 @@ usb4_2_pcie = &apciec2; usb4-3-pcie = &apciec3; wifi0 = &wifi0; - - usb4_0_rc = &usb4_0_acio; - usb4_0_nhi = &usb4_0_nhi; - usb4_1_rc = &usb4_1_acio; - usb4_1_nhi = &usb4_1_nhi; - usb4_2_rc = &usb4_2_acio; - usb4_2_nhi = &usb4_2_nhi; }; chosen { diff --git a/arch/arm64/boot/dts/apple/t6020-j414s.dts b/arch/arm64/boot/dts/apple/t6020-j414s.dts index 533bba8f4864d5..d25ddc974bd5ad 100644 --- a/arch/arm64/boot/dts/apple/t6020-j414s.dts +++ b/arch/arm64/boot/dts/apple/t6020-j414s.dts @@ -9,12 +9,6 @@ /dts-v1/; -/* - * Let m1n1 boot the PMP, which takes over the fabric and DCS p-states - * (needs an m1n1 that makes room for the PMP's tunables). - */ -#define APPLE_USE_PMP - #include "t6020.dtsi" #include "t602x-j414-j416.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6021.dtsi b/arch/arm64/boot/dts/apple/t6021.dtsi index bb1436a1f2dd40..f69afed98c55f8 100644 --- a/arch/arm64/boot/dts/apple/t6021.dtsi +++ b/arch/arm64/boot/dts/apple/t6021.dtsi @@ -24,6 +24,7 @@ #endif #define APPLE_T602X_NON_ULTRA +#define APPLE_USE_PMP #include "t602x-common.dtsi" diff --git a/arch/arm64/boot/dts/apple/t602x-die0.dtsi b/arch/arm64/boot/dts/apple/t602x-die0.dtsi index 828f6ac65c4a8b..7c1799131b46c5 100644 --- a/arch/arm64/boot/dts/apple/t602x-die0.dtsi +++ b/arch/arm64/boot/dts/apple/t602x-die0.dtsi @@ -722,6 +722,16 @@ status = "disabled"; }; + /* + * Disabled here on every board by design. The SEP is already + * running when Linux starts (warm attach: one shared-memory + * registration, no cold boot), so apple_sep enables this node + * and sep_dart with a changeset at module load, once it has + * picked this SoC's profile and before the DART probes. A + * board with the enclave only needs the sep alias, which the + * boot loader uses to add the sepfw region and the boot + * manifests. + */ sep: sep@396400000 { compatible = "apple,sep"; reg = <0x3 0x96400000 0x0 0x6C000>; diff --git a/arch/arm64/boot/dts/apple/t6030-dcp.dtsi b/arch/arm64/boot/dts/apple/t6030-dcp.dtsi index c2324b1083a616..511ebabee55b3d 100644 --- a/arch/arm64/boot/dts/apple/t6030-dcp.dtsi +++ b/arch/arm64/boot/dts/apple/t6030-dcp.dtsi @@ -87,6 +87,8 @@ <0x2 0x8e850000 0x0 0x4000>; power-domains = <&ps_disp_cpu>; clocks = <&clk_disp0>; + /* Display bandwidth request slot in the disp-5 window. */ + apple,bw-scratch = <&pmgr_dcp 0 5 0x988>; #address-cells = <2>; #size-cells = <2>; ranges; @@ -97,6 +99,12 @@ }; }; + pmgr_dcp: power-management@3503d0000 { + reg = <0x3 0x503d0000 0x0 0x4000>; + reg-names = "dcp-fw-pmgr"; + #apple,bw-scratch-cells = <3>; + }; + dcpext_dart: iommu@2d130c000 { compatible = "apple,t6030-dart", "apple,t8110-dart"; reg = <0x2 0xd130c000 0x0 0x4000>; diff --git a/arch/arm64/boot/dts/apple/t6030-j514s-j516s-audio.dtsi b/arch/arm64/boot/dts/apple/t6030-j514s-j516s-audio.dtsi new file mode 100644 index 00000000000000..a4dee6b04b1458 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6030-j514s-j516s-audio.dtsi @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* Speaker amplifier wiring shared by the 14- and 16-inch M3 Pro. */ + +&speaker_left_tweet { + shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; +}; + +&speaker_left_woof1 { + shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; +}; + +&speaker_left_woof2 { + shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; +}; + +&speaker_right_tweet { + shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; +}; + +&speaker_right_woof1 { + shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; +}; + +&speaker_right_woof2 { + shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; +}; diff --git a/arch/arm64/boot/dts/apple/t6030-j514s.dts b/arch/arm64/boot/dts/apple/t6030-j514s.dts index 1ccf2f1294d6b3..006c1a077c43bd 100644 --- a/arch/arm64/boot/dts/apple/t6030-j514s.dts +++ b/arch/arm64/boot/dts/apple/t6030-j514s.dts @@ -11,6 +11,7 @@ #include "t6030.dtsi" #include "t603x-j514-j516.dtsi" +#include "t6030-j514s-j516s-audio.dtsi" #include "t603x-j514s-j516s-usb4.dtsi" #include "t603x-j514s-j516s-hdmi.dtsi" @@ -41,36 +42,6 @@ brcm,board-type = "apple,texa"; }; -&speaker_left_tweet { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_left_woof1 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_left_woof2 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_right_tweet { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_right_woof1 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_right_woof2 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - &jack_codec { reset-gpios = <&pinctrl_nub 21 GPIO_ACTIVE_HIGH>; interrupts-extended = <&pinctrl_ap 196 IRQ_TYPE_LEVEL_LOW>; diff --git a/arch/arm64/boot/dts/apple/t6030-j516s.dts b/arch/arm64/boot/dts/apple/t6030-j516s.dts index d3fff6b103fde0..ae9e260c3da99b 100644 --- a/arch/arm64/boot/dts/apple/t6030-j516s.dts +++ b/arch/arm64/boot/dts/apple/t6030-j516s.dts @@ -11,6 +11,7 @@ #include "t6030.dtsi" #include "t603x-j514-j516.dtsi" +#include "t6030-j514s-j516s-audio.dtsi" #include "t603x-j514s-j516s-usb4.dtsi" #include "t603x-j514s-j516s-hdmi.dtsi" @@ -41,36 +42,6 @@ brcm,board-type = "apple,jura"; }; -&speaker_left_tweet { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_left_woof1 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_left_woof2 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_right_tweet { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_right_woof1 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_right_woof2 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - &jack_codec { reset-gpios = <&pinctrl_nub 21 GPIO_ACTIVE_HIGH>; interrupts-extended = <&pinctrl_ap 196 IRQ_TYPE_LEVEL_LOW>; diff --git a/arch/arm64/boot/dts/apple/t6030-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6030-peripherals.dtsi index 637d5067cce1ac..3c8e94c1d1c43b 100644 --- a/arch/arm64/boot/dts/apple/t6030-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6030-peripherals.dtsi @@ -517,10 +517,12 @@ reg = <0x3 0x0d000000 0x0 0x4000>, <0x3 0x0c000000 0x0 0x8000>, <0x3 0x0d078000 0x0 0x4000>; + reg-names = "core", "wrapper", "aux"; interrupt-parent = <&aic>; interrupts = , ; power-domains = <&ps_scodec>; + resets = <&ps_scodec>; iommus = <&dart_apr0 1>, <&dart_apr1 1>; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t6030.dtsi b/arch/arm64/boot/dts/apple/t6030.dtsi index ee1441a387dffe..953e45d650b009 100644 --- a/arch/arm64/boot/dts/apple/t6030.dtsi +++ b/arch/arm64/boot/dts/apple/t6030.dtsi @@ -2189,5 +2189,15 @@ apple,soc-die-keys = "Tf04", "Tf09", "Tf0A", "Tf0B", "Tf0D", "Tf0E", "Tf14", "Tf18", "Tf19", "Tf1A", "Tf24", "Tf25", "Tf2A", "Tf2B"; + /* + * SoC die limits from the ADT's /arm-io/pmp/iop-pmp-nub, the same in + * the J514s and J516s device trees: the PMP's fast die control holds + * the average die temperature at fast-die-ctrl-ts-avg-temp (100 C) + * and the hottest die sensor at the fast-die-ctrl-loop target (110 C). + * Power consumers shed performance from the first and hold their + * lowest state at the second. + */ + apple,soc-die-passive-millicelsius = <100000>; + apple,soc-die-hot-millicelsius = <110000>; apple,thermal-pressure-key = "mTPL"; }; diff --git a/arch/arm64/boot/dts/apple/t6031-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6031-peripherals.dtsi index c75802ef5f94ec..02108942465cf2 100644 --- a/arch/arm64/boot/dts/apple/t6031-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6031-peripherals.dtsi @@ -811,9 +811,11 @@ reg = <0x2 0xc5000000 0x0 0x4000>, <0x2 0xc4000000 0x0 0x1000000>, <0x2 0xc5078000 0x0 0x4000>; + reg-names = "core", "wrapper", "aux"; interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_scodec>; + resets = <&ps_scodec>; iommus = <&dart_apr00 1>, <&dart_apr01 1>; status = "disabled"; }; @@ -822,9 +824,11 @@ compatible = "apple,t6031-prores", "apple,prores"; reg = <0x2 0x87000000 0x0 0x4000>, <0x2 0x86000000 0x0 0x1000000>; + reg-names = "core", "wrapper"; interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_prores>; + resets = <&ps_prores>; iommus = <&dart_apr1 0>; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t6032-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6032-peripherals.dtsi index fd9e11eea31d99..66b41792e1de7d 100644 --- a/arch/arm64/boot/dts/apple/t6032-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6032-peripherals.dtsi @@ -449,9 +449,11 @@ reg = <0x2 0xc5000000 0x0 0x4000>, <0x2 0xc4000000 0x0 0x1000000>, <0x2 0xc5078000 0x0 0x4000>; + reg-names = "core", "wrapper", "aux"; interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_scodec>; + resets = <&ps_scodec>; iommus = <&ultra_dart_apr00 1>, <&ultra_dart_apr01 1>; status = "disabled"; }; @@ -460,9 +462,11 @@ compatible = "apple,t6032-prores", "apple,prores"; reg = <0x2 0x87000000 0x0 0x4000>, <0x2 0x86000000 0x0 0x1000000>; + reg-names = "core", "wrapper"; interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_prores>; + resets = <&ps_prores>; iommus = <&ultra_dart_apr10 0>; status = "disabled"; }; @@ -779,9 +783,11 @@ reg = <0x2 0xc5000000 0x0 0x4000>, <0x2 0xc4000000 0x0 0x1000000>, <0x2 0xc5078000 0x0 0x4000>; + reg-names = "core", "wrapper", "aux"; interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_scodec_die1>; + resets = <&ps_scodec_die1>; iommus = <&ultra_dart_apr20 1>, <&ultra_dart_apr21 1>; status = "disabled"; }; @@ -790,9 +796,11 @@ compatible = "apple,t6032-prores", "apple,prores"; reg = <0x2 0x87000000 0x0 0x4000>, <0x2 0x86000000 0x0 0x1000000>; + reg-names = "core", "wrapper"; interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_prores_die1>; + resets = <&ps_prores_die1>; iommus = <&ultra_dart_apr30 0>; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t603x-j514-j516.dtsi b/arch/arm64/boot/dts/apple/t603x-j514-j516.dtsi index 25eb746f430ae7..aa7cea142a27d7 100644 --- a/arch/arm64/boot/dts/apple/t603x-j514-j516.dtsi +++ b/arch/arm64/boot/dts/apple/t603x-j514-j516.dtsi @@ -87,6 +87,7 @@ &mtp { status = "okay"; + apple,rtkit-keep-running; }; &mtp_mbox { diff --git a/arch/arm64/boot/dts/apple/t6040-j616s-dpaudio.dtsi b/arch/arm64/boot/dts/apple/t6040-j616s-dpaudio.dtsi index e406a733c350d4..d00c7aa805c1e4 100644 --- a/arch/arm64/boot/dts/apple/t6040-j616s-dpaudio.dtsi +++ b/arch/arm64/boot/dts/apple/t6040-j616s-dpaudio.dtsi @@ -3,20 +3,13 @@ * DPA1 and DPA2 belong to DCPEXT0 and DCPEXT1, respectively. SIO supplies * their sample streams; neither interface has AP-side registers. * - * Both chains are enabled: the SIO DART, mailbox and CPU domain, DPA1 and - * DPA2 and their clients. The SIO itself stays disabled here: iBoot has - * loaded its firmware, and the boot loader enables the node once it has - * reserved that firmware and published the T6041 boot tables (it finds it - * by the alias). Without a T6041-aware loader DPA1 and DPA2 wait for their - * DMA channels and nothing else changes. The DCP side starts unless - * appledrm.hdmi_audio=0. + * Both chains are enabled: DPA1 and DPA2 and their clients. The SIO, its + * DART, mailbox and CPU domain are set up in t6040.dtsi. Without a + * T6041-aware loader DPA1 and DPA2 wait for their DMA channels and nothing + * else changes. The DCP side starts unless appledrm.hdmi_audio=0. */ / { - aliases { - sio = &sio; - }; - dpaudio1: audio-controller-1 { compatible = "apple,t6041-dpaudio", "apple,dpaudio"; dmas = <&sio 0x66>; @@ -86,34 +79,6 @@ }; }; -/* - * The SIO firmware drives the SPI, UART and DP audio shims, so keep their - * parents on while it runs, as on T6000, T8112 and T8140. The ADT lists - * only SIO as SIO_CPU's parent. Without this, SPI_P stays on only because - * the QSPI controller never runtime-suspends, and UART_P is left as iBoot - * set it; a T8140 SIO with SPI_P/UART_P off crashes at boot. - */ -&ps_sio_cpu { - power-domains = <&ps_sio>, <&ps_spi_p>, <&ps_uart_p>, <&ps_dpa_p>; - status = "okay"; -}; - -&ps_uart_p { - status = "okay"; -}; - -&sio_dart { - status = "okay"; -}; - -&sio_mbox { - status = "okay"; -}; - -&ps_dpa_p { - status = "okay"; -}; - &ps_dpa1 { status = "okay"; }; diff --git a/arch/arm64/boot/dts/apple/t6040-j616s.dts b/arch/arm64/boot/dts/apple/t6040-j616s.dts index a80edf92728813..021d36eaaafa98 100644 --- a/arch/arm64/boot/dts/apple/t6040-j616s.dts +++ b/arch/arm64/boot/dts/apple/t6040-j616s.dts @@ -192,48 +192,6 @@ }; }; -/* Scaler/CSC (MSR) and its DART, proven on this board. */ -&ps_msr0 { - status = "okay"; -}; - -&ps_msr0_ase_core { - status = "okay"; -}; - -&scaler0_dart { - status = "okay"; -}; - -&scaler0 { - status = "okay"; -}; - -/* - * ProRes encoder and its DART. The engine runs with SCODEC_STREAMING (and so - * SCODEC) powered. The driver has built-in power-up rows for it; an optional - * apple/prores-t6041-init.bin replaces them. - */ -&ps_fab1_soc { - status = "okay"; -}; - -&ps_scodec { - status = "okay"; -}; - -&ps_scodec_streaming { - status = "okay"; -}; - -&apr0_dart { - status = "okay"; -}; - -&apr0 { - status = "okay"; -}; - /* * USB4/Thunderbolt on all three Type-C ports: typec0 (left back, ACIO0), * typec1 (left front, ACIO1) and typec2 (right, ACIO2). The loader hands @@ -387,12 +345,3 @@ &ps_uart0 { status = "okay"; }; - -/* SIO AES engine, software keys only. */ -&ps_aes { - status = "okay"; -}; - -&aes { - status = "okay"; -}; diff --git a/arch/arm64/boot/dts/apple/t6040-j773s.dts b/arch/arm64/boot/dts/apple/t6040-j773s.dts index 94f5ba02c2aec1..90da1d0fb13499 100644 --- a/arch/arm64/boot/dts/apple/t6040-j773s.dts +++ b/arch/arm64/boot/dts/apple/t6040-j773s.dts @@ -322,6 +322,7 @@ /* ADT /amfm reg_on gP13 */ pwren-gpios = <&smc_gpio 0x13 GPIO_ACTIVE_HIGH>; reset-gpios = <&pinctrl 4 GPIO_ACTIVE_LOW>; + supports-clkreq; device_type = "pci"; bluetooth0: bluetooth@0,1 { diff --git a/arch/arm64/boot/dts/apple/t6040-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6040-peripherals.dtsi index f59b3f0a8fbd81..babbb53ec09914 100644 --- a/arch/arm64/boot/dts/apple/t6040-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6040-peripherals.dtsi @@ -25,7 +25,7 @@ power-domains = <&ps_dwi>; }; - /* ADT /arm-io/aes. */ + /* ADT /arm-io/aes: the SIO AES engine, software keys only. */ aes: crypto@42900c000 { compatible = "apple,t6041-aes", "apple,aes"; reg = <0x4 0x2900c000 0x0 0x4000>, @@ -35,7 +35,7 @@ interrupts = ; power-domains = <&ps_aes>; iommus = <&sio_dart 1>; - status = "disabled"; + status = "okay"; }; /* ADT /arm-io/aon-ptd. */ diff --git a/arch/arm64/boot/dts/apple/t6040-pmgr.dtsi b/arch/arm64/boot/dts/apple/t6040-pmgr.dtsi index 75650445572b10..4d733110e35278 100644 --- a/arch/arm64/boot/dts/apple/t6040-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t6040-pmgr.dtsi @@ -106,8 +106,7 @@ #reset-cells = <0>; label = "aes"; power-domains = <&ps_sio>; - apple,always-on; - status = "disabled"; + status = "okay"; }; ps_spi0: power-controller@1b8 { diff --git a/arch/arm64/boot/dts/apple/t6040.dtsi b/arch/arm64/boot/dts/apple/t6040.dtsi index e66c5b8d7739f3..fa3f47582cc4da 100644 --- a/arch/arm64/boot/dts/apple/t6040.dtsi +++ b/arch/arm64/boot/dts/apple/t6040.dtsi @@ -699,4 +699,90 @@ 0x5003c0000 0x5003e4000>; }; +/* + * The scaler/CSC (ADT scaler0, MSR) and its DART. It has no board wiring, + * so it is enabled on every M4 Pro. + */ +&ps_msr0 { + status = "okay"; +}; + +&ps_msr0_ase_core { + status = "okay"; +}; + +&scaler0_dart { + status = "okay"; +}; + +&scaler0 { + status = "okay"; +}; + +/* + * The ProRes encoder (ADT apr0) and its DART. It has no board wiring, so it + * is enabled on every M4 Pro. The engine runs with SCODEC_STREAMING (and so + * SCODEC) powered. The driver has built-in power-up rows for it; an optional + * apple/prores-t6041-init.bin replaces them. + */ +&ps_fab1_soc { + status = "okay"; +}; + +&ps_scodec { + status = "okay"; +}; + +&ps_scodec_streaming { + status = "okay"; +}; + +&apr0_dart { + status = "okay"; +}; + +&apr0 { + status = "okay"; +}; + #include "t6040-usb4.dtsi" + +/* + * The SIO coprocessor is part of every T6040 and has no board wiring: iBoot + * loads its firmware on every board, and the boot loader enables the SIO + * node, which it finds by the alias, once it has reserved that firmware and + * published the T6041 boot tables. The SIO AES engine sits behind its DART. + */ +/ { + aliases { + sio = &sio; + }; +}; + +/* + * The SIO firmware drives the SPI, UART and DP audio shims, so keep their + * parents on while it runs, as on T6000, T8112 and T8140. The ADT lists + * only SIO as SIO_CPU's parent. Without this, SPI_P stays on only because + * the QSPI controller never runtime-suspends, and UART_P is left as iBoot + * set it; a T8140 SIO with SPI_P/UART_P off crashes at boot. + */ +&ps_sio_cpu { + power-domains = <&ps_sio>, <&ps_spi_p>, <&ps_uart_p>, <&ps_dpa_p>; + status = "okay"; +}; + +&ps_uart_p { + status = "okay"; +}; + +&ps_dpa_p { + status = "okay"; +}; + +&sio_dart { + status = "okay"; +}; + +&sio_mbox { + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t6041-j575c-atc3.dtsi b/arch/arm64/boot/dts/apple/t6041-j575c-atc3.dtsi index 3971e75915e90c..1fe04fb9e6212f 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c-atc3.dtsi +++ b/arch/arm64/boot/dts/apple/t6041-j575c-atc3.dtsi @@ -117,6 +117,7 @@ apple,event-irq-in-sleep; /* Retimer set up before Linux keeps SuperSpeed down until replugged. */ apple,reset-inherited-usb2-connection; + apple,debug-lock-key = "575J"; typec3: connector { compatible = "usb-c-connector"; diff --git a/arch/arm64/boot/dts/apple/t6041-j575c-usbc-dcpext3.dtsi b/arch/arm64/boot/dts/apple/t6041-j575c-usbc-dcpext3.dtsi new file mode 100644 index 00000000000000..679fc57246ebcd --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6041-j575c-usbc-dcpext3.dtsi @@ -0,0 +1,220 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * A third USB-C DisplayPort processor on the J575c: dcpext3, with a route to + * each of the four back Type-C ports (typec0-3), next to dcpext1 and dcpext2. + * + * The node is the J614c/J616c's (t6041-j616c-usbc-dcpext3.dtsi) with the + * fourth route added: the J575c ADT has dcpext3 at the same address + * (/arm-io/dcpext3 0x106e00000 + 0x2_0000_0000, interrupts +0x48, + * external-index 4, bwr-agent DISP_EXT3 slot 6, dp-switch-ufp-endpoint 3) + * and iBoot preloads and starts it here too (iop-dcpext3-nub pre-loaded 1, + * running 1). As dcpext1 and dcpext2, no PMP and no DISPEXT3 power domain is + * described: the chain runs as iBoot left it powered. + * + * Everything here is disabled. The boot loader fills dcpext3's firmware + * memory from this boot's ADT (aura t6041_exts) and the display gate enables + * the chain once it has. + */ + +/ { + aliases { + dcpext3 = &dcpext3; + }; + + reserved-memory { + dcpext3_text: dcpext3-text { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + + dcpext3_data: dcpext3-data { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + + dcpext3_heap: dcpext3-heap { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + }; + + dcpext3: dcp@306e00000 { + compatible = "apple,t6041-dcpext", "apple,dcpext"; + reg = <0x3 0x06e00000 0x0 0x4000>, + <0x3 0x04000000 0x0 0x4000000>, + <0x3 0x06240000 0x0 0x10000>, + <0x3 0x063a8000 0x0 0x4000>, + <0x3 0x06800000 0x0 0x800000>; + reg-names = "coproc", "disp-0", "disp-1", "disp-2", "disp-3"; + mboxes = <&dcpext3_mbox>; + mbox-names = "mbox"; + iommus = <&dcpext3_dart 23>; + /* + * PMGR bandwidth agent scratch: the bwr-agent the ADT dispext3 + * function-bw_req_interrupt0 (0x4f) names: ADT + * pmgr bwr-agent DISP_EXT3, slot 6, so 0x20000 + 6 * 0x4000. + */ + apple,bw-scratch = <&pmgr_dcp 0 4 0x38000>; + /* ADT iop-dcpext3-nub external-index */ + apple,dcp-endpoint = <4>; + /* as dcpext0/1: without it apple-dcp's probe fails with -EINVAL */ + apple,iomfb-surfaces = <1 1 0 0>; + apple,connector-type = "USB-C"; + phys = <&atcphy0 PHY_TYPE_DP>, <&atcphy1 PHY_TYPE_DP>, + <&atcphy2 PHY_TYPE_DP>, <&atcphy3 PHY_TYPE_DP>; + phy-names = "typec0", "typec1", "typec2", "typec3"; + mux-controls = <&atcphy0_xbar 0>, <&atcphy1_xbar 0>, + <&atcphy2_xbar 0>, <&atcphy3_xbar 0>; + mux-control-names = "typec0", "typec1", "typec2", "typec3"; + /* + * indexed by route; crossbar state = 2 * dp-switch-ufp-endpoint + * (3) + port (0) + */ + apple,typec-dptx-phys = <0 1 2 3>; + apple,typec-mux-indices = <6 6 6 6>; + memory-region = <&dcpext3_text>, <&dcpext3_data>, <&dcpext3_heap>; + memory-region-names = "text", "data", "heap"; + status = "disabled"; + + dispext3_piodma: piodma { + iommus = <&dispext3_dart 16>; + }; + + typec-routes { + #address-cells = <1>; + #size-cells = <0>; + + route@0 { + reg = <0>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec0: endpoint { + remote-endpoint = <&typec0_dcpext3>; + }; + }; + }; + + route@1 { + reg = <1>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec1: endpoint { + remote-endpoint = <&typec1_dcpext3>; + }; + }; + }; + + route@2 { + reg = <2>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec2: endpoint { + remote-endpoint = <&typec2_dcpext3>; + }; + }; + }; + + route@3 { + reg = <3>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec3: endpoint { + remote-endpoint = <&typec3_dcpext3>; + }; + }; + }; + }; + }; + + dcpext3_mbox: mailbox@306e08000 { + compatible = "apple,t6041-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x3 0x06e08000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + status = "disabled"; + }; + + dispext3_dart: iommu@306300000 { + compatible = "apple,t6041-dart", "apple,t8110-dart"; + reg = <0x3 0x06300000 0x0 0xc000>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x10 0x0>; + interrupt-parent = <&aic>; + interrupts = ; + status = "disabled"; + }; + + dcpext3_dart: iommu@306340000 { + compatible = "apple,t6041-dart", "apple,t8110-dart"; + reg = <0x3 0x06340000 0x0 0xc000>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x10 0x0>; + interrupt-parent = <&aic>; + interrupts = ; + status = "disabled"; + }; +}; + +&typec0 { + ports { + port@3 { + typec0_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec0>; + }; + }; + }; +}; + +&typec1 { + ports { + port@3 { + typec1_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec1>; + }; + }; + }; +}; + +&typec2 { + ports { + port@3 { + typec2_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec2>; + }; + }; + }; +}; + +&typec3 { + ports { + port@3 { + typec3_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec3>; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t6041-j575c.dts b/arch/arm64/boot/dts/apple/t6041-j575c.dts index a9b42e9a63ab1d..bce7e4962eec32 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j575c.dts @@ -36,12 +36,23 @@ dcp = &dcp; disp0 = &display; disp0-piodma = &disp0_piodma; + nvram = &nvram; }; chosen { stdout-path = "serial0:115200n8"; }; + /* + * The boot NOR runs from a PMU rail that is on whenever the SoC is + * and that no OS switches. The ADT gives the flash no supply. + */ + nor_flash_vcc: regulator-nor-flash-vcc { + compatible = "regulator-fixed"; + regulator-name = "nor-flash-vcc"; + regulator-always-on; + }; + reserved-memory { #address-cells = <2>; #size-cells = <2>; @@ -178,6 +189,12 @@ <&cpu_p14 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, <&cpu_p15 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; }; + + map-dcs { + trip = <&cpu_die_passive>; + cooling-device = + <&pmc THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; }; }; @@ -993,6 +1010,18 @@ status = "okay"; }; +&pmc { + /* + * System power above DCS state 0 at each DCS state, measured on a + * J575c with all 32 DCS channels enabled (ADT mcc: 8 AMCCs, 4 DCS + * each, dcs-channel-enable-mask 0xffffffff) under 256 MiB GPU copies: + * 233 GB/s at state 5, 85 GB/s at states 0 and 1. States 1 and 2 draw + * no more than state 0, so the power allocator never asks for a limit + * below DCS state 2 (cooling state 3). + */ + apple,dcs-power-microwatt = <0 0 0 5508000 8559000 10966000>; +}; + /* The J616c's CPU keys and two fans, all read back on a J575c */ &smc_hwmon { temperature-TCMz { @@ -1089,6 +1118,24 @@ #include "hwmon-common.dtsi" #include "hwmon-fan-dual.dtsi" +&smc_hwmon { + /* + * This SMC spells the fan mode keys F0md/F1md, as the T6050 one does + * (it has no F0Md/F1Md and no Ftst unlock key). It accepts a manual + * speed for both fans from userspace and returns them to firmware + * control when the request is dropped. + */ + fan-F0Ac { + apple,fan-mode = "F0md"; + apple,fan-manual-control; + }; + + fan-F1Ac { + apple,fan-mode = "F1md"; + apple,fan-manual-control; + }; +}; + &pinctrl { status = "okay"; @@ -1221,6 +1268,7 @@ #size-cells = <2>; pwren-gpios = <&smc_gpio 0x13 GPIO_ACTIVE_HIGH>; reset-gpios = <&pinctrl 4 GPIO_ACTIVE_LOW>; + supports-clkreq; device_type = "pci"; bluetooth@0,1 { @@ -1250,6 +1298,7 @@ reset-gpios = <&pinctrl 5 GPIO_ACTIVE_LOW>; bus-range = <2 2>; pwren-gpios = <&smc_gpio 0x19 GPIO_ACTIVE_HIGH>; + supports-clkreq; #address-cells = <3>; #size-cells = <2>; ranges; @@ -1329,6 +1378,27 @@ status = "okay"; }; +/* + * The Neural Engine and its three DARTs, as on the J614c/J616c. The J575c's + * ADT has ane0 with pre-loaded firmware (__TEXT;__DATA); the loader fills the + * reservations of t6041-j616c-ane.dtsi and the firmware IOVAs from it. + */ +&ane0_dart0 { + status = "okay"; +}; + +&ane0_dart1 { + status = "okay"; +}; + +&ane0_dart2 { + status = "okay"; +}; + +&ane { + status = "okay"; +}; + /* Both JPEG engines; they have no board wiring. */ &ps_jpg { status = "okay"; @@ -1350,6 +1420,32 @@ status = "okay"; }; +/* + * First ProRes encoder (apr0) and its DART, as on the J616c. The J575c's ADT + * has apr0 and dart-apr0 at the t6041.dtsi addresses and interrupts. apr0 + * runs with SCODEC_STREAMING (and SCODEC) powered and uses the driver's + * built-in T6041 power-up rows. + */ +&ps_fab1_soc { + status = "okay"; +}; + +&ps_scodec { + status = "okay"; +}; + +&ps_scodec_streaming { + status = "okay"; +}; + +&apr0_dart { + status = "okay"; +}; + +&apr0 { + status = "okay"; +}; + /* * Three of the four back Thunderbolt ports, with the J773s's PD controllers * (nub-spmi-a0 0xc, 0xa and 0x8 for ATC0-2), as on the J616c. @@ -1400,6 +1496,7 @@ apple,event-irq-in-sleep; /* Retimer set up before Linux keeps SuperSpeed down until replugged. */ apple,reset-inherited-usb2-connection; + apple,debug-lock-key = "575J"; typec1: connector { compatible = "usb-c-connector"; @@ -1432,6 +1529,7 @@ apple,event-irq-in-sleep; /* Retimer set up before Linux keeps SuperSpeed down until replugged. */ apple,reset-inherited-usb2-connection; + apple,debug-lock-key = "575J"; typec2: connector { compatible = "usb-c-connector"; @@ -1788,6 +1886,8 @@ operating-points-v2 = <&gpu_opp>; apple,cs-opp = <&gpu_cs_opp>; apple,afr-opp = <&gpu_afr_opp>; + /* Avoid a core power cycle between interactive submissions, then release. */ + apple,idle-off-delay-ms = <16>; apple,firmware-version = <26 5 2>; }; @@ -1985,6 +2085,7 @@ #include "t6041-j575c-usb3.dtsi" #include "t6041-j575c-usbc.dtsi" #include "t6041-j575c-usbc-dcpext2.dtsi" +#include "t6041-j575c-usbc-dcpext3.dtsi" #include "t6041-j575c-hdmi.dtsi" /* Not described: the SEP (no Touch ID sensor). */ @@ -2015,3 +2116,79 @@ &gpu { power-domains = <&pmp_gfx>; }; + +/* + * Boot NOR, as on the J614c/J616c. ADT /arm-io/qspi ("qspi,qspimc", + * 0x229118000, IRQ 1573) is the t604x.dtsi qspi node, and the partition is + * /arm-io/qspi/spinor/anvram (0x700000, 0x100000), flash-relative; + * asahi-bless and asahi-nvram find it by its label. + */ +&qspi { + status = "okay"; + + flash@0 { + compatible = "jedec,spi-nor"; + reg = <0>; + spi-max-frequency = <10000000>; + spi-rx-bus-width = <1>; + spi-tx-bus-width = <1>; + vcc-supply = <&nor_flash_vcc>; + + partitions { + compatible = "fixed-partitions"; + #address-cells = <1>; + #size-cells = <1>; + + nvram: partition@700000 { + label = "nvram"; + reg = <0x700000 0x100000>; + }; + }; + }; +}; + +/* The QSPI controller cannot probe while its power state is disabled. */ +&ps_qspi { + status = "okay"; +}; + +/* + * Both MSR scalers (scaler0, scaler1) and their DARTs, as on the J616c. The + * J575c's ADT has them at the addresses, interrupts and PMGR offsets of + * t6041-j614-j616-j575-scaler.dtsi. + */ +&ps_fab5_soc { + status = "okay"; +}; + +&ps_msr0 { + status = "okay"; +}; + +&ps_msr0_ase_core { + status = "okay"; +}; + +&scaler0_dart { + status = "okay"; +}; + +&scaler0 { + status = "okay"; +}; + +&ps_msr1 { + status = "okay"; +}; + +&ps_msr1_ase_core { + status = "okay"; +}; + +&scaler1_dart { + status = "okay"; +}; + +&scaler1 { + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t6041-j614-j616-j575-scaler.dtsi b/arch/arm64/boot/dts/apple/t6041-j614-j616-j575-scaler.dtsi index 34ecb3b560df99..6140cc718d11c6 100644 --- a/arch/arm64/boot/dts/apple/t6041-j614-j616-j575-scaler.dtsi +++ b/arch/arm64/boot/dts/apple/t6041-j614-j616-j575-scaler.dtsi @@ -26,19 +26,6 @@ }; }; -&pmgr_aux { - ps_fab5_soc: power-controller@440 { - compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; - reg = <0x440 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = "fab5_soc"; - power-domains = <&ps_afi>; - apple,always-on; - status = "disabled"; - }; -}; - /* PMGR group 1 resolves via ps-groups to the main bank at 0x502280000. */ &pmgr { ps_msr1: ps_msr1_dart: power-controller@3b0 { diff --git a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi index f326f2aa740577..5edd587e8a81e6 100644 --- a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi +++ b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi @@ -33,6 +33,85 @@ sep = &sep; }; + /* + * Display power words and PMGR chains the DCP driver writes around + * suspend-to-RAM. The windows belong to PMC, PMGR, GAPF and AXI2AF; + * no driver binds this. + */ + dcp_power: display-power@5048a9c14 { + compatible = "apple,t6041-display-power"; + reg = <0x5 0x048a9c14 0x0 0x8>, + <0x5 0x022a1000 0x0 0x100>, + <0x5 0x0282d000 0x0 0x1000>, + <0x5 0x00578000 0x0 0x1000>, + <0x4 0x03000100 0x0 0x10>; + reg-names = "pmc-dcp", "pwrgate", "pwrgate-aux", "gapf", "axi2af"; + #address-cells = <1>; + #size-cells = <0>; + + chain@0 { + reg = <0>; + label = "ext3"; + apple,pwrgate-aux; + apple,gapf-offset = <0x740>; + apple,pwrgate-offsets = <0xfb4 0xfd8>; + power-domains = <&ps_dispext3_sys>, <&ps_dispext3_fe>, <&ps_dispext3_cpu>, + <&ps_dispext3_dbe>, <&ps_dpext3>, <&ps_dispext3_gp0>, + <&ps_dispext3_gp1>, <&ps_dispext3_gpl>, <&ps_dispext3_ppp>, + <&ps_dispext3_dsc>; + }; + + chain@1 { + reg = <1>; + label = "ext2"; + apple,pwrgate-aux; + apple,gapf-offset = <0xd80>; + apple,pwrgate-offsets = <0xb34 0xb58>; + power-domains = <&ps_dispext2_sys>, <&ps_dispext2_fe>, <&ps_dispext2_cpu>, + <&ps_dispext2_dbe>, <&ps_dpext2>, <&ps_dispext2_gp0>, + <&ps_dispext2_gp1>, <&ps_dispext2_gpl>, <&ps_dispext2_ppp>, + <&ps_dispext2_dsc>; + }; + + chain@2 { + reg = <2>; + label = "ext1"; + apple,pwrgate-aux; + apple,gapf-offset = <0xd00>; + apple,pwrgate-offsets = <0x6b4 0x6d8>; + power-domains = <&ps_dispext1_sys>, <&ps_dispext1_fe>, <&ps_dispext1_cpu>, + <&ps_dispext1_dbe>, <&ps_dpext1>, <&ps_dispext1_gp0>, + <&ps_dispext1_gp1>, <&ps_dispext1_gpl>, <&ps_dispext1_ppp>, + <&ps_dispext1_dsc>; + }; + + chain@3 { + reg = <3>; + label = "ext0"; + apple,pwrgate-aux; + apple,gapf-offset = <0x840>; + apple,pwrgate-offsets = <0x234 0x258>; + power-domains = <&ps_dispext0_sys>, <&ps_dispext0_fe>, <&ps_dispext0_cpu>, + <&ps_dispext0_dbe>, <&ps_dpext0>, <&ps_dispext0_gp0>, + <&ps_dispext0_gp1>, <&ps_dispext0_gpl>, <&ps_dispext0_ppp>, + <&ps_dispext0_dsc>; + }; + + chain@4 { + reg = <4>; + label = "main"; + apple,main-chain; + apple,gapf-offset = <0x540>; + apple,pwrgate-offsets = <0x1c 0x60>; + apple,fabric-domain = <&ps_fab6_soc>; + power-domains = <&ps_disp_sys>, <&ps_disp_fe>, <&ps_disp_cpu>, + <&ps_disp_spi>, <&ps_disp_spmi>, <&ps_disp_dbe>, + <&ps_disp_dp>, <&ps_disp_gp0>, <&ps_disp_gp1>, + <&ps_disp_gpl>, <&ps_disp_cmb>, <&ps_disp_ppp>, + <&ps_disp_brc>, <&ps_disp_blc>; + }; + }; + chosen { #address-cells = <2>; #size-cells = <2>; @@ -1197,6 +1276,9 @@ }; &smc { + apple,sleep-wake-type; + /* VDD_CIO mask: bit 8 + bit 0 keeps port 0 powered for atc0_common at commit. */ + apple,sleep-pmvc = <0x101>; status = "okay"; smc_gpio_low: gpio-low { @@ -1652,10 +1734,17 @@ <0x4 0x17020000 0x0 0x4000>, <0x4 0x17024000 0x0 0x4000>, <0x4 0x17028000 0x0 0x4000>, - <0x4 0x1702c000 0x0 0x4000>; + <0x4 0x1702c000 0x0 0x4000>, + <0x4 0x16000000 0x0 0x1000000>, + <0x4 0x15046200 0x0 0x4000>, + <0x4 0x15044000 0x0 0x4000>, + <0x4 0x17000000 0x0 0x40000>, + <0x4 0x17040000 0x0 0x28000>; reg-names = "config", "rc", "port0", "port1", "port2", "port3", - "phy0", "phy1", "phy2", "phy3"; + "phy0", "phy1", "phy2", "phy3", + "axi2af", "cio3pll", "clkgen", + "phy-block", "phy-ip"; ranges = <0x43000000 0xb 0xc0000000 0xb 0xc0000000 0x0 0x20000000>, <0x02000000 0x0 0x80000000 0xb 0x80000000 0x0 0x40000000>; pinctrl-names = "default"; @@ -1687,6 +1776,7 @@ #size-cells = <2>; pwren-gpios = <&smc_gpio 0x13 GPIO_ACTIVE_HIGH>; reset-gpios = <&pinctrl 4 GPIO_ACTIVE_LOW>; + supports-clkreq; device_type = "pci"; bluetooth0: bluetooth@0,1 { @@ -1714,6 +1804,7 @@ reset-gpios = <&pinctrl 5 GPIO_ACTIVE_LOW>; bus-range = <2 2>; pwren-gpios = <&smc_gpio 0x19 GPIO_ACTIVE_HIGH>; + supports-clkreq; #address-cells = <3>; #size-cells = <2>; ranges; @@ -1756,7 +1847,15 @@ phandle = <&display>; }; +&t6041_sleep { + apple,apcie = <&pcie0>; + apple,atc-phys = <&atcphy0>, <&atcphy1>, <&atcphy2>, <&atcphy3>; + status = "okay"; +}; + &dcp { + apple,sleep-host-stop; + apple,display-power = <&dcp_power>; clocks = <&clk_disp0>; phandle = <&dcp>; @@ -1792,6 +1891,7 @@ <19 IRQ_TYPE_EDGE_RISING>; interrupt-names = "irq", "select", "sleep", "wake"; apple,event-irq-in-sleep; + apple,sleep-ssps; typec0: connector { compatible = "usb-c-connector"; @@ -1830,6 +1930,7 @@ <71 IRQ_TYPE_EDGE_RISING>; interrupt-names = "irq", "select", "sleep", "wake"; apple,event-irq-in-sleep; + apple,sleep-ssps; }; hpm1: usb-pd@a { @@ -1841,6 +1942,7 @@ <45 IRQ_TYPE_EDGE_RISING>; interrupt-names = "irq", "select", "sleep", "wake"; apple,event-irq-in-sleep; + apple,sleep-ssps; typec1: connector { compatible = "usb-c-connector"; @@ -1882,6 +1984,7 @@ <19 IRQ_TYPE_EDGE_RISING>; interrupt-names = "irq", "select", "sleep", "wake"; apple,event-irq-in-sleep; + apple,sleep-ssps; typec2: connector { compatible = "usb-c-connector"; @@ -2308,6 +2411,8 @@ operating-points-v2 = <&gpu_opp>; apple,cs-opp = <&gpu_cs_opp>; apple,afr-opp = <&gpu_afr_opp>; + /* Avoid a core power cycle between interactive submissions, then release. */ + apple,idle-off-delay-ms = <16>; apple,firmware-version = <26 5 2>; }; @@ -2562,6 +2667,7 @@ #include "t6041-j616c-hdmi.dtsi" #include "t6041-j616c-usbc.dtsi" #include "t6041-j616c-usbc-dcpext2.dtsi" +#include "t6041-j616c-usbc-dcpext3.dtsi" /* * Keyboard backlight, as on the M4 Pro boards: the ADT /arm-io/pwm0 has one @@ -2746,55 +2852,18 @@ /* * DisplayPort/HDMI audio, as on the M4 Pro boards (t6040-j616s-dpaudio.dtsi). * The J614c's ADT has the J616s's: dcpext0's audio is dp-audio1 (SIO DMA - * channel 0x66) and dcpext1's is dp-audio2 (0x68), and the PMGR has UART_P - * (0x1a0) and DPA_P (0x1a8) under SIO, and DPA1 (0x238) and DPA2 (0x240) - * under DPA_P. The SIO stays disabled here: the loader enables it once it has - * reserved the firmware iBoot loaded (it finds it by the alias). + * channel 0x66) and dcpext1's is dp-audio2 (0x68). The PMGR has DPA1 + * (0x238) and DPA2 (0x240) under the shared DPA_P power state. */ -&pmgr { - ps_uart_p: power-controller@1a0 { - compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; - reg = <0x1a0 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = "uart_p"; - power-domains = <&ps_sio>; - }; - - ps_dpa_p: power-controller@1a8 { - compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; - reg = <0x1a8 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = "dpa_p"; - power-domains = <&ps_sio>; - apple,always-on; - }; - - ps_dpa1: power-controller@238 { - compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; - reg = <0x238 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = "dpa1"; - power-domains = <&ps_dpa_p>; - }; +&ps_dpa1 { + status = "okay"; +}; - ps_dpa2: power-controller@240 { - compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; - reg = <0x240 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = "dpa2"; - power-domains = <&ps_dpa_p>; - }; +&ps_dpa2 { + status = "okay"; }; / { - aliases { - sio = &sio; - }; - dpaudio1: audio-controller-1 { compatible = "apple,t6041-dpaudio", "apple,dpaudio"; dmas = <&sio 0x66>; @@ -2862,41 +2931,6 @@ }; }; -/* The SIO firmware drives the SPI, UART and DP audio shims: keep their parents on. */ -&ps_sio_cpu { - power-domains = <&ps_sio>, <&ps_spi_p>, <&ps_uart_p>, <&ps_dpa_p>; - status = "okay"; -}; - -&sio_dart { - status = "okay"; -}; - -&sio_mbox { - status = "okay"; -}; - -/* - * The Neural Engine, as on the M4 Pro boards. The J614c's ADT has ane0 with - * pre-loaded firmware (__TEXT;__DATA); the loader fills the reservations of - * t6041-j616c-ane.dtsi and the firmware IOVAs from it. - */ -&ane0_dart0 { - status = "okay"; -}; - -&ane0_dart1 { - status = "okay"; -}; - -&ane0_dart2 { - status = "okay"; -}; - -&ane { - status = "okay"; -}; - /* Both JPEG engines, as on the M4 Pro boards; they have no board wiring. */ &ps_jpg { status = "okay"; diff --git a/arch/arm64/boot/dts/apple/t6041-j614c.dts b/arch/arm64/boot/dts/apple/t6041-j614c.dts index 6deb66068c70be..d35e9b7e3808f8 100644 --- a/arch/arm64/boot/dts/apple/t6041-j614c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j614c.dts @@ -96,3 +96,21 @@ &mesa { firmware-name = "apple/mesacal-j614c.bin", "apple/msrk-j614c.bin"; }; + +/* + * ADT /arm-io/aon-ptd ptd_data_table: the battery record ("IFtb", layout 1, + * slots 0x12-0x15). Only its peek aperture is read. + */ +&aon_ptd { + apple,battery-record = <0x49467462 1 0x12 4>; + status = "okay"; +}; + +/* SIO AES engine, software keys only. */ +&ps_aes { + status = "okay"; +}; + +&aes { + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t6041-j616c-usbc-dcpext3.dtsi b/arch/arm64/boot/dts/apple/t6041-j616c-usbc-dcpext3.dtsi new file mode 100644 index 00000000000000..6257843799f9d3 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6041-j616c-usbc-dcpext3.dtsi @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * A third USB-C DisplayPort processor on the J614c and J616c: dcpext3, with + * a route to each of the three USB-C ports (typec0-2), next to dcpext1 and + * dcpext2. Each USB-C port can then drive a display of its own. + * + * dcpext3 is dcpext2's block moved from 0x6xxxxxxxx to 0x3xxxxxxxx (ADT + * /arm-io/dcpext3 at 0x106e00000 + 0x2_0000_0000, interrupts +0x48, + * external-index 4). iBoot preloads and starts it on the M4 Max + * (iop-dcpext3-nub pre-loaded 1, running 1). As dcpext1 and dcpext2 on this + * SoC, no PMP and no DISPEXT3 power domain is described. + * + * Everything here is disabled. The boot loader fills dcpext3's firmware + * memory from this boot's ADT (aura t6041_exts) and the display gate enables + * the chain once it has. + */ + +/ { + aliases { + dcpext3 = &dcpext3; + }; + + reserved-memory { + dcpext3_text: dcpext3-text { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + + dcpext3_data: dcpext3-data { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + + dcpext3_heap: dcpext3-heap { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + }; + + dcpext3: dcp@306e00000 { + compatible = "apple,t6041-dcpext", "apple,dcpext"; + reg = <0x3 0x06e00000 0x0 0x4000>, + <0x3 0x04000000 0x0 0x4000000>, + <0x3 0x06240000 0x0 0x10000>, + <0x3 0x063a8000 0x0 0x4000>, + <0x3 0x06800000 0x0 0x800000>; + reg-names = "coproc", "disp-0", "disp-1", "disp-2", "disp-3"; + mboxes = <&dcpext3_mbox>; + mbox-names = "mbox"; + iommus = <&dcpext3_dart 23>; + /* + * PMGR bandwidth agent scratch: the bwr-agent the ADT dispext3 + * function-bw_req_interrupt0 (0x4f) names: ADT + * pmgr bwr-agent DISP_EXT3, slot 6, so 0x20000 + 6 * 0x4000. + */ + apple,bw-scratch = <&pmgr_dcp 0 4 0x38000>; + /* ADT iop-dcpext3-nub external-index */ + apple,dcp-endpoint = <4>; + /* as dcpext0/1: without it apple-dcp's probe fails with -EINVAL */ + apple,iomfb-surfaces = <1 1 0 0>; + apple,connector-type = "USB-C"; + phys = <&atcphy0 PHY_TYPE_DP>, <&atcphy1 PHY_TYPE_DP>, <&atcphy2 PHY_TYPE_DP>; + phy-names = "typec0", "typec1", "typec2"; + mux-controls = <&atcphy0_xbar 0>, <&atcphy1_xbar 0>, <&atcphy2_xbar 0>; + mux-control-names = "typec0", "typec1", "typec2"; + /* + * indexed by route; crossbar state = 2 * dp-switch-ufp-endpoint + * (3) + port (0) + */ + apple,typec-dptx-phys = <0 1 2>; + apple,typec-mux-indices = <6 6 6>; + memory-region = <&dcpext3_text>, <&dcpext3_data>, <&dcpext3_heap>; + memory-region-names = "text", "data", "heap"; + status = "disabled"; + + dispext3_piodma: piodma { + iommus = <&dispext3_dart 16>; + }; + + typec-routes { + #address-cells = <1>; + #size-cells = <0>; + + route@0 { + reg = <0>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec0: endpoint { + remote-endpoint = <&typec0_dcpext3>; + }; + }; + }; + + route@1 { + reg = <1>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec1: endpoint { + remote-endpoint = <&typec1_dcpext3>; + }; + }; + }; + + route@2 { + reg = <2>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec2: endpoint { + remote-endpoint = <&typec2_dcpext3>; + }; + }; + }; + }; + }; + + dcpext3_mbox: mailbox@306e08000 { + compatible = "apple,t6041-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x3 0x06e08000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + status = "disabled"; + }; + + dispext3_dart: iommu@306300000 { + compatible = "apple,t6041-dart", "apple,t8110-dart"; + reg = <0x3 0x06300000 0x0 0xc000>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x10 0x0>; + interrupt-parent = <&aic>; + interrupts = ; + status = "disabled"; + }; + + dcpext3_dart: iommu@306340000 { + compatible = "apple,t6041-dart", "apple,t8110-dart"; + reg = <0x3 0x06340000 0x0 0xc000>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x10 0x0>; + interrupt-parent = <&aic>; + interrupts = ; + status = "disabled"; + }; +}; + +&typec0 { + ports { + port@3 { + typec0_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec0>; + }; + }; + }; +}; + +&typec1 { + ports { + port@3 { + typec1_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec1>; + }; + }; + }; +}; + +&typec2 { + ports { + port@3 { + typec2_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec2>; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t6041-j616c.dts b/arch/arm64/boot/dts/apple/t6041-j616c.dts index 80f0a2a103071a..ccdd779a5e5807 100644 --- a/arch/arm64/boot/dts/apple/t6041-j616c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j616c.dts @@ -41,6 +41,11 @@ apple,output-templates = <0xe 0x00800000>; }; +/* The 16-inch M4 Max chassis has High Power mode, as on the J616s */ +&clpc { + apple,high-power-mode; +}; + /* * ADT aop-spmi0/stockholm-spmi: the Stockholm NFC controller at SPMI 9, its * interrupts in 224-230 and its enable on SMC gp0e, as on the J616s. @@ -102,3 +107,65 @@ &aes { status = "okay"; }; + +/* + * First ProRes encoder (apr0) and its DART. Runs with SCODEC_STREAMING (and + * SCODEC) powered; uses the driver's built-in T6041 power-up rows, optionally + * overridden by apple/prores-t6041-init.bin. + */ +&ps_fab1_soc { + status = "okay"; +}; + +&ps_scodec { + status = "okay"; +}; + +&ps_scodec_streaming { + status = "okay"; +}; + +&apr0_dart { + status = "okay"; +}; + +&apr0 { + status = "okay"; +}; + +/* Both MSR scalers/CSCs (scaler0, scaler1) and their DARTs. */ +&ps_fab5_soc { + status = "okay"; +}; + +&ps_msr0 { + status = "okay"; +}; + +&ps_msr0_ase_core { + status = "okay"; +}; + +&scaler0_dart { + status = "okay"; +}; + +&scaler0 { + status = "okay"; +}; + +&ps_msr1 { + status = "okay"; +}; + +&ps_msr1_ase_core { + status = "okay"; +}; + +&scaler1_dart { + status = "okay"; +}; + +&scaler1 { + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t6041-pmgr.dtsi b/arch/arm64/boot/dts/apple/t6041-pmgr.dtsi new file mode 100644 index 00000000000000..2f7a2f483b3eca --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6041-pmgr.dtsi @@ -0,0 +1,424 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * T6041-specific PMGR power domains for hardware auto-managed DCS channels + * and memory/SoC fabrics. + * + * Offsets and parent links verified against the J616c ADT (/arm-io/pmgr + * devices and ps-groups). The DCS nodes omit their ADT parents, the AMCC + * power states, which are not described in this device tree. All 32 DCS + * channels (24 present on binned parts, 32 on full parts) and 12 fabrics + * are hardware auto-managed: the boot loader may leave them forced on, and + * they must be switched to hardware AUTO_ENABLE early at boot, before the + * PMP starts. On binned parts dcs_24-31 are fused off and read as off. + * + * Copyright The Asahi Linux Contributors + */ + +&pmgr_aux { + ps_fab0_soc: power-controller@168 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x168 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab0_soc"; + power-domains = <&ps_afi>; + apple,always-on; + apple,auto-managed; + }; + + ps_dcs_00: power-controller@188 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x188 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_00"; + apple,auto-managed; + }; + + ps_dcs_01: power-controller@1a0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_01"; + apple,auto-managed; + }; + + ps_dcs_02: power-controller@1b0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1b0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_02"; + apple,auto-managed; + }; + + ps_dcs_03: power-controller@1c0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_03"; + apple,auto-managed; + }; + + ps_dcs_08: power-controller@1d0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_08"; + apple,auto-managed; + }; + + ps_dcs_09: power-controller@1e0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_09"; + apple,auto-managed; + }; + + ps_dcs_10: power-controller@1f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_10"; + apple,auto-managed; + }; + + ps_dcs_11: power-controller@200 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x200 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_11"; + apple,auto-managed; + }; + + ps_dcs_16: power-controller@210 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x210 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_16"; + apple,auto-managed; + }; + + ps_dcs_17: power-controller@220 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x220 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_17"; + apple,auto-managed; + }; + + ps_dcs_18: power-controller@230 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x230 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_18"; + apple,auto-managed; + }; + + ps_dcs_19: power-controller@240 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x240 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_19"; + apple,auto-managed; + }; + + ps_dcs_24: power-controller@250 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x250 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_24"; + apple,auto-managed; + }; + + ps_dcs_25: power-controller@260 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x260 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_25"; + apple,auto-managed; + }; + + ps_dcs_26: power-controller@270 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x270 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_26"; + apple,auto-managed; + }; + + ps_fab_gw_0: power-controller@288 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x288 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab_gw_0"; + apple,always-on; + apple,auto-managed; + }; + + ps_fab_gw_1: power-controller@290 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x290 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab_gw_1"; + apple,always-on; + apple,auto-managed; + }; + + ps_fab_afr: power-controller@298 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x298 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab_afr"; + apple,always-on; + apple,auto-managed; + }; + + ps_fab1_soc: power-controller@2d0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab1_soc"; + power-domains = <&ps_afi>; + apple,always-on; + apple,auto-managed; + }; + + ps_fab2_soc: power-controller@338 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x338 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab2_soc"; + power-domains = <&ps_afi>; + apple,always-on; + apple,auto-managed; + }; + + ps_fab5_soc: power-controller@440 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x440 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab5_soc"; + power-domains = <&ps_afi>; + apple,always-on; + apple,auto-managed; + }; + + ps_fab7_soc: power-controller@488 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x488 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab7_soc"; + power-domains = <&ps_afi>; + apple,always-on; + apple,auto-managed; + }; + + /* dcs_27 sits at +0x530 rather than adjacent to dcs_26 (+0x280 is amcc27). */ + ps_dcs_27: power-controller@530 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x530 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_27"; + apple,auto-managed; + }; +}; + +&ps_fab6_soc { + apple,auto-managed; +}; + +&pmgr { + ps_fab4_soc: power-controller@128 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x128 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab4_soc"; + power-domains = <&ps_afc>; + apple,always-on; + apple,auto-managed; + }; + + ps_dcs_04: power-controller@2e0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_04"; + apple,auto-managed; + }; + + ps_dcs_05: power-controller@2e8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2e8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_05"; + apple,auto-managed; + }; + + ps_dcs_06: power-controller@2f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_06"; + apple,auto-managed; + }; + + ps_dcs_07: power-controller@2f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2f8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_07"; + apple,auto-managed; + }; + + ps_dcs_12: power-controller@300 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x300 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_12"; + apple,auto-managed; + }; + + ps_dcs_13: power-controller@308 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x308 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_13"; + apple,auto-managed; + }; + + ps_dcs_14: power-controller@310 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x310 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_14"; + apple,auto-managed; + }; + + ps_dcs_15: power-controller@318 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x318 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_15"; + apple,auto-managed; + }; + + ps_dcs_20: power-controller@320 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x320 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_20"; + apple,auto-managed; + }; + + ps_dcs_21: power-controller@328 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x328 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_21"; + apple,auto-managed; + }; + + ps_dcs_22: power-controller@330 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x330 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_22"; + apple,auto-managed; + }; + + ps_dcs_23: power-controller@338 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x338 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_23"; + apple,auto-managed; + }; + + ps_dcs_28: power-controller@340 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x340 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_28"; + apple,auto-managed; + }; + + ps_dcs_29: power-controller@348 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x348 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_29"; + apple,auto-managed; + }; + + ps_dcs_30: power-controller@350 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x350 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_30"; + apple,auto-managed; + }; + + ps_dcs_31: power-controller@358 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x358 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_31"; + apple,auto-managed; + }; +}; + +&ps_fab3_soc { + apple,auto-managed; +}; + +&pmgr_mini { + ps_nub_fabric: power-controller@100 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x100 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_fabric"; + apple,always-on; + apple,auto-managed; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t6041-sleep-pmgr.dtsi b/arch/arm64/boot/dts/apple/t6041-sleep-pmgr.dtsi new file mode 100644 index 00000000000000..82d293e918fd81 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6041-sleep-pmgr.dtsi @@ -0,0 +1,1850 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * Additional Apple T6041 ("M4 Max") PMGR power states used by suspend-to-RAM + * and display power-domain chains, beyond the nodes already described in + * t6041.dtsi, t604x-pmgr.dtsi, t6041-pmgr.dtsi (hardware auto-managed + * DCS/fabrics) and t6041-j614-j616-j575-scaler.dtsi. + * + * Offsets and parent links are verified against the J616c ADT (/arm-io/pmgr + * devices and ps-groups). Every newly added node stays disabled so + * apple-pmgr-pwrstate never probes or powers down firmware-owned blocks; + * boards enable nodes that have Linux consumers (such as ps_uart_p, ps_dpa_p, + * ps_dpa1 and ps_dpa2 on J614c/J616c). + * + * Copyright The Asahi Linux Contributors + */ + +&pmgr { + ps_apcie_gp: power-controller@100 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x100 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "apcie_gp"; + status = "disabled"; + }; + + ps_fpwm1: power-controller@140 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x140 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fpwm1"; + power-domains = <&ps_sio>; + status = "disabled"; + }; + + ps_fpwm2: power-controller@148 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x148 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fpwm2"; + power-domains = <&ps_sio>; + status = "disabled"; + }; + + ps_i2c0: power-controller@150 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x150 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "i2c0"; + power-domains = <&ps_sio>; + status = "disabled"; + }; + + ps_i2c5: power-controller@178 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x178 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "i2c5"; + power-domains = <&ps_sio>; + status = "disabled"; + }; + + ps_i2c7: power-controller@188 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x188 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "i2c7"; + power-domains = <&ps_sio>; + status = "disabled"; + }; + + ps_uart_p: power-controller@1a0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart_p"; + power-domains = <&ps_sio>; + status = "disabled"; + }; + + ps_dpa_p: power-controller@1a8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1a8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpa_p"; + power-domains = <&ps_sio>; + apple,always-on; + status = "disabled"; + }; + + ps_spi0: power-controller@1b8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1b8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "spi0"; + power-domains = <&ps_spi_p>; + status = "disabled"; + }; + + ps_spi1: power-controller@1c0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "spi1"; + power-domains = <&ps_spi_p>; + status = "disabled"; + }; + + ps_spi3: power-controller@1d0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "spi3"; + power-domains = <&ps_spi_p>; + status = "disabled"; + }; + + ps_spi4: power-controller@1d8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "spi4"; + power-domains = <&ps_spi_p>; + status = "disabled"; + }; + + ps_spi5: power-controller@1e0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "spi5"; + power-domains = <&ps_spi_p>; + status = "disabled"; + }; + + ps_uart_n: power-controller@1f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart_n"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart0: power-controller@1f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1f8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart0"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart1: power-controller@200 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x200 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart1"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart2: power-controller@208 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x208 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart2"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart3: power-controller@210 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x210 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart3"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart4: power-controller@218 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x218 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart4"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart5: power-controller@220 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x220 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart5"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart6: power-controller@228 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x228 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart6"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_dpa0: power-controller@230 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x230 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpa0"; + power-domains = <&ps_dpa_p>; + status = "disabled"; + }; + + ps_dpa1: power-controller@238 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x238 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpa1"; + power-domains = <&ps_dpa_p>; + status = "disabled"; + }; + + ps_dpa2: power-controller@240 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x240 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpa2"; + power-domains = <&ps_dpa_p>; + status = "disabled"; + }; + + ps_dpa3: power-controller@248 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x248 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpa3"; + power-domains = <&ps_dpa_p>; + status = "disabled"; + }; + + ps_dpa4: power-controller@250 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x250 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpa4"; + power-domains = <&ps_dpa_p>; + status = "disabled"; + }; + + ps_disp_sys: power-controller@258 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x258 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_sys"; + power-domains = <&ps_fab6_soc>; + status = "disabled"; + }; + + ps_amcc4: power-controller@260 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x260 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc4"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc5: power-controller@268 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x268 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc5"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc6: power-controller@270 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x270 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc6"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc7: power-controller@278 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x278 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc7"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc12: power-controller@280 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x280 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc12"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc13: power-controller@288 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x288 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc13"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc14: power-controller@290 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x290 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc14"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc15: power-controller@298 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x298 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc15"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc20: power-controller@2a0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc20"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc21: power-controller@2a8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2a8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc21"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc22: power-controller@2b0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2b0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc22"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc23: power-controller@2b8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2b8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc23"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc28: power-controller@2c0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc28"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc29: power-controller@2c8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2c8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc29"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc30: power-controller@2d0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc30"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc31: power-controller@2d8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc31"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_disp_fe: power-controller@368 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x368 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_fe"; + power-domains = <&ps_disp_sys>; + status = "disabled"; + }; + + ps_apcie_sys_gp: power-controller@390 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x390 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "apcie_sys_gp"; + power-domains = <&ps_fab3_soc>, <&ps_apcie_gp>; + status = "disabled"; + }; + + ps_apcie_phy_sw: power-controller@398 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x398 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "apcie_phy_sw"; + power-domains = <&ps_apcie_sys_st0>, <&ps_apcie_sys_st1>, + <&ps_apcie_sys_gp>; + status = "disabled"; + }; + + ps_prores: power-controller@3a8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3a8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "prores"; + power-domains = <&ps_fab6_soc>; + status = "disabled"; + }; +}; + +&pmgr_disp { + ps_disp_cpu: power-controller@0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_cpu"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_spi: power-controller@8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_spi"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_spmi: power-controller@10 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x10 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_spmi"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_dbe: power-controller@18 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x18 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_dbe"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_dp: power-controller@20 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x20 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dp"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_gp0: power-controller@28 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x28 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_gp0"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_gp1: power-controller@30 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x30 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_gp1"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_gpl: power-controller@38 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x38 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_gpl"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_cmb: power-controller@40 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x40 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_cmb"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_ppp: power-controller@48 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x48 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_ppp"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_brc: power-controller@50 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x50 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_brc"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_blc: power-controller@58 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x58 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_blc"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; +}; + +&pmgr_aux { + ps_ecpu_0: power-controller@0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ecpu_0"; + status = "disabled"; + }; + + ps_ecpu_1: power-controller@8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ecpu_1"; + status = "disabled"; + }; + + ps_ecpu_2: power-controller@10 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x10 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ecpu_2"; + status = "disabled"; + }; + + ps_ecpu_3: power-controller@18 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x18 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ecpu_3"; + status = "disabled"; + }; + + ps_pcpu0_0: power-controller@20 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x20 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu0_0"; + status = "disabled"; + }; + + ps_pcpu0_1: power-controller@28 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x28 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu0_1"; + status = "disabled"; + }; + + ps_pcpu0_2: power-controller@30 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x30 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu0_2"; + status = "disabled"; + }; + + ps_pcpu0_3: power-controller@38 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x38 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu0_3"; + status = "disabled"; + }; + + ps_pcpu0_4: power-controller@40 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x40 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu0_4"; + status = "disabled"; + }; + + ps_pcpu0_5: power-controller@48 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x48 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu0_5"; + status = "disabled"; + }; + + ps_pcpu1_0: power-controller@50 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x50 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu1_0"; + status = "disabled"; + }; + + ps_pcpu1_1: power-controller@58 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x58 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu1_1"; + status = "disabled"; + }; + + ps_pcpu1_2: power-controller@60 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x60 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu1_2"; + status = "disabled"; + }; + + ps_pcpu1_3: power-controller@68 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x68 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu1_3"; + status = "disabled"; + }; + + ps_pcpu1_4: power-controller@70 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x70 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu1_4"; + status = "disabled"; + }; + + ps_pcpu1_5: power-controller@78 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x78 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu1_5"; + status = "disabled"; + }; + + ps_ecpm: power-controller@80 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x80 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ecpm"; + status = "disabled"; + }; + + ps_pcpm0: power-controller@88 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x88 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpm0"; + status = "disabled"; + }; + + ps_pcpm1: power-controller@90 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x90 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpm1"; + status = "disabled"; + }; + + ps_dwi: power-controller@108 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x108 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dwi"; + status = "disabled"; + }; + + ps_aic: power-controller@118 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x118 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "aic"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pmc: power-controller@120 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x120 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pmc"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pms_c1ppt: power-controller@128 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x128 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pms_c1ppt"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_soc_dpe: power-controller@130 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x130 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "soc_dpe"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pmgr_soc_ocla: power-controller@138 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x138 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pmgr_soc_ocla"; + status = "disabled"; + }; + + ps_pms_fpwm0: power-controller@140 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x140 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pms_fpwm0"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pms_fpwm1: power-controller@148 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x148 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pms_fpwm1"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pms_fpwm2: power-controller@150 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x150 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pms_fpwm2"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pms_fpwm3: power-controller@158 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x158 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pms_fpwm3"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pms_fpwm4: power-controller@160 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x160 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pms_fpwm4"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_amcc0: power-controller@180 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x180 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc0"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_rom: power-controller@190 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x190 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "rom"; + power-domains = <&ps_amcc0>; + status = "disabled"; + }; + + ps_amcc1: power-controller@198 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x198 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc1"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc2: power-controller@1a8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1a8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc2"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc3: power-controller@1b8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1b8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc3"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc8: power-controller@1c8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1c8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc8"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc9: power-controller@1d8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc9"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc10: power-controller@1e8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1e8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc10"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc11: power-controller@1f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1f8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc11"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc16: power-controller@208 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x208 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc16"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc17: power-controller@218 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x218 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc17"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc18: power-controller@228 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x228 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc18"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc19: power-controller@238 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x238 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc19"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc24: power-controller@248 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x248 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc24"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc25: power-controller@258 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x258 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc25"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc26: power-controller@268 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x268 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc26"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc27: power-controller@280 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x280 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc27"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_dispext3_sys: power-controller@2d8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_sys"; + power-domains = <&ps_fab1_soc>; + status = "disabled"; + }; + + ps_dispext3_fe: power-controller@2e0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_fe"; + power-domains = <&ps_dispext3_sys>; + status = "disabled"; + }; + + ps_dispext3_cpu: power-controller@2e8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2e8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_cpu"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dispext3_dbe: power-controller@2f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_dbe"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dpext3: power-controller@2f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2f8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpext3"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dispext3_gp0: power-controller@300 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x300 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_gp0"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dispext3_gp1: power-controller@308 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x308 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_gp1"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dispext3_gpl: power-controller@310 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x310 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_gpl"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dispext3_ppp: power-controller@318 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x318 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_ppp"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dispext3_dsc: power-controller@320 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x320 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_dsc"; + power-domains = <&ps_dispext3_dbe>; + status = "disabled"; + }; + + ps_dispext0_sys: power-controller@340 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x340 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_sys"; + power-domains = <&ps_fab2_soc>; + status = "disabled"; + }; + + ps_dispext0_fe: power-controller@348 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x348 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_fe"; + power-domains = <&ps_dispext0_sys>; + status = "disabled"; + }; + + ps_dispext0_cpu: power-controller@350 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x350 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_cpu"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dispext0_dbe: power-controller@358 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x358 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_dbe"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dpext0: power-controller@360 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x360 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpext0"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dispext0_gp0: power-controller@368 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x368 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_gp0"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dispext0_gp1: power-controller@370 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x370 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_gp1"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dispext0_gpl: power-controller@378 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x378 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_gpl"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dispext0_ppp: power-controller@380 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x380 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_ppp"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dispext0_dsc: power-controller@388 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x388 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_dsc"; + power-domains = <&ps_dispext0_dbe>; + status = "disabled"; + }; + + ps_atc0_cio: power-controller@398 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x398 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_cio"; + power-domains = <&ps_atc0_common>; + status = "disabled"; + }; + + ps_atc0_pcie: power-controller@3a0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_pcie"; + power-domains = <&ps_atc0_common>; + status = "disabled"; + }; + + ps_atc0_cio_pcie: power-controller@3a8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3a8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_cio_pcie"; + power-domains = <&ps_atc0_cio>; + status = "disabled"; + }; + + ps_atc0_cio_usb: power-controller@3b0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3b0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_cio_usb"; + power-domains = <&ps_atc0_cio>; + status = "disabled"; + }; + + ps_atc1_cio: power-controller@3c0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_cio"; + power-domains = <&ps_atc1_common>; + status = "disabled"; + }; + + ps_atc1_pcie: power-controller@3c8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3c8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_pcie"; + power-domains = <&ps_atc1_common>; + status = "disabled"; + }; + + ps_atc1_cio_pcie: power-controller@3d0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_cio_pcie"; + power-domains = <&ps_atc1_cio>; + status = "disabled"; + }; + + ps_atc1_cio_usb: power-controller@3d8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_cio_usb"; + power-domains = <&ps_atc1_cio>; + status = "disabled"; + }; + + ps_atc2_cio: power-controller@3e8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3e8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_cio"; + power-domains = <&ps_atc2_common>; + status = "disabled"; + }; + + ps_atc2_pcie: power-controller@3f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_pcie"; + power-domains = <&ps_atc2_common>; + status = "disabled"; + }; + + ps_atc2_cio_pcie: power-controller@3f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3f8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_cio_pcie"; + power-domains = <&ps_atc2_cio>; + status = "disabled"; + }; + + ps_atc2_cio_usb: power-controller@400 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x400 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_cio_usb"; + power-domains = <&ps_atc2_cio>; + status = "disabled"; + }; + + ps_atc3_cio: power-controller@420 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x420 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_cio"; + power-domains = <&ps_atc3_common>; + status = "disabled"; + }; + + ps_atc3_pcie: power-controller@428 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x428 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_pcie"; + power-domains = <&ps_atc3_common>; + status = "disabled"; + }; + + ps_atc3_cio_pcie: power-controller@430 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x430 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_cio_pcie"; + power-domains = <&ps_atc3_cio>; + status = "disabled"; + }; + + ps_atc3_cio_usb: power-controller@438 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x438 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_cio_usb"; + power-domains = <&ps_atc3_cio>; + status = "disabled"; + }; + + ps_sbr: power-controller@448 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x448 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "sbr"; + power-domains = <&ps_fab5_soc>; + status = "disabled"; + }; + + ps_gpio: power-controller@450 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x450 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "gpio"; + power-domains = <&ps_sbr>; + status = "disabled"; + }; + + ps_msg: power-controller@458 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x458 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "msg"; + power-domains = <&ps_sbr>; + status = "disabled"; + }; + + ps_ap_tmm: power-controller@468 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x468 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ap_tmm"; + power-domains = <&ps_sbr>; + status = "disabled"; + }; + + ps_dispext1_sys: power-controller@490 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x490 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_sys"; + power-domains = <&ps_fab7_soc>; + status = "disabled"; + }; + + ps_dispext1_fe: power-controller@498 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x498 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_fe"; + power-domains = <&ps_dispext1_sys>; + status = "disabled"; + }; + + ps_dispext1_cpu: power-controller@4a0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_cpu"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dispext1_dbe: power-controller@4a8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4a8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_dbe"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dpext1: power-controller@4b0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4b0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpext1"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dispext1_gp0: power-controller@4b8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4b8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_gp0"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dispext1_gp1: power-controller@4c0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_gp1"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dispext1_gpl: power-controller@4c8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4c8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_gpl"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dispext1_ppp: power-controller@4d0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_ppp"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dispext1_dsc: power-controller@4d8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_dsc"; + power-domains = <&ps_dispext1_dbe>; + status = "disabled"; + }; + + ps_dispext2_sys: power-controller@4e0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_sys"; + power-domains = <&ps_fab7_soc>; + status = "disabled"; + }; + + ps_dispext2_fe: power-controller@4e8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4e8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_fe"; + power-domains = <&ps_dispext2_sys>; + status = "disabled"; + }; + + ps_dispext2_cpu: power-controller@4f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_cpu"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dispext2_dbe: power-controller@4f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4f8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_dbe"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dpext2: power-controller@500 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x500 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpext2"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dispext2_gp0: power-controller@508 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x508 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_gp0"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dispext2_gp1: power-controller@510 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x510 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_gp1"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dispext2_gpl: power-controller@518 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x518 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_gpl"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dispext2_ppp: power-controller@520 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x520 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_ppp"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dispext2_dsc: power-controller@528 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x528 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_dsc"; + power-domains = <&ps_dispext2_dbe>; + status = "disabled"; + }; +}; + +&pmgr_mini { + ps_debug_gated: power-controller@0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "debug_gated"; + status = "disabled"; + }; + + ps_nub_spmi_ahb: power-controller@58 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x58 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi_ahb"; + status = "disabled"; + }; + + ps_nub_spmi0: power-controller@60 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x60 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi0"; + power-domains = <&ps_nub_spmi_ahb>; + status = "disabled"; + }; + + ps_nub_spmi_a2: power-controller@78 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x78 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi_a2"; + status = "disabled"; + }; + + ps_nub_spi0: power-controller@80 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x80 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spi0"; + status = "disabled"; + }; + + ps_nub_aon: power-controller@88 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x88 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_aon"; + status = "disabled"; + }; + + ps_nub_ocla: power-controller@98 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x98 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_ocla"; + status = "disabled"; + }; + + ps_nub_spmi1: power-controller@c0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xc0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi1"; + power-domains = <&ps_nub_spmi_ahb>; + status = "disabled"; + }; + + ps_nub_spmi2: power-controller@e8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xe8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi2"; + power-domains = <&ps_nub_spmi_ahb>; + status = "disabled"; + }; + + ps_nub_spmi3: power-controller@f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xf0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi3"; + power-domains = <&ps_nub_spmi_ahb>; + status = "disabled"; + }; + + ps_nub_spmi4: power-controller@f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xf8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi4"; + power-domains = <&ps_nub_spmi_ahb>; + status = "disabled"; + }; + + ps_nub_sram: power-controller@108 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x108 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_sram"; + power-domains = <&ps_nub_fabric>; + status = "disabled"; + }; + + ps_debug_switch: power-controller@110 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x110 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "debug_switch"; + status = "disabled"; + }; +}; + +&pmgr_gfx { + ps_gpx: power-controller@0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "gpx"; + status = "disabled"; + }; +}; + +/* + * Parent-domain links absent from t604x-pmgr.dtsi (matching t6040-pmgr.dtsi, + * plus ps_atc3_common_dp -> ps_atc3_phymxwrap matching ps_atc0..2_common_dp). + * Every parent referenced here is enabled whenever its child is enabled. + */ +&ps_avd_sys { + power-domains = <&ps_fab0_soc>; +}; + +&ps_atc0_common { + power-domains = <&ps_fab2_soc>; +}; + +&ps_atc1_common { + power-domains = <&ps_fab2_soc>; +}; + +&ps_atc2_common { + power-domains = <&ps_fab2_soc>; +}; + +&ps_atc3_common { + power-domains = <&ps_fab2_soc>; +}; + +&ps_atc3_common_dp { + power-domains = <&ps_atc3_phymxwrap>; +}; + +&ps_ane_sys { + power-domains = <&ps_fab5_soc>, <&ps_fab4_soc>; +}; + +&ps_pmp { + power-domains = <&ps_pms>; +}; + +&ps_pms_sram { + power-domains = <&ps_pms>; +}; + +&ps_jpg { + power-domains = <&ps_fab4_soc>; +}; + +&ps_venc0_sys { + power-domains = <&ps_fab0_soc>; +}; + +&ps_venc1_sys { + power-domains = <&ps_fab0_soc>; +}; diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index 4c5719bc056051..837aeb8177e04b 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -9,7 +9,35 @@ &avd { compatible = "apple,t6041-max-avd", "apple,t6041-avd", "apple,t8132-avd"; - power-domains = <&ps_avd_sys>; + power-domains = <&ps_avd_sys>, <&pmc_soc_max>; + power-domain-names = "core", "perf"; +}; + +&ave { + power-domains = <&ps_venc0_dma>, <&ps_venc0_pipe4>, + <&ps_venc0_pipe5>, <&ps_venc0_me0>, <&ps_venc0_me1>, + <&pmc_soc_max>; + power-domain-names = "dma", "pipe4", "pipe5", "me0", "me1", "perf"; +}; + +/* The loader supplies the ANE firmware and reservations. */ +&ane0_dart0 { + status = "okay"; +}; + +&ane0_dart1 { + status = "okay"; +}; + +&ane0_dart2 { + status = "okay"; +}; + +&ane { + status = "okay"; + power-domains = <&ps_ane_sys>, <&ps_ane_cpu>, <&ps_ane_mpm>, + <&ps_ane_td>, <&ps_ane_base>, <&pmc_soc_max>; + power-domain-names = "sys", "cpu", "mpm", "td", "base", "perf"; }; /* @@ -339,10 +367,37 @@ &pmc { #cooling-cells = <2>; apple,static-voters = <1 3>; + + /* + * SoC fabric rail floor (rail 1, AP voter agent 3). T6041 has four + * SOC states (0-3; ADT pmp dvfs-domain and pmgr voltage-states0/28/29): + * state 2 (VMAX, 815 mV) already reaches the maximum SOC_AFC clock + * (2004 MHz) and matches ADT AVD-SOC-VMAX and VENC0-SOC-VMAX; state 3 + * (VOVD, 820 mV) only raises SOC_AFI (975 -> 1300 MHz) and is voted by + * CLPC for CPU/GPU demand. + */ + pmc_soc_max: floor-soc-max { + label = "soc-vmax"; + #power-domain-cells = <0>; + apple,rail = <1>; + apple,level = <2>; + }; }; +/* + * The GPU's memory states by the busy share the GPU driver reports, measured + * on a J616c: DCS 1, 2, 4 or 5 and fabric 0, 0, 0 or 3, split at 160, 500 + * and 800 permille, and the top column with no share reported. The top + * column matches apple_clpc_hw_t6041's DCS 5 / fabric 3 floor (full memory + * bandwidth), so busy GPU work keeps it; light work such as scrolling a + * browser gets the lower columns. With a 3 GB/s copy: DCS 0 / fabric 0 + * 5.46 W at 309 ns DRAM latency, DCS 3 6.22 W at 166 ns, DCS 4 6.92 W at + * 114 ns, DCS 5 7.04 W at 113 ns. + */ &clpc { compatible = "apple,t6041-max-clpc", "apple,t6041-clpc"; + apple,gpu-busy-memory-states = <1 2 4 5>, <0 0 0 3>; + apple,gpu-busy-permille = <160 500 800>; }; / { @@ -445,6 +500,198 @@ #address-cells = <0>; status = "disabled"; }; + + pmgr_disp: power-management@502290000 { + compatible = "apple,t6041-pmgr", "apple,t8103-pmgr", "syscon", "simple-mfd"; + reg = <0x5 0x02290000 0x0 0x4000>; + #address-cells = <1>; + #size-cells = <1>; + }; + + /* + * The CPU power-gate enables, in /arm-io/pmgr at 0x50282c000, one word + * per core: E core 0 at +0x0 and P0 core 0 (the boot core) at +0x40, + * matching the two wake gates t6041-sleep restores on resume. iBoot + * leaves the boot core's word clear, so P0 never powers down in WFI + * unless set early in boot. + */ + cluster_pwrgate: power-gate@50282c000 { + compatible = "apple,t6041-cluster-pwrgate", "apple,cluster-pwrgate"; + reg = <0x5 0x0282c000 0x0 0x4>, + <0x5 0x0282c040 0x0 0x4>; + }; + + /* + * Suspend-to-RAM at EL2 through aura's S2R mailbox; without the mailbox + * it stays out. Stays disabled at the SoC level so boards without + * qualified deep sleep (such as J575c) remain on s2idle; qualified board + * trees wire apple,apcie and apple,atc-phys and enable it. + */ + t6041_sleep: sleep-controller@508304000 { + compatible = "apple,t6041-sleep"; + reg = <0x5 0x08304000 0x0 0x4000>, + <0x5 0x02820000 0x0 0x4000>, + <0x5 0x0282c000 0x0 0x4000>, + <0x5 0x02888000 0x0 0x4000>, + <0x5 0x0836c000 0x0 0x4000>, + <0x5 0x08330000 0x0 0x4000>, + <0x5 0x08904000 0x0 0x4>, + <0x5 0x00038000 0x0 0x4000>, + <0x5 0x029dc000 0x0 0x880>, + <0x5 0x022d0000 0x0 0x880>, + <0x5 0x04800000 0x0 0xb0000>, + <0x5 0x003c0000 0x0 0x20000>, + <0x5 0x0020c000 0x0 0x800>, + <0x5 0x08004000 0x0 0x58>, + <0x2 0x20000000 0x0 0x200000>, + <0x2 0x22000000 0x0 0x200000>, + <0x2 0x24000000 0x0 0x200000>, + <0x2 0x26000000 0x0 0x200000>, + <0x2 0x28000000 0x0 0x200000>, + <0x2 0x2a000000 0x0 0x200000>, + <0x2 0x2c000000 0x0 0x200000>, + <0x2 0x2e000000 0x0 0x200000>, + <0x2 0x20200000 0x0 0x601000>, + <0x2 0x22200000 0x0 0x601000>, + <0x2 0x24200000 0x0 0x601000>, + <0x2 0x26200000 0x0 0x601000>, + <0x2 0x28200000 0x0 0x601000>, + <0x2 0x2a200000 0x0 0x601000>, + <0x2 0x2c200000 0x0 0x601000>, + <0x2 0x2e200000 0x0 0x601000>, + <0x4 0x03000100 0x0 0x10>, + <0x3 0xa3000100 0x0 0x10>, + <0x6 0x03000100 0x0 0x10>, + <0x6 0x07000100 0x0 0x10>, + <0x3 0x07000100 0x0 0x10>, + <0x4 0x0b000100 0x0 0x10>, + <0x2 0x80000100 0x0 0x10>, + <0x2 0x82000100 0x0 0x10>, + <0x2 0x84000100 0x0 0x10>, + <0x4 0x86000100 0x0 0x10>; + reg-names = "ps-aop", + "cluster", "pwrgate", "cpu-start", "wdt", + "aon-misc", "commit", "clk-mux", "ka-pmgr", + "ka-east", "pmc", "ptd", "perf", "wake", + "amcc0", "amcc1", "amcc2", "amcc3", + "amcc4", "amcc5", "amcc6", "amcc7", + "dcs0", "dcs1", "dcs2", "dcs3", + "dcs4", "dcs5", "dcs6", "dcs7", + "axi2af-disp", "axi2af-dispext0", + "axi2af-dispext1", "axi2af-dispext2", + "axi2af-dispext3", "axi2af-ans", + "axi2af-avd", "axi2af-venc0", + "axi2af-venc1", "axi2af-jpg"; + apple,pinctrl = <&pinctrl>; + apple,pinctrl-skip-pins = <190 191 192>; + apple,spmi-buses = <&nub_spmi0>, <&nub_spmi_a0>; + /* ADT ap-wake-sources unmasked across S2R */ + apple,wake-enable = <13 15 25 27 28 41 44 48 50 51 52 53 55 + 101 106 126 127 128 129 130 131 132 133 + 155 167>; + apple,sleep-off-domains = <&ps_venc1_me1>, <&ps_venc0_me1>, <&ps_venc1_pipe5>, + <&ps_venc1_pipe4>, <&ps_venc1_me0>, <&ps_venc0_pipe5>, + <&ps_venc0_pipe4>, <&ps_venc0_me0>, <&ps_apcie_phy_sw>, + <&ps_ane_base>, <&ps_venc1_dma>, <&ps_venc0_dma>, + <&ps_scodec_streaming>, <&ps_msr1_ase_core>, + <&ps_msr0_ase_core>, <&ps_apcie_sys_st1>, + <&ps_apcie_sys_st0>, <&ps_apcie_sys_gp>, <&ps_ane_td>, + <&ps_ane_mpm>, <&ps_ane_cpu>, <&ps_gfx>, <&ps_venc1_sys>, + <&ps_venc0_sys>, <&ps_spi5>, <&ps_spi4>, <&ps_spi3>, + <&ps_spi2>, <&ps_spi1>, <&ps_spi0>, <&ps_scodec>, + <&ps_rom>, <&ps_qspi>, <&ps_prores>, <&ps_pms_fpwm4>, + <&ps_pms_fpwm3>, <&ps_pms_fpwm2>, <&ps_pms_fpwm1>, + <&ps_pms_fpwm0>, <&ps_pmgr_soc_ocla>, <&ps_nub_spi0>, + <&ps_nub_ocla>, <&ps_msr1>, <&ps_msr0>, <&ps_msg>, + <&ps_jpg>, <&ps_ispsens0>, <&ps_isp_sys>, <&ps_i2c8>, + <&ps_i2c7>, <&ps_i2c6>, <&ps_i2c5>, <&ps_i2c4>, + <&ps_i2c3>, <&ps_i2c2>, <&ps_i2c1>, <&ps_i2c0>, + <&ps_fpwm2>, <&ps_fpwm1>, <&ps_fpwm0>, <&ps_dpa4>, + <&ps_dpa3>, <&ps_dpa2>, <&ps_dpa1>, <&ps_dpa0>, + <&ps_avd_sys>, <&ps_ans>, <&ps_apcie_st1>, + <&ps_apcie_st0>, <&ps_apcie_gp>, <&ps_ap_tmm>, + <&ps_ane_sys>, <&ps_afr>; + apple,atc-off-domains = <&ps_atc0_phymxwrap>, <&ps_atc1_phymxwrap>, + <&ps_atc2_phymxwrap>, <&ps_atc3_phymxwrap>, + <&ps_atc0_usb>, <&ps_atc1_usb>, + <&ps_atc2_usb>, <&ps_atc3_usb>, + <&ps_atc0_usb_aon>, <&ps_atc1_usb_aon>, + <&ps_atc2_usb_aon>, <&ps_atc3_usb_aon>, + <&ps_atc0_common_dp>, <&ps_atc1_common_dp>, + <&ps_atc2_common_dp>, <&ps_atc3_common_dp>, + <&ps_atc0_cio_usb>, <&ps_atc0_cio_pcie>, + <&ps_atc0_pcie>, <&ps_atc0_cio>, + <&ps_atc1_cio_usb>, <&ps_atc1_cio_pcie>, + <&ps_atc1_pcie>, <&ps_atc1_cio>, + <&ps_atc2_cio_usb>, <&ps_atc2_cio_pcie>, + <&ps_atc2_pcie>, <&ps_atc2_cio>, + <&ps_atc3_cio_usb>, <&ps_atc3_cio_pcie>, + <&ps_atc3_pcie>, <&ps_atc3_cio>, + <&ps_atc0_common>, <&ps_atc1_common>, + <&ps_atc2_common>, <&ps_atc3_common>; + apple,sleep-auto-domains = <&ps_fab_gw_1>, <&ps_fab_afr>, <&ps_fab4_soc>, + <&ps_amcc4>, <&ps_amcc5>, <&ps_amcc6>, <&ps_amcc7>, + <&ps_amcc12>, <&ps_amcc13>, <&ps_amcc14>, <&ps_amcc15>, + <&ps_amcc20>, <&ps_amcc21>, <&ps_amcc22>, <&ps_amcc23>, + <&ps_fab0_soc>, <&ps_amcc0>, <&ps_amcc1>, <&ps_amcc2>, + <&ps_amcc3>, <&ps_amcc8>, <&ps_amcc9>, <&ps_amcc10>, + <&ps_amcc11>, <&ps_amcc16>, <&ps_amcc17>, <&ps_amcc18>, + <&ps_amcc19>, <&ps_fab1_soc>, <&ps_fab6_soc>, + <&ps_fab7_soc>, <&ps_nub_sram>, <&ps_dcs_23>, <&ps_sep>, + <&ps_dcs_19>, <&ps_amcc24>, <&ps_amcc25>, <&ps_amcc26>, + <&ps_amcc27>, <&ps_amcc28>, <&ps_amcc29>, <&ps_amcc30>, + <&ps_amcc31>; + apple,sleep-auto-clkgate-domains = <&ps_nub_spmi_a0>, <&ps_nub_spmi_a1>, + <&ps_nub_spmi_a2>, <&ps_fab3_soc>, <&ps_pmc>, + <&ps_nub_spmi0>, <&ps_nub_spmi1>, + <&ps_nub_spmi2>, <&ps_nub_spmi3>, + <&ps_nub_spmi4>, <&ps_dcs_04>, <&ps_dcs_06>, + <&ps_dcs_07>, <&ps_dcs_12>, <&ps_dcs_13>, + <&ps_dcs_14>, <&ps_dcs_15>, <&ps_dcs_20>, + <&ps_dcs_21>, <&ps_dcs_22>, <&ps_dcs_00>, + <&ps_dcs_01>, <&ps_dcs_02>, <&ps_dcs_03>, + <&ps_dcs_08>, <&ps_dcs_09>, <&ps_dcs_10>, + <&ps_dcs_16>, <&ps_dcs_17>, <&ps_dcs_18>, + <&ps_dcs_24>, <&ps_dcs_25>, <&ps_dcs_26>, + <&ps_dcs_27>, <&ps_dcs_28>, <&ps_dcs_29>, + <&ps_dcs_30>, <&ps_dcs_31>; + apple,sleep-auto-active-domains = <&ps_gpx>, <&ps_pms>, <&ps_afi>, <&ps_afc>, + <&ps_fab_gw_0>, <&ps_debug_gated>, <&ps_nub_aon>, + <&ps_nub_fabric>, <&ps_debug_switch>, + <&ps_fab2_soc>, <&ps_pmp>, <&ps_pms_sram>, + <&ps_fab5_soc>, <&ps_dcs_05>, <&ps_dcs_11>, + <&ps_sbr>; + apple,sleep-keep-on-domains = <&ps_dwi>, <&ps_nub_spmi_ahb>, <&ps_nub_gpio>, + <&ps_aic>, <&ps_pms_c1ppt>, <&ps_soc_dpe>, <&ps_sio>, + <&ps_sio_cpu>, <&ps_spi_p>, <&ps_uart_p>, <&ps_dpa_p>, + <&ps_aes>, <&ps_gpio>, <&ps_uart_n>, <&ps_uart0>, + <&ps_uart1>, <&ps_uart2>, <&ps_uart3>, <&ps_uart4>, + <&ps_uart5>, <&ps_uart6>; + apple,cpu-domains = <&ps_ecpu_0>, <&ps_ecpu_1>, <&ps_ecpu_2>, <&ps_ecpu_3>, + <&ps_pcpu0_0>, <&ps_pcpu0_1>, <&ps_pcpu0_2>, <&ps_pcpu0_3>, + <&ps_pcpu0_4>, <&ps_pcpu0_5>, <&ps_pcpu1_0>, <&ps_pcpu1_1>, + <&ps_pcpu1_2>, <&ps_pcpu1_3>, <&ps_pcpu1_4>, <&ps_pcpu1_5>; + apple,cpm-domains = <&ps_ecpm>, <&ps_pcpm0>, <&ps_pcpm1>; + apple,sep-domain = <&ps_sep>; + apple,spmi-a0-domain = <&ps_nub_spmi_a0>; + apple,atc-common-domains = <&ps_atc0_common>, <&ps_atc1_common>, <&ps_atc2_common>, + <&ps_atc3_common>; + apple,atc-fabric-domain = <&ps_fab2_soc>; + apple,atc-afi-domain = <&ps_afi>; + apple,apcie-domains = <&ps_ans>, <&ps_apcie_gp>, <&ps_apcie_sys_gp>, + <&ps_apcie_st0>, <&ps_apcie_sys_st0>, <&ps_apcie_st1>, + <&ps_apcie_sys_st1>, <&ps_apcie_phy_sw>; + apple,commit-sio-domains = <&ps_sio>, <&ps_sio_cpu>; + apple,commit-periph-domains = <&ps_i2c6>, <&ps_i2c3>, <&ps_i2c2>, <&ps_i2c1>, + <&ps_spi2>; + apple,axi2af-domains = <&ps_atc0_common>, <&ps_atc1_common>, <&ps_atc2_common>, + <&ps_atc3_common>, <&ps_disp_sys>, <&ps_dispext0_sys>, + <&ps_dispext1_sys>, <&ps_dispext2_sys>, <&ps_dispext3_sys>, + <&ps_ans>, <&ps_avd_sys>, <&ps_venc0_sys>, <&ps_venc1_sys>, + <&ps_jpg>, <&ps_apcie_sys_gp>; + apple,full-part-detect-domains = <&ps_amcc24>, <&ps_amcc28>; + status = "disabled"; + }; }; &pmgr { @@ -455,7 +702,6 @@ #reset-cells = <0>; label = "aes"; power-domains = <&ps_sio>; - apple,always-on; status = "disabled"; }; }; @@ -537,6 +783,20 @@ opp-microwatt = <531000>; }; +/* + * What the SEP's DART gets around a sleep, as offset and value: the writes T8140's has + * (t8140.dtsi), which the J616C has slept with. The SEP driver saves the DART with them + * before it tells the enclave to sleep at suspend. + */ +&sep_dart { + apple,sleep-prepare = <0x80 0xa102>, <0x704 0xffffffff>; + apple,sleep-restore = <0x210 0x0>, <0x20c 0x800005f5>, + <0x220 0xf0f0f>, <0x224 0x80808>, + <0x300 0x1>, <0x318 0x1>; + apple,sleep-restore-late = <0x80 0x8000>, <0x228 0x3f3f3f3f>, + <0x22c 0x1010101>; +}; + /* * The ISP DART's address filter, from the full-die J616c ADT's dart-isp0 * dapf-instance-0 (its sixth reg window), in the ADT's order: the @@ -581,6 +841,7 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "venc1_sys"; + power-domains = <&ps_fab0_soc>; status = "disabled"; }; @@ -678,6 +939,61 @@ }; }; +/* + * First ProRes engine (ADT /arm-io/apr0) and its DART, from the J616c ADT. + * apr0 sits in the SCODEC block (PMGR bank 0 / pmgr_aux: FAB1_SOC 0x2d0 in + * t6041-pmgr.dtsi, SCODEC 0x328, SCODEC_STREAMING 0x330) with core, wrapper + * and aux windows. + */ +&pmgr_aux { + ps_scodec: power-controller@328 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x328 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "scodec"; + power-domains = <&ps_fab1_soc>; + status = "disabled"; + }; + + ps_scodec_streaming: power-controller@330 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x330 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "scodec_streaming"; + power-domains = <&ps_scodec>; + status = "disabled"; + }; +}; + +/ { + apr0: video-codec@301000000 { + compatible = "apple,t6041-prores", "apple,prores"; + reg = <0x3 0x01000000 0x0 0x4000>, + <0x3 0x00000000 0x0 0x1000000>, + <0x3 0x010c0000 0x0 0x4000>; + reg-names = "core", "wrapper", "aux"; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_scodec_streaming>; + iommus = <&apr0_dart 1>; + resets = <&ps_scodec>; + status = "disabled"; + }; + + apr0_dart: iommu@301020000 { + compatible = "apple,t6041-dart", "apple,t8110-dart"; + reg = <0x3 0x01020000 0x0 0xc000>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_scodec>; + status = "disabled"; + }; +}; + /* * The first video encoder (ADT ave0, soc-id t6040), its DARTs and its power * domains. It has no board wiring, so it is enabled on every M4 Max board. @@ -720,3 +1036,35 @@ &ave { status = "okay"; }; + +#include "t6041-pmgr.dtsi" +#include "t6041-sleep-pmgr.dtsi" + +/* The loader uses this alias to enable SIO after placing its firmware. */ +/ { + aliases { + sio = &sio; + }; +}; + +&ps_uart_p { + status = "okay"; +}; + +&ps_dpa_p { + status = "okay"; +}; + +/* The SIO firmware drives the SPI, UART and DP audio shims: keep their parents on. */ +&ps_sio_cpu { + power-domains = <&ps_sio>, <&ps_spi_p>, <&ps_uart_p>, <&ps_dpa_p>; + status = "okay"; +}; + +&sio_dart { + status = "okay"; +}; + +&sio_mbox { + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi b/arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi index 75df37d6053a61..16884a4c56e11e 100644 --- a/arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi +++ b/arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi @@ -2727,6 +2727,7 @@ #size-cells = <2>; pwren-gpios = <&smc_gpio 0x13 GPIO_ACTIVE_HIGH>; reset-gpios = <&pinctrl 4 GPIO_ACTIVE_LOW>; + supports-clkreq; device_type = "pci"; bluetooth0: bluetooth@0,1 { @@ -3431,6 +3432,7 @@ reset-gpios = <&pinctrl 5 GPIO_ACTIVE_LOW>; bus-range = <2 2>; pwren-gpios = <&smc_gpio 0x19 GPIO_ACTIVE_HIGH>; + supports-clkreq; #address-cells = <3>; #size-cells = <2>; ranges; diff --git a/arch/arm64/boot/dts/apple/t604x-pmgr.dtsi b/arch/arm64/boot/dts/apple/t604x-pmgr.dtsi index 977818bca2ec32..3104e3a8374d31 100644 --- a/arch/arm64/boot/dts/apple/t604x-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t604x-pmgr.dtsi @@ -350,14 +350,17 @@ }; &pmgr_aux { - /* Always on: the firmware leaves ATCn_USB on below it, and genpd refuses an active child under a parent it would turn off. */ + /* + * All USB-C ATC0-2 consumers (dwc3, atcphy, mailbox, DARTs, display + * crossbar, and USB4/CIO where enabled) manage runtime PM; + * ps_atc0..2_usb_aon stay always-on for wake and Type-C detection. + */ ps_atc0_common: power-controller@390 { compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; reg = <0x390 4>; #power-domain-cells = <0>; #reset-cells = <0>; label = "atc0_common"; - apple,always-on; }; ps_atc1_common: power-controller@3b8 { @@ -366,7 +369,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc1_common"; - apple,always-on; }; ps_atc2_common: power-controller@3e0 { @@ -375,7 +377,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc2_common"; - apple,always-on; }; }; @@ -431,6 +432,8 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc0_common_dp"; + /* The PHY coprocessor can keep running through s2idle. */ + apple,sleep-wakeup-path; power-domains = <&ps_atc0_phymxwrap>; }; @@ -467,6 +470,8 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc1_common_dp"; + /* The PHY coprocessor can keep running through s2idle. */ + apple,sleep-wakeup-path; power-domains = <&ps_atc1_phymxwrap>; }; @@ -503,6 +508,8 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc2_common_dp"; + /* The PHY coprocessor can keep running through s2idle. */ + apple,sleep-wakeup-path; power-domains = <&ps_atc2_phymxwrap>; }; }; @@ -578,6 +585,8 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc3_common_dp"; + /* The PHY coprocessor can keep running through s2idle. */ + apple,sleep-wakeup-path; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t604x.dtsi b/arch/arm64/boot/dts/apple/t604x.dtsi index b269473755b871..4db23b8ba7ff28 100644 --- a/arch/arm64/boot/dts/apple/t604x.dtsi +++ b/arch/arm64/boot/dts/apple/t604x.dtsi @@ -1860,10 +1860,10 @@ }; /* - * Disabled until the H16 firmware path is proven on hardware. The - * loader fills the preload reservations and the firmware IOVAs from - * the ADT, so enabling it then only takes status = "okay" here and on - * the three DARTs. + * Off here; each board enables it with its memory-region + * (t6041.dtsi for J575c/J614c/J616c, t604x-j614-j616.dtsi for + * J614s/J616s, and t6040-j773s.dts for J773s). The loader fills + * the preload reservations and firmware IOVAs from the ADT. */ ane: ane@484000000 { compatible = "apple,t6041-ane"; diff --git a/arch/arm64/boot/dts/apple/t6050-base.dtsi b/arch/arm64/boot/dts/apple/t6050-base.dtsi index 323033b71e5653..6a588396cf93ff 100644 --- a/arch/arm64/boot/dts/apple/t6050-base.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-base.dtsi @@ -68,10 +68,18 @@ T6050_CPU(label, mpidr, "apple,everest", pcluster_opp, cluster, 1024, l2, 0x30000, 0x20000) /* - * Caches. Every cluster has its own unified L2, shared by its six cores: the ADT's /cpus/cpuN - * l2-cache-size is 8 MiB on the M-tier (apple,sawtooth) cores and 16 MiB on the P-tier - * (apple,everest) cores in the J714c/s, J716c/s, J775c/d and J873s ADTs, and macOS reports - * hw.perflevelN.cpusperl2 = 6 on both tiers. The L1 sizes are macOS's + * Caches. Every M-tier (apple,sawtooth) cluster has a unified L2 shared by its cores: the ADT's + * /cpus/cpuN l2-cache-size is 8 MiB on those cores in the J714c/s, J716c/s, J775c/d and J873s + * ADTs, and macOS reports hw.perflevelN.cpusperl2 = 6. A P-tier (apple,everest) core has one + * more level: CLIDR_EL1 reports three cache levels there and two on an M-tier core. Each P core + * has a private unified L2 (its size is not established) in front of a 16 MiB unified L3 shared + * by the cluster, which is the cluster cache the ADT lists as the P cores' l2-cache-size. On + * J775c, a dependent-load sweep on one P core is not slowed by a second P core of the same + * cluster running the same sweep up to 512 KiB (private), but is from 8 MiB on (shared, half + * of 16 MiB); a core of an M-tier cluster slows neither. Describing all three levels matches the + * hardware and CLIDR_EL1 (and avoids a CLIDR level-count mismatch if init_cache_level() runs + * without early OF levels). + * The L1 sizes are macOS's * hw.perflevelN.l1icachesize/l1dcachesize: 128 KiB I and 64 KiB D on the M tier, 192 KiB I and * 128 KiB D on the P tier. The system level cache sits behind the memory controllers and is * shared with every agent; it is not part of the CPUs' cache hierarchy and is not described here. @@ -84,7 +92,21 @@ cache-size = ; \ } #define T6050_M_L2(label, name) T6050_L2(label, name, 0x800000) -#define T6050_P_L2(label, name) T6050_L2(label, name, 0x1000000) +/* A P core's private L2, in front of its cluster's L3. */ +#define T6050_P_L2(label, name, l3) \ + label: name { \ + compatible = "cache"; \ + cache-level = <2>; \ + cache-unified; \ + next-level-cache = <&l3>; \ + } +#define T6050_P_L3(label, name) \ + label: name { \ + compatible = "cache"; \ + cache-level = <3>; \ + cache-unified; \ + cache-size = <0x1000000>; \ + } / { compatible = "apple,t6050", "apple,arm-platform"; diff --git a/arch/arm64/boot/dts/apple/t6050-desktop.dtsi b/arch/arm64/boot/dts/apple/t6050-desktop.dtsi new file mode 100644 index 00000000000000..41cbd32d3b431d --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-desktop.dtsi @@ -0,0 +1,189 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * What the T6050 desktops (Mac Studio J775d, Mac mini J873s) share on die 0: the onboard + * Ethernet on PCIe port 2, and rear USB-C ports 1-3 (ATC0-2, their PD controllers on + * nub-spmi-a0 at SPMI addresses 0xc, 0xa and 0x8). Each board's ADT gives the same port, + * bridge, PHY and HPM layout for these; only the connectors' places differ. + * + * The board file includes this before its own &pcie0 and &nub_spmi_a0 nodes (its other root + * ports and HPMs follow these) and defines first: + * T6050_DESKTOP_HPM1_LABEL the label of rear port 2's connector (HPM1, ATC1) + * T6050_DESKTOP_HPM2_LABEL the label of rear port 3's connector (HPM2, ATC2) + * The board sets &pcie0's registers, interrupts, iommu-map and bus-range, and the + * ethernet0 alias through which the boot loader fills the MAC address. + * + * Copyright The Asahi Linux Contributors + */ + +/* + * PCIe port 2: the onboard Ethernet (ADT apcie0/pci-bridge2/lan0). The boot loader powers and + * trains the link and numbers its secondary bus 1. + */ +&pcie0 { + port02: pci@2,0 { + device_type = "pci"; + reg = <0x1000 0 0 0 0>; + bus-range = <1 1>; + apple,link-trained-by-bootloader; + + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &port02 0 0 0 0>, + <0 0 0 2 &port02 0 0 0 1>, + <0 0 0 3 &port02 0 0 0 2>, + <0 0 0 4 &port02 0 0 0 3>; + + /* The controller keeps no MAC address of its own */ + ethernet0: ethernet@0,0 { + reg = <0x10000 0x0 0x0 0x0 0x0>; + /* To be filled by the loader */ + local-mac-address = [00 00 00 00 00 00]; + }; + }; +}; + +&dart_apcie2 { + status = "okay"; +}; + +&nub_spmi_a0 { + /* + * /arm-io/nub-spmi-a0/hpm0: SN201202x (ACE3), SPMI address 0xc, port-number 1. + * Reserved: rear port 1 carries the DFU cable, the host's VDM reboot path and the + * debug console (KIS) through usb-drd0; a probe wakes the controller and sets its + * power state even when polled. No ATC0, usb-drd0 or dart-usb0 node either. + */ + hpm0: usb-pd@c { + compatible = "apple,sn201202x"; + reg = <0xc SPMI_USID>; + status = "disabled"; + }; + + /* /arm-io/nub-spmi-a0/hpm1: SN201202x (ACE3), SPMI address 0xa, port-number 2 */ + hpm1: usb-pd@a { + compatible = "apple,sn201202x"; + reg = <0xa SPMI_USID>; + + connector { + compatible = "usb-c-connector"; + label = T6050_DESKTOP_HPM1_LABEL; + power-role = "dual"; + data-role = "host"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + hpm1_hs: endpoint { + remote-endpoint = <&usb_drd1_hs>; + }; + }; + + port@1 { + reg = <1>; + hpm1_ss: endpoint { + remote-endpoint = <&atc1_phy_ep>; + }; + }; + }; + }; + }; + + /* /arm-io/nub-spmi-a0/hpm2: SN201202x (ACE3), SPMI address 8, port-number 3 */ + hpm2: usb-pd@8 { + compatible = "apple,sn201202x"; + reg = <0x8 SPMI_USID>; + status = "disabled"; + + connector { + compatible = "usb-c-connector"; + label = T6050_DESKTOP_HPM2_LABEL; + power-role = "dual"; + data-role = "dual"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + hpm2_hs: endpoint { + remote-endpoint = <&usb_drd2_hs>; + }; + }; + + port@1 { + reg = <1>; + hpm2_ss: endpoint { + remote-endpoint = <&atc2_phy_ep>; + }; + }; + + port@2 { + reg = <2>; + hpm2_dp: endpoint { + remote-endpoint = <&dcpext0_typec>; + }; + }; + }; + }; + }; +}; + +/* Rear USB-C port 2 (HPM1), USB data: ATC1's combo PHY, usb-drd1 and dart-usb1 */ +&atc1_phy { + port { + atc1_phy_ep: endpoint { + remote-endpoint = <&hpm1_ss>; + }; + }; +}; + +&usb_drd1 { + port { + usb_drd1_hs: endpoint { + remote-endpoint = <&hpm1_hs>; + }; + }; +}; + +/* + * Rear USB-C port 3 (HPM2): DisplayPort out from dcpext0 through ATC2, and USB beside it + * (usb-drd2, dart-usb2). The chain stays disabled: Aura's T6050 display handoff enables what + * dcpext0 references (phys, mux-controls, the PHY's mailbox and power domains, the typec + * route's HPM and its SPMI bus). + */ +&atc2_phy { + port { + atc2_phy_ep: endpoint { + remote-endpoint = <&hpm2_ss>; + }; + }; +}; + +&usb_drd2 { + port { + usb_drd2_hs: endpoint { + remote-endpoint = <&hpm2_hs>; + }; + }; +}; + +&dcpext0 { + typec-routes { + route@0 { + port { + dcpext0_typec: endpoint { + remote-endpoint = <&hpm2_dp>; + }; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-die0.dtsi b/arch/arm64/boot/dts/apple/t6050-die0.dtsi index 1d6887ef8bde1e..6643e2d66215ed 100644 --- a/arch/arm64/boot/dts/apple/t6050-die0.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-die0.dtsi @@ -39,7 +39,9 @@ wdt: watchdog@28836c000 { compatible = "apple,t6050-wdt", "apple,t8103-wdt"; - reg = <0x2 0x8836c000 0x0 0x4000>; + reg = <0x2 0x8836c000 0x0 0x4000>, + <0x2 0x8833002c 0x0 0x4>; + reg-names = "wdt", "reconfig"; clocks = <&clkref>; interrupts = ; }; diff --git a/arch/arm64/boot/dts/apple/t6050-j714c.dts b/arch/arm64/boot/dts/apple/t6050-j714c.dts index 7b42e646a56793..e60bae57450c43 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j714c.dts @@ -15,6 +15,11 @@ /dts-v1/; #define T6050_J714C +/* The M5 Max die-0 blocks (nub-spmi1, nub-spmi4) */ +#include "t6050-soc-max.dtsi" +/* ADT /arm-io/acio2: the right port's USB4/Thunderbolt router */ +#define T6050_ATC2_USB4_ROUTER +#include #include "t6050-max.dtsi" / { @@ -38,6 +43,8 @@ compatible = "apple,simple-framebuffer", "simple-framebuffer"; reg = <0 0 0 0>; /* To be filled by the loader */ /* Format properties will be added by the loader */ + /* Scanned out by the internal DCP, handed off or not. */ + display = <&dcp>; status = "disabled"; }; }; @@ -207,9 +214,56 @@ gpio-reserved-ranges = <0 80>, <81 25>, <108 113>; }; -/* This board's SMC fan and power keys are not yet checked */ +/* + * The keyboard backlight, as on J714s: ADT arm-io/pwm0/kbd-backlight, the + * fpwm s5l8920x at 0x3_05040000 (0x5_05040000 here), default-hz 25000, so a + * 40000 ns period on channel 0. + */ +/ { + led-controller { + compatible = "pwm-leds"; + + led-0 { + pwms = <&fpwm0 0 40000>; + label = "kbd_backlight"; + function = LED_FUNCTION_KBD_BACKLIGHT; + color = ; + max-brightness = <255>; + default-state = "keep"; + }; + }; +}; + +&fpwm0 { + status = "okay"; +}; + +/* + * SMC sensors, as on J714s: the J714cAP SMC has the same two fans (F0Ac/F1Ac, + * 2317..7826 rpm, mode keys F0md/F1md), power, voltage and current keys, plus + * every readable float T* key through apple,discover-temperatures in + * t6050-die0.dtsi. Discovery refuses to run once any temperature channel + * exists, so the shared temperature nodes and apple,soc-die-keys go. + */ +#include "hwmon-common.dtsi" +#include "hwmon-fan-dual.dtsi" +#include "hwmon-laptop.dtsi" + &smc_hwmon { - status = "disabled"; + /delete-property/ apple,soc-die-keys; + /delete-node/ temperature-TH0x; + /delete-node/ temperature-TB0T; + /delete-node/ temperature-TCHP; + /delete-node/ temperature-TW0P; + + /* The T6050 SMC spells the fan mode keys F0md/F1md. The SMC drives the fans. */ + fan-F0Ac { + apple,fan-mode = "F0md"; + }; + + fan-F1Ac { + apple,fan-mode = "F1md"; + }; }; /* @@ -236,8 +290,8 @@ /* * The keyboard and trackpad: the HID transport on the MTP's DockChannel FIFO. - * The J714c's MTP firmware owns the trackpad AFE reset, so there is no reset - * GPIO here, unlike the J716c. + * The J714c's MTP firmware does not reset the trackpad AFE, so the host does + * it through an SMC GPIO, as on the J714s. */ &mtp_dockchannel { status = "okay"; @@ -254,10 +308,15 @@ interrupt-names = "tx", "rx"; apple,fifo-size = <0x800>; apple,helper-cpu = <&mtp>; + /* + * ADT mtp function-afe-reset is the SMC pcIO template (0x10000, 0x11c0000), + * the same line as SMC GPIO gp1c, active low, which gpio-macsmc drives, as + * on the J714s. + */ + apple,afe-reset-gpios = <&smc_gpio_low 28 GPIO_ACTIVE_LOW>; multi-touch { apple,power-method = <2>; - apple,firmware-managed-reset; firmware-name = "apple/tpmtfw-j714c.bin"; }; diff --git a/arch/arm64/boot/dts/apple/t6050-j714s-display.dtsi b/arch/arm64/boot/dts/apple/t6050-j714s-display.dtsi index a7fb666907ef71..cc176808c8c25e 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s-display.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j714s-display.dtsi @@ -16,7 +16,6 @@ */ &dcpext1 { - apple,dcp-index = <2>; apple,connector-type = "USB-C"; apple,dptx-die = <0>; /* @@ -88,7 +87,6 @@ }; &dcpext2 { - apple,dcp-index = <3>; apple,connector-type = "USB-C"; apple,dptx-die = <0>; apple,typec-dptx-phys = <2 1 0>; @@ -145,7 +143,6 @@ }; &dcpext3 { - apple,dcp-index = <4>; apple,connector-type = "USB-C"; apple,dptx-die = <0>; }; @@ -272,26 +269,11 @@ }; }; -/* Scanout and PIODMA share the first register window, as on dispext0 */ -&dispext1_dart { - reg = <0x3 0x92300000 0x0 0xc000>; -}; - -&dispext2_dart { - reg = <0x3 0x02300000 0x0 0xc000>; -}; - -&dispext3_dart { - reg = <0x3 0x06300000 0x0 0xc000>; -}; - &atc2_xbar { status = "okay"; }; &atc1_dpxbar { - power-domains = <&ps_atc1_usb_aon>, <&ps_atc1_common>; - power-domain-names = "usb-aon", "common"; status = "okay"; }; @@ -329,8 +311,6 @@ /* The left-back crossbar (the inventory's, as atc1_dpxbar) and the PHY's tunnel clock gates */ &atc0_dpxbar { - power-domains = <&ps_atc0_usb_aon>, <&ps_atc0_common>; - power-domain-names = "usb-aon", "common"; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t6050-j714s-gpu-panel.dtsi b/arch/arm64/boot/dts/apple/t6050-j714s-gpu-panel.dtsi index 641f56817039ce..5b8a5e3862ff0a 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s-gpu-panel.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j714s-gpu-panel.dtsi @@ -90,50 +90,6 @@ }; }; -/* - * The four external display engines (dcpext0..3): the loader hands each over - * when its checks pass, else leaves it disabled. t6050-j714s-display.dtsi - * describes their routes. - */ - -/* The ADT lists no clocks for the external engines (clock-ids = []) */ -&dcpext1 { - apple,clock-ids; -}; - -&dcpext2 { - apple,clock-ids; -}; - -&dcpext3 { - apple,clock-ids; -}; - -/* ADT dart-dcpextN and dart-dispextN: vm-base 1 TiB, vm-size 3 TiB, as dcpext0's */ -&dcpext1_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext1_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext2_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext2_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext3_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext3_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - /* The inventory ASC nodes; the mailboxes below describe the same windows. */ /delete-node/ &gfx_asc; /delete-node/ &gfx1_asc; diff --git a/arch/arm64/boot/dts/apple/t6050-j714s-left-back.dtsi b/arch/arm64/boot/dts/apple/t6050-j714s-left-back.dtsi index e9de93f3d042d0..03181b7d1165f8 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s-left-back.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j714s-left-back.dtsi @@ -20,14 +20,7 @@ * and exporting this machine's ADT tunables. Older producers leave the port reserved. */ -/* - * The inventory gives ATC0_COMMON the FAB3 SoC domain as a parent, which is not described here. - * ATC1's and ATC2's common domains have none: do the same. J716c enables ps_fab3_soc instead, - * which would hand that fabric domain, and its other undescribed users, to genpd's unused - * power-off; left out, it stays as the boot loader leaves it, on. - */ &ps_atc0_common { - /delete-property/ power-domains; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t6050-j714s-sleep-soc.dtsi b/arch/arm64/boot/dts/apple/t6050-j714s-sleep-soc.dtsi index 9b0f2f0c3376ee..5ef086dee5765a 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s-sleep-soc.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j714s-sleep-soc.dtsi @@ -4576,7 +4576,11 @@ * taking that DART down and back to the live value before using it again. The router's host * also needs the port's PHY, which it stops after the router and starts before it. The left * port's router was never up in a trace: it has none of this and is powered off for a sleep. + * + * A board that includes these SoC values without that router (no acio2) defines + * T6050_SLEEP_SOC_NO_CIO first. */ +#ifndef T6050_SLEEP_SOC_NO_CIO &die0 { ps_prot: syscon@2803f0000 { compatible = "apple,t6050-ps-prot", "syscon"; @@ -4595,3 +4599,4 @@ &apciec2_dart { apple,clock-protection = <&ps_prot 31>; }; +#endif /* T6050_SLEEP_SOC_NO_CIO */ diff --git a/arch/arm64/boot/dts/apple/t6050-j714s.dts b/arch/arm64/boot/dts/apple/t6050-j714s.dts index 18b7c700c8469d..a411c8958d2f2d 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s.dts +++ b/arch/arm64/boot/dts/apple/t6050-j714s.dts @@ -14,6 +14,8 @@ /dts-v1/; #define T6050_J714S +/* ADT /arm-io/acio2: the right port's USB4/Thunderbolt router */ +#define T6050_ATC2_USB4_ROUTER #include #include "t6050-max.dtsi" @@ -42,11 +44,6 @@ model = "Apple MacBook Pro (14-inch, M5 Pro, 2026)"; chassis-type = "laptop"; - aliases { - /* the boot loader reserves the SEP firmware and adds its manifests through this alias */ - sep = &sep; - }; - chosen { #address-cells = <2>; #size-cells = <2>; @@ -56,6 +53,8 @@ compatible = "apple,simple-framebuffer", "simple-framebuffer"; reg = <0 0 0 0>; /* To be filled by the loader */ /* Format properties will be added by the loader */ + /* Scanned out by the internal DCP, handed off or not. */ + display = <&dcp>; status = "disabled"; }; }; @@ -524,64 +523,9 @@ power-domains = <&pmp0_gfx>; }; -/* - * The SEP (ADT sep, dart-sep): its mailbox, and its power domain with the two - * fabric parents left to the firmware, which genpd votes on and never turns off. - * The boot loader enables the SEP itself through its alias. - */ -&sep_mbox { - status = "okay"; -}; - -&ps_sep { - status = "okay"; -}; - -&ps_fab8_soc { - apple,firmware-owned; - status = "okay"; -}; - -&ps_fab0_piogw { - apple,firmware-owned; - status = "okay"; -}; - -/* - * Touch ID (ADT spi2/mesa): J616s's Mesa sensor (sensor-id 0x3356) at 8 MHz on - * chip select 0, powered by NUB GPIO 21 (function-mesa_pwr), data ready on AP - * GPIO 138. The controller's clock (ADT clock-ids 451) is the 24 MHz reference. - */ -&ps_nub_gpio { - status = "okay"; -}; - -&nub_gpio0 { - status = "okay"; -}; - -&ps_spi2 { - status = "okay"; -}; - -&spi2 { - clocks = <&clkref>; - status = "okay"; - - mesa: fingerprint@0 { - compatible = "apple,mesa-fingerprint"; - reg = <0>; - spi-max-frequency = <8000000>; - spi-cpol; - spi-cs-setup-delay-ns = <20>; - spi-cs-hold-delay-ns = <20>; - enable-gpios = <&nub_gpio0 21 GPIO_ACTIVE_HIGH>; - interrupt-parent = <&pinctrl_ap>; - interrupts = <138 IRQ_TYPE_EDGE_RISING>; - /* Per-device factory data from this Mac's own iBoot system container */ - firmware-name = "apple/mesacal-j714s.bin", "apple/msrk-j714s.bin"; - }; -}; +/* Touch ID: the SEP and the Mesa sensor, with this Mac's own calibration and root key */ +#define T6050_TOUCHID_FIRMWARE "apple/mesacal-j714s.bin", "apple/msrk-j714s.bin" +#include "t6050-touchid.dtsi" /* * The ProRes engine (apr0) and its DART, in the SCODEC power state. Its @@ -792,6 +736,36 @@ #include "t6050-j714s-sleep-soc.dtsi" #include "t6050-j714s-sleep-adt.dtsi" +/* A merged mode's pair is given only while every external display has an engine */ +&dcpext0 { + apple,merged-mode-limit; +}; + +&dcpext1 { + apple,merged-mode-limit; +}; + +&dcpext2 { + apple,merged-mode-limit; +}; + +&dcpext3 { + apple,merged-mode-limit; +}; + +/* The display coprocessors take the sleep through their firmware 27 method table */ +&sleep { + apple,display-method-sleep; +}; + +/* The SMC's wake reasons (ADT smc-pmu, event_name-bitN) */ +&smc { + apple,wake-reasons = <0 8 9 11 13 35 40 41 42 43 44 45 48>; + apple,wake-reason-names = "pwrbtn", "lid", "sdconn", "charger", "wifibt", + "trackpadkeyboard", "acattach", "acdetach", "USB-C_plug", + "USB2_plug", "USB2_wake", "aupo", "rtc"; +}; + /* * Sound through the AOP, as on J813: its audio service runs the serializers, the * CS42L84 headphone jack on admac-base-ns TX2/RX2 and the six SN012776 speaker amps diff --git a/arch/arm64/boot/dts/apple/t6050-j716c-display.dtsi b/arch/arm64/boot/dts/apple/t6050-j716c-display.dtsi index 3c8748edbe335a..297f43cf219fc0 100644 --- a/arch/arm64/boot/dts/apple/t6050-j716c-display.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j716c-display.dtsi @@ -1,54 +1,6 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT /* J716c external display processors and USB4 display routing. */ -&dcpext1_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext1_dart { - /* Scanout and PIODMA share the first register window. */ - reg = <0x3 0x92300000 0x0 0xc000>; - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext1 { - apple,bw-scratch = <&dcpext0_pmc 0 5 0x30000>; - apple,dcp-index = <2>; - apple,clock-ids; -}; - -&dcpext2_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext2_dart { - /* Scanout and PIODMA share the first register window. */ - reg = <0x3 0x02300000 0x0 0xc000>; - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext2 { - apple,bw-scratch = <&dcpext0_pmc 0 5 0x34000>; - apple,dcp-index = <3>; - apple,clock-ids; -}; - -&dcpext3_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext3_dart { - /* Scanout and PIODMA share the first register window. */ - reg = <0x3 0x06300000 0x0 0xc000>; - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext3 { - apple,bw-scratch = <&dcpext0_pmc 0 5 0x38000>; - apple,dcp-index = <4>; - apple,clock-ids; -}; - &atc2_phy { reg = <0x3 0x83000000 0x0 0x2c000>, <0x3 0x82a90000 0x0 0x4000>, diff --git a/arch/arm64/boot/dts/apple/t6050-j716c-left-usb4.dtsi b/arch/arm64/boot/dts/apple/t6050-j716c-left-usb4.dtsi index 196128d3add0c0..e4b3577abd45c4 100644 --- a/arch/arm64/boot/dts/apple/t6050-j716c-left-usb4.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j716c-left-usb4.dtsi @@ -1076,11 +1076,6 @@ /* DisplayPort alt mode and USB4 DP tunnels on the left ports. */ &atc0_dpxbar { - compatible = "apple,t6050-display-crossbar", "apple,t8142-display-crossbar"; - reg = <0x2 0xa324c000 0x0 0x4000>; - #mux-control-cells = <1>; - power-domains = <&ps_atc0_usb_aon>, <&ps_atc0_common>; - power-domain-names = "usb-aon", "common"; status = "okay"; }; &ps_atc0_common_dp_0 { @@ -1133,11 +1128,6 @@ hpm0_dp1: endpoint@1 { reg = <1>; remote-endpoint = <&dcpext2_left0>; }; }; }; }; }; &atc1_dpxbar { - compatible = "apple,t6050-display-crossbar", "apple,t8142-display-crossbar"; - reg = <0x2 0xab24c000 0x0 0x4000>; - #mux-control-cells = <1>; - power-domains = <&ps_atc1_usb_aon>, <&ps_atc1_common>; - power-domain-names = "usb-aon", "common"; status = "okay"; }; &ps_atc1_common_dp_0 { diff --git a/arch/arm64/boot/dts/apple/t6050-j716c-sep.dtsi b/arch/arm64/boot/dts/apple/t6050-j716c-sep.dtsi deleted file mode 100644 index 23019a719e07bb..00000000000000 --- a/arch/arm64/boot/dts/apple/t6050-j716c-sep.dtsi +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0+ OR MIT -/* J716c SEP handoff and the providers needed for warm registration. */ - -/ { - aliases { - /* The loader supplies the reserved image and registration manifests. */ - sep = &sep; - }; -}; - -/* The SEP and its DART are enabled by the driver after its policy is selected. */ -&sep_mbox { - status = "okay"; -}; - -&ps_sep { - status = "okay"; -}; - -/* Retain the fabric parents while the pre-booted enclave owns them. */ -&ps_fab8_soc { - apple,firmware-owned; - status = "okay"; -}; - -&ps_fab0_piogw { - apple,firmware-owned; - status = "okay"; -}; diff --git a/arch/arm64/boot/dts/apple/t6050-j716c.dts b/arch/arm64/boot/dts/apple/t6050-j716c.dts index a9e49cdf47ee17..863d0c524f3b64 100644 --- a/arch/arm64/boot/dts/apple/t6050-j716c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j716c.dts @@ -14,7 +14,12 @@ /dts-v1/; #define T6050_J716C +/* The M5 Max die-0 blocks (nub-spmi1, nub-spmi4) */ +#include "t6050-soc-max.dtsi" +/* ADT /arm-io/acio2: the right port's USB4/Thunderbolt router */ +#define T6050_ATC2_USB4_ROUTER #include "t6050-max.dtsi" +#include "hwmon-fan-dual.dtsi" / { compatible = "apple,j716c", "apple,t6050", "apple,arm-platform"; @@ -47,6 +52,8 @@ compatible = "apple,simple-framebuffer", "simple-framebuffer"; reg = <0 0 0 0>; /* To be filled by the loader */ /* Format properties will be added by the loader */ + /* Scanned out by the internal DCP, handed off or not. */ + display = <&dcp>; status = "disabled"; }; }; @@ -176,16 +183,32 @@ /* * Pin 112's register (0x29c0001c0) takes an SError when read, so only the pins a node - * here names are exposed: 80 (PCIe port 0's PERST#, ADT pci-bridge0 function-perst). + * here names are exposed: 80 (PCIe port 0's PERST#, ADT pci-bridge0 function-perst) and + * 138 (the Touch ID sensor's data-ready line). * A reserved line cannot be requested, so a node that names a new pin opens it here too. */ &pinctrl_ap { - gpio-reserved-ranges = <0 80>, <81 140>; + gpio-reserved-ranges = <0 80>, <81 57>, <139 82>; }; -/* This board's SMC fan and power keys are not yet checked */ +/* + * Inherit apple,discover-temperatures and apple,soc-die-keys ("TCMb") from + * t6050-die0.dtsi so all readable T* float sensors are discovered and TCMb + * supplies the macsmc_soc_die thermal zone for the GPU thermal governor. + * T6050 spells the fan mode keys F0md/F1md and accepts manual fan targets. + */ &smc_hwmon { - status = "disabled"; + status = "okay"; + + fan-F0Ac { + apple,fan-mode = "F0md"; + apple,fan-manual-control; + }; + + fan-F1Ac { + apple,fan-mode = "F1md"; + apple,fan-manual-control; + }; }; /* @@ -261,12 +284,15 @@ 63 2e 00 06 02 69 4f 53 00 00 00 00]; }; +/* Touch ID: the SEP and the Mesa sensor, with this Mac's own calibration and root key */ +#define T6050_TOUCHID_FIRMWARE "apple/mesacal-j716c.bin", "apple/msrk-j716c.bin" +#include "t6050-touchid.dtsi" + #include "t6050-j716c-isp.dtsi" #include "t6050-j716c-gpu-panel.dtsi" #include "t6050-j716c-display.dtsi" #include "t6050-j716c-left-usb4.dtsi" -#include "t6050-j716c-sep.dtsi" #include "t6050-j716c-sleep.dtsi" #include "t6050-j716c-sleep-full.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-j716s.dts b/arch/arm64/boot/dts/apple/t6050-j716s.dts index 72ef21fce1bf4e..7eb3a3415d8dd2 100644 --- a/arch/arm64/boot/dts/apple/t6050-j716s.dts +++ b/arch/arm64/boot/dts/apple/t6050-j716s.dts @@ -41,6 +41,8 @@ compatible = "apple,simple-framebuffer", "simple-framebuffer"; reg = <0 0 0 0>; /* To be filled by the loader */ /* Format properties will be added by the loader */ + /* Scanned out by the internal DCP, handed off or not. */ + display = <&dcp>; status = "disabled"; }; }; diff --git a/arch/arm64/boot/dts/apple/t6050-j775c.dts b/arch/arm64/boot/dts/apple/t6050-j775c.dts index 65d92d3a174800..53aeaf1c3f093b 100644 --- a/arch/arm64/boot/dts/apple/t6050-j775c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j775c.dts @@ -27,10 +27,22 @@ }; }; +/* + * From this board's macOS 27.2 (26B123) Automatic energy-mode CLPC floor + * residency under one CPU-bound thread: the top of the two DCS/fabric pairs + * it alternates between, read as DCS 6 and fabric 3 (state order, not + * verified). Low Power mode drops this floor and uses the SoC table instead. + */ +&clpc { + apple,cpu-busy-floor = <6 3>; +}; + /* PCIe port 0 is not described for this board yet */ &pcie0 { status = "disabled"; }; #define T6050_J775C +/* The M5 Max die-0 blocks (nub-spmi1, nub-spmi4) */ +#include "t6050-soc-max.dtsi" #include "t6050-peripherals.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-k114c-gpu.dtsi b/arch/arm64/boot/dts/apple/t6050-j775d-gpu.dtsi similarity index 78% rename from arch/arm64/boot/dts/apple/t6050-k114c-gpu.dtsi rename to arch/arm64/boot/dts/apple/t6050-j775d-gpu.dtsi index ceec5b22d2ae7f..8b64a03432d965 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c-gpu.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j775d-gpu.dtsi @@ -1,12 +1,15 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT /* - * K114c (M5 Max, G17C) GPU, for the boot loader's GPU handoff. Everything here - * stays disabled: the loader checks the ADT and the live GPU firmware build, - * fills the GPU reservations, then enables the power states, both mailboxes and - * the GPU, the GPU last. A loader that refuses leaves the GPU off. + * J775D GPU (G17D), for the boot loader's GPU handoff, as + * t6050-j714s-gpu-panel.dtsi describes the J714s's. Everything here stays + * disabled: the loader checks the ADT and the live GPU firmware state, fills + * the GPU reservations, and only then enables the nodes, the GPU last. A + * loader without the handoff, or one whose checks fail, leaves the GPU off. * - * Same layout as t6050-j714s-gpu-panel.dtsi; the GPU is G17C and, in the ADT, - * sgx and both GPU ASCs are the same as on the M5 Pro. + * Values are from the J775DAP 27.0 ADT (sgx, gfx-asc, gfx1-asc, pmgr). Both + * firmware roles, their mailboxes and the GPU node are die 0's, with the + * addresses and interrupts of a one-die T6050; die 1 adds only its power + * states (t6050-ultra.dtsi). */ / { @@ -103,16 +106,8 @@ apple,always-on; }; -/* - * The G17 firmware stays live across suspend-to-idle, as the G16's does on T8132: keep - * GFX on in the noirq phase instead of gating it under the running firmware. - */ -&ps_gfx { - apple,sleep-retained; -}; - &sgx { - compatible = "apple,agx-g17s"; + compatible = "apple,agx-g17d", "apple,agx-g17s"; /* ADT sgx reg[0]; the driver maps the first 16 MiB as "sgx" */ reg = <0x23 0x0 0x0 0x3fdc000>; reg-names = "sgx"; diff --git a/arch/arm64/boot/dts/apple/t6050-j775d.dts b/arch/arm64/boot/dts/apple/t6050-j775d.dts index 38923533c5f4c7..65bafecbc0056d 100644 --- a/arch/arm64/boot/dts/apple/t6050-j775d.dts +++ b/arch/arm64/boot/dts/apple/t6050-j775d.dts @@ -55,9 +55,42 @@ model = "Mac Studio J775D"; }; +/* + * The AOP, with its RTKit mailbox, its DART and the audio DMA controller, booted over the RTKit + * mailbox alone. This board's AOP firmware does not service the setup port: started through both, + * it sends nothing there and leaves the AP's message unread. The setup mailbox stays described, + * disabled. + */ +&aop_mbox { + status = "okay"; +}; + +&aop_dart { + status = "okay"; +}; + +&admac_base_ns { + status = "okay"; +}; + +&aop { + mboxes = <&aop_mbox>; + mbox-names = "mbox"; + status = "okay"; +}; + +/* + * Shared with the Mac mini: the onboard Ethernet (PCIe port 2, an RTL8127A here) and rear + * USB-C ports 1-3. Port 1 (HPM0, "back-right") is reserved for the debug link. + */ +#define T6050_DESKTOP_HPM1_LABEL "USB-C Back-right-middle" +#define T6050_DESKTOP_HPM2_LABEL "USB-C Back-left-middle" +#include "t6050-desktop.dtsi" + /* * PCIe ports 2 (the onboard 10 Gb Ethernet) and 3 (the rear USB-A xHCI). The boot loader * powers and trains both links; it disables a port, and its DART, whose link did not come up. + * Port 2's node is in t6050-desktop.dtsi. * * Port 0 carries the N1 (Wi-Fi and Bluetooth), described disabled until the boot loader trains * it (pci@0,0 below). @@ -93,32 +126,6 @@ <0x300 &dart_apcie0 1 3>; bus-range = <0 3>; - port02: pci@2,0 { - device_type = "pci"; - reg = <0x1000 0 0 0 0>; - bus-range = <1 1>; - apple,link-trained-by-bootloader; - - #address-cells = <3>; - #size-cells = <2>; - ranges; - - interrupt-controller; - #interrupt-cells = <1>; - interrupt-map-mask = <0 0 0 7>; - interrupt-map = <0 0 0 1 &port02 0 0 0 0>, - <0 0 0 2 &port02 0 0 0 1>, - <0 0 0 3 &port02 0 0 0 2>, - <0 0 0 4 &port02 0 0 0 3>; - - /* The RTL8127A keeps no MAC address of its own */ - ethernet0: ethernet@0,0 { - reg = <0x10000 0x0 0x0 0x0 0x0>; - /* To be filled by the loader */ - local-mac-address = [00 00 00 00 00 00]; - }; - }; - port03: pci@3,0 { device_type = "pci"; reg = <0x1800 0 0 0 0>; @@ -217,10 +224,6 @@ status = "okay"; }; -&dart_apcie2 { - status = "okay"; -}; - &dart_apcie3 { status = "okay"; }; @@ -301,92 +304,9 @@ /* * The USB-C ports: rear ports 1-4 on ATC0-3 of die 0, front ports 5 and 6 on ATC0 and ATC1 of * die 1. The HPMs of the rear ports are on nub-spmi-a0, those of the front ports on nub-spmi-a2. + * Rear ports 1-3 are in t6050-desktop.dtsi; rear port 4 and the front ports follow. */ &nub_spmi_a0 { - /* - * /arm-io/nub-spmi-a0/hpm0: SN201202x (ACE3), SPMI address 0xc, port-number 1 (back-right). - * Reserved: rear port 1 carries the DFU cable, the host's VDM reboot path and the - * debug console (KIS) through usb-drd0; a probe wakes the controller and sets its - * power state even when polled. No ATC0, usb-drd0 or dart-usb0 node either. - */ - hpm0: usb-pd@c { - compatible = "apple,sn201202x"; - reg = <0xc SPMI_USID>; - status = "disabled"; - }; - - /* /arm-io/nub-spmi-a0/hpm1: SN201202x (ACE3), SPMI address 0xa, port-number 2 */ - hpm1: usb-pd@a { - compatible = "apple,sn201202x"; - reg = <0xa SPMI_USID>; - - connector { - compatible = "usb-c-connector"; - label = "USB-C Back-right-middle"; - power-role = "dual"; - data-role = "host"; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - hpm1_hs: endpoint { - remote-endpoint = <&usb_drd1_hs>; - }; - }; - - port@1 { - reg = <1>; - hpm1_ss: endpoint { - remote-endpoint = <&atc1_phy_ep>; - }; - }; - }; - }; - }; - - /* /arm-io/nub-spmi-a0/hpm2: SN201202x (ACE3), SPMI address 8, port-number 3 */ - hpm2: usb-pd@8 { - compatible = "apple,sn201202x"; - reg = <0x8 SPMI_USID>; - status = "disabled"; - - connector { - compatible = "usb-c-connector"; - label = "USB-C Back-left-middle"; - power-role = "dual"; - data-role = "dual"; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - hpm2_hs: endpoint { - remote-endpoint = <&usb_drd2_hs>; - }; - }; - - port@1 { - reg = <1>; - hpm2_ss: endpoint { - remote-endpoint = <&atc2_phy_ep>; - }; - }; - - port@2 { - reg = <2>; - hpm2_dp: endpoint { - remote-endpoint = <&dcpext0_typec>; - }; - }; - }; - }; - }; - /* /arm-io/nub-spmi-a0/hpm3: SN201202x (ACE3), SPMI address 6, port-number 4 */ hpm3: usb-pd@6 { compatible = "apple,sn201202x"; @@ -416,9 +336,13 @@ }; }; - /* The USB4 router (usb4_3_acio), the PD driver's thunderbolt-switch */ - port@2 { - reg = <2>; + /* + * The USB4 router (usb4_3_acio), the PD driver's + * thunderbolt-switch; port@2 is reserved for DisplayPort + * (apple,dcp-typec-routes.yaml). + */ + port@3 { + reg = <3>; hpm3_tbt: endpoint { remote-endpoint = <&usb4_3_ep>; }; @@ -494,60 +418,6 @@ }; }; -/* - * Rear USB-C port 2 (HPM1, "back-right-middle"), USB data: ATC1's combo PHY, usb-drd1 and - * dart-usb1. - */ -&atc1_phy { - port { - atc1_phy_ep: endpoint { - remote-endpoint = <&hpm1_ss>; - }; - }; -}; - -&usb_drd1 { - port { - usb_drd1_hs: endpoint { - remote-endpoint = <&hpm1_hs>; - }; - }; -}; - -/* - * Rear USB-C port 3 (HPM2, "back-left-middle", the display port): DisplayPort out from dcpext0 - * through ATC2, and USB beside it (usb-drd2, dart-usb2). The chain stays disabled: Aura's T6050 - * display handoff enables what dcpext0 references (phys, mux-controls, the PHY's mailbox and - * power domains, the typec route's HPM and its SPMI bus). - */ -&atc2_phy { - port { - atc2_phy_ep: endpoint { - remote-endpoint = <&hpm2_ss>; - }; - }; -}; - -&usb_drd2 { - port { - usb_drd2_hs: endpoint { - remote-endpoint = <&hpm2_hs>; - }; - }; -}; - -&dcpext0 { - typec-routes { - route@0 { - port { - dcpext0_typec: endpoint { - remote-endpoint = <&hpm2_dp>; - }; - }; - }; - }; -}; - /* Rear USB-C port 4 (HPM3, "back-left"): ATC3, and its USB4/Thunderbolt router */ &atc3_phy { port { @@ -636,4 +506,40 @@ }; #define T6050_J775D +/* The M5 Max die-0 blocks (nub-spmi1, nub-spmi4) */ +#include "t6050-soc-max.dtsi" #include "t6050-peripherals.dtsi" + +/* + * The other three die-0 external display engines (dcpext1..3). The shared + * properties live in t6050-peripherals.dtsi; each empty typec-routes container + * asks the boot loader to write the engine's USB-C display routes from the ADT. + */ +&dcpext1 { + apple,connector-type = "USB-C"; + + typec-routes { + #address-cells = <1>; + #size-cells = <0>; + }; +}; + +&dcpext2 { + apple,connector-type = "USB-C"; + + typec-routes { + #address-cells = <1>; + #size-cells = <0>; + }; +}; + +&dcpext3 { + apple,connector-type = "USB-C"; + + typec-routes { + #address-cells = <1>; + #size-cells = <0>; + }; +}; + +#include "t6050-j775d-gpu.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-j873s.dts b/arch/arm64/boot/dts/apple/t6050-j873s.dts index 0a7976e50230f5..9c2e2a12c54352 100644 --- a/arch/arm64/boot/dts/apple/t6050-j873s.dts +++ b/arch/arm64/boot/dts/apple/t6050-j873s.dts @@ -5,8 +5,10 @@ * target-type: J873s * * One T6050 die (t6050-max.dtsi). Nobody has booted Linux on this board - * yet: beyond the SoC this file only adds the board's hardware inventory - * (t6050-peripherals.dtsi), all of it disabled, from the board's ADT. + * yet. Beyond the SoC this file adds the board's hardware inventory + * (t6050-peripherals.dtsi, all of it disabled), the onboard Ethernet and + * the N1 (Wi-Fi and Bluetooth) on PCIe, and rear USB-C ports 1-3, from + * the board's ADT. * * Copyright The Asahi Linux Contributors */ @@ -20,6 +22,14 @@ model = "Apple Mac mini (M5 Pro, 2026)"; chassis-type = "desktop"; + aliases { + /* the boot loader fills in the MAC address through this alias */ + ethernet0 = ðernet0; + /* kboot fills the N1's factory addresses from /chosen through these */ + wifi0 = &n1_alpha; + bluetooth0 = &n1_beta; + }; + chosen { #address-cells = <2>; #size-cells = <2>; @@ -27,10 +37,105 @@ }; }; -/* PCIe port 0 is not described for this board yet */ +/* + * Shared with the Mac Studio: the onboard Ethernet (PCIe port 2) and rear USB-C ports 1-3, the + * three Thunderbolt ports. Port 1 (HPM0, "back-middle") is reserved for the debug link. + */ +#define T6050_DESKTOP_HPM1_LABEL "USB-C Back-left" +#define T6050_DESKTOP_HPM2_LABEL "USB-C Back-right" +#include "t6050-desktop.dtsi" + +/* + * PCIe ports 2 (the onboard Ethernet) and 0 (the N1). The board's ADT has bridges for these two + * ports only: no SD reader (port 1) and no USB-A xHCI (port 3). Port 0 is described disabled + * until the boot loader trains it (pci@0,0 below). + */ &pcie0 { - status = "disabled"; + reg = <0x1c 0xb0000000 0x0 0x10000000>, + <0x4 0x14000000 0x0 0x4000>, + <0x4 0x12028000 0x0 0x8000>, + <0x4 0x17018000 0x0 0x4000>, + <0x4 0x12024000 0x0 0x4000>, + <0x4 0x10028000 0x0 0x8000>, + <0x4 0x17010000 0x0 0x4000>, + <0x4 0x10024000 0x0 0x4000>; + reg-names = "config", "rc", "port2", "phy2", "intr2axi2", + "port0", "phy0", "intr2axi0"; + interrupts = , + ; + interrupt-names = "port2", "port0"; + + /* + * The boot loader numbers port 2's secondary bus 1; port 0's is 2 + * until a boot loader that trains it renumbers both in the PCI core's + * order. The N1's three functions are on DART streams 1-3. + */ + iommu-map = <0x100 &dart_apcie2 1 1>, + <0x200 &dart_apcie0 1 3>; + bus-range = <0 2>; + + /* + * The N1 Wi-Fi/Bluetooth (106b:1900, its ROM), trained by the bootloader after the SMC + * releases its reset. Its driver boots the firmware and has this port reset after the ROM + * stage; Control, Alpha (Wi-Fi) and Beta (Bluetooth) then answer at functions 0-2. + * Disabled with its DART: a bootloader that trains the port enables both and renumbers the + * buses here (bus-range, reg, iommu-map) to the PCI core's order, port 0 first. + */ + port00: pci@0,0 { + device_type = "pci"; + reg = <0x0 0 0 0 0>; + bus-range = <2 2>; + apple,link-trained-by-bootloader; + /* + * Its PERST# (pci-bridge0 function-perst): /arm-io/gpio0 pin 0x50, pad + * register 0x140 of pinctrl_ap. Driven only by the root-port reset after + * the N1's ROM stage. + */ + reset-gpios = <&pinctrl_ap 80 GPIO_ACTIVE_LOW>; + status = "disabled"; + + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &port00 0 0 0 0>, + <0 0 0 2 &port00 0 0 0 1>, + <0 0 0 3 &port00 0 0 0 2>, + <0 0 0 4 &port00 0 0 0 3>; + + /* The firmware: the chip's image with this board's ticket; platform ID is + * (board 0x02 << 16) | chip 0x6050 */ + n1_control: control@0,0 { + compatible = "pci106b,1900"; + reg = <0x20000 0x0 0x0 0x0 0x0>; + firmware-name = "apple/centauri/j873s-ftab.bin"; + apple,centauri-platform-id = <0x00026050>; + apple,centauri-protocol = <27>; + }; + + n1_alpha: wifi@0,1 { + compatible = "pci106b,1902"; + reg = <0x20100 0x0 0x0 0x0 0x0>; + local-mac-address = [00 00 00 00 00 00]; + }; + + n1_beta: bluetooth@0,2 { + compatible = "pci106b,1903"; + reg = <0x20200 0x0 0x0 0x0 0x0>; + local-bd-address = [00 00 00 00 00 00]; + }; + }; }; +/* + * The front USB-C ports (ADT port-numbers 9 and 10, USB 3 only) sit behind a fixed USB hub on + * ATC3 (atc-phy3, usb-drd3), which has no PD controller. They are not described yet: the + * combo PHY starts USB only on a Type-C mux and orientation event, which a hub port without + * an HPM never gets. + */ + #define T6050_J873S #include "t6050-peripherals.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116-display.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116-display.dtsi new file mode 100644 index 00000000000000..7206ceb2951d02 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116-display.dtsi @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The internal tandem OLED panel and its display coprocessor on the K114c, K114s, K116c and + * K116s, for the boot loader's display hand-off. The four ADTs have the same disp0, dart-disp0, + * dcp and dart-dcp (the live K114s and K116s ADTs: disp0 clock-ids 361 and 458, both DARTs + * vm-base 1 TiB, vm-size 3 TiB) and no I2C backlight controller: the OLED's luminance is a DCP + * request (ADT /backlight-override dcp-brightness-node = 1). + * + * Everything stays disabled. The loader checks the ADT and the live DCP and DART state, + * publishes the DCP's firmware properties, the panel's brightness scale (ADT + * user-accessible-max-nits) and the ADT /vram as the framebuffer, and only then enables dcp, + * its DARTs and mailbox and the display subsystem. A loader without the hand-off, or one whose + * checks fail, leaves the boot framebuffer to simpledrm. + * + * The board adds the panel's size (the ADTs carry none). + */ + +/ { + aliases { + /* The loader writes apple,notch-height into the "dcp" alias */ + dcp = &dcp; + disp0 = &display; + }; + + /* As on J714s, with the internal display's DART (disp0, SID 0) */ + display: display-subsystem { + compatible = "apple,display-subsystem"; + iommus = <&disp0_dart 0>; + status = "disabled"; + }; +}; + +/* ADT dart-dcp and dart-disp0: vm-base 1 TiB, vm-size 3 TiB */ +&dcp_dart { + apple,dma-range = <0x100 0x0 0x300 0x0>; +}; + +&disp0_dart { + apple,dma-range = <0x100 0x0 0x300 0x0>; +}; + +&dcp { + /* + * ADT disp0 clock-ids. The loader adds the clock nodes, "clocks" and the + * bandwidth request scratch ("apple,bw-scratch") when it hands the panel + * over, as on the J714s, and refuses a tree that already has them. + */ + apple,clock-ids = <361 458>; + + /* + * The panel's plug takes about 2.9 ms on the K116s from the video interface's + * announcement to the firmware's "ioav i/f is now closed", and the next round of + * reports follows about 33 ms later. With the J714s's 2500 us the open landed 25 us + * before the close. The K boards run the same 27.2 DCP image for the same panel family. + */ + apple,panel-video-open-delay-us = <10000>; + + panel: panel { + compatible = "apple,panel"; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116-gpu.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116-gpu.dtsi new file mode 100644 index 00000000000000..92708423790865 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116-gpu.dtsi @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The GPU of the K114c, K114s, K116s and K116c (ADT /arm-io/sgx "gpu,t6050"), for the boot + * loader's GPU hand-off. It is the GPU half of t6050-j714s-gpu-panel.dtsi: the four boards' + * ADTs have the J714s's sgx, gfx-asc and gfx1-asc. + * + * Everything here stays disabled: the loader checks the ADT and the live GPU firmware build, + * fills the six reservations, then enables the GPU PMGR, GPX, AFR, GFX, both mailboxes and the + * GPU, the GPU last. A loader that refuses leaves the GPU off and the rest of the boot as it is. + * + * arm-io's ranges add 0x2_0000_0000 to the ADT's 0x21_xxxx_xxxx bus addresses. + */ + +/ { + aliases { + /* The loader finds the GPU through this alias */ + gpu = &sgx; + }; + + reserved-memory { + /* + * Filled and enabled by the loader from the ADT: sgx gpu-region-*, + * gfx-shared-region-*, gfx-shared-l2-region-* and gfx-handoff-* (the UAT + * ranges), the GPU ASCs' __TEXT (fw-text) and gfx-data-base to the end of + * gfx1-data-shared-ro (fw-data). iBoot places them; they differ per Mac. + */ + gpu_fw_text: gpu-fw-text { + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + + gpu_fw_data: gpu-fw-data { + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + + uat_ttbs: uat-ttbs { + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + + uat_pagetables: uat-pagetables { + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + + uat_l2_pagetables: uat-l2-pagetables { + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + + uat_handoff: uat-handoff { + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + }; +}; + +/* The inventory ASC nodes; the mailboxes below describe the same windows. */ +/delete-node/ &gfx_asc; +/delete-node/ &gfx1_asc; + +&{/soc} { + /* + * ADT gfx-asc: reg 0x21_02600000 + 0x88000 (wrapper), 0x21_02050000 + 8 (iop-vbar); + * interrupts [2798, 2797, 2800, 2799], of which the second and third are send-empty + * and recv-not-empty; role "GFX"; power-gates [614] (GFX_ASC). + */ + gfx_mbox: mailbox@2302600000 { + compatible = "apple,t6050-j775d-ascwrap-v6"; + reg = <0x23 0x2600000 0x0 0x88000>, + <0x23 0x2050000 0x0 0x8>; + reg-names = "wrapper", "iop-vbar"; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + apple,firmware-role = "GFX"; + power-domains = <&ps_gfx>; + #mbox-cells = <0>; + status = "disabled"; + }; + + /* + * ADT gfx1-asc: reg 0x21_02e00000 + 0x88000, 0x21_02850000 (ADT size 0x60000; the + * driver uses the first 8 bytes); interrupts [2802, 2801, 2804, 2803]; role "GFX1"; + * power-gates [657] (GFX_ASC1). + */ + gfx1_mbox: mailbox@2302e00000 { + compatible = "apple,t6050-j775d-ascwrap-v6"; + reg = <0x23 0x2e00000 0x0 0x88000>, + <0x23 0x2850000 0x0 0x8>; + reg-names = "wrapper", "iop-vbar"; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + apple,firmware-role = "GFX1"; + power-domains = <&ps_gfx>; + #mbox-cells = <0>; + status = "disabled"; + }; +}; + +/* + * ADT pmgr devices GPX (id 359, +0x0), AFR (id 360, +0x100) and GFX (id 362, +0x110) in the + * GPU PMGR. The ADT marks GPX and AFR, GFX's parents, critical; GFX not. + */ +&ps_gpx { + apple,always-on; +}; + +&ps_afr { + apple,always-on; +}; + +/* + * The G17 firmware stays live across suspend-to-idle, as the G16's does on T8132: keep + * GFX on in the noirq phase instead of gating it under the running firmware. + */ +&ps_gfx { + apple,sleep-retained; +}; + +&sgx { + /* What the loader checks and drivers/gpu/drm/asahi binds */ + compatible = "apple,agx-g17s"; + /* ADT sgx reg[0] 0x21_00000000 + 0x3fdc000; the driver maps the first 16 MiB as "sgx" */ + reg = <0x23 0x0 0x0 0x3fdc000>; + reg-names = "sgx"; + /delete-property/ interrupts; + mboxes = <&gfx_mbox>, <&gfx1_mbox>; + memory-region = <&uat_ttbs>, <&uat_pagetables>, <&uat_handoff>, + <&gpu_fw_data>, <&uat_l2_pagetables>, <&gpu_fw_text>; + memory-region-names = "ttbs", "pagetables", "handoff", "fw-data", + "l2-pagetables", "fw-text"; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116-usb.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116-usb.dtsi new file mode 100644 index 00000000000000..87b16d9a0429ac --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116-usb.dtsi @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The K114c, K114s, K116c and K116s USB-C ports ATC1 (left-front) and ATC2 (right): + * USB 2/3 and the PD controllers. A board file includes this after + * t6050-peripherals.dtsi, which describes nub-spmi-a1 for these boards. + * + * From the boards' ADT, the same on all four: + * ATC0 usb-drd0 left-back hpm0 nub-spmi-a0 0x0c (the boot link's debug port, not described) + * ATC1 usb-drd1 left-front hpm1 nub-spmi-a0 0x0a, port-number 2, acio-parent acio1 + * ATC2 usb-drd2 right hpm2 nub-spmi-a1 0x0c, port-number 3, acio-parent acio2 + * hpm5 nub-spmi-a0 0x08 (MagSafe, not a USB-C connector) + * The PD controllers are SN201202x. The USB4/Thunderbolt routers (acio1, acio2) and the + * DisplayPort routes are not described here; the PHYs run in USB mode. The combo PHY driver + * leaves ATC0 alone on purpose (apple,port-index 0). + * + * The boot loader fills the PHYs' tunables from the ADT through the atcphy aliases. + */ +/ { + aliases { + atcphy1 = &atc1_phy; + atcphy2 = &atc2_phy; + }; +}; + +/* ==== The left-front USB-C port (ATC1) ==== */ +&nub_spmi_a0 { + status = "okay"; + + hpm1: usb-pd@a { + compatible = "apple,sn201202x"; + reg = <0xa SPMI_USID>; + + connector { + compatible = "usb-c-connector"; + label = "USB-C Left-front"; + power-role = "dual"; + data-role = "dual"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + hpm1_hs: endpoint { + remote-endpoint = <&usb_drd1_hs>; + }; + }; + + port@1 { + reg = <1>; + hpm1_ss: endpoint { + remote-endpoint = <&atc1_phy_ep>; + }; + }; + }; + }; + }; +}; + +&atc1_phy_mbox { + status = "okay"; +}; + +&atc1_phy { + status = "okay"; + + port { + atc1_phy_ep: endpoint { + remote-endpoint = <&hpm1_ss>; + }; + }; +}; + +&usb_drd1 { + status = "okay"; + + port { + usb_drd1_hs: endpoint { + remote-endpoint = <&hpm1_hs>; + }; + }; +}; + +&usb_drd1_dart_0 { + status = "okay"; +}; + +&usb_drd1_dart_1 { + status = "okay"; +}; + +/* + * ==== The right USB-C port (ATC2) ==== + * + * The HPM is on its own bus, nub-spmi-a1, and nothing hands the port off, so the power + * domains, the PHY mailbox, the PHY, the DWC3 and its DARTs are enabled outright. The driver + * polls the generation 4 bus and refuses an interrupt on it. + */ +&ps_atc2_common { + status = "okay"; +}; + +&ps_atc2_usb_aon { + status = "okay"; +}; + +&ps_atc2_phymxwrap { + status = "okay"; +}; + +&ps_atc2_usb { + status = "okay"; +}; + +&atc2_phy_mbox { + status = "okay"; +}; + +&atc2_phy { + status = "okay"; + + port { + atc2_phy_ep: endpoint { + remote-endpoint = <&hpm2_ss>; + }; + }; +}; + +&usb_drd2 { + status = "okay"; + + port { + usb_drd2_hs: endpoint { + remote-endpoint = <&hpm2_hs>; + }; + }; +}; + +&usb_drd2_dart_0 { + status = "okay"; +}; + +&usb_drd2_dart_1 { + status = "okay"; +}; + +&nub_spmi_a1 { + /delete-property/ interrupts; + status = "okay"; + + hpm2: usb-pd@c { + compatible = "apple,sn201202x"; + reg = <0xc SPMI_USID>; + + connector { + compatible = "usb-c-connector"; + label = "USB-C Right"; + power-role = "dual"; + data-role = "dual"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + hpm2_hs: endpoint { + remote-endpoint = <&usb_drd2_hs>; + }; + }; + + port@1 { + reg = <1>; + hpm2_ss: endpoint { + remote-endpoint = <&atc2_phy_ep>; + }; + }; + }; + }; + }; +}; + +/* PCIe port 0's power states, used by pcie0 and dart_apcie0 (see t6050-k114-k116.dtsi) */ +&ps_fab6_soc { + apple,firmware-owned; + status = "okay"; +}; + +&ps_apcie_gp { + apple,firmware-owned; + status = "okay"; +}; + +&ps_apcie_sys_gp { + apple,firmware-owned; + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi index a111be4aad579f..073d8a94094f9f 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi @@ -35,6 +35,9 @@ aliases { serial0 = &dockchannel; + /* The boot loader fills the N1's factory addresses through these */ + wifi0 = &n1_alpha; + bluetooth0 = &n1_beta; }; chosen { @@ -46,6 +49,8 @@ compatible = "apple,simple-framebuffer", "simple-framebuffer"; reg = <0 0 0 0>; /* To be filled by the loader */ /* Format properties will be added by the loader */ + /* Scanned out by the internal DCP, handed off or not. */ + display = <&dcp>; status = "disabled"; }; }; @@ -78,35 +83,14 @@ }; }; -/* ATC1, ATC3 and the PD controller buses nub-spmi-a0 and -a2: not yet described for these boards */ -&nub_spmi_a0 { - status = "disabled"; -}; - +/* + * ATC3 and the PD controller bus nub-spmi-a2: not described for these boards. The + * USB-C ports ATC1 and ATC2 are in t6050-k114-k116-usb.dtsi. + */ &nub_spmi_a2 { status = "disabled"; }; -&atc1_phy_mbox { - status = "disabled"; -}; - -&atc1_phy { - status = "disabled"; -}; - -&usb_drd1 { - status = "disabled"; -}; - -&usb_drd1_dart_0 { - status = "disabled"; -}; - -&usb_drd1_dart_1 { - status = "disabled"; -}; - &atc3_phy_mbox { status = "disabled"; }; @@ -137,23 +121,192 @@ /* * As on J716c, where reading pin 112 takes an SError, only the pins a node - * here names are exposed, and none is yet. The N1 on PCIe port 0 needs its - * board's platform ID, which the static ADT does not carry, so the port and - * its PERST# pin stay unused for now. + * names are exposed: 80 and 81, PCIe ports 0 and 1's PERST#; 134 and 139, the jack + * codec's interrupt and reset; 138, the Touch ID sensor's data-ready line + * (t6050-touchid.dtsi). A board that names more pins replaces the list. */ &pinctrl_ap { - gpio-reserved-ranges = <0 221>; + gpio-reserved-ranges = <0 80>, <82 52>, <135 3>, <140 81>; }; /* - * The K114s N1 needs its own platform ID (its ADT /chosen board-id << 16 | 0x6050) - * before the port can be described. aura's T6050 hand-off still wants the host's - * iommu-map to mark the ports as it found them, so carry it with the host disabled. + * PCIe port 0: the N1 (Wi-Fi and Bluetooth), the same on all four boards and + * laid out as on J716c: the boot loader trains the link and keeps power, + * clocks, the PHY and PERST; Linux owns the routing, MSI and the DART. The + * port stays disabled until the loader trains it. From the boards' ADT: + * apcie0 gives port 0's registers and IRQ 1523, pci-bridge0's PERST# is GPIO + * 80, and the N1's three functions are on DART streams 1-3. + * + * The board file defines, before including this file, the N1's personalized + * firmware (T6050_K_N1_FIRMWARE) and its ADT /chosen board-id + * (T6050_K_BOARD_ID). The N1's platform ID is board-id << 16 | chip 0x6050. + * aura's T6050 hand-off wants the host's iommu-map to mark the ports as it + * found them. + * + * PCIe port 1: the SD card reader (ADT apcie0/pci-bridge1/pcie-sdreader, a + * GL9755), the same on all four boards' ADTs and laid out as on J714s. The + * boot loader leaves the port down, so the kernel trains it. From the ADTs: + * port1, phy1, intr2axi1: apcie0 reg[22], reg[24], reg[25] (port 0's are + * reg[16], reg[18], reg[19]), behind /arm-io's ranges (+0x200000000) + * phy-shared: apcie0 reg[3], the shared PHY's state, which the train reads; + * the boot loader leaves the PHY up with port 0 + * IRQ 1531: apcie0 interrupts[1] + * PERST#: pci-bridge1 function-perst, gpio0 pin 0x51 (81) + * power: pcie-sdreader function-sd_pwr_en, SMC pcIO (0x0, 0x190000), output + * 3 of smc_pcio below + * link tunables: pci-bridge1's apcie-config-tunables, pcie-rc-tunables and + * pcie-rc-gen{3,4,5}-shadow-tunables, as (offset, size, mask, value) + * The reader is behind dart-apcie1 (0x211000000, IRQ 1532; manual-availability: + * it answers only once the root complex is up). The ADT's mapper-apcie1 names + * no stream (the bridge requests one at run time), so stream 1 is this tree's + * choice, below the DART's first bypass stream (16), as on J714s. + * pci-bridge1's function-clkreq (gpio0 pin 0x4d) is not described: the + * driver does not take CLKREQ# lines. */ &pcie0 { - iommu-map = <0x100 &dart_apcie0 1 3>; + iommu-map = <0x100 &dart_apcie0 1 3>, + <0x200 &dart_apcie1 1 1>; bus-range = <0 4>; - status = "disabled"; + status = "okay"; + reg = <0x1c 0xb0000000 0x0 0x10000000>, + <0x4 0x14000000 0x0 0x4000>, + <0x4 0x10028000 0x0 0x8000>, + <0x4 0x17010000 0x0 0x4000>, + <0x4 0x10024000 0x0 0x4000>, + <0x4 0x11028000 0x0 0x8000>, + <0x4 0x17014000 0x0 0x4000>, + <0x4 0x11024000 0x0 0x4000>, + <0x4 0x17020000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "phy0", "intr2axi0", "port1", "phy1", "intr2axi1", + "phy-shared"; + interrupts = , + ; + interrupt-names = "port0", "port1"; + /* dart_apcie1 probes only once port 1 is up: the host must not wait for it */ + post-init-providers = <&dart_apcie1>; + + port00: pci@0,0 { + device_type = "pci"; + reg = <0x0 0 0 0 0>; + bus-range = <1 1>; + apple,link-trained-by-bootloader; + /* PERST#, driven only by the root-port reset after the N1's ROM stage */ + reset-gpios = <&pinctrl_ap 80 GPIO_ACTIVE_LOW>; + status = "disabled"; + + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &port00 0 0 0 0>, + <0 0 0 2 &port00 0 0 0 1>, + <0 0 0 3 &port00 0 0 0 2>, + <0 0 0 4 &port00 0 0 0 3>; + + n1_control: control@0,0 { + compatible = "pci106b,1900"; + reg = <0x10000 0x0 0x0 0x0 0x0>; + firmware-name = T6050_K_N1_FIRMWARE; + apple,centauri-platform-id = <((T6050_K_BOARD_ID << 16) | 0x6050)>; + apple,centauri-protocol = <27>; + }; + + n1_alpha: wifi@0,1 { + compatible = "pci106b,1902"; + reg = <0x10100 0x0 0x0 0x0 0x0>; + local-mac-address = [00 00 00 00 00 00]; + }; + + n1_beta: bluetooth@0,2 { + compatible = "pci106b,1903"; + reg = <0x10200 0x0 0x0 0x0 0x0>; + local-bd-address = [00 00 00 00 00 00]; + }; + }; + + port01: pci@1,0 { + device_type = "pci"; + reg = <0x800 0 0 0 0>; + bus-range = <2 2>; + /* Down at boot: the kernel trains it, powering the reader first */ + apple,link-trained-by-bootloader; + /* ADT pcie-sdreader function-sd_pwr_en: SMC pcIO output 3 below */ + pwren-gpios = <&smc_pcio 3 GPIO_ACTIVE_HIGH>; + /* PERST#: ADT pci-bridge1 function-perst, GPIO 81 */ + reset-gpios = <&pinctrl_ap 81 GPIO_ACTIVE_LOW>; + /* ADT pci-bridge1 */ + apple,apcie-config-tunables = <0x140 4 0x1 0x1>, + <0x144 4 0xffffff 0x253770>, + <0x8a8 4 0x1 0x1>, + <0x8ac 4 0x1 0x1>; + apple,pcie-rc-tunables = <0x78 4 0x7000 0x0>, + <0x194 4 0x2 0x2>, + <0xb80 4 0x7f3f3f 0x7f1e1e>, + <0xb88 4 0x7f3f3f 0x7f1e1e>; + apple,pcie-rc-gen3-shadow-tunables = <0x154 4 0xf0f0f0f 0x5050505>, + <0x890 4 0x3000000 0x0>, + <0x8a8 4 0xffff0f 0x1>; + apple,pcie-rc-gen4-shadow-tunables = <0x178 4 0xffff 0x5555>, + <0x890 4 0x3000000 0x1000000>, + <0x8a8 4 0xffff0f 0x1>; + apple,pcie-rc-gen5-shadow-tunables = <0x1ac 4 0xffff 0x5555>, + <0x890 4 0x3000000 0x2000000>, + <0x8a8 4 0xffff0f 0x1>; + + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &port01 0 0 0 0>, + <0 0 0 2 &port01 0 0 0 1>, + <0 0 0 3 &port01 0 0 0 2>, + <0 0 0 4 &port01 0 0 0 3>; + + /* + * The GL9755. Card detect and write protect are active high: ADT + * pcie-sdreader card-detect-polarity and write-protect-polarity = 1. + */ + sdhci0: mmc@0,0 { + compatible = "pci17a0,9755"; + reg = <0x20000 0x0 0x0 0x0 0x0>; + cd-inverted; + wp-inverted; + }; + }; +}; + +/* + * ADT dart-apcie1 manual-availability: pcie-apple enables it once port 1 is up. It sits in + * the same apcie block as port 0's DART and takes the same APCIE_SYS_GP (enabled in + * t6050-k114-k116-usb.dtsi), as the T6040's apcie1_dart at the same address does. + */ +&dart_apcie1 { + power-domains = <&ps_apcie_sys_gp>; + apple,manual-availability; + status = "okay"; +}; + +/* + * The PMU's RTC and its alarm. The four boards' ADTs (27.2) give the PMU + * (nub-spmi0/spmi-abbeyL1) the same registers: info-rtc (0x2002), + * info-rtc_alarm_offset (0x2008), info-rtc_irq_mask_offset (0x200e), + * info-rtc_alarm_ctrl (0x2000) and info-rtc_scrpad (0x2100), the registers of + * the T6041 PMU. It raises no interrupt on this SoC: an armed alarm can only + * wake the machine from a firmware sleep, not from s2idle. + */ +&pmu { + pmu_rtc: rtc { + compatible = "apple,t6050-pmu-rtc", "apple,t6041-pmu-rtc"; + nvmem-cells = <&rtc_offset>; + nvmem-cell-names = "rtc_offset"; + wakeup-source; + }; }; /* These boards' SMC fan and power keys are not yet checked */ @@ -259,8 +412,62 @@ /* * The board's pcIO outputs, from the ADT: dp2hdmi_pwr_en pKW8('pcIO', 0, 0x1a0000), * hdmi_pwr_en pKW8('pcIO', 0x800000, 0xf0000), and the trackpad AFE reset (2), - * pKW8('pcIO', 0x10000, 0x11c0000); the same as on J716c. + * pKW8('pcIO', 0x10000, 0x11c0000), the same as on J716c; then the SD reader's + * power (3), sd_pwr_en pKW8('pcIO', 0x0, 0x190000): ADT pcie-sdreader + * function-sd_pwr_en. */ &smc_pcio { - apple,output-commands = /bits/ 64 <0x001a000000000000 0x000f000000800000 0x011c000000010000>; + apple,output-commands = /bits/ 64 <0x001a000000000000 0x000f000000800000 + 0x011c000000010000 0x0019000000000000>; +}; + +/* + * Port 0's power: the ADT's apcie0 power-gates are APCIE_GP (137), APCIE_SYS_GP (143) and the + * fabric; APCIE_SYS_GP sits on APCIE_GP and FAB6_SOC. Its DART (dart-apcie0, which the N1 uses + * through the host's iommu-map) takes APCIE_SYS_GP, as the T600x/T602x PCIe DARTs do. The loader + * trains port 0 and keeps it powered for the hand-off, so these stay firmware-owned + * (enabled in t6050-k114-k116-usb.dtsi, which boards include after t6050-peripherals.dtsi). + */ +&dart_apcie0 { + power-domains = <&ps_apcie_sys_gp>; +}; + +/ { + aliases { + /* asahi-bless and the boot loader find the NVRAM partition by this alias */ + nvram = &nvram; + }; +}; + +/* + * The boot NOR's NVRAM partition, the same in the live K114s, K116s and J716c ADTs and the + * K114c and K116c 27.2 DeviceTrees: /arm-io/qspi/spinor/anvram, 0x700000, 0xc0000 bytes, 12 + * banks of 64 KiB. Only this partition is described, so the rest of the NOR has no device + * node. Single-wire, as on the J775D: spi-nor then sends no quad-enable status write at probe. + * + * The partition is writable, as on the J616s, J713 and J700, so asahi-bless and aurora-bless + * can set the next boot. spi-apple-qspi still starts read-only and, once root + * opts in, admits only bounded, verified programs and 4 KiB erases of a known part inside it. + */ +&qspi { + status = "okay"; + + flash@0 { + compatible = "jedec,spi-nor"; + reg = <0>; + spi-max-frequency = <25000000>; + spi-rx-bus-width = <1>; + spi-tx-bus-width = <1>; + + partitions { + compatible = "fixed-partitions"; + #address-cells = <1>; + #size-cells = <1>; + + nvram: partition@700000 { + label = "nvram"; + reg = <0x700000 0xc0000>; + }; + }; + }; }; diff --git a/arch/arm64/boot/dts/apple/t6050-k114-usb.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-usb.dtsi new file mode 100644 index 00000000000000..24184a4e505ce3 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-k114-usb.dtsi @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The 14-inch K boards' ports beyond t6050-k114-k116-usb.dtsi: the MagSafe 3 PD controller + * on nub-spmi-a0 and ATC2's USB4/Thunderbolt router with its PCIe tunnel. The live K114s ADT + * (27.2) and the K114c's have the same nodes and values here, phandles aside. + * + * Included after t6050-k114-k116-usb.dtsi. t6050-max.dtsi describes the ATC2 router for the + * boards that define T6050_K114C or T6050_K114S before including it. + */ + +/* + * nub-spmi-a0's generation 4 fault queue: ADT reg[1] 0x8a184000 + 0x4000, which macOS empties + * when the controller starts. + */ +&nub_spmi_a0 { + reg = <0x2 0x8a188000 0x0 0x4000>, + <0x2 0x8a184000 0x0 0x4000>; + + /* + * The MagSafe 3 port's PD controller (ADT hpm5, port-type 0x11). It has no USB data + * path, so it gets no connector node; tipd registers a Type-C port and a power supply + * for it. Its ADT features-supported is <3>, "Power In" only: no liquid detection. + */ + hpm5: usb-pd@8 { + compatible = "apple,sn201202x"; + reg = <0x8 SPMI_USID>; + apple,no-liquid-detection; + }; +}; + +/* + * The right port's USB4/Thunderbolt router (acio2) and PCIe tunnel; the DisplayPort route + * is not described. + */ +#include "t6050-max-atc2-router.dtsi" + +/* + * The host DROM from the ADT (/arm-io/acio2 thunderbolt-drom, the same on the K114c and the + * K114s); the boot loader replaces it + */ +&acio2_nhi { + apple,thunderbolt-drom = [fd 02 00 00 00 00 00 00 00 90 19 c3 8c 00 5c 00 + 00 00 00 00 00 00 08 81 82 02 82 00 00 00 08 82 + 92 01 82 00 00 00 03 83 20 08 84 00 00 00 00 00 + 00 08 85 00 00 00 00 00 00 05 86 09 01 00 08 87 + 00 00 00 00 00 00 05 88 09 01 00 05 89 09 01 00 + 05 8a 09 01 00 0e 01 41 70 70 6c 65 2c 20 49 6e + 63 2e 00 06 02 69 4f 53 00 00 00 00]; +}; + +/* The right router's suppliers, disabled in the inventory (as t6050-j714s-display.dtsi enables them) */ +&ps_atc2_cio { + status = "okay"; +}; + +&ps_atc2_cio_pcie { + status = "okay"; +}; + +&ps_atc2_cio_usb { + status = "okay"; +}; + +&ps_atc2_cio_auss { + status = "okay"; +}; + +&ps_atc2_pcie { + status = "okay"; +}; + +/* + * The router and its mailbox are on, with all five domains and the PCIe tunnel, whether or not + * t6050-max.dtsi leaves acio2 disabled and without the fifth domain for boards outside its list. + */ +&acio2_mbox { + status = "okay"; +}; + +&acio2 { + status = "okay"; + power-domains = <&ps_atc2_cio>, <&ps_atc2_cio_pcie>, + <&ps_atc2_cio_usb>, <&ps_atc2_cio_auss>, <&ps_atc2_pcie>; + apple,pcie-tunnel = <&acio2_pcie_tunnel>; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-k114.dtsi b/arch/arm64/boot/dts/apple/t6050-k114.dtsi new file mode 100644 index 00000000000000..4f9c13198dfff0 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-k114.dtsi @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The 14-inch K boards' chassis (K114c, M5 Max, and K114s, M5 Pro): what their ADTs describe + * alike beyond what t6050-k114-k116.dtsi shares with the 16-inch boards. The live K114s ADT + * (27.2) and the K114c's have the same nodes and values here, phandles aside. + * + * The speaker amps are left to the board: they need a qualified speaker protection, which + * the K114s does not have. + * + * Included after t6050-peripherals.dtsi. + */ + +/* + * The Neural Engine (ADT ane0, "ane,t8132exclave", firmware pre-loaded by iBoot), started only + * after the boot loader's preload hand-off + */ +#include "t6050-j714s-ane.dtsi" + +/* + * ANE_SYS's declared suppliers are the fabric domains: enabled the way + * the J714s enables them (t6050-j714s.dts for fab8/fab0, + * t6050-j716c-isp.dtsi for fab9). Left disabled they never register a + * provider and the enabled ps_ane_sys defers forever, taking ane0 and its + * three DARTs with it. + */ +&ps_fab0_piogw { + apple,firmware-owned; + status = "okay"; +}; + +&ps_fab8_soc { + apple,firmware-owned; + status = "okay"; +}; + +&ps_fab9_soc { + /delete-property/ power-domains; + apple,no-auto-pm; + apple,firmware-owned; + status = "okay"; +}; + +/* + * Pin 112's register takes an SError when read, so only the pins a node names are + * exposed: 80 and 81 (PCIe ports 0 and 1's PERST#); 106 and 107, the speaker amps' + * interrupt and shutdown line (ADT audio-speaker, used only where a board describes + * the amps); 134 and 139, the jack codec's interrupt and reset; 136 and 137, the + * speaker ID; 138, the Touch ID sensor's data-ready line (t6050-touchid.dtsi). + */ +&pinctrl_ap { + gpio-reserved-ranges = <0 80>, <82 24>, <108 26>, <135 1>, <140 81>; +}; + +/* + * The CS42L84 headphone codec (ADT /arm-io/i2c2/audio-codec-output): its reset line + * is AP pin 139, driven high to run the codec, and its interrupt AP pin 134, level + * low. + */ +&i2c2 { + status = "okay"; + + jack_codec: codec@4b { + compatible = "cirrus,cs42l84"; + reg = <0x4b>; + reset-gpios = <&pinctrl_ap 139 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 134 IRQ_TYPE_LEVEL_LOW>; + #sound-dai-cells = <0>; + sound-name-prefix = "Jack"; + }; +}; + +/ { + sound { + /* + * The headphone jack only. The speaker amps and the "Speaker" link are not + * described here: no speaker protection is qualified for this chassis + * (speakerguardd refuses it), and the K114 entry has the speakers off. + */ + compatible = "apple,k114-macaudio", "apple,macaudio"; + model = "MacBook Pro K114"; + /* ADT audio-speaker function-speaker-id0 and -id1 */ + speaker-id-gpios = <&pinctrl_ap 136 GPIO_ACTIVE_HIGH>, + <&pinctrl_ap 137 GPIO_ACTIVE_HIGH>; + #address-cells = <1>; + #size-cells = <0>; + + dai-link@0 { + reg = <0>; + link-name = "Headphone Jack"; + + cpu { + sound-dai = <&aop_audio 0>; + }; + + codec { + sound-dai = <&jack_codec>; + }; + }; + }; +}; + +/* The AOP, booted through its setup port, with its sensor and audio services. */ +&aop_mbox { + status = "okay"; +}; + +&aop_setup_mbox { + status = "okay"; +}; + +&aop_dart { + status = "okay"; +}; + +&aop { + status = "okay"; +}; + +/* + * The microphone array: ADT audio-hp-mic, three microphones on leap-s RX0 through the + * proxy ADMAC (Linux channel 1, as on J813), captured by the AOP audio service's own card. + */ +&admac_base_ns { + status = "okay"; +}; + +&admac_ec_proxy { + status = "okay"; +}; + +&aop_audio { + apple,chassis-name = "K114"; + apple,machine-kind = "MacBook Pro"; + dmas = <&admac_base_ns 4>, <&admac_base_ns 5>, + <&admac_base_ns 0>, <&admac_base_ns 1>, + <&admac_ec_proxy 1>; + dma-names = "cout", "cin", "spkr", "sense", "hpai"; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index 6100f9d1cf80c4..7923a3807e0101 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -4,13 +4,21 @@ * * target-type: K114c (Mac17,11) * - * Preliminary: described from the ADT only, not yet booted on the hardware. + * Boots on the hardware; the SD card reader (PCIe port 1) is tested. The other + * blocks are described from the ADT. * * Copyright The Asahi Linux Contributors */ /* Defined before the includes: t6050-max.dtsi guards the ATC2 router on it. */ #define T6050_K114C +/* The M5 Max die-0 blocks (nub-spmi1, nub-spmi4) */ +#include "t6050-soc-max.dtsi" +/* ADT /arm-io/acio2: the right port's USB4/Thunderbolt router */ +#define T6050_ATC2_USB4_ROUTER +/* The N1's firmware and this board's ADT board-id, for t6050-k114-k116.dtsi */ +#define T6050_K_N1_FIRMWARE "apple/centauri/k114c-ftab.bin" +#define T6050_K_BOARD_ID 0x04 #include "t6050-k114-k116.dtsi" / { @@ -24,96 +32,10 @@ #include "t6050-peripherals.dtsi" -/ { - aliases { - /* kboot fills the N1's factory addresses from /chosen through these */ - wifi0 = &n1_alpha; - bluetooth0 = &n1_beta; - nvram = &nvram; - }; -}; - -/* - * PCIe port 0: the N1 (Wi-Fi and Bluetooth), laid out as on J716c: the boot - * loader trains the link and keeps power, clocks, the PHY and PERST; Linux owns - * the routing, MSI and the DART. The port stays disabled until the loader - * trains it. - */ -&pcie0 { - reg = <0x1c 0xb0000000 0x0 0x10000000>, - <0x4 0x14000000 0x0 0x4000>, - <0x4 0x10028000 0x0 0x8000>, - <0x4 0x17010000 0x0 0x4000>, - <0x4 0x10024000 0x0 0x4000>; - reg-names = "config", "rc", "port0", "phy0", "intr2axi0"; - interrupts = ; - interrupt-names = "port0"; - - /* The N1's three functions are on DART streams 1-3 */ - iommu-map = <0x100 &dart_apcie0 1 3>; - bus-range = <0 4>; - status = "okay"; - - port00: pci@0,0 { - device_type = "pci"; - reg = <0x0 0 0 0 0>; - bus-range = <1 1>; - apple,link-trained-by-bootloader; - /* PERST#, driven only by the root-port reset after the N1's ROM stage */ - reset-gpios = <&pinctrl_ap 80 GPIO_ACTIVE_LOW>; - status = "disabled"; - - #address-cells = <3>; - #size-cells = <2>; - ranges; - - interrupt-controller; - #interrupt-cells = <1>; - interrupt-map-mask = <0 0 0 7>; - interrupt-map = <0 0 0 1 &port00 0 0 0 0>, - <0 0 0 2 &port00 0 0 0 1>, - <0 0 0 3 &port00 0 0 0 2>, - <0 0 0 4 &port00 0 0 0 3>; - - /* platform ID (board 0x04 << 16) | chip 0x6050 */ - n1_control: control@0,0 { - compatible = "pci106b,1900"; - reg = <0x10000 0x0 0x0 0x0 0x0>; - firmware-name = "apple/centauri/k114c-ftab.bin"; - apple,centauri-platform-id = <0x00046050>; - apple,centauri-protocol = <27>; - }; - - n1_alpha: wifi@0,1 { - compatible = "pci106b,1902"; - reg = <0x10100 0x0 0x0 0x0 0x0>; - local-mac-address = [00 00 00 00 00 00]; - }; - - n1_beta: bluetooth@0,2 { - compatible = "pci106b,1903"; - reg = <0x10200 0x0 0x0 0x0 0x0>; - local-bd-address = [00 00 00 00 00 00]; - }; - }; -}; - -/* - * Pin 112's register takes an SError when read, so only the pins a node here - * names are exposed: 80 (PCIe port 0's PERST#); 106 and 107, the speaker amps' - * interrupt and shutdown line; 134 and 139, the jack codec's interrupt and - * reset; 136 and 137, the speaker ID. - */ -&pinctrl_ap { - gpio-reserved-ranges = <0 80>, <81 25>, <108 26>, <135 1>, <138 1>, <140 81>; -}; - -#include "t6050-k114c-gpu.dtsi" - /* - * Sound through the AOP, as on J813: its audio service runs the serializers, the - * CS42L84 headphone jack on admac-base-ns TX2/RX2 and the six SN012776 speaker amps - * on TX0, their voltage and current sense on RX0 (ADT iop-audio-controller). + * The speakers, through the AOP as on J813: the six SN012776 speaker amps on admac-base-ns + * TX0, their voltage and current sense on RX0 (ADT iop-audio-controller). The jack, the + * card and the AOP are the chassis' (t6050-k114.dtsi). * * The amps (ADT /arm-io/i2c1/audio-speaker* and /arm-io/i2c3/audio-speaker*) share * one shutdown line, AP pin 107 (function-reset of the first), and one fault @@ -226,385 +148,67 @@ }; }; -/* - * The CS42L84 headphone codec (ADT /arm-io/i2c2/audio-codec-output): its reset line - * is AP pin 139, driven high to run the codec, and its interrupt AP pin 134, level - * low. - */ -&i2c2 { - status = "okay"; - - jack_codec: codec@4b { - compatible = "cirrus,cs42l84"; - reg = <0x4b>; - reset-gpios = <&pinctrl_ap 139 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 134 IRQ_TYPE_LEVEL_LOW>; - #sound-dai-cells = <0>; - sound-name-prefix = "Jack"; - }; -}; - -/ { - sound { - compatible = "apple,j714-macaudio", "apple,macaudio"; - model = "MacBook Pro K114"; - /* ADT audio-speaker function-speaker-id0 and -id1 */ - speaker-id-gpios = <&pinctrl_ap 136 GPIO_ACTIVE_HIGH>, - <&pinctrl_ap 137 GPIO_ACTIVE_HIGH>; - #address-cells = <1>; - #size-cells = <0>; - - dai-link@0 { - reg = <0>; - link-name = "Headphone Jack"; - - cpu { - sound-dai = <&aop_audio 0>; - }; - - codec { - sound-dai = <&jack_codec>; - }; - }; - - dai-link@1 { - reg = <1>; - link-name = "Speaker"; - /* - * Codecs in ADT speaker-config order, so that macaudio gives them - * playback slots 0-5 as macOS does (left channels in slots 0, 2 - * and 4, right in 1, 3 and 5). The idle masks are the ADT - * amp-tx-zd-config rows 0 and 1: left woofer 1 drives zeros in the - * right amps' sense slots, right woofer 1 in the left amps'. - */ - dai-tdm-idle-mode-0 = "zero"; - dai-tdm-slot-tx-idle-mask-0 = <0xfff0f0f0>; - dai-tdm-idle-mode-1 = "zero"; - dai-tdm-slot-tx-idle-mask-1 = <0xff0f0f0f>; - - cpu { - sound-dai = <&aop_audio 3>; - }; - - codec { - sound-dai = <&speaker_left_woof1>, <&speaker_right_woof1>, - <&speaker_left_woof2>, <&speaker_right_woof2>, - <&speaker_left_tweet>, <&speaker_right_tweet>; - }; - }; - }; -}; - -/* The AOP, booted through its setup port, with its sensor and audio services. */ -&aop_mbox { - status = "okay"; -}; +/* The 14-inch chassis: the Neural Engine, pins, the jack, the card and the AOP */ +#include "t6050-k114.dtsi" -&aop_setup_mbox { - status = "okay"; -}; +/* The GPU, handed over by the boot loader */ +#include "t6050-k114-k116-gpu.dtsi" -&aop_dart { - status = "okay"; -}; - -&aop { - status = "okay"; -}; +/* The internal panel, handed over by the boot loader */ +#include "t6050-k114-k116-display.dtsi" /* - * The microphone array: ADT audio-hp-mic, three microphones on leap-s RX0 through the - * proxy ADMAC (Linux channel 1, as on J813), captured by the AOP audio service's own card. + * The 14.2-inch 3024x1986 panel's active area (254 dpi, the notch rows included), for the + * DPI only (the ADT carries none) */ -&admac_base_ns { - status = "okay"; +&panel { + compatible = "apple,panel-k114", "apple,panel"; + width-mm = <302>; + height-mm = <199>; }; -&admac_ec_proxy { - status = "okay"; -}; - -&aop_audio { - apple,chassis-name = "K114"; - apple,machine-kind = "MacBook Pro"; - dmas = <&admac_base_ns 4>, <&admac_base_ns 5>, - <&admac_base_ns 0>, <&admac_base_ns 1>, - <&admac_ec_proxy 1>; - dma-names = "cout", "cin", "spkr", "sense", "hpai"; -}; +/* Touch ID: the SEP and the Mesa sensor, with this Mac's own calibration and root key */ +#define T6050_TOUCHID_FIRMWARE "apple/mesacal-k114c.bin", "apple/msrk-k114c.bin" +#include "t6050-touchid.dtsi" /* - * ==== The left-front USB-C port (ATC1) ==== - * - * ADT /arm-io/nub-spmi-a0/hpm1 (SN201202x, SPMI address 0xa, port-number 2, port-location - * "left-front", acio-parent acio1), with atc-phy1, usb-drd1 and dart-usb1. The K114cAP ADT - * has the same hpm0, hpm1, hpm5, atc-phy and usb-drd nodes as the J714cAP one, so this is the - * J714c port block. The ATC1 template nodes of t6050-dieX.dtsi are enabled here; the boards - * sharing t6050-k114-k116.dtsi keep them disabled. The port's USB4/Thunderbolt router - * (/arm-io/acio1) and its DisplayPort routes are not described; the PHY runs in USB mode. - * - * The left-back port (ATC0, hpm0) is the boot link's debug port; the combo PHY driver - * excludes it on purpose (apple,port-index 0). + * The K114c keeps J714's card with its speakers, at the J714's safe level. The + * chassis' K114 entry (t6050-k114.dtsi) has the jack only. */ -/ { - aliases { - atcphy1 = &atc1_phy; - }; -}; - -&nub_spmi_a0 { - status = "okay"; - /* reg[1]: the generation 4 fault queue, which macOS empties when the controller starts */ - reg = <0x2 0x8a188000 0x0 0x4000>, - <0x2 0x8a184000 0x0 0x4000>; - - hpm1: usb-pd@a { - compatible = "apple,sn201202x"; - reg = <0xa SPMI_USID>; - - connector { - compatible = "usb-c-connector"; - label = "USB-C Left-front"; - power-role = "dual"; - data-role = "dual"; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - hpm1_hs: endpoint { - remote-endpoint = <&usb_drd1_hs>; - }; - }; - - port@1 { - reg = <1>; - hpm1_ss: endpoint { - remote-endpoint = <&atc1_phy_ep>; - }; - }; - }; - }; - }; - - /* - * The MagSafe 3 port's PD controller (ADT hpm5, port-type 0x11). It has no USB data - * path, so it gets no connector node; tipd registers a Type-C port and a power supply - * for it. Its ADT features-supported is <3>, "Power In" only: no liquid detection. - */ - hpm5: usb-pd@8 { - compatible = "apple,sn201202x"; - reg = <0x8 SPMI_USID>; - apple,no-liquid-detection; - }; -}; - -&atc1_phy_mbox { - status = "okay"; -}; - -&atc1_phy { - status = "okay"; - - port { - atc1_phy_ep: endpoint { - remote-endpoint = <&hpm1_ss>; +&{/sound} { + compatible = "apple,j714-macaudio", "apple,macaudio"; + + dai-link@1 { + reg = <1>; + link-name = "Speaker"; + /* + * Codecs in ADT speaker-config order, so that macaudio gives them + * playback slots 0-5 as macOS does (left channels in slots 0, 2 + * and 4, right in 1, 3 and 5). The idle masks are the ADT + * amp-tx-zd-config rows 0 and 1: left woofer 1 drives zeros in the + * right amps' sense slots, right woofer 1 in the left amps'. + */ + dai-tdm-idle-mode-0 = "zero"; + dai-tdm-slot-tx-idle-mask-0 = <0xfff0f0f0>; + dai-tdm-idle-mode-1 = "zero"; + dai-tdm-slot-tx-idle-mask-1 = <0xff0f0f0f>; + + cpu { + sound-dai = <&aop_audio 3>; }; - }; -}; - -&usb_drd1 { - status = "okay"; - port { - usb_drd1_hs: endpoint { - remote-endpoint = <&hpm1_hs>; + codec { + sound-dai = <&speaker_left_woof1>, <&speaker_right_woof1>, + <&speaker_left_woof2>, <&speaker_right_woof2>, + <&speaker_left_tweet>, <&speaker_right_tweet>; }; }; }; -&usb_drd1_dart_0 { - status = "okay"; -}; - -&usb_drd1_dart_1 { - status = "okay"; -}; - /* - * ==== The right USB-C port (ATC2) ==== - * - * ADT /arm-io/nub-spmi-a1/hpm2 (SN201202x, SPMI address 0xc, port-number 3, port-location - * "right", acio-parent acio2), with atc-phy2, usb-drd2 and dart-usb2. The HPM is on its own - * bus, nub-spmi-a1, and nothing hands the port off, so the power domains, the PHY mailbox, the - * PHY, the DWC3 and its DARTs are enabled outright, as t6050-max-atc2.dtsi does for the J714c - * and J716c. Its USB4/Thunderbolt router (acio2) and PCIe tunnel are - * t6050-max-atc2-router.dtsi, included below; the DisplayPort route is not described. + * The USB-C ports ATC1 and ATC2, as on the other K boards (t6050-k114-k116-usb.dtsi), then the + * 14-inch chassis' MagSafe 3 PD controller and the right port's USB4/Thunderbolt router + * (t6050-k114-usb.dtsi). */ -/ { - aliases { - atcphy2 = &atc2_phy; - }; -}; - -&ps_atc2_common { - status = "okay"; -}; - -&ps_atc2_usb_aon { - status = "okay"; -}; - -&ps_atc2_phymxwrap { - status = "okay"; -}; - -&ps_atc2_usb { - status = "okay"; -}; - -&atc2_phy_mbox { - status = "okay"; -}; - -&atc2_phy { - status = "okay"; - - port { - atc2_phy_ep: endpoint { - remote-endpoint = <&hpm2_ss>; - }; - }; -}; - -&usb_drd2 { - status = "okay"; - - port { - usb_drd2_hs: endpoint { - remote-endpoint = <&hpm2_hs>; - }; - }; -}; - -&usb_drd2_dart_0 { - status = "okay"; -}; - -&usb_drd2_dart_1 { - status = "okay"; -}; - -&nub_spmi_a1 { - status = "okay"; - /* the driver polls the PD controllers and refuses an interrupt on this bus */ - /delete-property/ interrupts; - - hpm2: usb-pd@c { - compatible = "apple,sn201202x"; - reg = <0xc SPMI_USID>; - - connector { - compatible = "usb-c-connector"; - label = "USB-C Right"; - power-role = "dual"; - data-role = "dual"; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - hpm2_hs: endpoint { - remote-endpoint = <&usb_drd2_hs>; - }; - }; - - port@1 { - reg = <1>; - hpm2_ss: endpoint { - remote-endpoint = <&atc2_phy_ep>; - }; - }; - }; - }; - }; -}; - -#include "t6050-max-atc2-router.dtsi" - -/* The host DROM from the K114cAP ADT (/arm-io/acio2 thunderbolt-drom); the boot loader replaces it */ -&acio2_nhi { - apple,thunderbolt-drom = [fd 02 00 00 00 00 00 00 00 90 19 c3 8c 00 5c 00 - 00 00 00 00 00 00 08 81 82 02 82 00 00 00 08 82 - 92 01 82 00 00 00 03 83 20 08 84 00 00 00 00 00 - 00 08 85 00 00 00 00 00 00 05 86 09 01 00 08 87 - 00 00 00 00 00 00 05 88 09 01 00 05 89 09 01 00 - 05 8a 09 01 00 0e 01 41 70 70 6c 65 2c 20 49 6e - 63 2e 00 06 02 69 4f 53 00 00 00 00]; -}; - -/* The right router's suppliers, disabled in the inventory (as t6050-j714s-display.dtsi enables them) */ -&ps_atc2_cio { - status = "okay"; -}; - -&ps_atc2_cio_pcie { - status = "okay"; -}; - -&ps_atc2_cio_usb { - status = "okay"; -}; - -&ps_atc2_cio_auss { - status = "okay"; -}; - -&ps_atc2_pcie { - status = "okay"; -}; - -/* - * The router and its mailbox are on, with all five domains and the PCIe tunnel, whether or not - * t6050-max.dtsi leaves acio2 disabled and without the fifth domain for boards outside its list. - */ -&acio2_mbox { - status = "okay"; -}; - -&acio2 { - status = "okay"; - power-domains = <&ps_atc2_cio>, <&ps_atc2_cio_pcie>, - <&ps_atc2_cio_usb>, <&ps_atc2_cio_auss>, <&ps_atc2_pcie>; - apple,pcie-tunnel = <&acio2_pcie_tunnel>; -}; - -/* - * The boot NOR. spi-nor reads the part's JEDEC ID itself. The partition is - * read-only: no program or erase reaches the flash until a later change lifts it. - */ -&qspi { - status = "okay"; - - flash@0 { - compatible = "jedec,spi-nor"; - reg = <0>; - spi-max-frequency = <25000000>; - - partitions { - compatible = "fixed-partitions"; - #address-cells = <1>; - #size-cells = <1>; - - nvram: partition@700000 { - label = "nvram"; - reg = <0x700000 0xc0000>; - read-only; - }; - }; - }; -}; +#include "t6050-k114-k116-usb.dtsi" +#include "t6050-k114-usb.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-k114s.dts b/arch/arm64/boot/dts/apple/t6050-k114s.dts index caa609babef0d5..fdf02afb0530eb 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114s.dts @@ -4,11 +4,19 @@ * * target-type: K114s (Mac17,13) * - * Preliminary: described from the ADT only, not yet booted on the hardware. + * Preliminary: described from the ADT. Only the NVRAM partition (t6050-k114-k116.dtsi) has been run + * on a K114s, from the boot loader's tree; this file as a whole has not been booted. * * Copyright The Asahi Linux Contributors */ +/* Defined before the includes, which select this board's blocks on it. */ +#define T6050_K114S +/* ADT /arm-io/acio2: the right port's USB4/Thunderbolt router */ +#define T6050_ATC2_USB4_ROUTER +/* The N1's firmware and this board's ADT board-id, for t6050-k114-k116.dtsi */ +#define T6050_K_N1_FIRMWARE "apple/centauri/k114s-ftab.bin" +#define T6050_K_BOARD_ID 0x14 #include "t6050-k114-k116.dtsi" / { @@ -20,5 +28,35 @@ firmware-name = "apple/tpmtfw-k114s.bin"; }; -#define T6050_K114S #include "t6050-peripherals.dtsi" + +/* The 14-inch chassis: the Neural Engine, pins, the jack, the card and the AOP; no speakers */ +#include "t6050-k114.dtsi" + +/* The GPU, handed over by the boot loader */ +#include "t6050-k114-k116-gpu.dtsi" + +/* The internal panel, handed over by the boot loader */ +#include "t6050-k114-k116-display.dtsi" + +/* + * The 14.2-inch 3024x1986 panel's active area (254 dpi, the notch rows included), for the + * DPI only (the ADT carries none) + */ +&panel { + compatible = "apple,panel-k114", "apple,panel"; + width-mm = <302>; + height-mm = <199>; +}; + +/* Touch ID: the SEP and the Mesa sensor, with this Mac's own calibration and root key */ +#define T6050_TOUCHID_FIRMWARE "apple/mesacal-k114s.bin", "apple/msrk-k114s.bin" +#include "t6050-touchid.dtsi" + +/* + * The USB-C ports ATC1 and ATC2, as on the other K boards (t6050-k114-k116-usb.dtsi), then the + * 14-inch chassis' MagSafe 3 PD controller and the right port's USB4/Thunderbolt router + * (t6050-k114-usb.dtsi). + */ +#include "t6050-k114-k116-usb.dtsi" +#include "t6050-k114-usb.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-k116c.dts b/arch/arm64/boot/dts/apple/t6050-k116c.dts index ff9e875fb19516..4439c8fd8dc688 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116c.dts @@ -9,6 +9,9 @@ * Copyright The Asahi Linux Contributors */ +/* The N1's firmware and this board's ADT board-id, for t6050-k114-k116.dtsi */ +#define T6050_K_N1_FIRMWARE "apple/centauri/k116c-ftab.bin" +#define T6050_K_BOARD_ID 0x06 #include "t6050-k114-k116.dtsi" / { @@ -21,4 +24,26 @@ }; #define T6050_K116C +/* The M5 Max die-0 blocks (nub-spmi1, nub-spmi4) */ +#include "t6050-soc-max.dtsi" #include "t6050-peripherals.dtsi" + +/* The GPU, handed over by the boot loader */ +#include "t6050-k114-k116-gpu.dtsi" + +/* The internal panel, handed over by the boot loader */ +#include "t6050-k114-k116-display.dtsi" + +/* The 16.2-inch 3456x2234 panel's active area, for the DPI only (the ADT carries none) */ +&panel { + compatible = "apple,panel-k116", "apple,panel"; + width-mm = <345>; + height-mm = <223>; +}; + +/* Touch ID: the SEP and the Mesa sensor, with this Mac's own calibration and root key */ +#define T6050_TOUCHID_FIRMWARE "apple/mesacal-k116c.bin", "apple/msrk-k116c.bin" +#include "t6050-touchid.dtsi" + +/* The USB-C ports ATC1 and ATC2, as on the other K boards */ +#include "t6050-k114-k116-usb.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-k116s-gpu.dtsi b/arch/arm64/boot/dts/apple/t6050-k116s-gpu.dtsi deleted file mode 100644 index 7bc349759028da..00000000000000 --- a/arch/arm64/boot/dts/apple/t6050-k116s-gpu.dtsi +++ /dev/null @@ -1,155 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0+ OR MIT -/* - * K116s GPU (AGX G17S, ADT /arm-io/sgx "gpu,t6050") for the boot loader hand-off. - * - * It is the GPU half of t6050-j714s-gpu-panel.dtsi (integration/aurora 06c3db9c3752); the - * K116s tree already has its own display half. Everything stays disabled: a loader with the - * G17S hand-off fills the six reservations from the ADT and enables the GPU PMGR, GPX, AFR, - * GFX, both mailboxes and the GPU, the GPU last. Without such a loader (the enrolled aura - * 58d65df0 has none for this layout) this file changes nothing at run time except the two - * always-on marks, which sit on disabled nodes. - * - * Every value below was checked against the K116s 27.2 ADT. arm-io ranges add 0x2_0000_0000 - * to the 0x21_xxxx_xxxx bus addresses (bus 0x20_2000_0000 -> parent 0x22_2000_0000). - */ - -/ { - aliases { - /* The loader finds the GPU through this alias */ - gpu = &sgx; - }; - - reserved-memory { - /* - * Filled and enabled by the loader from the ADT. K116s 27.2 values, for - * reference only (never hard-code: iBoot places them): - * gpu-fw-text 0x100_00ff8000 + 0xa4000 gfx-asc __TEXT 0x50000, then - * gfx1-asc __TEXT 0x54000 at - * 0x100_01048000 - * gpu-fw-data 0x100_0251c000 + 0x184000 sgx gfx-data-base .. end of - * gfx1-data-shared-ro - * uat-ttbs 0x10f_fffa8000 + 0x4000 sgx gpu-region-base/-size - * uat-pagetables 0x10f_fff28000 + 0x80000 sgx gfx-shared-region-* - * uat-l2-pagetables 0x10f_fff24000 + 0x4000 sgx gfx-shared-l2-region-* - * uat-handoff 0x10f_fff20000 + 0x4000 sgx gfx-handoff-* - * The four UAT ranges are the J714s's (aura ec204ea50b5d message); the firmware - * segments differ (J714s 27.0: fw-text 0x100_00fd4000, fw-data 0x100_024f4000). - */ - gpu_fw_text: gpu-fw-text { - reg = <0 0 0 0>; - no-map; - status = "disabled"; - }; - - gpu_fw_data: gpu-fw-data { - reg = <0 0 0 0>; - no-map; - status = "disabled"; - }; - - uat_ttbs: uat-ttbs { - reg = <0 0 0 0>; - no-map; - status = "disabled"; - }; - - uat_pagetables: uat-pagetables { - reg = <0 0 0 0>; - no-map; - status = "disabled"; - }; - - uat_l2_pagetables: uat-l2-pagetables { - reg = <0 0 0 0>; - no-map; - status = "disabled"; - }; - - uat_handoff: uat-handoff { - reg = <0 0 0 0>; - no-map; - status = "disabled"; - }; - }; -}; - -/* The inventory ASC nodes; the mailboxes below describe the same windows. */ -/delete-node/ &gfx_asc; -/delete-node/ &gfx1_asc; - -&{/soc} { - /* - * ADT gfx-asc: reg 0x21_02600000 + 0x88000 (wrapper), 0x21_02050000 + 8 (iop-vbar); - * interrupts [2798, 2797, 2800, 2799], of which the second and third are send-empty - * and recv-not-empty; role "GFX"; power-gates [614] = GFX_ASC. As J714s. - */ - gfx_mbox: mailbox@2302600000 { - compatible = "apple,t6050-j775d-ascwrap-v6"; - reg = <0x23 0x2600000 0x0 0x88000>, - <0x23 0x2050000 0x0 0x8>; - reg-names = "wrapper", "iop-vbar"; - interrupts = , - ; - interrupt-names = "send-empty", "recv-not-empty"; - apple,firmware-role = "GFX"; - power-domains = <&ps_gfx>; - #mbox-cells = <0>; - status = "disabled"; - }; - - /* - * ADT gfx1-asc: reg 0x21_02e00000 + 0x88000, 0x21_02850000 (ADT size 0x60000; the - * driver uses the first 8 bytes as on J714s); interrupts [2802, 2801, 2804, 2803]; - * role "GFX1"; power-gates [657] = GFX_ASC1. - */ - gfx1_mbox: mailbox@2302e00000 { - compatible = "apple,t6050-j775d-ascwrap-v6"; - reg = <0x23 0x2e00000 0x0 0x88000>, - <0x23 0x2850000 0x0 0x8>; - reg-names = "wrapper", "iop-vbar"; - interrupts = , - ; - interrupt-names = "send-empty", "recv-not-empty"; - apple,firmware-role = "GFX1"; - power-domains = <&ps_gfx>; - #mbox-cells = <0>; - status = "disabled"; - }; -}; - -/* - * ADT pmgr devices: GPX (id 359, reg +0x0), AFR (id 360, +0x100) and GFX (id 362, +0x110) - * in the GPU PMGR (pmgr reg[51] 0x21_00e80000). The K116s ADT marks GPX and AFR critical, - * GFX not, as the J714s file states for its board. - */ -&ps_gpx { - apple,always-on; -}; - -&ps_afr { - apple,always-on; -}; - -&sgx { - /* - * "apple,agx-g17s" is what the loader checks and the driver binds - * (drivers/gpu/drm/asahi/driver.rs). The driver uses the J714 tables for it, - * 5 mV below this unit's ADT voltages at eight of the fourteen states. - */ - compatible = "apple,agx-g17s"; - /* ADT sgx reg[0] 0x21_00000000 + 0x3fdc000; the driver maps the first 16 MiB as "sgx" */ - reg = <0x23 0x0 0x0 0x3fdc000>; - reg-names = "sgx"; - /delete-property/ interrupts; - mboxes = <&gfx_mbox>, <&gfx1_mbox>; - memory-region = <&uat_ttbs>, <&uat_pagetables>, <&uat_handoff>, - <&gpu_fw_data>, <&uat_l2_pagetables>, <&gpu_fw_text>; - memory-region-names = "ttbs", "pagetables", "handoff", "fw-data", - "l2-pagetables", "fw-text"; - /* - * As t6050-j714s.dts: the GPU on the PMP's GFX report entry (report@f, on ps_gfx), - * so the PMP is told the GPU is on only while it is powered. The K116s already - * runs the PMP with its report (t6050-k116s.dts &pmp0_report). - */ - power-domains = <&pmp0_gfx>; -}; diff --git a/arch/arm64/boot/dts/apple/t6050-k116s-sleep.dtsi b/arch/arm64/boot/dts/apple/t6050-k116s-sleep.dtsi new file mode 100644 index 00000000000000..1c7c50da725271 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-k116s-sleep.dtsi @@ -0,0 +1,285 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * Deep sleep (suspend to RAM) on the K116s: the J714s description with this board's differences + * (the pins, the display coprocessor's secure mailbox, dcpext0). The sleep controller and what + * it needs from the rest of the tree. + */ + +/ { + aliases { + /* The boot loader finds the SIO by this alias */ + sio = &sio; + }; + + sleep: sleep-controller@280600000 { + compatible = "apple,t6050-sleep"; + reg = <0x2 0x80600000 0x0 0x4000>, + <0x2 0x80900000 0x0 0x4000>, + <0x2 0x88300000 0x0 0xc000>, + <0x23 0x00e80000 0x0 0x4000>, + <0x23 0x80600000 0x0 0xc000>, + <0x23 0x88300000 0x0 0x4000>, + <0x2 0x80760000 0x0 0x10000>, + <0x2 0x807d4000 0x0 0x4000>, + <0x2 0x80930000 0x0 0x4000>, + <0x23 0x00e90000 0x0 0x4000>, + <0x23 0x80760000 0x0 0x10000>, + <0x2 0x80700000 0x0 0x20000>, + <0x23 0x80700000 0x0 0x14000>, + <0x2 0x807ec000 0x0 0x4000>, + <0x2 0x80950000 0x0 0x4000>, + <0x23 0x807dc000 0x0 0x4000>, + <0x2 0x80620000 0x0 0x4000>, + <0x2 0x8062c000 0x0 0x4000>, + <0x2 0x80688000 0x0 0x4000>, + <0x2 0x88f04000 0x0 0x4000>, + <0x2 0x8836c000 0x0 0x4000>, + <0x2 0x88330000 0x0 0x4000>, + <0x2 0x80920000 0x0 0x4000>, + <0x2 0x8a014000 0x0 0x4000>, + <0x2 0x86700000 0x0 0x14000>, + <0x2 0x86806000 0x0 0x3000>, + <0x2 0x84240000 0x0 0x20000>, + <0x2 0x803f0000 0x0 0x4000>, + <0x2 0x88370000 0x0 0x4000>, + <0x23 0x88370000 0x0 0x4000>, + <0x2 0x10e40000 0x0 0x10000>, + <0x2 0x11e40000 0x0 0x10000>, + <0x2 0x12e40000 0x0 0x10000>, + <0x4 0x17020000 0x0 0x4000>, + <0x4 0x17980000 0x0 0x4000>, + <0x2 0x80000000 0x0 0x4000>, + <0x2 0x80078000 0x0 0x4000>, + <0x23 0x80078000 0x0 0x4000>, + <0x22 0x20200000 0x0 0x8000>, + <0x22 0x20400000 0x0 0x8000>, + <0x22 0x20600000 0x0 0x8000>, + <0x22 0x20800000 0x0 0x8000>, + <0x22 0x22200000 0x0 0x8000>, + <0x2 0x88004000 0x0 0x4000>, + <0x23 0x88004000 0x0 0x4000>, + <0x23 0x80400000 0x0 0x4000>; + reg-names = "ps0", "ps1", "ps-aon", "ps-gpx", "ps-media", "ps-gfx-aon", + "clk", "clk-soc", "clk1", "afr-clk", "media-clk", + "perf", "media-perf", "table0", "table1", "media-table", + "cluster", "pwrgate", "cpu-start", "commit", "wdt", "wdt-aux", + "disp-gate", "spmi", "pmc-voters", "pmc-rails", "ptd", "gapf", + "aon-clk", "media-aon-clk", "cpm0", "cpm1", "cpm2", + "storage-phy", "storage-phy-ip", + "clkgen", "clkgen-78", "media-clkgen-78", + "mcc22", "mcc23", "mcc24", "mcc25", "mcc26", + "wake", "wake-gfx", "aic-gfx"; + apple,display-coprocessors = <&dcp>, <&dcpext0>, <&dcpext1>, <&dcpext2>, <&dcpext3>; + apple,spmi-buses = <&nub_spmi_a0>, <&nub_spmi2>, <&nub_spmi_a1>, <&nub_spmi3>, + <&aop_spmi0>; + /* SEP's, PMP0's, SIO's and the DCP's DART, stopped in the sleep's last steps */ + apple,sleep-darts = <&sep_dart>, <&pmp0_dart>, <&sio_dart>, <&dcp_dart>; + /* The N1's host: its link is shut down for the sleep and brought back after it */ + apple,radio-pcie = <&pcie0>; + apple,pinctrl = <&pinctrl_ap>; + /* The display coprocessors take the sleep through their firmware 27 method table */ + apple,display-method-sleep; + }; +}; + +/* The SMC's wake reasons (ADT smc-pmu, event_name-bitN) */ +&smc { + apple,wake-reasons = <0 8 9 11 13 35 40 41 42 43 44 45 48>; + apple,wake-reason-names = "pwrbtn", "lid", "sdconn", "charger", "wifibt", + "trackpadkeyboard", "acattach", "acdetach", "USB-C_plug", + "USB2_plug", "USB2_wake", "aupo", "rtc"; +}; + +/* + * The N1's warm reset (ADT pci-bridge0 function-warm_reset: the SMC, key 'bpli'). The N1's + * firmware does not survive a sleep; the host resets the N1 after the wake, before its link + * trains. The writes that give the reset are the boot loader's to add (see the binding). + */ +&port00 { + apple,function-warm-reset = <&smc 0x62706c69 0x1000000>; +}; + +/* On through the commit: the sleep stops their users in its last steps. */ +&ps_pmp { + apple,always-on; +}; + +&ps_pms_sram { + apple,always-on; +}; + +&ps_gfx { + apple,always-on; +}; + +&ps_spi_p { + apple,always-on; +}; + +&ps_atc3_usb_aon { + apple,always-on; +}; + +&ps_sio { + apple,always-on; + status = "okay"; +}; + +&ps_sio_cpu { + apple,always-on; + status = "okay"; +}; + +/* The port controllers put in system power state S3 before the commit, then SLEEP */ +&hpm1 { + apple,sleep-ssps; + apple,sleep-ssps-rules; + apple,reset-on-failed-probe; +}; + +&hpm2 { + apple,sleep-ssps; + apple,sleep-ssps-rules; + apple,reset-on-failed-probe; +}; + +/* + * The MagSafe port's PD controller (ADT hpm5, nub-spmi-a0 0x08), described as + * on the J714s so that the sleep puts it in S3 with the others. + */ +&nub_spmi_a0 { + hpm5: usb-pd@8 { + compatible = "apple,sn201202x"; + reg = <0x8 SPMI_USID>; + apple,no-liquid-detection; + apple,sleep-ssps; + apple,sleep-ssps-rules; + apple,reset-on-failed-probe; + }; +}; + +&{/soc@200000000} { + /* + * The cores' power-gate enables, /arm-io/pmgr reg[0] + 0x2c000, one word per core: the + * boot loader leaves core 0's (the boot core's) and core 12's clear. Without them the + * boot cluster never powers down, and the sleep never gets past its first sequence. + */ + cluster_pwrgate: power-gate@28062c000 { + compatible = "apple,t6050-cluster-pwrgate", "apple,cluster-pwrgate"; + reg = <0x2 0x8062c000 0x0 0x4>, + <0x2 0x8062c0c0 0x0 0x4>; + }; +}; + +/* AOP2, running until the commit: its ASC mailbox at the AOP2 ASC + 0x8000 */ +&{/soc@200000000} { + aop2_mbox: mailbox@291608000 { + compatible = "apple,t6050-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x2 0x91608000 0x0 0x4000>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; +}; + +&aop2 { + reg = <0x2 0x91600000 0x0 0x4000>; + reg-names = "asc"; + /delete-property/ interrupts; + mboxes = <&aop2_mbox>; + mbox-names = "mbox"; + apple,dma-range = <0x110 0x0 0x10 0x0>; + status = "okay"; +}; + +/* + * The SIO, running until the sleep's own stop: its ASC bank split around its mailbox. The boot + * loader enables it with its firmware and tables. + */ +/delete-node/ &sio; + +&{/soc@200000000} { + sio_mbox: mailbox@505e08000 { + compatible = "apple,t6050-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x5 0x5e08000 0x0 0x4000>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + power-domains = <&ps_sio_cpu>; + #mbox-cells = <0>; + }; + + sio: dma-controller@505e00000 { + compatible = "apple,t6050-sio", "apple,sio"; + reg = <0x5 0x5e00000 0x0 0x8000>, + <0x5 0x5850000 0x0 0x4000>, + <0x5 0x5e0c000 0x0 0x7c000>; + reg-names = "asc", "auxiliary", "asc-tail"; + #dma-cells = <1>; + dma-channels = <128>; + mboxes = <&sio_mbox>; + iommus = <&sio_dart 0>; + power-domains = <&ps_sio_cpu>; + clocks = <&peripheral_clocks 359>, <&peripheral_clocks 358>; + status = "disabled"; + }; +}; + +&sio_dart { + power-domains = <&ps_sio_cpu>; + status = "okay"; +}; + +/* + * The AP pins a deep sleep neither saves nor restores: none. The K116s ADT's gpio0 has no + * no-restore-gpio-pins (the J714s's has 5 6 7 112 141), and with those skipped the panel stayed + * dark after a deep sleep. Without the property no pin is saved at all. + */ +&sleep { + apple,pinctrl-skip-pins = <>; +}; + +/* + * The display coprocessor's secure mailbox (ADT /arm-io/dcp-exclave-mailbox, + * iop,secure-rtbuddy-proxy, reg 0x4cae7c000). Firmware 27.2 acknowledges no IOP power state + * while nothing answers it, as on T8140. + */ +&{/soc@200000000} { + dcp_secure_mbox: mailbox@4cae7c000 { + compatible = "apple,t6050-secure-rtbuddy-proxy", "apple,secure-rtbuddy-proxy"; + reg = <0x4 0xcae7c000 0x0 0x4000>; + #mbox-cells = <0>; + }; +}; + +/* + * Not in mboxes: the boot loader hands the display over only to a node whose mboxes is the one + * ASC mailbox. The driver takes it from this property. + */ +&dcp { + apple,secure-mbox = <&dcp_secure_mbox>; +}; + +/* + * dcpext0 without its Type-C route, as dcpext1 to 3 are here. Its PHY's DP side + * is not described on this board, and the engine's probe waits for it and gives the engine + * up; a deep sleep needs the engine bound, to stop its firmware. + */ +&dcpext0 { + /delete-property/ apple,connector-type; + /delete-property/ apple,dptx-die; + /delete-property/ apple,typec-dptx-phys; + /delete-property/ apple,typec-mux-indices; + /delete-property/ phys; + /delete-property/ phy-names; + /delete-property/ mux-controls; + /delete-property/ mux-control-names; + /delete-node/ typec-routes; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index fe6468edc72c10..54d0391b6fde38 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -9,6 +9,9 @@ * Copyright The Asahi Linux Contributors */ +/* The N1's firmware and this board's ADT board-id, for t6050-k114-k116.dtsi */ +#define T6050_K_N1_FIRMWARE "apple/centauri/k116s-ftab.bin" +#define T6050_K_BOARD_ID 0x16 #include "t6050-k114-k116.dtsi" / { @@ -23,339 +26,22 @@ #define T6050_K116S #include "t6050-peripherals.dtsi" -/ { - aliases { - /* The loader fills the N1's factory addresses through these */ - wifi0 = &n1_alpha; - bluetooth0 = &n1_beta; - /* the boot loader reserves the SEP firmware and adds its manifests through this alias */ - sep = &sep; - }; -}; - &pinctrl_ap { /* * Pin 112 takes an SError when read, so only the pins a node names are * exposed: 80/81 (PCIe ports 0 and 1's PERST#), 106/107 (amp fault, amp - * shutdown), 134/139 (jack codec interrupt, reset) and 136/137 (speaker ID). + * shutdown), 134/139 (jack codec interrupt, reset), 136/137 (speaker ID) + * and 138 (Touch ID data ready). */ - gpio-reserved-ranges = <0 80>, <82 24>, <108 26>, <135 1>, <138 1>, <140 81>; + gpio-reserved-ranges = <0 80>, <82 24>, <108 26>, <135 1>, <140 81>; }; /* - * PCIe port 0: the N1 (Wi-Fi and Bluetooth), laid out as on J714s. ADT apcie0 - * gives port 0's registers and IRQ 1523, pci-bridge0's PERST# is GPIO 80, and - * the N1's three functions are on DART streams 1-3. The platform ID is this - * board's ADT /chosen board-id (0x16) << 16 | chip 0x6050. - * - * PCIe port 1: the SD card reader (ADT apcie0/pci-bridge1/pcie-sdreader, a - * GL9755), as on J714s. The boot loader leaves the port down, so the kernel - * trains it. From this board's ADT: - * port1, phy1, intr2axi1: apcie0 reg[22], reg[24], reg[25] (port 0's are - * reg[16], reg[18], reg[19]), behind /arm-io's ranges (+0x200000000) - * phy-shared: apcie0 reg[3], the shared PHY's state, which the train reads; - * the boot loader leaves the PHY up with port 0 - * IRQ 1531: apcie0 interrupts[1] - * PERST#: pci-bridge1 function-perst, gpio0 pin 0x51 (81) - * power: pcie-sdreader function-sd_pwr_en, SMC pcIO (0x0, 0x190000), output - * 0 of smc_pcio below - * link tunables: pci-bridge1's apcie-config-tunables, pcie-rc-tunables and - * pcie-rc-gen{3,4,5}-shadow-tunables, as (offset, size, mask, value) - * The reader is behind dart-apcie1 (0x211000000, IRQ 1532; manual-availability: - * it answers only once the root complex is up). The ADT's mapper-apcie1 names - * no stream (the bridge requests one at run time), so stream 1 is this tree's - * choice, below the DART's first bypass stream (16), as on J714s. - * pci-bridge1's function-clkreq (gpio0 pin 0x4d) is not described: the - * driver does not take CLKREQ# lines. + * PCIe port 0 (the N1) and port 1 (the SD card reader) are in t6050-k114-k116.dtsi. + * This board drives one SMC pcIO output (below), so the reader's power is output 0. */ -&pcie0 { - reg = <0x1c 0xb0000000 0x0 0x10000000>, - <0x4 0x14000000 0x0 0x4000>, - <0x4 0x10028000 0x0 0x8000>, - <0x4 0x17010000 0x0 0x4000>, - <0x4 0x10024000 0x0 0x4000>, - <0x4 0x11028000 0x0 0x8000>, - <0x4 0x17014000 0x0 0x4000>, - <0x4 0x11024000 0x0 0x4000>, - <0x4 0x17020000 0x0 0x4000>; - reg-names = "config", "rc", "port0", "phy0", "intr2axi0", "port1", "phy1", "intr2axi1", - "phy-shared"; - interrupts = , - ; - interrupt-names = "port0", "port1"; - iommu-map = <0x100 &dart_apcie0 1 3>, - <0x200 &apcie1_dart 1 1>; - bus-range = <0 4>; - /* apcie1_dart probes only once port 1 is up: the host must not wait for it */ - post-init-providers = <&apcie1_dart>; - status = "okay"; - - port00: pci@0,0 { - device_type = "pci"; - reg = <0x0 0 0 0 0>; - bus-range = <1 1>; - apple,link-trained-by-bootloader; - /* PERST#: ADT pci-bridge0 function-perst, GPIO 80 */ - reset-gpios = <&pinctrl_ap 80 GPIO_ACTIVE_LOW>; - status = "disabled"; - - #address-cells = <3>; - #size-cells = <2>; - ranges; - - interrupt-controller; - #interrupt-cells = <1>; - interrupt-map-mask = <0 0 0 7>; - interrupt-map = <0 0 0 1 &port00 0 0 0 0>, - <0 0 0 2 &port00 0 0 0 1>, - <0 0 0 3 &port00 0 0 0 2>, - <0 0 0 4 &port00 0 0 0 3>; - - n1_control: control@0,0 { - compatible = "pci106b,1900"; - reg = <0x10000 0x0 0x0 0x0 0x0>; - firmware-name = "apple/centauri/k116s-ftab.bin"; - apple,centauri-platform-id = <0x00166050>; - apple,centauri-protocol = <27>; - }; - - n1_alpha: wifi@0,1 { - compatible = "pci106b,1902"; - reg = <0x10100 0x0 0x0 0x0 0x0>; - local-mac-address = [00 00 00 00 00 00]; - }; - - n1_beta: bluetooth@0,2 { - compatible = "pci106b,1903"; - reg = <0x10200 0x0 0x0 0x0 0x0>; - local-bd-address = [00 00 00 00 00 00]; - }; - }; - - port01: pci@1,0 { - device_type = "pci"; - reg = <0x800 0 0 0 0>; - bus-range = <2 2>; - /* Down at boot: the kernel trains it, powering the reader first */ - apple,link-trained-by-bootloader; - /* ADT pcie-sdreader function-sd_pwr_en: SMC pcIO output 0 below */ - pwren-gpios = <&smc_pcio 0 GPIO_ACTIVE_HIGH>; - /* PERST#: ADT pci-bridge1 function-perst, GPIO 81 */ - reset-gpios = <&pinctrl_ap 81 GPIO_ACTIVE_LOW>; - /* ADT pci-bridge1 */ - apple,apcie-config-tunables = <0x140 4 0x1 0x1>, - <0x144 4 0xffffff 0x253770>, - <0x8a8 4 0x1 0x1>, - <0x8ac 4 0x1 0x1>; - apple,pcie-rc-tunables = <0x78 4 0x7000 0x0>, - <0x194 4 0x2 0x2>, - <0xb80 4 0x7f3f3f 0x7f1e1e>, - <0xb88 4 0x7f3f3f 0x7f1e1e>; - apple,pcie-rc-gen3-shadow-tunables = <0x154 4 0xf0f0f0f 0x5050505>, - <0x890 4 0x3000000 0x0>, - <0x8a8 4 0xffff0f 0x1>; - apple,pcie-rc-gen4-shadow-tunables = <0x178 4 0xffff 0x5555>, - <0x890 4 0x3000000 0x1000000>, - <0x8a8 4 0xffff0f 0x1>; - apple,pcie-rc-gen5-shadow-tunables = <0x1ac 4 0xffff 0x5555>, - <0x890 4 0x3000000 0x2000000>, - <0x8a8 4 0xffff0f 0x1>; - - #address-cells = <3>; - #size-cells = <2>; - ranges; - - interrupt-controller; - #interrupt-cells = <1>; - interrupt-map-mask = <0 0 0 7>; - interrupt-map = <0 0 0 1 &port01 0 0 0 0>, - <0 0 0 2 &port01 0 0 0 1>, - <0 0 0 3 &port01 0 0 0 2>, - <0 0 0 4 &port01 0 0 0 3>; - - /* - * The GL9755. Card detect and write protect are active high: ADT - * pcie-sdreader card-detect-polarity and write-protect-polarity = 1. - */ - sdhci0: mmc@0,0 { - compatible = "pci17a0,9755"; - reg = <0x20000 0x0 0x0 0x0 0x0>; - cd-inverted; - wp-inverted; - }; - }; -}; - -/* ADT dart-apcie1 manual-availability: pcie-apple enables it once port 1 is up */ -&apcie1_dart { - apple,manual-availability; - status = "okay"; -}; - -/* - * Type-C, from the ADT (as on J714s): - * ATC0 usb-drd0 left-back hpm0 nub-spmi-a0 0x0c (the debug port, not described) - * ATC1 usb-drd1 left-front hpm1 nub-spmi-a0 0x0a - * ATC2 usb-drd2 right hpm2 nub-spmi-a1 0x0c - * hpm5 nub-spmi-a0 0x08 (MagSafe, not a USB-C connector) - */ - -/* Left-front port (ATC1): the SN201202x hpm1 and the connector graph */ -&nub_spmi_a0 { - status = "okay"; - - hpm1: usb-pd@a { - compatible = "apple,sn201202x"; - reg = <0xa SPMI_USID>; - - typec1: connector { - compatible = "usb-c-connector"; - label = "USB-C Left-front"; - power-role = "dual"; - data-role = "dual"; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - typec1_hs: endpoint { - remote-endpoint = <&usb_drd1_hs>; - }; - }; - - port@1 { - reg = <1>; - typec1_ss: endpoint { - remote-endpoint = <&atc1_phy_typec>; - }; - }; - }; - }; - }; -}; - -&atc1_phy_mbox { - status = "okay"; -}; - -&atc1_phy { - status = "okay"; - - port { - atc1_phy_typec: endpoint { - remote-endpoint = <&typec1_ss>; - }; - }; -}; - -&usb_drd1 { - status = "okay"; - - port { - usb_drd1_hs: endpoint { - remote-endpoint = <&typec1_hs>; - }; - }; -}; - -&usb_drd1_dart_0 { - status = "okay"; -}; - -&usb_drd1_dart_1 { - status = "okay"; -}; - -/* - * Right port (ATC2): hpm2 on nub-spmi-a1, USB only (dcpext0's DisplayPort route - * through ATC2 stays off). The driver polls the generation 4 bus and refuses an - * interrupt, so it takes the first register window only, as on J714s. - */ -&nub_spmi_a1 { - reg = <0x2 0x8a1a8000 0x0 0x4000>; - /delete-property/ interrupts; - status = "okay"; - - hpm2: usb-pd@c { - compatible = "apple,sn201202x"; - reg = <0xc SPMI_USID>; - - typec2: connector { - compatible = "usb-c-connector"; - label = "USB-C Right"; - power-role = "dual"; - data-role = "dual"; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - typec2_hs: endpoint { - remote-endpoint = <&usb_drd2_hs>; - }; - }; - - port@1 { - reg = <1>; - typec2_ss: endpoint { - remote-endpoint = <&atc2_phy_typec>; - }; - }; - }; - }; - }; -}; - -&ps_atc2_common { - status = "okay"; -}; - -&ps_atc2_usb_aon { - status = "okay"; -}; - -&ps_atc2_phymxwrap { - status = "okay"; -}; - -&ps_atc2_usb { - status = "okay"; -}; - -&atc2_phy_mbox { - status = "okay"; -}; - -&atc2_phy { - status = "okay"; - - port { - atc2_phy_typec: endpoint { - remote-endpoint = <&typec2_ss>; - }; - }; -}; - -&usb_drd2 { - status = "okay"; - - port { - usb_drd2_hs: endpoint { - remote-endpoint = <&typec2_hs>; - }; - }; -}; - -&usb_drd2_dart_0 { - status = "okay"; -}; - -&usb_drd2_dart_1 { - status = "okay"; +&port01 { + pwren-gpios = <&smc_pcio 0 GPIO_ACTIVE_HIGH>; }; /* @@ -383,95 +69,6 @@ }; }; -/* - * The internal panel and the display coprocessor, for the boot loader's display - * hand-off (aura, chosen.aurora,t6050-display=1). Everything stays disabled: the - * loader checks the ADT and the live DCP and DART state, publishes the DCP's - * firmware properties, reserves the ADT /vram as the framebuffer and only then - * enables dcp, its DARTs and mailbox and the display subsystem. A loader without - * the hand-off leaves the boot framebuffer to simpledrm. - */ -/ { - aliases { - /* The loader writes apple,notch-height into the "dcp" alias */ - dcp = &dcp; - disp0 = &display; - }; - - /* As on J714s, with the internal display's DART (disp0, SID 0) */ - display: display-subsystem { - compatible = "apple,display-subsystem"; - iommus = <&disp0_dart 0>; - status = "disabled"; - }; -}; - -/* ADT dart-dcp and dart-disp0: vm-base 1 TiB, vm-size 3 TiB */ -&dcp_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&disp0_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcp { - /* - * ADT disp0 clock-ids. The loader adds the clock nodes, "clocks" and the - * bandwidth request scratch ("apple,bw-scratch") when it hands the panel - * over, as on the J714s, and refuses a tree that already has them. - */ - apple,clock-ids = <361 458>; - - /* - * The 16.2-inch 3456x2234 tandem OLED panel. The ADT carries no dimensions; - * these are the panel's active area, for the DPI only. - */ - panel { - compatible = "apple,panel-k116", "apple,panel"; - width-mm = <345>; - height-mm = <223>; - }; -}; - -/* The ADT lists no clocks for the external engines (clock-ids = []) */ -&dcpext1 { - apple,clock-ids; -}; - -&dcpext2 { - apple,clock-ids; -}; - -&dcpext3 { - apple,clock-ids; -}; - -/* ADT dart-dcpextN and dart-dispextN: vm-base 1 TiB, vm-size 3 TiB */ -&dcpext1_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext1_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext2_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext2_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext3_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext3_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - /* * The trackpad's AFE reset. The ADT names the SMC pcIO template (0x10000, * 0x11c0000), the same line as SMC GPIO gp1c, active low, which gpio-macsmc @@ -508,12 +105,20 @@ / { aliases { keyboard = &keyboard; - /* The loader fills the PHYs' tunables from the ADT through these */ - atcphy1 = &atc1_phy; - atcphy2 = &atc2_phy; }; }; +/* The USB-C ports ATC1 and ATC2, as on the other K boards */ +#include "t6050-k114-k116-usb.dtsi" + +/* + * Right port (ATC2): nub-spmi-a1 takes the first register window only, as on + * J714s. + */ +&nub_spmi_a1 { + reg = <0x2 0x8a1a8000 0x0 0x4000>; +}; + /* * The PMP (ADT pmp0, /chosen, /arm-io/pmgr), as on the J714s: iBoot loads its firmware and * the driver starts it with these boot arguments and the firmware properties in the tunables @@ -564,29 +169,6 @@ #include "t6050-k116s-pmp-tunables.dtsi" -/* - * The SEP (ADT sep, dart-sep), as on the J714s: its mailbox, and its power domain with the two - * fabric parents left to the firmware, which genpd votes on and never turns off. The boot - * loader enables the SEP itself through its alias. - */ -&sep_mbox { - status = "okay"; -}; - -&ps_sep { - status = "okay"; -}; - -&ps_fab8_soc { - apple,firmware-owned; - status = "okay"; -}; - -&ps_fab0_piogw { - apple,firmware-owned; - status = "okay"; -}; - /* Sound: the J714s description, every value checked against the K116s ADT. */ /* * The amps' shared shutdown line (SDZ): ADT audio-speaker function-reset, AP pin 107. One @@ -850,7 +432,26 @@ dma-names = "cout", "cin", "spkr", "sense", "hpai"; }; /* The GPU, handed over by the boot loader */ -#include "t6050-k116s-gpu.dtsi" +#include "t6050-k114-k116-gpu.dtsi" + +/* The internal panel, handed over by the boot loader */ +#include "t6050-k114-k116-display.dtsi" + +/* The 16.2-inch 3456x2234 panel's active area, for the DPI only (the ADT carries none) */ +&panel { + compatible = "apple,panel-k116", "apple,panel"; + width-mm = <345>; + height-mm = <223>; +}; + +/* + * As t6050-j714s.dts: the GPU on the PMP's GFX report entry (report@f, on ps_gfx), so the PMP + * is told the GPU is on only while it is powered. This board runs the PMP with its report + * (&pmp0_report above). + */ +&sgx { + power-domains = <&pmp0_gfx>; +}; /* * The camera: the T6050 ISP as J716c and J714s describe it. From the K116sAP ADT (27.2): @@ -872,18 +473,17 @@ #include "t6050-j716c-isp.dtsi" /* - * Two things the shared T6050 files now turn on for every board are held back here until - * they have been tried on the K116s: the CPU PMU (t6050-base.dtsi, measured on the J714s) - * and the CLPC's SMC link (t6050-die0.dtsi), through which the low-power platform profile - * polls the package power. Without the link that profile has only its frequency ceiling. - * To try them, remove this block. + * The CPU PMU the shared T6050 files turn on for every board (t6050-base.dtsi, measured on + * the J714s) is held back here until it has been tried on the K116s. To try it, remove + * this block. */ &cpu_pmu { status = "disabled"; }; +/* macOS offers High Power mode on this machine */ &clpc { - /delete-property/ apple,smc; + apple,high-power-mode; }; /* @@ -913,3 +513,94 @@ &avd { status = "okay"; }; + +/* Touch ID: the SEP and the Mesa sensor, with this Mac's own calibration and root key */ +#define T6050_TOUCHID_FIRMWARE "apple/mesacal-k116s.bin", "apple/msrk-k116s.bin" +#include "t6050-touchid.dtsi" + +/* + * The video encoder's power states, as on the J714s. iBoot leaves VENC0_SYS on, and the SoC does + * not enter the firmware-driven sleep with it on. Enabled and unused, genpd turns it off at + * boot. No encoder is described yet. + */ +&ps_fab1_piogw { + apple,firmware-owned; + status = "okay"; +}; + +&ps_fab0_soc { + apple,always-on; + status = "okay"; +}; + +&ps_venc0_sys { + status = "okay"; +}; + +&ps_venc0_dma { + status = "okay"; +}; + +&ps_venc0_pipe4 { + status = "okay"; +}; + +&ps_venc0_pipe5 { + status = "okay"; +}; + +&ps_venc0_me0 { + status = "okay"; +}; + +&ps_venc0_me1 { + status = "okay"; +}; + +/* + * Deep sleep: the sleep controller's description and the J714s's SoC values, then what differs + * on this board (firmware 27.2). + */ +#include "t6050-k116s-sleep.dtsi" +/* No USB4 router is described on this board: without the J714s's CIO sleep part. */ +#define T6050_SLEEP_SOC_NO_CIO +#include "t6050-j714s-sleep-soc.dtsi" + +/* + * macOS on this board parks the four clock words with 0x80100000 in the last 0.5 ms before its + * commit (traced as an aura guest); the J714s's values have bit 10 set. + */ +&sleep { + apple,seq-commit-sio = + <0x0 17 0x290 0x400024f>, + <0x0 17 0x2a0 0x400024f>, + <0x1 51 0xa0 0x0>, + <0x0 51 0xa0 0x80100000>, + <0x1 51 0xa0 0x0>, + <0x1 51 0xa4 0x0>, + <0x0 51 0xa4 0x80100000>, + <0x1 51 0xa4 0x0>, + <0x1 51 0x94 0x0>, + <0x0 51 0x94 0x80100000>, + <0x1 51 0x94 0x0>, + <0x1 51 0x90 0x0>, + <0x0 51 0x90 0x80100000>, + <0x1 51 0x90 0x0>; +}; + +/* + * The PMP firmware's __DATA starts at 0x56000 on 27.2 (ADT pmp0 segment-ranges: __TEXT 0x56000 + * bytes, __DATA 0x9b000 bytes), not at the J714s's 0x58000. With the wrong range kept over the + * sleep the PMP does not come back (endpoint discovery -62). + */ +&pmp0 { + apple,sram-keep = <0x56000 0x9b000>; +}; + +/* + * t6050-j714s-sleep-soc.dtsi, included above, sets the J714s's 2500 us; keep the K boards' + * 10000 us (t6050-k114-k116-display.dtsi). + */ +&dcp { + apple,panel-video-open-delay-us = <10000>; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-max.dtsi b/arch/arm64/boot/dts/apple/t6050-max.dtsi index 6d76d01cbda273..b1a95aa559a5e5 100644 --- a/arch/arm64/boot/dts/apple/t6050-max.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-max.dtsi @@ -39,12 +39,12 @@ T6050_M_CPU(cpu9, 40103, cpufreq_mc1, l2_cache_mc1); T6050_M_CPU(cpu10, 40104, cpufreq_mc1, l2_cache_mc1); T6050_M_CPU(cpu11, 40105, cpufreq_mc1, l2_cache_mc1); - T6050_P_CPU(cpu12, 10200, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu13, 10201, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu14, 10202, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu15, 10203, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu16, 10204, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu17, 10205, cpufreq_pc, l2_cache_pc); + T6050_P_CPU(cpu12, 10200, cpufreq_pc, l2_cache_p0); + T6050_P_CPU(cpu13, 10201, cpufreq_pc, l2_cache_p1); + T6050_P_CPU(cpu14, 10202, cpufreq_pc, l2_cache_p2); + T6050_P_CPU(cpu15, 10203, cpufreq_pc, l2_cache_p3); + T6050_P_CPU(cpu16, 10204, cpufreq_pc, l2_cache_p4); + T6050_P_CPU(cpu17, 10205, cpufreq_pc, l2_cache_p5); /* * The clusters are MPIDR Aff1 (M0, M1, then P), each with its own L2. The boot @@ -116,10 +116,16 @@ }; }; - /* One L2 per cluster (t6050-base.dtsi, "Caches"). */ + /* L2 per M cluster, L2 per P core, L3 per P cluster (t6050-base.dtsi, "Caches"). */ T6050_M_L2(l2_cache_mc0, l2-cache-mcluster0); T6050_M_L2(l2_cache_mc1, l2-cache-mcluster1); - T6050_P_L2(l2_cache_pc, l2-cache-pcluster); + T6050_P_L3(l3_cache_pc, l3-cache-pcluster); + T6050_P_L2(l2_cache_p0, l2-cache-pcore0, l3_cache_pc); + T6050_P_L2(l2_cache_p1, l2-cache-pcore1, l3_cache_pc); + T6050_P_L2(l2_cache_p2, l2-cache-pcore2, l3_cache_pc); + T6050_P_L2(l2_cache_p3, l2-cache-pcore3, l3_cache_pc); + T6050_P_L2(l2_cache_p4, l2-cache-pcore4, l3_cache_pc); + T6050_P_L2(l2_cache_p5, l2-cache-pcore5, l3_cache_pc); }; #define DIE @@ -213,7 +219,8 @@ #endif }; -#if defined(T6050_J714C) || defined(T6050_J714S) || defined(T6050_J716C) || defined(T6050_K114C) +/* Boards whose ADT has ATC2's USB4 router (acio2) define T6050_ATC2_USB4_ROUTER. */ +#ifdef T6050_ATC2_USB4_ROUTER /* * ATC2's USB4/Thunderbolt router (ADT /arm-io/acio2, acio-cpu2 and dart-acio2), powered per * connection: the PHY enters CIO mode, then the router's domains come on (ATC2_CIO, _PCIE, _USB, @@ -450,7 +457,6 @@ reg-names = "config", "rc", "port0", "fabric", "debug", "ltssm", "intr2axi"; /* The port's: link events and INTx */ interrupts = ; - interrupt-names = "port0"; power-domains = <&ps_atc2_pcie>; /* No boot loader hands the port over: the kernel cold-initializes it. */ apple,pciec-kernel-init; @@ -491,3 +497,47 @@ }; }; #endif + +/* + * Die 0's memory cache controllers (ADT /arm-io/mcc: amcc-count 8, + * dcs-count-per-amcc 4, AMCC a at 0x2220000000 + a * 0x2000000, four 16 KiB + * planes at +0x40000). Both M5 Pro and M5 Max boards include this file; M5 Pro + * enables AMCC 0..3 only (ADT amcc-enable-mask = 0xf, 16 planes), and M5 Max + * ships in both 460 GB/s (binned) and 614 GB/s (amcc-enable-mask = 0xff, + * 8 AMCCs) variants under the same board DTS. Because the binned 460 GB/s M5 + * Max's amcc-enable-mask has not been read from hardware yet and apple-mcc + * reads every listed plane aperture before rejecting it, keep mcc disabled + * here until the boot loader populates reg from the live ADT's + * amcc-enable-mask and enables the node (or a board whose enable mask is + * verified across all SKUs enables it); ranges covers all eight AMCCs for + * that update. + * + * The boot loader leaves every enabled plane's ways powered with allocation + * disabled until apple-mcc allows it. On laptops, each board's framebuffer0 + * names &dcp as its display so once mcc is enabled, allocation waits for the + * DCP to retire the boot scanout (and stays off when the boot loader keeps + * simpledrm). + */ +/ { + soc@2220000000 { + compatible = "simple-bus"; + #address-cells = <2>; + #size-cells = <2>; + ranges = <0x22 0x20000000 0x22 0x20000000 0x0 0x10000000>; + nonposted-mmio; + + mcc: memory-controller@2220000000 { + compatible = "apple,t6050-mcc"; + reg = <0x22 0x20000000 0x0 0x4000>, <0x22 0x20040000 0x0 0x4000>, + <0x22 0x20080000 0x0 0x4000>, <0x22 0x200c0000 0x0 0x4000>, + <0x22 0x22000000 0x0 0x4000>, <0x22 0x22040000 0x0 0x4000>, + <0x22 0x22080000 0x0 0x4000>, <0x22 0x220c0000 0x0 0x4000>, + <0x22 0x24000000 0x0 0x4000>, <0x22 0x24040000 0x0 0x4000>, + <0x22 0x24080000 0x0 0x4000>, <0x22 0x240c0000 0x0 0x4000>, + <0x22 0x26000000 0x0 0x4000>, <0x22 0x26040000 0x0 0x4000>, + <0x22 0x26080000 0x0 0x4000>, <0x22 0x260c0000 0x0 0x4000>; + apple,boot-dma-devices = <&dcp>; + status = "disabled"; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi index b85b06baf5453a..f4472ddf9eba4c 100644 --- a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi @@ -128,7 +128,8 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "fab0-piogw"; - status = "disabled"; + apple,firmware-owned; + status = "okay"; }; ps_fab3_soc: power-controller@1e0 { compatible = "apple,t6050-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -137,7 +138,8 @@ #reset-cells = <0>; label = "fab3-soc"; power-domains = <&ps_fab0_piogw>; - status = "disabled"; + apple,firmware-owned; + status = "okay"; }; ps_fab5_soc: power-controller@1f0 { compatible = "apple,t6050-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -146,7 +148,8 @@ #reset-cells = <0>; label = "fab5-soc"; power-domains = <&ps_fab0_piogw>; - status = "disabled"; + apple,firmware-owned; + status = "okay"; }; ps_sbr: power-controller@1f8 { compatible = "apple,t6050-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -363,6 +366,24 @@ }; }; +/* + * The ADT's PMGR device table gives every ATC's COMMON state a fabric parent: ATC0 and ATC1 + * hang off FAB3_SOC, ATC2 and ATC3 off FAB5_SOC. Without the link, genpd counts no + * powered child under the fabric while a port's PHY domains are held on, asks for the + * fabric to go off, and the PMGR refuses the write. + */ +&ps_atc1_common { + power-domains = <&ps_fab3_soc>; +}; + +&ps_atc2_common { + power-domains = <&ps_fab5_soc>; +}; + +&ps_atc3_common { + power-domains = <&ps_fab5_soc>; +}; + &pmgr1 { ps_ispsens0: power-controller@100 { compatible = "apple,t6050-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -1006,12 +1027,20 @@ label = "gpx"; status = "disabled"; }; + /* + * The T6050 boot chain hands AFR and GFX over with an auto-PM floor of + * clock-gated (PS_MIN = 4), and the power-state driver writes back the + * floor it reads, holding idle GFX at state 4. macOS runs both domains + * with a floor of power-gated, where idle GFX rests at state 0; request + * the same for all T6050 boards inheriting these domains. + */ ps_afr: power-controller@100 { compatible = "apple,t6050-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; reg = <0x100 4>; #power-domain-cells = <0>; #reset-cells = <0>; label = "afr"; + apple,min-state = <0>; status = "disabled"; }; ps_gfx: power-controller@110 { @@ -1021,6 +1050,7 @@ #reset-cells = <0>; label = "gfx"; power-domains = <&ps_afr>, <&ps_gpx>; + apple,min-state = <0>; status = "disabled"; }; }; @@ -1294,7 +1324,8 @@ #else &{/soc} { #endif -#if defined(T6050_J714C) || defined(T6050_J716C) || defined(T6050_J775C) || defined(T6050_J775D) || defined(T6050_K114C) || defined(T6050_K116C) +/* nub-spmi1: an M5 Max bus (t6050-soc-max.dtsi) */ +#ifdef T6050_MAX_PMIC_BUSES nub_spmi1: spmi@28a054000 { compatible = "apple,t6050-spmi", "apple,t8142-spmi"; reg = <0x2 0x8a054000 0x0 0x4000>, @@ -1307,7 +1338,8 @@ }; #endif -#if defined(T6050_J714C) || defined(T6050_J716C) || defined(T6050_J775C) || defined(T6050_J775D) || defined(T6050_K114C) || defined(T6050_K116C) +/* nub-spmi4: the other bus of t6050-soc-max.dtsi */ +#ifdef T6050_MAX_PMIC_BUSES nub_spmi4: spmi@28a114000 { compatible = "apple,t6050-spmi", "apple,t8142-spmi"; reg = <0x2 0x8a114000 0x0 0x4000>, @@ -1587,7 +1619,8 @@ status = "disabled"; }; -#if !defined(T6050_J714C) && !defined(T6050_J714S) && !defined(T6050_J716C) && !defined(T6050_K114C) +/* With ATC2's USB4 router, t6050-max.dtsi describes this DART with the router instead. */ +#ifndef T6050_ATC2_USB4_ROUTER apciec2_dart: iommu@384000000 { compatible = "apple,t6050-dart", "apple,t8110-dart"; reg = <0x3 0x84000000 0x0 0x20000>; @@ -1612,6 +1645,8 @@ compatible = "apple,t6050-display-crossbar", "apple,t8142-display-crossbar"; reg = <0x2 0xa324c000 0x0 0x4000>; #mux-control-cells = <1>; + power-domains = <&ps_atc0_usb_aon>, <&ps_atc0_common>; + power-domain-names = "usb-aon", "common"; status = "disabled"; }; @@ -1647,6 +1682,8 @@ compatible = "apple,t6050-display-crossbar", "apple,t8142-display-crossbar"; reg = <0x2 0xab24c000 0x0 0x4000>; #mux-control-cells = <1>; + power-domains = <&ps_atc1_usb_aon>, <&ps_atc1_common>; + power-domain-names = "usb-aon", "common"; status = "disabled"; }; @@ -1712,6 +1749,8 @@ compatible = "apple,t6050-display-crossbar", "apple,t8142-display-crossbar"; reg = <0x3 0x8b24c000 0x0 0x4000>; #mux-control-cells = <1>; + power-domains = <&ps_atc3_usb_aon>, <&ps_atc3_common>; + power-domain-names = "usb-aon", "common"; status = "disabled"; }; #endif @@ -2819,6 +2858,9 @@ mboxes = <&dcpext1_mbox>; mbox-names = "mbox"; iommus = <&dcpext1_dart 23>; + apple,bw-scratch = <&dcpext0_pmc 0 5 0x30000>; + apple,dcp-index = <2>; + apple,clock-ids; status = "disabled"; piodma { @@ -2831,15 +2873,17 @@ reg = <0x3 0x92340000 0x0 0x20000>; interrupts = ; #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; status = "disabled"; }; dispext1_dart: iommu@392300000 { compatible = "apple,t6050-dart", "apple,t8110-dart"; - reg = <0x3 0x92300000 0x0 0xc000>, - <0x3 0x92314000 0x0 0x4000>; + /* Scanout and PIODMA share the first register window, as on dart_dispext0 */ + reg = <0x3 0x92300000 0x0 0xc000>; interrupts = ; #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; status = "disabled"; }; @@ -2915,6 +2959,9 @@ mboxes = <&dcpext2_mbox>; mbox-names = "mbox"; iommus = <&dcpext2_dart 23>; + apple,bw-scratch = <&dcpext0_pmc 0 5 0x34000>; + apple,dcp-index = <3>; + apple,clock-ids; status = "disabled"; piodma { @@ -2927,15 +2974,17 @@ reg = <0x3 0x2340000 0x0 0x20000>; interrupts = ; #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; status = "disabled"; }; dispext2_dart: iommu@302300000 { compatible = "apple,t6050-dart", "apple,t8110-dart"; - reg = <0x3 0x2300000 0x0 0xc000>, - <0x3 0x2314000 0x0 0x4000>; + /* Scanout and PIODMA share the first register window, as on dart_dispext0 */ + reg = <0x3 0x2300000 0x0 0xc000>; interrupts = ; #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; status = "disabled"; }; @@ -3011,6 +3060,9 @@ mboxes = <&dcpext3_mbox>; mbox-names = "mbox"; iommus = <&dcpext3_dart 23>; + apple,bw-scratch = <&dcpext0_pmc 0 5 0x38000>; + apple,dcp-index = <4>; + apple,clock-ids; status = "disabled"; piodma { @@ -3023,15 +3075,17 @@ reg = <0x3 0x6340000 0x0 0x20000>; interrupts = ; #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; status = "disabled"; }; dispext3_dart: iommu@306300000 { compatible = "apple,t6050-dart", "apple,t8110-dart"; - reg = <0x3 0x6300000 0x0 0xc000>, - <0x3 0x6314000 0x0 0x4000>; + /* Scanout and PIODMA share the first register window, as on dart_dispext0 */ + reg = <0x3 0x6300000 0x0 0xc000>; interrupts = ; #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t6050-sep.dtsi b/arch/arm64/boot/dts/apple/t6050-sep.dtsi new file mode 100644 index 00000000000000..102b254178a1d6 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-sep.dtsi @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The SEP (ADT sep, dart-sep) on the T6050 laptops: its mailbox, and its power domain with the + * two fabric parents left to the firmware, which genpd votes on and never turns off. The SEP + * and its DART stay disabled here: apple_sep enables them after it selects its policy, and only + * where the mailbox is enabled. + * + * Included after t6050-peripherals.dtsi. + */ + +/ { + aliases { + /* the boot loader reserves the SEP firmware and adds its manifests through this alias */ + sep = &sep; + }; +}; + +&sep_mbox { + status = "okay"; +}; + +&ps_sep { + status = "okay"; +}; + +&ps_fab8_soc { + apple,firmware-owned; + status = "okay"; +}; + +&ps_fab0_piogw { + apple,firmware-owned; + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-soc-max.dtsi b/arch/arm64/boot/dts/apple/t6050-soc-max.dtsi new file mode 100644 index 00000000000000..1686e5ce952ab6 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-soc-max.dtsi @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The M5 Max's die-0 SoC part, for every board built on it: the MacBook Pros J714c, J716c, + * K114c and K116c and the Mac Studios J775c and J775d. Boards include it before + * t6050-peripherals.dtsi; it selects the blocks the M5 Pro's die does not have. + * + * The Max's ADTs (27.2: J714cAP, J716cAP, J775cAP, J775dAP, K114cAP, K116cAP, and the live + * J716c ADT) have two more SPMI buses than the M5 Pro's (J714sAP, J716sAP, J873sAP, K114sAP, + * K116sAP, and the live K114s and K116s ADTs): nub-spmi1 (spmi-mosquitoM1, interrupt 731) and + * nub-spmi4 (spmi-jerezC0 and spmi-jerezC1, interrupt 746), the Max's other PMICs. + */ +#define T6050_MAX_PMIC_BUSES diff --git a/arch/arm64/boot/dts/apple/t6050-studio-audio.dtsi b/arch/arm64/boot/dts/apple/t6050-studio-audio.dtsi index 07195f5be9841d..1a60bbf3e2b06d 100644 --- a/arch/arm64/boot/dts/apple/t6050-studio-audio.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-studio-audio.dtsi @@ -3,7 +3,7 @@ * The audio of the M5 Mac Studio (J775c, J775d): the headphone jack (a * CS42L84) and the built-in speaker (one SN012776), both reached through the * AOP's audio services. The card waits for its CPU component, the AOP audio - * node, which exists only after the boot loader's AOP handoff. + * node, which exists once the board enables the AOP. * * The speaker is described but stays off: the ADT's audio-speaker stream has * no RX (sense) slot, and macaudio admits the speaker only once a protection diff --git a/arch/arm64/boot/dts/apple/t6050-touchid.dtsi b/arch/arm64/boot/dts/apple/t6050-touchid.dtsi new file mode 100644 index 00000000000000..0d7cb8986b8094 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-touchid.dtsi @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * Touch ID on the T6050 laptops: the SEP (t6050-sep.dtsi) and the Mesa sensor (ADT spi2/mesa). + * The live ADTs of the J714s, J716c, K114s and K116s and the 27.2 DeviceTrees of the other + * boards describe it alike: spi2 at 8 MHz, chip select 0, powered by NUB GPIO 21 + * (function-mesa_pwr), data ready on AP GPIO 138. spi2 runs from the 24 MHz reference (ADT + * clock-ids 451). + * + * The board defines T6050_TOUCHID_FIRMWARE before including this file: the sensor's + * calibration and signed root key, per-device factory data that aurora-touchid-setup builds + * from this Mac's own iBoot System Container. The board also leaves AP pin 138 out of its + * gpio-reserved-ranges. + * + * Included after t6050-peripherals.dtsi. + */ + +#ifndef T6050_TOUCHID_FIRMWARE +#error "define T6050_TOUCHID_FIRMWARE (calibration, root key) before including t6050-touchid.dtsi" +#endif + +#include "t6050-sep.dtsi" + +&ps_nub_gpio { + status = "okay"; +}; + +&nub_gpio0 { + status = "okay"; +}; + +&ps_spi2 { + status = "okay"; +}; + +&spi2 { + clocks = <&clkref>; + status = "okay"; + + mesa: fingerprint@0 { + compatible = "apple,mesa-fingerprint"; + reg = <0>; + spi-max-frequency = <8000000>; + spi-cpol; + spi-cs-setup-delay-ns = <20>; + spi-cs-hold-delay-ns = <20>; + enable-gpios = <&nub_gpio0 21 GPIO_ACTIVE_HIGH>; + interrupt-parent = <&pinctrl_ap>; + interrupts = <138 IRQ_TYPE_EDGE_RISING>; + firmware-name = T6050_TOUCHID_FIRMWARE; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-ultra.dtsi b/arch/arm64/boot/dts/apple/t6050-ultra.dtsi index e9f0279e9373db..1dbff1f6ecbcf5 100644 --- a/arch/arm64/boot/dts/apple/t6050-ultra.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-ultra.dtsi @@ -37,11 +37,11 @@ T6050_M_CPU(cpu8, 40102, cpufreq_mc1, l2_cache_mc1); T6050_M_CPU(cpu9, 40103, cpufreq_mc1, l2_cache_mc1); T6050_M_CPU(cpu10, 40104, cpufreq_mc1, l2_cache_mc1); - T6050_P_CPU(cpu12, 10200, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu13, 10201, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu14, 10202, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu15, 10203, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu16, 10204, cpufreq_pc, l2_cache_pc); + T6050_P_CPU(cpu12, 10200, cpufreq_pc, l2_cache_p0); + T6050_P_CPU(cpu13, 10201, cpufreq_pc, l2_cache_p1); + T6050_P_CPU(cpu14, 10202, cpufreq_pc, l2_cache_p2); + T6050_P_CPU(cpu15, 10203, cpufreq_pc, l2_cache_p3); + T6050_P_CPU(cpu16, 10204, cpufreq_pc, l2_cache_p4); T6050_M_CPU(cpu18, 41000, cpufreq_mc0_die1, l2_cache_mc0_die1); T6050_M_CPU(cpu19, 41001, cpufreq_mc0_die1, l2_cache_mc0_die1); T6050_M_CPU(cpu20, 41002, cpufreq_mc0_die1, l2_cache_mc0_die1); @@ -52,20 +52,145 @@ T6050_M_CPU(cpu26, 41102, cpufreq_mc1_die1, l2_cache_mc1_die1); T6050_M_CPU(cpu27, 41103, cpufreq_mc1_die1, l2_cache_mc1_die1); T6050_M_CPU(cpu28, 41104, cpufreq_mc1_die1, l2_cache_mc1_die1); - T6050_P_CPU(cpu30, 11200, cpufreq_pc_die1, l2_cache_pc_die1); - T6050_P_CPU(cpu31, 11201, cpufreq_pc_die1, l2_cache_pc_die1); - T6050_P_CPU(cpu32, 11202, cpufreq_pc_die1, l2_cache_pc_die1); - T6050_P_CPU(cpu33, 11203, cpufreq_pc_die1, l2_cache_pc_die1); - T6050_P_CPU(cpu34, 11204, cpufreq_pc_die1, l2_cache_pc_die1); + T6050_P_CPU(cpu30, 11200, cpufreq_pc_die1, l2_cache_p0_die1); + T6050_P_CPU(cpu31, 11201, cpufreq_pc_die1, l2_cache_p1_die1); + T6050_P_CPU(cpu32, 11202, cpufreq_pc_die1, l2_cache_p2_die1); + T6050_P_CPU(cpu33, 11203, cpufreq_pc_die1, l2_cache_p3_die1); + T6050_P_CPU(cpu34, 11204, cpufreq_pc_die1, l2_cache_p4_die1); + + /* + * The clusters are MPIDR Aff1 (die 0's M0, M1 and P, then die 1's), each with its + * own L2. They are listed flat, as on the other two-die parts. The boot loader + * prunes the entries of cores it did not start. + */ + cpu-map { + cluster0 { + core0 { + cpu = <&cpu0>; + }; + core1 { + cpu = <&cpu1>; + }; + core2 { + cpu = <&cpu2>; + }; + core3 { + cpu = <&cpu3>; + }; + core4 { + cpu = <&cpu4>; + }; + }; + + cluster1 { + core0 { + cpu = <&cpu6>; + }; + core1 { + cpu = <&cpu7>; + }; + core2 { + cpu = <&cpu8>; + }; + core3 { + cpu = <&cpu9>; + }; + core4 { + cpu = <&cpu10>; + }; + }; + + cluster2 { + core0 { + cpu = <&cpu12>; + }; + core1 { + cpu = <&cpu13>; + }; + core2 { + cpu = <&cpu14>; + }; + core3 { + cpu = <&cpu15>; + }; + core4 { + cpu = <&cpu16>; + }; + }; + + cluster3 { + core0 { + cpu = <&cpu18>; + }; + core1 { + cpu = <&cpu19>; + }; + core2 { + cpu = <&cpu20>; + }; + core3 { + cpu = <&cpu21>; + }; + core4 { + cpu = <&cpu22>; + }; + }; + + cluster4 { + core0 { + cpu = <&cpu24>; + }; + core1 { + cpu = <&cpu25>; + }; + core2 { + cpu = <&cpu26>; + }; + core3 { + cpu = <&cpu27>; + }; + core4 { + cpu = <&cpu28>; + }; + }; + + cluster5 { + core0 { + cpu = <&cpu30>; + }; + core1 { + cpu = <&cpu31>; + }; + core2 { + cpu = <&cpu32>; + }; + core3 { + cpu = <&cpu33>; + }; + core4 { + cpu = <&cpu34>; + }; + }; + }; }; - /* One L2 per cluster (t6050-base.dtsi, "Caches"). */ + /* L2 per M cluster, L2 per P core, L3 per P cluster (t6050-base.dtsi, "Caches"). */ T6050_M_L2(l2_cache_mc0, l2-cache-mcluster0); T6050_M_L2(l2_cache_mc1, l2-cache-mcluster1); - T6050_P_L2(l2_cache_pc, l2-cache-pcluster); + T6050_P_L3(l3_cache_pc, l3-cache-pcluster); + T6050_P_L2(l2_cache_p0, l2-cache-pcore0, l3_cache_pc); + T6050_P_L2(l2_cache_p1, l2-cache-pcore1, l3_cache_pc); + T6050_P_L2(l2_cache_p2, l2-cache-pcore2, l3_cache_pc); + T6050_P_L2(l2_cache_p3, l2-cache-pcore3, l3_cache_pc); + T6050_P_L2(l2_cache_p4, l2-cache-pcore4, l3_cache_pc); T6050_M_L2(l2_cache_mc0_die1, l2-cache-mcluster0-die1); T6050_M_L2(l2_cache_mc1_die1, l2-cache-mcluster1-die1); - T6050_P_L2(l2_cache_pc_die1, l2-cache-pcluster-die1); + T6050_P_L3(l3_cache_pc_die1, l3-cache-pcluster-die1); + T6050_P_L2(l2_cache_p0_die1, l2-cache-pcore0-die1, l3_cache_pc_die1); + T6050_P_L2(l2_cache_p1_die1, l2-cache-pcore1-die1, l3_cache_pc_die1); + T6050_P_L2(l2_cache_p2_die1, l2-cache-pcore2-die1, l3_cache_pc_die1); + T6050_P_L2(l2_cache_p3_die1, l2-cache-pcore3-die1, l3_cache_pc_die1); + T6050_P_L2(l2_cache_p4_die1, l2-cache-pcore4-die1, l3_cache_pc_die1); /* Die 1 MMIO. The boot loader needs each die's bus. */ die1: soc@4200000000 { diff --git a/arch/arm64/boot/dts/apple/t8103-j274.dts b/arch/arm64/boot/dts/apple/t8103-j274.dts index 11d55fa84da335..387873272d6991 100644 --- a/arch/arm64/boot/dts/apple/t8103-j274.dts +++ b/arch/arm64/boot/dts/apple/t8103-j274.dts @@ -19,7 +19,6 @@ aliases { ethernet0 = ðernet0; - sio = &sio; }; }; diff --git a/arch/arm64/boot/dts/apple/t8103-j313.dts b/arch/arm64/boot/dts/apple/t8103-j313.dts index b1125b78a85d0a..87e12d3e70680d 100644 --- a/arch/arm64/boot/dts/apple/t8103-j313.dts +++ b/arch/arm64/boot/dts/apple/t8103-j313.dts @@ -179,6 +179,27 @@ status = "okay"; }; +&sleep { + status = "okay"; +}; + +/* The SMC's wake reasons (ADT smc-pmu, event_name-bitN) */ +&smc { + apple,wake-reasons = <0 8 9 11 12 21 40 41 42 43 44 45 48>; + apple,wake-reason-names = "pwrbtn", "lid", "charger", "codec", "wifibt", + "trackpadkeyboard", "acattach", "acdetach", "USB-C_plug", + "USB2_plug", "USB2_wake", "aupo", "rtc"; +}; + +/* The port controllers' system power state: S3 before a firmware-driven sleep, S0 after it */ +&hpm0 { + apple,sleep-ssps; +}; + +&hpm1 { + apple,sleep-ssps; +}; + &aop_audio { apple,chassis-name = "J313"; apple,machine-kind = "MacBook Air"; diff --git a/arch/arm64/boot/dts/apple/t8103-jxxx.dtsi b/arch/arm64/boot/dts/apple/t8103-jxxx.dtsi index 77485eb85b0b31..961f189cd78557 100644 --- a/arch/arm64/boot/dts/apple/t8103-jxxx.dtsi +++ b/arch/arm64/boot/dts/apple/t8103-jxxx.dtsi @@ -19,6 +19,7 @@ disp0-piodma = &disp0_piodma; serial0 = &serial0; serial2 = &serial2; + sio = &sio; wifi0 = &wifi0; atcphy0 = &atcphy0; atcphy1 = &atcphy1; diff --git a/arch/arm64/boot/dts/apple/t8103.dtsi b/arch/arm64/boot/dts/apple/t8103.dtsi index 38978c3675d3dc..02b06f1b2e6f6b 100644 --- a/arch/arm64/boot/dts/apple/t8103.dtsi +++ b/arch/arm64/boot/dts/apple/t8103.dtsi @@ -22,6 +22,8 @@ aliases { gpu = &gpu; + rtc0 = &smc_rtc; + rtc1 = &pmu_rtc; /* m1n1 copies this machine's Thunderbolt calibration onto the * node these names point at. Current m1n1 looks up usb4-N-acio * and usb4-N-nhi; the packaged 1.6.1 bootloader looks up @@ -658,6 +660,7 @@ dcp: dcp@231c00000 { compatible = "apple,t8103-dcp", "apple,dcp"; + apple,display-power = <&dcp_power>; mboxes = <&dcp_mbox>; mbox-names = "mbox"; iommus = <&dcp_dart 0 0x0 0x0 0x0 0xfc000000>; @@ -1111,6 +1114,43 @@ reg = <0x2 0x3b700000 0 0x14000>; }; + /* + * The power words the DCP's driver lowers and raises around a stop of its + * firmware: DISP0's CPU and front end, in the PMGR's power state block. + * No driver binds this. + */ + dcp_power: display-power@23b700000 { + compatible = "apple,t8103-display-power"; + reg = <0x2 0x3b700000 0x0 0x14000>; + reg-names = "ps"; + }; + + /* + * Suspend-to-RAM. The blocks the sleep writes, each shared with its own + * driver and not claimed: the main PMGR (CPM gating, the CPU clusters, + * SEP's power-gate wait), the always-on PMGR (the S2R timer), the SoC + * clock generator's muxes, the AOP's wake block (five mask, then five + * status words), the CPU start block, the watchdog and nub-spmi0. + * A board that sleeps enables it. + */ + sleep: sleep-controller@23b700000 { + compatible = "apple,t8103-sleep"; + reg = <0x2 0x3b700000 0x0 0x8c000>, + <0x2 0x3d280000 0x0 0x74000>, + <0x2 0x3b000000 0x0 0x41000>, + <0x2 0x3d004000 0x0 0x30>, + <0x2 0x3b754000 0x0 0x10>, + <0x2 0x3d2b0000 0x0 0x20>, + <0x2 0x3d0d9300 0x0 0x100>; + reg-names = "ps", "ps-aon", "clk-mux", "wake", + "cpu-start", "wdt", "spmi"; + /* NUB.SPMI0Sw3IRQ: the PMU RTC's alarm */ + apple,wake-enable = <54>; + apple,display-coprocessors = <&dcp>; + apple,pinctrl = <&pinctrl_ap>; + status = "disabled"; + }; + pmgr_dcp: power-management@23b738000 { reg = <0x2 0x3b738000 0x0 0x1000>, <0x2 0x3bc3c000 0x0 0x1000>; @@ -1209,11 +1249,26 @@ reg = <0x2 0x3d0d9300 0x0 0x100>; #address-cells = <2>; #size-cells = <0>; + #interrupt-cells = <2>; + interrupt-controller; + interrupt-parent = <&aic>; + interrupts = ; + apple,response-vector = <192>; pmic1: pmic@f { compatible = "apple,sera-pmic", "apple,spmi-nvmem"; reg = <0xf SPMI_USID>; + pmu_rtc: rtc { + compatible = "apple,t8103-pmu-rtc", "apple,t8112-pmu-rtc"; + apple,rtc-base = <0xd000>; + interrupt-parent = <&nub_spmi>; + interrupts = <2 IRQ_TYPE_EDGE_RISING>; + nvmem-cells = <&rtc_offset>; + nvmem-cell-names = "rtc_offset"; + wakeup-source; + }; + nvmem-layout { compatible = "fixed-layout"; #address-cells = <1>; @@ -1242,8 +1297,8 @@ bits = <3 1>; }; - fault_shadow: fault-shadow@a67b { - reg = <0xa67b 0x10>; + fault_shadow: fault-shadow@a47b { + reg = <0xa47b 0x10>; }; socd: socd@ab00 { @@ -1323,7 +1378,7 @@ compatible = "apple,smc-hwmon"; }; - rtc { + smc_rtc: rtc { compatible = "apple,smc-rtc"; nvmem-cells = <&rtc_offset>; nvmem-cell-names = "rtc_offset"; @@ -1378,6 +1433,11 @@ mboxes = <&sep_mbox>; mbox-names = "mbox"; iommus = <&sep_dart 0>; + /* + * The enclave stops reading its mailbox for good once + * the GPIO power state is switched off under it. + */ + power-domains = <&ps_sep>, <&ps_gpio>; status = "disabled"; }; @@ -1593,6 +1653,7 @@ dcpext: dcp@271c00000 { compatible = "apple,t8103-dcpext", "apple,dcpext"; + apple,display-power = <&dcp_power>; mboxes = <&dcpext_mbox>; mbox-names = "mbox"; iommus = <&dcpext_dart 0 0x0 0x0 0x0 0xfc000000>; diff --git a/arch/arm64/boot/dts/apple/t8112-hwmon-rails.dtsi b/arch/arm64/boot/dts/apple/t8112-hwmon-rails.dtsi new file mode 100644 index 00000000000000..bd9901415f02b4 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8112-hwmon-rails.dtsi @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * T8112 PMU rail channels published by the SMC on every board measured so + * far (J413, J473). + * + * The SMC samples the main PMU outputs (VPxy voltage, IPxy current, PPxy + * power) and a second regulator family (VRxy, IRxy, PRxy). With the other + * cluster held at its lowest step, one cluster under load moves only its + * own output. On the J413: + * P cluster (cpu4-7): VP0b 555-775 mV, IP0b up to 7.8 A, PP0b up to 6.1 W + * E cluster (cpu0-3): VPbb 537-905 mV, IPbb up to 2.2 A, PPbb up to 2.0 W + * GPU: VP1b 0 mV while power-gated, 900-930 mV under load, PP1b ~1.1 W + * The J473 moves the same outputs: PP0b 0.4 W idle, 12.7 W with the P + * cluster loaded; PPbb 0.01 W idle, 2.1 W with the E cluster loaded. + * The consumers of the other outputs are not mapped; they are labelled + * "PMU " and "Rail ". Outputs whose current and power read 0 in + * every state are left out. Linux only reads the SMC keys. + * + * The driver skips a voltage, current or power channel whose key the SMC + * does not have, so a board without one of these outputs loses only that + * channel. + */ + +&smc_hwmon { + voltage-VP0b { + apple,key-id = "VP0b"; + label = "P-cluster VP0b"; + }; + + voltage-VPbb { + apple,key-id = "VPbb"; + label = "E-cluster VPbb"; + }; + + voltage-VP1b { + apple,key-id = "VP1b"; + label = "GPU VP1b"; + }; + + voltage-VP2b { + apple,key-id = "VP2b"; + label = "PMU VP2b"; + }; + + voltage-VP3b { + apple,key-id = "VP3b"; + label = "PMU VP3b"; + }; + + voltage-VP4b { + apple,key-id = "VP4b"; + label = "PMU VP4b"; + }; + + voltage-VP7b { + apple,key-id = "VP7b"; + label = "PMU VP7b"; + }; + + voltage-VP7l { + apple,key-id = "VP7l"; + label = "PMU VP7l"; + }; + + voltage-VP9b { + apple,key-id = "VP9b"; + label = "PMU VP9b"; + }; + + voltage-VP9l { + apple,key-id = "VP9l"; + label = "PMU VP9l"; + }; + + voltage-VPdb { + apple,key-id = "VPdb"; + label = "PMU VPdb"; + }; + + voltage-VR4l { + apple,key-id = "VR4l"; + label = "Rail VR4l"; + }; + + voltage-VR5b { + apple,key-id = "VR5b"; + label = "Rail VR5b"; + }; + + voltage-VR6b { + apple,key-id = "VR6b"; + label = "Rail VR6b"; + }; + + voltage-VR8b { + apple,key-id = "VR8b"; + label = "Rail VR8b"; + }; + + voltage-VRab { + apple,key-id = "VRab"; + label = "Rail VRab"; + }; + + voltage-VRcb { + apple,key-id = "VRcb"; + label = "Rail VRcb"; + }; + + voltage-VRcl { + apple,key-id = "VRcl"; + label = "Rail VRcl"; + }; + + voltage-VReb { + apple,key-id = "VReb"; + label = "Rail VReb"; + }; + + current-IP0b { + apple,key-id = "IP0b"; + label = "P-cluster IP0b"; + }; + + current-IPbb { + apple,key-id = "IPbb"; + label = "E-cluster IPbb"; + }; + + current-IP1b { + apple,key-id = "IP1b"; + label = "GPU IP1b"; + }; + + current-IP2b { + apple,key-id = "IP2b"; + label = "PMU IP2b"; + }; + + current-IP4b { + apple,key-id = "IP4b"; + label = "PMU IP4b"; + }; + + current-IP7b { + apple,key-id = "IP7b"; + label = "PMU IP7b"; + }; + + current-IP7l { + apple,key-id = "IP7l"; + label = "PMU IP7l"; + }; + + current-IP9b { + apple,key-id = "IP9b"; + label = "PMU IP9b"; + }; + + current-IR4l { + apple,key-id = "IR4l"; + label = "Rail IR4l"; + }; + + current-IR5b { + apple,key-id = "IR5b"; + label = "Rail IR5b"; + }; + + current-IR8b { + apple,key-id = "IR8b"; + label = "Rail IR8b"; + }; + + current-IRcl { + apple,key-id = "IRcl"; + label = "Rail IRcl"; + }; + + power-PP0b { + apple,key-id = "PP0b"; + label = "P-cluster PP0b"; + }; + + power-PPbb { + apple,key-id = "PPbb"; + label = "E-cluster PPbb"; + }; + + power-PP1b { + apple,key-id = "PP1b"; + label = "GPU PP1b"; + }; + + power-PP2b { + apple,key-id = "PP2b"; + label = "PMU PP2b"; + }; + + power-PP4b { + apple,key-id = "PP4b"; + label = "PMU PP4b"; + }; + + power-PP7b { + apple,key-id = "PP7b"; + label = "PMU PP7b"; + }; + + power-PP7l { + apple,key-id = "PP7l"; + label = "PMU PP7l"; + }; + + power-PP9b { + apple,key-id = "PP9b"; + label = "PMU PP9b"; + }; + + power-PR4l { + apple,key-id = "PR4l"; + label = "Rail PR4l"; + }; + + power-PR5b { + apple,key-id = "PR5b"; + label = "Rail PR5b"; + }; + + power-PRcl { + apple,key-id = "PRcl"; + label = "Rail PRcl"; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8112-hwmon.dtsi b/arch/arm64/boot/dts/apple/t8112-hwmon.dtsi new file mode 100644 index 00000000000000..ec67a007315257 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8112-hwmon.dtsi @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * T8112 SoC temperature channels published by the SMC, beyond the ones in + * t8112.dtsi. They are sensors of the SoC die, read-only; the J413 and + * J473 SMCs both publish every key here. + * + * t8112.dtsi makes the hwmon node a thermal sensor provider, so the driver + * keeps the channel number of a temperature key the SMC does not have and + * hides that channel with one warning. + * + * Include this file after the board's other hwmon files. The thermal zones + * index the first channels of t8112.dtsi; nothing indexes these. + */ + +/* + * GPU temperatures. The SMC publishes them only while the GPU is powered: + * with the GPU off, Tg0e, Tg0m and Tg0q read 0 C and Tg0f, Tg0n and Tg0r + * 4.6 C (they track the first three plus a fixed 4.6 C). Those + * placeholders are no data. Tg0f, Tg0n and Tg0r are in t8112.dtsi. + */ +&smc_hwmon { + temperature-Tg0e { + apple,key-id = "Tg0e"; + label = "GPU Tg0e"; + apple,no-data-below-millicelsius = <10000>; + }; + + temperature-Tg0m { + apple,key-id = "Tg0m"; + label = "GPU Tg0m"; + apple,no-data-below-millicelsius = <10000>; + }; + + temperature-Tg0q { + apple,key-id = "Tg0q"; + label = "GPU Tg0q"; + apple,no-data-below-millicelsius = <10000>; + }; +}; + +/* + * The other CPU temperatures, after the GPU channels. Each sensor site has + * a reading, the same plus a fixed offset and a hotspot estimate; the CPU + * thermal zones use the offset keys of four P sites and Te05. Te04-Te06 + * follow the E cluster, every Tp key the P cluster, TCMz is the hottest + * hotspot key and TCMb the hottest offset key. + */ +&smc_hwmon { + temperature-TCMb { + apple,key-id = "TCMb"; + label = "SoC Die TCMb"; + }; + + temperature-Te04 { + apple,key-id = "Te04"; + label = "E-cluster Te04"; + }; + + temperature-Te06 { + apple,key-id = "Te06"; + label = "E-cluster Te06"; + }; + + temperature-Tp00 { + apple,key-id = "Tp00"; + label = "P-cluster Tp00"; + }; + + temperature-Tp02 { + apple,key-id = "Tp02"; + label = "P-cluster Tp02"; + }; + + temperature-Tp04 { + apple,key-id = "Tp04"; + label = "P-cluster Tp04"; + }; + + temperature-Tp06 { + apple,key-id = "Tp06"; + label = "P-cluster Tp06"; + }; + + temperature-Tp08 { + apple,key-id = "Tp08"; + label = "P-cluster Tp08"; + }; + + temperature-Tp0A { + apple,key-id = "Tp0A"; + label = "P-cluster Tp0A"; + }; + + temperature-Tp0C { + apple,key-id = "Tp0C"; + label = "P-cluster Tp0C"; + }; + + temperature-Tp0E { + apple,key-id = "Tp0E"; + label = "P-cluster Tp0E"; + }; + + temperature-Tp0a { + apple,key-id = "Tp0a"; + label = "P-cluster Tp0a"; + }; + + temperature-Tp0b { + apple,key-id = "Tp0b"; + label = "P-cluster Tp0b"; + }; + + temperature-Tp0c { + apple,key-id = "Tp0c"; + label = "P-cluster Tp0c"; + }; + + temperature-Tp0e { + apple,key-id = "Tp0e"; + label = "P-cluster Tp0e"; + }; + + temperature-Tp0f { + apple,key-id = "Tp0f"; + label = "P-cluster Tp0f"; + }; + + temperature-Tp0g { + apple,key-id = "Tp0g"; + label = "P-cluster Tp0g"; + }; + + temperature-Tp0i { + apple,key-id = "Tp0i"; + label = "P-cluster Tp0i"; + }; + + temperature-Tp0j { + apple,key-id = "Tp0j"; + label = "P-cluster Tp0j"; + }; + + temperature-Tp0k { + apple,key-id = "Tp0k"; + label = "P-cluster Tp0k"; + }; + + temperature-Tp0m { + apple,key-id = "Tp0m"; + label = "P-cluster Tp0m"; + }; + + temperature-Tp0n { + apple,key-id = "Tp0n"; + label = "P-cluster Tp0n"; + }; + + temperature-Tp0o { + apple,key-id = "Tp0o"; + label = "P-cluster Tp0o"; + }; + + temperature-Tp0q { + apple,key-id = "Tp0q"; + label = "P-cluster Tp0q"; + }; + + temperature-Tp0r { + apple,key-id = "Tp0r"; + label = "P-cluster Tp0r"; + }; + + temperature-Tp0s { + apple,key-id = "Tp0s"; + label = "P-cluster Tp0s"; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8112-j413-hwmon-rails.dtsi b/arch/arm64/boot/dts/apple/t8112-j413-hwmon-rails.dtsi index dfe95d1bdc2e9b..0655d73a96d271 100644 --- a/arch/arm64/boot/dts/apple/t8112-j413-hwmon-rails.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j413-hwmon-rails.dtsi @@ -1,180 +1,36 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT /* - * T8112 J413 PMU rail channels published by the SMC. - * - * The SMC samples the main PMU outputs (VPxy voltage, IPxy current, PPxy - * power) and a second regulator family (VRxy, IRxy, PRxy). With the other - * cluster held at its lowest step, one cluster under load moves only its - * own output: - * P cluster (cpu4-7): VP0b 555-775 mV, IP0b up to 7.8 A, PP0b up to 6.1 W - * E cluster (cpu0-3): VPbb 537-905 mV, IPbb up to 2.2 A, PPbb up to 2.0 W - * GPU: VP1b 0 mV while power-gated, 900-930 mV under load, PP1b ~1.1 W - * The consumers of the other outputs are not mapped; they are labelled - * "PMU " and "Rail ". Outputs whose current and power read 0 in - * every state are left out. Linux only reads the SMC keys. + * T8112 J413 PMU rail channels the J473 SMC does not publish. The rails + * both boards have are in t8112-hwmon-rails.dtsi, where the key naming is + * explained. The consumers of these outputs are not mapped. */ &smc_hwmon { - voltage-VP0b { - apple,key-id = "VP0b"; - label = "P-cluster VP0b"; - }; - - voltage-VPbb { - apple,key-id = "VPbb"; - label = "E-cluster VPbb"; - }; - - voltage-VP1b { - apple,key-id = "VP1b"; - label = "GPU VP1b"; - }; - voltage-VP0R { apple,key-id = "VP0R"; label = "PMU VP0R"; }; - voltage-VP2b { - apple,key-id = "VP2b"; - label = "PMU VP2b"; - }; - voltage-VP2l { apple,key-id = "VP2l"; label = "PMU VP2l"; }; - voltage-VP3b { - apple,key-id = "VP3b"; - label = "PMU VP3b"; - }; - - voltage-VP4b { - apple,key-id = "VP4b"; - label = "PMU VP4b"; - }; - - voltage-VP7b { - apple,key-id = "VP7b"; - label = "PMU VP7b"; - }; - - voltage-VP7l { - apple,key-id = "VP7l"; - label = "PMU VP7l"; - }; - voltage-VP8l { apple,key-id = "VP8l"; label = "PMU VP8l"; }; - voltage-VP9b { - apple,key-id = "VP9b"; - label = "PMU VP9b"; - }; - - voltage-VP9l { - apple,key-id = "VP9l"; - label = "PMU VP9l"; - }; - - voltage-VPdb { - apple,key-id = "VPdb"; - label = "PMU VPdb"; - }; - voltage-VPkl { apple,key-id = "VPkl"; label = "PMU VPkl"; }; - voltage-VR4l { - apple,key-id = "VR4l"; - label = "Rail VR4l"; - }; - - voltage-VR5b { - apple,key-id = "VR5b"; - label = "Rail VR5b"; - }; - - voltage-VR6b { - apple,key-id = "VR6b"; - label = "Rail VR6b"; - }; - - voltage-VR8b { - apple,key-id = "VR8b"; - label = "Rail VR8b"; - }; - - voltage-VRab { - apple,key-id = "VRab"; - label = "Rail VRab"; - }; - - voltage-VRcb { - apple,key-id = "VRcb"; - label = "Rail VRcb"; - }; - - voltage-VRcl { - apple,key-id = "VRcl"; - label = "Rail VRcl"; - }; - - voltage-VReb { - apple,key-id = "VReb"; - label = "Rail VReb"; - }; - - current-IP0b { - apple,key-id = "IP0b"; - label = "P-cluster IP0b"; - }; - - current-IPbb { - apple,key-id = "IPbb"; - label = "E-cluster IPbb"; - }; - - current-IP1b { - apple,key-id = "IP1b"; - label = "GPU IP1b"; - }; - - current-IP2b { - apple,key-id = "IP2b"; - label = "PMU IP2b"; - }; - - current-IP4b { - apple,key-id = "IP4b"; - label = "PMU IP4b"; - }; - - current-IP7b { - apple,key-id = "IP7b"; - label = "PMU IP7b"; - }; - - current-IP7l { - apple,key-id = "IP7l"; - label = "PMU IP7l"; - }; - current-IP8l { apple,key-id = "IP8l"; label = "PMU IP8l"; }; - current-IP9b { - apple,key-id = "IP9b"; - label = "PMU IP9b"; - }; - current-IPBR { apple,key-id = "IPBR"; label = "PMU IPBR"; @@ -185,71 +41,11 @@ label = "PMU IPkl"; }; - current-IR4l { - apple,key-id = "IR4l"; - label = "Rail IR4l"; - }; - - current-IR5b { - apple,key-id = "IR5b"; - label = "Rail IR5b"; - }; - - current-IR8b { - apple,key-id = "IR8b"; - label = "Rail IR8b"; - }; - - current-IRcl { - apple,key-id = "IRcl"; - label = "Rail IRcl"; - }; - - power-PP0b { - apple,key-id = "PP0b"; - label = "P-cluster PP0b"; - }; - - power-PPbb { - apple,key-id = "PPbb"; - label = "E-cluster PPbb"; - }; - - power-PP1b { - apple,key-id = "PP1b"; - label = "GPU PP1b"; - }; - - power-PP2b { - apple,key-id = "PP2b"; - label = "PMU PP2b"; - }; - - power-PP4b { - apple,key-id = "PP4b"; - label = "PMU PP4b"; - }; - - power-PP7b { - apple,key-id = "PP7b"; - label = "PMU PP7b"; - }; - - power-PP7l { - apple,key-id = "PP7l"; - label = "PMU PP7l"; - }; - power-PP8l { apple,key-id = "PP8l"; label = "PMU PP8l"; }; - power-PP9b { - apple,key-id = "PP9b"; - label = "PMU PP9b"; - }; - power-PPBR { apple,key-id = "PPBR"; label = "PMU PPBR"; @@ -260,23 +56,8 @@ label = "PMU PPkl"; }; - power-PR4l { - apple,key-id = "PR4l"; - label = "Rail PR4l"; - }; - - power-PR5b { - apple,key-id = "PR5b"; - label = "Rail PR5b"; - }; - power-PR8b { apple,key-id = "PR8b"; label = "Rail PR8b"; }; - - power-PRcl { - apple,key-id = "PRcl"; - label = "Rail PRcl"; - }; }; diff --git a/arch/arm64/boot/dts/apple/t8112-j413.dts b/arch/arm64/boot/dts/apple/t8112-j413.dts index ff99c23afb7a96..7f8825891237e7 100644 --- a/arch/arm64/boot/dts/apple/t8112-j413.dts +++ b/arch/arm64/boot/dts/apple/t8112-j413.dts @@ -270,7 +270,6 @@ }; actuator { - apple,click-strength = <0xc0 0x6e>; }; tp_accel { @@ -278,173 +277,9 @@ }; #include "hwmon-laptop.dtsi" +#include "t8112-hwmon-rails.dtsi" #include "t8112-j413-hwmon-rails.dtsi" - -/* - * GPU temperatures, after the channels the thermal zones index. The SMC - * publishes them only while the GPU is powered: with the GPU off, Tg0e, - * Tg0m and Tg0q read 0 C and Tg0f, Tg0n and Tg0r 4.6 C (they track the - * first three plus a fixed 4.6 C). Those placeholders are no data. - * Tg0f, Tg0n and Tg0r are in t8112.dtsi. - */ -&smc_hwmon { - temperature-Tg0e { - apple,key-id = "Tg0e"; - label = "GPU Tg0e"; - apple,no-data-below-millicelsius = <10000>; - }; - - temperature-Tg0m { - apple,key-id = "Tg0m"; - label = "GPU Tg0m"; - apple,no-data-below-millicelsius = <10000>; - }; - - temperature-Tg0q { - apple,key-id = "Tg0q"; - label = "GPU Tg0q"; - apple,no-data-below-millicelsius = <10000>; - }; -}; - -/* - * The other CPU temperatures, read-only, after the GPU channels. Each - * sensor site has a reading, the same plus a fixed offset and a hotspot - * estimate; the zones above use the offset keys of four P sites and Te05. - * Te04-Te06 follow the E cluster, every Tp key the P cluster, TCMz is the - * hottest hotspot key and TCMb the hottest offset key. - */ -&smc_hwmon { - temperature-TCMb { - apple,key-id = "TCMb"; - label = "SoC Die TCMb"; - }; - - temperature-Te04 { - apple,key-id = "Te04"; - label = "E-cluster Te04"; - }; - - temperature-Te06 { - apple,key-id = "Te06"; - label = "E-cluster Te06"; - }; - - temperature-Tp00 { - apple,key-id = "Tp00"; - label = "P-cluster Tp00"; - }; - - temperature-Tp02 { - apple,key-id = "Tp02"; - label = "P-cluster Tp02"; - }; - - temperature-Tp04 { - apple,key-id = "Tp04"; - label = "P-cluster Tp04"; - }; - - temperature-Tp06 { - apple,key-id = "Tp06"; - label = "P-cluster Tp06"; - }; - - temperature-Tp08 { - apple,key-id = "Tp08"; - label = "P-cluster Tp08"; - }; - - temperature-Tp0A { - apple,key-id = "Tp0A"; - label = "P-cluster Tp0A"; - }; - - temperature-Tp0C { - apple,key-id = "Tp0C"; - label = "P-cluster Tp0C"; - }; - - temperature-Tp0E { - apple,key-id = "Tp0E"; - label = "P-cluster Tp0E"; - }; - - temperature-Tp0a { - apple,key-id = "Tp0a"; - label = "P-cluster Tp0a"; - }; - - temperature-Tp0b { - apple,key-id = "Tp0b"; - label = "P-cluster Tp0b"; - }; - - temperature-Tp0c { - apple,key-id = "Tp0c"; - label = "P-cluster Tp0c"; - }; - - temperature-Tp0e { - apple,key-id = "Tp0e"; - label = "P-cluster Tp0e"; - }; - - temperature-Tp0f { - apple,key-id = "Tp0f"; - label = "P-cluster Tp0f"; - }; - - temperature-Tp0g { - apple,key-id = "Tp0g"; - label = "P-cluster Tp0g"; - }; - - temperature-Tp0i { - apple,key-id = "Tp0i"; - label = "P-cluster Tp0i"; - }; - - temperature-Tp0j { - apple,key-id = "Tp0j"; - label = "P-cluster Tp0j"; - }; - - temperature-Tp0k { - apple,key-id = "Tp0k"; - label = "P-cluster Tp0k"; - }; - - temperature-Tp0m { - apple,key-id = "Tp0m"; - label = "P-cluster Tp0m"; - }; - - temperature-Tp0n { - apple,key-id = "Tp0n"; - label = "P-cluster Tp0n"; - }; - - temperature-Tp0o { - apple,key-id = "Tp0o"; - label = "P-cluster Tp0o"; - }; - - temperature-Tp0q { - apple,key-id = "Tp0q"; - label = "P-cluster Tp0q"; - }; - - temperature-Tp0r { - apple,key-id = "Tp0r"; - label = "P-cluster Tp0r"; - }; - - temperature-Tp0s { - apple,key-id = "Tp0s"; - label = "P-cluster Tp0s"; - }; -}; +#include "t8112-hwmon.dtsi" /* * Mesa fingerprint sensor on spi2. The J413 platform device tree @@ -479,16 +314,6 @@ status = "okay"; }; -&nub_spmi1 { - status = "okay"; - - pmic@e { - compatible = "apple,vale-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - }; -}; - &i2c2 { retimer@18 { compatible = "apple,t8112-atcrt", "apple,atcrt"; diff --git a/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi index 9e7941dd584e0b..174308798291f2 100644 --- a/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi @@ -43,11 +43,3 @@ }; }; -&nub_spmi1 { - pmic@e { - compatible = "apple,vale-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - status = "disabled"; - }; -}; diff --git a/arch/arm64/boot/dts/apple/t8112-j473-fw27.dts b/arch/arm64/boot/dts/apple/t8112-j473-fw27.dts new file mode 100644 index 00000000000000..d71e8ac486ba23 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8112-j473-fw27.dts @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* J473 with macOS 27 system firmware (27.2 stub). */ +#include "t8112-j473.dts" + +/* + * The 27.2 GPU firmware keeps running through suspend-to-idle. Gating the GFX + * domain under it leaves the domain unable to power on at the wake, as on the + * t8112-j413-fw27 board. + */ +&ps_gfx { + apple,sleep-retained; +}; diff --git a/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi index 9e7941dd584e0b..174308798291f2 100644 --- a/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi @@ -43,11 +43,3 @@ }; }; -&nub_spmi1 { - pmic@e { - compatible = "apple,vale-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - status = "disabled"; - }; -}; diff --git a/arch/arm64/boot/dts/apple/t8112-j473.dts b/arch/arm64/boot/dts/apple/t8112-j473.dts index 84ecd65613567d..d56375d3d0f75f 100644 --- a/arch/arm64/boot/dts/apple/t8112-j473.dts +++ b/arch/arm64/boot/dts/apple/t8112-j473.dts @@ -24,6 +24,7 @@ ethernet0 = ðernet0; rtc0 = &smc_rtc; rtc1 = &pmu_rtc; + sep = &sep; wifi0 = &wifi0; }; }; @@ -277,6 +278,8 @@ }; #include "hwmon-mini.dtsi" +#include "t8112-hwmon-rails.dtsi" +#include "t8112-hwmon.dtsi" #include "t8112-j473-peripherals.dtsi" diff --git a/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi index b7e06632fdf791..a9b1d4c8a8a556 100644 --- a/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi @@ -26,11 +26,3 @@ }; }; -&nub_spmi1 { - pmic@e { - compatible = "apple,vale-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - status = "disabled"; - }; -}; diff --git a/arch/arm64/boot/dts/apple/t8112.dtsi b/arch/arm64/boot/dts/apple/t8112.dtsi index d6787eff621bb6..a5b0542e289894 100644 --- a/arch/arm64/boot/dts/apple/t8112.dtsi +++ b/arch/arm64/boot/dts/apple/t8112.dtsi @@ -27,6 +27,11 @@ #endif }; + clpc: performance-controller { + compatible = "apple,t8112-clpc", "apple,clpc"; + apple,smc = <&smc>; + }; + cpus { #address-cells = <2>; #size-cells = <0>; @@ -1519,12 +1524,18 @@ }; }; + /* ADT /arm-io/nub-spmi1: the auxiliary PMU (pmu-aux) at USID 0xe. */ nub_spmi1: spmi@23d794000 { compatible = "apple,t8112-spmi", "apple,t8103-spmi"; reg = <0x2 0x3d794000 0x0 0x100>; #address-cells = <2>; #size-cells = <0>; - status = "disabled"; + + pmic@e { + compatible = "apple,vale-pmic", "apple,spmi-nvmem"; + reg = <0xe SPMI_USID>; + read-only; + }; }; smc: smc@23e400000 { @@ -1847,6 +1858,16 @@ status = "disabled"; }; + /* + * Disabled here on every board by design. The SEP is already + * running when Linux starts (warm attach: one shared-memory + * registration, no cold boot), so apple_sep enables this node + * and sep_dart with a changeset at module load, once it has + * picked this SoC's profile and before the DART probes. A + * board with the enclave only needs the sep alias, which the + * boot loader uses to add the sepfw region and the boot + * manifests. + */ sep: sep@25e400000 { compatible = "apple,sep"; reg = <0x2 0x5e400000 0x0 0x6C000>; diff --git a/arch/arm64/boot/dts/apple/t8122-dcp.dtsi b/arch/arm64/boot/dts/apple/t8122-dcp.dtsi index 57655491a8e36a..fa98a40cc06482 100644 --- a/arch/arm64/boot/dts/apple/t8122-dcp.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-dcp.dtsi @@ -33,6 +33,8 @@ display: display-subsystem { compatible = "apple,t8122-display-subsystem"; iommus = <&disp0_dart 0>; + /* Keep the inherited scanout alias when adding external streams. */ + apple,dma-range = /bits/ 64 <0x10000000000 0x1000000000>; status = "disabled"; }; }; diff --git a/arch/arm64/boot/dts/apple/t8122-j504.dts b/arch/arm64/boot/dts/apple/t8122-j504.dts index f8258ba3a2f541..f290f011206777 100644 --- a/arch/arm64/boot/dts/apple/t8122-j504.dts +++ b/arch/arm64/boot/dts/apple/t8122-j504.dts @@ -39,13 +39,23 @@ &dcp { panel: panel { compatible = "apple,panel-j504", "apple,panel-mini-led", "apple,panel"; + /* + * The J514S panel: 3024x1964 at 254 ppi; 189 mm high without the + * 74 notch rows. The J504 boot framebuffer is 3024x1890 below them. + */ width-mm = <302>; height-mm = <196>; adj-height-mm = <189>; - apple,max-brightness = <600>; + apple,max-brightness = <500>; }; }; +/* The boot framebuffer is the same panel, as on the J613 (HiDPI scale for simpledrm). */ +&framebuffer0 { + panel = <&panel>; + post-init-providers = <&panel>; +}; + &wifi0 { brcm,board-type = "apple,tresco"; }; diff --git a/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi b/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi index f891967d74d041..496a99078aa531 100644 --- a/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi @@ -18,7 +18,6 @@ chassis-type = "laptop"; aliases { - dcpext = &dcpext; keyboard = &keyboard; sep = &sep; }; @@ -116,7 +115,7 @@ apple,temporal-filter = <1>; }; -/* Touch ID; its data-ready line (AP GPIO 199) is left out, so it polls. */ +/* Touch ID */ &spi2 { status = "okay"; }; @@ -124,82 +123,14 @@ &mesa { status = "okay"; enable-gpios = <&pinctrl_nub 29 GPIO_ACTIVE_HIGH>; + interrupt-parent = <&pinctrl_ap>; + interrupts = <199 IRQ_TYPE_EDGE_RISING>; spi-cs-setup-delay-ns = <20>; spi-cs-hold-delay-ns = <20>; }; #include "hwmon-laptop.dtsi" -/* - * One external display on either USB-C port: dcpext is crossbar state 2 of - * each ATC and its DPTX target is the ATC index. The display gate enables it - * and the routes once the boot loader has readied its firmware. - */ -&dcpext { - apple,connector-type = "USB-C"; - phys = <&atcphy0 PHY_TYPE_DP>, <&atcphy1 PHY_TYPE_DP>; - phy-names = "typec0", "typec1"; - mux-controls = <&atcphy0_xbar 0>, <&atcphy1_xbar 0>; - mux-control-names = "typec0", "typec1"; - apple,typec-mux-indices = <2 2>; - apple,typec-dptx-phys = <0 1>; - /* RTKit quirks of AsahiLinux/linux#607 (syslog/ioreport acks, kdebug). */ - apple,sync-syslog-ack; - - typec-routes { - #address-cells = <1>; - #size-cells = <0>; - - route@0 { - reg = <0>; - mode-switch; - status = "disabled"; - - port { - dcpext_typec0: endpoint { - remote-endpoint = <&typec0_dcpext>; - }; - }; - }; - - route@1 { - reg = <1>; - mode-switch; - status = "disabled"; - - port { - dcpext_typec1: endpoint { - remote-endpoint = <&typec1_dcpext>; - }; - }; - }; - }; -}; - -&typec0 { - ports { - port@3 { - reg = <3>; - - typec0_dcpext: endpoint { - remote-endpoint = <&dcpext_typec0>; - }; - }; - }; -}; - -&typec1 { - ports { - port@3 { - reg = <3>; - - typec1_dcpext: endpoint { - remote-endpoint = <&dcpext_typec1>; - }; - }; - }; -}; - / { /* * Fanless, same die and the same six CPU die sensors on both: every @@ -503,3 +434,13 @@ }; }; }; + +&mcc { + apple,boot-dma-devices = <&pmp>; + status = "okay"; +}; + +&sleep { + apple,debug-port = <&hpm0>; + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t8122-j615-25g83.dts b/arch/arm64/boot/dts/apple/t8122-j615-25g83.dts index 7aef84a8e34940..58ba870b999bc7 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615-25g83.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615-25g83.dts @@ -5,7 +5,11 @@ */ #include "t8122-j615.dts" #include "t8122-j613-dcp-25g83.dtsi" -#include "t8122-j613-qspi.dtsi" + +/* The memory floor has not run with the native J613 report on a J615. */ +&pmp_report { + /delete-property/ apple,cpu-memory-floor; +}; /* As on the J613 25G83. */ &mtp { @@ -16,8 +20,3 @@ &mtp_mt { apple,power-method = <2>; }; - -/* Keep the J615 NVRAM partition read-only. */ -&nvram_qspi { - read-only; -}; diff --git a/arch/arm64/boot/dts/apple/t8122-j615.dts b/arch/arm64/boot/dts/apple/t8122-j615.dts index efc761f62a9ec8..bd9f69a72acc05 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615.dts @@ -11,12 +11,21 @@ #include "t8122.dtsi" #include "t8122-j613-j615.dtsi" +#include "t8122-j613-qspi.dtsi" / { compatible = "apple,j615", "apple,t8122", "apple,arm-platform"; model = "Apple MacBook Air (15-inch, M3, 2024)"; }; +/* + * CPU memory floor, class 0x25 (DCS) at 4 and 0x21 (fabric) at 2. The 14.x + * PMP answers it with DVFS-STATE 0x24: 4-thread membw2 19.8 -> 68.2 GB/s. + */ +&pmp_report { + apple,cpu-memory-floor = <0x21 2 0x25 4>; +}; + &dcp { /* * DRM owns swap slots 0 and 1 here. On this panel the indicator @@ -165,9 +174,69 @@ &mtp_mt { firmware-name = "apple/tpmtfw-j615.bin"; + /* + * No apple,power-method: the 14.7 trackpad firmware takes only + * method 1 and the 27.x firmware only method 2. dockchannel-hid + * starts with method 1 and moves to method 2 when it is rejected. + */ +}; + +/* The J615 MTP firmware cannot be restarted once quiesced: hand it over running. */ +&mtp { + apple,rtkit-keep-running; }; &mesa { /* Per-device factory data from this Mac's own iBoot system container. */ firmware-name = "apple/mesacal-j615.bin"; }; + +/* + * The J615 ADT puts the boot NOR and its nvram on QSPIMC, as on the J613. + * No NVRAM write entry exists for this board yet: keep it read-only. + */ +&nvram_qspi { + read-only; +}; + +&ane_dart0 { + status = "okay"; +}; + +&ane_dart1 { + status = "okay"; +}; + +&ane_dart2 { + status = "okay"; +}; + +&ane { + status = "okay"; +}; + +/* + * The Wi-Fi/Bluetooth module's CLKREQ# is wired to the SoC (the J615 ADT gives + * the Wi-Fi bridge a CLKREQ function), so the link may use Clock PM and the L1 + * PM Substates. + */ +&port00 { + supports-clkreq; +}; + +/* + * The dcpext wiring is shared with the J613 (t8122-j613-j615.dtsi). fbdma is + * the display DART stream the dcpext scans framebuffers through, with the + * display subsystem's DVA window: on the J615 the gate must not add + * dispext0_dart to the display subsystem (apple,no-shared-display-dart), so + * appledrm mirrors framebuffers there instead. + */ +&dcpext { + apple,no-shared-display-dart; + + fbdma { + iommus = <&dispext0_dart 0>; + apple,dma-range = /bits/ 64 <0x10000000000 0x1000000000>; + }; +}; + diff --git a/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi b/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi index b6cd4ee1c40873..91aa0c621bcc76 100644 --- a/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi @@ -14,6 +14,7 @@ atcphy0 = &atcphy0; atcphy1 = &atcphy1; bluetooth0 = &bluetooth0; + dcpext = &dcpext; serial0 = &serial0; wifi0 = &wifi0; @@ -257,11 +258,92 @@ #include "spi1-nvram.dtsi" -/* Panel control remains firmware-owned until the host transport is supported. */ +/* + * The DP855 panel timing controller. i2c-dp855 reads the panel management + * devices behind it and shares its I2C engine with the display firmware + * through the controller's lock. Every T8122 board's ADT has the controller + * at /arm-io/spi4/dp855, with the chip select at /arm-io/spi4 + * function-spi_cs0: GPIO 136 on gpio0 (J613, J615, J504, J433 and J434). + */ &spi4 { + cs-gpios = <&pinctrl_ap 136 GPIO_ACTIVE_LOW>; + status = "okay"; + tcon: panel-controller@0 { compatible = "parade,dp855"; reg = <0>; - status = "disabled"; + spi-max-frequency = <1000000>; + spi-cs-setup-delay-ns = <20>; + spi-cs-hold-delay-ns = <20>; + }; +}; + +/* + * One external display on either USB-C port: dcpext is crossbar state 2 of + * each ATC and its DPTX target is the ATC index. The display gate enables it + * and the routes once the boot loader has readied its firmware. + */ +&dcpext { + apple,connector-type = "USB-C"; + phys = <&atcphy0 PHY_TYPE_DP>, <&atcphy1 PHY_TYPE_DP>; + phy-names = "typec0", "typec1"; + mux-controls = <&atcphy0_xbar 0>, <&atcphy1_xbar 0>; + mux-control-names = "typec0", "typec1"; + apple,typec-mux-indices = <2 2>; + apple,typec-dptx-phys = <0 1>; + /* RTKit quirks of AsahiLinux/linux#607 (syslog/ioreport acks, kdebug). */ + apple,sync-syslog-ack; + + typec-routes { + #address-cells = <1>; + #size-cells = <0>; + + route@0 { + reg = <0>; + mode-switch; + status = "disabled"; + + port { + dcpext_typec0: endpoint { + remote-endpoint = <&typec0_dcpext>; + }; + }; + }; + + route@1 { + reg = <1>; + mode-switch; + status = "disabled"; + + port { + dcpext_typec1: endpoint { + remote-endpoint = <&typec1_dcpext>; + }; + }; + }; + }; +}; + +&typec0 { + ports { + port@3 { + reg = <3>; + + typec0_dcpext: endpoint { + remote-endpoint = <&dcpext_typec0>; + }; + }; + }; +}; + +&typec1 { + ports { + port@3 { + reg = <3>; + + typec1_dcpext: endpoint { + remote-endpoint = <&dcpext_typec1>; + }; + }; }; }; diff --git a/arch/arm64/boot/dts/apple/t8122-peripheral-buses.dtsi b/arch/arm64/boot/dts/apple/t8122-peripheral-buses.dtsi index 1bdbd8356541fb..fa50c02496cebf 100644 --- a/arch/arm64/boot/dts/apple/t8122-peripheral-buses.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-peripheral-buses.dtsi @@ -26,6 +26,7 @@ status = "disabled"; }; + /* ADT /arm-io/nub-spmi1: the auxiliary PMU (pmu-aux) at USID 0xe. */ nub_spmi1: spmi@2e4794000 { compatible = "apple,t8122-spmi", "apple,t8103-spmi"; reg = <0x2 0xe4794000 0 0x4000>, @@ -37,7 +38,12 @@ #interrupt-cells = <2>; #address-cells = <2>; #size-cells = <0>; - status = "disabled"; + + pmic@e { + compatible = "apple,vale-pmic", "apple,spmi-nvmem"; + reg = <0xe SPMI_USID>; + read-only; + }; }; aop_spmi0: spmi@2f4894000 { diff --git a/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi index 355199f3a6a863..b740469f7578a8 100644 --- a/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi @@ -141,12 +141,69 @@ status = "disabled"; }; + ane_dart0: iommu@311800000 { + compatible = "apple,t8122-dart", "apple,t8110-dart"; + reg = <0x3 0x11800000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = ; + #iommu-cells = <1>; + power-domains = <&ps_ane_sys>; + apple,dma-range = <0x0 0x0 0x400 0x0>; + status = "disabled"; + }; + dart_ane_companion3: filter@311804000 { compatible = "apple,t8122-dapf", "apple,dapf"; reg = <0x3 0x11804000 0x0 0x4000>; status = "disabled"; }; + ane_dart1: iommu@311810000 { + compatible = "apple,t8122-dart", "apple,t8110-dart"; + reg = <0x3 0x11810000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = ; + #iommu-cells = <1>; + power-domains = <&ps_ane_sys>; + apple,dma-range = <0x0 0x0 0x400 0x0>; + status = "disabled"; + }; + + ane_dart2: iommu@311820000 { + compatible = "apple,t8122-dart", "apple,t8110-dart"; + reg = <0x3 0x11820000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = ; + #iommu-cells = <1>; + power-domains = <&ps_ane_sys>; + apple,dma-range = <0x0 0x0 0x400 0x0>; + status = "disabled"; + }; + + ane: ane@310000000 { + compatible = "apple,t8122-ane"; + reg = <0x3 0x10000000 0x0 0x2000000>, + <0x2 0xd0700000 0x0 0x18000>, + <0x2 0xd0724000 0x0 0x4000>; + reg-names = "engine", "pmgr", "aux-0"; + interrupt-parent = <&aic>; + interrupts = ; + iommus = <&ane_dart0 0>, <&ane_dart1 0>, <&ane_dart2 0>; + power-domains = <&ps_ane_sys>, <&ps_ane_cpu>, <&ps_ane_mpm>, + <&ps_ane_td>, <&ps_ane_base>; + apple,ane-type = <0xb0>; + apple,firmware-preloaded; + /* ADT dapf-instance-0: inclusive CPU addresses, in record order. */ + apple,dapf-ranges = /bits/ 64 <0x2a5468000 0x2a5468003>, + /bits/ 64 <0x2d0700438 0x2d070043b>, + /bits/ 64 <0x2d070c000 0x2d070c01b>, + /bits/ 64 <0x2d072682c 0x2d072682f>, + /bits/ 64 <0x292468000 0x292468003>; + /* Default layout; the loader supplies per-boot physical reservations. */ + apple,firmware-iovas = /bits/ 64 <0x10000000000 0x100000c8000>; + status = "disabled"; + }; + apcie1_piodma: dma-controller@595010000 { compatible = "apple,t8122-pcie-piodma", "apple,pcie-piodma"; reg = <0x5 0x95010000 0x0 0x4000>, @@ -225,12 +282,9 @@ status = "disabled"; }; - mcc: memory-controller@2d03c0000 { + mcc: memory-controller@220000000 { compatible = "apple,t8122-mcc", "apple,mcc"; - reg = <0x2 0xd03c0000 0x0 0x20000>, - <0x2 0xd0478000 0x0 0x149c>, - <0x2 0xd0780000 0x0 0x4000>, - <0x2 0x20000000 0x0 0x2000000>, + reg = <0x2 0x20000000 0x0 0x2000000>, <0x2 0x22000000 0x0 0x2000000>; status = "disabled"; }; @@ -442,10 +496,12 @@ reg = <0x3 0x21000000 0x0 0x4000>, <0x3 0x20000000 0x0 0x8000>, <0x3 0x21078000 0x0 0x4000>; + reg-names = "core", "wrapper", "aux"; interrupt-parent = <&aic>; interrupts = , ; power-domains = <&ps_scodec>; + resets = <&ps_scodec>; iommus = <&dart_apr0 1>, <&dart_apr1 1>; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t8122-pmgr.dtsi b/arch/arm64/boot/dts/apple/t8122-pmgr.dtsi index 982cdc301e1948..05bbe95509d710 100644 --- a/arch/arm64/boot/dts/apple/t8122-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-pmgr.dtsi @@ -792,6 +792,7 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "ane_sys"; + apple,no-auto-pm; }; ps_apcie_gp: power-controller@440 { @@ -1119,6 +1120,43 @@ power-domains = <&ps_venc_me0>; }; + ps_ane_mpm: power-controller@c000 { + compatible = "apple,t8122-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xc000 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_mpm"; + power-domains = <&ps_ane_sys>; + }; + + ps_ane_cpu: power-controller@c008 { + compatible = "apple,t8122-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xc008 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_cpu"; + apple,no-auto-pm; + power-domains = <&ps_ane_sys>; + }; + + ps_ane_td: power-controller@c010 { + compatible = "apple,t8122-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xc010 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_td"; + power-domains = <&ps_ane_sys>; + }; + + ps_ane_base: power-controller@c018 { + compatible = "apple,t8122-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xc018 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_base"; + power-domains = <&ps_ane_td>, <&ps_ane_cpu>; + }; + ps_disp_cpu: power-controller@10000 { compatible = "apple,t8122-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; reg = <0x10000 4>; diff --git a/arch/arm64/boot/dts/apple/t8122.dtsi b/arch/arm64/boot/dts/apple/t8122.dtsi index ad7382ac89ea41..b95470d118340f 100644 --- a/arch/arm64/boot/dts/apple/t8122.dtsi +++ b/arch/arm64/boot/dts/apple/t8122.dtsi @@ -558,6 +558,7 @@ mboxes = <&sep_mbox>; mbox-names = "mbox"; iommus = <&sep_dart 0>; + power-domains = <&ps_sep>, <&ps_gpio>; status = "disabled"; }; @@ -893,6 +894,41 @@ /* child nodes are added in t8122-pmgr.dtsi */ }; + sleep: sleep-controller@2d0700000 { + compatible = "apple,t8122-sleep"; + reg = <0x2 0xd0700000 0x0 0x14000>, + <0x2 0xd0724000 0x0 0x4000>, + <0x2 0xd0734000 0x0 0x10>, + <0x2 0xd0768000 0x0 0x40>, + <0x2 0xd0780000 0x0 0x8>, + <0x2 0xe42d4000 0x0 0x4>, + <0x2 0xe42b0000 0x0 0x30>, + <0x2 0xe4714000 0x0 0x100>, + <0x2 0xe4908000 0x0 0x100>, + <0x2 0xe4004000 0x0 0x48>, + <0x2 0xe4280000 0x0 0x4000>, + <0x2 0x20024000 0x0 0x1000>, + <0x2 0x20064000 0x0 0x1000>, + <0x2 0x20158000 0x0 0x1000>, + <0x2 0x20400000 0x0 0x1000>, + <0x5 0x9c000000 0x0 0x2000>, + <0x5 0x91000000 0x0 0x1000>, + <0x5 0x9e088000 0x0 0x3000>, + <0x5 0x9e000000 0x0 0x10000>, + <0x5 0x9e040000 0x0 0x10000>, + <0x5 0x94008000 0x0 0x5000>; + reg-names = "ps", "pwrgate", "cpu-start", "cllt", + "cluster", "commit", "wdt", "spmi", + "spmi-hpm", "wake", "ps-aon", + "mcc-a", "mcc-b", "mcc-c", "mcc-d", + "apcie-axi", "apcie-rc", "apcie-clkgen", + "apcie-phy", "apcie-phy-ip", "apcie-port0"; + apple,wake-enable = <155>; + apple,display-coprocessors = <&dcp>; + apple,pinctrl = <&pinctrl_ap>; + status = "disabled"; + }; + pmp_mbox: mbox@2d0c08000 { compatible = "apple,t8122-asc-mailbox", "apple,asc-mailbox-v4"; reg = <0x2 0xd0c08000 0x0 0x4000>; @@ -1141,6 +1177,17 @@ apple,soc-die-keys = "Tg0D", "Tg0P", "Tg0X", "Tg0b", "Tg0j", "Tg0v", "Te05", "Te0P", "Tp05", "Tp0L", "Tp0b", "Tp0r"; + /* + * SoC die limits from the ADT's /arm-io/pmp/iop-pmp-nub, + * the same in the J433, J434, J504, J613 and J615 device + * trees: the PMP's fast die control holds the average die + * temperature at fast-die-ctrl-ts-avg-temp (100 C) and the + * hottest die sensor at the fast-die-ctrl-loop target + * (110 C). Power consumers shed performance from the first + * and hold their lowest state at the second. + */ + apple,soc-die-passive-millicelsius = <100000>; + apple,soc-die-hot-millicelsius = <110000>; apple,thermal-pressure-key = "mTPL"; /* CPU die temperatures, first: thermal zones index them. */ diff --git a/arch/arm64/boot/dts/apple/t8132-dcp.dtsi b/arch/arm64/boot/dts/apple/t8132-dcp.dtsi index b4383741a15fb9..b50f371e31fb9c 100644 --- a/arch/arm64/boot/dts/apple/t8132-dcp.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-dcp.dtsi @@ -70,6 +70,7 @@ iommus = <&dcp_dart 23>; power-domains = <&ps_disp_cpu>; dma-noncoherent; + apple,bw-scratch = <&pmgr_dcp 0 4 0>; status = "disabled"; disp0_piodma: piodma { @@ -79,6 +80,18 @@ }; }; + /* + * The internal pipe's realtime bandwidth request slot in the PMC, 0x20000 + * into the window the DCP has as disp-4: bandwidth agent 0, the one the + * ADT's disp0 bw_req interrupt names (agents are 0x4000 apart from + * 0x20000; the dcpexts' agents 3 and 4 are pmgr_dcpext's slots). + */ + pmgr_dcp: power-management@382820000 { + reg = <0x3 0x82820000 0x0 0x8>; + reg-names = "dcp-bw-scratch"; + #apple,bw-scratch-cells = <3>; + }; + /* The scanout frontend; it has no registers of its own. */ display: display-subsystem { compatible = "apple,t8132-display-subsystem", "apple,t8132-display-diagnostics"; diff --git a/arch/arm64/boot/dts/apple/t8132-j604.dts b/arch/arm64/boot/dts/apple/t8132-j604.dts index e7d6be18925562..867c2c0c287c48 100644 --- a/arch/arm64/boot/dts/apple/t8132-j604.dts +++ b/arch/arm64/boot/dts/apple/t8132-j604.dts @@ -199,7 +199,7 @@ label = "USB-C Left Rear"; }; -/* hpm3 is ATC3's port controller; hpm5, the MagSafe port's, is not wired. */ +/* hpm3 is ATC3's port controller. The MagSafe port's, hpm5, is in t8132-laptop.dtsi. */ &nub_spmi_a1 { status = "okay"; @@ -266,7 +266,6 @@ }; &dwc3_3 { - dr_mode = "host"; maximum-speed = "super-speed"; phys = <&atcphy3 PHY_TYPE_USB2>, <&atcphy3 PHY_TYPE_USB3>; phy-names = "usb2-phy", "usb3-phy"; @@ -327,10 +326,6 @@ multi-touch { firmware-name = "apple/tpmtfw-j604.bin"; }; - - /* J604 ADT /arm-io/dockchannel-mtp/mtp-transport/actuator: Force Touch */ - actuator { - }; }; /* diff --git a/arch/arm64/boot/dts/apple/t8132-j623-j624.dtsi b/arch/arm64/boot/dts/apple/t8132-j623-j624.dtsi index ec07e49b3da468..63a530d946dd8c 100644 --- a/arch/arm64/boot/dts/apple/t8132-j623-j624.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-j623-j624.dtsi @@ -91,3 +91,23 @@ &avd { status = "okay"; }; + +/* + * ADT /arm-io/spi4/dp855: the panel timing controller. The J623 and J624 + * ADTs give the same chip select as the M4 laptops (spi4 function-spi_cs0, + * GPIO 76). i2c-dp855 reads the panel management devices behind it and + * shares its I2C engine with the display firmware through the controller's + * lock. + */ +&spi4 { + cs-gpios = <&pinctrl_ap 76 GPIO_ACTIVE_LOW>; + status = "okay"; + + panel-timing-controller@0 { + compatible = "parade,dp855"; + reg = <0>; + spi-max-frequency = <1000000>; + spi-cs-setup-delay-ns = <20>; + spi-cs-hold-delay-ns = <20>; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8132-j624.dts b/arch/arm64/boot/dts/apple/t8132-j624.dts index 042e9a66cbf4e5..69e0ae99ce818d 100644 --- a/arch/arm64/boot/dts/apple/t8132-j624.dts +++ b/arch/arm64/boot/dts/apple/t8132-j624.dts @@ -135,7 +135,6 @@ }; &dwc3_2 { - dr_mode = "host"; maximum-speed = "super-speed"; phys = <&atcphy2 PHY_TYPE_USB2>, <&atcphy2 PHY_TYPE_USB3>; phy-names = "usb2-phy", "usb3-phy"; @@ -179,7 +178,6 @@ }; &dwc3_3 { - dr_mode = "host"; maximum-speed = "super-speed"; phys = <&atcphy3 PHY_TYPE_USB2>, <&atcphy3 PHY_TYPE_USB3>; phy-names = "usb2-phy", "usb3-phy"; diff --git a/arch/arm64/boot/dts/apple/t8132-j713-j715.dtsi b/arch/arm64/boot/dts/apple/t8132-j713-j715.dtsi index 28e1d62a4a64da..2e135f45e7e1b2 100644 --- a/arch/arm64/boot/dts/apple/t8132-j713-j715.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-j713-j715.dtsi @@ -53,6 +53,7 @@ /* The radio's firmware island: the J713's here, the J715 overrides it. */ &wifi0 { brcm,board-type = "apple,garden"; + wakeup-source; }; &bluetooth0 { @@ -131,6 +132,15 @@ status = "okay"; }; +/* The SIO itself is described for every M4 Mac in t8132-sio.dtsi. */ +&ps_sio_cpu { + status = "okay"; +}; + +&ps_dpa_p { + status = "okay"; +}; + /* The J713's full 2560x1664 panel including the notch rows, 224 ppi. */ &dcp { apple,panel-width-mm = <290>; @@ -357,10 +367,10 @@ }; /* - * t8132-j713-pmgr.dtsi disables SCODEC and SIO_CPU, and their engines with - * them. Their DARTs, which name those states in t8132-peripherals.dtsi, would - * wait for them forever if anything enabled them, so drop the reference here. - * VENC is enabled there: the video encoder and its DARTs below. + * t8132-j713-pmgr.dtsi disables SCODEC, and its engines with it. Their DARTs, + * which name those states in t8132-peripherals.dtsi, would wait for them + * forever if anything enabled them, so drop the reference here. VENC is + * enabled there: the video encoder and its DARTs below. */ &dart_ave2 { /delete-property/ power-domains; @@ -370,10 +380,6 @@ /delete-property/ power-domains; }; -&dart_sio0 { - /delete-property/ power-domains; -}; - /* The video encoder; t8132-j713-pmgr.dtsi enables its VENC states. */ &dart_ave0 { status = "okay"; diff --git a/arch/arm64/boot/dts/apple/t8132-j713-pmgr.dtsi b/arch/arm64/boot/dts/apple/t8132-j713-pmgr.dtsi index 515fd982909895..36798a86d0eabf 100644 --- a/arch/arm64/boot/dts/apple/t8132-j713-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-j713-pmgr.dtsi @@ -220,8 +220,9 @@ status = "disabled"; }; +/* spi4 carries the DP855 panel controller (t8132-laptop.dtsi). */ &ps_spi4 { - status = "disabled"; + status = "okay"; }; &ps_trace_fab { diff --git a/arch/arm64/boot/dts/apple/t8132-j713.dts b/arch/arm64/boot/dts/apple/t8132-j713.dts index 440ecff14d4a1e..57c761674b0b44 100644 --- a/arch/arm64/boot/dts/apple/t8132-j713.dts +++ b/arch/arm64/boot/dts/apple/t8132-j713.dts @@ -193,8 +193,40 @@ apple,clock-protection = <&ps_prot 8>; }; +/* + * The words the firmware-27 stop of the internal DCP writes (by default, see + * dcp_s2r_layout_from_dt()), the same ones the deep sleep lowers: pmc-dcp, the PMGR + * power states and its power gate block. + */ +&soc { + dcp_power: display-power@3828a9c14 { + compatible = "apple,t8132-display-power"; + reg = <0x3 0x828a9c14 0x0 0x4>, + <0x3 0x80700000 0x0 0x14000>, + <0x3 0x80724000 0x0 0x2000>; + reg-names = "pmc-dcp", "ps", "pwrgate"; + }; +}; + +/* Clock-protection slice 42 (ADT dart-dcp): it guards DISP_CPU's power state. */ +&dcp_dart { + reg = <0x3 0x0a340000 0x0 0x20000>, + <0x3 0x8079cb80 0x0 0x4>; + reg-names = "dart", "gapf"; +}; + &dcp { apple,pmc-interface = <&pmc_disp0>; + apple,display-power = <&dcp_power>; + + panel: panel { + compatible = "apple,panel-j713", "apple,panel"; + /* 2560x1664 at 224 ppi; 64 notch rows above the desktop. */ + width-mm = <290>; + height-mm = <189>; + adj-height-mm = <181>; + apple,max-brightness = <500>; + }; }; /* diff --git a/arch/arm64/boot/dts/apple/t8132-j773g.dts b/arch/arm64/boot/dts/apple/t8132-j773g.dts index baf3e3ffcfecb9..fc0aec6118e651 100644 --- a/arch/arm64/boot/dts/apple/t8132-j773g.dts +++ b/arch/arm64/boot/dts/apple/t8132-j773g.dts @@ -4,7 +4,8 @@ * * target-type: J773g * - * Wired from the J773g ADT (macOS 26.6.2). + * Wired from the J773g ADT (macOS 26.6.2; the HDMI port on dcpext0 from the + * macOS 27.2 one). * * Copyright The Asahi Linux Contributors */ @@ -43,6 +44,117 @@ power-domains = <&ps_dispext0_fe>, <&ps_dptx_phy>; }; +/* + * The HDMI port as macOS 27.2 drives it: from dispext0 alone (4K60, and + * 4K120 with DSC; the main DCP started and then parked), through the LPDPTX + * PHY and the PS190 DP-to-HDMI converter. It is the M4 Max Mac Studio's HDMI + * port (t6041-j575c-hdmi.dtsi): the same PHY block, converter and rails, and + * it is handed over the same way, on the firmware-27 backend. + * + * Every node is disabled. On macOS 27.2 the boot loader (aura) fills + * dcpext0's firmware memory and firmware clocks, leaves the main DCP running + * idle, and enables the display subsystem on iBoot's framebuffer; the display + * gate (drivers/soc/apple/display-gate.c) then enables this chain and points + * the display subsystem at dispext0's DART. On the M4 26.6.2 firmware path + * none of it is enabled from here. + */ +/ { + reserved-memory { + /* Filled by the boot loader on macOS 27.2, as the J575c's. */ + dcpext0_text: dcpext0-text { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + + dcpext0_data: dcpext0-data { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + + dcpext0_heap: dcpext0-heap { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + }; +}; + +&soc { + /* + * ADT /arm-io/dptx-phy (dptx-phy,t8132, as the J575c's lpdptx-phy0): + * the T6050 layout, a core bank and a dptx bank, and the ADT's PLL + * calibration (FD0FD1SWAP unset). The display crossbar's dfp-endpoint 4 + * (lpdptx); dispext0 is its ufp-endpoint 0, which the PHY's source + * select takes as 1, dcpext0's apple,dcp-index. + */ + lpdptx_phy: phy@39a700000 { + compatible = "apple,t8132-dptx-phy", "apple,t6050-dptx-phy"; + reg = <0x3 0x9a700000 0x0 0x4000>, + <0x3 0x9a740000 0x0 0x10000>; + reg-names = "core", "dptx"; + power-domains = <&ps_dptx_phy>; + #phy-cells = <0>; + #reset-cells = <0>; + apple,ufp-endpoint = <0>; + apple,pll-dcocfg = <0x4>; + apple,pll-dtcvreg = <0xf>; + apple,pll-dtccal = <0x2>; + apple,pll-dcdadj = <0x10>; + apple,pll-dlfcfg = <0x3>; + apple,pll-rodcoroleakcomp = <0x0>; + status = "disabled"; + }; +}; + +/* + * No PMP runs off the M4 firmware path, and iBoot leaves DISPEXT0 powered + * with its CPU domain under hardware control: as on the J575c, the pipe has + * no power domain here, and Linux never switches it. Its front end (and + * through it DISPEXT0_SYS) is held by the boot framebuffer only: keep it on + * once the display driver has taken over, or the domain would be powered off + * under the running processor. + */ +&ps_dispext0_fe { + apple,always-on; +}; + +&dcpext0_mbox { + /delete-property/ power-domains; +}; + +&dcpext0_dart { + /delete-property/ power-domains; +}; + +&dispext0_dart { + /delete-property/ power-domains; +}; + +/* + * ADT /arm-io/dp2hdmi-gpio0: hdmi_hpd on AOP GPIO 41, hdmi_pwr_en on SMC + * gP0f and dp2hdmi_pwr_en on SMC gP1a (the J575c's rails). No Type-C route: + * dcpext0 drives only this port. + */ +&dcpext0 { + /delete-property/ power-domains; + apple,iomfb-surfaces = <1 1 0 0>; + apple,connector-type = "HDMI-A"; + hdmi-hpd-gpios = <&pinctrl_aop 41 GPIO_ACTIVE_HIGH>; + hdmi-pwren-gpios = <&smc_gpio 15 GPIO_ACTIVE_HIGH>; + dp2hdmi-pwren-gpios = <&smc_gpio 26 GPIO_ACTIVE_HIGH>; + phys = <&lpdptx_phy>; + phy-names = "dp-phy"; + /* the crossbar's output 4 (ADT dptx-phy dp-switch-dfp-endpoint) */ + apple,dptx-phy = <4>; + memory-region = <&dcpext0_text>, <&dcpext0_data>, <&dcpext0_heap>; + memory-region-names = "text", "data", "heap"; +}; + /* * Without this, the PMP firmware faults in the PMC block (0x382800000) * shortly after it starts on this board. J713 keeps ps_pmc out of Linux @@ -155,7 +267,6 @@ }; &dwc3_3 { - dr_mode = "host"; maximum-speed = "super-speed"; phys = <&atcphy3 PHY_TYPE_USB2>, <&atcphy3 PHY_TYPE_USB3>; phy-names = "usb2-phy", "usb3-phy"; @@ -260,6 +371,23 @@ brcm,board-type = "apple,sakhalin"; }; +/* + * This Mac hands its radio DART over unconfigured: every stream translates + * with no valid root and none is enabled. The managed radio contract only + * admits a SID16 left in its static bypass or disabled, so the DART would + * refuse the handover (-EBUSY) and port 0 would never probe. Linux owns the + * radio DART and trains port 0 itself instead. + */ +&dart_apcie0 { + /delete-property/ apple,managed-sids; + /delete-property/ apple,sid16-page; + /delete-property/ apple,dma-range; +}; + +&pcie0 { + /delete-property/ apple,managed-sids; +}; + #include "hwmon-common.dtsi" #include "hwmon-mini.dtsi" diff --git a/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi b/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi index 3f378b1ffc1cc4..f9cd8d3bd23663 100644 --- a/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi @@ -184,6 +184,20 @@ smc_hwmon: hwmon { compatible = "apple,smc-hwmon"; + /* + * The CPU die sensors of the M4. The SMC reports each in a key + * triplet; the middle key is listed, as on M3: under load it + * tracks the PMP's die hotspot within about 2 C, while the + * first key reads 8-11 C lower. E cluster: Te05 Te09 Te0H Te0S; + * P cluster: Tp01 ... Tp1R. The GPU (Tg) keys are left out: + * they hold a fixed placeholder while Linux drives the GPU. + * Keys the running SMC lacks are skipped at probe. + */ + apple,soc-die-keys = "Te05", "Te09", "Te0H", "Te0S", + "Tp01", "Tp05", "Tp09", "Tp0D", "Tp0V", + "Tp0Y", "Tp0b", "Tp0e", "Tp1B", "Tp1F", + "Tp1R"; + apple,thermal-pressure-key = "mTPL"; }; smc_rtc: rtc { @@ -362,7 +376,6 @@ }; &dwc3_0 { - dr_mode = "host"; maximum-speed = "super-speed"; phys = <&atcphy0 PHY_TYPE_USB2>, <&atcphy0 PHY_TYPE_USB3>; phy-names = "usb2-phy", "usb3-phy"; @@ -416,7 +429,6 @@ }; &dwc3_1 { - dr_mode = "host"; maximum-speed = "super-speed"; phys = <&atcphy1 PHY_TYPE_USB2>, <&atcphy1 PHY_TYPE_USB3>; phy-names = "usb2-phy", "usb3-phy"; @@ -443,6 +455,15 @@ &dart_apcie0 { apple,managed-sids = <1 2>; apple,dma-range = <0x100 0x00100000 0x0 0x3fe00000>; + /* + * Limit the static SID16 stream to this SoC MMIO page instead of + * keeping it in bypass. 0x381204000 sits 0x38000 bytes past aic's + * core window (0x381000000 + 0x1cc000) and below DRAM; no DT node + * claims it, so its owning SoC block is not identified in the DT yet. + * Blocking SID16 on J713 faulted on writes to this page within + * seconds, and J715 uses the same page with 0 faults. + */ + apple,sid16-page = /bits/ 64 <0x381204000>; status = "okay"; }; diff --git a/arch/arm64/boot/dts/apple/t8132-laptop.dtsi b/arch/arm64/boot/dts/apple/t8132-laptop.dtsi index 0e33ff67f6cffa..9b2a664fa41177 100644 --- a/arch/arm64/boot/dts/apple/t8132-laptop.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-laptop.dtsi @@ -141,6 +141,15 @@ stm { }; + + /* + * Force Touch: the trackpad's haptic engine, ADT + * /arm-io/dockchannel-mtp/mtp-transport/actuator on every M4 laptop. + * Without it the click stays firmware-driven and there is no Force + * Touch stage. + */ + actuator { + }; }; /* Mesa fingerprint sensor: power on nub GPIO 28, data-ready on AP GPIO 199. */ @@ -156,3 +165,42 @@ spi-cs-hold-delay-ns = <20>; status = "okay"; }; + +/* + * The MagSafe 3 port's PD controller, on nub-spmi-a0 next to ATC0 and ATC1's + * (SID 8, port-type 0x11, the same in each laptop's ADT). It has no USB data + * path, so it gets no connector node; tipd registers a Type-C port and a power + * supply for it. Its event, sleep and wake interrupts are 63, 69 and 71 in the + * same order as hpm0's. Its ADT features-supported is <3>, "Power In" only: no + * liquid detection. + */ +&nub_spmi_a0 { + hpm5: usb-pd@8 { + compatible = "apple,t8132-sn201202x", "apple,sn201202x"; + reg = <0x8 SPMI_USID>; + interrupts = <63 IRQ_TYPE_EDGE_RISING>, + <69 IRQ_TYPE_EDGE_RISING>, + <71 IRQ_TYPE_EDGE_RISING>; + interrupt-names = "irq", "sleep", "wake"; + apple,no-liquid-detection; + }; +}; + +/* + * ADT /arm-io/spi4/dp855: the panel timing controller, chip select from the + * spi4 function-spi_cs0 (the same pin on the J604 and J713). i2c-dp855 reads + * the panel management devices behind it and shares its I2C engine with the + * display firmware through the controller's lock. + */ +&spi4 { + cs-gpios = <&pinctrl_ap 76 GPIO_ACTIVE_LOW>; + status = "okay"; + + panel_controller: panel-timing-controller@0 { + compatible = "parade,dp855"; + reg = <0>; + spi-max-frequency = <1000000>; + spi-cs-setup-delay-ns = <20>; + spi-cs-hold-delay-ns = <20>; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi b/arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi index 2554025a5ca137..39e11e001052e7 100644 --- a/arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi @@ -1,5 +1,9 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT -/* Unclaimed T8132 peripheral buses. */ +/* + * Unclaimed T8132 peripheral buses. The SPI controllers run from the 24 MHz + * reference like every other Apple SPI controller: no driver provides + * peripheral_clocks, and spi-apple needs a clock rate to divide. + */ &soc { spi4: spi@3ad110000 { @@ -7,7 +11,7 @@ reg = <0x3 0xad110000 0 0x4000>; interrupt-parent = <&aic>; interrupts = ; - clocks = <&peripheral_clocks 422>; + clocks = <&clkref>; power-domains = <&ps_spi4>; #address-cells = <1>; #size-cells = <0>; @@ -42,6 +46,7 @@ status = "disabled"; }; + /* ADT /arm-io/nub-spmi1: the auxiliary PMU (pmu-aux) at USID 0xe. */ nub_spmi1: spmi@388614000 { compatible = "apple,t8132-spmi", "apple,t8103-spmi"; reg = <0x3 0x88614000 0 0x4000>, @@ -53,7 +58,12 @@ #interrupt-cells = <2>; #address-cells = <2>; #size-cells = <0>; - status = "disabled"; + + pmic@e { + compatible = "apple,club-pmic", "apple,spmi-nvmem"; + reg = <0xe SPMI_USID>; + read-only; + }; }; aop_spmi1: spmi@390b14000 { @@ -75,7 +85,7 @@ reg = <0x3 0xad10c000 0 0x4000>; interrupt-parent = <&aic>; interrupts = ; - clocks = <&peripheral_clocks 421>; + clocks = <&clkref>; power-domains = <&ps_spi3>; #address-cells = <1>; #size-cells = <0>; diff --git a/arch/arm64/boot/dts/apple/t8132-sio.dtsi b/arch/arm64/boot/dts/apple/t8132-sio.dtsi index 09861ddb281830..ba5d3815d452bb 100644 --- a/arch/arm64/boot/dts/apple/t8132-sio.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-sio.dtsi @@ -1,5 +1,16 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT -/* T8132 SIO resources; channel layout and firmware regions require loader support. */ +/* + * T8132 SIO resources. iBoot preloads the SIO firmware; the boot loader + * reserves it, publishes the boot tables (T6041 layout) and enables the SIO + * node, which it finds by the alias. Without such a loader the SIO stays + * disabled and nothing else changes. + */ + +/ { + aliases { + sio = &sio; + }; +}; &soc { sio_mbox: mailbox@3ade08000 { @@ -14,14 +25,17 @@ "recv-empty", "recv-not-empty"; #mbox-cells = <0>; power-domains = <&ps_sio_cpu>; - status = "disabled"; + status = "okay"; }; sio: dma-controller@3ade00000 { compatible = "apple,t8132-sio", "apple,sio"; reg = <0x3 0xade00000 0x0 0x8000>, <0x3 0xad850000 0x0 0x4000>; + reg-names = "asc", "auxiliary"; #dma-cells = <1>; + /* Channel numbers run up to dp-audio2's 0x68, as on T8140. */ + dma-channels = <128>; mboxes = <&sio_mbox>; iommus = <&dart_sio0 0>; power-domains = <&ps_sio_cpu>; @@ -29,3 +43,22 @@ status = "disabled"; }; }; + +/* The boot tables sit in the window above the preloaded segments (ADT vm-base, vm-size). */ +&dart_sio0 { + apple,dma-range = <0x100 0x1c000 0x2ff 0xfffe4000>; + status = "okay"; +}; + +/* + * The SIO firmware drives the SPI, UART and DP audio shims, so keep their + * parents on while it runs, as on T6041 and T8140. + */ +&ps_sio_cpu { + power-domains = <&ps_spi_p>, <&ps_uart_p>, <&ps_dpa_p>; + status = "okay"; +}; + +&ps_dpa_p { + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t8132-usb4.dtsi b/arch/arm64/boot/dts/apple/t8132-usb4.dtsi index be35c15c9e9ba0..7a800738401f8f 100644 --- a/arch/arm64/boot/dts/apple/t8132-usb4.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-usb4.dtsi @@ -77,13 +77,18 @@ nonposted-mmio; status = "disabled"; + /* + * No power-domains: the router populates its DART after it has powered + * its own states, and the native CIO sleep powers them off with the DART + * saved. A DART in ps_atc0_cio would hold that state on through the + * NHI's noirq suspend (it suspends after the NHI), and the sleep fails. + */ usb4_0_dart: iommu@a80000 { compatible = "apple,t8132-dart", "apple,t8110-dart"; reg = <0xa80000 0x20000>; interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <5>; - power-domains = <&ps_atc0_cio>; }; usb4_0_nhi: nhi@f00000 { @@ -194,13 +199,18 @@ nonposted-mmio; status = "disabled"; + /* + * No power-domains: the router populates its DART after it has powered + * its own states, and the native CIO sleep powers them off with the DART + * saved. A DART in ps_atc1_cio would hold that state on through the + * NHI's noirq suspend (it suspends after the NHI), and the sleep fails. + */ usb4_1_dart: iommu@a80000 { compatible = "apple,t8132-dart", "apple,t8110-dart"; reg = <0xa80000 0x20000>; interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <5>; - power-domains = <&ps_atc1_cio>; }; usb4_1_nhi: nhi@f00000 { diff --git a/arch/arm64/boot/dts/apple/t8140-j700.dts b/arch/arm64/boot/dts/apple/t8140-j700.dts index b20146bb491516..940431d7aac3bb 100644 --- a/arch/arm64/boot/dts/apple/t8140-j700.dts +++ b/arch/arm64/boot/dts/apple/t8140-j700.dts @@ -47,11 +47,6 @@ #size-cells = <2>; ranges; stdout-path = "serial0"; - /* - * Temporary: the secondary cores lose state in WFIT and the - * kernel does not yet stop using WFxT on T8140 by itself. - */ - bootargs = "arm64.nowfxt"; framebuffer0: framebuffer@0 { compatible = "apple,simple-framebuffer", "simple-framebuffer"; diff --git a/arch/arm64/boot/dts/apple/t8142-j704-audio.dtsi b/arch/arm64/boot/dts/apple/t8142-j704-audio.dtsi new file mode 100644 index 00000000000000..72ef40e339647a --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8142-j704-audio.dtsi @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * Apple MacBook Pro (14-inch, M5) J704: sound through the AOP firmware, the + * headphone jack and the microphone array only. + * + * The J704 ADT matches J813's audio wiring: the AOP (ascwrap-v6, mailbox + * IRQs 490-493), dart-aop, admac-base-ns (IRQ 549) and admac-leap-s + * (IRQ 551) at the same addresses, the CS42L84 jack codec at i2c1 0x4b + * (IRQ AP pin 100, reset nub pin 18) and the three-microphone "audio-hp-mic" + * LEAP stream. So this reuses J813's description, as J815 does. + * + * The speakers are six SN012776 on i2c3 (0x38-0x3d), but in a different + * order than J815's (ADT: 0x39 left woofer 2, 0x3a left tweeter, 0x3c right + * woofer 2, 0x3d right tweeter). Until their slots and a speaker protection + * profile are verified, neither the amplifiers nor their i2c3 bus are + * described: their driver never binds and Linux never configures them. Their + * shutdown (SDZ) line is not described either, so they keep the state iBoot + * left them in; with no speaker link there is no bit clock, so they cannot play. + */ + +#include "t8142-j813-audio.dtsi" + +&aop_audio { + /* The microphone card's name: AppleJ704HPAI. */ + apple,chassis-name = "J704"; + apple,machine-kind = "MacBook Pro"; +}; + +/delete-node/ &speaker_left_woofer; +/delete-node/ &speaker_left_tweeter; +/delete-node/ &speaker_right_woofer; +/delete-node/ &speaker_right_tweeter; +/* Nothing else is on the speakers' bus. */ +/delete-node/ &i2c3; + +/ { + sound { + compatible = "apple,j704-macaudio", "apple,macaudio"; + model = "MacBook Pro J704"; + + /delete-node/ dai-link@1; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8142-j704-pcie.dtsi b/arch/arm64/boot/dts/apple/t8142-j704-pcie.dtsi index a0694d50645556..9b65f408c43de1 100644 --- a/arch/arm64/boot/dts/apple/t8142-j704-pcie.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j704-pcie.dtsi @@ -1,11 +1,16 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT /* - * Internal PCIe: BCM4388 Wi-Fi/Bluetooth on apcie port 0 and the GL9755 SD - * card reader on port 2. As on J813, the bootloader trains the links and - * Linux uses the root ports as a generic ECAM host that owns the DARTs and - * the endpoints. Nothing programs the ports' RID-to-SID tables, so every - * function uses stream zero of its port's DART. Ranges, MSI maps and DART - * IRQs are from the J704 ADT; port 0 matches J813. + * Internal PCIe: BCM4388 Wi-Fi/Bluetooth on apcie port 0. As on J813, the + * bootloader trains the link and Linux uses the root port as a generic ECAM + * host that owns the DART and the endpoints. Nothing programs the port's + * RID-to-SID table, so both functions use stream zero of the port's DART. + * Ranges, the MSI map and the DART IRQ are from the J704 ADT; port 0 + * matches J813. + * + * The GL9755 SD card reader sits on port 2 (ADT pci-bridge2, bus 2, MSI map + * at 0x48a028000, pcie2_dart). The bootloader trains port 0 only, so the + * ECAM window and the MSI controller stop at port 0 until port 2 is + * trained too. */ &{/} { @@ -14,15 +19,18 @@ device_type = "pci"; #address-cells = <3>; #size-cells = <2>; - bus-range = <0 2>; - reg = <0x1c 0xb0000000 0 0x300000>; + bus-range = <0 1>; + reg = <0x1c 0xb0000000 0 0x200000>; ranges = <0x43000000 0xb 0xc0000000 0xb 0xc0000000 0 0x20000000>, <0x02000000 0 0x80000000 0xb 0x80000000 0 0x40000000>; dma-coherent; msi-parent = <&pcie0_msi>; + /* + * Port 2's root port (00:02.0) still enumerates on bus 0 and has no + * entry here, so "no iommu-map translation for id 0x10" is expected. + */ iommu-map = <0x100 &pcie0_dart 0 1>, - <0x101 &pcie0_dart 0 1>, - <0x200 &pcie2_dart 0 1>; + <0x101 &pcie0_dart 0 1>; port00: pci@0,0 { device_type = "pci"; @@ -49,34 +57,17 @@ local-bd-address = [00 00 00 00 00 00]; }; }; - - port02: pci@2,0 { - device_type = "pci"; - reg = <0x1000 0x0 0x0 0x0 0x0>; - bus-range = <2 2>; - #address-cells = <3>; - #size-cells = <2>; - ranges; - - sdhci0: mmc@0,0 { - compatible = "pci17a0,9755"; - reg = <0x20000 0x0 0x0 0x0 0x0>; - cd-inverted; - wp-inverted; - }; - }; }; }; &{/soc} { /* - * The MSI maps of ports 0 and 2. They share the root complex's AIC - * range (ADT msi-vector-offset 1741); 32 vectors are enough for both. + * Port 0's MSI map (ADT msi-vector-offset 1741, port 0 owns the first + * 32 vectors). */ pcie0_msi: msi-controller@488028000 { compatible = "apple,t8142-pcie-msi"; - reg = <0x4 0x88028000 0x0 0x8000>, - <0x4 0x8a028000 0x0 0x8000>; + reg = <0x4 0x88028000 0x0 0x8000>; msi-controller; msi-ranges = <&aic AIC_IRQ 1741 IRQ_TYPE_EDGE_RISING 32>; }; @@ -85,7 +76,3 @@ &pcie0_dart { status = "okay"; }; - -&pcie2_dart { - status = "okay"; -}; diff --git a/arch/arm64/boot/dts/apple/t8142-j704-usb.dtsi b/arch/arm64/boot/dts/apple/t8142-j704-usb.dtsi index 09c51e0888aa2f..fac15e4d4099f2 100644 --- a/arch/arm64/boot/dts/apple/t8142-j704-usb.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j704-usb.dtsi @@ -77,7 +77,7 @@ compatible = "usb-c-connector"; label = "USB-C Left-front"; power-role = "dual"; - data-role = "host"; + data-role = "dual"; ports { #address-cells = <1>; @@ -106,7 +106,7 @@ reg = <4 0x02280000 0 0xcd00>, <4 0x0228cd00 0 0x4b00>; reg-names = "dwc3-core", "dwc3-apple"; interrupts = ; - dr_mode = "host"; + dr_mode = "otg"; usb-role-switch; role-switch-default-mode = "host"; iommus = <&dwc3_0_dart 0>, <&dwc3_0_dart_1 1>; @@ -213,7 +213,7 @@ compatible = "usb-c-connector"; label = "USB-C Left-rear"; power-role = "dual"; - data-role = "host"; + data-role = "dual"; ports { #address-cells = <1>; @@ -243,7 +243,7 @@ reg = <4 0x0a280000 0 0xcd00>, <4 0x0a28cd00 0 0x4b00>; reg-names = "dwc3-core", "dwc3-apple"; interrupts = ; - dr_mode = "host"; + dr_mode = "otg"; usb-role-switch; role-switch-default-mode = "host"; iommus = <&dwc3_1_dart 0>, <&dwc3_1_dart_1 1>; @@ -365,7 +365,7 @@ compatible = "usb-c-connector"; label = "USB-C Right"; power-role = "dual"; - data-role = "host"; + data-role = "dual"; ports { #address-cells = <1>; @@ -394,7 +394,7 @@ reg = <4 0x1a280000 0 0xcd00>, <4 0x1a28cd00 0 0x4b00>; reg-names = "dwc3-core", "dwc3-apple"; interrupts = ; - dr_mode = "host"; + dr_mode = "otg"; usb-role-switch; role-switch-default-mode = "host"; iommus = <&dwc3_3_dart 0>, <&dwc3_3_dart_1 1>; diff --git a/arch/arm64/boot/dts/apple/t8142-j704.dts b/arch/arm64/boot/dts/apple/t8142-j704.dts index 3e775c37b29764..a4dafe5edee64f 100644 --- a/arch/arm64/boot/dts/apple/t8142-j704.dts +++ b/arch/arm64/boot/dts/apple/t8142-j704.dts @@ -326,3 +326,4 @@ #include "t8142-j704-pcie.dtsi" #include "t8142-j704-power.dtsi" #include "t8142-j704-hwmon.dtsi" +#include "t8142-j704-audio.dtsi" diff --git a/arch/arm64/boot/dts/apple/t8142-j813-audio.dtsi b/arch/arm64/boot/dts/apple/t8142-j813-audio.dtsi index c345bc3ff50acd..9bcdf37f2c60ea 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813-audio.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j813-audio.dtsi @@ -6,8 +6,8 @@ * runs the MCA serializers: "cout"/"cin" (CS42L84 headphone jack) on * admac-base-ns TX2/RX2 and "spkr" (four SN012776) on TX0, their V/I sense * on RX0 (ADT iop-audio-controller; RX1 is the firmware's speaker tap). - * The AOP itself is laid out like T8140's (ascwrap-v6, asc-mailbox-v4), - * including the setup port. + * The AOP core, its mailboxes and dart-aop are shared by every T8142 board + * (t8142-peripherals.dtsi); this file adds only its audio service. * Addresses are from the J813 ADT (arm-io offset 0x210000000). */ @@ -172,45 +172,6 @@ }; }; - aop_mbox: mailbox@390608000 { - compatible = "apple,t8142-asc-mailbox", "apple,asc-mailbox-v4"; - reg = <0x3 0x90608000 0x0 0x4000>; - interrupt-parent = <&aic>; - interrupts = , - , - , - ; - interrupt-names = "send-empty", "send-not-empty", - "recv-empty", "recv-not-empty"; - #mbox-cells = <0>; - }; - - /* - * The ADT's aop-exclave-mailbox, flagged exclave-assigned as on T8140, - * is the AOP setup port the host drives. Its ADT reg (0x3d067c000) is - * not behind the arm-io translation: AOP ASC + 0x4007c000, as on - * T8140. ADT interrupts [497, 494], T8140's +100. - */ - aop_setup_mbox: mailbox@3d067c000 { - compatible = "apple,t8142-aop-setup-mailbox", "apple,t8140-aop-setup-mailbox"; - reg = <0x3 0xd067c000 0x0 0x4000>; - interrupt-parent = <&aic>; - interrupts = , - ; - interrupt-names = "send-empty", "recv-not-empty"; - /* dart-aop stream 1: ADT vm-base-1 0x20000000000, as on T8140. */ - iommus = <&aop_dart 1>; - apple,dma-range = <0x200 0x0 0x10 0x0>; - #mbox-cells = <0>; - }; - - /* - * dart-aop: streams 0 (AOP), 3, 8 (admac-base-ns), 10 and 16 are the - * AP's; 1, 9 and 11 are exclave streams, of which the host drives 1 - * (setup port) and 11 (admac-leap-s) on the raw boot. As on T8140, the - * firmware's own mappings own the first slot, host buffers go above it. - */ - admac_base_ns: dma-controller@393800000 { compatible = "apple,t8140-admac"; reg = <0x3 0x93800000 0x0 0x34000>; @@ -330,37 +291,28 @@ ti,bclk-ratio = <250>; }; }; +}; - aop: aop@390c00000 { - compatible = "apple,t8142-aop", "apple,t8152-aop"; - reg = <0x3 0x90c00000 0x0 0x1e0000>, - <0x3 0x90600000 0x0 0x4000>; - reg-names = "mmio", "asc"; - mboxes = <&aop_mbox>, <&aop_setup_mbox>; - mbox-names = "mbox", "setup"; - iommus = <&aop_dart 0>; - apple,dma-range = <0x110 0x0 0x10 0x0>; - - aop_audio: audio { - compatible = "apple,t8142-aop-audio", "apple,t8152-aop-audio"; - /* The microphone card's name: AppleJ813HPAI. */ - apple,chassis-name = "J813"; - apple,machine-kind = "MacBook Air"; - /* hpai: leap-s RX0 (Linux channel 1, odd = DEV_TO_MEM). */ - dmas = <&admac_base_ns 4>, <&admac_base_ns 5>, - <&admac_base_ns 0>, <&admac_base_ns 1>, - <&admac_leap_s 1>; - dma-names = "cout", "cin", "spkr", "sense", "hpai"; - power-domains = <&ps_audio_mca0_m>, <&ps_audio_mca1_m>, - <&ps_audio_mca2_m>, <&ps_audio_mca3_m>, - <&ps_audio_mca4_m>, <&ps_audio_mca5_m>, - <&ps_audio_leap_s_a>, <&ps_audio_leap_rx0>, - <&ps_audio_leap_mca>; - power-domain-names = "mca0", "mca1", "mca2", - "mca3", "mca4", "mca5", - "leap_s_a", "leap_rx0", "leap_mca"; - #sound-dai-cells = <1>; - }; +&aop { + aop_audio: audio { + compatible = "apple,t8142-aop-audio", "apple,t8152-aop-audio"; + /* The microphone card's name: AppleJ813HPAI. */ + apple,chassis-name = "J813"; + apple,machine-kind = "MacBook Air"; + /* hpai: leap-s RX0 (Linux channel 1, odd = DEV_TO_MEM). */ + dmas = <&admac_base_ns 4>, <&admac_base_ns 5>, + <&admac_base_ns 0>, <&admac_base_ns 1>, + <&admac_leap_s 1>; + dma-names = "cout", "cin", "spkr", "sense", "hpai"; + power-domains = <&ps_audio_mca0_m>, <&ps_audio_mca1_m>, + <&ps_audio_mca2_m>, <&ps_audio_mca3_m>, + <&ps_audio_mca4_m>, <&ps_audio_mca5_m>, + <&ps_audio_leap_s_a>, <&ps_audio_leap_rx0>, + <&ps_audio_leap_mca>; + power-domain-names = "mca0", "mca1", "mca2", + "mca3", "mca4", "mca5", + "leap_s_a", "leap_rx0", "leap_mca"; + #sound-dai-cells = <1>; }; }; @@ -408,7 +360,3 @@ }; }; }; - -&aop_dart { - status = "okay"; -}; diff --git a/arch/arm64/boot/dts/apple/t8142-j813-j815.dtsi b/arch/arm64/boot/dts/apple/t8142-j813-j815.dtsi index b420c702477e70..240a268da80d9e 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813-j815.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j813-j815.dtsi @@ -434,92 +434,6 @@ apple,ps-wr-dis-bit = <6>; }; -/* - * The video encoder, its two DARTs and the VENC power tree: ADT ave behind - * dart-ave (DART + CPUDART), the same addresses, interrupts and power states - * on both boards. The boot loader hands over iBoot's preloaded firmware - * (memory regions, CRCs in /chosen) or disables the encoder when the ADT has - * no preload. - */ -&ps_venc_sys { - status = "okay"; -}; - -&ps_venc_dma { - status = "okay"; -}; - -&ps_venc_pipe4 { - status = "okay"; -}; - -&ps_venc_pipe5 { - status = "okay"; -}; - -&ps_venc_me0 { - status = "okay"; -}; - -&ps_venc_me1 { - status = "okay"; -}; - -&ave_dart0 { - status = "okay"; -}; - -&ave_dart1 { - status = "okay"; -}; - -&ave { - status = "okay"; -}; - -/* - * The Neural Engine (ADT ane and dart-ane, the same on both boards). It stays - * off until the first request: the firmware is started then, from the preload, - * and system sleep cycles it cold. The boot loader hands the preload over by - * the engine's compatible, or disables the node when there is none. - */ -&ps_ane_sys { - status = "okay"; -}; - -&ane_dart0 { - status = "okay"; -}; - -&ane_dart1 { - status = "okay"; -}; - -&ane_dart2 { - status = "okay"; -}; - -&ane { - status = "okay"; -}; - -/* Both JPEG engines and their DART (ADT jpeg0, jpeg1, dart-jpeg). */ -&ps_jpg { - status = "okay"; -}; - -&jpeg_dart { - status = "okay"; -}; - -&jpeg0 { - status = "okay"; -}; - -&jpeg1 { - status = "okay"; -}; - /* * SIO AES engine, software keys only. It registers below the CPU's aes-ce, so * it is used only when asked for by driver name. diff --git a/arch/arm64/boot/dts/apple/t8142-j813-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8142-j813-peripherals.dtsi index a387343ee2610d..c9038be7707c14 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j813-peripherals.dtsi @@ -4,6 +4,7 @@ / { aliases { nvram = &nvram; + pmp = &pmp; }; /* J813 ADT /arm-io/qspi clock-ids [396]; rate as the T8140 QSPI. */ @@ -102,10 +103,11 @@ mbox-names = "mbox"; iommus = <&pmp_dart 0>; power-domains = <&ps_pmp>; - /* ADT /chosen board-id, dram-vendor-id */ - apple,board-id = <36>; - apple,dram-vendor-id = <1>; - /* ADT /arm-io/pmgr pmc, pmc-pmgr (registry-v2 boot arguments) */ + /* + * ADT /arm-io/pmgr pmc, pmc-pmgr (registry-v2 boot arguments). + * The loader adds apple,board-id, apple,dram-vendor-id and the + * apple,tunable-* values from this machine's ADT. + */ apple,pmc = <1>; apple,pmc-pmgr = <31>; }; @@ -163,7 +165,6 @@ #pwm-cells = <2>; }; }; -#include "t8142-j813-pmp-tunables.dtsi" &pmp_dart { apple,dma-range = /bits/ 64 <0x10000000000 0xbff00000>; diff --git a/arch/arm64/boot/dts/apple/t8142-j813-pmp-tunables.dtsi b/arch/arm64/boot/dts/apple/t8142-j813-pmp-tunables.dtsi deleted file mode 100644 index fa34d4d80fe7d3..00000000000000 --- a/arch/arm64/boot/dts/apple/t8142-j813-pmp-tunables.dtsi +++ /dev/null @@ -1,70 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0+ OR MIT -/* - * J813 PMP firmware properties: the ADT /arm-io/pmp/iop-pmp-nub values the - * firmware queries by name at boot (pmp.rs serves apple,tunable-). - * Generated from the J813 ADT by tools/adtnub.py; raw ADT bytes. - */ - -&pmp { - apple,tunable-agx-dcs-bw-constraint = [00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00]; - apple,tunable-mc_quota_req_ptd_count = [08 00 00 00]; - apple,tunable-mc_cmd_ptd_count = [02 00 00 00]; - apple,tunable-ane-dcs-bw-dvfs-filter = [ff ff 1f 00]; - apple,tunable-sochot-sensors = [01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05 00 00 00 06 00 00 00 07 00 00 00 08 00 00 00 09 00 00 00 0a 00 00 00 0b 00 00 00 0c 00 00 00 0d 00 00 00 0e 00 00 00 0f 00 00 00 10 00 00 00 11 00 00 00 12 00 00 00 13 00 00 00 14 00 00 00 15 00 00 00 16 00 00 00 17 00 00 00 18 00 00 00]; - apple,tunable-soc-ni3-bw-threshold = [cc 0c 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 26 00 01 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 25 00 00 00 00 00 00 00 00 00 00 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 8f 3d 00 00 00 00 00]; - apple,tunable-agx-af-rd-bw-threshold = [00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 35 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 34 00 00 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 00 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 00 00 00 00 00 00 3a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 39 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 2d 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 2c 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 12 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 11 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 0e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3c 00 00 00 00 00 00 00 0d 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 3b 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 7a 00 00 00 00 00 00 00 32 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 79 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 2c 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 5a 00 00 00 00 00 00 00 2b 00 06 00 00 00 00 00 8a 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 89 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1e 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3e 00 00 00 00 00 00 00 1d 00 06 00 00 00 00 00 6f 00 00 00 00 00 00 00 3d 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 6e 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 34 00 00 00 00 00 00 00 09 00 06 00 00 00 00 00 5a 00 00 00 00 00 00 00 33 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2c 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 41 00 00 00 00 00 00 00 2b 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 40 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 19 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3c 00 00 00 00 00 00 00 18 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 3b 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 19 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 37 00 00 00 00 00 00 00 18 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 36 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 14 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 32 00 00 00 00 00 00 00 13 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 31 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 14 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 32 00 00 00 00 00 00 00 13 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 31 00 06 00 00 00]; - apple,tunable-ane-af-bw-dvfs-filter = [ff ff 1f 00]; - apple,tunable-ans-af-bw-threshold = [70 3d 0c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 70 3d 0b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00 00 00 00 00 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 cc 0c 1c 00 00 00 00 00]; - apple,tunable-ptd-range = [01 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 50 54 44 2d 4e 55 4c 4c 00 00 00 00 00 00 00 00 02 00 00 00 01 00 00 00 01 00 00 00 0b 00 00 00 50 4d 50 2d 53 54 41 54 55 53 00 00 00 00 00 00 03 00 00 00 02 00 00 00 04 00 00 00 00 00 00 00 44 56 46 53 2d 53 54 41 54 45 00 00 00 00 00 00 04 00 00 00 06 00 00 00 04 00 00 00 00 00 00 00 50 4d 50 54 4f 4f 4c 00 00 00 00 00 00 00 00 00 05 00 00 00 98 00 00 00 08 00 00 00 00 00 00 00 50 4d 53 2d 50 4d 47 52 2d 50 4b 54 00 00 00 00 06 00 00 00 a0 00 00 00 08 00 00 00 00 00 00 00 50 4d 53 2d 44 50 45 2d 50 4b 54 00 00 00 00 00 07 00 00 00 28 02 00 00 18 00 00 00 00 00 00 00 50 4d 53 2d 44 45 56 43 2d 50 4b 54 00 00 00 00 09 00 00 00 a8 00 00 00 80 01 00 00 00 00 00 00 53 4f 43 2d 44 45 56 2d 50 4b 54 00 00 00 00 00 0a 00 00 00 27 00 00 00 08 00 00 00 00 00 00 00 53 4f 43 2d 44 45 56 2d 50 53 2d 52 45 51 00 00 0b 00 00 00 2f 00 00 00 08 00 00 00 00 00 00 00 53 4f 43 2d 44 45 56 2d 50 53 2d 41 43 4b 00 00 0c 00 00 00 37 00 00 00 10 00 00 00 00 00 00 00 53 4f 43 2d 44 45 56 2d 44 56 46 53 00 00 00 00 0d 00 00 00 47 00 00 00 0a 00 00 00 00 00 00 00 53 4f 43 2d 44 45 56 2d 42 57 52 00 00 00 00 00 0e 00 00 00 13 00 00 00 0a 00 00 00 00 00 00 00 4d 43 2d 44 52 56 2d 54 4f 2d 43 54 52 4c 00 00 0f 00 00 00 51 00 00 00 01 00 00 00 00 00 00 00 44 56 46 53 2d 43 45 49 4c 00 00 00 00 00 00 00 14 00 00 00 0a 00 00 00 01 00 00 00 00 00 00 00 41 56 44 2d 4e 52 47 00 00 00 00 00 00 00 00 00 15 00 00 00 0b 00 00 00 01 00 00 00 00 00 00 00 53 4f 43 2d 41 4f 4e 2d 4e 52 47 00 00 00 00 00 16 00 00 00 0c 00 00 00 01 00 00 00 00 00 00 00 53 4f 43 2d 52 45 53 54 2d 4e 52 47 00 00 00 00 1e 00 00 00 1d 00 00 00 09 00 00 00 00 00 00 00 4d 43 2d 43 54 52 4c 2d 54 4f 2d 44 52 56 00 00 1f 00 00 00 0f 00 00 00 02 00 00 00 0c 00 00 00 46 41 53 54 2d 44 49 45 2d 43 45 00 00 00 00 00 20 00 00 00 52 00 00 00 07 00 00 00 0d 00 00 00 53 4d 43 2d 54 4f 2d 50 50 4d 00 00 00 00 00 00 21 00 00 00 0d 00 00 00 01 00 00 00 0a 00 00 00 4c 54 53 2d 56 4f 4c 54 2d 43 41 50 00 00 00 00 40 00 00 00 59 00 00 00 05 00 00 00 0e 00 00 00 50 50 4d 2d 54 4f 2d 53 4d 43 00 00 00 00 00 00 41 00 00 00 5e 00 00 00 05 00 00 00 0f 00 00 00 43 4c 50 43 2d 54 4f 2d 53 4d 43 00 00 00 00 00 43 00 00 00 11 00 00 00 02 00 00 00 00 00 00 00 46 41 53 54 2d 44 49 45 2d 54 4f 2d 53 4d 43 00 44 00 00 00 26 00 00 00 01 00 00 00 00 00 00 00 4d 45 4d 43 2d 54 4f 2d 53 4d 43 00 00 00 00 00 52 00 00 00 0e 00 00 00 01 00 00 00 00 00 00 00 4c 54 53 2d 54 4f 2d 47 46 58 00 00 00 00 00 00]; - apple,tunable-sram-index = [01 00 00 00]; - apple,tunable-no-shutdown = [01 00 00 00]; - apple,tunable-dvfs-domain = [01 00 00 00 08 00 00 00 00 00 00 00 44 43 53 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 05 00 00 00 00 00 00 00 53 4f 43 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 06 00 00 00 00 00 00 00 44 49 53 50 00 00 00 00 00 00 00 00 00 00 00 00]; - apple,tunable-dvfs-disp-min-state = [01 00 00 00]; - apple,tunable-fast-die-ctrl-ce-map = [01 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 41 43 43 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 50 41 43 43 5f 41 4e 45 00 00 00 00 00 00 00 00]; - apple,tunable-ane-dcs-bw-constraint = [00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00]; - apple,tunable-soc-ni2-bw-threshold = [cc 0c 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 26 00 01 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 25 00 00 00 00 00 00 00 00 00 00 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 8f 3d 00 00 00 00 00]; - apple,tunable-agx-af-wr-bw-constraint = [00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00]; - apple,tunable-user-power-managed = [01 00 00 00]; - apple,tunable-ane-af-bw-threshold = [00 00 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 1c 00 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 f3 01 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 f3 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 00 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 09 00 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 f3 01 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 f3 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 06 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 16 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 41 00 00 00 00 00 00 00 15 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 40 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 13 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3f 00 00 00 00 00 00 00 12 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 3e 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0d 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3a 00 00 00 00 00 00 00 0c 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 39 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0d 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3a 00 00 00 00 00 00 00 0c 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 39 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 32 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 31 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 1e 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 1d 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 0f 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 0e 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 09 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 08 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 02 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 02 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00]; - apple,tunable-lts-voltage = [01 00 00 00 03 00 00 00 03 00 00 00 01 00 00 00 45 41 43 43 00 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 02 00 00 00 50 41 43 43 00 00 00 00 03 00 00 00 01 00 00 00 06 00 00 00 00 00 00 00 41 4e 45 00 00 00 00 00 04 00 00 00 03 00 00 00 05 00 00 00 04 00 00 00 41 47 58 00 00 00 00 00]; - apple,tunable-ane-dcs-bw-threshold = [a3 f0 13 00 01 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 02 00 00 00 a3 f0 12 00 00 00 00 00 1e 05 3a 00 03 00 00 00 66 e6 26 00 00 00 00 00 0a 57 4a 00 04 00 00 00 1e 05 39 00 00 00 00 00 3d 0a 57 00 05 00 00 00 0a 57 49 00 00 00 00 00 3d 8a 65 00 06 00 00 00 3d 0a 56 00 00 00 00 00 5c 0f 74 00 07 00 00 00 3d 8a 64 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 00 00 00 00 a3 f0 13 00 01 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 02 00 00 00 a3 f0 12 00 00 00 00 00 1e 05 3a 00 03 00 00 00 66 e6 26 00 00 00 00 00 0a 57 4a 00 04 00 00 00 1e 05 39 00 00 00 00 00 3d 0a 57 00 05 00 00 00 0a 57 49 00 00 00 00 00 3d 8a 65 00 06 00 00 00 3d 0a 56 00 00 00 00 00 5c 0f 74 00 07 00 00 00 3d 8a 64 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 00 00 00 00 a3 f0 13 00 00 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 00 00 00 00 a3 f0 12 00 06 00 00 00 1e 05 3a 00 00 00 00 00 66 e6 26 00 06 00 00 00 0a 57 4a 00 00 00 00 00 1e 05 39 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 0f 00 00 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 00 00 00 00 00 00 0e 00 06 00 00 00 1e 05 3a 00 00 00 00 00 66 e6 26 00 06 00 00 00 0a 57 4a 00 00 00 00 00 1e 05 39 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 00 00 00 00 00 00 09 00 06 00 00 00 1e 05 3a 00 00 00 00 00 66 e6 26 00 06 00 00 00 0a 57 4a 00 00 00 00 00 1e 05 39 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 00 00 00 00 00 00 09 00 06 00 00 00 1e 05 3a 00 00 00 00 00 66 e6 26 00 06 00 00 00 0a 57 4a 00 00 00 00 00 1e 05 39 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0f 00 00 00 00 00 00 00 00 00 06 00 00 00 1e 05 3a 00 00 00 00 00 00 00 0e 00 06 00 00 00 0a 57 4a 00 00 00 00 00 1e 05 39 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0f 00 00 00 00 00 00 00 00 00 06 00 00 00 1e 05 3a 00 00 00 00 00 00 00 0e 00 06 00 00 00 0a 57 4a 00 00 00 00 00 1e 05 39 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2a 00 00 00 00 00 00 00 04 00 06 00 00 00 0a 57 4a 00 00 00 00 00 00 00 29 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2a 00 00 00 00 00 00 00 00 00 06 00 00 00 0a 57 4a 00 00 00 00 00 00 00 29 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 15 00 00 00 00 00 00 00 00 00 06 00 00 00 0a 57 4a 00 00 00 00 00 00 00 14 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2a 00 00 00 00 00 00 00 00 00 06 00 00 00 3d 0a 57 00 00 00 00 00 00 00 29 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2a 00 00 00 00 00 00 00 00 00 06 00 00 00 3d 0a 57 00 00 00 00 00 00 00 29 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00]; - apple,tunable-bwr-catch-up-factor = [00 00 01 00]; - apple,tunable-controller = [01 00 00 00 1f 00 00 00 43 00 00 00 00 00 00 00 00 00 00 00 44 49 45 2d 54 45 4d 50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 43 53 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 46 49 2d 54 4f 50 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 30 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 31 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 32 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 33 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 34 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 09 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 35 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 47 58 2d 41 46 2d 52 44 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 47 58 2d 41 46 2d 57 52 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 47 58 2d 44 43 53 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0d 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4e 45 2d 41 46 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4e 45 2d 44 43 53 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0f 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4e 53 2d 41 46 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 0e 00 00 00 1e 00 00 00 00 00 00 00 00 00 00 00 4d 45 4d 2d 43 41 43 48 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 11 00 00 00 52 00 00 00 21 00 00 00 00 00 00 00 00 00 00 00 4c 49 46 45 54 49 4d 45 2d 53 45 52 56 4f 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00]; - apple,tunable-soc-device-ps-group = [00 fc ff 1f 00 00 00 00]; - apple,tunable-agx-dcs-bw-threshold = [00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 13 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 27 00 00 00 00 00 00 00 12 00 00 00 00 00 00 00 39 00 00 00 00 00 00 00 26 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 38 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 e7 03 00 00 00 00 00 00 11 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 27 00 00 00 00 00 00 00 10 00 06 00 00 00 00 00 39 00 00 00 00 00 00 00 26 00 06 00 00 00 00 00 4a 00 00 00 00 00 00 00 38 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 49 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 00 00 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 0c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 27 00 00 00 00 00 00 00 0b 00 06 00 00 00 00 00 39 00 00 00 00 00 00 00 26 00 06 00 00 00 00 00 47 00 00 00 00 00 00 00 38 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 46 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 00 00 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 37 00 00 00 00 00 00 00 21 00 06 00 00 00 00 00 47 00 00 00 00 00 00 00 36 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 46 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 00 00 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 15 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 1f 00 00 00 00 00 00 00 14 00 06 00 00 00 00 00 47 00 00 00 00 00 00 00 1e 00 06 00 00 00 00 00 57 00 00 00 00 00 00 00 46 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 56 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 00 00 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 0e 00 00 00 00 00 00 00 07 00 06 00 00 00 00 00 32 00 00 00 00 00 00 00 0d 00 06 00 00 00 00 00 57 00 00 00 00 00 00 00 31 00 06 00 00 00 00 00 65 00 00 00 00 00 00 00 56 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 64 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 17 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 43 00 00 00 00 00 00 00 16 00 06 00 00 00 00 00 65 00 00 00 00 00 00 00 42 00 06 00 00 00 00 00 74 00 00 00 00 00 00 00 64 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2d 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 50 00 00 00 00 00 00 00 2c 00 06 00 00 00 00 00 74 00 00 00 00 00 00 00 4f 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 10 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 3c 00 00 00 00 00 00 00 0f 00 06 00 00 00 00 00 74 00 00 00 00 00 00 00 3b 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 05 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 14 00 00 00 00 00 00 00 04 00 06 00 00 00 00 00 1e 00 00 00 00 00 00 00 13 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 1d 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 14 00 00 00 00 00 00 00 09 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 13 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 09 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00]; - apple,tunable-soc-ni1-bw-threshold = [cc 0c 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 26 00 01 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 25 00 00 00 00 00 00 00 00 00 00 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 8f 3d 00 00 00 00 00]; - apple,tunable-mc_quota_rsp_ptd_count = [08 00 00 00]; - apple,tunable-lts-ctrl-ts = [00 00 05 00]; - apple,tunable-temp-sensor = [01 00 00 00 08 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 80 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 61 30 30 30 69 00 00 00 00 00 00 00 00 00 00 02 00 00 00 08 00 00 00 06 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 33 b3 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 61 30 30 31 69 00 00 00 00 00 00 00 00 00 00 03 00 00 00 08 00 00 00 06 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 66 e6 03 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 61 30 30 32 69 00 00 00 00 00 00 00 00 00 00 04 00 00 00 08 00 00 00 06 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 00 80 05 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 61 30 30 35 69 00 00 00 00 00 00 00 00 00 00 05 00 00 00 08 00 00 00 06 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00 66 e6 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 61 30 30 36 69 00 00 00 00 00 00 00 00 00 00 06 00 00 00 08 00 00 00 06 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 cc 4c 05 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 61 30 30 37 69 00 00 00 00 00 00 00 00 00 00 07 00 00 00 08 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 30 69 00 00 00 00 00 00 00 00 00 00 08 00 00 00 08 00 00 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 40 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 31 69 00 00 00 00 00 00 00 00 00 00 09 00 00 00 08 00 00 00 04 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 07 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 33 69 00 00 00 00 00 00 00 00 00 00 0a 00 00 00 08 00 00 00 04 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 40 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 34 69 00 00 00 00 00 00 00 00 00 00 0b 00 00 00 08 00 00 00 04 00 00 00 01 00 00 00 03 00 00 00 00 00 00 00 00 00 01 00 00 80 06 00 6e 00 00 00 7d 00 00 00 54 70 30 30 6c 69 00 00 00 00 00 00 00 00 00 00 0c 00 00 00 08 00 00 00 04 00 00 00 01 00 00 00 04 00 00 00 00 00 00 00 00 00 01 00 00 80 06 00 6e 00 00 00 7d 00 00 00 54 70 30 30 6d 69 00 00 00 00 00 00 00 00 00 00 0d 00 00 00 08 00 00 00 04 00 00 00 01 00 00 00 05 00 00 00 00 00 00 00 33 33 03 00 00 80 06 00 6e 00 00 00 7d 00 00 00 54 70 30 30 6e 69 00 00 00 00 00 00 00 00 00 00 0e 00 00 00 08 00 00 00 04 00 00 00 01 00 00 00 06 00 00 00 00 00 00 00 66 e6 02 00 00 80 06 00 6e 00 00 00 7d 00 00 00 54 70 30 30 6f 69 00 00 00 00 00 00 00 00 00 00 0f 00 00 00 08 00 00 00 04 00 00 00 01 00 00 00 07 00 00 00 00 00 00 00 99 99 02 00 00 80 06 00 6e 00 00 00 7d 00 00 00 54 70 30 30 70 69 00 00 00 00 00 00 00 00 00 00 10 00 00 00 08 00 00 00 04 00 00 00 01 00 00 00 09 00 00 00 00 00 00 00 33 33 02 00 00 80 06 00 6e 00 00 00 7d 00 00 00 54 70 30 30 72 69 00 00 00 00 00 00 00 00 00 00 11 00 00 00 08 00 00 00 04 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 39 69 00 00 00 00 00 00 00 00 00 00 12 00 00 00 08 00 00 00 04 00 00 00 02 00 00 00 01 00 00 00 00 00 00 00 00 40 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 61 69 00 00 00 00 00 00 00 00 00 00 13 00 00 00 08 00 00 00 04 00 00 00 02 00 00 00 02 00 00 00 00 00 00 00 00 00 07 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 36 69 00 00 00 00 00 00 00 00 00 00 14 00 00 00 08 00 00 00 04 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00 00 40 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 37 69 00 00 00 00 00 00 00 00 00 00 15 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 66 66 08 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 65 30 30 37 69 00 00 00 00 00 00 00 00 00 00 16 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 80 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 65 30 30 31 69 00 00 00 00 00 00 00 00 00 00 17 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 99 99 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 65 30 30 32 69 00 00 00 00 00 00 00 00 00 00 18 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 33 b3 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 65 30 30 33 69 00 00 00 00 00 00 00 00 00 00 19 00 00 00 01 00 00 00 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 6d 00 00 00 6d 00 00 00 4d 54 52 5f 54 4f 50 5f 41 47 58 00 00 00 00 00]; - apple,tunable-agx-af-wr-bw-dvfs-filter = [fe 7f 00 00]; - apple,tunable-dcs-bw-threshold = [a3 f0 13 00 01 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 02 00 00 00 a3 f0 12 00 00 00 00 00 1e 05 3a 00 03 00 00 00 66 e6 26 00 00 00 00 00 0a 57 4a 00 04 00 00 00 1e 05 39 00 00 00 00 00 3d 0a 57 00 05 00 00 00 0a 57 49 00 00 00 00 00 3d 8a 65 00 06 00 00 00 3d 0a 56 00 00 00 00 00 5c 0f 74 00 07 00 00 00 3d 8a 64 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 00 00 00 00]; - apple,tunable-mc_cmd_ack_ptd_count = [01 00 00 00]; - apple,tunable-soc-ni0-bw-threshold = [cc 0c 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 26 00 01 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 25 00 00 00 00 00 00 00 00 00 00 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 8f 3d 00 00 00 00 00]; - apple,tunable-fast-die-ctrl-loop = [01 00 00 00 00 00 00 00 00 00 00 00 66 06 00 00 47 41 00 00 00 00 6e 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 01 00 16 00 00 00 15 00 00 00 16 00 00 00 17 00 00 00 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 41 43 43 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 01 00 00 00 66 06 00 00 47 41 00 00 00 00 6e 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 01 00 16 00 00 00 07 00 00 00 08 00 00 00 09 00 00 00 0a 00 00 00 0b 00 00 00 0c 00 00 00 0d 00 00 00 0e 00 00 00 0f 00 00 00 10 00 00 00 11 00 00 00 12 00 00 00 13 00 00 00 14 00 00 00 00 00 00 00 00 00 00 00 50 41 43 43 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 02 00 00 00 66 06 00 00 47 41 00 00 00 00 6e 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 01 00 16 00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4e 45 00 00 00 00 00 00 00 00 00 00 00 00 00]; - apple,tunable-agx-dcs-bw-dvfs-filter = [fe 7f 00 00]; - apple,tunable-agx-af-rd-bw-dvfs-filter = [fe 7f 00 00]; - apple,tunable-firmware-name = [74 38 31 34 32 70 6d 70 00]; - apple,tunable-lts-clpc-voltage = [01 00 00 00 98 03 00 00 00 00 69 00 33 33 69 00 00 00 00 00 50 41 43 43 00 00 00 00]; - apple,tunable-soc-ni5-bw-threshold = [cc 0c 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 26 00 01 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 25 00 00 00 00 00 00 00 00 00 00 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 8f 3d 00 00 00 00 00]; - apple,tunable-energy-counter = [01 00 00 00 01 00 00 00 05 00 00 00 01 00 00 00 41 47 58 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 01 00 00 00 05 00 00 00 02 00 00 00 41 47 58 2d 53 52 41 4d 00 00 00 00 00 00 00 00 03 00 00 00 01 00 00 00 06 00 00 00 01 00 00 00 41 4e 45 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 14 00 00 00 00 00 00 00 56 44 45 43 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 15 00 00 00 00 00 00 00 53 4f 43 5f 41 4f 4e 00 00 00 00 00 00 00 00 00]; - apple,tunable-lts-config = [01 00 00 00 3b 01 00 00 a6 72 0f 00 00 00 00 00 b5 d5 0f 00 6e 00 00 00 69 00 00 00 00 00 11 00 33 b3 00 00 b0 32 47 01 02 00 00 00 47 03 00 00 3b 61 00 00 00 00 00 00 f7 dd 0f 00 6e 00 00 00 69 00 00 00 00 00 11 00 33 b3 00 00 d7 43 ef 02]; - apple,tunable-agx-af-rd-bw-constraint = [00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00]; - apple,tunable-ane-af-bw-constraint = [00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00]; - apple,tunable-mcache-stream = [0e 00 00 00 04 00 00 00 01 00 00 00 0d 00 00 00 0d 00 00 00 38 00 00 00 38 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 11 00 00 00 04 00 00 00 01 00 00 00 0e 00 00 00 0e 00 00 00 3c 00 00 00 3c 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 1b 00 00 00 04 00 00 00 01 00 00 00 0e 00 00 00 0e 00 00 00 3d 00 00 00 3d 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 13 00 00 00 04 00 00 00 01 00 00 00 0f 00 00 00 0f 00 00 00 40 00 00 00 40 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 24 00 00 00 04 00 00 00 01 00 00 00 0f 00 00 00 0f 00 00 00 41 00 00 00 41 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 1c 00 00 00 04 00 00 00 01 00 00 00 0f 00 00 00 0f 00 00 00 42 00 00 00 42 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 1e 00 00 00 03 00 00 00 01 00 00 00 02 00 00 00 02 00 00 00 0c 00 00 00 0c 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 2b 00 00 00 03 00 00 00 01 00 00 00 02 00 00 00 02 00 00 00 0e 00 00 00 0e 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 05 00 00 00 01 00 00 00 01 00 00 00 07 00 00 00 07 00 00 00 20 00 00 00 20 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 06 00 00 00 02 00 00 00 01 00 00 00 08 00 00 00 08 00 00 00 24 00 00 00 24 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 0b 00 00 00 05 00 00 00 01 00 00 00 0b 00 00 00 0b 00 00 00 30 00 00 00 30 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 01 00 00 00 04 00 00 00 00 00 00 00 01 00 00 00 11 00 00 00 11 00 00 00 48 00 00 00 48 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 01 00 00 00 02 00 00 00 00 00 00 00 01 00 00 00 13 00 00 00 13 00 00 00 50 00 00 00 50 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 15 00 00 00 15 00 00 00 58 00 00 00 5a 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 10 00 00 00 04 00 00 00 01 00 00 00 1f 00 00 00 1f 00 00 00 80 00 00 00 bf 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 0f 00 00 00 04 00 00 00 02 00 00 00 10 00 00 00 10 00 00 00 44 00 00 00 44 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 20 00 00 00 03 00 00 00 02 00 00 00 03 00 00 00 06 00 00 00 10 00 00 00 1f 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 01 00 00 00 1f 00 00 00 03 00 00 00 02 00 00 00 1e 00 00 00 1e 00 00 00 7c 00 00 00 7c 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 12 00 00 00 05 00 00 00 02 00 00 00 09 00 00 00 09 00 00 00 28 00 00 00 28 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 0a 00 00 00 05 00 00 00 02 00 00 00 0c 00 00 00 0c 00 00 00 34 00 00 00 34 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 15 00 00 00 07 00 00 00 02 00 00 00 16 00 00 00 16 00 00 00 5d 00 00 00 5d 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 36 00 00 00 07 00 00 00 02 00 00 00 16 00 00 00 16 00 00 00 5e 00 00 00 5e 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 37 00 00 00 07 00 00 00 02 00 00 00 16 00 00 00 16 00 00 00 5f 00 00 00 5f 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 19 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 04 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 1a 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 05 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 29 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00 06 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 2a 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 07 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 0d 00 00 00 0b 00 00 00 03 00 00 00 01 00 00 00 01 00 00 00 08 00 00 00 08 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 0c 00 00 00 0b 00 00 00 03 00 00 00 01 00 00 00 01 00 00 00 09 00 00 00 09 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 14 00 00 00 04 00 00 00 03 00 00 00 01 00 00 00 01 00 00 00 0a 00 00 00 0a 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 27 00 00 00 04 00 00 00 03 00 00 00 1d 00 00 00 1d 00 00 00 78 00 00 00 78 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 2c 00 00 00 03 00 00 00 03 00 00 00 18 00 00 00 18 00 00 00 64 00 00 00 64 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 2f 00 00 00 02 00 00 00 03 00 00 00 1a 00 00 00 1a 00 00 00 6c 00 00 00 6c 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 26 00 00 00 05 00 00 00 03 00 00 00 1c 00 00 00 1c 00 00 00 74 00 00 00 74 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 23 00 00 00 00 00 00 00 03 00 00 00 14 00 00 00 14 00 00 00 54 00 00 00 54 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 28 00 00 00 00 00 00 00 03 00 00 00 1b 00 00 00 1b 00 00 00 70 00 00 00 70 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 31 00 00 00 0f 00 00 00 03 00 00 00 17 00 00 00 17 00 00 00 60 00 00 00 60 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 30 00 00 00 0e 00 00 00 03 00 00 00 17 00 00 00 17 00 00 00 61 00 00 00 61 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 33 00 00 00 11 00 00 00 03 00 00 00 17 00 00 00 17 00 00 00 62 00 00 00 62 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 34 00 00 00 12 00 00 00 03 00 00 00 17 00 00 00 17 00 00 00 63 00 00 00 63 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 35 00 00 00 09 00 00 00 03 00 00 00 19 00 00 00 19 00 00 00 68 00 00 00 68 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 1d 00 00 00 09 00 00 00 03 00 00 00 19 00 00 00 19 00 00 00 69 00 00 00 6b 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 2d 00 00 00 0c 00 00 00 03 00 00 00 18 00 00 00 18 00 00 00 65 00 00 00 65 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 16 00 00 00 0b 00 00 00 03 00 00 00 ff ff 00 00 ff ff 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00]; - apple,tunable-ptd-driver-version = [01 00 00 00]; - apple,tunable-afi-top-bw-threshold = [99 19 3a 00 00 00 00 00 00 00 00 00 00 00 00 00 51 78 4d 00 01 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 51 78 4c 00 00 00 00 00 00 00 00 00 00 00 00 00 33 33 73 00 00 00 00 00 00 00 00 00 00 00 00 00 b8 1e 7c 00 00 00 00 00]; - apple,tunable-region-size = [00 00 0d 00 00 00 00 00]; - apple,tunable-coredump-enable = [40 00 00 00]; - apple,tunable-soc-ni4-bw-threshold = [cc 0c 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 26 00 01 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 25 00 00 00 00 00 00 00 00 00 00 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 8f 3d 00 00 00 00 00]; - apple,tunable-pm-ptd-ranges = [01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05 00 00 00 06 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 09 00 00 00 0a 00 00 00 0b 00 00 00 0c 00 00 00 0d 00 00 00 00 00 00 00 0f 00 00 00]; - apple,tunable-fast-die-ctrl-ts-avg-temp = [00 00 64 00]; - apple,tunable-lts-ctrl-loop = [02 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 02 00 00 00 01 00 00 00 07 00 00 00 08 00 00 00 09 00 00 00 0a 00 00 00 0b 00 00 00 0c 00 00 00 0d 00 00 00 0e 00 00 00 0f 00 00 00 10 00 00 00 11 00 00 00 12 00 00 00 13 00 00 00 14 00 00 00 00 00 00 00 00 00 00 00 50 41 43 43 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 01 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 19 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 47 50 55 00 00 00 00 00 00 00 00 00 00 00 00 00]; - apple,tunable-soc-device = [01 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 43 53 00 00 00 00 00 02 00 00 00 45 4e 4f 4e 01 00 00 00 16 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4d 43 43 00 00 00 00 17 00 00 00 45 4e 4f 4e 01 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 30 00 18 00 00 00 45 4e 4f 4e 01 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 31 00 19 00 00 00 45 4e 4f 4e 01 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 32 00 1a 00 00 00 45 4e 4f 4e 01 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 33 00 1b 00 00 00 45 4e 4f 4e 01 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 34 00 1c 00 00 00 45 4e 4f 4e 01 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 35 00 10 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 15 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 41 4f 4e 00 11 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 52 45 53 54 03 00 00 00 45 4e 4f 4e 03 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 41 43 43 30 00 00 00 04 00 00 00 45 4e 4f 4e 03 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 50 41 43 43 30 00 00 00 05 00 00 00 5f 58 46 47 03 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 47 58 00 00 00 00 00 06 00 00 00 45 4e 4f 4e 03 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4e 45 30 00 00 00 00 07 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 49 53 50 00 00 00 00 00 08 00 00 00 45 4e 4f 4e 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 49 53 50 00 00 00 00 09 00 00 00 45 4e 4f 4e 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 49 53 50 45 58 54 30 0a 00 00 00 45 4e 4f 4e 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 49 53 50 45 58 54 31 0b 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 56 45 00 00 00 00 00 0c 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 14 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 56 44 00 00 00 00 00 0d 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 4d 53 52 00 00 00 00 00 0e 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 4a 50 45 47 00 00 00 00 0f 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 43 4f 44 45 43 00 00 1d 00 00 00 5f 52 54 4c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 4c 54 52 00 00 00 00 00 1e 00 00 00 45 4e 4f 4e 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 54 43 30 00 00 00 00 1f 00 00 00 45 4e 4f 4e 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 54 43 31 00 00 00 00 20 00 00 00 45 4e 4f 4e 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 54 43 32 00 00 00 00 21 00 00 00 45 4e 4f 4e 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 54 43 33 00 00 00 00 22 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4e 53 00 00 00 00 00 23 00 00 00 45 4e 4f 4e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 50 43 49 45 00 00 00 00 24 00 00 00 45 4e 4f 4e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 42 52 00 00 00 00 00 25 00 00 00 45 4e 4f 4e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 45 50 00 00 00 00 00 26 00 00 00 45 4e 4f 4e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 49 4f 00 00 00 00 00]; - apple,tunable-fast-die-ctrl-ts = [00 00 05 00]; - apple,tunable-region-base = [00 00 50 80 03 00 00 00]; - apple,tunable-agx-af-wr-bw-threshold = [00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 35 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 34 00 00 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 00 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 00 00 00 00 00 00 3a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 39 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 2d 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 2c 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 12 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 11 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 0e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3c 00 00 00 00 00 00 00 0d 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 3b 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 7a 00 00 00 00 00 00 00 32 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 79 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 2c 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 5a 00 00 00 00 00 00 00 2b 00 06 00 00 00 00 00 8a 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 89 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1e 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3e 00 00 00 00 00 00 00 1d 00 06 00 00 00 00 00 6f 00 00 00 00 00 00 00 3d 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 6e 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 34 00 00 00 00 00 00 00 09 00 06 00 00 00 00 00 5a 00 00 00 00 00 00 00 33 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2c 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 41 00 00 00 00 00 00 00 2b 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 40 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 19 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3c 00 00 00 00 00 00 00 18 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 3b 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 19 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 37 00 00 00 00 00 00 00 18 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 36 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 14 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 32 00 00 00 00 00 00 00 13 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 31 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 14 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 32 00 00 00 00 00 00 00 13 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 31 00 06 00 00 00]; - apple,tunable-uuid = [30 41 37 44 41 39 43 33 2d 45 37 46 36 2d 33 31 35 31 2d 41 43 44 45 2d 44 41 30 31 37 42 45 42 45 36 34 35 00]; - apple,tunable-segment-names = [5f 5f 54 45 58 54 3b 5f 5f 44 41 54 41 00]; - apple,tunable-segment-ranges = [00 00 50 80 03 00 00 00 00 00 00 01 00 00 00 00 00 00 50 80 03 00 00 00 00 c0 03 00 03 00 00 00 00 c0 53 80 03 00 00 00 00 c0 03 01 00 00 00 00 00 c0 53 80 03 00 00 00 00 e0 06 00 06 00 00 00]; - apple,tunable-pre-loaded = [01 00 00 00]; -}; diff --git a/arch/arm64/boot/dts/apple/t8142-j813-usb.dtsi b/arch/arm64/boot/dts/apple/t8142-j813-usb.dtsi index 2eb0b1f16af473..bf81e9b35ce21a 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813-usb.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j813-usb.dtsi @@ -69,7 +69,7 @@ compatible = "usb-c-connector"; label = "USB-C Left-front"; power-role = "dual"; - data-role = "host"; + data-role = "dual"; ports { #address-cells = <1>; @@ -98,7 +98,7 @@ reg = <4 0x02280000 0 0xcd00>, <4 0x0228cd00 0 0x4b00>; reg-names = "dwc3-core", "dwc3-apple"; interrupts = ; - dr_mode = "host"; + dr_mode = "otg"; usb-role-switch; role-switch-default-mode = "host"; iommus = <&dwc3_0_dart_0 0>, <&dwc3_0_dart_1 1>; @@ -215,7 +215,7 @@ compatible = "usb-c-connector"; label = "USB-C Left-rear"; power-role = "dual"; - data-role = "host"; + data-role = "dual"; ports { #address-cells = <1>; @@ -245,7 +245,7 @@ reg = <4 0x0a280000 0 0xcd00>, <4 0x0a28cd00 0 0x4b00>; reg-names = "dwc3-core", "dwc3-apple"; interrupts = ; - dr_mode = "host"; + dr_mode = "otg"; usb-role-switch; role-switch-default-mode = "host"; iommus = <&dwc3_1_dart_0 0>, <&dwc3_1_dart_1 1>; diff --git a/arch/arm64/boot/dts/apple/t8142-j813-usb4.dtsi b/arch/arm64/boot/dts/apple/t8142-j813-usb4.dtsi new file mode 100644 index 00000000000000..1062212dba17f2 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8142-j813-usb4.dtsi @@ -0,0 +1,536 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J813 USB-C ports: the ACIO0 (front) and ACIO1 (rear) routers and their + * PCIe-C tunnels. + */ + +/ { + aliases { + + /* aura copies the router tunables here, the AP firmware one too. */ + usb4-0-acio = &acio0; + + usb4-0-pcie-adapter = &acio0; + + usb4-0-nhi = &acio0_nhi; + + /* aura copies the PCIe-C tunables here (needs aura#302). */ + usb4-0-pcie = &apciec0; + + /* aura copies the router tunables here, the AP firmware one too. */ + usb4-1-acio = &acio1; + + usb4-1-pcie-adapter = &acio1; + + usb4-1-nhi = &acio1_nhi; + + /* aura copies the PCIe-C tunables here (needs aura#302). */ + usb4-1-pcie = &apciec1; + }; +}; + +&pmgr { + + ps_atc0_pcie: power-controller@3c8 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3c8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc0_common>, <&ps_atc0_usb_aon>; + label = "atc0-pcie"; + }; + + ps_atc0_cio: power-controller@3d0 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc0_common>; + label = "atc0-cio"; + }; + + ps_atc1_pcie: power-controller@3d8 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc1_common>, <&ps_atc1_usb_aon>; + label = "atc1-pcie"; + }; + + ps_atc1_cio: power-controller@3e0 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc1_common>; + label = "atc1-cio"; + }; + + ps_atc0_cio_pcie: power-controller@4d8 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc0_cio>; + label = "atc0-cio-pcie"; + }; + + ps_atc0_cio_usb: power-controller@4e0 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc0_cio>; + label = "atc0-cio-usb"; + }; + + ps_atc1_cio_pcie: power-controller@4e8 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4e8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc1_cio>; + label = "atc1-cio-pcie"; + }; + + ps_atc1_cio_usb: power-controller@4f0 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc1_cio>; + label = "atc1-cio-usb"; + }; +}; + +/* Populate these DARTs only after their parent is powered and configured. */ +/delete-node/ &acio0_dart; +/delete-node/ &pciec0_dart; +/delete-node/ &acio1_dart; +/delete-node/ &pciec1_dart; + +&{/soc} { + + cio_reset: reset-controller@380780000 { + compatible = "apple,t8142-cio-reset"; + reg = <0x3 0x80780000 0x0 0x4000>; + #reset-cells = <1>; + }; + + pinctrl_aop: pinctrl@390824000 { + compatible = "apple,t8142-pinctrl", "apple,t8140-pinctrl", "apple,t8103-pinctrl"; + reg = <0x3 0x90824000 0x0 0x4000>; + gpio-controller; + #gpio-cells = <2>; + gpio-ranges = <&pinctrl_aop 0 0 77>; + apple,npins = <77>; + + /* Only LSTX pins 19 and 21 are ours; the AOP owns the rest of this bank. */ + gpio-reserved-ranges = <0 19>, <20 1>, <22 55>; + interrupt-controller; + #interrupt-cells = <2>; + interrupts = , + , + , + ; + apple,irq-group-base = <3>; + + acio0_lstx_pins: acio0-lstx-pins { + pinmux = <0x10013>; + }; + + acio1_lstx_pins: acio1-lstx-pins { + pinmux = <0x10015>; + }; + }; + + acio0_mbox: mailbox@401108000 { + compatible = "apple,t8142-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x4 0x01108000 0x0 0x4000>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* acio@ avoids the bootloader's legacy cio@ register-index fixup. */ + acio0: acio@401ac0000 { + compatible = "apple,t8142-usb4-acio"; + reg = <0x4 0x01ac0000 0x0 0xc000>, + <0x4 0x01080000 0x0 0x26000>, + <0x4 0x01e44000 0x0 0x4000>, + <0x4 0x01100000 0x0 0x4000>, + <0x4 0x01c80000 0x0 0x4000>; + reg-names = "rc", "sram", "pcie-adapter", "cpu", "router-ap-fw"; + mboxes = <&acio0_mbox>; + resets = <&cio_reset 0>; + + power-domains = <&ps_atc0_cio>, <&ps_atc0_cio_pcie>, + <&ps_atc0_cio_usb>, <&ps_atc0_pcie>; + thunderbolt-switch; + apple,pcie-tunnel = <&acio0_pcie_tunnel>; + + pinctrl-0 = <&acio0_lstx_pins>; + pinctrl-names = "lstx"; + lstx-gpios = <&pinctrl_aop 19 GPIO_ACTIVE_HIGH>; + + #address-cells = <1>; + #size-cells = <1>; + ranges = <0x0 0x4 0x01000000 0x1000000>; + nonposted-mmio; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@1 { + reg = <1>; + acio0_tbt: endpoint { + remote-endpoint = <&typec0_usb4>; + }; + }; + }; + + acio0_dart: iommu@a80000 { + compatible = "apple,t8142-dart", "apple,t8110-dart"; + reg = <0xa80000 0xc000>; + interrupts = ; + power-domains = <&ps_atc0_cio>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x4000 0x0 0xffff0000>; + apple,bypass-sids = <15>; + apple,full-error-reporting; + apple,ctc-flush; + }; + + acio0_nhi: nhi@f00000 { + compatible = "apple,t8142-usb4-nhi"; + reg = <0xf00000 0x100000>; + reg-names = "nhi"; + interrupts = , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + ; + interrupt-names = "txring0", "txring1", "txring2", "txring3", + "txring4", "txring5", "txring6", "txring7", + "txring8", "txring9", "txring10", "txring11", + "rxring0", "rxring1", "rxring2", "rxring3", + "rxring4", "rxring5", "rxring6", "rxring7", + "rxring8", "rxring9", "rxring10", "rxring11"; + + iommus = <&acio0_dart 0>, <&acio0_dart 1>, <&acio0_dart 2>, + <&acio0_dart 3>, <&acio0_dart 4>, <&acio0_dart 5>, + <&acio0_dart 6>, <&acio0_dart 7>, <&acio0_dart 8>, + <&acio0_dart 9>, <&acio0_dart 10>, <&acio0_dart 11>, + <&acio0_dart 16>, <&acio0_dart 17>, <&acio0_dart 18>, + <&acio0_dart 19>, <&acio0_dart 20>, <&acio0_dart 21>, + <&acio0_dart 22>, <&acio0_dart 23>, <&acio0_dart 24>, + <&acio0_dart 25>, <&acio0_dart 26>, <&acio0_dart 27>; + + /* Filled by the bootloader. */ + apple,thunderbolt-drom = [00]; + }; + }; + + acio1_mbox: mailbox@409108000 { + compatible = "apple,t8142-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x4 0x09108000 0x0 0x4000>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* acio@ avoids the bootloader's legacy cio@ register-index fixup. */ + acio1: acio@409ac0000 { + compatible = "apple,t8142-usb4-acio"; + reg = <0x4 0x09ac0000 0x0 0xc000>, + <0x4 0x09080000 0x0 0x26000>, + <0x4 0x09e44000 0x0 0x4000>, + <0x4 0x09100000 0x0 0x4000>, + <0x4 0x09c80000 0x0 0x4000>; + reg-names = "rc", "sram", "pcie-adapter", "cpu", "router-ap-fw"; + mboxes = <&acio1_mbox>; + resets = <&cio_reset 1>; + + power-domains = <&ps_atc1_cio>, <&ps_atc1_cio_pcie>, + <&ps_atc1_cio_usb>, <&ps_atc1_pcie>; + thunderbolt-switch; + apple,pcie-tunnel = <&acio1_pcie_tunnel>; + + pinctrl-0 = <&acio1_lstx_pins>; + pinctrl-names = "lstx"; + lstx-gpios = <&pinctrl_aop 21 GPIO_ACTIVE_HIGH>; + + #address-cells = <1>; + #size-cells = <1>; + ranges = <0x0 0x4 0x09000000 0x1000000>; + nonposted-mmio; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@1 { + reg = <1>; + acio1_tbt: endpoint { + remote-endpoint = <&typec1_usb4>; + }; + }; + }; + + acio1_dart: iommu@a80000 { + compatible = "apple,t8142-dart", "apple,t8110-dart"; + reg = <0xa80000 0xc000>; + interrupts = ; + power-domains = <&ps_atc1_cio>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x4000 0x0 0xffff0000>; + apple,bypass-sids = <15>; + apple,full-error-reporting; + apple,ctc-flush; + }; + + acio1_nhi: nhi@f00000 { + compatible = "apple,t8142-usb4-nhi"; + reg = <0xf00000 0x100000>; + reg-names = "nhi"; + interrupts = , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + ; + interrupt-names = "txring0", "txring1", "txring2", "txring3", + "txring4", "txring5", "txring6", "txring7", + "txring8", "txring9", "txring10", "txring11", + "rxring0", "rxring1", "rxring2", "rxring3", + "rxring4", "rxring5", "rxring6", "rxring7", + "rxring8", "rxring9", "rxring10", "rxring11"; + + iommus = <&acio1_dart 0>, <&acio1_dart 1>, <&acio1_dart 2>, + <&acio1_dart 3>, <&acio1_dart 4>, <&acio1_dart 5>, + <&acio1_dart 6>, <&acio1_dart 7>, <&acio1_dart 8>, + <&acio1_dart 9>, <&acio1_dart 10>, <&acio1_dart 11>, + <&acio1_dart 16>, <&acio1_dart 17>, <&acio1_dart 18>, + <&acio1_dart 19>, <&acio1_dart 20>, <&acio1_dart 21>, + <&acio1_dart 22>, <&acio1_dart 23>, <&acio1_dart 24>, + <&acio1_dart 25>, <&acio1_dart 26>, <&acio1_dart 27>; + + /* Filled by the bootloader. */ + apple,thunderbolt-drom = [00]; + }; + }; +}; + +/ { + acio0_pcie_tunnel: pcie-tunnel-0 { + #address-cells = <2>; + #size-cells = <2>; + ranges; + nonposted-mmio; + + pciec0_dart: iommu@404000000 { + compatible = "apple,t8142-dart", "apple,t8110-dart"; + reg = <0x4 0x04000000 0x0 0xc000>; + interrupts = ; + power-domains = <&ps_atc0_pcie>; + #iommu-cells = <1>; + apple,bypass-sids = <253 255>; + apple,full-error-reporting; + apple,ctc-flush; + }; + + apciec0: pcie@1c50000000 { + compatible = "apple,t8142-pciec"; + device_type = "pci"; + reg = <0x1c 0x50000000 0x0 0x10000000>, + <0x4 0x04034000 0x0 0x4000>, + <0x4 0x04020000 0x0 0x8000>, + <0x4 0x04038000 0x0 0x4000>, + <0x4 0x04060000 0x0 0x4000>, + <0x4 0x0402c000 0x0 0x4000>, + <0x4 0x04028000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "fabric", "debug", "ltssm", "intr2axi"; + interrupts = ; + power-domains = <&ps_atc0_pcie>; + + apple,pciec-kernel-init; + + msi-controller; + msi-parent = <&apciec0>; + msi-ranges = <&aic AIC_IRQ 1837 IRQ_TYPE_EDGE_RISING 32>; + apple,msi-vector-base = <96>; + + iommu-map = <0x0 &pciec0_dart 0x0 0x40>; + iommu-map-mask = <0x3f>; + + linux,pci-domain = <1>; + + bus-range = <0x0 0x7f>; + #address-cells = <3>; + #size-cells = <2>; + + ranges = <0x43000000 0x8 0x0 0x8 0x0 0x2 0x0>, + <0x02000000 0x0 0x00100000 0xa 0x00100000 0x0 0x3ff00000>, + <0x42000000 0x0 0x40000000 0xa 0x40000000 0x0 0x40000000>; + + apciec0_port: pci@0,0 { + device_type = "pci"; + reg = <0x0 0x0 0x0 0x0 0x0>; + external-facing; + + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &apciec0_port 0 0 0 0>, + <0 0 0 2 &apciec0_port 0 0 0 1>, + <0 0 0 3 &apciec0_port 0 0 0 2>, + <0 0 0 4 &apciec0_port 0 0 0 3>; + }; + }; + }; + + acio1_pcie_tunnel: pcie-tunnel-1 { + #address-cells = <2>; + #size-cells = <2>; + ranges; + nonposted-mmio; + + pciec1_dart: iommu@40c000000 { + compatible = "apple,t8142-dart", "apple,t8110-dart"; + reg = <0x4 0x0c000000 0x0 0xc000>; + interrupts = ; + power-domains = <&ps_atc1_pcie>; + #iommu-cells = <1>; + apple,bypass-sids = <253 255>; + apple,full-error-reporting; + apple,ctc-flush; + }; + + apciec1: pcie@1c60000000 { + compatible = "apple,t8142-pciec"; + device_type = "pci"; + reg = <0x1c 0x60000000 0x0 0x10000000>, + <0x4 0x0c034000 0x0 0x4000>, + <0x4 0x0c020000 0x0 0x8000>, + <0x4 0x0c038000 0x0 0x4000>, + <0x4 0x0c060000 0x0 0x4000>, + <0x4 0x0c02c000 0x0 0x4000>, + <0x4 0x0c028000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "fabric", "debug", "ltssm", "intr2axi"; + interrupts = ; + power-domains = <&ps_atc1_pcie>; + + apple,pciec-kernel-init; + + msi-controller; + msi-parent = <&apciec1>; + msi-ranges = <&aic AIC_IRQ 1869 IRQ_TYPE_EDGE_RISING 32>; + apple,msi-vector-base = <128>; + + iommu-map = <0x0 &pciec1_dart 0x0 0x40>; + iommu-map-mask = <0x3f>; + + linux,pci-domain = <2>; + + bus-range = <0x0 0x7f>; + #address-cells = <3>; + #size-cells = <2>; + + ranges = <0x43000000 0xc 0x0 0xc 0x0 0x2 0x0>, + <0x02000000 0x0 0x00100000 0xe 0x00100000 0x0 0x3ff00000>, + <0x42000000 0x0 0x40000000 0xe 0x40000000 0x0 0x40000000>; + + apciec1_port: pci@0,0 { + device_type = "pci"; + reg = <0x0 0x0 0x0 0x0 0x0>; + external-facing; + + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &apciec1_port 0 0 0 0>, + <0 0 0 2 &apciec1_port 0 0 0 1>, + <0 0 0 3 &apciec1_port 0 0 0 2>, + <0 0 0 4 &apciec1_port 0 0 0 3>; + }; + }; + }; +}; + +/* Port 3 of each connector is the board's DisplayPort alternate-mode route. */ +&typec0 { + ports { + port@4 { + reg = <4>; + typec0_usb4: endpoint { + remote-endpoint = <&acio0_tbt>; + }; + }; + }; +}; + +&typec1 { + ports { + port@4 { + reg = <4>; + typec1_usb4: endpoint { + remote-endpoint = <&acio1_tbt>; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8142-j813.dts b/arch/arm64/boot/dts/apple/t8142-j813.dts index 4c6cf3358ce3e0..9a56793fb956aa 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813.dts +++ b/arch/arm64/boot/dts/apple/t8142-j813.dts @@ -9,6 +9,7 @@ /dts-v1/; #include "t8142.dtsi" +#include / { compatible = "apple,j813", "apple,t8142", "apple,arm-platform"; @@ -128,26 +129,6 @@ #include "t8142-j813-audio.dtsi" #include "t8142-hwmon.dtsi" -/* - * Ambient light sensor, the AOP's "als" service: an ST VD6286, as on J815 - * (same ADT node, /arm-io/aop/iop-aop-nub/als). aop_als sends it the - * per-device calibration (apple/aop-als-cal.bin). No firmware-name: that - * names the CT817 setup-port message, which this sensor does not take. - */ -&aop { - aop_als: als { - compatible = "apple,t8142-aop-als", "apple,aop-als"; - }; - - /* - * Lid angle: the J813 AOP firmware announces a "las" service, as the - * J815's does, and aop_las reads the hinge angle from it. - */ - aop_las: las { - compatible = "apple,t8142-aop-las", "apple,aop-las"; - }; -}; - /* * N1 functions behind apcie port 0 (0000:00:00.0 -> 01:00.{0,1,2}), so the * loader has somewhere to put the factory addresses: it copies ADT /chosen @@ -169,6 +150,13 @@ #address-cells = <3>; #size-cells = <2>; ranges; + /* + * The N1's warm reset: the ADT's pci-bridge0 function-warm_reset (the SMC, key + * 'bpli', the same key and argument as on the T6050 boards) and the T6050 writes. + * The N1 driver restarts a stopped firmware with it. + */ + apple,function-warm-reset = <&smc 0x62706c69 0x1000000>; + apple,warm-reset-writes = <0x00010001 17000>, <0x00010001 20000>; n1_control: control@0,0 { compatible = "apple,t8142-centauri-control", "pci106b,1900"; @@ -194,6 +182,10 @@ &mtp_hid { multi-touch { firmware-name = "apple/tpmtfw-j813.bin"; + /* Palm classes flicker onto fingers for single reports. */ + apple,palm-debounce; + /* The same touch states and path IDs as the J815's pad. */ + apple,touch-states; }; }; @@ -293,3 +285,994 @@ &hpm1 { apple,sleep-ssps-rules; }; + +&smc_hwmon { + #thermal-sensor-cells = <1>; +}; + +/ { + /* + * Fanless: the CPUs are the only cooling devices, and both clusters + * share one die and one passive heat spreader. The PMP's fast + * die-temperature loop (apple,fast-die-effort) is the primary control: + * on J813, an all-core load holds the hottest SMC die sensor (Tp04) + * at 102.3-102.5 C while leaving the E cluster at 2.96 GHz and tapering + * the P cluster from 4.46 to 3.88-4.02 GHz as the chassis warms + * (13.2 W combined CPU rail power after 330 s). + * + * These per-sensor zones sit behind the PMP as a slow outer backstop + * and critical shutdown guard. The control (110 C) and critical + * (125 C, after three samples) trips come from the J813 ADT's PMP + * temp-sensor table, which gives every CPU die sensor a 110 C target + * and a 125 C maximum (sochot). A 95 C switch-on (15 C gap, 13 W + * measured sustainable power, 20 s integral time constant) keeps the + * power budget above the full-speed energy-model request (24.1 W) up to + * 103.6 C so cooling devices stay at state 0 throughout cold-start ramp + * and steady state under normal PMP operation (Tp04 <= 102.5 C), while + * regulating smoothly if PMP does not hold the die (k_po 887, k_pu 1774, + * k_i 88; a 4-7 C gap oscillated). The E cluster is weighted 3:1 over P + * and capped at state 5 (1152 MHz, more efficient per MHz than 300 MHz and + * above idle wake latency). + * + * Sensor indices count temperature-* children across hwmon-common + * (0: TH0x), hwmon-laptop (1-3: TB0T, TCHP, TW0P) and t8142-hwmon + * (4-7: Te04..Te0R, 8-21: Tp00..Tp1E). + */ + thermal-zones { + cpu-e0-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 4>; /* Te04 */ + sustainable-power = <13000>; + + trips { + cpu_e0_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_e0_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_e0_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_e0_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-e1-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 5>; /* Te08 */ + sustainable-power = <13000>; + + trips { + cpu_e1_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_e1_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_e1_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_e1_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-e2-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 6>; /* Te0C */ + sustainable-power = <13000>; + + trips { + cpu_e2_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_e2_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_e2_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_e2_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-e3-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 7>; /* Te0R */ + sustainable-power = <13000>; + + trips { + cpu_e3_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_e3_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_e3_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_e3_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p0-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 8>; /* Tp00 */ + sustainable-power = <13000>; + + trips { + cpu_p0_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p0_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p0_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p0_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p1-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 9>; /* Tp04 */ + sustainable-power = <13000>; + + trips { + cpu_p1_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p1_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p1_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p1_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p2-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 10>; /* Tp0C */ + sustainable-power = <13000>; + + trips { + cpu_p2_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p2_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p2_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p2_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p3-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 11>; /* Tp0G */ + sustainable-power = <13000>; + + trips { + cpu_p3_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p3_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p3_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p3_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p4-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 12>; /* Tp0O */ + sustainable-power = <13000>; + + trips { + cpu_p4_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p4_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p4_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p4_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p5-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 13>; /* Tp0R */ + sustainable-power = <13000>; + + trips { + cpu_p5_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p5_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p5_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p5_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p6-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 14>; /* Tp0X */ + sustainable-power = <13000>; + + trips { + cpu_p6_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p6_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p6_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p6_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p7-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 15>; /* Tp0a */ + sustainable-power = <13000>; + + trips { + cpu_p7_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p7_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p7_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p7_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p8-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 16>; /* Tp0p */ + sustainable-power = <13000>; + + trips { + cpu_p8_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p8_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p8_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p8_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p9-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 17>; /* Tp0u */ + sustainable-power = <13000>; + + trips { + cpu_p9_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p9_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p9_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p9_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p10-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 18>; /* Tp0y */ + sustainable-power = <13000>; + + trips { + cpu_p10_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p10_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p10_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p10_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p11-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 19>; /* Tp12 */ + sustainable-power = <13000>; + + trips { + cpu_p11_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p11_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p11_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p11_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p12-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 20>; /* Tp16 */ + sustainable-power = <13000>; + + trips { + cpu_p12_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p12_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p12_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p12_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p13-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 21>; /* Tp1E */ + sustainable-power = <13000>; + + trips { + cpu_p13_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p13_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p13_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p13_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + }; +}; + +#include "t8142-j813-usb4.dtsi" diff --git a/arch/arm64/boot/dts/apple/t8142-j815.dts b/arch/arm64/boot/dts/apple/t8142-j815.dts index 82e73d6dafc2b9..691b2c2e7b5637 100644 --- a/arch/arm64/boot/dts/apple/t8142-j815.dts +++ b/arch/arm64/boot/dts/apple/t8142-j815.dts @@ -6,7 +6,6 @@ * J813 board fragments and overrides what the J815 ADT shows to be * different: * - * - /chosen board-id 0x26 (J813: 0x24) * - 15.3" 2880x1864 panel (2880x1800 below the notch), 326 x 211 mm * - six SN012776 speaker amplifiers on i2c3 (0x38-0x3d: two tweeters and * four force-cancelling woofers); J813 has four @@ -136,14 +135,16 @@ multi-touch { /* ADT hid-merge-personality C1FD3,3 (J813: C1FD1,4). */ firmware-name = "apple/tpmtfw-j815.bin"; + /* Touch states and path IDs decoded on this pad against macOS. */ + apple,touch-states; + /* + * Hand classes past 12 mm on two reports, any contact past 22 mm + * at once (no finger on macOS passed 21 mm). + */ + apple,palm-tool-area = <1200 2200>; }; }; -&pmp { - /* ADT /chosen board-id (J815) */ - apple,board-id = <38>; -}; - &panel { compatible = "apple,panel-j815", "apple,panel"; width-mm = <326>; @@ -163,29 +164,6 @@ apple,speaker-amps = <6>; }; -/* - * Ambient light sensor, the AOP's "als" service: an ST VD6286, as on the - * M4 Pro, not T8140's CT817. aop_als sends it the per-device calibration - * (apple/aop-als-cal.bin) as its calibration property. There is no - * firmware-name: that names the CT817 setup-port message, which this sensor - * does not take. - */ -&aop { - aop_als: als { - compatible = "apple,t8142-aop-als", "apple,aop-als"; - }; - - /* - * Lid angle: the J815 AOP firmware announces a "las" service, which - * macOS 27.2 on this machine binds as an AppleSPUHIDDevice (usage page - * 0x20, usage 0x8a), as on T6050. The ADT's i2c1 "mogul-las" is the - * sensor's authentication chip, not the angle. - */ - aop_las: las { - compatible = "apple,t8142-aop-las", "apple,aop-las"; - }; -}; - /* Names as in speakersafetyd's j815.conf; slots from ADT speaker-config. */ &speaker_left_woofer { sound-name-prefix = "Left Woofer 1"; @@ -268,6 +246,12 @@ #address-cells = <3>; #size-cells = <2>; ranges; + /* + * The N1's warm reset, as on J813: the J815 ADT's pci-bridge0 + * function-warm_reset names the same SMC key 'bpli' and argument. + */ + apple,function-warm-reset = <&smc 0x62706c69 0x1000000>; + apple,warm-reset-writes = <0x00010001 17000>, <0x00010001 20000>; n1_control: control@0,0 { compatible = "apple,t8142-centauri-control", "pci106b,1900"; @@ -358,6 +342,29 @@ * init (drivers/soc/apple/dt.rs). */ &pmgr { + /* + * From the J815 ADT, as on J813: GPIO at +0x120 and SEP at +0xc00, both + * always on (the enclave gates its own domain). The SEP driver stages its + * sleep request on the SEP word, so the node has to name it. + */ + ps_gpio: power-controller@120 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x120 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "gpio"; + apple,always-on; + }; + + ps_sep: power-controller@c00 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xc00 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "sep"; + apple,always-on; + }; + ps_spi2: power-controller@440 { compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; reg = <0x440 4>; @@ -375,6 +382,7 @@ mboxes = <&sep_mbox>; mbox-names = "mbox"; iommus = <&sep_dart 0>; + power-domains = <&ps_sep>, <&ps_gpio>; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi index fccc55e1e28127..601d57d2f2061d 100644 --- a/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi @@ -181,7 +181,6 @@ power-domains = <&ps_ane_sys>; /* The firmware DVAs reach 0x100_xxxx_xxxx. */ apple,dma-range = <0x0 0x0 0x400 0x0>; - status = "disabled"; }; ane_dart1: iommu@421820000 { @@ -192,7 +191,6 @@ interrupts = ; power-domains = <&ps_ane_sys>; apple,dma-range = <0x0 0x0 0x400 0x0>; - status = "disabled"; }; ane_dart2: iommu@421840000 { @@ -203,7 +201,6 @@ interrupts = ; power-domains = <&ps_ane_sys>; apple,dma-range = <0x0 0x0 0x400 0x0>; - status = "disabled"; }; /* @@ -212,6 +209,9 @@ * boot loader hands the preload over as firmware-text and firmware-data. * PWGATE is the ADT's reg[2] (PMGR +0x24000) + 0x3640, measured under * macOS 27.2.1. + * Every T8142 board has it (same ane/dart-ane in the J704, J813 and J815 + * ADTs), so it is on by default; the boot loader hands the preload over + * by this compatible and disables the node when the ADT has none. */ ane: ane@420000000 { compatible = "apple,t8142-ane"; @@ -230,7 +230,6 @@ 0x3807002e8 0x3807002eb 0x38070c008 0x38070c00b 0x582668000 0x582668003>; - status = "disabled"; }; scaler0_dart: iommu@305260000 { @@ -240,10 +239,12 @@ /* No DART gate in the ADT: powered with its engine. */ power-domains = <&ps_msr>; #iommu-cells = <1>; - status = "disabled"; }; - /* ADT dart-jpeg: one DART for both engines, jpeg0 on SID 0, jpeg1 on SID 1. */ + /* + * ADT dart-jpeg: one DART for both engines, jpeg0 on SID 0, jpeg1 on SID 1. + * The JPEG engines need no firmware and are on every T8142 board. + */ jpeg_dart: iommu@301020000 { compatible = "apple,t8142-dart", "apple,t8110-dart"; reg = <0x3 0x1020000 0x0 0xc000>; @@ -252,7 +253,6 @@ /* ADT vm-base 0x100_0000_0000, vm-size 0x300_0000_0000 */ apple,dma-range = <0x100 0x0 0x300 0x0>; power-domains = <&ps_jpg>; - status = "disabled"; }; /* @@ -265,7 +265,6 @@ interrupts = ; iommus = <&jpeg_dart 0>; power-domains = <&ps_jpg>; - status = "disabled"; }; jpeg1: jpeg@301060000 { @@ -274,7 +273,6 @@ interrupts = ; iommus = <&jpeg_dart 1>; power-domains = <&ps_jpg>; - status = "disabled"; }; apr_dart: iommu@3a1020000 { @@ -602,7 +600,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "jpg"; - status = "disabled"; }; /* ADT pmgr device SCODEC (id 336): the ProRes engine and its DART. */ @@ -643,7 +640,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "ane_sys"; - status = "disabled"; }; ps_msr: power-controller@2a8 { @@ -652,7 +648,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "msr"; - status = "disabled"; }; ps_msr_ase_core: power-controller@320 { compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -661,7 +656,6 @@ #reset-cells = <0>; label = "msr-ase-core"; power-domains = <&ps_msr>; - status = "disabled"; }; /* @@ -675,7 +669,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "venc_sys"; - status = "disabled"; }; ps_venc_dma: power-controller@8000 { @@ -685,7 +678,6 @@ #reset-cells = <0>; label = "venc_dma"; power-domains = <&ps_venc_sys>; - status = "disabled"; }; ps_venc_pipe4: power-controller@8008 { @@ -695,7 +687,6 @@ #reset-cells = <0>; label = "venc_pipe4"; power-domains = <&ps_venc_dma>; - status = "disabled"; }; ps_venc_pipe5: power-controller@8010 { @@ -705,7 +696,6 @@ #reset-cells = <0>; label = "venc_pipe5"; power-domains = <&ps_venc_dma>; - status = "disabled"; }; ps_venc_me0: power-controller@8018 { @@ -715,7 +705,6 @@ #reset-cells = <0>; label = "venc_me0"; power-domains = <&ps_venc_dma>; - status = "disabled"; }; ps_venc_me1: power-controller@8020 { @@ -725,7 +714,6 @@ #reset-cells = <0>; label = "venc_me1"; power-domains = <&ps_venc_me0>; - status = "disabled"; }; }; @@ -797,7 +785,9 @@ * preloaded by iBoot and handed over by the boot loader, which adds the * memory regions. dart-ave is two DARTs (DART and CPUDART) on one IRQ; * stream 12 carries the temporal filter engines and must translate - * through the encoder's domain, not bypass. + * through the encoder's domain, not bypass. On by default (same ave and + * dart-ave in the J704, J813 and J815 ADTs); the boot loader disables + * the encoder when the ADT has no preload. */ ave_dart0: iommu@281080000 { compatible = "apple,t8142-dart", "apple,t8110-dart"; @@ -806,7 +796,6 @@ power-domains = <&ps_venc_sys>; #iommu-cells = <1>; apple,dma-range = <0x100 0x00004000 0x0 0xffffc000>; - status = "disabled"; }; ave_dart1: iommu@2810a0000 { @@ -816,7 +805,6 @@ power-domains = <&ps_venc_sys>; #iommu-cells = <1>; apple,dma-range = <0x100 0x00004000 0x0 0xffffc000>; - status = "disabled"; }; ave: video-codec@281100000 { @@ -835,7 +823,6 @@ power-domain-names = "dma", "pipe4", "pipe5", "me0", "me1"; iommus = <&ave_dart0 0>, <&ave_dart0 12>, <&ave_dart1 0>, <&ave_dart1 12>; - status = "disabled"; }; scaler0: scaler@305000000 { @@ -874,6 +861,89 @@ clocks = <&peripheral_clocks 399>; power-domains = <&ps_msr>, <&ps_msr_ase_core>; resets = <&ps_msr>; - status = "disabled"; + }; +}; + +/* + * The AOP (always-on processor), laid out like T8140's (ascwrap-v6, + * asc-mailbox-v4), including the setup port. Its /arm-io/aop, + * aop-exclave-mailbox and dart-aop nodes and its iop-aop-nub services are + * the same in the J704, J813 and J815 ADTs (arm-io offset 0x210000000), so + * every T8142 board gets the AOP and its sensor services here; a board adds + * only its audio service. The AOP core needs no power-domains: the ADT gives + * it no power-gates and the AP never switches its states off. + */ +&{/soc} { + aop_mbox: mailbox@390608000 { + compatible = "apple,t8142-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x3 0x90608000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* + * The ADT's aop-exclave-mailbox, flagged exclave-assigned as on T8140, + * is the AOP setup port the host drives. Its ADT reg (0x3d067c000) is + * not behind the arm-io translation: AOP ASC + 0x4007c000, as on + * T8140. ADT interrupts [497, 494], T8140's +100. + */ + aop_setup_mbox: mailbox@3d067c000 { + compatible = "apple,t8142-aop-setup-mailbox", "apple,t8140-aop-setup-mailbox"; + reg = <0x3 0xd067c000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + /* dart-aop stream 1: ADT vm-base-1 0x20000000000, as on T8140. */ + iommus = <&aop_dart 1>; + apple,dma-range = <0x200 0x0 0x10 0x0>; + #mbox-cells = <0>; + }; + + /* + * dart-aop: streams 0 (AOP), 3, 8 (admac-base-ns), 10 and 16 are the + * AP's; 1, 9 and 11 are exclave streams, of which the host drives 1 + * (setup port) and 11 (admac-leap-s) on the raw boot. As on T8140, the + * firmware's own mappings own the first slot, host buffers go above it. + */ + aop: aop@390c00000 { + compatible = "apple,t8142-aop", "apple,t8152-aop"; + reg = <0x3 0x90c00000 0x0 0x1e0000>, + <0x3 0x90600000 0x0 0x4000>; + reg-names = "mmio", "asc"; + mboxes = <&aop_mbox>, <&aop_setup_mbox>; + mbox-names = "mbox", "setup"; + iommus = <&aop_dart 0>; + apple,dma-range = <0x110 0x0 0x10 0x0>; + + /* + * Ambient light sensor, the AOP's "als" service + * (iop-aop-nub/als): an ST VD6286, as on the M4 Pro, not + * T8140's CT817. aop_als sends it the per-device calibration + * (apple/aop-als-cal.bin). There is no firmware-name: that + * names the CT817 setup-port message, which this sensor does + * not take. + */ + aop_als: als { + compatible = "apple,t8142-aop-als", "apple,aop-als"; + }; + + /* + * Lid angle: the AOP firmware announces a "las" service, which + * macOS binds as an AppleSPUHIDDevice (usage page 0x20, usage + * 0x8a), as on T6050. The ADT's i2c1 "mogul-las" is the + * sensor's authentication chip, not the angle; every T8142 + * laptop has it. The AOP registers the child only for a + * service its firmware announces. + */ + aop_las: las { + compatible = "apple,t8142-aop-las", "apple,aop-las"; + }; }; }; diff --git a/arch/arm64/boot/dts/apple/t8142.dtsi b/arch/arm64/boot/dts/apple/t8142.dtsi index 04bf85831e9e84..5efe61f299ef50 100644 --- a/arch/arm64/boot/dts/apple/t8142.dtsi +++ b/arch/arm64/boot/dts/apple/t8142.dtsi @@ -234,7 +234,12 @@ reg = <0x3 0x90fc0000 0x0 0xc000>; interrupts = ; #iommu-cells = <1>; - status = "disabled"; + /* + * No power-domains: AOP_DART is in the AOP's own power tree + * (pmgr AOP_FILTER), which runs from before the handoff and + * which the AP never switches off; the ADT gives dart-aop and + * aop no power-gates. + */ }; pmp_dart: iommu@380300000 { diff --git a/arch/arm64/boot/dts/apple/t8152-j873-audio.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-audio.dtsi new file mode 100644 index 00000000000000..72bfb845022b8f --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-audio.dtsi @@ -0,0 +1,258 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J873g audio: the AOP (always-on processor) owns the audio fabric, as + * on T8140. iBoot loads the AOP firmware (j873gaop) and leaves the CPU + * stopped; Linux starts it. The jack codec (CS42L84) and the speaker amp + * (SN012776) are on AP I2C buses; their data goes through AOP services on + * the base-ns ADMAC. Resources are from the 26A434 ADT: aop, dart-sbr, + * admac-base-ns, iop-audio-controller, i2c1, i2c3, pmgr. + */ +#include + +/* + * ADT dart-sbr (sbr_dart in t8152-peripherals.dtsi), shared with the PMP: + * mapper-aop 0, mapper-admac-base-ns 42. iBoot leaves streams 0, 1 and 42 + * translating (root slot 16 owned by the firmware) without setting the + * lock bit. + */ +&sbr_dart { + apple,retain-translation; + status = "okay"; +}; + +/ { + soc { + /* + * ADT aop: iop,ascwrap-v8, msgbox-mailbox-num 0, using-alias, + * not post-office: mailbox 0, aperture 1 of the bank at reg[2] + * (0x310740000) = 0x310740080. ADT interrupts [627, 626, 628]; + * the first two in the SMC order (send-empty, recv-not-empty). + */ + aop_mbox: mailbox@310740080 { + compatible = "apple,t8152-ascwrap-v8-mailbox"; + reg = <0x3 0x10740080 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* + * ADT admac-base-ns (admac-evolution,t8152): 13 TX and 13 RX + * channels, interrupt destination 0, dart-sbr stream 42. + */ + admac_base_ns: dma-controller@313900000 { + compatible = "apple,t8152-admac"; + reg = <0x3 0x13900000 0x0 0xb4000>; + dma-channels = <26>; + interrupts-extended = <&aic AIC_IRQ 640 IRQ_TYPE_LEVEL_HIGH>, + <0>, <0>, <0>; + #dma-cells = <1>; + iommus = <&sbr_dart 42>; + /* slot 17: slot 16 of stream 42 belongs to the firmware */ + apple,dma-range = <0x110 0x0 0x0 0x10000000>; + }; + + /* + * The AOP's PMGR (ADT pmgr devices AUDIO_MCA0_M..AUDIO_MCA5_M at + * 0x308284400 + 0x20 * N). Their parent audio_p is the + * firmware's: it is up while a service is in pw0 or pwrd. + */ + pmgr_aop: power-management@308284000 { + compatible = "apple,t8152-pmgr", "apple,t8103-pmgr", + "syscon", "simple-mfd"; + #address-cells = <1>; + #size-cells = <1>; + reg = <0x3 0x08284000 0x0 0x1000>; + + ps_audio_mca0_m: power-controller@400 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x400 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "audio_mca0_m"; + }; + + ps_audio_mca1_m: power-controller@420 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x420 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "audio_mca1_m"; + }; + + ps_audio_mca2_m: power-controller@440 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x440 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "audio_mca2_m"; + }; + + ps_audio_mca3_m: power-controller@460 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x460 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "audio_mca3_m"; + }; + + ps_audio_mca4_m: power-controller@480 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x480 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "audio_mca4_m"; + }; + + ps_audio_mca5_m: power-controller@4a0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x4a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "audio_mca5_m"; + }; + }; + + /* ADT i2c1: the CS42L84 jack codec (and the aqc NIC's EEPROM). */ + i2c1: i2c@331014000 { + compatible = "apple,t8152-i2c", "apple,t8103-i2c"; + reg = <0x3 0x31014000 0x0 0x4000>; + clocks = <&clkref>; + interrupts = ; + #address-cells = <1>; + #size-cells = <0>; + power-domains = <&ps_i2c1>; + + /* + * ADT audio-codec-output: function-reset GPIO 0xcc, + * interrupt on gpio0 pin 203. + */ + jack_codec: codec@4b { + compatible = "cirrus,cs42l84"; + reg = <0x4b>; + reset-gpios = <&pinctrl_ap 204 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 203 IRQ_TYPE_LEVEL_LOW>; + #sound-dai-cells = <0>; + sound-name-prefix = "Jack"; + }; + }; + + /* ADT i2c3: the SN012776 speaker amplifier. */ + i2c3: i2c@33101c000 { + compatible = "apple,t8152-i2c", "apple,t8103-i2c"; + reg = <0x3 0x3101c000 0x0 0x4000>; + clocks = <&clkref>; + interrupts = ; + #address-cells = <1>; + #size-cells = <0>; + power-domains = <&ps_i2c3>; + + /* + * ADT audio-speaker: function-reset GPIO 0xca, interrupt + * on gpio0 pin 193, speaker-config rx_slot 0, + * vsense_slot 0, isense_slot 2. + */ + speaker_amp: codec@38 { + compatible = "ti,sn012776", "ti,tas2764"; + reg = <0x38>; + shutdown-gpios = <&pinctrl_ap 202 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 193 IRQ_TYPE_LEVEL_LOW>; + #sound-dai-cells = <0>; + ti,imon-slot-no = <2>; + ti,vmon-slot-no = <0>; + /* the AOP's speaker frame: 250 BCLKs at 12 MHz */ + ti,bclk-ratio = <250>; + }; + }; + + aop: aop@310c00000 { + compatible = "apple,t8152-aop"; + reg = <0x3 0x10c00000 0x0 0x1e0000>, + <0x3 0x10600000 0x0 0x4000>; + reg-names = "mmio", "asc"; + mboxes = <&aop_mbox>; + mbox-names = "mbox"; + iommus = <&sbr_dart 0>; + /* slot 17: slot 16 belongs to the firmware */ + apple,dma-range = <0x110 0x0 0x10 0x0>; + + /* + * Bound by name to the firmware's "audio" EPIC service. + * ADT iop-audio-controller: cout/cin on base-ns TX5/RX5, + * spkr on TX1 with its sense data on RX1; Linux ADMAC + * channel = 2 * N for TX N, 2 * N + 1 for RX N. + */ + aop_audio: audio { + compatible = "apple,t8152-aop-audio"; + dmas = <&admac_base_ns 10>, <&admac_base_ns 11>, + <&admac_base_ns 2>, <&admac_base_ns 3>; + dma-names = "cout", "cin", "spkr", "sense"; + power-domains = <&ps_audio_mca0_m>, <&ps_audio_mca1_m>, + <&ps_audio_mca2_m>, <&ps_audio_mca3_m>, + <&ps_audio_mca4_m>, <&ps_audio_mca5_m>; + power-domain-names = "mca0", "mca1", "mca2", + "mca3", "mca4", "mca5"; + #sound-dai-cells = <1>; + }; + }; + }; + + sound { + compatible = "apple,j873-macaudio", "apple,macaudio"; + model = "Mac mini J873"; + #address-cells = <1>; + #size-cells = <0>; + + dai-link@0 { + reg = <0>; + link-name = "Headphone Jack"; + + cpu { + sound-dai = <&aop_audio 0>; + }; + codec { + sound-dai = <&jack_codec>; + }; + }; + + dai-link@1 { + reg = <1>; + link-name = "Speaker"; + + cpu { + sound-dai = <&aop_audio 3>; + }; + codec { + sound-dai = <&speaker_amp>; + }; + }; + }; +}; + +/* The I2C power states (PMGR, parent SIO_CPU is always on). */ +&pmgr { + ps_i2c1: power-controller@cc0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xcc0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "i2c1"; + }; + + ps_i2c3: power-controller@d00 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xd00 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "i2c3"; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873-avd.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-avd.dtsi new file mode 100644 index 00000000000000..d36cd5ef242b27 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-avd.dtsi @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* J873g: the Kopsia video decoder (described in t8152-peripherals.dtsi). */ + +&ps_avd { + status = "okay"; +}; + +&avd_dart { + status = "okay"; +}; + +&avd { + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi new file mode 100644 index 00000000000000..0c7df8e3a55ddf --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi @@ -0,0 +1,758 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J873g displays: three controllers for the rear USB-C and HDMI ports, + * driven through + * the DCP firmware's iBoot interface (apple,t8152-dcp-iboot). The + * bootloader hands over running or quiesced RTKit sessions. Unused + * controllers can claim another USB-C monitor through the shared crossbar. + * + * Resources are from the 26A434 ADT: dcp (iop,ascwrap-v8, post-office + * mailbox 5 with alias: 0x316020000 + 2 * 5 * 0x80), dart-dcp (SID 23), + * dart-disp0 (scanout SID 0), and the atc-phyN PHY windows. The Gen3 + * display DARTs stay locked by iBoot, each with its own live root, so the + * scanout stream is a child device with its own domain. Linux tables are + * published into vacant root slots, so the DMA window is the upper half of + * the 64 GiB vm-base window, above the firmware's and the bootloader's + * mappings. + */ +#include +#include + +/* + * The display coprocessors' PMGR power states (ADT pmgr devices DISP_CPU, + * DISPEXT0_CPU and DISPEXT1_CPU), which their DARTs follow. The PMGR does not + * switch them for the AP: the coprocessor is started through its PSD service + * (coproc-psd below) and its firmware runs the state, so Linux only reads + * DISPEXT0_CPU (coproc-ps). They are the firmware's: the OS keeps them on and + * never accesses them. + */ +&pmgr { + ps_dispext1_cpu: power-controller@aa0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xaa0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_cpu"; + apple,firmware-owned; + }; + + ps_dispext0_cpu: power-controller@e00 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xe00 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_cpu"; + apple,firmware-owned; + }; + + ps_disp_cpu: power-controller@14000 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x14000 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_cpu"; + apple,firmware-owned; + }; +}; + +&dcp_dart { + apple,dma-range = <0x108 0x0 0x8 0x0>; + power-domains = <&ps_disp_cpu>; + status = "okay"; +}; + +&disp0_dart { + apple,dma-range = <0x108 0x0 0x8 0x0>; + power-domains = <&ps_disp_cpu>; + status = "okay"; +}; + +&dcpext0_dart { + apple,dma-range = <0x108 0x0 0x8 0x0>; + power-domains = <&ps_dispext0_cpu>; + status = "okay"; +}; + +&dispext0_dart { + apple,dma-range = <0x108 0x0 0x8 0x0>; + power-domains = <&ps_dispext0_cpu>; + status = "okay"; +}; + +&dcpext1_dart { + apple,dma-range = <0x108 0x0 0x8 0x0>; + power-domains = <&ps_dispext1_cpu>; + status = "okay"; +}; + +&dispext1_dart { + reg-names = "dart", "dapf"; + apple,dma-range = <0x108 0x0 0x8 0x0>; + power-domains = <&ps_dispext1_cpu>; + status = "okay"; +}; + +/ { + soc { + /* + * ADT /arm-io/nub-spmi-a0 (gen 4): the USB-C PD controllers of + * the three rear ports, each of which can carry the USB-C display. + * Their event, sleep and wake sources are interrupts of this + * controller (the ADT's), its own line is AIC 682. A connector's + * display port leads to the port's display switch, which all + * DCPs share. + */ + nub_spmi_a0: spmi@308908000 { + compatible = "apple,t8152-spmi", "apple,t8142-spmi"; + reg = <0x3 0x08908000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = ; + interrupt-controller; + #interrupt-cells = <2>; + #address-cells = <2>; + #size-cells = <0>; + + /* back-middle */ + hpm0: usb-pd@c { + compatible = "apple,t8152-sn201202x", "apple,t8132-sn201202x", + "apple,sn201202x"; + reg = <0xc SPMI_USID>; + interrupts = <11 IRQ_TYPE_EDGE_RISING>, + <17 IRQ_TYPE_EDGE_RISING>, + <19 IRQ_TYPE_EDGE_RISING>; + interrupt-names = "irq", "sleep", "wake"; + + typec0: connector { + compatible = "usb-c-connector"; + label = "USB-C Back-middle"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + /* USB: not linked to its controller yet */ + port@0 { + reg = <0>; + }; + + /* SuperSpeed: the ATC PHY */ + port@1 { + reg = <1>; + + typec0_ss: endpoint { + remote-endpoint = <&atc0_phy_typec>; + }; + }; + + /* DisplayPort: the DCPs' display switch */ + port@3 { + reg = <3>; + + typec0_display: endpoint { + remote-endpoint = <&display_typec0>; + }; + }; + }; + }; + }; + + /* back-left */ + hpm1: usb-pd@a { + compatible = "apple,t8152-sn201202x", "apple,t8132-sn201202x", + "apple,sn201202x"; + reg = <0xa SPMI_USID>; + interrupts = <37 IRQ_TYPE_EDGE_RISING>, + <43 IRQ_TYPE_EDGE_RISING>, + <45 IRQ_TYPE_EDGE_RISING>; + interrupt-names = "irq", "sleep", "wake"; + + typec1: connector { + compatible = "usb-c-connector"; + label = "USB-C Back-left"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + /* USB: not linked to its controller yet */ + port@0 { + reg = <0>; + }; + + /* SuperSpeed: the ATC PHY */ + port@1 { + reg = <1>; + + typec1_ss: endpoint { + remote-endpoint = <&atc1_phy_typec>; + }; + }; + + /* DisplayPort: the DCPs' display switch */ + port@3 { + reg = <3>; + + typec1_display: endpoint { + remote-endpoint = <&display_typec1>; + }; + }; + }; + }; + }; + + /* back-right */ + hpm3: usb-pd@8 { + compatible = "apple,t8152-sn201202x", "apple,t8132-sn201202x", + "apple,sn201202x"; + reg = <0x8 SPMI_USID>; + interrupts = <63 IRQ_TYPE_EDGE_RISING>, + <69 IRQ_TYPE_EDGE_RISING>, + <71 IRQ_TYPE_EDGE_RISING>; + interrupt-names = "irq", "sleep", "wake"; + + typec3: connector { + compatible = "usb-c-connector"; + label = "USB-C Back-right"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + /* USB: not linked to its controller yet */ + port@0 { + reg = <0>; + }; + + /* SuperSpeed: the ATC PHY */ + port@1 { + reg = <1>; + + typec3_ss: endpoint { + remote-endpoint = <&atc3_phy_typec>; + }; + }; + + /* DisplayPort: the DCPs' display switch */ + port@3 { + reg = <3>; + + typec3_display: endpoint { + remote-endpoint = <&display_typec3>; + }; + }; + }; + }; + }; + }; + + /* + * ADT aop-gpio. Its interrupts are the AOP's, so it has no + * interrupt controller here; the HDMI HPD line is polled. + */ + pinctrl_aop: pinctrl@310824000 { + compatible = "apple,t8152-pinctrl", "apple,t8103-pinctrl"; + reg = <0x3 0x10824000 0x0 0x4000>; + gpio-controller; + #gpio-cells = <2>; + gpio-ranges = <&pinctrl_aop 0 0 77>; + apple,npins = <77>; + }; + + dcp_mbox: mailbox@316020500 { + compatible = "apple,t8152-ascwrap-v8-mailbox"; + reg = <0x3 0x16020500 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + dcp_iboot: display@286e00000 { + compatible = "apple,t8152-dcp-iboot"; + reg = <0x2 0x86e00000 0x0 0x74000>, + <0x3 0x00020044 0x0 0x1c>, + <0x3 0x1a760000 0x0 0x4000>, + <0x3 0x00700460 0x0 0x4>; + /* aux: ADT dptx0-aux, aux-ps: PMGR GLOBAL_AUX_CTRL0 */ + reg-names = "coproc", "dp-clock", "aux", "aux-ps"; + #address-cells = <2>; + #size-cells = <2>; + ranges; + mboxes = <&dcp_mbox>; + iommus = <&dcp_dart 23>; + power-domains = <&ps_disp_cpu>; + /* + * Cacheable DMA, as iBoot maps DCP buffers: the firmware + * faults on entries with the DART's no-cache bit. + */ + dma-coherent; + apple,dp-source = <0>; + + /* + * The display pipe's own stream: a separate device, so + * its domain imports dart-disp0's root, not dart-dcp's. + */ + scanout { + iommus = <&disp0_dart 0>; + dma-coherent; + }; + + /* + * USB-C back-middle: ADT atc-phy0. PS: the ATC's DP_0, DP_1 and + * USB_AON power states (+0, +0x20, +0x100), PSD: its common + * domain, read to tell whether the PHY runs; the ATC PHY + * driver powers them while the DP PHY is on. Tunables before + * and after the lane crossbar setup. The node is also the + * port's display switch for all DCPs. + */ + usb-c@403000000 { + reg = <0x4 0x03000000 0x0 0x84000>, + <0x3 0x08290000 0x0 0x104>, + <0x3 0x03a13700 0x0 0xc0>; + reg-names = "atc", "atc-ps", "atc-psd"; + apple,dfp-endpoint = <0>; + /* Powered while a DCP drives it */ + phys = <&atc0_phy PHY_TYPE_DP>; + /* The DCPs' display switch of the port */ + mode-switch; + apple,tunable-pre = + /* ACIOPHY_CMN_DFLT */ + <0x00800 0x00fc0000 0x00fc0000>, + <0x0084c 0x000ff800 0x000ff800>, + <0x0085c 0x000000ff 0x00000080>, + <0x00860 0x007fffff 0x0052bca4>, + <0x00864 0x02c00000 0x00800000>, + /* CIOPLL_CORE_DFLT */ + <0x01614 0x0003ffc0 0x0001e5c0>, + <0x01640 0x00000007 0x00000003>, + <0x01668 0x00000ffc 0x000005f0>; + apple,tunable-post = + /* ATC_FABRIC */ + <0x6c004 0x003f003f 0x00200020>, + <0x6c00c 0x000000f1 0x000000a1>, + <0x6c010 0x0000801f 0x00000004>, + <0x6c018 0x003f003f 0x00200020>, + <0x6c020 0x000000f1 0x000000a1>, + <0x6c024 0x0000801f 0x00000004>, + <0x6c02c 0x007f007f 0x00410041>, + <0x6c034 0x000000f1 0x00000071>, + <0x6c038 0x0000801f 0x00000004>, + <0x6c040 0x0000001f 0x00000010>, + <0x6c048 0x0000801f 0x00000004>, + <0x6c050 0x007f007f 0x00450045>, + <0x6c058 0x000000f1 0x00000051>, + <0x6c05c 0x0000801f 0x00000004>, + <0x6c064 0x0000003f 0x00000020>, + <0x6c06c 0x0000801f 0x00000004>, + <0x6c074 0x00000001 0x00000001>, + <0x6c078 0x0000801f 0x00000004>, + <0x6c080 0x001f001f 0x00100010>, + <0x6c084 0x000000f1 0x00000011>, + <0x6c088 0x00000001 0x00000001>, + <0x6c08c 0x00000001 0x00000001>, + <0x6c090 0x0000801f 0x00000004>, + <0x6c098 0x001f001f 0x00100010>, + <0x6c09c 0x000000f1 0x00000011>, + <0x6c0a0 0x0000801f 0x00000004>, + <0x6c0a8 0x000000ff 0x000000a0>, + <0x6c0ac 0x0000801f 0x00000004>, + <0x6c0b4 0x0000003f 0x00000020>, + <0x6c0bc 0x0000801f 0x00000004>, + <0x6c0c4 0x0000003f 0x00000020>, + <0x6c0cc 0x0000801f 0x00000004>, + <0x6c0d4 0x0000000f 0x00000008>, + <0x6c0d8 0x0000801f 0x00000004>, + <0x6c0e0 0x001f001f 0x00180018>, + <0x6c0e4 0x0000801f 0x00000004>, + <0x6c0ec 0x001f001f 0x00180018>, + <0x6c0f0 0x0000801f 0x00000004>, + <0x6c0f8 0x001f001f 0x00180018>, + <0x6c0fc 0x0000801f 0x00000004>, + <0x6c104 0x001f001f 0x00180018>, + <0x6c108 0x0000801f 0x00000004>, + <0x6c110 0x00000001 0x00000001>, + <0x6c114 0x0000801f 0x00000004>, + <0x6c11c 0x0000801f 0x00000004>, + <0x6c124 0x0000801f 0x00000004>, + <0x6c12c 0x0000801f 0x00000004>, + <0x6c134 0x0000801f 0x00000004>, + <0x6c13c 0xffffffff 0x01010101>, + <0x6c140 0x0000801f 0x00000004>, + <0x6c148 0x0000801f 0x00000004>, + <0x6c150 0xffffffff 0x01010101>, + <0x6c154 0x0000ffff 0x00000101>, + <0x6c158 0x0000801f 0x00000004>, + <0x6c160 0x0000801f 0x00000004>, + <0x6c168 0x0000801f 0x00000004>, + <0x6c170 0x0000801f 0x00000004>, + <0x6c178 0x0000801f 0x00000004>, + <0x6c180 0xffffffff 0x01010101>, + <0x6c184 0x0000801f 0x00000004>, + <0x6c18c 0x0000801f 0x00000004>, + <0x6c194 0x0000801f 0x00000004>, + /* DPPLL_CORE_DFLT */ + <0x01040 0x0000000c 0x00000008>, + <0x01060 0x0001c000 0x0000c000>, + <0x01098 0x00000f00 0x00000800>, + <0x0109c 0x000fe000 0x000fe000>, + <0x01108 0x07c00000 0x04000000>, + <0x0110c 0x0000007c 0x00000010>, + /* DPPLL_TOP_DFLT */ + <0x00e8c 0x0000007f 0x0000003c>, + <0x00e9c 0x0000007f 0x00000032>, + <0x00eac 0x0000007f 0x00000032>, + <0x00ebc 0x0000007f 0x0000005a>, + /* ASDC_AUX_SHM_DFLT */ + <0x02308 0x000000fc 0x00000084>; + + port { + display_typec0: endpoint { + remote-endpoint = <&typec0_display>; + }; + }; + }; + + /* + * USB-C back-left: ADT atc-phy1. PS: the ATC's DP_0, DP_1 and + * USB_AON power states (+0, +0x20, +0x100), PSD: its common + * domain, read to tell whether the PHY runs; the ATC PHY + * driver powers them while the DP PHY is on. Tunables before + * and after the lane crossbar setup. The node is also the + * port's display switch for all DCPs. + */ + usb-c@40b000000 { + reg = <0x4 0x0b000000 0x0 0x84000>, + <0x3 0x08290040 0x0 0x104>, + <0x3 0x03a13800 0x0 0xc0>; + reg-names = "atc", "atc-ps", "atc-psd"; + apple,dfp-endpoint = <1>; + /* Powered while a DCP drives it */ + phys = <&atc1_phy PHY_TYPE_DP>; + /* The DCPs' display switch of the port */ + mode-switch; + apple,tunable-pre = + /* ACIOPHY_CMN_DFLT */ + <0x00800 0x00fc0000 0x00fc0000>, + <0x0084c 0x000ff800 0x000ff800>, + <0x0085c 0x000000ff 0x00000080>, + <0x00860 0x007fffff 0x0052bc26>, + <0x00864 0x02c00000 0x00800000>, + /* CIOPLL_CORE_DFLT */ + <0x01614 0x0003ffc0 0x0001e5c0>, + <0x01640 0x00000007 0x00000003>, + <0x01668 0x00000ffc 0x000005f0>; + apple,tunable-post = + /* ATC_FABRIC */ + <0x6c004 0x003f003f 0x00200020>, + <0x6c00c 0x000000f1 0x000000a1>, + <0x6c010 0x0000801f 0x00000004>, + <0x6c018 0x003f003f 0x00200020>, + <0x6c020 0x000000f1 0x000000a1>, + <0x6c024 0x0000801f 0x00000004>, + <0x6c02c 0x007f007f 0x00410041>, + <0x6c034 0x000000f1 0x00000071>, + <0x6c038 0x0000801f 0x00000004>, + <0x6c040 0x0000001f 0x00000010>, + <0x6c048 0x0000801f 0x00000004>, + <0x6c050 0x007f007f 0x00450045>, + <0x6c058 0x000000f1 0x00000051>, + <0x6c05c 0x0000801f 0x00000004>, + <0x6c064 0x0000003f 0x00000020>, + <0x6c06c 0x0000801f 0x00000004>, + <0x6c074 0x00000001 0x00000001>, + <0x6c078 0x0000801f 0x00000004>, + <0x6c080 0x001f001f 0x00100010>, + <0x6c084 0x000000f1 0x00000011>, + <0x6c088 0x00000001 0x00000001>, + <0x6c08c 0x00000001 0x00000001>, + <0x6c090 0x0000801f 0x00000004>, + <0x6c098 0x001f001f 0x00100010>, + <0x6c09c 0x000000f1 0x00000011>, + <0x6c0a0 0x0000801f 0x00000004>, + <0x6c0a8 0x000000ff 0x000000a0>, + <0x6c0ac 0x0000801f 0x00000004>, + <0x6c0b4 0x0000003f 0x00000020>, + <0x6c0bc 0x0000801f 0x00000004>, + <0x6c0c4 0x0000003f 0x00000020>, + <0x6c0cc 0x0000801f 0x00000004>, + <0x6c0d4 0x0000000f 0x00000008>, + <0x6c0d8 0x0000801f 0x00000004>, + <0x6c0e0 0x001f001f 0x00180018>, + <0x6c0e4 0x0000801f 0x00000004>, + <0x6c0ec 0x001f001f 0x00180018>, + <0x6c0f0 0x0000801f 0x00000004>, + <0x6c0f8 0x001f001f 0x00180018>, + <0x6c0fc 0x0000801f 0x00000004>, + <0x6c104 0x001f001f 0x00180018>, + <0x6c108 0x0000801f 0x00000004>, + <0x6c110 0x00000001 0x00000001>, + <0x6c114 0x0000801f 0x00000004>, + <0x6c11c 0x0000801f 0x00000004>, + <0x6c124 0x0000801f 0x00000004>, + <0x6c12c 0x0000801f 0x00000004>, + <0x6c134 0x0000801f 0x00000004>, + <0x6c13c 0xffffffff 0x01010101>, + <0x6c140 0x0000801f 0x00000004>, + <0x6c148 0x0000801f 0x00000004>, + <0x6c150 0xffffffff 0x01010101>, + <0x6c154 0x0000ffff 0x00000101>, + <0x6c158 0x0000801f 0x00000004>, + <0x6c160 0x0000801f 0x00000004>, + <0x6c168 0x0000801f 0x00000004>, + <0x6c170 0x0000801f 0x00000004>, + <0x6c178 0x0000801f 0x00000004>, + <0x6c180 0xffffffff 0x01010101>, + <0x6c184 0x0000801f 0x00000004>, + <0x6c18c 0x0000801f 0x00000004>, + <0x6c194 0x0000801f 0x00000004>, + /* DPPLL_CORE_DFLT */ + <0x01040 0x0000000c 0x00000008>, + <0x01060 0x0001c000 0x0000c000>, + <0x01098 0x00000f00 0x00000800>, + <0x0109c 0x000fe000 0x000fe000>, + <0x01108 0x07c00000 0x04000000>, + <0x0110c 0x0000007c 0x00000010>, + /* DPPLL_TOP_DFLT */ + <0x00e8c 0x0000007f 0x0000003c>, + <0x00e9c 0x0000007f 0x00000032>, + <0x00eac 0x0000007f 0x00000032>, + <0x00ebc 0x0000007f 0x0000005a>, + /* ASDC_AUX_SHM_DFLT */ + <0x02308 0x000000fc 0x00000084>; + + port { + display_typec1: endpoint { + remote-endpoint = <&typec1_display>; + }; + }; + }; + + /* + * USB-C back-right: ADT atc-phy3. PS: the ATC's DP_0, DP_1 and + * USB_AON power states (+0, +0x20, +0x100), PSD: its common + * domain, read to tell whether the PHY runs; the ATC PHY + * driver powers them while the DP PHY is on. Tunables before + * and after the lane crossbar setup. The node is also the + * port's display switch for all DCPs. + */ + usb-c@413000000 { + reg = <0x4 0x13000000 0x0 0x84000>, + <0x3 0x082900c0 0x0 0x104>, + <0x3 0x03a13a00 0x0 0xc0>; + reg-names = "atc", "atc-ps", "atc-psd"; + apple,dfp-endpoint = <3>; + /* Powered while a DCP drives it */ + phys = <&atc3_phy PHY_TYPE_DP>; + /* The DCPs' display switch of the port */ + mode-switch; + apple,tunable-pre = + /* ACIOPHY_CMN_DFLT */ + <0x00800 0x00fc0000 0x00fc0000>, + <0x0084c 0x000ff800 0x000ff800>, + <0x0085c 0x000000ff 0x00000080>, + <0x00860 0x007fffff 0x0052bc26>, + <0x00864 0x02c00000 0x00800000>, + /* CIOPLL_CORE_DFLT */ + <0x01614 0x0003ffc0 0x0001e5c0>, + <0x01640 0x00000007 0x00000003>, + <0x01668 0x00000ffc 0x000005f0>; + apple,tunable-post = + /* ATC_FABRIC */ + <0x6c004 0x003f003f 0x00200020>, + <0x6c00c 0x000000f1 0x000000a1>, + <0x6c010 0x0000801f 0x00000004>, + <0x6c018 0x003f003f 0x00200020>, + <0x6c020 0x000000f1 0x000000a1>, + <0x6c024 0x0000801f 0x00000004>, + <0x6c02c 0x007f007f 0x00410041>, + <0x6c034 0x000000f1 0x00000071>, + <0x6c038 0x0000801f 0x00000004>, + <0x6c040 0x0000001f 0x00000010>, + <0x6c048 0x0000801f 0x00000004>, + <0x6c050 0x007f007f 0x00450045>, + <0x6c058 0x000000f1 0x00000051>, + <0x6c05c 0x0000801f 0x00000004>, + <0x6c064 0x0000003f 0x00000020>, + <0x6c06c 0x0000801f 0x00000004>, + <0x6c074 0x00000001 0x00000001>, + <0x6c078 0x0000801f 0x00000004>, + <0x6c080 0x001f001f 0x00100010>, + <0x6c084 0x000000f1 0x00000011>, + <0x6c088 0x00000001 0x00000001>, + <0x6c08c 0x00000001 0x00000001>, + <0x6c090 0x0000801f 0x00000004>, + <0x6c098 0x001f001f 0x00100010>, + <0x6c09c 0x000000f1 0x00000011>, + <0x6c0a0 0x0000801f 0x00000004>, + <0x6c0a8 0x000000ff 0x000000a0>, + <0x6c0ac 0x0000801f 0x00000004>, + <0x6c0b4 0x0000003f 0x00000020>, + <0x6c0bc 0x0000801f 0x00000004>, + <0x6c0c4 0x0000003f 0x00000020>, + <0x6c0cc 0x0000801f 0x00000004>, + <0x6c0d4 0x0000000f 0x00000008>, + <0x6c0d8 0x0000801f 0x00000004>, + <0x6c0e0 0x001f001f 0x00180018>, + <0x6c0e4 0x0000801f 0x00000004>, + <0x6c0ec 0x001f001f 0x00180018>, + <0x6c0f0 0x0000801f 0x00000004>, + <0x6c0f8 0x001f001f 0x00180018>, + <0x6c0fc 0x0000801f 0x00000004>, + <0x6c104 0x001f001f 0x00180018>, + <0x6c108 0x0000801f 0x00000004>, + <0x6c110 0x00000001 0x00000001>, + <0x6c114 0x0000801f 0x00000004>, + <0x6c11c 0x0000801f 0x00000004>, + <0x6c124 0x0000801f 0x00000004>, + <0x6c12c 0x0000801f 0x00000004>, + <0x6c134 0x0000801f 0x00000004>, + <0x6c13c 0xffffffff 0x01010101>, + <0x6c140 0x0000801f 0x00000004>, + <0x6c148 0x0000801f 0x00000004>, + <0x6c150 0xffffffff 0x01010101>, + <0x6c154 0x0000ffff 0x00000101>, + <0x6c158 0x0000801f 0x00000004>, + <0x6c160 0x0000801f 0x00000004>, + <0x6c168 0x0000801f 0x00000004>, + <0x6c170 0x0000801f 0x00000004>, + <0x6c178 0x0000801f 0x00000004>, + <0x6c180 0xffffffff 0x01010101>, + <0x6c184 0x0000801f 0x00000004>, + <0x6c18c 0x0000801f 0x00000004>, + <0x6c194 0x0000801f 0x00000004>, + /* DPPLL_CORE_DFLT */ + <0x01040 0x0000000c 0x00000008>, + <0x01060 0x0001c000 0x0000c000>, + <0x01098 0x00000f00 0x00000800>, + <0x0109c 0x000fe000 0x000fe000>, + <0x01108 0x07c00000 0x04000000>, + <0x0110c 0x0000007c 0x00000010>, + /* DPPLL_TOP_DFLT */ + <0x00e8c 0x0000007f 0x0000003c>, + <0x00e9c 0x0000007f 0x00000032>, + <0x00eac 0x0000007f 0x00000032>, + <0x00ebc 0x0000007f 0x0000005a>, + /* ASDC_AUX_SHM_DFLT */ + <0x02308 0x000000fc 0x00000084>; + + port { + display_typec3: endpoint { + remote-endpoint = <&typec3_display>; + }; + }; + }; + + }; + + /* + * DCPEXT0 (post-office mailbox 6) can drive USB-C, or the dedicated + * dptx-phy through the PS190 converter. ADT dcpext0, + * dart-dcpext0 and dart-dispext0. + */ + dcpext_mbox: mailbox@316020600 { + compatible = "apple,t8152-ascwrap-v8-mailbox"; + reg = <0x3 0x16020600 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + dcpext_iboot: display@32ae00000 { + compatible = "apple,t8152-dcp-iboot"; + reg = <0x3 0x2ae00000 0x0 0x74000>, + <0x3 0x1a740000 0x0 0x10000>, + <0x3 0x1a700000 0x0 0x4000>, + <0x3 0x1a764000 0x0 0x4000>, + <0x3 0x00700480 0x0 0x4>, + <0x3 0x007016c0 0x0 0x4>, + <0x3 0x00700e00 0x0 0x4>, + <0x3 0x03a12c00 0x0 0xc0>, + <0x3 0x03a10500 0x0 0xc0>; + /* aux: ADT dptx1-aux, aux-ps: PMGR GLOBAL_AUX_CTRL1 */ + /* PMGR DPTX_PHY, read-only DISPEXT0_CPU, PSD service 5 (dptx-phy) */ + reg-names = "coproc", "phy-core", "phy-apb", "aux", "aux-ps", + "phy-ps", "coproc-ps", "coproc-psd", "phy-psd"; + mboxes = <&dcpext_mbox>; + iommus = <&dcpext0_dart 23>; + power-domains = <&ps_dispext0_cpu>; + dma-coherent; + apple,dp-source = <1>; + apple,usb-c-ports = <&dcp_iboot>; + apple,hdmi; + /* ADT dp2hdmi-gpio0 function-hdmi_hpd */ + hpd-gpios = <&pinctrl_aop 41 GPIO_ACTIVE_HIGH>; + /* function-dp2hdmi_pwr_en, function-hdmi_pwr_en (SMC pcIO) */ + apple,smc = <&smc>; + apple,pcon-power = <0x7063494f 0x00140000 0x00000001>, + <0x7063494f 0x000f0000 0x00800001>; + /* ADT dptx-phy tunables, in AppleT8152DPTXPort::handleSetTunables order */ + apple,tunable-phy = <0x5180 0x1fff000 0x723000>, + <0x5184 0xffffffff 0x2bc>, + <0x7980 0x1fff000 0x723000>, + <0x7984 0xffffffff 0x2bc>, + <0xa180 0x1fff000 0x723000>, + <0xa184 0xffffffff 0x2bc>, + <0xc980 0x1fff000 0x723000>, + <0xc984 0xffffffff 0x2bc>, + <0x4524 0x3800000 0x2800000>, + <0x6d24 0x3800000 0x2800000>, + <0x9524 0x3800000 0x2800000>, + <0xbd24 0x3800000 0x2800000>, + <0x840 0xc 0x8>, + <0x860 0x1c000 0xc000>, + <0x898 0xf00 0x800>, + <0x89c 0xfe000 0xfe000>, + <0x908 0x7c00000 0x4000000>, + <0x90c 0x7c 0x10>, + <0x68c 0x7f 0x3c>, + <0x69c 0x7f 0x32>, + <0x6ac 0x7f 0x32>, + <0x6bc 0x7f 0x5a>, + <0x1408 0xfc 0x84>, + <0x1c4c 0xff800 0xff800>, + <0x1c5c 0xff 0x80>, + <0x1c60 0x7fffff 0x52bba7>, + <0x1c64 0x2c00000 0x800000>; + + scanout { + iommus = <&dispext0_dart 0>; + dma-coherent; + }; + + }; + + dcpext1_mbox: mailbox@316020700 { + compatible = "apple,t8152-ascwrap-v8-mailbox"; + reg = <0x3 0x16020700 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* ADT dcpext1: crossbar UFP2, firmware SID23, scanout SID0. */ + dcpext1_iboot: display@502e00000 { + compatible = "apple,t8152-dcp-iboot"; + reg = <0x5 0x02e00000 0x0 0x74000>, + <0x3 0x03a12d00 0x0 0xc0>; + reg-names = "coproc", "coproc-psd"; + mboxes = <&dcpext1_mbox>; + iommus = <&dcpext1_dart 23>; + power-domains = <&ps_dispext1_cpu>; + dma-coherent; + apple,dp-source = <2>; + apple,usb-c-ports = <&dcp_iboot>; + + scanout { + iommus = <&dispext1_dart 0>; + dma-coherent; + }; + + }; + + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi new file mode 100644 index 00000000000000..b40923e9fec9e4 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J873g internal PCIe (apcie) port 2: the on-board 10GbE NIC (ADT + * /arm-io/apcie/pci-bridge2/lan0; the ADT names an aqc107, the device has + * PCI ID 10ec:8127 and identifies as a Realtek RTL8125CP, XID 0x708). + * iBoot leaves the APCIE power domains on and + * the root complex enabled, but the AUS5 PHY gated and the lanes assigned + * to port 0; the loader ungates the PHY, writes the ADT lane-cfg and applies + * the dart-apcie2 tunables first. Port setup follows the T602x/T8122 + * register layout. Port 0 (N1) is bus 1, port 2 is bus 2. + * Resources are from the 26A434 ADT: apcie, dart-apcie2, gpio0. + */ +#include + +/ { + aliases { + ethernet0 = ðernet0; + }; +}; + +/* + * The internal PCIe power states (ADT pmgr devices APCIE_GP and APCIE_SYS_GP, + * the latter's parent the former). iBoot leaves both on, and Linux cannot redo + * the PHY and lane setup the loader does on them, so they stay on, without + * automatic power management: APCIE_GP has no automatic state set and would + * be power gated by it. dart-apcie2 takes APCIE_SYS_GP, as on T8142. + */ +&pmgr { + ps_apcie_gp: power-controller@8c0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x8c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "apcie_gp"; + apple,no-auto-pm; + apple,always-on; + }; + + ps_apcie_sys_gp: power-controller@ec0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xec0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "apcie_sys_gp"; + power-domains = <&ps_apcie_gp>; + apple,no-auto-pm; + apple,always-on; + }; +}; + +/* + * dart-apcie2, described in t8152-peripherals.dtsi. The ADT window is + * 0x20000; keep the 0xc000 this port was brought up with, the size that + * pcie0_dart has in t8152-j873-n1.dtsi. + */ +&pcie2_dart { + reg = <0x3 0x8a000000 0x0 0xc000>; + power-domains = <&ps_apcie_sys_gp>; + status = "okay"; +}; + +&pcie { + reg = <0x1c 0xb0000000 0x0 0x1000000>, /* config */ + <0x3 0x8c000000 0x0 0x4000>, /* rc */ + <0x3 0x88028000 0x0 0x4000>, /* port0 */ + <0x3 0x8f010000 0x0 0x4000>, /* phy0 */ + <0x3 0x8a028000 0x0 0x4000>, /* port2 */ + <0x3 0x8f018000 0x0 0x4000>; /* phy2 */ + reg-names = "config", "rc", "port0", "phy0", "port2", "phy2"; + /* One per root port, indexed by the port number. */ + interrupts = , + , + ; + iommu-map = <0x100 &pcie0_dart 1 1>, + <0x101 &pcie0_dart 2 1>, + <0x102 &pcie0_dart 3 1>, + <0x200 &pcie2_dart 1 1>; + bus-range = <0 7>; + + port02: pci@2,0 { + device_type = "pci"; + reg = <0x1000 0x0 0x0 0x0 0x0>; + reset-gpios = <&pinctrl_ap 5 GPIO_ACTIVE_LOW>; + bus-range = <2 2>; + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &port02 0 0 0 0>, + <0 0 0 2 &port02 0 0 0 1>, + <0 0 0 3 &port02 0 0 0 2>, + <0 0 0 4 &port02 0 0 0 3>; + + ethernet0: ethernet@0,0 { + reg = <0x20000 0x0 0x0 0x0 0x0>; + /* Filled in by the loader from the ADT. */ + local-mac-address = [00 00 00 00 00 00]; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873-gpu.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-gpu.dtsi index 2166be04d41118..24ae92c61489cb 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-gpu.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-gpu.dtsi @@ -112,6 +112,7 @@ "gfx-data", "gfx1-data", "gfx-data-shared-ro", "gfx1-data-shared-ro"; mboxes = <&gfx_asc>, <&gfx1_asc>; + apple,clpc = <&clpc>; }; /* diff --git a/arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi index ffa33863f782b2..3f4ba8834178b1 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi @@ -8,6 +8,12 @@ #include / { + aliases { + /* Filled by the loader from ADT /chosen mac-address-*. */ + wifi0 = &n1_alpha; + bluetooth0 = &n1_beta; + }; + soc { pinctrl_ap: pinctrl@31a000000 { compatible = "apple,t8152-pinctrl", "apple,t8103-pinctrl"; @@ -65,6 +71,13 @@ #address-cells = <3>; #size-cells = <2>; ranges; + /* + * The N1's warm reset, as on J813 and J815: the J873g ADT's + * pci-bridge0 function-warm_reset names the same SMC key 'bpli' + * and argument. + */ + apple,function-warm-reset = <&smc 0x62706c69 0x1000000>; + apple,warm-reset-writes = <0x00010001 17000>, <0x00010001 20000>; interrupt-controller; #interrupt-cells = <1>; interrupt-map-mask = <0 0 0 7>; @@ -72,6 +85,20 @@ <0 0 0 2 &port00 0 0 0 1>, <0 0 0 3 &port00 0 0 0 2>, <0 0 0 4 &port00 0 0 0 3>; + + n1_alpha: wifi@0,1 { + compatible = "pci106b,1902"; + reg = <0x10100 0x0 0x0 0x0 0x0>; + /* Filled by the loader */ + local-mac-address = [00 00 00 00 00 00]; + }; + + n1_beta: bluetooth@0,2 { + compatible = "pci106b,1903"; + reg = <0x10200 0x0 0x0 0x0 0x0>; + /* Filled by the loader */ + local-bd-address = [00 00 00 00 00 00]; + }; }; }; }; diff --git a/arch/arm64/boot/dts/apple/t8152-j873-nvme.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-nvme.dtsi new file mode 100644 index 00000000000000..741162fe483ff1 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-nvme.dtsi @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J873g ANS2 NVMe. + * iBoot leaves the ANS firmware running with the NVMe controller disabled; + * the driver wakes it with a fresh RTKit handshake (as m1n1 does). NVMe + * registers and NVMMU share the 0x325cc0000 window. The mailbox is the ANS + * post-office window (msgbox-mailbox-num 3, no alias: 0x316000000 + + * 0x10300), the SMC mailbox's counted FIFO. Its interrupts are the first two + * of the ADT's ans list, in the order the SMC and DCP mailboxes' ADT lists + * give theirs: send-empty, recv-not-empty. No PMGR power or reset yet. + * Resources are from the 26A434 ADT: ans, sart-ans. + */ + +/ { + soc { + ans_mbox: mailbox@316010300 { + compatible = "apple,t8152-ans-mailbox", + "apple,t8152-smc-mailbox"; + reg = <0x3 0x16010300 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + sart: iommu@325c50000 { + compatible = "apple,t8152-sart"; + reg = <0x3 0x25c50000 0x0 0xc000>; + }; + + nvme: nvme@325cc0000 { + compatible = "apple,t8152-nvme-ans2"; + reg = <0x3 0x25cc0000 0x0 0x60000>, + <0x3 0x21600000 0x0 0x4000>; + reg-names = "nvme", "ans"; + interrupts = ; + mboxes = <&ans_mbox>; + apple,sart = <&sart>; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873-qspi.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-qspi.dtsi index c03fbf04b24e4c..538511e3ffc170 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-qspi.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-qspi.dtsi @@ -25,7 +25,8 @@ "syscon", "simple-mfd"; #address-cells = <1>; #size-cells = <1>; - reg = <0x3 0x700000 0x0 0x14000>; + /* ADT pmgr reg[32]: power states up to DISP_CPU at 0x14000 */ + reg = <0x3 0x700000 0x0 0x1c000>; }; qspi: spi@331118000 { diff --git a/arch/arm64/boot/dts/apple/t8152-j873-thermal.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-thermal.dtsi new file mode 100644 index 00000000000000..e5fcb164591238 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-thermal.dtsi @@ -0,0 +1,993 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * Apple Mac mini (M6, J873g): SMC temperature sensors and CPU thermal zones. + * + * The SMC float temperature channels that read back stable values on the + * J873g; their physical locations are not established, so each keeps its SMC + * key as label. TVMD and the Tz* channels that read zero are left out. + * + * The limits are the machine's own: the J873g ADT's PMP temp-sensor table + * gives every CPU die sensor a 110 C target and a 125 C maximum, as on the + * other M4/M5-class Macs. The SMC's CPU die channels, Te* for the E cluster + * and Tp* for the P/M cluster, therefore each get a zone with a passive trip + * at the target, throttling both CPU clusters through cpufreq cooling, and a + * critical trip at the maximum. The other channels are reported only: the + * ADT gives them no limit. The SMC's own fan policy is no limit either; in + * its automatic mode it leaves the fan at its 1000 RPM minimum even at 93 C + * under sustained full load. + * + * Sensor list from Acelogic's J873 bring-up (linux-aurora j873). + */ + +#include + +&m6_smc_hwmon { + temperature-TCMb { apple,key-id = "TCMb"; label = "SMC TCMb"; }; + temperature-TH0a { apple,key-id = "TH0a"; label = "SMC TH0a"; }; + temperature-TH0b { apple,key-id = "TH0b"; label = "SMC TH0b"; }; + temperature-TH0x { apple,key-id = "TH0x"; label = "SMC TH0x"; }; + temperature-THSP { apple,key-id = "THSP"; label = "SMC THSP"; }; + temperature-TIED { apple,key-id = "TIED"; label = "SMC TIED"; }; + temperature-TMVR { apple,key-id = "TMVR"; label = "SMC TMVR"; }; + temperature-TN00 { apple,key-id = "TN00"; label = "SMC TN00"; }; + temperature-TN01 { apple,key-id = "TN01"; label = "SMC TN01"; }; + temperature-TPD0 { apple,key-id = "TPD0"; label = "SMC TPD0"; }; + temperature-TPD1 { apple,key-id = "TPD1"; label = "SMC TPD1"; }; + temperature-TPD2 { apple,key-id = "TPD2"; label = "SMC TPD2"; }; + temperature-TPD3 { apple,key-id = "TPD3"; label = "SMC TPD3"; }; + temperature-TPD4 { apple,key-id = "TPD4"; label = "SMC TPD4"; }; + temperature-TPD7 { apple,key-id = "TPD7"; label = "SMC TPD7"; }; + temperature-TPD9 { apple,key-id = "TPD9"; label = "SMC TPD9"; }; + temperature-TPDB { apple,key-id = "TPDB"; label = "SMC TPDB"; }; + temperature-TPDD { apple,key-id = "TPDD"; label = "SMC TPDD"; }; + temperature-TPDG { apple,key-id = "TPDG"; label = "SMC TPDG"; }; + temperature-TPDH { apple,key-id = "TPDH"; label = "SMC TPDH"; }; + temperature-TPDI { apple,key-id = "TPDI"; label = "SMC TPDI"; }; + temperature-TPDJ { apple,key-id = "TPDJ"; label = "SMC TPDJ"; }; + temperature-TPDK { apple,key-id = "TPDK"; label = "SMC TPDK"; }; + temperature-TPDL { apple,key-id = "TPDL"; label = "SMC TPDL"; }; + temperature-TPDM { apple,key-id = "TPDM"; label = "SMC TPDM"; }; + temperature-TPDN { apple,key-id = "TPDN"; label = "SMC TPDN"; }; + temperature-TPDX { apple,key-id = "TPDX"; label = "SMC TPDX"; }; + temperature-TPMP { apple,key-id = "TPMP"; label = "SMC TPMP"; }; + temperature-TPSD { apple,key-id = "TPSD"; label = "SMC TPSD"; }; + temperature-TPSP { apple,key-id = "TPSP"; label = "SMC TPSP"; }; + temperature-TRD5 { apple,key-id = "TRD5"; label = "SMC TRD5"; }; + temperature-TRD6 { apple,key-id = "TRD6"; label = "SMC TRD6"; }; + temperature-TRD8 { apple,key-id = "TRD8"; label = "SMC TRD8"; }; + temperature-TRDA { apple,key-id = "TRDA"; label = "SMC TRDA"; }; + temperature-TRDC { apple,key-id = "TRDC"; label = "SMC TRDC"; }; + temperature-TRDE { apple,key-id = "TRDE"; label = "SMC TRDE"; }; + temperature-TRDF { apple,key-id = "TRDF"; label = "SMC TRDF"; }; + temperature-TRDG { apple,key-id = "TRDG"; label = "SMC TRDG"; }; + temperature-TRDX { apple,key-id = "TRDX"; label = "SMC TRDX"; }; + temperature-TSCB { apple,key-id = "TSCB"; label = "SMC TSCB"; }; + temperature-TSCD { apple,key-id = "TSCD"; label = "SMC TSCD"; }; + temperature-TT0P { apple,key-id = "TT0P"; label = "SMC TT0P"; }; + temperature-TUVS { apple,key-id = "TUVS"; label = "SMC TUVS"; }; + temperature-TVD0 { apple,key-id = "TVD0"; label = "SMC TVD0"; }; + temperature-TVDA { apple,key-id = "TVDA"; label = "SMC TVDA"; }; + temperature-TVDC { apple,key-id = "TVDC"; label = "SMC TVDC"; }; + temperature-TVDE { apple,key-id = "TVDE"; label = "SMC TVDE"; }; + temperature-TVDG { apple,key-id = "TVDG"; label = "SMC TVDG"; }; + temperature-TVDP { apple,key-id = "TVDP"; label = "SMC TVDP"; }; + temperature-TVN0 { apple,key-id = "TVN0"; label = "SMC TVN0"; }; + temperature-TVN1 { apple,key-id = "TVN1"; label = "SMC TVN1"; }; + temperature-TVNS { apple,key-id = "TVNS"; label = "SMC TVNS"; }; + temperature-TVS0 { apple,key-id = "TVS0"; label = "SMC TVS0"; }; + temperature-TW0P { apple,key-id = "TW0P"; label = "SMC TW0P"; }; + temperature-Ta0O { apple,key-id = "Ta0O"; label = "SMC Ta0O"; }; + temperature-Ta0P { apple,key-id = "Ta0P"; label = "SMC Ta0P"; }; + temperature-Ta0Q { apple,key-id = "Ta0Q"; label = "SMC Ta0Q"; }; + temperature-Ta0S { apple,key-id = "Ta0S"; label = "SMC Ta0S"; }; + temperature-Ta0T { apple,key-id = "Ta0T"; label = "SMC Ta0T"; }; + temperature-Ta0V { apple,key-id = "Ta0V"; label = "SMC Ta0V"; }; + temperature-Ta0b { apple,key-id = "Ta0b"; label = "SMC Ta0b"; }; + temperature-Ta0c { apple,key-id = "Ta0c"; label = "SMC Ta0c"; }; + temperature-Ta0e { apple,key-id = "Ta0e"; label = "SMC Ta0e"; }; + temperature-Ta0f { apple,key-id = "Ta0f"; label = "SMC Ta0f"; }; + temperature-Ta0g { apple,key-id = "Ta0g"; label = "SMC Ta0g"; }; + temperature-Ta0h { apple,key-id = "Ta0h"; label = "SMC Ta0h"; }; + temperature-Te07 { apple,key-id = "Te07"; label = "SMC Te07"; }; + temperature-Te08 { apple,key-id = "Te08"; label = "SMC Te08"; }; + temperature-Te09 { apple,key-id = "Te09"; label = "SMC Te09"; }; + temperature-Te0c { apple,key-id = "Te0c"; label = "SMC Te0c"; }; + temperature-Te0e { apple,key-id = "Te0e"; label = "SMC Te0e"; }; + temperature-Te0f { apple,key-id = "Te0f"; label = "SMC Te0f"; }; + temperature-Te0g { apple,key-id = "Te0g"; label = "SMC Te0g"; }; + temperature-Te0h { apple,key-id = "Te0h"; label = "SMC Te0h"; }; + temperature-Te0i { apple,key-id = "Te0i"; label = "SMC Te0i"; }; + temperature-TfC1 { apple,key-id = "TfC1"; label = "SMC TfC1"; }; + temperature-TfCD { apple,key-id = "TfCD"; label = "SMC TfCD"; }; + temperature-Tg01 { apple,key-id = "Tg01"; label = "SMC Tg01"; }; + temperature-Tg07 { apple,key-id = "Tg07"; label = "SMC Tg07"; }; + temperature-Tg08 { apple,key-id = "Tg08"; label = "SMC Tg08"; }; + temperature-Tg09 { apple,key-id = "Tg09"; label = "SMC Tg09"; }; + temperature-Tg0a { apple,key-id = "Tg0a"; label = "SMC Tg0a"; }; + temperature-Tg0b { apple,key-id = "Tg0b"; label = "SMC Tg0b"; }; + temperature-Tg0c { apple,key-id = "Tg0c"; label = "SMC Tg0c"; }; + temperature-Tg0d { apple,key-id = "Tg0d"; label = "SMC Tg0d"; }; + temperature-Tg10 { apple,key-id = "Tg10"; label = "SMC Tg10"; }; + temperature-Tg17 { apple,key-id = "Tg17"; label = "SMC Tg17"; }; + temperature-Tg1a { apple,key-id = "Tg1a"; label = "SMC Tg1a"; }; + temperature-Tg1b { apple,key-id = "Tg1b"; label = "SMC Tg1b"; }; + temperature-Tg1c { apple,key-id = "Tg1c"; label = "SMC Tg1c"; }; + temperature-Tg1d { apple,key-id = "Tg1d"; label = "SMC Tg1d"; }; + temperature-Tg1e { apple,key-id = "Tg1e"; label = "SMC Tg1e"; }; + temperature-Tg1f { apple,key-id = "Tg1f"; label = "SMC Tg1f"; }; + temperature-Tg1g { apple,key-id = "Tg1g"; label = "SMC Tg1g"; }; + temperature-Tg1h { apple,key-id = "Tg1h"; label = "SMC Tg1h"; }; + temperature-Tp05 { apple,key-id = "Tp05"; label = "SMC Tp05"; }; + temperature-Tp07 { apple,key-id = "Tp07"; label = "SMC Tp07"; }; + temperature-Tp09 { apple,key-id = "Tp09"; label = "SMC Tp09"; }; + temperature-Tp0A { apple,key-id = "Tp0A"; label = "SMC Tp0A"; }; + temperature-Tp0E { apple,key-id = "Tp0E"; label = "SMC Tp0E"; }; + temperature-Tp0G { apple,key-id = "Tp0G"; label = "SMC Tp0G"; }; + temperature-Tp0I { apple,key-id = "Tp0I"; label = "SMC Tp0I"; }; + temperature-Tp0L { apple,key-id = "Tp0L"; label = "SMC Tp0L"; }; + temperature-Tp0b { apple,key-id = "Tp0b"; label = "SMC Tp0b"; }; + temperature-Tp0d { apple,key-id = "Tp0d"; label = "SMC Tp0d"; }; + temperature-Tp0g { apple,key-id = "Tp0g"; label = "SMC Tp0g"; }; + temperature-Tp0j { apple,key-id = "Tp0j"; label = "SMC Tp0j"; }; + temperature-Tp0m { apple,key-id = "Tp0m"; label = "SMC Tp0m"; }; + temperature-Tp0o { apple,key-id = "Tp0o"; label = "SMC Tp0o"; }; + temperature-Tp0r { apple,key-id = "Tp0r"; label = "SMC Tp0r"; }; + temperature-Tp0t { apple,key-id = "Tp0t"; label = "SMC Tp0t"; }; + temperature-Tp0u { apple,key-id = "Tp0u"; label = "SMC Tp0u"; }; + temperature-Tp0w { apple,key-id = "Tp0w"; label = "SMC Tp0w"; }; + temperature-Tp0x { apple,key-id = "Tp0x"; label = "SMC Tp0x"; }; + temperature-Tp0y { apple,key-id = "Tp0y"; label = "SMC Tp0y"; }; + temperature-Tp0z { apple,key-id = "Tp0z"; label = "SMC Tp0z"; }; + temperature-Ts00 { apple,key-id = "Ts00"; label = "SMC Ts00"; }; + temperature-Ts01 { apple,key-id = "Ts01"; label = "SMC Ts01"; }; + temperature-Ts02 { apple,key-id = "Ts02"; label = "SMC Ts02"; }; + temperature-Ts03 { apple,key-id = "Ts03"; label = "SMC Ts03"; }; + temperature-Ts04 { apple,key-id = "Ts04"; label = "SMC Ts04"; }; + temperature-Ts05 { apple,key-id = "Ts05"; label = "SMC Ts05"; }; + temperature-Ts06 { apple,key-id = "Ts06"; label = "SMC Ts06"; }; + temperature-Ts07 { apple,key-id = "Ts07"; label = "SMC Ts07"; }; + temperature-Ts08 { apple,key-id = "Ts08"; label = "SMC Ts08"; }; +}; +/ { + thermal-zones { + smc-te07-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 66>; + + trips { + m6_Te07_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te07_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te08-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 67>; + + trips { + m6_Te08_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te08_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te09-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 68>; + + trips { + m6_Te09_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te09_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te0c-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 69>; + + trips { + m6_Te0c_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te0c_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te0e-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 70>; + + trips { + m6_Te0e_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te0e_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te0f-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 71>; + + trips { + m6_Te0f_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te0f_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te0g-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 72>; + + trips { + m6_Te0g_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te0g_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te0h-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 73>; + + trips { + m6_Te0h_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te0h_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te0i-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 74>; + + trips { + m6_Te0i_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te0i_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp05-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 95>; + + trips { + m6_Tp05_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp05_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp07-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 96>; + + trips { + m6_Tp07_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp07_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp09-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 97>; + + trips { + m6_Tp09_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp09_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0a-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 98>; + + trips { + m6_Tp0A_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0A_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0e-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 99>; + + trips { + m6_Tp0E_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0E_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0g-2-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 100>; + + trips { + m6_Tp0G_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0G_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0i-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 101>; + + trips { + m6_Tp0I_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0I_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0l-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 102>; + + trips { + m6_Tp0L_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0L_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0b-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 103>; + + trips { + m6_Tp0b_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0b_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0d-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 104>; + + trips { + m6_Tp0d_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0d_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0g-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 105>; + + trips { + m6_Tp0g_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0g_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0j-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 106>; + + trips { + m6_Tp0j_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0j_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0m-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 107>; + + trips { + m6_Tp0m_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0m_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0o-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 108>; + + trips { + m6_Tp0o_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0o_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0r-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 109>; + + trips { + m6_Tp0r_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0r_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0t-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 110>; + + trips { + m6_Tp0t_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0t_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0u-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 111>; + + trips { + m6_Tp0u_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0u_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0w-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 112>; + + trips { + m6_Tp0w_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0w_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0x-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 113>; + + trips { + m6_Tp0x_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0x_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0y-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 114>; + + trips { + m6_Tp0y_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0y_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0z-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 115>; + + trips { + m6_Tp0z_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0z_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi new file mode 100644 index 00000000000000..d348e83d3f978e --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi @@ -0,0 +1,422 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J873g USB host bring-up: usb-drd1 (back-left port, USB2) and usb-drd2 + * (front ports via the on-board hub, USB2 and USB3). + * The loader powers the controllers and sets up the USB2 side of their ATC + * PHYs for host mode before Linux starts (there is no T8152 USB2 PHY or Type-C + * support yet). + * The controllers are described by their DWC3 core region, as hosts behind + * their two DARTs (apple,t8152-dwc3); their PHY reset, and on the Type-C port + * the role switch, exist but are left to the loader. + * usb-drd2's hub is wired to ATC2's PHY without a Type-C mux, so Linux brings + * that PHY up in USB3 mode (atc2_phy). + * The rear ports' ATC PHYs (atc0_phy, atc1_phy, atc3_phy) run CIO mode for + * USB4 alone: their DisplayPort alt mode is the display controllers', which + * take a PHY through its DP PHY, and their USB2 side stays with the loader. + * Resources are from the 26A434 ADT: dart-usb1/2, usb-drd1/2 (on atc-phy1 and + * atc-phy2), atc-phy0-3 and the pmgr devices ATCn_USB_AON, ATC1/2_USB and + * ATCn_COMMON_DP_0/1. + * + * dart-usb1 and dart-usb2 each have two DART instances (ADT reg[0] and + * reg[1], 0xc000 each, sharing one interrupt). t8152-peripherals.dtsi lists + * both windows on one node (dwc3_1_dart, dwc3_2_dart), but the DART driver + * drives one instance per node and the binding reads a second reg entry as + * DAPF or auxiliary registers. Keep instance 0 on the shared node, with its + * own window only, and describe instance 1 as a node of its own. + */ + +#include + +&dwc3_1_dart { + reg = <0x4 0x0b020000 0x0 0xc000>; + power-domains = <&ps_atc1_usb>; + status = "okay"; +}; + +&dwc3_2_dart { + reg = <0x3 0x83020000 0x0 0xc000>; + power-domains = <&ps_atc2_usb>; + status = "okay"; +}; + +/ { + aliases { + /* aura copies each ATC PHY's tunables from ADT atc-phyN here. */ + atcphy0 = &atc0_phy; + atcphy1 = &atc1_phy; + atcphy2 = &atc2_phy; + atcphy3 = &atc3_phy; + }; + + soc { + dwc3_1_dart_1: iommu@40b040000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x4 0x0b040000 0x0 0xc000>; + interrupts = ; + #iommu-cells = <1>; + power-domains = <&ps_atc1_usb>; + }; + + usb1: usb@40a430000 { + compatible = "apple,t8152-dwc3"; + reg = <0x4 0x0a430000 0x0 0xcd00>; + interrupts = ; + dr_mode = "host"; + maximum-speed = "high-speed"; + iommus = <&dwc3_1_dart 0>, <&dwc3_1_dart_1 1>; + power-domains = <&ps_atc1_usb>; + snps,dis_u2_susphy_quirk; + snps,dis_u3_susphy_quirk; + }; + + dwc3_2_dart_1: iommu@383040000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x3 0x83040000 0x0 0xc000>; + interrupts = ; + #iommu-cells = <1>; + power-domains = <&ps_atc2_usb>; + }; + + /* + * The ATCs' PMGR power states (ADT pmgr devices ATCn_COMMON_DP_0/1 + * from 0x308290000 and ATCn_USB_AON/USB from 0x308290100, 0x40 + * apart per ATC). Each ATC's three are those its PHY needs, and + * ATC1_USB and ATC2_USB are the USB controllers' states. The + * T8152 USB3 and CIO bring-ups run them without automatic power + * management. + * + * The ADT also gives usb-drd1/2 service-gates 175/176, but those + * PSD service blocks (0x303a1af00, 0x303a1b000) take a bus error + * from the CPU. The loader leaves ATC1/2_USB on; with USB_AON + * they hold the controllers' reset and the USB2 PHY setup it + * did, which Linux cannot redo yet, so they stay on. + */ + pmgr_atc: power-management@308290000 { + compatible = "apple,t8152-pmgr", "apple,t8103-pmgr", + "syscon", "simple-mfd"; + #address-cells = <1>; + #size-cells = <1>; + reg = <0x3 0x08290000 0x0 0x1000>; + + ps_atc0_common_dp_0: power-controller@0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_common_dp_0"; + apple,no-auto-pm; + }; + + ps_atc0_common_dp_1: power-controller@20 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x20 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_common_dp_1"; + apple,no-auto-pm; + }; + + ps_atc1_common_dp_0: power-controller@40 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x40 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_common_dp_0"; + apple,no-auto-pm; + }; + + ps_atc1_common_dp_1: power-controller@60 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x60 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_common_dp_1"; + apple,no-auto-pm; + }; + + ps_atc2_common_dp_0: power-controller@80 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x80 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_common_dp_0"; + apple,no-auto-pm; + }; + + ps_atc2_common_dp_1: power-controller@a0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xa0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_common_dp_1"; + apple,no-auto-pm; + }; + + ps_atc3_common_dp_0: power-controller@c0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xc0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_common_dp_0"; + apple,no-auto-pm; + }; + + ps_atc3_common_dp_1: power-controller@e0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xe0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_common_dp_1"; + apple,no-auto-pm; + }; + + /* + * The USB_AON states are kept on: each holds its USB + * controller's reset and PIPE handler state, and the + * rear ports' controllers stay with the loader. + */ + ps_atc0_usb_aon: power-controller@100 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x100 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_usb_aon"; + apple,no-auto-pm; + apple,always-on; + }; + + ps_atc1_usb_aon: power-controller@140 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x140 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_usb_aon"; + apple,no-auto-pm; + apple,always-on; + }; + + ps_atc1_usb: power-controller@160 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x160 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_usb"; + power-domains = <&ps_atc1_usb_aon>; + apple,no-auto-pm; + apple,always-on; + }; + + /* + * Kept on: it holds the USB controller's reset and the + * PIPE handler state the loader set up. Switched off, the + * controller stays in reset until the next boot. + */ + ps_atc2_usb_aon: power-controller@180 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x180 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_usb_aon"; + apple,no-auto-pm; + apple,always-on; + }; + + ps_atc2_usb: power-controller@1a0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x1a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_usb"; + power-domains = <&ps_atc2_usb_aon>; + apple,no-auto-pm; + apple,always-on; + }; + + ps_atc3_usb_aon: power-controller@1c0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x1c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_usb_aon"; + apple,no-auto-pm; + apple,always-on; + }; + }; + + /* + * The rear ports' ATCs' common domains: PSD services 55, 56 and 58 + * (ADT atc-phy0/1/3 clock-gates). + */ + ps_atc0_common: power-controller@303a13700 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x03a13700 0x0 0x100>; + #power-domain-cells = <0>; + label = "atc0_common"; + }; + + ps_atc1_common: power-controller@303a13800 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x03a13800 0x0 0x100>; + #power-domain-cells = <0>; + label = "atc1_common"; + }; + + ps_atc3_common: power-controller@303a13a00 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x03a13a00 0x0 0x100>; + #power-domain-cells = <0>; + label = "atc3_common"; + }; + + /* ATC2's common domain: PSD service 57 (ADT atc-phy2 clock-gates). */ + ps_atc2_common: power-controller@303a13900 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x03a13900 0x0 0x100>; + #power-domain-cells = <0>; + label = "atc2_common"; + }; + + /* + * ADT atc-phy2 as usb-drd2's USB3 PHY: the hub is wired to its + * lanes directly. The power domains are listed in the order the + * PHY needs them powered up. Its tunables are the atc-phy2 + * tunable_* groups that apply to USB3 on lane 0, applied as + * common-a before lane 0 is powered up and the crossbar set, then + * common-b and lane0-usb. Some of them differ between the four + * ATCs of the same Mac (calibration), so the bootloader copies + * them from the Mac's own ADT, through the atcphy2 alias. Without + * them the PHY runs USB2 only. + */ + atc2_phy: phy@383000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x3 0x83000000 0x0 0x84000>, + <0x3 0x82414000 0x0 0x4000>; + reg-names = "core", "pipehandler"; + #phy-cells = <1>; + apple,fixed-usb3; + power-domains = <&ps_atc2_usb_aon>, <&ps_atc2_common>, + <&ps_atc2_common_dp_0>, <&ps_atc2_common_dp_1>; + }; + + /* + * USB-C Back-middle: ADT atc-phy0 in CIO mode, see atc2_phy for the + * layout. The bootloader copies the atc-phy0 groups the CIO mode + * applies, through the atcphy0 alias: the common and PLL defaults + * as common-a, the fabric, PLL and the other common groups as + * common-b, and each lane's groups. + */ + atc0_phy: phy@403000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x4 0x03000000 0x0 0x84000>; + reg-names = "core"; + #phy-cells = <1>; + orientation-switch; + mode-switch; + power-domains = <&ps_atc0_usb_aon>, <&ps_atc0_common>, + <&ps_atc0_common_dp_0>, <&ps_atc0_common_dp_1>; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + atc0_phy_typec: endpoint { + remote-endpoint = <&typec0_ss>; + }; + }; + }; + }; + + /* + * USB-C Back-left: ADT atc-phy1 in CIO mode, see atc2_phy for the + * layout. The bootloader copies the atc-phy1 groups the CIO mode + * applies, through the atcphy1 alias: the common and PLL defaults + * as common-a, the fabric, PLL and the other common groups as + * common-b, and each lane's groups. + */ + atc1_phy: phy@40b000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x4 0x0b000000 0x0 0x84000>; + reg-names = "core"; + #phy-cells = <1>; + orientation-switch; + mode-switch; + power-domains = <&ps_atc1_usb_aon>, <&ps_atc1_common>, + <&ps_atc1_common_dp_0>, <&ps_atc1_common_dp_1>; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + atc1_phy_typec: endpoint { + remote-endpoint = <&typec1_ss>; + }; + }; + }; + }; + + /* + * USB-C Back-right: ADT atc-phy3 in CIO mode, see atc2_phy for the + * layout. The bootloader copies the atc-phy3 groups the CIO mode + * applies, through the atcphy3 alias: the common and PLL defaults + * as common-a, the fabric, PLL and the other common groups as + * common-b, and each lane's groups. + */ + atc3_phy: phy@413000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x4 0x13000000 0x0 0x84000>; + reg-names = "core"; + #phy-cells = <1>; + orientation-switch; + mode-switch; + power-domains = <&ps_atc3_usb_aon>, <&ps_atc3_common>, + <&ps_atc3_common_dp_0>, <&ps_atc3_common_dp_1>; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + atc3_phy_typec: endpoint { + remote-endpoint = <&typec3_ss>; + }; + }; + }; + }; + + /* usb-drd2: on-board VL822 hub behind the two front USB-C ports. */ + usb2: usb@382430000 { + compatible = "apple,t8152-dwc3"; + reg = <0x3 0x82430000 0x0 0xcd00>; + interrupts = ; + dr_mode = "host"; + phys = <&atc2_phy PHY_TYPE_USB3>; + phy-names = "usb3-phy"; + iommus = <&dwc3_2_dart 0>, <&dwc3_2_dart_1 1>; + power-domains = <&ps_atc2_usb>; + snps,dis_u2_susphy_quirk; + snps,dis_u3_susphy_quirk; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb4.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb4.dtsi new file mode 100644 index 00000000000000..ce96f4fb0cd91a --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-usb4.dtsi @@ -0,0 +1,690 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J873g rear USB-C ports in USB4 mode: three ACIO host routers with their + * NHI, PCIe-C tunnel and DARTs, and the T8152 PSD services they need. Each + * router's Thunderbolt switch is linked to the USB4 port (port@4) of its + * port's usb-c-connector, whose PD controller driver starts and stops it + * after it set the port's ATC PHY to CIO mode. + * + * Generated from the J873g ADT (27.2 iBoot): /arm-io/acio{0,1,3}, acio-cpuN, + * dart-acioN, apciecN and dart-apciecN. The tunables of the routers, their + * NHIs, PCIe-C ports and DARTs, and each router's DROM, are not in this file: + * the bootloader copies them from the Mac's own ADT (acioN, apciecN, + * dart-acioN, dart-apciecN) into the nodes the usb4-N aliases name, and the + * DARTs by their address. + * + * Each router coprocessor's mailbox is the 0x80 window at +0x80 of its + * acio-cpuN register block, with the SMC mailbox's counted FIFOs. Its + * interrupts are acio-cpuN's two, in the order the SMC mailbox's ADT list + * gives its own: send-empty, recv-not-empty. + */ + +#include + +/ { + aliases { + /* aura copies the router tunables and DROMs here, the AP firmware one too. */ + usb4-0-acio = &usb4_0; + usb4-0-pcie-adapter = &usb4_0; + usb4-0-nhi = &usb4_0_nhi; + usb4-1-acio = &usb4_1; + usb4-1-pcie-adapter = &usb4_1; + usb4-1-nhi = &usb4_1_nhi; + usb4-3-acio = &usb4_3; + usb4-3-pcie-adapter = &usb4_3; + usb4-3-nhi = &usb4_3_nhi; + /* aura copies the PCIe-C tunables here. */ + usb4-0-pcie = &usb4_0_pcie; + usb4-1-pcie = &usb4_1_pcie; + usb4-3-pcie = &usb4_3_pcie; + }; + + soc { + cio_reset: reset-controller@300780000 { + compatible = "apple,t8152-cio-reset"; + reg = <0x3 0x00780000 0x0 0x4000>; + #reset-cells = <1>; + }; + + cio_psd59: power-controller@303a13b00 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a13b00 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd60: power-controller@303a13c00 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a13c00 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd62: power-controller@303a13e00 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a13e00 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd63: power-controller@303a13f00 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a13f00 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd64: power-controller@303a14000 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a14000 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd66: power-controller@303a14200 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a14200 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd67: power-controller@303a14300 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a14300 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd68: power-controller@303a14400 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a14400 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd70: power-controller@303a14600 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a14600 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd86: power-controller@303a15600 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a15600 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd87: power-controller@303a15700 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a15700 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd89: power-controller@303a15900 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a15900 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio0_mbox: mailbox@401178080 { + compatible = "apple,t8152-cio-mailbox", + "apple,t8152-smc-mailbox"; + reg = <0x4 0x1178080 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* acio@ avoids the bootloader's legacy cio@ register-index fixup. */ + usb4_0: acio@401ac0000 { + compatible = "apple,t8152-usb4-acio"; + reg = <0x4 0x1ac0000 0x0 0xc000>, + <0x4 0x1080000 0x0 0x26000>, + <0x4 0x1e44000 0x0 0x4000>, + <0x4 0x1c80000 0x0 0x4000>; + reg-names = "rc", "sram", "pcie-adapter", "router-ap-fw"; + #address-cells = <1>; + #size-cells = <1>; + /* The router window and the shared Gen3 TLB invalidation aperture. */ + ranges = <0x0 0x4 0x1000000 0x1000000>, + <0x1000000 0x2 0x0 0x1000>; + nonposted-mmio; + mboxes = <&cio0_mbox>; + resets = <&cio_reset 0>; + power-domains = <&cio_psd59>, <&cio_psd63>, <&cio_psd67>, <&cio_psd86>; + pinctrl-names = "lstx"; + pinctrl-0 = <&usb4_0_lstx_pins>; + lstx-gpios = <&pinctrl_aop 19 GPIO_ACTIVE_HIGH>; + thunderbolt-switch; + apple,pcie-tunnel = <&usb4_0_tunnel>; + + usb4_0_dart: iommu@a80000 { + compatible = "apple,t8152-acio-dart"; + reg = <0xa80000 0xc000>, + <0x1000100 0x10>; + reg-names = "dart", "tlbi"; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd59>; + apple,dma-range = <0x100 0x0 0x10 0x0>; + }; + + usb4_0_nhi: nhi@f00000 { + compatible = "apple,t8152-usb4-nhi"; + reg = <0xf00000 0x100000>; + reg-names = "nhi"; + interrupt-parent = <&aic>; + interrupts = , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + ; + interrupt-names = "txring0", "txring1", "txring2", + "txring3", "txring4", "txring5", + "txring6", "txring7", "txring8", + "txring9", "txring10", "txring11", + "rxring0", "rxring1", "rxring2", + "rxring3", "rxring4", "rxring5", + "rxring6", "rxring7", "rxring8", + "rxring9", "rxring10", "rxring11"; + iommus = <&usb4_0_dart 0>, <&usb4_0_dart 1>, <&usb4_0_dart 2>, + <&usb4_0_dart 3>, <&usb4_0_dart 4>, <&usb4_0_dart 5>, + <&usb4_0_dart 6>, <&usb4_0_dart 7>, <&usb4_0_dart 8>, + <&usb4_0_dart 9>, <&usb4_0_dart 10>, <&usb4_0_dart 11>, + <&usb4_0_dart 16>, <&usb4_0_dart 17>, <&usb4_0_dart 18>, + <&usb4_0_dart 19>, <&usb4_0_dart 20>, <&usb4_0_dart 21>, + <&usb4_0_dart 22>, <&usb4_0_dart 23>, <&usb4_0_dart 24>, + <&usb4_0_dart 25>, <&usb4_0_dart 26>, <&usb4_0_dart 27>; + /* Filled by the bootloader. */ + apple,thunderbolt-drom = [00]; + }; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@1 { + reg = <1>; + usb4_0_sw: endpoint { + remote-endpoint = <&typec0_usb4>; + }; + }; + }; + }; + + cio1_mbox: mailbox@409178080 { + compatible = "apple,t8152-cio-mailbox", + "apple,t8152-smc-mailbox"; + reg = <0x4 0x9178080 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* acio@ avoids the bootloader's legacy cio@ register-index fixup. */ + usb4_1: acio@409ac0000 { + compatible = "apple,t8152-usb4-acio"; + reg = <0x4 0x9ac0000 0x0 0xc000>, + <0x4 0x9080000 0x0 0x26000>, + <0x4 0x9e44000 0x0 0x4000>, + <0x4 0x9c80000 0x0 0x4000>; + reg-names = "rc", "sram", "pcie-adapter", "router-ap-fw"; + #address-cells = <1>; + #size-cells = <1>; + /* The router window and the shared Gen3 TLB invalidation aperture. */ + ranges = <0x0 0x4 0x9000000 0x1000000>, + <0x1000000 0x2 0x0 0x1000>; + nonposted-mmio; + mboxes = <&cio1_mbox>; + resets = <&cio_reset 1>; + power-domains = <&cio_psd60>, <&cio_psd64>, <&cio_psd68>, <&cio_psd87>; + pinctrl-names = "lstx"; + pinctrl-0 = <&usb4_1_lstx_pins>; + lstx-gpios = <&pinctrl_aop 21 GPIO_ACTIVE_HIGH>; + thunderbolt-switch; + apple,pcie-tunnel = <&usb4_1_tunnel>; + + usb4_1_dart: iommu@a80000 { + compatible = "apple,t8152-acio-dart"; + reg = <0xa80000 0xc000>, + <0x1000180 0x10>; + reg-names = "dart", "tlbi"; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd60>; + apple,dma-range = <0x100 0x0 0x10 0x0>; + }; + + usb4_1_nhi: nhi@f00000 { + compatible = "apple,t8152-usb4-nhi"; + reg = <0xf00000 0x100000>; + reg-names = "nhi"; + interrupt-parent = <&aic>; + interrupts = , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + ; + interrupt-names = "txring0", "txring1", "txring2", + "txring3", "txring4", "txring5", + "txring6", "txring7", "txring8", + "txring9", "txring10", "txring11", + "rxring0", "rxring1", "rxring2", + "rxring3", "rxring4", "rxring5", + "rxring6", "rxring7", "rxring8", + "rxring9", "rxring10", "rxring11"; + iommus = <&usb4_1_dart 0>, <&usb4_1_dart 1>, <&usb4_1_dart 2>, + <&usb4_1_dart 3>, <&usb4_1_dart 4>, <&usb4_1_dart 5>, + <&usb4_1_dart 6>, <&usb4_1_dart 7>, <&usb4_1_dart 8>, + <&usb4_1_dart 9>, <&usb4_1_dart 10>, <&usb4_1_dart 11>, + <&usb4_1_dart 16>, <&usb4_1_dart 17>, <&usb4_1_dart 18>, + <&usb4_1_dart 19>, <&usb4_1_dart 20>, <&usb4_1_dart 21>, + <&usb4_1_dart 22>, <&usb4_1_dart 23>, <&usb4_1_dart 24>, + <&usb4_1_dart 25>, <&usb4_1_dart 26>, <&usb4_1_dart 27>; + /* Filled by the bootloader. */ + apple,thunderbolt-drom = [00]; + }; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@1 { + reg = <1>; + usb4_1_sw: endpoint { + remote-endpoint = <&typec1_usb4>; + }; + }; + }; + }; + + cio3_mbox: mailbox@411178080 { + compatible = "apple,t8152-cio-mailbox", + "apple,t8152-smc-mailbox"; + reg = <0x4 0x11178080 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* acio@ avoids the bootloader's legacy cio@ register-index fixup. */ + usb4_3: acio@411ac0000 { + compatible = "apple,t8152-usb4-acio"; + reg = <0x4 0x11ac0000 0x0 0xc000>, + <0x4 0x11080000 0x0 0x26000>, + <0x4 0x11e44000 0x0 0x4000>, + <0x4 0x11c80000 0x0 0x4000>; + reg-names = "rc", "sram", "pcie-adapter", "router-ap-fw"; + #address-cells = <1>; + #size-cells = <1>; + /* The router window and the shared Gen3 TLB invalidation aperture. */ + ranges = <0x0 0x4 0x11000000 0x1000000>, + <0x1000000 0x2 0x0 0x1000>; + nonposted-mmio; + mboxes = <&cio3_mbox>; + resets = <&cio_reset 3>; + power-domains = <&cio_psd62>, <&cio_psd66>, <&cio_psd70>, <&cio_psd89>; + pinctrl-names = "lstx"; + pinctrl-0 = <&usb4_3_lstx_pins>; + lstx-gpios = <&pinctrl_aop 25 GPIO_ACTIVE_HIGH>; + thunderbolt-switch; + apple,pcie-tunnel = <&usb4_3_tunnel>; + + usb4_3_dart: iommu@a80000 { + compatible = "apple,t8152-acio-dart"; + reg = <0xa80000 0xc000>, + <0x1000280 0x10>; + reg-names = "dart", "tlbi"; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd62>; + apple,dma-range = <0x100 0x0 0x10 0x0>; + }; + + usb4_3_nhi: nhi@f00000 { + compatible = "apple,t8152-usb4-nhi"; + reg = <0xf00000 0x100000>; + reg-names = "nhi"; + interrupt-parent = <&aic>; + interrupts = , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + ; + interrupt-names = "txring0", "txring1", "txring2", + "txring3", "txring4", "txring5", + "txring6", "txring7", "txring8", + "txring9", "txring10", "txring11", + "rxring0", "rxring1", "rxring2", + "rxring3", "rxring4", "rxring5", + "rxring6", "rxring7", "rxring8", + "rxring9", "rxring10", "rxring11"; + iommus = <&usb4_3_dart 0>, <&usb4_3_dart 1>, <&usb4_3_dart 2>, + <&usb4_3_dart 3>, <&usb4_3_dart 4>, <&usb4_3_dart 5>, + <&usb4_3_dart 6>, <&usb4_3_dart 7>, <&usb4_3_dart 8>, + <&usb4_3_dart 9>, <&usb4_3_dart 10>, <&usb4_3_dart 11>, + <&usb4_3_dart 16>, <&usb4_3_dart 17>, <&usb4_3_dart 18>, + <&usb4_3_dart 19>, <&usb4_3_dart 20>, <&usb4_3_dart 21>, + <&usb4_3_dart 22>, <&usb4_3_dart 23>, <&usb4_3_dart 24>, + <&usb4_3_dart 25>, <&usb4_3_dart 26>, <&usb4_3_dart 27>; + /* Filled by the bootloader. */ + apple,thunderbolt-drom = [00]; + }; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@1 { + reg = <1>; + usb4_3_sw: endpoint { + remote-endpoint = <&typec3_usb4>; + }; + }; + }; + }; + }; + + usb4_0_tunnel: usb4-pcie-tunnel-0 { + #address-cells = <2>; + #size-cells = <2>; + ranges; + nonposted-mmio; + + usb4_0_pcie_dart: iommu@404000000 { + compatible = "apple,t8152-pciec-dart"; + reg = <0x4 0x4000000 0x0 0xc000>, + <0x2 0x100 0x0 0x10>; + reg-names = "dart", "tlbi"; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd86>; + apple,dma-range = <0x100 0x80000000 0x0 0x7ff00000>; + }; + + usb4_0_pcie: pcie@1c50000000 { + compatible = "apple,t8152-pciec"; + device_type = "pci"; + reg = <0x1c 0x50000000 0x0 0x10000000>, + <0x4 0x4034000 0x0 0x4000>, + <0x4 0x4020000 0x0 0x8000>, + <0x4 0x4038000 0x0 0x4000>, + <0x4 0x4060000 0x0 0x4000>, + <0x4 0x402c000 0x0 0x4000>, + <0x4 0x4028000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "fabric", "debug", "ltssm", "intr2axi"; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd86>; + apple,pciec-kernel-init; + msi-controller; + msi-parent = <&usb4_0_pcie>; + msi-ranges = <&aic AIC_IRQ 1975 IRQ_TYPE_EDGE_RISING 32>; + apple,msi-vector-base = <96>; + iommu-map = <0 &usb4_0_pcie_dart 0 0x40>; + iommu-map-mask = <0x3f>; + linux,pci-domain = <1>; + bus-range = <0 0x7f>; + #address-cells = <3>; + #size-cells = <2>; + ranges = <0x43000000 0x8 0x0 0x8 0x0 0x2 0x0>, + <0x2000000 0x0 0x100000 0xa 0x100000 0x0 0x3ff00000>, + <0x42000000 0x0 0x40000000 0xa 0x40000000 0x0 0x40000000>; + + usb4_0_pcie_port: pci@0,0 { + device_type = "pci"; + reg = <0x0 0x0 0x0 0x0 0x0>; + external-facing; + #address-cells = <3>; + #size-cells = <2>; + ranges; + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &usb4_0_pcie_port 0 0 0 0>, + <0 0 0 2 &usb4_0_pcie_port 0 0 0 1>, + <0 0 0 3 &usb4_0_pcie_port 0 0 0 2>, + <0 0 0 4 &usb4_0_pcie_port 0 0 0 3>; + }; + }; + }; + + usb4_1_tunnel: usb4-pcie-tunnel-1 { + #address-cells = <2>; + #size-cells = <2>; + ranges; + nonposted-mmio; + + usb4_1_pcie_dart: iommu@40c000000 { + compatible = "apple,t8152-pciec-dart"; + reg = <0x4 0xc000000 0x0 0xc000>, + <0x2 0x180 0x0 0x10>; + reg-names = "dart", "tlbi"; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd87>; + apple,dma-range = <0x100 0x80000000 0x0 0x7ff00000>; + }; + + usb4_1_pcie: pcie@1c60000000 { + compatible = "apple,t8152-pciec"; + device_type = "pci"; + reg = <0x1c 0x60000000 0x0 0x10000000>, + <0x4 0xc034000 0x0 0x4000>, + <0x4 0xc020000 0x0 0x8000>, + <0x4 0xc038000 0x0 0x4000>, + <0x4 0xc060000 0x0 0x4000>, + <0x4 0xc02c000 0x0 0x4000>, + <0x4 0xc028000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "fabric", "debug", "ltssm", "intr2axi"; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd87>; + apple,pciec-kernel-init; + msi-controller; + msi-parent = <&usb4_1_pcie>; + msi-ranges = <&aic AIC_IRQ 2007 IRQ_TYPE_EDGE_RISING 32>; + apple,msi-vector-base = <128>; + iommu-map = <0 &usb4_1_pcie_dart 0 0x40>; + iommu-map-mask = <0x3f>; + linux,pci-domain = <2>; + bus-range = <0 0x7f>; + #address-cells = <3>; + #size-cells = <2>; + ranges = <0x43000000 0xc 0x0 0xc 0x0 0x2 0x0>, + <0x2000000 0x0 0x100000 0xe 0x100000 0x0 0x3ff00000>, + <0x42000000 0x0 0x40000000 0xe 0x40000000 0x0 0x40000000>; + + usb4_1_pcie_port: pci@0,0 { + device_type = "pci"; + reg = <0x0 0x0 0x0 0x0 0x0>; + external-facing; + #address-cells = <3>; + #size-cells = <2>; + ranges; + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &usb4_1_pcie_port 0 0 0 0>, + <0 0 0 2 &usb4_1_pcie_port 0 0 0 1>, + <0 0 0 3 &usb4_1_pcie_port 0 0 0 2>, + <0 0 0 4 &usb4_1_pcie_port 0 0 0 3>; + }; + }; + }; + + usb4_3_tunnel: usb4-pcie-tunnel-3 { + #address-cells = <2>; + #size-cells = <2>; + ranges; + nonposted-mmio; + + usb4_3_pcie_dart: iommu@414000000 { + compatible = "apple,t8152-pciec-dart"; + reg = <0x4 0x14000000 0x0 0xc000>, + <0x2 0x280 0x0 0x10>; + reg-names = "dart", "tlbi"; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd89>; + apple,dma-range = <0x100 0x80000000 0x0 0x7ff00000>; + }; + + usb4_3_pcie: pcie@1c80000000 { + compatible = "apple,t8152-pciec"; + device_type = "pci"; + reg = <0x1c 0x80000000 0x0 0x10000000>, + <0x4 0x14034000 0x0 0x4000>, + <0x4 0x14020000 0x0 0x8000>, + <0x4 0x14038000 0x0 0x4000>, + <0x4 0x14060000 0x0 0x4000>, + <0x4 0x1402c000 0x0 0x4000>, + <0x4 0x14028000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "fabric", "debug", "ltssm", "intr2axi"; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd89>; + apple,pciec-kernel-init; + msi-controller; + msi-parent = <&usb4_3_pcie>; + msi-ranges = <&aic AIC_IRQ 2071 IRQ_TYPE_EDGE_RISING 32>; + apple,msi-vector-base = <192>; + iommu-map = <0 &usb4_3_pcie_dart 0 0x40>; + iommu-map-mask = <0x3f>; + linux,pci-domain = <4>; + bus-range = <0 0x7f>; + #address-cells = <3>; + #size-cells = <2>; + ranges = <0x43000000 0x14 0x0 0x14 0x0 0x2 0x0>, + <0x2000000 0x0 0x100000 0x16 0x100000 0x0 0x3ff00000>, + <0x42000000 0x0 0x40000000 0x16 0x40000000 0x0 0x40000000>; + + usb4_3_pcie_port: pci@0,0 { + device_type = "pci"; + reg = <0x0 0x0 0x0 0x0 0x0>; + external-facing; + #address-cells = <3>; + #size-cells = <2>; + ranges; + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &usb4_3_pcie_port 0 0 0 0>, + <0 0 0 2 &usb4_3_pcie_port 0 0 0 1>, + <0 0 0 3 &usb4_3_pcie_port 0 0 0 2>, + <0 0 0 4 &usb4_3_pcie_port 0 0 0 3>; + }; + }; + }; +}; + +&pinctrl_aop { + usb4_0_lstx_pins: usb4-0-lstx-pins { + pinmux = <0x10013>; + }; + + usb4_1_lstx_pins: usb4-1-lstx-pins { + pinmux = <0x10015>; + }; + + usb4_3_lstx_pins: usb4-3-lstx-pins { + pinmux = <0x10019>; + }; +}; + +/* USB-C Back-middle: its router */ +&typec0 { + ports { + port@4 { + reg = <4>; + + typec0_usb4: endpoint { + remote-endpoint = <&usb4_0_sw>; + }; + }; + }; +}; + +/* USB-C Back-left: its router */ +&typec1 { + ports { + port@4 { + reg = <4>; + + typec1_usb4: endpoint { + remote-endpoint = <&usb4_1_sw>; + }; + }; + }; +}; + +/* USB-C Back-right: its router */ +&typec3 { + ports { + port@4 { + reg = <4>; + + typec3_usb4: endpoint { + remote-endpoint = <&usb4_3_sw>; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index 00fe5207a19562..b6743791d76acd 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -10,6 +10,7 @@ #include #include +#include / { compatible = "apple,j873g", "apple,t8152", "apple,arm-platform"; @@ -60,6 +61,59 @@ #address-cells = <2>; #size-cells = <0>; + /* + * Three clusters: E (6 cores), P (2) and M (4); P and M share a + * performance domain. capacity-dmips-mhz is single-thread work per + * MHz relative to a P core, from integer, compression and sort + * loops at each cluster's top P-state. + */ + cpu-map { + cluster0 { + core0 { + cpu = <&cpu0>; + }; + core1 { + cpu = <&cpu1>; + }; + core2 { + cpu = <&cpu2>; + }; + core3 { + cpu = <&cpu3>; + }; + core4 { + cpu = <&cpu4>; + }; + core5 { + cpu = <&cpu5>; + }; + }; + + cluster1 { + core0 { + cpu = <&cpu6>; + }; + core1 { + cpu = <&cpu7>; + }; + }; + + cluster2 { + core0 { + cpu = <&cpu8>; + }; + core1 { + cpu = <&cpu9>; + }; + core2 { + cpu = <&cpu10>; + }; + core3 { + cpu = <&cpu11>; + }; + }; + }; + cpu0: cpu@0 { compatible = "apple,t8152-e"; device_type = "cpu"; @@ -67,7 +121,9 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; + capacity-dmips-mhz = <800>; performance-domains = <&m6_e_cpufreq>; + #cooling-cells = <2>; }; cpu1: cpu@1 { @@ -77,7 +133,9 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; + capacity-dmips-mhz = <800>; performance-domains = <&m6_e_cpufreq>; + #cooling-cells = <2>; }; cpu2: cpu@2 { @@ -87,7 +145,9 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; + capacity-dmips-mhz = <800>; performance-domains = <&m6_e_cpufreq>; + #cooling-cells = <2>; }; cpu3: cpu@3 { @@ -97,7 +157,9 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; + capacity-dmips-mhz = <800>; performance-domains = <&m6_e_cpufreq>; + #cooling-cells = <2>; }; cpu4: cpu@4 { @@ -107,7 +169,9 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; + capacity-dmips-mhz = <800>; performance-domains = <&m6_e_cpufreq>; + #cooling-cells = <2>; }; cpu5: cpu@5 { @@ -117,7 +181,9 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; + capacity-dmips-mhz = <800>; performance-domains = <&m6_e_cpufreq>; + #cooling-cells = <2>; }; cpu6: cpu@10100 { @@ -127,7 +193,9 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; + capacity-dmips-mhz = <1024>; performance-domains = <&m6_pm_cpufreq>; + #cooling-cells = <2>; }; cpu7: cpu@10101 { @@ -137,7 +205,9 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; + capacity-dmips-mhz = <1024>; performance-domains = <&m6_pm_cpufreq>; + #cooling-cells = <2>; }; cpu8: cpu@40102 { @@ -147,7 +217,9 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; + capacity-dmips-mhz = <819>; performance-domains = <&m6_pm_cpufreq>; + #cooling-cells = <2>; }; cpu9: cpu@40103 { @@ -157,7 +229,9 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; + capacity-dmips-mhz = <819>; performance-domains = <&m6_pm_cpufreq>; + #cooling-cells = <2>; }; cpu10: cpu@40104 { @@ -167,7 +241,9 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; + capacity-dmips-mhz = <819>; performance-domains = <&m6_pm_cpufreq>; + #cooling-cells = <2>; }; cpu11: cpu@40105 { @@ -177,7 +253,9 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; + capacity-dmips-mhz = <819>; performance-domains = <&m6_pm_cpufreq>; + #cooling-cells = <2>; }; }; @@ -192,6 +270,26 @@ opp-hz = /bits/ 64 <1152000000>; opp-level = <3>; }; + opp-1584000000 { + opp-hz = /bits/ 64 <1584000000>; + opp-level = <4>; + }; + opp-1980000000 { + opp-hz = /bits/ 64 <1980000000>; + opp-level = <5>; + }; + opp-2304000000 { + opp-hz = /bits/ 64 <2304000000>; + opp-level = <6>; + }; + opp-2640000000 { + opp-hz = /bits/ 64 <2640000000>; + opp-level = <7>; + }; + opp-2940000000 { + opp-hz = /bits/ 64 <2940000000>; + opp-level = <8>; + }; }; m6_pm_opp: opp-table-pm { compatible = "operating-points-v2"; @@ -204,7 +302,88 @@ opp-hz = /bits/ 64 <1728000000>; opp-level = <3>; }; + opp-2040000000 { + opp-hz = /bits/ 64 <2040000000>; + opp-level = <4>; + }; + opp-2340000000 { + opp-hz = /bits/ 64 <2340000000>; + opp-level = <5>; + }; + opp-2640000000 { + opp-hz = /bits/ 64 <2640000000>; + opp-level = <6>; + }; + opp-2940000000 { + opp-hz = /bits/ 64 <2940000000>; + opp-level = <7>; + }; + opp-3216000000 { + opp-hz = /bits/ 64 <3216000000>; + opp-level = <8>; + }; + opp-3468000000 { + opp-hz = /bits/ 64 <3468000000>; + opp-level = <9>; + }; + opp-3696000000 { + opp-hz = /bits/ 64 <3696000000>; + opp-level = <10>; + }; + opp-3924000000 { + opp-hz = /bits/ 64 <3924000000>; + opp-level = <11>; + }; + opp-4092000000 { + opp-hz = /bits/ 64 <4092000000>; + opp-level = <12>; + }; + opp-4272000000 { + opp-hz = /bits/ 64 <4272000000>; + opp-level = <13>; + }; + opp-4416000000 { + opp-hz = /bits/ 64 <4416000000>; + opp-level = <14>; + }; + opp-4476000000 { + opp-hz = /bits/ 64 <4476000000>; + opp-level = <15>; + }; + opp-4512000000 { + opp-hz = /bits/ 64 <4512000000>; + opp-level = <16>; + }; + opp-4536000000 { + opp-hz = /bits/ 64 <4536000000>; + opp-level = <17>; + }; + opp-4584000000 { + opp-hz = /bits/ 64 <4584000000>; + opp-level = <18>; + }; + opp-4644000000 { + opp-hz = /bits/ 64 <4644000000>; + opp-level = <19>; + }; + opp-4692000000 { + opp-hz = /bits/ 64 <4692000000>; + opp-level = <20>; + }; + opp-4788000000 { + opp-hz = /bits/ 64 <4788000000>; + opp-level = <21>; + }; }; + + /* The 24 MHz timebase (ADT timebase-frequency), as on T8103. */ + clkref: clock-ref { + compatible = "fixed-clock"; + #clock-cells = <0>; + clock-frequency = <24000000>; + clock-output-names = "clkref"; + }; + timer { compatible = "arm,armv8-timer"; interrupts = , @@ -241,6 +420,62 @@ #performance-domain-cells = <0>; }; + /* + * ADT /arm-io/nub-spmi0 (gen 4) and its primary PMU, pmu-main + * ("woodcote", slave 0xe). The boot flags live in the legacy + * scratchpad (info-leg_scrpad = 0xf800), laid out as on T8103 + * and T8140; boot_stage read 0x30 (kernel started) here. + */ + nub_spmi0: spmi@308714000 { + /* + * Gen 4: FIFO registers at 0x200 (the block is 0x4000 + * long); polled, so no interrupts are described yet. + */ + compatible = "apple,t8152-spmi", "apple,t8142-spmi"; + reg = <0x3 0x08714000 0x0 0x4000>; + #address-cells = <2>; + #size-cells = <0>; + + pmic@e { + compatible = "apple,woodcote-pmic", "apple,spmi-nvmem"; + reg = <0xe SPMI_USID>; + + nvmem-layout { + compatible = "fixed-layout"; + #address-cells = <1>; + #size-cells = <1>; + + boot_stage: boot-stage@f801 { + reg = <0xf801 0x1>; + }; + + boot_error_count: boot-error-count@f802,0 { + reg = <0xf802 0x1>; + bits = <0 4>; + }; + + panic_count: panic-count@f802,4 { + reg = <0xf802 0x1>; + bits = <4 4>; + }; + + /* Set before off1, or the machine powers back on. */ + shutdown_flag: shutdown-flag@f80f,3 { + reg = <0xf80f 0x1>; + bits = <3 1>; + }; + }; + }; + }; + + /* ADT /arm-io/wdt (wdt,t8152): restart fallback and /dev/watchdog. */ + wdt: watchdog@3082b0000 { + compatible = "apple,t8152-wdt", "apple,t8103-wdt"; + reg = <3 0x082b0000 0 0x4000>; + clocks = <&clkref>; + interrupts = ; + }; + smc_mbox: mailbox@30c710080 { compatible = "apple,t8152-smc-mailbox"; reg = <3 0x0c710080 0 0x80>; @@ -257,14 +492,25 @@ reg-names = "smc", "sram"; mboxes = <&smc_mbox>; - hwmon { + /* Power off (MBSE = off1) and restart (MBSE = phra). */ + smc_reboot: reboot { + compatible = "apple,smc-reboot"; + nvmem-cells = <&shutdown_flag>, <&boot_stage>, + <&boot_error_count>, <&panic_count>; + nvmem-cell-names = "shutdown_flag", "boot_stage", + "boot_error_count", "panic_count"; + }; + + m6_smc_hwmon: hwmon { compatible = "apple,smc-hwmon"; - apple,discover-temperatures; + #thermal-sensor-cells = <1>; fan-F0Ac { apple,key-id = "F0Ac"; apple,fan-minimum = "F0Mn"; apple,fan-maximum = "F0Mx"; + apple,fan-target = "F0Tg"; + apple,fan-mode = "F0md"; label = "Fan"; }; }; @@ -295,12 +541,6 @@ <0x4 0x3040000 0x0 0xc000>; }; -/* Retain the register view published by this board's live hardware capture. */ -&dwc3_1_dart { - reg = <0x4 0xb020000 0x0 0xc000>, - <0x4 0xb040000 0x0 0xc000>; -}; - /* Retain the register view published by this board's live hardware capture. */ &dwc3_3_dart { reg = <0x4 0x13020000 0x0 0xc000>, @@ -423,10 +663,15 @@ <0x3 0xa0000000 0x0 0x8000>; }; -/* Unexposed chassis port instances remain described and disabled. */ - -/* Retain the register view published by this board's live hardware capture. */ -&dwc3_2_dart { - reg = <0x3 0x83020000 0x0 0xc000>, - <0x3 0x83040000 0x0 0xc000>; -}; +/* + * The J873g fragments enable and refine nodes of t8152-peripherals.dtsi + * (the USB, apcie port 2 and dart-sbr DARTs), so they come after it. + */ +#include "t8152-j873-nvme.dtsi" +#include "t8152-j873-usb.dtsi" +#include "t8152-j873-ethernet.dtsi" +#include "t8152-j873-audio.dtsi" +#include "t8152-j873-dcp.dtsi" +#include "t8152-j873-avd.dtsi" +#include "t8152-j873-thermal.dtsi" +#include "t8152-j873-usb4.dtsi" diff --git a/arch/arm64/boot/dts/apple/t8152-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8152-peripherals.dtsi index 578e7730ef5f15..d1dcb53240fc11 100644 --- a/arch/arm64/boot/dts/apple/t8152-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-peripherals.dtsi @@ -123,17 +123,20 @@ }; dcp_dart: iommu@286340000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; - reg = <0x2 0x86340000 0x0 0x20000>; + compatible = "apple,t8152-dart-gen3"; + reg = <0x2 0x86340000 0x0 0x20000>, + <0x2 0x00000400 0x0 0x10>; + reg-names = "dart", "tlbi"; interrupts = ; #iommu-cells = <1>; status = "disabled"; }; disp0_dart: iommu@286300000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; + compatible = "apple,t8152-dart-gen3"; reg = <0x2 0x86300000 0x0 0xc000>, - <0x2 0x86314000 0x0 0x4000>; + <0x2 0x00000400 0x0 0x10>; + reg-names = "dart", "tlbi"; interrupts = ; #iommu-cells = <1>; status = "disabled"; @@ -148,17 +151,20 @@ }; dcpext0_dart: iommu@32a340000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; - reg = <0x3 0x2a340000 0x0 0x20000>; + compatible = "apple,t8152-dart-gen3"; + reg = <0x3 0x2a340000 0x0 0x20000>, + <0x2 0x00000480 0x0 0x10>; + reg-names = "dart", "tlbi"; interrupts = ; #iommu-cells = <1>; status = "disabled"; }; dispext0_dart: iommu@32a300000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; + compatible = "apple,t8152-dart-gen3"; reg = <0x3 0x2a300000 0x0 0xc000>, - <0x3 0x2a314000 0x0 0x4000>; + <0x2 0x00000480 0x0 0x10>; + reg-names = "dart", "tlbi"; interrupts = ; #iommu-cells = <1>; status = "disabled"; @@ -223,11 +229,62 @@ status = "disabled"; }; + /* Kopsia decoder: PSD service 50, Gen3 DART streams 0..2. */ + ps_avd: power-controller@303a13200 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x03a13200 0x0 0x100>; + #power-domain-cells = <0>; + label = "avd"; + status = "disabled"; + }; + avd_dart: iommu@485020000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; - reg = <0x4 0x85020000 0x0 0x20000>; + compatible = "apple,t8152-avd-dart"; + reg = <0x4 0x85020000 0x0 0x20000>, <0x2 0x300 0x0 0x10>; + reg-names = "dart", "tlbi"; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_avd>; + /* A 64-GiB window within the ADT's 1..4-TiB DMA aperture. */ + apple,dma-range = <0x100 0x0 0x10 0x0>; + apple,tunable = < + 0x20c 0x80000121 0x80000121 + 0x220 0xf0f 0xf0f + 0x224 0xffff 0x909 + 0x300 0x1f31 0x1 + 0x308 0x3ffffffc 0x10000000 + 0x310 0x3ffffffc 0x3ffffffc + 0x800 0xf007f 0x10000 + 0x804 0xf007f 0x20002 + 0x808 0xf007f 0x50006 + 0x80c 0xf007f 0x20026 + 0x810 0xf007f 0x3002a + 0x814 0xf007f 0x40032 + 0x818 0xf007f 0x0 + 0x81c 0xf007f 0x0 + 0x820 0xf007f 0x0 + 0x824 0xf007f 0x0 + 0x828 0xf007f 0x0 + 0x82c 0xf007f 0x0 + 0x830 0xf007f 0x0 + 0x834 0xf007f 0x0 + 0x838 0xf007f 0x0 + 0x83c 0xf007f 0x0 + 0x4600 0x2 0x2 + >; + status = "disabled"; + }; + + avd: video-codec@485400000 { + compatible = "apple,t8152-avd"; + reg = <0x4 0x85400000 0x0 0x12000>, + <0x4 0x85500000 0x0 0x4000>, + <0x4 0x85100000 0x0 0x10000>, + <0x4 0x850c0000 0x0 0x4000>, + <0x4 0x85070000 0x0 0x4000>; + reg-names = "code", "mbox", "ctrl", "wrap", "dma"; + power-domains = <&ps_avd>; + iommus = <&avd_dart 0>, <&avd_dart 1>, <&avd_dart 2>; status = "disabled"; }; diff --git a/arch/arm64/configs/asahi.config b/arch/arm64/configs/asahi.config index 3173021d4f19d8..9d5077f609bbb7 100644 --- a/arch/arm64/configs/asahi.config +++ b/arch/arm64/configs/asahi.config @@ -20,6 +20,14 @@ CONFIG_THERMAL_GOV_POWER_ALLOCATOR=y # CONFIG_THERMAL_DEFAULT_GOV_STEP_WISE is not set CONFIG_THERMAL_DEFAULT_GOV_POWER_ALLOCATOR=y CONFIG_BT_BRCMEXT=y +# Classic Bluetooth headsets need RFCOMM for HFP/HSP, and the LE features are +# needed for BLE devices and LE pairing; the ARM64 defconfig leaves them out. +CONFIG_BT_RFCOMM=m +CONFIG_BT_RFCOMM_TTY=y +CONFIG_BT_BNEP=m +CONFIG_BT_BNEP_MC_FILTER=y +CONFIG_BT_BNEP_PROTO_FILTER=y +CONFIG_BT_LE=y CONFIG_BT_HCIBCM4377=m CONFIG_BT_MTK7932_PCIE=m CONFIG_BT_CENTAURI=m @@ -81,6 +89,7 @@ CONFIG_VIDEO_APPLE_SCALER=m CONFIG_DRM=y CONFIG_DRM_ASAHI=m CONFIG_DRM_ASAHI_G15=y +CONFIG_DRM_ASAHI_G14_V27_2=y CONFIG_DRM_ASAHI_G16=y CONFIG_DRM_ASAHI_G18=y CONFIG_DRM_ASAHI_M5=y @@ -88,6 +97,7 @@ CONFIG_DRM_ASAHI_M3_T8122=y CONFIG_DRM_ADP=m CONFIG_DRM_APPLE=m CONFIG_DRM_APPLE_DCP_T8132=y +CONFIG_DRM_APPLE_DCP_T8152=y CONFIG_DRM_APPLE_CEC=y CONFIG_DRM_APPLE_AUDIO=y CONFIG_DRM_APPLE_DCP_T6030_AUDIO=y @@ -156,6 +166,7 @@ CONFIG_SECURITY_LOCKDOWN_LSM=y CONFIG_SECURITY_LOCKDOWN_LSM_EARLY=y CONFIG_LOCK_DOWN_KERNEL_FORCE_NONE=y CONFIG_APPLE_PMGR_PWRSTATE=y +CONFIG_APPLE_PMGR_PSD=y CONFIG_APPLE_T6041_CIO_RECONFIG=y CONFIG_APPLE_PMC=y CONFIG_APPLE_CLUSTER_PWRGATE=y diff --git a/arch/arm64/configs/aurora_defconfig b/arch/arm64/configs/aurora_defconfig new file mode 100644 index 00000000000000..cd57de3bb1a375 --- /dev/null +++ b/arch/arm64/configs/aurora_defconfig @@ -0,0 +1,5568 @@ +CONFIG_UAPI_HEADER_TEST=y +# CONFIG_LOCALVERSION_AUTO is not set +CONFIG_BUILD_SALT="7.0.13-400.asahi.fc44.aarch64" +CONFIG_KERNEL_ZSTD=y +CONFIG_SYSVIPC=y +CONFIG_POSIX_MQUEUE=y +CONFIG_WATCH_QUEUE=y +CONFIG_AUDIT=y +CONFIG_NO_HZ_FULL=y +CONFIG_NO_HZ=y +CONFIG_HIGH_RES_TIMERS=y +CONFIG_POSIX_AUX_CLOCKS=y +CONFIG_BPF_JIT=y +CONFIG_BPF_JIT_ALWAYS_ON=y +CONFIG_BPF_PRELOAD=y +CONFIG_BPF_LSM=y +CONFIG_PREEMPT_DYNAMIC=y +CONFIG_SCHED_CORE=y +CONFIG_SCHED_CLASS_EXT=y +CONFIG_IRQ_TIME_ACCOUNTING=y +CONFIG_BSD_PROCESS_ACCT=y +CONFIG_BSD_PROCESS_ACCT_V3=y +CONFIG_TASKSTATS=y +CONFIG_TASK_DELAY_ACCT=y +CONFIG_TASK_XACCT=y +CONFIG_TASK_IO_ACCOUNTING=y +CONFIG_PSI=y +CONFIG_IKHEADERS=m +CONFIG_LOG_BUF_SHIFT=18 +CONFIG_PRINTK_INDEX=y +CONFIG_UCLAMP_TASK=y +CONFIG_NUMA_BALANCING=y +CONFIG_MEMCG=y +CONFIG_MEMCG_V1=y +CONFIG_BLK_CGROUP=y +CONFIG_CFS_BANDWIDTH=y +CONFIG_UCLAMP_TASK_GROUP=y +CONFIG_CGROUP_PIDS=y +CONFIG_CGROUP_RDMA=y +CONFIG_CGROUP_DMEM=y +CONFIG_CGROUP_FREEZER=y +CONFIG_CPUSETS=y +CONFIG_CGROUP_DEVICE=y +CONFIG_CGROUP_CPUACCT=y +CONFIG_CGROUP_PERF=y +CONFIG_CGROUP_BPF=y +CONFIG_CGROUP_MISC=y +CONFIG_NAMESPACES=y +CONFIG_USER_NS=y +CONFIG_CHECKPOINT_RESTORE=y +CONFIG_SCHED_AUTOGROUP=y +# CONFIG_INITRAMFS_PRESERVE_MTIME is not set +CONFIG_SYSFS_SYSCALL=y +CONFIG_EXPERT=y +CONFIG_SGETMASK_SYSCALL=y +CONFIG_PROFILING=y +CONFIG_RUST=y +CONFIG_KEXEC=y +CONFIG_KEXEC_SIG=y +CONFIG_CRASH_DM_CRYPT=y +CONFIG_KEXEC_HANDOVER=y +CONFIG_LIVEUPDATE=y +CONFIG_ARCH_SUNXI=y +CONFIG_ARCH_APPLE=y +CONFIG_ARCH_BCM=y +CONFIG_ARCH_BCM2835=y +CONFIG_ARCH_BST=y +CONFIG_ARCH_CIX=y +CONFIG_ARCH_K3=y +CONFIG_ARCH_HISI=y +CONFIG_ARCH_MESON=y +CONFIG_ARCH_MVEBU=y +CONFIG_ARCH_NXP=y +CONFIG_ARCH_LAYERSCAPE=y +CONFIG_ARCH_MXC=y +CONFIG_ARCH_S32=y +CONFIG_ARCH_QCOM=y +CONFIG_ARCH_RENESAS=y +CONFIG_ARCH_ROCKCHIP=y +CONFIG_ARCH_SEATTLE=y +CONFIG_ARCH_SYNQUACER=y +CONFIG_ARCH_TEGRA=y +CONFIG_ARCH_THUNDER=y +CONFIG_ARCH_THUNDER2=y +CONFIG_ARCH_VEXPRESS=y +CONFIG_ARCH_XGENE=y +CONFIG_ARCH_ZYNQMP=y +CONFIG_ARM64_ERRATUM_834220=y +CONFIG_ARM64_ERRATUM_2441007=y +CONFIG_ARM64_ERRATUM_1286807=y +CONFIG_ARM64_ERRATUM_1542419=y +CONFIG_ARM64_ERRATUM_2441009=y +# CONFIG_QCOM_FALKOR_ERRATUM_1003 is not set +CONFIG_ARM64_16K_PAGES=y +CONFIG_ARM64_VA_BITS_48=y +CONFIG_NR_CPUS=4096 +CONFIG_NUMA=y +CONFIG_NODES_SHIFT=9 +CONFIG_HZ_1000=y +CONFIG_PARAVIRT_TIME_ACCOUNTING=y +CONFIG_ARM64_SW_TTBR0_PAN=y +CONFIG_COMPAT=y +CONFIG_ARMV8_DEPRECATED=y +CONFIG_SWP_EMULATION=y +CONFIG_CP15_BARRIER_EMULATION=y +CONFIG_SETEND_EMULATION=y +CONFIG_ARM64_PMEM=y +CONFIG_ARM64_PSEUDO_NMI=y +CONFIG_ARM64_MEMORY_MODEL_CONTROL=y +CONFIG_RANDOMIZE_BASE=y +CONFIG_ARM64_CTXR_EXECMEM=y +CONFIG_ARM64_ACPI_PARKING_PROTOCOL=y +CONFIG_COMPRESSED_INSTALL=y +CONFIG_HIBERNATION=y +CONFIG_PM_QOS_CPU_SYSTEM_WAKEUP=y +CONFIG_PM_DEBUG=y +CONFIG_PM_TEST_SUSPEND=y +CONFIG_ENERGY_MODEL=y +CONFIG_ARM_PSCI_CPUIDLE=y +CONFIG_CPU_FREQ=y +CONFIG_CPU_FREQ_STAT=y +CONFIG_CPU_FREQ_GOV_POWERSAVE=y +CONFIG_CPU_FREQ_GOV_USERSPACE=y +CONFIG_CPU_FREQ_GOV_ONDEMAND=y +CONFIG_CPU_FREQ_GOV_CONSERVATIVE=y +CONFIG_CPUFREQ_DT=m +CONFIG_CPUFREQ_VIRT=m +CONFIG_ARM_ALLWINNER_SUN50I_CPUFREQ_NVMEM=m +CONFIG_ARM_APPLE_SOC_CPUFREQ=m +CONFIG_ARM_ARMADA_37XX_CPUFREQ=m +CONFIG_ARM_ARMADA_8K_CPUFREQ=m +CONFIG_ARM_SCPI_CPUFREQ=m +CONFIG_ARM_IMX_CPUFREQ_DT=m +CONFIG_ARM_QCOM_CPUFREQ_NVMEM=m +CONFIG_ARM_QCOM_CPUFREQ_HW=m +CONFIG_ARM_RASPBERRYPI_CPUFREQ=m +CONFIG_ARM_SCMI_CPUFREQ=m +# CONFIG_ARM_TEGRA20_CPUFREQ is not set +CONFIG_ARM_TEGRA186_CPUFREQ=m +CONFIG_ARM_TEGRA194_CPUFREQ=m +CONFIG_QORIQ_CPUFREQ=m +CONFIG_ACPI_CPPC_CPUFREQ=m +# CONFIG_ACPI_CPPC_CPUFREQ_FIE is not set +CONFIG_ACPI=y +CONFIG_ACPI_FPDT=y +CONFIG_ACPI_EC=y +CONFIG_ACPI_TAD=m +CONFIG_ACPI_DOCK=y +CONFIG_ACPI_IPMI=m +CONFIG_ACPI_PCI_SLOT=y +CONFIG_ACPI_HOTPLUG_MEMORY=y +CONFIG_ACPI_BGRT=y +CONFIG_ACPI_NFIT=m +CONFIG_ACPI_APEI=y +CONFIG_ACPI_APEI_GHES=y +CONFIG_ACPI_APEI_PCIEAER=y +CONFIG_ACPI_APEI_MEMORY_FAILURE=y +CONFIG_ACPI_APEI_EINJ=m +CONFIG_ACPI_PFRUT=m +CONFIG_ACPI_AGDI=y +CONFIG_ACPI_FFH=y +CONFIG_VIRTUALIZATION=y +CONFIG_KVM=y +CONFIG_LIVEPATCH=y +# CONFIG_SCHED_CLUSTER is not set +CONFIG_ARCH_MMAP_RND_BITS=18 +CONFIG_ARCH_MMAP_RND_COMPAT_BITS=11 +CONFIG_RANDOMIZE_KSTACK_OFFSET_DEFAULT=y +# CONFIG_RELR is not set +CONFIG_MODULES=y +CONFIG_MODULE_UNLOAD=y +CONFIG_MODULE_UNLOAD_TAINT_TRACKING=y +CONFIG_MODULE_COMPRESS=y +CONFIG_MODULE_COMPRESS_XZ=y +# CONFIG_MODULE_COMPRESS_ALL is not set +CONFIG_MODULE_DECOMPRESS=y +CONFIG_MODPROBE_PATH="/usr/sbin/modprobe" +CONFIG_BLK_DEV_ZONED=y +CONFIG_BLK_DEV_THROTTLING=y +CONFIG_BLK_WBT=y +CONFIG_BLK_CGROUP_IOLATENCY=y +CONFIG_BLK_CGROUP_FC_APPID=y +CONFIG_BLK_CGROUP_IOCOST=y +CONFIG_BLK_CGROUP_IOPRIO=y +CONFIG_BLK_SED_OPAL=y +CONFIG_PARTITION_ADVANCED=y +CONFIG_AIX_PARTITION=y +CONFIG_OSF_PARTITION=y +CONFIG_MAC_PARTITION=y +CONFIG_BSD_DISKLABEL=y +CONFIG_MINIX_SUBPARTITION=y +CONFIG_SOLARIS_X86_PARTITION=y +CONFIG_UNIXWARE_DISKLABEL=y +CONFIG_LDM_PARTITION=y +CONFIG_SGI_PARTITION=y +CONFIG_SUN_PARTITION=y +CONFIG_OF_PARTITION=y +CONFIG_IOSCHED_BFQ=y +CONFIG_BINFMT_MISC=m +CONFIG_ZSWAP=y +CONFIG_ZSWAP_SHRINKER_DEFAULT_ON=y +# CONFIG_SLAB_MERGE_DEFAULT is not set +CONFIG_SLAB_FREELIST_RANDOM=y +CONFIG_SLAB_FREELIST_HARDENED=y +CONFIG_KMALLOC_PARTITION_CACHES=y +# CONFIG_COMPAT_BRK is not set +CONFIG_MEMORY_HOTPLUG=y +CONFIG_MHP_DEFAULT_ONLINE_TYPE_ONLINE_AUTO=y +CONFIG_MEMORY_HOTREMOVE=y +CONFIG_KSM=y +CONFIG_DEFAULT_MMAP_MIN_ADDR=65536 +CONFIG_MEMORY_FAILURE=y +CONFIG_HWPOISON_INJECT=m +CONFIG_TRANSPARENT_HUGEPAGE=y +CONFIG_TRANSPARENT_HUGEPAGE_MADVISE=y +CONFIG_CMA_SYSFS=y +CONFIG_CMA_AREAS=7 +CONFIG_PAGE_BLOCK_MAX_ORDER=7 +CONFIG_IDLE_PAGE_TRACKING=y +CONFIG_ZONE_DEVICE=y +CONFIG_DEVICE_PRIVATE=y +CONFIG_USERFAULTFD=y +CONFIG_LRU_GEN=y +CONFIG_LRU_GEN_ENABLED=y +CONFIG_DAMON=y +CONFIG_DAMON_RECLAIM=y +CONFIG_DAMON_STAT=y +# CONFIG_DAMON_STAT_ENABLED_DEFAULT is not set +CONFIG_NET=y +CONFIG_PACKET=y +CONFIG_PACKET_DIAG=y +CONFIG_INET_PSP=y +CONFIG_UNIX_DIAG=y +CONFIG_TLS_DEVICE=y +CONFIG_XFRM_USER=y +CONFIG_XFRM_INTERFACE=m +CONFIG_XFRM_SUB_POLICY=y +CONFIG_XFRM_STATISTICS=y +CONFIG_NET_KEY=m +CONFIG_NET_KEY_MIGRATE=y +CONFIG_XFRM_IPTFS=m +CONFIG_SMC=m +CONFIG_SMC_DIAG=m +CONFIG_DIBS=m +CONFIG_DIBS_LO=y +CONFIG_XDP_SOCKETS=y +CONFIG_XDP_SOCKETS_DIAG=m +CONFIG_IP_MULTICAST=y +CONFIG_IP_ADVANCED_ROUTER=y +CONFIG_IP_FIB_TRIE_STATS=y +CONFIG_IP_MULTIPLE_TABLES=y +CONFIG_IP_ROUTE_MULTIPATH=y +CONFIG_IP_ROUTE_VERBOSE=y +CONFIG_NET_IPIP=m +CONFIG_NET_IPGRE_DEMUX=m +CONFIG_NET_IPGRE=m +CONFIG_NET_IPGRE_BROADCAST=y +CONFIG_IP_MROUTE=y +CONFIG_IP_MROUTE_MULTIPLE_TABLES=y +CONFIG_IP_PIMSM_V1=y +CONFIG_IP_PIMSM_V2=y +CONFIG_NET_IPVTI=m +CONFIG_NET_FOU_IP_TUNNELS=y +CONFIG_INET_AH=m +CONFIG_INET_ESP=m +CONFIG_INET_ESP_OFFLOAD=m +CONFIG_INET_ESPINTCP=y +CONFIG_INET_IPCOMP=m +CONFIG_INET_UDP_DIAG=y +CONFIG_INET_RAW_DIAG=y +CONFIG_INET_DIAG_DESTROY=y +CONFIG_TCP_CONG_ADVANCED=y +CONFIG_TCP_CONG_HSTCP=m +CONFIG_TCP_CONG_HYBLA=m +CONFIG_TCP_CONG_NV=m +CONFIG_TCP_CONG_SCALABLE=m +CONFIG_TCP_CONG_LP=m +CONFIG_TCP_CONG_VENO=m +CONFIG_TCP_CONG_YEAH=m +CONFIG_TCP_CONG_ILLINOIS=m +CONFIG_TCP_CONG_DCTCP=m +CONFIG_TCP_CONG_CDG=m +CONFIG_TCP_CONG_BBR=m +CONFIG_TCP_AO=y +CONFIG_TCP_MD5SIG=y +CONFIG_IPV6_ROUTER_PREF=y +CONFIG_IPV6_ROUTE_INFO=y +CONFIG_IPV6_OPTIMISTIC_DAD=y +CONFIG_INET6_AH=m +CONFIG_INET6_ESP=m +CONFIG_INET6_ESP_OFFLOAD=m +CONFIG_INET6_ESPINTCP=y +CONFIG_INET6_IPCOMP=m +CONFIG_IPV6_MIP6=y +CONFIG_IPV6_ILA=m +CONFIG_IPV6_VTI=m +CONFIG_IPV6_SIT_6RD=y +CONFIG_IPV6_GRE=m +CONFIG_IPV6_SUBTREES=y +CONFIG_IPV6_MROUTE=y +CONFIG_IPV6_MROUTE_MULTIPLE_TABLES=y +CONFIG_IPV6_PIMSM_V2=y +CONFIG_IPV6_SEG6_LWTUNNEL=y +CONFIG_IPV6_SEG6_HMAC=y +CONFIG_IPV6_RPL_LWTUNNEL=y +CONFIG_IPV6_IOAM6_LWTUNNEL=y +CONFIG_NETLABEL=y +CONFIG_MPTCP=y +CONFIG_NETWORK_PHY_TIMESTAMPING=y +CONFIG_NETFILTER=y +CONFIG_BRIDGE_NETFILTER=m +CONFIG_NETFILTER_NETLINK_HOOK=m +CONFIG_NF_CONNTRACK=m +CONFIG_NF_CONNTRACK_SECMARK=y +CONFIG_NF_CONNTRACK_ZONES=y +CONFIG_NF_CONNTRACK_PROCFS=y +CONFIG_NF_CONNTRACK_EVENTS=y +CONFIG_NF_CONNTRACK_TIMEOUT=y +CONFIG_NF_CONNTRACK_TIMESTAMP=y +CONFIG_NF_CONNTRACK_AMANDA=m +CONFIG_NF_CONNTRACK_FTP=m +CONFIG_NF_CONNTRACK_H323=m +CONFIG_NF_CONNTRACK_IRC=m +CONFIG_NF_CONNTRACK_NETBIOS_NS=m +CONFIG_NF_CONNTRACK_SNMP=m +CONFIG_NF_CONNTRACK_PPTP=m +CONFIG_NF_CONNTRACK_SANE=m +CONFIG_NF_CONNTRACK_SIP=m +CONFIG_NF_CONNTRACK_TFTP=m +CONFIG_NF_CT_NETLINK=m +CONFIG_NF_CT_NETLINK_TIMEOUT=m +CONFIG_NF_CT_NETLINK_HELPER=m +CONFIG_NETFILTER_NETLINK_GLUE_CT=y +CONFIG_NF_TABLES=m +CONFIG_NF_TABLES_INET=y +CONFIG_NF_TABLES_NETDEV=y +CONFIG_NFT_NUMGEN=m +CONFIG_NFT_CT=m +CONFIG_NFT_FLOW_OFFLOAD=m +CONFIG_NFT_CONNLIMIT=m +CONFIG_NFT_LOG=m +CONFIG_NFT_LIMIT=m +CONFIG_NFT_MASQ=m +CONFIG_NFT_REDIR=m +CONFIG_NFT_NAT=m +CONFIG_NFT_TUNNEL=m +CONFIG_NFT_QUEUE=m +CONFIG_NFT_QUOTA=m +CONFIG_NFT_REJECT=m +CONFIG_NFT_COMPAT=m +CONFIG_NFT_HASH=m +CONFIG_NFT_FIB_INET=m +CONFIG_NFT_XFRM=m +CONFIG_NFT_SOCKET=m +CONFIG_NFT_OSF=m +CONFIG_NFT_TPROXY=m +CONFIG_NFT_SYNPROXY=m +CONFIG_NFT_DUP_NETDEV=m +CONFIG_NFT_FWD_NETDEV=m +CONFIG_NFT_FIB_NETDEV=m +CONFIG_NFT_REJECT_NETDEV=m +CONFIG_NF_FLOW_TABLE_INET=m +CONFIG_NF_FLOW_TABLE=m +CONFIG_NF_FLOW_TABLE_PROCFS=y +CONFIG_NETFILTER_XTABLES=y +CONFIG_NETFILTER_XTABLES_LEGACY=y +CONFIG_NETFILTER_XT_SET=m +CONFIG_NETFILTER_XT_TARGET_AUDIT=m +CONFIG_NETFILTER_XT_TARGET_CHECKSUM=m +CONFIG_NETFILTER_XT_TARGET_CLASSIFY=m +CONFIG_NETFILTER_XT_TARGET_CONNMARK=m +CONFIG_NETFILTER_XT_TARGET_CONNSECMARK=m +CONFIG_NETFILTER_XT_TARGET_DSCP=m +CONFIG_NETFILTER_XT_TARGET_HMARK=m +CONFIG_NETFILTER_XT_TARGET_IDLETIMER=m +CONFIG_NETFILTER_XT_TARGET_LED=m +CONFIG_NETFILTER_XT_TARGET_LOG=m +CONFIG_NETFILTER_XT_TARGET_MARK=m +CONFIG_NETFILTER_XT_TARGET_NFLOG=m +CONFIG_NETFILTER_XT_TARGET_NFQUEUE=m +CONFIG_NETFILTER_XT_TARGET_NOTRACK=m +CONFIG_NETFILTER_XT_TARGET_TEE=m +CONFIG_NETFILTER_XT_TARGET_TPROXY=m +CONFIG_NETFILTER_XT_TARGET_TRACE=m +CONFIG_NETFILTER_XT_TARGET_SECMARK=m +CONFIG_NETFILTER_XT_TARGET_TCPMSS=m +CONFIG_NETFILTER_XT_TARGET_TCPOPTSTRIP=m +CONFIG_NETFILTER_XT_MATCH_ADDRTYPE=m +CONFIG_NETFILTER_XT_MATCH_BPF=m +CONFIG_NETFILTER_XT_MATCH_CGROUP=m +CONFIG_NETFILTER_XT_MATCH_CLUSTER=m +CONFIG_NETFILTER_XT_MATCH_COMMENT=m +CONFIG_NETFILTER_XT_MATCH_CONNBYTES=m +CONFIG_NETFILTER_XT_MATCH_CONNLABEL=m +CONFIG_NETFILTER_XT_MATCH_CONNLIMIT=m +CONFIG_NETFILTER_XT_MATCH_CONNMARK=m +CONFIG_NETFILTER_XT_MATCH_CONNTRACK=m +CONFIG_NETFILTER_XT_MATCH_CPU=m +CONFIG_NETFILTER_XT_MATCH_DCCP=m +CONFIG_NETFILTER_XT_MATCH_DEVGROUP=m +CONFIG_NETFILTER_XT_MATCH_DSCP=m +CONFIG_NETFILTER_XT_MATCH_ESP=m +CONFIG_NETFILTER_XT_MATCH_HASHLIMIT=m +CONFIG_NETFILTER_XT_MATCH_HELPER=m +CONFIG_NETFILTER_XT_MATCH_IPCOMP=m +CONFIG_NETFILTER_XT_MATCH_IPRANGE=m +CONFIG_NETFILTER_XT_MATCH_IPVS=m +CONFIG_NETFILTER_XT_MATCH_LENGTH=m +CONFIG_NETFILTER_XT_MATCH_LIMIT=m +CONFIG_NETFILTER_XT_MATCH_MAC=m +CONFIG_NETFILTER_XT_MATCH_MARK=m +CONFIG_NETFILTER_XT_MATCH_MULTIPORT=m +CONFIG_NETFILTER_XT_MATCH_NFACCT=m +CONFIG_NETFILTER_XT_MATCH_OSF=m +CONFIG_NETFILTER_XT_MATCH_OWNER=m +CONFIG_NETFILTER_XT_MATCH_POLICY=m +CONFIG_NETFILTER_XT_MATCH_PHYSDEV=m +CONFIG_NETFILTER_XT_MATCH_PKTTYPE=m +CONFIG_NETFILTER_XT_MATCH_QUOTA=m +CONFIG_NETFILTER_XT_MATCH_RATEEST=m +CONFIG_NETFILTER_XT_MATCH_REALM=m +CONFIG_NETFILTER_XT_MATCH_RECENT=m +CONFIG_NETFILTER_XT_MATCH_SOCKET=m +CONFIG_NETFILTER_XT_MATCH_STATE=m +CONFIG_NETFILTER_XT_MATCH_STATISTIC=m +CONFIG_NETFILTER_XT_MATCH_STRING=m +CONFIG_NETFILTER_XT_MATCH_TCPMSS=m +CONFIG_NETFILTER_XT_MATCH_TIME=m +CONFIG_NETFILTER_XT_MATCH_U32=m +CONFIG_IP_SET=m +CONFIG_IP_SET_BITMAP_IP=m +CONFIG_IP_SET_BITMAP_IPMAC=m +CONFIG_IP_SET_BITMAP_PORT=m +CONFIG_IP_SET_HASH_IP=m +CONFIG_IP_SET_HASH_IPMARK=m +CONFIG_IP_SET_HASH_IPPORT=m +CONFIG_IP_SET_HASH_IPPORTIP=m +CONFIG_IP_SET_HASH_IPPORTNET=m +CONFIG_IP_SET_HASH_IPMAC=m +CONFIG_IP_SET_HASH_MAC=m +CONFIG_IP_SET_HASH_NETPORTNET=m +CONFIG_IP_SET_HASH_NET=m +CONFIG_IP_SET_HASH_NETNET=m +CONFIG_IP_SET_HASH_NETPORT=m +CONFIG_IP_SET_HASH_NETIFACE=m +CONFIG_IP_SET_LIST_SET=m +CONFIG_IP_VS=m +CONFIG_IP_VS_IPV6=y +CONFIG_IP_VS_PROTO_TCP=y +CONFIG_IP_VS_PROTO_UDP=y +CONFIG_IP_VS_PROTO_ESP=y +CONFIG_IP_VS_PROTO_AH=y +CONFIG_IP_VS_PROTO_SCTP=y +CONFIG_IP_VS_RR=m +CONFIG_IP_VS_WRR=m +CONFIG_IP_VS_LC=m +CONFIG_IP_VS_WLC=m +CONFIG_IP_VS_FO=m +CONFIG_IP_VS_OVF=m +CONFIG_IP_VS_LBLC=m +CONFIG_IP_VS_LBLCR=m +CONFIG_IP_VS_DH=m +CONFIG_IP_VS_SH=m +CONFIG_IP_VS_MH=m +CONFIG_IP_VS_SED=m +CONFIG_IP_VS_NQ=m +CONFIG_IP_VS_TWOS=m +CONFIG_IP_VS_FTP=m +CONFIG_IP_VS_PE_SIP=m +CONFIG_NFT_DUP_IPV4=m +CONFIG_NFT_FIB_IPV4=m +CONFIG_NF_TABLES_ARP=y +CONFIG_NF_LOG_ARP=m +CONFIG_NF_LOG_IPV4=m +CONFIG_IP_NF_IPTABLES=m +CONFIG_IP_NF_MATCH_AH=m +CONFIG_IP_NF_MATCH_ECN=m +CONFIG_IP_NF_MATCH_RPFILTER=m +CONFIG_IP_NF_MATCH_TTL=m +CONFIG_IP_NF_TARGET_REJECT=m +CONFIG_IP_NF_TARGET_SYNPROXY=m +CONFIG_IP_NF_NAT=m +CONFIG_IP_NF_TARGET_MASQUERADE=m +CONFIG_IP_NF_TARGET_NETMAP=m +CONFIG_IP_NF_TARGET_REDIRECT=m +CONFIG_IP_NF_TARGET_ECN=m +CONFIG_IP_NF_TARGET_TTL=m +CONFIG_IP_NF_RAW=m +CONFIG_IP_NF_SECURITY=m +CONFIG_IP_NF_ARPFILTER=m +CONFIG_IP_NF_ARP_MANGLE=m +CONFIG_NFT_DUP_IPV6=m +CONFIG_NFT_FIB_IPV6=m +CONFIG_IP6_NF_IPTABLES=m +CONFIG_IP6_NF_MATCH_AH=m +CONFIG_IP6_NF_MATCH_EUI64=m +CONFIG_IP6_NF_MATCH_FRAG=m +CONFIG_IP6_NF_MATCH_OPTS=m +CONFIG_IP6_NF_MATCH_HL=m +CONFIG_IP6_NF_MATCH_IPV6HEADER=m +CONFIG_IP6_NF_MATCH_MH=m +CONFIG_IP6_NF_MATCH_RPFILTER=m +CONFIG_IP6_NF_MATCH_RT=m +CONFIG_IP6_NF_MATCH_SRH=m +CONFIG_IP6_NF_TARGET_HL=m +CONFIG_IP6_NF_TARGET_REJECT=m +CONFIG_IP6_NF_TARGET_SYNPROXY=m +CONFIG_IP6_NF_RAW=m +CONFIG_IP6_NF_SECURITY=m +CONFIG_IP6_NF_NAT=m +CONFIG_IP6_NF_TARGET_MASQUERADE=m +CONFIG_IP6_NF_TARGET_NPT=m +CONFIG_NF_TABLES_BRIDGE=m +CONFIG_NFT_BRIDGE_META=m +CONFIG_NFT_BRIDGE_REJECT=m +CONFIG_NF_CONNTRACK_BRIDGE=m +CONFIG_BRIDGE_NF_EBTABLES_LEGACY=m +CONFIG_BRIDGE_NF_EBTABLES=m +CONFIG_BRIDGE_EBT_BROUTE=m +CONFIG_BRIDGE_EBT_T_FILTER=m +CONFIG_BRIDGE_EBT_T_NAT=m +CONFIG_BRIDGE_EBT_802_3=m +CONFIG_BRIDGE_EBT_AMONG=m +CONFIG_BRIDGE_EBT_ARP=m +CONFIG_BRIDGE_EBT_IP=m +CONFIG_BRIDGE_EBT_IP6=m +CONFIG_BRIDGE_EBT_LIMIT=m +CONFIG_BRIDGE_EBT_MARK=m +CONFIG_BRIDGE_EBT_PKTTYPE=m +CONFIG_BRIDGE_EBT_STP=m +CONFIG_BRIDGE_EBT_VLAN=m +CONFIG_BRIDGE_EBT_ARPREPLY=m +CONFIG_BRIDGE_EBT_DNAT=m +CONFIG_BRIDGE_EBT_MARK_T=m +CONFIG_BRIDGE_EBT_REDIRECT=m +CONFIG_BRIDGE_EBT_SNAT=m +CONFIG_BRIDGE_EBT_LOG=m +CONFIG_BRIDGE_EBT_NFLOG=m +CONFIG_IP_SCTP=m +CONFIG_TIPC=m +CONFIG_ATM=m +CONFIG_ATM_BR2684=m +CONFIG_L2TP=m +CONFIG_L2TP_DEBUGFS=m +CONFIG_L2TP_V3=y +CONFIG_L2TP_IP=m +CONFIG_L2TP_ETH=m +CONFIG_BRIDGE=m +CONFIG_BRIDGE_VLAN_FILTERING=y +CONFIG_BRIDGE_MRP=y +CONFIG_BRIDGE_CFM=y +CONFIG_NET_DSA=m +CONFIG_NET_DSA_TAG_GSWIP=m +CONFIG_NET_DSA_TAG_KSZ=m +CONFIG_NET_DSA_TAG_OCELOT=m +CONFIG_NET_DSA_TAG_OCELOT_8021Q=m +CONFIG_NET_DSA_TAG_RTL4_A=m +CONFIG_NET_DSA_TAG_RTL8_4=m +CONFIG_NET_DSA_TAG_SJA1105=m +CONFIG_NET_DSA_TAG_TRAILER=m +CONFIG_VLAN_8021Q=m +CONFIG_VLAN_8021Q_GVRP=y +CONFIG_VLAN_8021Q_MVRP=y +CONFIG_6LOWPAN=m +CONFIG_6LOWPAN_DEBUGFS=y +CONFIG_6LOWPAN_GHC_EXT_HDR_HOP=m +CONFIG_6LOWPAN_GHC_UDP=m +CONFIG_6LOWPAN_GHC_ICMPV6=m +CONFIG_6LOWPAN_GHC_EXT_HDR_DEST=m +CONFIG_6LOWPAN_GHC_EXT_HDR_FRAG=m +CONFIG_6LOWPAN_GHC_EXT_HDR_ROUTE=m +CONFIG_IEEE802154=m +CONFIG_IEEE802154_6LOWPAN=m +CONFIG_MAC802154=m +CONFIG_NET_SCHED=y +CONFIG_NET_SCH_HTB=m +CONFIG_NET_SCH_HFSC=m +CONFIG_NET_SCH_PRIO=m +CONFIG_NET_SCH_MULTIQ=m +CONFIG_NET_SCH_RED=m +CONFIG_NET_SCH_SFB=m +CONFIG_NET_SCH_SFQ=m +CONFIG_NET_SCH_TEQL=m +CONFIG_NET_SCH_TBF=m +CONFIG_NET_SCH_CBS=m +CONFIG_NET_SCH_ETF=m +CONFIG_NET_SCH_TAPRIO=m +CONFIG_NET_SCH_GRED=m +CONFIG_NET_SCH_NETEM=m +CONFIG_NET_SCH_DRR=m +CONFIG_NET_SCH_MQPRIO=m +CONFIG_NET_SCH_CHOKE=m +CONFIG_NET_SCH_QFQ=m +CONFIG_NET_SCH_CODEL=m +CONFIG_NET_SCH_FQ_CODEL=y +CONFIG_NET_SCH_CAKE=m +CONFIG_NET_SCH_FQ=m +CONFIG_NET_SCH_HHF=m +CONFIG_NET_SCH_PIE=m +CONFIG_NET_SCH_FQ_PIE=m +CONFIG_NET_SCH_INGRESS=m +CONFIG_NET_SCH_PLUG=m +CONFIG_NET_SCH_ETS=m +CONFIG_NET_SCH_BPF=y +CONFIG_NET_SCH_DUALPI2=m +CONFIG_NET_CLS_BASIC=m +CONFIG_NET_CLS_ROUTE4=m +CONFIG_NET_CLS_FW=m +CONFIG_NET_CLS_U32=m +CONFIG_CLS_U32_PERF=y +CONFIG_CLS_U32_MARK=y +CONFIG_NET_CLS_FLOW=m +CONFIG_NET_CLS_CGROUP=y +CONFIG_NET_CLS_BPF=m +CONFIG_NET_CLS_FLOWER=m +CONFIG_NET_CLS_MATCHALL=m +CONFIG_NET_EMATCH=y +CONFIG_NET_EMATCH_CMP=m +CONFIG_NET_EMATCH_NBYTE=m +CONFIG_NET_EMATCH_U32=m +CONFIG_NET_EMATCH_META=m +CONFIG_NET_EMATCH_TEXT=m +CONFIG_NET_EMATCH_CANID=m +CONFIG_NET_EMATCH_IPSET=m +CONFIG_NET_EMATCH_IPT=m +CONFIG_NET_CLS_ACT=y +CONFIG_NET_ACT_POLICE=m +CONFIG_NET_ACT_GACT=m +CONFIG_GACT_PROB=y +CONFIG_NET_ACT_MIRRED=m +CONFIG_NET_ACT_SAMPLE=m +CONFIG_NET_ACT_NAT=m +CONFIG_NET_ACT_PEDIT=m +CONFIG_NET_ACT_SIMP=m +CONFIG_NET_ACT_SKBEDIT=m +CONFIG_NET_ACT_CSUM=m +CONFIG_NET_ACT_MPLS=m +CONFIG_NET_ACT_VLAN=m +CONFIG_NET_ACT_BPF=m +CONFIG_NET_ACT_CONNMARK=m +CONFIG_NET_ACT_CTINFO=m +CONFIG_NET_ACT_SKBMOD=m +CONFIG_NET_ACT_IFE=m +CONFIG_NET_ACT_TUNNEL_KEY=m +CONFIG_NET_ACT_CT=m +CONFIG_NET_ACT_GATE=m +CONFIG_NET_IFE_SKBMARK=m +CONFIG_NET_IFE_SKBPRIO=m +CONFIG_NET_IFE_SKBTCINDEX=m +CONFIG_NET_TC_SKB_EXT=y +CONFIG_DCB=y +CONFIG_BATMAN_ADV=m +CONFIG_BATMAN_ADV_TRACING=y +CONFIG_OPENVSWITCH=m +CONFIG_VSOCKETS=m +CONFIG_VMWARE_VMCI_VSOCKETS=m +CONFIG_VIRTIO_VSOCKETS=m +CONFIG_HYPERV_VSOCKETS=m +CONFIG_NETLINK_DIAG=y +CONFIG_MPLS_ROUTING=m +CONFIG_MPLS_IPTUNNEL=m +CONFIG_HSR=m +CONFIG_QRTR_SMD=m +CONFIG_NET_NCSI=y +CONFIG_NCSI_OEM_CMD_GET_MAC=y +CONFIG_NCSI_OEM_CMD_KEEP_PHY=y +CONFIG_CGROUP_NET_PRIO=y +CONFIG_BPF_STREAM_PARSER=y +CONFIG_NET_PKTGEN=m +CONFIG_NET_DROP_MONITOR=y +CONFIG_CAN=y +CONFIG_CAN_RAW=m +CONFIG_CAN_BCM=m +CONFIG_CAN_GW=m +CONFIG_CAN_J1939=m +CONFIG_CAN_ISOTP=m +CONFIG_BT=m +CONFIG_BT_RFCOMM=m +CONFIG_BT_RFCOMM_TTY=y +CONFIG_BT_BNEP=m +CONFIG_BT_BNEP_MC_FILTER=y +CONFIG_BT_BNEP_PROTO_FILTER=y +CONFIG_BT_HIDP=m +CONFIG_BT_6LOWPAN=m +CONFIG_BT_LEDS=y +CONFIG_BT_MSFTEXT=y +CONFIG_BT_AOSPEXT=y +CONFIG_BT_BRCMEXT=y +# CONFIG_BT_DEBUGFS is not set +CONFIG_BT_MTK7932_PCIE=m +CONFIG_BT_HCIBTUSB=m +CONFIG_BT_HCIBTUSB_AUTOSUSPEND=y +CONFIG_BT_HCIBTUSB_MTK=y +CONFIG_BT_HCIBTSDIO=m +CONFIG_BT_HCIUART=m +CONFIG_BT_HCIUART_NOKIA=m +CONFIG_BT_HCIUART_BCSP=y +CONFIG_BT_HCIUART_ATH3K=y +CONFIG_BT_HCIUART_LL=y +CONFIG_BT_HCIUART_INTEL=y +CONFIG_BT_HCIUART_BCM=y +CONFIG_BT_HCIUART_RTL=y +CONFIG_BT_HCIUART_QCA=y +CONFIG_BT_HCIUART_AG6XX=y +CONFIG_BT_HCIUART_MRVL=y +CONFIG_BT_HCIBCM203X=m +CONFIG_BT_HCIBCM4377=m +CONFIG_BT_HCIBPA10X=m +CONFIG_BT_HCIBFUSB=m +CONFIG_BT_HCIVHCI=m +CONFIG_BT_MRVL=m +CONFIG_BT_MRVL_SDIO=m +CONFIG_BT_ATH3K=m +CONFIG_BT_MTKSDIO=m +CONFIG_BT_MTKUART=m +CONFIG_BT_QCOMSMD=m +CONFIG_BT_VIRTIO=m +CONFIG_BT_NXPUART=m +CONFIG_BT_INTEL_PCIE=m +CONFIG_BT_CENTAURI=m +CONFIG_BT_HCICENTAURI=m +CONFIG_AF_RXRPC_IPV6=y +CONFIG_AF_RXRPC_DEBUG=y +CONFIG_RXKAD=y +CONFIG_RXGK=y +CONFIG_AF_KCM=m +CONFIG_MCTP=y +CONFIG_CFG80211=m +CONFIG_CFG80211_DEBUGFS=y +CONFIG_MAC80211=m +CONFIG_MAC80211_MESH=y +CONFIG_MAC80211_DEBUGFS=y +CONFIG_RFKILL=m +CONFIG_RFKILL_INPUT=y +CONFIG_RFKILL_GPIO=m +CONFIG_NET_9P=m +CONFIG_NET_9P_VIRTIO=m +CONFIG_NET_9P_USBG=m +CONFIG_NET_9P_RDMA=m +CONFIG_NFC=m +CONFIG_NFC_DIGITAL=m +CONFIG_NFC_NCI=m +CONFIG_NFC_NCI_SPI=m +CONFIG_NFC_HCI=m +CONFIG_NFC_SHDLC=y +CONFIG_NFC_TRF7970A=m +CONFIG_NFC_SIM=m +CONFIG_NFC_PORT100=m +CONFIG_NFC_APPLE_STOCKHOLM=m +CONFIG_NFC_PN544_I2C=m +CONFIG_NFC_PN533_USB=m +CONFIG_NFC_PN533_I2C=m +CONFIG_NFC_PN532_UART=m +CONFIG_NFC_MICROREAD_I2C=m +CONFIG_NFC_MRVL_USB=m +CONFIG_NFC_ST21NFCA_I2C=m +CONFIG_NFC_NXP_NCI=m +CONFIG_NFC_NXP_NCI_I2C=m +CONFIG_PCI=y +CONFIG_PCIEAER=y +CONFIG_PCIEAER_INJECT=m +CONFIG_PCIE_ECRC=y +CONFIG_PCIE_DPC=y +CONFIG_PCIE_PTM=y +CONFIG_PCIE_EDR=y +CONFIG_PCI_STUB=y +CONFIG_PCI_PF_STUB=m +CONFIG_PCI_NPEM=y +CONFIG_PCI_PRI=y +CONFIG_PCI_PASID=y +CONFIG_PCIE_TPH=y +CONFIG_PCI_P2PDMA=y +CONFIG_PCI_HYPERV=m +CONFIG_PCI_DYNAMIC_OF_NODES=y +CONFIG_HOTPLUG_PCI_ACPI=y +CONFIG_HOTPLUG_PCI_ACPI_AMPERE_ALTRA=m +CONFIG_HOTPLUG_PCI_ACPI_IBM=m +CONFIG_HOTPLUG_PCI_OCTEONEP=y +CONFIG_PCI_AARDVARK=y +CONFIG_PCIE_APPLE_T8140_BOOTSTRAP=y +CONFIG_PCIE_APPLE=y +CONFIG_PCIE_APPLE_MSI=y +CONFIG_PCIE_BRCMSTB=y +CONFIG_PCI_HOST_THUNDER_PEM=y +CONFIG_PCI_HOST_THUNDER_ECAM=y +CONFIG_PCI_HOST_GENERIC=y +CONFIG_PCI_HYPERV_INTERFACE=y +CONFIG_PCI_TEGRA=y +CONFIG_PCIE_RENESAS_RZG3S_HOST=y +CONFIG_PCIE_ROCKCHIP_HOST=y +CONFIG_PCI_XGENE=y +CONFIG_PCIE_XILINX=y +CONFIG_PCIE_XILINX_DMA_PL=y +CONFIG_PCIE_XILINX_NWL=y +CONFIG_PCIE_XILINX_CPM=y +CONFIG_PCIE_CADENCE_PLAT_HOST=y +CONFIG_PCI_SKY1_HOST=y +CONFIG_PCI_J721E_HOST=y +CONFIG_PCI_MESON=y +CONFIG_PCI_IMX6_HOST=y +CONFIG_PCI_LAYERSCAPE=y +CONFIG_PCI_HISI=y +CONFIG_PCIE_KIRIN=y +CONFIG_PCIE_HISI_STB=y +CONFIG_PCIE_ARMADA_8K=y +CONFIG_PCIE_TEGRA194_HOST=y +CONFIG_PCIE_NXP_S32G=y +CONFIG_PCIE_DW_PLAT_HOST=y +CONFIG_PCIE_QCOM=y +CONFIG_PCIE_ROCKCHIP_DW_HOST=y +CONFIG_PCI_KEYSTONE_HOST=y +CONFIG_PCIE_LAYERSCAPE_GEN4=y +CONFIG_PCIE_MOBIVEIL_PLAT=y +CONFIG_PCIE_MICROCHIP_HOST=y +CONFIG_PCI_SW_SWITCHTEC=m +CONFIG_CXL_BUS=m +CONFIG_CXL_FEATURES=y +CONFIG_RAPIDIO=m +CONFIG_RAPIDIO_TSI721=m +CONFIG_RAPIDIO_DMA_ENGINE=y +CONFIG_RAPIDIO_ENUM_BASIC=m +CONFIG_RAPIDIO_CHMAN=m +CONFIG_RAPIDIO_MPORT_CDEV=m +CONFIG_RAPIDIO_CPS_XX=m +CONFIG_RAPIDIO_CPS_GEN2=m +CONFIG_RAPIDIO_RXS_GEN3=m +CONFIG_DEVTMPFS=y +CONFIG_DEVTMPFS_MOUNT=y +CONFIG_DEVTMPFS_SAFE=y +CONFIG_FW_LOADER_COMPRESS=y +CONFIG_FW_LOADER_COMPRESS_ZSTD=y +# CONFIG_DM_KUNIT_TEST is not set +CONFIG_MOXTET=m +CONFIG_HISILICON_LPC=y +CONFIG_IMX_AIPSTZ=m +# CONFIG_QCOM_EBI2 is not set +CONFIG_QCOM_SSC_BLOCK_BUS=y +CONFIG_SUNXI_RSB=m +CONFIG_TEGRA_ACONNECT=m +CONFIG_TEGRA_GMI=m +CONFIG_FSL_MC_UAPI_SUPPORT=y +CONFIG_MHI_BUS_PCI_GENERIC=m +CONFIG_CONNECTOR=y +CONFIG_ARM_SCMI_PROTOCOL=y +CONFIG_ARM_SCMI_TRANSPORT_VIRTIO=y +CONFIG_ARM_SCMI_POWER_CONTROL=y +CONFIG_ARM_SCPI_PROTOCOL=m +CONFIG_FIRMWARE_MEMMAP=y +CONFIG_DMI_SYSFS=y +CONFIG_ISCSI_IBFT=m +CONFIG_FW_CFG_SYSFS=m +CONFIG_SYSFB_SIMPLEFB=y +CONFIG_TURRIS_MOX_RWTM=m +CONFIG_ARM_FFA_TRANSPORT=y +CONFIG_EFI_VARS_PSTORE_DEFAULT_DISABLE=y +CONFIG_EFI_ZBOOT=y +CONFIG_EFI_TEST=m +CONFIG_OVMF_DEBUG_LOG=y +CONFIG_TEE_STMM_EFI=m +CONFIG_IMX_DSP=m +CONFIG_IMX_SCU=y +CONFIG_IMX_SCMI_MISC_DRV=m +CONFIG_QCOM_QSEECOM=y +CONFIG_QCOM_QSEECOM_UEFISECAPP=y +CONFIG_TEGRA_BPMP=y +CONFIG_FWCTL_MLX5=m +CONFIG_FWCTL_PDS=m +CONFIG_GNSS=m +CONFIG_GNSS_MTK_SERIAL=m +CONFIG_GNSS_SIRF_SERIAL=m +CONFIG_GNSS_UBX_SERIAL=m +CONFIG_GNSS_USB=m +CONFIG_MTD=y +CONFIG_MTD_OF_PARTS=m +CONFIG_MTD_BLOCK=m +CONFIG_MTD_CFI=m +CONFIG_MTD_CFI_INTELEXT=m +CONFIG_MTD_CFI_AMDSTD=m +CONFIG_MTD_CFI_STAA=m +CONFIG_MTD_PHYSMAP=m +CONFIG_MTD_PHYSMAP_OF=y +CONFIG_MTD_DATAFLASH=m +CONFIG_MTD_DATAFLASH_WRITE_VERIFY=y +CONFIG_MTD_DATAFLASH_OTP=y +CONFIG_MTD_MCHP48L640=m +CONFIG_MTD_SST25L=m +CONFIG_MTD_PHRAM=m +CONFIG_MTD_MTDRAM=m +CONFIG_MTD_BLOCK2MTD=m +CONFIG_MTD_RAW_NAND=m +CONFIG_MTD_NAND_MARVELL=m +CONFIG_MTD_NAND_TEGRA=m +CONFIG_MTD_NAND_CADENCE=m +CONFIG_MTD_NAND_NANDSIM=m +CONFIG_MTD_SPI_NAND=m +CONFIG_MTD_NAND_ECC_MXIC=y +CONFIG_MTD_SPI_NOR=m +CONFIG_SPI_HISI_SFC=m +CONFIG_MTD_UBI=m +CONFIG_MTD_UBI_NVMEM=m +# CONFIG_PNP_DEBUG_MESSAGES is not set +CONFIG_BLK_DEV_NULL_BLK=m +CONFIG_BLK_DEV_RUST_NULL=m +CONFIG_ZRAM=m +CONFIG_ZRAM_BACKEND_LZ4=y +CONFIG_ZRAM_BACKEND_LZ4HC=y +CONFIG_ZRAM_BACKEND_ZSTD=y +CONFIG_ZRAM_BACKEND_DEFLATE=y +CONFIG_ZRAM_BACKEND_842=y +CONFIG_ZRAM_BACKEND_LZO=y +CONFIG_ZRAM_WRITEBACK=y +CONFIG_ZRAM_MULTI_COMP=y +CONFIG_BLK_DEV_LOOP=m +CONFIG_BLK_DEV_LOOP_MIN_COUNT=0 +CONFIG_BLK_DEV_DRBD=m +CONFIG_BLK_DEV_NBD=m +CONFIG_BLK_DEV_RAM=m +CONFIG_BLK_DEV_RAM_SIZE=16384 +CONFIG_ATA_OVER_ETH=m +CONFIG_VIRTIO_BLK=y +CONFIG_BLK_DEV_RBD=m +CONFIG_BLK_DEV_UBLK=m +CONFIG_BLK_DEV_RNBD_CLIENT=m +CONFIG_BLK_DEV_RNBD_SERVER=m +CONFIG_BLK_DEV_ZONED_LOOP=m +CONFIG_BLK_DEV_NVME=m +CONFIG_NVME_MULTIPATH=y +CONFIG_NVME_HWMON=y +CONFIG_NVME_RDMA=m +CONFIG_NVME_FC=m +CONFIG_NVME_TCP=m +CONFIG_NVME_TCP_TLS=y +CONFIG_NVME_HOST_AUTH=y +CONFIG_NVME_APPLE=m +CONFIG_NVME_TARGET=m +CONFIG_NVME_TARGET_PASSTHRU=y +CONFIG_NVME_TARGET_LOOP=m +CONFIG_NVME_TARGET_RDMA=m +CONFIG_NVME_TARGET_FC=m +CONFIG_NVME_TARGET_FCLOOP=m +CONFIG_NVME_TARGET_TCP=m +CONFIG_NVME_TARGET_TCP_TLS=y +CONFIG_NVME_TARGET_AUTH=y +CONFIG_RPMB=m +CONFIG_TI_FPC202=m +CONFIG_ENCLOSURE_SERVICES=m +CONFIG_SMPRO_ERRMON=m +CONFIG_SMPRO_MISC=m +CONFIG_HI6421V600_IRQ=m +CONFIG_QCOM_COINCELL=m +CONFIG_QCOM_FASTRPC=m +CONFIG_APDS9802ALS=m +CONFIG_ISL29003=m +CONFIG_ISL29020=m +CONFIG_SENSORS_TSL2550=m +CONFIG_SENSORS_BH1770=m +CONFIG_DW_XDATA_PCIE=m +CONFIG_XILINX_SDFEC=m +CONFIG_OPEN_DICE=m +CONFIG_NTSYNC=m +CONFIG_VCPU_STALL_DETECTOR=m +CONFIG_NSM=m +CONFIG_EEPROM_MAX6875=m +CONFIG_EEPROM_IDT_89HPESX=m +CONFIG_SENSORS_LIS3_I2C=m +CONFIG_VMWARE_VMCI=m +CONFIG_BCM_VK=m +CONFIG_BCM_VK_TTY=y +CONFIG_MISC_ALCOR_PCI=m +CONFIG_MISC_RTSX_PCI=m +CONFIG_MISC_RTSX_USB=m +CONFIG_UACCE=m +CONFIG_PVPANIC=y +CONFIG_PVPANIC_PCI=m +CONFIG_GP_PCI1XXXX=m +CONFIG_MISC_RP1=m +CONFIG_BLK_DEV_SD=y +CONFIG_CHR_DEV_ST=m +CONFIG_BLK_DEV_SR=y +CONFIG_CHR_DEV_SG=y +CONFIG_CHR_DEV_SCH=m +CONFIG_SCSI_ENCLOSURE=m +CONFIG_SCSI_CONSTANTS=y +CONFIG_SCSI_LOGGING=y +CONFIG_SCSI_SCAN_ASYNC=y +CONFIG_SCSI_FC_ATTRS=m +CONFIG_SCSI_SAS_ATA=y +CONFIG_ISCSI_TCP=m +CONFIG_SCSI_CXGB3_ISCSI=m +CONFIG_SCSI_CXGB4_ISCSI=m +CONFIG_SCSI_BNX2_ISCSI=m +CONFIG_SCSI_BNX2X_FCOE=m +CONFIG_BE2ISCSI=m +CONFIG_SCSI_HPSA=m +CONFIG_SCSI_MVSAS=m +# CONFIG_SCSI_MVSAS_DEBUG is not set +CONFIG_SCSI_MVSAS_TASKLET=y +CONFIG_SCSI_MVUMI=m +CONFIG_SCSI_ARCMSR=m +CONFIG_SCSI_ESAS2R=m +CONFIG_MEGARAID_NEWGEN=y +CONFIG_MEGARAID_MM=m +CONFIG_MEGARAID_MAILBOX=m +CONFIG_MEGARAID_LEGACY=m +CONFIG_MEGARAID_SAS=m +CONFIG_SCSI_MPT3SAS=m +CONFIG_SCSI_MPI3MR=m +CONFIG_SCSI_SMARTPQI=m +CONFIG_SCSI_HPTIOP=m +CONFIG_SCSI_MYRB=m +CONFIG_SCSI_MYRS=m +CONFIG_LIBFC=m +CONFIG_LIBFCOE=m +CONFIG_FCOE=m +CONFIG_SCSI_SNIC=m +CONFIG_SCSI_DMX3191D=m +CONFIG_SCSI_FDOMAIN_PCI=m +CONFIG_SCSI_INITIO=m +CONFIG_SCSI_INIA100=m +CONFIG_SCSI_STEX=m +CONFIG_SCSI_SYM53C8XX_2=m +CONFIG_SCSI_IPR=m +CONFIG_SCSI_QLOGIC_1280=m +CONFIG_SCSI_QLA_FC=m +CONFIG_TCM_QLA2XXX=m +CONFIG_SCSI_QLA_ISCSI=m +CONFIG_QEDI=m +CONFIG_QEDF=m +CONFIG_SCSI_LPFC=m +CONFIG_SCSI_EFCT=m +CONFIG_SCSI_DC395x=m +CONFIG_SCSI_AM53C974=m +CONFIG_SCSI_WD719X=m +CONFIG_SCSI_DEBUG=m +CONFIG_SCSI_PMCRAID=m +CONFIG_SCSI_VIRTIO=m +CONFIG_SCSI_CHELSIO_FCOE=m +CONFIG_SCSI_DH=y +CONFIG_SCSI_DH_RDAC=m +CONFIG_SCSI_DH_HP_SW=m +CONFIG_SCSI_DH_EMC=m +CONFIG_SCSI_DH_ALUA=m +CONFIG_ATA=y +CONFIG_SATA_AHCI=y +CONFIG_SATA_AHCI_PLATFORM=m +CONFIG_AHCI_DWC=m +CONFIG_AHCI_IMX=m +CONFIG_AHCI_CEVA=m +CONFIG_AHCI_MVEBU=m +CONFIG_AHCI_SUNXI=m +CONFIG_AHCI_TEGRA=m +CONFIG_AHCI_XGENE=m +CONFIG_AHCI_QORIQ=m +CONFIG_SATA_AHCI_SEATTLE=m +CONFIG_SATA_ACARD_AHCI=m +CONFIG_SATA_SIL24=m +CONFIG_PDC_ADMA=m +CONFIG_ATA_PIIX=y +CONFIG_SATA_MV=m +CONFIG_PATA_MARVELL=m +CONFIG_PATA_ACPI=m +CONFIG_ATA_GENERIC=m +CONFIG_MD=y +CONFIG_BLK_DEV_MD=y +CONFIG_MD_LINEAR=m +CONFIG_BCACHE=m +CONFIG_BLK_DEV_DM=y +CONFIG_DM_DEBUG=y +CONFIG_DM_UNSTRIPED=m +CONFIG_DM_CRYPT=m +CONFIG_DM_SNAPSHOT=y +CONFIG_DM_THIN_PROVISIONING=m +CONFIG_DM_CACHE=m +CONFIG_DM_WRITECACHE=m +CONFIG_DM_EBS=m +CONFIG_DM_ERA=m +CONFIG_DM_CLONE=m +CONFIG_DM_MIRROR=y +CONFIG_DM_LOG_USERSPACE=m +CONFIG_DM_RAID=m +CONFIG_DM_ZERO=y +CONFIG_DM_MULTIPATH=m +CONFIG_DM_MULTIPATH_QL=m +CONFIG_DM_MULTIPATH_ST=m +CONFIG_DM_MULTIPATH_HST=m +CONFIG_DM_MULTIPATH_IOA=m +CONFIG_DM_DELAY=m +CONFIG_DM_DUST=m +CONFIG_DM_INIT=y +CONFIG_DM_UEVENT=y +CONFIG_DM_FLAKEY=m +CONFIG_DM_VERITY=m +CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG=y +CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_SECONDARY_KEYRING=y +CONFIG_DM_VERITY_FEC=y +CONFIG_DM_SWITCH=m +CONFIG_DM_LOG_WRITES=m +CONFIG_DM_INTEGRITY=m +CONFIG_DM_ZONED=m +CONFIG_DM_VDO=m +CONFIG_TARGET_CORE=m +CONFIG_TCM_IBLOCK=m +CONFIG_TCM_FILEIO=m +CONFIG_TCM_PSCSI=m +CONFIG_TCM_USER2=m +CONFIG_LOOPBACK_TARGET=m +CONFIG_TCM_FC=m +CONFIG_ISCSI_TARGET=m +CONFIG_ISCSI_TARGET_CXGB4=m +CONFIG_REMOTE_TARGET=m +CONFIG_BONDING=m +CONFIG_DUMMY=m +CONFIG_WIREGUARD=m +CONFIG_OVPN=m +CONFIG_EQUALIZER=m +CONFIG_NET_FC=y +CONFIG_IFB=m +CONFIG_NET_TEAM=m +CONFIG_NET_TEAM_MODE_BROADCAST=m +CONFIG_NET_TEAM_MODE_ROUNDROBIN=m +CONFIG_NET_TEAM_MODE_RANDOM=m +CONFIG_NET_TEAM_MODE_ACTIVEBACKUP=m +CONFIG_NET_TEAM_MODE_LOADBALANCE=m +CONFIG_MACVLAN=m +CONFIG_MACVTAP=m +CONFIG_IPVLAN=m +CONFIG_IPVTAP=m +CONFIG_VXLAN=m +CONFIG_GENEVE=m +CONFIG_BAREUDP=m +CONFIG_GTP=m +CONFIG_PFCP=m +CONFIG_AMT=m +CONFIG_MACSEC=m +CONFIG_NETCONSOLE=m +CONFIG_NETCONSOLE_DYNAMIC=y +CONFIG_RIONET=m +CONFIG_TUN=m +CONFIG_VETH=m +CONFIG_VIRTIO_NET=m +CONFIG_NLMON=m +CONFIG_NETKIT=y +CONFIG_NET_VRF=m +CONFIG_VSOCKMON=m +CONFIG_MHI_NET=m +# CONFIG_ATM_DRIVERS is not set +CONFIG_B53_SPI_DRIVER=m +CONFIG_B53_MDIO_DRIVER=m +CONFIG_B53_MMAP_DRIVER=m +CONFIG_B53_SRAB_DRIVER=m +CONFIG_B53_SERDES=m +CONFIG_NET_DSA_BCM_SF2=m +CONFIG_NET_DSA_LOOP=m +CONFIG_NET_DSA_HIRSCHMANN_HELLCREEK=m +CONFIG_NET_DSA_MT7530=m +CONFIG_NET_DSA_MV88E6XXX=m +CONFIG_NET_DSA_MV88E6XXX_PTP=y +CONFIG_NET_DSA_MXL862=m +CONFIG_NET_DSA_QCA8K=m +CONFIG_NET_DSA_QCA8K_LEDS_SUPPORT=y +CONFIG_NET_DSA_XRS700X_I2C=m +CONFIG_NET_DSA_XRS700X_MDIO=m +CONFIG_NET_DSA_REALTEK=m +CONFIG_NET_DSA_SMSC_LAN9303_I2C=m +CONFIG_NET_DSA_SMSC_LAN9303_MDIO=m +# CONFIG_NET_VENDOR_3COM is not set +# CONFIG_NET_VENDOR_ADAPTEC is not set +CONFIG_ET131X=m +# CONFIG_NET_VENDOR_ALACRITECH is not set +CONFIG_ALTERA_TSE=m +CONFIG_ENA_ETHERNET=m +CONFIG_AMD8111_ETH=m +CONFIG_PCNET32=m +CONFIG_AMD_XGBE=m +CONFIG_AMD_XGBE_DCB=y +CONFIG_PDS_CORE=m +CONFIG_NET_XGENE=m +CONFIG_NET_XGENE_V2=m +CONFIG_AQTION=m +CONFIG_EMAC_ROCKCHIP=m +CONFIG_SPI_AX88796C=m +CONFIG_SPI_AX88796C_COMPRESSION=y +CONFIG_ATL2=m +CONFIG_ATL1=m +CONFIG_ATL1E=m +CONFIG_ATL1C=m +CONFIG_ALX=m +CONFIG_B44=m +CONFIG_BCMGENET=m +CONFIG_TIGON3=m +CONFIG_BNX2X=m +CONFIG_BNXT=m +CONFIG_BNXT_DCB=y +CONFIG_BNGE=m +CONFIG_MACB=m +CONFIG_MACB_PCI=m +CONFIG_THUNDER_NIC_PF=m +CONFIG_THUNDER_NIC_VF=m +CONFIG_CHELSIO_T1=m +CONFIG_CHELSIO_T1_1G=y +CONFIG_CHELSIO_T4_DCB=y +CONFIG_CHELSIO_T4VF=m +CONFIG_CHELSIO_IPSEC_INLINE=m +CONFIG_CHELSIO_TLS_DEVICE=m +# CONFIG_NET_VENDOR_CISCO is not set +# CONFIG_NET_VENDOR_CORTINA is not set +CONFIG_DM9051=m +# CONFIG_NET_VENDOR_DEC is not set +CONFIG_DL2K=m +CONFIG_SUNDANCE=m +# CONFIG_BE2NET_HWMON is not set +CONFIG_TSNEP=m +# CONFIG_NET_VENDOR_EZCHIP is not set +CONFIG_FEC=m +CONFIG_FSL_FMAN=m +CONFIG_GIANFAR=m +CONFIG_FSL_DPAA_ETH=m +CONFIG_FSL_DPAA2_ETH=m +CONFIG_FSL_DPAA2_ETH_DCB=y +CONFIG_FSL_DPAA2_SWITCH=m +CONFIG_FSL_ENETC=m +CONFIG_NXP_ENETC4=m +CONFIG_FSL_ENETC_VF=m +CONFIG_FSL_ENETC_QOS=y +CONFIG_FUN_ETH=m +CONFIG_GVE=m +CONFIG_HNS_DSAF=m +CONFIG_HNS_ENET=m +CONFIG_HNS3=m +CONFIG_HNS3_DCB=y +CONFIG_HNS3_HCLGEVF=m +CONFIG_HIBMCGE=m +# CONFIG_NET_VENDOR_HUAWEI is not set +# CONFIG_NET_VENDOR_I825XX is not set +CONFIG_E100=m +CONFIG_E1000=m +CONFIG_E1000E=m +CONFIG_IGB=m +CONFIG_IGBVF=m +CONFIG_IXGBE=m +CONFIG_IXGBE_DCB=y +CONFIG_IXGBEVF=m +CONFIG_I40E=m +CONFIG_I40EVF=m +CONFIG_ICE=m +CONFIG_FM10K=m +CONFIG_IGC=m +CONFIG_IDPF=m +CONFIG_IDPF_SINGLEQ=y +CONFIG_JME=m +CONFIG_ADIN1110=m +CONFIG_LITEX_LITEETH=m +CONFIG_MVNETA=m +CONFIG_MVPP2=m +CONFIG_MVPP2_PTP=y +CONFIG_SKGE=m +CONFIG_SKGE_GENESIS=y +CONFIG_SKY2=m +CONFIG_OCTEONTX2_AF=m +CONFIG_OCTEONTX2_PF=m +CONFIG_OCTEONTX2_VF=m +CONFIG_OCTEON_EP=m +CONFIG_OCTEON_EP_VF=m +CONFIG_PRESTERA=m +CONFIG_MLX4_EN=m +CONFIG_MLX5_CORE=m +CONFIG_MLX5_FPGA=y +CONFIG_MLX5_CORE_EN=y +CONFIG_MLX5_CORE_IPOIB=y +CONFIG_MLX5_MACSEC=y +CONFIG_MLX5_EN_IPSEC=y +CONFIG_MLX5_EN_TLS=y +CONFIG_MLX5_SF=y +CONFIG_MLX5_DPLL=m +CONFIG_MLXSW_CORE=m +CONFIG_MLXBF_GIGE=m +CONFIG_KSZ884X_PCI=m +CONFIG_LAN743X=m +CONFIG_LAN966X_SWITCH=m +# CONFIG_NET_VENDOR_MICROSEMI is not set +CONFIG_MICROSOFT_MANA=m +# CONFIG_NET_VENDOR_MUCSE is not set +CONFIG_MYRI10GE=m +CONFIG_FEALNX=m +# CONFIG_NET_VENDOR_NI is not set +CONFIG_NATSEMI=m +CONFIG_NS83820=m +CONFIG_NFP=m +# CONFIG_NFP_APP_ABM_NIC is not set +CONFIG_NE2K_PCI=m +CONFIG_FORCEDETH=m +CONFIG_ETHOC=m +CONFIG_IONIC=m +CONFIG_QLA3XXX=m +CONFIG_QLCNIC=m +CONFIG_NETXEN_NIC=m +CONFIG_QED=m +CONFIG_QEDE=m +# CONFIG_NET_VENDOR_BROCADE is not set +# CONFIG_NET_VENDOR_QUALCOMM is not set +CONFIG_R6040=m +CONFIG_8139CP=m +CONFIG_8139TOO=m +# CONFIG_8139TOO_PIO is not set +CONFIG_8139TOO_8129=y +CONFIG_R8169=m +CONFIG_R8169_LEDS=y +CONFIG_RAVB=m +CONFIG_RTSN=m +CONFIG_ROCKER=m +# CONFIG_NET_VENDOR_SAMSUNG is not set +# CONFIG_NET_VENDOR_SEEQ is not set +CONFIG_SC92031=m +CONFIG_SIS900=m +CONFIG_SIS190=m +# CONFIG_NET_VENDOR_SOLARFLARE is not set +CONFIG_SMC91X=m +CONFIG_EPIC100=m +CONFIG_SMSC911X=m +CONFIG_SMSC9420=m +CONFIG_SNI_NETSEC=m +CONFIG_STMMAC_ETH=m +CONFIG_DWMAC_DWC_QOS_ETH=m +CONFIG_DWMAC_TEGRA=m +CONFIG_DWMAC_MOTORCOMM=m +# CONFIG_NET_VENDOR_SUN is not set +# CONFIG_NET_VENDOR_SYNOPSYS is not set +CONFIG_TEHUTI=m +CONFIG_TEHUTI_TN40=m +CONFIG_TI_K3_AM65_CPSW_NUSS=m +CONFIG_TI_K3_AM65_CPSW_SWITCHDEV=y +CONFIG_TI_K3_AM65_CPTS=m +CONFIG_TI_AM65_CPSW_QOS=y +CONFIG_TI_ICSSG_PRUETH=m +CONFIG_TI_ICSSG_PRUETH_SR1=m +CONFIG_TI_PRUETH=m +CONFIG_MSE102X=m +CONFIG_VIA_RHINE=m +CONFIG_VIA_RHINE_MMIO=y +CONFIG_VIA_VELOCITY=m +CONFIG_NGBE=m +CONFIG_TXGBE=m +CONFIG_TXGBEVF=m +CONFIG_NGBEVF=m +# CONFIG_NET_VENDOR_WIZNET is not set +CONFIG_XILINX_EMACLITE=m +CONFIG_XILINX_LL_TEMAC=m +CONFIG_QCOM_IPA=m +CONFIG_PHYLIB=y +CONFIG_LED_TRIGGER_PHY=y +CONFIG_RUST_PHYLIB_ABSTRACTIONS=y +CONFIG_AS21XXX_PHY=m +CONFIG_AIR_EN8811H_PHY=m +CONFIG_AMD_PHY=m +CONFIG_MESON_GXL_PHY=m +CONFIG_ADIN_PHY=m +CONFIG_AQUANTIA_PHY=m +CONFIG_AX88796B_RUST_PHY=y +CONFIG_BCM54140_PHY=m +CONFIG_BCM87XX_PHY=m +CONFIG_CICADA_PHY=m +CONFIG_CORTINA_PHY=m +CONFIG_DAVICOM_PHY=m +CONFIG_ICPLUS_PHY=m +CONFIG_LXT_PHY=m +CONFIG_INTEL_XWAY_PHY=m +CONFIG_LSI_ET1011C_PHY=m +CONFIG_MARVELL_PHY=m +CONFIG_MARVELL_88Q2XXX_PHY=m +CONFIG_MARVELL_88X2222_PHY=m +CONFIG_MAXLINEAR_GPHY=m +CONFIG_MAXLINEAR_86110_PHY=m +CONFIG_MICREL_PHY=m +CONFIG_MICROCHIP_T1S_PHY=m +CONFIG_MICROSEMI_PHY=m +CONFIG_NATIONAL_PHY=m +CONFIG_NXP_CBTX_PHY=m +CONFIG_NXP_C45_TJA11XX_PHY=m +CONFIG_NCN26000_PHY=m +CONFIG_AT803X_PHY=m +CONFIG_QCA83XX_PHY=m +CONFIG_QCA808X_PHY=m +CONFIG_QCA807X_PHY=m +CONFIG_QSEMI_PHY=m +CONFIG_REALTEK_PHY_HWMON=y +CONFIG_ROCKCHIP_PHY=m +CONFIG_STE10XP=m +CONFIG_TERANETICS_PHY=m +CONFIG_DP83822_PHY=m +CONFIG_DP83848_PHY=m +CONFIG_DP83867_PHY=m +CONFIG_DP83869_PHY=m +CONFIG_DP83TD510_PHY=m +CONFIG_DP83TG720_PHY=m +CONFIG_VITESSE_PHY=m +CONFIG_XILINX_GMII2RGMII=m +CONFIG_CAN_VCAN=m +CONFIG_CAN_VXCAN=m +CONFIG_CAN_CAN327=m +CONFIG_CAN_FLEXCAN=m +CONFIG_CAN_SLCAN=m +CONFIG_CAN_XILINXCAN=m +CONFIG_CAN_CTUCANFD_PCI=m +CONFIG_CAN_CTUCANFD_PLATFORM=m +CONFIG_CAN_IFI_CANFD=m +CONFIG_CAN_M_CAN=m +CONFIG_CAN_M_CAN_PCI=m +CONFIG_CAN_M_CAN_PLATFORM=m +CONFIG_CAN_PEAK_PCIEFD=m +CONFIG_CAN_RCAR_CANFD=m +CONFIG_CAN_ROCKCHIP_CANFD=m +CONFIG_CAN_HI311X=m +CONFIG_CAN_MCP251X=m +CONFIG_CAN_MCP251XFD=m +CONFIG_CAN_8DEV_USB=m +CONFIG_CAN_EMS_USB=m +CONFIG_CAN_ESD_USB=m +CONFIG_CAN_F81604=m +CONFIG_CAN_GS_USB=m +CONFIG_CAN_KVASER_USB=m +CONFIG_CAN_MCBA_USB=m +CONFIG_CAN_PEAK_USB=m +CONFIG_MCTP_SERIAL=m +CONFIG_MCTP_TRANSPORT_I3C=m +CONFIG_MCTP_TRANSPORT_USB=m +CONFIG_MDIO_GPIO=m +CONFIG_MDIO_HISI_FEMAC=m +CONFIG_MDIO_MVUSB=m +CONFIG_MDIO_OCTEON=m +CONFIG_MDIO_IPQ8064=m +CONFIG_MDIO_BUS_MUX_GPIO=m +CONFIG_MDIO_BUS_MUX_MULTIPLEXER=m +CONFIG_MDIO_BUS_MUX_MMIOREG=m +CONFIG_PPP=m +CONFIG_PPP_BSDCOMP=m +CONFIG_PPP_DEFLATE=m +CONFIG_PPP_FILTER=y +CONFIG_PPP_MPPE=m +CONFIG_PPP_MULTILINK=y +CONFIG_PPPOATM=m +CONFIG_PPPOE=m +CONFIG_PPTP=m +CONFIG_PPPOL2TP=m +CONFIG_PPP_ASYNC=m +CONFIG_PPP_SYNC_TTY=m +CONFIG_SLIP=m +CONFIG_SLIP_COMPRESSED=y +CONFIG_SLIP_SMART=y +CONFIG_USB_CATC=m +CONFIG_USB_KAWETH=m +CONFIG_USB_PEGASUS=m +CONFIG_USB_RTL8150=m +CONFIG_USB_RTL8152=m +CONFIG_USB_LAN78XX=m +CONFIG_USB_USBNET=m +CONFIG_USB_NET_CDC_EEM=m +CONFIG_USB_NET_HUAWEI_CDC_NCM=m +CONFIG_USB_NET_CDC_MBIM=m +CONFIG_USB_NET_DM9601=m +CONFIG_USB_NET_SR9700=m +CONFIG_USB_NET_SMSC75XX=m +CONFIG_USB_NET_SMSC95XX=m +CONFIG_USB_NET_GL620A=m +CONFIG_USB_NET_PLUSB=m +CONFIG_USB_NET_MCS7830=m +CONFIG_USB_NET_RNDIS_HOST=m +CONFIG_USB_ALI_M5632=y +CONFIG_USB_AN2720=y +CONFIG_USB_EPSON2888=y +CONFIG_USB_KC2190=y +CONFIG_USB_NET_CX82310_ETH=m +CONFIG_USB_NET_KALMIA=m +CONFIG_USB_NET_QMI_WWAN=m +CONFIG_USB_HSO=m +CONFIG_USB_NET_INT51X1=m +CONFIG_USB_IPHETH=m +CONFIG_USB_SIERRA_NET=m +CONFIG_USB_VL600=m +CONFIG_USB_NET_CH9200=m +CONFIG_USB_NET_AQC111=m +# CONFIG_WLAN_VENDOR_ADMTEK is not set +CONFIG_APPLE_CENTAURI=m +CONFIG_APPLE_CENTAURI_T6050=m +CONFIG_ATH5K=m +CONFIG_ATH5K_DEBUG=y +CONFIG_ATH9K=m +CONFIG_ATH9K_AHB=y +CONFIG_ATH9K_DEBUGFS=y +CONFIG_ATH9K_PCI_NO_EEPROM=m +CONFIG_ATH9K_HTC=m +CONFIG_CARL9170=m +CONFIG_ATH6KL=m +CONFIG_ATH6KL_SDIO=m +CONFIG_ATH6KL_USB=m +CONFIG_ATH6KL_DEBUG=y +CONFIG_AR5523=m +CONFIG_WIL6210=m +CONFIG_ATH10K=m +CONFIG_ATH10K_PCI=m +CONFIG_ATH10K_AHB=y +CONFIG_ATH10K_SDIO=m +CONFIG_ATH10K_USB=m +CONFIG_ATH10K_SNOC=m +CONFIG_ATH10K_DEBUGFS=y +CONFIG_WCN36XX=m +CONFIG_ATH11K=m +CONFIG_ATH11K_AHB=m +CONFIG_ATH11K_PCI=m +CONFIG_ATH12K=m +CONFIG_ATH12K_AHB=y +# CONFIG_WLAN_VENDOR_ATMEL is not set +CONFIG_B43=m +CONFIG_B43_SDIO=y +CONFIG_B43LEGACY=m +# CONFIG_B43LEGACY_DEBUG is not set +CONFIG_BRCMSMAC=m +CONFIG_BRCMFMAC=m +CONFIG_BRCMFMAC_USB=y +CONFIG_BRCMFMAC_PCIE=y +CONFIG_IWL4965=m +CONFIG_IWL3945=m +CONFIG_IWLEGACY_DEBUG=y +CONFIG_IWLEGACY_DEBUGFS=y +CONFIG_IWLWIFI=m +CONFIG_IWLDVM=m +CONFIG_IWLMVM=m +CONFIG_IWLMLD=m +CONFIG_IWLWIFI_DEBUG=y +CONFIG_IWLWIFI_DEBUGFS=y +# CONFIG_IWLWIFI_DEVICE_TRACING is not set +# CONFIG_WLAN_VENDOR_INTERSIL is not set +CONFIG_LIBERTAS_THINFIRM=m +CONFIG_LIBERTAS_THINFIRM_USB=m +CONFIG_MWIFIEX=m +CONFIG_MWIFIEX_SDIO=m +CONFIG_MWIFIEX_PCIE=m +CONFIG_MWIFIEX_USB=m +CONFIG_MWL8K=m +CONFIG_MT7601U=m +CONFIG_MT76x0U=m +CONFIG_MT76x0E=m +CONFIG_MT76x2E=m +CONFIG_MT76x2U=m +CONFIG_MT7603E=m +CONFIG_MT7615E=m +CONFIG_MT7663U=m +CONFIG_MT7663S=m +CONFIG_MT7915E=m +CONFIG_MT7921E=m +CONFIG_MT7921S=m +CONFIG_MT7921U=m +CONFIG_MT7996E=m +CONFIG_MT7925E=m +CONFIG_MT7925U=m +CONFIG_MT7932_FULLMAC=m +# CONFIG_WLAN_VENDOR_PURELIFI is not set +CONFIG_RT2X00=m +CONFIG_RT2400PCI=m +CONFIG_RT2500PCI=m +CONFIG_RT61PCI=m +CONFIG_RT2800PCI=m +CONFIG_RT2500USB=m +CONFIG_RT73USB=m +CONFIG_RT2800USB=m +CONFIG_RT2800USB_RT3573=y +CONFIG_RT2800USB_RT53XX=y +CONFIG_RT2800USB_RT55XX=y +CONFIG_RT2800USB_UNKNOWN=y +CONFIG_RT2X00_LIB_DEBUGFS=y +CONFIG_RTL8180=m +CONFIG_RTL8187=m +CONFIG_RTL8192CE=m +CONFIG_RTL8192SE=m +CONFIG_RTL8192DE=m +CONFIG_RTL8723AE=m +CONFIG_RTL8723BE=m +CONFIG_RTL8188EE=m +CONFIG_RTL8192EE=m +CONFIG_RTL8821AE=m +CONFIG_RTL8192DU=m +# CONFIG_RTLWIFI_DEBUG is not set +CONFIG_RTL8XXXU=m +CONFIG_RTL8XXXU_UNTESTED=y +CONFIG_RTW88=m +CONFIG_RTW88_8822BE=m +CONFIG_RTW88_8822BS=m +CONFIG_RTW88_8822BU=m +CONFIG_RTW88_8822CE=m +CONFIG_RTW88_8822CS=m +CONFIG_RTW88_8822CU=m +CONFIG_RTW88_8723DE=m +CONFIG_RTW88_8723DS=m +CONFIG_RTW88_8723CS=m +CONFIG_RTW88_8723DU=m +CONFIG_RTW88_8821CE=m +CONFIG_RTW88_8821CS=m +CONFIG_RTW88_8821CU=m +CONFIG_RTW88_8821AU=m +CONFIG_RTW88_8812AU=m +CONFIG_RTW88_8814AE=m +CONFIG_RTW88_8814AU=m +CONFIG_RTW89=m +CONFIG_RTW89_8851BE=m +CONFIG_RTW89_8851BU=m +CONFIG_RTW89_8852AE=m +CONFIG_RTW89_8852AU=m +CONFIG_RTW89_8852BE=m +CONFIG_RTW89_8852BU=m +CONFIG_RTW89_8852BTE=m +CONFIG_RTW89_8852CE=m +CONFIG_RTW89_8852CU=m +CONFIG_RTW89_8922AE=m +CONFIG_RSI_91X=m +# CONFIG_WLAN_VENDOR_SILABS is not set +CONFIG_CW1200=m +CONFIG_CW1200_WLAN_SDIO=m +CONFIG_CW1200_WLAN_SPI=m +CONFIG_WL1251=m +CONFIG_WL1251_SPI=m +CONFIG_WL1251_SDIO=m +CONFIG_WL12XX=m +CONFIG_WL18XX=m +CONFIG_WLCORE_SPI=m +CONFIG_WLCORE_SDIO=m +CONFIG_ZD1211RW=m +CONFIG_QTNFMAC_PCIE=m +CONFIG_MAC80211_HWSIM=m +CONFIG_VIRT_WIFI=m +CONFIG_IEEE802154_FAKELB=m +CONFIG_IEEE802154_AT86RF230=m +CONFIG_IEEE802154_MRF24J40=m +CONFIG_IEEE802154_CC2520=m +CONFIG_IEEE802154_ATUSB=m +CONFIG_IEEE802154_ADF7242=m +CONFIG_IEEE802154_CA8210=m +CONFIG_IEEE802154_MCR20A=m +CONFIG_WWAN=m +CONFIG_WWAN_HWSIM=m +CONFIG_MHI_WWAN_CTRL=m +CONFIG_MHI_WWAN_MBIM=m +CONFIG_QCOM_BAM_DMUX=m +CONFIG_RPMSG_WWAN_CTRL=m +CONFIG_IOSM=m +CONFIG_MTK_T7XX=m +CONFIG_VMXNET3=m +CONFIG_USB4_NET=m +CONFIG_HYPERV_NET=m +CONFIG_NETDEVSIM=m +CONFIG_INPUT_MOUSEDEV=y +CONFIG_INPUT_JOYDEV=m +CONFIG_INPUT_EVDEV=y +CONFIG_KEYBOARD_ADC=m +CONFIG_KEYBOARD_ADP5585=m +CONFIG_KEYBOARD_QT1050=m +CONFIG_KEYBOARD_QT1070=m +CONFIG_KEYBOARD_GPIO=m +CONFIG_KEYBOARD_GPIO_POLLED=m +CONFIG_KEYBOARD_SNVS_PWRKEY=m +CONFIG_KEYBOARD_IMX_SC_KEY=m +CONFIG_KEYBOARD_TEGRA=m +CONFIG_KEYBOARD_PINEPHONE=m +CONFIG_KEYBOARD_STMPE=m +CONFIG_KEYBOARD_TM2_TOUCHKEY=m +CONFIG_KEYBOARD_CROS_EC=m +CONFIG_KEYBOARD_CYPRESS_SF=m +# CONFIG_MOUSE_PS2 is not set +CONFIG_MOUSE_APPLETOUCH=m +CONFIG_MOUSE_BCM5974=m +CONFIG_MOUSE_CYAPA=m +CONFIG_MOUSE_ELAN_I2C=m +CONFIG_MOUSE_ELAN_I2C_SMBUS=y +CONFIG_MOUSE_VSXXXAA=m +CONFIG_MOUSE_SYNAPTICS_I2C=m +CONFIG_MOUSE_SYNAPTICS_USB=m +CONFIG_INPUT_JOYSTICK=y +CONFIG_JOYSTICK_ANALOG=m +CONFIG_JOYSTICK_A3D=m +CONFIG_JOYSTICK_ADC=m +CONFIG_JOYSTICK_ADI=m +CONFIG_JOYSTICK_COBRA=m +CONFIG_JOYSTICK_GF2K=m +CONFIG_JOYSTICK_GRIP=m +CONFIG_JOYSTICK_GRIP_MP=m +CONFIG_JOYSTICK_GUILLEMOT=m +CONFIG_JOYSTICK_INTERACT=m +CONFIG_JOYSTICK_SIDEWINDER=m +CONFIG_JOYSTICK_TMDC=m +CONFIG_JOYSTICK_IFORCE=m +CONFIG_JOYSTICK_IFORCE_USB=m +CONFIG_JOYSTICK_IFORCE_232=m +CONFIG_JOYSTICK_JOYDUMP=m +CONFIG_JOYSTICK_XPAD=m +CONFIG_JOYSTICK_XPAD_FF=y +CONFIG_JOYSTICK_XPAD_LEDS=y +CONFIG_JOYSTICK_PSXPAD_SPI=m +CONFIG_JOYSTICK_PSXPAD_SPI_FF=y +CONFIG_JOYSTICK_PXRC=m +CONFIG_JOYSTICK_QWIIC=m +CONFIG_JOYSTICK_SENSEHAT=m +CONFIG_INPUT_TABLET=y +CONFIG_TABLET_USB_ACECAD=m +CONFIG_TABLET_USB_AIPTEK=m +CONFIG_TABLET_USB_HANWANG=m +CONFIG_TABLET_USB_KBTAB=m +CONFIG_TABLET_USB_PEGASUS=m +CONFIG_TABLET_SERIAL_WACOM4=m +CONFIG_INPUT_TOUCHSCREEN=y +CONFIG_TOUCHSCREEN_ADS7846=m +CONFIG_TOUCHSCREEN_ADC=m +CONFIG_TOUCHSCREEN_APPLE_Z2=m +CONFIG_TOUCHSCREEN_ATMEL_MXT=m +CONFIG_TOUCHSCREEN_AUO_PIXCIR=m +CONFIG_TOUCHSCREEN_CY8CTMA140=m +CONFIG_TOUCHSCREEN_CYTTSP5=m +CONFIG_TOUCHSCREEN_EETI=m +CONFIG_TOUCHSCREEN_EGALAX=m +CONFIG_TOUCHSCREEN_EXC3000=m +CONFIG_TOUCHSCREEN_GOODIX=m +CONFIG_TOUCHSCREEN_HIMAX_HX852X=m +CONFIG_TOUCHSCREEN_HYCON_HY46XX=m +CONFIG_TOUCHSCREEN_HYNITRON_CSTXXX=m +CONFIG_TOUCHSCREEN_HYNITRON_CST816X=m +CONFIG_TOUCHSCREEN_ILI210X=m +CONFIG_TOUCHSCREEN_ILITEK=m +CONFIG_TOUCHSCREEN_ELAN=m +CONFIG_TOUCHSCREEN_WACOM_I2C=m +CONFIG_TOUCHSCREEN_MMS114=m +CONFIG_TOUCHSCREEN_MSG2638=m +CONFIG_TOUCHSCREEN_NOVATEK_NVT_TS=m +CONFIG_TOUCHSCREEN_IMAGIS=m +CONFIG_TOUCHSCREEN_EDT_FT5X06=m +CONFIG_TOUCHSCREEN_RASPBERRYPI_FW=m +CONFIG_TOUCHSCREEN_TI_AM335X_TSC=m +CONFIG_TOUCHSCREEN_PIXCIR=m +CONFIG_TOUCHSCREEN_USB_COMPOSITE=m +CONFIG_TOUCHSCREEN_TSC2007=m +CONFIG_TOUCHSCREEN_TSC2007_IIO=y +CONFIG_TOUCHSCREEN_RM_TS=m +CONFIG_TOUCHSCREEN_SILEAD=m +CONFIG_TOUCHSCREEN_SIS_I2C=m +CONFIG_TOUCHSCREEN_ST1232=m +CONFIG_TOUCHSCREEN_STMPE=m +CONFIG_TOUCHSCREEN_ZET6223=m +CONFIG_TOUCHSCREEN_ZFORCE=m +CONFIG_TOUCHSCREEN_COLIBRI_VF50=m +CONFIG_TOUCHSCREEN_IQS5XX=m +CONFIG_TOUCHSCREEN_IQS7211=m +CONFIG_TOUCHSCREEN_ZINITIX=m +CONFIG_TOUCHSCREEN_HIMAX_HX83112B=m +CONFIG_INPUT_MISC=y +CONFIG_INPUT_BBNSM_PWRKEY=m +CONFIG_INPUT_CS40L50_VIBRA=m +CONFIG_INPUT_E3X0_BUTTON=m +CONFIG_INPUT_PM8941_PWRKEY=m +CONFIG_INPUT_PM8XXX_VIBRATOR=m +CONFIG_INPUT_MAX77650_ONKEY=m +CONFIG_INPUT_MAX77693_HAPTIC=m +CONFIG_INPUT_GPIO_BEEPER=m +CONFIG_INPUT_GPIO_VIBRA=m +CONFIG_INPUT_KXTJ9=m +CONFIG_INPUT_TPS65219_PWRBUTTON=m +CONFIG_INPUT_TPS6594_PWRBUTTON=m +CONFIG_INPUT_AXP20X_PEK=m +CONFIG_INPUT_UINPUT=m +CONFIG_INPUT_PWM_BEEPER=m +CONFIG_INPUT_RK805_PWRKEY=m +CONFIG_INPUT_IQS269A=m +CONFIG_INPUT_IQS626A=m +CONFIG_INPUT_IQS7222=m +CONFIG_INPUT_CMA3000=m +CONFIG_INPUT_CMA3000_I2C=m +CONFIG_INPUT_HISI_POWERKEY=y +CONFIG_INPUT_QNAP_MCU=m +CONFIG_INPUT_RT5120_PWRKEY=m +CONFIG_INPUT_MACSMC_INPUT=m +CONFIG_RMI4_I2C=m +CONFIG_RMI4_SPI=m +CONFIG_RMI4_SMB=m +CONFIG_RMI4_F1A=y +CONFIG_RMI4_F21=y +CONFIG_RMI4_F34=y +CONFIG_RMI4_F55=y +CONFIG_SERIO_SERPORT=m +CONFIG_SERIO_AMBAKMI=m +CONFIG_SERIO_RAW=m +CONFIG_SERIO_ALTERA_PS2=m +CONFIG_SERIO_ARC_PS2=m +CONFIG_GAMEPORT_EMU10K1=m +CONFIG_GAMEPORT_FM801=m +# CONFIG_LEGACY_PTYS is not set +# CONFIG_LEGACY_TIOCSTI is not set +CONFIG_SERIAL_8250=y +# CONFIG_SERIAL_8250_16550A_VARIANTS is not set +CONFIG_SERIAL_8250_CONSOLE=y +CONFIG_SERIAL_8250_EXAR=m +CONFIG_SERIAL_8250_NR_UARTS=32 +CONFIG_SERIAL_8250_RUNTIME_UARTS=32 +CONFIG_SERIAL_8250_EXTENDED=y +CONFIG_SERIAL_8250_SHARE_IRQ=y +CONFIG_SERIAL_8250_RSA=y +CONFIG_SERIAL_8250_MANY_PORTS=y +CONFIG_SERIAL_8250_PCI1XXXX=y +CONFIG_SERIAL_8250_BCM2835AUX=y +CONFIG_SERIAL_8250_DFL=m +CONFIG_SERIAL_8250_DW=y +CONFIG_SERIAL_8250_EM=y +CONFIG_SERIAL_8250_RT288X=y +CONFIG_SERIAL_8250_OMAP=y +CONFIG_SERIAL_OF_PLATFORM=y +CONFIG_SERIAL_AMBA_PL011=y +CONFIG_SERIAL_AMBA_PL011_CONSOLE=y +CONFIG_SERIAL_EARLYCON_SEMIHOST=y +CONFIG_SERIAL_APPLE_DOCKCHANNEL_EARLYCON=y +CONFIG_SERIAL_APPLE_DOCKCHANNEL=y +CONFIG_SERIAL_MESON=y +CONFIG_SERIAL_MESON_CONSOLE=y +CONFIG_SERIAL_SAMSUNG=y +CONFIG_SERIAL_SAMSUNG_CONSOLE=y +CONFIG_SERIAL_TEGRA=y +CONFIG_SERIAL_TEGRA_TCU=y +CONFIG_SERIAL_TEGRA_UTC=y +CONFIG_SERIAL_IMX=y +CONFIG_SERIAL_IMX_CONSOLE=y +# CONFIG_SERIAL_IMX_EARLYCON is not set +CONFIG_SERIAL_SH_SCI=y +CONFIG_SERIAL_RSCI=y +CONFIG_SERIAL_JSM=m +CONFIG_SERIAL_MSM=y +CONFIG_SERIAL_MSM_CONSOLE=y +CONFIG_SERIAL_QCOM_GENI=y +CONFIG_SERIAL_QCOM_GENI_CONSOLE=y +CONFIG_SERIAL_SC16IS7XX=m +CONFIG_SERIAL_XILINX_PS_UART=y +CONFIG_SERIAL_XILINX_PS_UART_CONSOLE=y +CONFIG_SERIAL_ARC=m +CONFIG_SERIAL_FSL_LPUART=y +CONFIG_SERIAL_FSL_LPUART_CONSOLE=y +CONFIG_SERIAL_FSL_LINFLEXUART=y +CONFIG_SERIAL_FSL_LINFLEXUART_CONSOLE=y +CONFIG_SERIAL_MVEBU_UART=y +CONFIG_NOZOMI=m +CONFIG_NULL_TTY=m +CONFIG_RPMSG_TTY=m +CONFIG_SERIAL_DEV_BUS=y +CONFIG_VIRTIO_CONSOLE=y +CONFIG_IPMI_HANDLER=m +CONFIG_IPMI_DEVICE_INTERFACE=m +CONFIG_IPMI_SSIF=m +CONFIG_IPMI_IPMB=m +CONFIG_IPMI_WATCHDOG=m +CONFIG_IPMI_POWEROFF=m +CONFIG_SSIF_IPMI_BMC=m +CONFIG_IPMB_DEVICE_INTERFACE=m +CONFIG_HW_RANDOM=y +CONFIG_HW_RANDOM_TIMERIOMEM=m +CONFIG_HW_RANDOM_BCM2835=m +CONFIG_HW_RANDOM_IPROC_RNG200=m +CONFIG_HW_RANDOM_OMAP=m +CONFIG_HW_RANDOM_VIRTIO=y +CONFIG_HW_RANDOM_HISI=m +CONFIG_HW_RANDOM_XGENE=m +CONFIG_HW_RANDOM_MESON=m +CONFIG_HW_RANDOM_CAVIUM=m +CONFIG_HW_RANDOM_XIPHERA=m +CONFIG_HW_RANDOM_CN10K=m +CONFIG_HW_RANDOM_ROCKCHIP=m +CONFIG_TCG_TPM2_HMAC=y +CONFIG_TCG_TIS=y +CONFIG_TCG_TIS_SPI=m +CONFIG_TCG_TIS_SPI_CR50=y +CONFIG_TCG_TIS_I2C=m +CONFIG_TCG_TIS_SYNQUACER=m +CONFIG_TCG_TIS_I2C_CR50=m +CONFIG_TCG_TIS_I2C_ATMEL=m +CONFIG_TCG_TIS_I2C_INFINEON=m +CONFIG_TCG_TIS_I2C_NUVOTON=m +CONFIG_TCG_VTPM_PROXY=m +CONFIG_TCG_FTPM_TEE=m +CONFIG_XILLYBUS=m +CONFIG_XILLYBUS_PCIE=m +CONFIG_XILLYBUS_OF=m +CONFIG_XILLYUSB=m +CONFIG_I2C_CHARDEV=m +CONFIG_I2C_ARB_GPIO_CHALLENGE=m +CONFIG_I2C_MUX_GPIO=m +CONFIG_I2C_MUX_GPMUX=m +CONFIG_I2C_MUX_LTC4306=m +CONFIG_I2C_MUX_PCA9541=m +CONFIG_I2C_MUX_PCA954x=m +CONFIG_I2C_MUX_PINCTRL=m +CONFIG_I2C_MUX_REG=m +CONFIG_I2C_MUX_MLXCPLD=m +CONFIG_I2C_MUX_MULE=m +CONFIG_I2C_AMD_MP2=m +CONFIG_I2C_NFORCE2=m +CONFIG_I2C_NVIDIA_GPU=m +CONFIG_I2C_ZHAOXIN=m +CONFIG_I2C_SCMI=m +CONFIG_I2C_BCM2835=m +CONFIG_I2C_BRCMSTB=m +CONFIG_I2C_CADENCE=m +CONFIG_I2C_DESIGNWARE_CORE=y +CONFIG_I2C_DESIGNWARE_PCI=m +CONFIG_I2C_GPIO=m +CONFIG_I2C_IMX=m +CONFIG_I2C_IMX_LPI2C=m +CONFIG_I2C_MLXBF=m +CONFIG_I2C_MESON=m +CONFIG_I2C_MV64XXX=m +CONFIG_I2C_OMAP=m +CONFIG_I2C_APPLE=m +CONFIG_I2C_DP855=m +CONFIG_I2C_PCA_PLATFORM=m +CONFIG_I2C_PXA=m +CONFIG_I2C_QCOM_CCI=m +CONFIG_I2C_QCOM_GENI=y +CONFIG_I2C_QUP=m +CONFIG_I2C_RIIC=m +CONFIG_I2C_RK3X=y +CONFIG_I2C_SIMTEC=m +CONFIG_I2C_SYNQUACER=m +CONFIG_I2C_TEGRA=m +CONFIG_I2C_TEGRA_BPMP=m +CONFIG_I2C_VERSATILE=m +CONFIG_I2C_THUNDERX=m +CONFIG_I2C_XILINX=m +CONFIG_I2C_XLP9XX=m +CONFIG_I2C_DIOLAN_U2C=m +CONFIG_I2C_DLN2=m +CONFIG_I2C_CP2615=m +CONFIG_I2C_PCI1XXXX=m +CONFIG_I2C_TINY_USB=m +CONFIG_I2C_MLXCPLD=m +CONFIG_I2C_CROS_EC_TUNNEL=m +CONFIG_I2C_XGENE_SLIMPRO=m +CONFIG_I2C_VIRTIO=m +CONFIG_I2C_STUB=m +CONFIG_I2C_SLAVE_EEPROM=m +CONFIG_I3C=m +CONFIG_ADI_I3C_MASTER=m +CONFIG_CDNS_I3C_MASTER=m +CONFIG_DW_I3C_MASTER=m +CONFIG_SVC_I3C_MASTER=m +CONFIG_MIPI_I3C_HCI=m +CONFIG_MIPI_I3C_HCI_PCI=m +CONFIG_RENESAS_I3C=m +CONFIG_SPI=y +CONFIG_SPI_ALTERA_DFL=m +CONFIG_SPI_AMLOGIC_SPIFC_A1=m +CONFIG_SPI_AMLOGIC_SPIFC_A4=m +CONFIG_SPI_AMLOGIC_SPISG=m +CONFIG_SPI_APPLE=m +CONFIG_SPI_APPLE_QSPI=m +CONFIG_SPI_ARMADA_3700=m +CONFIG_SPI_BCM2835=m +CONFIG_SPI_BCM2835AUX=m +CONFIG_SPI_CADENCE=m +CONFIG_SPI_CADENCE_QUADSPI=m +CONFIG_SPI_CADENCE_XSPI=m +CONFIG_SPI_CH341=m +CONFIG_SPI_DESIGNWARE=m +CONFIG_SPI_DW_DMA=y +CONFIG_SPI_DW_PCI=m +CONFIG_SPI_DW_MMIO=m +CONFIG_SPI_DLN2=m +CONFIG_SPI_FSL_LPSPI=m +CONFIG_SPI_FSL_QUADSPI=m +CONFIG_SPI_NXP_FLEXSPI=m +CONFIG_SPI_NXP_XSPI=m +CONFIG_SPI_GPIO=m +CONFIG_SPI_IMX=m +CONFIG_SPI_FSL_DSPI=m +CONFIG_SPI_MESON_SPICC=m +CONFIG_SPI_MESON_SPIFC=m +CONFIG_SPI_MICROCHIP_CORE_QSPI=m +CONFIG_SPI_OMAP24XX=m +CONFIG_SPI_ORION=m +CONFIG_SPI_PCI1XXXX=m +CONFIG_SPI_PL022=m +CONFIG_SPI_ROCKCHIP=m +CONFIG_SPI_ROCKCHIP_SFC=m +CONFIG_SPI_RSPI=m +CONFIG_SPI_RZV2H_RSPI=m +CONFIG_SPI_QCOM_QSPI=m +CONFIG_SPI_QPIC_SNAND=m +CONFIG_SPI_QUP=m +CONFIG_SPI_QCOM_GENI=m +CONFIG_SPI_SN_F_OSPI=m +CONFIG_SPI_SUN6I=m +CONFIG_SPI_SYNQUACER=m +CONFIG_SPI_TEGRA210_QUAD=y +CONFIG_SPI_TEGRA114=m +CONFIG_SPI_THUNDERX=m +CONFIG_SPI_VIRTIO=m +CONFIG_SPI_XILINX=m +CONFIG_SPI_XLP=m +CONFIG_SPI_ZYNQMP_GQSPI=m +CONFIG_SPI_AMD=y +CONFIG_SPI_MUX=m +CONFIG_SPI_SPIDEV=m +CONFIG_SPMI=y +CONFIG_SPMI_APPLE=y +CONFIG_SPMI_HISI3670=m +CONFIG_PPS_CLIENT_LDISC=m +CONFIG_PPS_CLIENT_GPIO=m +CONFIG_PPS_GENERATOR=m +CONFIG_DP83640_PHY=m +CONFIG_PTP_1588_CLOCK_KVM=m +CONFIG_PTP_1588_CLOCK_IDT82P33=m +CONFIG_PTP_1588_CLOCK_IDTCM=m +CONFIG_PTP_1588_CLOCK_FC3W=m +CONFIG_PTP_1588_CLOCK_MOCK=m +CONFIG_PTP_DFL_TOD=m +CONFIG_PTP_NETC_V4_TIMER=m +CONFIG_ZL3073X_I2C=m +CONFIG_ZL3073X_SPI=m +CONFIG_PINCTRL_AMD=y +CONFIG_PINCTRL_AMDISP=m +CONFIG_PINCTRL_APPLE_GPIO=m +CONFIG_PINCTRL_AS3722=y +CONFIG_PINCTRL_AXP209=m +CONFIG_PINCTRL_CY8C95X0=m +CONFIG_PINCTRL_MAX77620=y +CONFIG_PINCTRL_RK805=m +CONFIG_PINCTRL_SCMI=y +CONFIG_PINCTRL_SINGLE=y +CONFIG_PINCTRL_MLXBF3=m +CONFIG_PINCTRL_BRCMSTB=y +CONFIG_PINCTRL_BCM2712=y +CONFIG_PINCTRL_CS42L43=m +CONFIG_PINCTRL_SKY1=y +CONFIG_PINCTRL_IMX_SCMI=y +CONFIG_PINCTRL_IMX91=y +CONFIG_PINCTRL_IMX93=y +CONFIG_PINCTRL_S32G2=y +# CONFIG_PINCTRL_IPQ5018 is not set +# CONFIG_PINCTRL_IPQ5332 is not set +# CONFIG_PINCTRL_IPQ5424 is not set +# CONFIG_PINCTRL_IPQ8074 is not set +# CONFIG_PINCTRL_IPQ6018 is not set +# CONFIG_PINCTRL_IPQ9574 is not set +# CONFIG_PINCTRL_KAANAPALI is not set +# CONFIG_PINCTRL_MSM8953 is not set +# CONFIG_PINCTRL_MSM8976 is not set +# CONFIG_PINCTRL_MSM8994 is not set +CONFIG_PINCTRL_MSM8996=m +CONFIG_PINCTRL_MSM8998=m +CONFIG_PINCTRL_QCM2290=m +# CONFIG_PINCTRL_QCS404 is not set +# CONFIG_PINCTRL_QCS615 is not set +CONFIG_PINCTRL_QDF2XXX=m +# CONFIG_PINCTRL_QDU1000 is not set +# CONFIG_PINCTRL_SDM660 is not set +# CONFIG_PINCTRL_SDM670 is not set +CONFIG_PINCTRL_SDM845=m +# CONFIG_PINCTRL_SDX75 is not set +# CONFIG_PINCTRL_SM4450 is not set +CONFIG_PINCTRL_SM6115=m +# CONFIG_PINCTRL_SM6125 is not set +# CONFIG_PINCTRL_SM6350 is not set +# CONFIG_PINCTRL_SM6375 is not set +# CONFIG_PINCTRL_SM7150 is not set +CONFIG_PINCTRL_MILOS=m +# CONFIG_PINCTRL_SM8150 is not set +# CONFIG_PINCTRL_SM8250 is not set +# CONFIG_PINCTRL_SM8350 is not set +CONFIG_PINCTRL_SM8450=m +# CONFIG_PINCTRL_SM8550 is not set +# CONFIG_PINCTRL_SM8650 is not set +# CONFIG_PINCTRL_SM8750 is not set +CONFIG_PINCTRL_QCOM_SPMI_PMIC=y +CONFIG_PINCTRL_LPASS_LPI=m +CONFIG_PINCTRL_SC7280_LPASS_LPI=m +CONFIG_PINCTRL_SM4250_LPASS_LPI=m +CONFIG_PINCTRL_SM6115_LPASS_LPI=m +CONFIG_PINCTRL_SM8250_LPASS_LPI=m +CONFIG_PINCTRL_SM8450_LPASS_LPI=m +CONFIG_PINCTRL_SC8280XP_LPASS_LPI=m +CONFIG_PINCTRL_SM8550_LPASS_LPI=m +CONFIG_PINCTRL_SUN8I_H3=y +CONFIG_PINCTRL_SUN20I_D1=y +CONFIG_GPIO_CDEV_V1=y +CONFIG_GPIO_RASPBERRYPI_EXP=m +CONFIG_GPIO_BRCMSTB=m +CONFIG_GPIO_CADENCE=m +CONFIG_GPIO_DAVINCI=m +CONFIG_GPIO_DWAPB=m +CONFIG_GPIO_EXAR=m +CONFIG_GPIO_MB86S7X=m +CONFIG_GPIO_MPC8XXX=y +CONFIG_GPIO_MXC=m +CONFIG_GPIO_PL061=y +CONFIG_GPIO_RCAR=m +CONFIG_GPIO_SYSCON=m +CONFIG_GPIO_THUNDERX=m +CONFIG_GPIO_VF610=y +CONFIG_GPIO_WCD934X=m +CONFIG_GPIO_XGENE=y +CONFIG_GPIO_XGENE_SB=m +CONFIG_GPIO_XILINX=m +CONFIG_GPIO_XLP=m +CONFIG_GPIO_ZYNQ=m +CONFIG_GPIO_FXL6408=m +CONFIG_GPIO_DS4520=m +CONFIG_GPIO_MAX732X=m +CONFIG_GPIO_PCA953X=y +CONFIG_GPIO_PCA953X_IRQ=y +CONFIG_GPIO_PCA9570=m +CONFIG_GPIO_PCF857X=m +CONFIG_GPIO_TPIC2810=m +CONFIG_GPIO_ADP5585=m +CONFIG_GPIO_BD9571MWV=m +CONFIG_GPIO_CROS_EC=m +CONFIG_GPIO_DLN2=m +CONFIG_GPIO_MACSMC=m +CONFIG_GPIO_MAX77620=y +CONFIG_GPIO_MAX77650=m +CONFIG_GPIO_QIXIS_FPGA=m +CONFIG_GPIO_STMPE=y +CONFIG_GPIO_TPS65086=m +CONFIG_GPIO_WM8994=m +CONFIG_GPIO_MLXBF=m +CONFIG_GPIO_MLXBF2=m +CONFIG_GPIO_MLXBF3=m +CONFIG_GPIO_PCI_IDIO_16=m +CONFIG_GPIO_MOXTET=m +CONFIG_GPIO_MPSSE=m +CONFIG_GPIO_AGGREGATOR=m +CONFIG_GPIO_LINE_MUX=m +CONFIG_GPIO_VIRTIO=m +CONFIG_GPIO_SIM=m +CONFIG_GPIO_VIRTUSER=m +CONFIG_W1=m +CONFIG_W1_MASTER_DS2490=m +CONFIG_W1_MASTER_DS2482=m +CONFIG_W1_MASTER_GPIO=m +CONFIG_W1_MASTER_UART=m +CONFIG_W1_SLAVE_THERM=m +CONFIG_W1_SLAVE_SMEM=m +CONFIG_W1_SLAVE_DS2405=m +CONFIG_W1_SLAVE_DS2408=m +# CONFIG_W1_SLAVE_DS2408_READBACK is not set +CONFIG_W1_SLAVE_DS2413=m +CONFIG_W1_SLAVE_DS2406=m +CONFIG_W1_SLAVE_DS2423=m +CONFIG_W1_SLAVE_DS2805=m +CONFIG_W1_SLAVE_DS2430=m +CONFIG_W1_SLAVE_DS2431=m +CONFIG_W1_SLAVE_DS2433=m +CONFIG_W1_SLAVE_DS2433_CRC=y +CONFIG_W1_SLAVE_DS2438=m +CONFIG_W1_SLAVE_DS2780=m +CONFIG_W1_SLAVE_DS2781=m +CONFIG_W1_SLAVE_DS28E04=m +CONFIG_POWER_RESET_AS3722=y +CONFIG_POWER_RESET_GPIO=y +CONFIG_POWER_RESET_GPIO_RESTART=y +CONFIG_POWER_RESET_HISI=y +CONFIG_POWER_RESET_MACSMC=m +CONFIG_POWER_RESET_MSM=y +CONFIG_POWER_RESET_QCOM_PON=m +CONFIG_POWER_RESET_ODROID_GO_ULTRA_POWEROFF=y +CONFIG_POWER_RESET_REGULATOR=y +CONFIG_POWER_RESET_RESTART=y +CONFIG_POWER_RESET_TORADEX_EC=m +CONFIG_POWER_RESET_TPS65086=y +CONFIG_POWER_RESET_VEXPRESS=y +CONFIG_POWER_RESET_XGENE=y +CONFIG_POWER_RESET_SYSCON=y +CONFIG_POWER_RESET_SYSCON_POWEROFF=y +CONFIG_SYSCON_REBOOT_MODE=y +CONFIG_NVMEM_REBOOT_MODE=m +CONFIG_POWER_MLXBF=m +CONFIG_POWER_SEQUENCING_PCIE_M2=m +CONFIG_IP5XXX_POWER=m +CONFIG_BATTERY_CW2015=m +CONFIG_BATTERY_LENOVO_YOGA_C630=m +CONFIG_BATTERY_QCOM_BATTMGR=m +CONFIG_BATTERY_SAMSUNG_SDI=y +CONFIG_BATTERY_SBS=m +CONFIG_BATTERY_BQ27XXX=m +# CONFIG_BATTERY_BQ27XXX_HDQ is not set +CONFIG_CHARGER_AXP20X=m +CONFIG_BATTERY_AXP20X=m +CONFIG_AXP20X_POWER=m +CONFIG_BATTERY_MAX17040=m +CONFIG_BATTERY_MAX17042=m +CONFIG_BATTERY_MAX1720X=m +CONFIG_CHARGER_GPIO=m +CONFIG_CHARGER_LT3651=m +CONFIG_CHARGER_LTC4162L=m +CONFIG_CHARGER_MAX77650=m +CONFIG_CHARGER_MAX77705=m +CONFIG_CHARGER_MAX77976=m +CONFIG_CHARGER_MAX8971=m +CONFIG_CHARGER_QCOM_SMBB=m +CONFIG_CHARGER_BQ24735=m +CONFIG_CHARGER_BQ2515X=m +CONFIG_CHARGER_BQ25980=m +CONFIG_CHARGER_BQ256XX=m +CONFIG_CHARGER_RK817=m +CONFIG_CHARGER_SMB347=m +CONFIG_BATTERY_GAUGE_LTC2941=m +CONFIG_BATTERY_RT5033=m +CONFIG_CHARGER_RT5033=m +CONFIG_CHARGER_RT9467=m +CONFIG_CHARGER_RT9471=m +CONFIG_CHARGER_RT9756=m +CONFIG_CHARGER_CROS_USBPD=m +CONFIG_FUEL_GAUGE_STC3117=m +CONFIG_CHARGER_UCS1002=m +CONFIG_CHARGER_BD99954=m +CONFIG_BATTERY_SURFACE=m +CONFIG_CHARGER_SURFACE=m +CONFIG_BATTERY_UG3105=m +CONFIG_CHARGER_QCOM_SMB2=m +CONFIG_FUEL_GAUGE_MM8013=m +CONFIG_MACSMC_POWER=m +CONFIG_SENSORS_SMPRO=m +CONFIG_SENSORS_AD7314=m +CONFIG_SENSORS_AD7414=m +CONFIG_SENSORS_AD7418=m +CONFIG_SENSORS_ADM1025=m +CONFIG_SENSORS_ADM1026=m +CONFIG_SENSORS_ADM1029=m +CONFIG_SENSORS_ADM1031=m +CONFIG_SENSORS_ADM9240=m +CONFIG_SENSORS_ADT7310=m +CONFIG_SENSORS_ADT7410=m +CONFIG_SENSORS_ADT7411=m +CONFIG_SENSORS_ADT7462=m +CONFIG_SENSORS_ADT7470=m +CONFIG_SENSORS_ADT7475=m +CONFIG_SENSORS_AQUACOMPUTER_D5NEXT=m +CONFIG_SENSORS_ASC7621=m +CONFIG_SENSORS_ASUS_ROG_RYUJIN=m +CONFIG_SENSORS_AXI_FAN_CONTROL=m +CONFIG_SENSORS_APPLE_AON_PTD=m +CONFIG_SENSORS_APPLE_PMP_J613=m +CONFIG_SENSORS_ARM_SCMI=m +CONFIG_SENSORS_ARM_SCPI=m +CONFIG_SENSORS_ATXP1=m +CONFIG_SENSORS_CHIPCAP2=m +CONFIG_SENSORS_CORSAIR_CPRO=m +CONFIG_SENSORS_CORSAIR_PSU=m +CONFIG_SENSORS_DRIVETEMP=m +CONFIG_SENSORS_DS620=m +CONFIG_SENSORS_DS1621=m +CONFIG_SENSORS_F71805F=m +CONFIG_SENSORS_F71882FG=m +CONFIG_SENSORS_F75375S=m +CONFIG_SENSORS_MC33XS2410=m +CONFIG_SENSORS_FTSTEUTATES=m +CONFIG_SENSORS_GIGABYTE_WATERFORCE=m +CONFIG_SENSORS_GL518SM=m +CONFIG_SENSORS_GL520SM=m +CONFIG_SENSORS_G760A=m +CONFIG_SENSORS_G762=m +CONFIG_SENSORS_GPIO_FAN=m +CONFIG_SENSORS_HS3001=m +CONFIG_SENSORS_HTU31=m +CONFIG_SENSORS_IBMAEM=m +CONFIG_SENSORS_IBMPEX=m +CONFIG_SENSORS_IIO_HWMON=m +CONFIG_SENSORS_ISL28022=m +CONFIG_SENSORS_IT87=m +CONFIG_SENSORS_JC42=m +CONFIG_SENSORS_POWERZ=m +CONFIG_SENSORS_POWR1220=m +CONFIG_SENSORS_LINEAGE=m +CONFIG_SENSORS_LTC2945=m +CONFIG_SENSORS_LTC2947_I2C=m +CONFIG_SENSORS_LTC2947_SPI=m +CONFIG_SENSORS_LTC2990=m +CONFIG_SENSORS_LTC2991=m +CONFIG_SENSORS_LTC4151=m +CONFIG_SENSORS_LTC4215=m +CONFIG_SENSORS_LTC4222=m +CONFIG_SENSORS_LTC4245=m +CONFIG_SENSORS_LTC4260=m +CONFIG_SENSORS_LTC4261=m +CONFIG_SENSORS_MACSMC_HWMON=m +CONFIG_SENSORS_MAX1111=m +CONFIG_SENSORS_MAX16065=m +CONFIG_SENSORS_MAX1619=m +CONFIG_SENSORS_MAX1668=m +CONFIG_SENSORS_MAX197=m +CONFIG_SENSORS_MAX31722=m +CONFIG_SENSORS_MAX31760=m +CONFIG_MAX31827=m +CONFIG_SENSORS_MAX6620=m +CONFIG_SENSORS_MAX6639=m +CONFIG_SENSORS_MAX6650=m +CONFIG_SENSORS_MAX6697=m +CONFIG_SENSORS_MAX31790=m +CONFIG_SENSORS_MAX77705=m +CONFIG_SENSORS_MC34VR500=m +CONFIG_SENSORS_MCP3021=m +CONFIG_SENSORS_MLXREG_FAN=m +CONFIG_SENSORS_TC654=m +CONFIG_SENSORS_MR75203=m +CONFIG_SENSORS_ADCXX=m +CONFIG_SENSORS_LM63=m +CONFIG_SENSORS_LM70=m +CONFIG_SENSORS_LM73=m +CONFIG_SENSORS_LM75=m +CONFIG_SENSORS_LM77=m +CONFIG_SENSORS_LM78=m +CONFIG_SENSORS_LM80=m +CONFIG_SENSORS_LM83=m +CONFIG_SENSORS_LM85=m +CONFIG_SENSORS_LM87=m +CONFIG_SENSORS_LM90=m +CONFIG_SENSORS_LM92=m +CONFIG_SENSORS_LM93=m +CONFIG_SENSORS_LM95234=m +CONFIG_SENSORS_LM95241=m +CONFIG_SENSORS_LM95245=m +CONFIG_SENSORS_PC87360=m +CONFIG_SENSORS_PC87427=m +CONFIG_SENSORS_NTC_THERMISTOR=m +CONFIG_SENSORS_NCT6683=m +CONFIG_SENSORS_NCT6775=m +CONFIG_SENSORS_NCT6775_I2C=m +CONFIG_SENSORS_NCT7363=m +CONFIG_SENSORS_NCT7802=m +CONFIG_SENSORS_NCT7904=m +CONFIG_SENSORS_NPCM7XX=m +CONFIG_SENSORS_NZXT_KRAKEN2=m +CONFIG_SENSORS_NZXT_KRAKEN3=m +CONFIG_SENSORS_NZXT_SMART2=m +CONFIG_SENSORS_PCF8591=m +CONFIG_PMBUS=m +CONFIG_SENSORS_ADM1266=m +CONFIG_SENSORS_ADM1275=m +CONFIG_SENSORS_ADP1050=m +CONFIG_SENSORS_BEL_PFE=m +CONFIG_SENSORS_BPA_RS600=m +CONFIG_SENSORS_CRPS=m +CONFIG_SENSORS_DELTA_AHE50DC_FAN=m +CONFIG_SENSORS_FSP_3Y=m +CONFIG_SENSORS_HAC300S=m +CONFIG_SENSORS_DPS920AB=m +CONFIG_SENSORS_INA233=m +CONFIG_SENSORS_LM25066=m +CONFIG_SENSORS_LM25066_REGULATOR=y +CONFIG_SENSORS_LT3074=m +CONFIG_SENSORS_LT3074_REGULATOR=m +CONFIG_SENSORS_LT7182S=m +CONFIG_SENSORS_LTC2978=m +CONFIG_SENSORS_LTC3815=m +CONFIG_SENSORS_MAX16064=m +CONFIG_SENSORS_MAX17616=m +CONFIG_SENSORS_MAX20751=m +CONFIG_SENSORS_MAX34440=m +CONFIG_SENSORS_MAX8688=m +CONFIG_SENSORS_MP2869=m +CONFIG_SENSORS_MP2888=m +CONFIG_SENSORS_MP2891=m +CONFIG_SENSORS_MP2925=m +CONFIG_SENSORS_MP29502=m +CONFIG_SENSORS_MP2975=m +CONFIG_SENSORS_MP2993=m +CONFIG_SENSORS_MP2975_REGULATOR=y +CONFIG_SENSORS_MP5023=m +CONFIG_SENSORS_MP5920=m +CONFIG_SENSORS_MP5926=m +CONFIG_SENSORS_MP9941=m +CONFIG_SENSORS_MP9945=m +CONFIG_SENSORS_MPQ7932_REGULATOR=y +CONFIG_SENSORS_MPQ7932=m +CONFIG_SENSORS_MPQ8785=m +CONFIG_SENSORS_PIM4328=m +CONFIG_SENSORS_PLI1209BC=m +CONFIG_SENSORS_PLI1209BC_REGULATOR=y +CONFIG_SENSORS_PM6764TR=m +CONFIG_SENSORS_Q54SJ108A2=m +CONFIG_SENSORS_STEF48H28=m +CONFIG_SENSORS_TDA38640=m +CONFIG_SENSORS_TDA38640_REGULATOR=y +CONFIG_SENSORS_TPS25990=m +CONFIG_SENSORS_TPS40422=m +CONFIG_SENSORS_TPS53679=m +CONFIG_SENSORS_TPS546D24=m +CONFIG_SENSORS_UCD9000=m +CONFIG_SENSORS_UCD9200=m +CONFIG_SENSORS_XDP710=m +CONFIG_SENSORS_XDPE152=m +CONFIG_SENSORS_ZL6100=m +CONFIG_SENSORS_PT5161L=m +CONFIG_SENSORS_PWM_FAN=m +CONFIG_SENSORS_QNAP_MCU_HWMON=m +CONFIG_SENSORS_RASPBERRYPI_HWMON=m +CONFIG_SENSORS_SHT15=m +CONFIG_SENSORS_SHT21=m +CONFIG_SENSORS_SHT3x=m +CONFIG_SENSORS_SHTC1=m +CONFIG_SENSORS_SIS5595=m +CONFIG_SENSORS_SY7636A=m +CONFIG_SENSORS_DME1737=m +CONFIG_SENSORS_EMC1403=m +CONFIG_SENSORS_EMC2305=m +CONFIG_SENSORS_EMC6W201=m +CONFIG_SENSORS_SMSC47M1=m +CONFIG_SENSORS_SMSC47M192=m +CONFIG_SENSORS_SMSC47B397=m +CONFIG_SENSORS_SCH5627=m +CONFIG_SENSORS_SCH5636=m +CONFIG_SENSORS_SURFACE_FAN=m +CONFIG_SENSORS_SURFACE_TEMP=m +CONFIG_SENSORS_ADC128D818=m +CONFIG_SENSORS_ADS7828=m +CONFIG_SENSORS_ADS7871=m +CONFIG_SENSORS_AMC6821=m +CONFIG_SENSORS_INA209=m +CONFIG_SENSORS_INA2XX=m +CONFIG_SENSORS_INA238=m +CONFIG_SENSORS_INA3221=m +CONFIG_SENSORS_SPD5118=m +CONFIG_SENSORS_TC74=m +CONFIG_SENSORS_THMC50=m +CONFIG_SENSORS_TMP102=m +CONFIG_SENSORS_TMP103=m +CONFIG_SENSORS_TMP108=m +CONFIG_SENSORS_TMP401=m +CONFIG_SENSORS_TMP421=m +CONFIG_SENSORS_TMP464=m +CONFIG_SENSORS_TMP513=m +CONFIG_SENSORS_TSC1641=m +CONFIG_SENSORS_VEXPRESS=m +CONFIG_SENSORS_VIA686A=m +CONFIG_SENSORS_VT1211=m +CONFIG_SENSORS_VT8231=m +CONFIG_SENSORS_W83773G=m +CONFIG_SENSORS_W83781D=m +CONFIG_SENSORS_W83791D=m +CONFIG_SENSORS_W83792D=m +CONFIG_SENSORS_W83793=m +CONFIG_SENSORS_W83795=m +CONFIG_SENSORS_W83L785TS=m +CONFIG_SENSORS_W83L786NG=m +CONFIG_SENSORS_W83627HF=m +CONFIG_SENSORS_W83627EHF=m +CONFIG_SENSORS_XGENE=m +CONFIG_SENSORS_INTEL_M10_BMC_HWMON=m +CONFIG_SENSORS_ACPI_POWER=m +CONFIG_THERMAL_NETLINK=y +CONFIG_THERMAL_STATISTICS=y +CONFIG_THERMAL_DEFAULT_GOV_POWER_ALLOCATOR=y +CONFIG_THERMAL_GOV_FAIR_SHARE=y +CONFIG_THERMAL_GOV_USER_SPACE=y +CONFIG_THERMAL_GOV_POWER_ALLOCATOR=y +CONFIG_DEVFREQ_THERMAL=y +CONFIG_PCIE_THERMAL=y +CONFIG_THERMAL_MMIO=m +CONFIG_HISI_THERMAL=m +CONFIG_IMX_SC_THERMAL=m +CONFIG_IMX8MM_THERMAL=m +CONFIG_IMX91_THERMAL=m +CONFIG_K3_THERMAL=m +CONFIG_MAX77620_THERMAL=m +CONFIG_QORIQ_THERMAL=m +CONFIG_SUN8I_THERMAL=m +CONFIG_ROCKCHIP_THERMAL=m +CONFIG_ARMADA_THERMAL=m +CONFIG_BCM2711_THERMAL=m +CONFIG_BCM2835_THERMAL=m +CONFIG_RZG2L_THERMAL=m +CONFIG_RZG3E_THERMAL=m +CONFIG_RZG3S_THERMAL=m +CONFIG_TEGRA_SOCTHERM=m +CONFIG_TEGRA_BPMP_THERMAL=m +CONFIG_QCOM_TSENS=m +CONFIG_QCOM_SPMI_ADC_TM5=m +CONFIG_QCOM_SPMI_TEMP_ALARM=m +CONFIG_QCOM_LMH=m +CONFIG_KHADAS_MCU_FAN_THERMAL=m +CONFIG_APPLE_PMP_THERMAL=m +CONFIG_WATCHDOG=y +CONFIG_WATCHDOG_SYSFS=y +CONFIG_WATCHDOG_HRTIMER_PRETIMEOUT=y +CONFIG_SOFT_WATCHDOG=m +CONFIG_BD96801_WATCHDOG=m +CONFIG_CROS_EC_WATCHDOG=m +CONFIG_GPIO_WATCHDOG=m +CONFIG_WDAT_WDT=m +CONFIG_XILINX_WATCHDOG=m +CONFIG_XILINX_WINDOW_WATCHDOG=m +CONFIG_MLX_WDT=m +CONFIG_ARM_SP805_WATCHDOG=m +CONFIG_ARM_SBSA_WATCHDOG=m +CONFIG_ARMADA_37XX_WATCHDOG=m +CONFIG_CADENCE_WATCHDOG=m +CONFIG_DW_WATCHDOG=m +CONFIG_K3_RTI_WATCHDOG=m +CONFIG_SUNXI_WATCHDOG=m +CONFIG_MAX77620_WATCHDOG=m +CONFIG_IMX2_WDT=m +CONFIG_IMX_SC_WDT=m +CONFIG_IMX7ULP_WDT=m +CONFIG_S32G_WDT=m +CONFIG_TEGRA_WATCHDOG=m +CONFIG_QCOM_WDT=m +CONFIG_MESON_GXBB_WATCHDOG=m +CONFIG_MESON_WATCHDOG=m +CONFIG_ARM_SMC_WATCHDOG=m +CONFIG_RENESAS_WWDT=m +CONFIG_RENESAS_RZG2LWDT=m +CONFIG_RENESAS_RZV2HWDT=m +CONFIG_PM8916_WATCHDOG=m +CONFIG_APPLE_WATCHDOG=y +CONFIG_ALIM7101_WDT=m +CONFIG_I6300ESB_WDT=m +CONFIG_HP_WATCHDOG=m +CONFIG_NIC7018_WDT=m +CONFIG_BCM2835_WDT=m +CONFIG_PCIPCWATCHDOG=m +CONFIG_WDTPCI=m +CONFIG_USBPCWATCHDOG=m +CONFIG_SSB_DRIVER_GPIO=y +CONFIG_BCMA_DRIVER_GMAC_CMN=y +CONFIG_BCMA_DRIVER_GPIO=y +CONFIG_MFD_ADP5585=m +CONFIG_MFD_SMPRO=m +CONFIG_MFD_AS3722=y +CONFIG_MFD_BD9571MWV=m +CONFIG_MFD_AC100=m +CONFIG_MFD_AXP20X_I2C=y +CONFIG_MFD_AXP20X_RSB=m +CONFIG_MFD_CS40L50_I2C=m +CONFIG_MFD_CS40L50_SPI=m +CONFIG_MFD_CS42L43_I2C=m +CONFIG_MFD_CS42L43_SDW=m +CONFIG_MFD_MACSMC=y +CONFIG_MFD_DLN2=m +CONFIG_MFD_HI6421_PMIC=m +CONFIG_MFD_HI6421_SPMI=m +CONFIG_MFD_HI655X_PMIC=m +CONFIG_MFD_MAX5970=m +CONFIG_MFD_MAX77620=y +CONFIG_MFD_MAX77650=m +CONFIG_MFD_MAX77686=y +CONFIG_MFD_MAX77705=m +CONFIG_MFD_MAX77714=m +CONFIG_MFD_MAX77759=m +CONFIG_MFD_SPMI_PMIC=y +CONFIG_MFD_SY7636A=m +CONFIG_MFD_RT4831=m +CONFIG_MFD_RT5033=m +CONFIG_MFD_RT5120=m +CONFIG_MFD_RK8XX_I2C=m +CONFIG_MFD_RK8XX_SPI=m +CONFIG_MFD_SM501=m +CONFIG_MFD_SM501_GPIO=y +CONFIG_MFD_STMPE=y +CONFIG_STMPE_SPI=y +CONFIG_MFD_TI_AM335X_TSCADC=m +CONFIG_MFD_TPS65086=m +CONFIG_MFD_TPS65219=m +CONFIG_MFD_TPS6594_I2C=m +CONFIG_MFD_VX855=m +CONFIG_MFD_ROHM_BD718XX=y +CONFIG_MFD_ROHM_BD96801=m +CONFIG_MFD_WCD934X=m +CONFIG_MFD_KHADAS_MCU=m +CONFIG_MFD_QCOM_PM8008=m +CONFIG_MFD_INTEL_M10_BMC_SPI=m +CONFIG_MFD_INTEL_M10_BMC_PMCI=m +CONFIG_MFD_QNAP_MCU=m +CONFIG_MFD_RSMU_I2C=m +CONFIG_MFD_RSMU_SPI=m +CONFIG_REGULATOR_FIXED_VOLTAGE=y +CONFIG_REGULATOR_VIRTUAL_CONSUMER=m +CONFIG_REGULATOR_USERSPACE_CONSUMER=m +CONFIG_REGULATOR_ACT8865=m +CONFIG_REGULATOR_ADP5055=m +CONFIG_REGULATOR_ANATOP=m +CONFIG_REGULATOR_ARM_SCMI=y +CONFIG_REGULATOR_AS3722=m +CONFIG_REGULATOR_AW37503=m +CONFIG_REGULATOR_AXP20X=m +CONFIG_REGULATOR_BD718XX=m +CONFIG_REGULATOR_BD9571MWV=m +CONFIG_REGULATOR_BD96801=m +CONFIG_REGULATOR_CROS_EC=m +CONFIG_REGULATOR_FAN53555=y +CONFIG_REGULATOR_GPIO=y +CONFIG_REGULATOR_HI6421=m +CONFIG_REGULATOR_HI6421V530=m +CONFIG_REGULATOR_HI655X=m +CONFIG_REGULATOR_HI6421V600=m +CONFIG_REGULATOR_MAX5970=m +CONFIG_REGULATOR_MAX77503=m +CONFIG_REGULATOR_MAX77620=y +CONFIG_REGULATOR_MAX77650=m +CONFIG_REGULATOR_MAX77675=m +CONFIG_REGULATOR_MAX77857=m +CONFIG_REGULATOR_MAX8893=m +CONFIG_REGULATOR_MAX8973=m +CONFIG_REGULATOR_MAX20411=m +CONFIG_REGULATOR_MAX77686=m +CONFIG_REGULATOR_MAX77802=m +CONFIG_REGULATOR_MP5416=m +CONFIG_REGULATOR_MP8859=m +CONFIG_REGULATOR_MP886X=m +CONFIG_REGULATOR_MT6316=m +CONFIG_REGULATOR_MT6363=m +CONFIG_REGULATOR_PCA9450=m +CONFIG_REGULATOR_PF9453=m +CONFIG_REGULATOR_PF0900=m +CONFIG_REGULATOR_PF530X=m +CONFIG_REGULATOR_PF8X00=m +CONFIG_REGULATOR_PFUZE100=m +CONFIG_REGULATOR_PWM=y +CONFIG_REGULATOR_QCOM_PM8008=m +CONFIG_REGULATOR_QCOM_REFGEN=m +CONFIG_REGULATOR_QCOM_RPMH=y +CONFIG_REGULATOR_QCOM_SMD_RPM=m +CONFIG_REGULATOR_QCOM_SPMI=m +CONFIG_REGULATOR_QCOM_USB_VBUS=m +CONFIG_REGULATOR_RAA215300=m +CONFIG_REGULATOR_RASPBERRYPI_TOUCHSCREEN_ATTINY=m +CONFIG_REGULATOR_RASPBERRYPI_TOUCHSCREEN_V2=m +CONFIG_REGULATOR_RK808=m +CONFIG_REGULATOR_RT4801=m +CONFIG_REGULATOR_RT4803=m +CONFIG_REGULATOR_RT4831=m +CONFIG_REGULATOR_RT5033=m +CONFIG_REGULATOR_RT5120=m +CONFIG_REGULATOR_RT5190A=m +CONFIG_REGULATOR_RT5739=m +CONFIG_REGULATOR_RT5759=m +CONFIG_REGULATOR_RT6160=m +CONFIG_REGULATOR_RT6190=m +CONFIG_REGULATOR_RT6245=m +CONFIG_REGULATOR_RT8092=m +CONFIG_REGULATOR_RTQ2134=m +CONFIG_REGULATOR_RTMV20=m +CONFIG_REGULATOR_RTQ6752=m +CONFIG_REGULATOR_RTQ2208=m +# CONFIG_REGULATOR_SUN20I is not set +CONFIG_REGULATOR_SY7636A=m +CONFIG_REGULATOR_SY8106A=m +CONFIG_REGULATOR_SY8827N=m +CONFIG_REGULATOR_TPS62360=m +CONFIG_REGULATOR_TPS6286X=m +CONFIG_REGULATOR_TPS65086=m +CONFIG_REGULATOR_TPS65132=m +CONFIG_REGULATOR_TPS65185=m +CONFIG_REGULATOR_TPS65219=m +CONFIG_REGULATOR_VCTRL=m +CONFIG_REGULATOR_VEXPRESS=m +CONFIG_REGULATOR_WM8994=m +CONFIG_REGULATOR_QCOM_LABIBB=m +CONFIG_RC_CORE=y +CONFIG_BPF_LIRC_MODE2=y +CONFIG_LIRC=y +CONFIG_RC_MAP=m +CONFIG_RC_DECODERS=y +CONFIG_IR_IMON_DECODER=m +CONFIG_IR_JVC_DECODER=m +CONFIG_IR_MCE_KBD_DECODER=m +CONFIG_IR_NEC_DECODER=m +CONFIG_IR_RC5_DECODER=m +CONFIG_IR_RC6_DECODER=m +CONFIG_IR_RCMM_DECODER=m +CONFIG_IR_SANYO_DECODER=m +CONFIG_IR_SHARP_DECODER=m +CONFIG_IR_SONY_DECODER=m +CONFIG_IR_XMP_DECODER=m +CONFIG_RC_DEVICES=y +CONFIG_IR_ENE=m +CONFIG_IR_FINTEK=m +CONFIG_IR_GPIO_CIR=m +CONFIG_IR_GPIO_TX=m +CONFIG_IR_HIX5HD2=m +CONFIG_IR_IGORPLUGUSB=m +CONFIG_IR_IGUANA=m +CONFIG_IR_IMON=m +CONFIG_IR_IMON_RAW=m +CONFIG_IR_ITE_CIR=m +CONFIG_IR_MCEUSB=m +CONFIG_IR_MESON=m +CONFIG_IR_NUVOTON=m +CONFIG_IR_PWM_TX=m +CONFIG_IR_REDRAT3=m +CONFIG_IR_SERIAL=m +CONFIG_IR_SERIAL_TRANSMITTER=y +CONFIG_IR_SPI=m +CONFIG_IR_STREAMZAP=m +CONFIG_IR_SUNXI=m +CONFIG_IR_TOY=m +CONFIG_IR_TTUSBIR=m +CONFIG_RC_ATI_REMOTE=m +CONFIG_RC_LOOPBACK=m +CONFIG_RC_XBOX_DVD=m +CONFIG_MEDIA_CEC_RC=y +CONFIG_MEDIA_CEC_SUPPORT=y +CONFIG_CEC_CH7322=m +CONFIG_CEC_CROS_EC=m +CONFIG_CEC_MESON_AO=m +CONFIG_CEC_MESON_G12A_AO=m +CONFIG_CEC_GPIO=m +CONFIG_CEC_TEGRA=m +CONFIG_USB_PULSE8_CEC=m +CONFIG_USB_RAINSHADOW_CEC=m +CONFIG_MEDIA_SUPPORT=m +CONFIG_MEDIA_SUPPORT_FILTER=y +CONFIG_MEDIA_CAMERA_SUPPORT=y +CONFIG_MEDIA_ANALOG_TV_SUPPORT=y +CONFIG_MEDIA_DIGITAL_TV_SUPPORT=y +CONFIG_MEDIA_RADIO_SUPPORT=y +CONFIG_MEDIA_PLATFORM_SUPPORT=y +CONFIG_MEDIA_TEST_SUPPORT=y +CONFIG_MEDIA_USB_SUPPORT=y +CONFIG_USB_GSPCA=m +CONFIG_USB_GSPCA_BENQ=m +CONFIG_USB_GSPCA_CONEX=m +CONFIG_USB_GSPCA_CPIA1=m +CONFIG_USB_GSPCA_DTCS033=m +CONFIG_USB_GSPCA_ETOMS=m +CONFIG_USB_GSPCA_FINEPIX=m +CONFIG_USB_GSPCA_JEILINJ=m +CONFIG_USB_GSPCA_JL2005BCD=m +CONFIG_USB_GSPCA_KINECT=m +CONFIG_USB_GSPCA_KONICA=m +CONFIG_USB_GSPCA_MARS=m +CONFIG_USB_GSPCA_MR97310A=m +CONFIG_USB_GSPCA_NW80X=m +CONFIG_USB_GSPCA_OV519=m +CONFIG_USB_GSPCA_OV534=m +CONFIG_USB_GSPCA_OV534_9=m +CONFIG_USB_GSPCA_PAC207=m +CONFIG_USB_GSPCA_PAC7302=m +CONFIG_USB_GSPCA_PAC7311=m +CONFIG_USB_GSPCA_SE401=m +CONFIG_USB_GSPCA_SN9C2028=m +CONFIG_USB_GSPCA_SN9C20X=m +CONFIG_USB_GSPCA_SONIXB=m +CONFIG_USB_GSPCA_SONIXJ=m +CONFIG_USB_GSPCA_SPCA1528=m +CONFIG_USB_GSPCA_SPCA500=m +CONFIG_USB_GSPCA_SPCA501=m +CONFIG_USB_GSPCA_SPCA505=m +CONFIG_USB_GSPCA_SPCA506=m +CONFIG_USB_GSPCA_SPCA508=m +CONFIG_USB_GSPCA_SPCA561=m +CONFIG_USB_GSPCA_SQ905=m +CONFIG_USB_GSPCA_SQ905C=m +CONFIG_USB_GSPCA_SQ930X=m +CONFIG_USB_GSPCA_STK014=m +CONFIG_USB_GSPCA_STK1135=m +CONFIG_USB_GSPCA_STV0680=m +CONFIG_USB_GSPCA_SUNPLUS=m +CONFIG_USB_GSPCA_T613=m +CONFIG_USB_GSPCA_TOPRO=m +CONFIG_USB_GSPCA_TOUPTEK=m +CONFIG_USB_GSPCA_TV8532=m +CONFIG_USB_GSPCA_VC032X=m +CONFIG_USB_GSPCA_VICAM=m +CONFIG_USB_GSPCA_XIRLINK_CIT=m +CONFIG_USB_GSPCA_ZC3XX=m +CONFIG_USB_GL860=m +CONFIG_USB_M5602=m +CONFIG_USB_STV06XX=m +CONFIG_USB_PWC=m +CONFIG_USB_S2255=m +CONFIG_VIDEO_USBTV=m +CONFIG_USB_VIDEO_CLASS=m +CONFIG_VIDEO_GO7007=m +CONFIG_VIDEO_GO7007_USB=m +CONFIG_VIDEO_GO7007_USB_S2250_BOARD=m +CONFIG_VIDEO_HDPVR=m +CONFIG_VIDEO_PVRUSB2=m +CONFIG_VIDEO_STK1160=m +CONFIG_VIDEO_AU0828=m +CONFIG_VIDEO_CX231XX=m +CONFIG_VIDEO_CX231XX_ALSA=m +CONFIG_VIDEO_CX231XX_DVB=m +CONFIG_DVB_AS102=m +CONFIG_DVB_USB_V2=m +CONFIG_DVB_USB_AF9015=m +CONFIG_DVB_USB_AF9035=m +CONFIG_DVB_USB_ANYSEE=m +CONFIG_DVB_USB_AU6610=m +CONFIG_DVB_USB_AZ6007=m +CONFIG_DVB_USB_CE6230=m +CONFIG_DVB_USB_DVBSKY=m +CONFIG_DVB_USB_EC168=m +CONFIG_DVB_USB_GL861=m +CONFIG_DVB_USB_LME2510=m +CONFIG_DVB_USB_MXL111SF=m +CONFIG_DVB_USB_RTL28XXU=m +CONFIG_DVB_USB_ZD1301=m +CONFIG_DVB_USB=m +CONFIG_DVB_USB_A800=m +CONFIG_DVB_USB_AF9005=m +CONFIG_DVB_USB_AF9005_REMOTE=m +CONFIG_DVB_USB_AZ6027=m +CONFIG_DVB_USB_CINERGY_T2=m +CONFIG_DVB_USB_CXUSB=m +CONFIG_DVB_USB_CXUSB_ANALOG=y +CONFIG_DVB_USB_DIB0700=m +CONFIG_DVB_USB_DIBUSB_MB=m +CONFIG_DVB_USB_DIBUSB_MC=m +CONFIG_DVB_USB_DIGITV=m +CONFIG_DVB_USB_DTT200U=m +CONFIG_DVB_USB_DTV5100=m +CONFIG_DVB_USB_DW2102=m +CONFIG_DVB_USB_GP8PSK=m +CONFIG_DVB_USB_M920X=m +CONFIG_DVB_USB_NOVA_T_USB2=m +CONFIG_DVB_USB_OPERA1=m +CONFIG_DVB_USB_PCTV452E=m +CONFIG_DVB_USB_TECHNISAT_USB2=m +CONFIG_DVB_USB_TTUSB2=m +CONFIG_DVB_USB_UMT_010=m +CONFIG_DVB_USB_VP702X=m +CONFIG_DVB_USB_VP7045=m +CONFIG_SMS_USB_DRV=m +CONFIG_DVB_TTUSB_BUDGET=m +CONFIG_DVB_TTUSB_DEC=m +CONFIG_VIDEO_EM28XX=m +CONFIG_VIDEO_EM28XX_V4L2=m +CONFIG_VIDEO_EM28XX_ALSA=m +CONFIG_VIDEO_EM28XX_DVB=m +CONFIG_MEDIA_PCI_SUPPORT=y +CONFIG_VIDEO_SOLO6X10=m +CONFIG_VIDEO_TW686X=m +CONFIG_VIDEO_IVTV=m +CONFIG_VIDEO_FB_IVTV=m +CONFIG_VIDEO_HEXIUM_GEMINI=m +CONFIG_VIDEO_HEXIUM_ORION=m +CONFIG_VIDEO_MXB=m +CONFIG_VIDEO_BT848=m +CONFIG_DVB_BT8XX=m +CONFIG_VIDEO_CX18=m +CONFIG_VIDEO_CX18_ALSA=m +CONFIG_VIDEO_CX23885=m +CONFIG_MEDIA_ALTERA_CI=m +CONFIG_VIDEO_CX88=m +CONFIG_VIDEO_CX88_ALSA=m +CONFIG_VIDEO_CX88_BLACKBIRD=m +CONFIG_VIDEO_CX88_DVB=m +CONFIG_VIDEO_SAA7134=m +CONFIG_VIDEO_SAA7134_ALSA=m +CONFIG_VIDEO_SAA7134_DVB=m +CONFIG_VIDEO_SAA7134_GO7007=m +CONFIG_VIDEO_SAA7164=m +CONFIG_DVB_B2C2_FLEXCOP_PCI=m +CONFIG_DVB_DDBRIDGE=m +CONFIG_DVB_DM1105=m +CONFIG_MANTIS_CORE=m +CONFIG_DVB_MANTIS=m +CONFIG_DVB_HOPPER=m +CONFIG_DVB_NETUP_UNIDVB=m +CONFIG_DVB_NGENE=m +CONFIG_DVB_PLUTO2=m +CONFIG_DVB_PT1=m +CONFIG_DVB_PT3=m +CONFIG_DVB_SMIPCIE=m +CONFIG_DVB_BUDGET_CORE=m +CONFIG_DVB_BUDGET=m +CONFIG_DVB_BUDGET_CI=m +CONFIG_DVB_BUDGET_AV=m +CONFIG_IPU_BRIDGE=m +CONFIG_RADIO_MAXIRADIO=m +CONFIG_RADIO_SAA7706H=m +CONFIG_RADIO_SHARK=m +CONFIG_RADIO_SHARK2=m +CONFIG_RADIO_SI4713=m +CONFIG_RADIO_TEA5764=m +CONFIG_USB_DSBR=m +CONFIG_USB_KEENE=m +CONFIG_USB_MA901=m +CONFIG_USB_MR800=m +CONFIG_RADIO_SI470X=m +CONFIG_USB_SI470X=m +CONFIG_I2C_SI470X=m +CONFIG_V4L_PLATFORM_DRIVERS=y +CONFIG_V4L_MEM2MEM_DRIVERS=y +CONFIG_VIDEO_MUX=m +CONFIG_VIDEO_ALLEGRO_DVT=m +CONFIG_VIDEO_C3_ISP=m +CONFIG_VIDEO_C3_MIPI_ADAPTER=m +CONFIG_VIDEO_C3_MIPI_CSI2=m +CONFIG_VIDEO_MESON_GE2D=m +CONFIG_VIDEO_AMPHION_VPU=m +CONFIG_VIDEO_APPLE_ISP=m +CONFIG_VIDEO_APPLE_AVD=m +CONFIG_VIDEO_APPLE_AVE=m +CONFIG_VIDEO_APPLE_JPEG=m +CONFIG_VIDEO_APPLE_PRORES=m +CONFIG_VIDEO_APPLE_SCALER=m +CONFIG_VIDEO_MALI_C55=m +CONFIG_VIDEO_BCM2835_UNICAM=m +CONFIG_VIDEO_CADENCE_CSI2RX=m +CONFIG_VIDEO_CADENCE_CSI2TX=m +CONFIG_VIDEO_CODA=m +CONFIG_VIDEO_WAVE_VPU=m +CONFIG_VIDEO_E5010_JPEG_ENC=m +CONFIG_VIDEO_TEGRA_VDE=m +CONFIG_VIDEO_IMX7_CSI=m +CONFIG_VIDEO_IMX8MQ_MIPI_CSI2=m +CONFIG_VIDEO_IMX_MIPI_CSIS=m +CONFIG_VIDEO_IMX8_ISI=m +CONFIG_VIDEO_IMX8_ISI_M2M=y +CONFIG_VIDEO_IMX_PXP=m +CONFIG_VIDEO_DW100=m +CONFIG_VIDEO_IMX8_JPEG=m +CONFIG_VIDEO_QCOM_CAMSS=m +CONFIG_VIDEO_QCOM_IRIS=m +CONFIG_VIDEO_QCOM_VENUS=m +CONFIG_VIDEO_RASPBERRYPI_PISP_BE=m +CONFIG_VIDEO_RP1_CFE=m +CONFIG_VIDEO_RZG2L_CSI2=m +CONFIG_VIDEO_RZG2L_CRU=m +CONFIG_VIDEO_RZV2H_IVC=m +CONFIG_VIDEO_RENESAS_FCP=m +CONFIG_VIDEO_RENESAS_FDP1=m +CONFIG_VIDEO_RENESAS_VSP1=m +CONFIG_VIDEO_ROCKCHIP_RGA=m +CONFIG_VIDEO_ROCKCHIP_CIF=m +CONFIG_VIDEO_ROCKCHIP_ISP1=m +CONFIG_VIDEO_ROCKCHIP_VDEC=m +CONFIG_VIDEO_SUN4I_CSI=m +CONFIG_VIDEO_SUN6I_CSI=m +CONFIG_VIDEO_SUN8I_DEINTERLACE=m +CONFIG_VIDEO_SUN8I_ROTATE=m +CONFIG_VIDEO_SYNOPSYS_HDMIRX=m +CONFIG_VIDEO_SYNOPSYS_HDMIRX_LOAD_DEFAULT_EDID=y +CONFIG_VIDEO_DW_MIPI_CSI2RX=m +CONFIG_VIDEO_TI_CAL=m +CONFIG_VIDEO_TI_CAL_MC=y +CONFIG_VIDEO_TI_J721E_CSI2RX=m +CONFIG_VIDEO_HANTRO=m +CONFIG_VIDEO_HANTRO_HEVC_RFC=y +CONFIG_SMS_SDIO_DRV=m +CONFIG_V4L_TEST_DRIVERS=y +CONFIG_VIDEO_VIM2M=m +CONFIG_VIDEO_VICODEC=m +CONFIG_VIDEO_VIMC=m +CONFIG_VIDEO_VIVID=m +CONFIG_VIDEO_VIVID_CEC=y +CONFIG_VIDEO_VISL=m +CONFIG_VIDEO_AR0521=m +CONFIG_VIDEO_GC0308=m +CONFIG_VIDEO_GC0310=m +CONFIG_VIDEO_GC2145=m +CONFIG_VIDEO_HI556=m +CONFIG_VIDEO_HI846=m +CONFIG_VIDEO_HI847=m +CONFIG_VIDEO_IMX111=m +CONFIG_VIDEO_IMX208=m +CONFIG_VIDEO_IMX214=m +CONFIG_VIDEO_IMX219=m +CONFIG_VIDEO_IMX258=m +CONFIG_VIDEO_IMX274=m +CONFIG_VIDEO_IMX283=m +CONFIG_VIDEO_IMX290=m +CONFIG_VIDEO_IMX296=m +CONFIG_VIDEO_IMX319=m +CONFIG_VIDEO_IMX334=m +CONFIG_VIDEO_IMX335=m +CONFIG_VIDEO_IMX355=m +CONFIG_VIDEO_IMX412=m +CONFIG_VIDEO_IMX415=m +CONFIG_VIDEO_MT9M001=m +CONFIG_VIDEO_MT9M114=m +CONFIG_VIDEO_MT9P031=m +CONFIG_VIDEO_MT9T112=m +CONFIG_VIDEO_MT9V032=m +CONFIG_VIDEO_MT9V111=m +CONFIG_VIDEO_OG01A1B=m +CONFIG_VIDEO_OG0VE1B=m +CONFIG_VIDEO_OS05B10=m +CONFIG_VIDEO_OV01A10=m +CONFIG_VIDEO_OV02A10=m +CONFIG_VIDEO_OV02E10=m +CONFIG_VIDEO_OV02C10=m +CONFIG_VIDEO_OV08D10=m +CONFIG_VIDEO_OV08X40=m +CONFIG_VIDEO_OV13858=m +CONFIG_VIDEO_OV13B10=m +CONFIG_VIDEO_OV2659=m +CONFIG_VIDEO_OV2680=m +CONFIG_VIDEO_OV2685=m +CONFIG_VIDEO_OV2735=m +CONFIG_VIDEO_OV2740=m +CONFIG_VIDEO_OV4689=m +CONFIG_VIDEO_OV5640=m +CONFIG_VIDEO_OV5645=m +CONFIG_VIDEO_OV5647=m +CONFIG_VIDEO_OV5648=m +CONFIG_VIDEO_OV5670=m +CONFIG_VIDEO_OV5675=m +CONFIG_VIDEO_OV5693=m +CONFIG_VIDEO_OV5695=m +CONFIG_VIDEO_OV6211=m +CONFIG_VIDEO_OV64A40=m +CONFIG_VIDEO_OV7251=m +CONFIG_VIDEO_OV772X=m +CONFIG_VIDEO_OV7740=m +CONFIG_VIDEO_OV8856=m +CONFIG_VIDEO_OV8858=m +CONFIG_VIDEO_OV8865=m +CONFIG_VIDEO_OV9282=m +CONFIG_VIDEO_OV9640=m +CONFIG_VIDEO_OV9650=m +CONFIG_VIDEO_OV9734=m +CONFIG_VIDEO_RDACM20=m +CONFIG_VIDEO_RJ54N1=m +CONFIG_VIDEO_S5C73M3=m +CONFIG_VIDEO_S5K3M5=m +CONFIG_VIDEO_S5K5BAF=m +CONFIG_VIDEO_S5K6A3=m +CONFIG_VIDEO_S5KJN1=m +CONFIG_VIDEO_VD55G1=m +CONFIG_VIDEO_VD56G3=m +CONFIG_VIDEO_CCS=m +CONFIG_VIDEO_ET8EK8=m +CONFIG_VIDEO_AD5820=m +CONFIG_VIDEO_AK7375=m +CONFIG_VIDEO_DW9714=m +CONFIG_VIDEO_DW9719=m +CONFIG_VIDEO_DW9768=m +CONFIG_VIDEO_DW9807_VCM=m +CONFIG_VIDEO_ADP1653=m +CONFIG_VIDEO_LM3560=m +CONFIG_VIDEO_LM3646=m +CONFIG_VIDEO_TDA1997X=m +CONFIG_VIDEO_TLV320AIC23B=m +CONFIG_VIDEO_ADV7180=m +CONFIG_VIDEO_ADV7183=m +CONFIG_VIDEO_ADV748X=m +CONFIG_VIDEO_ADV7604=m +CONFIG_VIDEO_ADV7842=m +CONFIG_VIDEO_BT819=m +CONFIG_VIDEO_BT856=m +CONFIG_VIDEO_BT866=m +CONFIG_VIDEO_ISL7998X=m +CONFIG_VIDEO_LT6911UXE=m +CONFIG_VIDEO_KS0127=m +CONFIG_VIDEO_MAX9286=m +CONFIG_VIDEO_ML86V7667=m +CONFIG_VIDEO_SAA7110=m +CONFIG_VIDEO_TC358743=m +CONFIG_VIDEO_TC358743_CEC=y +CONFIG_VIDEO_TC358746=m +CONFIG_VIDEO_TVP514X=m +CONFIG_VIDEO_TVP7002=m +CONFIG_VIDEO_TW9910=m +CONFIG_VIDEO_VPX3220=m +CONFIG_VIDEO_ADV7170=m +CONFIG_VIDEO_ADV7175=m +CONFIG_VIDEO_ADV7343=m +CONFIG_VIDEO_ADV7393=m +CONFIG_VIDEO_AK881X=m +CONFIG_VIDEO_SAA7185=m +CONFIG_VIDEO_THS8200=m +CONFIG_VIDEO_I2C=m +CONFIG_VIDEO_ST_MIPID02=m +CONFIG_VIDEO_THS7303=m +CONFIG_VIDEO_DS90UB913=m +CONFIG_VIDEO_DS90UB953=m +CONFIG_VIDEO_DS90UB960=m +CONFIG_VIDEO_MAX96714=m +CONFIG_VIDEO_MAX96717=m +CONFIG_CXD2880_SPI_DRV=m +CONFIG_VIDEO_GS1662=m +CONFIG_AUXDISPLAY=y +CONFIG_HD44780=m +CONFIG_HT16K33=m +CONFIG_DRM=y +CONFIG_DRM_WERROR=y +CONFIG_DRM_PANIC=y +CONFIG_DRM_PANIC_SCREEN_QR_CODE=y +CONFIG_DRM_LOAD_EDID_FIRMWARE=y +CONFIG_DRM_DISPLAY_DP_AUX_CEC=y +CONFIG_DRM_DISPLAY_DP_AUX_CHARDEV=y +CONFIG_DRM_ADP=m +CONFIG_DRM_AMDGPU=m +CONFIG_DRM_AMDGPU_SI=y +CONFIG_DRM_AMDGPU_CIK=y +CONFIG_DRM_AMD_ISP=y +CONFIG_DRM_AMD_ACP=y +CONFIG_DRM_AMD_DC_SI=y +CONFIG_DRM_AMD_SECURE_DISPLAY=y +CONFIG_HSA_AMD=y +CONFIG_DRM_APPLE=m +CONFIG_DRM_APPLE_DCP_T8132=y +CONFIG_DRM_APPLE_DCP_T8152=y +CONFIG_DRM_HDLCD=m +CONFIG_DRM_MALI_DISPLAY=m +CONFIG_DRM_KOMEDA=m +CONFIG_DRM_ASAHI=m +CONFIG_DRM_ASAHI_G18=y +CONFIG_DRM_ASAHI_M5=y +CONFIG_DRM_ASAHI_M3_T8122=y +CONFIG_DRM_AST=m +CONFIG_DRM_CHIPONE_ICN6211=m +CONFIG_DRM_CHRONTEL_CH7033=m +CONFIG_DRM_CROS_EC_ANX7688=m +CONFIG_DRM_FSL_LDB=m +CONFIG_DRM_I2C_NXP_TDA998X=m +CONFIG_DRM_ITE_IT6263=m +CONFIG_DRM_ITE_IT6505=m +CONFIG_DRM_LONTIUM_LT8912B=m +CONFIG_DRM_LONTIUM_LT9611=m +CONFIG_DRM_LONTIUM_LT9611UXC=m +CONFIG_DRM_ITE_IT66121=m +CONFIG_DRM_NWL_MIPI_DSI=m +CONFIG_DRM_NXP_PTN3460=m +CONFIG_DRM_PARADE_PS8622=m +CONFIG_DRM_PARADE_PS8640=m +CONFIG_DRM_SAMSUNG_DSIM=m +CONFIG_DRM_SII902X=m +CONFIG_DRM_SII9234=m +CONFIG_DRM_SIMPLE_BRIDGE=m +CONFIG_DRM_SOLOMON_SSD2825=m +CONFIG_DRM_TOSHIBA_TC358762=m +CONFIG_DRM_TOSHIBA_TC358764=m +CONFIG_DRM_TOSHIBA_TC358767=m +CONFIG_DRM_TOSHIBA_TC358768=m +CONFIG_DRM_TOSHIBA_TC358775=m +CONFIG_DRM_TI_DLPC3433=m +CONFIG_DRM_TI_TFP410=m +CONFIG_DRM_TI_SN65DSI83=m +CONFIG_DRM_TI_SN65DSI86=m +CONFIG_DRM_TI_TPD12S015=m +CONFIG_DRM_WAVESHARE_BRIDGE=m +CONFIG_DRM_ANALOGIX_ANX6345=m +CONFIG_DRM_ANALOGIX_ANX78XX=m +CONFIG_DRM_ANALOGIX_ANX7625=m +CONFIG_DRM_I2C_ADV7511=m +CONFIG_DRM_I2C_ADV7511_AUDIO=y +CONFIG_DRM_CDNS_DSI=m +CONFIG_DRM_CDNS_MHDP8546=m +CONFIG_DRM_IMX8MP_DW_HDMI_BRIDGE=m +CONFIG_DRM_IMX8QM_LDB=m +CONFIG_DRM_IMX8QXP_LDB=m +CONFIG_DRM_IMX8QXP_PIXEL_COMBINER=m +CONFIG_DRM_IMX8QXP_PIXEL_LINK=m +CONFIG_DRM_IMX8QXP_PIXEL_LINK_TO_DPI=m +CONFIG_DRM_IMX93_MIPI_DSI=m +CONFIG_DRM_DW_HDMI_AHB_AUDIO=m +CONFIG_DRM_DW_HDMI_GP_AUDIO=m +CONFIG_DRM_DW_HDMI_CEC=m +CONFIG_DRM_DW_HDMI_QP_CEC=y +CONFIG_DRM_ETNAVIV=m +CONFIG_DRM_GUD=m +CONFIG_DRM_HISI_KIRIN=m +CONFIG_DRM_HYPERV=m +CONFIG_DRM_POWERVR=m +CONFIG_DRM_IMX8_DC=m +CONFIG_DRM_IMX_DCSS=m +CONFIG_DRM_IMX_LCDC=m +CONFIG_DRM_LIMA=m +CONFIG_DRM_MESON=m +CONFIG_DRM_MGAG200=m +CONFIG_DRM_MSM=m +# CONFIG_DRM_MSM_MDP4 is not set +# CONFIG_DRM_MSM_DSI_28NM_8960_PHY is not set +CONFIG_DRM_IMX_LCDIF=m +CONFIG_DRM_NOUVEAU=m +CONFIG_DRM_PANEL_ARM_VERSATILE=m +CONFIG_DRM_PANEL_BOE_BF060Y8M_AJ0=m +CONFIG_DRM_PANEL_BOE_TD4320=m +CONFIG_DRM_PANEL_BOE_TH101MB31UIG002_28A=m +CONFIG_DRM_PANEL_BOE_TV101WUM_NL6=m +CONFIG_DRM_PANEL_BOE_TV101WUM_LL2=m +CONFIG_DRM_PANEL_ELIDA_KD35T133=m +CONFIG_DRM_PANEL_FEIXIN_K101_IM2BA02=m +CONFIG_DRM_PANEL_FEIYANG_FY07024DI26A30D=m +CONFIG_DRM_PANEL_DSI_CM=m +CONFIG_DRM_PANEL_HIMAX_HX8279=m +CONFIG_DRM_PANEL_HIMAX_HX83102=m +CONFIG_DRM_PANEL_HIMAX_HX83112B=m +CONFIG_DRM_PANEL_HIMAX_HX8394=m +CONFIG_DRM_PANEL_HYDIS_HV101HD1=m +CONFIG_DRM_PANEL_ILITEK_IL9322=m +CONFIG_DRM_PANEL_ILITEK_ILI9341=m +CONFIG_DRM_PANEL_ILITEK_ILI9881C=m +CONFIG_DRM_PANEL_ILITEK_ILI9882T=m +CONFIG_DRM_PANEL_INNOLUX_EJ030NA=m +CONFIG_DRM_PANEL_JADARD_JD9365DA_H3=m +CONFIG_DRM_PANEL_JDI_LPM102A188A=m +CONFIG_DRM_PANEL_JDI_R63452=m +CONFIG_DRM_PANEL_KHADAS_TS050=m +CONFIG_DRM_PANEL_KINGDISPLAY_KD097D04=m +CONFIG_DRM_PANEL_LINCOLNTECH_LCD197=m +CONFIG_DRM_PANEL_LG_LD070WX3=m +CONFIG_DRM_PANEL_LG_LG4573=m +CONFIG_DRM_PANEL_MAGNACHIP_D53E6EA8966=m +CONFIG_DRM_PANEL_MANTIX_MLAF057WE51=m +CONFIG_DRM_PANEL_NEWVISION_NV3051D=m +CONFIG_DRM_PANEL_NOVATEK_NT35510=m +CONFIG_DRM_PANEL_NOVATEK_NT35560=m +CONFIG_DRM_PANEL_NOVATEK_NT35950=m +CONFIG_DRM_PANEL_NOVATEK_NT37801=m +CONFIG_DRM_PANEL_OLIMEX_LCD_OLINUXINO=m +CONFIG_DRM_PANEL_ORISETECH_OTM8009A=m +CONFIG_DRM_PANEL_PANASONIC_VVX10F034N00=m +CONFIG_DRM_PANEL_RASPBERRYPI_TOUCHSCREEN=m +CONFIG_DRM_PANEL_RAYDIUM_RM67200=m +CONFIG_DRM_PANEL_RAYDIUM_RM68200=m +CONFIG_DRM_PANEL_RAYDIUM_RM692E5=m +CONFIG_DRM_PANEL_RAYDIUM_RM69380=m +CONFIG_DRM_PANEL_RENESAS_R61307=m +CONFIG_DRM_PANEL_RENESAS_R69328=m +CONFIG_DRM_PANEL_RONBO_RB070D30=m +CONFIG_DRM_PANEL_SAMSUNG_AMS581VF01=m +CONFIG_DRM_PANEL_SAMSUNG_AMS639RQ08=m +CONFIG_DRM_PANEL_SAMSUNG_S6E88A0_AMS427AP24=m +CONFIG_DRM_PANEL_SAMSUNG_S6E88A0_AMS452EF01=m +CONFIG_DRM_PANEL_SAMSUNG_ATNA33XC20=m +CONFIG_DRM_PANEL_SAMSUNG_DB7430=m +CONFIG_DRM_PANEL_SAMSUNG_LD9040=m +CONFIG_DRM_PANEL_SAMSUNG_LTL106HL02=m +CONFIG_DRM_PANEL_SAMSUNG_S6E3FC2X01=m +CONFIG_DRM_PANEL_SAMSUNG_S6E3HA2=m +CONFIG_DRM_PANEL_SAMSUNG_S6E3HA8=m +CONFIG_DRM_PANEL_SAMSUNG_S6E63J0X03=m +CONFIG_DRM_PANEL_SAMSUNG_S6E8AA0=m +CONFIG_DRM_PANEL_SAMSUNG_S6E8AA5X01_AMS561RA01=m +CONFIG_DRM_PANEL_SAMSUNG_SOFEF00=m +CONFIG_DRM_PANEL_SEIKO_43WVF1G=m +CONFIG_DRM_PANEL_SHARP_LQ079L1SX01=m +CONFIG_DRM_PANEL_SHARP_LQ101R1SX01=m +CONFIG_DRM_PANEL_SHARP_LS043T1LE01=m +CONFIG_DRM_PANEL_SITRONIX_ST7701=m +CONFIG_DRM_PANEL_SITRONIX_ST7703=m +CONFIG_DRM_PANEL_SITRONIX_ST7789V=m +CONFIG_DRM_PANEL_SONY_TULIP_TRULY_NT35521=m +CONFIG_DRM_PANEL_STARTEK_KD070FHFID015=m +CONFIG_DRM_PANEL_EDP=m +CONFIG_DRM_PANEL_SIMPLE=m +CONFIG_DRM_PANEL_SUMMIT=m +CONFIG_DRM_PANEL_SYNAPTICS_TDDI=m +CONFIG_DRM_PANEL_TPO_TPG110=m +CONFIG_DRM_PANEL_TRULY_NT35597_WQXGA=m +CONFIG_DRM_PANEL_VISIONOX_G2647FB105=m +CONFIG_DRM_PANEL_VISIONOX_R66451=m +CONFIG_DRM_PANEL_VISIONOX_RM69299=m +CONFIG_DRM_PANEL_VISIONOX_RM692E5=m +CONFIG_DRM_PANEL_VISIONOX_VTDR6130=m +CONFIG_DRM_PANEL_WIDECHIPS_WS2401=m +CONFIG_DRM_PANFROST=m +CONFIG_DRM_PANTHOR=m +CONFIG_DRM_PL111=m +CONFIG_DRM_QXL=m +CONFIG_DRM_RADEON=m +CONFIG_DRM_RADEON_USERPTR=y +CONFIG_DRM_RZG2L_DU=m +CONFIG_DRM_ROCKCHIP=m +CONFIG_ROCKCHIP_VOP2=y +CONFIG_ROCKCHIP_ANALOGIX_DP=y +CONFIG_ROCKCHIP_CDN_DP=y +CONFIG_ROCKCHIP_DW_DP=y +CONFIG_ROCKCHIP_DW_HDMI=y +CONFIG_ROCKCHIP_DW_HDMI_QP=y +CONFIG_ROCKCHIP_DW_MIPI_DSI=y +CONFIG_ROCKCHIP_DW_MIPI_DSI2=y +CONFIG_ROCKCHIP_INNO_HDMI=y +CONFIG_ROCKCHIP_LVDS=y +CONFIG_ROCKCHIP_RGB=y +CONFIG_ROCKCHIP_RK3066_HDMI=y +CONFIG_DRM_ST7571=m +CONFIG_DRM_ST7571_I2C=m +CONFIG_DRM_ST7571_SPI=m +CONFIG_DRM_ST7586=m +CONFIG_DRM_ST7735R=m +CONFIG_DRM_ST7920=m +CONFIG_DRM_SSD130X=m +CONFIG_DRM_SSD130X_I2C=m +CONFIG_DRM_SSD130X_SPI=m +CONFIG_DRM_SUN4I=m +CONFIG_DRM_SIMPLEDRM=y +CONFIG_DRM_TEGRA=m +CONFIG_DRM_TEGRA_STAGING=y +CONFIG_DRM_TIDSS=m +CONFIG_DRM_BOCHS=m +CONFIG_DRM_CIRRUS_QEMU=m +CONFIG_DRM_GM12U320=m +CONFIG_DRM_PANEL_MIPI_DBI=m +CONFIG_DRM_PIXPAPER=m +CONFIG_TINYDRM_HX8357D=m +CONFIG_TINYDRM_ILI9163=m +CONFIG_TINYDRM_ILI9225=m +CONFIG_TINYDRM_ILI9341=m +CONFIG_TINYDRM_ILI9486=m +CONFIG_TINYDRM_MI0283QT=m +CONFIG_TINYDRM_REPAPER=m +CONFIG_TINYDRM_SHARP_MEMORY=m +CONFIG_DRM_UDL=m +CONFIG_DRM_V3D=m +CONFIG_DRM_VC4=m +CONFIG_DRM_VC4_HDMI_CEC=y +# CONFIG_DRM_VC4_KUNIT_TEST is not set +CONFIG_DRM_VGEM=m +CONFIG_DRM_VIRTIO_GPU=m +CONFIG_DRM_VKMS=m +CONFIG_DRM_VMWGFX=m +CONFIG_DRM_ZYNQMP_DPSUB=m +CONFIG_DRM_ZYNQMP_DPSUB_AUDIO=y +CONFIG_FB=y +CONFIG_FB_EFI=y +# CONFIG_FB_DEVICE is not set +CONFIG_FB_TILEBLITTING=y +CONFIG_LCD_CLASS_DEVICE=m +CONFIG_LCD_PLATFORM=m +CONFIG_BACKLIGHT_CLASS_DEVICE=y +CONFIG_BACKLIGHT_AW99706=m +CONFIG_BACKLIGHT_KTD253=m +CONFIG_BACKLIGHT_KTZ8866=m +CONFIG_BACKLIGHT_PWM=m +CONFIG_BACKLIGHT_APPLE_DWI=m +CONFIG_BACKLIGHT_QCOM_WLED=m +CONFIG_BACKLIGHT_RT4831=m +CONFIG_BACKLIGHT_LM3509=m +CONFIG_BACKLIGHT_LM3630A=m +CONFIG_BACKLIGHT_LP855X=m +CONFIG_BACKLIGHT_MP3309C=m +CONFIG_BACKLIGHT_GPIO=m +CONFIG_BACKLIGHT_ARCXCNN=m +CONFIG_BACKLIGHT_LED=m +CONFIG_FRAMEBUFFER_CONSOLE_ROTATION=y +CONFIG_FRAMEBUFFER_CONSOLE_DEFERRED_TAKEOVER=y +CONFIG_LOGO=y +CONFIG_LOGO_LINUX_CLUT224_FILE="drivers/video/logo/logo_linux_clut224.ppm" +CONFIG_DRM_ACCEL=y +CONFIG_DRM_ACCEL_ANE=m +CONFIG_DRM_ACCEL_ARM_ETHOSU=m +CONFIG_DRM_ACCEL_QAIC=m +CONFIG_DRM_ACCEL_ROCKET=m +CONFIG_SOUND=m +CONFIG_SND=m +CONFIG_SND_HRTIMER=m +CONFIG_SND_UTIMER=y +CONFIG_SND_SEQUENCER=m +CONFIG_SND_SEQ_DUMMY=m +CONFIG_SND_DUMMY=m +CONFIG_SND_ALOOP=m +CONFIG_SND_PCMTEST=m +CONFIG_SND_VIRMIDI=m +CONFIG_SND_MTPAV=m +CONFIG_SND_SERIAL_U16550=m +CONFIG_SND_SERIAL_GENERIC=m +CONFIG_SND_MPU401=m +CONFIG_SND_AC97_POWER_SAVE=y +CONFIG_SND_ALS300=m +CONFIG_SND_AU8810=m +CONFIG_SND_AU8820=m +CONFIG_SND_AU8830=m +CONFIG_SND_AZT3328=m +CONFIG_SND_BT87X=m +CONFIG_SND_CA0106=m +CONFIG_SND_CMIPCI=m +CONFIG_SND_OXYGEN=m +CONFIG_SND_CS4281=m +CONFIG_SND_CS46XX=m +CONFIG_SND_CTXFI=m +CONFIG_SND_DARLA20=m +CONFIG_SND_GINA20=m +CONFIG_SND_LAYLA20=m +CONFIG_SND_DARLA24=m +CONFIG_SND_GINA24=m +CONFIG_SND_LAYLA24=m +CONFIG_SND_MONA=m +CONFIG_SND_MIA=m +CONFIG_SND_ECHO3G=m +CONFIG_SND_INDIGO=m +CONFIG_SND_INDIGOIO=m +CONFIG_SND_INDIGODJ=m +CONFIG_SND_INDIGOIOX=m +CONFIG_SND_INDIGODJX=m +CONFIG_SND_EMU10K1=m +CONFIG_SND_EMU10K1X=m +CONFIG_SND_ENS1370=m +CONFIG_SND_ENS1371=m +CONFIG_SND_ES1938=m +CONFIG_SND_ES1968=m +CONFIG_SND_ES1968_INPUT=y +CONFIG_SND_ES1968_RADIO=y +CONFIG_SND_FM801=m +CONFIG_SND_FM801_TEA575X_BOOL=y +CONFIG_SND_HDSP=m +CONFIG_SND_HDSPM=m +CONFIG_SND_ICE1712=m +CONFIG_SND_ICE1724=m +CONFIG_SND_KORG1212=m +CONFIG_SND_LOLA=m +CONFIG_SND_LX6464ES=m +CONFIG_SND_MAESTRO3=m +CONFIG_SND_MAESTRO3_INPUT=y +CONFIG_SND_MIXART=m +CONFIG_SND_NM256=m +CONFIG_SND_PCXHR=m +CONFIG_SND_RIPTIDE=m +CONFIG_SND_RME32=m +CONFIG_SND_RME96=m +CONFIG_SND_RME9652=m +CONFIG_SND_SONICVIBES=m +CONFIG_SND_TRIDENT=m +CONFIG_SND_VIRTUOSO=m +CONFIG_SND_VX222=m +CONFIG_SND_YMFPCI=m +CONFIG_SND_HDA_HWDEP=y +CONFIG_SND_HDA_INPUT_BEEP=y +CONFIG_SND_HDA_INPUT_BEEP_MODE=0 +CONFIG_SND_HDA_PATCH_LOADER=y +CONFIG_SND_HDA_POWER_SAVE_DEFAULT=1 +CONFIG_SND_HDA_PREALLOC_SIZE=2048 +CONFIG_SND_HDA_INTEL=m +CONFIG_SND_HDA_TEGRA=m +CONFIG_SND_HDA_CIX_IPBLOQ=m +CONFIG_SND_HDA_ACPI=m +CONFIG_SND_HDA_CODEC_ANALOG=m +CONFIG_SND_HDA_CODEC_SIGMATEL=m +CONFIG_SND_HDA_CODEC_VIA=m +CONFIG_SND_HDA_CODEC_CONEXANT=m +CONFIG_SND_HDA_CODEC_SENARYTECH=m +CONFIG_SND_HDA_CODEC_CA0110=m +CONFIG_SND_HDA_CODEC_CA0132=m +CONFIG_SND_HDA_CODEC_CMEDIA=m +CONFIG_SND_HDA_CODEC_CM9825=m +CONFIG_SND_HDA_CODEC_SI3054=m +CONFIG_SND_HDA_CODEC_REALTEK=m +CONFIG_SND_HDA_CODEC_CIRRUS=m +CONFIG_SND_HDA_CODEC_CS8409=m +CONFIG_SND_HDA_CODEC_HDMI=m +CONFIG_SND_HDA_INTEL_HDMI_SILENT_STREAM=y +CONFIG_SND_HDA_SCODEC_CS35L41_I2C=m +CONFIG_SND_HDA_SCODEC_CS35L41_SPI=m +CONFIG_SND_HDA_SCODEC_TAS2781_I2C=m +CONFIG_SND_HDA_SCODEC_TAS2781_SPI=m +# CONFIG_SND_SPI is not set +CONFIG_SND_USB_AUDIO=m +CONFIG_SND_USB_AUDIO_MIDI_V2=y +CONFIG_SND_USB_UA101=m +CONFIG_SND_USB_CAIAQ=m +CONFIG_SND_USB_CAIAQ_INPUT=y +CONFIG_SND_USB_6FIRE=m +CONFIG_SND_USB_HIFACE=m +CONFIG_SND_BCD2000=m +CONFIG_SND_USB_AUDIO_QMI=m +CONFIG_SND_USB_POD=m +CONFIG_SND_USB_PODHD=m +CONFIG_SND_USB_TONEPORT=m +CONFIG_SND_USB_VARIAX=m +CONFIG_SND_SOC=m +CONFIG_SND_SOC_USB=m +CONFIG_SND_SOC_ADI_AXI_I2S=m +CONFIG_SND_SOC_ADI_AXI_SPDIF=m +CONFIG_SND_SOC_APPLE_AOP_AUDIO=m +CONFIG_SND_SOC_APPLE_T8152_AOP_AUDIO=m +CONFIG_SND_SOC_APPLE_MACAUDIO=m +CONFIG_SND_SOC_MIKROE_PROTO=m +CONFIG_SND_BCM2835_SOC_I2S=m +CONFIG_SND_DESIGNWARE_I2S=m +CONFIG_SND_DESIGNWARE_PCM=y +CONFIG_SND_SOC_FSL_ASRC=m +CONFIG_SND_SOC_FSL_MQS=m +CONFIG_SND_SOC_FSL_MICFIL=m +CONFIG_SND_SOC_FSL_EASRC=m +CONFIG_SND_SOC_FSL_XCVR=m +CONFIG_SND_SOC_FSL_RPMSG=m +CONFIG_SND_IMX_SOC=m +CONFIG_SND_SOC_IMX_ES8328=m +CONFIG_SND_SOC_IMX_SGTL5000=m +CONFIG_SND_SOC_FSL_ASOC_CARD=m +CONFIG_SND_SOC_IMX_AUDMIX=m +CONFIG_SND_SOC_IMX_HDMI=m +CONFIG_SND_SOC_IMX_CARD=m +CONFIG_SND_SOC_CHV3_I2S=m +CONFIG_SND_I2S_HI6210_I2S=m +CONFIG_SND_MESON_AXG_SOUND_CARD=m +CONFIG_SND_MESON_GX_SOUND_CARD=m +CONFIG_SND_SOC_QCOM=m +CONFIG_SND_SOC_APQ8016_SBC=m +CONFIG_SND_SOC_QDSP6_USB=m +CONFIG_SND_SOC_MSM8996=m +CONFIG_SND_SOC_SDM845=m +CONFIG_SND_SOC_SC8280XP=m +CONFIG_SND_SOC_SC7180=m +CONFIG_SND_SOC_SC7280=m +CONFIG_SND_SOC_X1E80100=m +CONFIG_SND_SOC_MSIOF=m +CONFIG_SND_SOC_RZ=m +CONFIG_SND_SOC_ROCKCHIP_I2S_TDM=m +CONFIG_SND_SOC_ROCKCHIP_PDM=m +CONFIG_SND_SOC_ROCKCHIP_SAI=m +CONFIG_SND_SOC_ROCKCHIP_SPDIF=m +CONFIG_SND_SOC_ROCKCHIP_MAX98090=m +CONFIG_SND_SOC_ROCKCHIP_RT5645=m +CONFIG_SND_SOC_RK3288_HDMI_ANALOG=m +CONFIG_SND_SOC_RK3399_GRU_SOUND=m +CONFIG_SND_SUN4I_CODEC=m +CONFIG_SND_SUN8I_CODEC=m +CONFIG_SND_SUN8I_CODEC_ANALOG=m +CONFIG_SND_SUN50I_CODEC_ANALOG=m +CONFIG_SND_SUN4I_I2S=m +CONFIG_SND_SUN4I_SPDIF=m +CONFIG_SND_SUN50I_DMIC=m +CONFIG_SND_SOC_TEGRA=m +CONFIG_SND_SOC_TEGRA20_AC97=m +CONFIG_SND_SOC_TEGRA20_I2S=m +CONFIG_SND_SOC_TEGRA20_SPDIF=m +CONFIG_SND_SOC_TEGRA30_I2S=m +CONFIG_SND_SOC_TEGRA210_AHUB=m +CONFIG_SND_SOC_TEGRA210_DMIC=m +CONFIG_SND_SOC_TEGRA210_I2S=m +CONFIG_SND_SOC_TEGRA210_OPE=m +CONFIG_SND_SOC_TEGRA186_ASRC=m +CONFIG_SND_SOC_TEGRA186_DSPK=m +CONFIG_SND_SOC_TEGRA210_ADMAIF=m +CONFIG_SND_SOC_TEGRA210_MVC=m +CONFIG_SND_SOC_TEGRA210_SFC=m +CONFIG_SND_SOC_TEGRA210_AMX=m +CONFIG_SND_SOC_TEGRA210_ADX=m +CONFIG_SND_SOC_TEGRA210_MIXER=m +CONFIG_SND_SOC_TEGRA_AUDIO_GRAPH_CARD=m +CONFIG_SND_SOC_TEGRA_RT5631=m +CONFIG_SND_SOC_TEGRA_RT5640=m +CONFIG_SND_SOC_TEGRA_MAX98090=m +CONFIG_SND_SOC_TEGRA_MAX98088=m +CONFIG_SND_SOC_TEGRA_RT5677=m +CONFIG_SND_SOC_TEGRA_SGTL5000=m +CONFIG_SND_SOC_J721E_EVM=m +CONFIG_SND_SOC_XILINX_I2S=m +CONFIG_SND_SOC_XILINX_AUDIO_FORMATTER=m +CONFIG_SND_SOC_XILINX_SPDIF=m +CONFIG_SND_SOC_SOF_TOPLEVEL=y +CONFIG_SND_SOC_SOF_PCI=m +CONFIG_SND_SOC_SOF_ACPI=m +CONFIG_SND_SOC_SOF_OF=m +CONFIG_SND_SOC_SOF_IMX_TOPLEVEL=y +CONFIG_SND_SOC_SOF_IMX8=m +CONFIG_SND_SOC_SOF_IMX9=m +CONFIG_SND_SOC_SOF_MTK_TOPLEVEL=y +CONFIG_SND_SOC_AC97_CODEC=m +CONFIG_SND_SOC_ADAU1372_I2C=m +CONFIG_SND_SOC_ADAU1372_SPI=m +CONFIG_SND_SOC_ADAU1373=m +CONFIG_SND_SOC_ADAU1761_I2C=m +CONFIG_SND_SOC_ADAU1761_SPI=m +CONFIG_SND_SOC_ADAU7118_HW=m +CONFIG_SND_SOC_ADAU7118_I2C=m +CONFIG_SND_SOC_AK4619=m +CONFIG_SND_SOC_AUDIO_IIO_AUX=m +CONFIG_SND_SOC_AW8738=m +CONFIG_SND_SOC_AW88395=m +CONFIG_SND_SOC_AW88166=m +CONFIG_SND_SOC_AW88261=m +CONFIG_SND_SOC_AW88081=m +CONFIG_SND_SOC_AW87390=m +CONFIG_SND_SOC_AW88399=m +CONFIG_SND_SOC_BD28623=m +CONFIG_SND_SOC_BT_SCO=m +CONFIG_SND_SOC_CHV3_CODEC=m +CONFIG_SND_SOC_CS35L56_SDW=m +CONFIG_SND_SOC_CS40L50=m +CONFIG_SND_SOC_CS42L42=m +CONFIG_SND_SOC_CS42L42_SDW=m +CONFIG_SND_SOC_CS42L43=m +CONFIG_SND_SOC_CS42L43_SDW=m +CONFIG_SND_SOC_CS4234=m +CONFIG_SND_SOC_CS4265=m +CONFIG_SND_SOC_CS4271_I2C=m +CONFIG_SND_SOC_CS42XX8_I2C=m +CONFIG_SND_SOC_CS43130=m +CONFIG_SND_SOC_CS48L32=m +CONFIG_SND_SOC_CS530X_I2C=m +CONFIG_SND_SOC_CX2072X=m +CONFIG_SND_SOC_DA7213=m +CONFIG_SND_SOC_ES7134=m +CONFIG_SND_SOC_ES8311=m +CONFIG_SND_SOC_ES8316=m +CONFIG_SND_SOC_ES8323=m +CONFIG_SND_SOC_ES8326=m +CONFIG_SND_SOC_ES8375=m +CONFIG_SND_SOC_ES8389=m +CONFIG_SND_SOC_HDA=m +CONFIG_SND_SOC_ICS43432=m +CONFIG_SND_SOC_IDT821034=m +CONFIG_SND_SOC_MAX9867=m +CONFIG_SND_SOC_MAX98520=m +CONFIG_SND_SOC_MAX98363=m +CONFIG_SND_SOC_MAX98373_I2C=m +CONFIG_SND_SOC_MAX98373_SDW=m +CONFIG_SND_SOC_MAX98390=m +CONFIG_SND_SOC_MAX98396=m +CONFIG_SND_SOC_MSM8916_WCD_ANALOG=m +CONFIG_SND_SOC_MSM8916_WCD_DIGITAL=m +CONFIG_SND_SOC_PCM1754=m +CONFIG_SND_SOC_PCM1789_I2C=m +CONFIG_SND_SOC_PCM186X_I2C=m +CONFIG_SND_SOC_PCM186X_SPI=m +CONFIG_SND_SOC_PCM3060_I2C=m +CONFIG_SND_SOC_PCM3060_SPI=m +CONFIG_SND_SOC_PCM5102A=m +CONFIG_SND_SOC_PCM512x_I2C=m +CONFIG_SND_SOC_PCM512x_SPI=m +CONFIG_SND_SOC_PCM6240=m +CONFIG_SND_SOC_PM4125_SDW=m +CONFIG_SND_SOC_RK3308=m +CONFIG_SND_SOC_RK3328=m +CONFIG_SND_SOC_RK817=m +CONFIG_SND_SOC_RT1017_SDCA_SDW=m +CONFIG_SND_SOC_RT1318_SDW=m +CONFIG_SND_SOC_RT1320_SDW=m +CONFIG_SND_SOC_RT5575=m +CONFIG_SND_SOC_RT5575_SPI=y +CONFIG_SND_SOC_RT5616=m +CONFIG_SND_SOC_RT5659=m +CONFIG_SND_SOC_RT5682_SDW=m +CONFIG_SND_SOC_RT700_SDW=m +CONFIG_SND_SOC_RT711_SDW=m +CONFIG_SND_SOC_RT711_SDCA_SDW=m +CONFIG_SND_SOC_RT712_SDCA_DMIC_SDW=m +CONFIG_SND_SOC_RT722_SDCA_SDW=m +CONFIG_SND_SOC_RT715_SDW=m +CONFIG_SND_SOC_RT715_SDCA_SDW=m +CONFIG_SND_SOC_RT9123=m +CONFIG_SND_SOC_RT9123P=m +CONFIG_SND_SOC_RTQ9124=m +CONFIG_SND_SOC_RTQ9128=m +CONFIG_SND_SOC_SIMPLE_AMPLIFIER=m +CONFIG_SND_SOC_SIMPLE_MUX=m +CONFIG_SND_SOC_SMA1303=m +CONFIG_SND_SOC_SMA1307=m +CONFIG_SND_SOC_SSM3515=m +CONFIG_SND_SOC_TAS2562=m +CONFIG_SND_SOC_TAS2780=m +CONFIG_SND_SOC_TAS2781_I2C=m +CONFIG_SND_SOC_TAS5805M=m +CONFIG_SND_SOC_TAS6424=m +CONFIG_SND_SOC_TDA7419=m +CONFIG_SND_SOC_TFA989X=m +CONFIG_SND_SOC_TLV320ADC3XXX=m +CONFIG_SND_SOC_TLV320AIC23_I2C=m +CONFIG_SND_SOC_TLV320AIC23_SPI=m +CONFIG_SND_SOC_TLV320AIC32X4_I2C=m +CONFIG_SND_SOC_TLV320AIC32X4_SPI=m +CONFIG_SND_SOC_TLV320AIC3X_I2C=m +CONFIG_SND_SOC_TLV320AIC3X_SPI=m +CONFIG_SND_SOC_TLV320ADCX140=m +CONFIG_SND_SOC_TSCS42XX=m +CONFIG_SND_SOC_UDA1342=m +CONFIG_SND_SOC_WCD9335=m +CONFIG_SND_SOC_WCD934X=m +CONFIG_SND_SOC_WCD937X_SDW=m +CONFIG_SND_SOC_WCD939X_SDW=m +CONFIG_SND_SOC_WM8524=m +CONFIG_SND_SOC_WM8731_I2C=m +CONFIG_SND_SOC_WM8731_SPI=m +CONFIG_SND_SOC_WM8741=m +CONFIG_SND_SOC_WM8753=m +CONFIG_SND_SOC_WM8804_I2C=m +CONFIG_SND_SOC_WM8804_SPI=m +CONFIG_SND_SOC_WM8903=m +CONFIG_SND_SOC_WM8940=m +CONFIG_SND_SOC_WM8960=m +CONFIG_SND_SOC_WM8961=m +CONFIG_SND_SOC_WM8962=m +CONFIG_SND_SOC_WSA883X=m +CONFIG_SND_SOC_WSA884X=m +CONFIG_SND_SOC_ZL38060=m +CONFIG_SND_SOC_MAX9759=m +CONFIG_SND_SOC_MT6357=m +CONFIG_SND_SOC_NAU8824=m +CONFIG_SND_SOC_NTP8918=m +CONFIG_SND_SOC_NTP8835=m +CONFIG_SND_SOC_TPA6130A2=m +CONFIG_SND_SOC_LPASS_WSA_MACRO=m +CONFIG_SND_SOC_LPASS_VA_MACRO=m +CONFIG_SND_AUDIO_GRAPH_CARD2=m +CONFIG_SND_AUDIO_GRAPH_CARD2_CUSTOM_SAMPLE=m +CONFIG_SND_VIRTIO=m +CONFIG_HID_BATTERY_STRENGTH=y +CONFIG_HIDRAW=y +CONFIG_UHID=m +CONFIG_HID_HAPTIC=y +CONFIG_HID_A4TECH=m +CONFIG_HID_ACCUTOUCH=m +CONFIG_HID_ACRUX=m +CONFIG_HID_ACRUX_FF=y +CONFIG_HID_APPLE=m +CONFIG_HID_APPLE_MTP_HAPTIC=m +CONFIG_HID_APPLEIR=m +CONFIG_HID_AUREAL=m +CONFIG_HID_BELKIN=m +CONFIG_HID_BETOP_FF=m +CONFIG_HID_BIGBEN_FF=m +CONFIG_HID_CHERRY=m +CONFIG_HID_CHICONY=m +CONFIG_HID_CORSAIR=m +CONFIG_HID_COUGAR=m +CONFIG_HID_MACALLY=m +CONFIG_HID_PRODIKEYS=m +CONFIG_HID_CMEDIA=m +CONFIG_HID_CP2112=m +CONFIG_HID_CREATIVE_SB0540=m +CONFIG_HID_CYPRESS=m +CONFIG_HID_DRAGONRISE=m +CONFIG_DRAGONRISE_FF=y +CONFIG_HID_EMS_FF=m +CONFIG_HID_ELAN=m +CONFIG_HID_ELECOM=m +CONFIG_HID_ELO=m +CONFIG_HID_EVISION=m +CONFIG_HID_EZKEY=m +CONFIG_HID_FT260=m +CONFIG_HID_GEMBIRD=m +CONFIG_HID_GFRM=m +CONFIG_HID_GLORIOUS=m +CONFIG_HID_HOLTEK=m +CONFIG_HOLTEK_FF=y +CONFIG_HID_GOODIX_SPI=m +CONFIG_HID_GOOGLE_STADIA_FF=m +CONFIG_HID_VIVALDI=m +CONFIG_HID_GT683R=m +CONFIG_HID_KEYTOUCH=m +CONFIG_HID_KYE=m +CONFIG_HID_KYSONA=m +CONFIG_HID_UCLOGIC=m +CONFIG_HID_WALTOP=m +CONFIG_HID_VIEWSONIC=m +CONFIG_HID_XIAOMI=m +CONFIG_HID_GYRATION=m +CONFIG_HID_ICADE=m +CONFIG_HID_ITE=m +CONFIG_HID_JABRA=m +CONFIG_HID_TWINHAN=m +CONFIG_HID_KENSINGTON=m +CONFIG_HID_LCPOWER=m +CONFIG_HID_LENOVO=m +CONFIG_HID_LETSKETCH=m +CONFIG_HID_LOGITECH=m +CONFIG_HID_LOGITECH_DJ=m +CONFIG_LOGITECH_FF=y +CONFIG_LOGIRUMBLEPAD2_FF=y +CONFIG_LOGIG940_FF=y +CONFIG_HID_MAGICMOUSE=m +CONFIG_HID_MALTRON=m +CONFIG_HID_MAYFLASH=m +CONFIG_HID_MEGAWORLD_FF=m +CONFIG_HID_MICROSOFT=m +CONFIG_HID_MONTEREY=m +CONFIG_HID_MULTITOUCH=m +CONFIG_HID_NINTENDO=m +CONFIG_NINTENDO_FF=y +CONFIG_HID_NTI=m +CONFIG_HID_NTRIG=y +CONFIG_HID_NVIDIA_SHIELD=m +CONFIG_NVIDIA_SHIELD_FF=y +CONFIG_HID_ORTEK=m +CONFIG_HID_PANTHERLORD=m +CONFIG_PANTHERLORD_FF=y +CONFIG_HID_PENMOUNT=m +CONFIG_HID_PETALYNX=m +CONFIG_HID_PICOLCD=m +CONFIG_HID_PICOLCD_FB=y +CONFIG_HID_PICOLCD_BACKLIGHT=y +CONFIG_HID_PICOLCD_LCD=y +CONFIG_HID_PICOLCD_LEDS=y +CONFIG_HID_PLANTRONICS=m +CONFIG_HID_PLAYSTATION=m +CONFIG_PLAYSTATION_FF=y +CONFIG_HID_PXRC=m +CONFIG_HID_RAPOO=m +CONFIG_HID_RAZER=m +CONFIG_HID_PRIMAX=m +CONFIG_HID_RETRODE=m +CONFIG_HID_ROCCAT=m +CONFIG_HID_SAITEK=m +CONFIG_HID_SAMSUNG=m +CONFIG_HID_SEMITEK=m +CONFIG_HID_SIGMAMICRO=m +CONFIG_HID_SONY=m +CONFIG_SONY_FF=y +CONFIG_HID_SPEEDLINK=m +CONFIG_HID_STEAM=m +CONFIG_STEAM_FF=y +CONFIG_HID_STEELSERIES=m +CONFIG_HID_SUNPLUS=m +CONFIG_HID_RMI=m +CONFIG_HID_GREENASIA=m +CONFIG_GREENASIA_FF=y +CONFIG_HID_HYPERV_MOUSE=m +CONFIG_HID_SMARTJOYPLUS=m +CONFIG_SMARTJOYPLUS_FF=y +CONFIG_HID_TIVO=m +CONFIG_HID_TOPSEED=m +CONFIG_HID_TOPRE=m +CONFIG_HID_THINGM=m +CONFIG_HID_THRUSTMASTER=m +CONFIG_THRUSTMASTER_FF=y +CONFIG_HID_UDRAW_PS3=m +CONFIG_HID_U2FZERO=m +CONFIG_HID_UNIVERSAL_PIDFF=m +CONFIG_HID_WACOM=m +CONFIG_HID_WIIMOTE=m +CONFIG_HID_WINWING=m +CONFIG_HID_XINMO=m +CONFIG_HID_ZEROPLUS=m +CONFIG_ZEROPLUS_FF=y +CONFIG_HID_ZYDACRON=m +CONFIG_HID_SENSOR_HUB=m +CONFIG_HID_ALPS=m +CONFIG_HID_MCP2221=m +CONFIG_HID_BPF=y +CONFIG_I2C_HID_ACPI=m +CONFIG_I2C_HID_OF=y +CONFIG_I2C_HID_OF_ELAN=m +CONFIG_I2C_HID_OF_GOODIX=m +CONFIG_SURFACE_HID=m +CONFIG_SURFACE_KBD=m +CONFIG_HID_PID=y +CONFIG_USB_HIDDEV=y +CONFIG_SPI_HID_APPLE_OF=m +CONFIG_HID_DOCKCHANNEL=m +CONFIG_USB_LED_TRIG=y +CONFIG_USB=y +CONFIG_USB_PCI_AMD=y +CONFIG_USB_ANNOUNCE_NEW_DEVICES=y +CONFIG_USB_OTG=y +CONFIG_USB_OTG_FSM=m +CONFIG_USB_LEDS_TRIGGER_USBPORT=m +CONFIG_USB_MON=y +CONFIG_USB_XHCI_HCD=y +CONFIG_USB_XHCI_DBGCAP=y +CONFIG_USB_XHCI_PCI_RENESAS=y +CONFIG_USB_XHCI_MVEBU=m +CONFIG_USB_XHCI_RZV2M=y +CONFIG_USB_XHCI_SIDEBAND=y +CONFIG_USB_XHCI_TEGRA=m +CONFIG_USB_EHCI_HCD=y +CONFIG_USB_EHCI_FSL=m +CONFIG_USB_EHCI_HCD_ORION=m +CONFIG_USB_EHCI_TEGRA=m +CONFIG_USB_EHCI_HCD_PLATFORM=m +CONFIG_USB_OHCI_HCD=m +CONFIG_USB_OHCI_HCD_PLATFORM=m +CONFIG_USB_UHCI_HCD=m +CONFIG_USB_SL811_HCD=m +CONFIG_USB_SL811_HCD_ISO=y +CONFIG_USB_PRINTER=m +CONFIG_USB_TMC=m +CONFIG_USB_STORAGE=m +CONFIG_USB_STORAGE_REALTEK=m +CONFIG_USB_STORAGE_DATAFAB=m +CONFIG_USB_STORAGE_FREECOM=m +CONFIG_USB_STORAGE_ISD200=m +CONFIG_USB_STORAGE_USBAT=m +CONFIG_USB_STORAGE_SDDR09=m +CONFIG_USB_STORAGE_SDDR55=m +CONFIG_USB_STORAGE_JUMPSHOT=m +CONFIG_USB_STORAGE_ALAUDA=m +CONFIG_USB_STORAGE_ONETOUCH=m +CONFIG_USB_STORAGE_KARMA=m +CONFIG_USB_STORAGE_CYPRESS_ATACB=m +CONFIG_USB_STORAGE_ENE_UB6250=m +CONFIG_USB_UAS=m +CONFIG_USB_MDC800=m +CONFIG_USB_MICROTEK=m +CONFIG_USBIP_CORE=m +CONFIG_USBIP_VHCI_HCD=m +CONFIG_USBIP_HOST=m +CONFIG_USBIP_VUDC=m +CONFIG_USB_CDNS_SUPPORT=m +CONFIG_USB_CDNS3=m +CONFIG_USB_CDNS3_HOST=y +CONFIG_USB_CDNS3_GADGET=y +CONFIG_USB_MUSB_HDRC=m +CONFIG_USB_MUSB_SUNXI=m +CONFIG_USB_DWC3=m +CONFIG_USB_DWC3_ULPI=y +CONFIG_USB_DWC2=m +CONFIG_USB_DWC2_PCI=m +CONFIG_USB_CHIPIDEA_UDC=y +CONFIG_USB_ISP1760=m +CONFIG_USB_SERIAL=y +CONFIG_USB_SERIAL_CONSOLE=y +CONFIG_USB_SERIAL_GENERIC=y +CONFIG_USB_SERIAL_SIMPLE=m +CONFIG_USB_SERIAL_AIRCABLE=m +CONFIG_USB_SERIAL_ARK3116=m +CONFIG_USB_SERIAL_BELKIN=m +CONFIG_USB_SERIAL_CH341=m +CONFIG_USB_SERIAL_WHITEHEAT=m +CONFIG_USB_SERIAL_DIGI_ACCELEPORT=m +CONFIG_USB_SERIAL_CP210X=m +CONFIG_USB_SERIAL_CYPRESS_M8=m +CONFIG_USB_SERIAL_EMPEG=m +CONFIG_USB_SERIAL_FTDI_SIO=m +CONFIG_USB_SERIAL_VISOR=m +CONFIG_USB_SERIAL_IPAQ=m +CONFIG_USB_SERIAL_IR=m +CONFIG_USB_SERIAL_EDGEPORT=m +CONFIG_USB_SERIAL_EDGEPORT_TI=m +CONFIG_USB_SERIAL_F81232=m +CONFIG_USB_SERIAL_F8153X=m +CONFIG_USB_SERIAL_GARMIN=m +CONFIG_USB_SERIAL_IPW=m +CONFIG_USB_SERIAL_IUU=m +CONFIG_USB_SERIAL_KEYSPAN_PDA=m +CONFIG_USB_SERIAL_KEYSPAN=m +CONFIG_USB_SERIAL_KLSI=m +CONFIG_USB_SERIAL_KOBIL_SCT=m +CONFIG_USB_SERIAL_MCT_U232=m +CONFIG_USB_SERIAL_MOS7720=m +CONFIG_USB_SERIAL_MOS7840=m +CONFIG_USB_SERIAL_NAVMAN=m +CONFIG_USB_SERIAL_PL2303=m +CONFIG_USB_SERIAL_OTI6858=m +CONFIG_USB_SERIAL_QCAUX=m +CONFIG_USB_SERIAL_QUALCOMM=m +CONFIG_USB_SERIAL_SPCP8X5=m +CONFIG_USB_SERIAL_SAFE=m +CONFIG_USB_SERIAL_SAFE_PADDED=y +CONFIG_USB_SERIAL_SIERRAWIRELESS=m +CONFIG_USB_SERIAL_SYMBOL=m +CONFIG_USB_SERIAL_TI=m +CONFIG_USB_SERIAL_CYBERJACK=m +CONFIG_USB_SERIAL_OPTION=m +CONFIG_USB_SERIAL_OMNINET=m +CONFIG_USB_SERIAL_OPTICON=m +CONFIG_USB_SERIAL_XSENS_MT=m +CONFIG_USB_SERIAL_SSU100=m +CONFIG_USB_SERIAL_QT2=m +CONFIG_USB_SERIAL_UPD78F0730=m +CONFIG_USB_SERIAL_XR=m +CONFIG_USB_SERIAL_DEBUG=m +CONFIG_USB_VL122_HUB=m +CONFIG_USB_EMI62=m +CONFIG_USB_EMI26=m +CONFIG_USB_ADUTUX=m +CONFIG_USB_SEVSEG=m +CONFIG_USB_LEGOTOWER=m +CONFIG_USB_LCD=m +CONFIG_USB_IDMOUSE=m +CONFIG_USB_APPLEDISPLAY=m +CONFIG_USB_QCOM_EUD=m +CONFIG_APPLE_MFI_FASTCHARGE=m +CONFIG_USB_SISUSBVGA=m +CONFIG_USB_LD=m +CONFIG_USB_TRANCEVIBRATOR=m +CONFIG_USB_IOWARRIOR=m +CONFIG_USB_ISIGHTFW=m +CONFIG_USB_YUREX=m +CONFIG_USB_HUB_USB251XB=m +CONFIG_USB_HSIC_USB3503=m +CONFIG_USB_HSIC_USB4604=m +CONFIG_USB_CHAOSKEY=m +CONFIG_USB_ONBOARD_DEV=m +CONFIG_USB_ONBOARD_DEV_USB5744=y +CONFIG_USB_ATM=m +CONFIG_USB_CXACRU=m +CONFIG_USB_UEAGLEATM=m +CONFIG_USB_XUSBATM=m +CONFIG_USB_GPIO_VBUS=m +CONFIG_USB_GADGET_VBUS_DRAW=100 +CONFIG_U_SERIAL_CONSOLE=y +CONFIG_USB_RZV2M_USB3DRD=m +CONFIG_USB_SNP_UDC_PLAT=m +CONFIG_USB_MAX3420_UDC=m +CONFIG_USB_TEGRA_XUDC=m +CONFIG_USB_CDNS2_UDC=m +CONFIG_USB_CONFIGFS=m +CONFIG_USB_CONFIGFS_SERIAL=y +CONFIG_USB_CONFIGFS_ACM=y +CONFIG_USB_CONFIGFS_NCM=y +CONFIG_USB_CONFIGFS_ECM=y +CONFIG_USB_CONFIGFS_ECM_SUBSET=y +CONFIG_USB_CONFIGFS_EEM=y +CONFIG_USB_CONFIGFS_MASS_STORAGE=y +CONFIG_USB_CONFIGFS_F_FS=y +CONFIG_USB_CONFIGFS_F_MIDI2=y +CONFIG_USB_CONFIGFS_F_HID=y +CONFIG_USB_CONFIGFS_F_TCM=y +CONFIG_TYPEC=m +CONFIG_TYPEC_TCPM=m +CONFIG_TYPEC_TCPCI=m +CONFIG_TYPEC_TCPCI_MAXIM=m +CONFIG_TYPEC_FUSB302=m +CONFIG_TYPEC_QCOM_PMIC=m +CONFIG_TYPEC_UCSI=m +CONFIG_UCSI_CCG=m +CONFIG_UCSI_ACPI=m +CONFIG_UCSI_STM32G0=m +CONFIG_UCSI_PMIC_GLINK=m +CONFIG_UCSI_LENOVO_YOGA_C630=m +CONFIG_TYPEC_TPS6598X=m +CONFIG_TYPEC_SN201202X=m +CONFIG_TYPEC_TPS6598X_DEBUG_COMMANDS=y +CONFIG_TYPEC_ANX7411=m +CONFIG_TYPEC_RT1719=m +CONFIG_TYPEC_HD3SS3220=m +CONFIG_TYPEC_STUSB160X=m +CONFIG_TYPEC_WUSB3801=m +CONFIG_TYPEC_MUX_FSA4480=m +CONFIG_TYPEC_MUX_GPIO_SBU=m +CONFIG_TYPEC_MUX_PI3USB30532=m +CONFIG_TYPEC_MUX_IT5205=m +CONFIG_TYPEC_MUX_NB7VPQ904M=m +CONFIG_TYPEC_MUX_PS883X=m +CONFIG_TYPEC_MUX_PTN36502=m +CONFIG_TYPEC_MUX_TUSB1046=m +CONFIG_TYPEC_DP_ALTMODE=m +CONFIG_TYPEC_NVIDIA_ALTMODE=m +CONFIG_TYPEC_TBT_ALTMODE=m +CONFIG_USB_ROLE_SWITCH=y +CONFIG_MMC=m +CONFIG_PWRSEQ_SD8787=m +CONFIG_SDIO_UART=m +CONFIG_MMC_ARMMMCI=m +# CONFIG_MMC_STM32_SDMMC is not set +CONFIG_MMC_SDHCI=m +CONFIG_MMC_SDHCI_PCI=m +CONFIG_MMC_SDHCI_ACPI=m +CONFIG_MMC_SDHCI_PLTFM=m +CONFIG_MMC_SDHCI_OF_ARASAN=m +CONFIG_MMC_SDHCI_OF_ESDHC=m +CONFIG_MMC_SDHCI_OF_DWCMSHC=m +CONFIG_MMC_SDHCI_CADENCE=m +CONFIG_MMC_SDHCI_ESDHC_IMX=m +CONFIG_MMC_SDHCI_TEGRA=m +CONFIG_MMC_SDHCI_PXAV3=m +CONFIG_MMC_SDHCI_F_SDH30=m +CONFIG_MMC_SDHCI_IPROC=m +CONFIG_MMC_MESON_GX=m +CONFIG_MMC_MESON_MX_SDIO=m +CONFIG_MMC_ALCOR=m +CONFIG_MMC_SDHCI_MSM=m +CONFIG_MMC_TIFM_SD=m +CONFIG_MMC_SPI=m +CONFIG_MMC_SDHI=m +CONFIG_MMC_CB710=m +CONFIG_MMC_VIA_SDMMC=m +CONFIG_MMC_CAVIUM_THUNDERX=m +CONFIG_MMC_DW=m +CONFIG_MMC_DW_BLUEFIELD=m +CONFIG_MMC_DW_EXYNOS=m +CONFIG_MMC_DW_HI3798CV200=m +CONFIG_MMC_DW_HI3798MV200=m +CONFIG_MMC_DW_K3=m +CONFIG_MMC_DW_PCI=m +CONFIG_MMC_DW_ROCKCHIP=m +CONFIG_MMC_VUB300=m +CONFIG_MMC_USHC=m +CONFIG_MMC_REALTEK_PCI=m +CONFIG_MMC_REALTEK_USB=m +CONFIG_MMC_SUNXI=m +CONFIG_MMC_HSQ=m +CONFIG_MMC_BCM2835=m +CONFIG_MMC_SDHCI_BRCMSTB=m +CONFIG_MMC_SDHCI_XENON=m +CONFIG_MMC_SDHCI_AM654=m +CONFIG_SCSI_UFSHCD=m +CONFIG_SCSI_UFS_BSG=y +CONFIG_SCSI_UFS_CRYPTO=y +CONFIG_SCSI_UFS_HWMON=y +CONFIG_SCSI_UFSHCD_PCI=m +CONFIG_SCSI_UFSHCD_PLATFORM=m +CONFIG_SCSI_UFS_CDNS_PLATFORM=m +CONFIG_SCSI_UFS_QCOM=m +CONFIG_SCSI_UFS_HISI=m +CONFIG_SCSI_UFS_TI_J721E=m +CONFIG_SCSI_UFS_ROCKCHIP=m +CONFIG_SCSI_UFS_AMD_VERSAL2=m +CONFIG_MEMSTICK=m +CONFIG_MSPRO_BLOCK=m +CONFIG_MEMSTICK_TIFM_MS=m +CONFIG_MEMSTICK_JMICRON_38X=m +CONFIG_MEMSTICK_R592=m +CONFIG_MEMSTICK_REALTEK_USB=m +CONFIG_LEDS_CLASS=y +CONFIG_LEDS_CLASS_FLASH=m +CONFIG_LEDS_BRIGHTNESS_HW_CHANGED=y +CONFIG_LEDS_AN30259A=m +CONFIG_LEDS_OSRAM_AMS_AS3668=m +CONFIG_LEDS_AW200XX=m +CONFIG_LEDS_CR0014114=m +CONFIG_LEDS_LM3530=m +CONFIG_LEDS_LM3532=m +CONFIG_LEDS_LM3692X=m +CONFIG_LEDS_PCA9532=m +CONFIG_LEDS_PCA9532_GPIO=y +CONFIG_LEDS_GPIO=m +CONFIG_LEDS_LP3944=m +CONFIG_LEDS_LP3952=m +CONFIG_LEDS_LP50XX=m +CONFIG_LEDS_LP8864=m +CONFIG_LEDS_PCA963X=m +CONFIG_LEDS_PCA995X=m +CONFIG_LEDS_QNAP_MCU=m +CONFIG_LEDS_PWM=m +CONFIG_LEDS_REGULATOR=m +CONFIG_LEDS_LT3593=m +CONFIG_LEDS_MAX5970=m +CONFIG_LEDS_TLC591XX=m +CONFIG_LEDS_MAX77650=m +CONFIG_LEDS_MAX77705=m +CONFIG_LEDS_IS31FL32XX=m +CONFIG_LEDS_BLINKM=m +CONFIG_LEDS_BLINKM_MULTICOLOR=y +CONFIG_LEDS_SYSCON=y +CONFIG_LEDS_MLXREG=m +CONFIG_LEDS_USER=m +CONFIG_LEDS_ST1202=m +CONFIG_LEDS_AS3645A=m +CONFIG_LEDS_LM3601X=m +CONFIG_LEDS_QCOM_FLASH=m +CONFIG_LEDS_SGM3140=m +CONFIG_LEDS_SY7802=m +CONFIG_LEDS_TPS6131X=m +CONFIG_LEDS_GROUP_MULTICOLOR=m +CONFIG_LEDS_KTD202X=m +CONFIG_LEDS_LP5812=m +CONFIG_LEDS_NCP5623=m +CONFIG_LEDS_PWM_MULTICOLOR=m +CONFIG_LEDS_QCOM_LPG=m +CONFIG_LEDS_TRIGGER_ONESHOT=m +CONFIG_LEDS_TRIGGER_DISK=y +CONFIG_LEDS_TRIGGER_MTD=y +CONFIG_LEDS_TRIGGER_HEARTBEAT=m +CONFIG_LEDS_TRIGGER_BACKLIGHT=m +CONFIG_LEDS_TRIGGER_CPU=y +CONFIG_LEDS_TRIGGER_ACTIVITY=m +CONFIG_LEDS_TRIGGER_GPIO=m +CONFIG_LEDS_TRIGGER_DEFAULT_ON=m +CONFIG_LEDS_TRIGGER_TRANSIENT=m +CONFIG_LEDS_TRIGGER_CAMERA=m +CONFIG_LEDS_TRIGGER_PANIC=y +CONFIG_LEDS_TRIGGER_NETDEV=m +CONFIG_LEDS_TRIGGER_TTY=m +CONFIG_LEDS_TRIGGER_INPUT_EVENTS=m +CONFIG_ACCESSIBILITY=y +CONFIG_A11Y_BRAILLE_CONSOLE=y +CONFIG_SPEAKUP=m +CONFIG_SPEAKUP_SYNTH_ACNTSA=m +CONFIG_SPEAKUP_SYNTH_APOLLO=m +CONFIG_SPEAKUP_SYNTH_AUDPTR=m +CONFIG_SPEAKUP_SYNTH_BNS=m +CONFIG_SPEAKUP_SYNTH_DECTLK=m +CONFIG_SPEAKUP_SYNTH_LTLK=m +CONFIG_SPEAKUP_SYNTH_SOFT=m +CONFIG_SPEAKUP_SYNTH_SPKOUT=m +CONFIG_SPEAKUP_SYNTH_TXPRT=m +CONFIG_INFINIBAND=m +CONFIG_INFINIBAND_USER_MAD=m +CONFIG_INFINIBAND_USER_ACCESS=m +CONFIG_INFINIBAND_BNG_RE=m +CONFIG_INFINIBAND_CXGB4=m +CONFIG_INFINIBAND_EFA=m +CONFIG_INFINIBAND_ERDMA=m +CONFIG_INFINIBAND_IONIC=m +CONFIG_INFINIBAND_IRDMA=m +CONFIG_MANA_INFINIBAND=m +CONFIG_MLX4_INFINIBAND=m +CONFIG_MLX5_INFINIBAND=m +CONFIG_INFINIBAND_MTHCA=m +CONFIG_INFINIBAND_OCRDMA=m +CONFIG_INFINIBAND_QEDR=m +CONFIG_RDMA_RXE=m +CONFIG_RDMA_SIW=m +CONFIG_INFINIBAND_IPOIB=m +CONFIG_INFINIBAND_IPOIB_CM=y +CONFIG_INFINIBAND_IPOIB_DEBUG_DATA=y +CONFIG_INFINIBAND_SRP=m +CONFIG_INFINIBAND_SRPT=m +CONFIG_INFINIBAND_ISER=m +CONFIG_INFINIBAND_ISERT=m +CONFIG_INFINIBAND_RTRS_CLIENT=m +CONFIG_INFINIBAND_RTRS_SERVER=m +CONFIG_EDAC=y +CONFIG_EDAC_GHES=y +CONFIG_EDAC_SCRUB=y +CONFIG_EDAC_ECS=y +CONFIG_EDAC_MEM_REPAIR=y +CONFIG_EDAC_LAYERSCAPE=m +CONFIG_EDAC_THUNDERX=m +CONFIG_EDAC_SYNOPSYS=m +CONFIG_EDAC_XGENE=m +CONFIG_EDAC_QCOM=m +CONFIG_EDAC_BLUEFIELD=m +CONFIG_EDAC_DMC520=m +CONFIG_EDAC_ZYNQMP=m +CONFIG_EDAC_VERSAL=m +CONFIG_EDAC_CORTEX_A72=m +CONFIG_EDAC_APPLE_SOC=m +CONFIG_EDAC_VERSALNET=m +CONFIG_RTC_CLASS=y +CONFIG_RTC_DRV_ABEOZ9=m +CONFIG_RTC_DRV_ABX80X=m +CONFIG_RTC_DRV_AC100=m +CONFIG_RTC_DRV_AS3722=m +CONFIG_RTC_DRV_DS1307=m +CONFIG_RTC_DRV_DS1374=m +CONFIG_RTC_DRV_DS1374_WDT=y +CONFIG_RTC_DRV_DS1672=m +CONFIG_RTC_DRV_HYM8563=m +CONFIG_RTC_DRV_MAX6900=m +CONFIG_RTC_DRV_MAX31335=m +CONFIG_RTC_DRV_MAX77686=m +CONFIG_RTC_DRV_NVIDIA_VRS10=m +CONFIG_RTC_DRV_NCT3018Y=m +CONFIG_RTC_DRV_RK808=m +CONFIG_RTC_DRV_RS5C372=m +CONFIG_RTC_DRV_ISL1208=m +CONFIG_RTC_DRV_ISL12022=m +CONFIG_RTC_DRV_ISL12026=m +CONFIG_RTC_DRV_X1205=m +CONFIG_RTC_DRV_PCF8523=m +CONFIG_RTC_DRV_PCF85363=m +CONFIG_RTC_DRV_PCF8563=m +CONFIG_RTC_DRV_PCF8583=m +CONFIG_RTC_DRV_M41T80=m +CONFIG_RTC_DRV_M41T80_WDT=y +CONFIG_RTC_DRV_BQ32K=m +CONFIG_RTC_DRV_S35390A=m +CONFIG_RTC_DRV_FM3130=m +CONFIG_RTC_DRV_RX8010=m +CONFIG_RTC_DRV_RX8581=m +CONFIG_RTC_DRV_RX8025=m +CONFIG_RTC_DRV_EM3027=m +CONFIG_RTC_DRV_RV3028=m +CONFIG_RTC_DRV_RV3032=m +CONFIG_RTC_DRV_RV8803=m +CONFIG_RTC_DRV_SD3078=m +CONFIG_RTC_DRV_M41T93=m +CONFIG_RTC_DRV_M41T94=m +CONFIG_RTC_DRV_DS1305=m +CONFIG_RTC_DRV_DS1343=m +CONFIG_RTC_DRV_DS1347=m +CONFIG_RTC_DRV_DS1390=m +CONFIG_RTC_DRV_MAX6916=m +CONFIG_RTC_DRV_R9701=m +CONFIG_RTC_DRV_RX4581=m +CONFIG_RTC_DRV_RS5C348=m +CONFIG_RTC_DRV_MAX6902=m +CONFIG_RTC_DRV_PCF2123=m +CONFIG_RTC_DRV_MCP795=m +CONFIG_RTC_DRV_DS3232=m +# CONFIG_RTC_DRV_DS3232_HWMON is not set +CONFIG_RTC_DRV_PCF2127=m +CONFIG_RTC_DRV_PCF85063=m +CONFIG_RTC_DRV_RV3029C2=m +CONFIG_RTC_DRV_DS1286=m +CONFIG_RTC_DRV_DS1511=m +CONFIG_RTC_DRV_DS1553=m +CONFIG_RTC_DRV_DS1685_FAMILY=m +CONFIG_RTC_DRV_DS1742=m +CONFIG_RTC_DRV_DS2404=m +CONFIG_RTC_DRV_EFI=y +CONFIG_RTC_DRV_STK17TA8=m +CONFIG_RTC_DRV_M48T35=m +CONFIG_RTC_DRV_M48T59=m +CONFIG_RTC_DRV_MSM6242=m +CONFIG_RTC_DRV_RP5C01=m +CONFIG_RTC_DRV_OPTEE=m +CONFIG_RTC_DRV_ZYNQMP=m +CONFIG_RTC_DRV_CROS_EC=m +CONFIG_RTC_DRV_FSL_FTM_ALARM=m +CONFIG_RTC_DRV_PL031=y +CONFIG_RTC_DRV_SUN6I=y +CONFIG_RTC_DRV_MV=m +CONFIG_RTC_DRV_ARMADA38X=m +CONFIG_RTC_DRV_CADENCE=m +CONFIG_RTC_DRV_PM8XXX=m +CONFIG_RTC_DRV_TEGRA=m +CONFIG_RTC_DRV_SNVS=m +CONFIG_RTC_DRV_BBNSM=m +CONFIG_RTC_DRV_IMX_BBM_SCMI=m +CONFIG_RTC_DRV_IMX_SC=m +CONFIG_RTC_DRV_XGENE=m +CONFIG_RTC_DRV_R7301=m +CONFIG_RTC_DRV_TI_K3=m +CONFIG_RTC_DRV_APPLE_PMU=y +CONFIG_RTC_DRV_MACSMC=y +CONFIG_RTC_DRV_S32G=m +CONFIG_DMADEVICES=y +CONFIG_ALTERA_MSGDMA=m +CONFIG_APPLE_SIO=m +CONFIG_ARM_DMA350=m +CONFIG_AXI_DMAC=m +CONFIG_BCM_SBA_RAID=m +CONFIG_DMA_BCM2835=m +CONFIG_DMA_SUN6I=m +CONFIG_DW_AXI_DMAC=m +CONFIG_FSL_EDMA=m +CONFIG_FSL_QDMA=m +CONFIG_HISI_DMA=m +CONFIG_IMX_SDMA=m +CONFIG_K3_DMA=m +CONFIG_MV_XOR=y +CONFIG_MV_XOR_V2=y +CONFIG_MXS_DMA=y +CONFIG_PL330_DMA=m +CONFIG_TEGRA186_GPC_DMA=m +CONFIG_TEGRA20_APB_DMA=y +CONFIG_TEGRA210_ADMA=m +CONFIG_XILINX_DMA=m +CONFIG_XILINX_XDMA=m +CONFIG_XILINX_ZYNQMP_DMA=m +CONFIG_XILINX_ZYNQMP_DPDMA=m +CONFIG_AMD_QDMA=m +CONFIG_QCOM_BAM_DMA=y +CONFIG_QCOM_GPI_DMA=m +CONFIG_QCOM_HIDMA_MGMT=m +CONFIG_QCOM_HIDMA=m +CONFIG_DW_DMAC=m +CONFIG_DW_DMAC_PCI=m +CONFIG_DW_EDMA=m +CONFIG_DW_EDMA_PCIE=m +CONFIG_RZ_DMAC=y +CONFIG_TI_K3_UDMA=m +CONFIG_TI_K3_UDMA_GLUE_LAYER=m +CONFIG_FSL_DPAA2_QDMA=m +CONFIG_ASYNC_TX_DMA=y +CONFIG_UDMABUF=y +CONFIG_DMABUF_HEAPS=y +CONFIG_DMABUF_HEAPS_SYSTEM=y +CONFIG_DMABUF_HEAPS_CMA=y +CONFIG_UIO_PCI_GENERIC=m +CONFIG_UIO_HV_GENERIC=m +CONFIG_UIO_DFL=m +CONFIG_VFIO=m +CONFIG_VFIO_DEVICE_CDEV=y +CONFIG_VFIO_NOIOMMU=y +CONFIG_VFIO_PCI=m +CONFIG_MLX5_VFIO_PCI=m +CONFIG_PDS_VFIO_PCI=m +CONFIG_VIRTIO_VFIO_PCI=m +CONFIG_NVGRACE_GPU_VFIO_PCI=m +CONFIG_QAT_VFIO_PCI=m +CONFIG_VFIO_PLATFORM=m +CONFIG_VFIO_AMBA=m +CONFIG_VFIO_PLATFORM_AMDXGBE_RESET=m +CONFIG_VFIO_FSL_MC=m +CONFIG_VFIO_CDX=m +CONFIG_VIRT_DRIVERS=y +CONFIG_VBOXGUEST=m +CONFIG_NITRO_ENCLAVES=m +CONFIG_EFI_SECRET=m +CONFIG_ARM_CCA_GUEST=m +CONFIG_VIRTIO_PCI=y +CONFIG_VIRTIO_VDPA=m +CONFIG_VIRTIO_BALLOON=m +CONFIG_VIRTIO_MEM=m +CONFIG_VIRTIO_INPUT=m +CONFIG_VIRTIO_MMIO=m +CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y +CONFIG_VIRTIO_RTC=m +CONFIG_VDPA=m +CONFIG_VDPA_SIM=m +CONFIG_VDPA_SIM_NET=m +CONFIG_VDPA_SIM_BLOCK=m +CONFIG_VDPA_USER=m +CONFIG_IFCVF=m +CONFIG_MLX5_VDPA_NET=m +CONFIG_VP_VDPA=m +CONFIG_SNET_VDPA=m +CONFIG_PDS_VDPA=m +CONFIG_OCTEONEP_VDPA=m +CONFIG_VHOST_NET=m +CONFIG_VHOST_SCSI=m +CONFIG_VHOST_VSOCK=m +CONFIG_VHOST_VDPA=m +CONFIG_HYPERV=y +CONFIG_HYPERV_UTILS=m +CONFIG_HYPERV_BALLOON=m +CONFIG_HYPERV_VMBUS=m +CONFIG_GPIB=m +CONFIG_GPIB_AGILENT_82350B=m +CONFIG_GPIB_AGILENT_82357A=m +CONFIG_GPIB_CEC_PCI=m +CONFIG_GPIB_NI_PCI_ISA=m +CONFIG_GPIB_CB7210=m +CONFIG_GPIB_NI_USB=m +CONFIG_GPIB_FLUKE=m +CONFIG_GPIB_FMH=m +CONFIG_GPIB_GPIO=m +CONFIG_GPIB_INES=m +CONFIG_GPIB_LPVO=m +CONFIG_STAGING=y +CONFIG_RTL8723BS=m +CONFIG_STAGING_MEDIA=y +CONFIG_VIDEO_MAX96712=m +CONFIG_VIDEO_MESON_VDEC=m +CONFIG_VIDEO_SUNXI=y +CONFIG_VIDEO_SUNXI_CEDRUS=m +CONFIG_VIDEO_SUN6I_ISP=m +CONFIG_VIDEO_TEGRA=m +CONFIG_SND_BCM2835=m +CONFIG_CHROME_PLATFORMS=y +CONFIG_CHROMEOS_ACPI=m +CONFIG_CHROMEOS_TBMC=y +CONFIG_CROS_EC=m +CONFIG_CROS_EC_I2C=m +CONFIG_CROS_EC_RPMSG=m +CONFIG_CROS_EC_SPI=m +CONFIG_CROS_EC_UART=m +CONFIG_CROS_KBD_LED_BACKLIGHT=m +# CONFIG_CROS_EC_LIGHTBAR is not set +# CONFIG_CROS_EC_DEBUGFS is not set +CONFIG_CROS_HPS_I2C=m +CONFIG_CHROMEOS_PRIVACY_SCREEN=m +CONFIG_MELLANOX_PLATFORM=y +CONFIG_MLX_PLATFORM=m +CONFIG_MLXREG_DPU=m +CONFIG_MLXREG_HOTPLUG=m +CONFIG_MLXREG_IO=m +CONFIG_MLXREG_LC=m +CONFIG_MLXBF_TMFIFO=m +CONFIG_MLXBF_BOOTCTL=m +CONFIG_MLXBF_PMC=m +CONFIG_SURFACE_ACPI_NOTIFY=m +CONFIG_SURFACE_AGGREGATOR_CDEV=m +CONFIG_SURFACE_AGGREGATOR_HUB=m +CONFIG_SURFACE_AGGREGATOR_REGISTRY=m +CONFIG_SURFACE_AGGREGATOR_TABLET_SWITCH=m +CONFIG_SURFACE_DTX=m +CONFIG_SURFACE_GPE=m +CONFIG_SURFACE_HOTPLUG=m +CONFIG_SURFACE_PLATFORM_PROFILE=m +CONFIG_SURFACE_PRO3_BUTTON=m +CONFIG_SURFACE_AGGREGATOR=m +CONFIG_EC_ACER_ASPIRE1=m +CONFIG_EC_LENOVO_YOGA_C630=m +CONFIG_EC_LENOVO_THINKPAD_T14S=m +CONFIG_BCM_VIDEOCORE=m +CONFIG_BCM2835_VCHIQ_MMAL=m +CONFIG_CLK_ICST=y +CONFIG_CLK_SP810=y +CONFIG_COMMON_CLK_MAX77686=y +CONFIG_COMMON_CLK_RK808=m +CONFIG_COMMON_CLK_SCPI=m +CONFIG_COMMON_CLK_SI5341=m +CONFIG_COMMON_CLK_SI544=m +CONFIG_COMMON_CLK_AXI_CLKGEN=m +CONFIG_COMMON_CLK_PWM=m +CONFIG_COMMON_CLK_RS9_PCIE=m +CONFIG_COMMON_CLK_SI521XX=y +CONFIG_COMMON_CLK_VC3=m +CONFIG_COMMON_CLK_VC7=m +CONFIG_COMMON_CLK_BD718XX=m +CONFIG_CLK_BCM2711_DVP=m +CONFIG_CLK_RASPBERRYPI=y +# CONFIG_COMMON_CLK_HI3516CV300 is not set +CONFIG_COMMON_CLK_HI3519=m +# CONFIG_COMMON_CLK_HI3798CV200 is not set +CONFIG_CLK_IMX8MM=y +CONFIG_CLK_IMX8MN=y +CONFIG_CLK_IMX8MP=y +CONFIG_CLK_IMX8MQ=y +CONFIG_CLK_IMX8QXP=y +CONFIG_CLK_IMX8ULP=y +CONFIG_CLK_IMX93=y +CONFIG_CLK_IMX95_BLK_CTL=m +CONFIG_TI_SCI_CLK=y +CONFIG_TI_SYSCON_CLK=m +CONFIG_COMMON_CLK_AXG_AUDIO=y +CONFIG_COMMON_CLK_T7_PERIPHERALS=m +CONFIG_COMMON_CLK_QCOM=y +CONFIG_CLK_GLYMUR_TCSRCC=y +# CONFIG_CLK_KAANAPALI_CAMCC is not set +# CONFIG_CLK_KAANAPALI_DISPCC is not set +# CONFIG_CLK_KAANAPALI_GCC is not set +# CONFIG_CLK_KAANAPALI_GPUCC is not set +# CONFIG_CLK_KAANAPALI_TCSRCC is not set +# CONFIG_CLK_KAANAPALI_VIDEOCC is not set +CONFIG_QCOM_A53PLL=m +# CONFIG_QCOM_CLK_APCC_MSM8996 is not set +# CONFIG_IPQ_APSS_6018 is not set +CONFIG_IPQ_GCC_5018=m +# CONFIG_IPQ_GCC_5332 is not set +# CONFIG_IPQ_GCC_5424 is not set +# CONFIG_IPQ_GCC_6018 is not set +# CONFIG_IPQ_GCC_8074 is not set +# CONFIG_IPQ_GCC_9574 is not set +CONFIG_IPQ_NSSCC_QCA8K=m +CONFIG_MSM_GCC_8939=m +# CONFIG_MSM_GCC_8953 is not set +# CONFIG_MSM_GCC_8976 is not set +# CONFIG_MSM_MMCC_8994 is not set +# CONFIG_MSM_GCC_8994 is not set +# CONFIG_MSM_MMCC_8998 is not set +CONFIG_QCM_GCC_2290=m +# CONFIG_QCM_DISPCC_2290 is not set +CONFIG_QCS_GCC_404=m +CONFIG_SC_LPASS_CORECC_7180=m +CONFIG_SDM_GCC_660=m +# CONFIG_SDM_MMCC_660 is not set +# CONFIG_SDM_GPUCC_660 is not set +# CONFIG_QDU_GCC_1000 is not set +# CONFIG_QDU_ECPRICC_1000 is not set +CONFIG_SDM_GCC_845=m +# CONFIG_SDX_GCC_75 is not set +# CONFIG_SM_CAMCC_4450 is not set +# CONFIG_SM_CAMCC_6350 is not set +# CONFIG_SM_CAMCC_8150 is not set +# CONFIG_SM_CAMCC_8450 is not set +# CONFIG_SM_CAMCC_8550 is not set +# CONFIG_SM_CAMCC_8750 is not set +# CONFIG_SM_DISPCC_8550 is not set +# CONFIG_SM_GCC_4450 is not set +CONFIG_SM_GCC_6115=m +# CONFIG_SM_GCC_6125 is not set +# CONFIG_SM_GCC_6350 is not set +# CONFIG_SM_GCC_6375 is not set +CONFIG_SM_GCC_7150=m +CONFIG_SM_GCC_8250=m +CONFIG_SM_GCC_8350=m +CONFIG_SM_GCC_8450=m +CONFIG_SM_GCC_8550=m +CONFIG_SM_GCC_8650=m +CONFIG_SM_GCC_8750=m +# CONFIG_SM_GPUCC_4450 is not set +# CONFIG_SM_GPUCC_6125 is not set +# CONFIG_SM_GPUCC_6375 is not set +# CONFIG_SM_GPUCC_6350 is not set +# CONFIG_SM_GPUCC_8150 is not set +# CONFIG_SM_GPUCC_8250 is not set +# CONFIG_SM_GPUCC_8350 is not set +# CONFIG_SM_GPUCC_8450 is not set +# CONFIG_SM_GPUCC_8550 is not set +# CONFIG_SM_LPASSCC_6115 is not set +# CONFIG_SM_TCSRCC_8550 is not set +CONFIG_SM_TCSRCC_8650=m +# CONFIG_SM_TCSRCC_8750 is not set +# CONFIG_SM_VIDEOCC_6350 is not set +# CONFIG_SM_VIDEOCC_8150 is not set +# CONFIG_SM_VIDEOCC_8550 is not set +# CONFIG_SM_VIDEOCC_8750 is not set +CONFIG_SPMI_PMIC_CLKDIV=m +CONFIG_QCOM_HFPLL=m +CONFIG_KPSS_XCC=m +# CONFIG_SM_VIDEOCC_8450 is not set +# CONFIG_CLK_RV1126B is not set +CONFIG_SUN55I_A523_CCU=m +CONFIG_SUN55I_A523_R_CCU=m +CONFIG_XILINX_VCU=m +CONFIG_COMMON_CLK_XLNX_CLKWZRD=m +CONFIG_HWSPINLOCK=y +CONFIG_HWSPINLOCK_OMAP=m +CONFIG_HWSPINLOCK_QCOM=m +CONFIG_HWSPINLOCK_SUN6I=m +CONFIG_TEGRA186_TIMER=y +CONFIG_RENESAS_OSTM=y +CONFIG_NXP_STM_TIMER=y +CONFIG_ARM_MHU=m +CONFIG_ARM_MHU_V2=m +CONFIG_ARM_MHU_V3=m +CONFIG_IMX_MBOX=m +CONFIG_PLATFORM_MHU=m +CONFIG_OMAP2PLUS_MBOX=m +CONFIG_ROCKCHIP_MBOX=y +CONFIG_BCM2835_MBOX=y +CONFIG_QCOM_APCS_IPC=m +CONFIG_TEGRA_HSP_MBOX=y +CONFIG_XGENE_SLIMPRO_MBOX=m +CONFIG_QCOM_CPUCP_MBOX=m +CONFIG_QCOM_IPCC=m +CONFIG_CIX_MBOX=m +CONFIG_IOMMU_DEFAULT_DMA_LAZY=y +CONFIG_ARM_SMMU=y +CONFIG_ARM_SMMU_V3=y +CONFIG_ARM_SMMU_V3_SVA=y +CONFIG_ARM_SMMU_V3_IOMMUFD=y +CONFIG_TEGRA241_CMDQV=y +CONFIG_QCOM_IOMMU=y +CONFIG_IOMMUFD=m +CONFIG_ROCKCHIP_IOMMU=y +CONFIG_SUN50I_IOMMU=y +CONFIG_TEGRA_IOMMU_SMMU=y +CONFIG_APPLE_DART=y +CONFIG_APPLE_DART_J713_DCP=y +CONFIG_VIRTIO_IOMMU=y +CONFIG_IMX_REMOTEPROC=m +CONFIG_IMX_DSP_REMOTEPROC=m +CONFIG_QCOM_Q6V5_ADSP=m +CONFIG_QCOM_Q6V5_MSS=m +CONFIG_QCOM_Q6V5_PAS=m +CONFIG_QCOM_Q6V5_WCSS=m +CONFIG_QCOM_SYSMON=m +CONFIG_QCOM_WCNSS_PIL=m +CONFIG_TI_K3_DSP_REMOTEPROC=m +CONFIG_TI_K3_M4_REMOTEPROC=m +CONFIG_TI_K3_R5_REMOTEPROC=m +CONFIG_XLNX_R5_REMOTEPROC=m +CONFIG_RPMSG_CHAR=m +CONFIG_RPMSG_CTRL=m +CONFIG_RPMSG_QCOM_GLINK_RPM=m +CONFIG_RPMSG_QCOM_GLINK_SMEM=m +CONFIG_RPMSG_QCOM_SMD=m +CONFIG_SOUNDWIRE=m +CONFIG_SOUNDWIRE_QCOM=m +# CONFIG_MESON_CLK_MEASURE is not set +CONFIG_APPLE_DBGVIEW=m +CONFIG_APPLE_DOCKCHANNEL=m +CONFIG_APPLE_PMGR_MISC=y +CONFIG_APPLE_SOC_SLEEP=y +CONFIG_APPLE_RTKIT_HELPER=m +CONFIG_APPLE_SART=m +CONFIG_APPLE_PMP=m +CONFIG_APPLE_REGVIEW=m +CONFIG_FSL_DPAA=y +CONFIG_FSL_MC_DPIO=m +CONFIG_DPAA2_CONSOLE=m +CONFIG_FSL_RCPM=y +CONFIG_A64FX_DIAG=y +CONFIG_SOC_IMX9=m +CONFIG_WPCM450_SOC=m +CONFIG_QCOM_AOSS_QMP=m +CONFIG_QCOM_PMIC_PDCHARGER_ULOG=m +CONFIG_QCOM_RAMP_CTRL=m +CONFIG_QCOM_RPM_MASTER_STATS=m +CONFIG_QCOM_SMEM=m +CONFIG_QCOM_SPM=y +# CONFIG_ARCH_R8A774B1 is not set +# CONFIG_ARCH_R8A774C0 is not set +# CONFIG_ARCH_R8A774E1 is not set +# CONFIG_ARCH_R8A77951 is not set +# CONFIG_ARCH_R8A77960 is not set +# CONFIG_ARCH_R8A77961 is not set +# CONFIG_ARCH_R8A77965 is not set +# CONFIG_ARCH_R8A77970 is not set +# CONFIG_ARCH_R8A77980 is not set +# CONFIG_ARCH_R8A77990 is not set +# CONFIG_ARCH_R8A77995 is not set +# CONFIG_ARCH_R8A779A0 is not set +# CONFIG_ARCH_R8A779F0 is not set +# CONFIG_ARCH_R8A779G0 is not set +# CONFIG_ARCH_R8A779H0 is not set +# CONFIG_ARCH_R9A09G047 is not set +CONFIG_ROCKCHIP_IODOMAIN=m +CONFIG_ROCKCHIP_DTPM=m +CONFIG_SOC_TEGRA_CBB=m +CONFIG_TI_PRUSS=m +CONFIG_RASPBERRYPI_POWER=y +CONFIG_IMX_SCU_PD=y +CONFIG_QCOM_CPR=m +CONFIG_QCOM_RPMHPD=y +CONFIG_QCOM_RPMPD=m +# CONFIG_SUN20I_PPU is not set +CONFIG_SUN50I_H6_PRCM_PPU=m +CONFIG_SUN55I_PCK600=m +CONFIG_TI_SCI_PM_DOMAINS=y +CONFIG_DEVFREQ_GOV_POWERSAVE=m +CONFIG_DEVFREQ_GOV_PASSIVE=m +CONFIG_ARM_HISI_UNCORE_DEVFREQ=m +CONFIG_ARM_IMX_BUS_DEVFREQ=m +CONFIG_ARM_IMX8M_DDRC_DEVFREQ=m +CONFIG_ARM_TEGRA_DEVFREQ=m +CONFIG_ARM_RK3399_DMC_DEVFREQ=m +CONFIG_ARM_SUN8I_A33_MBUS_DEVFREQ=m +CONFIG_EXTCON_ADC_JACK=m +CONFIG_EXTCON_GPIO=m +CONFIG_EXTCON_LC824206XA=m +CONFIG_EXTCON_PTN5150=m +CONFIG_EXTCON_SM5502=m +CONFIG_EXTCON_USB_GPIO=m +CONFIG_EXTCON_USBC_CROS_EC=m +CONFIG_EXTCON_USBC_TUSB320=m +CONFIG_MEMORY=y +CONFIG_ARM_PL172_MPMC=m +CONFIG_OMAP_GPMC=y +CONFIG_FPGA_DFL_EMIF=m +CONFIG_TEGRA210_EMC=m +CONFIG_IIO_BUFFER_HW_CONSUMER=m +CONFIG_IIO_SW_DEVICE=m +CONFIG_IIO_SW_TRIGGER=m +CONFIG_IIO_TRIGGERED_EVENT=m +CONFIG_ADXL313_I2C=m +CONFIG_ADXL313_SPI=m +CONFIG_ADXL355_I2C=m +CONFIG_ADXL355_SPI=m +CONFIG_ADXL367_SPI=m +CONFIG_ADXL367_I2C=m +CONFIG_ADXL372_SPI=m +CONFIG_ADXL372_I2C=m +CONFIG_ADXL380_SPI=m +CONFIG_ADXL380_I2C=m +CONFIG_BMA180=m +CONFIG_BMC150_ACCEL=m +CONFIG_DA280=m +CONFIG_DA311=m +CONFIG_DMARD10=m +CONFIG_HID_SENSOR_ACCEL_3D=m +CONFIG_IIO_CROS_EC_ACCEL_LEGACY=m +CONFIG_IIO_ST_ACCEL_3AXIS=m +CONFIG_IIO_KX022A_SPI=m +CONFIG_IIO_KX022A_I2C=m +CONFIG_KXSD9=m +CONFIG_KXCJK1013=m +CONFIG_MMA7660=m +CONFIG_MMA8452=m +CONFIG_MSA311=m +CONFIG_MXC4005=m +CONFIG_MXC6255=m +CONFIG_SCA3300=m +CONFIG_AD4000=m +CONFIG_AD4030=m +CONFIG_AD4062=m +CONFIG_AD4080=m +CONFIG_AD4130=m +CONFIG_AD4134=m +CONFIG_AD4170_4=m +CONFIG_AD4695=m +CONFIG_AD4851=m +CONFIG_AD7091R8=m +CONFIG_AD7124=m +CONFIG_AD7191=m +CONFIG_AD7292=m +CONFIG_AD7380=m +CONFIG_AD7405=m +CONFIG_AD7625=m +CONFIG_AD7766=m +CONFIG_AD7779=m +CONFIG_AD7949=m +CONFIG_AD9467=m +CONFIG_ADE9000=m +CONFIG_AXP20X_ADC=m +CONFIG_AXP288_ADC=m +CONFIG_DLN2_ADC=m +CONFIG_ENVELOPE_DETECTOR=m +CONFIG_INA2XX_ADC=m +CONFIG_IMX7D_ADC=m +CONFIG_IMX8QXP_ADC=m +CONFIG_IMX93_ADC=m +CONFIG_MAX11205=m +CONFIG_MAX11410=m +CONFIG_MAX1241=m +CONFIG_MAX1363=m +CONFIG_MAX14001=m +CONFIG_MAX34408=m +CONFIG_MCP320X=m +CONFIG_MCP3422=m +CONFIG_MCP3911=m +CONFIG_NXP_SAR_ADC=m +CONFIG_PAC1921=m +CONFIG_PAC1934=m +CONFIG_QCOM_SPMI_RRADC=m +CONFIG_QCOM_SPMI_IADC=m +CONFIG_QCOM_SPMI_VADC=m +CONFIG_QCOM_SPMI_ADC5=m +CONFIG_ROHM_BD79124=m +CONFIG_ROCKCHIP_SARADC=m +CONFIG_RICHTEK_RTQ6056=m +CONFIG_RZG2L_ADC=m +CONFIG_RZT2H_ADC=m +CONFIG_SD_ADC_MODULATOR=m +CONFIG_STMPE_ADC=m +CONFIG_SUN20I_GPADC=m +CONFIG_TI_ADC128S052=m +CONFIG_TI_ADS1015=m +CONFIG_TI_ADS1018=m +CONFIG_TI_ADS1100=m +CONFIG_TI_ADS131E08=m +CONFIG_TI_ADS131M02=m +CONFIG_TI_ADS7138=m +CONFIG_TI_ADS7924=m +CONFIG_TI_ADS8344=m +CONFIG_TI_AM335X_ADC=m +CONFIG_TI_LMP92064=m +CONFIG_TI_TSC2046=m +CONFIG_XILINX_XADC=m +CONFIG_XILINX_AMS=m +CONFIG_AD74115=m +CONFIG_AD74413R=m +CONFIG_IIO_RESCALE=m +CONFIG_ADL8113=m +CONFIG_HMC425=m +CONFIG_BME680=m +CONFIG_PMS7003=m +CONFIG_SCD30_CORE=m +CONFIG_SCD30_I2C=m +CONFIG_SCD30_SERIAL=m +CONFIG_IIO_AOP_SENSOR_LAS=m +CONFIG_IIO_AOP_SENSOR_ALS=m +CONFIG_IIO_AOP_SENSOR_MOTION=m +CONFIG_IIO_AOP_SENSOR_DEVMOTION=m +CONFIG_IIO_AOP_SENSOR_TEMP=m +CONFIG_IIO_CROS_EC_SENSORS_CORE=m +CONFIG_IIO_CROS_EC_SENSORS=m +CONFIG_IIO_CROS_EC_SENSORS_LID_ANGLE=m +CONFIG_IIO_CROS_EC_ACTIVITY=m +CONFIG_IIO_SCMI=m +CONFIG_AD3530R=m +CONFIG_AD3552R_HS=m +CONFIG_AD3552R=m +CONFIG_LTC2688=m +CONFIG_AD5766=m +CONFIG_AD5770R=m +CONFIG_AD7293=m +CONFIG_AD8460=m +CONFIG_BD79703=m +CONFIG_DPOT_DAC=m +CONFIG_LTC1660=m +CONFIG_LTC2664=m +CONFIG_MAX22007=m +CONFIG_MAX5522=m +CONFIG_MCP4728=m +CONFIG_MCP47FEB02=m +CONFIG_MCP4821=m +CONFIG_TI_DAC7311=m +CONFIG_ADF4377=m +CONFIG_ADXRS290=m +CONFIG_FXAS21002C=m +CONFIG_HID_SENSOR_GYRO_3D=m +CONFIG_MPU3050_I2C=m +CONFIG_IIO_ST_GYRO_3AXIS=m +CONFIG_MAX30100=m +CONFIG_DHT11=m +CONFIG_HDC100X=m +CONFIG_HDC2010=m +CONFIG_HID_SENSOR_HUMIDITY=m +CONFIG_HTS221=m +CONFIG_HTU21=m +CONFIG_SI7020=m +CONFIG_ADIS16475=m +CONFIG_ADIS16550=m +CONFIG_BMI160_I2C=m +CONFIG_BMI160_SPI=m +CONFIG_BMI270_I2C=m +CONFIG_BMI270_SPI=m +CONFIG_BOSCH_BNO055_SERIAL=m +CONFIG_BOSCH_BNO055_I2C=m +CONFIG_FXOS8700_I2C=m +CONFIG_FXOS8700_SPI=m +CONFIG_INV_ICM42600_I2C=m +CONFIG_INV_ICM42600_SPI=m +CONFIG_INV_ICM45600_I2C=m +CONFIG_INV_ICM45600_SPI=m +CONFIG_INV_ICM45600_I3C=m +CONFIG_INV_MPU6050_I2C=m +CONFIG_SMI330_I2C=m +CONFIG_SMI330_SPI=m +CONFIG_IIO_ST_LSM6DSX=m +CONFIG_ACPI_ALS=m +CONFIG_ADUX1020=m +CONFIG_AL3000A=m +CONFIG_AL3010=m +CONFIG_APDS9160=m +CONFIG_APDS9306=m +CONFIG_APDS9960=m +CONFIG_BH1745=m +CONFIG_BH1750=m +CONFIG_CM32181=m +CONFIG_CM3605=m +CONFIG_IIO_CROS_EC_LIGHT_PROX=m +CONFIG_GP2AP002=m +CONFIG_SENSORS_ISL29018=m +CONFIG_SENSORS_ISL29028=m +CONFIG_HID_SENSOR_ALS=m +CONFIG_ROHM_BU27034=m +CONFIG_RPR0521=m +CONFIG_LTR501=m +CONFIG_LTRF216A=m +CONFIG_LV0104CS=m +CONFIG_MAX44009=m +CONFIG_OPT3001=m +CONFIG_OPT4001=m +CONFIG_OPT4060=m +CONFIG_PA12203001=m +CONFIG_STK3310=m +CONFIG_ST_UVIS25=m +CONFIG_TCS3472=m +CONFIG_TSL2772=m +CONFIG_TSL4531=m +CONFIG_VCNL4000=m +CONFIG_VCNL4035=m +CONFIG_VEML3235=m +CONFIG_VEML6030=m +CONFIG_VEML6070=m +CONFIG_VL6180=m +CONFIG_ZOPT2201=m +CONFIG_AF8133J=m +CONFIG_AK8975=m +CONFIG_BMC150_MAGN_I2C=m +CONFIG_BMC150_MAGN_SPI=m +CONFIG_MAG3110=m +CONFIG_HID_SENSOR_MAGNETOMETER_3D=m +CONFIG_MMC5633=m +CONFIG_IIO_ST_MAGN_3AXIS=m +CONFIG_SENSORS_RM3100_I2C=m +CONFIG_SENSORS_RM3100_SPI=m +CONFIG_IIO_MUX=m +CONFIG_HID_SENSOR_INCLINOMETER_3D=m +CONFIG_HID_SENSOR_DEVICE_ROTATION=m +CONFIG_IIO_TIGHTLOOP_TRIGGER=m +CONFIG_IIO_SYSFS_TRIGGER=m +CONFIG_HID_SENSOR_CUSTOM_INTEL_HINGE=m +CONFIG_AD5110=m +CONFIG_AD5272=m +CONFIG_MCP4018=m +CONFIG_MCP41010=m +CONFIG_X9250=m +CONFIG_LMP91000=m +CONFIG_ABP060MG=m +CONFIG_ABP2030PA_I2C=m +CONFIG_ABP2030PA_SPI=m +CONFIG_BMP280=m +CONFIG_IIO_CROS_EC_BARO=m +CONFIG_ICP10100=m +CONFIG_MPL115_I2C=m +CONFIG_MPRLS0025PA_I2C=m +CONFIG_MPRLS0025PA_SPI=m +CONFIG_IIO_ST_PRESS=m +CONFIG_CROS_EC_MKBP_PROXIMITY=m +CONFIG_D3323AA=m +CONFIG_MB1232=m +CONFIG_SX9310=m +CONFIG_SX9324=m +CONFIG_SX9360=m +CONFIG_VCNL3020=m +CONFIG_VL53L0X_I2C=m +CONFIG_LTC2983=m +CONFIG_MAXIM_THERMOCOUPLE=m +CONFIG_HID_SENSOR_TEMP=m +CONFIG_MLX90614=m +CONFIG_MLX90632=m +CONFIG_TMP006=m +CONFIG_TMP117=m +CONFIG_MAX30208=m +CONFIG_MAX31856=m +CONFIG_MAX31865=m +CONFIG_MCP9600=m +CONFIG_PWM=y +CONFIG_PWM_PROVIDE_GPIO=y +CONFIG_PWM_ADP5585=m +CONFIG_PWM_APPLE=m +CONFIG_PWM_ARGON_FAN_HAT=m +CONFIG_PWM_AXI_PWMGEN=m +CONFIG_PWM_BCM2835=m +CONFIG_PWM_CLK=m +CONFIG_PWM_CROS_EC=m +CONFIG_PWM_DWC=m +CONFIG_PWM_GPIO=m +CONFIG_PWM_HIBVT=m +CONFIG_PWM_IMX27=m +CONFIG_PWM_IMX_TPM=m +CONFIG_PWM_MC33XS2410=m +CONFIG_PWM_MESON=m +CONFIG_PWM_OMAP_DMTIMER=m +CONFIG_PWM_PCA9685=m +CONFIG_PWM_RASPBERRYPI_POE=m +CONFIG_PWM_RENESAS_RZG2L_GPT=m +CONFIG_PWM_ROCKCHIP=m +CONFIG_PWM_STMPE=y +CONFIG_PWM_SUN4I=m +CONFIG_PWM_TEGRA=y +CONFIG_PWM_TIECAP=m +CONFIG_PWM_TIEHRPWM=m +CONFIG_PWM_XILINX=m +CONFIG_AL_FIC=y +CONFIG_BCM2712_MIP=y +CONFIG_XILINX_INTC=y +CONFIG_QCOM_PDC=y +CONFIG_QCOM_MPM=m +CONFIG_TI_SCI_INTR_IRQCHIP=y +CONFIG_TI_SCI_INTA_IRQCHIP=m +CONFIG_RESET_GPIO=m +CONFIG_RESET_IMX_SCU=m +CONFIG_RESET_IMX7=y +CONFIG_RESET_IMX8MP_AUDIOMIX=m +CONFIG_RESET_QCOM_AOSS=y +CONFIG_RESET_QCOM_PDC=m +CONFIG_RESET_RZG2L_USBPHY_CTRL=m +CONFIG_RESET_RZV2H_USB2PHY=m +CONFIG_RESET_TI_SCI=m +CONFIG_RESET_TI_SYSCON=m +CONFIG_RESET_TI_TPS380X=m +CONFIG_RESET_MESON=m +CONFIG_COMMON_RESET_HI3660=m +CONFIG_COMMON_RESET_HI6220=m +CONFIG_PHY_CAN_TRANSCEIVER=m +CONFIG_PHY_NXP_PTN3222=m +CONFIG_PHY_SNPS_EUSB2=m +CONFIG_PHY_TI_CD2E22=m +CONFIG_PHY_XGENE=y +CONFIG_PHY_SUN4I_USB=m +CONFIG_PHY_SUN50I_USB3=m +CONFIG_PHY_MESON8B_USB2=m +CONFIG_PHY_MESON_GXL_USB2=m +CONFIG_PHY_MESON_G12A_USB3_PCIE=m +CONFIG_PHY_MESON_AXG_PCIE=m +CONFIG_PHY_MESON_AXG_MIPI_DPHY=m +CONFIG_PHY_APPLE_ATC=m +CONFIG_PHY_APPLE_T6040_USB2=m +CONFIG_PHY_APPLE_DPTX=m +CONFIG_PHY_APPLE_T6050_DP=m +CONFIG_PHY_CADENCE_TORRENT=m +CONFIG_PHY_CADENCE_DPHY=m +CONFIG_PHY_CADENCE_DPHY_RX=m +CONFIG_PHY_CADENCE_SIERRA=m +CONFIG_PHY_CADENCE_SALVO=m +CONFIG_PHY_MIXEL_LVDS_PHY=m +CONFIG_PHY_MIXEL_MIPI_DPHY=m +CONFIG_PHY_FSL_IMX8M_PCIE=y +CONFIG_PHY_FSL_IMX8QM_HSIO=m +CONFIG_PHY_FSL_LYNX_28G=m +CONFIG_PHY_HI6220_USB=m +CONFIG_PHY_HI3660_USB=m +CONFIG_PHY_HI3670_USB=m +CONFIG_PHY_HISTB_COMBPHY=m +CONFIG_PHY_HISI_INNO_USB2=m +CONFIG_PHY_MVEBU_A3700_COMPHY=m +CONFIG_PHY_MVEBU_A3700_UTMI=m +CONFIG_PHY_MVEBU_A38X_COMPHY=m +CONFIG_PHY_MVEBU_CP110_COMPHY=m +CONFIG_PHY_MVEBU_CP110_UTMI=m +CONFIG_PHY_QCOM_EDP=m +CONFIG_PHY_QCOM_PCIE2=m +CONFIG_PHY_QCOM_QMP=m +CONFIG_PHY_QCOM_QMP_USB_LEGACY=m +CONFIG_PHY_QCOM_QUSB2=m +CONFIG_PHY_QCOM_EUSB2_REPEATER=m +CONFIG_PHY_QCOM_UNIPHY_PCIE_28LP=y +CONFIG_PHY_QCOM_M31_EUSB=m +CONFIG_PHY_QCOM_USB_HS=m +CONFIG_PHY_QCOM_USB_SNPS_FEMTO_V2=m +CONFIG_PHY_QCOM_USB_HSIC=m +CONFIG_PHY_QCOM_USB_HS_28NM=m +CONFIG_PHY_QCOM_USB_SS=m +CONFIG_PHY_QCOM_SGMII_ETH=m +CONFIG_PHY_RCAR_GEN3_USB2=m +CONFIG_PHY_RZ_G3E_USB3=m +CONFIG_PHY_ROCKCHIP_DP=m +CONFIG_PHY_ROCKCHIP_DPHY_RX0=m +CONFIG_PHY_ROCKCHIP_EMMC=m +CONFIG_PHY_ROCKCHIP_INNO_HDMI=m +CONFIG_PHY_ROCKCHIP_INNO_USB2=m +CONFIG_PHY_ROCKCHIP_INNO_CSIDPHY=m +CONFIG_PHY_ROCKCHIP_INNO_DSIDPHY=m +CONFIG_PHY_ROCKCHIP_NANENG_COMBO_PHY=m +CONFIG_PHY_ROCKCHIP_PCIE=y +CONFIG_PHY_ROCKCHIP_SAMSUNG_DCPHY=m +CONFIG_PHY_ROCKCHIP_SAMSUNG_HDPTX=m +CONFIG_PHY_ROCKCHIP_SNPS_PCIE3=m +CONFIG_PHY_ROCKCHIP_TYPEC=m +CONFIG_PHY_ROCKCHIP_USB=m +CONFIG_PHY_ROCKCHIP_USBDP=m +CONFIG_PHY_TEGRA_XUSB=m +CONFIG_OMAP_USB2=m +CONFIG_PHY_AM654_SERDES=m +CONFIG_PHY_J721E_WIZ=m +CONFIG_PHY_XILINX_ZYNQMP=m +CONFIG_POWERCAP=y +CONFIG_ARM_SCMI_POWERCAP=m +CONFIG_DTPM=y +CONFIG_DTPM_CPU=y +CONFIG_DTPM_DEVFREQ=y +CONFIG_ARM_CCI_PMU=m +CONFIG_ARM_CCN=y +CONFIG_ARM_CMN=m +CONFIG_ARM_NI=m +CONFIG_ARM_SMMU_V3_PMU=m +CONFIG_ARM_DSU_PMU=m +CONFIG_FSL_IMX8_DDR_PMU=m +CONFIG_FUJITSU_UNCORE_PMU=m +CONFIG_QCOM_L2_PMU=y +CONFIG_QCOM_L3_PMU=y +CONFIG_XGENE_PMU=y +CONFIG_ARM_SPE_PMU=m +CONFIG_ARM_DMC620_PMU=m +CONFIG_MARVELL_CN10K_TAD_PMU=m +CONFIG_APPLE_M1_CPU_PMU=y +CONFIG_ALIBABA_UNCORE_DRW_PMU=m +CONFIG_HISI_PMU=y +CONFIG_MARVELL_CN10K_DDR_PMU=m +CONFIG_DWC_PCIE_PMU=m +CONFIG_ARM_CORESIGHT_PMU_ARCH_SYSTEM_PMU=m +CONFIG_NVIDIA_CORESIGHT_PMU_ARCH_SYSTEM_PMU=m +CONFIG_AMPERE_CORESIGHT_PMU_ARCH_SYSTEM_PMU=m +CONFIG_MESON_DDR_PMU=m +CONFIG_CXL_PMU=m +CONFIG_MARVELL_PEM_PMU=m +CONFIG_USB4=m +CONFIG_USB4_APPLE_SOC=m +CONFIG_ANDROID_BINDER_IPC=y +CONFIG_ANDROID_BINDERFS=y +CONFIG_LIBNVDIMM=y +# CONFIG_BTT is not set +CONFIG_RAMDAX=m +CONFIG_DEV_DAX=y +CONFIG_DEV_DAX_KMEM=m +CONFIG_NVMEM_LAYOUT_SL28_VPD=m +CONFIG_NVMEM_LAYOUT_ONIE_TLV=m +CONFIG_EEPROM_AT24=m +CONFIG_EEPROM_AT25=m +CONFIG_EEPROM_93XX46=m +CONFIG_EEPROM_EE1004=m +CONFIG_EEPROM_M24LR=m +CONFIG_NVMEM_APPLE_EFUSES=m +CONFIG_NVMEM_APPLE_SPMI=y +CONFIG_NVMEM_IMX_OCOTP=m +CONFIG_NVMEM_IMX_OCOTP_ELE=m +CONFIG_NVMEM_IMX_OCOTP_SCU=m +CONFIG_NVMEM_LAYERSCAPE_SFP=m +CONFIG_NVMEM_MESON_MX_EFUSE=m +CONFIG_NVMEM_S32G_OCOTP=m +CONFIG_NVMEM_QCOM_QFPROM=m +CONFIG_NVMEM_QCOM_SEC_QFPROM=m +CONFIG_NVMEM_QNAP_MCU_EEPROM=m +CONFIG_NVMEM_RCAR_EFUSE=m +CONFIG_NVMEM_RMEM=m +CONFIG_NVMEM_ROCKCHIP_EFUSE=m +CONFIG_NVMEM_ROCKCHIP_OTP=m +CONFIG_NVMEM_SPMI_SDAM=m +CONFIG_NVMEM_SUNXI_SID=m +CONFIG_NVMEM_U_BOOT_ENV=m +CONFIG_NVMEM_ZYNQMP=m +# CONFIG_STM_PROTO_BASIC is not set +# CONFIG_STM_PROTO_SYS_T is not set +CONFIG_FPGA=m +CONFIG_ALTERA_PR_IP_CORE=m +CONFIG_ALTERA_PR_IP_CORE_PLAT=m +CONFIG_FPGA_MGR_ALTERA_PS_SPI=m +CONFIG_FPGA_MGR_ALTERA_CVP=m +CONFIG_FPGA_MGR_XILINX_SELECTMAP=m +CONFIG_FPGA_MGR_XILINX_SPI=m +CONFIG_FPGA_MGR_ICE40_SPI=m +CONFIG_FPGA_MGR_MACHXO2_SPI=m +CONFIG_XILINX_PR_DECOUPLER=m +CONFIG_OF_FPGA_REGION=m +CONFIG_FPGA_DFL=m +CONFIG_FPGA_DFL_FME=m +CONFIG_FPGA_DFL_FME_MGR=m +CONFIG_FPGA_DFL_FME_BRIDGE=m +CONFIG_FPGA_DFL_FME_REGION=m +CONFIG_FPGA_DFL_AFU=m +CONFIG_FPGA_DFL_NIOS_INTEL_PAC_N3000=m +CONFIG_FPGA_DFL_PCI=m +CONFIG_FPGA_MGR_ZYNQMP_FPGA=m +CONFIG_FPGA_M10_BMC_SEC_UPDATE=m +CONFIG_FPGA_MGR_LATTICE_SYSCONFIG_SPI=m +CONFIG_TEE=m +CONFIG_OPTEE=m +CONFIG_ARM_TSTEE=m +CONFIG_QCOMTEE=m +CONFIG_MUX_ADG792A=m +CONFIG_MUX_APPLE_DPXBAR=m +CONFIG_MUX_GPIO=m +CONFIG_SLIM_QCOM_NGD_CTRL=m +CONFIG_INTERCONNECT_IMX=m +CONFIG_INTERCONNECT_IMX8MM=m +CONFIG_INTERCONNECT_IMX8MN=m +CONFIG_INTERCONNECT_IMX8MQ=m +CONFIG_INTERCONNECT_IMX8MP=m +CONFIG_INTERCONNECT_QCOM=y +CONFIG_INTERCONNECT_QCOM_GLYMUR=y +CONFIG_INTERCONNECT_QCOM_MSM8916=m +CONFIG_INTERCONNECT_QCOM_MSM8953=m +CONFIG_INTERCONNECT_QCOM_MSM8996=m +CONFIG_INTERCONNECT_QCOM_OSM_L3=m +CONFIG_INTERCONNECT_QCOM_QCM2290=m +CONFIG_INTERCONNECT_QCOM_QCS8300=y +CONFIG_INTERCONNECT_QCOM_SA8775P=y +CONFIG_INTERCONNECT_QCOM_SC7180=y +CONFIG_INTERCONNECT_QCOM_SC7280=y +CONFIG_INTERCONNECT_QCOM_SC8180X=y +CONFIG_INTERCONNECT_QCOM_SC8280XP=y +CONFIG_INTERCONNECT_QCOM_SDM845=m +CONFIG_INTERCONNECT_QCOM_SDX75=m +CONFIG_INTERCONNECT_QCOM_SM6115=m +CONFIG_INTERCONNECT_QCOM_MILOS=m +CONFIG_INTERCONNECT_QCOM_SM8150=m +CONFIG_INTERCONNECT_QCOM_SM8250=m +CONFIG_INTERCONNECT_QCOM_SM8450=m +CONFIG_INTERCONNECT_QCOM_X1E80100=y +CONFIG_COUNTER=m +CONFIG_INTERRUPT_CNT=m +CONFIG_TI_ECAP_CAPTURE=m +CONFIG_TI_EQEP=m +CONFIG_HTE=y +CONFIG_HTE_TEGRA194=m +CONFIG_CDX_BUS=y +CONFIG_CDX_CONTROLLER=m +CONFIG_VALIDATE_FS_PARSER=y +CONFIG_EXT4_FS=y +CONFIG_EXT4_FS_POSIX_ACL=y +CONFIG_EXT4_FS_SECURITY=y +CONFIG_JFS_FS=m +CONFIG_JFS_POSIX_ACL=y +CONFIG_JFS_SECURITY=y +CONFIG_XFS_FS=m +CONFIG_XFS_SUPPORT_V4=y +CONFIG_XFS_SUPPORT_ASCII_CI=y +CONFIG_XFS_QUOTA=y +CONFIG_XFS_POSIX_ACL=y +CONFIG_GFS2_FS=m +CONFIG_GFS2_FS_LOCKING_DLM=y +CONFIG_BTRFS_FS=y +CONFIG_BTRFS_FS_POSIX_ACL=y +CONFIG_NILFS2_FS=m +CONFIG_F2FS_FS=m +CONFIG_F2FS_FS_SECURITY=y +CONFIG_F2FS_FS_COMPRESSION=y +CONFIG_F2FS_UNFAIR_RWSEM=y +CONFIG_ZONEFS_FS=m +CONFIG_FS_DAX=y +CONFIG_FS_ENCRYPTION=y +CONFIG_FS_VERITY=y +CONFIG_FANOTIFY=y +CONFIG_FANOTIFY_ACCESS_PERMISSIONS=y +CONFIG_QUOTA_NETLINK_INTERFACE=y +CONFIG_QFMT_V2=y +CONFIG_AUTOFS_FS=y +CONFIG_FUSE_FS=m +CONFIG_CUSE=m +CONFIG_VIRTIO_FS=m +CONFIG_OVERLAY_FS=m +CONFIG_FSCACHE_STATS=y +CONFIG_CACHEFILES=m +CONFIG_ISO9660_FS=m +CONFIG_JOLIET=y +CONFIG_ZISOFS=y +CONFIG_UDF_FS=m +CONFIG_MSDOS_FS=m +CONFIG_VFAT_FS=m +CONFIG_FAT_DEFAULT_IOCHARSET="ascii" +CONFIG_EXFAT_FS=m +CONFIG_NTFS3_FS=m +CONFIG_NTFS3_LZX_XPRESS=y +CONFIG_NTFS3_FS_POSIX_ACL=y +CONFIG_PROC_KCORE=y +CONFIG_PROC_VMCORE_DEVICE_DUMP=y +CONFIG_TMPFS_POSIX_ACL=y +CONFIG_TMPFS_INODE64=y +CONFIG_TMPFS_QUOTA=y +CONFIG_HUGETLBFS=y +CONFIG_EFIVAR_FS=y +CONFIG_ORANGEFS_FS=m +CONFIG_ECRYPT_FS=m +CONFIG_HFS_FS=m +CONFIG_HFSPLUS_FS=m +CONFIG_JFFS2_FS=m +CONFIG_JFFS2_SUMMARY=y +CONFIG_JFFS2_FS_XATTR=y +CONFIG_UBIFS_FS=m +CONFIG_UBIFS_ATIME_SUPPORT=y +CONFIG_UBIFS_FS_AUTHENTICATION=y +CONFIG_SQUASHFS=m +CONFIG_SQUASHFS_FILE_DIRECT=y +CONFIG_SQUASHFS_COMPILE_DECOMP_MULTI_PERCPU=y +CONFIG_SQUASHFS_XATTR=y +CONFIG_SQUASHFS_LZ4=y +CONFIG_SQUASHFS_LZO=y +CONFIG_SQUASHFS_XZ=y +CONFIG_SQUASHFS_ZSTD=y +CONFIG_MINIX_FS=m +CONFIG_ROMFS_FS=m +CONFIG_PSTORE_RAM=m +CONFIG_UFS_FS=m +CONFIG_EROFS_FS=m +CONFIG_EROFS_FS_ZIP_DEFLATE=y +CONFIG_EROFS_FS_ZIP_ZSTD=y +CONFIG_EROFS_FS_ZIP_ACCEL=y +CONFIG_VBOXSF_FS=m +CONFIG_NFS_FS=m +CONFIG_NFS_V3_ACL=y +CONFIG_NFS_V4=m +CONFIG_NFS_SWAP=y +CONFIG_NFS_V4_2=y +CONFIG_NFS_FSCACHE=y +# CONFIG_NFS_V4_2_READ_PLUS is not set +CONFIG_NFSD=m +CONFIG_NFSD_V3_ACL=y +CONFIG_NFSD_V4=y +CONFIG_NFSD_BLOCKLAYOUT=y +CONFIG_NFSD_SCSILAYOUT=y +CONFIG_NFSD_FLEXFILELAYOUT=y +CONFIG_NFSD_V4_2_INTER_SSC=y +CONFIG_NFSD_V4_SECURITY_LABEL=y +CONFIG_NFSD_V4_POSIX_ACLS=y +CONFIG_NFS_LOCALIO=y +CONFIG_SUNRPC_DEBUG=y +CONFIG_CEPH_FS=m +CONFIG_CEPH_FSCACHE=y +CONFIG_CEPH_FS_POSIX_ACL=y +CONFIG_CEPH_FS_SECURITY_LABEL=y +CONFIG_CIFS=m +# CONFIG_CIFS_STATS2 is not set +CONFIG_CIFS_UPCALL=y +CONFIG_CIFS_XATTR=y +CONFIG_CIFS_POSIX=y +CONFIG_CIFS_DFS_UPCALL=y +CONFIG_CIFS_SWN_UPCALL=y +CONFIG_CIFS_FSCACHE=y +# CONFIG_SMB_KUNIT_TESTS is not set +CONFIG_AFS_FS=m +CONFIG_AFS_DEBUG=y +CONFIG_AFS_FSCACHE=y +CONFIG_9P_FS=m +CONFIG_9P_FSCACHE=y +CONFIG_9P_FS_POSIX_ACL=y +CONFIG_9P_FS_SECURITY=y +CONFIG_NLS_DEFAULT="utf8" +CONFIG_NLS_CODEPAGE_437=y +CONFIG_NLS_CODEPAGE_737=m +CONFIG_NLS_CODEPAGE_775=m +CONFIG_NLS_CODEPAGE_850=m +CONFIG_NLS_CODEPAGE_852=m +CONFIG_NLS_CODEPAGE_855=m +CONFIG_NLS_CODEPAGE_857=m +CONFIG_NLS_CODEPAGE_860=m +CONFIG_NLS_CODEPAGE_861=m +CONFIG_NLS_CODEPAGE_862=m +CONFIG_NLS_CODEPAGE_863=m +CONFIG_NLS_CODEPAGE_864=m +CONFIG_NLS_CODEPAGE_865=m +CONFIG_NLS_CODEPAGE_866=m +CONFIG_NLS_CODEPAGE_869=m +CONFIG_NLS_CODEPAGE_936=m +CONFIG_NLS_CODEPAGE_950=m +CONFIG_NLS_CODEPAGE_932=m +CONFIG_NLS_CODEPAGE_949=m +CONFIG_NLS_CODEPAGE_874=m +CONFIG_NLS_ISO8859_8=m +CONFIG_NLS_CODEPAGE_1250=m +CONFIG_NLS_CODEPAGE_1251=m +CONFIG_NLS_ASCII=y +CONFIG_NLS_ISO8859_1=m +CONFIG_NLS_ISO8859_2=m +CONFIG_NLS_ISO8859_3=m +CONFIG_NLS_ISO8859_4=m +CONFIG_NLS_ISO8859_5=m +CONFIG_NLS_ISO8859_6=m +CONFIG_NLS_ISO8859_7=m +CONFIG_NLS_ISO8859_9=m +CONFIG_NLS_ISO8859_13=m +CONFIG_NLS_ISO8859_14=m +CONFIG_NLS_ISO8859_15=m +CONFIG_NLS_KOI8_R=m +CONFIG_NLS_KOI8_U=m +CONFIG_NLS_MAC_ROMAN=m +CONFIG_NLS_MAC_CELTIC=m +CONFIG_NLS_MAC_CENTEURO=m +CONFIG_NLS_MAC_CROATIAN=m +CONFIG_NLS_MAC_CYRILLIC=m +CONFIG_NLS_MAC_GAELIC=m +CONFIG_NLS_MAC_GREEK=m +CONFIG_NLS_MAC_ICELAND=m +CONFIG_NLS_MAC_INUIT=m +CONFIG_NLS_MAC_ROMANIAN=m +CONFIG_NLS_MAC_TURKISH=m +CONFIG_DLM=m +CONFIG_DLM_DEBUG=y +CONFIG_UNICODE=y +CONFIG_KEYS_REQUEST_CACHE=y +CONFIG_PERSISTENT_KEYRINGS=y +CONFIG_BIG_KEYS=y +CONFIG_TRUSTED_KEYS=y +# CONFIG_TRUSTED_KEYS_TPM is not set +CONFIG_KEY_DH_OPERATIONS=y +CONFIG_KEY_NOTIFICATIONS=y +CONFIG_SECURITY_DMESG_RESTRICT=y +CONFIG_PROC_MEM_ALWAYS_FORCE=y +CONFIG_SECURITY=y +CONFIG_SECURITY_INFINIBAND=y +CONFIG_SECURITY_NETWORK_XFRM=y +CONFIG_LSM_MMAP_MIN_ADDR=65535 +CONFIG_SECURITY_SELINUX=y +CONFIG_SECURITY_SELINUX_BOOTPARAM=y +CONFIG_SECURITY_TOMOYO=y +CONFIG_SECURITY_TOMOYO_ACTIVATION_TRIGGER="/usr/lib/systemd/systemd" +CONFIG_SECURITY_YAMA=y +CONFIG_SECURITY_LOCKDOWN_LSM=y +CONFIG_SECURITY_LOCKDOWN_LSM_EARLY=y +CONFIG_SECURITY_LANDLOCK=y +CONFIG_SECURITY_IPE=y +CONFIG_INTEGRITY_SIGNATURE=y +CONFIG_INTEGRITY_ASYMMETRIC_KEYS=y +CONFIG_INTEGRITY_PLATFORM_KEYRING=y +CONFIG_INTEGRITY_MACHINE_KEYRING=y +CONFIG_INTEGRITY_CA_MACHINE_KEYRING=y +CONFIG_INTEGRITY_CA_MACHINE_KEYRING_MAX=y +CONFIG_IMA=y +CONFIG_IMA_KEXEC=y +CONFIG_IMA_DEFAULT_HASH_SHA256=y +CONFIG_IMA_WRITE_POLICY=y +CONFIG_IMA_APPRAISE=y +CONFIG_IMA_ARCH_POLICY=y +CONFIG_IMA_APPRAISE_MODSIG=y +CONFIG_IMA_KEYRINGS_PERMIT_SIGNED_BY_BUILTIN_OR_SECONDARY=y +CONFIG_EVM=y +CONFIG_LSM="lockdown,yama,integrity,selinux,bpf,landlock,ipe" +CONFIG_INIT_ON_ALLOC_DEFAULT_ON=y +CONFIG_FORTIFY_SOURCE=y +CONFIG_HARDENED_USERCOPY=y +CONFIG_BUG_ON_DATA_CORRUPTION=y +CONFIG_CRYPTO_FIPS=y +CONFIG_CRYPTO_USER=m +CONFIG_CRYPTO_SELFTESTS=y +CONFIG_CRYPTO_NULL=y +CONFIG_CRYPTO_PCRYPT=m +CONFIG_CRYPTO_CRYPTD=y +CONFIG_CRYPTO_AUTHENC=y +CONFIG_CRYPTO_BENCHMARK=m +CONFIG_CRYPTO_ECDSA=y +CONFIG_CRYPTO_ECRDSA=m +CONFIG_CRYPTO_BLOWFISH=m +CONFIG_CRYPTO_CAST5=m +CONFIG_CRYPTO_CAST6=m +CONFIG_CRYPTO_SERPENT=m +CONFIG_CRYPTO_TWOFISH=m +CONFIG_CRYPTO_ADIANTUM=m +CONFIG_CRYPTO_HCTR2=m +CONFIG_CRYPTO_LRW=m +CONFIG_CRYPTO_AEGIS128=m +CONFIG_CRYPTO_CCM=y +CONFIG_CRYPTO_GCM=y +CONFIG_CRYPTO_SEQIV=y +CONFIG_CRYPTO_BLAKE2B=y +CONFIG_CRYPTO_CMAC=y +CONFIG_CRYPTO_MD4=m +CONFIG_CRYPTO_MD5=y +CONFIG_CRYPTO_RMD160=m +CONFIG_CRYPTO_SHA3=y +CONFIG_CRYPTO_WP512=m +CONFIG_CRYPTO_XCBC=m +CONFIG_CRYPTO_XXHASH=y +CONFIG_CRYPTO_CRC32C=y +CONFIG_CRYPTO_CRC32=m +CONFIG_CRYPTO_DEFLATE=y +CONFIG_CRYPTO_842=y +CONFIG_CRYPTO_LZ4HC=m +CONFIG_CRYPTO_DRBG=y +CONFIG_CRYPTO_JITTERENTROPY_OSR=1 +CONFIG_CRYPTO_USER_API_HASH=y +CONFIG_CRYPTO_USER_API_SKCIPHER=y +CONFIG_CRYPTO_USER_API_RNG=y +CONFIG_CRYPTO_USER_API_AEAD=y +# CONFIG_CRYPTO_USER_API_ENABLE_OBSOLETE is not set +CONFIG_CRYPTO_GHASH_ARM64_CE=m +CONFIG_CRYPTO_AES_ARM64_NEON_BLK=y +CONFIG_CRYPTO_AES_ARM64_BS=m +CONFIG_CRYPTO_AES_ARM64_CE_CCM=y +CONFIG_CRYPTO_DEV_SUN4I_SS=m +CONFIG_CRYPTO_DEV_SUN8I_CE=m +CONFIG_CRYPTO_DEV_SUN8I_CE_HASH=y +CONFIG_CRYPTO_DEV_SUN8I_CE_TRNG=y +CONFIG_CRYPTO_DEV_SUN8I_SS=m +CONFIG_CRYPTO_DEV_SUN8I_SS_HASH=y +CONFIG_CRYPTO_DEV_FSL_CAAM=m +CONFIG_CRYPTO_DEV_FSL_CAAM_RINGSIZE=3 +CONFIG_CRYPTO_DEV_FSL_CAAM_INTC=y +CONFIG_CRYPTO_DEV_FSL_CAAM_INTC_COUNT_THLD=8 +CONFIG_CRYPTO_DEV_FSL_CAAM_INTC_TIME_THLD=8192 +CONFIG_CRYPTO_DEV_FSL_DPAA2_CAAM=m +CONFIG_CRYPTO_DEV_ATMEL_ECC=m +CONFIG_CRYPTO_DEV_ATMEL_SHA204A=m +CONFIG_CRYPTO_DEV_CCP=y +CONFIG_CAVIUM_CPT=m +CONFIG_CRYPTO_DEV_NITROX_CNN55XX=m +CONFIG_CRYPTO_DEV_MARVELL_CESA=m +CONFIG_CRYPTO_DEV_OCTEONTX_CPT=m +CONFIG_CRYPTO_DEV_OCTEONTX2_CPT=m +CONFIG_CRYPTO_DEV_QAT_DH895xCC=m +CONFIG_CRYPTO_DEV_QAT_C3XXX=m +CONFIG_CRYPTO_DEV_QAT_C62X=m +CONFIG_CRYPTO_DEV_QAT_4XXX=m +CONFIG_CRYPTO_DEV_QAT_420XX=m +CONFIG_CRYPTO_DEV_QAT_DH895xCCVF=m +CONFIG_CRYPTO_DEV_QAT_C3XXXVF=m +CONFIG_CRYPTO_DEV_QAT_C62XVF=m +CONFIG_CRYPTO_DEV_ROCKCHIP=m +CONFIG_CRYPTO_DEV_TEGRA=m +CONFIG_CRYPTO_DEV_ZYNQMP_AES=m +CONFIG_CRYPTO_DEV_ZYNQMP_SHA3=m +CONFIG_CRYPTO_DEV_CHELSIO=m +CONFIG_CRYPTO_DEV_VIRTIO=m +CONFIG_CRYPTO_DEV_SAFEXCEL=m +CONFIG_CRYPTO_DEV_HISI_HPRE=m +CONFIG_CRYPTO_DEV_AMLOGIC_GXL=y +CONFIG_CRYPTO_DEV_APPLE_SIO_AES=m +CONFIG_CRYPTO_DEV_SA2UL=m +CONFIG_CRYPTO_DEV_TI_DTHEV2=m +CONFIG_PKCS8_PRIVATE_KEY_PARSER=m +CONFIG_SIGNED_PE_FILE_VERIFICATION=y +CONFIG_SYSTEM_EXTRA_CERTIFICATE=y +CONFIG_SECONDARY_TRUSTED_KEYRING=y +CONFIG_SYSTEM_BLACKLIST_KEYRING=y +CONFIG_SYSTEM_BLACKLIST_AUTH_UPDATE=y +# CONFIG_RAID6_PQ_BENCHMARK is not set +CONFIG_DMA_NUMA_CMA=y +CONFIG_CMA_SIZE_MBYTES=64 +CONFIG_PRINTK_TIME=y +CONFIG_CONSOLE_LOGLEVEL_QUIET=3 +CONFIG_BOOT_PRINTK_DELAY=y +CONFIG_DYNAMIC_DEBUG=y +# CONFIG_DEBUG_MISC is not set +CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT=y +CONFIG_DEBUG_INFO_BTF=y +CONFIG_STRIP_ASM_SYMS=y +CONFIG_HEADERS_INSTALL=y +CONFIG_MAGIC_SYSRQ_DEFAULT_ENABLE=0x0 +CONFIG_KGDB=y +CONFIG_KGDB_TESTS=y +CONFIG_UBSAN=y +CONFIG_UBSAN_SHIFT=y +# CONFIG_UBSAN_BOOL is not set +# CONFIG_UBSAN_ENUM is not set +CONFIG_UBSAN_KVM_EL2=y +CONFIG_PAGE_OWNER=y +CONFIG_PAGE_POISONING=y +CONFIG_DEBUG_WX=y +CONFIG_SCHED_STACK_END_CHECK=y +CONFIG_DEBUG_MEMORY_INIT=y +CONFIG_KFENCE=y +CONFIG_DEBUG_SHIRQ=y +CONFIG_SOFTLOCKUP_DETECTOR_INTR_STORM=y +CONFIG_HARDLOCKUP_DETECTOR=y +CONFIG_TEST_LOCKUP=m +CONFIG_LOCK_TORTURE_TEST=m +CONFIG_DEBUG_LIST=y +CONFIG_RCU_TORTURE_TEST=m +CONFIG_RCU_CPU_STALL_TIMEOUT=60 +CONFIG_LATENCYTOP=y +CONFIG_BOOTTIME_TRACING=y +CONFIG_FUNCTION_GRAPH_RETVAL=y +CONFIG_FPROBE=y +CONFIG_FUNCTION_PROFILER=y +CONFIG_STACK_TRACER=y +CONFIG_SCHED_TRACER=y +CONFIG_HWLAT_TRACER=y +CONFIG_TIMERLAT_TRACER=y +CONFIG_FTRACE_SYSCALLS=y +CONFIG_BLK_DEV_IO_TRACE=y +CONFIG_HIST_TRIGGERS=y +CONFIG_RING_BUFFER_BENCHMARK=m +CONFIG_TRACE_EVAL_MAP_FILE=y +CONFIG_RV=y +CONFIG_RV_PER_TASK_MONITORS=3 +CONFIG_RV_MON_WWNR=y +CONFIG_RV_MON_SCHED=y +CONFIG_IO_STRICT_DEVMEM=y +CONFIG_CORESIGHT=m +CONFIG_CORESIGHT_LINK_AND_SINK_TMC=m +CONFIG_CORESIGHT_CATU=m +CONFIG_CORESIGHT_SINK_TPIU=m +CONFIG_CORESIGHT_SINK_ETBV10=m +CONFIG_CORESIGHT_SOURCE_ETM4X=m +CONFIG_CORESIGHT_STM=m +CONFIG_CORESIGHT_CTCU=m +CONFIG_CORESIGHT_CPU_DEBUG=m +CONFIG_CORESIGHT_CTI=m +CONFIG_CORESIGHT_TRBE=m +CONFIG_ULTRASOC_SMB=m +CONFIG_CORESIGHT_TPDM=m +CONFIG_CORESIGHT_TNOC=m +CONFIG_KUNIT=m +# CONFIG_KUNIT_FAULT_TEST is not set +CONFIG_KUNIT_ALL_TESTS=m +# CONFIG_KUNIT_DEFAULT_ENABLED is not set +# CONFIG_TEST_LIST_SORT is not set +CONFIG_ATOMIC64_SELFTEST=y +CONFIG_ASYNC_RAID6_TEST=m +CONFIG_TEST_KSTRTOX=y +CONFIG_TEST_VMALLOC=m +CONFIG_TEST_BPF=m +CONFIG_LINEAR_RANGES_TEST=m +CONFIG_TEST_KMOD=m +CONFIG_TEST_HMM=m +CONFIG_MEMTEST=y diff --git a/arch/arm64/include/asm/apple-idle.h b/arch/arm64/include/asm/apple-idle.h index 619882f65d636e..62667f44becb7e 100644 --- a/arch/arm64/include/asm/apple-idle.h +++ b/arch/arm64/include/asm/apple-idle.h @@ -6,8 +6,13 @@ void apple_cpu_wfi(void); #ifdef CONFIG_ARCH_APPLE +#include + /* Called from smp_prepare_boot_cpu(): before the boot CPU's first idle. */ void apple_wfi_quirk_init(void); + +/* Set by the Apple CPU PMU driver while events are counting on this CPU. */ +DECLARE_PER_CPU(bool, apple_pmu_wfi_freeze); #else static inline void apple_wfi_quirk_init(void) { } #endif diff --git a/arch/arm64/include/asm/cputype.h b/arch/arm64/include/asm/cputype.h index 8215a3b1dac4ee..9fe3c491c96074 100644 --- a/arch/arm64/include/asm/cputype.h +++ b/arch/arm64/include/asm/cputype.h @@ -296,7 +296,31 @@ static inline u32 __attribute_const__ read_cpuid_id(void) return read_cpuid(MIDR_EL1); } -/* Apple part numbers from Donan onward identify the M4 and later generations. */ +/* + * Apple part numbers from Donan onward identify the M4 and later generations. + * + * These cores can come back from WFI and WFIT with their general-purpose and + * FP/SIMD registers cleared; SP and memory survive. On M1 to M3 the boot + * loader sets the cores up to keep that state in WFI (CYC_OVRD); from M4 on + * that register is locked before the kernel runs. The kernel keeps the state + * itself on every part matched here: cpu_do_idle() saves it around WFI, and + * WFxT is recorded as absent so that nothing executes WFIT. Neither idle=nop + * nor arm64.nowfxt is needed. + * + * Seen on: + * 0x054/0x055 T6040 (M4 Pro, J616s): the boot P core in WFI. + * 0x060/0x061 T8140 (A18 Pro, J700): the secondaries in WFI and WFIT. + * 0x062/0x063 T8142 (M5, J813): WFI in the idle loop, WFIT in a cpufreq + * __delay(). + * 0x064/0x065 T6050 (M5 Pro/Max, J714s/J716s): WFI. + * 0x072/0x073 T8152 (M6, J873): WFI at the first idle; WFIT under + * schedutil gave wrong SHA-256 results. + * Not measured separately, matched as the same core generations: 0x052/0x053 + * T8132 (M4), 0x058/0x059 T6041 (M4 Max), 0x068/0x069 and 0x06c/0x06d (M5 + * Pro/Max/Ultra variants). Later parts are matched as well: where the state + * would have survived, the save costs a few stores per idle entry; where it + * does not, a missing save corrupts the idle loop. + */ static inline bool midr_is_apple_m4_or_later(u32 midr) { return MIDR_IMPLEMENTOR(midr) == ARM_CPU_IMP_APPLE && diff --git a/arch/arm64/kernel/cpufeature.c b/arch/arm64/kernel/cpufeature.c index 4e5ae7bf52b06a..3d245b3213acdd 100644 --- a/arch/arm64/kernel/cpufeature.c +++ b/arch/arm64/kernel/cpufeature.c @@ -2627,40 +2627,6 @@ test_has_gicv5_legacy(const struct arm64_cpu_capabilities *entry, int scope) return !!(read_sysreg_s(SYS_ICC_IDR0_EL1) & ICC_IDR0_EL1_GCIE_LEGACY); } -/* - * Apple T8152 (M6) cores clear architectural state across WFIT, the FP/SIMD - * registers included. __delay() would execute it from any context, including - * the cpufreq transition polling that load-driven governors run on a CPU - * whose current task still has live FP/SIMD state: on J873 (M6) 25-56% of - * SHA-256 runs gave wrong results under schedutil. Treat WFxT as absent - * there, as arm64.nowfxt does, so __delay() uses WFE. T8142 (M5) was not - * measured; it is included because apple_m5_needs_wait_save() groups its - * cores with T8152 for this state loss. - * - * T6050 (M5 Pro and Max, parts 0x064 and 0x065) was not measured for the WFIT - * state loss either. On the K116s, at EL1 under the boot loader's monitor, - * ID_AA64ISAR2_EL1.WFxT reads 0, so the capability is not set there today - * with or without these entries, and __delay() already avoids WFIT on these - * cores by MIDR. The entries are a precaution for a kernel started at EL2, - * where the field may read as implemented. - */ -static bool has_wfxt(const struct arm64_cpu_capabilities *entry, int scope) -{ - static const struct midr_range apple_wfxt_loses_state[] = { - MIDR_ALL_VERSIONS(MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_T8142_E)), - MIDR_ALL_VERSIONS(MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_T8142_P)), - MIDR_ALL_VERSIONS(MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_T6050_064)), - MIDR_ALL_VERSIONS(MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_T6050_065)), - MIDR_ALL_VERSIONS(MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_T8152_E)), - MIDR_ALL_VERSIONS(MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_T8152_P)), - {} - }; - - if (is_midr_in_range_list(apple_wfxt_loses_state)) - return false; - return has_cpuid_feature(entry, scope); -} - static const struct arm64_cpu_capabilities arm64_features[] = { #ifdef CONFIG_ARM64_USER4K_EXPERIMENTAL { @@ -3165,7 +3131,7 @@ static const struct arm64_cpu_capabilities arm64_features[] = { .desc = "WFx with timeout", .capability = ARM64_HAS_WFXT, .type = ARM64_CPUCAP_SYSTEM_FEATURE, - .matches = has_wfxt, + .matches = has_cpuid_feature, ARM64_CPUID_FIELDS(ID_AA64ISAR2_EL1, WFxT, IMP) }, { @@ -3529,8 +3495,7 @@ static const struct arm64_cpu_capabilities arm64_elf_hwcaps[] = { HWCAP_CAP(ID_AA64ISAR2_EL1, CSSC, CMPBR, CAP_HWCAP, KERNEL_HWCAP_CMPBR), HWCAP_CAP(ID_AA64ISAR2_EL1, RPRFM, IMP, CAP_HWCAP, KERNEL_HWCAP_RPRFM), HWCAP_CAP(ID_AA64ISAR2_EL1, RPRES, IMP, CAP_HWCAP, KERNEL_HWCAP_RPRES), - /* WFxT loses state on apple_wfxt_loses_state parts; hide the hwcap there too. */ - HWCAP_CAP_MATCH_ID(has_wfxt, ID_AA64ISAR2_EL1, WFxT, IMP, CAP_HWCAP, KERNEL_HWCAP_WFXT), + HWCAP_CAP(ID_AA64ISAR2_EL1, WFxT, IMP, CAP_HWCAP, KERNEL_HWCAP_WFXT), HWCAP_CAP(ID_AA64ISAR2_EL1, MOPS, IMP, CAP_HWCAP, KERNEL_HWCAP_MOPS), HWCAP_CAP(ID_AA64ISAR2_EL1, BC, IMP, CAP_HWCAP, KERNEL_HWCAP_HBC), #ifdef CONFIG_ARM64_SME diff --git a/arch/arm64/kernel/cpuinfo.c b/arch/arm64/kernel/cpuinfo.c index 006cec695867df..f93f4e8782dc5c 100644 --- a/arch/arm64/kernel/cpuinfo.c +++ b/arch/arm64/kernel/cpuinfo.c @@ -551,9 +551,10 @@ static void __cpuinfo_store_cpu(struct cpuinfo_arm64 *info) info->reg_id_aa64isar2 = read_cpuid(ID_AA64ISAR2_EL1); /* * Timed waits bypass the register-saving idle path on Apple M4 and - * later cores. Record WFxT as absent on every CPU, so the sanitised - * register hides it from the kernel, KVM guests and userspace - * (HWCAP2_WFXT) and a boot argument cannot bring it back. + * later cores, and lose the same state there (see + * midr_is_apple_m4_or_later()). Record WFxT as absent on every CPU, + * so the sanitised register hides it from the kernel, KVM guests and + * userspace (HWCAP2_WFXT) and a boot argument cannot bring it back. */ if (IS_ENABLED(CONFIG_ARCH_APPLE) && midr_is_apple_m4_or_later(info->reg_midr)) diff --git a/arch/arm64/kernel/fpsimd.c b/arch/arm64/kernel/fpsimd.c index e7f1682a3059b5..aad17c3b44430a 100644 --- a/arch/arm64/kernel/fpsimd.c +++ b/arch/arm64/kernel/fpsimd.c @@ -1571,7 +1571,7 @@ static void fpsimd_flush_cpu_state(void) * NEON and leaving streaming mode or ZA enabled may increase power * consumption. */ - if (system_supports_sme()) + if (system_supports_sme() && read_sysreg_s(SYS_SVCR)) sme_smstop(); set_thread_flag(TIF_FOREIGN_FPSTATE); diff --git a/arch/arm64/kernel/idle.c b/arch/arm64/kernel/idle.c index 0d76030f78205b..a55e4f6144e09f 100644 --- a/arch/arm64/kernel/idle.c +++ b/arch/arm64/kernel/idle.c @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -51,10 +52,12 @@ early_param("idle", setup_idle); */ static bool apple_wfi_loses_regs __ro_after_init; static bool apple_keep_idle_nop __initdata; +static bool apple_wfi_deferred __initdata; /* - * The boot loader appends idle=nop after the user's arguments, so it cannot - * be overridden on the command line. This flag keeps it anyway. + * Older boot loaders append idle=nop after the user's arguments on these + * cores, so it cannot be overridden on the command line, and it is ignored + * below. This flag keeps it anyway, for comparisons. */ static int __init setup_apple_keep_idle_nop(char *arg) { @@ -65,36 +68,83 @@ early_param("apple_keep_idle_nop", setup_apple_keep_idle_nop); void __init apple_wfi_quirk_init(void) { - u32 model = read_cpuid_id() & MIDR_CPU_MODEL_MASK; + if (!midr_is_apple_m4_or_later(read_cpuid_id())) + return; + + apple_wfi_loses_regs = true; + pr_info("Apple: preserving registers across WFI\n"); - if (midr_is_apple_m4_or_later(read_cpuid_id())) { - apple_wfi_loses_regs = true; - pr_info("Apple: preserving registers across WFI\n"); - } /* - * aura (J813) and m1n1 (T6050) pass idle=nop on M4 and later for - * kernels without this quirk. Spinning idle keeps every core busy - * (cpuidle's WFI states spin too): on T8142 the SoC sits near 90 C - * and throttles, on T6050 the system draws about 10 W more at idle. - * WFI is safe here. + * aura and m1n1 used to pass idle=nop on M4 and later for kernels + * without this path. Spinning idle keeps every core busy (cpuidle's + * WFI states spin too): on T8142 the SoC sits near 90 C and + * throttles, on T6050 the system draws about 10 W more at idle, on + * T8140 the die idles at 85-92 C instead of 43 C. WFI is safe here. + * + * The switch waits until the built-in drivers have probed: on a + * K114c (M5 Max, chip 0x6050), WFI early in boot gated the unclaimed + * root domain nub_gpio off before pmgr and pinctrl probed. */ - if (idle == ARM64_IDLE_NOP && !apple_keep_idle_nop && - (model == MIDR_APPLE_T8142_E || model == MIDR_APPLE_T8142_P || - model == MIDR_APPLE_T6050_064 || model == MIDR_APPLE_T6050_065)) { - idle = ARM64_IDLE_WFI; - pr_info("Apple: idling in WFI, ignoring idle=nop\n"); + if (idle == ARM64_IDLE_NOP && !apple_keep_idle_nop) { + apple_wfi_deferred = true; + pr_info("Apple: WFI idling deferred until built-in drivers probe\n"); } } +/* + * Runs after the built-in drivers' initcalls. cpu_do_idle() reads idle on + * every entry, so the switch takes effect at once. + */ +static int __init apple_wfi_defer_enable(void) +{ + if (!apple_wfi_deferred) + return 0; + + idle = ARM64_IDLE_WFI; + pr_info("Apple: idling in WFI, ignoring idle=nop (after built-in probes)\n"); + return 0; +} +late_initcall_sync(apple_wfi_defer_enable); + static __always_inline bool apple_wfi_needs_save(void) { return unlikely(READ_ONCE(apple_wfi_loses_regs)); } + +DEFINE_PER_CPU(bool, apple_pmu_wfi_freeze); +EXPORT_PER_CPU_SYMBOL_GPL(apple_pmu_wfi_freeze); + +/* + * On M4 and later Apple cores some cycle counters keep counting in WFI + * (for example, M5 Max Sawtooth cores at about 1.5 GHz), which inflates + * CPU-wide perf counts with idle time. Freeze the counters and their + * interrupt across WFI whenever perf events are active on this CPU. + */ +static __always_inline void apple_wfi(void) +{ + /* Idle runs with preemption disabled: the raw accessor is enough. */ + if (unlikely(__this_cpu_read(apple_pmu_wfi_freeze))) { + u64 pmcr0 = read_sysreg_s(SYS_IMP_APL_PMCR0_EL1); + + write_sysreg_s(pmcr0 & ~(PMCR0_CNT_ENABLE_0_7 | + PMCR0_CNT_ENABLE_8_9 | + PMCR0_IMODE), + SYS_IMP_APL_PMCR0_EL1); + isb(); + apple_cpu_wfi(); + write_sysreg_s(pmcr0, SYS_IMP_APL_PMCR0_EL1); + isb(); + } else { + apple_cpu_wfi(); + } +} #else static __always_inline bool apple_wfi_needs_save(void) { return false; } + +static __always_inline void apple_wfi(void) { } #endif /* @@ -120,7 +170,7 @@ void __cpuidle cpu_do_idle(void) * them, even when the same task resumes on this CPU. */ fpsimd_save_and_flush_cpu_state(); - apple_cpu_wfi(); + apple_wfi(); } else { dsb(sy); wfi(); diff --git a/arch/arm64/kernel/smp.c b/arch/arm64/kernel/smp.c index f6b5decff53da5..f383d15a104cf0 100644 --- a/arch/arm64/kernel/smp.c +++ b/arch/arm64/kernel/smp.c @@ -139,8 +139,17 @@ int __cpu_up(unsigned int cpu, struct task_struct *idle) */ wait_for_completion_timeout(&cpu_running, msecs_to_jiffies(5000)); - if (cpu_online(cpu)) + if (cpu_online(cpu)) { + /* + * The CPU has taken its task. Cleared, as kernels before 5.x did, so a core that + * reaches __secondary_switched without a bring-up of its own waits in + * __secondary_too_slow instead of running as this CPU a second time. + */ + WRITE_ONCE(secondary_data.task, NULL); + dcache_clean_inval_poc((unsigned long)&secondary_data, + (unsigned long)&secondary_data + sizeof(secondary_data)); return 0; + } pr_crit("CPU%u: failed to come online\n", cpu); secondary_data.task = NULL; diff --git a/arch/arm64/kernel/smp_spin_table.c b/arch/arm64/kernel/smp_spin_table.c index e66806dbbf9c5d..0d0f200e3de6a8 100644 --- a/arch/arm64/kernel/smp_spin_table.c +++ b/arch/arm64/kernel/smp_spin_table.c @@ -222,6 +222,9 @@ int spin_table_hold_parked(void) int us, ret; unsigned int cpu; + /* No CPU restarted from here to the wake may pass the pen without its own bring-up. */ + write_pen_release(INVALID_HWID); + for_each_present_cpu(cpu) WRITE_ONCE(spin_table_hold_error[cpu], 0); WRITE_ONCE(spin_table_hold_generation, READ_ONCE(spin_table_hold_generation) + 1); @@ -331,6 +334,8 @@ void spin_table_stop_finished(void) /* Before any CPU is started again: the pen must let them boot. */ if (secondary_pen_deep) spin_table_pen_deep_set(0); + /* ...but only the one its bring-up releases (cores started early wait in the pen). */ + write_pen_release(INVALID_HWID); WRITE_ONCE(spin_table_hold_requested, false); WRITE_ONCE(spin_table_stop_requested, false); WRITE_ONCE(spin_table_stop_released, false); @@ -473,6 +478,14 @@ static int smp_rvbar_spin_table_cpu_kill(unsigned int cpu) static void smp_rvbar_spin_table_postboot(void) { + /* + * Close the pen behind this CPU. Left at its MPIDR, the next restart at the reset vector + * (after a sleep's commit, or a platform that starts every core at once at the wake) + * lets it straight through the pen into secondary_startup ahead of its own bring-up, + * with the secondary_data of its last boot: it then runs as that CPU with no STARTING + * callbacks run, e.g. without a tick device. + */ + write_pen_release(INVALID_HWID); cpumask_clear_cpu(smp_processor_id(), &spin_table_cpus_off); if (READ_ONCE(spin_table_power) && spin_table_power->cpu_restore) spin_table_power->cpu_restore(read_cpuid_mpidr() & MPIDR_HWID_BITMASK); diff --git a/arch/arm64/lib/delay.c b/arch/arm64/lib/delay.c index 591c2552147724..e278e060e78a9e 100644 --- a/arch/arm64/lib/delay.c +++ b/arch/arm64/lib/delay.c @@ -14,7 +14,6 @@ #include #include -#include #define USECS_TO_CYCLES(time_usecs) \ xloops_to_cycles((time_usecs) * 0x10C7UL) @@ -43,19 +42,6 @@ void __delay(unsigned long cycles) { cycles_t start = __delay_cycles(); - /* - * T8142 and T6050 can clear registers on WFIT just as it does on WFI. A delay - * may run with live kernel SIMD state, so the idle task's save/flush - * path is not applicable here. Keep the core awake for short delays. - */ - if (IS_ENABLED(CONFIG_ARCH_APPLE)) { - u32 midr = read_cpuid_id() & MIDR_CPU_MODEL_MASK; - - if (midr == MIDR_APPLE_T8142_E || midr == MIDR_APPLE_T8142_P || - midr == MIDR_APPLE_T6050_064 || midr == MIDR_APPLE_T6050_065) - goto counter_delay; - } - if (alternative_has_cap_unlikely(ARM64_HAS_WFXT)) { u64 end = start + cycles; @@ -74,7 +60,6 @@ void __delay(unsigned long cycles) wfe(); } -counter_delay: while ((__delay_cycles() - start) < cycles) cpu_relax(); } diff --git a/carry.toml b/carry.toml index 722272d6a2c53d..b26b80412baaeb 100644 --- a/carry.toml +++ b/carry.toml @@ -12,119 +12,78 @@ # commits an explicit subset of the PR's commits, in order (overrides after) # upstream ours only: where it is meant to go upstream, and what is blocking that # closed_ok a recorded decision to keep carrying a PR that upstream closed (S7) +# merge true: carry the PR head as one merge commit instead of picking its commits, when its +# branch already merges upstream and the author's resolution should be reused package = "linux" series = "7.3" series_check = "kernel-makefile" [upstream] repo = "https://github.com/aurora-silicon/linux.git" -ref = "integration/aurora" -intake = "00cbc67d1a0cb9212d4228961db6a02b95e75b24" +ref = "main" +intake = "4a42f31050028aa7b9e5dc007e7ea231acc66356" [inputs] repo = "https://github.com/omacom/linux-aurora.git" -[[carry]] -pr = "aurora-silicon/linux#2145" -commit = "4e3334872df8d6e618c7089ab7e87a3c68760508" -why = "DART: common scanout aperture before init" - [[carry]] pr = "aurora-silicon/linux#2146" -commit = "147001c39e7f4e0efce47d1e139641abfa791add" +commit = "89faf622777e5d0d562641d96fd74a5e36c6b636" +merge = true why = "M3 Pro GPU: pin the cd05 and 4118 firmware TEXT" - -[[carry]] -pr = "aurora-silicon/linux#2147" -commit = "98897fac88abbc9b382d22ea7764adb5bfe94b4d" -after = "147001c39e7f4e0efce47d1e139641abfa791add" -deps = ["aurora-silicon/linux#2146"] -why = "M3 (T8122) GPU runtime as on 7.2" +note = "re-pinned at intake 4a42f3105002: the old head no longer applied; the new head merges main and adds the any-T6030 pin" [[carry]] pr = "aurora-silicon/linux#2148" -commit = "5a2b02ae5cdcd8ab0cf304ed770897fc1e9d1510" -after = "48b5fd6db9877f1b5e44ccc3c16e80b76696e92e" -deps = ["aurora-silicon/linux#2145", "aurora-silicon/linux#2147"] +commit = "dd27aab2e03f6cd722c7e4b20deee390dbf7f68a" +merge = true +deps = ["aurora-silicon/linux#2146"] why = "M3 Max GPU and display: J514C, J514M, J516M, J516C" -note = "its branch carries copies (new SHAs) of #2146/#2147, so only its own 27 commits" +note = "head = the old pin 5a2b02ae5cdc plus a merge of main; one content conflict with main's T8132 gate in drivers/soc/apple/display-gate.c, both kept" [[carry]] pr = "aurora-silicon/linux#2149" -commit = "ae6c455e0679c607bb90da3ec4fbf48af676489f" -commits = ["555099395c72f4b1921b2fe2b7d220e9282f63e8", "bcb99bfb3480fe7bcf0531d4d111049395af9e61", "ae6c455e0679c607bb90da3ec4fbf48af676489f"] +commit = "348e1d69a283430513f76baeb2c6d0160696c747" +merge = true deps = ["aurora-silicon/linux#2148"] why = "M3 camera on 14.7 firmware" -note = "its first commit (T8122 ISP PMU base, 111f73220d21) is upstream as aa89283bd25d (#2670); only the other three" - -[[carry]] -pr = "aurora-silicon/linux#2150" -commit = "ab0b7b5339d592a10b943db1993f0d92f353646b" -why = "M4 Pro 16-inch (J616s) GPU: admit the fourth 25G83 firmware image" +note = "head = the old pin ae6c455e0679 merged with #2148's head; its first commit is already upstream as aa89283bd25d" [[carry]] pr = "aurora-silicon/linux#2151" -commit = "cb8d647d831c28ae2e8d5e5d6bf102b14e5349a0" -after = "13535c7426ff7c8b95aa67c33b0c4da823abe793" +commit = "668be257eedd925923aa0c61a3d7514ea6926954" +merge = true deps = ["aurora-silicon/linux#2148"] why = "M1 Air (J313) backlight, handed-over panel, keyboard" -note = "stacked on #2148; its branch carries copies of #2148's commits, so only its own 6" - -[[carry]] -pr = "aurora-silicon/linux#2152" -commit = "59b42888836ef863a1c6a13596d3e2c2ba524fdc" -why = "display v14.7: take primary planes that reach past the mode's edge" - -[[carry]] -pr = "aurora-silicon/linux#2153" -commit = "a50973082f9d149acbea6778a70ffbac4ef99b42" -why = "mt7932 Wi-Fi: WPA2-PSK with a TKIP group key" - -[[carry]] -pr = "aurora-silicon/linux#2154" -commit = "30c71bdc00e57d9196478b5b0bf99f8cc2c7070b" -why = "PCIe: root-port prefetchable window on cold-initialized tunnel ports" +note = "head = the old pin cb8d647d831c plus a merge of main" [[carry]] pr = "aurora-silicon/linux#2155" -commit = "fdb999e5a5043108abf4a6fc2dba51f7b7e082e5" +commit = "ad63582f81ac060c9bfdb15fc9cede07edfc2e9f" +commits = ["0acda1cdf788c1320dcd0365a5abd502464d9099", "ad63582f81ac060c9bfdb15fc9cede07edfc2e9f"] why = "ambient light sensor: CT720 color channels" - -[[carry]] -pr = "aurora-silicon/linux#2156" -commit = "9a847af26982b20c1ca93aac251b4d597aab11eb" -why = "Touch ID tooling (aurora-sep mesa-m3) hardening" - -[[carry]] -pr = "aurora-silicon/linux#2199" -commit = "b96b83d10ef7e2e3405fca8517ecd084c059cee0" -why = "cpufreq: no boost control without turbo mode" +note = "pinned at intake 4a42f3105002 to the last reviewed commit before #2155 merged main with the post-4a42f3105002 IIO API change (#3473); adds the describe-by-role follow-up" [[carry]] pr = "aurora-silicon/linux#3490" -commit = "d98f2a8e20c1c1e41068b984604ae24c8a4eb8be" -commits = ["d98f2a8e20c1c1e41068b984604ae24c8a4eb8be"] -deps = ["aurora-silicon/linux#2147", "aurora-silicon/linux#2148"] +commit = "e6e8509a4c22793d53597280f97eb63c4eae613d" +commits = ["717a6ff246c551d25d63097e2d65e1403c858249", "e6e8509a4c22793d53597280f97eb63c4eae613d"] +deps = ["aurora-silicon/linux#2148"] why = "M3/G15 GPU: qualified agx_stats, gpu_memory sysfs, and live fdinfo frequencies (for btop)" -note = "7.3-rebased single commit of aurora-silicon/linux#3490 (717a6ff246c5) on top of carry/aurora-7.3 (3058cc5cccb9), resolving context diffs against intake 00cbc67d1a0c" - -[[carry]] -ours = "j613-touchid-data-ready" -commit = "9d34362ed9ea45f3e6cba5c657aee1d52ff63841" -why = "M3 Air Touch ID data-ready line (no SPI polling, works after resume)" -upstream = "no PR yet; overlaps draft aurora-silicon/linux#1596, which also edits t8122-j613.dts. Needs an upstream PR (Scott's SoB) or folding into #1596" +note = "re-pinned at intake 4a42f3105002 to upstream #3490 head (two commits cherry-pick cleanly onto 4a42f3105002 + #2148; drops the 00cbc67d1a0c rebase commit d98f2a8e20c1)" [[carry]] -ours = "omacom/linux-aurora#370" -commit = "3a936edf2c49afddf0e173ad7c8593ae2ba4d885" -why = "brcmfmac PCIe: don't drop ring completions in the hard IRQ handler" -upstream = "merged on omacom 7.2 (Naeem Malik); no aurora-silicon PR yet. Needs one from its author" +pr = "aurora-silicon/linux#3770" +commit = "1fc02267da02fc8013fca445b617f9aee5c9fcb1" +commits = ["27b23c7d654525ae7ca12eb99d8f0c26a3072390", "1fc02267da02fc8013fca445b617f9aee5c9fcb1"] +why = "brcmfmac PCIe: don't drop ring completions in the hard IRQ handler and stop ring servicing across D0 sleeps" +note = "4a42f3105002 port of merged upstream aurora-silicon/linux#3770 (6b8d44fe3573, 9dab09e9226f; merge ac3f4d9d3888), replaces omacom/linux-aurora#370, adapts brcmf-suspend-tests.py mutation lists to 4a42f3105002" [[carry]] ours = "xart-pin-7.3" commit = "7d15e097880b49a4f07fa203b6bae0fd5c3a189f" why = "M1 Air (J313) Touch ID: the owner can pin the shared xART lockers setup rewrites (7.3 port, Naeem's J313 stage C/D pass)" -upstream = "port of omacom/linux-aurora#486 and #506 (7.2 line, open); drops when they land upstream" +upstream = "port of omacom/linux-aurora#486 (open) and #506 (closed); drops when an upstream equivalent covering J313 three-pin first activation lands" [[carry]] pr = "aurora-silicon/linux#3605" @@ -139,9 +98,9 @@ why = "ANE (H14): bind quietly when firmware is absent so boot has no spurious - [[carry]] pr = "aurora-silicon/linux#3607" commit = "40936f1338528a5a33f4410fbeec4d5c2cb92979" -commits = ["21bf1ba01f000e5869b7f749166090cf55663151", "aa3002fe6e90dd132bf73800c2254e18d1b28b30"] +commits = ["21bf1ba01f000e5869b7f749166090cf55663151", "aa3002fe6e90dd132bf73800c2254e18d1b28b30", "40936f1338528a5a33f4410fbeec4d5c2cb92979"] why = "Bluetooth (BCM4388): fix Read Local Supported Codecs v2 SoA layout and -EINVAL SCO caps so boot has zero codec capability errors and LC3 enumerates" -note = "carries the two runtime commits; the third commit adds KUnit tests to hci_bcm4377_test.c which postdates intake 00cbc67d1a0c" +note = "carries all three commits including KUnit tests (drivers/bluetooth/hci_bcm4377_test.c is present in 4a42f3105002)" [[carry]] pr = "aurora-silicon/linux#3608" @@ -150,23 +109,24 @@ why = "Asahi GPU: honor fault_log_ratelimit() in mark_pending_events() so suppre [[carry]] pr = "aurora-silicon/linux#3792" -commit = "a792526cbed2fbf7ecd2068801a9b7ec4808b5d9" +commit = "e47df5598945340b4ca06673463960d340310a42" +commits = ["e47df5598945340b4ca06673463960d340310a42"] why = "M3 Pro (J514S, J516S): with aura b17 keeping the notch rows (chosen.asahi,show-notch=1), unsized v14.7 panels came out notch-rows too tall (3024x2038), so DCP and GPU failed to probe (omacom/omarchy#20833)" -note = "7.3 backport against pre-#2814 boot_show_notch(void); upstream PR aurora-silicon/linux#3792 targets main's dcp_boot_show_notch(of_chosen)" +note = "4a42f3105002 port of merged upstream aurora-silicon/linux#3792 (a34278619b65, merge bbded5b8fbe1) targeting 4a42f3105002's dcp_boot_show_notch(of_chosen) and tools/asahi/dcp14-panel-tests.py; drops pre-#2814 backport a792526cbed2" [[carry]] pr = "aurora-silicon/linux#1969" -commit = "f837d8bcfc17e34c5fa833edd8ee4804e7c8d384" -commits = ["f837d8bcfc17e34c5fa833edd8ee4804e7c8d384"] +commit = "c8d07711e596231f59bdfb21f9fc8bcfcae772c2" +commits = ["c8d07711e596231f59bdfb21f9fc8bcfcae772c2"] why = "M3 Pro (T6030): set .swap_timestamps = true on dcp_v14_board_t6030 so the 120 Hz ProMotion panel stops capping swaps at 60 fps and unlocks locked-60Hz / 120Hz VRR mode splitting" -note = "7.3 port of merged upstream PR aurora-silicon/linux#1969 (merge commit 546464e28812, landed after intake 00cbc67d1a0c); retires automatically on next intake sync" +note = "4a42f3105002 carry of merged upstream PR aurora-silicon/linux#1969 (f8d416342d70 + 9181db401c48, merge commit 546464e28812) preserving Krish Nalekar authorship; retires automatically on next intake sync" [[carry]] pr = "aurora-silicon/linux#3799" -commit = "eb5f1b1e2665688d5c748dc342b744b9b6da352f" -commits = ["c64857fdf98a4cd7977464fd07ec03321f3b8f6d", "eb5f1b1e2665688d5c748dc342b744b9b6da352f"] +commit = "2805190c3a5f2f726935a5171c552df673e253e9" +commits = ["5a3363fd4ec0b30abc8626663fa447b4876029bc", "2805190c3a5f2f726935a5171c552df673e253e9"] why = "M3 Pro (T6030): guard never-valid SoC die sensors on binned SKUs with a die_seen latch and replace unverified Tf* placeholder apple,soc-die-keys (8 of 14 absent on J514S) with the 18 hardware-verified 12-core J514S CPU/fabric die sensors" -note = "7.3 backport of the two commits in aurora-silicon/linux#3799 against pre-refactor macsmc-hwmon.c and t6030.dtsi context" +note = "4a42f3105002 port of the two commits in aurora-silicon/linux#3799 (6da2a8f08011, 8ad53c838ca2) matching 4a42f3105002's macsmc-hwmon.c comment context" [[carry]] pr = "aurora-silicon/linux#3800" @@ -188,14 +148,14 @@ pr = "aurora-silicon/linux#3802" commit = "395aea0e7a9bbe934b3cbbf33c86214509393181" commits = ["395aea0e7a9bbe934b3cbbf33c86214509393181"] why = "M3 Pro (T6030): add per-CPU opp-microwatt power curves for Sawtooth (E) and Everest (P) OPP tables so Energy Aware Scheduling (sched_energy_aware=1 with schedutil) and power-allocator thermal governor work" -note = "7.3 cherry-pick of aurora-silicon/linux#3802" +note = "7.3 cherry-pick of merged upstream PR aurora-silicon/linux#3802 (merge bdb22f2d786f, landed after intake 4a42f3105002)" [[carry]] pr = "aurora-silicon/linux#3847" commit = "1068b9272e85bca4e45a62c0ba47b51c30e0e192" commits = ["6f03edf812bad8236e01906c869c3b7c87ebddaa", "1068b9272e85bca4e45a62c0ba47b51c30e0e192"] why = "M3 Max/Ultra (T6031/T6034/T6032): fix JPEG reg window (0x8000 -> 0x4000) overlapping dart_jpeg* and trim legacy 0x8000 boot.bin DTBs in apple-jpeg probe so both JPEG engines probe cleanly and ps_jpg reaches sync_state()" -note = "7.3 cherry-pick of the two commits in aurora-silicon/linux#3847" +note = "7.3 cherry-pick of merged upstream PR aurora-silicon/linux#3847 (merge 4f2dce318d5f, landed after intake 4a42f3105002)" [[carry]] pr = "aurora-silicon/linux#3854" @@ -223,4 +183,4 @@ pr = "aurora-silicon/linux#3857" commit = "ce7630d346c6e50fcc91cc90f99d2760e69d9fe0" commits = ["ce7630d346c6e50fcc91cc90f99d2760e69d9fe0"] why = "v14.7/v26.6 display (M3 Pro/Max, M4): register pixel blend mode (Coverage) on primary planes to eliminate the boot-time DRM alpha/blend-mode warning" -note = "7.3 cherry-pick of aurora-silicon/linux#3857" +note = "7.3 cherry-pick of merged upstream PR aurora-silicon/linux#3857 (merge 35e2cd47e305, landed after intake 4a42f3105002)" diff --git a/drivers/accel/ane/Makefile b/drivers/accel/ane/Makefile index 4557afbf5ddc55..a7d19a7259166e 100644 --- a/drivers/accel/ane/Makefile +++ b/drivers/accel/ane/Makefile @@ -3,14 +3,15 @@ obj-$(CONFIG_DRM_ACCEL_ANE) += ane.o ane_t6021.o obj-$(CONFIG_DRM_ACCEL_ANE_PM_KUNIT_TEST) += ane_pm_test.o ane_t6021_pm_test.o ane_fw_ids_test.o obj-$(CONFIG_DRM_ACCEL_ANE_H16_VALIDATION) += ane_h16_hwx.o ane_h16_preload.o ane_h16_load.o \ - ane_h16_program.o + ane_h16_program.o ane_fw_pages.o obj-$(CONFIG_DRM_ACCEL_ANE_KUNIT_TEST) += ane_drv_test.o obj-$(CONFIG_DRM_ACCEL_ANE_FW_KUNIT_TEST) += ane_fw_platform_test.o \ ane_fw_protocol_test.o ane_h16_tasks_test.o ane_h16_execute_test.o \ ane_fw_transport_test.o ane_h16_boot_test.o \ ane_h16_pending_test.o ane_h16_hwx_test.o ane_h16_preload_test.o \ ane_h16_program_test.o ane_fw_cold_test.o ane_h16_accel_test.o \ - ane_t6021_lifetime_test.o + ane_fw_pages_test.o \ + ane_t6021_lifetime_test.o ane_t6021_fwmap_test.o ane-y := \ ane_drv.o \ diff --git a/drivers/accel/ane/ane.h b/drivers/accel/ane/ane.h index 24a44ea99ed5db..b6d1ad449d5b13 100644 --- a/drivers/accel/ane/ane.h +++ b/drivers/accel/ane/ane.h @@ -20,10 +20,33 @@ #define ANE_DART_MAX 3 #define ANE_DART_SCRATCH_MAX 16 +/* + * What owns a node of ane_device.mm, kept in drm_mm_node.color (the + * allocator has no color_adjust, so the color only labels the node). + * Written under iommu_lock. + */ +enum ane_mm_owner { + ANE_MM_NONE, + /* A BO's range, its pages not in the DART. */ + ANE_MM_BO_UNMAPPED, + /* A BO's range, its pages in the DART. */ + ANE_MM_BO_MAPPED, + /* A fault-drain page in a hole, reserved by the drain. */ + ANE_MM_SCRATCH, + /* The range of a BO freed while wedged (ane_preserve_bo()). */ + ANE_MM_PRESERVED, +}; + +/* + * A fault-drain page. @node is the node the drain reserved for a page in + * a hole; @host is the node of an unmapped BO whose range holds the page. + * Exactly one of them is set. + */ struct ane_dart_scratch { u64 iova; struct page *page; struct drm_mm_node *node; + struct drm_mm_node *host; }; struct ane_device { @@ -46,6 +69,8 @@ struct ane_device { void __iomem *ps; struct drm_mm mm; + /* Size of the device address range that mm manages. */ + u64 iova_span; struct iommu_domain *domain; unsigned long shift; struct ane_dart { @@ -68,6 +93,15 @@ struct ane_device { struct mutex pm_lock; struct list_head bo_list; + /* + * BOs whose pages are in the DART now. Between jobs this is the last + * job's set; ane_submit() unmaps every other BO before the engine + * starts, so a job reaches only the buffers it names. job_seq tags + * the BOs of the job being set up. Both under engine_lock. + */ + struct list_head mapped_list; + u64 job_seq; + /* * Wedge-preserved BO ranges, tied to their still-inserted drm_mm * nodes (see ane_reclaim_preserved). Registered under engine_lock. @@ -223,6 +257,11 @@ static inline bool ane_tm_failure_recoverable(bool tm_retention, } #if IS_ENABLED(CONFIG_KUNIT) +u64 ane_bo_iova_size(u32 npages, unsigned int shift); +int ane_bo_check_size(u64 size, u64 iova_span); +struct page *ane_dart_alloc_scratch_page(void); +int ane_dart_scratch_slot(struct ane_device *ane, u64 iova, u64 size, + struct drm_mm_node **host); int ane_submit_check_sizes(const struct drm_ane_submit *args, size_t cmd_size, size_t btsp_size); #endif @@ -249,9 +288,9 @@ int ane_dart_init(struct ane_device *ane); void ane_dart_mask(struct ane_device *ane); void ane_dart_unmask(struct ane_device *ane); bool ane_dart_faulted(struct ane_device *ane, u64 *iova, u32 *status); -int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova, - struct ane_dart_scratch *scratch, int *pages); +int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova); void ane_dart_release_scratch(struct ane_device *ane, struct ane_dart_scratch *scratch, int pages); +bool ane_dart_scratch_in(struct ane_device *ane, struct drm_mm_node *host); #endif /* __ANE_H__ */ diff --git a/drivers/accel/ane/ane_dart.c b/drivers/accel/ane/ane_dart.c index f99d5c5b5c0c1b..47957fc6d8bf37 100644 --- a/drivers/accel/ane/ane_dart.c +++ b/drivers/accel/ane/ane_dart.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* Copyright 2026 Joshua Warren */ +#include #include #include #include @@ -170,6 +171,71 @@ bool ane_dart_faulted(struct ane_device *ane, u64 *iova, u32 *status) return false; } +/* + * The scratch page is mapped read-write for the job that faulted, and + * the job's output can carry what it reads from there: hand it out + * zeroed. + */ +VISIBLE_IF_KUNIT struct page *ane_dart_alloc_scratch_page(void) +{ + return alloc_page(GFP_KERNEL | __GFP_ZERO); +} +EXPORT_SYMBOL_IF_KUNIT(ane_dart_alloc_scratch_page); + +/* + * Where may a fault-drain page go? A fault is a missing PTE in one of two + * places. In a hole of the allocator (a wild address), the drain reserves + * a node for the page (@host stays NULL). Or in the range of a BO that is + * not in the DART: ane_submit() takes every BO that the job does not name + * out of the DART, so an access past the end of a job's buffer, or a + * descriptor that points at another buffer of this or another file, lands + * there; the ranges are packed, so this is the common case. The page then + * goes into that BO's range and @host is the BO's node. That BO cannot get + * its pages back into the DART, nor its range back to the allocator, while + * the page is there (ane_dart_scratch_in()), so no scratch PTE outlives + * the drain into a mapped BO. Anything else (a mapped BO, a scratch page, + * a wedge-preserved range) has PTEs and cannot fault: refuse it. + * + * Callers hold iommu_lock. + */ +VISIBLE_IF_KUNIT int ane_dart_scratch_slot(struct ane_device *ane, u64 iova, + u64 size, struct drm_mm_node **host) +{ + struct drm_mm *mm = &ane->mm; + struct drm_mm_node *node; + + *host = NULL; + if (iova + size < iova) + return -EINVAL; + /* A drain in an unmapped BO has no separate drm_mm node. */ + for (int i = 0; i < ane->scratch_pages; i++) + if (ane->scratch[i].iova == iova) + return -EBUSY; + drm_mm_for_each_node_in_range(node, mm, iova, iova + size) { + /* Past the end of the range that the allocator manages. */ + if (node == &mm->head_node) + return -ERANGE; + if (node->color != ANE_MM_BO_UNMAPPED || + node->start > iova || + node->start + node->size < iova + size) + return -EBUSY; + *host = node; + return 0; + } + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(ane_dart_scratch_slot); + +/* Does a drain page sit in the range of the BO that owns @host? */ +bool ane_dart_scratch_in(struct ane_device *ane, struct drm_mm_node *host) +{ + for (int i = 0; i < ane->scratch_pages; i++) + if (host && ane->scratch[i].host == host) + return true; + return false; +} +EXPORT_SYMBOL_IF_KUNIT(ane_dart_scratch_in); + /* * A fault is a missing PTE, nothing more: the page tables are provider * owned and unchanged, so the stream-restore apple-dart uses at reset @@ -179,68 +245,76 @@ bool ane_dart_faulted(struct ane_device *ane, u64 *iova, u32 *status) * completes and the engine drains on its own; the scratch pages are * unmapped once the request has been failed cleanly. * - * The throwaway page is mapped at the faulting address, which is - * allocator-free by definition of a translation fault - but the drm_mm - * allocator knows nothing about a raw iommu_map. A scratch PTE that - * outlives its release path (any future bug on the wedge side) would - * then sit, untracked, in a range the allocator considers free: the - * next BO_INIT maps onto it and fails with dart_init_pte's "we require - * an unmap first" WARN. So the scratch range is RESERVED in the - * allocator first: a node-tracked mapping can never collide with a - * later BO_INIT, and a scratch whose release is skipped degrades into - * a bounded, benign leak instead of a poisoned address space. Reserve - * failure means a live BO node already owns the faulting page (a wild - * descriptor, not a hole): refuse and let the caller wedge, fail - * closed. + * The drm_mm allocator knows nothing about a raw iommu_map, so a scratch + * PTE is always inside a node: one the drain reserves in a hole, or the + * node of the unmapped BO it landed in (ane_dart_scratch_slot()). A + * node-tracked mapping can never collide with a later BO_INIT, and a + * scratch whose release is skipped degrades into a bounded, benign leak + * instead of a poisoned address space. A page that no drain may take + * is refused, and the caller wedges and recovers, fail closed. + * + * Callers hold engine_lock, which keeps the BOs' DART state still. */ -int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova, - struct ane_dart_scratch *scratch, int *pages) +int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova) { - struct drm_mm_node *node; + struct ane_dart_scratch *scratch; + struct drm_mm_node *node = NULL, *host; struct page *page; u64 iova; int ret, i; - page = alloc_page(GFP_KERNEL); + lockdep_assert_held(&ane->engine_lock); + page = ane_dart_alloc_scratch_page(); if (!page) return -ENOMEM; iova = fault_iova & ~((1ULL << ane->shift) - 1); - node = kzalloc_obj(*node); - if (!node) { - __free_page(page); - return -ENOMEM; - } - node->start = iova; - node->size = BIT(ane->shift); - mutex_lock(&ane->iommu_lock); - ret = drm_mm_reserve_node(&ane->mm, node); - if (ret) { - mutex_unlock(&ane->iommu_lock); - kfree(node); - __free_page(page); - return ret; + ret = ane_dart_scratch_slot(ane, iova, BIT(ane->shift), &host); + if (ret) + goto refuse; + if (!host) { + node = kzalloc_obj(*node); + if (!node) { + ret = -ENOMEM; + goto refuse; + } + node->start = iova; + node->size = BIT(ane->shift); + node->color = ANE_MM_SCRATCH; + ret = drm_mm_reserve_node(&ane->mm, node); + if (ret) { + kfree(node); + goto refuse; + } } ret = iommu_map(ane->domain, iova, page_to_phys(page), BIT(ane->shift), IOMMU_READ | IOMMU_WRITE, GFP_KERNEL); - mutex_unlock(&ane->iommu_lock); if (ret) { - mutex_lock(&ane->iommu_lock); - drm_mm_remove_node(node); - mutex_unlock(&ane->iommu_lock); - kfree(node); - __free_page(page); - return ret; + if (node) { + drm_mm_remove_node(node); + kfree(node); + } + goto refuse; } - scratch[*pages].iova = iova; - scratch[*pages].page = page; - scratch[*pages].node = node; - (*pages)++; + mutex_unlock(&ane->iommu_lock); + dev_dbg(ane->dev, "fault drain: page at %#llx in %s\n", iova, + host ? "an unmapped buffer's range" : "a hole"); + scratch = &ane->scratch[ane->scratch_pages++]; + scratch->iova = iova; + scratch->page = page; + scratch->node = node; + scratch->host = host; for (i = 0; i < ane->dart_count; i++) ane_dart_invalidate(ane, &ane->darts[i]); return 0; + +refuse: + mutex_unlock(&ane->iommu_lock); + __free_page(page); + dev_dbg(ane->dev, "fault drain refused at %#llx: %d\n", iova, ret); + return ret; } void ane_dart_release_scratch(struct ane_device *ane, @@ -258,9 +332,12 @@ void ane_dart_release_scratch(struct ane_device *ane, dev_err(ane->dev, "scratch unmap short at %#llx: %zu\n", scratch[i].iova, unmapped); - drm_mm_remove_node(scratch[i].node); - kfree(scratch[i].node); + if (scratch[i].node) { + drm_mm_remove_node(scratch[i].node); + kfree(scratch[i].node); + } scratch[i].node = NULL; + scratch[i].host = NULL; __free_page(scratch[i].page); scratch[i].page = NULL; } diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index 9db29596045700..37c27a726071f5 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -81,27 +81,37 @@ MODULE_PARM_DESC(autosuspend_ms, "Power the ANE off this many ms after its last use (default 1500; 0 = keep it powered while the driver is bound)"); /* - * 1 (default): BO_INIT maps a buffer object with one iommu_map_sg(), so + * 1 (default): a buffer object goes into the DART (at the first SUBMIT + * that names it, see ane_dart_confine()) with one iommu_map_sg(), so * apple-dart invalidates the TLB of each DART once for each BO. 0: one * iommu_map() and one TLB invalidate on each DART for each page (a * 458 MB buffer: 27,955 pages x 3 DARTs = 83,865 invalidates). Read - * once for each BO_INIT; BOs mapped either way unmap the same way. + * at each map; BOs mapped either way unmap the same way. */ static bool map_batch = true; module_param(map_batch, bool, 0644); MODULE_PARM_DESC(map_batch, - "BO_INIT DART mapping: 1 = one TLB sync for each buffer object (default); 0 = one TLB sync for each page"); + "Buffer object DART mapping: 1 = one TLB sync for each buffer object (default); 0 = one TLB sync for each page"); #define CMD_BUF_BDX 0 #define KRN_BUF_BDX 1 +/* + * A BO owns its IOVA range (mm, iova) from BO_INIT to its free, but its + * pages are in the DART only while @mapped: from the first SUBMIT that + * names it until a SUBMIT that does not (see ane_dart_confine()). + */ struct ane_bo { struct drm_gem_object base; struct list_head node; + struct list_head mapped_node; struct drm_mm_node *mm; u32 npages; struct page **pages; dma_addr_t iova; + u64 job_seq; + int prot; + bool mapped; }; #define to_bo(gem) (container_of(gem, struct ane_bo, base)) @@ -115,6 +125,33 @@ static struct ane_bo *bo_lookup(struct drm_file *file, u32 handle) return to_bo(gem); } +/* + * The IOVA span of a buffer object. Computed in 64 bits: the reservation + * and the map must cover the same range for any page count. + */ +VISIBLE_IF_KUNIT u64 ane_bo_iova_size(u32 npages, unsigned int shift) +{ + return (u64)npages << shift; +} +EXPORT_SYMBOL_IF_KUNIT(ane_bo_iova_size); + +/* + * A buffer object must fit the device address range the allocator + * manages, or it can never be mapped. Refusing it before any page is + * allocated also keeps the page count within the u32 that the map + * paths use. + */ +VISIBLE_IF_KUNIT int ane_bo_check_size(u64 size, u64 iova_span) +{ + if (!size) + return -EINVAL; + if (size > iova_span || size > U64_MAX - (PAGE_SIZE - 1) || + round_up(size, PAGE_SIZE) > iova_span) + return -E2BIG; + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(ane_bo_check_size); + /* Unmap every valid PTE in [start, end) and return how many there were. */ static unsigned long ane_iommu_clear_range(struct ane_device *ane, u64 start, u64 end) @@ -145,7 +182,7 @@ static int ane_iommu_map_each(struct ane_device *ane, struct ane_bo *bo, int err = 0; for (u32 i = 0; i < bo->npages; i++) { - dma_addr_t iova = bo->iova + (i << ane->shift); + dma_addr_t iova = bo->iova + ((u64)i << ane->shift); bool healed = false; retry: @@ -168,12 +205,12 @@ static int ane_iommu_map_each(struct ane_device *ane, struct ane_bo *bo, unmapped = iommu_unmap(ane->domain, bo->iova + - (i << ane->shift), + ((u64)i << ane->shift), 1UL << ane->shift); if (unmapped != 1UL << ane->shift) dev_err(ane->dev, "rollback unmap short at %#llx: %zu\n", - bo->iova + (i << ane->shift), + bo->iova + ((u64)i << ane->shift), unmapped); } break; @@ -191,7 +228,7 @@ static int ane_iommu_map_each(struct ane_device *ane, struct ane_bo *bo, static int ane_iommu_map_batch(struct ane_device *ane, struct ane_bo *bo, int prot) { - size_t size = (size_t)bo->npages << ane->shift; + size_t size = ane_bo_iova_size(bo->npages, ane->shift); struct sg_table sgt; unsigned long strays; ssize_t mapped; @@ -240,54 +277,111 @@ static int ane_iommu_map_batch(struct ane_device *ane, struct ane_bo *bo, * setup, invalidation and fault IRQs are all provider-owned); * iommu_unmap() flushes through the provider before returning, so pages * may be reclaimed once it succeeds. + * + * BO_INIT only reserves the BO's IOVA range. The pages go into the DART + * when a SUBMIT names the BO (ane_dart_confine()), so the range stays the + * BO's for its whole life while its PTEs come and go. */ -static int ane_iommu_map_pages(struct ane_device *ane, struct ane_bo *bo) +static int ane_iommu_reserve(struct ane_device *ane, struct ane_bo *bo) { - int prot = IOMMU_READ | IOMMU_WRITE; int err; lockdep_assert_held(&ane->engine_lock); if (bo->mm) return -EBUSY; + bo->prot = IOMMU_READ | IOMMU_WRITE; if (map_mode & 1) - prot |= IOMMU_CACHE; + bo->prot |= IOMMU_CACHE; bo->mm = kzalloc_obj(*bo->mm); if (!bo->mm) return -ENOMEM; mutex_lock(&ane->iommu_lock); - /* reserve area from ANE address space */ err = drm_mm_insert_node_generic(&ane->mm, bo->mm, - bo->npages << ane->shift, - 1UL << ane->shift, 0, 0); + ane_bo_iova_size(bo->npages, ane->shift), + 1UL << ane->shift, ANE_MM_BO_UNMAPPED, + 0); + mutex_unlock(&ane->iommu_lock); if (err < 0) { dev_err(ane->dev, "out of ANE space: %d\n", err); - goto unlock; + kfree(bo->mm); + bo->mm = NULL; + return err; } bo->iova = bo->mm->start; + return 0; +} + +/* + * Put the pages of a BO with a reserved range into the DART. A fault + * drain may have put a scratch page into the range of a BO that is not in + * the DART (ane_dart_drain_fault()); the scratch pages are released when + * the faulting job completes or at the recovery after it, both before any + * later SUBMIT gets here, so such a page is never found here. Refuse it + * anyway: mapping over it would take the scratch PTE for a stray and + * clear it, and the scratch release would then unmap the BO's page. + */ +static int ane_bo_dart_map(struct ane_device *ane, struct ane_bo *bo) +{ + int err; + + lockdep_assert_held(&ane->engine_lock); + if (bo->mapped) + return 0; + if (!bo->mm) + return -EINVAL; + if (WARN_ON_ONCE(ane_dart_scratch_in(ane, bo->mm))) + return -EBUSY; + mutex_lock(&ane->iommu_lock); if (READ_ONCE(map_batch)) - err = ane_iommu_map_batch(ane, bo, prot); + err = ane_iommu_map_batch(ane, bo, bo->prot); else - err = ane_iommu_map_each(ane, bo, prot); - if (err < 0) { - drm_mm_remove_node(bo->mm); - bo->iova = 0; - } - -unlock: + err = ane_iommu_map_each(ane, bo, bo->prot); + if (!err) + bo->mm->color = ANE_MM_BO_MAPPED; mutex_unlock(&ane->iommu_lock); - if (err < 0) { - kfree(bo->mm); - bo->mm = NULL; + if (err < 0) + return err; + + bo->mapped = true; + list_add_tail(&bo->mapped_node, &ane->mapped_list); + return 0; +} + +/* + * Take the pages of a BO out of the DART and keep its range. A mapped BO + * has a PTE on every page, so one range unmap (one TLB flush per DART) + * takes them all; a short unmap is cleared page by page. + */ +static void ane_bo_dart_unmap(struct ane_device *ane, struct ane_bo *bo) +{ + size_t size = ane_bo_iova_size(bo->npages, ane->shift); + size_t unmapped; + + lockdep_assert_held(&ane->engine_lock); + if (!bo->mapped) + return; + + mutex_lock(&ane->iommu_lock); + unmapped = iommu_unmap(ane->domain, bo->iova, size); + if (unmapped != size) { + dev_err(ane->dev, "unmap short at %#llx+%#zx: %zu\n", + bo->iova, size, unmapped); + ane_iommu_clear_range(ane, bo->iova, bo->iova + size); } - return err; + bo->mm->color = ANE_MM_BO_UNMAPPED; + mutex_unlock(&ane->iommu_lock); + + list_del_init(&bo->mapped_node); + bo->mapped = false; } +/* Unmap a BO and give its range back to the allocator. */ static void ane_iommu_unmap_pages(struct ane_device *ane, struct ane_bo *bo) { struct drm_mm_node *mm = bo->mm; @@ -298,16 +392,10 @@ static void ane_iommu_unmap_pages(struct ane_device *ane, struct ane_bo *bo) return; list_del_init(&bo->node); + ane_bo_dart_unmap(ane, bo); + /* ane_gem_free_object() preserves a range that holds a drain page. */ + WARN_ON_ONCE(ane_dart_scratch_in(ane, mm)); mutex_lock(&ane->iommu_lock); - for (u32 i = 0; i < bo->npages; i++) { - dma_addr_t iova = bo->iova + (i << ane->shift); - size_t unmapped = iommu_unmap(ane->domain, iova, - 1UL << ane->shift); - - if (unmapped != 1UL << ane->shift) - dev_err(ane->dev, "unmap short at %#llx: %zu\n", - iova, unmapped); - } drm_mm_remove_node(mm); bo->mm = NULL; bo->iova = 0; @@ -316,6 +404,42 @@ static void ane_iommu_unmap_pages(struct ane_device *ane, struct ane_bo *bo) kfree(mm); } +/* + * All files share one DART domain, and the task descriptors of a job + * address memory as a tile base plus an offset the kernel cannot check. + * So the DART is the bound: before the engine starts, every BO that is + * not part of this job leaves the DART and every BO of the job is put + * in. A descriptor that leaves the job's buffers then lands in a hole + * and faults (see ane_dart_drain_fault()) instead of reaching another + * file's buffer. Jobs run one at a time under engine_lock, and a job's + * lookup references keep its BOs alive until it completed, so the set + * cannot change under a running job. A BO that the next job names again + * stays mapped, so repeated jobs on the same buffers cost no remapping. + */ +static int ane_dart_confine(struct ane_device *ane, struct ane_bo **job, + int count) +{ + struct ane_bo *bo, *tmp; + u64 seq; + int err; + + lockdep_assert_held(&ane->engine_lock); + seq = ++ane->job_seq; + for (int i = 0; i < count; i++) + job[i]->job_seq = seq; + + list_for_each_entry_safe(bo, tmp, &ane->mapped_list, mapped_node) + if (bo->job_seq != seq) + ane_bo_dart_unmap(ane, bo); + + for (int i = 0; i < count; i++) { + err = ane_bo_dart_map(ane, job[i]); + if (err) + return err; + } + return 0; +} + /* * A BO freed while the engine is wedged keeps its mapping and its pages * (DMA may still be reading the IOVA), but the GEM object is gone. The @@ -330,12 +454,17 @@ struct ane_preserved { struct drm_mm_node *mm; struct page **pages; u32 npages; + /* The BO's pages were in the DART, not only drain pages. */ + bool mapped; }; static void ane_preserve_bo(struct ane_device *ane, struct ane_bo *bo) { struct ane_preserved *p; + mutex_lock(&ane->iommu_lock); + bo->mm->color = ANE_MM_PRESERVED; + mutex_unlock(&ane->iommu_lock); p = kzalloc_obj(*p); if (!p) { /* Fail closed the old way: the node stays inserted and the @@ -349,6 +478,7 @@ static void ane_preserve_bo(struct ane_device *ane, struct ane_bo *bo) p->mm = bo->mm; p->pages = bo->pages; p->npages = bo->npages; + p->mapped = bo->mapped; list_add_tail(&p->list, &ane->preserved_list); bo->mm = NULL; bo->pages = NULL; @@ -367,16 +497,17 @@ void ane_reclaim_preserved(struct ane_device *ane) u64 iova = p->mm->start; mutex_lock(&ane->iommu_lock); - for (u32 i = 0; i < p->npages; i++) { + /* Its drain pages went with the scratch release above. */ + for (u32 i = 0; p->mapped && i < p->npages; i++) { size_t unmapped; unmapped = iommu_unmap(ane->domain, - iova + (i << ane->shift), + iova + ((u64)i << ane->shift), 1UL << ane->shift); if (unmapped != 1UL << ane->shift) dev_err(ane->dev, "preserved unmap short at %#llx: %zu\n", - iova + (i << ane->shift), unmapped); + iova + ((u64)i << ane->shift), unmapped); } drm_mm_remove_node(p->mm); mutex_unlock(&ane->iommu_lock); @@ -432,18 +563,28 @@ static void ane_gem_free_object(struct drm_gem_object *gem) mutex_lock(&ane->engine_lock); if (bo->mm) { - if (atomic_read(&ane->wedged)) { + /* + * A drain page in the range of a BO that is not in the DART + * stays until the recovery that follows the wedge, and the + * range must stay reserved until then. + */ + if ((atomic_read(&ane->wedged) && bo->mapped) || + ane_dart_scratch_in(ane, bo->mm)) { /* Fail closed: keep the mapping and the pages so no * IOVA is torn down or page reused underneath active * DMA. The range's node stays reserved and tracked * until recovery quiesces the engine and reclaims * it, so no later BO_INIT can map over these PTEs * (a leaked-but-forgotten mapping turns into - * dart_init_pte -EEXIST WARNs). + * dart_init_pte -EEXIST WARNs). A BO that is not in + * the DART was not part of the job that wedged and + * the engine cannot reach it, so it is freed below. */ dev_err(ane->dev, "wedged: preserving bo mapping\n"); list_del_init(&bo->node); + list_del_init(&bo->mapped_node); ane_preserve_bo(ane, bo); + bo->mapped = false; } else { ane_iommu_unmap_pages(ane, bo); } @@ -488,13 +629,17 @@ static int ane_bo_init(struct drm_device *drm, void *data, struct ane_bo *bo; int err; - if (args->pad || !args->size) + if (args->pad) return -EINVAL; + err = ane_bo_check_size(args->size, ane->iova_span); + if (err) + return err; bo = kzalloc_obj(*bo); if (!bo) return -ENOMEM; INIT_LIST_HEAD(&bo->node); + INIT_LIST_HEAD(&bo->mapped_node); gem = &bo->base; gem->funcs = &ane_gem_object_funcs; @@ -529,7 +674,7 @@ static int ane_bo_init(struct drm_device *drm, void *data, goto unlock_put; } - err = ane_iommu_map_pages(ane, bo); + err = ane_iommu_reserve(ane, bo); if (err < 0) goto unlock_put; list_add_tail(&bo->node, &ane->bo_list); @@ -609,9 +754,11 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) struct drm_ane_submit *args = data; struct drm_gem_object *gem[DRM_ANE_TILE_COUNT] = { 0 }; struct drm_gem_object *btsp = NULL; + struct ane_bo *job[DRM_ANE_TILE_COUNT + 1]; struct ane_bo *bo; struct ane_request req; u64 stats_idx = 0; + int njob = 0; int err; memset(&req, 0, sizeof(req)); @@ -677,8 +824,14 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) /* * Lookup references are held across the synchronous execute and * dropped only after ane_tm_execute() confirmed completion, so a - * concurrent BO_FREE cannot unmap a buffer the engine reads. + * concurrent BO_FREE cannot unmap a buffer the engine reads. The + * same references are the job's DART set (ane_dart_confine()). */ + for (int bdx = 0; bdx < DRM_ANE_TILE_COUNT; bdx++) + if (gem[bdx]) + job[njob++] = to_bo(gem[bdx]); + job[njob++] = to_bo(btsp); + mutex_lock(&ane->engine_lock); if (ane->removed) { err = -ENODEV; @@ -690,6 +843,12 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) goto unlock; } + err = ane_dart_confine(ane, job, njob); + if (err) { + dev_err_ratelimited(ane->dev, "job buffers not mapped: %d\n", err); + goto unlock; + } + err = ane_perf_begin(ane); if (err) { dev_err_ratelimited(ane->dev, "performance request failed: %d\n", err); @@ -1044,7 +1203,8 @@ static int ane_iommu_domain_init(struct ane_device *ane) return -EINVAL; ane->domain = domain; ane->shift = PAGE_SHIFT; - drm_mm_init(&ane->mm, min_iova, limit - min_iova); + ane->iova_span = limit - min_iova; + drm_mm_init(&ane->mm, min_iova, ane->iova_span); return 0; } @@ -1256,6 +1416,7 @@ static int ane_platform_probe(struct platform_device *pdev) mutex_init(&ane->engine_lock); mutex_init(&ane->pm_lock); INIT_LIST_HEAD(&ane->bo_list); + INIT_LIST_HEAD(&ane->mapped_list); INIT_LIST_HEAD(&ane->preserved_list); err = ane_perf_init(ane, soc->high_level); if (err < 0) @@ -1354,9 +1515,10 @@ static void ane_platform_remove(struct platform_device *pdev) return; } + /* Drain pages first: they may sit in the range of a listed BO. */ + ane_reclaim_preserved(ane); list_for_each_entry_safe(bo, tmp, &ane->bo_list, node) ane_iommu_unmap_pages(ane, bo); - ane_reclaim_preserved(ane); drm_mm_takedown(&ane->mm); ane_detach_genpd(ane); diff --git a/drivers/accel/ane/ane_drv_test.c b/drivers/accel/ane/ane_drv_test.c index 90708b9613de3d..c2e0876ab45035 100644 --- a/drivers/accel/ane/ane_drv_test.c +++ b/drivers/accel/ane/ane_drv_test.c @@ -1,11 +1,17 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* - * KUnit tests for the buffer size checks of DRM_IOCTL_ANE_SUBMIT. + * KUnit tests for the buffer size checks of DRM_IOCTL_ANE_SUBMIT and + * DRM_IOCTL_ANE_BO_INIT, and the fault-drain scratch page. */ #include +#include +#include +#include #include +#include + #include "ane.h" struct ane_submit_size_case { @@ -145,7 +151,223 @@ static struct kunit_suite ane_recovery_test_suite = { .test_cases = ane_recovery_test_cases, }; -kunit_test_suites(&ane_submit_test_suite, &ane_recovery_test_suite); +/* BO_INIT: the reservation and the map must agree for any page count. */ +static void ane_bo_iova_size_test(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, ane_bo_iova_size(1, 14), (u64)SZ_16K); + KUNIT_EXPECT_EQ(test, ane_bo_iova_size(0x3ffff, 14), + (u64)SZ_4G - SZ_16K); + KUNIT_EXPECT_EQ(test, ane_bo_iova_size(0x40000, 14), (u64)SZ_4G); + KUNIT_EXPECT_EQ(test, ane_bo_iova_size(0x40001, 14), + (u64)SZ_4G + SZ_16K); + KUNIT_EXPECT_EQ(test, ane_bo_iova_size(U32_MAX, 12), + (u64)U32_MAX << 12); +} + +struct ane_bo_size_case { + const char *desc; + u64 size; + u64 span; + int ret; +}; + +/* The H13 allocator range: one page above zero up to 4 GiB. */ +#define ANE_TEST_SPAN ((u64)SZ_4G - PAGE_SIZE) + +static const struct ane_bo_size_case ane_bo_size_cases[] = { + { "zero bytes", 0, ANE_TEST_SPAN, -EINVAL }, + { "one byte", 1, ANE_TEST_SPAN, 0 }, + { "the whole range", ANE_TEST_SPAN, ANE_TEST_SPAN, 0 }, + { "one byte past the range", ANE_TEST_SPAN + 1, ANE_TEST_SPAN, -E2BIG }, + { "4 GiB", SZ_4G, ANE_TEST_SPAN, -E2BIG }, + { "4 GiB and one page", (u64)SZ_4G + PAGE_SIZE, ANE_TEST_SPAN, -E2BIG }, + { "page count past u32", (u64)PAGE_SIZE << 32, ANE_TEST_SPAN, -E2BIG }, + { "largest u64", U64_MAX, ANE_TEST_SPAN, -E2BIG }, + { "rounds up past a smaller range", SZ_16K + 1, SZ_16K + 1, -E2BIG }, + /* round_up() would wrap to 0 below these, for any range. */ + { "largest u64, whole u64 range", U64_MAX, U64_MAX, -E2BIG }, + { "one byte past the last whole page, whole u64 range", + U64_MAX - (PAGE_SIZE - 1) + 1, U64_MAX, -E2BIG }, + { "last whole page, whole u64 range", U64_MAX - (PAGE_SIZE - 1), + U64_MAX, 0 }, +}; + +KUNIT_ARRAY_PARAM_DESC(ane_bo_size, ane_bo_size_cases, desc); + +static void ane_bo_check_size_test(struct kunit *test) +{ + const struct ane_bo_size_case *c = test->param_value; + + KUNIT_EXPECT_EQ(test, ane_bo_check_size(c->size, c->span), c->ret); +} + +/* + * The fault-drain scratch page is readable by the job that faulted. + * Dirty some pages and give them back to the allocator first, so an + * unzeroed allocation would very likely hand one of them out again + * (likely, not certain: the allocator may pick other pages). + */ +#define ANE_TEST_SCRATCH_PAGES 16 + +static void ane_dart_scratch_page_zeroed_test(struct kunit *test) +{ + struct page *pages[ANE_TEST_SCRATCH_PAGES]; + int i; + + /* The allocator zeroes every page itself: nothing to tell apart. */ + if (want_init_on_alloc(GFP_KERNEL)) + kunit_skip(test, "init_on_alloc zeroes every page"); + + for (i = 0; i < ARRAY_SIZE(pages); i++) { + pages[i] = alloc_page(GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, pages[i]); + memset(page_address(pages[i]), 0xa5, PAGE_SIZE); + } + for (i = 0; i < ARRAY_SIZE(pages); i++) + __free_page(pages[i]); + + for (i = 0; i < ARRAY_SIZE(pages); i++) { + pages[i] = ane_dart_alloc_scratch_page(); + KUNIT_ASSERT_NOT_NULL(test, pages[i]); + } + for (i = 0; i < ARRAY_SIZE(pages); i++) { + KUNIT_EXPECT_TRUE_MSG(test, + !memchr_inv(page_address(pages[i]), 0, + PAGE_SIZE), + "scratch page %d is not zeroed", i); + __free_page(pages[i]); + } +} + +/* + * Where a fault-drain page may go. The H13 layout: 16 KiB DART pages, + * BO ranges packed back to back by the allocator. A job's buffer is in + * the DART (MAPPED); the next BO, of this or another file, is not + * (UNMAPPED), so a read a few bytes past the job's buffer faults in the + * neighbour's range. + */ +#define ANE_TEST_PG SZ_16K + +static struct drm_mm_node *ane_test_node(struct kunit *test, struct drm_mm *mm, + u64 page, u64 pages, + enum ane_mm_owner owner) +{ + struct drm_mm_node *node = kunit_kzalloc(test, sizeof(*node), + GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, node); + node->start = page * ANE_TEST_PG; + node->size = pages * ANE_TEST_PG; + node->color = owner; + KUNIT_ASSERT_EQ(test, drm_mm_reserve_node(mm, node), 0); + return node; +} + +static void ane_dart_scratch_slot_test(struct kunit *test) +{ + struct ane_device *ane = kunit_kzalloc(test, sizeof(*ane), GFP_KERNEL); + struct drm_mm_node *job, *next, *other, *scratch, *kept, *host; + struct drm_mm *mm; + + KUNIT_ASSERT_NOT_NULL(test, ane); + mm = &ane->mm; + + /* One page above zero up to 64 pages. */ + drm_mm_init(mm, ANE_TEST_PG, 63 * ANE_TEST_PG); + job = ane_test_node(test, mm, 1, 4, ANE_MM_BO_MAPPED); + next = ane_test_node(test, mm, 5, 3, ANE_MM_BO_UNMAPPED); + other = ane_test_node(test, mm, 8, 2, ANE_MM_BO_UNMAPPED); + scratch = ane_test_node(test, mm, 12, 1, ANE_MM_SCRATCH); + kept = ane_test_node(test, mm, 13, 2, ANE_MM_PRESERVED); + + /* Past the end of the job's buffer: the packed neighbour. */ + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 5 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_PTR_EQ(test, host, next); + /* Inside and at the last page of a buffer the job does not name. */ + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 6 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_PTR_EQ(test, host, next); + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 9 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_PTR_EQ(test, host, other); + /* An unmapped BO can host multiple drains at distinct IOVAs. */ + ane->scratch[0].iova = 5 * ANE_TEST_PG; + ane->scratch[0].host = next; + ane->scratch_pages = 1; + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 5 * ANE_TEST_PG, + ANE_TEST_PG, &host), -EBUSY); + KUNIT_EXPECT_NULL(test, host); + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 6 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_PTR_EQ(test, host, next); + /* A hole: the drain reserves its own node. */ + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 10 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_NULL(test, host); + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 40 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_NULL(test, host); + /* Ranges with PTEs cannot take a drain page. */ + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 4 * ANE_TEST_PG, + ANE_TEST_PG, &host), -EBUSY); + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 12 * ANE_TEST_PG, + ANE_TEST_PG, &host), -EBUSY); + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 14 * ANE_TEST_PG, + ANE_TEST_PG, &host), -EBUSY); + KUNIT_EXPECT_NULL(test, host); + /* Past the end of the allocator range. */ + KUNIT_EXPECT_NE(test, ane_dart_scratch_slot(ane, 64 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_NE(test, ane_dart_scratch_slot(ane, U64_MAX & ~(u64)(ANE_TEST_PG - 1), + ANE_TEST_PG, &host), 0); + + drm_mm_remove_node(job); + drm_mm_remove_node(next); + drm_mm_remove_node(other); + drm_mm_remove_node(scratch); + drm_mm_remove_node(kept); + drm_mm_takedown(mm); +} + +/* + * A BO whose range holds a drain page must not be mapped or have its + * range freed until the drain page is released. + */ +static void ane_dart_scratch_in_test(struct kunit *test) +{ + struct ane_device *ane = kunit_kzalloc(test, sizeof(*ane), GFP_KERNEL); + struct drm_mm_node a = {}, b = {}; + + KUNIT_ASSERT_NOT_NULL(test, ane); + KUNIT_EXPECT_FALSE(test, ane_dart_scratch_in(ane, &a)); + ane->scratch[0].host = NULL; /* a page in a hole */ + ane->scratch[1].host = &b; + ane->scratch_pages = 2; + KUNIT_EXPECT_FALSE(test, ane_dart_scratch_in(ane, &a)); + KUNIT_EXPECT_TRUE(test, ane_dart_scratch_in(ane, &b)); + KUNIT_EXPECT_FALSE(test, ane_dart_scratch_in(ane, NULL)); + /* Released: the count is what the drain and release maintain. */ + ane->scratch_pages = 0; + KUNIT_EXPECT_FALSE(test, ane_dart_scratch_in(ane, &b)); +} + +static struct kunit_case ane_bo_test_cases[] = { + KUNIT_CASE(ane_bo_iova_size_test), + KUNIT_CASE_PARAM(ane_bo_check_size_test, ane_bo_size_gen_params), + KUNIT_CASE(ane_dart_scratch_page_zeroed_test), + KUNIT_CASE(ane_dart_scratch_slot_test), + KUNIT_CASE(ane_dart_scratch_in_test), + {} +}; + +static struct kunit_suite ane_bo_test_suite = { + .name = "ane-bo", + .test_cases = ane_bo_test_cases, +}; + +kunit_test_suites(&ane_submit_test_suite, &ane_recovery_test_suite, + &ane_bo_test_suite); MODULE_DESCRIPTION("KUnit tests for the Apple Neural Engine SUBMIT checks"); MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index 1cf7da420b3c97..07921a5b289c7a 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -18,13 +19,16 @@ #include #include #include +#include #include #include #include #include #include +#include #include "ane_fw_cold.h" +#include "ane_fw_pages.h" #include "ane_fw_sleep.h" #include "ane_h16_accel.h" @@ -54,6 +58,13 @@ struct ane_fw_mapping { dma_addr_t physical; /* The DVA range, for a mapping in the window. */ struct drm_mm_node node; + /* + * A cached surface: discontiguous pages (ane_fw_pages_alloc()), mapped + * through b->memory for cache maintenance and at consecutive DVAs. + */ + struct page **pages; + struct sg_table sgt; + bool dma_mapped; }; struct ane_fw_backend { @@ -104,6 +115,12 @@ struct ane_fw_backend { bool pmu_base_set; /* The engine's own ANE_SYS reference (b->power) is held. */ bool power_ref; + /* + * In a runtime PM callback of b->power: genpd has ANE_SYS on (resume) + * or turns it off after the callback (suspend), so the power steps + * take and drop no reference of their own. + */ + bool in_rpm; struct list_head mappings; /* Serialize stage changes, command publication and retained lifetimes. */ struct mutex lock; @@ -133,6 +150,22 @@ struct ane_fw_backend { struct work_struct start; /* ANE_SYS and the child power states are on: the engine is readable. */ bool powered; + /* + * Recovery of a session quarantined by a hung request (ane_fw_hung()): + * at runtime by the recover work, else by the next system sleep. + * hung_down: the quarantined engine was powered off under its firmware; + * from then on genpd's next ANE_SYS OFF, with the PMGR actual state off, + * sets hung_off (ane_fw_genpd_event()), the proof the firmware is gone. + */ + struct delayed_work recover; + bool hung_down, hung_off; + /* Boot time of the OFF that set hung_off. */ + u64 hung_off_at; + /* Runtime recoveries, limited (ane_fw_recover_admit()); under lock. */ + struct ane_fw_recover_limit recover_limit; + /* A power-down outside a sleep: a stuck power word cannot wait for one. */ + bool runtime_off; + u64 recoveries, recover_failures, recover_limited; }; /* One ANE per SoC. The observer exists before platform driver registration: @@ -198,6 +231,12 @@ static struct kexec_blocker ane_fw_kexec = { .reason = "ANE firmware retains private DMA mappings until hardware reset", }; +/* Engines that park have their power held by runtime PM between requests. */ +static bool ane_fw_rpm(const struct ane_fw_backend *b) +{ + return b->soc->macos_sleep; +} + static int ane_fw_quarantine(struct ane_fw_backend *b, int error) { unsigned int i; @@ -205,6 +244,11 @@ static int ane_fw_quarantine(struct ane_fw_backend *b, int error) b->stage = ANE_STAGE_QUARANTINED; dev_err(&b->pdev->dev, "ANE quarantined (%d); mappings and power retained, reboot required\n", error); + /* Runtime PM held a powered engine between requests: pin it on. */ + if (ane_fw_rpm(b) && b->powered && !b->power_ref) { + pm_runtime_get_noresume(&b->pdev->dev); + b->power_ref = true; + } /* The engine and DARTs are only readable once powered. */ if (!b->powered) return error; @@ -472,6 +516,7 @@ static int ane_fw_exclave_mode_stop(struct ane_fw_backend *b) static int ane_fw_suspend_firmware(struct ane_fw_backend *b) { u8 command[8] = {}; + size_t mark; u8 *slot; u32 status; int ret; @@ -485,6 +530,12 @@ static int ane_fw_suspend_firmware(struct ane_fw_backend *b) ret = ane_fw_transport_settle(&b->transport, 2 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC); if (ret < 0) return ret; + /* + * The transport survives a warm sleep, so the arena the 0x31 and + * SUSPEND commands take must be given back once SUSPEND is answered, + * or every sleep would keep it until the next firmware boot. + */ + mark = ane_fw_transport_mark(&b->transport); ret = ane_fw_exclave_mode_stop(b); if (ret) { ane_h16_session_dump_fwlog(&b->session); @@ -514,6 +565,9 @@ static int ane_fw_suspend_firmware(struct ane_fw_backend *b) dev_info(&b->pdev->dev, "H17 ANE: SUSPEND reply %*ph\n", (int)sizeof(command), command); if (get_unaligned_le16(command + 6)) return -EREMOTEIO; + /* Both commands are answered and their replies read. */ + if (ane_fw_transport_release(&b->transport, mark)) + dev_warn(&b->pdev->dev, "H17 ANE: SUSPEND arena not released\n"); dev_info(&b->pdev->dev, "H17 ANE: SUSPEND acknowledged, wrapper status %#x\n", ane_rd32(b, b->engine + b->soc->wrapper + 0x48)); /* @@ -557,7 +611,7 @@ static int ane_fw_ps_off(struct ane_fw_backend *b, u32 offset) if (!ane_poll32(b, reg, ANE_FW_PS_OFF_MASK, 0, 1, 1000)) return 0; } - if (!apple_sleep_request_deep_once()) + if (b->in_rpm || b->runtime_off || !apple_sleep_request_deep_once()) return ret; dev_warn(&b->pdev->dev, "H17 ANE: power word %#x still stuck, taking the deep path\n", offset); return 0; @@ -583,7 +637,7 @@ static int ane_fw_power_down_staged(struct ane_fw_backend *b) if (ret) return ret; /* No engine or DART access from here until ANE_SYS is back on. */ - b->powered = false; + WRITE_ONCE(b->powered, false); b->power_ref = false; pm_runtime_put_sync(b->power); /* @@ -624,16 +678,19 @@ static int ane_fw_power_down(struct ane_fw_backend *b) if (ret) return ret; /* No engine or DART access from here until ANE_SYS is back on. */ - b->powered = false; - b->power_ref = false; + WRITE_ONCE(b->powered, false); /* * Our reference was the last one on ANE_SYS: genpd turns it off once the * ANE DARTs are idle, or at the latest in the noirq phase of the system * suspend. ane_fw_genpd_event() records that, and the resume reports a - * domain that stayed on. + * domain that stayed on. Between requests runtime PM holds the engine + * instead, and its runtime suspend lets the domain go. */ - pm_runtime_put_sync(b->power); - dev_info(&b->pdev->dev, "H17 ANE: powered down for system sleep\n"); + if (b->power_ref) { + b->power_ref = false; + pm_runtime_put_sync_suspend(b->power); + } + dev_info(&b->pdev->dev, "H17 ANE: powered down\n"); return 0; } @@ -736,6 +793,42 @@ static int ane_fw_reload_segment(struct ane_fw_backend *b, unsigned int i) -EKEYREJECTED : 0; } +#define ANE_FW_RECOVER_QUIET_MS 100U + +/* + * A recovered engine takes requests only once it has settled: the new + * firmware has posted nothing for ANE_FW_RECOVER_QUIET_MS (what it posts + * meanwhile, such as its own SHAREDMALLOCs, is served), and its power, DARTs + * and transport read healthy (ane_fw_recover_settled()). Until then the + * session stays closed: the replay waits, and requests wait in + * ane_h16_session_enter(). + */ +static int ane_fw_recover_settle(struct ane_fw_backend *b) +{ + struct ane_fw_settled st = {}; + u64 start = ktime_get_ns(); + int served; + + served = ane_fw_transport_settle(&b->transport, + (u64)ANE_FW_RECOVER_QUIET_MS * NSEC_PER_MSEC, + ((u64)ANE_FW_RECOVER_QUIET_MS + 1000) * NSEC_PER_MSEC); + st.transport_error = served < 0 ? served : b->transport.error; + st.sys = ane_rd32(b, b->pmgr + b->soc->pmgr_sys); + st.cpu = ane_rd32(b, b->pmgr + b->soc->pmgr_cpu); + for (unsigned int i = 0; i < ANE_FW_DARTS; i++) + st.dart_error[i] = ane_rd32(b, b->dart[i] + 0x100); + if (!ane_fw_recover_settled(&st)) { + dev_err(&b->pdev->dev, + "H17 ANE: recovered engine not settled: transport %d, ANE_SYS %#x CPU %#x, DART errors %#x %#x %#x\n", + st.transport_error, st.sys, st.cpu, st.dart_error[0], st.dart_error[1], + st.dart_error[2]); + return st.transport_error ?: -EIO; + } + dev_dbg(&b->pdev->dev, "H17 ANE: recovered engine settled in %llu ms, %d posts served\n", + div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), served); + return 0; +} + /* * After resume, the cold way: power up from the cold state with the same * checks as at boot (the engine and DARTs must read their reset values), @@ -744,8 +837,10 @@ static int ane_fw_reload_segment(struct ane_fw_backend *b, unsigned int i) * and startup as start-at-boot does. The shared allocations are carried * into the new transport and served again; programs loaded before are lost. * Every wait is bounded (power polls, READY, ANE_FW_TIMEOUT_NS commands). + * With @recover the old firmware was a quarantined one, proven gone + * (ane_fw_hung_gone()): its quarantine ends before the replay. */ -static int ane_fw_cold_cycle_boot(struct ane_fw_backend *b) +static int ane_fw_cold_cycle_boot(struct ane_fw_backend *b, bool recover) { struct device *dev = &b->pdev->dev; struct ane_fw_transport *old; @@ -806,11 +901,20 @@ static int ane_fw_cold_cycle_boot(struct ane_fw_backend *b) if (ret) return ret; b->transport.allow_free = true; + /* Nothing reaches a recovered engine before it settled, the replay included. */ + if (recover) { + ret = ane_fw_recover_settle(b); + if (ret) + return ret; + } b->resume_ready_ns = ktime_get_ns(); dev_dbg(dev, "H17 ANE: booted again from the preload after system sleep in %llu ms\n", div_u64(b->resume_ready_ns - start, NSEC_PER_MSEC)); /* Every open program back behind its handle, as the application left it. */ ane_h16_session_restart(&b->session); + /* Programs closed while quarantined go back to the spares. */ + if (recover) + ane_h16_session_recovered(&b->session); ret = ane_h16_session_replay(&b->session, &b->resume_replayed, &b->resume_first_ns); if (ret) { dev_err(dev, "H17 ANE: PROGRAM REPLAY FAILED %d after %u programs; session quarantined\n", @@ -866,15 +970,20 @@ static int ane_fw_stop_wait(struct ane_fw_backend *b) return 0; } -/* Every port of every ANE DART idle: what macOS checks before it powers one down. */ -static int ane_fw_dart_idle(struct ane_fw_backend *b) +/* + * Every port of every ANE DART idle: what macOS checks before it powers one down. + * Polls each active port for up to @timeout_us (sleeping @sleep_us between reads). + */ +static int ane_fw_dart_idle_wait(struct ane_fw_backend *b, unsigned long sleep_us, + u64 timeout_us) { for (unsigned int i = 0; i < ANE_FW_DARTS; i++) { u32 params = ane_rd32(b, b->dart[i] + 4); unsigned int ports = max((params >> 16) & 7, (params >> 20) & 7); for (unsigned int p = 0; p < min(ports, 4U); p++) { - int ret = ane_poll32(b, b->dart[i] + 0x230 + 4 * p, U32_MAX, 0, 1, 10000); + int ret = ane_poll32(b, b->dart[i] + 0x230 + 4 * p, U32_MAX, 0, + sleep_us, timeout_us); if (ret) { dev_err(&b->pdev->dev, "H17 ANE: DART %u port %u not idle: %#x\n", @@ -886,6 +995,11 @@ static int ane_fw_dart_idle(struct ane_fw_backend *b) return 0; } +static int ane_fw_dart_idle(struct ane_fw_backend *b) +{ + return ane_fw_dart_idle_wait(b, 1, 10000); +} + /* * Each DART as macOS leaves it before the power words (recorded, 25G83): its counters * cleared, error status acknowledged, every enabled stream disabled one at a time, then @@ -1015,32 +1129,470 @@ static int ane_fw_cold_cycle_down(struct ane_fw_backend *b) return ane_fw_power_down(b); } -/* A request for a parked engine: boot it from the preload, as after a sleep. */ -static int ane_fw_session_wake(void *ctx) +/* + * The parked engine's autosuspend delay: a request that finds it parked waits + * for a cold boot from the preload and the replay of its programs, ~18 ms on + * a J700 (~10 ms for the boot alone on H16). Two seconds keep that under 1% of + * a pause longer than the delay, and keep the engine from cycling its power + * faster than every two seconds. power/autosuspend_delay_ms changes it; a + * negative value keeps the engine up until the next system sleep. + */ +#define ANE_FW_AUTOSUSPEND_MS 2000 + +/* + * After a bring-up or a boot for a request: hand the engine's ANE_SYS + * reference to runtime PM, which parks the engine once it has been idle for + * its autosuspend delay. A quarantined engine keeps its reference. + */ +static void ane_fw_rpm_idle(struct ane_fw_backend *b) +{ + lockdep_assert_held(&b->lock); + if (!ane_fw_rpm(b) || !b->power_ref || b->stage != ANE_STAGE_PROGRAM || + b->session.quarantined) + return; + b->power_ref = false; + pm_runtime_mark_last_busy(&b->pdev->dev); + pm_runtime_put_autosuspend(&b->pdev->dev); +} + +/* + * Boot a parked engine from the preload, as after a sleep. ANE_SYS is on: + * runtime PM resumed the device, which holds the domain, so the power steps + * take no reference of their own. + */ +static void ane_fw_unpark(struct ane_fw_backend *b) { - struct ane_fw_backend *b = ctx; int ret; - if (READ_ONCE(b->stage) == ANE_STAGE_PROBED) - return READ_ONCE(b->in_sleep) ? -EAGAIN : ane_fw_first_bringup(b); - guard(mutex)(&b->lock); - if (!b->parked) - return 0; - /* The system is going to sleep or coming back: PM_POST_SUSPEND wakes waiters. */ - if (b->in_sleep) - return -EAGAIN; - ret = ane_fw_cold_cycle_boot(b); + lockdep_assert_held(&b->lock); + if (!b->parked || READ_ONCE(b->in_sleep)) + return; + b->in_rpm = true; + ret = ane_fw_cold_cycle_boot(b, false); + b->in_rpm = false; WRITE_ONCE(b->parked, false); WRITE_ONCE(b->session.parked, false); if (ret) { + /* Power and mappings stay for diagnosis: the quarantine pins the device. */ ane_fw_quarantine(b, ret); - b->session.quarantined = true; + WRITE_ONCE(b->session.quarantined, true); } ane_h16_session_sleep(&b->session, false); dev_info(&b->pdev->dev, "H17 ANE: up for a request%s\n", ret ? " FAILED" : ""); +} + +/* + * Recovery of a session quarantined by a hung request, as the H16 and T8112 + * paths do it and as macOS restarts the firmware after a request timeout: + * the engine is powered off under the firmware, proven off, booted again + * from the preload, and every open program is replayed behind its handle. + * + * The firmware is not asked for anything: a STOP to a hung firmware times + * out and changes nothing, and macOS goes on with the power-off when its + * stop is not answered. No new register is written either: the power-down + * is the one a sleep and a park use (sub-block, PWGATE and its ack, CPU, + * then ANE_SYS through genpd, which deactivates the DARTs right before it). + * At runtime we power down only once every ANE DART port reads idle, so no + * DMA is cut off mid-flight; ports that stay busy leave recovery to the + * next system sleep, which takes the deep path. + * + * Nothing the old firmware could reach is reused before ane_fw_hung_proven(): + * genpd reported ANE_SYS off after our power-down, with its PMGR actual + * state off, and the CPU and sub-block power states read off. Only then does + * the cold boot clear pool, IPC, heap and heap tail, copy TEXT and DATA from + * the preload again (digests checked) and give back the memory of programs + * closed while quarantined. The power-up before it repeats the cold PMGR, + * PWGATE and DART checks of every boot. + */ +#define ANE_FW_HUNG_DRAIN_MS 100U +#define ANE_FW_HUNG_OFF_MS 2000 + +/* + * Power a quarantined engine off under its firmware. From here on, genpd's + * next ANE_SYS OFF proves it off: we hold ANE_SYS until the power-down puts + * it, so no OFF can come earlier. + */ +static int ane_fw_hung_down(struct ane_fw_backend *b, bool runtime) +{ + int ret; + + if (!b->hung_down) { + WRITE_ONCE(b->hung_off, false); + /* Seen by ane_fw_genpd_event() before the put below can turn ANE_SYS off. */ + smp_store_release(&b->hung_down, true); + } + if (!b->powered) { + /* Off already: an earlier attempt, whose proof may still come. */ + if (b->power_ref) { + b->power_ref = false; + pm_runtime_put_sync_suspend(b->power); + } + return 0; + } + /* At runtime there is no deep path: a stuck power word fails it. */ + b->runtime_off = runtime; + ret = ane_fw_power_down(b); + b->runtime_off = false; return ret; } +static bool ane_fw_hung_proven(struct ane_fw_backend *b) +{ + struct ane_fw_hung_proof p = { + .down = b->hung_down, + .sys_off = READ_ONCE(b->hung_off), + .held = b->powered || b->power_ref, + }; + + /* PMGR only: readable whatever ANE_SYS does. */ + ane_fw_snapshot_pmgr(b); + return ane_fw_hung_gone(&p, &b->cold); +} + +/* At runtime genpd turns ANE_SYS off once the ANE DARTs are idle too. */ +static bool ane_fw_hung_wait_off(struct ane_fw_backend *b) +{ + u64 deadline = ktime_get_ns() + ANE_FW_HUNG_OFF_MS * NSEC_PER_MSEC; + + while (!READ_ONCE(b->hung_off) && ktime_get_ns() < deadline) + usleep_range(10000, 20000); + return READ_ONCE(b->hung_off); +} + +#define ANE_FW_RECOVER_OFF_MS 100U + +/* + * A recovery used to power ANE_SYS on again within about a millisecond of + * genpd turning it off: the cold boot's power-up followed the proof at once. + * Every other power cycle of the engine (idle park, system sleep) keeps it + * off for seconds. Keep it off for ANE_FW_RECOVER_OFF_MS; returns the ms + * waited. + */ +static unsigned int ane_fw_hung_stay_off(struct ane_fw_backend *b) +{ + u64 min_ns = (u64)ANE_FW_RECOVER_OFF_MS * NSEC_PER_MSEC; + /* Acquire: pairs with the release in ane_fw_genpd_event(), after hung_off_at. */ + u64 off_at = smp_load_acquire(&b->hung_off) ? READ_ONCE(b->hung_off_at) : 0; + u64 wait = ane_fw_recover_off_wait(off_at, ktime_get_boottime_ns(), min_ns); + unsigned int ms = DIV_ROUND_UP_ULL(wait, NSEC_PER_MSEC); + + if (ms) + msleep(ms); + return ms; +} + +/* The new firmware is up: the next hang starts its proof afresh. */ +static void ane_fw_hung_recovered(struct ane_fw_backend *b) +{ + b->hung_down = false; + WRITE_ONCE(b->hung_off, false); + b->recoveries++; +} + +/* + * Runtime recovery limit (ane_fw_recover_admit()): at most five recoveries + * within a minute, backing off from 1 s (doubling each time) so a client that + * hangs the engine again right away cannot storm ANE_SYS power cycles. A sixth + * hang within the window leaves the engine quarantined until a system sleep. + */ +#define ANE_FW_RECOVER_BURST 5U +#define ANE_FW_RECOVER_WINDOW_S 60U +#define ANE_FW_RECOVER_BACKOFF_MS 1000U + +static const struct ane_fw_recover_policy ane_fw_recover_default = { + .burst = ANE_FW_RECOVER_BURST, + .window_ns = (u64)ANE_FW_RECOVER_WINDOW_S * NSEC_PER_SEC, + .backoff_ns = (u64)ANE_FW_RECOVER_BACKOFF_MS * NSEC_PER_MSEC, +}; + +/* + * Whether this recovery may run now. Called under b->lock; a recovery that + * must wait is queued again for then, with the session left quarantined + * (requests fail with -EIO meanwhile and nothing reaches the engine). + */ +static bool ane_fw_recover_admitted(struct ane_fw_backend *b, u64 now) +{ + bool tripped = b->recover_limit.tripped; + u64 wait; + + switch (ane_fw_recover_admit(&b->recover_limit, &ane_fw_recover_default, now, &wait)) { + case ANE_FW_RECOVER_NOW: + ane_fw_recover_note(&b->recover_limit, now); + return true; + case ANE_FW_RECOVER_LATER: + dev_warn(&b->pdev->dev, + "H17 ANE: hung again within %u s: recovery backs off %llu ms\n", + ANE_FW_RECOVER_WINDOW_S, div_u64(wait, NSEC_PER_MSEC)); + mod_delayed_work(system_dfl_wq, &b->recover, + nsecs_to_jiffies(wait) + 1); + return false; + case ANE_FW_RECOVER_STOP: + default: + b->recover_limited++; + if (!tripped) + dev_err(&b->pdev->dev, + "H17 ANE: %u recoveries within %u s: no more runtime recoveries; quarantined until the next system sleep\n", + ANE_FW_RECOVER_BURST, ANE_FW_RECOVER_WINDOW_S); + return false; + } +} + +static void ane_fw_recover_work(struct work_struct *work) +{ + struct ane_fw_backend *b = container_of(to_delayed_work(work), struct ane_fw_backend, + recover); + struct device *dev = &b->pdev->dev; + bool rpm = ane_fw_rpm(b), held = false, reschedule = false; + unsigned int off = 0; + u64 start, last; + int ret; + + /* + * Keep runtime PM from starting a park, and wait for any park in + * flight before taking b->lock so dropping ANE_SYS under b->lock + * cannot wait on a callback that needs b->lock. + */ + if (rpm) { + pm_runtime_get_noresume(dev); + pm_runtime_barrier(dev); + held = true; + } + scoped_guard(mutex, &b->lock) { + /* A system sleep recovers it itself (ane_fw_sleep_prepare()). */ + if (READ_ONCE(b->in_sleep) || b->slept || b->parked || + b->stage != ANE_STAGE_PROGRAM || !b->session.quarantined) { + reschedule = b->stage == ANE_STAGE_PROGRAM && !b->parked && !b->slept && + !READ_ONCE(b->in_sleep) && !b->session.quarantined; + break; + } + start = ktime_get_ns(); + if (!ane_fw_recover_admitted(b, ktime_get_boottime_ns())) + break; + /* Closes admission: requests wait in ane_h16_session_enter() meanwhile. */ + ane_h16_session_sleep(&b->session, true); + /* + * Wait for every ANE DART port to drain before cutting power under a + * firmware that did not stop, as the clean stop and macOS do. + */ + if (b->powered && + ane_fw_dart_idle_wait(b, 1000, ANE_FW_HUNG_DRAIN_MS * USEC_PER_MSEC)) { + b->recover_failures++; + dev_err(dev, + "H17 ANE: hung engine still has DMA in flight after %u ms; no power cut at runtime, quarantined until the next system sleep\n", + ANE_FW_HUNG_DRAIN_MS); + ane_h16_session_sleep(&b->session, false); + break; + } + /* Hand our reference to b->power_ref so ane_fw_hung_down() drops ANE_SYS. */ + if (held) { + if (b->power_ref) + pm_runtime_put_noidle(dev); + else + b->power_ref = true; + held = false; + } + ret = ane_fw_hung_down(b, true); + if (!ret && !ane_fw_hung_wait_off(b)) + ret = -ETIMEDOUT; + if (!ret) + off = ane_fw_hung_stay_off(b); + if (!ret && !ane_fw_hung_proven(b)) + ret = -EIO; + if (ret) { + b->recover_failures++; + dev_err(dev, + "H17 ANE: hung engine not proven off (%d; ANE_SYS %#x CPU %#x sub-block %#x); quarantined until the next system sleep\n", + ret, ane_rd32(b, b->pmgr + b->soc->pmgr_sys), + ane_rd32(b, b->pmgr + b->soc->pmgr_cpu), + ane_rd32(b, b->pmgr + b->soc->pmgr_subblock)); + ane_h16_session_sleep(&b->session, false); + break; + } + b->resume_replayed = 0; + b->resume_first_ns = 0; + ret = ane_fw_cold_cycle_boot(b, true); + if (ret) { + b->recover_failures++; + /* Booted over memory proven free: as any failed boot, until reboot. */ + ane_fw_quarantine(b, ret); + WRITE_ONCE(b->session.quarantined, true); + } else { + ane_fw_hung_recovered(b); + ane_fw_rpm_idle(b); + } + ane_h16_session_sleep(&b->session, false); + dev_info(dev, + "H17 ANE: %s after a hung request in %llu ms (off %u ms), %u programs replayed; recovery %u of %u within %u s\n", + ret ? "recovery FAILED" : "firmware recovered", + div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), off, b->resume_replayed, + ane_fw_recover_recent(&b->recover_limit, ktime_get_boottime_ns(), + ane_fw_recover_default.window_ns, &last), + ANE_FW_RECOVER_BURST, ANE_FW_RECOVER_WINDOW_S); + } + if (held) { + if (reschedule) { + pm_runtime_mark_last_busy(dev); + pm_runtime_put_autosuspend(dev); + } else { + pm_runtime_put_noidle(dev); + } + } +} + +/* Session ops->hung: may run under the session lock, so only queue. */ +static void ane_fw_hung(void *ctx, int error) +{ + struct ane_fw_backend *b = ctx; + + if (READ_ONCE(b->in_sleep)) + return; + if (READ_ONCE(b->recover_limit.tripped)) { + dev_warn(&b->pdev->dev, + "H17 ANE: session quarantined (%d); recovery limit reached, left quarantined\n", + error); + return; + } + dev_warn(&b->pdev->dev, "H17 ANE: session quarantined (%d); restarting the engine\n", + error); + /* A recovery already waiting out its backoff keeps its time. */ + queue_delayed_work(system_dfl_wq, &b->recover, 0); +} + +/* + * A request for a parked engine: runtime PM resumes the device, and its + * resume callback boots the engine. Called without b->lock, which the + * callback takes. + */ +static int ane_fw_session_wake(void *ctx) +{ + struct ane_fw_backend *b = ctx; + int ret; + + if (READ_ONCE(b->stage) == ANE_STAGE_PROBED) { + if (READ_ONCE(b->in_sleep)) + return -EAGAIN; + ret = ane_fw_first_bringup(b); + if (!ret) { + guard(mutex)(&b->lock); + ane_fw_rpm_idle(b); + } + return ret; + } + if (!READ_ONCE(b->parked)) + return 0; + /* The system is going to sleep or coming back: PM_POST_SUSPEND wakes waiters. */ + if (READ_ONCE(b->in_sleep)) + return -EAGAIN; + ret = pm_runtime_resume_and_get(&b->pdev->dev); + if (ret < 0) + return ret; + /* + * Still parked: either the device never suspended (runtime PM forbidden, + * or a negative autosuspend delay) and a system sleep parked the engine, + * or a system sleep began and prevented the resume callback from booting + * it. + */ + if (READ_ONCE(b->parked)) { + guard(mutex)(&b->lock); + ane_fw_unpark(b); + } + if (READ_ONCE(b->parked)) { + pm_runtime_put_sync_suspend(&b->pdev->dev); + return -EAGAIN; + } + pm_runtime_mark_last_busy(&b->pdev->dev); + pm_runtime_put_autosuspend(&b->pdev->dev); + return READ_ONCE(b->session.quarantined) ? -EIO : 0; +} + +/* + * Runtime suspend after the autosuspend delay: the way down a system sleep + * takes, then parked as after a wake, with the session left closed. There + * is no firmware to send anything to: a close is deferred and a request + * waits in ane_h16_session_enter(), which wakes the engine; the wake reopens + * the session, and a program closed meanwhile is lost to the new firmware + * and only released. Outside a system sleep there is no deep path to fall + * back on, so a firmware stop that fails quarantines the engine, which keeps + * its power, as a failed sleep does. + */ +int ane_fw_staged_runtime_suspend(struct device *dev) +{ + struct ane_fw_backend *b = ane_backend; + int ret; + + /* Powered off by a power-down that held the reference: nothing to stop. */ + if (!b || &b->pdev->dev != dev || !ane_fw_rpm(b) || !READ_ONCE(b->powered)) + return 0; + guard(mutex)(&b->lock); + if (!b->powered) + return 0; + /* Bringing up, quarantined, or in a system sleep, which parks it itself. */ + if (b->stage != ANE_STAGE_PROGRAM || READ_ONCE(b->in_sleep) || + READ_ONCE(b->session.quarantined)) + return -EBUSY; + /* Closes admission and waits for every request in flight. */ + ane_h16_session_sleep(&b->session, true); + /* The gate release on the way quarantined it: that is the recovery's (ane_fw_hung()). */ + if (READ_ONCE(b->session.quarantined)) { + ane_h16_session_sleep(&b->session, false); + return -EBUSY; + } + /* + * An execute that raced the autosuspend boundary may have finished while + * draining and refreshed last_busy: wait out the new delay instead of + * parking right after it. + */ + if (pm_runtime_autosuspend_expiration(dev)) { + ane_h16_session_sleep(&b->session, false); + return -EBUSY; + } + for (unsigned int ch = 0; ch < ANE_FW_CHANNELS; ch++) { + if (b->transport.pending[ch].active) { + /* Something is still pending on a ring: autosuspend tries later. */ + ane_h16_session_sleep(&b->session, false); + pm_runtime_mark_last_busy(dev); + return -EBUSY; + } + } + /* Do not cut power at runtime idle if clean firmware stop is disabled. */ + if (!ane_fw_clean_stop(b) || !b->pmu_base_set) { + ane_h16_session_sleep(&b->session, false); + return -EBUSY; + } + b->in_rpm = true; + ret = ane_fw_firmware_stop(b); + if (!ret) + ret = ane_fw_power_down(b); + b->in_rpm = false; + if (ret) { + ane_fw_quarantine(b, ret); + WRITE_ONCE(b->session.quarantined, true); + ane_h16_session_sleep(&b->session, false); + dev_err(dev, "H17 ANE: idle park failed (%d): quarantined\n", ret); + return -EBUSY; + } + WRITE_ONCE(b->parked, true); + WRITE_ONCE(b->session.parked, true); + wake_up_all(&b->session.wake); + dev_info(dev, "H17 ANE: idle: parked until the next request\n"); + return 0; +} + +/* Runtime resume for a request (ane_fw_session_wake()): boot the parked engine. */ +int ane_fw_staged_runtime_resume(struct device *dev) +{ + struct ane_fw_backend *b = ane_backend; + + /* Only a parked engine that serves programs is booted here. */ + if (!b || &b->pdev->dev != dev || !ane_fw_rpm(b) || + READ_ONCE(b->stage) != ANE_STAGE_PROGRAM || !READ_ONCE(b->parked)) + return 0; + guard(mutex)(&b->lock); + ane_fw_unpark(b); + /* A failed boot is the quarantine's to report: the device itself is up. */ + return 0; +} + static int ane_fw_sleep_prepare(struct ane_fw_backend *b) { int ret; @@ -1080,6 +1632,26 @@ static int ane_fw_sleep_prepare(struct ane_fw_backend *b) b->sys_off_at = 0; b->sys_off_pmgr = 0; b->sys_on_pmgr = 0; + /* + * A session quarantined by a hung request (or by the gate release just + * now): the firmware can't be asked for anything, so the engine goes + * off under it, and this sleep takes the deep path, as after a failed + * stop. The resume ends the quarantine once the power-off is proven. + */ + if (b->session.quarantined) { + if (b->powered || !READ_ONCE(b->hung_off)) + apple_sleep_request_deep_once(); + ret = ane_fw_hung_down(b, false); + dev_info(&b->pdev->dev, "H17 ANE: hung engine powered off for system sleep (%d)\n", + ret); + if (ret) { + ane_fw_quarantine(b, ret); + ane_h16_session_sleep(&b->session, false); + return ret; + } + b->slept = true; + return 0; + } if (!ane_fw_sleep_warm(b)) { ret = ane_fw_cold_cycle_down(b); if (ret == -EBUSY) { @@ -1099,7 +1671,7 @@ static int ane_fw_sleep_prepare(struct ane_fw_backend *b) * session (SPEC-ANE-SLEEP.md section 6). */ ane_fw_quarantine(b, ret); - b->session.quarantined = true; + WRITE_ONCE(b->session.quarantined, true); ane_h16_session_sleep(&b->session, false); return ret; } @@ -1141,6 +1713,15 @@ static int ane_fw_genpd_event(struct notifier_block *nb, unsigned long action, v b->sys_offs++; b->sys_off_pmgr = ane_rd32(b, b->pmgr + b->soc->pmgr_sys); b->sys_off_at = now; + /* + * After a hung engine's power-down (acquire: pairs with the release in + * ane_fw_hung_down()): the proof it is gone. + */ + if (smp_load_acquire(&b->hung_down) && ane_fw_sys_off(b->sys_off_pmgr)) { + WRITE_ONCE(b->hung_off_at, now); + /* hung_off_at is read after hung_off (ane_fw_hung_stay_off()). */ + smp_store_release(&b->hung_off, true); + } } else if (action == GENPD_NOTIFY_ON) { b->sys_ons++; b->sys_on_pmgr = ane_rd32(b, b->pmgr + b->soc->pmgr_sys); @@ -1153,6 +1734,7 @@ static int ane_fw_genpd_event(struct notifier_block *nb, unsigned long action, v static void ane_fw_sleep_resume(struct ane_fw_backend *b) { + bool recover = false, warm; s64 ready, first; u64 start; int ret; @@ -1161,8 +1743,21 @@ static void ane_fw_sleep_resume(struct ane_fw_backend *b) if (!b->slept) return; b->slept = false; + /* A hung engine went off for this sleep: a cold boot once proven gone. */ + if (b->session.quarantined) { + if (!ane_fw_hung_proven(b)) { + dev_err(&b->pdev->dev, + "H17 ANE: hung engine not proven off across the sleep (ANE_SYS genpd off %u, PMGR %#x at off; CPU %#x sub-block %#x); kept quarantined\n", + b->sys_offs, b->sys_off_pmgr, b->cold.cpu, b->cold.subblock); + ane_h16_session_sleep(&b->session, false); + return; + } + recover = true; + } /* Stay off until a request needs the engine, as macOS does. */ - if (b->soc->macos_sleep && !b->session.quarantined) { + if (b->soc->macos_sleep && !recover) { + /* Powered off for the sleep: runtime recoveries start counting afresh. */ + ane_fw_recover_reset(&b->recover_limit); WRITE_ONCE(b->parked, true); WRITE_ONCE(b->session.parked, true); dev_info(&b->pdev->dev, "H17 ANE: resume ok: parked until the next request\n"); @@ -1172,19 +1767,27 @@ static void ane_fw_sleep_resume(struct ane_fw_backend *b) b->resume_ready_ns = 0; b->resume_first_ns = 0; b->resume_replayed = 0; - ret = ane_fw_sleep_warm(b) ? ane_fw_warm_boot(b) : ane_fw_cold_cycle_boot(b); - if (ret && ane_fw_sleep_warm(b)) { + /* The firmware of a hung engine was not suspended: only a cold boot. */ + warm = ane_fw_sleep_warm(b) && !recover; + ret = warm ? ane_fw_warm_boot(b) : ane_fw_cold_cycle_boot(b, recover); + if (ret && warm) { /* Fall back to the cold cycle: off again, then boot from the preload. */ dev_warn(&b->pdev->dev, "H17 ANE: warm boot failed (%d); cold boot and program replay\n", ret); ret = b->powered ? ane_fw_power_down(b) : 0; if (!ret) - ret = ane_fw_cold_cycle_boot(b); + ret = ane_fw_cold_cycle_boot(b, false); } if (ret) { /* Every mapping and backing stays for diagnosis. */ ane_fw_quarantine(b, ret); - b->session.quarantined = true; + WRITE_ONCE(b->session.quarantined, true); + } else if (recover) { + ane_fw_hung_recovered(b); + ane_fw_rpm_idle(b); + dev_info(&b->pdev->dev, "H17 ANE: quarantined engine recovered by system sleep%s\n", + b->recover_limit.tripped ? "; recovery limit reset" : ""); + ane_fw_recover_reset(&b->recover_limit); } ane_h16_session_sleep(&b->session, false); /* genpd's record of the domain across this sleep (boot time, so it counts s2idle). */ @@ -1241,9 +1844,34 @@ static int ane_fw_pm_event(struct notifier_block *nb, unsigned long event, void if (event == PM_SUSPEND_PREPARE) { WRITE_ONCE(b->in_sleep, true); WRITE_ONCE(b->session.wake_blocked, true); + /* + * A recovery under way finishes first; one still waiting out its + * backoff is dropped: the sleep recovers the engine itself. + */ + cancel_delayed_work_sync(&b->recover); } if (event == PM_SUSPEND_PREPARE && retained) { - if (!ane_fw_sleep_prepare(b)) + struct device *dev = &b->pdev->dev; + int ret; + + /* + * No idle park from here on: the sleep takes the engine down + * itself. A park that already began finishes first (the sleep + * waits for b->lock and finds the engine parked). + */ + if (ane_fw_rpm(b)) + pm_runtime_get_noresume(dev); + ret = ane_fw_sleep_prepare(b); + if (ane_fw_rpm(b)) { + if (!ret && !READ_ONCE(b->powered)) { + /* Off now, as before: genpd may turn ANE_SYS off. */ + pm_runtime_put_sync_suspend(dev); + } else { + pm_runtime_mark_last_busy(dev); + pm_runtime_put_autosuspend(dev); + } + } + if (!ret) return NOTIFY_DONE; ane_fw_sleep_unblock(b); dev_warn_once(&b->pdev->dev, ANE_FW_SLEEP_REFUSED); @@ -1285,20 +1913,87 @@ static int ane_fw_retain(struct ane_fw_backend *b) return 0; } +/* + * iommu_map and iommu_map_sgtable include the DART's normal range + * synchronization and propagate its timeout. Extra invalidates do not fix + * stale output BAR bindings between programs; the transport's queued first + * EXECUTE after a program change does. + */ +static int ane_fw_map_status(struct ane_fw_backend *b) +{ + for (unsigned int i = 0; i < ANE_FW_DARTS; i++) + if (ane_rd32(b, b->dart[i] + 0x100)) + return -EIO; + return 0; +} + static int ane_fw_map(struct ane_fw_backend *b, u64 dva, phys_addr_t pa, size_t size, int prot) { int ret = iommu_map(b->domain, dva, pa, size, prot, GFP_KERNEL); + return ret ?: ane_fw_map_status(b); +} + +/* + * Pages, CPU alias and cache maintenance of a cached surface no longer mapped + * for the engine (failed allocation before mapping, or after iommu_unmap()). + */ +static void ane_fw_pages_release(struct ane_fw_backend *b, struct ane_fw_mapping *m) +{ + if (m->sgt.sgl) { + if (m->dma_mapped) + dma_unmap_sgtable(b->memory, &m->sgt, DMA_BIDIRECTIONAL, + DMA_ATTR_SKIP_CPU_SYNC); + sg_free_table(&m->sgt); + } + if (m->surface.cpu) + vunmap(m->surface.cpu); + ane_fw_pages_free(m->pages, m->surface.size); +} + +/* + * A cached surface from discontiguous pages: blocks of the DART granule or + * larger, charged to the caller's memcg, with a contiguous CPU alias (vmap) + * and DVA range. The firmware runs from whatever the DARTs map, so nothing + * needs a contiguous physical range the size of the program, which only CMA + * could give (a 66 MB H17 program needed cma=256M). b->memory is dma-direct; + * its mapping only does the cache maintenance, so its addresses must be the + * physical ones. + */ +static int ane_fw_alloc_pages(struct ane_fw_backend *b, size_t size, struct ane_fw_mapping *m) +{ + struct scatterlist *sg; + int min_order, ret; + unsigned int i; + + min_order = ane_fw_pages_granule_order(b->domain->pgsize_bitmap); + if (min_order < 0) + return min_order; + m->pages = ane_fw_pages_alloc(size, min_order, get_order(SZ_2M), + GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_RETRY_MAYFAIL); + if (IS_ERR(m->pages)) { + ret = PTR_ERR(m->pages); + m->pages = NULL; + return ret; + } + m->surface.size = size; + m->surface.cpu = vmap(m->pages, size >> PAGE_SHIFT, VM_MAP, PAGE_KERNEL); + if (!m->surface.cpu) + return -ENOMEM; + ret = sg_alloc_table_from_pages(&m->sgt, m->pages, size >> PAGE_SHIFT, 0, size, + GFP_KERNEL_ACCOUNT | __GFP_NOWARN); if (ret) return ret; - /* iommu_map includes the DART's normal range synchronization and - * propagates its timeout. Extra invalidates do not fix stale output - * BAR bindings between programs; the transport's queued first EXECUTE - * after a program change does. - */ - for (unsigned int i = 0; i < ANE_FW_DARTS; i++) - if (ane_rd32(b, b->dart[i] + 0x100)) + /* Writes the zeroes back before the engine sees the pages. */ + ret = dma_map_sgtable(b->memory, &m->sgt, DMA_BIDIRECTIONAL, 0); + if (ret) + return ret; + m->dma_mapped = true; + if (m->sgt.nents != m->sgt.orig_nents) + return -EIO; + for_each_sgtable_dma_sg(&m->sgt, sg, i) + if (sg_dma_address(sg) != sg_phys(sg) || sg_dma_len(sg) != sg->length) return -EIO; return 0; } @@ -1322,21 +2017,23 @@ static int ane_fw_alloc_mem(struct ane_fw_backend *b, u64 dva, size_t size, m = kzalloc_obj(*m); if (!m) return -ENOMEM; - if (cached) - m->surface.cpu = dma_alloc_noncoherent(b->memory, size, &m->physical, - DMA_BIDIRECTIONAL, GFP_KERNEL); - else + if (cached) { + ret = ane_fw_alloc_pages(b, size, m); + if (ret) { + /* Never mapped for the engine: free it all now. */ + ane_fw_pages_release(b, m); + kfree(m); + return ret; + } + /* The mapping: ane_fw_program_sync() maintains the whole of it. */ + m->surface.handle = (uintptr_t)m; + } else { m->surface.cpu = dma_alloc_coherent(b->memory, size, &m->physical, GFP_KERNEL); - if (!m->surface.cpu) { - kfree(m); - return -ENOMEM; - } - if (cached) { - /* Zero it and write the zeroes back before the engine sees it. */ - memset(m->surface.cpu, 0, size); - dma_sync_single_for_device(b->memory, m->physical, size, DMA_BIDIRECTIONAL); - m->surface.handle = m->physical; + if (!m->surface.cpu) { + kfree(m); + return -ENOMEM; + } } mutex_lock(&b->window_lock); if (dva == ANE_FW_WINDOW_ANY) { @@ -1347,8 +2044,7 @@ static int ane_fw_alloc_mem(struct ane_fw_backend *b, u64 dva, size_t size, if (ret) { mutex_unlock(&b->window_lock); if (cached) - dma_free_noncoherent(b->memory, size, m->surface.cpu, - m->physical, DMA_BIDIRECTIONAL); + ane_fw_pages_release(b, m); else dma_free_coherent(b->memory, size, m->surface.cpu, m->physical); kfree(m); @@ -1364,7 +2060,13 @@ static int ane_fw_alloc_mem(struct ane_fw_backend *b, u64 dva, size_t size, */ list_add_tail(&m->list, &b->mappings); mutex_unlock(&b->window_lock); - ret = ane_fw_map(b, dva, m->physical, size, prot); + if (cached) { + ssize_t mapped = iommu_map_sgtable(b->domain, dva, &m->sgt, prot); + + ret = mapped < 0 ? mapped : (size_t)mapped != size ? -EIO : ane_fw_map_status(b); + } else { + ret = ane_fw_map(b, dva, m->physical, size, prot); + } if (!ret) *s = m->surface; return ret; @@ -1492,10 +2194,22 @@ static int ane_fw_power(struct ane_fw_backend *b, bool raw_boot) return ret; } +static void ane_fw_apply_bridge_ops(struct ane_fw_backend *b) +{ + unsigned int i; + + for (i = 0; i < b->soc->bridge_op_count; i++) { + const struct ane_fw_bridge_op *op = &b->soc->bridge_ops[i]; + void __iomem *reg = b->engine + op->offset; + + ane_wr32(b, ane_fw_bridge_op_apply(ane_rd32(b, reg), op), reg); + } +} + /* * ANE_SYS on, then the child power steps from the cold state, then (for a - * cold boot) the engine's reset values, and CE. At boot and again after a - * power-down for sleep. + * cold boot) the engine's reset values, CE, and any per-SoC engine bridge + * register updates. At boot and again after a power-down for sleep. */ static int ane_fw_power_up(struct ane_fw_backend *b, bool raw_boot, bool cold_engine) { @@ -1505,7 +2219,7 @@ static int ane_fw_power_up(struct ane_fw_backend *b, bool raw_boot, bool cold_en int ret; /* Taken once; a failed attempt keeps it for the retry or the quarantine. */ - if (!b->power_ref) { + if (!b->power_ref && !b->in_rpm) { ret = pm_runtime_resume_and_get(b->power); if (ret < 0) return ret; @@ -1535,7 +2249,7 @@ static int ane_fw_power_up(struct ane_fw_backend *b, bool raw_boot, bool cold_en ret = ane_poll32(b, b->gate + 0x30, U32_MAX, 0, 1, 100000); if (ret) return ret; - b->powered = true; + WRITE_ONCE(b->powered, true); ane_fw_snapshot_engine(b); /* A warm resume finds a suspended firmware's state, not reset values. */ if (cold_engine && !ane_fw_cold_engine_valid(&b->cold, b->soc)) { @@ -1551,6 +2265,7 @@ static int ane_fw_power_up(struct ane_fw_backend *b, bool raw_boot, bool cold_en if ((ane_rd64(b, b->engine + 0x18a4010) & 3) != 3 || ane_rd64(b, b->engine + 0x18a4018)) return -EIO; + ane_fw_apply_bridge_ops(b); dev_dbg(dev, "ANE power: ANE_SYS on, child/PWGATE/CE ready\n"); return 0; } @@ -1989,8 +2704,7 @@ static void ane_fw_program_unmap(void *ctx, const struct ane_fw_surface *s) mutex_unlock(&b->window_lock); return; } - dma_free_noncoherent(b->memory, s->size, m->surface.cpu, m->physical, - DMA_BIDIRECTIONAL); + ane_fw_pages_release(b, m); mutex_lock(&b->window_lock); drm_mm_remove_node(&m->node); mutex_unlock(&b->window_lock); @@ -2008,11 +2722,12 @@ static void ane_fw_program_log(void *ctx, const char *item, u64 a, u64 c) static void ane_fw_program_sync(void *ctx, const struct ane_fw_surface *s, bool for_device) { struct ane_fw_backend *b = ctx; + struct ane_fw_mapping *m = (struct ane_fw_mapping *)(uintptr_t)s->handle; if (for_device) - dma_sync_single_for_device(b->memory, s->handle, s->size, DMA_BIDIRECTIONAL); + dma_sync_sgtable_for_device(b->memory, &m->sgt, DMA_BIDIRECTIONAL); else - dma_sync_single_for_cpu(b->memory, s->handle, s->size, DMA_BIDIRECTIONAL); + dma_sync_sgtable_for_cpu(b->memory, &m->sgt, DMA_BIDIRECTIONAL); } static void ane_fw_program_busy(void *ctx, bool busy) @@ -2020,6 +2735,15 @@ static void ane_fw_program_busy(void *ctx, bool busy) struct ane_fw_backend *b = ctx; apple_clpc_ane_set_active(b->clpc, busy); + /* Under the session lock: no callback runs here, the park drains first. */ + if (!ane_fw_rpm(b)) + return; + if (busy) { + pm_runtime_get_noresume(&b->pdev->dev); + } else { + pm_runtime_mark_last_busy(&b->pdev->dev); + pm_runtime_put_autosuspend(&b->pdev->dev); + } } static const struct ane_h16_session_ops ane_fw_session_ops = { @@ -2029,6 +2753,7 @@ static const struct ane_h16_session_ops ane_fw_session_ops = { .sync = ane_fw_program_sync, .busy = ane_fw_program_busy, .wake = ane_fw_session_wake, + .hung = ane_fw_hung, }; /* @@ -2071,14 +2796,18 @@ static const struct file_operations ane_fw_execute_fops = { static void ane_fw_debugfs(struct ane_fw_backend *b) { - struct dentry *root = debugfs_lookup("ane-h17", NULL); + struct dentry *root = debugfs_lookup("ane-h17", NULL), *dir; bool found = root; if (!found) root = debugfs_create_dir("ane-h17", NULL); - debugfs_create_file("execute", 0600, - debugfs_create_dir(dev_name(&b->pdev->dev), root), - &b->session, &ane_fw_execute_fops); + dir = debugfs_create_dir(dev_name(&b->pdev->dev), root); + debugfs_create_file("execute", 0600, dir, &b->session, &ane_fw_execute_fops); + /* Hung-request recoveries (ane_fw_hung()), at runtime or by a sleep. */ + debugfs_create_u64("recoveries", 0400, dir, &b->recoveries); + debugfs_create_u64("recover_failures", 0400, dir, &b->recover_failures); + /* Recoveries refused by the limit (ane_fw_recover_admit()). */ + debugfs_create_u64("recover_limited", 0400, dir, &b->recover_limited); if (found) dput(root); } @@ -2164,7 +2893,7 @@ static int ane_fw_first_bringup(struct ane_fw_backend *b) b->stage = ANE_STAGE_PROGRAM; ret = 0; } else { - b->session.quarantined = true; + WRITE_ONCE(b->session.quarantined, true); } WRITE_ONCE(b->parked, false); WRITE_ONCE(b->session.parked, false); @@ -2550,6 +3279,7 @@ int ane_fw_staged_init(struct platform_device *pdev, const struct ane_fw_platfor } dev_info(&pdev->dev, "H17 ANE: loader hand-off verified; starting the engine\n"); INIT_WORK(&b->start, ane_fw_start_work); + INIT_DELAYED_WORK(&b->recover, ane_fw_recover_work); return 0; fail: ane_fw_observer_free(b); @@ -2582,10 +3312,17 @@ int ane_fw_staged_bind(struct platform_device *pdev) return ret; pm_runtime_get_noresume(dev); b->bind_held = true; + /* Idle, runtime PM parks the engine (ane_fw_staged_runtime_suspend()). */ + if (ane_fw_rpm(b)) { + pm_runtime_set_autosuspend_delay(dev, ANE_FW_AUTOSUSPEND_MS); + pm_runtime_use_autosuspend(dev); + } } ret = devm_pm_runtime_enable(dev); if (ret) { if (handoff) { + if (ane_fw_rpm(b)) + pm_runtime_dont_use_autosuspend(dev); b->bind_held = false; pm_runtime_put_noidle(dev); pm_runtime_set_suspended(dev); @@ -2615,6 +3352,8 @@ void ane_fw_staged_unbind(struct platform_device *pdev) if (b && b->pdev == pdev) { ane_fw_bind_release(b); + if (ane_fw_rpm(b)) + pm_runtime_dont_use_autosuspend(&pdev->dev); if (b->genpd_nb_added) dev_pm_genpd_remove_notifier(&pdev->dev); b->genpd_nb_added = false; @@ -2656,6 +3395,7 @@ bool ane_fw_staged_exit(void) if (!b) return false; cancel_work_sync(&b->start); + cancel_delayed_work_sync(&b->recover); /* A retained backend pins the module. No unload or in-place retry. */ if (WARN_ON(b->retained)) return true; diff --git a/drivers/accel/ane/ane_fw_cold.h b/drivers/accel/ane/ane_fw_cold.h index 0af12b6ca1bc81..10cc760ef29453 100644 --- a/drivers/accel/ane/ane_fw_cold.h +++ b/drivers/accel/ane/ane_fw_cold.h @@ -86,6 +86,175 @@ static inline bool ane_fw_cold_engine_restartable(const struct ane_fw_cold_state return true; } +/* ANE_SYS's actual power state (PMGR bits 7:4) reads off. */ +static inline bool ane_fw_sys_off(u32 sys) +{ + return !(sys & 0xf0); +} + +/* + * A session quarantined by a hung request, powered off under its firmware + * without a stop. down: our power-down of the quarantined engine began + * (ANE_SYS was still held by us then, so no earlier OFF counts); sys_off: + * genpd then reported ANE_SYS off with its PMGR actual state off; held: we + * hold ANE_SYS or the child power states again. + */ +struct ane_fw_hung_proof { + bool down, sys_off, held; +}; + +/* + * The old firmware is gone, and the memory it could reach (pool, IPC, heap, + * heap tail, DATA, programs closed while quarantined) may be reused, only + * when ANE_SYS really went off after our power-down and the ANE CPU and + * sub-block power states read off now (@pmgr, read from PMGR, which is + * readable in any power state). Anything less keeps the quarantine. + */ +static inline bool ane_fw_hung_gone(const struct ane_fw_hung_proof *p, + const struct ane_fw_cold_state *pmgr) +{ + return p->down && p->sys_off && !p->held && ane_fw_cold_pmgr_valid(pmgr, true); +} + +/* + * How long a recovery still keeps ANE_SYS off, @min_ns from the OFF at + * @off_at (boot time) given @now: the whole of it when the OFF time is + * unknown or lies ahead. + */ +static inline u64 ane_fw_recover_off_wait(u64 off_at, u64 now, u64 min_ns) +{ + if (!off_at || now < off_at) + return min_ns; + return now - off_at >= min_ns ? 0 : min_ns - (now - off_at); +} + +/* + * After a recovery's cold boot, before any request (the replay of open + * programs included) reaches the new firmware: ANE_SYS and the ANE CPU power + * state still target and read on, no DART reports a fault, and the + * transport, after serving what the firmware posted while it went quiet, has + * not failed. Anything less fails the recovery. The sub-block power state and + * CE are left to the firmware once it runs (it gates the engine itself), so + * they are not judged. + */ +struct ane_fw_settled { + u32 sys, cpu; + u32 dart_error[ANE_FW_DARTS]; + int transport_error; +}; + +static inline bool ane_fw_recover_settled(const struct ane_fw_settled *s) +{ + unsigned int i; + + if ((s->sys & 0xff) != 0xff || (s->cpu & 0xff) != 0xff || s->transport_error) + return false; + for (i = 0; i < ANE_FW_DARTS; i++) + if (s->dart_error[i]) + return false; + return true; +} + +/* + * Runtime recoveries of a hung engine are limited. Each one powers the + * engine off under its firmware and boots it again; a client that hangs it + * again right away turns that into a storm of power cycles, and eight of them + * within six seconds locked the whole SoC up on a J700. So: + * + * - the first recovery in @window_ns runs at once; each later one in the + * window waits @backoff_ns after the one before it, twice as long for each + * recovery already in the window, at most @window_ns; + * - a recovery that would be the (@burst + 1)th within @window_ns trips the + * limit: no more runtime recoveries, the engine stays quarantined until a + * system sleep powers it off and boots it again. + * + * Every attempt counts, failed or not, from when it starts. + */ +#define ANE_FW_RECOVER_BURST_MAX 16 + +struct ane_fw_recover_policy { + unsigned int burst; + u64 window_ns, backoff_ns; +}; + +struct ane_fw_recover_limit { + /* Start times of the latest attempts, a ring of count entries before next. */ + u64 at[ANE_FW_RECOVER_BURST_MAX]; + unsigned int next, count; + bool tripped; +}; + +enum ane_fw_recover_verdict { + ANE_FW_RECOVER_NOW, + ANE_FW_RECOVER_LATER, + ANE_FW_RECOVER_STOP, +}; + +/* Attempts that started less than @window_ns before @now, and the latest start. */ +static inline unsigned int ane_fw_recover_recent(const struct ane_fw_recover_limit *l, + u64 now, u64 window_ns, u64 *last) +{ + unsigned int i, recent = 0; + + *last = 0; + for (i = 0; i < l->count; i++) { + u64 at = l->at[(l->next + ANE_FW_RECOVER_BURST_MAX - 1 - i) % + ANE_FW_RECOVER_BURST_MAX]; + + if (at > now || now - at >= window_ns) + break; + if (!recent++) + *last = at; + } + return recent; +} + +/* + * May a recovery start at @now? LATER sets *@wait_ns, after which to ask + * again; STOP trips the limit, which stays tripped until + * ane_fw_recover_reset(). + */ +static inline enum ane_fw_recover_verdict +ane_fw_recover_admit(struct ane_fw_recover_limit *l, const struct ane_fw_recover_policy *p, + u64 now, u64 *wait_ns) +{ + unsigned int burst = clamp(p->burst, 1U, (unsigned int)ANE_FW_RECOVER_BURST_MAX); + u64 last, delay = p->backoff_ns; + unsigned int recent, i; + + *wait_ns = 0; + if (l->tripped) + return ANE_FW_RECOVER_STOP; + recent = ane_fw_recover_recent(l, now, p->window_ns, &last); + if (recent >= burst) { + l->tripped = true; + return ANE_FW_RECOVER_STOP; + } + if (!recent) + return ANE_FW_RECOVER_NOW; + for (i = 1; i < recent && delay < p->window_ns; i++) + delay *= 2; + delay = min(delay, p->window_ns); + if (now - last >= delay) + return ANE_FW_RECOVER_NOW; + *wait_ns = last + delay - now; + return ANE_FW_RECOVER_LATER; +} + +/* A recovery attempt starts at @now. */ +static inline void ane_fw_recover_note(struct ane_fw_recover_limit *l, u64 now) +{ + l->at[l->next] = now; + l->next = (l->next + 1) % ANE_FW_RECOVER_BURST_MAX; + if (l->count < ANE_FW_RECOVER_BURST_MAX) + l->count++; +} + +static inline void ane_fw_recover_reset(struct ane_fw_recover_limit *l) +{ + memset(l, 0, sizeof(*l)); +} + /* * RVBAR (engine +0x1050000) and the TEXT entry: latched at TEXT (bit 0 set) * is ready; with bit 0 clear the entry may be written; latched at any other @@ -184,6 +353,8 @@ int ane_fw_staged_bind(struct platform_device *pdev); bool ane_fw_staged_bound(struct device *dev); void ane_fw_staged_unbind(struct platform_device *pdev); int ane_fw_staged_suspend(struct device *dev); +int ane_fw_staged_runtime_suspend(struct device *dev); +int ane_fw_staged_runtime_resume(struct device *dev); void ane_fw_staged_start(void); bool ane_fw_staged_exit(void); diff --git a/drivers/accel/ane/ane_fw_cold_test.c b/drivers/accel/ane/ane_fw_cold_test.c index cc6052dea2ca21..8aa8b3949dfcde 100644 --- a/drivers/accel/ane/ane_fw_cold_test.c +++ b/drivers/accel/ane/ane_fw_cold_test.c @@ -365,7 +365,234 @@ static void ane_cold_no_clpc_test(struct kunit *test) #endif } +/* + * Recovery of a hung engine reuses its memory only with the whole proof: our + * power-down began, ANE_SYS then went off as PMGR reads it, nothing is held + * again, and the ANE CPU and sub-block read off now. + */ +static void ane_cold_hung_gone_test(struct kunit *test) +{ + const struct ane_fw_hung_proof proven = { .down = true, .sys_off = true }; + struct ane_fw_cold_state off = ane_cold_fixture(), s; + struct ane_fw_hung_proof p; + + KUNIT_EXPECT_TRUE(test, ane_fw_sys_off(0x200)); + KUNIT_EXPECT_TRUE(test, ane_fw_sys_off(0x20f)); + KUNIT_EXPECT_FALSE(test, ane_fw_sys_off(0x23ff)); + KUNIT_EXPECT_FALSE(test, ane_fw_sys_off(0x10)); + + KUNIT_EXPECT_TRUE(test, ane_fw_hung_gone(&proven, &off)); + /* No power-down of ours, so an OFF proves nothing about the hung firmware. */ + p = proven; + p.down = false; + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&p, &off)); + /* ANE_SYS never reported off (runtime DARTs held it, or no genpd notifier). */ + p = proven; + p.sys_off = false; + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&p, &off)); + /* Powered again, or a reference still held. */ + p = proven; + p.held = true; + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&p, &off)); + /* The ANE CPU power state targets or reads on. */ + s = off; + s.cpu |= 0xf; + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&proven, &s)); + s = off; + s.cpu |= 0xf0; + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&proven, &s)); + /* A sub-block word left on, or BUSY latched as a stuck power-down leaves it. */ + s = off; + s.subblock = 0x3ff; + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&proven, &s)); + s = off; + s.subblock = 0x300 | BIT(11); + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&proven, &s)); +} + +#define REC_S(x) ((u64)(x) * NSEC_PER_SEC) +#define REC_MS(x) ((u64)(x) * NSEC_PER_MSEC) + +/* Ask at @now and, when admitted, start the attempt then (as the recover work does). */ +static enum ane_fw_recover_verdict rec_try(struct ane_fw_recover_limit *l, + const struct ane_fw_recover_policy *p, + u64 now, u64 *wait) +{ + enum ane_fw_recover_verdict v = ane_fw_recover_admit(l, p, now, wait); + + if (v == ANE_FW_RECOVER_NOW) + ane_fw_recover_note(l, now); + return v; +} + +/* + * A storm of hangs (0.6 s after each recovery): with the policy (5 in 60 s, + * 1 s backoff) the recoveries spread out to 0, 1, 3, 7 and 15 s, and the + * sixth hang stops them until a system sleep resets the limit. + */ +static void ane_cold_recover_storm_test(struct kunit *test) +{ + const struct ane_fw_recover_policy p = { + .burst = 5, .window_ns = REC_S(60), .backoff_ns = REC_S(1), + }; + static const u64 expect[] = { 0, 1, 3, 7, 15 }; + struct ane_fw_recover_limit l = {}; + u64 now = REC_S(100), wait, started[ARRAY_SIZE(expect)]; + unsigned int done = 0, refused = 0; + + /* Hang 0.6 s after each recovery; a refused one is asked again when told. */ + while (done < ARRAY_SIZE(expect)) { + enum ane_fw_recover_verdict v = rec_try(&l, &p, now, &wait); + + KUNIT_ASSERT_NE(test, v, ANE_FW_RECOVER_STOP); + if (v == ANE_FW_RECOVER_LATER) { + KUNIT_ASSERT_GT(test, wait, 0ULL); + refused++; + now += wait; + continue; + } + started[done++] = now; + now += REC_MS(600); + } + for (unsigned int i = 0; i < ARRAY_SIZE(expect); i++) + KUNIT_EXPECT_EQ(test, started[i] - started[0], REC_S(expect[i])); + KUNIT_EXPECT_EQ(test, refused, 4U); + /* The sixth hang within the minute trips the limit, and it stays tripped. */ + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_STOP); + KUNIT_EXPECT_TRUE(test, l.tripped); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + REC_S(3600), &wait), ANE_FW_RECOVER_STOP); + KUNIT_EXPECT_EQ(test, wait, 0ULL); + /* A system sleep clears it: the next one runs at once. */ + ane_fw_recover_reset(&l); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + REC_S(3601), &wait), ANE_FW_RECOVER_NOW); +} + +/* Backoff doubling, its cap, the sliding window and the burst bounds. */ +static void ane_cold_recover_backoff_test(struct kunit *test) +{ + struct ane_fw_recover_policy p = { + .burst = 16, .window_ns = REC_S(10), .backoff_ns = REC_S(1), + }; + struct ane_fw_recover_limit l = {}; + u64 now = REC_S(1), wait; + + /* First in the window: at once. */ + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + KUNIT_EXPECT_EQ(test, wait, 0ULL); + /* Second: 1 s after the first; asked 0.25 s after it, wait 0.75 s. */ + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + REC_MS(250), &wait), ANE_FW_RECOVER_LATER); + KUNIT_EXPECT_EQ(test, wait, REC_MS(750)); + now += REC_S(1); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + /* Third: 2 s after the second; fourth: 4 s; fifth: capped at the window. */ + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_LATER); + KUNIT_EXPECT_EQ(test, wait, REC_S(2)); + now += REC_S(2); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_LATER); + KUNIT_EXPECT_EQ(test, wait, REC_S(4)); + now += REC_S(4); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + /* Started at 0, 1, 3 and 7 s; at 7 s all four are in the 10 s window. */ + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_LATER); + KUNIT_EXPECT_EQ(test, wait, REC_S(8)); + /* At 10 s the first has left the window: three recent, 4 s after the latest. */ + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + REC_S(3), &wait), ANE_FW_RECOVER_LATER); + KUNIT_EXPECT_EQ(test, wait, REC_S(1)); + /* At 11 s the first two have: two recent, 2 s after the latest, due. */ + now += REC_S(4); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + KUNIT_EXPECT_FALSE(test, l.tripped); + /* Quiet for a whole window: no backoff at all. */ + now += REC_S(10); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + + /* Delays never exceed the window, whatever the backoff. */ + ane_fw_recover_reset(&l); + p.backoff_ns = REC_S(60); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_LATER); + KUNIT_EXPECT_EQ(test, wait, REC_S(10)); + + /* No backoff: only the burst limits. A burst of 0 counts as 1. */ + ane_fw_recover_reset(&l); + p.backoff_ns = 0; + p.burst = 0; + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + 1, &wait), ANE_FW_RECOVER_STOP); + + /* A burst above the ring is the ring: 16 at once, the 17th stops. */ + ane_fw_recover_reset(&l); + p.burst = 100; + for (unsigned int i = 0; i < ANE_FW_RECOVER_BURST_MAX; i++) + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + i, &wait), ANE_FW_RECOVER_NOW); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + 16, &wait), ANE_FW_RECOVER_STOP); + + /* A clock that went back (a stamp after now) is not counted as recent. */ + ane_fw_recover_reset(&l); + p.burst = 2; + p.backoff_ns = REC_S(1); + ane_fw_recover_note(&l, now + REC_S(5)); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); +} + +/* A recovery keeps ANE_SYS off for its minimum, counted from genpd's OFF. */ +static void ane_cold_recover_off_test(struct kunit *test) +{ + const u64 min = 100 * NSEC_PER_MSEC, off = 5 * NSEC_PER_SEC; + + /* The storm's recoveries powered up again within about a millisecond. */ + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(off, off + NSEC_PER_MSEC, min), + 99 * NSEC_PER_MSEC); + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(off, off, min), min); + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(off, off + min, min), 0ULL); + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(off, off + NSEC_PER_SEC, min), 0ULL); + /* No OFF recorded, or one in the future: wait the whole minimum. */ + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(0, off, min), min); + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(off, off - 1, min), min); + /* No minimum: never wait. */ + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(off, off, 0), 0ULL); + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(0, off, 0), 0ULL); +} + +/* A recovered engine takes requests only with everything reading healthy. */ +static void ane_cold_recover_settled_test(struct kunit *test) +{ + const struct ane_fw_settled up = { .sys = 0x23ff, .cpu = 0x0f0003ff }; + struct ane_fw_settled s; + + KUNIT_EXPECT_TRUE(test, ane_fw_recover_settled(&up)); + /* ANE_SYS or the CPU not (yet) on, in target or actual state. */ + s = up; + s.sys = 0x230f; + KUNIT_EXPECT_FALSE(test, ane_fw_recover_settled(&s)); + s = up; + s.sys = 0x23f0; + KUNIT_EXPECT_FALSE(test, ane_fw_recover_settled(&s)); + s = up; + s.cpu = 0x0f0003f0; + KUNIT_EXPECT_FALSE(test, ane_fw_recover_settled(&s)); + s = up; + s.cpu = 0x0f000300; + KUNIT_EXPECT_FALSE(test, ane_fw_recover_settled(&s)); + /* A DART fault on any of the three. */ + for (unsigned int i = 0; i < ANE_FW_DARTS; i++) { + s = up; + s.dart_error[i] = 0x80000001; + KUNIT_EXPECT_FALSE(test, ane_fw_recover_settled(&s)); + } + /* The transport failed while serving the new firmware's posts. */ + s = up; + s.transport_error = -ENOSPC; + KUNIT_EXPECT_FALSE(test, ane_fw_recover_settled(&s)); +} + static struct kunit_case ane_cold_cases[] = { + KUNIT_CASE(ane_cold_recover_settled_test), + KUNIT_CASE(ane_cold_recover_off_test), + KUNIT_CASE(ane_cold_recover_storm_test), + KUNIT_CASE(ane_cold_recover_backoff_test), + KUNIT_CASE(ane_cold_hung_gone_test), KUNIT_CASE(ane_cold_no_clpc_test), KUNIT_CASE(ane_cold_restartable_test), KUNIT_CASE(ane_cold_rvbar_test), diff --git a/drivers/accel/ane/ane_fw_pages.c b/drivers/accel/ane/ane_fw_pages.c new file mode 100644 index 00000000000000..c0dba2a11f0766 --- /dev/null +++ b/drivers/accel/ane/ane_fw_pages.c @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Discontiguous backing for ANE buffers. The engine sees memory only through + * its DARTs, so a buffer needs to be contiguous in the engine's address + * space only: it is built from blocks of at least 1 << min_order pages (the + * DART granule), each physically contiguous and naturally aligned, and the + * caller maps them at consecutive DVAs. A large program then loads without a + * contiguous allocation the size of the program (CMA, or the buddy + * allocator's largest order). + */ +#include +#include +#include +#include +#include +#include + +#include "ane_fw_pages.h" + +/** + * ane_fw_pages_alloc - zeroed pages for a buffer the engine sees through its DARTs + * @size: bytes, a nonzero multiple of PAGE_SIZE << @min_order + * @min_order: order of the smallest block: the DART granule + * @max_order: order of the largest block to try + * @gfp: allocation flags of the smallest blocks (__GFP_ACCOUNT also charges + * the page array) + * + * Blocks start at the largest order the remaining size fills, as dma-iommu + * builds its buffers, and fall back to smaller ones; an order that failed is + * not tried again for this buffer. Only the smallest blocks reclaim as @gfp + * permits: the larger ones are opportunistic (__GFP_NORETRY). No failure + * warns: userspace chooses the size. + * + * Every block is split into order-0 pages, so each page has its own + * reference, as vm_insert_pages() and vmap() want; pages[i * (1 << min_order)] + * starts a physically contiguous block of at least 1 << min_order pages, + * naturally aligned. + * + * Return: the page array (kvfree()d by ane_fw_pages_free()), or an ERR_PTR. + */ +struct page **ane_fw_pages_alloc(size_t size, unsigned int min_order, + unsigned int max_order, gfp_t gfp) +{ + unsigned long count = size >> PAGE_SHIFT, done = 0; + unsigned int order; + struct page **pages; + + if (!size || min_order > MAX_PAGE_ORDER || + !IS_ALIGNED(size, PAGE_SIZE << min_order) || (gfp & __GFP_COMP)) + return ERR_PTR(-EINVAL); + gfp |= __GFP_ZERO | __GFP_NOWARN; + pages = kvcalloc(count, sizeof(*pages), + GFP_KERNEL | (gfp & __GFP_ACCOUNT) | __GFP_NOWARN); + if (!pages) + return ERR_PTR(-ENOMEM); + order = clamp(max_order, min_order, (unsigned int)MAX_PAGE_ORDER); + while (done < count) { + struct page *page; + + order = ane_fw_pages_order(count - done, order, min_order); + page = alloc_pages(order > min_order ? + (gfp & ~__GFP_RETRY_MAYFAIL) | __GFP_NORETRY : gfp, + order); + if (!page) { + if (order == min_order) + goto fail; + order--; + continue; + } + if (order) + split_page(page, order); + for (unsigned long i = 0; i < 1UL << order; i++) + pages[done + i] = page + i; + done += 1UL << order; + } + return pages; + +fail: + ane_fw_pages_free(pages, done << PAGE_SHIFT); + return ERR_PTR(-ENOMEM); +} +EXPORT_SYMBOL_GPL(ane_fw_pages_alloc); + +/* Free the first @size bytes of pages and the array; NULL is a no-op. */ +void ane_fw_pages_free(struct page **pages, size_t size) +{ + if (!pages) + return; + for (unsigned long i = 0; i < size >> PAGE_SHIFT; i++) + __free_page(pages[i]); + kvfree(pages); +} +EXPORT_SYMBOL_GPL(ane_fw_pages_free); + +MODULE_DESCRIPTION("Discontiguous page backing for Apple Neural Engine buffers"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_fw_pages.h b/drivers/accel/ane/ane_fw_pages.h new file mode 100644 index 00000000000000..500356577157f2 --- /dev/null +++ b/drivers/accel/ane/ane_fw_pages.h @@ -0,0 +1,41 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_FW_PAGES_H__ +#define __ANE_FW_PAGES_H__ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Minimum page allocation order for an IOMMU domain's smallest granule, or + * -EINVAL if @pgsize_bitmap has no page size set. + */ +static inline int ane_fw_pages_granule_order(unsigned long pgsize_bitmap) +{ + if (!pgsize_bitmap) + return -EINVAL; + return get_order(1UL << __ffs(pgsize_bitmap)); +} + +/* + * The order of the next block of a discontiguous buffer with @remaining + * pages to go, at most @order (the last order that worked) and at least + * @min_order: the largest power of two the rest still fills. @remaining is + * a nonzero multiple of 1 << @min_order. + */ +static inline unsigned int ane_fw_pages_order(unsigned long remaining, unsigned int order, + unsigned int min_order) +{ + return max(min_t(unsigned int, order, ilog2(remaining)), min_order); +} + +struct page **ane_fw_pages_alloc(size_t size, unsigned int min_order, + unsigned int max_order, gfp_t gfp); +void ane_fw_pages_free(struct page **pages, size_t size); + +#endif diff --git a/drivers/accel/ane/ane_fw_pages_test.c b/drivers/accel/ane/ane_fw_pages_test.c new file mode 100644 index 00000000000000..c27f81cbb78d1b --- /dev/null +++ b/drivers/accel/ane/ane_fw_pages_test.c @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include +#include +#include +#include +#include + +#include "ane_fw_pages.h" + +/* The largest block the rest fills, never above the last one that worked. */ +static void ane_pages_order_test(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(13, 7, 0), 3U); + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(5, 7, 0), 2U); + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(1, 7, 0), 0U); + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(4096, 7, 0), 7U); + /* After a failure at order 3, a 13-page rest takes order 2 blocks. */ + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(13, 2, 0), 2U); + /* Never below the DART granule. */ + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(4, 7, 2), 2U); + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(12, 1, 2), 2U); +} + +/* + * Every DART granule is physically contiguous and aligned, every page is an + * order-0 page with its own reference, and the memory is zeroed. + */ +static void ane_pages_check(struct kunit *test, struct page **pages, size_t size, + unsigned int min_order) +{ + unsigned long block = 1UL << min_order, count = size >> PAGE_SHIFT; + + for (unsigned long i = 0; i < count; i++) { + unsigned long first = page_to_pfn(pages[round_down(i, block)]); + + KUNIT_ASSERT_NOT_NULL(test, pages[i]); + KUNIT_EXPECT_TRUE(test, IS_ALIGNED(first, block)); + KUNIT_EXPECT_EQ(test, page_to_pfn(pages[i]), first + i % block); + KUNIT_EXPECT_FALSE(test, PageCompound(pages[i])); + KUNIT_EXPECT_EQ(test, page_count(pages[i]), 1); + KUNIT_EXPECT_TRUE(test, mem_is_zero(page_address(pages[i]), PAGE_SIZE)); + } +} + +/* A size that is no power of two takes blocks of several orders. */ +static void ane_pages_mixed_test(struct kunit *test) +{ + unsigned int min_order = get_order(SZ_16K); + size_t size = 13 * SZ_16K; + struct page **pages; + u8 *cpu; + + pages = ane_fw_pages_alloc(size, min_order, get_order(SZ_2M), + GFP_KERNEL_ACCOUNT | __GFP_ZERO); + KUNIT_ASSERT_FALSE(test, IS_ERR(pages)); + ane_pages_check(test, pages, size, min_order); + /* The CPU alias the backend makes: one contiguous view of every page. */ + cpu = vmap(pages, size >> PAGE_SHIFT, VM_MAP, PAGE_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, cpu); + for (unsigned long i = 0; i < size >> PAGE_SHIFT; i++) + cpu[i * PAGE_SIZE + 7] = i + 1; + for (unsigned long i = 0; i < size >> PAGE_SHIFT; i++) { + KUNIT_EXPECT_EQ(test, ((u8 *)page_address(pages[i]))[7], (u8)(i + 1)); + KUNIT_EXPECT_PTR_EQ(test, vmalloc_to_page(cpu + i * PAGE_SIZE), pages[i]); + } + vunmap(cpu); + ane_fw_pages_free(pages, size); +} + +/* The minimum block order follows the IOMMU domain's smallest page size. */ +static void ane_pages_granule_test(struct kunit *test) +{ + struct page **pages; + int min_order; + + KUNIT_EXPECT_EQ(test, ane_fw_pages_granule_order(0), -EINVAL); + KUNIT_EXPECT_EQ(test, ane_fw_pages_granule_order(SZ_4K), get_order(SZ_4K)); + KUNIT_EXPECT_EQ(test, ane_fw_pages_granule_order(SZ_16K), get_order(SZ_16K)); + KUNIT_EXPECT_EQ(test, ane_fw_pages_granule_order(SZ_64K), get_order(SZ_64K)); + KUNIT_EXPECT_EQ(test, ane_fw_pages_granule_order(SZ_16K | SZ_2M), get_order(SZ_16K)); + KUNIT_EXPECT_EQ(test, ane_fw_pages_granule_order(SZ_4K | SZ_16K), get_order(SZ_4K)); + + min_order = ane_fw_pages_granule_order(SZ_64K | SZ_2M); + KUNIT_ASSERT_GE(test, min_order, 0); + /* The helper enforces zeroing even when __GFP_ZERO is omitted. */ + pages = ane_fw_pages_alloc(3 * SZ_64K, min_order, get_order(SZ_2M), + GFP_KERNEL_ACCOUNT); + KUNIT_ASSERT_FALSE(test, IS_ERR(pages)); + ane_pages_check(test, pages, 3 * SZ_64K, min_order); + ane_fw_pages_free(pages, 3 * SZ_64K); +} + +/* A larger buffer, as a program region: granule blocks at the very least. */ +static void ane_pages_large_test(struct kunit *test) +{ + unsigned int min_order = get_order(SZ_16K); + size_t size = SZ_8M + 3 * SZ_16K; + struct page **pages; + + pages = ane_fw_pages_alloc(size, min_order, get_order(SZ_2M), + GFP_KERNEL_ACCOUNT | __GFP_ZERO); + KUNIT_ASSERT_FALSE(test, IS_ERR(pages)); + ane_pages_check(test, pages, size, min_order); + ane_fw_pages_free(pages, size); +} + +/* Orders out of the allocator's range are clamped, not tried (or warned about). */ +static void ane_pages_clamp_test(struct kunit *test) +{ + unsigned int min_order = get_order(SZ_16K); + struct page **pages; + + pages = ane_fw_pages_alloc(2 * SZ_16K, min_order, MAX_PAGE_ORDER + 4, + GFP_KERNEL_ACCOUNT | __GFP_ZERO); + KUNIT_ASSERT_FALSE(test, IS_ERR(pages)); + ane_pages_check(test, pages, 2 * SZ_16K, min_order); + ane_fw_pages_free(pages, 2 * SZ_16K); + /* A maximum below the granule still allocates granules. */ + pages = ane_fw_pages_alloc(3 * SZ_16K, min_order, 0, + GFP_KERNEL_ACCOUNT | __GFP_ZERO); + KUNIT_ASSERT_FALSE(test, IS_ERR(pages)); + ane_pages_check(test, pages, 3 * SZ_16K, min_order); + ane_fw_pages_free(pages, 3 * SZ_16K); +} + +static void ane_pages_invalid_test(struct kunit *test) +{ + unsigned int min_order = get_order(SZ_16K); + + KUNIT_EXPECT_EQ(test, PTR_ERR(ane_fw_pages_alloc(0, min_order, 7, GFP_KERNEL)), + -EINVAL); + /* Only whole DART granules. */ + KUNIT_EXPECT_EQ(test, PTR_ERR(ane_fw_pages_alloc(5 * PAGE_SIZE, 2, 7, GFP_KERNEL)), + -EINVAL); + KUNIT_EXPECT_EQ(test, PTR_ERR(ane_fw_pages_alloc(SZ_16K, MAX_PAGE_ORDER + 1, + MAX_PAGE_ORDER + 1, GFP_KERNEL)), + -EINVAL); + KUNIT_EXPECT_EQ(test, PTR_ERR(ane_fw_pages_alloc(SZ_16K, min_order, min_order, + GFP_KERNEL | __GFP_COMP)), + -EINVAL); + /* Freeing nothing is fine. */ + ane_fw_pages_free(NULL, SZ_16K); +} + +static struct kunit_case ane_pages_cases[] = { + KUNIT_CASE(ane_pages_order_test), + KUNIT_CASE(ane_pages_granule_test), + KUNIT_CASE(ane_pages_mixed_test), + KUNIT_CASE(ane_pages_large_test), + KUNIT_CASE(ane_pages_clamp_test), + KUNIT_CASE(ane_pages_invalid_test), + {} +}; + +static struct kunit_suite ane_pages_suite = { + .name = "ane-fw-pages", + .test_cases = ane_pages_cases, +}; + +kunit_test_suite(ane_pages_suite); + +MODULE_DESCRIPTION("KUnit tests for the ANE discontiguous page backing"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_fw_platform.c b/drivers/accel/ane/ane_fw_platform.c index b020192b4d8082..1ba2da0cce8c98 100644 --- a/drivers/accel/ane/ane_fw_platform.c +++ b/drivers/accel/ane/ane_fw_platform.c @@ -33,6 +33,20 @@ static const u32 ane_t8132_reg_sizes[] = { 0x2000000, 0x18000, 0x4000, 0x30000, 0xff4000, 0x4000, }; +/* T8122 (M3) H15: engine, PMGR and PMGR aux-0 windows from the ADT. */ +static const char * const ane_t8122_reg_names[] = { + "engine", "pmgr", "aux-0", +}; + +static const u32 ane_t8122_reg_sizes[] = { + 0x2000000, 0x18000, 0x4000, +}; + +/* The same five domains; ANE_SYS sits at +0x438 in the T8122 PMGR. */ +static const u32 ane_t8122_power_words[] = { + 0x438, 0xc008, 0xc000, 0xc010, 0xc018, +}; + /* Offsets in reg[1]; genpd, never the ANE driver, owns transitions. */ static const u32 ane_h16_power_words[] = { 0x3c0, 0xc008, 0xc000, 0xc010, 0xc018, @@ -64,6 +78,51 @@ static const u8 ane_t6050_text_pin_27_0[] = { 0xd1, 0xa2, 0x20, 0xd0, 0xee, 0x43, 0x8b, 0x8f, }; +/* + * M3 (T8122): H15 engine running the macOS 27.2 (26B123) firmware on the + * shared H16 AP-direct backend: ASC wrapper at +0x1400000, scratch at + * +0x1840050, doorbell/IPI at +0x1844000, ANE_SYS at PMGR +0x438, and five + * DAPF records at DART0 + 0x4000. Cold restart + program replay across sleep. + */ +const struct ane_fw_platform ane_t8122_platform = { + .h16_profiles = ane_t8122_profiles_26b123, + .h16_profile_count = ARRAY_SIZE(ane_t8122_profiles_26b123), + .h16_mmio = ane_h15_mmio_t8122, + .h16_mmio_count = ARRAY_SIZE(ane_h15_mmio_t8122), + .dart_params = 0x8, + .dapf_dart = 0, + .dapf_offset = 0x4000, + .dapf_size = SZ_16K, + .dapf_count = 5, + .soc = 0x8122, + .chip_family = 15, + .ane_type = 0xb0, + .hwx_subtype = 6, + .task_generation = 15, + .interrupt_count = 1, + .irq_role = ANE_FW_IRQ_UNKNOWN, + .owner = ANE_FW_OWNER_AP, + .reg_names = ane_t8122_reg_names, + .reg_sizes = ane_t8122_reg_sizes, + .reg_count = ARRAY_SIZE(ane_t8122_reg_names), + .wrapper = 0x1400000, + .mailbox = 0x1408000, + .scratch = 0x1840050, + .doorbell = 0x1844000, + .irq_status = 0x184c000, + .irq_ack = 0x1850000, + .power_words = ane_t8122_power_words, + .power_count = ARRAY_SIZE(ane_t8122_power_words), + .build_name = "27.2 26B123", + .preload_dva = { 0x10000000000, 0x100000c8000 }, + .preload_size = { 0xc8000, 0x2a4000 }, + .stream_mask = BIT(0), + .sleep_cold = true, + .boot_qualified = true, + .firmware_preloaded = true, + .safe_reset = false, +}; + const struct ane_fw_platform ane_h16_platform = { .h16_profiles = ane_h16_profiles, .h16_profile_count = ARRAY_SIZE(ane_h16_profiles), @@ -247,6 +306,9 @@ const struct ane_fw_platform ane_h17_platform = { .boot_qualified = true, \ .firmware_preloaded = true, \ .safe_reset = false, \ + /* Exclave mode at boot, cold sleep cycle and parked start. */ \ + .exclave_mode_stop = true, \ + .macos_sleep = true, \ .sleep_warm = false, \ .pmgr_sys = 0x3a8, \ .pmgr_cpu = 0x3c8, \ @@ -318,7 +380,55 @@ const struct ane_fw_platform ane_t6050_platform = { * T8140's order: sub-block, PWGATE request 3, acknowledge 0, CPU, then * ANE_SYS. So sleep and the parked start follow T8140. */ +/* + * T8142 engine bus-bridge setup (engine + 0x0000..0x400c), written after + * CE bring-up and before releasing the ANE CPU on every power-up. Without + * these register updates the bridge remains at its reset configuration and + * bottlenecks compute-bound models by 1.4x-3.1x on J813. + * + * Derived directly from clean-room Aura Stage-2 hypervisor MMIO traces of + * engine + 0x0000..0x401c across two consecutive ANE power-up cycles on + * J813 (T8142); /arm-io/ane in the T8142 ADT carries no bridge tunable + * properties. Each entry records only the bits observed to change + * (clear = R32 & ~W32, set = W32 & ~R32) on the 25 registers whose value + * changed (8 traced no-op writes where W32 == R32 are omitted), preserving + * all unmodified reset bits without inferred field masks. + */ +static const struct ane_fw_bridge_op ane_t8142_bridge_ops[] = { + /* Engine bridge block +0x0000..0x0034. */ + { 0x0000, 0x00000000, 0x8000001a }, + { 0x0004, 0x00000002, 0x800c000c }, + { 0x0008, 0x00000002, 0x800c000c }, + { 0x000c, 0x00000002, 0x800c000c }, + { 0x0010, 0x00000000, 0x80000001 }, + { 0x0014, 0x00000000, 0x80000001 }, + { 0x0018, 0x00000008, 0x80000012 }, + { 0x001c, 0x00000000, 0x80000010 }, + { 0x0020, 0x00000002, 0x8010000c }, + { 0x0024, 0x00000002, 0x80000004 }, + { 0x0028, 0x00000002, 0x80000004 }, + { 0x002c, 0x00000000, 0x80000004 }, + { 0x0030, 0x00000008, 0x80000010 }, + { 0x0034, 0x00000008, 0x80000010 }, + /* Engine bridge block +0x0100..0x0108. */ + { 0x0100, 0x00000000, 0x000000ff }, + { 0x0104, 0x00000000, 0x00000003 }, + { 0x0108, 0x00000006, 0x00000001 }, + /* Engine bridge block +0x0300..0x0404. */ + { 0x0300, 0x00000000, 0x1c000001 }, + { 0x0304, 0x00000000, 0x02020000 }, + { 0x0314, 0x00000000, 0x80000000 }, + { 0x031c, 0x00000000, 0x80000000 }, + { 0x0324, 0x00000000, 0x80000000 }, + { 0x0404, 0xffee0000, 0x00000041 }, + /* Engine bridge registers +0x0b00 and +0x400c. */ + { 0x0b00, 0x00000000, 0x7fffffff }, + { 0x400c, 0x00000001, 0x00000000 }, +}; + #define ANE_T8142_PLATFORM \ + .bridge_ops = ane_t8142_bridge_ops, \ + .bridge_op_count = ARRAY_SIZE(ane_t8142_bridge_ops), \ .soc = 0x8142, \ .chip_family = 17, \ .ane_type = 0x210, \ @@ -598,3 +708,18 @@ int ane_fw_platform_resume(struct device *dev) return 0; return ane_h16_backend_resume(dev); } + +/* Runtime PM callbacks of the bound H16 or H17 device. */ +int ane_fw_platform_runtime_suspend(struct device *dev) +{ + if (ane_fw_staged_bound(dev)) + return ane_fw_staged_runtime_suspend(dev); + return ane_h16_backend_runtime_suspend(dev); +} + +int ane_fw_platform_runtime_resume(struct device *dev) +{ + if (ane_fw_staged_bound(dev)) + return ane_fw_staged_runtime_resume(dev); + return ane_h16_backend_runtime_resume(dev); +} diff --git a/drivers/accel/ane/ane_fw_platform.h b/drivers/accel/ane/ane_fw_platform.h index f203f426a91844..bd553fe342e89b 100644 --- a/drivers/accel/ane/ane_fw_platform.h +++ b/drivers/accel/ane/ane_fw_platform.h @@ -27,6 +27,12 @@ enum ane_fw_irq_role { ANE_FW_IRQ_CHANNELS, }; +struct ane_fw_bridge_op { + u32 offset; + u32 clear; + u32 set; +}; + /* Later firmware generations must never enter the H14 staging path. */ struct ane_fw_platform { const struct ane_h16_profile *h16_profiles; @@ -34,6 +40,9 @@ struct ane_fw_platform { /* DART/DAPF register tables, one per supported DART revision. */ const struct ane_h16_mmio *h16_mmio; unsigned int h16_mmio_count; + /* Engine AXI2AF bridge register updates applied after CE bring-up at every power-up. */ + const struct ane_fw_bridge_op *bridge_ops; + unsigned int bridge_op_count; /* DART PARAMS3, the one DART register read before a table is chosen. */ u32 dart_params; /* The DAPF bank: iommus entry that owns it, offset from its reg, size. */ @@ -125,6 +134,12 @@ struct ane_fw_platform { const char *build_name; }; +static inline u32 ane_fw_bridge_op_apply(u32 current_val, + const struct ane_fw_bridge_op *op) +{ + return (current_val & ~op->clear) | op->set; +} + /* Pure range check: the boot loader supplies the physical addresses. */ static inline bool ane_fw_preload_ranges_valid(const struct ane_fw_platform *soc, const u64 phys[2], @@ -171,6 +186,7 @@ ane_fw_sleep_path(const struct ane_fw_platform *platform) extern const struct ane_fw_platform ane_h16_platform, ane_h17_platform, ane_t6050_platform, ane_t8142_platform; +extern const struct ane_fw_platform ane_t8122_platform; extern const struct ane_fw_platform ane_t8132_platform; int ane_fw_platform_preflight(struct platform_device *pdev, const struct ane_fw_platform *soc); @@ -180,6 +196,8 @@ int ane_fw_platform_probe(struct platform_device *pdev, void ane_fw_platform_remove(struct platform_device *pdev); int ane_fw_platform_suspend(struct device *dev); int ane_fw_platform_resume(struct device *dev); +int ane_fw_platform_runtime_suspend(struct device *dev); +int ane_fw_platform_runtime_resume(struct device *dev); int ane_fw_preload_range(struct device_node *np, unsigned int index, u64 *phys, u64 *size); const struct ane_fw_platform *ane_fw_platform_build(struct device_node *np, const struct ane_fw_platform *soc); @@ -187,5 +205,7 @@ int ane_h16_backend_probe(struct platform_device *pdev, const struct ane_fw_plat void ane_h16_backend_remove(struct platform_device *pdev); int ane_h16_backend_suspend(struct device *dev); int ane_h16_backend_resume(struct device *dev); +int ane_h16_backend_runtime_suspend(struct device *dev); +int ane_h16_backend_runtime_resume(struct device *dev); #endif /* __ANE_FW_PLATFORM_H__ */ diff --git a/drivers/accel/ane/ane_fw_platform_test.c b/drivers/accel/ane/ane_fw_platform_test.c index 66b8a8565a507e..31119a89111aa8 100644 --- a/drivers/accel/ane/ane_fw_platform_test.c +++ b/drivers/accel/ane/ane_fw_platform_test.c @@ -38,6 +38,27 @@ static void ane_preload_ranges_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, ane_fw_preload_ranges_valid(&soc, phys, size, dva)); } +static void ane_preload_physical_order_test(struct kunit *test) +{ + const struct ane_fw_platform platform = { + .preload_dva = { SZ_1M, SZ_1M + SZ_16K }, + .preload_size = { SZ_16K, SZ_32K }, + }; + const u64 *size = platform.preload_size; + const u64 *dva = platform.preload_dva; + u64 phys[] = { SZ_2M + SZ_32K, SZ_2M }; + + /* DATA can precede TEXT and touch its boundary in physical memory. */ + KUNIT_EXPECT_TRUE(test, ane_fw_preload_ranges_valid(&platform, phys, size, dva)); + phys[0] -= SZ_16K; + KUNIT_EXPECT_FALSE(test, ane_fw_preload_ranges_valid(&platform, phys, size, dva)); + + /* DATA's end must not wrap, even if its base is valid and aligned. */ + phys[0] = SZ_2M; + phys[1] = U64_MAX - SZ_16K + 1; + KUNIT_EXPECT_FALSE(test, ane_fw_preload_ranges_valid(&platform, phys, size, dva)); +} + /* * H16 and H17 devices (any firmware platform) take the backend's sleep path, * never the rtclient one; only the H13/H14 rtclient (no platform) does. @@ -68,6 +89,32 @@ static void ane_platform_staged_bind_test(struct kunit *test) } #if IS_BUILTIN(CONFIG_DRM_ACCEL_ANE) && IS_BUILTIN(CONFIG_DRM_ACCEL_ANE_FW_KUNIT_TEST) +/* M3 (T8122) H15: three reg windows, five DAPF records at DART0 + 0x4000, cold sleep. */ +static void ane_t8122_platform_test(struct kunit *test) +{ + struct platform_device *pdev = platform_device_alloc("ane-t8122", -1); + u64 phys[] = { 0x100000000, 0x200000000 }; + + KUNIT_ASSERT_NOT_NULL(test, pdev); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.soc, 0x8122U); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.chip_family, 15U); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.ane_type, 0xb0U); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.hwx_subtype, 6U); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.reg_count, 3U); + KUNIT_EXPECT_STREQ(test, ane_t8122_platform.reg_names[2], "aux-0"); + KUNIT_EXPECT_FALSE(test, ane_t8122_platform.has_xl); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.dapf_dart, 0U); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.dapf_offset, 0x4000U); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.dapf_count, 5); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.power_words[0], 0x438U); + KUNIT_EXPECT_TRUE(test, ane_t8122_platform.sleep_cold); + KUNIT_EXPECT_TRUE(test, ane_fw_preload_ranges_valid(&ane_t8122_platform, phys, + ane_t8122_platform.preload_size, + ane_t8122_platform.preload_dva)); + KUNIT_EXPECT_EQ(test, ane_fw_platform_preflight(pdev, &ane_t8122_platform), -EINVAL); + platform_device_put(pdev); +} + /* One engine: no aux-3, five DAPF records; a node without DT is refused. */ static void ane_t8132_platform_test(struct kunit *test) { @@ -153,17 +200,63 @@ static void ane_t6050_builds_test(struct kunit *test) i == j); } } + +/* + * T8142: both firmware builds carry the AXI2AF bridge register updates with + * aligned offsets inside the engine window, disjoint clear/set masks, and + * non-empty transitions; other H17 platforms stay untouched. + */ +static void ane_t8142_bridge_ops_test(struct kunit *test) +{ + const struct ane_fw_platform *b27_0 = &ane_t8142_platform, *b27_2 = b27_0->next_build; + const struct ane_fw_platform *builds[] = { b27_0, b27_2 }; + unsigned int i, j; + + KUNIT_ASSERT_NOT_NULL(test, b27_2); + KUNIT_EXPECT_NULL(test, b27_2->next_build); + KUNIT_EXPECT_EQ(test, ane_h17_platform.bridge_op_count, 0U); + KUNIT_EXPECT_EQ(test, ane_t6050_platform.bridge_op_count, 0U); + for (i = 0; i < ARRAY_SIZE(builds); i++) { + const struct ane_fw_platform *b = builds[i]; + + KUNIT_EXPECT_EQ(test, b->soc, 0x8142U); + KUNIT_ASSERT_NOT_NULL(test, b->bridge_ops); + KUNIT_ASSERT_EQ(test, b->bridge_op_count, 25U); + for (j = 0; j < b->bridge_op_count; j++) { + const struct ane_fw_bridge_op *op = &b->bridge_ops[j]; + + KUNIT_EXPECT_TRUE(test, IS_ALIGNED(op->offset, 4)); + KUNIT_EXPECT_LE(test, op->offset + 4, b->reg_sizes[0]); + KUNIT_EXPECT_EQ(test, op->clear & op->set, 0U); + KUNIT_EXPECT_NE(test, op->clear | op->set, 0U); + } + } + /* Preserves untouched reset bits and stays idempotent once applied. */ + KUNIT_EXPECT_EQ(test, ane_fw_bridge_op_apply(0x10000008U, &b27_0->bridge_ops[12]), + 0x90000010U); + KUNIT_EXPECT_EQ(test, ane_fw_bridge_op_apply(0x90000010U, &b27_0->bridge_ops[12]), + 0x90000010U); + KUNIT_EXPECT_EQ(test, ane_fw_bridge_op_apply(0x000413b6U, &b27_0->bridge_ops[16]), + 0x000413b1U); + KUNIT_EXPECT_EQ(test, ane_fw_bridge_op_apply(0xffff0030U, &b27_0->bridge_ops[22]), + 0x00110071U); + KUNIT_EXPECT_EQ(test, ane_fw_bridge_op_apply(0x00000001U, &b27_0->bridge_ops[24]), + 0x00000000U); +} #endif static struct kunit_case ane_fw_platform_cases[] = { #if IS_BUILTIN(CONFIG_DRM_ACCEL_ANE) && IS_BUILTIN(CONFIG_DRM_ACCEL_ANE_FW_KUNIT_TEST) + KUNIT_CASE(ane_t8122_platform_test), KUNIT_CASE(ane_t8132_platform_test), KUNIT_CASE(ane_t8132_builds_test), KUNIT_CASE(ane_t6050_builds_test), + KUNIT_CASE(ane_t8142_bridge_ops_test), #endif KUNIT_CASE(ane_platform_staged_bind_test), KUNIT_CASE(ane_platform_sleep_path_test), KUNIT_CASE(ane_preload_ranges_test), + KUNIT_CASE(ane_preload_physical_order_test), {} }; diff --git a/drivers/accel/ane/ane_fw_transport.h b/drivers/accel/ane/ane_fw_transport.h index e0e1a0edd12111..b4e834d04eb0f0 100644 --- a/drivers/accel/ane/ane_fw_transport.h +++ b/drivers/accel/ane/ane_fw_transport.h @@ -377,7 +377,7 @@ ane_fw_transport_bar_context(struct ane_fw_transport *t, u8 *copy, size_t size) */ static inline bool ane_fw_transport_switch_safe(const struct ane_fw_transport *t) { - return t->soc->chip_family == 16 || t->soc->chip_family == 17; + return t->soc->chip_family >= 15; } /* ane_fw_transport_publish_at() offset that copies to the end of the arena. */ @@ -723,7 +723,9 @@ ane_fw_transport_free(struct ane_fw_transport *t, void *slot, u64 dva, u64 bytes * firmware frees it after UNLOAD (often only during a later program), but the * backing stays mapped until reset: without reuse the 12 MiB quota ran out at * the sixth program of a boot. Only memory the firmware itself gave back by - * FREE is served again, and only for the same tag and size. + * FREE, or that the host reserved for the request + * (ane_fw_transport_shared_reserve()), is served again, and only for the + * same tag and size. */ static inline unsigned int ane_fw_shared_reusable(const struct ane_fw_transport *t, size_t size, u64 tag) @@ -737,11 +739,80 @@ ane_fw_shared_reusable(const struct ane_fw_transport *t, size_t size, u64 tag) return t->shared_count; } +/* + * A new shared allocation of size bytes under tag, within the host's caps + * (ANE_FW_SHARED_MAX entries, ANE_FW_SHARED_TOTAL bytes): its index, live. + */ +static inline int ane_fw_shared_add(struct ane_fw_transport *t, size_t size, u64 tag, + unsigned int *index) +{ + struct ane_fw_surface s = {}; + unsigned int i; + int ret; + + if (t->shared_count == ANE_FW_SHARED_MAX || size > ANE_FW_SHARED_TOTAL - + t->shared_bytes) + return -ENOSPC; + ret = t->ops->alloc(t->ctx, size, tag, &s); + if (ret) + return ret; + if (!ane_fw_surface_valid(&s) || !IS_ALIGNED(s.dva, SZ_16K) || + s.size != size || ane_fw_surfaces_overlap(&s, &t->ipc) || + ane_fw_surfaces_overlap(&s, &t->pool)) + return -EPROTO; + for (i = 0; i < t->shared_count; i++) + if (ane_fw_surfaces_overlap(&s, &t->shared[i])) + return -EPROTO; + *index = t->shared_count; + t->shared_tags[t->shared_count] = tag; + t->shared_retired[t->shared_count] = false; + t->shared[t->shared_count++] = s; + t->shared_bytes += size; + return 0; +} + +/* + * Make sure a later SHAREDMALLOC request of size bytes under tag is served + * from memory the host already has: a retired allocation of that tag and + * size, or a new one made now and kept retired for it. The firmware waits + * for the answer to every request, with its shared-memory lock held, and a + * request the host cannot serve is never answered: the command behind it + * stalls and only a power cycle recovers the engine. A request the host + * knows is coming is therefore taken before the command that causes it, so + * running out of memory or quota (-ENOMEM, -ENOSPC) refuses that command + * before the firmware sees it. + */ +static inline int ane_fw_transport_shared_reserve(struct ane_fw_transport *t, size_t size, + u32 tag) +{ + unsigned int i; + int ret; + + if (t->error) + return t->error; + if (!size || !IS_ALIGNED(size, SZ_16K)) + return -EINVAL; + if (ane_fw_shared_reusable(t, size, tag) < t->shared_count) + return 0; + ret = ane_fw_shared_add(t, size, tag, &i); + /* + * An invalid surface from the backend is a host error, as it is for a + * request (ane_fw_transport_shared()): its mapping is not recorded, so + * retrying would map another one at every LOAD. + */ + if (ret == -EPROTO) + return ane_fw_transport_fail(t, ret); + if (ret) + return ret; + t->shared_retired[i] = true; + ane_fw_shared_note(t, "reserve", i); + return 0; +} + static inline int ane_fw_transport_irq(struct ane_fw_transport *t, u32 *pending); static inline int ane_fw_transport_shared(struct ane_fw_transport *t) { - struct ane_fw_surface s = {}; u64 word0, word1, word2; size_t size; unsigned int i; @@ -801,33 +872,13 @@ static inline int ane_fw_transport_shared(struct ane_fw_transport *t) ane_fw_shared_note(t, "reuse", i); return 0; } - if (t->shared_count == ANE_FW_SHARED_MAX || size > ANE_FW_SHARED_TOTAL - - t->shared_bytes) { - ret = -ENOSPC; - goto refused; - } - ret = t->ops->alloc(t->ctx, size, word2, &s); + ret = ane_fw_shared_add(t, size, word2, &i); if (ret) goto refused; - if (!ane_fw_surface_valid(&s) || !IS_ALIGNED(s.dva, SZ_16K) || - s.size != size || ane_fw_surfaces_overlap(&s, &t->ipc) || - ane_fw_surfaces_overlap(&s, &t->pool)) { - ret = -EPROTO; - goto refused; - } - for (i = 0; i < t->shared_count; i++) { - if (ane_fw_surfaces_overlap(&s, &t->shared[i])) { - ret = -EPROTO; - goto refused; - } - } - t->shared_tags[t->shared_count] = word2; - t->shared[t->shared_count++] = s; - t->shared_bytes += size; t->ops->store64(t->ctx, p + 8, 0); - t->ops->store64(t->ctx, p + 16, t->shared_count); + t->ops->store64(t->ctx, p + 16, i + 1); t->ops->write_barrier(t->ctx); - t->ops->store64(t->ctx, p, s.dva | 1); + t->ops->store64(t->ctx, p, t->shared[i].dva | 1); t->ops->write_barrier(t->ctx); ane_fw_transport_doorbell(t, ANE_FW_SHAREDMALLOC); ane_fw_transport_advance(t, ANE_FW_SHAREDMALLOC); diff --git a/drivers/accel/ane/ane_fw_transport_test.c b/drivers/accel/ane/ane_fw_transport_test.c index c38415ada6c6b6..77c80c7dc5e4a9 100644 --- a/drivers/accel/ane/ane_fw_transport_test.c +++ b/drivers/accel/ane/ane_fw_transport_test.c @@ -1186,6 +1186,87 @@ static void ane_transport_pool_no_free_test(struct kunit *test) KUNIT_EXPECT_EQ(test, ane_fw_transport_shared(&f->t), -ENOSPC); } +/* + * A reserved allocation is kept retired and serves the request it was made + * for, with no allocation then; a full quota or no memory refuses the + * reservation without failing the transport or touching the ring. + */ +static void ane_transport_shared_reserve_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + unsigned int i; + u64 dva; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared_reserve(&f->t, 1, ANE_FW_SHARED_EXPP), + -EINVAL); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + 0); + KUNIT_EXPECT_EQ(test, f->allocs, 1U); + KUNIT_EXPECT_TRUE(test, f->t.shared_retired[0]); + dva = f->t.shared[0].dva; + /* Already there: no second allocation. */ + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + 0); + KUNIT_EXPECT_EQ(test, f->allocs, 1U); + ane_test_shared_request(f, 0, SZ_2M, ANE_FW_SHARED_EXPP); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared(&f->t), 0); + KUNIT_EXPECT_EQ(test, f->allocs, 1U); + KUNIT_EXPECT_FALSE(test, f->t.shared_retired[0]); + KUNIT_EXPECT_EQ(test, ane_test_load(f, ane_test_slot(f, ANE_FW_SHAREDMALLOC) - + ANE_FW_SLOT_SIZE), dva | 1); + + /* No memory: refused, and nothing recorded. */ + f->alloc_error = -ENOMEM; + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + -ENOMEM); + KUNIT_EXPECT_EQ(test, f->t.shared_count, 1U); + KUNIT_EXPECT_EQ(test, f->t.error, 0); + f->alloc_error = 0; + f->allocs = 1; + + /* Fill the quota with live pools; one more is refused cleanly. */ + for (i = 1; i < ANE_FW_SHARED_TOTAL / SZ_2M; i++) { + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, + ANE_FW_SHARED_EXPP), 0); + ane_test_shared_request(f, 0, SZ_2M, ANE_FW_SHARED_EXPP); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared(&f->t), 0); + } + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + -ENOSPC); + KUNIT_EXPECT_EQ(test, f->t.error, 0); + KUNIT_EXPECT_EQ(test, f->refusals, 0U); + + /* A FREE gives one back, which serves the next reservation. */ + f->t.native_free = true; + ane_test_shared_request(f, dva, 0, 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared(&f->t), 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + 0); + KUNIT_EXPECT_EQ(test, f->allocs, (unsigned int)(ANE_FW_SHARED_TOTAL / SZ_2M)); + KUNIT_EXPECT_EQ(test, f->t.error, 0); +} + +/* + * A backend surface that fails validation fails the transport, as it does for + * a request, so a later LOAD does not map another one. + */ +static void ane_transport_shared_reserve_invalid_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + f->alloc_bad = 1; + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + -EPROTO); + KUNIT_EXPECT_EQ(test, f->t.error, -EPROTO); + KUNIT_EXPECT_EQ(test, f->t.shared_count, 0U); + KUNIT_EXPECT_EQ(test, f->t.shared_bytes, 0UL); + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + -EPROTO); + KUNIT_EXPECT_EQ(test, f->allocs, 1U); +} + /* A FREE posted after UNLOAD is answered by the settle loop. */ static void ane_transport_settle_test(struct kunit *test) { @@ -1273,6 +1354,46 @@ static void ane_transport_mode_stop_test(struct kunit *test) KUNIT_EXPECT_EQ(test, f->t.error, 0); } +/* + * A warm sleep publishes EXCLAVE_MODE_STOP and SUSPEND on a transport that + * survives the wake (ane_fw_suspend_firmware()). Once both are answered and + * the SUSPEND reply was read, releasing to the mark taken before them gives + * the arena back: the next command lands where 0x31 did, and sleep after + * sleep the arena does not shrink. + */ +static void ane_transport_sleep_release_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 command[8] = {}; + u32 ch = f->t.control_ch; + size_t mark; + u64 first; + unsigned int i; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + mark = ane_fw_transport_mark(&f->t); + for (i = 0; i < 64; i++) { + KUNIT_ASSERT_EQ(test, ane_fw_transport_publish_mode_stop(&f->t, TEST_DEADLINE), 0); + if (!i) + first = f->t.pending[ch].dva; + KUNIT_ASSERT_EQ(test, f->t.pending[ch].dva, first); + /* Released too early: a command is still pending. */ + KUNIT_ASSERT_EQ(test, ane_fw_transport_release(&f->t, mark), -EBUSY); + ane_test_reply(f, ch); + KUNIT_ASSERT_EQ(test, ane_fw_transport_wait(&f->t, ch), 0); + + put_unaligned_le16(0x24, command + 4); /* SUSPEND */ + KUNIT_ASSERT_EQ(test, ane_fw_transport_publish(&f->t, ANE_FW_IO, command, + sizeof(command), TEST_DEADLINE), 0); + KUNIT_ASSERT_GT(test, ane_fw_transport_mark(&f->t), mark); + ane_test_reply(f, ANE_FW_IO); + KUNIT_ASSERT_EQ(test, ane_fw_transport_wait(&f->t, ANE_FW_IO), 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_release(&f->t, mark), 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_mark(&f->t), mark); + } + KUNIT_EXPECT_EQ(test, f->t.error, 0); +} + /* * The control ring completes without clearing the result word (H17 C6): * DVA|1, length, and the published size still in word 2. Accepted there; @@ -1550,6 +1671,8 @@ static struct kunit_case ane_transport_cases[] = { KUNIT_CASE(ane_transport_pool_reuse_test), KUNIT_CASE(ane_transport_pool_reuse_native_test), KUNIT_CASE(ane_transport_pool_no_free_test), + KUNIT_CASE(ane_transport_shared_reserve_test), + KUNIT_CASE(ane_transport_shared_reserve_invalid_test), KUNIT_CASE(ane_transport_settle_test), KUNIT_CASE(ane_transport_carry_shared_test), KUNIT_CASE(ane_transport_mode_stop_test), @@ -1588,6 +1711,7 @@ static struct kunit_case ane_transport_cases[] = { KUNIT_CASE(ane_transport_wait_test), KUNIT_CASE(ane_transport_wait_polls_test), KUNIT_CASE(ane_transport_poll_sleep_test), + KUNIT_CASE(ane_transport_sleep_release_test), {} }; diff --git a/drivers/accel/ane/ane_h16_accel.c b/drivers/accel/ane/ane_h16_accel.c index 8ae375af68ed72..186fee5210bc3d 100644 --- a/drivers/accel/ane/ane_h16_accel.c +++ b/drivers/accel/ane/ane_h16_accel.c @@ -7,12 +7,14 @@ * commands. A process may map its program's surfaces (inputs and outputs * only) and run requests on them in place, without copies. */ +#include #include #include #include #include #include #include +#include #include #include @@ -157,12 +159,180 @@ static int ane_h16_load_ioctl(struct drm_device *drm, void *data, struct drm_fil return ret; } +/* + * The user memory of one EXECUTE buffer, taken before any driver lock: its + * pages pinned, or, where they cannot be pinned (VM_PFNMAP and VM_IO + * mappings, such as a GEM-shmem or dma-buf heap mmap), a kernel bounce copy. + * Faulting user memory in can wait for as long as whoever backs it likes, and + * mmap() of the node takes the file and node locks under the process mmap + * lock, so no lock of ours is held then. Under the node lock the request + * copies through the kernel mapping of the pinned pages or the bounce copy, + * neither of which faults; a bounced output goes back to user memory after + * both locks are dropped. + */ +struct ane_h16_user_buffer { + struct page **pages; + void *bounce; + u64 ptr; + unsigned int count; + size_t offset; + size_t size; + bool write, dirty; +}; + +static int ane_h16_user_pin(struct ane_h16_user_buffer *u, u64 ptr, size_t size, bool write) +{ + int ret; + + *u = (struct ane_h16_user_buffer) { + .offset = offset_in_page(ptr), + .size = size, + .write = write, + }; + /* At most INT_MAX pages, checked before the page count can wrap. */ + if (!size || ptr + size < ptr || size > (size_t)INT_MAX * PAGE_SIZE - u->offset) + return -EFAULT; + u->count = DIV_ROUND_UP(u->offset + size, PAGE_SIZE); + u->pages = kvmalloc_array(u->count, sizeof(*u->pages), GFP_KERNEL); + if (!u->pages) + return -ENOMEM; + ret = pin_user_pages_fast(ptr & PAGE_MASK, u->count, write ? FOLL_WRITE : 0, u->pages); + if (ret == u->count) + return 0; + if (ret > 0) + unpin_user_pages(u->pages, ret); + kvfree(u->pages); + u->pages = NULL; + return ret < 0 ? ret : -EFAULT; +} + +static void ane_h16_user_unpin(struct ane_h16_user_buffer *u) +{ + if (!u->pages) + return; + unpin_user_pages_dirty_lock(u->pages, u->count, u->dirty); + kvfree(u->pages); + u->pages = NULL; +} + +/* + * Whether [ptr, ptr + size) is completely mapped with the requested access + * and reaches a VM_PFNMAP or VM_IO mapping, whose pages cannot be pinned. + */ +static bool ane_h16_user_unpinnable(u64 ptr, size_t size, bool write) +{ + struct mm_struct *mm = current->mm; + struct vm_area_struct *vma; + unsigned long need = write ? VM_WRITE : VM_READ; + u64 addr = ptr, end = ptr + size; + bool unpinnable = false; + + if (!size || end < ptr) + return false; + mmap_read_lock(mm); + while (addr < end) { + vma = find_vma(mm, addr); + if (!vma || vma->vm_start > addr || !(vma->vm_flags & need)) { + unpinnable = false; + break; + } + if (vma->vm_flags & (VM_PFNMAP | VM_IO)) + unpinnable = true; + addr = vma->vm_end; + } + mmap_read_unlock(mm); + return unpinnable; +} + +/* A kernel copy of the buffer; an input is read into it now. */ +static int ane_h16_user_bounce(struct ane_h16_user_buffer *u, u64 ptr, size_t size, bool write) +{ + *u = (struct ane_h16_user_buffer) { .size = size, .write = write }; + u->bounce = kvmalloc(size, GFP_KERNEL_ACCOUNT); + if (!u->bounce) + return -ENOMEM; + u->ptr = ptr; + if (!write && copy_from_user(u->bounce, u64_to_user_ptr(ptr), size)) { + kvfree(u->bounce); + u->bounce = NULL; + return -EFAULT; + } + return 0; +} + +/* + * Take one buffer with no lock held: pin it, or bounce it when it lies in a + * mapping whose pages cannot be pinned. An input is read into the bounce copy + * now, and fails here as copy_from_user() would; an output is written back by + * ane_h16_user_put(). Unmapped memory and read-only outputs still fail here. + */ +static int ane_h16_user_get(struct ane_h16_user_buffer *u, u64 ptr, size_t size, bool write) +{ + int ret = ane_h16_user_pin(u, ptr, size, write); + + if (ret != -EFAULT || !ane_h16_user_unpinnable(ptr, size, write)) + return ret; + return ane_h16_user_bounce(u, ptr, size, write); +} + +/* Release one buffer after both locks are dropped; a bounced output goes back now. */ +static int ane_h16_user_put(struct ane_h16_user_buffer *u) +{ + int ret = 0; + + if (!u->bounce) { + ane_h16_user_unpin(u); + return 0; + } + if (u->dirty && copy_to_user(u64_to_user_ptr(u->ptr), u->bounce, u->size)) + ret = -EFAULT; + kvfree(u->bounce); + u->bounce = NULL; + return ret; +} + +/* + * Copy between cpu and the pinned pages or the bounce copy. It cannot fault: + * safe under the node lock. + */ +static void ane_h16_user_copy(struct ane_h16_user_buffer *u, void *cpu, bool to_user) +{ + size_t done = 0, offset = u->offset; + unsigned int i; + + if (u->bounce) { + if (to_user) + memcpy(u->bounce, cpu, u->size); + else + memcpy(cpu, u->bounce, u->size); + u->dirty |= to_user; + return; + } + for (i = 0; i < u->count; i++) { + size_t n = min_t(size_t, PAGE_SIZE - offset, u->size - done); + u8 *page = kmap_local_page(u->pages[i]); + + if (to_user) { + memcpy(page + offset, (u8 *)cpu + done, n); + flush_dcache_page(u->pages[i]); + } else { + memcpy((u8 *)cpu + done, page + offset, n); + } + kunmap_local(page); + done += n; + offset = 0; + } + if (to_user) + u->dirty = true; +} + static int ane_h16_exec_ioctl(struct drm_device *drm, void *data, struct drm_file *file) { struct ane_h16_accel *a = to_h16_accel(drm); struct ane_h16_accel_file *f = file->driver_priv; struct drm_ane_h16_exec *args = data; struct drm_ane_h16_buffer buffers[ANE_H16_SURFACES]; + struct ane_h16_user_buffer user[ANE_H16_SURFACES] = {}; struct ane_h16_program *p; u64 start, locked, copied, done; unsigned int i; @@ -177,22 +347,48 @@ static int ane_h16_exec_ioctl(struct drm_device *drm, void *data, struct drm_fil array_size(args->count, sizeof(*buffers)))) return -EFAULT; start = ktime_get_ns(); + /* + * Check the buffers against the loaded program, then take them (pin or + * bounce) with no lock held: user memory is not touched under a lock of + * ours. The program can change while unlocked, so the taken buffers are + * checked against it again under the file lock, which then pins the + * program through the request. + */ mutex_lock(&f->lock); - ret = ane_h16_session_enter(a->session, file->filp->f_flags & O_NONBLOCK); - if (ret) { - mutex_unlock(&f->lock); - return ret; - } p = f->program; - if (!p || p->closed || args->count != p->resource_count) { + if (!p || args->count != p->resource_count) ret = -EINVAL; - goto unlock; + for (i = 0; i < args->count && !in_place && !ret; i++) { + if (buffers[i].size != p->resources[i].buffer.size) + ret = -EINVAL; + user[i].write = p->resources[i].permissions == 2; } + mutex_unlock(&f->lock); + if (ret) + return ret; for (i = 0; i < args->count && !in_place; i++) { - if (buffers[i].size != p->resources[i].buffer.size) { + ret = ane_h16_user_get(&user[i], buffers[i].ptr, buffers[i].size, + user[i].write); + if (ret) + goto unpin; + } + mutex_lock(&f->lock); + p = f->program; + if (!p || args->count != p->resource_count) + ret = -EINVAL; + for (i = 0; i < args->count && !in_place && !ret; i++) { + bool write = p->resources[i].permissions == 2; + + if (buffers[i].size != p->resources[i].buffer.size || user[i].write != write) ret = -EINVAL; - goto unlock; - } + } + if (!ret) + ret = ane_h16_session_enter(a->session, file->filp->f_flags & O_NONBLOCK); + if (ret) + goto unlock_file; + if (p->closed) { + ret = -EINVAL; + goto unlock; } ret = ane_h16_session_acquire(a->session, p); if (ret) @@ -202,14 +398,10 @@ static int ane_h16_exec_ioctl(struct drm_device *drm, void *data, struct drm_fil for (i = 0; i < args->count && !in_place; i++) { void *cpu = p->surfaces[i]->cpu; - if (p->resources[i].permissions == 1) { - if (copy_from_user(cpu, u64_to_user_ptr(buffers[i].ptr), buffers[i].size)) { - ret = -EFAULT; - goto release; - } - } else { + if (p->resources[i].permissions == 1) + ane_h16_user_copy(&user[i], cpu, false); + else memset(cpu, 0xff, buffers[i].size); - } } ane_h16_session_sync(a->session, p, true); copied = ktime_get_ns(); @@ -219,10 +411,8 @@ static int ane_h16_exec_ioctl(struct drm_device *drm, void *data, struct drm_fil done = ktime_get_ns(); ane_h16_session_sync(a->session, p, false); for (i = 0; i < args->count && !in_place; i++) - if (p->resources[i].permissions == 2 && - copy_to_user(u64_to_user_ptr(buffers[i].ptr), p->surfaces[i]->cpu, - buffers[i].size)) - ret = -EFAULT; + if (p->resources[i].permissions == 2) + ane_h16_user_copy(&user[i], p->surfaces[i]->cpu, true); if (!ret) { u64 end = ktime_get_ns(); const u64 *ns = a->session->timing.ns; @@ -248,7 +438,15 @@ static int ane_h16_exec_ioctl(struct drm_device *drm, void *data, struct drm_fil ane_h16_session_release(a->session, p); unlock: mutex_unlock(&a->lock); +unlock_file: mutex_unlock(&f->lock); +unpin: + for (i = 0; i < args->count && !in_place; i++) { + int put = ane_h16_user_put(&user[i]); + + if (put && !ret) + ret = put; + } return ret; } @@ -421,8 +619,65 @@ static const struct drm_driver ane_h16_drm_driver = { .desc = "Apple Neural Engine (H16 and later)", }; +/* + * ane_stats and wedged on the ANE device, as ane.ko and ane_t6021 have them + * (Documentation/ABI/testing/sysfs-class-accel-ane), for the node's lifetime. + * Both are lock-free reads, so a hung request cannot block them. + */ +struct ane_h16_sysfs { + struct ane_h16_session *session; + struct device_attribute stats, wedged; + struct attribute *attrs[3]; + struct attribute_group group; +}; + +static ssize_t ane_h16_stats_show(struct device *dev, struct device_attribute *attr, char *buf) +{ + struct ane_h16_sysfs *sys = container_of(attr, struct ane_h16_sysfs, stats); + + return ane_stats_emit(buf, &sys->session->sysfs_ctrs); +} + +/* + * 1 while the session is quarantined: a request hung or failed with an + * uncertain outcome, and requests are refused until a recovery or a system + * sleep proves the old firmware gone. A parked or sleeping engine is not + * wedged: the next request brings it up. + */ +static ssize_t ane_h16_wedged_show(struct device *dev, struct device_attribute *attr, char *buf) +{ + struct ane_h16_sysfs *sys = container_of(attr, struct ane_h16_sysfs, wedged); + + return sysfs_emit(buf, "%d\n", READ_ONCE(sys->session->quarantined)); +} + +static struct ane_h16_sysfs *ane_h16_sysfs_add(struct device *dev, + struct ane_h16_session *session) +{ + struct ane_h16_sysfs *sys = devm_kzalloc(dev, sizeof(*sys), GFP_KERNEL); + int ret; + + if (!sys) + return ERR_PTR(-ENOMEM); + sys->session = session; + sysfs_attr_init(&sys->stats.attr); + sys->stats.attr.name = "ane_stats"; + sys->stats.attr.mode = 0444; + sys->stats.show = ane_h16_stats_show; + sysfs_attr_init(&sys->wedged.attr); + sys->wedged.attr.name = "wedged"; + sys->wedged.attr.mode = 0444; + sys->wedged.show = ane_h16_wedged_show; + sys->attrs[0] = &sys->stats.attr; + sys->attrs[1] = &sys->wedged.attr; + sys->group.attrs = sys->attrs; + ret = devm_device_add_group(dev, &sys->group); + return ret ? ERR_PTR(ret) : sys; +} + int ane_h16_accel_register(struct device *dev, struct ane_h16_session *session) { + struct ane_h16_sysfs *sys; struct ane_h16_accel *a; int ret; @@ -438,6 +693,10 @@ int ane_h16_accel_register(struct device *dev, struct ane_h16_session *session) ret = drm_dev_register(&a->drm, 0); if (ret) return ret; + /* The node works without them: report and go on. */ + sys = ane_h16_sysfs_add(dev, session); + if (IS_ERR(sys)) + drm_warn(&a->drm, "no ane_stats or wedged in sysfs (%pe)\n", sys); drm_info(&a->drm, "H%u accel node ready (ABI 3, %s)\n", session->transport->soc->chip_family, ane_fw_transport_switch_safe(session->transport) ? diff --git a/drivers/accel/ane/ane_h16_accel_test.c b/drivers/accel/ane/ane_h16_accel_test.c index b88a8d70336e5b..db2bf056dbf657 100644 --- a/drivers/accel/ane/ane_h16_accel_test.c +++ b/drivers/accel/ane/ane_h16_accel_test.c @@ -5,6 +5,7 @@ */ #include #include +#include #include #include @@ -60,9 +61,224 @@ static void ane_h16_accel_open_test(struct kunit *test) drm_dev_unregister(&a->drm); } +/* + * EXECUTE pins a plain buffer's pages before it takes the node lock and copies + * through them under it. The copies equal what copy_from_user() and + * copy_to_user() move, at an offset that crosses pages; an unmapped buffer, + * a read-only output and a wrapping range fail at the pin, holding nothing. + */ +static void ane_h16_accel_user_pages_test(struct kunit *test) +{ + const size_t size = 2 * PAGE_SIZE, off = PAGE_SIZE - 24; + struct ane_h16_user_buffer u; + unsigned long user, ro; + u8 *src, *dst; + size_t i; + + user = kunit_vm_mmap(test, NULL, 0, 3 * PAGE_SIZE, PROT_READ | PROT_WRITE, + MAP_ANONYMOUS | MAP_PRIVATE, 0); + ro = kunit_vm_mmap(test, NULL, 0, PAGE_SIZE, PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, 0); + KUNIT_ASSERT_TRUE(test, user && !IS_ERR_VALUE(user)); + KUNIT_ASSERT_TRUE(test, ro && !IS_ERR_VALUE(ro)); + src = kunit_kzalloc(test, size, GFP_KERNEL); + dst = kunit_kzalloc(test, size, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, src); + KUNIT_ASSERT_NOT_NULL(test, dst); + for (i = 0; i < size; i++) + src[i] = i * 7 + 3; + KUNIT_ASSERT_EQ(test, copy_to_user((void __user *)(user + off), src, size), 0); + + /* An input: three pages for a buffer that starts 24 bytes before a page end. */ + KUNIT_ASSERT_EQ(test, ane_h16_user_pin(&u, user + off, size, false), 0); + KUNIT_EXPECT_EQ(test, u.count, 3U); + ane_h16_user_copy(&u, dst, false); + KUNIT_EXPECT_MEMEQ(test, dst, src, size); + KUNIT_EXPECT_FALSE(test, u.dirty); + ane_h16_user_unpin(&u); + KUNIT_EXPECT_NULL(test, u.pages); + + /* An output: written through the pinned pages, read back from user memory. */ + for (i = 0; i < size; i++) + src[i] ^= 0x5a; + KUNIT_ASSERT_EQ(test, ane_h16_user_pin(&u, user + off, size, true), 0); + ane_h16_user_copy(&u, src, true); + KUNIT_EXPECT_TRUE(test, u.dirty); + ane_h16_user_unpin(&u); + KUNIT_ASSERT_EQ(test, copy_from_user(dst, (void __user *)(user + off), size), 0); + KUNIT_EXPECT_MEMEQ(test, dst, src, size); + + KUNIT_EXPECT_EQ(test, ane_h16_user_pin(&u, 0, 64, false), -EFAULT); + KUNIT_EXPECT_NULL(test, u.pages); + KUNIT_EXPECT_EQ(test, ane_h16_user_pin(&u, ro, 64, true), -EFAULT); + KUNIT_EXPECT_NULL(test, u.pages); + KUNIT_EXPECT_EQ(test, ane_h16_user_pin(&u, ro, 64, false), 0); + ane_h16_user_unpin(&u); + KUNIT_EXPECT_EQ(test, ane_h16_user_pin(&u, U64_MAX - 8, 64, false), -EFAULT); + KUNIT_EXPECT_NULL(test, u.pages); + /* A size whose page count would wrap to 0 without its own check. */ + KUNIT_EXPECT_EQ(test, ane_h16_user_pin(&u, PAGE_SIZE - 1, + SIZE_MAX - (PAGE_SIZE - 1), false), -EFAULT); + KUNIT_EXPECT_NULL(test, u.pages); + KUNIT_EXPECT_EQ(test, ane_h16_user_pin(&u, 0, (size_t)INT_MAX * PAGE_SIZE + 1, false), + -EFAULT); + KUNIT_EXPECT_NULL(test, u.pages); +} + +/* Set or clear VM_IO on the mapping at @addr, which pin_user_pages_fast() then refuses. */ +static void ane_h16_accel_test_vm_io(unsigned long addr, bool on) +{ + struct mm_struct *mm = current->mm; + struct vm_area_struct *vma; + + mmap_write_lock(mm); + vma = find_vma(mm, addr); + if (vma && vma->vm_start <= addr) { + if (on) + vm_flags_set(vma, VM_IO); + else + vm_flags_clear(vma, VM_IO); + } + mmap_write_unlock(mm); +} + +/* + * A buffer in a mapping whose pages cannot be pinned (VM_PFNMAP or VM_IO: a + * GEM-shmem or dma-buf heap mmap) is bounced: an input is read when it is + * taken, with no lock held, an output is written back when it is put, after + * the locks drop, and only once the request copied into it. A VM_IO flag set + * on anonymous memory is seen by the range check but not by the lockless + * pin, so the bounce itself is called directly here. + */ +static void ane_h16_accel_user_bounce_test(struct kunit *test) +{ + const size_t size = 2 * PAGE_SIZE, off = PAGE_SIZE - 24; + struct ane_h16_user_buffer u; + unsigned long user, ro; + u8 *src, *dst; + size_t i; + + user = kunit_vm_mmap(test, NULL, 0, 3 * PAGE_SIZE, PROT_READ | PROT_WRITE, + MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE, 0); + ro = kunit_vm_mmap(test, NULL, 0, PAGE_SIZE, PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, 0); + KUNIT_ASSERT_TRUE(test, user && !IS_ERR_VALUE(user)); + KUNIT_ASSERT_TRUE(test, ro && !IS_ERR_VALUE(ro)); + src = kunit_kzalloc(test, size, GFP_KERNEL); + dst = kunit_kzalloc(test, size, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, src); + KUNIT_ASSERT_NOT_NULL(test, dst); + for (i = 0; i < size; i++) + src[i] = i * 5 + 1; + KUNIT_ASSERT_EQ(test, copy_to_user((void __user *)(user + off), src, size), 0); + + /* The range check finds a VM_IO mapping anywhere in the range and checks access. */ + KUNIT_EXPECT_FALSE(test, ane_h16_user_unpinnable(user + off, size, false)); + KUNIT_EXPECT_FALSE(test, ane_h16_user_unpinnable(user + off, size, true)); + ane_h16_accel_test_vm_io(user, true); + KUNIT_EXPECT_TRUE(test, ane_h16_user_unpinnable(user + off, size, false)); + KUNIT_EXPECT_TRUE(test, ane_h16_user_unpinnable(user + off, size, true)); + /* A VM_IO mapping extending into an unmapped hole fails before bouncing. */ + { + unsigned long hole = kunit_vm_mmap(test, NULL, 0, 2 * PAGE_SIZE, + PROT_READ | PROT_WRITE, + MAP_ANONYMOUS | MAP_PRIVATE, 0); + + KUNIT_ASSERT_TRUE(test, hole && !IS_ERR_VALUE(hole)); + KUNIT_ASSERT_EQ(test, vm_munmap(hole + PAGE_SIZE, PAGE_SIZE), 0); + ane_h16_accel_test_vm_io(hole, true); + KUNIT_EXPECT_TRUE(test, ane_h16_user_unpinnable(hole, PAGE_SIZE, true)); + KUNIT_EXPECT_FALSE(test, ane_h16_user_unpinnable(hole, 2 * PAGE_SIZE, false)); + KUNIT_EXPECT_FALSE(test, ane_h16_user_unpinnable(hole, 2 * PAGE_SIZE, true)); + KUNIT_EXPECT_EQ(test, ane_h16_user_get(&u, hole, 2 * PAGE_SIZE, true), -EFAULT); + KUNIT_EXPECT_NULL(test, u.bounce); + KUNIT_EXPECT_NULL(test, u.pages); + ane_h16_accel_test_vm_io(hole, false); + } + /* A read-only VM_IO mapping is readable as an input, but fails as an output. */ + ane_h16_accel_test_vm_io(ro, true); + KUNIT_EXPECT_TRUE(test, ane_h16_user_unpinnable(ro, 64, false)); + KUNIT_EXPECT_FALSE(test, ane_h16_user_unpinnable(ro, 64, true)); + KUNIT_EXPECT_EQ(test, ane_h16_user_get(&u, ro, 64, true), -EFAULT); + KUNIT_EXPECT_NULL(test, u.bounce); + KUNIT_EXPECT_NULL(test, u.pages); + ane_h16_accel_test_vm_io(ro, false); + ane_h16_accel_test_vm_io(user, false); + + /* An input: read into the bounce copy when taken. */ + KUNIT_ASSERT_EQ(test, ane_h16_user_bounce(&u, user + off, size, false), 0); + KUNIT_EXPECT_NULL(test, u.pages); + KUNIT_EXPECT_NOT_NULL(test, u.bounce); + ane_h16_user_copy(&u, dst, false); + KUNIT_EXPECT_MEMEQ(test, dst, src, size); + KUNIT_EXPECT_EQ(test, ane_h16_user_put(&u), 0); + KUNIT_EXPECT_NULL(test, u.bounce); + + /* An output the request never wrote: user memory is left as it was. */ + KUNIT_ASSERT_EQ(test, ane_h16_user_bounce(&u, user + off, size, true), 0); + KUNIT_EXPECT_EQ(test, ane_h16_user_put(&u), 0); + KUNIT_ASSERT_EQ(test, copy_from_user(dst, (void __user *)(user + off), size), 0); + KUNIT_EXPECT_MEMEQ(test, dst, src, size); + + /* An output: written back at the put. */ + for (i = 0; i < size; i++) + src[i] ^= 0xa5; + KUNIT_ASSERT_EQ(test, ane_h16_user_bounce(&u, user + off, size, true), 0); + ane_h16_user_copy(&u, src, true); + KUNIT_EXPECT_EQ(test, ane_h16_user_put(&u), 0); + KUNIT_ASSERT_EQ(test, copy_from_user(dst, (void __user *)(user + off), size), 0); + KUNIT_EXPECT_MEMEQ(test, dst, src, size); + + /* Unmapped memory, and an output in a read-only mapping, still fail when taken. */ + KUNIT_EXPECT_EQ(test, ane_h16_user_get(&u, 0, 64, false), -EFAULT); + KUNIT_EXPECT_NULL(test, u.bounce); + KUNIT_EXPECT_EQ(test, ane_h16_user_get(&u, ro, 64, true), -EFAULT); + KUNIT_EXPECT_NULL(test, u.bounce); + KUNIT_EXPECT_NULL(test, u.pages); +} + +/* + * ane_stats and wedged land on the device with the format of the other ANE + * drivers and follow the session: its counters and its quarantine. + */ +static void ane_h16_accel_sysfs_test(struct kunit *test) +{ + struct device *dev = drm_kunit_helper_alloc_device(test); + struct ane_h16_session *s = kunit_kzalloc(test, sizeof(*s), GFP_KERNEL); + char *buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + struct kernfs_node *kn; + struct ane_h16_sysfs *sys; + u64 ticket; + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + KUNIT_ASSERT_NOT_NULL(test, s); + KUNIT_ASSERT_NOT_NULL(test, buf); + ane_stats_counters_init(&s->sysfs_ctrs, &s->sysfs_ring, 0); + s->sysfs_ring.slots = &s->sysfs_slot; + sys = ane_h16_sysfs_add(dev, s); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, sys); + kn = sysfs_get_dirent(dev->kobj.sd, "ane_stats"); + KUNIT_EXPECT_NOT_NULL(test, kn); + sysfs_put(kn); + kn = sysfs_get_dirent(dev->kobj.sd, "wedged"); + KUNIT_EXPECT_NOT_NULL(test, kn); + sysfs_put(kn); + + ticket = ane_stats_begin(&s->sysfs_ctrs, &s->sysfs_ring, 1000, 1); + ane_stats_complete(&s->sysfs_ctrs, &s->sysfs_ring, ticket, 3000, -ETIMEDOUT, 0); + KUNIT_EXPECT_GT(test, ane_h16_stats_show(dev, &sys->stats, buf), 0); + KUNIT_EXPECT_STREQ(test, buf, "busy_ns 2000\njobs 1\n"); + KUNIT_EXPECT_EQ(test, ane_h16_wedged_show(dev, &sys->wedged, buf), 2); + KUNIT_EXPECT_STREQ(test, buf, "0\n"); + s->quarantined = true; + ane_h16_wedged_show(dev, &sys->wedged, buf); + KUNIT_EXPECT_STREQ(test, buf, "1\n"); +} + static struct kunit_case ane_h16_accel_cases[] = { KUNIT_CASE(ane_h16_accel_fops_test), KUNIT_CASE(ane_h16_accel_open_test), + KUNIT_CASE(ane_h16_accel_user_pages_test), + KUNIT_CASE(ane_h16_accel_user_bounce_test), + KUNIT_CASE(ane_h16_accel_sysfs_test), {} }; @@ -73,5 +289,5 @@ static struct kunit_suite ane_h16_accel_suite = { kunit_test_suite(ane_h16_accel_suite); -MODULE_DESCRIPTION("KUnit open test for the H16 ANE accel node"); +MODULE_DESCRIPTION("KUnit open and user-buffer tests for the H16 ANE accel node"); MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_backend.c b/drivers/accel/ane/ane_h16_backend.c index be62b0e5c703e0..4fb0001b94b4c1 100644 --- a/drivers/accel/ane/ane_h16_backend.c +++ b/drivers/accel/ane/ane_h16_backend.c @@ -118,6 +118,14 @@ struct ane_h16_device { bool program_ready; /* Firmware suspended and the engine power gated for system sleep. */ bool slept; + /* Powered off at idle (or after system sleep) until the next request. */ + bool parked; + /* System sleep transition under way (PM_SUSPEND_PREPARE..PM_POST_SUSPEND). */ + bool in_sleep; + /* Runtime PM autosuspend enabled on h->dev, and our own holds on it. */ + bool rpm_enabled; + bool rpm_held; + bool rpm_busy; /* genpd's transitions of each of the five domains across a sleep. */ struct ane_h16_genpd { struct notifier_block nb; @@ -207,12 +215,53 @@ static void ane_h16_log(void *ctx, const char *item, u64 a, u64 b) dev_info(h->dev, "H16 %s %llx %llx\n", item, a, b); } +/* Engines that cycle cold across sleep park through runtime PM between requests. */ +static bool ane_h16_rpm(const struct ane_h16_device *h) +{ + return h->boot.soc->sleep_cold && !h->boot.soc->sleep_warm; +} + +/* + * The parked engine's autosuspend delay: a request that finds it parked waits + * for a cold boot from the preload and the replay of its programs (~10-18 ms). + * Two seconds keep that under 1% of a pause longer than the delay and prevent + * cycling power faster than every two seconds. power/autosuspend_delay_ms + * changes it; a negative value keeps the engine up until the next system sleep. + */ +#define ANE_H16_AUTOSUSPEND_MS 2000 + +static void ane_h16_rpm_pin(struct ane_h16_device *h) +{ + lockdep_assert_held(&ane_h16_lock); + if (h->rpm_enabled && h->engine_on && !h->rpm_held) { + pm_runtime_get_noresume(h->dev); + h->rpm_held = true; + } +} + +/* + * After bring-up: hand the device's runtime PM reference to autosuspend, which + * parks the engine once idle for ANE_H16_AUTOSUSPEND_MS. A quarantined engine + * keeps its reference. + */ +static void ane_h16_rpm_idle(struct ane_h16_device *h) +{ + lockdep_assert_held(&ane_h16_lock); + if (!h->rpm_enabled || !h->rpm_held || !h->program_ready || + h->boot.quarantined || h->session.quarantined) + return; + h->rpm_held = false; + pm_runtime_mark_last_busy(h->dev); + pm_runtime_put_autosuspend(h->dev); +} + static void ane_h16_startup_fwlog(struct ane_h16_device *h); static void ane_h16_quarantine(void *ctx, int error) { struct ane_h16_device *h = ctx; + ane_h16_rpm_pin(h); if ((error == -ETIMEDOUT || error == -ESHUTDOWN) && h->boot.stage == ANE_H16_BOOT) ane_h16_startup_fwlog(h); @@ -340,8 +389,8 @@ static void ane_h16_power_down(struct ane_h16_device *h) pm_runtime_put_sync(h->dart[i]); for (i = h->powered; i-- > 0; ) pm_runtime_put_sync(h->power[i]); - h->engine_on = false; - dev_info(h->dev, "H16 ANE: powered down for system sleep\n"); + WRITE_ONCE(h->engine_on, false); + dev_info(h->dev, "H16 ANE: powered down\n"); } /* The five domains in order, then the DARTs (their resume restores SID0). */ @@ -360,7 +409,7 @@ static int ane_h16_power_up(struct ane_h16_device *h) if (ret < 0) goto dart; } - h->engine_on = true; + WRITE_ONCE(h->engine_on, true); return 0; dart: while (j--) @@ -478,8 +527,9 @@ static void ane_h16_genpd_record(struct ane_h16_device *h) * again. At runtime the ANE DARTs, which sit in it, hold it on, so it stays * on across a runtime power cycle of the other four. A firmware startup stall * on the J616s survives that, and is cleared once sys is off too, as it is in - * system sleep. The DARTs keep their SID0 state across it, as they do across - * system sleep (the ANE DART's suspend and resume neither save nor restore). + * system sleep. When sys powers off in runtime suspend or system sleep, the + * ANE DARTs suspend first and save/restore TTBR and TCR across the cycle; an + * isolated sys cycle leaves their SID0 state intact across the reset. */ static int ane_h16_sys_cycle(struct ane_h16_device *h) { @@ -593,15 +643,152 @@ static int ane_h16_boot_again(struct ane_h16_device *h, unsigned int *restarts, return ret; } -static int ane_h16_cold_boot(struct ane_h16_device *h) +static int ane_h16_cold_boot(struct ane_h16_device *h, unsigned int *restarts, + const char *what, const char *why, bool recover) { int ret; ret = ane_h16_power_cycle(h, false); if (ret) return ret; - return ane_h16_boot_again(h, &h->resume_restarts, "resume restart/budget", - "after system sleep", h->sleep_quarantined); + return ane_h16_boot_again(h, restarts, what, why, recover); +} + +/* + * Boot a parked engine from the preload, as after a cold system sleep, and + * replay every open program behind its handle. Caller holds ane_h16_lock. + */ +static void ane_h16_unpark(struct ane_h16_device *h) +{ + unsigned int restarts = 0; + u64 start; + int ret; + + lockdep_assert_held(&ane_h16_lock); + if (!h->parked || READ_ONCE(h->in_sleep)) + return; + start = ktime_get_ns(); + h->resume_ready_ns = 0; + h->resume_first_ns = 0; + h->resume_replayed = 0; + ret = ane_h16_cold_boot(h, &restarts, "wake restart/budget", + "on runtime wake", false); + WRITE_ONCE(h->parked, false); + WRITE_ONCE(h->session.parked, false); + if (ret) { + /* Power and mappings stay for diagnosis: quarantine pins the device. */ + ane_h16_quarantine(h, ret); + h->boot.quarantined = true; + WRITE_ONCE(h->session.quarantined, true); + } + ane_h16_session_sleep(&h->session, false); + dev_info(h->dev, "H16 ANE: up for a request%s in %llu ms, %u programs replayed, %u restarts\n", + ret ? " FAILED" : "", div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), + h->resume_replayed, restarts); +} + +/* + * A request for a parked engine: runtime PM resumes the device (and its + * DART suppliers) and its resume callback boots the engine. Called without + * ane_h16_lock, which the callback takes. + */ +static int ane_h16_session_wake(void *ctx) +{ + struct ane_h16_device *h = ctx; + int ret; + + if (!READ_ONCE(h->parked)) + return 0; + /* The system is going to sleep or coming back: PM_POST_SUSPEND wakes waiters. */ + if (READ_ONCE(h->in_sleep)) + return -EAGAIN; + ret = pm_runtime_resume_and_get(h->dev); + if (ret < 0) + return ret; + /* + * Still parked: either the device never suspended (runtime PM forbidden + * or a negative autosuspend delay) and a system sleep parked the engine, + * or a system sleep began and prevented the resume callback from booting + * it. + */ + if (READ_ONCE(h->parked)) { + guard(mutex)(&ane_h16_lock); + ane_h16_unpark(h); + } + if (READ_ONCE(h->parked)) { + pm_runtime_put_sync_suspend(h->dev); + return -EAGAIN; + } + pm_runtime_mark_last_busy(h->dev); + pm_runtime_put_autosuspend(h->dev); + return READ_ONCE(h->session.quarantined) ? -EIO : 0; +} + +/* + * Runtime suspend after the autosuspend delay: drain in-flight requests, + * power down the five domains and explicit DART holds, and leave the session + * closed and parked. Returning 0 drops the DART device links so all three + * ANE IOMMUs and ANE_SYS power off until the next request. + */ +int ane_h16_backend_runtime_suspend(struct device *dev) +{ + struct ane_h16_device *h = dev_get_drvdata(dev); + + /* Powered off already (or pre-acquire): nothing to stop, no lock needed. */ + if (!h || !READ_ONCE(h->rpm_enabled) || !READ_ONCE(h->engine_on)) + return 0; + guard(mutex)(&ane_h16_lock); + if (!h->engine_on) + return 0; + /* Bringing up, quarantined, recovering, or in a system sleep. */ + if (!h->program_ready || READ_ONCE(h->in_sleep) || h->boot.quarantined || + READ_ONCE(h->session.quarantined) || READ_ONCE(h->recovering)) + return -EBUSY; + /* Closes admission, waits for requests in flight and releases gating. */ + ane_h16_session_sleep(&h->session, true); + /* Gate release quarantined it: leave recovery to ane_h16_hung(). */ + if (READ_ONCE(h->session.quarantined)) { + ane_h16_session_sleep(&h->session, false); + return -EBUSY; + } + /* + * An execute that raced the autosuspend boundary may have finished while + * draining and refreshed last_busy: wait out the new delay instead of + * parking right after it. + */ + if (pm_runtime_autosuspend_expiration(dev)) { + ane_h16_session_sleep(&h->session, false); + return -EBUSY; + } + for (unsigned int ch = 0; ch < ANE_FW_CHANNELS; ch++) { + if (h->boot.transport.pending[ch].active) { + /* Something is still pending on a ring: autosuspend tries later. */ + ane_h16_session_sleep(&h->session, false); + pm_runtime_mark_last_busy(dev); + return -EBUSY; + } + } + ane_h16_power_down(h); + WRITE_ONCE(h->parked, true); + WRITE_ONCE(h->session.parked, true); + wake_up_all(&h->session.wake); + dev_info(dev, "H16 ANE: idle: parked until the next request\n"); + return 0; +} + +/* Runtime resume for a request (ane_h16_session_wake()): boot the parked engine. */ +int ane_h16_backend_runtime_resume(struct device *dev) +{ + struct ane_h16_device *h = dev_get_drvdata(dev); + + /* Only a parked engine that serves programs is booted here. */ + if (!h || !READ_ONCE(h->rpm_enabled) || !READ_ONCE(h->program_ready) || + !READ_ONCE(h->parked)) + return 0; + guard(mutex)(&ane_h16_lock); + ane_h16_unpark(h); + /* A failed boot is the quarantine's to report: the device itself is up. */ + return 0; } /* @@ -646,15 +833,19 @@ static int ane_h16_sleep_prepare(struct ane_h16_device *h) int ret; guard(mutex)(&ane_h16_lock); + /* Parked: already off, with nothing to stop. */ + if (h->parked) + return 0; for (unsigned int i = 0; i < ARRAY_SIZE(h->genpd); i++) { h->genpd[i].offs = 0; h->genpd[i].ons = 0; h->genpd[i].off_at = 0; h->genpd[i].off_ns = 0; } - h->sleep_quarantined = false; + WRITE_ONCE(h->sleep_quarantined, false); if (!h->program_ready || (h->boot.quarantined && !ane_t6021_hung_stop)) return -EBUSY; + ane_h16_session_sleep(&h->session, true); /* Without hung_stop a quarantined session stays so across the sleep. */ if (ane_t6021_hung_stop && (h->boot.quarantined || h->session.quarantined)) { unsigned int held; @@ -664,18 +855,20 @@ static int ane_h16_sleep_prepare(struct ane_h16_device *h) * off under it, DARTs held until its domains are off, and boot * it cold on resume if every domain went off. */ - ane_h16_session_sleep(&h->session, true); if (h->engine_on) { held = ane_h16_hold_darts(h); ane_h16_power_down(h); ane_h16_release_darts(h, held); } - h->sleep_quarantined = true; + if (h->rpm_enabled && h->rpm_held) { + h->rpm_held = false; + pm_runtime_put_noidle(h->dev); + } + WRITE_ONCE(h->sleep_quarantined, true); dev_info(h->dev, "H16 ANE: quarantined engine powered off for system sleep\n"); WRITE_ONCE(h->slept, true); return 0; } - ane_h16_session_sleep(&h->session, true); if (!h->boot.soc->sleep_warm) { /* Cold cycle: nothing in flight, then power off under the firmware. */ for (unsigned int ch = 0; ch < ANE_FW_CHANNELS; ch++) { @@ -693,7 +886,7 @@ static int ane_h16_sleep_prepare(struct ane_h16_device *h) /* Powered, maybe suspended: keep everything, refuse, close. */ ane_h16_quarantine(h, ret); h->boot.quarantined = true; - h->session.quarantined = true; + WRITE_ONCE(h->session.quarantined, true); ane_h16_session_sleep(&h->session, false); return ret; } @@ -704,57 +897,100 @@ static int ane_h16_sleep_prepare(struct ane_h16_device *h) static void ane_h16_sleep_resume(struct ane_h16_device *h) { + bool rpm = READ_ONCE(h->rpm_enabled); + bool held = false; s64 ready, first; u64 start; int ret; - guard(mutex)(&ane_h16_lock); - if (!h->slept) - return; - start = ktime_get_ns(); - h->resume_ready_ns = 0; - h->resume_first_ns = 0; - h->resume_replayed = 0; - h->resume_cold = !h->boot.soc->sleep_warm || h->sleep_quarantined; - h->resume_restarts = 0; - if (h->sleep_quarantined && !ane_h16_slept_off(h)) { - /* Not proven off: the old firmware may still run. Keep it. */ - dev_err(h->dev, "H16 ANE: a domain of the quarantined engine never went off; kept quarantined\n"); - ret = ane_h16_power_up(h); - if (!ret) - ret = -EIO; - } else if (h->resume_cold) { - ret = ane_h16_cold_boot(h); - } else { - ret = ane_h16_warm_boot(h); + /* + * Normal runtime-PM sleep stays parked after wake until a request + * needs the engine. A quarantined engine being recovered by sleep + * needs the device active across its cold boot; take a reference + * outside ane_h16_lock so runtime resume cannot wait on the lock. + */ + if (rpm && READ_ONCE(h->slept) && READ_ONCE(h->sleep_quarantined) && + pm_runtime_resume_and_get(h->dev) >= 0) + held = true; + scoped_guard(mutex, &ane_h16_lock) { + if (!h->slept) + break; + if (rpm && !h->sleep_quarantined) { + WRITE_ONCE(h->slept, false); + WRITE_ONCE(h->parked, true); + WRITE_ONCE(h->session.parked, true); + ane_h16_genpd_record(h); + dev_info(h->dev, "H16 ANE: resume ok: parked until the next request\n"); + break; + } + start = ktime_get_ns(); + h->resume_ready_ns = 0; + h->resume_first_ns = 0; + h->resume_replayed = 0; + h->resume_cold = !h->boot.soc->sleep_warm || h->sleep_quarantined; + h->resume_restarts = 0; + if (h->sleep_quarantined && !ane_h16_slept_off(h)) { + /* Not proven off: the old firmware may still run. Keep it. */ + dev_err(h->dev, "H16 ANE: a domain of the quarantined engine never went off; kept quarantined\n"); + ret = ane_h16_power_up(h); + if (!ret) + ret = -EIO; + } else if (h->resume_cold) { + ret = ane_h16_cold_boot(h, &h->resume_restarts, "resume restart/budget", + "after system sleep", h->sleep_quarantined); + } else { + ret = ane_h16_warm_boot(h); + if (ret) { + dev_warn(h->dev, "H16 ANE: warm boot failed (%d); cold boot and program replay\n", + ret); + h->resume_cold = true; + ret = ane_h16_cold_boot(h, &h->resume_restarts, + "resume restart/budget", + "after system sleep", false); + } + } + WRITE_ONCE(h->slept, false); if (ret) { - dev_warn(h->dev, "H16 ANE: warm boot failed (%d); cold boot and program replay\n", - ret); - h->resume_cold = true; - ret = ane_h16_cold_boot(h); + /* Every mapping and backing stays for diagnosis. */ + ane_h16_quarantine(h, ret); + h->boot.quarantined = true; + WRITE_ONCE(h->session.quarantined, true); + } else if (h->sleep_quarantined) { + h->recoveries++; + dev_info(h->dev, "H16 ANE: quarantined engine recovered by system sleep\n"); } + WRITE_ONCE(h->sleep_quarantined, false); + ane_h16_session_sleep(&h->session, false); + ane_h16_genpd_record(h); + /* One line per wake; times from PM_POST_SUSPEND, which follows the thaw. */ + ready = h->resume_ready_ns ? + div_u64(h->resume_ready_ns - start, NSEC_PER_MSEC) : -1; + first = h->resume_first_ns ? + div_u64(h->resume_first_ns - start, NSEC_PER_MSEC) : -1; + dev_info(h->dev, + "H16 ANE: resume %s: %s, firmware ready %lld ms, first program ready %lld ms, node reopened %llu ms, %u programs replayed, %u restarts\n", + ret ? "FAILED" : "ok", h->resume_cold ? "cold" : "warm", ready, first, + div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), h->resume_replayed, + h->resume_restarts); } - WRITE_ONCE(h->slept, false); - if (ret) { - /* Every mapping and backing stays for diagnosis. */ - ane_h16_quarantine(h, ret); - h->boot.quarantined = true; - h->session.quarantined = true; - } else if (h->sleep_quarantined) { - h->recoveries++; - dev_info(h->dev, "H16 ANE: quarantined engine recovered by system sleep\n"); + if (held) { + pm_runtime_mark_last_busy(h->dev); + pm_runtime_put_autosuspend(h->dev); } - h->sleep_quarantined = false; - ane_h16_session_sleep(&h->session, false); - ane_h16_genpd_record(h); - /* One line per wake; times from PM_POST_SUSPEND, which follows the thaw. */ - ready = h->resume_ready_ns ? div_u64(h->resume_ready_ns - start, NSEC_PER_MSEC) : -1; - first = h->resume_first_ns ? div_u64(h->resume_first_ns - start, NSEC_PER_MSEC) : -1; - dev_info(h->dev, - "H16 ANE: resume %s: %s, firmware ready %lld ms, first program ready %lld ms, node reopened %llu ms, %u programs replayed, %u restarts\n", - ret ? "FAILED" : "ok", h->resume_cold ? "cold" : "warm", ready, first, - div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), h->resume_replayed, - h->resume_restarts); +} + +/* + * Clear the sleep gates on PM_POST_SUSPEND or when PM_SUSPEND_PREPARE refuses + * a transition (the PM core does not send PM_POST_SUSPEND to the refusing + * notifier). + */ +static void ane_h16_sleep_unblock(struct ane_h16_device *h) +{ + WRITE_ONCE(h->in_sleep, false); + WRITE_ONCE(h->session.wake_blocked, false); + WRITE_ONCE(h->recover_blocked, false); + if (READ_ONCE(h->program_ready)) + wake_up_all(&h->session.wake); } static int ane_h16_pm_event(struct notifier_block *nb, unsigned long event, void *unused) @@ -777,16 +1013,39 @@ static int ane_h16_pm_event(struct notifier_block *nb, unsigned long event, void } if (event == PM_POST_SUSPEND) { ane_h16_sleep_resume(h); - WRITE_ONCE(h->recover_blocked, false); + ane_h16_sleep_unblock(h); return NOTIFY_DONE; } if (event == PM_SUSPEND_PREPARE && pinned) { + struct device *dev = h->dev; + bool rpm = READ_ONCE(h->rpm_enabled); + int ret; + + WRITE_ONCE(h->in_sleep, true); + WRITE_ONCE(h->session.wake_blocked, true); /* A recovery under way finishes first; sleep handles later ones. */ WRITE_ONCE(h->recover_blocked, true); flush_work(&h->recover); - if (!ane_h16_sleep_prepare(h)) + /* + * No idle park from here on: the sleep takes the engine down + * itself. A park that already began finishes first (the sleep + * waits for ane_h16_lock and finds the engine parked). + */ + if (rpm) + pm_runtime_get_noresume(dev); + ret = ane_h16_sleep_prepare(h); + if (rpm) { + if (!ret && !READ_ONCE(h->engine_on)) { + /* Off now: suspend so the DART links drop too. */ + pm_runtime_put_sync_suspend(dev); + } else { + pm_runtime_mark_last_busy(dev); + pm_runtime_put_autosuspend(dev); + } + } + if (!ret) return NOTIFY_DONE; - WRITE_ONCE(h->recover_blocked, false); + ane_h16_sleep_unblock(h); dev_warn_once(h->dev, ANE_FW_SLEEP_REFUSED); return NOTIFY_BAD; } @@ -828,7 +1087,8 @@ int ane_h16_backend_suspend(struct device *dev) { struct ane_h16_device *h = dev_get_drvdata(dev); /* Running firmware that the notifier did not suspend: refuse. */ - bool running = h && READ_ONCE(h->pinned) && !READ_ONCE(h->slept); + bool running = h && READ_ONCE(h->pinned) && READ_ONCE(h->engine_on) && + !READ_ONCE(h->slept); if (running) dev_warn_once(dev, ANE_FW_SLEEP_REFUSED); @@ -1501,32 +1761,57 @@ static void ane_h16_recover_work(struct work_struct *work) [ANE_T6021_RESTART_DONE] = "done", }; enum ane_t6021_restart_stage stage; + bool rpm = READ_ONCE(h->rpm_enabled), held = false, reschedule = false; u64 start = ktime_get_ns(); int ret; - guard(mutex)(&ane_h16_lock); - if (READ_ONCE(h->recover_blocked) || h->slept || !h->program_ready || - h->boot.quarantined || !h->session.quarantined || !ane_t6021_hung_stop) { + /* + * Keep runtime PM from starting a park and wait for any park in flight + * before taking ane_h16_lock. + */ + if (rpm) { + pm_runtime_get_noresume(h->dev); + pm_runtime_barrier(h->dev); + held = true; + } + scoped_guard(mutex, &ane_h16_lock) { + if (READ_ONCE(h->recover_blocked) || h->slept || h->parked || + !h->program_ready || h->boot.quarantined || + !h->session.quarantined || !ane_t6021_hung_stop) { + reschedule = h->program_ready && !h->parked && !h->slept && + !READ_ONCE(h->in_sleep) && !h->boot.quarantined && + !h->session.quarantined; + WRITE_ONCE(h->recovering, false); + break; + } + ane_h16_session_sleep(&h->session, true); + h->resume_replayed = 0; + h->resume_first_ns = 0; + ret = ane_t6021_restart_run(&ane_h16_restart_ops, h, false, &stage); + if (ret) { + h->recover_failures++; + dev_err(h->dev, + "H16 ANE: recovery after a hung request failed at the %s, error %d; quarantined until the next system sleep\n", + stages[stage], ret); + } else { + h->recoveries++; + reschedule = true; + dev_info(h->dev, + "H16 ANE: firmware recovered after a hung request in %llu ms, %u programs replayed\n", + div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), + h->resume_replayed); + } + ane_h16_session_sleep(&h->session, false); WRITE_ONCE(h->recovering, false); - return; } - ane_h16_session_sleep(&h->session, true); - h->resume_replayed = 0; - h->resume_first_ns = 0; - ret = ane_t6021_restart_run(&ane_h16_restart_ops, h, false, &stage); - if (ret) { - h->recover_failures++; - dev_err(h->dev, - "H16 ANE: recovery after a hung request failed at the %s, error %d; quarantined until the next system sleep\n", - stages[stage], ret); - } else { - h->recoveries++; - dev_info(h->dev, - "H16 ANE: firmware recovered after a hung request in %llu ms, %u programs replayed\n", - div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), h->resume_replayed); + if (held) { + if (reschedule) { + pm_runtime_mark_last_busy(h->dev); + pm_runtime_put_autosuspend(h->dev); + } else { + pm_runtime_put_noidle(h->dev); + } } - ane_h16_session_sleep(&h->session, false); - WRITE_ONCE(h->recovering, false); } /* Session ops->hung: may run under the session lock, so only queue. */ @@ -1546,6 +1831,7 @@ static const struct ane_h16_session_ops ane_h16_session_ops = { .unmap = ane_h16_program_unmap, .log = ane_h16_log, .busy = ane_h16_busy, + .wake = ane_h16_session_wake, .hung = ane_h16_hung, }; @@ -1628,6 +1914,7 @@ static void ane_h16_release(struct ane_h16_device *h) pm_runtime_put_sync(pd); dev_pm_domain_detach(pd, true); } + WRITE_ONCE(h->engine_on, false); h->acquired = false; vfree(h->pristine_data); h->pristine_data = NULL; @@ -1678,6 +1965,17 @@ static void ane_h16_busy(void *ctx, bool busy) struct ane_h16_device *h = ctx; apple_clpc_ane_set_active(h->clpc, busy); + /* Under the session lock: no callback runs here, the park drains first. */ + if (READ_ONCE(h->rpm_enabled)) { + if (busy && !h->rpm_busy) { + pm_runtime_get_noresume(h->dev); + h->rpm_busy = true; + } else if (!busy && h->rpm_busy) { + h->rpm_busy = false; + pm_runtime_mark_last_busy(h->dev); + pm_runtime_put_autosuspend(h->dev); + } + } if (!h->perf) return; if (busy) { @@ -1798,7 +2096,7 @@ static int ane_h16_acquire(struct platform_device *pdev, struct ane_h16_device * if (ret < 0) return ret; h->darts_powered++; - h->engine_on = h->darts_powered == ARRAY_SIZE(h->dart); + WRITE_ONCE(h->engine_on, h->darts_powered == ARRAY_SIZE(h->dart)); h->window[ANE_H16_DART0 + i] = ioremap_np(r.start, resource_size(&r)); if (!h->window[ANE_H16_DART0 + i]) return -ENOMEM; @@ -1930,7 +2228,7 @@ static int ane_h16_program_stage(struct ane_h16_device *h) ret); return ret; } - h->program_ready = true; + WRITE_ONCE(h->program_ready, true); ane_h16_irq_wait_set(h, true); dev_info(h->dev, "H16 stage 5 program window %llx..%llx%s\n", h->program_start, h->program_end - 1, h->clpc ? ", CLPC input attached" : ""); @@ -1979,6 +2277,7 @@ static int ane_h16_advance(struct ane_h16_device *h, enum ane_h16_stage stage) h->refused = true; return ret; } + ane_h16_rpm_idle(h); } dev_info(h->dev, "H16 stage %s complete%s\n", ane_h16_stage_name(stage), h->boot.ran ? "; held until reboot" : ""); @@ -1988,6 +2287,10 @@ static int ane_h16_advance(struct ane_h16_device *h, enum ane_h16_stage stage) ane_h16_stage_name(stage), ret); h->refused = true; ane_h16_release(h); + if (h->rpm_enabled && h->rpm_held) { + h->rpm_held = false; + pm_runtime_put_sync_suspend(h->dev); + } return ret; } @@ -2214,19 +2517,36 @@ int ane_h16_backend_probe(struct platform_device *pdev, const struct ane_fw_plat ret = register_pm_notifier(&h->pm_notifier); if (ret) { dev_err(h->dev, "H16 PM notifier refused, error %d\n", ret); - debugfs_remove_recursive(h->debugfs); - mutex_lock(&ane_h16_lock); - if (!--ane_h16_debugfs_users) { - debugfs_remove_recursive(ane_h16_debugfs); - ane_h16_debugfs = NULL; + goto err_notifier; + } + if (ane_h16_rpm(h)) { + ret = pm_runtime_set_active(h->dev); + if (ret) { + dev_err(h->dev, "H16 runtime PM activation refused, error %d\n", ret); + unregister_pm_notifier(&h->pm_notifier); + goto err_notifier; } - mutex_unlock(&ane_h16_lock); - platform_set_drvdata(pdev, NULL); - kfree(h); - return ret; + pm_runtime_get_noresume(h->dev); + h->rpm_held = true; + pm_runtime_set_autosuspend_delay(h->dev, ANE_H16_AUTOSUSPEND_MS); + pm_runtime_use_autosuspend(h->dev); + WRITE_ONCE(h->rpm_enabled, true); + pm_runtime_enable(h->dev); } schedule_work(&h->start); return 0; +err_notifier: + debugfs_remove_recursive(h->debugfs); + mutex_lock(&ane_h16_lock); + if (!--ane_h16_debugfs_users) { + debugfs_remove_recursive(ane_h16_debugfs); + ane_h16_debugfs = NULL; + } + mutex_unlock(&ane_h16_lock); + platform_set_drvdata(pdev, NULL); + drm_mm_takedown(&h->program_window); + kfree(h); + return ret; free: dev_err(h->dev, "H16 DT description refused, error %d\n", ret); drm_mm_takedown(&h->program_window); @@ -2239,26 +2559,48 @@ int ane_h16_backend_probe(struct platform_device *pdev, const struct ane_fw_plat void ane_h16_backend_remove(struct platform_device *pdev) { struct ane_h16_device *h = platform_get_drvdata(pdev); - bool keep; + bool keep, rpm_was_enabled; if (!h) return; /* Waits for the boot bring-up and any stage write in progress. */ cancel_work_sync(&h->start); cancel_work_sync(&h->recover); - if (h->program_ready) { + if (READ_ONCE(h->program_ready)) { cancel_delayed_work_sync(&h->session.gate_work); /* Return released exports; mapped ones stay with their mappings. */ flush_work(&h->session.export_work); } debugfs_remove_recursive(h->debugfs); + /* + * Stop runtime PM outside ane_h16_lock before touching state: waits for + * any in-flight park or wake callback and prevents new ones. A parked + * device stays suspended; an active device stays active. + */ + rpm_was_enabled = READ_ONCE(h->rpm_enabled); + if (rpm_was_enabled) { + pm_runtime_disable(h->dev); + pm_runtime_dont_use_autosuspend(h->dev); + } /* * Nothing can pin the device any more: the start work, the recovery * and the stage file are gone. An unpinned device drops its PM * notifier here, outside ane_h16_lock; a pinned one keeps it. */ - scoped_guard(mutex, &ane_h16_lock) + scoped_guard(mutex, &ane_h16_lock) { keep = h->boot.ran || h->pinned; + if (h->rpm_enabled) { + if (h->rpm_held) { + h->rpm_held = false; + pm_runtime_put_noidle(h->dev); + } + if (h->rpm_busy) { + h->rpm_busy = false; + pm_runtime_put_noidle(h->dev); + } + WRITE_ONCE(h->rpm_enabled, false); + } + } if (!keep) unregister_pm_notifier(&h->pm_notifier); mutex_lock(&ane_h16_lock); @@ -2272,7 +2614,11 @@ void ane_h16_backend_remove(struct platform_device *pdev) } else { ane_h16_release(h); drm_mm_takedown(&h->program_window); + platform_set_drvdata(pdev, NULL); kfree(h); } mutex_unlock(&ane_h16_lock); + /* Drop any remaining supplier device-link holds after pre-RUN rollback. */ + if (!keep && rpm_was_enabled) + pm_runtime_set_suspended(&pdev->dev); } diff --git a/drivers/accel/ane/ane_h16_boot.h b/drivers/accel/ane/ane_h16_boot.h index 671e2e3ec5dbf6..a606deb941e6eb 100644 --- a/drivers/accel/ane/ane_h16_boot.h +++ b/drivers/accel/ane/ane_h16_boot.h @@ -439,10 +439,13 @@ static inline int ane_h16_prepare(struct ane_h16_boot *b) { const struct ane_h16_build *f = b->build; unsigned int i, j; - int ret = ane_h16_ce(b); + int ret; - if (ret) - return ret; + if (f->ce) { + ret = ane_h16_ce(b); + if (ret) + return ret; + } for (i = 0; i < f->tunable_count; i++) { const struct ane_h16_tunables *group = &f->tunables[i]; diff --git a/drivers/accel/ane/ane_h16_boot_data.h b/drivers/accel/ane/ane_h16_boot_data.h index b845bf347d2111..8298ab635b7d67 100644 --- a/drivers/accel/ane/ane_h16_boot_data.h +++ b/drivers/accel/ane/ane_h16_boot_data.h @@ -600,4 +600,89 @@ static const struct ane_h16_profile ane_h16_profiles[] __maybe_unused = { }, }; +/* + * T8122 (M3) ANE DARTs, revision 2.0 (PARAMS3 0x2a2a0200). Same fault/protect/ + * lock and DAPF record layout as T6041/T8132, with the DAPF bank at DART0 + * + 0x4000. + */ +static const struct ane_h16_mmio ane_h15_mmio_t8122[] __maybe_unused = { + { + .dart_revision = 0x0200, + .dart_fault = 0x100, + .dart_address_lo = 0x170, + .dart_address_hi = 0x174, + .dart_protect = 0x200, + .dart_lock = 0x208, + .dapf_records = 0, + .dapf_stride = 0x40, + .dapf_end_mask = ~3ULL, + .dapf_r0 = 0x31, + .dapf_r4 = 0, + .dapf_r20 = 1, + }, +}; + +/* T8122 (M3) H15 27.2 (26B123): no CE block and no pre-RUN engine tunables. */ +static const struct ane_h16_build ane_h15_build_t8122_26b123 = { + .cpu_control = 0x1400044, + .rvbar = 0x1050000, + .ready = 0x08042006, + .run = 0x10, + .scratch_polls = 1000, + .scratch_delay_us = 1000, + .command_timeout_ns = 3000000000ULL, + .pool_dva = 0x10000384000, + .ipc_dva = 0x100003d0000, + .heap_dva = 0x100003e4000, + .shared_dva = 0x10001300000, + .expected_rvbar = 0x10000000001, + .pool_size = 0x40000, + .init_offset = 0x180, + .init_size = 0x174, + .config_span = 0x380000, + .config_window = 0x10000000, + .template_count = 64, + .template_word = 0x12c, + .template_value = 4, + .max_channels = 0x21, + .max_heap = SZ_16M, + .native_free = true, + .startup = { { 4, 12 }, { 0, 12 }, { 3, 16 }, { 0x22, 100 } }, +}; + +/* + * M3 Air (J615) 27.2 (26B123) preload: TEXT 0xc8000, DATA 0x2a4000. + * Patchbay cells in DATA order (GKTS, ECAP, ARcM mutable; ABOI, ZSOI fixed). + */ +static const struct ane_h16_preload_cell ane_h15_patchbay_26b123_t8122[] = { + { "GKTS", 0x6850, 8, true }, + { "ECAP", 0x6943, 8, true }, + { "ARcM", 0x6a18, 4, true }, + { "ABOI", 0x6a75, 8, false }, + { "ZSOI", 0x6a85, 4, false }, +}; + +static const struct ane_h16_preload_rule ane_h15_preload_26b123_j615 = { + .cells = ane_h15_patchbay_26b123_t8122, + .cell_count = ARRAY_SIZE(ane_h15_patchbay_26b123_t8122), + .zero_start = 0x2a4000, + .zero_end = 0x2a4000, + .text_size = 0xc8000, + .data_size = 0x2a4000, + .digest = { + 0xed, 0x4a, 0x5a, 0xcf, 0x99, 0x53, 0x21, 0xd1, + 0x51, 0xca, 0xc8, 0xec, 0x2d, 0x2b, 0xf1, 0x1a, + 0x0f, 0xb7, 0x34, 0x4c, 0x43, 0xc0, 0xec, 0x24, + 0x01, 0x6b, 0x59, 0x09, 0x37, 0xee, 0x29, 0x17, + }, +}; + +static const struct ane_h16_profile ane_t8122_profiles_26b123[] __maybe_unused = { + { + .identity = "H15 T8122 27.2 26B123 J615", + .preload = &ane_h15_preload_26b123_j615, + .build = &ane_h15_build_t8122_26b123, + }, +}; + #endif /* __ANE_H16_BOOT_DATA_H__ */ diff --git a/drivers/accel/ane/ane_h16_boot_test.c b/drivers/accel/ane/ane_h16_boot_test.c index b4ea8bebf04cb8..88047e7d938f28 100644 --- a/drivers/accel/ane/ane_h16_boot_test.c +++ b/drivers/accel/ane/ane_h16_boot_test.c @@ -1318,6 +1318,26 @@ static void ane_h16_no_xl_test(struct kunit *test) KUNIT_EXPECT_EQ(test, s->xl_writes, 0U); } +/* H15 (T8122): no CE block, no tunables, five DAPF records, DART rev 0x200. */ +static void ane_h16_t8122_no_ce_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->build = ane_h15_build_t8122_26b123; + s->mmio = ane_h15_mmio_t8122[0]; + s->dart_params = 0x2a2a0200; + s->soc.h16_mmio = ane_h15_mmio_t8122; + s->soc.h16_mmio_count = ARRAY_SIZE(ane_h15_mmio_t8122); + s->soc.dapf_count = 5; + s->soc.has_xl = false; + s->ce_timeout = true; + s->expect_tuning = 0; + KUNIT_ASSERT_EQ(test, ane_h16_run(&s->boot, ANE_H16_STARTUP), 0); + KUNIT_EXPECT_EQ(test, s->tuning_writes, 0U); + KUNIT_EXPECT_EQ(test, s->ce_ack, 0ULL); + KUNIT_EXPECT_EQ(test, s->dapf_writes, 25U); +} + /* The T8132 boots with its own engine writes only: no XL or C1PPT. */ static void ane_h16_t8132_tunables_test(struct kunit *test) { @@ -1402,6 +1422,7 @@ static struct kunit_case ane_h16_boot_cases[] = { KUNIT_CASE(ane_h16_dapf_five_test), KUNIT_CASE(ane_h16_dapf_five_readback_test), KUNIT_CASE(ane_h16_no_xl_test), + KUNIT_CASE(ane_h16_t8122_no_ce_test), KUNIT_CASE(ane_h16_t8132_tunables_test), KUNIT_CASE(ane_h16_t8132_locked_test), KUNIT_CASE(ane_h16_t8132_locked_strobe_test), diff --git a/drivers/accel/ane/ane_h16_hwx.c b/drivers/accel/ane/ane_h16_hwx.c index a7ad970ba02af2..2c5d72671c738a 100644 --- a/drivers/accel/ane/ane_h16_hwx.c +++ b/drivers/accel/ane/ane_h16_hwx.c @@ -16,7 +16,62 @@ struct hwx_range { u64 start, size; }; +struct hwx_target { + u32 subtype; + u32 linear, mixed; + unsigned int header_words; + u32 trailer_bar; + bool has_perf_record; + bool allow_zero_prologue; + bool require_tight_end; + bool allow_stabs_note; + bool allow_slot5_table; + bool allow_zero_scratch_text_flags; +}; + +static const struct hwx_target *hwx_target(u32 subtype) +{ + static const struct hwx_target targets[] = { + { + .subtype = ANE_HWX_SUBTYPE_H15, + .linear = 0x890, + .mixed = 0x8b0, + .header_words = 8, + .trailer_bar = 5, + .allow_zero_prologue = true, + }, + { + .subtype = ANE_HWX_SUBTYPE_H16, + .linear = 0x8a0, + .mixed = 0x8c0, + .header_words = 9, + .trailer_bar = 4, + .has_perf_record = true, + .require_tight_end = true, + }, + { + .subtype = ANE_HWX_SUBTYPE_H17, + .linear = 0x8a0, + .mixed = 0x8c0, + .header_words = 9, + .trailer_bar = 4, + .has_perf_record = true, + .allow_zero_prologue = true, + .allow_stabs_note = true, + .allow_slot5_table = true, + .allow_zero_scratch_text_flags = true, + }, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(targets); i++) + if (targets[i].subtype == subtype) + return &targets[i]; + return NULL; +} + struct hwx_parser { + const struct hwx_target *target; const u8 *bytes; size_t size, command_end; struct ane_h16_hwx info; @@ -117,7 +172,7 @@ static int hwx_segment(struct hwx_parser *p, const u8 *c, u32 length) * zin_ane_compiler 10.205 marks it 0 there too on H17 (relocations are checked below). */ flags = get_unaligned_le32(c + 68); - if (text && p->info.subtype == ANE_HWX_SUBTYPE_H17 && p->info.scratch.size) { + if (text && p->target->allow_zero_scratch_text_flags && p->info.scratch.size) { if (flags != 4 && flags) return -ENOEXEC; } else if (flags != (surface ? 6 : text ? (p->info.scratch.size ? 4 : 0) : 4)) { @@ -214,18 +269,31 @@ static int hwx_segment(struct hwx_parser *p, const u8 *c, u32 length) return 0; } +/* + * The fp32 trailer word at +0x880 (+0x8a0 with scratch) is 10000.0f in HWX + * from ANECompiler 10.205 and mil-hwx-compiler, and 1000.0f in H16 and H17 + * HWX from ANECompiler 10.302 (macOS 27.3). Both load; any other value is + * refused. + */ +static u32 hwx_trailer_value(const u8 *c, u32 offset) +{ + u32 value = get_unaligned_le32(c + offset); + + return value == 0x447a0000 ? value : 0x461c4000; +} + static int hwx_program(struct hwx_parser *p) { + const struct hwx_target *t = p->target; const u8 *c = p->bytes + p->info.program_offset; struct ane_h16_hwx *info = &p->info; - u32 length = get_unaligned_le32(c + 4), records, record_limit, table, i; + u32 length = get_unaligned_le32(c + 4), records, record_limit, table, i, off, count; u32 prologue = 1; size_t final_end = 0; u64 work_limit = 0; - bool mixed = length == 0x8c0; + bool mixed = length == t->mixed; - /* H17 streams open with 0 (linked programs) or 1 (Apple's matmul and add output). */ - if (info->subtype == ANE_HWX_SUBTYPE_H17 && info->text.size >= 4 && + if (t->allow_zero_prologue && info->text.size >= 4 && !get_unaligned_le32(p->bytes + info->text.offset)) prologue = 0; /* Nonzero cells only; every other byte is checked below. */ @@ -237,9 +305,9 @@ static int hwx_program(struct hwx_parser *p) u8 *expected; int ret = -ENOEXEC; - if (length != 0x8a0 && !mixed) + if (length != t->linear && !mixed) return -ENOEXEC; - if (get_unaligned_le32(c + 0xc) != (mixed ? 0x22a : 0x222) || + if (get_unaligned_le32(c + 0xc) != length / 4 - 6 || get_unaligned_le64(c + 0x10) != info->text.vm || get_unaligned_le64(c + 0x810) != info->text.vm || get_unaligned_le64(c + 0x20) != info->constants.vm || @@ -248,7 +316,7 @@ static int hwx_program(struct hwx_parser *p) get_unaligned_le32(c + 0x838) != U32_MAX || get_unaligned_le32(c + 0x83c) != U32_MAX || get_unaligned_le32(c + 0x844) != 0xffff || - get_unaligned_le32(c + 0x848) != (mixed ? 0x8b8 : 0x898)) + get_unaligned_le32(c + 0x848) != length - 8) return -ENOEXEC; records = get_unaligned_le32(c + 0x860); info->tasks = get_unaligned_le32(c + 0x830); @@ -268,7 +336,7 @@ static int hwx_program(struct hwx_parser *p) * kernel fill consecutive slots from slot 6 (+0x70); Apple's zin_ane_compiler 10.205 * starts the same run at slot 5 (+0x60) on H17, the task stream naming slots 5, 6, 7. */ - table = info->subtype == ANE_HWX_SUBTYPE_H17 && get_unaligned_le64(c + 0x60) ? 0x60 : 0x70; + table = t->allow_slot5_table && get_unaligned_le64(c + 0x60) ? 0x60 : 0x70; for (i = 0; i < 5; i++) { u64 base = i < info->surface_count ? info->surfaces[i].section.vm : i == info->surface_count ? info->kernel.vm : 0; @@ -284,7 +352,7 @@ static int hwx_program(struct hwx_parser *p) */ for (i = 0; i < info->surface_count; i++) work_limit += info->surfaces[i].allocation; - if (get_unaligned_le32(c + (mixed ? 0x8b0 : 0x890)) > work_limit) + if (get_unaligned_le32(c + length - 16) > work_limit) return -ENOEXEC; /* Construct the exact fixed trailer and reserved-space expectation. */ @@ -295,29 +363,37 @@ static int hwx_program(struct hwx_parser *p) memcpy(expected + common[i], c + common[i], 4); for (i = 0; i < 5; i++) memcpy(expected + table + i * 16, c + table + i * 16, 8); - put_unaligned_le32(4, expected + 0x868); - put_unaligned_le32(mixed ? 4 : 2, expected + 0x870); - put_unaligned_le32(mixed ? 2 : 7, expected + 0x878); - put_unaligned_le32(8, expected + 0x87c); - put_unaligned_le32(mixed ? get_unaligned_le32(c + 0x858) : 0x461c4000, - expected + 0x880); - put_unaligned_le32(mixed ? 3 : 9, expected + 0x888); - put_unaligned_le32(8, expected + 0x88c); + count = 1 + (mixed ? 2 : 0) + (t->has_perf_record ? 1 : 0); + put_unaligned_le32(t->trailer_bar, expected + 0x868); + put_unaligned_le32(count, expected + 0x870); + off = 0x878; if (mixed) { - put_unaligned_le32(0x08020004, expected + 0x890); - put_unaligned_le32(8, expected + 0x894); - put_unaligned_le32(7, expected + 0x898); - put_unaligned_le32(8, expected + 0x89c); - put_unaligned_le32(0x461c4000, expected + 0x8a0); - put_unaligned_le32(9, expected + 0x8a8); - put_unaligned_le32(8, expected + 0x8ac); + put_unaligned_le32(2, expected + off); + put_unaligned_le32(8, expected + off + 4); + put_unaligned_le32(get_unaligned_le32(c + 0x858), expected + off + 8); + off += 16; + put_unaligned_le32(3, expected + off); + put_unaligned_le32(8, expected + off + 4); + put_unaligned_le32(0x08020004, expected + off + 8); + put_unaligned_le32(8, expected + off + 12); + off += 16; + } + if (t->has_perf_record) { + put_unaligned_le32(7, expected + off); + put_unaligned_le32(8, expected + off + 4); + put_unaligned_le32(hwx_trailer_value(c, off + 8), expected + off + 8); + off += 16; } - memcpy(expected + (mixed ? 0x8b0 : 0x890), c + (mixed ? 0x8b0 : 0x890), 4); - memcpy(expected + (mixed ? 0x8b8 : 0x898), "main", 5); + put_unaligned_le32(9, expected + off); + put_unaligned_le32(8, expected + off + 4); + memcpy(expected + off + 8, c + off + 8, 4); + off += 16; + memcpy(expected + off, "main", 5); if (!memcmp(c, expected, length)) { - ret = ane_hx_task_stream_validate_limit(p->bytes + info->text.offset, - info->text.size, info->tasks, prologue, - &record_limit, &final_end); + ret = ane_hx_task_stream_validate_hdr(p->bytes + info->text.offset, + info->text.size, info->tasks, prologue, + info->task_header_words, &record_limit, + &final_end); /* This compiler hint need not equal the encoded record count. */ if (!ret && (!records || records > record_limit)) ret = -ENOEXEC; @@ -326,8 +402,7 @@ static int hwx_program(struct hwx_parser *p) * zero blocks after it leave the engine armed, and the next * EXECUTE on the device times out. */ - if (!ret && info->subtype == ANE_HWX_SUBTYPE_H16 && - final_end != info->text.size) + if (!ret && t->require_tight_end && final_end != info->text.size) ret = -ENOEXEC; } kfree(expected); @@ -480,7 +555,7 @@ static int hwx_symbols(struct hwx_parser *p) * n_desc holds the stabs type number. They name no address; their strings are * still checked below. */ - bool h17 = p->info.subtype == ANE_HWX_SUBTYPE_H17; + bool h17 = p->target->allow_stabs_note; bool stab = h17 && (s[4] == 0x20 || s[4] == 0x80); if (strx >= p->strsize || @@ -525,37 +600,30 @@ static int hwx_symbols(struct hwx_parser *p) static bool hwx_relocations_in_payload(const struct hwx_parser *p, unsigned long *sites) { const u8 *text = p->bytes + p->info.text.offset; - size_t pos = 16; + struct ane_hx_task t; + size_t pos = 16, record; + u32 count; + int ret; while (pos < p->info.text.size) { - u32 words = (get_unaligned_le32(text + pos) >> 16) & 0x7ff; - size_t end, record; - - if (!words) { - pos += 16; + ret = ane_hx_task_frame(text, p->info.text.size, pos, + p->info.task_header_words, &t); + if (ret < 0) + return false; + pos = t.next; + if (!ret) continue; + for (record = t.rec; record < t.end; record += 4 + count * 4) { + count = ane_hx_record_count(get_unaligned_le32(text + record)); + bitmap_clear(sites, record / 4 + 1, count); } - end = pos + words * 4; - record = pos + 9 * 4; - if ((get_unaligned_le32(text + pos + 8 * 4) & 3) == 3) - record += 4; - while (record < end) { - u32 header = get_unaligned_le32(text + record); - u32 count = header & BIT(31) ? - 1 + hweight32((header >> 15) & 0xffff) : - 1 + ((header >> 15) & 0x3f); - - record += 4; - bitmap_clear(sites, record / 4, count); - record += count * 4; - } - pos = ALIGN(end, 16); } return bitmap_empty(sites, p->info.text.size / 4); } int ane_h16_hwx_validate(const void *bytes, size_t size, struct ane_h16_hwx *info) { + const struct hwx_target *target; struct hwx_parser *p; const void *relocations; const u8 *c = bytes; @@ -566,11 +634,12 @@ int ane_h16_hwx_validate(const void *bytes, size_t size, struct ane_h16_hwx *inf if (!c || !info || size < 32 || size > ANE_H16_HWX_MAX || get_unaligned_le32(c) != 0xbeefface || get_unaligned_le32(c + 4) != 0x80 || - (get_unaligned_le32(c + 8) != ANE_HWX_SUBTYPE_H16 && - get_unaligned_le32(c + 8) != ANE_HWX_SUBTYPE_H17) || get_unaligned_le32(c + 12) != 2 || get_unaligned_le32(c + 24) != 0x200000 || get_unaligned_le32(c + 28)) return -ENOEXEC; + target = hwx_target(get_unaligned_le32(c + 8)); + if (!target) + return -ENOEXEC; count = get_unaligned_le32(c + 16); length = get_unaligned_le32(c + 20); if (!count || count > HWX_COMMANDS_MAX || !hwx_fits(32, length, size)) @@ -578,10 +647,12 @@ int ane_h16_hwx_validate(const void *bytes, size_t size, struct ane_h16_hwx *inf p = kzalloc_obj(*p); if (!p) return -ENOMEM; + p->target = target; p->bytes = bytes; p->size = size; p->command_end = 32 + (size_t)length; - p->info.subtype = get_unaligned_le32(p->bytes + 8); + p->info.subtype = target->subtype; + p->info.task_header_words = target->header_words; for (i = 0; i < count; i++) { u32 cmd, len; @@ -615,7 +686,8 @@ int ane_h16_hwx_validate(const void *bytes, size_t size, struct ane_h16_hwx *inf goto invalid; p->tensors[p->tensor_count++] = pos; } else if (get_unaligned_le32(c + 8) == 4) { - if (p->info.program_offset || (len != 0x8a0 && len != 0x8c0)) + if (p->info.program_offset || + (len != p->target->linear && len != p->target->mixed)) goto invalid; p->info.program_offset = pos; } else { @@ -644,7 +716,7 @@ int ane_h16_hwx_validate(const void *bytes, size_t size, struct ane_h16_hwx *inf * LC_NOTE: zin_ane_compiler 10.205 (H17) records its runtime version * inline, offset 40 into this command, 4 bytes. It maps nothing. */ - if (p->info.subtype != ANE_HWX_SUBTYPE_H17 || p->note || len != 48 || + if (!p->target->allow_stabs_note || p->note || len != 48 || !hwx_name(c + 8, "rt.version") || get_unaligned_le64(c + 24) != 40 || get_unaligned_le64(c + 32) != 4 || !hwx_zero(c, 44, len)) goto invalid; diff --git a/drivers/accel/ane/ane_h16_hwx.h b/drivers/accel/ane/ane_h16_hwx.h index dedfa58741964c..eb1022a8928ed5 100644 --- a/drivers/accel/ane/ane_h16_hwx.h +++ b/drivers/accel/ane/ane_h16_hwx.h @@ -10,7 +10,8 @@ #define ANE_H16_SECTIONS 8 #define ANE_H16_REGIONS 7 #define ANE_H16_HWX_MAX (SZ_256M + SZ_1M) -/* Mach-O CPU subtypes of the two targets that share this container form. */ +/* Mach-O CPU subtypes of the targets that share this container form. */ +#define ANE_HWX_SUBTYPE_H15 6 #define ANE_HWX_SUBTYPE_H16 7 #define ANE_HWX_SUBTYPE_H17 9 @@ -53,6 +54,8 @@ struct ane_h16_hwx { struct ane_h16_hwx_section text, constants, kernel, scratch; /* Target; a backend accepts only its own engine's subtype. */ u32 subtype; + /* Fixed words per task of the target's task stream (ane_hx_task_frame()). */ + u32 task_header_words; struct ane_h16_hwx_surface surfaces[ANE_H16_SURFACES]; u32 surface_count; u32 tasks; diff --git a/drivers/accel/ane/ane_h16_hwx_test.c b/drivers/accel/ane/ane_h16_hwx_test.c index a6e3976cda8f3b..896fd719fe3b78 100644 --- a/drivers/accel/ane/ane_h16_hwx_test.c +++ b/drivers/accel/ane/ane_h16_hwx_test.c @@ -275,6 +275,31 @@ static void hwx_program_test(struct kunit *test) } } +/* The fp32 trailer word: 10000.0f or 1000.0f, in every form; nothing else. */ +static void hwx_trailer_test(struct kunit *test) +{ + static const u32 refused[] = { 0, 0x3f800000, 0x42c80000, 0x461c4001, 0x447a0001 }; + unsigned int variant, i; + + for (variant = 0; variant < 4; variant++) { + struct hwx_fixture *f = fixture_create(test, variant & 1, variant & 2); + struct ane_h16_hwx info; + u8 *word; + + KUNIT_ASSERT_NOT_NULL(test, f); + word = f->bytes + f->program + ((variant & 1) ? 0x8a0 : 0x880); + KUNIT_ASSERT_EQ(test, get_unaligned_le32(word), 0x461c4000U); + put_unaligned_le32(0x447a0000, word); + KUNIT_EXPECT_EQ_MSG(test, ane_h16_hwx_validate(f->bytes, f->size, &info), 0, + "form %u, 1000.0f", variant); + for (i = 0; i < ARRAY_SIZE(refused); i++) { + put_unaligned_le32(refused[i], word); + KUNIT_EXPECT_EQ_MSG(test, ane_h16_hwx_validate(f->bytes, f->size, &info), + -ENOEXEC, "form %u, word %#x", variant, refused[i]); + } + } +} + /* Build only structural tasks: no model bytes or hardware fixtures needed. */ static void fixture_tasks(struct hwx_fixture *f, u32 tasks, u32 records) { @@ -804,6 +829,85 @@ static void hwx_h17_zin_test(struct kunit *test) #undef AS_H16 } +/* + * H15 (M3, subtype 6): 0x890 linear / 0x8b0 mixed program descriptor (no fp32 + * trailer record, trailer_bar 5), 8-word task header, prologue 0 or 1. + */ +static void hwx_h15_test(struct kunit *test) +{ + unsigned int form; + + for (form = 0; form < 2; form++) { + struct hwx_fixture *f = fixture_create(test, form, false); + struct ane_h16_hwx info = {}; + u32 prog_len = form ? 0x8b0 : 0x890; + u32 old_len = form ? 0x8c0 : 0x8a0; + u8 *c, *text, *section; + + KUNIT_ASSERT_NOT_NULL(test, f); + /* Shrink the program descriptor command by 16 bytes (drop key=7 record). */ + c = f->bytes + f->program; + put_unaligned_le32(ANE_HWX_SUBTYPE_H15, f->bytes + 8); + put_unaligned_le32(prog_len, c + 4); + put_unaligned_le32(form ? 0x226 : 0x21e, c + 0xc); + put_unaligned_le32(form ? 0x8a8 : 0x888, c + 0x848); + put_unaligned_le32(5, c + 0x868); + put_unaligned_le32(form ? 3 : 1, c + 0x870); + if (form) { + /* Mixed 0x8b0: keep key=2 and key=3, move key=9 to +0x898. */ + put_unaligned_le32(9, c + 0x898); + put_unaligned_le32(8, c + 0x89c); + put_unaligned_le32(0, c + 0x8a0); + put_unaligned_le32(0, c + 0x8a4); + memcpy(c + 0x8a8, "main", 5); + } else { + /* Linear 0x890: single key=9 record at +0x878. */ + put_unaligned_le32(9, c + 0x878); + put_unaligned_le32(8, c + 0x87c); + put_unaligned_le32(0, c + 0x880); + put_unaligned_le32(0, c + 0x884); + memcpy(c + 0x888, "main", 5); + } + /* Shift remaining load commands + symtab/strings back by 16 bytes. */ + memmove(c + prog_len, c + old_len, f->reloc + 8 - (f->program + old_len)); + f->cursor -= 16; + f->symtab -= 16; + f->symbols -= 16; + f->strings -= 16; + put_unaligned_le32(f->cursor - 32, f->bytes + 20); + put_unaligned_le32(f->symbols, f->bytes + f->symtab + 8); + put_unaligned_le32(f->strings, f->bytes + f->symtab + 16); + + /* H15 task stream: 8-word header + 2-word record (40 B) + 16 B prologue. */ + text = f->bytes + SZ_16K; + section = f->bytes + f->text_command + 72; + memset(text, 0, 64); + put_unaligned_le32(0, text); + put_unaligned_le32(10 << 16, text + 16); + put_unaligned_le32(0x4100 / 4, text + 48); + put_unaligned_le64(56, section + 40); + put_unaligned_le32(14, c + 0x824); + + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), 0); + KUNIT_EXPECT_EQ(test, info.subtype, ANE_HWX_SUBTYPE_H15); + KUNIT_EXPECT_EQ(test, info.tasks, 1U); + /* Prologue 1 is accepted too. */ + put_unaligned_le32(1, text); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), 0); + /* H16 rejects an H15 layout. */ + put_unaligned_le32(ANE_HWX_SUBTYPE_H16, f->bytes + 8); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + put_unaligned_le32(ANE_HWX_SUBTYPE_H15, f->bytes + 8); + /* A 9-word H16 task header fails H15 validation. */ + put_unaligned_le32(11 << 16, text + 16); + put_unaligned_le32(0, text + 48); + put_unaligned_le32(0x4100 / 4, text + 52); + put_unaligned_le64(60, section + 40); + put_unaligned_le32(15, c + 0x824); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + } +} + static struct kunit_case hwx_cases[] = { KUNIT_CASE(hwx_forms_test), KUNIT_CASE(hwx_header_test), @@ -812,6 +916,7 @@ static struct kunit_case hwx_cases[] = { KUNIT_CASE(hwx_element_format_test), KUNIT_CASE(hwx_surface_order_test), KUNIT_CASE(hwx_program_test), + KUNIT_CASE(hwx_trailer_test), KUNIT_CASE(hwx_staged_counts_test), KUNIT_CASE(hwx_final_task_end_test), KUNIT_CASE(hwx_geometry_test), @@ -823,6 +928,7 @@ static struct kunit_case hwx_cases[] = { KUNIT_CASE(hwx_load_resources_test), KUNIT_CASE(hwx_import_bounds_test), KUNIT_CASE(hwx_h17_zin_test), + KUNIT_CASE(hwx_h15_test), {} }; @@ -832,4 +938,5 @@ static struct kunit_suite hwx_suite = { }; kunit_test_suite(hwx_suite); +MODULE_DESCRIPTION("KUnit tests for Apple ANE HWX loading"); MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_pending_test.c b/drivers/accel/ane/ane_h16_pending_test.c index ed866c45710d7f..fef233e2c8ed24 100644 --- a/drivers/accel/ane/ane_h16_pending_test.c +++ b/drivers/accel/ane/ane_h16_pending_test.c @@ -328,4 +328,5 @@ static struct kunit_suite pending_suite = { }; kunit_test_suite(pending_suite); +MODULE_DESCRIPTION("KUnit tests for Apple ANE pending requests"); MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_preload_test.c b/drivers/accel/ane/ane_h16_preload_test.c index 54112eae618bff..e29071d92538f2 100644 --- a/drivers/accel/ane/ane_h16_preload_test.c +++ b/drivers/accel/ane/ane_h16_preload_test.c @@ -457,4 +457,5 @@ static struct kunit_suite preload_suite = { }; kunit_test_suite(preload_suite); +MODULE_DESCRIPTION("KUnit tests for Apple ANE firmware preload"); MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_program.c b/drivers/accel/ane/ane_h16_program.c index e7d9c67bc89a96..3ab72b3fa607d1 100644 --- a/drivers/accel/ane/ane_h16_program.c +++ b/drivers/accel/ane/ane_h16_program.c @@ -8,6 +8,7 @@ #include #include "ane_h16_program.h" +#include "ane_h16_tasks.h" /* * The one LOAD slot table. Slot 1 carries the HWX kernel section, or the @@ -302,10 +303,12 @@ int ane_h16_process_bindings(const struct ane_h16_hwx *hwx, const void *generic, hwx->surface_count > ANE_H16_SURFACES || (hwx->scratch.size && !scratch)) return -EINVAL; entries = hwx->surface_count + !!hwx->scratch.size; + /* The firmware reads the whole section: every byte has its one value. */ if (generic_size != ANE_H16_GENERIC_HEADER + entries * ANE_H16_GENERIC_ENTRY || get_unaligned_le32(g) != ANE_H16_GENERIC_MAGIC || !get_unaligned_le32(g + 4) || get_unaligned_le32(g + 4) > ANE_H16_GENERIC_VERSION || + memchr_inv(g + 8, 0, ANE_H16_GENERIC_COUNT - 8) || get_unaligned_le32(g + ANE_H16_GENERIC_COUNT) != entries) return -ENOEXEC; for (i = 0; i < entries; i++) { @@ -320,7 +323,11 @@ int ane_h16_process_bindings(const struct ane_h16_hwx *hwx, const void *generic, if (get_unaligned_le32(e) != 1 || id == 2 || id == 3 || id > ANE_H16_GENERIC_ID_MAX || get_unaligned_le32(e + 8) != direction - 1 || - get_unaligned_le32(e + 0x10) != direction) + get_unaligned_le32(e + 0xc) || + get_unaligned_le32(e + 0x10) != direction || + memchr_inv(e + 0x14, 0, 0xc) || + get_unaligned_le32(e + 0x28) != ANE_H16_GENERIC_ENTRY_TAIL || + get_unaligned_le32(e + 0x2c)) return -ENOEXEC; /* The scratch entry may round __bss up to its 16 KiB mapping. */ if (is_scratch ? bytes < hwx->scratch.size || @@ -355,6 +362,22 @@ int ane_h16_process_bindings(const struct ane_h16_hwx *hwx, const void *generic, } EXPORT_SYMBOL_GPL(ane_h16_process_bindings); +/* The kernel slot runs to the end of the section's last 16 KiB page of its region. */ +static u64 h16_kernel_reach(const struct ane_h16_hwx *hwx) +{ + unsigned int i; + + for (i = 0; i < hwx->region_count; i++) { + const struct ane_h16_hwx_region *r = &hwx->regions[i]; + u64 offset = hwx->kernel.vm - r->vm; + + if (r->kind == ANE_H16_REGION_KERNEL && hwx->kernel.vm >= r->vm && + offset < r->size && hwx->kernel.size <= r->size - offset) + return ALIGN(offset + hwx->kernel.size, SZ_16K) - offset; + } + return hwx->kernel.size; +} + /* * The operation section binds BAR slots to resources: per record, a count at * +8 and (slot, tag) pairs from +0xc. A tag is a generic-section ID, or the @@ -363,6 +386,12 @@ EXPORT_SYMBOL_GPL(ane_h16_process_bindings); * name the resource whose HWX address is that base. Kernel programs must bind * the kernel: the legacy tag 2 instead makes the H17 firmware assert and stop * answering (H17 harness facts, kernel-table programs). + * + * Each DMA base offset in the task stream is taken relative to the DVA of + * the buffer bound to its slot, so every base must name a bound slot and + * stay inside that buffer with the extent of its transfer: a surface's + * declared size, the scratch's __bss size, or the kernel section to the end + * of its last 16 KiB page, which is what the kernel slot maps. */ int ane_h16_operation_validate(const struct ane_h16_hwx_snapshot *snapshot, const struct ane_h16_hwx *hwx, const void *operation, @@ -374,6 +403,7 @@ int ane_h16_operation_validate(const struct ane_h16_hwx_snapshot *snapshot, const u8 *o = operation, *c; unsigned int r, records, i, j; bool kernel_bound = false; + u64 *bound; int ret; if (!hwx || !o || !bindings || count != hwx->surface_count || @@ -390,43 +420,107 @@ int ane_h16_operation_validate(const struct ane_h16_hwx_snapshot *snapshot, return -ENOEXEC; records = get_unaligned_le32(o); if (!records || records > ANE_H16_OPERATION_RECORDS_MAX || - operation_size != 4 + (size_t)records * ANE_H16_OPERATION_RECORD) + operation_size != 4 + (size_t)records * ANE_H16_OPERATION_RECORD || + hwx->text.offset > snapshot->size || hwx->text.size > snapshot->size - hwx->text.offset) return -ENOEXEC; + bound = kcalloc(ANE_HX_DMA_SLOTS, sizeof(*bound), GFP_KERNEL); + if (!bound) + return -ENOMEM; + ret = -ENOEXEC; for (r = 0; r < records; r++) { const u8 *rec = o + 4 + r * ANE_H16_OPERATION_RECORD; u32 refs = get_unaligned_le32(rec + 8); u64 seen = 0; if (get_unaligned_le32(rec) || get_unaligned_le32(rec + 4) || - refs > ANE_H16_OPERATION_REFS_MAX) - return -ENOEXEC; + refs > ANE_H16_OPERATION_REFS_MAX || + memchr_inv(rec + 0xc + refs * 8, 0, ANE_H16_OPERATION_RECORD - 0xc - refs * 8)) + goto out; for (i = 0; i < refs; i++) { u32 slot = get_unaligned_le32(rec + 0xc + i * 8); u32 tag = get_unaligned_le32(rec + 0x10 + i * 8); - u64 base, want = 0; + u64 base, want = 0, size = 0; - if (slot >= 64 || (seen & BIT_ULL(slot))) - return -ENOEXEC; + if (slot >= ANE_HX_DMA_SLOTS || (seen & BIT_ULL(slot))) + goto out; seen |= BIT_ULL(slot); base = get_unaligned_le64(c + 0x10 * (slot + 1)); if (tag == ANE_H16_RESOURCE_KERNEL && hwx->kernel.size) { want = hwx->kernel.vm; + size = h16_kernel_reach(hwx); kernel_bound = true; } else if (scratch && hwx->scratch.size && tag == scratch->index) { want = scratch->hwx_vm; + size = hwx->scratch.size; } else { for (j = 0; j < count; j++) - if (tag == bindings[j].index) + if (tag == bindings[j].index) { want = bindings[j].hwx_vm; + size = bindings[j].bytes; + } } if (!want || base != want) - return -ENOEXEC; + goto out; + bound[slot] = size; } } - return hwx->kernel.size && !kernel_bound ? -ENOEXEC : 0; + if (hwx->kernel.size && !kernel_bound) + goto out; + ret = ane_hx_task_stream_dma_validate((const u8 *)snapshot->bytes + hwx->text.offset, + hwx->text.size, hwx->task_header_words, bound); +out: + kfree(bound); + return ret; } EXPORT_SYMBOL_GPL(ane_h16_operation_validate); +/* + * The procedure and text-properties sections have one form each, which the + * kernel derives from the validated program: one procedure, and one text + * segment of the whole task stream with its task count. The firmware takes + * the stream's framing (segment offset, size, task count) from the text + * properties, so any other form would describe a stream other than the one + * the task validator checked. + */ +void ane_h16_fixed_sections(const struct ane_h16_hwx *hwx, + u8 procedure[ANE_H16_PROCEDURE_SIZE], + u8 properties[ANE_H16_PROPERTIES_SIZE]) +{ + static const u32 call[] = { 1, 3, 0, 0, 1, 0, U32_MAX, 4 }; + unsigned int i; + + memset(procedure, 0, ANE_H16_PROCEDURE_SIZE); + put_unaligned_le32(1, procedure); + put_unaligned_le64(0x18, procedure + 8); + put_unaligned_le64(sizeof(call), procedure + 0x10); + for (i = 0; i < ARRAY_SIZE(call); i++) + put_unaligned_le32(call[i], procedure + 0x18 + i * 4); + memset(properties, 0, ANE_H16_PROPERTIES_SIZE); + put_unaligned_le32(1, properties); + put_unaligned_le32(hwx->tasks, properties + 0xc); + put_unaligned_le64(hwx->text.size, properties + 0x20); +} +EXPORT_SYMBOL_GPL(ane_h16_fixed_sections); + +int ane_h16_fixed_sections_validate(const struct ane_h16_hwx *hwx, + const void *const aux[ANE_H16_AUX_COUNT], + const size_t aux_size[ANE_H16_AUX_COUNT]) +{ + u8 procedure[ANE_H16_PROCEDURE_SIZE], properties[ANE_H16_PROPERTIES_SIZE]; + + if (!hwx || !aux || !aux_size || !aux[ANE_H16_AUX_PROCEDURE] || + !aux[ANE_H16_AUX_TEXT_PROPERTIES]) + return -EINVAL; + ane_h16_fixed_sections(hwx, procedure, properties); + if (aux_size[ANE_H16_AUX_PROCEDURE] != sizeof(procedure) || + aux_size[ANE_H16_AUX_TEXT_PROPERTIES] != sizeof(properties) || + memcmp(aux[ANE_H16_AUX_PROCEDURE], procedure, sizeof(procedure)) || + memcmp(aux[ANE_H16_AUX_TEXT_PROPERTIES], properties, sizeof(properties))) + return -ENOEXEC; + return 0; +} +EXPORT_SYMBOL_GPL(ane_h16_fixed_sections_validate); + /* * The mcache custom-BAR records come from the program descriptor relocation * tuples pinned by the HWX validator. The linear 0x8a0 form has one prefetch @@ -448,12 +542,35 @@ int ane_h16_custom_bars(const struct ane_h16_hwx_snapshot *snapshot, ret = ane_h16_hwx_snapshot_check(snapshot); if (ret) return ret; - if (!hwx->program_offset || snapshot->size < 0x8a0 || - hwx->program_offset > snapshot->size - 0x8a0) + if (!hwx->program_offset || snapshot->size < 0x890 || + hwx->program_offset > snapshot->size - 0x890) return -ENOEXEC; c = (const u8 *)snapshot->bytes + hwx->program_offset; *count = 0; length = get_unaligned_le32(c + 4); + if (length == 0x890) + return 0; + if (length == 0x8b0) { + if (snapshot->size < 0x8b0 || hwx->program_offset > snapshot->size - 0x8b0) + return -ENOEXEC; + bar = get_unaligned_le16(c + 0x890); + offset = c[0x893]; + width = c[0x894]; + if (!width || width > 16 || offset > 64 - width || dsid >= BIT(width)) + return -ENOEXEC; + bars[0] = (struct ane_h16_custom_bar) { + .configuration = 1, + .value_type = 1, + .bar = bar, + .bit_offset = offset, + .bit_width = width, + .value = dsid, + }; + *count = 1; + return 0; + } + if (snapshot->size < 0x8a0 || hwx->program_offset > snapshot->size - 0x8a0) + return -ENOEXEC; bar = get_unaligned_le32(c + 0x868); offset = get_unaligned_le32(c + 0x878); width = get_unaligned_le32(c + 0x87c); @@ -532,6 +649,8 @@ static int h16_session_init(struct ane_h16_session *s, struct ane_fw_transport * INIT_LIST_HEAD(&s->programs); INIT_LIST_HEAD(&s->held); spin_lock_init(&s->stats_lock); + ane_stats_counters_init(&s->sysfs_ctrs, &s->sysfs_ring, 0); + s->sysfs_ring.slots = &s->sysfs_slot; INIT_DELAYED_WORK(&s->gate_work, h16_gate_work); spin_lock_init(&s->export_lock); INIT_LIST_HEAD(&s->exports_done); @@ -563,7 +682,7 @@ static int h16_fail(struct ane_h16_session *s, int error) if (!s->error) s->error = error; if (!s->quarantined) { - s->quarantined = true; + WRITE_ONCE(s->quarantined, true); ane_h16_pending_fail_all(&s->pending, s->error); wake_up_all(&s->wake); s->ops->log(s->ctx, "program quarantine", (u64)-s->error, 0); @@ -631,6 +750,36 @@ static int h16_pool_room(struct ane_h16_session *s, const size_t *lengths, return 0; } +/* + * Every CREATE makes the firmware ask for a 2 MiB EXPP process pool by + * SHAREDMALLOC and wait for it before it answers; a pool it could not get + * leaves the CREATE stalled and the engine quarantined, and with it every + * other program of the session. Take the pool before LOAD instead + * (ane_fw_transport_shared_reserve()), so that without memory or quota the + * LOAD fails cleanly, before any traffic. A FREE of a torn-down program's + * pool may still be posted (it can come after the post-UNLOAD settle): + * serve it and try once more before giving up. + */ +static int h16_process_pool(struct ane_h16_session *s) +{ + int ret = ane_fw_transport_shared_reserve(s->transport, SZ_2M, ANE_FW_SHARED_EXPP); + + if (ret == -ENOSPC) { + ret = ane_fw_transport_settle(s->transport, s->settle_ns, + max(s->settle_ns, ANE_H16_SETTLE_LIMIT_NS)); + if (ret < 0) + return h16_fail(s, ret); + ret = ane_fw_transport_shared_reserve(s->transport, SZ_2M, + ANE_FW_SHARED_EXPP); + } + if (ret && s->transport->error) + return h16_fail(s, ret); + if (ret) + s->ops->log(s->ctx, "LOAD: no process pool", (u64)-ret, + s->transport->shared_bytes); + return ret; +} + /* * Outside a request batch, the commands published since mark were all * acknowledged and the firmware keeps no pointer into them: give their @@ -872,8 +1021,14 @@ EXPORT_SYMBOL_GPL(ane_h16_export_get); /* * Drop a reference. The last one returns a released surface to the spares - * from a work item: a mapping's last put runs under the process mmap lock, - * which an EXECUTE may wait for while holding the node lock. + * from a work item, because the spares need the node lock and the last put + * can come from two places that cannot take it: h16_give_back(), which + * already holds it, and a mapping's close in munmap() or process exit, which + * would then wait under the process mmap lock for a running request to end. + * Taking the node lock under the mmap lock is the order ane_h16_mmap() uses; + * the order that must not happen is the reverse, so nothing that faults user + * memory or takes the mmap lock runs under the node lock (EXECUTE pins or + * bounces its buffers before taking it). */ void ane_h16_export_put(struct ane_h16_export *e) { @@ -947,9 +1102,11 @@ static int h16_program_bind(const struct ane_h16_program *p, { int ret; - ret = ane_h16_process_bindings(&p->hwx, aux[ANE_H16_AUX_GENERIC], - aux_size[ANE_H16_AUX_GENERIC], b->bindings, - &b->count, &b->scratch); + ret = ane_h16_fixed_sections_validate(&p->hwx, aux, aux_size); + if (!ret) + ret = ane_h16_process_bindings(&p->hwx, aux[ANE_H16_AUX_GENERIC], + aux_size[ANE_H16_AUX_GENERIC], b->bindings, + &b->count, &b->scratch); if (!ret) ret = ane_h16_operation_validate(&p->snapshot, &p->hwx, aux[ANE_H16_AUX_OPERATION], @@ -1101,6 +1258,9 @@ int ane_h16_session_load(struct ane_h16_session *s, if (ret) return ret; ret = h16_load_room(s); + if (ret) + return ret; + ret = h16_process_pool(s); if (ret) return ret; p = kzalloc_obj(*p); @@ -1479,6 +1639,19 @@ static int h16_execute_room(struct ane_h16_session *s, struct ane_h16_program *p * barrier before the caller reads outputs. Any uncertain outcome quarantines * the session and keeps every mapping. */ +/* + * A request counts in ane_stats from its first firmware traffic (the opening + * gate, or the EXECUTE itself when the gate is already open) until it ends + * either way. A refusal or local failure before that point reached nothing. + */ +static void h16_count_begin(struct ane_h16_session *s, bool *counted, u64 *ticket) +{ + if (*counted) + return; + *ticket = ane_stats_begin(&s->sysfs_ctrs, &s->sysfs_ring, ktime_get_ns(), 1); + *counted = true; +} + static int h16_execute(struct ane_h16_session *s, struct ane_h16_program *p) { struct ane_h16_execute_buffer buffers[ANE_H16_SURFACES + 1]; @@ -1493,6 +1666,8 @@ static int h16_execute(struct ane_h16_session *s, struct ane_h16_program *p) unsigned int i; u64 deadline, polls, t0, gate_open, t1 = 0, t2 = 0, t3, end; u64 entry = h16_now(s); + bool counted = false; + u64 ticket = 0; int ret; if (!s || !p || p->session != s) @@ -1539,6 +1714,7 @@ static int h16_execute(struct ane_h16_session *s, struct ane_h16_program *p) trace->step = H16_STEP_GATE_OPEN; t0 = h16_now(s); if (!s->gate_held) { + h16_count_begin(s, &counted, &ticket); ret = h16_gate(s, 0); if (ret) goto fail; @@ -1573,6 +1749,8 @@ static int h16_execute(struct ane_h16_session *s, struct ane_h16_program *p) ANE_FW_DATA_CHAIN); if (!ret) { trace->step = H16_STEP_SEND; + /* With the gate already open, the request itself is the first traffic. */ + h16_count_begin(s, &counted, &ticket); t1 = h16_now(s); ret = h16_send(s, ANE_FW_DATA_CHAIN, command, length, &reply); } @@ -1614,8 +1792,11 @@ static int h16_execute(struct ane_h16_session *s, struct ane_h16_program *p) x->polls = s->transport->polls - polls; kfree(command); x->ns[ANE_H16_T_FINISH] = h16_now(s) - end; + ane_stats_complete(&s->sysfs_ctrs, &s->sysfs_ring, ticket, ktime_get_ns(), 0, 0); return 0; fail: + if (counted) + ane_stats_complete(&s->sysfs_ctrs, &s->sysfs_ring, ticket, ktime_get_ns(), ret, 0); s->ops->log(s->ctx, "EXECUTE failed", (u64)-ret, request->key.uuid); /* * Step 1 opening gate, 2 channel-7 ack, 3 report wait, 4 closing gate. @@ -2045,7 +2226,7 @@ void ane_h16_session_recovered(struct ane_h16_session *s) { struct ane_h16_program *p, *n; - s->quarantined = false; + WRITE_ONCE(s->quarantined, false); s->pending.quarantined = false; s->pending.error = 0; s->error = 0; @@ -2074,6 +2255,9 @@ static int h16_replay(struct ane_h16_session *s, struct ane_h16_program *p) unsigned int i; int ret; + ret = h16_process_pool(s); + if (ret) + return ret; command = kzalloc(ANE_H16_CREATE_SIZE, GFP_KERNEL); if (!command) return -ENOMEM; @@ -2137,7 +2321,7 @@ int ane_h16_session_replay(struct ane_h16_session *s, unsigned int *replayed, ret = h16_replay(s, p); if (ret) { s->ops->log(s->ctx, "PROGRAM REPLAY FAILED", p->key.program, (u64)-ret); - return ret; + return h16_fail(s, ret); } if (!(*replayed)++) *first_ns = h16_now(s); diff --git a/drivers/accel/ane/ane_h16_program.h b/drivers/accel/ane/ane_h16_program.h index bb30d3dce8c20d..914f3a8d45bdf7 100644 --- a/drivers/accel/ane/ane_h16_program.h +++ b/drivers/accel/ane/ane_h16_program.h @@ -11,6 +11,7 @@ #include "ane_fw_transport.h" #include "ane_h16_load.h" #include "ane_h16_pending.h" +#include "ane_stats.h" /* * Program lifecycle for one H16 firmware session: LOAD_PROGRAM, CREATE_PROCESS, @@ -53,6 +54,8 @@ #define ANE_H16_GENERIC_HEADER 0x208 #define ANE_H16_GENERIC_ENTRY 0x30 #define ANE_H16_GENERIC_ID_MAX 0x3c +/* The u32 at +0x28 of every entry, as every host builder writes it. */ +#define ANE_H16_GENERIC_ENTRY_TAIL 0xffff /* Host-built operation section: a count, then fixed-size BAR records. */ #define ANE_H16_OPERATION_RECORD 0x40c @@ -71,6 +74,10 @@ enum ane_h16_aux { #define ANE_H16_AUX_MIN 0x28 #define ANE_H16_AUX_MAX SZ_64K +/* The one form of the procedure and text-properties sections. */ +#define ANE_H16_PROCEDURE_SIZE 0x38 +#define ANE_H16_PROPERTIES_SIZE 0x28 + /* Source of one LOAD slot. */ enum ane_h16_slot_source { ANE_H16_SLOT_EMPTY, @@ -155,6 +162,12 @@ int ane_h16_operation_validate(const struct ane_h16_hwx_snapshot *snapshot, const struct ane_h16_process_binding *bindings, unsigned int count, const struct ane_h16_process_binding *scratch); +void ane_h16_fixed_sections(const struct ane_h16_hwx *hwx, + u8 procedure[ANE_H16_PROCEDURE_SIZE], + u8 properties[ANE_H16_PROPERTIES_SIZE]); +int ane_h16_fixed_sections_validate(const struct ane_h16_hwx *hwx, + const void *const aux[ANE_H16_AUX_COUNT], + const size_t aux_size[ANE_H16_AUX_COUNT]); int ane_h16_custom_bars(const struct ane_h16_hwx_snapshot *snapshot, const struct ane_h16_hwx *hwx, u32 dsid, struct ane_h16_custom_bar *bars, unsigned int *count); @@ -402,6 +415,14 @@ struct ane_h16_session { /* Accounted EXECUTEs; the lock lets a reader snapshot them. */ spinlock_t stats_lock; struct ane_h16_exec_stats stats; + /* + * The sysfs ane_stats counters: every request published to the + * firmware, failed ones included, and the union of their busy time. + * Unlike stats, they never reset. One ring slot: no timeline is kept. + */ + struct ane_stats_counters sysfs_ctrs; + struct ane_stats_ring sysfs_ring; + struct ane_stats_ring_entry sysfs_slot; /* Exports whose last mapping is gone, returned by export_work. */ spinlock_t export_lock; struct list_head exports_done; diff --git a/drivers/accel/ane/ane_h16_program_test.c b/drivers/accel/ane/ane_h16_program_test.c index a72ee6616f8d7a..302b88299d3bc9 100644 --- a/drivers/accel/ane/ane_h16_program_test.c +++ b/drivers/accel/ane/ane_h16_program_test.c @@ -16,6 +16,8 @@ #define FW_IPC_DVA 0x100003d0000ULL #define FW_POOL_DVA 0x10000384000ULL #define FW_MAP_DVA 0x10001f00000ULL +/* Shared (SHAREDMALLOC) allocations, far above the program mappings. */ +#define FW_SHARED_DVA 0x10010000000ULL #define FW_RING_SLOTS 8 #define FW_REPORTS 0x8000 @@ -80,6 +82,9 @@ struct prog_fw { /* ops->hung calls and the error of the last one. */ unsigned int hung; int hung_error; + /* ops->wake calls and replayed programs during runtime-PM unpark tests. */ + unsigned int wakes; + unsigned int wake_replayed; /* * Bytes mapped and not unmapped, ops->unmap calls, the most bytes a * nonzero window lets be mapped at once (-ENOSPC beyond), and the @@ -87,6 +92,22 @@ struct prog_fw { */ u64 live, window; unsigned int unmaps, map_fail_at; + /* + * SHAREDMALLOC: with expp, CREATE asks for a 2 MiB EXPP pool and is + * answered only once the host served it, and UNLOAD frees the pool + * again, as the H16/H17 firmware does. irq holds the pending + * notification bits; allocs counts ops->alloc calls, alloc_fail + * makes them fail with -ENOMEM. + */ + bool expp, alloc_fail; + u32 irq; + u64 shared_dva; + unsigned int allocs; + /* The CREATE waiting for its pool, by IO slot; its program ID. */ + u8 *create_slot; + u64 create_length, create_dva; + u32 create_program; + u64 expp_dva[32]; }; static u64 fw_load(void *ctx, const void *p) @@ -105,7 +126,9 @@ static void fw_barrier(void *ctx) static u32 fw_read32(void *ctx, u32 reg) { - return 0; + struct prog_fw *f = ctx; + + return reg == f->soc.irq_status ? f->irq : 0; } static u8 *fw_slot(struct prog_fw *f, unsigned int ch) @@ -118,6 +141,17 @@ static void fw_advance(struct prog_fw *f, unsigned int ch) f->head[ch] = (f->head[ch] + 1) % f->t.channels[ch].slots; } +/* A SHAREDMALLOC request in the firmware's next slot, notified. */ +static void fw_shared_post(struct prog_fw *f, u64 word0, u64 bytes, u64 tag) +{ + u8 *slot = fw_slot(f, ANE_FW_SHAREDMALLOC); + + put_unaligned_le64(bytes, slot + 8); + put_unaligned_le64(tag, slot + 16); + put_unaligned_le64(word0, slot); + f->irq |= BIT(ANE_FW_SHAREDMALLOC); +} + static void fw_report(struct prog_fw *f, u64 uuid, u32 program, u32 process, u32 state) { u32 offset = FW_REPORTS + (f->reports++ % 16) * 0x60; @@ -232,8 +266,16 @@ static void fw_command(struct prog_fw *f, unsigned int ch) cmd + ANE_H16_LOAD_ID_OFFSET); break; case ANE_H16_UNLOAD_PROGRAM: - if (get_unaligned_le32(cmd + 8) - f->program < 32) - f->programs_live &= ~BIT(get_unaligned_le32(cmd + 8) - f->program); + if (get_unaligned_le32(cmd + 8) - f->program < 32) { + u32 i = get_unaligned_le32(cmd + 8) - f->program; + + f->programs_live &= ~BIT(i); + /* The pool comes back by FREE, after the UNLOAD reply. */ + if (f->expp && f->expp_dva[i]) { + fw_shared_post(f, f->expp_dva[i], 0, 0); + f->expp_dva[i] = 0; + } + } break; case ANE_H16_TERMINATE_PROCESS: if (get_unaligned_le32(cmd + 0xc) - f->process < 32) @@ -244,6 +286,16 @@ static void fw_command(struct prog_fw *f, unsigned int ch) put_unaligned_le32(fw_take_id(&f->processes_live, f->process), cmd + 0xc); if (f->mode == FW_CREATE_BODY) cmd[0x100] = 1; + if (f->expp) { + /* No reply until the host served the process pool. */ + f->create_slot = slot; + f->create_length = length; + f->create_dva = dva; + f->create_program = get_unaligned_le32(cmd + 8); + fw_shared_post(f, 0, SZ_2M, ANE_FW_SHARED_EXPP); + fw_advance(f, ch); + return; + } break; case ANE_H16_EXECUTE: f->exec_length = min_t(size_t, length, sizeof(f->exec)); @@ -258,12 +310,35 @@ static void fw_command(struct prog_fw *f, unsigned int ch) fw_execute(f, cmd); } +/* The host answered the SHAREDMALLOC slot; a CREATE waiting for it completes. */ +static void fw_shared_answered(struct prog_fw *f) +{ + u8 *slot = fw_slot(f, ANE_FW_SHAREDMALLOC); + u64 word0 = get_unaligned_le64(slot); + + if (!(word0 & 1)) + return; + fw_advance(f, ANE_FW_SHAREDMALLOC); + if (word0 == 1 || !f->create_slot) + return; + if (f->create_program - f->program < 32) + f->expp_dva[f->create_program - f->program] = word0 & ~1ULL; + put_unaligned_le64(f->create_length, f->create_slot + 8); + put_unaligned_le64(0, f->create_slot + 16); + put_unaligned_le64(f->create_dva | 1, f->create_slot); + f->create_slot = NULL; +} + static void fw_write32(void *ctx, u32 reg, u32 value) { struct prog_fw *f = ctx; + if (reg == f->soc.irq_ack) + f->irq &= ~value; if (reg != f->soc.doorbell) return; + if (value & BIT(ANE_FW_SHAREDMALLOC)) + fw_shared_answered(f); /* Commands take doorbell_ns to answer; returning report slots is free. */ if (value & (BIT(ANE_FW_IO) | BIT(ANE_FW_DATA_CHAIN))) f->now += f->doorbell_ns; @@ -294,9 +369,22 @@ static void fw_relax(void *ctx, u64 waited_ns) } } +static void *fw_zalloc(struct kunit *test, size_t size); + static int fw_alloc(void *ctx, size_t size, u32 tag, struct ane_fw_surface *s) { - return -ENOMEM; + struct prog_fw *f = ctx; + + f->allocs++; + if (f->alloc_fail) + return -ENOMEM; + *s = (struct ane_fw_surface) { + .cpu = fw_zalloc(f->test, size), .dva = f->shared_dva, .size = size, + }; + if (!s->cpu) + return -ENOMEM; + f->shared_dva += size; + return 0; } static void fw_refused(void *ctx, u64 w0, u64 w1, u64 w2, int error) @@ -481,6 +569,7 @@ static struct prog_fw *fw_create_family(struct kunit *test, unsigned int family) put_unaligned_le64(f->ipc.dva + 0x800 + i * 0x200, p + 0x50); } f->next_dva = FW_MAP_DVA; + f->shared_dva = FW_SHARED_DVA; f->program = 0x11; f->process = 0; if (ane_fw_transport_init(&f->t, &f->soc, &fw_ops, f, f->ipc, f->pool, SZ_16K, @@ -589,6 +678,15 @@ static size_t test_aux_size[ANE_H16_AUX_COUNT] = { 0x298, 0x410, 0x38, 0x28 }; #define TEST_GENERIC_BASE 8 +/* The procedure and text-properties sections a host builder writes for hwx. */ +static void fixed_fill(const struct ane_h16_hwx *hwx) +{ + ane_h16_fixed_sections(hwx, test_aux[ANE_H16_AUX_PROCEDURE], + test_aux[ANE_H16_AUX_TEXT_PROPERTIES]); + test_aux_size[ANE_H16_AUX_PROCEDURE] = ANE_H16_PROCEDURE_SIZE; + test_aux_size[ANE_H16_AUX_TEXT_PROPERTIES] = ANE_H16_PROPERTIES_SIZE; +} + static int fw_load_snapshot(struct prog_fw *f, struct ane_h16_hwx_snapshot *snapshot, struct ane_h16_program **p) { @@ -601,6 +699,7 @@ static int fw_load_snapshot(struct prog_fw *f, struct ane_h16_hwx_snapshot *snap test_aux_size[ANE_H16_AUX_OPERATION] = operation_fill(test_aux[ANE_H16_AUX_OPERATION], snapshot, &hwx, TEST_GENERIC_BASE); + fixed_fill(&hwx); return ane_h16_session_load(&f->s, snapshot, test_aux_ptr, test_aux_size, p); } @@ -1245,6 +1344,7 @@ static void program_scratch_test(struct kunit *test) put_unaligned_le32(TEST_GENERIC_BASE + 2, e + 4); test_aux_size[ANE_H16_AUX_GENERIC] = size; + fixed_fill(hwx); KUNIT_ASSERT_EQ(test, ane_h16_session_load(&f->s, snapshot, test_aux_ptr, test_aux_size, &p), 0); KUNIT_ASSERT_TRUE(test, p->has_scratch); @@ -1325,6 +1425,7 @@ static void program_bad_operation_test(struct kunit *test) test_aux_size[ANE_H16_AUX_OPERATION] = operation_fill(test_aux[ANE_H16_AUX_OPERATION], snapshot, &hwx, TEST_GENERIC_BASE); + fixed_fill(&hwx); /* One record more than the section carries. */ put_unaligned_le32(get_unaligned_le32(test_aux[ANE_H16_AUX_OPERATION]) + 1, test_aux[ANE_H16_AUX_OPERATION]); @@ -1400,6 +1501,68 @@ static void program_stall_trace_test(struct kunit *test) KUNIT_EXPECT_EQ(test, f->fail_other, 2); } +/* + * The sysfs ane_stats counters take every request that reached the firmware, + * a failed one too, but not one refused before it: a client retrying on a + * quarantined engine does not inflate them. Resetting the debugfs statistics + * leaves them alone, and nothing stays in flight after either outcome. + */ +static void program_sysfs_stats_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL; + u64 busy; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p), 0); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 0LL); + KUNIT_EXPECT_EQ(test, ane_stats_snapshot(&f->s.sysfs_ctrs), 0ULL); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 1LL); + KUNIT_EXPECT_EQ(test, atomic_read(&f->s.sysfs_ctrs.inflight), 0); + busy = ane_stats_snapshot(&f->s.sysfs_ctrs); + ane_h16_session_stats(&f->s, NULL, true); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 1LL); + + f->mode = FW_REPORT_STALL; + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, p), -ETIMEDOUT); + KUNIT_EXPECT_TRUE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 2LL); + KUNIT_EXPECT_EQ(test, atomic_read(&f->s.sysfs_ctrs.inflight), 0); + KUNIT_EXPECT_GE(test, ane_stats_snapshot(&f->s.sysfs_ctrs), busy); + + f->mode = FW_OK; + KUNIT_EXPECT_LT(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 2LL); + KUNIT_EXPECT_EQ(test, atomic_read(&f->s.sysfs_ctrs.inflight), 0); +} + +/* + * With the gate held open by earlier requests, the EXECUTE is the request's + * first firmware traffic: a request that fails locally before it went out + * (here no UUID is left for its pending entry) sent nothing and does not + * count in ane_stats. + */ +static void program_sysfs_stats_held_gate_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL; + unsigned int sent; + + KUNIT_ASSERT_NOT_NULL(test, f); + f->s.gate_hold_ns = 1000; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p), 0); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_ASSERT_TRUE(test, f->s.gate_held); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 1LL); + f->s.pending.next_uuid = U64_MAX; + sent = f->count; + KUNIT_EXPECT_LT(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_EXPECT_EQ(test, f->count, sent); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 1LL); + KUNIT_EXPECT_EQ(test, atomic_read(&f->s.sysfs_ctrs.inflight), 0); +} + /* The phases of one EXECUTE add up, and only successful ones are accounted. */ static void program_timing_test(struct kunit *test) { @@ -1610,6 +1773,68 @@ static void program_pool_test(struct kunit *test) KUNIT_EXPECT_EQ(test, f->count, sent + 2); } +/* The add-128 source 1 base record: [0x4d10, 0x4d14], relocated on BAR slot 6. */ +#define ADD128_SRC1 (0x4d10 / 4 | 1 << 15 | BIT(29) | 6 << 23) + +/* + * Run the LOAD checks of the add-128 program with its source 1 base record + * header and offset replaced. The operation section binds x, y, z to slots + * 6, 7, 8; source 1 reads 128 rows of 0x100 bytes, all 32 KiB of x. + */ +static int add128_dma_load(struct kunit *test, u32 header, u64 offset) +{ + struct ane_h16_process_binding bindings[ANE_H16_SURFACES], scratch = {}; + struct ane_h16_hwx_snapshot *snapshot = kunit_kzalloc(test, sizeof(*snapshot), + GFP_KERNEL); + u8 *hwx = sparse_bytes(test, add128_hwx_runs, ARRAY_SIZE(add128_hwx_runs), + ADD128_HWX_SIZE); + u8 *generic = sparse_bytes(test, add128_generic_runs, ARRAY_SIZE(add128_generic_runs), + ADD128_GENERIC_SIZE); + u8 *operation = sparse_bytes(test, add128_operation_runs, + ARRAY_SIZE(add128_operation_runs), ADD128_OPERATION_SIZE); + unsigned int count; + size_t at; + int ret; + + if (!snapshot || !hwx || !generic || !operation) + return -ENOMEM; + for (at = 0; at + 12 <= ADD128_HWX_SIZE; at += 4) + if (get_unaligned_le32(hwx + at) == ADD128_SRC1) + break; + if (at + 12 > ADD128_HWX_SIZE) + return -ENOENT; + put_unaligned_le32(header, hwx + at); + put_unaligned_le64(offset, hwx + at + 4); + ret = ane_h16_hwx_snapshot_create(hwx, ADD128_HWX_SIZE, snapshot); + if (ret) + return ret; + ret = kunit_add_action_or_reset(test, snapshot_free, snapshot); + if (ret) + return ret; + ret = ane_h16_process_bindings(&snapshot->info, generic, ADD128_GENERIC_SIZE, bindings, + &count, &scratch); + if (!ret) + ret = ane_h16_operation_validate(snapshot, &snapshot->info, operation, + ADD128_OPERATION_SIZE, bindings, count, &scratch); + return ret; +} + +/* Each DMA base stays inside the buffer its slot binds, at LOAD and before any mapping. */ +static void program_add128_dma_test(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, add128_dma_load(test, ADD128_SRC1, 0), 0); + /* One 64-byte line past the end of x, into z's place, and before x. */ + KUNIT_EXPECT_EQ(test, add128_dma_load(test, ADD128_SRC1, 0x40), -ENOEXEC); + KUNIT_EXPECT_EQ(test, add128_dma_load(test, ADD128_SRC1, 0x10000), -ENOEXEC); + KUNIT_EXPECT_EQ(test, add128_dma_load(test, ADD128_SRC1, -0x8000), -ENOEXEC); + /* Slot 9, which the operation section does not bind. */ + KUNIT_EXPECT_EQ(test, add128_dma_load(test, (ADD128_SRC1 & ~(0x3f << 23)) | 9 << 23, 0), + -ENOEXEC); + /* The base without its relocation: an absolute DVA. */ + KUNIT_EXPECT_EQ(test, add128_dma_load(test, ADD128_SRC1 & ~(BIT(29) | 0x3f << 23), 0), + -ENOEXEC); +} + static u8 *fw_sparse_large(struct kunit *test, const struct ane_h16_sparse_run *runs, unsigned int count, size_t size) { @@ -1657,6 +1882,147 @@ static void mobilenet_sections(struct kunit *test, const void *aux[ANE_H16_AUX_C ARRAY_SIZE(mobilenet_properties_runs), aux_size[3]); } +/* + * Every byte of the four host-built sections has its one value. The add128 + * and mobilenet fixtures' sections from h16-sections.py are the kernel's + * procedure and text properties, and any other procedure, text framing or + * nonzero reserved byte is refused at LOAD, before anything is mapped or sent. + */ +static void program_sections_exact_test(struct kunit *test) +{ + struct ane_h16_process_binding bindings[ANE_H16_SURFACES], scratch = {}; + struct ane_h16_hwx_snapshot *snapshot = kunit_kzalloc(test, sizeof(*snapshot), + GFP_KERNEL); + size_t aux_size[ANE_H16_AUX_COUNT] = { + ADD128_GENERIC_SIZE, ADD128_OPERATION_SIZE, + ADD128_PROCEDURE_SIZE, ADD128_PROPERTIES_SIZE, + }; + static const size_t generic_bytes[] = { 0x8, 0x100, 0x203 }; + static const size_t entry_bytes[] = { 0xc, 0x14, 0x1f, 0x28, 0x2c }; + const void *mobilenet[ANE_H16_AUX_COUNT]; + size_t mobilenet_size[ANE_H16_AUX_COUNT]; + struct ane_h16_hwx_snapshot *m = mobilenet_snapshot(test); + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL; + void *aux[ANE_H16_AUX_COUNT]; + u8 *hwx, *g, *o, *pr, *tp; + unsigned int i, count; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, snapshot); + KUNIT_ASSERT_NOT_NULL(test, m); + hwx = sparse_bytes(test, add128_hwx_runs, ARRAY_SIZE(add128_hwx_runs), ADD128_HWX_SIZE); + g = sparse_bytes(test, add128_generic_runs, ARRAY_SIZE(add128_generic_runs), + ADD128_GENERIC_SIZE); + o = sparse_bytes(test, add128_operation_runs, ARRAY_SIZE(add128_operation_runs), + ADD128_OPERATION_SIZE); + pr = sparse_bytes(test, add128_procedure_runs, ARRAY_SIZE(add128_procedure_runs), + ADD128_PROCEDURE_SIZE); + tp = sparse_bytes(test, add128_properties_runs, ARRAY_SIZE(add128_properties_runs), + ADD128_PROPERTIES_SIZE); + aux[0] = g; + aux[1] = o; + aux[2] = pr; + aux[3] = tp; + KUNIT_ASSERT_NOT_NULL(test, hwx); + for (i = 0; i < ANE_H16_AUX_COUNT; i++) + KUNIT_ASSERT_NOT_NULL(test, aux[i]); + KUNIT_ASSERT_EQ(test, ane_h16_hwx_snapshot_create(hwx, ADD128_HWX_SIZE, snapshot), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, snapshot_free, snapshot), 0); + + /* What the builder wrote is the kernel's form, for one task and for 28. */ + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), 0); + mobilenet_sections(test, mobilenet, mobilenet_size); + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&m->info, mobilenet, + mobilenet_size), 0); + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&m->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + + /* Another task count, segment offset or size, or a longer section. */ + put_unaligned_le32(2, tp + 0xc); + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + put_unaligned_le32(1, tp + 0xc); + put_unaligned_le64(0x10, tp + 0x10); + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + put_unaligned_le64(0, tp + 0x10); + put_unaligned_le64(0x120, tp + 0x20); + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + put_unaligned_le64(0x130, tp + 0x20); + aux_size[3] = ADD128_PROPERTIES_SIZE + 4; + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + aux_size[3] = ADD128_PROPERTIES_SIZE; + /* A second procedure, or another word of the one there is. */ + put_unaligned_le32(2, pr); + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + put_unaligned_le32(1, pr); + pr[0x34] = 5; + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + pr[0x34] = 4; + + /* Reserved generic bytes: in the header and in every field of an entry. */ + KUNIT_ASSERT_EQ(test, ane_h16_process_bindings(&snapshot->info, g, ADD128_GENERIC_SIZE, + bindings, &count, &scratch), 0); + for (i = 0; i < ARRAY_SIZE(generic_bytes); i++) { + g[generic_bytes[i]] ^= 1; + KUNIT_EXPECT_EQ(test, ane_h16_process_bindings(&snapshot->info, g, + ADD128_GENERIC_SIZE, bindings, + &count, &scratch), -ENOEXEC); + g[generic_bytes[i]] ^= 1; + } + for (i = 0; i < ARRAY_SIZE(entry_bytes); i++) { + u8 *e = g + ANE_H16_GENERIC_HEADER + 2 * ANE_H16_GENERIC_ENTRY + entry_bytes[i]; + + *e ^= 1; + KUNIT_EXPECT_EQ(test, ane_h16_process_bindings(&snapshot->info, g, + ADD128_GENERIC_SIZE, bindings, + &count, &scratch), -ENOEXEC); + *e ^= 1; + } + KUNIT_ASSERT_EQ(test, ane_h16_process_bindings(&snapshot->info, g, ADD128_GENERIC_SIZE, + bindings, &count, &scratch), 0); + /* An operation record's bytes after its last reference. */ + KUNIT_EXPECT_EQ(test, ane_h16_operation_validate(snapshot, &snapshot->info, o, + ADD128_OPERATION_SIZE, bindings, count, + &scratch), 0); + o[4 + 0xc + 3 * 8] = 7; + KUNIT_EXPECT_EQ(test, ane_h16_operation_validate(snapshot, &snapshot->info, o, + ADD128_OPERATION_SIZE, bindings, count, + &scratch), -ENOEXEC); + o[4 + 0xc + 3 * 8] = 0; + o[ADD128_OPERATION_SIZE - 1] = 1; + KUNIT_EXPECT_EQ(test, ane_h16_operation_validate(snapshot, &snapshot->info, o, + ADD128_OPERATION_SIZE, bindings, count, + &scratch), -ENOEXEC); + o[ADD128_OPERATION_SIZE - 1] = 0; + + /* At LOAD: refused before any mapping or firmware traffic, then loads. */ + put_unaligned_le32(2, tp + 0xc); + KUNIT_EXPECT_EQ(test, ane_h16_session_load(&f->s, snapshot, (const void *const *)aux, + aux_size, &p), -ENOEXEC); + KUNIT_EXPECT_PTR_EQ(test, p, NULL); + KUNIT_EXPECT_EQ(test, f->count, 0); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + put_unaligned_le32(1, tp + 0xc); + KUNIT_ASSERT_EQ(test, ane_h16_session_load(&f->s, snapshot, (const void *const *)aux, + aux_size, &p), 0); + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, p), 0); +} + /* * The H17 MobileNetV1 HWX is one linked program: 28 tasks, input x and * output y as surfaces, the 3.5 MiB __DATA scratch on BAR slot 3 and the @@ -2142,6 +2508,66 @@ static void program_sleep_gate_test(struct kunit *test) mutex_unlock(lock); } +/* + * Closing the session for a park or a sleep releases a held gate. When that + * fails, the session is quarantined there and the backend told once, so a + * backend checks for the quarantine after closing (the H17 park and sleep + * do) and recovers it with a verified power cycle: the open program is + * replayed and runs again behind its handle. + */ +static void program_sleep_gate_quarantine_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL; + struct mutex *lock = kunit_kzalloc(test, sizeof(*lock), GFP_KERNEL); + unsigned int replayed; + u64 first; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, lock); + mutex_init(lock); + f->s.ops = &fw_session_ops_hung; + f->s.gate_hold_ns = 1000; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p), 0); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_ASSERT_TRUE(test, f->s.gate_held); + + /* + * The firmware takes nothing any more: the closing gate fails. The + * session lock is set only around the sleep gate, so no idle gate work + * outlives the test (as in program_gate_hold_test). + */ + f->t.armed = false; + f->s.lock = lock; + ane_h16_session_sleep(&f->s, true); + KUNIT_EXPECT_TRUE(test, f->s.asleep); + KUNIT_EXPECT_FALSE(test, f->s.gate_held); + KUNIT_EXPECT_TRUE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 1U); + /* Closed again while quarantined: no second report. */ + ane_h16_session_sleep(&f->s, false); + ane_h16_session_sleep(&f->s, true); + KUNIT_EXPECT_EQ(test, f->hung, 1U); + + /* Powered off, proven off, booted again from the preload. */ + f->t.armed = true; + fw_cold_boot(f); + ane_h16_session_restart(&f->s); + ane_h16_session_recovered(&f->s); + KUNIT_ASSERT_EQ(test, ane_h16_session_replay(&f->s, &replayed, &first), 0); + KUNIT_EXPECT_EQ(test, replayed, 1U); + ane_h16_session_sleep(&f->s, false); + f->s.lock = NULL; + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_EXPECT_EQ(test, f->hung, 1U); + f->now += 1000; + KUNIT_EXPECT_EQ(test, ane_h16_session_gate_expire(&f->s), 0); + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, p), 0); + ane_h16_session_put(&f->s, p); + cancel_delayed_work_sync(&f->s.gate_work); +} + /* A program survives a sleep: the same handle executes afterwards. */ static void program_sleep_keeps_program_test(struct kunit *test) { @@ -3355,6 +3781,471 @@ static void program_unmap_refused_load_test(struct kunit *test) KUNIT_EXPECT_EQ(test, fw_cycle(f), 0); } +/* A LOAD that comes in while the backend recovers the engine, as a client does. */ +struct recover_client { + struct prog_fw *f; + /* The session lock, kept here: the test clears f->s.lock before the end. */ + struct mutex *lock; + struct ane_h16_hwx_snapshot *snapshot; + struct ane_h16_program *program; + struct task_struct *task; + struct completion entered, done; + int enter, load; + /* Firmware commands seen when the request got in. */ + unsigned int sent_at_entry; +}; + +static int recover_client_run(void *arg) +{ + struct recover_client *c = arg; + struct ane_h16_session *s = &c->f->s; + + complete(&c->entered); + c->enter = ane_h16_session_enter(s, false); + if (!c->enter) { + c->sent_at_entry = c->f->count; + c->load = fw_load_snapshot(c->f, c->snapshot, &c->program); + mutex_unlock(s->lock); + } + complete(&c->done); + set_current_state(TASK_INTERRUPTIBLE); + while (!kthread_should_stop()) { + schedule(); + set_current_state(TASK_INTERRUPTIBLE); + } + __set_current_state(TASK_RUNNING); + return 0; +} + +/* Also after a failed assertion: let a waiting client in, then stop it. */ +static void recover_client_stop(void *arg) +{ + struct recover_client *c = arg; + struct ane_h16_session *s = &c->f->s; + + mutex_lock(c->lock); + s->asleep = false; + wake_up_all(&s->wake); + mutex_unlock(c->lock); + kthread_stop(c->task); + cancel_delayed_work_sync(&s->gate_work); +} + +/* + * What the H17 recovery relies on to keep requests off an engine that is + * not back yet. While a recovery waits out its backoff, the quarantined + * session refuses requests with -EIO and nothing reaches the firmware. + * While the recovery runs (session closed), a request waits in + * ane_h16_session_enter(): nothing is sent before the backend reopens the + * session, which it does only after the cold boot, the settle and the + * replay; then the request runs on the new firmware. + */ +static void program_recover_gate_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL, *q = NULL; + struct mutex *lock = kunit_kzalloc(test, sizeof(*lock), GFP_KERNEL); + struct recover_client *c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL); + unsigned int sent, replayed; + u64 first; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, lock); + KUNIT_ASSERT_NOT_NULL(test, c); + mutex_init(lock); + f->s.ops = &fw_session_ops_hung; + f->s.gate_hold_ns = 1000; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p), 0); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_ASSERT_TRUE(test, f->s.gate_held); + + /* The engine stops answering: quarantined, the backend told once. */ + f->t.armed = false; + f->s.lock = lock; + ane_h16_session_sleep(&f->s, true); + ane_h16_session_sleep(&f->s, false); + KUNIT_ASSERT_TRUE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 1U); + + /* Backoff: open but quarantined. Requests fail at once, with no traffic. */ + sent = f->count; + KUNIT_ASSERT_EQ(test, ane_h16_session_enter(&f->s, false), 0); + KUNIT_EXPECT_EQ(test, fw_load_program(f, &q), -EIO); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, p), -EIO); + mutex_unlock(lock); + KUNIT_EXPECT_EQ(test, f->count, sent); + KUNIT_EXPECT_NULL(test, q); + + /* The recovery closes the session; a client's LOAD comes in and waits. */ + ane_h16_session_sleep(&f->s, true); + c->f = f; + c->lock = lock; + c->snapshot = fw_snapshot(test, false, false); + KUNIT_ASSERT_NOT_NULL(test, c->snapshot); + init_completion(&c->entered); + init_completion(&c->done); + c->task = kthread_run(recover_client_run, c, "ane-recover-client"); + KUNIT_ASSERT_FALSE(test, IS_ERR(c->task)); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, recover_client_stop, c), 0); + KUNIT_ASSERT_TRUE(test, wait_for_completion_timeout(&c->entered, HZ) > 0); + KUNIT_EXPECT_EQ(test, ane_h16_session_enter(&f->s, true), -EAGAIN); + + /* Powered off, kept off, booted again: still closed, the client waits. */ + f->t.armed = true; + fw_cold_boot(f); + ane_h16_session_restart(&f->s); + ane_h16_session_recovered(&f->s); + KUNIT_EXPECT_EQ(test, wait_for_completion_timeout(&c->done, HZ / 10), 0UL); + /* The replay is the first traffic on the new firmware. */ + KUNIT_ASSERT_EQ(test, ane_h16_session_replay(&f->s, &replayed, &first), 0); + KUNIT_EXPECT_EQ(test, replayed, 1U); + KUNIT_EXPECT_EQ(test, wait_for_completion_timeout(&c->done, HZ / 10), 0UL); + sent = f->count; + + /* Settled: the backend reopens the session and the LOAD goes through. */ + ane_h16_session_sleep(&f->s, false); + KUNIT_ASSERT_TRUE(test, wait_for_completion_timeout(&c->done, 5 * HZ) > 0); + KUNIT_EXPECT_EQ(test, c->enter, 0); + KUNIT_EXPECT_EQ(test, c->sent_at_entry, sent); + KUNIT_EXPECT_EQ(test, c->load, 0); + KUNIT_EXPECT_GT(test, f->count, sent); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 1U); + + /* + * Both the replayed program and the new one run on the new firmware. + * The session lock is dropped first, so no idle gate work outlives + * the test (as in program_sleep_gate_quarantine_test). + */ + f->s.lock = NULL; + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + if (c->program) + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, c->program), 0); + f->now += 1000; + KUNIT_EXPECT_EQ(test, ane_h16_session_gate_expire(&f->s), 0); + if (c->program) { + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, c->program), 0); + ane_h16_session_put(&f->s, c->program); + } + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, p), 0); + ane_h16_session_put(&f->s, p); +} + +/* As the firmware does at boot: a small shared allocation of its own. */ +static void fw_boot_allocations(struct kunit *test, struct prog_fw *f) +{ + fw_shared_post(f, 0, SZ_16K, 0x43434d44); + KUNIT_ASSERT_EQ(test, ane_fw_transport_irq(&f->t, &(u32){ 0 }), 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared(&f->t), 0); +} + +/* + * Every live program holds a 2 MiB EXPP process pool, which the firmware + * asks for during CREATE and waits for. Six programs at once on the Neo + * went past the 12 MiB shared quota: the pool was refused, the CREATE + * stalled, and the quarantine took the five other programs with it. Now + * the LOAD past the quota fails with -ENOSPC before any traffic, the + * engine stays up, the other programs keep running, and a closed + * program's pool serves the next LOAD. + */ +static void program_process_pool_quota_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p[ANE_FW_SHARED_TOTAL / SZ_2M + 1] = {}, *q = NULL; + unsigned int i, n = 0, count, allocs; + int ret; + + KUNIT_ASSERT_NOT_NULL(test, f); + f->s.ops = &fw_session_ops_hung; + f->t.native_free = true; + f->expp = true; + fw_boot_allocations(test, f); + while (n < ARRAY_SIZE(p)) { + count = f->count; + ret = fw_load_program(f, &p[n]); + if (ret) + break; + KUNIT_EXPECT_EQ(test, f->count, count + 2); + n++; + } + /* 16 KiB of the quota is the firmware's: room for one pool less. */ + KUNIT_EXPECT_EQ(test, n, (unsigned int)(ANE_FW_SHARED_TOTAL / SZ_2M - 1)); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_PTR_EQ(test, p[n], NULL); + KUNIT_EXPECT_EQ(test, f->count, count); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 0U); + KUNIT_EXPECT_EQ(test, f->t.error, 0); + for (i = 0; i < n; i++) + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, p[i]), 0); + + /* The FREE after UNLOAD makes the pool serve the next LOAD. */ + allocs = f->allocs; + KUNIT_ASSERT_EQ(test, ane_h16_session_close(&f->s, p[0]), 0); + ane_h16_session_put(&f->s, p[0]); + KUNIT_ASSERT_EQ(test, fw_load_program(f, &q), 0); + KUNIT_EXPECT_EQ(test, f->allocs, allocs); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, q), 0); + KUNIT_ASSERT_EQ(test, ane_h16_session_close(&f->s, q), 0); + ane_h16_session_put(&f->s, q); + for (i = 1; i < n; i++) { + KUNIT_ASSERT_EQ(test, ane_h16_session_close(&f->s, p[i]), 0); + ane_h16_session_put(&f->s, p[i]); + } + /* Load and close cycles take no new pool. */ + for (i = 0; i < 20; i++) + KUNIT_ASSERT_EQ(test, fw_cycle(f), 0); + KUNIT_EXPECT_EQ(test, f->allocs, allocs); + KUNIT_EXPECT_EQ(test, f->hung, 0U); +} + +/* No memory for the pool: -ENOMEM before any traffic, and the next LOAD works. */ +static void program_process_pool_nomem_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *a = NULL, *b = NULL; + + KUNIT_ASSERT_NOT_NULL(test, f); + f->s.ops = &fw_session_ops_hung; + f->t.native_free = true; + f->expp = true; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &a), 0); + KUNIT_EXPECT_EQ(test, f->count, 2U); + f->alloc_fail = true; + KUNIT_EXPECT_EQ(test, fw_load_program(f, &b), -ENOMEM); + KUNIT_EXPECT_PTR_EQ(test, b, NULL); + KUNIT_EXPECT_EQ(test, f->count, 2U); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 0U); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, a), 0); + f->alloc_fail = false; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &b), 0); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, b), 0); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, a), 0); + KUNIT_EXPECT_EQ(test, f->t.shared_count, 2U); + KUNIT_EXPECT_EQ(test, f->hung, 0U); +} + +/* + * A FREE the firmware posts only after the post-UNLOAD settle: at the quota + * the LOAD serves it and takes that pool instead of failing. + */ +static void program_process_pool_late_free_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p[ANE_FW_SHARED_TOTAL / SZ_2M] = {}, *q = NULL; + unsigned int i, allocs; + + KUNIT_ASSERT_NOT_NULL(test, f); + f->s.ops = &fw_session_ops_hung; + f->t.native_free = true; + f->expp = true; + for (i = 0; i < ARRAY_SIZE(p); i++) + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p[i]), 0); + KUNIT_EXPECT_EQ(test, f->t.shared_bytes, (size_t)ANE_FW_SHARED_TOTAL); + /* Torn down, with the FREE held back past the settle. */ + f->expp = false; + KUNIT_ASSERT_EQ(test, ane_h16_session_close(&f->s, p[0]), 0); + ane_h16_session_put(&f->s, p[0]); + f->expp = true; + fw_shared_post(f, f->expp_dva[0], 0, 0); + f->expp_dva[0] = 0; + allocs = f->allocs; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &q), 0); + KUNIT_EXPECT_EQ(test, f->allocs, allocs); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, q), 0); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 0U); +} + +/* + * A replay that cannot take its process pool (no memory) fails, and the + * session is quarantined as for any other failed replay. + */ +static void program_process_pool_replay_nomem_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL; + struct mutex *lock = kunit_kzalloc(test, sizeof(*lock), GFP_KERNEL); + unsigned int replayed; + u64 first; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, lock); + mutex_init(lock); + f->s.ops = &fw_session_ops_hung; + f->t.native_free = true; + f->expp = true; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p), 0); + + f->s.lock = lock; + ane_h16_session_sleep(&f->s, true); + fw_cold_boot(f); + ane_h16_session_restart(&f->s); + ane_h16_session_recovered(&f->s); + f->alloc_fail = true; + KUNIT_EXPECT_EQ(test, ane_h16_session_replay(&f->s, &replayed, &first), -ENOMEM); + KUNIT_EXPECT_EQ(test, replayed, 0U); + KUNIT_EXPECT_TRUE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 1U); + f->alloc_fail = false; + ane_h16_session_sleep(&f->s, false); + f->s.lock = NULL; + cancel_delayed_work_sync(&f->s.gate_work); +} + +static void fw_cold_boot(struct prog_fw *f); + +static int fw_rpm_wake(void *ctx) +{ + struct prog_fw *f = ctx; + u64 first = 0; + int ret; + + if (!READ_ONCE(f->s.parked)) + return 0; + if (READ_ONCE(f->s.wake_blocked)) + return -EAGAIN; + f->wakes++; + fw_cold_boot(f); + ane_h16_session_restart(&f->s); + ret = ane_h16_session_replay(&f->s, &f->wake_replayed, &first); + WRITE_ONCE(f->s.parked, false); + ane_h16_session_sleep(&f->s, false); + return ret; +} + +static const struct ane_h16_session_ops fw_session_ops_rpm = { + .map = fw_map, + .unmap = fw_unmap, + .log = fw_log, + .busy = fw_busy, + .sync = fw_sync, + .wake = fw_rpm_wake, + .hung = fw_hung, +}; + +/* + * H16 runtime-PM idle park + wake/replay across repeat add128 runs: + * closing a program while parked defers teardown without unmapping, waking + * cold-boots and replays still-open programs behind their handles, releases + * deferred closes once back up, and runs repeat EXECUTEs with zero faults. + */ +static void program_rpm_park_wake_replay_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *a = NULL, *b = NULL; + struct mutex *lock = kunit_kzalloc(test, sizeof(*lock), GFP_KERNEL); + u8 *exec = kunit_kzalloc(test, sizeof(f->exec), GFP_KERNEL); + size_t exec_length; + unsigned int round; + u32 prog_id; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, lock); + KUNIT_ASSERT_NOT_NULL(test, exec); + mutex_init(lock); + f->s.lock = lock; + f->s.ops = &fw_session_ops_rpm; + f->strict = true; + + KUNIT_ASSERT_EQ(test, ane_h16_session_enter(&f->s, false), 0); + KUNIT_ASSERT_EQ(test, fw_load_program(f, &a), 0); + KUNIT_ASSERT_EQ(test, fw_load_program(f, &b), 0); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, a), 0); + mutex_unlock(lock); + memcpy(exec, f->exec, sizeof(f->exec)); + exec_length = f->exec_length; + KUNIT_EXPECT_EQ(test, f->busy_on, 1U); + KUNIT_EXPECT_EQ(test, f->busy_off, 1U); + KUNIT_EXPECT_EQ(test, f->busy_depth, 0); + + /* First park: close b while parked (deferred, no unmap while parked). */ + ane_h16_session_sleep(&f->s, true); + WRITE_ONCE(f->s.parked, true); + mutex_lock(lock); + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, b), -EINPROGRESS); + mutex_unlock(lock); + KUNIT_EXPECT_EQ(test, f->unmaps, 0U); + + /* Two park/wake cycles running the same add128 handle cleanly. */ + for (round = 1; round <= 2; round++) { + prog_id = a->key.program; + KUNIT_ASSERT_EQ(test, ane_h16_session_enter(&f->s, false), 0); + KUNIT_EXPECT_EQ(test, f->wakes, round); + KUNIT_EXPECT_EQ(test, f->wake_replayed, 1U); + KUNIT_EXPECT_FALSE(test, f->s.parked); + KUNIT_EXPECT_EQ(test, a->key.program, prog_id + 0x10); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, a), 0); + mutex_unlock(lock); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(f->exec + 0x30), + ANE_H16_EXECUTE_FLAG_QUEUED); + KUNIT_EXPECT_EQ(test, f->exec_length, exec_length); + KUNIT_EXPECT_EQ(test, memcmp(f->exec + 0x34, exec + 0x34, + exec_length - 0x34), 0); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + if (round == 1) { + ane_h16_session_sleep(&f->s, true); + WRITE_ONCE(f->s.parked, true); + } + } + + KUNIT_EXPECT_EQ(test, f->busy_on, 3U); + KUNIT_EXPECT_EQ(test, f->busy_off, 3U); + mutex_lock(lock); + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, a), 0); + mutex_unlock(lock); + ane_h16_session_put(&f->s, a); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); +} + +/* + * System sleep while already parked blocks ops->wake (-EAGAIN) without + * booting; after PM_POST_SUSPEND unblocks it, the next request wakes and + * replays the open program cleanly. + */ +static void program_rpm_s2r_while_parked_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL; + struct mutex *lock = kunit_kzalloc(test, sizeof(*lock), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, lock); + mutex_init(lock); + f->s.lock = lock; + f->s.ops = &fw_session_ops_rpm; + f->strict = true; + + KUNIT_ASSERT_EQ(test, ane_h16_session_enter(&f->s, false), 0); + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p), 0); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + mutex_unlock(lock); + + /* Idle park, then S2R starts while parked. */ + ane_h16_session_sleep(&f->s, true); + WRITE_ONCE(f->s.parked, true); + WRITE_ONCE(f->s.wake_blocked, true); + + /* O_NONBLOCK sees -EAGAIN and never wakes the engine during sleep. */ + KUNIT_EXPECT_EQ(test, ane_h16_session_enter(&f->s, true), -EAGAIN); + KUNIT_EXPECT_EQ(test, f->wakes, 0U); + KUNIT_EXPECT_TRUE(test, f->s.parked); + KUNIT_EXPECT_TRUE(test, f->s.asleep); + + /* PM_POST_SUSPEND unblocks wake; next request wakes and replays p. */ + WRITE_ONCE(f->s.wake_blocked, false); + wake_up_all(&f->s.wake); + KUNIT_ASSERT_EQ(test, ane_h16_session_enter(&f->s, false), 0); + KUNIT_EXPECT_EQ(test, f->wakes, 1U); + KUNIT_EXPECT_EQ(test, f->wake_replayed, 1U); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, p), 0); + mutex_unlock(lock); + ane_h16_session_put(&f->s, p); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); +} + static struct kunit_case program_cases[] = { KUNIT_CASE_SLOW(program_pool_rewind_test), KUNIT_CASE_SLOW(program_pool_resident_test), @@ -3383,6 +4274,10 @@ static struct kunit_case program_cases[] = { KUNIT_CASE(program_sleep_replay_failure_test), KUNIT_CASE(program_sleep_replay_deferred_test), KUNIT_CASE(program_sleep_gate_test), + KUNIT_CASE(program_sleep_gate_quarantine_test), + KUNIT_CASE(program_recover_gate_test), + KUNIT_CASE(program_rpm_park_wake_replay_test), + KUNIT_CASE(program_rpm_s2r_while_parked_test), KUNIT_CASE(program_sleep_keeps_program_test), KUNIT_CASE(program_sleep_restart_test), KUNIT_CASE(program_sleep_restart_deferred_test), @@ -3395,6 +4290,8 @@ static struct kunit_case program_cases[] = { KUNIT_CASE(program_add128_slots_test), KUNIT_CASE(program_kernel_slots_test), KUNIT_CASE(program_add128_hwx_test), + KUNIT_CASE(program_add128_dma_test), + KUNIT_CASE(program_sections_exact_test), KUNIT_CASE(program_replies_test), KUNIT_CASE(program_deny_list_test), KUNIT_CASE(program_custom_bar_test), @@ -3406,6 +4303,8 @@ static struct kunit_case program_cases[] = { KUNIT_CASE(program_bad_report_test), KUNIT_CASE(program_stall_trace_test), KUNIT_CASE(program_timing_test), + KUNIT_CASE(program_sysfs_stats_test), + KUNIT_CASE(program_sysfs_stats_held_gate_test), KUNIT_CASE(program_fwlog_line_test), KUNIT_CASE(program_shared_tag_test), KUNIT_CASE(program_pool_test), @@ -3415,6 +4314,10 @@ static struct kunit_case program_cases[] = { KUNIT_CASE(program_h17_sections_test), KUNIT_CASE(program_h17_mobilenet_test), KUNIT_CASE(program_h17_switch_test), + KUNIT_CASE(program_process_pool_quota_test), + KUNIT_CASE(program_process_pool_nomem_test), + KUNIT_CASE(program_process_pool_late_free_test), + KUNIT_CASE(program_process_pool_replay_nomem_test), {} }; diff --git a/drivers/accel/ane/ane_h16_tasks.h b/drivers/accel/ane/ane_h16_tasks.h index e96ff85d778abe..702e6f88893c3b 100644 --- a/drivers/accel/ane/ane_h16_tasks.h +++ b/drivers/accel/ane/ane_h16_tasks.h @@ -6,7 +6,10 @@ #include #include #include +#include +#include #include +#include #include #include #include @@ -33,60 +36,97 @@ static inline bool ane_h16_register_valid(u32 word) return false; } +/* Values after record header @h: a dense run, or one plus a scatter mask's bits. */ +static inline u32 ane_hx_record_count(u32 h) +{ + return h & BIT(31) ? 1 + hweight32((h >> 15) & 0xffff) : ((h >> 15) & 0x3f) + 1; +} + /* * A stream opens with a 16-byte frame: little-endian u32 @prologue, then - * twelve reserved zero bytes. H16 programs open with 1; measured H17 programs - * open with 0 or 1. The last task may end at the end of the section; - * every other task is padded with zeros to 16 bytes. This structural gate - * does not replace container/tensor/aperture validation. + * twelve reserved zero bytes. H15/H16/H17 programs share this framing with + * @header_words fixed words per task (8 on H15, 9 on H16 and H17, from the + * HWX target), the task's length in words in bits 16-26 of the first. Low + * bits 3 in the last fixed word add one more header word. The last task may + * end at the end of the section; every other task is padded with zeros to + * 16 bytes, and a 16-byte zero block may stand between tasks. + * + * ane_hx_task_frame() is the one walk of this framing: the structural gate, + * the relocation check of the HWX validator and the DMA bound all step + * through a stream with it, so they cannot disagree on where a task's + * records start. + */ +struct ane_hx_task { + size_t rec, end; /* the task's records */ + size_t next; /* the next task or zero block */ +}; + +/* + * Frame the task or zero block at @pos of a stream of @size bytes. Returns 1 + * for a task, 0 for a zero block (only @t->next is set) and -ENOEXEC for a + * frame that does not fit or is not padded with zeros. + */ +static inline int ane_hx_task_frame(const u8 *p, size_t size, size_t pos, + unsigned int header_words, struct ane_hx_task *t) +{ + u32 words; + + if (!header_words || pos > size || size - pos < 16) + return -ENOEXEC; + words = (get_unaligned_le32(p + pos) >> 16) & 0x7ff; + if (!words) { + t->next = pos + 16; + return memchr_inv(p + pos, 0, 16) ? -ENOEXEC : 0; + } + if (words < header_words || words > (size - pos) / 4) + return -ENOEXEC; + t->end = pos + words * 4; + if ((get_unaligned_le32(p + pos + (header_words - 1) * 4) & 3) == 3) + header_words++; + if (words < header_words) + return -ENOEXEC; + t->rec = pos + header_words * 4; + t->next = t->end == size ? size : ALIGN(t->end, 16); + if (t->next > size || memchr_inv(p + t->end, 0, t->next - t->end)) + return -ENOEXEC; + return 1; +} + +/* + * The structural gate over the framing above. Every record names registers + * of the H16 image. This gate does not replace container/tensor/aperture + * validation. */ static inline int -ane_hx_task_stream_validate_limit(const void *text, size_t size, u32 expected_tasks, - u32 prologue, u32 *record_limit, size_t *final_end) +ane_hx_task_stream_validate_hdr(const void *text, size_t size, u32 expected_tasks, + u32 prologue, unsigned int header_words, + u32 *record_limit, size_t *final_end) { const u8 *p = text; size_t pos = 16, last = 0; u32 tasks = 0, limit = 0; - if (!p || !expected_tasks || size < 16 || size > ANE_H16_TASK_MAX || - (size & 3) || get_unaligned_le32(p) != prologue || - memchr_inv(p + 4, 0, 12)) + if (!p || !expected_tasks || size < 16 || size > ANE_H16_TASK_MAX || (size & 3) || + get_unaligned_le32(p) != prologue || memchr_inv(p + 4, 0, 12)) return -ENOEXEC; while (pos < size) { - u32 words, header_words = 9; - size_t end, padded, rec; + struct ane_hx_task t; + int ret = ane_hx_task_frame(p, size, pos, header_words, &t); + size_t rec; - if (size - pos < 16) - return -ENOEXEC; - words = (get_unaligned_le32(p + pos) >> 16) & 0x7ff; - if (!words) { - if (memchr_inv(p + pos, 0, 16)) - return -ENOEXEC; - pos += 16; + if (ret < 0) + return ret; + pos = t.next; + if (!ret) continue; - } - if (words < 9 || words > (size - pos) / 4) - return -ENOEXEC; - end = pos + words * 4; - if ((get_unaligned_le32(p + pos + 8 * 4) & 3) == 3) - header_words++; - if (words < header_words) - return -ENOEXEC; - rec = pos + header_words * 4; /* A record needs at least one header and one register value. */ - limit += (end - rec) / 8; - while (rec < end) { - u32 h = get_unaligned_le32(p + rec); - u32 base = h & 0x7fff; - u32 mask = (h >> 15) & 0xffff; - u32 count, i; + limit += (t.end - t.rec) / 8; + for (rec = t.rec; rec < t.end; ) { + u32 h = get_unaligned_le32(p + rec), count = ane_hx_record_count(h); + u32 base = h & 0x7fff, mask = (h >> 15) & 0xffff, i; rec += 4; - if (h & BIT(31)) - count = 1 + hweight32(mask); - else - count = ((h >> 15) & 0x3f) + 1; - if (count > (end - rec) / 4 || !ane_h16_register_valid(base)) + if (count > (t.end - rec) / 4 || !ane_h16_register_valid(base)) return -ENOEXEC; if (h & BIT(31)) { for (i = 0; i < 16; i++) @@ -100,11 +140,7 @@ ane_hx_task_stream_validate_limit(const void *text, size_t size, u32 expected_ta } rec += count * 4; } - padded = end == size ? end : ALIGN(end, 16); - if (padded > size || memchr_inv(p + end, 0, padded - end)) - return -ENOEXEC; - last = end; - pos = padded; + last = t.end; if (++tasks > expected_tasks) return -ENOEXEC; } @@ -117,6 +153,14 @@ ane_hx_task_stream_validate_limit(const void *text, size_t size, u32 expected_ta return 0; } +static inline int +ane_hx_task_stream_validate_limit(const void *text, size_t size, u32 expected_tasks, + u32 prologue, u32 *record_limit, size_t *final_end) +{ + return ane_hx_task_stream_validate_hdr(text, size, expected_tasks, prologue, 9, + record_limit, final_end); +} + static inline int ane_hx_task_stream_validate(const void *text, size_t size, u32 expected_tasks, u32 prologue) { @@ -130,6 +174,433 @@ ane_h16_task_stream_validate(const void *text, size_t size, u32 expected_tasks) return ane_hx_task_stream_validate(text, size, expected_tasks, 1); } +/* + * DMA bases. A task names each buffer the engine reads or writes as a + * relocated [lo, hi] record: its 64-bit offset is taken relative to the DVA + * of the buffer bound to the record's BAR slot, and nothing after this point + * bounds the sum. The bases are the input DMA's sources 1 and 2, the output + * DMA, the coefficient DMA and the lookup table. + */ +#define ANE_HX_DMA_SLOTS 64 +#define ANE_HX_DMA_WORDS (23 + 81 + 21 + 72) + +/* Image index of a common or DMA register byte address, or -1. */ +static inline int ane_hx_dma_index(u32 addr) +{ + if (addr < 0x5c) + return addr / 4; + if (addr >= 0x4d00 && addr < 0x4e44) + return 23 + (addr - 0x4d00) / 4; + if (addr >= 0x5100 && addr < 0x5154) + return 104 + (addr - 0x5100) / 4; + if (addr >= 0x5500 && addr < 0x5620) + return 125 + (addr - 0x5500) / 4; + return -1; +} + +static inline bool ane_hx_dma_base(u32 addr) +{ + switch (addr & ~4) { + case 0x4d10: case 0x4d28: case 0x5108: case 0x5510: case 0x5618: + return true; + } + return false; +} + +/* + * The DMA registers a task may set: the bases, their strides, formats and + * coefficient lanes, and the words that only configure or hint a transfer. + * The rest of each DMA block (metadata and compression, texture, crop and + * wrap, the bias, post-scale and palette tables) moves addresses this bound + * does not model, and no measured program sets it, so it stays zero. + */ +static inline bool ane_hx_dma_modelled(u32 addr) +{ + return (addr >= 0x4d00 && addr <= 0x4d3c) || addr == 0x4d68 || addr == 0x4d6c || + addr == 0x5100 || addr == 0x5104 || (addr >= 0x5108 && addr <= 0x511c) || + addr == 0x5138 || addr == 0x5500 || addr == 0x5504 || + (addr >= 0x5510 && addr <= 0x55dc) || (addr >= 0x5610 && addr <= 0x561c); +} + +/* Source 1, source 2 and destination DMA configuration and coefficient lanes. */ +static inline bool ane_hx_dma_config(u32 addr) +{ + return addr == 0x4d00 || addr == 0x4d04 || addr == 0x5100 || + (addr >= 0x5520 && addr <= 0x555c); +} + +/* + * Whether configuration word @w at @addr enables its DMA: any non-zero value + * except a coefficient lane's idle form, 0x20 in the low half, which + * lookup-table tasks write for the lanes they do not fetch. + */ +static inline bool ane_hx_dma_config_on(u32 addr, u32 w) +{ + return w && !(addr >= 0x5520 && addr <= 0x555c && (w & 0xffff) == 0x20); +} + +/* + * A count of @n steps @stride apart. Only a zero stride lets a zero count be + * read as one: the kernel cannot bound what a zero count moves when the + * engine steps by the stride. + */ +static inline int ane_hx_dma_count(u32 n, u32 stride, u64 *count) +{ + if (!n && stride) + return -ENOEXEC; + *count = max(1U, n); + return 0; +} + +/* Byte address of value @i of the record with header @h. */ +static inline u32 ane_hx_record_addr(u32 h, u32 i) +{ + u32 base = h & 0x7fff, mask = (h >> 15) & 0xffff, bit; + + if (!(h & BIT(31)) || !i) + return (base + i) * 4; + for (bit = 0; bit < 16; bit++) + if ((mask & BIT(bit)) && !--i) + break; + return (base + bit + 1) * 4; +} + +/* + * Bytes an input or output DMA stream touches from its base: the last + * element of the last row, plane, depth slice and group. Interleave k packs + * k channels into each element, so a plane holds k channels (the measured + * matmul staging writes 128 channels interleaved 8 as 16 planes of 2 KiB, its + * exact scratch). The row, plane, depth and group strides follow the base; + * a zero height, channel, depth or group count is one only with a zero + * stride (ane_hx_dma_count()). + */ +static inline int ane_hx_dma_tile(const u32 *img, u32 base, u64 *extent) +{ + static const u8 bytes[] = { 1, 1, 2, 4 }; + bool dst = base == 0x5108; + u32 stride = base + 8, format = dst ? 0x5138 : base == 0x4d10 ? 0x4d68 : 0x4d6c; + u32 dim = dst ? 0x14 : 0x4, f = img[ane_hx_dma_index(format)], step; + u64 k = max(1U, (f >> 24) & 0xf), n, sum, term; + unsigned int i; + + sum = (u64)max(1U, img[ane_hx_dma_index(dim)]) * bytes[(f >> 12) & 3] * k; + for (i = 1; i < 5; i++) { + step = img[ane_hx_dma_index(stride + 4 * (i - 1))]; + if (ane_hx_dma_count(img[ane_hx_dma_index(i < 4 ? dim + 4 * i : 0x24)], step, &n)) + return -ENOEXEC; + if (i == 2) + n = DIV_ROUND_UP(n, k); + if (check_mul_overflow(n - 1, (u64)step, &term) || + check_add_overflow(sum, term, &sum)) + return -ENOEXEC; + } + *extent = sum; + return 0; +} + +/* + * Bytes the coefficient DMA reads from its base: the furthest of the 16 lanes + * (offset 0x5560 + 4i, size 0x55a0 + 4i, at least the per-channel aligned + * size 0x5504; an unset size is 64), then every group (stride 0x5518) and + * every output channel group (stride 0x551c) after the first. An output + * channel group is 16 << (common word 0x40 & 7) channels, 128 when that + * word is unset. As with a zero width, a lane of size 0 is refused rather + * than read as nothing, and a zero group or channel count is one only with + * a zero stride. + */ +static inline int ane_hx_dma_kernel(const u32 *img, u64 *extent) +{ + u32 group_stride = img[ane_hx_dma_index(0x5518)]; + u32 ocg_stride = img[ane_hx_dma_index(0x551c)]; + u64 lanes = 0, size, groups, ocgs, term; + unsigned int i; + + for (i = 0; i < 16; i++) { + size = max(img[ane_hx_dma_index(0x55a0 + 4 * i)], img[ane_hx_dma_index(0x5504)]); + if (!size) + return -ENOEXEC; + lanes = max(lanes, img[ane_hx_dma_index(0x5560 + 4 * i)] + size); + } + if (ane_hx_dma_count(img[ane_hx_dma_index(0x24)], group_stride, &groups) || + ane_hx_dma_count(img[ane_hx_dma_index(0x1c)], ocg_stride, &ocgs)) + return -ENOEXEC; + ocgs = DIV_ROUND_UP(ocgs, 16U << (img[ane_hx_dma_index(0x40)] & 7)); + if (check_mul_overflow(groups - 1, (u64)group_stride, &term) || + check_add_overflow(lanes, term, &lanes) || + check_mul_overflow(ocgs - 1, (u64)ocg_stride, &term) || + check_add_overflow(lanes, term, extent)) + return -ENOEXEC; + return 0; +} + +/* The five DMA bases, in the order of ane_hx_dma_state's arrays. */ +static const u16 ane_hx_dma_base_addr[] = { 0x4d10, 0x4d28, 0x5108, 0x5510, 0x5618 }; +#define ANE_HX_DMA_BASES ARRAY_SIZE(ane_hx_dma_base_addr) + +/* + * One task's register image, the image words it wrote, and each base's slot + * and offset as it wrote them. + */ +struct ane_hx_dma_state { + u32 img[ANE_HX_DMA_WORDS]; + DECLARE_BITMAP(set, ANE_HX_DMA_WORDS); + u64 offset[ANE_HX_DMA_BASES]; + u8 slot[ANE_HX_DMA_BASES]; + u8 written; /* bit b: base b was written */ +}; + +/* + * The reset values of the image: a task starts from them, and a program + * may leave out every word that holds its reset value. On the J775D's H17 a + * second task that leaves out the output base or a row stride runs with + * the reset value 0, and one that leaves out the widths does not run with + * the first task's. + */ +static inline void ane_hx_dma_defaults(struct ane_hx_dma_state *st) +{ + unsigned int i; + + memset(st, 0, sizeof(*st)); + /* Input and output channel counts (0x0c, 0x1c) reset to 16 on H16/H17. */ + st->img[ane_hx_dma_index(0x0c)] = 16; + st->img[ane_hx_dma_index(0x1c)] = 16; + st->img[ane_hx_dma_index(0x40)] = 3; + for (i = 0; i < 16; i++) + st->img[ane_hx_dma_index(0x55a0 + 4 * i)] = 64; +} + +/* + * Registers outside the common and DMA blocks that the bound does not model. + * The L2 (0x4100), planar engine (0x4500) and neural engine (0x4900) blocks + * configure on-chip buffers and arithmetic, and none of them can be + * relocated, so none carries a buffer address. 0x44d0 is never written; of + * the cache DMA block (0x5900), only the words the compiler writes, none of + * them an address, may be non-zero. + */ +static inline bool ane_hx_other_allowed(u32 addr) +{ + if (addr == 0x44d0) + return false; + if (addr >= 0x5900 && addr < 0x5934) + return addr == 0x5900 || addr == 0x5904 || addr == 0x5908 || + addr == 0x5918 || addr == 0x5928 || addr == 0x592c; + return true; +} + +/* + * Apply one task's records (bytes [rec, end) of @p) to @st, refusing the + * header forms the task stream never uses. A relocated record covering a + * base's [lo, hi] pair sets that base's slot and offset. Any other + * relocation names the slot 4 custom BAR and takes its value + * (ane_h16_custom_bars()), which this check does not see, so the + * configuration word must already enable its DMA: that value must not be + * able to turn a DMA on. + * A word written twice in one task must repeat its value, and a base its + * slot too, so no earlier write names anything unchecked; H17 programs + * repeat source 2's base unchanged. + */ +static inline int ane_hx_dma_apply(const u8 *p, size_t rec, size_t end, + struct ane_hx_dma_state *st) +{ + unsigned int i, b; + int index; + + while (rec < end) { + u32 h = get_unaligned_le32(p + rec), count = ane_hx_record_count(h); + bool reloc = !(h & BIT(31)) && (h & BIT(29)); + u32 slot = (h >> 23) & 0x3f, first = (h & 0x7fff) * 4; + + rec += 4; + if (count > (end - rec) / 4) + return -ENOEXEC; + /* Dense header bits 21, 22 and 30 are unused, the slot only names a relocation. */ + if (!(h & BIT(31)) && ((h & (BIT(21) | BIT(22) | BIT(30))) || (!reloc && slot))) + return -ENOEXEC; + if (reloc && count == 2 && ane_hx_dma_base(first) && !(first & 4)) { + u64 offset = get_unaligned_le32(p + rec) | + (u64)get_unaligned_le32(p + rec + 4) << 32; + + for (b = 0; ane_hx_dma_base_addr[b] != first; b++) + ; + if ((st->written & BIT(b)) && st->slot[b] != slot) + return -ENOEXEC; + st->offset[b] = offset; + st->slot[b] = slot; + st->written |= BIT(b); + } else if (reloc) { + if (slot != 4) + return -ENOEXEC; + for (i = 0; i < count; i++) + if (!ane_hx_dma_config(first + 4 * i) || + !ane_hx_dma_config_on(first + 4 * i, + get_unaligned_le32(p + rec + 4 * i))) + return -ENOEXEC; + } + for (i = 0; i < count; i++) { + u32 addr = ane_hx_record_addr(h, i); + u32 w = get_unaligned_le32(p + rec + 4 * i); + + if (!reloc && ane_hx_dma_base(addr)) + return -ENOEXEC; + index = ane_hx_dma_index(addr); + if (index < 0) { + if (w && !ane_hx_other_allowed(addr)) + return -ENOEXEC; + continue; + } + if (test_and_set_bit(index, st->set) && st->img[index] != w) + return -ENOEXEC; + st->img[index] = w; + } + rec += count * 4; + } + return 0; +} + +/* + * The DMA words of an image: only modelled registers, and no wrap, offset, + * crop or compression. Format bits other than the interleave, the element + * size and the bits every program sets are refused, as is an output channel + * group (common word 0x40 & 7) above 5, the largest the compiler writes. + */ +static inline int ane_hx_dma_image_check(const u32 *img) +{ + unsigned int i; + + for (i = 23; i < ANE_HX_DMA_WORDS; i++) { + u32 addr = i < 104 ? 0x4d00 + (i - 23) * 4 : i < 125 ? 0x5100 + (i - 104) * 4 : + 0x5500 + (i - 125) * 4; + + if (img[i] && !ane_hx_dma_modelled(addr)) + return -ENOEXEC; + } + if ((img[ane_hx_dma_index(0x4d08)] | img[ane_hx_dma_index(0x4d0c)]) & ~0xffU || + (img[ane_hx_dma_index(0x4d68)] | img[ane_hx_dma_index(0x4d6c)]) & ~0x0f003031U || + img[ane_hx_dma_index(0x5104)] & ~0x7f000000U || + img[ane_hx_dma_index(0x5138)] & ~0x0f303031U || + (img[ane_hx_dma_index(0x40)] & 7) > 5) + return -ENOEXEC; + return 0; +} + +/* + * What one task enables it must also locate and size. Each DMA has its + * configuration words: source 1 0x4d00, source 2 0x4d04, the destination + * 0x5100, the 16 coefficient lanes 0x5520-0x555c and the lookup table's + * 0x5600-0x5614, which enable it as ane_hx_dma_config_on() says. An + * enabled DMA needs its relocated base in the same task, and an enabled + * input or output stream a width, height and channel count that are not + * zero. A zero width is not read as one: on the J775D's H17 a task without + * widths stalled the engine, and on H16 a matmul without them ran 256 wide. + * A zero depth or group count is one only with a zero stride, which every + * program that leaves them out has (ane_hx_dma_tile()). + */ +static inline int ane_hx_dma_enabled_check(const struct ane_hx_dma_state *st) +{ + static const struct { u16 config, last, dim; u8 base; } dma[] = { + { 0x4d00, 0x4d00, 0x4, 0 }, { 0x4d04, 0x4d04, 0x4, 1 }, + { 0x5100, 0x5100, 0x14, 2 }, { 0x5520, 0x555c, 0, 3 }, + { 0x5600, 0x5614, 0, 4 }, + }; + unsigned int i; + bool on; + u32 a; + + for (i = 0; i < ARRAY_SIZE(dma); i++) { + for (a = dma[i].config, on = false; a <= dma[i].last; a += 4) + if (ane_hx_dma_config_on(a, st->img[ane_hx_dma_index(a)])) + on = true; + if (!on) + continue; + if (!(st->written & BIT(dma[i].base))) + return -ENOEXEC; + for (a = dma[i].dim; dma[i].dim && a <= dma[i].dim + 8; a += 4) + if (!st->img[ane_hx_dma_index(a)]) + return -ENOEXEC; + } + return 0; +} + +/* + * Base @b of @st, with the extent its image gives, must lie inside the buffer + * bound to its slot: the end of the last 64-byte line it touches, + * ALIGN(offset + extent, 64), at most the buffer's size. The offset is + * unsigned: a negative one is larger than any buffer. + */ +static inline int ane_hx_dma_fits(const struct ane_hx_dma_state *st, unsigned int b, + const u64 bound[ANE_HX_DMA_SLOTS]) +{ + u32 base = ane_hx_dma_base_addr[b]; + u64 extent, last; + int ret = 0; + + if (base == 0x5510) + ret = ane_hx_dma_kernel(st->img, &extent); + else if (base == 0x5618) + extent = max(64U, st->img[ane_hx_dma_index(0x5614)]); + else + ret = ane_hx_dma_tile(st->img, base, &extent); + if (ret || !bound[st->slot[b]] || + check_add_overflow(st->offset[b], extent, &last) || + check_add_overflow(last, 63ULL, &last) || + (last & ~63ULL) > bound[st->slot[b]]) + return -ENOEXEC; + return 0; +} + +/* + * Bound every DMA base of an already validated stream with @header_words + * fixed words per task. @bound[s] is the size of the buffer the operation + * section binds to BAR slot s, 0 when it binds none. A base must be a + * relocated [lo, hi] record on a bound slot, and its offset plus the extent + * of its transfer must stay inside that buffer. + * + * Each task is checked on its own words over the reset values, which is the + * state the engine runs it from (see ane_hx_dma_defaults()). A word a task + * leaves out holds its reset value, whatever an earlier task wrote there, + * and a DMA the task does not enable reads and writes nothing. No base can + * reach a later task either: every DMA a task enables has its base written + * in that task (ane_hx_dma_enabled_check()). + */ +static inline int +ane_hx_task_stream_dma_validate(const void *text, size_t size, unsigned int header_words, + const u64 bound[ANE_HX_DMA_SLOTS]) +{ + struct ane_hx_dma_state *task; + struct ane_hx_task t; + const u8 *p = text; + size_t pos = 16; + unsigned int b; + int ret = 0; + + if (!p || !bound || size < 16 || size > ANE_H16_TASK_MAX || (size & 3)) + return -ENOEXEC; + task = kmalloc_obj(*task); + if (!task) + return -ENOMEM; + while (pos < size) { + ret = ane_hx_task_frame(p, size, pos, header_words, &t); + if (ret < 0) + break; + pos = t.next; + if (!ret) + continue; + ane_hx_dma_defaults(task); + ret = ane_hx_dma_apply(p, t.rec, t.end, task); + if (!ret) + ret = ane_hx_dma_image_check(task->img); + if (!ret) + ret = ane_hx_dma_enabled_check(task); + for (b = 0; !ret && b < ANE_HX_DMA_BASES; b++) + if (task->written & BIT(b)) + ret = ane_hx_dma_fits(task, b, bound); + if (ret) + break; + } + kfree(task); + return ret; +} + /* Section ordinal is supplied only by the validated complete section table. * This checks Mach-O relocation entries, not the distinct aperture records. */ diff --git a/drivers/accel/ane/ane_h16_tasks_test.c b/drivers/accel/ane/ane_h16_tasks_test.c index 2104e429185b72..787f846e6fcd11 100644 --- a/drivers/accel/ane/ane_h16_tasks_test.c +++ b/drivers/accel/ane/ane_h16_tasks_test.c @@ -137,6 +137,707 @@ static void ane_h17_prologue_test(struct kunit *test) KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), -ENOEXEC); } +/* + * One 16x16x128 fp16 add task as mil-hwx-compiler writes it: source 1 on BAR + * slot 6 and the destination on slot 7, each a relocated [lo, hi] record, + * rows of 0x40 and planes of 0x400 bytes, a source depth stride of 0. + * Returns the stream size. + */ +static size_t dma_task(u8 *text, u64 src, u64 dst) +{ + static const u32 dims[] = { 16, 16, 128, 0, 16, 16, 128 }; + size_t at = 16 + 9 * 4; + unsigned int i; + +#define PUT(v) do { put_unaligned_le32(v, text + at); at += 4; } while (0) + memset(text, 0, 256); + put_unaligned_le32(1, text); + PUT(0x4 / 4 | 6 << 15); + for (i = 0; i < ARRAY_SIZE(dims); i++) + PUT(dims[i]); + PUT(0x4d18 / 4 | 2 << 15); + PUT(0x40); + PUT(0x400); + PUT(0); + PUT(0x4d68 / 4); + PUT(0x1002031); + PUT(0x5110 / 4 | 1 << 15); + PUT(0x40); + PUT(0x400); + PUT(0x5138 / 4); + PUT(0x1302031); + PUT(0x4d10 / 4 | 1 << 15 | BIT(29) | 6 << 23); + PUT(lower_32_bits(src)); + PUT(upper_32_bits(src)); + PUT(0x5108 / 4 | 1 << 15 | BIT(29) | 7 << 23); + PUT(lower_32_bits(dst)); + PUT(upper_32_bits(dst)); + /* The cache-allocation word takes the slot 4 custom BAR value. */ + PUT(0x4d00 / 4 | BIT(29) | 4 << 23); + PUT(0x21); +#undef PUT + put_unaligned_le32((at - 16) / 4 << 16, text + 16); + return at; +} + +/* Record @n (0-based) of dma_task's one task. */ +static u8 *dma_record(u8 *text, unsigned int n) +{ + static const u8 words[] = { 8, 4, 2, 3, 2, 3, 3, 2 }; + size_t at = 16 + 9 * 4; + + while (n--) + at += words[n] * 4; + return text + at; +} + +static void ane_hx_dma_bound_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000 }; + u8 text[256]; + size_t size; + + /* 15 rows of 0x40, 127 planes of 0x400 and one 32-byte row: exactly 128 KiB. */ + size = dma_task(text, 0, 0); + KUNIT_ASSERT_EQ(test, ane_h16_task_stream_validate(text, size, 1), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + size = dma_task(text, 0x40, 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + size = dma_task(text, 0, 0x20000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + size = dma_task(text, 0, -0x70000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + size = dma_task(text, -1, 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* A larger buffer takes the same offset. */ + bound[7] = 0x40000; + size = dma_task(text, 0, 0x20000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + + /* A slot the operation section does not bind. */ + bound[7] = 0; + size = dma_task(text, 0, 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + bound[7] = 0x20000; + + /* A base without relocation, or relocated on the custom BAR slot. */ + put_unaligned_le32(0x4d10 / 4 | 1 << 15, dma_record(text, 5)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(0x4d10 / 4 | 1 << 15 | BIT(29) | 4 << 23, dma_record(text, 5)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* A relocated record that is not exactly the [lo, hi] pair. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x4d0c / 4 | 1 << 15 | BIT(29) | 6 << 23, dma_record(text, 5)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* A scatter write of the hi word. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(BIT(31) | BIT(15) | 0x5108 / 4, dma_record(text, 6)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* A relocation on a stride, and an unused header bit. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x4d18 / 4 | 1 << 15 | BIT(29) | 6 << 23, dma_record(text, 1)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(0x4d18 / 4 | 1 << 15 | BIT(30), dma_record(text, 1)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + + /* One byte more of plane stride crosses a line past the end. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x401, dma_record(text, 1) + 8); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* Rows, planes and depth slices whose sum wraps 64 bits to 32 bytes. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x80000001, dma_record(text, 0) + 8); + put_unaligned_le32(0x80000001, dma_record(text, 0) + 12); + put_unaligned_le32(3, dma_record(text, 0) + 16); + put_unaligned_le32(U32_MAX, dma_record(text, 1) + 4); + put_unaligned_le32(U32_MAX, dma_record(text, 1) + 8); + put_unaligned_le32(0x80000000, dma_record(text, 1) + 12); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* A source 1 metadata address, which the bound does not model. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x4d40 / 4, dma_record(text, 2)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* A wrap configuration beside the cache hint. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x4d08 / 4, dma_record(text, 2)); + put_unaligned_le32(0x1ce, dma_record(text, 2) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(0xce, dma_record(text, 2) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); +} + +/* Record headers: @n dense words from @addr, and a relocated [lo, hi] pair on @slot. */ +#define DMA_REC(addr, n) ((addr) / 4 | ((n) - 1) << 15) +#define DMA_RELOC(addr, slot) (DMA_REC(addr, 2) | BIT(29) | (slot) << 23) + +/* + * Parts of dma_task's one task, for streams of several tasks: its geometry + * (dimensions with @rows source rows, strides with @plane source plane + * stride, formats), its two bases (source 1 at @src, the destination at 0) + * and the source 1 configuration word that enables it. + */ +enum { DMA_GEOMETRY = 1, DMA_BASES = 2, DMA_ENABLE = 4, DMA_EXTRA = 8 }; + +/* Append one task of @parts, then @n more words of @extra; returns the new end. */ +static size_t dma_append(u8 *text, size_t at, unsigned int parts, u32 rows, u32 plane, + u64 src, const u32 *extra, unsigned int n) +{ + const u32 geometry[] = { + DMA_REC(0x4, 7), 16, rows, 128, 0, 16, 16, 128, + DMA_REC(0x4d18, 3), 0x40, plane, 0, DMA_REC(0x4d68, 1), 0x1002031, + DMA_REC(0x5110, 2), 0x40, 0x400, DMA_REC(0x5138, 1), 0x1302031, + }; + const u32 bases[] = { + DMA_RELOC(0x4d10, 6), lower_32_bits(src), upper_32_bits(src), + DMA_RELOC(0x5108, 7), 0, 0, + }; + const u32 enable[] = { DMA_REC(0x4d00, 1) | BIT(29) | 4 << 23, 0x21 }; + const struct { unsigned int part; const u32 *w; unsigned int n; } part[] = { + { DMA_GEOMETRY, geometry, ARRAY_SIZE(geometry) }, + { DMA_BASES, bases, ARRAY_SIZE(bases) }, + { DMA_ENABLE, enable, ARRAY_SIZE(enable) }, + { DMA_EXTRA, extra, n }, + }; + size_t task = at; + unsigned int k, i; + + parts |= DMA_EXTRA; + memset(text + at, 0, 9 * 4); + at += 9 * 4; + for (k = 0; k < ARRAY_SIZE(part); k++) + for (i = 0; (parts & part[k].part) && i < part[k].n; i++, at += 4) + put_unaligned_le32(part[k].w[i], text + at); + put_unaligned_le32((at - task) / 4 << 16, text + task); + return ALIGN(at, 16); +} + +/* A stream of one complete task from dma_append() with @n words of @extra. */ +static size_t dma_one(u8 *text, u32 plane, const u32 *extra, unsigned int n) +{ + memset(text, 0, 512); + put_unaligned_le32(1, text); + return dma_append(text, 16, 7, 16, plane, 0, extra, n); +} + +/* A stream of two tasks, @first then @second, from dma_append(). */ +static size_t dma_two(u8 *text, unsigned int first, unsigned int second, u32 plane) +{ + size_t at; + + memset(text, 0, 512); + put_unaligned_le32(1, text); + at = dma_append(text, 16, first, 16, 0x400, 0, NULL, 0); + return dma_append(text, at, second, 16, plane, 0, NULL, 0); +} + +/* + * Each task runs from the reset values, so each is checked on its own words + * over them, and every DMA a task enables has its base in that task. A word + * a task leaves out holds its reset value, whatever an earlier task wrote. + */ +static void ane_hx_dma_reset_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000 }; + const u32 groups[] = { DMA_REC(0x24, 1), 2, DMA_REC(0x4d24, 1), 0x20000 }; + const u32 dst_only[] = { + DMA_REC(0x4, 7), 16, 32, 128, 0, 16, 16, 128, + DMA_REC(0x5110, 2), 0x40, 0x400, DMA_REC(0x5138, 1), 0x1302031, + DMA_RELOC(0x5108, 7), 0, 0, + }; + u8 text[512]; + size_t size; + + /* Both tasks complete and in range. */ + size = dma_two(text, 7, 7, 0x400); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* + * Task N: geometry with no base; task N+1: the bases and the enable + * alone, which enable source 1 with no size of its own. + */ + size = dma_two(text, DMA_GEOMETRY, DMA_BASES | DMA_ENABLE, 0x400); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* N+1 with larger planes and nothing enabled moves nothing: N's base does not reach it. */ + size = dma_two(text, 7, DMA_GEOMETRY, 0x800); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* ... but enabling source 1 there without its base is refused, */ + size = dma_two(text, 7, DMA_GEOMETRY | DMA_ENABLE, 0x800); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* ... and so is its base with those planes. */ + size = dma_two(text, 7, 7, 0x800); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + + /* + * An L2-resident task: N+1 takes its input from L2 and writes only the + * destination, with 32 rows. Source 1 is not enabled in N+1, so N's + * source base is not read with N+1's rows (which would end past 128 KiB). + */ + memset(text, 0, 512); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 7, 16, 0x400, 0, NULL, 0); + size = dma_append(text, size, 0, 0, 0, 0, dst_only, ARRAY_SIZE(dst_only)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + + /* + * A word left at its reset value after an earlier task set it: N reads + * two groups 128 KiB apart from a 256 KiB source; N+1 leaves the group + * count and stride out and reads one group from 128 KiB on. + */ + bound[6] = 0x40000; + memset(text, 0, 512); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 7, 16, 0x400, 0, groups, ARRAY_SIZE(groups)); + size = dma_append(text, size, 7, 16, 0x400, 0x20000, NULL, 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* N+1 writing the two groups itself reaches 128 KiB past the source. */ + memset(text, 0, 512); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 7, 16, 0x400, 0, groups, ARRAY_SIZE(groups)); + size = dma_append(text, size, 7, 16, 0x400, 0x20000, groups, ARRAY_SIZE(groups)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); +} + +/* + * A base written twice in one task must repeat its slot and offset: an + * out-of-range first write followed by an in-range one is refused, as is + * a second write on another slot. H17 programs repeat 0x4d28 unchanged. + */ +static void ane_hx_dma_rewrite_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000, [8] = 0x20000 }; + u32 again[] = { DMA_RELOC(0x4d10, 6), 0, 0 }; + u8 text[512]; + size_t size; + + memset(text, 0, 512); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 7, 16, 0x400, 0, again, ARRAY_SIZE(again)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + memset(text, 0, 512); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 7, 16, 0x400, 0x20000, again, ARRAY_SIZE(again)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + again[0] = DMA_RELOC(0x4d10, 8); + memset(text, 0, 512); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 7, 16, 0x400, 0, again, ARRAY_SIZE(again)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); +} + +/* + * A task that enables a DMA must locate it and give it a real size; the + * channel group, the format bits and the registers outside the modelled + * blocks stay within what the compiler writes. + */ +static void ane_hx_dma_strict_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000 }; + u8 text[256]; + size_t size; + + /* The destination enabled: the cache word (record 7) becomes its configuration 0x5100. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x5100 / 4, dma_record(text, 7)); + put_unaligned_le32(0x1000021, dma_record(text, 7) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* ... with a zero channel count, */ + put_unaligned_le32(0, dma_record(text, 0) + 28); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(128, dma_record(text, 0) + 28); + /* ... and without its base: record 6 rewrites the destination strides instead. */ + put_unaligned_le32(0x5110 / 4 | 1 << 15, dma_record(text, 6)); + put_unaligned_le32(0x40, dma_record(text, 6) + 4); + put_unaligned_le32(0x400, dma_record(text, 6) + 8); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* A zero channel count on an enabled source. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0, dma_record(text, 0) + 12); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* + * A zero width on an enabled stream: the J775D's H17 stalled on one and + * an M4 Pro ran one 256 wide, so it is not read as one. + */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0, dma_record(text, 0) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* The destination's width matters once the destination is enabled. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0, dma_record(text, 0) + 20); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + put_unaligned_le32(0x5100 / 4, dma_record(text, 7)); + put_unaligned_le32(0x1000021, dma_record(text, 7) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(16, dma_record(text, 0) + 20); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* An output channel group of 6, then 5: common word 0x40 in place of the source format. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x40 / 4, dma_record(text, 2)); + put_unaligned_le32(6, dma_record(text, 2) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(5, dma_record(text, 2) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* A source format bit the compiler never sets. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x1002033, dma_record(text, 2) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* 0x44d0, and a cache DMA word the compiler never writes, in place of the source format. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x44d0 / 4, dma_record(text, 2)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(0x590c / 4, dma_record(text, 2)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(0x5904 / 4, dma_record(text, 2)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); +} + +/* + * The end of a transfer is the end of the last 64-byte line it touches: a + * 64-byte lookup table at offset 1 reads [0, 128). + */ +static void ane_hx_dma_align_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 100 }; + u8 text[64] = {}; + size_t at = 16 + 9 * 4; + + put_unaligned_le32(1, text); + put_unaligned_le32(0x5618 / 4 | 1 << 15 | BIT(29) | 6 << 23, text + at); + put_unaligned_le32(1, text + at + 4); + put_unaligned_le32(0, text + at + 8); + at += 12; + put_unaligned_le32((at - 16) / 4 << 16, text + 16); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, 9, bound), -ENOEXEC); + bound[6] = 128; + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, 9, bound), 0); + /* Offset 0x41: the line at 0x40 through the one at 0x80. */ + put_unaligned_le32(0x41, text + 16 + 9 * 4 + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, 9, bound), -ENOEXEC); +} + +/* + * Coefficient DMA: 16 lanes of 0x80 bytes at 0x80 apart from a base on slot + * 8, then a second output channel group 0x800 on (256 channels, 128 per + * group). + */ +static void ane_hx_dma_kernel_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [8] = 0x1000 }; + u8 text[512] = {}; + size_t at = 16 + 9 * 4; + unsigned int i; + +#define PUT(v) do { put_unaligned_le32(v, text + at); at += 4; } while (0) + put_unaligned_le32(1, text); + PUT(0x1c / 4); + PUT(256); + PUT(0x551c / 4); + PUT(0x800); + PUT(0x5560 / 4 | 31 << 15); + for (i = 0; i < 16; i++) + PUT(i * 0x80); + for (i = 0; i < 16; i++) + PUT(0x80); + PUT(0x5510 / 4 | 1 << 15 | BIT(29) | 8 << 23); + PUT(0); + PUT(0); +#undef PUT + put_unaligned_le32((at - 16) / 4 << 16, text + 16); + KUNIT_ASSERT_EQ(test, ane_h16_task_stream_validate(text, at, 1), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, 9, bound), 0); + bound[8] = 0xfc0; + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, 9, bound), -ENOEXEC); + /* 3 at 0x40 is the default 128-channel group, 2 a 64-channel one: four groups. */ + bound[8] = 0x1000; + put_unaligned_le32(0x40 / 4, text + at); + put_unaligned_le32(2, text + at + 4); + put_unaligned_le32((at + 8 - 16) / 4 << 16, text + 16); + KUNIT_ASSERT_EQ(test, ane_h16_task_stream_validate(text, at + 8, 1), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at + 8, 9, bound), -ENOEXEC); + bound[8] = 0x2000; + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at + 8, 9, bound), 0); +} + +/* + * A matmul's coefficient DMA from slot 3: 16 lanes of 0x1000 bytes 0x1000 + * apart, 256 output channels in two groups of 128 (common word 0x40 unset) + * @ocgs apart, the lane configuration words set to @lane (none when 0) and + * the base written when @base. + */ +static size_t dma_kernel(u8 *text, u32 lane, bool base, u32 ocgs) +{ + size_t at = 16 + 9 * 4; + unsigned int i; + + memset(text, 0, 512); + put_unaligned_le32(1, text); +#define PUT(v) do { put_unaligned_le32(v, text + at); at += 4; } while (0) + PUT(DMA_REC(0x1c, 1)); + PUT(256); + PUT(DMA_REC(0x3c, 1)); + PUT(0x20200004); + PUT(DMA_REC(0x551c, 1)); + PUT(ocgs); + PUT(DMA_REC(0x5560, 32)); + for (i = 0; i < 16; i++) + PUT(i * 0x1000); + for (i = 0; i < 16; i++) + PUT(0x1000); + if (lane) { + /* Enabled lanes take the custom BAR value; idle ones are not relocated. */ + PUT(DMA_REC(0x5520, 16) | ((lane & 0xffff) == 0x20 ? 0 : BIT(29) | 4 << 23)); + for (i = 0; i < 16; i++) + PUT(lane); + } + if (base) { + PUT(DMA_RELOC(0x5510, 3)); + PUT(0); + PUT(0); + } +#undef PUT + put_unaligned_le32((at - 16) / 4 << 16, text + 16); + return at; +} + +/* + * The coefficient DMA is held to the same rule as the others: lanes that + * enable it need its base in the task. A lookup-table task writes its lanes + * idle (0x20 in the low half) and fetches nothing. The second + * output channel group of 128 x 256 fp16 coefficients starts 0x10000 into + * them; a group stride of 0x40000 reads 0x30000 past a 0x20000 buffer. + */ +static void ane_hx_dma_kernel_enable_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [3] = 0x20000 }; + u8 text[512]; + size_t size; + + size = dma_kernel(text, 0x10041, true, 0x10000); + KUNIT_ASSERT_EQ(test, ane_h16_task_stream_validate(text, size, 1), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + size = dma_kernel(text, 0x10041, true, 0x40000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* Enabled lanes without a base. */ + size = dma_kernel(text, 0x10041, false, 0x10000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* Idle lanes without a base fetch nothing; any other lane word enables the DMA. */ + size = dma_kernel(text, 0x50020, false, 0x40000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + size = dma_kernel(text, 0x50022, false, 0x40000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + size = dma_kernel(text, 0x50120, false, 0x40000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* A base written beside idle lanes is still bounded. */ + size = dma_kernel(text, 0x50020, true, 0x40000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* Idle lanes that take the custom BAR value could become enabled lanes. */ + size = dma_kernel(text, 0x50020, false, 0x10000); + put_unaligned_le32(get_unaligned_le32(text + size - 17 * 4) | BIT(29) | 4 << 23, + text + size - 17 * 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); +} + +/* + * Counts the bound cannot read as one, and a lane that reads nothing. In + * dma_kernel()'s task, 52, 60 and 68 hold the records of the output channel + * count, common word 0x3c and the output channel group stride; 80 + 4i + * holds lane i's offset and 144 + 4i its size. + */ +static void ane_hx_dma_kernel_count_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [3] = 0x20000 }; + u8 text[512]; + size_t size; + + /* No group count with a group stride, then two groups 0x1000 apart. */ + size = dma_kernel(text, 0x10041, true, 0x10000); + put_unaligned_le32(DMA_REC(0x5518, 1), text + 60); + put_unaligned_le32(0x1000, text + 64); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(DMA_REC(0x24, 1), text + 68); + put_unaligned_le32(2, text + 72); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* No output channel count with an output channel group stride. */ + size = dma_kernel(text, 0x10041, true, 0x10000); + put_unaligned_le32(0, text + 56); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + size = dma_kernel(text, 0x10041, true, 0); + put_unaligned_le32(0, text + 56); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* A lane of size 0 at the end of the buffer, then one 0x5504 sizes. */ + size = dma_kernel(text, 0x10041, true, 0); + put_unaligned_le32(0x20000, text + 80 + 15 * 4); + put_unaligned_le32(0, text + 144 + 15 * 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(DMA_REC(0x5504, 1), text + 60); + put_unaligned_le32(0x80, text + 64); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(0x1f000, text + 80 + 15 * 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); +} + +/* + * A zero depth or group count on a source or the destination is one only + * with a zero stride. dma_task()'s source has depth 0 and writes its depth + * stride at record 1 + 12. + */ +static void ane_hx_dma_count_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000 }; + static const u32 dst_depth[] = { DMA_REC(0x5118, 1), 0x400 }; + static const u32 dst_depths[] = { DMA_REC(0x5118, 1), 0x400, DMA_REC(0x20, 1), 1 }; + static const u32 src_group[] = { DMA_REC(0x4d24, 1), 0x20000 }; + static const u32 dst_group[] = { DMA_REC(0x511c, 1), 0x20000 }; + static const u32 src_groups[] = { DMA_REC(0x24, 1), 1, DMA_REC(0x4d24, 1), 0x20000 }; + u8 text[512]; + size_t size; + + size = dma_task(text, 0, 0); + put_unaligned_le32(0x400, dma_record(text, 1) + 12); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(1, dma_record(text, 0) + 16); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + put_unaligned_le32(2, dma_record(text, 0) + 16); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + + size = dma_one(text, 0x400, dst_depth, ARRAY_SIZE(dst_depth)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + size = dma_one(text, 0x400, dst_depths, ARRAY_SIZE(dst_depths)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + size = dma_one(text, 0x400, src_group, ARRAY_SIZE(src_group)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + size = dma_one(text, 0x400, dst_group, ARRAY_SIZE(dst_group)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + size = dma_one(text, 0x400, src_groups, ARRAY_SIZE(src_groups)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); +} + +/* + * A word written twice in one task repeats its value: a plane stride that + * would end past the source, then one that would not, is refused. A + * configuration word on the custom BAR must already enable its DMA. + */ +static void ane_hx_dma_repeat_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000 }; + static const u32 plane[] = { DMA_REC(0x4d1c, 1), 0x400 }; + u8 text[512]; + size_t size; + + size = dma_one(text, 0x400, plane, ARRAY_SIZE(plane)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + size = dma_one(text, 0x800, plane, ARRAY_SIZE(plane)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + + size = dma_task(text, 0, 0); + put_unaligned_le32(0, dma_record(text, 7) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); +} + +/* + * One H15 task: eight header words (nine when @extra sets the last one's + * low bits), then a source 1 row stride of @row, three L2 records and + * dma_task()'s geometry, bases and enable. Read with nine header words, the + * row stride record would be a header word and the L2 records would hide + * it, so the stride goes unchecked. + */ +static size_t dma_h15(u8 *text, u32 row, bool extra) +{ + static const u32 tail[] = { + DMA_REC(0x4104, 1), DMA_REC(0x4108, 2), DMA_REC(0x410c, 1), 0, + DMA_REC(0x4, 7), 16, 16, 128, 0, 16, 16, 128, + DMA_REC(0x4d1c, 2), 0x400, 0, DMA_REC(0x4d68, 1), 0x1002031, + DMA_REC(0x5110, 2), 0x40, 0x400, DMA_REC(0x5138, 1), 0x1302031, + DMA_RELOC(0x4d10, 6), 0, 0, DMA_RELOC(0x5108, 7), 0, 0, + DMA_REC(0x4d00, 1) | BIT(29) | 4 << 23, 0x21, + }; + size_t at = 16 + 8 * 4; + unsigned int i; + + memset(text, 0, 256); + put_unaligned_le32(1, text); + if (extra) { + put_unaligned_le32(3, text + at - 4); + at += 4; + } + put_unaligned_le32(DMA_REC(0x4d18, 1), text + at); + put_unaligned_le32(row, text + at + 4); + at += 8; + for (i = 0; i < ARRAY_SIZE(tail); i++, at += 4) + put_unaligned_le32(tail[i], text + at); + put_unaligned_le32((at - 16) / 4 << 16, text + 16); + return at; +} + +/* The DMA bound walks a stream with its target's header words, as the structural gate does. */ +static void ane_hx_dma_h15_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000 }; + u8 text[256]; + size_t size; + bool extra; + + for (extra = false; ; extra = true) { + size = dma_h15(text, 0x40, extra); + KUNIT_ASSERT_EQ(test, ane_hx_task_stream_validate_hdr(text, size, 1, 1, 8, + NULL, NULL), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 8, bound), 0); + /* 15 rows of 0x1040 end past the source. */ + size = dma_h15(text, 0x1040, extra); + KUNIT_ASSERT_EQ(test, ane_hx_task_stream_validate_hdr(text, size, 1, 1, 8, + NULL, NULL), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 8, bound), + -ENOEXEC); + if (extra) + break; + } + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 0, bound), -ENOEXEC); +} + +/* + * Input and output channel counts (0x0c, 0x1c) reset to 16 on H16/H17, so + * programs omit them for 16-channel tensors while an explicit 0 is still + * refused. Destination word 0x5104 carries dependency bits in 30:24 without + * shifting the DMA address; bits outside 0x7f000000 remain refused. + */ +static void ane_hx_dma_channel_default_and_dst_dep_test(struct kunit *test) +{ + /* 16 channels interleaved 8 -> 2 planes of 0x400 (0x400 + 16*2*8 = 0x500). */ + static const u32 omitted_ch[] = { + DMA_REC(0x4, 2), 16, 1, + DMA_REC(0x14, 2), 16, 1, + DMA_REC(0x4d18, 2), 0x100, 0x400, DMA_REC(0x4d68, 1), 0x8002031, + DMA_REC(0x5110, 2), 0x100, 0x400, DMA_REC(0x5138, 1), 0x8302031, + DMA_RELOC(0x4d10, 6), 0, 0, + DMA_RELOC(0x5108, 7), 0, 0, + DMA_REC(0x4d00, 1), 0x20010041, + DMA_REC(0x5100, 2), 0x10100e1, 0x01000000, + }; + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x500, [7] = 0x500 }; + u8 text[512]; + size_t size; + + memset(text, 0, sizeof(text)); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 0, 0, 0, 0, omitted_ch, ARRAY_SIZE(omitted_ch)); + KUNIT_ASSERT_EQ(test, ane_h16_task_stream_validate(text, size, 1), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + + /* One 64-byte line short of the 16-channel (2-plane) extent is refused. */ + bound[6] = 0x4c0; + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + bound[6] = 0x500; + bound[7] = 0x4c0; + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + bound[7] = 0x500; + + /* 0x5104 bits outside 30:24 are refused. */ + put_unaligned_le32(0x24000000, text + 16 + 9 * 4 + (ARRAY_SIZE(omitted_ch) - 1) * 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + put_unaligned_le32(0x01000001, text + 16 + 9 * 4 + (ARRAY_SIZE(omitted_ch) - 1) * 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(0x80000000, text + 16 + 9 * 4 + (ARRAY_SIZE(omitted_ch) - 1) * 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); +} + static struct kunit_case ane_h16_task_cases[] = { KUNIT_CASE(ane_h16_prologue_test), KUNIT_CASE(ane_h17_prologue_test), @@ -144,6 +845,18 @@ static struct kunit_case ane_h16_task_cases[] = { KUNIT_CASE(ane_h16_scatter_task_test), KUNIT_CASE(ane_h16_extra_header_test), KUNIT_CASE(ane_h16_relocation_test), + KUNIT_CASE(ane_hx_dma_bound_test), + KUNIT_CASE(ane_hx_dma_kernel_test), + KUNIT_CASE(ane_hx_dma_kernel_enable_test), + KUNIT_CASE(ane_hx_dma_kernel_count_test), + KUNIT_CASE(ane_hx_dma_count_test), + KUNIT_CASE(ane_hx_dma_repeat_test), + KUNIT_CASE(ane_hx_dma_h15_test), + KUNIT_CASE(ane_hx_dma_channel_default_and_dst_dep_test), + KUNIT_CASE(ane_hx_dma_reset_test), + KUNIT_CASE(ane_hx_dma_rewrite_test), + KUNIT_CASE(ane_hx_dma_strict_test), + KUNIT_CASE(ane_hx_dma_align_test), {} }; @@ -153,5 +866,5 @@ static struct kunit_suite ane_h16_task_suite = { }; kunit_test_suite(ane_h16_task_suite); -MODULE_DESCRIPTION("KUnit tests for H16 task and relocation validation"); +MODULE_DESCRIPTION("KUnit tests for H16 task, relocation and DMA base validation"); MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_pm_test.c b/drivers/accel/ane/ane_pm_test.c index 5c372a2a730113..d01117e09ad292 100644 --- a/drivers/accel/ane/ane_pm_test.c +++ b/drivers/accel/ane/ane_pm_test.c @@ -1,9 +1,12 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* Exercise recovery against the real runtime-PM and device-link core. */ #include +#include #include +#include #include +#include "ane_fw_sleep.h" #include "ane_pm.h" struct ane_pm_test_dev { @@ -228,6 +231,484 @@ static void ane_pm_cycle_resume_error_test(struct kunit *test) pm_runtime_put_noidle(ctx.consumer); } +/* + * Exercise the H16 runtime-PM idle-park, wake, system-sleep and unbind model + * against the real Linux runtime-PM and device-link core: one consumer device + * linked to three DART suppliers (DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE) + * plus five attached power-domain devices. + */ +struct ane_h16_rpm_sim { + struct device dev; + struct device *power[5]; + struct device *dart[3]; + struct device_link *links[3]; + /* Serializes simulated power-state and park transitions. */ + struct mutex lock; + bool engine_on; + bool program_ready; + bool parked; + bool slept; + bool in_sleep; + bool pinned; + bool rpm_enabled; + bool rpm_held; + bool rpm_busy; + unsigned int power_downs; + unsigned int power_ups; + unsigned int parks; + unsigned int unparks; + bool dart_active_at_resume; +}; + +static void h16_sim_power_down(struct ane_h16_rpm_sim *s) +{ + int i; + + for (i = ARRAY_SIZE(s->dart); i-- > 0; ) + pm_runtime_put_sync(s->dart[i]); + for (i = ARRAY_SIZE(s->power); i-- > 0; ) + pm_runtime_put_sync(s->power[i]); + WRITE_ONCE(s->engine_on, false); + s->power_downs++; +} + +static int h16_sim_power_up(struct ane_h16_rpm_sim *s) +{ + int i, j, ret; + + for (i = 0; i < ARRAY_SIZE(s->power); i++) { + ret = pm_runtime_resume_and_get(s->power[i]); + if (ret < 0) + goto err_power; + } + for (j = 0; j < ARRAY_SIZE(s->dart); j++) { + ret = pm_runtime_resume_and_get(s->dart[j]); + if (ret < 0) + goto err_dart; + } + WRITE_ONCE(s->engine_on, true); + s->power_ups++; + return 0; +err_dart: + while (j--) + pm_runtime_put_sync(s->dart[j]); +err_power: + while (i--) + pm_runtime_put_sync(s->power[i]); + return ret; +} + +static void h16_sim_unpark(struct ane_h16_rpm_sim *s) +{ + lockdep_assert_held(&s->lock); + if (!s->parked || READ_ONCE(s->in_sleep)) + return; + if (!h16_sim_power_up(s)) + s->unparks++; + WRITE_ONCE(s->parked, false); +} + +static int h16_sim_runtime_suspend(struct device *dev) +{ + struct ane_h16_rpm_sim *s = container_of(dev, struct ane_h16_rpm_sim, dev); + + if (!READ_ONCE(s->rpm_enabled) || !READ_ONCE(s->engine_on)) + return 0; + mutex_lock(&s->lock); + if (!s->engine_on) { + mutex_unlock(&s->lock); + return 0; + } + if (!s->program_ready || READ_ONCE(s->in_sleep)) { + mutex_unlock(&s->lock); + return -EBUSY; + } + if (pm_runtime_autosuspend_expiration(dev)) { + mutex_unlock(&s->lock); + return -EBUSY; + } + h16_sim_power_down(s); + WRITE_ONCE(s->parked, true); + s->parks++; + mutex_unlock(&s->lock); + return 0; +} + +static int h16_sim_runtime_resume(struct device *dev) +{ + struct ane_h16_rpm_sim *s = container_of(dev, struct ane_h16_rpm_sim, dev); + bool all_darts_active = true; + int i; + + for (i = 0; i < ARRAY_SIZE(s->dart); i++) + all_darts_active &= pm_runtime_active(s->dart[i]); + s->dart_active_at_resume = all_darts_active; + + if (!READ_ONCE(s->rpm_enabled) || !READ_ONCE(s->program_ready) || + !READ_ONCE(s->parked)) + return 0; + mutex_lock(&s->lock); + h16_sim_unpark(s); + mutex_unlock(&s->lock); + return 0; +} + +static const struct dev_pm_ops h16_sim_pm_ops = { + .runtime_suspend = h16_sim_runtime_suspend, + .runtime_resume = h16_sim_runtime_resume, +}; + +static const struct device_type h16_sim_type = { + .pm = &h16_sim_pm_ops, +}; + +static void h16_sim_release(struct device *dev) +{ + kfree(container_of(dev, struct ane_h16_rpm_sim, dev)); +} + +static void h16_sim_unregister(void *data) +{ + struct ane_h16_rpm_sim *s = data; + + device_unregister(&s->dev); +} + +static void h16_sim_power_cleanup(void *data) +{ + struct ane_h16_rpm_sim *s = data; + + if (READ_ONCE(s->rpm_enabled)) { + pm_runtime_disable(&s->dev); + pm_runtime_dont_use_autosuspend(&s->dev); + if (s->rpm_held) { + s->rpm_held = false; + pm_runtime_put_noidle(&s->dev); + } + if (s->rpm_busy) { + s->rpm_busy = false; + pm_runtime_put_noidle(&s->dev); + } + WRITE_ONCE(s->rpm_enabled, false); + } + if (READ_ONCE(s->engine_on)) + h16_sim_power_down(s); + pm_runtime_set_suspended(&s->dev); +} + +static struct ane_h16_rpm_sim *h16_sim_create(struct kunit *test, int delay_ms) +{ + static const char * const pd_names[] = { + "h16-ane-sys", "h16-ane-cpu", "h16-ane-mpm", + "h16-ane-td", "h16-ane-base", + }; + static const char * const dart_names[] = { + "h16-ane-dart0", "h16-ane-dart1", "h16-ane-dart2", + }; + struct ane_h16_rpm_sim *s; + int i, ret; + + s = kzalloc_obj(*s); + if (!s) + return NULL; + mutex_init(&s->lock); + device_initialize(&s->dev); + s->dev.release = h16_sim_release; + s->dev.type = &h16_sim_type; + ret = dev_set_name(&s->dev, "h16-ane-rpm-consumer"); + if (!ret) + ret = device_add(&s->dev); + if (ret) { + put_device(&s->dev); + return NULL; + } + if (kunit_add_action_or_reset(test, h16_sim_unregister, s)) + return NULL; + + for (i = 0; i < ARRAY_SIZE(s->power); i++) { + s->power[i] = ane_pm_test_register(test, pd_names[i]); + if (!s->power[i]) + return NULL; + } + for (i = 0; i < ARRAY_SIZE(s->dart); i++) { + s->dart[i] = ane_pm_test_register(test, dart_names[i]); + if (!s->dart[i]) + return NULL; + /* Matches apple_dart_probe_device() supplier links. */ + s->links[i] = device_link_add(&s->dev, s->dart[i], + DL_FLAG_STATELESS | + DL_FLAG_PM_RUNTIME | + DL_FLAG_RPM_ACTIVE); + if (!s->links[i]) + return NULL; + if (kunit_add_action_or_reset(test, ane_pm_test_unlink, s->links[i])) + return NULL; + } + /* LIFO: drop power and disable runtime PM before links/suppliers go. */ + if (kunit_add_action_or_reset(test, h16_sim_power_cleanup, s)) + return NULL; + KUNIT_ASSERT_EQ(test, pm_runtime_set_active(&s->dev), 0); + pm_runtime_get_noresume(&s->dev); + s->rpm_held = true; + pm_runtime_set_autosuspend_delay(&s->dev, delay_ms); + pm_runtime_use_autosuspend(&s->dev); + WRITE_ONCE(s->rpm_enabled, true); + pm_runtime_enable(&s->dev); + + KUNIT_ASSERT_EQ(test, h16_sim_power_up(s), 0); + /* First boot power-up is not counted as an unpark/wake power-up. */ + s->power_ups = 0; + s->pinned = true; + WRITE_ONCE(s->program_ready, true); + return s; +} + +static void h16_sim_wait_darts_suspended(struct kunit *test, struct ane_h16_rpm_sim *s) +{ + int i, tries; + + for (i = 0; i < ARRAY_SIZE(s->dart); i++) { + for (tries = 0; tries < 40 && !pm_runtime_suspended(s->dart[i]); tries++) + usleep_range(10000, 15000); + } +} + +static void h16_sim_wait_suspended(struct kunit *test, struct ane_h16_rpm_sim *s) +{ + int i; + + for (i = 0; i < 40 && !pm_runtime_suspended(&s->dev); i++) + usleep_range(10000, 15000); + pm_runtime_barrier(&s->dev); + KUNIT_ASSERT_TRUE(test, pm_runtime_suspended(&s->dev)); + h16_sim_wait_darts_suspended(test, s); +} + +static void h16_sim_expect_all_off(struct kunit *test, struct ane_h16_rpm_sim *s) +{ + int i; + + KUNIT_EXPECT_TRUE(test, pm_runtime_status_suspended(&s->dev)); + KUNIT_EXPECT_EQ(test, atomic_read(&s->dev.power.usage_count), 0); + for (i = 0; i < ARRAY_SIZE(s->dart); i++) { + KUNIT_EXPECT_TRUE(test, pm_runtime_suspended(s->dart[i])); + KUNIT_EXPECT_EQ(test, atomic_read(&s->dart[i]->power.usage_count), 0); + } + for (i = 0; i < ARRAY_SIZE(s->power); i++) { + KUNIT_EXPECT_TRUE(test, pm_runtime_suspended(s->power[i])); + KUNIT_EXPECT_EQ(test, atomic_read(&s->power[i]->power.usage_count), 0); + } +} + +static int h16_sim_session_wake(struct ane_h16_rpm_sim *s) +{ + int ret; + + if (!READ_ONCE(s->parked)) + return 0; + if (READ_ONCE(s->in_sleep)) + return -EAGAIN; + ret = pm_runtime_resume_and_get(&s->dev); + if (ret < 0) + return ret; + if (READ_ONCE(s->parked)) { + mutex_lock(&s->lock); + h16_sim_unpark(s); + mutex_unlock(&s->lock); + } + if (READ_ONCE(s->parked)) { + pm_runtime_put_sync_suspend(&s->dev); + return -EAGAIN; + } + pm_runtime_mark_last_busy(&s->dev); + pm_runtime_put_autosuspend(&s->dev); + return 0; +} + +/* + * Idle autosuspend parks H16: all five power domains and all three DART + * suppliers drop to suspended with usage_count == 0. Waking resumes the + * DART suppliers before the consumer callback powers the five domains up. + */ +static void ane_pm_h16_idle_park_wake_test(struct kunit *test) +{ + struct ane_h16_rpm_sim *s = h16_sim_create(test, 80); + int i; + + KUNIT_ASSERT_NOT_NULL(test, s); + + /* Hand off boot hold to autosuspend. */ + s->rpm_held = false; + pm_runtime_mark_last_busy(&s->dev); + pm_runtime_put_autosuspend(&s->dev); + + /* Simulate an EXECUTE busy hold blocking suspend while in flight. */ + pm_runtime_get_noresume(&s->dev); + s->rpm_busy = true; + msleep(120); + KUNIT_EXPECT_TRUE(test, pm_runtime_active(&s->dev)); + KUNIT_EXPECT_FALSE(test, s->parked); + + /* End EXECUTE: autosuspend parks consumer, 5 domains and 3 DARTs. */ + s->rpm_busy = false; + pm_runtime_mark_last_busy(&s->dev); + pm_runtime_put_autosuspend(&s->dev); + h16_sim_wait_suspended(test, s); + KUNIT_EXPECT_TRUE(test, s->parked); + KUNIT_EXPECT_FALSE(test, s->engine_on); + KUNIT_EXPECT_EQ(test, s->parks, 1U); + KUNIT_EXPECT_EQ(test, s->power_downs, 1U); + h16_sim_expect_all_off(test, s); + + /* Wake for a request: DARTs resume first, then 5 domains power up. */ + KUNIT_ASSERT_EQ(test, h16_sim_session_wake(s), 0); + KUNIT_EXPECT_TRUE(test, s->dart_active_at_resume); + KUNIT_EXPECT_FALSE(test, s->parked); + KUNIT_EXPECT_TRUE(test, s->engine_on); + KUNIT_EXPECT_EQ(test, s->unparks, 1U); + KUNIT_EXPECT_EQ(test, s->power_ups, 1U); + for (i = 0; i < ARRAY_SIZE(s->power); i++) + KUNIT_EXPECT_TRUE(test, pm_runtime_active(s->power[i])); + for (i = 0; i < ARRAY_SIZE(s->dart); i++) + KUNIT_EXPECT_TRUE(test, pm_runtime_active(s->dart[i])); + + /* Second idle park + wake cycle stays clean and balanced. */ + h16_sim_wait_suspended(test, s); + KUNIT_EXPECT_EQ(test, s->parks, 2U); + KUNIT_EXPECT_EQ(test, s->power_downs, 2U); + h16_sim_expect_all_off(test, s); + + KUNIT_ASSERT_EQ(test, h16_sim_session_wake(s), 0); + KUNIT_EXPECT_EQ(test, s->unparks, 2U); + KUNIT_EXPECT_EQ(test, s->power_ups, 2U); + KUNIT_EXPECT_TRUE(test, s->engine_on); +} + +/* + * System S2R while already parked does no double power_down or double + * power_up and passes the device-suspend backstop. S2R while active powers + * down once, suspends the DARTs, and stays parked on resume (including the + * pm_runtime_forbid fallback wake path). + */ +static void ane_pm_h16_s2r_while_parked_test(struct kunit *test) +{ + struct ane_h16_rpm_sim *s = h16_sim_create(test, 80); + bool running; + + KUNIT_ASSERT_NOT_NULL(test, s); + s->rpm_held = false; + pm_runtime_mark_last_busy(&s->dev); + pm_runtime_put_autosuspend(&s->dev); + h16_sim_wait_suspended(test, s); + KUNIT_ASSERT_EQ(test, s->power_downs, 1U); + + /* S2R prepare while already parked: no second power_down. */ + WRITE_ONCE(s->in_sleep, true); + pm_runtime_get_noresume(&s->dev); + mutex_lock(&s->lock); + if (!s->parked) { + h16_sim_power_down(s); + WRITE_ONCE(s->slept, true); + } + mutex_unlock(&s->lock); + pm_runtime_put_sync_suspend(&s->dev); + + /* Device-suspend backstop must allow sleep while parked. */ + running = s->pinned && READ_ONCE(s->engine_on) && !READ_ONCE(s->slept); + KUNIT_EXPECT_EQ(test, ane_fw_sleep_backstop(running), 0); + KUNIT_EXPECT_EQ(test, s->power_downs, 1U); + KUNIT_EXPECT_FALSE(test, s->slept); + /* Requests during S2R get -EAGAIN without booting. */ + KUNIT_EXPECT_EQ(test, h16_sim_session_wake(s), -EAGAIN); + + /* S2R resume while parked: no power_up, stays parked. */ + WRITE_ONCE(s->in_sleep, false); + KUNIT_EXPECT_EQ(test, s->power_ups, 0U); + KUNIT_EXPECT_TRUE(test, s->parked); + h16_sim_expect_all_off(test, s); + + /* First request after S2R wakes cleanly. */ + KUNIT_ASSERT_EQ(test, h16_sim_session_wake(s), 0); + KUNIT_EXPECT_EQ(test, s->unparks, 1U); + KUNIT_EXPECT_EQ(test, s->power_ups, 1U); + + /* Now S2R while active with runtime PM forbidden (power/control=on). */ + pm_runtime_forbid(&s->dev); + WRITE_ONCE(s->in_sleep, true); + pm_runtime_get_noresume(&s->dev); + mutex_lock(&s->lock); + h16_sim_power_down(s); + WRITE_ONCE(s->slept, true); + mutex_unlock(&s->lock); + pm_runtime_put_sync_suspend(&s->dev); + running = s->pinned && READ_ONCE(s->engine_on) && !READ_ONCE(s->slept); + KUNIT_EXPECT_EQ(test, ane_fw_sleep_backstop(running), 0); + KUNIT_EXPECT_EQ(test, s->power_downs, 2U); + + /* PM_POST_SUSPEND parks the engine; consumer stayed RPM_ACTIVE (forbidden). */ + mutex_lock(&s->lock); + WRITE_ONCE(s->slept, false); + WRITE_ONCE(s->parked, true); + mutex_unlock(&s->lock); + WRITE_ONCE(s->in_sleep, false); + KUNIT_EXPECT_TRUE(test, pm_runtime_active(&s->dev)); + KUNIT_EXPECT_TRUE(test, s->parked); + + /* Fallback unpark path in session_wake boots when RPM never suspended. */ + KUNIT_ASSERT_EQ(test, h16_sim_session_wake(s), 0); + KUNIT_EXPECT_FALSE(test, s->parked); + KUNIT_EXPECT_TRUE(test, s->engine_on); + KUNIT_EXPECT_EQ(test, s->unparks, 2U); + KUNIT_EXPECT_EQ(test, s->power_ups, 2U); + pm_runtime_allow(&s->dev); +} + +/* + * Unbind/remove while parked disables runtime PM without waking the engine or + * double-powering down. + */ +static void ane_pm_h16_unbind_while_parked_test(struct kunit *test) +{ + struct ane_h16_rpm_sim *s = h16_sim_create(test, 20); + + KUNIT_ASSERT_NOT_NULL(test, s); + s->rpm_held = false; + pm_runtime_mark_last_busy(&s->dev); + pm_runtime_put_autosuspend(&s->dev); + h16_sim_wait_suspended(test, s); + KUNIT_ASSERT_EQ(test, s->power_downs, 1U); + KUNIT_ASSERT_EQ(test, s->unparks, 0U); + + /* Remove while parked: stays suspended, no wake or double power-down. */ + pm_runtime_disable(&s->dev); + pm_runtime_dont_use_autosuspend(&s->dev); + WRITE_ONCE(s->rpm_enabled, false); + KUNIT_EXPECT_EQ(test, s->power_downs, 1U); + KUNIT_EXPECT_EQ(test, s->power_ups, 0U); + KUNIT_EXPECT_EQ(test, s->unparks, 0U); + h16_sim_expect_all_off(test, s); +} + +/* + * Pre-RUN unbind/rollback while active drops the device hold, powers down + * the five domains and three DARTs, and releases the supplier device links. + */ +static void ane_pm_h16_unbind_rollback_test(struct kunit *test) +{ + struct ane_h16_rpm_sim *s = h16_sim_create(test, 20); + + KUNIT_ASSERT_NOT_NULL(test, s); + pm_runtime_disable(&s->dev); + pm_runtime_dont_use_autosuspend(&s->dev); + s->rpm_held = false; + pm_runtime_put_noidle(&s->dev); + WRITE_ONCE(s->rpm_enabled, false); + h16_sim_power_down(s); + KUNIT_EXPECT_EQ(test, pm_runtime_set_suspended(&s->dev), 0); + h16_sim_wait_darts_suspended(test, s); + h16_sim_expect_all_off(test, s); +} + static struct kunit_case ane_pm_test_cases[] = { KUNIT_CASE(ane_pm_cycle_domains_test), KUNIT_CASE(ane_pm_cycle_single_test), @@ -235,6 +716,10 @@ static struct kunit_case ane_pm_test_cases[] = { KUNIT_CASE(ane_pm_cycle_supplier_error_test), KUNIT_CASE(ane_pm_cycle_verify_error_test), KUNIT_CASE(ane_pm_cycle_resume_error_test), + KUNIT_CASE(ane_pm_h16_idle_park_wake_test), + KUNIT_CASE(ane_pm_h16_s2r_while_parked_test), + KUNIT_CASE(ane_pm_h16_unbind_while_parked_test), + KUNIT_CASE(ane_pm_h16_unbind_rollback_test), {} }; diff --git a/drivers/accel/ane/ane_t6021_fwload.c b/drivers/accel/ane/ane_t6021_fwload.c index 21e0f2ce7e9dfd..69c7a0adc2c693 100644 --- a/drivers/accel/ane/ane_t6021_fwload.c +++ b/drivers/accel/ane/ane_t6021_fwload.c @@ -13,7 +13,10 @@ * three bound instances). Segment-wise copy * (__TEXT fileoff 0x4000 -> vm 0, __DATA -> its vmaddr; vmsize * tail zero from the coherent alloc). Coherent memory needs no - * explicit cache clean. + * explicit cache clean. The engine maps __TEXT read-only, at + * fw_iova and at the entry alias (ane_t6021_fw_prot(), selected by + * the pinned segment table); DATA and the rest stay read-write. + * The kernel writes TEXT through its CPU mapping only. * 4. Which copy runs. By default the staged copy (own memory). The * option fw_alias_reserved=1 (T6021 only) maps the copy iBoot * preloaded at SEG0/SEGi; probe refuses it unless no-map @@ -74,6 +77,7 @@ #include "ane_t6021.h" #include "ane_t6021_boot.h" #include "ane_fw_validate.h" +#include "ane_t6021_fwmap.h" MODULE_FIRMWARE(ANE_FW_SELENE_NAME); MODULE_FIRMWARE(ANE_FW_BIA_NAME); @@ -236,8 +240,75 @@ static int ane_t6021_pmu_map(struct ane_t6021 *ane, struct iommu_domain *dom) return ret; } +/* The coherent allocation maps every page read-write for the engine at + * fw_iova. Map the __TEXT pages there again, at the same IOVA and PA, + * read-only. The IOVA range stays the DMA API's and the same number of + * bytes stays mapped, so dma_free_coherent() unmaps it as before. + * + * Each step is one 16 KiB DART leaf (the coherent allocation is 16 KiB + * aligned in IOVA and PA, checked below), so iommu_unmap() takes it out + * whole or not at all, and it syncs the IOTLB before it returns. If a page + * can be neither mapped read-only nor put back read-write, the range has a + * hole that dma_free_coherent() would trip on: then the allocation is kept + * (fw_buf cleared, a bounded leak on a failed probe) instead of freed. + */ +static int ane_t6021_fw_staged_protect(struct ane_t6021 *ane) +{ + const struct ane_t602x_soc *soc = of_device_get_match_data(ane->dev); + struct iommu_domain *dom = iommu_get_domain_for_dev(ane->dev); + int rw = IOMMU_READ | IOMMU_WRITE; + size_t unmapped; + u64 off; + int ret; + + if (!dom) + return -ENODEV; + if (dev_is_dma_coherent(ane->dev)) + rw |= IOMMU_CACHE; + for (off = 0; off < ane->fw_size; off += ANE_T6021_FW_ALIAS_PAGE) { + u64 iova = ane->fw_iova + off; + int prot = ane_t6021_fw_prot(soc->fw->segs, ANE_FW_NSEGS, off, + ANE_T6021_FW_ALIAS_PAGE, rw); + phys_addr_t pa; + + if (prot == rw) + continue; + pa = iommu_iova_to_phys(dom, iova); + if (!pa || pa & (ANE_T6021_FW_ALIAS_PAGE - 1)) + return -EFAULT; + unmapped = iommu_unmap(dom, iova, ANE_T6021_FW_ALIAS_PAGE); + if (unmapped != ANE_T6021_FW_ALIAS_PAGE) { + if (unmapped) + goto hole; + return -EIO; + } + ret = iommu_map(dom, iova, pa, ANE_T6021_FW_ALIAS_PAGE, prot, + GFP_KERNEL); + /* Never leave a hole for dma_free_coherent() to trip on. */ + if (ret && iommu_map(dom, iova, pa, ANE_T6021_FW_ALIAS_PAGE, rw, + GFP_KERNEL)) + goto hole; + if (!ret && iommu_iova_to_phys(dom, iova) != pa) + ret = -EIO; + if (ret) { + dev_err(ane->dev, "fwload: TEXT +%#llx read-only map: %d\n", + off, ret); + return ret; + } + } + return 0; + +hole: + dev_err(ane->dev, + "fwload: +%#llx left unmapped, keeping the firmware buffer\n", + off); + ane->fw_buf = NULL; + return -EIO; +} + static int ane_t6021_fw_alias_map(struct ane_t6021 *ane, bool reserved) { + const struct ane_t602x_soc *soc = of_device_get_match_data(ane->dev); struct iommu_domain *dom = iommu_get_domain_for_dev(ane->dev); void __iomem *eng = ane->base[ANE_T6021_REG_ENGINE]; u64 rvbar = readq(eng + ANE_ASC_RVBAR); @@ -332,7 +403,12 @@ static int ane_t6021_fw_alias_map(struct ane_t6021 *ane, bool reserved) } ret = iommu_map(dom, win[w].iova + o, pa, - ANE_T6021_FW_ALIAS_PAGE, prot, + ANE_T6021_FW_ALIAS_PAGE, + ane_t6021_fw_prot(soc->fw->segs, + ANE_FW_NSEGS, + win[w].iova + o - entry, + ANE_T6021_FW_ALIAS_PAGE, + prot), GFP_KERNEL); if (ret) { dev_err(ane->dev, @@ -393,8 +469,11 @@ static int ane_t6021_fw_alias_map(struct ane_t6021 *ane, bool reserved) ret = -EEXIST; goto err_unmap; } - ret = iommu_map(dom, entry + off, pa, - ANE_T6021_FW_ALIAS_PAGE, prot, GFP_KERNEL); + ret = iommu_map(dom, entry + off, pa, ANE_T6021_FW_ALIAS_PAGE, + ane_t6021_fw_prot(soc->fw->segs, ANE_FW_NSEGS, + off, ANE_T6021_FW_ALIAS_PAGE, + prot), + GFP_KERNEL); if (ret) { dev_err(ane->dev, "fwalias: iommu_map +%#llx: %d\n", off, ret); @@ -624,7 +703,9 @@ int ane_t6021_fwload_probe(struct ane_t6021 *ane) "fwload: %s PRELOAD validated + DART-mapped: entry %#llx, iova %pad size %#x\n", img->name, entry, &iova, alloc_size); - ret = reserved ? 0 : ane_t6021_fw_patch(ane, buf); + ret = ane_t6021_fw_staged_protect(ane); + if (!ret && !reserved) + ret = ane_t6021_fw_patch(ane, buf); if (!ret) ret = ane_t6021_fw_alias_map(ane, reserved); if (ret) { diff --git a/drivers/accel/ane/ane_t6021_fwmap.h b/drivers/accel/ane/ane_t6021_fwmap.h new file mode 100644 index 00000000000000..60e0352ae8b0cc --- /dev/null +++ b/drivers/accel/ane/ane_t6021_fwmap.h @@ -0,0 +1,45 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * Engine-side protection of the staged H14 firmware image. + * + * Kept free of device access so the KUnit suite (ane_t6021_fwmap_test.c) + * runs the same code as the loader (ane_t6021_fwload.c). + */ +#ifndef __ANE_T6021_FWMAP_H__ +#define __ANE_T6021_FWMAP_H__ + +#include +#include +#include +#include + +#include "ane_fw_validate.h" + +/* + * IOMMU protection for the engine's mapping of [off, off + len) of the + * staged image, off counted from the image's vm base. A range that lies + * wholly inside the image's __TEXT segment (found by name in the pinned + * segment table) loses IOMMU_WRITE; every other range (DATA, the vmsize + * tail, the extra RAM after the image) keeps prot. This is the device + * side only: the kernel still writes TEXT through its own mapping (the + * DATA base patch, the re-copy before a restart). + */ +static inline int ane_t6021_fw_prot(const struct ane_fw_seg *segs, + unsigned int nsegs, u64 off, u64 len, + int prot) +{ + unsigned int i; + + for (i = 0; i < nsegs; i++) { + const struct ane_fw_seg *s = &segs[i]; + + if (strcmp(s->name, "__TEXT")) + continue; + if (off >= s->vmaddr && len <= s->vmsize && + off - s->vmaddr <= s->vmsize - len) + return prot & ~IOMMU_WRITE; + } + return prot; +} + +#endif /* __ANE_T6021_FWMAP_H__ */ diff --git a/drivers/accel/ane/ane_t6021_fwmap_test.c b/drivers/accel/ane/ane_t6021_fwmap_test.c new file mode 100644 index 00000000000000..8f44fe2bd817de --- /dev/null +++ b/drivers/accel/ane/ane_t6021_fwmap_test.c @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include +#include + +#include "ane_t6021_fwmap.h" + +#define RW (IOMMU_READ | IOMMU_WRITE) + +/* Every 16 KiB page of the pinned __TEXT is read-only for the engine, every + * page from the DATA vmaddr to the end of the allocation stays read-write. + */ +static void fw_prot_image(struct kunit *test, const struct ane_fw_image *img) +{ + const struct ane_fw_seg *text = &img->segs[0]; + u64 end = ANE_FW_BUF_SIZE + SZ_2M; + u64 off; + + KUNIT_ASSERT_STREQ(test, text->name, "__TEXT"); + KUNIT_ASSERT_EQ(test, img->segs[1].vmaddr, text->vmaddr + text->vmsize); + for (off = 0; off < end; off += SZ_16K) { + int want = off < text->vmsize ? IOMMU_READ : RW; + + KUNIT_EXPECT_EQ_MSG(test, ane_t6021_fw_prot(img->segs, ANE_FW_NSEGS, + off, SZ_16K, RW), + want, "%s +%#llx", img->name, off); + KUNIT_EXPECT_EQ_MSG(test, ane_t6021_fw_prot(img->segs, ANE_FW_NSEGS, + off, SZ_16K, + RW | IOMMU_CACHE), + want | IOMMU_CACHE, "%s +%#llx", img->name, off); + } +} + +static void fw_prot_selene_test(struct kunit *test) +{ + fw_prot_image(test, &ane_fw_selene); +} + +static void fw_prot_bia_test(struct kunit *test) +{ + fw_prot_image(test, &ane_fw_bia); +} + +/* TEXT is found by name, wherever the table puts it; a range that is not + * wholly inside it (here one that runs into DATA) stays writable. + */ +static void fw_prot_by_table_test(struct kunit *test) +{ + static const struct ane_fw_seg segs[ANE_FW_NSEGS] = { + { 0x000000, 0x100000, 0x004000, 0x100000, "__DATA" }, + { 0x100000, 0x008000, 0x104000, 0x008000, "__TEXT" }, + }; + + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, 0, SZ_16K, RW), RW); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, 0x100000, + SZ_16K, RW), IOMMU_READ); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, 0x104000, + SZ_16K, RW), IOMMU_READ); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, 0x0fc000, + SZ_16K, RW), RW); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, 0x104000, + SZ_32K, RW), RW); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, 0x108000, + SZ_16K, RW), RW); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, U64_MAX - 1, + SZ_16K, RW), RW); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, 1, 0x100000, SZ_16K, RW), RW); +} + +static struct kunit_case fwmap_cases[] = { + KUNIT_CASE(fw_prot_selene_test), + KUNIT_CASE(fw_prot_bia_test), + KUNIT_CASE(fw_prot_by_table_test), + {} +}; + +static struct kunit_suite fwmap_suite = { + .name = "ane-t6021-fwmap", + .test_cases = fwmap_cases, +}; + +kunit_test_suite(fwmap_suite); + +MODULE_LICENSE("Dual MIT/GPL"); +MODULE_DESCRIPTION("ANE H14 staged firmware mapping protection tests"); diff --git a/drivers/accel/ane/ane_t6021_lifetime.h b/drivers/accel/ane/ane_t6021_lifetime.h index db0689f2609d8e..0d20f3687c41fa 100644 --- a/drivers/accel/ane/ane_t6021_lifetime.h +++ b/drivers/accel/ane/ane_t6021_lifetime.h @@ -25,8 +25,10 @@ * the next poll and the cursor does not move. * * A program is shared by every file that loaded byte-identical sections and - * outlives the firmware instance it was loaded into. Each file holds one - * reference per program it loaded, by an opaque kernel ID that never changes. + * outlives the firmware instance it was loaded into. It owns a kernel copy of + * its sections, made at PROG_LOAD, and the firmware only ever reads that + * copy. Each file holds one reference per program it loaded, by an opaque + * kernel ID that never changes. * Whether the program is in the firmware right now (resident) is separate: * * - When the last file holding a program closes, it is unloaded: @@ -50,6 +52,7 @@ #define __ANE_T6021_LIFETIME_H__ #include +#include #include #include #include @@ -210,14 +213,108 @@ struct ane_t6021_prog { enum ane_t6021_prog_state state; bool resident; /* LOADed into the current firmware instance */ u64 last_use; - /* The program's own reference on each section buffer, or NULL, and - * the IOVA and size its LOAD names for that section. + /* The program's own kernel copy of each section, or NULL, and the + * IOVA and size its LOAD names for that section. */ void *sec[ANE_T6021_PROG_SECS]; u64 sec_iova[ANE_T6021_PROG_SECS]; u64 sec_size[ANE_T6021_PROG_SECS]; }; +/* + * The sections of a program while PROG_LOAD builds it, by slot (id - 1). + * Each is a kernel copy no client can map and the engine maps read-only: + * the cache key, the TD check and every LOAD of the program read the copy, + * never the caller's buffer, so what was keyed and checked is what the + * firmware reads. PROG_LOAD also keys a view of the caller's buffers (mem + * the BOs) to find a program already loaded; that view is never loaded. + */ +struct ane_t6021_secs { + void *mem[ANE_T6021_PROG_SECS]; /* driver allocation, NULL: no section */ + u8 *cpu[ANE_T6021_PROG_SECS]; + u64 iova[ANE_T6021_PROG_SECS]; + u64 size[ANE_T6021_PROG_SECS]; +}; + +/* Copy @size bytes of the caller's section at @src into @cpu, the kernel + * allocation @mem at @iova, and record it at @slot. @src is not read again. + */ +static inline void ane_t6021_secs_fill(struct ane_t6021_secs *s, + unsigned int slot, void *mem, u8 *cpu, + u64 iova, const u8 *src, u64 size) +{ + memcpy(cpu, src, size); + s->mem[slot] = mem; + s->cpu[slot] = cpu; + s->iova[slot] = iova; + s->size[slot] = size; +} + +/* + * The cache key of the copies: SHA-256 over each section's id, size and + * bytes in slot order, so identical bytes give the same program. Returns + * ane_t6021_td_flags_check() of the TD stream copy. + */ +static inline int ane_t6021_secs_key(const struct ane_t6021_secs *s, + u8 digest[SHA256_DIGEST_SIZE]) +{ + struct sha256_ctx sha; + unsigned int i; + int td_flags = 0; + + sha256_init(&sha); + for (i = 0; i < ANE_T6021_PROG_SECS; i++) { + u64 hdr[2] = { i + 1, s->size[i] }; + + if (!s->mem[i]) + continue; + sha256_update(&sha, (const u8 *)hdr, sizeof(hdr)); + sha256_update(&sha, s->cpu[i], s->size[i]); + if (i + 1 == ANE_T6021_SEC_TEXT) + td_flags = ane_t6021_td_flags_check(s->cpu[i], + s->size[i]); + } + sha256_final(&sha, digest); + return td_flags; +} + +/* The program takes the copies; @s keeps none. */ +static inline void ane_t6021_secs_give(struct ane_t6021_secs *s, + struct ane_t6021_prog *p) +{ + unsigned int i; + + for (i = 0; i < ANE_T6021_PROG_SECS; i++) { + p->sec[i] = s->mem[i]; + p->sec_iova[i] = s->iova[i]; + p->sec_size[i] = s->size[i]; + } + memset(s, 0, sizeof(*s)); +} + +/* + * The section records of a LOAD_PROGRAM (0x200) into the zeroed command + * @cmd: one 0x30-byte record per section at its identity slot from +0x08, + * flags bit0 = 1, id at +0x04, iova at +0x18, size at +0x20. The same + * records serve the first load and every reload. + */ +static inline void ane_t6021_load_records(u8 *cmd, + const struct ane_t6021_prog *p) +{ + unsigned int i; + + for (i = 0; i < ANE_T6021_PROG_SECS; i++) { + u8 *rec = cmd + 0x8 + i * 0x30; + + if (!p->sec[i]) + continue; + *(__le32 *)(rec + 0x00) = cpu_to_le32(1); + *(__le32 *)(rec + 0x04) = cpu_to_le32(i + 1); + *(__le64 *)(rec + 0x18) = cpu_to_le64(p->sec_iova[i]); + *(__le64 *)(rec + 0x20) = cpu_to_le64(p->sec_size[i]); + } +} + struct ane_t6021_progtab { struct ane_t6021_prog progs[ANE_T6021_MAX_PROGRAMS]; unsigned int hi; /* slots below this index may be in use */ @@ -235,7 +332,7 @@ struct ane_t6021_fdprogs { struct ane_t6021_progtab_ops { /* Unload from the firmware; zero only when every command was acked. */ int (*unload)(void *ctx, struct ane_t6021_prog *p); - /* The firmware no longer reads the sections: drop their references. */ + /* The firmware no longer reads the sections: free their copies. */ void (*release)(void *ctx, struct ane_t6021_prog *p); /* LOAD the program again; on success set fw_prog_id. */ int (*load)(void *ctx, struct ane_t6021_prog *p); @@ -297,8 +394,8 @@ static inline bool ane_t6021_prog_unloadable(const struct ane_t6021_prog *p) /* * Claim a slot for a program about to be loaded. It starts HELD so nothing - * can find it, and it owns the section references taken before the LOAD is - * sent: if the LOAD fails, the buffers stay held with it. Make room in the + * can find it, and it owns the section copies given to it before the LOAD is + * sent: if the LOAD fails, the copies stay held with it. Make room in the * firmware before this: a restart frees unreferenced slots, this one too. */ static inline struct ane_t6021_prog * @@ -582,7 +679,7 @@ static inline int ane_t6021_progtab_ensure(struct ane_t6021_progtab *t, /* * A verified firmware restart dropped every program and process. Programs * no file holds are freed; held ones become LIVE and non-resident, keep - * their kernel IDs and section references, and load again on next use. + * their kernel IDs and section copies, and load again on next use. */ static inline void ane_t6021_progtab_restarted(struct ane_t6021_progtab *t, const struct ane_t6021_progtab_ops *ops, diff --git a/drivers/accel/ane/ane_t6021_lifetime_test.c b/drivers/accel/ane/ane_t6021_lifetime_test.c index 4654a2d2fa9011..b2620a351ca814 100644 --- a/drivers/accel/ane/ane_t6021_lifetime_test.c +++ b/drivers/accel/ane/ane_t6021_lifetime_test.c @@ -111,6 +111,119 @@ static void td_flags_test(struct kunit *test) KUNIT_EXPECT_EQ(test, ane_t6021_td_flags_check(td, 2), 0); } +/* Fill @s with a TD stream (slot 2) and a constant section (slot 6) of @buf. */ +static void fill_two(struct kunit *test, struct ane_t6021_secs *s, + const u8 *buf, u8 **copy) +{ + copy[0] = kunit_kzalloc(test, 0x90, GFP_KERNEL); + copy[1] = kunit_kzalloc(test, 0x40, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, copy[0]); + KUNIT_ASSERT_NOT_NULL(test, copy[1]); + ane_t6021_secs_fill(s, ANE_T6021_SEC_TEXT - 1, copy[0], copy[0], + 0x40000000, buf, 0x90); + ane_t6021_secs_fill(s, 6, copy[1], copy[1], 0x40004000, buf + 0x90, + 0x40); +} + +static void check_records(struct kunit *test, const u8 *cmd) +{ + unsigned int i; + + for (i = 0; i < ANE_T6021_PROG_SECS; i++) { + const u8 *rec = cmd + 0x8 + i * 0x30; + u32 want_id = 0; + u64 want_iova = 0, want_size = 0; + + if (i == ANE_T6021_SEC_TEXT - 1) { + want_id = ANE_T6021_SEC_TEXT; + want_iova = 0x40000000; + want_size = 0x90; + } else if (i == 6) { + want_id = 7; + want_iova = 0x40004000; + want_size = 0x40; + } + KUNIT_EXPECT_EQ(test, get_unaligned_le32(rec), want_id ? 1U : 0U); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(rec + 0x04), want_id); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(rec + 0x18), want_iova); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(rec + 0x20), want_size); + } +} + +/* + * PROG_LOAD keys, checks and names a kernel copy of the caller's sections. + * The caller's buffer stays writable to it after the load, so a change + * there must reach neither the key, nor the TD check, nor the memory any + * LOAD of the program (first or reload) names. + */ +static void prog_sections_copied_test(struct kunit *test) +{ + struct ane_t6021_secs *secs, *ref, *now; + u8 digest[SHA256_DIGEST_SIZE], want[SHA256_DIGEST_SIZE]; + u8 changed[SHA256_DIGEST_SIZE]; + u8 *buf, *orig, *cmd, *copy[2], *ref_copy[2], *now_copy[2]; + struct ane_t6021_prog *p; + unsigned int i; + + buf = kunit_kzalloc(test, 0xd0, GFP_KERNEL); + cmd = kunit_kzalloc(test, 0x1c0, GFP_KERNEL); + p = kunit_kzalloc(test, sizeof(*p), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + KUNIT_ASSERT_NOT_NULL(test, cmd); + KUNIT_ASSERT_NOT_NULL(test, p); + secs = kunit_kzalloc(test, sizeof(*secs), GFP_KERNEL); + ref = kunit_kzalloc(test, sizeof(*ref), GFP_KERNEL); + now = kunit_kzalloc(test, sizeof(*now), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, secs); + KUNIT_ASSERT_NOT_NULL(test, ref); + KUNIT_ASSERT_NOT_NULL(test, now); + /* A well-formed single-task TD stream, then constants. */ + put_task(buf, 0x10, 0x20, 0x2a); + memset(buf + 0x90, 0x5a, 0x40); + orig = kunit_kzalloc(test, 0xd0, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, orig); + memcpy(orig, buf, 0xd0); + + fill_two(test, secs, buf, copy); + /* The caller rewrites its buffer: a TD stream the check refuses and + * other constants. + */ + put32(buf + 0x18, 0x08); + memset(buf + 0x90, 0xa5, 0x40); + + /* Key and check see the bytes as they were at the copy. */ + KUNIT_EXPECT_EQ(test, ane_t6021_secs_key(secs, digest), 0); + fill_two(test, ref, orig, ref_copy); + KUNIT_EXPECT_EQ(test, ane_t6021_secs_key(ref, want), 0); + KUNIT_EXPECT_EQ(test, memcmp(digest, want, sizeof(want)), 0); + /* The rewritten bytes would have been refused and keyed apart. */ + fill_two(test, now, buf, now_copy); + KUNIT_EXPECT_EQ(test, ane_t6021_secs_key(now, changed), -EINVAL); + KUNIT_EXPECT_NE(test, memcmp(digest, changed, sizeof(changed)), 0); + + /* The program owns the copies; the LOAD names them, not the buffer. */ + ane_t6021_secs_give(secs, p); + for (i = 0; i < ANE_T6021_PROG_SECS; i++) + KUNIT_EXPECT_NULL(test, secs->mem[i]); + KUNIT_EXPECT_PTR_EQ(test, p->sec[ANE_T6021_SEC_TEXT - 1], (void *)copy[0]); + KUNIT_EXPECT_PTR_EQ(test, p->sec[6], (void *)copy[1]); + ane_t6021_load_records(cmd, p); + check_records(test, cmd); + KUNIT_EXPECT_EQ(test, memcmp(copy[0], orig, 0x90), 0); + KUNIT_EXPECT_EQ(test, memcmp(copy[1], orig + 0x90, 0x40), 0); + KUNIT_EXPECT_NE(test, memcmp(copy[0], buf, 0x90), 0); + + /* A reload after an eviction or restart names the same copies, whatever + * the caller's buffer holds by then. + */ + memset(buf, 0xff, 0xd0); + memset(cmd, 0, 0x1c0); + ane_t6021_load_records(cmd, p); + check_records(test, cmd); + KUNIT_EXPECT_EQ(test, memcmp(copy[0], orig, 0x90), 0); + KUNIT_EXPECT_EQ(test, memcmp(copy[1], orig + 0x90, 0x40), 0); +} + /* A fake firmware. Records every command class and fails on demand. */ struct fake_fw { struct kunit *test; @@ -856,6 +969,7 @@ static struct kunit_case lifetime_cases[] = { KUNIT_CASE(mring_classify_test), KUNIT_CASE(legtab_reuse_test), KUNIT_CASE(td_flags_test), + KUNIT_CASE(prog_sections_copied_test), KUNIT_CASE(progtab_shared_unload_test), KUNIT_CASE(multitask_unloaded_at_close_test), KUNIT_CASE(progtab_failed_unload_holds_test), diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index b565f31112ae79..5ec41205d36e05 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -9,8 +9,9 @@ * CREATE_PROCESS 0x202, PROCEDURE_CALL 0x204) driven through the * ioctls in this file; * - DRM accel: BO_INIT/BO_FREE plus PROG_LOAD/PROC_CREATE/EXEC per - * include/uapi/drm/ane_accel.h (ABI 2). Sections ride BOs the - * user supplies; one global mutex serializes every firmware + * include/uapi/drm/ane_accel.h (ABI 2). Sections arrive in BOs + * the user supplies and PROG_LOAD copies them into kernel memory; + * one global mutex serializes every firmware * command; completion = the legacy exchange's reply PLUS the * firmware's finish event on the IO_T2H ring. EXEC also returns the * fw's target-to-host slots (drained after every exchange). @@ -72,6 +73,7 @@ #include #include #include +#include #include #include #include @@ -347,9 +349,9 @@ struct ane_t6021_fd { /* Per-file handle counter and every per-fd list against same-fd concurrent * ioctls. A BO whose IOVA reached the firmware (fw_ref) never goes back to - * the kernel: a program section is held until a verified reset, an io BO is parked - * for reuse (see ane_t6021_bo_release). Every other BO frees at its last - * reference. + * the kernel: an io BO is parked for reuse (see ane_t6021_bo_release). Every + * other BO frees at its last reference. Program sections are not BOs: a + * program owns a kernel copy of them (struct ane_t6021_sec_copy). * * Per-BO cap: matvec weights emitted by the H14 compiler are bounded by * `reduction * columns * 2`, which reaches 20 MiB at (K,N)=(2048,5120). @@ -357,7 +359,8 @@ struct ane_t6021_fd { * and any H14 softmax/reduction with an 8 MiB table. Total BO bytes * across all fds are capped separately (bo_total_max_mb) by an atomic * counter, enforced at alloc and released when the memory is really - * freed. Program sections stay held until a verified reset, and one large model's + * freed. The section copies of the programs count against the same cap: + * they stay until the firmware dropped the program, and one large model's * programs alone can hold gigabytes. * A cap of 0 refuses every BO_INIT with -ENOSPC; there is no unlimited * value. Every BO also needs IOVA below 4 GiB (32-bit DMA mask), so @@ -365,7 +368,6 @@ struct ane_t6021_fd { * The 16 KiB alignment check is unchanged: every DMA site assumes it. */ #define ANE_T6021_BO_MAX SZ_1G -#define ANE_T6021_BO_HASH_CHUNK SZ_1M struct ane_t6021_bo { struct list_head node; @@ -376,10 +378,7 @@ struct ane_t6021_bo { dma_addr_t dma; size_t size; u64 fw_epoch; - u32 prog_refs; /* program sections using this BO */ bool fw_ref; /* the firmware received this IOVA */ - bool fw_program; /* a loaded program keeps this IOVA */ - bool fw_io; /* published as a CALL buffer */ struct device *dev; }; @@ -429,11 +428,10 @@ static u64 ane_t6021_bo_epoch = 1; static DEFINE_SPINLOCK(ane_t6021_bo_pool_lock); /* Final put: the last handle or mapping is gone. The firmware must never - * see a freed IOVA, so a current-generation fw_ref BO is retained: a program - * section stays held, because a cached firmware program keeps reading - * it; an io BO goes to the pool, unless a quarantined firmware may still - * write it. Every other BO frees here, so the BO cap bounds only the - * memory the firmware may touch. + * see a freed IOVA, so a current-generation fw_ref BO is retained: an io BO + * goes to the pool, unless a quarantined firmware may still write it. Every + * other BO frees here, so the BO cap bounds only the memory the firmware + * may touch. */ static void ane_t6021_bo_destroy(struct ane_t6021_bo *bo) { @@ -451,7 +449,7 @@ static void ane_t6021_bo_release(struct kref *ref) spin_lock(&ane_t6021_bo_pool_lock); release = !bo->fw_ref || bo->fw_epoch != ane_t6021_bo_epoch; if (!release) { - if (bo->fw_program || atomic_read(&ane_t6021_quarantined)) + if (atomic_read(&ane_t6021_quarantined)) list_add_tail(&bo->node, &ane_t6021_bo_held); else list_add_tail(&bo->node, &ane_t6021_bo_pool); @@ -481,18 +479,10 @@ static void ane_t6021_bo_new_epoch(void) } /* bo_lock and a live handle protect the BO while its IOVA is published. */ -static void ane_t6021_bo_publish(struct ane_t6021_bo *bo, bool program) +static void ane_t6021_bo_publish(struct ane_t6021_bo *bo) { - if (bo->fw_epoch != ane_t6021_bo_epoch) { - bo->fw_program = false; - bo->fw_io = false; - } bo->fw_epoch = ane_t6021_bo_epoch; bo->fw_ref = true; - if (program) - bo->fw_program = true; - else - bo->fw_io = true; } /* A parked io BO of SIZE's page-aligned size, or NULL. */ @@ -1471,13 +1461,14 @@ static int ane_rtclient_command(struct ane_rtclient *ane, /* ---- LOAD / CREATE / CALL wrappers ---- */ /* Two loads of byte-identical sections share one program and one process. - * The key is SHA-256 over every section's id, size and bytes, so a client - * can only reach a program whose bytes it also supplied, and every file - * holds a reference on each program it loaded. The last close unloads a - * program, at most ANE_T6021_FW_RESIDENT_MAX programs are resident, and a - * program a file still holds loads again on its next use after it was - * unloaded for room or a restart (ane_t6021_lifetime.h). Protected by - * ane_t6021_fw_lock. + * The key is SHA-256 over every section's id, size and bytes, taken over the + * program's own kernel copy of the sections that the firmware reads and no + * client can map or change, so a client can only reach a program whose bytes + * it also supplied. Every file holds a reference on each program it loaded. + * The last close unloads a program, at most ANE_T6021_FW_RESIDENT_MAX + * programs are resident, and a program a file still holds loads again on + * its next use after it was unloaded for room or a restart + * (ane_t6021_lifetime.h). Protected by ane_t6021_fw_lock. */ static struct ane_t6021_progtab ane_t6021_progtab; static struct ane_fw_ids ane_t6021_ids; @@ -1560,28 +1551,137 @@ static int ane_t6021_prog_unload_op(void *ctx, struct ane_t6021_prog *p) return ret; } -/* The firmware no longer reads the sections: drop the program's references. - * A BO no other program uses stops being a program BO, and is freed or - * pooled by the usual rule at its last put. +/* A program's kernel copy of one section: kernel pages mapped for the same + * device as the BOs, never mapped to userspace and not written after + * PROG_LOAD filled it. The pages are mapped DMA_TO_DEVICE, which the DMA + * API maps read-only in the IOMMU: the engine, which runs every client's + * jobs in the same DART domain, can read the copy but not change it after + * it was checked. Counted against bo_total_max_mb like a BO. */ +struct ane_t6021_sec_copy { + struct device *dev; + struct page **pages; + unsigned int npages; + struct sg_table sgt; + void *cpu; + dma_addr_t dma; + size_t size; /* allocated bytes, page aligned */ +}; + +static void ane_t6021_sec_copy_put_pages(struct ane_t6021_sec_copy *c) +{ + unsigned int i; + + for (i = 0; i < c->npages; i++) + if (c->pages[i]) + __free_page(c->pages[i]); + kvfree(c->pages); +} + +/* The mapping must be one IOVA range: a LOAD record names iova + size. */ +static bool ane_t6021_sec_copy_contiguous(const struct ane_t6021_sec_copy *c) +{ + struct scatterlist *sg; + dma_addr_t next = c->dma; + unsigned int i; + + for_each_sgtable_dma_sg(&c->sgt, sg, i) { + if (sg_dma_address(sg) != next) + return false; + next += sg_dma_len(sg); + } + return next - c->dma == c->size; +} + +static struct ane_t6021_sec_copy * +ane_t6021_sec_copy_alloc(struct ane_rtclient *ane, u64 size) +{ + struct ane_t6021_sec_copy *c; + size_t alloc; + unsigned int i; + int ret = -ENOMEM; + + /* No BO holds more, so a larger section is refused anyway. */ + if (size > ANE_T6021_BO_MAX) + return ERR_PTR(-EINVAL); + alloc = PAGE_ALIGN(max_t(size_t, size, 1)); + if (atomic64_add_return(alloc, &ane_t6021_bo_total_bytes) > + (s64)bo_total_max_mb << 20) { + atomic64_sub(alloc, &ane_t6021_bo_total_bytes); + return ERR_PTR(-ENOSPC); + } + c = kzalloc_obj(*c); + if (!c) + goto err_account; + c->dev = ane->dev; + c->size = alloc; + c->npages = alloc >> PAGE_SHIFT; + c->pages = kvcalloc(c->npages, sizeof(*c->pages), GFP_KERNEL); + if (!c->pages) + goto err_free; + /* Zeroed: the device reads the tail past the section too. */ + for (i = 0; i < c->npages; i++) { + c->pages[i] = alloc_page(GFP_KERNEL | __GFP_ZERO); + if (!c->pages[i]) + goto err_pages; + } + if (sg_alloc_table_from_pages(&c->sgt, c->pages, c->npages, 0, alloc, + GFP_KERNEL)) + goto err_pages; + if (dma_map_sgtable(c->dev, &c->sgt, DMA_TO_DEVICE, 0)) + goto err_sgt; + c->dma = sg_dma_address(c->sgt.sgl); + /* The same IOVA rules as a BO (see ane_t6021_bo_init_locked()). */ + if (!ane_t6021_sec_copy_contiguous(c) || !IS_ALIGNED(c->dma, SZ_16K) || + (ane->fw && !ane_t6021_fw_alias_iova_ok(ane->fw, c->dma, alloc))) { + ret = -ERANGE; + goto err_unmap; + } + c->cpu = vmap(c->pages, c->npages, VM_MAP, PAGE_KERNEL); + if (!c->cpu) + goto err_unmap; + return c; + +err_unmap: + dma_unmap_sgtable(c->dev, &c->sgt, DMA_TO_DEVICE, 0); +err_sgt: + sg_free_table(&c->sgt); +err_pages: + ane_t6021_sec_copy_put_pages(c); +err_free: + kfree(c); +err_account: + atomic64_sub(alloc, &ane_t6021_bo_total_bytes); + return ERR_PTR(ret); +} + +/* Hand what the CPU wrote to the copy over to the device. */ +static void ane_t6021_sec_copy_sync(struct ane_t6021_sec_copy *c) +{ + dma_sync_sgtable_for_device(c->dev, &c->sgt, DMA_TO_DEVICE); +} + +static void ane_t6021_sec_copy_free(struct ane_t6021_sec_copy *c) +{ + vunmap(c->cpu); + dma_unmap_sgtable(c->dev, &c->sgt, DMA_TO_DEVICE, 0); + sg_free_table(&c->sgt); + ane_t6021_sec_copy_put_pages(c); + atomic64_sub(c->size, &ane_t6021_bo_total_bytes); + kfree(c); +} + +/* The firmware no longer reads the sections: free the program's copies. */ static void ane_t6021_prog_release_op(void *ctx, struct ane_t6021_prog *p) { unsigned int i; - mutex_lock(&ane_t6021_bo_lock); for (i = 0; i < ANE_T6021_PROG_SECS; i++) { - struct ane_t6021_bo *bo = p->sec[i]; - - if (!bo) + if (!p->sec[i]) continue; + ane_t6021_sec_copy_free(p->sec[i]); p->sec[i] = NULL; - if (!WARN_ON(!bo->prog_refs) && !--bo->prog_refs) { - bo->fw_program = false; - bo->fw_ref = bo->fw_io; - } - kref_put(&bo->refcount, ane_t6021_bo_release); } - mutex_unlock(&ane_t6021_bo_lock); } /* @@ -1590,8 +1690,8 @@ static void ane_t6021_prog_release_op(void *ctx, struct ane_t6021_prog *p) * at slot 6 and slot 5 stays empty when id 6 is absent). flags bit0 = 1, id * at +0x04, iova at +0x18, size at +0x20. The firmware writes the program ID * back at +0x1b8. Used for the first load and for every reload after an - * eviction or a restart; the section IOVAs are republished to the current - * firmware generation before the doorbell. + * eviction or a restart; every record names the program's kernel copy of + * the section, which lives until the firmware dropped the program for good. */ static int ane_rtclient_send_load(struct ane_rtclient *ane, struct ane_t6021_prog *p) @@ -1599,29 +1699,13 @@ static int ane_rtclient_send_load(struct ane_rtclient *ane, struct ane_legacy_buffer *command = ane->cmd_buf; u8 *cmd; u32 fw_prog; - unsigned int i; int ret; if (!command || atomic_read(&ane_t6021_quarantined)) return -ENODEV; cmd = command->cpu; memset(cmd, 0, SZ_16K); - mutex_lock(&ane_t6021_bo_lock); - for (i = 0; i < ANE_T6021_PROG_SECS; i++) { - u64 slot_base = 0x8 + (u64)i * 0x30; - - if (!p->sec[i]) - continue; - /* The firmware may read the section any time after the - * doorbell, including during a timeout. - */ - ane_t6021_bo_publish(p->sec[i], true); - *(u32 *)(cmd + slot_base + 0x00) = cpu_to_le32(1); - *(u32 *)(cmd + slot_base + 0x04) = cpu_to_le32(i + 1); - *(u64 *)(cmd + slot_base + 0x18) = cpu_to_le64(p->sec_iova[i]); - *(u64 *)(cmd + slot_base + 0x20) = cpu_to_le64(p->sec_size[i]); - } - mutex_unlock(&ane_t6021_bo_lock); + ane_t6021_load_records(cmd, p); *(u32 *)(cmd + 0x1b8) = cpu_to_le32(U32_MAX); /* The LOAD command is 0x1C0 bytes: the nine 0x30 records end at * 0x1b8, ProgramId at +0x1b8, 8 bytes of zero tail. @@ -1692,11 +1776,28 @@ static const struct ane_t6021_progtab_ops ane_t6021_progtab_ops = { .restart = ane_t6021_prog_restart_op, }; +/* The BO of this file that holds section @sec, or NULL. Under bo_lock. */ +static struct ane_t6021_bo * +ane_t6021_sec_bo_locked(struct ane_t6021_fd *fd, + const struct drm_ane_section *sec) +{ + struct ane_t6021_bo *b; + + lockdep_assert_held(&ane_t6021_bo_lock); + list_for_each_entry(b, &fd->bos, node) { + if (b->handle != sec->bo_handle) + continue; + if (sec->size > b->size || sec->offset > b->size - sec->size) + return NULL; + return b; + } + return NULL; +} + /* Build a LOAD_PROGRAM (0x200) message in a kernel-owned buffer. The - * section bytes live in the BOs the user supplied (section_ptr), the - * generic binds (bufferId, bo_handle, size) patch the generic section - * at iova +0x20 / +0x28 once the BO is copied. Returns 0 with - * *prog_id set on success. + * section bytes are copied out of the BOs the user supplied (section_ptr) + * into kernel memory the program owns; the generic binds are accepted + * and unused (see below). Returns 0 with *prog_id set on success. */ static int ane_rtclient_load_program(struct ane_rtclient *ane, struct drm_file *file, @@ -1707,6 +1808,7 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, struct drm_ane_generic_bind *binds; struct ane_t6021_fd *fd = file->driver_priv; struct ane_t6021_prog *cached, *prog = NULL; + struct ane_t6021_secs secs = {}; bool sent = false; int td_flags = 0; u32 key, gen; @@ -1770,64 +1872,77 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, } } - /* Identical sections share one firmware program (see the table). - * A constant section can reach 20 MiB (the H14 (K,N)=(2048,5120) - * matvec), so feed the hash in ANE_T6021_BO_HASH_CHUNK-sized slices - * under bo_lock: a single sha256_update of a 20 MiB buffer would - * rely on a 20 MiB stack argument list and has no upper bound on - * the chunk that the BO could supply. + /* Copy every section out of the caller's buffer into kernel memory no + * client can map, then key and check the copies: identical sections + * share one firmware program (see the table), and the bytes keyed and + * checked here are the bytes every LOAD of the program names. Each + * copy is made with one read of the buffer, under bo_lock. + */ + /* Every section must name a BO of this file that holds it. A program + * already in the table has its own checked copies, so look it up from + * the caller's bytes first: loading it again takes no copies and no + * part of bo_total_max_mb. Bytes changed meanwhile only change the + * key; they are never what the firmware reads. */ { - struct sha256_ctx sha; - void *scratch; + struct ane_t6021_secs view = {}; - sha256_init(&sha); - scratch = kvmalloc(ANE_T6021_BO_HASH_CHUNK, GFP_KERNEL); - if (!scratch) { - ret = -ENOMEM; + mutex_lock(&ane_t6021_bo_lock); + for (i = 0; i < user->section_count; i++) { + struct ane_t6021_bo *bo; + unsigned int slot = sections[i].id - 1; + + bo = ane_t6021_sec_bo_locked(fd, §ions[i]); + if (!bo) + break; + view.mem[slot] = bo; + view.cpu[slot] = (u8 *)bo->cpu + sections[i].offset; + view.size[slot] = sections[i].size; + } + if (i == user->section_count) + ane_t6021_secs_key(&view, digest); + mutex_unlock(&ane_t6021_bo_lock); + if (i < user->section_count) { + ret = -EINVAL; goto out; } - for (i = 0; i < user->section_count; i++) { - struct ane_t6021_bo *bo = NULL, *b; - u64 hdr[2] = { sections[i].id, sections[i].size }; - size_t left; + } + cached = ane_t6021_prog_find(digest); + if (cached) { + ret = ane_t6021_fdprogs_ref(&ane_t6021_progtab, &fd->progs, + cached); + if (!ret) + *prog_id = cached->prog_id; + goto out; + } + for (i = 0; i < user->section_count; i++) { + struct ane_t6021_sec_copy *c; + struct ane_t6021_bo *bo; + unsigned int slot = sections[i].id - 1; - mutex_lock(&ane_t6021_bo_lock); - list_for_each_entry(b, &fd->bos, node) { - if (b->handle == sections[i].bo_handle) { - bo = b; - break; - } - } - if (!bo || sections[i].size > bo->size || - sections[i].offset > bo->size - sections[i].size) { - mutex_unlock(&ane_t6021_bo_lock); - kvfree(scratch); - ret = -EINVAL; - goto out; - } - sha256_update(&sha, (const u8 *)hdr, sizeof(hdr)); - /* Checked in the same snapshot as the key. */ - if (sections[i].id == ANE_T6021_SEC_TEXT) - td_flags = ane_t6021_td_flags_check((const u8 *)bo->cpu + - sections[i].offset, - sections[i].size); - left = sections[i].size; - while (left) { - size_t n = min_t(size_t, left, - ANE_T6021_BO_HASH_CHUNK); - - memcpy(scratch, (const u8 *)bo->cpu + - sections[i].offset + - (sections[i].size - left), n); - sha256_update(&sha, scratch, n); - left -= n; - } - mutex_unlock(&ane_t6021_bo_lock); + c = ane_t6021_sec_copy_alloc(ane, sections[i].size); + if (IS_ERR(c)) { + ret = PTR_ERR(c); + goto out; + } + /* Looked up again: the BO may have been freed meanwhile. */ + mutex_lock(&ane_t6021_bo_lock); + bo = ane_t6021_sec_bo_locked(fd, §ions[i]); + if (bo) + ane_t6021_secs_fill(&secs, slot, c, c->cpu, c->dma, + (const u8 *)bo->cpu + + sections[i].offset, + sections[i].size); + mutex_unlock(&ane_t6021_bo_lock); + if (bo) + ane_t6021_sec_copy_sync(c); + if (!bo) { + ane_t6021_sec_copy_free(c); + ret = -EINVAL; + goto out; } - kvfree(scratch); - sha256_final(&sha, digest); } + td_flags = ane_t6021_secs_key(&secs, digest); /* A program that opens or closes on the wrong task wedges the firmware * for every client; refuse it before the firmware sees it. */ @@ -1873,37 +1988,10 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, goto out; } gen = ane_t6021_progtab.gen; - /* The record slot IS the section identity (slot = id - 1). The program - * takes its own reference on each section buffer, kept until the - * firmware dropped the program for good (or forever if uncertain). + /* The program owns the copies from here, until the firmware dropped it + * for good (or forever if uncertain). */ - for (i = 0; i < user->section_count; i++) { - struct ane_t6021_bo *bo = NULL, *b; - unsigned int slot = sections[i].id - 1; - - mutex_lock(&ane_t6021_bo_lock); - list_for_each_entry(b, &fd->bos, node) { - if (b->handle == sections[i].bo_handle) { - bo = b; - break; - } - } - if (bo && sections[i].size <= bo->size && - sections[i].offset <= bo->size - sections[i].size) { - kref_get(&bo->refcount); - bo->prog_refs++; - prog->sec[slot] = bo; - prog->sec_iova[slot] = bo->dma + sections[i].offset; - prog->sec_size[slot] = sections[i].size; - } else { - bo = NULL; - } - mutex_unlock(&ane_t6021_bo_lock); - if (!bo) { - ret = -EINVAL; - goto out; - } - } + ane_t6021_secs_give(&secs, prog); /* Generic binds are accepted for ABI compatibility and unused: the * LOAD record already carries iova + size, and the generic section * image is prepared by userspace (generic.bin). @@ -1929,6 +2017,10 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, /* The firmware never saw these IOVAs: give the reservation back. */ if (prog && !sent) ane_t6021_progtab_cancel(prog, &ane_t6021_progtab_ops, ane); + /* Copies no program took (a cached program, or a failed load). */ + for (i = 0; i < ANE_T6021_PROG_SECS; i++) + if (secs.mem[i]) + ane_t6021_sec_copy_free(secs.mem[i]); kfree(sections); kfree(binds); return ret; @@ -2203,7 +2295,7 @@ static int ane_rtclient_procedure_call(struct ane_rtclient *ane, /* Keep this IO element out of the reuse pool until completion. */ kref_get(&bo->refcount); exec_bos[pinned++] = bo; - ane_t6021_bo_publish(bo, false); + ane_t6021_bo_publish(bo); iova = bo->dma; mutex_unlock(&ane_t6021_bo_lock); *(u32 *)(cmd + slot_base + 0x00) = cpu_to_le32(1); @@ -3867,8 +3959,19 @@ static int __maybe_unused ane_rtclient_sleep_pm_resume(struct device *dev) return ane_t6021_pm_resume(ane_rtclient_get_sleep_pm(dev)); } +static int __maybe_unused ane_rtclient_runtime_suspend(struct device *dev) +{ + return ane_rtclient_is_platform(dev) ? ane_fw_platform_runtime_suspend(dev) : 0; +} + +static int __maybe_unused ane_rtclient_runtime_resume(struct device *dev) +{ + return ane_rtclient_is_platform(dev) ? ane_fw_platform_runtime_resume(dev) : 0; +} + static const struct dev_pm_ops __maybe_unused ane_rtclient_sleep_pm = { SYSTEM_SLEEP_PM_OPS(ane_rtclient_sleep_pm_suspend, ane_rtclient_sleep_pm_resume) + RUNTIME_PM_OPS(ane_rtclient_runtime_suspend, ane_rtclient_runtime_resume, NULL) }; static int ane_rtclient_probe_inner(struct platform_device *pdev, @@ -4412,6 +4515,10 @@ static void ane_rtclient_remove(struct platform_device *pdev) "remove HELD: no teardown — reboot reclaims\n"); } +static const struct ane_t602x_soc ane_t8122_soc = { + .platform = &ane_t8122_platform, +}; + static const struct ane_t602x_soc ane_h16_soc = { .platform = &ane_h16_platform, }; @@ -4437,6 +4544,7 @@ static const struct of_device_id ane_rtclient_of_match[] = { { .compatible = "apple,t6021-ane", .data = &ane_t6021_soc }, { .compatible = "apple,t6022-ane", .data = &ane_t6022_soc }, { .compatible = "apple,t8112-ane", .data = &ane_t8112_soc }, + { .compatible = "apple,t8122-ane", .data = &ane_t8122_soc }, { .compatible = "apple,t6041-ane", .data = &ane_h16_soc }, { .compatible = "apple,t8132-ane", .data = &ane_t8132_soc }, { .compatible = "apple,t8140-ane", .data = &ane_h17_soc }, @@ -4526,7 +4634,7 @@ static struct platform_driver ane_rtclient_driver = { .name = "ane_t6021", .of_match_table = ane_rtclient_of_match, .dev_groups = ane_t6021_stats_groups, - .pm = pm_sleep_ptr(&ane_rtclient_sleep_pm), + .pm = pm_ptr(&ane_rtclient_sleep_pm), .suppress_bind_attrs = true, }, .probe = ane_rtclient_probe, diff --git a/drivers/accel/ane/ane_tm.c b/drivers/accel/ane/ane_tm.c index 609a6e650b7626..0175a18f0a79ae 100644 --- a/drivers/accel/ane/ane_tm.c +++ b/drivers/accel/ane/ane_tm.c @@ -465,8 +465,7 @@ int ane_tm_execute(struct ane_device *ane, struct ane_request *req) err = -EIO; break; } - err = ane_dart_drain_fault(ane, fault_iova, scratch, - &ane->scratch_pages); + err = ane_dart_drain_fault(ane, fault_iova); if (err) break; /* The retried transaction now completes; poll on. */ diff --git a/drivers/base/swnode.c b/drivers/base/swnode.c index 84a77ffa3dc4bb..07c586973c47fe 100644 --- a/drivers/base/swnode.c +++ b/drivers/base/swnode.c @@ -29,6 +29,8 @@ struct swnode { struct fwnode_handle fwnode; const struct software_node *node; int id; + /* Device the managed node's lifetime is tied to. */ + struct device *owner; /* hierarchy */ struct ida child_ids; @@ -37,7 +39,6 @@ struct swnode { struct swnode *parent; unsigned int allocated:1; - unsigned int managed:1; }; static DEFINE_IDA(swnode_root_ids); @@ -1145,7 +1146,7 @@ int device_create_managed_software_node(struct device *dev, if (IS_ERR(fwnode)) return PTR_ERR(fwnode); - to_swnode(fwnode)->managed = true; + to_swnode(fwnode)->owner = dev; set_secondary_fwnode(dev, fwnode); if (device_is_registered(dev)) @@ -1206,12 +1207,16 @@ void software_node_notify_remove(struct device *dev) if (!device_match_fwnode(dev, &swnode->fwnode) && swnode->fwnode.dev == dev) swnode->fwnode.dev = NULL; - swnode_put(swnode); - - if (swnode->managed) { + /* + * Check ownership before dropping this device's reference: when the + * owner is already gone, the put below may free the node. + */ + if (swnode->owner == dev) { set_secondary_fwnode(dev, NULL); swnode_put(swnode); } + + swnode_put(swnode); } void __init software_node_init(void) diff --git a/drivers/base/test/Kconfig b/drivers/base/test/Kconfig index 1ecf0791241a1b..d48d7016f8ca1f 100644 --- a/drivers/base/test/Kconfig +++ b/drivers/base/test/Kconfig @@ -20,6 +20,6 @@ config DRIVER_PE_KUNIT_TEST default KUNIT_ALL_TESTS config DRIVER_SWNODE_KUNIT_TEST - tristate "KUnit Tests for software node fw_devlink links" if !KUNIT_ALL_TESTS + tristate "KUnit Tests for software nodes" if !KUNIT_ALL_TESTS depends on KUNIT default KUNIT_ALL_TESTS diff --git a/drivers/base/test/Makefile b/drivers/base/test/Makefile index 9ced7bbd569fc4..b37ec934e8ae24 100644 --- a/drivers/base/test/Makefile +++ b/drivers/base/test/Makefile @@ -8,3 +8,4 @@ obj-$(CONFIG_DRIVER_PE_KUNIT_TEST) += property-entry-test.o CFLAGS_property-entry-test.o += $(DISABLE_STRUCTLEAK_PLUGIN) obj-$(CONFIG_DRIVER_SWNODE_KUNIT_TEST) += swnode-devlink-test.o +obj-$(CONFIG_DRIVER_SWNODE_KUNIT_TEST) += swnode-managed-test.o diff --git a/drivers/base/test/swnode-managed-test.c b/drivers/base/test/swnode-managed-test.c new file mode 100644 index 00000000000000..9ea46c95535740 --- /dev/null +++ b/drivers/base/test/swnode-managed-test.c @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the lifetime of managed software nodes. + * + * A node created with device_create_managed_software_node() belongs to one + * device, but other devices may carry the same fwnode (a child that reuses + * its parent's node, a gpiochip's gdev->dev, an i2c adapter). Removing any + * of them must drop only that device's reference, in either order, and the + * node must be freed exactly once after the last one is gone. + * + * The use-after-free and double put these tests guard against are silent + * without CONFIG_KASAN; with it, KASAN fails the running test. + */ + +#include +#include +#include + +#include + +static const struct property_entry swnode_managed_props[] = { + PROPERTY_ENTRY_U32("test-value", 42), + { } +}; + +static void swnode_managed_dev_release(struct device *dev) +{ + kfree(dev); +} + +static struct device *swnode_managed_dev_add(struct kunit *test, + const char *name, + struct fwnode_handle *fwnode) +{ + struct device *dev; + int ret; + + dev = kzalloc_obj(*dev); + KUNIT_ASSERT_NOT_NULL(test, dev); + + device_initialize(dev); + dev->release = swnode_managed_dev_release; + device_set_node(dev, fwnode); + + ret = dev_set_name(dev, "%s", name); + if (!ret) + ret = device_add(dev); + if (ret) { + put_device(dev); + KUNIT_FAIL_AND_ABORT(test, "adding %s failed: %d\n", name, ret); + } + + return dev; +} + +/* Add the owner, give it a managed node, add a second device sharing it. */ +static void swnode_managed_setup(struct kunit *test, struct device **owner, + struct device **sharer) +{ + struct fwnode_handle *fwnode; + int ret; + + *owner = swnode_managed_dev_add(test, "swnode-managed-owner", NULL); + + ret = device_create_managed_software_node(*owner, swnode_managed_props, + NULL); + if (ret) { + device_unregister(*owner); + KUNIT_FAIL_AND_ABORT(test, "creating the node failed: %d\n", ret); + } + + fwnode = dev_fwnode(*owner); + KUNIT_ASSERT_TRUE(test, is_software_node(fwnode)); + + *sharer = swnode_managed_dev_add(test, "swnode-managed-sharer", fwnode); +} + +static void swnode_managed_expect_value(struct kunit *test, struct device *dev) +{ + u32 val = 0; + + KUNIT_EXPECT_EQ(test, device_property_read_u32(dev, "test-value", &val), + 0); + KUNIT_EXPECT_EQ(test, val, 42); +} + +/* + * The usual order: the sharer goes first. It must not take the owner's + * reference with it, or the owner's removal frees the node and then puts + * it again. + */ +static void swnode_managed_sharer_removed_first(struct kunit *test) +{ + struct device *owner, *sharer; + + swnode_managed_setup(test, &owner, &sharer); + + device_unregister(sharer); + + KUNIT_EXPECT_TRUE(test, is_software_node(dev_fwnode(owner))); + swnode_managed_expect_value(test, owner); + + device_unregister(owner); +} + +/* + * The owner goes first. The sharer keeps the node alive through its own + * reference, and its removal drops the last one: nothing may read the node + * after that. + */ +static void swnode_managed_owner_removed_first(struct kunit *test) +{ + struct device *owner, *sharer; + + swnode_managed_setup(test, &owner, &sharer); + + device_unregister(owner); + + KUNIT_EXPECT_TRUE(test, is_software_node(dev_fwnode(sharer))); + swnode_managed_expect_value(test, sharer); + + device_unregister(sharer); +} + +static struct kunit_case swnode_managed_test_cases[] = { + KUNIT_CASE(swnode_managed_sharer_removed_first), + KUNIT_CASE(swnode_managed_owner_removed_first), + { } +}; + +static struct kunit_suite swnode_managed_test_suite = { + .name = "software-node-managed", + .test_cases = swnode_managed_test_cases, +}; + +kunit_test_suite(swnode_managed_test_suite); + +MODULE_DESCRIPTION("Test module for managed software node lifetime"); +MODULE_LICENSE("GPL"); diff --git a/drivers/bluetooth/Kconfig b/drivers/bluetooth/Kconfig index 002a8985ca04fd..08c6af1c39d38a 100644 --- a/drivers/bluetooth/Kconfig +++ b/drivers/bluetooth/Kconfig @@ -345,6 +345,19 @@ config BT_HCIBCM4377 Say Y here to compile support for HCI BCM4377 family devices into the kernel or say M to compile it as module (hci_bcm4377). +config BT_HCIBCM4377_KUNIT_TEST + bool "KUnit tests for the HCI BCM4377 PCIe driver" if !KUNIT_ALL_TESTS + depends on KUNIT=y && BT_HCIBCM4377 + default KUNIT_ALL_TESTS + help + Build KUnit tests into the BCM4377 family PCIe driver. They check, + without radio hardware, that a transfer ring is filled at the + host's own producer index whatever the shared ring state holds, + and that an event longer than its completion entry's footer is + dropped. + + If unsure, say N. + config BT_HCIBPA10X tristate "HCI BPA10x USB driver" depends on BT_HCIUART diff --git a/drivers/bluetooth/btcentauri.c b/drivers/bluetooth/btcentauri.c index 11bbc9d0cc6d1e..fb827b10a2a9fc 100644 --- a/drivers/bluetooth/btcentauri.c +++ b/drivers/bluetooth/btcentauri.c @@ -49,9 +49,13 @@ static bool arm_le_data_rings = true; module_param(arm_le_data_rings, bool, 0444); MODULE_PARM_DESC(arm_le_data_rings, "Arm native Beta LE rings for radio bring-up"); -static bool arm_auxiliary_rings; +static bool arm_auxiliary_rings = true; module_param(arm_auxiliary_rings, bool, 0444); -MODULE_PARM_DESC(arm_auxiliary_rings, "Diagnostic: arm remaining native Beta resources and capture received frames privately"); +MODULE_PARM_DESC(arm_auxiliary_rings, "Arm Beta's ACL data rings"); + +static bool diagnostic_capture; +module_param(diagnostic_capture, bool, 0444); +MODULE_PARM_DESC(diagnostic_capture, "Diagnostic: arm every auxiliary ring and capture received frames privately; requires the auxiliary rings"); static bool native_startup; module_param(native_startup, bool, 0444); @@ -73,7 +77,7 @@ static bool accept_list; module_param(accept_list, bool, 0444); MODULE_PARM_DESC(accept_list, "Let the controller filter LE scans by its accept list (off: report its size as 0, the host filters)"); -static bool enable_acl; +static bool enable_acl = true; module_param(enable_acl, bool, 0444); MODULE_PARM_DESC(enable_acl, "Experimental ACL data delivery; requires LE and auxiliary rings"); @@ -90,8 +94,8 @@ struct cen_aux_spec { bool receive; }; -/* Host native Beta inventory; each resource is opt-in until target-qualified. - * HCI and LE rings remain in their existing, separately qualified arenas. +/* Beta's auxiliary rings. Only the ACL rings (2 and 8) are armed by default; the + * others only with diagnostic_capture. HCI and LE rings have their own arenas. */ static const struct cen_aux_spec cen_aux_specs[] = { { 2, 9, 2592, false }, /* ACL TX */ @@ -110,6 +114,7 @@ static const struct cen_aux_spec cen_aux_specs[] = { struct cen_aux_state { u32 offset, packets; u16 head, post; + bool opened; }; struct cen_bt { @@ -318,11 +323,14 @@ static int cen_aux_start(struct cen_bt *bt) return -ENOSPC; state->offset = offset; offset = ALIGN(offset + length, SZ_4K); + if (!diagnostic_capture && spec->id != 2 && spec->id != 8) + continue; ret = cen_open_ring(bt, spec->id, spec->slots, state->offset, spec->footer); if (ret) { dev_err(&bt->pdev->dev, "Auxiliary ring %u open failed: %d\n", spec->id, ret); return ret; } + state->opened = true; if (!spec->receive) continue; for (slot = 0; slot < spec->slots - 1; slot++) @@ -343,7 +351,7 @@ static int cen_aux_drain(struct cen_bt *bt, bool repost) u16 tail; int budget = spec->slots; - if (!spec->receive) + if (!state->opened || !spec->receive) continue; tail = cen_tail(bt, spec->id); if (tail >= spec->slots) @@ -951,7 +959,7 @@ static int cen_status_show(struct seq_file *s, void *unused) bt->capture_used, bt->capture_records, bt->capture_dropped); if (arm_auxiliary_rings) for (i = 0; i < ARRAY_SIZE(cen_aux_specs); i++) - if (cen_aux_specs[i].receive) + if (cen_aux_specs[i].receive && bt->aux[i].opened) seq_printf(s, "aux_rx ring=%u packets=%u consumed=%u device_tail=%u\n", cen_aux_specs[i].id, bt->aux[i].packets, bt->aux[i].head, cen_tail(bt, cen_aux_specs[i].id)); @@ -1007,9 +1015,15 @@ static int cen_probe(struct pci_dev *pdev, const struct pci_device_id *id) struct cen_bt *bt; struct hci_dev *hdev; int ret; + struct pci_host_bridge *bridge = pci_find_host_bridge(pdev->bus); - if (!(of_machine_is_compatible("apple,j813") || of_machine_is_compatible("apple,j815") || - of_machine_is_compatible("apple,j873g")) || + /* + * The T6050 transport (btcentauri_t6050.c) owns every N1 function behind + * an "apple,t6050-pcie" host, as in centauri_pci.c. Any other host is + * ours; the firmware and IPC state are checked below. + */ + if ((bridge && bridge->dev.parent && + of_device_is_compatible(bridge->dev.parent->of_node, "apple,t6050-pcie")) || PCI_FUNC(pdev->devfn) != 2) return -ENODEV; bt = devm_kzalloc(&pdev->dev, sizeof(*bt), GFP_KERNEL); @@ -1022,6 +1036,8 @@ static int cen_probe(struct pci_dev *pdev, const struct pci_device_id *id) skb_queue_head_init(&bt->le_txq); if (enable_acl && (!arm_le_data_rings || !arm_auxiliary_rings)) return -EINVAL; + if (diagnostic_capture && !arm_auxiliary_rings) + return -EINVAL; if (native_hrb && (!native_startup || !enable_acl)) return -EINVAL; INIT_DELAYED_WORK(&bt->poll, cen_poll); @@ -1034,10 +1050,15 @@ static int cen_probe(struct pci_dev *pdev, const struct pci_device_id *id) if (ret) return ret; bt->bar = pcim_iomap_table(pdev)[0]; - if (readl(bt->bar + 0x18) != 2 || readl(bt->bar) != 0) - return dev_err_probe(&pdev->dev, -EBUSY, - "Beta requires running firmware and unowned IPC (exec=%u ipc=%u)\n", - readl(bt->bar + 0x18), readl(bt->bar)); + /* + * The function appears with the N1's IPC start, before Beta's firmware runs. + * apple_centauri attaches it again once that firmware is up. + */ + if (readl(bt->bar + 0x18) != 2 || readl(bt->bar) != 0) { + dev_info(&pdev->dev, "waiting for Beta's firmware (exec=%u ipc=%u)\n", + readl(bt->bar + 0x18), readl(bt->bar)); + return -ENXIO; + } ret = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(40)); if (ret) return ret; @@ -1045,7 +1066,7 @@ static int cen_probe(struct pci_dev *pdev, const struct pci_device_id *id) if (!bt->arena) return -ENOMEM; memset(bt->arena, 0, CEN_ARENA_SIZE); - if (arm_auxiliary_rings) { + if (diagnostic_capture) { bt->capture = kvzalloc(CEN_CAPTURE_SIZE, GFP_KERNEL); if (!bt->capture) { ret = -ENOMEM; @@ -1164,7 +1185,13 @@ static int cen_suspend(struct device *dev) bt->transport_paused = true; mutex_unlock(&bt->lock); cancel_delayed_work_sync(&bt->poll); - if (of_machine_is_compatible("apple,j813") && bt->ipc_requested) { + /* + * Tell Beta's firmware the host is going to sleep on every N1 board, as + * Alpha does. Only a running firmware can take the request; one that + * isn't running has nothing to quiesce. + */ + if (bt->ipc_requested && readl(bt->bar + 0x18) == 2 && + readl(bt->bar) == 2) { bt->transport_sleep_sent = true; ret = cen_transport_state(bt, true); if (ret) diff --git a/drivers/bluetooth/btcentauri_t6050.c b/drivers/bluetooth/btcentauri_t6050.c index b436effc29ba81..8f2f21da04ddf0 100644 --- a/drivers/bluetooth/btcentauri_t6050.c +++ b/drivers/bluetooth/btcentauri_t6050.c @@ -443,6 +443,29 @@ static void cen_fixup_scan_response(u8 *event, size_t length) } } +static bool cen_rx_pending(struct cen_bt *bt) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cen_aux_specs); i++) { + if (!bt->aux[i].opened || !cen_aux_specs[i].receive) + continue; + if (bt->aux[i].head != cen_tail(bt, cen_aux_specs[i].id)) + return true; + } + if (bt->le_rx_head != cen_tail(bt, 10)) + return true; + return bt->rx_head != cen_tail(bt, 7); +} + +static bool cen_tx_ready(struct cen_bt *bt, struct sk_buff_head *queue, + u16 ring, u16 slots, u16 head) +{ + if (skb_queue_empty(queue)) + return false; + return (head + 1) % slots != cen_tail(bt, ring); +} + static void cen_io_work(struct work_struct *work) { struct cen_bt *bt = container_of(work, struct cen_bt, io_work); @@ -536,6 +559,12 @@ static void cen_io_work(struct work_struct *work) cen_transmit(bt, &bt->le_txq, 4, CEN_LE_SLOTS, CEN_LE_TX, CEN_LE_FOOTER, &bt->le_tx_head))) goto protocol_error; + if (cen_rx_pending(bt) || + cen_tx_ready(bt, &bt->txq, 1, CEN_TX_SLOTS, bt->tx_head) || + cen_tx_ready(bt, &bt->acl_txq, 2, cen_aux_specs[0].slots, + bt->acl_tx_head) || + cen_tx_ready(bt, &bt->le_txq, 4, CEN_LE_SLOTS, bt->le_tx_head)) + schedule_work(&bt->io_work); goto unlock; protocol_error: bt->running = false; @@ -815,6 +844,8 @@ static int cen_request_irqs(struct cen_bt *bt) return 0; } +static int cen_transport_state(struct cen_bt *bt, bool asleep); + /* * Called with the participant device locked, outside Control's boot_lock. Keep * the transport alive through HCI unregister: its close may send final commands. @@ -824,11 +855,23 @@ static int cen_request_irqs(struct cen_bt *bt) static int cen_quiesce(void *data) { struct cen_bt *bt = data; + int wake_ret = 0; if (bt->host_quiesced) return 0; + if (bt->transport_sleep_sent) { + bt->transport_sleep_sent = false; + wake_ret = cen_transport_state(bt, false); + if (wake_ret) + dev_warn(&bt->pdev->dev, + "Beta ACIPC host wake failed during teardown (%d)\n", + wake_ret); + } mutex_lock(&bt->lock); bt->quiescing = true; + if (wake_ret) + bt->running = false; + WRITE_ONCE(bt->transport_paused, false); mutex_unlock(&bt->lock); if (bt->hci_registered) { hci_unregister_dev(bt->hdev); @@ -1153,9 +1196,11 @@ static int cen_suspend_noirq(struct device *dev) if (!bt->transport_sleep_sent || !pm_suspend_via_firmware() || !pdev->pm_cap) return 0; if (!pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmctrl)) { - pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, - (pmctrl & ~PCI_PM_CTRL_STATE_MASK) | - PCI_D3hot | PCI_PM_CTRL_PME_ENABLE); + pmctrl &= ~(PCI_PM_CTRL_STATE_MASK | PCI_PM_CTRL_PME_ENABLE); + pmctrl |= (__force u16)PCI_D3hot; + if (device_may_wakeup(dev) && READ_ONCE(bt->running)) + pmctrl |= PCI_PM_CTRL_PME_ENABLE; + pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, pmctrl); mdelay(pdev->d3hot_delay); } return 0; @@ -1181,7 +1226,7 @@ static int cen_resume_noirq(struct device *dev) } if (pdev->pm_cap && !pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmctrl) && - (pmctrl & PCI_PM_CTRL_STATE_MASK) != PCI_D0) { + (pmctrl & PCI_PM_CTRL_STATE_MASK) != (__force u16)PCI_D0) { pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, pmctrl & ~PCI_PM_CTRL_STATE_MASK); mdelay(pdev->d3hot_delay); diff --git a/drivers/bluetooth/hci_bcm4377.c b/drivers/bluetooth/hci_bcm4377.c index 02cc8fccbc27c2..b29e3ab61e34af 100644 --- a/drivers/bluetooth/hci_bcm4377.c +++ b/drivers/bluetooth/hci_bcm4377.c @@ -5,6 +5,7 @@ * Copyright (C) The Asahi Linux Contributors */ +#include #include #include #include @@ -440,6 +441,7 @@ struct bcm4377_transfer_ring { size_t mapped_payload_size; u8 completion_ring; u16 n_entries; + u16 head; u8 generation; bool sync; @@ -671,6 +673,19 @@ static void bcm4377_ring_doorbell(struct bcm4377_data *bcm4377, u8 doorbell, iowrite32(db, bcm4377->bar0 + BCM4377_BAR0_DOORBELL); } +/* + * The producer index of a transfer ring is kept by the host. The copy in + * ring_state is shared with the device and only ever written here, never + * read back, so what the device writes there cannot move the slot the host + * fills next. + */ +static void bcm4377_set_xfer_head(struct bcm4377_data *bcm4377, + struct bcm4377_transfer_ring *ring, u16 head) +{ + ring->head = head; + bcm4377->ring_state->xfer_ring_head[ring->ring_id] = cpu_to_le16(head); +} + static int bcm4377_extract_msgid(struct bcm4377_data *bcm4377, struct bcm4377_transfer_ring *ring, u16 raw_msgid, u8 *msgid) @@ -699,7 +714,7 @@ static int bcm4377_extract_msgid(struct bcm4377_data *bcm4377, static void bcm4377_handle_event(struct bcm4377_data *bcm4377, struct bcm4377_transfer_ring *ring, u16 raw_msgid, u8 entry_flags, u8 type, - void *payload, size_t len) + void *payload, size_t len, size_t footer_size) { struct sk_buff *skb; u16 head; @@ -728,6 +743,12 @@ static void bcm4377_handle_event(struct bcm4377_data *bcm4377, } payload = ring->payloads + msgid * ring->mapped_payload_size; + } else if (len > footer_size) { + /* The payload is in the completion entry's footer. */ + dev_warn(&bcm4377->pdev->dev, + "invalid footer payload len in event for ring %d: %zu > %zu\n", + ring->ring_id, len, footer_size); + goto out; } skb = bt_skb_alloc(len, GFP_ATOMIC); @@ -739,9 +760,8 @@ static void bcm4377_handle_event(struct bcm4377_data *bcm4377, hci_recv_frame(bcm4377->hdev, skb); out: - head = le16_to_cpu(bcm4377->ring_state->xfer_ring_head[ring->ring_id]); - head = (head + 1) % ring->n_entries; - bcm4377->ring_state->xfer_ring_head[ring->ring_id] = cpu_to_le16(head); + head = (ring->head + 1) % ring->n_entries; + bcm4377_set_xfer_head(bcm4377, ring, head); bcm4377_ring_doorbell(bcm4377, ring->doorbell, head); @@ -831,17 +851,17 @@ static void bcm4377_handle_completion(struct bcm4377_data *bcm4377, case BCM4377_XFER_RING_HCI_D2H: bcm4377_handle_event(bcm4377, &bcm4377->hci_d2h_ring, msg_id, entry->flags, HCI_EVENT_PKT, data, - data_len); + data_len, ring->payload_size); break; case BCM4377_XFER_RING_SCO_D2H: bcm4377_handle_event(bcm4377, &bcm4377->sco_d2h_ring, msg_id, entry->flags, HCI_SCODATA_PKT, data, - data_len); + data_len, ring->payload_size); break; case BCM4377_XFER_RING_ACL_D2H: bcm4377_handle_event(bcm4377, &bcm4377->acl_d2h_ring, msg_id, entry->flags, HCI_ACLDATA_PKT, data, - data_len); + data_len, ring->payload_size); break; default: @@ -855,26 +875,31 @@ static void bcm4377_handle_completion(struct bcm4377_data *bcm4377, static void bcm4377_poll_completion_ring(struct bcm4377_data *bcm4377, struct bcm4377_completion_ring *ring) { - u16 tail; __le16 *heads = bcm4377->ring_state->completion_ring_head; __le16 *tails = bcm4377->ring_state->completion_ring_tail; + u16 head, tail, i; if (!ring->enabled) return; + /* Sample the producer index after the interrupt status read. */ + dma_rmb(); + head = le16_to_cpu(READ_ONCE(heads[ring->ring_id])); + if (head >= ring->n_entries) { + dev_warn_ratelimited(&bcm4377->pdev->dev, + "invalid head %u for completion ring %u\n", + head, ring->ring_id); + return; + } + tail = le16_to_cpu(tails[ring->ring_id]); dev_dbg(&bcm4377->pdev->dev, "completion ring #%d: head: %d, tail: %d\n", ring->ring_id, - le16_to_cpu(heads[ring->ring_id]), tail); - - while (tail != le16_to_cpu(READ_ONCE(heads[ring->ring_id]))) { - /* - * ensure the CPU doesn't speculate through the comparison. - * otherwise it might already read the (empty) queue entry - * before the updated head has been loaded and checked. - */ - dma_rmb(); + head, tail); + /* Read the published entries after observing the device's head. */ + dma_rmb(); + for (i = 0; tail != head && i < ring->n_entries; i++) { bcm4377_handle_completion(bcm4377, ring, tail); tail = (tail + 1) % ring->n_entries; @@ -984,7 +1009,7 @@ static int bcm4377_enqueue(struct bcm4377_data *bcm4377, spin_lock_irqsave(&ring->lock, flags); - head = le16_to_cpu(bcm4377->ring_state->xfer_ring_head[ring->ring_id]); + head = ring->head; tail = le16_to_cpu(bcm4377->ring_state->xfer_ring_tail[ring->ring_id]); new_head = (head + 1) % ring->n_entries; @@ -1041,8 +1066,7 @@ static int bcm4377_enqueue(struct bcm4377_data *bcm4377, dev_dbg(&bcm4377->pdev->dev, "updating head for transfer queue #%d to %d\n", ring->ring_id, new_head); - bcm4377->ring_state->xfer_ring_head[ring->ring_id] = - cpu_to_le16(new_head); + bcm4377_set_xfer_head(bcm4377, ring, new_head); if (!ring->sync) bcm4377_ring_doorbell(bcm4377, ring->doorbell, new_head); @@ -1147,7 +1171,7 @@ static int bcm4377_create_transfer_ring(struct bcm4377_data *bcm4377, msg.flags = cpu_to_le16(flags); msg.footer_size = ring->payload_size / 4; - bcm4377->ring_state->xfer_ring_head[ring->ring_id] = 0; + bcm4377_set_xfer_head(bcm4377, ring, 0); bcm4377->ring_state->xfer_ring_tail[ring->ring_id] = 0; ring->generation++; spin_unlock_irqrestore(&ring->lock, spinlock_flags); @@ -1180,8 +1204,7 @@ static int bcm4377_create_transfer_ring(struct bcm4377_data *bcm4377, * to reply by acknowledging them in the completion ring */ if (ring->virtual || ring->d2h_buffers_only) { - bcm4377->ring_state->xfer_ring_head[ring->ring_id] = - cpu_to_le16(0xf); + bcm4377_set_xfer_head(bcm4377, ring, 0xf); bcm4377_ring_doorbell(bcm4377, ring->doorbell, 0xf); } @@ -1450,6 +1473,7 @@ static int bcm4377_pci_reset(struct bcm4377_data *bcm4377) WRITE_ONCE(bcm4377->rti_status, 0); memset(bcm4377->ring_state, 0, sizeof(*bcm4377->ring_state)); + bcm4377->control_h2d_ring.head = 0; bcm4377->control_h2d_ring.generation = 0; bcm4377->control_ack_ring.enabled = false; bitmap_zero(bcm4377->control_h2d_ring.msgids, @@ -1941,12 +1965,40 @@ static int bcm4377_hci_set_bdaddr(struct hci_dev *hdev, const bdaddr_t *bdaddr) return 0; } +/* + * The ACL transfer ring takes at most MAX_ACL_PAYLOAD_SIZE bytes per entry + * (HCI_MAX_ACL_SIZE of data), and bcm4377_enqueue() refuses anything larger. + * The core fragments ACL data to the MTUs the controller reports, so a + * controller that reports more than the ring takes would have every larger + * fragment dropped. Fragment to what the ring takes instead. + */ +static void bcm4377_clamp_acl_mtu(struct hci_dev *hdev) +{ + struct bcm4377_data *bcm4377 = hci_get_drvdata(hdev); + + if (hdev->acl_mtu > HCI_MAX_ACL_SIZE) { + dev_info(&bcm4377->pdev->dev, + "controller ACL MTU %u exceeds the ACL ring's %u, using %u\n", + hdev->acl_mtu, HCI_MAX_ACL_SIZE, HCI_MAX_ACL_SIZE); + hdev->acl_mtu = HCI_MAX_ACL_SIZE; + } + + if (hdev->le_mtu > HCI_MAX_ACL_SIZE) { + dev_info(&bcm4377->pdev->dev, + "controller LE MTU %u exceeds the ACL ring's %u, using %u\n", + hdev->le_mtu, HCI_MAX_ACL_SIZE, HCI_MAX_ACL_SIZE); + hdev->le_mtu = HCI_MAX_ACL_SIZE; + } +} + static int bcm4377_hci_post_init(struct hci_dev *hdev) { struct bcm4377_data *bcm4377 = hci_get_drvdata(hdev); const bdaddr_t *bda = NULL; int ret; + bcm4377_clamp_acl_mtu(hdev); + if (!bcm4377->cal_needed) return 0; @@ -2770,14 +2822,20 @@ static void bcm4377_reset_work(struct work_struct *work) { struct bcm4377_reset_work *rw = container_of(work, struct bcm4377_reset_work, work); + int ret; /* * Remove and probe again: probe resets the function and boots the * firmware from scratch. device_reprobe() frees the old bcm4377_data, * which is why this work and its device reference live outside it. + * A timeout during system resume gets here while the driver core + * blocks probing: the probe is deferred and runs once resume completes. */ - if (device_reprobe(&rw->pdev->dev)) - dev_err(&rw->pdev->dev, "reprobe after command timeout failed\n"); + ret = device_reprobe(&rw->pdev->dev); + if (ret == -EPROBE_DEFER) + dev_info(&rw->pdev->dev, "reprobe after command timeout deferred\n"); + else if (ret) + dev_err(&rw->pdev->dev, "reprobe after command timeout failed: %d\n", ret); pci_dev_put(rw->pdev); kfree(rw); @@ -3194,6 +3252,24 @@ static int bcm4377_resume(struct device *dev) bcm4377->wake_armed = false; } + /* + * A real sleep took the function's power: the firmware is gone, and every resume command + * would only time out (two times 2 s inside the system resume, then the rebind anyway). + * Restore the private BAR0 windows and mark needs_reset before queueing the rebind so + * neither hci_close() during device_reprobe() nor a stray frame can write BAR0 through + * unconfigured reset windows. Skip the resume commands and rebind from the work queue; + * probe boots the firmware from scratch. + */ + if (pm_resume_via_firmware() && !bcm4377->dma_window_base) { + bcm4377->quiesced = false; + bcm4377->resume_powered = false; + bcm4377->needs_reset = true; + bcm4377_init_cfg(bcm4377); + WRITE_ONCE(bcm4377->setup_retry_blocked, false); + bcm4377_queue_rebind(bcm4377, "power lost in the sleep"); + return 0; + } + if (bcm4377->quiesced) { iowrite32(BCM4377_BAR0_SLEEP_CONTROL_UNQUIESCE, bcm4377->bar0 + BCM4377_BAR0_SLEEP_CONTROL); @@ -3397,3 +3473,7 @@ MODULE_FIRMWARE("brcm/brcmbt4387*.bin"); MODULE_FIRMWARE("brcm/brcmbt4387*.ptb"); MODULE_FIRMWARE("brcm/brcmbt4388*.bin"); MODULE_FIRMWARE("brcm/brcmbt4388*.ptb"); + +#if IS_ENABLED(CONFIG_BT_HCIBCM4377_KUNIT_TEST) +#include "hci_bcm4377_test.c" +#endif diff --git a/drivers/bluetooth/hci_bcm4377_test.c b/drivers/bluetooth/hci_bcm4377_test.c new file mode 100644 index 00000000000000..7beb3ddd267163 --- /dev/null +++ b/drivers/bluetooth/hci_bcm4377_test.c @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the hci_bcm4377 ring bookkeeping. Built as part of + * hci_bcm4377.c, so the tests reach its static helpers. They run without + * the radio: BAR0 and the shared ring state are plain kernel memory. + */ +#include + +#define BCM4377_TEST_BAR0_SIZE 0x200 + +struct bcm4377_test_ctx { + struct bcm4377_data *bcm4377; + struct pci_dev *pdev; +}; + +static int bcm4377_test_init(struct kunit *test) +{ + struct bcm4377_test_ctx *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->pdev = kunit_kzalloc(test, sizeof(*ctx->pdev), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->pdev); + ctx->pdev->dev.init_name = "bcm4377-kunit"; + ctx->bcm4377 = kunit_kzalloc(test, sizeof(*ctx->bcm4377), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->bcm4377); + ctx->bcm4377->pdev = ctx->pdev; + ctx->bcm4377->ring_state = + kunit_kzalloc(test, sizeof(*ctx->bcm4377->ring_state), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->bcm4377->ring_state); + ctx->bcm4377->bar0 = (void __iomem *)kunit_kzalloc(test, BCM4377_TEST_BAR0_SIZE, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, (void __force *)ctx->bcm4377->bar0); + test->priv = ctx; + return 0; +} + +/* + * The slot the host fills comes from its own producer index: whatever the + * device leaves in the shared head, the entry lands inside the ring. + */ +static void bcm4377_enqueue_uses_host_head_test(struct kunit *test) +{ + struct bcm4377_test_ctx *ctx = test->priv; + struct bcm4377_data *bcm4377 = ctx->bcm4377; + struct bcm4377_transfer_ring *ring = &bcm4377->hci_h2d_ring; + const size_t slot = sizeof(struct bcm4377_xfer_ring_entry) + 16; + const size_t guard = slot; + struct bcm4377_xfer_ring_entry *entry; + u8 data[8], *buf; + size_t i; + + ring->ring_id = BCM4377_XFER_RING_HCI_H2D; + ring->n_entries = 4; + ring->payload_size = 16; + ring->sync = true; + spin_lock_init(&ring->lock); + buf = kunit_kzalloc(test, ring->n_entries * slot + guard, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + ring->ring = buf; + memset(data, 0x5a, sizeof(data)); + + /* A head one past the last slot, as the device could write it. */ + bcm4377->ring_state->xfer_ring_head[ring->ring_id] = cpu_to_le16(4); + KUNIT_ASSERT_EQ(test, bcm4377_enqueue(bcm4377, ring, data, sizeof(data), false), 0); + + for (i = 0; i < guard; i++) + KUNIT_EXPECT_EQ(test, buf[ring->n_entries * slot + i], 0); + entry = (void *)buf; + KUNIT_EXPECT_EQ(test, le16_to_cpu(entry->len), sizeof(data)); + KUNIT_EXPECT_EQ(test, entry->flags, BCM4377_XFER_RING_FLAG_PAYLOAD_IN_FOOTER); + KUNIT_EXPECT_EQ(test, ring->head, 1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(bcm4377->ring_state->xfer_ring_head[ring->ring_id]), 1); + + /* A far-off value written later does not move the next slot either. */ + bcm4377->ring_state->xfer_ring_head[ring->ring_id] = cpu_to_le16(0xffff); + KUNIT_ASSERT_EQ(test, bcm4377_enqueue(bcm4377, ring, data, sizeof(data), false), 0); + entry = (void *)(buf + slot); + KUNIT_EXPECT_EQ(test, le16_to_cpu(entry->len), sizeof(data)); + KUNIT_EXPECT_EQ(test, ring->head, 2); + for (i = 0; i < guard; i++) + KUNIT_EXPECT_EQ(test, buf[ring->n_entries * slot + i], 0); +} + +/* + * An event whose payload sits in the completion entry's footer can be no + * longer than that footer; a longer one is dropped and the ring moves on. + */ +static void bcm4377_footer_event_len_test(struct kunit *test) +{ + static const u32 lens[] = { 9, 0xfffffff8, 0xffffffff, 8 }; + struct bcm4377_test_ctx *ctx = test->priv; + struct bcm4377_data *bcm4377 = ctx->bcm4377; + struct bcm4377_transfer_ring *ring = &bcm4377->hci_d2h_ring; + struct bcm4377_completion_ring_entry *entry; + struct bcm4377_completion_ring cring = { + .ring_id = BCM4377_EVENT_RING_HCI_ACL, + .payload_size = 8, + .n_entries = 2, + .transfer_rings = BIT(BCM4377_XFER_RING_HCI_D2H), + }; + size_t i; + + ring->ring_id = BCM4377_XFER_RING_HCI_D2H; + ring->n_entries = 8; + ring->virtual = true; + ring->enabled = true; + spin_lock_init(&ring->lock); + /* Room past the footer, so a missing check reads this, not a neighbour. */ + cring.ring = kunit_kzalloc(test, 2 * (sizeof(*entry) + cring.payload_size) + 64, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, cring.ring); + entry = cring.ring; + entry->ring_id = cpu_to_le16(BCM4377_XFER_RING_HCI_D2H); + entry->flags = BCM4377_XFER_RING_FLAG_PAYLOAD_IN_FOOTER; + + /* No HCI device: an accepted frame is freed by hci_recv_frame(). */ + for (i = 0; i < ARRAY_SIZE(lens); i++) { + entry->len = cpu_to_le32(lens[i]); + bcm4377_handle_completion(bcm4377, &cring, 0); + KUNIT_EXPECT_EQ(test, ring->head, i + 1); + } +} + +static struct kunit_case bcm4377_test_cases[] = { + KUNIT_CASE(bcm4377_enqueue_uses_host_head_test), + KUNIT_CASE(bcm4377_footer_event_len_test), + {} +}; + +static struct kunit_suite bcm4377_test_suite = { + .name = "hci_bcm4377", + .init = bcm4377_test_init, + .test_cases = bcm4377_test_cases, +}; + +kunit_test_suite(bcm4377_test_suite); diff --git a/drivers/bluetooth/mt7932_bt_pcie.c b/drivers/bluetooth/mt7932_bt_pcie.c index 0882703177b90a..cc01adea054fa5 100644 --- a/drivers/bluetooth/mt7932_bt_pcie.c +++ b/drivers/bluetooth/mt7932_bt_pcie.c @@ -69,6 +69,15 @@ /* How long a wake reason may take to arrive once the transport is back. */ #define BT7932_WAKE_REASON_MS 200 +/* + * The firmware files carry their version in their names, and a firmware + * update renames them. User space can install the newest image of each kind + * under a name that does not change; look for that first, then for the + * versioned names. + */ +#define BT7932_FW_B0_STABLE "mediatek/mt7932/bt-b0.bin" +#define BT7932_FW_B1_STABLE "mediatek/mt7932/bt-b1.bin" +#define BT7932_PTX_STABLE "mediatek/mt7932/bt-ptb.ptx" #define BT7932_FW_B0 "mediatek/MT7932B0_OS_TypeB_0.1.44.0_241001003711.bin" #define BT7932_FW_B1 "mediatek/MT7932B1_OS_TypeB_2.0.177.0_260706180356.bin" #define BT7932_FW_B1_FALLBACK "mediatek/MT7932B1_OS_TypeB_0.1.133.0_260128190103.bin" @@ -401,31 +410,76 @@ static int bt7932_validate_ptx(const u8 *data, size_t size) return next == size ? 0 : -EINVAL; } +static int bt7932_validate_image(const u8 *data, size_t size) +{ + if (size <= 32 || size - 32 > U32_MAX - 3) + return -EINVAL; + if (memcmp(data + size - 32 + 16, "ALPS\x8a\x10\x8a\x10", 8)) + return -EINVAL; + return 0; +} + +static const char *const bt7932_b0_names[] = { + BT7932_FW_B0_STABLE, BT7932_FW_B0, +}; + +static const char *const bt7932_b1_names[] = { + BT7932_FW_B1_STABLE, BT7932_FW_B1, BT7932_FW_B1_FALLBACK, +}; + +static const char *const bt7932_ptx_names[] = { + BT7932_PTX_STABLE, BT7932_PTX, +}; + +/* + * Load the first of @names that exists and passes @validate. A file that is + * missing or fails validation moves on to the next name, so a bad + * version-independent file cannot hide a good versioned one. Only the last + * name warns when it is missing. + */ +static int bt7932_request_valid(struct bt7932 *bt, const struct firmware **fw, + const char *const *names, size_t count, + int (*validate)(const u8 *data, size_t size)) +{ + struct device *dev = &bt->pdev->dev; + int ret = -ENOENT; + size_t i; + + for (i = 0; i < count; i++) { + if (i + 1 < count) + ret = firmware_request_nowarn(fw, names[i], dev); + else + ret = request_firmware(fw, names[i], dev); + if (ret == -ENOENT) + continue; + if (ret) + return ret; + ret = validate((*fw)->data, (*fw)->size); + if (!ret) + return 0; + dev_warn(dev, "%s is not usable (%d)\n", names[i], ret); + release_firmware(*fw); + *fw = NULL; + } + return ret; +} + static int bt7932_read_inputs(struct bt7932 *bt) { const struct firmware *fw; - const u8 *trailer; u64 last; int i, ret; - if (!bt->rom) { - ret = request_firmware(&fw, BT7932_FW_B0, &bt->pdev->dev); - } else { - ret = firmware_request_nowarn(&fw, BT7932_FW_B1, &bt->pdev->dev); - if (ret == -ENOENT) - ret = request_firmware(&fw, BT7932_FW_B1_FALLBACK, &bt->pdev->dev); - } + if (!bt->rom) + ret = bt7932_request_valid(bt, &fw, bt7932_b0_names, + ARRAY_SIZE(bt7932_b0_names), + bt7932_validate_image); + else + ret = bt7932_request_valid(bt, &fw, bt7932_b1_names, + ARRAY_SIZE(bt7932_b1_names), + bt7932_validate_image); if (ret) return ret; - if (fw->size <= 32 || fw->size - 32 > U32_MAX - 3) { - ret = -EINVAL; - goto release_image; - } - trailer = fw->data + fw->size - 32; - if (memcmp(trailer + 16, "ALPS\x8a\x10\x8a\x10", 8)) { - ret = -EINVAL; - goto release_image; - } bt->image_body = fw->size - 32; bt->image_size = ALIGN(bt->image_body, 4); bt->image = dma_alloc_coherent(&bt->pdev->dev, bt->image_size, @@ -459,16 +513,15 @@ static int bt7932_read_inputs(struct bt7932 *bt) release_firmware(fw); if (ret) return ret; - ret = request_firmware(&fw, BT7932_PTX, &bt->pdev->dev); + ret = bt7932_request_valid(bt, &fw, bt7932_ptx_names, + ARRAY_SIZE(bt7932_ptx_names), + bt7932_validate_ptx); if (ret) return ret; - ret = bt7932_validate_ptx(fw->data, fw->size); - if (!ret) { - bt->ptx_size = fw->size; - bt->ptx = kmemdup(fw->data, fw->size, GFP_KERNEL); - if (!bt->ptx) - ret = -ENOMEM; - } + bt->ptx_size = fw->size; + bt->ptx = kmemdup(fw->data, fw->size, GFP_KERNEL); + if (!bt->ptx) + ret = -ENOMEM; release_firmware(fw); if (ret) return ret; @@ -1988,6 +2041,9 @@ module_pci_driver(bt7932_driver); MODULE_DESCRIPTION("MediaTek MT7932 Bluetooth PCIe transport for the Apple MacBook Neo"); MODULE_LICENSE("GPL"); +MODULE_FIRMWARE(BT7932_FW_B0_STABLE); +MODULE_FIRMWARE(BT7932_FW_B1_STABLE); +MODULE_FIRMWARE(BT7932_PTX_STABLE); MODULE_FIRMWARE(BT7932_FW_B0); MODULE_FIRMWARE(BT7932_FW_B1); MODULE_FIRMWARE(BT7932_FW_B1_FALLBACK); diff --git a/drivers/cpufreq/Kconfig.arm b/drivers/cpufreq/Kconfig.arm index a441668f9e0cc6..f1072141ae6e7c 100644 --- a/drivers/cpufreq/Kconfig.arm +++ b/drivers/cpufreq/Kconfig.arm @@ -32,6 +32,23 @@ config ARM_APPLE_SOC_CPUFREQ This adds the CPUFreq driver for Apple Silicon machines (e.g. Apple M1). +config ARM_APPLE_SOC_CPUFREQ_KUNIT_TEST + bool "KUnit tests for Apple Silicon SoC CPUFreq" if !KUNIT_ALL_TESTS + depends on ARM_APPLE_SOC_CPUFREQ=y && KUNIT=y + depends on ARM64 + default KUNIT_ALL_TESTS + help + Build tests for the Apple Silicon CPU cluster performance state + driver: the command and status register layout of each SoC, the + waited-for and the lazily verified request paths, the fast + die-temperature limit and its devicetree parsing, and the board + thermal ownership cap. The cluster registers are ordinary memory, + which the MMIO accessors of arm64 can read and write; no hardware + is accessed. The policy suite skips when a CPUFreq driver is already + registered. + + If unsure, say N. + config ARM_ARMADA_37XX_CPUFREQ tristate "Armada 37xx CPUFreq support" depends on ARCH_MVEBU || COMPILE_TEST diff --git a/drivers/cpufreq/apple-soc-cpufreq-test.c b/drivers/cpufreq/apple-soc-cpufreq-test.c new file mode 100644 index 00000000000000..8a207c186d590e --- /dev/null +++ b/drivers/cpufreq/apple-soc-cpufreq-test.c @@ -0,0 +1,1543 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the Apple SoC CPU cluster performance state driver: the + * per-SoC command and status register layouts, the waited-for and the lazily + * verified request paths, the fast die-temperature limit arithmetic and its + * devicetree parsing, and the board thermal ownership cap. + * + * The cluster registers are a block of ordinary memory: the driver only uses + * plain MMIO accessors on its base pointer, and no test maps a device. A + * written request reads back as accepted, as on an idle cluster; a test sets + * the busy bit or another state itself to play the hardware. + * + * Most tests run on a cpufreq policy that is not known to the cpufreq core. + * The ->get() and thermal ownership tests need a policy of the core, so their + * suite registers a cpufreq driver of its own, whose requests do nothing, and + * is skipped where a cpufreq driver is already registered. + * + * Included by apple-soc-cpufreq.c. + */ + +#include +#include +#include + +#define CFT_REGS_SIZE 0x100 +#define CFT_NR_STATES 5 + +/* Frequencies in kHz and the P-state (OPP level) of each; made-up values. */ +static const struct cpufreq_frequency_table cft_table[CFT_NR_STATES + 1] = { + { .driver_data = 1, .frequency = 600000 }, + { .driver_data = 4, .frequency = 1200000 }, + { .driver_data = 7, .frequency = 1800000 }, + { .driver_data = 10, .frequency = 2400000 }, + { .driver_data = 15, .frequency = 3000000 }, + { .frequency = CPUFREQ_TABLE_END }, +}; + +struct cft_ctx { + struct cpufreq_policy *policy; + struct apple_cpu_priv *priv; + struct cpufreq_frequency_table *table; + u8 *regs; +}; + +static u64 cft_cmd(u8 *regs) +{ + return le64_to_cpup((__le64 *)(regs + APPLE_DVFS_CMD)); +} + +static void cft_set_cmd(u8 *regs, u64 val) +{ + *(__le64 *)(regs + APPLE_DVFS_CMD) = cpu_to_le64(val); +} + +static void cft_set_status(u8 *regs, u32 val) +{ + *(__le32 *)(regs + APPLE_DVFS_STATUS) = cpu_to_le32(val); +} + +static void cft_priv_init(struct apple_cpu_priv *priv, u8 *regs, + const struct apple_soc_cpufreq_info *info, + unsigned int pstate) +{ + /* As apple_soc_cpufreq_init() leaves it. */ + priv->reg_base = (void __iomem __force *)regs; + priv->info = info; + raw_spin_lock_init(&priv->lock); + hrtimer_setup(&priv->verify_timer, apple_soc_cpufreq_verify, + CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD); + priv->pending_pstate = -1; + priv->cap_pstate = info->max_pstate; + priv->waited = true; + priv->expected_pstate = pstate; + cft_set_cmd(regs, pstate); +} + +/* A cluster of @info that idles in @pstate, with the cft_table states. */ +static struct cft_ctx *cft_setup(struct kunit *test, + const struct apple_soc_cpufreq_info *info, + unsigned int pstate) +{ + struct cft_ctx *prev = test->priv; + struct cft_ctx *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->regs = kunit_kzalloc(test, CFT_REGS_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->regs); + ctx->table = kunit_kzalloc(test, sizeof(cft_table), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->table); + memcpy(ctx->table, cft_table, sizeof(cft_table)); + ctx->policy = kunit_kzalloc(test, sizeof(*ctx->policy), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->policy); + ctx->priv = kunit_kzalloc(test, sizeof(*ctx->priv), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->priv); + + /* A test may set up one cluster after another, on the same device. */ + if (prev) { + hrtimer_cancel(&prev->priv->verify_timer); + ctx->priv->cpu_dev = prev->priv->cpu_dev; + } else { + ctx->priv->cpu_dev = kunit_device_register(test, "apple-cpufreq-test"); + } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->priv->cpu_dev); + cft_priv_init(ctx->priv, ctx->regs, info, pstate); + + ctx->policy->freq_table = ctx->table; + ctx->policy->freq_table_sorted = CPUFREQ_TABLE_SORTED_ASCENDING; + ctx->policy->min = ctx->table[0].frequency; + ctx->policy->max = ctx->table[CFT_NR_STATES - 1].frequency; + ctx->policy->cur = ctx->table[0].frequency; + ctx->policy->driver_data = ctx->priv; + + test->priv = ctx; + return ctx; +} + +static void cft_exit(struct kunit *test) +{ + struct cft_ctx *ctx = test->priv; + + if (ctx && ctx->priv) + hrtimer_cancel(&ctx->priv->verify_timer); +} + +/* + * The lazily verified paths arm the verify timer, a hard interrupt timer due + * within a millisecond or less. A test calls them with interrupts off, so + * that the timer cannot run, and ends the section here: this returns whether + * the timer was armed, and cancels it. The test then runs the timer callback + * itself, in the state it has prepared. + */ +static bool cft_thaw(struct cft_ctx *ctx, unsigned long flags) +{ + bool queued = hrtimer_is_queued(&ctx->priv->verify_timer); + + hrtimer_cancel(&ctx->priv->verify_timer); + local_irq_restore(flags); + return queued; +} + +/* Runs the verify timer callback once, as cft_thaw() describes. */ +static bool cft_verify(struct cft_ctx *ctx) +{ + unsigned long flags; + + local_irq_save(flags); + apple_soc_cpufreq_verify(&ctx->priv->verify_timer); + return cft_thaw(ctx, flags); +} + +static bool cft_lazy_request(struct cft_ctx *ctx, unsigned int index, + unsigned int *freq) +{ + unsigned long flags; + + local_irq_save(flags); + *freq = apple_soc_cpufreq_lazy_request(ctx->policy, index); + return cft_thaw(ctx, flags); +} + +static bool cft_lazy_cap(struct cft_ctx *ctx, unsigned int cap, + unsigned int freq, int *moved) +{ + unsigned long flags; + + local_irq_save(flags); + *moved = apple_soc_cpufreq_lazy_cap(ctx->priv, cap, freq); + return cft_thaw(ctx, flags); +} + +/* + * Register layouts + */ + +struct cft_layout { + const char *compatible; + u64 ps1_mask; + u64 cur_pstate_mask; + u64 min_pstate; + u64 max_pstate; + bool has_ps2; +}; + +static const struct cft_layout cft_layouts[] = { + { "apple,s5l8960x-cluster-cpufreq", GENMASK(24, 22), GENMASK(5, 3), 0, 7, false }, + { "apple,t8103-cluster-cpufreq", GENMASK(4, 0), GENMASK(7, 4), 0, 15, true }, + { "apple,t8112-cluster-cpufreq", GENMASK(4, 0), GENMASK(9, 5), 0, 31, false }, + { "apple,t8132-cluster-cpufreq", GENMASK(4, 0), 0, 0, 31, false }, + { "apple,cluster-cpufreq", GENMASK(4, 0), 0, 0, 15, false }, + { "apple,t8140-cluster-cpufreq", GENMASK(4, 0), 0, 1, 31, false }, + { "apple,t6050-cluster-cpufreq", GENMASK(4, 0), 0, 0, 31, false }, + { "apple,t8142-cluster-cpufreq", GENMASK(4, 0), 0, 1, 31, false }, + { "apple,t8152-cluster-cpufreq", GENMASK(4, 0), 0, 2, 31, false }, +}; + +static void cft_layout_desc(const struct cft_layout *l, char *desc) +{ + strscpy(desc, l->compatible, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(cft_layout, cft_layouts, cft_layout_desc); + +static const struct apple_soc_cpufreq_info *cft_match(const char *compatible) +{ + const struct of_device_id *id; + + for (id = apple_soc_cpufreq_of_match; id->compatible[0]; id++) + if (!strcmp(id->compatible, compatible)) + return id->data; + return NULL; +} + +/* Each compatible selects the layout of its SoC. */ +static void cft_test_layout(struct kunit *test) +{ + const struct cft_layout *l = test->param_value; + const struct apple_soc_cpufreq_info *info = cft_match(l->compatible); + + KUNIT_ASSERT_NOT_NULL(test, info); + KUNIT_EXPECT_EQ(test, info->ps1_mask, l->ps1_mask); + KUNIT_EXPECT_EQ(test, info->ps1_shift, __ffs64(l->ps1_mask)); + KUNIT_EXPECT_EQ(test, info->cur_pstate_mask, l->cur_pstate_mask); + if (l->cur_pstate_mask) + KUNIT_EXPECT_EQ(test, info->cur_pstate_shift, + __ffs64(l->cur_pstate_mask)); + KUNIT_EXPECT_EQ(test, info->min_pstate, l->min_pstate); + KUNIT_EXPECT_EQ(test, info->max_pstate, l->max_pstate); + KUNIT_EXPECT_EQ(test, info->has_ps2, l->has_ps2); +} + +/* What every layout must satisfy for the request and readback code to work. */ +static void cft_test_layout_invariants(struct kunit *test) +{ + const struct of_device_id *id; + + for (id = apple_soc_cpufreq_of_match; id->compatible[0]; id++) { + const struct apple_soc_cpufreq_info *info = id->data; + + KUNIT_ASSERT_NOT_NULL_MSG(test, info, "%s", id->compatible); + KUNIT_ASSERT_NE_MSG(test, info->ps1_mask, 0, "%s", id->compatible); + /* The request field holds every P-state. */ + KUNIT_EXPECT_EQ_MSG(test, info->ps1_shift, __ffs64(info->ps1_mask), + "%s", id->compatible); + KUNIT_EXPECT_LE_MSG(test, info->min_pstate, info->max_pstate, + "%s", id->compatible); + KUNIT_EXPECT_LE_MSG(test, info->max_pstate, + info->ps1_mask >> info->ps1_shift, + "%s", id->compatible); + KUNIT_EXPECT_LE_MSG(test, info->max_unmanaged_pstate, info->max_pstate, + "%s", id->compatible); + if (info->has_ps2) + KUNIT_EXPECT_LE_MSG(test, info->max_pstate, + FIELD_MAX(APPLE_DVFS_CMD_PS2), + "%s", id->compatible); + /* So does the status field, where the SoC has one. */ + if (info->cur_pstate_mask) { + KUNIT_EXPECT_EQ_MSG(test, info->cur_pstate_shift, + __ffs64(info->cur_pstate_mask), + "%s", id->compatible); + KUNIT_EXPECT_LE_MSG(test, info->max_pstate, + info->cur_pstate_mask >> info->cur_pstate_shift, + "%s", id->compatible); + } + /* Verification reads the request back as APPLE_DVFS_CMD_PS1. */ + if (info->verify_transition) + KUNIT_EXPECT_EQ_MSG(test, info->ps1_mask, APPLE_DVFS_CMD_PS1, + "%s", id->compatible); + } +} + +struct cft_write { + const char *name; + const struct apple_soc_cpufreq_info *info; + u64 before; + unsigned int pstate; + u64 after; +}; + +static const struct cft_write cft_writes[] = { + { "t8103 sets PS1 and PS2", &soc_t8103_info, 0, 9, + BIT(25) | (9 << 12) | 9 }, + { "t8103 replaces PS1 and PS2 only", &soc_t8103_info, ~0ULL, 9, + (~0ULL & ~(GENMASK_ULL(15, 12) | GENMASK_ULL(4, 0))) | (9 << 12) | 9 }, + { "t8112 sets PS1", &soc_t8112_info, 0, 21, BIT(25) | 21 }, + { "t8112 leaves the PS2 bits", &soc_t8112_info, ~0ULL, 21, + (~0ULL & ~GENMASK_ULL(4, 0)) | 21 }, + { "s5l8960x sets bits 24:22", &soc_s5l8960x_info, 0, 5, + BIT(25) | (5 << 22) }, + { "s5l8960x replaces bits 24:22 only", &soc_s5l8960x_info, ~0ULL, 5, + (~0ULL & ~GENMASK_ULL(24, 22)) | (5 << 22) }, + { "t8140 highest state", &soc_t8140_info, 0, 31, BIT(25) | 31 }, + { "t8132 lowest state", &soc_t8132_info, GENMASK_ULL(4, 0), 0, BIT(25) }, + { "generic", &soc_default_info, 3, 12, BIT(25) | 12 }, +}; + +static void cft_write_desc(const struct cft_write *w, char *desc) +{ + strscpy(desc, w->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(cft_write, cft_writes, cft_write_desc); + +/* A request replaces the state fields of its SoC and sets the SET bit. */ +static void cft_test_write(struct kunit *test) +{ + const struct cft_write *w = test->param_value; + struct cft_ctx *ctx = cft_setup(test, w->info, 0); + + apple_soc_cpufreq_write(ctx->priv, w->before, w->pstate); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), w->after); +} + +static void cft_test_timeout(struct kunit *test) +{ + static const struct apple_soc_cpufreq_info own = { + .transition_timeout_us = 1234, + }; + static const struct apple_soc_cpufreq_info none = {}; + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_timeout(&own), 1234); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_timeout(&none), + APPLE_DVFS_TRANSITION_TIMEOUT); +} + +/* + * Waited-for requests + */ + +/* The frequency-table index selects the P-state, not the other way round. */ +static void cft_test_request(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8103_info, 4); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 3), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | (10 << 12) | 10); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 0), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | (1 << 12) | 1); +} + +/* A P-state outside the range of the SoC is refused before any write. */ +static void cft_test_request_range(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8103_info, 4); + + ctx->table[4].driver_data = 16; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 4), -EINVAL); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + ctx->table[4].driver_data = 15; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 4), 0); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 15); + + /* The states of T8152 start at 2, those of T8140 at 1. */ + ctx = cft_setup(test, &soc_t8152_info, 4); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 0), -EINVAL); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + KUNIT_EXPECT_FALSE(test, ctx->priv->transition_failed); + ctx->table[0].driver_data = 2; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 0), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 2); + + ctx = cft_setup(test, &soc_t8140_info, 4); + ctx->table[0].driver_data = 0; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 0), -EINVAL); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + ctx->table[0].driver_data = 1; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 0), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 1); +} + +/* A SoC that does not verify drops a request to a busy cluster, no more. */ +static void cft_test_set_pstate_busy(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 4); + + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 4); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), -EIO); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), APPLE_DVFS_CMD_BUSY | 4); + KUNIT_EXPECT_FALSE(test, ctx->priv->transition_failed); + + cft_set_cmd(ctx->regs, 4); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 10); +} + +static void cft_test_set_pstate_verified(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t6050_info, 4); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 10); + KUNIT_EXPECT_EQ(test, ctx->priv->expected_pstate, 10); + + /* The accepted state is not requested again. */ + cft_set_cmd(ctx->regs, 10); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 10); + KUNIT_EXPECT_FALSE(test, ctx->priv->transition_failed); +} + +/* A state nobody asked for stops all requests: someone else owns the cluster. */ +static void cft_test_set_pstate_unexpected(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t6050_info, 4); + + cft_set_cmd(ctx->regs, 7); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), -EIO); + KUNIT_EXPECT_TRUE(test, ctx->priv->transition_failed); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 7); + KUNIT_EXPECT_EQ(test, ctx->priv->expected_pstate, 4); + + /* Not even one that would now match. */ + cft_set_cmd(ctx->regs, 4); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), -EIO); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); +} + +static void cft_test_set_pstate_verified_busy(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t6050_info, 4); + + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 4); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), -EIO); + KUNIT_EXPECT_TRUE(test, ctx->priv->transition_failed); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), APPLE_DVFS_CMD_BUSY | 4); + KUNIT_EXPECT_EQ(test, ctx->priv->expected_pstate, 4); +} + +/* ->fast_switch() of a SoC that does not verify: lowest state at or above. */ +static void cft_test_fast_switch(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8103_info, 4); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_fast_switch(ctx->policy, 1300000), + 1800000); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | (7 << 12) | 7); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_fast_switch(ctx->policy, 600000), + 600000); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | (1 << 12) | 1); + /* The policy limits clamp the target. */ + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_fast_switch(ctx->policy, UINT_MAX), + 3000000); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | (15 << 12) | 15); + ctx->policy->max = 2400000; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_fast_switch(ctx->policy, 3000000), + 2400000); + + /* 0 tells the scheduler that nothing was requested. */ + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 10); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_fast_switch(ctx->policy, 600000), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), APPLE_DVFS_CMD_BUSY | 10); +} + +static void cft_test_pstate_freq(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 4); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_pstate_freq(ctx->policy, 1), 600000); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_pstate_freq(ctx->policy, 15), 3000000); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_pstate_freq(ctx->policy, 0), 0); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_pstate_freq(ctx->policy, 5), 0); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_pstate_freq(ctx->policy, 31), 0); + /* An entry the core has marked invalid has no frequency. */ + ctx->table[2].frequency = CPUFREQ_ENTRY_INVALID; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_pstate_freq(ctx->policy, 7), 0); +} + +/* + * Lazily verified requests + */ + +/* An idle cluster takes the request at once; the timer verifies it. */ +static void cft_test_lazy_idle(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned int freq; + bool queued; + + queued = cft_lazy_request(ctx, 3, &freq); + KUNIT_EXPECT_EQ(test, freq, 2400000); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 10); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 10); + KUNIT_EXPECT_EQ(test, priv->asked_pstate, 10); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, -1); + KUNIT_EXPECT_FALSE(test, priv->waited); + KUNIT_EXPECT_EQ(test, ktime_us_delta(priv->verify_deadline, priv->write_time), + APPLE_DVFS_TRANSITION_TIMEOUT); + + /* The cluster accepted it: the timer has nothing to say or do. */ + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_FALSE(test, priv->transition_failed); + KUNIT_EXPECT_FALSE(test, priv->failure_unreported); + + /* The accepted state is not written again. */ + cft_set_cmd(ctx->regs, 10); + queued = cft_lazy_request(ctx, 3, &freq); + KUNIT_EXPECT_EQ(test, freq, 2400000); + KUNIT_EXPECT_FALSE(test, queued); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 10); +} + +/* A busy cluster keeps the newest request pending; the timer writes it. */ +static void cft_test_lazy_busy(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned int freq; + bool queued; + + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 4); + queued = cft_lazy_request(ctx, 3, &freq); + /* Committed all the same: schedutil does not ask twice. */ + KUNIT_EXPECT_EQ(test, freq, 2400000); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), APPLE_DVFS_CMD_BUSY | 4); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, 10); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 4); + KUNIT_EXPECT_NE(test, ktime_to_ns(priv->verify_deadline), 0); + + queued = cft_lazy_request(ctx, 2, &freq); + KUNIT_EXPECT_EQ(test, freq, 1800000); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, 7); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), APPLE_DVFS_CMD_BUSY | 4); + + /* Still busy, within the timeout: the timer looks again. */ + priv->verify_deadline = ktime_add_ms(ktime_get(), 60 * MSEC_PER_SEC); + KUNIT_EXPECT_TRUE(test, cft_verify(ctx)); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, 7); + KUNIT_EXPECT_FALSE(test, priv->transition_failed); + + /* The transition finished as expected: the pending request goes out. */ + cft_set_cmd(ctx->regs, 4); + KUNIT_EXPECT_TRUE(test, cft_verify(ctx)); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 7); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 7); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, -1); + + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_FALSE(test, priv->transition_failed); +} + +/* A pending request for the state the cluster settled in is not written. */ +static void cft_test_lazy_pending_same(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + + ctx->priv->pending_pstate = 4; + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + KUNIT_EXPECT_EQ(test, ctx->priv->pending_pstate, -1); + KUNIT_EXPECT_FALSE(test, ctx->priv->transition_failed); +} + +/* An unexpected state fails the request; the timer reports it, once. */ +static void cft_test_lazy_unexpected(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned int freq; + bool queued; + + cft_set_cmd(ctx->regs, 9); + queued = cft_lazy_request(ctx, 3, &freq); + KUNIT_EXPECT_EQ(test, freq, 0); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_TRUE(test, priv->transition_failed); + KUNIT_EXPECT_TRUE(test, priv->failure_unreported); + KUNIT_EXPECT_EQ(test, priv->failure_command, 9); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 9); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 4); + + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_FALSE(test, priv->failure_unreported); + + /* No request after a failure, even one that would now match. */ + cft_set_cmd(ctx->regs, 4); + queued = cft_lazy_request(ctx, 3, &freq); + KUNIT_EXPECT_EQ(test, freq, 0); + KUNIT_EXPECT_FALSE(test, queued); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + priv->pending_pstate = 10; + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); +} + +/* The timer finds what a request did not: the last request of a burst. */ +static void cft_test_lazy_verify_fails(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + + /* The state changed under us. */ + cft_set_cmd(ctx->regs, 9); + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_TRUE(test, priv->transition_failed); + KUNIT_EXPECT_FALSE(test, priv->failure_unreported); + KUNIT_EXPECT_EQ(test, priv->failure_command, 9); + + /* Busy for longer than the timeout; the pending request is dropped. */ + ctx = cft_setup(test, &soc_t8140_info, 4); + priv = ctx->priv; + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 4); + priv->pending_pstate = 7; + priv->verify_deadline = ktime_sub_us(ktime_get(), 1); + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_TRUE(test, priv->transition_failed); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, -1); + KUNIT_EXPECT_EQ(test, priv->failure_command, APPLE_DVFS_CMD_BUSY | 4); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), APPLE_DVFS_CMD_BUSY | 4); +} + +static void cft_test_lazy_range(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + unsigned int freq; + bool queued; + + ctx->table[3].driver_data = 0; + queued = cft_lazy_request(ctx, 3, &freq); + KUNIT_EXPECT_FALSE(test, queued); + KUNIT_EXPECT_EQ(test, freq, 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + /* Not a fast-switch request at all: waited-for requests keep the cluster. */ + KUNIT_EXPECT_TRUE(test, ctx->priv->waited); +} + +/* ->fast_switch() of a lazily verified SoC, with and without a limit. */ +static void cft_test_lazy_fast_switch(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned long flags; + unsigned int freq; + bool queued; + + local_irq_save(flags); + freq = apple_soc_cpufreq_fast_switch(ctx->policy, 1300000); + queued = cft_thaw(ctx, flags); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, freq, 1800000); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 7); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 7); + + /* Above the limit: the limit is requested, and returned. */ + priv->cap_pstate = 4; + priv->cap_freq = 1200000; + local_irq_save(flags); + freq = apple_soc_cpufreq_fast_switch(ctx->policy, 3000000); + queued = cft_thaw(ctx, flags); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, freq, 1200000); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 4); + KUNIT_EXPECT_EQ(test, priv->asked_pstate, 15); + + /* At the limit: as asked. */ + local_irq_save(flags); + freq = apple_soc_cpufreq_fast_switch(ctx->policy, 1200000); + cft_thaw(ctx, flags); + KUNIT_EXPECT_EQ(test, freq, 1200000); + KUNIT_EXPECT_EQ(test, priv->asked_pstate, 4); +} + +/* A new limit moves the cluster at once, down and back up. */ +static void cft_test_lazy_cap(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned int freq; + bool queued; + int moved; + + cft_lazy_request(ctx, 4, &freq); + KUNIT_ASSERT_EQ(test, freq, 3000000); + KUNIT_ASSERT_EQ(test, priv->expected_pstate, 15); + + queued = cft_lazy_cap(ctx, 7, 1800000, &moved); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, moved, 7); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 7); + KUNIT_EXPECT_EQ(test, priv->cap_pstate, 7); + KUNIT_EXPECT_EQ(test, priv->cap_freq, 1800000); + /* What the scheduler asked for is remembered. */ + KUNIT_EXPECT_EQ(test, priv->asked_pstate, 15); + + /* Nothing to move when the limit is already applied. */ + cft_lazy_cap(ctx, 7, 1800000, &moved); + KUNIT_EXPECT_EQ(test, moved, -1); + + /* A lower state than the limit stays where the scheduler put it. */ + cft_lazy_request(ctx, 1, &freq); + KUNIT_EXPECT_EQ(test, freq, 1200000); + cft_lazy_cap(ctx, 10, 2400000, &moved); + KUNIT_EXPECT_EQ(test, moved, -1); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 4); + + /* The limit rises before schedutil saw it fall: the request is restored. */ + cft_lazy_request(ctx, 4, &freq); + KUNIT_EXPECT_EQ(test, freq, 2400000); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 10); + cft_lazy_cap(ctx, 31, 3000000, &moved); + KUNIT_EXPECT_EQ(test, moved, 15); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 15); + + /* A busy cluster gets the limit as its pending request. */ + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 15); + queued = cft_lazy_cap(ctx, 4, 1200000, &moved); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, moved, 4); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, 4); + /* And is not asked again while that is pending. */ + cft_lazy_cap(ctx, 4, 1200000, &moved); + KUNIT_EXPECT_EQ(test, moved, -1); +} + +/* Waited-for requests own the cluster: the limit is recorded, no more. */ +static void cft_test_lazy_cap_waited(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned int freq; + bool queued; + int moved; + + queued = cft_lazy_cap(ctx, 1, 600000, &moved); + KUNIT_EXPECT_FALSE(test, queued); + KUNIT_EXPECT_EQ(test, moved, -1); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + KUNIT_EXPECT_EQ(test, priv->cap_pstate, 1); + KUNIT_EXPECT_EQ(test, priv->cap_freq, 600000); + + /* Nor is a cluster moved whose requests have stopped. */ + cft_lazy_request(ctx, 0, &freq); + KUNIT_ASSERT_EQ(test, freq, 600000); + priv->asked_pstate = 15; + priv->transition_failed = true; + cft_lazy_cap(ctx, 7, 1800000, &moved); + KUNIT_EXPECT_EQ(test, moved, -1); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 1); +} + +static void cft_test_drain(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + + priv->waited = false; + priv->pending_pstate = 7; + priv->failure_unreported = true; + priv->failure_command = APPLE_DVFS_CMD_BUSY | 4; + hrtimer_start(&priv->verify_timer, ms_to_ktime(60 * MSEC_PER_SEC), + HRTIMER_MODE_REL_HARD); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_drain(priv), 7); + KUNIT_EXPECT_FALSE(test, hrtimer_is_queued(&priv->verify_timer)); + KUNIT_EXPECT_TRUE(test, priv->waited); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, -1); + KUNIT_EXPECT_FALSE(test, priv->failure_unreported); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_drain(priv), -1); +} + +/* ->target_index() replaces a pending request and waits for its own. */ +static void cft_test_set_target_lazy(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + + priv->waited = false; + priv->pending_pstate = 10; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_target(ctx->policy, 2), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 7); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 7); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, -1); + KUNIT_EXPECT_TRUE(test, priv->waited); +} + +/* Suspend settles the cluster and records where as policy->cur. */ +static void cft_test_suspend_lazy(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + + /* No suspend frequency: only the driver's own part runs. */ + ctx->policy->suspend_freq = 0; + + priv->waited = false; + priv->pending_pstate = 10; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_suspend(ctx->policy), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 10); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 10); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, -1); + KUNIT_EXPECT_EQ(test, ctx->policy->cur, 2400000); + + /* Nothing pending: policy->cur follows the accepted state. */ + ctx->policy->cur = 600000; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_suspend(ctx->policy), 0); + KUNIT_EXPECT_EQ(test, ctx->policy->cur, 2400000); + + /* A cluster that does not settle fails the suspend. */ + ctx->policy->cur = 600000; + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 10); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_suspend(ctx->policy), -EIO); + KUNIT_EXPECT_EQ(test, ctx->policy->cur, 600000); +} + +#ifdef CONFIG_SUSPEND +static void cft_restore_pm_flags(void *flags) +{ + pm_suspend_global_flags = *(unsigned int *)flags; +} +#endif + +/* After a firmware-driven sleep the state the cluster woke in is adopted. */ +static void cft_test_resume(struct kunit *test) +{ +#ifdef CONFIG_SUSPEND + struct cft_ctx *ctx = cft_setup(test, &soc_t6050_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned int *flags; + + /* Put the global flags back even if an assertion ends the case. */ + flags = kunit_kmalloc(test, sizeof(*flags), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, flags); + *flags = pm_suspend_global_flags; + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, cft_restore_pm_flags, flags), 0); + + pm_suspend_clear_flags(); + + priv->transition_failed = true; + cft_set_cmd(ctx->regs, 9); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_resume(ctx->policy), 0); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 4); + KUNIT_EXPECT_TRUE(test, priv->transition_failed); + + pm_set_resume_via_firmware(); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_resume(ctx->policy), 0); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 9); + KUNIT_EXPECT_FALSE(test, priv->transition_failed); + + /* A busy cluster has no state to adopt yet. */ + priv->transition_failed = true; + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 12); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_resume(ctx->policy), 0); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 9); + KUNIT_EXPECT_TRUE(test, priv->transition_failed); + + /* A SoC that does not verify expects nothing. */ + ctx = cft_setup(test, &soc_t8112_info, 4); + cft_set_cmd(ctx->regs, 9); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_resume(ctx->policy), 0); + KUNIT_EXPECT_EQ(test, ctx->priv->expected_pstate, 4); +#else + kunit_skip(test, "needs CONFIG_SUSPEND"); +#endif +} + +/* + * Board thermal ownership cap + */ + +static void cft_test_unmanaged_max(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8132_info, 4); + unsigned int i; + + /* Highest state allowed without a thermal policy: 4. */ + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_unmanaged_max(ctx->policy), 1200000); + + mutex_lock(&apple_soc_thermal_owner_lock); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_owner_cap(ctx->policy), 1200000); + ctx->priv->thermal_owned = true; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_owner_cap(ctx->policy), + FREQ_QOS_MAX_DEFAULT_VALUE); + mutex_unlock(&apple_soc_thermal_owner_lock); + + ctx->table[1].frequency = CPUFREQ_ENTRY_INVALID; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_unmanaged_max(ctx->policy), 600000); + + /* No state is allowed: the slowest one has to do. */ + for (i = 0; i < CFT_NR_STATES; i++) + ctx->table[i].driver_data = 5 + i; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_unmanaged_max(ctx->policy), 600000); + + ctx = cft_setup(test, &soc_t8152_info, 4); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_unmanaged_max(ctx->policy), 600000); +} + +/* + * Fast die-temperature limit + */ + +static const unsigned long cft_power[CFT_NR_STATES] = { 100, 300, 500, 800, 1000 }; + +/* A limit that only knows its policy and the power of each state. */ +static struct apple_fast_die *cft_fast_die(struct kunit *test, struct cft_ctx *ctx) +{ + struct apple_fast_die *fd; + unsigned int i; + + fd = kunit_kzalloc(test, struct_size(fd, power, CFT_NR_STATES), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, fd); + fd->nr_states = CFT_NR_STATES; + for (i = 0; i < CFT_NR_STATES; i++) + fd->power[i] = cft_power[i]; + fd->policy = ctx->policy; + fd->max = ctx->table[CFT_NR_STATES - 1].frequency; + spin_lock_init(&fd->lock); + return fd; +} + +static bool cft_is_state(unsigned int freq) +{ + unsigned int i; + + for (i = 0; i < CFT_NR_STATES; i++) + if (cft_table[i].frequency == freq) + return true; + return false; +} + +static void cft_test_fast_die_fit(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 4); + struct apple_fast_die *fd = cft_fast_die(test, ctx); + + /* The slowest state when nothing fits. */ + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 0), 600000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 99), 600000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 100), 600000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 299), 600000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 300), 1200000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 999), 2400000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 1000), 3000000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, U64_MAX), 3000000); +} + +static void cft_test_fast_die_limit(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 4); + struct apple_fast_die *fd = cft_fast_die(test, ctx); + unsigned int effort, limit, last = UINT_MAX; + + /* No effort is no limit, whatever 1000 / 255 rounds to. */ + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 0), 3000000); + /* 204 / 255 of 1000 is 800, 203 / 255 is 796. */ + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 1), 2400000); + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 51), 2400000); + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 52), 1800000); + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 128), 1200000); + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 255), 600000); + + for (effort = 0; effort <= APPLE_FAST_DIE_EFFORT_MAX; effort++) { + limit = apple_fast_die_limit(fd, effort); + KUNIT_EXPECT_LE_MSG(test, limit, last, "effort %u", effort); + KUNIT_EXPECT_TRUE_MSG(test, cft_is_state(limit), "effort %u: %u", + effort, limit); + last = limit; + } + + /* Tens of watts, in microwatts: the budget needs more than 32 bits. */ + fd->power[CFT_NR_STATES - 1] = 50000000; + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 0), 3000000); + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 255), 600000); +} + +static void cft_test_fast_die_interval(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 4); + struct apple_fast_die *fd = cft_fast_die(test, ctx); + + KUNIT_EXPECT_EQ(test, ktime_to_ms(apple_fast_die_interval(fd)), 5); + /* Warned, but the PMP runs: back to the fast interval. */ + fd->warned = true; + KUNIT_EXPECT_EQ(test, ktime_to_ms(apple_fast_die_interval(fd)), 5); + fd->waiting = true; + KUNIT_EXPECT_EQ(test, ktime_to_ms(apple_fast_die_interval(fd)), 1000); + fd->warned = false; + KUNIT_EXPECT_EQ(test, ktime_to_ms(apple_fast_die_interval(fd)), 100); +} + +/* The hrtimer samples only when the per-CPU timers do not. */ +static void cft_test_fast_die_arm(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 4); + struct apple_fast_die *fd = cft_fast_die(test, ctx); + + hrtimer_setup(&fd->poll, apple_fast_die_poll, CLOCK_MONOTONIC, + HRTIMER_MODE_REL_SOFT); + /* The slowest interval: the timer is cancelled long before it runs. */ + fd->waiting = true; + fd->warned = true; + + spin_lock_bh(&fd->lock); + fd->per_cpu = true; + fd->limit = fd->max; + apple_fast_die_arm(fd); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_FALSE(test, fd->polling); + KUNIT_EXPECT_FALSE(test, hrtimer_is_queued(&fd->poll)); + + spin_lock_bh(&fd->lock); + fd->limit = fd->max - 1; + fd->stopping = true; + apple_fast_die_arm(fd); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_FALSE(test, fd->polling); + KUNIT_EXPECT_FALSE(test, hrtimer_is_queued(&fd->poll)); + + spin_lock_bh(&fd->lock); + fd->stopping = false; + apple_fast_die_arm(fd); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_TRUE(test, fd->polling); + KUNIT_EXPECT_TRUE(test, hrtimer_is_queued(&fd->poll)); + hrtimer_cancel(&fd->poll); + + /* Already polling: not armed twice. */ + spin_lock_bh(&fd->lock); + apple_fast_die_arm(fd); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_FALSE(test, hrtimer_is_queued(&fd->poll)); + + /* Without per-CPU timers the hrtimer samples at the maximum too. */ + spin_lock_bh(&fd->lock); + fd->polling = false; + fd->per_cpu = false; + fd->limit = fd->max; + apple_fast_die_arm(fd); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_TRUE(test, fd->polling); + KUNIT_EXPECT_TRUE(test, hrtimer_is_queued(&fd->poll)); + hrtimer_cancel(&fd->poll); +} + +/* A limit moves a lazily verified cluster and scaling_cur_freq with it. */ +static void cft_test_fast_die_cap(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_fast_die *fd = cft_fast_die(test, ctx); + struct apple_cpu_priv *priv = ctx->priv; + unsigned long flags; + unsigned int freq; + bool queued; + + cft_lazy_request(ctx, 4, &freq); + KUNIT_ASSERT_EQ(test, freq, 3000000); + ctx->policy->cur = freq; + + /* The fastest state at or below the limit. */ + local_irq_save(flags); + apple_fast_die_cap(fd, 2000000); + queued = cft_thaw(ctx, flags); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, priv->cap_pstate, 7); + KUNIT_EXPECT_EQ(test, priv->cap_freq, 1800000); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 7); + KUNIT_EXPECT_EQ(test, ctx->policy->cur, 1800000); + + /* A limit below every state changes nothing. */ + local_irq_save(flags); + apple_fast_die_cap(fd, 599999); + queued = cft_thaw(ctx, flags); + KUNIT_EXPECT_FALSE(test, queued); + KUNIT_EXPECT_EQ(test, priv->cap_pstate, 7); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 7); + + /* A limit that is a state is that state. */ + local_irq_save(flags); + apple_fast_die_cap(fd, 3000000); + queued = cft_thaw(ctx, flags); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, priv->cap_pstate, 15); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 15); + KUNIT_EXPECT_EQ(test, ctx->policy->cur, 3000000); +} + +/* A SoC whose requests the core limits is left to the core. */ +static void cft_test_fast_die_cap_unverified(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 15); + struct apple_fast_die *fd = cft_fast_die(test, ctx); + + ctx->policy->cur = 3000000; + apple_fast_die_cap(fd, 1800000); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 15); + KUNIT_EXPECT_EQ(test, ctx->priv->cap_pstate, soc_t8112_info.max_pstate); + KUNIT_EXPECT_EQ(test, ctx->policy->cur, 3000000); +} + +static void cft_fast_die_exit(void *data) +{ + apple_fast_die_exit(data); +} + +static void cft_free_cpus(void *data) +{ + struct cpufreq_policy *policy = data; + + free_cpumask_var(policy->cpus); +} + +static void cft_remove_opps(void *data) +{ + dev_pm_opp_remove_all_dynamic(data); +} + +/* + * A cluster ready for apple_fast_die_init(): its CPU device has an OPP for + * every state, without power, and its policy has QoS constraints and no CPU, + * so that no per-CPU timer of the machine is touched. + */ +static struct cft_ctx *cft_fast_die_setup(struct kunit *test, + const struct apple_soc_cpufreq_info *info) +{ + struct cft_ctx *ctx = cft_setup(test, info, 4); + unsigned int i; + + KUNIT_ASSERT_TRUE(test, zalloc_cpumask_var(&ctx->policy->cpus, GFP_KERNEL)); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, cft_free_cpus, + ctx->policy), 0); + freq_constraints_init(&ctx->policy->constraints); + + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, cft_remove_opps, + ctx->priv->cpu_dev), 0); + for (i = 0; i < CFT_NR_STATES; i++) { + struct dev_pm_opp_data opp = { + .level = ctx->table[i].driver_data, + .freq = ctx->table[i].frequency * 1000UL, + .u_volt = 800000, + }; + + KUNIT_ASSERT_EQ(test, dev_pm_opp_add_dynamic(ctx->priv->cpu_dev, &opp), 0); + } + + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, cft_fast_die_exit, + ctx->priv), 0); + return ctx; +} + +/* A cluster node with @value as its apple,fast-die-effort, or without one. */ +static struct device_node *cft_cluster_node(struct kunit *test, __be32 *value, + unsigned int cells) +{ + struct device_node *np; + struct property *prop; + + np = kunit_kzalloc(test, sizeof(*np), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, np); + np->name = "cpufreq"; + np->full_name = "cpufreq-test"; + if (!value) + return np; + + prop = kunit_kzalloc(test, sizeof(*prop), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, prop); + prop->name = "apple,fast-die-effort"; + prop->value = value; + prop->length = cells * sizeof(*value); + np->properties = prop; + return np; +} + +static s32 cft_qos_max(struct cft_ctx *ctx) +{ + return freq_qos_read_value(&ctx->policy->constraints, FREQ_QOS_MAX); +} + +/* No limit described, none needed: nothing is set up. */ +static void cft_test_fast_die_init_none(struct kunit *test) +{ + struct cft_ctx *ctx = cft_fast_die_setup(test, &soc_t8112_info); + struct device_node *np = cft_cluster_node(test, NULL, 0); + + KUNIT_EXPECT_EQ(test, apple_fast_die_init(ctx->policy, np), 0); + KUNIT_EXPECT_NULL(test, ctx->priv->fast_die); + KUNIT_EXPECT_EQ(test, cft_qos_max(ctx), FREQ_QOS_MAX_DEFAULT_VALUE); +} + +/* A SoC that needs the limit is held at the fallback by an older devicetree. */ +static void cft_test_fast_die_init_required(struct kunit *test) +{ + struct cft_ctx *ctx = cft_fast_die_setup(test, &soc_t8140_info); + struct device_node *np = cft_cluster_node(test, NULL, 0); + struct apple_fast_die *fd; + unsigned int i; + + KUNIT_ASSERT_EQ(test, apple_fast_die_init(ctx->policy, np), 0); + fd = ctx->priv->fast_die; + KUNIT_ASSERT_NOT_NULL(test, fd); + + spin_lock_bh(&fd->lock); + KUNIT_EXPECT_NULL(test, fd->report); + KUNIT_EXPECT_TRUE(test, fd->warned); + KUNIT_EXPECT_EQ(test, fd->nr_states, CFT_NR_STATES); + /* The OPPs describe no power: the frequency stands in. */ + for (i = 0; i < CFT_NR_STATES; i++) + KUNIT_EXPECT_EQ(test, fd->power[i], ctx->table[i].frequency); + KUNIT_EXPECT_EQ(test, fd->max, 3000000); + /* The fastest state with at most a third of the fastest state's power. */ + KUNIT_EXPECT_EQ(test, fd->fallback, 600000); + KUNIT_EXPECT_EQ(test, fd->limit, 600000); + spin_unlock_bh(&fd->lock); + + KUNIT_EXPECT_EQ(test, cft_qos_max(ctx), 600000); + /* Fast-switch requests are clamped from the start. */ + KUNIT_EXPECT_EQ(test, ctx->priv->cap_pstate, 1); + KUNIT_EXPECT_EQ(test, ctx->priv->cap_freq, 600000); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + + apple_fast_die_exit(ctx->priv); + KUNIT_EXPECT_NULL(test, ctx->priv->fast_die); + KUNIT_EXPECT_EQ(test, cft_qos_max(ctx), FREQ_QOS_MAX_DEFAULT_VALUE); +} + +KUNIT_DEFINE_ACTION_WRAPPER(cft_put_report, of_node_put, struct device_node *); + +/* The property names the PMP report node and the lane of the cluster. */ +static void cft_test_fast_die_init_described(struct kunit *test) +{ + struct cft_ctx *ctx = cft_fast_die_setup(test, &soc_t8140_info); + struct device_node *np, *report; + struct apple_fast_die *fd; + __be32 *value; + int ret; + + /* Hold a reference to the first node that can stand in for the report. */ + for (report = of_find_all_nodes(NULL); report; + report = of_find_all_nodes(report)) { + if (report->phandle) + break; + } + if (!report) + kunit_skip(test, "no devicetree node with a phandle"); + ret = kunit_add_action_or_reset(test, cft_put_report, report); + KUNIT_ASSERT_EQ(test, ret, 0); + + value = kunit_kzalloc(test, 2 * sizeof(*value), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, value); + value[0] = cpu_to_be32(report->phandle); + value[1] = cpu_to_be32(3); + np = cft_cluster_node(test, value, 2); + + KUNIT_ASSERT_EQ(test, apple_fast_die_init(ctx->policy, np), 0); + fd = ctx->priv->fast_die; + KUNIT_ASSERT_NOT_NULL(test, fd); + + spin_lock_bh(&fd->lock); + KUNIT_EXPECT_PTR_EQ(test, fd->report, report); + KUNIT_EXPECT_EQ(test, fd->lane, 3); + KUNIT_EXPECT_FALSE(test, fd->warned); + /* Held at the fallback until the PMP is found running. */ + KUNIT_EXPECT_EQ(test, fd->limit, 600000); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_EQ(test, cft_qos_max(ctx), 600000); + + apple_fast_die_exit(ctx->priv); + KUNIT_EXPECT_NULL(test, ctx->priv->fast_die); +} + +/* A misdescribed limit fails closed, also where none is required. */ +static void cft_test_fast_die_init_invalid(struct kunit *test) +{ + struct cft_ctx *ctx = cft_fast_die_setup(test, &soc_t8112_info); + struct apple_fast_die *fd; + struct device_node *np; + __be32 *value; + + /* A phandle without the lane cell. */ + value = kunit_kzalloc(test, sizeof(*value), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, value); + value[0] = cpu_to_be32(1); + np = cft_cluster_node(test, value, 1); + + KUNIT_ASSERT_EQ(test, apple_fast_die_init(ctx->policy, np), 0); + fd = ctx->priv->fast_die; + KUNIT_ASSERT_NOT_NULL(test, fd); + + spin_lock_bh(&fd->lock); + KUNIT_EXPECT_NULL(test, fd->report); + KUNIT_EXPECT_TRUE(test, fd->warned); + KUNIT_EXPECT_EQ(test, fd->limit, 600000); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_EQ(test, cft_qos_max(ctx), 600000); + + apple_fast_die_exit(ctx->priv); + KUNIT_EXPECT_EQ(test, cft_qos_max(ctx), FREQ_QOS_MAX_DEFAULT_VALUE); +} + +static struct kunit_case apple_soc_cpufreq_test_cases[] = { + KUNIT_CASE_PARAM(cft_test_layout, cft_layout_gen_params), + KUNIT_CASE(cft_test_layout_invariants), + KUNIT_CASE_PARAM(cft_test_write, cft_write_gen_params), + KUNIT_CASE(cft_test_timeout), + KUNIT_CASE(cft_test_request), + KUNIT_CASE(cft_test_request_range), + KUNIT_CASE(cft_test_set_pstate_busy), + KUNIT_CASE(cft_test_set_pstate_verified), + KUNIT_CASE(cft_test_set_pstate_unexpected), + KUNIT_CASE(cft_test_set_pstate_verified_busy), + KUNIT_CASE(cft_test_fast_switch), + KUNIT_CASE(cft_test_pstate_freq), + KUNIT_CASE(cft_test_lazy_idle), + KUNIT_CASE(cft_test_lazy_busy), + KUNIT_CASE(cft_test_lazy_pending_same), + KUNIT_CASE(cft_test_lazy_unexpected), + KUNIT_CASE(cft_test_lazy_verify_fails), + KUNIT_CASE(cft_test_lazy_range), + KUNIT_CASE(cft_test_lazy_fast_switch), + KUNIT_CASE(cft_test_lazy_cap), + KUNIT_CASE(cft_test_lazy_cap_waited), + KUNIT_CASE(cft_test_drain), + KUNIT_CASE(cft_test_set_target_lazy), + KUNIT_CASE(cft_test_suspend_lazy), + KUNIT_CASE(cft_test_resume), + KUNIT_CASE(cft_test_unmanaged_max), + KUNIT_CASE(cft_test_fast_die_fit), + KUNIT_CASE(cft_test_fast_die_limit), + KUNIT_CASE(cft_test_fast_die_interval), + KUNIT_CASE(cft_test_fast_die_arm), + KUNIT_CASE(cft_test_fast_die_cap), + KUNIT_CASE(cft_test_fast_die_cap_unverified), + KUNIT_CASE(cft_test_fast_die_init_none), + KUNIT_CASE(cft_test_fast_die_init_required), + KUNIT_CASE(cft_test_fast_die_init_described), + KUNIT_CASE(cft_test_fast_die_init_invalid), + {} +}; + +static struct kunit_suite apple_soc_cpufreq_test_suite = { + .name = "apple_soc_cpufreq", + .exit = cft_exit, + .test_cases = apple_soc_cpufreq_test_cases, +}; + +/* + * Tests on a policy of the cpufreq core + * + * ->get() finds its policy through the core, and the thermal ownership call + * takes the policy lock and checks which driver is registered. The suite + * registers a driver under this driver's name whose policies carry a cluster + * as above; its ->target_index() does nothing, so that the governor of the + * policy never touches the cluster the tests work on. + */ + +static u8 *cft_live_regs; +static struct apple_cpu_priv *cft_live_priv; +static struct cpufreq_frequency_table cft_live_table[CFT_NR_STATES + 1]; +static int cft_live_ret = -ENODEV; + +static int cft_live_init(struct cpufreq_policy *policy) +{ + policy->driver_data = cft_live_priv; + policy->freq_table = cft_live_table; + policy->cur = cft_live_table[0].frequency; + return 0; +} + +static void cft_live_exit(struct cpufreq_policy *policy) +{ + policy->driver_data = NULL; +} + +static int cft_live_target(struct cpufreq_policy *policy, unsigned int index) +{ + return 0; +} + +static struct cpufreq_driver cft_live_driver = { + .name = "apple-cpufreq", + .flags = CPUFREQ_HAVE_GOVERNOR_PER_POLICY, + .verify = cpufreq_generic_frequency_table_verify, + .init = cft_live_init, + .exit = cft_live_exit, + .target_index = cft_live_target, +}; + +static int cft_live_suite_init(struct kunit_suite *suite) +{ + cft_live_regs = kzalloc(CFT_REGS_SIZE, GFP_KERNEL); + cft_live_priv = kzalloc_obj(*cft_live_priv); + if (!cft_live_regs || !cft_live_priv) { + cft_live_ret = -ENOMEM; + return 0; + } + + memcpy(cft_live_table, cft_table, sizeof(cft_table)); + cft_live_priv->cpu_dev = get_cpu_device(cpumask_first(cpu_online_mask)); + cft_priv_init(cft_live_priv, cft_live_regs, &soc_default_info, 4); + + cft_live_ret = cpufreq_register_driver(&cft_live_driver); + return 0; +} + +static void cft_live_suite_exit(struct kunit_suite *suite) +{ + if (!cft_live_ret) + cpufreq_unregister_driver(&cft_live_driver); + cft_live_ret = -ENODEV; + kfree(cft_live_priv); + kfree(cft_live_regs); + cft_live_priv = NULL; + cft_live_regs = NULL; +} + +static int cft_live_test_init(struct kunit *test) +{ + if (cft_live_ret == -EEXIST) + kunit_skip(test, "a cpufreq driver is already registered"); + KUNIT_ASSERT_EQ(test, cft_live_ret, 0); + KUNIT_ASSERT_STREQ(test, cft_live_driver.name, apple_soc_cpufreq_driver.name); + return 0; +} + +static void cft_live_test_exit(struct kunit *test) +{ + if (cft_live_ret) + return; + cft_live_priv->info = &soc_default_info; + cft_set_cmd(cft_live_regs, 4); + cft_set_status(cft_live_regs, 0); +} + +struct cft_get { + const char *name; + const struct apple_soc_cpufreq_info *info; + u32 status; + u64 cmd; + unsigned int freq; +}; + +/* + * The current state sits in the status register at a place that moved from + * SoC to SoC; every other bit of the register is set, the target state next + * to it included. Without a known status layout the last request stands in. + */ +static const struct cft_get cft_gets[] = { + { "s5l8960x status bits 5:3", &soc_s5l8960x_info, + ~(u32)GENMASK(5, 3) | (4 << 3), ~0ULL, 1200000 }, + { "t8103 status bits 7:4", &soc_t8103_info, + ~(u32)GENMASK(7, 4) | (10 << 4), ~0ULL, 2400000 }, + { "t8112 status bits 9:5", &soc_t8112_info, + ~(u32)GENMASK(9, 5) | (15 << 5), ~0ULL, 3000000 }, + { "t8112 lowest state", &soc_t8112_info, + ~(u32)GENMASK(9, 5) | (1 << 5), ~0ULL, 600000 }, + { "generic command state", &soc_default_info, + ~0U, ~GENMASK_ULL(4, 0) | 7, 1800000 }, + { "t8132 command state", &soc_t8132_info, + 0, ~GENMASK_ULL(4, 0) | 10, 2400000 }, + { "t8140 command state", &soc_t8140_info, + ~0U, 15, 3000000 }, + /* States without a frequency-table entry have no frequency. */ + { "t8103 unknown state", &soc_t8103_info, + ~(u32)GENMASK(7, 4) | (5 << 4), 4, 0 }, + { "t8112 state beyond the table", &soc_t8112_info, ~0U, 4, 0 }, + { "t8112 state 0", &soc_t8112_info, 0, 4, 0 }, + { "generic state beyond the table", &soc_default_info, 4 << 4, ~0ULL, 0 }, +}; + +static void cft_get_desc(const struct cft_get *g, char *desc) +{ + strscpy(desc, g->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(cft_get, cft_gets, cft_get_desc); + +static void cft_test_get(struct kunit *test) +{ + const struct cft_get *g = test->param_value; + + cft_live_priv->info = g->info; + cft_set_status(cft_live_regs, g->status); + cft_set_cmd(cft_live_regs, g->cmd); + KUNIT_EXPECT_EQ(test, + apple_soc_cpufreq_get_rate(cpumask_first(cpu_online_mask)), + g->freq); +} + +/* The thermal driver takes the higher states and gives them back. */ +static void cft_test_thermal_owner(struct kunit *test) +{ + struct apple_cpu_priv *priv = cft_live_priv; + struct cpufreq_policy *policy; + int ret; + + policy = cpufreq_cpu_get(cpumask_first(cpu_online_mask)); + KUNIT_ASSERT_NOT_NULL(test, policy); + priv->info = &soc_t8132_info; + + /* A cluster that is not held back has nothing to hand over. */ + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_thermal_owner(policy, true), + -ENODEV); + KUNIT_EXPECT_FALSE(test, priv->thermal_owned); + + /* As apple_soc_cpufreq_init() holds it back. */ + mutex_lock(&apple_soc_thermal_owner_lock); + ret = freq_qos_add_request(&policy->constraints, &priv->unmanaged_cap, + FREQ_QOS_MAX, apple_soc_cpufreq_owner_cap(policy)); + mutex_unlock(&apple_soc_thermal_owner_lock); + KUNIT_EXPECT_GE(test, ret, 0); + if (ret < 0) + goto out; + KUNIT_EXPECT_EQ(test, freq_qos_read_value(&policy->constraints, FREQ_QOS_MAX), + 1200000); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_thermal_owner(policy, true), 0); + KUNIT_EXPECT_TRUE(test, priv->thermal_owned); + KUNIT_EXPECT_GE(test, freq_qos_read_value(&policy->constraints, FREQ_QOS_MAX), + 3000000); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_thermal_owner(policy, true), 0); + KUNIT_EXPECT_TRUE(test, priv->thermal_owned); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_thermal_owner(policy, false), 0); + KUNIT_EXPECT_FALSE(test, priv->thermal_owned); + KUNIT_EXPECT_EQ(test, freq_qos_read_value(&policy->constraints, FREQ_QOS_MAX), + 1200000); + + freq_qos_remove_request(&priv->unmanaged_cap); +out: + priv->thermal_owned = false; + cpufreq_cpu_put(policy); +} + +static struct kunit_case apple_soc_cpufreq_policy_test_cases[] = { + KUNIT_CASE_PARAM(cft_test_get, cft_get_gen_params), + KUNIT_CASE(cft_test_thermal_owner), + {} +}; + +static struct kunit_suite apple_soc_cpufreq_policy_test_suite = { + .name = "apple_soc_cpufreq_policy", + .suite_init = cft_live_suite_init, + .suite_exit = cft_live_suite_exit, + .init = cft_live_test_init, + .exit = cft_live_test_exit, + .test_cases = apple_soc_cpufreq_policy_test_cases, +}; + +kunit_test_suites(&apple_soc_cpufreq_test_suite, + &apple_soc_cpufreq_policy_test_suite); diff --git a/drivers/cpufreq/apple-soc-cpufreq.c b/drivers/cpufreq/apple-soc-cpufreq.c index 09233d4b4208d7..beb06e86090a6c 100644 --- a/drivers/cpufreq/apple-soc-cpufreq.c +++ b/drivers/cpufreq/apple-soc-cpufreq.c @@ -314,10 +314,17 @@ static const struct apple_soc_cpufreq_info soc_t8142_info = { .ps1_shift = APPLE_DVFS_CMD_PS1_SHIFT, }; -/* T8152 ACC uses state 2 as the first OPP and shares P/M requests. */ +/* + * T8152 ACC uses state 2 as the first OPP and shares P/M requests. It has no + * PMP fast die-temperature loop, so states above 3 are held back until the + * board's thermal policy takes ownership, see + * apple_soc_cpufreq_set_thermal_owner(): the SMC thermal zones once they + * throttle the cluster (macsmc-hwmon). This bootstrap ceiling is a Linux + * restriction, not a firmware thermal or safety limit. + */ static const struct apple_soc_cpufreq_info soc_t8152_info = { .verify_transition = true, - .needs_thermal_policy = true, + .needs_thermal_owner = true, .transition_timeout_us = 2000, .max_unmanaged_pstate = 3, .min_pstate = 2, @@ -1626,6 +1633,19 @@ static int __init apple_soc_cpufreq_module_init(void) if (!of_machine_is_compatible("apple,arm-platform")) return -ENODEV; + + /* + * Boost only means something with turbo-mode OPPs. Without any, no + * policy supports it, and turning it on through the global "boost" + * file fails with -EINVAL; power-profiles-daemon then cannot set its + * profile. Offer no boost control on such SoCs. + */ + np = of_find_node_with_property(NULL, "turbo-mode"); + if (np) + of_node_put(np); + else + apple_soc_cpufreq_driver.set_boost = NULL; + if (of_machine_is_compatible("apple,t8132")) { apple_soc_cpufreq_driver.online = apple_soc_cpufreq_online; apple_soc_cpufreq_driver.offline = apple_soc_cpufreq_offline; @@ -1680,6 +1700,10 @@ static void __exit apple_soc_cpufreq_module_exit(void) } module_exit(apple_soc_cpufreq_module_exit); +#if IS_ENABLED(CONFIG_ARM_APPLE_SOC_CPUFREQ_KUNIT_TEST) +#include "apple-soc-cpufreq-test.c" +#endif + MODULE_DEVICE_TABLE(of, apple_soc_cpufreq_of_match); MODULE_AUTHOR("Hector Martin "); MODULE_DESCRIPTION("Apple SoC CPU cluster DVFS driver"); diff --git a/drivers/cpufreq/apple-soc-cpufreq.kunitconfig b/drivers/cpufreq/apple-soc-cpufreq.kunitconfig new file mode 100644 index 00000000000000..68ca699bc91a4e --- /dev/null +++ b/drivers/cpufreq/apple-soc-cpufreq.kunitconfig @@ -0,0 +1,9 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/cpufreq/apple-soc-cpufreq.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_PM=y +CONFIG_SUSPEND=y +CONFIG_CPU_FREQ=y +CONFIG_ARM_APPLE_SOC_CPUFREQ=y +CONFIG_ARM_APPLE_SOC_CPUFREQ_KUNIT_TEST=y diff --git a/drivers/dma/Kconfig b/drivers/dma/Kconfig index 924164e62f1a3f..aa35dfcab74481 100644 --- a/drivers/dma/Kconfig +++ b/drivers/dma/Kconfig @@ -127,6 +127,9 @@ config APPLE_SIO_KUNIT_TEST generic SIO of the M1 and M2, and a T6030 SIO only with validated protocol-10 boot tables. The compatible selects the firmware layout. Also check protocol-9 table order, DMA array counts and ACK failures. + And check that a firmware ACK, NACK or report naming a tag that + is not outstanding, or a channel the device does not have, is + dropped. config APPLE_SIO_T6030_KUNIT_TEST bool "KUnit tests for the T6030 SIO boot-table check" if !KUNIT_ALL_TESTS diff --git a/drivers/dma/apple-admac-test.h b/drivers/dma/apple-admac-test.h index 24d390b9d6d5b1..26bb3472ea03e6 100644 --- a/drivers/dma/apple-admac-test.h +++ b/drivers/dma/apple-admac-test.h @@ -185,9 +185,63 @@ static void admac_realign_only_a_configured_capture(struct kunit *test) KUNIT_EXPECT_FALSE(test, admac_resume_realigns(&adchan)); } +/* + * The client's peripheral config is only valid while it configures the + * channel: a restore after a system sleep keeps the frame size taken then and + * does not read the client's memory again. + */ +static void admac_restore_keeps_the_frame_size(struct kunit *test) +{ + struct dma_slave_config config = {}; + struct admac_chan *adchan; + struct admac_data *ad; + void *regs; + u32 *frame; + + /* A capture channel (1) of a two-channel controller, its registers plain memory */ + ad = kunit_kzalloc(test, struct_size(ad, channels, 2), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ad); + ad->nchannels = 2; + regs = kunit_kzalloc(test, REG_CHAN_BASE(ad, 2), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, regs); + ad->base = (void __iomem *)regs; + adchan = &ad->channels[1]; + adchan->no = 1; + adchan->host = ad; + + frame = kunit_kzalloc(test, sizeof(*frame), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, frame); + *frame = 16; + + config.direction = DMA_DEV_TO_MEM; + config.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES; + config.src_port_window_size = 4; + config.peripheral_config = frame; + config.peripheral_size = sizeof(*frame); + KUNIT_ASSERT_EQ(test, admac_device_config(&adchan->chan, &config), 0); + KUNIT_EXPECT_EQ(test, adchan->realign_bytes, 16); + KUNIT_EXPECT_TRUE(test, adchan->cfg_valid); + KUNIT_EXPECT_NULL(test, adchan->cfg.peripheral_config); + KUNIT_EXPECT_EQ(test, adchan->cfg.peripheral_size, 0); + + /* The client's memory is reused, the channel's registers are lost */ + memset(frame, 0xa5, sizeof(*frame)); + writel_relaxed(0, ad->base + REG_BUS_WIDTH(ad, adchan->no)); + adchan->lost = true; + admac_restore_chan(adchan); + + KUNIT_EXPECT_FALSE(test, adchan->lost); + KUNIT_EXPECT_EQ(test, adchan->realign_bytes, 16); + KUNIT_EXPECT_NULL(test, adchan->cfg.peripheral_config); + /* The rest of the configuration is programmed again */ + KUNIT_EXPECT_EQ(test, readl_relaxed(ad->base + REG_BUS_WIDTH(ad, adchan->no)), + BUS_WIDTH_32BIT | BUS_WIDTH_FRAME_4_WORDS); +} + static struct kunit_case admac_realign_cases[] = { KUNIT_CASE(admac_realign_needs_a_frame_size), KUNIT_CASE(admac_realign_only_a_configured_capture), + KUNIT_CASE(admac_restore_keeps_the_frame_size), {} }; diff --git a/drivers/dma/apple-admac.c b/drivers/dma/apple-admac.c index e330bb9300975e..a42ba9559db11c 100644 --- a/drivers/dma/apple-admac.c +++ b/drivers/dma/apple-admac.c @@ -78,13 +78,29 @@ */ #define REG_CHAN_BASE_LEGACY(ch) (0x8000 + (ch) * 0x200) #define REG_CHAN_BASE_EVOLVED(ch) (((ch) & 1 ? 0xc000 : 0x8000) + ((ch) / 2) * 0x200) -#define REG_CHAN_BASE(ad, ch) ((ad)->evolved_layout ? \ +/* + * T8152 (ADT admac-evolution,t8152; the macOS AudioDMAController-T8152 + * driver): the same per-channel block, 0x4000 apart, TX at 0x40000 and RX + * at 0x80000, and a channel has to be put in state 2 (+0x30 bits 3:0) + * before it is started. The descriptor and report FIFO ports are the legacy + * ones (the RX descriptor port answers at 0x14000 + 4n, not at the ADT's + * 0x10040 + 4n). + */ +#define REG_CHAN_BASE_T8152(ch) (((ch) & 1 ? 0x80000 : 0x40000) + ((ch) / 2) * 0x4000) +#define REG_CHAN_BASE(ad, ch) ((ad)->t8152_layout ? REG_CHAN_BASE_T8152(ch) : \ + (ad)->evolved_layout ? \ REG_CHAN_BASE_EVOLVED(ch) : REG_CHAN_BASE_LEGACY(ch)) #define REG_CHAN_CTL(ad, ch) (REG_CHAN_BASE(ad, ch) + 0x00) #define REG_CHAN_CTL_RST_RINGS BIT(0) #define REG_CHAN_CONFIG(ad, ch) (REG_CHAN_BASE(ad, ch) + 0x04) +/* macOS writes this for the T8152 base-ns channels before every start */ +#define CHAN_CONFIG_T8152 0x029b0000 #define REG_CHAN_BURST(ad, ch) (REG_CHAN_BASE(ad, ch) + 0x30) +/* T8152: the low nibble of the same register is the channel state */ +#define REG_CHAN_STATE(ad, ch) REG_CHAN_BURST(ad, ch) +#define CHAN_STATE_MASK GENMASK(3, 0) +#define CHAN_STATE_READY 2 #define REG_DESC_RING(ad, ch) (REG_CHAN_BASE(ad, ch) + 0x70) #define REG_REPORT_RING(ad, ch) (REG_CHAN_BASE(ad, ch) + 0x74) @@ -112,6 +128,11 @@ #define REG_DESC_WRITE(ch) (0x10000 + ((ch) / 2) * 0x4 + ((ch) & 1) * 0x4000) #define REG_REPORT_READ(ch) (0x10100 + ((ch) / 2) * 0x4 + ((ch) & 1) * 0x4000) +/* T8152: the AP's share of each SRAM pool starts above the firmware's. */ +#define T8152_SRAM_BASE 0x1000 +#define T8152_SRAM_BLOCK 1024 +#define SRAM_SIZE_MASK GENMASK(15, 0) + #define REG_TX_INTSTATE(idx) (0x0030 + (idx) * 4) #define REG_RX_INTSTATE(idx) (0x0040 + (idx) * 4) #define REG_GLOBAL_INTSTATE(idx) (0x0050 + (idx) * 4) @@ -163,6 +184,8 @@ struct admac_chan { struct tasklet_struct tasklet; u32 carveout; + /* T8152: transfer descriptor id, 1..255 */ + u8 desc_id; spinlock_t lock; struct admac_tx *current_tx; @@ -214,6 +237,7 @@ struct admac_data { bool evolved_layout; bool split_channels; bool display; + bool t8152_layout; bool ctl_programmed; /* Display ADMAC: its control block's two windows and their tunables */ void __iomem *control[2]; @@ -247,6 +271,7 @@ struct admac_hw { bool evolved_layout; bool split_channels; bool display; + bool t8152_layout; }; static int admac_alloc_sram_carveout(struct admac_data *ad, @@ -255,6 +280,8 @@ static int admac_alloc_sram_carveout(struct admac_data *ad, { struct admac_sram *sram; int i, ret = 0, nblocks; + u32 first = 0, block = SRAM_BLOCK; + ad->txcache.size = readl_relaxed(ad->base + REG_TX_SRAM_SIZE); ad->rxcache.size = readl_relaxed(ad->base + REG_RX_SRAM_SIZE); /* T8132 reports channel metadata in the upper half of these words. */ @@ -262,6 +289,13 @@ static int admac_alloc_sram_carveout(struct admac_data *ad, ad->txcache.size &= GENMASK(15, 0); ad->rxcache.size &= GENMASK(15, 0); } + if (ad->t8152_layout) { + /* bits 31:24 are the channel count */ + ad->txcache.size &= SRAM_SIZE_MASK; + ad->rxcache.size &= SRAM_SIZE_MASK; + first = T8152_SRAM_BASE; + block = T8152_SRAM_BLOCK; + } if (dir == DMA_MEM_TO_DEV) sram = &ad->txcache; @@ -270,14 +304,14 @@ static int admac_alloc_sram_carveout(struct admac_data *ad, mutex_lock(&ad->cache_alloc_lock); - nblocks = sram->size / SRAM_BLOCK; + nblocks = sram->size > first ? (sram->size - first) / block : 0; for (i = ad->split_channels ? 1 : 0; i < nblocks; i++) if (!(sram->allocated & BIT(i))) break; if (i < nblocks) { - *out = FIELD_PREP(CHAN_SRAM_CARVEOUT_BASE, i * SRAM_BLOCK) | - FIELD_PREP(CHAN_SRAM_CARVEOUT_SIZE, SRAM_BLOCK); + *out = FIELD_PREP(CHAN_SRAM_CARVEOUT_BASE, first + i * block) | + FIELD_PREP(CHAN_SRAM_CARVEOUT_SIZE, block); sram->allocated |= BIT(i); } else { ret = -EBUSY; @@ -294,18 +328,24 @@ static void admac_free_sram_carveout(struct admac_data *ad, { struct admac_sram *sram; u32 base = FIELD_GET(CHAN_SRAM_CARVEOUT_BASE, carveout); + u32 first = 0, block = SRAM_BLOCK; int i; + if (ad->t8152_layout) { + first = T8152_SRAM_BASE; + block = T8152_SRAM_BLOCK; + } + if (dir == DMA_MEM_TO_DEV) sram = &ad->txcache; else sram = &ad->rxcache; - if (WARN_ON(base >= sram->size)) + if (WARN_ON(base < first || base >= sram->size)) return; mutex_lock(&ad->cache_alloc_lock); - i = base / SRAM_BLOCK; + i = (base - first) / block; sram->allocated &= ~BIT(i); mutex_unlock(&ad->cache_alloc_lock); } @@ -409,6 +449,15 @@ static void admac_write_hw_desc(struct admac_data *ad, int channo, adchan->seq = adchan->seq == 0xff ? 1 : adchan->seq + 1; flags = DISPLAY_FLAG_DESC_REPORT | adchan->seq; + } else if (ad->t8152_layout) { + /* + * T8152: the low byte of the last word is a descriptor id, + * which macOS counts 1..255 and never leaves at 0. + */ + struct admac_chan *adchan = &ad->channels[channo]; + + adchan->desc_id = adchan->desc_id == 255 ? 1 : adchan->desc_id + 1; + flags = FLAG_DESC_NOTIFY | adchan->desc_id; } dev_dbg(ad->dev, "ch%d descriptor: addr=0x%pad len=0x%zx flags=0x%x\n", @@ -671,6 +720,11 @@ static void admac_start_chan(struct admac_chan *adchan) writel_relaxed(STATUS_DESC_DONE | STATUS_ERR, ad->base + REG_CHAN_INTMASK(ad, adchan->no, ad->irq_index)); } + if (ad->t8152_layout) { + writel_relaxed(CHAN_CONFIG_T8152, ad->base + REG_CHAN_CONFIG(ad, adchan->no)); + admac_modify(ad, REG_CHAN_STATE(ad, adchan->no), CHAN_STATE_MASK, + CHAN_STATE_READY); + } switch (admac_chan_direction(adchan->no)) { case DMA_MEM_TO_DEV: @@ -768,7 +822,8 @@ static void admac_reset_rings(struct admac_chan *adchan) writel_relaxed(0, ad->base + REG_CHAN_CTL(ad, adchan->no)); } -static int admac_device_config(struct dma_chan *chan, struct dma_slave_config *config); +static int admac_program_config(struct admac_chan *adchan, + const struct dma_slave_config *config); /* Registers can't be reached before a client powers the fabric, so this waits for it. */ static void admac_restore_chan(struct admac_chan *adchan) @@ -782,8 +837,9 @@ static void admac_restore_chan(struct admac_chan *adchan) if (ad->split_channels || ad->display) writel_relaxed(T8132_CTL_VAL, ad->base + REG_CTL); writel_relaxed(adchan->carveout, ad->base + REG_CHAN_SRAM_CARVEOUT(ad, adchan->no)); + /* The registers only: realign_bytes was taken when the client configured. */ if (adchan->cfg_valid) - admac_device_config(&adchan->chan, &adchan->cfg); + admac_program_config(adchan, &adchan->cfg); } /* @@ -1411,10 +1467,10 @@ static int admac_display_probe_control(struct admac_data *ad) return 0; } -static int admac_device_config(struct dma_chan *chan, - struct dma_slave_config *config) +/* Program a channel's registers from @config, a client's or the saved copy. */ +static int admac_program_config(struct admac_chan *adchan, + const struct dma_slave_config *config) { - struct admac_chan *adchan = to_admac_chan(chan); struct admac_data *ad = adchan->host; bool is_tx = admac_chan_direction(adchan->no) == DMA_MEM_TO_DEV; int wordsize = 0; @@ -1445,7 +1501,8 @@ static int admac_device_config(struct dma_chan *chan, * of words position in a frame. That's where the importance of this control * comes from. */ - switch (is_tx ? config->dst_port_window_size : config->src_port_window_size) { + switch (ad->t8152_layout ? 0 : + is_tx ? config->dst_port_window_size : config->src_port_window_size) { case 0 ... 1: break; case 2: @@ -1465,8 +1522,6 @@ static int admac_device_config(struct dma_chan *chan, writel_relaxed(bus_width, ad->base + REG_BUS_WIDTH(ad, adchan->no)); - adchan->realign_bytes = admac_config_realign_bytes(config); - /* * By FIFOCTL_LIMIT we seem to set the maximal number of bytes allowed to be * held in controller's per-channel FIFO. Transfers seem to be triggered @@ -1485,7 +1540,28 @@ static int admac_device_config(struct dma_chan *chan, ad->base + REG_CHAN_FIFOCTL(ad, adchan->no)); } + return 0; +} + +static int admac_device_config(struct dma_chan *chan, + struct dma_slave_config *config) +{ + struct admac_chan *adchan = to_admac_chan(chan); + int ret; + + ret = admac_program_config(adchan, config); + if (ret) + return ret; + + /* + * The peripheral config is the client's memory and only valid during + * this call: take the frame size from it now and keep no pointer to it + * in the copy a restore programs the channel from. + */ + adchan->realign_bytes = admac_config_realign_bytes(config); adchan->cfg = *config; + adchan->cfg.peripheral_config = NULL; + adchan->cfg.peripheral_size = 0; adchan->cfg_valid = true; return 0; @@ -1588,6 +1664,7 @@ static int admac_probe(struct platform_device *pdev) ad->evolved_layout = hw->evolved_layout; ad->split_channels = hw->split_channels; ad->display = hw->display; + ad->t8152_layout = hw->t8152_layout; mutex_init(&ad->cache_alloc_lock); if (ad->display) { @@ -1751,8 +1828,13 @@ static const struct admac_hw admac_t6050_display_hw = { .display = true, }; +static const struct admac_hw admac_t8152_hw = { + .t8152_layout = true, +}; + static const struct of_device_id admac_of_match[] = { { .compatible = "apple,t6050-display-admac", .data = &admac_t6050_display_hw }, + { .compatible = "apple,t8152-admac", .data = &admac_t8152_hw }, { .compatible = "apple,t8140-admac", .data = &admac_t8140_hw }, { .compatible = "apple,t8132-admac", .data = &admac_t8132_hw }, { .compatible = "apple,t8122-admac", .data = &admac_t8122_hw }, diff --git a/drivers/dma/apple-sio-msg-test.c b/drivers/dma/apple-sio-msg-test.c new file mode 100644 index 00000000000000..321b4f1bf9061b --- /dev/null +++ b/drivers/dma/apple-sio-msg-test.c @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by apple-sio.c: the checks sio_recv_msg() applies to the tag and + * the channel a firmware message names. + */ +#include +#include + +static u64 sio_test_msg(u8 type, u8 tag, u8 sioep) +{ + return FIELD_PREP(SIOMSG_TYPE, type) | FIELD_PREP(SIOMSG_TAG, tag) | + FIELD_PREP(SIOMSG_EP, sioep); +} + +/* + * The firmware's ACKs, NACKs and reports name a tag and a channel. Only a + * tag the host has outstanding is completed; tag 0, tags past the table and + * channels past the device's are dropped without a WARN. + */ +static void sio_recv_msg_checks_tag_and_channel_test(struct kunit *test) +{ + bool tainted = test_taint(TAINT_WARN); + struct sio_data *sio; + struct device *dev; + + dev = kunit_device_register(test, "apple-sio-msg-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + sio = kunit_kzalloc(test, struct_size(sio, channels, 1), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sio); + sio->dev = dev; + sio->nchannels = 1; + /* As allocated, before the probe sets anything up. */ + init_completion(&sio->tags.completions[3]); + init_completion(&sio->tags.completions[4]); + + sio_recv_msg(sio, EP_SIO, sio_test_msg(MSG_ACK, 0, 0)); + KUNIT_EXPECT_EQ(test, sio->tags.completions[0].done, 0); + KUNIT_EXPECT_FALSE(test, sio->tags.acked[0]); + + sio_recv_msg(sio, EP_SIO, sio_test_msg(MSG_ACK, 17, 0)); + sio_recv_msg(sio, EP_SIO, sio_test_msg(MSG_NACK, 63, 0)); + sio_recv_msg(sio, EP_SIO, sio_test_msg(MSG_REPORT, 1, 0xff)); + + /* Tag 4 was never handed out. */ + sio_recv_msg(sio, EP_SIO, sio_test_msg(MSG_ACK, 4, 0)); + KUNIT_EXPECT_EQ(test, sio->tags.completions[4].done, 0); + KUNIT_EXPECT_FALSE(test, sio->tags.acked[4]); + + /* An outstanding tag is still completed. */ + set_bit(3, sio->tags.allocated); + sio_recv_msg(sio, EP_SIO, sio_test_msg(MSG_ACK, 3, 0)); + KUNIT_EXPECT_EQ(test, sio->tags.completions[3].done, 1); + KUNIT_EXPECT_TRUE(test, sio->tags.acked[3]); + + if (!tainted) + KUNIT_EXPECT_FALSE(test, test_taint(TAINT_WARN)); +} + +static struct kunit_case sio_msg_test_cases[] = { + KUNIT_CASE(sio_recv_msg_checks_tag_and_channel_test), + {} +}; + +static struct kunit_suite sio_msg_test_suite = { + .name = "apple-sio-msg", + .test_cases = sio_msg_test_cases, +}; + +kunit_test_suite(sio_msg_test_suite); diff --git a/drivers/dma/apple-sio-t6030-test.dtso b/drivers/dma/apple-sio-t6030-test.dtso index df42f31a2a8d13..5f9cf0cfedbe27 100644 --- a/drivers/dma/apple-sio-t6030-test.dtso +++ b/drivers/dma/apple-sio-t6030-test.dtso @@ -41,6 +41,39 @@ 0x1c 0x5a 0x1d 0x40>; }; + /* + * A low-window SIO (M2) as a loader leaves it for either firmware: the earlier tables, + * and T6030's shim records and device types in a second list, for protocol 10. + */ + low_w: low-w { iommu-addresses = <&low 0x0 0x30000 0x0 0x2d000>; }; + + low: sio-low-window-test-both { + compatible = "apple,t8112-sio", "apple,sio"; + dma-channels = <8>; + memory-region = <&low_w>; + apple,sio-firmware-params = <0x1e 0x30 0x1f 0x300 0xb 0x31 0xc 0x1b80 + 0xf 0x34 0x10 0x1e000 0x30d 0x54 0x30e 0x4000 + 0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xa0 + 0x1c 0x5a 0x1d 0x40>; + apple,sio-firmware-params-v10 = <0x1e 0x30 0x1f 0x300 0xb 0x31 0xc 0x1b80 + 0xf 0x34 0x10 0x1e000 0x30d 0x54 0x30e 0x4000 + 0x1a 0x58 0x1b 0x40 0x22 0x5b 0x23 0xd8 + 0x1c 0x5c 0x1d 0x48>; + }; + + /* The second list with the earlier shim records: not protocol 10's */ + lowbad_w: lowbad-w { iommu-addresses = <&lowbad 0x0 0x30000 0x0 0x2d000>; }; + + lowbad: sio-low-window-test-bad-v10 { + compatible = "apple,t8112-sio", "apple,sio"; + dma-channels = <8>; + memory-region = <&lowbad_w>; + apple,sio-firmware-params = <0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xa0 + 0x1c 0x5a 0x1d 0x40>; + apple,sio-firmware-params-v10 = <0x1a 0x58 0x1b 0x40 0x22 0x5b 0x23 0xa0 + 0x1c 0x5c 0x1d 0x48>; + }; + sio-t6030-test-unmapped { apple,sio-firmware-params = <0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xd8 0x1c 0x5a 0x1d 0x48>; diff --git a/drivers/dma/apple-sio-t6041-test.c b/drivers/dma/apple-sio-t6041-test.c index d5d13f609d7b05..12adc5349637c5 100644 --- a/drivers/dma/apple-sio-t6041-test.c +++ b/drivers/dma/apple-sio-t6041-test.c @@ -265,6 +265,7 @@ static void sio_t6041_match_test(struct kunit *test) KUNIT_EXPECT_PTR_EQ(test, sio_hw_t8140.arrays, &sio_t6041_arrays); KUNIT_EXPECT_TRUE(test, sio_hw_t8140.check_boot_tables == sio_t6041_check_boot_tables); KUNIT_EXPECT_EQ(test, sio_hw_t6041.protocol, 10U); + KUNIT_EXPECT_TRUE(test, sio_hw_t6041.stop_at_commit); KUNIT_EXPECT_TRUE(test, sio_hw_t6041.clear_period_desc); KUNIT_EXPECT_PTR_EQ(test, sio_hw_t6041.arrays, &sio_t6041_arrays); /* Protocol 10 alone is T6030's too, which keeps its own contract. */ diff --git a/drivers/dma/apple-sio-test.c b/drivers/dma/apple-sio-test.c index 1088b967686386..8c77aaa978160d 100644 --- a/drivers/dma/apple-sio-test.c +++ b/drivers/dma/apple-sio-test.c @@ -273,7 +273,7 @@ static void sio_t6030_device_tree_test(struct kunit *test) int ret; KUNIT_ASSERT_NOT_NULL_MSG(test, np, "%s", nodes[i][0]); - ret = sio_t6030_check_node(np); + ret = sio_t6030_check_node(np, "apple,sio-firmware-params"); if (!strcmp(nodes[i][1], "admitted")) KUNIT_EXPECT_EQ_MSG(test, ret, 0, "%s", nodes[i][0]); else @@ -309,6 +309,71 @@ static void sio_t6030_probe_test(struct kunit *test) } } +/* + * A low-window SIO's parameter list follows the protocol its firmware reports: the earlier + * tables for protocol 9, the second list for protocol 10; a protocol-10 firmware without a valid + * second list gets no DMA (the earlier shim records crash it at the first channel configuration). + */ +static void sio_low_window_params_test(struct kunit *test) +{ + static const struct { + const char *path; + u32 protocol; + const char *prop; + bool mismatch; + } cases[] = { + { "/sio-t6030-test/sio-low-window-test-both", 9, "apple,sio-firmware-params", false }, + { "/sio-t6030-test/sio-low-window-test-both", 10, "apple,sio-firmware-params-v10", + false }, + { "/sio-t6030-test/sio-low-window-test-bad-v10", 10, NULL, true }, + { "/sio-t6030-test/sio-low-window-test-bad-v10", 9, "apple,sio-firmware-params", + false }, + /* An older loader: the earlier tables only */ + { "/sio-t6030-test/sio-t6030-test-earlier", 10, NULL, true }, + { "/sio-t6030-test/sio-t6030-test-earlier", 9, "apple,sio-firmware-params", false }, + /* T6030: its protocol-10 tables are the first list */ + { "/sio-t6030-test/sio-t6030-test-v10", 10, "apple,sio-firmware-params", false }, + }; + struct device *dev = kunit_kzalloc(test, sizeof(*dev), GFP_KERNEL); + unsigned int i; + + KUNIT_ASSERT_EQ(test, 0, of_overlay_apply_kunit(test, apple_sio_t6030_test)); + for (i = 0; i < ARRAY_SIZE(cases); i++) { + struct device_node *np __free(device_node) = of_find_node_by_path(cases[i].path); + struct sio_data *sio = kunit_kzalloc(test, sizeof(*sio), GFP_KERNEL); + const char *propname; + + KUNIT_ASSERT_NOT_NULL_MSG(test, np, "%s", cases[i].path); + KUNIT_ASSERT_NOT_NULL(test, dev); + KUNIT_ASSERT_NOT_NULL(test, sio); + dev->of_node = np; + sio->dev = dev; + sio->protocol = cases[i].protocol; + propname = sio_dt_params_name(sio); + if (cases[i].prop) + KUNIT_EXPECT_STREQ_MSG(test, propname, cases[i].prop, "%s v%u", + cases[i].path, cases[i].protocol); + else + KUNIT_EXPECT_NULL(test, propname); + KUNIT_EXPECT_EQ_MSG(test, sio->tables_mismatch, cases[i].mismatch, "%s v%u", + cases[i].path, cases[i].protocol); + } +} + +static void sio_protocol10_cyclic_without_tables_test(struct kunit *test) +{ + struct sio_data *sio = kunit_kzalloc(test, sizeof(*sio), GFP_KERNEL); + struct sio_chan *chan = kunit_kzalloc(test, sizeof(*chan), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, sio); + KUNIT_ASSERT_NOT_NULL(test, chan); + sio->tables_mismatch = true; + chan->host = sio; + + KUNIT_EXPECT_NULL(test, sio_prep_dma_cyclic(&chan->vc.chan, 0, 4096, 1024, + sio_chan_direction(chan->no), 0)); +} + static struct kunit_case sio_t6030_test_cases[] = { KUNIT_CASE(sio_t6030_protocol10_test), KUNIT_CASE(sio_t6030_earlier_loader_test), @@ -318,6 +383,8 @@ static struct kunit_case sio_t6030_test_cases[] = { KUNIT_CASE(sio_t6030_spans_test), KUNIT_CASE(sio_t6030_device_tree_test), KUNIT_CASE(sio_t6030_probe_test), + KUNIT_CASE(sio_low_window_params_test), + KUNIT_CASE(sio_protocol10_cyclic_without_tables_test), {} }; diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index cb75beb54ae994..b6f52869044590 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -189,6 +189,8 @@ struct sio_data { /* The firmware is stopped for a system sleep. */ bool asleep; bool firmware_only; + /* Protocol 10 firmware given the earlier boot tables: no DMA, which would crash it */ + bool tables_mismatch; bool commit_registered; bool commit_used; u32 protocol; @@ -370,16 +372,16 @@ static int sio_t6030_windows(struct device_node *np, struct sio_t6030_window *wi return err == -ENOENT ? n : err; } -/* 0 when the node's boot tables are protocol-10 tables inside its mapped windows */ -static int sio_t6030_check_node(struct device_node *np) +/* 0 when the node's boot tables in propname are protocol-10 tables inside its mapped windows */ +static int sio_t6030_check_node(struct device_node *np, const char *propname) { struct sio_t6030_window windows[SIO_T6030_WINDOWS_MAX]; u32 params[2 * SIO_T6030_PARAMS_MAX]; int nparams, nwindows; - nparams = of_property_count_u32_elems(np, "apple,sio-firmware-params"); + nparams = of_property_count_u32_elems(np, propname); if (nparams <= 0 || nparams > ARRAY_SIZE(params) || - of_property_read_u32_array(np, "apple,sio-firmware-params", params, nparams)) + of_property_read_u32_array(np, propname, params, nparams)) return -EINVAL; nwindows = sio_t6030_windows(np, windows, ARRAY_SIZE(windows)); if (nwindows < 0) @@ -389,7 +391,7 @@ static int sio_t6030_check_node(struct device_node *np) static int sio_t6030_check_boot_tables(struct device *dev) { - if (sio_t6030_check_node(dev->of_node)) { + if (sio_t6030_check_node(dev->of_node, "apple,sio-firmware-params")) { dev_err(dev, "boot tables are not for SIO protocol 10; leaving the SIO stopped\n"); return -ENODEV; } @@ -654,6 +656,7 @@ static const struct sio_hw_data sio_hw_t6030 = { * the 5 of the host's mailbox call timeout is not part of the record. */ static const struct sio_hw_data sio_hw_t6041 = { + .stop_at_commit = true, .protocol = 10, .fifo_threshold = 0x600, .cfg_word4 = 0x800, @@ -697,18 +700,24 @@ static const struct sio_hw_data sio_hw_t6050 = { }; /* - * The T6050 description is in force on the board it has run on. On another T6050 board the - * node is taken as before: by its generic compatible. + * The T6050 description, with its stop at the sleep's commit, is in force on the boards + * that describe the sleep. On another T6050 board the node is taken as before: by its + * generic compatible. */ static bool sio_t6050_board(void) { - return of_machine_is_compatible("apple,j714s"); + return apple_t6050_sleep_described(); } static const struct of_device_id sio_of_match[] = { { .compatible = "apple,t6050-sio", .data = &sio_hw_t6050 }, { .compatible = "apple,t6041-sio", .data = &sio_hw_t6041 }, { .compatible = "apple,t8140-sio", .data = &sio_hw_t8140 }, + /* + * T8132 (M4): the J773g ADT describes the SIO tables as T8140's and + * its DisplayPort audio channels alike ([2, 0, 0x800, 0x800, 0x800, 0]). + */ + { .compatible = "apple,t8132-sio", .data = &sio_hw_t8140 }, { .compatible = "apple,t6030-sio", .data = &sio_hw_t6030 }, { .compatible = "apple,sio", .data = &sio_hw_generic }, { } @@ -869,7 +878,8 @@ static struct dma_async_tx_descriptor *sio_prep_dma_cyclic( struct sio_chan *siochan = to_sio_chan(chan); struct sio_tx *siotx; - if (direction != sio_chan_direction(siochan->no)) + if (siochan->host->tables_mismatch || + direction != sio_chan_direction(siochan->no)) return NULL; siotx = sio_alloc_tx(siochan, buf_addr, buf_len, period_len, GFP_NOWAIT); @@ -1534,6 +1544,16 @@ static void sio_process_report(struct sio_chan *siochan) spin_unlock_irqrestore(&siochan->vc.lock, flags); } +/* + * A tag the firmware names in an ACK or NACK must be one the host handed out + * and has not freed: tag 0 is never allocated, and the field is wider than + * the table. + */ +static bool sio_tag_outstanding(struct sio_data *sio, u8 tag) +{ + return tag && tag < SIO_NTAGS && test_bit(tag, sio->tags.allocated); +} + static void sio_recv_msg(void *cookie, u8 ep, u64 msg) { struct sio_data *sio = cookie; @@ -1558,13 +1578,21 @@ static void sio_recv_msg(void *cookie, u8 ep, u64 msg) fallthrough; case MSG_ACK: case MSG_NACK: - if (WARN_ON(tag >= SIO_NTAGS)) + if (!sio_tag_outstanding(sio, tag)) { + dev_warn_ratelimited(sio->dev, + "ack for tag %u, which is not outstanding\n", + tag); break; + } if (tags->atomic[tag]) { sio_ack_callback callback = tags->ack_callback[tag]; - if (callback && !WARN_ON(sioep >= sio->nchannels)) + if (callback && sioep >= sio->nchannels) + dev_warn_ratelimited(sio->dev, + "ack for channel %u of %d\n", + sioep, sio->nchannels); + else if (callback) callback(&sio->channels[sioep], tags->cookie[tag], type == MSG_ACK); if (type == MSG_NACK) @@ -1577,8 +1605,12 @@ static void sio_recv_msg(void *cookie, u8 ep, u64 msg) break; case MSG_REPORT: - if (WARN_ON(sioep >= sio->nchannels)) + if (sioep >= sio->nchannels) { + dev_warn_ratelimited(sio->dev, + "report for channel %u of %d\n", + sioep, sio->nchannels); break; + } sio_process_report(&sio->channels[sioep]); break; @@ -1678,6 +1710,9 @@ static int sio_device_config(struct dma_chan *chan, struct sio_shmem_chan_config cfg; int ret; + if (sio->tables_mismatch) + return -ENODEV; + if (config->peripheral_config) { if (config->peripheral_size != sizeof(struct apple_sio_idle)) return -EINVAL; @@ -1926,15 +1961,43 @@ static int sio_alloc_shmem(struct sio_data *sio) return err; } +/* + * A low-window SIO (M1, M2) takes the earlier boot tables when its firmware reports protocol 9 + * and T6030's when it reports protocol 10 (the M2's 27.2 firmware, with an ADT the same as its + * 13.5 one's), so the boot loader passes T6030's tables as a second list, used for protocol 10. + * A protocol-10 firmware given only the earlier tables (an older boot loader) crashes at its + * first channel configuration; keep the firmware running for sleep, but offer it no DMA. + */ +static const char *sio_dt_params_name(struct sio_data *sio) +{ + struct device_node *np = sio->dev->of_node; + + if (sio->protocol != 10) + return "apple,sio-firmware-params"; + if (!sio_t6030_check_node(np, "apple,sio-firmware-params-v10")) + return "apple,sio-firmware-params-v10"; + if (!sio_t6030_check_node(np, "apple,sio-firmware-params")) + return "apple,sio-firmware-params"; + + sio->tables_mismatch = true; + return NULL; +} + static int sio_send_dt_params(struct sio_data *sio) { struct device_node *np = sio->dev->of_node; - const char *propname = "apple,sio-firmware-params"; + const char *propname; int nparams, err, i; if (sio->hw->send_dt_params) return sio->hw->send_dt_params(sio); + propname = sio_dt_params_name(sio); + if (!propname) { + dev_err(sio->dev, "boot tables are not for SIO protocol 10; no DMA\n"); + return 0; + } + nparams = of_property_count_u32_elems(np, propname); if (nparams < 0) { err = nparams; @@ -2051,7 +2114,7 @@ static int sio_probe(struct platform_device *pdev) dev_err(&pdev->dev, "couldn't initialize rtkit\n"); goto rpm_put; } - for (i = 1; i < SIO_NTAGS; i++) + for (i = 0; i < SIO_NTAGS; i++) init_completion(&sio->tags.completions[i]); dma = &sio->dma; @@ -2116,6 +2179,10 @@ static int sio_probe(struct platform_device *pdev) err = sio_send_dt_params(sio); if (err < 0) return dev_err_probe(&pdev->dev, err, "failed to send boot-up parameters\n"); + if (sio->tables_mismatch) { + sio->firmware_only = true; + goto rpm_put; + } err = sio_alloc_shmem(sio); if (err < 0) @@ -2354,4 +2421,5 @@ MODULE_LICENSE("Dual MIT/GPL"); #if IS_ENABLED(CONFIG_APPLE_SIO_KUNIT_TEST) #include "apple-sio-probe-test.c" #include "apple-sio-boot-test.c" +#include "apple-sio-msg-test.c" #endif diff --git a/drivers/edac/Kconfig b/drivers/edac/Kconfig index e0dfd136599bb9..633d8c3859ddb4 100644 --- a/drivers/edac/Kconfig +++ b/drivers/edac/Kconfig @@ -582,6 +582,19 @@ config EDAC_APPLE_SOC acknowledged and counted in the EDAC core; a source that stays asserted without status is masked. +config EDAC_APPLE_SOC_KUNIT_TEST + tristate "KUnit tests for Apple SoC error reporting" if !KUNIT_ALL_TESTS + depends on EDAC_APPLE_SOC && KUNIT + default KUNIT_ALL_TESTS + help + Build KUnit tests for the Apple SoC error reporting driver: the + interrupt index to error source tables, the T6041 and T8140 NI + status decode and acknowledge against a fake register block, the + uncorrectable error counts and the mask and backoff of lines that + stay asserted. + + If unsure, say N. + config EDAC_VERSALNET tristate "AMD VersalNET DDR Controller" depends on CDX_CONTROLLER && ARCH_ZYNQMP diff --git a/drivers/edac/Makefile b/drivers/edac/Makefile index 2cd51f0046b0e1..553f5fd3caf4cb 100644 --- a/drivers/edac/Makefile +++ b/drivers/edac/Makefile @@ -92,3 +92,4 @@ obj-$(CONFIG_EDAC_LOONGSON) += loongson_edac.o obj-$(CONFIG_EDAC_VERSALNET) += versalnet_edac.o obj-$(CONFIG_EDAC_CORTEX_A72) += a72_edac.o obj-$(CONFIG_EDAC_APPLE_SOC) += apple_soc_edac.o +obj-$(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) += apple_soc_edac-test.o diff --git a/drivers/edac/apple_soc_edac-internal.h b/drivers/edac/apple_soc_edac-internal.h new file mode 100644 index 00000000000000..489cae0394f6f3 --- /dev/null +++ b/drivers/edac/apple_soc_edac-internal.h @@ -0,0 +1,89 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _APPLE_SOC_EDAC_INTERNAL_H +#define _APPLE_SOC_EDAC_INTERNAL_H + +#include +#include +#include + +#define APPLE_SOC_EDAC_NAME "apple_soc_edac" + +/* + * The sources' status registers have no established acknowledge contract, + * so a line is masked when it fires and unmasked again after a backoff. + * A line still asserted after APPLE_SOC_EDAC_MAX_RETRIES backoffs stays + * masked; its count keeps the record. + */ +#define APPLE_SOC_EDAC_BACKOFF_MS 1000 +#define APPLE_SOC_EDAC_BACKOFF_MAX_MS 60000 +#define APPLE_SOC_EDAC_MAX_RETRIES 8 + +#define T6041_NI_REGS 25 +#define T6041_NI_STATUS 0x416c + +struct apple_soc_edac_range { + u8 first; + u8 count; + const char *name; +}; + +/* + * A fabric NI whose error status sits in its aperture: a block of status words, + * one per error type, whose set bits name the port. They're acknowledged by + * writing the set bits back. + */ +struct apple_soc_edac_ni { + u8 index; /* interrupt index */ + u8 reg; /* reg index of the NI's aperture */ + u16 status; /* offset of the first status word */ + u32 words; /* bit n: a status word at status + 4 * n */ +}; + +struct apple_soc_edac_hw { + const struct apple_soc_edac_range *ranges; + size_t nranges; + const struct apple_soc_edac_ni *ni; + size_t nni; + unsigned int num_irqs; + unsigned int num_status_regs; + bool event_log; +}; + +struct apple_soc_edac; + +struct apple_soc_edac_irq { + struct apple_soc_edac *edac; + const char *source; + unsigned int index; + int irq; + const struct apple_soc_edac_ni *ni; + void __iomem *ni_base; + unsigned int retries; + unsigned int backoff_ms; + unsigned long armed_jiffies; + struct delayed_work rearm; +}; + +struct apple_soc_edac { + struct device *dev; + struct edac_device_ctl_info *dci; + const struct apple_soc_edac_hw *hw; + struct apple_soc_edac_irq *irqs; + void __iomem **status_regs; +}; + +#if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) +const char *apple_soc_edac_source(const struct apple_soc_edac_hw *hw, + unsigned int index); +u32 apple_soc_edac_read(void __iomem *reg); +void apple_soc_edac_write(void __iomem *reg, u32 val); +bool apple_soc_edac_t6041_status(struct apple_soc_edac_irq *irq_data, + bool *error, bool *cleared); +bool apple_soc_edac_ni_status(struct apple_soc_edac_irq *irq_data, + bool *cleared); +void apple_soc_edac_rearm(struct work_struct *work); +irqreturn_t apple_soc_edac_irq_thread(int irq, void *data); +extern const struct of_device_id apple_soc_edac_of_match[]; +#endif + +#endif diff --git a/drivers/edac/apple_soc_edac-test.c b/drivers/edac/apple_soc_edac-test.c new file mode 100644 index 00000000000000..165325873c1a08 --- /dev/null +++ b/drivers/edac/apple_soc_edac-test.c @@ -0,0 +1,830 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the Apple SoC platform error reporting driver + * + * Copyright The Aurora Silicon Contributors + * + * Included at the end of apple_soc_edac.c. The status registers are a fake + * write-one-to-clear register block behind the driver's static-stubbed + * accessors, so no MMIO is touched and every access is bounds checked. + */ + +#include +#include +#include +#include +#include + +#include "edac_module.h" +#include "apple_soc_edac-internal.h" + +#define EDAC_TEST_WORDS 64 +/* Not a valid interrupt: the IRQ core ignores masks and unmasks of it. */ +#define EDAC_TEST_IRQ INT_MAX + +struct edac_test_fake { + u32 regs[EDAC_TEST_WORDS]; + /* Bits that stay set after an acknowledge. */ + u32 sticky[EDAC_TEST_WORDS]; + unsigned int acks[EDAC_TEST_WORDS]; + unsigned int reads; + unsigned int writes; + unsigned int stray; +}; + +struct edac_test_ctx { + struct device *dev; + struct edac_test_fake fake; + struct apple_soc_edac edac; + struct apple_soc_edac_irq irq; + void __iomem *status_regs[T6041_NI_REGS]; +}; + +static int edac_test_word(struct edac_test_fake *fake, void __iomem *reg) +{ + uintptr_t off = (uintptr_t)(void __force *)reg - (uintptr_t)fake->regs; + + if (off % 4 || off >= sizeof(fake->regs)) { + fake->stray++; + return -1; + } + + return off / 4; +} + +static u32 edac_test_read(void __iomem *reg) +{ + struct kunit *test = kunit_get_current_test(); + struct edac_test_ctx *ctx = test->priv; + int word = edac_test_word(&ctx->fake, reg); + + if (word < 0) + return 0; + ctx->fake.reads++; + return ctx->fake.regs[word]; +} + +static void edac_test_write(void __iomem *reg, u32 val) +{ + struct kunit *test = kunit_get_current_test(); + struct edac_test_ctx *ctx = test->priv; + int word = edac_test_word(&ctx->fake, reg); + + if (word < 0) + return; + ctx->fake.writes++; + ctx->fake.acks[word]++; + ctx->fake.regs[word] = (ctx->fake.regs[word] & ~val) | + ctx->fake.sticky[word]; +} + +static void edac_test_free_dci(void *data) +{ + edac_device_free_ctl_info(data); +} + +static void edac_test_cancel(void *data) +{ + struct apple_soc_edac_irq *irq_data = data; + + cancel_delayed_work_sync(&irq_data->rearm); +} + +/* + * Set up one error line of @hw the way probe does, with the T6041 status + * words and the NI status block of the line in the fake register block. + */ +static struct edac_test_ctx *edac_test_line(struct kunit *test, + const struct apple_soc_edac_hw *hw, + unsigned int index) +{ + struct edac_test_ctx *ctx = test->priv; + struct apple_soc_edac_irq *irq_data = &ctx->irq; + struct device *dev = ctx->dev; + unsigned int i; + + /* A previous line of the same case: its EDAC device name is reused. */ + if (ctx->edac.dci) { + kunit_release_action(test, edac_test_cancel, irq_data); + kunit_release_action(test, edac_test_free_dci, ctx->edac.dci); + } + memset(&ctx->fake, 0, sizeof(ctx->fake)); + memset(&ctx->edac, 0, sizeof(ctx->edac)); + memset(irq_data, 0, sizeof(*irq_data)); + ctx->edac.dev = dev; + ctx->edac.hw = hw; + ctx->edac.irqs = irq_data; + ctx->edac.dci = edac_device_alloc_ctl_info(0, "apple_soc_edac_kunit", + 1, "platform", 1, 0, 0); + KUNIT_ASSERT_NOT_NULL(test, ctx->edac.dci); + KUNIT_ASSERT_EQ(test, 0, kunit_add_action_or_reset(test, + edac_test_free_dci, + ctx->edac.dci)); + ctx->edac.dci->dev = dev; + ctx->edac.dci->ctl_name = APPLE_SOC_EDAC_NAME; + ctx->edac.dci->dev_name = dev_name(dev); + ctx->edac.dci->log_ue = 0; + ctx->edac.dci->panic_on_ue = 0; + + /* T6041 line 45 + n reads its status word at fake word n. */ + for (i = 0; i < T6041_NI_REGS; i++) + ctx->status_regs[i] = (void __iomem __force *) + ((uintptr_t)&ctx->fake.regs[i] - T6041_NI_STATUS); + if (hw->num_status_regs) + ctx->edac.status_regs = ctx->status_regs; + + irq_data->edac = &ctx->edac; + irq_data->source = apple_soc_edac_source(hw, index); + KUNIT_ASSERT_NOT_NULL(test, irq_data->source); + irq_data->index = index; + irq_data->irq = EDAC_TEST_IRQ; + irq_data->backoff_ms = APPLE_SOC_EDAC_BACKOFF_MS; + irq_data->armed_jiffies = jiffies; + INIT_DELAYED_WORK(&irq_data->rearm, apple_soc_edac_rearm); + KUNIT_ASSERT_EQ(test, 0, kunit_add_action_or_reset(test, + edac_test_cancel, + irq_data)); + + /* An NI's status word n is fake word n. */ + for (i = 0; i < hw->nni; i++) { + if (hw->ni[i].index != index) + continue; + irq_data->ni = &hw->ni[i]; + irq_data->ni_base = (void __iomem __force *) + ((uintptr_t)ctx->fake.regs - hw->ni[i].status); + } + + return ctx; +} + +static u32 edac_test_ue(struct edac_test_ctx *ctx) +{ + return ctx->edac.dci->counters.ue_count; +} + +/* Run the IRQ thread; returns the rearm delay in jiffies, 0 if none. */ +static unsigned long edac_test_fire(struct kunit *test, + struct edac_test_ctx *ctx, + unsigned int expect_backoff_ms) +{ + struct apple_soc_edac_irq *irq_data = &ctx->irq; + unsigned long before, after, expires, delay; + + before = jiffies; + KUNIT_EXPECT_EQ(test, IRQ_HANDLED, + apple_soc_edac_irq_thread(irq_data->irq, irq_data)); + KUNIT_EXPECT_EQ(test, ctx->fake.stray, 0U); + after = jiffies; + + if (!delayed_work_pending(&irq_data->rearm)) { + KUNIT_EXPECT_EQ(test, 0U, expect_backoff_ms); + return 0; + } + + expires = irq_data->rearm.timer.expires; + cancel_delayed_work_sync(&irq_data->rearm); + delay = msecs_to_jiffies(expect_backoff_ms); + KUNIT_EXPECT_NE(test, 0U, expect_backoff_ms); + KUNIT_EXPECT_TRUE(test, time_after_eq(expires, before + delay)); + KUNIT_EXPECT_TRUE(test, time_before_eq(expires, after + delay)); + + return expires - before; +} + +static int edac_test_init(struct kunit *test) +{ + struct edac_test_ctx *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + if (!ctx) + return -ENOMEM; + test->priv = ctx; + ctx->dev = kunit_device_register(test, "apple-soc-edac-kunit"); + if (IS_ERR(ctx->dev)) + return PTR_ERR(ctx->dev); + kunit_activate_static_stub(test, apple_soc_edac_read, edac_test_read); + kunit_activate_static_stub(test, apple_soc_edac_write, edac_test_write); + + return 0; +} + +static const char *const edac_test_error_compatibles[] = { + "apple,t6000-error-handler", + "apple,t6041-error-handler", "apple,t8112-error-handler", + "apple,t8140-error-handler", +}; + +static const char *const edac_test_event_compatibles[] = { + "apple,t6000-event-log", + "apple,t6041-event-log", "apple,t8112-event-log", + "apple,t8140-event-log", +}; + +static const struct apple_soc_edac_hw *edac_test_hw(struct kunit *test, + const char *compatible) +{ + const struct of_device_id *id; + + for (id = apple_soc_edac_of_match; id->compatible[0]; id++) + if (!strcmp(id->compatible, compatible)) { + KUNIT_ASSERT_NOT_NULL(test, id->data); + return id->data; + } + + KUNIT_FAIL_AND_ABORT(test, "no match data for %s", compatible); + return NULL; +} + +static void edac_test_expect_source(struct kunit *test, + const struct apple_soc_edac_hw *hw, + unsigned int index, const char *expect) +{ + const char *name = apple_soc_edac_source(hw, index); + + if (!expect) { + KUNIT_EXPECT_NULL_MSG(test, name, "index %u", index); + return; + } + KUNIT_EXPECT_NOT_NULL_MSG(test, name, "index %u", index); + if (name) + KUNIT_EXPECT_STREQ_MSG(test, name, expect, "index %u", index); +} + +/* Every T6041 line maps to its range name, gaps and the tail to none. */ +static void edac_test_source_t6041(struct kunit *test) +{ + static const struct { + unsigned int index; + const char *name; + } cases[] = { + { 0, "sep" }, { 8, "sep" }, { 9, "pmgr" }, { 10, NULL }, + { 25, NULL }, { 26, "sram" }, { 28, "sram" }, { 29, NULL }, + { 44, NULL }, { 45, "ni0" }, { 47, "ni0" }, { 48, "ni1" }, + { 51, "ni1" }, { 52, "ni2" }, { 56, "ni3" }, { 63, "ni3" }, + { 64, "ni4" }, { 66, "ni5" }, { 68, "ni6" }, { 69, "ni6" }, + { 70, NULL }, { 88, NULL }, { 89, NULL }, { 255, NULL }, + { UINT_MAX, NULL }, + }; + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cases); i++) + edac_test_expect_source(test, hw, cases[i].index, cases[i].name); +} + +/* Range edges of every SoC: first and last line in, neighbours per table. */ +static void edac_test_source_edges(struct kunit *test) +{ + unsigned int h, r, i, claimed; + + for (h = 0; h < ARRAY_SIZE(edac_test_error_compatibles); h++) { + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, edac_test_error_compatibles[h]); + + claimed = 0; + for (i = 0; i < hw->num_irqs; i++) + claimed += !!apple_soc_edac_source(hw, i); + + for (r = 0; r < hw->nranges; r++) { + const struct apple_soc_edac_range *range = &hw->ranges[r]; + unsigned int last = range->first + range->count - 1; + + edac_test_expect_source(test, hw, range->first, + range->name); + edac_test_expect_source(test, hw, last, range->name); + claimed -= range->count; + } + /* Lines outside every range are left unclaimed. */ + KUNIT_EXPECT_EQ_MSG(test, claimed, 0U, "hw %u", h); + KUNIT_EXPECT_NULL(test, apple_soc_edac_source(hw, hw->num_irqs)); + } +} + +/* The ranges fit the interrupt count, ascend and do not overlap. */ +static void edac_test_tables(struct kunit *test) +{ + unsigned int h, r, end; + + for (h = 0; h < ARRAY_SIZE(edac_test_error_compatibles); h++) { + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, edac_test_error_compatibles[h]); + + KUNIT_EXPECT_FALSE(test, hw->event_log); + KUNIT_EXPECT_GT(test, hw->nranges, (size_t)0); + end = 0; + for (r = 0; r < hw->nranges; r++) { + const struct apple_soc_edac_range *range = &hw->ranges[r]; + + KUNIT_EXPECT_NOT_NULL(test, range->name); + KUNIT_EXPECT_GT(test, range->count, 0); + KUNIT_EXPECT_GE_MSG(test, (unsigned int)range->first, end, + "hw %u range %u", h, r); + end = range->first + range->count; + KUNIT_EXPECT_LE_MSG(test, end, hw->num_irqs, + "hw %u range %u", h, r); + } + } + + for (h = 0; h < ARRAY_SIZE(edac_test_event_compatibles); h++) { + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, edac_test_event_compatibles[h]); + + KUNIT_EXPECT_TRUE(test, hw->event_log); + KUNIT_EXPECT_EQ(test, hw->nranges, (size_t)0); + KUNIT_EXPECT_EQ(test, hw->nni, (size_t)0); + } +} + +/* T6041: exactly the NI lines 45-69 own one status aperture each. */ +static void edac_test_t6041_status_lines(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + unsigned int i; + + KUNIT_EXPECT_EQ(test, hw->num_status_regs, T6041_NI_REGS); + for (i = 45; i < 45 + T6041_NI_REGS; i++) { + const char *name = apple_soc_edac_source(hw, i); + + KUNIT_ASSERT_NOT_NULL(test, name); + KUNIT_EXPECT_EQ_MSG(test, strncmp(name, "ni", 2), 0, "index %u", i); + } + KUNIT_EXPECT_NULL(test, apple_soc_edac_source(hw, 44)); + KUNIT_EXPECT_NULL(test, apple_soc_edac_source(hw, 45 + T6041_NI_REGS)); +} + +/* T8140 NI blocks sit on claimed NI lines with a valid aperture and words. */ +static void edac_test_t8140_ni_table(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); + unsigned int i, j; + + KUNIT_EXPECT_EQ(test, hw->nni, (size_t)6); + for (i = 0; i < hw->nni; i++) { + const struct apple_soc_edac_ni *ni = &hw->ni[i]; + const char *name = apple_soc_edac_source(hw, ni->index); + + KUNIT_ASSERT_NOT_NULL(test, name); + KUNIT_EXPECT_EQ(test, strncmp(name, "ni", 2), 0); + KUNIT_EXPECT_NE(test, ni->words, 0U); + KUNIT_EXPECT_EQ(test, ni->status % 4, 0); + /* Interrupt n is described by the n-th interrupt-less reg. */ + KUNIT_EXPECT_GE(test, ni->reg, 9); + for (j = 0; j < i; j++) { + KUNIT_EXPECT_NE(test, ni->index, hw->ni[j].index); + KUNIT_EXPECT_NE(test, ni->reg, hw->ni[j].reg); + } + } + /* The NSI and PIO lines have no status block. */ + for (i = 24; i < 26; i++) + for (j = 0; j < hw->nni; j++) + KUNIT_EXPECT_NE(test, (unsigned int)hw->ni[j].index, i); +} + +static void edac_test_event_log_source(struct kunit *test) +{ + unsigned int h; + + for (h = 0; h < ARRAY_SIZE(edac_test_event_compatibles); h++) { + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, edac_test_event_compatibles[h]); + + edac_test_expect_source(test, hw, 0, "event-log"); + edac_test_expect_source(test, hw, hw->num_irqs - 1, "event-log"); + edac_test_expect_source(test, hw, hw->num_irqs, "event-log"); + } +} + +static void edac_test_of_match(struct kunit *test) +{ + const struct of_device_id *id; + unsigned int n = 0; + + for (id = apple_soc_edac_of_match; id->compatible[0]; id++) { + const struct apple_soc_edac_hw *hw = id->data; + + KUNIT_ASSERT_NOT_NULL(test, hw); + KUNIT_EXPECT_GT(test, hw->num_irqs, 0U); + KUNIT_EXPECT_EQ_MSG(test, hw->event_log, + !!strstr(id->compatible, "-event-log"), + "%s", id->compatible); + n++; + } + KUNIT_EXPECT_EQ(test, n, 8U); +} + +static bool edac_test_t6041(struct edac_test_ctx *ctx, bool *error, + bool *cleared) +{ + return apple_soc_edac_t6041_status(&ctx->irq, error, cleared); +} + +/* A T6041 NI word that reads zero is left alone. */ +static void edac_test_t6041_status_zero(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 50); + bool error = true, cleared = false; + + KUNIT_EXPECT_FALSE(test, edac_test_t6041(ctx, &error, &cleared)); + KUNIT_EXPECT_FALSE(test, error); + KUNIT_EXPECT_TRUE(test, cleared); + KUNIT_EXPECT_EQ(test, ctx->fake.reads, 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.writes, 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.stray, 0U); +} + +/* Each bit is acknowledged; only bits 0-2 and 4-7 are platform errors. */ +static void edac_test_t6041_status_mask(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 45); + unsigned int bit; + bool error, cleared; + + for (bit = 0; bit < 32; bit++) { + ctx->fake.regs[0] = BIT(bit); + KUNIT_EXPECT_TRUE(test, edac_test_t6041(ctx, &error, &cleared)); + KUNIT_EXPECT_EQ_MSG(test, error, bit < 8 && bit != 3, "bit %u", bit); + KUNIT_EXPECT_TRUE(test, cleared); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[0], 0U); + } + KUNIT_EXPECT_EQ(test, ctx->fake.acks[0], 32U); + + /* Bit 3 among higher bits is still no error. */ + ctx->fake.regs[0] = 0xffffff08; + apple_soc_edac_t6041_status(&ctx->irq, &error, &cleared); + KUNIT_EXPECT_FALSE(test, error); + ctx->fake.regs[0] = 0xffffffff; + apple_soc_edac_t6041_status(&ctx->irq, &error, &cleared); + KUNIT_EXPECT_TRUE(test, error); + KUNIT_EXPECT_EQ(test, ctx->fake.stray, 0U); +} + +/* A word that reads back set after the acknowledge is reported. */ +static void edac_test_t6041_status_sticky(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 60); + bool error, cleared; + + ctx->fake.regs[15] = 0x11; + ctx->fake.sticky[15] = 0x10; + KUNIT_EXPECT_TRUE(test, edac_test_t6041(ctx, &error, &cleared)); + KUNIT_EXPECT_TRUE(test, error); + KUNIT_EXPECT_FALSE(test, cleared); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[15], 0x10U); + KUNIT_EXPECT_EQ(test, ctx->fake.acks[15], 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.reads, 2U); +} + +/* Line 45 + n uses aperture n, and lines outside 45-69 touch none. */ +static void edac_test_t6041_status_index(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 45); + static const unsigned int outside[] = { 0, 9, 26, 44, 70, 88 }; + bool error, cleared; + unsigned int i; + + for (i = 0; i < T6041_NI_REGS; i++) + ctx->fake.regs[i] = 0x1; + + for (i = 0; i < T6041_NI_REGS; i++) { + ctx->irq.index = 45 + i; + KUNIT_EXPECT_TRUE(test, edac_test_t6041(ctx, &error, &cleared)); + KUNIT_EXPECT_EQ_MSG(test, ctx->fake.acks[i], 1U, "line %u", 45 + i); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[i], 0U); + } + + for (i = 0; i < T6041_NI_REGS; i++) + ctx->fake.regs[i] = 0x1; + ctx->fake.reads = 0; + for (i = 0; i < ARRAY_SIZE(outside); i++) { + ctx->irq.index = outside[i]; + KUNIT_EXPECT_FALSE(test, edac_test_t6041(ctx, &error, &cleared)); + KUNIT_EXPECT_FALSE(test, error); + KUNIT_EXPECT_TRUE(test, cleared); + } + KUNIT_EXPECT_EQ(test, ctx->fake.reads, 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.stray, 0U); +} + +/* Only the words in the NI's mask are read, and set ones are acknowledged. */ +static void edac_test_ni_status_words(struct kunit *test) +{ + /* SoC NI 0: 0x1ffd7ff */ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 18); + unsigned int bit; + bool cleared = false; + + KUNIT_ASSERT_NOT_NULL(test, ctx->irq.ni); + for (bit = 0; bit < 32; bit++) + ctx->fake.regs[bit] = 0xa5a5a5a5; + + KUNIT_EXPECT_TRUE(test, apple_soc_edac_ni_status(&ctx->irq, &cleared)); + KUNIT_EXPECT_TRUE(test, cleared); + for (bit = 0; bit < 32; bit++) { + bool in = ctx->irq.ni->words & BIT(bit); + + KUNIT_EXPECT_EQ_MSG(test, ctx->fake.acks[bit], in ? 1U : 0U, + "word %u", bit); + KUNIT_EXPECT_EQ_MSG(test, ctx->fake.regs[bit], + in ? 0U : 0xa5a5a5a5U, "word %u", bit); + } + KUNIT_EXPECT_EQ(test, ctx->fake.reads, + 2 * hweight32(ctx->irq.ni->words)); + KUNIT_EXPECT_EQ(test, ctx->fake.stray, 0U); +} + +/* No word set: nothing found and nothing written. */ +static void edac_test_ni_status_none(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 22); + bool cleared = false; + + KUNIT_ASSERT_NOT_NULL(test, ctx->irq.ni); + KUNIT_EXPECT_FALSE(test, apple_soc_edac_ni_status(&ctx->irq, &cleared)); + KUNIT_EXPECT_TRUE(test, cleared); + KUNIT_EXPECT_EQ(test, ctx->fake.writes, 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.reads, + hweight32(ctx->irq.ni->words)); +} + +/* One word of several staying set makes the NI not cleared. */ +static void edac_test_ni_status_sticky(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 23); + bool cleared = true; + + /* GFX NI: 0x3ff7ff, so words 0 and 21 are both in the mask. */ + ctx->fake.regs[0] = 0x2; + ctx->fake.regs[21] = 0x80000001; + ctx->fake.sticky[21] = 0x80000000; + KUNIT_EXPECT_TRUE(test, apple_soc_edac_ni_status(&ctx->irq, &cleared)); + KUNIT_EXPECT_FALSE(test, cleared); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[0], 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[21], 0x80000000U); + KUNIT_EXPECT_EQ(test, ctx->fake.acks[0], 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.acks[21], 1U); +} + +/* Word 31 sits at status + 0x7c; word 11 of an NI without it is never read. */ +static void edac_test_ni_status_top_word(struct kunit *test) +{ + static const struct apple_soc_edac_ni ni = { 18, 9, 0x100, BIT(31) }; + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 18); + bool cleared; + + ctx->irq.ni = ∋ + ctx->irq.ni_base = (void __iomem __force *) + ((uintptr_t)ctx->fake.regs - ni.status); + ctx->fake.regs[31] = 0xffffffff; + ctx->fake.regs[30] = 0x1; + KUNIT_EXPECT_TRUE(test, apple_soc_edac_ni_status(&ctx->irq, &cleared)); + KUNIT_EXPECT_TRUE(test, cleared); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[31], 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[30], 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.reads, 2U); + + /* Word 11 is outside SoC NI 0's mask. */ + ctx->irq.ni = &ctx->edac.hw->ni[0]; + ctx->irq.ni_base = (void __iomem __force *) + ((uintptr_t)ctx->fake.regs - ctx->edac.hw->ni[0].status); + ctx->fake.regs[30] = 0; + ctx->fake.regs[11] = 0x1; + KUNIT_EXPECT_FALSE(test, apple_soc_edac_ni_status(&ctx->irq, &cleared)); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[11], 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.stray, 0U); +} + +/* T6041 NI error acknowledged: one UE, the line stays unmasked. */ +static void edac_test_irq_t6041_error(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 47); + + ctx->fake.regs[2] = 0x4; + KUNIT_EXPECT_EQ(test, edac_test_fire(test, ctx, 0), 0UL); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 1U); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[2], 0U); +} + +/* Bit 3 alone is acknowledged without an error count. */ +static void edac_test_irq_t6041_bit3(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 69); + + ctx->fake.regs[24] = BIT(3); + KUNIT_EXPECT_EQ(test, edac_test_fire(test, ctx, 0), 0UL); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.acks[24], 1U); +} + +/* An NI line with no status set is masked and backed off, not counted. */ +static void edac_test_irq_t6041_empty(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 56); + + edac_test_fire(test, ctx, APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 0U); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.writes, 0U); +} + +/* An acknowledge that does not take counts once and backs off. */ +static void edac_test_irq_t6041_sticky(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 64); + + ctx->fake.regs[19] = 0x1; + ctx->fake.sticky[19] = 0x1; + edac_test_fire(test, ctx, APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 1U); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 1U); +} + +/* Lines without a status contract count a UE and back off. */ +static void edac_test_irq_no_status(struct kunit *test) +{ + static const struct { + const char *compatible; + unsigned int index; + } lines[] = { + { "apple,t6041-error-handler", 3 }, /* sep */ + { "apple,t6041-error-handler", 27 }, /* sram */ + { "apple,t6000-error-handler", 33 }, /* ni0, no status on T6000 */ + { "apple,t8112-error-handler", 2 }, /* sep */ + { "apple,t8140-error-handler", 24 }, /* nsi */ + { "apple,t6000-event-log", 0 }, + { "apple,t8140-event-log", 8 }, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(lines); i++) { + const struct apple_soc_edac_hw *hw; + struct edac_test_ctx *ctx; + + hw = edac_test_hw(test, lines[i].compatible); + ctx = edac_test_line(test, hw, lines[i].index); + KUNIT_EXPECT_NULL(test, ctx->irq.ni); + edac_test_fire(test, ctx, APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ_MSG(test, edac_test_ue(ctx), 1U, "line %u", i); + KUNIT_EXPECT_EQ(test, ctx->fake.reads, 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.writes, 0U); + } +} + +/* T8140 NI: acknowledged status is one UE without a mask. */ +static void edac_test_irq_ni_error(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 21); + + ctx->fake.regs[24] = 0x100; + KUNIT_EXPECT_EQ(test, edac_test_fire(test, ctx, 0), 0UL); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.acks[24], 1U); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 0U); +} + +/* T8140 NI asserted with no status: masked, no UE. Sticky: UE once + mask. */ +static void edac_test_irq_ni_empty_sticky(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 19); + + edac_test_fire(test, ctx, APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 0U); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 1U); + + ctx->fake.regs[3] = 0x8; + ctx->fake.sticky[3] = 0x8; + edac_test_fire(test, ctx, 2 * APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 1U); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 2U); +} + +/* The backoff doubles to its cap; after the retry limit the line stays off. */ +static void edac_test_irq_backoff_limit(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6000-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 0); + unsigned int i, expect = APPLE_SOC_EDAC_BACKOFF_MS; + + for (i = 0; i < APPLE_SOC_EDAC_MAX_RETRIES; i++) { + /* Fires straight after its unmask: still asserted. */ + ctx->irq.armed_jiffies = jiffies; + edac_test_fire(test, ctx, expect); + expect = min(expect * 2, APPLE_SOC_EDAC_BACKOFF_MAX_MS); + KUNIT_EXPECT_EQ(test, ctx->irq.backoff_ms, expect); + } + KUNIT_EXPECT_EQ(test, ctx->irq.backoff_ms, APPLE_SOC_EDAC_BACKOFF_MAX_MS); + + ctx->irq.armed_jiffies = jiffies; + edac_test_fire(test, ctx, 0); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, APPLE_SOC_EDAC_MAX_RETRIES + 1); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), APPLE_SOC_EDAC_MAX_RETRIES + 1); +} + +/* A line that stayed quiet for a minute after its unmask starts over. */ +static void edac_test_irq_backoff_reset(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8112-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 1); + + ctx->irq.retries = APPLE_SOC_EDAC_MAX_RETRIES + 1; + ctx->irq.backoff_ms = APPLE_SOC_EDAC_BACKOFF_MAX_MS; + ctx->irq.armed_jiffies = jiffies - + msecs_to_jiffies(APPLE_SOC_EDAC_BACKOFF_MAX_MS) - 1; + edac_test_fire(test, ctx, APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 1U); + KUNIT_EXPECT_EQ(test, ctx->irq.backoff_ms, 2 * APPLE_SOC_EDAC_BACKOFF_MS); + + /* Unmasked under a minute ago: still counting. */ + ctx->irq.armed_jiffies = jiffies - + msecs_to_jiffies(APPLE_SOC_EDAC_BACKOFF_MAX_MS) + HZ; + edac_test_fire(test, ctx, 2 * APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 2U); +} + +/* The rearm work unmasks and restarts the quiet-period clock. */ +static void edac_test_rearm(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6000-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 12); + unsigned long before; + + ctx->irq.armed_jiffies = jiffies - 10 * HZ; + before = jiffies; + apple_soc_edac_rearm(&ctx->irq.rearm.work); + KUNIT_EXPECT_GE(test, ctx->irq.armed_jiffies, before); + KUNIT_EXPECT_LE(test, ctx->irq.armed_jiffies, jiffies); +} + +static struct kunit_case apple_soc_edac_test_cases[] = { + KUNIT_CASE(edac_test_source_t6041), + KUNIT_CASE(edac_test_source_edges), + KUNIT_CASE(edac_test_tables), + KUNIT_CASE(edac_test_t6041_status_lines), + KUNIT_CASE(edac_test_t8140_ni_table), + KUNIT_CASE(edac_test_event_log_source), + KUNIT_CASE(edac_test_of_match), + KUNIT_CASE(edac_test_t6041_status_zero), + KUNIT_CASE(edac_test_t6041_status_mask), + KUNIT_CASE(edac_test_t6041_status_sticky), + KUNIT_CASE(edac_test_t6041_status_index), + KUNIT_CASE(edac_test_ni_status_words), + KUNIT_CASE(edac_test_ni_status_none), + KUNIT_CASE(edac_test_ni_status_sticky), + KUNIT_CASE(edac_test_ni_status_top_word), + KUNIT_CASE(edac_test_irq_t6041_error), + KUNIT_CASE(edac_test_irq_t6041_bit3), + KUNIT_CASE(edac_test_irq_t6041_empty), + KUNIT_CASE(edac_test_irq_t6041_sticky), + KUNIT_CASE(edac_test_irq_no_status), + KUNIT_CASE(edac_test_irq_ni_error), + KUNIT_CASE(edac_test_irq_ni_empty_sticky), + KUNIT_CASE(edac_test_irq_backoff_limit), + KUNIT_CASE(edac_test_irq_backoff_reset), + KUNIT_CASE(edac_test_rearm), + {} +}; + +static struct kunit_suite apple_soc_edac_test_suite = { + .name = "apple-soc-edac", + .init = edac_test_init, + .test_cases = apple_soc_edac_test_cases, +}; + +kunit_test_suite(apple_soc_edac_test_suite); + +MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING"); +MODULE_LICENSE("GPL"); diff --git a/drivers/edac/apple_soc_edac.c b/drivers/edac/apple_soc_edac.c index ffdc17fe92e627..bd48da07615cf8 100644 --- a/drivers/edac/apple_soc_edac.c +++ b/drivers/edac/apple_soc_edac.c @@ -5,6 +5,9 @@ * Copyright The Aurora Silicon Contributors */ +#if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) +#include +#endif #include #include #include @@ -16,71 +19,14 @@ #include "edac_module.h" -#define APPLE_SOC_EDAC_NAME "apple_soc_edac" +#include "apple_soc_edac-internal.h" -/* - * The sources' status registers have no established acknowledge contract, - * so a line is masked when it fires and unmasked again after a backoff. - * A line still asserted after APPLE_SOC_EDAC_MAX_RETRIES backoffs stays - * masked; its count keeps the record. - */ -#define APPLE_SOC_EDAC_BACKOFF_MS 1000 -#define APPLE_SOC_EDAC_BACKOFF_MAX_MS 60000 -#define APPLE_SOC_EDAC_MAX_RETRIES 8 - -#define T6041_NI_REGS 25 -#define T6041_NI_STATUS 0x416c - -struct apple_soc_edac_range { - u8 first; - u8 count; - const char *name; -}; - -/* - * A fabric NI whose error status sits in its aperture: a block of status words, - * one per error type, whose set bits name the port. They're acknowledged by - * writing the set bits back. - */ -struct apple_soc_edac_ni { - u8 index; /* interrupt index */ - u8 reg; /* reg index of the NI's aperture */ - u16 status; /* offset of the first status word */ - u32 words; /* bit n: a status word at status + 4 * n */ -}; - -struct apple_soc_edac_hw { - const struct apple_soc_edac_range *ranges; - size_t nranges; - const struct apple_soc_edac_ni *ni; - size_t nni; - unsigned int num_irqs; - unsigned int num_status_regs; - bool event_log; -}; - -struct apple_soc_edac; - -struct apple_soc_edac_irq { - struct apple_soc_edac *edac; - const char *source; - unsigned int index; - int irq; - const struct apple_soc_edac_ni *ni; - void __iomem *ni_base; - unsigned int retries; - unsigned int backoff_ms; - unsigned long armed_jiffies; - struct delayed_work rearm; -}; - -struct apple_soc_edac { - struct device *dev; - struct edac_device_ctl_info *dci; - const struct apple_soc_edac_hw *hw; - struct apple_soc_edac_irq *irqs; - void __iomem **status_regs; -}; +#if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) +#include +#else +#define VISIBLE_IF_KUNIT static +#define EXPORT_SYMBOL_IF_KUNIT(symbol) +#endif /* * DCS IRQs drive a separate thermal loop and are intentionally omitted. @@ -200,8 +146,8 @@ static const struct apple_soc_edac_hw t8140_event_hw = { .event_log = true, }; -static const char *apple_soc_edac_source(const struct apple_soc_edac_hw *hw, - unsigned int index) +VISIBLE_IF_KUNIT const char * +apple_soc_edac_source(const struct apple_soc_edac_hw *hw, unsigned int index) { size_t i; @@ -217,13 +163,33 @@ static const char *apple_soc_edac_source(const struct apple_soc_edac_hw *hw, return NULL; } +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_source); + +/* Status register accessors; KUnit redirects them to a fake register block. */ +VISIBLE_IF_KUNIT u32 apple_soc_edac_read(void __iomem *reg) +{ +#if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(apple_soc_edac_read, reg); +#endif + return readl(reg); +} +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_read); + +VISIBLE_IF_KUNIT void apple_soc_edac_write(void __iomem *reg, u32 val) +{ +#if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(apple_soc_edac_write, reg, val); +#endif + writel(val, reg); +} +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_write); /* * Read and acknowledge a T6041 NI status word. Returns whether it was set; * @error says whether a bit in the platform error policy was set and * @cleared whether the word reads back clear after the acknowledge. */ -static bool apple_soc_edac_t6041_status(struct apple_soc_edac_irq *irq_data, +VISIBLE_IF_KUNIT bool apple_soc_edac_t6041_status(struct apple_soc_edac_irq *irq_data, bool *error, bool *cleared) { struct apple_soc_edac *edac = irq_data->edac; @@ -236,14 +202,14 @@ static bool apple_soc_edac_t6041_status(struct apple_soc_edac_irq *irq_data, void __iomem *reg = edac->status_regs[irq_data->index - 45] + T6041_NI_STATUS; - status = readl(reg); + status = apple_soc_edac_read(reg); if (!status) return false; /* Bit 3 is not part of the platform error policy. */ *error = status & 0xf7; - writel(status, reg); - left = readl(reg); + apple_soc_edac_write(reg, status); + left = apple_soc_edac_read(reg); if (left) { *cleared = false; dev_info_ratelimited(edac->dev, @@ -256,12 +222,13 @@ static bool apple_soc_edac_t6041_status(struct apple_soc_edac_irq *irq_data, return false; } +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_t6041_status); /* * Log and acknowledge an NI's set status words. Returns whether any was set; * @cleared says whether all of them read back clear. */ -static bool apple_soc_edac_ni_status(struct apple_soc_edac_irq *irq_data, +VISIBLE_IF_KUNIT bool apple_soc_edac_ni_status(struct apple_soc_edac_irq *irq_data, bool *cleared) { const struct apple_soc_edac_ni *ni = irq_data->ni; @@ -273,11 +240,11 @@ static bool apple_soc_edac_ni_status(struct apple_soc_edac_irq *irq_data, *cleared = true; for_each_set_bit(bit, &words, 32) { offset = ni->status + 4 * bit; - status = readl(irq_data->ni_base + offset); + status = apple_soc_edac_read(irq_data->ni_base + offset); if (!status) continue; - writel(status, irq_data->ni_base + offset); - left = readl(irq_data->ni_base + offset); + apple_soc_edac_write(irq_data->ni_base + offset, status); + left = apple_soc_edac_read(irq_data->ni_base + offset); dev_err_ratelimited(irq_data->edac->dev, "%s: status %#x at %#x, %#x after the acknowledge\n", irq_data->source, status, offset, left); @@ -288,8 +255,9 @@ static bool apple_soc_edac_ni_status(struct apple_soc_edac_irq *irq_data, return found; } +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_ni_status); -static void apple_soc_edac_rearm(struct work_struct *work) +VISIBLE_IF_KUNIT void apple_soc_edac_rearm(struct work_struct *work) { struct apple_soc_edac_irq *irq_data = container_of(to_delayed_work(work), struct apple_soc_edac_irq, @@ -298,8 +266,9 @@ static void apple_soc_edac_rearm(struct work_struct *work) irq_data->armed_jiffies = jiffies; enable_irq(irq_data->irq); } +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_rearm); -static irqreturn_t apple_soc_edac_irq_thread(int irq, void *data) +VISIBLE_IF_KUNIT irqreturn_t apple_soc_edac_irq_thread(int irq, void *data) { struct apple_soc_edac_irq *irq_data = data; struct apple_soc_edac *edac = irq_data->edac; @@ -371,6 +340,7 @@ static irqreturn_t apple_soc_edac_irq_thread(int irq, void *data) return IRQ_HANDLED; } +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_irq_thread); static int apple_soc_edac_map_ni(struct platform_device *pdev, struct apple_soc_edac_irq *irq_data) @@ -515,7 +485,7 @@ static void apple_soc_edac_remove(struct platform_device *pdev) edac_device_free_ctl_info(edac->dci); } -static const struct of_device_id apple_soc_edac_of_match[] = { +VISIBLE_IF_KUNIT const struct of_device_id apple_soc_edac_of_match[] = { { .compatible = "apple,t6000-error-handler", .data = &t6000_error_hw }, { .compatible = "apple,t6041-error-handler", .data = &t6041_error_hw }, { .compatible = "apple,t8112-error-handler", .data = &t8112_error_hw }, @@ -526,6 +496,7 @@ static const struct of_device_id apple_soc_edac_of_match[] = { { .compatible = "apple,t8140-event-log", .data = &t8140_event_hw }, { } }; +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_of_match); MODULE_DEVICE_TABLE(of, apple_soc_edac_of_match); static struct platform_driver apple_soc_edac_driver = { diff --git a/drivers/edac/apple_soc_edac.kunitconfig b/drivers/edac/apple_soc_edac.kunitconfig new file mode 100644 index 00000000000000..987bd6c1c064c2 --- /dev/null +++ b/drivers/edac/apple_soc_edac.kunitconfig @@ -0,0 +1,6 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_RAS=y +CONFIG_EDAC=y +CONFIG_EDAC_APPLE_SOC=y +CONFIG_EDAC_APPLE_SOC_KUNIT_TEST=y diff --git a/drivers/gpio/Kconfig b/drivers/gpio/Kconfig index a48586bb8edbae..b35f8bbe369624 100644 --- a/drivers/gpio/Kconfig +++ b/drivers/gpio/Kconfig @@ -1557,6 +1557,19 @@ config GPIO_MACSMC This driver can also be built as a module. If so, the module will be called gpio-macsmc. +config GPIO_MACSMC_KUNIT_TEST + bool "KUnit tests for the Apple SMC GPIO driver" if !KUNIT_ALL_TESTS + depends on GPIO_MACSMC=y && KUNIT=y + depends on MFD_MACSMC_KUNIT_TEST + default KUNIT_ALL_TESTS + help + Build tests for the Apple SMC GPIO driver: the gPxx key names of + the pins, the output command words, the J700 pcIO and J713 radio + lines with their remembered levels, the DT output and pcIO + templates, the valid line mask and the pcIO output-command chip. + A static stub replaces SMC writes, so the tests need no Apple + hardware. + config GPIO_MADERA tristate "Cirrus Logic Madera class codecs" depends on PINCTRL_MADERA diff --git a/drivers/gpio/gpio-macsmc-test.c b/drivers/gpio/gpio-macsmc-test.c new file mode 100644 index 00000000000000..50482dd40e5638 --- /dev/null +++ b/drivers/gpio/gpio-macsmc-test.c @@ -0,0 +1,467 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SMC GPIO driver: the gPxx key names, the output + * command words, the board-specific lines (J700 pcIO outputs, the J713 radio + * line) with their cached levels, the DT command templates and the + * pcIO output-command variant. + * + * SMC writes go to a static stub on apple_smc_write() (see + * MFD_MACSMC_KUNIT_TEST); the gpio_chip is registered with gpiolib so the + * driver's callbacks run on a real chip. The SMC has no keys here, so no + * line needs an SMC read. + * + * Included by gpio-macsmc.c. + */ + +#include +#include +#include +#include + +#define GPIO_TEST_GP ((smc_key)_SMC_KEY("gP\0\0")) +#define GPIO_TEST_GPL ((smc_key)_SMC_KEY("gp\0\0")) + +struct macsmc_gpio_test_write { + smc_key key; + size_t size; + u64 val; +}; + +struct macsmc_gpio_test { + struct apple_smc smc; + u8 shmem[256]; + /* + * The driver state, and the pcIO commands it points at, live in ctx: + * ctx is allocated before the device, so they outlive the gpio_chip + * that the device's devres removes at the end of the case. + */ + struct macsmc_gpio gpio; + u64 commands[2]; + struct macsmc_gpio *smcgp; + struct device *dev; + struct software_node swnode; + struct macsmc_gpio_test_write writes[8]; + unsigned int nr_writes; + int write_ret; +}; + +static int macsmc_gpio_test_write(struct apple_smc *smc, smc_key key, + const void *buf, size_t size) +{ + struct macsmc_gpio_test *ctx = container_of(smc, struct macsmc_gpio_test, smc); + struct macsmc_gpio_test_write *w; + + if (ctx->nr_writes < ARRAY_SIZE(ctx->writes)) { + w = &ctx->writes[ctx->nr_writes]; + w->key = key; + w->size = size; + w->val = 0; + memcpy(&w->val, buf, min(size, sizeof(w->val))); + } + ctx->nr_writes++; + return ctx->write_ret; +} + +KUNIT_DEFINE_ACTION_WRAPPER(macsmc_gpio_test_remove_swnode, device_remove_software_node, + struct device *); +KUNIT_DEFINE_ACTION_WRAPPER(macsmc_gpio_test_unregister_swnode, software_node_unregister, + const struct software_node *); + +static struct macsmc_gpio_test *macsmc_gpio_test_alloc(struct kunit *test, + const char *name, + const struct property_entry *props) +{ + struct macsmc_gpio_test *ctx; + int ret; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + mutex_init(&ctx->smc.mutex); + spin_lock_init(&ctx->smc.lock); + /* Any SMC command fails: the SMC never booted. */ + ctx->smc.shmem.iomem = (void __force __iomem *)ctx->shmem; + + /* + * The gpiochip's device shares the parent's fwnode and drops its + * reference after the parent's devres runs, so the node is registered + * before the device and unregistered after it is gone. A managed node + * would get its reference dropped once per device. + */ + if (props) { + ctx->swnode.properties = props; + KUNIT_ASSERT_EQ(test, software_node_register(&ctx->swnode), 0); + ret = kunit_add_action_or_reset(test, macsmc_gpio_test_unregister_swnode, + &ctx->swnode); + KUNIT_ASSERT_EQ(test, ret, 0); + } + + ctx->dev = kunit_device_register(test, name); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + if (props) { + KUNIT_ASSERT_EQ(test, device_add_software_node(ctx->dev, &ctx->swnode), 0); + ret = kunit_add_action_or_reset(test, macsmc_gpio_test_remove_swnode, ctx->dev); + KUNIT_ASSERT_EQ(test, ret, 0); + } + + ctx->smcgp = &ctx->gpio; + ctx->smcgp->dev = ctx->dev; + ctx->smcgp->smc = &ctx->smc; + mutex_init(&ctx->smcgp->j713_reg_on_lock); + + kunit_activate_static_stub(test, apple_smc_write, macsmc_gpio_test_write); + return ctx; +} + +/* The chip macsmc_gpio_probe() registers, on an SMC without GPIO keys. */ +static void macsmc_gpio_test_register(struct kunit *test, struct macsmc_gpio_test *ctx, + smc_key base_key, bool j700, bool j713) +{ + struct macsmc_gpio *smcgp = ctx->smcgp; + + smcgp->base_key = base_key; + smcgp->j700_pcio = j700; + smcgp->j713 = j713; + KUNIT_ASSERT_EQ(test, macsmc_gpio_parse_templates(smcgp), 0); + + smcgp->gc.label = "macsmc-gpio-test"; + smcgp->gc.owner = THIS_MODULE; + smcgp->gc.get = macsmc_gpio_get; + smcgp->gc.set = macsmc_gpio_set; + smcgp->gc.get_direction = macsmc_gpio_get_direction; + smcgp->gc.init_valid_mask = macsmc_gpio_init_valid_mask; + smcgp->gc.can_sleep = true; + smcgp->gc.ngpio = MAX_GPIO; + smcgp->gc.base = -1; + smcgp->gc.parent = ctx->dev; + KUNIT_ASSERT_EQ(test, devm_gpiochip_add_data(ctx->dev, &smcgp->gc, smcgp), 0); +} + +static void macsmc_gpio_test_expect_write(struct kunit *test, + struct macsmc_gpio_test *ctx, + unsigned int idx, smc_key key, + size_t size, u64 val) +{ + KUNIT_ASSERT_LT(test, idx, ctx->nr_writes); + KUNIT_EXPECT_EQ_MSG(test, ctx->writes[idx].key, key, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, ctx->writes[idx].size, size, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, ctx->writes[idx].val, val, "write %u", idx); +} + +/* Pin numbers become two lowercase hex digits after the base key. */ +static void macsmc_gpio_test_key_name(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GP, 0), _SMC_KEY("gP00")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GP, 0x0a), _SMC_KEY("gP0a")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GP, 0x13), _SMC_KEY("gP13")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GP, 0x3f), _SMC_KEY("gP3f")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GPL, 0x05), _SMC_KEY("gp05")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GPL, 0xc1), _SMC_KEY("gpc1")); +} + +/* Key names parse back to pin numbers; non-hex names are rejected. */ +static void macsmc_gpio_test_key_nr(struct kunit *test) +{ + unsigned int i; + + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gP13")), 0x13); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gP0a")), 10); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gP0A")), 10); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gp3f")), 63); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gPzz")), -1); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gPg0")), -1); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gP0-")), -1); + + for (i = 0; i < MAX_GPIO; i++) + KUNIT_EXPECT_EQ_MSG(test, macsmc_gpio_nr(macsmc_gpio_key(GPIO_TEST_GP, i)), i, + "pin %u", i); +} + +/* A plain line is set with a CMD_OUTPUT word carrying the level in bit 0. */ +static void macsmc_gpio_test_set_plain(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, "gpio", NULL); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, false, false); + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, 0x2c, 0), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gP05"), 4, CMD_OUTPUT | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP2c"), 4, CMD_OUTPUT); + + ctx->write_ret = -EIO; + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 1), -EIO); +} + +/* On the J713 family gP13 is the radio's reg_on: template | level, cached. */ +static void macsmc_gpio_test_j713_reg_on(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, "gpio", NULL); + struct gpio_chip *gc = &ctx->smcgp->gc; + const unsigned int pin = MACSMC_J713_RADIO_REG_ON_GPIO; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, false, true); + KUNIT_EXPECT_EQ(test, gc->get_direction(gc, pin), GPIO_LINE_DIRECTION_OUT); + /* No readback: nothing is known before the first write. */ + KUNIT_EXPECT_EQ(test, gc->get(gc, pin), -EOPNOTSUPP); + + KUNIT_EXPECT_EQ(test, gc->set(gc, pin, 1), 0); + KUNIT_EXPECT_EQ(test, gc->get(gc, pin), 1); + KUNIT_EXPECT_EQ(test, gc->set(gc, pin, 0), 0); + KUNIT_EXPECT_EQ(test, gc->get(gc, pin), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gP13"), 4, + MACSMC_J713_RADIO_REG_ON_TEMPLATE | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP13"), 4, + MACSMC_J713_RADIO_REG_ON_TEMPLATE); + + /* A failed write does not change the reported level. */ + ctx->write_ret = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, gc->set(gc, pin, 1), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, gc->get(gc, pin), 0); +} + +/* The radio line is gP13 only: not gp13, not another gP pin. */ +static void macsmc_gpio_test_j713_other_lines(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, "gpio", NULL); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GPL, false, true); + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J713_RADIO_REG_ON_GPIO, 1), 0); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gp13"), 4, CMD_OUTPUT | 1); + + ctx->smcgp->base_key = GPIO_TEST_GP; + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J713_RADIO_REG_ON_GPIO - 1, 1), 0); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP12"), 4, CMD_OUTPUT | 1); + + /* Without the J713 flag gP13 is a plain line too. */ + ctx->smcgp->j713 = false; + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J713_RADIO_REG_ON_GPIO, 0), 0); + macsmc_gpio_test_expect_write(test, ctx, 2, _SMC_KEY("gP13"), 4, CMD_OUTPUT); +} + +static const u32 macsmc_gpio_test_out_tmpl[] = { 5, 0x00a00000, 0x3e, 0x00300000 }; + +static const struct property_entry macsmc_gpio_test_out_props[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", macsmc_gpio_test_out_tmpl), + {} +}; + +/* apple,output-templates: pairs; the write is template | level. */ +static void macsmc_gpio_test_output_template(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = + macsmc_gpio_test_alloc(test, "gpio", macsmc_gpio_test_out_props); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, false, false); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 5)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 0x3e)); + KUNIT_EXPECT_FALSE(test, gpiochip_line_is_valid(gc, 6)); + KUNIT_EXPECT_EQ(test, gc->get_direction(gc, 5), GPIO_LINE_DIRECTION_OUT); + + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, 0x3e, 0), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gP05"), 4, 0x00a00001); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP3e"), 4, 0x00300000); + + ctx->write_ret = -EIO; + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 0), -EIO); +} + +static const u32 macsmc_gpio_test_pcio_tmpl[] = { 21, 0x40000, 0x150000 }; + +static const struct property_entry macsmc_gpio_test_pcio_props[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", macsmc_gpio_test_out_tmpl), + PROPERTY_ENTRY_U32_ARRAY("apple,pcio-templates", macsmc_gpio_test_pcio_tmpl), + {} +}; + +/* + * J700: pins 19 and 8 and the pcio-templates pins are eight-byte pcIO + * writes, hi << 32 | lo | level, whose level is remembered for reads. + */ +static void macsmc_gpio_test_j700_pcio(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = + macsmc_gpio_test_alloc(test, "gpio", macsmc_gpio_test_pcio_props); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, true, false); + KUNIT_EXPECT_EQ(test, gc->get_direction(gc, MACSMC_J700_AFE_RESET_GPIO), + GPIO_LINE_DIRECTION_OUT); + + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_AFE_RESET_GPIO, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_RADIO_REG_ON_GPIO, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, 21, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_AFE_RESET_GPIO, 0), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 4); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("pcIO"), 8, + ((u64)MACSMC_J700_AFE_RESET_HI << 32) | + MACSMC_J700_AFE_RESET_LO | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("pcIO"), 8, + ((u64)MACSMC_J700_RADIO_REG_ON_HI << 32) | + MACSMC_J700_RADIO_REG_ON_LO | 1); + macsmc_gpio_test_expect_write(test, ctx, 2, _SMC_KEY("pcIO"), 8, + (0x150000ULL << 32) | 0x40000 | 1); + macsmc_gpio_test_expect_write(test, ctx, 3, _SMC_KEY("pcIO"), 8, + ((u64)MACSMC_J700_AFE_RESET_HI << 32) | + MACSMC_J700_AFE_RESET_LO); + + KUNIT_EXPECT_EQ(test, gc->get(gc, MACSMC_J700_AFE_RESET_GPIO), 0); + KUNIT_EXPECT_EQ(test, gc->get(gc, MACSMC_J700_RADIO_REG_ON_GPIO), 1); + KUNIT_EXPECT_EQ(test, gc->get(gc, 21), 1); + + /* A failed write keeps the remembered level. */ + ctx->write_ret = -EIO; + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_RADIO_REG_ON_GPIO, 0), -EIO); + KUNIT_EXPECT_EQ(test, gc->get(gc, MACSMC_J700_RADIO_REG_ON_GPIO), 1); + + /* An output template still wins over pcIO for its own pin. */ + ctx->write_ret = 0; + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 1), 0); + macsmc_gpio_test_expect_write(test, ctx, 5, _SMC_KEY("gP05"), 4, 0x00a00001); +} + +/* The valid mask is the board's fixed lines plus the templated ones. */ +static void macsmc_gpio_test_valid_mask(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = + macsmc_gpio_test_alloc(test, "gpio", macsmc_gpio_test_pcio_props); + struct gpio_chip *gc = &ctx->smcgp->gc; + unsigned int i, valid = 0; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, true, false); + for (i = 0; i < MAX_GPIO; i++) + valid += gpiochip_line_is_valid(gc, i); + KUNIT_EXPECT_EQ(test, valid, 5); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, MACSMC_J700_AFE_RESET_GPIO)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, MACSMC_J700_RADIO_REG_ON_GPIO)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 21)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 5)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 0x3e)); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* Off the J700, pcio-templates do nothing: those pins are plain gPxx lines. */ +static void macsmc_gpio_test_pcio_template_not_j700(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = + macsmc_gpio_test_alloc(test, "gpio", macsmc_gpio_test_pcio_props); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, false, false); + KUNIT_EXPECT_FALSE(test, gpiochip_line_is_valid(gc, 21)); + KUNIT_EXPECT_FALSE(test, gpiochip_line_is_valid(gc, MACSMC_J700_AFE_RESET_GPIO)); + KUNIT_EXPECT_EQ(test, gc->set(gc, 21, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_AFE_RESET_GPIO, 1), 0); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gP15"), 4, CMD_OUTPUT | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP13"), 4, CMD_OUTPUT | 1); +} + +static int macsmc_gpio_test_parse(struct kunit *test, const char *name, + const struct property_entry *props) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, name, props); + + return macsmc_gpio_parse_templates(ctx->smcgp); +} + +/* Malformed template lists are refused, the pin bound is 0..63. */ +static void macsmc_gpio_test_template_errors(struct kunit *test) +{ + static const u32 odd[] = { 5, 0x00a00000, 6 }; + static const u32 pin64[] = { 64, 0x00a00000 }; + static const u32 pin63[] = { 63, 0x00a00000 }; + static const u32 pcio_short[] = { 21, 0x40000, 0x150000, 22 }; + static const u32 pcio_pin64[] = { 64, 0x40000, 0x150000 }; + const struct property_entry p_odd[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", odd), {} + }; + const struct property_entry p_pin64[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", pin64), {} + }; + const struct property_entry p_pin63[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", pin63), {} + }; + const struct property_entry p_pcio_short[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,pcio-templates", pcio_short), {} + }; + const struct property_entry p_pcio_pin64[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,pcio-templates", pcio_pin64), {} + }; + + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse0", p_odd), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse1", p_pin64), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse2", p_pin63), 0); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse3", p_pcio_short), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse4", p_pcio_pin64), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse5", NULL), 0); +} + +/* apple,smc-pcio-gpio: line N writes output_commands[N] | level as LE64 to pcIO. */ +static void macsmc_gpio_test_pcio_outputs(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, "gpio", NULL); + struct macsmc_gpio *smcgp = ctx->smcgp; + struct gpio_chip *gc = &smcgp->gc; + static const u64 commands[] = { 0x0013000000010000ULL, 0x0008000000800000ULL }; + + BUILD_BUG_ON(sizeof(commands) != sizeof(ctx->commands)); + memcpy(ctx->commands, commands, sizeof(commands)); + smcgp->output_commands = ctx->commands; + + /* As macsmc_pcio_probe() sets it up. */ + gc->label = "macsmc-pcio-output-test"; + gc->owner = THIS_MODULE; + gc->get = macsmc_pcio_get; + gc->set = macsmc_pcio_set; + gc->direction_output = macsmc_pcio_set; + gc->get_direction = macsmc_pcio_get_direction; + gc->can_sleep = true; + gc->ngpio = ARRAY_SIZE(commands); + gc->base = -1; + gc->parent = ctx->dev; + KUNIT_ASSERT_EQ(test, devm_gpiochip_add_data(ctx->dev, gc, smcgp), 0); + + KUNIT_EXPECT_EQ(test, gc->get_direction(gc, 1), GPIO_LINE_DIRECTION_OUT); + KUNIT_EXPECT_EQ(test, gc->get(gc, 0), -EOPNOTSUPP); + + /* A positive status from the write is success. */ + ctx->write_ret = 8; + KUNIT_EXPECT_EQ(test, gc->set(gc, 0, 1), 0); + ctx->write_ret = 0; + KUNIT_EXPECT_EQ(test, gc->direction_output(gc, 1, 0), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, 1, 1), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 3); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("pcIO"), 8, commands[0] | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("pcIO"), 8, commands[1]); + macsmc_gpio_test_expect_write(test, ctx, 2, _SMC_KEY("pcIO"), 8, commands[1] | 1); + + ctx->write_ret = -EBUSY; + KUNIT_EXPECT_EQ(test, gc->set(gc, 0, 0), -EBUSY); +} + +static struct kunit_case macsmc_gpio_test_cases[] = { + KUNIT_CASE(macsmc_gpio_test_key_name), + KUNIT_CASE(macsmc_gpio_test_key_nr), + KUNIT_CASE(macsmc_gpio_test_set_plain), + KUNIT_CASE(macsmc_gpio_test_j713_reg_on), + KUNIT_CASE(macsmc_gpio_test_j713_other_lines), + KUNIT_CASE(macsmc_gpio_test_output_template), + KUNIT_CASE(macsmc_gpio_test_j700_pcio), + KUNIT_CASE(macsmc_gpio_test_valid_mask), + KUNIT_CASE(macsmc_gpio_test_pcio_template_not_j700), + KUNIT_CASE(macsmc_gpio_test_template_errors), + KUNIT_CASE(macsmc_gpio_test_pcio_outputs), + {} +}; + +static struct kunit_suite macsmc_gpio_test_suite = { + .name = "macsmc-gpio", + .test_cases = macsmc_gpio_test_cases, +}; + +kunit_test_suite(macsmc_gpio_test_suite); diff --git a/drivers/gpio/gpio-macsmc.c b/drivers/gpio/gpio-macsmc.c index 434ed549d4c1ed..68b1802a1eacf0 100644 --- a/drivers/gpio/gpio-macsmc.c +++ b/drivers/gpio/gpio-macsmc.c @@ -599,3 +599,7 @@ module_platform_driver(macsmc_gpio_driver); MODULE_AUTHOR("Hector Martin "); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple SMC GPIO driver"); + +#if IS_ENABLED(CONFIG_GPIO_MACSMC_KUNIT_TEST) +#include "gpio-macsmc-test.c" +#endif diff --git a/drivers/gpio/gpio-macsmc.kunitconfig b/drivers/gpio/gpio-macsmc.kunitconfig new file mode 100644 index 00000000000000..1b9e736fdd0e7e --- /dev/null +++ b/drivers/gpio/gpio-macsmc.kunitconfig @@ -0,0 +1,12 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/gpio/gpio-macsmc.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_GPIOLIB=y +CONFIG_GPIO_MACSMC=y +CONFIG_GPIO_MACSMC_KUNIT_TEST=y diff --git a/drivers/gpu/drm/apple/Kconfig b/drivers/gpu/drm/apple/Kconfig index 99632ffe1535cb..689171db4ebe0c 100644 --- a/drivers/gpu/drm/apple/Kconfig +++ b/drivers/gpu/drm/apple/Kconfig @@ -75,6 +75,24 @@ config DRM_APPLE_DCP_T8132 Load appledrm explicitly before the GPU, with its alias autoload disabled, after guarded admission of the inherited display DARTs. +config DRM_APPLE_DCP_T8152 + bool "Mac mini M6 (J873g) displays" + depends on DRM_APPLE + depends on TYPEC + depends on MFD_MACSMC=y || MFD_MACSMC=DRM_APPLE + select APERTURE_HELPERS + help + Lets the common Apple display driver drive the three display + coprocessors of the T8152 Mac mini (J873g) through their firmware's + iBoot interface: the HDMI port, whose DisplayPort-to-HDMI converter + is powered through the SMC, and displays on the rear USB-C ports, + whose DisplayPort alt mode the USB Type-C port driver of their PD + controllers reports (TYPEC_SN201202X). + + The boot loader hands each coprocessor over, running or quiesced, + with the AFK endpoints it left running. The adopted sessions cannot + be stopped; their DMA stays retained until reboot. + config DRM_APPLE_DEBUG bool "Enable additional driver debugging" depends on DRM_APPLE @@ -110,6 +128,9 @@ config DRM_APPLE_PARSER_KUNIT_TEST help Build tests for AFKv2 lengths, DMA ownership and reply correlation, legacy EPIC replies, and H17P IOMFB callback envelopes and sizes. + Also check that the DCP dictionary parsers (display metadata, + DPTX capabilities, log events, timing catalogs, EDID properties + and audio elements) reject truncated and malformed blobs. The tests use allocated buffers and fake devices and do not require an Apple display controller or any firmware. diff --git a/drivers/gpu/drm/apple/Makefile b/drivers/gpu/drm/apple/Makefile index a6687d7cccd657..6098e8efb7c597 100644 --- a/drivers/gpu/drm/apple/Makefile +++ b/drivers/gpu/drm/apple/Makefile @@ -18,8 +18,12 @@ appledrm-y += iomfb_v14_7_tpl.o appledrm-y += iomfb_v26_6_desktop.o appledrm-y += iomfb_v14_7.o iomfb_v14_7_link.o appledrm-$(CONFIG_DRM_APPLE_DCP_T8132) += iomfb_m4.o t8132_ext_drm.o +appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += t8152_atc.o t8152_aux.o t8152_dptx.o +appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += t8152_hdmi.o t8152_typec.o +appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += iomfb_iboot.o iboot_drm.o appledrm-y += iomfb_h17p.o appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += iomfb_h17p_test.o parser_test.o +appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += iomfb_v27_test.o appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += iomfb_external_hdr_hints_test.o appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += apple_resume_test.o appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += apple_boot_display_test.o @@ -51,8 +55,10 @@ obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += afk-service-test.o obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp_cec_test.o obj-$(CONFIG_DRM_APPLE_PARSER_KUNIT_TEST) += afkv2-test.o +appledrm-$(CONFIG_DRM_APPLE_PARSER_KUNIT_TEST) += parser-bounds-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += parser-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += hotplug-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += v14-board-test.o +appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += v14-plane-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += audio-no-sio-test.dtbo.o diff --git a/drivers/gpu/drm/apple/afk-parser-test.c b/drivers/gpu/drm/apple/afk-parser-test.c index c1a956a6616f14..99873d53329d1e 100644 --- a/drivers/gpu/drm/apple/afk-parser-test.c +++ b/drivers/gpu/drm/apple/afk-parser-test.c @@ -182,6 +182,104 @@ static void afk_compact_service_call_report_test(struct kunit *test) KUNIT_EXPECT_EQ(test, cap.pa, 0x3400); } +/* + * Replies to firmware calls wait on the endpoint's transmit queue. While it + * makes no progress, further calls are taken only as long as their replies + * fit the room of one message. + */ +struct compact_reply_gate { + struct work_struct work; + struct completion open; +}; + +static void compact_reply_gate_fn(struct work_struct *work) +{ + struct compact_reply_gate *gate = + container_of(work, struct compact_reply_gate, work); + + wait_for_completion(&gate->open); +} + +static int compact_call_count_cb(struct apple_epic_service *service, u16 group, + u32 command, const void *data, size_t size, + void *reply, size_t room) +{ + unsigned int *count = service->cookie; + + (*count)++; + return 0; +} + +static const struct apple_epic_service_ops compact_call_count_ops = { + .name = "compact-call-test", + .call_v2 = compact_call_count_cb, +}; + +static void afk_compact_call_reply_budget_test(struct kunit *test) +{ + /* Four calls of this size take all the room; the timestamp and sub-header precede. */ + const size_t payload_size = AFK_COMPACT_MESSAGE_MAX / 4; + const size_t wire_size = 16 + payload_size; + struct apple_dcp_afkep *ep = test->priv; + struct compact_reply_gate gate; + struct epic_compact_sub_hdr *sub; + struct epic_service_call *call; + unsigned int handled = 0, i; + u8 *wire; + + wire = kunit_kzalloc(test, wire_size, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, wire); + sub = (void *)(wire + 8); + sub->category = 1; + sub->type = EPIC_SUBTYPE_STD_SERVICE; + call = (void *)((u8 *)(sub + 1) + sizeof(struct epic_compact_desc)); + call->command = cpu_to_le32(4); + call->data_len = cpu_to_le32(payload_size - sizeof(struct epic_compact_desc) - + sizeof(*call)); + call->magic = cpu_to_le32(EPIC_SERVICE_CALL_MAGIC); + + ep->services[0].ops = &compact_call_count_ops; + ep->services[0].cookie = &handled; + ep->tx_wq = alloc_ordered_workqueue("afk-parser-test-tx", 0); + KUNIT_ASSERT_NOT_NULL(test, ep->tx_wq); + + /* The queue is ordered: nothing behind the gate runs until it opens. */ + INIT_WORK_ONSTACK(&gate.work, compact_reply_gate_fn); + init_completion(&gate.open); + queue_work(ep->tx_wq, &gate.work); + + /* A call left without a reply must hold off a coordinated sleep. */ + ep->dcp->v27_sleep_transport = true; + for (i = 0; i < 4; i++) + afk_recv_compact_message(ep, 1, wire, wire_size); + KUNIT_EXPECT_FALSE(test, ep->sleep_poisoned); + afk_recv_compact_message(ep, 1, wire, wire_size); + KUNIT_EXPECT_EQ(test, handled, 4U); + KUNIT_EXPECT_EQ(test, atomic_read(&ep->sleep_jobs), 4); + KUNIT_EXPECT_TRUE(test, ep->sleep_poisoned); + + /* A small call no longer fits either. */ + call->data_len = cpu_to_le32(0); + afk_recv_compact_message(ep, 1, wire, + 16 + sizeof(struct epic_compact_desc) + sizeof(*call)); + KUNIT_EXPECT_EQ(test, handled, 4U); + KUNIT_EXPECT_EQ(test, atomic_read(&ep->sleep_jobs), 4); + + /* The replies fail without a transmit ring, which frees their room. */ + complete(&gate.open); + flush_workqueue(ep->tx_wq); + KUNIT_EXPECT_EQ(test, atomic_read(&ep->sleep_jobs), 0); + + afk_recv_compact_message(ep, 1, wire, + 16 + sizeof(struct epic_compact_desc) + sizeof(*call)); + KUNIT_EXPECT_EQ(test, handled, 5U); + + destroy_workqueue(ep->tx_wq); + ep->tx_wq = NULL; + destroy_work_on_stack(&gate.work); + KUNIT_EXPECT_EQ(test, atomic_read(&ep->sleep_jobs), 0); +} + /* * Slot reuse for re-announced compact services. The firmware re-announces a * service under a fresh interface on every DP relink without closing the old @@ -341,6 +439,7 @@ static void afk_compact_cut_before_wildcard_test(struct kunit *test) static struct kunit_case afk_parser_cases[] = { KUNIT_CASE(afk_serialized_report_test), KUNIT_CASE(afk_compact_service_call_report_test), + KUNIT_CASE(afk_compact_call_reply_budget_test), KUNIT_CASE(afk_compact_header_test), KUNIT_CASE(afk_short_epic_test), KUNIT_CASE(afk_short_reply_test), diff --git a/drivers/gpu/drm/apple/afk-service-test.c b/drivers/gpu/drm/apple/afk-service-test.c index 06db01a8f84d3f..fcd64cde1df663 100644 --- a/drivers/gpu/drm/apple/afk-service-test.c +++ b/drivers/gpu/drm/apple/afk-service-test.c @@ -266,11 +266,86 @@ static void afk_service_declined_channel_test(struct kunit *test) KUNIT_EXPECT_TRUE(test, afk_service_retired(service, 3)); } +static const struct apple_epic_service_ops singleton_video_ops = { + .name = "singleton-video", + .reusable = true, + .singleton = true, +}; + +static const struct apple_epic_service_ops singleton_audio_ops = { + .name = "singleton-audio", + .reusable = true, + .singleton = true, +}; + +/* + * The firmware announces its AV video and audio interfaces again on fresh + * channels on every display attach and never closes the old ones. Announce + * them as the endpoint's receive path does: take the first reclaimable + * slot, then supersede the previous instance. The superseded audio + * instance stays pinned by its owner until the successor's init drops it. + */ +static struct apple_epic_service * +afk_test_announce(struct apple_epic_service *slots, unsigned int nr, + const struct apple_epic_service_ops *ops, u32 channel) +{ + struct apple_epic_service *admitted = NULL; + unsigned int i; + + /* As afk_recv_handle_init(): admit first, then retire what it replaces. */ + for (i = 0; i < nr && !admitted; i++) + if (afk_service_reinit(&slots[i], NULL, ops, channel)) + admitted = &slots[i]; + if (!admitted) + return NULL; + for (i = 0; i < nr; i++) + if (&slots[i] != admitted) + afk_service_supersede(&slots[i], ops, channel); + return admitted; +} + +static void afk_service_singleton_reannounce_test(struct kunit *test) +{ + struct apple_epic_service *slots, *video, *audio, *owned = NULL; + const unsigned int nr = 4; + unsigned int i; + u32 channel = 5; + + slots = kunit_kcalloc(test, nr, sizeof(*slots), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, slots); + for (i = 0; i < nr; i++) + spin_lock_init(&slots[i].lock); + + /* Many more attaches than slots: the budget stays bounded. */ + for (i = 0; i < 4 * AFK_MAX_CHANNEL; i++, channel += 4) { + video = afk_test_announce(slots, nr, &singleton_video_ops, channel); + KUNIT_ASSERT_NOT_NULL(test, video); + KUNIT_EXPECT_TRUE(test, afk_service_matches(video, channel)); + audio = afk_test_announce(slots, nr, &singleton_audio_ops, channel + 2); + KUNIT_ASSERT_NOT_NULL(test, audio); + /* The audio owner pins the new instance and lets go of the old one. */ + KUNIT_ASSERT_PTR_EQ(test, afk_service_get(audio), audio); + if (owned) + afk_service_put(owned); + owned = audio; + } + + /* A different service is never superseded by a singleton announcement. */ + KUNIT_EXPECT_FALSE(test, afk_service_supersede(owned, &singleton_video_ops, 1)); + /* Nor is the instance announced on the same channel. */ + KUNIT_EXPECT_FALSE(test, afk_service_supersede(owned, &singleton_audio_ops, + owned->channel)); + /* Only singleton services are superseded. */ + KUNIT_EXPECT_FALSE(test, afk_service_supersede(owned, &reusable_ops, 1)); + afk_service_put(owned); +} + static struct kunit_case afk_service_cases[] = { KUNIT_CASE(afk_service_admission_test), KUNIT_CASE(dptx_service_identity_test), KUNIT_CASE(dptx_service_duplicate_close_test), KUNIT_CASE(afk_service_many_generations_test), + KUNIT_CASE(afk_service_singleton_reannounce_test), KUNIT_CASE(afk_service_reader_pin_test), KUNIT_CASE(afk_service_pending_reply_test), KUNIT_CASE(afk_service_completed_reader_test), diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index 724a78c4bb93c6..10e3586487a9d8 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -83,6 +83,18 @@ void afk_service_retry(struct apple_dcp_afkep *ep) } EXPORT_SYMBOL_IF_KUNIT(afk_service_retry); +/* How long the host waits for the firmware: the processor's own, or one second. */ +static unsigned int afk_timeout_ms(struct apple_dcp_afkep *ep) +{ + return ep->dcp->hw.afk_timeout_ms ?: MSEC_PER_SEC; +} + +/* The same for a service the caller may not have; the call fails without one. */ +static unsigned int afk_service_timeout_ms(struct apple_epic_service *service) +{ + return service ? afk_timeout_ms(service->ep) : MSEC_PER_SEC; +} + static void afk_send(struct apple_dcp_afkep *ep, u64 message) { dcp_send_message(ep->dcp, ep->endpoint, message); @@ -115,7 +127,8 @@ struct apple_dcp_afkep *afk_init(struct apple_dcp *dcp, u32 endpoint, afkep->ops = ops; afkep->dcp = dcp; - afkep->wire_v2 = dcp->fw_compat == DCP_FIRMWARE_V_27_0 || dcp_is_ext26(dcp); + afkep->wire_v2 = dcp->fw_compat == DCP_FIRMWARE_V_27_0 || dcp_is_ext26(dcp) || + dcp->hw.afk_v2; afkep->endpoint = endpoint; afkep->wq = alloc_ordered_workqueue("apple-dcp-afkep%02x", WQ_MEM_RECLAIM, endpoint); @@ -168,6 +181,9 @@ void afk_quiesce(struct apple_dcp_afkep *afkep) destroy_workqueue(afkep->tx_wq); afkep->tx_wq = NULL; } + /* Drain any external TX sender that passed stopping before it was set. */ + mutex_lock(&afkep->tx_lock); + mutex_unlock(&afkep->tx_lock); kvfree(afkep->compact_rx_data); afkep->compact_rx_data = NULL; for (i = 0; i < afkep->num_channels; i++) @@ -184,7 +200,8 @@ void afk_shutdown(struct apple_dcp_afkep *afkep) afk_send(afkep, FIELD_PREP(RBEP_TYPE, RBEP_SHUTDOWN)); int ret; - ret = wait_for_completion_timeout(&afkep->stopped, msecs_to_jiffies(1000)); + ret = wait_for_completion_timeout(&afkep->stopped, + msecs_to_jiffies(afk_timeout_ms(afkep))); if (ret <= 0) { dev_err(afkep->dcp->dev, "Timed out shutting down AFK endpoint %02x", afkep->endpoint); } @@ -235,6 +252,36 @@ static int afk_start_polled(struct apple_dcp_afkep *ep) return -ETIMEDOUT; } +/* + * An endpoint the bootloader left running (afk_live_endpoints): an INIT + * on a live endpoint asserts in the firmware. Stop it and wait for the + * acknowledgment first. Its old ring stays with the bootloader, which + * keeps it reserved. + */ +static int afk_stop_live(struct apple_dcp_afkep *ep) +{ + u32 bit; + + if (ep->endpoint < 0x20 || ep->endpoint >= 0x40) + return 0; + bit = BIT(ep->endpoint - 0x20); + if (!(ep->dcp->afk_live_endpoints & bit)) + return 0; + reinit_completion(&ep->stopped); + afk_send(ep, FIELD_PREP(RBEP_TYPE, RBEP_SHUTDOWN)); + if (!wait_for_completion_timeout(&ep->stopped, + msecs_to_jiffies(afk_timeout_ms(ep)))) { + dev_err(ep->dcp->dev, "AFK[ep:%02x]: inherited endpoint did not stop\n", + ep->endpoint); + return -ETIMEDOUT; + } + reinit_completion(&ep->stopped); + ep->dcp->afk_live_endpoints &= ~bit; + dev_info(ep->dcp->dev, "AFK[ep:%02x]: inherited endpoint stopped\n", + ep->endpoint); + return 0; +} + int afk_start(struct apple_dcp_afkep *ep) { int ret; @@ -248,6 +295,16 @@ int afk_start(struct apple_dcp_afkep *ep) } reinit_completion(&ep->started); + /* + * An adopted session's endpoint map went to the bootloader, and RTKit + * starts only endpoints it knows. Registered before anything is sent, + * the endpoint's replies are not reported as an unknown endpoint's. + */ + if (ep->dcp->hw.afk_adopt_endpoints) + apple_rtkit_adopt_ep(ep->dcp->rtk, ep->endpoint); + ret = afk_stop_live(ep); + if (ret) + return ret; ret = apple_rtkit_start_ep(ep->dcp->rtk, ep->endpoint); if (ret) return ret; @@ -256,7 +313,8 @@ int afk_start(struct apple_dcp_afkep *ep) return afk_start_polled(ep); afk_send(ep, FIELD_PREP(RBEP_TYPE, RBEP_INIT)); - ret = wait_for_completion_timeout(&ep->started, msecs_to_jiffies(1000)); + ret = wait_for_completion_timeout(&ep->started, + msecs_to_jiffies(afk_timeout_ms(ep))); if (ret <= 0 && ep->dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL) dev_warn(ep->dcp->dev, @@ -596,8 +654,11 @@ static int afk_send_compact_fragment(struct apple_dcp_afkep *ep, u16 intf_id, void *message; size_t message_size, advance; u32 rptr, wptr, old_wptr; + u64 doorbell; int ret = 0; + lockdep_assert_held(&ep->tx_lock); + if (!ep->txbfr.ready || !ep->txbfr.stride) return -EIO; @@ -679,10 +740,15 @@ static int afk_send_compact_fragment(struct apple_dcp_afkep *ep, u16 intf_id, dma_wmb(); WRITE_ONCE(*ep->txbfr.wptr, cpu_to_le32(wptr)); dma_wmb(); + doorbell = FIELD_PREP(RBEP_TYPE, RBEP_RECV) | + ((u64)(rptr & 0xffff) << 32) | + ((u64)(wptr & 0xffff) << 16) | (old_wptr & 0xffff); + spin_unlock_irqrestore(&ep->lock, flags); + /* The firmware's own client rings with RECV and both pointers. */ - afk_send(ep, FIELD_PREP(RBEP_TYPE, RBEP_RECV) | - ((u64)(rptr & 0xffff) << 32) | - ((u64)(wptr & 0xffff) << 16) | (old_wptr & 0xffff)); + afk_send(ep, doorbell); + kfree(message); + return 0; out_unlock: spin_unlock_irqrestore(&ep->lock, flags); @@ -719,7 +785,7 @@ static int afk_send_compact(struct apple_dcp_afkep *ep, u16 intf_id, u8 type, if (payload_size) memcpy(sub + 1, payload, payload_size); - mutex_lock(&ep->compact_tx_lock); + mutex_lock(&ep->tx_lock); deadline = jiffies + msecs_to_jiffies(5000); while (offset < total) { chunk = min_t(size_t, total - offset, AFK_COMPACT_FRAGMENT_SIZE); @@ -747,7 +813,7 @@ static int afk_send_compact(struct apple_dcp_afkep *ep, u16 intf_id, u8 type, /* Never start a new header into an unfinished remote assembly. */ if (ret && offset) afk_compact_tx_desync(ep, ret); - mutex_unlock(&ep->compact_tx_lock); + mutex_unlock(&ep->tx_lock); kvfree(body); return ret; } @@ -971,6 +1037,7 @@ static void afk_recv_handle_compact_init(struct apple_dcp_afkep *ep, if (ops->init) ops->init(service, service_name, service_name, unit); + wake_up_all(&ep->service_wq); dev_info(ep->dcp->dev, "AFK[ep:%02x]: new compact service %s on interface %u%s\n", @@ -1116,6 +1183,43 @@ struct afk_compact_reply { u8 data[]; }; +/* + * Replies wait on the transmit queue for ring space that only the firmware + * frees, while the receive worker keeps taking calls, so what is queued + * needs a limit of its own. One message is at most AFK_COMPACT_MESSAGE_MAX + * bytes and the receive side assembles one at a time; the queued replies + * together get the same room. A reply is never larger than its call, so + * any single call fits when nothing else is queued, and the calls the + * firmware makes are a small fraction of that even in a burst. + */ +static bool afk_compact_reply_reserve(struct apple_dcp_afkep *ep, size_t size) +{ + guard(spinlock_irqsave)(&ep->lock); + if (size > AFK_COMPACT_MESSAGE_MAX || + ep->compact_reply_bytes > AFK_COMPACT_MESSAGE_MAX - size) + return false; + ep->compact_reply_bytes += size; + return true; +} + +static void afk_compact_reply_release(struct apple_dcp_afkep *ep, size_t size) +{ + guard(spinlock_irqsave)(&ep->lock); + ep->compact_reply_bytes -= size; +} + +/* + * A call that gets no reply leaves the firmware waiting on it, so a + * coordinated sleep must not run against it afterwards. + */ +static void afk_compact_call_unanswered(struct apple_dcp_afkep *ep) +{ + if (!ep->dcp->v27_sleep_transport) + return; + guard(spinlock_irqsave)(&ep->lock); + ep->sleep_poisoned = true; +} + static void afk_compact_reply_worker(struct work_struct *work) { struct afk_compact_reply *r = container_of(work, struct afk_compact_reply, work); @@ -1127,10 +1231,9 @@ static void afk_compact_reply_worker(struct work_struct *work) dev_err(r->ep->dcp->dev, "AFK[ep:%02x]: failed to reply to compact service call: %d\n", r->ep->endpoint, ret); - if (ret && r->ep->dcp->v27_sleep_transport) { - guard(spinlock_irqsave)(&r->ep->lock); - r->ep->sleep_poisoned = true; - } + if (ret) + afk_compact_call_unanswered(r->ep); + afk_compact_reply_release(r->ep, r->size); atomic_dec_return_release(&r->ep->sleep_jobs); kvfree(r); } @@ -1167,9 +1270,19 @@ static void afk_recv_handle_compact_call(struct apple_dcp_afkep *ep, group = le16_to_cpu(call->group); command = le32_to_cpu(call->command); + if (!afk_compact_reply_reserve(ep, payload_size)) { + dev_warn_ratelimited(ep->dcp->dev, + "AFK[ep:%02x]: too many replies queued, dropping compact service %u call %u:%u\n", + ep->endpoint, channel, group, command); + afk_compact_call_unanswered(ep); + return; + } r = kvzalloc(struct_size(r, data, payload_size), GFP_KERNEL); - if (!r) + if (!r) { + afk_compact_reply_release(ep, payload_size); + afk_compact_call_unanswered(ep); return; + } INIT_WORK(&r->work, afk_compact_reply_worker); r->ep = ep; r->channel = channel; @@ -1543,15 +1656,16 @@ int afk_v27_sleep_control(struct apple_dcp_afkep *ep, bool open) ret = afk_v27_sleep_check(ep); if (ret) return ret; + mutex_lock(&ep->tx_lock); spin_lock_irqsave(&ep->lock, flags); /* A callback reply may have failed since the inventory check. */ if (ep->stopping || ep->sleep_poisoned || ep->sleep_waiting) { ret = -EBUSY; - goto out; + goto out_tx_unlock; } if (ep->sleep_closed == !open) { ret = -EALREADY; - goto out; + goto out_tx_unlock; } dma_rmb(); rptr = le32_to_cpu(READ_ONCE(*ep->txbfr.rptr)); @@ -1562,7 +1676,7 @@ int afk_v27_sleep_control(struct apple_dcp_afkep *ep, bool open) ep->txbfr.bufsz % ep->txbfr.stride || ep->txbfr.bufsz - wptr < sizeof(*hdr)) { ret = -EPROTO; - goto out; + goto out_tx_unlock; } /* Use the existing dummy-header wrap format and keep one slot empty. */ next = ALIGN(wptr + sizeof(*hdr) + sizeof(payload), ep->txbfr.stride); @@ -1573,7 +1687,7 @@ int afk_v27_sleep_control(struct apple_dcp_afkep *ep, bool open) if ((wptr < rptr && next >= rptr) || (wptr >= rptr && next <= wptr && next >= rptr)) { ret = -EAGAIN; - goto out; + goto out_tx_unlock; } hdr = ep->txbfr.buf + wptr; hdr->magic = cpu_to_le32(QE_MAGIC); @@ -1599,6 +1713,7 @@ int afk_v27_sleep_control(struct apple_dcp_afkep *ep, bool open) FIELD_PREP(RBEP_TYPE, RBEP_RECV) | (u64)rptr << 32 | (u64)next << 16 | old, NULL, true); spin_unlock_irqrestore(&ep->lock, flags); + mutex_unlock(&ep->tx_lock); if (!ret && !wait_for_completion_timeout(&ep->sleep_done, msecs_to_jiffies(250))) ret = -ETIMEDOUT; @@ -1607,9 +1722,13 @@ int afk_v27_sleep_control(struct apple_dcp_afkep *ep, bool open) ep->sleep_poisoned = true; ep->sleep_waiting = false; } - out: spin_unlock_irqrestore(&ep->lock, flags); return ret; + +out_tx_unlock: + spin_unlock_irqrestore(&ep->lock, flags); + mutex_unlock(&ep->tx_lock); + return ret; } /* Pending identities are owned only by the ordered endpoint workqueue. */ @@ -1660,6 +1779,7 @@ static void afk_retry_service_init(struct apple_dcp_afkep *ep) if (ops->init) ops->init(service, service->pending_name, service->pending_class, service->pending_unit); + wake_up_all(&ep->service_wq); if (service->enabled) afk_populate_service_debugfs(service); kfree(service->pending_name); @@ -1741,7 +1861,7 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, * EPICProviderClass was used. If the init call has props parse them and * use EPICProviderClass to match the service. */ - if (props_size > 36) { + if (props_size > 36 && !ep->dcp->hw.afk_announced_names) { int ret = parse(props, props_size, &ctx); if (ret) { dev_err(ep->dcp->dev, @@ -1786,8 +1906,17 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, service_name = epic_class; } } else { - service_name = name; - } + service_name = name; + /* + * hw.afk_announced_names: the announced name is the service's + * identity, and its handler gets it as the EPIC name. + */ + if (ep->dcp->hw.afk_announced_names) { + epic_name = kstrdup(name, GFP_KERNEL); + if (!epic_name) + return; + } + } if (ep->match_epic_name) ops = afk_match_service(ep, epic_name); @@ -1810,6 +1939,8 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, if (!ops && dcp_is_ext26(ep->dcp) && ep->ops && !strcmp(ep->ops->name, "native26-observer")) ops = ep->ops; + if (!ops) + ops = ep->unmatched_ops; if (!ops) { dev_err(ep->dcp->dev, "AFK[ep:%02x]: unable to match service %s on channel %d\n", @@ -1881,12 +2012,28 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, goto free; } } + /* + * Only an admitted, opened successor retires the instance it + * replaces: a replacement rejected above (no slot, admission or OPEN + * failure) leaves the previous instance usable by its owner. + */ + for (ch_idx = 0; ch_idx < ep->num_channels; ch_idx++) { + struct apple_epic_service *old = &ep->services[ch_idx]; + + if (old != service && afk_service_supersede(old, ops, channel)) { + dev_info(ep->dcp->dev, + "AFK[ep:%02x]: %s on channel %u supersedes channel %u\n", + ep->endpoint, service_name, channel, old->channel); + afk_remove_service_debugfs(old); + } + } if (ops->prepare) afk_service_publish(service); if (ops->init_props) ops->init_props(service, epic_unit, props, props_size); if (ops->init) ops->init(service, epic_name, epic_class, epic_unit); + wake_up_all(&ep->service_wq); dev_info(ep->dcp->dev, "AFK[ep:%02x]: new service %s on channel %d\n", ep->endpoint, service_name, channel); @@ -2921,6 +3068,7 @@ static int afk_send_epic_token(struct apple_dcp_afkep *ep, u32 channel, u16 tag, } } + mutex_lock(&ep->tx_lock); spin_lock_irqsave(&ep->lock, flags); if (READ_ONCE(ep->dcp->sleep_v27_closed) && ecat != EPIC_CAT_REPLY) { ret = -EBUSY; @@ -3106,12 +3254,17 @@ static int afk_send_epic_token(struct apple_dcp_afkep *ep, u32 channel, u16 tag, /* Publish the completed entry before allowing the consumer to read it. */ dma_wmb(); *ep->txbfr.wptr = cpu_to_le32(wptr); + spin_unlock_irqrestore(&ep->lock, flags); + + /* Keep tx_lock held across the doorbell so ring writes stay ordered. */ afk_send(ep, FIELD_PREP(RBEP_TYPE, RBEP_SEND) | - FIELD_PREP(SEND_WPTR, wptr)); - ret = 0; + FIELD_PREP(SEND_WPTR, wptr)); + mutex_unlock(&ep->tx_lock); + return 0; out: spin_unlock_irqrestore(&ep->lock, flags); + mutex_unlock(&ep->tx_lock); return ret; } @@ -3138,7 +3291,7 @@ int afk_send_command(struct apple_epic_service *service, u8 type, { return afk_send_command_timeout(service, type, payload, payload_len, output, output_len, retcode, - MSEC_PER_SEC); + afk_service_timeout_ms(service)); } static u16 afk_command_tag(struct apple_epic_service *service, u8 slot) @@ -3151,7 +3304,7 @@ static u16 afk_command_tag(struct apple_epic_service *service, u8 slot) if (!ep->wire_v2) return ((service->cmd_tag++ & 0xff) << 8) | slot; - /* Send already nests the endpoint lock below the service lock. */ + /* Endpoint lock nests below the service lock. */ spin_lock_irqsave(&ep->lock, flags); tag = afkv2_command_id(ep->command_tags[service->channel]++, slot); spin_unlock_irqrestore(&ep->lock, flags); @@ -3183,6 +3336,15 @@ int afk_send_command_timeout(struct apple_epic_service *service, u8 type, output, output_len, retcode, timeout_ms, NULL); } +int afk_send_command_len(struct apple_epic_service *service, u8 type, + const void *payload, size_t payload_len, void *output, + size_t output_len, u32 *retcode, size_t *received) +{ + return afk_send_command_timeout_len(service, type, payload, payload_len, + output, output_len, retcode, + afk_service_timeout_ms(service), received); +} + /* * @reply_len (legacy EPIC only): return just the bytes the firmware reported * in its reply instead of the whole allocated output. @@ -3270,11 +3432,20 @@ static int afk_send_command_common(struct apple_epic_service *service, u8 type, goto err_put_service; } - rxbuf = dma_alloc_coherent(ep->dcp->dev, output_len, &rxbuf_dma, - GFP_KERNEL); - if (!rxbuf) { - ret = -ENOMEM; - goto err_put_service; + /* + * A command without output carries no reply buffer: firmware that + * answers some commands with a status alone asserts when it is given + * one, since it then copies an empty reply. + */ + rxbuf = NULL; + rxbuf_dma = 0; + if (output_len) { + rxbuf = dma_alloc_coherent(ep->dcp->dev, output_len, &rxbuf_dma, + GFP_KERNEL); + if (!rxbuf) { + ret = -ENOMEM; + goto err_put_service; + } } txbuf = dma_alloc_coherent(ep->dcp->dev, payload_len, &txbuf_dma, GFP_KERNEL); @@ -3331,6 +3502,7 @@ static int afk_send_command_common(struct apple_epic_service *service, u8 type, service->cmds[idx].done = false; service->cmds[idx].completion = &completion; init_completion(&completion); + spin_unlock_irqrestore(&service->lock, flags); if (ep->inline_v2) { ret = afkv2_encode_inline_command(inline_command, @@ -3347,7 +3519,6 @@ static int afk_send_command_common(struct apple_epic_service *service, u8 type, } kfree(inline_command); inline_command = NULL; - spin_unlock_irqrestore(&service->lock, flags); if (ret) goto err_free_cmd; @@ -3432,7 +3603,7 @@ static int afk_send_command_common(struct apple_epic_service *service, u8 type, if (!dcp_is_ext26(ep->dcp)) dma_free_coherent(ep->dcp->dev, payload_len, txbuf, txbuf_dma); err_free_rxbuf: - if (!dcp_is_ext26(ep->dcp)) + if (rxbuf && !dcp_is_ext26(ep->dcp)) dma_free_coherent(ep->dcp->dev, output_len, rxbuf, rxbuf_dma); err_put_service: afk_service_put(service); @@ -3445,7 +3616,7 @@ int afk_service_call(struct apple_epic_service *service, u16 group, u32 command, { return afk_service_call_timeout(service, group, command, data, data_len, data_pad, output, output_len, - output_pad, MSEC_PER_SEC); + output_pad, afk_service_timeout_ms(service)); } int afk_service_call_len(struct apple_epic_service *service, u16 group, @@ -3455,7 +3626,7 @@ int afk_service_call_len(struct apple_epic_service *service, u16 group, { return afk_service_call_timeout_len(service, group, command, data, data_len, data_pad, output, output_len, output_pad, - MSEC_PER_SEC, received); + afk_service_timeout_ms(service), received); } int afk_service_call_timeout(struct apple_epic_service *service, u16 group, @@ -3488,7 +3659,7 @@ int afk_service_call_timeout_len(struct apple_epic_service *service, u16 group, if (!service) return -ENODEV; - bfr = kzalloc(bfr_len, GFP_KERNEL); + bfr = kvzalloc(bfr_len, GFP_KERNEL); if (!bfr) return -ENOMEM; @@ -3558,7 +3729,7 @@ int afk_service_call_timeout_len(struct apple_epic_service *service, u16 group, } out: - kfree(bfr); + kvfree(bfr); return ret; } @@ -3596,7 +3767,7 @@ int afk_service_call_with_reply_len(struct apple_epic_service *service, &bfr_len) || bfr_len > U32_MAX) return -EOVERFLOW; - bfr = kzalloc(bfr_len, GFP_KERNEL); + bfr = kvzalloc(bfr_len, GFP_KERNEL); if (!bfr) return -ENOMEM; @@ -3641,7 +3812,7 @@ int afk_service_call_with_reply_len(struct apple_epic_service *service, } out: - kfree(bfr); + kvfree(bfr); return ret; } diff --git a/drivers/gpu/drm/apple/afk.h b/drivers/gpu/drm/apple/afk.h index b2c7c5deddb29b..df2c292a5e03e7 100644 --- a/drivers/gpu/drm/apple/afk.h +++ b/drivers/gpu/drm/apple/afk.h @@ -83,8 +83,8 @@ struct apple_epic_service { bool started; struct { - struct dentry *entry; - u8 *scratch; + struct dentry *entry; + u8 *scratch; } debugfs; }; @@ -258,6 +258,36 @@ static inline void afk_service_retire_channel(struct apple_epic_service *service spin_unlock_irqrestore(&service->lock, flags); } +/* + * A singleton service has one live instance per endpoint. The firmware + * announces it again on a fresh channel when the display is attached again, + * without closing the previous channel (as for compact services, see + * afk_compact_slot()). Once the instance announced on @channel has been + * admitted, it supersedes @service: retire it, so that its slot is + * reclaimed once its last user lets go. The successor's init takes over + * the service's state. Call this only after the successor holds its own + * slot; a rejected successor must leave @service usable. + */ +static inline bool afk_service_supersede(struct apple_epic_service *service, + const struct apple_epic_service_ops *ops, + u32 channel) +{ + unsigned long flags; + bool superseded; + + if (!ops->singleton) + return false; + spin_lock_irqsave(&service->lock, flags); + superseded = service->ops == ops && !service->torndown && + service->channel != channel; + if (superseded) { + service->enabled = false; + service->torndown = true; + } + spin_unlock_irqrestore(&service->lock, flags); + return superseded; +} + static inline bool afk_service_matches(struct apple_epic_service *service, u32 channel) { @@ -554,6 +584,8 @@ struct apple_dcp_afkep { void *rx_scratch; spinlock_t lock; + /* Serializes TX ring writes and mailbox doorbells outside ep->lock. */ + struct mutex tx_lock; u16 qe_seq; bool stopping; /* lock: no new receive work after shutdown. */ @@ -573,15 +605,23 @@ struct apple_dcp_afkep { bool compact_tx_desync; /* Replies to firmware calls, see afk_compact_reply_worker(). */ struct workqueue_struct *tx_wq; + /* Payload bytes of the replies queued there and not yet sent (lock). */ + size_t compact_reply_bytes; /* Accepted RX and queued replies, until each worker has returned. */ atomic_t sleep_jobs; - struct mutex compact_tx_lock; struct afk_fragment_state compact_rx; void *compact_rx_data; const struct apple_epic_service_ops *ops; + /* + * Bound to an announced service no entry of @ops names, which is then + * opened like a matched one. NULL leaves such a service unopened. + */ + const struct apple_epic_service_ops *unmatched_ops; struct apple_epic_service services[AFK_MAX_CHANNEL]; u32 num_channels; + /* Woken once a service has opened and its init callback has run. */ + wait_queue_head_t service_wq; struct dentry *debugfs_entry; @@ -599,9 +639,10 @@ static inline void afk_ep_init_state(struct apple_dcp_afkep *ep) u32 i; spin_lock_init(&ep->lock); + mutex_init(&ep->tx_lock); INIT_LIST_HEAD(&ep->compact_cmds); init_waitqueue_head(&ep->compact_orphan_wq); - mutex_init(&ep->compact_tx_lock); + init_waitqueue_head(&ep->service_wq); init_completion(&ep->started); init_completion(&ep->stopped); init_completion(&ep->sleep_done); @@ -641,6 +682,13 @@ int afk_send_command_timeout(struct apple_epic_service *service, u8 type, const void *payload, size_t payload_len, void *output, size_t output_len, u32 *retcode, unsigned int timeout_ms); +/* + * As afk_send_command(), and @received is set to the number of bytes of + * @output the reply filled: an AFKv2 reply may be shorter than @output_len. + */ +int afk_send_command_len(struct apple_epic_service *service, u8 type, + const void *payload, size_t payload_len, void *output, + size_t output_len, u32 *retcode, size_t *received); int afk_service_call(struct apple_epic_service *service, u16 group, u32 command, const void *data, size_t data_len, size_t data_pad, void *output, size_t output_len, size_t output_pad); diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 41a3327f47b41a..06e36e3a4a00d6 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -8,10 +8,10 @@ */ #include +#include #include #include #include -#include #include #include #include @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -52,6 +53,7 @@ #include "apple_boot_display.h" #include "apple_resume.h" +#include "dcp-hdr-metadata.h" #include "dcp.h" #include "plane.h" #include "iomfb_m4.h" @@ -73,16 +75,59 @@ struct apple_drm_private { bool s2r_skipped; /* A dark wake left the outputs as the suspend did, for the next resume. */ bool dark_held; - struct notifier_block pm_nb; + /* On apple_drm_pm_list while bound, for the system-sleep notifier. */ + struct list_head pm_node; + /* The notifier's output restore, run outside apple_drm_pm_lock. */ + struct work_struct pm_resume_work; }; static int apple_drm_pm_notify(struct notifier_block *nb, unsigned long action, void *data); +#ifdef CONFIG_PM_SLEEP +static void apple_drm_pm_resume_work(struct work_struct *work); +#endif + +/* + * One system-sleep notifier for every bound display subsystem (and for the + * T8132 external outputs), registered at module init. Registering it from the + * component bind would take the PM notifier chain's rwsem under + * component_mutex, while a PM notifier that takes a lock held around a + * component_add() (as the Apple CIO driver's does with its device lock, which + * it holds while populating the NHI) closes a cycle: component_mutex -> + * pm_chain_head.rwsem -> acio->lock -> component_mutex. + * + * apple_drm_pm_lock is a leaf: it guards apple_drm_pm_list only, and nothing + * else is taken under it. At PM_POST_SUSPEND the notifier queues each + * device's restore (pm_resume_work) on apple_drm_pm_wq under it; the restore + * itself, which takes the hotplug, modeset and DCP locks, runs from the work. + * PM_POST_SUSPEND comes after user space is thawed, as before. The next + * PM_SUSPEND_PREPARE flushes the queue, outside the lock, so a restore never + * overlaps the next suspend, and apple_drm_uninit() cancels its device's + * after taking it off the list. + */ +static DEFINE_MUTEX(apple_drm_pm_lock); +static LIST_HEAD(apple_drm_pm_list); +/* Ordered, so the next suspend's PM_SUSPEND_PREPARE can wait for every restore. */ +static struct workqueue_struct *apple_drm_pm_wq; +/* + * Below the DCPs' own notifiers (dcp_s2r_pm_register(), priority 0), whatever + * the probe order: the chain runs higher priorities first and appends equal + * ones, and a DCP that defers past module init would otherwise come after + * this one. At PM_POST_SUSPEND a DCPEXT's dark-wake firmware restart then + * still finishes before the restore here is queued, and a DCP that refuses + * PM_SUSPEND_PREPARE rolls back only the notifiers before it, as at bind. + */ +static struct notifier_block apple_drm_pm_nb = { + .notifier_call = apple_drm_pm_notify, + .priority = -1, +}; /* Component readiness is later than platform probe/bind. */ static DEFINE_MUTEX(apple_g15_display_lock); static struct device *apple_t6030_display; static struct device *apple_t6031_display; static struct device *apple_t8132_display; +#define APPLE_DRM_PUBLISHED_MAX 8 +static struct device *apple_drm_published[APPLE_DRM_PUBLISHED_MAX]; /* The publication slot of a G15/G16 SoC's internal display subsystem, or NULL. */ static struct device **apple_g15_display_slot(struct device *dev) @@ -166,6 +211,67 @@ int apple_drm_t8132_link_device(struct device *consumer) } EXPORT_SYMBOL_GPL(apple_drm_t8132_link_device); +static int apple_drm_display_publish(struct device *dev) +{ + int free_slot = -1; + int i; + + if (!dev->of_node) + return 0; + guard(mutex)(&apple_g15_display_lock); + for (i = 0; i < ARRAY_SIZE(apple_drm_published); i++) { + if (apple_drm_published[i] == dev) + return 0; + if (apple_drm_published[i] && + apple_drm_published[i]->of_node == dev->of_node) + return -EBUSY; + if (!apple_drm_published[i] && free_slot < 0) + free_slot = i; + } + if (free_slot < 0) + return -ENOSPC; + apple_drm_published[free_slot] = get_device(dev); + return 0; +} + +static void apple_drm_display_withdraw(struct device *dev) +{ + struct device *old = NULL; + int i; + + scoped_guard(mutex, &apple_g15_display_lock) { + for (i = 0; i < ARRAY_SIZE(apple_drm_published); i++) { + if (apple_drm_published[i] == dev) { + old = apple_drm_published[i]; + apple_drm_published[i] = NULL; + break; + } + } + } + put_device(old); +} + +int apple_drm_link_device(struct device *consumer, + const struct device_node *display_node) +{ + struct device_link *link; + int i; + + if (!consumer || !consumer->of_node || !display_node) + return -EINVAL; + guard(mutex)(&apple_g15_display_lock); + for (i = 0; i < ARRAY_SIZE(apple_drm_published); i++) { + if (apple_drm_published[i] && + apple_drm_published[i]->of_node == display_node) { + link = device_link_add(consumer, apple_drm_published[i], + DL_FLAG_AUTOREMOVE_CONSUMER); + return link ? 0 : -EINVAL; + } + } + return -EPROBE_DEFER; +} +EXPORT_SYMBOL_GPL(apple_drm_link_device); + DEFINE_DRM_GEM_DMA_FOPS(apple_fops); #define DART_PAGE_SIZE 16384 @@ -180,6 +286,42 @@ static int apple_drm_gem_dumb_create(struct drm_file *file_priv, return drm_gem_dma_dumb_create_internal(file_priv, drm, args); } +/* + * A T8122 dcpext mirrors framebuffers into its own display DART domain. + * Remove a buffer's mirror before its pages and its DVA are released. + */ +static void apple_drm_gem_free(struct drm_gem_object *gem) +{ + struct drm_crtc *crtc; + + drm_for_each_crtc(crtc, gem->dev) { + if (t8132_ext_crtc(crtc)) + continue; + dcp_fb_unmirror(to_apple_crtc(crtc)->dcp, to_drm_gem_dma_obj(gem)); + } + drm_gem_dma_object_free(gem); +} + +static const struct drm_gem_object_funcs apple_drm_gem_funcs = { + .free = apple_drm_gem_free, + .print_info = drm_gem_dma_object_print_info, + .get_sg_table = drm_gem_dma_object_get_sg_table, + .vmap = drm_gem_dma_object_vmap, + .mmap = drm_gem_dma_object_mmap, + .vm_ops = &drm_gem_dma_vm_ops, +}; + +static struct drm_gem_object *apple_drm_gem_create_object(struct drm_device *drm, + size_t size) +{ + struct drm_gem_dma_object *obj = kzalloc_obj(*obj); + + if (!obj) + return ERR_PTR(-ENOMEM); + obj->base.funcs = &apple_drm_gem_funcs; + return &obj->base; +} + #ifdef CONFIG_DRM_FBDEV_EMULATION static int apple_drm_fbdev_probe(struct drm_fb_helper *helper, struct drm_fb_helper_surface_size *sizes) @@ -241,9 +383,13 @@ static void apple_drm_reset_hdr(struct drm_device *dev) drm_connector_list_iter_begin(dev, &iter); drm_for_each_connector_iter(conn, &iter) { struct drm_connector_state *cs = conn->state; + u8 default_bpc = conn->max_bpc_property ? 12 : 0; if (!cs->crtc || (!cs->hdr_output_metadata && - cs->colorspace == DRM_MODE_COLORIMETRY_DEFAULT)) + cs->colorspace == DRM_MODE_COLORIMETRY_DEFAULT && + cs->color_format == DRM_CONNECTOR_COLOR_FORMAT_AUTO && + cs->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_AUTO && + (!default_bpc || cs->max_requested_bpc == default_bpc))) continue; cs = drm_atomic_get_connector_state(state, conn); if (IS_ERR(cs)) { @@ -253,6 +399,10 @@ static void apple_drm_reset_hdr(struct drm_device *dev) drm_property_blob_put(cs->hdr_output_metadata); cs->hdr_output_metadata = NULL; cs->colorspace = DRM_MODE_COLORIMETRY_DEFAULT; + cs->color_format = DRM_CONNECTOR_COLOR_FORMAT_AUTO; + cs->hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; + if (default_bpc) + cs->max_requested_bpc = default_bpc; changed = true; } drm_connector_list_iter_end(&iter); @@ -300,6 +450,7 @@ static const struct drm_driver apple_drm_driver = { DRM_FBDEV_DMA_DRIVER_OPS, #endif .postclose = apple_drm_postclose, + .gem_create_object = apple_drm_gem_create_object, .name = DRIVER_NAME, .desc = DRIVER_DESC, .major = 1, @@ -777,11 +928,82 @@ static int apple_atomic_commit(struct drm_device *dev, return ret; } +static int apple_atomic_check(struct drm_device *dev, + struct drm_atomic_commit *state) +{ + struct drm_plane *plane; + struct drm_plane_state *old_plane_state, *new_plane_state; + struct drm_crtc *crtc; + struct drm_crtc_state *crtc_state; + int i, ret; + + ret = drm_atomic_helper_check_modeset(dev, state); + if (ret) + return ret; + + /* + * Until a displayed KMS swap retires the boot scanout, pull the CRTC + * and its primary plane into every commit touching that CRTC so a + * cursor- or overlay-only commit replays the intended slot-zero state + * and framebuffer reference inside the atomic transaction. + */ + for_each_oldnew_plane_in_state(state, plane, old_plane_state, + new_plane_state, i) { + struct drm_crtc *targets[2] = { + old_plane_state->crtc, + new_plane_state->crtc, + }; + + for (int t = 0; t < ARRAY_SIZE(targets); t++) { + struct drm_crtc *target = targets[t]; + + if (!target || t8132_ext_crtc(target)) + continue; + if (!dcp_boot_surface_pending(to_apple_crtc(target)->dcp)) + continue; + crtc_state = drm_atomic_get_crtc_state(state, target); + if (IS_ERR(crtc_state)) + return PTR_ERR(crtc_state); + } + } + + for_each_new_crtc_in_state(state, crtc, crtc_state, i) { + struct drm_plane_state *plane_state; + + if (t8132_ext_crtc(crtc) || !crtc->primary) + continue; + if (!crtc_state->enable || !crtc_state->active) + continue; + if (!dcp_boot_surface_pending(to_apple_crtc(crtc)->dcp)) + continue; + + plane_state = drm_atomic_get_plane_state(state, crtc->primary); + if (IS_ERR(plane_state)) + return PTR_ERR(plane_state); + crtc_state->planes_changed = true; + } + + if (dev->mode_config.normalize_zpos) { + ret = drm_atomic_normalize_zpos(dev, state); + if (ret) + return ret; + } + + ret = drm_atomic_helper_check_planes(dev, state); + if (ret) + return ret; + + if (state->legacy_cursor_update) + state->async_update = !drm_atomic_helper_async_check(dev, state); + + return 0; +} + static const struct drm_mode_config_funcs apple_mode_config_funcs = { .atomic_state_alloc = apple_atomic_state_alloc, .atomic_state_clear = apple_atomic_state_clear, .atomic_state_free = apple_atomic_state_free, - .atomic_check = drm_atomic_helper_check, + .atomic_check = apple_atomic_check, .atomic_commit = apple_atomic_commit, .fb_create = drm_gem_fb_create, }; @@ -851,10 +1073,19 @@ static void apple_connector_early_unregister(struct drm_connector *connector) apple_connector_backlight_early_unregister(to_apple_connector(connector)); } +static void apple_connector_reset(struct drm_connector *connector) +{ + drm_atomic_helper_connector_reset(connector); + if (connector->state && connector->max_bpc_property) { + connector->state->max_requested_bpc = 12; + connector->state->max_bpc = 12; + } +} + static const struct drm_connector_funcs apple_connector_funcs = { .fill_modes = drm_helper_probe_single_connector_modes, .destroy = appledrm_connector_cleanup, - .reset = drm_atomic_helper_connector_reset, + .reset = apple_connector_reset, .atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state, .atomic_destroy_state = drm_atomic_helper_connector_destroy_state, .detect = apple_connector_detect, @@ -917,21 +1148,36 @@ static int apple_connector_atomic_check(struct drm_connector *conn, { struct drm_connector_state *old = drm_atomic_get_old_connector_state(state, conn); struct drm_connector_state *new = drm_atomic_get_new_connector_state(state, conn); + const struct drm_property_blob *blob = new->hdr_output_metadata; struct drm_crtc_state *crtc_state; - if (!new->crtc || (old->colorspace == new->colorspace && - drm_connector_atomic_hdr_metadata_equal(old, new))) + if (blob && (blob->length != sizeof(struct hdr_output_metadata) || + !dcp_hdr_is_type1(blob->data))) + return -EINVAL; + + if (!new->crtc) + return 0; + if (old->colorspace == new->colorspace && + old->color_format == new->color_format && + old->hdmi.broadcast_rgb == new->hdmi.broadcast_rgb && + old->max_requested_bpc == new->max_requested_bpc && + drm_connector_atomic_hdr_metadata_equal(old, new)) return 0; crtc_state = drm_atomic_get_crtc_state(state, new->crtc); if (IS_ERR(crtc_state)) return PTR_ERR(crtc_state); /* - * The output colour element follows the EOTF and colorspace, so a - * change of either is a mode set. Where the firmware takes HDR10 - * static metadata on a live link, a new block alone is sent with this - * commit's flush (dcp_hdr_metadata_sync()) and the colour mode stays. + * The output colour element follows EOTF, colorspace, format, range + * and bit depth, so changing any of them requires a mode set. Where + * the firmware takes HDR10 static metadata on a live link, updating + * the metadata payload alone is sent with this commit's flush + * (dcp_hdr_metadata_sync()) and the colour mode stays. */ - if (old->colorspace == new->colorspace && old->crtc == new->crtc && + if (old->colorspace == new->colorspace && + old->color_format == new->color_format && + old->hdmi.broadcast_rgb == new->hdmi.broadcast_rgb && + old->max_requested_bpc == new->max_requested_bpc && + old->crtc == new->crtc && apple_connector_eotf(old) == apple_connector_eotf(new) && to_apple_connector(conn)->dcp && dcp_hdr_metadata_live(to_apple_connector(conn)->dcp)) @@ -981,28 +1227,65 @@ static int apple_connector_attach_pq_reference(struct drm_connector *connector) } /* - * External displays can take a PQ BT.2020 signal where the firmware - * offers one, and a desktop 26.x panel PQ content it shows as EDR; - * dcp_crtc_atomic_check() refuses it elsewhere. + * External displays expose the colour properties backed by DCP's per-timing + * ColorModes catalogue (Colorspace, HDR_OUTPUT_METADATA, Broadcast RGB, + * color format, max bpc); dcp_crtc_atomic_check() validates each request + * against the active timing's catalogue. An internal panel with EDR + * headroom (dcp_panel_edr()) exposes Colorspace (BT2020_RGB), + * HDR_OUTPUT_METADATA and PQ_REFERENCE_LUMINANCE; an SDR panel offers no + * HDR at all. */ static int apple_connector_attach_hdr(struct drm_connector *connector, - bool panel_edr) -{ - const u32 colorspaces = BIT(DRM_MODE_COLORIMETRY_BT2020_RGB); + bool panel_edr, bool ext_color_props) +{ + static const u32 panel_colorspaces = BIT(DRM_MODE_COLORIMETRY_BT2020_RGB); + static const u32 hdmi_colorspaces = + BIT(DRM_MODE_COLORIMETRY_SMPTE_170M_YCC) | + BIT(DRM_MODE_COLORIMETRY_BT709_YCC) | + BIT(DRM_MODE_COLORIMETRY_XVYCC_601) | + BIT(DRM_MODE_COLORIMETRY_XVYCC_709) | + BIT(DRM_MODE_COLORIMETRY_SYCC_601) | + BIT(DRM_MODE_COLORIMETRY_OPYCC_601) | + BIT(DRM_MODE_COLORIMETRY_OPRGB) | + BIT(DRM_MODE_COLORIMETRY_BT2020_CYCC) | + BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) | + BIT(DRM_MODE_COLORIMETRY_BT2020_YCC) | + BIT(DRM_MODE_COLORIMETRY_DCI_P3_RGB_D65) | + BIT(DRM_MODE_COLORIMETRY_DCI_P3_RGB_THEATER); + static const u32 dp_colorspaces = + BIT(DRM_MODE_COLORIMETRY_RGB_WIDE_FIXED) | + BIT(DRM_MODE_COLORIMETRY_RGB_WIDE_FLOAT) | + BIT(DRM_MODE_COLORIMETRY_OPRGB) | + BIT(DRM_MODE_COLORIMETRY_DCI_P3_RGB_D65) | + BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) | + BIT(DRM_MODE_COLORIMETRY_BT601_YCC) | + BIT(DRM_MODE_COLORIMETRY_BT709_YCC) | + BIT(DRM_MODE_COLORIMETRY_XVYCC_601) | + BIT(DRM_MODE_COLORIMETRY_XVYCC_709) | + BIT(DRM_MODE_COLORIMETRY_SYCC_601) | + BIT(DRM_MODE_COLORIMETRY_OPYCC_601) | + BIT(DRM_MODE_COLORIMETRY_BT2020_CYCC) | + BIT(DRM_MODE_COLORIMETRY_BT2020_YCC); + static const unsigned long ext_color_formats = + BIT(DRM_OUTPUT_COLOR_FORMAT_RGB444) | + BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444) | + BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422) | + BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR420); int ret; switch (connector->connector_type) { case DRM_MODE_CONNECTOR_eDP: if (!panel_edr) return 0; - fallthrough; + ret = drm_mode_create_dp_colorspace_property(connector, panel_colorspaces); + break; /* A desktop 26.x Type-C route is a pipeline output carrying DisplayPort. */ case DRM_MODE_CONNECTOR_USB: case DRM_MODE_CONNECTOR_DisplayPort: - ret = drm_mode_create_dp_colorspace_property(connector, colorspaces); + ret = drm_mode_create_dp_colorspace_property(connector, dp_colorspaces); break; case DRM_MODE_CONNECTOR_HDMIA: - ret = drm_mode_create_hdmi_colorspace_property(connector, colorspaces); + ret = drm_mode_create_hdmi_colorspace_property(connector, hdmi_colorspaces); break; default: return 0; @@ -1015,7 +1298,20 @@ static int apple_connector_attach_hdr(struct drm_connector *connector, drm_connector_attach_hdr_output_metadata_property(connector); if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) return apple_connector_attach_pq_reference(connector); - return 0; + if (!ext_color_props) + return 0; + ret = drm_connector_attach_broadcast_rgb_property(connector); + if (ret) + return ret; + ret = drm_connector_attach_color_format_property(connector, ext_color_formats); + if (ret) + return ret; + /* drm_connector_attach_max_bpc_property() populates connector->state. */ + if (!connector->state) + apple_connector_reset(connector); + if (!connector->state) + return -ENOMEM; + return drm_connector_attach_max_bpc_property(connector, 8, 12); } static const struct drm_crtc_helper_funcs apple_crtc_helper_funcs = { @@ -1057,8 +1353,8 @@ static int apple_connector_create(struct drm_device *drm, ret = drm_connector_attach_vrr_capable_property(&connector->base); if (ret) goto err_cleanup; - ret = apple_connector_attach_hdr(&connector->base, - dcp_fw_compat_panel_edr(dcp)); + ret = apple_connector_attach_hdr(&connector->base, dcp_panel_edr(dcp), + dcp_ext_color_props_supported(dcp)); if (ret) goto err_cleanup; @@ -1268,9 +1564,10 @@ static int apple_probe_per_dcp(struct device *dev, * Type-C connector any of whose pipelines is native26 offers no BT.2020/PQ * output contract. Every other pipeline has a 10-bit primary. */ -static bool apple_typec_port_rgb8_only(struct platform_device **dcp, int num_dcp, - struct platform_device *pipeline, - unsigned int port_idx) +VISIBLE_IF_KUNIT bool apple_typec_port_rgb8_only(struct platform_device **dcp, + int num_dcp, + struct platform_device *pipeline, + unsigned int port_idx) { int i; @@ -1288,6 +1585,24 @@ static bool apple_typec_port_rgb8_only(struct platform_device **dcp, int num_dcp return false; } +static bool apple_typec_port_color_props(struct platform_device **dcp, + int num_dcp, + struct platform_device *pipeline, + unsigned int port_idx) +{ + int i; + + for (i = 0; i < num_dcp; i++) { + if (pipeline && dcp[i] != pipeline) + continue; + if (!dcp_typec_port_has_candidate(port_idx, dcp[i])) + continue; + if (dcp_ext_color_props_supported(dcp[i])) + return true; + } + return false; +} + /* * Create a connector per physical Type-C port and attach it to every * pipeline that can drive it. The M2 Pro/Max laptops append a second @@ -1390,7 +1705,12 @@ static int apple_probe_typec_ports(struct drm_device *drm, * intact; its capabilities are not the pipeline's. */ if (!apple_typec_port_rgb8_only(dcp, num_dcp, pipeline, port_idx)) { - ret = apple_connector_attach_hdr(&connector->base, false); + bool color_props = apple_typec_port_color_props(dcp, num_dcp, + pipeline, + port_idx); + + ret = apple_connector_attach_hdr(&connector->base, false, + color_props); if (ret) return ret; } @@ -1503,6 +1823,8 @@ static const struct of_device_id apple_dcp_id_tbl[] = { #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8132) { .compatible = "apple,t8132-dcp" }, #endif + /* apple_dcp_usable(): only one on firmware 27.2 (apple_t8132_dcpext_v27_2()). */ + { .compatible = "apple,t8132-dcpext" }, {}, }; @@ -1521,7 +1843,21 @@ static bool apple_dcp_usable(struct device_node *np) dcp_h17p_external_supported(np)) && /* t6041_dcpext=0 keeps the T6041 external processors out. */ (!of_device_is_compatible(np, "apple,t6041-dcpext") || - dcp_t6041_ext_enabled()); + dcp_t6041_ext_enabled()) && + /* + * The T8132 main DCP is the M4 backend's on its 26.6.2 + * firmware path, and the firmware-27 backend's wherever the + * boot loader handed it over with the 27.2 image and its + * clocks, on any board (see dcp_check_firmware_version()). + */ + (!of_device_is_compatible(np, "apple,t8132-dcp") || + apple_t8132_firmware_path() || apple_t8132_dcp_v27_2(np)) && + /* + * A T8132 dcpext the M4 backend adopts is no component: its + * outputs are t8132_ext_drm.c's. One on the 27.2 image is a pipe. + */ + (!of_device_is_compatible(np, "apple,t8132-dcpext") || + apple_t8132_dcpext_v27_2(np)); } static void apple_drm_quiesce_connectors(struct drm_device *drm) @@ -1547,6 +1883,22 @@ static void apple_drm_quiesce_connectors(struct drm_device *drm) drm_connector_list_iter_end(&iter); } +/* Process the hotplug reports queued while the display processors started. */ +static void apple_drm_flush_start_reports(struct drm_device *drm) +{ + struct drm_connector_list_iter iter; + struct drm_connector *connector; + + drm_connector_list_iter_begin(drm, &iter); + drm_for_each_connector_iter(connector, &iter) { + /* A T8132 external output has no DCP hotplug work. */ + if (t8132_ext_connector(connector)) + continue; + flush_work(&to_apple_connector(connector)->hotplug_wq); + } + drm_connector_list_iter_end(&iter); +} + /* * Each display processor runs its own RTKit firmware, and starting one waits * for its firmware: a T6041 external processor takes 0.6 to 1.6 s to bring up @@ -1704,8 +2056,12 @@ static int apple_drm_init_dcp(struct device *dev) return -ENODEV; } - /* HACK: Wait for dcp* to settle before a modeset */ - msleep(100); + /* + * What the firmware reported while its processor started (connection, + * modes) is processed before the device registers, so the first + * modeset sees it. Later reports arrive as hotplug events. + */ + apple_drm_flush_start_reports(&apple->drm); return 0; } @@ -1737,6 +2093,10 @@ static int apple_drm_init(struct device *dev) if (IS_ERR(apple)) return PTR_ERR(apple); + INIT_LIST_HEAD(&apple->pm_node); +#ifdef CONFIG_PM_SLEEP + INIT_WORK(&apple->pm_resume_work, apple_drm_pm_resume_work); +#endif dev_set_drvdata(dev, apple); ret = drmm_mode_config_init(&apple->drm); @@ -1878,9 +2238,17 @@ static int apple_drm_init(struct device *dev) drm_dev_unregister(&apple->drm); goto err_unbind; } + ret = apple_drm_display_publish(dev); + if (ret) { + apple_g15_display_withdraw(dev); + t8132_ext_drm_fini(&apple->drm); + drm_dev_unregister(&apple->drm); + goto err_unbind; + } - apple->pm_nb.notifier_call = apple_drm_pm_notify; - register_pm_notifier(&apple->pm_nb); + mutex_lock(&apple_drm_pm_lock); + list_add_tail(&apple->pm_node, &apple_drm_pm_list); + mutex_unlock(&apple_drm_pm_lock); return 0; @@ -1899,13 +2267,19 @@ static void apple_drm_uninit(struct device *dev) { struct apple_drm_private *apple = dev_get_drvdata(dev); + apple_drm_display_withdraw(dev); apple_g15_display_withdraw(dev); /* An aborted takeover leaves its DCPs running until the reboot. */ if (apple->aborted) return; - unregister_pm_notifier(&apple->pm_nb); + mutex_lock(&apple_drm_pm_lock); + list_del_init(&apple->pm_node); + mutex_unlock(&apple_drm_pm_lock); +#ifdef CONFIG_PM_SLEEP + cancel_work_sync(&apple->pm_resume_work); +#endif /* Before anything of the DRM device is torn down. */ t8132_ext_drm_fini(&apple->drm); @@ -1929,7 +2303,7 @@ static void apple_drm_unbind(struct device *dev) apple_drm_uninit(dev); } -const struct component_master_ops apple_drm_ops = { +static const struct component_master_ops apple_drm_ops = { .bind = apple_drm_bind, .unbind = apple_drm_unbind, }; @@ -2052,10 +2426,23 @@ static int apple_platform_suspend(struct device *dev) if (apple && apple->dark_held) return 0; + if (pm_suspend_via_firmware()) { + int ret = dcp_t6041_s2r_all(false); + + if (ret) + return ret; + } + if (apple && !apple->aborted) { apple->s2r_skipped = apple_drm_firmware_stopped(apple); - if (!apple->s2r_skipped) - return drm_mode_config_helper_suspend(&apple->drm); + if (!apple->s2r_skipped) { + int ret = drm_mode_config_helper_suspend(&apple->drm); + + if (ret) { + dcp_t6041_s2r_all(true); + return ret; + } + } } return 0; @@ -2103,6 +2490,10 @@ static int apple_platform_resume(struct device *dev) { struct apple_drm_private *apple = dev_get_drvdata(dev); + /* Nothing if this suspend never took the display down. */ + if (dcp_t6041_s2r_all(true)) + dev_err(dev, "T6041 S2R display resume failed\n"); + if (!apple || apple->aborted || apple->s2r_skipped) return 0; @@ -2126,17 +2517,43 @@ static void apple_platform_complete(struct device *dev) apple_drm_resume_outputs(apple); } -/* It failed before ->prepare() reached this device, so ->complete() didn't run either. */ -static int apple_drm_pm_notify(struct notifier_block *nb, unsigned long action, void *data) +/* + * Queued at PM_POST_SUSPEND: the sleep failed before ->prepare() reached this + * device, so ->complete() didn't run either. + */ +static void apple_drm_pm_resume_work(struct work_struct *work) { - struct apple_drm_private *apple = container_of(nb, struct apple_drm_private, pm_nb); + struct apple_drm_private *apple = + container_of(work, struct apple_drm_private, pm_resume_work); - if (action == PM_POST_SUSPEND && apple->dark_held) { + if (apple->dark_held) { dev_warn(apple->drm.dev, "dark wake over without a resume: outputs back now\n"); apple_drm_resume_outputs(apple); } +} - return NOTIFY_DONE; +static int apple_drm_pm_notify(struct notifier_block *nb, unsigned long action, void *data) +{ + struct apple_drm_private *apple; + int ret; + + /* No restore queued by the last PM_POST_SUSPEND overlaps the next transition. */ + if (action == PM_SUSPEND_PREPARE || action == PM_HIBERNATION_PREPARE || + action == PM_RESTORE_PREPARE) + flush_workqueue(apple_drm_pm_wq); + + /* The T8132 external outputs' sleep handling (a no-op without them). */ + ret = t8132_ext_drm_pm_event(action); + if (action != PM_POST_SUSPEND) + return ret; + + mutex_lock(&apple_drm_pm_lock); + list_for_each_entry(apple, &apple_drm_pm_list, pm_node) + if (apple->dark_held) + queue_work(apple_drm_pm_wq, &apple->pm_resume_work); + mutex_unlock(&apple_drm_pm_lock); + + return ret; } static const struct dev_pm_ops apple_platform_pm_ops = { @@ -2187,9 +2604,21 @@ static int __init appledrm_register(void) ret = dcp_register(); if (ret) goto unregister_audio; + apple_drm_pm_wq = alloc_ordered_workqueue("appledrm-pm", 0); + if (!apple_drm_pm_wq) { + ret = -ENOMEM; + goto unregister_dcp; + } + ret = register_pm_notifier(&apple_drm_pm_nb); + if (ret) + goto destroy_wq; ret = platform_driver_register(&apple_platform_driver); if (!ret) return 0; + unregister_pm_notifier(&apple_drm_pm_nb); +destroy_wq: + destroy_workqueue(apple_drm_pm_wq); +unregister_dcp: dcp_unregister(); unregister_audio: apple_j613_display_fail(); @@ -2207,6 +2636,8 @@ static void __exit appledrm_unregister(void) #endif dcp_unregister(); platform_driver_unregister(&apple_platform_driver); + unregister_pm_notifier(&apple_drm_pm_nb); + destroy_workqueue(apple_drm_pm_wq); } module_init(appledrm_register); diff --git a/drivers/gpu/drm/apple/audio-legacy-test.c b/drivers/gpu/drm/apple/audio-legacy-test.c new file mode 100644 index 00000000000000..99249c702a36d5 --- /dev/null +++ b/drivers/gpu/drm/apple/audio-legacy-test.c @@ -0,0 +1,401 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by audio.c: on the legacy (pre-14.7) audio service a stopped + * stream keeps its runtime PM reference until sync_stop has waited for the + * DMA terminate, a failed START leaves exactly one reference to put, and the + * element catalog is asked for with the full 256 KiB capacity. + * The production trigger and sync_stop run; the audio service's link calls + * and the DMA channel are stubbed. + */ +#include +#include +#include + +struct dcpaud_legacy_test { + struct dma_device dma; + struct dma_chan channel; + struct dma_async_tx_descriptor desc; + char sequence[32]; + unsigned int nsequence; + /* The runtime PM usage count when the terminate was waited for */ + int usage_at_drain; + int startlink_err; + /* The published service instance, as dcp_audiosrv_instance() reports it */ + u64 instance; + size_t elements_asked; + size_t catalog; + struct device *dev; +}; + +static struct dcpaud_legacy_test *dcpaud_legacy_current; + +static void dcpaud_legacy_record(char step) +{ + struct dcpaud_legacy_test *t = dcpaud_legacy_current; + + if (t->nsequence < sizeof(t->sequence) - 1) + t->sequence[t->nsequence++] = step; +} + +static int dcpaud_legacy_terminate(struct dma_chan *chan) +{ + dcpaud_legacy_record('X'); + return 0; +} + +static void dcpaud_legacy_drain(struct dma_chan *chan) +{ + struct dcpaud_legacy_test *t = dcpaud_legacy_current; + + t->usage_at_drain = atomic_read(&t->dev->power.usage_count); + dcpaud_legacy_record('D'); +} + +static dma_cookie_t dcpaud_legacy_submit(struct dma_async_tx_descriptor *tx) +{ + return 1; +} + +static struct dma_async_tx_descriptor * +dcpaud_legacy_prep(struct dma_chan *chan, dma_addr_t buf, size_t len, size_t period, + enum dma_transfer_direction dir, unsigned long flags) +{ + struct dcpaud_legacy_test *t = dcpaud_legacy_current; + + dcpaud_legacy_record('Q'); + t->desc.chan = chan; + t->desc.tx_submit = dcpaud_legacy_submit; + return &t->desc; +} + +static void dcpaud_legacy_issue(struct dma_chan *chan) +{ +} + +static enum dma_status dcpaud_legacy_status(struct dma_chan *chan, dma_cookie_t cookie, + struct dma_tx_state *state) +{ + return DMA_COMPLETE; +} + +static int dcpaud_legacy_startlink(struct device *dev, struct dcp_sound_cookie *cookie, u64 *gen) +{ + if (gen) + *gen = dcpaud_legacy_current->instance; + dcpaud_legacy_record('T'); + return dcpaud_legacy_current->startlink_err; +} + +static int dcpaud_legacy_stoplink(struct device *dev) +{ + dcpaud_legacy_record('S'); + return 0; +} + +static void dcpaud_legacy_rpm_disable(void *data) +{ + pm_runtime_disable(data); +} + +static void dcpaud_legacy_close(void *data) +{ + snd_dmaengine_pcm_close(data); +} + +/* A legacy service instance with a sink, and a configured stream on it */ +static struct snd_pcm_substream *dcpaud_legacy_setup(struct kunit *test, + struct dcp_audio **audio) +{ + struct dcpaud_legacy_test *t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + struct dcp_audio *dcpaud = kunit_kzalloc(test, sizeof(*dcpaud), GFP_KERNEL); + struct snd_pcm_substream *sub = kunit_kzalloc(test, sizeof(*sub), GFP_KERNEL); + struct snd_pcm_runtime *runtime = kunit_kzalloc(test, sizeof(*runtime), GFP_KERNEL); + struct snd_pcm *pcm = kunit_kzalloc(test, sizeof(*pcm), GFP_KERNEL); + struct platform_device *pdev; + + KUNIT_ASSERT_NOT_NULL(test, t); + KUNIT_ASSERT_NOT_NULL(test, dcpaud); + KUNIT_ASSERT_NOT_NULL(test, sub); + KUNIT_ASSERT_NOT_NULL(test, runtime); + KUNIT_ASSERT_NOT_NULL(test, pcm); + pdev = kunit_platform_device_alloc(test, "dcpaud-legacy", PLATFORM_DEVID_AUTO); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pdev); + platform_set_drvdata(pdev, dcpaud); + dcpaud->dev = &pdev->dev; + dcpaud->dcp_dev = &pdev->dev; + mutex_init(&dcpaud->data_lock); + INIT_DELAYED_WORK(&dcpaud->void_work, dcpaud_void_work); + dcpaud->connected = true; + dcpaud->substream = sub; + + /* Runtime PM on, without callbacks: only the usage count matters */ + pm_runtime_no_callbacks(dcpaud->dev); + pm_runtime_enable(dcpaud->dev); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, dcpaud_legacy_rpm_disable, + dcpaud->dev), 0); + + dcpaud_legacy_current = t; + t->dev = dcpaud->dev; + t->usage_at_drain = -1; + t->channel.device = &t->dma; + t->dma.device_terminate_all = dcpaud_legacy_terminate; + t->dma.device_synchronize = dcpaud_legacy_drain; + t->dma.device_tx_status = dcpaud_legacy_status; + t->dma.device_prep_dma_cyclic = dcpaud_legacy_prep; + t->dma.device_issue_pending = dcpaud_legacy_issue; + kunit_activate_static_stub(test, dcp_audiosrv_startlink, dcpaud_legacy_startlink); + kunit_activate_static_stub(test, dcp_audiosrv_stoplink, dcpaud_legacy_stoplink); + + pcm->private_data = dcpaud; + pcm->nonatomic = true; + sub->pcm = pcm; + sub->runtime = runtime; + mutex_init(&sub->self_group.mutex); + spin_lock_init(&sub->self_group.lock); + sub->group = &sub->self_group; + runtime->frame_bits = 64; + runtime->rate = 48000; + runtime->buffer_size = 8192; + runtime->period_size = 512; + KUNIT_ASSERT_EQ(test, snd_dmaengine_pcm_open(sub, &t->channel), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, dcpaud_legacy_close, sub), 0); + + *audio = dcpaud; + return sub; +} + +static int dcpaud_legacy_usage(struct dcp_audio *dcpaud) +{ + return atomic_read(&dcpaud->dev->power.usage_count); +} + +static void dcpaud_legacy_stop_waits_for_dma(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_setup(test, &audio); + + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 1); + + /* The terminate is only started: the DPA stays powered */ + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "TQXS"); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 1); + + /* The reference goes once the terminate was waited for */ + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "TQXSD"); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_current->usage_at_drain, 1); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); + KUNIT_EXPECT_FALSE(test, audio->pm_held); + + /* A second sync_stop (close after prepare) has nothing to put */ + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); +} + +static void dcpaud_legacy_suspend_waits_for_dma(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_setup(test, &audio); + + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_SUSPEND), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 1); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "TQXSD"); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_current->usage_at_drain, 1); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); +} + +static void dcpaud_legacy_failed_start(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_setup(test, &audio); + + /* START fails at the link; ALSA undoes it with a STOP */ + dcpaud_legacy_current->startlink_err = -EIO; + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), -EIO); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 1); + + /* Retried before sync_stop ran: still one reference */ + dcpaud_legacy_current->startlink_err = 0; + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 1); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "TXSTQXSD"); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); +} + +static void dcpaud_legacy_void_takes_no_reference(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_setup(test, &audio); + + /* No sink: the stream plays into the void; a 10 s period never elapses here */ + audio->open_unplugged = true; + sub->runtime->period_size = 480000; + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + KUNIT_EXPECT_TRUE(test, audio->void_running); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "D"); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); +} + +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) +static u64 dcpaud_legacy_instance(struct device *dev) +{ + return dcpaud_legacy_current->instance; +} + +/* A started stream, RUNNING as the PCM core has it, on service instance 5 */ +static struct snd_pcm_substream *dcpaud_legacy_running(struct kunit *test, + struct dcp_audio **audio) +{ + struct snd_pcm_substream *sub = dcpaud_legacy_setup(test, audio); + struct snd_pcm_runtime *runtime = sub->runtime; + + runtime->status = kunit_kzalloc(test, sizeof(*runtime->status), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, runtime->status); + init_waitqueue_head(&runtime->sleep); + init_waitqueue_head(&runtime->tsleep); + sub->ops = &dcp_playback_ops; + INIT_WORK(&(*audio)->replaced_work, dcpaud_replaced_work); + dcpaud_legacy_current->instance = 5; + kunit_activate_static_stub(test, dcp_audiosrv_instance, dcpaud_legacy_instance); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + runtime->state = SNDRV_PCM_STATE_RUNNING; + runtime->status->state = SNDRV_PCM_STATE_RUNNING; + return sub; +} + +/* + * The firmware published a successor of the service with the sink still + * connected: the stream's link went with the old instance. The connect that + * follows the successor's Open ends the stream as an xrun (DMA terminate and + * link stop, as on any STOP); sync_stop then puts the PM reference. + */ +static void dcpaud_legacy_replaced_instance_ends_stream(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_running(test, &audio); + + KUNIT_EXPECT_EQ(test, audio->start_gen, 5ULL); + dcpaud_legacy_current->instance = 6; + dcpaud_replaced_work(&audio->replaced_work); + KUNIT_EXPECT_EQ(test, (int)sub->runtime->state, (int)SNDRV_PCM_STATE_XRUN); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "TQXS"); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); + + /* Prepared again by userspace, the next START is the successor's */ + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + KUNIT_EXPECT_EQ(test, audio->start_gen, 6ULL); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); +} + +/* A connect with the stream's own instance still published leaves it playing */ +static void dcpaud_legacy_same_instance_keeps_stream(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_running(test, &audio); + + dcpaud_replaced_work(&audio->replaced_work); + KUNIT_EXPECT_EQ(test, (int)sub->runtime->state, (int)SNDRV_PCM_STATE_RUNNING); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "TQ"); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); +} + +/* A stream playing into the void has no link to lose */ +static void dcpaud_legacy_replaced_instance_keeps_void(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_setup(test, &audio); + + sub->runtime->status = kunit_kzalloc(test, sizeof(*sub->runtime->status), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sub->runtime->status); + sub->ops = &dcp_playback_ops; + INIT_WORK(&audio->replaced_work, dcpaud_replaced_work); + kunit_activate_static_stub(test, dcp_audiosrv_instance, dcpaud_legacy_instance); + audio->open_unplugged = true; + sub->runtime->period_size = 480000; + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + sub->runtime->state = SNDRV_PCM_STATE_RUNNING; + dcpaud_legacy_current->instance = 6; + dcpaud_replaced_work(&audio->replaced_work); + KUNIT_EXPECT_EQ(test, (int)sub->runtime->state, (int)SNDRV_PCM_STATE_RUNNING); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); +} +#endif + +static int dcpaud_legacy_get_elements(struct device *dev, void *elements, size_t maxsize) +{ + struct dcpaud_legacy_test *t = dcpaud_legacy_current; + + t->elements_asked = maxsize; + /* What the service returns: cut off at the buffer's end */ + memset(elements, 0xa5, min(t->catalog, maxsize)); + return 0; +} + +static int dcpaud_legacy_get_attrs(struct device *dev, void *attrs, size_t maxsize) +{ + return 0; +} + +static void dcpaud_legacy_free(void *data) +{ + kvfree(data); +} + +static void dcpaud_legacy_elements_capacity(struct kunit *test) +{ + struct dcp_audio *audio; + u8 *elements; + + dcpaud_legacy_setup(test, &audio); + elements = kvzalloc(DCPAUD_ELEMENTS_MAXSIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, elements); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, dcpaud_legacy_free, elements), 0); + audio->elements = elements; + audio->productattrs = kunit_kzalloc(test, DCPAUD_PRODUCTATTRS_MAXSIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, audio->productattrs); + kunit_activate_static_stub(test, dcp_audiosrv_get_elements, dcpaud_legacy_get_elements); + kunit_activate_static_stub(test, dcp_audiosrv_get_product_attrs, dcpaud_legacy_get_attrs); + + /* A TV behind a USB-C to HDMI adapter: 17312 bytes of elements */ + dcpaud_legacy_current->catalog = 17312; + KUNIT_ASSERT_FALSE(test, dcpaud_native_link(audio)); + KUNIT_ASSERT_EQ(test, dcpaud_read_remote_info(audio), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_current->elements_asked, (size_t)SZ_256K); + KUNIT_EXPECT_EQ(test, elements[17311], 0xa5); + KUNIT_EXPECT_EQ(test, elements[17312], 0); +} + +static struct kunit_case dcpaud_legacy_cases[] = { + KUNIT_CASE(dcpaud_legacy_stop_waits_for_dma), + KUNIT_CASE(dcpaud_legacy_suspend_waits_for_dma), + KUNIT_CASE(dcpaud_legacy_failed_start), + KUNIT_CASE(dcpaud_legacy_void_takes_no_reference), + KUNIT_CASE(dcpaud_legacy_elements_capacity), +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + KUNIT_CASE(dcpaud_legacy_replaced_instance_ends_stream), + KUNIT_CASE(dcpaud_legacy_same_instance_keeps_stream), + KUNIT_CASE(dcpaud_legacy_replaced_instance_keeps_void), +#endif + {} +}; + +static struct kunit_suite dcpaud_legacy_suite = { + .name = "apple-dcpaud-legacy", + .test_cases = dcpaud_legacy_cases, +}; + +kunit_test_suite(dcpaud_legacy_suite); diff --git a/drivers/gpu/drm/apple/audio-link-test.c b/drivers/gpu/drm/apple/audio-link-test.c index 1b0ac5f147c4a4..908b0e73bc3f2d 100644 --- a/drivers/gpu/drm/apple/audio-link-test.c +++ b/drivers/gpu/drm/apple/audio-link-test.c @@ -687,6 +687,86 @@ static void dcpaud_sleep_ends_cleared_dma(struct kunit *test) KUNIT_EXPECT_EQ(test, atomic_read(&audio->dev->power.usage_count), 0); } +/* The monitor's ELD, as drm builds it from an EDID with a name: 'QG270 S3' */ +static int dcpaud_eld_test_sink(struct device *dev, u8 *eld, size_t size) +{ + static const char name[] = "QG270 S3"; + + memset(eld, 0, size); + eld[DRM_ELD_VER] = DRM_ELD_VER_CEA861D; + eld[DRM_ELD_CEA_EDID_VER_MNL] = DRM_ELD_CEA_EDID_VER_CEA861BCD | + (sizeof(name) - 1); + eld[DRM_ELD_MANUFACTURER_NAME0] = 0x04; + eld[DRM_ELD_MANUFACTURER_NAME1] = 0x72; + memcpy(eld + DRM_ELD_MONITOR_NAME_STRING, name, sizeof(name) - 1); + return 0; +} + +/* + * A Type-C processor's service connects before its route's EDID is read: the + * card has the basic fallback. Once the EDID is published, it takes the name. + */ +static void dcpaud_eld_refresh_takes_monitor_name(struct kunit *test) +{ + struct platform_device *pdev; + struct dcp_audio *dcpaud = dcpaud_link_setup(test, &pdev); + u8 eld[DCPAUD_ELD_SIZE]; + + mutex_init(&dcpaud->data_lock); + dcpaud->connected = true; + dcpaud_build_eld(dcpaud, dcpaud->eld); /* no EDID yet: fallback */ + KUNIT_EXPECT_EQ(test, drm_eld_mnl(dcpaud->eld), 0); + KUNIT_EXPECT_EQ(test, drm_eld_sad_count(dcpaud->eld), 1); + + kunit_activate_static_stub(test, dcp_audio_sink_eld, dcpaud_eld_test_sink); + dcpaud_build_eld(dcpaud, eld); + KUNIT_EXPECT_TRUE(test, dcpaud_eld_update(dcpaud, eld)); + KUNIT_EXPECT_EQ(test, drm_eld_mnl(dcpaud->eld), 8); + KUNIT_EXPECT_MEMEQ(test, dcpaud->eld + DRM_ELD_MONITOR_NAME_STRING, "QG270 S3", 8); + KUNIT_EXPECT_EQ(test, drm_eld_sad_count(dcpaud->eld), 1); + /* The same ELD again is no change. */ + KUNIT_EXPECT_FALSE(test, dcpaud_eld_update(dcpaud, eld)); +} + +/* A card without a sink keeps its zero ELD: the jack follows the firmware. */ +static void dcpaud_eld_refresh_needs_connection(struct kunit *test) +{ + struct platform_device *pdev; + struct dcp_audio *dcpaud = dcpaud_link_setup(test, &pdev); + u8 eld[DCPAUD_ELD_SIZE]; + + mutex_init(&dcpaud->data_lock); + kunit_activate_static_stub(test, dcp_audio_sink_eld, dcpaud_eld_test_sink); + dcpaud_build_eld(dcpaud, eld); + KUNIT_EXPECT_FALSE(test, dcpaud_eld_update(dcpaud, eld)); + KUNIT_EXPECT_EQ(test, dcpaud->eld[DRM_ELD_VER], 0); +} + +/* The EDID was cleared (stale route) or is still to be read: no ELD */ +static int dcpaud_eld_test_no_edid(struct device *dev, u8 *eld, size_t size) +{ + memset(eld, 0, size); + return -ENODATA; +} + +/* A cleared or unread EDID leaves a connected card's named ELD as it is. */ +static void dcpaud_eld_refresh_keeps_name_without_edid(struct kunit *test) +{ + struct platform_device *pdev; + struct dcp_audio *dcpaud = dcpaud_link_setup(test, &pdev); + + mutex_init(&dcpaud->data_lock); + dcpaud->connected = true; + kunit_activate_static_stub(test, dcp_audio_sink_eld, dcpaud_eld_test_sink); + KUNIT_EXPECT_TRUE(test, dcpaud_refresh_eld_from_edid(dcpaud)); + KUNIT_EXPECT_EQ(test, drm_eld_mnl(dcpaud->eld), 8); + + kunit_activate_static_stub(test, dcp_audio_sink_eld, dcpaud_eld_test_no_edid); + KUNIT_EXPECT_FALSE(test, dcpaud_refresh_eld_from_edid(dcpaud)); + KUNIT_EXPECT_EQ(test, drm_eld_mnl(dcpaud->eld), 8); + KUNIT_EXPECT_MEMEQ(test, dcpaud->eld + DRM_ELD_MONITOR_NAME_STRING, "QG270 S3", 8); +} + static struct kunit_case dcpaud_link_cases[] = { KUNIT_CASE(dcpaud_link_release_instance), KUNIT_CASE(dcpaud_disconnect_sync_completes_live_owner), @@ -707,6 +787,9 @@ static struct kunit_case dcpaud_link_cases[] = { KUNIT_CASE(dcpaud_sleep_suspends_running_stream), KUNIT_CASE(dcpaud_sleep_releases_held_link), KUNIT_CASE(dcpaud_sleep_ends_cleared_dma), + KUNIT_CASE(dcpaud_eld_refresh_takes_monitor_name), + KUNIT_CASE(dcpaud_eld_refresh_needs_connection), + KUNIT_CASE(dcpaud_eld_refresh_keeps_name_without_edid), {} }; diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index 51fcc346a575b4..d2333b9340b32e 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -21,6 +21,8 @@ #include #include #include +#include +#include #include #include #include @@ -37,11 +39,15 @@ #include "audio.h" #include "parser.h" -#define DCPAUD_ELEMENTS_MAXSIZE 16384 +/* + * The element catalog capacity, on every firmware. Elements that do not + * fit come back cut off at the buffer's end with a used size of 0: a TV + * behind a USB-C to HDMI adapter has 17312 bytes of them. macOS 13 asks + * for up to 256 KiB. + */ +#define DCPAUD_ELEMENTS_MAXSIZE SZ_256K #define DCPAUD_PRODUCTATTRS_MAXSIZE 1024 #define DCPAUD_ELD_SIZE MAX_ELD_BYTES -/* The native element catalog capacity (14.7 external role). */ -#define DCPAUD_ELEMENTS_V14_7 SZ_256K /* * SIO takes one of its 64 descriptor slots per period, shared by all its @@ -67,6 +73,9 @@ #define DCPAUD_HELD_PERIOD_MAX_US 50000 struct dcp_audio { + /* The display output the processor drives, from its device tree node */ + const char *port_name; + const char *port_id; struct device *dev; struct device *dcp_dev; struct device *dma_dev; @@ -97,6 +106,16 @@ struct dcp_audio { ktime_t void_start; u64 void_periods; struct delayed_work void_work; + /* The stream holds a runtime PM reference, put in sync_stop; stream lock */ + bool pm_held; + /* The service instance the stream's link started on; stream lock */ + u64 start_gen; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* Ends a stream on a replaced instance, see dcpaud_replaced_work() */ + struct work_struct replaced_work; + /* replaced_work is enabled: the card is bound, see dcpaud_comp_unbind() */ + bool replaced_enabled; +#endif void *elements; void *productattrs; @@ -142,11 +161,6 @@ static inline bool dcpaud_native_link(struct dcp_audio *dcpaud) #endif } -static inline size_t dcpaud_elements_size(struct dcp_audio *dcpaud) -{ - return dcpaud_native_link(dcpaud) ? DCPAUD_ELEMENTS_V14_7 : DCPAUD_ELEMENTS_MAXSIZE; -} - static const struct snd_pcm_hardware dcp_pcm_hw = { .info = SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_INTERLEAVED, @@ -195,7 +209,7 @@ static int dcpaud_read_remote_info(struct dcp_audio *dcpaud) int ret; ret = dcp_audiosrv_get_elements(dcpaud->dcp_dev, dcpaud->elements, - dcpaud_elements_size(dcpaud)); + DCPAUD_ELEMENTS_MAXSIZE); if (ret < 0) return ret; @@ -252,7 +266,7 @@ static void dcpaud_consult_elements(struct dcp_audio *dcpaud, struct dcp_parse_ctx elements = { .dcp = dev_get_drvdata(dcpaud->dcp_dev), .blob = dcpaud->elements + 4, - .len = dcpaud_elements_size(dcpaud) - 4, + .len = DCPAUD_ELEMENTS_MAXSIZE - 4, .pos = 0, #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) .v14_7_audio = dcpaud->native_link, @@ -301,7 +315,7 @@ static int dcpaud_select_cookie(struct dcp_audio *dcpaud, struct dcp_parse_ctx elements = { .dcp = dev_get_drvdata(dcpaud->dcp_dev), .blob = dcpaud->elements + 4, - .len = dcpaud_elements_size(dcpaud) - 4, + .len = DCPAUD_ELEMENTS_MAXSIZE - 4, .pos = 0, #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) .v14_7_audio = dcpaud->native_link, @@ -318,16 +332,16 @@ static int dcpaud_select_cookie(struct dcp_audio *dcpaud, } static int dcpaud_rule_channels(struct snd_pcm_hw_params *params, - struct snd_pcm_hw_rule *rule) + struct snd_pcm_hw_rule *rule) { struct dcp_audio *dcpaud = rule->private; struct snd_interval *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); struct dcp_sound_format_mask hits = {0, 0, 0}; - dcpaud_consult_elements(dcpaud, params, &hits); + dcpaud_consult_elements(dcpaud, params, &hits); - return dcpaud_interval_bitmask(c, hits.nchans); + return dcpaud_interval_bitmask(c, hits.nchans); } static int dcpaud_refine_fmt_mask(struct snd_mask *m, u64 mask) @@ -343,29 +357,29 @@ static int dcpaud_refine_fmt_mask(struct snd_mask *m, u64 mask) } static int dcpaud_rule_format(struct snd_pcm_hw_params *params, - struct snd_pcm_hw_rule *rule) + struct snd_pcm_hw_rule *rule) { struct dcp_audio *dcpaud = rule->private; struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT); struct dcp_sound_format_mask hits; - dcpaud_consult_elements(dcpaud, params, &hits); + dcpaud_consult_elements(dcpaud, params, &hits); - return dcpaud_refine_fmt_mask(f, hits.formats); + return dcpaud_refine_fmt_mask(f, hits.formats); } static int dcpaud_rule_rate(struct snd_pcm_hw_params *params, - struct snd_pcm_hw_rule *rule) + struct snd_pcm_hw_rule *rule) { struct dcp_audio *dcpaud = rule->private; struct snd_interval *r = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); struct dcp_sound_format_mask hits; - dcpaud_consult_elements(dcpaud, params, &hits); + dcpaud_consult_elements(dcpaud, params, &hits); - return snd_interval_rate_bits(r, hits.rates); + return snd_interval_rate_bits(r, hits.rates); } static int dcpaud_init_dma(struct dcp_audio *dcpaud) @@ -410,6 +424,9 @@ static int dcp_pcm_open(struct snd_pcm_substream *substream) .flags = SND_DMAENGINE_PCM_DAI_FLAG_PACK, }; struct snd_pcm_hardware hw; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + u64 gen; +#endif int ret; mutex_lock(&dcpaud->data_lock); @@ -428,7 +445,48 @@ static int dcp_pcm_open(struct snd_pcm_substream *substream) goto refine; } +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + gen = dcp_audiosrv_instance(dcpaud->dcp_dev); +#endif ret = dcpaud_read_remote_info(dcpaud); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* + * The firmware announces the audio service again while the display + * link is set up again (a modeset, at boot), and refuses calls to the + * instance it is replacing meanwhile. Userspace probes the PCM once + * and drops an output whose open fails, so read from the successor. + * The sink is taken as the successor reports it. A refusal is -EINVAL + * (a non-zero retcode); a missing service, a timeout or no memory is + * not waited out. + */ + if (ret == -EINVAL && dcp_audiosrv_replaced(dcpaud->dcp_dev, gen)) { + dev_dbg(dcpaud->dev, "sink info read failed on a replaced instance (%d), retrying\n", + ret); + mutex_lock(&dcpaud->data_lock); + dcpaud->open_unplugged = !dcpaud->connected; + dcpaud->open_cookie = dcpaud->connection_cookie; + mutex_unlock(&dcpaud->data_lock); + if (dcpaud->open_unplugged) { + hw = dcp_pcm_hw_unplugged; + goto refine; + } + ret = dcpaud_read_remote_info(dcpaud); + } +#endif + if (ret == -ENODEV) { + /* + * No instance answers: the service went and its unplug is on the + * way. Open as unplugged, as before the plug, and with a cookie + * no connection has, so that no stream op of this open takes the + * sink as connected. + */ + mutex_lock(&dcpaud->data_lock); + dcpaud->open_unplugged = true; + dcpaud->open_cookie = dcpaud->connection_cookie - 1; + mutex_unlock(&dcpaud->data_lock); + hw = dcp_pcm_hw_unplugged; + goto refine; + } if (ret < 0) return ret; @@ -682,9 +740,13 @@ static int dcp_pcm_trigger(struct snd_pcm_substream *substream, int cmd) if (dcpaud->open_unplugged || !dcpaud_connection_up(dcpaud)) return dcpaud_void_start(substream); - WARN_ON(pm_runtime_get_sync(dcpaud->dev) < 0); + /* A START can follow a failed one before sync_stop ran */ + if (!dcpaud->pm_held) { + WARN_ON(pm_runtime_get_sync(dcpaud->dev) < 0); + dcpaud->pm_held = true; + } ret = dcp_audiosrv_startlink(dcpaud->dcp_dev, - &dcpaud->selected_cookie); + &dcpaud->selected_cookie, &dcpaud->start_gen); if (ret < 0) return ret; break; @@ -715,9 +777,8 @@ static int dcp_pcm_trigger(struct snd_pcm_substream *substream, int cmd) case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: + /* The runtime PM reference goes in sync_stop */ ret = dcp_audiosrv_stoplink(dcpaud->dcp_dev); - pm_runtime_mark_last_busy(dcpaud->dev); - __pm_runtime_put_autosuspend(dcpaud->dev); if (ret < 0) return ret; break; @@ -727,19 +788,37 @@ static int dcp_pcm_trigger(struct snd_pcm_substream *substream, int cmd) } /* - * ALSA calls this once a stream has stopped, outside the stream lock, before - * the next hw_params, prepare or hw_free and at close. + * ALSA calls this once a stream has stopped (STOP, SUSPEND, or the STOP that + * undoes a failed START), outside the stream lock, before the next + * hw_params, prepare or hw_free, at close, at system suspend and at + * disconnect. The DMA terminate STOP started is asynchronous: putting the + * runtime PM reference in STOP powered the DPA's domain (ps_dpa*) down while + * SIO still ran DMA towards it, and SIO crashed ("Shim DMA unavailable", the + * TERMINATE timing out after it), taking DP audio down on every output until + * a reboot. Wait for the terminate first. */ static int dcp_pcm_sync_stop(struct snd_pcm_substream *substream) { struct dcp_audio *dcpaud = substream->pcm->private_data; + bool held; cancel_delayed_work_sync(&dcpaud->void_work); + snd_dmaengine_pcm_sync_stop(substream); + + snd_pcm_stream_lock_irq(substream); + held = dcpaud->pm_held; + dcpaud->pm_held = false; + snd_pcm_stream_unlock_irq(substream); + + if (held) { + pm_runtime_mark_last_busy(dcpaud->dev); + __pm_runtime_put_autosuspend(dcpaud->dev); + } return 0; } -struct snd_pcm_ops dcp_playback_ops = { +static const struct snd_pcm_ops dcp_playback_ops = { .open = dcp_pcm_open, .close = dcp_pcm_close, .hw_params = dcp_pcm_hw_params, @@ -814,7 +893,7 @@ static int dcpaud_pin_rate_format(struct dcp_audio *dcpaud, struct dcp_parse_ctx elements = { .dcp = dev_get_drvdata(dcpaud->dcp_dev), .blob = dcpaud->elements + 4, - .len = dcpaud_elements_size(dcpaud) - 4, + .len = DCPAUD_ELEMENTS_MAXSIZE - 4, .pos = 0, .v14_7_audio = dcpaud->native_link, }; @@ -1337,7 +1416,7 @@ static int dcpaud_select_default_cookie(struct dcp_audio *dcpaud) struct dcp_parse_ctx elements = { .dcp = dev_get_drvdata(dcpaud->dcp_dev), .blob = dcpaud->elements + 4, - .len = dcpaud_elements_size(dcpaud) - 4, + .len = DCPAUD_ELEMENTS_MAXSIZE - 4, .pos = 0, .v14_7_audio = dcpaud->native_link, }; @@ -1543,7 +1622,7 @@ static const struct snd_pcm_ops dcp_native_playback_ops = { #include "hdmi-codec-chmap.h" static int dcpaud_chmap_ctl_get(struct snd_kcontrol *kcontrol, - struct snd_ctl_elem_value *ucontrol) + struct snd_ctl_elem_value *ucontrol) { struct snd_pcm_chmap *info = snd_kcontrol_chip(kcontrol); struct dcp_audio *dcpaud = info->private_data; @@ -1736,13 +1815,32 @@ static int dcpaud_create_jack(struct dcp_audio *dcpaud) &dcpaud->jack, true, false); } +/* + * Names the card after the output its processor drives, as the device tree + * describes it, so that each display's card is told apart: "Apple HDMI" + * (card id HDMI), "Apple USB-C DisplayPort" (USBC), "Apple DisplayPort". + * ALSA makes a repeated id unique. + */ +static void dcpaud_port_names(struct dcp_audio *dcpaud, struct device_node *dcp_node) +{ + dcpaud->port_name = "DisplayPort"; + dcpaud->port_id = "DisplayPort"; + if (of_property_match_string(dcp_node, "apple,connector-type", "HDMI-A") >= 0) { + dcpaud->port_name = "HDMI"; + dcpaud->port_id = "HDMI"; + } else if (of_property_match_string(dcp_node, "apple,connector-type", "USB-C") >= 0) { + dcpaud->port_name = "USB-C DisplayPort"; + dcpaud->port_id = "USBC"; + } +} + static void dcpaud_set_card_names(struct dcp_audio *dcpaud) { struct snd_card *card = dcpaud->card; strscpy(card->driver, "apple_dcp", sizeof(card->driver)); - strscpy(card->longname, "Apple DisplayPort", sizeof(card->longname)); - strscpy(card->shortname, "Apple DisplayPort", sizeof(card->shortname)); + snprintf(card->shortname, sizeof(card->shortname), "Apple %s", dcpaud->port_name); + snprintf(card->longname, sizeof(card->longname), "Apple %s audio", dcpaud->port_name); } #ifdef CONFIG_SND_DEBUG @@ -1780,7 +1878,7 @@ static int dcpaud_init_snd_card(struct dcp_audio *dcpaud) return -ENODEV; - ret = snd_card_new(dcpaud->dev, DCPAUD_CARD_SLOTS, SNDRV_DEFAULT_STR1, + ret = snd_card_new(dcpaud->dev, DCPAUD_CARD_SLOTS, dcpaud->port_id, THIS_MODULE, 0, &dcpaud->card); if (ret) return ret; @@ -1815,6 +1913,36 @@ static int dcpaud_init_snd_card(struct dcp_audio *dcpaud) return ret; } +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) +/* + * The firmware publishes a successor of the audio service while the display + * link is set up again, also with the sink connected throughout (after a + * wake, the monitor's HPD pulse). The successor comes up plugged, so the card + * sees no unplug; the link a running stream started on went with the old + * instance, its DMA stops and the stream would wait forever. It ends as an + * xrun instead, and userspace prepares it again on the successor. + */ +static void dcpaud_replaced_work(struct work_struct *work) +{ + struct dcp_audio *dcpaud = container_of(work, struct dcp_audio, replaced_work); + struct snd_pcm_substream *substream = dcpaud->substream; + + if (!substream || !dcpaud->dcp_dev) + return; + /* + * Under the stream lock (a mutex: the PCM is nonatomic), as START + * takes the instance under it: no START completes in between. + */ + snd_pcm_stream_lock_irq(substream); + if (substream->runtime && snd_pcm_running(substream) && !dcpaud->void_running && + dcpaud->start_gen != dcp_audiosrv_instance(dcpaud->dcp_dev)) { + dev_dbg(dcpaud->dev, "stream's link went with its service\n"); + snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN); + } + snd_pcm_stream_unlock_irq(substream); +} +#endif + void dcpaud_connect(struct platform_device *pdev, bool connected) { struct dcp_audio *dcpaud = platform_get_drvdata(pdev); @@ -1828,6 +1956,58 @@ void dcpaud_connect(struct platform_device *pdev, bool connected) mutex_lock(&dcpaud->data_lock); dcpaud_report_hotplug(dcpaud, connected, eld); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* A connect follows each newly opened instance; see dcpaud_replaced_work() */ + if (connected && !dcpaud->native_link && dcpaud->card) + schedule_work(&dcpaud->replaced_work); +#endif +} + +/* + * The connected sink's ELD, built again from the connector's EDID. The ELD is + * built as the audio service connects, which on a Type-C processor can come + * before its route is up and the display's EDID is read (at boot, and as the + * service is published again after a sleep): the card would keep the basic + * fallback without the monitor's name. A card that is not connected stays so. + * Returns whether the stored ELD changed. + */ +static bool dcpaud_eld_update(struct dcp_audio *dcpaud, const u8 *eld) +{ + bool changed; + + mutex_lock(&dcpaud->data_lock); + changed = dcpaud->connected && memcmp(dcpaud->eld, eld, DCPAUD_ELD_SIZE); + if (changed) + memcpy(dcpaud->eld, eld, DCPAUD_ELD_SIZE); + mutex_unlock(&dcpaud->data_lock); + return changed; +} + +/* + * Only an ELD built from an EDID replaces the stored one. The EDID code also + * ends here after clearing a stale EDID (an old route or service) or while a + * read is still to be retried; the card then keeps what it has rather than + * falling back to basic stereo without the monitor's name. + */ +static bool dcpaud_refresh_eld_from_edid(struct dcp_audio *dcpaud) +{ + u8 eld[DCPAUD_ELD_SIZE]; + + if (dcp_audio_sink_eld(dcpaud->dcp_dev, eld, DCPAUD_ELD_SIZE) || + !eld[DRM_ELD_VER]) + return false; + dcpaud_build_eld(dcpaud, eld); + return dcpaud_eld_update(dcpaud, eld); +} + +void dcpaud_refresh_eld(struct platform_device *pdev) +{ + struct dcp_audio *dcpaud = platform_get_drvdata(pdev); + + if (!dcpaud || !dcpaud->dcp_dev || !dcpaud->card) + return; + if (dcpaud_refresh_eld_from_edid(dcpaud)) + snd_ctl_notify(dcpaud->card, SNDRV_CTL_EVENT_MASK_VALUE, &dcpaud->eld_ctl->id); } void dcpaud_disconnect(struct platform_device *pdev) @@ -1874,6 +2054,7 @@ static int dcpaud_comp_bind(struct device *dev, struct device *main, void *data) dev_info(dev, "No audio support\n"); goto rpm_put; } + dcpaud_port_names(dcpaud, dcp_node); index = of_property_match_string(dev->of_node, "dma-names", "tx"); if (index < 0) { @@ -1896,16 +2077,9 @@ static int dcpaud_comp_bind(struct device *dev, struct device *main, void *data) dcpaud->dcp_dev = &dcp_pdev->dev; #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) - /* Native external roles share the link lifecycle and element catalog. */ - if (dcp_audiosrv_native_link(dcpaud->dcp_dev)) { - void *elements = devm_kzalloc(dev, DCPAUD_ELEMENTS_V14_7, GFP_KERNEL); - - if (!elements) - goto rpm_put; - devm_kfree(dev, dcpaud->elements); - dcpaud->elements = elements; + /* Native external roles share the link lifecycle. */ + if (dcp_audiosrv_native_link(dcpaud->dcp_dev)) dcpaud->native_link = true; - } #endif dma_pdev = of_find_device_by_node(dma_spec.np); @@ -1925,10 +2099,15 @@ static int dcpaud_comp_bind(struct device *dev, struct device *main, void *data) ret = dcpaud_init_snd_card(dcpaud); if (!ret) { +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* Connects may queue it from now on, with a card to act on. */ + enable_work(&dcpaud->replaced_work); + dcpaud->replaced_enabled = true; +#endif dcpaud_expose_debugfs_blob(dcpaud, "selected_cookie", &dcpaud->selected_cookie, sizeof(dcpaud->selected_cookie)); dcpaud_expose_debugfs_blob(dcpaud, "elements", dcpaud->elements, - dcpaud_elements_size(dcpaud)); + DCPAUD_ELEMENTS_MAXSIZE); dcpaud_expose_debugfs_blob(dcpaud, "product_attrs", dcpaud->productattrs, DCPAUD_PRODUCTATTRS_MAXSIZE); } @@ -1944,6 +2123,17 @@ static void dcpaud_comp_unbind(struct device *dev, struct device *main, { struct dcp_audio *dcpaud = dev_get_drvdata(dev); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* + * The DCP unbinds after its audio and may still connect: a connect + * from now on queues nothing, and a queued or running work ends + * before the card goes. + */ + if (dcpaud->replaced_enabled) { + disable_work_sync(&dcpaud->replaced_work); + dcpaud->replaced_enabled = false; + } +#endif /* snd_card_free_when_closed() checks for NULL */ snd_card_free_when_closed(dcpaud->card); @@ -1980,18 +2170,27 @@ static const struct component_ops dcpaud_comp_ops = { .unbind = dcpaud_comp_unbind, }; +static void dcpaud_free_elements(void *elements) +{ + kvfree(elements); +} + static int dcpaud_probe(struct platform_device *pdev) { struct dcp_audio *dcpaud; + int ret; dcpaud = devm_kzalloc(&pdev->dev, sizeof(*dcpaud), GFP_KERNEL); if (!dcpaud) return -ENOMEM; - dcpaud->elements = devm_kzalloc(&pdev->dev, DCPAUD_ELEMENTS_MAXSIZE, - GFP_KERNEL); + dcpaud->elements = kvzalloc(DCPAUD_ELEMENTS_MAXSIZE, GFP_KERNEL); if (!dcpaud->elements) return -ENOMEM; + ret = devm_add_action_or_reset(&pdev->dev, dcpaud_free_elements, + dcpaud->elements); + if (ret) + return ret; dcpaud->productattrs = devm_kzalloc(&pdev->dev, DCPAUD_PRODUCTATTRS_MAXSIZE, GFP_KERNEL); @@ -2003,6 +2202,9 @@ static int dcpaud_probe(struct platform_device *pdev) #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) mutex_init(&dcpaud->link_lock); INIT_WORK(&dcpaud->stale_work, dcpaud_stale_work); + INIT_WORK(&dcpaud->replaced_work, dcpaud_replaced_work); + /* Enabled once the card is bound, see dcpaud_comp_bind() */ + disable_work(&dcpaud->replaced_work); #endif INIT_DELAYED_WORK(&dcpaud->void_work, dcpaud_void_work); platform_set_drvdata(pdev, dcpaud); @@ -2071,6 +2273,39 @@ static __maybe_unused int dcpaud_system_suspend(struct device *dev) return 0; } +/* + * The DCP's firmware drives this block. A DCP that keeps its coprocessor + * running through a sleep keeps its own power domains for it, and this + * block's domain must stay with them: cutting it at noirq under running DCP + * firmware resets the machine. A DCP that stops its firmware for the sleep + * needs nothing held here, so the domain goes down as before. A DCP device + * without a driver may still run firmware that a boot stage or an earlier + * bind left running, so its block is kept too. Every device's .suspend has + * run before this late phase, so the DCP's choice is known + * (dcp_sleep_keeps_firmware()). + */ +static __maybe_unused int dcpaud_suspend_late(struct device *dev) +{ + struct device_node *endpoint, *dcp_node = NULL; + struct platform_device *dcp_pdev = NULL; + + endpoint = of_graph_get_endpoint_by_regs(dev->of_node, 0, 0); + if (endpoint) { + dcp_node = of_graph_get_remote_port_parent(endpoint); + of_node_put(endpoint); + } + if (dcp_node && of_device_is_available(dcp_node)) + dcp_pdev = of_find_device_by_node(dcp_node); + of_node_put(dcp_node); + if (dcp_pdev) { + if (dcp_sleep_keeps_firmware(&dcp_pdev->dev)) + device_set_wakeup_path(dev); + put_device(&dcp_pdev->dev); + } + + return pm_runtime_force_suspend(dev); +} + /* * Runtime PM stops in the late phase and comes back in the early one, so it * works through every device's .suspend and .resume. The display resumes @@ -2083,7 +2318,7 @@ static __maybe_unused int dcpaud_system_suspend(struct device *dev) static const struct dev_pm_ops dcpaud_pm_ops = { .prepare = pm_sleep_ptr(dcpaud_pm_prepare), SYSTEM_SLEEP_PM_OPS(dcpaud_system_suspend, NULL) - LATE_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend, pm_runtime_force_resume) + LATE_SYSTEM_SLEEP_PM_OPS(dcpaud_suspend_late, pm_runtime_force_resume) RUNTIME_PM_OPS(dcpaud_suspend, dcpaud_resume, NULL) }; @@ -2110,11 +2345,12 @@ int __init dcp_audio_register(void) void dcp_audio_unregister(void) { - platform_driver_unregister(&dcpaud_driver); + platform_driver_unregister(&dcpaud_driver); } #if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) #include "audio-no-sio-test.c" +#include "audio-legacy-test.c" #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) #include "audio-link-test.c" #endif diff --git a/drivers/gpu/drm/apple/audio.h b/drivers/gpu/drm/apple/audio.h index 0ba2ba225af5e5..189abae53b073e 100644 --- a/drivers/gpu/drm/apple/audio.h +++ b/drivers/gpu/drm/apple/audio.h @@ -8,7 +8,7 @@ struct platform_device; struct dcp_sound_cookie; int dcp_audiosrv_prepare(struct device *dev, struct dcp_sound_cookie *cookie); -int dcp_audiosrv_startlink(struct device *dev, struct dcp_sound_cookie *cookie); +int dcp_audiosrv_startlink(struct device *dev, struct dcp_sound_cookie *cookie, u64 *gen); int dcp_audiosrv_stoplink(struct device *dev); int dcp_audiosrv_unprepare(struct device *dev); int dcp_audiosrv_get_elements(struct device *dev, void *elements, size_t maxsize); @@ -17,6 +17,7 @@ int dcp_audio_sink_eld(struct device *dev, u8 *eld, size_t size); void dcpaud_connect(struct platform_device *pdev, bool connected); void dcpaud_disconnect(struct platform_device *pdev); +void dcpaud_refresh_eld(struct platform_device *pdev); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) /* Native link methods for 14.7 and desktop 26.x external roles. */ @@ -47,6 +48,9 @@ struct dcp_audio_link_format { bool dcp_audiosrv_link_by_format(struct device *dev); bool dcp_audiosrv_native_link(struct device *dev); +/* The published audio service instance; whether it was replaced since @gen */ +u64 dcp_audiosrv_instance(struct device *dev); +bool dcp_audiosrv_replaced(struct device *dev, u64 gen); int dcp_audiosrv_open(struct device *dev); void dcp_audiosrv_close(struct device *dev); int dcp_audiosrv_link(struct device *dev, enum dcp_audio_link op, diff --git a/drivers/gpu/drm/apple/av-lifetime-test.c b/drivers/gpu/drm/apple/av-lifetime-test.c index 1a466dfbbaca93..54b8ed919fb2a8 100644 --- a/drivers/gpu/drm/apple/av-lifetime-test.c +++ b/drivers/gpu/drm/apple/av-lifetime-test.c @@ -160,6 +160,7 @@ static struct av_life_test *av_life_setup(struct kunit *test, work_func_t owner_ init_waitqueue_head(&t->asrv->gen_wq); #endif INIT_WORK(&t->asrv->start_av_service_wq, owner_fn); + INIT_DELAYED_WORK(&t->asrv->open_check_wq, owner_fn); INIT_WORK(&t->asrv->terminate_wq, owner_fn); INIT_WORK(&t->dcp->external_audio_work, av_life_owner_fn); t->asrv->works_live = true; @@ -360,26 +361,29 @@ static void av_lifetime_quiesce_once_restart_once(struct kunit *test) static void av_lifetime_report_after_stop(struct kunit *test) { struct av_life_test *t = av_life_setup(test, av_life_owner_fn); - struct apple_epic_service svc = { }; + /* Off the stack: the service and its pending-command table are large. */ + struct apple_epic_service *svc = kunit_kzalloc(test, sizeof(*svc), GFP_KERNEL); struct epic_service_call call = { .group = cpu_to_le16(2), .command = cpu_to_le32(1), .magic = cpu_to_le32(EPIC_SERVICE_CALL_MAGIC), }; + + KUNIT_ASSERT_NOT_NULL(test, svc); t->dcp->fw_compat = DCP_FIRMWARE_V_14_7; t->dcp->external_native = true; t->ep->dcp = t->dcp; - svc.ep = t->ep; - t->asrv->srv = &svc; + svc->ep = t->ep; + t->asrv->srv = svc; av_audiosrv_quiesce(t->dcp); av_audiosrv_quiesce(t->dcp); - av_audiosrv_report(&svc, 0, &call, sizeof(call)); + av_audiosrv_report(svc, 0, &call, sizeof(call)); KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 0); KUNIT_EXPECT_FALSE(test, work_busy(&t->asrv->terminate_wq)); av_audiosrv_reports_restart(t->dcp); - av_audiosrv_report(&svc, 0, &call, sizeof(call)); + av_audiosrv_report(svc, 0, &call, sizeof(call)); flush_work(&t->asrv->terminate_wq); KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 1); av_audiosrv_quiesce(t->dcp); diff --git a/drivers/gpu/drm/apple/av.c b/drivers/gpu/drm/apple/av.c index efca053134e1ac..3496f5ccdfb50d 100644 --- a/drivers/gpu/drm/apple/av.c +++ b/drivers/gpu/drm/apple/av.c @@ -65,6 +65,9 @@ static const struct dcp_av_audio_cmds dcp_av_audio_cmds_v13_5 = { .get_product_attrs = 18, }; +/* How long an Open refused by an instance being replaced waits for the next one */ +#define AV_AUDIOSRV_REPLACE_MS 1000 + /* * Firmware 27's external role (the T6050 DCPEXTs), as macOS 27 drives it on * the M5 Pro: the 13.5 numbers without the started and stopping @@ -133,6 +136,13 @@ struct audiosrv_data { bool warned_get_elements; bool warned_get_product_attrs; bool is_open; + /* + * A classic Open the firmware refused (-EINVAL), judged once the + * instance has had time to be replaced (av_work_open_check()). + */ + struct delayed_work open_check_wq; + struct device *open_check_dev; + int open_refused; /* INIT_WORK has run for the embedded owner works. */ bool works_live; /* Report and service-start admission. Writers hold srv_rwsem. */ @@ -185,9 +195,9 @@ static void av_audiosrv_init(struct apple_epic_service *service, const char *nam down_write(&asrv->srv_rwsem); old = asrv->srv; - asrv->srv = service; + WRITE_ONCE(asrv->srv, service); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) - asrv->gen++; + WRITE_ONCE(asrv->gen, asrv->gen + 1); #endif queue_start = !asrv->reports_stopped; up_write(&asrv->srv_rwsem); @@ -198,6 +208,8 @@ static void av_audiosrv_init(struct apple_epic_service *service, const char *nam afk_service_put(old); asrv->plugged = true; + /* A classic Open is its instance's: the one published now is opened afresh. */ + asrv->is_open = false; /* A new instance, maybe a new sink: its catalog is asked for afresh. */ WRITE_ONCE(asrv->elements_empty, false); mutex_unlock(&asrv->plug_lock); @@ -216,9 +228,9 @@ static void av_audiosrv_teardown(struct apple_epic_service *service) down_write(&asrv->srv_rwsem); owned = asrv->srv == service; if (owned) { - asrv->srv = NULL; + WRITE_ONCE(asrv->srv, NULL); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) - asrv->gen++; + WRITE_ONCE(asrv->gen, asrv->gen + 1); #endif } up_write(&asrv->srv_rwsem); @@ -226,6 +238,7 @@ static void av_audiosrv_teardown(struct apple_epic_service *service) /* A stale generation must not unplug its successor. */ if (owned) { asrv->plugged = false; + asrv->is_open = false; if (asrv->audio_dev) dcpaud_disconnect(asrv->audio_dev); } @@ -251,13 +264,21 @@ int dcp_audiosrv_prepare(struct device *dev, struct dcp_sound_cookie *cookie) return ret; } -int dcp_audiosrv_startlink(struct device *dev, struct dcp_sound_cookie *cookie) +/* @gen: the instance the link starts on (dcp_audiosrv_instance()), or NULL */ +int dcp_audiosrv_startlink(struct device *dev, struct dcp_sound_cookie *cookie, u64 *gen) { - struct apple_dcp *dcp = dev_get_drvdata(dev); - struct audiosrv_data *asrv = dcp->audiosrv; + struct apple_dcp *dcp; + struct audiosrv_data *asrv; int ret; + KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_startlink, dev, cookie, gen); + dcp = dev_get_drvdata(dev); + asrv = dcp->audiosrv; down_write(&asrv->srv_rwsem); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + if (gen) + *gen = asrv->gen; +#endif ret = afk_service_call(asrv->srv, 0, asrv->cmds.start_link, cookie, sizeof(*cookie), 64 - sizeof(*cookie), NULL, 0, 64); @@ -268,10 +289,13 @@ int dcp_audiosrv_startlink(struct device *dev, struct dcp_sound_cookie *cookie) int dcp_audiosrv_stoplink(struct device *dev) { - struct apple_dcp *dcp = dev_get_drvdata(dev); - struct audiosrv_data *asrv = dcp->audiosrv; + struct apple_dcp *dcp; + struct audiosrv_data *asrv; int ret; + KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_stoplink, dev); + dcp = dev_get_drvdata(dev); + asrv = dcp->audiosrv; down_write(&asrv->srv_rwsem); ret = afk_service_call(asrv->srv, 0, asrv->cmds.stop_link, NULL, 0, 64, NULL, 0, 64); @@ -339,8 +363,40 @@ static int av_audiosrv_call(struct apple_epic_service *srv, u32 command, const v return afk_service_call(srv, 0, command, body, body_len, body_pad, reply, reply_len, 0); } -/* How long an Open refused by an instance being replaced waits for the next one */ -#define AV_AUDIOSRV_REPLACE_MS 1000 +/* The audio service instance now published, as dcp_audiosrv_replaced() takes it. */ +u64 dcp_audiosrv_instance(struct device *dev) +{ + struct apple_dcp *dcp; + struct audiosrv_data *asrv; + + KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_instance, dev); + dcp = dev_get_drvdata(dev); + asrv = dcp->audiosrv; + if (!asrv) + return 0; + guard(rwsem_read)(&asrv->srv_rwsem); + return asrv->gen; +} + +/* + * Whether instance @gen has a published successor, waiting for one as + * dcp_audiosrv_open() does: the firmware refuses calls to an instance it is + * replacing, and publishes the successor within some hundred milliseconds. + */ +bool dcp_audiosrv_replaced(struct device *dev, u64 gen) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + struct audiosrv_data *asrv = dcp->audiosrv; + + if (!asrv) + return false; + if (wait_event_interruptible_timeout(asrv->gen_wq, + READ_ONCE(asrv->srv) && READ_ONCE(asrv->gen) != gen, + msecs_to_jiffies(AV_AUDIOSRV_REPLACE_MS)) < 0) + return false; + guard(rwsem_read)(&asrv->srv_rwsem); + return asrv->srv && asrv->gen != gen; +} /* * The 14.7 external role: the service is open while a PCM is (see @@ -617,12 +673,12 @@ dcp_audiosrv_osobject_call(struct apple_epic_service *service, u16 group, static_assert(sizeof(*hdr) == 48); size_t received = 0, used; size_t bfr_len = output_maxsize + sizeof(*hdr); - void *bfr __free(kfree) = NULL; + void *bfr __free(kvfree) = NULL; int ret; KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_osobject_call, service, group, command, output, output_maxsize, output_size); - bfr = kzalloc(bfr_len, GFP_KERNEL); + bfr = kvzalloc(bfr_len, GFP_KERNEL); if (!bfr) return -ENOMEM; @@ -686,13 +742,16 @@ static bool av_elements_need_more(int ret, size_t size, size_t cap, bool empty) int dcp_audiosrv_get_elements(struct device *dev, void *elements, size_t maxsize) { - struct apple_dcp *dcp = dev_get_drvdata(dev); - struct audiosrv_data *asrv = dcp->audiosrv; + struct apple_dcp *dcp; + struct audiosrv_data *asrv; struct apple_epic_service *srv; size_t size = 0, cap; bool compact, empty; int ret; + KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_get_elements, dev, elements, maxsize); + dcp = dev_get_drvdata(dev); + asrv = dcp->audiosrv; if (!asrv) return -ENODEV; scoped_guard(rwsem_read, &asrv->srv_rwsem) @@ -740,12 +799,15 @@ int dcp_audiosrv_get_elements(struct device *dev, void *elements, size_t maxsize int dcp_audiosrv_get_product_attrs(struct device *dev, void *attrs, size_t maxsize) { - struct apple_dcp *dcp = dev_get_drvdata(dev); - struct audiosrv_data *asrv = dcp->audiosrv; + struct apple_dcp *dcp; + struct audiosrv_data *asrv; struct apple_epic_service *srv; size_t size; int ret; + KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_get_product_attrs, dev, attrs, maxsize); + dcp = dev_get_drvdata(dev); + asrv = dcp->audiosrv; if (!asrv) return -ENODEV; scoped_guard(rwsem_read, &asrv->srv_rwsem) @@ -1018,12 +1080,14 @@ static const struct apple_epic_service_ops avep_ops[] = { { .name = "DCPAVSimpleVideoInterface", .reusable = true, + .singleton = true, .init = av_interface_init, .teardown = av_interface_teardown, }, { .name = "DCPAVAudioInterface", .reusable = true, + .singleton = true, .init = av_audiosrv_init, .report = av_audiosrv_report, .teardown = av_audiosrv_teardown, @@ -1039,10 +1103,32 @@ static const struct apple_epic_service_ops avep_ops[] = { {} }; +void av_audio_sink_changed(struct apple_dcp *dcp) +{ + struct audiosrv_data *asrv = dcp->audiosrv; + + /* A CEC-only endpoint has no audio owner (av_service_connect()). */ + if (!asrv) + return; + scoped_guard(mutex, &asrv->plug_lock) { + if (asrv->audio_dev) + dcpaud_refresh_eld(asrv->audio_dev); + } +} + +/* Whether @service is the published instance; plug_lock held, then srv_rwsem */ +static bool av_audiosrv_published(struct audiosrv_data *asrv, + struct apple_epic_service *service) +{ + guard(rwsem_read)(&asrv->srv_rwsem); + return asrv->srv == service; +} + void av_service_connect(struct apple_dcp *dcp) { struct apple_epic_service *service; struct audiosrv_data *asrv = dcp->audiosrv; + bool opened; int ret; /* @@ -1061,7 +1147,9 @@ void av_service_connect(struct apple_dcp *dcp) /* open AV audio service */ dev_info(dcp->dev, "%s: starting audio service, plugged:%d\n", __func__, asrv->plugged); - if (asrv->is_open) + scoped_guard(mutex, &asrv->plug_lock) + opened = asrv->is_open; + if (opened) goto out; #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) @@ -1096,16 +1184,34 @@ void av_service_connect(struct apple_dcp *dcp) ret = afk_service_call(service, 0, asrv->cmds.open, NULL, 0, 32, NULL, 0, 32); + if (ret == -EINVAL) { + /* + * The firmware refuses an Open on an instance it is replacing (a + * resume, a modeset), and publishes the successor, whose own + * connect opens it, within AV_AUDIOSRV_REPLACE_MS. Judge the + * refusal then, so a lasting one is still reported. + */ + WRITE_ONCE(asrv->open_refused, ret); + mod_delayed_work(system_wq, &asrv->open_check_wq, + msecs_to_jiffies(AV_AUDIOSRV_REPLACE_MS)); + goto out; + } if (ret) { dev_err(dcp->dev, "error opening audio service: %d\n", ret); goto out; } - mutex_lock(&asrv->plug_lock); - asrv->is_open = true; - - if (asrv->audio_dev) - dcpaud_connect(asrv->audio_dev, asrv->plugged); - mutex_unlock(&asrv->plug_lock); + /* + * The Open ran without locks: it is this instance's only if the + * instance is still the published one. A successor published meanwhile + * is opened by its own connect. + */ + scoped_guard(mutex, &asrv->plug_lock) { + if (av_audiosrv_published(asrv, service)) { + asrv->is_open = true; + if (asrv->audio_dev) + dcpaud_connect(asrv->audio_dev, asrv->plugged); + } + } out: afk_service_put(service); } @@ -1137,6 +1243,7 @@ static void __av_service_disconnect(struct apple_dcp *dcp, const u64 *gen) { struct apple_epic_service *service; struct audiosrv_data *asrv = dcp->audiosrv; + bool opened; int ret; /* A CEC-only endpoint has no audio owner (av_service_connect()). */ @@ -1188,16 +1295,15 @@ static void __av_service_disconnect(struct apple_dcp *dcp, const u64 *gen) goto out; } #endif - if (!asrv->is_open) + /* Only the published instance's Open is closed, and only once. */ + scoped_guard(mutex, &asrv->plug_lock) { + opened = asrv->is_open && av_audiosrv_published(asrv, service); + if (opened && asrv->audio_dev) + dcpaud_disconnect(asrv->audio_dev); + } + if (!opened) goto out; - mutex_lock(&asrv->plug_lock); - - if (asrv->audio_dev) - dcpaud_disconnect(asrv->audio_dev); - - mutex_unlock(&asrv->plug_lock); - ret = afk_service_call(service, 0, asrv->cmds.close, NULL, 0, 16, NULL, 0, 16); if (ret) { @@ -1205,7 +1311,11 @@ static void __av_service_disconnect(struct apple_dcp *dcp, const u64 *gen) } if (service->torndown) afk_service_disable(service); - asrv->is_open = false; + /* A successor published meanwhile keeps its own state. */ + scoped_guard(mutex, &asrv->plug_lock) { + if (av_audiosrv_published(asrv, service)) + asrv->is_open = false; + } out: afk_service_put(service); } @@ -1252,8 +1362,28 @@ static void av_work_service_start(struct work_struct *work) av_service_connect(dcp); } +/* A refused classic Open, AV_AUDIOSRV_REPLACE_MS later (av_service_connect()) */ +static void av_work_open_check(struct work_struct *work) +{ + struct audiosrv_data *asrv = + container_of(to_delayed_work(work), struct audiosrv_data, open_check_wq); + int ret = READ_ONCE(asrv->open_refused); + bool opened, gone; + + scoped_guard(mutex, &asrv->plug_lock) { + opened = asrv->is_open; + gone = !READ_ONCE(asrv->srv); + } + if (opened || gone) + dev_dbg(asrv->open_check_dev, "audio service Open refused (%d) by an instance since %s\n", + ret, opened ? "replaced" : "removed"); + else + dev_err(asrv->open_check_dev, "error opening audio service: %d\n", ret); +} + static void av_audiosrv_flush_owner(struct audiosrv_data *asrv) { + flush_delayed_work(&asrv->open_check_wq); flush_work(&asrv->start_av_service_wq); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) flush_work(&asrv->terminate_wq); @@ -1282,6 +1412,7 @@ static bool av_audiosrv_drain_owner(struct audiosrv_data *asrv) */ if (first_stop) { disable_work_sync(&asrv->start_av_service_wq); + disable_delayed_work_sync(&asrv->open_check_wq); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) disable_work_sync(&asrv->terminate_wq); #endif @@ -1382,6 +1513,7 @@ void av_audiosrv_reports_restart(struct apple_dcp *dcp) } asrv->work_disabled = false; enable_work(&asrv->start_av_service_wq); + enable_delayed_work(&asrv->open_check_wq); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) enable_work(&asrv->terminate_wq); #endif @@ -1452,11 +1584,9 @@ int avep_init(struct apple_dcp *dcp) case DCP_FIRMWARE_V_26_6_DESKTOP: audiosrv_data->cmds = dcp_av_audio_cmds_v13_5; break; -#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) case DCP_FIRMWARE_V_27_0: audiosrv_data->cmds = dcp_av_audio_cmds_v27; break; -#endif default: #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) /* @@ -1476,6 +1606,8 @@ int avep_init(struct apple_dcp *dcp) } INIT_WORK(&audiosrv_data->start_av_service_wq, av_work_service_start); + INIT_DELAYED_WORK(&audiosrv_data->open_check_wq, av_work_open_check); + audiosrv_data->open_check_dev = dcp->dev; #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) INIT_WORK(&audiosrv_data->terminate_wq, av_work_service_terminate); mutex_init(&audiosrv_data->open_lock); diff --git a/drivers/gpu/drm/apple/av.h b/drivers/gpu/drm/apple/av.h index 82b5cc3388fd86..c41a853a573822 100644 --- a/drivers/gpu/drm/apple/av.h +++ b/drivers/gpu/drm/apple/av.h @@ -12,6 +12,8 @@ extern bool hdmi_audio; #if IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) void av_service_connect(struct apple_dcp *dcp); void av_service_disconnect(struct apple_dcp *dcp); +/* The sink's EDID was published again: a connected card takes its ELD. */ +void av_audio_sink_changed(struct apple_dcp *dcp); /* Stop and drain owner work after the caller stops its native initializer. */ void av_audiosrv_quiesce(struct apple_dcp *dcp); /* Pair of av_audiosrv_quiesce after a later successful bind. */ @@ -25,6 +27,7 @@ static inline void av_audio_before_modeset(struct apple_dcp *dcp) { } #else static inline void av_service_connect(struct apple_dcp *dcp) { } static inline void av_service_disconnect(struct apple_dcp *dcp) { } +static inline void av_audio_sink_changed(struct apple_dcp *dcp) { } static inline void av_audiosrv_quiesce(struct apple_dcp *dcp) { } static inline void av_audiosrv_reports_restart(struct apple_dcp *dcp) { } static inline void av_audio_before_modeset(struct apple_dcp *dcp) { } diff --git a/drivers/gpu/drm/apple/cec_adap_test.c b/drivers/gpu/drm/apple/cec_adap_test.c index 61a30501b3ef7d..d4b560c96fc68a 100644 --- a/drivers/gpu/drm/apple/cec_adap_test.c +++ b/drivers/gpu/drm/apple/cec_adap_test.c @@ -159,12 +159,13 @@ static struct dcp_cec_test_ctx *dcp_cec_test_setup(struct kunit *test) KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); spin_lock_init(&ctx->lock); - ctx->dev = kunit_device_register(test, "apple-dcp-cec-kunit"); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); - + /* + * The fakes are allocated before the device: KUnit frees in reverse + * order, and the device's devres (dcp_cec_devm_release()) still uses + * them when the device is unregistered. + */ ctx->dcp = kunit_kzalloc(test, sizeof(*ctx->dcp), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dcp); - ctx->dcp->dev = ctx->dev; ctx->dcp->fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA; ctx->ep = kunit_kzalloc(test, sizeof(*ctx->ep), GFP_KERNEL); @@ -173,6 +174,10 @@ static struct dcp_cec_test_ctx *dcp_cec_test_setup(struct kunit *test) ctx->ep->endpoint = AV_AUDIO_ENDPOINT_DESKTOP; ctx->ep->compact = true; + ctx->dev = kunit_device_register(test, "apple-dcp-cec-kunit"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + ctx->dcp->dev = ctx->dev; + ctx->port_srv.ep = ctx->ep; ctx->dcp->dptxport[0].service = &ctx->port_srv; diff --git a/drivers/gpu/drm/apple/connector.c b/drivers/gpu/drm/apple/connector.c index f3953abda34212..e3c8c876a215ae 100644 --- a/drivers/gpu/drm/apple/connector.c +++ b/drivers/gpu/drm/apple/connector.c @@ -11,6 +11,7 @@ #include #include #include +#include #include @@ -84,7 +85,7 @@ static int chunk_show(struct seq_file *m, } if (chunk) - seq_write(m, chunk->data, chunk->length); + seq_write(m, chunk->data, chunk->length); mutex_unlock(&apple_con->chunk_lock); @@ -94,18 +95,18 @@ static int chunk_show(struct seq_file *m, #define CONNECTOR_DEBUGFS_ENTRY(name, type) \ static int chunk_ ## name ## _show(struct seq_file *m, void *data) \ { \ - return chunk_show(m, type); \ + return chunk_show(m, type); \ } \ static int chunk_ ## name ## _open(struct inode *inode, struct file *file) \ { \ - return single_open(file, chunk_ ## name ## _show, inode->i_private); \ + return single_open(file, chunk_ ## name ## _show, inode->i_private); \ } \ static const struct file_operations chunk_ ## name ## _fops = { \ - .owner = THIS_MODULE, \ - .open = chunk_ ## name ## _open, \ - .read = seq_read, \ - .llseek = seq_lseek, \ - .release = single_release, \ + .owner = THIS_MODULE, \ + .open = chunk_ ## name ## _open, \ + .read = seq_read, \ + .llseek = seq_lseek, \ + .release = single_release, \ } CONNECTOR_DEBUGFS_ENTRY(color, DCP_CHUNK_COLOR_ELEMENTS); @@ -113,6 +114,151 @@ CONNECTOR_DEBUGFS_ENTRY(timing, DCP_CHUNK_TIMING_ELELMENTS); CONNECTOR_DEBUGFS_ENTRY(display_attribs, DCP_CHUNK_DISPLAY_ATTRIBUTES); CONNECTOR_DEBUGFS_ENTRY(transport, DCP_CHUNK_TRANSPORT); +static const char *dcp_color_format_name(u8 format) +{ + switch (format) { + case DCP_COLOR_FORMAT_RGB: + return "RGB"; + case DCP_COLOR_FORMAT_YCBCR420: + return "YCbCr420"; + case DCP_COLOR_FORMAT_YCBCR444: + return "YCbCr444"; + case DCP_COLOR_FORMAT_YCBCR422: + return "YCbCr422"; + case DCP_COLOR_FORMAT_YCBCR422_DP: + return "YCbCr422_DP"; + case DCP_COLOR_FORMAT_YCBCR422_HDMI: + return "YCbCr422_HDMI"; + default: + return "other"; + } +} + +static const char *dcp_color_eotf_name(u8 eotf) +{ + switch (eotf) { + case DCP_EOTF_SDR_GAMMA: + return "SDR"; + case DCP_EOTF_HDR_GAMMA: + return "HDR_gamma"; + case DCP_EOTF_ST_2084: + return "PQ"; + case DCP_EOTF_BT_2100: + return "HLG"; + default: + return "other"; + } +} + +static const char *dcp_colorimetry_name(u8 colorimetry) +{ + switch (colorimetry) { + case DCP_COLORIMETRY_BT601: + return "BT601"; + case DCP_COLORIMETRY_BT709: + return "BT709"; + case DCP_COLORIMETRY_XVYCC_601: + return "xvYCC601"; + case DCP_COLORIMETRY_XVYCC_709: + return "xvYCC709"; + case DCP_COLORIMETRY_SYCC_601: + return "sYCC601"; + case DCP_COLORIMETRY_ADOBE_YCC_601: + return "AdobeYCC601"; + case DCP_COLORIMETRY_BT2020_CYCC: + return "BT2020_CYCC"; + case DCP_COLORIMETRY_BT2020_YCC: + return "BT2020_YCC"; + case DCP_COLORIMETRY_BT2020_RGB: + return "BT2020_RGB"; + case DCP_COLORIMETRY_SRGB: + return "sRGB"; + case DCP_COLORIMETRY_SCRGB: + return "scRGB"; + case DCP_COLORIMETRY_SCRGB_FIXED: + return "scRGB_fixed"; + case DCP_COLORIMETRY_ADOBE_RGB: + return "AdobeRGB"; + case DCP_COLORIMETRY_DCI_P3_RGB_D65: + return "DCI_P3_D65"; + case DCP_COLORIMETRY_DCI_P3_RGB_THEATER: + return "DCI_P3_Theater"; + case DCP_COLORIMETRY_RGB: + return "Default_RGB"; + default: + return "other"; + } +} + +static int color_state_show(struct seq_file *m, void *data) +{ + struct apple_connector *apple_con = m->private; + struct platform_device *pdev = READ_ONCE(apple_con->dcp); + struct apple_dcp *dcp; + struct dcp_color_mode cm; + u8 sent[24] = {}; + bool hdr_service, hdr_infoframe, hdr_sent_valid; + u32 timing_id, color_id; + + bool vrr_enabled, output_pq, output_hdr, output_edr; + + if (!pdev) { + seq_puts(m, "pipeline: none\n"); + return 0; + } + dcp = platform_get_drvdata(pdev); + if (!dcp) { + seq_puts(m, "pipeline: unbound\n"); + return 0; + } + + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + timing_id = dcp->mode.timing_mode_id; + color_id = dcp->mode.color_mode_id; + cm = dcp->active_color; + vrr_enabled = dcp->vrr_enabled; + output_pq = dcp->output_pq; + output_hdr = dcp->output_hdr; + output_edr = dcp->output_edr; + hdr_service = !!dcp->hdr.service; + hdr_infoframe = dcp->hdr.infoframe; + hdr_sent_valid = dcp->hdr.sent_valid; + if (hdr_sent_valid) + memcpy(sent, dcp->hdr.sent, sizeof(sent)); + } + + seq_printf(m, "timing_id: %u\n", timing_id); + seq_printf(m, "color_id: %u\n", color_id); + if (cm.score >= 0) { + seq_printf(m, "depth: %u\n", cm.depth); + seq_printf(m, "format: %s (%u)\n", dcp_color_format_name(cm.format), cm.format); + seq_printf(m, "colorimetry: %s (%u)\n", + dcp_colorimetry_name(cm.colorimetry), cm.colorimetry); + seq_printf(m, "eotf: %s (%u)\n", dcp_color_eotf_name(cm.eotf), cm.eotf); + seq_printf(m, "range: %s (%u)\n", + cm.range == DCP_COLOR_YCBCR_RANGE_FULL ? "Full" : "Limited", + cm.range); + } else { + seq_puts(m, "depth: none\n"); + } + seq_printf(m, "vrr_enabled: %u\n", vrr_enabled); + seq_printf(m, "output_pq: %u\n", output_pq); + seq_printf(m, "output_hdr: %u\n", output_hdr); + seq_printf(m, "output_edr: %u\n", output_edr); + seq_printf(m, "hdr_service: %u\n", hdr_service); + seq_printf(m, "hdr_infoframe: %u\n", hdr_infoframe); + seq_printf(m, "hdr_sent_valid: %u\n", hdr_sent_valid); + if (hdr_sent_valid) { + seq_printf(m, "hdr_mastering_max: %u\n", get_unaligned_le16(sent + 16)); + seq_printf(m, "hdr_mastering_min: %u\n", get_unaligned_le16(sent + 18)); + seq_printf(m, "hdr_max_cll: %u\n", get_unaligned_le16(sent + 20)); + seq_printf(m, "hdr_max_fall: %u\n", get_unaligned_le16(sent + 22)); + } + return 0; +} + +DEFINE_SHOW_ATTRIBUTE(color_state); + static void dcp_afk_debugfs_root(struct platform_device *pdev, int ep, struct dentry *root) { #if IS_ENABLED(CONFIG_DRM_APPLE_DEBUG) @@ -155,7 +301,9 @@ void apple_connector_debugfs_init(struct drm_connector *connector, struct dentry debugfs_create_file("DisplayAttributes", 0444, root, apple_con, &chunk_display_attribs_fops); debugfs_create_file("Transport", 0444, root, apple_con, - &chunk_transport_fops); + &chunk_transport_fops); + debugfs_create_file("color_state", 0444, root, apple_con, + &color_state_fops); switch (connector->connector_type) { case DRM_MODE_CONNECTOR_DisplayPort: diff --git a/drivers/gpu/drm/apple/dcp-color.h b/drivers/gpu/drm/apple/dcp-color.h new file mode 100644 index 00000000000000..e9a683dcde9bc4 --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-color.h @@ -0,0 +1,355 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * Output colour mode selection for Apple DCP external displays. + * + * Maps standard DRM connector properties (HDR_OUTPUT_METADATA EOTF, + * Colorspace, color format, Broadcast RGB, max bpc) onto the per-timing + * ColorModes catalogue reported by DCP firmware. + */ +#ifndef __APPLE_DCP_COLOR_H__ +#define __APPLE_DCP_COLOR_H__ + +#include +#include +#include +#include + +#include "parser.h" + +struct dcp_color_request { + u8 eotf; /* enum hdmi_eotf */ + u8 colorspace; /* enum drm_colorspace */ + u8 color_format; /* enum drm_connector_color_format */ + u8 broadcast_rgb; /* enum drm_hdmi_broadcast_rgb */ + u8 max_bpc; /* 0 (uncapped) or 8..12 */ + bool allow_hdr; + bool allow_dsc; + bool allow_unsafe_sdr; + bool default_rgb; +}; + +static inline bool dcp_color_request_is_default(const struct dcp_color_request *req) +{ + return req->color_format == DRM_CONNECTOR_COLOR_FORMAT_AUTO && + req->broadcast_rgb == DRM_HDMI_BROADCAST_RGB_AUTO && + (!req->max_bpc || req->max_bpc >= 12); +} + +static inline bool dcp_color_format_is_ycbcr422(u8 format) +{ + return format == DCP_COLOR_FORMAT_YCBCR422 || + format == DCP_COLOR_FORMAT_YCBCR422_DP || + format == DCP_COLOR_FORMAT_YCBCR422_HDMI; +} + +static inline u8 dcp_color_entry_format(const struct dcp_color_entry *e) +{ + if (e->flags & DCP_COLOR_FLAG_DOWNSTREAM_420) + return DCP_COLOR_FORMAT_YCBCR420; + return e->format; +} + +static inline u8 dcp_color_wire_bpp(u8 format, u8 depth) +{ + if (format == DCP_COLOR_FORMAT_YCBCR420) + return (depth * 3) / 2; + if (dcp_color_format_is_ycbcr422(format)) + return depth * 2; + return depth * 3; +} + +static inline bool dcp_color_format_matches(u8 fmt, u8 req_fmt) +{ + switch (req_fmt) { + case DRM_CONNECTOR_COLOR_FORMAT_AUTO: + return fmt == DCP_COLOR_FORMAT_RGB || + fmt == DCP_COLOR_FORMAT_YCBCR444 || + dcp_color_format_is_ycbcr422(fmt) || + fmt == DCP_COLOR_FORMAT_YCBCR420; + case DRM_CONNECTOR_COLOR_FORMAT_RGB444: + return fmt == DCP_COLOR_FORMAT_RGB; + case DRM_CONNECTOR_COLOR_FORMAT_YCBCR444: + return fmt == DCP_COLOR_FORMAT_YCBCR444; + case DRM_CONNECTOR_COLOR_FORMAT_YCBCR422: + return dcp_color_format_is_ycbcr422(fmt); + case DRM_CONNECTOR_COLOR_FORMAT_YCBCR420: + return fmt == DCP_COLOR_FORMAT_YCBCR420; + default: + return false; + } +} + +static inline bool dcp_color_eotf_matches(u8 eotf, const struct dcp_color_request *req) +{ + switch (req->eotf) { + case HDMI_EOTF_TRADITIONAL_GAMMA_SDR: + return eotf == DCP_EOTF_SDR_GAMMA; + case HDMI_EOTF_TRADITIONAL_GAMMA_HDR: + return req->allow_hdr && eotf == DCP_EOTF_HDR_GAMMA; + case HDMI_EOTF_SMPTE_ST2084: + return req->allow_hdr && eotf == DCP_EOTF_ST_2084; + case HDMI_EOTF_BT_2100_HLG: + return req->allow_hdr && eotf == DCP_EOTF_BT_2100; + default: + return false; + } +} + +static inline bool dcp_color_range_matches(u8 range, u8 broadcast_rgb) +{ + switch (broadcast_rgb) { + case DRM_HDMI_BROADCAST_RGB_AUTO: + return true; + case DRM_HDMI_BROADCAST_RGB_FULL: + return range == DCP_COLOR_YCBCR_RANGE_FULL; + case DRM_HDMI_BROADCAST_RGB_LIMITED: + return range == DCP_COLOR_YCBCR_RANGE_LIMITED; + default: + return false; + } +} + +static inline bool dcp_color_space_matches(u8 colorimetry, + const struct dcp_color_request *req) +{ + bool hdr = req->eotf != HDMI_EOTF_TRADITIONAL_GAMMA_SDR; + + switch (req->colorspace) { + case DRM_MODE_COLORIMETRY_DEFAULT: + if (hdr) + return colorimetry == DCP_COLORIMETRY_BT2020_RGB || + colorimetry == DCP_COLORIMETRY_BT2020_YCC || + colorimetry == DCP_COLORIMETRY_BT2020_CYCC; + return true; + case DRM_MODE_COLORIMETRY_BT2020_RGB: + if (colorimetry == DCP_COLORIMETRY_BT2020_RGB) + return true; + /* + * Compositors (e.g. Mutter) request BT2020_RGB with AUTO format + * for HDR even on timings where only YCbCr BT.2020 is safe. + */ + return hdr && + req->color_format == DRM_CONNECTOR_COLOR_FORMAT_AUTO && + colorimetry == DCP_COLORIMETRY_BT2020_YCC; + case DRM_MODE_COLORIMETRY_BT2020_YCC: + return colorimetry == DCP_COLORIMETRY_BT2020_YCC; + case DRM_MODE_COLORIMETRY_BT2020_CYCC: + return colorimetry == DCP_COLORIMETRY_BT2020_CYCC; + case DRM_MODE_COLORIMETRY_BT709_YCC: + return colorimetry == DCP_COLORIMETRY_BT709; + case DRM_MODE_COLORIMETRY_SMPTE_170M_YCC: + case DRM_MODE_COLORIMETRY_BT601_YCC: + return colorimetry == DCP_COLORIMETRY_BT601; + case DRM_MODE_COLORIMETRY_XVYCC_601: + return colorimetry == DCP_COLORIMETRY_XVYCC_601; + case DRM_MODE_COLORIMETRY_XVYCC_709: + return colorimetry == DCP_COLORIMETRY_XVYCC_709; + case DRM_MODE_COLORIMETRY_SYCC_601: + return colorimetry == DCP_COLORIMETRY_SYCC_601; + case DRM_MODE_COLORIMETRY_OPYCC_601: + return colorimetry == DCP_COLORIMETRY_ADOBE_YCC_601; + case DRM_MODE_COLORIMETRY_OPRGB: + return colorimetry == DCP_COLORIMETRY_ADOBE_RGB; + case DRM_MODE_COLORIMETRY_DCI_P3_RGB_D65: + return colorimetry == DCP_COLORIMETRY_DCI_P3_RGB_D65; + case DRM_MODE_COLORIMETRY_DCI_P3_RGB_THEATER: + return colorimetry == DCP_COLORIMETRY_DCI_P3_RGB_THEATER; + case DRM_MODE_COLORIMETRY_RGB_WIDE_FIXED: + return colorimetry == DCP_COLORIMETRY_SCRGB_FIXED; + case DRM_MODE_COLORIMETRY_RGB_WIDE_FLOAT: + return colorimetry == DCP_COLORIMETRY_SCRGB; + default: + return false; + } +} + +static inline u32 dcp_color_entry_rank(const struct dcp_color_entry *e, + const struct dcp_color_request *req) +{ + u32 fmt_rank, space_rank, depth_rank, range_rank, dsc_rank; + bool hdr = req->eotf != HDMI_EOTF_TRADITIONAL_GAMMA_SDR; + u8 fmt = dcp_color_entry_format(e); + + switch (fmt) { + case DCP_COLOR_FORMAT_RGB: + fmt_rank = 6; + break; + case DCP_COLOR_FORMAT_YCBCR444: + fmt_rank = 5; + break; + case DCP_COLOR_FORMAT_YCBCR422: + fmt_rank = 4; + break; + case DCP_COLOR_FORMAT_YCBCR422_DP: + fmt_rank = 3; + break; + case DCP_COLOR_FORMAT_YCBCR422_HDMI: + fmt_rank = 2; + break; + case DCP_COLOR_FORMAT_YCBCR420: + fmt_rank = 1; + break; + default: + fmt_rank = 0; + break; + } + + if (hdr) { + if (e->colorimetry == DCP_COLORIMETRY_BT2020_RGB) + space_rank = 3; + else if (e->colorimetry == DCP_COLORIMETRY_BT2020_YCC) + space_rank = 2; + else + space_rank = 1; + } else if (req->colorspace == DRM_MODE_COLORIMETRY_DEFAULT) { + if (fmt == DCP_COLOR_FORMAT_RGB) { + if (req->default_rgb && e->colorimetry == DCP_COLORIMETRY_RGB) + space_rank = 4; + else if (e->colorimetry == DCP_COLORIMETRY_SRGB || + e->colorimetry == DCP_COLORIMETRY_BT709) + space_rank = 3; + else if (e->colorimetry == DCP_COLORIMETRY_RGB) + space_rank = 2; + else + space_rank = 1; + } else { + if (e->colorimetry == DCP_COLORIMETRY_BT709) + space_rank = 3; + else if (e->colorimetry == DCP_COLORIMETRY_BT601) + space_rank = 2; + else + space_rank = 1; + } + } else { + space_rank = 1; + } + + if (req->eotf == HDMI_EOTF_SMPTE_ST2084 && + req->color_format == DRM_CONNECTOR_COLOR_FORMAT_AUTO) { + /* Match pq_mode_rank(): 10 bpc fits HDR framebuffers directly. */ + depth_rank = e->depth == 10 ? 3 : (e->depth == 12 ? 2 : 1); + } else { + depth_rank = e->depth; + } + + if (fmt == DCP_COLOR_FORMAT_RGB) + range_rank = e->range == DCP_COLOR_YCBCR_RANGE_FULL ? 2 : 1; + else + range_rank = e->range == DCP_COLOR_YCBCR_RANGE_LIMITED ? 2 : 1; + + dsc_rank = (e->flags & DCP_COLOR_FLAG_DSC) ? 0 : 1; + + return (fmt_rank << 16) | (space_rank << 12) | (depth_rank << 6) | + (range_rank << 2) | dsc_rank; +} + +static inline void dcp_color_mode_from_entry(struct dcp_color_mode *out, + const struct dcp_color_entry *e) +{ + out->score = 0; + out->id = e->id; + out->eotf = e->eotf; + out->format = dcp_color_entry_format(e); + out->colorimetry = e->colorimetry; + out->range = e->range; + out->depth = e->depth; +} + +static inline int dcp_default_sdr_color(const struct dcp_display_mode *mode, + struct dcp_color_mode *out) +{ + const struct dcp_color_mode *cmode = NULL; + unsigned int i; + + if (mode->color_mode_id == mode->sdr_rgb.id && mode->sdr_rgb.score >= 0) + cmode = &mode->sdr_rgb; + else if (mode->color_mode_id == mode->sdr_444.id && mode->sdr_444.score >= 0) + cmode = &mode->sdr_444; + else if (mode->color_mode_id == mode->sdr.id && mode->sdr.score >= 0) + cmode = &mode->sdr; + else if (mode->color_mode_id == mode->best.id && mode->best.score >= 0) + cmode = &mode->best; + + if (cmode) { + *out = *cmode; + for (i = 0; i < mode->nr_colors; i++) { + if (mode->colors[i].id == out->id) { + out->format = dcp_color_entry_format(&mode->colors[i]); + break; + } + } + return 0; + } + return -EINVAL; +} + +static inline int dcp_select_color_mode(const struct dcp_display_mode *mode, + const struct dcp_color_request *req, + struct dcp_color_mode *out) +{ + u8 max_bpc = req->max_bpc ? req->max_bpc : 12; + bool hdr = req->eotf != HDMI_EOTF_TRADITIONAL_GAMMA_SDR; + unsigned int pass, max_pass, i; + const struct dcp_color_entry *best = NULL; + u32 best_rank = 0; + + if (dcp_color_request_is_default(req)) { + if (req->eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR && + req->colorspace == DRM_MODE_COLORIMETRY_DEFAULT) + return dcp_default_sdr_color(mode, out); + if (req->eotf == HDMI_EOTF_SMPTE_ST2084 && + (req->colorspace == DRM_MODE_COLORIMETRY_DEFAULT || + req->colorspace == DRM_MODE_COLORIMETRY_BT2020_RGB)) { + if (!req->allow_hdr || mode->pq.score < 0) + return -EINVAL; + *out = mode->pq; + return 0; + } + } + + if (hdr && !req->allow_hdr) + return -EINVAL; + + max_pass = (req->allow_unsafe_sdr && !mode->sdr_usable && mode->sdr_unsafe) ? 2 : 1; + for (pass = 0; pass < max_pass && !best; pass++) { + bool allow_unsafe = pass > 0; + + for (i = 0; i < mode->nr_colors; i++) { + const struct dcp_color_entry *e = &mode->colors[i]; + u8 fmt = dcp_color_entry_format(e); + u32 rank; + + if ((e->flags & DCP_COLOR_FLAG_UNSAFE) && !allow_unsafe) + continue; + if ((e->flags & DCP_COLOR_FLAG_DSC) && hdr && + (!req->allow_dsc || allow_unsafe)) + continue; + if (allow_unsafe && hdr && mode->sdr_unsafe_max_bpp && + dcp_color_wire_bpp(fmt, e->depth) > mode->sdr_unsafe_max_bpp) + continue; + if (e->depth > max_bpc) + continue; + if (!dcp_color_eotf_matches(e->eotf, req)) + continue; + if (!dcp_color_format_matches(fmt, req->color_format)) + continue; + if (!dcp_color_range_matches(e->range, req->broadcast_rgb)) + continue; + if (!dcp_color_space_matches(e->colorimetry, req)) + continue; + rank = dcp_color_entry_rank(e, req); + /* Entries are sorted by descending firmware score: keep first on ties. */ + if (!best || rank > best_rank) { + best = e; + best_rank = rank; + } + } + } + + if (!best) + return -EINVAL; + dcp_color_mode_from_entry(out, best); + return 0; +} + +#endif /* __APPLE_DCP_COLOR_H__ */ diff --git a/drivers/gpu/drm/apple/dcp-display-metadata.c b/drivers/gpu/drm/apple/dcp-display-metadata.c index bcc3f70d8db7ac..1e393c2ea9d2b0 100644 --- a/drivers/gpu/drm/apple/dcp-display-metadata.c +++ b/drivers/gpu/drm/apple/dcp-display-metadata.c @@ -198,6 +198,19 @@ const struct dcp_color_space *dcp_panel_gamut_color_space(enum dcp_panel_gamut g } } +/* + * An internal panel's colour target: the standard space its ADT names, or + * else Display P3. Every untagged RGB surface on an internal panel is tagged + * P3-D65 (see iomfb_template.c), so a panel whose ADT names no space known + * here (the K114s says "Rec2020") is described in the space it is driven in. + * Zero primaries are no description: compositors build a singular + * conversion matrix from them. + */ +const struct dcp_color_space *dcp_panel_color_target(enum dcp_panel_gamut gamut) +{ + return dcp_panel_gamut_color_space(gamut) ?: dcp_color_space_lookup("display-p3"); +} + /* * Firmware chromaticities win. Without a complete, valid set, use the panel's * named target. Without either the block keeps its nominal white only. diff --git a/drivers/gpu/drm/apple/dcp-display-metadata.h b/drivers/gpu/drm/apple/dcp-display-metadata.h index 20ba07d691fe70..9a12bebaacbf21 100644 --- a/drivers/gpu/drm/apple/dcp-display-metadata.h +++ b/drivers/gpu/drm/apple/dcp-display-metadata.h @@ -50,6 +50,7 @@ struct dcp_color_space { const struct dcp_color_space *dcp_color_space_lookup(const char *name); const struct dcp_color_space *dcp_panel_gamut_color_space(enum dcp_panel_gamut gamut); +const struct dcp_color_space *dcp_panel_color_target(enum dcp_panel_gamut gamut); struct drm_edid; struct drm_display_mode; diff --git a/drivers/gpu/drm/apple/dcp-edr.h b/drivers/gpu/drm/apple/dcp-edr.h index 0bfb0bf72660db..fc5dc03e6f53f7 100644 --- a/drivers/gpu/drm/apple/dcp-edr.h +++ b/drivers/gpu/drm/apple/dcp-edr.h @@ -35,7 +35,8 @@ /* * The panel's potential headroom, the ADT backlight node's * EDRPotentialHeadroom (16.16), as a ceiling x1000. macOS never gives the - * panel more. 0: no ceiling, for a value that is missing or not above 1.0. + * panel more. 0: the panel has no EDR headroom (a value missing or not + * above 1.0), so it gets no peak and the EDR path never runs for it. */ static inline u32 dcp_edr_ceiling(u32 fixed) { diff --git a/drivers/gpu/drm/apple/dcp-fabric-effects.h b/drivers/gpu/drm/apple/dcp-fabric-effects.h index 3f4ad7c7eb52d3..60a99a96341d7a 100644 --- a/drivers/gpu/drm/apple/dcp-fabric-effects.h +++ b/drivers/gpu/drm/apple/dcp-fabric-effects.h @@ -231,6 +231,12 @@ dcp_fabric_run_rebalance(const struct dcp_fabric_rebalance_ops *ops, void *ctx) } } +static inline bool dcp_fabric_has_available_routes(bool has_container, + unsigned int available_children) +{ + return has_container && available_children > 0; +} + static inline int dcp_fabric_run_probe(bool has_routes, int (*register_routes)(void *ctx), void *ctx) { diff --git a/drivers/gpu/drm/apple/dcp-fabric-test.c b/drivers/gpu/drm/apple/dcp-fabric-test.c index 254b1bb74358d5..6e3f69ba68c80b 100644 --- a/drivers/gpu/drm/apple/dcp-fabric-test.c +++ b/drivers/gpu/drm/apple/dcp-fabric-test.c @@ -242,7 +242,6 @@ static const struct fabric_scenario scenarios[] = { { "S32_dual_hdmi_reclaim_core", 32 }, { "S33_dual_scores", 33 }, { "S34_dual_park_reselect", 34 }, - { "S35_dual_retry_off", 35 }, { "S40_desktop_promotion", 40 }, { "S41_dedicated_hdmi", 41 }, { "S50a_panel_has_no_routes_core", 50 }, @@ -269,7 +268,7 @@ static void fabric_scenario_test(struct kunit *test) enum dcp_fabric_fixed_step steps[2]; unsigned int count, order; - fabric_init(&f, scenario->id >= 30 && scenario->id <= 35); + fabric_init(&f, scenario->id >= 30 && scenario->id <= 34); switch (scenario->id) { case 1: f.port[0].preferred = &f.route[0][0]; @@ -438,9 +437,6 @@ static void fabric_scenario_test(struct kunit *test) f.pipeline[0].presence = DCP_FABRIC_SETTLING; KUNIT_EXPECT_EQ(test, fabric_tunnel(&f, 1, 0), 0); break; - case 35: - kunit_skip(test, "TB match-data retry policy is tested by W3"); - break; case 50: f.port[0].routes = NULL; KUNIT_EXPECT_PTR_EQ(test, @@ -481,6 +477,9 @@ static void fabric_scenario_test(struct kunit *test) KUNIT_EXPECT_EQ(test, dcp_fabric_tunnel_request(f.port, 1, DCP_FABRIC_DPIN_MAX, &found), -EINVAL); break; + default: + KUNIT_FAIL(test, "scenario %u has no checks", scenario->id); + break; } } @@ -1561,10 +1560,18 @@ static void fabric_effect_s50a_test(struct kunit *test) struct fabric_fake f; fabric_fake_init(&f, test, false); + KUNIT_EXPECT_FALSE(test, dcp_fabric_has_available_routes(false, 0)); + KUNIT_EXPECT_FALSE(test, dcp_fabric_has_available_routes(true, 0)); + KUNIT_EXPECT_TRUE(test, dcp_fabric_has_available_routes(true, 1)); KUNIT_EXPECT_EQ(test, dcp_fabric_run_probe(false, fabric_fake_register, &f), 0); + KUNIT_EXPECT_EQ(test, + dcp_fabric_run_probe(dcp_fabric_has_available_routes(true, 0), + fabric_fake_register, &f), 0); KUNIT_EXPECT_EQ(test, f.count, 0U); KUNIT_EXPECT_FALSE(test, f.f.pipeline[0].owned); - KUNIT_EXPECT_EQ(test, dcp_fabric_run_probe(true, fabric_fake_register, &f), 0); + KUNIT_EXPECT_EQ(test, + dcp_fabric_run_probe(dcp_fabric_has_available_routes(true, 1), + fabric_fake_register, &f), 0); KUNIT_ASSERT_EQ(test, f.count, 1U); KUNIT_EXPECT_EQ(test, f.trace[0], FX_REGISTER); } diff --git a/drivers/gpu/drm/apple/dcp-fabric-topology-test.c b/drivers/gpu/drm/apple/dcp-fabric-topology-test.c index 2240be4d8b2a38..f1c62a6f010ae6 100644 --- a/drivers/gpu/drm/apple/dcp-fabric-topology-test.c +++ b/drivers/gpu/drm/apple/dcp-fabric-topology-test.c @@ -410,6 +410,122 @@ static void topology_route_skip_test(struct kunit *test) KUNIT_EXPECT_TRUE(test, of_device_is_available(route_np)); } +/* + * apple_typec_port_rgb8_only(): a Type-C port is 8-bit RGB only if one of + * the pipelines in scope (all of them, or only @pipeline) is a candidate for + * the port and runs the native26 (ext26) IOMFB method set. + */ +enum { RGB8_PLAIN, RGB8_EXT26, RGB8_NODATA, RGB8_PIPES }; +enum { RGB8_BOTH, RGB8_PLAIN_ONLY, RGB8_NODATA_EXT26, RGB8_NONE, RGB8_PORTS }; + +struct topology_rgb8 { + struct apple_dcp_typec_port port[RGB8_PORTS]; + struct apple_dcp_typec_route route[RGB8_PORTS][2]; + struct apple_dcp dcp[RGB8_PIPES]; + struct platform_device *pdev[RGB8_PIPES]; + unsigned int first; +}; + +static void topology_rgb8_unlist(void *data) +{ + struct topology_rgb8 *t = data; + unsigned int p; + + guard(mutex)(&dcp_typec_fabric_lock); + for (p = 0; p < RGB8_PORTS; p++) + list_del(&t->port[p].link); +} + +static void topology_rgb8_route(struct topology_rgb8 *t, unsigned int p, + unsigned int slot, unsigned int pipe) +{ + struct apple_dcp_typec_route *route = &t->route[p][slot]; + + route->dcp = &t->dcp[pipe]; + route->port = &t->port[p]; + list_add_tail(&route->port_link, &t->port[p].routes); +} + +static struct topology_rgb8 *topology_rgb8_init(struct kunit *test) +{ + struct topology_rgb8 *t; + unsigned int p, i; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t); + for (i = 0; i < RGB8_PIPES; i++) { + t->pdev[i] = kunit_platform_device_alloc(test, "dcp-rgb8", + PLATFORM_DEVID_AUTO); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t->pdev[i]); + KUNIT_ASSERT_EQ(test, kunit_platform_device_add(test, t->pdev[i]), 0); + t->dcp[i].dev = &t->pdev[i]->dev; + if (i != RGB8_NODATA) + platform_set_drvdata(t->pdev[i], &t->dcp[i]); + } + t->dcp[RGB8_EXT26].hw.iomfb_method_profile = DCP_IOMFB_METHODS_J613_EXT26; + /* An ext26 method set that cannot be reached: no drvdata */ + t->dcp[RGB8_NODATA].hw.iomfb_method_profile = DCP_IOMFB_METHODS_J613_EXT26; + + t->first = dcp_typec_nr_ports(); + scoped_guard(mutex, &dcp_typec_fabric_lock) { + for (p = 0; p < RGB8_PORTS; p++) + INIT_LIST_HEAD(&t->port[p].routes); + topology_rgb8_route(t, RGB8_BOTH, 0, RGB8_PLAIN); + topology_rgb8_route(t, RGB8_BOTH, 1, RGB8_EXT26); + topology_rgb8_route(t, RGB8_PLAIN_ONLY, 0, RGB8_PLAIN); + topology_rgb8_route(t, RGB8_NODATA_EXT26, 0, RGB8_NODATA); + topology_rgb8_route(t, RGB8_NODATA_EXT26, 1, RGB8_EXT26); + for (p = 0; p < RGB8_PORTS; p++) + list_add_tail(&t->port[p].link, &dcp_typec_ports); + } + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, topology_rgb8_unlist, t), 0); + return t; +} + +static void topology_rgb8_only_test(struct kunit *test) +{ + struct topology_rgb8 *t = topology_rgb8_init(test); + struct platform_device *all[] = { + t->pdev[RGB8_PLAIN], t->pdev[RGB8_EXT26], t->pdev[RGB8_NODATA], + }; + struct platform_device *nodata_first[] = { + t->pdev[RGB8_NODATA], t->pdev[RGB8_PLAIN], t->pdev[RGB8_EXT26], + }; + struct platform_device *plain = t->pdev[RGB8_PLAIN]; + struct platform_device *ext26 = t->pdev[RGB8_EXT26]; + struct platform_device *nodata = t->pdev[RGB8_NODATA]; + unsigned int both = t->first + RGB8_BOTH; + unsigned int plain_only = t->first + RGB8_PLAIN_ONLY; + unsigned int nodata_ext26 = t->first + RGB8_NODATA_EXT26; + unsigned int none = t->first + RGB8_NONE; + + /* No pipelines at all */ + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 0, NULL, both)); + + /* Any pipeline: an ext26 candidate after a 10-bit one */ + KUNIT_EXPECT_TRUE(test, apple_typec_port_rgb8_only(all, 3, NULL, both)); + KUNIT_EXPECT_TRUE(test, apple_typec_port_rgb8_only(nodata_first, 3, NULL, both)); + + /* One pipeline: only its own method set counts */ + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 3, plain, both)); + KUNIT_EXPECT_TRUE(test, apple_typec_port_rgb8_only(all, 3, ext26, both)); + /* A pipeline that is not a candidate for the port */ + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 3, ext26, plain_only)); + + /* The ext26 pipeline is not a candidate for this port */ + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 3, NULL, plain_only)); + + /* A candidate without drvdata is skipped, not dereferenced */ + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 3, nodata, nodata_ext26)); + KUNIT_EXPECT_TRUE(test, apple_typec_port_rgb8_only(nodata_first, 3, NULL, + nodata_ext26)); + + /* A port without routes, and one past the last port */ + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 3, NULL, none)); + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 3, NULL, + t->first + RGB8_PORTS)); +} + static struct kunit_case dcp_topology_cases[] = { KUNIT_CASE(topology_pipeline_identity_test), KUNIT_CASE(topology_adopt_release_test), @@ -417,6 +533,7 @@ static struct kunit_case dcp_topology_cases[] = { KUNIT_CASE(topology_connector_group_test), KUNIT_CASE(topology_route_supplier_test), KUNIT_CASE(topology_route_skip_test), + KUNIT_CASE(topology_rgb8_only_test), {} }; diff --git a/drivers/gpu/drm/apple/dcp-fabric.c b/drivers/gpu/drm/apple/dcp-fabric.c index 08f5057cf1a9d7..22148f031868fe 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.c +++ b/drivers/gpu/drm/apple/dcp-fabric.c @@ -12,7 +12,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -226,6 +228,17 @@ bool dcp_hdmi_port_attached(struct apple_dcp *dcp) gpiod_get_value_cansleep(dcp->hdmi_hpd) > 0; } +bool dcp_t8132_ext_m4_node(const struct device_node *np) +{ + return of_device_is_compatible(np, "apple,t8132-dcpext") && + !apple_t8132_dcpext_v27_2(np); +} + +bool dcp_is_t8132_ext(const struct apple_dcp *dcp) +{ + return dcp_t8132_ext_m4_node(dcp->dev->of_node); +} + /* * A route of an adopted T8132 dcpext whose PHY has no DP alt mode: the * crossbar's DP PHY output has nothing behind it. The board marks the PHYs @@ -234,17 +247,12 @@ bool dcp_hdmi_port_attached(struct apple_dcp *dcp) */ static bool dcp_typec_route_no_dp_alt(const struct apple_dcp_typec_route *route) { - if (!of_device_is_compatible(route->dcp->dev->of_node, "apple,t8132-dcpext")) + if (!dcp_is_t8132_ext(route->dcp)) return false; return IS_ERR_OR_NULL(route->phy) || !of_property_read_bool(route->phy->dev.of_node, "apple,dp-alt-mode"); } -bool dcp_is_t8132_ext(const struct apple_dcp *dcp) -{ - return of_device_is_compatible(dcp->dev->of_node, "apple,t8132-dcpext"); -} - /* * DP IN outputs (bits 0/1) whose tunnel pixel clock source @route cannot be: * T6030 even sources only, T8132 its dcpexts (2 and 4), others any. @@ -458,6 +466,31 @@ bool dcp_is_typec_only(struct platform_device *pdev) return !dcp->fixed_phy; } +/* + * Whether @phy's own PLL clocks the DP IN adapters of its USB4 router, so that + * the tunnel's pixel clock is set through phy_configure(), a property of the + * PHY: the T6040 ATC PHY (M4 Pro/Max, also on T6041) feeds DP IN 0 and 1 from + * its AUSPLL. Such a PHY also needs no apple_atc_dp_tunnel_open(). + */ +static bool dcp_phy_clocks_tunnel(struct phy *phy) +{ + return phy && of_device_is_compatible(phy->dev.of_node, "apple,t6040-atcphy"); +} + +/* Start the tunnel pixel clock of DP IN @dpin at link rate code @rate, or stop it (0). */ +static int dcp_phy_tunnel_rate(struct phy *phy, unsigned int dpin, u8 rate) +{ + union phy_configure_opts opts = { + .dp = { + .set_tunnel_rate = 1, + .tunnel_dpin = dpin, + .tunnel_rate = rate, + }, + }; + + return phy_configure(phy, &opts); +} + static int dcp_route_clock_rate(struct apple_dcp_typec_route *route, struct phy *phy, unsigned int dpin, u8 rate) { @@ -481,6 +514,14 @@ static int dcp_route_clock_rate(struct apple_dcp_typec_route *route, return ret; } + /* A PHY whose own PLL feeds the DP IN pixel clocks takes the rate itself. */ + if (dcp_phy_clocks_tunnel(phy)) { + ret = dcp_phy_tunnel_rate(phy, dpin, rate); + if (!ret) + route->tunnel_rate = rate; + return ret; + } + /* A T8132 dcpext names its source (2 or 4), as T6030 does. */ if (of_machine_is_compatible("apple,t6030") || t8132) { typeof(apple_atc_dp_tunnel_rate_source) *fn; @@ -531,6 +572,7 @@ static int dcp_typec_route_activate(struct apple_dcp_typec_route *route, static int dcp_typec_route_deactivate(struct apple_dcp_typec_route *route); static int dcp_dpxbar_preselect(struct mux_control *mux, int state); static bool dcp_xbar_t8142(struct mux_control *mux); +static bool dcp_xbar_t6041(struct mux_control *mux); static int dcp_dpxbar_tunnel_select_source(struct mux_control *mux, int state) { @@ -545,6 +587,7 @@ static int dcp_dpxbar_tunnel_select_source(struct mux_control *mux, int state) return ret; } +/* A desktop external processor on firmware 27: T6041's, or the J773g's T8132 one. */ static bool dcp_t6041_ext_v27(const struct apple_dcp *dcp) { return dcp->fw_compat == DCP_FIRMWARE_V_27_0 && dcp->desktop_external; @@ -810,11 +853,13 @@ static int dcp_typec_route_deactivate(struct apple_dcp_typec_route *route) } else { ret = dcp_dpxbar_preselect(route->active_xbar, MUX_IDLE_DISCONNECT); /* - * The T8142-layout crossbar writes an output only when it - * is selected: one never selected is idle already. + * The T8142-layout and runtime-PM T6041 + * crossbars write an output only when it is + * selected: one never selected is idle already. */ if (ret == -EOPNOTSUPP && (dcp_xbar_t8142(route->active_xbar) || + dcp_xbar_t6041(route->active_xbar) || dcp_typec_route_no_dp_alt(route))) ret = 0; } @@ -1213,12 +1258,12 @@ static void dcp_hdmi_capacity_available(void *ctx) * never tracked: when the hold expires, the desktop has let the HDMI CRTC go * and the hybrid is free for a Type-C display again. */ -void dcp_fabric_hdmi_unplugged(struct apple_dcp *dcp) +static void dcp_fabric_hdmi_unplugged_locked(struct apple_dcp *dcp) { unsigned long flags; u64 generation; - guard(mutex)(&dcp_typec_fabric_lock); + lockdep_assert_held(&dcp_typec_fabric_lock); generation = dcp_hdmi_edge(dcp); if (!generation) return; @@ -1230,6 +1275,31 @@ void dcp_fabric_hdmi_unplugged(struct apple_dcp *dcp) dcp_fabric_hybrid_kick(dcp, 0); } +void dcp_fabric_hdmi_unplugged(struct apple_dcp *dcp) +{ + guard(mutex)(&dcp_typec_fabric_lock); + dcp_fabric_hdmi_unplugged_locked(dcp); +} + +/* + * Release a fixed HDMI link unplugged while its HPD IRQ was masked. Hold + * the fabric lock from the ownership check through the presence update so + * a Type-C route cannot take the same DPTX port during the release. + */ +void dcp_hdmi_unplugged_in_sleep(struct apple_dcp *dcp) +{ + guard(mutex)(&dcp_typec_fabric_lock); + + if (dcp->active_typec_route || !dcp->connector || + !READ_ONCE(dcp->connector->connected) || + gpiod_get_value_cansleep(dcp->hdmi_hpd) != 0) + return; + + dev_info(dcp->dev, "HDMI display unplugged during sleep\n"); + dcp_hdmi_disconnect(dcp); + dcp_fabric_hdmi_unplugged_locked(dcp); +} + static void dcp_hdmi_settle_work(struct work_struct *work) { struct apple_dcp *dcp = container_of(to_delayed_work(work), @@ -2238,17 +2308,27 @@ static bool dcp_xbar_t8142(struct mux_control *mux) "apple,t8142-display-crossbar"); } +/* The T6041-layout crossbar (one per ATC on T6040/T6041) */ +static bool dcp_xbar_t6041(struct mux_control *mux) +{ + return mux && of_device_is_compatible(mux->chip->dev.parent->of_node, + "apple,t6041-display-crossbar"); +} + /* * Tunnel routes whose crossbar must point the DP IN output at its pipeline * before the firmware uses AUX through it, i.e. from DCP's Activate: the T6030 - * 14.7 pipeline on its T602X crossbar (other T602X tunnels keep their order) - * and firmware 27 on the T8142-layout crossbar. Selecting routes the output - * only; its clocks follow the link. + * 14.7 pipeline on its T602X crossbar (other T602X tunnels keep their order), + * the T6041 crossbar on every firmware (its runtime-PM path only writes the + * mux while selected), and firmware 27 on the T8142-layout crossbar. Selecting + * routes the output only; its clocks follow the link. */ static bool dcp_t602x_tunnel_route(struct apple_dcp_typec_route *route) { if (!route || !route->tunnel || !route->active_xbar) return false; + if (dcp_xbar_t6041(route->active_xbar)) + return true; if (route->dcp->fw_compat == DCP_FIRMWARE_V_27_0) return dcp_xbar_t8142(route->active_xbar); return route->dcp->fw_compat == DCP_FIRMWARE_V_14_7 && @@ -2308,6 +2388,9 @@ static void dcp_tunnel_prepare(struct apple_dcp_typec_route *route, if (ret && ret != -EOPNOTSUPP) dev_warn(dcp->dev, "DP tunnel crossbar preselect failed: %d\n", ret); + /* The clock call starts everything on a PHY that clocks the tunnel. */ + if (dcp_phy_clocks_tunnel(dcp->phy)) + return; open = symbol_get(apple_atc_dp_tunnel_open); if (!open) return; @@ -2356,6 +2439,12 @@ static int dcp_tunnel_split_up_locked(struct apple_dcp *dcp) ret = mux_control_try_select(dcp->split.xbar, dcp->split.mux_state); if (!ret) dcp->split.xbar_up = true; + /* + * T6041 DP IN selection reserves and routes the mux only, so + * the first link up also enables the connection clocks. + */ + if (!ret && dcp_xbar_t6041(dcp->split.xbar)) + ret = dcp_dpxbar_link(dcp->split.xbar, true); } else { ret = dcp_dpxbar_link(dcp->split.xbar, true); } @@ -2493,7 +2582,13 @@ int dcp_tunnel_crossbar_up(struct apple_dcp *dcp, u32 unit) ret = mux_control_try_select(route->active_xbar, route->mux_index); if (!ret) route->xbar_up = true; - /* T602X DP IN selection reserves and routes the mux only. */ + /* + * T602X, T6041 and T8142 DP IN selection reserves and routes + * the mux only, so the first link up also enables the + * connection: without this its clocks stay off until a + * retrain, and a mode set that keeps the trained link (5K on + * 26.6) never gets any video. + */ if (!ret && dcp_t602x_tunnel_route(route)) { ret = dcp_tunnel_xbar_configure(route); if (!ret) @@ -2788,6 +2883,14 @@ int dcp_tunnel_dpin_activate(struct apple_dcp *dcp, u32 unit, bool active) if (unit) { if (!dcp->split.active || !dcp->split.generation || !dcp->split.set_active) return 0; + if (active && dcp_xbar_t6041(dcp->split.xbar) && + !dcp->split.xbar_up) { + ret = mux_control_try_select(dcp->split.xbar, + dcp->split.mux_state); + if (ret) + return ret; + dcp->split.xbar_up = true; + } return dcp->split.set_active(dcp->split.binding, active); } /* Route the upstream engine before firmware begins AUX negotiation. @@ -3130,12 +3233,16 @@ static int dcp_tb_split_teardown_locked(struct apple_dcp_typec_port *port, /* Retire the callback before dropping its clock reference. */ dcp->split.active = false; if (dcp->phy) { - typeof(apple_atc_dp_tunnel_rate) *stop = - symbol_get(apple_atc_dp_tunnel_rate); + if (dcp_phy_clocks_tunnel(dcp->phy)) { + dcp_phy_tunnel_rate(dcp->phy, 1, 0); + } else { + typeof(apple_atc_dp_tunnel_rate) *stop = + symbol_get(apple_atc_dp_tunnel_rate); - if (stop) { - stop(dcp->phy, 1, 0); - symbol_put(apple_atc_dp_tunnel_rate); + if (stop) { + stop(dcp->phy, 1, 0); + symbol_put(apple_atc_dp_tunnel_rate); + } } } if (dcp->split.xbar) { @@ -4959,8 +5066,10 @@ static int dcp_register_typec_routes_present(void *data) dcp->nr_typec_routes++; } - if (!dcp->nr_typec_routes) - return dev_err_probe(dev, -EINVAL, "Type-C route container is empty\n"); + if (!dcp->nr_typec_routes) { + dev_info(dev, "no usable Type-C display routes\n"); + return 0; + } dcp->phy_managed_by_typec = true; return 0; @@ -4991,8 +5100,35 @@ int dcp_register_typec_routes(struct apple_dcp *dcp) struct device_node *routes __free(device_node) = of_get_child_by_name(dcp->dev->of_node, "typec-routes"); struct dcp_route_probe_context ctx = { .dcp = dcp, .routes = routes }; + bool has_routes = dcp_typec_routes_available(routes); + + if (routes && !has_routes) + dev_info(dcp->dev, "no usable Type-C display routes\n"); + + return dcp_fabric_run_probe(has_routes, dcp_register_typec_routes_present, &ctx); +} + +/* + * A DCP whose firmware runs through a sleep keeps driving the DP PHY of its + * output, so the PHY's power domain has to stay up with the DCP's own: cut at + * noirq under the running firmware, it resets the SoC (J473, firmware 27.2). + * Put the PHY devices in use on the wakeup path, as the DCP itself is. + */ +static void dcp_phy_set_wakeup_path(struct phy *phy) +{ + if (!IS_ERR_OR_NULL(phy) && phy->dev.parent) + device_set_wakeup_path(phy->dev.parent); +} - return dcp_fabric_run_probe(!!routes, dcp_register_typec_routes_present, &ctx); +void dcp_sleep_hold_phys(struct apple_dcp *dcp) +{ + struct apple_dcp_typec_route *route; + + guard(mutex)(&dcp_typec_fabric_lock); + route = dcp->active_typec_route; + dcp_phy_set_wakeup_path(dcp->phy); + if (route) + dcp_phy_set_wakeup_path(route->phy); } /* diff --git a/drivers/gpu/drm/apple/dcp-fabric.h b/drivers/gpu/drm/apple/dcp-fabric.h index 7876718cbfdfaa..139c75f27f674d 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.h +++ b/drivers/gpu/drm/apple/dcp-fabric.h @@ -4,9 +4,11 @@ #include #include +#include #include #include "dcp-fabric-core.h" +#include "dcp-fabric-effects.h" struct apple_connector; struct apple_crtc; @@ -78,6 +80,12 @@ bool dcp_has_typec_routes(struct platform_device *pdev); unsigned int dcp_typec_nr_ports(void); struct device_node *dcp_typec_port_of_node(unsigned int idx); bool dcp_typec_port_has_candidate(unsigned int idx, struct platform_device *pdev); +#if IS_ENABLED(CONFIG_KUNIT) +/* apple_drv.c: whether a native26 pipeline can drive Type-C port @port_idx */ +bool apple_typec_port_rgb8_only(struct platform_device **dcp, int num_dcp, + struct platform_device *pipeline, + unsigned int port_idx); +#endif /* Connectors by apple,connector-group; T6050's tunnel-only pairs after the others in each */ #define DCP_TYPEC_CONNECTOR_GROUPS 4 unsigned int dcp_typec_nr_passes(void); @@ -120,11 +128,23 @@ int dcp_tunnel_set_rate(struct apple_dcp *dcp, struct phy *phy, u32 unit, u32 link_rate); int dcp_tunnel_dpin_activate(struct apple_dcp *dcp, u32 unit, bool active); -/* An adopted T8132 dcpext. */ +/* + * A T8132 dcpext adopted through the M4 26.6.2 backend (iomfb_m4.c, + * t8132_ext_drm.c). A J773g dcpext on firmware 27.2 is an ordinary + * firmware-27 pipe instead and is neither of these. + */ +bool dcp_t8132_ext_m4_node(const struct device_node *np); bool dcp_is_t8132_ext(const struct apple_dcp *dcp); /* DCP probe, resume and endpoint teardown hooks. */ +static inline bool dcp_typec_routes_available(const struct device_node *routes) +{ + return dcp_fabric_has_available_routes(!!routes, + routes ? of_get_available_child_count(routes) : 0); +} + int dcp_register_typec_routes(struct apple_dcp *dcp); +void dcp_sleep_hold_phys(struct apple_dcp *dcp); void dcp_typec_route_park(struct apple_dcp *dcp); void dcp_typec_route_unpark(struct apple_dcp *dcp); int dcp_fabric_sleep_release(struct apple_dcp *dcp, s64 ms[2]); diff --git a/drivers/gpu/drm/apple/dcp-firmware-test.c b/drivers/gpu/drm/apple/dcp-firmware-test.c new file mode 100644 index 00000000000000..86291297a660b9 --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-firmware-test.c @@ -0,0 +1,335 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Included by dcp.c to exercise probe's firmware admission without hardware. */ +#include + +static void dcp_firmware_13_5_compat(struct kunit *test) +{ + static const char primary[] = "apple,t8112-dcp\0apple,dcp"; + static const char external[] = "apple,t8112-dcpext\0apple,dcpext"; + __be32 firmware[] = { cpu_to_be32(13), cpu_to_be32(5), 0 }; + __be32 compat[] = { cpu_to_be32(13), cpu_to_be32(3), 0 }; + struct property properties[] = { + { .name = "apple,firmware-compat", .length = sizeof(compat), + .value = compat, .next = &properties[1] }, + { .name = "apple,firmware-version", .length = sizeof(firmware), + .value = firmware, .next = &properties[2] }, + { .name = "compatible", .length = sizeof(primary), .value = (void *)primary }, + }; + struct device_node node = { .properties = properties }; + struct device dev = { + .init_name = "dcp-firmware-test", + .of_node = &node, + .driver = &apple_platform_driver.driver, + }; + + /* The 13.5 stub can advertise 13.3 IOMFB compatibility. */ + KUNIT_ASSERT_NOT_NULL(test, of_device_get_match_data(&dev)); + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), DCP_FIRMWARE_V_13_5); + firmware[1] = cpu_to_be32(3); + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), DCP_FIRMWARE_UNKNOWN); + firmware[1] = cpu_to_be32(5); + + properties[2].length = sizeof(external); + properties[2].value = (void *)external; + KUNIT_ASSERT_NOT_NULL(test, of_device_get_match_data(&dev)); + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), DCP_FIRMWARE_V_13_5); + compat[1] = cpu_to_be32(5); + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), DCP_FIRMWARE_V_13_5); +} + +static void dcp_firmware_27_method_admission(struct kunit *test) +{ + struct device dev = { .init_name = "dcp-firmware-test" }; + const struct dcp_method_entry *methods = iomfb_v27_methods("27.2.0"); + const struct dcp_method_entry *earlier = iomfb_v27_methods("27.0.0"); + struct dcp_method_entry *incomplete; + unsigned int missing; + + KUNIT_ASSERT_NOT_NULL(test, methods); + KUNIT_ASSERT_NOT_NULL(test, earlier); + KUNIT_EXPECT_PTR_NE(test, methods, earlier); + KUNIT_EXPECT_NE(test, memcmp(methods[dcpep_swap_submit].tag, + earlier[dcpep_swap_submit].tag, + sizeof(methods[dcpep_swap_submit].tag)), 0); + KUNIT_EXPECT_EQ(test, dcp_v27_method_table(&dev, "27.2.0"), DCP_FIRMWARE_V_27_0); + KUNIT_EXPECT_EQ(test, dcp_v27_method_table(&dev, "27.3.0"), DCP_FIRMWARE_UNKNOWN); + KUNIT_EXPECT_EQ(test, dcp_v27_method_table(&dev, "27.2.1"), DCP_FIRMWARE_UNKNOWN); + + incomplete = kunit_kmalloc(test, sizeof(*methods) * dcpep_num_methods, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, incomplete); + memcpy(incomplete, methods, sizeof(*methods) * dcpep_num_methods); + memset(incomplete[dcpep_dfb_ready_query].tag, 0, + sizeof(incomplete[dcpep_dfb_ready_query].tag)); + KUNIT_EXPECT_NULL(test, iomfb_v27_missing_method(incomplete, &missing)); + KUNIT_EXPECT_EQ(test, missing, 0U); + memset(incomplete[dcpep_swap_submit].tag, 0, sizeof(incomplete[dcpep_swap_submit].tag)); + KUNIT_EXPECT_STREQ(test, iomfb_v27_missing_method(incomplete, &missing), + methods[dcpep_swap_submit].name); + KUNIT_EXPECT_EQ(test, missing, 1U); +} + +/* + * Firmware 27 provider clocks on a T602x display processor: the 27.2 ADT + * lists none (an empty /arm-io/disp0 and dispext clock-ids), and the + * node keeps its display clock. + */ +static void dcp_firmware_27_empty_clock_table(struct kunit *test) +{ + static const char primary[] = "apple,t6020-dcp\0apple,dcp"; + __be32 display = cpu_to_be32(1); + struct property properties[] = { + { .name = "apple,clock-ids", .length = 0, .value = &display, + .next = &properties[1] }, + { .name = "clocks", .length = sizeof(display), .value = &display, + .next = &properties[2] }, + { .name = "compatible", .length = sizeof(primary), .value = (void *)primary }, + }; + struct device_node node = { .properties = properties }; + struct device dev = { .init_name = "dcp-firmware-test", .of_node = &node }; + struct apple_dcp *dcp = kunit_kzalloc(test, sizeof(*dcp), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, dcp); + dcp->dev = &dev; + dcp->num_firmware_clocks = 3; + KUNIT_EXPECT_EQ(test, dcp_firmware_clocks_v27(dcp), 0); + KUNIT_EXPECT_EQ(test, dcp->num_firmware_clocks, 0U); + KUNIT_EXPECT_NULL(test, dcp->firmware_clocks); + + /* Without the table the firmware's clocks are unknown: refused. */ + properties[0].name = "apple,unrelated"; + KUNIT_EXPECT_EQ(test, dcp_firmware_clocks_v27(dcp), -EINVAL); +} + +/* + * Explicit match-data and image-UUID pins stay ahead of generic firmware-27 + * admission: T8122 wrong/missing 27.2 UUIDs and internal T8142 unknown 27.x + * builds are terminally refused rather than using generic v27 or H17P, + * while generic refmac DCPs (T6030, T8112) take firmware 27 on complete 27.x + * method tables and refuse incomplete ones. + */ +static void dcp_firmware_27_pin_precedence(struct kunit *test) +{ + static const char t6030[] = "apple,t6030-dcp"; + static const char t6041[] = "apple,t6041-dcp\0apple,dcp"; + static const char t6041_ext[] = "apple,t6041-dcpext\0apple,dcpext"; + static const char t8122[] = "apple,t8122-dcp\0apple,dcp"; + static const char t8122_ext[] = "apple,t8122-dcpext\0apple,dcpext"; + static const char t8142[] = "apple,t8142-dcp"; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8132) + static const char t8132[] = "apple,t8132-dcp"; +#endif + static const char bad_uuid[] = "00000000-0000-0000-0000-000000000000"; + __be32 compat_26_6[] = { cpu_to_be32(26), cpu_to_be32(6), cpu_to_be32(2) }; + __be32 compat_27_0[] = { cpu_to_be32(27), 0, 0 }; + __be32 compat_27_1[] = { cpu_to_be32(27), cpu_to_be32(1), 0 }; + __be32 compat_27_2[] = { cpu_to_be32(27), cpu_to_be32(2), 0 }; + __be32 compat_27_3[] = { cpu_to_be32(27), cpu_to_be32(3), 0 }; + struct dcp_pin_precedence_fixture { + struct property props[4]; + struct property ext_props[3]; + struct device_node node; + struct device_node ext_node; + struct device dev; + } *fx; + + fx = kunit_kzalloc(test, sizeof(*fx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, fx); + + fx->props[0] = (struct property) { + .name = "apple,firmware-compat", + .length = sizeof(compat_27_2), + .value = compat_27_2, + .next = &fx->props[1], + }; + fx->props[1] = (struct property) { + .name = "apple,firmware-version", + .length = sizeof(compat_27_2), + .value = compat_27_2, + .next = &fx->props[2], + }; + fx->props[2] = (struct property) { + .name = "apple,firmware-uuid", + .length = sizeof(bad_uuid), + .value = (void *)bad_uuid, + .next = &fx->props[3], + }; + fx->props[3] = (struct property) { + .name = "compatible", + .length = sizeof(t6030), + .value = (void *)t6030, + }; + fx->ext_props[0] = (struct property) { + .name = "apple,firmware-compat", + .length = sizeof(compat_27_2), + .value = compat_27_2, + .next = &fx->ext_props[1], + }; + fx->ext_props[1] = (struct property) { + .name = "apple,firmware-version", + .length = sizeof(compat_27_2), + .value = compat_27_2, + .next = &fx->ext_props[2], + }; + fx->ext_props[2] = (struct property) { + .name = "compatible", + .length = sizeof(t8122_ext), + .value = (void *)t8122_ext, + }; + fx->node.properties = fx->props; + fx->ext_node.properties = fx->ext_props; + fx->dev.init_name = "dcp-firmware-test"; + fx->dev.of_node = &fx->node; + fx->dev.driver = &apple_platform_driver.driver; + + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_V_27_0); + + fx->props[0].value = compat_27_3; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_UNKNOWN); + fx->props[0].value = compat_27_2; + + /* T6041 internal and external UUID pins remain enforced on 27.2. */ + fx->props[3].length = sizeof(t6041); + fx->props[3].value = (void *)t6041; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_UNKNOWN); + + fx->props[2].length = sizeof(APPLE_T6041_DCP_26B123_UUID); + fx->props[2].value = (void *)APPLE_T6041_DCP_26B123_UUID; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_V_27_0); + + fx->props[3].length = sizeof(t6041_ext); + fx->props[3].value = (void *)t6041_ext; + fx->props[2].length = sizeof(bad_uuid); + fx->props[2].value = (void *)bad_uuid; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_UNKNOWN); + + fx->props[2].name = "apple,unrelated"; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_UNKNOWN); + + fx->props[2].name = "apple,firmware-uuid"; + fx->props[2].length = sizeof(APPLE_T6041_DCP_26B123_UUID); + fx->props[2].value = (void *)APPLE_T6041_DCP_26B123_UUID; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_V_27_0); + + /* T8122 wrong or missing 27.2 UUID is terminally refused (never takes generic v27). */ + fx->props[3].length = sizeof(t8122); + fx->props[3].value = (void *)t8122; + fx->props[2].name = "apple,firmware-uuid"; + fx->props[2].length = sizeof(bad_uuid); + fx->props[2].value = (void *)bad_uuid; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_UNKNOWN); + KUNIT_EXPECT_FALSE(test, + apple_t8122_dcpext_v27_2_for_internal(&fx->ext_node, &fx->node)); + + fx->props[2].name = "apple,unrelated"; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_UNKNOWN); + KUNIT_EXPECT_FALSE(test, + apple_t8122_dcpext_v27_2_for_internal(&fx->ext_node, &fx->node)); + + fx->props[2].name = "apple,firmware-uuid"; + fx->props[2].length = sizeof(APPLE_T8122_DCP_26B123_UUID); + fx->props[2].value = (void *)APPLE_T8122_DCP_26B123_UUID; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_V_27_0); + KUNIT_EXPECT_TRUE(test, + apple_t8122_dcpext_v27_2_for_internal(&fx->ext_node, &fx->node)); + + /* T8122 external with mismatched version is terminally refused regardless of live tree. */ + fx->ext_props[1].value = compat_27_0; + KUNIT_EXPECT_FALSE(test, + apple_t8122_dcpext_v27_2_for_internal(&fx->ext_node, &fx->node)); + fx->dev.of_node = &fx->ext_node; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_UNKNOWN); + fx->ext_props[1].value = compat_27_2; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + apple_t8122_dcpext_v27_2(&fx->ext_node) ? + DCP_FIRMWARE_V_27_0 : DCP_FIRMWARE_UNKNOWN); + fx->dev.of_node = &fx->node; + + /* Internal T8142: known 27.x takes v27, unknown 27.x is refused (never takes H17P). */ + fx->props[3].length = sizeof(t8142); + fx->props[3].value = (void *)t8142; + fx->props[0].value = compat_27_0; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_V_27_0); + fx->props[0].value = compat_27_2; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_V_27_0); + fx->props[0].value = compat_27_1; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_UNKNOWN); + fx->props[0].value = compat_27_3; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_UNKNOWN); + fx->props[0].value = compat_26_6; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + DCP_FIRMWARE_H17P); + fx->props[0].value = compat_27_2; + +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8132) + /* + * T8132 keeps its M4 match-data pin on 27.2, never generic firmware + * 27: the M4 backend's on its 26.6.2 firmware path, nobody's off it. + */ + fx->props[3].length = sizeof(t8132); + fx->props[3].value = (void *)t8132; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + apple_t8132_firmware_path() ? DCP_FIRMWARE_M4 : + DCP_FIRMWARE_UNKNOWN); +#endif +} + +static void dcp_typec_routes_available_children(struct kunit *test) +{ + static const char disabled[] = "disabled"; + static const char okay[] = "okay"; + struct property child_status = { + .name = "status", .length = sizeof(disabled), .value = (void *)disabled, + }; + struct device_node child = { + .name = "route", .full_name = "route@0", .properties = &child_status, + }; + struct device_node routes = { + .name = "typec-routes", .full_name = "typec-routes", + }; + struct device_node parent = { + .name = "dcp", .full_name = "dcp", .child = &routes, + }; + + /* Empty typec-routes container has no available route children. */ + KUNIT_EXPECT_FALSE(test, dcp_has_available_typec_routes(&parent)); + + /* Container with only disabled child routes has no available routes. */ + routes.child = &child; + KUNIT_EXPECT_FALSE(test, dcp_has_available_typec_routes(&parent)); + + /* Available child route activates Type-C route detection. */ + child_status.length = sizeof(okay); + child_status.value = (void *)okay; + KUNIT_EXPECT_TRUE(test, dcp_has_available_typec_routes(&parent)); +} + +static struct kunit_case dcp_firmware_cases[] = { + KUNIT_CASE(dcp_firmware_13_5_compat), + KUNIT_CASE(dcp_firmware_27_method_admission), + KUNIT_CASE(dcp_firmware_27_empty_clock_table), + KUNIT_CASE(dcp_firmware_27_pin_precedence), + KUNIT_CASE(dcp_typec_routes_available_children), + {} +}; + +static struct kunit_suite dcp_firmware_suite = { + .name = "apple-dcp-firmware", + .test_cases = dcp_firmware_cases, +}; + +kunit_test_suite(dcp_firmware_suite); diff --git a/drivers/gpu/drm/apple/dcp-hdr-metadata.h b/drivers/gpu/drm/apple/dcp-hdr-metadata.h index 15937ac47fe9a4..a3815e954065a8 100644 --- a/drivers/gpu/drm/apple/dcp-hdr-metadata.h +++ b/drivers/gpu/drm/apple/dcp-hdr-metadata.h @@ -1,6 +1,6 @@ /* SPDX-License-Identifier: GPL-2.0-only OR MIT */ /* - * HDR10 static metadata for the DCPAV service of desktop 26.x DCPs. + * HDR10 static metadata for the DCPAV service. * * The display's Dynamic Range and Mastering InfoFrame is link state the * firmware builds itself: the host sends DCPAV selector 0x15 @@ -62,6 +62,11 @@ #define DCP_HDR_STOP_STATUS 0x70 #define DCP_HDR_INFOFRAME_DRM 0x87 +static inline bool dcp_hdr_is_type1(const struct hdr_output_metadata *hdr) +{ + return !hdr->metadata_type && !hdr->hdmi_metadata_type1.metadata_type; +} + /* The 24-byte Type 1 body of @hdr; -EINVAL unless it is a Type 1 block. */ static inline int dcp_hdr_data(u8 data[DCP_HDR_DATA_SIZE], const struct hdr_output_metadata *hdr) @@ -69,7 +74,7 @@ static inline int dcp_hdr_data(u8 data[DCP_HDR_DATA_SIZE], const struct hdr_metadata_infoframe *t1 = &hdr->hdmi_metadata_type1; unsigned int i; - if (hdr->metadata_type || t1->metadata_type) + if (!dcp_hdr_is_type1(hdr)) return -EINVAL; for (i = 0; i < 3; i++) { put_unaligned_le16(t1->display_primaries[i].x, data + i * 4); diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 515e6bf065f098..81de9acc87461a 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -28,6 +29,7 @@ #include "dptxep.h" #include "dcp_backlight.h" #include "dcp-announce.h" +#include "dcp-color.h" #include "dcp-display-metadata.h" #include "dcp-metadata-epoch.h" #include "dcp-180hz.h" @@ -226,9 +228,9 @@ struct dcp_panel { int height_mm; /// panel has a mini-LED backlight bool has_mini_led; - /// peak panel luminance in nits, for EDR (desktop 26.x; 0 if unknown) + /// peak panel luminance in nits, for EDR (0 if unknown or no EDR headroom) u32 peak_nits; - /// EDR headroom ceiling x1000 from the ADT (desktop 26.x; 0 if none) + /// EDR headroom ceiling x1000 from the ADT (0: the panel has no EDR headroom) u32 edr_ceiling; /// calibrated colour target from the raw ADT; NULL if not given const struct dcp_color_space *color_target; @@ -250,6 +252,50 @@ struct dcp_s2r_layout { u32 disp_streams; /* "pmc-dcp" counts the powered DCPs: T8132 and T8140 only */ bool pmc_dcp; + /* + * From the device tree (dcp_s2r_layout_from_dt()): only the @*_mask bits of a + * retention word are written, @*_off while off and the value read at probe back on. + * Zero masks: the whole words, as above. + */ + u32 ret_ff_mask, ret_ff_off, ret_ff_on; + u32 ret_mem_mask, ret_mem_off, ret_mem_on; +}; + +/* + * One display power chain parsed from a child node of + * apple,t6041-display-power. domains[] is ordered sys, fe, cpu, then child + * sub-domains (parent-before-child; powered off in reverse). + */ +struct dcp_t6041_chain { + const char *name; + u32 reg; + bool is_main; + void __iomem *gapf; + void __iomem *pg_a; + void __iomem *pg_b; + void __iomem *fabric; + void __iomem **domains; + u32 *child_saved; + unsigned int num_domains; +}; + +/* + * Mapped register windows and display power chains from apple,display-power + * (apple,t6041-display-power) for host-driven T6041 suspend-to-RAM; mapped + * once at probe. + */ +struct dcp_t6041_power { + void __iomem *pmc_dcp; + void __iomem *pwrgate; + void __iomem *pwrgate_aux; + void __iomem *gapf; + void __iomem *axi2af; + struct dcp_t6041_chain *chains; + unsigned int num_chains; + struct dcp_t6041_chain *main_chain; + bool child_valid; + u32 boot_ps[3]; + bool boot_ps_valid; }; /* @@ -284,6 +330,8 @@ struct apple_dcp_hw_data { * standard RTKit wake instead of starting or restarting the ASC. */ bool adopt_live_session; + /* Bootloader property marking this DCP as running under iBoot. */ + const char *iboot_handoff; enum dcp_firmware_version firmware_compat; /* Firmware-visible clock aperture, independent of the AP PMGR window. */ const struct resource *firmware_clock; @@ -315,7 +363,8 @@ struct apple_dcp_hw_data { * The endpoint the DPTX port services are announced on, where it is not * the firmware's default (DPTX_ENDPOINT_V2 on firmware 27): the T8142 * dcpext announces them on DPTX_ENDPOINT. 0: the default, or on a - * firmware-27 dcpext what its firmware advertises (dcp_v27_dptx_layout()). + * firmware-27 dcpext or DCP with Type-C routes what its firmware + * advertises (dcp_v27_dptx_layout()). */ u8 dptx_endpoint; /* @@ -345,6 +394,39 @@ struct apple_dcp_hw_data { * firmware 27.0 and 27.2.1), so there is no secure port to idle before the IOP. */ bool s2r_no_secure_port; + /* + * Every AFK endpoint speaks AFKv2 (see afk_init()), whatever the + * firmware interface: for a firmware that does so on all of them + * without an IOMFB interface version that implies it. + */ + bool afk_v2; + /* + * The RTKit session is taken over without its endpoint map (see + * apple_rtkit_init_adopted()): afk_start() registers each endpoint + * with RTKit before starting it. + */ + bool afk_adopt_endpoints; + /* + * AFK services are matched by the name in their announcement; the + * properties after it are not parsed (afk_recv_handle_init()). + */ + bool afk_announced_names; + /* + * How long AFK waits for the firmware to start or stop an endpoint + * and to answer a command or service call (afk_timeout_ms()); zero + * for one second. + */ + unsigned int afk_timeout_ms; + /* + * Firmware 27 reaches its register windows through its DART here, so map_reg maps + * them there (T8103: its power-down faults on an unmapped window otherwise). + */ + bool map_reg_dart; + /* + * The display DART goes off and on with the coprocessor's own stop and start: no + * D572 turns it off first, and the stop's power-down resets it (T8103). + */ + bool s2r_disp_dart_with_dcp; }; enum dcp_test_point { @@ -387,18 +469,6 @@ struct dcp_desktop_state { u32 vrr_min_on, vrr_min_off, vrr_min_sent; /* The frame's colour matrix, sent after an adaptive sync update. */ struct iomfb_set_matrix_req matrix; - /* - * HDR10 static metadata (external processors): the pinned - * dcpav-service-epic service, the Type 1 body last sent on this link - * (taken or refused), if any, and whether the firmware took one, so - * that the link carries a Dynamic Range and Mastering InfoFrame. - * hdr_lock protects all of them. - */ - spinlock_t hdr_lock; - struct apple_epic_service *av_service; - u8 hdr_sent[24]; - bool hdr_sent_valid; - bool hdr_infoframe; u32 present_id; bool present_pending; /* @@ -439,6 +509,8 @@ struct dcp_desktop_state { /* TODO: move IOMFB members to its own struct */ struct dcpext_scanout; +struct t8152_display; +struct dcp_iboot; struct dcp_hdmi; struct dcp_cec; @@ -473,6 +545,8 @@ struct apple_dcp { struct iomfb_m4 *v26_6; /* An adopted session has no confirmed firmware DMA stop boundary. */ bool retain_dma; + /* RTKit session handed over running by a boot stage (apple,rtkit-handoff) */ + bool rtkit_adopted; /* * Allocates AFK rings where the DMA API cannot, on an adopted * J713 external DCP whose DART only takes the retained allocator. @@ -523,6 +597,18 @@ struct apple_dcp { struct platform_device *piodma; bool piodma_created; struct iommu_domain *iommu_dom; + /* + * J615 dcpext: a child device on the display DART stream the external + * pipe scans framebuffers through. Framebuffers are mirrored into its + * domain at the display subsystem's addresses. fb_mirrors holds the + * mapped length of every mirrored GEM object, indexed by the object's + * address, until the object is freed; fb_mirror_lock protects it and + * fb_dom. + */ + struct platform_device *fbdma; + struct iommu_domain *fb_dom; + struct xarray fb_mirrors; + struct mutex fb_mirror_lock; /* which of the nine cumulative A031 notify-client states to send next */ unsigned int a031_step; struct apple_rtkit *rtk; @@ -561,14 +647,28 @@ struct apple_dcp { /* firmware version and compatible firmware version */ enum dcp_firmware_version fw_compat; + /* T8152: the DisplayPort hardware behind the DPTX port (t8152_display.h) */ + struct t8152_display *t8152; + /* DCP_FIRMWARE_IBOOT: the display driven through it (iomfb_iboot.h) */ + struct dcp_iboot *iboot; /* Bumped by every iomfb poweron; see afk_compact_slot(). */ u32 afk_power_gen; + /* + * AFK endpoints the bootloader left running, bit N for endpoint + * 0x20 + N, from its hand-off: afk_start() stops each before its + * INIT. Zero for a processor without such a hand-off. + */ + u32 afk_live_endpoints; /* Firmware 27.x: the method IDs of this build (iomfb_v27_methods()). */ const struct dcp_method_entry *v27_methods; bool external; /* Any external processor (apple,dcpext), whatever its SoC; set at probe. */ bool dcpext; - /* A desktop 26.x external processor (apple,t6041-dcpext) */ + /* + * A desktop external processor: apple,t6041-dcpext (26.x or 27.2), or + * the J773g's apple,t8132-dcpext on 27.2 (apple_t8132_dcpext_v27_2()), + * which drives the HDMI port the same way. + */ bool desktop_external; /* * A failsafe dcpext (dcp_ext_is_failsafe(): T8122's, T6041's, T6050's): @@ -579,6 +679,8 @@ struct apple_dcp { */ bool ext_failsafe; bool ext_dead; + /* T6041 S2R: this external DCP's firmware stop ran in a sleep of this boot */ + bool t6041_ext_seen; /* * A T6030 external processor in the main DRM device: the kernel starts * its firmware on first use, its modes come from the attached display. @@ -701,6 +803,8 @@ struct apple_dcp { /* Display registers mappable to the DCP */ struct resource *disp_registers[MAX_DISP_REGISTERS]; + /* Their DART mappings with hw.map_reg_dart, made at the firmware's first map_reg */ + dma_addr_t map_reg_dva[MAX_DISP_REGISTERS]; unsigned int nr_disp_registers; struct resource disp_bw_scratch_res; @@ -720,6 +824,8 @@ struct apple_dcp { struct dcp_channel ch_cmd, ch_oobcmd; struct dcp_channel ch_cb, ch_oobcb, ch_async, ch_oobasync; + /* In-flight dcp_ack() mailbox sends not yet queued to RTKit. */ + atomic_t pending_acks; /* iomfb EP callback handlers */ const iomfb_cb_handler *cb_handlers; @@ -787,13 +893,28 @@ struct apple_dcp { bool typec_hpd_held; bool use_timestamps; bool vrr_enabled; + struct { + /* Pins the AV service and tracks HDR10 metadata for its link. */ + spinlock_t lock; + struct apple_epic_service *service; + u64 generation; + u8 sent[24]; + bool sent_valid; + bool infoframe; + } hdr; + /* The selected IOMFB backend programs catalogue colour IDs and PQ surfaces. */ + bool iomfb_template_pq; /* * The mode set asks for a PQ signal; output_pq: the one set carries it; - * output_edr: a panel shows the PQ content as EDR, edr_sent: swaps - * still carry EDR state the firmware must be told to drop. + * output_hdr: any non-SDR EOTF (PQ/HLG/HDR-gamma); output_edr: a panel + * shows the PQ content as EDR, edr_sent: swaps still carry EDR state + * the firmware must be told to drop. */ + struct dcp_color_request color_req; + struct dcp_color_mode active_color; bool pq_requested; bool output_pq; + bool output_hdr; bool output_edr; bool edr_sent; /* @@ -843,8 +964,14 @@ struct apple_dcp { bool sleep_v27_unhandled; bool s2r_active; bool s2r_stopped; + bool s2r_hdmi_irq_disabled; /* DPMS off stopped the firmware and lowered the domains; DPMS on brings them back. */ bool dpms_powered_off; + /* + * The firmware confirmed the scanout stop of a set_power_state(0) and no power-on has + * started since: its D572(0) has come and gone, and a second set_power_state(0) gets none. + */ + bool pipe_off; /* Refused its idle with the display off: the firmware still runs, the display is dark. */ bool s2r_refused_off; /* The firmware's secure mailbox, where it has one. */ @@ -858,6 +985,14 @@ struct apple_dcp { struct delayed_work secure_poll_wq; /* Stopped and not restarted, which outlives a suspend that gets refused. */ bool s2r_fw_down; + /* Stopped cold for firmware-driven sleep, with no restart until reboot. */ + bool sleep_cold_stopped; + /* + * Its last system suspend left the firmware running and its domains on + * (wakeup path), see dcp_sleep_keeps_firmware(). Cleared by the next + * suspend and resume. + */ + bool sleep_fw_runs; /* DCPEXT kept down through a dark wake, see dcp_s2r_dark_finish(). */ bool s2r_dark_held; struct notifier_block s2r_pm_nb; @@ -882,15 +1017,25 @@ struct apple_dcp { bool s2r_power_on; bool s2r_power_oob; u8 s2r_step; + struct mutex s2r_dart_lock; /* serializes D572 DART callback with s2r_active */ struct completion s2r_dart_done; + int s2r_dart_err; + struct completion s2r_hpd_done; + bool sleep_host_stop; + struct dcp_t6041_power t6041_power; struct device *s2r_disp_dart; struct device *s2r_dcp_dart; + /* hw.s2r without a layout in its hw data: the device tree's, see dcp_s2r_layout_from_dt() */ + struct dcp_s2r_layout s2r_dt_layout; + bool s2r_dt_layout_ok; /* eDP display without DP-HDMI conversion */ bool main_display; /* clear all surfaces on init */ bool surfaces_cleared; + bool boot_surface_pending; + bool boot_scanout_reserved; /* enable CRC calculation */ bool crc_enabled; @@ -969,9 +1114,19 @@ struct apple_dcp { char link_line[120]; u64 link_line_generation; u8 link_dsc; + /* + * hw.only_120hz_modes: the refresh rate iBoot left the panel at, from the + * firmware's "update_rr_index syncrate N" line before our first mode set + * (dcp_rtk_syslog_boot_rate()); 0 until seen. + */ + u32 boot_rate; /* V27 sleep: the panel's next mode set is the mode it already has */ bool v27_keep_mode; + /* Since the V27 wake: the panel's video interface opened, firmware reported the panel */ + struct completion v27_wake_video, v27_wake_hotplug; +#define V27_WAKE_VIDEO_MS 1500 +#define V27_WAKE_HOTPLUG_MS 250 /* V27 sleep: the output area of the call being pushed holds this (an in/out word) */ const void *push_out_prefill; @@ -1182,6 +1337,19 @@ struct apple_dcp { struct dcp_cec *cec; }; +/* A DCP driven through the firmware's iBoot interface alone. */ +static inline bool dcp_is_iboot(const struct apple_dcp *dcp) +{ + return dcp->fw_compat == DCP_FIRMWARE_IBOOT; +} + +struct apple_rtkit_shmem; +/* The common RTKit shared memory hooks, for a processor with its own RTKit ops. */ +int dcp_rtk_shmem_setup(void *cookie, struct apple_rtkit_shmem *bfr); +void dcp_rtk_shmem_destroy(void *cookie, struct apple_rtkit_shmem *bfr); +/* Keep a session that cannot be stopped, its DMA and this driver until reboot. */ +int dcp_retain_live_session(struct apple_dcp *dcp); + /* T8132 firmware uses its own wire codec, with the common DRM/KMS owner. */ static inline bool iomfb_is_m4(const struct apple_dcp *dcp) { @@ -1311,6 +1479,31 @@ static inline void dcp_takeover_adopt_proven(struct apple_dcp *dcp) WRITE_ONCE(dcp->desktop->takeover_adopted, false); } +/* + * Firmware interfaces whose swaps carry EDR, i.e. that the driver's EDR path + * implements (dcp_edr_prepare()): desktop 26.x and firmware 27. This is the + * interface ABI, not the panel: whether a panel has EDR headroom comes from + * its ADT (dcp_panel_edr()). + */ +static inline bool dcp_fw_swap_has_edr(struct apple_dcp *dcp) +{ + return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || + dcp->fw_compat == DCP_FIRMWARE_V_27_0; +} + +/* + * Whether the firmware decodes PQ surfaces on its EDR panel path. Firmware 27 + * does not: on the K114s (T6050) a surface tagged ST 2084 is decoded with the + * sRGB curve and scaled by about 10000/100, and every other transfer function + * value gives the plain sRGB decode, whatever the colour space. A PQ desktop + * then clips everything above a quarter of the code range to the panel's peak. + * So firmware 27 panels don't offer PQ until the EDR path maps it some other way. + */ +static inline bool dcp_fw_panel_decodes_pq(struct apple_dcp *dcp) +{ + return dcp->fw_compat != DCP_FIRMWARE_V_27_0; +} + static inline bool dcp_vrr_live(struct apple_dcp *dcp) { return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP && dcp->main_display && @@ -1349,12 +1542,20 @@ static inline bool dcp_is_v14_7_external(const struct apple_dcp *dcp) } /* - * Firmware 27's external processors (the T6050 DCPEXTs): their DP/HDMI - * audio service is the desktop one, on endpoint 0x2b (see av.c). + * Firmware 27's external processors with its own DPTX endpoint layout (the + * T6050 and firmware-27 T6041 DCPEXTs, ports on DPTX_ENDPOINT_V2): their + * DP/HDMI audio service is the desktop one, on endpoint 0x2b (see av.c). + * + * A firmware-27 DCP on the classic layout (the T8112 DCPs, whose 27.2 + * firmware advertises its ports on DPTX_ENDPOINT, dcp_v27_dptx_layout()) + * has the classic audio service on AV_ENDPOINT: there 0x2b is HDCP only. + * The layout is read as set at probe, so that the DP audio driver, which + * binds before the DCP starts, sees the same role as the DCP. */ static inline bool dcp_is_v27_external(const struct apple_dcp *dcp) { - return dcp->fw_compat == DCP_FIRMWARE_V_27_0 && dcp->hw.num_dptx_ports; + return dcp->fw_compat == DCP_FIRMWARE_V_27_0 && dcp->hw.num_dptx_ports && + dcp->hw.dptx_endpoint == DPTX_ENDPOINT_V2; } /* The 14.7 internal panel (J514S/J516S), presented through DCPLink. */ diff --git a/drivers/gpu/drm/apple/dcp-panel-test.h b/drivers/gpu/drm/apple/dcp-panel-test.h index 05d575d975fd50..428281e1a3feb1 100644 --- a/drivers/gpu/drm/apple/dcp-panel-test.h +++ b/drivers/gpu/drm/apple/dcp-panel-test.h @@ -1,6 +1,6 @@ /* SPDX-License-Identifier: GPL-2.0-only OR MIT */ /* Synthetic J616s-shaped input: no /panel or /product/panel. */ -static const u8 panel_test_adt[] = { +static const u8 panel_test_adt[] __maybe_unused = { 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x6e, 0x61, 0x6d, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, diff --git a/drivers/gpu/drm/apple/dcp-peer-frames-v27.h b/drivers/gpu/drm/apple/dcp-peer-frames-v27.h index abb7798a1764fe..ebd747a52eb8c7 100644 --- a/drivers/gpu/drm/apple/dcp-peer-frames-v27.h +++ b/drivers/gpu/drm/apple/dcp-peer-frames-v27.h @@ -8,10 +8,23 @@ * outstanding swaps, as in the existing single-pipe retirement path. */ struct dcp_peer_frames_v27 { - u32 first, submitted, engine[2], retired; - bool active, armed, failed, have[2], have_retired; + u32 timing; + u32 color; + u32 min_vrr; + bool output_hdr; + u32 first, submitted, engine[2], retired, shown[2]; + bool active, armed, failed, have[2], have_retired, have_shown[2]; }; +static inline bool dcp_peer_vrr_only_v27(const struct dcp_peer_frames_v27 *frames, + u32 timing, u32 color, u32 min_vrr, + bool output_hdr) +{ + return frames->active && !frames->failed && frames->timing == timing && + frames->color == color && frames->min_vrr != min_vrr && + frames->output_hdr == output_hdr; +} + static inline void dcp_peer_frame_submit_v27(struct dcp_peer_frames_v27 *s, u32 id) { if (!s->armed) { @@ -21,9 +34,14 @@ static inline void dcp_peer_frame_submit_v27(struct dcp_peer_frames_v27 *s, u32 s->submitted = id; } +/* + * *shown: both engines' firmware reported the retired swap itself as + * displayed, from completions of that swap ID. + */ static inline bool dcp_peer_frame_complete_v27(struct dcp_peer_frames_v27 *s, unsigned int engine, u32 id, - u32 *watermark) + bool shown_now, u32 *watermark, + bool *shown) { u32 done; @@ -33,6 +51,10 @@ static inline bool dcp_peer_frame_complete_v27(struct dcp_peer_frames_v27 *s, return false; s->engine[engine] = id; s->have[engine] = true; + if (shown_now) { + s->shown[engine] = id; + s->have_shown[engine] = true; + } if (!s->have[0] || !s->have[1]) return false; done = (s32)(s->engine[0] - s->engine[1]) < 0 ? s->engine[0] : s->engine[1]; @@ -40,6 +62,8 @@ static inline bool dcp_peer_frame_complete_v27(struct dcp_peer_frames_v27 *s, return false; s->retired = *watermark = done; s->have_retired = true; + *shown = s->have_shown[0] && s->shown[0] == done && + s->have_shown[1] && s->shown[1] == done; return true; } #endif diff --git a/drivers/gpu/drm/apple/dcp-peer-modeset-probe-v27.inc b/drivers/gpu/drm/apple/dcp-peer-modeset-probe-v27.inc index a5aa449b446dd0..0ac6d6c3447618 100644 --- a/drivers/gpu/drm/apple/dcp-peer-modeset-probe-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-modeset-probe-v27.inc @@ -7,11 +7,16 @@ static int dcp_peer_probe_power(struct apple_dcp *dcp, struct apple_dcp *peer, bool on) { struct dcp_peer_video_wait *wait; - struct dcp_method_entry method = { .name = "peer_power_test", - .tag = {'A', '4', '8', '4'} }; + struct dcp_method_entry method = { .name = "peer_power_test" }; u8 power[16] = {}, response[8]; + char peer_tag[4]; int ret; + ret = iomfb_v27_tag(dcp->v27_methods, "A484", method.tag) ?: + iomfb_v27_tag(peer->v27_methods, "A484", peer_tag); + if (ret) + return ret; + wait = kzalloc(sizeof(*wait), GFP_KERNEL); if (!wait) return -ENOMEM; @@ -134,13 +139,18 @@ static int dcp_peer_probe_modeset(struct apple_dcp *dcp, struct apple_dcp *peer, bool firmware_requires_merge) { struct dcp_peer_video_wait *wait; - struct dcp_method_entry method = { .name = "peer_modeset_test", - .tag = {'A', '4', '1', '3'} }; + struct dcp_method_entry method = { .name = "peer_modeset_test" }; __le32 mode[2] = {video->color_id, video->timing_id}; u32 primary_id, peer_id, phase, status; unsigned long deadline; + char peer_tag[4]; int ret; + ret = iomfb_v27_tag(dcp->v27_methods, "A413", method.tag) ?: + iomfb_v27_tag(peer->v27_methods, "A413", peer_tag); + if (ret) + return ret; + { guard(mutex)(&dcp_peer_lock); if (dcp->peer_reserved != peer || peer->peer_owner != dcp || diff --git a/drivers/gpu/drm/apple/dcp-peer-probe-v27.inc b/drivers/gpu/drm/apple/dcp-peer-probe-v27.inc index 33def11c752ea1..a1c017c98e0853 100644 --- a/drivers/gpu/drm/apple/dcp-peer-probe-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-probe-v27.inc @@ -24,9 +24,7 @@ static ssize_t peer_setup_test_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { - static const struct dcp_method_entry method = { - .name = "setup_peer_dcp", .tag = {'A', '3', '6', '6'}, - }; + struct dcp_method_entry method = { .name = "setup_peer_dcp" }; struct apple_dcp *dcp = dev_get_drvdata(dev); struct dcp_peer_probe_wait *wait; __le32 enabled = cpu_to_le32(1); @@ -55,6 +53,11 @@ static ssize_t peer_setup_test_store(struct device *dev, kref_put(&wait->refs, dcp_peer_probe_free); return -EBUSY; } + ret = iomfb_v27_tag(dcp->v27_methods, "A366", method.tag); + if (ret) { + kref_put(&wait->refs, dcp_peer_probe_free); + return ret; + } kref_get(&wait->refs); /* Peer-DCP setup (one bool argument): four input * bytes (boolean followed by zero padding), no output. diff --git a/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc b/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc index cd8340105b37bf..6b45166543e816 100644 --- a/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc @@ -69,7 +69,7 @@ static void dcp_peer_finish_v27(struct apple_dcp *dcp, struct apple_dcp *peer) if (!dcp_peer_both_v27(dcp, peer, "A449", config, sizeof(config), NULL, 0x7c, false) && !dcp_peer_param_v27(dcp, peer, 3, 1, 0x10000) && !dcp_peer_both_v27(dcp, peer, "A453", &zero, sizeof(zero), tile, sizeof(tile), false) && - !dcp_peer_param_v27(dcp, peer, 6, 1, dcp->output_pq ? 0x20000 : 0x10000)) + !dcp_peer_param_v27(dcp, peer, 6, 1, dcp->output_hdr ? 0x20000 : 0x10000)) dev_info(dcp->dev, "paired engines report %ux%u each\n", le32_to_cpu(tile[0]), le32_to_cpu(tile[1])); } @@ -112,7 +112,7 @@ static int dcp_peer_limited_stop_v27(struct apple_dcp *dcp, struct apple_dcp *pe int dcp_peer_modeset_v27(struct apple_dcp *dcp, u32 timing, u32 color, u32 min_vrr) { struct apple_dcp *peer; - bool limited, prepared; + bool limited, prepared, vrr_only; int ret = -EOPNOTSUPP; if (!peer_scanout || !peer_allocation_probe || @@ -120,8 +120,13 @@ int dcp_peer_modeset_v27(struct apple_dcp *dcp, u32 timing, u32 color, u32 min_v return ret; if (timing > U32_MAX - 10000 || color > U32_MAX - 10000) return -EINVAL; - /* No paired call, nor wait for one, for a display the limit leaves no pair. */ + /* + * No paired call, nor wait for one, for a display without a peer or one + * the limit leaves no pair. The device lock below may be the probe's. + */ scoped_guard(mutex, &dcp_peer_lock) { + if (!dcp->peer_reserved) + return ret; limited = dcp_peer_limited_pair_locked(dcp, &prepared); if (limited && !prepared) return ret; @@ -145,11 +150,52 @@ int dcp_peer_modeset_v27(struct apple_dcp *dcp, u32 timing, u32 color, u32 min_v ret = -EBUSY; goto unlock; } + vrr_only = dcp->peer_tiling.modeset_complete && + peer->peer_tiling.modeset_complete && + dcp_peer_vrr_only_v27(&dcp->peer_frames, timing, color, + min_vrr, dcp->output_hdr); } if (limited) { ret = dcp_peer_limited_stop_v27(dcp, peer); goto peer_unlock; } + /* + * Adaptive sync uses parameter 15 on both engines. Leave a running + * pair installed when its timing and color are still current. If + * either engine refuses the update, rebuild both with the new rate. + */ + if (vrr_only) { + bool still_owned, updated = false; + + ret = dcp_peer_param_v27(dcp, peer, 15, 3, min_vrr); + scoped_guard(mutex, &dcp_peer_lock) { + still_owned = dcp->peer_reserved == peer && + peer->peer_owner == dcp; + limited = still_owned && + dcp_peer_limited_pair_locked(dcp, &prepared); + if (!ret && !limited && still_owned && + dcp->peer_tiling.modeset_complete && + peer->peer_tiling.modeset_complete && + dcp_peer_vrr_only_v27(&dcp->peer_frames, timing, + color, min_vrr, + dcp->output_hdr)) { + dcp->peer_frames.min_vrr = min_vrr; + dev_dbg(dcp->dev, "paired adaptive sync minimum %#x\n", min_vrr); + updated = true; + } + } + if (updated) + goto peer_unlock; + if (!still_owned) { + ret = -EBUSY; + goto peer_unlock; + } + if (limited) { + ret = prepared ? dcp_peer_limited_stop_v27(dcp, peer) + : -EOPNOTSUPP; + goto peer_unlock; + } + } ret = dcp_peer_prepare_v27(dcp, peer, min_vrr); if (ret) goto peer_unlock; @@ -158,7 +204,13 @@ int dcp_peer_modeset_v27(struct apple_dcp *dcp, u32 timing, u32 color, u32 min_v dcp_peer_finish_v27(dcp, peer); if (!ret) { guard(mutex)(&dcp_peer_lock); - dcp->peer_frames = (struct dcp_peer_frames_v27){ .active = true }; + dcp->peer_frames = (struct dcp_peer_frames_v27){ + .timing = timing, + .color = color, + .min_vrr = min_vrr, + .output_hdr = dcp->output_hdr, + .active = true, + }; dev_info(dcp->dev, "paired DRM mode ready: timing=%u color=%u min_vrr=%#x\n", timing, color, min_vrr); } @@ -325,11 +377,12 @@ void dcp_peer_swap_failed_v27(struct apple_dcp *dcp) dcp_mode_invalidate(&dcp->mode_state); } -bool dcp_peer_swap_complete_v27(struct apple_dcp *dcp, u32 id, ktime_t now, - void (*report)(struct apple_dcp *, u32, ktime_t)) +bool dcp_peer_swap_complete_v27(struct apple_dcp *dcp, u32 id, ktime_t now, bool shown, + void (*report)(struct apple_dcp *, u32, ktime_t, bool)) { struct apple_dcp *owner; u32 watermark; + bool both_shown; /* Independent CRTCs must not serialize through the pair's mutex. */ if (!peer_scanout || (!READ_ONCE(dcp->peer_frames.active) && @@ -339,9 +392,10 @@ bool dcp_peer_swap_complete_v27(struct apple_dcp *dcp, u32 id, ktime_t now, owner = dcp->peer_owner ?: dcp; if (!peer_scanout || !owner->peer_frames.active) return false; - if (dcp_peer_frame_complete_v27(&owner->peer_frames, dcp != owner, id, &watermark)) + if (dcp_peer_frame_complete_v27(&owner->peer_frames, dcp != owner, id, shown, + &watermark, &both_shown)) /* Queue the combined watermark to the primary IOMFB owner. */ - report(owner, watermark, now); + report(owner, watermark, now, both_shown); return true; } diff --git a/drivers/gpu/drm/apple/dcp-peer-swap-probe-v27.inc b/drivers/gpu/drm/apple/dcp-peer-swap-probe-v27.inc index ed73f355eda7ec..343fa1872badae 100644 --- a/drivers/gpu/drm/apple/dcp-peer-swap-probe-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-swap-probe-v27.inc @@ -6,6 +6,7 @@ struct dcp_peer_background { struct iomfb_transaction transaction; struct dcp_peer_video_wait *wait; struct dcp_swap_submit_req_v27 wire; + char tag[4]; bool sent; }; @@ -26,10 +27,11 @@ static void dcp_peer_background_start(struct apple_dcp *dcp, { struct dcp_peer_background *background = container_of(transaction, struct dcp_peer_background, transaction); - struct dcp_method_entry method = { .name = "peer_background_test", - .tag = {'A', '4', '0', '8'} }; + struct dcp_method_entry method = { .name = "peer_background_test" }; struct dcp_swap_submit_resp_v27 failed = { .ret = ~0U }; + memcpy(method.tag, background->tag, sizeof(method.tag)); + background->sent = true; if (!dcp_present_begin_h17p(&dcp->present_state_h17p, background->wire.swap.swap_id)) { @@ -55,13 +57,18 @@ static int dcp_peer_queue_background(struct apple_dcp *dcp, struct dcp_peer_video_wait *wait) { struct dcp_peer_background *background; + char tag[4]; int ret; + ret = iomfb_v27_tag(dcp->v27_methods, "A408", tag); + if (ret) + return ret; background = kzalloc_obj(*background); if (!background) return -ENOMEM; background->wire = *wire; background->wait = wait; + memcpy(background->tag, tag, sizeof(background->tag)); kref_get(&wait->refs); background->transaction.start = dcp_peer_background_start; background->transaction.release = dcp_peer_background_release; @@ -185,6 +192,7 @@ static void dcp_peer_a407_background_start(struct apple_dcp *dcp, { struct dcp_peer_a407_background *background = container_of(transaction, struct dcp_peer_a407_background, transaction); + /* The J714s's 27.0 swap form, whose table names A407 (iomfb_v27_methods_j714s()). */ struct dcp_method_entry method = { .name = "peer_background_test", .tag = {'A', '4', '0', '7'} }; struct dcp_swap_submit_resp_v27 failed = { .ret = ~0U }; @@ -345,6 +353,8 @@ static ssize_t peer_swap_test_store(struct device *dev, dcp->crtc->base.state->active || peer->crtc->base.state->active || dcp->fw_compat != DCP_FIRMWARE_V_27_0 || peer->fw_compat != DCP_FIRMWARE_V_27_0 || + /* Both engines must take the swap form the owner sends. */ + dcp->v27_a407 != peer->v27_a407 || !device_trylock(peer->dev)) { ret = -EBUSY; goto out; diff --git a/drivers/gpu/drm/apple/dcp-peer-v27.inc b/drivers/gpu/drm/apple/dcp-peer-v27.inc index a824ab7e992659..34ee3e472d3ef0 100644 --- a/drivers/gpu/drm/apple/dcp-peer-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-v27.inc @@ -8,12 +8,14 @@ module_param(peer_allocation_probe, bool, 0444); MODULE_PARM_DESC(peer_allocation_probe, "Firmware27 logical peer allocation for merged modes (default: on)"); /* - * The platform limit on merged modes (dcp_fabric_merged_fits()) holds on the - * board it has run on, for the J714s's T6050 external display processors. + * The platform limit on merged modes (dcp_fabric_merged_fits()) holds for the + * external display processors whose node says so (apple,merged-mode-limit). */ static bool dcp_peer_limit_applies(struct apple_dcp *dcp) { - return dcp->fw_compat == DCP_FIRMWARE_V_27_0 && dcp_j714s_ext(dcp->dev); + return dcp->fw_compat == DCP_FIRMWARE_V_27_0 && + of_device_is_compatible(dcp->dev->of_node, "apple,t6050-dcpext") && + of_property_read_bool(dcp->dev->of_node, "apple,merged-mode-limit"); } /* @@ -68,8 +70,7 @@ void dcp_peer_limit_update_v27(struct drm_device *drm) unsigned int n = 0, i; struct drm_crtc *crtc; - /* Neither a board without the limit nor a device without CRTCs. */ - if (!of_machine_is_compatible("apple,j714s") || !drm->mode_config.num_crtc) + if (!drm->mode_config.num_crtc) return; scoped_guard(mutex, &dcp_peer_lock) { drm_for_each_crtc(crtc, drm) { diff --git a/drivers/gpu/drm/apple/dcp-peer-video-probe-v27.inc b/drivers/gpu/drm/apple/dcp-peer-video-probe-v27.inc index 3560cfc447a99f..86b0f20b5823d4 100644 --- a/drivers/gpu/drm/apple/dcp-peer-video-probe-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-video-probe-v27.inc @@ -37,6 +37,10 @@ static int dcp_peer_video_call_stream(struct apple_dcp *dcp, bool independent, if (out_size > sizeof(wait->reply)) return -EINVAL; + /* The calls name 27.0 IDs: this engine's build may number them differently. */ + ret = iomfb_v27_tag(dcp->v27_methods, tag, method.tag); + if (ret) + return ret; /* An unrelated AP thread gets its own firmware stream. A369/A367/etc. * must not be mistaken for nested callbacks of the pending A413. * Stream1 (the driver's OOB context) is independent of stream0. @@ -46,7 +50,6 @@ static int dcp_peer_video_call_stream(struct apple_dcp *dcp, bool independent, wait = kzalloc(sizeof(*wait), GFP_KERNEL); if (!wait) return -ENOMEM; - memcpy(method.tag, tag, sizeof(method.tag)); wait->size = out_size; init_completion(&wait->done); kref_init(&wait->refs); diff --git a/drivers/gpu/drm/apple/dcp-v27-sleep.inc b/drivers/gpu/drm/apple/dcp-v27-sleep.inc index 027927a4ec055f..6bbef61ae18d2c 100644 --- a/drivers/gpu/drm/apple/dcp-v27-sleep.inc +++ b/drivers/gpu/drm/apple/dcp-v27-sleep.inc @@ -69,6 +69,13 @@ static void dcp_v27_sessions(struct apple_dcp *dcp, bool open); static bool dcp_v27_external(struct apple_dcp *dcp); static int dcp_v27_rtkit_cycle(struct apple_dcp *dcp, unsigned int pause_ms); +/* The wake's mode set waits for these two reports: none from before the power-on counts. */ +static void dcp_v27_wake_expect(struct apple_dcp *dcp) +{ + reinit_completion(&dcp->v27_wake_video); + reinit_completion(&dcp->v27_wake_hotplug); +} + /* * The calls made before A484's plain form in either direction, at the wake and at the display's * sleep: A414, A489, A489, A487, A489, A412. At the wake each is followed by A500's wake form, at @@ -250,6 +257,41 @@ static int dcp_v27_ext_cycle_ready(struct apple_dcp *dcp) return dcp->s2r_dcp_dart ? 0 : -ENODEV; } +/* + * A restart with the secure port (firmware 27.2), as dcp_s2r_warm_restart() does it: the + * port restarted before RUN, mapped between the main mailbox's IOP report and its AP on, then on. + */ +static int dcp_v27_warm_restart(struct apple_dcp *dcp, bool strict) +{ + int ret; + + if (dcp->secure_rtk && dcp->secure_answered) { + dcp_secure_poll_stop(dcp); + ret = apple_rtkit_port_restart(dcp->secure_rtk); + if (ret) + dev_warn(dcp->dev, "V27 wake: secure port restart: %d\n", ret); + } + return strict ? apple_rtkit_warm_restart_strict(dcp->rtk) : + apple_rtkit_warm_restart_stopped(dcp->rtk); +} + +static int dcp_v27_boot(struct apple_dcp *dcp) +{ + bool secure = dcp->secure_rtk && dcp->secure_answered; + int ret; + + ret = apple_rtkit_boot_with(dcp->rtk, secure ? dcp_secure_port_map : NULL, dcp); + if (ret || !secure) + return ret; + ret = dcp->secure_map_ret ?: apple_rtkit_port_on(dcp->secure_rtk, DCP_SECURE_TIMEOUT_MS); + if (ret) + dev_warn(dcp->dev, "V27 wake: secure port map %d (%lld us), on %d\n", + dcp->secure_map_ret, dcp->secure_map_us, ret); + else + dcp_secure_poll_start(dcp); + return 0; +} + /* * macOS's DCP stop/restart between its wake steps: sessions closed, AP and IOP * idle, IDLE_DONE, receive off, CPU_CONTROL RUN off; dart-dcp stopped, the display's domain off and, @@ -273,7 +315,11 @@ static int dcp_v27_rtkit_cycle(struct apple_dcp *dcp, unsigned int pause_ms) if (s && s->cycle_failed) return -ECANCELED; dcp_v27_sessions(dcp, false); - ret = apple_rtkit_idle_strict(dcp->rtk); + /* With a secure port: the IOP idle is taken only after the port's AP idle */ + if (dcp->secure_rtk && dcp->secure_answered) + ret = apple_rtkit_idle_strict_with(dcp->rtk, dcp_secure_port_idle_strict, dcp); + else + ret = apple_rtkit_idle_strict(dcp->rtk); if (ret) { dev_warn(dcp->dev, "V27 wake: RTKit cycle: idle %d\n", ret); dcp_v27_sessions(dcp, true); @@ -349,12 +395,12 @@ static int dcp_v27_rtkit_cycle(struct apple_dcp *dcp, unsigned int pause_ms) dev_warn(dcp->dev, "V27 wake: RTKit cycle: display DART rewrite %d\n", ret); } } - ret = apple_rtkit_warm_restart_strict(dcp->rtk); + ret = dcp_v27_warm_restart(dcp, true); if (!ret) { writel(readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) | APPLE_DCP_COPROC_CPU_CONTROL_RUN, dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); run_status = readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_STATUS); - ret = apple_rtkit_boot(dcp->rtk); + ret = dcp_v27_boot(dcp); } /* * An external processor that did not start is not left down: its DART, power words and @@ -373,13 +419,13 @@ static int dcp_v27_rtkit_cycle(struct apple_dcp *dcp, unsigned int pause_ms) ret = apple_dart_m5_display_cycle(dcp->s2r_dcp_dart, true); } if (!ret) - ret = apple_rtkit_warm_restart_stopped(dcp->rtk); + ret = dcp_v27_warm_restart(dcp, false); if (!ret) { writel(readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) | APPLE_DCP_COPROC_CPU_CONTROL_RUN, dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); run_status = readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_STATUS); - ret = apple_rtkit_boot(dcp->rtk); + ret = dcp_v27_boot(dcp); } } if (ret) { @@ -1177,6 +1223,8 @@ static int dcp_v27_reopen_live(struct apple_dcp *dcp) dcp_v27_rtkit_cycle(dcp, 0); if (s->soft_off && v27_a115) iomfb_v27_sleep_call(dcp, "A489", NULL, 0, 4); + /* Before the call that brings the panel up: its reports come from workers. */ + dcp_v27_wake_expect(dcp); ret = iomfb_v27_sleep_rpc(dcp, false, true); if (ret) return ret; @@ -1208,6 +1256,8 @@ static int dcp_v27_reopen_live(struct apple_dcp *dcp) dcp_v27_display_stage(dcp, per_call, per_call && v27_session_rounds, per_call); if (v27_session_rounds) dcp_v27_sessions(dcp, true); + /* Again, in the session the display comes on in. */ + dcp_v27_wake_expect(dcp); ret = iomfb_v27_sleep_plain(dcp, true); if (ret) return ret; @@ -1258,6 +1308,8 @@ static int dcp_v27_reopen_live(struct apple_dcp *dcp) return 0; } +static int dcp_v27_secure_idle_atomic(void *data); + static int dcp_v27_late_arm(void *data) { struct dcp_v27_sleep *s = data; @@ -1287,6 +1339,8 @@ static int dcp_v27_late_arm(void *data) ret = apple_rtkit_v27_arm(dcp->rtk, &s->rx); if (ret) dev_info(dcp->dev, "V27 arm: RTKit %d\n", ret); + else + apple_rtkit_v27_set_after_ap(s->rx, dcp_v27_secure_idle_atomic, dcp); } if (ret) { if (s->display && !s->display_early) { @@ -1301,11 +1355,32 @@ static int dcp_v27_late_arm(void *data) s->firmware = NULL; return ret; } + /* + * The secure port is idled from the late stop, with nothing else reading it. Stopped + * only here, once the sleep is armed: a refused or cancelled sleep before this leaves + * the poller running, and a disarm without a stop starts it again. + */ + if (dcp->secure_rtk && dcp->secure_answered) + dcp_secure_poll_stop(dcp); s->phase = V27_ARMED; return 0; } -static int dcp_v27_late_check(void *data) +/* + * With a secure port (firmware 27.2): its AP idle between the main mailbox's AP idle and + * its IOP idle, polled, as this runs with interrupts off. Not acknowledged, it fails the stop: + * the firmware would not take the IOP idle. + */ +static int dcp_v27_secure_idle_atomic(void *data) +{ + struct apple_dcp *dcp = data; + + if (!dcp->secure_rtk || !dcp->secure_answered) + return 0; + return apple_rtkit_v27_port_ap_idle_atomic(dcp->secure_rtk, 5000); +} + +static int dcp_v27_late_check(void *data, bool committed) { struct dcp_v27_sleep *s = data; struct apple_dcp *dcp = s->dcp; @@ -1322,7 +1397,7 @@ static int dcp_v27_late_check(void *data) if (!ret) ret = apple_dart_v27_check(s->firmware); if (!ret) - ret = apple_rtkit_v27_check(s->rx); + ret = apple_rtkit_v27_check(s->rx, committed); return ret; } @@ -1376,8 +1451,12 @@ static int dcp_v27_late_disarm(void *data, bool stopped) if (ret) return dcp_v27_fail(s, ret); s->rx = NULL; - if (!stopped) + if (!stopped) { s->phase = V27_PREPARED; + /* The firmware never stopped: the port is read again. A wake's boot does it otherwise. */ + if (s->dcp->secure_rtk && s->dcp->secure_answered) + dcp_secure_poll_start(s->dcp); + } return 0; } @@ -1439,9 +1518,8 @@ static int dcp_v27_sleep_prepare(struct apple_dcp *dcp) dev_warn(dcp->dev, "V27 sleep: no sleep RPC arguments in the DT\n"); return -EOPNOTSUPP; } - if (!dcp->retain_dma || IS_ERR_OR_NULL(dcp->rtk) || !dcp->active || dcp->crashed || dcp->quiescing || - dcp->secure_rtk) - return dcp_v27_refuse(dcp, "coprocessor not live (dma, rtkit, active, crashed, quiescing, secure)"); + if (!dcp->retain_dma || IS_ERR_OR_NULL(dcp->rtk) || !dcp->active || dcp->crashed || dcp->quiescing) + return dcp_v27_refuse(dcp, "coprocessor not live (dma, rtkit, active, crashed, quiescing)"); /* Mode-config suspend is the actual DRM scanout-owner boundary. No HPD * shortcut: external firmware still executes A484/A500/AFK and late IDLE. */ @@ -1606,7 +1684,18 @@ static int dcp_v27_sleep_prepare(struct apple_dcp *dcp) if (ret) goto uncertain; for (i = ARRAY_SIZE(v27_sleep_endpoints); i-- > 0;) { - ret = afk_v27_sleep_control(dcp->sleep_v27_ep[v27_sleep_endpoints[i] - 0x20], false); + struct apple_dcp_afkep *ep = dcp->sleep_v27_ep[v27_sleep_endpoints[i] - 0x20]; + int check; + + /* + * An endpoint still taking a message (a service announced late, seen on 0x31 of + * a K116s DCPEXT) answers -EBUSY for a moment: wait it out as the other steps do, + * rather than refuse the sleep. + */ + if (ep) + read_poll_timeout(afk_v27_sleep_check, check, check != -EBUSY, 1000, + 300 * USEC_PER_MSEC, false, ep); + ret = afk_v27_sleep_control(ep, false); if (ret) { char name[12]; @@ -1694,7 +1783,7 @@ static int dcp_v27_sleep_restart(struct apple_dcp *dcp) if (s->phase == V27_STOPPED) { ret = apple_sleep_display_v27_power_ready(dcp->dev); if (!ret) - ret = apple_rtkit_warm_restart_strict(dcp->rtk); + ret = dcp_v27_warm_restart(dcp, true); /* * The final step stopped this CPU and it is still stopped: the firmware boots * from its reset vector next, so the state tracked before the stop does not @@ -1703,12 +1792,12 @@ static int dcp_v27_sleep_restart(struct apple_dcp *dcp) if (ret == -EUCLEAN && READ_ONCE(dcp->s2r_fw_down) && !(readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) & APPLE_DCP_COPROC_CPU_CONTROL_RUN)) - ret = apple_rtkit_warm_restart_stopped(dcp->rtk); + ret = dcp_v27_warm_restart(dcp, false); if (ret) return dcp_v27_fail(s, ret); writel(readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) | APPLE_DCP_COPROC_CPU_CONTROL_RUN, dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); - ret = apple_rtkit_boot(dcp->rtk); + ret = dcp_v27_boot(dcp); if (ret) return dcp_v27_fail(s, ret); } diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index b16995083020dc..6abd5cc9fda605 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -14,15 +14,18 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -38,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -50,6 +54,7 @@ #include #include #include +#include #include #include #include @@ -77,6 +82,7 @@ #include "dptx-service.h" #include "iomfb.h" #include "iomfb_internal.h" +#include "iomfb_iboot.h" #include "iomfb_m4.h" #include "ibootep.h" #include "iomfb_internal.h" @@ -114,15 +120,15 @@ static bool dcp_session_retained(struct device *dev) return retained; } -static int dcp_pin_live_session(struct apple_dcp *dcp) +/* + * Keep a live session's DMA device, domain use and this driver until reboot, + * and refuse a new probe of its device after an unbind. + */ +int dcp_retain_live_session(struct apple_dcp *dcp) { struct dcp_session_ref *session; - if ((!dcp->hw.adopt_live_session && - dcp->hw.iomfb_method_profile != - DCP_IOMFB_METHODS_H17P_EXTERNAL) || - !dcp_fail_stop(dcp) || - dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17G || dcp->retain_dma) + if (dcp->retain_dma) return 0; session = kzalloc_obj(*session); if (!session) @@ -143,6 +149,17 @@ static int dcp_pin_live_session(struct apple_dcp *dcp) return 0; } +static int dcp_pin_live_session(struct apple_dcp *dcp) +{ + if ((!dcp->hw.adopt_live_session && + dcp->hw.iomfb_method_profile != + DCP_IOMFB_METHODS_H17P_EXTERNAL) || + !dcp_fail_stop(dcp) || + dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17G || dcp->retain_dma) + return 0; + return dcp_retain_live_session(dcp); +} + static void dcp_release_dma_domain(void *data) { struct apple_dcp *dcp = data; @@ -244,18 +261,24 @@ static void dcp_secure_port_start(struct apple_dcp *dcp) } /* Between the main mailbox's AP idle and its IOP idle. */ -static void dcp_secure_port_idle(void *data) +static int dcp_secure_port_idle_strict(void *data) { struct apple_dcp *dcp = data; int ret; if (!dcp->secure_rtk || !dcp->secure_answered) - return; + return 0; dcp_secure_poll_stop(dcp); ret = apple_rtkit_port_idle(dcp->secure_rtk, DCP_SECURE_TIMEOUT_MS); if (ret) dev_warn(dcp->dev, "secure port AP idle not acknowledged: %d\n", ret); + return ret; +} + +static void dcp_secure_port_idle(void *data) +{ + dcp_secure_port_idle_strict(data); } static void dcp_release_secure_rtkit(void *data) @@ -272,10 +295,18 @@ static int dcp_secure_port_init(struct apple_dcp *dcp) { struct device *dev = dcp->dev; - if (of_property_match_string(dev->of_node, "mbox-names", "secure") < 0) + /* + * The secure mailbox is the second of mboxes, or named by apple,secure-mbox where the + * boot loader wants mboxes to hold the one ASC mailbox (it refuses the display handoff + * otherwise). + */ + if (of_property_match_string(dev->of_node, "mbox-names", "secure") >= 0) + dcp->secure_rtk = apple_rtkit_init(dev, dcp, "secure", 0, &dcp_secure_rtkit_ops); + else if (of_property_present(dev->of_node, "apple,secure-mbox")) + dcp->secure_rtk = apple_rtkit_init_mbox_prop(dev, dcp, "apple,secure-mbox", + &dcp_secure_rtkit_ops); + else return 0; - - dcp->secure_rtk = apple_rtkit_init(dev, dcp, "secure", 0, &dcp_secure_rtkit_ops); if (IS_ERR(dcp->secure_rtk)) { int ret = PTR_ERR(dcp->secure_rtk); @@ -293,21 +324,155 @@ static int dcp_secure_port_init(struct apple_dcp *dcp) * display domains through apple,display-power, and the internal DCP only takes IOP idle * once its secure port has gone idle. A device tree without those keeps the firmware * running: DPMS is the backlight alone and the display stays up across a sleep. A SoC - * without a secure mailbox says so (hw.s2r_no_secure_port), and one behind - * appledrm.s2r_untested stops its firmware for DPMS off and J813 system sleep. + * without a secure mailbox says so (hw.s2r_no_secure_port). Power words from the device + * tree stop the firmware by default; a SoC whose static words are only derived (T8142) does + * so only with appledrm.s2r_untested. + */ +/* + * hw.s2r without a layout in its hw data takes its words from the device tree, the ones its + * deep sleep lowers: DISP_CPU is the first state of the DCP's power-domains, DISP_FE that + * state's parent and DISP_SYS theirs, each at its reg in the power manager whose block the + * display-power node's "ps" starts. The retention words are DISP_CPU's two + * apple,retention-workaround entries (power manager offset, mask, value while off), in the + * node's "pwrgate" block, and the value each reads now, with the DCP running, is the one it + * gets back at power-on. It counts in pmc-dcp where the node has that word. The DART streams + * are the ones its DARTs have enabled at probe, see dcp_s2r_layout_streams(). */ +static int dcp_s2r_layout_from_dt(struct apple_dcp *dcp) +{ + struct dcp_s2r_layout *l = &dcp->s2r_dt_layout; + struct device_node *power, *pmgr = NULL, *ps[3] = {}; + struct resource ps_res, gate_res, pmgr_res; + u32 off[3], ret[6]; + void __iomem *gate; + int i, err = -EINVAL; + + power = of_parse_phandle(dcp->dev->of_node, "apple,display-power", 0); + if (!power) + return -ENODEV; + if (of_address_to_resource(power, of_property_match_string(power, "reg-names", "ps"), + &ps_res) || + of_address_to_resource(power, of_property_match_string(power, "reg-names", "pwrgate"), + &gate_res)) + goto out; + ps[0] = of_parse_phandle(dcp->dev->of_node, "power-domains", 0); + for (i = 1; i < 3 && ps[i - 1]; i++) + ps[i] = of_parse_phandle(ps[i - 1], "power-domains", 0); + if (!ps[2]) + goto out; + pmgr = of_get_parent(ps[0]); + if (!pmgr || of_address_to_resource(pmgr, 0, &pmgr_res) || pmgr_res.start != ps_res.start) + goto out; + for (i = 0; i < 3; i++) { + struct device_node *parent = of_get_parent(ps[i]); + + of_node_put(parent); + if (parent != pmgr || of_property_read_u32(ps[i], "reg", &off[i]) || + resource_size(&ps_res) < 4 || off[i] > resource_size(&ps_res) - 4 || + off[i] % 4) + goto out; + } + if (of_property_read_u32_array(ps[0], "apple,retention-workaround", ret, 6) || + of_property_count_u32_elems(ps[0], "apple,retention-workaround") != 6) + goto out; + for (i = 0; i < 6; i += 3) { + u64 at = pmgr_res.start + ret[i]; + + if (at <= gate_res.start || at + 4 > gate_res.end + 1 || at % 4 || !ret[i + 1] || + ret[i + 2] & ~ret[i + 1]) + goto out; + } + gate = ioremap(gate_res.start, resource_size(&gate_res)); + if (!gate) { + err = -ENOMEM; + goto out; + } + *l = (struct dcp_s2r_layout){ + .disp_cpu = off[0], + .disp_fe = off[1], + .disp_sys = off[2], + .ret_ff = pmgr_res.start + ret[0] - gate_res.start, + .ret_ff_mask = ret[1], + .ret_ff_off = ret[2], + .ret_mem = pmgr_res.start + ret[3] - gate_res.start, + .ret_mem_mask = ret[4], + .ret_mem_off = ret[5], + .pmc_dcp = of_property_match_string(power, "reg-names", "pmc-dcp") >= 0, + }; + l->ret_ff_on = readl(gate + l->ret_ff); + l->ret_mem_on = readl(gate + l->ret_mem); + iounmap(gate); + dcp->s2r_dt_layout_ok = true; + dev_dbg(dcp->dev, "display power from the device tree: CPU %#x FE %#x SYS %#x, retention %#x/%#x on %#x/%#x\n", + l->disp_cpu, l->disp_fe, l->disp_sys, l->ret_ff, l->ret_mem, l->ret_ff_on, + l->ret_mem_on); + err = 0; +out: + for (i = 0; i < 3; i++) + of_node_put(ps[i]); + of_node_put(pmgr); + of_node_put(power); + return err; +} + +static struct device *dcp_s2r_find_dart(struct device_node *np); + +/* + * A device-tree layout's DART streams: the ones its DARTs have enabled at probe, with the + * firmware running. A DCP DART, or a piodma DART where the DCP has a piodma node, that is + * missing or reads none leaves nothing for the stop to restore, so the layout is refused. + */ +static int dcp_s2r_layout_streams(struct apple_dcp *dcp) +{ + struct device_node *piodma; + struct device *dart; + + dart = dcp_s2r_find_dart(dcp->dev->of_node); + if (!dart) + return -ENODEV; + dcp->s2r_dt_layout.dcp_streams = apple_dart_enabled_streams(dart); + put_device(dart); + if (!dcp->s2r_dt_layout.dcp_streams) + return -ENODATA; + piodma = of_get_child_by_name(dcp->dev->of_node, "piodma"); + if (piodma) { + dart = dcp_s2r_find_dart(piodma); + of_node_put(piodma); + if (!dart) + return -ENODEV; + dcp->s2r_dt_layout.disp_streams = apple_dart_enabled_streams(dart); + put_device(dart); + if (!dcp->s2r_dt_layout.disp_streams) + return -ENODATA; + } + dev_dbg(dcp->dev, "DART streams for the stop: DCP %#x, display %#x\n", + dcp->s2r_dt_layout.dcp_streams, dcp->s2r_dt_layout.disp_streams); + return 0; +} + static void dcp_s2r_check_dt(struct apple_dcp *dcp) { struct device_node *np = dcp->dev->of_node; bool power = of_property_present(np, "apple,display-power"); bool secure = dcp->hw.s2r_no_secure_port || - of_property_match_string(np, "mbox-names", "secure") >= 0; + of_property_match_string(np, "mbox-names", "secure") >= 0 || + of_property_present(np, "apple,secure-mbox"); if (dcp->hw.s2r && (!power || !secure)) { dev_info(dcp->dev, "no %s in the device tree, the firmware keeps running\n", !power ? "apple,display-power" : "secure mailbox"); dcp->hw.s2r = false; } + if (dcp->hw.s2r && !dcp->hw.s2r_layout) { + int ret = dcp_s2r_layout_from_dt(dcp) ?: dcp_s2r_layout_streams(dcp); + + if (ret) { + dev_info(dcp->dev, "no display power layout (%d), the firmware keeps running\n", + ret); + dcp->s2r_dt_layout_ok = false; + dcp->hw.s2r = false; + } + } if (dcp->hw.s2r_ext && !power) { dev_info(dcp->dev, "no apple,display-power in the device tree, the firmware keeps running\n"); dcp->hw.s2r_ext = false; @@ -331,13 +496,18 @@ static void dcp_release_rtkit(void *data) #define DCP_BOOT_TIMEOUT msecs_to_jiffies(1000) +/* + * The H17P external display path is admitted by the processor and its + * firmware: an apple,t8140-dcpext node (the H17P external method profile) + * whose apple,firmware-version and apple,firmware-compat name the one + * firmware release that path speaks. The board does not enter into it. + */ bool dcp_h17p_external_supported(struct device_node *np) { u32 firmware[DCP_EXTERNAL_FW_CELLS], compat[DCP_EXTERNAL_FW_CELLS]; int firmware_cells, compat_cells; - if (!of_machine_is_compatible("apple,j700") || - !of_device_is_compatible(np, "apple,t8140-dcpext")) + if (!of_device_is_compatible(np, "apple,t8140-dcpext")) return false; firmware_cells = of_property_read_variable_u32_array( np, "apple,firmware-version", firmware, @@ -467,12 +637,13 @@ MODULE_PARM_DESC(t6050_ext_sleep, /* * What a T6050 external display processor gained outside the firmware 27 sleep itself (the * Type-C reconnect skipped for a crashed one, a crashed one refusing a deep sleep before - * anything is stopped, the link line) is in force on the board it has run on, the J714s. - * Elsewhere, other boards with the same SoC included, these are as before. + * anything is stopped, the link line) is in force where the sleep's description has the + * display coprocessors sleep by their method table (apple,display-method-sleep). Elsewhere, + * other boards with the same SoC included, these are as before. */ static bool dcp_j714s_ext(struct device *dev) { - return of_machine_is_compatible("apple,j714s") && + return apple_t6050_sleep_property("apple,display-method-sleep") && of_device_is_compatible(dev->of_node, "apple,t6050-dcpext"); } @@ -484,7 +655,7 @@ static bool dcp_j714s_ext(struct device *dev) static bool s2r_untested; module_param(s2r_untested, bool, 0444); MODULE_PARM_DESC(s2r_untested, - "Stop the DCP firmware on DPMS off and J813 system sleep using derived T8142 power words (default 0)"); + "Stop the DCP firmware on DPMS off and system sleep using derived T8142 power words (default 0)"); bool dcp_t6041_ext_enabled(void) { @@ -506,7 +677,21 @@ bool dcp_t6041_ext_enabled(void) static bool dcp_desktop_external(struct apple_dcp *dcp) { - return of_device_is_compatible(dcp->dev->of_node, "apple,t6041-dcpext"); + return dcp->desktop_external; +} + +/* + * The T6041 external processors, and the Mac mini's (J773g) T8132 ones on + * macOS 27.2: macOS drives the mini's HDMI port from dcpext0 alone, through + * the LPDPTX PHY (source select = dcp-index 1) and a PS190 DP-to-HDMI + * converter on the same SMC rails (gP0f, gP1a) as the M4 Max Mac Studio's + * (J575c), whose dcpext0 drives its HDMI port the same way. Its fixed PHY is + * powered at probe and its converter rails settle before the link, as there. + */ +static bool dcp_desktop_external_node(const struct device_node *np) +{ + return of_device_is_compatible(np, "apple,t6041-dcpext") || + apple_t8132_dcpext_v27_2(np); } /* @@ -749,25 +934,6 @@ static void send_vblank_event(struct drm_device *dev, drm_send_event_timestamp_locked(dev, &e->base, now); } -/** - * dcp_crtc_send_page_flip_event - helper to send vblank event after pageflip - * @crtc: CRTC whose flip completed - * @e: pending vblank event - * @now: swap completion timestamp - * @start: swap submission timestamp - * - * Compensate for unknown slack between page flip and arrival of the - * swap_complete callback. Minimal observed duration on DCP with HDMI output - * was around 2.3 ms. If the fb swap was submitted closer to the expected - * swap_complete it gets a penalty of one frame duration. This is on the border - * of unreasonable considering that Apple advertises support for 240 Hz (frame - * duration of 4.167 ms). - * It is unreasonable considering kwin's kms commit scheduling. Kwin commits - * 1.5 ms + the mode's vblank time before the expected next page flip - * completion. This results in presenting at half the display's rate for HDMI - * outputs. - * This might be a difference between dcp and dcpext. - */ /* * Advance the CRTC's flip sequence by the number of refresh periods since the * previous flip (at least one), so that userspace sees a non-zero, increasing @@ -792,6 +958,25 @@ static u64 dcp_crtc_next_flip_seq(struct apple_crtc *crtc, ktime_t flip) return crtc->flip_seq; } +/** + * dcp_crtc_send_page_flip_event - helper to send vblank event after pageflip + * @crtc: CRTC whose flip completed + * @e: pending vblank event + * @now: swap completion timestamp + * @start: swap submission timestamp + * + * Compensate for unknown slack between page flip and arrival of the + * swap_complete callback. Minimal observed duration on DCP with HDMI output + * was around 2.3 ms. If the fb swap was submitted closer to the expected + * swap_complete it gets a penalty of one frame duration. This is on the border + * of unreasonable considering that Apple advertises support for 240 Hz (frame + * duration of 4.167 ms). + * It is unreasonable considering kwin's kms commit scheduling. Kwin commits + * 1.5 ms + the mode's vblank time before the expected next page flip + * completion. This results in presenting at half the display's rate for HDMI + * outputs. + * This might be a difference between dcp and dcpext. + */ static void dcp_crtc_send_page_flip_event(struct apple_crtc *crtc, struct drm_pending_vblank_event *e, ktime_t now, ktime_t start) @@ -1292,15 +1477,23 @@ static void dcp_panel_read_adt(struct apple_dcp *dcp) dcp->panel.height_mm = panel.height_mm; if (dcp->panel_identity) dcp->panel_identity->adt = panel.identity; - dcp->panel.color_target = ret ? NULL : dcp_panel_gamut_color_space(panel.gamut); - if (desktop || dcp->fw_compat == DCP_FIRMWARE_V_27_0) - dcp->panel.edr_ceiling = dcp_edr_ceiling(panel.edr_potential_headroom); + if (ret || !dcp_panel_gamut_color_space(panel.gamut)) + dev_info(dcp->dev, "panel ADT: no known colour gamut, EDID primaries default to Display P3\n"); + dcp->panel.color_target = + dcp_panel_color_target(ret ? DCP_PANEL_GAMUT_UNSPECIFIED : panel.gamut); + /* + * Whether the panel has EDR headroom at all is the machine's to say: an + * XDR panel's backlight node carries EDRPotentialHeadroom above 1.0, an + * SDR panel none. Without it the panel gets no peak, so it shows no PQ + * content as EDR and offers userspace no HDR (dcp_panel_edr()). + */ + dcp->panel.edr_ceiling = dcp_edr_ceiling(panel.edr_potential_headroom); /* * Firmware 27 reports no peak (desktop 26.x: res_max_panel_brightness()). * The ADT's LmaxProduct gives it (1600 nits on the M5 Pro). Only a peak * above the SDR range gives headroom. */ - if (dcp->fw_compat == DCP_FIRMWARE_V_27_0) { + if (dcp->panel.edr_ceiling && dcp->fw_compat == DCP_FIRMWARE_V_27_0) { u32 peak = panel.lmax_product >> 16; if (peak > dcp->brightness.maximum && peak <= 10000) { @@ -1466,7 +1659,7 @@ const struct drm_edid *dcp_panel_edid_snapshot(struct apple_dcp *dcp, *generation = id->generation; spin_unlock_irqrestore(&dcp->metadata.lock, flags); /* PQ content is shown as EDR up to the peak (see dcp_edr_prepare()). */ - if (READ_ONCE(dcp->panel.peak_nits)) { + if (READ_ONCE(dcp->panel.peak_nits) && dcp_fw_panel_decodes_pq(dcp)) { metadata.pq = true; metadata.static_metadata_type1 = true; metadata.bt2020_rgb = true; @@ -1694,7 +1887,16 @@ VISIBLE_IF_KUNIT void dcp_swap_watchdog(struct work_struct *work) void dcp_swap_watchdog_arm(struct apple_dcp *dcp) { - if (dcp_is_typec_output(dcp) || dcp_desktop_swap_watched(dcp)) { + /* + * Every external pipe can lose its sink under an accepted swap, not + * only a Type-C route: an HDMI display on a fixed port also drops HPD, + * for instance while it wakes from standby after DPMS on. Unwatched, + * the dropped present holds the IOMFB queue until its ten second + * timeout, which declares the coprocessor crashed, and the mode set + * that would bring the display back waits behind it. + */ + if (dcp_is_typec_output(dcp) || !dcp_has_panel(dcp) || + dcp_desktop_swap_watched(dcp)) { dcp->swap_watchdog_deadline = jiffies + msecs_to_jiffies(DCP_SWAP_WATCHDOG_MS); mod_delayed_work(system_dfl_wq, &dcp->swap_watchdog_wq, @@ -1843,7 +2045,171 @@ static int dcp_check_iova_contiguous(struct iommu_domain *domain, return 0; } -static int dcp_rtk_shmem_setup(void *cookie, struct apple_rtkit_shmem *bfr) +#define DCP_RTKIT_HANDOFF "dcp-live-v1" +#define DCP_RTKIT_LIVE_BUFFER_CELLS 5 +#define DCP_RTKIT_LIVE_MAX_BUFFERS 4 + +struct dcp_rtkit_live { + struct apple_rtkit_adopted_session session; + struct apple_rtkit_inherited_buffer buffers[DCP_RTKIT_LIVE_MAX_BUFFERS]; +}; + +/* + * Inside one of this DCP's no-map reserved-memory carveouts. Those are also what + * the IOMMU core rebuilds the DCP's DART mappings from when it takes over a + * locked root, so a buffer outside them would lose its mapping at attach. A + * region in the linear map would alias the write-combined mapping of the buffer + * with a cacheable one, and a reusable (CMA) region could be handed out. + */ +static bool dcp_rtkit_live_carveout(struct device_node *np, phys_addr_t phys, + size_t size) +{ + int i, count = of_count_phandle_with_args(np, "memory-region", NULL); + bool found = false; + + for (i = 0; !found && i < count; i++) { + struct device_node *mem = of_parse_phandle(np, "memory-region", i); + struct reserved_mem *rmem; + + if (!mem) + break; + rmem = of_reserved_mem_lookup(mem); + found = rmem && of_property_present(mem, "no-map") && + !of_property_present(mem, "reusable") && + phys >= rmem->base && size <= rmem->size && + phys - rmem->base <= rmem->size - size; + of_node_put(mem); + } + return found; +} + +static void dcp_rtkit_live_unmap(struct dcp_rtkit_live *live) +{ + unsigned int i; + + for (i = 0; i < live->session.num_buffers; i++) + vunmap(live->buffers[i].shmem.private); + live->session.num_buffers = 0; +} + +/* + * A boot stage that negotiated RTKit with this DCP and handed it over running + * describes the session on the node, with the RTKit handoff properties of other + * co-processors handed over running: apple,rtkit-handoff ("dcp-live-v1") and + * apple,rtkit-buffers ( per system buffer, the + * device address being the DART input address), plus apple,rtkit-version and + * apple,rtkit-epmap (word i = endpoints 32i..32i+31). Each buffer lies in one of + * the node's memory-region carveouts, mapped there through its iommu-addresses. + * Such a firmware does not repeat HELLO or EPMAP. Returns 1 with the session + * filled in, 0 without a description, or an error for one that cannot be adopted + * safely. + */ +static int dcp_rtkit_live_parse(struct apple_dcp *dcp, struct dcp_rtkit_live *live) +{ + u32 cells[DCP_RTKIT_LIVE_MAX_BUFFERS * DCP_RTKIT_LIVE_BUFFER_CELLS]; + struct device_node *np = dcp->dev->of_node; + struct iommu_domain *domain; + const char *handoff; + int count, i, ret; + u32 version; + + if (!of_property_present(np, "apple,rtkit-handoff")) + return 0; + ret = of_property_read_string(np, "apple,rtkit-handoff", &handoff); + if (ret) + return ret; + if (strcmp(handoff, DCP_RTKIT_HANDOFF)) { + dev_err(dcp->dev, "unknown RTKit handoff \"%s\"\n", handoff); + return -EINVAL; + } + if (!(readl_relaxed(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) & + APPLE_DCP_COPROC_CPU_CONTROL_RUN)) { + dev_err(dcp->dev, "live RTKit session without a running CPU\n"); + return -ENODEV; + } + ret = of_property_read_u32(np, "apple,rtkit-version", &version); + if (ret || version > U16_MAX) + return ret ?: -EINVAL; + live->session.protocol_version = version; + ret = of_property_read_u32_array(np, "apple,rtkit-epmap", + live->session.epmap, + APPLE_RTKIT_ADOPTED_EPMAP_WORDS); + if (ret) + return ret; + + /* A session without shared buffers has the property, empty. */ + if (!of_find_property(np, "apple,rtkit-buffers", NULL)) + return -EINVAL; + count = of_property_count_u32_elems(np, "apple,rtkit-buffers"); + if (count == -ENODATA) + count = 0; + if (count < 0 || count > ARRAY_SIZE(cells) || + count % DCP_RTKIT_LIVE_BUFFER_CELLS) + return -EINVAL; + if (count) { + ret = of_property_read_u32_array(np, "apple,rtkit-buffers", + cells, count); + if (ret) + return ret; + } + count /= DCP_RTKIT_LIVE_BUFFER_CELLS; + + domain = iommu_get_domain_for_dev(dcp->dev); + if (count && !domain) + return -ENODEV; + + live->session.buffers = live->buffers; + for (i = 0; i < count; i++) { + const u32 *t = &cells[i * DCP_RTKIT_LIVE_BUFFER_CELLS]; + struct apple_rtkit_inherited_buffer *b = &live->buffers[i]; + u64 iova = (u64)t[1] << 32 | t[2]; + u64 size = t[3]; + phys_addr_t phys; + + /* The system endpoints with shared buffers, as for other handoffs. */ + if ((t[0] != 1 && t[0] != 2 && t[0] != 4 && t[0] != 8) || + t[4] > 1 || !size || size > SZ_16M || !PAGE_ALIGNED(iova) || + !PAGE_ALIGNED(size) || iova + size < iova) { + ret = -EINVAL; + goto fail; + } + /* The DCP's own DART says where the buffer is; it must be contiguous. */ + phys = iommu_iova_to_phys(domain, iova); + ret = phys ? dcp_check_iova_contiguous(domain, iova, size, phys) : -ENXIO; + if (ret) { + dev_err(dcp->dev, "live RTKit buffer ep%u iova %#llx+%#llx is not mapped\n", + t[0], iova, size); + goto fail; + } + if (!dcp_rtkit_live_carveout(np, phys, size)) { + dev_err(dcp->dev, "live RTKit buffer %pa+%#llx is not in a DCP carveout\n", + &phys, size); + ret = -EACCES; + goto fail; + } + + /* Firmware writes without CPU cache maintenance. */ + ret = dcp_vmap_wc(phys, size, &b->shmem.iomem, &b->shmem.private); + if (ret) + goto fail; + b->endpoint = t[0]; + b->shmem.iova = iova; + b->shmem.size = size; + /* + * The is_mapped cell only says who placed the buffer; Linux has + * mapped every one here, and is_mapped makes RTKit unmap it. + */ + b->shmem.is_mapped = true; + live->session.num_buffers = i + 1; + } + return 1; + +fail: + dcp_rtkit_live_unmap(live); + return ret; +} + +int dcp_rtk_shmem_setup(void *cookie, struct apple_rtkit_shmem *bfr) { struct apple_dcp *dcp = cookie; int ret; @@ -1904,7 +2270,7 @@ static int dcp_rtk_shmem_setup(void *cookie, struct apple_rtkit_shmem *bfr) return 0; } -static void dcp_rtk_shmem_destroy(void *cookie, struct apple_rtkit_shmem *bfr) +void dcp_rtk_shmem_destroy(void *cookie, struct apple_rtkit_shmem *bfr) { struct apple_dcp *dcp = cookie; @@ -1933,8 +2299,30 @@ static bool dcp_rtk_syslog_mode_set(void *cookie, const char *context, const cha return false; } +/* + * The T6050 internal DCP (hw.only_120hz_modes) can't survive a mode set away + * from the timing iBoot left the panel at: 120 -> 60 Hz crashes it, and so does + * 60 -> 120 Hz when macOS left the panel at 60 Hz. The firmware names that + * rate when it starts, "IOMFB update_rr_index syncrate 60", before any mode set + * of ours: keep the first one (dcp_mode_settable()). + */ +static void dcp_rtk_syslog_boot_rate(struct apple_dcp *dcp, const char *message) +{ + const char *p; + u32 rate; + + if (!dcp->hw.only_120hz_modes || READ_ONCE(dcp->boot_rate)) + return; + p = strstr(message, "update_rr_index syncrate "); + if (!p || sscanf(p, "update_rr_index syncrate %u", &rate) != 1) + return; + if (rate >= 24 && rate <= 240) + WRITE_ONCE(dcp->boot_rate, rate); +} + static bool dcp_rtk_syslog_is_debug(void *cookie, const char *context, const char *message) { + dcp_rtk_syslog_boot_rate(cookie, message); return dcp_h17p_syslog_is_debug(context, message); } @@ -1971,17 +2359,21 @@ void dcp_send_message(struct apple_dcp *dcp, u8 endpoint, u64 message) bool native_14_7 = dcp->fw_compat == DCP_FIRMWARE_V_14_7; int ret; + might_sleep(); + if (READ_ONCE(dcp->quiescing) || (dcp_is_ext26(dcp) && READ_ONCE(dcp->ext26_blocked))) return; trace_dcp_send_msg(dcp, endpoint, message); /* - * The adopted T6030 14.7 session shares this mailbox with the panel - * link. A non-sleeping send fails while that FIFO is full, and the - * DisplayPort handshake then waits for a reply that was never sent. + * The adopted T6030 14.7 and native26 (ext26) sessions share this + * mailbox with the panel link. A non-sleeping send fails while that + * FIFO is full, and the DisplayPort handshake then waits for a reply + * that was never sent. All callers are sleepable, so always use + * sleeping sends on 14.7/ext26 and keep atomic sends on other firmware. */ ret = apple_rtkit_send_message(dcp->rtk, endpoint, message, NULL, - (native_14_7 || dcp_is_ext26(dcp)) ? in_atomic() : true); + !(native_14_7 || dcp_is_ext26(dcp))); if (ret && dcp_is_ext26(dcp)) { WRITE_ONCE(dcp->crashed, true); dev_err(dcp->dev, "native26 mailbox send failed ep=%#x: %d\n", endpoint, ret); @@ -2045,16 +2437,20 @@ int dcp_crtc_atomic_check(struct drm_crtc *crtc, struct drm_atomic_commit *commi /* * On desktop 26.6 firmware the panel takes VRR_ENABLED with the next - * frame, without a mode set (see dcp_vrr_update()). The external - * processors ignore a new minimum rate on a live mode, so they still - * change adaptive sync with a mode set, as firmware 27's externals do: - * macOS switches between a timing's fixed and variable modes with a - * full mode set. + * frame, without a mode set (see dcp_vrr_update()), once a mode set + * has armed adaptive sync. An adopted boot mode starts fixed + * (!dcp->vrr_enabled), so enabling VRR_ENABLED the first time still + * needs one mode set; other template pipes change adaptive sync inside + * iomfb_modeset() via a full mode set, except firmware 27 panels which + * do not re-modeset on VRR. */ - if ((dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || - (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && !dcp->main_display && - !dcp_has_panel(dcp))) && - crtc_state->enable && !dcp_vrr_live(dcp)) { + if (READ_ONCE(dcp->iomfb_template_pq) && + !(dcp->fw_compat == DCP_FIRMWARE_V_27_0 && + (dcp->main_display || dcp_has_panel(dcp))) && + crtc_state->enable && + !(dcp_vrr_live(dcp) && + (READ_ONCE(dcp->vrr_enabled) || !crtc_state->vrr_enabled || + (dcp->desktop && READ_ONCE(dcp->desktop->vrr_failed))))) { struct drm_crtc_state *old = drm_atomic_get_old_crtc_state(commit, crtc); @@ -2296,6 +2692,37 @@ static unsigned long dcp_dptx_wait_linkcfg(struct apple_dcp *dcp, u32 port, } } +/* + * A fixed HDMI port can come up from the boot loader with a default surface + * already active, in which case the firmware does not start fresh link + * training while AP HPD is withheld. Assert AP HPD from the converter's real + * HPD GPIO before waiting for link configuration, except on paths where HPD + * has another owner (such as 13.5 DP2HDMI, where the converter holds HPD on + * its own and linkcfg timeout is non-fatal, or an adopted session whose + * post-wait path drives HPD). + */ +static int dcp_assert_hpd_before_link_wait(struct apple_dcp *dcp, u32 port, + bool late_hpd, bool skip_fixed_hdmi) +{ + bool typec = dcp_is_typec_output(dcp); + bool fixed_hdmi = !typec && !skip_fixed_hdmi && + dcp->fixed_connector_type == DRM_MODE_CONNECTOR_HDMIA && + dcp->hdmi_hpd; + int level; + + if (late_hpd || (!typec && !fixed_hdmi)) + return 0; + if (fixed_hdmi) { + level = gpiod_get_value_cansleep(dcp->hdmi_hpd); + if (level <= 0) + return level < 0 ? level : -ENOLINK; + } + if (dcp_uses_t6020_tunnel_flow(dcp)) + return dptxport_set_hpd_timeout(dcp->dptxport[port].service, + true, 8000); + return dptxport_set_hpd(dcp->dptxport[port].service, true); +} + /* * Connect DPTX port @port. On failure, @retryable (if given) tells whether * the attempt left nothing outstanding in the firmware, so that a later @@ -2312,16 +2739,15 @@ static int dcp_dptx_connect_raw(struct apple_dcp *dcp, u32 port, bool *retryable bool late_hpd = dcp_ext_dptx_607(dcp); bool t8132 = dcp_is_t8132_ext(dcp); /* - * A DP2HDMI output on the 13.5 firmware line asserts its own HPD, in - * dcp_enable_dp2hdmi_hpd(), and the connect asks the firmware for HPD - * only on a DisplayPort connector or a late-HPD path, so this firmware - * is never asked to detect the sink and never sends the link - * configuration the wait below looks for. Treat the timeout as - * non-fatal, as the compact and late-HPD cases do, instead of - * withdrawing the display. + * A DP2HDMI output asserts its own HPD, in dcp_enable_dp2hdmi_hpd(). + * The 13.5 firmware line is then never asked to detect the sink and + * never sends the link configuration the wait below looks for, and a + * session a boot stage handed over has a link it already trained. + * Treat the timeout as non-fatal there, as the compact and late-HPD + * cases do, instead of withdrawing the display. */ bool dp2hdmi = dcp->hdmi_hpd && !dcp_is_typec_output(dcp) && - dcp->fw_compat == DCP_FIRMWARE_V_13_5; + (dcp->fw_compat == DCP_FIRMWARE_V_13_5 || dcp->rtkit_adopted); bool compact, withdrawn; unsigned long timeout; u64 generation; @@ -2448,19 +2874,17 @@ static int dcp_dptx_connect_raw(struct apple_dcp *dcp, u32 port, bool *retryable goto out_release; } dcp->dptxport[port].connected = true; - if (dcp_is_typec_output(dcp) && !late_hpd) { - if (dcp_uses_t6020_tunnel_flow(dcp)) - ret = dptxport_set_hpd_timeout(dcp->dptxport[port].service, - true, 8000); + ret = dcp_assert_hpd_before_link_wait(dcp, port, late_hpd, dp2hdmi); + if (ret) { + if (ret == -ENOLINK) + dev_dbg(dcp->dev, + "dcp_dptx_connect: HDMI HPD dropped before assert\n"); else - ret = dptxport_set_hpd(dcp->dptxport[port].service, true); - if (ret) { dev_err(dcp->dev, - "dcp_dptx_connect: failed to assert Type-C HPD: %d\n", + "dcp_dptx_connect: failed to assert AP HPD: %d\n", ret); - dcp->dptxport[port].connected = false; - goto out_release; - } + dcp->dptxport[port].connected = false; + goto out_release; } mutex_unlock(&dcp->hpd_mutex); @@ -2495,8 +2919,9 @@ static int dcp_dptx_connect_raw(struct apple_dcp *dcp, u32 port, bool *retryable ret = 0; } else if (!ret && dp2hdmi) { /* - * The converter holds HPD itself, and dptxport_set_hpd() below runs - * only for a DisplayPort connector, so nothing is asserted here. + * The converter holds HPD itself; dptxport_set_hpd() below raises + * the firmware's HPD only on an adopted session, whose release at + * start dropped it. */ dev_dbg(dcp->dev, "dcp_dptx_connect: no link configuration on port %u, HPD is the converter's\n", @@ -2519,7 +2944,8 @@ static int dcp_dptx_connect_raw(struct apple_dcp *dcp, u32 port, bool *retryable usleep_range(5, 10); - if (dcp->connector_type == DRM_MODE_CONNECTOR_DisplayPort || late_hpd) { + if (dcp->connector_type == DRM_MODE_CONNECTOR_DisplayPort || late_hpd || + (dp2hdmi && dcp->rtkit_adopted)) { ret = dptxport_set_hpd(dcp->dptxport[port].service, true); if (ret && late_hpd) dev_err(dcp->dev, @@ -4142,13 +4568,26 @@ bool dcp_fw_compat_is_desktop(struct platform_device *pdev) return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP; } -/* Firmware whose panel shows PQ content as EDR (dcp_panel_edr_supported()). */ -bool dcp_fw_compat_panel_edr(struct platform_device *pdev) +/* + * Whether @pdev's internal panel can show PQ content as EDR: the panel has + * EDR headroom (the ADT's EDRPotentialHeadroom, see dcp_panel_read_adt()), + * and the firmware interface is one whose swaps carry EDR, which the driver + * implements for desktop 26.x and firmware 27 (dcp_panel_edr_supported()). + */ +bool dcp_panel_edr(struct platform_device *pdev) +{ + struct apple_dcp *dcp = platform_get_drvdata(pdev); + + return dcp_fw_swap_has_edr(dcp) && dcp_fw_panel_decodes_pq(dcp) && + dcp_has_panel(dcp) && dcp->panel.edr_ceiling; +} + +/* External connectors driven by iomfb_template support full colour selection. */ +bool dcp_ext_color_props_supported(struct platform_device *pdev) { struct apple_dcp *dcp = platform_get_drvdata(pdev); - return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || - dcp->fw_compat == DCP_FIRMWARE_V_27_0; + return !dcp_is_ext26(dcp) && !dcp_fw_compat_is_14_7(pdev); } bool dcp_fw_compat_is_14_7(struct platform_device *pdev) @@ -4224,37 +4663,7 @@ static const struct apple_epic_service_ops dcp_compact_aux_ops[] = { static void dcp_av_service_init(struct apple_epic_service *service, const char *name, const char *class, s64 unit) { - struct dcp_desktop_state *d = service->ep->dcp->desktop; - struct apple_epic_service *old; - - service = afk_service_get(service); - if (!service) - return; - scoped_guard(spinlock_irqsave, &d->hdr_lock) { - old = d->av_service; - d->av_service = service; - d->hdr_sent_valid = false; - d->hdr_infoframe = false; - } - if (old) - afk_service_put(old); -} - -static void dcp_av_service_teardown(struct apple_epic_service *service) -{ - struct dcp_desktop_state *d = service->ep->dcp->desktop; - bool owned; - - scoped_guard(spinlock_irqsave, &d->hdr_lock) { - owned = d->av_service == service; - if (owned) { - d->av_service = NULL; - d->hdr_sent_valid = false; - d->hdr_infoframe = false; - } - } - if (owned) - afk_service_put(service); + dcp_hdr_service_bind(service); } static const struct apple_epic_service_ops dcp_ext_av_service_ops[] = { @@ -4262,7 +4671,7 @@ static const struct apple_epic_service_ops dcp_ext_av_service_ops[] = { .name = "dcpav-service-epic", .reusable = true, .init = dcp_av_service_init, - .teardown = dcp_av_service_teardown, + .teardown = dcp_hdr_service_unbind, }, { .name = "*", @@ -4657,6 +5066,9 @@ static int dcp_ext26_start_services(struct apple_dcp *dcp) * whose firmware advertises both of those gets the controller and its ports * there. * + * A primary DCP can also serve external ports when the device tree connects + * Type-C display routes to it. + * * Decided here, not at probe: RTKit is woken at bind, and its endpoint map is * known only from then on. Hardware data that names an endpoint keeps it: * T8142's dcpext (the same layout), and the T6050 and firmware-27 T6041 @@ -4664,8 +5076,8 @@ static int dcp_ext26_start_services(struct apple_dcp *dcp) */ static void dcp_v27_dptx_layout(struct apple_dcp *dcp) { - if (dcp->fw_compat != DCP_FIRMWARE_V_27_0 || !dcp->dcpext || - dcp->hw.dptx_endpoint) + if (dcp->fw_compat != DCP_FIRMWARE_V_27_0 || + (!dcp->dcpext && !dcp->nr_typec_routes) || dcp->hw.dptx_endpoint) return; if (!apple_rtkit_has_endpoint(dcp->rtk, DPTX_CONTROLLER_ENDPOINT) || !apple_rtkit_has_endpoint(dcp->rtk, DPTX_ENDPOINT)) @@ -4689,6 +5101,7 @@ int dcp_start(struct platform_device *pdev) /* Even if nothing starts, dcp_wait_ready() must find it initialised. */ init_completion(&dcp->start_done); + mutex_init(&dcp->s2r_dart_lock); init_completion(&dcp->s2r_dart_done); if (dcp->fw_compat == DCP_FIRMWARE_V_26_6) return iomfb_v26_6_start(dcp); @@ -4760,6 +5173,24 @@ int dcp_start(struct platform_device *pdev) if (ret) { dev_warn(dcp->dev, "Failed to start DPTX endpoint: %d\n", ret); + } else if (dcp->rtkit_adopted && + dptx_service_available(&dcp->dptxport[0])) { + /* + * The boot stage that handed this DCP over left the + * port's display up on a link it trained. Release it, + * so that the next connect trains the link and reads + * the sink again: until then the firmware only has its + * default modes and no EDID. Its HPD goes low as well; + * dcp_dptx_connect() raises it again after the link wait, + * so that the firmware sees the display plugged. + */ + ret = dptxport_set_hpd(dcp->dptxport[0].service, false); + if (!ret) + ret = dptxport_release_display(dcp->dptxport[0].service); + if (ret) + dev_warn(dcp->dev, "adopted DPTX display not released: %d\n", + ret); + ret = 0; #ifdef DCP_DPTX_DISCONNECT_ON_INIT /* * This disconnect / connect cycle on init is only necessary @@ -4890,8 +5321,6 @@ static void _dcp_poweroff(struct apple_dcp *dcp) iomfb_poweroff_v26_6_desktop(dcp); if (dcp->edr_hm) dcp->edr_restart = true; - /* The link set up again starts without HDR10 metadata. */ - dcp_hdr_metadata_forget(dcp); break; case DCP_FIRMWARE_V_26_6: iomfb_v26_6_poweroff(dcp); @@ -4913,6 +5342,13 @@ static void _dcp_poweroff(struct apple_dcp *dcp) WARN_ONCE(true, "Unexpected firmware version: %u\n", dcp->fw_compat); break; } + /* The link set up again starts without HDR10 metadata. */ + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + dcp->active_color.score = -1; + dcp->output_pq = false; + dcp->output_hdr = false; + } + dcp_hdr_metadata_forget(dcp); } static void dcp_resume_enable_irq(void *ctx) @@ -4932,20 +5368,43 @@ static const struct dcp_fabric_resume_ops dcp_resume_ops = { .sample = dcp_resume_sample, }; +/* + * Sample fixed-HDMI HPD and reconnect DPTX port 0 (or power off / report + * unplug when no sink is present). Shared by initial bring-up and deep sleep + * recovery. + */ +static void dcp_fixed_hdmi_reconnect(struct apple_dcp *dcp, bool poweroff_unplugged) +{ + bool connected; + int ret; + + if (dcp_is_typec_output(dcp) || !dcp->hdmi_hpd || + READ_ONCE(dcp->active_typec_route)) + return; + + /* Check HPD before enabling the edge-triggered IRQ. */ + connected = gpiod_get_value_cansleep(dcp->hdmi_hpd); + dev_info(dcp->dev, "%s: DP2HDMI HPD connected:%d\n", __func__, connected); + + if (connected && !READ_ONCE(dcp->hdmi_yielded)) { + ret = dcp_dptx_connect(dcp, 0); + if (ret) + dev_warn(dcp->dev, "HDMI DPTX connect failed: %d\n", ret); + } else if (!connected) { + if (poweroff_unplugged) + _dcp_poweroff(dcp); + else if (dcp->connector) + disconnected_hpd_event(dcp->connector); + } +} + static int dcp_enable_dp2hdmi_hpd(struct apple_dcp *dcp) { if (dcp_is_typec_output(dcp)) { if (READ_ONCE(dcp->typec_cable_connected)) dcp_dptx_connect(dcp, 0); - } else if (dcp->hdmi_hpd) { - /* Check HPD before enabling the edge-triggered IRQ. */ - bool connected = gpiod_get_value_cansleep(dcp->hdmi_hpd); - dev_info(dcp->dev, "%s: DP2HDMI HPD connected:%d\n", __func__, connected); - - if (connected && !READ_ONCE(dcp->hdmi_yielded)) - dcp_dptx_connect(dcp, 0); - else if (!connected) - _dcp_poweroff(dcp); + } else { + dcp_fixed_hdmi_reconnect(dcp, true); } if (dcp->hdmi_hpd_irq) @@ -5462,12 +5921,35 @@ static void dcp_work_backlight_fallback(struct work_struct *work) dev_warn(dcp->dev, "backlight registration failed: %d\n", ret); } +/* Drop every framebuffer mirror before the fbdma domain goes away. */ +static void dcp_fb_unmirror_all(struct apple_dcp *dcp) +{ + unsigned long index; + void *entry; + + guard(mutex)(&dcp->fb_mirror_lock); + if (dcp->fb_dom) { + xa_for_each(&dcp->fb_mirrors, index, entry) { + /* An object stays in fb_mirrors only while it is alive. */ + struct drm_gem_dma_object *obj = (void *)index; + + iommu_unmap(dcp->fb_dom, obj->dma_addr, xa_to_value(entry)); + } + } + xa_destroy(&dcp->fb_mirrors); + WRITE_ONCE(dcp->fb_dom, NULL); +} + static void dcp_release_piodma_iommu_dev(struct apple_dcp *dcp) { if (dcp->retain_dma) { WRITE_ONCE(dcp->quiescing, true); return; } + dcp_fb_unmirror_all(dcp); + if (dcp->fbdma) + of_platform_device_destroy(&dcp->fbdma->dev, NULL); + dcp->fbdma = NULL; if (dcp->piodma) { if (dcp->piodma_created) of_platform_device_destroy(&dcp->piodma->dev, NULL); @@ -5479,6 +5961,151 @@ static void dcp_release_piodma_iommu_dev(struct apple_dcp *dcp) dcp->piodma_created = false; } +/* + * J615 dcpext: the external pipe reads framebuffers through its + * own display DART, not the internal one the display subsystem's domain + * covers. An "fbdma" child, on that DART's stream 0 with the display + * subsystem's DVA window, gets a domain the framebuffers are mirrored into. + * Without the node nothing changes. The display gate disables the node when + * it shares that DART with the display subsystem instead, whose domain then + * already maps every framebuffer there. + */ +static int dcp_create_fbdma_dev(struct apple_dcp *dcp) +{ + struct device_node *node __free(device_node) = NULL; + struct iommu_domain *dom; + int ret; + + if (!dcp->ext_failsafe || dcp->fbdma) + return 0; + node = of_get_available_child_by_name(dcp->dev->of_node, "fbdma"); + if (!node) + return 0; + dcp->fbdma = of_platform_device_create(node, NULL, dcp->dev); + if (!dcp->fbdma) + return dev_err_probe(dcp->dev, -ENODEV, "fbdma: could not create %pOF\n", node); + ret = dma_set_mask_and_coherent(&dcp->fbdma->dev, DMA_BIT_MASK(42)); + if (!ret) + ret = of_dma_configure(&dcp->fbdma->dev, node, true); + dom = ret ? NULL : iommu_get_domain_for_dev(&dcp->fbdma->dev); + if (IS_ERR_OR_NULL(dom)) { + ret = ret ?: PTR_ERR_OR_ZERO(dom) ?: -ENODEV; + of_platform_device_destroy(&dcp->fbdma->dev, NULL); + dcp->fbdma = NULL; + return dev_err_probe(dcp->dev, ret, "fbdma: no IOMMU domain\n"); + } + scoped_guard(mutex, &dcp->fb_mirror_lock) + WRITE_ONCE(dcp->fb_dom, dom); + dev_info(dcp->dev, "fbdma: framebuffers mirrored through %pOF\n", node); + return 0; +} + +/* + * Map the pages behind [@iova, @iova + @size) of @src into the fbdma domain + * at the same addresses, read-only. The pages are taken from @src's own + * translations, so this needs no scatterlist: an imported buffer's belongs + * to its exporter. Each step looks up one of @src's smallest pages, so a hole + * cannot hide inside a step; that needs both domains to share that page size. + * Returns 0, or a negative errno with nothing left mapped. + */ +static int dcp_fb_mirror_range(struct apple_dcp *dcp, struct iommu_domain *src, + dma_addr_t iova, size_t size) +{ + unsigned long pgsize; + phys_addr_t phys, run_phys = 0; + size_t off, run_len = 0, mapped = 0; + int ret = 0; + + if (!src->pgsize_bitmap || !dcp->fb_dom->pgsize_bitmap) + return -EINVAL; + pgsize = 1UL << __ffs(src->pgsize_bitmap); + if (pgsize != 1UL << __ffs(dcp->fb_dom->pgsize_bitmap) || + !IS_ALIGNED(iova | size, pgsize)) + return -EINVAL; + for (off = 0; off <= size && !ret; off += pgsize) { + phys = off < size ? iommu_iova_to_phys(src, iova + off) : 0; + if (run_len && phys && phys == run_phys + run_len) { + run_len += pgsize; + continue; + } + /* The run of physically contiguous pages ends here. */ + if (run_len) { + ret = iommu_map(dcp->fb_dom, iova + mapped, run_phys, run_len, + IOMMU_READ, GFP_KERNEL); + if (!ret) + mapped += run_len; + } + if (!ret && off < size && !phys) + ret = -EFAULT; + run_phys = phys; + run_len = pgsize; + } + if (ret && mapped) + iommu_unmap(dcp->fb_dom, iova, mapped); + return ret; +} + +/* + * Map @fb's GEM objects into the fbdma domain at their display DVAs. A + * mapping lasts as long as its object and its DVA do: dcp_fb_unmirror() + * removes it when the object is freed. + */ +int dcp_fb_mirror(struct apple_dcp *dcp, struct drm_framebuffer *fb) +{ + struct iommu_domain *src; + unsigned int i; + + if (!READ_ONCE(dcp->fb_dom)) + return 0; + src = iommu_get_domain_for_dev(drm_dev_dma_dev(fb->dev)); + guard(mutex)(&dcp->fb_mirror_lock); + if (!dcp->fb_dom || IS_ERR_OR_NULL(src)) + return -ENODEV; + for (i = 0; i < fb->format->num_planes; i++) { + struct drm_gem_dma_object *obj = drm_fb_dma_get_gem_obj(fb, i); + unsigned long index = (unsigned long)obj; + int ret; + + if (!obj) + return -EINVAL; + if (xa_load(&dcp->fb_mirrors, index)) + continue; + ret = dcp_fb_mirror_range(dcp, src, obj->dma_addr, obj->base.size); + if (!ret) { + ret = xa_err(xa_store(&dcp->fb_mirrors, index, + xa_mk_value(obj->base.size), GFP_KERNEL)); + if (ret) + iommu_unmap(dcp->fb_dom, obj->dma_addr, obj->base.size); + } + if (ret) { + dev_warn_ratelimited(dcp->dev, + "fbdma: %pad (%zu bytes, %s) not mirrored: %d\n", + &obj->dma_addr, obj->base.size, + obj->sgt ? "imported" : "native", ret); + return ret; + } + } + return 0; +} + +/* @obj is being freed: the external pipe must not read its pages any more. */ +void dcp_fb_unmirror(struct platform_device *pdev, struct drm_gem_dma_object *obj) +{ + struct apple_dcp *dcp; + void *entry; + + if (!pdev) + return; + dcp = platform_get_drvdata(pdev); + if (!dcp || !READ_ONCE(dcp->fb_dom)) + return; + guard(mutex)(&dcp->fb_mirror_lock); + entry = xa_erase(&dcp->fb_mirrors, (unsigned long)obj); + if (entry && dcp->fb_dom) + iommu_unmap(dcp->fb_dom, obj->dma_addr, xa_to_value(entry)); +} +EXPORT_SYMBOL_GPL(dcp_fb_unmirror); + void dcp_retain_framebuffer(struct platform_device *pdev, struct dcp_fb_reference *entry) { @@ -5914,31 +6541,25 @@ static bool dcp_ext26_admitted(struct device_node *np) } /* - * J716c shares the 27.0 endpoint-control wire format, not the J714s normal - * IOMFB method or panel profile. Establish this before RTKit can receive any - * application traffic, including traffic that invalidates a later inventory. + * Firmware 27 (T6050) sleep endpoint-control transport. Establish this before + * RTKit can receive any application traffic, including traffic that invalidates + * a later inventory. Admitted for a T6050 DCP/DCPEXT whose firmware 27 method + * table has an ID for every call the sleep sends. */ static bool dcp_v27_sleep_transport_supported(struct apple_dcp *dcp) { struct device *dev = dcp->dev; - char compat[DCP_FW_VERSION_STR_LEN]; if (!IS_ENABLED(CONFIG_APPLE_SOC_SLEEP)) return false; - if (dcp->v27_j714s) - return true; - if (!of_machine_is_compatible("apple,j716c") || - !of_machine_is_compatible("apple,t6050") || - !(of_device_is_compatible(dev->of_node, "apple,t6050-dcp") || + if (!(of_device_is_compatible(dev->of_node, "apple,t6050-dcp") || of_device_is_compatible(dev->of_node, "apple,t6050-dcpext")) || !dcp->hw.adopt_live_session || dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_DEFAULT || dcp->fw_compat != DCP_FIRMWARE_V_27_0) return false; - /* The enum also covers later 27.x method tables. */ - return dcp_read_fw_version(dev, "apple,firmware-compat", compat) >= 0 && - !strcmp(compat, "27.0.0"); + return iomfb_v27_sleep_methods_complete(dcp->v27_methods); } /* @@ -5966,51 +6587,141 @@ static enum dcp_firmware_version dcp_v27_method_table(struct device *dev, return DCP_FIRMWARE_V_27_0; } +/* + * Firmware 27 is selected by the ABI the DCP reports, the same on every SoC: + * a DCP or dcpext whose firmware-compat is 27 or later runs the common + * firmware-27 instance with the method table of that build. The interfaces + * written for older firmware make it panic (T8142 on 27.0 with H17P: "ap_link: + * callback failed with: 0x5"), so a 27 or later build without a complete + * table is not started at all. Pure, so the host test runs the same rule. + */ +enum dcp_v27_admission dcp_v27_admission(const char *compat, + const struct dcp_method_entry **methods, + const char **missing, + unsigned int *num_missing) +{ + unsigned int major; + + *methods = NULL; + *missing = NULL; + *num_missing = 0; + if (sscanf(compat, "%u.", &major) != 1 || major < 27) + return DCP_V27_NOT_V27; + *methods = iomfb_v27_methods(compat); + if (!*methods) + return DCP_V27_NO_TABLE; + *missing = iomfb_v27_missing_method(*methods, num_missing); + if (*missing) + return DCP_V27_INCOMPLETE; + return DCP_V27_ADMITTED; +} + +/* + * Returns true if the DCP reports firmware 27 or later, with @version the + * firmware-27 instance or DCP_FIRMWARE_UNKNOWN if this build cannot be started. + */ +static bool dcp_firmware_27(struct device *dev, + enum dcp_firmware_version *version) +{ + char compat[DCP_FW_VERSION_STR_LEN]; + const struct dcp_method_entry *methods; + unsigned int num_missing; + const char *missing; + + if (dcp_read_fw_version(dev, "apple,firmware-compat", compat) < 0) + return false; + if (dcp_v27_admission(compat, &methods, &missing, &num_missing) == + DCP_V27_NOT_V27) + return false; + /* Logs why a build without a complete table is not started. */ + *version = dcp_v27_method_table(dev, compat); + return true; +} + static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) { const struct apple_dcp_hw_data *hw = of_device_get_match_data(dev); const struct dcp_v14_board *v14_board; char compat_str[DCP_FW_VERSION_STR_LEN]; char fw_str[DCP_FW_VERSION_STR_LEN]; + enum dcp_firmware_version version; int ret; /* - * T8142 (J813) on macOS 27.0: the H17P interface written for its 26.x - * firmware makes the 27.0 DCP firmware panic right after the first - * hotplug ("ap_link: callback failed with: 0x5"). It runs the T6050's - * firmware-27 generation, and so does 27.2, with the 27.2 method table. + * T6050 and T8142 dcpext were introduced on firmware 27 and have no + * older interface. */ - if (of_device_is_compatible(dev->of_node, "apple,t8142-dcp")) { + if (hw->firmware_compat == DCP_FIRMWARE_V_27_0) { ret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); - if (ret >= 0 && (!strcmp(compat_str, "27.0.0") || - !strcmp(compat_str, "27.2.0"))) - return DCP_FIRMWARE_V_27_0; + if (ret < 0) { + dev_err(dev, "DCP firmware-compat missing has no 27.x method table\n"); + return DCP_FIRMWARE_UNKNOWN; + } + return dcp_v27_method_table(dev, compat_str); } /* - * The T8122 (M3 MacBook Air) internal DCP on the 27.2 (26B123) image - * runs the firmware-27 backend with the 27.2 table, as the T6041's - * 27.2 internal DCP does. Its 14.x image keeps the native 14.7 path - * and the 25G83 profile its own, below. + * T8142 (J813) on firmware 27 or later: the H17P interface written for + * its 26.x firmware makes 27.x firmware panic right after the first + * hotplug ("ap_link: callback failed with: 0x5"). Keep ahead of its + * H17P match-data pin so known 27.x builds take the common firmware-27 + * backend and unknown 27.x builds are terminally refused. + */ + if (of_device_is_compatible(dev->of_node, "apple,t8142-dcp") && + dcp_firmware_27(dev, &version)) + return version; + + /* + * T8132 external processors: the Mac mini's (J773g) on macOS 27.2 + * (26B123), handed over as the T6041's 27.2 ones are, run the + * firmware-27 backend with the 27.2 method table, as on T6041; any + * other is the M4 backend's (below). Both need + * CONFIG_DRM_APPLE_DCP_T8132, which matches the T8132 nodes. + * + * ASSUMED, NOT TRACED: the T8132 26B123 image (B3BA603C) numbers its + * IOMFB methods as the T6041 (964EDE5B) and T8142 26B123 images do + * (dcp_methods_27_2), and calls the same D-callbacks. A trace of macOS + * 27.2 driving the mini's dcpext0 has to confirm the A4xx/A5xx IDs + * before this is relied on. */ - if (apple_t8122_dcp_v27_2(dev->of_node)) { - /* Checked by apple_t8122_dcp_v27_2(). */ + if (apple_t8132_dcpext_v27_2(dev->of_node)) { + /* Checked by apple_t8132_dcpext_v27_2(). */ dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); return dcp_v27_method_table(dev, compat_str); } - if (hw->firmware_compat == DCP_FIRMWARE_V_27_0) { - ret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); - if (ret < 0) { - dev_err(dev, "DCP firmware-compat missing has no 27.x method table\n"); - return DCP_FIRMWARE_UNKNOWN; - } + /* + * The T8132 internal panel's processor on the macOS 27.2 stub, handed + * over by the boot loader with the 26B123 image (see + * apple_t8132_dcp_v27_2()): the firmware-27 backend with the 27.2 + * method table. That this image numbers its IOMFB methods as the + * T6041 and T8142 26B123 images do is the same assumption the J773g + * dcpext case above makes. + */ + if (apple_t8132_dcp_v27_2(dev->of_node)) { + /* Checked by apple_t8132_dcp_v27_2(). */ + dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); return dcp_v27_method_table(dev, compat_str); } /* - * SoCs introduced with H17-generation firmware pin its interface; the - * loader may not recognise their boot firmware version. + * The M4 backend (iomfb_m4.c) is written for the 26.6.2 firmware path + * only (apple_t8132_firmware_path()). Off it, as on a Mac mini booted + * from macOS 27.2, the boot loader leaves the main DCP running idle and + * hands it to nobody: never adopt or touch it. iomfb_m4_init() would + * refuse such firmware too, but only after the probe has claimed the + * DCP's IOMMU domain. + */ + if (hw->firmware_compat == DCP_FIRMWARE_M4 && !apple_t8132_firmware_path()) { + dev_info(dev, "T8132 display processor left alone off the M4 26.6.2 firmware path\n"); + return DCP_FIRMWARE_UNKNOWN; + } + + /* + * SoCs introduced with M4 or H17-generation firmware pin their + * interface; keep explicit match-data pins ahead of the generic + * firmware-27 rule below so T8132 (but for the 27.2 dcpext above) and + * T8140 stay on their pinned backend. */ if (hw->firmware_compat != DCP_FIRMWARE_UNKNOWN) return hw->firmware_compat; @@ -6022,7 +6733,8 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) * T6041 (M4 Pro/Max) uses its desktop IOMFB instance on 26.5.2 and * 26.6.2 firmware, where boot firmware and compatibility versions must * match. The pinned 27.2 (26B123) T6041 DCP image uses the firmware-27 - * backend on internal and external display processors. + * backend on internal and external display processors. Keep ahead of + * dcp_firmware_27() so the T6041 image UUID pin remains enforced. */ if (of_device_is_compatible(dev->of_node, "apple,t6041-dcp") || of_device_is_compatible(dev->of_node, "apple,t6041-dcpext")) { @@ -6041,6 +6753,25 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) return DCP_FIRMWARE_UNKNOWN; } + /* + * T8122 (M3 MacBook Air) internal and external DCPs pin the 27.2 + * (26B123) image UUID on firmware 27.x: any wrong or missing UUID on a + * firmware 27+ build is terminally refused rather than falling through + * to generic firmware-27 or legacy 14.x selection. + */ + if ((of_device_is_compatible(dev->of_node, "apple,t8122-dcp") || + of_device_is_compatible(dev->of_node, "apple,t8122-dcpext")) && + dcp_firmware_27(dev, &version)) { + if (apple_t8122_dcp_v27_2(dev->of_node) || + apple_t8122_dcpext_v27_2(dev->of_node)) + return version; + dev_err(dev, "T8122 display not started: unpinned 27.x DCP firmware UUID\n"); + return DCP_FIRMWARE_UNKNOWN; + } + + if (dcp_firmware_27(dev, &version)) + return version; + ret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); if (ret < 0) { dev_err(dev, "Could not read 'apple,firmware-compat': %d\n", ret); @@ -6078,14 +6809,18 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) /* * The T8122 external processor: Linux starts it and drives 14.7 - * firmware through the classic IOMFB template, as on M1/M2. + * firmware through the classic IOMFB template, as on M1/M2. On the + * 27.2 image it runs the firmware-27 backend with the 27.2 table, as + * the internal processor does. */ if (of_device_is_compatible(dev->of_node, "apple,t8122-dcpext")) { if (dcp_ext26_admitted(dev->of_node)) return DCP_FIRMWARE_H17P; + if (apple_t8122_dcpext_v27_2(dev->of_node)) + return dcp_v27_method_table(dev, compat_str); if (!strcmp(compat_str, "14.7.0")) return DCP_FIRMWARE_V_14_7_TEMPLATE; - dev_err(dev, "T8122 external display not started: DCP firmware-compat %s is not 14.7.0\n", + dev_err(dev, "T8122 external display not started: DCP firmware-compat %s is neither 14.7.0 nor the 27.2 image\n", compat_str); return DCP_FIRMWARE_UNKNOWN; } @@ -6120,6 +6855,14 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) (strncmp(fw_str, "14.7.0", sizeof(compat_str)) == 0)) return DCP_FIRMWARE_V_14_7_TEMPLATE; + /* + * The loader reports the method ABI for each DCP. Legacy match data + * leaves the ABI to this property, so accept a complete table here + * when the reported ABI has no legacy implementation. + */ + if (iomfb_v27_methods(compat_str)) + return dcp_v27_method_table(dev, compat_str); + dev_err(dev, "DCP firmware-compat %s (FW: %s) is not supported\n", compat_str, fw_str); @@ -6223,60 +6966,104 @@ VISIBLE_IF_KUNIT void dcp_enable_typec_work(struct apple_dcp *dcp) } } -static int dcp_firmware_metadata_v27(struct apple_dcp *dcp) +static bool dcp_has_available_typec_routes(struct device_node *np) { - struct device *dev = dcp->dev; - struct device_node *fb; - struct resource resource; - int clocks, index, ret; + struct device_node *routes, *child; + bool avail = false; - /* - * The framebuffer region is the one the boot loader scanned out of; it - * backs the firmware's default framebuffer. An external processor the - * boot loader drove no display from (T6050's dcpext4, the HDMI port's) - * has none: it binds without one, and its default-framebuffer requests - * are refused (dfb_region_size 0). - */ - index = of_property_match_string(dev->of_node, "memory-region-names", - "framebuffer"); - if (index == -ENODATA || index == -EINVAL) { - dcp->dfb_region_size = 0; - dev_info(dev, "no boot framebuffer\n"); - goto clocks; + routes = of_get_child_by_name(np, "typec-routes"); + if (!routes) + return false; + if (of_device_is_available(routes)) { + for_each_available_child_of_node(routes, child) { + of_node_put(child); + avail = true; + break; + } } - if (index < 0) - return index; - fb = of_parse_phandle(dev->of_node, "memory-region", index); - if (!fb) - return -EINVAL; - ret = of_address_to_resource(fb, 0, &resource); - of_node_put(fb); + of_node_put(routes); + return avail; +} + +static bool dcp_is_internal_panel_only(const struct apple_dcp *dcp) +{ + struct device_node *np = dcp->dev->of_node; + + return dcp->panel_identity && !dcp->dcpext && + !of_property_present(np, "phys") && + !dcp_has_available_typec_routes(np); +} + +static u8 dcp_dart_dma_bits(struct device_node *np) +{ + struct of_phandle_args args; + u32 range[4]; + u64 base, size, end; + int ret; + + ret = of_parse_phandle_with_args(np, "iommus", "#iommu-cells", 0, &args); if (ret) - return ret; - dcp->dfb_region_size = resource_size(&resource); - if (!dcp->dfb_region_size) - return -EINVAL; + return 0; + ret = of_property_read_u32_array(args.np, "apple,dma-range", range, 4); + of_node_put(args.np); + if (ret) + return 0; + base = ((u64)range[0] << 32) | range[1]; + size = ((u64)range[2] << 32) | range[3]; + if (!size || base + size < base) + return 0; + end = base + size - 1; + return clamp_t(u8, fls64(end), 32, 48); +} + +static void dcp_apply_dt_profile(struct apple_dcp *dcp) +{ + struct device_node *np = dcp->dev->of_node; + u32 running; + + if (of_property_present(np, "apple,rtkit-handoff")) + dcp->hw.adopt_live_session = true; + + if (dcp->fw_compat != DCP_FIRMWARE_V_27_0) + return; + + /* iBoot can leave the ASC running without negotiating RTKit. */ + if (dcp->hw.iboot_handoff && + of_property_read_variable_u32_array(np, dcp->hw.iboot_handoff, + &running, 1, 1) == 1 && + running == 1) + dcp->hw.adopt_live_session = true; + + if (!dcp->hw.firmware_dma_bits) + dcp->hw.firmware_dma_bits = dcp_dart_dma_bits(np); + if (dcp_is_internal_panel_only(dcp)) + dcp->hw.num_dptx_ports = 0; +} + +/* + * The provider clocks firmware 27 asks for by index (getClockFrequency): + * apple,clock-ids, published by the boot loader from the ADT. + */ +static int dcp_firmware_clocks_v27(struct apple_dcp *dcp) +{ + struct device *dev = dcp->dev; + int clocks, index, ret; -clocks: - /* - * T6041 device trees carry the single 712 MHz disp0 clock unless the - * boot loader publishes the two /arm-io/disp0 provider clocks - * (376 at 712 MHz and 460 at 0 Hz). Expose the same two-entry table - * when apple,clock-ids is absent so getClockFrequency(0/1) matches. - */ /* - * The T8122 /arm-io/disp0 names the same pair (345 at 712 MHz, the - * device tree's disp0 clock, and 416 at 0 Hz). + * Internal panels whose device tree carries only the single unnamed + * disp0 clock without apple,clock-ids (T6041, T8122, T6030, T6031, + * T8112): expose the two-entry [disp0, 0 Hz] table so + * getClockFrequency(0/1) matches /arm-io/disp0. Non-panel paths or + * nodes without a single unnamed clock still require apple,clock-ids. */ if (!of_property_present(dev->of_node, "apple,clock-ids") && - (of_device_is_compatible(dev->of_node, "apple,t6041-dcp") || - of_device_is_compatible(dev->of_node, "apple,t8122-dcp"))) { - struct clk *clk = devm_clk_get_optional(dev, NULL); + dcp_is_internal_panel_only(dcp) && + !of_property_present(dev->of_node, "clock-names") && + of_count_phandle_with_args(dev->of_node, "clocks", "#clock-cells") == 1) { + struct clk *clk = devm_clk_get(dev, NULL); if (IS_ERR(clk)) return PTR_ERR(clk); - if (!clk) - return 0; dcp->firmware_clocks = devm_kcalloc(dev, 2, sizeof(*dcp->firmware_clocks), GFP_KERNEL); @@ -6286,8 +7073,10 @@ static int dcp_firmware_metadata_v27(struct apple_dcp *dcp) dcp->num_firmware_clocks = 2; return 0; } + /* External processors without a provider clock table (T6041, T8122). */ if (!of_property_present(dev->of_node, "apple,clock-ids") && - of_device_is_compatible(dev->of_node, "apple,t6041-dcpext")) + (of_device_is_compatible(dev->of_node, "apple,t6041-dcpext") || + of_device_is_compatible(dev->of_node, "apple,t8122-dcpext"))) return 0; clocks = of_property_count_u32_elems(dev->of_node, "apple,clock-ids"); if (clocks == -ENODATA && @@ -6295,6 +7084,15 @@ static int dcp_firmware_metadata_v27(struct apple_dcp *dcp) clocks = 0; if (clocks < 0 || clocks > 64) return -EINVAL; + /* + * An explicitly empty table: the firmware takes no provider clocks + * (every T602x display processor on 27.2). A display clock the node + * lists is the DCP's own clock, not a provider clock. + */ + if (!clocks) { + dcp->num_firmware_clocks = 0; + return 0; + } /* * A DCP that also boots earlier firmware (T8142) lists the clock those * use first and names the provider clocks "firmware-". Take only @@ -6328,6 +7126,56 @@ static int dcp_firmware_metadata_v27(struct apple_dcp *dcp) return 0; } +static int dcp_firmware_metadata_v27(struct apple_dcp *dcp) +{ + struct device *dev = dcp->dev; + struct device_node *fb; + struct resource resource; + int index, ret; + + /* + * The framebuffer region is the one the boot loader scanned out of; it + * backs the firmware's default framebuffer. An external processor the + * boot loader drove no display from (T6050's dcpext4, the HDMI port's) + * has none: it binds without one, and its default-framebuffer requests + * are refused (dfb_region_size 0). + */ + index = of_property_match_string(dev->of_node, "memory-region-names", + "framebuffer"); + if (index == -ENODATA || index == -EINVAL) { + dcp->dfb_region_size = 0; + dev_info(dev, "no boot framebuffer\n"); + return dcp_firmware_clocks_v27(dcp); + } + if (index < 0) + return index; + fb = of_parse_phandle(dev->of_node, "memory-region", index); + if (!fb) + return -EINVAL; + ret = of_address_to_resource(fb, 0, &resource); + of_node_put(fb); + if (ret) + return ret; + dcp->dfb_region_size = resource_size(&resource); + if (!dcp->dfb_region_size) + return -EINVAL; + /* + * The boot surface is on screen until a displayed swap of ours + * replaces it. Reserve its retirement record before any present. + * Without the record the display still takes over, and a cache + * controller waiting on it keeps allocation off. + */ + ret = apple_mcc_boot_scanout_reserve(dev->of_node); + if (ret == -ENOMEM) + dev_warn(dev, "no boot scanout record: system cache allocation stays off\n"); + else if (ret) + return ret; + dcp->boot_scanout_reserved = !ret; + WRITE_ONCE(dcp->boot_surface_pending, true); + + return dcp_firmware_clocks_v27(dcp); +} + static bool dcp_external_is_idle(struct apple_dcp *dcp) { u32 control = readl_relaxed(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); @@ -6344,14 +7192,19 @@ static bool dcp_external_is_idle(struct apple_dcp *dcp) * drive the full panel (aura: chosen.asahi,show-notch=1). Follow it, so the * mode covers the same rows as the boot framebuffer did. */ -static bool boot_show_notch(void) +static bool dcp_boot_show_notch(const struct device_node *chosen) { const char *val; - return !of_property_read_string(of_chosen, "asahi,show-notch", &val) && + return !of_property_read_string(chosen, "asahi,show-notch", &val) && !strcmp(val, "1"); } +static bool boot_show_notch(void) +{ + return dcp_boot_show_notch(of_chosen); +} + /* * T8122 dcpext (DCP_FIRMWARE_V_14_7_TEMPLATE): if the PMP runs, the display * gate added its DISPEXT request and pointed the dcpext at it @@ -6451,7 +7304,9 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat { struct device_node *panel_np; struct apple_dcp *dcp = dev_get_drvdata(dev); + struct dcp_rtkit_live live_rtkit = {}; u32 cpu_ctrl; + int live = 0; int ret; if (dcp->fw_compat == DCP_FIRMWARE_V_27_0) { @@ -6624,6 +7479,9 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat if (ret) return dev_err_probe(dev, ret, "Failed to create PIODMA iommu child device\n"); + ret = dcp_create_fbdma_dev(dcp); + if (ret) + goto err_piodma; if (!dcp->iommu_dom) { ret = dev_err_probe(dev, -EPROBE_DEFER, "PIODMA iommu domain is unavailable\n"); @@ -6707,12 +7565,30 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); } + /* + * Check a handed-over session before anything is retained for it: a + * description that fails leaves the DCP unbound and nothing pinned. + * Its buffers are in no-map carveouts, which the kernel never hands out. + */ + live = dcp_rtkit_live_parse(dcp, &live_rtkit); + if (live < 0) { + ret = dev_err_probe(dev, live, "Invalid live RTKit handoff\n"); + goto err_piodma; + } /* Registering the mailbox can already expose RTKit buffer requests. */ ret = dcp_pin_live_session(dcp); - if (ret) + if (ret) { + if (live) + dcp_rtkit_live_unmap(&live_rtkit); goto err_piodma; + } /* External H17P supplies shared-buffer addresses during RTKit startup. */ - if (dcp->hw.iomfb_method_profile == + if (live) + dcp->rtk = apple_rtkit_init_adopted_with_session( + dev, dcp, "mbox", 0, + dcp->hw.link_report ? &link_report_rtkit_ops : &rtkit_ops, + &live_rtkit.session); + else if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL) dcp->rtk = apple_rtkit_init(dev, dcp, "mbox", 0, &external_h17p_rtkit_ops); @@ -6721,6 +7597,8 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat else dcp->rtk = apple_rtkit_init(dev, dcp, "mbox", 0, &rtkit_ops); if (IS_ERR(dcp->rtk)) { + if (live) + dcp_rtkit_live_unmap(&live_rtkit); ret = dev_err_probe(dev, PTR_ERR(dcp->rtk), "Failed to initialize RTKit\n"); goto err_piodma; @@ -6728,6 +7606,7 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat ret = devm_add_action_or_reset(dev, dcp_release_rtkit, dcp); if (ret) goto err_piodma; + dcp->rtkit_adopted = live; dcp_s2r_check_dt(dcp); /* After a warm restart its log counters need echoing, or it refuses its next idle. */ if (dcp->hw.s2r || dcp->hw.s2r_ext) @@ -6740,7 +7619,9 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat dev_dbg(dev, "negotiating RTKit with the running DCP\n"); /* Announce host readiness before awaiting external IOP readiness. */ - if (dcp->hw.iomfb_method_profile == + if (live) + ret = 0; /* HELLO and EPMAP happened before the handoff */ + else if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL) ret = apple_rtkit_wake_early_ap(dcp->rtk); else if (dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP) @@ -6768,8 +7649,9 @@ static void dcp_ext_give_up(struct apple_dcp *dcp, int err, const char *when); /* * The external processors whose failure must not take the DRM device down: - * T8122's, T6041's, T6050's and T8142's dcpext. One that fails to probe or bind joins - * as an unusable pipe (ext_dead), and the other displays go on without it. + * T8122's, T6041's, T6050's and T8142's dcpext, and the J773g's on 27.2. One + * that fails to probe or bind joins as an unusable pipe (ext_dead), and the + * other displays go on without it. * With every processor failed the DRM device has no pipe and does not bind. */ static bool dcp_ext_is_failsafe(struct device_node *np) @@ -6777,7 +7659,8 @@ static bool dcp_ext_is_failsafe(struct device_node *np) return of_device_is_compatible(np, "apple,t8122-dcpext") || of_device_is_compatible(np, "apple,t6041-dcpext") || of_device_is_compatible(np, "apple,t6050-dcpext") || - of_device_is_compatible(np, "apple,t8142-dcpext"); + of_device_is_compatible(np, "apple,t8142-dcpext") || + apple_t8132_dcpext_v27_2(np); } /* @@ -6879,6 +7762,9 @@ VISIBLE_IF_KUNIT void dcp_comp_unbind(struct device *dev, struct device *main, v drm_dev_get(dcp->crtc->base.dev); dcp->drm_retained = true; } + /* Its handler talks to the session this unbind leaves behind. */ + if (dcp->hdmi_hpd_irq) + disable_irq(dcp->hdmi_hpd_irq); iomfb_queue_stop(dcp); afk_quiesce(dcp->avep); afk_quiesce(dcp->dptxep); @@ -6905,6 +7791,7 @@ VISIBLE_IF_KUNIT void dcp_comp_unbind(struct device *dev, struct device *main, v dcp->announce.stopped = true; disable_delayed_work_sync(&dcp->announce_wq); dcp_test_point(dcp, DCP_TEST_UNBIND_ANNOUNCE_STOPPED); + disable_delayed_work_sync(&dcp->swap_watchdog_wq); cancel_work_sync(&dcp->vblank_wq); if (dcp->connector) cancel_work_sync(&dcp->connector->hotplug_wq); @@ -6999,10 +7886,12 @@ VISIBLE_IF_KUNIT void dcp_comp_unbind(struct device *dev, struct device *main, v cancel_work_sync(&dcp->bl_register_wq); cancel_work_sync(&dcp->bl_update_wq); } - if (dcp->clk) - devm_clk_put(dev, dcp->clk); + /* + * Both clocks are released with the bind's devres group. An explicit + * devm_clk_put() would also match the NULL devres entry of an absent + * optional clock and warn. + */ dcp->clk = NULL; - /* optional and possibly NULL, released with the bind's devres group */ dcp->clk_194 = NULL; dcp->firmware_clocks = NULL; dcp->num_firmware_clocks = 0; @@ -7082,8 +7971,9 @@ static void dcp_desktop_phy_off(void *data) } /* - * The fixed HDMI output of a desktop 26.x external processor (T6041 dcpext0): - * its DP PHY is powered here, as the boot loader's working sequence does. A + * The fixed HDMI output of a desktop external processor (T6041 dcpext0, and + * the J773g's T8132 dcpext0 on 27.2): its DP PHY is powered here, as the + * boot loader's working sequence does. A * Type-C output (dcpext1) has no fixed PHY; the display fabric powers the * PHY of the route a port claims (see dcp_typec_phy_on()). */ @@ -7125,7 +8015,7 @@ static void dcp_t8132_ext_routes(struct apple_dcp *dcp) of_get_child_by_name(dcp->dev->of_node, "typec-routes"); int ret; - if (!routes || !of_get_available_child_count(routes)) { + if (!dcp_typec_routes_available(routes)) { dev_info(dcp->dev, "no Type-C display routes enabled\n"); return; } @@ -7150,30 +8040,426 @@ static void dcp_t8132_ext_routes(struct apple_dcp *dcp) static int dcp_s2r_pm_register(struct apple_dcp *dcp); -static int dcp_platform_probe_pipe(struct platform_device *pdev) +/* A DCP node with apple,sleep-host-stop: the SoC's sleep needs the display stopped from here. */ +static bool dcp_sleep_host_stop; +static bool dcp_sleep_host_stop_missing; +static struct apple_dcp *dcp_t6041_host; + +static void dcp_t6041_host_release(void *data) { - const struct apple_dcp_hw_data *hw = of_device_get_match_data(&pdev->dev); - enum dcp_firmware_version fw_compat; - struct device *dev = &pdev->dev; - struct apple_dcp *dcp; - int ret, surf, num_surfs; - bool routes_failed = false; - u32 surf_en; - u32 mux_index; + struct apple_dcp *dcp = data; - if (dcp_session_retained(dev)) - return dev_err_probe(dev, -EBUSY, "Previous live DCP session requires a reboot\n"); + if (READ_ONCE(dcp_t6041_host) == dcp) { + WRITE_ONCE(dcp_sleep_host_stop, false); + WRITE_ONCE(dcp_t6041_host, NULL); + } +} - /* Reject unsupported external firmware before replacing the boot display. */ - if (of_device_is_compatible(dev->of_node, "apple,t8140-dcpext") && - !dcp_h17p_external_supported(dev->of_node)) { +#define DCP_T6041_MAX_PMGR_MAPS 16 + +struct dcp_t6041_pmgr_map { + struct device_node *np; + void __iomem *base; + resource_size_t size; +}; + +struct dcp_t6041_pmgr_cache { + struct dcp_t6041_pmgr_map maps[DCP_T6041_MAX_PMGR_MAPS]; + unsigned int count; +}; + +static void dcp_t6041_iounmap(void *base) +{ + iounmap((__force void __iomem *)base); +} + +static void dcp_t6041_pmgr_cache_put(struct dcp_t6041_pmgr_cache *cache) +{ + unsigned int i; + + for (i = 0; i < cache->count; i++) + of_node_put(cache->maps[i].np); +} + +static void __iomem *dcp_t6041_map_reg(struct device *dev, struct device_node *np, + const char *name, resource_size_t min_size, + resource_size_t *out_size) +{ + struct resource res; + resource_size_t size; + void __iomem *base; + int index; + + index = of_property_match_string(np, "reg-names", name); + if (index < 0) + return IOMEM_ERR_PTR(index); + if (of_address_to_resource(np, index, &res)) + return IOMEM_ERR_PTR(-EINVAL); + size = resource_size(&res); + if (size < min_size) { + dev_err(dev, "%pOF reg '%s' too small (%pa < %pa)\n", + np, name, &size, &min_size); + return IOMEM_ERR_PTR(-EINVAL); + } + + /* Shared with the PMGR, PMC and fabric drivers, so not claimed. */ + base = devm_ioremap(dev, res.start, size); + if (!base) + return IOMEM_ERR_PTR(-ENOMEM); + if (out_size) + *out_size = size; + + return base; +} + +static void __iomem *dcp_t6041_map_ps_node(struct device *dev, + struct dcp_t6041_pmgr_cache *cache, + struct device_node *ps_np) +{ + struct device_node *pmgr_np __free(device_node) = of_get_parent(ps_np); + struct dcp_t6041_pmgr_map *map = NULL; + struct resource res; + resource_size_t size; + void __iomem *base; + unsigned int i; + u32 off; + int ret; + + if (!pmgr_np) { + dev_err(dev, "%pOF has no parent pmgr node\n", ps_np); + return IOMEM_ERR_PTR(-EINVAL); + } + if (of_property_read_u32_index(ps_np, "reg", 0, &off)) { + dev_err(dev, "%pOF missing reg offset\n", ps_np); + return IOMEM_ERR_PTR(-EINVAL); + } + + for (i = 0; i < cache->count; i++) { + if (cache->maps[i].np == pmgr_np) { + map = &cache->maps[i]; + break; + } + } + + if (!map) { + if (cache->count >= ARRAY_SIZE(cache->maps)) { + dev_err(dev, "too many distinct pmgr parents for %pOF\n", ps_np); + return IOMEM_ERR_PTR(-ENOSPC); + } + if (of_address_to_resource(pmgr_np, 0, &res)) { + dev_err(dev, "%pOF missing parent pmgr reg\n", pmgr_np); + return IOMEM_ERR_PTR(-EINVAL); + } + size = resource_size(&res); + /* Shared with the PMGR driver, so mapped via of_iomap without claiming. */ + base = of_iomap(pmgr_np, 0); + if (!base) + return IOMEM_ERR_PTR(-ENOMEM); + ret = devm_add_action_or_reset(dev, dcp_t6041_iounmap, (__force void *)base); + if (ret) + return IOMEM_ERR_PTR(ret); + + map = &cache->maps[cache->count++]; + map->np = of_node_get(pmgr_np); + map->base = base; + map->size = size; + } + + if ((off & 3) || off > map->size || map->size - off < sizeof(u32)) { + dev_err(dev, "%pOF reg offset %#x out of bounds for %pOF (%pa)\n", + ps_np, off, pmgr_np, &map->size); + return IOMEM_ERR_PTR(-EINVAL); + } + + return map->base + off; +} + +static int dcp_t6041_parse_chain(struct device *dev, struct dcp_t6041_power *pwr, + struct dcp_t6041_pmgr_cache *cache, + struct device_node *child, + resource_size_t gapf_size, + resource_size_t pg_size, + resource_size_t pg_aux_size, + struct dcp_t6041_chain *chain) +{ + struct of_phandle_args args; + resource_size_t pg_lim; + void __iomem *pg_base; + u32 gapf_off, pg_off[2]; + bool pg_aux; + int count, i; + + if (of_property_read_u32(child, "reg", &chain->reg)) { + dev_err(dev, "%pOF missing reg\n", child); + return -EINVAL; + } + if (of_property_read_string(child, "label", &chain->name)) + chain->name = child->name; + + chain->is_main = of_property_read_bool(child, "apple,main-chain"); + pg_aux = of_property_read_bool(child, "apple,pwrgate-aux"); + + if (of_property_read_u32(child, "apple,gapf-offset", &gapf_off) || + (gapf_off & 3) || gapf_off > gapf_size || gapf_size - gapf_off < sizeof(u32)) { + dev_err(dev, "%pOF invalid apple,gapf-offset\n", child); + return -EINVAL; + } + chain->gapf = pwr->gapf + gapf_off; + + pg_base = pg_aux ? pwr->pwrgate_aux : pwr->pwrgate; + pg_lim = pg_aux ? pg_aux_size : pg_size; + if (of_property_read_u32_array(child, "apple,pwrgate-offsets", pg_off, 2) || + (pg_off[0] & 3) || pg_off[0] > pg_lim || pg_lim - pg_off[0] < sizeof(u32) || + (pg_off[1] & 3) || pg_off[1] > pg_lim || pg_lim - pg_off[1] < sizeof(u32)) { + dev_err(dev, "%pOF invalid apple,pwrgate-offsets\n", child); + return -EINVAL; + } + chain->pg_a = pg_base + pg_off[0]; + chain->pg_b = pg_base + pg_off[1]; + + if (of_property_present(child, "apple,fabric-domain")) { + struct device_node *fab_np __free(device_node) = + of_parse_phandle(child, "apple,fabric-domain", 0); + + if (!fab_np) { + dev_err(dev, "%pOF invalid apple,fabric-domain\n", child); + return -EINVAL; + } + chain->fabric = dcp_t6041_map_ps_node(dev, cache, fab_np); + if (IS_ERR(chain->fabric)) + return PTR_ERR(chain->fabric); + } else if (chain->is_main) { + dev_err(dev, "%pOF main chain missing apple,fabric-domain\n", child); + return -EINVAL; + } + + count = of_count_phandle_with_args(child, "power-domains", "#power-domain-cells"); + if (count < 3) { + dev_err(dev, "%pOF needs at least 3 power-domains (got %d)\n", child, count); + return -EINVAL; + } + + chain->domains = devm_kcalloc(dev, count, sizeof(*chain->domains), GFP_KERNEL); + if (!chain->domains) + return -ENOMEM; + chain->num_domains = count; + + for (i = 0; i < count; i++) { + int ret = of_parse_phandle_with_args(child, "power-domains", + "#power-domain-cells", i, &args); + void __iomem *reg; + + if (ret) { + dev_err(dev, "%pOF power-domains[%d] parse failed: %d\n", child, i, ret); + return ret; + } + reg = dcp_t6041_map_ps_node(dev, cache, args.np); + of_node_put(args.np); + if (IS_ERR(reg)) + return PTR_ERR(reg); + chain->domains[i] = reg; + } + + if (chain->is_main && count > 3) { + chain->child_saved = devm_kcalloc(dev, count - 3, sizeof(*chain->child_saved), + GFP_KERNEL); + if (!chain->child_saved) + return -ENOMEM; + } + + return 0; +} + +static int dcp_t6041_map_power(struct apple_dcp *dcp) +{ + struct device *dev = dcp->dev; + struct device_node *np __free(device_node) = + of_parse_phandle(dev->of_node, "apple,display-power", 0); + struct dcp_t6041_power *pwr = &dcp->t6041_power; + struct dcp_t6041_pmgr_cache cache = {}; + resource_size_t pg_size = 0, pg_aux_size = 0, gapf_size = 0; + const struct { + const char *name; + void __iomem **dst; + resource_size_t min_size; + resource_size_t *out_size; + } regs[] = { + { "pmc-dcp", &pwr->pmc_dcp, 0x8, NULL }, + { "pwrgate", &pwr->pwrgate, 0x4, &pg_size }, + { "pwrgate-aux", &pwr->pwrgate_aux, 0x4, &pg_aux_size }, + { "gapf", &pwr->gapf, 0x4, &gapf_size }, + { "axi2af", &pwr->axi2af, 0xc, NULL }, + }; + unsigned int nchains = 0, idx = 0, main_count = 0, i, j; + int ret; + + if (!np) + return -ENODEV; + if (!of_device_is_compatible(np, "apple,t6041-display-power")) + return -EINVAL; + + for (i = 0; i < ARRAY_SIZE(regs); i++) { + void __iomem *base = dcp_t6041_map_reg(dev, np, regs[i].name, + regs[i].min_size, regs[i].out_size); + + if (IS_ERR(base)) { + dev_err(dev, "apple,display-power reg '%s' failed: %ld\n", + regs[i].name, PTR_ERR(base)); + ret = PTR_ERR(base); + goto err; + } + *regs[i].dst = base; + } + + for_each_available_child_of_node_scoped(np, child) { + if (!of_node_name_eq(child, "chain")) + continue; + nchains++; + } + if (!nchains) { + dev_err(dev, "%pOF has no chain child nodes\n", np); + ret = -EINVAL; + goto err; + } + + pwr->chains = devm_kcalloc(dev, nchains, sizeof(*pwr->chains), GFP_KERNEL); + if (!pwr->chains) { + ret = -ENOMEM; + goto err; + } + pwr->num_chains = nchains; + + for_each_available_child_of_node_scoped(np, child) { + if (!of_node_name_eq(child, "chain")) + continue; + ret = dcp_t6041_parse_chain(dev, pwr, &cache, child, + gapf_size, pg_size, pg_aux_size, + &pwr->chains[idx]); + if (ret) + goto err; + if (pwr->chains[idx].is_main) + main_count++; + idx++; + } + + if (main_count != 1) { + dev_err(dev, "%pOF expected exactly 1 apple,main-chain, got %u\n", + np, main_count); + ret = -EINVAL; + goto err; + } + + /* Order chains by ascending reg address so lowering order matches DT. */ + for (i = 1; i < nchains; i++) { + struct dcp_t6041_chain key = pwr->chains[i]; + + for (j = i; j > 0 && pwr->chains[j - 1].reg > key.reg; j--) + pwr->chains[j] = pwr->chains[j - 1]; + pwr->chains[j] = key; + } + for (i = 1; i < nchains; i++) { + if (pwr->chains[i].reg == pwr->chains[i - 1].reg) { + dev_err(dev, "%pOF duplicate chain reg %u\n", + np, pwr->chains[i].reg); + ret = -EINVAL; + goto err; + } + } + for (i = 0; i < nchains; i++) { + if (pwr->chains[i].is_main) { + pwr->main_chain = &pwr->chains[i]; + break; + } + } + + dcp_t6041_pmgr_cache_put(&cache); + return 0; + +err: + dcp_t6041_pmgr_cache_put(&cache); + memset(pwr, 0, sizeof(*pwr)); + return ret; +} + +/* + * T8132 (Mac mini, J773g) external processor on firmware 27.2, admitted by + * dcp_check_firmware_version(): what the T6041 dcpext gets on that firmware + * (see dcp_platform_probe_pipe()), whatever hw data the compatible matched. + * - firmware_dma_bits 41: its firmware DART's window (ADT dart-dcpext0 + * vm-base 1 TiB, vm-size-23 64 GiB; apple,dma-range <0x100 0 0x10 0>) + * ends at 1 TiB + 64 GiB, which takes 41 bits, as on T6041. + * - num_dptx_ports 2: the dcpdptx-port-epic units 0 and 1 every external + * processor of this generation has (T6041's, and T8132's own on the M4 + * path); the fixed HDMI port is unit 0. + * - adopt_live_session: iBoot leaves it running with the 27.2 image + * loaded (ADT pre-loaded = running = 1), as the boot loader hands it + * over; Linux never starts its CPU. + * - sink_metadata_edid: the display it finds at boot is its first sink, + * as on the T6041 dcpext. + * No sleep support: neither a firmware-27 sleep nor a link release has run + * on this processor. + */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8132_dcpext_v27 = { + .firmware_dma_bits = 41, + .num_dptx_ports = 2, + .adopt_live_session = true, + .firmware_compat = DCP_FIRMWARE_V_27_0, + .sink_metadata_edid = true, +}; + +/* + * T8132 internal display processor on firmware 27.2, admitted by + * dcp_check_firmware_version(), whatever hw data its compatible matched: + * - firmware_dma_bits 41: its firmware DART's window (apple,dma-range + * <0x100 0 0x10 0>, 1 TiB + 64 GiB) takes 41 bits, as the dcpext's does. + * - num_dptx_ports 0: it drives the panel only. + * - adopt_live_session: iBoot leaves it running with the 27.2 image and the + * panel lit; Linux never starts its CPU. + * - s2r: the firmware-27 stop (iomfb_v27.c) for DPMS off and deep sleep, + * with the 27.2 table's calls and the power words its device tree names + * (dcp_s2r_layout_from_dt()). It has no secure mailbox. + */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8132_v27 = { + .firmware_dma_bits = 41, + .num_dptx_ports = 0, + .adopt_live_session = true, + .firmware_compat = DCP_FIRMWARE_V_27_0, + .s2r = true, + .s2r_no_secure_port = true, +}; + +static int dcp_platform_probe_pipe(struct platform_device *pdev) +{ + const struct apple_dcp_hw_data *hw = of_device_get_match_data(&pdev->dev); + enum dcp_firmware_version fw_compat; + struct device *dev = &pdev->dev; + struct apple_dcp *dcp; + int ret, surf, num_surfs; + bool routes_failed = false; + u32 surf_en; + u32 mux_index; + + if (dcp_session_retained(dev)) + return dev_err_probe(dev, -EBUSY, "Previous live DCP session requires a reboot\n"); + + /* Reject unsupported external firmware before replacing the boot display. */ + if (of_device_is_compatible(dev->of_node, "apple,t8140-dcpext") && + !dcp_h17p_external_supported(dev->of_node)) { dev_err(dev, "Unsupported external display hardware or firmware handoff\n"); return -ENODEV; } fw_compat = dcp_check_firmware_version(dev); - if (fw_compat == DCP_FIRMWARE_UNKNOWN) + if (fw_compat == DCP_FIRMWARE_UNKNOWN) { + /* + * The firmware does not change until the next boot, so this + * processor never registers its Type-C display routes: disable + * them, so that the port controllers that name them as their + * mode switch do not wait for them, and USB on the ports goes on. + */ + dcp_typec_routes_disable_dev(dev); return -ENODEV; + } if (fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || (fw_compat == DCP_FIRMWARE_V_27_0 && of_device_is_compatible(dev->of_node, "apple,t6041-dcp"))) { @@ -7199,6 +8485,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) */ if (fw_compat != DCP_FIRMWARE_V_14_7 && fw_compat != DCP_FIRMWARE_V_26_6 && + fw_compat != DCP_FIRMWARE_V_27_0 && fw_compat != DCP_FIRMWARE_M4 && !of_property_present(dev->of_node, "apple,bw-scratch") && !hw->firmware_clock) @@ -7214,6 +8501,10 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) INIT_LIST_HEAD(&dcp->swapped_out_fbs); mutex_init(&dcp->swapped_out_fbs_lock); + xa_init(&dcp->fb_mirrors); + mutex_init(&dcp->fb_mirror_lock); + init_completion(&dcp->v27_wake_video); + init_completion(&dcp->v27_wake_hotplug); ret = dcp_backlight_init(dcp, dev); if (ret) return ret; @@ -7221,7 +8512,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) dcp->fw_compat = fw_compat; dcp->v27_j714s = fw_compat == DCP_FIRMWARE_V_27_0 && - of_machine_is_compatible("apple,j714s"); + apple_t6050_sleep_property("apple,display-method-sleep"); /* * Probe-lifetime like the desktop state: component bind opens a devres * group on this device and releases it on failure or unbind. @@ -7259,7 +8550,6 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) dcp->desktop = devm_kzalloc(dev, sizeof(*dcp->desktop), GFP_KERNEL); if (!dcp->desktop) return -ENOMEM; - spin_lock_init(&dcp->desktop->hdr_lock); /* * The opaque client identity of the IOMFB calls. The firmware's * own client passes a kernel pointer there; pass a random value @@ -7271,7 +8561,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) dcp->ext_failsafe = dcp_ext_is_failsafe(dev->of_node); dcp->dcpext = of_device_is_compatible(dev->of_node, "apple,dcpext"); dcp->external = of_device_is_compatible(dev->of_node, "apple,t6030-dcpext"); - dcp->desktop_external = of_device_is_compatible(dev->of_node, "apple,t6041-dcpext"); + dcp->desktop_external = dcp_desktop_external_node(dev->of_node); dcp->external_native = dcp->external && dcp_t6030_ext_native(dev->of_node); /* * J714s: the internal panel's processor suspends and resumes asynchronously, not in @@ -7303,12 +8593,15 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) dcp_fabric_init(dcp); spin_lock_init(&dcp->mode_state.lock); spin_lock_init(&dcp->metadata.lock); + spin_lock_init(&dcp->hdr.lock); + dcp->active_color.score = -1; mutex_init(&dcp->dcpavserv.lock); INIT_WORK(&dcp->dcpavserv.close_wq, dcpavserv_close_work); ret = dcpavserv_edid_retry_init(dcp); if (ret) return ret; dcp->hw = *(struct apple_dcp_hw_data *)of_device_get_match_data(dev); + dcp_apply_dt_profile(dcp); /* The link report: on the board it has run on (dcp_j714s_ext()). */ if (!dcp_j714s_ext(dev)) dcp->hw.link_report = false; @@ -7320,41 +8613,45 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) of_device_is_compatible(dev->of_node, "apple,t8142-dcp")) dcp->hw.iomfb_method_profile = DCP_IOMFB_METHODS_DEFAULT; /* - * T6041 internal panel on firmware 27 adopts the running DCP session - * with 41-bit firmware DMA addressing and no DPTX port services, - * matching the H17-generation internal-panel profile. - */ - if (fw_compat == DCP_FIRMWARE_V_27_0 && - of_device_is_compatible(dev->of_node, "apple,t6041-dcp")) { - dcp->hw.firmware_dma_bits = 41; - dcp->hw.num_dptx_ports = 0; - dcp->hw.adopt_live_session = true; - } - /* - * The same for the T8122 internal panel on firmware 27: its DART - * window is 0x100_0000_0000 + 64 GiB, and dcpext drives the external - * ports. + * The T8122 external processor on firmware 27: the boot loader leaves + * it unpowered (its DISPEXT domains are off at handoff), so Linux + * starts it as on 14.7, with the firmware-27 endpoints and both DPTX + * port services. Its DART window is the internal panel's, which the + * display gate copied onto its DARTs (gate_t8122_dcpext_alias()): + * 0x100_0000_0000 + 64 GiB, so 41-bit firmware DMA addressing as there. */ if (fw_compat == DCP_FIRMWARE_V_27_0 && - of_device_is_compatible(dev->of_node, "apple,t8122-dcp")) { - dcp->hw.firmware_dma_bits = 41; - dcp->hw.num_dptx_ports = 0; - dcp->hw.adopt_live_session = true; + of_device_is_compatible(dev->of_node, "apple,t8122-dcpext")) { + if (!dcp->hw.firmware_dma_bits) + dcp->hw.firmware_dma_bits = 41; + dcp->hw.num_dptx_ports = 2; + dcp->hw.fw_14_7_endpoints = false; + dcp->hw.adopt_live_session = false; } if (fw_compat == DCP_FIRMWARE_V_27_0 && of_device_is_compatible(dev->of_node, "apple,t6041-dcpext")) { - dcp->hw.firmware_dma_bits = 41; + if (!dcp->hw.firmware_dma_bits) + dcp->hw.firmware_dma_bits = 41; dcp->hw.num_dptx_ports = 2; dcp->hw.adopt_live_session = true; dcp->hw.sink_metadata_edid = true; /* Its ports where they have been opened so far, see dcp_v27_dptx_layout(). */ dcp->hw.dptx_endpoint = DPTX_ENDPOINT_V2; } + if (fw_compat == DCP_FIRMWARE_V_27_0 && + of_device_is_compatible(dev->of_node, "apple,t8132-dcpext")) + dcp->hw = apple_dcp_hw_t8132_dcpext_v27; + if (fw_compat == DCP_FIRMWARE_V_27_0 && + of_device_is_compatible(dev->of_node, "apple,t8132-dcp")) + dcp->hw = apple_dcp_hw_t8132_v27; /* - * A SoC with derived power words is offered the stop only when asked for, and only on + * A stop needs power words: a static layout, or the device tree's (see + * dcp_s2r_layout_from_dt(), offered by default). A SoC whose static words are only + * derived (hw.s2r_untested, T8142) is offered it only when asked for, and only on * firmware 27.0, whose calls are the ones that ran with them. */ - if (dcp->hw.s2r && (!dcp->hw.s2r_layout || + if (dcp->hw.s2r && ((!dcp->hw.s2r_layout && + !of_property_present(dev->of_node, "apple,display-power")) || (dcp->hw.s2r_untested && (!s2r_untested || fw_compat != DCP_FIRMWARE_V_27_0)))) dcp->hw.s2r = false; @@ -7406,9 +8703,28 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) of_property_read_u32(dev->of_node, "apple,dcp-endpoint", &dcp->peer_endpoint); if (of_property_read_bool(dev->of_node, "apple,typec-hybrid-first")) dcp_typec_hybrid_first_dt(); + if (of_property_read_bool(dev->of_node, "apple,sleep-host-stop")) { + ret = dcp_t6041_map_power(dcp); + if (ret) { + dev_err(dev, + "apple,display-power unusable (%d): host-driven sleep disabled\n", + ret); + WRITE_ONCE(dcp_sleep_host_stop_missing, true); + } else { + dcp->sleep_host_stop = true; + WRITE_ONCE(dcp_t6041_host, dcp); + WRITE_ONCE(dcp_sleep_host_stop, true); + ret = devm_add_action_or_reset(dev, dcp_t6041_host_release, dcp); + if (ret) + return ret; + } + } of_property_read_u32(dev->of_node, "apple,dptx-phy", &dcp->dptx_phy); of_property_read_u32(dev->of_node, "apple,dptx-die", &dcp->dptx_die); dcp->fixed_dptx_phy = dcp->dptx_phy; + mutex_init(&dcp->s2r_dart_lock); + init_completion(&dcp->s2r_dart_done); + init_completion(&dcp->s2r_hpd_done); init_completion(&dcp->typec_iomfb_hpd_ready); INIT_DELAYED_WORK(&dcp->typec_reconnect_wq, dcp_typec_reconnect_work); @@ -7884,13 +9200,54 @@ static int dcp_platform_probe_t8132_ext(struct platform_device *pdev) * bind's, may still appear (bounded by the deferred probe timeout); on any * other failure join as an unusable pipe. */ +/* + * A DCP driven through the iBoot interface alone (DCP_FIRMWARE_IBOOT, + * iomfb_iboot.c): no component of a display subsystem, with a DRM device of + * its own. Its adopted session cannot be stopped: once the firmware is + * touched, its DMA and this driver stay until reboot, and a failed start + * leaves the device bound without a display. + */ +static int dcp_platform_probe_iboot(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct apple_dcp *dcp; + int ret; + + if (dcp_session_retained(dev)) + return dev_err_probe(dev, -EBUSY, "Previous live DCP session requires a reboot\n"); + dcp = kzalloc_obj(*dcp); + if (!dcp) + return -ENOMEM; + ret = devm_add_action_or_reset(dev, dcp_release_context, dcp); + if (ret) + return ret; + dcp->dev = dev; + dcp->hw = *(struct apple_dcp_hw_data *)of_device_get_match_data(dev); + dcp->fw_compat = dcp->hw.firmware_compat; + ret = iommu_device_use_default_domain(dev); + if (ret) + return ret; + ret = devm_add_action_or_reset(dev, dcp_release_dma_domain, dcp); + if (ret) + return ret; + platform_set_drvdata(pdev, dcp); + return dcp_iboot_probe(dcp); +} + static int dcp_platform_probe(struct platform_device *pdev) { + const struct apple_dcp_hw_data *hw = of_device_get_match_data(&pdev->dev); struct device *dev = &pdev->dev; struct apple_dcp *dcp; void *group; int ret; + if (hw->firmware_compat == DCP_FIRMWARE_IBOOT) { + /* The port controllers wait for the USB-C display switches. */ + t8152_typec_register(dev); + return dcp_platform_probe_iboot(pdev); + } + /* t6041_dcpext=0: stay off the external processors' hardware. */ if (of_device_is_compatible(dev->of_node, "apple,t6041-dcpext") && !t6041_dcpext) { @@ -7898,7 +9255,7 @@ static int dcp_platform_probe(struct platform_device *pdev) return -ENODEV; } - if (of_device_is_compatible(dev->of_node, "apple,t8132-dcpext")) + if (dcp_t8132_ext_m4_node(dev->of_node)) return dcp_platform_probe_t8132_ext(pdev); if (!dcp_ext_is_failsafe(dev->of_node)) return dcp_platform_probe_pipe(pdev); @@ -7949,6 +9306,11 @@ static void dcp_platform_remove(struct platform_device *pdev) { struct apple_dcp *dcp = platform_get_drvdata(pdev); + /* No component and none of the works below; see dcp_iboot_remove(). */ + if (dcp && dcp_is_iboot(dcp)) { + dcp_iboot_remove(dcp); + return; + } if (dcp) { cancel_work_sync(&dcp->s2r_prewarm_work); cancel_delayed_work_sync(&dcp->s2r_prewarm_off_wq); @@ -7974,7 +9336,7 @@ static void dcp_platform_remove(struct platform_device *pdev) if (dcp) av_audiosrv_quiesce(dcp); /* An adopted external DCP never joined the DRM device. */ - if (of_device_is_compatible(pdev->dev.of_node, "apple,t8132-dcpext")) { + if (dcp_t8132_ext_m4_node(pdev->dev.of_node)) { /* Enabled with its Type-C routes, see dcp_t8132_ext_routes(). */ if (dcp) disable_delayed_work_sync(&dcp->typec_reconnect_wq); @@ -8008,6 +9370,9 @@ VISIBLE_IF_KUNIT void dcp_platform_shutdown(struct platform_device *pdev) if (dcp_takeover_was_aborted(dcp)) return; + /* The iBoot interface's display stays as it is: no component to remove. */ + if (dcp && dcp_is_iboot(dcp)) + return; if (dcp && iomfb_is_m4(dcp)) { dcp_comp_unbind(&pdev->dev, NULL, NULL); @@ -8040,7 +9405,7 @@ VISIBLE_IF_KUNIT void dcp_platform_shutdown(struct platform_device *pdev) } /* An adopted external DCP never joined the DRM device. */ - if (of_device_is_compatible(pdev->dev.of_node, "apple,t8132-dcpext")) + if (dcp_t8132_ext_m4_node(pdev->dev.of_node)) return; component_del(&pdev->dev, &dcp_comp_ops); } @@ -8239,6 +9604,9 @@ static void dcp_platform_complete(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); + /* The iBoot interface's display stays powered across system sleep. */ + if (dcp_is_iboot(dcp)) + return; if (dcp_is_ext26(dcp)) { WRITE_ONCE(dcp->ext26_pm_preparing, false); if (dcp->ext26_pm_work_off && !READ_ONCE(dcp->ext26_blocked) && @@ -8314,6 +9682,29 @@ static const struct dcp_s2r_layout dcp_s2r_t8142 = { .pmc_dcp = false, }; +/* + * T8103's, from its device tree: DISP0's CPU (0x10018) and front end (0x360) power words, + * and no system word or retention words. The DCP's firmware DART has its stream 0, the + * display DART streams 0 and 4 (the display and its PIODMA). + */ +static const struct dcp_s2r_layout dcp_s2r_t8103 = { + .disp_cpu = 0x10018, + .disp_fe = 0x360, + .dcp_streams = BIT(0), + .disp_streams = BIT(0) | BIT(4), +}; + +/* + * T8103's external display processor: DISPEXT0's CPU (0x378) and front end (0x368) + * power words, with the same DART stream layout as the internal DCP. + */ +static const struct dcp_s2r_layout dcp_s2r_t8103_ext = { + .disp_cpu = 0x378, + .disp_fe = 0x368, + .dcp_streams = BIT(0), + .disp_streams = BIT(0) | BIT(4), +}; + /* TEST: J813 external processors, ADT DISPEXT0/1 power words. */ static const struct dcp_s2r_layout dcp_s2r_t8142_ext[] = { { .disp_cpu = 0x428, .disp_fe = 0x418, .disp_sys = 0x308, @@ -8331,8 +9722,14 @@ static const struct dcp_s2r_layout *dcp_s2r_layout(struct apple_dcp *dcp) { if (dcp_s2r_is_t8142_ext(dcp)) return &dcp_s2r_t8142_ext[dcp->index - 1]; - return dcp->hw.s2r_layout ?: &dcp_s2r_t8140; + if (dcp->hw.s2r_layout) + return dcp->hw.s2r_layout; + return dcp->s2r_dt_layout_ok ? &dcp->s2r_dt_layout : &dcp_s2r_t8140; } + +/* T6041's display stop and restart for its own sleep driver, below: T8140's DART streams. */ +#define DCP_S2R_DISP_STREAMS (dcp_s2r_t8140.disp_streams) +#define DCP_S2R_DCP_STREAMS (dcp_s2r_t8140.dcp_streams) #define DCP_PS_MIN GENMASK(19, 16) static struct device *dcp_s2r_find_dart(struct device_node *np) @@ -8373,22 +9770,40 @@ static void dcp_s2r_find_darts(struct apple_dcp *dcp) } } +static void dcp_s2r_dart_end(struct apple_dcp *dcp) +{ + guard(mutex)(&dcp->s2r_dart_lock); + WRITE_ONCE(dcp->s2r_active, false); +} + void dcp_s2r_dart_power(struct apple_dcp *dcp, u32 on) { + int ret = 0; + + if (dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP) + dev_dbg(dcp->dev, "D572(%u) s2r_active=%u\n", + on, READ_ONCE(dcp->s2r_active)); + + guard(mutex)(&dcp->s2r_dart_lock); if (!READ_ONCE(dcp->s2r_active)) return; if (dcp->s2r_disp_dart) - apple_dart_display_streams(dcp->s2r_disp_dart, dcp_s2r_layout(dcp)->disp_streams, - on, false); - complete(&dcp->s2r_dart_done); + ret = apple_dart_display_streams(dcp->s2r_disp_dart, + dcp_s2r_layout(dcp)->disp_streams, + on, false); + if (ret) + WRITE_ONCE(dcp->s2r_dart_err, ret); + if (dcp->fw_compat != DCP_FIRMWARE_V_26_6_DESKTOP || !on || ret) + complete(&dcp->s2r_dart_done); } static bool dcp_s2r_capable(struct apple_dcp *dcp) { /* - * Firmware 27.2 and 27.3 run as V_27_0 with their own tables, which have no tag for the - * AP link's release (27.2 moved it to A550): an empty tag panics the firmware. + * Firmware 27.2 and 27.3 run as V_27_0 with their own tables. 27.2's has the AP link's + * release (A550); a table without a tag for it can't stop: an empty tag panics the + * firmware. */ if (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && (!dcp->v27_methods || !dcp->v27_methods[dcpep_unnamed_500].tag[0])) @@ -8456,6 +9871,7 @@ static int dcp_s2r_quiesce(struct apple_dcp *dcp, u32 *status) bool idle; int ret; + WRITE_ONCE(dcp->s2r_dart_err, 0); reinit_completion(&dcp->s2r_dart_done); dcp_s2r_find_darts(dcp); WRITE_ONCE(dcp->s2r_active, true); @@ -8481,6 +9897,11 @@ static int dcp_s2r_quiesce(struct apple_dcp *dcp, u32 *status) ret = -ETIMEDOUT; goto err; } + ret = READ_ONCE(dcp->s2r_dart_err); + if (ret) { + dev_err(dcp->dev, "display DART stream off failed on D572: %d\n", ret); + goto err; + } dev_dbg(dcp->dev, "display off: set_power_state(0) %lld ms, D572 %lld ms\n", power_ms, ktime_ms_delta(ktime_get(), start)); display_off = true; @@ -8533,13 +9954,13 @@ static int dcp_s2r_quiesce(struct apple_dcp *dcp, u32 *status) dev_dbg(dcp->dev, "firmware idle after %lld ms, status %#x\n", ktime_ms_delta(ktime_get(), start), *status); - WRITE_ONCE(dcp->s2r_active, false); + dcp_s2r_dart_end(dcp); dcp->s2r_refused_off = false; return 0; err: - WRITE_ONCE(dcp->s2r_active, false); + dcp_s2r_dart_end(dcp); dcp_s2r_put_darts(dcp); /* * Refused with the display off: leave the firmware running, never stop it under its @@ -8561,8 +9982,16 @@ static int dcp_s2r_quiesce(struct apple_dcp *dcp, u32 *status) /* Its power state can only be lowered once this has finished. */ static int dcp_s2r_stop_streams(struct apple_dcp *dcp) { + int ret; + if (!dcp->s2r_dcp_dart) return -ENODEV; + if (dcp->hw.s2r_disp_dart_with_dcp && dcp->s2r_disp_dart) { + ret = apple_dart_display_streams(dcp->s2r_disp_dart, + dcp_s2r_layout(dcp)->disp_streams, false, true); + if (ret) + return ret; + } return apple_dart_display_streams(dcp->s2r_dcp_dart, dcp_s2r_layout(dcp)->dcp_streams, false, true); @@ -8600,10 +10029,12 @@ static int dcp_s2r_stop_firmware(struct apple_dcp *dcp) */ static bool dcp_s2r_ext_capable(struct apple_dcp *dcp) { + if (!dcp->hw.s2r_ext || !of_property_present(dcp->dev->of_node, "apple,display-power")) + return false; if (dcp->fw_compat == DCP_FIRMWARE_V_27_0) - return dcp->hw.s2r_ext && s2r_untested && dcp->v27_methods && + return (!dcp->hw.s2r_untested || s2r_untested) && dcp->v27_methods && dcp->v27_methods[dcpep_unnamed_500].tag[0]; - return dcp->fw_compat == DCP_FIRMWARE_H17P && dcp->hw.s2r_ext; + return dcp->fw_compat == DCP_FIRMWARE_H17P; } /* @@ -8686,11 +10117,28 @@ static int dcp_s2r_stop_crashed(struct apple_dcp *dcp) return 0; } +static void dcp_s2r_hdmi_irq_disable(struct apple_dcp *dcp) +{ + if (dcp->hdmi_hpd_irq && !dcp->s2r_hdmi_irq_disabled) { + disable_irq(dcp->hdmi_hpd_irq); + dcp->s2r_hdmi_irq_disabled = true; + } +} + +static void dcp_s2r_hdmi_irq_enable(struct apple_dcp *dcp) +{ + if (dcp->hdmi_hpd_irq && dcp->s2r_hdmi_irq_disabled) { + dcp->s2r_hdmi_irq_disabled = false; + dcp_fabric_run_resume(&dcp_resume_ops, dcp); + } +} + static int dcp_s2r_ext_suspend(struct apple_dcp *dcp) { int ret; if (READ_ONCE(dcp->s2r_fw_down)) { + dcp_s2r_hdmi_irq_disable(dcp); dcp_s2r_stop_failed_start(dcp); dcp_s2r_find_darts(dcp); dcp->s2r_stopped = true; @@ -8705,9 +10153,15 @@ static int dcp_s2r_ext_suspend(struct apple_dcp *dcp) return 0; } - /* No A500 and no disconnect: the link and its crossbar output just go down. */ + /* + * No A500 and no disconnect: the link and its crossbar output just go down. + * If dcp_s2r_stop_crashed() fails, it calls dcp_s2r_restart_failed_stop(), + * which re-enables hdmi_hpd_irq on a clean restart or leaves it disabled + * while the firmware stays crashed. + */ if (dcp_s2r_stops_crashed(dcp)) { dcp_disable_typec_work(dcp, false); + dcp_s2r_hdmi_irq_disable(dcp); dcp_typec_route_park(dcp); return dcp_s2r_stop_crashed(dcp); } @@ -8718,9 +10172,11 @@ static int dcp_s2r_ext_suspend(struct apple_dcp *dcp) dev_dbg(dcp->dev, "a display is attached: released for the sleep, connected again after it\n"); dcp_disable_typec_work(dcp, false); + dcp_s2r_hdmi_irq_disable(dcp); ret = dcp_external_disconnect(dcp, false); if (ret) { dcp_enable_typec_work(dcp); + dcp_s2r_hdmi_irq_enable(dcp); return ret; } @@ -8730,6 +10186,7 @@ static int dcp_s2r_ext_suspend(struct apple_dcp *dcp) if (iomfb_queue_settle(dcp, msecs_to_jiffies(500))) { iomfb_pause_presentation(dcp, false); dcp_enable_typec_work(dcp); + dcp_s2r_hdmi_irq_enable(dcp); dev_err(dcp->dev, "display updates still pending, refusing sleep\n"); return -EBUSY; } @@ -8742,6 +10199,7 @@ static int dcp_s2r_ext_suspend(struct apple_dcp *dcp) dev_err(dcp->dev, "no reply to A500: %d\n", ret); WRITE_ONCE(dcp->crashed, true); dcp_typec_route_unpark(dcp); + /* Keep typec work and hdmi_hpd_irq disabled while firmware is crashed. */ return ret == -ETIMEDOUT ? -EBUSY : ret; } usleep_range(4000, 5000); @@ -8753,6 +10211,7 @@ static int dcp_s2r_ext_suspend(struct apple_dcp *dcp) readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_STATUS)); WRITE_ONCE(dcp->crashed, true); dcp_typec_route_unpark(dcp); + /* Keep typec work and hdmi_hpd_irq disabled while firmware is crashed. */ return ret == -ETIMEDOUT ? -EBUSY : ret; } @@ -8781,6 +10240,13 @@ static int dcp_s2r_suspend(struct apple_dcp *dcp) bool was_off; int ret; + /* + * Not bound into the display subsystem (a component unbind released the RTKit + * session): nothing of the firmware is this driver's to stop. + */ + if (IS_ERR_OR_NULL(dcp->rtk)) + return 0; + /* Still stopped from a suspend that never reached the commit. */ if (READ_ONCE(dcp->s2r_fw_down)) { dcp_s2r_stop_failed_start(dcp); @@ -8840,7 +10306,13 @@ static void dcp_s2r_ps_lower(void __iomem *reg) writel((val & ~GENMASK(3, 0)) | GENMASK(9, 8), reg); } -/* Its display-power words, pmc-dcp only where the layout has one. */ +/* A retention word: the whole of it from a hw-data layout, only its masked bits from the DT's. */ +static void dcp_s2r_ret_write(void __iomem *reg, u32 mask, u32 val, u32 word) +{ + writel(mask ? (readl(reg) & ~mask) | (val & mask) : word, reg); +} + +/* Its display-power words, pwrgate and pmc-dcp only where the layout has them. */ static int dcp_s2r_map_power(struct apple_dcp *dcp, void __iomem **ps, void __iomem **pwrgate, void __iomem **pmc) { @@ -8851,12 +10323,14 @@ static int dcp_s2r_map_power(struct apple_dcp *dcp, void __iomem **ps, void __io if (!np) return -ENODEV; *ps = of_iomap(np, of_property_match_string(np, "reg-names", "ps")); - *pwrgate = of_iomap(np, of_property_match_string(np, "reg-names", "pwrgate")); + if (dcp_s2r_layout(dcp)->ret_ff) + *pwrgate = of_iomap(np, of_property_match_string(np, "reg-names", "pwrgate")); if (dcp_s2r_layout(dcp)->pmc_dcp) *pmc = of_iomap(np, of_property_match_string(np, "reg-names", "pmc-dcp")); of_node_put(np); - return *ps && *pwrgate && (*pmc || !dcp_s2r_layout(dcp)->pmc_dcp) ? 0 : -ENODEV; + return *ps && (*pwrgate || !dcp_s2r_layout(dcp)->ret_ff) && + (*pmc || !dcp_s2r_layout(dcp)->pmc_dcp) ? 0 : -ENODEV; } /* macOS's power-off, measured 3 of 3 on T8140. The firmware is stopped and its DARTs are off. */ @@ -8867,30 +10341,45 @@ static int dcp_s2r_domains_off(struct apple_dcp *dcp) u32 val; int ret; - dcp->s2r_domains_up = false; ret = dcp_s2r_map_power(dcp, &ps, &pwrgate, &pmc); if (ret) goto out; + /* + * The display DART goes off with these domains, and every framebuffer is mapped + * into it: an unmap while they are off, a client freeing a buffer after DPMS off, + * would reach its registers and reset the SoC. The firmware's D572 does not say + * so on every firmware (27.2 reports 1 at the stop). Dark until the domains are + * back, as for an external DCP. + */ + if (dcp->s2r_disp_dart) { + ret = apple_dart_power_dark(dcp->s2r_disp_dart, true); + if (ret) + goto out; + } + dcp->s2r_domains_up = false; if (pmc) dcp_pmc_set(dcp, pmc, false); val = readl(ps + l->disp_cpu); if (val & BIT(28)) writel(val & ~(BIT(28) | GENMASK(9, 8)), ps + l->disp_cpu); if (l->ret_ff) { - writel(3, pwrgate + l->ret_ff); - writel(0, pwrgate + l->ret_mem); + dcp_s2r_ret_write(pwrgate + l->ret_ff, l->ret_ff_mask, l->ret_ff_off, 3); + dcp_s2r_ret_write(pwrgate + l->ret_mem, l->ret_mem_mask, l->ret_mem_off, 0); } dcp_s2r_ps_lower(ps + l->disp_cpu); dcp_s2r_ps_lower(ps + l->disp_fe); - dcp_s2r_ps_lower(ps + l->disp_sys); + /* A layout without a system word has 0 there, a different domain's word. */ + if (l->disp_sys) + dcp_s2r_ps_lower(ps + l->disp_sys); ret = readl_poll_timeout(ps + l->disp_cpu, val, !FIELD_GET(GENMASK(7, 4), val), 100, 50000); if (ret) dev_err(dcp->dev, "DISP_CPU did not power off: %#x\n", val); dev_dbg(dcp->dev, "display domains off: CPU %#x FE %#x SYS %#x\n", - readl(ps + l->disp_cpu), readl(ps + l->disp_fe), readl(ps + l->disp_sys)); + readl(ps + l->disp_cpu), readl(ps + l->disp_fe), + l->disp_sys ? readl(ps + l->disp_sys) : 0); out: if (ps) iounmap(ps); @@ -8917,21 +10406,23 @@ static int dcp_s2r_domains_on(struct apple_dcp *dcp) if (ret) goto out; - val = readl(ps + l->disp_sys) & ~(GENMASK(9, 8) | GENMASK(3, 0) | BIT(28)); - writel(val | 0xf, ps + l->disp_sys); - writel(val | 0xf | BIT(28), ps + l->disp_sys); + if (l->disp_sys) { + val = readl(ps + l->disp_sys) & ~(GENMASK(9, 8) | GENMASK(3, 0) | BIT(28)); + writel(val | 0xf, ps + l->disp_sys); + writel(val | 0xf | BIT(28), ps + l->disp_sys); + } val = readl(ps + l->disp_fe) & ~(GENMASK(9, 8) | GENMASK(3, 0)); writel(val | 0xf, ps + l->disp_fe); val = readl(ps + l->disp_cpu) & ~(GENMASK(9, 8) | GENMASK(3, 0) | BIT(28)); - if (dcp_s2r_is_t8142_ext(dcp)) { - /* Retain the CPU when idle, as in the measured J813 wake sequence. */ + if (dcp->hw.s2r_ext) { + /* Retain the external CPU when idle (apple,min-state = 4). */ val = (val & ~DCP_PS_MIN) | FIELD_PREP(DCP_PS_MIN, 4); writel(val, ps + l->disp_cpu); } writel(val | 0xf, ps + l->disp_cpu); if (l->ret_ff) { - writel(0, pwrgate + l->ret_ff); - writel(1, pwrgate + l->ret_mem); + dcp_s2r_ret_write(pwrgate + l->ret_ff, l->ret_ff_mask, l->ret_ff_on, 0); + dcp_s2r_ret_write(pwrgate + l->ret_mem, l->ret_mem_mask, l->ret_mem_on, 1); } writel(val | 0xf | BIT(28), ps + l->disp_cpu); if (pmc) @@ -8966,7 +10457,7 @@ static int dcp_s2r_ext_domains_on(struct apple_dcp *dcp) u32 val; int i, ret = -ENODEV; - if (dcp_s2r_is_t8142_ext(dcp)) + if (dcp->hw.s2r_layout) return dcp_s2r_domains_on(dcp); np = of_parse_phandle(dcp->dev->of_node, "apple,display-power", 0); @@ -9037,14 +10528,27 @@ static int dcp_s2r_ext_start(struct apple_dcp *dcp, bool cycled) ret = dcp_s2r_ext_domains_on(dcp); if (ret) return ret; + /* Powered again: the invalidations held while it was dark run now. */ + if (dcp->s2r_disp_dart) { + ret = apple_dart_power_dark(dcp->s2r_disp_dart, false); + if (ret) + return ret; + } /* After the domains, whose writes it would reject, the DART protects them again. */ - apple_dart_display_streams(dcp->s2r_dcp_dart, dcp_s2r_layout(dcp)->dcp_streams, true, - false); + ret = apple_dart_display_streams(dcp->s2r_dcp_dart, dcp_s2r_layout(dcp)->dcp_streams, + true, false); + if (ret) + return ret; + /* Set up again before the firmware runs, which uses it right away. */ + if (dcp->hw.s2r_disp_dart_with_dcp && dcp->s2r_disp_dart) { + ret = apple_dart_display_streams(dcp->s2r_disp_dart, + dcp_s2r_layout(dcp)->disp_streams, true, false); + if (ret) + return ret; + } if (!cycled) return apple_rtkit_sleep_return(dcp->rtk, control); - if (dcp->s2r_disp_dart) - apple_dart_power_dark(dcp->s2r_disp_dart, false); return apple_rtkit_power_cycled_return(dcp->rtk, control); } @@ -9063,7 +10567,7 @@ static int dcp_s2r_ext_domains_off(struct apple_dcp *dcp) int i, ret = -ENODEV; u32 val; - if (dcp_s2r_is_t8142_ext(dcp)) + if (dcp->hw.s2r_layout) return dcp_s2r_domains_off(dcp); np = of_parse_phandle(dcp->dev->of_node, "apple,display-power", 0); @@ -9079,8 +10583,11 @@ static int dcp_s2r_ext_domains_off(struct apple_dcp *dcp) * Its display DART goes off with DISPEXT0, and every framebuffer is mapped into it: a * map during the hold would reach its registers. Dark until the domains are back. */ - if (dcp->s2r_disp_dart) - apple_dart_power_dark(dcp->s2r_disp_dart, true); + if (dcp->s2r_disp_dart) { + ret = apple_dart_power_dark(dcp->s2r_disp_dart, true); + if (ret) + goto out; + } dcp->s2r_domains_up = false; dcp_pmc_set(dcp, pmc, false); ret = 0; @@ -9122,7 +10629,7 @@ static bool dcp_s2r_ext_cpu_on(struct apple_dcp *dcp) of_node_put(np); if (!ps) return false; - on = FIELD_GET(GENMASK(7, 4), readl(ps + (dcp_s2r_is_t8142_ext(dcp) ? + on = FIELD_GET(GENMASK(7, 4), readl(ps + (dcp->hw.s2r_layout ? dcp_s2r_layout(dcp)->disp_cpu : 0x328))); iounmap(ps); @@ -9177,15 +10684,34 @@ static int dcp_s2r_warm_restart(struct apple_dcp *dcp) { int ret; + if (IS_ERR_OR_NULL(dcp->rtk)) + return -ENODEV; dcp_s2r_forget_crash(dcp); ret = dcp_s2r_domains_on(dcp); if (ret) return ret; + /* Powered again: the invalidations held while it was dark run now. */ + if (dcp->s2r_disp_dart) { + ret = apple_dart_power_dark(dcp->s2r_disp_dart, false); + if (ret) + return ret; + } /* After the domains, whose writes it would reject, the DART protects them again. */ - if (dcp->s2r_dcp_dart) - apple_dart_display_streams(dcp->s2r_dcp_dart, dcp_s2r_layout(dcp)->dcp_streams, - true, false); + if (dcp->s2r_dcp_dart) { + ret = apple_dart_display_streams(dcp->s2r_dcp_dart, + dcp_s2r_layout(dcp)->dcp_streams, + true, false); + if (ret) + return ret; + } + /* Set up again before the firmware runs, which uses it right away. */ + if (dcp->hw.s2r_disp_dart_with_dcp && dcp->s2r_disp_dart) { + ret = apple_dart_display_streams(dcp->s2r_disp_dart, + dcp_s2r_layout(dcp)->disp_streams, true, false); + if (ret) + return ret; + } if (dcp->secure_rtk) { dcp_secure_poll_stop(dcp); @@ -9228,6 +10754,7 @@ static int dcp_s2r_warm_restart(struct apple_dcp *dcp) */ static int dcp_s2r_display_on(struct apple_dcp *dcp) { + bool done; int ret; ret = dcp_s2r_warm_restart(dcp); @@ -9236,6 +10763,7 @@ static int dcp_s2r_display_on(struct apple_dcp *dcp) return ret; } + WRITE_ONCE(dcp->s2r_dart_err, 0); reinit_completion(&dcp->s2r_dart_done); WRITE_ONCE(dcp->s2r_active, true); @@ -9243,13 +10771,19 @@ static int dcp_s2r_display_on(struct apple_dcp *dcp) ret = dcp_s2r_power(dcp, true, true, true); if (ret) { dev_err(dcp->dev, "no reply to set_power_state(1): %d\n", ret); - goto out; + dcp_s2r_dart_end(dcp); + return ret; } - if (!wait_for_completion_timeout(&dcp->s2r_dart_done, - msecs_to_jiffies(DCP_S2R_D572_TIMEOUT_MS))) + done = wait_for_completion_timeout(&dcp->s2r_dart_done, + msecs_to_jiffies(DCP_S2R_D572_TIMEOUT_MS)); + dcp_s2r_dart_end(dcp); + if (!done && !completion_done(&dcp->s2r_dart_done)) { dev_warn(dcp->dev, "no D572 after set_power_state(1), scanout DART left off\n"); -out: - WRITE_ONCE(dcp->s2r_active, false); + return -ETIMEDOUT; + } + ret = READ_ONCE(dcp->s2r_dart_err); + if (ret) + dev_err(dcp->dev, "display DART stream on failed on D572: %d\n", ret); return ret; } @@ -9272,6 +10806,7 @@ static void dcp_s2r_restart_done(struct apple_dcp *dcp, int ret) dcp_typec_route_unpark(dcp); if (ret) { WRITE_ONCE(dcp->crashed, true); + /* Firmware stays stopped/crashed, so hdmi_hpd_irq intentionally stays disabled. */ dev_warn(dcp->dev, "firmware stopped for sleep, display stays off until reboot\n"); return; } @@ -9281,6 +10816,20 @@ static void dcp_s2r_restart_done(struct apple_dcp *dcp, int ret) iomfb_pause_presentation(dcp, false); if (ext && !READ_ONCE(dcp->typec_work_enabled)) dcp_enable_typec_work(dcp); + if (ext && !dcp_is_typec_output(dcp) && dcp->hdmi_hpd && + !READ_ONCE(dcp->active_typec_route)) { + if (dcp->external_native) { + dcp_fabric_hdmi_reinit(dcp, "after deep sleep"); + } else { + if (dcp->hdmi_pwren) + gpiod_set_value_cansleep(dcp->hdmi_pwren, 1); + if (dcp->dp2hdmi_pwren) + gpiod_set_value_cansleep(dcp->dp2hdmi_pwren, 1); + } + dcp_fixed_hdmi_reconnect(dcp, false); + } + if (ext) + dcp_s2r_hdmi_irq_enable(dcp); } /* @@ -9339,6 +10888,9 @@ static int dcp_s2r_resume(struct apple_dcp *dcp) bool real = pm_resume_via_firmware(); dcp->s2r_stopped = false; + /* No RTKit session since the suspend stopped it: nothing to start. */ + if (IS_ERR_OR_NULL(dcp->rtk)) + return 0; /* A real sleep took the domains' power. */ if (real) dcp->s2r_domains_up = false; @@ -9488,13 +11040,28 @@ static void dcp_s2r_light_running(struct apple_dcp *dcp) int ret; dcp_s2r_find_darts(dcp); + WRITE_ONCE(dcp->s2r_dart_err, 0); reinit_completion(&dcp->s2r_dart_done); WRITE_ONCE(dcp->s2r_active, true); ret = dcp_s2r_power(dcp, true, true, true); - if (!ret && !wait_for_completion_timeout(&dcp->s2r_dart_done, - msecs_to_jiffies(DCP_S2R_D572_TIMEOUT_MS))) - dev_warn(dcp->dev, "no D572 after set_power_state(1), scanout DART left off\n"); - WRITE_ONCE(dcp->s2r_active, false); + if (!ret) { + bool done = wait_for_completion_timeout(&dcp->s2r_dart_done, + msecs_to_jiffies(DCP_S2R_D572_TIMEOUT_MS)); + + dcp_s2r_dart_end(dcp); + if (!done && !completion_done(&dcp->s2r_dart_done)) { + dev_warn(dcp->dev, + "no D572 after set_power_state(1), scanout DART left off\n"); + ret = -ETIMEDOUT; + } else { + ret = READ_ONCE(dcp->s2r_dart_err); + if (ret) + dev_err(dcp->dev, "display DART stream on failed on D572: %d\n", + ret); + } + } else { + dcp_s2r_dart_end(dcp); + } dcp_s2r_put_darts(dcp); if (ret) { WRITE_ONCE(dcp->crashed, true); @@ -9572,15 +11139,18 @@ static void dcp_s2r_prewarm_work(struct work_struct *work) guard(mutex)(&dcp->s2r_prewarm_lock); light = dcp->s2r_wake_light; dcp->s2r_wake_light = false; - if (!dcp->dpms_powered_off || !READ_ONCE(dcp->s2r_fw_down) || READ_ONCE(dcp->crashed)) + if (!dcp->dpms_powered_off || !READ_ONCE(dcp->s2r_fw_down) || READ_ONCE(dcp->crashed) || + IS_ERR_OR_NULL(dcp->rtk)) return; dcp_s2r_find_darts(dcp); ret = dcp_s2r_warm_restart(dcp); if (ret) { /* Back as DPMS off left it, stopped and powered down: DPMS on starts it again. */ dcp_s2r_stop_failed_start(dcp); - dcp_s2r_stop_streams(dcp); - dcp_s2r_domains_off(dcp); + if (!dcp_s2r_stop_streams(dcp)) + dcp_s2r_domains_off(dcp); + else + WRITE_ONCE(dcp->crashed, true); dcp_s2r_put_darts(dcp); dev_warn(dcp->dev, "wake: firmware start failed, DPMS on tries again: %d\n", ret); return; @@ -9647,11 +11217,25 @@ static void dcp_dpms_power_off(struct apple_dcp *dcp) __dcp_dpms_power_off(dcp); } +/* + * Internal 26.6 DCP firmware stops cold when firmware-driven deep sleep will + * cut display power, because there is no cold-restart path for it yet. In a + * sleep dry run the coprocessor is left running and takes the ordinary suspend + * path instead. + */ +static bool dcp_sleep_owned(struct apple_dcp *dcp) +{ + return IS_ENABLED(CONFIG_APPLE_SOC_SLEEP) && dcp->fw_compat == DCP_FIRMWARE_V_26_6 && + !dcp->external && apple_sleep_commit_stops_coprocs() && !apple_sleep_dry_run(); +} + bool dcp_s2r_firmware_stopped(struct platform_device *pdev) { struct apple_dcp *dcp = platform_get_drvdata(pdev); - return READ_ONCE(dcp->s2r_fw_down); + /* Whichever of this and the display subsystem suspends first: nothing commits to it. */ + return READ_ONCE(dcp->s2r_fw_down) || READ_ONCE(dcp->sleep_cold_stopped) || + (pm_suspend_via_firmware() && dcp_sleep_owned(dcp)); } #include "dcp-v27-sleep.inc" @@ -9717,13 +11301,43 @@ static void dcp_t8132_sleep_stopped(struct apple_dcp *dcp) WRITE_ONCE(dcp->t8132_release_late, false); } +/** + * dcp_sleep_keeps_firmware - whether a DCP's firmware runs through this sleep + * @dev: the DCP device + * + * For blocks the DCP's firmware drives (DP audio), from their late suspend, + * after every device's .suspend. It takes the DCP's device lock, which can + * sleep, so it is not for the noirq phase. True when the DCP's suspend left + * its coprocessor running with its domains on, or when no driver is bound + * (a boot stage or an earlier bind may have left the firmware running). + * False when the suspend stopped the firmware (S2R, the 27.x sleep, an M4 + * stop or power gate) or never ran it. + */ +bool dcp_sleep_keeps_firmware(struct device *dev) +{ + struct apple_dcp *dcp; + bool runs; + + device_lock(dev); + dcp = dev->driver ? dev_get_drvdata(dev) : NULL; + runs = !dev->driver || (dcp && dcp->sleep_fw_runs); + device_unlock(dev); + + return runs; +} +EXPORT_SYMBOL_GPL(dcp_sleep_keeps_firmware); + static int dcp_platform_suspend(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); + dcp->sleep_fw_runs = false; /* Its power sequences may crash the DCP and blank the panel. */ if (dcp_takeover_was_aborted(dcp)) return -EBUSY; + /* The iBoot interface's display stays powered across system sleep. */ + if (dcp_is_iboot(dcp)) + return 0; /* * An external DCP given up at probe may never have set up the works @@ -9740,13 +11354,37 @@ static int dcp_platform_suspend(struct device *dev) if (pm_suspend_via_firmware() && dcp_v27_sleep_selected(dcp)) return dcp_v27_sleep_suspend(dcp); + if (READ_ONCE(dcp->sleep_cold_stopped)) + return 0; + if (pm_suspend_via_firmware() && dcp_sleep_owned(dcp)) { + u32 control = readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); + struct apple_rtkit *rtk = dcp->rtk ?: dcp_v26_rtkit(dcp); + + dev_warn(dev, "display coprocessor stopped cold for sleep (control %#x); panel stays off until reboot\n", + control); + WRITE_ONCE(dcp->quiescing, true); + /* + * Run the 26.6 firmware's panel-off and sleep-entry calls, then + * request RTKit AP and IOP idle before halting the coprocessor. + */ + dcp_v26_sleep_calls(dcp, 2); + if (!IS_ERR_OR_NULL(rtk)) { + int ret = apple_rtkit_idle_with(rtk, dcp_secure_port_idle, dcp); + + if (ret) + dev_warn(dev, "RTKit idle before cold stop failed: %d\n", ret); + } + WRITE_ONCE(dcp->sleep_cold_stopped, true); + dcp_s2r_cpu_stop(dcp); + return 0; + } + /* - * J813 uses the same qualified stop as DPMS off. Probe already gates - * its derived power layout on appledrm.s2r_untested; without this - * system-suspend path an active panel leaves the DCP running. + * The same stop as DPMS off; without this system-suspend path an active + * panel leaves the DCP running. Probe already gates a derived power + * layout (T8142) on appledrm.s2r_untested. */ - if (pm_suspend_via_firmware() && dcp_s2r_capable(dcp) && - (!dcp->hw.s2r_untested || of_machine_is_compatible("apple,j813"))) { + if (pm_suspend_via_firmware() && dcp_s2r_capable(dcp)) { int ret = dcp_s2r_suspend(dcp); /* Lit by the last resume with its CRTC off: the next resume finds it off by DPMS. */ @@ -9776,7 +11414,10 @@ static int dcp_platform_suspend(struct device *dev) return ret; } dcp_t8132_sleep_stopped(dcp); + dcp->sleep_fw_runs = !iomfb_m4_sleep_stopped(dcp); device_set_wakeup_path(dev); + if (dcp->sleep_fw_runs) + dcp_sleep_hold_phys(dcp); return 0; } if (dcp_is_ext26(dcp) && pm_suspend_target_state != PM_SUSPEND_TO_IDLE) { @@ -9831,7 +11472,9 @@ static int dcp_platform_suspend(struct device *dev) /* Pair with the H17P unpark; native26 has its own retained resume. */ if (dcp_is_external_h17p(dcp)) dcp_typec_route_park(dcp); + dcp->sleep_fw_runs = true; device_set_wakeup_path(dev); + dcp_sleep_hold_phys(dcp); if (dcp_is_ext26(dcp)) dev_dbg(dev, "native26 retained s2idle stop; firmware and supplier leases held\n"); return 0; @@ -9854,7 +11497,21 @@ static int dcp_platform_suspend(struct device *dev) if (dcp->hdmi_hpd_irq) { disable_irq(dcp->hdmi_hpd_irq); - if (!dcp->active_typec_route) { + /* + * The firmware runs through this sleep, so the HDMI output + * keeps its link as through DPMS off (see dcp_poweroff()), and + * resume lights it again through dcp_poweron(). Only a display + * that is gone is reported and released here. Releasing one + * that stays attached reports it unplugged, and nothing + * connects it again after the wake: its HPD stays high, so no + * edge comes, and a CRTC userspace turned off for the unplug + * never runs dcp_poweron(). A T6030 native output's resume sets + * its PHY and crossbar up again (dcp_fabric_hdmi_reinit()), + * which needs the link down, so it is still released. + */ + if (!dcp->active_typec_route && + (dcp->external_native || + gpiod_get_value_cansleep(dcp->hdmi_hpd) <= 0)) { disconnected_hpd_event(dcp->connector); dcp_dptx_disconnect(dcp, 0); } @@ -9864,23 +11521,38 @@ static int dcp_platform_suspend(struct device *dev) * domains to stay on. We need this as we do not support full * shutdown properly yet. */ + dcp->sleep_fw_runs = true; device_set_wakeup_path(dev); + dcp_sleep_hold_phys(dcp); /* Last: the steps above still talk to the coprocessor. */ dcp_hold_for_sleep(dcp); return 0; } +void dcp_hdmi_disconnect(struct apple_dcp *dcp) +{ + disconnected_hpd_event(dcp->connector); + dcp_dptx_disconnect(dcp, 0); +} + static int dcp_platform_resume(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); + dcp->sleep_fw_runs = false; if (dcp_takeover_was_aborted(dcp)) return 0; + if (dcp_is_iboot(dcp)) + return 0; if (dcp_v27_sleep_selected(dcp) && READ_ONCE(dcp->sleep_v27_closed)) return dcp_v27_sleep_resume(dcp); + /* Stopped cold, with no restart path until reboot. */ + if (READ_ONCE(dcp->sleep_cold_stopped)) + return 0; + if (dcp->s2r_stopped) return dcp_s2r_resume(dcp); @@ -9916,6 +11588,9 @@ static int dcp_platform_resume(struct device *dev) /* The HDMI output's PHY and crossbar may have lost their setup in sleep. */ if (dcp->external_native) dcp_fabric_hdmi_reinit(dcp, "after system sleep"); + /* Before the HPD IRQ comes back: an edge from now on is replayed. */ + if (dcp->hdmi_hpd_irq) + dcp_hdmi_unplugged_in_sleep(dcp); /* Observe future edges before sampling any edges lost in sleep. */ if (dcp->hdmi_hpd_irq) dcp_fabric_run_resume(&dcp_resume_ops, dcp); @@ -10010,20 +11685,43 @@ static const struct apple_dcp_hw_data apple_dcp_hw_t8142 = { .s2r_layout = &dcp_s2r_t8142, }; +/* T8103's DCP: the firmware stop around DPMS off and system sleep, with its own power words */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8103 = { + .num_dptx_ports = 0, + .s2r = true, + .s2r_no_secure_port = true, + .s2r_layout = &dcp_s2r_t8103, + .map_reg_dart = true, + .s2r_disp_dart_with_dcp = true, +}; + +/* T8103's external DCP: maps register windows through its DART and stops/restarts across S2R */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8103_dcpext = { + .num_dptx_ports = 2, + .s2r_ext = true, + .s2r_no_secure_port = true, + .s2r_layout = &dcp_s2r_t8103_ext, + .map_reg_dart = true, + .s2r_disp_dart_with_dcp = true, +}; + static const struct apple_dcp_hw_data apple_dcp_hw_dcp = { .num_dptx_ports = 0, }; static const struct apple_dcp_hw_data apple_dcp_hw_t6030 = { + .iboot_handoff = "apple,t6030-handoff", .num_dptx_ports = 1, }; static const struct apple_dcp_hw_data apple_dcp_hw_t8122 = { + .iboot_handoff = "apple,t8122-handoff", .num_dptx_ports = 2, }; /* The internal panel only, through the 14.x IOMFB, as on T6030. */ static const struct apple_dcp_hw_data apple_dcp_hw_t6031 = { + .iboot_handoff = "apple,t6031-handoff", .num_dptx_ports = 1, }; @@ -10056,6 +11754,7 @@ static const struct apple_dcp_hw_data apple_dcp_hw_t8132_dcpext = { /* T6041 (M4 Pro/Max), desktop 26.6 firmware */ static const struct apple_dcp_hw_data apple_dcp_hw_t6041 = { + .iboot_handoff = "apple,t6041-handoff", .num_dptx_ports = 2, }; @@ -10109,25 +11808,52 @@ static const struct apple_dcp_hw_data apple_dcp_hw_t8142_dcpext = { .dptx_controller = true, /* TEST: firmware 27.2 link release, gated by appledrm.s2r_untested. */ .s2r_ext = true, + .s2r_untested = true, .s2r_no_secure_port = true, .s2r_layout = &dcp_s2r_t8142_ext[0], }; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8152) +/* + * T8152 (J873g): the DCP and both DCPEXTs, driven through the firmware's + * iBoot interface (disp0-service, dispext-service) over AFKv2, with the + * DPAV controller and DPTX port endpoints opened as the firmware expects + * them. The bootloader leaves each session running or quiesced; a running + * one is taken without the RTKit handshake. + */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8152_iboot = { + .num_dptx_ports = 2, + .firmware_compat = DCP_FIRMWARE_IBOOT, + .afk_v2 = true, + .afk_adopt_endpoints = true, + .afk_announced_names = true, + .afk_timeout_ms = 3000, +}; +#endif + static const struct of_device_id of_match[] = { { .compatible = "apple,t8142-dcpext", .data = &apple_dcp_hw_t8142_dcpext }, +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8152) + { .compatible = "apple,t8152-dcp-iboot", .data = &apple_dcp_hw_t8152_iboot }, +#endif { .compatible = "apple,t6041-dcp", .data = &apple_dcp_hw_t6041, }, { .compatible = "apple,t6041-dcpext", .data = &apple_dcp_hw_t6041_dcpext, }, { .compatible = "apple,t6050-dcp", .data = &apple_dcp_hw_t6050 }, { .compatible = "apple,t6050-dcpext", .data = &apple_dcp_hw_t6050_dcpext }, { .compatible = "apple,t6020-dcp", .data = &apple_dcp_hw_t6020, }, { .compatible = "apple,t6020-dcpext", .data = &apple_dcp_hw_t6020_dcpext, }, + { .compatible = "apple,t8103-dcp", .data = &apple_dcp_hw_t8103, }, + { .compatible = "apple,t8103-dcpext", .data = &apple_dcp_hw_t8103_dcpext, }, { .compatible = "apple,t8112-dcp", .data = &apple_dcp_hw_t8112, }, { .compatible = "apple,t8140-dcp", .data = &apple_dcp_hw_t8140, }, { .compatible = "apple,t8140-dcpext", .data = &apple_dcp_hw_t8140_external, }, { .compatible = "apple,t8142-dcp", .data = &apple_dcp_hw_t8142, }, #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8132) { .compatible = "apple,t8132-dcp", .data = &apple_dcp_hw_t8132, }, - /* Same firmware as the internal DCP; adopted from the boot loader. */ + /* + * Same firmware as the internal DCP; adopted from the boot loader. The + * J773g's on 27.2 is a firmware-27 pipe (apple_dcp_hw_t8132_dcpext_v27). + */ { .compatible = "apple,t8132-dcpext", .data = &apple_dcp_hw_t8132_dcpext, }, #endif { .compatible = "apple,t6030-dcp", .data = &apple_dcp_hw_t6030, }, @@ -10154,6 +11880,845 @@ static struct platform_driver apple_platform_driver = { }, }; +/* + * T6041 suspend-to-RAM: each display firmware is stopped from Linux before the sleep, from the + * display subsystem's own suspend, and the internal one is restarted warm after the wake. + */ +static int dcp_stop_poller(void *data) +{ + while (!kthread_should_stop()) { + apple_rtkit_poll(data); + usleep_range(500, 1000); + } + return 0; +} + +static int dcp_t6041_recommit(struct apple_dcp *dcp); + +static int dcp_t6041_stop_one(struct device *dev, void *data) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + bool external = *(bool *)data; + struct task_struct *poller; + bool keep_set = false; + bool powered_off = false; + /* The display DART's streams turned off here, not by a D572(0). */ + bool streams_off = false; + bool idle_attempted = false; + bool idle; + u32 ctrl, status; + int ret; + + /* dcp->external is only set on T6030. */ + if (!dcp || IS_ERR_OR_NULL(dcp->rtk) || dcp->sleep_host_stop == external) + return 0; + /* + * An external DCP stopped for an earlier sleep stays down, with its domains forced off by + * the power word step: reading its registers again hung the second sleep of a boot (11 Nov). + */ + if (external && dcp->t6041_ext_seen) + return 0; + if (!apple_rtkit_is_running(dcp->rtk)) { + ret = 0; + if (external) { + if (dcp->coproc_reg && + (readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) & + APPLE_DCP_COPROC_CPU_CONTROL_RUN)) { + dcp_s2r_cpu_stop(dcp); + ret = readl_poll_timeout(dcp->coproc_reg + + APPLE_DCP_COPROC_CPU_CONTROL, + ctrl, + !(ctrl & APPLE_DCP_COPROC_CPU_CONTROL_RUN), + 100, 10000); + if (ret) { + dev_err(dev, + "coprocessor RUN bit did not clear: control %#x\n", + ctrl); + return ret; + } + } + dcp_s2r_find_darts(dcp); + if (dcp->s2r_disp_dart) + ret = apple_dart_display_streams(dcp->s2r_disp_dart, + DCP_S2R_DISP_STREAMS, + false, true); + if (!ret && dcp->s2r_dcp_dart) + ret = dcp_s2r_stop_streams(dcp); + if (!ret) + dcp->t6041_ext_seen = true; + } + dcp_s2r_put_darts(dcp); + return ret; + } + dcp_drain_for_sleep(dcp); + cancel_delayed_work_sync(&dcp->swap_watchdog_wq); + iomfb_pause_presentation(dcp, true); + iomfb_queue_settle(dcp, msecs_to_jiffies(500)); + dcp_s2r_find_darts(dcp); + if (!external) { + if (dcp->s2r_disp_dart) + apple_dart_display_keep(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, true); + if (dcp->s2r_dcp_dart) + apple_dart_display_keep(dcp->s2r_dcp_dart, DCP_S2R_DCP_STREAMS, true); + keep_set = true; + /* + * As linux#1477 dcp_t6041_s2r_stop: the pipe off through the firmware, then wait for + * its calls to settle. No av_service_disconnect: the firmware answered it with an + * unplug (HPD removed), and after the warm restart it refused every mode set with + * "HPD is 0 link_status is 0" (10 Nov). No display sleep transition after the + * power-off either. + */ + /* + * The firmware's D572(0) after the power-off says it is done with the display, and + * dcp_s2r_dart_power() turns the display DART's streams off right there, as macOS + * does. Turned off while the pipe still scanned out, they crashed the firmware + * (axi_rd_err, 11 Nov). Without D572(0) abort sleep instead of tearing down domains + * while scanning out. + */ + /* + * A DPMS off before the sleep (the desktop blanking on a lid close) already ran + * set_power_state(0), and its scanout stop was confirmed: its D572(0) came then, + * while s2r_active was clear, and a second set_power_state(0) gets none. Turn the + * display DART's streams off as that D572(0) would have; the pipe no longer scans + * out. + */ + if (READ_ONCE(dcp->pipe_off)) { + dev_info(dev, "display already off: no second power-off\n"); + if (dcp->s2r_disp_dart) { + streams_off = true; + ret = apple_dart_display_streams(dcp->s2r_disp_dart, + DCP_S2R_DISP_STREAMS, + false, false); + if (ret) + goto err_unwind; + } + } else { + unsigned long d572 = msecs_to_jiffies(DCP_S2R_D572_TIMEOUT_MS); + + WRITE_ONCE(dcp->s2r_dart_err, 0); + reinit_completion(&dcp->s2r_dart_done); + WRITE_ONCE(dcp->s2r_active, true); + _dcp_poweroff(dcp); + powered_off = true; + if (!wait_for_completion_timeout(&dcp->s2r_dart_done, d572)) { + dcp_s2r_dart_end(dcp); + dev_err(dev, "no D572 after the power-off\n"); + ret = -ETIMEDOUT; + goto err_unwind; + } + dcp_s2r_dart_end(dcp); + ret = READ_ONCE(dcp->s2r_dart_err); + if (ret) { + dev_err(dev, "display DART stream off failed on D572: %d\n", ret); + goto err_unwind; + } + } + if (read_poll_timeout(iomfb_channels_idle, idle, idle, 1000, 200000, false, dcp)) { + dev_err(dev, "display calls still in flight after the power-off\n"); + ret = -ETIMEDOUT; + goto err_unwind; + } + } + ret = iomfb_s2r_500_v26_6_desktop(dcp); + if (ret) { + dev_err(dev, "no reply to A500: %d\n", ret); + goto err_unwind; + } + if (read_poll_timeout(iomfb_channels_idle, idle, idle, 1000, 100000, false, dcp)) { + dev_err(dev, "display calls still in flight after A500\n"); + ret = -ETIMEDOUT; + goto err_unwind; + } + idle_attempted = true; + ret = apple_rtkit_idle(dcp->rtk); + if (ret) { + poller = kthread_run(dcp_stop_poller, dcp->rtk, "dcpstop"); + ret = apple_rtkit_idle(dcp->rtk); + if (!IS_ERR(poller)) + kthread_stop(poller); + } + if (ret) { + dev_err(dev, "the firmware didn't go idle for the sleep: %d\n", ret); + goto err_unwind; + } + apple_rtkit_poll(dcp->rtk); + /* + * T6041 desktop firmware reaches status 0x6d (IDLE set, STOPPED clear) on + * apple_rtkit_idle(). Both AP and IOP have already acknowledged IDLE here, + * so proceed even if IDLE is late, matching apple_rtkit_sleep_idle(). + */ + ret = readl_poll_timeout(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_STATUS, status, + status & APPLE_DCP_COPROC_CPU_STATUS_IDLE, 100, 50000); + if (ret) + dev_warn(dev, "coprocessor did not set IDLE after RTKit idle: status %#x\n", + status); + /* + * QUIESCED and SLEEP after idle: T23 reached STOPPED (0x6e) only this way. Not for the + * internal DCP: linux#1477 stops it at the idle (A500, idle, mailbox off, run bit, bit 5) + * and its warm restart then works; after a shutdown ours crashed in the restart (10 Nov, + * data abort at 0xffffffff00000040 right after the first shmem_setup). + */ + if (external) { + ret = apple_rtkit_shutdown(dcp->rtk); + if (ret) + dev_warn(dev, "external coprocessor shutdown failed: %d\n", ret); + if (readl_poll_timeout(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_STATUS, status, + (status & (APPLE_DCP_COPROC_CPU_STATUS_IDLE | + APPLE_DCP_COPROC_CPU_STATUS_STOPPED)) == + (APPLE_DCP_COPROC_CPU_STATUS_IDLE | + APPLE_DCP_COPROC_CPU_STATUS_STOPPED), 100, 50000)) + dev_warn(dev, "external coprocessor did not reach stopped: status %#x\n", + status); + } + WRITE_ONCE(dcp->crashed, true); + WRITE_ONCE(dcp->ext_dead, true); + WRITE_ONCE(dcp->s2r_fw_down, true); + apple_rtkit_mailbox_off(dcp->rtk); + dcp_s2r_cpu_stop(dcp); + ret = readl_poll_timeout(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL, ctrl, + !(ctrl & APPLE_DCP_COPROC_CPU_CONTROL_RUN), 100, 10000); + if (ret) { + dev_err(dev, "coprocessor RUN bit did not clear: control %#x\n", ctrl); + dcp_s2r_put_darts(dcp); + return ret; + } + /* + * External display DARTs go dark for good while their block is still on: + * the power word step forces the external display domains off and nothing raises + * them, but the framebuffers are mapped through all display DARTs, so every + * later unmap would flush a DART behind a dead block (11 Nov). + * Marked dark, the flush only publishes to memory. + */ + ret = 0; + if (external && dcp->s2r_disp_dart) + ret = apple_dart_display_streams(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, + false, true); + if (!ret) + ret = dcp_s2r_stop_streams(dcp); + dcp_s2r_put_darts(dcp); + if (ret) { + dev_err(dev, "failed to stop DCP DART streams: %d\n", ret); + return ret; + } + if (external) + dcp->t6041_ext_seen = true; + + return 0; + +err_unwind: + { + int dart_ret = 0; + + if (!external) { + if (keep_set) { + if (dcp->s2r_disp_dart) + apple_dart_display_keep(dcp->s2r_disp_dart, + DCP_S2R_DISP_STREAMS, false); + if (dcp->s2r_dcp_dart) + apple_dart_display_keep(dcp->s2r_dcp_dart, + DCP_S2R_DCP_STREAMS, false); + } + if ((powered_off || streams_off) && dcp->s2r_disp_dart) + dart_ret = apple_dart_display_streams(dcp->s2r_disp_dart, + DCP_S2R_DISP_STREAMS, + true, false); + } + dcp_s2r_put_darts(dcp); + if (dart_ret) { + dev_err(dev, "display DART restore after failed stop failed: %d\n", + dart_ret); + WRITE_ONCE(dcp->crashed, true); + return ret; + } + } + iomfb_pause_presentation(dcp, false); + if (idle_attempted) { + int ap_ret = apple_rtkit_ap_power(dcp->rtk, true); + + if (ap_ret) + dev_warn(dev, "AP on after failed stop: %d\n", ap_ret); + } + if (!external && powered_off) { + if (dcp_t6041_recommit(dcp)) + dev_err(dev, "display recovery after failed stop failed\n"); + else + dcp_backlight_s2r_restore(dcp); + } + return ret; +} + +/* + * The power words of each display CPU down, after its firmware stopped. The fabric rejects + * writes to a DCP's CPU word until bit 4 of its GAPF slice is clear: ADT + * clock-protection-slice-index, 0x100 + 0x40 * index. Then macOS's order on the Neo. + */ +static int dcp_t6041_word_try(struct device *dev, struct dcp_t6041_power *pwr, + struct dcp_t6041_chain *chain) +{ + void __iomem *gapf = chain->gapf; + void __iomem *rsys = chain->domains[0]; + void __iomem *rfe = chain->domains[1]; + void __iomem *rcpu = chain->domains[2]; + void __iomem *ra = chain->pg_a; + void __iomem *rb = chain->pg_b; + void __iomem *rfab = NULL; + unsigned int i; + u32 val, fab = 0, cur; + int ret = 0; + + val = readl(gapf); + writel(val & ~BIT(4), gapf); + if (readl_poll_timeout(gapf, cur, !(cur & BIT(4)), 10, 5000)) { + dev_err(dev, "dcp %s: GAPF write protection stayed set: %#x\n", + chain->name, cur); + return -ETIMEDOUT; + } + val = readl(rcpu); + writel(val & ~(BIT(28) | GENMASK(9, 8)), rcpu); + if (readl_poll_timeout(rcpu, cur, !(cur & BIT(28)), 10, 5000)) { + dev_err(dev, "dcp %s: CPU auto-enable did not clear: %#x\n", + chain->name, cur); + return -ETIMEDOUT; + } + val = cur; + /* + * Everything macOS's sleep check wants off under this CPU, last first: DSC, PPP, GPL, + * GP1, GP0, DPEXT, DBE. iBoot leaves them on over a DCP Linux never started. + */ + if (chain->is_main && chain->child_saved) { + for (i = 3; i < chain->num_domains; i++) + chain->child_saved[i - 3] = readl(chain->domains[i]); + pwr->child_valid = true; + } + for (i = chain->num_domains; i-- > 3; ) { + void __iomem *sub = chain->domains[i]; + + val = readl(sub); + if (val & BIT(28)) { + val &= ~(BIT(28) | GENMASK(9, 8)); + writel(val, sub); + } + writel((val & ~GENMASK(3, 0)) | GENMASK(9, 8), sub); + if (readl_poll_timeout(sub, cur, !FIELD_GET(GENMASK(7, 4), cur), + 50, 20000)) { + dev_err(dev, "dcp %s: child %u did not power off: %#x\n", + chain->name, i - 2, cur); + return -ETIMEDOUT; + } + } + val = readl(rcpu); + /* + * Two things the restart sets that boot did not have, undone before the lowering: bit 0 of + * both words of bridge 4 (boot 0x10000 / 0x101330, after a restart 0x10001 / 0x101331) and the + * display voter count at pmc-dcp (boot 0, after a restart 1). With them left, the + * second lowering of a boot ends with FE 0x200 and SYS 0x800 (bit 11) instead of 0x300 / 0x300. + */ + if (chain->is_main) { + writel(readl(pwr->axi2af + 0x4) & ~1U, pwr->axi2af + 0x4); + writel(readl(pwr->axi2af + 0x8) & ~1U, pwr->axi2af + 0x8); + writel(0, pwr->pmc_dcp); + } + if (chain->fabric) { + /* + * The internal display's SYS hangs off fab6_soc, which gates itself as soon as + * nothing under it is on. Lowered while the fabric is already going (second stop + * of a boot, the external pipes long off), SYS latches PARENT_OFF (reads 0x800, + * FE 0x200), the sleep engine waits on that bit and the chip resets. So: the + * fabric on by hand until SYS is down. + */ + rfab = chain->fabric; + fab = readl(rfab); + writel((fab & ~(BIT(28) | GENMASK(9, 8) | GENMASK(3, 0))) | 0xf, rfab); + if (readl_poll_timeout(rfab, cur, FIELD_GET(GENMASK(7, 4), cur) == 0xf, + 50, 20000)) { + dev_err(dev, "dcp %s: fabric domain not on: %#x\n", chain->name, cur); + ret = -ETIMEDOUT; + goto restore_fab; + } + } + writel(3, ra); + writel(0, rb); + writel((val & ~GENMASK(3, 0)) | GENMASK(9, 8), rcpu); + val = readl(rfe); + if (val & BIT(28)) + writel(val & ~(BIT(28) | GENMASK(9, 8)), rfe); + writel((readl(rfe) & ~GENMASK(3, 0)) | GENMASK(9, 8), rfe); + val = readl(rsys); + if (val & BIT(28)) + writel(val & ~(BIT(28) | GENMASK(9, 8)), rsys); + writel((readl(rsys) & ~GENMASK(3, 0)) | GENMASK(9, 8), rsys); + /* + * Verify CPU, FE and SYS all reach off; macOS polls up to 50 ms here. The internal + * chain must also not have latched PARENT_OFF (bit 11), see above. + */ + if (readl_poll_timeout(rcpu, cur, + !FIELD_GET(GENMASK(7, 4), cur) && + (!chain->is_main || !(cur & BIT(11))), + 50, 100000)) { + dev_err(dev, "dcp %s: cpu still %#x\n", chain->name, cur); + ret = -ETIMEDOUT; + goto restore_fab; + } + if (readl_poll_timeout(rfe, cur, + !FIELD_GET(GENMASK(7, 4), cur) && + (!chain->is_main || !(cur & BIT(11))), + 50, 100000)) { + dev_err(dev, "dcp %s: fe still %#x\n", chain->name, cur); + ret = -ETIMEDOUT; + goto restore_fab; + } + if (readl_poll_timeout(rsys, cur, + !FIELD_GET(GENMASK(7, 4), cur) && + (!chain->is_main || !(cur & BIT(11))), + 50, 100000)) { + dev_err(dev, "dcp %s: sys still %#x\n", chain->name, cur); + ret = -ETIMEDOUT; + goto restore_fab; + } +restore_fab: + if (rfab) { + /* Back to automatic, as it was; the flag bits are write-one-to-clear, left alone. */ + writel((readl(rfab) & ~(GENMASK(9, 8) | BIT(28))) | (fab & BIT(28)), rfab); + if (readl_poll_timeout(rfab, cur, (cur & BIT(28)) == (fab & BIT(28)), 10, 5000)) { + dev_err(dev, "dcp %s: fabric auto-enable did not restore: %#x\n", + chain->name, cur); + if (!ret) + ret = -ETIMEDOUT; + } + } + + return ret; +} + +/* + * After a real wake: the internal DCP back, as linux#1477 does it for the M4 Pro + * (t6040_disp_back, dcp_t6041_s2r_domains_on, dcp_t6041_s2r_resume, the warm restart and the + * mode set of dcp_hib_recommit): DISP_SYS on, the retention pair (A := 0, B := 1), DISP_FE on, + * the GAPF protection off, DISP_CPU on, its child domains as the stop found them, the PMC voter, + * both DARTs' streams, the idled firmware restarted, the pipe powered and the mode set again. + */ +static int dcp_t6041_recommit(struct apple_dcp *dcp) +{ + struct apple_crtc *acrtc = READ_ONCE(dcp->crtc); + struct drm_modeset_acquire_ctx ctx; + struct drm_atomic_commit *state; + struct drm_crtc_state *cs; + struct drm_crtc *crtc; + ktime_t start = ktime_get(); + bool idle; + int ret; + + reinit_completion(&dcp->s2r_hpd_done); + iomfb_poweron_v26_6_desktop(dcp); + if (dcp->desktop && dcp->desktop->poweron_result) { + dev_err(dcp->dev, "display power-on after the sleep failed (%u)\n", + dcp->desktop->poweron_result); + return dcp->desktop->poweron_result == 1 ? -ETIMEDOUT : -EIO; + } + if (!wait_for_completion_timeout(&dcp->s2r_hpd_done, msecs_to_jiffies(1000))) { + dev_err(dcp->dev, "no D575 hotplug %lld ms after power-on\n", + ktime_ms_delta(ktime_get(), start)); + return -ETIMEDOUT; + } + dev_dbg(dcp->dev, "D575 hotplug ready %lld ms after power-on\n", + ktime_ms_delta(ktime_get(), start)); + if (read_poll_timeout(iomfb_channels_idle, idle, idle, 1000, 200000, false, dcp)) { + dev_err(dcp->dev, "display calls still in flight after D575\n"); + return -ETIMEDOUT; + } + if (!acrtc) + return 0; + crtc = &acrtc->base; + DRM_MODESET_LOCK_ALL_BEGIN(crtc->dev, ctx, 0, ret); + if (!crtc->state->active) { + ret = 0; + goto unlock; + } + state = drm_atomic_commit_alloc(crtc->dev); + if (!state) { + ret = -ENOMEM; + goto unlock; + } + state->acquire_ctx = &ctx; + cs = drm_atomic_get_crtc_state(state, crtc); + if (IS_ERR(cs)) { + ret = PTR_ERR(cs); + goto put; + } + cs->mode_changed = true; + ret = drm_atomic_add_affected_connectors(state, crtc); + if (!ret) + ret = drm_atomic_add_affected_planes(state, crtc); + if (!ret) + ret = drm_atomic_commit(state); +put: + drm_atomic_commit_put(state); +unlock: + DRM_MODESET_LOCK_ALL_END(crtc->dev, ctx, ret); + return ret; +} + +/* + * The internal display's SYS, FE and CPU power words as they were before the first stop (from + * boot: SYS and FE with no flags, the CPU word 0x1000030f, automatic). The restart leaves the CPU + * word manual (0x0f0003ff) and SYS/FE with both flags, and the first display power-off after such + * a wake hung the machine (11 Nov, run 6). Captured once and put back once the display runs again. + */ +static int dcp_t6041_boot_ps_io(struct apple_dcp *dcp, bool restore) +{ + static const char *const names[3] = { "sys", "fe", "cpu" }; + struct dcp_t6041_power *pwr = &dcp->t6041_power; + const struct dcp_t6041_chain *main = pwr->main_chain; + bool idle; + u32 cur; + int i; + + if (!main || main->num_domains < 3) + return -EINVAL; + + if (!restore) { + if (pwr->boot_ps_valid) + return 0; + for (i = 0; i < 3; i++) + pwr->boot_ps[i] = readl(main->domains[i]); + pwr->boot_ps_valid = true; + return 0; + } + + if (!pwr->boot_ps_valid) + return 0; + + if (read_poll_timeout(iomfb_channels_idle, idle, idle, 1000, 200000, false, dcp)) { + dev_err(dcp->dev, "display calls still in flight before restoring boot power words\n"); + return -ETIMEDOUT; + } + for (i = 0; i < 3; i++) { + if (!pwr->boot_ps[i]) + continue; + if (readl_poll_timeout(main->domains[i], cur, + FIELD_GET(GENMASK(7, 4), cur) == 0xf && !(cur & BIT(11)), + 50, 10000)) { + dev_err(dcp->dev, "display %s power word not on before restore: %#x\n", + names[i], cur); + return -ETIMEDOUT; + } + } + for (i = 0; i < 3; i++) { + u32 want = pwr->boot_ps[i] & ~0xf0U; + + if (!pwr->boot_ps[i]) + continue; + writel(want, main->domains[i]); + if (want & BIT(28)) { + /* + * AUTO_ENABLE lets hardware drop PS_ACTUAL to 0 while the DCP CPU sits + * idle in WFI, so poll target + AUTO_ENABLE + !PARENT_OFF instead. + */ + if (readl_poll_timeout(main->domains[i], cur, + (cur & (BIT(28) | GENMASK(3, 0))) == + (want & (BIT(28) | GENMASK(3, 0))) && + !(cur & BIT(11)), 50, 10000)) { + dev_err(dcp->dev, + "display %s power word did not restore auto-enable: %#x\n", + names[i], cur); + return -ETIMEDOUT; + } + } else { + if (readl_poll_timeout(main->domains[i], cur, + FIELD_GET(GENMASK(7, 4), cur) == 0xf && + !(cur & BIT(11)), 50, 10000)) { + dev_err(dcp->dev, + "display %s power word did not stay on after restore: %#x\n", + names[i], cur); + return -ETIMEDOUT; + } + } + } + + return 0; +} + +static int dcp_t6041_start_one(struct device *dev, void *data) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + struct dcp_t6041_power *pwr; + const struct dcp_t6041_chain *main; + void __iomem *rsys, *rfe, *rcpu, *gapf, *pmc; + unsigned int i; + u32 v, cur, to = 0; + int ret, ps_ret; + + if (!dcp || IS_ERR_OR_NULL(dcp->rtk) || !dcp->sleep_host_stop) + return 0; + pwr = &dcp->t6041_power; + main = pwr->main_chain; + if (!main || main->num_domains < 3) + return -EINVAL; + rsys = main->domains[0]; + rfe = main->domains[1]; + rcpu = main->domains[2]; + gapf = main->gapf; + pmc = pwr->pmc_dcp; + + v = readl(rsys) & ~(GENMASK(9, 8) | GENMASK(3, 0) | BIT(28)); + /* + * As macOS's wake writes them: target on with both flag bits clear (0xf). Raised with the + * flags kept (0x30f) the word reads 0x3ff, a later write can't clear them, and the next + * lowering then latches bit 11 on SYS (0x800) and leaves FE at 0x200: the sleep engine waits + * on that bit and the chip resets (second sleep of a boot, 11 Nov). + */ + writel((v & ~0x30fU) | 0xf, rsys); + if (readl_poll_timeout(rsys, cur, + FIELD_GET(GENMASK(7, 4), cur) == 0xf && !(cur & BIT(11)), + 50, 10000)) + to |= BIT(0); + writel(0, main->pg_a); + writel(1, main->pg_b); + /* + * Bridge 4 stays as boot has it (bit 0 of both words clear, 0x10000 / 0x101330), unlike + * macOS's wake: with it set, the driver's own display power-off after a wake froze the whole + * machine right after "dcp_poweroff() done" (login after a wake, sddm restart; 11 Nov). + */ + v = readl(rfe) & ~(GENMASK(9, 8) | GENMASK(3, 0) | BIT(28)); + writel((v & ~0x30fU) | 0xf, rfe); + if (readl_poll_timeout(rfe, cur, + FIELD_GET(GENMASK(7, 4), cur) == 0xf && !(cur & BIT(11)), + 50, 10000)) + to |= BIT(1); + writel(readl(gapf) & ~BIT(4), gapf); + if (readl_poll_timeout(gapf, cur, !(cur & BIT(4)), 10, 5000)) + to |= BIT(3); + v = readl(rcpu); + writel((v & ~(0x30fU | BIT(28))) | 0xf, rcpu); + mb(); + if (readl_poll_timeout(rcpu, cur, + FIELD_GET(GENMASK(7, 4), cur) == 0xf && !(cur & BIT(11)), + 50, 10000)) + to |= BIT(2); + for (i = 3; i < main->num_domains && pwr->child_valid && main->child_saved; i++) { + void __iomem *cw = main->domains[i]; + u32 want = main->child_saved[i - 3]; + + if (!(want & 0xf) || (readl(cw) & 0xf0)) + continue; + writel(want, cw); + if (readl_poll_timeout(cw, cur, cur & 0xf0, 50, 2000)) + to |= (i - 3 < 24) ? BIT(8 + (i - 3)) : BIT(31); + } + dcp_pmc_set(dcp, pmc, true); + if (to & 0xf) { + dev_err(dev, "display domains not on after the sleep: %#x\n", to); + return -ETIMEDOUT; + } + if (to) + dev_warn(dev, "display child domains not on after the sleep: %#x\n", to); + + dcp_s2r_find_darts(dcp); + ret = 0; + if (dcp->s2r_disp_dart) { + apple_dart_display_keep(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, false); + ret = apple_dart_display_streams(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, + true, false); + } + if (!ret && dcp->s2r_dcp_dart) { + apple_dart_display_keep(dcp->s2r_dcp_dart, DCP_S2R_DCP_STREAMS, false); + ret = apple_dart_display_streams(dcp->s2r_dcp_dart, DCP_S2R_DCP_STREAMS, + true, false); + } + dcp_s2r_put_darts(dcp); + if (ret) { + dev_err(dev, "display DART stream restore after the sleep failed: %d\n", ret); + WRITE_ONCE(dcp->crashed, true); + return ret; + } + + WRITE_ONCE(dcp->crashed, false); + WRITE_ONCE(dcp->ext_dead, false); + ret = apple_rtkit_power_cycled_return(dcp->rtk, + dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); + if (ret) { + dev_err(dev, "the firmware's warm restart after the sleep failed: %d\n", ret); + WRITE_ONCE(dcp->crashed, true); + return ret; + } + WRITE_ONCE(dcp->s2r_fw_down, false); + /* + * Before the mode set, not after it: the commit's swap is what hands the firmware the + * console's framebuffer, and fbcon draws into that memory without committing again. With + * presentation still paused the swap was dropped and the panel stayed black with everything + * else up (10 Nov). + */ + iomfb_pause_presentation(dcp, false); + ret = dcp_t6041_recommit(dcp); + if (ret) + dev_err(dev, "mode set after the sleep failed: %d\n", ret); + /* + * Always restore backlight and boot power words once domains and RTKit warm restart + * succeeded, even if recommit timed out (e.g., wake with lid closed): leaving disp_cpu + * manual hangs the next display power-off. + */ + dcp_backlight_s2r_restore(dcp); + ps_ret = dcp_t6041_boot_ps_io(dcp, true); + return ret ?: ps_ret; +} + +static bool dcp_t6041_down, dcp_t6041_words; + +/* @np's first DART, dark or lit if its driver is bound. */ +static int dcp_t6041_dart_dark(struct device_node *np, bool dark) +{ + struct device_node *dart = np ? of_parse_phandle(np, "iommus", 0) : NULL; + struct platform_device *pdev = dart ? of_find_device_by_node(dart) : NULL; + int ret = 0; + + of_node_put(dart); + if (!pdev) + return 0; + if (device_is_bound(&pdev->dev)) + ret = apple_dart_power_dark(&pdev->dev, dark); + put_device(&pdev->dev); + return ret; +} + +/* + * Every external chain's DARTs, dark before their domains go off. The display subsystem maps + * every framebuffer through the display DARTs, and an unmap after the wake (an sddm restart, a + * logout) flushed one behind a dead block and stopped the machine (12 Nov). By node, so a chain + * whose DCP never bound, which the display subsystem skips as unusable, is covered too, and so + * is every chain a board enables, not only the first two. + */ +static int dcp_t6041_ext_darts_dark(void) +{ + struct device_node *np, *piodma, *fail_np = NULL; + bool fail_on_dcp = false; + int ret = 0; + + for_each_compatible_node(np, NULL, "apple,t6041-dcpext") { + if (!of_device_is_available(np)) + continue; + piodma = of_get_child_by_name(np, "piodma"); + ret = dcp_t6041_dart_dark(piodma, true); + of_node_put(piodma); + if (ret) { + fail_np = np; + break; + } + ret = dcp_t6041_dart_dark(np, true); + if (ret) { + fail_np = np; + fail_on_dcp = true; + break; + } + } + if (!ret) + return 0; + for_each_compatible_node(np, NULL, "apple,t6041-dcpext") { + if (!of_device_is_available(np)) + continue; + if (np == fail_np) { + if (fail_on_dcp) { + piodma = of_get_child_by_name(np, "piodma"); + dcp_t6041_dart_dark(piodma, false); + of_node_put(piodma); + } + of_node_put(np); + break; + } + dcp_t6041_dart_dark(np, false); + piodma = of_get_child_by_name(np, "piodma"); + dcp_t6041_dart_dark(piodma, false); + of_node_put(piodma); + } + of_node_put(fail_np); + return ret; +} + +enum dcp_t6041_step { DCP_S2R_FW_STOP, DCP_S2R_WORDS_DOWN, DCP_S2R_START }; + +/* Each step once per sleep. */ +static int dcp_t6041_s2r_step(enum dcp_t6041_step step) +{ + struct apple_dcp *host = READ_ONCE(dcp_t6041_host); + bool external = true; + unsigned int i; + int ret; + + if (!host) + return -ENODEV; + + if (step == DCP_S2R_START) { + if (!dcp_t6041_down) + return 0; + dcp_t6041_down = false; + dcp_t6041_words = false; + return driver_for_each_device(&apple_platform_driver.driver, NULL, NULL, + dcp_t6041_start_one); + } + if (step == DCP_S2R_WORDS_DOWN) { + if (dcp_t6041_words || !dcp_t6041_down) + return 0; + ret = dcp_t6041_ext_darts_dark(); + if (ret) + return ret; + dcp_t6041_words = true; + for (i = 0; i < host->t6041_power.num_chains; i++) { + ret = dcp_t6041_word_try(host->dev, &host->t6041_power, + &host->t6041_power.chains[i]); + if (ret) + return ret; + } + return 0; + } + if (dcp_t6041_down) + return 0; + dcp_t6041_boot_ps_io(host, false); + ret = driver_for_each_device(&apple_platform_driver.driver, NULL, &external, + dcp_t6041_stop_one); + if (ret) + return ret; + external = false; + ret = driver_for_each_device(&apple_platform_driver.driver, NULL, &external, + dcp_t6041_stop_one); + if (ret) { + if (READ_ONCE(host->s2r_fw_down)) + dcp_t6041_down = true; + return ret; + } + dcp_t6041_down = true; + return 0; +} + +/* T6041: the display down for a real sleep and back after it. */ +int dcp_t6041_s2r_all(bool start) +{ + int ret; + + if (!READ_ONCE(dcp_sleep_host_stop)) { + if (!start && READ_ONCE(dcp_sleep_host_stop_missing)) { + pr_err("apple-dcp: host-driven sleep required but apple,display-power unavailable\n"); + return -ENODEV; + } + return 0; + } + if (start) + return dcp_t6041_s2r_step(DCP_S2R_START); + if (dcp_t6041_down) + return 0; + ret = dcp_t6041_s2r_step(DCP_S2R_FW_STOP); + if (ret) { + if (dcp_t6041_down && dcp_t6041_s2r_step(DCP_S2R_START)) + pr_err("apple-dcp: T6041 S2R display unwind failed\n"); + return ret; + } + ret = dcp_t6041_s2r_step(DCP_S2R_WORDS_DOWN); + if (ret) { + if (dcp_t6041_s2r_step(DCP_S2R_START)) + pr_err("apple-dcp: T6041 S2R display unwind failed\n"); + return ret; + } + return 0; +} + int __init dcp_register(void) { return platform_driver_register(&apple_platform_driver); @@ -10162,8 +12727,11 @@ int __init dcp_register(void) void dcp_unregister(void) { platform_driver_unregister(&apple_platform_driver); + t8152_typec_unregister(); } #if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) #include "dcp_external_audio_test.c" +#include "dcp_handoff_test.c" +#include "dcp-firmware-test.c" #endif diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index f1d0f49026d601..4ea6ebc535f5fe 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -63,6 +63,7 @@ struct apple_encoder { #define to_apple_encoder(x) container_of(x, struct apple_encoder, base) void dcp_poweroff(struct platform_device *pdev); +bool dcp_sleep_keeps_firmware(struct device *dev); int dcp_typec_prepare_route(struct apple_dcp *dcp); void dcp_poweron(struct platform_device *pdev); void dcp_external_recover(struct platform_device *pdev); @@ -82,16 +83,30 @@ int dcp_peer_stop_v27(struct apple_dcp *dcp); struct apple_dcp *dcp_peer_scanout_v27(struct apple_dcp *dcp); void dcp_peer_swap_armed_v27(struct apple_dcp *dcp, u32 id); void dcp_peer_swap_failed_v27(struct apple_dcp *dcp); -bool dcp_peer_swap_complete_v27(struct apple_dcp *dcp, u32 id, ktime_t now, - void (*report)(struct apple_dcp *, u32, ktime_t)); +bool dcp_peer_swap_complete_v27(struct apple_dcp *dcp, u32 id, ktime_t now, bool shown, + void (*report)(struct apple_dcp *, u32, ktime_t, bool)); int dcp_set_crc(struct drm_crtc *crtc, bool enabled); int dcp_crtc_atomic_check(struct drm_crtc *crtc, struct drm_atomic_commit *commit); int dcp_get_connector_type(struct platform_device *pdev); bool dcp_fw_compat_is_12_x(struct platform_device *pdev); bool dcp_fw_compat_is_14_7(struct platform_device *pdev); bool dcp_fw_compat_is_desktop(struct platform_device *pdev); -bool dcp_fw_compat_panel_edr(struct platform_device *pdev); +bool dcp_panel_edr(struct platform_device *pdev); +bool dcp_ext_color_props_supported(struct platform_device *pdev); unsigned int dcp_gamma_lut_size(struct platform_device *pdev); +/* Whether a DCP reporting firmware-compat @compat runs the firmware-27 instance. */ +enum dcp_v27_admission { + DCP_V27_NOT_V27, /* older than 27: the older interfaces decide */ + DCP_V27_NO_TABLE, /* 27 or later, no method table for the build */ + DCP_V27_INCOMPLETE, /* 27 or later, a method has no known ID */ + DCP_V27_ADMITTED, +}; + +struct dcp_method_entry; +enum dcp_v27_admission dcp_v27_admission(const char *compat, + const struct dcp_method_entry **methods, + const char **missing, + unsigned int *num_missing); /* T6041 external display processors may join the DRM device. */ bool dcp_t6041_ext_enabled(void); void dcp_backlight_takeover_registered(struct platform_device *pdev); @@ -105,12 +120,16 @@ void dcp_ext26_open_services(struct apple_dcp *dcp); int dcp_ext26_layout_stop(struct apple_dcp *dcp); int dcp_wait_ready(struct platform_device *pdev, u64 timeout); void dcp_flush(struct drm_crtc *crtc, struct drm_atomic_commit *commit); +bool dcp_boot_surface_pending(struct platform_device *pdev); bool dcp_hdr_metadata_live(struct platform_device *pdev); bool dcp_edr_live(struct platform_device *pdev); void dcp_retain_framebuffer(struct platform_device *pdev, struct dcp_fb_reference *entry); void dcp_arm_retained_framebuffers(struct apple_dcp *dcp, u32 swap_id); void dcp_unarm_retained_framebuffers(struct apple_dcp *dcp, u32 swap_id); +int dcp_fb_mirror(struct apple_dcp *dcp, struct drm_framebuffer *fb); +struct drm_gem_dma_object; +void dcp_fb_unmirror(struct platform_device *pdev, struct drm_gem_dma_object *obj); void dcp_release_retained_framebuffers(struct apple_dcp *dcp, u32 swap_id); void dcp_release_all_retained_framebuffers(struct apple_dcp *dcp); bool dcp_is_initialized(struct platform_device *pdev); @@ -137,6 +156,7 @@ void dcp_set_dimensions(struct apple_dcp *dcp, u64 generation); void dcp_panel_read_dimensions(struct apple_dcp *dcp, struct device_node *panel_np); void dcp_update_connector_dimensions(struct apple_dcp *dcp, struct drm_connector *connector); +/* Must be called from sleepable context; may sleep on 14.7/ext26 mailboxes. */ void dcp_send_message(struct apple_dcp *dcp, u8 endpoint, u64 message); int dcp_dptx_connect_oob(struct platform_device *pdev, u32 port); @@ -153,6 +173,7 @@ int dcp_dptx_park(struct apple_dcp *dcp); int dcp_dptx_disconnect_oob(struct platform_device *pdev, u32 port); bool dcp_hold_resume_event(struct platform_device *pdev); bool dcp_s2r_firmware_stopped(struct platform_device *pdev); +int dcp_t6041_s2r_all(bool start); int iomfb_start_rtkit(struct apple_dcp *dcp); void iomfb_ext26_start(struct apple_dcp *dcp); @@ -183,6 +204,8 @@ bool apple_t8122_25g83_board(void); void dcp_typec_hybrid_first_dt(void); void dcp_fabric_hdmi_unplugged(struct apple_dcp *dcp); +void dcp_hdmi_unplugged_in_sleep(struct apple_dcp *dcp); +void dcp_hdmi_disconnect(struct apple_dcp *dcp); void dcp_fabric_hybrid_kick(struct apple_dcp *dcp, unsigned int delay_ms); void dcp_hdmi_yield_link(struct apple_dcp *dcp); void dcp_link_recovery_schedule(struct apple_dcp *dcp); diff --git a/drivers/gpu/drm/apple/dcp_backlight.c b/drivers/gpu/drm/apple/dcp_backlight.c index a487e9b770aabe..5746c318e54cd0 100644 --- a/drivers/gpu/drm/apple/dcp_backlight.c +++ b/drivers/gpu/drm/apple/dcp_backlight.c @@ -252,6 +252,9 @@ static int dcp_get_brightness(struct backlight_device *bd) if (READ_ONCE(dcp->quiescing)) return -ENODEV; + /* Nothing is presented any more: there is no level to report. */ + if (READ_ONCE(dcp->crashed)) + return -EIO; if (dcp_backlight_active(dcp) || dcp_backlight_desktop(dcp)) { /* @@ -431,6 +434,34 @@ void dcp_backlight_finish_fade(struct apple_dcp *dcp) dcp_backlight_kick(dcp); } +/* + * After the S2R display restart: ask for the user's level again and send it, whatever the + * backlight core's flags say at that moment. The class device resumes on its own schedule: + * when it runs after the restart the panel stays dark until then (suspended and core_blank + * still set at the mode set, 11 Nov), and when it runs before, its request goes to a firmware + * that isn't up yet and nothing sends it again (the dark lid wakes). + */ +void dcp_backlight_s2r_restore(struct apple_dcp *dcp) +{ + struct backlight_device *bd = READ_ONCE(dcp->brightness.bl_dev); + unsigned long flags; + + if (!dcp_backlight_desktop(dcp) || !bd) + return; + spin_lock_irqsave(&dcp->backlight.lock, flags); + /* + * A level sent to the firmware that the stop then took down never gets its answer: the + * state stayed in_flight for good and nothing was sent again (dark lid wake of 20:30, + * "sent 0 ... dirty 1 in_flight 1"). The restarted firmware knows nothing of it. + */ + dcp->backlight.state.in_flight = false; + dcp->backlight.state.retries = 0; + dcp_bl_request(&dcp->backlight.state, bd->props.brightness, false, false); + dcp->backlight.state.dirty = true; + spin_unlock_irqrestore(&dcp->backlight.lock, flags); + dcp_backlight_kick(dcp); +} + int dcp_backlight_dpms(struct apple_dcp *dcp, bool on) { unsigned long flags; @@ -857,6 +888,9 @@ static int dcp_set_brightness(struct backlight_device *bd) if (READ_ONCE(dcp->quiescing)) return -ENODEV; + /* A crashed processor discards every present, the level with it. */ + if (READ_ONCE(dcp->crashed)) + return -EIO; if (dcp_backlight_active(dcp) || dcp_backlight_desktop(dcp)) { struct dcp_backlight_state *state = &dcp->backlight.state; diff --git a/drivers/gpu/drm/apple/dcp_backlight.h b/drivers/gpu/drm/apple/dcp_backlight.h index 0045e995885d7c..bb200ace902584 100644 --- a/drivers/gpu/drm/apple/dcp_backlight.h +++ b/drivers/gpu/drm/apple/dcp_backlight.h @@ -407,6 +407,7 @@ bool dcp_backlight_desktop_prepare(struct apple_dcp *dcp, u32 id, bool have_surface, u32 *nits); void dcp_backlight_desktop_finish(struct apple_dcp *dcp, u32 id, bool reply, bool accepted); +void dcp_backlight_s2r_restore(struct apple_dcp *dcp); /* * kick only queues work; it must not submit a top-level RPC from the caller. diff --git a/drivers/gpu/drm/apple/dcp_dropped_swap_test.c b/drivers/gpu/drm/apple/dcp_dropped_swap_test.c index dc5b145fab5285..473ca29bfaee4b 100644 --- a/drivers/gpu/drm/apple/dcp_dropped_swap_test.c +++ b/drivers/gpu/drm/apple/dcp_dropped_swap_test.c @@ -266,6 +266,46 @@ static void dropped_present_retired_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, READ_ONCE(dcp->mode_state.valid)); } +/* + * The same drop on an HDMI display behind a fixed port (no panel, no Type-C + * route): the J473's HDMI display drops HPD while it wakes from standby after + * DPMS on, under an accepted swap. The watchdog must retire that present too, + * instead of leaving it to the queue's ten second timeout, which declares the + * coprocessor crashed and refuses every later mode set. + */ +static void dropped_present_fixed_hdmi_test(struct kunit *test) +{ + struct dropped_test *t = dropped_test_external(test); + struct apple_dcp *dcp = &t->dcp; + + dcp->fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA; + KUNIT_ASSERT_FALSE(test, dcp_has_panel(dcp)); + + dropped_test_present(test, t, 0, &t->fb[1]); + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&dcp->swap_watchdog_wq)); + KUNIT_EXPECT_EQ(test, iomfb_queue_settle(dcp, msecs_to_jiffies(2000)), 0); + KUNIT_EXPECT_FALSE(test, READ_ONCE(dcp->crashed)); + KUNIT_EXPECT_TRUE(test, t->present[0].released); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&dcp->iomfb.timeout)); + KUNIT_EXPECT_TRUE(test, dcp_present_was_retired_h17p(&dcp->present_state_h17p, + DROPPED_SWAP_ID)); + flush_delayed_work(&dcp->swap_watchdog_wq); + KUNIT_EXPECT_FALSE(test, READ_ONCE(dcp->mode_state.valid)); +} + +/* A built-in panel keeps its swaps unwatched, as before. */ +static void panel_swap_unwatched_test(struct kunit *test) +{ + struct dropped_test *t = dropped_test_external(test); + struct apple_dcp *dcp = &t->dcp; + + dcp->fixed_connector_type = DRM_MODE_CONNECTOR_eDP; + dcp->panel.width_mm = 300; + KUNIT_ASSERT_TRUE(test, dcp_has_panel(dcp)); + dcp_swap_watchdog_arm(dcp); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&dcp->swap_watchdog_wq)); +} + /* * The firmware might still read a dropped present: its framebuffers, and the * one it would have replaced, stay referenced until a later present @@ -546,6 +586,8 @@ static struct kunit_case dropped_swap_cases[] = { KUNIT_CASE(desktop_present_completion_test), KUNIT_CASE(takeover_adopt_watched_test), KUNIT_CASE(dropped_present_retired_test), + KUNIT_CASE(dropped_present_fixed_hdmi_test), + KUNIT_CASE(panel_swap_unwatched_test), KUNIT_CASE(dropped_present_buffers_test), KUNIT_CASE(completed_present_kept_test), KUNIT_CASE(stop_deferred_test), diff --git a/drivers/gpu/drm/apple/dcp_handoff_test.c b/drivers/gpu/drm/apple/dcp_handoff_test.c new file mode 100644 index 00000000000000..22c88773b9114c --- /dev/null +++ b/drivers/gpu/drm/apple/dcp_handoff_test.c @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by dcp.c: the boot loader handoff state the driver reads before + * it starts a display coprocessor. dcp_external_is_idle() runs on a fake + * coprocessor register window; dcp_boot_show_notch(), which boot_show_notch() + * applies to /chosen, on nodes of the test's own. Nothing here reads or + * writes the device tree, so the suite is safe next to a probing display. + */ +#include +#include + +#include "dcp-lifecycle.h" + +#define DCP_HANDOFF_COPROC_SIZE (APPLE_DCP_COPROC_CPU_STATUS + sizeof(u32)) + +static struct apple_dcp *dcp_handoff_coproc(struct kunit *test, u32 control, u32 status) +{ + struct apple_dcp *dcp = kunit_kzalloc(test, sizeof(*dcp), GFP_KERNEL); + void *regs = kunit_kzalloc(test, DCP_HANDOFF_COPROC_SIZE, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, dcp); + KUNIT_ASSERT_NOT_NULL(test, regs); + *(u32 *)(regs + APPLE_DCP_COPROC_CPU_CONTROL) = control; + *(u32 *)(regs + APPLE_DCP_COPROC_CPU_STATUS) = status; + dcp->coproc_reg = (void __iomem __force *)regs; + return dcp; +} + +static void dcp_handoff_external_idle(struct kunit *test) +{ + const u32 run = APPLE_DCP_COPROC_CPU_CONTROL_RUN; + const u32 stopped = APPLE_DCP_COPROC_CPU_STATUS_STOPPED; + const u32 idle = APPLE_DCP_COPROC_CPU_STATUS_IDLE; + const u32 others = ~(u32)APPLE_DCP_COPROC_CPU_STATUS_RUNNING; + unsigned int bits; + + /* Inherited idle: the CPU enabled, and stopped and idle in its status. */ + KUNIT_EXPECT_TRUE(test, dcp_external_is_idle(dcp_handoff_coproc(test, run, + stopped | idle))); + + /* Every other combination of the three bits is not. */ + for (bits = 0; bits < 7; bits++) { + u32 control = bits & 1 ? run : 0; + u32 status = (bits & 2 ? stopped : 0) | (bits & 4 ? idle : 0); + + KUNIT_EXPECT_FALSE_MSG(test, + dcp_external_is_idle(dcp_handoff_coproc(test, control, + status)), + "control %#x status %#x", control, status); + } + + /* + * Other bits in either register do not change the answer. RUNNING is + * left out of them: apple_dcp_coprocessor_is_active() reads it as an + * active processor, and whether the check should refuse it next to + * STOPPED and IDLE is not this test's to pin. + */ + KUNIT_EXPECT_TRUE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~0u, others))); + KUNIT_EXPECT_FALSE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~run, others))); + KUNIT_EXPECT_FALSE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~0u, + others & ~idle))); + KUNIT_EXPECT_FALSE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~0u, + others & ~stopped))); +} + +/* + * dcp_boot_show_notch() on a node of the test's own, never part of the + * device tree, with asahi,show-notch holding @length bytes at @value. + */ +static bool dcp_handoff_notch(const void *value, int length) +{ + struct property prop = { + .name = "asahi,show-notch", + .length = length, + .value = (void *)value, + }; + struct device_node chosen = { .properties = &prop }; + + return dcp_boot_show_notch(&chosen); +} + +#define dcp_handoff_notch_string(s) dcp_handoff_notch(s, sizeof(s)) + +static void dcp_handoff_boot_notch(struct kunit *test) +{ + static const char unterminated[] = { '1' }; + static const __be32 cell = cpu_to_be32(1); + struct property other = { + .name = "bootargs", + .length = sizeof("1"), + .value = "1", + }; + struct device_node chosen = {}; + + /* Absent, or no /chosen at all: the notch rows stay out of the mode. */ + KUNIT_EXPECT_FALSE(test, dcp_boot_show_notch(NULL)); + KUNIT_EXPECT_FALSE(test, dcp_boot_show_notch(&chosen)); + chosen.properties = &other; + KUNIT_EXPECT_FALSE(test, dcp_boot_show_notch(&chosen)); + /* Only the string "1" the boot loader writes shows the notch. */ + KUNIT_EXPECT_TRUE(test, dcp_handoff_notch_string("1")); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch_string("0")); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch_string("")); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch_string("10")); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch_string("yes")); + /* A cell, an empty property or an unterminated "1" is not that string. */ + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(&cell, sizeof(cell))); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(NULL, 0)); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(unterminated, sizeof(unterminated))); +} + +static struct kunit_case dcp_handoff_cases[] = { + KUNIT_CASE(dcp_handoff_external_idle), + KUNIT_CASE(dcp_handoff_boot_notch), + {} +}; + +static struct kunit_suite dcp_handoff_suite = { + .name = "apple-dcp-handoff", + .test_cases = dcp_handoff_cases, +}; + +kunit_test_suite(dcp_handoff_suite); diff --git a/drivers/gpu/drm/apple/dcp_trace.c b/drivers/gpu/drm/apple/dcp_trace.c deleted file mode 100644 index d18e71af73a74d..00000000000000 --- a/drivers/gpu/drm/apple/dcp_trace.c +++ /dev/null @@ -1,3 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -#define CREATE_TRACE_POINTS -#include "dcp_trace.h" \ No newline at end of file diff --git a/drivers/gpu/drm/apple/dcpext_drm.c b/drivers/gpu/drm/apple/dcpext_drm.c index 1d9981b5def3f9..53ff271e105e6e 100644 --- a/drivers/gpu/drm/apple/dcpext_drm.c +++ b/drivers/gpu/drm/apple/dcpext_drm.c @@ -290,7 +290,7 @@ static void ext_plane_update(struct drm_plane *plane, struct drm_atomic_commit * static void ext_plane_disable(struct drm_plane *plane, struct drm_atomic_commit *state) { struct dcpext_drm *ext = container_of(plane->dev, struct dcpext_drm, drm); - u32 *dst = ext->pixels; + __le32 *dst = ext->pixels; struct dcpext_frame frame; int idx, i, ret; diff --git a/drivers/gpu/drm/apple/dptxep.c b/drivers/gpu/drm/apple/dptxep.c index 1714bdbb2a6bf2..513514cd2cfb1e 100644 --- a/drivers/gpu/drm/apple/dptxep.c +++ b/drivers/gpu/drm/apple/dptxep.c @@ -482,11 +482,12 @@ static int dptxport_call_set_active_lane_count(struct apple_epic_service *servic ret = dptx_j700_validate_lanes(dptx, lane_count); if (ret) return ret; - } else if (dptx->lane_count < lane_count && - !(dcp_is_t8132_ext(dcp) && dcp_is_usb4_output(dcp))) { + } else if (dptx->lane_count < lane_count && !dcp_is_usb4_output(dcp) && + dcp->dptx_phy <= 3) { /* - * A T8132 tunnel has no PHY lanes to check: its lane count - * is the tunnel's, and lane_count holds the previous active one. + * A DP tunnel or a fixed non-ATC-PHY output (dptx_phy > 3) has + * no ATC PHY lanes to check: its lane count is accepted below, + * and lane_count holds the previous active one. */ dev_err(dcp->dev, "set_active_lane_count: unexpected lane " "count:%llu phy: %d\n", lane_count, dptx->lane_count); @@ -986,7 +987,7 @@ static int dptxport_call(struct apple_epic_service *service, u32 idx, lc->lane_count = cpu_to_le64(dptx->lane_count); return 0; } - case DPTX_APCALL_SET_ACTIVE_LANE_COUNT: + case DPTX_APCALL_SET_ACTIVE_LANE_COUNT: return dptxport_call_link_config(service, true, data, data_size, reply, reply_size); case DPTX_APCALL_GET_SUPPORTS_HPD: @@ -1059,7 +1060,7 @@ static int dptxport_call(struct apple_epic_service *service, u32 idx, reply, reply_size); return dptxport_call_set_drive_settings(service, data, data_size, reply, reply_size); - case DPTX_APCALL_ACTIVATE: + case DPTX_APCALL_ACTIVATE: return dptxport_call_activate(service, data, data_size, reply, reply_size); case DPTX_APCALL_DEACTIVATE: @@ -1667,13 +1668,15 @@ int dptxep_init(struct apple_dcp *dcp) * up so a later announce can still bind. */ /* - * A firmware-27 external processor whose ports are not - * on this endpoint announces nothing here either (a 27.2 - * dcpext on DPTX_ENDPOINT_V2 where its firmware does not - * advertise DPTX_ENDPOINT, see dcp_v27_dptx_layout()). + * A firmware-27 external processor, or a firmware-27 + * DCP with Type-C routes, whose ports are not on this + * endpoint announces nothing here either (a 27.2 DCP on + * DPTX_ENDPOINT_V2 where its firmware does not advertise + * DPTX_ENDPOINT, see dcp_v27_dptx_layout()). */ if (dcp_fw_is_14_7(dcp) || dcp_is_ext26(dcp) || - (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && dcp->dcpext)) { + (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && + (dcp->dcpext || dcp->nr_typec_routes))) { dev_info(dcp->dev, "DPTX port %u not announced yet\n", port); return 0; diff --git a/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c b/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c new file mode 100644 index 00000000000000..584b37ccd4ff1c --- /dev/null +++ b/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c @@ -0,0 +1,155 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by dpavservep.c: which announced AV services the DP/HDMI AV + * client admits. dcpavserv_identity() runs on a fake service, endpoint and + * DCP; each row is one announcement (name, class, unit, channel) on one + * endpoint and wire protocol. + */ +#include + +enum dpavid_role { + DPAVID_LEGACY, /* classic AFK wire */ + DPAVID_V2, /* AFKV2 wire */ + DPAVID_EXT26, /* AFKV2 wire, native26 external role */ +}; + +struct dpavid_case { + const char *desc; + enum dpavid_role role; + u32 endpoint; + const char *name; + const char *class; + s64 unit; + u32 channel; + bool admitted; +}; + +#define DPAVID_NAME "dcpav-service-epic" + +static const struct dpavid_case dpavid_cases[] = { + /* The service name gates every role. */ + { "legacy: no name", DPAVID_LEGACY, DPAVSERV_ENDPOINT, NULL, NULL, 0, 1, false }, + { "legacy: other name", DPAVID_LEGACY, DPAVSERV_ENDPOINT, "dcpav-service", + NULL, 0, 1, false }, + { "v2: other name", DPAVID_V2, DPAVSERV_ENDPOINT_V2, "dcpdp-service-epic", + "DCPDP13Service", 3, 3, false }, + { "ext26: other name", DPAVID_EXT26, DPAVSERV_ENDPOINT, "dcpdp-service-epic", + "DCPDPService", 0, 1, false }, + + /* Classic wire: unit 0 only, class and channel not consulted. */ + { "legacy: unit 0", DPAVID_LEGACY, DPAVSERV_ENDPOINT, DPAVID_NAME, NULL, 0, 0, true }, + { "legacy: unit 0, any class", DPAVID_LEGACY, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDPService", 0, 9, true }, + { "legacy: unit 1", DPAVID_LEGACY, DPAVSERV_ENDPOINT, DPAVID_NAME, NULL, 1, 1, false }, + + /* AFKV2 on the V2 endpoint: interface-id is the unit, equal to the channel. */ + { "v2 ep 0x2a: DP2HDMI unit == channel", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "AppleDCPDP2HDMI", 3, 3, true }, + { "v2 ep 0x2a: DP13 unit == channel", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDP13Service", 0xffff, 0xffff, true }, + { "v2 ep 0x2a: unit != channel", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDP13Service", 2, 3, false }, + { "v2 ep 0x2a: unit 0", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDP13Service", 0, 3, false }, + { "v2 ep 0x2a: channel 0", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDP13Service", 0, 0, false }, + { "v2 ep 0x2a: channel over u16", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDP13Service", 0x10000, 0x10000, false }, + { "v2 ep 0x2a: no class", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + NULL, 3, 3, false }, + { "v2 ep 0x2a: DCPDPService class", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDPService", 3, 3, false }, + + /* + * AFKV2 on the classic DPAV endpoint: the MCDP29xx converters and the + * M3/M4 Airs' generic DCPDP13Service, with EPICUnit 0 and a bounded + * dynamic interface-id. AppleDCPDP2HDMI and the other classes stay refused. + */ + { "v2 ep 0x28: DP13 unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDP13Service", 0, 7, true }, + { "v2 ep 0x28: DP2HDMI unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "AppleDCPDP2HDMI", 0, 1, false }, + { "v2 ep 0x28: MCDP29XX unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "AppleDCPMCDP29XX", 0, 5, true }, + { "v2 ep 0x28: MCDP2900 unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "AppleDCPMCDP2900", 0, 1, true }, + { "v2 ep 0x28: MCDP2900 unit 1", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "AppleDCPMCDP2900", 1, 1, false }, + { "v2 ep 0x28: other MCDP part", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "AppleDCPMCDP2800", 0, 1, false }, + { "v2 ep 0x28: unit 0, channel at u16 max", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDP13Service", 0, 0xffff, true }, + { "v2 ep 0x28: unit == channel", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDP13Service", 7, 7, false }, + { "v2 ep 0x28: channel 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDP13Service", 0, 0, false }, + { "v2 ep 0x28: channel over u16", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDP13Service", 0, 0x10000, false }, + { "v2 ep 0x28: no class", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + NULL, 0, 7, false }, + { "v2 ep 0x28: DCPDPService class", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDPService", 0, 7, false }, + + /* AFKV2 on any other endpoint. */ + { "v2 other endpoint", DPAVID_V2, 0x29, DPAVID_NAME, "DCPDP13Service", 0, 7, false }, + + /* native26: DCPDPService, unit 0, nonzero channel, classic endpoint only. */ + { "ext26: DCPDPService unit 0", DPAVID_EXT26, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDPService", 0, 1, true }, + { "ext26: unit 1", DPAVID_EXT26, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDPService", 1, 1, false }, + { "ext26: channel 0", DPAVID_EXT26, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDPService", 0, 0, false }, + { "ext26: no class", DPAVID_EXT26, DPAVSERV_ENDPOINT, DPAVID_NAME, + NULL, 0, 1, false }, + { "ext26: DP13 class", DPAVID_EXT26, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDP13Service", 0, 1, false }, + { "ext26: V2 endpoint", DPAVID_EXT26, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDPService", 0, 1, false }, +}; + +static void dpavid_case_desc(const struct dpavid_case *c, char *desc) +{ + strscpy(desc, c->desc, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(dpavid, dpavid_cases, dpavid_case_desc); + +static void dpavid_admission(struct kunit *test) +{ + const struct dpavid_case *c = test->param_value; + struct apple_epic_service *svc; + struct apple_dcp_afkep *ep; + struct apple_dcp *dcp; + + dcp = kunit_kzalloc(test, sizeof(*dcp), GFP_KERNEL); + ep = kunit_kzalloc(test, sizeof(*ep), GFP_KERNEL); + svc = kunit_kzalloc(test, sizeof(*svc), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dcp); + KUNIT_ASSERT_NOT_NULL(test, ep); + KUNIT_ASSERT_NOT_NULL(test, svc); + + if (c->role == DPAVID_EXT26) + dcp->hw.iomfb_method_profile = DCP_IOMFB_METHODS_J613_EXT26; + ep->dcp = dcp; + ep->endpoint = c->endpoint; + ep->wire_v2 = c->role != DPAVID_LEGACY; + svc->ep = ep; + svc->channel = c->channel; + + KUNIT_EXPECT_EQ(test, dcp_is_ext26(dcp), c->role == DPAVID_EXT26); + KUNIT_EXPECT_EQ(test, dcpavserv_identity(svc, c->name, c->class, c->unit), + c->admitted); +} + +static struct kunit_case dpavid_test_cases[] = { + KUNIT_CASE_PARAM(dpavid_admission, dpavid_gen_params), + {} +}; + +static struct kunit_suite dpavid_suite = { + .name = "apple-dcpavserv-identity", + .test_cases = dpavid_test_cases, +}; + +kunit_test_suite(dpavid_suite); diff --git a/drivers/gpu/drm/apple/epic/dpavservep-v14-test.c b/drivers/gpu/drm/apple/epic/dpavservep-v14-test.c index 1912f87454e5d6..c1e06f94af4b1a 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep-v14-test.c +++ b/drivers/gpu/drm/apple/epic/dpavservep-v14-test.c @@ -152,6 +152,7 @@ static struct av14_test *av14_setup(struct kunit *test, bool native) t->dcp->external_native = native; mutex_init(&t->dcp->hpd_mutex); mutex_init(&t->dcp->dcpavserv.lock); + spin_lock_init(&t->dcp->hdr.lock); INIT_WORK(&t->dcp->dcpavserv.close_wq, dcpavserv_close_work); /* Queued work runs here, in test context: av14_run_close_work() */ disable_work(&t->dcp->dcpavserv.close_wq); diff --git a/drivers/gpu/drm/apple/epic/dpavservep.c b/drivers/gpu/drm/apple/epic/dpavservep.c index f94cf659e9a193..de678ef34b6756 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep.c +++ b/drivers/gpu/drm/apple/epic/dpavservep.c @@ -17,7 +17,9 @@ #include "../afk.h" #include "../dcp.h" #include "../dcp-internal.h" +#include "../dcp-fabric.h" #include "../connector.h" +#include "../iomfb_internal.h" #include "../trace.h" static void dcpavserv_notify_edid(struct apple_epic_service *service) @@ -34,6 +36,16 @@ static void dcpavserv_notify_edid(struct apple_epic_service *service) schedule_work(&connector->hotplug_wq); } +static bool dcpavserv_hdr_class(const char *class) +{ + return class && + (!strcmp(class, "DCPDP13Service") || + !strcmp(class, "DCPDPService") || + !strcmp(class, "AppleDCPDP2HDMI") || + !strcmp(class, "AppleDCPMCDP29XX") || + !strcmp(class, "AppleDCPMCDP2900")); +} + static bool dcpavserv_identity(struct apple_epic_service *service, const char *name, const char *class, s64 unit) { @@ -44,27 +56,38 @@ static bool dcpavserv_identity(struct apple_epic_service *service, const char *n class && !strcmp(class, "DCPDPService") && service->channel; if (!service->ep->wire_v2) return unit == 0; - if (!class || (strcmp(class, "AppleDCPDP2HDMI") && - strcmp(class, "DCPDP13Service")) || - !service->channel || service->channel > U16_MAX) + if (!class || !service->channel || service->channel > U16_MAX) return false; /* H17P's lower-case interface-id is dynamic, not a physical-port unit. */ if (service->ep->endpoint == DPAVSERV_ENDPOINT_V2) - return unit == service->channel; + return (!strcmp(class, "AppleDCPDP2HDMI") || + !strcmp(class, "DCPDP13Service")) && unit == service->channel; /* - * An AFKV2 AV service on the classic DPAV endpoint carries EPICUnit 0; - * its interface-id (the channel) is dynamic across reconnects. + * Firmware 27 names an MCDP29xx DP-to-HDMI converter's AV service after + * its part (the M2 Mac mini's HDMI port, USB-C to HDMI adapters) and + * announces it on the classic DPAV endpoint with EPICUnit 0; its + * interface-id (the channel) is dynamic across reconnects. The M3 and + * M4 Airs' external processors announce the generic DCPDP13Service + * there the same way. */ - return service->ep->endpoint == DPAVSERV_ENDPOINT && unit == 0; + return service->ep->endpoint == DPAVSERV_ENDPOINT && unit == 0 && + (!strcmp(class, "AppleDCPMCDP29XX") || + !strcmp(class, "AppleDCPMCDP2900") || + !strcmp(class, "DCPDP13Service")); } static bool dcpavserv_admission_current(struct apple_dcp *dcp, u64 generation) { lockdep_assert_held(&dcp->hpd_mutex); - /* Initial service discovery may precede the first Type-C attachment. */ + /* + * Initial service discovery may precede the first Type-C attachment. A + * fixed output that no Type-C display has borrowed (the HDMI port) has no + * Type-C cable to wait for: every sleep and DPMS cycle still moves the + * generation on, so a service announced before it is not taken after it. + */ return !READ_ONCE(dcp->quiescing) && !READ_ONCE(dcp->external_physically_absent) && generation == dcp->typec_generation && - (!generation || dcp->typec_cable_connected); + (!generation || dcp->typec_cable_connected || !dcp_is_typec_output(dcp)); } /* Admission runs before AFKV2 OPEN and before readers can pin the service. */ @@ -137,6 +160,9 @@ static void dcpavserv_init(struct apple_epic_service *service, const char *name, dcp->dcpavserv.opened = NULL; dcp->dcpavserv.opened_epoch = 0; service->cookie = &dcp->dcpavserv; + if (!dcp->desktop && !dcp_is_ext26(dcp) && + dcpavserv_hdr_class(class)) + dcp_hdr_service_bind(service); complete(&dcp->dcpavserv.enable_completion); published = true; } @@ -182,6 +208,7 @@ static void dcpavserv_teardown(struct apple_epic_service *service) mutex_lock(&dcp->dcpavserv.lock); if (dcp->dcpavserv.service == service) { + dcp_hdr_service_unbind(service); dcp->dcpavserv.enabled = false; dcp->dcpavserv.service = NULL; dcp->dcpavserv.epoch++; @@ -211,6 +238,7 @@ void dpavservep_detach(struct apple_dcp *dcp) dcp->dcpavserv.opened_epoch = 0; reinit_completion(&dcp->dcpavserv.enable_completion); if (service) { + dcp_hdr_service_unbind(service); afk_service_retire(service); dcpavserv_invalidate_edid(dcp); } @@ -827,4 +855,5 @@ int dpavservep_init(struct apple_dcp *dcp) #if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) #include "dpavservep-v14-test.c" +#include "dpavservep-identity-test.c" #endif diff --git a/drivers/gpu/drm/apple/epic/panelavep.c b/drivers/gpu/drm/apple/epic/panelavep.c index cd4507b2bf78fa..6e7a0cb682bcf4 100644 --- a/drivers/gpu/drm/apple/epic/panelavep.c +++ b/drivers/gpu/drm/apple/epic/panelavep.c @@ -131,9 +131,11 @@ static void panelav_open_worker(struct work_struct *work) if (ret) dev_warn(service->ep->dcp->dev, "panel AV: video interface %u OPEN failed: %d\n", service->channel, ret); - else + else { + complete(&service->ep->dcp->v27_wake_video); dev_info(service->ep->dcp->dev, "panel AV: video interface %u opened\n", service->channel); + } afk_service_put(service); kfree(w); } diff --git a/drivers/gpu/drm/apple/iboot_drm.c b/drivers/gpu/drm/apple/iboot_drm.c new file mode 100644 index 00000000000000..fbe43688c52e42 --- /dev/null +++ b/drivers/gpu/drm/apple/iboot_drm.c @@ -0,0 +1,1115 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KMS of a DCP driven through the iBoot interface (DCP_FIRMWARE_IBOOT): a DRM + * device of its own per DCP with one primary plane, CRTC, encoder and + * connector. The firmware only takes width, height and refresh rate for a + * mode and picks the timing itself; the modes come from the sink's EDID, or + * from the firmware's list built with CVT. + * + * Framebuffers are shadow buffers copied by the CPU into the scanout + * buffers, and a modeset only changes their geometry, as the bootloader + * does. Changing the surface address between Linux buffers made later + * modesets crash the firmware (IOMFB axi_rd_err), so the scanout buffers + * are the only surfaces the firmware gets. There is no vblank interrupt. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dcp-internal.h" +#include "ibootep.h" +#include "iomfb_iboot.h" +#include "t8152_display.h" + +/* + * Swap between the scanout buffers per frame. Off: frames are copied into + * the buffer on screen, which tears during motion. + */ +static bool buffered = true; +module_param_named(iboot_buffered, buffered, bool, 0444); +MODULE_PARM_DESC(iboot_buffered, "iBoot interface displays: copy each frame into a scanout buffer that is not on screen (default: on)"); + +DEFINE_DRM_GEM_DMA_FOPS(dcp_iboot_fops); + +/* + * Not the display subsystem's "apple": these DCPs take no direct scanout, + * every frame is copied, so userspace must not treat them as that one. + */ +static const struct drm_driver dcp_iboot_drm_driver = { + /* + * Frames are copied by the CPU, imported ones too: a compositor + * driving both displays imports one device's buffers into the other. + */ + DRM_GEM_DMA_DRIVER_OPS_VMAP, + DRM_FBDEV_DMA_DRIVER_OPS, + .name = "apple-dcpib", + .desc = "Apple DCP (iBoot interface)", + .major = 1, + .minor = 0, + .driver_features = DRIVER_GEM | DRIVER_MODESET | DRIVER_ATOMIC, + .fops = &dcp_iboot_fops, +}; + +struct dcp_iboot *dcp_iboot_alloc(struct device *dev) +{ + return devm_drm_dev_alloc(dev, &dcp_iboot_drm_driver, struct dcp_iboot, drm); +} + +const char *dcp_iboot_driver_name(void) +{ + return dcp_iboot_drm_driver.name; +} + +static const u32 dcp_iboot_formats[] = { + DRM_FORMAT_XRGB8888, + DRM_FORMAT_ARGB8888, +}; + +static int iboot_refresh(const struct iboot_timing_mode *t) +{ + return (le32_to_cpu(t->fps) + 0x8000) >> 16; +} + +/* + * Whether @t works: the link at the PHY's highest rate must carry it (24 bpp + * plus about 12% blanking against rate x lanes x 0.8 for 8b/10b); a mode + * beyond that only blanks the display. + */ +static bool iboot_mode_fits(struct dcp_iboot *ib, const struct iboot_timing_mode *t) +{ + const struct t8152_phy_ops *phy = ib->disp.phy; + /* + * The lanes the firmware may train, as GET_MAX_LANE_COUNT reports them: + * the USB-C route's. Not the last training's: a sink that replugs while + * the display is off is trained with a single lane. + */ + u32 lanes = (phy->max_lane_count ? phy->max_lane_count(&ib->disp) : 4) ?: 2; + u64 link = (u64)phy->max_link_rate * 270000000ULL * lanes * 8 / 10; + u64 pixels = (u64)le32_to_cpu(t->width) * le32_to_cpu(t->height) * + iboot_refresh(t); + + /* Hotplug may return modes larger than the buffers allocated at probe. */ + if ((u64)ALIGN(le32_to_cpu(t->width) * 4, 64) * le32_to_cpu(t->height) > + ib->scan[0].size) + return false; + return pixels * 24 * 112 / 100 <= link; +} + +/* @mode's refresh rate in 16.16, as drm_mode_vrefresh() computes it. */ +static u32 iboot_mode_fps(const struct drm_display_mode *mode) +{ + u64 num = mul_u32_u32(mode->clock, 1000) << 16; + u64 den = mul_u32_u32(mode->htotal, mode->vtotal); + + if (mode->flags & DRM_MODE_FLAG_INTERLACE) + num *= 2; + if (mode->flags & DRM_MODE_FLAG_DBLSCAN) + den *= 2; + if (mode->vscan > 1) + den *= mode->vscan; + return den ? DIV64_U64_ROUND_CLOSEST(num, den) : 0; +} + +/* + * The firmware mode for @mode: same size, refresh rate within 1 Hz (EDID's + * 59.94 against the firmware's 60.00), the nearest one by the exact rate. + * The firmware picks the timing from the rate, and next to the sink's + * 2560x1440@59.951 (241.5 MHz) it lists a 60.000 standard mode that it + * drives with CVT at 312.25 MHz, which the J873g's USB-C EV2780 rejects. + */ +static const struct iboot_timing_mode * +iboot_find_mode(struct dcp_iboot *ib, const struct drm_display_mode *mode) +{ + const struct iboot_timing_mode *best = NULL; + u32 fps = iboot_mode_fps(mode); + + for (unsigned int i = 0; i < ib->nr_tmodes; i++) { + const struct iboot_timing_mode *t = &ib->tmodes[i]; + + if (!t->valid || le32_to_cpu(t->width) != mode->hdisplay || + le32_to_cpu(t->height) != mode->vdisplay || + abs_diff(le32_to_cpu(t->fps), fps) > 0x10000 || + !iboot_mode_fits(ib, t)) + continue; + if (!best || abs_diff(le32_to_cpu(t->fps), fps) < + abs_diff(le32_to_cpu(best->fps), fps)) + best = t; + } + return best; +} + +/* + * Valid, at most 32 bpp, the highest depth, then the lowest colorimetry, + * encoding and EOTF, as the bootloader chooses. Deeper modes the HDMI + * converter offers are refused by SET_MODE. + */ +static bool iboot_color_better(const struct iboot_color_mode *a, + const struct iboot_color_mode *b) +{ + u32 abpp = le32_to_cpu(a->bpp), bbpp = le32_to_cpu(b->bpp); + bool afits = abpp <= 32, bfits = bbpp <= 32; + + if (!!a->valid != !!b->valid) + return a->valid; + if (afits != bfits) + return afits; + if (abpp != bbpp) + return abpp > bbpp; + if (a->colorimetry != b->colorimetry) + return le32_to_cpu(a->colorimetry) < le32_to_cpu(b->colorimetry); + if (a->encoding != b->encoding) + return le32_to_cpu(a->encoding) < le32_to_cpu(b->encoding); + return le32_to_cpu(a->eotf) < le32_to_cpu(b->eotf); +} + +static const struct iboot_color_mode *iboot_find_color(struct dcp_iboot *ib) +{ + const struct iboot_color_mode *best = NULL; + + for (unsigned int i = 0; i < ib->nr_cmodes; i++) + if (!best || iboot_color_better(&ib->cmodes[i], best)) + best = &ib->cmodes[i]; + return best && best->valid ? best : NULL; +} + +/* + * A conservative console mode from 50 to 60 Hz, up to 1920x1080 on + * USB-C. Userspace can select the larger modes, including 2560x1440@60, + * after the sink's EDID is available. + */ +static const struct iboot_timing_mode *iboot_preferred(struct dcp_iboot *ib) +{ + const struct iboot_timing_mode *best = NULL; + + for (unsigned int i = 0; i < ib->nr_tmodes; i++) { + const struct iboot_timing_mode *t = &ib->tmodes[i]; + + /* + * Byte 0 bit 6 marks standard modes a converter adds on its own + * (the J873g PS190 lists 3840x2160 for a 2560x1440 monitor); + * the bootloader's largest mode skips them too. + */ + if (!t->valid || iboot_refresh(t) > 60 || iboot_refresh(t) < 50 || + (t->flags[0] & 0x40) || + (!ib->disp.hdmi && (le32_to_cpu(t->width) > 1920 || + le32_to_cpu(t->height) > 1080)) || + !iboot_mode_fits(ib, t)) + continue; + if (!best || (u64)le32_to_cpu(t->width) * le32_to_cpu(t->height) > + (u64)le32_to_cpu(best->width) * le32_to_cpu(best->height) || + (t->width == best->width && t->height == best->height && + le32_to_cpu(t->fps) > le32_to_cpu(best->fps))) + best = t; + } + return best; +} + +/* + * The sink's EDID modes the firmware also has (mode_valid drops the rest), + * the largest of them preferred: firmware modes the sink does not list, + * such as 1400x1050 on the J873g EV2780, stay black. + */ +static int iboot_edid_get_modes(struct drm_connector *connector) +{ + struct dcp_iboot *ib = to_dcp_iboot(connector->dev); + struct drm_display_mode *mode, *best = NULL; + int count = drm_edid_connector_add_modes(connector); + + mutex_lock(&ib->lock); + list_for_each_entry(mode, &connector->probed_modes, head) { + mode->type &= ~DRM_MODE_TYPE_PREFERRED; + if (!iboot_find_mode(ib, mode)) + continue; + if (!best || mode->hdisplay * mode->vdisplay > + best->hdisplay * best->vdisplay || + (mode->hdisplay * mode->vdisplay == + best->hdisplay * best->vdisplay && + drm_mode_vrefresh(mode) > drm_mode_vrefresh(best))) + best = mode; + } + if (best) + best->type |= DRM_MODE_TYPE_PREFERRED; + mutex_unlock(&ib->lock); + return count; +} + +static int iboot_connector_get_modes(struct drm_connector *connector) +{ + struct dcp_iboot *ib = to_dcp_iboot(connector->dev); + const struct iboot_timing_mode *preferred; + int count = 0; + + drm_edid_connector_update(connector, ib->edid); + if (ib->edid) + return iboot_edid_get_modes(connector); + + /* Without an EDID, the firmware's list. */ + mutex_lock(&ib->lock); + preferred = iboot_preferred(ib); + for (unsigned int i = 0; i < ib->nr_tmodes; i++) { + const struct iboot_timing_mode *t = &ib->tmodes[i]; + struct drm_display_mode *mode; + + if (!t->valid || !iboot_mode_fits(ib, t)) + continue; + mode = drm_cvt_mode(connector->dev, le32_to_cpu(t->width), + le32_to_cpu(t->height), iboot_refresh(t), + false, false, false); + if (!mode) + continue; + if (t == preferred) + mode->type |= DRM_MODE_TYPE_PREFERRED; + drm_mode_probed_add(connector, mode); + count++; + } + mutex_unlock(&ib->lock); + return count; +} + +static enum drm_mode_status +iboot_connector_mode_valid(struct drm_connector *connector, + const struct drm_display_mode *mode) +{ + struct dcp_iboot *ib = to_dcp_iboot(connector->dev); + + return iboot_find_mode(ib, mode) ? MODE_OK : MODE_NOMODE; +} + +static const struct drm_connector_helper_funcs iboot_connector_helper = { + .get_modes = iboot_connector_get_modes, + .mode_valid = iboot_connector_mode_valid, +}; + +static int iboot_set_mode_locked(struct dcp_iboot *ib, + const struct iboot_timing_mode *t, + const struct iboot_color_mode *c); + +/* With ib->lock held; queued work will observe the cleared pending slot. */ +static void iboot_cancel_swap_locked(struct dcp_iboot *ib) +{ + hrtimer_cancel(&ib->swap_timer); + ib->pending = -1; +} + +/* Read the sink's EDID through the PHY, if it can, and keep it. */ +void dcp_iboot_update_edid(struct dcp_iboot *ib) +{ + const struct drm_edid *edid = NULL; + u8 *buf; + int len; + + if (!ib->disp.phy->read_edid) + return; + buf = kzalloc(4 * EDID_LENGTH, GFP_KERNEL); + if (!buf) + return; + len = ib->disp.phy->read_edid(&ib->disp, buf, 4 * EDID_LENGTH); + if (len >= EDID_LENGTH) { + edid = drm_edid_alloc(buf, len); + if (edid && !drm_edid_valid(edid)) { + drm_edid_free(edid); + edid = NULL; + } + } + if (!edid) + dev_warn(ib->dcp->dev, "no EDID: %d\n", len); + else + dev_info(ib->dcp->dev, "EDID: %d bytes\n", len); + drm_edid_free(ib->edid); + ib->edid = edid; + kfree(buf); +} + +static enum drm_connector_status +iboot_connector_detect(struct drm_connector *connector, bool force) +{ + struct dcp_iboot *ib = to_dcp_iboot(connector->dev); + struct t8152_display *disp = &ib->disp; + struct apple_dcp *dcp = ib->dcp; + enum drm_connector_status status; + bool flipped = false; + int hpd; + + mutex_lock(&ib->lock); + t8152_hdmi_port_poll(disp); + if (disp->hpd_gpio) { + hpd = gpiod_get_value_cansleep(disp->hpd_gpio); + } else if (disp->phy->detect) { + hpd = disp->phy->detect(disp, &flipped); + } else { + status = ib->nr_tmodes ? connector_status_connected : + connector_status_disconnected; + goto out; + } + if (hpd < 0) { + status = connector_status_unknown; + goto out; + } + if (hpd != disp->hpd) { + dev_info(dcp->dev, "sink %s\n", hpd ? "plugged" : "unplugged"); + disp->hpd = hpd; + /* + * USB-C: the DPTX port's HPD follows the port's Type-C state, + * and a new plug may come the other way round. + */ + if (disp->usbc) { + if (!hpd || ib->powered) { + iboot_cancel_swap_locked(ib); + if (t8152_dptx_disconnect(disp, 0)) + dev_err(dcp->dev, "DPTX release failed\n"); + if (!ibootep_set_power(dcp, false)) { + ib->powered = false; + ib->mode_set = false; + disp->phy->deactivate(disp); + } + } + /* + * A plug while the display stayed on (unplug and plug + * between two polls): start the PHY cold again, the + * new plug may come the other way round. + */ + if (hpd) + disp->phy->deactivate(disp); + /* The sink may be on another port now. */ + if (hpd && disp->phy->select) + disp->phy->select(disp); + if (hpd && disp->phy->set_orientation) + disp->phy->set_orientation(disp, flipped); + /* The firmware talks AUX as soon as it sees HPD. */ + if (hpd && disp->phy->activate(disp)) + dev_err(dcp->dev, "PHY activation failed\n"); + if (hpd && t8152_dptx_connect(disp, 0)) + dev_err(dcp->dev, "DPTX connect failed\n"); + if (hpd && t8152_dptx_set_hpd(disp, 0, true)) + dev_err(dcp->dev, "DPTX HPD update failed\n"); + } + /* A new sink: the firmware reads its EDID, take the new lists. */ + if (hpd && (dcp_iboot_wait_hpd(ib) || dcp_iboot_get_modes(ib))) { + dev_err(dcp->dev, "no modes from the new sink\n"); + ib->nr_tmodes = 0; + ib->nr_cmodes = 0; + /* A sleeping EIZO may need its link started anew. */ + if (disp->usbc && !disp->on_hdmi && + time_after(jiffies, ib->relink_time + 60 * HZ)) { + ib->relink_time = jiffies; + schedule_work(&ib->relink_work); + } + } + /* + * The EDID once the firmware has read it, so the sink's DDC + * answers, and before SET_MODE: reading it borrows the AUX path + * while the firmware does no AUX. + */ + if (hpd && ib->nr_tmodes) + dcp_iboot_update_edid(ib); + /* + * A fast reconnect can finish before userspace disables the CRTC. + * Restore its requested state even though unplug powered it off. + */ + if (hpd && ib->enabled && ib->cur_mode.valid) { + const struct iboot_timing_mode *t = NULL; + const struct iboot_color_mode *c = iboot_find_color(ib); + int ret = 0; + + for (unsigned int i = 0; i < ib->nr_tmodes; i++) { + const struct iboot_timing_mode *candidate = &ib->tmodes[i]; + + if (candidate->valid && candidate->width == ib->cur_mode.width && + candidate->height == ib->cur_mode.height && + candidate->fps == ib->cur_mode.fps) { + t = candidate; + break; + } + } + if (t && c && !ib->powered) { + ret = ibootep_set_surface(dcp, ib->scan_dva[ib->front], + le32_to_cpu(t->width), + le32_to_cpu(t->height), + ALIGN(le32_to_cpu(t->width) * 4, 64)); + if (!ret) + ret = ibootep_set_power(dcp, true); + ib->powered = !ret; + } + if (t && c && !ret) + iboot_set_mode_locked(ib, t, c); + } + } + status = hpd && ib->nr_tmodes ? connector_status_connected : + connector_status_disconnected; +out: + mutex_unlock(&ib->lock); + return status; +} + +static const struct drm_connector_funcs iboot_connector_funcs = { + .detect = iboot_connector_detect, + .fill_modes = drm_helper_probe_single_connector_modes, + .destroy = drm_connector_cleanup, + .reset = drm_atomic_helper_connector_reset, + .atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state, + .atomic_destroy_state = drm_atomic_helper_connector_destroy_state, +}; + +static int iboot_plane_atomic_check(struct drm_plane *plane, + struct drm_atomic_commit *state) +{ + struct drm_plane_state *new = drm_atomic_get_new_plane_state(state, plane); + struct dcp_iboot *ib = to_dcp_iboot(plane->dev); + struct drm_crtc_state *crtc_state = NULL; + u32 width, height; + int ret; + + if (new->crtc) + crtc_state = drm_atomic_get_new_crtc_state(state, new->crtc); + /* The surface fills the whole mode; no scaling or positioning. */ + ret = drm_atomic_helper_check_plane_state(new, crtc_state, + DRM_PLANE_NO_SCALING, + DRM_PLANE_NO_SCALING, + false, false); + if (ret || !new->visible) + return ret; + /* The helper clips src/dst; raw src_w/src_h may exceed the CRTC. */ + if ((new->src.x1 | new->src.y1 | new->src.x2 | new->src.y2) & 0xffff) + return -EINVAL; + width = drm_rect_width(&new->src) >> 16; + height = drm_rect_height(&new->src) >> 16; + return (u64)ALIGN(width * 4, 64) * height <= ib->scan[0].size ? 0 : -EINVAL; +} + +static void iboot_rect_grow(struct drm_rect *r, const struct drm_rect *add) +{ + if (!drm_rect_visible(r)) { + *r = *add; + return; + } + r->x1 = min(r->x1, add->x1); + r->y1 = min(r->y1, add->y1); + r->x2 = max(r->x2, add->x2); + r->y2 = max(r->y2, add->y2); +} + +/* The current mode's refresh period, from its exact 16.16 rate. */ +static s64 iboot_period_ns(struct dcp_iboot *ib) +{ + u32 fps = le32_to_cpu(ib->cur_mode.fps); + + if (fps < (24 << 16)) + fps = 60 << 16; + return div64_u64((u64)NSEC_PER_SEC << 16, fps); +} + +/* Whether a frame may be shown: the display is on, set up and alive. */ +static bool iboot_scanning_locked(struct dcp_iboot *ib) +{ + struct apple_rtkit *rtk = READ_ONCE(ib->dcp->rtk); + + return ib->powered && ib->mode_set && ib->disp.hpd && rtk && + !apple_rtkit_is_crashed(rtk); +} + +/* Show scan[buf]. Called with ib->lock held. */ +static void iboot_swap_locked(struct dcp_iboot *ib, unsigned int buf, u32 w, + u32 h, u32 pitch) +{ + int ret; + + if (!iboot_scanning_locked(ib)) + return; + + /* The pipe must see the whole frame before it is swapped in. */ + wmb(); + ret = ibootep_set_surface(ib->dcp, ib->scan_dva[buf], w, h, pitch); + if (ret) { + /* Still on the old buffer, which misses this frame. */ + dev_err_ratelimited(ib->dcp->dev, "swap failed: %d\n", ret); + ib->stale[ib->front] = DRM_RECT_INIT(0, 0, INT_MAX / 2, INT_MAX / 2); + return; + } + ib->last_swap = ktime_get(); + ib->retired[ib->front] = ib->last_swap; + ib->front = buf; +} + +static void iboot_swap_work(struct work_struct *work) +{ + struct dcp_iboot *ib = container_of(work, struct dcp_iboot, swap_work); + + mutex_lock(&ib->lock); + if (ib->pending >= 0) { + iboot_swap_locked(ib, ib->pending, ib->pending_w, + ib->pending_h, ib->pending_pitch); + ib->pending = -1; + } + mutex_unlock(&ib->lock); +} + +static enum hrtimer_restart iboot_swap_timer(struct hrtimer *t) +{ + struct dcp_iboot *ib = container_of(t, struct dcp_iboot, swap_timer); + + queue_work(system_highpri_wq, &ib->swap_work); + return HRTIMER_NORESTART; +} + +/* + * Copy the frame into a scanout buffer that is not on screen and show it. + * That buffer already holds an older frame: copy this frame's damage and + * what changed since that buffer was last written. + * + * SET_SURFACE returns before the pipe takes the buffer at its next frame + * start, and there is no vblank interrupt. Several swaps within one refresh + * let an older frame stay on screen (a cursor that jumps back), so swaps are + * spaced one refresh apart: a frame that comes sooner waits in a pending + * buffer, which a newer frame overwrites, and a timer swaps it in. The + * commit itself never waits, so a client's next frame is not held up. + */ +static void iboot_plane_atomic_update(struct drm_plane *plane, + struct drm_atomic_commit *state) +{ + struct drm_plane_state *old = drm_atomic_get_old_plane_state(state, plane); + struct drm_plane_state *new = drm_atomic_get_new_plane_state(state, plane); + struct drm_shadow_plane_state *shadow = to_drm_shadow_plane_state(new); + struct dcp_iboot *ib = to_dcp_iboot(plane->dev); + struct drm_framebuffer *fb = new->fb; + struct drm_atomic_helper_damage_iter iter; + struct drm_rect clip, source_clip, src, full, damage = { 0, 0, 0, 0 }; + unsigned int pitch, back; + struct iosys_map dst; + s64 period, since; + + if (!fb || !new->visible) + return; + src = DRM_RECT_INIT(new->src.x1 >> 16, new->src.y1 >> 16, + drm_rect_width(&new->src) >> 16, + drm_rect_height(&new->src) >> 16); + full = DRM_RECT_INIT(0, 0, drm_rect_width(&src), drm_rect_height(&src)); + pitch = ALIGN(drm_rect_width(&full) * 4, 64); + drm_atomic_helper_damage_iter_init(&iter, old, new); + drm_atomic_for_each_plane_damage(&iter, &clip) { + if (!drm_rect_intersect(&clip, &src)) + continue; + drm_rect_translate(&clip, -src.x1, -src.y1); + iboot_rect_grow(&damage, &clip); + } + if (!drm_rect_visible(&damage)) + return; + + mutex_lock(&ib->lock); + if (!iboot_scanning_locked(ib)) + goto out; + period = iboot_period_ns(ib); + if (!READ_ONCE(buffered)) { + /* Into the buffer on screen (tears during motion). */ + back = ib->front; + } else if (ib->pending >= 0) { + back = ib->pending; + } else { + /* The other buffer that left the screen first. */ + unsigned int a = (ib->front + 1) % DCP_IBOOT_SCANOUT_BUFS; + unsigned int b = (ib->front + 2) % DCP_IBOOT_SCANOUT_BUFS; + s64 wait; + + back = ktime_before(ib->retired[a], ib->retired[b]) ? a : b; + /* Off screen for a full refresh: only after a mode change. */ + wait = period - ktime_to_ns(ktime_sub(ktime_get(), ib->retired[back])); + if (ib->mode_set && wait > 0) + usleep_range(div_s64(wait, NSEC_PER_USEC), + div_s64(wait, NSEC_PER_USEC) + 100); + } + clip = ib->stale[back]; + iboot_rect_grow(&clip, &damage); + if (drm_rect_intersect(&clip, &full)) { + iosys_map_set_vaddr(&dst, ib->scan_wc[back]); + iosys_map_incr(&dst, drm_fb_clip_offset(pitch, fb->format, &clip)); + source_clip = clip; + drm_rect_translate(&source_clip, src.x1, src.y1); + drm_fb_memcpy(&dst, &pitch, shadow->data, fb, &source_clip); + } + ib->stale[back] = (struct drm_rect){ 0, 0, 0, 0 }; + for (unsigned int i = 0; i < DCP_IBOOT_SCANOUT_BUFS; i++) + if (i != back) + iboot_rect_grow(&ib->stale[i], &damage); + if (back == ib->front) + goto out; + + since = ktime_to_ns(ktime_sub(ktime_get(), ib->last_swap)); + if (ib->pending < 0 && (!ib->mode_set || since >= period)) { + iboot_swap_locked(ib, back, drm_rect_width(&full), + drm_rect_height(&full), pitch); + goto out; + } + ib->pending_w = drm_rect_width(&full); + ib->pending_h = drm_rect_height(&full); + ib->pending_pitch = pitch; + if (ib->pending < 0) { + ib->pending = back; + hrtimer_start(&ib->swap_timer, ktime_add_ns(ib->last_swap, period), + HRTIMER_MODE_ABS); + } +out: + mutex_unlock(&ib->lock); +} + +static const struct drm_plane_helper_funcs iboot_plane_helper = { + DRM_GEM_SHADOW_PLANE_HELPER_FUNCS, + .atomic_check = iboot_plane_atomic_check, + .atomic_update = iboot_plane_atomic_update, +}; + +static const struct drm_plane_funcs iboot_plane_funcs = { + .update_plane = drm_atomic_helper_update_plane, + .disable_plane = drm_atomic_helper_disable_plane, + .destroy = drm_plane_cleanup, + DRM_GEM_SHADOW_PLANE_FUNCS, +}; + +static int iboot_crtc_atomic_check(struct drm_crtc *crtc, + struct drm_atomic_commit *state) +{ + struct drm_crtc_state *new = drm_atomic_get_new_crtc_state(state, crtc); + struct dcp_iboot *ib = to_dcp_iboot(crtc->dev); + + /* + * No vblank interrupt: page-flip events come from a timer at the + * mode's refresh rate (drm_vblank_helper), so a compositor and its + * clients render once per refresh instead of as fast as commits + * complete. A commit that leaves the CRTC off gets no flush + * (commit_tail_rpm flushes active CRTCs only), so its event goes out + * at once, as before. + */ + new->no_vblank = !new->active; + if (new->enable && !iboot_find_mode(ib, &new->mode)) + return -EINVAL; + return 0; +} + +/* SET_MODE, then the scanout buffer with the new mode's geometry. */ +static int iboot_set_mode_locked(struct dcp_iboot *ib, + const struct iboot_timing_mode *t, + const struct iboot_color_mode *c) +{ + int ret; + + /* + * Right after power on the firmware may still train the link, and it + * fails SET_MODE with an error status until the link is up. It sends + * no message once it is: the DPTX calls it makes while training (link + * configuration, rate, lane count) have no last one, and a sink can + * be trained twice in a row. So SET_MODE is retried. In the traced + * J873g modesets the link was up 76 to 229 ms after power on; one + * failed SET_MODE takes about 200 ms itself, so 200 ms between tries + * cover a second training, and five tries give up after about two + * seconds. On USB-C the DP alt mode reentry below takes over then. + */ + for (int i = 0; i < 5; i++) { + ret = ibootep_set_mode(ib->dcp, t, c); + if (ret != -EIO) + break; + msleep(200); + } + if (ret) { + dev_err(ib->dcp->dev, "set_mode failed: %d\n", ret); + /* + * USB-C: a sink that no longer answers AUX (seen after the + * monitor's deep sleep) is connected anew: its link is + * released, and the plug that follows starts the PHY cold + * and sets the mode again. At most once a minute, so a dead + * sink does not loop. + */ + if (ib->disp.usbc && !ib->disp.on_hdmi && + time_after(jiffies, ib->relink_time + 60 * HZ)) { + ib->cur_mode = *t; + ib->mode_failed = true; + ib->relink_time = jiffies; + schedule_work(&ib->relink_work); + } + return ret; + } + ib->cur_mode = *t; + ib->mode_set = true; + ib->mode_failed = false; + /* The buffers hold the old geometry: the next frame is copied whole. */ + for (unsigned int i = 0; i < DCP_IBOOT_SCANOUT_BUFS; i++) + ib->stale[i] = DRM_RECT_INIT(0, 0, INT_MAX / 2, INT_MAX / 2); + /* A pending frame has the old geometry. */ + iboot_cancel_swap_locked(ib); + /* As the bootloader swaps after a modeset. */ + ret = ibootep_set_surface(ib->dcp, ib->scan_dva[ib->front], + le32_to_cpu(t->width), le32_to_cpu(t->height), + ALIGN(le32_to_cpu(t->width) * 4, 64)); + if (ret) + dev_err(ib->dcp->dev, "set_surface failed: %d\n", ret); + return ret; +} + +/* + * The boot mode again: a display powered on without SET_MODE counts as idle + * to the firmware's AV stack, which powers the link off after 30 s. + */ +int dcp_iboot_set_boot_mode(struct dcp_iboot *ib) +{ + const struct iboot_timing_mode *best = NULL; + const struct iboot_color_mode *c; + int ret = -ENOENT; + + mutex_lock(&ib->lock); + for (unsigned int i = 0; i < ib->nr_tmodes; i++) { + const struct iboot_timing_mode *t = &ib->tmodes[i]; + + if (!t->valid || le32_to_cpu(t->width) != ib->boot_w || + le32_to_cpu(t->height) != ib->boot_h || + iboot_refresh(t) > 60) + continue; + if (!best || le32_to_cpu(t->fps) > le32_to_cpu(best->fps)) + best = t; + } + c = iboot_find_color(ib); + if (best && c) + ret = iboot_set_mode_locked(ib, best, c); + mutex_unlock(&ib->lock); + return ret; +} + +/* + * The DCPAV service starts the firmware's idle power off timer when its video + * interface comes up: until a SET_MODE follows, it counts the powered-on + * display as idle and takes the link down 30 s later. The probe's SET_MODE + * comes before the interface starts, so one follows it here. + */ +void dcp_iboot_reset_mode(struct dcp_iboot *ib) +{ + const struct iboot_color_mode *c; + + mutex_lock(&ib->lock); + c = iboot_find_color(ib); + if (c && ib->powered && ib->mode_set) + iboot_set_mode_locked(ib, &ib->cur_mode, c); + mutex_unlock(&ib->lock); +} + +/* + * From the AFK receive work of the DPAV endpoint: let the firmware finish + * opening the interface before the SET_MODE, which waits for a reply that + * another endpoint's receive work completes. + */ +void dcp_iboot_av_started(struct dcp_iboot *ib) +{ + queue_delayed_work(system_percpu_wq, &ib->av_work, msecs_to_jiffies(1000)); +} + +static void iboot_crtc_atomic_enable(struct drm_crtc *crtc, + struct drm_atomic_commit *state) +{ + struct drm_crtc_state *new = drm_atomic_get_new_crtc_state(state, crtc); + struct dcp_iboot *ib = to_dcp_iboot(crtc->dev); + struct apple_dcp *dcp = ib->dcp; + const struct iboot_timing_mode *t; + const struct iboot_color_mode *c; + int ret; + + mutex_lock(&ib->lock); + t = iboot_find_mode(ib, &new->mode); + c = iboot_find_color(ib); + if (!t || !c) + goto out; + ib->enabled = true; + if (!ib->powered) { + /* The PHY starts cold first; the firmware then trains. */ + ret = ib->disp.phy->activate(&ib->disp); + if (ret) { + dev_err(dcp->dev, "PHY activation failed: %d\n", ret); + goto out; + } + /* A pipe powered on without a surface fetches from a null base. */ + ret = ibootep_set_surface(dcp, ib->scan_dva[ib->front], + le32_to_cpu(t->width), le32_to_cpu(t->height), + ALIGN(le32_to_cpu(t->width) * 4, 64)); + if (ret) { + dev_err(dcp->dev, "set_surface failed: %d\n", ret); + goto out; + } + ret = ibootep_set_power(dcp, true); + if (ret) { + dev_err(dcp->dev, "set_power failed: %d\n", ret); + goto out; + } + ib->powered = true; + } + if (ib->mode_set && !memcmp(t, &ib->cur_mode, sizeof(*t))) + goto out; + dev_info(dcp->dev, "modeset %ux%u@%d\n", le32_to_cpu(t->width), + le32_to_cpu(t->height), iboot_refresh(t)); + /* + * As the bootloader configures a display: query the sink and both mode + * lists again before SET_MODE, and look the mode up in the fresh list. + * The DPTX port stays connected; reconnecting it here drops the link + * and the HDMI firmware then fails SET_MODE. + */ + ret = ibootep_set_power(dcp, true); + if (!ret) + ret = ibootep_get_hpd(dcp, NULL, NULL) < 0; + if (!ret) + ret = dcp_iboot_get_modes(ib); + if (ret) + dev_err(dcp->dev, "refreshing the modes failed: %d\n", ret); + t = iboot_find_mode(ib, &new->mode); + c = iboot_find_color(ib); + if (!t || !c) + goto out; + iboot_set_mode_locked(ib, t, c); +out: + mutex_unlock(&ib->lock); + drm_crtc_vblank_on(crtc); +} + +static void iboot_crtc_atomic_disable(struct drm_crtc *crtc, + struct drm_atomic_commit *state) +{ + struct drm_crtc_state *new = drm_atomic_get_new_crtc_state(state, crtc); + struct dcp_iboot *ib = to_dcp_iboot(crtc->dev); + int ret, idx; + + drm_crtc_vblank_off(crtc); + /* A mode change: SET_MODE alone switches, as before. */ + if (new->active) + return; + /* + * After an unbind the firmware session is retained as it is, and the + * shutdown commit only releases the state. + */ + if (!drm_dev_enter(crtc->dev, &idx)) + return; + /* + * Display off (DPMS, blanking): the firmware stops the pipe and the + * monitor goes to sleep. The next enable sets the mode again. + */ + mutex_lock(&ib->lock); + ib->enabled = false; + iboot_cancel_swap_locked(ib); + if (ib->powered) { + ret = ibootep_set_power(ib->dcp, false); + if (ret) { + dev_err(ib->dcp->dev, "set_power off failed: %d\n", ret); + } else { + dev_info(ib->dcp->dev, "display off\n"); + /* Nothing scans out: power the PHY down as well. */ + if (!ib->disp.phy->deactivate(&ib->disp)) + ib->disp.port[0].link_rate = 0; + } + ib->powered = !!ret; + ib->mode_set = false; + } + mutex_unlock(&ib->lock); + drm_dev_exit(idx); +} + +static const struct drm_crtc_helper_funcs iboot_crtc_helper = { + .atomic_check = iboot_crtc_atomic_check, + .atomic_flush = drm_crtc_vblank_atomic_flush, + .atomic_enable = iboot_crtc_atomic_enable, + .atomic_disable = iboot_crtc_atomic_disable, +}; + +static const struct drm_crtc_funcs iboot_crtc_funcs = { + .reset = drm_atomic_helper_crtc_reset, + .destroy = drm_crtc_cleanup, + .set_config = drm_atomic_helper_set_config, + .page_flip = drm_atomic_helper_page_flip, + .atomic_duplicate_state = drm_atomic_helper_crtc_duplicate_state, + .atomic_destroy_state = drm_atomic_helper_crtc_destroy_state, + DRM_CRTC_VBLANK_TIMER_FUNCS, +}; + +static const struct drm_encoder_funcs iboot_encoder_funcs = { + .destroy = drm_encoder_cleanup, +}; + +/* Modeset before the plane update, which copies at the new geometry. */ +static const struct drm_mode_config_helper_funcs iboot_mode_config_helpers = { + .atomic_commit_tail = drm_atomic_helper_commit_tail_rpm, +}; + +static const struct drm_mode_config_funcs iboot_mode_config_funcs = { + /* fbdev writes reach the scanout buffer through the dirty damage */ + .fb_create = drm_gem_fb_create_with_dirty, + .atomic_check = drm_atomic_helper_check, + .atomic_commit = drm_atomic_helper_commit, +}; + +/* + * Release the link of a USB-C sink that does not answer, and have the port's + * sink plugged again: the port's Type-C state still shows it, so the next + * look at the ports connects it as a new one. + */ +static void iboot_relink_work(struct work_struct *work) +{ + struct dcp_iboot *ib = container_of(work, struct dcp_iboot, relink_work); + struct t8152_display *disp = &ib->disp; + int ret; + + dev_info(ib->dcp->dev, "USB-C sink does not answer, connecting it again\n"); + mutex_lock(&ib->lock); + iboot_cancel_swap_locked(ib); + ret = t8152_dptx_disconnect(disp, 0); + if (!ret) + ret = ibootep_set_power(ib->dcp, false); + if (!ret) { + ib->powered = false; + ib->mode_set = false; + ret = disp->phy->deactivate(disp); + } + if (ret) { + mutex_unlock(&ib->lock); + dev_err(ib->dcp->dev, "cannot release old DP link: %d\n", ret); + return; + } + disp->hpd = 0; + mutex_unlock(&ib->lock); + drm_kms_helper_hotplug_event(&ib->drm); + dcp_iboot_hpd_event(ib); +} + +static void iboot_hpd_work(struct work_struct *work) +{ + struct dcp_iboot *ib = container_of(to_delayed_work(work), struct dcp_iboot, + hpd_work); + + if (!READ_ONCE(ib->ready)) + return; + drm_helper_hpd_irq_event(&ib->drm); + /* + * USB-C changes come from the ports' display switches. The HDMI port's + * HPD line has no interrupt: poll it while this DCP can take the port. + */ + if (READ_ONCE(ib->ready) && ib->disp.hdmi_port) + queue_delayed_work(system_freezable_wq, &ib->hpd_work, + msecs_to_jiffies(250)); +} + +/* + * A USB-C port's Type-C state changed: look at the ports shortly. A HPD pulse + * the port driver learns of after the fact comes as HPD low and high at once; + * the delay takes both together. + */ +void dcp_iboot_hpd_event(struct dcp_iboot *ib) +{ + if (READ_ONCE(ib->ready)) + mod_delayed_work(system_freezable_wq, &ib->hpd_work, + msecs_to_jiffies(100)); +} + +void dcp_iboot_kms_stop(struct dcp_iboot *ib) +{ + if (!ib->kms_work_ready) + return; + + cancel_delayed_work_sync(&ib->hpd_work); + hrtimer_cancel(&ib->swap_timer); + cancel_work_sync(&ib->swap_work); + cancel_work_sync(&ib->relink_work); +} + +static void iboot_swap_stop(void *data) +{ + dcp_iboot_kms_stop(data); +} + +int dcp_iboot_kms_init(struct dcp_iboot *ib) +{ + struct drm_device *drm = &ib->drm; + u32 max_w = 3840, max_h = 2160; + int ret; + + ib->pending = -1; + INIT_WORK(&ib->swap_work, iboot_swap_work); + INIT_WORK(&ib->relink_work, iboot_relink_work); + INIT_DELAYED_WORK(&ib->hpd_work, iboot_hpd_work); + hrtimer_setup(&ib->swap_timer, iboot_swap_timer, CLOCK_MONOTONIC, + HRTIMER_MODE_ABS); + ib->kms_work_ready = true; + ret = devm_add_action_or_reset(ib->dcp->dev, iboot_swap_stop, ib); + if (ret) + return ret; + + for (unsigned int i = 0; i < ib->nr_tmodes; i++) { + max_w = max(max_w, le32_to_cpu(ib->tmodes[i].width)); + max_h = max(max_h, le32_to_cpu(ib->tmodes[i].height)); + } + + ret = drmm_mode_config_init(drm); + if (ret) + return ret; + ib->relink_time = jiffies - 61 * HZ; + + drm->mode_config.min_width = 320; + drm->mode_config.min_height = 240; + drm->mode_config.max_width = max_w; + drm->mode_config.max_height = max_h; + drm->mode_config.preferred_depth = 24; + drm->mode_config.funcs = &iboot_mode_config_funcs; + drm->mode_config.helper_private = &iboot_mode_config_helpers; + + ret = drm_universal_plane_init(drm, &ib->plane, 0, &iboot_plane_funcs, + dcp_iboot_formats, ARRAY_SIZE(dcp_iboot_formats), + NULL, DRM_PLANE_TYPE_PRIMARY, NULL); + if (ret) + return ret; + drm_plane_helper_add(&ib->plane, &iboot_plane_helper); + drm_plane_enable_fb_damage_clips(&ib->plane); + + ret = drm_crtc_init_with_planes(drm, &ib->crtc, &ib->plane, NULL, + &iboot_crtc_funcs, NULL); + if (ret) + return ret; + drm_crtc_helper_add(&ib->crtc, &iboot_crtc_helper); + + ret = drm_vblank_init(drm, 1); + if (ret) + return ret; + + ret = drm_encoder_init(drm, &ib->encoder, &iboot_encoder_funcs, + DRM_MODE_ENCODER_TMDS, NULL); + if (ret) + return ret; + ib->encoder.possible_crtcs = drm_crtc_mask(&ib->crtc); + + ret = drm_connector_init(drm, &ib->connector, &iboot_connector_funcs, + ib->disp.hdmi ? DRM_MODE_CONNECTOR_HDMIA : + DRM_MODE_CONNECTOR_DisplayPort); + if (ret) + return ret; + drm_connector_helper_add(&ib->connector, &iboot_connector_helper); + if (ib->disp.hpd_gpio || ib->disp.usbc) + ib->connector.polled = DRM_CONNECTOR_POLL_CONNECT | + DRM_CONNECTOR_POLL_DISCONNECT; + if (ib->disp.usbc) + ib->connector.polled = DRM_CONNECTOR_POLL_HPD; + ret = drm_connector_attach_encoder(&ib->connector, &ib->encoder); + if (ret) + return ret; + + drm_mode_config_reset(drm); + return 0; +} diff --git a/drivers/gpu/drm/apple/ibootep.c b/drivers/gpu/drm/apple/ibootep.c index 7f90f68bf26f64..1a12fb947d2ccf 100644 --- a/drivers/gpu/drm/apple/ibootep.c +++ b/drivers/gpu/drm/apple/ibootep.c @@ -22,9 +22,12 @@ #define IBOOT_PATTERN_STRIDE DCPEXT_STRIDE enum iboot_query_op { + IBOOT_SET_SURFACE = 1, + IBOOT_SET_POWER = 2, IBOOT_GET_HPD = 3, IBOOT_GET_TIMING_MODES = 4, IBOOT_GET_COLOR_MODES = 5, + IBOOT_SET_MODE = 6, }; /* Packed layouts from m1n1 src/dcp_iboot.h and swap_set_layer_cmd_v13_3. */ @@ -148,15 +151,25 @@ static int iboot_parse_swap_begin(const u8 *reply, size_t received, u32 *id) return 0; } -static int iboot_parse_modes(const u8 *payload, size_t size, u32 *count) +/* A mode list: a count, then as many 24-byte records. */ +static int iboot_parse_mode_count(const u8 *payload, size_t size, u32 *count) { - u32 i; - if (size < 4) return -EPROTO; *count = get_unaligned_le32(payload); if (*count > (size - 4) / IBOOT_MODE_SIZE) return -EPROTO; + return 0; +} + +static int iboot_parse_modes(const u8 *payload, size_t size, u32 *count) +{ + u32 i; + int ret; + + ret = iboot_parse_mode_count(payload, size, count); + if (ret) + return ret; for (i = 0; i < *count; i++) if (get_unaligned_le32(payload + 4 + i * IBOOT_MODE_SIZE) > 1) return -EPROTO; @@ -234,7 +247,13 @@ static int iboot_build_pattern_request(u32 op, const void *data, size_t data_siz size_t expected; switch (op) { + case 1: /* SetSurface */ + expected = sizeof(struct iboot_layer); + break; case 2: expected = 1; break; /* SetPower */ + case 3 ... 5: /* GetHPD, GetTimingModes, GetColorModes */ + expected = 0; + break; case 6: expected = 2 * IBOOT_MODE_SIZE; break; /* SetMode */ case 15: expected = 0; break; /* SwapBegin */ case 16: expected = sizeof(struct iboot_swap_layer_v13_3); break; @@ -401,7 +420,7 @@ static struct iboot_query *iboot_find_query(struct apple_dcp *dcp) struct apple_dcp_afkep *ep = READ_ONCE(dcp->ibootep); u32 i; - if (!dcp->external || !ep) + if ((!dcp->external && !dcp_is_iboot(dcp)) || !ep) return ERR_PTR(-ENODEV); for (i = 0; i < AFK_MAX_CHANNEL; i++) { struct iboot_query *query = smp_load_acquire(&ep->services[i].cookie); @@ -668,6 +687,157 @@ int ibootep_present_pattern(struct apple_dcp *dcp, u64 iova, size_t size, u32 st return ret; } +/* + * One display command of the iBoot interface, with its reply payload copied + * to @out (at least @min_size bytes of it; returns the bytes copied), or a + * setter if @out is NULL. On AFKv2 the setters answer with a transport + * status alone: given a reply buffer, the firmware copies an empty reply + * into it and asserts, so they go out without one. Only the reply's own + * length is checked, not that its first word repeats @op. + */ +static int iboot_command(struct apple_dcp *dcp, u32 op, const void *data, + size_t size, void *out, size_t out_size, size_t min_size) +{ + struct iboot_query *query = iboot_find_query(dcp); + u8 request[16 + sizeof(struct iboot_swap_layer_v13_3)]; + size_t len, received = 0; + u32 retcode = 0, reply_len; + u8 *reply = NULL; + int ret; + + if (IS_ERR(query)) + return PTR_ERR(query); + ret = iboot_build_pattern_request(op, data, size, request, + sizeof(request), &len); + if (ret) + return ret; + if (out || !query->service->ep->wire_v2) { + reply = kzalloc(IBOOT_QUERY_RX_SIZE, GFP_KERNEL); + if (!reply) + return -ENOMEM; + } + ret = afk_send_command_len(query->service, EPIC_SUBTYPE_STD_SERVICE, + request, len, reply, + reply ? IBOOT_QUERY_RX_SIZE : 0, &retcode, + &received); + if (!ret && retcode) { + dev_dbg(dcp->dev, "iBoot command %u returned %#x\n", op, retcode); + ret = -EIO; + } + if (ret || !out) + goto out; + reply_len = received >= 8 ? get_unaligned_le32(reply + 4) : 0; + if (reply_len < 8 || reply_len > received || reply_len - 8 < min_size) { + dev_err(dcp->dev, "iBoot: bad response length for command %u\n", op); + ret = -EPROTO; + goto out; + } + ret = min_t(size_t, reply_len - 8, out_size); + memcpy(out, reply + 8, ret); +out: + kfree(reply); + return ret; +} + +int ibootep_set_power(struct apple_dcp *dcp, bool on) +{ + u8 power = on; + + return iboot_command(dcp, IBOOT_SET_POWER, &power, sizeof(power), NULL, + 0, 0); +} + +int ibootep_get_hpd(struct apple_dcp *dcp, u32 *timings, u32 *colors) +{ + u8 payload[12]; + u32 timing_count, color_count; + bool hpd; + int ret; + + ret = iboot_command(dcp, IBOOT_GET_HPD, NULL, 0, payload, sizeof(payload), + sizeof(payload)); + if (ret >= 0) + ret = iboot_parse_hpd(payload, ret, &hpd, &timing_count, + &color_count); + if (ret) + return ret; + if (timings) + *timings = timing_count; + if (colors) + *colors = color_count; + return hpd; +} + +static int iboot_get_modes(struct apple_dcp *dcp, u32 op, void **modes, + unsigned int *count) +{ + u32 n; + u8 *buf; + int ret; + + buf = kzalloc(IBOOT_QUERY_RX_SIZE, GFP_KERNEL); + if (!buf) + return -ENOMEM; + ret = iboot_command(dcp, op, NULL, 0, buf, IBOOT_QUERY_RX_SIZE, 4); + if (ret >= 0) + ret = iboot_parse_mode_count(buf, ret, &n); + if (!ret) { + *modes = kmemdup(buf + 4, n * IBOOT_MODE_SIZE, GFP_KERNEL); + if (*modes) + *count = n; + else + ret = -ENOMEM; + } + kfree(buf); + return ret; +} + +int ibootep_get_timing_modes(struct apple_dcp *dcp, + struct iboot_timing_mode **modes, + unsigned int *count) +{ + return iboot_get_modes(dcp, IBOOT_GET_TIMING_MODES, (void **)modes, count); +} + +int ibootep_get_color_modes(struct apple_dcp *dcp, + struct iboot_color_mode **modes, unsigned int *count) +{ + return iboot_get_modes(dcp, IBOOT_GET_COLOR_MODES, (void **)modes, count); +} + +int ibootep_set_mode(struct apple_dcp *dcp, const struct iboot_timing_mode *timing, + const struct iboot_color_mode *color) +{ + struct { + struct iboot_timing_mode timing; + struct iboot_color_mode color; + } __packed mode = { *timing, *color }; + + return iboot_command(dcp, IBOOT_SET_MODE, &mode, sizeof(mode), NULL, 0, 0); +} + +int ibootep_set_surface(struct apple_dcp *dcp, u64 iova, u32 width, u32 height, + u32 stride) +{ + /* One linear BGRA plane, SDR, in colour space 2 as the bootloader sets. */ + struct iboot_layer layer = { + .planes = { { + .addr = cpu_to_le64(iova), + .stride = cpu_to_le32(stride), + .addr_format = cpu_to_le32(1), + } }, + .plane_count = cpu_to_le32(1), + .width = cpu_to_le32(width), + .height = cpu_to_le32(height), + .surface_format = cpu_to_le32(1), + .colorspace = cpu_to_le32(2), + .eotf = cpu_to_le32(1), + }; + + return iboot_command(dcp, IBOOT_SET_SURFACE, &layer, sizeof(layer), NULL, + 0, 0); +} + static ssize_t dcpext_modes_query_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) @@ -699,7 +869,7 @@ static void disp_service_init(struct apple_epic_service *service, const char *na struct iboot_query *query; int ret; - if (!dcp->external) + if (!dcp->external && !dcp_is_iboot(dcp)) return; query = devm_kzalloc(dcp->dev, sizeof(*query), GFP_KERNEL); if (!query) @@ -710,6 +880,16 @@ static void disp_service_init(struct apple_epic_service *service, const char *na ret = devm_add_action_or_reset(dcp->dev, iboot_query_cancel, query); if (ret) return; + /* + * A DCP driven through this interface alone has a display driver that + * sends every command (the exported ibootep_* calls); it takes no + * manual queries next to them. + */ + if (dcp_is_iboot(dcp)) { + /* Published for iboot_find_query()'s acquire. */ + smp_store_release(&service->cookie, query); + return; + } /* Remove the sysfs entry before cancelling work during device cleanup. */ ret = devm_device_add_group(dcp->dev, &iboot_query_group); if (ret) { @@ -741,6 +921,19 @@ static const struct apple_epic_service_ops external_ibootep_ops[] = { {} }; +/* DCP_FIRMWARE_IBOOT: the main DCP's service, or an external one's. */ +static const struct apple_epic_service_ops iboot_variant_ops[] = { + { + .name = "disp0-service", + .init = disp_service_init, + }, + { + .name = "dispext-service", + .init = disp_service_init, + }, + {} +}; + int ibootep_init(struct apple_dcp *dcp) { const struct apple_epic_service_ops *ops = ibootep_ops; @@ -751,6 +944,8 @@ int ibootep_init(struct apple_dcp *dcp) return -EBUSY; if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL) ops = external_ibootep_ops; + if (dcp_is_iboot(dcp)) + ops = iboot_variant_ops; dcp->ibootep = afk_init(dcp, DISP0_ENDPOINT, ops); if (IS_ERR(dcp->ibootep)) { ret = PTR_ERR(dcp->ibootep); diff --git a/drivers/gpu/drm/apple/ibootep.h b/drivers/gpu/drm/apple/ibootep.h index aa44c2f8754e44..aa6ad17a61be17 100644 --- a/drivers/gpu/drm/apple/ibootep.h +++ b/drivers/gpu/drm/apple/ibootep.h @@ -27,4 +27,42 @@ int ibootep_rearm_pattern(struct apple_dcp *dcp); */ int ibootep_present_frame(struct apple_dcp *dcp, u64 iova, size_t size, u32 stride); +/* + * The iBoot interface's display commands, for a DCP driven through it + * (DCP_FIRMWARE_IBOOT) and for the T6030 external role. Sleepable callers + * outside the AFK receive queue; the caller serializes them. + */ +struct iboot_timing_mode { + __le32 valid; + __le32 width; + __le32 height; + __le32 fps; /* 16.16 */ + /* byte 0 bit 6: a standard mode the firmware adds on its own */ + u8 flags[8]; +} __packed; + +struct iboot_color_mode { + __le32 valid; + __le32 colorimetry; + __le32 eotf; + __le32 encoding; + __le32 bpp; + u8 pad[4]; +} __packed; + +int ibootep_set_power(struct apple_dcp *dcp, bool on); +/* 1 with a sink, 0 without; the counts of its timing and colour modes. */ +int ibootep_get_hpd(struct apple_dcp *dcp, u32 *timings, u32 *colors); +/* The sink's mode lists, newly allocated; the caller frees them. */ +int ibootep_get_timing_modes(struct apple_dcp *dcp, + struct iboot_timing_mode **modes, + unsigned int *count); +int ibootep_get_color_modes(struct apple_dcp *dcp, + struct iboot_color_mode **modes, unsigned int *count); +int ibootep_set_mode(struct apple_dcp *dcp, const struct iboot_timing_mode *timing, + const struct iboot_color_mode *color); +/* SET_SURFACE: scan out one linear BGRA plane at @iova. */ +int ibootep_set_surface(struct apple_dcp *dcp, u64 iova, u32 width, u32 height, + u32 stride); + #endif diff --git a/drivers/gpu/drm/apple/iomfb-legacy-methods-test.c b/drivers/gpu/drm/apple/iomfb-legacy-methods-test.c new file mode 100644 index 00000000000000..858cc605639ec3 --- /dev/null +++ b/drivers/gpu/drm/apple/iomfb-legacy-methods-test.c @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Included by the 13.3 IOMFB backend shared by firmware 13.5. */ +#include + +static void iomfb_legacy_required_methods(struct kunit *test) +{ + static const enum dcpep_method required[] = { + dcpep_start_signal, + dcpep_set_digital_out_mode, + dcpep_swap_start, + dcpep_swap_submit, + dcpep_set_power_state, + }; + char empty[sizeof(dcp_methods[0].tag)] = {}; + unsigned int i, j; + + for (i = 0; i < ARRAY_SIZE(required); i++) { + const struct dcp_method_entry *entry = &dcp_methods[required[i]]; + + KUNIT_EXPECT_NOT_NULL(test, entry->name); + KUNIT_EXPECT_MEMNEQ(test, entry->tag, empty, sizeof(entry->tag)); + for (j = 0; j < i; j++) + KUNIT_EXPECT_MEMNEQ(test, entry->tag, dcp_methods[required[j]].tag, + sizeof(entry->tag)); + } +} + +static struct kunit_case iomfb_legacy_methods_cases[] = { + KUNIT_CASE(iomfb_legacy_required_methods), + {} +}; + +static struct kunit_suite iomfb_legacy_methods_suite = { + .name = "apple-iomfb-legacy-methods", + .test_cases = iomfb_legacy_methods_cases, +}; + +kunit_test_suite(iomfb_legacy_methods_suite); diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 38282c45ba88fc..cfb3f4f984724e 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -37,6 +37,7 @@ #include #include +#include "av.h" #include "cec.h" #include "dcp.h" #include "dcp-hdr-metadata.h" @@ -349,17 +350,22 @@ static u16 dcp_packet_start(struct dcp_channel *ch, u8 depth) /* Pushes and pops the depth of the call stack with safety checks */ static u8 dcp_push_depth(u8 *depth) { - u8 ret = (*depth)++; + u8 ret = *depth; WARN_ON(ret >= DCP_MAX_CALL_DEPTH); + WRITE_ONCE(*depth, ret + 1); return ret; } static u8 dcp_pop_depth(u8 *depth) { - WARN_ON((*depth) == 0); + u8 val = *depth; - return --(*depth); + WARN_ON(val == 0); + val--; + /* Pair with iomfb_channels_idle() so callers observe prior ACK sends. */ + smp_store_release(depth, val); + return val; } /* Older firmware and the H17G method profile retain their existing transport. */ @@ -373,9 +379,14 @@ static bool iomfb_uses_queue(struct apple_dcp *dcp) bool iomfb_channels_idle(struct apple_dcp *dcp) { - return !dcp->ch_cmd.depth && !dcp->ch_cb.depth && - !dcp->ch_oobcmd.depth && !dcp->ch_oobcb.depth && - !dcp->ch_async.depth && !dcp->ch_oobasync.depth; + /* Pair with dcp_pop_depth() / dcp_ack() pending_acks ordering. */ + return !smp_load_acquire(&dcp->ch_cmd.depth) && + !smp_load_acquire(&dcp->ch_cb.depth) && + !smp_load_acquire(&dcp->ch_oobcmd.depth) && + !smp_load_acquire(&dcp->ch_oobcb.depth) && + !smp_load_acquire(&dcp->ch_async.depth) && + !smp_load_acquire(&dcp->ch_oobasync.depth) && + !atomic_read_acquire(&dcp->pending_acks); } enum iomfb_opaque_x_state { @@ -398,7 +409,13 @@ static int iomfb_enqueue_opaque_x(struct apple_dcp *dcp) struct iomfb_opaque_x_transaction *opaque; lockdep_assert_held(&dcp->iomfb.lock); - /* DCPEXT rejects enableGPAlphaDiv; retain the panel-only workaround. */ + /* + * H17P blends the X byte of an XRGB surface as alpha; this property + * makes the panel pipe take it as opaque. It is sent to panels only: + * the H17P external controller answers it with status 4, which + * iomfb_opaque_x_complete() treats as fatal, and native26 external + * pipes keep their own presentation path. + */ if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL || dcp_is_ext26(dcp)) return 0; @@ -893,11 +910,14 @@ static void iomfb_v27_sleep_start(struct apple_dcp *dcp, rpc->data, iomfb_v27_sleep_done, rpc); dcp->push_out_prefill = NULL; if ((rpc->a442 || rpc->a442_key) && !rpc->oob) { - static const struct dcp_method_entry a442 = { - .name = "v27_a442", .tag = { 'A', '4', '4', '2' }, - }; + struct dcp_method_entry a442 = { .name = "v27_a442" }; u8 in[92]; + if (iomfb_v27_tag(dcp->v27_methods, "A442", a442.tag)) { + dev_warn_once(dcp->dev, "skipping v27 wake A442: unmapped method tag\n"); + return; + } + memset(in, 0xaa, sizeof(in)); memset(in, 0, 16); in[8] = rpc->a442_key ?: 0x41; @@ -905,6 +925,9 @@ static void iomfb_v27_sleep_start(struct apple_dcp *dcp, if (rpc->a442_key) { memset(in + 80, 0, 12); in[84] = 0x20; + } else if (iomfb_v27_methods_renumbered(dcp->v27_methods)) { + /* 27.2 reads the filler as an index count and a block size. */ + memset(in + 16, 0, sizeof(in) - 16); } dcp_push(dcp, true, &a442, sizeof(in), 4100, in, iomfb_v27_a442_done, NULL); } @@ -982,6 +1005,9 @@ int iomfb_v27_sleep_plain(struct apple_dcp *dcp, bool on) static int iomfb_v27_rpc(struct apple_dcp *dcp, bool a500, bool on, bool flags) { + struct dcp_method_entry method = { + .name = a500 ? "v27_sleep_500" : "v27_sleep_power", + }; struct iomfb_v27_sleep_rpc *rpc; u8 args[IOMFB_V27_SLEEP_ARGS]; int ret; @@ -992,6 +1018,9 @@ static int iomfb_v27_rpc(struct apple_dcp *dcp, bool a500, bool on, bool flags) (a500 || flags ? iomfb_v27_sleep_args(dcp, a500, args) : iomfb_v27_display_args(dcp, false, args))) return -EOPNOTSUPP; + ret = iomfb_v27_tag(dcp->v27_methods, a500 ? "A500" : "A484", method.tag); + if (ret) + return ret; rpc = kzalloc_obj(*rpc); if (!rpc) return -ENOMEM; @@ -1000,10 +1029,7 @@ static int iomfb_v27_rpc(struct apple_dcp *dcp, bool a500, bool on, bool flags) rpc->status = ~0U; rpc->transaction.start = iomfb_v27_sleep_start; rpc->transaction.release = iomfb_v27_sleep_release; - rpc->method = (struct dcp_method_entry) { - .name = a500 ? "v27_sleep_500" : "v27_sleep_power", - }; - memcpy(rpc->method.tag, a500 ? "A500" : "A484", 4); + rpc->method = method; /* * Off, before each DCP's and DCPEXT's sleep idle: A484 with the sleep's flags, then * A500's sleep form. On, after the wake: A500's wake form, then A484 with the flags. @@ -1075,6 +1101,7 @@ int iomfb_v27_sleep_a115(struct apple_dcp *dcp, bool awake) static int iomfb_v27_call(struct apple_dcp *dcp, const char *tag, const void *in, u32 in_len, u32 out_len, bool inout, u8 a442_key) { + struct dcp_method_entry method = { .name = "v27_display_stage" }; struct iomfb_v27_sleep_rpc *rpc; int ret; @@ -1082,6 +1109,9 @@ static int iomfb_v27_call(struct apple_dcp *dcp, const char *tag, const void *in dcp->fw_compat != DCP_FIRMWARE_V_27_0 || in_len > sizeof(rpc->data) || (inout && out_len > sizeof(rpc->data))) return -EOPNOTSUPP; + ret = iomfb_v27_tag(dcp->v27_methods, tag, method.tag); + if (ret) + return ret; rpc = kzalloc_obj(*rpc); if (!rpc) return -ENOMEM; @@ -1091,8 +1121,7 @@ static int iomfb_v27_call(struct apple_dcp *dcp, const char *tag, const void *in rpc->any_reply = true; rpc->transaction.start = iomfb_v27_sleep_start; rpc->transaction.release = iomfb_v27_sleep_release; - rpc->method = (struct dcp_method_entry) { .name = "v27_display_stage" }; - memcpy(rpc->method.tag, tag, 4); + rpc->method = method; rpc->input = in_len; rpc->output = out_len; rpc->inout = inout; @@ -1423,11 +1452,21 @@ void dcp_ack(struct apple_dcp *dcp, enum dcp_context_id context) { struct dcp_channel *ch = dcp_get_channel(dcp, context); + /* + * Track the in-flight ACK before popping ch->depth so a concurrent + * iomfb_channels_idle() poll cannot see idle before the ACK is queued + * to RTKit, while popping ch->depth before sending so DCP's next + * callback cannot race ch->depth. + */ + atomic_inc(&dcp->pending_acks); dcp_pop_depth(&ch->depth); if (dcp_is_ext26(dcp)) dma_wmb(); dcp_send_message(dcp, IOMFB_ENDPOINT, dcpep_ack(context)); + /* Order dcp_send_message() before publishing pending_acks == 0. */ + smp_mb__before_atomic(); + atomic_dec(&dcp->pending_acks); } /* @@ -2051,9 +2090,12 @@ void dcp_hotplug(struct work_struct *work) } /* - * J700/25G83 asks D134 after publishing its external video interface. - * The observed async record has no input and a four-byte result. Use the - * existing zero reply for this record only; its feature remains unsupported. + * The H17P external firmware (26.6.2) asks D134 after publishing its + * external video interface. The observed async record has no input and a + * four-byte result. Use the existing zero reply for this record only; its + * feature remains unsupported. The record belongs to the firmware ABI: the + * method profile is only set for that firmware, which probe has already + * checked against apple,firmware-version (dcp_h17p_external_supported()). */ static bool dcp_external_zero_reply(struct apple_dcp *dcp, int tag, enum dcp_context_id context, @@ -2062,9 +2104,7 @@ static bool dcp_external_zero_reply(struct apple_dcp *dcp, int tag, return tag == 134 && context == DCP_CONTEXT_ASYNC && in_len == 0 && out_len == sizeof(u32) && dcp->hw.iomfb_method_profile == - DCP_IOMFB_METHODS_H17P_EXTERNAL && - of_machine_is_compatible("apple,j700") && - of_device_is_compatible(dcp->dev->of_node, "apple,t8140-dcpext"); + DCP_IOMFB_METHODS_H17P_EXTERNAL; } static void dcpep_handle_cb(struct apple_dcp *dcp, enum dcp_context_id context, @@ -2423,6 +2463,14 @@ u64 dcp_modes_transfer_begin(struct apple_dcp *dcp) * catalog, except on H17P external, which publishes an empty one. A * transfer started before the current attachment is never published. */ +static bool dcp_sdr_default_rgb(struct apple_dcp *dcp) +{ + return dcp->fw_compat == DCP_FIRMWARE_V_27_0 && !dcp_has_panel(dcp); +} + +static const struct dcp_display_mode * +dcp_find_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode); + int dcp_modes_replace(struct apple_dcp *dcp, struct dcp_parse_ctx *ctx, u64 generation) { @@ -2455,9 +2503,14 @@ int dcp_modes_replace(struct apple_dcp *dcp, struct dcp_parse_ctx *ctx, if (ret) return ret; ctx->metadata_timing = dcp_firmware_metadata_enabled(dcp); - ctx->sdr_default_rgb = dcp->fw_compat == DCP_FIRMWARE_V_27_0 && - !dcp_has_panel(dcp); - ctx->pq_dsc = dcp->fw_compat == DCP_FIRMWARE_V_27_0; + ctx->sdr_default_rgb = dcp_sdr_default_rgb(dcp); + /* + * The template sends a timing and colour ID to DCP. It can + * select an entry the timing lists as needing DSC, just as + * for SDR. The parser still rejects unsafe PQ entries. + */ + ctx->pq_dsc = READ_ONCE(dcp->iomfb_template_pq) && + !dcp_has_panel(dcp); } ctx->zero_vrr_range_fallback = dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP; ctx->internal_present_deadline = dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP; @@ -2923,6 +2976,11 @@ int dcp_get_modes(struct drm_connector *connector) } edid_done: + /* + * The connector's ELD follows its EDID: a card connected before this + * EDID was published (a Type-C route's service opens first) takes it now. + */ + av_audio_sink_changed(dcp); /* Discovery can replace the catalogue while the OOB read waits. */ if (dcp_is_ext26(dcp)) { if (READ_ONCE(dcp->crashed) || READ_ONCE(dcp->ext26_blocked)) @@ -2997,15 +3055,15 @@ static int dcp_desktop_modeset(struct apple_dcp *dcp, struct drm_crtc_state *crtc_state) { struct dcp_desktop_state *d = dcp->desktop; - struct dcp_display_mode matched; + const struct dcp_display_mode *matched; if (d->trial_modeset_ok) { d->trial_modeset_ok = false; /* The trial installed a VRR timing variable too (see the mode set). */ if (d->mode_live && - lookup_mode(dcp, &crtc_state->mode, &matched) && - matched.timing_mode_id == d->trial_timing_mode_id && - matched.color_mode_id == d->trial_color_mode_id) { + (matched = dcp_find_mode(dcp, &crtc_state->mode)) && + matched->timing_mode_id == d->trial_timing_mode_id && + matched->color_mode_id == d->trial_color_mode_id) { dev_dbg(dcp->dev, "keeping the takeover mode " DRM_MODE_FMT "\n", DRM_MODE_ARG(&crtc_state->mode)); return 0; @@ -3030,20 +3088,26 @@ MODULE_PARM_DESC(takeover_adopt, static int dcp_takeover_adopt(struct apple_dcp *dcp, const struct drm_display_mode *m) { struct dcp_desktop_state *d = dcp->desktop; - struct dcp_display_mode sel; + const struct dcp_display_mode *sel = dcp_find_mode(dcp, m); - if (!lookup_mode(dcp, m, &sel)) + if (!sel) return -ENOENT; - dcp->mode = (struct dcp_set_digital_out_mode_req) { - .color_mode_id = sel.color_mode_id, - .timing_mode_id = sel.timing_mode_id, - }; - dcp->use_timestamps = sel.needs_timestamps; - dcp->vrr_enabled = false; + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + dcp->mode = (struct dcp_set_digital_out_mode_req) { + .color_mode_id = sel->color_mode_id, + .timing_mode_id = sel->timing_mode_id, + }; + if (dcp_default_sdr_color(sel, &dcp->active_color)) + dcp->active_color.score = -1; + dcp->output_pq = false; + dcp->output_hdr = false; + dcp->vrr_enabled = false; + } + dcp->use_timestamps = sel->needs_timestamps; d->mode_live = true; d->takeover_adopted = true; dev_info(dcp->dev, "takeover: adopting the live mode (color:%u timing:%u) " DRM_MODE_FMT "\n", - sel.color_mode_id, sel.timing_mode_id, DRM_MODE_ARG(m)); + sel->color_mode_id, sel->timing_mode_id, DRM_MODE_ARG(m)); return 0; } @@ -3179,29 +3243,26 @@ int dcp_takeover_trial(struct platform_device *pdev, const char **reason) } /* - * PQ output goes through the IOMFB template's mode set, which picks the - * timing's PQ element (see dcp_display_mode.pq): the desktop 26.x firmware, - * the external H17P processor and the firmware 27 external processors. The - * other processors, and the firmware 27 panel, keep SDR. + * The template chooses a PQ colour ID and tags the surfaces. The caller + * checks for that ID in the current timing catalogue. Panels keep their + * existing SDR/EDR path, with the desktop template retaining PQ support. */ static bool dcp_hdr_output_supported(struct apple_dcp *dcp) { - if (iomfb_is_m4(dcp)) - return false; - return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || - dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL || - (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && !dcp_has_panel(dcp)); + return READ_ONCE(dcp->iomfb_template_pq) && + (!dcp_has_panel(dcp) || dcp->desktop); } /* - * A desktop 26.x or firmware 27 panel keeps its SDR link and shows PQ - * content as EDR, given the panel's peak (see res_max_panel_brightness()). + * A desktop 26.x or firmware 27 panel with EDR headroom (dcp_panel_edr()) + * keeps its SDR link and shows PQ content as EDR, given the panel's peak + * (see res_max_panel_brightness()). */ static bool dcp_panel_edr_supported(struct apple_dcp *dcp) { - return (dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || - dcp->fw_compat == DCP_FIRMWARE_V_27_0) && - dcp_has_panel(dcp) && READ_ONCE(dcp->panel.peak_nits); + return dcp_fw_swap_has_edr(dcp) && dcp_fw_panel_decodes_pq(dcp) && + dcp_has_panel(dcp) && dcp->panel.edr_ceiling && + READ_ONCE(dcp->panel.peak_nits); } /* The state of the connector on @crtc that @commit sets up. */ @@ -3253,20 +3314,66 @@ static bool dcp_crtc_bt2020(struct apple_dcp *dcp, struct drm_crtc *crtc, return conn_state && conn_state->colorspace == DRM_MODE_COLORIMETRY_BT2020_RGB; } -/* - * HDR10 static metadata is link state on the external processors: a link - * set up again (mode set, power off) starts without it. - */ -void dcp_hdr_metadata_forget(struct apple_dcp *dcp) +static void dcp_hdr_reset_locked(struct apple_dcp *dcp) { - struct dcp_desktop_state *d = dcp->desktop; + lockdep_assert_held(&dcp->hdr.lock); + dcp->hdr.generation++; + dcp->hdr.sent_valid = false; + dcp->hdr.infoframe = false; +} + +void dcp_hdr_service_bind(struct apple_epic_service *service) +{ + struct apple_dcp *dcp = service->ep->dcp; + struct apple_epic_service *old; - if (!d) + service = afk_service_get(service); + if (!service) return; - scoped_guard(spinlock_irqsave, &d->hdr_lock) { - d->hdr_sent_valid = false; - d->hdr_infoframe = false; + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + old = dcp->hdr.service; + WRITE_ONCE(dcp->hdr.service, service); + dcp_hdr_reset_locked(dcp); } + if (old) + afk_service_put(old); +} + +void dcp_hdr_service_unbind(struct apple_epic_service *service) +{ + struct apple_dcp *dcp = service->ep->dcp; + bool owned; + + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + owned = dcp->hdr.service == service; + if (owned) { + WRITE_ONCE(dcp->hdr.service, NULL); + dcp_hdr_reset_locked(dcp); + } + } + if (owned) + afk_service_put(service); +} + +/* A link set up again starts without the previous HDR10 metadata. */ +void dcp_hdr_metadata_forget(struct apple_dcp *dcp) +{ + guard(spinlock_irqsave)(&dcp->hdr.lock); + dcp_hdr_reset_locked(dcp); +} + +static int dcp_hdr_send(struct apple_epic_service *service, + const void *msg, size_t msg_len, + void *reply, size_t reply_len, + u32 *retcode, size_t *received) +{ + if (service->ep->wire_v2) + return afk_send_command_len(service, EPIC_SUBTYPE_STD_SERVICE, + msg, msg_len, reply, reply_len, + retcode, received); + return afk_send_command_with_reply_len(service, EPIC_SUBTYPE_STD_SERVICE, + msg, msg_len, reply, reply_len, + retcode, received); } /* @@ -3277,33 +3384,34 @@ void dcp_hdr_metadata_forget(struct apple_dcp *dcp) */ static void dcp_hdr_infoframe_stop(struct apple_dcp *dcp) { - struct dcp_desktop_state *d = dcp->desktop; struct apple_epic_service *service = NULL; u8 msg[DCP_HDR_STOP_SIZE], reply[DCP_HDR_STOP_SIZE] = {}; size_t received = 0; + u64 generation; u32 retcode = 0; int ret; - if (!d || READ_ONCE(dcp->crashed)) + if (READ_ONCE(dcp->crashed)) return; - scoped_guard(spinlock_irqsave, &d->hdr_lock) - if (d->hdr_infoframe) - service = afk_service_get(d->av_service); + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + generation = dcp->hdr.generation; + if (dcp->hdr.infoframe) + service = afk_service_get(dcp->hdr.service); + } if (!service) return; dcp_hdr_stop_message(msg); - ret = afk_send_command_with_reply_len(service, EPIC_SUBTYPE_STD_SERVICE, - msg, sizeof(msg), reply, sizeof(reply), - &retcode, &received); + ret = dcp_hdr_send(service, msg, sizeof(msg), reply, sizeof(reply), + &retcode, &received); ret = dcp_hdr_stop_reply(ret, retcode, reply, received); if (ret) dev_warn(dcp->dev, "HDR InfoFrame not stopped: %d\n", ret); else dev_dbg(dcp->dev, "HDR InfoFrame stopped\n"); - scoped_guard(spinlock_irqsave, &d->hdr_lock) - if (d->av_service == service) - d->hdr_infoframe = false; + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) + if (dcp->hdr.service == service && dcp->hdr.generation == generation) + dcp->hdr.infoframe = false; afk_service_put(service); } @@ -3312,8 +3420,8 @@ bool dcp_hdr_metadata_live(struct platform_device *pdev) { struct apple_dcp *dcp = platform_get_drvdata(pdev); - return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP && - !dcp_has_panel(dcp); + return READ_ONCE(dcp->iomfb_template_pq) && !dcp_has_panel(dcp) && + (dcp->desktop || READ_ONCE(dcp->hdr.service)); } /* @@ -3354,98 +3462,125 @@ static void dcp_edr_sync(struct apple_dcp *dcp, struct drm_crtc *crtc, static void dcp_hdr_metadata_sync(struct apple_dcp *dcp, struct drm_crtc *crtc, struct drm_atomic_commit *commit) { - struct dcp_desktop_state *d = dcp->desktop; - const struct drm_connector_state *conn_state = NULL; - struct drm_connector_state *state; - struct drm_connector *connector; + const struct drm_connector_state *conn_state; struct apple_epic_service *service; u8 data[DCP_HDR_DATA_SIZE], msg[DCP_HDR_MSG_SIZE]; u8 reply[DCP_HDR_MSG_SIZE] = {}; size_t received = 0; + u64 generation; u32 retcode = 0; bool same; - int i, ret; + int transport, ret; - if (!d || !dcp->output_pq || READ_ONCE(dcp->crashed) || + if (!dcp->output_hdr || READ_ONCE(dcp->crashed) || !dcp_hdr_metadata_live(to_apple_crtc(crtc)->dcp)) return; - for_each_new_connector_in_state(commit, connector, state, i) - if (state->crtc == crtc) - conn_state = state; - if (!conn_state && dcp->connector && dcp->connector->base.state && - dcp->connector->base.state->crtc == crtc) - conn_state = dcp->connector->base.state; + conn_state = dcp_crtc_connector_state(dcp, crtc, commit); if (!conn_state || !conn_state->hdr_output_metadata || conn_state->hdr_output_metadata->length != sizeof(struct hdr_output_metadata)) return; if (((const struct hdr_output_metadata *)conn_state->hdr_output_metadata->data) - ->hdmi_metadata_type1.eotf != HDMI_EOTF_SMPTE_ST2084 || + ->hdmi_metadata_type1.eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR || dcp_hdr_data(data, conn_state->hdr_output_metadata->data)) return; /* Most frames change nothing: compare before pinning the service. */ - scoped_guard(spinlock_irqsave, &d->hdr_lock) { - same = d->hdr_sent_valid && !memcmp(d->hdr_sent, data, sizeof(data)); - service = same ? NULL : afk_service_get(d->av_service); + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + generation = dcp->hdr.generation; + same = dcp->hdr.sent_valid && !memcmp(dcp->hdr.sent, data, sizeof(data)); + service = same ? NULL : afk_service_get(dcp->hdr.service); } if (!service) return; dcp_hdr_message(msg, data); - ret = afk_send_command_with_reply_len(service, EPIC_SUBTYPE_STD_SERVICE, - msg, sizeof(msg), reply, sizeof(reply), - &retcode, &received); - ret = dcp_hdr_reply(ret, retcode, reply, received); - /* - * A block the firmware refused is not sent again on every frame (the - * command is synchronous): only a new block, a new mode set or a new - * service instance retries. - */ + transport = dcp_hdr_send(service, msg, sizeof(msg), reply, sizeof(reply), + &retcode, &received); + ret = dcp_hdr_reply(transport, retcode, reply, received); if (ret) dev_warn_ratelimited(dcp->dev, "HDR static metadata not taken: %d\n", ret); else dev_dbg(dcp->dev, "HDR static metadata: MaxCLL %u MaxFALL %u mastering %u/%u\n", get_unaligned_le16(data + 20), get_unaligned_le16(data + 22), get_unaligned_le16(data + 16), get_unaligned_le16(data + 18)); - scoped_guard(spinlock_irqsave, &d->hdr_lock) { - if (d->av_service == service) { - memcpy(d->hdr_sent, data, sizeof(data)); - d->hdr_sent_valid = true; + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + if (dcp->hdr.service == service && dcp->hdr.generation == generation) { + /* Without a valid reply, the previous block may no longer be active. */ + dcp->hdr.sent_valid = !transport && ret != -EPROTO; + if (dcp->hdr.sent_valid) + memcpy(dcp->hdr.sent, data, sizeof(data)); if (!ret) - d->hdr_infoframe = true; + dcp->hdr.infoframe = true; } } afk_service_put(service); } -/* Only an SDR or a PQ signal, and PQ only where the timing has an element. */ +static void dcp_crtc_color_request(struct apple_dcp *dcp, struct drm_crtc *crtc, + struct drm_atomic_commit *commit, + struct dcp_color_request *req) +{ + const struct drm_connector_state *conn_state = + dcp_crtc_connector_state(dcp, crtc, commit); + + *req = (struct dcp_color_request) { + .eotf = dcp_crtc_eotf(dcp, crtc, commit), + .colorspace = conn_state ? conn_state->colorspace : + DRM_MODE_COLORIMETRY_DEFAULT, + .color_format = conn_state ? conn_state->color_format : + DRM_CONNECTOR_COLOR_FORMAT_AUTO, + .broadcast_rgb = conn_state ? conn_state->hdmi.broadcast_rgb : + DRM_HDMI_BROADCAST_RGB_AUTO, + .max_bpc = conn_state ? conn_state->max_requested_bpc : 0, + .allow_hdr = dcp_hdr_output_supported(dcp), + .allow_dsc = READ_ONCE(dcp->iomfb_template_pq) && !dcp_has_panel(dcp), + .allow_unsafe_sdr = dcp->hw.iomfb_method_profile != + DCP_IOMFB_METHODS_H17P_EXTERNAL, + .default_rgb = dcp_sdr_default_rgb(dcp), + }; +} + +/* Validate requested EOTF, colorspace, format, range and bpc against the timing. */ int dcp_crtc_check_hdr(struct apple_dcp *dcp, struct drm_crtc *crtc, struct drm_atomic_commit *commit) { struct drm_crtc_state *crtc_state = drm_atomic_get_new_crtc_state(commit, crtc); - struct dcp_display_mode mode; + struct dcp_color_request req; + struct dcp_color_mode selected; + const struct dcp_display_mode *mode; if (!crtc_state || !crtc_state->enable || !drm_atomic_crtc_needs_modeset(crtc_state)) return 0; - switch (dcp_crtc_eotf(dcp, crtc, commit)) { - case HDMI_EOTF_TRADITIONAL_GAMMA_SDR: - return 0; - case HDMI_EOTF_SMPTE_ST2084: - if (dcp_panel_edr_supported(dcp)) + dcp_crtc_color_request(dcp, crtc, commit, &req); + if (dcp_panel_edr_supported(dcp)) { + if (req.eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR || + req.eotf == HDMI_EOTF_SMPTE_ST2084) return 0; - if (dcp_hdr_output_supported(dcp) && - lookup_mode(dcp, &crtc_state->mode, &mode) && mode.pq.score >= 0) + return -EINVAL; + } + if (dcp_color_request_is_default(&req) && + req.eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR && + req.colorspace == DRM_MODE_COLORIMETRY_DEFAULT) + return 0; + if (!READ_ONCE(dcp->iomfb_template_pq) || dcp_is_ext26(dcp)) { + /* Fixed 8-bit SDR pipes satisfy any default SDR request with max_bpc >= 8. */ + if (req.eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR && + req.colorspace == DRM_MODE_COLORIMETRY_DEFAULT && + req.color_format == DRM_CONNECTOR_COLOR_FORMAT_AUTO && + req.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_AUTO && + (!req.max_bpc || req.max_bpc >= 8)) return 0; - fallthrough; - default: return -EINVAL; } + mode = dcp_find_mode(dcp, &crtc_state->mode); + if (!mode) + return -EINVAL; + return dcp_select_color_mode(mode, &req, &selected); } -/* The user may own drm_display_mode, so we need to search for our copy */ -bool lookup_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode, - struct dcp_display_mode *out) +static const struct dcp_display_mode * +dcp_find_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode) { struct dcp_display_mode *modes; unsigned int count, i; @@ -3458,7 +3593,7 @@ bool lookup_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode, DRM_MODE_MATCH_TIMINGS | DRM_MODE_MATCH_CLOCK)) { if (!modes[i].automatic_rgb8_quirk) - goto found; + return &modes[i]; mutex_lock(&dcp->hpd_mutex); mutex_lock(&dcp->dcpavserv.lock); spin_lock_irqsave(&dcp->metadata.lock, flags); @@ -3467,16 +3602,24 @@ bool lookup_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode, mutex_unlock(&dcp->dcpavserv.lock); mutex_unlock(&dcp->hpd_mutex); if (eligible) - goto found; + return &modes[i]; } } - return false; + return NULL; +} -found: +/* The user may own drm_display_mode, so we need to search for our copy */ +bool lookup_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode, + struct dcp_display_mode *out) +{ + const struct dcp_display_mode *found = dcp_find_mode(dcp, mode); + + if (!found) + return false; /* Callers keep a copy, never a pointer into the catalog. */ if (out) - *out = modes[i]; + *out = *found; return true; } @@ -3490,22 +3633,25 @@ bool lookup_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode, static bool dcp_mode_settable(struct apple_dcp *dcp, const struct drm_display_mode *mode) { - struct dcp_display_mode dcp_mode; + const struct dcp_display_mode *dcp_mode = dcp_find_mode(dcp, mode); - if (!lookup_mode(dcp, mode, &dcp_mode)) + if (!dcp_mode) return false; if (dcp->fw_compat == DCP_FIRMWARE_H17P && !dcp_is_ext26(dcp) && dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17P_EXTERNAL) - return dcp_mode.mode.type & DRM_MODE_TYPE_PREFERRED; + return dcp_mode->mode.type & DRM_MODE_TYPE_PREFERRED; /* - * The T6050 internal DCP (M5 Max) crashes on 3024x1986@60 and the - * other 60 Hz timings it lists. Only the 120 Hz timing is known to - * survive a modeset, so refuse the rest until they are understood. + * The T6050 internal DCP (M5 Max, K114s) crashes on a mode set away + * from the timing iBoot left the panel at: 120 -> 60 Hz, and 60 -> + * 120 Hz when macOS left it at 60 Hz. Offer only the rate the + * firmware reported at start (dcp_rtk_syslog_boot_rate()), 120 Hz + * when it reported none. */ - if (dcp->hw.only_120hz_modes && drm_mode_vrefresh(mode) != 120) + if (dcp->hw.only_120hz_modes && + drm_mode_vrefresh(mode) != (READ_ONCE(dcp->boot_rate) ?: 120)) return false; return true; @@ -3593,11 +3739,29 @@ int dcp_crtc_atomic_modeset(struct drm_crtc *crtc, if (crtc_state->mode.hdisplay == 0 && crtc_state->mode.vdisplay == 0) return 0; - dcp->pq_requested = dcp_crtc_eotf(dcp, crtc, commit) == HDMI_EOTF_SMPTE_ST2084; + /* + * The DCP of an HDMI output plugs the display in only some time after + * its link came up (dcp_poweron() connects it): a second or more after + * a system resume, as the converter and the display wake up. A mode set + * before that fails in the firmware ("setmode failed", the pipe not + * enabled) after a 200 ms wait. Leave the mode unset instead: the + * hotplug that connects the display finds the mode invalid with the + * CRTC active, and sets it again (dcp_hotplug()). + */ + if (dcp->hdmi_hpd && !dcp_is_typec_output(dcp) && dcp->connector && + !READ_ONCE(dcp->connector->connected)) { + dev_dbg(dcp->dev, "HDMI display not plugged in yet: mode set deferred to its hotplug\n"); + dcp_mode_set_valid(&dcp->mode_state, false); + return -EAGAIN; + } + + dcp_crtc_color_request(dcp, crtc, commit, &dcp->color_req); + dcp->pq_requested = dcp->color_req.eotf == HDMI_EOTF_SMPTE_ST2084; dcp->output_edr = dcp->pq_requested && dcp_panel_edr_supported(dcp) && dcp_crtc_bt2020(dcp, crtc, commit); dcp->pq_requested &= dcp_hdr_output_supported(dcp); - if (!dcp->pq_requested) + if (dcp->color_req.eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR || + !dcp_hdr_output_supported(dcp)) dcp_hdr_infoframe_stop(dcp); dcp_hdr_metadata_forget(dcp); dcp_mode_begin(&dcp->mode_state); @@ -3799,6 +3963,20 @@ iomfb_scanout_prepare_h17p(struct apple_dcp *dcp, struct drm_crtc *crtc, drm_framebuffer_get(new_state->fb); } } + if (dcp->boot_surface_pending && scanout->fb[0]) { + struct drm_plane_state *primary = crtc->primary ? + drm_atomic_get_new_plane_state(state, crtc->primary) : NULL; + + /* + * Match the explicit slot-zero clear in iomfb_flush() when the + * primary plane is disabled; dcp->iomfb.scanout keeps its own + * reference pinned until completion replaces it. + */ + if (!primary || primary->crtc != crtc || !primary->visible || !primary->fb) { + drm_framebuffer_put(scanout->fb[0]); + scanout->fb[0] = NULL; + } + } if (dcp_is_ext26(dcp)) { struct iomfb_scanout_h17p *dropped; u64 bytes = ext26_scanout_bytes(scanout); @@ -4314,6 +4492,7 @@ void dcp_flush(struct drm_crtc *crtc, struct drm_atomic_commit *commit) { struct platform_device *pdev = to_apple_crtc(crtc)->dcp; struct apple_dcp *dcp = platform_get_drvdata(pdev); + bool route_ready; if (iomfb_is_m4(dcp)) { struct drm_plane_state *plane = drm_atomic_get_new_plane_state(commit, @@ -4366,13 +4545,13 @@ void dcp_flush(struct drm_crtc *crtc, struct drm_atomic_commit *commit) return; } - if ((dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || - dcp->fw_compat == DCP_FIRMWARE_V_27_0) && - READ_ONCE(dcp->mode_state.valid) && dcp->connector && - READ_ONCE(dcp->connector->connected)) { + route_ready = dcp_crtc_route_ready(crtc, commit, true); + if (READ_ONCE(dcp->mode_state.valid) && dcp->connector && + READ_ONCE(dcp->connector->connected) && + !(to_apple_atomic_state(commit)->failed_routes & drm_crtc_mask(crtc))) { /* A panel's EDR switches without a mode set (dcp_edr_live()). */ dcp_edr_sync(dcp, crtc, commit); - if (dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP) + if (route_ready) dcp_hdr_metadata_sync(dcp, crtc, commit); } @@ -4391,7 +4570,7 @@ void dcp_flush(struct drm_crtc *crtc, struct drm_atomic_commit *commit) * firmware has reported the display back. */ if ((to_apple_atomic_state(commit)->failed_routes & drm_crtc_mask(crtc)) || - !dcp_crtc_route_ready(crtc, commit, true) || + !route_ready || !READ_ONCE(dcp->mode_state.valid) || !dcp->connector || !dcp->connector->connected) { schedule_work(&dcp->vblank_wq); return; @@ -4464,6 +4643,13 @@ static void iomfb_start(struct apple_dcp *dcp) } } +bool dcp_boot_surface_pending(struct platform_device *pdev) +{ + struct apple_dcp *dcp = pdev ? platform_get_drvdata(pdev) : NULL; + + return dcp && READ_ONCE(dcp->boot_surface_pending); +} + bool dcp_is_initialized(struct platform_device *pdev) { struct apple_dcp *dcp = platform_get_drvdata(pdev); diff --git a/drivers/gpu/drm/apple/iomfb.h b/drivers/gpu/drm/apple/iomfb.h index e230a9eac9c5c1..0b2c04b7c61232 100644 --- a/drivers/gpu/drm/apple/iomfb.h +++ b/drivers/gpu/drm/apple/iomfb.h @@ -198,6 +198,28 @@ enum dcpep_method { dcpep_pipe_set_476, dcpep_unnamed_500, iomfbep_set_brightness_correction, + /* + * Firmware 27.x sleep and paired-mode calls named by their 27.0 ID. + * Optional for single-engine boot (iomfb_v27_missing_method() skips + * them); iomfb_v27_tag() refuses any call missing from a renumbered + * table. + */ + dcpep_v27_sleep_a115, + dcpep_v27_wake_a442, + dcpep_v27_peer_a360, + dcpep_v27_peer_a361, + dcpep_v27_peer_a362, + dcpep_v27_peer_a364, + dcpep_v27_peer_a365, + dcpep_v27_peer_a366, + dcpep_v27_peer_a367, + dcpep_v27_peer_a368, + dcpep_v27_peer_a369, + dcpep_v27_peer_a370, + dcpep_v27_peer_a371, + dcpep_v27_peer_a372, + dcpep_v27_peer_a373, + dcpep_v27_peer_a449, dcpep_num_methods }; @@ -220,6 +242,9 @@ struct dcp_method_entry { /* The IOMFB method table of a firmware 27.x build, by its compat string; NULL if unknown. */ const struct dcp_method_entry *iomfb_v27_methods(const char *compat); +bool iomfb_v27_methods_renumbered(const struct dcp_method_entry *methods); +int iomfb_v27_tag(const struct dcp_method_entry *methods, const char *tag, char *out); +bool iomfb_v27_sleep_methods_complete(const struct dcp_method_entry *methods); const struct dcp_method_entry *iomfb_v27_methods_j714s(struct device *dev, const struct dcp_method_entry *methods); /* The first method of a firmware 27.x table that has no ID, NULL if none. */ diff --git a/drivers/gpu/drm/apple/iomfb_h17p.c b/drivers/gpu/drm/apple/iomfb_h17p.c index 54a82ce65dbe1f..8476c1ddeba9cb 100644 --- a/drivers/gpu/drm/apple/iomfb_h17p.c +++ b/drivers/gpu/drm/apple/iomfb_h17p.c @@ -13,6 +13,7 @@ #include "iomfb_v12_3.h" #include "iomfb_v13_3.h" #include "iomfb_v14_7_tpl.h" +#include "dcp-internal.h" #include "version_utils.h" struct dcp_callback_size { @@ -1302,7 +1303,7 @@ void iomfb_start_h17p(struct apple_dcp *dcp) } WRITE_ONCE(dcp->pipe_enabled_h17p, false); dcp->cb_handlers = cb_handlers; - dcp_start_signal(dcp, false, dcp_started, NULL); + iomfb_template_start(dcp); } #if IS_ENABLED(CONFIG_DRM_APPLE_KUNIT_TEST) diff --git a/drivers/gpu/drm/apple/iomfb_iboot.c b/drivers/gpu/drm/apple/iomfb_iboot.c new file mode 100644 index 00000000000000..d949ad9d769e8f --- /dev/null +++ b/drivers/gpu/drm/apple/iomfb_iboot.c @@ -0,0 +1,886 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * DCP_FIRMWARE_IBOOT: the T8152 DCPs, driven through their firmware's + * iBoot interface alone. + * + * The bootloader leaves a successful display's RTKit session running, or + * quiesces it after a failed setup, and leaves an unused DCPEXT's firmware + * loaded and waiting for an RTKit wake (apple,rtkit-wake). This adopts or + * wakes that session, stops the AFK endpoints the bootloader left running + * and starts the iBoot (disp0-service or dispext-service), DPAV and DPTX + * port endpoints, reconnects the DPTX port and asserts HPD, then registers + * a DRM device whose flips are iBoot SET_SURFACE calls (iboot_drm.c), in + * the order the bootloader brings the display up. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "afk.h" +#include "dcp.h" +#include "dcp-internal.h" +#include "ibootep.h" +#include "iomfb_iboot.h" +#include "t8152_display.h" + +#define DCP_IBOOT_HPD_TIMEOUT_MS 10000 +/* RTKit's oslog system endpoint */ +#define DCP_IBOOT_RTKIT_EP_OSLOG 8 +/* The coprocessor's CPU control (bit 4: run) and status registers */ +#define DCP_IBOOT_CPU_CONTROL 0x44 +#define DCP_IBOOT_CPU_CONTROL_RUN BIT(4) +#define DCP_IBOOT_CPU_STATUS 0x48 + +static void dcp_iboot_rtk_crashed(void *cookie, const void *crashlog, size_t size) +{ + struct apple_dcp *dcp = cookie; + + WRITE_ONCE(dcp->crashed, true); + dev_err(dcp->dev, "DCP firmware crashed\n"); +} + +static void dcp_iboot_rtk_recv(void *cookie, u8 endpoint, u64 message) +{ + struct apple_dcp *dcp = cookie; + struct apple_dcp_afkep *ep = NULL; + + if (READ_ONCE(dcp->quiescing)) + return; + switch (endpoint) { + case DISP0_ENDPOINT: + ep = READ_ONCE(dcp->ibootep); + break; + case DPTX_CONTROLLER_ENDPOINT: + ep = READ_ONCE(dcp->dptx_controller_ep); + break; + case DPTX_ENDPOINT: + ep = READ_ONCE(dcp->dptxep); + break; + } + if (IS_ERR_OR_NULL(ep)) { + dev_dbg(dcp->dev, "message %#llx for idle endpoint %#x\n", + message, endpoint); + return; + } + afk_receive_message(ep, message); +} + +/* + * Buffers the firmware placed in its own DART mappings, or new ones, as for + * every DCP; and a woken DCPEXT's oslog ring. + */ +static int dcp_iboot_rtk_shmem_setup(void *cookie, u8 endpoint, + struct apple_rtkit_shmem *bfr) +{ + struct apple_dcp *dcp = cookie; + + /* + * A woken DCPEXT offers the oslog ring in its own firmware segment, at + * an address only the firmware's retained DART tables map. Linux never + * reads that ring and only acknowledges its write counters: take it as + * the firmware's, without a CPU mapping. The request needs no reply; + * the bootloader sends none either. + */ + if (bfr->iova && endpoint == DCP_IBOOT_RTKIT_EP_OSLOG) { + struct iommu_domain *domain = iommu_get_domain_for_dev(dcp->dev); + + if (domain && !iommu_iova_to_phys(domain, bfr->iova)) { + bfr->is_mapped = true; + return 0; + } + } + return dcp_rtk_shmem_setup(cookie, bfr); +} + +static void dcp_iboot_rtk_shmem_destroy(void *cookie, struct apple_rtkit_shmem *bfr) +{ + /* The firmware's oslog ring, taken without a mapping */ + if (bfr->is_mapped && !bfr->buffer) + return; + dcp_rtk_shmem_destroy(cookie, bfr); +} + +static bool dcp_iboot_rtk_syslog_debug(void *cookie, const char *context, + const char *message) +{ + /* Surface logging through fbcon would itself submit another surface. */ + return strstr(message, "setSurfaceRequest") || + strstr(message, "swap_submit_dcp") || + strstr(message, "validateRequest: inSize"); +} + +static const struct apple_rtkit_ops dcp_iboot_rtkit_ops = { + .crashed = dcp_iboot_rtk_crashed, + .recv_message = dcp_iboot_rtk_recv, + .shmem_setup_ep = dcp_iboot_rtk_shmem_setup, + .shmem_destroy = dcp_iboot_rtk_shmem_destroy, + .syslog_is_debug = dcp_iboot_rtk_syslog_debug, +}; + +/* + * Nothing scans out the bootloader's framebuffers while the main DCP stays + * off: drop the simpledrm devices on them, outputs that would show nothing. + * This detaches a simpledrm that is bound already, as the built-in one is + * long before this probe; one loaded later would bind again. + */ +static void dcp_iboot_drop_boot_fbs(void) +{ + struct device_node *chosen __free(device_node) = of_find_node_by_path("/chosen"); + + for_each_child_of_node_scoped(chosen, np) { + struct resource res; + + if (!of_device_is_compatible(np, "simple-framebuffer") || + of_address_to_resource(np, 0, &res)) + continue; + aperture_remove_conflicting_devices(res.start, resource_size(&res), + dcp_iboot_driver_name()); + } +} + +static bool dcp_iboot_handoff_quiesced(struct dcp_iboot *ib) +{ + struct device_node *chosen __free(device_node) = of_find_node_by_path("/chosen"); + const char *version; + u32 running; + + if (ib->disp.hdmi || !chosen) + return false; + if (!of_property_read_u32(chosen, "apple,dcp-rtkit-running", &running)) + return running == 0; + /* + * This older J873 loader predates the state property. Its failed + * display setup quiesces DCP and keeps iBoot's placeholder framebuffer; + * a successful setup hands over ON. Restrict this fallback to the + * verified loader build, rather than guessing for other handoffs. + */ + if (of_property_read_string(chosen, "asahi,m1n1-stage2-version", &version) || + strcmp(version, "v0.1.0-259-ga30a589a")) + return false; + for_each_child_of_node_scoped(chosen, np) { + u32 width, height; + + if (of_device_is_compatible(np, "simple-framebuffer") && + !of_property_read_u32(np, "width", &width) && + !of_property_read_u32(np, "height", &height)) + return width == 640 && height == 1136; + } + return false; +} + +/* The unused DCPEXT firmware is loaded and powered by iBoot. */ +static int dcp_iboot_check_wake(struct apple_dcp *dcp) +{ + struct platform_device *pdev = to_platform_device(dcp->dev); + struct resource *res; + void __iomem *psd, *coproc; + + res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "coproc-psd"); + if (!res) + return -EINVAL; + psd = devm_ioremap(dcp->dev, res->start, resource_size(res)); + if (!psd) + return -ENOMEM; + /* A read from the coprocessor while gated hangs the machine. */ + if (readl(psd + 0x80) & 7) + return -ENODEV; + res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "coproc"); + if (!res) + return -EINVAL; + coproc = devm_ioremap(dcp->dev, res->start, resource_size(res)); + if (!coproc) + return -ENOMEM; + dev_info(dcp->dev, "firmware handoff: CPU control %#x status %#x\n", + readl(coproc + DCP_IBOOT_CPU_CONTROL), + readl(coproc + DCP_IBOOT_CPU_STATUS)); + return (readl(coproc + DCP_IBOOT_CPU_CONTROL) & + DCP_IBOOT_CPU_CONTROL_RUN) ? 0 : -ENODEV; +} + +/* + * Wake only a quiesced session: IOP INIT on a running DCP can panic it. A + * running one is taken as it runs, without the HELLO/EPMAP handshake; + * its AFK endpoints are then registered as they start (hw.afk_adopt_endpoints). + */ +static int dcp_iboot_boot(struct dcp_iboot *ib) +{ + struct apple_dcp *dcp = ib->dcp; + bool wake = of_property_read_bool(dcp->dev->of_node, "apple,rtkit-wake"); + struct apple_rtkit *rtk; + int ret; + + if ((!ib->disp.hdmi && wake) || dcp_iboot_handoff_quiesced(ib)) { + if (wake) { + ret = dcp_iboot_check_wake(dcp); + if (ret) + return ret; + } + rtk = apple_rtkit_init(dcp->dev, dcp, NULL, 0, &dcp_iboot_rtkit_ops); + if (IS_ERR(rtk)) + return PTR_ERR(rtk); + dcp->rtk = rtk; + ret = apple_rtkit_wake(rtk); + dev_info(dcp->dev, "quiesced DCP wake: %d\n", ret); + return ret; + } + rtk = apple_rtkit_init_adopted(dcp->dev, dcp, NULL, 0, &dcp_iboot_rtkit_ops); + if (IS_ERR(rtk)) + return PTR_ERR(rtk); + dcp->rtk = rtk; + return apple_rtkit_adopt_running(rtk); +} + +/* + * The display pipe scans out through dart-disp0, the DCP fetches through + * dart-dcp. Both are locked with their own live root, so each needs its own + * device and domain: one domain spanning both would publish dart-dcp's root + * into dart-disp0 and drop the scanout mappings the bootloader left there + * (the pipe then faults, IOMFB axi_rd_err). Scanout buffers are allocated on + * the DCP device and mapped into the scanout domain at the same address. + */ +static int dcp_iboot_scanout_init(struct dcp_iboot *ib) +{ + struct device *dev = ib->dcp->dev; + struct device_node *np __free(device_node) = + of_get_child_by_name(dev->of_node, "scanout"); + int ret; + + if (!np) + return -ENODEV; + ib->scanout = of_platform_device_create(np, NULL, dev); + if (!ib->scanout) + ib->scanout = of_find_device_by_node(np); + if (!ib->scanout) + return -ENODEV; + ret = dma_set_mask_and_coherent(&ib->scanout->dev, DMA_BIT_MASK(64)); + if (ret) + return ret; + ret = of_dma_configure(&ib->scanout->dev, np, true); + if (ret) + return ret; + ib->scanout_dom = iommu_get_domain_for_dev(&ib->scanout->dev); + return ib->scanout_dom ? 0 : -ENODEV; +} + +/* Firmware-visible memory: never freed, the firmware may still use it. */ +static int dcp_iboot_dma_alloc(struct dcp_iboot *ib, struct dcp_iboot_dma *dma, + size_t size) +{ + dma->size = PAGE_ALIGN(size); + dma->cpu = dma_alloc_coherent(ib->dcp->dev, dma->size, &dma->iova, + GFP_KERNEL); + return dma->cpu ? 0 : -ENOMEM; +} + +static void *dcp_iboot_vmap_wc(struct sg_table *sgt) +{ + unsigned int n = 0, count = 0; + struct sg_page_iter iter; + struct page **pages; + void *vaddr; + + for_each_sgtable_page(sgt, &iter, 0) + count++; + pages = kvmalloc_array(count, sizeof(*pages), GFP_KERNEL); + if (!pages) + return NULL; + for_each_sgtable_page(sgt, &iter, 0) + pages[n++] = sg_page_iter_page(&iter); + vaddr = vmap(pages, count, VM_MAP, pgprot_writecombine(PAGE_KERNEL)); + kvfree(pages); + return vaddr; +} + +/* + * The display pipe's DART is locked and comes with the firmware's own + * mappings. The address the coprocessor's allocator handed out for a scanout + * buffer can be one of them, and mapping over it corrupts what the pipe + * fetches every frame (the picture flickers). Start at @dva and go down until + * a range with no mapping is found. + */ +static dma_addr_t dcp_iboot_scan_free_dva(struct dcp_iboot *ib, dma_addr_t dva, + size_t size) +{ + const size_t step = SZ_16K; + + size = ALIGN(size, step); + for (int tries = 0; tries < 64 && dva >= size; tries++) { + size_t off; + + for (off = 0; off < size; off += step) + if (iommu_iova_to_phys(ib->scanout_dom, dva + off)) + break; + if (off == size) + return dva; + dev_info(ib->dcp->dev, "scanout DART: %pad+%#zx is in use, moving down\n", + &dva, off); + dva -= size; + } + return 0; +} + +/* One scanout buffer: allocated, cleared, mapped for the CPU and the pipe. */ +static int dcp_iboot_scan_alloc(struct dcp_iboot *ib, int i, size_t size) +{ + struct dcp_iboot_dma *fb = &ib->scan[i]; + struct sg_table sgt; + ssize_t mapped; + dma_addr_t dva; + int ret; + + ret = dcp_iboot_dma_alloc(ib, fb, size); + if (ret) + return ret; + ret = dma_get_sgtable(ib->dcp->dev, &sgt, fb->cpu, fb->iova, fb->size); + if (ret) + return ret; + /* + * The DCP is coherent, the display pipe is not: it reads memory past + * the CPU caches, and frames written through the cacheable mapping + * show only once evicted. Write through a write-combined mapping of + * the same pages, with the zeroing of the allocation cleaned out first. + */ + arch_wb_cache_pmem(fb->cpu, fb->size); + ib->scan_wc[i] = dcp_iboot_vmap_wc(&sgt); + if (!ib->scan_wc[i]) { + sg_free_table(&sgt); + return -ENOMEM; + } + memset(ib->scan_wc[i], 0, fb->size); + /* + * Cacheable, as the bootloader maps scanout buffers: the pipe faults on + * entries with the DART's no-cache bit (IOMFB axi_rd_err). + */ + dva = dcp_iboot_scan_free_dva(ib, fb->iova, fb->size); + if (!dva) { + sg_free_table(&sgt); + return -ENOSPC; + } + mapped = iommu_map_sgtable(ib->scanout_dom, dva, &sgt, + IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE); + sg_free_table(&sgt); + if (mapped < (ssize_t)fb->size) + return mapped < 0 ? mapped : -ENOMEM; + ib->scan_dva[i] = dva; + dev_info(ib->dcp->dev, "scanout buffer %d: %zu bytes at %pad\n", i, + fb->size, &dva); + return 0; +} + +/* + * A fresh iBoot session has no surface. Whenever the pipe runs without one + * (the link retrains when the DPTX services restart, SET_MODE turns it on), + * it fetches from a null base and the firmware takes an NMI (IOMFB + * axi_rd_err). Hand it a black buffer of the boot mode at once, sized from + * the bootloader's simple-framebuffer. + */ +static int dcp_iboot_boot_surface(struct dcp_iboot *ib) +{ + /* + * The boot display's framebuffer is /chosen's; the bootloader adds the + * second display's (HDMI) at the root. + */ + struct device_node *chosen __free(device_node) = + of_find_node_by_path("/chosen"); + struct device_node *parent __free(device_node) = + ib->disp.dp_source ? + of_find_node_by_path("/") : of_node_get(chosen); + u32 width = 1280, height = 720, stride = 1280 * 4; + size_t size; + int ret; + + for_each_child_of_node_scoped(parent, np) { + struct resource res; + + if (!of_device_is_compatible(np, "simple-framebuffer")) + continue; + of_property_read_u32(np, "width", &width); + of_property_read_u32(np, "height", &height); + of_property_read_u32(np, "stride", &stride); + /* + * Take the display over from simpledrm on the bootloader's + * framebuffer, so it does not shadow this driver's output + * (fbcon on a framebuffer nothing scans out). + */ + if (!of_address_to_resource(np, 0, &res)) { + ret = aperture_remove_conflicting_devices(res.start, + resource_size(&res), + dcp_iboot_driver_name()); + if (ret) + dev_warn(ib->dcp->dev, "simpledrm stays: %d\n", ret); + } + break; + } + /* + * Large enough for the largest mode: while a SET_MODE switches, the + * pipe briefly scans the current surface with the new mode's size. + * A monitor may first appear after probe, with a larger mode list. + */ + size = max_t(size_t, (size_t)stride * height, 3840 * 2160 * 4); + for (unsigned int i = 0; i < ib->nr_tmodes; i++) + size = max_t(size_t, size, (size_t)le32_to_cpu(ib->tmodes[i].width) * + le32_to_cpu(ib->tmodes[i].height) * 4); + ib->boot_w = width; + ib->boot_h = height; + ib->boot_stride = stride; + for (int i = 0; i < ARRAY_SIZE(ib->scan); i++) { + ret = dcp_iboot_scan_alloc(ib, i, size); + if (ret) + return ret; + } + ib->front = 0; + ret = ibootep_set_surface(ib->dcp, ib->scan_dva[0], width, height, stride); + dev_info(ib->dcp->dev, "boot surface %ux%u at %pad: %d\n", width, height, + &ib->scan_dva[0], ret); + return ret; +} + +/* Both mode lists of the current sink; a list is kept when its query fails. */ +int dcp_iboot_get_modes(struct dcp_iboot *ib) +{ + struct iboot_timing_mode *tmodes; + struct iboot_color_mode *cmodes; + unsigned int count; + int ret; + + ret = ibootep_get_timing_modes(ib->dcp, &tmodes, &count); + if (ret) + return ret; + kfree(ib->tmodes); + ib->tmodes = tmodes; + ib->nr_tmodes = count; + ret = ibootep_get_color_modes(ib->dcp, &cmodes, &count); + if (ret) + return ret; + kfree(ib->cmodes); + ib->cmodes = cmodes; + ib->nr_cmodes = count; + return 0; +} + +/* + * Wait until the firmware reports a sink with modes, as the bootloader does. + * Nothing on the iBoot interface announces the sink, so GET_HPD is asked + * every 100 ms; the J873g ports took 268 to 328 ms after power on. + */ +int dcp_iboot_wait_hpd(struct dcp_iboot *ib) +{ + unsigned long timeout = jiffies + msecs_to_jiffies(DCP_IBOOT_HPD_TIMEOUT_MS); + u32 timings = 0, colors = 0; + int hpd; + + do { + hpd = ibootep_get_hpd(ib->dcp, &timings, &colors); + if (hpd > 0 && timings && colors) { + dev_info(ib->dcp->dev, "sink: %u timing, %u color modes\n", + timings, colors); + return 0; + } + msleep(100); + } while (time_before(jiffies, timeout)); + + dev_err(ib->dcp->dev, "no sink (hpd %d, %u timing, %u color modes)\n", hpd, + timings, colors); + return hpd < 0 ? hpd : -ENODEV; +} + +static void dcp_iboot_av_work(struct work_struct *work) +{ + struct dcp_iboot *ib = container_of(to_delayed_work(work), struct dcp_iboot, + av_work); + + if (READ_ONCE(ib->ready)) + dcp_iboot_reset_mode(ib); +} + +/* + * The DPAV controller endpoint's services take no host commands, but the + * firmware expects all of them opened: its video interface powers the + * display on and starts its idle power off timer, so SET_MODE follows once + * that one is up. + */ +static void dcp_iboot_dpav_init(struct apple_epic_service *service, + const char *name, const char *class, s64 unit) +{ + struct dcp_iboot *ib = READ_ONCE(service->ep->dcp->iboot); + + if (ib && name && strstr(name, "dcpav-video-interface")) + dcp_iboot_av_started(ib); +} + +static const struct apple_epic_service_ops dcp_iboot_dpav_ops = { + .name = "dcpav", + .reusable = true, + .init = dcp_iboot_dpav_init, +}; + +static unsigned int dcp_iboot_ep_services(struct apple_dcp_afkep *ep) +{ + unsigned int count = 0; + + for (unsigned int i = 0; i < AFK_MAX_CHANNEL; i++) + count += READ_ONCE(ep->services[i].enabled); + return count; +} + +/* + * The endpoint's services as it announces them, up to @expected within the + * AFK timeout; none is an error, fewer a warning. + */ +static int dcp_iboot_wait_services(struct apple_dcp *dcp, + struct apple_dcp_afkep *ep, unsigned int expected) +{ + unsigned int count; + + wait_event_timeout(ep->service_wq, dcp_iboot_ep_services(ep) >= expected, + msecs_to_jiffies(dcp->hw.afk_timeout_ms)); + count = dcp_iboot_ep_services(ep); + if (!count) { + dev_err(dcp->dev, "endpoint %#x announced no service\n", ep->endpoint); + return -ETIMEDOUT; + } + if (count < expected) + dev_warn(dcp->dev, "endpoint %#x: %u of %u services\n", ep->endpoint, + count, expected); + return 0; +} + +static int dcp_iboot_start_ep(struct apple_dcp *dcp, u32 endpoint, + struct apple_dcp_afkep **slot, + const struct apple_epic_service_ops *ops, + unsigned int expected) +{ + struct apple_dcp_afkep *ep = afk_init(dcp, endpoint, NULL); + int ret; + + if (IS_ERR(ep)) + return PTR_ERR(ep); + ep->unmatched_ops = ops; + WRITE_ONCE(*slot, ep); + ret = afk_start(ep); + if (ret) { + dev_err(dcp->dev, "endpoint %#x did not start: %d\n", endpoint, ret); + return ret; + } + return dcp_iboot_wait_services(dcp, ep, expected); +} + +/* The iBoot service is ready once its init callback has run. */ +static int dcp_iboot_start_iboot(struct apple_dcp *dcp) +{ + int ret; + + ret = ibootep_init(dcp); + if (ret) + return ret; + wait_event_timeout(dcp->ibootep->service_wq, ibootep_is_ready(dcp), + msecs_to_jiffies(dcp->hw.afk_timeout_ms)); + return ibootep_is_ready(dcp) ? 0 : -ENODEV; +} + +/* + * Once adopted, the DCP may still DMA into our buffers. Stop the host side: + * no more endpoint work or messages, no KMS work, and RTKit detached with + * its buffers retained. Firmware-visible storage stays allocated until + * reboot. + */ +static void dcp_iboot_detach(struct dcp_iboot *ib) +{ + struct apple_dcp *dcp = ib->dcp; + + WRITE_ONCE(ib->ready, false); + WRITE_ONCE(dcp->quiescing, true); + cancel_delayed_work_sync(&ib->av_work); + dcp_iboot_kms_stop(ib); + afk_quiesce(dcp->ibootep); + afk_quiesce(dcp->dptx_controller_ep); + afk_quiesce(dcp->dptxep); + if (!IS_ERR_OR_NULL(dcp->rtk)) + apple_rtkit_free_retaining_buffers(dcp->rtk); + WRITE_ONCE(dcp->rtk, NULL); +} + +static int dcp_iboot_start(struct dcp_iboot *ib) +{ + struct t8152_display *disp = &ib->disp; + struct apple_dcp *dcp = ib->dcp; + struct device *dev = dcp->dev; + bool sink = true; + int ret; + + ret = dcp_iboot_start_iboot(dcp); + if (ret) + return dev_err_probe(dev, ret, "no disp0-service\n"); + /* + * The new iBoot session has dropped the surface while the pipe still + * runs: it fetches from a null base (IOMFB axi_rd_err, firmware NMI) + * unless it is powered off at once. It comes back on below, after a + * surface is set. + */ + ret = ibootep_set_power(dcp, false); + if (ret) + return dev_err_probe(dev, ret, "display power off failed\n"); + ret = dcp_iboot_start_ep(dcp, DPTX_CONTROLLER_ENDPOINT, + &dcp->dptx_controller_ep, &dcp_iboot_dpav_ops, 4); + if (ret) + return dev_err_probe(dev, ret, "no DPAV controllers\n"); + ret = dcp_iboot_start_ep(dcp, DPTX_ENDPOINT, &dcp->dptxep, + &t8152_dptx_port_ops, 2); + if (ret) + return dev_err_probe(dev, ret, "no DPTX port service\n"); + if (disp->usbc) { + ret = t8152_dptx_disconnect(disp, 0); + if (ret) + return dev_err_probe(dev, ret, "cannot release inherited DP link\n"); + } + + /* + * USB-C negotiation can outlive probe or fail while a monitor sleeps. + * Register the connector first; the hotplug path owns all USB-C links. + */ + if (disp->usbc) + sink = false; + if (sink) { + ret = t8152_dptx_connect(disp, 0); + if (ret) + return dev_err_probe(dev, ret, "DPTX connect failed\n"); + ret = t8152_dptx_set_hpd(disp, 0, true); + if (ret) + return dev_err_probe(dev, ret, "DPTX hotplug failed\n"); + ret = dcp_iboot_wait_hpd(ib); + if (ret) + return ret; + ret = dcp_iboot_get_modes(ib); + if (ret) + return dev_err_probe(dev, ret, "no modes\n"); + } + ret = dcp_iboot_boot_surface(ib); + if (ret) + return dev_err_probe(dev, ret, "no boot surface\n"); + /* Keep an idle connector registered while the PD controller negotiates. */ + if (!sink) { + dev_info(dev, "waiting for a USB-C display\n"); + goto register_kms; + } + disp->hpd = 1; + /* + * Without the bootloader's link (no display on the port at boot) the + * PHY starts cold, the right way round for the plug. + */ + if (disp->phy->detect && disp->phy->set_orientation) { + bool flipped; + + if (disp->phy->detect(disp, &flipped) > 0) { + if (disp->phy->select) + disp->phy->select(disp); + disp->phy->set_orientation(disp, flipped); + } + } + ret = disp->phy->activate(disp); + if (ret) + return dev_err_probe(dev, ret, "PHY activation failed\n"); + /* While the display is still off and the firmware does no AUX. */ + dcp_iboot_update_edid(ib); + ret = ibootep_set_power(dcp, true); + if (ret) + return dev_err_probe(dev, ret, "set_power failed\n"); + ib->powered = true; + dev_info(dev, "%u timing modes, %u color modes\n", ib->nr_tmodes, + ib->nr_cmodes); + +register_kms: + ret = dcp_iboot_kms_init(ib); + if (ret) + return ret; + if (sink) { + ret = dcp_iboot_set_boot_mode(ib); + if (ret) + dev_warn(dev, "boot mode not set again: %d\n", ret); + } + ret = drm_dev_register(&ib->drm, 0); + if (ret) + return ret; + WRITE_ONCE(ib->ready, true); + if (disp->hpd_gpio || disp->usbc) + drmm_kms_helper_poll_init(&ib->drm); + if (disp->usbc) + queue_delayed_work(system_freezable_wq, &ib->hpd_work, + msecs_to_jiffies(250)); + drm_client_setup(&ib->drm, NULL); + return 0; +} + +/* + * hdmi_np: DCPEXT0's node, which describes the HDMI PHY; its source select + * names the DCP driving HDMI (0 the main DCP, 1 DCPEXT0). On the J873g, + * iBoot lights only a monitor on the back-right port, through the main DCP, + * and leaves HDMI to the kernel even when HDMI is the only display. A + * source a bootloader did set is still adopted. + */ +int dcp_iboot_probe(struct apple_dcp *dcp) +{ + struct device *dev = dcp->dev; + /* Read by whichever DCP probes first, before any DCP drives a port. */ + int boot_link = t8152_atc_boot_link(dev); + struct device_node *hdmi_np __free(device_node) = t8152_hdmi_node(); + int source = hdmi_np ? t8152_hdmi_source(hdmi_np) : -ENODEV; + struct t8152_display *disp; + struct dcp_iboot *ib; + u32 dp_source = 0; + bool main_dcp; + u32 live; + int ret; + + if (dev->of_node == hdmi_np && source != 1 && + !of_property_present(dev->of_node, "apple,usb-c-ports")) { + dev_info(dev, "%s\n", source == 0 ? "HDMI is on the main DCP" : + "no bootloader HDMI link to adopt"); + return -ENODEV; + } + + /* + * A main DCP that the bootloader left without a display cannot power + * one: its SET_POWER never completes, on HDMI or USB-C. It has one + * when it drives HDMI or the bootloader's link on a USB-C port; none + * when iBoot found no monitor on back-right, with HDMI alone too. Then + * leave its outputs to the DCPEXTs, which start cold, and the shared + * HDMI port with them. If the ports could not be read, bind as before. + */ + of_property_read_u32(dev->of_node, "apple,dp-source", &dp_source); + main_dcp = dev->of_node != hdmi_np && !dp_source; + if (main_dcp && source != 0 && boot_link == 0) { + dcp_iboot_drop_boot_fbs(); + dev_info(dev, "no display from the bootloader: main DCP off, the DCPEXTs drive the outputs\n"); + return -ENODEV; + } + + /* + * The bootloader's AFK endpoint hand-off: without it there is no + * telling whether an endpoint is live, and an INIT on a live one + * asserts in the firmware. + */ + ret = of_property_read_u32(dev->of_node, "apple,afk-active-endpoints", &live); + if (ret || live & ~GENMASK(15, 0)) + return dev_err_probe(dev, -EINVAL, + "bootloader AFK endpoint handoff required\n"); + + ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64)); + if (ret) + return ret; + + ib = dcp_iboot_alloc(dev); + if (IS_ERR(ib)) + return PTR_ERR(ib); + ib->dcp = dcp; + disp = &ib->disp; + disp->dcp = dcp; + disp->dev = dev; + disp->dp_source = dev->of_node == hdmi_np ? 1 : 0; + of_property_read_u32(dev->of_node, "apple,dp-source", &disp->dp_source); + if (disp->dp_source > 2) + return -EINVAL; + of_property_read_u32(dev->of_node, "apple,die", &disp->die); + dcp->afk_live_endpoints = live; + mutex_init(&ib->lock); + INIT_DELAYED_WORK(&ib->av_work, dcp_iboot_av_work); + + ret = dcp_iboot_scanout_init(ib); + if (ret) + return dev_err_probe(dev, ret, "no scanout DART stream\n"); + + disp->hdmi = source >= 0 && source == disp->dp_source; + if (disp->hdmi && dev->of_node != hdmi_np) + dev_info(dev, "HDMI from the main DCP (no USB-C display at boot)\n"); + /* Read only: the pin belongs to a controller the AOP runs. */ + disp->hpd_gpio = NULL; + if (disp->hdmi) + disp->hpd_gpio = devm_fwnode_gpiod_get(dev, of_fwnode_handle(hdmi_np), + "hpd", GPIOD_ASIS, "hpd"); + if (PTR_ERR(disp->hpd_gpio) == -ENOENT) + disp->hpd_gpio = NULL; + if (IS_ERR(disp->hpd_gpio)) + return dev_err_probe(dev, PTR_ERR(disp->hpd_gpio), "no HPD GPIO\n"); + disp->hpd = 0; + ret = disp->hdmi ? t8152_hdmi_init(disp, hdmi_np) : t8152_atc_init(disp); + if (ret) + return dev_err_probe(dev, ret, "no DisplayPort PHY\n"); + /* Nobody has HDMI from the bootloader: it is one of the shared ports. */ + if (!disp->hdmi && source < 0 && hdmi_np) { + ret = t8152_hdmi_port_init(disp, hdmi_np); + if (ret) + return dev_err_probe(dev, ret, "no shared HDMI port\n"); + } + + WRITE_ONCE(dcp->t8152, disp); + WRITE_ONCE(dcp->iboot, ib); + ret = dcp_iboot_boot(ib); + if (IS_ERR_OR_NULL(dcp->rtk)) { + dcp->rtk = NULL; + return dev_err_probe(dev, ret, "cannot adopt the DCP\n"); + } + /* + * From here on the DCP may DMA into what this driver gives it, and + * there is no safe way to stop it: retain the session until reboot. + */ + if (dcp_retain_live_session(dcp)) { + dev_warn(dev, "live session not recorded; its DMA stays allocated\n"); + WRITE_ONCE(dcp->retain_dma, true); + } + /* The device stays bound from here on: follow the USB-C ports. */ + if (t8152_typec_init(disp)) + dev_err(dev, "USB-C ports not followed, no USB-C display\n"); + if (ret) + dev_err(dev, "cannot adopt the DCP: %d\n", ret); + else + ret = dcp_iboot_start(ib); + if (!ret) + return 0; + + /* + * Gate RX before draining endpoint work; keep RTKit available until + * every sender has stopped. Do not reclaim firmware-visible storage + * or let the driver core retry a partially started session. + */ + dcp_iboot_detach(ib); + dev_err(dev, "initialization failed (%d); live DMA resources retained until reboot\n", + ret); + return 0; +} + +/* An unbind: the DRM device goes, the firmware session and its DMA stay. */ +void dcp_iboot_remove(struct apple_dcp *dcp) +{ + struct dcp_iboot *ib = dcp->iboot; + bool registered; + + if (!ib) + return; + registered = READ_ONCE(ib->ready); + if (ib->drm.mode_config.poll_enabled) + drm_kms_helper_poll_disable(&ib->drm); + if (!READ_ONCE(dcp->quiescing)) + dcp_iboot_detach(ib); + if (registered) { + drm_dev_unplug(&ib->drm); + /* Drops the committed state's connector reference. */ + drm_atomic_helper_shutdown(&ib->drm); + } +} diff --git a/drivers/gpu/drm/apple/iomfb_iboot.h b/drivers/gpu/drm/apple/iomfb_iboot.h new file mode 100644 index 00000000000000..bddeeedc198d52 --- /dev/null +++ b/drivers/gpu/drm/apple/iomfb_iboot.h @@ -0,0 +1,146 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * DCP_FIRMWARE_IBOOT: a T8152 DCP driven through its firmware's iBoot + * interface alone, with a DRM device of its own (iomfb_iboot.c, iboot_drm.c). + */ +#ifndef __APPLE_IOMFB_IBOOT_H__ +#define __APPLE_IOMFB_IBOOT_H__ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "ibootep.h" +#include "t8152_display.h" + +struct apple_dcp; +struct device; +struct drm_edid; +struct iommu_domain; +struct platform_device; + +struct dcp_iboot_dma { + void *cpu; + dma_addr_t iova; + size_t size; +}; + +/* + * Scanout buffers, each for the largest mode: a frame is copied into one not + * on screen, which SET_SURFACE then shows. Copying into the buffer being + * scanned out tore every frame. Three, so the one written next left the + * screen a frame ago. + */ +#define DCP_IBOOT_SCANOUT_BUFS 3 + +struct dcp_iboot { + struct drm_device drm; + struct apple_dcp *dcp; + struct t8152_display disp; + + /* The DRM device is registered and the session up. */ + bool ready; + bool kms_work_ready; + + /* The scanout DART's own device and domain (dcp_iboot_scanout_init()). */ + struct platform_device *scanout; + struct iommu_domain *scanout_dom; + struct dcp_iboot_dma scan[DCP_IBOOT_SCANOUT_BUFS]; + /* their pages write-combined: the pipe does not snoop the CPU caches */ + void *scan_wc[DCP_IBOOT_SCANOUT_BUFS]; + /* their addresses in the display pipe's DART */ + dma_addr_t scan_dva[DCP_IBOOT_SCANOUT_BUFS]; + /* scan[front] is on screen (or set as the surface at the next power on) */ + unsigned int front; + /* the part of the current picture scan[i] does not hold yet */ + struct drm_rect stale[DCP_IBOOT_SCANOUT_BUFS]; + /* when scan[i] stopped being the requested surface */ + ktime_t retired[DCP_IBOOT_SCANOUT_BUFS]; + /* the last SET_SURFACE of a new buffer */ + ktime_t last_swap; + /* + * A frame written within one refresh of the last swap waits in + * scan[pending] (-1: none) for swap_timer, at most one swap per + * refresh; a newer frame overwrites it. + */ + int pending; + u32 pending_w, pending_h, pending_pitch; + struct hrtimer swap_timer; + struct work_struct swap_work; + u32 boot_w, boot_h, boot_stride; + + /* the sink's EDID, read through the PHY (NULL if unavailable) */ + const struct drm_edid *edid; + + /* iBoot state below, under lock */ + struct mutex lock; + bool enabled; + bool powered; + struct iboot_timing_mode *tmodes; + unsigned int nr_tmodes; + struct iboot_color_mode *cmodes; + unsigned int nr_cmodes; + struct iboot_timing_mode cur_mode; + bool mode_set; + /* SET_MODE of cur_mode failed; the next plug sets it again */ + bool mode_failed; + /* USB-C: connect the sink anew when it stopped answering */ + struct work_struct relink_work; + unsigned long relink_time; + /* + * The DPAV video interface started: SET_MODE again, or the + * firmware's idle power off timer takes the link down 30 s later. + */ + struct delayed_work av_work; + struct delayed_work hpd_work; + + struct drm_plane plane; + struct drm_crtc crtc; + struct drm_encoder encoder; + struct drm_connector connector; +}; + +static inline struct dcp_iboot *to_dcp_iboot(struct drm_device *drm) +{ + return container_of(drm, struct dcp_iboot, drm); +} + +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8152) +/* t8152_typec.c */ +void t8152_typec_register(struct device *dev); +void t8152_typec_unregister(void); + +/* iomfb_iboot.c */ +int dcp_iboot_probe(struct apple_dcp *dcp); +void dcp_iboot_remove(struct apple_dcp *dcp); +int dcp_iboot_wait_hpd(struct dcp_iboot *ib); +int dcp_iboot_get_modes(struct dcp_iboot *ib); + +/* iboot_drm.c */ +struct dcp_iboot *dcp_iboot_alloc(struct device *dev); +const char *dcp_iboot_driver_name(void); +int dcp_iboot_kms_init(struct dcp_iboot *ib); +void dcp_iboot_kms_stop(struct dcp_iboot *ib); +int dcp_iboot_set_boot_mode(struct dcp_iboot *ib); +void dcp_iboot_update_edid(struct dcp_iboot *ib); +void dcp_iboot_reset_mode(struct dcp_iboot *ib); +void dcp_iboot_av_started(struct dcp_iboot *ib); +void dcp_iboot_hpd_event(struct dcp_iboot *ib); +#else +static inline void t8152_typec_register(struct device *dev) { } +static inline void t8152_typec_unregister(void) { } +static inline int dcp_iboot_probe(struct apple_dcp *dcp) { return -ENODEV; } +static inline void dcp_iboot_remove(struct apple_dcp *dcp) { } +#endif + +#endif diff --git a/drivers/gpu/drm/apple/iomfb_internal.h b/drivers/gpu/drm/apple/iomfb_internal.h index 1fcaa17574dbe2..ba804e3618cf8e 100644 --- a/drivers/gpu/drm/apple/iomfb_internal.h +++ b/drivers/gpu/drm/apple/iomfb_internal.h @@ -66,11 +66,11 @@ typedef void (*dcp_callback_t)(struct apple_dcp *, void *, void *); #define TRAMPOLINE_IN(func, handler, T_in) \ typedef void (*callback_##handler)(struct apple_dcp *, T_in *); \ - \ + \ static bool __maybe_unused func(struct apple_dcp *dcp, int tag, void *out, void *in) \ { \ callback_##handler cb = handler; \ - \ + \ trace_iomfb_callback(dcp, tag, #handler); \ cb(dcp, in); \ return true; \ @@ -78,12 +78,12 @@ typedef void (*dcp_callback_t)(struct apple_dcp *, void *, void *); #define TRAMPOLINE_INOUT(func, handler, T_in, T_out) \ typedef T_out (*callback_##handler)(struct apple_dcp *, T_in *); \ - \ + \ static bool __maybe_unused func(struct apple_dcp *dcp, int tag, void *out, void *in) \ { \ T_out *typed_out = out; \ callback_##handler cb = handler; \ - \ + \ trace_iomfb_callback(dcp, tag, #handler); \ *typed_out = cb(dcp, in); \ return true; \ @@ -93,7 +93,7 @@ typedef void (*dcp_callback_t)(struct apple_dcp *, void *, void *); static bool __maybe_unused func(struct apple_dcp *dcp, int tag, void *out, void *in) \ { \ T_out *typed_out = out; \ - \ + \ trace_iomfb_callback(dcp, tag, #handler); \ *typed_out = handler(dcp); \ return true; \ @@ -124,6 +124,8 @@ u8 dcp_crtc_eotf(struct apple_dcp *dcp, struct drm_crtc *crtc, int dcp_crtc_check_hdr(struct apple_dcp *dcp, struct drm_crtc *crtc, struct drm_atomic_commit *commit); void dcp_hdr_metadata_forget(struct apple_dcp *dcp); +void dcp_hdr_service_bind(struct apple_epic_service *service); +void dcp_hdr_service_unbind(struct apple_epic_service *service); int iomfb_ext26_blank(struct apple_dcp *dcp); bool iomfb_ext26_backing_fresh(struct apple_dcp *dcp, struct drm_framebuffer *fb); int iomfb_ext26_retain_epoch(struct apple_dcp *dcp); diff --git a/drivers/gpu/drm/apple/iomfb_m4.c b/drivers/gpu/drm/apple/iomfb_m4.c index 42caa27a508a06..da94f912821e48 100644 --- a/drivers/gpu/drm/apple/iomfb_m4.c +++ b/drivers/gpu/drm/apple/iomfb_m4.c @@ -2725,7 +2725,12 @@ int iomfb_m4_init(struct apple_dcp *owner) return -ENOMEM; dcp->owner = owner; dcp->dev = dev; - dcp->bw_mailbox = dcp_m4_bw_mailbox(dev); + /* + * The 26.6.2 panel path runs without the realtime bandwidth mailbox; + * the slot the DT gives the internal DCP is the firmware-27 backend's. + */ + if (external) + dcp->bw_mailbox = dcp_m4_bw_mailbox(dev); mutex_init(&dcp->lock); mutex_init(&dcp->ext_modes_lock); spin_lock_init(&dcp->state_lock); @@ -5836,6 +5841,23 @@ bool iomfb_m4_ext_stopped(struct apple_dcp *owner) return stopped; } +/* + * Its CPU is down for the sleep: an external DCP stopped for a deep sleep, or + * an internal one powered down with its domains (iomfb_m4_power_gate()). + */ +bool iomfb_m4_sleep_stopped(struct apple_dcp *owner) +{ + struct iomfb_m4 *dcp = owner->v26_6; + bool stopped; + + if (!dcp) + return false; + mutex_lock(&dcp->lock); + stopped = dcp->ext_stopped || dcp->gated; + mutex_unlock(&dcp->lock); + return stopped; +} + /* apple-drm, a consumer of this device, has blanked the panel before this. */ int iomfb_m4_suspend(struct apple_dcp *owner) { diff --git a/drivers/gpu/drm/apple/iomfb_m4.h b/drivers/gpu/drm/apple/iomfb_m4.h index 6e09d07e0c8994..cfd10118d0836b 100644 --- a/drivers/gpu/drm/apple/iomfb_m4.h +++ b/drivers/gpu/drm/apple/iomfb_m4.h @@ -81,6 +81,7 @@ void iomfb_m4_ext_relink_lost(struct apple_dcp *dcp); void iomfb_m4_ext_relink_wait(struct apple_dcp *dcp, unsigned long deadline); int iomfb_m4_ext_relink_end(struct apple_dcp *dcp); bool iomfb_m4_ext_stopped(struct apple_dcp *dcp); +bool iomfb_m4_sleep_stopped(struct apple_dcp *dcp); /* The caller has waited for the producer fence before publishing the DMA GEM. */ int iomfb_m4_present(struct apple_dcp *dcp, struct drm_framebuffer *fb, @@ -164,6 +165,7 @@ static inline void iomfb_m4_ext_relink_lost(struct apple_dcp *dcp) { } static inline void iomfb_m4_ext_relink_wait(struct apple_dcp *dcp, unsigned long deadline) { } static inline int iomfb_m4_ext_relink_end(struct apple_dcp *dcp) { return 0; } static inline bool iomfb_m4_ext_stopped(struct apple_dcp *dcp) { return false; } +static inline bool iomfb_m4_sleep_stopped(struct apple_dcp *dcp) { return false; } static inline int iomfb_m4_present(struct apple_dcp *dcp, struct drm_framebuffer *fb, dma_addr_t dva, size_t mapped) diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 0e9064dcb289b9..050522f5a6fda5 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -669,9 +670,15 @@ static void dcp_external_hint_done(struct apple_dcp *dcp, void *out, void *cooki /* * After every mode set on an external display macOS sends IOMFB * parameters 3 and 6 (16.16): 3 at 1.0, and 6 at 1.0 for an SDR colour - * mode or 2.0 for a PQ one. Send the same, after the mode set. Only the - * H17P external path does so for now: the desktop 26.x external processors - * have not been checked with an HDR display yet. + * mode or 2.0 for a PQ one. Send the same, after the mode set. + * + * Every firmware has set_parameter_dcp, but the parameter numbers are the + * firmware's own, so the hints follow the firmware ABI rather than the + * method's presence: the H17P external firmware (26.6.2) and an unpaired + * external firmware 27 processor, the two on which macOS was seen sending + * them (iomfb_modeset()). The desktop 26.6 firmware is built without + * them, and older firmware is not sent them: no macOS trace shows what + * those builds take under these numbers. */ static void dcp_external_hdr_hints(struct apple_dcp *dcp, bool pq) { @@ -737,7 +744,7 @@ static u32 dcpep_cb_zero(struct apple_dcp *dcp) return 0; } -static void dcp_report_swap_complete(struct apple_dcp *dcp, u32 id, ktime_t now) +static void dcp_report_swap_complete(struct apple_dcp *dcp, u32 id, ktime_t now, bool shown) { bool retire = true; if (dcp_is_ext26(dcp)) { @@ -790,8 +797,18 @@ static void dcp_report_swap_complete(struct apple_dcp *dcp, u32 id, ktime_t now) dcp->crashed = true; return; } - if (dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17G) + if (dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17G) { + /* Only a displayed KMS swap that touched boot slot zero retires it. */ + if (dcp->boot_surface_pending && shown && dcp->iomfb.next_scanout && + !iomfb_present_brightness_only_h17p(dcp) && + (DCP_FW_SWAP(dcp).swap.swap_enabled & BIT(0))) { + WRITE_ONCE(dcp->boot_surface_pending, false); + dev_info(dcp->dev, "boot scanout retired by displayed swap %u\n", id); + if (dcp->boot_scanout_reserved) + apple_mcc_boot_scanout_retired(dcp->dev->of_node); + } retire = iomfb_present_complete_h17p(dcp); + } #endif #if DCP_FW_DESKTOP_26(DCP_FW_VER) /* Late or duplicate completions cannot retire the replacement's flip. */ @@ -825,15 +842,17 @@ static void dcp_report_swap_complete(struct apple_dcp *dcp, u32 id, ktime_t now) } #if (DCP_FW_H17(DCP_FW_VER) && DCP_FW_VER >= DCP_FW_VERSION(27, 0, 0)) -struct dcp_peer_completion { u32 id; ktime_t time; }; +struct dcp_peer_completion { u32 id; ktime_t time; bool shown; }; + static void dcp_peer_report_on_owner(struct apple_dcp *owner, void *data, void *cookie) { struct dcp_peer_completion *completion = data; - dcp_report_swap_complete(owner, completion->id, completion->time); + dcp_report_swap_complete(owner, completion->id, completion->time, completion->shown); } -static void dcp_peer_queue_completion(struct apple_dcp *owner, u32 id, ktime_t time) + +static void dcp_peer_queue_completion(struct apple_dcp *owner, u32 id, ktime_t time, bool shown) { - struct dcp_peer_completion completion = { id, time }; + struct dcp_peer_completion completion = { id, time, shown }; if (iomfb_queue_callback(owner, dcp_peer_report_on_owner, &completion, sizeof(completion), NULL)) { WRITE_ONCE(owner->crashed, true); @@ -842,16 +861,28 @@ static void dcp_peer_queue_completion(struct apple_dcp *owner, u32 id, ktime_t t } #endif -static void dcpep_cb_swap_complete(struct apple_dcp *dcp, - struct DCP_FW_NAME(dc_swap_complete_resp) *resp) +/* Only the swap id of a swap_complete record is used. */ +static void dcp_swap_complete_id(struct apple_dcp *dcp, u32 swap_id, bool shown) { ktime_t now = dcp_is_ext26(dcp) ? ns_to_ktime(dcp->ext26_rx_ns) : ktime_get(); - trace_iomfb_swap_complete(dcp, resp->swap_id); + trace_iomfb_swap_complete(dcp, swap_id); #if (DCP_FW_H17(DCP_FW_VER) && DCP_FW_VER >= DCP_FW_VERSION(27, 0, 0)) - if (dcp_peer_swap_complete_v27(dcp, resp->swap_id, now, dcp_peer_queue_completion)) + if (dcp_peer_swap_complete_v27(dcp, swap_id, now, shown, + dcp_peer_queue_completion)) return; #endif - dcp_report_swap_complete(dcp, resp->swap_id, now); + dcp_report_swap_complete(dcp, swap_id, now, shown); +} + +static void dcpep_cb_swap_complete(struct apple_dcp *dcp, + struct DCP_FW_NAME(dc_swap_complete_resp) *resp) +{ + bool shown = false; + +#if DCP_FW_H17(DCP_FW_VER) + shown = resp->unkbool; +#endif + dcp_swap_complete_id(dcp, resp->swap_id, shown); } /* special */ @@ -1483,8 +1514,7 @@ static u64 dcpep_cb_get_frequency(struct apple_dcp *dcp) return clk_get_rate(dcp->clk); } -#if DCP_FW_VER >= DCP_FW_VERSION(13, 2, 0) && !DCP_FW_H17(DCP_FW_VER) && \ - !DCP_FW_DESKTOP_26(DCP_FW_VER) +#if DCP_FW_VER >= DCP_FW_VERSION(13, 2, 0) && !DCP_FW_DESKTOP_26(DCP_FW_VER) /* The DVA that map_reg hands out for display register range @index. */ static dma_addr_t dcpep_map_reg_dva(struct apple_dcp *dcp, u32 index, struct resource *rsrc) @@ -1531,6 +1561,17 @@ static struct DCP_FW_NAME(dcp_map_reg_resp) dcpep_cb_map_reg(struct apple_dcp *d */ dma_addr_t dva = dcp->fw_compat == DCP_FIRMWARE_V_27_0 ? dcp->disp_firmware_base[req->index] : rsrc->start; + + /* Where firmware 27 goes through its DART: mapped there, once. */ + if (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && dcp->hw.map_reg_dart) { + if (!dcp->map_reg_dva[req->index]) { + dva = dcpep_map_reg_dva(dcp, req->index, rsrc); + if (WARN_ON(dva == DMA_MAPPING_ERROR)) + return (struct DCP_FW_NAME(dcp_map_reg_resp)) { .ret = 1 }; + dcp->map_reg_dva[req->index] = dva; + } + dva = dcp->map_reg_dva[req->index]; + } #elif DCP_FW_DESKTOP_26(DCP_FW_VER) /* * The desktop 26.x firmware takes the register windows' @@ -2555,6 +2596,7 @@ void DCP_FW_NAME(iomfb_poweron)(struct apple_dcp *dcp) u32 handle; #endif dev_info(dcp->dev, "dcp_poweron() starting\n"); + WRITE_ONCE(dcp->pipe_off, false); #if DCP_FW_H17(DCP_FW_VER) if (dcp_is_ext26(dcp)) return; /* Native26 publishes A473 only after a successful A413. */ @@ -2767,6 +2809,40 @@ int DCP_FW_NAME(iomfb_s2r_power)(struct apple_dcp *dcp, bool on, bool named_call } #endif +#if DCP_FW_DESKTOP_26(DCP_FW_VER) +DCP_THUNK_IN(dcp_unnamed_500, dcpep_unnamed_500, u32); + +static void dcp_s2r_500_done(struct apple_dcp *dcp, void *out, void *cookie) +{ + struct dcp_wait_cookie *wait = cookie; + + complete(&wait->done); + kref_put(&wait->refcount, release_wait_cookie); +} + +/* Sleep test: H17P's A500, same number and bytes as this firmware's neighbours. */ +int DCP_FW_NAME(iomfb_s2r_500)(struct apple_dcp *dcp) +{ + struct dcp_wait_cookie *cookie; + unsigned long left; + u32 val = 0xaaaa0000; + + cookie = kzalloc_obj(*cookie); + if (!cookie) + return -ENOMEM; + init_completion(&cookie->done); + kref_init(&cookie->refcount); + kref_get(&cookie->refcount); + + dcp_unnamed_500(dcp, false, &val, dcp_s2r_500_done, cookie); + + left = wait_for_completion_timeout(&cookie->done, msecs_to_jiffies(1000)); + kref_put(&cookie->refcount, release_wait_cookie); + + return left ? 0 : -ETIMEDOUT; +} +#endif + static bool dcp_power_stop_confirmed(struct dcp_wait_cookie *cookie) { /* H17P does not confirm that scanout has stopped. */ @@ -2850,9 +2926,27 @@ void DCP_FW_NAME(iomfb_poweroff)(struct apple_dcp *dcp) #endif #if DCP_FW_H17(DCP_FW_VER) - /* H17P has no known safe pipe-off or surface-free transition. */ - if (dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17G) - return; + /* + * H17P has no known safe pipe-off or surface-free transition for + * its panel. An external pipe stops like the H17G one: otherwise + * DPMS off leaves it scanning out the last frame. + */ + if (dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17G) { + if (dcp_has_panel(dcp)) + return; + /* + * The firmware withdrew the mode (it is describing the display + * again after a hotplug, see dcp_mode_withdraw()): no scanout of + * ours is left to stop, and while it republishes the display it + * answers neither the clear swap nor setPowerState(0). Both then + * time out and leave the pipe unable to power on again. + */ + if (!READ_ONCE(dcp->mode_state.valid)) { + dev_dbg(dcp->dev, "%s: no valid mode, pipe left to the firmware\n", + __func__); + return; + } + } #endif #if DCP_FW_DESKTOP_26(DCP_FW_VER) @@ -2873,7 +2967,8 @@ void DCP_FW_NAME(iomfb_poweroff)(struct apple_dcp *dcp) kref_get(&cookie->refcount); #if DCP_FW_H17(DCP_FW_VER) - if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17G) + if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17G || + !dcp_has_panel(dcp)) dcp_prepare_clear_swap(dcp, swap); #else #if DCP_FW_DESKTOP_26(DCP_FW_VER) @@ -2952,10 +3047,12 @@ void DCP_FW_NAME(iomfb_poweroff)(struct apple_dcp *dcp) dev_dbg(dcp->dev, "setPowerState(0) finished with %d ms to spare", jiffies_to_msecs(ret)); - if (dcp_power_stop_confirmed(poff_cookie)) + if (dcp_power_stop_confirmed(poff_cookie)) { dcp_release_all_retained_framebuffers(dcp); - else + WRITE_ONCE(dcp->pipe_off, true); + } else { dev_warn(dcp->dev, "scanout stop was not confirmed\n"); + } } kref_put(&poff_cookie->refcount, release_wait_cookie); @@ -3207,6 +3304,12 @@ dcpep_cb_hotplug_v26_6(struct apple_dcp *dcp, struct dcp_hotplug_req_v26_6 *req) if (!dcp->main_display && !connected) dcp->desktop->ext_pipe_off = true; + /* Signal T6041 S2R resume before dcpep_cb_hotplug() skips main_display. */ + if (connected) { + dev_dbg(dcp->dev, "D575 hotplug connected=1\n"); + complete(&dcp->s2r_hpd_done); + } + dcpep_cb_hotplug(dcp, &connected); if (paired && tiled_valid) @@ -3471,13 +3574,11 @@ static void dcp_swapped(struct apple_dcp *dcp, void *data, void *cookie) return; } if (dcp_is_ext26(dcp) && dcp->ext26_early_complete && dcp->ext26_early_id == swap_id) { - struct DCP_FW_NAME(dc_swap_complete_resp) completed = { .swap_id = swap_id }; - u64 received = dcp->ext26_rx_ns; dcp->ext26_early_complete = false; dcp->ext26_rx_ns = dcp->ext26_early_ns; - dcpep_cb_swap_complete(dcp, &completed); + dcp_swap_complete_id(dcp, swap_id, false); dcp->ext26_rx_ns = received; return; } @@ -3914,12 +4015,16 @@ static void dcp_modeset_select(struct apple_dcp *dcp, void *out, void *cookie) int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, struct drm_crtc_state *crtc_state) { - struct dcp_display_mode selected, *mode = &selected; + struct dcp_display_mode *mode __free(kfree) = kzalloc_obj(*mode); struct dcp_modeset_cookie *modeset; struct dcp_wait_cookie *cookie; + struct dcp_color_mode selected_color = { .score = -1 }; struct dcp_color_mode *cmode = NULL; int ret; + if (!mode) + return -ENOMEM; + if (dcp->crashed) return -ENODEV; /* A timed-out command still owns its channel until firmware replies. */ @@ -3932,35 +4037,44 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, return -EIO; } - /* An HDR commit scans out through the timing's PQ element. */ - if (dcp->pq_requested && mode->pq.score >= 0) + if (!dcp_select_color_mode(mode, &dcp->color_req, &selected_color)) { + mode->color_mode_id = selected_color.id; + cmode = &selected_color; + } else if (dcp->pq_requested && mode->pq.score >= 0) { mode->color_mode_id = mode->pq.id; - - dev_dbg(dcp->dev, - "set_digital_out_mode(color:%d timing:%d) " DRM_MODE_FMT "\n", - mode->color_mode_id, mode->timing_mode_id, - DRM_MODE_ARG(&crtc_state->mode)); - if (mode->color_mode_id == mode->pq.id && mode->pq.score >= 0) cmode = &mode->pq; - else if (mode->color_mode_id == mode->sdr_rgb.id) + } else if (mode->color_mode_id == mode->sdr_rgb.id) { cmode = &mode->sdr_rgb; - else if (mode->color_mode_id == mode->sdr_444.id) + } else if (mode->color_mode_id == mode->sdr_444.id) { cmode = &mode->sdr_444; - else if (mode->color_mode_id == mode->sdr.id) + } else if (mode->color_mode_id == mode->sdr.id) { cmode = &mode->sdr; - else if (mode->color_mode_id == mode->best.id) + } else if (mode->color_mode_id == mode->best.id) { cmode = &mode->best; + } + + dev_dbg(dcp->dev, + "set_digital_out_mode(color:%d timing:%d) " DRM_MODE_FMT "\n", + mode->color_mode_id, mode->timing_mode_id, + DRM_MODE_ARG(&crtc_state->mode)); if (cmode) dev_dbg(dcp->dev, "color mode depth:%hhu format:%u colorimetry:%u eotf:%u range:%u vrr:%u\n", cmode->depth, cmode->format, cmode->colorimetry, cmode->eotf, cmode->range, mode->vrr); - dcp->mode = (struct dcp_set_digital_out_mode_req) { - .color_mode_id = mode->color_mode_id, - .timing_mode_id = mode->timing_mode_id - }; - dcp->output_pq = dcp->pq_requested && mode->pq.score >= 0; + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + dcp->mode = (struct dcp_set_digital_out_mode_req) { + .color_mode_id = mode->color_mode_id, + .timing_mode_id = mode->timing_mode_id + }; + if (cmode) + dcp->active_color = *cmode; + else + dcp->active_color.score = -1; + dcp->output_pq = cmode && cmode->eotf == DCP_EOTF_ST_2084; + dcp->output_hdr = cmode && cmode->eotf != DCP_EOTF_SDR_GAMMA; + } /* VRR modes need swap timestamps, see iomfb_flush(); so do fixed internal timings. */ dcp->use_timestamps = mode->needs_timestamps; @@ -4176,13 +4290,17 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, #endif ) { - struct dcp_display_mode selected, *mode = &selected; + struct dcp_display_mode *mode __free(kfree) = kzalloc_obj(*mode); struct dcp_wait_cookie *cookie; + struct dcp_color_mode selected_color = { .score = -1 }; struct dcp_color_mode *cmode = NULL; bool paired = false; bool keep_mode = false; int ret; + if (!mode) + return -ENOMEM; + #if DCP_FW_H17(DCP_FW_VER) && DCP_FW_VER < DCP_FW_VERSION(27, 0, 0) if (dcp_is_ext26(dcp)) { u32 pitch = primary && primary->fb ? primary->fb->pitches[0] : dcp->ext26_stride; @@ -4219,9 +4337,21 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, return -EIO; } - /* An HDR commit scans out through the timing's PQ element. */ - if (dcp->pq_requested && mode->pq.score >= 0) + if (!dcp_select_color_mode(mode, &dcp->color_req, &selected_color)) { + mode->color_mode_id = selected_color.id; + cmode = &selected_color; + } else if (dcp->pq_requested && mode->pq.score >= 0) { mode->color_mode_id = mode->pq.id; + cmode = &mode->pq; + } else if (mode->color_mode_id == mode->sdr_rgb.id) { + cmode = &mode->sdr_rgb; + } else if (mode->color_mode_id == mode->sdr_444.id) { + cmode = &mode->sdr_444; + } else if (mode->color_mode_id == mode->sdr.id) { + cmode = &mode->sdr; + } else if (mode->color_mode_id == mode->best.id) { + cmode = &mode->best; + } /* The connection's audio link runs through the mode set. */ av_audio_before_modeset(dcp); @@ -4230,16 +4360,6 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, "set_digital_out_mode(color:%d timing:%d) " DRM_MODE_FMT "\n", mode->color_mode_id, mode->timing_mode_id, DRM_MODE_ARG(&crtc_state->mode)); - if (mode->color_mode_id == mode->pq.id && mode->pq.score >= 0) - cmode = &mode->pq; - else if (mode->color_mode_id == mode->sdr_rgb.id) - cmode = &mode->sdr_rgb; - else if (mode->color_mode_id == mode->sdr_444.id) - cmode = &mode->sdr_444; - else if (mode->color_mode_id == mode->sdr.id) - cmode = &mode->sdr; - else if (mode->color_mode_id == mode->best.id) - cmode = &mode->best; if (dcp_is_ext26(dcp)) { if (mode->sdr_rgb.score < 0 || mode->sdr_rgb.depth != 8 || mode->sdr_rgb.format != DCP_COLOR_FORMAT_RGB || crtc_state->vrr_enabled) @@ -4264,12 +4384,34 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, keep_mode = dcp->v27_j714s && xchg(&dcp->v27_keep_mode, false) && dcp->mode.color_mode_id == mode->color_mode_id && dcp->mode.timing_mode_id == mode->timing_mode_id; -#endif - dcp->mode = (struct dcp_set_digital_out_mode_req){ - .color_mode_id = mode->color_mode_id, - .timing_mode_id = mode->timing_mode_id - }; - dcp->output_pq = dcp->pq_requested && mode->pq.score >= 0; + /* + * Firmware 27.2: sent once the panel's video interface is open again and the firmware + * has reported the panel, which it does after the open. + */ + if (keep_mode && iomfb_v27_methods_renumbered(dcp->v27_methods)) { + if (!wait_for_completion_timeout(&dcp->v27_wake_video, + msecs_to_jiffies(V27_WAKE_VIDEO_MS))) + dev_warn(dcp->dev, "V27 wake: panel video interface not open after %u ms\n", + V27_WAKE_VIDEO_MS); + else if (!wait_for_completion_timeout(&dcp->v27_wake_hotplug, + msecs_to_jiffies(V27_WAKE_HOTPLUG_MS))) + dev_warn(dcp->dev, "V27 wake: no hotplug report %u ms after the panel's open\n", + V27_WAKE_HOTPLUG_MS); + keep_mode = false; + } +#endif + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + dcp->mode = (struct dcp_set_digital_out_mode_req){ + .color_mode_id = mode->color_mode_id, + .timing_mode_id = mode->timing_mode_id + }; + if (cmode) + dcp->active_color = *cmode; + else + dcp->active_color.score = -1; + dcp->output_pq = cmode && cmode->eotf == DCP_EOTF_ST_2084; + dcp->output_hdr = cmode && cmode->eotf != DCP_EOTF_SDR_GAMMA; + } /* Built-in ProMotion panels require timestamps even in fixed-120 mode. */ dcp->use_timestamps = mode->needs_timestamps && dcp->main_display; @@ -4324,11 +4466,12 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, complete_set_digital_out_mode(dcp, NULL, cookie); } else #endif - if (mode->vrr && - dcp->hw.iomfb_method_profile != - DCP_IOMFB_METHODS_H17P_EXTERNAL) + if ((mode->vrr || dcp->vrr_enabled) && + dcp->hw.iomfb_method_profile != + DCP_IOMFB_METHODS_H17P_EXTERNAL) dcp_set_adaptive_sync(dcp, - crtc_state->vrr_enabled ? mode->min_vrr : 0, + mode->vrr && crtc_state->vrr_enabled ? + mode->min_vrr : 0, cookie); else dcp_set_digital_out_mode(dcp, false, &dcp->mode, @@ -4398,7 +4541,7 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, /* A firmware 27 pair took them on both engines (dcp_peer_finish_v27()). */ if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL || (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && !dcp_has_panel(dcp) && !paired)) - dcp_external_hdr_hints(dcp, dcp->output_pq); + dcp_external_hdr_hints(dcp, dcp->output_hdr); dcp_link_report(dcp, &crtc_state->mode); return 0; @@ -4498,9 +4641,11 @@ void DCP_FW_NAME(iomfb_flush)(struct apple_dcp *dcp, struct drm_crtc *crtc, stru l = apl_plane->iomfb_surf; req->swap.swap_enabled |= BIT(l); - if (!new_state->fb || !new_state->visible) { + if (!new_state->fb || !new_state->visible) + continue; + /* Never submit a surface with no translation in the scanout DART. */ + if (dcp_fb_mirror(dcp, new_state->fb)) continue; - } req->surf_null[l] = false; has_surface = 1; @@ -4531,14 +4676,39 @@ void DCP_FW_NAME(iomfb_flush)(struct apple_dcp *dcp, struct drm_crtc *crtc, stru req->surf[l].base.colorspace = DCP_COLORSPACE_P3_D65; /* - * On a PQ output the compositor has already encoded RGB - * surfaces for the sink: BT.2020 primaries, PQ code values. - * An EDR panel takes the same and maps them into its headroom. + * On an HDR output the compositor has already encoded RGB + * surfaces for the sink: BT.2020 primaries, PQ or HLG code + * values. An EDR panel takes PQ and maps it into its headroom. + * Wide-gamut SDR outputs tag RGB surfaces with their target + * primaries so DCP passes them through without sRGB gamut + * remapping. */ - if ((dcp->output_pq || dcp->output_edr) && - !new_state->fb->format->is_yuv) { - req->surf[l].base.colorspace = DCP_COLORSPACE_BT2020; - req->surf[l].base.xfer_func = DCP_XFER_FUNC_PQ; + if (!new_state->fb->format->is_yuv) { + if (dcp->output_pq || dcp->output_edr) { + req->surf[l].base.colorspace = DCP_COLORSPACE_BT2020; + req->surf[l].base.xfer_func = DCP_XFER_FUNC_PQ; + } else if (dcp->output_hdr && + dcp->active_color.eotf == DCP_EOTF_BT_2100) { + req->surf[l].base.colorspace = DCP_COLORSPACE_BT2020; + req->surf[l].base.xfer_func = DCP_XFER_FUNC_HLG; + } else if (!dcp_has_panel(dcp) && + dcp->active_color.score >= 0) { + switch (dcp->active_color.colorimetry) { + case DCP_COLORIMETRY_BT2020_RGB: + case DCP_COLORIMETRY_BT2020_YCC: + case DCP_COLORIMETRY_BT2020_CYCC: + req->surf[l].base.colorspace = DCP_COLORSPACE_BT2020; + break; + case DCP_COLORIMETRY_DCI_P3_RGB_D65: + req->surf[l].base.colorspace = DCP_COLORSPACE_P3_D65; + break; + case DCP_COLORIMETRY_DCI_P3_RGB_THEATER: + req->surf[l].base.colorspace = DCP_COLORSPACE_DCI_P3; + break; + default: + break; + } + } } #if DCP_FW_H17(DCP_FW_VER) @@ -4550,14 +4720,28 @@ void DCP_FW_NAME(iomfb_flush)(struct apple_dcp *dcp, struct drm_crtc *crtc, stru if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL && !new_state->fb->format->is_yuv && - req->surf[l].base.colorspace == DCP_COLORSPACE_P3_D65) + req->surf[l].base.colorspace == DCP_COLORSPACE_P3_D65 && + (dcp->active_color.score < 0 || + dcp->active_color.colorimetry != DCP_COLORIMETRY_DCI_P3_RGB_D65)) req->surf[l].base.colorspace = DCP_COLORSPACE_UNSPECIFIED; #endif } +#if DCP_FW_H17(DCP_FW_VER) + /* + * Keep sending an explicit slot-zero update until a displayed KMS + * completion confirms the boot scanout has retired. An enabled primary + * plane is pulled into the atomic commit by apple_atomic_check(); if + * slot zero is still absent here, the primary plane is disabled and + * slot zero should be cleared. + */ + if (dcp->boot_surface_pending && !(req->swap.swap_enabled & BIT(0))) + req->swap.swap_enabled |= BIT(0); +#endif + if (!has_surface && !crtc_state->color_mgmt_changed) { if (crtc_state->enable && crtc_state->active && - !crtc_state->planes_changed) { + !crtc_state->planes_changed && !dcp->boot_surface_pending) { schedule_work(&dcp->vblank_wq); return; } @@ -4714,8 +4898,12 @@ static void res_max_panel_brightness(struct apple_dcp *dcp, void *out, void *coo { u32 peak = out ? get_unaligned_le32(out) >> 16 : 0; - /* Only a peak above the SDR range gives EDR headroom. */ - if (peak > dcp->brightness.maximum && peak <= 10000) { + /* + * Only a panel with EDR headroom (the ADT's EDRPotentialHeadroom) and a + * peak above the SDR range shows PQ content as EDR. + */ + if (dcp->panel.edr_ceiling && peak > dcp->brightness.maximum && + peak <= 10000) { dev_info(dcp->dev, "panel peak luminance %u nits\n", peak); WRITE_ONCE(dcp->panel.peak_nits, peak); } @@ -4919,6 +5107,13 @@ static void dcp_started(struct apple_dcp *dcp, void *data, void *cookie) iomfb_get_color_remap_mode(dcp, false, &color_remap, init_1, cookie); } +/* These sessions program the catalogue's colour ID and tag PQ surfaces. */ +static void iomfb_template_start(struct apple_dcp *dcp) +{ + WRITE_ONCE(dcp->iomfb_template_pq, true); + dcp_start_signal(dcp, false, dcp_started, NULL); +} + void DCP_FW_NAME(iomfb_shutdown)(struct apple_dcp *dcp) { #if DCP_FW_DESKTOP_26(DCP_FW_VER) diff --git a/drivers/gpu/drm/apple/iomfb_template.h b/drivers/gpu/drm/apple/iomfb_template.h index 5820f624350d7d..f4c47eba0406f1 100644 --- a/drivers/gpu/drm/apple/iomfb_template.h +++ b/drivers/gpu/drm/apple/iomfb_template.h @@ -394,6 +394,9 @@ void DCP_FW_NAME(iomfb_poweroff)(struct apple_dcp *dcp); void DCP_FW_NAME(iomfb_sleep)(struct apple_dcp *dcp); void DCP_FW_NAME(iomfb_start)(struct apple_dcp *dcp); void DCP_FW_NAME(iomfb_shutdown)(struct apple_dcp *dcp); +#if DCP_FW_DESKTOP_26(DCP_FW_VER) +int DCP_FW_NAME(iomfb_s2r_500)(struct apple_dcp *dcp); +#endif #if DCP_FW_H17(DCP_FW_VER) int DCP_FW_NAME(iomfb_s2r_500)(struct apple_dcp *dcp); int DCP_FW_NAME(iomfb_s2r_power)(struct apple_dcp *dcp, bool on, bool named_calls, bool oob); diff --git a/drivers/gpu/drm/apple/iomfb_v12_3.c b/drivers/gpu/drm/apple/iomfb_v12_3.c index b2d07426897337..c6726efea47865 100644 --- a/drivers/gpu/drm/apple/iomfb_v12_3.c +++ b/drivers/gpu/drm/apple/iomfb_v12_3.c @@ -1,11 +1,17 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* Copyright The Asahi Linux Contributors */ -/* Include all per-version headers before defining DCP_FW ourself. */ +/* + * Include all per-version headers before defining DCP_FW ourself. + * dcp-internal.h pulls in the remaining ones; included first from inside + * the template, they would rely on #pragma push_macro to keep our DCP_FW, + * which sparse does not implement. + */ #include "iomfb_v12_3.h" #include "iomfb_v13_3.h" #include "iomfb_v14_7_tpl.h" #include "iomfb_h17p.h" +#include "dcp-internal.h" #include "version_utils.h" static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { @@ -105,7 +111,7 @@ void DCP_FW_NAME(iomfb_start)(struct apple_dcp *dcp) { dcp->cb_handlers = cb_handlers; - dcp_start_signal(dcp, false, dcp_started, NULL); + iomfb_template_start(dcp); } #undef DCP_FW_VER diff --git a/drivers/gpu/drm/apple/iomfb_v13_3.c b/drivers/gpu/drm/apple/iomfb_v13_3.c index 6d9caa6b27780f..3521abccf038e6 100644 --- a/drivers/gpu/drm/apple/iomfb_v13_3.c +++ b/drivers/gpu/drm/apple/iomfb_v13_3.c @@ -1,11 +1,17 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* Copyright The Asahi Linux Contributors */ -/* Include all per-version headers before defining DCP_FW ourself. */ +/* + * Include all per-version headers before defining DCP_FW ourself. + * dcp-internal.h pulls in the remaining ones; included first from inside + * the template, they would rely on #pragma push_macro to keep our DCP_FW, + * which sparse does not implement. + */ #include "iomfb_v12_3.h" #include "iomfb_v13_3.h" #include "iomfb_v14_7_tpl.h" #include "iomfb_h17p.h" +#include "dcp-internal.h" #include "version_utils.h" static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { @@ -110,8 +116,12 @@ void DCP_FW_NAME(iomfb_start)(struct apple_dcp *dcp) { dcp->cb_handlers = cb_handlers; - dcp_start_signal(dcp, false, dcp_started, NULL); + iomfb_template_start(dcp); } #undef DCP_FW_VER #undef DCP_FW + +#if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) +#include "iomfb-legacy-methods-test.c" +#endif diff --git a/drivers/gpu/drm/apple/iomfb_v14_7.c b/drivers/gpu/drm/apple/iomfb_v14_7.c index a99bfed67183fd..5b0983a643b748 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7.c @@ -42,6 +42,7 @@ #include "iomfb_v14_7.h" #include "iomfb_v14_7_backlight.h" #include "iomfb_v14_7_board.h" +#include "iomfb_v14_7_plane.h" #include "iomfb_v14_7_link.h" #include "iomfb_v14_7_swap.h" #include "av.h" @@ -130,12 +131,40 @@ static const struct dcp_v14_board dcp_v14_board_j615 = { .name = "J615", .debugfs = "dcp-j615", .dcp_compatible = "apple,t8122-dcp", - .machine = "apple,j615", + .panel = "apple,panel-j615", .firmware_uuid = DCP_V14_J613_FIRMWARE_UUID, .handoff = "apple,t8122-handoff", .panel_width = 2880, .panel_height = 1864, .promotion = false, + .panel_nits = true, + .ctm_set = A(421), + .ctm_get = A(420), +}; + +/* + * J504 (MacBook Pro 14", M3): the J613 DCP image on the same T8122 DCP (the + * J504 ADT names it), driving the 14" mini-LED panel of the J514S: 3024x1964 + * with 74 notch rows above the 3024x1890 boot framebuffer, at 60 or 120 Hz. + * The colour matrix methods are this image's, and so is the panel level + * block the J613 qualified (brightness in nits, 500 at most here). Its swaps + * keep zero timestamps as on the Airs. Every panel timing and the + * display clock are logged for the first boots. Selected by the T8122 DCP + * and the panel node the board device tree puts under it + * (apple,panel-j504), not by the machine. + */ +static const struct dcp_v14_board dcp_v14_board_j504 = { + .name = "J504", + .debugfs = "dcp-j504", + .dcp_compatible = "apple,t8122-dcp", + .panel = "apple,panel-j504", + .firmware_uuid = DCP_V14_J613_FIRMWARE_UUID, + .handoff = "apple,t8122-handoff", + .panel_width = 3024, + .panel_height = 1964, + .promotion = true, + .log_bringup = true, + .panel_nits = true, .ctm_set = A(421), .ctm_get = A(420), }; @@ -193,6 +222,7 @@ static const struct dcp_v14_board *const dcp_v14_boards[] = { &dcp_v14_board_t6030, &dcp_v14_board_j613, &dcp_v14_board_j615, + &dcp_v14_board_j504, &dcp_v14_board_j516c, &dcp_v14_board_j514c, }; @@ -1640,6 +1670,7 @@ static int dcp_v14_cpu_running(struct device *dev, const char *name) */ const struct dcp_v14_board *dcp_v14_board_select(dcp_v14_compat_fn dcp_is, dcp_v14_compat_fn machine_is, + dcp_v14_compat_fn panel_is, const void *ctx, bool *dcp_known) { const struct dcp_v14_board *board; @@ -1653,6 +1684,8 @@ const struct dcp_v14_board *dcp_v14_board_select(dcp_v14_compat_fn dcp_is, *dcp_known = true; if (board->machine && !machine_is(ctx, board->machine)) continue; + if (board->panel && !panel_is(ctx, board->panel)) + continue; return board; } return NULL; @@ -1673,13 +1706,22 @@ static bool dcp_v14_machine_is(const void *np, const char *compat) return of_machine_is_compatible(compat); } +/* The panel the board device tree puts under the DCP node. */ +static bool dcp_v14_panel_is(const void *np, const char *compat) +{ + struct device_node *panel __free(device_node) = + of_get_child_by_name(np, "panel"); + + return panel && of_device_is_compatible(panel, compat); +} + const struct dcp_v14_board *iomfb_v14_7_board(struct device *dev) { const struct dcp_v14_board *board; bool dcp_known; - board = dcp_v14_board_select(dcp_v14_node_is, dcp_v14_machine_is, dev->of_node, - &dcp_known); + board = dcp_v14_board_select(dcp_v14_node_is, dcp_v14_machine_is, dcp_v14_panel_is, + dev->of_node, &dcp_known); if (board) return board; if (dcp_known) { @@ -1689,11 +1731,17 @@ const struct dcp_v14_board *iomfb_v14_7_board(struct device *dev) return NULL; } +/* + * A record selected by its panel node was matched to that panel, so its own + * panel_nits decides; the records still selected by the machine keep their + * machine list. + */ static bool dcp_v14_panel_nits_admit(const struct dcp_v14_board *board, dcp_v14_compat_fn machine_is, const void *ctx) { return board && board->panel_nits && - (machine_is(ctx, "apple,j514s") || machine_is(ctx, "apple,j516s") || + (board->panel || + machine_is(ctx, "apple,j514s") || machine_is(ctx, "apple,j516s") || machine_is(ctx, "apple,j516c") || machine_is(ctx, "apple,j613")); } @@ -3085,12 +3133,7 @@ int iomfb_v14_7_atomic_check(struct apple_dcp *dcp, struct drm_crtc *crtc, if (fb->modifier != DRM_FORMAT_MOD_LINEAR || fb->offsets[0] || fb->pitches[0] < width * 4 || (fb->pitches[0] & 63)) return -EINVAL; - /* An external pipe may show the top-left of a larger framebuffer. */ - if (p->src_x || p->src_y || p->crtc_x || p->crtc_y || - p->src_w != width << 16 || p->src_h != height << 16 || - p->crtc_w != width || p->crtc_h != height || - (dcp->external ? fb->width < width || fb->height < height : - fb->width != width || fb->height != height)) + if (!dcp_v14_plane_fits_mode(p, width, height, dcp->external)) return -EINVAL; obj = drm_fb_dma_get_gem_obj(fb, 0); if (!obj || !obj->dma_addr || (u64)fb->pitches[0] * height > obj->base.size) @@ -3200,13 +3243,13 @@ bool iomfb_v14_7_external_showing(struct apple_dcp *dcp, const struct drm_display_mode *drm_mode) { struct apple_dcp_v14 *v14 = dcp->v14; - struct dcp_display_mode mode = {}; + struct dcp_display_mode *mode __free(kfree) = kzalloc_obj(*mode); bool live; - if (!dcp->external_native || !v14 || !lookup_mode(dcp, drm_mode, &mode)) + if (!mode || !dcp->external_native || !v14 || !lookup_mode(dcp, drm_mode, mode)) return false; mutex_lock(&v14->lock); - live = dcp_v14_external_described(v14) && dcp_v14_external_mode_live(v14, &mode); + live = dcp_v14_external_described(v14) && dcp_v14_external_mode_live(v14, mode); mutex_unlock(&v14->lock); return live; } @@ -3235,10 +3278,12 @@ static void dcp_v14_audio_on(struct apple_dcp *dcp) static int dcp_v14_external_modeset(struct apple_dcp *dcp, struct drm_crtc_state *crtc_state) { struct apple_dcp_v14 *v14 = dcp->v14; - struct dcp_display_mode mode = {}; + struct dcp_display_mode *mode __free(kfree) = kzalloc_obj(*mode); bool audio_off = false; int ret = 0; + if (!mode) + return -ENOMEM; if (!v14 || READ_ONCE(v14->failed) || !v14->opened) return -EIO; /* @@ -3254,7 +3299,7 @@ static int dcp_v14_external_modeset(struct apple_dcp *dcp, struct drm_crtc_state if (ret) goto out; /* Only after the wait: a new description replaces the catalog. */ - if (!lookup_mode(dcp, &crtc_state->mode, &mode)) { + if (!lookup_mode(dcp, &crtc_state->mode, mode)) { mutex_unlock(&v14->lock); ret = -EINVAL; goto out; @@ -3264,10 +3309,11 @@ static int dcp_v14_external_modeset(struct apple_dcp *dcp, struct drm_crtc_state * it again only restarts its timings under the display. A retry or a * replayed CRTC lands here when the display came back as it was. */ - if (dcp_v14_external_mode_live(v14, &mode)) { + if (dcp_v14_external_mode_live(v14, mode)) { mutex_unlock(&v14->lock); dev_info(dcp->dev, "display mode " DRM_MODE_FMT " (timing %u, color %u) already active and showing\n", - DRM_MODE_ARG(&crtc_state->mode), mode.timing_mode_id, mode.color_mode_id); + DRM_MODE_ARG(&crtc_state->mode), + mode->timing_mode_id, mode->color_mode_id); atomic_set(&dcp->external_retries, 0); dcp_mode_set_valid(&dcp->mode_state, true); if (dcp->avep) @@ -3279,7 +3325,7 @@ static int dcp_v14_external_modeset(struct apple_dcp *dcp, struct drm_crtc_state if (READ_ONCE(v14->failed)) ret = -EIO; if (!ret) - ret = dcp_v14_set_mode(v14, mode.color_mode_id, mode.timing_mode_id); + ret = dcp_v14_set_mode(v14, mode->color_mode_id, mode->timing_mode_id); if (!ret) ret = dcp_v14_set_power(v14, true); /* @@ -3292,19 +3338,19 @@ static int dcp_v14_external_modeset(struct apple_dcp *dcp, struct drm_crtc_state * before the first swap. */ if (!ret) - ret = dcp_v14_set_mode(v14, mode.color_mode_id, mode.timing_mode_id); + ret = dcp_v14_set_mode(v14, mode->color_mode_id, mode->timing_mode_id); if (!ret) { - v14->panel_width = mode.mode.hdisplay; - v14->panel_height = mode.mode.vdisplay; - v14->mode_timing = mode.timing_mode_id; - v14->mode_color = mode.color_mode_id; + v14->panel_width = mode->mode.hdisplay; + v14->panel_height = mode->mode.vdisplay; + v14->mode_timing = mode->timing_mode_id; + v14->mode_color = mode->color_mode_id; v14->mode_swaps = 0; v14->mode_live = true; } mutex_unlock(&v14->lock); out: dev_info(dcp->dev, "display mode " DRM_MODE_FMT " (timing %u, color %u): %d\n", - DRM_MODE_ARG(&crtc_state->mode), mode.timing_mode_id, mode.color_mode_id, ret); + DRM_MODE_ARG(&crtc_state->mode), mode->timing_mode_id, mode->color_mode_id, ret); if (ret) { /* * A mode that is gone, or a description that never settled: @@ -3344,12 +3390,15 @@ void iomfb_v14_7_flush(struct apple_dcp *dcp, struct drm_crtc *crtc, struct drm_plane_state *p = drm_atomic_get_new_plane_state(state, crtc->primary); struct drm_crtc_state *cs = drm_atomic_get_new_crtc_state(state, crtc); struct drm_framebuffer *fb; + u32 width = 0, height = 0; if (!p) p = crtc->primary->state; if (!cs) cs = crtc->state; fb = p && p->visible ? p->fb : NULL; + if (fb) + dcp_v14_plane_scanout_size(p, dcp->external, &width, &height); /* * No swaps while an external display is off, unset, unplugged, or * being described again. @@ -3364,10 +3413,7 @@ void iomfb_v14_7_flush(struct apple_dcp *dcp, struct drm_crtc *crtc, if (!dcp->external) dcp_v14_configure_backlight(dcp); dcp->swap_start = ktime_get(); - if (dcp->v14 && dcp_v14_present(dcp->v14, fb, - fb ? (dcp->external ? p->src_w >> 16 : fb->width) : 0, - fb ? (dcp->external ? p->src_h >> 16 : fb->height) : 0, - dcp->notch_height, cs)) { + if (dcp->v14 && dcp_v14_present(dcp->v14, fb, width, height, dcp->notch_height, cs)) { dcp_drm_crtc_page_flip(dcp, ktime_get()); /* * The swap completed: the framebuffers this commit and earlier diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c b/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c index a84e45338793e5..3eea1558792fec 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c @@ -122,41 +122,71 @@ static bool v14_bl_ctx_machine_is(const void *ctx, const char *compat) return !strcmp(((const char *const *)ctx)[1], compat); } -/* Only admitted T6030, J516C and J613 internal panels carry levels. */ +/* The DCP's panel node compatible; NULL: no panel node. */ +static bool v14_bl_ctx_panel_is(const void *ctx, const char *compat) +{ + const char *panel = ((const char *const *)ctx)[2]; + + return panel && !strcmp(panel, compat); +} + +/* Only admitted T6030, J516C and J613 internal panels and the J504 panel carry levels. */ static void v14_bl_boards(struct kunit *test) { - static const char *const t6030_j516s[] = { "apple,t6030-dcp", "apple,j516s" }; - static const char *const t6030_j514s[] = { "apple,t6030-dcp", "apple,j514s" }; - static const char *const j613[] = { "apple,t8122-dcp", "apple,j613" }; - static const char *const j615[] = { "apple,t8122-dcp", "apple,j615" }; - static const char *const j516c[] = { "apple,t6031-dcp", "apple,j516c" }; - static const char *const other_t6030[] = { "apple,t6030-dcp", "apple,other" }; + static const char *const t6030_j516s[] = { "apple,t6030-dcp", "apple,j516s", NULL }; + static const char *const t6030_j514s[] = { "apple,t6030-dcp", "apple,j514s", NULL }; + static const char *const j613[] = { "apple,t8122-dcp", "apple,j613", NULL }; + static const char *const j615[] = { "apple,t8122-dcp", "apple,j615", "apple,panel-j615" }; + static const char *const j615_no_panel[] = { "apple,t8122-dcp", "apple,j615", NULL }; + static const char *const j504[] = { "apple,t8122-dcp", "apple,j504", "apple,panel-j504" }; + static const char *const j504_no_panel[] = { "apple,t8122-dcp", "apple,j504", NULL }; + static const char *const j516c[] = { "apple,t6031-dcp", "apple,j516c", NULL }; + static const char *const other_t6030[] = { "apple,t6030-dcp", "apple,other", NULL }; const struct dcp_v14_board *board; bool known; - board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, t6030_j516s, &known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + t6030_j516s, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_TRUE(test, board->panel_nits); KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, t6030_j516s)); - board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, t6030_j514s, &known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + t6030_j514s, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_TRUE(test, board->panel_nits); KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, t6030_j514s)); - board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, other_t6030, &known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + other_t6030, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_FALSE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, other_t6030)); - board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, j613, &known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + j613, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_TRUE(test, board->panel_nits); KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j613)); - KUNIT_EXPECT_FALSE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j615)); - board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, j615, &known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + j615, &known); + KUNIT_ASSERT_PTR_EQ(test, board, &dcp_v14_board_j615); + KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j615)); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + j615_no_panel, &known); + KUNIT_EXPECT_NULL(test, board); + KUNIT_EXPECT_TRUE(test, known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + j504, &known); KUNIT_ASSERT_NOT_NULL(test, board); - KUNIT_EXPECT_FALSE(test, board->panel_nits); - board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, j516c, &known); + KUNIT_EXPECT_TRUE(test, board->panel_nits); + KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j504)); + /* The J504 record follows its panel node: without it the machine gets none. */ + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + j504_no_panel, &known); + KUNIT_EXPECT_NULL(test, board); + KUNIT_EXPECT_TRUE(test, known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + j516c, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_TRUE(test, board->panel_nits); KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j516c)); @@ -348,13 +378,13 @@ static bool v14_bl_queued(struct apple_dcp_v14 *v14) } /* - * The production paths on J615 and J514C: no policy is consulted, no + * The production paths on J514C: no policy is consulted, no * level is encoded, the work does nothing, sleep leaves the gate alone. */ static void v14_bl_other_boards_untouched(struct kunit *test) { const struct dcp_v14_board *boards[] = { - &dcp_v14_board_j615, &dcp_v14_board_j514c, + &dcp_v14_board_j514c, }; struct dcp_backlight_present present; unsigned int i; @@ -472,6 +502,11 @@ static void v14_bl_t6030_swap_levels(struct kunit *test) v14_bl_swap_levels(test, &dcp_v14_board_t6030); } +static void v14_bl_j615_swap_levels(struct kunit *test) +{ + v14_bl_swap_levels(test, &dcp_v14_board_j615); +} + static void v14_bl_j613_swap_levels(struct kunit *test) { v14_bl_swap_levels(test, &dcp_v14_board_j613); @@ -586,6 +621,7 @@ static struct kunit_case v14_backlight_cases[] = { KUNIT_CASE(v14_bl_external_untouched), KUNIT_CASE(v14_bl_t6030_swap_levels), KUNIT_CASE(v14_bl_j613_swap_levels), + KUNIT_CASE(v14_bl_j615_swap_levels), KUNIT_CASE(v14_bl_t6030_gate), KUNIT_CASE(v14_bl_t6030_work), {} diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_board.h b/drivers/gpu/drm/apple/iomfb_v14_7_board.h index 6de1ae90041221..8394a99f3d2f50 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7_board.h +++ b/drivers/gpu/drm/apple/iomfb_v14_7_board.h @@ -19,6 +19,8 @@ struct dcp_v14_board { const char *dcp_compatible; /* The machine compatible; NULL for any machine with this DCP. */ const char *machine; + /* The compatible of the DCP's "panel" child; NULL for any panel. */ + const char *panel; /* The firmware image whose layouts were tested on this board. */ const char *firmware_uuid; /* Set to <1> by the boot loader on the DCP, display and PIODMA nodes. */ @@ -50,16 +52,21 @@ struct dcp_v14_board { bool panel_nits; }; -/* Whether the DCP node or the machine (as @ctx gives them) has @compat. */ +/* + * Whether the DCP node, the machine or the DCP's panel node (as @ctx gives + * them) has @compat. + */ typedef bool (*dcp_v14_compat_fn)(const void *ctx, const char *compat); /* * The board record of a DCP. NULL if there is none: *@dcp_known then says * whether a record names the DCP's compatible (but no record is for this - * machine) or none does (not an internal 14.x DCP). + * machine and panel) or none does (not an internal 14.x DCP). A record with + * a machine is for that machine, one with a panel for a DCP with that panel. */ const struct dcp_v14_board *dcp_v14_board_select(dcp_v14_compat_fn dcp_is, dcp_v14_compat_fn machine_is, + dcp_v14_compat_fn panel_is, const void *ctx, bool *dcp_known); /* diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_plane.h b/drivers/gpu/drm/apple/iomfb_v14_7_plane.h new file mode 100644 index 00000000000000..d330d38ca6d015 --- /dev/null +++ b/drivers/gpu/drm/apple/iomfb_v14_7_plane.h @@ -0,0 +1,65 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ + +#ifndef __APPLE_IOMFB_V14_7_PLANE_H__ +#define __APPLE_IOMFB_V14_7_PLANE_H__ + +#include + +#include +#include +#include + +/* + * The 14.7 presenter scans out one unscaled image of the mode's size from + * the top-left corner of the framebuffer. Judge a plane by its clipped + * rectangles, which drm_atomic_helper_check_plane_state() has set by the + * time the CRTC is checked: a plane that reaches past the right or bottom + * edge of the mode is clipped there, and what remains is exactly what the + * presenter scans out. Compositors put up such planes, for example when they + * centre a mirrored output and round its borders up on both sides. + * + * A plane that starts left of or above the mode, or that is scaled, starts + * its clipped source inside the framebuffer or differs in size from the + * mode, which the presenter cannot show. Clipping rounds the source toward + * 1:1, so a plane that reaches past the edge with a source less than a pixel + * off unscaled may clip to exactly the mode's size; it is then taken and + * shown unscaled. + * + * An external pipe may show the top-left of a larger framebuffer; the panel + * takes only a framebuffer of its mode's size. + */ +static inline bool dcp_v14_plane_fits_mode(const struct drm_plane_state *p, + u32 width, u32 height, bool external) +{ + const struct drm_framebuffer *fb = p->fb; + + if (p->src.x1 || p->src.y1 || p->dst.x1 || p->dst.y1) + return false; + if (drm_rect_width(&p->src) != (int)(width << 16) || + drm_rect_height(&p->src) != (int)(height << 16) || + drm_rect_width(&p->dst) != (int)width || + drm_rect_height(&p->dst) != (int)height) + return false; + if (external) + return fb->width >= width && fb->height >= height; + return fb->width == width && fb->height == height; +} + +/* + * The size of the image the presenter scans out for a visible plane that + * dcp_v14_plane_fits_mode() took: its clipped source on an external pipe, + * where the framebuffer may be larger, and the framebuffer on the panel. + */ +static inline void dcp_v14_plane_scanout_size(const struct drm_plane_state *p, + bool external, u32 *width, u32 *height) +{ + if (external) { + *width = drm_rect_width(&p->src) >> 16; + *height = drm_rect_height(&p->src) >> 16; + } else { + *width = p->fb->width; + *height = p->fb->height; + } +} + +#endif /* __APPLE_IOMFB_V14_7_PLANE_H__ */ diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_tpl.c b/drivers/gpu/drm/apple/iomfb_v14_7_tpl.c index 6ad66e7c84690a..88e7909ec826d0 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7_tpl.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7_tpl.c @@ -7,11 +7,17 @@ * iomfb_v14_7.c, the native DCPLink backend for T6030 panels. */ -/* Include all per-version headers before defining DCP_FW ourself. */ +/* + * Include all per-version headers before defining DCP_FW ourself. + * dcp-internal.h pulls in the remaining ones; included first from inside + * the template, they would rely on #pragma push_macro to keep our DCP_FW, + * which sparse does not implement. + */ #include "iomfb_v12_3.h" #include "iomfb_v13_3.h" #include "iomfb_v14_7_tpl.h" #include "iomfb_h17p.h" +#include "dcp-internal.h" #include "version_utils.h" static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { @@ -118,7 +124,7 @@ void DCP_FW_NAME(iomfb_start)(struct apple_dcp *dcp) { dcp->cb_handlers = cb_handlers; - dcp_start_signal(dcp, false, dcp_started, NULL); + iomfb_template_start(dcp); } #undef DCP_FW_VER diff --git a/drivers/gpu/drm/apple/iomfb_v26_6.c b/drivers/gpu/drm/apple/iomfb_v26_6.c index 1f456dc17776a6..2f0b1ffa1ae085 100644 --- a/drivers/gpu/drm/apple/iomfb_v26_6.c +++ b/drivers/gpu/drm/apple/iomfb_v26_6.c @@ -554,6 +554,24 @@ static int dcp_v26_callback(void *cookie, u32 tag, } if (tag == D(576) && SHAPE(4, 0)) return 0; + /* + * Callbacks the firmware sends when the display is powered down (A473, observed in + * macOS's panel-off and in Linux's sleep calls), answered as the H17P and M4 drivers + * answer them: a no-op (D2), swap_complete_intent_gated (D592, a no-op), + * powerUpDART (D572, success) and get_calendar_time_ms (D209). + */ + if ((tag == D(2) && SHAPE(0, 0)) || (tag == D(592) && SHAPE(20, 0))) + return 0; + if (tag == D(572) && SHAPE(4, 4)) { + if (v26->dcp) + dcp_s2r_dart_power(v26->dcp, get_unaligned_le32(in)); + memset(out, 0, 4); + return 0; + } + if (tag == D(209) && SHAPE(0, 8)) { + put_unaligned_le64(ktime_get_real_ns() / NSEC_PER_MSEC, out); + return 0; + } if (tag == D(300) && SHAPE(16, 0)) { dcp_v26_publish(v26, in); return 0; @@ -1740,9 +1758,11 @@ int iomfb_v26_6_atomic_check(struct apple_dcp *dcp, struct drm_crtc *crtc, int iomfb_v26_6_modeset(struct apple_dcp *dcp, struct drm_crtc_state *crtc_state) { - struct dcp_display_mode mode; + struct dcp_display_mode *mode __free(kfree) = kzalloc_obj(*mode); - if (!lookup_mode(dcp, &crtc_state->mode, &mode)) + if (!mode) + return -ENOMEM; + if (!lookup_mode(dcp, &crtc_state->mode, mode)) return -EINVAL; /* * The firmware keeps the timing it booted with, which every mode @@ -1751,8 +1771,8 @@ int iomfb_v26_6_modeset(struct apple_dcp *dcp, struct drm_crtc_state *crtc_state * (locked 60 Hz). */ if (dcp->v26) { - WRITE_ONCE(dcp->v26->timed, mode.vrr); - WRITE_ONCE(dcp->v26->refresh, drm_mode_vrefresh(&mode.mode)); + WRITE_ONCE(dcp->v26->timed, mode->vrr); + WRITE_ONCE(dcp->v26->refresh, drm_mode_vrefresh(&mode->mode)); } dcp_mode_set_valid(&dcp->mode_state, true); return 0; @@ -1772,7 +1792,8 @@ void iomfb_v26_6_flush(struct apple_dcp *dcp, struct drm_crtc *crtc, p = crtc->primary->state; fb = p && p->visible ? p->fb : NULL; dcp->swap_start = ktime_get(); - if (!dcp->v26 || !dcp_v26_present(dcp->v26, fb, dcp->notch_height, &presented, cs)) { + if (READ_ONCE(dcp->sleep_cold_stopped) || !dcp->v26 || + !dcp_v26_present(dcp->v26, fb, dcp->notch_height, &presented, cs)) { dcp_v26_cancel_event(dcp); return; } @@ -1926,3 +1947,81 @@ void iomfb_v26_6_poweroff(struct apple_dcp *dcp) dcp_v26_present(dcp->v26, NULL, 0, NULL, NULL); } } + +/* + * Calls the 26.6 firmware receives from macOS before a system sleep, in the order and + * with the inputs observed on its mailbox and RPC memory. + * The panel-off group: A414 (8 zero bytes; reply 1), A478 (reply 1) twice, A476(1), + * A478, A412 (reply 1), A473 (16 zero bytes; reply 8 zero bytes), A500 (0, 0). + * The sleep-entry group: A478, A476(1), A473 (bytes 8, 11 and 12 set to 1), A115 + * (reply 0), A500 (0, 1). @groups: 1 sends the sleep-entry group only, 2 sends the + * panel-off group first, then the sleep-entry group. Every reply is compared with + * the expected firmware reply; a mismatch returns -EPROTO. + */ +static int dcp_v26_sleep_call(struct apple_dcp_v26 *v26, u32 tag, const void *in, u32 in_size, + const void *want, u32 want_size, bool *same) +{ + u8 out[8] = {}; + int ret; + + ret = dcp_v26_call(v26, tag, in, in_size, want_size ? out : NULL, want_size, 0); + if (!ret && want_size && memcmp(out, want, want_size)) { + dev_warn(v26->dev, "sleep call %#x reply %*ph, expected %*ph\n", tag, want_size, + out, want_size, want); + *same = false; + } + return ret; +} + +int dcp_v26_sleep_calls(struct apple_dcp *dcp, int groups) +{ + static const u8 zero16[16], one[4] = { 1 }, one8[8] = { 1 }; + static const u8 a473_entry[16] = { [8] = 1, [11] = 1, [12] = 1 }; + static const u8 a500_off[4] = { 0, 0 }, a500_entry[4] = { 0, 1 }; + struct apple_dcp_v26 *v26 = dcp->v26; + bool same = true; + int ret = 0; + + if (!v26 || !v26->started) + return -ENODEV; + mutex_lock(&v26->lock); + if (groups >= 2) { + ret = dcp_v26_sleep_call(v26, A(414), zero16, 8, one8, 8, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(478), NULL, 0, one, 4, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(478), NULL, 0, one, 4, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(476), one, 4, NULL, 0, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(478), NULL, 0, one, 4, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(412), NULL, 0, one, 4, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(473), zero16, 16, zero16, 8, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(500), a500_off, 4, NULL, 0, &same); + dev_dbg(v26->dev, "panel-off calls before sleep: %d\n", ret); + } + if (!ret) + ret = dcp_v26_sleep_call(v26, A(478), NULL, 0, one, 4, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(476), one, 4, NULL, 0, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(473), a473_entry, 16, zero16, 8, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(115), NULL, 0, zero16, 4, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(500), a500_entry, 4, NULL, 0, &same); + mutex_unlock(&v26->lock); + if (!ret && !same) + ret = -EPROTO; + dev_dbg(v26->dev, "sleep calls (groups %d): %d, replies %s expected\n", groups, ret, + same ? "matched" : "differed from"); + return ret; +} + +struct apple_rtkit *dcp_v26_rtkit(struct apple_dcp *dcp) +{ + return dcp->v26 ? dcp->v26->rtk : NULL; +} diff --git a/drivers/gpu/drm/apple/iomfb_v26_6.h b/drivers/gpu/drm/apple/iomfb_v26_6.h index 2831ee2f793458..1b856a09eb21f9 100644 --- a/drivers/gpu/drm/apple/iomfb_v26_6.h +++ b/drivers/gpu/drm/apple/iomfb_v26_6.h @@ -11,6 +11,7 @@ #include struct apple_dcp; +struct apple_rtkit; struct apple_dcp_v26; struct dcp_v26_board; struct device; @@ -51,5 +52,8 @@ void iomfb_v26_6_flush(struct apple_dcp *dcp, struct drm_crtc *crtc, struct drm_atomic_commit *state); void iomfb_v26_6_poweron(struct apple_dcp *dcp); void iomfb_v26_6_poweroff(struct apple_dcp *dcp); +/* Pre-sleep shutdown calls and the session's RTKit for firmware-driven sleep. */ +int dcp_v26_sleep_calls(struct apple_dcp *dcp, int groups); +struct apple_rtkit *dcp_v26_rtkit(struct apple_dcp *dcp); #endif /* __APPLE_IOMFB_V26_6_H__ */ diff --git a/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c b/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c index c2d0bee01e05f9..e3585174b0fd11 100644 --- a/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c +++ b/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c @@ -9,12 +9,18 @@ * the H17-generation 26.x firmware of iomfb_h17p.c. */ -/* Include all per-version headers before defining DCP_FW ourself. */ +/* + * Include all per-version headers before defining DCP_FW ourself. + * dcp-internal.h pulls in the remaining ones; included first from inside + * the template, they would rely on #pragma push_macro to keep our DCP_FW, + * which sparse does not implement. + */ #include "iomfb_v12_3.h" #include "iomfb_v13_3.h" #include "iomfb_v14_7_tpl.h" #include "iomfb_v26_6_desktop.h" #include "iomfb_h17p.h" +#include "dcp-internal.h" #include "version_utils.h" static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { @@ -34,6 +40,7 @@ static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { IOMFB_METHOD("A414", dcpep_pipe_cfg_414), IOMFB_METHOD("A423", iomfbep_set_matrix), IOMFB_METHOD("A427", iomfbep_get_color_remap_mode), + IOMFB_METHOD("A428", iomfbep_set_brightness_correction), IOMFB_METHOD("A442", dcpep_set_parameter_dcp), IOMFB_METHOD("A446", dcpep_create_default_fb), IOMFB_METHOD("A450", dcpep_enable_disable_video_power_savings), @@ -44,6 +51,7 @@ static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { IOMFB_METHOD("A469", iomfbep_abort_swaps_dcp), IOMFB_METHOD("A473", dcpep_set_power_state), IOMFB_METHOD("A474", dcpep_pipe_query_474), + IOMFB_METHOD("A500", dcpep_unnamed_500), /* A364 get_mode_info and A420/A421 gamma: see iomfb_template.c */ }; @@ -52,6 +60,22 @@ static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { #include "iomfb_template.c" +/* + * D572: 0 when the firmware is done with the display, 1 when it wants it back. Only a + * sleep path waiting for it (s2r_active) acts on it; the firmware takes a zero status. + */ +static bool trampoline_dart_power_v26_6_desktop(struct apple_dcp *dcp, int tag, void *out, + void *in) +{ + const struct dcp_packet_header *header = in - sizeof(*header); + + /* A bool in a 4-byte slot: its upper padding bytes are not cleared. */ + if (header->in_len >= sizeof(u32)) + dcp_s2r_dart_power(dcp, !!*(const u8 *)in); + + return trampoline_zero(dcp, tag, out, in); +} + /* * D114 periodically publishes dictionary-valued statistics: the analytics * event, answered by dcp_dict_passthrough_reply(). @@ -229,14 +253,16 @@ static const iomfb_cb_handler cb_handlers[IOMFB_MAX_CB] = { [565] = trampoline_true, /* set_property_bool */ [567] = trampoline_true, /* set_property_str */ /* a zero status for both its start and stop events */ - [572] = trampoline_zero, + [572] = trampoline_dart_power_v26_6_desktop, [575] = trampoline_hotplug, [576] = trampoline_nop, [581] = trampoline_nop, [582] = trampoline_true, /* create_default_fb_surface */ + [583] = trampoline_nop, /* clear_default_surface */ [588] = trampoline_nop, /* resize_default_fb_surface_gated */ [590] = trampoline_swap_complete, [592] = trampoline_swap_complete_intent_gated, + [597] = trampoline_zero, /* sleep test: (0, 4), purpose unknown */ [593] = trampoline_abort_swap_ap_gated, /* a four-byte padded notification; only its first byte is read */ [594] = trampoline_enable_backlight_message_ap_gated, @@ -323,9 +349,11 @@ static const struct dcp_cb_min_v26_6_desktop cb_min[IOMFB_MAX_CB] = { [576] = CB_MIN(0, 0), [581] = CB_MIN(0, 0), [582] = CB_MIN(0, sizeof(u8)), + [583] = CB_MIN(0, 0), [588] = CB_MIN(0, 0), [590] = CB_MIN(sizeof(struct DCP_FW_NAME(dc_swap_complete_resp)), 0), [592] = CB_MIN(sizeof(dcp_swap_intent_t), 0), + [597] = CB_MIN(0, sizeof(u32)), [593] = CB_MIN(sizeof(u32), 0), [594] = CB_MIN(sizeof(u8), 0), [595] = CB_MIN(0, 0), @@ -347,7 +375,7 @@ void DCP_FW_NAME(iomfb_start)(struct apple_dcp *dcp) { dcp->cb_handlers = cb_handlers; - dcp_start_signal(dcp, false, dcp_started, NULL); + iomfb_template_start(dcp); } #undef DCP_FW_VER diff --git a/drivers/gpu/drm/apple/iomfb_v27.c b/drivers/gpu/drm/apple/iomfb_v27.c index a7d7d6b93f341d..1f2e8121127c77 100644 --- a/drivers/gpu/drm/apple/iomfb_v27.c +++ b/drivers/gpu/drm/apple/iomfb_v27.c @@ -164,6 +164,22 @@ static const struct dcp_method_entry dcp_methods_27_0[dcpep_num_methods] = { * the IOMFB calls around it; 27.2 moved both to A550/A551. */ IOMFB_METHOD("A500", dcpep_unnamed_500), + IOMFB_METHOD("A115", dcpep_v27_sleep_a115), + IOMFB_METHOD("A442", dcpep_v27_wake_a442), + IOMFB_METHOD("A360", dcpep_v27_peer_a360), + IOMFB_METHOD("A361", dcpep_v27_peer_a361), + IOMFB_METHOD("A362", dcpep_v27_peer_a362), + IOMFB_METHOD("A364", dcpep_v27_peer_a364), + IOMFB_METHOD("A365", dcpep_v27_peer_a365), + IOMFB_METHOD("A366", dcpep_v27_peer_a366), + IOMFB_METHOD("A367", dcpep_v27_peer_a367), + IOMFB_METHOD("A368", dcpep_v27_peer_a368), + IOMFB_METHOD("A369", dcpep_v27_peer_a369), + IOMFB_METHOD("A370", dcpep_v27_peer_a370), + IOMFB_METHOD("A371", dcpep_v27_peer_a371), + IOMFB_METHOD("A372", dcpep_v27_peer_a372), + IOMFB_METHOD("A373", dcpep_v27_peer_a373), + IOMFB_METHOD("A449", dcpep_v27_peer_a449), }; /* @@ -222,6 +238,22 @@ static const struct dcp_method_entry dcp_methods_27_2[dcpep_num_methods] = { * dispatch where 26A428's compares 'A500' (0x1df68c vs 0x1de0dc, same code). */ IOMFB_METHOD("A550", dcpep_unnamed_500), + IOMFB_METHOD("A115", dcpep_v27_sleep_a115), + IOMFB_METHOD("A492", dcpep_v27_wake_a442), + IOMFB_METHOD("A360", dcpep_v27_peer_a360), + IOMFB_METHOD("A361", dcpep_v27_peer_a361), + IOMFB_METHOD("A362", dcpep_v27_peer_a362), + IOMFB_METHOD("A364", dcpep_v27_peer_a364), + IOMFB_METHOD("A365", dcpep_v27_peer_a365), + IOMFB_METHOD("A366", dcpep_v27_peer_a366), + IOMFB_METHOD("A367", dcpep_v27_peer_a367), + IOMFB_METHOD("A368", dcpep_v27_peer_a368), + IOMFB_METHOD("A369", dcpep_v27_peer_a369), + IOMFB_METHOD("A370", dcpep_v27_peer_a370), + IOMFB_METHOD("A371", dcpep_v27_peer_a371), + IOMFB_METHOD("A372", dcpep_v27_peer_a372), + IOMFB_METHOD("A373", dcpep_v27_peer_a373), + IOMFB_METHOD("A499", dcpep_v27_peer_a449), }; /* @@ -269,6 +301,76 @@ const struct dcp_method_entry *iomfb_v27_methods(const char *compat) return NULL; } +/* + * Translate @tag, a 27.0 ID named directly by sleep or paired-mode callers, + * into the build of @methods (4 bytes in @out). On 27.0 (including the J714s + * copy) the tag is sent unchanged. On a renumbered build every ID must come + * from @methods; a missing entry returns -EOPNOTSUPP instead of sending an + * unknown tag that would panic the firmware. + */ +int iomfb_v27_tag(const struct dcp_method_entry *methods, const char *tag, char *out) +{ + unsigned int i; + char in[4]; + + if (!methods) + return -EOPNOTSUPP; + memcpy(in, tag, 4); + if (!iomfb_v27_methods_renumbered(methods)) { + memcpy(out, in, 4); + return 0; + } + for (i = 0; i < dcpep_num_methods; i++) { + if (dcp_methods_27_0[i].tag[0] && !memcmp(dcp_methods_27_0[i].tag, in, 4)) { + if (!methods[i].tag[0]) + return -EOPNOTSUPP; + memcpy(out, methods[i].tag, 4); + return 0; + } + } + return -EOPNOTSUPP; +} + +/* Whether @methods is a build's table whose AP method IDs differ from 27.0's. */ +bool iomfb_v27_methods_renumbered(const struct dcp_method_entry *methods) +{ + unsigned int i; + + if (!methods || methods == dcp_methods_27_0) + return false; + for (i = 0; i < dcpep_num_methods; i++) { + if (memcmp(methods[i].tag, dcp_methods_27_0[i].tag, 4) && + !(i == dcpep_swap_submit && !memcmp(methods[i].tag, "A407", 4))) + return true; + } + return false; +} + +static const enum dcpep_method iomfb_v27_sleep_methods[] = { + dcpep_is_main_display, + dcpep_pipe_cfg_414, + dcpep_set_power_state, + dcpep_pipe_set_476, + dcpep_pipe_query_478, + dcpep_unnamed_500, + dcpep_v27_sleep_a115, + dcpep_v27_wake_a442, +}; + +/* Whether @methods names an ID for every call the firmware 27 display sleep sends. */ +bool iomfb_v27_sleep_methods_complete(const struct dcp_method_entry *methods) +{ + unsigned int i; + + if (!methods) + return false; + for (i = 0; i < ARRAY_SIZE(iomfb_v27_sleep_methods); i++) { + if (!methods[iomfb_v27_sleep_methods[i]].tag[0]) + return false; + } + return true; +} + /* * The 27.0 table for the J714s, the board the firmware 27 sleep has run on (dcp->v27_j714s): a * copy with the sleep's A500 added. The shared table keeps the methods it had, so every other @@ -309,9 +411,14 @@ const char *iomfb_v27_missing_method(const struct dcp_method_entry *methods, *count = 0; for (i = 0; i < dcpep_num_methods; i++) { - /* Only a firmware sleep sends unnamed_500, and it checks the build's table. */ + /* + * Only sleep and paired-mode paths send unnamed_500 and the + * v27-optional entries; each checks the build's table before + * sending. + */ if (!dcp_methods_27_0[i].tag[0] || methods[i].tag[0] || - i == dcpep_dfb_ready_query || i == dcpep_unnamed_500) + i == dcpep_dfb_ready_query || i == dcpep_unnamed_500 || + i >= dcpep_v27_sleep_a115) continue; if (!first) first = dcp_methods_27_0[i].name; @@ -406,6 +513,9 @@ static bool trampoline_hotplug_h17p(struct apple_dcp *dcp, int tag, if (!(request->tiled_display_null & 1)) memcpy(out, request->tiled_display, sizeof(request->tiled_display)); + /* The V27 wake's mode set waits for the firmware's report of the panel */ + if (request->connected && dcp->v27_j714s) + complete(&dcp->v27_wake_hotplug); return trampoline_hotplug(dcp, tag, out, in); } @@ -817,7 +927,7 @@ bool iomfb_v27_callback_size_valid(unsigned int tag, u32 input, u32 output) void iomfb_start_v27(struct apple_dcp *dcp) { dcp->cb_handlers = cb_handlers; - dcp_start_signal(dcp, false, dcp_started, NULL); + iomfb_template_start(dcp); } #undef DCP_FW_VER diff --git a/drivers/gpu/drm/apple/iomfb_v27_test.c b/drivers/gpu/drm/apple/iomfb_v27_test.c new file mode 100644 index 00000000000000..0c20e9c0d1f891 --- /dev/null +++ b/drivers/gpu/drm/apple/iomfb_v27_test.c @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Copyright 2026 Aurora Silicon */ + +/* + * Firmware 27 is selected by the firmware-compat a DCP reports, on every SoC: + * 27 or later runs the firmware-27 instance when the build has a complete + * method table and is not started otherwise; older firmware is left to the + * older interfaces. These tests cover that rule and the in-tree tables. + */ + +#include +#include +#include + +#include "dcp.h" +#include "iomfb.h" +#include "iomfb_v27.h" + +static enum dcp_v27_admission admission(const char *compat) +{ + const struct dcp_method_entry *methods; + unsigned int num_missing; + const char *missing; + + return dcp_v27_admission(compat, &methods, &missing, &num_missing); +} + +/* Builds with a complete table start, whatever SoC reports them. */ +static void v27_complete_table_admits_test(struct kunit *test) +{ + const struct dcp_method_entry *methods; + unsigned int num_missing; + const char *missing; + + KUNIT_EXPECT_EQ(test, dcp_v27_admission("27.2.0", &methods, &missing, + &num_missing), + DCP_V27_ADMITTED); + KUNIT_EXPECT_PTR_EQ(test, methods, iomfb_v27_methods("27.2.0")); + KUNIT_EXPECT_PTR_EQ(test, missing, NULL); + KUNIT_EXPECT_EQ(test, num_missing, 0U); + KUNIT_EXPECT_EQ(test, admission("27.0.0"), DCP_V27_ADMITTED); +} + +/* 27 or later without a usable table is refused, never handed down. */ +static void v27_unusable_table_refuses_test(struct kunit *test) +{ + const struct dcp_method_entry *methods; + unsigned int num_missing; + const char *missing; + + KUNIT_EXPECT_EQ(test, admission("27.1.0"), DCP_V27_NO_TABLE); + KUNIT_EXPECT_EQ(test, admission("28.0.0"), DCP_V27_NO_TABLE); + KUNIT_EXPECT_EQ(test, dcp_v27_admission("27.3.0", &methods, &missing, + &num_missing), + DCP_V27_INCOMPLETE); + KUNIT_EXPECT_NOT_NULL(test, missing); + KUNIT_EXPECT_GT(test, num_missing, 0U); +} + +/* Older firmware keeps the 26.x, 14.x and 13.x selection. */ +static void v27_older_firmware_not_v27_test(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, admission("26.6.2"), DCP_V27_NOT_V27); + KUNIT_EXPECT_EQ(test, admission("26.5.2"), DCP_V27_NOT_V27); + KUNIT_EXPECT_EQ(test, admission("14.7.0"), DCP_V27_NOT_V27); + KUNIT_EXPECT_EQ(test, admission("13.5.0"), DCP_V27_NOT_V27); + KUNIT_EXPECT_EQ(test, admission("12.3.0"), DCP_V27_NOT_V27); + KUNIT_EXPECT_EQ(test, admission("UNKNOWN"), DCP_V27_NOT_V27); +} + +static struct kunit_case v27_cases[] = { + KUNIT_CASE(v27_complete_table_admits_test), + KUNIT_CASE(v27_unusable_table_refuses_test), + KUNIT_CASE(v27_older_firmware_not_v27_test), + {} +}; + +static struct kunit_suite v27_suite = { + .name = "apple-dcp-v27", + .test_cases = v27_cases, +}; + +kunit_test_suite(v27_suite); + +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/gpu/drm/apple/parser-bounds-test.c b/drivers/gpu/drm/apple/parser-bounds-test.c new file mode 100644 index 00000000000000..2c4db5f99eaa87 --- /dev/null +++ b/drivers/gpu/drm/apple/parser-bounds-test.c @@ -0,0 +1,1416 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the DCP serialized dictionary parsers that the other parser + * suites do not call: display metadata, DPTX capabilities, system log events, + * timing catalogs, panel EDID properties and audio elements. Firmware hands + * these blobs to the driver, so beyond the accepted shapes every parser must + * fail on every truncation of a valid blob instead of reading past its end. + * + * All values are synthetic. + */ + +#include +#include +#include +#include +#include +#include + +#if IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) +#include +#endif + +#include "dcp-peer-v27.h" +#include "parser.h" + +/* Tag: size in bits 0-23, type in 24-28, padding in 29-30, last in 31. */ +#define PB_DICT 1 +#define PB_ARRAY 2 +#define PB_INT64 4 +#define PB_STRING 9 +#define PB_BLOB 10 +#define PB_BOOL 11 +#define PB_CAP 8192 + +struct pb { + struct kunit *test; + u8 *data; + u32 len; +}; + +static struct pb *pb_new(struct kunit *test, bool header) +{ + struct pb *b = kunit_kzalloc(test, sizeof(*b), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, b); + b->data = kunit_kzalloc(test, PB_CAP, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, b->data); + b->test = test; + if (header) { + put_unaligned_le32(0xd3, b->data); + b->len = 4; + } + return b; +} + +static void pb_raw(struct pb *b, const void *bytes, u32 n) +{ + KUNIT_ASSERT_LE(b->test, b->len + n, PB_CAP); + memcpy(b->data + b->len, bytes, n); + b->len += n; +} + +static void pb_word(struct pb *b, u32 word) +{ + b->len = round_up(b->len, 4); + KUNIT_ASSERT_LE(b->test, b->len + 4, PB_CAP); + put_unaligned_le32(word, b->data + b->len); + b->len += 4; +} + +static void pb_tag(struct pb *b, u32 type, u32 size) +{ + pb_word(b, size | type << 24); +} + +static void pb_str(struct pb *b, const char *s) +{ + pb_tag(b, PB_STRING, strlen(s)); + pb_raw(b, s, strlen(s)); +} + +static void pb_int(struct pb *b, s64 value) +{ + u8 raw[8]; + + pb_tag(b, PB_INT64, 0); + put_unaligned_le64(value, raw); + pb_raw(b, raw, sizeof(raw)); +} + +static void pb_kint(struct pb *b, const char *key, s64 value) +{ + pb_str(b, key); + pb_int(b, value); +} + +static void pb_kbool(struct pb *b, const char *key, bool value) +{ + pb_str(b, key); + pb_tag(b, PB_BOOL, value); +} + +static void pb_kstr(struct pb *b, const char *key, const char *value) +{ + pb_str(b, key); + pb_str(b, value); +} + +typedef int (*pb_parse_fn)(const u8 *data, size_t len, void *priv); + +/* + * Every strict prefix of @b must fail. The bytes after the prefix stay in + * place and complete a valid blob, so a parser that reads past its length + * succeeds instead. Each prefix also runs from an exact-size allocation, + * which KASAN checks when enabled. + */ +static void pb_expect_prefixes_fail(struct pb *b, pb_parse_fn fn, void *priv) +{ + struct kunit *test = b->test; + u32 len; + + for (len = 0; len < b->len; len++) { + u8 *copy; + + KUNIT_EXPECT_LT_MSG(test, fn(b->data, len, priv), 0, + "prefix %u of %u", len, b->len); + if (!len) + continue; + copy = kmemdup(b->data, len, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, copy); + KUNIT_EXPECT_LT_MSG(test, fn(copy, len, priv), 0, + "exact prefix %u of %u", len, b->len); + kfree(copy); + } +} + +/* A parser that reports an error leaves its output alone. */ +static void pb_expect_untouched(struct kunit *test, const void *out, size_t size) +{ + KUNIT_EXPECT_NULL(test, memchr_inv(out, 0xa5, size)); +} + +/* Serialized framing */ + +static bool pb_complete(struct pb *b) +{ + return dcp_property_complete(b->data, b->len, b->len); +} + +static void parser_bounds_framing_test(struct kunit *test) +{ + struct pb *b; + + /* The last-element flag in bit 31 is accepted. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_str(b, "Key"); + pb_word(b, PB_INT64 << 24 | BIT(31)); + pb_raw(b, "\0\0\0\0\0\0\0\0", 8); + KUNIT_EXPECT_TRUE(test, pb_complete(b)); + + /* Padding bits 29 and 30 must be clear. */ + b = pb_new(test, true); + pb_word(b, PB_BOOL << 24 | BIT(29)); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + b = pb_new(test, true); + pb_word(b, PB_BOOL << 24 | BIT(30)); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + /* Types the serializer does not define. */ + b = pb_new(test, true); + pb_tag(b, 3, 0); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + b = pb_new(test, true); + pb_tag(b, 0, 0); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + /* An integer is eight bytes whatever its tag size says. */ + b = pb_new(test, true); + pb_tag(b, PB_INT64, 4); + pb_raw(b, "\1\0\0\0", 4); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + /* A string or blob longer than the bytes left. */ + b = pb_new(test, true); + pb_tag(b, PB_STRING, 5); + pb_raw(b, "abcd", 4); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + b = pb_new(test, true); + pb_tag(b, PB_BLOB, 0xffffff); + pb_raw(b, "abcd", 4); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + /* The largest dictionary count, doubled for its keys, still ends at the blob. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 0xffffff); + pb_kint(b, "Key", 1); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); +} + +static void pb_nest(struct pb *b, unsigned int depth) +{ + unsigned int i; + + for (i = 0; i < depth; i++) + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_BOOL, 1); +} + +/* The skipper bounds its recursion at 32 levels: 31 containers fit. */ +static void parser_bounds_depth_test(struct kunit *test) +{ + struct pb *b; + + b = pb_new(test, true); + pb_nest(b, 31); + KUNIT_EXPECT_TRUE(test, pb_complete(b)); + + b = pb_new(test, true); + pb_nest(b, 32); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + b = pb_new(test, true); + pb_nest(b, 1000); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); +} + +static void parser_bounds_array_count_test(struct kunit *test) +{ + struct dcp_parse_ctx ctx; + struct pb *b; + u32 count = 0xa5a5a5a5; + + b = pb_new(test, true); + pb_tag(b, PB_ARRAY, 3); + pb_int(b, 1); + pb_int(b, 2); + pb_int(b, 3); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_array_count(&ctx, &count), 0); + KUNIT_EXPECT_EQ(test, count, 3); + /* The cursor is not consumed. */ + KUNIT_EXPECT_EQ(test, ctx.pos, 4); + + /* Only the tag is read: a count beyond the blob is the caller's to bound. */ + b = pb_new(test, true); + pb_tag(b, PB_ARRAY, 0xffffff); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_array_count(&ctx, &count), 0); + KUNIT_EXPECT_EQ(test, count, 0xffffff); + + count = 0xa5a5a5a5; + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_array_count(&ctx, &count), -EINVAL); + KUNIT_ASSERT_EQ(test, parse(b->data, 6, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_array_count(&ctx, &count), -EINVAL); + KUNIT_EXPECT_EQ(test, count, 0xa5a5a5a5); +} + +/* DisplayAttributes */ + +static void pb_point(struct pb *b, const char *key, s64 x, s64 y, s64 gamma) +{ + pb_str(b, key); + pb_tag(b, PB_DICT, gamma ? 3 : 2); + pb_kint(b, "X", x); + pb_kint(b, "Y", y); + if (gamma) + pb_kint(b, "Gamma", gamma); +} + +static void pb_product(struct pb *b, const char *manufacturer, s64 product, + const char *name) +{ + pb_tag(b, PB_DICT, 7); + pb_kstr(b, "ManufacturerID", manufacturer); + pb_kint(b, "ProductID", product); + pb_kstr(b, "ProductName", name); + pb_kint(b, "SerialNumber", 7); + pb_kint(b, "WeekOfManufacture", 10); + pb_kint(b, "YearOfManufacture", 2024); + pb_kstr(b, "AlphanumericSerialNumber", "SN0001"); +} + +static struct pb *pb_display_attributes(struct kunit *test) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_DICT, 10); + pb_kint(b, "MaxHorizontalImageSize", 60); + pb_kint(b, "MaxVerticalImageSize", 34); + pb_str(b, "Chromaticity"); + pb_tag(b, PB_DICT, 3); + pb_point(b, "Red", 42000, 21000, 0); + pb_point(b, "Green", 20000, 45000, 0); + pb_point(b, "Blue", 10000, 4000, 0); + pb_point(b, "DefaultWhitePoint", 20500, 21500, 144179); + pb_kbool(b, "SupportsPQEOTF", true); + pb_kbool(b, "SupportsHDRStaticMetadataType1", true); + pb_kint(b, "SupportsBT2020RGB", 1); + pb_str(b, "Luminance"); + pb_tag(b, PB_DICT, 3); + pb_kint(b, "Max", 600 << 16); + pb_kint(b, "MaxFrameAverage", 400 << 16); + pb_kint(b, "Min", 1 << 12); + pb_kstr(b, "Unknown", "ignored"); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 0x1234, "Synthetic"); + return b; +} + +static int pb_run_display_metadata(const u8 *data, size_t len, void *priv) +{ + struct dcp_parse_ctx ctx; + int ret = parse(data, len, &ctx); + + return ret ?: parse_display_metadata(&ctx, priv); +} + +static void parser_bounds_metadata_test(struct kunit *test) +{ + struct pb *b = pb_display_attributes(test); + struct dcp_display_metadata md; + + memset(&md, 0xa5, sizeof(md)); + KUNIT_ASSERT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), 0); + KUNIT_EXPECT_EQ(test, md.width_cm, 60); + KUNIT_EXPECT_EQ(test, md.height_cm, 34); + KUNIT_EXPECT_EQ(test, md.chromaticity[0][0], 42000); + KUNIT_EXPECT_EQ(test, md.chromaticity[1][1], 45000); + KUNIT_EXPECT_EQ(test, md.chromaticity[2][1], 4000); + KUNIT_EXPECT_EQ(test, md.white[0], 20500); + KUNIT_EXPECT_EQ(test, md.white[1], 21500); + KUNIT_EXPECT_EQ(test, md.gamma, 144179); + KUNIT_EXPECT_STREQ(test, md.manufacturer, "TST"); + KUNIT_EXPECT_EQ(test, md.product, 0x1234); + KUNIT_EXPECT_STREQ(test, md.name, "Synthetic"); + KUNIT_EXPECT_STREQ(test, md.serial_text, "SN0001"); + KUNIT_EXPECT_EQ(test, md.serial, 7); + KUNIT_EXPECT_EQ(test, md.week, 10); + KUNIT_EXPECT_EQ(test, md.year, 2024); + KUNIT_EXPECT_TRUE(test, md.pq); + KUNIT_EXPECT_TRUE(test, md.static_metadata_type1); + KUNIT_EXPECT_TRUE(test, md.bt2020_rgb); + KUNIT_EXPECT_EQ(test, md.max_luminance, 600 << 16); + KUNIT_EXPECT_EQ(test, md.max_fall, 400 << 16); + KUNIT_EXPECT_EQ(test, md.min_luminance, 1 << 12); + KUNIT_EXPECT_EQ(test, md.defaults, 0); +} + +static void parser_bounds_metadata_truncated_test(struct kunit *test) +{ + struct pb *b = pb_display_attributes(test); + struct dcp_display_metadata md; + + memset(&md, 0xa5, sizeof(md)); + pb_expect_prefixes_fail(b, pb_run_display_metadata, &md); + pb_expect_untouched(test, &md, sizeof(md)); +} + +/* Optional values out of range fall back to EDID defaults; identity is required. */ +static void parser_bounds_metadata_defaults_test(struct kunit *test) +{ + struct dcp_display_metadata md; + struct pb *b; + + b = pb_new(test, true); + pb_tag(b, PB_DICT, 6); + pb_kint(b, "MaxHorizontalImageSize", 256); + pb_kint(b, "MaxVerticalImageSize", 34); + /* Primaries without a white point are no colour description. */ + pb_str(b, "Chromaticity"); + pb_tag(b, PB_DICT, 3); + pb_point(b, "Red", 42000, 21000, 0); + pb_point(b, "Green", 20000, 45000, 0); + pb_point(b, "Blue", 10000, 4000, 0); + /* A minimum at the maximum is no luminance range. */ + pb_str(b, "Luminance"); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "Max", 100); + pb_kint(b, "Min", 100); + pb_kstr(b, "SupportsBT2020RGB", "yes"); + pb_str(b, "ProductAttributes"); + pb_tag(b, PB_DICT, 2); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 1); + + KUNIT_ASSERT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), 0); + KUNIT_EXPECT_EQ(test, md.width_cm, 0); + KUNIT_EXPECT_EQ(test, md.height_cm, 0); + KUNIT_EXPECT_EQ(test, md.chromaticity[0][0], 0); + KUNIT_EXPECT_EQ(test, md.max_luminance, 0); + KUNIT_EXPECT_FALSE(test, md.bt2020_rgb); + KUNIT_EXPECT_EQ(test, md.defaults, + DCP_METADATA_DEFAULT_SIZE | DCP_METADATA_DEFAULT_COLOR | + DCP_METADATA_DEFAULT_NAME | DCP_METADATA_DEFAULT_DATE); + + /* No ProductAttributes at all. */ + memset(&md, 0xa5, sizeof(md)); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "MaxHorizontalImageSize", 60); + pb_kint(b, "MaxVerticalImageSize", 34); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + pb_expect_untouched(test, &md, sizeof(md)); +} + +static void parser_bounds_metadata_keys_test(struct kunit *test) +{ + struct dcp_display_metadata md; + char key[80]; + struct pb *b; + + memset(&md, 0xa5, sizeof(md)); + + /* A repeated key. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kint(b, "MaxHorizontalImageSize", 60); + pb_kint(b, "MaxHorizontalImageSize", 61); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 1, "Synthetic"); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + /* A key with a control character. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "Odd\nKey", 1); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 1, "Synthetic"); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + /* An empty key and one longer than the key buffer. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "", 1); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 1, "Synthetic"); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + memset(key, 'K', sizeof(key)); + key[64] = 0; + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, key, 1); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 1, "Synthetic"); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + /* A key of the wrong type. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_int(b, 1); + pb_int(b, 1); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + /* An array where the dictionary goes. */ + b = pb_new(test, true); + pb_tag(b, PB_ARRAY, 0); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + pb_expect_untouched(test, &md, sizeof(md)); +} + +static int pb_run_panel_product(const u8 *data, size_t len, void *priv) +{ + struct dcp_parse_ctx ctx; + int ret = parse(data, len, &ctx); + + return ret ?: parse_panel_product_metadata(&ctx, priv); +} + +static void parser_bounds_product_test(struct kunit *test) +{ + struct dcp_display_metadata md; + char label[257]; + struct pb *b; + + /* A panel label is cut to a descriptor; its date is not read. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 4); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 0xffff); + pb_kstr(b, "ProductName", "Synthetic Panel Label"); + pb_kstr(b, "WeekOfManufacture", "not a number"); + KUNIT_ASSERT_EQ(test, pb_run_panel_product(b->data, b->len, &md), 0); + KUNIT_EXPECT_STREQ(test, md.manufacturer, "TST"); + KUNIT_EXPECT_EQ(test, md.product, 0xffff); + KUNIT_EXPECT_STREQ(test, md.name, "Synthetic Pan"); + KUNIT_EXPECT_EQ(test, md.week, 0); + + /* A blank label reads as absent. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 1); + pb_kstr(b, "ProductName", " "); + KUNIT_ASSERT_EQ(test, pb_run_panel_product(b->data, b->len, &md), 0); + KUNIT_EXPECT_EQ(test, md.name[0], 0); + + /* The legacy ID alone gives the manufacturer: TST = 20 << 10 | 19 << 5 | 20. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "LegacyManufacturerID", 20 << 10 | 19 << 5 | 20); + pb_kint(b, "ProductID", 1); + KUNIT_ASSERT_EQ(test, pb_run_panel_product(b->data, b->len, &md), 0); + KUNIT_EXPECT_STREQ(test, md.manufacturer, "TST"); + + memset(&md, 0xa5, sizeof(md)); + + /* A legacy ID that disagrees with the manufacturer. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "LegacyManufacturerID", 1 << 10 | 1 << 5 | 1); + pb_kint(b, "ProductID", 1); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + + /* Not three capitals; a product beyond 16 bits; no product. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kstr(b, "ManufacturerID", "tst"); + pb_kint(b, "ProductID", 1); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kstr(b, "ManufacturerID", "TSTX"); + pb_kint(b, "ProductID", 1); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 0x10000); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kstr(b, "ManufacturerID", "TST"); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + + /* A label longer than 255 bytes or with a control character. */ + memset(label, 'L', sizeof(label)); + label[256] = 0; + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 1); + pb_kstr(b, "ProductName", label); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 1); + pb_kstr(b, "ProductName", "Tab\there"); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + + pb_expect_untouched(test, &md, sizeof(md)); + + b = pb_new(test, true); + pb_product(b, "TST", 1, "Synthetic"); + pb_expect_prefixes_fail(b, pb_run_panel_product, &md); + pb_expect_untouched(test, &md, sizeof(md)); +} + +/* DPTX port capabilities */ + +static int pb_run_dptx_caps(const u8 *data, size_t len, void *priv) +{ + struct dcp_parse_ctx ctx; + int ret = parse(data, len, &ctx); + + return ret ?: parse_dptx_caps(&ctx, priv); +} + +static void parser_bounds_dptx_caps_test(struct kunit *test) +{ + struct dcp_dptx_caps caps; + struct pb *b; + + b = pb_new(test, true); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "MaxPixelWidth", 5120); + pb_str(b, "Nested"); + pb_tag(b, PB_ARRAY, 2); + pb_tag(b, PB_DICT, 0); + pb_int(b, 3); + pb_kint(b, "MaxTotalPixelRate", 1000000); + pb_kint(b, "MaxActivePixelRate", U32_MAX); + KUNIT_ASSERT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), 0); + KUNIT_EXPECT_EQ(test, caps.width, 5120); + KUNIT_EXPECT_EQ(test, caps.total_rate, 1000000); + KUNIT_EXPECT_EQ(test, caps.active_rate, U32_MAX); + + memset(&caps, 0xa5, sizeof(caps)); + pb_expect_prefixes_fail(b, pb_run_dptx_caps, &caps); + + /* A missing limit. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "MaxPixelWidth", 5120); + pb_kint(b, "MaxTotalPixelRate", 1000000); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -ENOENT); + + /* A repeated limit. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "MaxPixelWidth", 5120); + pb_kint(b, "MaxPixelWidth", 4096); + pb_kint(b, "MaxTotalPixelRate", 1000000); + pb_kint(b, "MaxActivePixelRate", 1000000); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + + /* Zero, beyond 32 bits, negative, or not an integer. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kint(b, "MaxPixelWidth", 0); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kint(b, "MaxTotalPixelRate", (s64)U32_MAX + 1); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kint(b, "MaxActivePixelRate", -1); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kstr(b, "MaxPixelWidth", "5120"); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + + pb_expect_untouched(test, &caps, sizeof(caps)); +} + +/* System log brightness events */ + +static struct pb *pb_mnits_event(struct kunit *test, const char *event, s64 mnits) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_DICT, 5); + pb_kstr(b, "logEvent", event); + pb_kint(b, "timestamp", 1234); + pb_kint(b, "iDAC", 56); + pb_str(b, "extra"); + pb_tag(b, PB_DICT, 1); + pb_kbool(b, "x", false); + pb_kint(b, "mNits", mnits); + return b; +} + +static int pb_run_mnits(const u8 *data, size_t len, void *priv) +{ + struct dcp_parse_ctx ctx; + int ret = parse(data, len, &ctx); + + return ret ?: parse_system_log_mnits(&ctx, priv); +} + +static void parser_bounds_mnits_test(struct kunit *test) +{ + struct dcp_system_ev_mnits entry; + struct pb *b; + + b = pb_mnits_event(test, "Display (Event Forward)", 500000); + KUNIT_ASSERT_EQ(test, pb_run_mnits(b->data, b->len, &entry), 0); + KUNIT_EXPECT_EQ(test, entry.millinits, 500000); + KUNIT_EXPECT_EQ(test, entry.idac, 56); + KUNIT_EXPECT_EQ(test, entry.timestamp, 1234); + + memset(&entry, 0xa5, sizeof(entry)); + pb_expect_prefixes_fail(b, pb_run_mnits, &entry); + + b = pb_mnits_event(test, "Display (Event Forward) ", 500000); + KUNIT_EXPECT_EQ(test, pb_run_mnits(b->data, b->len, &entry), -EINVAL); + b = pb_mnits_event(test, "Display (Event Forward)", -1); + KUNIT_EXPECT_EQ(test, pb_run_mnits(b->data, b->len, &entry), -EINVAL); + b = pb_mnits_event(test, "Display (Event Forward)", (s64)U32_MAX + 1); + KUNIT_EXPECT_EQ(test, pb_run_mnits(b->data, b->len, &entry), -ERANGE); + + /* No timestamp. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "logEvent", "Display (Event Forward)"); + pb_kint(b, "iDAC", 56); + pb_kint(b, "mNits", 1); + KUNIT_EXPECT_EQ(test, pb_run_mnits(b->data, b->len, &entry), -EINVAL); + + pb_expect_untouched(test, &entry, sizeof(entry)); +} + +static int pb_run_mnits_pairs(const u8 *data, size_t len, void *priv) +{ + return parse_system_log_mnits_pairs(data, len, priv); +} + +/* Header-less key/value pairs, read up to the first one that does not parse. */ +static void parser_bounds_mnits_pairs_test(struct kunit *test) +{ + struct dcp_system_ev_mnits entry; + struct pb *b; + + b = pb_new(test, false); + pb_kint(b, "timestamp", 99); + pb_kint(b, "iDAC", -5); + pb_kstr(b, "other", "value"); + pb_kint(b, "mNits", 250); + KUNIT_ASSERT_EQ(test, pb_run_mnits_pairs(b->data, b->len, &entry), 0); + KUNIT_EXPECT_EQ(test, entry.millinits, 250); + KUNIT_EXPECT_EQ(test, entry.idac, 0); + KUNIT_EXPECT_EQ(test, entry.timestamp, 99); + + /* mNits comes last, so no prefix holds all of it. */ + memset(&entry, 0xa5, sizeof(entry)); + pb_expect_prefixes_fail(b, pb_run_mnits_pairs, &entry); + pb_expect_untouched(test, &entry, sizeof(entry)); + + /* A key whose length runs past the end stops the walk before mNits. */ + b = pb_new(test, false); + pb_tag(b, PB_STRING, 0x1000); + pb_raw(b, "mNits", 5); + pb_kint(b, "mNits", 250); + KUNIT_EXPECT_EQ(test, pb_run_mnits_pairs(b->data, b->len, &entry), -EINVAL); + + /* A value of the wrong type stops it too. */ + b = pb_new(test, false); + pb_kstr(b, "iDAC", "56"); + pb_kint(b, "mNits", 250); + KUNIT_EXPECT_EQ(test, pb_run_mnits_pairs(b->data, b->len, &entry), -EINVAL); + + b = pb_new(test, false); + pb_kint(b, "mNits", (s64)U32_MAX + 1); + KUNIT_EXPECT_EQ(test, pb_run_mnits_pairs(b->data, b->len, &entry), -EINVAL); + pb_expect_untouched(test, &entry, sizeof(entry)); +} + +/* TimingElements catalogs */ + +static void pb_dimension(struct pb *b, const char *key, s64 active, s64 total) +{ + pb_str(b, key); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "Active", active); + pb_kint(b, "Total", total); + pb_kint(b, "FrontPorch", 8); + pb_kint(b, "SyncWidth", 4); +} + +static struct pb *pb_timing_ids(struct kunit *test) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_ARRAY, 4); + pb_tag(b, PB_DICT, 3); + pb_kint(b, "ID", 3); + pb_dimension(b, "HorizontalAttributes", 1920, 2200); + pb_dimension(b, "VerticalAttributes", 1080, 1125); + /* Malformed entries are skipped: an ID of the wrong type, one beyond 32 bits. */ + pb_tag(b, PB_DICT, 1); + pb_kstr(b, "ID", "4"); + pb_tag(b, PB_DICT, 1); + pb_kint(b, "ID", (s64)U32_MAX + 5); + /* No size: zero. */ + pb_tag(b, PB_DICT, 2); + pb_kbool(b, "IsPreferred", true); + pb_kint(b, "ID", 9); + return b; +} + +static int pb_run_timing_ids(const u8 *data, size_t len, void *priv) +{ + return dcp_parse_timing_ids(data, len, priv, 4); +} + +static void parser_bounds_timing_ids_test(struct kunit *test) +{ + struct dcp_timing_id ids[4]; + struct pb *b = pb_timing_ids(test); + + memset(ids, 0xa5, sizeof(ids)); + KUNIT_ASSERT_EQ(test, dcp_parse_timing_ids(b->data, b->len, ids, 4), 2); + KUNIT_EXPECT_EQ(test, ids[0].id, 3); + KUNIT_EXPECT_EQ(test, ids[0].width, 1920); + KUNIT_EXPECT_EQ(test, ids[0].height, 1080); + KUNIT_EXPECT_EQ(test, ids[1].id, 9); + KUNIT_EXPECT_EQ(test, ids[1].width, 0); + KUNIT_EXPECT_EQ(test, ids[1].height, 0); + pb_expect_untouched(test, &ids[2], 2 * sizeof(ids[0])); + + /* At most @max are written. */ + memset(ids, 0xa5, sizeof(ids)); + KUNIT_EXPECT_EQ(test, dcp_parse_timing_ids(b->data, b->len, ids, 1), 1); + KUNIT_EXPECT_EQ(test, ids[0].id, 3); + pb_expect_untouched(test, &ids[1], 3 * sizeof(ids[0])); + KUNIT_EXPECT_EQ(test, dcp_parse_timing_ids(b->data, b->len, ids, 0), 0); + + /* Every truncation ends in a skip that cannot finish. */ + pb_expect_prefixes_fail(b, pb_run_timing_ids, ids); + + /* A dictionary is no catalog. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 0); + KUNIT_EXPECT_EQ(test, dcp_parse_timing_ids(b->data, b->len, ids, 4), -EINVAL); +} + +#define PB_MAX_COLORS 8 + +struct pb_colors { + unsigned int count; + struct dcp_color_element e[PB_MAX_COLORS]; +}; + +static void pb_collect_color(void *data, const struct dcp_color_element *e) +{ + struct pb_colors *c = data; + + if (c->count < PB_MAX_COLORS) + c->e[c->count] = *e; + c->count++; +} + +static void pb_color(struct pb *b, s64 id, s64 eotf) +{ + pb_tag(b, PB_DICT, 5); + pb_kint(b, "ID", id); + pb_kint(b, "Depth", 10); + pb_kint(b, "EOTF", eotf); + pb_kbool(b, "IsVirtual", false); + pb_kint(b, "Score", 100 + id); +} + +static struct pb *pb_timing_colors(struct kunit *test) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_ARRAY, 3); + /* A malformed entry that would match. */ + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ID", 5); + pb_kstr(b, "IsInterlaced", "no"); + /* Another timing. */ + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ID", 4); + pb_str(b, "ColorModes"); + pb_tag(b, PB_ARRAY, 1); + pb_color(b, 99, 0); + /* The timing, its colours before its ID. */ + pb_tag(b, PB_DICT, 5); + pb_str(b, "ColorModes"); + pb_tag(b, PB_ARRAY, 2); + pb_color(b, 10, 0); + pb_color(b, 11, 2); + pb_str(b, "UnsafeColorElementIDs"); + pb_tag(b, PB_ARRAY, 1); + pb_int(b, 11); + pb_str(b, "DSCRequiredColorElementIDs"); + pb_tag(b, PB_ARRAY, 1); + pb_int(b, 10); + pb_kbool(b, "IsInterlaced", true); + pb_kint(b, "ID", 5); + return b; +} + +static int pb_run_timing_colors(const u8 *data, size_t len, void *priv) +{ + struct pb_colors *c = priv; + + c->count = 0; + return dcp_parse_timing_colors(data, len, 5, pb_collect_color, c, NULL); +} + +static void parser_bounds_timing_colors_test(struct kunit *test) +{ + struct pb *b = pb_timing_colors(test); + struct pb_colors *c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL); + bool interlaced = false; + + KUNIT_ASSERT_NOT_NULL(test, c); + KUNIT_ASSERT_EQ(test, dcp_parse_timing_colors(b->data, b->len, 5, pb_collect_color, + c, &interlaced), 0); + KUNIT_EXPECT_TRUE(test, interlaced); + KUNIT_ASSERT_EQ(test, c->count, 2); + KUNIT_EXPECT_EQ(test, c->e[0].id, 10); + KUNIT_EXPECT_EQ(test, c->e[0].depth, 10); + KUNIT_EXPECT_EQ(test, c->e[0].score, 110); + KUNIT_EXPECT_EQ(test, c->e[0].range, -1); + KUNIT_EXPECT_FALSE(test, c->e[0].is_virtual); + KUNIT_EXPECT_FALSE(test, c->e[0].unsafe); + KUNIT_EXPECT_TRUE(test, c->e[0].dsc_required); + KUNIT_EXPECT_EQ(test, c->e[1].id, 11); + KUNIT_EXPECT_EQ(test, c->e[1].eotf, 2); + KUNIT_EXPECT_TRUE(test, c->e[1].unsafe); + KUNIT_EXPECT_FALSE(test, c->e[1].dsc_required); + + c->count = 0; + KUNIT_EXPECT_EQ(test, dcp_parse_timing_colors(b->data, b->len, 6, pb_collect_color, + c, NULL), -ENOENT); + KUNIT_EXPECT_EQ(test, c->count, 0); + + pb_expect_prefixes_fail(b, pb_run_timing_colors, c); +} + +/* + * The restricted ID lists hold 64 entries each: further IDs are dropped, not + * written over the neighbouring list. + */ +static void parser_bounds_timing_colors_lists_test(struct kunit *test) +{ + struct pb_colors *c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL); + struct pb *b = pb_new(test, true); + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, c); + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "ID", 1); + pb_str(b, "DSCRequiredColorElementIDs"); + pb_tag(b, PB_ARRAY, 1); + pb_int(b, 10); + pb_str(b, "UnsafeColorElementIDs"); + pb_tag(b, PB_ARRAY, 65); + for (i = 0; i < 64; i++) + pb_int(b, 1000 + i); + pb_int(b, 11); + pb_str(b, "ColorModes"); + pb_tag(b, PB_ARRAY, 2); + pb_color(b, 10, 0); + pb_color(b, 11, 0); + + KUNIT_ASSERT_EQ(test, dcp_parse_timing_colors(b->data, b->len, 1, pb_collect_color, + c, NULL), 0); + KUNIT_ASSERT_EQ(test, c->count, 2); + KUNIT_EXPECT_TRUE(test, c->e[0].dsc_required); + KUNIT_EXPECT_FALSE(test, c->e[0].unsafe); + KUNIT_EXPECT_FALSE(test, c->e[1].dsc_required); + KUNIT_EXPECT_FALSE(test, c->e[1].unsafe); + + /* A list entry of the wrong type makes the entry malformed. */ + b = pb_new(test, true); + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ID", 1); + pb_str(b, "UnsafeColorElementIDs"); + pb_tag(b, PB_ARRAY, 1); + pb_str(b, "11"); + c->count = 0; + KUNIT_EXPECT_EQ(test, dcp_parse_timing_colors(b->data, b->len, 1, pb_collect_color, + c, NULL), -ENOENT); + KUNIT_EXPECT_EQ(test, c->count, 0); +} + +/* Panel EDID properties */ + +static void pb_edid(u8 *edid, unsigned int blocks) +{ + memset(edid, 0, blocks * 128); + memcpy(edid, "\x00\xff\xff\xff\xff\xff\xff\x00", 8); + edid[126] = blocks - 1; +} + +static void pb_kedid(struct pb *b, const char *key, const u8 *edid, u32 size) +{ + pb_str(b, key); + pb_tag(b, PB_BLOB, size); + pb_raw(b, edid, size); +} + +static void parser_bounds_edid_raw_test(struct kunit *test) +{ + u8 *edid = kunit_kzalloc(test, 4224, GFP_KERNEL); + const u8 *found = NULL; + size_t size = 0; + + KUNIT_ASSERT_NOT_NULL(test, edid); + pb_edid(edid, 2); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 256, &found, &size), 0); + KUNIT_EXPECT_PTR_EQ(test, found, (const u8 *)edid); + KUNIT_EXPECT_EQ(test, size, 256); + /* Trailing bytes after the extensions are not EDID. */ + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 300, &found, &size), 0); + KUNIT_EXPECT_EQ(test, size, 256); + + /* Extension blocks the buffer does not hold. */ + found = NULL; + size = 0; + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 255, &found, &size), -EINVAL); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 128, &found, &size), -EINVAL); + /* 33 blocks exceed the 4 KiB bound even when present. */ + pb_edid(edid, 33); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 4224, &found, &size), -EINVAL); + pb_edid(edid, 32); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 4096, &found, &size), 0); + KUNIT_EXPECT_EQ(test, size, 4096); + + /* Fewer than 128 bytes is no raw EDID, and no serialized blob either. */ + found = NULL; + size = 0; + pb_edid(edid, 1); + KUNIT_EXPECT_LT(test, parse_panel_edid_data(edid, 127, &found, &size), 0); + KUNIT_EXPECT_NULL(test, found); + KUNIT_EXPECT_EQ(test, size, 0); +} + +static int pb_run_edid(const u8 *data, size_t len, void *priv) +{ + const u8 *edid; + size_t size; + + return parse_panel_edid_data(data, len, &edid, &size); +} + +static void parser_bounds_edid_serialized_test(struct kunit *test) +{ + u8 *edid = kunit_kzalloc(test, 384, GFP_KERNEL); + const u8 *found; + unsigned int i; + size_t size; + struct pb *b; + + KUNIT_ASSERT_NOT_NULL(test, edid); + pb_edid(edid, 2); + + /* A blob at the root. */ + b = pb_new(test, true); + pb_tag(b, PB_BLOB, 256); + pb_raw(b, edid, 256); + KUNIT_ASSERT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), 0); + KUNIT_EXPECT_PTR_EQ(test, found, (const u8 *)b->data + 8); + KUNIT_EXPECT_EQ(test, size, 256); + + /* A named blob in a nested dictionary, after other values. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "Other", 1); + pb_str(b, "Properties"); + pb_tag(b, PB_DICT, 2); + pb_kedid(b, "NotEDID", edid, 128); + pb_kedid(b, "IODisplayEDID", edid, 256); + KUNIT_ASSERT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), 0); + KUNIT_EXPECT_EQ(test, size, 256); + KUNIT_EXPECT_EQ(test, memcmp(found, edid, 256), 0); + pb_expect_prefixes_fail(b, pb_run_edid, NULL); + + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "edid", edid, 256); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), 0); + + /* No EDID key. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDIDs", edid, 256); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -ENOENT); + + /* Sizes that are no whole EDID, or disagree with its extension count. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDID", edid, 130); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDID", edid, 384); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDID", edid + 1, 128); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -EINVAL); + + /* A blob size beyond the bytes present. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_str(b, "EDID"); + pb_tag(b, PB_BLOB, 256); + pb_raw(b, edid, 128); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -EINVAL); + + /* Deeper than four dictionaries. */ + b = pb_new(test, true); + for (i = 0; i < 5; i++) { + pb_tag(b, PB_DICT, 1); + pb_str(b, "Nested"); + } + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDID", edid, 128); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -E2BIG); + + /* More entries than the walk budget. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 64); + for (i = 0; i < 64; i++) + pb_kint(b, "N", i); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -E2BIG); +} + +/* Mode ranking */ + +static void pb_mode(struct dcp_display_mode *m, int clock, u16 htotal, u16 vtotal, + bool preferred) +{ + memset(m, 0, sizeof(*m)); + m->mode.clock = clock; + m->mode.htotal = htotal; + m->mode.vtotal = vtotal; + m->firmware_preferred = preferred; +} + +static void parser_bounds_default_above_test(struct kunit *test) +{ + struct dcp_display_mode a, b; + + /* The higher refresh rate first, whatever the preference or score. */ + pb_mode(&a, 297000, 2200, 1125, false); + pb_mode(&b, 148500, 2200, 1125, true); + KUNIT_EXPECT_TRUE(test, dcp_mode_default_above(&a, 0, &b, 100)); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_above(&b, 100, &a, 0)); + + /* Same rate from different totals: IsPreferred, then the score. */ + pb_mode(&a, 297000, 4400, 1125, false); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_above(&a, 100, &b, 0)); + KUNIT_EXPECT_TRUE(test, dcp_mode_default_above(&b, 0, &a, 100)); + a.firmware_preferred = true; + KUNIT_EXPECT_TRUE(test, dcp_mode_default_above(&a, 1, &b, 0)); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_above(&a, 0, &b, 0)); + + /* The cross products do not wrap at the largest timings. */ + pb_mode(&a, INT_MAX, U16_MAX, U16_MAX, false); + pb_mode(&b, INT_MAX - 1, U16_MAX, U16_MAX, false); + KUNIT_EXPECT_TRUE(test, dcp_mode_default_above(&a, 0, &b, 0)); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_above(&b, 0, &a, 0)); +} + +#if IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) +/* Audio elements */ + +static void pb_layout(struct pb *b, s64 nchans, const char * const *labels, + unsigned int nlabels) +{ + unsigned int i; + + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ActiveChannelCount", nchans); + pb_str(b, "ChannelLayout"); + pb_tag(b, PB_ARRAY, nlabels); + for (i = 0; i < nlabels; i++) + pb_str(b, labels[i]); +} + +static const char * const pb_stereo[] = { "Front Left", "Front Right" }; +static const char * const pb_surround[] = { + "Front Left", "Front Right", "Front Center", "Low Frequency Effects", + "Rear Left", "Rear Right", "Side Left", "Rear Center", +}; + +static void pb_avep(struct pb *b, s64 rate, s64 sample_size, const char *cookie_key, + u32 cookie_size) +{ + u8 cookie[DCP_SOUND_COOKIE_MAX + 4]; + unsigned int i; + + for (i = 0; i < sizeof(cookie); i++) + cookie[i] = i + 1; + pb_tag(b, PB_DICT, 5); + pb_kint(b, "StreamSampleRate", rate); + pb_kint(b, "SampleSize", sample_size); + pb_kstr(b, "Other", "skipped"); + pb_str(b, "AudioChannelLayoutElements"); + pb_tag(b, PB_ARRAY, 2); + pb_layout(b, 2, pb_stereo, ARRAY_SIZE(pb_stereo)); + pb_layout(b, 8, pb_surround, ARRAY_SIZE(pb_surround)); + pb_str(b, cookie_key); + pb_tag(b, PB_BLOB, cookie_size); + pb_raw(b, cookie, cookie_size); +} + +static struct pb *pb_audio(struct kunit *test, u32 cookie_size, bool unmatched) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_ARRAY, unmatched ? 3 : 2); + pb_avep(b, 44100, 16, "ElementData", cookie_size); + pb_avep(b, 48000, 24, "ElementData", cookie_size); + /* A rate ALSA has no bit for and a sample size it has no format for. */ + if (unmatched) + pb_avep(b, 12345, 18, "ElementData", cookie_size); + return b; +} + +static const struct dcp_sound_format_mask pb_any = { + .formats = ~0ULL, .rates = ~0U, .nchans = ~0U, +}; + +/* + * Channel counts the firmware reports but the u32 channel mask has no bit + * for (32 and up, negative, wider than 32 bits) match nothing; they must not + * wrap onto the bit of a small count (1 << 33 is 1 << 1 on arm64). + */ +static void parser_bounds_sound_wide_layouts_test(struct kunit *test) +{ + static const s64 counts[] = { 2, 31, 32, 33, 34, 63, 64, -1, -31, 0x100000001LL }; + struct dcp_sound_format_mask sieve = pb_any, hits; + struct dcp_parse_ctx ctx; + struct pb *b = pb_new(test, true); + unsigned int i; + + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 3); + pb_kint(b, "StreamSampleRate", 48000); + pb_kint(b, "SampleSize", 16); + pb_str(b, "AudioChannelLayoutElements"); + pb_tag(b, PB_ARRAY, ARRAY_SIZE(counts)); + for (i = 0; i < ARRAY_SIZE(counts); i++) { + pb_tag(b, PB_DICT, 1); + pb_kint(b, "ActiveChannelCount", counts[i]); + } + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_constraints(&ctx, &sieve, &hits), 0); + KUNIT_EXPECT_EQ(test, hits.nchans, BIT(2) | BIT(31)); + + /* No layout has 0 or 1 channels: a sieve for those matches no element */ + sieve.nchans = BIT(0) | BIT(1); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_constraints(&ctx, &sieve, &hits), 0); + KUNIT_EXPECT_EQ(test, hits.nchans, 0U); + KUNIT_EXPECT_EQ(test, hits.rates, 0U); +} + +/* + * A count wider than 32 bits is not the low 32 bits of itself: a layout + * claiming 0x100000008 channels must not be taken for the 8-channel one + * and replace its channel map. + */ +static void parser_bounds_sound_wide_layout_map_test(struct kunit *test) +{ + struct dcp_sound_format_mask sieve = { + .formats = SNDRV_PCM_FMTBIT_S16, + .rates = SNDRV_PCM_RATE_48000, + .nchans = BIT(8), + }; + u8 data[DCP_SOUND_COOKIE_SIZE] = { 1 }; + struct snd_pcm_chmap_elem chmap = {}; + struct dcp_sound_cookie cookie = {}; + struct dcp_parse_ctx ctx; + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "StreamSampleRate", 48000); + pb_kint(b, "SampleSize", 16); + pb_str(b, "AudioChannelLayoutElements"); + pb_tag(b, PB_ARRAY, 2); + pb_layout(b, 8, pb_surround, ARRAY_SIZE(pb_surround)); + pb_layout(b, 0x100000008LL, pb_stereo, ARRAY_SIZE(pb_stereo)); + pb_str(b, "ElementData"); + pb_tag(b, PB_BLOB, sizeof(data)); + pb_raw(b, data, sizeof(data)); + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 1); + KUNIT_EXPECT_EQ(test, chmap.channels, 8); + KUNIT_EXPECT_EQ(test, chmap.map[3], SNDRV_CHMAP_LFE); +} + +static void parser_bounds_sound_constraints_test(struct kunit *test) +{ + struct dcp_sound_format_mask sieve = pb_any, hits; + struct dcp_parse_ctx ctx; + struct pb *b = pb_audio(test, DCP_SOUND_COOKIE_SIZE, true); + u32 len; + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_constraints(&ctx, &sieve, &hits), 0); + KUNIT_EXPECT_EQ(test, hits.rates, SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000); + KUNIT_EXPECT_EQ(test, hits.formats, SNDRV_PCM_FMTBIT_S16 | SNDRV_PCM_FMTBIT_S24); + KUNIT_EXPECT_EQ(test, hits.nchans, BIT(2) | BIT(8)); + + sieve.rates = SNDRV_PCM_RATE_48000; + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_constraints(&ctx, &sieve, &hits), 0); + KUNIT_EXPECT_EQ(test, hits.rates, SNDRV_PCM_RATE_48000); + KUNIT_EXPECT_EQ(test, hits.formats, SNDRV_PCM_FMTBIT_S24); + + /* The parser reports a truncation instead of the elements it did read. */ + sieve = pb_any; + for (len = 4; len < b->len; len++) { + KUNIT_ASSERT_EQ(test, parse(b->data, len, &ctx), 0); + KUNIT_EXPECT_LT_MSG(test, parse_sound_constraints(&ctx, &sieve, &hits), 0, + "prefix %u of %u", len, b->len); + } +} + +static void parser_bounds_sound_mode_test(struct kunit *test) +{ + struct dcp_sound_format_mask sieve = { + .formats = SNDRV_PCM_FMTBIT_S24, + .rates = SNDRV_PCM_RATE_48000, + .nchans = BIT(8), + }; + struct snd_pcm_chmap_elem chmap = {}; + struct dcp_sound_cookie cookie = {}; + struct dcp_parse_ctx ctx; + struct pb *b = pb_audio(test, DCP_SOUND_COOKIE_SIZE, true); + u32 len; + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 1); + KUNIT_ASSERT_EQ(test, chmap.channels, 8); + KUNIT_EXPECT_EQ(test, chmap.map[0], SNDRV_CHMAP_FL); + KUNIT_EXPECT_EQ(test, chmap.map[3], SNDRV_CHMAP_LFE); + /* A label the table does not name. */ + KUNIT_EXPECT_EQ(test, chmap.map[6], SNDRV_CHMAP_UNKNOWN); + KUNIT_EXPECT_EQ(test, chmap.map[7], SNDRV_CHMAP_RC); + KUNIT_EXPECT_EQ(test, cookie.data[0], 1); + KUNIT_EXPECT_EQ(test, cookie.data[DCP_SOUND_COOKIE_SIZE - 1], DCP_SOUND_COOKIE_SIZE); + + /* No element matches. */ + sieve.rates = SNDRV_PCM_RATE_96000; + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 0); + sieve.rates = SNDRV_PCM_RATE_48000; + + /* Link data shorter than the service takes. */ + b = pb_audio(test, DCP_SOUND_COOKIE_SIZE - 1, true); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), -EINVAL); + +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* The 14.7 external role takes 32 bytes. */ + b = pb_audio(test, DCP_SOUND_COOKIE_SIZE, true); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + ctx.v14_7_audio = true; + KUNIT_EXPECT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), -EINVAL); + b = pb_audio(test, DCP_SOUND_COOKIE_SIZE_V14_7, true); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + ctx.v14_7_audio = true; + KUNIT_ASSERT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 1); + KUNIT_EXPECT_EQ(test, cookie.data[DCP_SOUND_COOKIE_SIZE_V14_7 - 1], + DCP_SOUND_COOKIE_SIZE_V14_7); +#endif + + /* The matching element is the last: no prefix holds all of it. */ + b = pb_audio(test, DCP_SOUND_COOKIE_SIZE, false); + for (len = 4; len < b->len; len++) { + KUNIT_ASSERT_EQ(test, parse(b->data, len, &ctx), 0); + KUNIT_EXPECT_LT_MSG(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 0, + "prefix %u of %u", len, b->len); + } +} + +/* A layout with more labels than a channel map holds is cut at the map. */ +static void parser_bounds_sound_chmap_test(struct kunit *test) +{ + struct dcp_sound_format_mask sieve = pb_any; + struct snd_pcm_chmap_elem chmap = {}; + struct dcp_parse_ctx ctx; + struct pb *b = pb_new(test, true); + unsigned int i; + + sieve.nchans = BIT(2); + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "StreamSampleRate", 48000); + pb_kint(b, "SampleSize", 24); + pb_str(b, "AudioChannelLayoutElements"); + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ActiveChannelCount", 2); + pb_str(b, "ChannelLayout"); + pb_tag(b, PB_ARRAY, ARRAY_SIZE(chmap.map) + 5); + for (i = 0; i < ARRAY_SIZE(chmap.map) + 5; i++) + pb_str(b, i & 1 ? "Front Right" : "Front Left"); + pb_str(b, "ElementData"); + pb_tag(b, PB_BLOB, DCP_SOUND_COOKIE_MAX); + pb_raw(b, "abcdefghijklmnopqrstuvwxyz0123456789", DCP_SOUND_COOKIE_MAX); + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, NULL), 1); + KUNIT_EXPECT_EQ(test, chmap.channels, ARRAY_SIZE(chmap.map)); + KUNIT_EXPECT_EQ(test, chmap.map[ARRAY_SIZE(chmap.map) - 1], SNDRV_CHMAP_FL); +} +#endif + +static struct kunit_case parser_bounds_cases[] = { + KUNIT_CASE(parser_bounds_framing_test), + KUNIT_CASE(parser_bounds_depth_test), + KUNIT_CASE(parser_bounds_array_count_test), + KUNIT_CASE(parser_bounds_metadata_test), + KUNIT_CASE(parser_bounds_metadata_truncated_test), + KUNIT_CASE(parser_bounds_metadata_defaults_test), + KUNIT_CASE(parser_bounds_metadata_keys_test), + KUNIT_CASE(parser_bounds_product_test), + KUNIT_CASE(parser_bounds_dptx_caps_test), + KUNIT_CASE(parser_bounds_mnits_test), + KUNIT_CASE(parser_bounds_mnits_pairs_test), + KUNIT_CASE(parser_bounds_timing_ids_test), + KUNIT_CASE(parser_bounds_timing_colors_test), + KUNIT_CASE(parser_bounds_timing_colors_lists_test), + KUNIT_CASE(parser_bounds_edid_raw_test), + KUNIT_CASE(parser_bounds_edid_serialized_test), + KUNIT_CASE(parser_bounds_default_above_test), +#if IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) + KUNIT_CASE(parser_bounds_sound_constraints_test), + KUNIT_CASE(parser_bounds_sound_wide_layouts_test), + KUNIT_CASE(parser_bounds_sound_wide_layout_map_test), + KUNIT_CASE(parser_bounds_sound_mode_test), + KUNIT_CASE(parser_bounds_sound_chmap_test), +#endif + {} +}; + +static struct kunit_suite parser_bounds_suite = { + .name = "apple-dcp-parser-bounds", + .test_cases = parser_bounds_cases, +}; + +kunit_test_suite(parser_bounds_suite); diff --git a/drivers/gpu/drm/apple/parser-test.c b/drivers/gpu/drm/apple/parser-test.c index e79da0fb0ad08e..3cd787b9e05503 100644 --- a/drivers/gpu/drm/apple/parser-test.c +++ b/drivers/gpu/drm/apple/parser-test.c @@ -1428,8 +1428,9 @@ static void parser_panel_identity(struct kunit *test) struct dcp_parse_ctx ctx; const struct drm_edid *edid; const struct edid *raw; - struct dcp_display_mode modes[2] = {}; + struct dcp_display_mode *modes = kunit_kcalloc(test, 2, sizeof(*modes), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, modes); modes[0].mode = (struct drm_display_mode) { .clock = 540005, .hdisplay = 3456, .hsync_start = 3500, .hsync_end = 3550, .htotal = 4000, .vdisplay = 2160, @@ -1457,7 +1458,7 @@ static void parser_panel_identity(struct kunit *test) KUNIT_ASSERT_EQ(test, parse(blob->data, blob->size, &ctx), 0); KUNIT_ASSERT_EQ(test, parse_panel_metadata(&ctx, &metadata), 0); KUNIT_EXPECT_STREQ(test, metadata.name, "Synthetic Int"); - edid = dcp_panel_edid(&metadata, NULL, modes, ARRAY_SIZE(modes), 345, 223); + edid = dcp_panel_edid(&metadata, NULL, modes, 2, 345, 223); KUNIT_ASSERT_FALSE(test, IS_ERR(edid)); KUNIT_EXPECT_TRUE(test, drm_edid_valid(edid)); raw = drm_edid_raw(edid); @@ -1654,6 +1655,28 @@ static void parser_panel_adt_color_target(struct kunit *test) for (unsigned int i = 0; i < ARRAY_SIZE(srgb); i++) KUNIT_EXPECT_EQ(test, panel_color_coord(raw, i), srgb[i]); + /* + * A gamut not known here (the K114s ADT says "Rec2020") gives no + * target of its own: the panel is described as Display P3, the space + * its surfaces are tagged with, never with zero primaries. + */ + parser_adt_synthetic_matrix(matrix, 1 << 20); + size = parser_adt_color_fixture(adt, sizeof(adt), "Rec2020", sizeof("Rec2020"), + matrix, sizeof(matrix)); + panel = (struct dcp_panel_adt) {}; + KUNIT_ASSERT_EQ(test, dcp_panel_adt_parse(adt, size, &panel), 0); + KUNIT_EXPECT_EQ(test, panel.gamut, DCP_PANEL_GAMUT_UNSPECIFIED); + KUNIT_EXPECT_NULL(test, dcp_panel_gamut_color_space(panel.gamut)); + target = dcp_panel_color_target(panel.gamut); + KUNIT_EXPECT_PTR_EQ(test, target, dcp_color_space_lookup("display-p3")); + raw = panel_color_edid(test, &metadata, target); + for (unsigned int i = 0; i < ARRAY_SIZE(p3); i++) + KUNIT_EXPECT_EQ(test, panel_color_coord(raw, i), p3[i]); + KUNIT_EXPECT_EQ(test, raw->gamma, 120); + /* A known gamut keeps its own space. */ + KUNIT_EXPECT_PTR_EQ(test, dcp_panel_color_target(DCP_PANEL_GAMUT_SRGB), + dcp_color_space_lookup("srgb")); + /* Unknown, malformed, short, wrong-version, unbounded, non-neutral or singular. */ for (unsigned int fault = 0; fault < 7; fault++) { const char *name = fault == 0 ? "AdobeRGB" : "P3"; @@ -1790,6 +1813,7 @@ static void parser_panel_of_dimensions(struct kunit *test) static void parser_panel_publication(struct kunit *test, enum dcp_firmware_version fw_compat, bool desktop_state) { + const size_t adt_capacity = 512; const char *gamut = fw_compat == DCP_FIRMWARE_H17P ? "sRGB" : "P3"; struct apple_dcp *dcp = kunit_kzalloc(test, sizeof(*dcp), GFP_KERNEL); struct dcp_desktop_state *desktop = kunit_kzalloc(test, sizeof(*desktop), GFP_KERNEL); @@ -1802,7 +1826,7 @@ static void parser_panel_publication(struct kunit *test, }; struct dcp_panel_adt before = panel; __le32 matrix[10]; - u8 adt[512]; + u8 *adt = kunit_kmalloc(test, adt_capacity, GFP_KERNEL); size_t adt_size; struct device *dev = drm_kunit_helper_alloc_device(test); struct drm_device *drm; @@ -1820,11 +1844,12 @@ static void parser_panel_publication(struct kunit *test, KUNIT_ASSERT_NOT_NULL(test, id); KUNIT_ASSERT_NOT_NULL(test, pipeline); KUNIT_ASSERT_NOT_NULL(test, connector); + KUNIT_ASSERT_NOT_NULL(test, adt); ret = drmm_connector_init(drm, &connector->base, &parser_route_connector_funcs, DRM_MODE_CONNECTOR_eDP, NULL); KUNIT_ASSERT_EQ(test, ret, 0); parser_adt_synthetic_matrix(matrix, 1 << 20); - adt_size = parser_adt_color_fixture(adt, sizeof(adt), gamut, strlen(gamut) + 1, + adt_size = parser_adt_color_fixture(adt, adt_capacity, gamut, strlen(gamut) + 1, matrix, sizeof(matrix)); KUNIT_ASSERT_GT(test, adt_size, (size_t)0); ret = dcp_panel_adt_parse(adt, adt_size, &panel); @@ -1843,7 +1868,7 @@ static void parser_panel_publication(struct kunit *test, dcp->fw_compat = fw_compat; dcp->panel.width_mm = panel.width_mm; dcp->panel.height_mm = panel.height_mm; - dcp->panel.color_target = dcp_panel_gamut_color_space(panel.gamut); + dcp->panel.color_target = dcp_panel_color_target(panel.gamut); id->adt = panel.identity; dcp->connector = connector; dcp->modes = &mode; @@ -2028,12 +2053,13 @@ static void parser_desktop_metadata_timing(struct kunit *test) */ static void parser_internal_v27_only_120hz(struct kunit *test) { - struct dcp_display_mode catalog[2] = {}; + struct dcp_display_mode *catalog = kunit_kcalloc(test, 2, sizeof(*catalog), GFP_KERNEL); struct apple_dcp *dcp = kunit_kzalloc(test, sizeof(*dcp), GFP_KERNEL); struct platform_device *pipeline = kunit_kzalloc(test, sizeof(*pipeline), GFP_KERNEL); struct apple_connector *connector = kunit_kzalloc(test, sizeof(*connector), GFP_KERNEL); unsigned int i; + KUNIT_ASSERT_NOT_NULL(test, catalog); KUNIT_ASSERT_NOT_NULL(test, dcp); KUNIT_ASSERT_NOT_NULL(test, pipeline); KUNIT_ASSERT_NOT_NULL(test, connector); @@ -2063,6 +2089,12 @@ static void parser_internal_v27_only_120hz(struct kunit *test) KUNIT_EXPECT_EQ(test, dcp_mode_valid(&connector->base, &catalog[0].mode), MODE_OK); KUNIT_EXPECT_EQ(test, dcp_mode_valid(&connector->base, &catalog[1].mode), MODE_BAD); + /* iBoot left the panel at 60 Hz: only the 60 Hz timing, no mode set away from it. */ + dcp->boot_rate = 60; + KUNIT_EXPECT_EQ(test, dcp_mode_valid(&connector->base, &catalog[0].mode), MODE_BAD); + KUNIT_EXPECT_EQ(test, dcp_mode_valid(&connector->base, &catalog[1].mode), MODE_OK); + dcp->boot_rate = 0; + /* The T8142 Air internal DCP (60 Hz panel, firmware 27.0) and the T6050 dcpext keep every mode. */ dcp->hw.only_120hz_modes = false; KUNIT_EXPECT_EQ(test, dcp_mode_valid(&connector->base, &catalog[0].mode), MODE_OK); @@ -2072,6 +2104,268 @@ static void parser_internal_v27_only_120hz(struct kunit *test) dcp_modes_release(dcp); } +struct parser_unsafe_timing { + s64 id, score; + s64 hactive, htotal, hporch, hsync; + s64 vactive, vtotal, vporch, vsync, refresh; + bool preferred, unsafe, dsc, second; +}; + +static void blob_color_ids(struct parser_blob *blob, const char *key, bool listed) +{ + blob_key(blob, key); + blob_tag(blob, 2, listed); + if (listed) { + blob_tag(blob, 4, 0); + put_unaligned_le64(80, blob->data + blob->size); + blob->size += 8; + } +} + +/* + * A timing as a desktop dcpext lists it for a monitor behind a DP to HDMI + * converter: one RGB element (ID 80), which UnsafeColorElementIDs and + * DSCRequiredColorElementIDs may list, and optionally a second (ID 81) that + * neither does. + */ +static void blob_unsafe_timing(struct parser_blob *blob, + const struct parser_unsafe_timing *t) +{ + blob_tag(blob, 1, 10); + blob_bool(blob, "IsVirtual", false); + blob_int(blob, "ID", t->id); + blob_int(blob, "Score", t->score); + blob_timing_dimension(blob, "HorizontalAttributes", t->hactive, t->htotal, + t->hporch, t->hsync, + ((u64)t->vtotal * t->refresh << 16) / 1000); + blob_timing_dimension(blob, "VerticalAttributes", t->vactive, t->vtotal, + t->vporch, t->vsync, t->refresh << 16); + blob_color_ids(blob, "UnsafeColorElementIDs", t->unsafe); + blob_color_ids(blob, "DSCRequiredColorElementIDs", t->dsc); + blob_key(blob, "ColorModes"); + blob_tag(blob, 2, 1 + t->second); + blob_color(blob, 80, 242999, 0, DCP_COLOR_FORMAT_RGB); + if (t->second) + blob_color(blob, 81, 242998, 0, DCP_COLOR_FORMAT_RGB); + blob_bool(blob, "IsPreferred", t->preferred); + blob_bool(blob, "IsInterlaced", false); +} + +static struct dcp_display_mode * +parser_unsafe_modes(struct kunit *test, struct parser_blob *blob, + const struct parser_unsafe_timing *timings, unsigned int n, + bool external_sdr, unsigned int *count) +{ + struct dcp_parse_ctx ctx; + unsigned int i; + + put_unaligned_le32(0xd3, blob->data); + blob->size = 4; + blob_tag(blob, 2, n); + for (i = 0; i < n; i++) + blob_unsafe_timing(blob, &timings[i]); + if (parse(blob->data, blob->size, &ctx)) + return ERR_PTR(-EINVAL); + ctx.dcp = &parser_dcp; + return enumerate_modes(&ctx, count, 600, 340, 0, false, external_sdr); +} + +static const struct dcp_display_mode * +parser_default_mode(const struct dcp_display_mode *modes, unsigned int count) +{ + const struct dcp_display_mode *found = NULL; + unsigned int i; + + for (i = 0; i < count; i++) + if (modes[i].mode.type & DRM_MODE_TYPE_PREFERRED) { + if (found) + return NULL; + found = &modes[i]; + } + return found; +} + +/* + * A Dell S2725QS behind a USB-C to HDMI cable: firmware marks 3840x2160 at + * 60 Hz IsPreferred with the highest score, but lists its only element as + * unsafe (594 MHz is above the 340 MHz of the EDID's HDMI 1.4 block), and + * also prefers 1920x1080 at 120 Hz. macOS drives the 60 Hz timing; so must + * the default. An unsafe timing the firmware does not prefer never is. + */ +static void parser_unsafe_preferred_default(struct kunit *test) +{ + struct parser_unsafe_timing timings[] = { + { 72, 16349, 1920, 2200, 88, 44, 1080, 1125, 4, 5, 120, true, false }, + { 50, 16598, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 60, true, true }, + { 48, 15379, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 30, false, false }, + { 77, 6442, 2560, 2720, 48, 32, 1440, 1525, 3, 5, 120, false, true }, + }; + struct parser_blob *blob = kunit_kzalloc(test, sizeof(*blob), GFP_KERNEL); + const struct dcp_display_mode *def; + struct dcp_display_mode *modes; + unsigned int count, i; + + KUNIT_ASSERT_NOT_NULL(test, blob); + modes = parser_unsafe_modes(test, blob, timings, ARRAY_SIZE(timings), + false, &count); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, modes); + KUNIT_ASSERT_EQ(test, count, 4U); + for (i = 0; i < count; i++) { + KUNIT_EXPECT_EQ(test, modes[i].color_mode_id, 80); + KUNIT_EXPECT_EQ(test, modes[i].sdr_usable, !timings[i].unsafe); + KUNIT_EXPECT_EQ(test, modes[i].sdr_unsafe, timings[i].unsafe); + } + def = parser_default_mode(modes, count); + KUNIT_ASSERT_NOT_NULL(test, def); + KUNIT_EXPECT_EQ(test, def->timing_mode_id, 50); + KUNIT_EXPECT_EQ(test, def->mode.clock, 594000); + kfree(modes); + + /* Not preferred, the unsafe 60 Hz timing leaves 1920x1080 the default. */ + timings[1].preferred = false; + modes = parser_unsafe_modes(test, blob, timings, ARRAY_SIZE(timings), + false, &count); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, modes); + KUNIT_ASSERT_EQ(test, count, 4U); + def = parser_default_mode(modes, count); + KUNIT_ASSERT_NOT_NULL(test, def); + KUNIT_EXPECT_EQ(test, def->timing_mode_id, 72); + kfree(modes); +} + +/* + * A timing only DSC can carry is not an unsafe one: preferred or not, and + * whether or not its element is listed as unsafe too, it is never a default + * candidate. + */ +static void parser_unsafe_preferred_dsc(struct kunit *test) +{ + struct parser_unsafe_timing timings[] = { + { 72, 16349, 1920, 2200, 88, 44, 1080, 1125, 4, 5, 120, true, false }, + { 50, 16598, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 60, true, false, true }, + }; + struct parser_blob *blob = kunit_kzalloc(test, sizeof(*blob), GFP_KERNEL); + const struct dcp_display_mode *def; + struct dcp_display_mode *modes; + unsigned int count, pass; + + KUNIT_ASSERT_NOT_NULL(test, blob); + for (pass = 0; pass < 2; pass++) { + timings[1].unsafe = pass; + modes = parser_unsafe_modes(test, blob, timings, ARRAY_SIZE(timings), + false, &count); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, modes); + KUNIT_ASSERT_EQ(test, count, 2U); + KUNIT_EXPECT_EQ(test, modes[1].timing_mode_id, 50); + KUNIT_EXPECT_TRUE(test, modes[1].firmware_preferred); + KUNIT_EXPECT_FALSE(test, modes[1].sdr_usable); + KUNIT_EXPECT_FALSE(test, modes[1].sdr_unsafe); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_candidate(&modes[1])); + KUNIT_EXPECT_TRUE(test, dcp_mode_default_candidate(&modes[0])); + def = parser_default_mode(modes, count); + KUNIT_ASSERT_NOT_NULL(test, def); + KUNIT_EXPECT_EQ(test, def->timing_mode_id, 72); + kfree(modes); + } +} + +/* + * The external SDR path (T8140) never records an unsafe element: it drops a + * timing whose only element is unsafe, and one with a safe element besides + * is plainly usable. The same catalog elsewhere records both. + */ +static void parser_unsafe_external_sdr(struct kunit *test) +{ + struct parser_unsafe_timing timings[] = { + { 72, 16349, 1920, 2200, 88, 44, 1080, 1125, 4, 5, 120, true, false }, + { 50, 16598, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 60, true, true }, + { 48, 15379, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 30, true, true, + false, true }, + }; + struct parser_blob *blob = kunit_kzalloc(test, sizeof(*blob), GFP_KERNEL); + const struct dcp_display_mode *def; + struct dcp_display_mode *modes; + unsigned int count, i; + + KUNIT_ASSERT_NOT_NULL(test, blob); + modes = parser_unsafe_modes(test, blob, timings, ARRAY_SIZE(timings), + true, &count); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, modes); + KUNIT_ASSERT_EQ(test, count, 2U); + KUNIT_EXPECT_EQ(test, modes[0].timing_mode_id, 72); + KUNIT_EXPECT_EQ(test, modes[1].timing_mode_id, 48); + KUNIT_EXPECT_EQ(test, modes[1].color_mode_id, 81); + for (i = 0; i < count; i++) { + KUNIT_EXPECT_TRUE(test, modes[i].firmware_preferred); + KUNIT_EXPECT_TRUE(test, modes[i].sdr_usable); + KUNIT_EXPECT_FALSE(test, modes[i].sdr_unsafe); + } + def = parser_default_mode(modes, count); + KUNIT_ASSERT_NOT_NULL(test, def); + KUNIT_EXPECT_EQ(test, def->timing_mode_id, 48); + kfree(modes); + + modes = parser_unsafe_modes(test, blob, timings, ARRAY_SIZE(timings), + false, &count); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, modes); + KUNIT_ASSERT_EQ(test, count, 3U); + KUNIT_EXPECT_FALSE(test, modes[1].sdr_usable); + KUNIT_EXPECT_TRUE(test, modes[1].sdr_unsafe); + KUNIT_EXPECT_TRUE(test, modes[2].sdr_usable); + KUNIT_EXPECT_TRUE(test, modes[2].sdr_unsafe); + kfree(modes); +} + +/* + * Two timings of the native resolution, both IsPreferred: the one with a + * usable SDR element is the default, whatever the refresh rate of the unsafe + * one, since nothing falls back to it when the unsafe timing fails. The + * unsafe timing is then out of the ranking altogether, as it was before it + * could be a candidate. + */ +static void parser_unsafe_preferred_usable_wins(struct kunit *test) +{ + struct parser_unsafe_timing timings[] = { + { 72, 16349, 1920, 2200, 88, 44, 1080, 1125, 4, 5, 120, true, false }, + { 50, 16598, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 60, true, true }, + { 48, 15379, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 30, true, false }, + { 46, 15000, 3840, 5500, 1276, 88, 2160, 2250, 8, 10, 24, false, false }, + }; + static const struct { + bool preferred_30, preferred_24; + s64 expect; + } cases[] = { + /* Usable and preferred at 30 Hz beats unsafe and preferred at 60 Hz. */ + { true, false, 48 }, + /* No usable timing is preferred: the Dell S2725QS case, 60 Hz. */ + { false, false, 50 }, + /* + * Only the 24 Hz one is: the unsafe timing is out, and the + * usable ones rank as ever, the higher refresh rate first. + */ + { false, true, 48 }, + }; + struct parser_blob *blob = kunit_kzalloc(test, sizeof(*blob), GFP_KERNEL); + const struct dcp_display_mode *def; + struct dcp_display_mode *modes; + unsigned int count, i; + + KUNIT_ASSERT_NOT_NULL(test, blob); + for (i = 0; i < ARRAY_SIZE(cases); i++) { + timings[2].preferred = cases[i].preferred_30; + timings[3].preferred = cases[i].preferred_24; + modes = parser_unsafe_modes(test, blob, timings, ARRAY_SIZE(timings), + false, &count); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, modes); + KUNIT_ASSERT_EQ(test, count, 4U); + KUNIT_EXPECT_TRUE(test, dcp_mode_default_candidate(&modes[1])); + def = parser_default_mode(modes, count); + KUNIT_ASSERT_NOT_NULL(test, def); + KUNIT_EXPECT_EQ(test, def->timing_mode_id, cases[i].expect); + kfree(modes); + } +} + static struct kunit_case parser_cases[] = { KUNIT_CASE(parser_internal_v27_only_120hz), KUNIT_CASE(parser_panel_of_dimensions), @@ -2116,6 +2410,10 @@ static struct kunit_case parser_cases[] = { KUNIT_CASE(parser_catalog_release), KUNIT_CASE(parser_property_bounds), KUNIT_CASE(parser_desktop_metadata_timing), + KUNIT_CASE(parser_unsafe_preferred_default), + KUNIT_CASE(parser_unsafe_preferred_dsc), + KUNIT_CASE(parser_unsafe_external_sdr), + KUNIT_CASE(parser_unsafe_preferred_usable_wins), {} }; diff --git a/drivers/gpu/drm/apple/parser.c b/drivers/gpu/drm/apple/parser.c index 8538b0cb5aa0e7..35a8c2bf25de96 100644 --- a/drivers/gpu/drm/apple/parser.c +++ b/drivers/gpu/drm/apple/parser.c @@ -390,9 +390,9 @@ static int parse_dimension(struct dcp_parse_ctx *handle, struct dimension *dim, else ret = parse_int_bound(it.handle, &dim->pixel_repetition, 0, U32_MAX); - } - else + } else { ret = skip(it.handle); + } if (!IS_ERR_OR_NULL(key)) kfree(key); @@ -571,23 +571,45 @@ static int parse_timing_color_restrictions(struct dcp_parse_ctx *handle, return 0; } +static u8 color_wire_bpp(enum dcp_color_format fmt, u8 depth) +{ + if (fmt == DCP_COLOR_FORMAT_YCBCR420) + return (depth * 3) / 2; + if (fmt == DCP_COLOR_FORMAT_YCBCR422 || + fmt == DCP_COLOR_FORMAT_YCBCR422_DP || + fmt == DCP_COLOR_FORMAT_YCBCR422_HDMI) + return depth * 2; + return depth * 3; +} + /* * An HDR output scans out through a PQ BT.2020 element. Prefer RGB, which * needs no conversion, then 10 bits per component, which is what an HDR * framebuffer carries; a timing without link bandwidth for PQ RGB may still * offer YCbCr 4:4:4, which the processor converts the RGB surfaces to. */ -static unsigned int pq_mode_rank(const struct color_mode *cmode) +static unsigned int pq_mode_rank(const struct color_mode *cmode, + bool downstream_420) { + enum dcp_color_format fmt = downstream_420 ? + DCP_COLOR_FORMAT_YCBCR420 : cmode->pixel_encoding; unsigned int rank; if (cmode->eotf != DCP_EOTF_ST_2084) return 0; - if (cmode->pixel_encoding == DCP_COLOR_FORMAT_RGB && + if (fmt == DCP_COLOR_FORMAT_RGB && cmode->colorimetry == DCP_COLORIMETRY_BT2020_RGB && cmode->dynamic_range == DCP_COLOR_YCBCR_RANGE_FULL) + rank = 7; + else if (fmt == DCP_COLOR_FORMAT_YCBCR444 && + cmode->colorimetry == DCP_COLORIMETRY_BT2020_YCC) + rank = 5; + else if ((fmt == DCP_COLOR_FORMAT_YCBCR422 || + fmt == DCP_COLOR_FORMAT_YCBCR422_DP || + fmt == DCP_COLOR_FORMAT_YCBCR422_HDMI) && + cmode->colorimetry == DCP_COLORIMETRY_BT2020_YCC) rank = 3; - else if (cmode->pixel_encoding == DCP_COLOR_FORMAT_YCBCR444 && + else if (fmt == DCP_COLOR_FORMAT_YCBCR420 && cmode->colorimetry == DCP_COLORIMETRY_BT2020_YCC) rank = 1; else @@ -595,33 +617,114 @@ static unsigned int pq_mode_rank(const struct color_mode *cmode) return rank + (cmode->depth == 10); } -/* A PQ element that needs DSC ranks below every one that does not. */ -#define PQ_RANK_NO_DSC 4 +static void record_color_entry(struct dcp_display_mode *out, + s64 *scores, + const struct color_mode *cmode, + const struct timing_color_restrictions *limits, + bool limits_known, bool downstream_420) +{ + struct dcp_color_entry entry = {}; + unsigned int pos, end; + + static_assert(DCP_EOTF_COUNT <= 8); + static_assert(DCP_COLOR_FORMAT_COUNT <= 16); + static_assert(DCP_COLOR_YCBCR_RANGE_COUNT <= 2); + static_assert(DCP_COLORIMETRY_COUNT <= 32); + + if (cmode->colorimetry < 0 || cmode->colorimetry >= DCP_COLORIMETRY_COUNT || + cmode->depth < 8 || cmode->depth > 12 || + cmode->dynamic_range < 0 || cmode->dynamic_range >= DCP_COLOR_YCBCR_RANGE_COUNT || + cmode->eotf < 0 || cmode->eotf >= DCP_EOTF_COUNT || + cmode->pixel_encoding < 0 || cmode->pixel_encoding >= DCP_COLOR_FORMAT_COUNT) + return; + + entry.id = cmode->id; + entry.eotf = cmode->eotf; + entry.format = cmode->pixel_encoding; + entry.range = cmode->dynamic_range; + entry.colorimetry = cmode->colorimetry; + entry.depth = cmode->depth; + if (downstream_420) + entry.flags |= DCP_COLOR_FLAG_DOWNSTREAM_420; + if (limits_known) { + if (timing_color_contains(&limits->unsafe, cmode->id)) + entry.flags |= DCP_COLOR_FLAG_UNSAFE; + if (timing_color_contains(&limits->dsc_required, cmode->id)) + entry.flags |= DCP_COLOR_FLAG_DSC; + } + + pos = out->nr_colors; + while (pos > 0 && scores[pos - 1] < cmode->score) + pos--; + if (pos >= DCP_MAX_COLOR_ENTRIES) + return; + end = out->nr_colors < DCP_MAX_COLOR_ENTRIES ? out->nr_colors : DCP_MAX_COLOR_ENTRIES - 1; + if (end > pos) { + memmove(&out->colors[pos + 1], &out->colors[pos], + (end - pos) * sizeof(out->colors[0])); + memmove(&scores[pos + 1], &scores[pos], + (end - pos) * sizeof(scores[0])); + } + out->colors[pos] = entry; + scores[pos] = cmode->score; + if (out->nr_colors < DCP_MAX_COLOR_ENTRIES) + out->nr_colors++; +} /* - * @dsc: firmware 27, whose processor compresses an element the timing lists - * as needing DSC itself, as for SDR: such a PQ element is usable too. + * @dsc: the modeset delegates compression of DSC-required elements to DCP. */ static void collect_pq_mode(struct dcp_color_mode *pq, unsigned int *best_rank, struct color_mode *cmode, - const struct timing_color_restrictions *limits, bool dsc) + const struct timing_color_restrictions *limits, + bool dsc, bool downstream_420) { - unsigned int rank = pq_mode_rank(cmode); + unsigned int rank = pq_mode_rank(cmode, downstream_420); + bool needs_dsc = timing_color_contains(&limits->dsc_required, cmode->id); - if (!rank || timing_color_contains(&limits->unsafe, cmode->id)) - return; - if (!timing_color_contains(&limits->dsc_required, cmode->id)) - rank += PQ_RANK_NO_DSC; - else if (!dsc) + if (!rank || (needs_dsc && !dsc) || + timing_color_contains(&limits->unsafe, cmode->id)) return; + + /* Break equal format and depth ranks in favour of no compression. */ + rank = 2 * rank + !needs_dsc; if (rank < *best_rank) return; if (rank > *best_rank) pq->score = -1; - fill_color_mode(pq, cmode); + if (!fill_color_mode(pq, cmode) && downstream_420 && pq->id == cmode->id) + pq->format = DCP_COLOR_FORMAT_YCBCR420; *best_rank = rank; } +static int parse_downstream_pixel_encoding(struct dcp_parse_ctx *handle, + s64 *encoding) +{ + struct iterator it; + int ret; + + *encoding = -1; + ret = iterator_begin(handle, &it, true); + if (ret) + return ret; + + for (; it.idx < it.len; ++it.idx) { + char *key = parse_string(it.handle); + + if (IS_ERR(key)) + return PTR_ERR(key); + if (!strcmp(key, "PixelEncoding")) + ret = parse_int(it.handle, encoding); + else + ret = skip(it.handle); + kfree(key); + if (ret) + return ret; + } + + return 0; +} + static int parse_color_modes(struct dcp_parse_ctx *handle, struct dcp_display_mode *out, bool external_sdr, const struct timing_color_restrictions *limits, @@ -630,26 +733,37 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, { struct iterator outer_it; struct dcp_color_mode bootstrap = { .score = -1 }; + s64 *color_scores; unsigned int best_sdr_rank = 0, best_unsafe_rank = 0, best_pq_rank = 0; - unsigned int best_rgb_rank = 0; + unsigned int best_unsafe_pq_rank = 0, best_rgb_rank = 0; int ret = 0; + out->sdr_444.score = -1; out->sdr_rgb.score = -1; out->sdr.score = -1; out->best.score = -1; out->pq.score = -1; + out->nr_colors = 0; + out->sdr_unsafe_max_bpp = 0; out->sdr_usable = false; + out->sdr_unsafe = false; out->has_bootstrap = false; ret = iterator_begin(handle, &outer_it, false); if (ret) return ret; + color_scores = kcalloc(DCP_MAX_COLOR_ENTRIES, sizeof(*color_scores), + GFP_KERNEL); + if (!color_scores) + return -ENOMEM; + for (; outer_it.idx < outer_it.len; ++outer_it.idx) { struct iterator it; static const char * const fields[] = { "Colorimetry", "Depth", "DynamicRange", "EOTF", "ID", "PixelEncoding", "Score", "IsVirtual" }; unsigned int seen = 0; - bool is_virtual = true; + bool is_virtual = true, downstream_420; + s64 downstream_encoding = -1; struct color_mode cmode = { .colorimetry = -1, .depth = -1, @@ -662,7 +776,7 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, ret = iterator_begin(handle, &it, true); if (ret) - return ret; + goto out_free; for (; it.idx < it.len; ++it.idx) { char *key = parse_string(it.handle); @@ -681,6 +795,9 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, ret = parse_int(it.handle, &cmode.colorimetry); else if (!strcmp(key, "Depth")) ret = parse_int(it.handle, &cmode.depth); + else if (!strcmp(key, "DownstreamFormat")) + ret = parse_downstream_pixel_encoding(it.handle, + &downstream_encoding); else if (!strcmp(key, "DynamicRange")) ret = parse_int(it.handle, &cmode.dynamic_range); else if (!strcmp(key, "EOTF")) @@ -700,7 +817,7 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, kfree(key); if (ret) - return ret; + goto out_free; } /* @@ -717,19 +834,43 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, cmode.id > U32_MAX) continue; + /* + * DP-to-HDMI bridges downsample 4K60 YCbCr 4:4:4/4:2:2 to + * YCbCr 4:2:0 on the downstream link. Preserve cmode.pixel_encoding + * as the upstream encoding and flag the downstream wire format. + */ + downstream_420 = downstream_encoding == DCP_COLOR_FORMAT_YCBCR420; + trace_iomfb_color_mode(handle->dcp, cmode.id, cmode.score, cmode.depth, cmode.colorimetry, cmode.eotf, cmode.dynamic_range, cmode.pixel_encoding); + record_color_entry(out, color_scores, &cmode, limits, + limits_known, downstream_420); if (limits_known) collect_pq_mode(&out->pq, &best_pq_rank, &cmode, limits, - handle->pq_dsc); + handle->pq_dsc, downstream_420); if (cmode.eotf == DCP_EOTF_SDR_GAMMA && (!limits_known || (!timing_color_contains(&limits->unsafe, cmode.id) && - !timing_color_contains(&limits->dsc_required, cmode.id)))) + !timing_color_contains(&limits->dsc_required, cmode.id)))) { out->sdr_usable = true; + } else if (!external_sdr && cmode.eotf == DCP_EOTF_SDR_GAMMA && + !timing_color_contains(&limits->dsc_required, cmode.id)) { + out->sdr_unsafe = true; + if (cmode.depth >= 8 && cmode.depth <= 12 && + cmode.pixel_encoding >= 0 && + cmode.pixel_encoding < DCP_COLOR_FORMAT_COUNT) { + enum dcp_color_format wire_fmt = downstream_420 ? + DCP_COLOR_FORMAT_YCBCR420 : + cmode.pixel_encoding; + u8 bpp = color_wire_bpp(wire_fmt, cmode.depth); + + if (bpp > out->sdr_unsafe_max_bpp) + out->sdr_unsafe_max_bpp = bpp; + } + } if (external_sdr) { unsigned int rank; @@ -786,7 +927,58 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, fill_color_mode(&out->best, &cmode); } - return 0; + /* + * Timings above HDMI 1.4's 340 MHz clock behind DP-to-HDMI 2.0 bridges + * list every element in UnsafeColorElementIDs even though SDR already + * drives them through those unsafe elements. DCP firmware omits + * over-budget non-DSC modes from ColorModes (e.g. 12-bit RGB on + * 1080p180 and 10/12-bit RGB on 1440p144); as an additional link-budget + * guard, bound the fallback to the wire bpp of the timing's non-DSC + * unsafe SDR elements, and keep UnsafeColorElementIDs strict whenever + * any safe SDR element exists. + */ + if (!external_sdr && limits_known && out->pq.score < 0 && + !out->sdr_usable && out->sdr_unsafe) { + unsigned int i; + + for (i = 0; i < out->nr_colors; i++) { + const struct dcp_color_entry *e = &out->colors[i]; + bool ds420 = !!(e->flags & DCP_COLOR_FLAG_DOWNSTREAM_420); + enum dcp_color_format wire_fmt = ds420 ? + DCP_COLOR_FORMAT_YCBCR420 : e->format; + struct color_mode c = { + .id = e->id, + .depth = e->depth, + .dynamic_range = e->range, + .eotf = e->eotf, + .pixel_encoding = e->format, + .colorimetry = e->colorimetry, + .score = color_scores[i], + }; + unsigned int rank; + + if (e->flags & DCP_COLOR_FLAG_DSC) + continue; + if (out->sdr_unsafe_max_bpp && + color_wire_bpp(wire_fmt, e->depth) > out->sdr_unsafe_max_bpp) + continue; + rank = pq_mode_rank(&c, ds420); + if (!rank) + continue; + rank = 2 * rank + 1; + if (rank < best_unsafe_pq_rank) + continue; + if (rank > best_unsafe_pq_rank) + out->pq.score = -1; + if (!fill_color_mode(&out->pq, &c) && ds420 && out->pq.id == e->id) + out->pq.format = DCP_COLOR_FORMAT_YCBCR420; + best_unsafe_pq_rank = rank; + } + } + +out_free: + kfree(color_scores); + return ret; } /* @@ -865,13 +1057,12 @@ static int parse_mode(struct dcp_parse_ctx *handle, bool limits_known; struct drm_display_mode *mode = &out->mode; - *out = (struct dcp_display_mode) { - .sdr_rgb.score = -1, - .sdr_444.score = -1, - .sdr.score = -1, - .best.score = -1, - .pq.score = -1, - }; + memset(out, 0, sizeof(*out)); + out->sdr_rgb.score = -1; + out->sdr_444.score = -1; + out->sdr.score = -1; + out->best.score = -1; + out->pq.score = -1; *score = -1; handle->ambiguous_180hz = false; @@ -1186,9 +1377,9 @@ static bool dcp_180hz_ids_current(struct dcp_parse_ctx handle, /* * An external display defaults to its native resolution at the highest * refresh rate it can take, as other systems pick it, rather than to the - * timing its EDID lists first. Among the timings of that resolution with a - * usable SDR element, the higher refresh rate ranks first, then IsPreferred, - * then the firmware score. + * timing its EDID lists first. Among the default candidates of that + * resolution, the higher refresh rate ranks first, then IsPreferred, then the + * firmware score. */ VISIBLE_IF_KUNIT bool dcp_mode_default_above(const struct dcp_display_mode *mode, s64 score, @@ -1206,21 +1397,54 @@ VISIBLE_IF_KUNIT bool dcp_mode_default_above(const struct dcp_display_mode *mode return score > best_score; } +/* + * A timing the default may be. Firmware lists a color element as unsafe + * when the timing needs a faster link than it can vouch for: behind a USB-C + * to HDMI cable (a Parade PS176) a Dell S2725QS gets every 3840x2160 60 Hz + * element listed, the timings above the 340 MHz of its EDID's HDMI 1.4 block + * being unsafe though its HDMI 2.x block takes 600 MHz. The firmware still + * marks that timing IsPreferred and scores it highest, and macOS drives it + * at 60 Hz (DPTimingModeId 50, an HBR2 x4 link) from the same list. So a + * timing the firmware prefers stays a candidate when its SDR elements are + * unsafe; one only DSC can carry does not, and neither does an unsafe timing + * the firmware does not prefer. dcp_external_default() still passes it over + * when the firmware also prefers a usable timing of the same resolution. + */ +VISIBLE_IF_KUNIT bool dcp_mode_default_candidate(const struct dcp_display_mode *m) +{ + if (m->automatic_rgb8_quirk) + return false; + return m->sdr_usable || (m->sdr_unsafe && m->firmware_preferred); +} + +static bool dcp_mode_same_size(const struct dcp_display_mode *a, + const struct dcp_display_mode *b) +{ + return a->mode.hdisplay == b->mode.hdisplay && + a->mode.vdisplay == b->mode.vdisplay; +} + /* * The native resolution: the largest the firmware marks IsPreferred, or the * largest of all when it marks none. + * + * Nothing falls back to another timing when the default fails to light up, + * so a timing with only unsafe SDR elements is the default only when the + * firmware prefers no usable timing of the native resolution. With one, the + * unsafe timings are left out and the usable ones rank among themselves. */ static struct dcp_display_mode *dcp_external_default(struct dcp_display_mode *modes, unsigned int count) { struct dcp_display_mode *native = NULL, *best = NULL; + bool usable_preferred = false; unsigned int i; for (i = 0; i < count; i++) { const struct dcp_display_mode *m = &modes[i]; u64 area = (u64)m->mode.hdisplay * m->mode.vdisplay; - if (m->automatic_rgb8_quirk || !m->sdr_usable) + if (!dcp_mode_default_candidate(m)) continue; if (!native || (m->firmware_preferred && !native->firmware_preferred) || @@ -1230,12 +1454,18 @@ static struct dcp_display_mode *dcp_external_default(struct dcp_display_mode *mo } if (!native) return NULL; + for (i = 0; i < count; i++) { + const struct dcp_display_mode *m = &modes[i]; + + if (dcp_mode_default_candidate(m) && dcp_mode_same_size(m, native) && + m->sdr_usable && m->firmware_preferred) + usable_preferred = true; + } for (i = 0; i < count; i++) { struct dcp_display_mode *m = &modes[i]; - if (m->automatic_rgb8_quirk || !m->sdr_usable || - m->mode.hdisplay != native->mode.hdisplay || - m->mode.vdisplay != native->mode.vdisplay) + if (!dcp_mode_default_candidate(m) || !dcp_mode_same_size(m, native) || + (usable_preferred && !m->sdr_usable)) continue; if (!best || dcp_mode_default_above(m, m->score, best, best->score)) best = m; @@ -2189,8 +2419,9 @@ static int parse_chan_layout_element(struct dcp_parse_ctx *handle, return ret; } + /* A count no u32 holds is no channel count: U32_MAX matches nothing */ if (nchans_out) - *nchans_out = nchans; + *nchans_out = nchans >= 0 && nchans <= U32_MAX ? nchans : U32_MAX; return 0; } @@ -2207,12 +2438,14 @@ static int parse_nchans_mask(struct dcp_parse_ctx *handle, unsigned int *mask) return ret; for (; it.idx < it.len; ++it.idx) { - int nchans; + unsigned int nchans; ret = parse_chan_layout_element(it.handle, &nchans, NULL); if (ret) return ret; - *mask |= 1 << nchans; + /* The firmware's count: one the mask has no bit for matches no sieve */ + if (nchans < BITS_PER_TYPE(*mask)) + *mask |= BIT(nchans); } return 0; @@ -2275,7 +2508,7 @@ static int parse_mode_in_avep_element(struct dcp_parse_ctx *handle, for (; it.idx < it.len; ++it.idx) { if (consume_string(it.handle, "AudioChannelLayoutElements")) { struct iterator inner_it; - int nchans; + unsigned int nchans; ret = iterator_begin(it.handle, &inner_it, false); if (ret) diff --git a/drivers/gpu/drm/apple/parser.h b/drivers/gpu/drm/apple/parser.h index f39ec76b9bb0bd..d7edfa8721ca59 100644 --- a/drivers/gpu/drm/apple/parser.h +++ b/drivers/gpu/drm/apple/parser.h @@ -42,8 +42,7 @@ struct dcp_parse_ctx { */ bool sdr_default_rgb; /* - * A firmware 27 processor: it compresses a PQ element the timing lists - * as needing DSC itself, so such an element is usable for PQ. + * The modeset delegates compression of DSC-required elements to DCP. */ bool pq_dsc; /* @@ -83,8 +82,8 @@ enum dcp_color_eotf { enum dcp_color_format { DCP_COLOR_FORMAT_RGB = 0, // "RGB" DCP_COLOR_FORMAT_YCBCR420 = 1, // "YUV 4:2:0" - DCP_COLOR_FORMAT_YCBCR422 = 3, // "YUV 4:2:2" - DCP_COLOR_FORMAT_YCBCR444 = 2, // "YUV 4:4:4" + DCP_COLOR_FORMAT_YCBCR422 = 2, // "YUV 4:2:2" + DCP_COLOR_FORMAT_YCBCR444 = 3, // "YUV 4:4:4" DCP_COLOR_FORMAT_DV_NATIVE = 4, // "DolbyVision (native)" DCP_COLOR_FORMAT_DV_HDMI = 5, // "DolbyVision (HDMI)" DCP_COLOR_FORMAT_YCBCR422_DP = 6, // "YCbCr 4:2:2 (DP tunnel)" @@ -136,6 +135,23 @@ struct dcp_color_mode { u8 depth; }; +#define DCP_COLOR_FLAG_UNSAFE (1U << 0) +#define DCP_COLOR_FLAG_DSC (1U << 1) +#define DCP_COLOR_FLAG_DOWNSTREAM_420 (1U << 2) +#define DCP_MAX_COLOR_ENTRIES 64 + +/* Compact colour element retained per timing, sorted by descending score. */ +struct dcp_color_entry { + u32 id; + u8 eotf : 3; + u8 format : 4; + u8 range : 1; + u8 colorimetry : 5; + u8 flags : 3; + u8 depth; + u8 pad; +}; + /* * Represents a single display mode. These mode objects are populated at * runtime based on the TimingElements dictionary sent by the DCP. @@ -163,6 +179,11 @@ struct dcp_display_mode { bool firmware_preferred; /* An SDR color element that is neither unsafe nor DSC only */ bool sdr_usable; + /* + * An SDR color element the firmware lists as unsafe, but not DSC + * only, outside the external SDR path + */ + bool sdr_unsafe; /* The firmware score of the timing */ s64 score; /* The sync polarity flags of the timing, if it reports them */ @@ -180,6 +201,11 @@ struct dcp_display_mode { /* Immutable receipt provenance; never retag a cached exception. */ struct dcp_metadata_ticket unsafe_rgb8_ticket; u64 unsafe_rgb8_service_epoch; + /* Real colour elements reported for this timing, descending by score. */ + struct dcp_color_entry colors[DCP_MAX_COLOR_ENTRIES]; + u8 nr_colors; + /* Max wire bits/pixel among non-DSC unsafe SDR elements (0 if none). */ + u8 sdr_unsafe_max_bpp; }; struct dimension { @@ -202,6 +228,7 @@ bool dcp_property_complete(const void *blob, size_t received, size_t advertised) #if IS_ENABLED(CONFIG_KUNIT) bool dcp_mode_default_above(const struct dcp_display_mode *mode, s64 score, const struct dcp_display_mode *best, s64 best_score); +bool dcp_mode_default_candidate(const struct dcp_display_mode *m); bool dcp_mode_ranks_above(bool preferred, s64 score, bool best_preferred, s64 best_score); #endif diff --git a/drivers/gpu/drm/apple/plane.c b/drivers/gpu/drm/apple/plane.c index 35b86474e8f71a..e21e626ddee883 100644 --- a/drivers/gpu/drm/apple/plane.c +++ b/drivers/gpu/drm/apple/plane.c @@ -496,13 +496,13 @@ static void apple_plane_atomic_update(struct drm_plane *plane, } /* - * DCP doesn't support XBGR8 / XRGB8 / XBGR2101010 natively. Blending as + * DCP doesn't support XBGR8 / XRGB8 / XRGB2101010 natively. Blending as * pre-multiplied alpha with a black background can be used as * workaround for the bottommost plane. */ if (fmt->format == DRM_FORMAT_XRGB8888 || fmt->format == DRM_FORMAT_XBGR8888 || - fmt->format == DRM_FORMAT_XBGR2101010 || + fmt->format == DRM_FORMAT_XRGB2101010 || base->pixel_blend_mode == DRM_MODE_BLEND_PREMULTI) is_premultiplied = true; @@ -655,7 +655,7 @@ static const struct drm_plane_helper_funcs apple_plane_helper_funcs = { // Duplicate drm_atomic_helper_plane_reset but allocate struct apple_plane_state static void apple_plane_reset(struct drm_plane *plane) { - struct apple_plane_state *state = to_apple_plane_state(plane->state); + struct apple_plane_state *state = to_apple_plane_state(plane->state); if (state) { apple_plane_cleanup_fb(plane, &state->base); __drm_atomic_helper_plane_destroy_state(&state->base); @@ -671,17 +671,17 @@ static void apple_plane_reset(struct drm_plane *plane) static struct drm_plane_state * apple_plane_duplicate_state(struct drm_plane *plane) { - struct apple_plane_state *apple_plane_state, *old_apple_plane_state; + struct apple_plane_state *apple_plane_state, *old_apple_plane_state; if (!plane->state) return NULL; - old_apple_plane_state = to_apple_plane_state(plane->state); - apple_plane_state = kzalloc(sizeof(*apple_plane_state), GFP_KERNEL); - if (!apple_plane_state) - return NULL; + old_apple_plane_state = to_apple_plane_state(plane->state); + apple_plane_state = kzalloc(sizeof(*apple_plane_state), GFP_KERNEL); + if (!apple_plane_state) + return NULL; - __drm_atomic_helper_plane_duplicate_state(plane, &apple_plane_state->base); + __drm_atomic_helper_plane_duplicate_state(plane, &apple_plane_state->base); apple_plane_state->surf = old_apple_plane_state->surf; apple_plane_state->src_rect = old_apple_plane_state->src_rect; diff --git a/drivers/gpu/drm/apple/t8132_ext_drm.c b/drivers/gpu/drm/apple/t8132_ext_drm.c index 9e21dfee0ada1c..8bcb7da6c9001a 100644 --- a/drivers/gpu/drm/apple/t8132_ext_drm.c +++ b/drivers/gpu/drm/apple/t8132_ext_drm.c @@ -111,19 +111,19 @@ static DEFINE_SPINLOCK(t8132_ext_lock); /* Registered outputs, for t8132_ext_drm_hotplug() (t8132_ext_lock) */ static struct t8132_ext_out *t8132_ext_live[T8132_EXT_MAX]; /* - * Every output initialised, for the layer's one PM notifier, all of one DRM - * device (t8132_ext_pm_drm, the first to init; a second one's outputs get no - * sleep handling): set up by its t8132_ext_drm_init(), the notifier registered - * after them; its t8132_ext_drm_fini() unregisters it before anything is torn - * down. All under t8132_ext_reg_lock, which the notifier holds throughout: - * outermost, before any modeset lock, and never held to (un)register the - * notifier. + * Every output initialised, for the sleep handling (t8132_ext_drm_pm_event(), + * called from appledrm's one PM notifier, registered at module init), all of + * one DRM device (t8132_ext_pm_drm, the first to init; a second one's outputs + * get no sleep handling): set up by its t8132_ext_drm_init(), emptied by its + * t8132_ext_drm_fini() before anything is torn down. All under + * t8132_ext_reg_lock, which the sleep handling holds throughout, so a call + * under way finishes before fini empties the registry: outermost, before any + * modeset lock. */ static DEFINE_MUTEX(t8132_ext_reg_lock); static struct drm_device *t8132_ext_pm_drm; static struct t8132_ext_out *t8132_ext_outs[T8132_EXT_MAX]; static unsigned int t8132_ext_nouts; -static bool t8132_ext_pm_registered; static const u32 t8132_ext_formats[] = { DRM_FORMAT_XRGB8888, @@ -919,7 +919,7 @@ static void t8132_ext_relink_end(struct t8132_ext_out *out) * display DART and a frame shown, iomfb_m4_ext_restore_result()) sets the * connector's link status BAD and sends a hotplug event: the compositor has * to set the mode again. A display released for the sleep was waited for - * before (t8132_ext_pm_notify()); its connector's hold ends here, and the + * before (t8132_ext_drm_pm_event()); its connector's hold ends here, and the * hotplug held meanwhile goes out at the end. */ static void t8132_ext_sleep_restore(struct t8132_ext_out *out) @@ -1012,11 +1012,12 @@ static void t8132_ext_sleep_end(struct t8132_ext_out *out) } /* - * The layer's one PM notifier, for every output. A refused sleep gets - * no PM_POST_SUSPEND here (the chain rolls back only the notifiers before - * this one): the outputs already prepared come back at once. + * The layer's sleep handling, for every output, called from appledrm's PM + * notifier (apple_drm_pm_notify()). A sleep this refuses gets no + * PM_POST_SUSPEND here, since the chain rolls back only the notifiers before + * appledrm's: the outputs already prepared come back at once. */ -static int t8132_ext_pm_notify(struct notifier_block *nb, unsigned long event, void *unused) +int t8132_ext_drm_pm_event(unsigned long event) { unsigned long deadline; unsigned int i; @@ -1046,14 +1047,10 @@ static int t8132_ext_pm_notify(struct notifier_block *nb, unsigned long event, v return NOTIFY_DONE; } -static struct notifier_block t8132_ext_pm_nb = { - .notifier_call = t8132_ext_pm_notify, -}; - /* * First in the DRM device's unbind (and its probe's failure paths), - * before drm_dev_unregister() and any DRM object is torn down: the PM - * notifier unregistered (a call of it under way finishes first), then every + * before drm_dev_unregister() and any DRM object is torn down: the registry + * emptied for the sleep handling (a call of it under way finishes first), then every * output dying, its work cancelled, and one left in a sleep (no * PM_POST_SUSPEND will come) out of it, its connector's hold ended. Only for * the DRM device whose outputs these are; called again, nothing. @@ -1063,19 +1060,15 @@ void t8132_ext_drm_fini(struct drm_device *drm) struct t8132_ext_out *outs[T8132_EXT_MAX]; unsigned int n = 0; unsigned long flags; - bool mine, reg; + bool mine; + /* A sleep-handling call under way holds the registry lock: it finishes first. */ mutex_lock(&t8132_ext_reg_lock); mine = drm && t8132_ext_pm_drm == drm; - reg = mine && t8132_ext_pm_registered; - mutex_unlock(&t8132_ext_reg_lock); - if (!mine) + if (!mine) { + mutex_unlock(&t8132_ext_reg_lock); return; - /* Not under the registry lock: a call under way holds it. */ - if (reg) - unregister_pm_notifier(&t8132_ext_pm_nb); - mutex_lock(&t8132_ext_reg_lock); - t8132_ext_pm_registered = false; + } for (n = 0; n < t8132_ext_nouts; n++) { outs[n] = t8132_ext_outs[n]; t8132_ext_outs[n] = NULL; @@ -1195,7 +1188,7 @@ int t8132_ext_drm_init(struct drm_device *drm) struct device_node *np; unsigned int count = 0; int err; - bool mine, reg; + bool mine; int ret = 0; if (!apple_t8132_firmware_path()) @@ -1229,18 +1222,6 @@ int t8132_ext_drm_init(struct drm_device *drm) put_device(&pdev->dev); ret = ret ?: err; } - /* - * After the outputs, not under the registry lock (see there); - * unregistered first by t8132_ext_drm_fini(). - */ - mutex_lock(&t8132_ext_reg_lock); - reg = mine && t8132_ext_nouts && !t8132_ext_pm_registered; - mutex_unlock(&t8132_ext_reg_lock); - if (reg && !register_pm_notifier(&t8132_ext_pm_nb)) { - mutex_lock(&t8132_ext_reg_lock); - t8132_ext_pm_registered = true; - mutex_unlock(&t8132_ext_reg_lock); - } if (count || ret) drm_info(drm, "%u T8132 external output(s): %d\n", count, ret); return ret; diff --git a/drivers/gpu/drm/apple/t8132_ext_drm.h b/drivers/gpu/drm/apple/t8132_ext_drm.h index df79579a5e8a55..8792ced388bda7 100644 --- a/drivers/gpu/drm/apple/t8132_ext_drm.h +++ b/drivers/gpu/drm/apple/t8132_ext_drm.h @@ -4,6 +4,7 @@ #define __APPLE_T8132_EXT_DRM_H__ #include +#include #include struct device; @@ -15,7 +16,7 @@ struct drm_atomic_commit; #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8132) int t8132_ext_drm_init(struct drm_device *drm); -/* First in the DRM device's teardown: the PM notifier and the work stopped. */ +/* First in the DRM device's teardown: the sleep handling and the work stopped. */ void t8132_ext_drm_fini(struct drm_device *drm); /* The objects of these outputs are not apple_crtc/apple_connector/apple_plane. */ bool t8132_ext_crtc(const struct drm_crtc *crtc); @@ -28,6 +29,8 @@ void t8132_ext_drm_flip_done(struct device *dcpext); /* Whether @state has one of these CRTCs, and wait for their flips. */ bool t8132_ext_drm_in_commit(struct drm_atomic_commit *state); void t8132_ext_drm_wait_flips(struct drm_atomic_commit *state); +/* System-sleep event from appledrm's PM notifier: a notifier return value. */ +int t8132_ext_drm_pm_event(unsigned long event); #else static inline int t8132_ext_drm_init(struct drm_device *drm) { return 0; } static inline void t8132_ext_drm_fini(struct drm_device *drm) { } @@ -38,6 +41,7 @@ static inline void t8132_ext_drm_hotplug(struct device *dcpext) { } static inline void t8132_ext_drm_flip_done(struct device *dcpext) { } static inline bool t8132_ext_drm_in_commit(struct drm_atomic_commit *state) { return false; } static inline void t8132_ext_drm_wait_flips(struct drm_atomic_commit *state) { } +static inline int t8132_ext_drm_pm_event(unsigned long event) { return NOTIFY_DONE; } #endif #endif diff --git a/drivers/gpu/drm/apple/t8152_atc.c b/drivers/gpu/drm/apple/t8152_atc.c new file mode 100644 index 00000000000000..4c2a5cd9ba1ba1 --- /dev/null +++ b/drivers/gpu/drm/apple/t8152_atc.c @@ -0,0 +1,978 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * T8152 (J873g) ATC PHYs as DisplayPort outputs of the DCPs' DPTX ports. + * + * Interim, until drivers/phy/apple/atc.c has a DisplayPort mode for T8152 + * and the display crossbar driver and the Type-C route layer of + * dcp-fabric.c take over the route and the choice of port: this programs + * the PHY's DisplayPort lanes, its pixel clock and the crossbar route + * itself. + * + * The bootloader trains a USB-C display before Linux starts; this takes + * that link over and then follows the firmware: link rate changes (stop and + * set up the lanes again), drive settings, the DCP -> ATCn/DFP0 crossbar + * route, and with the display off or unplugged a full power down and a cold + * start. A DCP drives one USB-C port at a time: the one it claims from the + * shared ports once their Type-C state shows a sink (t8152_typec.c). + * + * The ATC PHY driver powers the PHY: it holds the PHY's power domains while + * the port's DP PHY is on, and keeps the PHY out of USB4 meanwhile. So the DP + * PHY goes on before any PHY register access of a cold start, and off once + * the PHY is powered down, and a bootloader display's PHY stays on with it. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dptxep.h" +#include "t8152_display.h" + +#define ATC_AON 0x1e00 +#define ATC_CFG 0x60000 +#define ATC_XBAR 0x74000 +/* + * The DP clock switch at CFG + 0x14 (select), + 0x18 (enable) and + 0x1c + * (status). DP pixel clock n (1..4) runs from switch n: select field n is n + * for PMGR DP clock n - 1, 7 for none, and enable/status bit 1 + 7 * (n - 1) + * gates that PMGR clock. PCLK1 is used here, from PMGR DP0, whose divider + * atc_clock_write() sets for the link rate. + */ +#define ATC_CLKSW_SELECT (ATC_CFG + 0x14) +#define ATC_CLKSW_ENABLE (ATC_CFG + 0x18) +#define ATC_CLKSW_STATUS (ATC_CFG + 0x1c) +#define ATC_CLKSW_PCLK1_SEL GENMASK(2, 0) +#define ATC_CLKSW_PCLK1_MODE BIT(12) +#define ATC_CLKSW_PCLK1_OFF 7 +#define ATC_CLKSW_PCLK1_DP0 1 +#define ATC_CLKSW_PCLK1_EN BIT(1) +#define ATC_TIMEOUT_US 10000 + +struct t8152_atc_port { + void __iomem *base; + unsigned int index; /* ATC instance */ + /* display crossbar DFP endpoint of this ATC */ + u32 dfp; + /* AP DisplayPort AUX controller aux0 (shared), for the EDID */ + struct t8152_aux *aux; + /* PMGR power states of the ATC dependencies, read to tell if it runs */ + void __iomem *ps; + void __iomem *psd; + /* the port's DP PHY of the ATC PHY driver, which powers the PHY */ + struct phy *phy; + /* {offset, mask, value} tunables, before and after the lane setup */ + const __be32 *tunable[2]; + int tunable_len[2]; + /* This ATC's PMGR DP clock divider selects the link rate. */ + void __iomem *dp_clock; + bool swap; + bool active; + bool route_started; + u32 link_rate; + u32 lanes, next_lanes; +}; + +struct t8152_atc { + struct t8152_aux aux; + struct t8152_atc_port port[4]; + unsigned int nports; + /* the port the DCP drives, and the one a sink was found on */ + struct t8152_atc_port *cur, *next; +}; + +/* J873 has one display crossbar. Claims outlive firmware PHY power cycles. */ +static DEFINE_MUTEX(atc_owner_lock); +static struct device *atc_owner[4]; +/* The bootloader's link from the main DCP, read once: t8152_atc_boot_link(). */ +static bool atc_boot_read; +static int atc_boot_link; +/* All three DCPs borrow the same AP AUX controller for EDID reads. */ +static DEFINE_MUTEX(atc_aux_lock); + +static struct t8152_atc_port *atc_cur(struct t8152_display *disp) +{ + return ((struct t8152_atc *)disp->phy_priv)->cur; +} + +static const u32 atc_rates[] = { + LINK_RATE_RBR, LINK_RATE_HBR, LINK_RATE_HBR2, LINK_RATE_HBR3, +}; + +static bool atc_dp_pma(struct t8152_atc_port *atc, u32 pma) +{ + return atc->lanes == 4 || pma == !atc->swap; +} + +static bool atc_dp_register(struct t8152_atc_port *atc, u32 offset) +{ + if (offset >= 0x3000 && offset < 0xc000) + return atc_dp_pma(atc, 0); + if (offset >= 0xc000 && offset < 0x15000) + return atc_dp_pma(atc, 1); + return true; +} + +static void atc_update(struct t8152_atc_port *atc, u32 offset, u32 mask, u32 value) +{ + u32 reg = readl(atc->base + offset); + + writel((reg & ~mask) | value, atc->base + offset); +} + +static int atc_poll(struct t8152_atc_port *atc, u32 offset, u32 mask, u32 value) +{ + u32 reg; + + return readl_poll_timeout(atc->base + offset, reg, + (reg & mask) == value, 1, ATC_TIMEOUT_US); +} + +static int atc_route_stop(struct t8152_display *disp, struct t8152_atc_port *atc) +{ + u32 ufp = disp->dp_source * 2; + u32 mask = BIT(ufp); + + if (!atc->route_started) + return 0; + atc_update(atc, ATC_XBAR + 0x3c, mask, 0); + atc_update(atc, ATC_XBAR, mask, 0); + atc_update(atc, ATC_XBAR + 0xc, mask, 0); + atc_update(atc, ATC_XBAR + 0x24, 0x100, 0); + udelay(1); + /* + * With the pipe powered off (the bootloader hands the display over + * that way) nothing acknowledges the stop; the route is idle then, so + * finish it anyway. + */ + if (atc_poll(atc, ATC_XBAR + 0x800, mask, 0) || + atc_poll(atc, ATC_XBAR + 0x808, mask, 0) || + atc_poll(atc, ATC_XBAR + 0x81c, 0x100, 0)) + dev_info(disp->dev, "ATC%u: no crossbar stop acknowledgment\n", atc->index); + atc_update(atc, ATC_XBAR + 8, mask, 0); + atc_update(atc, ATC_XBAR + 0x20, 7 << (3 * ufp), 0); + atc_update(atc, ATC_XBAR + 0x38, 0x700, 0); + atc_update(atc, ATC_XBAR + 4, mask, mask); + atc_update(atc, ATC_XBAR + 0x1c, mask, mask); + atc_update(atc, ATC_XBAR + 0x34, 0x100, 0x100); + atc->route_started = false; + dev_dbg(disp->dev, "ATC%u: display route disabled\n", atc->index); + return 0; +} + +/* + * A source -> ATCn/DFP0 route, PCLK1: both DFP0 mux fields (0x44 bits 23:20 + * and 11:8) select the source. The upstream reset, clock and enable fields + * are indexed by DCP endpoint * 2 + DPTX port, independently of the + * downstream DFP0 fields. AUX borrowing keeps that DCP's clock path. + */ +#define ATC_SEL_AUX0 9 /* UFP endpoint 5 (aux0) + 4 */ + +static int atc_route_start_sel(struct t8152_display *disp, + struct t8152_atc_port *atc, u32 sel) +{ + u32 ufp = disp->dp_source * 2; + u32 mask = BIT(ufp); + + if (atc->route_started) + return 0; + atc_update(atc, ATC_XBAR + 0x44, 0x00f00000, sel << 20); + atc_update(atc, ATC_XBAR + 0x44, 0x00000f00, sel << 8); + atc_update(atc, ATC_XBAR + 4, mask, 0); + atc_update(atc, ATC_XBAR + 0x1c, mask, 0); + atc_update(atc, ATC_XBAR + 0x34, 0x100, 0); + udelay(1); + if (atc_poll(atc, ATC_XBAR + 0x804, mask, 0) || + atc_poll(atc, ATC_XBAR + 0x818, mask, 0) || + atc_poll(atc, ATC_XBAR + 0x82c, 0x100, 0)) { + dev_err(disp->dev, "ATC%u: crossbar reset acknowledgment timeout\n", + atc->index); + return -ETIMEDOUT; + } + atc_update(atc, ATC_XBAR + 8, mask, mask); + atc_update(atc, ATC_XBAR + 0x20, 7 << (3 * ufp), 1 << (3 * ufp)); + atc_update(atc, ATC_XBAR + 0x38, 0x700, 0x100); + atc_update(atc, ATC_XBAR + 0x48, 1, 0); + atc_update(atc, ATC_XBAR, mask, mask); + atc_update(atc, ATC_XBAR + 0xc, mask, mask); + atc_update(atc, ATC_XBAR + 0x24, 0x100, 0x100); + atc_update(atc, ATC_XBAR + 0x4c, 0x100, 0x100); + atc_update(atc, ATC_XBAR + 0x3c, mask, mask); + atc->route_started = true; + dev_dbg(disp->dev, "ATC%u: source %u to local DFP0 route configured\n", + atc->index, sel); + return 0; +} + +static int atc_route_start(struct t8152_display *disp, struct t8152_atc_port *atc) +{ + return atc_route_start_sel(disp, atc, disp->dp_source * 2); +} + +/* Common four-lane setup; the rate-dependent fields follow in atc_dp_start. */ +static const struct { + u32 offset, mask, value; +} atc_dp_setup[] = { + { 0x2044, 0xffff, 0x4b0 }, + { 0x4c, 0x3c0000, 0x3c0000 }, + { 0x4c80, 0x40, 0x40 }, + { 0xdc80, 0x40, 0x40 }, + { 0x4fd4, 0x2000000, 0x2000000 }, + { 0x4fd4, 0x1800000, 0x800000 }, + { 0xdfd4, 0x2000000, 0x2000000 }, + { 0xdfd4, 0x1800000, 0x800000 }, + { 0x4d84, 0x1c0000, 0 }, + { 0x4fd4, 1, 0 }, + { 0x4fd4, 8, 0 }, + { 0x4fd4, 2, 2 }, + { 0x4fd4, 0x10, 0x10 }, + { 0x8904, 0x1c0000, 0 }, + { 0x8800, 0x10000000, 0 }, + { 0x8800, 0x80000000, 0 }, + { 0x8800, 0x20000000, 0x20000000 }, + { 0x8804, 1, 1 }, + { 0xdd84, 0x1c0000, 0 }, + { 0xdfd4, 1, 0 }, + { 0xdfd4, 8, 0 }, + { 0xdfd4, 2, 2 }, + { 0xdfd4, 0x10, 0x10 }, + { 0x11904, 0x1c0000, 0 }, + { 0x11800, 0x10000000, 0 }, + { 0x11800, 0x80000000, 0 }, + { 0x11800, 0x20000000, 0x20000000 }, + { 0x11804, 1, 1 }, + { 0x3c04, 2, 2 }, + { 0x3c04, 1, 1 }, + { 0xcc04, 2, 2 }, + { 0xcc04, 1, 1 }, +}; + +/* Program the PMGR DP clock divider and wait for the change to settle. */ +static int atc_clock_write(struct t8152_atc_port *atc, u32 divider) +{ + u32 reg = readl(atc->dp_clock); + + writel((reg & ~0x0f000000) | (divider << 24), atc->dp_clock); + return readl_poll_timeout(atc->dp_clock, reg, !(reg & BIT(30)), 1, + ATC_TIMEOUT_US); +} + +/* Stop the DP lanes: route, pixel clock, then both PMAs. */ +static int atc_dp_stop(struct t8152_display *disp, struct t8152_atc_port *atc) +{ + u32 reg; + + atc_route_stop(disp, atc); + atc_update(atc, ATC_CLKSW_SELECT, ATC_CLKSW_PCLK1_SEL | ATC_CLKSW_PCLK1_MODE, + ATC_CLKSW_PCLK1_OFF); + atc_update(atc, ATC_CLKSW_ENABLE, ATC_CLKSW_PCLK1_EN, 0); + if (readl_poll_timeout(atc->base + ATC_CLKSW_STATUS, reg, + !(reg & ATC_CLKSW_PCLK1_EN), 1, ATC_TIMEOUT_US)) { + dev_err(disp->dev, "ATC%u: DPTX clock stop failed\n", atc->index); + return -ETIMEDOUT; + } + atc_update(atc, 0x2040, BIT(16), 0); + udelay(5); + atc_update(atc, 0x2000, BIT(15), 0); + atc_update(atc, 0x2000, BIT(13), 0); + atc_update(atc, 0x2000, BIT(14), 0); + atc_update(atc, 0x2000, BIT(2), 0); + atc_update(atc, 0x2000, BIT(3), BIT(3)); + atc_update(atc, 0xe10, BIT(2), BIT(2)); + atc_update(atc, 0xe08, BIT(29), BIT(29)); + /* Remove both PMA clock requests, then clamp and power down both lanes. */ + for (u32 offset = 0x1e18; offset <= 0x1e1c; offset += 4) { + u32 pma = (offset - 0x1e18) / 4; + + if (!atc_dp_pma(atc, pma)) + continue; + atc_update(atc, ATC_AON + 0x24, + BIT(12 + 2 * pma) | BIT(16 + 2 * pma), 0); + udelay(1); + atc_update(atc, offset, BIT(5), 0); + udelay(1); + atc_update(atc, offset, BIT(0), BIT(0)); + udelay(1); + atc_update(atc, offset, BIT(2), 0); + udelay(1); + atc_update(atc, offset, BIT(1), 0); + udelay(1); + } + atc->link_rate = 0; + return 0; +} + +/* DP lane setup at rate index r. */ +static int atc_dp_start(struct t8152_display *disp, struct t8152_atc_port *atc, u32 r) +{ + static const u32 tx_ctrl[] = { 0x4eb0, 0x8b10, 0xdeb0, 0x11b10 }; + static const u32 wake_count[] = { 0xbb5, 0xbb7, 0xbb8, 0xbb9 }; + u32 reg; + int ret; + + if (readl(atc->dp_clock) & BIT(30)) + return -EBUSY; + if (!r) { + atc_update(atc, 0xe10, BIT(2), BIT(2)); + atc_update(atc, 0xe08, BIT(29), BIT(29)); + } + for (u32 i = 0; i < 2; i++) { + u32 offset = 0x1e18 + 4 * i; + + if (!atc_dp_pma(atc, i)) + continue; + atc_update(atc, ATC_AON + 0x24, BIT(12 + 2 * i), BIT(12 + 2 * i)); + udelay(1); + atc_update(atc, ATC_AON + 0x24, BIT(16 + 2 * i), BIT(16 + 2 * i)); + udelay(1); + atc_update(atc, offset, BIT(1), BIT(1)); + udelay(1); + atc_update(atc, offset, BIT(2), BIT(2)); + udelay(1); + atc_update(atc, offset, BIT(0), 0); + udelay(1); + atc_update(atc, offset, BIT(5), BIT(5)); + udelay(2); + } + atc_update(atc, 0x2000, 0x380000, r << 19); + for (unsigned int i = 0; i < ARRAY_SIZE(atc_dp_setup); i++) + if (atc_dp_register(atc, atc_dp_setup[i].offset)) + atc_update(atc, atc_dp_setup[i].offset, atc_dp_setup[i].mask, + atc_dp_setup[i].value); + for (u32 i = 0; i < 2; i++) { + if (!atc_dp_pma(atc, i)) + continue; + atc_update(atc, 0x8684 + i * 0x9000, 3, r ? 0 : 1); + atc_update(atc, 0x4c80 + i * 0x9000, 0x30, r ? 0 : 0x10); + } + for (unsigned int i = 0; i < ARRAY_SIZE(tx_ctrl); i++) { + if (!atc_dp_register(atc, tx_ctrl[i])) + continue; + atc_update(atc, tx_ctrl[i], 0x7e07ff, 1); + atc_update(atc, tx_ctrl[i] - 0x14, 0x7f, r < 2 ? 0x65 : 0x40); + } + atc_update(atc, 0x2000, 0x70, 0x10); + atc_update(atc, 0x2000, BIT(13), BIT(13)); + atc_update(atc, 0x2044, 0xffff0000, wake_count[r] << 16); + atc_update(atc, atc->swap ? 0x89f0 : 0x119f0, BIT(14), BIT(14)); + atc_update(atc, 0x2000, BIT(2), BIT(2)); + atc_update(atc, 0x2000, BIT(3), BIT(3)); + atc_update(atc, 0x2040, BIT(16), BIT(16)); + + ret = atc_clock_write(atc, 10 - r); + if (ret) { + dev_err(disp->dev, "ATC%u: DP clock change timeout\n", atc->index); + return ret; + } + /* + * Clock the stream from PMGR DP0 at the link-rate divider just set. + * With source 0 selected instead, the pixel clock does not follow the + * divider, and every mode above about 165 MHz stays black. + */ + atc_update(atc, ATC_CLKSW_SELECT, ATC_CLKSW_PCLK1_SEL | ATC_CLKSW_PCLK1_MODE, + ATC_CLKSW_PCLK1_DP0); + atc_update(atc, ATC_CLKSW_ENABLE, ATC_CLKSW_PCLK1_EN, ATC_CLKSW_PCLK1_EN); + if (readl_poll_timeout(atc->base + ATC_CLKSW_STATUS, reg, + reg & ATC_CLKSW_PCLK1_EN, 1, ATC_TIMEOUT_US)) { + dev_err(disp->dev, "ATC%u: DP pixel clock does not start\n", atc->index); + return -ETIMEDOUT; + } + ret = atc_route_start(disp, atc); + if (ret) + return ret; + atc->link_rate = atc_rates[r]; + dev_info(disp->dev, "ATC%u: %u-lane DPTX setup at rate %#x\n", atc->index, + atc->lanes, atc->link_rate); + return 0; +} + +#define ATC_PSD_STATE 0x80 + +static void atc_apply_tunables(struct t8152_atc_port *atc, unsigned int which) +{ + const __be32 *t = atc->tunable[which]; + + for (int i = 0; i + 3 <= atc->tunable_len[which]; i += 3) + atc_update(atc, be32_to_cpu(t[i]), be32_to_cpu(t[i + 1]), + be32_to_cpu(t[i + 2])); +} + +/* Cold start: the PHY's power, the common block and AUX, then the lanes at HBR. */ +static int atc_activate(struct t8152_display *disp) +{ + struct t8152_atc_port *atc = atc_cur(disp); + void __iomem *cfg = atc->base + ATC_CFG; + u32 reg; + int ret; + + if (READ_ONCE(atc_owner[atc->index]) != disp->dev) + return -EBUSY; + if (atc->active) + return 0; + if (!atc->tunable[0] || !atc->tunable[1]) + return -EOPNOTSUPP; + /* -EBUSY while the PHY runs USB4 */ + ret = phy_power_on(atc->phy); + if (ret) { + dev_err(disp->dev, "ATC%u: PHY not powered: %d\n", atc->index, ret); + return ret; + } + if (readl(cfg) != 4 || (readl(cfg + 4) & 3) || readl(cfg + 0x30)) + goto fail; + writel(readl(cfg + 0x30) | BIT(0), cfg + 0x30); + udelay(1); + writel(readl(cfg) | BIT(0), cfg); + if (readl_poll_timeout(cfg + 4, reg, reg & BIT(0), 1, ATC_TIMEOUT_US)) + goto fail; + writel(readl(cfg) | BIT(1), cfg); + if (readl_poll_timeout(cfg + 4, reg, reg & BIT(1), 1, ATC_TIMEOUT_US)) + goto fail; + writel(readl(cfg) & ~BIT(2), cfg); + udelay(1); + writel(readl(cfg) | BIT(3), cfg); + + atc_apply_tunables(atc, 0); + /* Pin D/F keeps the other PMA out of the DP path. */ + atc_update(atc, 0x4c, 0x1f, + atc->lanes == 2 ? (atc->swap ? 0x11 : 0x10) : 0x14); + atc_update(atc, 0x4c, 0x3ffe0, + atc->lanes == 2 || atc->swap ? 0x100 : 0x22000); + atc_apply_tunables(atc, 1); + atc_update(atc, ATC_CFG + 8, BIT(1), atc->swap ? BIT(1) : 0); + writel(readl(cfg) | BIT(4), cfg); + if ((readl(cfg) & 0x1f) != 0x1b) + goto fail; + /* AUX: release small and big sleep, then the AUX clamp. */ + atc_update(atc, ATC_AON + 0x24, BIT(8), BIT(8)); + udelay(1); + atc_update(atc, ATC_AON + 0x24, BIT(6), BIT(6)); + udelay(1); + atc_update(atc, ATC_AON + 0x24, BIT(10), 0); + udelay(1); + atc->active = true; + dev_info(disp->dev, "ATC%u: common PHY and AUX up from cold\n", atc->index); + /* + * The lanes start at HBR right away. From cold, AUX only works with + * the DP PLL and PMAs running (without them the firmware reports + * DEVICE_NOT_RESPONDING); the firmware switches to its rate afterwards. + */ + return atc_dp_start(disp, atc, 1); +fail: + dev_err(disp->dev, "ATC%u: cold start failed (cfg %#x/%#x)\n", + atc->index, readl(cfg), readl(cfg + 4)); + phy_power_off(atc->phy); + return -EIO; +} + +/* Power the PHY down, its power included. */ +static int atc_deactivate(struct t8152_display *disp) +{ + struct t8152_atc_port *atc = atc_cur(disp); + void __iomem *cfg = atc->base + ATC_CFG; + int ret = 0; + u32 reg; + + if (!atc->active) + return 0; + if (atc->link_rate && atc_dp_stop(disp, atc)) { + dev_err(disp->dev, "ATC%u: DP stop failed\n", atc->index); + return -EIO; + } + atc_route_stop(disp, atc); + atc_update(atc, ATC_AON + 0x24, BIT(10), BIT(10)); + udelay(1); + atc_update(atc, ATC_AON + 0x24, BIT(6), 0); + udelay(1); + atc_update(atc, ATC_AON + 0x24, BIT(8), 0); + udelay(1); + writel(readl(cfg) & ~BIT(4), cfg); + udelay(1); + writel(readl(cfg) & ~BIT(3), cfg); + writel(readl(cfg) | BIT(2), cfg); + writel(readl(cfg) & ~BIT(1), cfg); + if (readl_poll_timeout(cfg + 4, reg, !(reg & BIT(1)), 1, ATC_TIMEOUT_US)) { + dev_err(disp->dev, "ATC%u: big-sleep entry timeout\n", atc->index); + ret = -ETIMEDOUT; + } + writel(readl(cfg) & ~BIT(0), cfg); + if (readl_poll_timeout(cfg + 4, reg, !(reg & BIT(0)), 1, ATC_TIMEOUT_US)) { + dev_err(disp->dev, "ATC%u: small-sleep entry timeout\n", atc->index); + ret = -ETIMEDOUT; + } + writel(readl(cfg + 0x30) & ~BIT(0), cfg + 0x30); + atc->active = false; + /* Then its power: the next activation starts it cold. */ + if (phy_power_off(atc->phy)) + ret = -ETIMEDOUT; + dev_info(disp->dev, "ATC%u: powered down: %d\n", atc->index, ret); + return ret; +} + +static int atc_set_link_rate(struct t8152_display *disp, u32 rate) +{ + struct t8152_atc_port *atc = atc_cur(disp); + u32 r; + int ret; + + /* The firmware drops the link (rate 0) before it retrains. */ + if (!rate || rate == atc->link_rate) + return 0; + for (r = 0; r < ARRAY_SIZE(atc_rates); r++) + if (atc_rates[r] == rate) + break; + if (r == ARRAY_SIZE(atc_rates) || !atc->active) + return -EINVAL; + dev_info(disp->dev, "ATC%u: link rate %#x, was %#x\n", atc->index, rate, + atc->link_rate); + if (atc->link_rate) { + ret = atc_dp_stop(disp, atc); + if (ret) + return ret; + } + return atc_dp_start(disp, atc, r); +} + +static int atc_set_route(struct t8152_display *disp, bool enable) +{ + struct t8152_atc_port *atc = atc_cur(disp); + + if (!enable) + return atc_route_stop(disp, atc); + if (!atc->active) + return -ENODEV; + if (atc_route_start(disp, atc)) + return -EIO; + mdelay(5); + return 0; +} + +/* + * Lane drive presets, indexed by voltage * 4 + pre-emphasis; they serve + * every link rate. + */ +static const u32 atc_drive_presets[16] = { + 0x025, 0x420, 0x717, 0x90f, 0x019, 0x397, 0x78f, 0x025, + 0x011, 0x38f, 0x025, 0x025, 0x000, 0x025, 0x025, 0x025, +}; + +static int atc_set_drive(struct t8152_display *disp, + const struct t8152_drive_settings *settings, u32 count) +{ + struct t8152_atc_port *atc = atc_cur(disp); + u32 presets[4]; + + if (!count) + return 0; + if (count > atc->lanes || !atc->active || !atc->link_rate) + return -EINVAL; + /* Validate the entire request before changing any lane. */ + for (u32 i = 0; i < count; i++) { + u32 v = le32_to_cpu(settings[i].voltage); + u32 e = le32_to_cpu(settings[i].pre_emphasis); + + if (settings[i].format || v > 3 || e > 3 || v + e > 3) + return -EINVAL; + presets[i] = atc_drive_presets[v * 4 + e]; + } + for (u32 i = 0; i < count; i++) { + u32 pma = (i / 2) ^ !atc->swap; + /* Even DP lanes use the PMA RX pair, odd lanes its TX pair. */ + u32 offset = ((i & 1) ? 0x4eb0 : 0x8b10) + pma * 0x9000; + u32 preset = presets[i]; + u32 control = 1 | (((preset >> 13) & 0x3f) << 17) | + (((preset >> 7) & 0x3f) << 5); + + atc_update(atc, offset, 0x7e07ff, control); + atc_update(atc, offset - 0x14, 0x7f, (preset & 0x3f) | 0x40); + } + return 0; +} + +static void atc_set_orientation(struct t8152_display *disp, bool flipped) +{ + struct t8152_atc_port *atc = atc_cur(disp); + + /* Applied by the next cold start; a running PHY keeps its own. */ + if (atc->active && atc->swap != flipped) + dev_warn(disp->dev, "ATC%u: orientation changed while active\n", + atc->index); + atc->swap = flipped; + atc->lanes = atc->next_lanes; +} + +static u32 atc_max_lane_count(struct t8152_display *disp) +{ + return atc_cur(disp)->lanes; +} + +/* + * The sink's EDID through the AP AUX controller aux0, which reaches the ATC + * through crossbar UFP aux0 like the DCP: the DCP's route comes down for + * the read, so this runs while the firmware does no AUX itself (display + * off, HPD not asserted yet). + */ +static int atc_read_edid(struct t8152_display *disp, u8 *buf, size_t size) +{ + struct t8152_atc_port *atc = atc_cur(disp); + bool was_started = atc->route_started; + int ret; + + if (!atc->active || !atc->aux->regs) + return -ENODEV; + mutex_lock(&atc_aux_lock); + /* The AUX output select of an ATC port: ATC instance * 3 + local DFP. */ + atc->aux->sel = atc->index * 3; + ret = t8152_aux_init(disp, atc->aux); + if (ret) + goto out; + atc_route_stop(disp, atc); + ret = atc_route_start_sel(disp, atc, ATC_SEL_AUX0); + if (!ret) + ret = t8152_aux_read_edid(disp, atc->aux, buf, size); + atc_route_stop(disp, atc); + if (was_started) + atc_route_start(disp, atc); +out: + mutex_unlock(&atc_aux_lock); + return ret; +} + +/* + * 1 with a sink on one of the ports: the current one first, then the + * others; select() switches to a port found that way. + */ +static int atc_detect(struct t8152_display *disp, bool *flipped) +{ + struct t8152_atc *atc = disp->phy_priv; + int ret = 0; + + mutex_lock(&atc_owner_lock); + atc->next = atc->cur; + /* Keep a monitor on its controller, including while userspace blanks it. */ + if (atc_owner[atc->cur->index] == disp->dev) { + ret = t8152_typec_sink(disp, atc->cur->index, flipped, + &atc->cur->next_lanes); + /* The plug changed: a new sink */ + if (ret > 0 && (atc->cur->swap != *flipped || + atc->cur->lanes != atc->cur->next_lanes)) + disp->hpd = 0; + if (ret) + goto out; + /* Unplug powers down in KMS; release on the next poll. */ + if (!atc->cur->active) + atc_owner[atc->cur->index] = NULL; + } + for (unsigned int i = 0; i < atc->nports; i++) { + struct t8152_atc_port *port = &atc->port[i]; + + if (atc_owner[port->index] || + t8152_typec_sink(disp, port->index, flipped, &port->next_lanes) <= 0) + continue; + atc_owner[port->index] = disp->dev; + atc->next = port; + disp->hpd = 0; + ret = 1; + break; + } +out: + mutex_unlock(&atc_owner_lock); + return ret; +} + +/* + * Drive the port a sink was found on: power the old one down and connect + * the DPTX port to the new one's display crossbar endpoint. + */ +static void atc_select(struct t8152_display *disp) +{ + struct t8152_atc *atc = disp->phy_priv; + struct t8152_atc_port *port = atc->next; + + if (!port || port == atc->cur) + return; + if (atc->cur->active && atc_deactivate(disp)) + return; + mutex_lock(&atc_owner_lock); + if (atc_owner[atc->cur->index] == disp->dev) + atc_owner[atc->cur->index] = NULL; + mutex_unlock(&atc_owner_lock); + dev_info(disp->dev, "USB-C display on ATC%u now, was ATC%u\n", + port->index, atc->cur->index); + atc->cur = port; + disp->dcp_output = port->dfp; +} + +/* + * Before the DCP drives another PHY (the HDMI port): give up the claim on a + * port that is powered down. False while the current port is still up. + */ +bool t8152_atc_release(struct t8152_display *disp) +{ + struct t8152_atc_port *atc = atc_cur(disp); + + if (atc->active) + return false; + guard(mutex)(&atc_owner_lock); + if (atc_owner[atc->index] == disp->dev) + atc_owner[atc->index] = NULL; + return true; +} + +static const struct t8152_phy_ops atc_ops = { + .activate = atc_activate, + .deactivate = atc_deactivate, + .set_link_rate = atc_set_link_rate, + .max_lane_count = atc_max_lane_count, + .set_drive = atc_set_drive, + .set_route = atc_set_route, + .set_orientation = atc_set_orientation, + .read_edid = atc_read_edid, + .detect = atc_detect, + .select = atc_select, + .max_link_rate = LINK_RATE_HBR2, +}; + +/* PMGR registers, inside blocks their power domain driver has claimed. */ +static void __iomem *atc_map(struct t8152_display *disp, struct device_node *np, + const char *name) +{ + int i = of_property_match_string(np, "reg-names", name); + struct resource res; + + if (i < 0 || of_address_to_resource(np, i, &res)) + return NULL; + return devm_ioremap(disp->dev, res.start, resource_size(&res)); +} + +/* + * The PHY block hangs the bus while it is power-gated: look at it only with + * its DP dependencies and the common PSD up. + */ +static bool atc_powered(void __iomem *ps, void __iomem *psd) +{ + return (readl(ps) & 0xf0) == 0xf0 && !(readl(psd + ATC_PSD_STATE) & 7); +} + +/* The crossbar routes the port from the DCP with this dp-source. */ +static bool atc_routed(void __iomem *base, u32 dp_source) +{ + return ((readl(base + ATC_XBAR + 0x44) >> 20) & 0xf) == dp_source * 2; +} + +/* Common block out of reset and AUX up, as the bootloader leaves a link. */ +static bool atc_link_up(u32 cfg) +{ + return (cfg & 0x1f) == 0x1b; +} + +static int atc_port_init(struct t8152_display *disp, struct t8152_atc *atc, + struct device_node *np, void __iomem *dp_clock) +{ + struct t8152_atc_port *port = &atc->port[atc->nports]; + u32 cfg, r; + + port->base = atc_map(disp, np, "atc"); + port->ps = atc_map(disp, np, "atc-ps"); + port->psd = atc_map(disp, np, "atc-psd"); + if (!port->base || !port->ps || !port->psd) + return -ENOMEM; + port->phy = devm_of_phy_optional_get(disp->dev, np, NULL); + if (IS_ERR(port->phy)) + return dev_err_probe(disp->dev, PTR_ERR(port->phy), "%pOF: no PHY\n", np); + /* The node without ports is ATC3's (J873g back-right). */ + port->dfp = 3; + of_property_read_u32(np, "apple,dfp-endpoint", &port->dfp); + port->index = port->dfp; + port->lanes = 4; + port->next_lanes = 4; + if (port->index >= 4) + return -EINVAL; + port->dp_clock = dp_clock + port->index * 8; + port->aux = &atc->aux; + port->tunable[0] = of_get_property(np, "apple,tunable-pre", + &port->tunable_len[0]); + port->tunable[1] = of_get_property(np, "apple,tunable-post", + &port->tunable_len[1]); + port->tunable_len[0] /= sizeof(__be32); + port->tunable_len[1] /= sizeof(__be32); + atc->nports++; + + if (!atc_powered(port->ps, port->psd)) { + dev_info(disp->dev, "ATC%u: powered down\n", port->index); + return 0; + } + /* A different DCP may already be driving this port. */ + if (atc_owner[port->index] || !atc_routed(port->base, disp->dp_source)) + return 0; + cfg = readl(port->base + ATC_CFG); + port->active = atc_link_up(cfg); + /* + * The bootloader's display keeps the PHY powered through its DP PHY. The + * common block runs the same way in USB4, whose PHY refuses the DP PHY. + */ + if (port->active && phy_power_on(port->phy)) { + dev_info(disp->dev, "ATC%u: runs USB4\n", port->index); + port->active = false; + return 0; + } + if ((readl(port->base + 0x4c) & 0x1f) == 0x10 || + (readl(port->base + 0x4c) & 0x1f) == 0x11) { + port->lanes = 2; + port->next_lanes = 2; + } + port->swap = !!(readl(port->base + ATC_CFG + 8) & BIT(1)); + port->route_started = + (readl(port->base + ATC_XBAR) & BIT(disp->dp_source * 2)) && + (readl(port->base + ATC_XBAR + 0x3c) & BIT(disp->dp_source * 2)); + r = (readl(port->base + 0x2000) >> 19) & 7; + if (port->active && (readl(port->base + 0x2040) & BIT(16)) && + r < ARRAY_SIZE(atc_rates)) + port->link_rate = atc_rates[r]; + dev_info(disp->dev, + "ATC%u: inherited state: active %d, rate %#x, route %d, reversed %d (cfg %#x)\n", + port->index, port->active, port->link_rate, port->route_started, + port->swap, cfg); + return 0; +} + +static void __iomem *atc_iomap(struct device_node *np, const char *name) +{ + int i = of_property_match_string(np, "reg-names", name); + + return i < 0 ? NULL : of_iomap(np, i); +} + +/* 1 with a bootloader link from this dp-source, 0 without, or an error. */ +static int atc_port_boot_link(struct device_node *np, u32 dp_source) +{ + void __iomem *base = atc_iomap(np, "atc"); + void __iomem *ps = atc_iomap(np, "atc-ps"); + void __iomem *psd = atc_iomap(np, "atc-psd"); + int ret = -ENODEV; + + /* What atc_port_init() adopts. A port in USB4 routes from no DCP. */ + if (base && ps && psd) + ret = atc_powered(ps, psd) && atc_routed(base, dp_source) && + atc_link_up(readl(base + ATC_CFG)); + if (psd) + iounmap(psd); + if (ps) + iounmap(ps); + if (base) + iounmap(base); + return ret; +} + +/* + * 1 when the bootloader left a DisplayPort link from the main DCP + * (dp-source 0) on one of the USB-C ports, 0 when every port was read and + * none has one, an error when a port could not be read. The DCPs share the + * ports (the DCPEXTs' apple,usb-c-ports name the main DCP), so the first DCP + * to probe reads them, before any DCP claims or powers one, and the others + * get its answer. + */ +int t8152_atc_boot_link(struct device *dev) +{ + struct device_node *ports __free(device_node) = + of_parse_phandle(dev->of_node, "apple,usb-c-ports", 0); + struct device_node *np = ports ?: dev->of_node; + bool children = false; + + guard(mutex)(&atc_owner_lock); + if (atc_boot_read) + return atc_boot_link; + atc_boot_read = true; + atc_boot_link = 0; + for_each_child_of_node_scoped(np, child) { + if (!of_property_present(child, "apple,dfp-endpoint")) + continue; + children = true; + atc_boot_link = atc_port_boot_link(child, 0); + if (atc_boot_link) + break; + } + if (!children) + atc_boot_link = atc_port_boot_link(np, 0); + return atc_boot_link; +} + +int t8152_atc_init(struct t8152_display *disp) +{ + struct device_node *ports __free(device_node) = + of_parse_phandle(disp->dev->of_node, "apple,usb-c-ports", 0); + struct device_node *np = ports ?: disp->dev->of_node; + struct resource clock_res; + void __iomem *dp_clock; + struct t8152_atc *atc; + int ret; + + atc = devm_kzalloc(disp->dev, sizeof(*atc), GFP_KERNEL); + if (!atc) + return -ENOMEM; + ret = of_property_match_string(np, "reg-names", "dp-clock"); + if (ret < 0 || of_address_to_resource(np, ret, &clock_res)) + return -EINVAL; + /* Older J873 DTs describe ATC3's divider alone; each ATC has its own. */ + if (resource_size(&clock_res) == 4 && clock_res.start == 0x30002005cULL) + clock_res.start -= 3 * 8; + if (resource_size(&clock_res) < 28) + return -EINVAL; + dp_clock = devm_ioremap(disp->dev, clock_res.start, resource_size(&clock_res)); + if (!dp_clock) + return -ENOMEM; + /* Shared AUX0 is serialized by atc_aux_lock. */ + atc->aux.regs = atc_map(disp, np, "aux"); + atc->aux.ps = atc_map(disp, np, "aux-ps"); + if (!atc->aux.ps) + atc->aux.regs = NULL; + + guard(mutex)(&atc_owner_lock); + /* One child per USB-C port, or the node itself for ATC3 alone. */ + for_each_child_of_node_scoped(np, child) { + if (!of_property_present(child, "apple,dfp-endpoint")) + continue; + if (atc->nports == ARRAY_SIZE(atc->port)) + break; + ret = atc_port_init(disp, atc, child, dp_clock); + if (ret) + goto err_power; + } + if (!atc->nports) { + ret = atc_port_init(disp, atc, np, dp_clock); + if (ret) + goto err_power; + } + + /* Only adopt a bootloader route belonging to this DCP. */ + atc->cur = &atc->port[0]; + for (unsigned int i = 0; i < atc->nports; i++) { + if (atc->port[i].active) { + atc->cur = &atc->port[i]; + atc_owner[atc->cur->index] = disp->dev; + break; + } + } + atc->next = atc->cur; + disp->phy = &atc_ops; + disp->phy_priv = atc; + disp->usbc = true; + disp->dcp_output = atc->cur->dfp; + dev_info(disp->dev, "USB-C display on ATC%u (%u ports)\n", atc->cur->index, + atc->nports); + return 0; + +err_power: + /* + * A later port failed or deferred: the probe starts over, so give back + * the PHY power atc_port_init() took for an inherited link. + */ + for (unsigned int i = 0; i < atc->nports; i++) + if (atc->port[i].active) + phy_power_off(atc->port[i].phy); + return ret; +} diff --git a/drivers/gpu/drm/apple/t8152_aux.c b/drivers/gpu/drm/apple/t8152_aux.c new file mode 100644 index 00000000000000..8e2dbd2d2bd0c2 --- /dev/null +++ b/drivers/gpu/drm/apple/t8152_aux.c @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * The T8152 AP's DisplayPort AUX controllers aux0 and aux1: Analogix-derived + * DPTX cores with their own request framing. They attach to the display + * crossbar as UFP endpoints 5 and 6; the PHY code routes one to its port + * for the time of a read. Used for the sink's EDID, which the DCP firmware + * does not hand out on its iBoot interface. + * + * Interim, until the DCP's DPAV service or a DRM DP AUX channel provides the + * EDID on T8152. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "t8152_display.h" + +#define AUX_TIMEOUT_US 10000 +#define AUX_SEL 0x000 /* output: 9 crossbar UFP aux0, 0x10 lpdptx PHY */ +#define AUX_FUNC_EN_2 0x01c +#define AUX_FUNC_EN_N BIT(2) +#define AUX_HW_RETRY 0x390 +#define AUX_INT_STA 0x3dc +#define AUX_REPLY BIT(1) +#define AUX_ERROR BIT(0) +#define AUX_CH_STA 0x780 +#define AUX_DEFER_CTL 0x788 +#define AUX_RX_COMM 0x78c +#define AUX_BUF_CTL 0x790 +#define AUX_BUF_CLR BIT(9) +#define AUX_BUF_COUNT GENMASK(8, 0) +#define AUX_LEN 0x794 +#define AUX_ADDR_7_0 0x798 +#define AUX_ADDR_15_8 0x79c +#define AUX_CMD_ADDR 0x7a0 /* request in [7:4], address [19:16] */ +#define AUX_CTL 0x7a4 +#define AUX_GO BIT(0) +#define AUX_ADDR_ONLY BIT(1) +#define AUX_DATA 0xc00 /* one byte per word */ +#define AUX_MAX 16 + +#define AUX_NATIVE_WRITE 0x80 +#define AUX_I2C_WRITE 0x00 +#define AUX_I2C_READ 0x10 +#define AUX_I2C_MOT 0x40 +#define DDC_ADDR 0x50 +#define DPCD_SET_POWER 0x600 +#define DP_SET_POWER_D0 1 + +static void aux_update(void __iomem *reg, u32 mask, u32 value) +{ + writel((readl(reg) & ~mask) | value, reg); +} + +int t8152_aux_init(struct t8152_display *disp, struct t8152_aux *aux) +{ + u32 reg; + + /* PMGR power state of the controller */ + aux_update(aux->ps, 0xf, 0xf); + if (readl_poll_timeout(aux->ps, reg, ((reg >> 4) & 0xf) == 0xf, 1, + AUX_TIMEOUT_US)) { + dev_err(disp->dev, "AUX: controller does not power up\n"); + return -ETIMEDOUT; + } + writel(AUX_REPLY | AUX_ERROR, aux->regs + AUX_INT_STA); + aux_update(aux->regs + AUX_FUNC_EN_2, AUX_FUNC_EN_N, AUX_FUNC_EN_N); + usleep_range(10, 20); + aux_update(aux->regs + AUX_FUNC_EN_2, AUX_FUNC_EN_N, 0); + /* + * Bits 21:8 of AUX_HW_RETRY are a 14-bit reply timeout, not Analogix's + * three-bit expected-delay field: the value 3 let native reads pass + * but timed out the EDID through a USB-C to HDMI adapter. 3200, with + * a retry interval of 3. + */ + writel((3200 << 8) | (3 << 3), aux->regs + AUX_HW_RETRY); + writel(BIT(7) | 1, aux->regs + AUX_DEFER_CTL); + aux_update(aux->regs + AUX_SEL, 0x3f, aux->sel); + return 0; +} + +/* One AUX request of up to 16 bytes; returns the bytes transferred. */ +static int aux_xfer(struct t8152_aux *aux, u32 cmd, u32 addr, u8 *buf, + u32 len, bool write) +{ + u32 sta, n; + int i; + + for (int tries = 0; tries < 7; tries++) { + writel(AUX_BUF_CLR, aux->regs + AUX_BUF_CTL); + writel(len ? len - 1 : 0, aux->regs + AUX_LEN); + writel(addr & 0xff, aux->regs + AUX_ADDR_7_0); + writel((addr >> 8) & 0xff, aux->regs + AUX_ADDR_15_8); + writel((cmd & 0xf0) | ((addr >> 16) & 0xf), aux->regs + AUX_CMD_ADDR); + aux_update(aux->regs + AUX_CTL, AUX_ADDR_ONLY, len ? 0 : AUX_ADDR_ONLY); + for (i = 0; write && i < len; i++) + writel(buf[i], aux->regs + AUX_DATA + 4 * i); + writel(AUX_REPLY | AUX_ERROR, aux->regs + AUX_INT_STA); + aux_update(aux->regs + AUX_CTL, AUX_GO, AUX_GO); + if (readl_poll_timeout(aux->regs + AUX_INT_STA, sta, + sta & (AUX_REPLY | AUX_ERROR), 10, 20000)) + return -ETIMEDOUT; + writel(AUX_REPLY | AUX_ERROR, aux->regs + AUX_INT_STA); + if ((sta & AUX_ERROR) || (readl(aux->regs + AUX_CH_STA) & 0xf)) + return -EIO; + /* [3:2] I2C and [1:0] AUX reply: 0 ACK, 1 NACK, 2 DEFER */ + sta = readl(aux->regs + AUX_RX_COMM); + if (sta & 0x5) + return -ENXIO; + if (sta & 0xa) { + usleep_range(500, 1000); + continue; + } + if (write) + return len; + n = min(readl(aux->regs + AUX_BUF_CTL) & AUX_BUF_COUNT, len); + for (i = 0; i < n; i++) + buf[i] = readl(aux->regs + AUX_DATA + 4 * i); + return n; + } + return -EBUSY; +} + +/* DDC over I2C-over-AUX: offset 0, then 16-byte reads up to @size. */ +static int aux_ddc_read(struct t8152_aux *aux, u8 *buf, size_t size) +{ + u8 offset = 0; + size_t done = 0; + int ret; + + ret = aux_xfer(aux, AUX_I2C_WRITE | AUX_I2C_MOT, DDC_ADDR, &offset, 1, true); + while (ret >= 0 && done < size) { + ret = aux_xfer(aux, AUX_I2C_READ | AUX_I2C_MOT, DDC_ADDR, + buf + done, min_t(size_t, size - done, AUX_MAX), + false); + if (ret > 0) + done += ret; + else if (!ret) + ret = -EIO; + } + /* End the I2C transaction with an address-only read without MOT. */ + aux_xfer(aux, AUX_I2C_READ, DDC_ADDR, NULL, 0, false); + return ret < 0 ? ret : done; +} + +/* + * The EDID over DDC, the base block and its extensions; the sink answers + * AUX only some time after the path is up, and a sink just plugged in a + * little later still. + */ +int t8152_aux_read_edid(struct t8152_display *disp, struct t8152_aux *aux, + u8 *buf, size_t size) +{ + u8 d0 = DP_SET_POWER_D0; + int ret = -EIO, ext; + + for (int i = 0; i < 30 && (ret == -EIO || ret == -ETIMEDOUT); i++) { + msleep(i ? 100 : 20); + /* + * A sink left in D3 (after an unplug) NACKs DDC: wake it + * first, as the DP spec asks before AUX use. + */ + ret = aux_xfer(aux, AUX_NATIVE_WRITE, DPCD_SET_POWER, &d0, 1, true); + if (ret < 0) + continue; + usleep_range(1000, 2000); + ret = aux_ddc_read(aux, buf, min_t(size_t, size, EDID_LENGTH)); + } + if (ret != EDID_LENGTH) + return ret < 0 ? ret : -EIO; + ext = min_t(size_t, buf[0x7e], size / EDID_LENGTH - 1); + return ext ? aux_ddc_read(aux, buf, (1 + ext) * EDID_LENGTH) : ret; +} + +/* + * The controller named by np's "aux" and "aux-ps" regs (np need not be the + * DCP's own node); the PMGR register is mapped without claiming it. + */ +void t8152_aux_probe(struct t8152_display *disp, struct t8152_aux *aux, + u32 sel, struct device_node *np) +{ + int ps = of_property_match_string(np, "reg-names", "aux-ps"); + int regs = of_property_match_string(np, "reg-names", "aux"); + struct resource res; + + aux->sel = sel; + if (ps < 0 || regs < 0 || of_address_to_resource(np, ps, &res)) + return; + aux->ps = devm_ioremap(disp->dev, res.start, resource_size(&res)); + aux->regs = devm_of_iomap(disp->dev, np, regs, NULL); + if (IS_ERR(aux->regs) || !aux->ps) + aux->regs = NULL; +} diff --git a/drivers/gpu/drm/apple/t8152_display.h b/drivers/gpu/drm/apple/t8152_display.h new file mode 100644 index 00000000000000..3cdf58c8634221 --- /dev/null +++ b/drivers/gpu/drm/apple/t8152_display.h @@ -0,0 +1,142 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * The T8152 (Mac mini J873g) DisplayPort hardware behind a DCP's DPTX port + * that no subsystem driver covers yet: the ATC PHYs' DisplayPort lanes and + * their display crossbar route (t8152_atc.c), the HDMI port's dedicated + * DisplayPort PHY and PS190 converter (t8152_hdmi.c), the AP's DisplayPort + * AUX controllers that read the sink's EDID (t8152_aux.c), and the DPTX port + * service the DCP firmware calls into for the PHY (t8152_dptx.c). The rear + * USB-C ports' DisplayPort alt mode state comes from their Type-C port + * driver, through the ports' shared display switches (t8152_typec.c). + * + * Interim: the ATC DisplayPort mode moves to drivers/phy/apple/atc.c and the + * choice of port with DP alt mode to the Type-C route layer of dcp-fabric.c, + * each in its own change. Until then these files program the registers + * themselves, for the iBoot interface DCPs of iomfb_iboot.c alone. + */ +#ifndef __APPLE_T8152_DISPLAY_H__ +#define __APPLE_T8152_DISPLAY_H__ + +#include + +struct apple_dcp; +struct apple_epic_service_ops; +struct device; +struct device_node; +struct gpio_desc; +struct t8152_display; +struct t8152_hdmi; +struct t8152_typec; + +/* SET_DRIVE_SETTINGS and GET_DRIVE_SETTINGS records, one per lane */ +struct t8152_drive_settings { + __le32 format; + __le32 voltage; + __le32 pre_emphasis; +} __packed; + +/* The PHY behind the DCP's DPTX port; link rates in DPCD units. */ +struct t8152_phy_ops { + int (*activate)(struct t8152_display *disp); + int (*deactivate)(struct t8152_display *disp); + int (*set_link_rate)(struct t8152_display *disp, u32 rate); + /* optional */ + int (*set_lane_count)(struct t8152_display *disp, u32 lanes); + u32 (*max_lane_count)(struct t8152_display *disp); + int (*set_drive)(struct t8152_display *disp, + const struct t8152_drive_settings *settings, u32 count); + int (*set_route)(struct t8152_display *disp, bool enable); + /* optional: plug orientation for the next activation */ + void (*set_orientation)(struct t8152_display *disp, bool flipped); + /* optional: the sink's EDID, returns its length */ + int (*read_edid)(struct t8152_display *disp, u8 *buf, size_t size); + /* + * optional: 1 with a sink on one of the PHY's ports, 0 without; the + * port it found is taken by select() in the plug path + */ + int (*detect)(struct t8152_display *disp, bool *flipped); + void (*select)(struct t8152_display *disp); + u32 max_link_rate; +}; + +/* The DPTX port state the firmware's calls set and read back. */ +struct t8152_port { + u32 link_rate; + u32 lanes; + /* the drive settings the firmware set last, for GET_DRIVE_SETTINGS */ + struct t8152_drive_settings drive[4]; + u32 drive_count; +}; + +/* An AP DisplayPort AUX controller, and its output select */ +struct t8152_aux { + void __iomem *regs; + void __iomem *ps; + u32 sel; +}; + +/* The DisplayPort side of one DCP */ +struct t8152_display { + struct apple_dcp *dcp; + struct device *dev; + /* display crossbar UFP endpoint of the DCP; DPTX port 0 */ + u32 dp_source; + /* display crossbar DFP endpoint the DCP drives */ + u32 dcp_output; + u32 die; + + const struct t8152_phy_ops *phy; + void *phy_priv; + /* optional sink HPD line (HDMI), polled; the last level seen */ + struct gpio_desc *hpd_gpio; + int hpd; + /* USB-C: plug and HPD come from the ports' display switches */ + bool usbc; + struct t8152_typec *typec; + /* HDMI PHY: DCPEXT0's, or the main DCP's on an HDMI-only boot */ + bool hdmi; + /* + * The HDMI port of the shared ports when the bootloader brought HDMI + * up on no DCP: taken while this DCP drives no USB-C display, with + * the USB-C PHY kept to switch back. + */ + struct t8152_hdmi *hdmi_port; + bool on_hdmi; + const struct t8152_phy_ops *usbc_phy; + void *usbc_phy_priv; + u32 usbc_output; + + struct t8152_port port[2]; +}; + +/* t8152_atc.c */ +int t8152_atc_boot_link(struct device *dev); +int t8152_atc_init(struct t8152_display *disp); +bool t8152_atc_release(struct t8152_display *disp); + +/* t8152_hdmi.c */ +struct device_node *t8152_hdmi_node(void); +int t8152_hdmi_source(struct device_node *np); +int t8152_hdmi_init(struct t8152_display *disp, struct device_node *np); +int t8152_hdmi_port_init(struct t8152_display *disp, struct device_node *np); +void t8152_hdmi_port_poll(struct t8152_display *disp); + +/* t8152_aux.c */ +void t8152_aux_probe(struct t8152_display *disp, struct t8152_aux *aux, + u32 sel, struct device_node *np); +int t8152_aux_init(struct t8152_display *disp, struct t8152_aux *aux); +int t8152_aux_read_edid(struct t8152_display *disp, struct t8152_aux *aux, + u8 *buf, size_t size); + +/* t8152_typec.c, see also iomfb_iboot.h */ +int t8152_typec_init(struct t8152_display *disp); +int t8152_typec_sink(struct t8152_display *disp, u32 index, bool *flipped, + u32 *lanes); + +/* t8152_dptx.c */ +extern const struct apple_epic_service_ops t8152_dptx_port_ops; +int t8152_dptx_connect(struct t8152_display *disp, unsigned int port); +int t8152_dptx_disconnect(struct t8152_display *disp, unsigned int port); +int t8152_dptx_set_hpd(struct t8152_display *disp, unsigned int port, bool hpd); + +#endif diff --git a/drivers/gpu/drm/apple/t8152_dptx.c b/drivers/gpu/drm/apple/t8152_dptx.c new file mode 100644 index 00000000000000..14da33f3c7c3ee --- /dev/null +++ b/drivers/gpu/drm/apple/t8152_dptx.c @@ -0,0 +1,315 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * The DPTX port service of a T8152 iBoot interface DCP: the calls the + * firmware makes into the AP for the PHY behind its DPTX port, and the + * port's release and HPD calls. + * + * dptxep.c serves the same calls for the PHYs of the PHY framework, the + * display crossbar mux and Thunderbolt tunnels. The T8152 PHYs are + * programmed by t8152_atc.c and t8152_hdmi.c instead: their link rate, + * lanes and drive settings are applied here, and the drive settings are + * read back as they were set. The port's connect and display request are + * dptxep.c's. Interim, until the T8152 PHYs are PHY framework providers + * and dptxep.c can host this service. + */ + +#include +#include +#include + +#include "afk.h" +#include "dcp-internal.h" +#include "dptx-service.h" +#include "dptxep.h" +#include "t8152_display.h" + +/* IOReturn values the firmware takes as call status */ +#define KIO_RETURN_ERROR 0xe00002bcU +#define KIO_RETURN_BAD_ARG 0xe00002c2U +#define KIO_RETURN_UNSUPPORTED 0xe00002c7U +#define KIO_RETURN_NOT_READY 0xe00002d8U + +static bool dptx_needs_port(u32 command) +{ + switch (command) { + case DPTX_APCALL_ACTIVATE: + case DPTX_APCALL_DEACTIVATE: + case DPTX_APCALL_WILL_CHANGE_LINKG_CONFIG: + case DPTX_APCALL_DID_CHANGE_LINK_CONFIG: + case DPTX_APCALL_SET_LINK_RATE: + case DPTX_APCALL_SET_DOWN_SPREAD: + case DPTX_APCALL_SET_ACTIVE_LANE_COUNT: + case DPTX_APCALL_SET_DRIVE_SETTINGS: + case DPTX_APCALL_GET_LINK_RATE: + case DPTX_APCALL_GET_ACTIVE_LANE_COUNT: + case DPTX_APCALL_GET_DRIVE_SETTINGS: + return true; + default: + return false; + } +} + +/* + * One call; the IOReturn status. Requests carry their argument, replies + * their value, at offset 16. @reply holds a copy of the request. + */ +static u32 dptx_apcall(struct t8152_display *disp, struct t8152_port *port, + u16 group, u32 command, const void *data, size_t data_size, + void *reply, size_t reply_size) +{ + const struct t8152_phy_ops *phy = disp->phy; + u64 value; + u32 arg; + + if (group && !(group == 1 && (command == DPTX_APCALL_SET_DRIVE_SETTINGS || + command == DPTX_APCALL_GET_DRIVE_SETTINGS))) + return KIO_RETURN_UNSUPPORTED; + + if ((!port || !phy) && dptx_needs_port(command)) + return KIO_RETURN_NOT_READY; + + switch (command) { + case DPTX_APCALL_ACTIVATE: + if (phy->activate(disp)) + return KIO_RETURN_ERROR; + port->link_rate = LINK_RATE_HBR; + return 0; + case DPTX_APCALL_DEACTIVATE: + if (phy->deactivate(disp)) + return KIO_RETURN_ERROR; + port->link_rate = 0; + return 0; + case DPTX_APCALL_WILL_CHANGE_LINKG_CONFIG: + case DPTX_APCALL_DID_CHANGE_LINK_CONFIG: + return phy->set_route(disp, command == + DPTX_APCALL_DID_CHANGE_LINK_CONFIG) ? + KIO_RETURN_ERROR : 0; + case DPTX_APCALL_GET_MAX_LINK_RATE: + value = phy ? phy->max_link_rate : LINK_RATE_HBR; + break; + case DPTX_APCALL_GET_LINK_RATE: + value = port->link_rate; + break; + case DPTX_APCALL_SET_LINK_RATE: + if (data_size < 17) + return KIO_RETURN_BAD_ARG; + arg = ((const u8 *)data)[16]; + if (arg > phy->max_link_rate) + return KIO_RETURN_UNSUPPORTED; + if (phy->set_link_rate(disp, arg)) + return KIO_RETURN_ERROR; + port->link_rate = arg; + return 0; + case DPTX_APCALL_GET_MAX_LANE_COUNT: + value = phy && phy->max_lane_count ? phy->max_lane_count(disp) : 4; + break; + case DPTX_APCALL_GET_ACTIVE_LANE_COUNT: + value = port->lanes; + break; + case DPTX_APCALL_SET_ACTIVE_LANE_COUNT: + if (data_size < 20) + return KIO_RETURN_BAD_ARG; + arg = get_unaligned_le32(data + 16); + if (arg == 3 || arg > 4) + return KIO_RETURN_BAD_ARG; + dev_info(disp->dev, "DPTX: %u active lanes\n", arg); + if (phy->set_lane_count && phy->set_lane_count(disp, arg)) + return KIO_RETURN_ERROR; + port->lanes = arg; + return 0; + case DPTX_APCALL_GET_MAX_DRIVE_SETTINGS: { + const struct t8152_drive_settings maximum = { + 0, cpu_to_le32(3), cpu_to_le32(3) + }; + + if (reply_size < 16 + sizeof(maximum)) + return KIO_RETURN_BAD_ARG; + memcpy(reply + 16, &maximum, sizeof(maximum)); + return 0; + } + case DPTX_APCALL_SET_DRIVE_SETTINGS: { + struct t8152_drive_settings settings[4]; + + if (group != 1) + return KIO_RETURN_UNSUPPORTED; + if (data_size < 32) + return KIO_RETURN_BAD_ARG; + arg = get_unaligned_le32(data + 16); + if (arg > 4 || data_size < 32 + arg * sizeof(settings[0])) + return KIO_RETURN_BAD_ARG; + memcpy(settings, data + 32, arg * sizeof(settings[0])); + if (phy->set_drive(disp, settings, arg)) + return KIO_RETURN_ERROR; + memcpy(port->drive, settings, arg * sizeof(settings[0])); + port->drive_count = arg; + return 0; + } + case DPTX_APCALL_GET_DRIVE_SETTINGS: + /* + * The firmware reads back what it set during link training; an + * unsupported reply here was followed by a firmware crash. + * Same layout as SET: count at 16, settings from 32. + */ + if (group != 1) + return KIO_RETURN_UNSUPPORTED; + if (reply_size < 32 + port->drive_count * sizeof(port->drive[0])) + return KIO_RETURN_BAD_ARG; + put_unaligned_le32(port->drive_count, reply + 16); + memcpy(reply + 32, port->drive, + port->drive_count * sizeof(port->drive[0])); + return 0; + case DPTX_APCALL_SET_DOWN_SPREAD: + if (data_size < 17) + return KIO_RETURN_BAD_ARG; + /* The link is set up with downspread disabled. */ + return ((const u8 *)data)[16] ? KIO_RETURN_UNSUPPORTED : 0; + case DPTX_APCALL_GET_SUPPORTS_DOWN_SPREAD: + case DPTX_APCALL_GET_DOWN_SPREAD: + case DPTX_APCALL_GET_SUPPORTS_LANE_MAPPING: + case DPTX_APCALL_GET_VIRTUAL_DEVICE_MODE: + value = 0; + break; + case DPTX_APCALL_GET_SUPPORTS_HPD: + value = 1; + break; + case DPTX_APCALL_INACTIVE_SINK_DETECTED: + case DPTX_APCALL_DEVICE_NOT_RESPONDING: + case DPTX_APCALL_DEVICE_BUSY_TIMEOUT: + case DPTX_APCALL_DEVICE_NOT_STARTED: + /* Link fault reports: acknowledged with a zero status. */ + dev_info(disp->dev, "DPTX: firmware reports link fault %u\n", + command); + return 0; + case DPTX_APCALL_SET_TILED_DISPLAY_HINTS: + /* Acknowledged, the hints unused. */ + return 0; + default: + dev_info(disp->dev, "DPTX: unsupported call %u\n", command); + return KIO_RETURN_UNSUPPORTED; + } + + if (reply_size < 16 + sizeof(value)) + return KIO_RETURN_BAD_ARG; + put_unaligned_le64(value, reply + 16); + return 0; +} + +/* + * The reply starts as a copy of the request and carries the call's status + * in its first word; the transport status is always success. + */ +static int t8152_dptx_call(struct apple_epic_service *service, u16 group, + u32 command, const void *data, size_t size, + void *reply, size_t room) +{ + struct apple_dcp *dcp = service->ep->dcp; + struct dptx_port *dptx = service->cookie; + struct t8152_display *disp = READ_ONCE(dcp->t8152); + u32 status; + + dev_dbg(dcp->dev, "DPTX: port %d group %u command %u size %zu\n", + dptx ? (int)dptx->unit : -1, group, command, size); + memcpy(reply, data, min(room, size)); + if (disp) + status = dptx_apcall(disp, dptx ? &disp->port[dptx->unit] : NULL, + group, command, data, size, reply, room); + else + status = KIO_RETURN_NOT_READY; + if (status) + dev_dbg(dcp->dev, "DPTX: group %u command %u -> %#x\n", group, + command, status); + put_unaligned_le32(status, reply); + return 0; +} + +/* + * The ports in the order the firmware announces them. A further service is + * opened as well, without a port. + */ +static int t8152_dptx_prepare(struct apple_epic_service *service, + const char *name, const char *class, s64 unit) +{ + struct apple_dcp *dcp = service->ep->dcp; + + for (unsigned int i = 0; i < ARRAY_SIZE(dcp->dptxport); i++) + if (!dcp->dptxport[i].service) + return dptx_service_bind(service, &dcp->dptxport[i], i); + return 0; +} + +static void t8152_dptx_init(struct apple_epic_service *service, + const char *name, const char *class, s64 unit) +{ + if (service->cookie) + dptx_service_publish(service); +} + +/* Bound to every service of the DPTX endpoint (afk unmatched_ops). */ +const struct apple_epic_service_ops t8152_dptx_port_ops = { + .name = "dcpdptx-port", + .prepare = t8152_dptx_prepare, + .init = t8152_dptx_init, + .call_v2 = t8152_dptx_call, +}; + +static struct apple_epic_service *t8152_dptx_service(struct t8152_display *disp, + unsigned int port) +{ + struct dptx_port *dptx = &disp->dcp->dptxport[port]; + + return dptx_service_available(dptx) ? dptx->service : NULL; +} + +/* Connect the port to the PHY the DCP drives and request the display. */ +int t8152_dptx_connect(struct t8152_display *disp, unsigned int port) +{ + struct apple_epic_service *service = t8152_dptx_service(disp, port); + int ret; + + if (!service) + return -ENODEV; + ret = dptxport_connect(service, 0, disp->dcp_output, disp->die, true); + if (!ret) + ret = dptxport_request_display(service); + return ret; +} + +/* + * HPD as the port reports it to the firmware (group 8, command 8): the + * reply's first word is the call's status. + */ +int t8152_dptx_set_hpd(struct t8152_display *disp, unsigned int port, bool hpd) +{ + struct apple_epic_service *service = t8152_dptx_service(disp, port); + struct { + u8 pad[16]; + __le32 hpd; + } __packed cmd = { .hpd = cpu_to_le32(hpd) }, resp = {}; + size_t received; + int ret; + + if (!service) + return -ENODEV; + ret = afk_service_call_len(service, 8, 8, &cmd, sizeof(cmd), 12, &resp, + sizeof(resp), 12, &received); + if (ret) + return ret; + return get_unaligned_le32(resp.pad) ? -EIO : 0; +} + +/* Release the display (group 8, command 7), then HPD low. */ +int t8152_dptx_disconnect(struct t8152_display *disp, unsigned int port) +{ + struct apple_epic_service *service = t8152_dptx_service(disp, port); + __le32 status = 0; + size_t received; + int ret; + + if (!service) + return -ENODEV; + ret = afk_service_call_len(service, 8, 7, NULL, 0, 16, &status, + sizeof(status), 12, &received); + if (ret || status) + return ret ?: -EIO; + return t8152_dptx_set_hpd(disp, port, false); +} diff --git a/drivers/gpu/drm/apple/t8152_hdmi.c b/drivers/gpu/drm/apple/t8152_hdmi.c new file mode 100644 index 00000000000000..5b11879b1724b4 --- /dev/null +++ b/drivers/gpu/drm/apple/t8152_hdmi.c @@ -0,0 +1,669 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * The J873g HDMI port: the T8152's dedicated DisplayPort PHY in display + * crossbar 0's lpdptx slot, converted by a PS190. + * + * Interim, until drivers/phy/apple/dptx.c has a T8152 type (its lanes are + * 0x2800 apart from 0x4500) and the PS190's power through the SMC is + * described as a supply: this programs the PHY and powers the converter + * itself. + * + * When the bootloader brought HDMI up, this keeps its setup and reprograms + * what a link training changes: the PLL for a new link rate and the active + * lanes. Drive settings are only recorded, and there is no per-link route. + * When it did not (no HDMI monitor at boot, or a USB-C display on the main + * DCP), the HDMI port joins the shared USB-C ports: a DCP without a USB-C + * display takes it on a plug and starts the PHY and the PS190 from cold. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dptxep.h" +#include "t8152_display.h" + +#define HDMI_LANES 4 +#define HDMI_LANE0 0x4500 +#define HDMI_LANE_STRIDE 0x2800 + +struct t8152_hdmi { + void __iomem *core; + void __iomem *apb; + /* AP DisplayPort AUX controller aux1, for the EDID */ + struct t8152_aux aux; + /* The cold start of the HDMI port taken from the shared ports: */ + void __iomem *ps; /* PMGR power state of the PHY */ + void __iomem *psd; /* PMGR PSD service of the PHY */ + struct gpio_desc *hpd; + struct device_node *smc_np; + const __be32 *pcon, *tunable; + int pcon_len, tunable_len; + bool active; +}; + +/* + * The DCP driving the HDMI port taken from the shared ports, if any, and its + * HPD line, requested once for all the DCPs that may take the port. + */ +static DEFINE_MUTEX(hdmi_port_lock); +static struct device *hdmi_port_owner; +static struct gpio_desc *hdmi_port_hpd; +static unsigned int hdmi_port_users; + +#define HDMI_PS_TARGET GENMASK(3, 0) +#define HDMI_PS_ACTUAL GENMASK(7, 4) +#define HDMI_PS_FLAGS GENMASK(9, 8) /* write-one-to-clear */ +#define HDMI_PSD_STATE 0x80 +#define HDMI_PSD_TARGET 0x90 +#define HDMI_POWER_TIMEOUT_US 100000 + +/* APB 0x10 bits 3:0: the crossbar UFP feeding the PHY */ +#define HDMI_SOURCE_SELECT 0x10 +#define HDMI_SOURCE_AUX1 6 /* UFP endpoint of the aux1 controller */ + +static void hdmi_set_bits(struct t8152_hdmi *hdmi, u32 offset, u32 shift, + u32 mask, u32 value) +{ + u32 reg = readl(hdmi->core + offset); + + writel((reg & ~mask) | (value << shift), hdmi->core + offset); +} + +static void hdmi_apb_update(struct t8152_hdmi *hdmi, u32 offset, u32 mask, + u32 value) +{ + u32 reg = readl(hdmi->apb + offset); + + writel((reg & ~mask) | value, hdmi->apb + offset); +} + +/* The PLL configuration words for each link rate (DPCD units). */ +static const struct { + u32 rate; + u32 w[22]; +} hdmi_pll_configs[] = { + { LINK_RATE_RBR, + { 1, 0x21c, 0, 0, 1, 0x13, 1, 0, 0, 0x1a, 1, 0x3c, 2, 1, 0, 0, 1, 0, + 0, 0, 1, 3 } }, + { LINK_RATE_HBR, + { 1, 0x1c2, 0x1fff, 0x3ffe, 1, 0x13, 1, 0, 0, 0x1a, 1, 0x32, 2, 1, 0, + 0, 1, 0, 0, 0, 1, 3 } }, + { LINK_RATE_HBR2, + { 0, 0x1c2, 0x1fff, 0x3ffe, 1, 9, 1, 0, 0, 0x1a, 1, 0x32, 1, 0, 0, 1, + 0, 0, 0, 1, 1, 3 } }, + { LINK_RATE_HBR3, + { 0, 0x2a3, 0x2ffd, 0x3ffc, 1, 9, 1, 0, 0, 0x1a, 1, 0x5a, 1, 0, 0, 1, + 0, 0, 0, 1, 1, 3 } }, +}; + +/* A PLL command: command in 0x408[2:0], request bit 3, acknowledge bit 19. */ +static int hdmi_pll_command(struct t8152_display *disp, struct t8152_hdmi *hdmi, + u32 command) +{ + int i; + + hdmi_set_bits(hdmi, 0x408, 6, 0x40, 1); + hdmi_set_bits(hdmi, 0x408, 0, 0x7, command); + hdmi_set_bits(hdmi, 0x408, 3, 0x8, 1); + for (i = 0; i < 10; i++) { + usleep_range(16, 32); + if (readl(hdmi->core + 0x408) & BIT(19)) + break; + } + hdmi_set_bits(hdmi, 0x408, 3, 0x8, 0); + hdmi_set_bits(hdmi, 0x408, 6, 0x40, 0); + if (i == 10) { + dev_err(disp->dev, "HDMI: no ACK to PLL command %u\n", command); + return -ETIMEDOUT; + } + return 0; +} + +/* The lane-disable bits of each lane; 0x2420 holds the mask of unused lanes. */ +static void hdmi_set_lanes(struct t8152_hdmi *hdmi, u32 lanes) +{ + static const u32 offsets[] = { 0x64, 0x24, 0x24, 0x48, 0x48, 0x5c, 0x5c, 0x48 }; + static const u32 shifts[] = { 4, 4, 1, 0, 1, 2, 3, 4 }; + static const u32 masks[] = { 0x10, 0x10, 0x2, 0x1, 0x2, 0x4, 0x8, 0x10 }; + u32 lane, i; + + hdmi_set_bits(hdmi, 0x2400, 0, 0x1, 0); + for (lane = 0; lane < HDMI_LANES; lane++) { + u32 base = HDMI_LANE0 + lane * HDMI_LANE_STRIDE; + + for (i = 0; i < ARRAY_SIZE(offsets); i++) + hdmi_set_bits(hdmi, base + offsets[i], shifts[i], + masks[i], lane >= lanes); + } + hdmi_set_bits(hdmi, 0x2420, 0, 0xf, 0xf & ~((1 << lanes) - 1)); + hdmi_set_bits(hdmi, 0x2400, 0, 0x1, 1); +} + +static int hdmi_activate(struct t8152_display *disp) +{ + return 0; +} + +static int hdmi_deactivate(struct t8152_display *disp) +{ + dev_info(disp->dev, "HDMI: keeping the link up on deactivate\n"); + return 0; +} + +/* + * A new link rate: lanes off, PLL down, the PLL frequency, half link rate, + * PLL up again. + */ +static int hdmi_set_link_rate(struct t8152_display *disp, u32 rate) +{ + struct t8152_hdmi *hdmi = disp->phy_priv; + const u32 *w = NULL; + bool half; + size_t i; + int ret; + + for (i = 0; i < ARRAY_SIZE(hdmi_pll_configs); i++) + if (hdmi_pll_configs[i].rate == rate) + w = hdmi_pll_configs[i].w; + if (!w) + return -EINVAL; + + dev_info(disp->dev, "HDMI: link rate %#x\n", rate); + hdmi_set_bits(hdmi, 0x2400, 0, 0x1, 0); + ret = hdmi_pll_command(disp, hdmi, 0); + if (ret) + return ret; + + /* The PLL frequency, downspread off */ + hdmi_set_bits(hdmi, 0x6c0, 0, 0x7ff, w[1]); + hdmi_set_bits(hdmi, 0x6c0, 11, 0x800, w[6]); + hdmi_set_bits(hdmi, 0x6c0, 13, 0x2000, w[10]); + hdmi_set_bits(hdmi, 0x6c0, 18, 0x3c0000, w[21]); + hdmi_set_bits(hdmi, 0x6c4, 14, 0xfffc000, w[2]); + hdmi_set_bits(hdmi, 0x6c4, 0, 0x3fff, + (!(w[7] & 1) && w[2] < 2) ? 0 : w[3]); + hdmi_set_bits(hdmi, 0x6c8, 14, 0xc000, w[0]); + hdmi_set_bits(hdmi, 0x6c8, 8, 0x100, 0); + hdmi_set_bits(hdmi, 0x6c8, 0, 0xff, w[8]); + hdmi_set_bits(hdmi, 0x6c8, 9, 0x3e00, w[5]); + hdmi_set_bits(hdmi, 0x6c8, 16, 0x10000, w[17]); + hdmi_set_bits(hdmi, 0x6c8, 26, 0xfc000000, w[9]); + hdmi_set_bits(hdmi, 0x6cc, 0, 0x7f, w[11]); + hdmi_set_bits(hdmi, 0x6cc, 9, 0x600, w[13]); + hdmi_set_bits(hdmi, 0x6cc, 11, 0x7800, w[14]); + hdmi_set_bits(hdmi, 0x6cc, 15, 0x38000, w[15]); + hdmi_set_bits(hdmi, 0x6cc, 20, 0x100000, w[16]); + hdmi_set_bits(hdmi, 0x6cc, 21, 0x200000, w[18]); + hdmi_set_bits(hdmi, 0x6cc, 22, 0xc00000, w[19]); + hdmi_set_bits(hdmi, 0x6cc, 24, 0x3000000, w[4]); + hdmi_set_bits(hdmi, 0x6cc, 26, 0xc000000, w[20]); + + /* Latch the link rate dependent shadow registers (APB 0xa0). */ + hdmi_apb_update(hdmi, 0xa0, BIT(3), BIT(3)); + hdmi_apb_update(hdmi, 0xa0, BIT(2), BIT(2)); + hdmi_apb_update(hdmi, 0xa0, BIT(18), BIT(18)); + hdmi_apb_update(hdmi, 0xa0, BIT(18), 0); + hdmi_apb_update(hdmi, 0xa0, BIT(19), BIT(19)); + hdmi_apb_update(hdmi, 0xa0, BIT(19), 0); + hdmi_apb_update(hdmi, 0xa0, BIT(2), 0); + hdmi_apb_update(hdmi, 0xa0, BIT(3), 0); + + /* No UHBR rates; half link rate from HBR up. */ + half = rate >= LINK_RATE_HBR; + hdmi_set_bits(hdmi, 0x2400, 2, 0x4, 0); + hdmi_set_bits(hdmi, 0x2400, 3, 0x8, !half); + hdmi_set_bits(hdmi, 0x0000, 17, 0x20000, !half); + + ret = hdmi_pll_command(disp, hdmi, 7); + if (ret) + return ret; + if (!(readl(hdmi->core + 0x438) & BIT(30))) { + dev_err(disp->dev, "HDMI: PLL failed to lock at rate %#x\n", rate); + return -EIO; + } + return 0; +} + +static int hdmi_set_lane_count(struct t8152_display *disp, u32 lanes) +{ + /* The PHY takes no zero lane count. */ + if (lanes) + hdmi_set_lanes(disp->phy_priv, lanes); + return 0; +} + +static int hdmi_set_drive(struct t8152_display *disp, + const struct t8152_drive_settings *settings, u32 count) +{ + return 0; +} + +static int hdmi_set_route(struct t8152_display *disp, bool enable) +{ + return 0; +} + +/* + * The sink's EDID through the AP AUX controller aux1: the PHY takes its + * source from aux1 for the read (its AUX reaches the PS190, which reads the + * monitor's DDC), then from the DCP again. The display is off meanwhile. + */ +static int hdmi_read_edid(struct t8152_display *disp, u8 *buf, size_t size) +{ + struct t8152_hdmi *hdmi = disp->phy_priv; + u32 src; + int ret; + + if (!hdmi->aux.regs) + return -ENODEV; + ret = t8152_aux_init(disp, &hdmi->aux); + if (ret) + return ret; + src = readl(hdmi->apb + HDMI_SOURCE_SELECT); + writel((src & ~0xf) | HDMI_SOURCE_AUX1, hdmi->apb + HDMI_SOURCE_SELECT); + ret = t8152_aux_read_edid(disp, &hdmi->aux, buf, size); + writel(src, hdmi->apb + HDMI_SOURCE_SELECT); + return ret; +} + +static const struct t8152_phy_ops hdmi_ops = { + .activate = hdmi_activate, + .deactivate = hdmi_deactivate, + .set_link_rate = hdmi_set_link_rate, + .set_lane_count = hdmi_set_lane_count, + .set_drive = hdmi_set_drive, + .set_route = hdmi_set_route, + .read_edid = hdmi_read_edid, + .max_link_rate = LINK_RATE_HBR3, +}; + +/* + * The PS190's power through the SMC: the {key, value} writes of + * apple,pcon-power. The PS190 drives the HDMI HPD line only while it is + * powered, and the AP AUX controller that reads the USB-C monitors' EDID + * gets no reply from any USB-C port while it is off. Nothing here waits + * for it to come up: a DCP takes the port only once it sees HPD + * (t8152_hdmi_port_poll()), and an EDID read retries until the AUX + * replies (t8152_aux_read_edid()). On a port taken over, these writes find + * the PS190 powered since probe. + */ +static int hdmi_pcon_power(struct t8152_display *disp, struct t8152_hdmi *hdmi) +{ + struct platform_device *smc_pdev = of_find_device_by_node(hdmi->smc_np); + struct apple_smc *smc = smc_pdev ? platform_get_drvdata(smc_pdev) : NULL; + int ret = 0; + + if (!smc) { + ret = -EPROBE_DEFER; + goto out; + } + for (int i = 0; i + 3 <= hdmi->pcon_len; i += 3) { + u64 value = (u64)be32_to_cpu(hdmi->pcon[i + 1]) << 32 | + be32_to_cpu(hdmi->pcon[i + 2]); + + ret = apple_smc_write(smc, be32_to_cpu(hdmi->pcon[i]), &value, + sizeof(value)); + if (ret) { + dev_err(disp->dev, "HDMI: PS190 power failed: %d\n", ret); + goto out; + } + } +out: + if (smc_pdev) + put_device(&smc_pdev->dev); + return ret; +} + +/* The PHY's PMGR and PSD power, then the PS190's. */ +static int hdmi_power_up(struct t8152_display *disp, struct t8152_hdmi *hdmi) +{ + int ret; + u32 val; + + if ((readl(hdmi->ps) & HDMI_PS_ACTUAL) != HDMI_PS_ACTUAL) { + val = readl(hdmi->ps) & ~(HDMI_PS_TARGET | HDMI_PS_FLAGS); + writel(val | HDMI_PS_TARGET, hdmi->ps); + ret = readl_poll_timeout(hdmi->ps, val, + (val & HDMI_PS_ACTUAL) == HDMI_PS_ACTUAL, + 10, HDMI_POWER_TIMEOUT_US); + if (ret) { + dev_err(disp->dev, "HDMI: PHY power state stays %#x\n", val); + return ret; + } + } + if (readl(hdmi->psd + HDMI_PSD_STATE) & 7) { + writel(0, hdmi->psd + HDMI_PSD_TARGET); + ret = readl_poll_timeout(hdmi->psd + HDMI_PSD_STATE, val, !(val & 7), + 10, HDMI_POWER_TIMEOUT_US); + if (ret) { + dev_err(disp->dev, "HDMI: PHY PSD state stays %#x\n", val); + return ret; + } + } + return hdmi_pcon_power(disp, hdmi); +} + +/* The impedance calibration: wait for 0x1c04 bit 0, take 0x1c24 bits 12:6. */ +static void hdmi_impedance_calibration(struct t8152_display *disp, + struct t8152_hdmi *hdmi) +{ + u32 val; + + if (readl_poll_timeout(hdmi->core + 0x1c04, val, val & 1, 10, 1000000)) + dev_warn(disp->dev, "HDMI: impedance calibration timed out\n"); + hdmi_set_bits(hdmi, 0x1c00, 4, 0x3f0, 0x3f); + val = readl(hdmi->core + 0x1c24); + hdmi_set_bits(hdmi, 0x1c18, 15, 0x3f8000, (val >> 6) & 0x7f); + hdmi_set_bits(hdmi, 0x1c18, 14, 0x4000, 1); +} + +/* + * The cold start, as the bootloader does it: power, source select, PLL, AUX + * and PHY power, the tunables, the PLL and PHY activation, four lanes and + * the impedance calibration. Once up, the link is kept on deactivate, as + * for the bootloader's HDMI. + */ +static int hdmi_port_activate(struct t8152_display *disp) +{ + struct t8152_hdmi *hdmi = disp->phy_priv; + int ret; + + if (hdmi->active) + return 0; + ret = hdmi_power_up(disp, hdmi); + if (ret) + return ret; + /* The source select: only the low nibble */ + hdmi_apb_update(hdmi, HDMI_SOURCE_SELECT, 0xf, disp->dp_source); + /* PLL, AUX and PHY power enables */ + hdmi_apb_update(hdmi, 0x48, 0x010, 0x010); + usleep_range(1000, 2000); + hdmi_apb_update(hdmi, 0x48, 0x020, 0x020); + hdmi_apb_update(hdmi, 0x48, 0x040, 0); + hdmi_apb_update(hdmi, 0x48, 0x100, 0x100); + usleep_range(1000, 2000); + hdmi_apb_update(hdmi, 0x48, 0x200, 0x200); + hdmi_apb_update(hdmi, 0x48, 0x400, 0); + hdmi_apb_update(hdmi, 0x48, 0x001, 0x001); + usleep_range(1000, 2000); + hdmi_apb_update(hdmi, 0x48, 0x002, 0x002); + hdmi_apb_update(hdmi, 0x48, 0x004, 0); + + for (int i = 0; i + 3 <= hdmi->tunable_len; i += 3) { + void __iomem *reg = hdmi->core + be32_to_cpu(hdmi->tunable[i]); + + writel((readl(reg) & ~be32_to_cpu(hdmi->tunable[i + 1])) | + be32_to_cpu(hdmi->tunable[i + 2]), reg); + } + + hdmi_set_bits(hdmi, 0x08d0, 4, 0x10, 1); /* single-ended PLL clock */ + hdmi_set_bits(hdmi, 0x0000, 1, 0x02, 1); /* PLL on */ + hdmi_set_bits(hdmi, 0x1400, 0, 0x01, 0); /* AUX common control */ + hdmi_set_bits(hdmi, 0x1c00, 4, 0x3f0, 0x3c); /* PHY on */ + hdmi_set_bits(hdmi, 0x0000, 0, 0x01, 1); + usleep_range(1000, 2000); + hdmi_set_lanes(hdmi, HDMI_LANES); + hdmi_impedance_calibration(disp, hdmi); + hdmi->active = true; + dev_info(disp->dev, "HDMI: PHY up from cold, source %u\n", disp->dp_source); + return 0; +} + +static const struct t8152_phy_ops hdmi_port_ops = { + .activate = hdmi_port_activate, + .deactivate = hdmi_deactivate, + .set_link_rate = hdmi_set_link_rate, + .set_lane_count = hdmi_set_lane_count, + .set_drive = hdmi_set_drive, + .set_route = hdmi_set_route, + .read_edid = hdmi_read_edid, + .max_link_rate = LINK_RATE_HBR3, +}; + +/* Registers shared with the other DCPs that may take the HDMI port. */ +static void __iomem *hdmi_ioremap(struct t8152_display *disp, + struct device_node *np, const char *name) +{ + int index = of_property_match_string(np, "reg-names", name); + struct resource res; + + if (index < 0 || of_address_to_resource(np, index, &res)) + return NULL; + return devm_ioremap(disp->dev, res.start, resource_size(&res)); +} + +static void hdmi_put_smc(void *data) +{ + of_node_put(data); +} + +static void hdmi_port_put(void *data) +{ + guard(mutex)(&hdmi_port_lock); + if (!--hdmi_port_users) { + gpiod_put(hdmi_port_hpd); + hdmi_port_hpd = NULL; + } +} + +static struct gpio_desc *hdmi_port_get(struct t8152_display *disp, + struct device_node *np) +{ + struct gpio_desc *hpd; + int ret; + + scoped_guard(mutex, &hdmi_port_lock) { + if (!hdmi_port_users) { + hpd = fwnode_gpiod_get_index(of_fwnode_handle(np), "hpd", 0, + GPIOD_ASIS, "hdmi-hpd"); + if (IS_ERR(hpd)) + return hpd; + hdmi_port_hpd = hpd; + } + hdmi_port_users++; + hpd = hdmi_port_hpd; + } + ret = devm_add_action_or_reset(disp->dev, hdmi_port_put, NULL); + return ret ? ERR_PTR(ret) : hpd; +} + +/* + * The HDMI port of the shared ports, for every DCP: the PHY's source select + * takes each one's crossbar endpoint. Without the cold start description in + * np, HDMI stays the bootloader's. + */ +int t8152_hdmi_port_init(struct t8152_display *disp, struct device_node *np) +{ + struct t8152_hdmi *hdmi; + int ret; + + if (!of_property_present(np, "apple,pcon-power")) + return 0; + hdmi = devm_kzalloc(disp->dev, sizeof(*hdmi), GFP_KERNEL); + if (!hdmi) + return -ENOMEM; + hdmi->core = hdmi_ioremap(disp, np, "phy-core"); + hdmi->apb = hdmi_ioremap(disp, np, "phy-apb"); + hdmi->ps = hdmi_ioremap(disp, np, "phy-ps"); + hdmi->psd = hdmi_ioremap(disp, np, "phy-psd"); + hdmi->aux.regs = hdmi_ioremap(disp, np, "aux"); + hdmi->aux.ps = hdmi_ioremap(disp, np, "aux-ps"); + /* AUX output select 0x10: the lpdptx PHY */ + hdmi->aux.sel = 0x10; + if (!hdmi->core || !hdmi->apb || !hdmi->ps || !hdmi->psd) + return -ENOMEM; + if (!hdmi->aux.ps) + hdmi->aux.regs = NULL; + hdmi->pcon = of_get_property(np, "apple,pcon-power", &hdmi->pcon_len); + hdmi->pcon_len /= sizeof(__be32); + hdmi->tunable = of_get_property(np, "apple,tunable-phy", + &hdmi->tunable_len); + hdmi->tunable_len /= sizeof(__be32); + hdmi->smc_np = of_parse_phandle(np, "apple,smc", 0); + if (!hdmi->smc_np) + return -EINVAL; + ret = devm_add_action_or_reset(disp->dev, hdmi_put_smc, hdmi->smc_np); + if (ret) + return ret; + /* Without the bootloader's HDMI nothing else powers the PS190. */ + ret = hdmi_pcon_power(disp, hdmi); + if (ret) + return ret; + /* Every DCP that may take the port watches the same line. */ + hdmi->hpd = hdmi_port_get(disp, np); + if (IS_ERR(hdmi->hpd)) + return PTR_ERR(hdmi->hpd); + disp->hdmi_port = hdmi; + dev_info(disp->dev, "HDMI: port shared, taken without a USB-C display\n"); + return 0; +} + +/* + * Take the HDMI port when a sink is plugged in and this DCP drives no USB-C + * display; give it back once the sink is gone and the plug path has + * released the link. Called from the connector's detect with the display + * lock held. + */ +void t8152_hdmi_port_poll(struct t8152_display *disp) +{ + struct t8152_hdmi *hdmi = disp->hdmi_port; + int hpd; + + if (!hdmi) + return; + hpd = gpiod_get_value_cansleep(hdmi->hpd); + if (hpd < 0) + return; + guard(mutex)(&hdmi_port_lock); + if (disp->on_hdmi) { + if (hpd || disp->hpd) + return; + disp->phy = disp->usbc_phy; + disp->phy_priv = disp->usbc_phy_priv; + disp->dcp_output = disp->usbc_output; + disp->hpd_gpio = NULL; + disp->on_hdmi = false; + hdmi_port_owner = NULL; + dev_info(disp->dev, "HDMI: port given back\n"); + return; + } + if (!hpd || disp->hpd || hdmi_port_owner || !t8152_atc_release(disp)) + return; + hdmi_port_owner = disp->dev; + disp->usbc_phy = disp->phy; + disp->usbc_phy_priv = disp->phy_priv; + disp->usbc_output = disp->dcp_output; + disp->phy = &hdmi_port_ops; + disp->phy_priv = hdmi; + /* display crossbar DFP endpoint lpdptx */ + disp->dcp_output = 4; + disp->hpd_gpio = hdmi->hpd; + disp->on_hdmi = true; + dev_info(disp->dev, "HDMI: sink plugged, taking the HDMI port\n"); +} + +/* The DCP node that describes the HDMI PHY (DCPEXT0's). */ +struct device_node *t8152_hdmi_node(void) +{ + struct device_node *np; + + for_each_compatible_node(np, NULL, "apple,t8152-dcp-iboot") + if (of_property_read_bool(np, "apple,hdmi")) + return np; + return NULL; +} + +static void __iomem *hdmi_map(struct device *dev, struct device_node *np, + const char *name) +{ + int index = of_property_match_string(np, "reg-names", name); + + if (index < 0) + return IOMEM_ERR_PTR(index); + return devm_of_iomap(dev, np, index, NULL); +} + +static bool hdmi_power_active(struct device_node *np, const char *name) +{ + int index = of_property_match_string(np, "reg-names", name); + void __iomem *regs; + u32 state; + + if (index < 0) + return false; + regs = of_iomap(np, index); + if (!regs) + return false; + state = readl(regs); + iounmap(regs); + /* Both the requested and actual PMGR states must be active. */ + return (state & GENMASK(7, 0)) == GENMASK(7, 0); +} + +/* + * The DCP the bootloader wired to the PHY (its source select: 0 for the main + * DCP on the HDMI-only route, 1 for DCPEXT0 next to a USB-C display), or + * -ENODEV if it left the PHY off or the PLL unlocked. + */ +int t8152_hdmi_source(struct device_node *np) +{ + int core = of_property_match_string(np, "reg-names", "phy-core"); + int apb = of_property_match_string(np, "reg-names", "phy-apb"); + void __iomem *core_regs, *apb_regs; + int ret = -ENODEV; + + /* The PHY aperture aborts while gated, including on a USB-C-only boot. */ + if (core < 0 || apb < 0 || !hdmi_power_active(np, "phy-ps")) + return -ENODEV; + core_regs = of_iomap(np, core); + apb_regs = of_iomap(np, apb); + if (core_regs && apb_regs && readl(core_regs + 0x438) & BIT(30)) + ret = readl(apb_regs + HDMI_SOURCE_SELECT) & 0xf; + if (apb_regs) + iounmap(apb_regs); + if (core_regs) + iounmap(core_regs); + if (ret == 1 && !hdmi_power_active(np, "coproc-ps")) + return -ENODEV; + if (ret != 0 && ret != 1) + return -ENODEV; + return ret; +} + +/* The PHY, its AUX controller and its HPD line come from np. */ +int t8152_hdmi_init(struct t8152_display *disp, struct device_node *np) +{ + struct t8152_hdmi *hdmi; + + hdmi = devm_kzalloc(disp->dev, sizeof(*hdmi), GFP_KERNEL); + if (!hdmi) + return -ENOMEM; + hdmi->core = hdmi_map(disp->dev, np, "phy-core"); + if (IS_ERR(hdmi->core)) + return PTR_ERR(hdmi->core); + hdmi->apb = hdmi_map(disp->dev, np, "phy-apb"); + if (IS_ERR(hdmi->apb)) + return PTR_ERR(hdmi->apb); + + /* AUX output select 0x10: the lpdptx PHY */ + t8152_aux_probe(disp, &hdmi->aux, 0x10, np); + + dev_info(disp->dev, "HDMI: inherited source select %u, PLL %slocked\n", + readl(hdmi->apb + HDMI_SOURCE_SELECT) & 0xf, + readl(hdmi->core + 0x438) & BIT(30) ? "" : "not "); + + disp->phy = &hdmi_ops; + disp->phy_priv = hdmi; + /* display crossbar DFP endpoint lpdptx */ + disp->dcp_output = 4; + return 0; +} diff --git a/drivers/gpu/drm/apple/t8152_typec.c b/drivers/gpu/drm/apple/t8152_typec.c new file mode 100644 index 00000000000000..afae7b2546d607 --- /dev/null +++ b/drivers/gpu/drm/apple/t8152_typec.c @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * The rear USB-C ports' DisplayPort alt mode, from the USB Type-C port + * driver that owns their PD controllers. Each port has one Type-C mode + * switch for the display path, shared by all DCPs: the port's usb-c node in + * the shared ports node (apple,usb-c-ports), whose endpoint is at the display + * port of the port's connector. The Type-C class looks at three mode switches + * of a connector at most, and the port's PHY needs one as well, so there is + * no room for one per DCP. + * + * The first DCP that probes registers the switches, and they stay until the + * driver is unloaded: the port driver keeps using a switch it found, and + * must not wait for a DCP that cannot start. A switch records what the + * display path reads (DisplayPort alt mode with HPD high, the lanes of the + * pin assignment, the plug orientation) and has every DCP that drives USB-C + * look at its ports; t8152_atc.c claims a port for one of them. + * + * The switches are dcp-fabric.c's in the device tree only. Its route layer + * switches a DP PHY and the display crossbar through their own drivers and + * connects the sink through the DCP's IOMFB DPTX service; these DCPs program + * the ATC PHY and the crossbar themselves and connect through the iBoot + * interface's DPTX port service, so their switches record the state alone. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "iomfb_iboot.h" +#include "t8152_display.h" + +/* The ATC instances, as the display crossbar's DFP endpoints number them */ +#define T8152_TYPEC_PORTS 4 + +struct t8152_typec_port { + struct typec_mux_dev *mux; + /* below under t8152_typec_lock */ + bool sink; + bool flipped; + u32 lanes; +}; + +/* A DCP that drives USB-C, told about the ports' changes */ +struct t8152_typec { + struct list_head node; + struct t8152_display *disp; +}; + +/* Registers the switches, once */ +static DEFINE_MUTEX(t8152_typec_register_lock); +/* Below under t8152_typec_register_lock: the switches' parent, which no DCP binding owns */ +static struct faux_device *t8152_typec_owner; +/* The status changesets of ports whose switch could not be registered */ +struct t8152_typec_disabled { + struct list_head node; + struct of_changeset cs; +}; + +static LIST_HEAD(t8152_typec_disabled_ports); +/* The ports' state, written by the port driver, and the DCPs that read it */ +static DEFINE_SPINLOCK(t8152_typec_lock); +static struct t8152_typec_port t8152_typec_ports[T8152_TYPEC_PORTS]; +static LIST_HEAD(t8152_typec_displays); + +static int t8152_typec_set(struct typec_mux_dev *mux, struct typec_mux_state *state) +{ + struct t8152_typec_port *port = typec_mux_get_drvdata(mux); + struct typec_displayport_data *dp = NULL; + struct t8152_typec *typec; + bool flipped = false; + u32 lanes = 4; + + if (state->alt && state->alt->svid == USB_TYPEC_DP_SID && + state->mode >= TYPEC_DP_STATE_A && state->mode <= TYPEC_DP_STATE_F) { + dp = state->data; + flipped = typec_altmode_get_orientation(state->alt) == + TYPEC_ORIENTATION_REVERSE; + /* B, D and F share the cable with USB 3: two DisplayPort lanes */ + if (state->mode == TYPEC_DP_STATE_B || state->mode == TYPEC_DP_STATE_D || + state->mode == TYPEC_DP_STATE_F) + lanes = 2; + } + + guard(spinlock)(&t8152_typec_lock); + /* The sink answers AUX once it raised HPD, not at alt mode entry. */ + port->sink = dp && (dp->status & DP_STATUS_HPD_STATE); + port->flipped = flipped; + port->lanes = lanes; + list_for_each_entry(typec, &t8152_typec_displays, node) + dcp_iboot_hpd_event(container_of(typec->disp, struct dcp_iboot, disp)); + return 0; +} + +/* + * 1 with a DisplayPort sink on the port of ATC @index (DP alt mode, HPD + * high), 0 without. + * + * A HPD pulse that ends before the DCP looks is not a new sink: an EV2780 + * without a video stream drops HPD for about 160 ms every few seconds, and + * connecting it anew each time kept its link from coming up. A sink that is + * really unplugged leaves DP alt mode with its partner. + */ +int t8152_typec_sink(struct t8152_display *disp, u32 index, bool *flipped, + u32 *lanes) +{ + struct t8152_typec_port *port; + + if (!disp->typec || index >= T8152_TYPEC_PORTS) + return 0; + port = &t8152_typec_ports[index]; + guard(spinlock)(&t8152_typec_lock); + if (!port->mux || !port->sink) + return 0; + *flipped = port->flipped; + *lanes = port->lanes; + return 1; +} + +static int t8152_typec_port_register(struct device *dev, struct device_node *np) +{ + struct typec_mux_desc desc = {}; + struct t8152_typec_port *port; + struct typec_mux_dev *mux; + u32 index; + int ret; + + ret = of_property_read_u32(np, "apple,dfp-endpoint", &index); + if (ret || index >= T8152_TYPEC_PORTS) + return dev_err_probe(dev, ret ?: -EINVAL, "%pOF: invalid port\n", np); + port = &t8152_typec_ports[index]; + if (port->mux) + return 0; + desc.fwnode = of_fwnode_handle(np); + desc.set = t8152_typec_set; + desc.drvdata = port; + desc.name = kasprintf(GFP_KERNEL, "dcp-usb-c%u", index); + if (!desc.name) + return -ENOMEM; + port->lanes = 4; + /* Under the shared owner, not @dev: the switch outlives any DCP's binding. */ + mux = typec_mux_register(&t8152_typec_owner->dev, &desc); + kfree(desc.name); + if (IS_ERR(mux)) + return dev_err_probe(dev, PTR_ERR(mux), "%pOF: switch not registered\n", np); + scoped_guard(spinlock, &t8152_typec_lock) + port->mux = mux; + return 0; +} + +/* + * A switch that cannot be registered: the port driver goes on without it. + * The changeset stays applied until the driver unloads, which reverts it. + */ +static void t8152_typec_port_disable(struct device *dev, struct device_node *np) +{ + struct t8152_typec_disabled *d = kzalloc(sizeof(*d), GFP_KERNEL); + + if (!d) + return; + of_changeset_init(&d->cs); + if (!of_changeset_update_prop_string(&d->cs, np, "status", "disabled") && + !of_changeset_apply(&d->cs)) { + list_add(&d->node, &t8152_typec_disabled_ports); + return; + } + dev_err(dev, "%pOF: could not disable the display switch\n", np); + of_changeset_destroy(&d->cs); + kfree(d); +} + +/* + * Register the display switches of the USB-C ports the DCP @dev can drive, + * unless another DCP did. Called first in the DCP's probe, so that the port + * driver, which waits for them, never waits for a DCP that cannot start. + */ +void t8152_typec_register(struct device *dev) +{ + struct device_node *ports __free(device_node) = + of_parse_phandle(dev->of_node, "apple,usb-c-ports", 0); + struct device_node *np = ports ?: dev->of_node; + + guard(mutex)(&t8152_typec_register_lock); + if (!t8152_typec_owner) { + t8152_typec_owner = faux_device_create("t8152-typec", NULL, NULL); + if (!t8152_typec_owner) { + dev_err(dev, "no owner for the USB-C display switches\n"); + return; + } + } + for_each_available_child_of_node_scoped(np, child) { + if (of_property_present(child, "mode-switch") && + t8152_typec_port_register(dev, child)) + t8152_typec_port_disable(dev, child); + } +} + +/* At driver unload, once no DCP is bound */ +void t8152_typec_unregister(void) +{ + guard(mutex)(&t8152_typec_register_lock); + for (unsigned int i = 0; i < T8152_TYPEC_PORTS; i++) { + struct typec_mux_dev *mux = t8152_typec_ports[i].mux; + + if (!mux) + continue; + scoped_guard(spinlock, &t8152_typec_lock) + t8152_typec_ports[i].mux = NULL; + typec_mux_unregister(mux); + } + while (!list_empty(&t8152_typec_disabled_ports)) { + struct t8152_typec_disabled *d = + list_first_entry(&t8152_typec_disabled_ports, typeof(*d), node); + + list_del(&d->node); + /* A changeset that cannot be reverted is still part of the tree: keep it */ + if (of_changeset_revert(&d->cs)) + continue; + of_changeset_destroy(&d->cs); + kfree(d); + } + if (t8152_typec_owner) { + faux_device_destroy(t8152_typec_owner); + t8152_typec_owner = NULL; + } +} + +static void t8152_typec_leave(void *data) +{ + struct t8152_typec *typec = data; + + scoped_guard(spinlock, &t8152_typec_lock) + list_del(&typec->node); +} + +/* + * Have the DCP see the USB-C ports' display state from now on: call this + * once the DCP stays bound. Without it, the DCP sees no USB-C sink. + */ +int t8152_typec_init(struct t8152_display *disp) +{ + struct t8152_typec *typec; + int ret; + + typec = devm_kzalloc(disp->dev, sizeof(*typec), GFP_KERNEL); + if (!typec) + return -ENOMEM; + typec->disp = disp; + scoped_guard(spinlock, &t8152_typec_lock) + list_add_tail(&typec->node, &t8152_typec_displays); + ret = devm_add_action_or_reset(disp->dev, t8152_typec_leave, typec); + if (ret) + return ret; + disp->typec = typec; + return 0; +} diff --git a/drivers/gpu/drm/apple/tests/display.kunitconfig b/drivers/gpu/drm/apple/tests/display.kunitconfig new file mode 100644 index 00000000000000..03105b192c48ef --- /dev/null +++ b/drivers/gpu/drm/apple/tests/display.kunitconfig @@ -0,0 +1,12 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_PM=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_DRM=y +CONFIG_BACKLIGHT_CLASS_DEVICE=y +CONFIG_DRM_APPLE=y +CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST=y +CONFIG_OF_OVERLAY=y diff --git a/drivers/gpu/drm/apple/v14-board-test.c b/drivers/gpu/drm/apple/v14-board-test.c index f9b84ab36a7cc1..3148bc81c04586 100644 --- a/drivers/gpu/drm/apple/v14-board-test.c +++ b/drivers/gpu/drm/apple/v14-board-test.c @@ -21,6 +21,7 @@ struct board_ctx { const char *dcp; const char *const *machine; /* NULL-terminated root compatibles */ + const char *panel; /* the DCP's panel node compatible; NULL: none */ }; static bool board_ctx_dcp_is(const void *ctx, const char *compat) @@ -41,12 +42,26 @@ static bool board_ctx_machine_is(const void *ctx, const char *compat) return false; } +static bool board_ctx_panel_is(const void *ctx, const char *compat) +{ + const struct board_ctx *c = ctx; + + return c->panel && !strcmp(c->panel, compat); +} + +static const struct dcp_v14_board *board_for_panel(const char *dcp, const char *const *machine, + const char *panel, bool *known) +{ + const struct board_ctx ctx = { .dcp = dcp, .machine = machine, .panel = panel }; + + return dcp_v14_board_select(board_ctx_dcp_is, board_ctx_machine_is, board_ctx_panel_is, + &ctx, known); +} + static const struct dcp_v14_board *board_for(const char *dcp, const char *const *machine, bool *known) { - const struct board_ctx ctx = { .dcp = dcp, .machine = machine }; - - return dcp_v14_board_select(board_ctx_dcp_is, board_ctx_machine_is, &ctx, known); + return board_for_panel(dcp, machine, NULL, known); } static const char *const j516c[] = { "apple,j516c", "apple,t6031", "apple,arm-platform", NULL }; @@ -54,6 +69,8 @@ static const char *const j514c[] = { "apple,j514c", "apple,t6031", "apple,arm-pl static const char *const j516m[] = { "apple,j516m", "apple,t6034", "apple,arm-platform", NULL }; static const char *const j516s[] = { "apple,j516s", "apple,t6030", "apple,arm-platform", NULL }; static const char *const j613[] = { "apple,j613", "apple,t8122", "apple,arm-platform", NULL }; +static const char *const j504[] = { "apple,j504", "apple,t8122", "apple,arm-platform", NULL }; +static const char *const j433[] = { "apple,j433", "apple,t8122", "apple,arm-platform", NULL }; static void v14_board_j516c(struct kunit *test) { @@ -247,7 +264,55 @@ static void v14_swap_timestamps_encoding(struct kunit *test) } } +/* + * J504 (14" M3 MacBook Pro): the J613 image on the T8122 DCP, its own 3024x1964 + * ProMotion panel, the qualified level block (brightness) and unstamped swaps, selected by + * the DCP's panel node (apple,panel-j504). The other T8122 Macs (J433, J434) have no record. + */ +static void v14_board_j504(struct kunit *test) +{ + const struct dcp_v14_board *b, *air; + bool known; + + b = board_for_panel("apple,t8122-dcp", j504, "apple,panel-j504", &known); + KUNIT_ASSERT_NOT_NULL(test, b); + air = board_for("apple,t8122-dcp", j613, &known); + KUNIT_ASSERT_NOT_NULL(test, air); + KUNIT_EXPECT_PTR_NE(test, b, air); + KUNIT_EXPECT_STREQ(test, b->name, "J504"); + KUNIT_EXPECT_NULL(test, b->machine); + KUNIT_EXPECT_STREQ(test, b->panel, "apple,panel-j504"); + KUNIT_EXPECT_STREQ(test, b->handoff, "apple,t8122-handoff"); + KUNIT_EXPECT_STREQ(test, b->firmware_uuid, J613_DCP_IMAGE); + KUNIT_EXPECT_EQ(test, b->panel_width, 3024); + KUNIT_EXPECT_EQ(test, b->panel_height, 1964); + KUNIT_EXPECT_TRUE(test, b->promotion); + KUNIT_EXPECT_TRUE(test, b->log_bringup); + KUNIT_EXPECT_TRUE(test, b->panel_nits); + KUNIT_EXPECT_EQ(test, b->ctm_set, air->ctm_set); + KUNIT_EXPECT_EQ(test, b->ctm_get, air->ctm_get); + KUNIT_EXPECT_TRUE(test, dcp_v14_board_admits(b, J613_DCP_IMAGE)); + KUNIT_EXPECT_FALSE(test, dcp_v14_board_admits(b, T6030_DCP_IMAGE)); + KUNIT_EXPECT_FALSE(test, dcp_v14_board_admits(b, J516C_DCP_IMAGE)); + KUNIT_EXPECT_FALSE(test, dcp_v14_board_stamps_swaps(b, false)); + + KUNIT_EXPECT_NULL(test, board_for("apple,t8122-dcp", j433, &known)); + KUNIT_EXPECT_TRUE(test, known); + /* The record follows the panel node, not the machine: none without it. */ + KUNIT_EXPECT_NULL(test, board_for("apple,t8122-dcp", j504, &known)); + KUNIT_EXPECT_TRUE(test, known); + KUNIT_EXPECT_NULL(test, board_for_panel("apple,t8122-dcp", j504, "apple,panel-j514", + &known)); + /* The Airs keep their machine records whatever the panel node says. */ + KUNIT_EXPECT_PTR_EQ(test, board_for_panel("apple,t8122-dcp", j613, "apple,panel-j504", + &known), air); + /* Another SoC's DCP with the J504 panel gets no J504 record. */ + KUNIT_EXPECT_NULL(test, board_for_panel("apple,t6031-dcp", j504, "apple,panel-j504", + &known)); +} + static struct kunit_case v14_board_cases[] = { + KUNIT_CASE(v14_board_j504), KUNIT_CASE(v14_board_j516c), KUNIT_CASE(v14_board_j514c), KUNIT_CASE(v14_board_t6031_other_boards), diff --git a/drivers/gpu/drm/apple/v14-plane-test.c b/drivers/gpu/drm/apple/v14-plane-test.c new file mode 100644 index 00000000000000..2527b6726c7595 --- /dev/null +++ b/drivers/gpu/drm/apple/v14-plane-test.c @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Which primary planes the 14.7 presenter takes: one unscaled image of the + * mode's size from the top-left of the framebuffer, judged on the rectangles + * drm_atomic_helper_check_plane_state() clips to the mode, with the scaling + * limits apple_plane_atomic_check() passes it. A plane that reaches past the + * right or bottom edge of the mode is clipped there and taken; one that is + * offset into the mode, starts left of or above it, or is scaled is not. For + * a plane it takes, check the size iomfb_v14_7_flush() hands the presenter. + */ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "iomfb_v14_7_plane.h" + +struct v14_plane_case { + const char *name; + u16 hdisplay, vdisplay; /* the mode */ + u32 fb_w, fb_h; + int crtc_x, crtc_y; + u32 crtc_w, crtc_h; + u32 src_x, src_y, src_w, src_h; /* whole pixels */ + bool external; + bool fits; + u32 shown_w, shown_h; /* clipped source, when it fits */ + u32 src_w_frac; /* 16.16 fraction added to src_w */ +}; + +static const struct v14_plane_case v14_plane_cases[] = { + { "external, exact", 1920, 1080, 1920, 1080, 0, 0, 1920, 1080, + 0, 0, 1920, 1080, true, true, 1920, 1080 }, + /* + * KWin mirroring a 3024x1964 panel at scale 1.7 onto a 1920x1080 + * display: 1663 columns of picture and 129 of border on each side. + */ + { "external, one column past the right edge", 1920, 1080, 1921, 1080, + 0, 0, 1921, 1080, 0, 0, 1921, 1080, true, true, 1920, 1080 }, + { "external, one row past the bottom edge", 1920, 1080, 1920, 1081, + 0, 0, 1920, 1081, 0, 0, 1920, 1081, true, true, 1920, 1080 }, + { "external, past the right and bottom edges", 1920, 1080, 1921, 1081, + 0, 0, 1921, 1081, 0, 0, 1921, 1081, true, true, 1920, 1080 }, + /* + * Clipping rounds the source toward 1:1: 1921 + 1/65536 columns on + * 1921 clip to exactly 1920 << 16, while 1921.5 on 1921 clip to + * (1920 << 16) + 32750, which is scaled. + */ + { "external, past the edge, source a 65536th over 1:1", 1920, 1080, + 1922, 1080, 0, 0, 1921, 1080, 0, 0, 1921, 1080, true, true, + 1920, 1080, .src_w_frac = 1 }, + { "external, past the edge, source half a pixel over 1:1", 1920, 1080, + 1922, 1080, 0, 0, 1921, 1080, 0, 0, 1921, 1080, true, false, + .src_w_frac = 0x8000 }, + { "external, top-left of a larger framebuffer", 1920, 1080, 2560, 1440, + 0, 0, 1920, 1080, 0, 0, 1920, 1080, true, true, 1920, 1080 }, + { "external, starts left of the mode", 1920, 1080, 1921, 1080, + -1, 0, 1921, 1080, 0, 0, 1921, 1080, true, false }, + { "external, starts above the mode", 1920, 1080, 1920, 1081, + 0, -1, 1920, 1081, 0, 0, 1920, 1081, true, false }, + { "external, offset into the framebuffer", 1920, 1080, 1921, 1080, + 0, 0, 1920, 1080, 1, 0, 1920, 1080, true, false }, + { "external, scaled to the mode", 1920, 1080, 1921, 1080, + 0, 0, 1920, 1080, 0, 0, 1921, 1080, true, false }, + { "external, narrower than the mode", 1920, 1080, 1919, 1080, + 0, 0, 1919, 1080, 0, 0, 1919, 1080, true, false }, + { "external, positioned inside the mode", 1920, 1080, 1920, 1080, + 1, 0, 1919, 1080, 0, 0, 1919, 1080, true, false }, + { "panel, exact", 3024, 1964, 3024, 1964, 0, 0, 3024, 1964, + 0, 0, 3024, 1964, false, true, 3024, 1964 }, + { "panel, larger framebuffer", 3024, 1964, 3025, 1964, 0, 0, 3025, 1964, + 0, 0, 3025, 1964, false, false }, +}; + +static void v14_plane_case_desc(const struct v14_plane_case *c, char *desc) +{ + strscpy(desc, c->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(v14_plane, v14_plane_cases, v14_plane_case_desc); + +static void v14_plane_fits_mode(struct kunit *test) +{ + const struct v14_plane_case *c = test->param_value; + struct drm_plane *plane = kunit_kzalloc(test, sizeof(*plane), GFP_KERNEL); + struct drm_crtc *crtc = kunit_kzalloc(test, sizeof(*crtc), GFP_KERNEL); + struct drm_framebuffer *fb = kunit_kzalloc(test, sizeof(*fb), GFP_KERNEL); + struct drm_crtc_state *crtc_state = + kunit_kzalloc(test, sizeof(*crtc_state), GFP_KERNEL); + struct drm_plane_state p; + u32 shown_w, shown_h; + int ret; + + KUNIT_ASSERT_NOT_NULL(test, plane); + KUNIT_ASSERT_NOT_NULL(test, crtc); + KUNIT_ASSERT_NOT_NULL(test, fb); + KUNIT_ASSERT_NOT_NULL(test, crtc_state); + fb->width = c->fb_w; + fb->height = c->fb_h; + crtc_state->crtc = crtc; + crtc_state->enable = true; + crtc_state->mode.hdisplay = c->hdisplay; + crtc_state->mode.vdisplay = c->vdisplay; + p = (struct drm_plane_state) { + .plane = plane, .crtc = crtc, .fb = fb, + .rotation = DRM_MODE_ROTATE_0, + .crtc_x = c->crtc_x, .crtc_y = c->crtc_y, + .crtc_w = c->crtc_w, .crtc_h = c->crtc_h, + .src_x = c->src_x << 16, .src_y = c->src_y << 16, + .src_w = (c->src_w << 16) + c->src_w_frac, + .src_h = c->src_h << 16, + }; + /* As apple_plane_atomic_check() runs it, before the CRTC is checked. */ + ret = drm_atomic_helper_check_plane_state(&p, crtc_state, + DRM_PLANE_NO_SCALING / 2, + DRM_PLANE_NO_SCALING * 4, + true, true); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_ASSERT_TRUE(test, p.visible); + + KUNIT_EXPECT_EQ(test, dcp_v14_plane_fits_mode(&p, c->hdisplay, c->vdisplay, + c->external), c->fits); + if (!c->fits) + return; + /* What iomfb_v14_7_flush() hands the presenter. */ + dcp_v14_plane_scanout_size(&p, c->external, &shown_w, &shown_h); + KUNIT_EXPECT_EQ(test, shown_w, c->shown_w); + KUNIT_EXPECT_EQ(test, shown_h, c->shown_h); +} + +static struct kunit_case v14_plane_test_cases[] = { + KUNIT_CASE_PARAM(v14_plane_fits_mode, v14_plane_gen_params), + {} +}; + +static struct kunit_suite v14_plane_test_suite = { + .name = "apple-dcp-v14-plane", + .test_cases = v14_plane_test_cases, +}; + +kunit_test_suite(v14_plane_test_suite); diff --git a/drivers/gpu/drm/apple/version_utils.h b/drivers/gpu/drm/apple/version_utils.h index 8cf36e39d3f247..47a96e36eec3f4 100644 --- a/drivers/gpu/drm/apple/version_utils.h +++ b/drivers/gpu/drm/apple/version_utils.h @@ -10,7 +10,7 @@ #define DCP_FW_UNION(u) (u).DCP_FW #define DCP_FW_SUFFIX CONCATENATE(_, DCP_FW) #define DCP_FW_NAME(name) CONCATENATE(name, DCP_FW_SUFFIX) -#define DCP_FW_VERSION(x, y, z) ( ((x) << 16) | ((y) << 8) | (z) ) +#define DCP_FW_VERSION(x, y, z) (((x) << 16) | ((y) << 8) | (z)) /* * 26.x firmware exists in two unrelated wire lineages. The H17-generation @@ -62,6 +62,12 @@ enum dcp_firmware_version { */ DCP_FIRMWARE_V_26_6_DESKTOP, DCP_FIRMWARE_V_27_0, + /* + * A DCP driven through its firmware's iBoot interface alone + * (disp0-service, dispext-service; see ibootep.c), not through + * IOMFB: the T8152 one. + */ + DCP_FIRMWARE_IBOOT, }; #endif /*__APPLE_VERSION_UTILS_H__*/ diff --git a/drivers/gpu/drm/asahi/Kconfig b/drivers/gpu/drm/asahi/Kconfig index d383802ee8825f..7666284ed97363 100644 --- a/drivers/gpu/drm/asahi/Kconfig +++ b/drivers/gpu/drm/asahi/Kconfig @@ -29,7 +29,7 @@ config DRM_ASAHI be called aurora. It keeps "asahi" as a module alias. config DRM_ASAHI_G16 - bool "Apple M4 (G16G) support" + bool "Apple M4 (G16G) and M3 Pro (G15S 27.2) support" depends on DRM_ASAHI && ARM64 depends on DRM_APPLE=y || (DRM_APPLE=m && DRM_ASAHI=m) depends on DRM_APPLE_DCP_T8132 @@ -38,18 +38,19 @@ config DRM_ASAHI_G16 depends on THERMAL_OF default y help - Backend for the M4 (T8132) GPU running the 25G83 firmware of - macOS 26.6.2, which the boot loader leaves loaded. The driver - binds when the GPU node appears and starts the firmware once the - PMP supplier, and a native display the boot loader handed over, - are up. The firmware session is retained until reboot and stays - running across suspend-to-idle. + Shared backend for the M4 (T8132) GPU on firmware 25G83 or + 26B123 and the M3 Pro (T6030) GPU on 26B123. The boot loader + leaves the firmware loaded and publishes its handoff. A native + display, if handed over, starts before the GPU. T8132 also + retains its PMP supplier. The firmware session is retained until + reboot and stays running across suspend-to-idle. A rendering VM pins about 0.7 GiB. An aborted receipt disables that command class until reboot. config DRM_ASAHI_G18 bool "Apple M6 (G18G, T8152) support (experimental)" depends on DRM_ASAHI && ARM64 + depends on APPLE_CLPC=y || APPLE_CLPC=DRM_ASAHI || APPLE_CLPC=n select WANT_DEV_COREDUMP help Backend for the Mac mini M6 (J873) GPU and its 26A428 firmware. @@ -79,11 +80,21 @@ config DRM_ASAHI_DEBUG_ALLOCATOR Say N unless you are debugging firmware structures or porting to a new firmware version. +config DRM_ASAHI_UAT_ADOPTION + bool + help + The firmware UAT handoff adoption shared by the G15 backend and the + T8122 runtime (g15/uat.rs, g15/regs.rs). + config DRM_ASAHI_M3_T8122 bool "M3 MacBook Air GPU runtime (T8122, 14.8.3 firmware)" depends on DRM_ASAHI - # The runtime adopts the firmware's UAT through the G15 backend's handoff helpers. - depends on DRM_ASAHI_G15 + # The runtime adopts the firmware's UAT as the G15 backend does, without + # needing that backend: M3 Pro/Max keep their own setting. + # Its PMP votes call apple-pmp directly (m3_device.rs). + depends on APPLE_PMP=y || (APPLE_PMP=m && DRM_ASAHI=m) + select DRM_ASAHI_UAT_ADOPTION + select APPLE_T8122_GPU_PMP_LINK select CRYPTO_LIB_SHA256 default n help @@ -95,12 +106,25 @@ config DRM_ASAHI_M3_T8122 boards and firmware do not gain automatic admission. Other GPUs are not affected. +config DRM_ASAHI_G14_V27_2 + bool "Apple G14G on GPU firmware 27.2" + depends on DRM_ASAHI + # The firmware's UAT is adopted through the G15 backend's handoff helpers. + depends on DRM_ASAHI_G15 + default y + help + Start an M2 GPU (G14G) whose boot loader reports GPU firmware + 27.2, and register a DRM device on it. Clients use + the shared submission interface for compute and rendering. + Other GPUs and firmware versions are not affected. + config DRM_ASAHI_G15 bool "Apple M3 Pro/Max (G15) support" depends on DRM_ASAHI depends on DRM_APPLE=y || (DRM_APPLE=m && DRM_ASAHI=m) select APPLE_T6030_GPU_PMP_LINK select CRYPTO_LIB_SHA256 + select DRM_ASAHI_UAT_ADOPTION default y help Backend for the M3 Pro (T6030) and M3 Max (T6031) GPUs on the diff --git a/drivers/gpu/drm/asahi/Makefile b/drivers/gpu/drm/asahi/Makefile index e8d4ccb27f2100..238ea2207db79f 100644 --- a/drivers/gpu/drm/asahi/Makefile +++ b/drivers/gpu/drm/asahi/Makefile @@ -5,8 +5,10 @@ aurora-y := asahi_core.o fwid.o legacy_sched.o sysfs.o user_pages.o g17/sync_inp CFLAGS_g17/trace.o := -I$(src)/g17 aurora-$(CONFIG_DRM_ASAHI_G15) += g15/glue.o +aurora-$(CONFIG_DRM_ASAHI_UAT_ADOPTION) += g15/uat_glue.o aurora-$(CONFIG_DRM_ASAHI_G16) += g16/glue.o -aurora-y += retain.o cpu_capacity.o g17/mesh_tvb_floor.o g17/mesh_exclusion.o +aurora-y += retain.o sleep_pd.o cpu_capacity.o g17/mesh_tvb_floor.o g17/mesh_exclusion.o rtkit_dump.o aurora-$(CONFIG_DRM_ASAHI_G18) += g18/sync_input.o +aurora-$(CONFIG_DRM_ASAHI_G18) += g18/demand.o diff --git a/drivers/gpu/drm/asahi/alloc.rs b/drivers/gpu/drm/asahi/alloc.rs index 10e367b1a15fae..d2f46dc0c9c76e 100644 --- a/drivers/gpu/drm/asahi/alloc.rs +++ b/drivers/gpu/drm/asahi/alloc.rs @@ -674,7 +674,13 @@ impl RawAllocation for HeapAllocation { struct HeapAllocatorInner { dev: AsahiDevRef, allocated: usize, - backing_objects: KVec<(crate::gem::ObjectRef, mmu::KernelMapping, u64)>, + /// Each block, its mapping, its GPU address and, for a client VM, its charge. + backing_objects: KVec<( + crate::gem::ObjectRef, + mmu::KernelMapping, + u64, + Option, + )>, garbage: Option>>, total_garbage: usize, name: CString, @@ -789,7 +795,19 @@ impl HeapAllocator { ); } - let mut obj = crate::gem::new_kernel_object(&self.dev, size_aligned)?; + // A client VM's heap grows with what the client submits (scene buffers are sized + // from its render targets), so its blocks count against that client's limit, like + // the client's own objects, and not as kernel memory. + let (mut obj, charge) = match self.vm.memory_client() { + Some(client) => { + let commit = crate::memacct::LEDGER.admit(client, size_aligned as u64)?; + let obj = crate::gem::new_kernel_object_user_charged(&self.dev, size_aligned)?; + let charge = crate::memacct::Charge::user(commit, None); + charge.set_held(true); + (obj, Some(charge)) + } + None => (crate::gem::new_kernel_object(&self.dev, size_aligned)?, None), + }; if self.cpu_maps && debug_enabled(DebugFlags::FillAllocations) { let obj_size = obj.size(); if let Ok(vmap) = obj.vmap() { @@ -868,7 +886,7 @@ impl HeapAllocator { self.mm.with_inner(|inner| { inner .backing_objects - .push((obj, mapping, gpu_ptr), GFP_KERNEL) + .push((obj, mapping, gpu_ptr, charge), GFP_KERNEL) })?; self.top = new_top; diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index b9706916510321..f0af56b1377a42 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -17,6 +17,10 @@ mod fw; mod fwid; #[cfg(CONFIG_DRM_ASAHI_G15)] mod g15; +// Without the G15 backend, only the UAT adoption the T8122 runtime shares with it. +#[cfg(all(CONFIG_DRM_ASAHI_UAT_ADOPTION, not(CONFIG_DRM_ASAHI_G15)))] +#[path = "g15/adopt.rs"] +mod g15; mod g17; mod gem; @@ -27,6 +31,12 @@ mod g18; #[cfg(CONFIG_DRM_ASAHI_M5)] mod m5; mod gpu; +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +mod g14_v27_2; +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +mod g14_v27_2_abi; +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +mod g14_v27_2_render; mod hw; mod initdata; mod m3; @@ -49,8 +59,6 @@ mod sysfs_exports; mod timestamp; mod usage; mod util; -#[cfg(CONFIG_DRM_ASAHI_MAPLE_TREE)] -mod vm; mod workqueue; use kernel::prelude::*; @@ -105,6 +113,8 @@ impl kernel::InPlaceModule for DriverModule { unsafe { queue_share::init() }; // SAFETY: Module init runs once, before either adapter is registered below. unsafe { g17::exec_share::init() }; + // SAFETY: Module init runs once, before either adapter is registered below. + unsafe { g17::init() }; try_pin_init!(Self { // Initialize the queue first, before registration can invoke probe. _cleanup: cleanup::QueueOwner::new()?, @@ -262,7 +272,7 @@ module! { description: "G16: compute completion-stamp deadline, ms (0 permits unbounded compute; firmware recovery stays active)", }, g16_repoll_us: u32 { - default: 15, + default: 8, description: "G16: repoll interval while publication waits for record consumption, us", }, g16_resnap_us: u32 { diff --git a/drivers/gpu/drm/asahi/buffer.rs b/drivers/gpu/drm/asahi/buffer.rs index 314087edcd3a9f..7a19153a9096f9 100644 --- a/drivers/gpu/drm/asahi/buffer.rs +++ b/drivers/gpu/drm/asahi/buffer.rs @@ -289,6 +289,71 @@ impl Drop for Scene::ver { } } +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +impl SceneG14V13_5 { + pub(crate) fn render_addresses(&self) -> (u64, u64) { + self.object.with(|raw, _| (raw.user_buffer.or(0).into(), raw.stats.into())) + } + + /// Zeroes the first `bytes` of the Tail Pointer Cache, so that a fragment pass run after + /// a firmware recovery stopped its tiler finds no tiles. + /// + /// # Safety + /// + /// The GPU must not access the TPC during the call (its tiler is stopped and no other + /// render using this buffer is in flight), and no CPU reference into it may be live. + pub(crate) unsafe fn clear_tpc(&self, bytes: usize) -> Result { + // SAFETY: forwarded from the caller. + unsafe { self.object.tpc.zero_prefix(bytes) } + } +} + +/// Host-owned parameter-buffer inputs that persist across firmware submissions. +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +pub(crate) struct ParameterBufferInfo { + pub(crate) page_list: u64, + pub(crate) page_list_size: u32, + pub(crate) max_blocks: u32, + pub(crate) block_list: u64, + pub(crate) block_control: u64, + pub(crate) block_size: u32, + pub(crate) counter: u64, + pub(crate) max_pages: u32, + pub(crate) max_linear_pages: u32, +} + +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +impl BufferG14V13_5 { + pub(crate) fn parameter_info(&self) -> ParameterBufferInfo { + self.inner.lock().info.with(|raw, inner| ParameterBufferInfo { + page_list: inner.page_list.gpu_va().get(), + page_list_size: raw.page_list_size, + max_blocks: raw.max_blocks, + block_list: inner.block_list.gpu_va().get(), + block_control: inner.block_ctl.gpu_va().get(), + block_size: raw.block_size, + counter: inner.counter.gpu_va().get(), + max_pages: raw.max_pages, + max_linear_pages: raw.max_pages_nomemless, + }) + } + + pub(crate) fn increment_parameter_counter(&self) { + self.increment(); + let inner = self.inner.lock(); + inner.info.counter.with(|raw, _| { + crate::pgtable::clean_poc(core::ptr::from_ref(raw).cast(), core::mem::size_of_val(raw)); + }); + crate::pgtable::poc_barrier(); + } + + /// The 27.2 firmware owns the page list once bound. Publish only new block descriptors + /// and the block-control producer, using the legacy manager for backing allocation. + pub(crate) fn ensure_parameter_blocks(&self, count: usize) -> Result { + self.ensure_blocks_inner(count, false, true) + } +} + /// Inner data for a single TVB buffer object. #[versions(AGX)] struct BufferInner { @@ -318,6 +383,13 @@ pub(crate) struct Buffer { inner: Arc>, } +/// Address space in which the parameter-buffer lists are visible to their consumers. +pub(crate) enum ParameterListPlacement { + VmPrivate, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + KernelGpu, +} + #[versions(AGX)] impl Buffer::ver { /// Create a new Buffer for a given VM, given the per-VM allocators. @@ -327,6 +399,7 @@ impl Buffer::ver { ualloc: Arc>, ualloc_priv: Arc>, mgr: &BufferManager::ver, + list_placement: ParameterListPlacement, ) -> Result { // These are the typical max numbers on macOS. // 8GB machines have this halved. @@ -349,19 +422,33 @@ impl Buffer::ver { let preempt2_size = num_clusters_adj * gpu.get_cfg().preempt2_size; let preempt3_size = num_clusters_adj * gpu.get_cfg().preempt3_size; + let (page_list, block_list) = { + let mut vm_private; + let lists = match list_placement { + ParameterListPlacement::VmPrivate => { + vm_private = ualloc_priv.lock(); + &mut *vm_private + } + // The lists live in the kernel half of the UAT so the firmware can rebuild them. + // The parameter manager writes them while the render engines run, so the GPU + // mapping must be writable: a read-only mapping leaves a stalled write fault + // that blocks the context flush after the render and every later completion. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + ParameterListPlacement::KernelGpu => &mut alloc.gpu, + }; + ( + lists.array_empty_tagged(max_pages, b"PLST")?, + lists.array_empty_tagged(max_blocks * 2, b"BLST")?, + ) + }; let shared = &mut alloc.shared; let info = alloc.private.new_init( - { - let ualloc_priv = &ualloc_priv; - try_init!(buffer::Info::ver { - block_ctl: shared.new_default::()?, - counter: shared.new_default::()?, - page_list: ualloc_priv.lock().array_empty_tagged(max_pages, b"PLST")?, - block_list: ualloc_priv - .lock() - .array_empty_tagged(max_blocks * 2, b"BLST")?, - }) - }, + try_init!(buffer::Info::ver { + block_ctl: shared.new_default::()?, + counter: shared.new_default::()?, + page_list, + block_list, + }), |inner, _p| { try_init!(buffer::raw::Info::ver { gpu_counter: 0x0, @@ -486,16 +573,18 @@ impl Buffer::ver { /// The buffer manager owns the buffer while scenes on it are in flight, so the new size is only /// published if no scene is active. pub(crate) fn ensure_blocks(&self, min_blocks: usize) -> Result { - self.ensure_blocks_inner(min_blocks, false) + self.ensure_blocks_inner(min_blocks, false, false) } /// [`Self::ensure_blocks`] for a caller that guarantees all work that used this buffer has /// completed: the new size is published although scenes of completed jobs may still be held. pub(crate) fn ensure_blocks_idle(&self, min_blocks: usize) -> Result { - self.ensure_blocks_inner(min_blocks, true) + self.ensure_blocks_inner(min_blocks, true, false) } - fn ensure_blocks_inner(&self, min_blocks: usize, fw_idle: bool) -> Result { + fn ensure_blocks_inner( + &self, min_blocks: usize, fw_idle: bool, firmware_pages: bool, + ) -> Result { let mut inner = self.inner.lock(); let cur_count = inner.blocks.len(); @@ -529,18 +618,29 @@ impl Buffer::ver { .push(block, GFP_KERNEL) .expect("push() failed after reserve()"); inner.info.block_list[2 * (cur_count + i)] = page_num; - for j in 0..PAGES_PER_BLOCK { - inner.info.page_list[(cur_count + i) * PAGES_PER_BLOCK + j] = page_num + j as u32; + if !firmware_pages { + for j in 0..PAGES_PER_BLOCK { + inner.info.page_list[(cur_count + i) * PAGES_PER_BLOCK + j] = page_num + j as u32; + } } } + if firmware_pages { + let added = &inner.info.block_list.as_slice()[2 * cur_count..2 * new_count]; + crate::pgtable::clean_poc(added.as_ptr().cast(), core::mem::size_of_val(added)); + crate::pgtable::poc_barrier(); + } inner.info.block_ctl.with(|raw, _inner| { raw.total.store(new_count as u32, Ordering::SeqCst); raw.wptr.store(new_count as u32, Ordering::SeqCst); + if firmware_pages { + crate::pgtable::clean_poc(core::ptr::from_ref(raw).cast(), core::mem::size_of_val(raw)); + crate::pgtable::poc_barrier(); + } }); /* Only do this update if the buffer manager is idle (which means we own it) */ - if inner.active_scenes == 0 || fw_idle { + if !firmware_pages && (inner.active_scenes == 0 || fw_idle) { let page_count = (new_count * PAGES_PER_BLOCK) as u32; inner.info.with(|raw, _inner| { raw.page_count.store(page_count, Ordering::Relaxed); diff --git a/drivers/gpu/drm/asahi/cleanup.rs b/drivers/gpu/drm/asahi/cleanup.rs index 52436b40304c03..4e4e95c5729b96 100644 --- a/drivers/gpu/drm/asahi/cleanup.rs +++ b/drivers/gpu/drm/asahi/cleanup.rs @@ -84,6 +84,9 @@ impl WorkItem for Item { pub(crate) struct Deferred(Option>>>); impl Deferred { + /// Heap bytes one deferred value takes: the value and its release work item. + pub(crate) const HEAP_BYTES: usize = core::mem::size_of::>(); + pub(crate) fn new(value: T) -> Result { let item = KBox::pin_init( pin_init!(Item { diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 77ffd32891cd2b..4ca274e2be4064 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -53,6 +53,9 @@ pub(crate) struct AsahiPlatformDriverData<'bound> { #[cfg(CONFIG_DRM_ASAHI_G16)] pub(crate) g16: Option>, m3: Option, + /// The G14 firmware-27.2 backend, whose firmware must be stopped on unbind. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + g14_v27_2: Option>, /// Raw `struct device *` of the platform device. Stored once at probe /// time so the `Drop` impl can find the sysfs file on unregister. raw_dev: *mut bindings::device, @@ -150,6 +153,7 @@ impl drm::driver::Driver for AsahiDrmDriver { /// Firmware interface selected by the hardware compatible. pub(crate) enum ProbeConfig { Legacy(&'static hw::HwConfig), + LegacyWithG14Handoff(&'static hw::HwConfig), G17(&'static g17::Config), /// M5 Pro, Max and Ultra: the ID registers select the configuration. G17M5, @@ -193,11 +197,11 @@ macro_rules! asahi_of_device_table { ), ( of::DeviceId::new(c"apple,agx-t8103"), - ProbeConfig::Legacy(&hw::t8103::HWCONFIG) + ProbeConfig::LegacyWithG14Handoff(&hw::t8103::HWCONFIG) ), ( of::DeviceId::new(c"apple,agx-t8112"), - ProbeConfig::Legacy(&hw::t8112::HWCONFIG) + ProbeConfig::LegacyWithG14Handoff(&hw::t8112::HWCONFIG) ), ( of::DeviceId::new(c"apple,agx-t6000"), @@ -267,22 +271,61 @@ unsafe fn sleep_data<'a>(dev: *mut bindings::device) -> &'a AsahiPlatformDriverD /// Runs before any device suspends, so the GPU goes first and work still in flight can finish. unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_int { + // SAFETY: Called by the PM core. + let data = unsafe { sleep_data(dev) }; + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + if let Some(backend) = data.g14_v27_2.as_ref() { + // SAFETY: Reads a global flag word. + let deep = unsafe { bindings::pm_suspend_via_firmware() }; + return kernel::error::from_result(|| backend.sleep_prepare(deep).map(|_| 0)); + } // SAFETY: Reads a global flag word. if !unsafe { bindings::pm_suspend_via_firmware() } { return 0; } - // SAFETY: Called by the PM core. - let data = unsafe { sleep_data(dev) }; match data.g17.as_ref() { Some(gpu) => kernel::error::from_result(|| gpu.sleep_prepare().map(|_| 0)), None => EBUSY.to_errno(), } } +extern "C" { + fn asahi_sleep_pd_init(dev: *mut core::ffi::c_void) -> core::ffi::c_int; + fn asahi_sleep_pd_suspend_noirq(dev: *mut core::ffi::c_void) -> core::ffi::c_int; + fn asahi_sleep_pd_resume_noirq(dev: *mut core::ffi::c_void) -> core::ffi::c_int; +} + +/// Allocates per-device suspend-to-idle power-domain hold state tied to `dev`'s binding. +fn sleep_pd_init(dev: &kernel::device::Device>) -> Result { + // SAFETY: `dev` is being probed, so attaching devres state to its raw device is valid. + kernel::error::to_result(unsafe { asahi_sleep_pd_init(dev.as_raw().cast()) }) +} + +/// Holds the GPU's attached power domain across suspend-to-idle while its firmware stays live. +pub(crate) unsafe extern "C" fn sleep_suspend_noirq( + dev: *mut bindings::device, +) -> core::ffi::c_int { + // SAFETY: Called by the PM core with a bound GPU device. + unsafe { asahi_sleep_pd_suspend_noirq(dev.cast()) } +} + +/// Releases any suspend-to-idle power-domain hold taken by [`sleep_suspend_noirq`]. +pub(crate) unsafe extern "C" fn sleep_resume_noirq( + dev: *mut bindings::device, +) -> core::ffi::c_int { + // SAFETY: Called by the PM core with a bound GPU device. + unsafe { asahi_sleep_pd_resume_noirq(dev.cast()) } +} + /// Runs after every device resumed. Does nothing unless [`sleep_prepare`] stopped the firmware. unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { // SAFETY: Called by the PM core. - if let Some(gpu) = unsafe { sleep_data(dev) }.g17.as_ref() { + let data = unsafe { sleep_data(dev) }; + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + if let Some(backend) = data.g14_v27_2.as_ref() { + backend.sleep_complete(); + } + if let Some(gpu) = data.g17.as_ref() { gpu.sleep_complete(); } } @@ -290,6 +333,8 @@ unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { static SLEEP_OPS: SleepOps = SleepOps(bindings::dev_pm_ops { prepare: Some(sleep_prepare), complete: Some(sleep_complete), + suspend_noirq: Some(sleep_suspend_noirq), + resume_noirq: Some(sleep_resume_noirq), // SAFETY: All-zero is the absence of every other callback. ..unsafe { core::mem::zeroed() } }); @@ -306,6 +351,8 @@ unsafe extern "C" fn sleep_refuse(_dev: *mut bindings::device) -> core::ffi::c_i static SLEEP_REFUSE_OPS: SleepOps = SleepOps(bindings::dev_pm_ops { prepare: Some(sleep_refuse), + suspend_noirq: Some(sleep_suspend_noirq), + resume_noirq: Some(sleep_resume_noirq), // SAFETY: All-zero is the absence of every other callback. ..unsafe { core::mem::zeroed() } }); @@ -330,6 +377,8 @@ impl platform::Driver for AsahiPlatformDriver { // parameter set it; a no-op everywhere else. unsafe { bindings::apple_pmp_agx_activity_release() }; if let Some(gpu) = this.g17.as_ref() { + #[cfg(CONFIG_DRM_ASAHI_G18)] + crate::g18::compat::g17p::g17p_unpublish_gfx_data(); // Driver data is dropped after devres, so CPU control must happen in unbind. gpu.shutdown(); } @@ -337,6 +386,10 @@ impl platform::Driver for AsahiPlatformDriver { if let Some(m3) = this.m3.as_ref() { m3.stop(); } + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + if let Some(backend) = this.g14_v27_2.as_ref() { + backend.stop(); + } this.close_binding(); } @@ -353,14 +406,25 @@ impl platform::Driver for AsahiPlatformDriver { dev_info!(pdev.as_ref(), "Probing...\n"); - let cfg = match info.ok_or(ENODEV)? { - ProbeConfig::Legacy(cfg) => *cfg, + let info = info.ok_or(ENODEV)?; + sleep_pd_init(pdev.as_ref())?; + + let (cfg, has_g14_handoff) = match info { + ProbeConfig::Legacy(cfg) => (*cfg, false), + ProbeConfig::LegacyWithG14Handoff(cfg) => (*cfg, true), ProbeConfig::G17(cfg) => { return AsahiPlatformDriver::probe_g17(pdev, regs::G17Resources::new(pdev)?, cfg) } ProbeConfig::G17M5 => return AsahiPlatformDriver::probe_g17_m5(pdev), #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] - ProbeConfig::M3(crate::m3::Chip::T8122) => return AsahiPlatformDriver::probe_t8122(pdev), + ProbeConfig::M3(crate::m3::Chip::T8122) => { + // The shared G16 backend owns the handoffs its T8122 row describes (27.2). + #[cfg(CONFIG_DRM_ASAHI_G16)] + if crate::g16::claims(pdev.as_ref(), &crate::g16::hw::t8122::CONFIG) { + return Err(ENODEV); + } + return AsahiPlatformDriver::probe_t8122(pdev); + } ProbeConfig::M3(chip) => return Err(crate::m3::refuse_probe(pdev, *chip)), #[cfg(CONFIG_DRM_ASAHI_M5)] ProbeConfig::M5 => return AsahiPlatformDriver::probe_m5(pdev), @@ -368,6 +432,26 @@ impl platform::Driver for AsahiPlatformDriver { ProbeConfig::M5 => return Err(ENODEV), }; + let fwnode = pdev.as_ref().fwnode().ok_or(EIO)?; + let compat: KVec = fwnode + .property_read_array_vec(c"apple,firmware-compat", 3)? + .required_by(pdev.as_ref())?; + + // The loader advertises the supported wire layout independently of the image version. + if has_g14_handoff && compat.as_slice() == [27, 2, 0] { + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + { + let (registers, writable) = match cfg.gpu_gen { + hw::GpuGen::G13 => (hw::t8103::REGISTERS_V27_2, hw::t8103::WRITABLE_V27_2), + hw::GpuGen::G14 => (hw::t8112::REGISTERS_V27_2, hw::t8112::WRITABLE_V27_2), + _ => return Err(ENODEV), + }; + return AsahiPlatformDriver::probe_g14_v27_2(pdev, cfg, registers, writable); + } + #[cfg(not(CONFIG_DRM_ASAHI_G14_V27_2))] + return Err(ENODEV); + } + // SAFETY: The selected SoC's UAT output width bounds all device DMA. unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(cfg.uat_oas)?)? }; @@ -379,11 +463,6 @@ impl platform::Driver for AsahiPlatformDriver { // Start the coprocessor CPU, so UAT can initialize the handoff regs::Resources::start_cpu(pdev)?; - let fwnode = pdev.as_ref().fwnode().ok_or(EIO)?; - let compat: KVec = fwnode - .property_read_array_vec(c"apple,firmware-compat", 3)? - .required_by(pdev.as_ref())?; - let drm = drm::UnregisteredDevice::::new(pdev, Ok(()))?; // SAFETY: Every adapter calls close_binding in unbind before devres; // probe errors drop this local owner while the bound callback is live. @@ -449,6 +528,8 @@ impl platform::Driver for AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev, @@ -461,11 +542,53 @@ impl platform::Driver for AsahiPlatformDriver { } impl AsahiPlatformDriver { + /// G14 with firmware 27.2: start the firmware and register its DRM device. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + fn probe_g14_v27_2<'bound>( + pdev: &'bound platform::Device>, + cfg: &'static hw::HwConfig, + registers: &'static [hw::RegisterV27_2], + writable: u64, + ) -> Result> { + let crate::g14_v27_2::Started { backend, drm, binding, resources } = + crate::g14_v27_2::start(pdev, cfg, registers, writable)?; + let gpu = backend.clone() as Arc; + let data = try_pin_init!(AsahiDrmRegistrationData { gpu, resources }); + // SAFETY: The registration is stored in the platform data and unregistered when it is + // dropped, after the backend has stopped the firmware. + let reg = match unsafe { drm::Registration::new(pdev.as_ref(), drm, data, 0) } { + Ok(reg) => reg, + Err(error) => { + backend.stop(); + return Err(error); + } + }; + dev_info!( + pdev.as_ref(), + "{:?} firmware 27.2 running; DRM device registered\n", + cfg.gpu_gen + ); + Ok(AsahiPlatformDriverData { + binding, + _device: reg.device().into(), + _reg: reg, + g17: None, + #[cfg(CONFIG_DRM_ASAHI_G16)] + g16: None, + m3: None, + g14_v27_2: Some(backend), + raw_dev: core::ptr::null_mut(), + raw_stats: core::ptr::null_mut(), + stats: None, + }) + } + #[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) fn probe_g15<'bound>( pdev: &'bound platform::Device>, cfg: &'static crate::g15::Config, ) -> Result> { + sleep_pd_init(pdev.as_ref())?; // SAFETY: Admission checks the SoC and the UAT output width before DMA starts. unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(cfg.uat_oas)?)? }; let resources = regs::Resources::new(pdev)?; @@ -487,6 +610,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev: core::ptr::null_mut(), @@ -529,6 +654,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: Some(backend), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + g14_v27_2: None, raw_dev: core::ptr::null_mut(), raw_stats: core::ptr::null_mut(), stats: None, @@ -599,12 +726,19 @@ impl AsahiPlatformDriver { error ); } + // The G17P firmware DATA diagnostics read only the bound GPU's own data segment. + #[cfg(CONFIG_DRM_ASAHI_G18)] + if cfg.identity.gpu_variant == hw::GpuVariant::P { + crate::g18::compat::g17p::g17p_publish_gfx_data(pdev.as_ref()); + } Ok(AsahiPlatformDriverData { binding, _device: reg.device().into(), _reg: reg, g17: Some(gpu), m3: None, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev, @@ -652,6 +786,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev: core::ptr::null_mut(), @@ -667,6 +803,7 @@ impl AsahiPlatformDriver { pdev: &'bound platform::Device>, cfg: &'static crate::g16::Config, ) -> Result> { + sleep_pd_init(pdev.as_ref())?; // SAFETY: the qualified UAT output width constrains this device's DMA. unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(cfg.uat_oas)?)? }; let resources = regs::Resources::new(pdev)?; @@ -691,6 +828,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + g14_v27_2: None, g16: Some(gpu), raw_dev, raw_stats, @@ -747,6 +886,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev: core::ptr::null_mut(), @@ -773,6 +914,8 @@ impl Drop for AsahiPlatformDriverData<'_> { } drop(self.stats.take()); if let Some(gpu) = self.g17.as_ref() { + #[cfg(CONFIG_DRM_ASAHI_G18)] + crate::g18::compat::g17p::g17p_unpublish_gfx_data(); // Also covers failure to allocate platform driver data after the probe body returned. gpu.shutdown(); } @@ -780,5 +923,9 @@ impl Drop for AsahiPlatformDriverData<'_> { if let Some(m3) = self.m3.as_ref() { m3.stop(); } + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + if let Some(backend) = self.g14_v27_2.as_ref() { + backend.stop(); + } } } diff --git a/drivers/gpu/drm/asahi/event.rs b/drivers/gpu/drm/asahi/event.rs index edd7d701e665cd..28e70c2fb09f75 100644 --- a/drivers/gpu/drm/asahi/event.rs +++ b/drivers/gpu/drm/asahi/event.rs @@ -54,6 +54,11 @@ pub(crate) type Event = slotalloc::Guard; pub(crate) struct EventValue(u32); impl EventValue { + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + pub(crate) fn raw(self) -> u32 { + self.0 + } + /// Returns the `EventValue` that succeeds this one. pub(crate) fn next(&self) -> EventValue { EventValue(self.0.wrapping_add(0x100)) @@ -119,6 +124,14 @@ impl EventInner { // keeps the GpuObject the stamp is contained within alive. EventValue(unsafe { &*self.stamp }.load(Ordering::Acquire)) } + + /// Read a completion stamp written by an agent outside the CPU coherency domain. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + pub(crate) fn current_noncoherent(&self) -> EventValue { + crate::pgtable::clean_invalidate_poc(self.stamp.cast(), core::mem::size_of::()); + crate::pgtable::poc_barrier(); + self.current() + } } impl slotalloc::SlotItem for EventInner { @@ -199,6 +212,24 @@ impl EventManager { Ok(ev) } + /// Make freshly initialized stamps visible before a non-coherent firmware starts. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + pub(crate) fn sync_initial_stamps(&self) { + self.alloc.with_inner(|inner| { + let stamps = inner.stamps.as_slice(); + let fw_stamps = inner.fw_stamps.as_slice(); + crate::pgtable::clean_poc(stamps.as_ptr().cast(), core::mem::size_of_val(stamps)); + crate::pgtable::clean_poc(fw_stamps.as_ptr().cast(), core::mem::size_of_val(fw_stamps)); + }); + crate::pgtable::poc_barrier(); + } + + /// Reserve the normal stamp pair for a kernel queue that polls its own completion. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + pub(crate) fn try_get_polled(&self) -> Result { + self.alloc.try_get(None) + } + /// Signals an event by slot, indicating completion (of one or more commands). pub(crate) fn signal(&self, slot: u32) { match self diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index b69834163d5b92..dab076bc63ee60 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -94,6 +94,9 @@ pub(crate) const DRM_ASAHI_RENDER_SHADER_WRITES: u32 = /// (DRM_ASAHI_RENDER_STAGE_PREFIXES), as the complete struct drm_asahi_cmd_render_m5. pub(crate) const DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2: u64 = uapi::DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2 as u64; +/// Render commands accept tile buffers of up to 48 KiB. +pub(crate) const DRM_ASAHI_FEATURE_TILE_BUFFER_48K: u64 = + uapi::DRM_ASAHI_FEATURE_TILE_BUFFER_48K as u64; /// Compute commands may declare a stream that ends with a memory-scoped flush /// (DRM_ASAHI_COMPUTE_VISIBLE_COMPLETION). pub(crate) const DRM_ASAHI_FEATURE_COMPUTE_VISIBLE_COMPLETION: u64 = @@ -106,6 +109,10 @@ pub(crate) const DRM_ASAHI_COMPUTE_VISIBLE_COMPLETION: u32 = /// (`drm_asahi_queue_create::compute_timeout_ms`). pub(crate) const DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT: u64 = uapi::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT as u64; +/// The kernel spreads one compute queue's independent commands over several firmware compute +/// queues itself. +pub(crate) const DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL: u64 = + uapi::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL as u64; /// The tiling half waits only on the render and compute prefixes of the command's stage-prefix /// fields, its fragment half on the whole ones. #[allow(dead_code)] @@ -134,10 +141,11 @@ pub(crate) const DRM_ASAHI_RENDER_PROGRAM_TASK: u32 = uapi::DRM_ASAHI_RENDER_PRO #[allow(dead_code)] pub(crate) const DRM_ASAHI_COMPUTE_USES_MATRIX: u32 = uapi::drm_asahi_compute_flags_DRM_ASAHI_COMPUTE_USES_MATRIX as u32; -/// The compute command neither copies nor resets queries, so it cannot observe -/// timestamps the host publishes after earlier commands complete -/// (DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS). Accepted, and reported with -/// DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS by the G17 command sets. +/// The compute command reads and writes no timestamp or availability word whose +/// host publication is still pending for an earlier command, so it need not wait +/// for that publication (DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS). It may copy or reset +/// queries whose words are already published. Accepted, and reported with +/// DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS, by the G17 command sets. pub(crate) const DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS: u32 = uapi::drm_asahi_compute_flags_DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS as u32; @@ -166,41 +174,20 @@ impl Drop for Vm { // object must not outlive the client's VM handle. status.release_mirror(); } - if self.vm.status().is_some() { - // Tracked jobs can outlive their file's VM handle. Their last guard performs - // these unmaps once no accepted work can still dereference the mappings. - if let Err(error) = self - .vm - .unmap_user_ranges(self.user_range.clone(), self.kernel_range.clone()) - { - pr_err!("Vm::Drop: deferred user unmap failed: {:?}\n", error); - } - self.vm.bo_deferred_cleanup(); - self.gpu.vm_closed(&self.vm); - return; - } - // When the user Vm is dropped, verify that no user mappings exists. - let left_range = self.user_range.start..self.kernel_range.start; - let right_range = self.kernel_range.end..self.user_range.end; - - if !left_range.is_empty() - && self - .vm - .unmap_range(None, left_range.start, left_range.range()) - .is_err() - { - pr_err!("Vm::Drop: vm.unmap_range() failed\n"); - } - if !right_range.is_empty() - && self - .vm - .unmap_range(None, right_range.start, right_range.range()) - .is_err() + // Tracked jobs can outlive their file's VM handle: their last guard runs the + // teardown once no accepted work can still dereference the mappings. On + // untracked VMs this unmaps every user GPUVA at once without allocating or + // charging split nodes, so teardown succeeds even at the client's memory limit. + if let Err(error) = self + .vm + .unmap_user_ranges(self.user_range.clone(), self.kernel_range.clone()) { - pr_err!("Vm::Drop: vm.unmap_range() failed\n"); + pr_err!("Vm::Drop: user unmap failed: {:?}\n", error); } - self.vm.bo_deferred_cleanup(); + if self.vm.status().is_some() { + self.gpu.vm_closed(&self.vm); + } } } @@ -290,38 +277,51 @@ impl SyncItem { in_count: u32, out_count: u32, allow_cumulative: bool, - ) -> Result> { + ) -> Result> { let count = in_count.checked_add(out_count).ok_or(EOVERFLOW)?; const STRIDE: usize = core::mem::size_of::(); + const CHUNK: usize = 8; let size = STRIDE.checked_mul(count as usize).ok_or(EOVERFLOW)?; - let mut vec = KVec::with_capacity(count as usize, GFP_KERNEL)?; + // Userspace sets the count. Charge the allocation to the caller and + // allow noncontiguous backing pages. + let mut vec = KVVec::with_capacity(count as usize, GFP_KERNEL_ACCOUNT)?; let mut anchor = None; - // Read each record once so validation and use see the same retained bytes. + // Read each record once in small stack chunks so validation and use see the + // same retained bytes without a per-entry copy_from_user. let mut reader = UserSlice::new(UserPtr::from_addr(ptr as usize), size).reader(); + let mut buf = MaybeUninit::<[uapi::drm_asahi_sync; CHUNK]>::uninit(); - for i in 0..count { - let mut sync: MaybeUninit = MaybeUninit::uninit(); + let mut base = 0u32; + while base < count { + let chunk = ((count - base) as usize).min(CHUNK); + let raw = buf.as_mut_ptr().cast::(); - // SAFETY: The size of `sync` is STRIDE + // SAFETY: `buf` holds `CHUNK` contiguous `drm_asahi_sync` entries and + // `chunk <= CHUNK`, so `chunk * STRIDE` bytes are writable. reader.read_raw(unsafe { - core::slice::from_raw_parts_mut(sync.as_mut_ptr().cast::>(), STRIDE) + core::slice::from_raw_parts_mut(raw.cast::>(), chunk * STRIDE) })?; - // SAFETY: All bit patterns in the struct are valid - let sync = unsafe { sync.assume_init() }; + for offset in 0..chunk { + let i = base + offset as u32; + // SAFETY: `read_raw` initialized `chunk` contiguous entries starting at `raw`, + // `offset < chunk`, and all bit patterns in the struct are valid. + let sync = unsafe { raw.add(offset).read() }; - if sync.sync_type == crate::g17::sync_output::SYNC_CUMULATIVE { - if !allow_cumulative || i < in_count || anchor.is_some() { - return Err(EINVAL); + if sync.sync_type == crate::g17::sync_output::SYNC_CUMULATIVE { + if !allow_cumulative || i < in_count || anchor.is_some() { + return Err(EINVAL); + } + anchor = Some(i as usize); } - anchor = Some(i as usize); + vec.push( + Self::parse_one(file, sync, i >= in_count, allow_cumulative)?, + GFP_KERNEL_ACCOUNT, + )?; } - vec.push( - Self::parse_one(file, sync, i >= in_count, allow_cumulative)?, - GFP_KERNEL, - )?; + base += chunk as u32; } if let Some(anchor) = anchor { let bundle = crate::g17::sync_output::SignalBundle::new( @@ -343,16 +343,79 @@ impl SyncItem { #[derive(Clone)] pub(crate) enum Object { - TimestampBuffer(Arc), + TimestampBuffer(Arc), +} + +/// Kernel memory one `GEM_BIND_OBJECT` bind keeps that no GEM object accounts for: its table entry +/// and the bound buffer's records (an `Arc` count, the [`crate::timestamp::Bound`] and the +/// buffer's heap records). The object's pages and its CPU mapping, which the shmem helper shares +/// between every vmap of one object, belong to the object and are charged when it is created. +/// Each bind is charged this much against the client's and the device's memory limits, as a user +/// object of that size would be, so a file's binds are bounded by those limits. +const BOUND_OBJECT_BYTES: u64 = (core::mem::size_of::() + + core::mem::size_of::() + + core::mem::size_of::() + + crate::timestamp::Buffer::HEAP_BYTES) as u64; + +/// The firmware timestamp window is one fixed range per device that every file's firmware-aliased +/// timestamp buffers share. A file may hold at most this fraction of it (4 MiB of a 64 MiB +/// window), so one client cannot fill it for every other: Mesa binds one small buffer per GL +/// context, one per timestamped query pool and one debug buffer. +const TIMESTAMP_WINDOW_SHARE_PER_FILE: u64 = 16; + +/// A file's limit on window bytes for a window of `window_size` bytes (0: no window). +fn window_limit(window_size: u64) -> u64 { + window_size / TIMESTAMP_WINDOW_SHARE_PER_FILE +} + +/// Charges one bind to `client`, or fails with `ENOMEM` and charges nothing. +fn admit_bind( + ledger: &'static memacct::Ledger, + client: &Arc, +) -> Result { + ledger.admit(client, BOUND_OBJECT_BYTES) } /// A queue in a file's table. Its count in the creating process's share of the device's /// queues is given back once the queue itself is gone. pub(crate) struct TableQueue { queue: KBox, + /// Reusable staging buffer for `SUBMIT` command buffers, avoiding per-submit heap + /// allocations and keeping large command buffers off the kernel stack. + cmdbuf: KVVec, _share: Option, } +impl TableQueue { + /// Maximum command-buffer capacity retained on a queue between submissions. + const REUSE_CMDBUF_CAP: usize = 4096; + + /// Takes the cached command-buffer staging allocation so userspace copies run outside the + /// queue mutex (preventing `queue.lock()` -> `mmap_lock` lock-order inversion). + fn take_cmdbuf(&mut self) -> KVVec { + core::mem::take(&mut self.cmdbuf) + } + + /// Returns a cleared command-buffer allocation to the per-queue cache when within the + /// reuse capacity cap; oversized buffers are dropped. + fn return_cmdbuf(&mut self, mut buf: KVVec) { + buf.clear(); + if buf.capacity() > 0 + && buf.capacity() <= Self::REUSE_CMDBUF_CAP + && buf.capacity() >= self.cmdbuf.capacity() + { + self.cmdbuf = buf; + } + } +} + +fn copy_cmdbuf_from_user(buf: &mut KVVec, addr: u64, size: usize) -> Result { + buf.clear(); + UserSlice::new(UserPtr::from_addr(addr as usize), size) + .reader() + .read_all(buf, GFP_KERNEL_ACCOUNT) +} + impl Deref for TableQueue { type Target = dyn queue::Queue; @@ -400,6 +463,18 @@ pub(crate) type DrmFile = drm::File; /// Minimum reserved AS for kernel mappings const VM_KERNEL_MIN_SIZE: u64 = 0x20000000; +/// Most VMs one file may hold at a time. Mesa creates one per file. Each VM holds kernel memory +/// that is not charged to the client (its GPUVM, allocators and per-VM objects). +const MAX_VMS_PER_FILE: u32 = 64; + +/// Takes a slot for a new VM in a file's VM table, or fails with EBUSY past +/// [`MAX_VMS_PER_FILE`], as the ID allocator reports a full range. +fn reserve_vm_slot<'a>( + vms: &'a xarray::XArray>, +) -> Result>> { + vms.lock().reserve_limit(1..=MAX_VMS_PER_FILE, GFP_KERNEL) +} + impl drm::file::DriverFile for File { type Driver = driver::AsahiDrmDriver; @@ -585,8 +660,13 @@ impl File { gpu.get_params(&mut params)?; params.features |= gpu.feature_flags(); + // Every backend admits the USC cache invalidate in the VDM root barrier. + params.features |= uapi::DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE as u64; if Self::supports_user_memory(reg_data) { - params.features |= uapi::DRM_ASAHI_FEATURE_USERPTR as u64; + // GEM_USERPTR pins are bounded by the GPU memory ledger only, not by + // RLIMIT_MEMLOCK (UserPages::pin()). + params.features |= uapi::DRM_ASAHI_FEATURE_USERPTR as u64 + | uapi::DRM_ASAHI_FEATURE_USERPTR_NO_MEMLOCK as u64; } if Self::supports_residency_control(reg_data) { params.features |= uapi::DRM_ASAHI_FEATURE_GEM_RESIDENCY as u64; @@ -677,6 +757,11 @@ impl File { // Every other runtime here reports DRM_ASAHI_GPU_HAL_LEGACY. return Err(EINVAL); } + // Take the table slot first, so that a VM past the cap is refused before anything of it + // is built. + let vm_xa = file.inner().vms(); + let resv = reserve_vm_slot(vm_xa.get_ref())?; + let id: u32 = resv.index().try_into()?; reg_data.gpu.admit_vm( device.as_ref().as_ref(), file.inner() @@ -727,10 +812,6 @@ impl File { }, ); - let vm_xa = file.inner().vms(); - let resv = vm_xa.lock().reserve_limit(1..=u32::MAX, GFP_KERNEL)?; - let id: u32 = resv.index().try_into()?; - mod_dev_dbg!(device, "[File {} VM {}]: VM Create\n", file_id, id); mod_dev_dbg!( device, @@ -1584,21 +1665,43 @@ impl File { .try_into()?; let bo = gem::ObjectRef::new(gem::Object::lookup_handle(file, data.handle)?); + // Charge the bind and take its table slot first, so that a bind past the client's memory + // limit is refused (ENOMEM, as an object creation would be) before the buffer gets a + // window alias or a CPU mapping. A later failure drops the charge and the slot. + let charge = admit_bind(&memacct::LEDGER, &file.inner().mem)?; + let objects = file.inner().objects(); + let resv = objects + .lock() + .reserve_limit(1..=u32::MAX, GFP_KERNEL_ACCOUNT)?; + let handle: u32 = resv.index().try_into()?; + // Take the bound range from the file's share of the firmware timestamp window before + // mapping. Past its share the buffer may not go in the window: the backend maps it + // without one if it can, or fails with ENOSPC as for a full window. A buffer mapped + // without the window gives the share back at once. + let limit = window_limit(reg_data.gpu.timestamp_window_size()); + let window = if limit == 0 { + crate::timestamp::WindowPermit::Unrestricted + } else { + match memacct::Client::take_window(&file.inner().mem, data.range, limit) { + Some(share) => crate::timestamp::WindowPermit::Share(share), + None => crate::timestamp::WindowPermit::Denied, + } + }; + let buffer = reg_data.gpu.map_timestamp_buffer( + bo, + offset..end_offset, + window, + )?; let mapping = Arc::new( - reg_data.gpu.map_timestamp_buffer(bo, offset..end_offset)?, - GFP_KERNEL, + crate::timestamp::Bound::new(buffer, charge), + GFP_KERNEL_ACCOUNT, )?; - let obj = KBox::new(Object::TimestampBuffer(mapping), GFP_KERNEL)?; - let handle = file - .inner() - .objects() - .lock() - .insert_limit(1..=u32::MAX, obj, GFP_KERNEL); - // StoreError owns the rejected object. Convert it only after the - // temporary XArray guard is gone: dropping a mapping may sleep. - let handle = handle? as u64; + let obj = KBox::new(Object::TimestampBuffer(mapping), GFP_KERNEL_ACCOUNT)?; + // fill() takes and releases the XArray lock itself, so a rejected object, which + // StoreError owns, is dropped outside it: dropping a mapping may sleep. + resv.fill(obj)?; - data.object_handle = handle as u32; + data.object_handle = handle; Ok(0) } @@ -1749,6 +1852,7 @@ impl File { resv.fill(Arc::pin_init( new_mutex!(TableQueue { queue, + cmdbuf: KVVec::new(), _share: share, }), GFP_KERNEL, @@ -1820,28 +1924,47 @@ impl File { data.queue_id, id ); - let mut vec = KVec::new(); - let copy_commands = |bytes: &mut KVec| { - UserSlice::new( - UserPtr::from_addr(data.cmdbuf as usize), - data.cmdbuf_size as usize, - ) - .reader() - .read_all(bytes, GFP_KERNEL) - }; + let cmdbuf_size = data.cmdbuf_size as usize; let guarded = gpu.as_any().is::() || gpu.tracked_submission(); // Once G17 output syncobjs are resolved, its queue must install a fence - // on every failure. Take the fallible userspace snapshot before that point. - if guarded { - copy_commands(&mut vec)?; - } - let syncs = SyncItem::parse_array( + // on every failure. Take the fallible userspace snapshot before that point, + // staging into a buffer taken from the queue's reusable cache so user + // copies never execute under `queue.lock()`. + let mut cmdbuf = if guarded { + let mut buf = queue.lock().take_cmdbuf(); + if let Err(e) = copy_cmdbuf_from_user(&mut buf, data.cmdbuf, cmdbuf_size) { + queue.lock().return_cmdbuf(buf); + return Err(e); + } + Some(buf) + } else { + None + }; + let cumulative_sync = gpu.as_any().is::() || { + #[cfg(CONFIG_DRM_ASAHI_G16)] + { + gpu.as_any().is::() + } + #[cfg(not(CONFIG_DRM_ASAHI_G16))] + { + false + } + }; + let syncs = match SyncItem::parse_array( file, data.syncs, data.in_sync_count, data.out_sync_count, - gpu.as_any().is::(), - )?; + cumulative_sync, + ) { + Ok(syncs) => syncs, + Err(e) => { + if let Some(buf) = cmdbuf { + queue.lock().return_cmdbuf(buf); + } + return Err(e); + } + }; mod_dev_dbg!( device, @@ -1851,22 +1974,33 @@ impl File { id ); - // Copy the command buffer into the kernel. Because we need to iterate - // the command buffer twice, we do this in one big copy_from_user to - // avoid TOCTOU issues. - if !guarded { - copy_commands(&mut vec)?; - } + // Copy the command buffer into the kernel outside `queue.lock()`. Because we + // need to iterate the command buffer twice, we do this in one big copy_from_user + // to avoid TOCTOU issues. + let cmdbuf = match cmdbuf.take() { + Some(buf) => buf, + None => { + let mut buf = queue.lock().take_cmdbuf(); + if let Err(e) = copy_cmdbuf_from_user(&mut buf, data.cmdbuf, cmdbuf_size) { + queue.lock().return_cmdbuf(buf); + return Err(e); + } + buf + } + }; let objects = file.inner().objects(); - let ret = queue.lock().submit( + let mut guard = queue.lock(); + let ret = guard.queue.submit( reg_data, id, syncs, data.in_sync_count as usize, - &vec, + cmdbuf.as_slice(), objects, ); + guard.return_cmdbuf(cmdbuf); + drop(guard); if ret.is_ok() { if let Some((util_min, duration_ms)) = gpu.syncobj_wait_hint() { @@ -1938,3 +2072,101 @@ impl Drop for File { Self::mark_clients_closed(this, |_| true); } } + +#[kernel::macros::kunit_tests(asahi_vm_table)] +mod vm_table_tests { + use super::*; + + #[test] + fn a_file_holds_at_most_max_vms_per_file() -> Result { + let vms = KBox::pin_init( + xarray::XArray::>::new(xarray::AllocKind::Alloc1), + GFP_KERNEL, + )?; + let mut held = KVec::new(); + for _ in 0..MAX_VMS_PER_FILE { + held.push(reserve_vm_slot(&vms)?, GFP_KERNEL)?; + } + assert_eq!(reserve_vm_slot(&vms).err(), Some(EBUSY)); + // A destroyed VM frees its slot for the next. + held.pop(); + held.push(reserve_vm_slot(&vms)?, GFP_KERNEL)?; + assert_eq!(reserve_vm_slot(&vms).err(), Some(EBUSY)); + // Another file's VM table has its own budget while the first is full. + let other = KBox::pin_init( + xarray::XArray::>::new(xarray::AllocKind::Alloc1), + GFP_KERNEL, + )?; + let _other_slot = reserve_vm_slot(&other)?; + // Closing the first file releases every slot for reuse. + held.clear(); + let _reused = reserve_vm_slot(&vms)?; + Ok(()) + } +} + +#[kernel::macros::kunit_tests(asahi_bound_object_charge)] +mod bound_object_charge_tests { + use super::*; + use crate::memacct::{Ledger, Limits}; + + static BINDS: Ledger = Ledger::new(); + + #[test] + fn a_bind_is_charged_its_records_and_refused_past_the_client_limit() -> Result { + // The charge covers the table entry, the bound record and the buffer's heap records. + assert!( + BOUND_OBJECT_BYTES as usize + >= core::mem::size_of::() + + core::mem::size_of::() + + crate::timestamp::Buffer::HEAP_BYTES + ); + BINDS.set_limits(Limits { device: 0, client: 4 * BOUND_OBJECT_BYTES }); + let client = memacct::Client::new()?; + let mut held = KVec::new(); + for _ in 0..4 { + held.push(admit_bind(&BINDS, &client)?, GFP_KERNEL)?; + } + assert_eq!(client.committed(), 4 * BOUND_OBJECT_BYTES); + // The fifth is refused with ENOMEM, as an object creation past the limit is, and + // charges nothing. + assert_eq!(admit_bind(&BINDS, &client).err(), Some(ENOMEM)); + assert_eq!(client.committed(), 4 * BOUND_OBJECT_BYTES); + // An unbind gives its charge back, and the next bind fits again. + held.pop(); + assert_eq!(client.committed(), 3 * BOUND_OBJECT_BYTES); + held.push(admit_bind(&BINDS, &client)?, GFP_KERNEL)?; + drop(held); + assert_eq!(client.committed(), 0); + Ok(()) + } + + #[test] + fn a_file_holds_at_most_its_share_of_the_timestamp_window() -> Result { + const MIB: u64 = 1 << 20; + let limit = window_limit(64 * MIB); + assert_eq!(limit, 4 * MIB); + assert_eq!(window_limit(0), 0); + let a = memacct::Client::new()?; + let b = memacct::Client::new()?; + // One file binds up to its share and no further, whatever the buffer sizes. + let first = memacct::Client::take_window(&a, 3 * MIB, limit); + assert!(first.is_some()); + assert!(memacct::Client::take_window(&a, 2 * MIB, limit).is_none()); + let second = memacct::Client::take_window(&a, MIB, limit); + assert!(second.is_some()); + assert_eq!(a.timestamp_window(), 4 * MIB); + assert!(memacct::Client::take_window(&a, 16 * 1024, limit).is_none()); + // Another file has its own share. + let other = memacct::Client::take_window(&b, 4 * MIB, limit); + assert!(other.is_some()); + // An unbind gives the share back; a limit of 0 (no window) takes nothing. + drop(first); + assert_eq!(a.timestamp_window(), MIB); + assert!(memacct::Client::take_window(&a, MIB, 0).is_none()); + drop((second, other)); + assert_eq!(a.timestamp_window(), 0); + assert_eq!(b.timestamp_window(), 0); + Ok(()) + } +} diff --git a/drivers/gpu/drm/asahi/fw/initdata.rs b/drivers/gpu/drm/asahi/fw/initdata.rs index 7c7488e950acef..7c7e3cfe45eb08 100644 --- a/drivers/gpu/drm/asahi/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/fw/initdata.rs @@ -637,7 +637,7 @@ pub(crate) mod raw { pub(crate) afr_unkpad: u32, } - #[versions(AGX)] + #[versions(AGX_V27_2)] #[derive(Debug)] #[repr(C)] pub(crate) struct HwDataB { @@ -663,10 +663,15 @@ pub(crate) mod raw { pub(crate) yuv_matrices: Array<0x3f, Array<3, Array<4, i16>>>, pub(crate) pad_1c8: Pad<0x8>, + #[ver(V < V27_2)] pub(crate) io_mappings: Array, + #[ver(V >= V27_2)] + pub(crate) io_mappings: Array<60, crate::g17::fw::initdata::RegisterMapEntry>, #[ver(V >= V13_0B4)] pub(crate) sgx_sram_ptr: U64, + #[ver(V >= V27_2)] + pub(crate) coredump_copy_buffer_size: U64, pub(crate) chip_id: u32, pub(crate) unk_454: u32, @@ -835,7 +840,7 @@ pub(crate) mod raw { #[ver(V >= V13_0B4)] pub(crate) unk_c3c: u32, } - #[versions(AGX)] + #[versions(AGX_V27_2)] default_zeroed!(HwDataB::ver); #[derive(Debug)] @@ -1243,7 +1248,7 @@ pub(crate) mod raw { pub(crate) index_mask: U64, } - #[versions(AGX)] + #[versions(AGX_V27_2)] #[derive(Debug)] #[repr(C)] pub(crate) struct InitData<'a> { @@ -1253,20 +1258,65 @@ pub(crate) mod raw { pub(crate) unk_buf: GpuPointer<'a, &'a [u8]>, pub(crate) unk_8: u32, pub(crate) unk_c: u32, + #[ver(V < V27_2)] pub(crate) runtime_pointers: GpuPointer<'a, super::RuntimePointers::ver>, + #[ver(V < V27_2)] pub(crate) globals: GpuPointer<'a, super::Globals::ver>, + #[ver(V < V27_2)] pub(crate) fw_status: GpuPointer<'a, super::FwStatus>, + // From 27.2 the root names opaque records; their layouts live with the 27.2 builder. + #[ver(V >= V27_2)] + pub(crate) runtime_pointers: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) globals: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) role: u32, + #[ver(V >= V27_2)] + pub(crate) host_mapped_fw_allocations: u32, pub(crate) uat_page_size: u16, pub(crate) uat_page_bits: u8, pub(crate) uat_num_levels: u8, pub(crate) uat_level_info: Array<0x3, UatLevelInfo>, pub(crate) __pad0: Pad<0x14>, + #[ver(V < V27_2)] pub(crate) host_mapped_fw_allocations: u32, + #[ver(V < V27_2)] pub(crate) unk_ac: u32, + #[ver(V < V27_2)] pub(crate) unk_b0: u32, + #[ver(V < V27_2)] pub(crate) unk_b4: u32, + #[ver(V < V27_2)] pub(crate) unk_b8: u32, + #[ver(V >= V27_2)] + pub(crate) status_record: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) control: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) power: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) extra: GpuPointer<'a, &'a [u8]>, } + + // Layout checks for the firmware 27.2 root and hardware data against the 13.5 layout. + const _: () = { + // T8112's older layout locates its optional SRAM pointer after 25 IO records. + assert!(core::mem::offset_of!(HwDataBG14V13_5, io_mappings) == 0x640); + assert!(core::mem::size_of::() == 0x20); + assert!(core::mem::offset_of!(HwDataBG14V13_5, sgx_sram_ptr) == 0x960); + assert!(core::mem::offset_of!(HwDataBG14V27_2, io_mappings) == 0x640); + assert!(core::mem::offset_of!(HwDataBG14V27_2, sgx_sram_ptr) == 0xfa0); + assert!(core::mem::offset_of!(HwDataBG14V27_2, coredump_copy_buffer_size) == 0xfa8); + assert!(core::mem::offset_of!(HwDataBG14V27_2, chip_id) == 0xfb0); + type Root = InitDataG14V27_2<'static>; + assert!(core::mem::offset_of!(Root, ver_info) == 0); + assert!(core::mem::offset_of!(Root, role) == 0x28); + assert!(core::mem::offset_of!(Root, host_mapped_fw_allocations) == 0x2c); + assert!(core::mem::offset_of!(Root, uat_level_info) == 0x34); + assert!(core::mem::offset_of!(Root, status_record) == 0xa8); + assert!(core::mem::offset_of!(Root, extra) == 0xc0); + assert!(core::mem::size_of::() == 0xc8); + }; } #[derive(Debug)] diff --git a/drivers/gpu/drm/asahi/fw/job.rs b/drivers/gpu/drm/asahi/fw/job.rs index aaa83355b437d2..39f2616b73da6c 100644 --- a/drivers/gpu/drm/asahi/fw/job.rs +++ b/drivers/gpu/drm/asahi/fw/job.rs @@ -5,7 +5,7 @@ use super::types::*; use crate::{ default_zeroed, - mmu, + timestamp, trivial_gpustruct, // }; use kernel::prelude::Result; @@ -128,7 +128,7 @@ trivial_gpustruct!(RenderTimestamps); #[derive(Debug)] pub(crate) struct UserTimestamp { - pub(crate) mapping: Arc, + pub(crate) mapping: Arc, pub(crate) offset: usize, } @@ -144,12 +144,12 @@ impl UserTimestamps { start_addr: self .start .as_ref() - .map(|a| GpuPointer::from_mapping(&a.mapping, a.offset)) + .map(|a| GpuPointer::from_mapping(a.mapping.firmware_mapping()?, a.offset)) .transpose()?, end_addr: self .end .as_ref() - .map(|a| GpuPointer::from_mapping(&a.mapping, a.offset)) + .map(|a| GpuPointer::from_mapping(a.mapping.firmware_mapping()?, a.offset)) .transpose()?, }) } diff --git a/drivers/gpu/drm/asahi/fwid.rs b/drivers/gpu/drm/asahi/fwid.rs index f9525c0c08f306..f855ba4c57e1ce 100644 --- a/drivers/gpu/drm/asahi/fwid.rs +++ b/drivers/gpu/drm/asahi/fwid.rs @@ -287,6 +287,7 @@ impl fmt::Display for Identity { /// Identifies the firmware build loaded at `text` (DATA `data_size` bytes) among `builds`, /// before any firmware-visible write. #[cfg_attr(not(CONFIG_DRM_ASAHI_G16), allow(dead_code))] +#[inline(never)] pub(crate) fn identify( dev: &device::Device, text: Range, @@ -458,6 +459,11 @@ mod tests { 0xb5, 0xcd, 0xfb, 0xd6, 0xd7, 0xcb, 0xc7, 0xf1, 0xba, 0xa2, 0xcc, 0x8b, 0x37, 0xee, 0x5d, 0x6e, 0x5e, 0x98, ], + [ + 0x19, 0xd9, 0x97, 0x49, 0x3e, 0x00, 0x76, 0x3d, 0xe3, 0x1f, 0x40, 0x0a, 0x59, 0x2d, + 0x8a, 0xea, 0xe6, 0xbd, 0x11, 0x72, 0xc5, 0x85, 0x96, 0x61, 0x78, 0x1b, 0x42, 0x15, + 0xde, 0xbc, 0x87, 0x0b, + ], ]; for (i, digest) in digests.into_iter().enumerate() { let found = measured(build.images, 0x138000, &[[0x59839, 0x5991c]], digest).unwrap(); @@ -563,14 +569,71 @@ mod tests { 0x86, 0x8b, 0xc9, 0xcf, ], ]; + // builds[0] is the normalized entry; the per-board J713 entries follow it. + let normalized = &builds[0]; + assert!(normalized + .boot_filled + .iter() + .all(|&(offset, len)| u64::from(offset) + u64::from(len) <= normalized.text_size)); + let found = measured( + builds, + 0x13c000, + &[[0x5c8df, 0x5c9c2]], + normalized.text_sha256, + ) + .unwrap(); + assert!(core::ptr::eq(found, normalized)); for (i, digest) in digests.into_iter().enumerate() { let found = measured(builds, 0x13c000, &[[0x5c8df, 0x5c9c2]], digest).unwrap(); - assert!(core::ptr::eq(found, &builds[i])); + assert!(core::ptr::eq(found, &builds[i + 1])); assert!(measured(builds, 0x138000, &[[0x5c8df, 0x5c9c2]], digest).is_none()); } assert!(measured(builds, 0x13c000, &[[0x5c8df, 0x5c9c2]], [0; 32]).is_none()); } + #[cfg(CONFIG_DRM_ASAHI_G16)] + #[test] + fn j773g_accepts_its_loaded_image() { + let builds = crate::g16::hw::t8132::CONFIG.firmware; + let digest = [ + 0x91, 0x54, 0xc7, 0xf8, 0x4b, 0xce, 0x32, 0x15, 0x1e, 0x8a, 0x97, 0x41, 0x7d, 0x6a, + 0x20, 0x7a, 0x9e, 0xaf, 0x03, 0x54, 0xb4, 0xb8, 0xd6, 0xf0, 0x2a, 0xf5, 0x29, 0x95, + 0x40, 0xd3, 0xe8, 0x5a, + ]; + let found = measured(builds, 0x13c000, &[[0x5c8df, 0x5c9c2]], digest).unwrap(); + assert_eq!(found.name, "Apple GFX 25G83 (normalized loaded image, J773g)"); + assert_eq!(found.boot_filled, &[(0x224, 4), (0x5c917, 8)]); + assert!(measured(builds, 0x138000, &[[0x5c8df, 0x5c9c2]], digest).is_none()); + } + + #[cfg(CONFIG_DRM_ASAHI_G16)] + #[test] + fn t8132_25g83_b000_zeroes_what_iboot_fills() { + let builds = crate::g16::hw::t8132::CONFIG.firmware; + let filled = crate::g16::hw::t8132::BOOT_FILLED_25G83_B000; + let build = builds.iter().find(|b| b.boot_filled == filled).unwrap(); + let [gkts, ecap] = build.entropy[0]; + // The header's per-boot word and DATA address, then one value per parameter record: + // each follows its 8-byte tag and length, back to back from the GKTS record. + assert_eq!(filled[..2], [(0x224, 4), (0x23c, 8)]); + let mut next = gkts; + for &(off, len) in &filled[2..filled.len() - 4] { + assert_eq!(off, next + 8); + next = off + len; + } + assert_eq!(next, 0x5c8df + 0x231); + assert!(filled.contains(&(gkts + 8, 8))); + assert!(filled.contains(&(ecap + 8, 8))); + // Then each tunable table's count byte and body, 0x350 bytes from its header. + for (i, table) in [next, next + 0x350].into_iter().enumerate() { + let at = filled.len() - 4 + 2 * i; + assert_eq!(filled[at..at + 2], [(table + 3, 1), (table + 4, 0x34c)]); + } + let found = measured(builds, 0x13c000, &[[gkts, ecap]], build.text_sha256).unwrap(); + assert!(core::ptr::eq(found, build)); + assert!(measured(builds, 0x138000, &[[gkts, ecap]], build.text_sha256).is_none()); + } + #[test] fn t6050_admits_only_its_pinned_image() { for cfg in [ @@ -585,6 +648,28 @@ mod tests { } } + #[test] + fn m5_builds_name_their_layouts() { + use crate::g17::fw::variant::{Firmware, M5Layouts}; + for cfg in [&crate::hw::t6050::CONFIG, &crate::hw::t6050::CONFIG_MAX] { + let Firmware::Identified(builds) = cfg.firmware else { + panic!("the M5 Pro and Max must identify their loaded firmware"); + }; + for (i, build) in builds.iter().enumerate() { + // 27.2 (26B123) moved the InitData layouts. + let layouts = if build.os_version >= [27, 2, 0] { + M5Layouts::V26B123 + } else { + M5Layouts::V26A428 + }; + assert_eq!(build.variant.m5_layouts, Some(layouts)); + for other in &builds[i + 1..] { + assert_ne!(build.images[0].text_sha256, other.images[0].text_sha256); + } + } + } + } + fn t6050_admits_only(builds: &[crate::g17::fw::variant::Build]) { for image in builds.iter().flat_map(|build| build.images) { // Both roles' records, inside TEXT. diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs new file mode 100644 index 00000000000000..24a1b9c66e237c --- /dev/null +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -0,0 +1,2078 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! G14 GPU firmware boot, submission and retirement. +//! +//! [`start`] builds the 27.2 root (`gpu/v27_2.rs`) on the records of a 13.5 G14 manager, +//! installs the driver's kernel window in the loader's UAT regions, starts the ASC, holds the +//! GPU powered and retires one kernel-owned compute job. [`Backend`] then serves clients +//! through the common submission front end (`m3_submit`). Compute uses the bootstrap +//! queue. A render owns a separate tiler and fragment submission and their parameter buffer +//! until both data masters have retired. +//! +//! The runtime is driven by the firmware's endpoint-0x20 notifications, which it sends after +//! publishing records on its event, statistics and log rings: each one runs the service, which +//! consumes those rings (the firmware waits for space in them) and retires completed commands. +//! Completion follows the queue's retired position, which the firmware advances in order. There +//! is a delayed service run while waiting for firmware to free a pool slot or make room on +//! the device-control ring. These changes need not generate a notification. + +use core::ops::Range; +use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use kernel::{ + device, + drm::sched, + new_condvar, new_delayed_work, new_mutex, new_spinlock, new_work, + platform, + prelude::*, + soc::apple::rtkit, + sync::{aref::ARef, Arc, ArcBorrow, CondVar, CondVarTimeoutResult, Mutex, SpinLock}, + time::{delay::fsleep, msecs_to_jiffies, Delta, Instant, Monotonic}, + uapi, + workqueue::{impl_has_delayed_work, impl_has_work, DelayedWork, OwnedQueue, Work, WorkItem}, +}; + +use crate::{ + alloc, event, g14_v27_2_render as render, gem, + gpu::{self, CommandPool, ComputeJob, GpuManagerG14V13_5, QueueInfo, RootV27_2, POOL_SLOTS}, + gpu::{FirmwareEvent, FRAGMENT, TILER}, + hw, mmu, queue, + m3::m3_submit::{Command, Packet}, +}; + +/// The recovery handshake is the one G16 answers: share its decisions (which phase the host may +/// answer, how a snapshot entry decodes, the recovery-storm window) instead of restating them. +/// Its FirmwareData offsets are G16's own and unused here. +#[path = "g16/recovery/logic.rs"] +#[allow(dead_code)] +mod recovery_logic; +use recovery_logic::{RecoveryAction, SnapshotEntry}; +use crate::g14_v27_2_abi::{self, Stopped}; + +/// RTKit endpoints of the GPU firmware. +const EP_FIRMWARE: u8 = 0x20; +const EP_DOORBELL: u8 = 0x21; + +/// ASC CPU control register and its run bit. +const ASC_CPU_CONTROL: usize = 0x44; +const ASC_RUN: u32 = 0x10; + +#[cfg(CONFIG_APPLE_SOC_SLEEP)] +#[allow(improper_ctypes)] +unsafe extern "C" { + fn apple_sleep_commit_stops_coprocs() -> bool; + fn apple_sleep_coproc_register_first( + dev: *mut kernel::bindings::device, + last_stop: Option core::ffi::c_int>, + data: *mut core::ffi::c_void, + ) -> core::ffi::c_int; + fn apple_sleep_coproc_set_ready(dev: *mut kernel::bindings::device, ready: bool); + fn apple_sleep_coproc_stopped(dev: *mut kernel::bindings::device) -> bool; + fn apple_sleep_coproc_wake_error(dev: *mut kernel::bindings::device) -> core::ffi::c_int; + fn apple_sleep_coproc_unregister(dev: *mut kernel::bindings::device); +} + +#[cfg(CONFIG_APPLE_SOC_SLEEP)] +struct CommitStop { + rtk: *mut kernel::bindings::apple_rtkit, + asc_ctl: *mut u8, + ran: bool, + idle_ret: core::ffi::c_int, + idle_us: u32, +} + +#[cfg(CONFIG_APPLE_SOC_SLEEP)] +// SAFETY: Owned by `State` under `Runtime::state`; read and written in the commit callback with +// interrupts off on the single boot CPU. +unsafe impl Send for CommitStop {} + +#[cfg(CONFIG_APPLE_SOC_SLEEP)] +unsafe extern "C" fn g14_v27_2_commit_stop(data: *mut core::ffi::c_void) -> core::ffi::c_int { + // SAFETY: `data` points to the heap-allocated `CommitStop` owned by `State::commit_stop` + // until `sleep_complete` (or `stop`) unregisters this callback. + let c = unsafe { &mut *data.cast::() }; + c.ran = true; + // SAFETY: `rtk` and `asc_ctl` remain mapped and live for the boot; runs at commit time with + // interrupts off and all refusals behind it. + unsafe { + c.idle_ret = kernel::bindings::apple_rtkit_sleep_idle_polled( + c.rtk, + c.asc_ctl.cast(), + &mut c.idle_us, + ); + if c.idle_ret != 0 { + return c.idle_ret; + } + kernel::bindings::apple_rtkit_mailbox_recv_off(c.rtk); + let ctl = kernel::bindings::readl(c.asc_ctl.cast()); + kernel::bindings::writel(ctl & !ASC_RUN, c.asc_ctl.cast()); + } + 0 +} + +/// Commands slower than this are a hang; the firmware state is then not trusted. +const COMMAND_TIMEOUT_MS: i64 = 5000; +/// How long `stop` lets published work retire before it fails what is left. +const STOP_DRAIN_MS: u32 = 2000; +/// Bound on the wait between a command's completion stamp and its retired position. +const RETIRE_WAIT_US: i64 = 2000; +/// Poll interval when firmware can release a resource without an interrupt. +const RESOURCE_RETRY_MS: u32 = 10; +/// Work item for the poll. Ordinary firmware notifications can still queue immediate work. +const RETRY_WORK: u64 = 1; +/// The firmware's recovery handshake (the G16/M3 order and limits): phase 1 follows the error +/// event within 50 ms; the whole handshake within 1 s; then the stopped work leaves its queue. +const PHASE1_WAIT_MS: i64 = 50; +const HANDSHAKE_MS: i64 = 1000; +const RECOVERY_DRAIN_MS: i64 = 1000; +/// Further recoveries answered while the stopped work drains (work behind it can time out in +/// turn) before the runtime gives up. +const FURTHER_RECOVERIES: u32 = 4; +/// Event ring record kinds kept for the logs of a timeout or a recovery. +const EVENT_HISTORY: usize = 8; +/// Rounds start only within this budget; one round takes at most PHASE1_WAIT_MS + +/// HANDSHAKE_MS + RECOVERY_DRAIN_MS, so the lock is released well within the 10 s scheduler +/// job timeout. +const RECOVERY_BUDGET_MS: i64 = 5000; + +struct FirmwareWait { + since: Instant, + last_kick: Option>, +} + +impl FirmwareWait { + /// Bound the wait even if the blocked command has not been published yet. + fn kick_due(wait: &mut Option) -> Result { + let now = Instant::now(); + let wait = wait.get_or_insert(Self { since: now, last_kick: None }); + if now - wait.since >= Delta::from_millis(COMMAND_TIMEOUT_MS) { + return Err(ETIMEDOUT); + } + if wait.last_kick.is_some_and(|last| { + now - last < Delta::from_millis(RESOURCE_RETRY_MS.into()) + }) { + return Ok(false); + } + wait.last_kick = Some(now); + Ok(true) + } +} + +/// The ASC control page and Fender operating-point page, kept mapped until the firmware is stopped. +pub(crate) struct AscControl(*mut u8, *mut u8); +// SAFETY: device register pages; accesses are single 32-bit MMIO operations. +unsafe impl Send for AscControl {} +// SAFETY: as above. +unsafe impl Sync for AscControl {} + +impl AscControl { + fn new(phys: u64, sgx: u64) -> Result { + // SAFETY: `phys` is the ASC register window of this platform device. Apple SoC fabrics + // require non-posted MMIO (`nonposted-mmio`); a posted write to ASC_CPU_CONTROL resets + // T8103 immediately. + let ptr = unsafe { kernel::bindings::ioremap_np(phys, 0x4000) }; + if ptr.is_null() { return Err(ENOMEM); } + // SAFETY: `sgx + 0xd01000` is the Fender operating-point register inside the SGX window. + let fender = unsafe { kernel::bindings::ioremap_np(sgx + 0xd01000, 0x1000) }; + if fender.is_null() { + // SAFETY: mapped above. + unsafe { kernel::bindings::iounmap(ptr) }; + return Err(ENOMEM); + } + Ok(Self(ptr.cast(), fender.cast())) + } + fn read(&self, at: usize) -> u32 { + // SAFETY: `at` is a register offset inside the mapped page. + unsafe { kernel::bindings::readl(self.0.add(at).cast()) } + } + fn write(&self, at: usize, value: u32) { + // SAFETY: as above. + unsafe { kernel::bindings::writel(value, self.0.add(at).cast()) } + } + fn fender(&self) -> u32 { + // SAFETY: mapped Fender register page. + unsafe { kernel::bindings::readl(self.1.cast()) } + } + /// Clears the ASC run bit. + fn halt(&self) { + self.write(ASC_CPU_CONTROL, self.read(ASC_CPU_CONTROL) & !ASC_RUN); + } +} + +impl Drop for AscControl { + fn drop(&mut self) { + // SAFETY: mapped in `new`, unmapped once. + unsafe { + kernel::bindings::iounmap(self.1.cast()); + kernel::bindings::iounmap(self.0.cast()); + } + } +} + +/// Whether a Fender word says the GPU is powered: a nonzero index and no request pending. +fn gpu_powered(fender: u32) -> bool { + fender & 0x10 == 0 && fender & 0xf != 0 +} + +/// Whether a Fender word says the GPU is powered off: zero index and no request pending. +fn gpu_powered_off(fender: u32) -> bool { + fender & 0x1f == 0 +} + +/// The GPU MMU fault status, read when a command times out: a pending fault names the faulting +/// address and unit, an empty status says the work stalled without a page fault. +struct FaultStatus { + page: *mut u8, + info: usize, + addr: Option, + g14x: bool, +} +// SAFETY: a device register page that is only read, one 32-bit MMIO load at a time. +unsafe impl Send for FaultStatus {} +// SAFETY: as above. +unsafe impl Sync for FaultStatus {} + +impl FaultStatus { + fn new(sgx: u64, cfg: &'static hw::HwConfig) -> Result { + let (info, addr, g14x) = crate::regs::Resources::fault_registers(cfg); + let base = info & !0xfff; + if addr.is_some_and(|a| a & !0xfff != base) { + return Err(EINVAL); + } + // SAFETY: the page lies inside this platform device's SGX register window. + let page = unsafe { kernel::bindings::ioremap_np(sgx + base as u64, 0x1000) }; + if page.is_null() { return Err(ENOMEM); } + Ok(Self { page: page.cast(), info: info - base, addr: addr.map(|a| a - base), g14x }) + } + fn read64(&self, at: usize) -> u64 { + // SAFETY: `at` and `at + 4` are register offsets inside the mapped page. + let (lo, hi) = unsafe { + (kernel::bindings::readl(self.page.add(at).cast()), + kernel::bindings::readl(self.page.add(at + 4).cast())) + }; + u64::from(lo) | (u64::from(hi) << 32) + } + fn log(&self, dev: &device::Device) { + let info = self.read64(self.info); + if info & 1 == 0 { + dev_err!(dev, "GPU: no MMU fault pending at the timeout (FAULT_INFO={:#x})\n", info); + return; + } + let addr = self.addr.map_or(info >> 30, |at| self.read64(at)); + dev_err!(dev, "GPU: MMU fault pending at the timeout: FAULT_INFO={:#x} {:?}\n", info, + crate::regs::decode_fault(info, addr, self.g14x)); + } +} + +impl Drop for FaultStatus { + fn drop(&mut self) { + // SAFETY: mapped in `new`, unmapped once. + unsafe { kernel::bindings::iounmap(self.page.cast()) } + } +} + +/// Where the firmware's messages go: the runtime once it exists, nowhere before or after. +#[pin_data] +pub(crate) struct Notify { + dev: ARef, + #[pin] + runtime: SpinLock>>, + /// Endpoint-0x20 messages received, reported when the firmware stops. + messages: AtomicU64, +} + +impl Notify { + fn new(dev: &device::Device) -> Result> { + Arc::pin_init(pin_init!(Self { + dev: dev.into(), + runtime <- new_spinlock!(None, "g14_v27_2::Notify::runtime"), + messages: AtomicU64::new(0), + }), GFP_KERNEL) + } + + /// Queues one service run if a runtime is attached. A run already queued covers this one. + fn wake(&self) { + if let Some(runtime) = self.runtime.lock().as_ref() { + if !runtime.deep_sleeping.load(Ordering::Acquire) { + let _ = runtime.queue.enqueue::, 0>(runtime.clone()); + } + } + } + + /// Queues a poll while attached. Detaching also fences off poll requests before teardown. + fn retry(&self) { + if let Some(runtime) = self.runtime.lock().as_ref() { + if runtime.healthy() && !runtime.deep_sleeping.load(Ordering::Acquire) { + let _ = runtime.queue.enqueue_delayed::, RETRY_WORK>( + runtime.clone(), msecs_to_jiffies(RESOURCE_RETRY_MS), + ); + } + } + } + + fn attach(&self, runtime: Arc) { + *self.runtime.lock() = Some(runtime); + } + + /// Toggles `deep_sleeping` under the same lock that guards `wake` and `retry`, so no + /// notification can race a queue drain after this returns with `deep == true`. + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + fn set_deep_sleeping(&self, runtime: &Runtime, deep: bool) { + let _guard = self.runtime.lock(); + runtime.deep_sleeping.store(deep, Ordering::Release); + } + + /// After this returns, nothing queues service work. + fn detach(&self) -> Option> { + self.runtime.lock().take() + } +} + +/// RTKit operations of the GPU firmware: its crash log lives in the loader's data segment. +pub(crate) struct Firmware; + +#[vtable] +impl rtkit::Operations for Firmware { + type Data = Arc; + type Buffer = crate::g17::CrashLog; + + const COPROC_PLACES_BUFFERS: bool = true; + + fn shmem_map(notify: ArcBorrow<'_, Notify>, iova: usize, size: usize) -> Result { + crate::g17::CrashLog::from_firmware(¬ify.dev, iova, size) + } + + fn crashed(notify: ArcBorrow<'_, Notify>, log: Option<&[u8]>) { + unsafe extern "C" { + fn asahi_save_rtkit_dump(dev: *mut core::ffi::c_void, data: *const u8, size: usize); + } + dev_err!(&*notify.dev, "GPU firmware crashed\n"); + if let Some(log) = log { + // SAFETY: RTKit and the device remain live throughout this synchronous copy. + unsafe { asahi_save_rtkit_dump(notify.dev.as_raw().cast(), log.as_ptr(), log.len()) }; + } + // The service sees the crash and fails outstanding work. + notify.wake(); + } + + /// The firmware sends endpoint 0x20 a message after it publishes event, statistics or log + /// records. Whatever the message, the service reads every ring and the queue's position, + /// so each one is a wakeup. + fn recv_message(notify: ArcBorrow<'_, Notify>, ep: u8, _message: u64) { + if ep == EP_FIRMWARE { + notify.messages.fetch_add(1, Ordering::Relaxed); + notify.wake(); + } + } +} + +type Peer = Pin>>; + +/// Waits for a shared-word acknowledgement, checking `done` every millisecond and draining the +/// firmware's rings, for at most `ms`. Only for the start/stop handshakes whose acknowledgement +/// is a word the firmware writes with no message: the ready status, the command-service +/// installation, device-control (idle-policy) consumption and the running flag. The existing G14 +/// path waits for its device-control channel the same way (`channel::TxChannel::wait_for`). +fn wait(root: &RootV27_2, ms: i64, mut done: impl FnMut() -> Result) -> Result { + let start = Instant::::now(); + loop { + if done()? { return Ok(()); } + if start.elapsed() >= Delta::from_millis(ms) { return Err(ETIMEDOUT); } + let _ = root.drain(); + fsleep(Delta::from_millis(1)); + } +} + +/// Publishes an idle-policy record and waits until the firmware has consumed and +/// acknowledged it. On error, returns `(published, err)` where `published` is true if the +/// control record was already written to shared memory before the failure. +fn try_set_idle_policy( + root: &RootV27_2, + peer: &mut Peer, + allow_off: bool, +) -> core::result::Result<(), (bool, Error)> { + let (target, generation) = root.publish_idle_policy(allow_off).map_err(|e| (false, e))?; + peer.as_mut() + .send_message(EP_DOORBELL, gpu::DEVICE_CONTROL_KICK) + .map_err(|e| (true, e))?; + wait(root, 3000, || { + Ok(root.idle_progress()? == [target; 3] && root.idle_acknowledgement()? == generation) + }) + .map_err(|e| (true, e)) +} + +/// Publishes an idle-policy record and waits until the firmware has consumed and +/// acknowledged it. +fn set_idle_policy(root: &RootV27_2, peer: &mut Peer, allow_off: bool) -> Result { + try_set_idle_policy(root, peer, allow_off).map_err(|(_, e)| e) +} + +/// Stops firmware that no runtime owns: allow power-off, then RTKit power-off, then the ASC +/// run bit. Everything it could reach is kept for the rest of the boot. +fn halt_unowned(dev: &device::Device, mut peer: Peer, root: crate::fw::types::GpuObject, + asc: AscControl, booted: bool) { + if booted { + let allowed = set_idle_policy(&root, &mut peer, true); + // SAFETY: the RTKit instance is live and owned here. + let off = kernel::error::to_result(unsafe { kernel::bindings::apple_rtkit_poweroff(peer.as_raw()) }); + dev_err!(dev, "GPU firmware halted: allow-off={:?} power-off={:?}\n", allowed, off); + } + asc.halt(); + core::mem::forget(peer); + core::mem::forget(root); + core::mem::forget(asc); +} + +/// A started 27.2 GPU, ready for DRM registration. +pub(crate) struct Started<'a> { + pub(crate) backend: Arc, + pub(crate) drm: kernel::drm::UnregisteredDevice, + pub(crate) binding: crate::binding::Owner, + pub(crate) resources: crate::regs::Resources<'a>, +} + +/// Starts the firmware and retires the boot job. +pub(crate) fn start<'a>( + pdev: &'a platform::Device>, + cfg: &'static hw::HwConfig, + registers: &'static [hw::RegisterV27_2], + writable: u64, +) -> Result> { + use kernel::dma::{Device as _, DmaMask}; + let dev: &device::Device = pdev.as_ref(); + let geometry = mmu::UatGeometry { ias: cfg.uat_ias, oas: cfg.uat_oas }; + let mut window = mmu::FirmwareWindow::reserve(dev, geometry)?; + let sgx = pdev.resource_by_name(c"sgx").ok_or(EINVAL)?; + let asc = AscControl::new(pdev.resource_by_name(c"asc").ok_or(EINVAL)?.start(), sgx.start())?; + let control = asc.read(ASC_CPU_CONTROL); + if control & ASC_RUN != 0 { return Err(EBUSY); } + let notify = Notify::new(dev)?; + let mut peer = KBox::pin( + rtkit::RtKit::::new(dev, None, 0, notify.clone())?, + GFP_KERNEL)?; + let resources = crate::regs::Resources::new(pdev)?; + let fault = FaultStatus::new(sgx.start(), cfg)?; + let copy_bytes: u32 = dev.fwnode().ok_or(ENODEV)? + .property_read(c"apple,coredump-copy-buffer").required_by(dev)?; + let board = gpu::BoardV27_2 { + sgx: sgx.start(), sgx_size: sgx.size() as u64, copy_bytes, registers, writable, + }; + + // SAFETY: the mask is the UAT's physical width. + unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(geometry.oas)?)? }; + let drm = kernel::drm::UnregisteredDevice::::new(pdev, Ok(()))?; + // SAFETY: the unregistered DRM instance is private to this bound probe. + let binding = unsafe { crate::binding::Owner::new(pdev.as_ref(), &drm)? }; + let uat = mmu::Uat::new_adopted(&drm, geometry, &window.regions())?; + let graph = GpuManagerG14V13_5::build_graph(&drm, &resources, cfg, KBox::new(uat, GFP_KERNEL)?, + gpu::GraphProfile::G14V27_2)?; + let root = RootV27_2::build(&graph, &board)?; + let pool = CommandPool::new(&mut gpu::GpuManager::alloc(&*graph), cfg)?; + // Timestamp buffers are bound in the timestamp aperture while the firmware runs, and the + // window only carries the tables that exist now: link the aperture's tables first. + graph.kernel_uat().prepare_kernel_tables(&[graph.timestamp_range()])?; + window.mirror(graph.kernel_uat())?; + window.install()?; + window.announce(); + asc.write(ASC_CPU_CONTROL, control | ASC_RUN); + + // From here the firmware may read everything the window names: nothing is freed. + let mut booted = false; + let mut step = "loader handoff"; + let result = (|| -> Result { + let start = Instant::::now(); + while !window.answered() { + if start.elapsed() >= Delta::from_millis(1000) { return Err(ETIMEDOUT); } + fsleep(Delta::from_millis(1)); + } + step = "RTKit boot"; + peer.as_mut().boot()?; + booted = true; + peer.as_mut().start_endpoint(EP_FIRMWARE)?; + peer.as_mut().start_endpoint(EP_DOORBELL)?; + if !window.intact() { return Err(EIO); } + step = "initialization"; + peer.as_mut().send_message(EP_FIRMWARE, gpu::init_message(root.gpu_va().get()))?; + // The firmware sets status +0x14 when it has initialized; the first control record + // waits for it. + wait(&root, 2000, || root.initialized())?; + step = "keep-powered policy"; + set_idle_policy(&root, &mut peer, false)?; + // Powered initialization installs the command handlers and then clears the + // installation request the root set (+0x4c24). + step = "command-handler installation"; + wait(&root, 500, || root.commands_installed())?; + step = "boot job"; + root.publish_boot_job(resources.operating_point())?; + peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?; + wait(&root, 3000, || root.boot_job_complete()) + })(); + if let Err(e) = result { + dev_err!(dev, "GPU firmware 27.2 did not start: {}: {:?}\n", step, e); + halt_unowned(dev, peer, root, asc, booted); + core::mem::forget(window); + core::mem::forget(pool); + core::mem::forget(graph); + return Err(e); + } + // The firmware keeps using the window until it is stopped; it stays for the life of the boot. + core::mem::forget(window); + let backend = Backend::start(&drm, dev, notify, peer, root, graph, pool, asc, fault, cfg)?; + Ok(Started { backend, drm, binding, resources }) +} + +/// Whether the packet's VM has failed (`VmStatus` latched): its work is no longer admitted. +fn vm_failed(packet: &Packet) -> bool { + packet.vm.status().is_some_and(|status| status.get() != 0) +} + +/// Latches the VM of work a recovery stopped as guilty, before the work drains: from here on +/// `submit` refuses it and `pump` publishes none of its queued packets. +fn latch_guilty(packet: &Packet, error: Error) { + if let Some(status) = packet.vm.status() { + status.note_recovery_guilty(); + status.record(error); + } +} + +struct Inflight { + packet: Arc, + last: bool, + publication_error: Option, + stamp: event::EventValue, + slot: usize, + /// Queue publications up to and including this command, counted from take-over. + ordinal: u64, + started: Instant, + /// Set when the firmware stopped this command: it fails its packet when it leaves the queue. + doomed: Option, + _bind: mmu::VmBind, +} + +struct RenderFlight { + packet: Arc, + last: bool, + bind: mmu::VmBind, + scene: render::Prep, + slots: [usize; 2], + stamps: [event::EventValue; 2], + targets: [u32; 2], + started: Instant, + doomed: Option, +} + +/// Who a recovery round blamed, for its log line: the client, and the stopped work's stamps +/// (render: tiler and fragment; compute: the stopped command's and the queue's current one). +struct Blamed { + owner: crate::m3::m3_submit::Owner, + stamps: [u32; 2], + /// The stopped compute command's queue ordinal: the drain waits for this command only. The + /// packet's later commands were not stopped and retire (failed) through the normal path. + stopped: Option, +} + +struct State { + peer: Peer, + root: crate::fw::types::GpuObject, + pool: CommandPool, + asc: AscControl, + fault: FaultStatus, + queue: QueueInfo, + last: event::EventValue, + sequence: u64, + next_slot: usize, + waiting_unlink: Option, + waiting_control: Option, + /// Publications and retirements counted on the queue's position block. + published: u64, + /// Completion stamps seen before the retired position they precede. + late: u64, + /// Pool slots holding a published command, one bit each. + busy: u64, + /// Free slots passed over because the firmware still held them. + skipped: u64, + /// Retired slots whose cursor is not advanced yet: the firmware had not recorded the + /// value to advance it to (`CommandPool::retire`). One bit each. + unacked: u64, + /// Retirements whose cursor had to wait for the firmware's record. + deferred: u64, + retired_total: u64, + retired_raw: u32, + capacity: u32, + inflight: KVec, + rendering: Option, + pending: KVec<(Arc, usize)>, + accepting: bool, + submitted: u64, + retired: u64, + /// A fault or timeout the firmware reported (error, named slot), answered by `recover`. + firmware_error: Option<(Error, i32)>, + recoveries: u64, + /// Recovery-storm window (`recovery_logic::admit`): its start and the recoveries in it. + recovery_window: u64, + recovery_count: u32, + /// Reports read and rounds answered: tells a stale report from a new one. + ledger: g14_v27_2_abi::RecoveryLedger, + /// Kind words of the last event ring records read, and how many were read in all. + events: [u32; EVENT_HISTORY], + events_read: u64, + /// Packets with a command the firmware stopped (`blame`), with their VM job guard, kept + /// for the rest of the boot: the firmware may still reach that memory. Allocated with + /// `g14_v27_2_abi::QUARANTINE_LIMIT` places at start, so keeping one never allocates. + kept: KVec>, + /// The stopped commands of those packets, with their VM binding and scene, once they left + /// their queue (`Runtime::keep`). Held, never read. + kept_compute: KVec, + kept_renders: KVec, + /// Set when a sleep/wake failure may have left the GPU domain unpowered or stopped so + /// teardown skips live-hardware MMIO and RTKit operations. + hardware_unreachable: bool, + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + commit_stop: Option>, +} + +impl State { + /// Stop publishing this packet. Report failure only once any published prefix retires. + fn fail_publication(&mut self, packet: &Arc, err: Error) { + let _ = self.pending.remove(0); + if let Some(last) = self.inflight.iter_mut().rev() + .find(|flight| Arc::ptr_eq(&flight.packet, packet)) + { + last.publication_error = Some(err); + } else { + if g14_v27_2_abi::guard_releasable(false, self.kept(packet)) { + packet.release_guard(); + } + packet.finish(Err(err)); + } + } + + /// The kinds of the last event ring records read, oldest first, for a log line. + fn recent_events(&self) -> ([u32; EVENT_HISTORY], usize) { + let count = self.events_read.min(EVENT_HISTORY as u64) as usize; + let mut out = [0; EVENT_HISTORY]; + for (i, kind) in out.iter_mut().take(count).enumerate() { + let at = (self.events_read - count as u64 + i as u64) % EVENT_HISTORY as u64; + *kind = self.events[at as usize]; + } + (out, count) + } + + fn running(&self) -> bool { + !self.inflight.is_empty() || self.rendering.is_some() + } + + /// Whether a queue holds any of the packet's commands. + fn live(&self, packet: &Arc) -> bool { + self.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, packet)) + || self.rendering.as_ref().is_some_and(|flight| Arc::ptr_eq(&flight.packet, packet)) + } + + /// Whether a recovery stopped a command of the packet: it stays owned for the boot. + fn kept(&self, packet: &Arc) -> bool { + self.kept.iter().any(|kept| Arc::ptr_eq(kept, packet)) + } + + /// Whether the runtime owns the packet's VM job guard (`g14_v27_2_abi::guard_releasable`). + fn owns(&self, packet: &Arc) -> bool { + !g14_v27_2_abi::guard_releasable(self.live(packet), self.kept(packet)) + } + + fn pending(&self, packet: &Arc) -> bool { + self.pending.iter().any(|(current, _)| Arc::ptr_eq(current, packet)) + } + + fn advance_packet(&mut self, last: bool) { + if last { + let _ = self.pending.remove(0); + } else { + self.pending[0].1 += 1; + } + } +} + +#[pin_data(PinnedDrop)] +pub(crate) struct Runtime { + dev: ARef, + graph: Arc, + healthy: AtomicBool, + /// Set between [`Runtime::sleep_prepare`] and [`Runtime::sleep_complete`]: nothing is + /// published across a system sleep. + asleep: AtomicBool, + /// Set across a firmware-driven deep sleep once workers are drained and the commit stop + /// is armed; prevents workers from touching the stopped firmware or mailbox. + deep_sleeping: AtomicBool, + notify: Arc, + /// Runs the service. Only `Notify` queues on it, and `stop` drains it. + queue: OwnedQueue, + #[pin] + state: Mutex>, + /// Signalled when no work is pending or published, or the runtime fails. + #[pin] + idle: CondVar, + #[pin] + work: Work, + #[pin] + retry: DelayedWork, +} + +impl_has_work! { + impl HasWork for Runtime { self.work } +} + +impl WorkItem for Runtime { + type Pointer = Arc; + fn run(this: Arc) { + this.service(); + } +} + +impl_has_delayed_work! { + impl HasDelayedWork for Runtime { self.retry } +} + +impl WorkItem for Runtime { + type Pointer = Arc; + fn run(this: Arc) { + if this.healthy() { + this.service(); + } + } +} + +#[pinned_drop] +impl PinnedDrop for Runtime { + fn drop(self: Pin<&mut Self>) { + // `Notify` holds a reference until `stop`, so this runs only after it, or for a + // runtime that never took over the firmware. + if self.state.lock().is_some() { self.stop(); } + } +} + +impl Runtime { + pub(crate) fn healthy(&self) -> bool { self.healthy.load(Ordering::Acquire) } + + /// Runs the service once more: the DRM scheduler's job timeout calls this, so a command the + /// firmware never completes still reaches the command timeout. + pub(crate) fn wake(&self) { self.notify.wake(); } + + /// Queues a packet and publishes what the pool has room for; the firmware's completion + /// notifications run the service, which retires it and publishes the rest. + pub(crate) fn submit(self: &Arc, packet: Arc) -> Result { + if !self.healthy() { return Err(EIO); } + if packet.commands.is_empty() { + return Err(ENOTSUPP); + } + // A VM that lost its context (a recovery found it guilty, or its work failed) runs + // nothing more on the GPU. + if vm_failed(&packet) { return Err(EIO); } + let mut guard = self.state.lock(); + let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; + if !self.healthy() { return Err(EIO); } + if !state.accepting { return Err(ENODEV); } + state.pending.push((packet, 0), GFP_KERNEL)?; + self.pump(state); + Ok(()) + } + + /// Withdraws a packet's unpublished commands; published ones retire normally. + pub(crate) fn withdraw(&self, packet: &Arc) { + let mut guard = self.state.lock(); + if let Some(state) = Option::as_mut(&mut *guard) { + if let Some(i) = state.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)) { + let _ = state.pending.remove(i); + } + if !state.owns(packet) { + packet.release_guard(); + } + if state.pending.is_empty() { + state.waiting_unlink = None; + } + } + } + + fn fail_all(&self, state: &mut State, error: Error) { + self.healthy.store(false, Ordering::Release); + self.idle.notify_all(); + while let Some((packet, _)) = state.pending.pop() { + if !state.owns(&packet) { + packet.release_guard(); + } + packet.finish(Err(error)); + } + if let Some(flight) = &state.rendering { + if let Some(status) = flight.packet.vm.status() { status.record(error); } + flight.packet.finish(Err(error)); + } + // Published work stays owned: the firmware may still read it. + for f in state.inflight.iter() { + if let Some(status) = f.packet.vm.status() { status.record(error); } + f.packet.finish(Err(error)); + } + } + + /// Advances the cursors of retired slots that were waiting for the firmware's record. + fn acknowledge(&self, state: &mut State) { + let mut pending = state.unacked; + while pending != 0 { + let slot = pending.trailing_zeros() as usize; + pending &= pending - 1; + match state.pool.retire(slot) { + Ok(false) => {} + Ok(true) => state.unacked &= !(1 << slot), + Err(e) => { + dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", e); + state.unacked &= !(1 << slot); + } + } + } + } + + /// Finds unlinked slots without moving any publication cursor. + fn free_slots(&self, state: &mut State, count: usize) -> Result> { + let mut slots = [0; 2]; + let mut found = 0; + for k in 0..POOL_SLOTS { + let slot = (state.next_slot + k) % POOL_SLOTS; + if state.busy & (1 << slot) != 0 { continue; } + if state.pool.registered(slot)? { + // The firmware can count another record for a retired slot after its cursor + // was advanced, and keeps the slot listed until the cursor matches again: + // advance it to the current count. The slot's last command stays intact in + // its buffer, so an early unlink is harmless. + state.pool.retire(slot)?; + state.skipped += 1; + continue; + } + slots[found] = slot; + found += 1; + if found == count { + state.waiting_unlink = None; + return Ok(Some(slots)); + } + } + if FirmwareWait::kick_due(&mut state.waiting_unlink)? { + state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?; + for dm in [TILER, FRAGMENT] { + if state.root.render_queue_announced(dm) { + state.peer.as_mut().send_message(EP_DOORBELL, RootV27_2::render_kick(dm))?; + } + } + } + self.notify.retry(); + Ok(None) + } + + /// Compute commands may pipeline. A render pair is a scheduling boundary so its buffer, + /// timestamps and dependencies remain owned until both data masters retire. + fn pump(&self, state: &mut State) { + self.acknowledge(state); + if !self.healthy() || self.asleep.load(Ordering::Acquire) || state.rendering.is_some() { + return; + } + while state.inflight.len() < POOL_SLOTS - 1 && !state.pending.is_empty() { + let (packet, index) = (state.pending[0].0.clone(), state.pending[0].1); + if vm_failed(&packet) { + // Queued before its VM failed: none of it is published from now on. + state.fail_publication(&packet, EIO); + continue; + } + let command = packet.commands[index]; + let paired = matches!(command, Command::Render { .. }); + if paired && state.running() { return; } + let count = if paired { 2 } else { 1 }; + let slots = match self.free_slots(state, count) { + Ok(Some(slots)) => slots, + Ok(None) => return, + Err(err) => { + dev_err!(self.dev, "GPU: command pool stalled: {:?} busy={:#x} unacked={:#x} inflight={} rendering={}\n", + err, state.busy, state.unacked, state.inflight.len(), state.rendering.is_some()); + for slot in 0..POOL_SLOTS { + if let Ok((count, cursor, linked)) = state.pool.describe(slot) { + if linked != 0 || count != cursor { + dev_err!(self.dev, "GPU: slot {}: records={} cursor={} linked={}\n", + slot, count, cursor, linked); + } + } + } + self.fail_all(state, err); + return; + } + }; + let last = index + 1 == packet.commands.len(); + let result = match command { + Command::Compute(control) => + self.publish_compute(state, &packet, index, control, last, slots[0]), + Command::Render { command, usc } => + self.publish_render(state, &packet, index, &command, usc, last, slots), + }; + match result { + Ok(()) if paired || !self.healthy() => return, + Ok(()) => {} + Err(EBUSY) if state.running() => return, + Err(err) => { + dev_err!(self.dev, "GPU: command publication failed {:?}\n", err); + state.fail_publication(&packet, err); + } + } + } + } + + fn publish_compute( + &self, state: &mut State, packet: &Arc, index: usize, + control: crate::m3::agx_compute::Control, last: bool, slot: usize, + ) -> Result { + let bind = self.graph.kernel_uat().bind(&packet.vm)?; + let preempt = packet.preempt.as_ref().ok_or(EINVAL)?.gpu_va().get(); + let stamp = state.last.next(); + let job = ComputeJob { + context: bind.slot(), + sequence: state.sequence, + cdm_base: control.base, + cdm_end: control.end, + usc_base: control.usc_base, + preempt, + timestamps: packet.timestamp_addresses(index), + helper: control.helper, + sampler_heap: control.sampler_heap, + sampler_count: control.sampler_count, + }; + let command = state.pool.encode(slot, &state.queue, stamp.raw(), &job)?; + let submission = state.root.stage_compute(command)?; + let ordinal = state.published + 1; + // Commit ownership before the firmware can see the new work. + state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, + publication_error: None, started: Instant::now(), doomed: None, _bind: bind }, + GFP_KERNEL)?; + packet.mark_published(); + submission.publish(); + state.pool.mark_published(slot); + state.last = stamp; + state.sequence += 1; + state.unacked &= !(1 << slot); + state.busy |= 1 << slot; + state.published = ordinal; + state.next_slot = (slot + 1) % POOL_SLOTS; + state.submitted += 1; + state.advance_packet(last); + if let Err(err) = state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK) { + self.fail_all(state, err); + } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + fn publish_render( + &self, state: &mut State, packet: &Arc, index: usize, + command: &crate::m3::agx_uapi::UapiRenderCommand, usc: u64, last: bool, slots: [usize; 2], + ) -> Result { + let queue = packet.render_queue.as_ref().ok_or(EINVAL)?; + let scene = queue.prepare(command, usc)?; + let bind = self.graph.kernel_uat().bind(&packet.vm)?; + let context = bind.slot(); + let (tiler, tiler_stamp) = state.root.render_queue(TILER); + let (fragment, fragment_stamp) = state.root.render_queue(FRAGMENT); + let stamps = [tiler_stamp.next(), fragment_stamp.next()]; + let with_buffer = scene.buffer_op.is_some(); + let timestamps = packet.render_timestamp_addresses(index); + let attachments = &packet.render_attachments[index]; + let ta = state.pool.encode_with(slots[TILER], context, state.sequence, stamps[TILER].raw(), + |cmd, stream, common| { + render::encode_vertex(cmd, stream, &common, &tiler, tiler.compute_state, + command, &scene, stamps[FRAGMENT].raw(), fragment.slot, + timestamps[TILER], &attachments[TILER])?; + if let Some(op) = scene.buffer_op { + render::encode_buffer_op(&mut cmd[render::INITBUF_AT..][..0x20], &common, &scene, op); + } + Ok(()) + })?; + let fs = state.pool.encode_with(slots[FRAGMENT], context, state.sequence + 1, stamps[FRAGMENT].raw(), + |cmd, stream, common| { + render::encode_fragment(cmd, stream, &common, &fragment, fragment.compute_state, + command, &scene, timestamps[FRAGMENT], &attachments[FRAGMENT])?; + render::encode_own_barrier(&mut cmd[render::OWN_BARRIER_AT..][..render::OWN_BARRIER_SIZE], + &tiler, stamps[TILER].raw(), stamps[FRAGMENT].raw()); + Ok(()) + })?; + let ta_work = [ta + render::INITBUF_AT as u64, ta]; + let fs_work = [fs + render::OWN_BARRIER_AT as u64, fs]; + let ta_post = state.root.stage_render(TILER, &ta_work[usize::from(!with_buffer)..])?; + let fs_post = state.root.stage_render(FRAGMENT, &fs_work)?; + state.rendering = Some(RenderFlight { + packet: packet.clone(), last, bind, scene, slots, stamps, + targets: [ta_post.target(), fs_post.target()], started: Instant::now(), doomed: None, + }); + queue.published(); + packet.mark_published(); + // Queue the fragment dependency before kicking the tiler that satisfies it. + fs_post.publish(); + ta_post.publish(); + for slot in slots { + state.pool.mark_published(slot); + } + for slot in slots { + state.busy |= 1 << slot; + state.unacked &= !(1 << slot); + } + state.next_slot = (slots[FRAGMENT] + 1) % POOL_SLOTS; + state.sequence += 2; + state.submitted += 2; + state.advance_packet(last); + for dm in [FRAGMENT, TILER] { + if let Err(err) = state.peer.as_mut().send_message(EP_DOORBELL, RootV27_2::render_kick(dm)) { + self.fail_all(state, err); + break; + } + } + Ok(()) + } + + fn retire_slot(&self, state: &mut State, slot: usize) { + match state.pool.retire(slot) { + Ok(true) => {} + Ok(false) => { + state.unacked |= 1 << slot; + state.deferred += 1; + } + Err(err) => dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", err), + } + state.busy &= !(1 << slot); + state.retired += 1; + } + + fn retire_render(&self, state: &mut State) -> Result { + let Some(flight) = state.rendering.as_ref() else { return Ok(()); }; + let (targets, stamps, doomed, started) = + (flight.targets, flight.stamps, flight.doomed, flight.started); + let done = |root: &RootV27_2, dm: usize| -> Result { + // A command the firmware stopped leaves its queue without reaching its stamp. + if doomed.is_some() { root.render_retired(dm, targets[dm]) } + else { root.render_done(dm, targets[dm], stamps[dm]) } + }; + let mut ta_done = done(&state.root, TILER)?; + let mut fs_done = done(&state.root, FRAGMENT)?; + if !(ta_done && fs_done) + && state.root.render_queue(TILER).1 >= stamps[TILER] + && state.root.render_queue(FRAGMENT).1 >= stamps[FRAGMENT] + { + // As on the compute queue, the final stamp precedes the retired cursor and + // there may be no separate notification when the cursor changes. + let start = Instant::::now(); + while !(ta_done && fs_done) && start.elapsed() < Delta::from_micros(RETIRE_WAIT_US) { + fsleep(Delta::from_micros(20)); + ta_done = done(&state.root, TILER)?; + fs_done = done(&state.root, FRAGMENT)?; + } + } + if ta_done && fs_done { + let flight = state.rendering.take().ok_or(EIO)?; + for slot in flight.slots { + self.retire_slot(state, slot); + } + if let Some(err) = flight.doomed { + self.fail_doomed(state, &flight.packet, err); + self.keep(&mut state.kept_renders, flight); + } else if flight.last { + flight.packet.retired(); + } else if !state.pending(&flight.packet) { + flight.packet.release_guard(); + } + } else if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { + dev_err!(self.dev, "GPU: render timed out: TA retired={} fragment retired={}\n", ta_done, fs_done); + if g14_v27_2_abi::command_timeout_action(state.root.recovery_phase()?) + == g14_v27_2_abi::TimeoutAction::Recover + { + // The firmware has a round open whose event was not seen. Recovery blames the + // work it stopped and waits until that left its queue. Then retire again, so a + // stopped render's fence is signalled and the queue behind it runs without + // waiting for another message; an innocent render got its clock restarted. + if self.recover(state, ETIMEDOUT, -1)? { + return self.retire_render(state); + } + } + self.log_silent_hang(state, "render"); + return Err(ETIMEDOUT); + } + Ok(()) + } + + /// Fails a packet the firmware stopped, once none of its commands is in a queue: its + /// unpublished commands are withdrawn, and its VM records the error (the client sees a + /// lost context). Other clients' work is not touched. + /// + /// A stopped command left its queue without a completion stamp: that proves queue progress, + /// not that the GPU no longer reaches its memory (the G16 rule, `Retirement::Aborted`). So + /// its VM job guard is not released: the error completion quarantines it (no mapping + /// changes), the packet stays in `State::kept` (`blame`), and the caller keeps the flight + /// with its VM binding and scene (`keep`), all for the rest of the boot. Pool slots follow + /// the normal rule: reused only after the firmware unregisters them (`free_slots`), and + /// then in the slot's other buffer, so the stopped command stays intact. + fn fail_doomed(&self, state: &mut State, packet: &Arc, err: Error) { + if state.live(packet) { return; } + if let Some(i) = state.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)) { + let _ = state.pending.remove(i); + } + // Record it even if a racing scheduler timeout already claimed the fence (as fail_all). + if let Some(status) = packet.vm.status() { status.record(err); } + packet.finish(Err(err)); + } + + /// Keeps a stopped command that left its queue, with its VM binding and scene, for the rest + /// of the boot (`State::kept_compute`, `kept_renders`). Its packet is already in + /// `State::kept`, so ownership does not depend on this allocation. If it fails, the flight + /// is leaked, which keeps it as well; it is never dropped. + fn keep(&self, list: &mut KVec, flight: T) { + if list.reserve(1, GFP_KERNEL).is_err() { + dev_warn!(self.dev, "GPU: no memory to track a stopped command; leaking it\n"); + core::mem::forget(flight); + return; + } + if let Err(kernel::alloc::kvec::PushError(flight)) = list.push_within_capacity(flight) { + core::mem::forget(flight); + } + } + + /// Adds the packet of stopped work to `State::kept` before anything is marked, so it stays + /// owned from here on. Err(EIO) once `g14_v27_2_abi::QUARANTINE_LIMIT` packets are kept: + /// the caller then fails all work, and published work stays owned. + fn reserve_kept(&self, state: &mut State, packet: &Arc) -> Result { + if state.kept(packet) { return Ok(()); } + if !g14_v27_2_abi::quarantine_fits(state.kept.len()) { + dev_err!(self.dev, "GPU: {} clients' stopped work kept this boot; not recovering more\n", + state.kept.len()); + return Err(EIO); + } + // Within the capacity allocated at start: never allocates. + state.kept.push_within_capacity(packet.clone()).map_err(|_| EIO) + } + + /// Marks the work the firmware's snapshot named (`g14_v27_2_abi::Attribution`): the + /// published render pair, or the compute command with that completion stamp and the rest of + /// its packet. Err(EIO) if that work is no longer tracked: the caller then fails all work. + fn blame(&self, state: &mut State, error: Error, work: Stopped) -> Result { + let blamed = match work { + Stopped::Render => { + let Some(packet) = state.rendering.as_ref().map(|f| f.packet.clone()) + else { return Err(EIO); }; + self.reserve_kept(state, &packet)?; + let Some(flight) = state.rendering.as_mut() else { return Err(EIO); }; + flight.doomed = Some(error); + latch_guilty(&flight.packet, error); + Blamed { owner: flight.packet.owner, + stamps: [flight.stamps[TILER].raw(), flight.stamps[FRAGMENT].raw()], + stopped: None } + } + Stopped::Compute(stamp) => { + let flights = state.inflight.iter().map(|f| (f.stamp.raw(), f.ordinal)); + let Some((packet, stopped)) = g14_v27_2_abi::stopped_compute(flights, state.retired_total, stamp) + .map(|i| (state.inflight[i].packet.clone(), state.inflight[i].ordinal)) + else { return Err(EIO); }; + self.reserve_kept(state, &packet)?; + let owned = |f: &&mut Inflight| Arc::ptr_eq(&f.packet, &packet); + for flight in state.inflight.iter_mut().filter(owned) { + flight.doomed.get_or_insert(error); + } + latch_guilty(&packet, error); + Blamed { owner: packet.owner, stamps: [stamp, state.queue_stamp()], + stopped: Some(stopped) } + } + }; + Ok(blamed) + } + + /// The last resort of a command timeout: the firmware has no recovery round open, so it + /// reported nothing the host can answer. Logs what a row needs to tell a silent hang from a + /// missed report: queue positions and recovery words (`log_timeout`), the MMU fault status, + /// and the last event ring kinds with the report and round counts. + fn log_silent_hang(&self, state: &State, work: &str) { + state.root.log_timeout(&self.dev); + state.fault.log(&self.dev); + let (events, seen) = state.recent_events(); + let (reports, answered) = state.ledger.counts(); + dev_err!(self.dev, "GPU: {} timed out with no recovery round open: last events {:?} ({} read), {} reports, {} rounds answered (last {:?}); failing all work\n", + work, &events[..seen], state.events_read, reports, answered, state.ledger.last()); + } + + /// Whether the stopped work has left its queue: the render pair, or the compute command at + /// `stopped` (its packet's later commands run normally and are failed as they retire). + fn doomed_retired(&self, state: &mut State, stopped: Option) -> Result { + if let Some(flight) = state.rendering.as_ref() { + if flight.doomed.is_some() { + return Ok(state.root.render_retired(TILER, flight.targets[TILER])? + && state.root.render_retired(FRAGMENT, flight.targets[FRAGMENT])?); + } + } + let Some(ordinal) = stopped.or_else(|| + state.inflight.iter().rev().find(|f| f.doomed.is_some()).map(|f| f.ordinal)) + else { return Ok(true); }; + self.advance(state)?; + Ok(state.retired_total >= ordinal) + } + + /// Waits up to `ms` for the firmware's next recovery phase: 1 before the host answered, + /// 3 with the same `generation` after it answered 2. Ok(None) on timeout; Err(EPROTO) on + /// any phase the protocol does not allow (`recovery_logic::action`). + fn wait_recovery(&self, state: &mut State, answered: bool, generation: u64, ms: i64) + -> Result> { + let start = Instant::::now(); + loop { + let phase = state.root.recovery_phase()?; + let same = !answered || state.root.halt_count()? == generation; + match recovery_logic::action(phase, answered, same) { + RecoveryAction::Wait => {} + RecoveryAction::ProtocolError => { + dev_err!(self.dev, "GPU: recovery phase {} (answered {}, same generation {})\n", + phase, answered, same); + return Err(EPROTO); + } + found => return Ok(Some(found)), + } + if start.elapsed() > Delta::from_millis(ms) { return Ok(None); } + if state.peer.is_crashed() { return Err(EIO); } + let _ = state.root.drain(); + fsleep(Delta::from_millis(1)); + } + } + + /// The firmware recovery handshake after a fault or command timeout (the G16/M3 protocol). + /// The firmware stops every queue and publishes phase 1 with a generation and a snapshot of + /// the stopped work; the host marks that work (`blame`), clears the tiler storage of a + /// stopped tiler, answers 2, waits for 3 with the same generation and answers 0. The stopped + /// work then leaves its queue and fails only its own packet and VM; the next recoveries + /// while it drains are answered the same way, a bounded number of times. Errors here fail + /// all work (the runtime is not trusted). Ok(false) if the firmware opened no round within + /// PHASE1_WAIT_MS: the caller decides whether its report was stale. + fn recover(&self, state: &mut State, error: Error, slot: i32) -> Result { + state.root.log_timeout(&self.dev); + let mut rounds = 0; + // A round the host already answered must not be answered again. + let mut previous = state.ledger.last(); + let began = Instant::::now(); + loop { + // The state lock is held throughout: keep the whole recovery, including a last round + // started at the budget, inside the DRM scheduler's job timeout. + if began.elapsed() > Delta::from_millis(RECOVERY_BUDGET_MS) { + dev_err!(self.dev, "GPU: recovery took more than {} ms\n", RECOVERY_BUDGET_MS); + return Err(ETIMEDOUT); + } + if self.wait_recovery(state, false, 0, PHASE1_WAIT_MS)?.is_none() { + // A further round starts at a phase 1 the drain saw: it cannot go missing. + if rounds > 0 { return Err(EPROTO); } + return Ok(false); + } + let now = ::ktime_get() as u64; + if !recovery_logic::admit(now, &mut state.recovery_window, &mut state.recovery_count) { + dev_err!(self.dev, "GPU: {} recoveries in {} s; not answering more\n", + recovery_logic::WINDOW_LIMIT, recovery_logic::WINDOW_NS / 1_000_000_000); + return Err(EIO); + } + let generation = state.root.halt_count()?; + if !g14_v27_2_abi::new_round(previous, generation) { + dev_err!(self.dev, "GPU: recovery generation {} repeated\n", generation); + return Err(EPROTO); + } + previous = Some(generation); + // Retired work must not be blamed: refresh the retired position first. + self.advance(state)?; + let render = state.rendering.as_ref() + .map(|f| [f.stamps[TILER].raw(), f.stamps[FRAGMENT].raw()]); + let mut attribution = g14_v27_2_abi::Attribution::default(); + let mut entries = 0; + let mut first = [(0u32, 0u32); 4]; + let mut stopped_tiler = false; + for i in 0..gpu::RECOVERY_SNAPSHOT_ENTRIES { + let (flags, target) = state.root.recovery_entry(i)?; + let Some(entry) = SnapshotEntry::decode(flags, target) else { break; }; + entries += 1; + stopped_tiler |= gpu::stopped_tiler(entry.flags); + let retired = state.retired_total; + let inflight = &state.inflight; + attribution.add(entry.flags, entry.target, render, |stamp| { + let flights = inflight.iter().map(|f| (f.stamp.raw(), f.ordinal)); + g14_v27_2_abi::stopped_compute(flights, retired, stamp).is_some() + }); + if let Some(at) = first.get_mut(i) { *at = (entry.flags, entry.target); } + } + let shown = &first[..entries.min(first.len())]; + let (events, seen) = state.recent_events(); + // Every round is attributed: work behind the first stopped command can time out in + // turn. Unnamed or ambiguous stopped work keeps the fail-stop. + let Some(work) = attribution.result() else { + dev_err!(self.dev, "GPU: recovery {} ({:?}, slot {}) names no single tracked command: snapshot ({} entries) {:x?}, events {:?}\n", + generation, error, slot, entries, shown, &events[..seen]); + return Err(EIO); + }; + let blamed = self.blame(state, error, work)?; + let (what, second) = match work { + Stopped::Render => ("render, tiler", "fragment"), + Stopped::Compute(_) => ("compute", "queue at"), + }; + dev_warn!(self.dev, "GPU: recovery {} ({:?}, slot {}, events {:?}): snapshot ({} entries) {:x?}; stopped {} {:#x} ({} {:#x}) of {}[{}]\n", + generation, error, slot, &events[..seen], entries, shown, what, + blamed.stamps[0], second, blamed.stamps[1], + blamed.owner.process(), blamed.owner.pid); + if stopped_tiler { + if let Some(flight) = state.rendering.as_ref() { + let ta_left = state.root.render_retired(TILER, flight.targets[TILER])?; + if !ta_left { + // SAFETY: the firmware is in recovery phase 1 with every queue stopped, + // so the GPU does not access the stopped tiler's TPC; the CPU reads it + // nowhere, and the state lock (held) serializes every render flight. + unsafe { flight.scene.clear_tpc()? }; + dev_err!(self.dev, "GPU: cleared the stopped tiler's TPC storage\n"); + } + } + } + let start = Instant::::now(); + state.root.answer_recovery(2)?; + let mut reached = self.wait_recovery(state, true, generation, HANDSHAKE_MS / 2)?; + if reached.is_none() { + dev_warn!(self.dev, "GPU: no recovery phase 3 in {} ms; ringing the device-control doorbell\n", + HANDSHAKE_MS / 2); + let _ = state.peer.as_mut().send_message(EP_DOORBELL, gpu::DEVICE_CONTROL_KICK); + reached = self.wait_recovery(state, true, generation, HANDSHAKE_MS / 2)?; + } + if reached != Some(RecoveryAction::Resume) { + return Err(ETIMEDOUT); + } + state.root.answer_recovery(0)?; + state.ledger.answered(generation); + dev_info!(self.dev, "GPU: recovery {} answered in {} ms\n", + generation, start.elapsed().as_millis()); + let start = Instant::::now(); + loop { + let _ = state.root.drain(); + if self.doomed_retired(state, blamed.stopped)? { + state.recoveries += 1; + // Work behind the stopped command waited out the recovery: restart its clocks. + let now = Instant::now(); + for flight in state.inflight.iter_mut() { flight.started = now; } + if let Some(flight) = state.rendering.as_mut() { flight.started = now; } + dev_err!(self.dev, + "GPU: recovered ({} so far): stopped work left the queue after {} ms\n", + state.recoveries, start.elapsed().as_millis()); + return Ok(true); + } + if state.peer.is_crashed() { return Err(EIO); } + // Phase 0 = still draining; 1 = a new recovery (a new generation is checked + // at the next round); the host's own phases mean the handshake was misread. + match recovery_logic::action(state.root.recovery_phase()?, false, true) { + RecoveryAction::Wait => {} + RecoveryAction::MarkAndAcknowledge => break, + _ => { + dev_err!(self.dev, "GPU: recovery phase {} while the stopped work drained\n", + state.root.recovery_phase()?); + return Err(EPROTO); + } + } + if start.elapsed() > Delta::from_millis(RECOVERY_DRAIN_MS) { + dev_err!(self.dev, "GPU: stopped work did not leave the queue\n"); + state.root.log_timeout(&self.dev); + return Err(ETIMEDOUT); + } + fsleep(Delta::from_millis(1)); + } + rounds += 1; + dev_err!(self.dev, "GPU: firmware entered recovery again while the stopped work drained ({})\n", + rounds); + if rounds > FURTHER_RECOVERIES { return Err(EIO); } + } + } + + /// Reads the queue's retired position into `retired_total`. + fn advance(&self, state: &mut State) -> Result { + let (_, raw) = state.root.progress()?; + if state.capacity != 0 && raw < state.capacity { + let delta = (raw + state.capacity - state.retired_raw) % state.capacity; + state.retired_total += u64::from(delta); + state.retired_raw = raw; + } + Ok(()) + } + + /// Retires completed commands, publishes more and consumes the firmware's rings. + fn service(&self) { + let mut guard = self.state.lock(); + let Some(state) = Option::as_mut(&mut *guard) else { return; }; + self.service_locked(state); + if !state.running() && (state.pending.is_empty() || self.asleep.load(Ordering::Acquire)) { + self.idle.notify_all(); + } + } + + fn process_events(&self, state: &mut State) -> Result { + // A fault and a timeout read in one pass are one report (`RecoveryLedger`). + let mut reported = false; + // Limit one pass to the ring capacity. Further arrivals notify the worker again. + for _ in 0..256 { + let Some((cursor, kind, event)) = state.root.peek_event()? else { break; }; + state.events[(state.events_read % EVENT_HISTORY as u64) as usize] = kind; + state.events_read += 1; + match event { + FirmwareEvent::Grow(request) if request.halt_count == state.root.halt_count()? => { + let Some(reply) = state.root.reserve_control_reply()? else { + // Leave the GrowTVB request at the head of the event ring until + // there is space for its reply. + if FirmwareWait::kick_due(&mut state.waiting_control)? { + state.peer.as_mut().send_message( + EP_DOORBELL, gpu::DEVICE_CONTROL_KICK, + )?; + } + self.notify.retry(); + return Ok(()); + }; + let granted = state.rendering.as_ref() + .filter(|flight| flight.bind.slot() == request.vm && flight.scene.slot() == request.buffer) + .and_then(|flight| flight.packet.render_queue.as_ref()) + .is_some_and(|queue| queue.grow().unwrap_or(false)); + reply.grow(request, granted)?; + state.peer.as_mut().send_message(EP_DOORBELL, gpu::DEVICE_CONTROL_KICK)?; + } + FirmwareEvent::ChannelError => { + dev_err!(self.dev, "GPU firmware rejected a channel record\n"); + state.root.consume_event(cursor)?; + return Err(EIO); + } + FirmwareEvent::Timeout { slot } => { + dev_err!(self.dev, "GPU firmware timed out a command (slot {})\n", slot); + state.firmware_error.get_or_insert((ETIMEDOUT, slot)); + if !core::mem::replace(&mut reported, true) { state.ledger.report(); } + } + FirmwareEvent::Fault => { + dev_err!(self.dev, "GPU firmware reported a GPU fault\n"); + state.fault.log(&self.dev); + state.firmware_error.get_or_insert((EIO, -1)); + if !core::mem::replace(&mut reported, true) { state.ledger.report(); } + } + FirmwareEvent::Grow(_) | FirmwareEvent::Notification => {} + } + state.waiting_control = None; + state.root.consume_event(cursor)?; + } + Ok(()) + } + + fn service_locked(&self, state: &mut State) { + let _ = state.root.drain(); + if !self.healthy() { return; } + if state.peer.is_crashed() { + dev_err!(self.dev, "GPU firmware crashed; failing {} pending and {} published commands\n", + state.pending.len(), state.inflight.len()); + self.fail_all(state, EIO); + return; + } + if let Err(err) = self.process_events(state) { + dev_err!(self.dev, "GPU: event service failed: {:?}\n", err); + self.fail_all(state, err); + return; + } + if let Some((error, slot)) = state.firmware_error.take() { + match self.recover(state, error, slot) { + Ok(true) => {} + // The host answered this report's round before it read the report (a round + // opened while stopped work drained, or found at a command timeout). + Ok(false) if state.ledger.report_answered() => { + dev_warn!(self.dev, "GPU: firmware report {:?} (slot {}) is for recovery {:?}, already answered\n", + error, slot, state.ledger.last()); + } + Ok(false) => { + dev_err!(self.dev, "GPU: firmware reported {:?} (slot {}) but did not enter recovery\n", + error, slot); + self.fail_all(state, ETIMEDOUT); + return; + } + Err(err) => { + dev_err!(self.dev, "GPU: recovery failed ({:?}); failing all work\n", err); + self.fail_all(state, err); + return; + } + } + } + if let Err(err) = self.retire_render(state) { self.fail_all(state, err); return; } + if let Err(e) = self.advance(state) { self.fail_all(state, e); return; } + // The completion stamp is written before the firmware's post-processing advances the + // retired position, and that advance sends no message. If the front command's stamp + // is there but its position is not, the advance is imminent: wait for it, bounded, + // rather than for a notification that does not come. + if let Some((ordinal, stamp)) = state.inflight.first().map(|f| (f.ordinal, f.stamp)) { + if state.retired_total < ordinal && state.root.queue().1 >= stamp { + state.late += 1; + let start = Instant::::now(); + while state.retired_total < ordinal && start.elapsed() < Delta::from_micros(RETIRE_WAIT_US) { + fsleep(Delta::from_micros(20)); + if let Err(e) = self.advance(state) { self.fail_all(state, e); return; } + } + } + } + while !state.inflight.is_empty() { + let front = &state.inflight[0]; + let (ordinal, started, expected) = (front.ordinal, front.started, front.stamp.raw()); + if state.retired_total >= ordinal { + if let Ok(done) = state.inflight.remove(0) { + self.retire_slot(state, done.slot); + if let Some(err) = done.doomed { + self.fail_doomed(state, &done.packet, err); + self.keep(&mut state.kept_compute, done); + } else if let Some(err) = done.publication_error { + done.packet.release_guard(); + done.packet.finish(Err(err)); + } else if done.last { + done.packet.retired(); + } else if !state.owns(&done.packet) && !state.pending(&done.packet) { + done.packet.release_guard(); + } + } + continue; + } + if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { + dev_err!(self.dev, "GPU: compute command timed out: stamp={:#x} expected={:#x} submitted={} completed={}\n", + state.queue_stamp(), expected, state.submitted, state.retired); + let phase = state.root.recovery_phase().unwrap_or(0); + if g14_v27_2_abi::command_timeout_action(phase) == g14_v27_2_abi::TimeoutAction::Recover { + // The firmware has a round open whose event was not seen. Recovery blames + // the command it names by stamp, which need not be this front one, and + // fails only that client; the others' work resumes after phase 0. + match self.recover(state, ETIMEDOUT, -1) { + Ok(true) => continue, + Ok(false) => {} + Err(err) => { + dev_err!(self.dev, "GPU: recovery failed ({:?}); failing all work\n", err); + self.fail_all(state, err); + return; + } + } + } + self.log_silent_hang(state, "compute"); + self.fail_all(state, ETIMEDOUT); + return; + } + break; + } + if !self.healthy() { return; } + self.pump(state); + } + + /// Rolls back a failed deep-sleep prepare. If an allow-off policy record was published, + /// keep-powered must be confirmed before reopening submissions; otherwise the backend is + /// failed rather than resuming with an unconfirmed idle policy. + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + fn abort_deep_prepare(&self, state: &mut State, policy_published: bool, err: Error) -> Error { + if policy_published { + if let Err(rb_err) = set_idle_policy(&state.root, &mut state.peer, false) { + dev_err!( + self.dev, + "GPU: deep sleep rollback failed to restore keep-powered: {:?}\n", + rb_err + ); + self.fail_all(state, rb_err); + self.notify.set_deep_sleeping(self, false); + self.asleep.store(false, Ordering::Release); + return err; + } + } + self.notify.set_deep_sleeping(self, false); + self.asleep.store(false, Ordering::Release); + if self.healthy() { + self.pump(state); + self.notify.wake(); + } + err + } + + /// Before a system sleep: holds new publications and lets published work retire. + /// + /// For suspend-to-idle (`!deep`), the firmware keeps running with its keep-powered policy + /// (`apple,sleep-retained`). For a firmware-driven deep sleep (`deep`), workers are drained, + /// idle power-off is permitted, and a commit-time stop is registered with the SoC sleep + /// driver so the firmware is idled and halted only after all refusals have passed, then + /// warm-restarted in [`sleep_complete`]. + pub(crate) fn sleep_prepare(&self, deep: bool) -> Result { + let mut guard = self.state.lock(); + if !self.healthy() || guard.is_none() { return Ok(()); } + if self.deep_sleeping.load(Ordering::Acquire) { + return Err(EBUSY); + } + // Hold publications first, then let what is published retire. User space is frozen by + // now; only the scheduler's queued jobs can still arrive, and they wait in `pending`. + self.asleep.store(true, Ordering::Release); + let mut remaining = msecs_to_jiffies(STOP_DRAIN_MS); + loop { + let Some(state) = Option::as_mut(&mut *guard) else { return Ok(()); }; + if !self.healthy() { return Ok(()); } + if !state.running() { + // No recovery round crosses a sleep: a round open now (the firmware stopped + // without anything of ours running) is answered by the service first. + let phase = state.root.recovery_phase().unwrap_or(0); + if phase != 0 { + dev_err!(self.dev, "GPU: sleep refused, firmware recovery phase {}\n", phase); + self.asleep.store(false, Ordering::Release); + self.pump(state); + self.notify.wake(); + return Err(EBUSY); + } + break; + } + if remaining == 0 { + dev_err!(self.dev, "GPU: sleep refused, {} compute commands and {} render pairs still running\n", + state.inflight.len(), usize::from(state.rendering.is_some())); + self.asleep.store(false, Ordering::Release); + self.pump(state); + return Err(EBUSY); + } + remaining = match self.idle.wait_timeout(&mut guard, remaining) { + CondVarTimeoutResult::Woken { jiffies } => jiffies, + _ => 0, + }; + } + if !deep { + if let Some(state) = Option::as_ref(&*guard) { + dev_info!(self.dev, "GPU held for sleep: submitted={} completed={} pending={}\n", + state.submitted, state.retired, state.pending.len()); + } + return Ok(()); + } + #[cfg(not(CONFIG_APPLE_SOC_SLEEP))] + { + if let Some(state) = Option::as_mut(&mut *guard) { + self.asleep.store(false, Ordering::Release); + self.pump(state); + } + return Err(EBUSY); + } + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + { + let has_pwr_controller = + Option::as_ref(&*guard).is_some_and(|s| s.root.has_pwr_controller()); + // SAFETY: Reads global sleep-driver availability and suspend mode. + if !has_pwr_controller || !unsafe { apple_sleep_commit_stops_coprocs() } { + if let Some(state) = Option::as_mut(&mut *guard) { + self.asleep.store(false, Ordering::Release); + self.pump(state); + } + return Err(EBUSY); + } + // Close Notify admission under its spinlock before dropping `state` and draining. + self.notify.set_deep_sleeping(self, true); + drop(guard); + // Flush any queued retry or service work; `deep_sleeping` keeps new work out. + // SAFETY: `self.retry` is an initialized, pinned delayed work item. + unsafe { + let work = Work::raw_get(DelayedWork::raw_as_work(&self.retry)); + let delayed = kernel::container_of!(work, kernel::bindings::delayed_work, work); + kernel::bindings::flush_delayed_work(delayed); + } + self.queue.drain(); + + let mut guard = self.state.lock(); + let Some(state) = Option::as_mut(&mut *guard) else { + self.notify.set_deep_sleeping(self, false); + return Ok(()); + }; + if !self.healthy() || state.running() { + return Err(self.abort_deep_prepare(state, false, EBUSY)); + } + if let Err((published, err)) = try_set_idle_policy(&state.root, &mut state.peer, true) { + dev_err!(self.dev, "GPU: deep sleep refused, allow-off failed: {:?}\n", err); + return Err(self.abort_deep_prepare(state, published, err)); + } + if let Err(err) = wait(&state.root, 500, || Ok(gpu_powered_off(state.asc.fender()))) { + dev_err!( + self.dev, + "GPU: deep sleep refused, GPU did not power off (fender={:#x}): {:?}\n", + state.asc.fender(), + err + ); + return Err(self.abort_deep_prepare(state, true, err)); + } + // SAFETY: `ASC_CPU_CONTROL` lies within the mapped ASC page. + let asc_ctl = unsafe { state.asc.0.add(ASC_CPU_CONTROL) }; + let commit = match KBox::new(CommitStop { + rtk: state.peer.as_raw(), + asc_ctl, + ran: false, + idle_ret: 0, + idle_us: 0, + }, GFP_KERNEL) { + Ok(c) => c, + Err(err) => return Err(self.abort_deep_prepare(state, true, err.into())), + }; + state.commit_stop = Some(commit); + let data = state.commit_stop.as_deref_mut().map_or(core::ptr::null_mut(), |c| { + core::ptr::from_mut(c).cast::() + }); + // SAFETY: `dev` is the live GPU device; `data` points to `state.commit_stop` which + // remains allocated at the same address until unregistered in `sleep_complete`/`stop`. + let ret = unsafe { + apple_sleep_coproc_register_first( + self.dev.as_raw(), + Some(g14_v27_2_commit_stop), + data, + ) + }; + if ret != 0 { + state.commit_stop = None; + return Err(self.abort_deep_prepare(state, true, Error::from_errno(ret))); + } + // SAFETY: `dev` was just registered above. + unsafe { apple_sleep_coproc_set_ready(self.dev.as_raw(), true) }; + dev_info!(self.dev, "GPU prepared for deep sleep: submitted={} completed={} pending={}\n", + state.submitted, state.retired, state.pending.len()); + Ok(()) + } + } + + /// After the sleep: warm-restarts the firmware after a real deep sleep, then publishes held work. + pub(crate) fn sleep_complete(&self) { + let mut guard = self.state.lock(); + let Some(state) = Option::as_mut(&mut *guard) else { + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + self.notify.set_deep_sleeping(self, false); + self.asleep.store(false, Ordering::Release); + return; + }; + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + if let Some(commit) = state.commit_stop.take() { + // SAFETY: `dev` was registered in `sleep_prepare`; `commit` stays live until after + // `apple_sleep_coproc_unregister` completes. + let stopped = commit.ran + || unsafe { apple_sleep_coproc_stopped(self.dev.as_raw()) }; + // SAFETY: `dev` is still registered until the unregister below. + let wake_err = unsafe { apple_sleep_coproc_wake_error(self.dev.as_raw()) }; + // SAFETY: Matches `apple_sleep_coproc_register_first` in `sleep_prepare`. + unsafe { apple_sleep_coproc_unregister(self.dev.as_raw()) }; + // SAFETY: Reads a global flag word. + let real = unsafe { kernel::bindings::pm_resume_via_firmware() }; + if !stopped && !real { + dev_info!(self.dev, "GPU: deep sleep refused before commit; restoring keep-powered\n"); + if let Err(err) = set_idle_policy(&state.root, &mut state.peer, false) { + dev_err!(self.dev, "GPU: failed to restore keep-powered policy: {:?}\n", err); + self.fail_all(state, err); + } + self.notify.set_deep_sleeping(self, false); + self.asleep.store(false, Ordering::Release); + state.waiting_unlink = None; + if self.healthy() { + self.pump(state); + self.notify.wake(); + } + return; + } + if !real { + dev_warn!(self.dev, "GPU: sleep refused after commit stop; firmware stays stopped\n"); + state.hardware_unreachable = true; + self.notify.set_deep_sleeping(self, false); + self.asleep.store(false, Ordering::Release); + self.fail_all(state, EIO); + return; + } + if commit.idle_ret != 0 || wake_err != 0 { + dev_err!( + self.dev, + "GPU: skipping warm restart after commit/wake error (idle_ret={} wake_err={})\n", + commit.idle_ret, + wake_err + ); + state.hardware_unreachable = true; + self.notify.set_deep_sleeping(self, false); + self.asleep.store(false, Ordering::Release); + self.fail_all(state, EIO); + return; + } + let started = Instant::::now(); + let ctl_before = state.asc.read(ASC_CPU_CONTROL); + let restart = (|| -> Result { + // SAFETY: `peer` is live and the firmware was stopped at the commit. + kernel::error::to_result(unsafe { + kernel::bindings::apple_rtkit_warm_restart(state.peer.as_raw()) + })?; + state.asc.write(ASC_CPU_CONTROL, ctl_before | ASC_RUN); + state.peer.as_mut().boot()?; + set_idle_policy(&state.root, &mut state.peer, false)?; + wait(&state.root, 500, || Ok(gpu_powered(state.asc.fender()))) + })(); + self.notify.set_deep_sleeping(self, false); + self.asleep.store(false, Ordering::Release); + state.waiting_unlink = None; + state.waiting_control = None; + match restart { + Ok(()) => { + // No round crosses a sleep (sleep_prepare refuses one), and the restarted + // firmware may count generations again from its start: forget old rounds. + state.ledger = g14_v27_2_abi::RecoveryLedger::default(); + dev_info!(self.dev, "GPU firmware 27.2 back in {} us (commit idle={} {} us, pending={})\n", + started.elapsed().as_micros_ceil(), commit.idle_ret, commit.idle_us, + state.pending.len()); + if self.healthy() { + self.pump(state); + self.notify.wake(); + } + } + Err(err) => { + dev_err!(self.dev, "GPU firmware 27.2 warm restart failed: {:?} (crashed={})\n", + err, state.peer.is_crashed()); + self.fail_all(state, err); + } + } + return; + } + if !self.asleep.swap(false, Ordering::AcqRel) { return; } + dev_info!(self.dev, "GPU released after sleep: running={:?} pending={}\n", + state.root.firmware_running(), state.pending.len()); + state.waiting_unlink = None; + if self.healthy() { self.pump(state); } + } + + /// Stops the firmware: retire or fail outstanding work, allow power-off, then halt the ASC + /// with every mapping still in place (RTKit power-off if the firmware does not stop). + pub(crate) fn stop(&self) { + // Close admission while the service retires work already accepted. + { + let mut guard = self.state.lock(); + let Some(state) = Option::as_mut(&mut *guard) else { return; }; + state.accepting = false; + let start = Instant::::now(); + while self.healthy() && start.elapsed() < Delta::from_millis(STOP_DRAIN_MS.into()) { + let Some(state) = guard.as_ref() else { break; }; + if !state.running() && state.pending.is_empty() { break; } + let _ = self.idle.wait_timeout(&mut guard, msecs_to_jiffies(STOP_DRAIN_MS)); + } + // Serialize the last permitted publication with the transition to shutdown. + self.healthy.store(false, Ordering::Release); + } + // Detach prevents new enqueues. Flush the delayed item before draining the queue, + // since a pending timer may not have queued its work yet. + drop(self.notify.detach()); + // SAFETY: This is the initialized, pinned retry item. It cannot rearm after detach. + unsafe { + let work = Work::raw_get(DelayedWork::raw_as_work(&self.retry)); + let delayed = kernel::container_of!(work, kernel::bindings::delayed_work, work); + kernel::bindings::flush_delayed_work(delayed); + } + self.queue.drain(); + let mut guard = self.state.lock(); + let Some(mut state) = guard.take() else { return; }; + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + if let Some(_commit) = state.commit_stop.take() { + // SAFETY: Matches `apple_sleep_coproc_register_first` in `sleep_prepare`; PM + // unbind/shutdown does not run concurrently with the IRQ-off commit, and `_commit` + // stays alive until after unregister completes. + unsafe { apple_sleep_coproc_unregister(self.dev.as_raw()) }; + } + self.fail_all(&mut state, ENODEV); + if state.hardware_unreachable { + dev_info!( + self.dev, + "GPU stopped: skipping hardware teardown after failed sleep/wake (submitted={} completed={} notifications={})\n", + state.submitted, + state.retired, + self.notify.messages.load(Ordering::Relaxed) + ); + } else { + let allowed = set_idle_policy(&state.root, &mut state.peer, true); + let root = &state.root; + let _ = wait(root, 500, || Ok(root.firmware_running()? == 0)); + let running = root.firmware_running(); + let forced = (running != Ok(0)).then(|| { + // SAFETY: the RTKit instance is live and owned here. + kernel::error::to_result(unsafe { kernel::bindings::apple_rtkit_poweroff(state.peer.as_raw()) }) + }); + state.asc.halt(); + dev_info!(self.dev, "GPU stopped: allow-off={:?} running={:?} forced-off={:?} submitted={} completed={} notifications={} late={} skipped-slots={} deferred-cursors={}\n", + allowed, running, forced, state.submitted, state.retired, + self.notify.messages.load(Ordering::Relaxed), state.late, state.skipped, state.deferred); + if running != Ok(0) && forced != Some(Ok(())) { + dev_err!(self.dev, "GPU firmware did not stop; a reset is required\n"); + } + } + // Keep everything the firmware could reach for the rest of the boot, halted or not: + // its page tables still name these pages, and the boot handoff window that start() + // keeps for the life of the boot still references the graph's tables. Releasing them + // needs that window torn down first, which this runtime does not do. + core::mem::forget(state); + core::mem::forget(self.graph.clone()); + } +} + +impl State { + fn queue_stamp(&self) -> u32 { + self.root.queue().1.raw() + } +} + +pub(crate) struct Backend { + graph: Arc, + runtime: Arc, + scheduler: Arc>, + ids: gpu::SequenceIDs, + preempt_bytes: usize, +} + +impl Backend { + /// Takes over the running firmware after the boot job. + #[allow(clippy::too_many_arguments)] + fn start( + drm: &crate::driver::AsahiDrmDevice, + dev: &device::Device, + notify: Arc, + peer: Peer, + root: crate::fw::types::GpuObject, + graph: Arc, + pool: CommandPool, + asc: AscControl, + fault: FaultStatus, + cfg: &'static hw::HwConfig, + ) -> Result> { + // The runtime is created empty first, so no allocation failure can drop firmware-visible + // state. Every failure after the state is moved in goes through Runtime::stop, which + // halts the firmware and keeps all of its memory. + let runtime_graph = graph.clone(); + let runtime_notify = notify.clone(); + let runtime = match OwnedQueue::new_ordered(c"asahi-g14-v27-2").and_then(|queue| + Arc::pin_init(try_pin_init!(Runtime { + dev: dev.into(), + graph: runtime_graph, + healthy: AtomicBool::new(true), + asleep: AtomicBool::new(false), + deep_sleeping: AtomicBool::new(false), + notify: runtime_notify, + queue, + state <- new_mutex!(None, "g14_v27_2::Runtime::state"), + idle <- new_condvar!("g14_v27_2::Runtime::idle"), + work <- new_work!("g14_v27_2::Runtime::work"), + retry <- new_delayed_work!("g14_v27_2::Runtime::retry"), + }), GFP_KERNEL)) { + Ok(runtime) => runtime, + Err(e) => { + halt_unowned(dev, peer, root, asc, true); + core::mem::forget(pool); + core::mem::forget(graph); + return Err(e); + } + }; + let (queue, last) = root.queue(); + let checked = (|| -> Result<(u32, u32, KVec>)> { + let (head, retired) = root.progress()?; + if head != retired { return Err(EBUSY); } + let kept = KVec::with_capacity(g14_v27_2_abi::QUARANTINE_LIMIT, GFP_KERNEL)?; + Ok((head, root.capacity()?, kept)) + })(); + let (head, capacity, kept) = match checked { + Ok(v) => v, + Err(e) => { + halt_unowned(dev, peer, root, asc, true); + core::mem::forget(pool); + core::mem::forget(graph); + return Err(e); + } + }; + *runtime.state.lock() = Some(State { + peer, root, pool, asc, fault, queue, last, + sequence: u64::from(head), + next_slot: 0, + waiting_unlink: None, + waiting_control: None, + published: 0, + late: 0, + busy: 0, + skipped: 0, + unacked: 0, + deferred: 0, + retired_total: 0, + retired_raw: head, + capacity, + inflight: KVec::new(), + rendering: None, + pending: KVec::new(), + accepting: true, + submitted: 0, + retired: 0, + firmware_error: None, + recoveries: 0, + recovery_window: 0, + recovery_count: 0, + ledger: g14_v27_2_abi::RecoveryLedger::default(), + events: [0; EVENT_HISTORY], + events_read: 0, + kept, + kept_compute: KVec::new(), + kept_renders: KVec::new(), + hardware_unreachable: false, + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + commit_stop: None, + }); + // From here the firmware's messages run the service; one run consumes anything it + // published before. + notify.attach(runtime.clone()); + notify.wake(); + // One run queue per DRM scheduler priority (the front end maps queue priorities 0-3). + let scheduler = match sched::Scheduler::new(drm.as_ref().as_ref(), 4, POOL_SLOTS as u32 - 1, 0, 10000, + c"asahi_g14_sched").and_then(|s| Arc::new(s, GFP_KERNEL).map_err(Into::into)) { + Ok(scheduler) => scheduler, + Err(e) => { + runtime.stop(); + return Err(e); + } + }; + let preempt_bytes = cfg.compute_preempt1_size + 0x20; + match Arc::new(Self { graph, runtime: runtime.clone(), scheduler, ids: gpu::SequenceIDs::default(), preempt_bytes }, + GFP_KERNEL) { + Ok(backend) => Ok(backend), + Err(e) => { runtime.stop(); Err(e.into()) } + } + } + + pub(crate) fn stop(&self) { self.runtime.stop(); } + pub(crate) fn sleep_prepare(&self, deep: bool) -> Result { self.runtime.sleep_prepare(deep) } + pub(crate) fn sleep_complete(&self) { self.runtime.sleep_complete() } +} + +impl Drop for Backend { + fn drop(&mut self) { self.runtime.stop(); } +} + +impl gpu::Gpu for Backend { + fn stats_snapshot(&self) -> Option> { None } + fn as_any(&self) -> &dyn core::any::Any { self } + fn arc_as_any(self: Arc) -> Arc { self as Arc } + fn manager(&self) -> Option<&dyn gpu::GpuManager> { None } + fn init(&self) -> Result { if self.runtime.healthy() { Ok(()) } else { Err(ENODEV) } } + fn ids(&self) -> &gpu::SequenceIDs { &self.ids } + fn is_crashed(&self) -> bool { !self.runtime.healthy() } + fn get_params(&self, params: &mut uapi::drm_asahi_params_global) -> Result { + ::get_params(&self.graph, params)?; + params.max_commands_per_submission = crate::m3::agx_uapi::UAPI_MAX_HARDWARE_COMMANDS; + params.max_attachments = crate::m3::agx_uapi::UAPI_MAX_ATTACHMENTS as u32; + Ok(()) + } + fn supports_vm_status(&self) -> bool { true } + fn feature_flags(&self) -> u64 { + uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS as u64 + | uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_SCHEDULED_QUEUES as u64 + } + fn tracked_submission(&self) -> bool { true } + fn base_clock_hz(&self) -> u32 { ::base_clock_hz(&self.graph) } + fn uat_geometry(&self) -> mmu::UatGeometry { ::uat_geometry(&self.graph) } + fn new_vm(&self, range: Range) -> Result { + self.graph.kernel_uat().new_vm(self.ids.vm.next(), range)?.with_tracked_status() + } + fn new_queue(&self, vm: mmu::Vm, ualloc: Arc>, + ualloc_priv: Arc>, priority: u32, + usc_exec_base: u64, _usage: Arc) -> Result> { + let render = Arc::new(render::QueueRender::new(self.graph.clone(), ualloc, ualloc_priv.clone())?, + GFP_KERNEL)?; + Ok(KBox::new(crate::m3::m3_submit::Queue::new_g14_v27_2(self.runtime.clone(), self.scheduler.clone(), + vm, priority, usc_exec_base, ualloc_priv, self.preempt_bytes, render)?, GFP_KERNEL)?) + } + fn timestamp_window_size(&self) -> u64 { + ::timestamp_window_size(&self.graph) + } + fn map_timestamp_buffer( + &self, + bo: gem::ObjectRef, + range: Range, + window: crate::timestamp::WindowPermit, + ) -> Result { + // The aperture's tables were linked before the firmware window was mirrored (start()). + ::map_timestamp_buffer(&self.graph, bo, range, window) + } +} diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs new file mode 100644 index 00000000000000..96d4992845d68f --- /dev/null +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -0,0 +1,778 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! G14 firmware queue and event records with no kernel or MMIO dependencies. + +#[cfg(not(test))] +use kernel::prelude::kunit_tests; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum QueueError { + Geometry, + Full, +} + +/// Compute the next producer after validating the shared cursor range and available space. +pub(crate) fn queue_head( + capacity: u32, + write: u32, + retired: u32, + count: u32, +) -> Result { + if capacity < 2 + || capacity > u16::MAX.into() + || write >= capacity + || retired >= capacity + || count == 0 + || count >= capacity + { + return Err(QueueError::Geometry); + } + let free = (retired + capacity - write - 1) % capacity; + if count > free { + return Err(QueueError::Full); + } + Ok((write + count) % capacity) +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct GrowRequest { + pub(crate) vm: u32, + pub(crate) buffer: u32, + pub(crate) counter: u32, + pub(crate) subpipe: u32, + pub(crate) halt_count: u64, +} + +impl GrowRequest { + pub(crate) fn decode([vm, buffer, counter, subpipe, halt_low, halt_high]: [u32; 6]) -> Self { + Self { + vm, + buffer, + counter, + subpipe, + halt_count: u64::from(halt_low) | (u64::from(halt_high) << 32), + } + } + + pub(crate) fn reply(self, granted: bool) -> [u32; 16] { + const GROW_REPLY: u32 = 8; + let mut record = [0; 16]; + record[..8].copy_from_slice(&[ + GROW_REPLY, + u32::from(granted), + self.buffer, + self.vm, + self.counter, + self.subpipe, + self.halt_count as u32, + (self.halt_count >> 32) as u32, + ]); + record + } +} + +/// Control-object recovery words (the recovery block G16 and M3 answer in their FirmwareData): +/// the u64 recovery generation, which growth requests also carry; 0x10 on, the recovery phase +/// (firmware 1 -> host 2 -> firmware 3 -> host 0); the snapshot of the work the firmware +/// stopped, {flags u32, target u32} pairs, at the same offset as in the M3 object, up to the +/// next recovery field. Seen on the J473: a stopped tiler {0x1f, its next stamp}, a stopped +/// compute {0x7, its next stamp}. +pub(crate) const RECOVERY_GENERATION: usize = 0x4bf0; +pub(crate) const RECOVERY_PHASE: usize = 0x4c00; +pub(crate) const RECOVERY_SNAPSHOT: usize = 0x4298; +const RECOVERY_SNAPSHOT_END: usize = 0x4b20; +pub(crate) const RECOVERY_SNAPSHOT_ENTRIES: usize = (RECOVERY_SNAPSHOT_END - RECOVERY_SNAPSHOT) / 8; + +/// A snapshot entry of a stopped tiler (valid + tiler bits): its TPC storage must be cleared +/// before the host answers phase 2, as G16 does. +pub(crate) const fn stopped_tiler(flags: u32) -> bool { + flags & 9 == 9 +} + +/// The tracked work a recovery snapshot names. A snapshot entry's target is the completion +/// stamp the stopped command would have written (J473: compute stamp 0x7900 written, entry +/// {0x7, 0x7a00}; tiler stamp 0x2156500 written, entry {0x1f, 0x2156600}). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum Stopped { + /// The published render pair (either of its completion stamps). + Render, + /// The published compute command with this completion stamp. + Compute(u32), +} + +/// Attribution of one recovery round: every valid snapshot entry must name the same tracked, +/// unretired work, else the round is ambiguous and the caller fails all work (fail-stop). +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(crate) struct Attribution { + work: Option, + ambiguous: bool, +} + +impl Attribution { + /// Adds a valid entry. `render` holds the published render pair's completion stamps; + /// `compute(stamp)` says whether an unretired compute command carries that stamp. + pub(crate) fn add(&mut self, flags: u32, target: u32, render: Option<[u32; 2]>, + compute: impl Fn(u32) -> bool) { + let as_render = render.is_some_and(|stamps| stamps.contains(&target)); + // A stopped tiler can only be the render pair. + let as_compute = !stopped_tiler(flags) && compute(target); + let work = match (as_render, as_compute) { + (true, false) => Stopped::Render, + (false, true) => Stopped::Compute(target), + _ => { + self.ambiguous = true; + return; + } + }; + match self.work { + None => self.work = Some(work), + Some(seen) if seen == work => {} + Some(_) => self.ambiguous = true, + } + } + + /// The stopped work, if the round named exactly one tracked command. + pub(crate) fn result(self) -> Option { + if self.ambiguous { None } else { self.work } + } +} + +/// The published compute command a snapshot target names: the one, among commands the queue +/// has not retired (`ordinal > retired`), whose completion stamp is `stamp`. `flights` yields +/// each published command's (completion stamp, ordinal) in publication order. A command that +/// already retired is never blamed, even before the host has taken it off its list. +pub(crate) fn stopped_compute( + flights: impl IntoIterator, + retired: u64, + stamp: u32, +) -> Option { + flights.into_iter().position(|(s, ordinal)| s == stamp && ordinal > retired) +} + +/// What the host does when a command ran past the driver's command timeout. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum TimeoutAction { + /// The firmware has a recovery round open (phase 1): answer it, which blames the work it + /// stopped by stamp and fails only that client. + Recover, + /// No round open: the firmware reported nothing and stopped nothing that the host can + /// answer (a silent hang), or the handshake is in a state the host does not own. Failing + /// all work is the last resort. + FailAll, +} + +/// The driver's command timeout is only a backstop for the firmware's own recovery: it fails +/// every client only when the firmware has no round open. +pub(crate) const fn command_timeout_action(phase: u32) -> TimeoutAction { + match phase { + 1 => TimeoutAction::Recover, + _ => TimeoutAction::FailAll, + } +} + +/// A further recovery round while stopped work drains must carry a new generation; the same +/// generation again means the host misread the handshake. +pub(crate) const fn new_round(previous: Option, generation: u64) -> bool { + match previous { + None => true, + Some(p) => generation != p, + } +} + +/// Tells a fault or timeout report on the event ring that needs a recovery from one whose round +/// the host already answered. +/// +/// The firmware posts the report, then opens the round (phase 1). The host can answer a round +/// before it reads its report: a further round opened while stopped work drains, or a round +/// found at a command timeout. That report is then still in the ring, and the next service pass +/// reads it after the firmware is back at phase 0. It must be consumed, not answered with a +/// wait for a phase 1 that never comes, which would fail all work. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(crate) struct RecoveryLedger { + /// Service passes that read fault or timeout records. One pass counts once, so a fault and + /// a timeout posted for the same stop are one report. + reports: u64, + /// Rounds the host answered. + answered: u64, + /// Generation of the last round answered. + last: Option, +} + +impl RecoveryLedger { + /// A service pass read fault or timeout records. + pub(crate) fn report(&mut self) { + self.reports = self.reports.saturating_add(1); + } + + /// The host answered round `generation` (wrote phase 0). + pub(crate) fn answered(&mut self, generation: u64) { + self.answered = self.answered.saturating_add(1); + self.last = Some(generation); + } + + /// Generation of the last round answered: a round at phase 1 must carry another one + /// (`new_round`). + pub(crate) const fn last(&self) -> Option { + self.last + } + + /// With no new round open after a report: whether every report read so far has a round the + /// host already answered. Then the report is stale and is consumed. Otherwise the firmware + /// reported a stop without entering recovery. + pub(crate) const fn report_answered(&self) -> bool { + self.reports <= self.answered + } + + /// Reports read and rounds answered so far, for a log line. + pub(crate) const fn counts(&self) -> (u64, u64) { + (self.reports, self.answered) + } +} + +/// Packets with stopped work one boot may keep (`Runtime::keep`). A kept packet pins its VM, +/// and with it one user UAT context, and a render one also pins its scene. The limit is half +/// the user contexts, so innocent clients keep the rest. +pub(crate) const QUARANTINE_LIMIT: usize = 31; + +/// Whether one more packet with stopped work fits next to the `kept` ones. When it does not, +/// the caller fails all work, and everything published stays owned. +pub(crate) const fn quarantine_fits(kept: usize) -> bool { + kept < QUARANTINE_LIMIT +} + +/// Whether a packet's VM job guard may be released, so its mappings may change. That needs +/// none of its commands in a queue (`live`) and no stopped command of it kept (`kept`). The +/// firmware may still reach a stopped command's memory, so a kept packet stays owned for the +/// rest of the boot, whoever asks: retirement, `withdraw` or `fail_all`. +pub(crate) const fn guard_releasable(live: bool, kept: bool) -> bool { + !live && !kept +} + +/// Event ring record kinds. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum EventKind { + /// 0: the firmware stopped on a GPU fault and entered recovery. + Fault, + /// 4: the firmware timed out a command (slot at `TIMEOUT_SLOT_OFFSET`) and entered recovery. + Timeout, + /// 6: a buffer growth request. + Grow, + /// 7: the firmware rejected a channel record. + ChannelError, + /// Anything else (stage flags, statistics): nothing for the host to answer. + Notification, +} + +/// Byte offset of the slot a timeout record names. +pub(crate) const TIMEOUT_SLOT_OFFSET: usize = 0x0c; + +pub(crate) const fn event_kind(kind: u32) -> EventKind { + match kind { + 0 => EventKind::Fault, + 4 => EventKind::Timeout, + 6 => EventKind::Grow, + 7 => EventKind::ChannelError, + _ => EventKind::Notification, + } +} + +/// Globals words of the firmware's per-pipe progress checks and compute watchdog, which the +/// shared 0xe48-byte 27.2 Globals hold at the same offsets as the M3 and M4 27.2 runtimes write +/// them (`m3_power_26`, `g16/fw/initdata`), with the 13.5 names: 0x24 relaxed compute kill +/// timeout (ms), 0x78 command submission enabled, 0x998/0x99c/0x9a0 progress-check intervals +/// of 3D/TA/compute (firmware polls), 0x9c8 compute context-switch timeout (ms), 0x9cc compute +/// kill timeout (ms), 0x9b8/0x9bc/0x9c0 the compute back-off words (0x9bc is the G15 layout's +/// `cdm_backoff_timeout`), 0xe28. Left zero, the firmware's progress recovery (armed in HwDataB) +/// times out TA and compute work that runs past a poll within a second or two. The TA interval +/// is the 100 polls the M3 runtime uses for long vertex loops (`m3_config`), not 10. +pub(crate) const GLOBALS_PROGRESS: [(usize, u32); 11] = [ + (0x24, 3000), + (0x78, 1), + (0x998, 40), + (0x99c, 100), + (0x9a0, 250), + (0x9b8, 2), + (0x9bc, 40), + (0x9c0, 5), + (0x9c8, 40), + (0x9cc, 50), + (0xe28, 3), +]; + +/// Size of the 27.2 Globals object. +pub(crate) const GLOBALS_BYTES: usize = 0xe48; + +/// Where the 27.2 compute command (type 3, 0x358 bytes) keeps the user timestamp pair: right +/// after the command time (+0x2c4) and the internal start/end pointers (+0x2cc), the order of +/// the 13.5 compute command and of the 27.2 render commands (vertex +0x5e4, fragment +0x948). +pub(crate) const COMPUTE_USER_TIMESTAMPS: usize = 0x2dc; + +/// The 27.2 compute command's JobMeta flush_stamps word, after the completion stamp, firmware +/// stamp, stamp value and slot (+0x298..+0x2b4); the render commands keep it at the same place +/// of their JobMeta (vertex +0x5a0, fragment +0x904), and the M3 27.2 compute command sets it +/// when it does not coalesce. Set, the firmware flushes the command's stamps when it completes. +pub(crate) const COMPUTE_FLUSH_STAMPS: usize = 0x2b4; +/// The 13.5 compute JobParameters1 inside the 27.2 compute command. +pub(crate) const COMPUTE_JOB_PARAMETERS1: usize = 0x68; + +/// The value of a 27.2 Timestamp operation's user word: like the 13.5 and the M3 27.2 +/// operations it names the command's start/end pair of user destinations, not a destination. +/// Zero when the command has no user timestamps. +pub(crate) fn user_timestamp_pointer(pair_va: u64, pair: [u64; 2]) -> u64 { + if pair == [0; 2] { + 0 + } else { + pair_va + } +} + +fn put64(b: &mut [u8], at: usize, v: u64) { + b[at..at + 8].copy_from_slice(&v.to_le_bytes()); +} + +fn put32(b: &mut [u8], at: usize, v: u32) { + b[at..at + 4].copy_from_slice(&v.to_le_bytes()); +} + +/// Writes a compute helper program (binary: USC offset | 1, data, configuration) into the +/// 13.5 JobParameters1 of a 27.2 compute command, at the places the 13.5 G14 compute path +/// fills: program +0x40, argument +0x48, configuration +0x50. +pub(crate) fn encode_compute_helper(cmd: &mut [u8], binary: u32, data: u64, config: u32) { + put32(cmd, COMPUTE_JOB_PARAMETERS1 + 0x40, binary); + put64(cmd, COMPUTE_JOB_PARAMETERS1 + 0x48, data); + put32(cmd, COMPUTE_JOB_PARAMETERS1 + 0x50, config); +} + +/// Where the 27.2 compute command keeps its sampler heap (u64), sampler count and sampler bound: +/// the 13.5 EncoderParams sampler words, 0x10 bytes further on as in the 27.2 fragment command +/// (13.5 0x8ac, 27.2 0x8bc). The firmware loads the same three words of every command type +/// into the data master's sampler state (TA 0x558/0x560/0x564, 3D 0x8bc/0x8c4/0x8c8, compute +/// here), the count and the bound as 11-bit fields. +pub(crate) const COMPUTE_SAMPLER_HEAP: usize = 0x284; +pub(crate) const COMPUTE_SAMPLER_COUNT: usize = 0x28c; +pub(crate) const COMPUTE_SAMPLER_MAX: usize = 0x290; + +/// The sampler bound the 13.5 compute command stores next to the count: the count plus one, +/// or zero without samplers. +pub(crate) fn compute_sampler_max(count: u32) -> u32 { + if count == 0 { + 0 + } else { + count + 1 + } +} + +/// Writes the sampler heap of a zeroed 27.2 compute command. A command without samplers +/// (heap and count zero) keeps the words zero. The caller has validated the heap: at most +/// 1024 samplers, both fields set or both zero. +pub(crate) fn encode_compute_samplers(cmd: &mut [u8], heap: u64, count: u32) { + put64(cmd, COMPUTE_SAMPLER_HEAP, heap); + put32(cmd, COMPUTE_SAMPLER_COUNT, count); + put32(cmd, COMPUTE_SAMPLER_MAX, compute_sampler_max(count)); +} + +/// Writes the user timestamp pair of a zeroed 27.2 compute command at `cmd_va` and returns the +/// Timestamp operations' user word ([`user_timestamp_pointer`]). +pub(crate) fn encode_compute_timestamps(cmd: &mut [u8], cmd_va: u64, timestamps: [u64; 2]) -> u64 { + put64(cmd, COMPUTE_USER_TIMESTAMPS, timestamps[0]); + put64(cmd, COMPUTE_USER_TIMESTAMPS + 8, timestamps[1]); + user_timestamp_pointer(cmd_va + COMPUTE_USER_TIMESTAMPS as u64, timestamps) +} + +/// The command buffer a pool slot uses: each slot owns two, `2 * slot` and `2 * slot + 1`, +/// and alternates between them. The firmware may still read a retired command's JobMeta for +/// stamp stores it queued after it unlinked the slot, so a slot's next command must not +/// overwrite it. +pub(crate) fn pool_command(slot: usize, second: bool) -> usize { + 2 * slot + usize::from(second) +} + +/// Whether slot `slot`'s next command goes to its second buffer: the one it did not last +/// publish, given one bit per slot set when the last published command used the second. +/// Encoding does not change the bits, so a command that is encoded but never published is +/// replaced in the same spare buffer. +pub(crate) fn spare_buffer(published: u64, slot: usize) -> bool { + published & (1 << slot) == 0 +} + +#[cfg_attr(not(test), kunit_tests(asahi_g14_fw_queues))] +#[cfg_attr(test, allow(dead_code))] +mod tests { + use super::*; + + #[test] + fn a_slot_never_rewrites_the_command_it_published_last() { + const SLOTS: usize = 48; + let mut owner = [usize::MAX; 2 * SLOTS]; + let mut published = 0u64; + let mut last = [usize::MAX; SLOTS]; + for round in 0..6 { + for slot in 0..SLOTS { + let c = pool_command(slot, spare_buffer(published, slot)); + assert!(c < 2 * SLOTS); + // Two buffers per slot, never shared with another slot. + assert!(owner[c] == usize::MAX || owner[c] == slot); + owner[c] = slot; + // Never the buffer the slot last published. + assert_ne!(c, last[slot]); + // Every third slot's publication fails once: the retry takes the same spare. + if (slot + round) % 3 == 0 { + assert_eq!(pool_command(slot, spare_buffer(published, slot)), c); + } + published ^= 1 << slot; + last[slot] = c; + } + } + } + + #[test] + fn head_wraps_and_keeps_one_entry_free() { + assert_eq!(queue_head(8, 7, 7, 2), Ok(1)); + assert_eq!(queue_head(8, 7, 2, 2), Ok(1)); + assert_eq!(queue_head(8, 7, 2, 3), Err(QueueError::Full)); + assert_eq!(queue_head(8, 7, 0, 1), Err(QueueError::Full)); + } + + #[test] + fn corrupted_cursors_and_invalid_depth_fail_before_publication() { + for (capacity, write, read, count) in [ + (0, 0, 0, 1), + (8, 8, 0, 1), + (8, 0, 8, 1), + (8, 0, 0, 0), + (8, 0, 0, 8), + (1 << 16, 0, 0, 1), + ] { + assert_eq!( + queue_head(capacity, write, read, count), + Err(QueueError::Geometry) + ); + } + } + + #[test] + fn growth_replies_echo_request_identity_and_clear_unused_words() { + let request = GrowRequest::decode([2, 9, 31, 1, 0x789a_bcde, 0x1234_5678]); + assert_eq!(request.halt_count, 0x1234_5678_789a_bcde); + assert_eq!( + request.reply(true), + [ + 8, + 1, + 9, + 2, + 31, + 1, + 0x789a_bcde, + 0x1234_5678, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ] + ); + assert_eq!( + request.reply(false), + [ + 8, + 0, + 9, + 2, + 31, + 1, + 0x789a_bcde, + 0x1234_5678, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ] + ); + } + + #[test] + fn recovery_events_are_decoded_and_others_stay_notifications() { + assert_eq!(event_kind(0), EventKind::Fault); + assert_eq!(event_kind(4), EventKind::Timeout); + assert_eq!(event_kind(6), EventKind::Grow); + assert_eq!(event_kind(7), EventKind::ChannelError); + for kind in [1, 2, 3, 5, 8, u32::MAX] { + assert_eq!(event_kind(kind), EventKind::Notification); + } + // The H1 record [4, 0, 0, 1, ...]: slot in the fourth word. + assert_eq!(TIMEOUT_SLOT_OFFSET / 4, 3); + } + + #[test] + fn recovery_block_geometry_matches_the_g16_order() { + // Phase 0x10 above the u64 generation, as in the G16/M3 FirmwareData. + assert_eq!(RECOVERY_PHASE - RECOVERY_GENERATION, 0x10); + assert_eq!(RECOVERY_SNAPSHOT_ENTRIES, 273); + assert!(RECOVERY_SNAPSHOT + 8 * RECOVERY_SNAPSHOT_ENTRIES <= RECOVERY_SNAPSHOT_END); + assert!(RECOVERY_SNAPSHOT_END <= RECOVERY_GENERATION); + } + + #[test] + fn only_a_valid_tiler_entry_clears_tiler_storage() { + // J473 snapshots: stopped tiler {0x1f, ..}, stopped compute {0x7, ..}. + assert!(stopped_tiler(0x1f)); + assert!(!stopped_tiler(0x7)); + assert!(!stopped_tiler(0x8)); + assert!(stopped_tiler(0x9 | (0x70 << 4))); + } + + #[test] + fn a_completed_front_entry_is_not_blamed_for_a_later_stop() { + // Host list: 0x7900 completed but not yet retired by the host, 0x7a00 stopped. + let unretired = [0x7900u32, 0x7a00, 0x7b00]; + let mut a = Attribution::default(); + a.add(0x7, 0x7a00, None, |s| unretired.contains(&s)); + assert_eq!(a.result(), Some(Stopped::Compute(0x7a00))); + } + + #[test] + fn render_entries_name_the_published_pair() { + let pair = Some([0x2156600, 0x3156600]); + let mut a = Attribution::default(); + a.add(0x1f, 0x2156600, pair, |_| false); + a.add(0x7, 0x3156600, pair, |_| false); + assert_eq!(a.result(), Some(Stopped::Render)); + // A stopped tiler that matches no published pair is not pinned on compute. + let mut a = Attribution::default(); + a.add(0x1f, 0x7a00, None, |s| s == 0x7a00); + assert_eq!(a.result(), None); + } + + #[test] + fn untracked_mixed_or_colliding_entries_fail_stop() { + let mut a = Attribution::default(); + assert_eq!(a.result(), None); + a.add(0x7, 0x7c00, None, |s| s == 0x7a00); + assert_eq!(a.result(), None); + let mut a = Attribution::default(); + a.add(0x7, 0x7a00, None, |s| s == 0x7a00 || s == 0x7b00); + a.add(0x7, 0x7b00, None, |s| s == 0x7a00 || s == 0x7b00); + assert_eq!(a.result(), None); + let mut a = Attribution::default(); + a.add(0x7, 0x3156600, Some([0x2156600, 0x3156600]), |s| s == 0x3156600); + assert_eq!(a.result(), None); + } + + #[test] + fn recovery_rounds_while_draining_need_a_new_generation() { + assert!(new_round(None, 1)); + assert!(new_round(Some(1), 2)); + assert!(!new_round(Some(2), 2)); + assert!(new_round(Some(u64::MAX), 0)); + } + + #[test] + fn a_report_read_before_its_round_is_answered_once() { + // Report, then its round: balanced, nothing left over. + let mut ledger = RecoveryLedger::default(); + ledger.report(); + ledger.answered(7); + assert!(ledger.report_answered()); + assert_eq!(ledger.last(), Some(7)); + // A later report with no round open is a stop without recovery: not consumed. + ledger.report(); + assert!(!ledger.report_answered()); + } + + #[test] + fn a_stale_report_after_a_drain_round_is_consumed() { + // Round 7 from its report; round 8 opened while 7's work drained, answered before its + // report was read. Round 8's report then comes on the next pass, at phase 0. + let mut ledger = RecoveryLedger::default(); + ledger.report(); + ledger.answered(7); + ledger.answered(8); + ledger.report(); + assert!(ledger.report_answered()); + // Round 8 is answered: phase 1 with generation 8 again is not a new round. + assert!(!new_round(ledger.last(), 8)); + assert!(new_round(ledger.last(), 9)); + // Its credit is spent: a further report without a round is not stale. + ledger.report(); + assert!(!ledger.report_answered()); + } + + #[test] + fn a_stale_report_after_a_timeout_round_is_consumed() { + // The command timeout found phase 1 and answered round 3 before the event was read. + let mut ledger = RecoveryLedger::default(); + ledger.answered(3); + ledger.report(); + assert!(ledger.report_answered()); + } + + #[test] + fn a_timed_out_compute_is_blamed_by_stamp_and_spares_its_neighbours() { + // Compute list in publication order: (owner, completion stamp, ordinal). Client A's + // command completed and retired, but the host has not taken it off its list yet; B's + // command is the one the firmware timed out (event 4); C's command was published after + // it and waits behind it. + let flights = [('A', 0x7900u32, 1u64), ('B', 0x7a00, 2), ('C', 0x7b00, 3)]; + let retired = 1; + let unretired = |stamp| stopped_compute(flights.iter().map(|f| (f.1, f.2)), retired, stamp) + .is_some(); + // The J473 compute snapshot: one entry {0x7, next stamp of the stopped command}. + let mut a = Attribution::default(); + a.add(0x7, 0x7a00, None, unretired); + assert_eq!(a.result(), Some(Stopped::Compute(0x7a00))); + let stopped = stopped_compute(flights.iter().map(|f| (f.1, f.2)), retired, 0x7a00); + assert_eq!(stopped, Some(1)); + // blame() dooms every listed command of the stopped command's packet, and only those. + let guilty = flights[stopped.unwrap()].0; + let doomed: [bool; 3] = core::array::from_fn(|i| flights[i].0 == guilty); + assert_eq!(doomed, [false, true, false]); + // A target naming the retired front is not blamed on it. + assert_eq!(stopped_compute(flights.iter().map(|f| (f.1, f.2)), retired, 0x7900), None); + let mut a = Attribution::default(); + a.add(0x7, 0x7900, None, unretired); + assert_eq!(a.result(), None); + } + + #[test] + fn the_command_timeout_fails_all_only_without_a_recovery_round() { + assert_eq!(command_timeout_action(1), TimeoutAction::Recover); + // Silent hang: no round open. + assert_eq!(command_timeout_action(0), TimeoutAction::FailAll); + // The host's own phases or anything else: the handshake is not the firmware's to + // continue, so the host does not answer it from a timeout. + for phase in [2, 3, 4, u32::MAX] { + assert_eq!(command_timeout_action(phase), TimeoutAction::FailAll); + } + } + + #[test] + fn a_withdrawn_stopped_packet_keeps_its_guard() { + // The scheduler withdraws a packet whose stopped command left the queue: it is no + // longer live, but it is kept, so its guard stays. + assert!(!guard_releasable(false, true)); + // Still in a queue, kept or not. + assert!(!guard_releasable(true, false)); + assert!(!guard_releasable(true, true)); + // Retired innocent work. + assert!(guard_releasable(false, false)); + } + + #[test] + fn kept_packets_are_bounded_per_boot() { + assert!(quarantine_fits(0)); + assert!(quarantine_fits(QUARANTINE_LIMIT - 1)); + assert!(!quarantine_fits(QUARANTINE_LIMIT)); + assert!(!quarantine_fits(usize::MAX)); + // Innocent clients keep at least half of the 63 user UAT contexts. + assert!(2 * QUARANTINE_LIMIT <= 63); + } + + #[test] + fn progress_words_fit_the_globals_and_leave_power_words_alone() { + let power = [0x58usize, 0x5a, 0x5c, 0x6e, 0x84, 0x88, 0x8c, 0x98]; + for (i, &(at, value)) in GLOBALS_PROGRESS.iter().enumerate() { + assert_eq!(at % 4, 0); + assert!(at + 4 <= GLOBALS_BYTES); + assert_ne!(value, 0); + assert!(power.iter().all(|&p| p + 4 <= at || at + 4 <= p)); + assert!(GLOBALS_PROGRESS[i + 1..].iter().all(|&(other, _)| other != at)); + } + // Every progress interval is set: a zero interval is what stopped work in a poll. + for at in [0x998, 0x99c, 0x9a0] { + assert!(GLOBALS_PROGRESS.iter().any(|&(o, v)| o == at && v != 0)); + } + } + + /// Size of the 27.2 compute command. + const COMPUTE_COMMAND_BYTES: usize = 0x358; + + /// Byte ranges `encode_compute` (gpu/v27_2.rs) writes in the 27.2 compute command, and + /// the words its stream hands the firmware to write (+0x264, +0x2c4, +0x304, +0x314, + /// +0x340). + const COMPUTE_WRITES: &[(usize, usize)] = &[ + (0, 4), (4, 8), (0xc, 4), (0x10, 8), + (0x68, 8), (0x70, 8), (0x78, 8), (0x80, 8), (0x88, 8), (0x90, 8), (0x98, 8), (0xa0, 8), + (0xc0, 8), + (0x1e8, 8), (0x1f0, 4), (0x220, 8), (0x228, 8), (0x264, 8), (0x270, 4), + (0x298, 0x20), (0x2c4, 0x18), (0x304, 8), (0x314, 8), (0x334, 0x14), + ]; + + /// Whether `len` bytes at `at` fit the command and are none the compute encoder uses. + fn free(at: usize, len: usize) -> bool { + at + len <= COMPUTE_COMMAND_BYTES + && COMPUTE_WRITES.iter().all(|&(o, l)| o + l <= at || at + len <= o) + } + + #[test] + fn the_compute_helper_lands_in_free_job_parameters() { + let mut cmd = [0u8; COMPUTE_COMMAND_BYTES]; + encode_compute_helper(&mut cmd, 0x1235, 0x11_2233_4400, 0x7_0000); + let read64 = |at: usize| u64::from_le_bytes(cmd[at..at + 8].try_into().unwrap()); + let read32 = |at: usize| u32::from_le_bytes(cmd[at..at + 4].try_into().unwrap()); + assert_eq!((read32(0xa8), read64(0xb0), read32(0xb8)), (0x1235, 0x11_2233_4400, 0x7_0000)); + for (at, len) in [(0xa8, 4), (0xb0, 8), (0xb8, 4)] { + assert!(free(at, len)); + } + } + + #[test] + fn the_compute_samplers_sit_between_the_encoder_mask_and_the_job_meta() { + let mut cmd = [0u8; COMPUTE_COMMAND_BYTES]; + encode_compute_samplers(&mut cmd, 0x2d_fff4_4000, 1024); + let read64 = |at: usize| u64::from_le_bytes(cmd[at..at + 8].try_into().unwrap()); + let read32 = |at: usize| u32::from_le_bytes(cmd[at..at + 4].try_into().unwrap()); + assert_eq!( + (read64(0x284), read32(0x28c), read32(0x290)), + (0x2d_fff4_4000, 1024, 1025) + ); + // After the encoder mask (+0x270) and before the JobMeta stamps (+0x298), in no other + // word the compute encoder writes. + for (at, len) in [(0x284, 8), (0x28c, 4), (0x290, 4)] { + assert!(free(at, len)); + assert!(0x270 + 4 <= at && at + len <= 0x298); + } + // The firmware takes the count and the bound as 11-bit fields. + assert!(compute_sampler_max(1024) < 1 << 11); + + let mut none = [0u8; COMPUTE_COMMAND_BYTES]; + encode_compute_samplers(&mut none, 0, 0); + assert!(none.iter().all(|&b| b == 0)); + } + + #[test] + fn flush_stamps_follows_the_compute_job_meta_and_misses_the_user_pair() { + // The JobMeta words the encoder writes end right before it: slot at +0x2b0. + assert_eq!(COMPUTE_FLUSH_STAMPS, 0x2b0 + 4); + assert!(COMPUTE_FLUSH_STAMPS + 4 <= COMPUTE_USER_TIMESTAMPS); + assert_eq!(COMPUTE_FLUSH_STAMPS % 4, 0); + } + + #[test] + fn a_timestamp_operation_names_the_pair_only_when_there_is_one() { + assert_eq!(user_timestamp_pointer(0x1000, [0, 0]), 0); + assert_eq!(user_timestamp_pointer(0x1000, [0x40, 0]), 0x1000); + assert_eq!(user_timestamp_pointer(0x1000, [0, 0x48]), 0x1000); + } + + #[test] + fn the_compute_user_pair_lands_in_a_free_place() { + let mut cmd = [0u8; COMPUTE_COMMAND_BYTES]; + let pair = [0xffff_ffa1_8140_0010, 0xffff_ffa1_8140_0018]; + assert_eq!(encode_compute_timestamps(&mut cmd, 0x8000, pair), 0x8000 + 0x2dc); + let read64 = |at: usize| u64::from_le_bytes(cmd[at..at + 8].try_into().unwrap()); + assert_eq!([read64(0x2dc), read64(0x2e4)], pair); + assert!(free(0x2dc, 16)); + // No timestamps leave the command as it was. + let mut empty = [0u8; COMPUTE_COMMAND_BYTES]; + assert_eq!(encode_compute_timestamps(&mut empty, 0x8000, [0; 2]), 0); + assert!(empty.iter().all(|&b| b == 0)); + } +} diff --git a/drivers/gpu/drm/asahi/g14_v27_2_render.rs b/drivers/gpu/drm/asahi/g14_v27_2_render.rs new file mode 100644 index 00000000000000..dbe95b5bd20332 --- /dev/null +++ b/drivers/gpu/drm/asahi/g14_v27_2_render.rs @@ -0,0 +1,1099 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! G14 firmware render command and parameter buffer encoders. +//! +//! The TA and fragment data masters consume distinct records. The render runtime owns both +//! records and the scene until both queues retire. Each logical queue owns its parameter +//! buffer, including the firmware-written page and block cursors, across submissions. + +use crate::alloc::Allocator as _; +use crate::fw::types::GpuArray; +use crate::gpu::QueueInfo; +use crate::m3::agx_attachments::Attachments; +use crate::m3::agx_uapi::UapiRenderCommand; +use crate::{buffer, fw}; +use core::mem::offset_of; +use kernel::{ + new_mutex, + prelude::*, + sync::{Arc, Mutex}, +}; + +type Rv = fw::vertex::raw::RunVertexG14V13_5<'static>; +type Rv13 = fw::vertex::raw::RunVertexG13V13_5<'static>; +type Rf = fw::fragment::raw::RunFragmentG14V13_5<'static>; +type Rf13 = fw::fragment::raw::RunFragmentG13V13_5<'static>; +type Meta = fw::job::raw::JobMeta; + +const TILECTL_DISABLE_CLUSTERING: u32 = 1 << 0; + +pub(crate) const INITBUF_AT: usize = 0xf00; +pub(crate) const OWN_BARRIER_AT: usize = 0xf40; +pub(crate) const OWN_BARRIER_SIZE: usize = 0x40; + +/// G14 stamp dependency queued on FS immediately before RunFragment. +pub(crate) fn encode_own_barrier( + record: &mut [u8], + ta: &QueueInfo, + ta_target: u32, + fs_target: u32, +) { + put32(record, 0, 4); + put64(record, 0x04, ta.fw_stamp); + put64(record, 0x0c, ta.fw_stamp); + put32(record, 0x14, ta_target); + put32(record, 0x20, ta.slot); + put32(record, 0x24, fs_target); +} + +struct Binding { + info: GpuArray, + slot: u32, + blocks: u32, + initialized: bool, +} + +pub(crate) struct QueueRender { + graph: Arc, + buffer: buffer::BufferG14V13_5, + ualloc: Arc>, + binding: Pin>>>, +} + +pub(crate) struct Prep { + scene: buffer::SceneG14V13_5, + aux_fb: GpuArray, + tile: buffer::TileInfo, + scene27: GpuArray, + info_va: u64, + usc: u64, + gpu_gen: crate::hw::GpuGen, + tiling_control: u32, + core_masks: [u32; 2], + pub(crate) buffer_op: Option, +} + +#[derive(Clone, Copy)] +pub(crate) enum BufferOp { + Rebuild, + Grow, +} + +impl Prep { + pub(crate) fn slot(&self) -> u32 { + self.scene.slot() + } + + /// Clears the tiler's TPC storage after a firmware recovery stopped the tiler. + /// Zeroes the scene's TPC after a firmware recovery stopped its tiler. + /// + /// # Safety + /// + /// As [`crate::buffer::Scene::clear_tpc`]. + pub(crate) unsafe fn clear_tpc(&self) -> Result { + // SAFETY: forwarded from the caller. + unsafe { self.scene.clear_tpc(self.tile.tpc_size) } + } +} + +fn to_cmdbuf(r: &UapiRenderCommand) -> kernel::uapi::drm_asahi_cmd_render { + // SAFETY: the UAPI struct is plain data; all-zero is a valid value. + let mut c: kernel::uapi::drm_asahi_cmd_render = unsafe { core::mem::zeroed() }; + // This path has one cluster. The shared tiler only needs dimensions and sample geometry. + c.isp_zls_pixels = r.depth_dimensions; + c.width_px = r.width; + c.height_px = r.height; + c.layers = r.layers; + c.utile_width_px = r.utile_width; + c.utile_height_px = r.utile_height; + c.samples = r.samples; + c.sample_size_B = r.sample_size; + c.ppp_ctrl = r.ppp_control; + c.ppp_multisamplectl = r.multisample_control; + // The tiling parameters carry the vertex helper's configuration, as in the 13.5 command. + c.vertex_helper.cfg = r.vertex_helper.config; + c +} + +impl QueueRender { + pub(crate) fn new( + graph: Arc, + ualloc: Arc>, + ualloc_priv: Arc>, + ) -> Result { + let buffer = graph.new_render_buffer(ualloc.clone(), ualloc_priv)?; + Ok(Self { + graph, + buffer, + ualloc, + binding: KBox::pin_init(new_mutex!(None), GFP_KERNEL)?, + }) + } + + /// Called with the render data masters idle, so making a fresh binding cannot free memory + /// which a previous flight still owns. + pub(crate) fn prepare(&self, r: &UapiRenderCommand, usc: u64) -> Result { + let clusters = + ::get_dyncfg(&self.graph) + .id + .num_clusters; + let tile = crate::queue::QueueInnerG14V13_5::get_tiling_params(&to_cmdbuf(r), clusters)?; + self.buffer.ensure_parameter_blocks(tile.min_tvb_blocks)?; + let mut alloc = + ::alloc(&self.graph); + let scene = self.buffer.new_scene(&mut alloc, &tile)?; + let mut scene27 = alloc.shared.array_empty::(0x48)?; + let aux_fb = self.ualloc.lock().array_empty_tagged(0x8000, b"AXFB")?; + let (user_buffer, stats) = scene.render_addresses(); + put64(scene27.as_mut_slice(), 0x18, user_buffer); + put64(scene27.as_mut_slice(), 0x30, stats); + crate::pgtable::clean_poc(scene27.as_slice().as_ptr(), scene27.len()); + + let mut guard = self.binding.lock(); + if guard + .as_ref() + .is_none_or(|binding| binding.slot != scene.slot()) + || scene.rebind() + { + // Remember a failed rebind too. The slot allocator may return the same token on retry. + *guard = None; + let mut info = alloc.shared.array_empty::(0x90)?; + let p = self.buffer.parameter_info(); + let record = info.as_mut_slice(); + put32(record, 0x08, scene.slot()); + put64(record, 0x18, p.page_list); + put64(record, 0x20, p.page_list); + put32(record, 0x28, p.page_list_size); + put32(record, 0x30, p.max_blocks); + put64(record, 0x3c, p.block_list); + put64(record, 0x44, p.block_control); + put32(record, 0x4c, u32::MAX); + put32(record, 0x50, p.block_size); + put64(record, 0x5c, p.counter); + put32(record, 0x74, p.max_pages); + put32(record, 0x78, p.max_linear_pages); + crate::pgtable::clean_poc(record.as_ptr(), record.len()); + *guard = Some(Binding { + info, + slot: scene.slot(), + blocks: 0, + initialized: false, + }); + } + let binding = guard.as_ref().ok_or(EIO)?; + let buffer_op = if !binding.initialized { + Some(BufferOp::Rebuild) + } else if self.buffer.block_count() > binding.blocks { + Some(BufferOp::Grow) + } else { + None + }; + let cfg = ::get_cfg(&self.graph); + let dyncfg = + ::get_dyncfg(&self.graph); + let core_masks = [ + *dyncfg.id.core_masks_packed.first().unwrap_or(&0), + *dyncfg.id.core_masks_packed.get(1).unwrap_or(&0), + ]; + Ok(Prep { + scene, + aux_fb, + tile, + scene27, + info_va: binding.info.gpu_va().get(), + usc, + gpu_gen: cfg.gpu_gen, + tiling_control: cfg.render.tiling_control | TILECTL_DISABLE_CLUSTERING, + core_masks, + buffer_op, + }) + } + + pub(crate) fn published(&self) { + if let Some(binding) = Option::as_mut(&mut *self.binding.lock()) { + binding.initialized = true; + binding.blocks = self.buffer.block_count(); + self.buffer.increment_parameter_counter(); + } + } + + /// A running TA can request more backing. The firmware computes the page list itself. + pub(crate) fn grow(&self) -> Result { + let mut guard = self.binding.lock(); + let binding = Option::as_mut(&mut *guard).ok_or(EIO)?; + let count = self.buffer.block_count() as usize; + let grown = self.buffer.ensure_parameter_blocks(count + 1)?; + binding.blocks = self.buffer.block_count(); + Ok(grown) + } +} + +fn put32(b: &mut [u8], at: usize, v: u32) { + b[at..at + 4].copy_from_slice(&v.to_le_bytes()); +} +fn put64(b: &mut [u8], at: usize, v: u64) { + b[at..at + 8].copy_from_slice(&v.to_le_bytes()); +} + +/// Inputs both records share. +pub(crate) struct Common { + pub(crate) cmd_va: u64, + pub(crate) stream_va: u64, + pub(crate) tracking: u64, + pub(crate) timestamps: u64, + pub(crate) context: u32, + pub(crate) sequence: u64, + pub(crate) stamp_value: u32, +} + +/// Header shared by every 27.2 record (as compute): type, sequence, context, tracking. +fn header(b: &mut [u8], kind: u32, c: &Common) { + put32(b, 0, kind); + put64(b, 4, c.sequence); + put32(b, 0xc, c.context); + put64(b, 0x10, c.tracking); +} + +/// Write the destinations used by both internal timestamp paths. `user` names the command's +/// pair of user destinations, or is 0 ([`crate::g14_v27_2_abi::user_timestamp_pointer`]). +fn timestamp_op( + s: &mut [u8], + at: usize, + start: bool, + q: &QueueInfo, + command_time: u64, + ts_pointers: u64, + internal0: u64, + internal1: u64, + user: u64, +) { + put32(s, at, if start { 0x8000_0003 } else { 3 }); + put64(s, at + 0x04, command_time); + put64(s, at + 0x0c, ts_pointers); + put64( + s, + at + 0x14, + if start { ts_pointers } else { ts_pointers + 8 }, + ); + put64(s, at + 0x1c, q.queue); + put64(s, at + 0x24, user); + put64(s, at + 0x2c, internal0); + put64(s, at + 0x34, internal1); +} + +pub(crate) fn encode_buffer_op(rec: &mut [u8], c: &Common, p: &Prep, op: BufferOp) { + put32( + rec, + 0, + match op { + BufferOp::Rebuild => 6, + BufferOp::Grow => 5, + }, + ); + put32(rec, 4, c.context); + put32(rec, 8, p.slot()); + // Rebuild is a range operation with zero count. Grow uses the published block producer. + let info = match op { + BufferOp::Rebuild => 0x14, + BufferOp::Grow => 0x0c, + }; + put64(rec, info, p.info_va); + put32(rec, info + 8, c.stamp_value); +} + +/// Encodes the tiler command and its stream. The fragment stamp is its wakeup target. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_vertex( + cmd: &mut [u8], + stream: &mut [u8], + c: &Common, + q: &QueueInfo, + vertex_state: u64, + r: &UapiRenderCommand, + p: &Prep, + frag_stamp: u32, + frag_slot: u32, + timestamps: [u64; 2], + attachments: &Attachments, +) -> Result { + let jp2 = |field: usize| 0x488 + field - offset_of!(Rv, job_params2); + header(cmd, 0, c); + let scene = &p.scene; + let (info_va, scene_va) = (p.info_va, p.scene27.gpu_va().get()); + // StartVertex and FinalizeVertex point past the state header word. + let vertex_state = vertex_state + 4; + let samples_log2 = match r.samples { + 1 => 0, + 2 => 1, + 4 => 2, + _ => return Err(EINVAL), + }; + let utile_config = + ((p.tile.utile_width / 16) << 12) | ((p.tile.utile_height / 16) << 14) | samples_log2; + put32(cmd, 0x18, scene.slot()); + put64(cmd, 0x20, info_va); + put64(cmd, 0x28, scene_va); + put64(cmd, 0x30, scene.kernel_buffer_pointer().into()); + // JobParameters1 at 0x38, 13.5 G13 or G14 internal layout. + macro_rules! write_vtx_jp1 { + ($R:ty) => {{ + let jp1 = |field: usize| 0x38 + field - offset_of!($R, job_params1); + put64(cmd, jp1(offset_of!($R, job_params1.unk_0)), 0x200); + put32(cmd, jp1(offset_of!($R, job_params1.unk_8)), 0x1e3c_e508); + put32(cmd, jp1(offset_of!($R, job_params1.unk_c)), 0x1e3c_e508); + put64( + cmd, + jp1(offset_of!($R, job_params1.tvb_tilemap)), + scene.tvb_tilemap_pointer().into(), + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.tpc)), + scene.tpc_pointer().into(), + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.tvb_heapmeta)), + scene + .tvb_heapmeta_pointer() + .or(0x8000_0000_0000_0000) + .into(), + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.iogpu_unk_54)), + 0x3a_0012_006b_0003, + ); + put64(cmd, jp1(offset_of!($R, job_params1.iogpu_unk_56)), 1); + put32( + cmd, + jp1(offset_of!($R, job_params1.utile_config)), + utile_config, + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.ppp_multisamplectl)), + r.multisample_control, + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.tvb_layermeta)), + scene.tvb_layermeta_pointer().into(), + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.preempt_buf1)), + scene.preempt_buf_1_pointer().into(), + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.preempt_buf2)), + scene.preempt_buf_2_pointer().into(), + ); + put64(cmd, jp1(offset_of!($R, job_params1.unk_80)), 1); + put64( + cmd, + jp1(offset_of!($R, job_params1.preempt_buf3)), + scene.preempt_buf_3_pointer().or(0x4_0000_0000_0000).into(), + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.vdm_ctrl_stream_base)), + r.vdm_base, + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.usc_exec_base_ta)), + p.usc, + ); + put64(cmd, jp1(offset_of!($R, job_params1.unk_f8)), 0x8c60); + put32( + cmd, + jp1(offset_of!($R, job_params1.helper_program)), + r.vertex_helper.binary, + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.helper_arg)), + r.vertex_helper.data, + ); + put32(cmd, jp1(offset_of!($R, job_params1.unk_118)), 0x1c); + }}; + } + if p.gpu_gen == crate::hw::GpuGen::G13 { + write_vtx_jp1!(Rv13); + let jp1 = |field: usize| 0x38 + field - offset_of!(Rv13, job_params1); + let mask_off = jp1(offset_of!(Rv13, job_params1.core_mask)); + put32(cmd, mask_off, p.core_masks[0]); + put32(cmd, mask_off + 4, p.core_masks[1]); + put32( + cmd, + jp1(offset_of!(Rv13, job_params1.tiling_control)), + p.tiling_control, + ); + put64( + cmd, + jp1(offset_of!(Rv13, job_params1.unk_f0)), + 0x1c + u64::from(crate::util::align(p.tile.meta1_blocks, 4)), + ); + } else { + write_vtx_jp1!(Rv); + } + // Tiling parameters at 0x3bc (13.5 block), + the new word at +0x30. + { + let at = 0x3bc; + let n = core::mem::size_of::(); + // SAFETY: `TilingParameters` is a `repr(C)` plain-data struct of `n` bytes. + let src = unsafe { + core::slice::from_raw_parts(core::ptr::from_ref(&p.tile.params).cast::(), n) + }; + cmd[at..at + n].copy_from_slice(src); + put32(cmd, at + 0x30, scene.slot()); + } + put64(cmd, 0x45c, scene.tpc_pointer().into()); + put64(cmd, 0x464, p.tile.tpc_size as u64); + let mseq = 0x46c; + const STREAM: u32 = 0x300; + put64(cmd, mseq, c.stream_va); + put32(cmd, mseq + 8, STREAM); + put32(cmd, 0x478, frag_slot); + put32(cmd, 0x47c, frag_stamp); + put64( + cmd, + jp2(offset_of!(Rv, job_params2.preempt_buf1)), + scene.preempt_buf_1_pointer().into(), + ); + put64(cmd, 0x558, r.sampler_heap); + put32(cmd, 0x560, u32::from(r.sampler_count)); + put32(cmd, 0x564, u32::from(r.sampler_count)); + // Allow a synchronous parameter-buffer request. + put32(cmd, 0x570, 1); + // Job meta at 0x580. + put64(cmd, 0x584, q.stamp); + put64(cmd, 0x58c, q.fw_stamp); + put32(cmd, 0x594, c.stamp_value); + put32(cmd, 0x598, q.slot); + // flush_stamps: the firmware's per-queue completion walk stops at a command whose meta + // leaves this clear, so the host stamp is never written and later commands never retire. + put32(cmd, 0x5a0, 1); + // The event-control index is independent of the completion stamp slot. + put64(cmd, 0x5a4, 0); // uuid (compute leaves it 0) + let command_time = c.cmd_va + 0x5cc; + let ts = c.cmd_va + 0x5d4; + put64(cmd, 0x5d4, c.timestamps); + put64(cmd, 0x5dc, c.timestamps + 8); + put64(cmd, 0x5e4, timestamps[0]); + put64(cmd, 0x5ec, timestamps[1]); + let user = crate::g14_v27_2_abi::user_timestamp_pointer(c.cmd_va + 0x5e4, timestamps); + let internal0 = c.cmd_va + 0x61c; + let internal1 = c.cmd_va + 0x538; + let flag = c.cmd_va + 0x568; + let unk_pointee = c.cmd_va + 0x480; + let unk_buf_0 = c.cmd_va + 0x5b4; + let tiling = c.cmd_va + 0x3bc; + let jp1_va = c.cmd_va + 0x38; + + // Stream: StartVertex (0x19c), Timestamp, wait for the vertex pipe, Timestamp, + // FinalizeVertex (0x9c), end. + let s = stream; + put32(s, 0, 5); + put64(s, 0x04, tiling); + put64(s, 0x0c, jp1_va); + put64(s, 0x14, info_va); + put64(s, 0x1c, scene_va); + put64(s, 0x24, vertex_state); + put64(s, 0x2c, q.queue); + put64(s, 0x34, flag); + put32(s, 0x3c, c.context); + put32(s, 0x40, 1); + put32(s, 0x48, scene.slot()); + // Match the command metadata: the default event-control index is zero. + put64(s, 0x5c, unk_pointee); + put64(s, 0x64, unk_buf_0); + s[0x80..0x180].copy_from_slice(&attachments.0[..0x100]); + put32(s, 0x180, u32::from(attachments.count())); + put64(s, 0x188, c.sequence); + put32(s, 0x190, q.slot); + put32(s, 0x194, 1); // The tiler command uses the single-cluster layout. + timestamp_op( + s, + 0x19c, + true, + q, + command_time, + ts, + internal0, + internal1, + user, + ); + put32(s, 0x1e8, 0x0000_0100); + timestamp_op( + s, + 0x1ec, + false, + q, + command_time, + ts, + internal0, + internal1, + user, + ); + let fin = 0x238; + put32(s, fin, 6); + put64(s, fin + 0x04, scene_va); + put64(s, fin + 0x0c, info_va); + put64(s, fin + 0x14, vertex_state); + put64(s, fin + 0x1c, q.queue); + put64(s, fin + 0x24, flag); + put32(s, fin + 0x2c, c.context); + put64(s, fin + 0x34, unk_pointee); + put64(s, fin + 0x48, q.fw_stamp); + put32(s, fin + 0x50, c.stamp_value); + put32(s, fin + 0x78, (-(fin as i32)) as u32); + put64(s, fin + 0x8d, c.cmd_va + 0x60c); + put32(s, fin + 0x9c, 0x4000_0002); + debug_assert!(fin + 0xa0 <= STREAM as usize); + Ok(()) +} + +/// Translate the legacy common fragment fields around the wider metadata and sampler tail. +const fn frag_at(offset: usize) -> usize { + let meta = offset_of!(Rf, meta); + let event_seq = meta + offset_of!(Meta, event_seq); + if offset < FRAG_SAMPLERS13 { + offset + } else if offset < meta { + offset + 0x10 + } else if offset < event_seq { + offset + 0x14 + } else { + offset + 0x18 + } +} + +/// 13.5 offset of the sampler array (encoder_params), where the 27.2 +0x10 band starts. +const FRAG_SAMPLERS13: usize = 0x8ac; +/// 27.2 fragment stream: op 7 (0x1b4), Timestamp, WFI 0x00010000, Timestamp, op 8 (0xbc), end. +const FRAG_STREAM: u32 = 0x340; +/// Encodes the fragment command and its stream. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_fragment( + cmd: &mut [u8], + stream: &mut [u8], + c: &Common, + q: &QueueInfo, + fragment_state: u64, + r: &UapiRenderCommand, + p: &Prep, + timestamps: [u64; 2], + attachments: &Attachments, +) -> Result { + let fragment_state = fragment_state + 4; + // Anchors of the 13.5 layout this mapping assumes. + if offset_of!(Rf, meta) != 0x8d0 + || offset_of!(Rf, encoder_params) + offset_of!(fw::job::raw::EncoderParams, sampler_array) + != FRAG_SAMPLERS13 + || offset_of!(Rf, job_params1) != 0x80 + || offset_of!(Rf, job_params2) != 0x3c8 + || offset_of!(Rf, job_params3) != 0x4b8 + || cmd.len() < 0x9b0 + || stream.len() < FRAG_STREAM as usize + { + return Err(EINVAL); + } + let scene = &p.scene; + let samples_log2 = match r.samples { + 1 => 0u32, + 2 => 1, + 4 => 2, + _ => return Err(EINVAL), + }; + let utile_config = + ((p.tile.utile_width / 16) << 12) | ((p.tile.utile_height / 16) << 14) | samples_log2; + let mut tile_config: u64 = 0x280; + if r.layers > 1 { + tile_config |= 1; + } + if r.flags & 2 != 0 { + tile_config |= 0x10000; + } // process empty tiles + let pixels_per_utile = u32::from(r.utile_width) * u32::from(r.utile_height); + let tib_blocks = (u32::from(r.sample_size) * (pixels_per_utile << samples_log2)).div_ceil(2048); + let isp_ctl = 0xc000u32 | (r.flags & (1 << 18)); // depth bias is integer + let rgn_size = u64::from(p.tile.params.rgn_size); + let (info_va, scene_va) = (p.info_va, p.scene27.gpu_va().get()); + let va = |o: usize| c.cmd_va + o as u64; + let w32 = |b: &mut [u8], o13: usize, v: u32| put32(b, frag_at(o13), v); + let w64 = |b: &mut [u8], o13: usize, v: u64| put64(b, frag_at(o13), v); + let w16 = |b: &mut [u8], o13: usize, v: u16| { + let a = frag_at(o13); + b[a..a + 2].copy_from_slice(&v.to_le_bytes()); + }; + + // Header: 0x10 stays 0; microsequence at 0x14/0x1c; tracking slot at 0x20. + put32(cmd, 0, 1); + put64(cmd, 4, c.sequence); + put32(cmd, 0xc, c.context); + let mseq = 0x14; + put64(cmd, mseq, c.stream_va); + put32(cmd, mseq + 8, FRAG_STREAM); + put64(cmd, 0x20, c.tracking); + put64(cmd, 0x28, info_va); + put64(cmd, 0x30, scene_va); + w64( + cmd, + offset_of!(Rf, unk_buffer_buf), + scene.kernel_buffer_pointer().into(), + ); + w64( + cmd, + offset_of!(Rf, tvb_tilemap), + scene.tvb_tilemap_pointer().into(), + ); + w64( + cmd, + offset_of!(Rf, ppp_multisamplectl), + r.multisample_control, + ); + w32(cmd, offset_of!(Rf, samples), u32::from(r.samples)); + w16( + cmd, + offset_of!(Rf, tiles_per_mtile_y), + p.tile.tiles_per_mtile_y as u16, + ); + w16( + cmd, + offset_of!(Rf, tiles_per_mtile_x), + p.tile.tiles_per_mtile_x as u16, + ); + w32(cmd, offset_of!(Rf, isp_merge_upper_x), r.merge_upper_x); + w32(cmd, offset_of!(Rf, isp_merge_upper_y), r.merge_upper_y); + w64(cmd, offset_of!(Rf, tile_count), u64::from(p.tile.tiles)); + // Job parameters 1 (13.5 G13 or G14 internal layout). + let g13 = p.gpu_gen == crate::hw::GpuGen::G13; + macro_rules! write_frag_jp1 { + ($R:ty) => {{ + w32(cmd, offset_of!($R, job_params1.utile_config), utile_config); + w64( + cmd, + offset_of!($R, job_params1.bg.rsrc_spec), + r.background.resource_spec, + ); + w64( + cmd, + offset_of!($R, job_params1.bg.address), + u64::from(r.background.usc), + ); + w64( + cmd, + offset_of!($R, job_params1.ppp_multisamplectl), + r.multisample_control, + ); + w64( + cmd, + offset_of!($R, job_params1.isp_scissor_base), + r.scissor_base, + ); + w64( + cmd, + offset_of!($R, job_params1.isp_dbias_base), + r.depth_bias_base, + ); + w64( + cmd, + offset_of!($R, job_params1.isp_oclqry_base), + r.occlusion_query_base, + ); + for base in [ + offset_of!($R, job_params1.aux_fb_info), + offset_of!($R, job_params3.aux_fb_info), + ] { + w32(cmd, base, isp_ctl); + w32(cmd, base + 8, u32::from(r.width)); + w32(cmd, base + 0xc, u32::from(r.height)); + w64(cmd, base + 0x10, 0x10_0000); + } + w64( + cmd, + offset_of!($R, job_params1.isp_zls_pixels), + u64::from(r.depth_dimensions), + ); + w64(cmd, offset_of!($R, job_params1.zls_ctrl), r.zls_control); + for (o, v) in [ + (offset_of!($R, job_params1.z_load), r.depth.base), + (offset_of!($R, job_params1.z_store), r.depth.base), + (offset_of!($R, job_params1.s_load), r.stencil.base), + (offset_of!($R, job_params1.s_store), r.stencil.base), + ( + offset_of!($R, job_params1.z_load_stride), + u64::from(r.depth.stride), + ), + ( + offset_of!($R, job_params1.z_store_stride), + u64::from(r.depth.stride), + ), + ( + offset_of!($R, job_params1.s_load_stride), + u64::from(r.stencil.stride), + ), + ( + offset_of!($R, job_params1.s_store_stride), + u64::from(r.stencil.stride), + ), + ( + offset_of!($R, job_params1.z_load_comp), + r.depth.compression_base, + ), + ( + offset_of!($R, job_params1.z_load_comp_stride), + u64::from(r.depth.compression_stride), + ), + ( + offset_of!($R, job_params1.z_store_comp), + r.depth.compression_base, + ), + ( + offset_of!($R, job_params1.z_store_comp_stride), + u64::from(r.depth.compression_stride), + ), + ( + offset_of!($R, job_params1.s_load_comp), + r.stencil.compression_base, + ), + ( + offset_of!($R, job_params1.s_load_comp_stride), + u64::from(r.stencil.compression_stride), + ), + ( + offset_of!($R, job_params1.s_store_comp), + r.stencil.compression_base, + ), + ( + offset_of!($R, job_params1.s_store_comp_stride), + u64::from(r.stencil.compression_stride), + ), + ( + offset_of!($R, job_params1.tvb_tilemap), + scene.tvb_tilemap_pointer().into(), + ), + ( + offset_of!($R, job_params1.tvb_layermeta), + scene.tvb_layermeta_pointer().into(), + ), + ( + offset_of!($R, job_params1.mtile_stride_dwords), + (4 * rgn_size) << 24, + ), + ( + offset_of!($R, job_params1.tvb_heapmeta), + scene.tvb_heapmeta_pointer().into(), + ), + (offset_of!($R, job_params1.tile_config), tile_config), + (offset_of!($R, job_params1.aux_fb), p.aux_fb.gpu_va().get()), + (offset_of!($R, job_params1.usc_exec_base_isp), p.usc), + (offset_of!($R, job_params1.unk_140), 0x8c60), + ( + offset_of!($R, job_params1.helper_arg), + r.fragment_helper.data, + ), + (offset_of!($R, job_params1.unk_158), 0x1c), + ] { + w64(cmd, o, v); + } + w32( + cmd, + offset_of!($R, job_params1.helper_program), + r.fragment_helper.binary, + ); + }}; + } + if g13 { + write_frag_jp1!(Rf13); + } else { + write_frag_jp1!(Rf); + w64(cmd, offset_of!(Rf, job_params1.unk_58_g14_0), 0x404_0404); + } + // Job parameters 2, + the new JP2+0x44 = buffer slot (cmd+0x40c). + w32( + cmd, + offset_of!(Rf, job_params2.eot_rsrc_spec), + r.end_of_tile.resource_spec as u32, + ); + w32(cmd, offset_of!(Rf, job_params2.eot_usc), r.end_of_tile.usc); + w32( + cmd, + offset_of!(Rf, job_params2.isp_merge_upper_x), + r.merge_upper_x, + ); + w32( + cmd, + offset_of!(Rf, job_params2.isp_merge_upper_y), + r.merge_upper_y, + ); + w16( + cmd, + offset_of!(Rf, job_params2.utiles_per_mtile_y), + p.tile.utiles_per_mtile_y as u16, + ); + w16( + cmd, + offset_of!(Rf, job_params2.utiles_per_mtile_x), + p.tile.utiles_per_mtile_x as u16, + ); + w32( + cmd, + offset_of!(Rf, job_params2.tile_counts), + ((p.tile.tiles_y - 1) << 12) | (p.tile.tiles_x - 1), + ); + w32(cmd, offset_of!(Rf, job_params2.tib_blocks), tib_blocks); + w32( + cmd, + offset_of!(Rf, job_params2.isp_bgobjdepth), + r.depth_clear, + ); + w32( + cmd, + offset_of!(Rf, job_params2.isp_bgobjvals), + if g13 { r.stencil_clear | 0x400 } else { r.stencil_clear }, + ); + w32(cmd, offset_of!(Rf, job_params2.unk_3c), 1); + w32( + cmd, + offset_of!(Rf, job_params2.helper_cfg), + r.fragment_helper.config, + ); + put32(cmd, 0x40c, scene.slot()); + // Job parameters 3 (13.5 fill). + for (o, v) in [ + ( + offset_of!(Rf, job_params3.isp_dbias_base.ptr), + r.depth_bias_base, + ), + ( + offset_of!(Rf, job_params3.isp_scissor_base.ptr), + r.scissor_base, + ), + ( + offset_of!(Rf, job_params3.isp_oclqry_base), + r.occlusion_query_base, + ), + ( + offset_of!(Rf, job_params3.unk_partial_bg.rsrc_spec), + r.partial_background.resource_spec, + ), + ( + offset_of!(Rf, job_params3.unk_partial_bg.address), + u64::from(r.partial_background.usc), + ), + ( + offset_of!(Rf, job_params3.partial_bg.rsrc_spec), + r.partial_background.resource_spec, + ), + ( + offset_of!(Rf, job_params3.partial_bg.address), + u64::from(r.partial_background.usc), + ), + (offset_of!(Rf, job_params3.zls_ctrl), r.zls_control), + ( + offset_of!(Rf, job_params3.unk_290), + if g13 { 0 } else { 0x404_0404 }, + ), + (offset_of!(Rf, job_params3.z_load), r.depth.base), + ( + offset_of!(Rf, job_params3.z_partial_stride), + u64::from(r.depth.stride), + ), + ( + offset_of!(Rf, job_params3.z_partial_comp_stride), + u64::from(r.depth.compression_stride), + ), + (offset_of!(Rf, job_params3.z_store), r.depth.base), + (offset_of!(Rf, job_params3.z_partial), r.depth.base), + ( + offset_of!(Rf, job_params3.z_partial_comp), + r.depth.compression_base, + ), + (offset_of!(Rf, job_params3.s_load), r.stencil.base), + ( + offset_of!(Rf, job_params3.s_partial_stride), + u64::from(r.stencil.stride), + ), + ( + offset_of!(Rf, job_params3.s_partial_comp_stride), + u64::from(r.stencil.compression_stride), + ), + (offset_of!(Rf, job_params3.s_store), r.stencil.base), + (offset_of!(Rf, job_params3.s_partial), r.stencil.base), + ( + offset_of!(Rf, job_params3.s_partial_comp), + r.stencil.compression_base, + ), + (offset_of!(Rf, job_params3.tile_config), tile_config), + ( + offset_of!(Rf, job_params3.isp_zls_pixels), + u64::from(r.depth_dimensions), + ), + ] { + w64(cmd, o, v); + } + w32(cmd, offset_of!(Rf, job_params3.tib_blocks), tib_blocks); + for base in [ + offset_of!(Rf, job_params3.unk_partial_eot), + offset_of!(Rf, job_params3.partial_eot), + ] { + w32( + cmd, + base + offset_of!(fw::fragment::raw::EotProgram, rsrc_spec), + r.partial_end_of_tile.resource_spec as u32, + ); + w32( + cmd, + base + offset_of!(fw::fragment::raw::EotProgram, address), + r.partial_end_of_tile.usc, + ); + } + w32( + cmd, + offset_of!(Rf, job_params3.isp_bgobjdepth), + r.depth_clear, + ); + w32( + cmd, + offset_of!(Rf, job_params3.isp_bgobjvals), + r.stencil_clear, + ); + w32( + cmd, + offset_of!(Rf, job_params3.sample_size), + u32::from(r.sample_size), + ); + put64(cmd, 0x8bc, r.sampler_heap); + put32(cmd, 0x8c4, u32::from(r.sampler_count)); + put32(cmd, 0x8c8, u32::from(r.sampler_count)); + w32(cmd, offset_of!(Rf, encoder_params.unk_mask), u32::MAX); + w32( + cmd, + offset_of!(Rf, process_empty_tiles), + u32::from(r.flags & 2 != 0), + ); + w32(cmd, offset_of!(Rf, no_clear_pipeline_textures), 1); + // 0x8d8 unk_pointee, 0x8dc skip/done flag, 0x770, 0x888, 0x88c stay 0. + let meta = offset_of!(Rf, meta); + w64(cmd, meta + offset_of!(Meta, stamp), q.stamp); + w64(cmd, meta + offset_of!(Meta, fw_stamp), q.fw_stamp); + w32(cmd, meta + offset_of!(Meta, stamp_value), c.stamp_value); + w32(cmd, meta + offset_of!(Meta, stamp_slot), q.slot); + // evctl_index 0 (13.5 fixed), uuid (u64 at 0x908) 0, event_seq 0. flush_stamps (0x904) is + // set, as for the tiler: without it the completion walk stops at this command. + put32(cmd, 0x904, 1); + w64(cmd, offset_of!(Rf, unk_buf_10), 1); + w64( + cmd, + offset_of!(Rf, timestamp_pointers.start_addr), + c.timestamps, + ); + w64( + cmd, + offset_of!(Rf, timestamp_pointers.end_addr), + c.timestamps + 8, + ); + let command_time = va(frag_at(offset_of!(Rf, command_time))); + let ts = va(frag_at(offset_of!(Rf, timestamp_pointers))); + put64(cmd, 0x948, timestamps[0]); + put64(cmd, 0x950, timestamps[1]); + let user = crate::g14_v27_2_abi::user_timestamp_pointer(va(0x948), timestamps); + let internal0 = va(0x980); + let internal1 = va(0x89c); + let (jp1, jp2) = (va(0x80), va(0x3c8)); + let busy = va(frag_at(offset_of!(Rf, busy_flag))); + let unk_pointee = va(frag_at(offset_of!(Rf, unk_pointee))); + let flag = va(frag_at(offset_of!(Rf, unk_v13_3))); + let flag758 = va(frag_at(offset_of!(Rf, unk_758_flag))); + let unk_buf_0 = va(frag_at(offset_of!(Rf, unk_buf_0))); + if (busy, unk_pointee, flag, flag758, unk_buf_0, command_time) + != ( + va(0x888), + va(0x8d8), + va(0x8dc), + va(0x770), + va(0x918), + va(0x930), + ) + { + return Err(EINVAL); + } + + // op 7 StartFragment (0x1b4). + let s = stream; + put32(s, 0, 7); + put64(s, 0x04, jp2); + put64(s, 0x0c, jp1); + put64(s, 0x14, scene_va); + put64(s, 0x1c, fragment_state); + put64(s, 0x24, busy); + put64(s, 0x2c, scene_va + 0x3c); + put64(s, 0x34, unk_pointee); + put64(s, 0x3c, flag); + put64(s, 0x44, q.queue); + put64(s, 0x4c, c.cmd_va); + put32(s, 0x54, c.context); + put32(s, 0x58, 1); + put32(s, 0x60, scene.slot()); + put32(s, 0x64, 0); // sync_grow + put32(s, 0x68, 0); // event_seq + put32(s, 0x6c, 0); // evctl_index + put64(s, 0x74, flag758); + put64(s, 0x7c, unk_buf_0); + put64(s, 0x98, 0); // uuid + s[0xa0..0x1a0].copy_from_slice(&attachments.0[..0x100]); + put32(s, 0x1a0, u32::from(attachments.count())); + put64(s, 0x1a8, c.sequence); + put32(s, 0x1b0, q.slot); + timestamp_op( + s, + 0x1b4, + true, + q, + command_time, + ts, + internal0, + internal1, + user, + ); + put32(s, 0x200, 0x0001_0000); // wait for the fragment pipe + timestamp_op( + s, + 0x204, + false, + q, + command_time, + ts, + internal0, + internal1, + user, + ); + // op 8 FinalizeFragment (0xbc). + let fin = 0x250; + put32(s, fin, 8); + put64(s, fin + 0x04, 0); // uuid + put64(s, fin + 0x0c, q.fw_stamp); + put32(s, fin + 0x14, c.stamp_value); + put64(s, fin + 0x1c, scene_va); + put64(s, fin + 0x24, info_va); + put32(s, fin + 0x2c, 1); + put64(s, fin + 0x30, fragment_state); + put64(s, fin + 0x38, unk_pointee); + put64(s, fin + 0x40, flag); + put64(s, fin + 0x48, busy); + put64(s, fin + 0x50, q.queue); + put64(s, fin + 0x58, c.cmd_va); + put32(s, fin + 0x60, c.context); + put64(s, fin + 0x64, flag758); + put32(s, fin + 0x98, (-(fin as i32)) as u32); + s[fin + 0x9c] = 0; + put64(s, fin + 0xad, va(0x970)); + put32(s, fin + 0xb5, q.slot); + put32(s, fin + 0xbc, 0x4000_0002); + debug_assert!(fin + 0xc0 <= FRAG_STREAM as usize); + Ok(()) +} diff --git a/drivers/gpu/drm/asahi/g15/adopt.rs b/drivers/gpu/drm/asahi/g15/adopt.rs new file mode 100644 index 00000000000000..5dd54b04aaec6b --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/adopt.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Without the G15 backend (`CONFIG_DRM_ASAHI_G15=n`), the parts of it the T8122 runtime uses to +//! adopt the firmware's UAT: the handoff window ([`uat`]), its mappings ([`regs`]) and the +//! hardware constants they name ([`hw`]). Nothing here probes a device. + +// Only the adoption is used; the rest of these files serves the G15 backend. +#![allow(dead_code)] + +// hw.rs's `t6031` submodule is cfg-gated on G15; were it built here, a #[path]-loaded file +// would look for it at g15/t6031.rs, not g15/hw/t6031.rs. +#[path = "hw.rs"] +pub(crate) mod hw; +#[path = "regs.rs"] +pub(crate) mod regs; +#[path = "uat.rs"] +pub(crate) mod uat; + +use kernel::prelude::*; + +extern "C" { + fn asahi_g15_memory_mode(start: u64, size: u64) -> u32; +} + +/// WB for complete reserved RAM, WC for aligned non-RAM carveouts; reject everything else. +pub(crate) fn memory_mode(start: u64, size: u64) -> Result { + // SAFETY: Only queries resources and page metadata; it does not create a mapping. + match unsafe { asahi_g15_memory_mode(start, size) } { + 0 => Err(EINVAL), + mode => Ok(mode), + } +} diff --git a/drivers/gpu/drm/asahi/g15/command.rs b/drivers/gpu/drm/asahi/g15/command.rs index 66e52e69811977..edb076df3d493c 100644 --- a/drivers/gpu/drm/asahi/g15/command.rs +++ b/drivers/gpu/drm/asahi/g15/command.rs @@ -34,7 +34,7 @@ use kernel::{prelude::*, sync::Arc, xarray}; use super::wire as uapi; use super::{gate, hw}; -use crate::{file, mmu, util::AnyBitPattern, util::Reader}; +use crate::{file, mmu, timestamp, util::AnyBitPattern, util::Reader}; /// Largest command buffer. pub(crate) const MAX_CMDBUF: usize = 4 << 20; @@ -135,7 +135,7 @@ pub(crate) struct Submission { /// Render and compute commands, for the queue's EXACT_PRIOR ordinals. pub(crate) counts: [u64; 2], /// The timestamp buffers the commands name, retained with the job. - pub(crate) timestamps: KVec>, + pub(crate) timestamps: KVec>, } /// What the per-command checks need. @@ -146,8 +146,8 @@ pub(crate) struct Context<'a> { pub(crate) usc_base: u64, } -struct CheckedContext<'a> { - vm: &'a mut mmu::VmReadGuard, +struct CheckedContext<'a, 'b> { + vm: &'a mut mmu::VmReadGuard<'b>, usc_base: u64, } @@ -158,7 +158,7 @@ pub(crate) struct Prepared<'a> { /// Arena VAs of each command's timestamp slots. resolved: KVec<[u64; 4]>, counts: [u64; 2], - timestamps: KVec>, + timestamps: KVec>, } /// One command of the stream. @@ -349,7 +349,7 @@ pub(crate) fn check_stream(bytes: &[u8], early_tiling: bool) -> Result { /// The timestamp buffers named by a submission, resolved to firmware arena VAs. struct Timestamps<'a> { objects: Pin<&'a xarray::XArray>>, - held: KVec>, + held: KVec>, } impl Timestamps<'_> { @@ -365,15 +365,15 @@ impl Timestamps<'_> { .get(timestamp.handle.try_into()?) .ok_or(ENOENT)? .clone(); - let file::Object::TimestampBuffer(mapping) = object; - let mapping = mapping.firmware_mapping()?; + let file::Object::TimestampBuffer(buffer) = object; + let mapping = buffer.firmware_mapping()?; let offset = timestamp.offset as usize; if offset % 8 != 0 || offset >= mapping.size() || mapping.size() - offset < 8 { return Err(EINVAL); } let va = mapping.iova() + offset as u64; - if !self.held.iter().any(|held| Arc::ptr_eq(held, &mapping)) { - self.held.push(mapping, GFP_KERNEL)?; + if !self.held.iter().any(|held| Arc::ptr_eq(held, &buffer)) { + self.held.push(buffer, GFP_KERNEL)?; } Ok(va) } @@ -383,7 +383,7 @@ impl Timestamps<'_> { /// GPU access: a driver range ENOENT, outside the user range EINVAL, an unmapped page ENOENT, a /// page without the access EACCES. pub(crate) fn cover( - vm: &mut mmu::VmReadGuard, + vm: &mut mmu::VmReadGuard<'_>, start: u64, end: u64, read: bool, @@ -419,7 +419,7 @@ pub(crate) fn cover( /// Attachment spans, 128-byte granular, actually mapped with `write` or read access. fn check_attachments( - vm: &mut mmu::VmReadGuard, + vm: &mut mmu::VmReadGuard<'_>, list: &[uapi::drm_asahi_attachment], write: bool, ) -> Result { @@ -482,7 +482,7 @@ fn geometry_bytes(cmd: &uapi::drm_asahi_cmd_render) -> (u64, u64) { } /// Per-command render admission. -fn check_render(context: &mut CheckedContext<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Result { +fn check_render(context: &mut CheckedContext<'_, '_>, cmd: &uapi::drm_asahi_cmd_render) -> Result { let vm = &mut *context.vm; let allowed = PROCESS_EMPTY_TILES | NO_VERTEX_CLUSTERING @@ -567,7 +567,7 @@ fn check_render(context: &mut CheckedContext<'_>, cmd: &uapi::drm_asahi_cmd_rend /// Per-command compute admission. fn check_compute( - context: &mut CheckedContext<'_>, + context: &mut CheckedContext<'_, '_>, cmd: &uapi::drm_asahi_cmd_compute, attachments: &[uapi::drm_asahi_attachment], ) -> Result { diff --git a/drivers/gpu/drm/asahi/g15/fence.rs b/drivers/gpu/drm/asahi/g15/fence.rs index bb857642280702..55a85472a794de 100644 --- a/drivers/gpu/drm/asahi/g15/fence.rs +++ b/drivers/gpu/drm/asahi/g15/fence.rs @@ -179,12 +179,12 @@ fn install(outputs: impl Iterator, fence: &Fence) { /// accepted, a signalled error fence when the submission is refused (the shared `file.rs` /// contract of `tracked_submission`). pub(crate) struct Syncs { - syncs: KVec, + syncs: KVVec, input_count: usize, } impl Syncs { - pub(crate) fn new(syncs: KVec, input_count: usize) -> Self { + pub(crate) fn new(syncs: KVVec, input_count: usize) -> Self { Self { syncs, input_count } } diff --git a/drivers/gpu/drm/asahi/g15/gate.rs b/drivers/gpu/drm/asahi/g15/gate.rs index 590f5e6f0a5c11..c4a233e5917991 100644 --- a/drivers/gpu/drm/asahi/g15/gate.rs +++ b/drivers/gpu/drm/asahi/g15/gate.rs @@ -2,7 +2,9 @@ //! Stream admission gates (safety nets for userspace encoders). //! -//! VDM: the root stream's first word is 0x21000960. CDM walk from `cdm_ctrl_stream_base` through +//! VDM: the root stream's first word is 0x21000960, or 0x21000968 with the USC cache invalidate. +//! +//! CDM walk from `cdm_ctrl_stream_base` through //! links until TERMINATE (0x40000000), at most 64 links and [`CDM_MAX_BYTES`] of records (a //! longer or cyclic stream is rejected): barriers 0x60000160, 0x60001560, 0x600215fe, 0x600201fe; //! link 0x2000XXXX; direct launch (40 B, the G15 layout), indirect launches 36 B @@ -20,6 +22,8 @@ use super::{command::cover, command::USC_WINDOW, params}; use crate::mmu; const VDM_ROOT: u32 = 0x21000960; +/// USC cache invalidate bit of the VDM root barrier (DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE). +const VDM_ROOT_USC_INVAL: u32 = 0x8; const CDM_TERMINATE: u32 = 0x40000000; const CDM_BARRIERS: [u32; 4] = [0x60000160, 0x600215fe, 0x60001560, 0x600201fe]; const CDM_LINK: u32 = 0x20000000; @@ -71,7 +75,7 @@ struct Window { impl Window { /// The `count` words at `va`, reading whole spans of up to 256 bytes (not past the page /// unless the record crosses it). Unreadable memory: EFAULT. - fn words(&mut self, vm: &mut mmu::VmReadGuard, va: u64, count: usize) -> Result<[u32; 10]> { + fn words(&mut self, vm: &mut mmu::VmReadGuard<'_>, va: u64, count: usize) -> Result<[u32; 10]> { let n = count * 4; let cached = self.len != 0 && va >= self.va @@ -108,7 +112,7 @@ struct Checked { /// One page check of `[start, end)` under the walk's page budget: ENOSPC once the budget is /// spent. -fn check(vm: &mut mmu::VmReadGuard, start: u64, end: u64, count: &mut u32) -> Result { +fn check(vm: &mut mmu::VmReadGuard<'_>, start: u64, end: u64, count: &mut u32) -> Result { if *count >= CDM_MAX_PAGE_CHECKS { return Err(ENOSPC); } @@ -118,7 +122,7 @@ fn check(vm: &mut mmu::VmReadGuard, start: u64, end: u64, count: &mut u32) -> Re /// A launch's program: inside the queue's 4 GiB USC window, 64-aligned, first block readable. /// The last proven program page is not checked again. -fn program(vm: &mut mmu::VmReadGuard, usc: u64, address: u64, checked: &mut Checked) -> Result { +fn program(vm: &mut mmu::VmReadGuard<'_>, usc: u64, address: u64, checked: &mut Checked) -> Result { if address < usc || address - usc >= USC_WINDOW || address & 63 != 0 { return Err(EINVAL); } @@ -134,7 +138,7 @@ fn program(vm: &mut mmu::VmReadGuard, usc: u64, address: u64, checked: &mut Chec /// An indirect launch's 12 argument bytes: readable. The last proven argument page is not /// checked again; arguments that cross a page are checked each time. -fn arguments(vm: &mut mmu::VmReadGuard, address: u64, checked: &mut Checked) -> Result { +fn arguments(vm: &mut mmu::VmReadGuard<'_>, address: u64, checked: &mut Checked) -> Result { let end = address.checked_add(12).ok_or(EINVAL)?; let page = address & !(mmu::UAT_PGMSK as u64); let within = (end - 1) & !(mmu::UAT_PGMSK as u64) == page; @@ -148,15 +152,16 @@ fn arguments(vm: &mut mmu::VmReadGuard, address: u64, checked: &mut Checked) -> Ok(()) } -/// VDM admission: a normal root stream opens with exactly the G15 barrier. -pub(crate) fn vdm(vm: &mut mmu::VmReadGuard, va: u64) -> Result { +/// VDM admission: a normal root stream opens with the G15 barrier, with or +/// without the USC cache invalidate. +pub(crate) fn vdm(vm: &mut mmu::VmReadGuard<'_>, va: u64) -> Result { if !params::stream_gate() { return Ok(()); } let mut bytes = [0u8; 4]; vm.read_user(va, &mut bytes).map_err(|_| EFAULT)?; let word = u32::from_le_bytes(bytes); - if word != VDM_ROOT { + if word & !VDM_ROOT_USC_INVAL != VDM_ROOT { return Err(reject("VDM root", va, &[word])); } Ok(()) @@ -165,7 +170,7 @@ pub(crate) fn vdm(vm: &mut mmu::VmReadGuard, va: u64) -> Result { /// CDM admission: walks the stream from its base through no-return links until TERMINATE, /// admitting only the known G15S records: direct launch (40), indirect launch (36/24), barriers /// (4), link (8). -pub(crate) fn cdm(vm: &mut mmu::VmReadGuard, usc: u64, base: u64) -> Result { +pub(crate) fn cdm(vm: &mut mmu::VmReadGuard<'_>, usc: u64, base: u64) -> Result { if !params::stream_gate() { return Ok(()); } diff --git a/drivers/gpu/drm/asahi/g15/glue.c b/drivers/gpu/drm/asahi/g15/glue.c index 2a0346228c1e58..a12a5e6fa2fe78 100644 --- a/drivers/gpu/drm/asahi/g15/glue.c +++ b/drivers/gpu/drm/asahi/g15/glue.c @@ -29,9 +29,6 @@ void asahi_g15_release_power(struct device *dev); void asahi_g15_reprobe(void); void asahi_g15_report_loader_gpu(void); int asahi_g15_adt_phram(u64 *start, u64 *size); -bool asahi_g15_ram_disjoint(u64 start, u64 size); -bool asahi_g15_ram_within(u64 start, u64 size); -unsigned int asahi_g15_memory_mode(u64 start, u64 size); void __iomem *asahi_g15_ioremap_wc(u64 start, size_t size); bool asahi_g15_dma_coherent(struct device *dev); int asahi_g15_pmp_prepare(struct device *dev); @@ -275,13 +272,6 @@ int asahi_g15_adt_phram(u64 *start, u64 *size) return 0; } -/* The range is disjoint from System RAM (ADT region admission). */ -bool asahi_g15_ram_disjoint(u64 start, u64 size) -{ - return region_intersects(start, size, IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE) == - REGION_DISJOINT; -} - /* * Whether DMA mappings of the device skip cache maintenance. The G15 firmware * objects rely on the DMA mapping cleaning their pages to the point of @@ -292,42 +282,6 @@ bool asahi_g15_dma_coherent(struct device *dev) return dev_is_dma_coherent(dev); } -/* - * Every page must be valid, System RAM and still reserved from the allocator. - * REGION_INTERSECTS alone also accepts RAM mixed with undefined memory holes. - */ -bool asahi_g15_ram_within(u64 start, u64 size) -{ - u64 end, pa; - - if (!size || !IS_ALIGNED(start, PAGE_SIZE) || - !IS_ALIGNED(size, PAGE_SIZE) || check_add_overflow(start, size, &end)) - return false; - for (pa = start; pa < end; pa += PAGE_SIZE) { - unsigned long pfn = PHYS_PFN(pa); - - if (!pfn_valid(pfn) || !page_is_ram(pfn) || - !PageReserved(pfn_to_page(pfn))) - return false; - } - return true; -} - -/* One classification for every adopted-UAT and firmware-region CPU mapping. */ -unsigned int asahi_g15_memory_mode(u64 start, u64 size) -{ - u64 end; - - if (!size || !IS_ALIGNED(start, PAGE_SIZE) || - !IS_ALIGNED(size, PAGE_SIZE) || check_add_overflow(start, size, &end)) - return 0; - if (asahi_g15_ram_within(start, size)) - return MEMREMAP_WB; - if (asahi_g15_ram_disjoint(start, size)) - return MEMREMAP_WC; - return 0; -} - /* The inherited RTKit buffer inside firmware DATA. */ void __iomem *asahi_g15_ioremap_wc(u64 start, size_t size) { diff --git a/drivers/gpu/drm/asahi/g15/hw.rs b/drivers/gpu/drm/asahi/g15/hw.rs index b2110883102104..cac11c55d3ca00 100644 --- a/drivers/gpu/drm/asahi/g15/hw.rs +++ b/drivers/gpu/drm/asahi/g15/hw.rs @@ -7,6 +7,7 @@ use core::ops::Range; +#[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) mod t6031; /// Identification register values of a qualified G15S. @@ -91,6 +92,7 @@ pub(crate) struct ComputeRegs { } /// The T6030 configuration. +#[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) mod t6030 { use super::super::Config; use super::{ComputeRegs, FirmwareBuild, HwId, Layout}; @@ -175,6 +177,69 @@ pub(crate) mod t6030 { 0xe7, 0x9b, 0xb9, 0xb0, 0x22, 0x09, 0xdb, 0x53, ], }, + // J514S firmware measured on the 14.7 boot chain; desktop rendering + // was verified with the bring-up prefix override (issue #247). + FirmwareBuild { + name: "J514S cd05 firmware (14.7 boot chain)", + machine: Some(kernel::c_str!("apple,j514s")), + text_size: 0x5c000, + data_size: 0x114000, + marker: 0x58e88, + text_sha256: [ + 0xcd, 0x05, 0xaf, 0x6a, 0x82, 0x8b, 0x52, 0xe4, + 0xc2, 0xfe, 0xd2, 0x00, 0x86, 0xd3, 0xd1, 0x8a, + 0x7d, 0xb4, 0x2e, 0x03, 0xa8, 0xfd, 0x6f, 0x83, + 0x54, 0xf9, 0xf0, 0x6e, 0x0a, 0x61, 0x36, 0x3e, + ], + }, + // Some J516S units on the same 14.7 boot chain load a different B0 + // TEXT image with identical sizes and marker. Pin its complete + // measured digest for the J516S only. + FirmwareBuild { + name: "J516S cd05 firmware (14.7 boot chain)", + machine: Some(kernel::c_str!("apple,j516s")), + text_size: 0x5c000, + data_size: 0x114000, + marker: 0x58e88, + text_sha256: [ + 0xcd, 0x05, 0xaf, 0x6a, 0x82, 0x8b, 0x52, 0xe4, + 0xc2, 0xfe, 0xd2, 0x00, 0x86, 0xd3, 0xd1, 0x8a, + 0x7d, 0xb4, 0x2e, 0x03, 0xa8, 0xfd, 0x6f, 0x83, + 0x54, 0xf9, 0xf0, 0x6e, 0x0a, 0x61, 0x36, 0x3e, + ], + }, + // J514S (14-inch) firmware measured on the 14.7 boot chain with + // system firmware 26.6.2; the GPU reached READY with the bring-up + // prefix override (issue #247). + FirmwareBuild { + name: "J514S 4118 firmware (14.7 boot chain)", + machine: Some(kernel::c_str!("apple,j514s")), + text_size: 0x5c000, + data_size: 0x114000, + marker: 0x58e88, + text_sha256: [ + 0x41, 0x18, 0x33, 0xa7, 0xde, 0xd7, 0x73, 0xfe, + 0xea, 0xc4, 0xa1, 0x81, 0x55, 0x2e, 0x3f, 0xf5, + 0x58, 0x2e, 0xaf, 0x44, 0x35, 0xf2, 0xdd, 0x8f, + 0x62, 0x0c, 0x1e, 0xd0, 0xb3, 0x1d, 0xf1, 0xb0, + ], + }, + // J516S (16-inch) firmware measured on the 14.7 boot chain with + // system firmware 26.6.2; the GPU reached READY with the bring-up + // prefix override (issue #247). + FirmwareBuild { + name: "J516S 4118 firmware (14.7 boot chain)", + machine: Some(kernel::c_str!("apple,j516s")), + text_size: 0x5c000, + data_size: 0x114000, + marker: 0x58e88, + text_sha256: [ + 0x41, 0x18, 0x33, 0xa7, 0xde, 0xd7, 0x73, 0xfe, + 0xea, 0xc4, 0xa1, 0x81, 0x55, 0x2e, 0x3f, 0xf5, + 0x58, 0x2e, 0xaf, 0x44, 0x35, 0xf2, 0xdd, 0x8f, + 0x62, 0x0c, 0x1e, 0xd0, 0xb3, 0x1d, 0xf1, 0xb0, + ], + }, ], machine: kernel::c_str!("apple,t6030"), platform: super::Platform::AdtWithPmp, diff --git a/drivers/gpu/drm/asahi/g15/job.rs b/drivers/gpu/drm/asahi/g15/job.rs index a93b6039cc4665..0022b8d1cb764e 100644 --- a/drivers/gpu/drm/asahi/g15/job.rs +++ b/drivers/gpu/drm/asahi/g15/job.rs @@ -36,7 +36,7 @@ use kernel::{ }; use super::{command::Command, fence::JobFence, hw, queue::QueueState, vm::VmState, Shared}; -use crate::mmu; +use crate::{mmu, timestamp}; /// A job as the engine sees it. #[pin_data] @@ -58,7 +58,7 @@ pub(crate) struct Job { /// The engine's bookkeeping; `progress.signaled` makes [`Job::complete`] act once. pub(crate) progress: super::engine::Progress, /// The timestamp buffers the commands name (their arena VAs stay mapped while the job lives). - _timestamps: KVec>, + _timestamps: KVec>, /// Retains the VM's mappings (deferred unmaps, deferred VM close) while the firmware may /// access them. _guard: mmu::VmJobGuard, @@ -75,7 +75,7 @@ impl Job { vm: Arc, commands: KVec, fence: JobFence, - timestamps: KVec>, + timestamps: KVec>, guard: mmu::VmJobGuard, ) -> Result> { let progress = super::engine::Progress::new(commands.len()); diff --git a/drivers/gpu/drm/asahi/g15/mod.rs b/drivers/gpu/drm/asahi/g15/mod.rs index 4cb221fb0a5df6..f59cd893bf9e58 100644 --- a/drivers/gpu/drm/asahi/g15/mod.rs +++ b/drivers/gpu/drm/asahi/g15/mod.rs @@ -202,10 +202,21 @@ impl platform::Driver for Driver<'_> { // after probe_g15 started firmware would return an unbound device. try_pin_init!(Driver { _driver: { + // Not EPROBE_DEFER: a deferred device stays listed in devices_deferred until the + // deferred-probe work runs, even after activate()'s probe fails for good. Activation + // reprobes every unbound device; a device added later sees MODULE_READY set. if !MODULE_READY.load(Ordering::Acquire) { - return Err(EPROBE_DEFER); + return Err(ENODEV); } let cfg = *info.ok_or(ENODEV)?; + if pdev.as_ref().of_node().is_some_and(|node| { + !matches!( + node.get_opt_property::(c_str!("apple,g16-handoff-version")), + Ok(None) + ) + }) { + return Err(ENODEV); + } dev_info!(pdev.as_ref(), "G15: probing ({})\n", cfg.name); match crate::driver::AsahiPlatformDriver::probe_g15(pdev, cfg) { Ok(driver) => Some(driver), @@ -578,6 +589,10 @@ impl Firmware { } impl gpu::Gpu for Gpu { + fn max_cmdbuf_size(&self) -> usize { + command::MAX_CMDBUF + } + fn stats_snapshot(&self) -> Option> { None } @@ -680,11 +695,19 @@ impl gpu::Gpu for Gpu { )?) } + fn timestamp_window_size(&self) -> u64 { + hw::va::TIMESTAMPS_SIZE + } + fn map_timestamp_buffer( &self, bo: gem::ObjectRef, range: Range, + window: crate::timestamp::WindowPermit, ) -> Result { - crate::timestamp::Buffer::firmware(timestamp::map(self, bo, range)?) + if !window.is_allowed() { + return Err(ENOSPC); + } + crate::timestamp::Buffer::firmware(timestamp::map(self, bo, range)?, window.into_share()) } } diff --git a/drivers/gpu/drm/asahi/g15/params.rs b/drivers/gpu/drm/asahi/g15/params.rs index c2c34864750611..17ac71c28aa225 100644 --- a/drivers/gpu/drm/asahi/g15/params.rs +++ b/drivers/gpu/drm/asahi/g15/params.rs @@ -3,9 +3,10 @@ //! Module parameters and the GET_PARAMS identity. //! //! With the shared `file.rs` additions (VM_STATUS and VM_STATUS_MIRROR from `supports_vm_status`, -//! INDEPENDENT_QUEUES from `queue_limits`, SOFT_FAULTS suppressed by `soft_faults`), the feature -//! word is exactly 0x3e (0xbe with `g15_early_tiling`). Never advertise SOFT_FAULTS, -//! FEW_PRIMITIVES or RENDER_RAY_QUERY on G15S. +//! INDEPENDENT_QUEUES from `queue_limits`, SOFT_FAULTS suppressed by `soft_faults`, and +//! VDM_USC_INVALIDATE, bit 40 in both numberings), the feature word is exactly 0x3e (0xbe with +//! `g15_early_tiling`) plus bit 40. Never advertise SOFT_FAULTS, FEW_PRIMITIVES or +//! RENDER_RAY_QUERY on G15S. use kernel::prelude::*; diff --git a/drivers/gpu/drm/asahi/g15/queue.rs b/drivers/gpu/drm/asahi/g15/queue.rs index 03a8f46c8a0fce..3bdebb7995e44f 100644 --- a/drivers/gpu/drm/asahi/g15/queue.rs +++ b/drivers/gpu/drm/asahi/g15/queue.rs @@ -212,7 +212,7 @@ impl crate::queue::Queue for Queue { &mut self, _reg_data: &crate::driver::AsahiRegData<'_>, id: u64, - syncs: KVec, + syncs: KVVec, in_sync_count: usize, cmdbuf_raw: &[u8], objects: Pin<&xarray::XArray>>, diff --git a/drivers/gpu/drm/asahi/g15/regs.rs b/drivers/gpu/drm/asahi/g15/regs.rs index 05a1b390b3dffc..98e7d4c8cf78a4 100644 --- a/drivers/gpu/drm/asahi/g15/regs.rs +++ b/drivers/gpu/drm/asahi/g15/regs.rs @@ -125,7 +125,7 @@ impl Mapping { if size == 0 { return Err(EINVAL); } - let mode = super::boot::glue::memory_mode(phys, size as u64)?; + let mode = super::memory_mode(phys, size as u64)?; if mode == bindings::MEMREMAP_WC as u32 { return Self::write_combined(phys, size); } @@ -252,6 +252,7 @@ impl Regs { /// Reads the identification words and the enabled-core mask (once the GPU is powered). A /// SoC with more than 32 core slots carries the mask in two words. + #[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) fn identity(&self, cfg: &super::Config) -> Result { let version = self.sgx.io().try_read32(SGX_ID)?; let counts = self.sgx.io().try_read32(SGX_ID + 0x10)?; diff --git a/drivers/gpu/drm/asahi/g15/uat.rs b/drivers/gpu/drm/asahi/g15/uat.rs index 0f91f7c9f06100..9a93e6d17a59f0 100644 --- a/drivers/gpu/drm/asahi/g15/uat.rs +++ b/drivers/gpu/drm/asahi/g15/uat.rs @@ -38,12 +38,14 @@ use kernel::{ bindings, device, io::Io, prelude::*, - sync::Arc, time::{delay::fsleep, Delta, Instant, Monotonic}, }; +#[cfg(CONFIG_DRM_ASAHI_G15)] +use kernel::sync::Arc; use super::hw; use super::regs::{mb, rmb, wmb, Mapping}; +#[cfg(CONFIG_DRM_ASAHI_G15)] use crate::driver::AsahiDrmDevice as AsahiDevice; use crate::{mmu, pgtable}; @@ -69,6 +71,7 @@ const fn indices(va: u64) -> [usize; 3] { } /// Creates the adopted UAT over the ADT regions (step 2 above). +#[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) fn adopt( dev: &AsahiDevice, cfg: &'static super::Config, @@ -118,7 +121,7 @@ fn clean_entries(pa: u64, first: usize, count: usize) -> Result { } /// Cleans a whole RAM table page to the point of coherency. -fn clean_page(pa: u64) -> Result { +pub(crate) fn clean_page(pa: u64) -> Result { clean_entries(pa, 0, ENTRIES) } @@ -201,6 +204,7 @@ pub(crate) struct Window { impl Window { /// Maps the UAT handoff regions ([`Mapping::region`]). + #[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) fn new(adt: &super::adt::GpuAdt) -> Result { Self::from_regions(adt.handoff.start, adt.ttbs.start, adt.tables.start, adt.shared_l2.start) } diff --git a/drivers/gpu/drm/asahi/g15/uat_glue.c b/drivers/gpu/drm/asahi/g15/uat_glue.c new file mode 100644 index 00000000000000..134ff4bb28ab6b --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/uat_glue.c @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * C helpers of the UAT adoption (g15/uat.rs, g15/regs.rs), built for the G15 + * backend and for the T8122 runtime, which adopts the firmware's UAT the same + * way (CONFIG_DRM_ASAHI_UAT_ADOPTION). + */ +#include +#include +#include +#include +#include +#include + +bool asahi_g15_ram_disjoint(u64 start, u64 size); +bool asahi_g15_ram_within(u64 start, u64 size); +unsigned int asahi_g15_memory_mode(u64 start, u64 size); + +/* The range is disjoint from System RAM (ADT region admission). */ +bool asahi_g15_ram_disjoint(u64 start, u64 size) +{ + return region_intersects(start, size, IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE) == + REGION_DISJOINT; +} + +/* + * Every page must be valid, System RAM and still reserved from the allocator. + * REGION_INTERSECTS alone also accepts RAM mixed with undefined memory holes. + */ +bool asahi_g15_ram_within(u64 start, u64 size) +{ + u64 end, pa; + + if (!size || !IS_ALIGNED(start, PAGE_SIZE) || + !IS_ALIGNED(size, PAGE_SIZE) || check_add_overflow(start, size, &end)) + return false; + for (pa = start; pa < end; pa += PAGE_SIZE) { + unsigned long pfn = PHYS_PFN(pa); + + if (!pfn_valid(pfn) || !page_is_ram(pfn) || + !PageReserved(pfn_to_page(pfn))) + return false; + } + return true; +} + +/* One classification for every adopted-UAT and firmware-region CPU mapping. */ +unsigned int asahi_g15_memory_mode(u64 start, u64 size) +{ + u64 end; + + if (!size || !IS_ALIGNED(start, PAGE_SIZE) || + !IS_ALIGNED(size, PAGE_SIZE) || check_add_overflow(start, size, &end)) + return 0; + if (asahi_g15_ram_within(start, size)) + return MEMREMAP_WB; + if (asahi_g15_ram_disjoint(start, size)) + return MEMREMAP_WC; + return 0; +} diff --git a/drivers/gpu/drm/asahi/g16/adt.rs b/drivers/gpu/drm/asahi/g16/adt.rs index 804703b19cecc7..b33a037f2e969b 100644 --- a/drivers/gpu/drm/asahi/g16/adt.rs +++ b/drivers/gpu/drm/asahi/g16/adt.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! J713's explicit boot-loader GPU handoff. +//! Explicit boot-loader GPU handoff. //! -//! Unlike the synthesized T6030 node, J713 supplies six named no-map reservations and an -//! explicit segment/handoff ABI. Admit those reservations before mapping anything. The -//! performance-state source is the machine's original ADT, preserved by m1n1 in the named -//! phram reservation. It is copied and parsed before any firmware-visible write. +//! The boot loader supplies six named no-map reservations and an explicit +//! segment/handoff ABI. Admission checks the reservations before mapping. +//! The boot loader preserves the original ADT in the named phram reservation. +//! The driver copies and parses it before any firmware-visible write. #[path = "adt/perf.rs"] pub(crate) mod perf; @@ -13,7 +13,7 @@ pub(crate) mod perf; use core::ops::Range; use kernel::{bindings, c_str, device, of, prelude::*}; -use super::{boot::glue, hw}; +use super::{boot::glue, hw, Config}; /// Independently owned reservations; none may intersect System RAM or another reservation. pub(crate) struct GpuAdt { @@ -24,6 +24,8 @@ pub(crate) struct GpuAdt { pub(crate) text: Range, pub(crate) data: Range, pub(crate) performance: perf::Source, + /// The firmware layout the boot loader's handoff describes. + pub(crate) layout: &'static hw::FwLayout, } /// Find the one original-ADT phram export, with explicit 64-bit reservation cells. @@ -118,23 +120,93 @@ fn performance_source(regions: &[Range]) -> Result<(KVVec, u64)> { Ok((copy?, start)) } -/// Validates the FDT contract and returns the reserved physical regions, read-only. -pub(crate) fn read(dev: &device::Device) -> Result { +/// Whether the boot loader selected this backend. Presence is enough to route probe; +/// admission independently validates the property and the complete handoff. +pub(super) fn has_handoff(dev: &device::Device, cfg: &Config) -> bool { + dev.of_node() + .is_some_and(|node| !matches!(node.get_opt_property::(cfg.handoff_property), Ok(None))) +} + +/// Whether this backend owns `dev` under `cfg`: the handoff marker is present and, where `cfg` +/// names `firmware_compat` values, the handoff also describes one of its layouts and +/// `apple,firmware-compat` is one of those values. A compatible that another backend also +/// serves (`needs_handoff_marker`) is probed only then. +pub(crate) fn claims(dev: &device::Device, cfg: &Config) -> bool { + if !has_handoff(dev, cfg) { + return false; + } + if cfg.firmware_compat.is_empty() { + return true; + } + if layout(dev, cfg).is_none() { + return false; + } + let Some(node) = dev.of_node() else { + return false; + }; + let compat: Result> = node.get_property(c_str!("apple,firmware-compat")); + compat.is_ok_and(|compat| cfg.firmware_compat.iter().any(|c| compat.as_slice() == c)) +} + +/// The boot loader's handoff for the loaded firmware: its version, segment VAs and flags. +fn handoff(dev: &device::Device, cfg: &Config) -> Result<(u32, KVec, KVec)> { let node = dev.of_node().ok_or(EINVAL)?; - let version: u32 = node.get_property(c_str!("apple,g16-handoff-version"))?; + let version: u32 = node.get_property(cfg.handoff_property)?; let vas: KVec = node.get_property(c_str!("apple,firmware-segment-vas"))?; let flags: KVec = node.get_property(c_str!("apple,firmware-segment-flags"))?; + Ok((version, vas, flags)) +} + +/// The firmware layout the boot loader's handoff describes, if it describes a known one. +pub(crate) fn layout(dev: &device::Device, cfg: &Config) -> Option<&'static hw::FwLayout> { + let (version, vas, flags) = handoff(dev, cfg).ok()?; + cfg.layouts + .iter() + .copied() + .find(|layout| layout.matches(version, &vas, &flags)) +} + +/// Validates the FDT contract and returns the reserved physical regions, read-only. +#[inline(never)] +pub(crate) fn read(dev: &device::Device, cfg: &Config) -> Result> { + let node = dev.of_node().ok_or(EINVAL)?; + let (version, vas, flags) = handoff(dev, cfg)?; let names: KVec = node.get_property(c_str!("memory-region-names"))?; let phandles: KVec = node.get_property(c_str!("memory-region"))?; - if version != 1 - || vas.as_slice() != [hw::UPPER, hw::UPPER + 0x60000] - || flags.as_slice() != [1, 0] - || phandles.len() != 6 - || names.as_slice() != b"ttbs\0pagetables\0handoff\0shared-l2\0fw-text\0fw-data\0" - { + let layout = cfg + .layouts + .iter() + .copied() + .find(|layout| layout.matches(version, &vas, &flags)); + let Some(layout) = layout else { + dev_err!( + dev, + "G16: unsupported boot-loader handoff (version {}, {} segments)\n", + version, + vas.len() + ); + return Err(EINVAL); + }; + const CANONICAL: &[u8] = b"ttbs\0pagetables\0handoff\0shared-l2\0fw-text\0fw-data\0"; + // A boot loader that also serves the older M3 runtime names the shared L2 table a second + // time, first, as "pagetables-l2". Accept that entry only as an alias: it must reference + // the very reservation "shared-l2" references. Anything else (a second or unknown + // reservation) keeps the contract refused. The six canonical regions are then looked up + // and validated by name below, exactly as without the alias. + const L2_ALIAS: &[u8] = b"pagetables-l2\0"; + let canonical = phandles.len() == 6 && names.as_slice() == CANONICAL; + let aliased = phandles.len() == 7 + && names.as_slice().len() == L2_ALIAS.len() + CANONICAL.len() + && names.as_slice().starts_with(L2_ALIAS) + && &names.as_slice()[L2_ALIAS.len()..] == CANONICAL + && phandles[0] == phandles[4]; + if !canonical && !aliased { dev_err!(dev, "G16: unsupported boot-loader handoff contract\n"); return Err(EINVAL); } + if aliased { + dev_info!(dev, "G16: pagetables-l2 is an alias of shared-l2 (same reservation)\n"); + } let names = [ c_str!("ttbs"), c_str!("pagetables"), @@ -148,8 +220,8 @@ pub(crate) fn read(dev: &device::Device) -> Result { hw::TABLES_SIZE, hw::HANDOFF_SIZE, hw::SHARED_L2_SIZE, - 0x60000, - 0x13c000, + layout.text_size, + layout.data_size, ]; let mut regions: [Range; 6] = Default::default(); for (index, (name, expected)) in names.iter().zip(sizes).enumerate() { @@ -178,7 +250,7 @@ pub(crate) fn read(dev: &device::Device) -> Result { regions[index] = start..end; } let (copy, source_pa) = performance_source(®ions)?; - let performance = perf::parse(©).map_err(|error| { + let performance = perf::parse(©, cfg.adt_compatible).map_err(|error| { dev_err!( dev, "M4 original ADT performance data rejected: {:?}\n", @@ -195,13 +267,17 @@ pub(crate) fn read(dev: &device::Device) -> Result { performance.count ); let [ttbs, tables, handoff, shared_l2, text, data] = regions; - Ok(GpuAdt { - ttbs, - tables, - handoff, - shared_l2, - text, - data, - performance, - }) + Ok(KBox::init( + init!(GpuAdt { + ttbs, + tables, + handoff, + shared_l2, + text, + data, + performance, + layout, + }), + GFP_KERNEL, + )?) } diff --git a/drivers/gpu/drm/asahi/g16/adt/perf.rs b/drivers/gpu/drm/asahi/g16/adt/perf.rs index 1824cd255358ab..e2ebedb8862e30 100644 --- a/drivers/gpu/drm/asahi/g16/adt/perf.rs +++ b/drivers/gpu/drm/asahi/g16/adt/perf.rs @@ -24,6 +24,27 @@ pub(crate) struct Source { pub(crate) core_mv: [u32; MAX_STATES], pub(crate) sram_frequency_mhz: [u32; MAX_STATES], pub(crate) sram_mv: [u32; MAX_STATES], + /// The sgx node's `gpu-pwr-sample-period-aic-clks`: exact GPU power sample period in ticks + /// of the system counter, where the tree has it. + pub(crate) power_sample_clks: Option, + /// The sgx node's `gpu-power-sample-period`: coarse integer millisecond GPU power sample + /// period, where the tree has it. + pub(crate) power_sample_period_ms: Option, + /// `/arm-io/pmgr/clpc` `cpu-avg-limiter-input-tc`: average-power filter time constant in + /// milliseconds, where the tree has it. + pub(crate) avg_power_filter_tc_ms: Option, + /// `/arm-io/pmgr/clpc` `cpu-lowpeak-limiter-input-tc`: low-peak power limiter filter time + /// constant in milliseconds, where the tree has it. + pub(crate) lowpeak_limiter_tc_ms: Option, + /// `/arm-io/pmgr/clpc` `cpu-lowpeak-limiter-ki`: low-peak power limiter integral gain in + /// Q16.16 fixed point, where the tree has it. + pub(crate) lowpeak_limiter_ki_q16: Option, + /// `/arm-io/pmgr/clpc` `cpu-lowpeak-limiter-kp`: low-peak power limiter proportional gain + /// in Q16.16 fixed point, where the tree has it. + pub(crate) lowpeak_limiter_kp_q16: Option, + /// `/arm-io/gfx-asc/iop-gfx-nub` `coredump-copy-buffer`: size in bytes of the host crash + /// copy buffer, where the tree has it. + pub(crate) coredump_copy_size: Option, } fn u32_at(data: &[u8], at: usize) -> Result { @@ -129,6 +150,15 @@ impl<'a> Tree<'a> { } u32_at(data, 0) } + + fn opt_nonzero_cell(&self, node: usize, name: &[u8]) -> Result, Error> { + match self.cell(node, name) { + Ok(0) => Err(Error::Range), + Ok(value) => Ok(Some(value)), + Err(Error::Missing) => Ok(None), + Err(error) => Err(error), + } + } } fn decode_record(data: &[u8], state: usize) -> Result<(u32, u32), Error> { @@ -146,7 +176,7 @@ fn decode_record(data: &[u8], state: usize) -> Result<(u32, u32), Error> { /// Copying and physical reservation admission are the caller's responsibility. No reference to /// `data` escapes. Padding after the root is permitted because phram exports whole pages. -pub(crate) fn parse(data: &[u8]) -> Result { +pub(crate) fn parse(data: &[u8], sgx_compatible: &[u8]) -> Result { if data.is_empty() || data.len() > 0x20_0000 { return Err(Error::Malformed); } @@ -158,7 +188,7 @@ pub(crate) fn parse(data: &[u8]) -> Result { if compatible.last() != Some(&0) || !compatible .split(|&c| c == 0) - .any(|value| value == b"gpu,t8132") + .any(|value| value == sgx_compatible) { return Err(Error::Identity); } @@ -174,12 +204,59 @@ pub(crate) fn parse(data: &[u8]) -> Result { if core.len() != count * 8 || sram.len() != count * 8 { return Err(Error::Shape); } + let power_sample_clks = tree.opt_nonzero_cell(sgx, b"gpu-pwr-sample-period-aic-clks")?; + let power_sample_period_ms = tree.opt_nonzero_cell(sgx, b"gpu-power-sample-period")?; + let clpc = match tree.child(armio, b"pmgr") { + Ok(pmgr) => match tree.child(pmgr, b"clpc") { + Ok(clpc) => Some(clpc), + Err(Error::Missing) => None, + Err(error) => return Err(error), + }, + Err(Error::Missing) => None, + Err(error) => return Err(error), + }; + let ( + avg_power_filter_tc_ms, + lowpeak_limiter_tc_ms, + lowpeak_limiter_ki_q16, + lowpeak_limiter_kp_q16, + ) = if let Some(clpc) = clpc { + ( + tree.opt_nonzero_cell(clpc, b"cpu-avg-limiter-input-tc")?, + tree.opt_nonzero_cell(clpc, b"cpu-lowpeak-limiter-input-tc")?, + tree.opt_nonzero_cell(clpc, b"cpu-lowpeak-limiter-ki")?, + tree.opt_nonzero_cell(clpc, b"cpu-lowpeak-limiter-kp")?, + ) + } else { + (None, None, None, None) + }; + let coredump_copy_size = match tree.child(armio, b"gfx-asc") { + Ok(asc) => match tree.child(asc, b"iop-gfx-nub") { + Ok(nub) => match tree.opt_nonzero_cell(nub, b"coredump-copy-buffer")? { + Some(bytes) if bytes & 0xfff != 0 || bytes > 0x10_0000 => { + return Err(Error::Range); + } + other => other, + }, + Err(Error::Missing) => None, + Err(error) => return Err(error), + }, + Err(Error::Missing) => None, + Err(error) => return Err(error), + }; let mut source = Source { count, frequency_mhz: [0; MAX_STATES], core_mv: [0; MAX_STATES], sram_frequency_mhz: [0; MAX_STATES], sram_mv: [0; MAX_STATES], + power_sample_clks, + power_sample_period_ms, + avg_power_filter_tc_ms, + lowpeak_limiter_tc_ms, + lowpeak_limiter_ki_q16, + lowpeak_limiter_kp_q16, + coredump_copy_size, }; for i in 0..count { (source.frequency_mhz[i], source.core_mv[i]) = decode_record(core, i)?; diff --git a/drivers/gpu/drm/asahi/g16/board.rs b/drivers/gpu/drm/asahi/g16/board.rs index 9d005164e6de82..56798b017f5a9a 100644 --- a/drivers/gpu/drm/asahi/g16/board.rs +++ b/drivers/gpu/drm/asahi/g16/board.rs @@ -1,37 +1,34 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! M4 board admission for the qualified firmware graph. -//! -//! M4 uses ten firmware rows selected from sixteen source states, including off, and sixteen -//! voltage lanes. The source values belong to this machine's preserved original ADT. +//! Qualify firmware DVFS rows using this machine's preserved original ADT. pub(crate) mod data; use super::adt::GpuAdt; -use super::fw::initdata::{Performance, PERF_STATES}; +use super::fw::initdata::Performance; use kernel::{device, prelude::*}; /// Admit the qualified table layout while preserving every machine-specific source value. -/// Differently shaped tables and inconsistent voltage pairs fail before publication. +/// The firmware DVFS row count is derived directly from the preserved ADT table shape rather +/// than from a board compatible check; differently shaped tables or inconsistent voltage pairs +/// fail before publication. pub(crate) fn qualify(dev: &device::Device, adt: &GpuAdt) -> Result { let (performance, layout) = data::select_named(&adt.performance).map_err(|error| { - dev_err!( - dev, - "M4 original ADT performance layout rejected: {:?}\n", - error - ); + dev_err!(dev, "GPU original ADT performance layout rejected: {:?}\n", error); EINVAL })?; dev_info!( dev, - "M4 ADT DVFS: 16 source states -> 10 firmware rows ({} layout), top {} MHz\n", + "GPU ADT DVFS: {} source states -> {} firmware rows ({} layout), top {} MHz\n", + adt.performance.count, + performance.count, layout, - performance.frequency[PERF_STATES - 1] + performance.frequency[performance.count - 1] ); - for i in 0..PERF_STATES { + for i in 0..performance.count { dev_info!( dev, - "M4 ADT DVFS S{}: main={} MHz auxiliary={} MHz core={} mV SRAM={} mV\n", + "GPU ADT DVFS S{}: main={} MHz auxiliary={} MHz core={} mV SRAM={} mV\n", i, performance.frequency[i], performance.auxiliary[i], diff --git a/drivers/gpu/drm/asahi/g16/board/data.rs b/drivers/gpu/drm/asahi/g16/board/data.rs index 6d18386727a7f3..12dc2884263fc2 100644 --- a/drivers/gpu/drm/asahi/g16/board/data.rs +++ b/drivers/gpu/drm/asahi/g16/board/data.rs @@ -1,40 +1,49 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! Qualified selections of the original ADT's sixteen performance states for 25G83. +//! Select firmware DVFS rows from this machine's ADT performance states. //! -//! The firmware takes ten rows, each a main and an auxiliary frequency at one voltage. Every -//! qualified layout maps the sixteen ADT states onto those rows by index; the values are always -//! this machine's own, never frequencies or voltages copied from a reference machine. +//! Each row pairs a main and an auxiliary frequency at a shared voltage. -pub(crate) const SOURCE_STATES: usize = 16; - -/// One qualified mapping of the ADT states onto the firmware rows. +/// One qualified mapping of the ADT states onto the first `rows` firmware rows. pub(crate) struct Layout { pub(crate) name: &'static str, + pub(crate) rows: usize, pub(crate) main: [usize; PERF_STATES], pub(crate) auxiliary: [usize; PERF_STATES], } /// Tried in order; a layout matches only when each row's two states share frequency, SRAM -/// frequency and both voltages, so the shapes below cannot be mistaken for each other. +/// frequency and both voltages. The 10-row (6 equal-voltage pairs) and 11-row (5 equal-voltage +/// pairs plus a single top state) ADT shapes are mutually exclusive, so the row count is +/// derived directly from the ADT table without any board check. pub(crate) const LAYOUTS: [Layout; 2] = [ - // J713: four common low states followed by six equal-voltage pairs. + // 10-row ADT shape (e.g. J713/J715): four common low states followed by six equal-voltage + // pairs (4/5 through 14/15). Layout { - name: "J713", - main: [0, 1, 2, 3, 5, 7, 9, 11, 13, 15], - auxiliary: [0, 1, 2, 3, 4, 6, 8, 10, 12, 14], + name: "10-row", + rows: 10, + main: [0, 1, 2, 3, 5, 7, 9, 11, 13, 15, 0], + auxiliary: [0, 1, 2, 3, 4, 6, 8, 10, 12, 14, 0], }, - // J604 (MacBook Pro 14-inch, M4): five low states, five equal-voltage pairs (5/6 to - // 13/14) and a single top state 15. Eleven distinct rows do not fit in ten, so the fifth - // low state (4) is left out; the four lowest states, every pair and the top state keep - // their own ADT values. + // 11-row ADT shape (e.g. J604/J773g): five low states, five equal-voltage pairs (5/6 + // through 13/14) and a single top state 15, with every distinct state kept. Layout { - name: "J604", - main: [0, 1, 2, 3, 6, 8, 10, 12, 14, 15], - auxiliary: [0, 1, 2, 3, 5, 7, 9, 11, 13, 15], + name: "11-row", + rows: 11, + main: [0, 1, 2, 3, 4, 6, 8, 10, 12, 14, 15], + auxiliary: [0, 1, 2, 3, 4, 5, 7, 9, 11, 13, 15], }, ]; +// Four low states, then five equal-voltage pairs. The equal frequency at source +// states 9 and 10 belongs to two voltage bins and is kept in both rows. +const NINE_ROW_LAYOUT: Layout = Layout { + name: "9-row", + rows: 9, + main: [0, 1, 2, 3, 5, 7, 9, 11, 13, 0, 0], + auxiliary: [0, 1, 2, 3, 4, 6, 8, 10, 12, 0, 0], +}; + use super::super::fw::initdata::{Performance, PERF_STATES}; /// Allocation-free selection, also exercised directly by the host-side source-data tests. @@ -44,15 +53,18 @@ pub(crate) fn select( select_named(source).map(|(performance, _)| performance) } -/// As [`select`], with the name of the layout that matched. +/// As [`select`], with the name of the ADT shape that matched. pub(crate) fn select_named( source: &super::super::adt::perf::Source, ) -> core::result::Result<(Performance, &'static str), super::super::adt::perf::Error> { use super::super::adt::perf::Error; - if source.count != SOURCE_STATES { - return Err(Error::Shape); - } - for layout in LAYOUTS.iter() { + + let layouts = match source.count { + 14 => core::slice::from_ref(&NINE_ROW_LAYOUT), + 16 => LAYOUTS.as_slice(), + _ => return Err(Error::Shape), + }; + for layout in layouts { match select_layout(source, layout) { Err(Error::Shape) => continue, Err(error) => return Err(error), @@ -68,12 +80,13 @@ fn select_layout( ) -> core::result::Result { use super::super::adt::perf::Error; let mut performance = Performance { + count: layout.rows, frequency: [0; PERF_STATES], auxiliary: [0; PERF_STATES], voltage: [0; PERF_STATES], sram: [0; PERF_STATES], }; - for i in 0..PERF_STATES { + for i in 0..layout.rows { let (main, aux) = (layout.main[i], layout.auxiliary[i]); if source.frequency_mhz[main] != source.sram_frequency_mhz[main] || source.frequency_mhz[aux] != source.sram_frequency_mhz[aux] diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index f7f2cb25c56eab..5864452f42fa33 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -1,12 +1,15 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! M4/J713 cold admission and the qualified 25G83 firmware start sequence. +//! M4/J713 cold admission and the firmware start sequence (25G83; 26B123 once its unknowns are +//! known). //! //! The Rust owner validates firmware identity and all inherited regions before publication, -//! holds the PMP AGX vote, prepares owned objects and publishes context0 while ASC RUN is clear. +//! holds the PMP AGX vote (25G83; 26B123 sends none), prepares owned objects and publishes +//! context0 while ASC RUN is clear. //! It negotiates RTKit protocol12, accepts only the inherited EP1 crash buffer, then submits -//! initdata plus NOP0x1a and policy0x34/0x0a. Control+0x14 and exact retired indices qualify -//! READY; no M3 firmware constants or device-control sequence are reused. +//! initdata plus the consume-only NOP and policy (re-import Globals, start; 0x1a, 0x34 and +//! 0x0a on 25G83, 0x19, 0x35 and 0x0a on 26B123). Control+0x14 and exact retired indices +//! qualify READY; no M3 firmware constants or device-control sequence are reused. //! Firmware-reachable backing and the RTKit cookie remain retained until reboot. use core::ffi::c_void; @@ -25,11 +28,10 @@ use kernel::{ use super::adt::{self, GpuAdt}; use super::channel::{self, Channel, Channels}; use super::event::Events; -use super::fw::channels::{devctl, DevCtl}; -use super::fw::initdata::control; -use super::hw; +use super::fw::channels::DevCtl; +use super::hw::{self, LoaderTable}; use super::initdata::{self, InitData}; -use super::object::Objects; +use super::object::{Class, Objects, Placement, Request}; use super::{regs, uat, Config, Shared}; use crate::driver::AsahiDrmDevice; use crate::{mmu, regs as shared_regs}; @@ -42,7 +44,11 @@ pub(crate) mod glue { extern "C" { fn asahi_g16_board() -> bool; - fn asahi_g16_display_prepare(dev: *mut core::ffi::c_void) -> core::ffi::c_int; + fn asahi_g16_display_prepare( + dev: *mut core::ffi::c_void, + display_compat: *const core::ffi::c_char, + ) -> core::ffi::c_int; + fn asahi_g16_timebase_hz() -> u32; fn asahi_g16_hold_power(dev: *mut core::ffi::c_void) -> core::ffi::c_int; fn asahi_g16_ram_disjoint(start: u64, size: u64) -> bool; fn asahi_g16_ioremap_wc(start: u64, size: usize) -> *mut core::ffi::c_void; @@ -60,16 +66,27 @@ pub(crate) mod glue { ) -> core::ffi::c_int; } - /// A qualified J713/T8132 board. + /// A qualified T8132 board (J713, J773g). pub(crate) fn board() -> bool { // SAFETY: Reads the machine compatible strings only. unsafe { asahi_g16_board() } } /// Links the GPU to the published native display, or defers until it is. - pub(crate) fn display_prepare(dev: &device::Device) -> Result { - // SAFETY: `dev` is the bound GPU device; the helper only adds a device link. - kernel::error::to_result(unsafe { asahi_g16_display_prepare(dev.as_raw().cast()) }) + pub(crate) fn display_prepare(dev: &device::Device, display_compatible: &[u8]) -> Result { + let Ok(cstr) = core::ffi::CStr::from_bytes_with_nul(display_compatible) else { + return Err(EINVAL); + }; + // SAFETY: `dev` is the bound GPU device; `cstr` is NUL-terminated. + kernel::error::to_result(unsafe { + asahi_g16_display_prepare(dev.as_raw().cast(), cstr.as_ptr().cast()) + }) + } + + /// The system counter frequency in Hz, as the boot loader programmed it. + pub(crate) fn timebase_hz() -> u32 { + // SAFETY: Reads the system counter frequency register only. + unsafe { asahi_g16_timebase_hz() } } /// Holds the GFX power domain for the retained session. @@ -280,7 +297,7 @@ unsafe extern "C" fn rtkit_shmem_destroy( } /// The GPU's RTKit callbacks. -static RTKIT_OPS: bindings::apple_rtkit_ops = bindings::apple_rtkit_ops { +const RTKIT_OPS_BASE: bindings::apple_rtkit_ops = bindings::apple_rtkit_ops { flags: 0, crashed: Some(rtkit_crashed), recv_message: Some(rtkit_recv), @@ -293,6 +310,56 @@ static RTKIT_OPS: bindings::apple_rtkit_ops = bindings::apple_rtkit_ops { protocol_version: 12, }; +/// 25G83: the firmware's crash buffer is mapped without a reply. +static RTKIT_OPS: bindings::apple_rtkit_ops = RTKIT_OPS_BASE; + +/// 26B123: the crash-log endpoint starts while the endpoint map is handled, and the firmware's +/// request for its own crash buffer is sent back unchanged. +static RTKIT_OPS_27_2: bindings::apple_rtkit_ops = bindings::apple_rtkit_ops { + flags: bindings::APPLE_RTKIT_COPROC_PLACES_BUFFERS, + ..RTKIT_OPS_BASE +}; + +/// The host log buffer message the 26B123 start sends from RTKit's `before_ap` hook. +struct LogBuffer { + rtk: *mut bindings::apple_rtkit, + shared: *const Shared, + message: u64, + result: core::ffi::c_int, +} + +/// RTKit `before_ap` hook of the 26B123 start: once the firmware's own crash buffer has been +/// set up (and its request sent back), hands it the host log buffer before AP power-on. +/// +/// # Safety +/// +/// `data` must point to a live [`LogBuffer`] exclusively borrowed for this call, whose `rtk` +/// is the RTKit instance running the hook and whose `shared` outlives it. +unsafe extern "C" fn publish_log_buffer(data: *mut c_void) { + // SAFETY: By the function's contract. + let log = unsafe { &mut *data.cast::() }; + // SAFETY: By the function's contract. + let shared = unsafe { &*log.shared }; + let start = Instant::::now(); + while matches!(shared.rtkit_buffer.load(Ordering::Acquire), 0 | u64::MAX) { + if start.elapsed() > Delta::from_millis(1000) { + log.result = ETIMEDOUT.to_errno(); + return; + } + fsleep(Delta::from_millis(1)); + } + // SAFETY: `log.rtk` is the live RTKit instance running this hook. + log.result = unsafe { + bindings::apple_rtkit_send_message( + log.rtk, + hw::start_27_2::EP_CRASHLOG, + log.message, + core::ptr::null_mut(), + false, + ) + }; +} + /// The GPU's RTKit client. Never freed: the firmware session lasts until reboot. /// /// # Invariants @@ -309,11 +376,15 @@ unsafe impl Sync for Rtkit {} impl Rtkit { /// Initializes the sole RTKit owner on the default mailbox (retained). - fn new(dev: &device::Device, shared: &Arc) -> Result { + fn new( + dev: &device::Device, + shared: &Arc, + ops: &'static bindings::apple_rtkit_ops, + ) -> Result { let cookie = Arc::into_raw(shared.clone()) as *mut c_void; // SAFETY: `dev` is valid, the name is a NUL-terminated string and the ops are static. let rtk = from_err_ptr(unsafe { - bindings::apple_rtkit_init(dev.as_raw(), cookie, core::ptr::null(), 0, &RTKIT_OPS) + bindings::apple_rtkit_init(dev.as_raw(), cookie, core::ptr::null(), 0, ops) }); match rtk { // INVARIANT: The cookie stays leaked from here on. @@ -342,6 +413,21 @@ impl Rtkit { to_result(unsafe { bindings::apple_rtkit_warm_restart(self.rtk) }) } + /// Waits for the firmware to report in without an IOP power request, runs `before_ap`, then + /// sets the AP on. + /// + /// # Safety + /// + /// `before_ap` must be safe to call with `data`, from this thread, during this call. + unsafe fn boot_with( + &mut self, + before_ap: unsafe extern "C" fn(*mut c_void), + data: *mut c_void, + ) -> Result { + // SAFETY: `rtk` is live by the type invariant; the caller vouches for the hook. + to_result(unsafe { bindings::apple_rtkit_boot_with(self.rtk, Some(before_ap), data) }) + } + /// Waits for the firmware to report in, and sets the AP on. pub(crate) fn boot(&mut self) -> Result { // SAFETY: `rtk` is live by the type invariant. @@ -384,7 +470,7 @@ impl Rtkit { /// The result of admission: everything probe-time checks established, nothing written. pub(crate) struct Admitted { pub(crate) regs: regs::Regs, - pub(crate) adt: GpuAdt, + pub(crate) adt: KBox, } /// The running firmware session: RTKit, MMIO and the adopted UAT. (The @@ -394,8 +480,13 @@ pub(crate) struct Session { pub(crate) shared: Arc, pub(crate) rtkit: Rtkit, pub(crate) regs: regs::Regs, - pub(crate) adt: GpuAdt, + pub(crate) adt: KBox, uat: Arc, + /// The PPL handoff page, mapped here only to read the firmware's powered flag + /// ([`hw::FwLayout::powered`]); `None` when the firmware keeps the GPU powered. + handoff: Option, + /// True once cold boot (`START`) has completed and the firmware may idle-power-off the GPU. + booted: bool, } impl Session { @@ -406,16 +497,74 @@ impl Session { /// Live transport and powered-firmware health, plus any previously latched failure. pub(crate) fn check(&self) -> Result { - self.shared.check()?; - if !self.rtkit.running() - || self.regs.asc_control()? & regs::ASC_RUN == 0 - || self.regs.pstate()? > 9 - { + self.transport()?; + if self.regs.asc_control()? & regs::ASC_RUN == 0 { return Err(EIO); } + // Only read SGX pstate while the GPU is powered under the PPL handoff lock. + if let Some(pstate) = self.while_powered(regs::Regs::pstate)? { + if pstate > self.regs.top() { + return Err(EIO); + } + } self.uat.check_adopted_bindings() } + /// The transport alone: a latched failure, or RTKit stopped or crashed. No register or + /// UAT read, so the retirement loop can ask between its receipts. + pub(crate) fn transport(&self) -> Result { + self.shared.check()?; + if !self.rtkit.running() { + return Err(EIO); + } + Ok(()) + } + + /// Runs `read` with the GPU held powered, or returns `None` while it is powered down. A + /// firmware that powers the GPU down while idle changes GPU power only while it holds the + /// PPL handoff lock, and records the result on the handoff page before releasing it. The + /// AP side of the lock is held here across that record and `read`, so the GPU cannot go + /// down between them. Reading a GPU register while it is down takes an SError. + fn while_powered(&self, read: impl FnOnce(®s::Regs) -> Result) -> Result> { + let (Some(page), Some(offset)) = (&self.handoff, self.adt.layout.powered) else { + return read(&self.regs).map(Some); + }; + let _held = self.uat.lock_m4_handoff()?; + if page.io().try_read8(offset)? == 0 { + return Ok(None); + } + read(&self.regs).map(Some) + } + + /// The engine receipts of a running firmware, or `None` while the GPU is powered down. + pub(crate) fn engine_state(&self) -> Result> { + self.while_powered(regs::Regs::engine_state) + } + + /// All supported engine fault banks while firmware is halted for recovery, + /// or `None` while the GPU is powered down. + pub(crate) fn fault_scan(&self) -> Result> { + self.while_powered(regs::Regs::fault_scan) + } + + /// Writes the host-owned device-control generation register (`sgx + 0xd60000`). Once cold + /// boot has completed and the firmware may idle-power-off the GPU, the access is guarded by + /// [`Self::while_powered`], returning `EAGAIN` if the GPU is currently powered down. + pub(crate) fn set_generation(&self, value: u32) -> Result { + // On G15S this word belongs to submit channel 0. The device-control + // producer is supplied by its separate InitData pointer. + if self.adt.layout.initdata.tx == super::fw::initdata::TxLayout::RingHeader { + return Ok(()); + } + if !self.booted { + return self.regs.set_generation(value); + } + match self.while_powered(|regs| regs.set_generation(value))? { + Some(()) => Ok(()), + None => Err(EAGAIN), + } + } + /// Sends a mailbox message. pub(crate) fn send(&mut self, endpoint: u8, message: u64) -> Result { self.rtkit.send(endpoint, message) @@ -466,28 +615,37 @@ pub(crate) fn admit( _dev: &AsahiDrmDevice, cfg: &'static Config, res: shared_regs::G16Resources, -) -> Result { +) -> Result> { let dev = pdev.as_ref(); - if !glue::board() { + // The board check guards the PMP AGX vote, which only the 25G83 start sends. A firmware + // whose handoff names the start without the vote (26B123) rests on the firmware identity + // checks below instead. + let votes = !matches!( + adt::layout(dev, cfg), + Some(layout) if layout.start == hw::Start::MacOs27_2 + ); + if votes && !glue::board() { return Err(ENODEV); } - // Retain the PMP supplier (and its AGX bridge) before any vote. - // SAFETY: `dev` is the bound GPU device. - let ret = unsafe { bindings::apple_pmp_j713_gpu_prepare(dev.as_raw()) }; - if ret != 0 { - let err = Error::from_errno(ret); - if err != EPROBE_DEFER { - dev_err!(dev, "PMP supplier not ready: {:?}\n", err); + if cfg.prepare_pmp { + // Retain the PMP supplier (and its AGX bridge) before any vote. + // SAFETY: `dev` is the bound GPU device. + let ret = unsafe { bindings::apple_pmp_j713_gpu_prepare(dev.as_raw()) }; + if ret != 0 { + let err = Error::from_errno(ret); + if err != EPROBE_DEFER { + dev_err!(dev, "PMP supplier not ready: {:?}\n", err); + } + return Err(err); } - return Err(err); } - glue::display_prepare(dev).inspect_err(|e| { + glue::display_prepare(dev, cfg.display_compatible).inspect_err(|e| { if *e != EPROBE_DEFER { dev_err!(dev, "native display not admitted: {:?}\n", e); } })?; - let adt = - adt::read(dev).inspect_err(|e| dev_err!(dev, "ADT GPU regions not admitted: {:?}\n", e))?; + let adt = adt::read(dev, cfg) + .inspect_err(|e| dev_err!(dev, "ADT GPU regions not admitted: {:?}\n", e))?; crate::fwid::identify( dev, adt.text.clone(), @@ -495,31 +653,54 @@ pub(crate) fn admit( cfg.firmware, ) .inspect_err(|e| dev_err!(dev, "loaded GFX TEXT identity mismatch: {:?}\n", e))?; - dev_info!(dev, "M4: firmware identity accepted\n"); + dev_info!( + dev, + "M4: firmware identity accepted ({} layout)\n", + adt.layout.name + ); + // Refuse a firmware whose start needs something not known yet before anything is held. + let mut unknown = false; + for what in adt.layout.unknown() { + dev_err!( + dev, + "G16: the {} firmware cannot be started yet; not known: {}\n", + adt.layout.name, + what + ); + unknown = true; + } + if unknown { + return Err(ENOTSUPP); + } // Firmware objects are cleaned to the point of coherency by their DMA mapping: that needs // a device that is not DMA-coherent, as the synthesized node is. if glue::dma_unsupported(dev) { dev_err!(dev, "G16: unsupported coherent, IOMMU or custom DMA path\n"); return Err(EINVAL); } - let regs = regs::Regs::new(pdev, res)?; + let regs = regs::Regs::new(pdev, res, cfg)?; // Once power admission starts, even a rejected cold check must not detach the GFX // domain under an inherited firmware owner. Keep the module and platform binding; once // the module's removal has begun nothing is held. glue::retain_module()?; glue::hold_power(dev)?; let (power_offset, power_state) = glue::power_domain_state(dev)?; - if power_offset != 0x250 || (power_state >> 4) & 0xf != 0xf { + if power_offset != cfg.power_offset || (power_state >> 4) & 0xf != 0xf { dev_err!( dev, - "M4 GFX domain not admitted: register{:#x} state{:#x}\n", + "GFX domain not admitted: register{:#x} state{:#x}\n", power_offset, power_state ); return Err(Error::from_errno(-(bindings::EHOSTDOWN as i32))); } - dev_info!(dev, "T8132 G16G admitted, ASC={:#x}\n", regs.asc_control()?); - Ok(Admitted { regs, adt }) + dev_info!( + dev, + "T{:x} GPU admitted, ASC={:#x}\n", + cfg.chip_id, + regs.asc_control()? + ); + Ok(KBox::init(init!(Admitted { regs, adt }), GFP_KERNEL)?) } /// Posts one device control with only the opcode and waits for it. @@ -558,6 +739,7 @@ fn wait_boot_control( || done > target || write != target { + channels.log_stop(session, init, "unexpected boot-control indices"); return Err(eproto()); } if ready == 1 && read == target && done == target { @@ -569,30 +751,70 @@ fn wait_boot_control( stable = None; } if start.elapsed() > Delta::from_millis(timeout_ms) { - dev_err!( - session.dev, - "M4 boot control target{} ready{} indices{}/{}/{}\n", - target, - ready, - read, - done, - write - ); + channels.log_stop(session, init, "boot control not retired in time"); return Err(ETIMEDOUT); } fsleep(Delta::from_micros(1000)); } } +/// Writes the register-map records into the firmware's table in loaded DATA, which must be +/// empty on cold entry. This is the only host write to the loaded DATA segment. +fn publish_loader_table(session: &Session, init: &InitData, offset: u64) -> Result { + let table = init.loader_bytes(); + let loader = regs::Mapping::write_combined(session.adt.data.start + offset, table.len())?; + for _ in 0..2 { + for offset in (0..table.len()).step_by(4) { + if loader.io().try_read32(offset)? != 0 { + return Err(EBUSY); + } + } + regs::rmb(); + } + for (i, word) in table.chunks_exact(4).enumerate() { + loader + .io() + .try_write32(u32::from_le_bytes(word.try_into().unwrap()), i * 4)?; + } + regs::wmb(); + Ok(()) +} + /// Wake the sole firmware instance, publish its loader table, then qualify NOP and policy. +#[inline(never)] fn run( session: &mut Session, events: &mut Events, built: &mut (InitData, Channels, u32), + cfg: &Config, + log_buffer: Option<(u64, usize)>, ) -> Result { let dev = session.dev.clone(); let (init, channels, _) = built; - session.rtkit.wake()?; + let kind = session.adt.layout.start; + match kind { + hw::Start::Wake25G83 => session.rtkit.wake()?, + hw::Start::MacOs27_2 => { + use hw::start_27_2 as s; + let (va, log_size) = log_buffer.ok_or(EINVAL)?; + let mut log = LogBuffer { + rtk: session.rtkit.as_raw(), + shared: &*session.shared, + message: s::MSG_LOG_BUFFER + | (((log_size >> 12) as u64) << s::MSG_LOG_BUFFER_PAGES_SHIFT) + | (va & s::MSG_LOG_BUFFER_ADDR_MASK), + result: 0, + }; + // SAFETY: `log` lives on this stack frame across the call and nothing else + // borrows it; the hook runs on this thread before `boot_with` returns. + unsafe { + session + .rtkit + .boot_with(publish_log_buffer, (&raw mut log).cast())? + }; + to_result(log.result)?; + } + } let start = Instant::::now(); while matches!( session.shared.rtkit_buffer.load(Ordering::Acquire), @@ -612,50 +834,84 @@ fn run( { return Err(eproto()); } + if kind == hw::Start::MacOs27_2 { + if let Some(probe) = session.regs.publish_host_block(cfg)? { + dev_info!( + dev, + "G16: 27.2 host block published, scratch {:#x}\n", + probe + ); + } + } session.rtkit.start_endpoint(hw::ep::FIRMWARE)?; session.rtkit.start_endpoint(hw::ep::DOORBELL)?; - for _ in 0..10 { - fsleep(Delta::from_millis(10)); - channels.drain_rings(&dev, events)?; - session.check()?; - } - session.regs.set_generation(0)?; - channels.stage_boot_nop(session)?; - // This table is the only host write to the loaded DATA segment. It is empty on cold entry. - let table = init.loader_bytes(); - let loader = regs::Mapping::write_combined(session.adt.data.start + 0x1332f0, table.len())?; - for _ in 0..2 { - for offset in (0..table.len()).step_by(4) { - if loader.io().try_read32(offset)? != 0 { - return Err(EBUSY); - } + let devctl = init.abi.devctl(); + if kind == hw::Start::Wake25G83 { + for _ in 0..10 { + fsleep(Delta::from_millis(10)); + channels.drain_rings(&dev, events)?; + session.check()?; } - regs::rmb(); + session.regs.set_generation(0)?; } - for (i, word) in table.chunks_exact(4).enumerate() { - loader - .io() - .try_write32(u32::from_le_bytes(word.try_into().unwrap()), i * 4)?; + channels.stage_boot_nop(session, devctl.nop)?; + match session.adt.layout.loader_table { + Some(LoaderTable::Host(offset)) => publish_loader_table(session, init, offset)?, + // The firmware copies the register map from HW data while it parses InitData. + Some(LoaderTable::Firmware) => {} + // Admission refuses such a layout; never guess here. + None => return Err(ENOTSUPP), } - regs::wmb(); let root = init.root_va()?; session.send( hw::ep::FIRMWARE, hw::ep::INITDATA | (root & hw::ep::INITDATA_ADDR_MASK), )?; - session.send(hw::ep::DOORBELL, 0x0083000000000011)?; + let g15s_channels = init.layout.tx == super::fw::initdata::TxLayout::RingHeader; + let init_kick = if g15s_channels { + hw::engine::DEVCTL_DOORBELL + } else { + hw::engine::DEVCTL_INIT_DOORBELL + }; + session.send(hw::ep::DOORBELL, init_kick)?; wait_boot_control(session, channels, events, init, 1, 5000)?; - devctl_op(session, channels, events, init, devctl::IMPORT_GLOBALS)?; - wait_boot_control(session, channels, events, init, 2, 2000)?; + let base = 1; let scheduler = init.control.as_ref().ok_or(EINVAL)?; - if scheduler.r32(control::SCHEDULER)? != 0 { - return Err(EBUSY); + let scheduler_word = init.firmware_data().scheduler; + devctl_op(session, channels, events, init, devctl.import_globals)?; + wait_boot_control(session, channels, events, init, base + 1, 5000)?; + let pending = scheduler.r32(scheduler_word)?; + if kind == hw::Start::MacOs27_2 { + // The InitData request (1) can still be pending here on 26B123: the firmware consumes it + // when it powers the GPU up or recovers, and the boot records need not power it up. Post + // START with it pending; never stack a second request. + if pending > 1 { + channels.log_stop( + session, + init, + "scheduler word unexpected after IMPORT_GLOBALS", + ); + return Err(EBUSY); + } + if pending == 0 { + scheduler.w32(scheduler_word, 1)?; + } + } else { + if pending != 0 { + channels.log_stop(session, init, "scheduler word set after IMPORT_GLOBALS"); + return Err(EBUSY); + } + scheduler.w32(scheduler_word, 1)?; } - scheduler.w32(control::SCHEDULER, 1)?; regs::wmb(); - devctl_op(session, channels, events, init, devctl::START)?; - wait_boot_control(session, channels, events, init, 3, 2000)?; - session.send(hw::ep::DOORBELL, 0x0083000000000010)?; + devctl_op(session, channels, events, init, devctl.start)?; + wait_boot_control(session, channels, events, init, base + 2, 2000)?; + let receive_kick = if g15s_channels { + hw::engine::G15S_RECEIVE_DOORBELL + } else { + hw::engine::RECEIVE_DOORBELL + }; + session.send(hw::ep::DOORBELL, receive_kick)?; for _ in 0..10 { fsleep(Delta::from_millis(10)); channels.drain_rings(&dev, events)?; @@ -664,73 +920,120 @@ fn run( return Err(eproto()); } } - if channels.devctl.read()? != 3 - || channels.devctl.completion()? != 3 - || channels.devctl.write()? != 3 - || scheduler.r32(control::SCHEDULER)? != 0 + if channels.devctl.read()? != base + 2 + || channels.devctl.completion()? != base + 2 + || channels.devctl.write()? != base + 2 + || (kind == hw::Start::Wake25G83 && scheduler.r32(scheduler_word)? != 0) { + channels.log_stop(session, init, "boot controls not settled after START"); return Err(EBUSY); } dev_info!( dev, - "M4 firmware accepted owned initdata root{:#x}, NOP and policy; READY\n", - root + "M4 firmware accepted owned initdata root{:#x}, NOP and policy; READY (scheduler {})\n", + root, + scheduler.r32(scheduler_word)? ); Ok(()) } +/// Retains a failed firmware start out-of-line so [`start`] never reserves an [`Orphan`] slot on +/// its normal stack frame. +#[cold] +#[inline(never)] +fn retain_start_failure( + shared: &Shared, + session: Session, + objects: Objects, + built: Option<(InitData, Channels, u32)>, + events: Events, +) { + let (init, channels) = match built { + Some((init, channels, _)) => (Some(init), Some(channels)), + None => (None, None), + }; + match KBox::::new_uninit(GFP_KERNEL) { + Ok(slot) => { + let orphan = slot + .write_init(init!(Orphan { + session, + _objects: objects, + channels, + _init: init, + events, + })) + .unwrap_or_else(|e| match e {}); + shared.retain_failed(super::Retained::Orphan(orphan)); + } + Err(_) => { + dev_err!( + shared.dev.as_ref(), + "G16: cannot keep the failed session; leaked\n" + ); + // Without memory for the box, leak the firmware-reachable parts. + core::mem::forget((session, objects, channels, init, events)); + } + } +} + /// Brings the firmware to READY. #[inline(never)] pub(crate) fn start( - admitted: Admitted, + admitted: KBox, dev: &AsahiDrmDevice, cfg: &'static Config, shared: &Arc, -) -> Result { - let Admitted { regs, adt } = admitted; +) -> Result> { + let Admitted { regs, adt } = KBox::into_inner(admitted); let d: ARef = shared.dev.clone(); // Cold ownership must hold before the PMP vote as well as immediately before RUN. if regs.asc_control()? & regs::ASC_RUN != 0 { return Err(EBUSY); } - // SAFETY: `d` is the bound GPU device. - let ret = unsafe { bindings::apple_pmp_j713_gpu_get(d.as_raw()) }; - if ret != 0 { - dev_err!(d, "PMP AGX vote failed: {}\n", ret); - return Err(Error::from_errno(ret)); + let kind = adt.layout.start; + if kind == hw::Start::MacOs27_2 { + // 26B123 sends no PMP AGX vote: the firmware acknowledges its own IOP power-on once + // GFXCAXI2AF is enabled and RUN is raised. + dev_info!(d, "G16: 26B123: starting without PMP AGX vote\n"); + regs.enable_axi2af()?; + } else { + // SAFETY: `d` is the bound GPU device. + let ret = unsafe { bindings::apple_pmp_j713_gpu_get(d.as_raw()) }; + if ret != 0 { + dev_err!(d, "PMP AGX vote failed: {}\n", ret); + return Err(Error::from_errno(ret)); + } } let id = regs.identity()?; dev_info!( d, - "M4 G16G: power acknowledged, version={:#x} counts={:#x} core-mask={:#x}\n", + "T{:x}: power acknowledged, version={:#x} counts={:#x} core-mask={:#x}\n", + cfg.chip_id, id.version, id.counts, id.cores ); - if !cfg - .hw_ids - .iter() - .any(|h| h.version == id.version && h.counts == id.counts) - { + if !cfg.hw_ids.iter().any(|h| h.matches(id.version, id.counts)) { dev_err!( d, - "unsupported G16G hardware: version {:#x} counts {:#x}\n", + "unsupported GPU hardware: version {:#x} counts {:#x}\n", id.version, id.counts ); return Err(eproto()); } - // M4 has one cluster with up to ten enabled cores. - if id.core_masks[0] == 0 || id.cores >> hw::CLUSTER_BITS != 0 { - dev_err!(d, "implausible G16G core mask {:#x}\n", id.cores); + if id.cores >> cfg.core_slots() != 0 || id.core_masks[..cfg.num_clusters as usize].contains(&0) + { + dev_err!(d, "implausible GPU core mask {:#x}\n", id.cores); return Err(eproto()); } dev_info!( d, - "M4 G16G: {} cores enabled\n", - id.core_masks[0].count_ones() + "T{:x}: {} cores enabled\n", + cfg.chip_id, + id.cores.count_ones() ); - if regs.pstate()? > 9 { + if regs.pstate()? > regs.top() { return Err(eproto()); } // Cold only: ASC RUN clear and an all-zero TTBAT before ownership. @@ -742,6 +1045,13 @@ pub(crate) fn start( if !window.ttbat_is_clear()? { return Err(EBUSY); } + let handoff = match adt.layout.powered { + Some(_) => Some(regs::Mapping::write_combined( + adt.handoff.start, + hw::HANDOFF_SIZE as usize, + )?), + None => None, + }; // Adopt the UAT and prove the leaf words before anything firmware-visible is written: no // context names the shadow window or the lower root yet. let uat = uat::adopt(dev, cfg, &adt)?; @@ -758,13 +1068,24 @@ pub(crate) fn start( core::mem::forget(objects); return Err(e); } - let rtkit = match Rtkit::new(&d, shared) { + let ops = match kind { + hw::Start::Wake25G83 => &RTKIT_OPS, + hw::Start::MacOs27_2 => &RTKIT_OPS_27_2, + }; + let rtkit = match Rtkit::new(&d, shared, ops) { Ok(rtkit) => rtkit, Err(e) => { core::mem::forget(objects); return Err(e); } }; + let booted_slot = match KBox::::new_uninit(GFP_KERNEL) { + Ok(slot) => slot, + Err(e) => { + core::mem::forget(objects); + return Err(e.into()); + } + }; let mut session = Session { dev: d.clone(), shared: shared.clone(), @@ -772,13 +1093,44 @@ pub(crate) fn start( regs, adt, uat, + handoff, + booted: false, }; let mut events = Events::new(); let mut built = None; let result = (|| { events.reserve()?; // Every host object and every context-0 alias is prepared before RUN is set. - built = Some(initdata::build(&d, &session.adt, &mut objects)?); + built = Some(initdata::build( + &d, + &session.adt, + cfg, + &session.regs, + id.cores.count_ones(), + &mut objects, + )?); + if let Some((init, _, _)) = built.as_ref() { + // The running firmware may report any state of the board's table, up to S10 on J773g. + session.regs.set_table(init.rows); + } + let log_buffer = match kind { + hw::Start::MacOs27_2 => { + let log_size = session.adt.performance.coredump_copy_size.ok_or(EINVAL)? as usize; + let va = objects + .alloc(Request { + size: log_size, + class: Class::Fw, + placement: Placement::Anywhere, + offset: 0, + client: None, + lower: None, + cpu: true, + })? + .va; + Some((va, log_size)) + } + hw::Start::Wake25G83 => None, + }; objects.window.lock().bootstrap(&d, &session.uat)?; uat::tlbi_all(); if session.regs.asc_control()? & regs::ASC_RUN != 0 { @@ -790,7 +1142,16 @@ pub(crate) fn start( if session.regs.asc_control()? & regs::ASC_RUN == 0 { return Err(EIO); } - run(&mut session, &mut events, built.as_mut().ok_or(EINVAL)?) + objects.window.lock().await_firmware_magic(&d)?; + run( + &mut session, + &mut events, + built.as_mut().ok_or(EINVAL)?, + cfg, + log_buffer, + )?; + session.booted = true; + Ok(()) })(); if let Err(e) = result { dev_err!( @@ -798,27 +1159,19 @@ pub(crate) fn start( "G16 start failed: {:?}; session retained until reboot\n", e ); - let (init, channels) = match built { - Some((init, channels, _)) => (Some(init), Some(channels)), - None => (None, None), - }; - shared.orphan(Orphan { - session, - _objects: objects, - channels, - _init: init, - events, - }); + retain_start_failure(shared, session, objects, built, events); return Err(e); } let (init, channels, max_frequency_khz) = built.ok_or(EINVAL)?; - Ok(Booted { - session, - init, - objects, - channels, - events, - id, - max_frequency_khz, - }) + Ok(booted_slot + .write_init(init!(Booted { + session, + init, + objects, + channels, + events, + id, + max_frequency_khz, + })) + .unwrap_or_else(|e| match e {})) } diff --git a/drivers/gpu/drm/asahi/g16/channel.rs b/drivers/gpu/drm/asahi/g16/channel.rs index 7e67501a4c8c75..22c792c1135534 100644 --- a/drivers/gpu/drm/asahi/g16/channel.rs +++ b/drivers/gpu/drm/asahi/g16/channel.rs @@ -15,9 +15,8 @@ use kernel::{ use super::boot::Session; use super::event::Events; -use super::fw::channels::{ - DevCtl, SubmitRecord, RING_SLOTS, STATE_COMPLETION, STATE_READ, STATE_WRITE, -}; +use super::fw::channels::{DevCtl, SubmitRecord, RING_SLOTS, STATE_READ, STATE_WRITE}; +use super::fw::initdata::TxLayout; use super::hw::{self, rings}; use super::initdata::InitData; use super::object::{Class, FwObject, Objects, Placement, Request}; @@ -36,25 +35,61 @@ pub(crate) enum Channel { pub(crate) struct Ring { pub(crate) state: Arc, pub(crate) ring: Arc, + completion: usize, + header: usize, } impl Ring { + pub(crate) fn new( + state: Arc, + ring: Arc, + tx: TxLayout, + control: bool, + ) -> Self { + Self { + state, + ring, + completion: tx.completion(), + header: tx.ring_header(control), + } + } + /// The consumer's read index (state +0x00). pub(crate) fn read(&self) -> Result { self.state.r32(STATE_READ) } - /// The completion index (state +0x10). + /// The completion index in the channel's state block. pub(crate) fn completion(&self) -> Result { - self.state.r32(STATE_COMPLETION) + // Submit rings with a producer header retire at the consumer's read cursor. + if self.header != 0 { + self.read() + } else { + self.state.r32(self.completion) + } } - /// The producer's write index (state +0x20). + /// The producer's write index, either in state or at the start of the ring. pub(crate) fn write(&self) -> Result { - self.state.r32(STATE_WRITE) + if self.header == 0 { + self.state.r32(STATE_WRITE) + } else { + self.ring.r32(0) + } + } + + fn set_write(&self, value: u32) -> Result { + if self.header == 0 { + self.state.w32(STATE_WRITE, value) + } else { + self.ring.w32(0, value) + } } } +/// Maximum firmware log entries printed per recovery before suppressing excess entries. +pub(crate) const RECOVERY_FWLOG_CAP: usize = 32; + /// The channels and rings. pub(crate) struct Channels { /// The 12 submit channels (TA, FS and compute are used). @@ -63,6 +98,8 @@ pub(crate) struct Channels { pub(crate) event: Ring, /// The nine log sub-rings share one state object (9 x 0x30) and one ring object. pub(crate) log: Ring, + /// Backing payload buffer (`LOG_DATA`, 9 x 256 x 0xd8) indexed by firmware log records. + log_data: Arc, pub(crate) trace: Ring, pub(crate) stats: Ring, /// Allocated for the firmware; the host never uses it. @@ -90,9 +127,11 @@ impl Channels { /// Their state is uncached; the submit records use the qualified ASC-cached class. pub(crate) fn alloc_submit_and_attach( objects: &mut Objects, + tx: TxLayout, devctl: Ring, event: Ring, log: Ring, + log_data: Arc, trace: Ring, stats: Ring, fwctl: Ring, @@ -100,10 +139,16 @@ impl Channels { let mut submit = KVec::with_capacity(rings::CHANNELS as usize, GFP_KERNEL)?; for _ in 0..rings::CHANNELS { submit.push( - Ring { - state: fw_object(objects, rings::STATE_SIZE, false)?, - ring: fw_object(objects, rings::CHANNEL_RING_SIZE, true)?, - }, + Ring::new( + fw_object(objects, rings::STATE_SIZE, false)?, + fw_object( + objects, + rings::CHANNEL_RING_SIZE + tx.ring_header(false), + tx == TxLayout::StateBlock, + )?, + tx, + false, + ), GFP_KERNEL, )?; } @@ -112,6 +157,7 @@ impl Channels { devctl, event, log, + log_data, trace, stats, _fwctl: fwctl, @@ -135,7 +181,7 @@ impl Channels { self.channel(channel).read() } - /// The channel's write cell (state +0x20). + /// The channel's producer. pub(crate) fn write_cell(&self, channel: Channel) -> Result { self.channel(channel).write() } @@ -172,19 +218,20 @@ impl Channels { return Err(EBUSY); } ring.ring.write( - producer as usize * rings::CHANNEL_RECORD, + ring.header + producer as usize * rings::CHANNEL_RECORD, &record.to_bytes(), )?; wmb(); let producer = (producer + 1) % RING_SLOTS; - ring.state.w32(STATE_WRITE, producer)?; + ring.set_write(producer)?; wmb(); self.producer[ch] = producer; Ok(producer) } - /// Stage the boot NOP before the initdata root is handed to the firmware. - pub(crate) fn stage_boot_nop(&mut self, session: &Session) -> Result { + /// Stage the boot NOP (the firmware ABI's consume-only `nop` opcode) before the initdata + /// root is handed to the firmware. + pub(crate) fn stage_boot_nop(&mut self, session: &Session, nop: u32) -> Result { if self.devctl_producer != 0 || self.devctl.read()? != 0 || self.devctl.completion()? != 0 @@ -192,54 +239,212 @@ impl Channels { { return Err(super::boot::eproto()); } - self.devctl - .ring - .write(0, &DevCtl::op(super::fw::channels::devctl::NOP).to_bytes())?; + self.devctl.ring.write(0, &DevCtl::op(nop).to_bytes())?; wmb(); - session.regs.set_generation(1)?; - self.devctl.state.w32(STATE_WRITE, 1)?; + session.set_generation(1)?; + self.devctl.set_write(1)?; wmb(); self.devctl_producer = 1; Ok(()) } - /// Consumes a receive ring to its firmware producer. - fn drain_one(ring: &Ring, offset: usize, capacity: u32) -> Result { - let producer = ring.state.r32(offset + STATE_WRITE)?; - let consumer = ring.state.r32(offset + STATE_READ)?; - if producer >= capacity || consumer >= capacity { + /// The one error line for a stop during the boot sequence: why, the device-control indices + /// and the FirmwareData recovery words. Reads host RAM only, never a GPU register. + pub(crate) fn log_stop(&self, session: &Session, init: &InitData, why: &str) { + let ix = |r: Result| r.unwrap_or(u32::MAX); + let fd = init.firmware_data(); + let word = |o: usize| init.control.as_ref().map_or(u32::MAX, |c| ix(c.r32(o))); + dev_err!( + session.dev, + "G16 boot stopped: {}: devctl read {} completion {} write {} producer {}; phase {:#x} scheduler {:#x} ready {:#x}\n", + why, + ix(self.devctl.read()), + ix(self.devctl.completion()), + ix(self.devctl.write()), + self.devctl_producer, + word(fd.phase), + word(fd.scheduler), + ix(init.readiness()) + ); + } + + /// Drains one firmware log sub-ring. Outside recovery (`budget` is `None`), advances the + /// consumer directly without touching the payload pages. During recovery (`Some(remaining)`), + /// prints up to the last `*remaining` entries and counts any older/excess entries suppressed. + #[inline(never)] + fn drain_log_ring( + &self, + dev: &kernel::device::Device, + thread: usize, + budget: Option<&mut usize>, + suppressed: &mut usize, + ) -> Result { + let offset = thread * 0x30; + let producer = self.log.state.r32(offset + STATE_WRITE)?; + let mut consumer = self.log.state.r32(offset + STATE_READ)?; + if producer >= RING_SLOTS || consumer >= RING_SLOTS { return Err(super::boot::eproto()); } - if consumer != producer { - ring.state.w32(offset + STATE_READ, producer)?; - wmb(); + if consumer == producer { + return Ok(()); } + if let Some(remaining) = budget { + rmb(); + let pending = producer.wrapping_sub(consumer) % RING_SLOTS; + if (pending as usize) > *remaining { + let skip = pending as usize - *remaining; + *suppressed = suppressed.saturating_add(skip); + consumer = (consumer + skip as u32) % RING_SLOTS; + } + while consumer != producer { + let entry_off = + (thread * RING_SLOTS as usize + consumer as usize) * rings::EVENT_RECORD; + let kind = self.log.ring.r32(entry_off)?; + let slot = self.log.ring.r32(entry_off + 8)?; + let payload_idx = thread * RING_SLOTS as usize + (slot & 255) as usize; + let payload_off = payload_idx * rings::LOG_PAYLOAD_SIZE; + let ptype = self.log_data.r32(payload_off)?; + let seq = self.log_data.r32(payload_off + 4)?; + let mut text = [0u8; rings::LOG_PAYLOAD_TEXT_SIZE]; + self.log_data + .read(payload_off + rings::LOG_PAYLOAD_TEXT_OFFSET, &mut text)?; + let len = text.iter().position(|&b| b == 0).unwrap_or(text.len()); + let line = core::str::from_utf8(&text[..len]) + .ok() + .map(|s| s.trim_end_matches(['\r', '\n'])); + match line { + Some(msg) if !msg.is_empty() && kind == 2 && ptype == 3 => { + dev_warn!( + dev, + "G16: fwlog[{}] seq={} slot={}: {}\n", + thread, + seq, + slot, + msg + ); + } + Some(msg) if !msg.is_empty() => { + dev_warn!( + dev, + "G16: fwlog[{}] kind={} ptype={} seq={} slot={}: {}\n", + thread, + kind, + ptype, + seq, + slot, + msg + ); + } + _ => { + dev_warn!( + dev, + "G16: fwlog[{}] kind={} ptype={} seq={} slot={} (non-text len={})\n", + thread, + kind, + ptype, + seq, + slot, + len + ); + } + } + *remaining = remaining.saturating_sub(1); + consumer = (consumer + 1) % RING_SLOTS; + } + } + self.log.state.w32(offset + STATE_READ, producer)?; + wmb(); Ok(()) } + /// Drains the event and statistics receive rings, which carry completion notifications and + /// firmware recovery announcements. Hot retirement passes use this to avoid polling the + /// auxiliary log and trace rings on every flight; periodic housekeeping drains the rest. + pub(crate) fn drain_events_and_stats( + &self, + dev: &kernel::device::Device, + events: &mut Events, + ) -> Result { + let mut result = events.drain(dev, &self.event); + let stats = events.drain_statistics(dev, &self.stats); + if result.is_ok() { + result = stats; + } + result + } + + /// Drains the nine log sub-rings and the ktrace receive ring. When `fwlog_budget` is `Some`, + /// prints drained firmware log records up to the remaining budget. + pub(crate) fn drain_auxiliary_rings_with_log( + &self, + dev: &kernel::device::Device, + mut fwlog_budget: Option<&mut usize>, + ) -> Result { + let mut result = Ok(()); + let mut suppressed = 0usize; + let mut keep = |r: Result| { + if result.is_ok() { + result = r; + } + }; + for i in 0..rings::LOG_RINGS { + keep(self.drain_log_ring(dev, i, fwlog_budget.as_deref_mut(), &mut suppressed)); + } + if suppressed != 0 { + dev_warn!( + dev, + "G16: fwlog: suppressed {} additional entries during recovery\n", + suppressed + ); + } + keep(self.drain_trace(dev)); + result + } + + /// Drains the nine log sub-rings and the ktrace receive ring silently. + pub(crate) fn drain_auxiliary_rings(&self, dev: &kernel::device::Device) -> Result { + self.drain_auxiliary_rings_with_log(dev, None) + } + /// Drains every receive ring: events (decoded into `events`), the nine log sub-rings, trace - /// and stats. + /// and stats, whatever another ring reported. The firmware waits while its event ring is + /// full, so one bad record must never leave a ring undrained. The first error is returned + /// once all are done. pub(crate) fn drain_rings(&self, dev: &kernel::device::Device, events: &mut Events) -> Result { - events.drain(dev, &self.event)?; - for i in 0..rings::LOG_RINGS { - Self::drain_one(&self.log, i * 0x30, 256)?; + let mut result = self.drain_events_and_stats(dev, events); + let aux = self.drain_auxiliary_rings(dev); + if result.is_ok() { + result = aux; } - // Ktrace has twice the capacity of the other receive rings. + result + } + + /// Ktrace has twice the capacity of the other receive rings. A record of another type than + /// the qualified one (5) is logged and consumed, then reported. + fn drain_trace(&self, dev: &kernel::device::Device) -> Result { let producer = self.trace.write()?; let mut consumer = self.trace.read()?; if producer >= 512 || consumer >= 512 { return Err(super::boot::eproto()); } rmb(); + let mut result = Ok(()); while consumer != producer { - if self.trace.ring.r32(consumer as usize * 0x48)? != 5 { - return Err(super::boot::eproto()); + let kind = self.trace.ring.r32(consumer as usize * 0x48)?; + if kind != 5 && result.is_ok() { + dev_err!( + dev, + "unexpected M4 firmware trace record type {} at {}\n", + kind, + consumer + ); + result = Err(super::boot::eproto()); } consumer = (consumer + 1) % 512; self.trace.state.w32(STATE_READ, consumer)?; wmb(); } - events.drain_statistics(dev, &self.stats) + result } } @@ -266,6 +471,7 @@ pub(crate) fn devctl_submit( channels.drain_rings(&dev, events)?; session.check()?; if init.halted()? { + channels.log_stop(session, init, "firmware halted before a control was posted"); return Err(EBUSY); } if expired() { @@ -285,8 +491,8 @@ pub(crate) fn devctl_submit( .ring .write(producer as usize * rings::DEVCTL_RECORD, &record.to_bytes())?; wmb(); - session.regs.set_generation(next)?; - channels.devctl.state.w32(STATE_WRITE, next)?; + session.set_generation(next)?; + channels.devctl.set_write(next)?; wmb(); channels.devctl_producer = next; session.send(hw::ep::DOORBELL, hw::engine::DEVCTL_DOORBELL)?; @@ -300,6 +506,7 @@ pub(crate) fn devctl_submit( return Ok(()); } if init.halted()? { + channels.log_stop(session, init, "firmware halted awaiting a control"); return Err(EBUSY); } if expired() { @@ -333,14 +540,35 @@ impl Firmware { ) } - /// The latched transport error: an RTKit crash or a refused RTKit buffer. + /// The latched transport error: an RTKit crash or a refused RTKit buffer. The register + /// and UAT checks of [`Session::check`] run once per pass, in its callers. pub(crate) fn transport_error(&self) -> Option { - self.session.check().err() + self.session.transport().err() } - /// Drains the receive rings and decodes events. Called first in every poll pass. + /// Drains the receive rings and decodes events. Called on full housekeeping and idle passes. pub(crate) fn drain_rings(&mut self) -> Result { let dev = self.session.dev.clone(); - self.channels.drain_rings(&dev, &mut self.events) + let mut result = self.channels.drain_events_and_stats(&dev, &mut self.events); + let aux = self.drain_auxiliary_rings(); + if result.is_ok() { + result = aux; + } + result + } + + /// Drains only the event and statistics rings on the hot retirement path. + pub(crate) fn drain_events_and_stats(&mut self) -> Result { + let dev = self.session.dev.clone(); + self.channels.drain_events_and_stats(&dev, &mut self.events) + } + + /// Drains the auxiliary log and trace rings on periodic housekeeping passes. Prints firmware + /// log records (bounded per recovery) whenever a firmware recovery is pending or running. + pub(crate) fn drain_auxiliary_rings(&mut self) -> Result { + let dev = self.session.dev.clone(); + let log_fwlog = self.recovery.receipt_fault || self.recovery_pending().unwrap_or(false); + let budget = log_fwlog.then_some(&mut self.recovery.fwlog_remaining); + self.channels.drain_auxiliary_rings_with_log(&dev, budget) } } diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index a2b329789444cc..da75e71a9ddc1c 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -9,7 +9,10 @@ //! Render/compute attachments are retained with the immutable command; the whole //! VM job guard protects indirect and bindless accesses through retirement. //! Exact historical prefixes become immutable per-command dependencies. Ray-query state -//! remains disabled. +//! (RENDER_RAY_QUERY) and the AS-build flag (BOUNDED_AS_BUILD) are the M4 Pro's G17P command +//! set ([`super::rt`]): compute scratch layouts and intersection tables, render ray-query +//! stages, and compute flag bit 2 (alongside COMPUTE_NO_QUERY_ACCESS); every other compute +//! flag and reserved word stays MBZ. use core::mem::{offset_of, size_of}; use core::ops::Range; @@ -34,9 +37,34 @@ const NONE: u16 = uapi::DRM_ASAHI_BARRIER_NONE as u16; const VERTEX_SCRATCH: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_VERTEX_SCRATCH; const PROCESS_EMPTY_TILES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_PROCESS_EMPTY_TILES; +const NO_VERTEX_CLUSTERING: u32 = + uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_NO_VERTEX_CLUSTERING; const RSRC_SPEC_HI: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_RSRC_SPEC_HI; const DBIAS_IS_INT: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_DBIAS_IS_INT; +const FEW_PRIMITIVES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FEW_PRIMITIVES; const FRAGMENT_BARRIERS: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; +const STAGE_PREFIXES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; +const COMPUTE_NO_QUERY_ACCESS: u32 = + uapi::drm_asahi_compute_flags_DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS as u32; + +const RENDER_STAGE_PREFIXES_OFF: usize = + offset_of!(uapi::drm_asahi_cmd_render_m5, stage_prefixes); +const RENDER_M5_SIZE: usize = size_of::(); + +const _: () = { + assert!(RENDER_STAGE_PREFIXES_OFF == size_of::()); + assert!(size_of::() == 448); + assert!(RENDER_M5_SIZE == 480); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, ta_cdm_barrier) == 0); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, reserved0) == 2); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, reserved1) == 4); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, ta_prior_cdm) == 8); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, ta_vdm_barrier) == 16); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, reserved2) == 18); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, reserved3) == 20); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, ta_prior_vdm) == 24); + assert!(size_of::() == 32); +}; const CMD_RENDER: u32 = uapi::drm_asahi_cmd_type_DRM_ASAHI_CMD_RENDER; const CMD_COMPUTE: u32 = uapi::drm_asahi_cmd_type_DRM_ASAHI_CMD_COMPUTE; @@ -46,7 +74,7 @@ const SET_COMPUTE_ATTACHMENTS: u32 = uapi::drm_asahi_cmd_type_DRM_ASAHI_SET_COMP const MAX_DIMENSION: u16 = 16384; const MAX_LAYERS: u16 = 2048; -const MAX_TILE_BUFFER: u32 = 32768; +const ZLS_METADATA_STRIDE: u64 = 0x80; /// Size of a queue's USC window. pub(crate) const USC_WINDOW: u64 = 1 << 32; @@ -63,6 +91,7 @@ pub(crate) struct Order { pub(crate) engine: usize, pub(crate) sequence: u64, pub(crate) wait_through: [Option; 2], + pub(crate) ta_wait_through: [Option; 2], } impl Order { @@ -106,18 +135,36 @@ impl Order { engine, sequence: sequences[engine], wait_through, + ta_wait_through: wait_through, }) } - /// A same-engine command cannot jump a hole in its queue's completed frontier. - /// Cross-engine historical dependencies end at the named prefix, even while later - /// commands in that older submission remain pending. - pub(crate) fn ready(&self, completed: [u64; 2]) -> bool { - completed[self.engine].checked_add(1) == Some(self.sequence) + /// Narrows the tiling half's prefixes to `tiling` (`DRM_ASAHI_RENDER_STAGE_PREFIXES`), + /// requiring each stage prefix to stay within the command's full fragment prefix. + pub(crate) fn narrow_tiling(&mut self, tiling: &Self) -> Result { + for index in 0..2 { + if tiling.wait_through[index].unwrap_or(0) > self.wait_through[index].unwrap_or(0) { + return Err(EINVAL); + } + } + self.ta_wait_through = tiling.wait_through; + Ok(()) + } + + /// A same-engine command cannot jump a hole in its queue's published frontier. + /// Cross-engine dependencies may also follow published predecessors via hardware + /// ring barriers (FS -> CDM and CDM -> TA) while same-VM work pipelines; cross-VM + /// switches, InitBM and timestamp query accesses still drain to completion. + pub(crate) fn ready(&self, completed: [u64; 2], published: [u64; 2]) -> bool { + let frontier = [ + published[RENDER].max(completed[RENDER]), + published[COMPUTE].max(completed[COMPUTE]), + ]; + frontier[self.engine].checked_add(1) == Some(self.sequence) && self .wait_through .iter() - .zip(completed) + .zip(frontier) .all(|(prefix, observed)| prefix.is_none_or(|last| observed >= last)) } } @@ -126,20 +173,53 @@ impl Order { pub(crate) struct RenderCommand { /// The payload, zero-extended to the full UAPI structure. pub(crate) cmd: uapi::drm_asahi_cmd_render, + /// The validated ray-query state of the vertex and fragment stages. + pub(crate) ray_query: [super::rt::RayQueryStage; 2], + /// The SCS-capable UMA pool of both stages' scratch. + pub(crate) scs: super::rt::ScsSeeds, /// Retained timestamp destinations, published after full command retirement. pub(crate) timestamp_outputs: crate::timestamp::Destinations, /// Explicit hardware attachments in effect for each render engine. pub(crate) vertex_attachments: KVec, pub(crate) fragment_attachments: KVec, + /// Whether this pass exceeds the light-TA wave threshold (multi-layer or large tilemap). + pub(crate) heavy_ta: bool, +} + +impl RenderCommand { + /// Whether this render pass requires the conservative `TA_WAVE_PASSES` wave window. + pub(crate) fn is_heavy_ta(&self) -> bool { + self.heavy_ta + } + + /// Whether this render pass is multisampled. + pub(crate) fn is_multisampled(&self) -> bool { + self.cmd.samples > 1 + } } /// A validated compute command. pub(crate) struct ComputeCommand { pub(crate) cmd: uapi::drm_asahi_cmd_compute, + /// The validated scratch layout and intersection tables. + pub(crate) ray: super::rt::ComputeRay, + /// The SCS-capable UMA pool of the scratch. + pub(crate) scs: super::rt::ScsSeeds, + /// DRM_ASAHI_COMPUTE_AS_BUILD. + pub(crate) as_build: bool, /// The compute attachments in effect (validated writable). pub(crate) attachments: KVec, /// Retained timestamp destinations, published after full command retirement. pub(crate) timestamp_outputs: crate::timestamp::Destinations, + /// False when userspace asserts this dispatch neither copies nor resets timestamp queries. + pub(crate) query_access: bool, +} + +impl ComputeCommand { + /// Whether this compute command uses ray-tracing or SCS-scratch state. + pub(crate) fn is_rt(&self) -> bool { + self.as_build || self.ray.intersection.enabled() || self.scs.needed != 0 + } } /// A validated command. @@ -148,12 +228,141 @@ pub(crate) enum Command { Compute(KBox), } +impl Command { + /// The command traces rays or builds acceleration structures and gets the long execution + /// allowance, as do the other commands of its submission (`Job::long`). + pub(crate) fn long(&self) -> bool { + match self { + Command::Render(r) => { + super::rt::select(false, r.ray_query.map(|stage| stage.traces()), false) + } + Command::Compute(c) => { + super::rt::select(c.ray.intersection.enabled(), [false; 2], c.as_build) + } + } + } + + /// The SCS-capable UMA pool the command runs on ([`super::rt::ScsSeeds::NONE`] without + /// shader-context scratch). + pub(crate) fn scs(&self) -> super::rt::ScsSeeds { + match self { + Command::Render(r) => r.scs, + Command::Compute(c) => c.scs, + } + } +} + +/// Inline storage for the common 1-2 command submission, spilling to a heap `KVec` above 2. +pub(crate) enum Commands { + Empty, + One([Command; 1]), + Two([Command; 2]), + Heap(KVec), +} + +impl Commands { + fn new() -> Self { + Self::Empty + } + + fn push(&mut self, command: Command) -> Result { + match self { + Self::Heap(vec) => vec.push(command, GFP_KERNEL)?, + Self::Two(_) => { + // Allocate before moving inline entries so OOM leaves `self` intact. + let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; + if let Self::Two([a, b]) = core::mem::replace(self, Self::Empty) { + let _ = vec.push_within_capacity(a); + let _ = vec.push_within_capacity(b); + let _ = vec.push_within_capacity(command); + } + *self = Self::Heap(vec); + } + Self::One(_) => { + if let Self::One([a]) = core::mem::replace(self, Self::Empty) { + *self = Self::Two([a, command]); + } + } + Self::Empty => *self = Self::One([command]), + } + Ok(()) + } +} + +impl core::ops::Deref for Commands { + type Target = [Command]; + + fn deref(&self) -> &[Command] { + match self { + Self::Empty => &[], + Self::One(items) => items, + Self::Two(items) => items, + Self::Heap(vec) => vec, + } + } +} + +impl core::ops::DerefMut for Commands { + fn deref_mut(&mut self) -> &mut [Command] { + match self { + Self::Empty => &mut [], + Self::One(items) => items, + Self::Two(items) => items, + Self::Heap(vec) => vec, + } + } +} + +/// Inline storage for the common 1-2 command ordinals, spilling to a heap `KVec` above 2. +pub(crate) enum Orders { + Empty, + One([Order; 1]), + Two([Order; 2]), + Heap(KVec), +} + +impl Orders { + fn new() -> Self { + Self::Empty + } + + fn push(&mut self, order: Order) -> Result { + match self { + Self::Heap(vec) => vec.push(order, GFP_KERNEL)?, + Self::Two([a, b]) => { + let (a, b) = (*a, *b); + let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; + let _ = vec.push_within_capacity(a); + let _ = vec.push_within_capacity(b); + let _ = vec.push_within_capacity(order); + *self = Self::Heap(vec); + } + Self::One([a]) => *self = Self::Two([*a, order]), + Self::Empty => *self = Self::One([order]), + } + Ok(()) + } +} + +impl core::ops::Deref for Orders { + type Target = [Order]; + + fn deref(&self) -> &[Order] { + match self { + Self::Empty => &[], + Self::One(items) => items, + Self::Two(items) => items, + Self::Heap(vec) => vec, + } + } +} + /// A validated SUBMIT. pub(crate) struct Submission { /// The commands, in submission order. - pub(crate) commands: KVec, + pub(crate) commands: Commands, /// Exact per-command queue-local ordinals, allocated before scheduler acceptance. - pub(crate) orders: KVec, + pub(crate) orders: Orders, /// Render and compute commands, for the queue's accepted-command accounting. pub(crate) counts: [u64; 2], } @@ -164,16 +373,21 @@ pub(crate) struct Context<'a> { pub(crate) vm: &'a mmu::Vm, /// The queue's USC window base. pub(crate) usc_base: u64, + /// Enabled GPU cores, which SCS memory is sized for. + pub(crate) active_cores: u32, + /// The queue's reserved render scratch pages per stage (`render_scs_layout`). + pub(crate) render_scs: [u16; 2], + /// Largest tile buffer render commands may use, in bytes (`Config::max_tile_buffer`). + pub(crate) max_tile_buffer: u32, } -/// A stream whose timestamps and ordinals are resolved ([`prepare`]), before its spans are -/// checked ([`Prepared::validate`]). -pub(crate) struct Prepared<'a> { - bytes: &'a [u8], - /// CPU views and their backing resolved before scheduler acceptance. - resolved: KVec, - orders: KVec, +/// A stream whose timestamps and ordinals are resolved ([`ParsedStream::prepare`]), before its +/// spans are checked ([`Prepared::validate`]). +pub(crate) struct Prepared { + commands: Commands, + orders: Orders, counts: [u64; 2], + gpu_generation: u32, } /// One command of the stream. @@ -237,6 +451,97 @@ fn payload(bytes: &[u8]) -> Result { Reader::new(bytes).read_up_to(bytes.len()) } +/// Decodes the 32-byte `drm_asahi_render_stage_prefixes` tail from a 480-byte +/// `drm_asahi_cmd_render_m5` payload without adding a duplicate `AnyBitPattern` impl. +fn decode_stage_prefixes(tail: &[u8]) -> Result { + let bytes: &[u8; 32] = tail.try_into().map_err(|_| EINVAL)?; + let u16_at = |o: usize| u16::from_le_bytes([bytes[o], bytes[o + 1]]); + let u32_at = |o: usize| { + u32::from_le_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]]) + }; + let u64_at = |o: usize| { + u64::from_le_bytes([ + bytes[o], + bytes[o + 1], + bytes[o + 2], + bytes[o + 3], + bytes[o + 4], + bytes[o + 5], + bytes[o + 6], + bytes[o + 7], + ]) + }; + Ok(uapi::drm_asahi_render_stage_prefixes { + ta_cdm_barrier: u16_at(0), + reserved0: u16_at(2), + reserved1: u32_at(4), + ta_prior_cdm: u64_at(8), + ta_vdm_barrier: u16_at(16), + reserved2: u16_at(18), + reserved3: u32_at(20), + ta_prior_vdm: u64_at(24), + }) +} + +/// Decodes a render command. With `DRM_ASAHI_RENDER_STAGE_PREFIXES`, the payload must be +/// the exact 480-byte `drm_asahi_cmd_render_m5` with zero reserved fields and without +/// `DRM_ASAHI_RENDER_FRAGMENT_BARRIERS`. Without the flag, any trailing bytes must be zero. +fn render_payload( + bytes: &[u8], +) -> Result<( + uapi::drm_asahi_cmd_render, + Option, +)> { + let head_len = bytes.len().min(RENDER_STAGE_PREFIXES_OFF); + let cmd: uapi::drm_asahi_cmd_render = Reader::new(&bytes[..head_len]).read_up_to(head_len)?; + let tail = bytes.get(RENDER_STAGE_PREFIXES_OFF..).unwrap_or(&[]); + if cmd.flags & STAGE_PREFIXES != 0 { + if bytes.len() != RENDER_M5_SIZE || cmd.flags & FRAGMENT_BARRIERS != 0 { + return Err(EINVAL); + } + let prefixes = decode_stage_prefixes(tail)?; + if prefixes.reserved0 != 0 + || prefixes.reserved1 != 0 + || prefixes.reserved2 != 0 + || prefixes.reserved3 != 0 + { + return Err(EINVAL); + } + Ok((cmd, Some(prefixes))) + } else { + if tail.iter().any(|&byte| byte != 0) { + return Err(EINVAL); + } + Ok((cmd, None)) + } +} + +/// Render payload bytes before the ray-query stages: they follow the historical prefixes. +const RAY_QUERY_START: usize = offset_of!(uapi::drm_asahi_cmd_render, prior_cdm) + size_of::(); + +/// The ray-query stages of a render payload; a shorter payload reads both stages zeroed. +/// Bounded by [`RENDER_STAGE_PREFIXES_OFF`] so 480-byte `STAGE_PREFIXES` tails stay separate. +fn render_ray_query(bytes: &[u8]) -> Result<[super::rt::RayQueryStage; 2]> { + let rq_end = bytes.len().min(RENDER_STAGE_PREFIXES_OFF); + super::rt::RayQueryStage::parse_pair(bytes.get(RAY_QUERY_START..rq_end).unwrap_or(&[])) +} + +/// The scratch layout and intersection tables of a compute command. The M5 auxiliary +/// allocation and the reserved word stay MBZ. +fn compute_ray(cmd: &uapi::drm_asahi_cmd_compute) -> Result { + super::rt::ComputeRay::new( + cmd.scs_layout, + cmd.cdm_auxiliary_allocation, + cmd.reserved, + cmd.intersection_pool, + cmd.intersection_pool_bytes, + cmd.intersection_first, + cmd.intersection_count, + cmd.intersection_default_program, + cmd.intersection_default_control, + ) +} + /// Whether `[start, start + size)` is a nonempty range inside `range`. fn inside(start: u64, size: u64, range: &Range) -> bool { size != 0 && start >= range.start && start < range.end && size <= range.end - start @@ -260,145 +565,157 @@ fn check_render_helpers(cmd: &uapi::drm_asahi_cmd_render) -> Result { /// Reject geometry which cannot fit any retained pass before a submission is accepted. /// The encoder owns the sizing formula; admission and publication use the same calculation. -fn check_geometry(cmd: &uapi::drm_asahi_cmd_render) -> Result { - super::encode::Geometry::new(cmd, 0) +fn check_geometry( + cmd: &uapi::drm_asahi_cmd_render, + num_clusters: u32, + gpu_generation: u32, +) -> Result { + super::encode::Geometry::new_for(cmd, 0, num_clusters, gpu_generation) .validate_capacity(hw::client::TPC_SIZE, hw::client::TILEMAP_SIZE) } -/// Structural validation of a whole command stream, before anything is looked up. -pub(crate) fn check_stream(bytes: &[u8], early_tiling: bool) -> Result { - if bytes.is_empty() || bytes.len() > MAX_CMDBUF || bytes.len() % 8 != 0 { +fn render_allowed_flags(early_tiling: bool, gpu_generation: u32) -> u32 { + let gen_flags = if gpu_generation >= 16 { + FEW_PRIMITIVES + } else { + NO_VERTEX_CLUSTERING + }; + PROCESS_EMPTY_TILES + | DBIAS_IS_INT + | RSRC_SPEC_HI + | gen_flags + | if early_tiling { + FRAGMENT_BARRIERS | STAGE_PREFIXES + } else { + 0 + } +} + +fn validate_attachments_header(entry: &Entry<'_>) -> Result { + if entry.barriers != [NONE; 2] + || entry.payload.len() % ATTACHMENT_SIZE != 0 + || entry.payload.len() / ATTACHMENT_SIZE > hw::sizes::MAX_ATTACHMENTS + { return Err(EINVAL); } - let range = hw::USER_RANGE; - let mut counts = [0u32; 2]; - for entry in stream(bytes) { - let entry = entry?; - match entry.kind { - SET_VERTEX_ATTACHMENTS | SET_FRAGMENT_ATTACHMENTS | SET_COMPUTE_ATTACHMENTS => { - if entry.barriers != [NONE; 2] - || entry.payload.len() % ATTACHMENT_SIZE != 0 - || entry.payload.len() / ATTACHMENT_SIZE > hw::sizes::MAX_ATTACHMENTS - { - return Err(EINVAL); - } - for bytes in entry.payload.chunks_exact(ATTACHMENT_SIZE) { - let attachment: uapi::drm_asahi_attachment = Reader::new(bytes).read()?; - if attachment.pad != 0 - || attachment.flags != 0 - || !inside(attachment.pointer, attachment.size, &range) - { - return Err(EINVAL); - } - } - continue; - } - _ => {} - } - if (entry.barriers[RENDER] != NONE && u32::from(entry.barriers[RENDER]) > counts[RENDER]) - || (entry.barriers[COMPUTE] != NONE - && u32::from(entry.barriers[COMPUTE]) > counts[COMPUTE]) + Ok(()) +} + +fn validate_attachment(attachment: &uapi::drm_asahi_attachment, range: &Range) -> Result { + if attachment.pad != 0 + || attachment.flags != 0 + || !inside(attachment.pointer, attachment.size, range) + { + return Err(EINVAL); + } + Ok(()) +} + +fn validate_render_entry( + entry: &Entry<'_>, + counts: [u32; 2], + early_tiling: bool, + num_clusters: u32, + gpu_generation: u32, +) -> Result<( + uapi::drm_asahi_cmd_render, + Option, + [super::rt::RayQueryStage; 2], +)> { + let (packet, prefixes) = render_payload(entry.payload)?; + let cmd = &packet; + // The ray-query stages after the historical prefixes (RENDER_RAY_QUERY, G16+ only). + let ray_query = render_ray_query(entry.payload)?; + if gpu_generation < 16 + && ray_query + .iter() + .any(|stage| stage.intersection.enabled() || stage.scratch.enabled()) + { + return Err(EINVAL); + } + if let Some(prefixes) = prefixes { + if (prefixes.ta_vdm_barrier != NONE && u32::from(prefixes.ta_vdm_barrier) > counts[RENDER]) + || (prefixes.ta_cdm_barrier != NONE + && u32::from(prefixes.ta_cdm_barrier) > counts[COMPUTE]) { return Err(EINVAL); } - match entry.kind { - CMD_RENDER => { - let packet: uapi::drm_asahi_cmd_render = payload(entry.payload)?; - let cmd = &packet; - // Ray-query extensions belong to G17; reject every nonzero byte - // beyond the common historical-prefix fields on G16. - let end = offset_of!(uapi::drm_asahi_cmd_render, prior_cdm) + size_of::(); - if entry.payload.get(end..).is_some_and(|tail| tail.iter().any(|&b| b != 0)) { - return Err(EINVAL); - } - check_render_helpers(cmd)?; - // M4 HAL200 resource words carry all four high halves. - let allowed = PROCESS_EMPTY_TILES - | DBIAS_IS_INT - | RSRC_SPEC_HI - | if early_tiling { FRAGMENT_BARRIERS } else { 0 }; - if cmd.flags & !allowed != 0 - || !(1..=MAX_DIMENSION).contains(&cmd.width_px) - || !(1..=MAX_DIMENSION).contains(&cmd.height_px) - || !(1..=MAX_LAYERS).contains(&cmd.layers) - || !matches!(cmd.samples, 1 | 2 | 4) - { - return Err(EINVAL); - } - check_geometry(cmd)?; - // Timestamp copies are reserved for another runtime. No copy - // feature is advertised, and zero handles do not waive MBZ offsets. - if cmd - .ts_frag_end_copies - .iter() - .any(|ts| ts.handle != 0 || ts.offset != 0) - { - return Err(EINVAL); - } - // `payload` rejects nonzero ray-query bytes beyond the prior - // extension. RENDER_RAY_QUERY is never advertised on G16. - // Never discard unflagged high words, nor accept the flag without them. - if cmd.flags & RSRC_SPEC_HI != 0 && entry.payload.len() < RSRC_SPEC_HI_MIN { - return Err(EINVAL); - } - if cmd.flags & RSRC_SPEC_HI == 0 - && (cmd.bg_eot_rsrc_spec_hi != 0 - || cmd.bg_eot_partial_rsrc_spec_hi != 0 - || cmd.bg_rsrc_spec_hi != 0 - || cmd.bg_partial_rsrc_spec_hi != 0) - { - return Err(EINVAL); - } - counts[RENDER] += 1; - } - CMD_COMPUTE => { - let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; - let cmd = &packet; - if cmd.flags != 0 - || cmd.cdm_ctrl_stream_end <= cmd.cdm_ctrl_stream_base - || !inside( - cmd.cdm_ctrl_stream_base, - cmd.cdm_ctrl_stream_end - cmd.cdm_ctrl_stream_base, - &range, - ) - { - return Err(EINVAL); - } - // The G17P scratch layout and intersection tables: never on G16. - if cmd - .ts_end_copies - .iter() - .any(|ts| ts.handle != 0 || ts.offset != 0) - || packet.scs_layout != 0 - || packet.cdm_auxiliary_allocation != 0 - || packet.reserved != 0 - || packet.intersection_pool != 0 - || packet.intersection_pool_bytes != 0 - || packet.intersection_first != 0 - || packet.intersection_count != 0 - || packet.intersection_default_program != 0 - || packet.intersection_default_control != 0 - { - return Err(EINVAL); - } - counts[COMPUTE] += 1; - } - _ => return Err(EINVAL), - } - if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { - return Err(EINVAL); - } } - if counts == [0; 2] { + check_render_helpers(cmd)?; + let allowed = render_allowed_flags(early_tiling, gpu_generation); + if cmd.flags & !allowed != 0 + || !(1..=MAX_DIMENSION).contains(&cmd.width_px) + || !(1..=MAX_DIMENSION).contains(&cmd.height_px) + || !(1..=MAX_LAYERS).contains(&cmd.layers) + || !matches!(cmd.samples, 1 | 2 | 4) + { return Err(EINVAL); } - Ok(()) + check_geometry(cmd, num_clusters, gpu_generation)?; + // Timestamp copies are reserved for another runtime. No copy + // feature is advertised, and zero handles do not waive MBZ offsets. + if cmd + .ts_frag_end_copies + .iter() + .any(|ts| ts.handle != 0 || ts.offset != 0) + { + return Err(EINVAL); + } + // Never discard unflagged high words, nor accept the flag without them. + if cmd.flags & RSRC_SPEC_HI != 0 && entry.payload.len() < RSRC_SPEC_HI_MIN { + return Err(EINVAL); + } + if cmd.flags & RSRC_SPEC_HI == 0 + && (cmd.bg_eot_rsrc_spec_hi != 0 + || cmd.bg_eot_partial_rsrc_spec_hi != 0 + || cmd.bg_rsrc_spec_hi != 0 + || cmd.bg_partial_rsrc_spec_hi != 0) + { + return Err(EINVAL); + } + Ok((packet, prefixes, ray_query)) } -/// Checks that `[start, end)` (rounded out to pages) is user memory mapped with the requested -/// GPU access: a driver range ENOENT, outside the user range EINVAL, an unmapped page ENOENT, a -/// page without the access EACCES. -pub(crate) fn cover(vm: &mmu::Vm, start: u64, end: u64, read: bool, write: bool) -> Result { +fn validate_compute_entry( + entry: &Entry<'_>, + range: &Range, + gpu_generation: u32, +) -> Result<(uapi::drm_asahi_cmd_compute, super::rt::ComputeRay, bool)> { + let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; + let cmd = &packet; + let Some(as_build) = super::rt::as_build(cmd.flags & !COMPUTE_NO_QUERY_ACCESS) else { + return Err(EINVAL); + }; + if gpu_generation < 16 && as_build { + return Err(EINVAL); + } + if cmd.cdm_ctrl_stream_end <= cmd.cdm_ctrl_stream_base + || !inside( + cmd.cdm_ctrl_stream_base, + cmd.cdm_ctrl_stream_end - cmd.cdm_ctrl_stream_base, + range, + ) + { + return Err(EINVAL); + } + if cmd + .ts_end_copies + .iter() + .any(|ts| ts.handle != 0 || ts.offset != 0) + { + return Err(EINVAL); + } + // The G17P scratch layout and intersection tables (RENDER_RAY_QUERY, G16+ only). + let ray = compute_ray(cmd)?; + if gpu_generation < 16 && (ray.intersection.enabled() || ray.scratch.enabled()) { + return Err(EINVAL); + } + Ok((packet, ray, as_build)) +} + +/// Checks that `[start, end)` (rounded out to pages) lies inside the user address range and +/// outside every driver-reserved range, returning `(first_page, byte_size)`. +fn align_span(start: u64, end: u64) -> Result<(u64, u64)> { let mask = mmu::UAT_PGMSK as u64; if end <= start { return Err(EINVAL); @@ -418,17 +735,348 @@ pub(crate) fn cover(vm: &mmu::Vm, start: u64, end: u64, read: bool, write: bool) if first < range.start || last > range.end { return Err(EINVAL); } - if vm.covers_range(first, last - first, read, write) { + Ok((first, last - first)) +} + +/// Maximum page-aligned GPUVM spans retained in one logical queue's validation cache. +const MAX_PROOF_RANGES: usize = 128; + +/// Bounded cache of validated page-aligned GPUVM spans and permissions. +struct ProofCache { + epoch: Option, + ranges: [(u64, u64, u8); MAX_PROOF_RANGES], + count: usize, + overflow: bool, +} + +impl ProofCache { + const fn new() -> Self { + Self { + epoch: None, + ranges: [(0, 0, 0); MAX_PROOF_RANGES], + count: 0, + overflow: false, + } + } + + fn contains(outer: (u64, u64, u8), inner: (u64, u64, u8)) -> bool { + outer.2 & inner.2 == inner.2 + && inner.0 >= outer.0 + && inner.0.checked_add(inner.1).is_some_and(|end| { + outer + .0 + .checked_add(outer.1) + .is_some_and(|limit| end <= limit) + }) + } + + fn invalidate(&mut self) { + self.epoch = None; + self.count = 0; + self.overflow = false; + } + + fn covers_entry(&self, req: (u64, u64, u8)) -> bool { + self.ranges[..self.count] + .iter() + .any(|&range| Self::contains(range, req)) + } + + fn covers_aligned(&self, epoch: Option, first: u64, size: u64, access: u8) -> bool { + self.epoch.is_some() && self.epoch == epoch && self.covers_entry((first, size, access)) + } + + fn insert_entry(&mut self, mut req: (u64, u64, u8)) { + if req.1 == 0 || req.2 == 0 || req.2 & !3 != 0 { + return; + } + if self.covers_entry(req) { + return; + } + // Merge only equal permissions so an adjacent writable span never widens a read-only + // span. Restart after each merge because the widened range may join an earlier entry. + let mut index = 0; + while index < self.count { + let range = self.ranges[index]; + let end = req.0.saturating_add(req.1); + let other_end = range.0.saturating_add(range.1); + if Self::contains(req, range) + || (req.2 == range.2 && req.0 <= other_end && range.0 <= end) + { + if req.2 == range.2 { + let start = req.0.min(range.0); + req = (start, end.max(other_end) - start, req.2); + } + self.count -= 1; + self.ranges[index] = self.ranges[self.count]; + index = 0; + } else { + index += 1; + } + } + if self.count == self.ranges.len() { + self.overflow = true; + return; + } + self.ranges[self.count] = req; + self.count += 1; + } + + fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { + if epoch.is_none() { + self.invalidate(); + return; + } + if self.epoch != epoch || self.overflow { + self.epoch = epoch; + self.count = 0; + self.overflow = false; + } + self.insert_entry((first, size, access)); + } + + fn record_slice(&mut self, epoch: Option, ranges: &[(u64, u64, u8)]) { + if epoch.is_none() { + self.invalidate(); + return; + } + if self.epoch == epoch && !self.overflow { + for &req in ranges { + self.insert_entry(req); + } + if !self.overflow { + return; + } + } + self.epoch = epoch; + self.count = 0; + self.overflow = false; + for &req in ranges { + self.insert_entry(req); + } + } +} + +/// Heap-resident validation scratch paired with [`ProofCache`] so `Prepared::validate` never +/// stages kilobytes of span/command arrays on the kernel stack. +struct ValidateScratch { + batch: SpanBatch, + missing: [(u64, u64, u8); 48], + vdm_vas: [u64; MAX_COMMANDS as usize], + cdm_ranges: [(u64, u64); MAX_COMMANDS as usize], +} + +impl ValidateScratch { + const fn new() -> Self { + Self { + batch: SpanBatch::new(), + missing: [(0, 0, 0); 48], + vdm_vas: [0; MAX_COMMANDS as usize], + cdm_ranges: [(0, 0); MAX_COMMANDS as usize], + } + } +} + +/// One logical queue's bounded cache of validated page-aligned GPUVM spans and permissions, +/// together with reusable scratch buffers for `Prepared::validate`. +/// Mapping mutations invalidate or hide the VM's validation epoch so stale proofs are never +/// reused across unmaps or remaps. +pub(crate) struct SpanProof { + cache: ProofCache, + scratch: ValidateScratch, +} + +impl SpanProof { + #[allow(dead_code)] + pub(crate) const fn new() -> Self { + Self { + cache: ProofCache::new(), + scratch: ValidateScratch::new(), + } + } + + pub(crate) fn invalidate(&mut self) { + self.cache.invalidate(); + } + + pub(crate) fn covers_aligned( + &self, + epoch: Option, + first: u64, + size: u64, + access: u8, + ) -> bool { + self.cache.covers_aligned(epoch, first, size, access) + } + + pub(crate) fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { + self.cache.record_one(epoch, first, size, access); + } +} + +/// Batches page-aligned GPUVM coverage checks under one `gpuvm.lock_inner()` hold while +/// preserving exact per-span `ENOENT` / `EACCES` / `EINVAL` error reporting on failure. +struct SpanBatch { + ranges: [(u64, u64, u8); 48], + len: usize, +} + +impl SpanBatch { + const fn new() -> Self { + Self { + ranges: [(0, 0, 0); 48], + len: 0, + } + } + + fn push(&mut self, vm: &mmu::Vm, start: u64, end: u64, read: bool, write: bool) -> Result { + let (first, size) = align_span(start, end)?; + let access = u8::from(read) | (u8::from(write) << 1); + if self.ranges[..self.len] + .iter() + .any(|&(a, s, acc)| a == first && s == size && (acc & access) == access) + { + return Ok(()); + } + if self.len == self.ranges.len() { + self.flush(vm)?; + } + self.ranges[self.len] = (first, size, access); + self.len += 1; + Ok(()) + } + + fn report_failure(vm: &mmu::Vm, ranges: &[(u64, u64, u8)]) -> Result { + for &(first, size, access) in ranges { + let read = access & 1 != 0; + let write = access & 2 != 0; + if !vm.covers_range(first, size, read, write) { + return if vm.covers_range(first, size, false, false) { + Err(EACCES) + } else { + Err(ENOENT) + }; + } + } + Ok(()) + } + + fn flush(&mut self, vm: &mmu::Vm) -> Result { + let n = self.len; + if n == 0 { + return Ok(()); + } + self.len = 0; + if vm.covers_ranges_batch(&self.ranges[..n]).0 { + return Ok(()); + } + Self::report_failure(vm, &self.ranges[..n]) + } + + fn clear(&mut self) { + self.len = 0; + } + + fn flush_with_proof_parts( + &mut self, + vm: &mmu::Vm, + cache: &mut ProofCache, + missing: &mut [(u64, u64, u8); 48], + ) -> Result { + let n = self.len; + if n == 0 { + return Ok(()); + } + self.len = 0; + let epoch = vm.mapping_validation_epoch(); + if cache.epoch.is_some() && cache.epoch == epoch { + let mut missing_len = 0usize; + for &req in &self.ranges[..n] { + if !cache.covers_entry(req) { + missing[missing_len] = req; + missing_len += 1; + } + } + if missing_len == 0 { + return Ok(()); + } + let (mut covered, mut walked) = vm.covers_ranges_batch(&missing[..missing_len]); + if covered && walked != cache.epoch { + (covered, walked) = vm.covers_ranges_batch(&self.ranges[..n]); + } + if covered { + cache.record_slice(walked, &self.ranges[..n]); + return Ok(()); + } + cache.invalidate(); + return Self::report_failure(vm, &self.ranges[..n]); + } + let (covered, walked) = vm.covers_ranges_batch(&self.ranges[..n]); + if covered { + cache.record_slice(walked, &self.ranges[..n]); + return Ok(()); + } + cache.invalidate(); + Self::report_failure(vm, &self.ranges[..n]) + } + + #[allow(dead_code)] + fn flush_with_proof(&mut self, vm: &mmu::Vm, proof: &mut SpanProof) -> Result { + self.flush_with_proof_parts(vm, &mut proof.cache, &mut proof.scratch.missing) + } + + fn flush_locked_with_cache( + &mut self, + guard: &mut mmu::VmReadGuard<'_>, + epoch: Option, + cache: &mut ProofCache, + ) -> Result { + let n = self.len; + if n == 0 { + return Ok(()); + } + self.len = 0; + let mut had_miss = false; + for &(first, size, access) in &self.ranges[..n] { + if cache.covers_aligned(epoch, first, size, access) { + continue; + } + had_miss = true; + let read = access & 1 != 0; + let write = access & 2 != 0; + if !guard.covers_range(first, size, read, write) { + cache.invalidate(); + return if guard.covers_range(first, size, false, false) { + Err(EACCES) + } else { + Err(ENOENT) + }; + } + } + if had_miss { + cache.record_slice(epoch, &self.ranges[..n]); + } Ok(()) - } else if vm.covers_range(first, last - first, false, false) { - Err(EACCES) - } else { - Err(ENOENT) + } + + #[allow(dead_code)] + fn flush_locked_with_proof( + &mut self, + guard: &mut mmu::VmReadGuard<'_>, + epoch: Option, + proof: &mut SpanProof, + ) -> Result { + self.flush_locked_with_cache(guard, epoch, &mut proof.cache) } } /// Attachment spans, 128-byte granular, actually mapped with `write` or read access. -fn check_attachments(vm: &mmu::Vm, list: &[uapi::drm_asahi_attachment], write: bool) -> Result { +fn check_attachments( + batch: &mut SpanBatch, + vm: &mmu::Vm, + list: &[uapi::drm_asahi_attachment], + write: bool, +) -> Result { for attachment in list { let end = attachment .pointer @@ -442,16 +1090,21 @@ fn check_attachments(vm: &mmu::Vm, list: &[uapi::drm_asahi_attachment], write: b if (last - first) / 128 > u64::from(u32::MAX) { return Err(EINVAL); } - cover(vm, first, last, true, write)?; + batch.push(vm, first, last, true, write)?; } Ok(()) } -/// Parses the attachment list of a SET_*_ATTACHMENTS command. -fn attachment_list(bytes: &[u8]) -> Result> { +/// Parses the attachment list of a SET_*_ATTACHMENTS command, validating every entry in one pass. +fn attachment_list_checked( + bytes: &[u8], + range: &Range, +) -> Result> { let mut list = KVec::with_capacity(bytes.len() / ATTACHMENT_SIZE, GFP_KERNEL)?; for bytes in bytes.chunks_exact(ATTACHMENT_SIZE) { - list.push(Reader::new(bytes).read()?, GFP_KERNEL)?; + let attachment: uapi::drm_asahi_attachment = Reader::new(bytes).read()?; + validate_attachment(&attachment, range)?; + list.push(attachment, GFP_KERNEL)?; } Ok(list) } @@ -466,32 +1119,84 @@ fn copy_list(lists: &[&[uapi::drm_asahi_attachment]]) -> Result, + epoch: Option, + mut proof: Option<&mut SpanProof>, + start: u64, + end: u64, + read: bool, + write: bool, +) -> Result { + let (first, size) = align_span(start, end)?; + let access = u8::from(read) | (u8::from(write) << 1); + if proof + .as_deref() + .is_some_and(|cache| cache.covers_aligned(epoch, first, size, access)) + { + return Ok(()); + } + if guard.covers_range(first, size, read, write) { + if let Some(cache) = proof.as_deref_mut() { + cache.record_one(epoch, first, size, access); + } + Ok(()) + } else { + if let Some(cache) = proof.as_deref_mut() { + cache.invalidate(); + } + if guard.covers_range(first, size, false, false) { + Err(EACCES) + } else { + Err(ENOENT) + } + } +} + /// Whether a GVA can be named by a 32-bit compact pointer. fn compact(gva: u64) -> bool { (0x1000000000..0x9000000000).contains(&gva) } -/// Validate uncompressed Z/S register state and coverage through each layer base. -/// This is a minimum span check, not a complete plane-extent validation: the UAPI -/// does not describe the complete ZLS surface layout. The encoded stride is a -/// register word, not a byte distance (the C HAL200 contract). +/// Validate Z/S register state (including compressed metadata) and coverage through each layer +/// base. This is a minimum span check, not a complete plane-extent validation: the UAPI does +/// not describe the complete ZLS surface layout. The encoded stride is a register word, not a +/// byte distance (the C HAL200 contract). fn check_zls_plane( + batch: &mut SpanBatch, context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render, stencil: bool, ) -> Result { - let (z, mask) = if stencil { - (&cmd.stencil, (1u64 << 3) | (1 << 7) | (1 << 14) | (1 << 18)) + let (z, mask, comp_mask) = if stencil { + ( + &cmd.stencil, + (1u64 << 3) | (1 << 4) | (1 << 7) | (1 << 8) | (1 << 14) | (1 << 18), + (1u64 << 4) | (1 << 8), + ) } else { ( &cmd.depth, - (1u64 << 1) | (1 << 5) | (1 << 15) | (1 << 19) | (3 << 25), + (1u64 << 1) | (1 << 2) | (1 << 5) | (1 << 6) | (1 << 15) | (1 << 19) | (3 << 25), + (1u64 << 2) | (1 << 6), ) }; - if (z.base == 0 && (z.stride != 0 || cmd.zls_ctrl & mask != 0)) + let compressed = cmd.zls_ctrl & comp_mask != 0; + if (z.base == 0 + && (z.stride != 0 + || z.comp_base != 0 + || z.comp_stride != 0 + || cmd.zls_ctrl & mask != 0)) || (z.base != 0 && cmd.layers > 1 && z.stride == 0) || (z.stride != 0 && z.stride & 0x3fff != 1) || z.base & 3 != 0 + || (z.comp_base == 0 && z.comp_stride != 0) + || (z.comp_base != 0) != compressed + || z.comp_base & 3 != 0 + || z.comp_stride & 0x3fff != 0 { return Err(EINVAL); } @@ -501,7 +1206,7 @@ fn check_zls_plane( .checked_mul(u64::from(cmd.layers - 1)) .and_then(|bytes| bytes.checked_add(1)) .ok_or(EINVAL)?; - cover( + batch.push( context.vm, z.base, z.base.checked_add(minimum).ok_or(EINVAL)?, @@ -509,6 +1214,20 @@ fn check_zls_plane( true, )?; } + if z.comp_base != 0 { + let distance = (u64::from(z.comp_stride >> 14) + 1) * ZLS_METADATA_STRIDE; + let minimum = distance + .checked_mul(u64::from(cmd.layers - 1)) + .and_then(|bytes| bytes.checked_add(1)) + .ok_or(EINVAL)?; + batch.push( + context.vm, + z.comp_base, + z.comp_base.checked_add(minimum).ok_or(EINVAL)?, + true, + true, + )?; + } if cmd.depth.base == 0 && cmd.stencil.base == 0 && (cmd.zls_ctrl != 0 || cmd.isp_zls_pixels != 0) @@ -518,15 +1237,38 @@ fn check_zls_plane( Ok(()) } -/// Per-command render admission. -fn check_render(context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Result { +/// Per-command render admission. Pushes VM spans into `batch` so a multi-pass SUBMIT flushes +/// coverage once across all passes. +fn check_render( + batch: &mut SpanBatch, + context: &Context<'_>, + cmd: &uapi::drm_asahi_cmd_render, + vertex: &[uapi::drm_asahi_attachment], + fragment: &[uapi::drm_asahi_attachment], +) -> Result { + check_render_for(batch, context, cmd, vertex, fragment, 16) +} + +fn check_render_for( + batch: &mut SpanBatch, + context: &Context<'_>, + cmd: &uapi::drm_asahi_cmd_render, + vertex: &[uapi::drm_asahi_attachment], + fragment: &[uapi::drm_asahi_attachment], + gpu_generation: u32, +) -> Result { check_render_helpers(cmd)?; let vm = context.vm; let allowed = PROCESS_EMPTY_TILES | RSRC_SPEC_HI | DBIAS_IS_INT + | if gpu_generation >= 16 { + FEW_PRIMITIVES + } else { + uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_NO_VERTEX_CLUSTERING + } | if super::params::early_tiling() { - FRAGMENT_BARRIERS + FRAGMENT_BARRIERS | STAGE_PREFIXES } else { 0 }; @@ -541,34 +1283,28 @@ fn check_render(context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Resu || !matches!(cmd.samples, 1 | 2 | 4) || !matches!(cmd.utile_width_px, 16 | 32) || !matches!(cmd.utile_height_px, 16 | 32) - || tile_buffer > MAX_TILE_BUFFER + || tile_buffer > context.max_tile_buffer || cmd.sampler_heap != 0 || cmd.sampler_count != 0 || cmd.ppp_ctrl & !0x203 != 0 - || cmd.zls_ctrl & !0x00000000060cc0aa != 0 + || cmd.zls_ctrl & !0x00000000060cc1fe != 0 || cmd.isp_zls_pixels & 0xc0000000 != 0 || !matches!((cmd.zls_ctrl >> 25) & 3, 0 | 2) || ((cmd.zls_ctrl >> 1) & 1) != ((cmd.zls_ctrl >> 5) & 1) + || ((cmd.zls_ctrl >> 2) & 1) != ((cmd.zls_ctrl >> 6) & 1) || ((cmd.zls_ctrl >> 3) & 1) != ((cmd.zls_ctrl >> 7) & 1) + || ((cmd.zls_ctrl >> 4) & 1) != ((cmd.zls_ctrl >> 8) & 1) { return Err(EINVAL); } - if cmd.stencil.comp_base != 0 - || cmd.stencil.comp_stride != 0 - || cmd.depth.comp_base != 0 - || cmd.depth.comp_stride != 0 - { - return Err(Error::from_errno(-(kernel::bindings::EOPNOTSUPP as i32))); - } // VDM: compact-addressable and readable; scissor: four-byte aligned. let vdm = cmd.vdm_ctrl_stream_base; let scissor = cmd.isp_scissor_base; if vdm & 3 != 0 || !compact(vdm) || scissor == 0 || scissor & 3 != 0 { return Err(EINVAL); } - cover(vm, vdm, vdm + 4, true, false)?; - gate::vdm(vm, vdm)?; - cover( + batch.push(vm, vdm, vdm + 4, true, false)?; + batch.push( vm, scissor, scissor.checked_add(4).ok_or(EINVAL)?, @@ -580,7 +1316,7 @@ fn check_render(context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Resu if base & 3 != 0 { return Err(EINVAL); } - cover(vm, base, base.checked_add(4).ok_or(EINVAL)?, true, false)?; + batch.push(vm, base, base.checked_add(4).ok_or(EINVAL)?, true, false)?; } else if cmd.flags & DBIAS_IS_INT != 0 { return Err(EINVAL); } @@ -589,7 +1325,7 @@ fn check_render(context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Resu return Err(EINVAL); } let base = cmd.isp_oclqry_base; - cover(vm, base, base.checked_add(8).ok_or(EINVAL)?, true, true)?; + batch.push(vm, base, base.checked_add(8).ok_or(EINVAL)?, true, true)?; } for program in [&cmd.bg, &cmd.eot, &cmd.partial_bg, &cmd.partial_eot] { if program.usc == 0 { @@ -599,7 +1335,7 @@ fn check_render(context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Resu .usc_base .checked_add(u64::from(program.usc & !63)) .ok_or(EINVAL)?; - cover( + batch.push( vm, address, address.checked_add(64).ok_or(EINVAL)?, @@ -607,20 +1343,85 @@ fn check_render(context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Resu false, )?; } - check_zls_plane(context, cmd, false)?; - check_zls_plane(context, cmd, true)?; + check_zls_plane(batch, context, cmd, false)?; + check_zls_plane(batch, context, cmd, true)?; + check_attachments(batch, vm, vertex, true)?; + check_attachments(batch, vm, fragment, true)?; Ok(()) } +/// The hardware reads the intersection pool and the default intersection program: both must +/// be mapped readable, as on the M4 Pro. +fn check_intersection( + batch: &mut SpanBatch, + vm: &mmu::Vm, + tables: &super::rt::IntersectionTables, +) -> Result { + if !tables.enabled() { + return Ok(()); + } + let end = tables.pool.checked_add(tables.pool_bytes).ok_or(EINVAL)?; + batch.push(vm, tables.pool, end, true, false)?; + let code = tables.default_code(); + if code != 0 { + batch.push(vm, code, code.checked_add(64).ok_or(EINVAL)?, true, false)?; + } + Ok(()) +} + +/// Per-command render ray-query admission. A render's scratch must fit what its queue +/// reserved (`render_scs_layout`): the render's UMA pool was sized for that (EINVAL beyond it, +/// as on the M4 Pro). Returns the SCS-capable pool the render runs on, sized for the +/// reservation ([`super::rt::pool_seeds`]). +fn check_render_ray( + batch: &mut SpanBatch, + context: &Context<'_>, + stages: &[super::rt::RayQueryStage; 2], +) -> Result { + for stage in stages { + check_intersection(batch, context.vm, &stage.intersection)?; + } + if !stages.iter().any(|stage| stage.scratch.enabled()) { + return Ok(super::rt::ScsSeeds::NONE); + } + let pages = stages.map(|stage| stage.scratch.pages()); + let needed = super::rt::required_seeds(context.active_cores, &pages)?; + let reserved = super::rt::required_seeds(context.active_cores, &context.render_scs)?; + if needed > reserved { + return Err(EINVAL); + } + let pool = super::rt::pool_seeds(context.active_cores, context.render_scs)?; + Ok(super::rt::ScsSeeds { needed, pool }) +} + +/// Per-command compute ray admission: the tables are mapped and the scratch fits an +/// SCS-capable UMA pool (E2BIG). Returns the SCS-capable pool the command runs on. +fn check_compute_ray( + batch: &mut SpanBatch, + context: &Context<'_>, + ray: &super::rt::ComputeRay, +) -> Result { + check_intersection(batch, context.vm, &ray.intersection)?; + if !ray.scratch.enabled() { + return Ok(super::rt::ScsSeeds::NONE); + } + let pages = ray.scratch.pages(); + Ok(super::rt::ScsSeeds { + needed: super::rt::required_seeds(context.active_cores, &[pages])?, + pool: super::rt::pool_seeds(context.active_cores, [pages, 0])?, + }) +} + /// Per-command compute admission. fn check_compute( + batch: &mut SpanBatch, context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_compute, attachments: &[uapi::drm_asahi_attachment], -) -> Result { +) -> Result<(u64, u64)> { let vm = context.vm; let (base, end) = (cmd.cdm_ctrl_stream_base, cmd.cdm_ctrl_stream_end); - if cmd.flags != 0 + if super::rt::as_build(cmd.flags & !COMPUTE_NO_QUERY_ACCESS).is_none() || cmd.sampler_count != 0 || cmd.sampler_heap != 0 || !helper_is_empty(&cmd.helper) @@ -631,135 +1432,414 @@ fn check_compute( { return Err(EINVAL); } - cover(vm, base, end, true, false)?; - gate::cdm(vm, context.usc_base, base, end)?; - check_attachments(vm, attachments, true) + batch.push(vm, base, end, true, false)?; + check_attachments(batch, vm, attachments, true)?; + Ok((base, end)) } -/// Resolves timestamps and exact historical-prefix dependencies of a valid stream -/// ([`check_stream`]) for a queue that accepted `accepted` render and compute commands before -/// this ioctl. -pub(crate) fn prepare<'a>( - bytes: &'a [u8], - accepted: [u64; 2], - objects: Pin<&xarray::XArray>>, -) -> Result> { - let mut resolved = KVec::new(); - for entry in stream(bytes) { - let entry = entry?; - let outputs = match entry.kind { - CMD_RENDER => { - let packet: uapi::drm_asahi_cmd_render = payload(entry.payload)?; - let cmd = &packet; - crate::timestamp::Destinations::resolve_aligned( - objects, - &[cmd.ts_vtx, cmd.ts_frag], - )? - } - CMD_COMPUTE => { - let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; - let cmd = &packet; - crate::timestamp::Destinations::resolve_aligned(objects, &[cmd.ts])? +/// Per-command barrier and stage-prefix metadata captured during single-pass parsing. +#[derive(Copy, Clone)] +struct OrderMeta { + barriers: [u16; 2], + prefixes: Option, +} + +/// Inline storage for 1-2 command barrier metadata records, spilling to a heap `KVec` above 2. +enum OrderMetas { + Empty, + One([OrderMeta; 1]), + Two([OrderMeta; 2]), + Heap(KVec), +} + +impl OrderMetas { + fn new() -> Self { + Self::Empty + } + + fn push(&mut self, meta: OrderMeta) -> Result { + match self { + Self::Heap(vec) => vec.push(meta, GFP_KERNEL)?, + Self::Two([a, b]) => { + let (a, b) = (*a, *b); + let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; + let _ = vec.push_within_capacity(a); + let _ = vec.push_within_capacity(b); + let _ = vec.push_within_capacity(meta); + *self = Self::Heap(vec); } - _ => continue, - }; - resolved.push(outputs, GFP_KERNEL)?; + Self::One([a]) => *self = Self::Two([*a, meta]), + Self::Empty => *self = Self::One([meta]), + } + Ok(()) } +} + +impl core::ops::Deref for OrderMetas { + type Target = [OrderMeta]; + + fn deref(&self) -> &[OrderMeta] { + match self { + Self::Empty => &[], + Self::One(items) => items, + Self::Two(items) => items, + Self::Heap(vec) => vec, + } + } +} + +/// Tracks the active attachment list during single-pass parsing so the first consuming command +/// takes ownership without copying, while later commands sharing the same list clone from it. +enum AttachmentState { + Empty, + Fresh(KVec), + FromCommand(usize), +} + +/// A structurally valid, decoded command stream before timestamp/ordinal resolution and VM checks. +pub(crate) struct ParsedStream { + commands: Commands, + meta: OrderMetas, + counts: [u64; 2], + gpu_generation: u32, +} + +/// Structurally validates and decodes a command stream in a single pass, before anything is +/// looked up or device state is consulted. +pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result { + parse_stream_for(bytes, early_tiling, 1, 16) +} + +/// [`parse_stream`] parameterized by the GPU's cluster count and hardware generation. +pub(crate) fn parse_stream_for( + bytes: &[u8], + early_tiling: bool, + num_clusters: u32, + gpu_generation: u32, +) -> Result { + if bytes.is_empty() || bytes.len() > MAX_CMDBUF || bytes.len() % 8 != 0 { + return Err(EINVAL); + } + let range = hw::USER_RANGE; + let mut counts = [0u32; 2]; + let mut commands = Commands::new(); + let mut meta = OrderMetas::new(); + let mut vertex = AttachmentState::Empty; + let mut fragment = AttachmentState::Empty; + let mut compute = AttachmentState::Empty; - // Historical priors and header barriers. - let mut preceding = [0u16; 2]; - let mut orders = KVec::with_capacity(resolved.len(), GFP_KERNEL)?; for entry in stream(bytes) { let entry = entry?; - let (engine, prior) = match entry.kind { + match entry.kind { + SET_VERTEX_ATTACHMENTS | SET_FRAGMENT_ATTACHMENTS | SET_COMPUTE_ATTACHMENTS => { + validate_attachments_header(&entry)?; + let list = attachment_list_checked(entry.payload, &range)?; + let state = if list.is_empty() { + AttachmentState::Empty + } else { + AttachmentState::Fresh(list) + }; + match entry.kind { + SET_VERTEX_ATTACHMENTS => vertex = state, + SET_FRAGMENT_ATTACHMENTS => fragment = state, + SET_COMPUTE_ATTACHMENTS => compute = state, + _ => {} + } + continue; + } + _ => {} + } + if (entry.barriers[RENDER] != NONE && u32::from(entry.barriers[RENDER]) > counts[RENDER]) + || (entry.barriers[COMPUTE] != NONE + && u32::from(entry.barriers[COMPUTE]) > counts[COMPUTE]) + { + return Err(EINVAL); + } + let next_idx = commands.len(); + match entry.kind { CMD_RENDER => { - let packet: uapi::drm_asahi_cmd_render = payload(entry.payload)?; - (RENDER, [packet.prior_vdm, packet.prior_cdm]) + let (packet, prefixes, ray_query) = validate_render_entry( + &entry, + counts, + early_tiling, + num_clusters, + gpu_generation, + )?; + counts[RENDER] += 1; + if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { + return Err(EINVAL); + } + let take_render = |state: &mut AttachmentState, is_fragment: bool| { + match core::mem::replace(state, AttachmentState::Empty) { + AttachmentState::Empty => Ok(KVec::new()), + AttachmentState::Fresh(list) => { + *state = AttachmentState::FromCommand(next_idx); + Ok(list) + } + AttachmentState::FromCommand(prev_idx) => { + *state = AttachmentState::FromCommand(prev_idx); + match &commands[prev_idx] { + Command::Render(prev) => { + let src = if is_fragment { + &prev.fragment_attachments + } else { + &prev.vertex_attachments + }; + copy_list(&[src]) + } + Command::Compute(_) => Err(EINVAL), + } + } + } + }; + let vertex_attachments = take_render(&mut vertex, false)?; + let fragment_attachments = take_render(&mut fragment, true)?; + let heavy_ta = packet.layers > 1 + || super::encode::Geometry::new_for(&packet, 0, num_clusters, gpu_generation) + .tilemap_bytes + > hw::sizes::TA_LIGHT_TILEMAP_BYTES; + commands.push(Command::Render(KBox::new( + RenderCommand { + cmd: packet, + ray_query, + scs: super::rt::ScsSeeds::NONE, + timestamp_outputs: crate::timestamp::Destinations::empty(), + vertex_attachments, + fragment_attachments, + heavy_ta, + }, + GFP_KERNEL, + )?))?; + meta.push(OrderMeta { + barriers: entry.barriers, + prefixes, + })?; } CMD_COMPUTE => { - let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; - (COMPUTE, [packet.prior_vdm, packet.prior_cdm]) + let (packet, ray, as_build) = + validate_compute_entry(&entry, &range, gpu_generation)?; + counts[COMPUTE] += 1; + if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { + return Err(EINVAL); + } + let attachments = match core::mem::replace(&mut compute, AttachmentState::Empty) { + AttachmentState::Empty => KVec::new(), + AttachmentState::Fresh(list) => { + compute = AttachmentState::FromCommand(next_idx); + list + } + AttachmentState::FromCommand(prev_idx) => { + compute = AttachmentState::FromCommand(prev_idx); + match &commands[prev_idx] { + Command::Compute(prev) => copy_list(&[&prev.attachments])?, + Command::Render(_) => return Err(EINVAL), + } + } + }; + commands.push(Command::Compute(KBox::new( + ComputeCommand { + cmd: packet, + ray, + scs: super::rt::ScsSeeds::NONE, + as_build, + attachments, + timestamp_outputs: crate::timestamp::Destinations::empty(), + query_access: packet.flags & COMPUTE_NO_QUERY_ACCESS == 0, + }, + GFP_KERNEL, + )?))?; + meta.push(OrderMeta { + barriers: entry.barriers, + prefixes: None, + })?; } - _ => continue, - }; - orders.push( - Order::new(accepted, preceding, entry.barriers, prior, engine)?, - GFP_KERNEL, - )?; - preceding[engine] += 1; + _ => return Err(EINVAL), + } } - - Ok(Prepared { - bytes, - resolved, - orders, - counts: [u64::from(preceding[RENDER]), u64::from(preceding[COMPUTE])], + if counts == [0; 2] { + return Err(EINVAL); + } + Ok(ParsedStream { + commands, + meta, + counts: [u64::from(counts[RENDER]), u64::from(counts[COMPUTE])], + gpu_generation, }) } -impl Prepared<'_> { +impl ParsedStream { + /// Resolves timestamps in place and computes exact historical-prefix dependencies for a queue + /// that accepted `accepted` render and compute commands before this ioctl. + pub(crate) fn prepare( + mut self, + accepted: [u64; 2], + objects: Pin<&xarray::XArray>>, + ) -> Result { + let mut orders = Orders::new(); + let mut preceding = [0u16; 2]; + for (command, meta) in self.commands.iter_mut().zip(self.meta.iter()) { + let (engine, prior) = match command { + Command::Render(render) => { + render.timestamp_outputs = crate::timestamp::Destinations::resolve_aligned( + objects, + &[render.cmd.ts_vtx, render.cmd.ts_frag], + )?; + (RENDER, [render.cmd.prior_vdm, render.cmd.prior_cdm]) + } + Command::Compute(compute) => { + compute.timestamp_outputs = crate::timestamp::Destinations::resolve_aligned( + objects, + &[compute.cmd.ts], + )?; + (COMPUTE, [compute.cmd.prior_vdm, compute.cmd.prior_cdm]) + } + }; + let mut order = Order::new(accepted, preceding, meta.barriers, prior, engine)?; + if let Some(prefixes) = meta.prefixes { + let tiling = Order::new( + accepted, + preceding, + [prefixes.ta_vdm_barrier, prefixes.ta_cdm_barrier], + [prefixes.ta_prior_vdm, prefixes.ta_prior_cdm], + RENDER, + )?; + order.narrow_tiling(&tiling)?; + } + orders.push(order)?; + preceding[engine] += 1; + } + Ok(Prepared { + commands: self.commands, + orders, + counts: self.counts, + gpu_generation: self.gpu_generation, + }) + } +} + +impl SpanProof { + /// Allocates a [`SpanProof`] directly on the heap without staging its range or scratch arrays + /// on the kernel stack. + #[inline(never)] + pub(crate) fn new_boxed() -> Result> { + Ok(KBox::init( + init!(Self { + cache <- init!(ProofCache { + epoch: None, + ranges <- ::pin_init::init_array_from_fn(|_| (0, 0, 0)), + count: 0, + overflow: false, + }), + scratch <- init!(ValidateScratch { + batch <- init!(SpanBatch { + ranges <- ::pin_init::init_array_from_fn(|_| (0, 0, 0)), + len: 0, + }), + missing <- ::pin_init::init_array_from_fn(|_| (0, 0, 0)), + vdm_vas <- ::pin_init::init_array_from_fn(|_| 0), + cdm_ranges <- ::pin_init::init_array_from_fn(|_| (0, 0)), + }), + }), + GFP_KERNEL, + )?) + } +} + +impl Prepared { /// Checks each command's spans, programs and stream gates, with a job reference on the VM /// already held so that the checked mappings are retained until the job retires. - pub(crate) fn validate(self, context: &Context<'_>) -> Result { + pub(crate) fn validate( + self, + context: &Context<'_>, + proof: &mut SpanProof, + ) -> Result { let Prepared { - bytes, - resolved, + mut commands, orders, counts, + gpu_generation, } = self; - let mut commands = KVec::with_capacity(resolved.len(), GFP_KERNEL)?; - let mut vertex = KVec::new(); - let mut fragment = KVec::new(); - let mut compute = KVec::new(); - let mut resolved = resolved.into_iter(); - for entry in stream(bytes) { - let entry = entry?; - match entry.kind { - SET_VERTEX_ATTACHMENTS => vertex = attachment_list(entry.payload)?, - SET_FRAGMENT_ATTACHMENTS => fragment = attachment_list(entry.payload)?, - SET_COMPUTE_ATTACHMENTS => compute = attachment_list(entry.payload)?, - CMD_RENDER => { - let packet: uapi::drm_asahi_cmd_render = payload(entry.payload)?; - let cmd = &packet; - let outputs = resolved.next().ok_or(EINVAL)?; - check_render(context, cmd)?; - check_attachments(context.vm, &vertex, true)?; - check_attachments(context.vm, &fragment, true)?; - commands.push( - Command::Render(KBox::new( - RenderCommand { - cmd: *cmd, - timestamp_outputs: outputs, - vertex_attachments: copy_list(&[&vertex])?, - fragment_attachments: copy_list(&[&fragment])?, - }, - GFP_KERNEL, - )?), - GFP_KERNEL, - )?; - } - CMD_COMPUTE => { - let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; - let cmd = &packet; - check_compute(context, cmd, &compute)?; - let outputs = resolved.next().ok_or(EINVAL)?; - commands.push( - Command::Compute(KBox::new( - ComputeCommand { - cmd: *cmd, - attachments: copy_list(&[&compute])?, - timestamp_outputs: outputs, - }, - GFP_KERNEL, - )?), - GFP_KERNEL, - )?; + if commands.is_empty() { + return Err(EINVAL); + } + let mut vdm_count = 0usize; + let mut cdm_count = 0usize; + { + let scratch = &mut proof.scratch; + scratch.batch.clear(); + for command in commands.iter_mut() { + match command { + Command::Render(render) => { + check_render_for( + &mut scratch.batch, + context, + &render.cmd, + &render.vertex_attachments, + &render.fragment_attachments, + gpu_generation, + )?; + render.scs = + check_render_ray(&mut scratch.batch, context, &render.ray_query)?; + if vdm_count >= scratch.vdm_vas.len() { + return Err(EINVAL); + } + scratch.vdm_vas[vdm_count] = render.cmd.vdm_ctrl_stream_base; + vdm_count += 1; + } + Command::Compute(compute) => { + let range = check_compute( + &mut scratch.batch, + context, + &compute.cmd, + &compute.attachments, + )?; + compute.scs = + check_compute_ray(&mut scratch.batch, context, &compute.ray)?; + if cdm_count >= scratch.cdm_ranges.len() { + return Err(EINVAL); + } + scratch.cdm_ranges[cdm_count] = range; + cdm_count += 1; + } } - _ => return Err(EINVAL), } } - if commands.is_empty() { - return Err(EINVAL); + let stream_gate = super::params::stream_gate(); + let need_vdm = vdm_count != 0 && stream_gate; + let need_cdm = cdm_count != 0 && stream_gate; + if need_vdm || need_cdm { + if need_cdm { + kernel::task::might_sleep(); + if kernel::current!().signal_pending() { + return Err(ERESTARTSYS); + } + } + let mut guard = Some(context.vm.read_lock().map_err(|_| EFAULT)?); + let mut epoch = guard.as_ref().and_then(|g| g.epoch()); + if let Some(g) = guard.as_mut() { + let SpanProof { cache, scratch } = proof; + scratch.batch.flush_locked_with_cache(g, epoch, cache)?; + if need_vdm { + gate::vdm_batch_locked(g, &scratch.vdm_vas[..vdm_count])?; + } + } + for i in 0..cdm_count { + let (base, end) = proof.scratch.cdm_ranges[i]; + gate::cdm_locked( + context.vm, + &mut guard, + &mut epoch, + context.usc_base, + base, + end, + Some(&mut *proof), + )?; + } + } else { + let SpanProof { cache, scratch } = proof; + scratch + .batch + .flush_with_proof_parts(context.vm, cache, &mut scratch.missing)?; } Ok(Submission { counts, diff --git a/drivers/gpu/drm/asahi/g16/encode.rs b/drivers/gpu/drm/asahi/g16/encode.rs index a9bf84943b8054..33fa638acb765d 100644 --- a/drivers/gpu/drm/asahi/g16/encode.rs +++ b/drivers/gpu/drm/asahi/g16/encode.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! M4 25G83 HAL200 work-image and microsequence encoders. +//! M4 HAL200 work-image and microsequence encoders (25G83 and 26B123 work layouts). //! //! Pure byte builders over retained firmware/client addresses. Allocation, //! address-range admission, owner leases, cache visibility and publication are @@ -8,7 +8,7 @@ use kernel::{prelude::*, uapi}; -use super::fw::graph::manager; +use super::fw::graph::{manager, pools}; use super::fw::work::{self, barrier, compute, fs, initbm, scene, ta, REG_RECORD}; use super::hw; @@ -67,11 +67,40 @@ pub(crate) const fn compact(gva: u64) -> u64 { gva.wrapping_sub(0x1000000000) } +/// Packed UMA page-table cache (PTC) policy word written to `0xa5a1` (TA), `0xa5a9` (FS), +/// and `0xa599` (compute): low 16 bits = min entries, bits 31..16 = mid entries, bits 63..32 = +/// max entries. +pub(super) const fn uma_ptc_word(min: u16, mid: u16, max: u16) -> u64 { + (min as u64) | ((mid as u64) << 16) | ((max as u64) << 32) +} + +/// Packed DUPM resource-control word written to `0xd419` (TA), `0xd429` (FS), and `0xd411` +/// (compute): lower and upper 32-bit resource-allocation limits. +pub(super) const fn dupm_control_word(lo: u32, hi: u32) -> u64 { + (lo as u64) | ((hi as u64) << 32) +} + +/// Default DUPM resource-control word shared by TA, FS and compute work items. +pub(super) const DEFAULT_DUPM_CONTROL: u64 = dupm_control_word(1, 2); + +/// Default per-stage hardware control word written to `0x101e1`/`0x12099` (TA), +/// `0x101e9`/`0x120a1` (FS), and `0x101d9`/`0x12091` (compute). +pub(super) const STAGE_CTRL_DEFAULT: u64 = 0x1c; + +/// Fragment tile-state base bits (`0x16068`) for G15 and G16+ hardware, plus the required +/// enable bit at bit 37. +const TILE_STATE_BASE_G15: u64 = 0x36011; +const TILE_STATE_BASE_G16: u64 = 0x3717f; +const TILE_STATE_ENABLE_BIT: u64 = 1 << 37; + #[path = "encode/compute.rs"] mod compute_encoder; +use compute_encoder::put_generation; #[allow(unused_imports)] // Pure encoder utilities are exercised by the host ABI harness. pub(crate) use compute_encoder::{ - encode_compute, init_compute_pool, preserve_compute_descriptor, ComputeEncodeError, ComputeRefs, + encode_compute, encode_compute_for, encode_compute_rt, init_compute_pool, + preserve_compute_descriptor, validate_compute_descriptor, ComputeEncodeError, ComputeRefs, + ComputeRt, COMPUTE_SCS_DRIVER_WORD, }; /// Tiling geometry and register words of a render (accelerator count 2). @@ -115,9 +144,20 @@ impl Geometry { Ok(()) } - /// The geometry of render `u` with layer metadata at `heap`. The render was validated - /// (width, height, layers >= 1, samples 1, 2 or 4, utiles 16 or 32). + /// The geometry of render `u` with layer metadata at `heap` for single-cluster G16G. pub(crate) fn new(u: &uapi::drm_asahi_cmd_render, heap: u64) -> Self { + Self::new_for(u, heap, 1, 16) + } + + /// The geometry of render `u` with layer metadata at `heap` for a GPU with `num_clusters` + /// clusters and `gpu_generation`. The render was validated (width, height, layers >= 1, + /// samples 1, 2 or 4, utiles 16 or 32). + pub(crate) fn new_for( + u: &uapi::drm_asahi_cmd_render, + heap: u64, + num_clusters: u32, + gpu_generation: u32, + ) -> Self { let (w, h, l) = ( u32::from(u.width_px), u32::from(u.height_px), @@ -156,7 +196,7 @@ impl Geometry { }; g.utile_config = utile_w | utile_h | log2s; g.tilemap_bytes = align(5 * g.e * u64::from(l), 0x1000); - g.tpc_bytes = g.e * 8 * u64::from(l); + g.tpc_bytes = u64::from(num_clusters.max(1)) * g.e * 8 * u64::from(l); g.layer_metadata = heap + if l > 1 { 0x200 } else { 0 }; g.layer_mode = if l == 1 { 0x8000 @@ -172,12 +212,19 @@ impl Geometry { ) as u32 | log2s << 17; g.tile_mode = 0x280 | u32::from(l > 1) | if empty { 1 << 16 } else { 0 }; - g.isp_control = 0xc000 | (u.flags & (1 << 18)); - g.native_tiles = 0x3717fu64 + let few_primitives = + u.flags & uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FEW_PRIMITIVES != 0; + g.isp_control = 0xc000 | (u.flags & (1 << 18)) | u32::from(few_primitives); + let native_tiles_base = if gpu_generation < 16 { + TILE_STATE_BASE_G15 + } else { + TILE_STATE_BASE_G16 + }; + g.native_tiles = native_tiles_base | u64::from(l > 1) << 32 | u64::from(g.tx.wrapping_sub(1)) << 44 | u64::from(g.ty.wrapping_sub(1)) << 53 - | 137438953472u64 + | TILE_STATE_ENABLE_BIT | u64::from(g.utile_config & 0xf000) << 28; g } @@ -277,6 +324,7 @@ pub(crate) fn barrier( mod render_encoder; #[allow(unused_imports)] // Includes private-tail variants rejected by the shared Mesa UAPI. pub(crate) use render_encoder::{ - append_fs_timestamp_copies, encode_fs, encode_ta, fill_scene, initbm, render_attachments, - scene, scene_render, PassRefs, RenderRefs, + append_fs_timestamp_copies, encode_fs, encode_fs_for, encode_fs_rt, encode_ta, encode_ta_for, + encode_ta_rt, fill_scene, initbm, render_attachments, render_attachments_for, scene, + scene_prefix, scene_render, PassRefs, RenderRefs, StageRt, RENDER_SCS_ENABLE, }; diff --git a/drivers/gpu/drm/asahi/g16/encode/compute.rs b/drivers/gpu/drm/asahi/g16/encode/compute.rs index 08a4f9ee9cefd9..c7a8430d8a78df 100644 --- a/drivers/gpu/drm/asahi/g16/encode/compute.rs +++ b/drivers/gpu/drm/asahi/g16/encode/compute.rs @@ -1,8 +1,31 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! Pure G16G/25G83 compute encoding. Publication and lifetime proofs belong to the engine. +//! Pure G16G compute encoding (25G83 and 26B123 work layouts). Publication and lifetime proofs +//! belong to the engine. -use super::{compute, manager, put16, put32, put64, put8, uapi}; +use super::{compute, manager, pools, put16, put32, put64, put8, uapi}; + +/// G15-only compute stage control register emitted immediately before [`REG_STAGE_CTRL`]. +const REG_G15_STAGE_CTRL: u32 = 0x12091; +/// Shared compute stage control register. +const REG_STAGE_CTRL: u32 = 0x101d9; +/// HAL200 compute USC-base register (`0x10071`). +const REG_HAL200_USC_BASE: u32 = 0x10071; +/// Default compute stage hardware control word (`0x101d9` / G15 `0x12091`). +const STAGE_CTRL_DEFAULT: u64 = 0x1c; +/// Packed compute UMA page-table cache (PTC) policy word (`0xa599`): min=0x20, mid=0x40, max=0x132. +const COMPUTE_UMA_PTC: u64 = 0x20 | (0x40 << 16) | (0x132 << 32); +/// Packed compute DUPM resource-control word (`0xd411`): lo=1, hi=2. +const DEFAULT_DUPM_CONTROL: u64 = 1 | (2 << 32); + +/// Stores the binding generation `v` as a little-endian integer of `bytes` (1 or 8) bytes. +pub(super) fn put_generation(b: &mut [u8], off: usize, bytes: usize, v: u8) { + if bytes == 1 { + put8(b, off, v); + } else { + put64(b, off, u64::from(v)); + } +} /// A rejected detached image is never publishable; all validation precedes writes. #[derive(Copy, Clone, Debug, PartialEq, Eq)] @@ -28,6 +51,8 @@ pub(crate) struct ComputeRefs { pub(crate) work: u64, pub(crate) work_gva: u64, pub(crate) seq: u64, + /// Zero selects the embedded `work + DESCRIPTOR`; otherwise a separate firmware UMA manager. + pub(crate) descriptor_fw: u64, pub(crate) preempt_gva: u64, pub(crate) its: u64, pub(crate) stats_fw: u64, @@ -42,6 +67,8 @@ pub(crate) struct ComputeRefs { pub(crate) record_fw: u64, pub(crate) binding_generation: u8, pub(crate) uma_slot: u32, + /// Firmware completion event assigned to this compute pipe (e.g. 15 or 16). + pub(crate) event: u32, /// Native command descriptor identifier (work+0x820), independent of compute index. pub(crate) command_id: u64, /// Native u32 compute sequence/index (StartCompute+0x38). @@ -53,6 +80,60 @@ pub(crate) struct ComputeRefs { pub(crate) submitted: u64, } +/// The first and last register records of a ray-query compute work item, as macOS 27.2 on the +/// J773g writes them: 0x017e1 = 1 first (only in ray-query items) and 0x017d9 = 1 last. macOS +/// also writes the trailing 0x017d9 in some compute work without ray queries; G16G's +/// non-ray-query work keeps the list it has always had. +const RAY_QUERY_FIRST: (u32, u64) = (0x017e1, 1); +const RAY_QUERY_LAST: (u32, u64) = (0x017d9, 1); +/// Write the SCS driver word 0x1a141 after 0x1a0e9 for a command with scratch, as g17's G17P +/// compute program does (zero on Gen1). Off: 25F84's program does not write it. Trace +/// question T1. +pub(crate) const COMPUTE_SCS_DRIVER_WORD: bool = false; + +/// The ray-tracing words of one compute work item, and the UMA pool it runs with. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct ComputeRt { + /// 0x1a089, 0x1a091, 0x1a059, 0x1a061, 0x1a0b9, 0x1a0c1. + pub(crate) intersection: [u64; 6], + /// 0x101d1. + pub(crate) size: u64, + /// 0xd479. + pub(crate) tail: u64, + /// 0x1a0e9. + pub(crate) stack: u64, + /// 0x107a1. + pub(crate) window: u64, + /// 0x1a141, with [`COMPUTE_SCS_DRIVER_WORD`]. + pub(crate) driver: u64, + /// The command has scratch (the gated registers apply). + pub(crate) scs: bool, + /// Freelist entries of the unit's UMA pool, published in a fresh descriptor (SEEDS_A/B). + pub(crate) seeds: u32, + /// Records of the unit's freelist, published in a fresh descriptor (+0x1c). + pub(crate) records: u32, +} + +impl ComputeRt { + /// A command without ray state in a base UMA pool: the words G16G has always written. + pub(crate) const DISABLED: Self = Self { + intersection: [0; 6], + size: 0, + tail: 0, + stack: 8, + window: 0xff0000, + driver: 0, + scs: false, + seeds: 8192, + records: manager::UNK_1C_VALUE, + }; +} + +/// Register records of a compute work item at most: the 24 of [`compute::SEL`], optional G15 +/// `0x12091`, optional HAL200 `0x10071`, the ray-query first and last records and the gated SCS +/// driver word. +const MAX_REGS: usize = compute::SEL.len() + 5; + const FW_START: u64 = 0xfffffc2000000000; const FW_END: u64 = 0xfffffc2ffc000000; const VM_START: u64 = 0x4000; @@ -99,17 +180,17 @@ pub(crate) fn init_compute_pool( Ok(()) } -/// Restores the complete allocator descriptor into a newly encoded, unpublished work after -/// the engine has proved A retired, distinct B displaced A in the same UMA slot, and B retired. -/// Numeric checks here do not establish that ownership proof. The old descriptor's completion -/// counter must equal A's cumulative submission count. Pool/list/counter backing stays pinned; -/// only the work pointer and destination slot are rewritten. Returns the next private counter. -pub(crate) fn preserve_compute_descriptor( +fn validate_compute_descriptor_inner( r: &ComputeRefs, old: &[u8; compute::DESCRIPTOR_SIZE], submitted_before: u64, - w: &mut [u8; compute::WORK_SIZE], + check_index: bool, ) -> Result { + fn read32(b: &[u8], off: usize) -> u32 { + let mut v = [0; 4]; + v.copy_from_slice(&b[off..off + 4]); + u32::from_le_bytes(v) + } fn read64(b: &[u8], off: usize) -> u64 { let mut v = [0; 8]; v.copy_from_slice(&b[off..off + 8]); @@ -120,6 +201,7 @@ pub(crate) fn preserve_compute_descriptor( || r.submitted != submitted_before + 1 || r.uma_slot == 0 || r.uma_slot > 32 + || (check_index && read32(old, manager::INDEX) != r.uma_slot) || read64(old, manager::WORK) != r.work || read64(old, manager::FREELIST) != r.pool_state_gva || read64(old, manager::POOL_TABLE) != r.page_list_gva @@ -128,20 +210,54 @@ pub(crate) fn preserve_compute_descriptor( { return Err(ComputeEncodeError::Descriptor); } + Ok(submitted_before + 1) +} + +/// Validates an in-place retained compute UMA manager descriptor before reuse after displacement. +/// Numeric checks here do not establish ownership proof; the engine proves prior retirement and +/// distinct displacement first. Returns the next private submission counter. +pub(crate) fn validate_compute_descriptor( + r: &ComputeRefs, + old: &[u8; compute::DESCRIPTOR_SIZE], + submitted_before: u64, +) -> Result { + validate_compute_descriptor_inner(r, old, submitted_before, true) +} + +/// Restores the complete allocator descriptor into a newly encoded, unpublished work after +/// the engine has proved A retired, distinct B displaced A in the same UMA slot, and B retired. +/// Numeric checks here do not establish that ownership proof. The old descriptor's completion +/// counter must equal A's cumulative submission count. Pool/list/counter backing stays pinned; +/// only the work pointer and destination slot are rewritten. Returns the next private counter. +#[allow(dead_code)] +pub(crate) fn preserve_compute_descriptor( + r: &ComputeRefs, + old: &[u8; compute::DESCRIPTOR_SIZE], + submitted_before: u64, + w: &mut [u8; compute::WORK_SIZE], +) -> Result { + let next = validate_compute_descriptor_inner(r, old, submitted_before, false)?; w[compute::DESCRIPTOR..compute::DESCRIPTOR + compute::DESCRIPTOR_SIZE].copy_from_slice(old); put64(w, compute::DESCRIPTOR + manager::WORK, r.work); put32(w, compute::DESCRIPTOR + manager::INDEX, r.uma_slot); - Ok(submitted_before + 1) + Ok(next) } -fn timestamp(q: &mut [u8], off: usize, end: bool, r: &ComputeRefs, requested: bool) { +fn timestamp( + q: &mut [u8], + off: usize, + end: bool, + r: &ComputeRefs, + requested: bool, + auxiliary: usize, +) { put32(q, off, if end { 3 } else { 0x80000003 }); put64(q, off + 4, r.work + 0x82c); put64(q, off + 0xc, r.work + 0x834); put64(q, off + 0x14, r.work + if end { 0x83c } else { 0x834 }); put64(q, off + 0x1c, r.qinfo); put64(q, off + 0x24, if requested { r.work + 0x844 } else { 0 }); - put64(q, off + 0x2c, r.work + 0x89c); + put64(q, off + 0x2c, r.work + auxiliary as u64); put64(q, off + 0x34, r.work + 0x7dc); put64(q, off + 0x44, 1); } @@ -150,8 +266,55 @@ fn timestamp(q: &mut [u8], off: usize, end: bool, r: &ComputeRefs, requested: bo /// `r` is authoritative; `n` is only the shared engine's software ordinal. The zeroed sequence /// is mirrored at work+0x900; its live pointer is `r.seq`, which may name that embedded copy or /// a separate retained object. Absolute references into the sequence use `r.seq` in both cases. -#[allow(clippy::too_many_arguments)] +#[allow(clippy::too_many_arguments, dead_code)] pub(crate) fn encode_compute( + r: &ComputeRefs, + c: &uapi::drm_asahi_cmd_compute, + att: &[uapi::drm_asahi_attachment], + ts_va: &[u64; 2], + ctx: u32, + n: u64, + fault_mask: u32, + w: &mut [u8; compute::WORK_SIZE], + q: &mut [u8; compute::SEQ_SIZE], +) -> Result<(), ComputeEncodeError> { + encode_compute_for(&compute::V25G83, r, c, att, ts_va, ctx, n, fault_mask, w, q) +} + +/// [`encode_compute`] for the work layout of another firmware ABI. +#[allow(clippy::too_many_arguments, dead_code)] +pub(crate) fn encode_compute_for( + layout: &compute::Layout, + r: &ComputeRefs, + c: &uapi::drm_asahi_cmd_compute, + att: &[uapi::drm_asahi_attachment], + ts_va: &[u64; 2], + ctx: u32, + n: u64, + fault_mask: u32, + w: &mut [u8; compute::WORK_SIZE], + q: &mut [u8; compute::SEQ_SIZE], +) -> Result<(), ComputeEncodeError> { + encode_compute_rt( + layout, + r, + c, + att, + ts_va, + ctx, + n, + fault_mask, + &ComputeRt::DISABLED, + w, + q, + ) +} + +/// [`encode_compute_for`] with the command's ray-tracing words and its unit's UMA pool. With +/// [`ComputeRt::DISABLED`] the bytes are [`encode_compute_for`]'s. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_compute_rt( + layout: &compute::Layout, r: &ComputeRefs, c: &uapi::drm_asahi_cmd_compute, att: &[uapi::drm_asahi_attachment], @@ -159,15 +322,27 @@ pub(crate) fn encode_compute( ctx: u32, _n: u64, fault_mask: u32, + rt: &ComputeRt, w: &mut [u8; compute::WORK_SIZE], q: &mut [u8; compute::SEQ_SIZE], ) -> Result<(), ComputeEncodeError> { + // Whole 2-MiB pool rows within the freelist the manager reports, which is never smaller + // than a base unit's. + if rt.seeds == 0 + || rt.seeds % 512 != 0 + || rt.seeds > rt.records + || rt.records < manager::UNK_1C_VALUE + { + return Err(ComputeEncodeError::Storage); + } if ctx == 0 || ctx >= 64 { return Err(ComputeEncodeError::Context); } if r.binding_generation == 0 || r.uma_slot == 0 || r.uma_slot > 32 + || r.event == 0 + || r.event >= 128 || r.target_stamp & 0xff != 0 || r.submitted == 0 { @@ -175,6 +350,7 @@ pub(crate) fn encode_compute( } if !fw(r.work, compute::WORK_SIZE as u64) || !fw(r.seq, compute::SEQ_SIZE as u64) + || (r.descriptor_fw != 0 && !fw(r.descriptor_fw, compute::DESCRIPTOR_SIZE as u64)) || !fw(r.qinfo, 0x24c0) || !fw(r.stats_fw, 0xe10) || !fw(r.auxiliary_fw, compute::AUX_SIZE as u64) @@ -192,7 +368,12 @@ pub(crate) fn encode_compute( compute::CONTEXT_STORE_SIZE as u64, 0x4000, ) - || !gpu(r.pool_state_gva, compute::POOL_STATE_SIZE as u64, 0x4000) + // The freelist: one u64 seed address per record. + || !gpu( + r.pool_state_gva, + u64::from(rt.records) * core::mem::size_of::() as u64, + 0x4000, + ) || !gpu(r.page_list_gva, compute::PAGE_LIST_SIZE as u64, 0x4000) || (r.usc_base != 0 && !gpu(r.usc_base, 0x100000000, 0x100000000)) { @@ -234,43 +415,65 @@ pub(crate) fn encode_compute( } } let pre = r.preempt_gva; + let tail = layout.preempt_tail; + let [i0, i1, i2, i3, i4, i5] = rt.intersection; let values = [ pre, base, - pre + 0x1480, - pre + 0x1488, - pre + 0x1490, - pre + 0x1498, + pre + tail, + pre + tail + 8, + pre + tail + 0x10, + pre + tail + 0x18, 0x154024201, 0x10c08860, - 0x1c, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 8, - 0xff0000, - 0x13200400020, - 0x200000001, + STAGE_CTRL_DEFAULT, + i0, + i1, + i2, + i3, + i4, + i5, + rt.size, + rt.tail, + rt.stack, + rt.window, + COMPUTE_UMA_PTC, + DEFAULT_DUPM_CONTROL, 1, 1, 1, ]; w.fill(0); q.fill(0); - for (i, (&sel, &value)) in compute::SEL.iter().zip(values.iter()).enumerate() { + let mut records = [(0u32, 0u64); MAX_REGS]; + let mut count = 0; + let mut push = |sel: u32, value: u64| { + records[count] = (sel, value); + count += 1; + }; + if rt.scs { + push(RAY_QUERY_FIRST.0, RAY_QUERY_FIRST.1); + } + for (&sel, &value) in compute::SEL.iter().zip(values.iter()) { + if sel == REG_STAGE_CTRL && layout.has_reg_12091 { + push(REG_G15_STAGE_CTRL, STAGE_CTRL_DEFAULT); + } + push(sel, value); + if sel == 0x1a0e9 && COMPUTE_SCS_DRIVER_WORD && rt.scs { + push(0x1a141, rt.driver); + } + } + if layout.has_usc_base_reg && r.usc_base != 0 { + push(REG_HAL200_USC_BASE, r.usc_base); + } + if rt.scs { + push(RAY_QUERY_LAST.0, RAY_QUERY_LAST.1); + } + for (i, &(sel, value)) in records[..count].iter().enumerate() { put32(w, compute::REGS + i * 12, sel); put64(w, compute::REGS + i * 12 + 4, value); } - let count = if r.usc_base == 0 { 24 } else { 25 }; - if r.usc_base != 0 { - put32(w, compute::REGS + 24 * 12, 0x10071); - put64(w, compute::REGS + 24 * 12 + 4, r.usc_base); - } + let count = count as u16; put32(w, 0, 3); put32(w, 0xc, ctx); put64( @@ -294,7 +497,7 @@ pub(crate) fn encode_compute( put64(w, 0x800, r.user_stamp); put64(w, 0x808, r.fw_stamp); put32(w, 0x810, r.target_stamp); - put32(w, 0x814, compute::EVENT); + put32(w, 0x814, r.event); put32(w, 0x81c, 1); put32(w, 0x818, r.work_818); put64(w, 0x820, r.command_id); @@ -302,12 +505,22 @@ pub(crate) fn encode_compute( put64(w, 0x83c, r.its + 8); put64(w, 0x844, ts_va[0]); put64(w, 0x84c, ts_va[1]); - put64(w, 0x86a, r.work + compute::DESCRIPTOR as u64); + let descriptor_fw = if r.descriptor_fw == 0 { + r.work + compute::DESCRIPTOR as u64 + } else { + r.descriptor_fw + }; + put64(w, 0x86a, descriptor_fw); put8(w, 0x872, 1); - put64(w, 0x873, 0x1588000); - put64(w, 0x87b, 0xef8000); + put64(w, 0x873, layout.pool_words[0]); + put64(w, 0x87b, layout.pool_words[1]); put64(w, 0x883, r.auxiliary_fw); - put8(w, 0x88b, r.binding_generation); + put_generation( + w, + compute::GENERATION, + layout.generation_bytes, + r.binding_generation, + ); put32(q, 0, 0xb); put64(q, 0x14, r.work + 0x20); @@ -317,6 +530,7 @@ pub(crate) fn encode_compute( put32(q, 0x30, u32::from(fault_mask != 0)); put32(q, 0x38, r.compute_index); put32(q, 0x3c, r.work_818); + put32(q, compute::START_SCS, u32::from(rt.scs)); put64(q, 0x44, r.work + 0x76c); put32(q, 0x50, 1); for (i, a) in att.iter().enumerate() { @@ -329,18 +543,18 @@ pub(crate) fn encode_compute( put16(q, off + 0xe, 1); } put32(q, 0x158, att.len() as u32); - put64(q, 0x160, r.work + compute::DESCRIPTOR as u64); + put64(q, 0x160, descriptor_fw); put64(q, 0x178, r.auxiliary_gva); - put64(q, 0x188, r.context_store_gva); - put64(q, 0x190, r.context_store_gva + 0xf400); - put64(q, 0x198, r.context_store_gva + 0x1e800); - put64(q, 0x1a0, r.context_store_gva + 0x1f000); - put64(q, 0x1a8, r.work + 0x8ac); - put32(q, 0x1b8, compute::EVENT); + put64(q, 0x188, r.context_store_gva + layout.context_store_offsets[0]); + put64(q, 0x190, r.context_store_gva + layout.context_store_offsets[1]); + put64(q, 0x198, r.context_store_gva + layout.context_store_offsets[2]); + put64(q, 0x1a0, r.context_store_gva + layout.context_store_offsets[3]); + put64(q, 0x1a8, r.work + layout.target as u64); + put32(q, 0x1b8, r.event); let requested = ts_va[0] != 0 || ts_va[1] != 0; - timestamp(q, compute::TS_START, false, r, requested); + timestamp(q, compute::TS_START, false, r, requested, layout.auxiliary); put32(q, 0x208, 1); - timestamp(q, compute::TS_END, true, r, requested); + timestamp(q, compute::TS_END, true, r, requested, layout.auxiliary); let f = compute::FINALIZE; put32(q, f, 0xc); put64(q, f + 4, r.stats_fw); @@ -353,8 +567,8 @@ pub(crate) fn encode_compute( put64(q, f + 0x5c, r.seq + 0x160); put32(q, f + 0x64, 0u32.wrapping_sub(f as u32)); put8(q, f + 0x68, u8::from(!att.is_empty())); - put64(q, f + 0x69, r.work + 0x8ac); - put64(q, f + 0x71, r.work + 0x88c); + put64(q, f + 0x69, r.work + layout.target as u64); + put64(q, f + 0x71, r.work + layout.completion as u64); put32(q, compute::END, 0x40000002); w[compute::SEQ_EMBEDDED..compute::SEQ_EMBEDDED + compute::SEQ_SIZE].copy_from_slice(q); @@ -369,12 +583,12 @@ pub(crate) fn encode_compute( put32(w, d + manager::INDEX, r.uma_slot); put32(w, d + manager::ONE, 2); put64(w, d + manager::FREELIST, r.pool_state_gva); - put32(w, d + manager::UNK_1C, manager::UNK_1C_VALUE); - put32(w, d + manager::SEEDS_A, 8192); - put32(w, d + manager::SEEDS_B, 8192); + put32(w, d + manager::UNK_1C, rt.records); + put32(w, d + manager::SEEDS_A, rt.seeds); + put32(w, d + manager::SEEDS_B, rt.seeds); put64(w, d + manager::POOL_TABLE, r.page_list_gva); put32(w, d + 0x40, 4); - put32(w, d + 0x48, 128); + put32(w, d + manager::ROW_WORDS, pools::row_words(rt.seeds)); put64(w, compute::DESCRIPTOR_COUNTER, r.counter_fw); // Native M+0x5c distinguishes shared compute from per-workqueue-private pools. // Retain the existing value for these persistent units reused across queues; diff --git a/drivers/gpu/drm/asahi/g16/encode/render.rs b/drivers/gpu/drm/asahi/g16/encode/render.rs index b054ec08198b74..7212a2b501e9b7 100644 --- a/drivers/gpu/drm/asahi/g16/encode/render.rs +++ b/drivers/gpu/drm/asahi/g16/encode/render.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! M4 25G83 HAL200 render wire records. Inputs are frozen, retained addresses; +//! M4 HAL200 render wire records (25G83 and 26B123). Inputs are frozen, retained addresses; //! these builders neither allocate nor publish queue/notifier state. use super::*; @@ -21,7 +21,8 @@ pub(crate) struct RenderRefs { pub(crate) uma_aux: [u64; 2], pub(crate) uma_gpu: u64, pub(crate) pb_mgr: u64, - /// GPU VA of the scene list, not its firmware alias. + /// Fallback GPU VA of the scene list when `PassRefs::scene_list` is zero (ABI tests). + #[allow(dead_code)] pub(crate) scene_list: u64, #[allow(dead_code)] pub(crate) mgr_misc: u64, @@ -55,6 +56,8 @@ pub(crate) struct PassRefs { pub(crate) heap_gva: u64, /// Scratch GPU VA; scratch_fw is a same-backing firmware alias. pub(crate) scene_user_gva: u64, + /// Per-pass scene list GPU VA, not its firmware alias. + pub(crate) scene_list: u64, pub(crate) scratch_fw: u64, pub(crate) pre_gva: [u64; 3], #[allow(dead_code)] @@ -66,6 +69,82 @@ pub(crate) struct PassRefs { pub(crate) ta_scratch: u64, } +/// Packed 16-bit tiler hardware configuration fields written to TA `0x1c051`. +const TA_TILER_CONFIG: u64 = 0x0003 | (0x006b << 16) | (0x0012 << 32) | (0x003a << 48); +/// Default render cache configuration written to TA `0x1c8f8` and FS `0x100b8`. +const RENDER_CACHE_CONFIG: u64 = 0x8860; +/// Default ISP control word written to FS `0x15049` and mirrored at FS work `+0x9d0`. +const FS_ISP_CTRL_DEFAULT: u64 = 0x10_0000; +/// Default ZLS per-lane sample mask written to FS `0x15349` and mirrored at FS work `+0x940`. +const FS_ZLS_SAMPLE_MASK_DEFAULT: u64 = 0x0404_0404; +/// UMA page-table cache (PTC) policy words for G16G render (`0xa5a1`/`0xa5a9`) and G15S TA/FS. +const G16G_RENDER_UMA_PTC: u64 = uma_ptc_word(0x20, 0x40, 0x60); +const G15S_TA_UMA_PTC: u64 = uma_ptc_word(0x20, 0x40, 0x7f); +const G15S_FS_UMA_PTC: u64 = uma_ptc_word(0x20, 0x40, 0x9f); + +/// Write the macOS 27.2 J773g SCS enable pair (`0x017e1 = 1` before `at`, `0x017d9 = 1` at the +/// end) in the register list of a render stage with scratch: `0x017e1 = 1` first in the TA list +/// (before `0x1748`) and after `0x1739` in the FS list, with `0x017d9 = 1` last in both, matching +/// `encode::compute` (`RAY_QUERY_FIRST`/`RAY_QUERY_LAST`) and the M5 render register lists. +pub(crate) const RENDER_SCS_ENABLE: bool = true; + +/// The ray-query words of one render stage (the M4 Pro's 25G83 render programs). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct StageRt { + /// TA 0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, 0x1a0d1; FS 0x1a0a9, 0x1a0b1, 0x1a079, + /// 0x1a081, 0x1a0d9, 0x1a0e1. + pub(crate) intersection: [u64; 6], + /// TA 0x101c9, FS 0x101c1. + pub(crate) size: u64, + /// TA 0xd471, FS 0xd469. + pub(crate) tail: u64, + /// TA 0x1a0f1, FS 0x1a0f9. + pub(crate) stack: u64, + /// TA 0x10799; FS 0x10791 with bit 9. + pub(crate) window: u64, + /// The stage has scratch (the gated register applies). + pub(crate) scs: bool, +} + +impl StageRt { + /// A stage without ray queries: the words G16G has always written. + pub(crate) const DISABLED: Self = Self { + intersection: [0; 6], + size: 0, + tail: 0, + stack: 8, + window: 0xff0000, + scs: false, + }; +} + +/// Register records, bracketed with `0x017e1 = 1` before record `at` and `0x017d9 = 1` at the +/// end when `RENDER_SCS_ENABLE && scs`; returns the record count. +fn stage_regs(dst: &mut [u8], sel: &[u32], val: &[u64], scs: bool, at: usize) -> u16 { + if !(RENDER_SCS_ENABLE && scs) { + regs(dst, sel, val); + return sel.len() as u16; + } + regs(dst, &sel[..at], &val[..at]); + put32(dst, REG_RECORD * at, 0x017e1); + put64(dst, REG_RECORD * at + 4, 1); + if let Some(rest) = dst.get_mut(REG_RECORD * (at + 1)..) { + regs(rest, &sel[at..], &val[at..]); + } + let last = REG_RECORD * (sel.len() + 1); + put32(dst, last, 0x017d9); + put64(dst, last + 4, 1); + sel.len() as u16 + 2 +} + +fn scene_list_va(r: &RenderRefs, p: &PassRefs) -> u64 { + if p.scene_list != 0 { + p.scene_list + } else { + r.scene_list + } +} + fn metadata(w: &mut [u8], off: usize, r: &RenderRefs, engine: usize, target: u32) { put64(w, off, r.user_stamp[engine]); put64(w, off + 8, r.fw_stamp[engine]); @@ -76,7 +155,7 @@ fn metadata(w: &mut [u8], off: usize, r: &RenderRefs, engine: usize, target: u32 // Wire sequence stays zero; host reservations are 64-bit notifier state. } -fn inline_uma(q: &mut [u8], off: usize, r: &RenderRefs, engine: usize) { +fn inline_uma(q: &mut [u8], off: usize, r: &RenderRefs, engine: usize, engine_byte: bool) { put64(q, off, r.uma_mgr[0]); put64( q, @@ -85,9 +164,12 @@ fn inline_uma(q: &mut [u8], off: usize, r: &RenderRefs, engine: usize) { ); put64(q, off + 0x28, r.counter[engine]); put32(q, off + 0x30, 0x70 + engine as u32); - put8(q, off + 0x34, engine as u8); + if engine_byte { + put8(q, off + 0x34, engine as u8); + } } +#[allow(clippy::too_many_arguments)] fn timestamps( q: &mut [u8], off: usize, @@ -96,11 +178,12 @@ fn timestamps( user: bool, uuid: u32, engine: usize, + auxiliary: usize, ) { - let (control, pair, auxiliary, context, user_pair) = if engine == 0 { - (0x8c0, 0x8c8, 0x928, 0x83c, 0x8d8) + let (control, pair, context, user_pair) = if engine == 0 { + (0x8c0, 0x8c8, 0x83c, 0x8d8) } else { - (0xc08, 0xc10, 0xc70, 0xb84, 0xc20) + (0xc08, 0xc10, 0xb84, 0xc20) }; for end in [false, true] { let base = off + if end { 0x50 } else { 0 }; @@ -110,7 +193,7 @@ fn timestamps( put64(q, base + 0x14, work + pair + if end { 8 } else { 0 }); put64(q, base + 0x1c, queue); put64(q, base + 0x24, if user { work + user_pair } else { 0 }); - put64(q, base + 0x2c, work + auxiliary); + put64(q, base + 0x2c, work + auxiliary as u64); put64(q, base + 0x34, work + context); put64(q, base + 0x44, u64::from(uuid)); } @@ -126,9 +209,60 @@ fn internal_pair(w: &mut [u8], p: &PassRefs, engine: usize, ts: &[u64; 4]) { put64(w, off + 0x18, ts[2 * engine + 1]); } -/// Encode the 66-record single-cluster tiler work and its exact 0x300 sequence. -#[allow(clippy::too_many_arguments)] +/// Encode the 25G83 66-record single-cluster tiler work and its exact 0x300 sequence. +#[allow(clippy::too_many_arguments, dead_code)] pub(crate) fn encode_ta( + r: &RenderRefs, + p: &PassRefs, + u: &uapi::drm_asahi_cmd_render, + ts_va: &[u64; 4], + ctx: u32, + target: u32, + geo: &Geometry, + cl: Option<&ClusterLayout>, + w: &mut [u8; ta::WORK_SIZE], + q: &mut [u8; ta::SEQ_SIZE], +) { + encode_ta_for(&ta::V25G83, r, p, u, ts_va, ctx, target, geo, cl, w, q) +} + +/// Encode the 66-record single-cluster tiler work of `layout`'s ABI and its exact 0x300 +/// sequence. +#[allow(clippy::too_many_arguments, dead_code)] +pub(crate) fn encode_ta_for( + layout: &ta::Layout, + r: &RenderRefs, + p: &PassRefs, + u: &uapi::drm_asahi_cmd_render, + ts_va: &[u64; 4], + ctx: u32, + target: u32, + geo: &Geometry, + cl: Option<&ClusterLayout>, + w: &mut [u8; ta::WORK_SIZE], + q: &mut [u8; ta::SEQ_SIZE], +) { + encode_ta_rt( + layout, + r, + p, + u, + ts_va, + ctx, + target, + geo, + cl, + &StageRt::DISABLED, + w, + q, + ) +} + +/// [`encode_ta_for`] with the vertex stage's ray-query words. With [`StageRt::DISABLED`] the +/// bytes are [`encode_ta_for`]'s. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_ta_rt( + layout: &ta::Layout, r: &RenderRefs, p: &PassRefs, u: &uapi::drm_asahi_cmd_render, @@ -137,6 +271,7 @@ pub(crate) fn encode_ta( target: u32, geo: &Geometry, _cl: Option<&ClusterLayout>, + rt: &StageRt, w: &mut [u8; ta::WORK_SIZE], q: &mut [u8; ta::SEQ_SIZE], ) { @@ -150,76 +285,159 @@ pub(crate) fn encode_ta( 0x7000000000 })) & 0x7ffffffffe) | ((scratch & (1 << 42)) >> 3); - let val: [u64; 66] = [ - 1, - 0x200, - compact(p.tilemap_gva), - compact(p.tilemap_gva), - compact(p.tpc_gva), - compact(p.heap_gva) | 1 << 63, - compact(p.heap_gva) | 1 << 63, - 0x003a0012006b0003, - 1, - u64::from(geo.utile_config), - u.ppp_multisamplectl, - compact(p.pre_gva[0]), - compact(p.pre_gva[0]), - compact(p.pre_gva[1]), - compact(p.pre_gva[1]), - 1, - compact(p.pre_gva[2]) | 1 << 50, - 0, - compact(u.vdm_ctrl_stream_base) & !3, - compact(geo.layer_metadata), - compact(geo.layer_metadata), - 0, - 0, - 0, - 0, - 0, - 0, - 0x8860, - u64::from(geo.region_stride), - u64::from(geo.region_stride), - 0x88, - u64::from(2 | (u.ppp_ctrl & 0x201)), - u64::from(geo.pixels), - u64::from(geo.screen), - geo.x_blocks, - geo.y_blocks, - u64::from(geo.blocks), - u64::from(geo.tpc_stride), - 0x100, - u64::from(geo.layer_mode), - 0, - u64::MAX, - u64::MAX, - 0, - 0x1c, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 8, - 0xff0000, - u64::from(r.parameter_id), - compact(r.scene_list), - compact(r.scene_list), - scratch_word, - 0x6000400020, - 0x200000001, - u64::from(r.uuid), - u64::from(r.uuid), - u64::from(r.uuid), - // USC base is a shared queue property carried by the render refs. - r.usc_base, - ]; - regs(&mut w[ta::REGS..], &ta::SEL, &val); + let count = match layout.profile { + ta::RegProfile::G16G => { + let val: [u64; 66] = [ + 1, + 0x200, + compact(p.tilemap_gva), + compact(p.tilemap_gva), + compact(p.tpc_gva), + compact(p.heap_gva) | 1 << 63, + compact(p.heap_gva) | 1 << 63, + TA_TILER_CONFIG, + 1, + u64::from(geo.utile_config), + u.ppp_multisamplectl, + compact(p.pre_gva[0]), + compact(p.pre_gva[0]), + compact(p.pre_gva[1]), + compact(p.pre_gva[1]), + 1, + compact(p.pre_gva[2]) | 1 << 50, + 0, + compact(u.vdm_ctrl_stream_base) & !3, + compact(geo.layer_metadata), + compact(geo.layer_metadata), + 0, + 0, + 0, + 0, + 0, + 0, + RENDER_CACHE_CONFIG, + u64::from(geo.region_stride), + u64::from(geo.region_stride), + 0x88, + u64::from(2 | (u.ppp_ctrl & 0x201)), + u64::from(geo.pixels), + u64::from(geo.screen), + geo.x_blocks, + geo.y_blocks, + u64::from(geo.blocks), + u64::from(geo.tpc_stride), + 0x100, + u64::from(geo.layer_mode), + 0, + u64::MAX, + u64::MAX, + 0, + STAGE_CTRL_DEFAULT, + 0, + rt.intersection[0], + rt.intersection[1], + rt.intersection[2], + rt.intersection[3], + rt.intersection[4], + rt.intersection[5], + rt.size, + rt.tail, + rt.stack, + rt.window, + u64::from(r.parameter_id), + compact(scene_list_va(r, p)), + compact(scene_list_va(r, p)), + scratch_word, + G16G_RENDER_UMA_PTC, + DEFAULT_DUPM_CONTROL, + u64::from(r.uuid), + u64::from(r.uuid), + u64::from(r.uuid), + // USC base is a shared queue property carried by the render refs. + r.usc_base, + ]; + stage_regs(&mut w[ta::REGS..], &ta::SEL, &val, rt.scs, 0) + } + ta::RegProfile::G15S => { + let val: [u64; 74] = [ + 0x200, + compact(p.tilemap_gva), + compact(p.tilemap_gva), + 0, + 0, + compact(p.tpc_gva), + compact(p.heap_gva) | 1 << 63, + compact(p.heap_gva) | 1 << 63, + TA_TILER_CONFIG, + 1, + u64::from(geo.utile_config), + u.ppp_multisamplectl, + compact(p.pre_gva[0]), + compact(p.pre_gva[0]), + compact(p.pre_gva[1]), + compact(p.pre_gva[1]), + 1, + compact(p.pre_gva[2]) | 1 << 50, + 0, + compact(u.vdm_ctrl_stream_base) & !3, + 0, + 0, + 0, + 1, + 0, + compact(geo.layer_metadata), + compact(geo.layer_metadata), + 0, + 0, + 0, + 0, + 4 * u64::from(r.pb_init_blocks), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + RENDER_CACHE_CONFIG, + u64::from(geo.region_stride), + u64::from(geo.region_stride), + 0x88, + u64::from(2 | (u.ppp_ctrl & 0x201)), + u64::from(geo.pixels), + u64::from(geo.screen), + geo.x_blocks, + geo.y_blocks, + u64::from(geo.blocks), + u64::from(geo.tpc_stride), + 0x100, + u64::from(geo.layer_mode), + STAGE_CTRL_DEFAULT, + STAGE_CTRL_DEFAULT, + 0, + rt.intersection[0], + rt.intersection[1], + rt.intersection[2], + rt.intersection[3], + rt.intersection[4], + rt.intersection[5], + rt.size, + rt.tail, + rt.stack, + rt.window, + G15S_TA_UMA_PTC, + DEFAULT_DUPM_CONTROL, + u64::from(r.uuid), + u64::from(r.uuid), + u64::from(r.uuid), + u64::from(r.parameter_id), + compact(scene_list_va(r, p)), + compact(scene_list_va(r, p)), + scratch_word, + ]; + stage_regs(&mut w[ta::REGS..], &ta::SEL_G15S, &val, rt.scs, 0) + } + }; put64(w, 4, r.counter[0]); put32(w, 0xc, ctx); put64(w, 0x10, r.notifier); @@ -228,9 +446,9 @@ pub(crate) fn encode_ta( put64(w, 0x28, p.scene); put64(w, 0x30, p.scene + 0x100); put64(w, 0x740, p.ta_work_gva + 0x40); - put16(w, 0x748, 66); - put16(w, 0x74a, 66 * 12); - put64(w, 0x760, p.tpc_fw); + put16(w, 0x748, count); + put16(w, 0x74a, count * 12); + put64(w, 0x760, if layout.tpc_is_gva { p.tpc_gva } else { p.tpc_fw }); put64(w, ta::TPC_BYTES, geo.tpc_bytes); put64(w, 0x770, p.ta_seq); put32(w, 0x778, ta::SEQ_SIZE as u32); @@ -242,7 +460,7 @@ pub(crate) fn encode_ta( put64(w, 0x8fe, r.uma_mgr[0]); put8(w, 0x906, 1); put64(w, 0x90f, r.uma_aux[0]); - put8(w, 0x917, r.generation); + put_generation(w, ta::GENERATION, layout.generation_bytes, r.generation); let work = p.ta_work; put32(q, 0, 5); @@ -258,8 +476,9 @@ pub(crate) fn encode_ta( put64(q, 0x64, work + 0x784); put64(q, 0x6c, work + 0x8a8); put32(q, 0x7c, r.uuid); + put32(q, ta::START_SCS, u32::from(RENDER_SCS_ENABLE && rt.scs)); // TA attachments are filled by render_attachments before publication. - inline_uma(q, 0x190, r, 0); + inline_uma(q, 0x190, r, 0, layout.inline_uma_engine_byte); timestamps( q, 0x1cc, @@ -268,6 +487,7 @@ pub(crate) fn encode_ta( ts_va[0] != 0 || ts_va[1] != 0, r.uuid, 0, + layout.auxiliary, ); let f = 0x268; put32(q, f, 6); @@ -283,14 +503,67 @@ pub(crate) fn encode_ta( put32(q, f + 0x50, target); put64(q, f + 0x78, p.ta_seq + 0x190); put32(q, f + 0x80, 0u32.wrapping_sub(f as u32)); - put64(q, f + 0x85, work + 0x918); - put8(q, f + 0x8d, 1); + put64(q, f + 0x85, work + layout.completion as u64); + put8(q, f + 0x8d, layout.finalize_flag); put32(q, f + 0x94, 0x40000002); } -/// Encode the 82-record fragment work and base 0x380 sequence. -#[allow(clippy::too_many_arguments)] +/// Encode the 25G83 82-record fragment work and base 0x380 sequence. +#[allow(clippy::too_many_arguments, dead_code)] pub(crate) fn encode_fs( + r: &RenderRefs, + p: &PassRefs, + u: &uapi::drm_asahi_cmd_render, + ts_va: &[u64; 4], + ctx: u32, + usc: u64, + n: u64, + target: u32, + geo: &Geometry, + w: &mut [u8; fs::WORK_SIZE], + q: &mut [u8], +) { + encode_fs_for(&fs::V25G83, r, p, u, ts_va, ctx, usc, n, target, geo, w, q) +} + +/// Encode the 82-record fragment work of `layout`'s ABI and base 0x380 sequence. +#[allow(clippy::too_many_arguments, dead_code)] +pub(crate) fn encode_fs_for( + layout: &fs::Layout, + r: &RenderRefs, + p: &PassRefs, + u: &uapi::drm_asahi_cmd_render, + ts_va: &[u64; 4], + ctx: u32, + usc: u64, + n: u64, + target: u32, + geo: &Geometry, + w: &mut [u8; fs::WORK_SIZE], + q: &mut [u8], +) { + encode_fs_rt( + layout, + r, + p, + u, + ts_va, + ctx, + usc, + n, + target, + geo, + &StageRt::DISABLED, + w, + q, + ) +} + +/// [`encode_fs_for`] with the fragment stage's ray-query words. With [`StageRt::DISABLED`] +/// the bytes are [`encode_fs_for`]'s. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_fs_rt( + layout: &fs::Layout, r: &RenderRefs, p: &PassRefs, u: &uapi::drm_asahi_cmd_render, @@ -300,115 +573,218 @@ pub(crate) fn encode_fs( _n: u64, target: u32, geo: &Geometry, + rt: &StageRt, w: &mut [u8; fs::WORK_SIZE], q: &mut [u8], ) { w.fill(0); q.fill(0); - let val: [u64; 82] = [ - 1, - u64::from(geo.utile_config), - prog_rsrc(u, &u.eot, u.bg_eot_rsrc_spec_hi), - prog_addr(usc, &u.eot), - prog_rsrc(u, &u.bg, u.bg_rsrc_spec_hi), - prog_addr(usc, &u.bg), - u64::from(u.isp_merge_upper_x), - u64::from(u.isp_merge_upper_y), - 0, - 0, - 0, - 0, - u.ppp_multisamplectl, - u64::from(geo.isp_blocks), - u64::from(geo.isp_blocks), - u64::from(geo.screen), - 0, - 0xff0200, - p.heap_gva & !63, - u.isp_scissor_base & !3, - u.isp_dbias_base & !3, - u64::from(geo.isp_control), - u64::from(u.height_px) << 32 | u64::from(u.width_px), - 0x100000, - u64::from(geo.tilebuffer_control), - u64::from(u.isp_zls_pixels), - u64::from(u.isp_bgobjdepth), - u64::from(u.isp_bgobjvals), - u.isp_oclqry_base & !15, - u.zls_ctrl, - 0x04040404, - 0, - u.depth.base, - u.depth.base, - u.stencil.base, - u.stencil.base, - 0, - 0, - 0, - 0, - u64::from(u.depth.stride), - u64::from(u.depth.stride), - u64::from(u.stencil.stride), - u64::from(u.stencil.stride), - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - p.tilemap_gva, - geo.layer_metadata, - u64::from(geo.region_stride) << 26, - u64::from(geo.tile_mode), - 0, - 0, - 0, - 0x8860, - p.aux_gva, - p.aux_gva, - 0x1c, - 0, - geo.native_tiles, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 8, - 0x6000400020, - 0x200000001, - u64::from(r.uuid), - u64::from(r.uuid), - u64::from(r.uuid), - u64::from(r.parameter_id), - compact(r.scene_list), - usc, - ]; - regs(&mut w[fs::REGS..], &fs::SEL, &val); + let count = match layout.profile { + fs::RegProfile::G16G => { + let val: [u64; 82] = [ + 1, + u64::from(geo.utile_config), + prog_rsrc(u, &u.eot, u.bg_eot_rsrc_spec_hi), + prog_addr(usc, &u.eot), + prog_rsrc(u, &u.bg, u.bg_rsrc_spec_hi), + prog_addr(usc, &u.bg), + u64::from(u.isp_merge_upper_x), + u64::from(u.isp_merge_upper_y), + 0, + 0, + 0, + 0, + u.ppp_multisamplectl, + u64::from(geo.isp_blocks), + u64::from(geo.isp_blocks), + u64::from(geo.screen), + 0, + rt.window | 1 << 9, + p.heap_gva & !63, + u.isp_scissor_base & !3, + u.isp_dbias_base & !3, + u64::from(geo.isp_control), + u64::from(u.height_px) << 32 | u64::from(u.width_px), + FS_ISP_CTRL_DEFAULT, + u64::from(geo.tilebuffer_control), + u64::from(u.isp_zls_pixels), + u64::from(u.isp_bgobjdepth), + u64::from(u.isp_bgobjvals), + u.isp_oclqry_base & !15, + u.zls_ctrl, + FS_ZLS_SAMPLE_MASK_DEFAULT, + 0, + u.depth.base, + u.depth.base, + u.stencil.base, + u.stencil.base, + 0, + 0, + 0, + 0, + u64::from(u.depth.stride), + u64::from(u.depth.stride), + u64::from(u.stencil.stride), + u64::from(u.stencil.stride), + u.depth.comp_base, + u64::from(u.depth.comp_stride), + u.depth.comp_base, + u64::from(u.depth.comp_stride), + u.stencil.comp_base, + u64::from(u.stencil.comp_stride), + u.stencil.comp_base, + u64::from(u.stencil.comp_stride), + p.tilemap_gva, + geo.layer_metadata, + u64::from(geo.region_stride) << 26, + u64::from(geo.tile_mode), + 0, + 0, + 0, + RENDER_CACHE_CONFIG, + p.aux_gva, + p.aux_gva, + STAGE_CTRL_DEFAULT, + 0, + geo.native_tiles, + rt.intersection[0], + rt.intersection[1], + rt.intersection[2], + rt.intersection[3], + rt.intersection[4], + rt.intersection[5], + rt.size, + rt.tail, + rt.stack, + G16G_RENDER_UMA_PTC, + DEFAULT_DUPM_CONTROL, + u64::from(r.uuid), + u64::from(r.uuid), + u64::from(r.uuid), + u64::from(r.parameter_id), + compact(scene_list_va(r, p)), + usc, + ]; + stage_regs(&mut w[fs::REGS..], &fs::SEL, &val, rt.scs, 1) + } + fs::RegProfile::G15S => { + let val: [u64; 82] = [ + 1, + u64::from(geo.utile_config), + prog_rsrc(u, &u.eot, u.bg_eot_rsrc_spec_hi), + prog_addr(usc, &u.eot), + prog_rsrc(u, &u.bg, u.bg_rsrc_spec_hi), + prog_addr(usc, &u.bg), + u64::from(u.isp_merge_upper_x), + u64::from(u.isp_merge_upper_y), + 0, + 0, + 0, + 0, + u.ppp_multisamplectl, + u64::from(geo.isp_blocks), + u64::from(geo.isp_blocks), + u64::from(geo.screen), + rt.window | 1 << 9, + p.heap_gva & !63, + u.isp_scissor_base & !3, + u.isp_dbias_base & !3, + u64::from(geo.isp_control), + u64::from(u.height_px) << 32 | u64::from(u.width_px), + FS_ISP_CTRL_DEFAULT, + u64::from(geo.tilebuffer_control), + u64::from(u.isp_zls_pixels), + u64::from(u.isp_bgobjdepth), + u64::from(u.isp_bgobjvals), + u.isp_oclqry_base & !15, + u.zls_ctrl, + FS_ZLS_SAMPLE_MASK_DEFAULT, + 0, + u.depth.base, + u.depth.base, + u.stencil.base, + u.stencil.base, + 0, + 0, + 0, + 0, + u64::from(u.depth.stride), + u64::from(u.depth.stride), + u64::from(u.stencil.stride), + u64::from(u.stencil.stride), + u.depth.comp_base, + u64::from(u.depth.comp_stride), + u.depth.comp_base, + u64::from(u.depth.comp_stride), + u.stencil.comp_base, + u64::from(u.stencil.comp_stride), + u.stencil.comp_base, + u64::from(u.stencil.comp_stride), + p.tilemap_gva, + geo.layer_metadata, + u64::from(geo.region_stride) << 26, + u64::from(geo.tile_mode), + 0, + 0, + 0, + RENDER_CACHE_CONFIG, + p.aux_gva, + p.aux_gva, + STAGE_CTRL_DEFAULT, + STAGE_CTRL_DEFAULT, + 0, + geo.native_tiles, + 0, + rt.intersection[0], + rt.intersection[1], + rt.intersection[2], + rt.intersection[3], + rt.intersection[4], + rt.intersection[5], + rt.size, + rt.tail, + rt.stack, + u64::from(r.parameter_id), + compact(scene_list_va(r, p)), + G15S_FS_UMA_PTC, + DEFAULT_DUPM_CONTROL, + u64::from(r.uuid), + u64::from(r.uuid), + u64::from(r.uuid), + ]; + stage_regs(&mut w[fs::REGS..], &fs::SEL_G15S, &val, rt.scs, 1) + } + }; put32(w, 0, 1); put64(w, 4, r.counter[1]); put32(w, 0xc, ctx); put64(w, 0x14, p.fs_seq); - put32(w, 0x1c, fs::SEQ_SIZE as u32); + put32(w, 0x1c, layout.seq_size as u32); put64(w, 0x20, r.notifier + 0x200); put64(w, 0x28, r.pb_mgr); put64(w, 0x30, p.scene); put64(w, 0x38, p.scene + 0x100); put64(w, 0x40, p.tilemap_gva); - put32(w, 0x50, 1); - put32(w, 0x54, geo.isp_blocks); - put32(w, 0x60, geo.x_blocks as u32); - put32(w, 0x64, geo.y_blocks as u32); - put32(w, 0x68, geo.blocks); + match layout.profile { + fs::RegProfile::G16G => { + put32(w, 0x50, 1); + put32(w, 0x54, geo.isp_blocks); + put32(w, 0x60, geo.x_blocks as u32); + put32(w, 0x64, geo.y_blocks as u32); + put32(w, 0x68, geo.blocks); + } + fs::RegProfile::G15S => { + put32(w, 0x48, 0x88); + put32(w, 0x50, 1); + put32(w, 0x54, geo.isp_blocks); + put32(w, 0x68, u.isp_merge_upper_x); + put32(w, 0x6c, u.isp_merge_upper_y); + } + } put32(w, 0x78, geo.tiles); put64(w, 0x780, p.fs_work_gva + 0x80); - put16(w, 0x788, 82); - put16(w, 0x78a, 82 * 12); + put16(w, 0x788, count); + put16(w, 0x78a, count * 12); put64(w, 0x7a0, u.isp_dbias_base); put64(w, 0x7b0, u.isp_scissor_base); put64(w, 0x7c0, u.isp_oclqry_base); @@ -421,15 +797,19 @@ pub(crate) fn encode_fs( ); put64(w, 0x930, prog_addr(usc, &u.partial_bg)); put64(w, 0x938, u.zls_ctrl); - put64(w, 0x940, 0x04040404); + put64(w, 0x940, FS_ZLS_SAMPLE_MASK_DEFAULT); put64(w, 0x948, u.depth.base); put64(w, 0x950, u64::from(u.depth.stride)); + put64(w, 0x958, u64::from(u.depth.comp_stride)); put64(w, 0x960, u.depth.base); put64(w, 0x968, u.depth.base); + put64(w, 0x970, u.depth.comp_base); put64(w, 0x978, u.stencil.base); put64(w, 0x980, u64::from(u.stencil.stride)); + put64(w, 0x988, u64::from(u.stencil.comp_stride)); put64(w, 0x990, u.stencil.base); put64(w, 0x998, u.stencil.base); + put64(w, 0x9a0, u.stencil.comp_base); put64(w, 0x9b8, u64::from(geo.tilebuffer_control)); put64(w, 0x9c0, u64::from(geo.isp_control)); put64( @@ -437,7 +817,7 @@ pub(crate) fn encode_fs( 0x9c8, u64::from(u.height_px) << 32 | u64::from(u.width_px), ); - put64(w, 0x9d0, 0x100000); + put64(w, 0x9d0, FS_ISP_CTRL_DEFAULT); put64(w, 0x9d8, u64::from(geo.tile_mode)); put64(w, 0x9f4, prog_rsrc(u, &u.eot, u.bg_eot_rsrc_spec_hi)); put64(w, 0x9fc, prog_addr(usc, &u.eot)); @@ -458,8 +838,8 @@ pub(crate) fn encode_fs( put64(w, 0xc46, r.uma_mgr[0]); put8(w, 0xc4e, 1); put64(w, 0xc57, r.uma_aux[1]); - put8(w, 0xc5f, r.generation); - put8(w, 0xc84, 1); + put_generation(w, fs::GENERATION, layout.generation_bytes, r.generation); + put8(w, layout.flag, 1); let work = p.fs_work; put32(q, 0, 7); @@ -467,7 +847,7 @@ pub(crate) fn encode_fs( put64(q, 0x1c, p.scene); put64(q, 0x24, r.activity[1]); put64(q, 0x2c, work + 0xb70); - put64(q, 0x34, p.scene + 0x54); + put64(q, 0x34, p.scene + layout.scene_field_off); put64(q, 0x3c, work + 0xbb0); put64(q, 0x44, work + 0xbb4); put64(q, 0x4c, r.qinfo[1]); @@ -478,17 +858,19 @@ pub(crate) fn encode_fs( put64(q, 0x7c, work + 0xa58); put64(q, 0x84, work + 0xbf0); put32(q, 0xa0, r.uuid); - inline_uma(q, 0x1b0, r, 1); + put32(q, fs::START_SCS, u32::from(RENDER_SCS_ENABLE && rt.scs)); + inline_uma(q, 0x1b0, r, 1, layout.inline_uma_engine_byte); timestamps( q, - 0x1ec, + layout.ts_start, work, r.qinfo[1], ts_va[2] != 0 || ts_va[3] != 0, r.uuid, 1, + layout.auxiliary, ); - let f = 0x288; + let f = layout.finalize; put32(q, f, 8); put32(q, f + 4, r.uuid); put64(q, f + 0xc, r.fw_stamp[1]); @@ -506,16 +888,37 @@ pub(crate) fn encode_fs( put64(q, f + 0x64, work + 0xa58); put64(q, f + 0x98, p.fs_seq + 0x1b0); put32(q, f + 0xa0, 0u32.wrapping_sub(f as u32)); - put64(q, f + 0xa5, work + 0xc60); - put32(q, f + 0xad, 1); - put8(q, f + 0xb1, 1); - put32(q, f + 0xb2, 0x71); - put32(q, f + 0xbc, 0x40000002); + put64(q, f + 0xa5, work + layout.completion as u64); + if layout.compact_finalize { + put32(q, f + 0xad, 0x71); + put32(q, f + 0xb4, work::op::END); + } else { + put32(q, f + 0xad, 1); + put8(q, f + 0xb1, 1); + put32(q, f + 0xb2, 0x71); + put32(q, f + 0xbc, work::op::END); + } } /// Complete attachment blocks include the count at the last word. The scheduler /// has validated full retained ranges; alignment is for firmware cache lines. pub(crate) fn render_attachments(q: &mut [u8], engine: usize, att: &[uapi::drm_asahi_attachment]) { + let finalize = if engine == 0 { + ta::FINALIZE + } else { + fs::FINALIZE + }; + render_attachments_for(q, engine, finalize, att); +} + +/// [`render_attachments`] with an explicit finalize-record offset for ABIs whose FS +/// microsequence finalize offset differs from [`fs::FINALIZE`]. +pub(crate) fn render_attachments_for( + q: &mut [u8], + engine: usize, + finalize: usize, + att: &[uapi::drm_asahi_attachment], +) { let base = if engine == 0 { 0x88 } else { 0xa8 }; for (i, a) in att.iter().enumerate().take(16) { let start = a.pointer & !127; @@ -527,39 +930,62 @@ pub(crate) fn render_attachments(q: &mut [u8], engine: usize, att: &[uapi::drm_a put16(q, off + 0xe, 1); } put32(q, base + 0x100, att.len().min(16) as u32); - let f = if engine == 0 { - ta::FINALIZE + 0x84 - } else { - fs::FINALIZE + 0xa4 - }; + let f = finalize + if engine == 0 { 0x84 } else { 0xa4 }; put8(q, f, u8::from(!att.is_empty())); } /// Base scene metadata in caller-owned storage. A full scene belongs to the /// retained slot and should not be placed on the kernel stack. pub(crate) fn fill_scene(r: &RenderRefs, p: &PassRefs, out: &mut [u8]) { - let Some(out) = out.get_mut(..scene::SIZE) else { + if out.len() < scene::ACTIVE_SIZE { return; - }; + } + let len = out.len().min(scene::SIZE); + let out = &mut out[..len]; out.fill(0); put64(out, 0, p.scene_user_gva); put64(out, 8, p.scratch_fw); - put64(out, 0x28, compact(r.scene_list)); + put64(out, 0x28, compact(scene_list_va(r, p))); put64(out, 0x40, p.scene + 0x200); put64(out, 0x500, r.uma_submitted); } /// Small scene header for direct writes into a zeroed retained firmware object. -#[allow(dead_code)] pub(crate) fn scene(r: &RenderRefs, p: &PassRefs, _n: u64) -> [u8; 0x80] { let mut out = [0u8; 0x80]; put64(&mut out, 0, p.scene_user_gva); put64(&mut out, 8, p.scratch_fw); - put64(&mut out, 0x28, compact(r.scene_list)); + put64(&mut out, 0x28, compact(scene_list_va(r, p))); put64(&mut out, 0x40, p.scene + 0x200); out } +/// Active scene prefix block (`0x300..0x380`: optional InitBM record + own-TA wait barrier) +/// for direct clean same-VM writes without zeroing dead gaps in the 2 KiB scene scratch image. +pub(crate) fn scene_prefix(r: &RenderRefs, ctx: u32, target: u32, init: bool) -> [u8; 0x80] { + let mut out = [0u8; 0x80]; + if init { + put( + &mut out, + 0, + &initbm(ctx, r.parameter_id, r.pb_mgr, target), + ); + } + put( + &mut out, + 0x40, + &barrier( + r.fw_stamp[0], + target, + 0x70, + target, + 0, + work::BarrierType::Stamp, + ), + ); + out +} + /// Populate the scene-owned InitBM and own-TA wait before exposing either work. pub(crate) fn scene_render( r: &RenderRefs, diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 5ee33d71432d1a..fc08739e9e6710 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -3,10 +3,14 @@ //! Serialized M4 execution over the shared Asahi frontend. //! //! A userspace submission retains all commands, mappings and inputs through its final fence. -//! One command at a time is encoded into one of two retained units, then published to the -//! classic engine queues. Reuse requires a complete wire receipt followed by replacement -//! by the other retired unit in the same UMA slot. TA and FS remain a paired publication -//! with the native explicit TA dependency. This total order satisfies Mesa's command barriers. +//! Each command is encoded into a retained unit, then published to the classic engine queues. +//! A render is published only with nothing else in flight, and nothing is published behind +//! it. Compute commands queue behind in-flight compute commands (up to +//! [`params::compute_flights`]), each in its own unit of UMA slot 1: the firmware runs its +//! compute queue in publication order, each command to its Finalize, so publication order is +//! execution order. A unit is reused only after a later publication fully retired (it +//! displaced the unit). TA and FS remain a paired publication with the native explicit TA +//! dependency. This total order satisfies Mesa's command barriers. //! Firmware failure retains every possibly reachable owner. Completions are signalled only //! after dropping the device lock. @@ -16,11 +20,11 @@ use kernel::{prelude::*, sync::Arc}; use super::channel::Channel; use super::command::{Command, ComputeCommand, RenderCommand}; -use super::encode::{self, ComputeRefs, Geometry, RenderRefs}; -use super::fw::channels::SubmitRecord; +use super::encode::{self, ComputeRefs, ComputeRt, Geometry, RenderRefs, StageRt}; +use super::fw::channels::{SubmitRecord, RING_SLOTS}; use super::fw::graph::{notifier_page, qstate}; use super::fw::work::{self, BarrierType}; -use super::hw::sizes; +use super::hw::{engine as engine_ids, sizes}; use super::job::{Completions, Job}; use super::slots::Claims; use super::{params, Firmware, Shared}; @@ -54,8 +58,9 @@ pub(crate) fn now_ns() -> u64 { ::ktime_get() as u64 } -/// Counter value carried by a native 25G83 submit-pipe record. -fn counter_ticks() -> u64 { +/// Counter value carried by a native 25G83 submit-pipe record (the 24 MHz counter of the +/// firmware's internal timestamps). +pub(crate) fn counter_ticks() -> u64 { #[cfg(target_arch = "aarch64")] { let value: u64; @@ -131,6 +136,157 @@ impl Progress { } } +/// Resolved in-flight producer target for a hardware ring barrier. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +struct WaitTarget { + stamp: u32, + /// True if the waited producer flight carries `InitBM` (buffer-manager initialization). + initbm: bool, +} + +/// Selects the hardware ring barrier type for a same-VM handoff. +/// +/// Unlike G15 (`g15/hw.rs: CROSS_ENGINE_HOLD` — "Never both type 0"), G16 (M4 25G83/26B123) +/// does not require a software-job hold on one cross-engine direction when neither side +/// carries `InitBM`. On G16, every stage (CDM, TA, FS) executes its `FINALIZE` +/// micro-sequence — flushing stage caches to the shared coherent fabric — before firmware +/// advances `fw_stamp`, so waiting on `fw_stamp` with `BarrierType::Stamp` (type 0) in both +/// directions (`fs2c` and `c2ta`/`c2fs`) avoids hold bubbles within one VM (same ASID and +/// UAT page tables). Zero-fault M4 J773g runs (13,873 `fs2c` and 20,506 `c2ta` type-0 +/// handoffs) confirm no GPU wedge or hang, while CTS synchronization / pipeline-barrier +/// coverage validates producer-to-consumer memory visibility. +/// +/// Keep `BarrierType::Hold` (type 1) whenever either producer or consumer carries `InitBM` +/// (checked against both the waited target and any live `InitBM` flight). Cross-VM switches, +/// recovery paths, and `query_access` CPU-timestamp waits drain `flights` completely first. +const fn cross_engine_barrier_type(producer_initbm: bool, consumer_initbm: bool) -> BarrierType { + BarrierType::from_stamp_only(!producer_initbm && !consumer_initbm) +} + +/// Whether a compute command of `vm` that runs shader-context scratch (SCS) work (`scs`), or +/// does not, must wait for compute flight `f` to retire before it is published. +/// +/// SCS compute (ray queries, and every compute command of a job with SCS scratch) shares the +/// compute engine only with SCS compute of its own VM. Each compute work item sets the +/// engine's SCS state in its register list, enabled for SCS work and disabled otherwise. An +/// SCS item that other compute overlaps is reported complete while its stores are still in +/// flight, and they land after its fence has signalled, also after its VM is gone. +fn scs_compute_conflict(f: &Flight, vm: &Arc, scs: bool) -> bool { + f.computes != 0 && (f.rt_compute != scs || (scs && !Arc::ptr_eq(&f.job.vm, vm))) +} + +/// Whether a render of `vm`, multisampled when `msaa`, must wait for render flight `f` to +/// retire before it is published. +/// +/// Every VM's render passes share the one firmware TA/FS queue pair. While passes of two VMs +/// are both published there and one of the VMs renders multisampled +/// (`VmStateInner::renders_msaa`), that VM's passes can lose coverage (uncovered or zero +/// pixels and samples, also in single-sampled passes that read its multisampled images) and +/// its fragment shaders can read VA 0. Ordering the two passes' TA and FS with ring barriers +/// does not prevent it; publishing one only after the other retired does. Passes of one VM, +/// and passes of VMs that never render multisampled, still share the queues. +fn msaa_render_conflict(f: &Flight, vm: &Arc, msaa: bool) -> bool { + f.renders != 0 + && !Arc::ptr_eq(&f.job.vm, vm) + && (msaa || vm.renders_msaa() || f.job.vm.renders_msaa()) +} + +/// Resolved ring-barrier placement for one render pass (legacy, `FRAGMENT_BARRIERS`, or +/// `DRM_ASAHI_RENDER_STAGE_PREFIXES`). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +struct RenderBarrierPlan { + early: bool, + ta_prev_wait: bool, + ta_fs_wait: Option, + fs_render_wait: Option, + ta_compute_wait: [Option; sizes::COMPUTE_PIPES], + fs_compute_wait: [Option; sizes::COMPUTE_PIPES], +} + +/// Computes TA/FS hardware ring barriers for a render command from its flags, prior render +/// FS stamp, resolved render waits (`fs_wait_render`, `ta_wait_fs`), resolved `[ta, fs]` +/// per-pipe compute wait stamps, and whether the immediately preceding in-flight render belongs +/// to a different VM (`cross_vm_prev`). +/// +/// Same-VM pipelined renders share one parameter-buffer / UMA slot, and cross-VM pipelined +/// renders use distinct UMA slots (`RENDER_UMA_SLOT + slot`) on the shared TA/FS pipes: TA(N) +/// always waits on TA(N-1) (`ta_prev_wait`, matching G15's `prev_barrier`) whenever +/// `ta_fs_wait` does not already wait on `prev_fs` (which dominates `prev_ta` via +/// `own_barrier`). Same-VM independent FS passes omit `fs_dep`, while `cross_vm_prev` forces +/// `fs_render_wait = Some(prev_fs)` (whenever `ta_fs_wait != Some(prev_fs)`) so cross-VM TA +/// overlaps the previous VM's FS without ever overlapping two VMs' FS/PB teardowns. +#[expect( + clippy::too_many_arguments, + reason = "Pure barrier-plan helper mirrors the exact render barrier inputs." +)] +fn plan_render_barriers( + flags: u32, + class_behind: bool, + early_tiling: bool, + prev_fs: u32, + fs_wait_render: Option, + ta_wait_fs: Option, + compute_waits: [[Option; sizes::COMPUTE_PIPES]; 2], + cross_vm_prev: bool, +) -> RenderBarrierPlan { + let staged = + flags & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES != 0; + let frag_only = + flags & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS != 0; + let no_render_barrier = fs_wait_render.is_none(); + let early = class_behind + && early_tiling + && if staged { + ta_wait_fs != Some(prev_fs) + } else { + frag_only || no_render_barrier + }; + let ta_fs_wait = if !class_behind { + None + } else if !early { + if !early_tiling { + Some(prev_fs) + } else if staged { + ta_wait_fs.or(Some(prev_fs)) + } else { + fs_wait_render.or(Some(prev_fs)) + } + } else if staged { + ta_wait_fs + } else { + None + }; + let ta_prev_wait = class_behind && ta_fs_wait != Some(prev_fs); + let effective_fs_wait = if cross_vm_prev && class_behind { + Some(prev_fs) + } else { + fs_wait_render + }; + let fs_render_wait = if class_behind + && (early || (cross_vm_prev && ta_fs_wait != Some(prev_fs))) + && effective_fs_wait != ta_fs_wait + { + effective_fs_wait + } else { + None + }; + let [ta_compute_wait, fs_wait] = compute_waits; + let mut fs_compute_wait = [None; sizes::COMPUTE_PIPES]; + for p in 0..sizes::COMPUTE_PIPES { + if fs_wait[p] != ta_compute_wait[p] { + fs_compute_wait[p] = fs_wait[p]; + } + } + RenderBarrierPlan { + early, + ta_prev_wait, + ta_fs_wait, + fs_render_wait, + ta_compute_wait, + fs_compute_wait, + } +} + /// Engine of the previous member. #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub(crate) enum Prev { @@ -152,11 +308,13 @@ pub(crate) struct Flight { pub(crate) count: usize, pub(crate) computes: u32, pub(crate) renders: u32, + /// Compute pipe (`0..COMPUTE_PIPES`) this flight was published to. + pub(crate) compute_pipe: u8, /// Compute: final FW stamp, ring end (exclusive) and ring position before the prefix. pub(crate) target: u32, pub(crate) head: u32, pub(crate) c_start: u32, - /// Render: final TA/FS stamps, ring ends and ring positions before the prefix. + /// Render: final TA/FS stamps, ring ends and ring positions. pub(crate) ta_target: u32, pub(crate) fs_target: u32, pub(crate) ta_head: u32, @@ -165,10 +323,17 @@ pub(crate) struct Flight { pub(crate) fs_start: u32, /// Channel producers (TA, FS, compute) after the prefix's records. pub(crate) rec: [u32; 3], - /// Compute member j's FW stamp target, and the FS target it waits on directly (0: none): - /// its predecessors in the prefix (for the compute-hang check). + /// Whether `Channel::Compute` read and completion cursors already passed `rec[2]` before + /// the shared submit ring could wrap past this flight. + pub(crate) chan_settled: bool, + /// Compute member j's FW stamp target, the FS target it waits on directly (0: none), and + /// its private UMA counter value after publication. pub(crate) cstamp: [u32; sizes::COMPUTE_SLOTS], pub(crate) cwait: [u32; sizes::COMPUTE_SLOTS], + pub(crate) csubmitted: [u64; sizes::COMPUTE_SLOTS], + /// Render member j's TA and FS FW stamp targets. + pub(crate) r_ta_stamp: [u32; sizes::RENDER_SLOTS], + pub(crate) r_fs_stamp: [u32; sizes::RENDER_SLOTS], /// Compute slots, pass slots and clustering buffers it holds. pub(crate) claims: Claims, /// A kill or recovery ended this prefix's VM: later prefixes of it fail with EIO. @@ -178,8 +343,31 @@ pub(crate) struct Flight { pub(crate) uma_submitted: u64, pub(crate) recovery_suspect: bool, pub(crate) recovery_started_ns: u64, + /// First time this suspect flight passed its stage/queue gates with unsettled receipts, and + /// how many consecutive unsettled polls have observed it since then. + pub(crate) gate_passed_ns: Option, + pub(crate) unsettled_polls: u32, /// Publication time, ns. pub(crate) published_ns: u64, + /// Published behind another flight. + pub(crate) behind: bool, + /// The PB epoch this render prefix uses (its own, or a reused allocator-slot epoch). + pub(crate) pb: Option>, + /// Its allocator slot (`0` or `1`, decoupled from `claims.pass[0]`). + pub(crate) pb_slot: u32, + /// Its allocator slot binding (`Pools::bind`). + pub(crate) pb_binding: u64, + /// Whether this render carries InitBM (priming renders always drain before pipelining). + pub(crate) initbm: bool, + /// Whether this flight publishes CPU-written command timestamps on retirement. + pub(crate) has_timestamps: bool, + /// Whether this flight runs ray-tracing or SCS-scratch compute (pinned to compute pipe 0). + pub(crate) rt_compute: bool, + /// Whether this flight includes any heavy-TA render pass (multi-layer or large tilemap). + pub(crate) heavy_render: bool, + /// Whether this flight includes a multisampled render pass; its VM is marked + /// (`VmStateInner::note_msaa_render`) once the flight becomes visible. + pub(crate) msaa: bool, } impl Flight { @@ -191,6 +379,7 @@ impl Flight { count: 0, computes: 0, renders: 0, + compute_pipe: 0, target: 0, head: 0, c_start: 0, @@ -201,14 +390,29 @@ impl Flight { ta_start: 0, fs_start: 0, rec: [0; 3], + chan_settled: false, cstamp: [0; sizes::COMPUTE_SLOTS], cwait: [0; sizes::COMPUTE_SLOTS], + csubmitted: [0; sizes::COMPUTE_SLOTS], + r_ta_stamp: [0; sizes::RENDER_SLOTS], + r_fs_stamp: [0; sizes::RENDER_SLOTS], claims: Claims::new(), doomed: false, uma_submitted: 0, recovery_suspect: false, recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, published_ns: 0, + behind: false, + pb: None, + pb_slot: 0, + pb_binding: 0, + initbm: false, + has_timestamps: false, + rt_compute: false, + heavy_render: false, + msaa: false, } } } @@ -220,16 +424,19 @@ impl Flight { struct Prefix { computes: u32, renders: u32, + compute_pipe: usize, prev: Prev, /// This prefix (re)initializes the PB with InitBM. initbm: bool, c_head: u32, ta_head: u32, fs_head: u32, - /// Last compute ordinal / last draw ordinal. + /// Last total compute ordinal, per-pipe compute ordinal, and draw ordinal. n: u64, + pipe_n: u64, draw: u64, last_ct: u32, + last_ta: u32, last_fs: u32, } @@ -241,8 +448,49 @@ enum PublicationError { Uncertain(Error), } +/// Why a publication pass stopped at a ready job without publishing it (`Stats::hold_causes`). +/// +/// A drain cause means the job waits for an empty engine; the others wait behind in-flight +/// work for headroom or ordering. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum HoldCause { + /// The job's VM failed, or a flight is doomed or suspect in a recovery. + DrainFailed, + /// A cold `InitBM` render is in flight. + DrainInitbm, + /// Compute behind render of another VM, render behind compute of another VM, an SCS + /// compute conflict, or a render beside another VM's render while one of the two VMs + /// renders multisampled. + DrainCross, + /// No warm PB/UMA allocator slot of the VM can take the render behind active flights. + DrainPb, + /// The TA wave window is full. + TaWave, + /// Flight, render pass or compute unit headroom. + Slot, + /// The job's dependency check failed: it fails once it reaches publication. + /// (`Engine::pick()` skips jobs still waiting for a dependency.) + Dependency, + /// Any other admission refusal behind in-flight work. + Other, +} + +impl HoldCause { + pub(crate) const COUNT: usize = 8; + pub(crate) const NAMES: [&'static str; Self::COUNT] = [ + "drain_failed", + "drain_initbm", + "drain_cross", + "drain_pb", + "ta_wave", + "slot", + "dependency", + "other", + ]; +} + /// Engine statistics, printed by `aurora-g16/stats`. -#[derive(Default)] +#[derive(Default, Zeroable)] pub(crate) struct Stats { pub(crate) pub_ns: u64, pub(crate) idle_from_ns: u64, @@ -291,12 +539,18 @@ pub(crate) struct Stats { /// Why ready jobs stayed unpublished: both flights published, a channel record unconsumed, /// no free slot. pub(crate) hold: [u64; 3], + /// `hold[0]` split by [`HoldCause`]. + pub(crate) hold_causes: [u64; HoldCause::COUNT], + /// Compute commands published behind in-flight ones. + pub(crate) behind: u64, + /// Most flights in flight at once. + pub(crate) max_flights: u64, } /// Host-side phase timers of publication and polling, on with `debug_flags` bit 49 /// (`Debug1`); printed as the `prof:` line of `aurora-g16/stats`. A measurement aid: nothing is /// timed while the flag is off. -#[derive(Default)] +#[derive(Default, Zeroable)] pub(crate) struct Prof { /// Published prefixes timed. pub(crate) prefixes: u64, @@ -351,17 +605,21 @@ struct Scratch { } impl Scratch { - fn new() -> Result { + #[inline(never)] + fn new_boxed() -> Result> { let z = |n| KVec::from_elem(0u8, n, GFP_KERNEL); - Ok(Self { - cw: z(work::compute::WORK_SIZE)?, - cq: z(work::compute::SEQ_SIZE)?, - ta: z(work::ta::WORK_SIZE)?, - tas: z(work::ta::SEQ_SIZE)?, - fs: z(work::fs::WORK_SIZE)?, - fss: z(work::fs::SEQ_SIZE)?, - scene: z(work::scene::SIZE)?, - }) + KBox::try_init( + try_init!(Self { + cw: z(work::compute::WORK_SIZE)?, + cq: z(work::compute::SEQ_SIZE)?, + ta: z(work::ta::WORK_SIZE)?, + tas: z(work::ta::SEQ_SIZE)?, + fs: z(work::fs::WORK_SIZE)?, + fss: z(work::fs::SEQ_SIZE)?, + scene: z(work::scene::ACTIVE_SIZE)?, + }), + GFP_KERNEL, + ) } } @@ -386,12 +644,17 @@ pub(crate) struct Engine { /// The device's shared state, for the transport-error latch; set by the first poll or /// submission. pub(crate) shared: Option>, - /// Host compute ordinal and draw ordinal of the last publication. + /// Authenticated GPU tick tuple captured by [`Firmware::retired_snapshot`] for the oldest + /// flight (`[start, end, 0, 0]` for compute; `[ta_start, ta_end, fs_start, fs_end]` for + /// render), reused by accounting without re-reading WC cells. + pub(crate) retired_ticks: [u64; 4], + /// Host compute ordinal, per-pipe compute ordinals, and draw ordinal of the last publication. pub(crate) ordinal: u64, + pub(crate) pipe_ordinal: [u64; sizes::COMPUTE_PIPES], pub(crate) draw: u64, /// Newest published receipts, the tail. - pub(crate) target: u32, - pub(crate) head: u32, + pub(crate) target: [u32; sizes::COMPUTE_PIPES], + pub(crate) head: [u32; sizes::COMPUTE_PIPES], pub(crate) ta_target: u32, pub(crate) fs_target: u32, pub(crate) ta_head: u32, @@ -399,32 +662,56 @@ pub(crate) struct Engine { /// Event counts at the tail's publication. pub(crate) events: u32, pub(crate) stage_seen: u32, - /// The compute queue / render queues were registered by a first record (`new_queue`). - pub(crate) queue_registered: bool, + /// The compute pipes / render queues were registered by a first record (`new_queue`). + pub(crate) queue_registered: [bool; sizes::COMPUTE_PIPES], + pub(crate) next_compute_pipe: u8, + /// Last VM id that published onto each compute pipe (warm per-VM `qinfo` affinity). + pub(crate) pipe_last_vm: [Option; sizes::COMPUTE_PIPES], + /// Monotonic last-use counter per compute pipe for LRU idle-pipe selection. + pub(crate) pipe_last_used: [u64; sizes::COMPUTE_PIPES], + pub(crate) pipe_use_seq: u64, + /// Transient bitmask of compute pipes being drained for handoff to a waiting job that has + /// no eligible pipe (e.g. a base-only VM limited to pipe 0). + pub(crate) handoff_avoid_pipes: u32, pub(crate) render_registered: bool, pub(crate) ta_registered: bool, /// A ready prefix waits only for a record's consumption: repoll sooner. pub(crate) chan_wait: bool, - /// Progress tracking of the oldest prefix. - pub(crate) progress_flight: u64, - pub(crate) progress: [Option; 3], - pub(crate) stats: Stats, + /// A ready same-VM pending job is blocked solely on flight, pass/compute slot, or work-ring + /// headroom (not cross-VM/InitBM drain, external fences, or CPU timestamp waits): repoll + /// sooner to refill freed slots promptly. + pub(crate) slot_wait: bool, + /// A ready same-VM render job is paused by `TA_WAVE_PASSES` pacing until TA advances. + pub(crate) ta_wave_wait: bool, + /// An EP 0x20 event arrived with a flight still settling its final receipt: repoll sooner. + pub(crate) short_repoll: bool, + /// An idle poll pass inside the housekeeping cadence skipped housekeeping: queue a backup + /// poll so it runs once the cadence elapses. + pub(crate) housekeeping_owed: bool, + /// A ready job is held behind flights that all belong to its own VM, for any cause but a + /// failure, a cross-VM overlap or a failed dependency: one of those flights retiring is + /// what releases it, so repoll soon instead of after `resnap_us`. + pub(crate) held_wait: bool, + /// Absolute deadline (`ktime_get_ns`) for busy-state same-queue horizon micro-coalescing + /// (0 when no batch is held). + pub(crate) coalesce_deadline_ns: u64, + /// Progress tracking of the oldest compute pipes `0..COMPUTE_PIPES` and render flights. + pub(crate) progress_flight: [u64; sizes::COMPUTE_PIPES + 1], + pub(crate) progress: [Option; sizes::COMPUTE_PIPES + 2], + /// Boxed with [`Self::prof`]: `Firmware` is built on the probe's stack. + pub(crate) stats: KBox, /// Phase timers (debug_flags bit 49). - pub(crate) prof: Prof, + pub(crate) prof: KBox, /// The `aurora-g16/stats` file. pub(crate) debugfs: Option>>>>, scratch: Option>, } impl Engine { + #[inline(never)] pub(crate) fn new() -> Result { // Wrapped native stamps are safe only while pending references fit within the - // signed half-window. This backend publishes exactly one command at a time, - // retires its full wire/owner receipt, then builds the next command/barrier. - // Do not add submission-ahead without revisiting the dependency lifetime proof. - if sizes::FLIGHTS != 1 { - return Err(EINVAL); - } + // signed half-window: at most FLIGHTS commands are published at once, far inside it. Ok(Self { pending: KVec::new(), flights: KVec::with_capacity(sizes::FLIGHTS, GFP_KERNEL)?, @@ -432,28 +719,41 @@ impl Engine { frozen: false, turn: 0, shared: None, + retired_ticks: [0; 4], ordinal: 0, + pipe_ordinal: [0; sizes::COMPUTE_PIPES], draw: 0, - target: 0, - head: 0, + target: [0; sizes::COMPUTE_PIPES], + head: [0; sizes::COMPUTE_PIPES], ta_target: 0, fs_target: 0, ta_head: 0, fs_head: 0, events: 0, stage_seen: 0, - queue_registered: false, + queue_registered: [false; sizes::COMPUTE_PIPES], + next_compute_pipe: 0, + pipe_last_vm: [None; sizes::COMPUTE_PIPES], + pipe_last_used: [0; sizes::COMPUTE_PIPES], + pipe_use_seq: 0, + handoff_avoid_pipes: 0, render_registered: false, ta_registered: false, chan_wait: false, - progress_flight: 0, - progress: [None; 3], - stats: Stats::default(), - prof: Prof::default(), + slot_wait: false, + ta_wave_wait: false, + short_repoll: false, + housekeeping_owed: false, + held_wait: false, + coalesce_deadline_ns: 0, + progress_flight: [0; sizes::COMPUTE_PIPES + 1], + progress: [None; sizes::COMPUTE_PIPES + 2], + stats: KBox::zeroed(GFP_KERNEL)?, + prof: KBox::zeroed(GFP_KERNEL)?, debugfs: None, // Allocate host encoder buffers before any submitted fence can depend on // the device mutex. Publication must never enter direct reclaim here. - scratch: Some(KBox::new(Scratch::new()?, GFP_KERNEL)?), + scratch: Some(Scratch::new_boxed()?), }) } @@ -603,12 +903,14 @@ impl Firmware { /// The single in-order Finalize frontier for each held M4 event. These cells are never /// reset after first publication, including across client VM switches and recovery. - pub(crate) fn recovery_snapshot(&self) -> Result<[u32; 3]> { - Ok([ - self.graph.render.fw_stamp[0].r32(0)?, - self.graph.render.fw_stamp[1].r32(0)?, - self.graph.compute.fw_stamp.r32(0)?, - ]) + pub(crate) fn recovery_snapshot(&self) -> Result<[u32; 2 + sizes::COMPUTE_PIPES]> { + let mut stage = [0u32; 2 + sizes::COMPUTE_PIPES]; + stage[0] = self.graph.render.fw_stamp[0].r32(0)?; + stage[1] = self.graph.render.fw_stamp[1].r32(0)?; + for (p, compute) in self.graph.compute.iter().enumerate() { + stage[2 + p] = compute.fw_stamp.r32(0)?; + } + Ok(stage) } /// Authenticate one firmware affected-work snapshot entry against its retained owner. @@ -618,45 +920,65 @@ impl Firmware { flags: u32, event: u32, target: u32, - stage: [u32; 3], + stage: [u32; 2 + sizes::COMPUTE_PIPES], ) -> Result { - if flags & 1 != 0 - && super::recovery::logic::last_retired_target( - &self.recovery.last_retired, - event, - target, - ) - { + if flags & 1 != 0 && self.recovery.last_retired.contains(event, target) { // A notification may follow the full receipt. It names the retained old // owner, not the next command that happens to occupy the flight list. return Ok(()); } - let f = self.engine.flights.first_mut().ok_or(ENOENT)?; - let matches = match event { - 15 => f.computes != 0 && f.target == target, - 0x70 => f.renders != 0 && f.ta_target == target, - 0x71 => f.renders != 0 && f.fs_target == target, - _ => false, - }; - if !matches || flags & 1 == 0 { + // The named owner: the oldest flight, or with compute/render queued behind it a later one. + let compute_pipe = work::compute::pipe_of_event(event); + let f = self + .engine + .flights + .iter_mut() + .find(|f| match event { + 0x70 => { + f.renders != 0 + && f.r_ta_stamp[..(f.renders as usize).min(f.r_ta_stamp.len())] + .contains(&target) + } + 0x71 => { + f.renders != 0 + && f.r_fs_stamp[..(f.renders as usize).min(f.r_fs_stamp.len())] + .contains(&target) + } + _ => compute_pipe.is_some_and(|pipe| { + f.computes != 0 + && f.compute_pipe as usize == pipe + && f.cstamp[..(f.computes as usize).min(f.cstamp.len())].contains(&target) + }), + }) + .ok_or(ENOENT)?; + if flags & 1 == 0 { return Err(ENOENT); } - if flags & 9 == 9 - && f.renders != 0 - && !super::poll::stamp_reached(stage[0], f.ta_target, self.engine.ta_target) - { - let k = f.claims.pass[0] as usize; - let pass = f.job.resources.render()?.passes.get(k).ok_or(EINVAL)?; - let bytes = pass.ta_work.r64(work::ta::TPC_BYTES)?; - if bytes == 0 || bytes > pass.tpc.size as u64 { - return Err(ERANGE); + if flags & 9 == 9 && f.renders != 0 { + let mut cleaned = false; + let count = (f.renders as usize).min(f.r_ta_stamp.len()); + for m in 0..count { + if super::poll::stamp_reached(stage[0], f.r_ta_stamp[m], self.engine.ta_target) { + continue; + } + let k = f.claims.pass[m] as usize; + let pass = f.job.resources.render_pass(k)?; + let bytes = pass.ta_work.r64(work::ta::TPC_BYTES)?; + if bytes == 0 || bytes > pass.tpc.size as u64 { + return Err(ERANGE); + } + pass.tpc.fill(0, 0, bytes as usize)?; + cleaned = true; + } + if cleaned { + wmb(); } - pass.tpc.fill(0, 0, bytes as usize)?; - wmb(); } f.doomed = true; f.recovery_suspect = true; f.recovery_started_ns = now_ns(); + f.gate_passed_ns = None; + f.unsettled_polls = 0; Ok(()) } @@ -664,23 +986,31 @@ impl Firmware { /// in the snapshot. Keep it until either its full receipt or its passed-abort proof. pub(crate) fn recovery_prepare_suspects( &mut self, - stage: [u32; 3], + stage: [u32; 2 + sizes::COMPUTE_PIPES], _event: u32, fault_asid: Option, ) -> Result { - let Some(f) = self.engine.flights.first_mut() else { - return Ok(()); - }; let reached = super::recovery::logic::stamp_reached; - let unfinished = (f.computes != 0 && !reached(stage[2], f.target, self.engine.target)) - || (f.renders != 0 - && (!reached(stage[0], f.ta_target, self.engine.ta_target) - || !reached(stage[1], f.fs_target, self.engine.fs_target))); - if unfinished { - f.recovery_suspect = true; - f.recovery_started_ns = now_ns(); - if fault_asid.is_some_and(|asid| asid >= 1 && asid == f.job.vm.slot) { - f.doomed = true; + let (target, ta_target, fs_target) = ( + self.engine.target, + self.engine.ta_target, + self.engine.fs_target, + ); + // Every unfinished flight, including compute queued behind the oldest on either pipe. + for f in self.engine.flights.iter_mut() { + let pipe = (f.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + let unfinished = (f.computes != 0 && !reached(stage[2 + pipe], f.target, target[pipe])) + || (f.renders != 0 + && (!reached(stage[0], f.ta_target, ta_target) + || !reached(stage[1], f.fs_target, fs_target))); + if unfinished { + f.recovery_suspect = true; + f.recovery_started_ns = now_ns(); + f.gate_passed_ns = None; + f.unsettled_polls = 0; + if fault_asid.is_some_and(|asid| asid >= 1 && asid == f.job.vm.slot) { + f.doomed = true; + } } } Ok(()) @@ -705,6 +1035,7 @@ impl Firmware { } self.engine.pending.push(job.clone(), GFP_NOWAIT)?; job.progress.set_pending(true); + job.origin.mark_enqueued(); let q = &job.queue; let owned = self.engine.queue_published(&job) + self @@ -733,25 +1064,156 @@ impl Firmware { self.service_power()?; self.drain_rings()?; self.check_hangs(done)?; + self.publish_checked(done) + } + + /// [`Self::publish`] for a fast submit or poll pass that already drained/retired under this + /// device lock; verifies RTKit/transport liveness without repeating the 1 ms `Session::check` + /// register and UAT table walk on every command. + pub(crate) fn publish_checked(&mut self, done: &mut Completions) -> Result { + if self + .session + .shared + .sleeping + .load(core::sync::atomic::Ordering::Acquire) + { + return Ok(()); + } + self.session.transport()?; // The initial G16 backend deliberately serializes hardware publication. Stronger // ordering satisfies Mesa's barriers while slot displacement and cache ownership // stay explicit. Never enable G15's submit-ahead policy on the M4 wire by accident. let mut result = Ok(()); + let mut pending_rings = 0u8; + let mut batch_published = 0u64; self.engine.chan_wait = false; + self.engine.slot_wait = false; + self.engine.ta_wave_wait = false; + self.engine.held_wait = false; + self.engine.handoff_avoid_pipes = 0; + self.engine.coalesce_deadline_ns = 0; while self.recovery.failed().is_none() && !self.engine.frozen && !self.engine.pending.is_empty() { + self.engine.handoff_avoid_pipes = 0; let Some(index) = self.engine.pick() else { break; }; - let job = self.engine.pending[index].clone(); + let mut job = self.engine.pending[index].clone(); // Even a failed job may have an earlier command in flight. An aggregate - // error fence must not race that command's access to user buffers. - if !self.engine.flights.is_empty() { - self.engine.stats.hold[0] += 1; - break; + // error fence must not race that command's access to user buffers: healthy + // non-InitBM commands (compute or warm-PB render of any VM) queue behind + // active flights; when the head queue cannot queue behind (e.g. its class + // hit its flight cap), still allow another ready queue to run concurrently + // while preserving per-queue FIFO, unless the head job itself requires + // `flights` to drain to empty first (unprimed cold InitBM render, failed + // VM, or recovery/InitBM in flight). + let mut ta_pending: Option = None; + if !self.engine.flights.is_empty() + && !self.can_queue_behind_with_ta(&job, &mut ta_pending) + { + if self.needs_engine_drain(&job) { + self.note_hold(&job, true, 0); + break; + } + // If the selected head waiter has no eligible compute pipe (e.g. a base-only + // VM limited to pipe 0 while an incumbent refills pipe 0, or a 9th VM when all + // pipes are occupied), let one compatible pipe drain for handoff while other + // pipes continue dispatching. + self.engine.handoff_avoid_pipes = self + .compute_handoff_pipe(&job) + .map_or(0, |pipe| 1u32 << pipe); + let ta_val = *ta_pending.get_or_insert_with(|| self.ta_pending_passes()); + let ta_wave_paused = ta_val >= self.active_ta_wave_cap(); + let mut alt: Option = None; + for (i, cand) in self.engine.pending.iter().enumerate() { + if i == index { + continue; + } + // Fast O(1) skip for blocked head-queue followers: `Engine::pick` chose the + // earliest pending job of `job.queue`, so later jobs of the same queue are + // FIFO-blocked unless an independent non-query compute may bypass TA-wave + // paused renders. + if i > index + && Arc::ptr_eq(&cand.queue, &job.queue) + && !(ta_wave_paused + && matches!( + command(cand, cand.progress.sent()), + Some(Command::Compute(c)) if !c.query_access + )) + { + continue; + } + if !self.can_queue_behind_with_ta(cand, &mut ta_pending) { + continue; + } + // Preserve per-queue FIFO: never jump a later job of a queue ahead + // of an earlier pending job of the same queue, except when TA wave + // pacing pauses earlier ready renders and an independent non-query + // compute (such as pre-gfx culling) has all dependencies published + // (`can_queue_behind` already checked `check_command_dependencies`). + let same_queue_blocked = self.engine.pending[..i].iter().any(|earlier| { + if !Arc::ptr_eq(&earlier.queue, &cand.queue) { + return false; + } + let allow_pre_gfx = ta_wave_paused + && matches!( + command(cand, cand.progress.sent()), + Some(Command::Compute(c)) if !c.query_access + ) + && matches!( + command(earlier, earlier.progress.sent()), + Some(Command::Render(r)) + if ta_val >= self.ta_wave_cap_for(r.is_heavy_ta()) + ) + && !self.needs_engine_drain(earlier) + && earlier + .check_command_dependencies(earlier.progress.sent()) + .is_ok(); + !allow_pre_gfx + }); + if same_queue_blocked { + continue; + } + let better = match alt { + None => true, + Some(best) => { + let prev = &self.engine.pending[best]; + cand.queue.priority < prev.queue.priority + || (cand.queue.priority == prev.queue.priority + && cand.queue.turn.load(Ordering::Relaxed) + < prev.queue.turn.load(Ordering::Relaxed)) + } + }; + if better { + alt = Some(i); + } + } + match alt { + Some(i) => job = self.engine.pending[i].clone(), + None => { + self.engine.handoff_avoid_pipes = 0; + self.engine.slot_wait = self + .engine + .pending + .iter() + .any(|cand| self.blocked_on_slot_headroom(cand)); + self.engine.ta_wave_wait = self.engine.pending.iter().any(|cand| { + matches!( + command(cand, cand.progress.sent()), + Some(Command::Render(r)) + if ta_val >= self.ta_wave_cap_for(r.is_heavy_ta()) + ) && !self.needs_engine_drain(cand) + && cand + .check_command_dependencies(cand.progress.sent()) + .is_ok() + }); + self.note_hold(&job, false, ta_val); + break; + } + } } if job.vm.status.get() != 0 { self.engine.unpend(&job); @@ -772,7 +1234,7 @@ impl Firmware { } } Some(Command::Render(_)) => { - if self.slots.render_exhausted() { + if self.slots.render_exhausted() || self.pools.exhausted() { Some((super::command::RENDER, EIO)) } else if super::recovery::logic::next_ordinal(self.engine.draw).is_none() { Some((super::command::RENDER, EOVERFLOW)) @@ -782,6 +1244,43 @@ impl Firmware { } None => None, }; + // A VM whose own units were all quarantined (without the class being exhausted) + // cannot run compute again: cancel its queue like an exhausted class would. + if class_error.is_none() + && matches!(command(&job, job.progress.sent()), Some(Command::Compute(_))) + && job + .resources + .compute_slot_mask() + .is_ok_and(|mask| self.slots.compute_exhausted_in_mask(mask)) + { + self.engine.unpend(&job); + let _ = job.mark_terminal_retired(); + complete(done, &job, Err(ECANCELED)); + continue; + } + // A VM whose render pass slots were all quarantined, or that cannot acquire a + // physical PB allocator slot because the alternate slot is quarantined and the + // active slot belongs to another VM, cannot render again: cancel its queue + // immediately instead of spinning on EAGAIN and stalling unrelated compute. + if class_error.is_none() + && matches!(command(&job, job.progress.sent()), Some(Command::Render(_))) + && (job.resources.pb_slot_mask().is_ok_and(|(mask, home)| { + self.pools.exhausted_for_mask_mode( + &job.vm, + mask, + home, + job.resources.render_scs(), + ) + }) || job + .resources + .render_passes() + .is_ok_and(|n| self.slots.render_exhausted_within(n))) + { + self.engine.unpend(&job); + let _ = job.mark_terminal_retired(); + complete(done, &job, Err(ECANCELED)); + continue; + } if let Some((class, error)) = class_error { self.mark_class_unavailable(class, error); self.engine.unpend(&job); @@ -793,7 +1292,10 @@ impl Firmware { } match job.check_command_dependencies(job.progress.sent()) { Ok(()) => {} - Err(e) if e == EAGAIN => break, + Err(e) if e == EAGAIN => { + self.engine.handoff_avoid_pipes = 0; + break; + } Err(e) => { self.engine.unpend(&job); let _ = job.mark_terminal_retired(); @@ -801,16 +1303,46 @@ impl Firmware { continue; } } - self.engine.turn += 1; - job.queue.turn.store(self.engine.turn, Ordering::Relaxed); - match self.publish_prefix(&job, done) { + let pub_res = self.publish_prefix(&job, done, &mut pending_rings); + self.engine.handoff_avoid_pipes = 0; + match pub_res { Ok(()) => { + self.engine.turn += 1; + job.queue.turn.store(self.engine.turn, Ordering::Relaxed); + batch_published += 1; self.recovery.publication_wait_deadline = None; if job.progress.sent() == job.progress.count() { self.engine.unpend(&job); // fully published } + // Ring TA/FS immediately once a render wave fills the active TA wave window so + // the GPU starts tiling right away instead of waiting behind another loop + // iteration or an alt-class compute publication. + if pending_rings & ((1u8 << (Channel::Fs as u8)) | (1u8 << (Channel::Ta as u8))) + != 0 + && self.ta_pending_passes() >= self.active_ta_wave_cap() + { + if let Err(e) = self.flush_doorbells(&mut pending_rings) { + dev_err!( + self.graph.dev.as_ref(), + "G16: render wave doorbell ring failed after visibility began ({:?})\n", + e + ); + self.fail_stop(EIO, done); + result = Err(EIO); + break; + } + } continue; } + Err(PublicationError::Unpublished(e)) + if e == EAGAIN && !self.engine.flights.is_empty() => + { + // Waits for an in-flight command: its retirement repolls publication, + // and the flights' own deadlines apply. + let i = if self.engine.chan_wait { 1 } else { 2 }; + self.engine.stats.hold[i] += 1; + break; + } Err(PublicationError::Unpublished(e)) if e == EAGAIN => { let i = if self.engine.chan_wait { 1 } else { 2 }; self.engine.stats.hold[i] += 1; @@ -830,6 +1362,12 @@ impl Firmware { .0 }); if super::recovery::logic::expired(now_ns(), deadline) { + // `self.engine.flights.is_empty()` already implies `pending_rings == 0` + // today, but flush defensively so records posted earlier in the batch + // cannot be stranded if this error ever stops being fatal. + if pending_rings != 0 { + let _ = self.flush_doorbells(&mut pending_rings); + } return Err(ETIMEDOUT); } break; @@ -840,6 +1378,7 @@ impl Firmware { complete(done, &job, Err(e)); } Err(PublicationError::Uncertain(e)) => { + pending_rings = 0; self.engine.unpend(&job); // A counter or producer may be visible: retain and stop globally. dev_err!( @@ -856,6 +1395,24 @@ impl Firmware { } } } + if batch_published > 1 { + self.engine.stats.grouped = self + .engine + .stats + .grouped + .saturating_add(batch_published - 1); + } + if pending_rings != 0 { + if let Err(e) = self.flush_doorbells(&mut pending_rings) { + dev_err!( + self.graph.dev.as_ref(), + "G16: batched doorbell ring failed after visibility began ({:?})\n", + e + ); + self.fail_stop(EIO, done); + result = Err(EIO); + } + } if !self.engine.chan_wait { self.recovery.publication_wait_deadline = None; } @@ -865,200 +1422,2092 @@ impl Firmware { result } - /// Whether some of `job`'s commands were published: such a job is retained after a - /// fail-stop. - pub(crate) fn job_partly_published(&self, job: &Job) -> bool { - job.progress.sent() != 0 + /// Rings each submit channel touched during a publication batch once, waking Compute + /// first so pre-gfx compute starts immediately ahead of TA barriers while preserving + /// FS-before-TA doorbell order for render batches. + fn flush_doorbells(&mut self, pending_rings: &mut u8) -> Result { + let mask = core::mem::take(pending_rings); + for channel in [Channel::Compute, Channel::Fs, Channel::Ta] { + if mask & (1u8 << (channel as u8)) != 0 { + self.session.ring(channel)?; + } + } + Ok(()) } - /// Addresses and cumulative allocator state of the selected retained render unit. - fn render_refs(&mut self, k: usize, job: &Job, draw: u64) -> Result<(RenderRefs, bool)> { - let generation = job.vm.generation; - let arena = job.resources.render()?; - let mut a = arena.pools.prepare(k, draw)?; - let epoch = job.resources.pb(job.progress.sent() as usize)?; - epoch.prepare(k, arena.pools.heap_gva(k)?)?; - a.pb_mgr = epoch.manager.va; - a.mgr_misc = epoch.misc.va; - let r = &self.graph.render; - let stage = draw.checked_mul(2).ok_or(EOVERFLOW)?; - Ok(( - RenderRefs { - notifier: r.notifier.va, - legacy_empty: r.legacy_empty.va, - qinfo: [r.qinfo[0].va, r.qinfo[1].va], - user_stamp: [ - r.notifier.va + notifier_page::TA_STAMP as u64, - r.notifier.va + notifier_page::FS_STAMP as u64, - ], - fw_stamp: [r.fw_stamp[0].va, r.fw_stamp[1].va], - uma_mgr: a.uma_mgr, - uma_aux: a.uma_aux, - uma_gpu: a.uma_gpu, - pb_mgr: a.pb_mgr, - scene_list: a.scene_list, - mgr_misc: a.mgr_misc, - pb_init_blocks: a.init_blocks, - parameter_id: a.parameter_id, - generation, - activity: [self.init.ta_activity.va + 4, self.init.fs_activity.va + 8], - counter: [stage, stage - 1], - uma_submitted: a.uma_submitted, - uuid: (draw as u32).wrapping_add(1), - usc_base: job.queue.usc_base, - }, - a.init_buffer, - )) + /// Whether render `r` of `vm` may be published beside the flights in flight + /// ([`msaa_render_conflict`]). Every member of a prefix is checked, not only its first. + fn msaa_member_allowed(&self, vm: &Arc, r: &RenderCommand) -> bool { + !self + .engine + .flights + .iter() + .any(|f| msaa_render_conflict(f, vm, r.is_multisampled())) } - /// Publishes the next command of `job`. All images and ring entries precede the host - /// producer writes and queue kicks. EAGAIN defers while storage/channel state is held; - /// The error records whether firmware may see a counter/producer update, independently - /// of errno; unpublished EIO is still an ordinary job failure. - fn publish_prefix( - &mut self, - job: &Arc, - done: &mut Completions, - ) -> core::result::Result<(), PublicationError> { - let mut f = Flight::new(job.clone()); - let mut visible = false; - let result = self.publish_prefix_into(job, &mut f, &mut visible); - match result { - Err(e) if !visible => { - // Never published: its storage is free again, and horizon jobs taken into it - // fail with it. - self.slots.release(&mut f.claims); - for j2 in f.group.iter() { - complete(done, j2, Err(e)); - } - Err(PublicationError::Unpublished(e)) + /// Whether `job` requires `self.engine.flights` to drain to empty before it can + /// publish (so `alt`-class bypass must not keep refilling the engine ahead of it). + fn needs_engine_drain(&self, job: &Arc) -> bool { + let cmd = command(job, job.progress.sent()); + let is_render = matches!(cmd, Some(Command::Render(_))); + let is_compute = matches!(cmd, Some(Command::Compute(_))); + let is_rt_compute = is_compute + && (job.resources.compute_scs() + || matches!(cmd, Some(Command::Compute(c)) if c.is_rt())); + let is_msaa_render = matches!(cmd, Some(Command::Render(r)) if r.is_multisampled()); + job.vm.status.get() != 0 + || self.engine.flights.iter().any(|f| { + f.doomed + || f.recovery_suspect + || f.initbm + || (is_compute && scs_compute_conflict(f, &job.vm, is_rt_compute)) + || (is_render && msaa_render_conflict(f, &job.vm, is_msaa_render)) + || (((is_compute && f.renders != 0) || (is_render && f.computes != 0)) + && !Arc::ptr_eq(&f.job.vm, &job.vm)) + }) + || (is_render && !self.render_can_pipeline(job)) + } + + /// Whether `job`'s render can reuse a warm PB/UMA allocator slot of its VM behind active + /// flights, without the drain that a fresh `InitBM` epoch needs. + fn render_can_pipeline(&self, job: &Arc) -> bool { + job.resources + .pb_slot_mask() + .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) + .is_ok_and(|(mask, home, blocks)| { + self.pools.can_pipeline_in_mask_blocks_mode( + &job.vm, + mask, + home, + blocks, + job.resources.render_scs(), + ) + }) + } + + /// Why a publication pass stopped at `job`: `drain` when [`Self::needs_engine_drain`] + /// held it, otherwise the first refusal of [`Self::can_queue_behind_with_ta`] that + /// applies, with `ta_pending` from that check. Of the drain causes, a failure, an `InitBM` + /// flight and the PB check are tested directly; what remains of `needs_engine_drain()` is a + /// cross-VM or SCS overlap. + fn hold_cause(&self, job: &Arc, drain: bool, ta_pending: usize) -> HoldCause { + let render = command(job, job.progress.sent()); + if drain { + if job.vm.status.get() != 0 + || self + .engine + .flights + .iter() + .any(|f| f.doomed || f.recovery_suspect) + { + HoldCause::DrainFailed + } else if self.engine.flights.iter().any(|f| f.initbm) { + HoldCause::DrainInitbm + } else if matches!(render, Some(Command::Render(_))) && !self.render_can_pipeline(job) { + HoldCause::DrainPb + } else { + HoldCause::DrainCross } - Err(e) => Err(PublicationError::Uncertain(e)), - Ok(()) => Ok(()), + } else if job.check_command_dependencies(job.progress.sent()).is_err() { + HoldCause::Dependency + } else if matches!(render, Some(Command::Render(r)) + if ta_pending >= self.ta_wave_cap_for(r.is_heavy_ta())) + { + HoldCause::TaWave + } else if self.blocked_on_slot_headroom(job) { + HoldCause::Slot + } else { + HoldCause::Other } } - fn publish_prefix_into( - &mut self, - job: &Arc, - f: &mut Flight, - visible: &mut bool, - ) -> Result { - if !self.engine.flights.is_empty() { - return Err(EAGAIN); + /// Counts a publication pass that stopped at the ready `job` behind in-flight work, and + /// marks it [`Engine::held_wait`] when only its own VM's flights hold it. + fn note_hold(&mut self, job: &Arc, drain: bool, ta_pending: usize) { + let cause = self.hold_cause(job, drain, ta_pending); + let s = &mut self.engine.stats; + s.hold[0] += 1; + s.hold_causes[cause as usize] += 1; + if !matches!( + cause, + HoldCause::DrainFailed | HoldCause::DrainCross | HoldCause::Dependency + ) && self + .engine + .flights + .iter() + .all(|f| Arc::ptr_eq(&f.job.vm, &job.vm)) + { + self.engine.held_wait = true; } - let index = job.progress.sent(); - let cmd = command(job, index).ok_or(EINVAL)?; - let render = matches!(cmd, Command::Render(_)); - if job.vm.status.get() != 0 { - return Err(EIO); + } + + /// Whether `job` is ready to run without an engine drain but currently blocked solely on + /// flight-depth or pass/compute-slot headroom (not on InitBM/recovery drain, external sync + /// dependencies, or CPU timestamp-publish waits). + fn blocked_on_slot_headroom(&self, job: &Arc) -> bool { + let e = &self.engine; + if e.flights.is_empty() || self.needs_engine_drain(job) { + return false; } - if if render { - self.slots.render_exhausted() - } else { - self.slots.compute_exhausted() - } { - return Err(EIO); + let sent = job.progress.sent(); + if job.check_command_dependencies(sent).is_err() { + return false; } - let channels: &[Channel] = if render { - &[Channel::Fs, Channel::Ta] - } else { - &[Channel::Compute] - }; - for &channel in channels { - let pipe = self.channels.channel(channel); - let producer = self.channels.producer(channel); - if pipe.read()? != producer - || pipe.completion()? != producer - || pipe.write()? != producer - { - self.engine.chan_wait = true; - return Err(EAGAIN); + if e.flights.len() >= super::hw::sizes::FLIGHTS { + return true; + } + match command(job, sent) { + Some(Command::Compute(c)) => { + let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); + let scs = job.resources.compute_scs() || c.is_rt(); + compute_count > 0 + && !self.slots.compute_exhausted() + && (compute_count >= params::compute_flights() + || job + .resources + .compute_slot_mask() + .is_ok_and(|mask| !self.has_compute_pipe_for_vm(&job.vm, mask, scs))) } + Some(Command::Render(_)) => { + let render_count: usize = e.flights.iter().map(|f| f.renders as usize).sum(); + render_count > 0 + && !self.slots.render_exhausted() + && !self.pools.exhausted() + && (render_count >= params::render_flights() + || job + .resources + .render_passes() + .is_ok_and(|passes| !self.slots.pass_available(passes))) + } + None => false, } - if self.engine.scratch.is_none() { - return Err(EIO); + } + + /// Unfinished TA passes across active render flights. Returns immediately without reading + /// WC memory when total active render passes are already below `TA_WAVE_PASSES`. + pub(crate) fn ta_pending_passes(&self) -> usize { + let active_renders: usize = self + .engine + .flights + .iter() + .map(|f| f.renders as usize) + .sum(); + if active_renders < super::hw::sizes::TA_WAVE_PASSES { + return active_renders; } - self.engine.stats.prep_from_ns = now_ns(); - let mut prefix = Prefix { - n: self.engine.ordinal, - draw: self.engine.draw, - c_head: self.graph.compute.qstate.r32(qstate::WRITE)?, - ta_head: self.graph.render.qstate[0].r32(qstate::WRITE)?, - fs_head: self.graph.render.qstate[1].r32(qstate::WRITE)?, - ..Default::default() + let Ok(obs) = self.graph.render.fw_stamp[0].r32(0) else { + return active_renders; }; - if prefix.c_head >= 256 || prefix.ta_head >= 256 || prefix.fs_head >= 256 { - return Err(super::boot::eproto()); - } - f.c_start = prefix.c_head; - f.ta_start = prefix.ta_head; - f.fs_start = prefix.fs_head; - match cmd { - Command::Compute(c) => self.prefix_compute(job, c, &mut prefix, f, false)?, - Command::Render(r) => { - let geometry = Geometry::new(&r.cmd, 0); - if job.resources.render()?.passes.iter().all(|slot| { - geometry - .validate_capacity(slot.tpc.size as u64, slot.tilemap.size as u64) - .is_err() - }) { - return Err(E2BIG); + let tail = self.engine.ta_target; + let mut pending = 0usize; + for f in &self.engine.flights { + for &stamp in &f.r_ta_stamp[..(f.renders as usize).min(f.r_ta_stamp.len())] { + if !super::recovery::logic::stamp_reached(obs, stamp, tail) { + pending += 1; } - let k = self - .slots - .pick_pass(job.resources.render()?, &geometry, 0) - .ok_or(EAGAIN)?; - f.claims.pass[0] = k as u32; - f.claims.pass_mask = 1 << k; - self.slots.pass_busy |= 1 << k; - self.prefix_render(job, r, &mut prefix, f)?; } } - f.first = index as usize; - f.count = 1; - f.computes = prefix.computes; - f.renders = prefix.renders; - f.target = prefix.last_ct; - f.ta_target = if render { - encode::stamp(prefix.draw) + pending + } + + /// Adaptive TA wave window for a candidate render pass: conservative `TA_WAVE_PASSES` (4) + /// when either the candidate or any active render flight is heavy (multi-layer or tilemap + /// above `TA_LIGHT_TILEMAP_BYTES`), and `TA_WAVE_PASSES_LIGHT` (8) for light single-layer + /// render bursts. + fn ta_wave_cap_for(&self, cand_heavy: bool) -> usize { + if cand_heavy + || self + .engine + .flights + .iter() + .any(|fl| fl.renders != 0 && fl.heavy_render) + { + super::hw::sizes::TA_WAVE_PASSES } else { - 0 - }; - f.fs_target = prefix.last_fs; - f.head = prefix.c_head; - f.ta_head = prefix.ta_head; - f.fs_head = prefix.fs_head; - if self.recovery_pending()? { - return Err(EAGAIN); + super::hw::sizes::TA_WAVE_PASSES_LIGHT } - if render { - job.resources - .pb(index as usize)? - .check_assignment(f.claims.pass[0] as usize)?; + } + + /// Active TA wave window across in-flight renders and pending render heads, used for + /// immediate wave doorbell flushes and `ta_wave_ready()` hysteresis. + pub(crate) fn active_ta_wave_cap(&self) -> usize { + if self + .engine + .flights + .iter() + .any(|fl| fl.renders != 0 && fl.heavy_render) + || self.engine.pending.iter().any(|cand| { + matches!( + command(cand, cand.progress.sent()), + Some(Command::Render(r)) if r.is_heavy_ta() + ) + }) + { + super::hw::sizes::TA_WAVE_PASSES + } else { + super::hw::sizes::TA_WAVE_PASSES_LIGHT } - // Reserve lifetime ownership before any counter or producer becomes reachable. - job.vm.vm.mark_binding_published()?; - self.slots.hold_vm(&f.claims, &job.vm)?; - self.slots.publish(&f.claims)?; - // Even a failed first store may have become visible. From this boundary preserve - // every owner and return explicit uncertainty rather than guessing from errno. - *visible = true; - let publication = (|| -> Result { + } + + /// Whether `job`'s next command may be published behind the flights in flight: + /// + /// - Compute queues behind healthy non-InitBM compute and render flights of its own VM + /// (up to [`params::compute_flights`] active computes), each in its own + /// `ComputeSlot` and hardware UMA slot (`COMPUTE_UMA_SLOT + index`), unless `query_access` + /// is set and a same-queue predecessor in its compute or render barrier prefix has + /// CPU-published timestamp outputs that have not retired yet + /// (`DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS` clears `query_access`). + /// - Render queues behind healthy non-InitBM render flights of any VM or same-VM compute + /// flights (up to [`params::render_flights`] active renders), rotating `PassSlot` + /// (`0..RENDER_SLOTS`) while reusing that VM's warm PB/UMA allocator slot + /// (`Pools::can_pipeline_within`, each owning its own hardware UMA slot + /// `RENDER_UMA_SLOT + slot`). Hardware barriers on the CDM/TA/FS rings preserve exact + /// same-engine, cross-engine, and cross-VM FS ordering while allowing cross-VM TA to + /// overlap the preceding VM's FS. + /// - Cross-VM compute/render overlap is disallowed in both directions so a long compute + /// dispatch from one client cannot starve another client's fragment shading into a + /// firmware DM1 timeout. Cold InitBM priming renders and every failure or recovery path + /// still drain the engine first. + /// - Cross-VM non-SCS compute runs concurrently across disjoint per-VM firmware workqueues + /// (`graph.compute[0..COMPUTE_PIPES]`): two different VMs/ASIDs are never queued into the + /// same in-flight `qinfo`, avoiding cross-VM engine drains without sharing an active + /// workqueue ring. SCS/RT compute still drains against non-SCS or other-VM compute. + fn can_queue_behind(&self, job: &Arc) -> bool { + let mut ta_pending = None; + self.can_queue_behind_with_ta(job, &mut ta_pending) + } + + /// [`Self::can_queue_behind`] with an optional caller-hoisted cache of + /// [`Self::ta_pending_passes`] so scanning many pending jobs performs at most one WC stamp + /// read per pass. + fn can_queue_behind_with_ta(&self, job: &Arc, ta_pending: &mut Option) -> bool { + let e = &self.engine; + let sent = job.progress.sent(); + if job.vm.status.get() != 0 + || e.flights.len() >= super::hw::sizes::FLIGHTS + || e.flights + .iter() + .any(|f| f.doomed || f.recovery_suspect || f.initbm) + { + return false; + } + if job.check_command_dependencies(sent).is_err() { + return false; + } + match command(job, sent) { + Some(Command::Compute(c)) => { + // G16 publishes timestamp results into user query-pool BOs on CPU during flight + // retirement, so dispatches without DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS must wait + // for prior timestamped flights in their dependency prefix to retire first. + let waits_for_timestamps = c.query_access + && (job.command_order(sent).is_some_and(|o| { + let waits_class = |class: usize| { + o.wait_through[class].is_some_and(|last| { + e.flights.iter().any(|f| { + let matches_class = if class == super::command::RENDER { + f.renders != 0 + } else { + f.computes != 0 + }; + matches_class + && f.has_timestamps + && Arc::ptr_eq(&f.job.queue, &job.queue) + && f.job + .command_order(f.first as u32) + .is_none_or(|fo| fo.sequence <= last) + }) + }) + }; + waits_class(super::command::COMPUTE) || waits_class(super::command::RENDER) + }) || job.fw_waits.iter().any(|w| { + (0..2).any(|class| { + w.last_ordinal[class].is_some_and(|last| { + e.flights.iter().any(|f| { + let matches_class = if class == super::command::RENDER { + f.renders != 0 + } else { + f.computes != 0 + }; + matches_class + && f.has_timestamps + && Arc::ptr_eq(&f.job.queue, &w.queue) + && f.job + .command_order(f.first as u32) + .is_none_or(|fo| fo.sequence <= last) + }) + }) + }) + })); + let cross_vm_render = e + .flights + .iter() + .any(|f| f.renders != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); + let scs = job.resources.compute_scs() || c.is_rt(); + let scs_conflict = e + .flights + .iter() + .any(|f| scs_compute_conflict(f, &job.vm, scs)); + let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); + !cross_vm_render + && !scs_conflict + && !waits_for_timestamps + && compute_count < params::compute_flights() + && !self.slots.compute_exhausted() + && super::recovery::logic::next_ordinal(e.ordinal).is_some() + && job + .resources + .compute_slot_mask() + .is_ok_and(|mask| self.has_compute_pipe_for_vm(&job.vm, mask, scs)) + } + Some(Command::Render(r)) => { + let cross_vm_compute = e + .flights + .iter() + .any(|f| f.computes != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); + let msaa_conflict = !self.msaa_member_allowed(&job.vm, r); + let render_count: usize = e.flights.iter().map(|f| f.renders as usize).sum(); + let ta_cap = self.ta_wave_cap_for(r.is_heavy_ta()); + !cross_vm_compute + && !msaa_conflict + && render_count < params::render_flights() + && *ta_pending.get_or_insert_with(|| self.ta_pending_passes()) < ta_cap + && !self.slots.render_exhausted() + && !self.pools.exhausted() + && super::recovery::logic::next_ordinal(e.draw).is_some() + && self.render_can_pipeline(job) + && job + .resources + .render_passes() + .is_ok_and(|passes| self.slots.pass_available(passes)) + } + None => false, + } + } + + /// Whether `self.engine.pending` is an eligible single-queue, single-VM busy horizon + /// batch that can accumulate more same-queue commands before publishing. + fn can_defer_busy_coalesce(&self, now: u64) -> bool { + if self.recovery.failed().is_some() + || self.engine.frozen + || self.engine.flights.is_empty() + || self.engine.pending.is_empty() + || self.engine.flights.len() >= super::hw::sizes::FLIGHTS + || self.engine.chan_wait + || self.engine.slot_wait + || self.engine.ta_wave_wait + || self.engine.held_wait + || self + .engine + .flights + .iter() + .any(|f| f.doomed || f.recovery_suspect || f.initbm) + { + return false; + } + let head = &self.engine.pending[0]; + let head_sent = head.progress.sent(); + if head.vm.status.get() != 0 + || head.long() + || !self.can_queue_behind(head) + || self + .engine + .flights + .iter() + .any(|fl| !Arc::ptr_eq(&fl.job.queue, &head.queue)) + || self + .engine + .pending + .iter() + .any(|j| !Arc::ptr_eq(&j.queue, &head.queue) || !Arc::ptr_eq(&j.vm, &head.vm)) + { + return false; + } + let Some(head_order) = head.command_order(head_sent) else { + return false; + }; + match command(head, head_sent) { + Some(Command::Compute(c)) => { + if head.resources.compute_scs() + || c.is_rt() + || head_order.wait_through != [None, None] + || !head.fw_waits.is_empty() + || self.compute_queue_is_heavy(&head.queue, now) + { + return false; + } + let queue_active: usize = self + .engine + .flights + .iter() + .filter(|fl| fl.computes != 0 && Arc::ptr_eq(&fl.job.queue, &head.queue)) + .map(|fl| fl.computes as usize) + .sum(); + if queue_active < 2 { + return false; + } + let Some(mut next_seq) = head_order.sequence.checked_add(1) else { + return false; + }; + let mut pending_cmds = 1usize; + for k in (head_sent + 1)..head.progress.count() { + let Some(Command::Compute(c2)) = command(head, k) else { + return false; + }; + if c2.is_rt() || !head.can_fold_horizon_cmd(k, next_seq) { + return false; + } + let Some(s) = next_seq.checked_add(1) else { + return false; + }; + next_seq = s; + pending_cmds += 1; + } + for j in &self.engine.pending[1..] { + let n = j.progress.count(); + if j.long() + || j.resources.compute_scs() + || !j.can_fold_horizon_job(next_seq) + || (0..n).any(|k| { + matches!(command(j, k), Some(Command::Compute(c2)) if c2.is_rt()) + }) + { + return false; + } + let Some(s) = next_seq.checked_add(u64::from(n)) else { + return false; + }; + next_seq = s; + pending_cmds += n as usize; + } + let active_computes: usize = self + .engine + .flights + .iter() + .map(|fl| fl.computes as usize) + .sum(); + let Ok(slot_mask) = head.resources.compute_slot_mask() else { + return false; + }; + let Some(pipe) = self.choose_compute_pipe( + &head.queue, + &head.vm, + [None; sizes::COMPUTE_PIPES], + slot_mask, + false, + false, + ) else { + return false; + }; + let free_c = self.slots.free_compute_in_mask_for_pipe(slot_mask, pipe) as usize; + let cap = super::hw::sizes::COALESCE_MAX_CMDS + .min(free_c) + .min(params::compute_flights().saturating_sub(active_computes)) + .min(super::hw::sizes::COMPUTE_SLOTS); + cap > 1 && pending_cmds < cap + } + Some(Command::Render(r)) => { + if head.resources.render_scs() || !head.fw_waits.is_empty() { + return false; + } + let queue_active: usize = self + .engine + .flights + .iter() + .filter(|fl| fl.renders != 0 && Arc::ptr_eq(&fl.job.queue, &head.queue)) + .map(|fl| fl.renders as usize) + .sum(); + if queue_active < 2 { + return false; + } + let Some(mut next_seq) = head_order.sequence.checked_add(1) else { + return false; + }; + let mut wave_heavy = r.is_heavy_ta(); + let mut pending_cmds = 1usize; + for k in (head_sent + 1)..head.progress.count() { + if !head.can_fold_render_cmd(k, next_seq) { + return false; + } + if matches!(command(head, k), Some(Command::Render(r2)) if r2.is_heavy_ta()) { + wave_heavy = true; + } + let Some(s) = next_seq.checked_add(1) else { + return false; + }; + next_seq = s; + pending_cmds += 1; + } + for j in &self.engine.pending[1..] { + let n = j.progress.count(); + if j.long() + || j.resources.render_scs() + || !j.can_fold_render_horizon_job(next_seq) + { + return false; + } + if (0..n).any(|k| { + matches!(command(j, k), Some(Command::Render(r2)) if r2.is_heavy_ta()) + }) { + wave_heavy = true; + } + let Some(s) = next_seq.checked_add(u64::from(n)) else { + return false; + }; + next_seq = s; + pending_cmds += n as usize; + } + let active_renders: usize = self + .engine + .flights + .iter() + .map(|fl| fl.renders as usize) + .sum(); + let wave_cap = self.ta_wave_cap_for(wave_heavy); + let ta_room = wave_cap.saturating_sub(self.ta_pending_passes()); + let cap = super::hw::sizes::COALESCE_MAX_CMDS + .min(params::render_flights().saturating_sub(active_renders)) + .min(ta_room) + .min(super::hw::sizes::RENDER_SLOTS); + cap > 1 && pending_cmds < cap + } + None => false, + } + } + + /// Defers immediate publication for up to `COALESCE_WINDOW_US` while a single queue already + /// has `>= 2` active commands in flight so consecutive same-queue `SUBMIT` ioctls accumulate + /// into one multi-command flight (up to `COALESCE_MAX_CMDS`), cutting `SubmitRecord`s, WC + /// producer updates, and doorbells without delaying `d=1`/`d=2`, barriered streams, RT/SCS + /// work, or multi-queue/cross-VM handoffs. + pub(crate) fn defer_busy_coalesce(&mut self, now: u64) -> Option { + if !self.can_defer_busy_coalesce(now) { + self.engine.coalesce_deadline_ns = 0; + return None; + } + if self.engine.coalesce_deadline_ns == 0 { + self.engine.coalesce_deadline_ns = + now.saturating_add(super::hw::sizes::COALESCE_WINDOW_NS); + } + if now >= self.engine.coalesce_deadline_ns { + self.engine.coalesce_deadline_ns = 0; + return None; + } + let rem_ns = self.engine.coalesce_deadline_ns.saturating_sub(now); + Some((rem_ns.div_ceil(1000) as u32).clamp(1, super::hw::sizes::COALESCE_WINDOW_US)) + } + + /// Resolves the newest in-flight target stamp and producer `InitBM` state for `class` + /// (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`) across `job`'s same-queue `target_seq` + /// and any cross-queue `job.fw_waits` (plus an earlier member of an in-progress render batch + /// `current`). Returns `Ok(None)` when no barrier is needed or every waited prefix retired. + fn wait_stamp_for_with( + &self, + job: &Arc, + class: usize, + target_seq: Option, + current: Option<&Flight>, + ) -> Result> { + let mut targets: [Option<(&Arc, u64, bool)>; + 1 + super::fence::MAX_FW_WAITS] = [None; 1 + super::fence::MAX_FW_WAITS]; + let mut count = 0usize; + if let Some(last) = target_seq { + if job.queue.completed[class].load(Ordering::Acquire) < last { + targets[count] = Some((&job.queue, last, false)); + count += 1; + } + } + for wait in job.fw_waits.iter() { + let Some(last) = wait.last_ordinal[class] else { + continue; + }; + if wait.queue.completed[class].load(Ordering::Acquire) >= last { + continue; + } + if let Some(slot) = targets[..count] + .iter_mut() + .flatten() + .find(|(q, _, _)| Arc::ptr_eq(q, &wait.queue)) + { + slot.1 = slot.1.max(last); + } else if count < targets.len() { + targets[count] = Some((&wait.queue, last, false)); + count += 1; + } else { + return Err(EAGAIN); + } + } + if count == 0 { + return Ok(None); + } + let mut newest: Option = None; + let scan_flight = |flight: &Flight, + targets: &mut [Option<(&Arc, u64, bool)>], + newest: &mut Option| + -> Result { + if class == super::command::COMPUTE { + if flight.computes == 0 { + return Ok(()); + } + } else if flight.renders == 0 { + return Ok(()); + } + if !targets + .iter() + .flatten() + .any(|(q, _, _)| Arc::ptr_eq(&flight.job.queue, q)) + { + return Ok(()); + } + let max_members = if class == super::command::COMPUTE { + (flight.computes as usize).min(flight.cstamp.len()) + } else { + (flight.renders as usize).min(flight.r_fs_stamp.len()) + }; + let mut member = 0usize; + for k in flight.first..flight.first + flight.count { + if member >= max_members { + break; + } + if let Some(fo) = flight.job.command_order(k as u32) { + if fo.engine == class { + for (q, last, found) in targets.iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence == *last { + *found = true; + let stamp = if class == super::command::COMPUTE { + flight.cstamp[member] + } else { + flight.r_fs_stamp[member] + }; + *newest = Some(WaitTarget { + stamp, + initbm: flight.initbm, + }); + } + } + } + } + member += 1; + } + for j2 in flight.group.iter() { + for k in 0..j2.progress.count() { + if member >= max_members { + break; + } + if let Some(fo) = j2.command_order(k) { + if fo.engine == class { + for (q, last, found) in targets.iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence == *last { + *found = true; + let stamp = if class == super::command::COMPUTE { + flight.cstamp[member] + } else { + flight.r_fs_stamp[member] + }; + *newest = Some(WaitTarget { + stamp, + initbm: flight.initbm, + }); + } + } + } + } + member += 1; + } + } + Ok(()) + }; + for flight in &self.engine.flights { + scan_flight(flight, &mut targets[..count], &mut newest)?; + } + if let Some(cur) = current { + scan_flight(cur, &mut targets[..count], &mut newest)?; + } + if targets[..count].iter().flatten().any(|(_, _, found)| !*found) { + return Err(EAGAIN); + } + Ok(newest) + } + + /// Resolves a same-queue or cross-queue target stamp for `class` across published flights. + fn wait_stamp_for( + &self, + job: &Arc, + class: usize, + target_seq: Option, + ) -> Result> { + self.wait_stamp_for_with(job, class, target_seq, None) + } + + /// Resolves a cross-engine barrier target when `job`'s command `index` waits on an in-flight + /// command of `other` engine (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`), including + /// cross-queue `fw_waits`. Returns `Ok(None)` when no barrier is needed or retired. + fn cross_engine_wait( + &self, + job: &Arc, + index: u32, + other: usize, + ) -> Result> { + let target_seq = job + .command_order(index) + .and_then(|o| o.wait_through[other]); + self.wait_stamp_for(job, other, target_seq) + } + + /// Resolves the newest in-flight compute producer on each compute pipe across `job`'s + /// same-queue `target_seq` and any cross-queue `job.fw_waits`. Returns + /// `Ok([None; COMPUTE_PIPES])` when no barrier is needed or every waited prefix retired, + /// and `Err(EAGAIN)` if any unretired target ordinal is missing from `flights`. + fn wait_compute_stamps_for( + &self, + job: &Arc, + target_seq: Option, + ) -> Result<[Option; sizes::COMPUTE_PIPES]> { + let mut targets: [Option<(&Arc, u64, bool)>; + 1 + super::fence::MAX_FW_WAITS] = [None; 1 + super::fence::MAX_FW_WAITS]; + let mut count = 0usize; + if let Some(last) = target_seq { + if job.queue.completed[super::command::COMPUTE].load(Ordering::Acquire) < last { + targets[count] = Some((&job.queue, last, false)); + count += 1; + } + } + for wait in job.fw_waits.iter() { + let Some(last) = wait.last_ordinal[super::command::COMPUTE] else { + continue; + }; + if wait.queue.completed[super::command::COMPUTE].load(Ordering::Acquire) >= last { + continue; + } + if let Some(slot) = targets[..count] + .iter_mut() + .flatten() + .find(|(q, _, _)| Arc::ptr_eq(q, &wait.queue)) + { + slot.1 = slot.1.max(last); + } else if count < targets.len() { + targets[count] = Some((&wait.queue, last, false)); + count += 1; + } else { + return Err(EAGAIN); + } + } + if count == 0 { + return Ok([None; sizes::COMPUTE_PIPES]); + } + let mut waits = [None; sizes::COMPUTE_PIPES]; + for flight in &self.engine.flights { + if flight.computes == 0 + || !targets[..count] + .iter() + .flatten() + .any(|(q, _, _)| Arc::ptr_eq(&flight.job.queue, q)) + { + continue; + } + let pipe = flight.compute_pipe as usize; + if pipe >= sizes::COMPUTE_PIPES { + return Err(EIO); + } + let mut member = 0usize; + for k in flight.first..flight.first + flight.count { + if let Some(fo) = flight.job.command_order(k as u32) { + if fo.engine == super::command::COMPUTE { + let mut matched = false; + for (q, last, found) in targets[..count].iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence <= *last { + if fo.sequence == *last { + *found = true; + } + matched = true; + } + } + if matched { + waits[pipe] = Some(WaitTarget { + stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, + initbm: flight.initbm, + }); + } + } + } + member += 1; + } + for j2 in flight.group.iter() { + for k in 0..j2.progress.count() { + if let Some(fo) = j2.command_order(k) { + if fo.engine == super::command::COMPUTE { + let mut matched = false; + for (q, last, found) in targets[..count].iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence <= *last { + if fo.sequence == *last { + *found = true; + } + matched = true; + } + } + if matched { + waits[pipe] = Some(WaitTarget { + stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, + initbm: flight.initbm, + }); + } + } + } + member += 1; + } + } + } + for (q, last, found) in targets[..count].iter().flatten() { + if !*found && !q.is_compute_retired(*last) { + return Err(EAGAIN); + } + } + Ok(waits) + } + + /// Whether `queue`'s recent or active compute work is heavy enough to benefit from 2-pipe + /// CDM fanout rather than 1-pipe affinity and horizon folding: + /// - per-queue retired CDM GPU duration EWMA `>= COMPUTE_HEAVY_EMA_US`, or + /// - a sole active single-command compute flight of `queue` on its pipe has already been + /// executing for `>= COMPUTE_HEAVY_INFLIGHT_NS` without completing (instant detection + /// before retirement updates the EWMA, while queued multi-flight light bursts never false- + /// trigger from queueing age). + fn compute_queue_is_heavy(&self, queue: &Arc, now: u64) -> bool { + if queue.compute_ewma_us.load(Ordering::Relaxed) >= super::hw::sizes::COMPUTE_HEAVY_EMA_US { + return true; + } + let mut pipe_flights = [0usize; super::hw::sizes::COMPUTE_PIPES]; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + pipe_flights[p] += 1; + } + } + self.engine.flights.iter().any(|fl| { + let p = (fl.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + fl.computes == 1 + && pipe_flights[p] == 1 + && Arc::ptr_eq(&fl.job.queue, queue) + && fl.published_ns != 0 + && now.saturating_sub(fl.published_ns) + >= super::hw::sizes::COMPUTE_HEAVY_INFLIGHT_NS + }) + } + + /// When a ready compute job cannot queue behind active flights because every compatible + /// compute pipe is currently occupied by another VM (for example a base-only VM limited to + /// pipe 0, or a 9th VM when all 8 pipes are occupied), pick one compatible occupied pipe to + /// drain for handoff while other pipes continue dispatching. + fn compute_handoff_pipe(&self, job: &Arc) -> Option { + let sent = job.progress.sent(); + let Some(Command::Compute(c)) = command(job, sent) else { + return None; + }; + if job.vm.status.get() != 0 + || self.slots.compute_exhausted() + || job.check_command_dependencies(sent).is_err() + { + return None; + } + let Ok(slot_mask) = job.resources.compute_slot_mask() else { + return None; + }; + let scs = job.resources.compute_scs() || c.is_rt(); + if self.has_compute_pipe_for_vm(&job.vm, slot_mask, scs) { + return None; + } + let mut other_load = [0usize; sizes::COMPUTE_PIPES]; + for fl in &self.engine.flights { + if fl.computes != 0 && !Arc::ptr_eq(&fl.job.vm, &job.vm) { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + other_load[p] += fl.computes as usize; + } + } + let limit = if scs { 1 } else { sizes::COMPUTE_PIPES }; + let mut best: Option<(usize, usize)> = None; + for (p, &load) in other_load.iter().enumerate().take(limit) { + if load == 0 { + continue; + } + let allowed = if p == 0 { + slot_mask + } else { + slot_mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) + }; + if allowed == 0 || self.slots.compute_exhausted_in_mask(allowed) { + continue; + } + if best.is_none_or(|(_, prev)| load < prev) { + best = Some((p, load)); + } + } + best.map(|(p, _)| p) + } + + /// Whether `vm` can acquire a compute pipe (`0..COMPUTE_PIPES`) without sharing an active + /// `qinfo` with another VM, exceeding `MAX_VM_COMPUTE_PIPES`, using a pipe draining for + /// handoff, or lacking an available unit in `slot_mask`. + fn has_compute_pipe_for_vm( + &self, + vm: &Arc, + slot_mask: u32, + rt_compute: bool, + ) -> bool { + let avoid = self.engine.handoff_avoid_pipes; + let mut active_same = [false; sizes::COMPUTE_PIPES]; + let mut active_other = [false; sizes::COMPUTE_PIPES]; + let mut any_rt = rt_compute; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + if Arc::ptr_eq(&fl.job.vm, vm) { + active_same[p] = true; + } else { + active_other[p] = true; + } + any_rt |= fl.rt_compute; + } + } + if any_rt { + return (avoid & 1) == 0 + && !active_other[0] + && self.slots.compute_available_in_mask_for_pipe(slot_mask, 0); + } + let vm_active_pipes = active_same.iter().filter(|&&a| a).count(); + for p in 0..sizes::COMPUTE_PIPES { + if (avoid & (1u32 << p)) != 0 || active_other[p] { + continue; + } + if !active_same[p] && vm_active_pipes >= sizes::MAX_VM_COMPUTE_PIPES { + continue; + } + if self.slots.compute_available_in_mask_for_pipe(slot_mask, p) { + return true; + } + } + false + } + + /// Minimum active compute count on another pipe eligible for `vm` besides `pipe`, used to + /// balance heavy barrier-free compute across up to `MAX_VM_COMPUTE_PIPES` pipes of `vm`. + fn other_vm_compute_pipe_load( + &self, + vm: &Arc, + pipe: usize, + slot_mask: u32, + ) -> Option { + let mut active_same = [0usize; sizes::COMPUTE_PIPES]; + let mut active_other = [false; sizes::COMPUTE_PIPES]; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + if Arc::ptr_eq(&fl.job.vm, vm) { + active_same[p] += fl.computes as usize; + } else { + active_other[p] = true; + } + } + } + let vm_active_pipes = active_same.iter().filter(|&&n| n != 0).count(); + let mut best: Option = None; + for p in 0..sizes::COMPUTE_PIPES { + if p == pipe || active_other[p] { + continue; + } + if active_same[p] == 0 && vm_active_pipes >= sizes::MAX_VM_COMPUTE_PIPES { + continue; + } + if !self.slots.compute_available_in_mask_for_pipe(slot_mask, p) { + continue; + } + best = Some(match best { + Some(prev) => prev.min(active_same[p]), + None => active_same[p], + }); + } + best + } + + /// Chooses which compute pipe (`0..COMPUTE_PIPES`) executes the next compute command + /// without ever mixing two different VMs/ASIDs inside one active `qinfo`: + /// - RT/SCS compute (or any flight while RT/SCS compute is active) stays on pipe 0. + /// - If the command waits only on one pipe of its own VM, reuse that pipe (in-order ring, + /// zero `c2c` barrier). + /// - If barrier-free (`waits` all `None`), `!heavy_compute`, and `queue` already has an active + /// compute flight on a single pipe with free units, keep that light queue pipe-affine so + /// consecutive horizon submits fold onto one workqueue without splitting across pipes. + /// - Otherwise, lease an idle pipe (preferring `vm`'s warm-affine `pipe_last_vm`, then never- + /// used, then LRU, preferring secondary pipes `1..COMPUTE_PIPES` for fresh/LRU picks so + /// pipe 0 stays free for base-only/SCS VMs) up to `MAX_VM_COMPUTE_PIPES` active pipes per + /// VM, or pick `vm`'s active eligible pipe with fewest commands in flight. + /// - Returns `None` when every eligible pipe is currently active for another VM or has no + /// available compute unit. + fn choose_compute_pipe( + &self, + queue: &Arc, + vm: &Arc, + waits: [Option; sizes::COMPUTE_PIPES], + slot_mask: u32, + rt_compute: bool, + heavy_compute: bool, + ) -> Option { + let mut active_same = [0usize; sizes::COMPUTE_PIPES]; + let mut active_other = [false; sizes::COMPUTE_PIPES]; + let mut any_rt = rt_compute; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + if Arc::ptr_eq(&fl.job.vm, vm) { + active_same[p] += fl.computes as usize; + } else { + active_other[p] = true; + } + any_rt |= fl.rt_compute; + } + } + let avoid = self.engine.handoff_avoid_pipes; + let vm_active_pipes = active_same.iter().filter(|&&n| n != 0).count(); + let pipe_ok = |p: usize| -> bool { + (avoid & (1u32 << p)) == 0 + && !active_other[p] + && (active_same[p] != 0 || vm_active_pipes < sizes::MAX_VM_COMPUTE_PIPES) + && self.slots.compute_available_in_mask_for_pipe(slot_mask, p) + }; + if any_rt { + return pipe_ok(0).then_some(0); + } + let mut wait_pipe: Option = None; + let mut wait_count = 0usize; + for (p, w) in waits.iter().enumerate() { + if w.is_some() { + wait_pipe = Some(p); + wait_count += 1; + } + } + if wait_count == 1 { + if let Some(p) = wait_pipe { + if pipe_ok(p) { + return Some(p); + } + } + } + if wait_count == 0 && !heavy_compute { + let mut q_pipe: Option = None; + for fl in &self.engine.flights { + if fl.computes != 0 && Arc::ptr_eq(&fl.job.queue, queue) { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + match q_pipe { + None => q_pipe = Some(p), + Some(prev) if prev == p => {} + Some(_) => { + q_pipe = None; + break; + } + } + } + } + if let Some(p) = q_pipe { + if pipe_ok(p) { + return Some(p); + } + } + } + let pick_idle = |prefer_secondary: bool| -> Option { + // 1. Warm VM-affine idle pipe (keeps the same VM on the same `qinfo`). + for p in 0..sizes::COMPUTE_PIPES { + if active_same[p] == 0 + && pipe_ok(p) + && self.engine.pipe_last_vm[p] == Some(vm.id) + { + return Some(p); + } + } + // 2. Never-used idle pipe, preferring secondary pipes for extension-capable VMs so + // pipe 0 remains immediately available to base-only and SCS VMs. + let mut order = [0usize; sizes::COMPUTE_PIPES]; + if prefer_secondary { + for i in 0..(sizes::COMPUTE_PIPES - 1) { + order[i] = i + 1; + } + order[sizes::COMPUTE_PIPES - 1] = 0; + } else { + for (i, slot) in order.iter_mut().enumerate() { + *slot = i; + } + } + for &p in &order { + if active_same[p] == 0 && pipe_ok(p) && self.engine.pipe_last_vm[p].is_none() { + return Some(p); + } + } + // 3. Least-recently-used idle pipe, preferring secondary pipes when `prefer_secondary` + // is set so pipe 0 remains available to base-only and SCS VMs. + if prefer_secondary { + let mut best_sec: Option<(usize, u64)> = None; + for p in 1..sizes::COMPUTE_PIPES { + if active_same[p] == 0 && pipe_ok(p) { + let used = self.engine.pipe_last_used[p]; + if best_sec.is_none_or(|(_, prev)| used < prev) { + best_sec = Some((p, used)); + } + } + } + if let Some((p, _)) = best_sec { + return Some(p); + } + if active_same[0] == 0 && pipe_ok(0) { + return Some(0); + } + } else { + let mut best: Option<(usize, u64)> = None; + for p in 0..sizes::COMPUTE_PIPES { + if active_same[p] == 0 && pipe_ok(p) { + let used = self.engine.pipe_last_used[p]; + if best.is_none_or(|(_, prev)| used < prev) { + best = Some((p, used)); + } + } + } + if let Some((p, _)) = best { + return Some(p); + } + } + None + }; + let has_secondary = (slot_mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1)) != 0; + let prefer_secondary = has_secondary && active_other.iter().any(|&a| a); + if vm_active_pipes < sizes::MAX_VM_COMPUTE_PIPES { + if let Some(p) = pick_idle(prefer_secondary) { + return Some(p); + } + } + // Reuse this VM's least-loaded eligible active pipe, breaking ties by `next_compute_pipe`. + let start = (self.engine.next_compute_pipe as usize) % sizes::COMPUTE_PIPES; + let mut best: Option<(usize, usize)> = None; + for i in 0..sizes::COMPUTE_PIPES { + let p = (start + i) % sizes::COMPUTE_PIPES; + if active_same[p] != 0 && pipe_ok(p) { + let load = active_same[p]; + if best.is_none_or(|(_, prev)| load < prev) { + best = Some((p, load)); + } + } + } + best.map(|(p, _)| p) + } + + /// Whether some of `job`'s commands were published: such a job is retained after a + /// fail-stop. + pub(crate) fn job_partly_published(&self, job: &Job) -> bool { + job.progress.sent() != 0 + } + + /// Addresses and cumulative allocator state of the selected retained render allocator slot. + fn render_refs( + &mut self, + alloc_slot: usize, + job: &Job, + draw: u64, + render_pipelined: bool, + engine_behind: bool, + ) -> Result<(RenderRefs, bool, Arc, u64)> { + let generation = job.vm.generation; + let mut a = job + .resources + .prepare_pb_in_flight(alloc_slot, draw, render_pipelined)?; + let (pb_mask, _) = job.resources.pb_slot_mask()?; + let heap_blocks = job.resources.pb_heap_blocks()?; + let render_scs = job.resources.render_scs(); + // Reuse this VM's retired epoch of the allocator slot when still bound, matching the + // SCS mode, and sized for the VM's current PB heap (no reseed/InitBM). + let (epoch, reused) = match self.pools.reusable_for_mask_mode( + alloc_slot, + &job.vm, + pb_mask, + heap_blocks, + render_scs, + ) { + Some(e) => { + self.pools.stats.reused += 1; + a.init_buffer = false; + (e, true) + } + None => { + if engine_behind { + return Err(EAGAIN); + } + let e = job.resources.take_pb()?; + if let Err(err) = e.prepare_with_scs_for( + self.init.abi.pb_manager(), + alloc_slot, + job.resources.pb_heap_gva(alloc_slot)?, + heap_blocks, + render_scs, + ) { + job.resources.return_pb(e); + return Err(err); + } + self.pools.stats.fresh += 1; + (e, false) + } + }; + let binding = self.pools.bind(alloc_slot, reused); + a.pb_mgr = epoch.manager.va; + a.mgr_misc = epoch.misc.va; + let r = &self.graph.render; + let stage = draw.checked_mul(2).ok_or(EOVERFLOW)?; + Ok(( + RenderRefs { + notifier: r.notifier.va, + legacy_empty: r.legacy_empty.va, + qinfo: [r.qinfo[0].va, r.qinfo[1].va], + user_stamp: [ + r.notifier.va + notifier_page::TA_STAMP as u64, + r.notifier.va + notifier_page::FS_STAMP as u64, + ], + fw_stamp: [r.fw_stamp[0].va, r.fw_stamp[1].va], + uma_mgr: a.uma_mgr, + uma_aux: a.uma_aux, + uma_gpu: a.uma_gpu, + pb_mgr: a.pb_mgr, + scene_list: 0, + mgr_misc: a.mgr_misc, + pb_init_blocks: epoch.heap_blocks(), + parameter_id: a.parameter_id, + generation, + activity: [self.init.ta_activity.va + 4, self.init.fs_activity.va + 8], + counter: [stage, stage - 1], + uma_submitted: a.uma_submitted, + uuid: (draw as u32).wrapping_add(1), + usc_base: job.queue.usc_base, + }, + a.init_buffer, + epoch, + binding, + )) + } + + /// Allocator references for subsequent passes (`member > 0`) in a non-InitBM multi-pass + /// render flight, reusing the active slot and PB epoch while advancing `uma_submitted` by 2. + fn render_refs_batched( + &self, + alloc_slot: usize, + job: &Job, + draw: u64, + epoch: &super::pools::PbEpoch, + prev_uma_submitted: u64, + ) -> Result { + let a = job.resources.pb_allocator_refs(alloc_slot)?; + let r = &self.graph.render; + let stage = draw.checked_mul(2).ok_or(EOVERFLOW)?; + let uma_submitted = prev_uma_submitted.checked_add(2).ok_or(EOVERFLOW)?; + Ok(RenderRefs { + notifier: r.notifier.va, + legacy_empty: r.legacy_empty.va, + qinfo: [r.qinfo[0].va, r.qinfo[1].va], + user_stamp: [ + r.notifier.va + notifier_page::TA_STAMP as u64, + r.notifier.va + notifier_page::FS_STAMP as u64, + ], + fw_stamp: [r.fw_stamp[0].va, r.fw_stamp[1].va], + uma_mgr: a.uma_mgr, + uma_aux: a.uma_aux, + uma_gpu: a.uma_gpu, + pb_mgr: epoch.manager.va, + scene_list: 0, + mgr_misc: epoch.misc.va, + pb_init_blocks: epoch.heap_blocks(), + parameter_id: a.parameter_id, + generation: job.vm.generation, + activity: [self.init.ta_activity.va + 4, self.init.fs_activity.va + 8], + counter: [stage, stage - 1], + uma_submitted, + uuid: (draw as u32).wrapping_add(1), + usc_base: job.queue.usc_base, + }) + } + + /// Publishes the next command of `job`. All images and ring entries precede the host + /// producer writes and queue kicks. EAGAIN defers while storage/channel state is held; + /// The error records whether firmware may see a counter/producer update, independently + /// of errno; unpublished EIO is still an ordinary job failure. + #[inline(never)] + fn publish_prefix( + &mut self, + job: &Arc, + _done: &mut Completions, + pending_rings: &mut u8, + ) -> core::result::Result<(), PublicationError> { + let mut f = Flight::new(job.clone()); + let mut visible = false; + let result = self.publish_prefix_into(job, &mut f, &mut visible, pending_rings); + match result { + Err(e) if !visible => { + // Never published: its storage is free again. Horizon candidates are removed + // from `pending` only after visibility begins, so they remain untouched here. + self.slots.release(&mut f.claims); + f.group.clear(); + Err(PublicationError::Unpublished(e)) + } + Err(e) => Err(PublicationError::Uncertain(e)), + Ok(()) => Ok(()), + } + } + + fn publish_prefix_into( + &mut self, + job: &Arc, + f: &mut Flight, + visible: &mut bool, + pending_rings: &mut u8, + ) -> Result { + let result = self.publish_prefix_body(job, f, visible, pending_rings); + if result.is_err() && !*visible { + if f.pb.is_some() { + self.pools.cancel_alloc(f.pb_slot as usize); + } + if let Some(epoch) = f.pb.take() { + if epoch.unexposed() { + job.resources.return_pb(epoch); + } + } + } + result + } + + fn publish_prefix_body( + &mut self, + job: &Arc, + f: &mut Flight, + visible: &mut bool, + pending_rings: &mut u8, + ) -> Result { + let behind = !self.engine.flights.is_empty(); + if behind && !self.can_queue_behind(job) { + return Err(EAGAIN); + } + let index = job.progress.sent(); + let cmd = command(job, index).ok_or(EINVAL)?; + let render = matches!(cmd, Command::Render(_)); + let class_behind = self + .engine + .flights + .iter() + .any(|f| if render { f.renders != 0 } else { f.computes != 0 }); + if job.vm.status.get() != 0 { + return Err(EIO); + } + if if render { + self.slots.render_exhausted() || self.pools.exhausted() + } else { + self.slots.compute_exhausted() + } { + return Err(EIO); + } + let channels: &[Channel] = if render { + &[Channel::Fs, Channel::Ta] + } else { + &[Channel::Compute] + }; + let (compute_pipe, c_waits, heavy_compute) = if render { + (0usize, [None; sizes::COMPUTE_PIPES], false) + } else { + let slot_mask = job.resources.compute_slot_mask()?; + let rt_compute = job.resources.compute_scs() + || matches!(cmd, Command::Compute(c) if c.is_rt()); + let waits = self.wait_compute_stamps_for( + job, + job.command_order(index) + .and_then(|o| o.wait_through[super::command::COMPUTE]), + )?; + let heavy = self.compute_queue_is_heavy(&job.queue, now_ns()); + let Some(pipe) = self.choose_compute_pipe( + &job.queue, + &job.vm, + waits, + slot_mask, + rt_compute, + heavy, + ) else { + self.engine.slot_wait = true; + return Err(EAGAIN); + }; + (pipe, waits, heavy) + }; + let pipe_behind = !render + && self + .engine + .flights + .iter() + .any(|fl| fl.computes != 0 && fl.compute_pipe as usize == compute_pipe); + if !render && class_behind { + self.latch_compute_channel_receipts()?; + } + for &channel in channels { + let pipe = self.channels.channel(channel); + let producer = self.channels.producer(channel); + let busy = if class_behind { + // Behind in-flight commands on this class: post after their unconsumed records + // and never lap an unsettled compute flight's shared submit-channel record. + let wrap_bound = channel == Channel::Compute + && self.engine.flights.iter().any(|fl| { + fl.computes != 0 + && !fl.chan_settled + && producer + .wrapping_sub((fl.rec[2] + RING_SLOTS - 1) % RING_SLOTS) + % RING_SLOTS + >= RING_SLOTS - 2 + }); + pipe.write()? != producer + || producer.wrapping_sub(pipe.read()?) % RING_SLOTS >= sizes::AHEAD_RECORDS + || wrap_bound + } else { + pipe.read()? != producer + || pipe.completion()? != producer + || pipe.write()? != producer + }; + if busy { + self.engine.chan_wait = true; + return Err(EAGAIN); + } + } + if self.engine.scratch.is_none() { + return Err(EIO); + } + self.engine.stats.prep_from_ns = now_ns(); + let (c_head, ta_head, fs_head) = if render { + ( + 0, + self.graph.render.qstate[0].r32(qstate::WRITE)?, + self.graph.render.qstate[1].r32(qstate::WRITE)?, + ) + } else { + ( + self.graph.compute[compute_pipe].qstate.r32(qstate::WRITE)?, + 0, + 0, + ) + }; + let mut prefix = Prefix { + compute_pipe, + n: self.engine.ordinal, + pipe_n: if render { + 0 + } else { + self.engine.pipe_ordinal[compute_pipe] + }, + draw: self.engine.draw, + c_head, + ta_head, + fs_head, + ..Default::default() + }; + if prefix.c_head >= 256 || prefix.ta_head >= 256 || prefix.fs_head >= 256 { + return Err(super::boot::eproto()); + } + let mut c_read = prefix.c_head; + let mut ta_read = prefix.ta_head; + let mut fs_read = prefix.fs_head; + if render && class_behind { + // Room for up to 5 TA entries (prev_barrier, ta_fs_barrier, 2x compute_barrier, + // ta_work) and 5 FS entries (fs_dep, 2x fs_compute_barrier, own_barrier, fs_work). + ta_read = self.graph.render.qstate[0].r32(qstate::READ)?; + fs_read = self.graph.render.qstate[1].r32(qstate::READ)?; + if ta_read >= 256 + || fs_read >= 256 + || prefix.ta_head.wrapping_sub(ta_read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 6 + || prefix.fs_head.wrapping_sub(fs_read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 6 + { + self.engine.slot_wait = true; + return Err(EAGAIN); + } + } else if !render && pipe_behind { + // Room for optional fs2c + up to COMPUTE_PIPES-1 cross-pipe barriers + compute work. + let min_free = 2 + sizes::COMPUTE_PIPES as u32; + c_read = self.graph.compute[compute_pipe].qstate.r32(qstate::READ)?; + if c_read >= 256 + || prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP + >= sizes::QUEUE_CAP - min_free + { + self.engine.slot_wait = true; + return Err(EAGAIN); + } + } + f.first = index as usize; + f.compute_pipe = compute_pipe as u8; + f.c_start = prefix.c_head; + f.ta_start = prefix.ta_head; + f.fs_start = prefix.fs_head; + let mut end = index + 1; + let mut hz_stop: Option = None; + match cmd { + Command::Compute(c) => { + self.prefix_compute( + job, + &job.resources, + index, + c, + c_waits, + &mut prefix, + f, + false, + )?; + let mut last_seq = job.command_order(index).map(|o| o.sequence); + let slot_mask = job.resources.compute_slot_mask()?; + let free_c = self + .slots + .free_compute_in_mask_for_pipe(slot_mask, compute_pipe) + as usize; + let mut active_pipe = [0usize; sizes::COMPUTE_PIPES]; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + active_pipe[p] += fl.computes as usize; + } + } + let active_computes: usize = active_pipe.iter().sum(); + // Keep heavy barrier-free compute balanced across this VM's CDM pipes while light + // single-queue compute streams stay pipe-affine and fold freely into one batch. + let pipe_fold_cap = if heavy_compute && c_waits == [None; sizes::COMPUTE_PIPES] { + match self.other_vm_compute_pipe_load(&job.vm, compute_pipe, slot_mask) { + Some(other_load) => { + other_load.saturating_sub(active_pipe[compute_pipe] + 1) + } + None => usize::MAX, + } + } else { + usize::MAX + }; + let used = prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP; + let ring_more = (sizes::QUEUE_CAP.saturating_sub(2 + sizes::COMPUTE_PIPES as u32)) + .saturating_sub(used) as usize; + let mut more_slots = free_c + .min(params::compute_flights().saturating_sub(active_computes + 1)) + .min(sizes::COMPUTE_SLOTS.saturating_sub(1)) + .min(ring_more) + .min(pipe_fold_cap); + let rt_head = job.resources.compute_scs() || c.is_rt(); + // Fold trailing barrier-free compute commands of the base job first. + while !rt_head && more_slots > 0 && end < job.progress.count() { + let Some(next_seq) = last_seq.and_then(|s| s.checked_add(1)) else { + break; + }; + if !job.can_fold_horizon_cmd(end, next_seq) + || super::recovery::logic::next_ordinal(prefix.n).is_none() + { + break; + } + let Some(Command::Compute(c2)) = command(job, end) else { + break; + }; + if c2.is_rt() { + break; + } + self.prefix_compute( + job, + &job.resources, + end, + c2, + [None; sizes::COMPUTE_PIPES], + &mut prefix, + f, + false, + )?; + last_seq = Some(next_seq); + end += 1; + more_slots -= 1; + } + // Compute horizon: fold subsequent ready, barrier-free compute-only jobs of + // the same queue and VM into the same CDM producer advance and doorbell. + // Any non-qualifying job of this queue ends the scan so no later job overtakes it. + if !rt_head && !job.long() && end == job.progress.count() { + hz_stop = Some(0); + let mut idx = 0; + while idx < self.engine.pending.len() { + let j2 = self.engine.pending[idx].clone(); + idx += 1; + if Arc::ptr_eq(&j2, job) || !Arc::ptr_eq(&j2.queue, &job.queue) { + continue; + } + if 1 + f.group.len() >= sizes::HORIZON_JOBS as usize { + hz_stop = Some(1); + break; + } + let n2 = j2.progress.count(); + let Some(first_seq) = last_seq.and_then(|s| s.checked_add(1)) else { + hz_stop = Some(3); + break; + }; + if !Arc::ptr_eq(&j2.vm, &job.vm) + || j2.progress.sent() != 0 + || n2 == 0 + || j2.long() + || j2.resources.compute_scs() + || (0..n2).any(|k| { + matches!(command(&j2, k), Some(Command::Compute(c2)) if c2.is_rt()) + }) + || !j2.can_fold_horizon_job(first_seq) + { + hz_stop = Some(3); + break; + } + let n2_usize = n2 as usize; + if n2_usize > more_slots { + hz_stop = Some(2); + break; + } + let mut test_n = prefix.n; + let mut ord_ok = true; + for _ in 0..n2 { + match super::recovery::logic::next_ordinal(test_n) { + Some(next) => test_n = next, + None => { + ord_ok = false; + break; + } + } + } + if !ord_ok { + hz_stop = Some(2); + break; + } + if f.group.reserve(1, GFP_NOWAIT).is_err() { + hz_stop = Some(1); + break; + } + for k in 0..n2 { + match command(&j2, k).ok_or(EINVAL)? { + Command::Compute(c2) => { + self.prefix_compute( + &j2, + &job.resources, + k, + c2, + [None; sizes::COMPUTE_PIPES], + &mut prefix, + f, + false, + )?; + } + Command::Render(_) => return Err(EINVAL), + } + } + last_seq = Some(first_seq + u64::from(n2 - 1)); + more_slots -= n2_usize; + let _ = f.group.push_within_capacity(j2); + } + } + } + Command::Render(r) => { + let geometry = + Geometry::new_for(&r.cmd, 0, self.cfg.num_clusters, self.cfg.gpu_generation); + let n = job.resources.render_passes()?; + if (0..n).all(|k| { + job.resources.render_pass(k).is_err_and(|_| true) + || job.resources.render_pass(k).is_ok_and(|slot| { + geometry + .validate_capacity(slot.tpc.size as u64, slot.tilemap.size as u64) + .is_err() + }) + }) { + return Err(E2BIG); + } + let Some(k) = + self.slots + .pick_pass_in_for(&job.resources, &geometry, 0, Some(job.vm.id)) + else { + self.engine.slot_wait = true; + return Err(EAGAIN); + }; + f.claims.pass[0] = k as u32; + f.claims.pass_count = 1; + f.claims.pass_mask = 1u64 << k; + self.slots.pass_busy |= 1u64 << k; + self.prefix_render( + job, + &job.resources, + index, + r, + geometry, + &mut prefix, + f, + behind, + class_behind, + )?; + f.count = 1; + // Batch consecutive ready non-InitBM render passes of the same SUBMIT into + // one TA/FS producer advance, one UMA submitted update, and one SubmitRecord. + if !f.initbm { + let stage_prefix = + kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; + let mut last_seq = job.command_order(index).map(|o| o.sequence); + let active_renders: usize = self + .engine + .flights + .iter() + .map(|fl| fl.renders as usize) + .sum(); + let ta_pending_before = self.ta_pending_passes(); + let mut wave_heavy = + self.ta_wave_cap_for(r.is_heavy_ta()) == sizes::TA_WAVE_PASSES; + let wave_cap = if wave_heavy { + sizes::TA_WAVE_PASSES + } else { + sizes::TA_WAVE_PASSES_LIGHT + }; + let mut more_renders = params::render_flights() + .saturating_sub(active_renders + 1) + .min(sizes::RENDER_SLOTS.saturating_sub(1)) + .min(wave_cap.saturating_sub(ta_pending_before + 1)); + while more_renders > 0 && end < job.progress.count() { + let Some(next_seq) = last_seq.and_then(|s| s.checked_add(1)) else { + break; + }; + if !job.can_fold_render_cmd(end, next_seq) + || super::recovery::logic::next_ordinal(prefix.draw).is_none() + { + break; + } + let Some(Command::Render(r2)) = command(job, end) else { + break; + }; + if !self.msaa_member_allowed(&job.vm, r2) { + break; + } + if r2.is_heavy_ta() && !wave_heavy { + if ta_pending_before + prefix.renders as usize + 1 + > sizes::TA_WAVE_PASSES + { + break; + } + wave_heavy = true; + more_renders = more_renders.min( + sizes::TA_WAVE_PASSES + .saturating_sub(ta_pending_before + prefix.renders as usize), + ); + } + let Some(o2) = job.command_order(end) else { + break; + }; + let ta_used = prefix.ta_head.wrapping_sub(ta_read) % sizes::QUEUE_CAP; + let fs_used = prefix.fs_head.wrapping_sub(fs_read) % sizes::QUEUE_CAP; + if ta_used >= sizes::QUEUE_CAP - 6 || fs_used >= sizes::QUEUE_CAP - 6 { + break; + } + let geo2 = Geometry::new_for( + &r2.cmd, + 0, + self.cfg.num_clusters, + self.cfg.gpu_generation, + ); + let Some(k2) = self.slots.pick_pass_in_for( + &job.resources, + &geo2, + f.claims.pass_mask, + Some(job.vm.id), + ) else { + break; + }; + let staged2 = r2.cmd.flags + & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES + != 0; + if self + .wait_compute_stamps_for( + job, + o2.ta_wait_through[super::command::COMPUTE], + ) + .is_err() + || self + .wait_compute_stamps_for( + job, + o2.wait_through[super::command::COMPUTE], + ) + .is_err() + || self + .wait_stamp_for_with( + job, + super::command::RENDER, + o2.wait_through[super::command::RENDER], + Some(f), + ) + .is_err() + || (staged2 + && params::early_tiling() + && self + .wait_stamp_for_with( + job, + super::command::RENDER, + o2.ta_wait_through[super::command::RENDER], + Some(f), + ) + .is_err()) + { + break; + } + let member = prefix.renders as usize; + f.claims.pass[member] = k2 as u32; + f.claims.pass_count += 1; + f.claims.pass_mask |= 1u64 << k2; + self.slots.pass_busy |= 1u64 << k2; + self.prefix_render( + job, + &job.resources, + end, + r2, + geo2, + &mut prefix, + f, + behind, + class_behind, + )?; + last_seq = Some(next_seq); + end += 1; + f.count = (end - index) as usize; + more_renders -= 1; + } + // Cross-job render horizon: fold subsequent ready render-only jobs of + // the same queue and VM into the same adaptive TA wave flight, sharing + // one TA/FS producer advance, one UMA submitted update, and one doorbell. + // Any non-qualifying job of this queue ends the scan so no later job + // overtakes it. + if end == job.progress.count() && more_renders > 0 { + let mut idx = 0; + while more_renders > 0 && idx < self.engine.pending.len() { + let j2 = self.engine.pending[idx].clone(); + idx += 1; + if Arc::ptr_eq(&j2, job) || !Arc::ptr_eq(&j2.queue, &job.queue) { + continue; + } + if 1 + f.group.len() >= sizes::HORIZON_JOBS as usize { + break; + } + let n2 = j2.progress.count(); + let n2_usize = n2 as usize; + let Some(first_seq) = last_seq.and_then(|s| s.checked_add(1)) else { + break; + }; + if !Arc::ptr_eq(&j2.vm, &job.vm) + || j2.long() != job.long() + || j2.resources.render_scs() != job.resources.render_scs() + || n2 == 0 + || n2_usize > more_renders + || !j2.can_fold_render_horizon_job(first_seq) + { + break; + } + let mut test_draw = prefix.draw; + let mut ord_ok = true; + for _ in 0..n2 { + match super::recovery::logic::next_ordinal(test_draw) { + Some(next) => test_draw = next, + None => { + ord_ok = false; + break; + } + } + } + if !ord_ok { + break; + } + let ta_used = + (prefix.ta_head.wrapping_sub(ta_read) % sizes::QUEUE_CAP) as usize; + let fs_used = + (prefix.fs_head.wrapping_sub(fs_read) % sizes::QUEUE_CAP) as usize; + let need_ring = n2_usize * (sizes::MAX_RENDER_RING_ENTRIES + 1); + if ta_used + need_ring >= sizes::QUEUE_CAP as usize + || fs_used + need_ring >= sizes::QUEUE_CAP as usize + { + break; + } + let mut picked = [0usize; sizes::TA_WAVE_PASSES_LIGHT]; + let mut picked_mask = f.claims.pass_mask; + let mut precheck_ok = true; + let mut job_heavy = false; + for k in 0..n2 { + let Some(Command::Render(r2)) = command(&j2, k) else { + precheck_ok = false; + break; + }; + if !self.msaa_member_allowed(&job.vm, r2) { + precheck_ok = false; + break; + } + if r2.is_heavy_ta() { + job_heavy = true; + } + let Some(o2) = j2.command_order(k) else { + precheck_ok = false; + break; + }; + let geo2 = Geometry::new_for( + &r2.cmd, + 0, + self.cfg.num_clusters, + self.cfg.gpu_generation, + ); + let Some(slot) = self.slots.pick_pass_in_for( + &job.resources, + &geo2, + picked_mask, + Some(job.vm.id), + ) else { + precheck_ok = false; + break; + }; + let staged2 = r2.cmd.flags & stage_prefix != 0; + let render_wait_ok = |target: Option| -> bool { + match target { + None => true, + Some(seq) if seq >= first_seq => { + seq < first_seq + u64::from(k) + } + Some(seq) => self + .wait_stamp_for_with( + &j2, + super::command::RENDER, + Some(seq), + Some(f), + ) + .is_ok(), + } + }; + if self + .wait_compute_stamps_for( + &j2, + o2.ta_wait_through[super::command::COMPUTE], + ) + .is_err() + || self + .wait_compute_stamps_for( + &j2, + o2.wait_through[super::command::COMPUTE], + ) + .is_err() + || !render_wait_ok(o2.wait_through[super::command::RENDER]) + || (staged2 + && params::early_tiling() + && !render_wait_ok( + o2.ta_wait_through[super::command::RENDER], + )) + { + precheck_ok = false; + break; + } + picked[k as usize] = slot; + picked_mask |= 1u64 << slot; + } + if !precheck_ok + || (job_heavy + && !wave_heavy + && ta_pending_before + prefix.renders as usize + n2_usize + > sizes::TA_WAVE_PASSES) + || f.group.reserve(1, GFP_NOWAIT).is_err() + { + break; + } + let _ = f.group.push_within_capacity(j2.clone()); + for k in 0..n2 { + let Some(Command::Render(r2)) = command(&j2, k) else { + return Err(EINVAL); + }; + let geo2 = Geometry::new_for( + &r2.cmd, + 0, + self.cfg.num_clusters, + self.cfg.gpu_generation, + ); + let slot = picked[k as usize]; + let member = prefix.renders as usize; + f.claims.pass[member] = slot as u32; + f.claims.pass_count += 1; + f.claims.pass_mask |= 1u64 << slot; + self.slots.pass_busy |= 1u64 << slot; + self.prefix_render( + &j2, + &job.resources, + k, + r2, + geo2, + &mut prefix, + f, + behind, + class_behind, + )?; + } + last_seq = Some(first_seq + u64::from(n2 - 1)); + more_renders -= n2_usize; + if job_heavy && !wave_heavy { + wave_heavy = true; + let ta_in_wave = ta_pending_before + prefix.renders as usize; + more_renders = more_renders + .min(sizes::TA_WAVE_PASSES.saturating_sub(ta_in_wave)); + } + } + } + } + } + } + f.first = index as usize; + f.count = (end - index) as usize; + f.computes = prefix.computes; + f.renders = prefix.renders; + f.target = prefix.last_ct; + f.ta_target = if render { prefix.last_ta } else { 0 }; + f.fs_target = prefix.last_fs; + f.head = prefix.c_head; + f.ta_head = prefix.ta_head; + f.fs_head = prefix.fs_head; + if self.recovery_pending()? { + return Err(EAGAIN); + } + if render { + f.pb.as_ref() + .ok_or(EINVAL)? + .check_assignment(f.pb_slot as usize)?; + self.pools.hold_alloc( + f.pb_slot as usize, + &job.vm, + job.resources.pb_owner_arena(f.pb_slot as usize), + job.resources.pb_uma_lease(f.pb_slot as usize), + )?; + } + // Reserve lifetime ownership before any counter or producer becomes reachable. + job.vm.vm.mark_binding_published()?; + self.slots.verify_held(&f.claims)?; + self.slots.publish(&mut f.claims)?; + // Even a failed first store may have become visible. From this boundary preserve + // every owner and return explicit uncertainty rather than guessing from errno. + *visible = true; + if f.msaa { + job.vm.note_msaa_render(); + } + let publication = (|| -> Result { if render { - let k = f.claims.pass[0] as usize; - job.resources.pb(index as usize)?.expose(); - job.resources.render()?.pools.publish(k, f.uma_submitted)?; + let a = f.pb_slot as usize; + f.pb.as_ref().ok_or(EINVAL)?.expose(); + job.resources.commit_render(f.count as u32); + for j2 in f.group.iter() { + j2.resources.commit_render(j2.progress.count()); + } + job.resources + .publish_pb_batch(a, f.uma_submitted, f.renders)?; + self.pools.publish_flight(a); // Notifier service dereferences u32 counters; the host ordering ledger - // remains u64. Eight-byte spacing is retained allocation padding. + // remains u64. Eight-byte spacing is retained allocation padding. Always + // advance both TA and FS thresholds to the newest published draw ordinal + // so firmware never skips updating `TA_STAMP` on fast tail flights. self.graph.render.threshold.w32(0, prefix.draw as u32)?; self.graph.render.threshold.w32(8, prefix.draw as u32)?; } else { - let k = f.claims.slot[0] as usize; - job.resources.compute()?.compute[k] - .counter - .w64(0, f.uma_submitted)?; - self.graph.compute.threshold.w32(0, prefix.n as u32)?; + for m in 0..f.claims.slot_count as usize { + let k = f.claims.slot[m] as usize; + job.resources + .compute_unit(k)? + .counter + .w64(0, f.csubmitted[m])?; + } + self.graph.compute[compute_pipe] + .threshold + .w32(0, prefix.pipe_n as u32)?; } wmb(); if render { @@ -1070,19 +3519,21 @@ impl Firmware { self.graph.render.qstate[1].w32(qstate::WRITE, prefix.fs_head)?; } else { publish_producer( - &self.graph.compute.qstate, + &self.graph.compute[compute_pipe].qstate, prefix.c_head, &mut self.engine.stats.publications[0], )?; } wmb(); + // Every command posts its own record: the firmware does not pick up a WRITE + // advance without one, also while the queue is running. for &channel in channels { let (qinfo, head, event, fresh) = match channel { Channel::Compute => ( - self.graph.compute.qinfo.va, + self.graph.compute[compute_pipe].qinfo.va, prefix.c_head, - 15, - !self.engine.queue_registered, + work::compute::EVENTS[compute_pipe] as u8, + !self.engine.queue_registered[compute_pipe], ), Channel::Ta => ( self.graph.render.qinfo[0].va, @@ -1105,8 +3556,12 @@ impl Firmware { event, new_queue: u8::from(fresh), }; - self.channels.post(channel, &record)?; - self.session.ring(channel)?; + if class_behind { + self.channels.post_ahead(channel, &record)?; + } else { + self.channels.post(channel, &record)?; + } + *pending_rings |= 1u8 << (channel as u8); } Ok(()) })(); @@ -1130,15 +3585,59 @@ impl Firmware { self.engine.ta_registered = true; self.engine.render_registered = true; } else { - self.engine.target = f.target; - self.engine.head = f.head; - self.engine.queue_registered = true; + self.engine.pipe_ordinal[compute_pipe] = prefix.pipe_n; + self.engine.target[compute_pipe] = f.target; + self.engine.head[compute_pipe] = f.head; + self.engine.queue_registered[compute_pipe] = true; + self.engine.pipe_use_seq = self.engine.pipe_use_seq.wrapping_add(1); + self.engine.pipe_last_vm[compute_pipe] = Some(job.vm.id); + self.engine.pipe_last_used[compute_pipe] = self.engine.pipe_use_seq; + self.engine.next_compute_pipe = ((compute_pipe + 1) % sizes::COMPUTE_PIPES) as u8; } self.engine.events = self.events.compute_events; self.engine.stage_seen = self.events.stage_events; + f.behind = behind; self.stat_publish(f); - self.renew_deadlines(); - job.progress.set_sent(index + 1); + // First in-flight command on this render class or compute pipe starts about now; + // commands queued behind the same class/pipe keep its oldest deadline. + if render { + if !class_behind { + self.renew_render_deadline(); + } + } else if !pipe_behind { + self.renew_compute_pipe_deadline(compute_pipe); + } + job.progress.set_sent(end); + for k in index..end { + job.command_published(k); + } + for j2 in f.group.iter() { + let n2 = j2.progress.count(); + j2.progress.set_sent(n2); + for k in 0..n2 { + j2.command_published(k); + } + self.engine.turn += 1; + j2.queue.turn.store(self.engine.turn, Ordering::Relaxed); + j2.progress.set_pending(false); + self.engine.pending.retain(|p| !Arc::ptr_eq(p, j2)); + } + if !render { + let s = &mut self.engine.stats; + let jobs = 1 + f.group.len(); + let bucket = (jobs - 1).min(s.hz.len() - 1); + s.hz[bucket] += 1; + if let Some(stop) = hz_stop { + s.hz_stop[stop] += 1; + } + if class_behind { + s.hz_behind += 1; + } + s.grouped = s.grouped.saturating_add(f.group.len() as u64); + } else if !f.group.is_empty() { + let s = &mut self.engine.stats; + s.grouped = s.grouped.saturating_add(f.group.len() as u64); + } let mut flight = Flight::new(job.clone()); core::mem::swap(&mut flight, f); self.engine @@ -1150,28 +3649,43 @@ impl Firmware { core::mem::forget(flight); EIO })?; + let s = &mut self.engine.stats; + s.max_flights = s.max_flights.max(self.engine.flights.len() as u64); publication.map_err(|_| EIO) } /// Encodes one command into its retained compute unit and appends it to the CDM ring. + #[expect( + clippy::too_many_arguments, + reason = "Encodes one compute member into a shared flight and prefix state." + )] fn prefix_compute( &mut self, job: &Arc, + resources: &super::resources::Prepared, + cmd_index: u32, cmd: &ComputeCommand, + c_waits: [Option; sizes::COMPUTE_PIPES], pf: &mut Prefix, f: &mut Flight, _later_render: bool, ) -> Result { + let member = pf.computes as usize; + if member >= sizes::COMPUTE_SLOTS { + return Err(EAGAIN); + } + let pipe = pf.compute_pipe; let n = super::recovery::logic::next_ordinal(pf.n).ok_or(EOVERFLOW)?; - let target = encode::stamp(n); + let pipe_n = super::recovery::logic::next_ordinal(pf.pipe_n).ok_or(EOVERFLOW)?; + let target = encode::stamp(pipe_n); let index = self .slots - .claim_compute(job.resources.compute()?, &mut f.claims, 0)? + .claim_compute_for_pipe(resources, &mut f.claims, Some(job.vm.id), pipe)? .ok_or(EAGAIN)?; let generation = job.vm.generation; - self.slots.hold_vm(&f.claims, &job.vm)?; - let s = &job.resources.compute()?.compute[index]; - let g = &self.graph.compute; + self.slots.hold_compute_slot(index, &job.vm, resources)?; + let s = resources.compute_unit(index)?; + let g = &self.graph.compute[pipe]; let before = s.counter.r64(0)?; let submitted = before.checked_add(1).ok_or(EOVERFLOW)?; let refs = ComputeRefs { @@ -1181,8 +3695,10 @@ impl Firmware { fw_stamp: g.fw_stamp.va, work: s.work.va, work_gva: s.work.lower_gva.ok_or(EINVAL)?, - // Exact embedded sequence: every self-reference then matches the 25G83 layout. - seq: s.work.va + 0x900, + // Separate device-lifetime firmware-cached microsequence record for this unit index. + seq: s.seq.va, + // Separate per-VM uncached UMA manager descriptor inside `s.uma_lease`. + descriptor_fw: s.descriptor.va, preempt_gva: s.preempt.gva.ok_or(EINVAL)?, its: s.its.va, stats_fw: self.init.compute_activity.va, @@ -1195,7 +3711,10 @@ impl Firmware { usc_base: job.queue.usc_base, record_fw: g.notifier.va + notifier_page::COMPUTE_RECORD as u64, binding_generation: generation, - uma_slot: 1, + // Each unit owns its UMA slot: the firmware starts a queued command while the + // one before it still runs, and two owners of one slot then corrupt each other. + uma_slot: engine_ids::COMPUTE_UMA_SLOT + index as u32, + event: work::compute::EVENTS[pipe], // Preserve the already qualified packet bytes while expressing the native // fields separately. This compatibility identifier is not proof of native // global command-ID allocation or uniqueness after compute-index wrap. @@ -1205,11 +3724,14 @@ impl Firmware { target_stamp: target, submitted, }; + let rt = compute_rt(&cmd.ray, s.seeds); let scratch = self.engine.scratch.as_deref_mut().ok_or(ENOMEM)?; let w = image(&mut scratch.cw)?; + let q = image(&mut scratch.cq)?; // User results are published coherently after the complete retirement receipt. // The firmware's internal timestamp pair remains enabled. - encode::encode_compute( + encode::encode_compute_rt( + self.init.abi.compute(), &refs, &cmd.cmd, &cmd.attachments, @@ -1217,62 +3739,283 @@ impl Firmware { job.vm.slot, n, 1, + &rt, w, - image(&mut scratch.cq)?, + q, ) .map_err(|_| EINVAL)?; - if before != 0 { - // Slots::claim_compute proved a different fully retired unit displaced this - // descriptor in the same hardware slot. Keep every firmware-mutated byte. - let mut descriptor = [0u8; work::compute::DESCRIPTOR_SIZE]; - s.work.read(work::compute::DESCRIPTOR, &mut descriptor)?; - if encode::preserve_compute_descriptor(&refs, &descriptor, before, w).is_err() { - // This is retained allocator identity/completion corruption, not a client - // refusal. Keep the unit and its previous VM lease mapped forever; cancelling - // preparation would make the corrupt descriptor available to another job. - self.slots.quarantine(&mut f.claims); - return Err(EIO); + s.seq.write(0, q)?; + let full_work = self.slots.compute_needs_full_work(index) || before == 0; + if full_work { + if before != 0 { + // Slots::claim_compute proved a different fully retired unit displaced this + // descriptor in the same hardware slot. Validate the retained descriptor in place. + let mut descriptor = [0u8; work::compute::DESCRIPTOR_SIZE]; + s.descriptor.read(0, &mut descriptor)?; + if encode::validate_compute_descriptor(&refs, &descriptor, before).is_err() { + // This is retained allocator identity/completion corruption, not a client + // refusal. Keep the unit and its previous VM lease mapped forever; cancelling + // preparation would make the corrupt descriptor available to another job. + self.slots.quarantine(&mut f.claims); + self.sync_quarantine_hints(); + return Err(EIO); + } + } + s.work.write(0, &w[..work::compute::BODY_ACTIVE_END])?; + } else { + // Clean same-VM reuse: `s.descriptor` stays intact in place and was authenticated on + // retirement for this exact unit and VM, static NOTIFIER (0xc00..0xd18) and tail + // (0xee0..0xf08) remain intact in place, and the live microsequence lives in + // firmware-cached `s.seq`. Write only the active head and body before `SEQ_EMBEDDED`. + s.work.write(0, &w[..work::compute::HEAD_ACTIVE_SIZE])?; + s.work.write( + work::compute::BODY_ACTIVE_START, + &w[work::compute::BODY_ACTIVE_START..work::compute::SEQ_EMBEDDED], + )?; + } + let wait_render = self.cross_engine_wait(job, cmd_index, super::command::RENDER)?; + let fs2c_bar = if let Some(wait_fs) = wait_render { + // Check producer InitBM explicitly in addition to the scheduler drain guard so + // FS -> CDM handoff: downgrade to `BarrierType::Stamp` (type 0) only when neither + // the waited render nor any live flight carries `InitBM` and the GPU does not need + // G15's cross-engine hold; G16 FS `FINALIZE` flushes caches before advancing + // `fw_stamp[1]` (see `cross_engine_barrier_type`). + let producer_initbm = self.cfg.cross_engine_hold + || wait_fs.initbm + || self.engine.flights.iter().any(|fl| fl.initbm); + let bar_type = cross_engine_barrier_type(producer_initbm, false); + let bar = encode::barrier( + self.graph.render.fw_stamp[1].va, + wait_fs.stamp, + 0x71, + target, + 0, + bar_type, + ); + s.barrier.write(0, &bar)?; + Some((wait_fs.stamp, bar_type)) + } else { + None + }; + let mut c2c_mask = 0u32; + for (p_idx, wait_opt) in c_waits.iter().enumerate() { + if p_idx == pipe { + continue; + } + if let Some(wait_c) = *wait_opt { + let producer_initbm = + wait_c.initbm || self.engine.flights.iter().any(|fl| fl.initbm); + let bar_type = cross_engine_barrier_type(producer_initbm, false); + let bar = encode::barrier( + self.graph.compute[p_idx].fw_stamp.va, + wait_c.stamp, + work::compute::EVENTS[p_idx], + target, + 0, + bar_type, + ); + let off = (1 + p_idx) * work::barrier::SIZE; + s.barrier.write(off, &bar)?; + c2c_mask |= 1u32 << p_idx; } } - s.work.write(0, w)?; f.uma_submitted = submitted; + f.csubmitted[member] = submitted; + f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); + f.rt_compute |= resources.compute_scs() || cmd.is_rt(); wmb(); + if let Some((wait_fs, bar_type)) = fs2c_bar { + g.ring.w64(8 * pf.c_head as usize, s.barrier.va)?; + pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; + if bar_type == BarrierType::Stamp { + self.engine.stats.fs2c0 += 1; + } + f.cwait[member] = wait_fs; + } else { + f.cwait[member] = 0; + } + let mut rem = c2c_mask; + while rem != 0 { + let p_idx = rem.trailing_zeros() as usize; + rem &= rem - 1; + g.ring.w64( + 8 * pf.c_head as usize, + s.barrier.va + ((1 + p_idx) * work::barrier::SIZE) as u64, + )?; + pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; + } g.ring.w64(8 * pf.c_head as usize, s.work.va)?; pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; - f.cstamp[0] = target; - f.cwait[0] = 0; - pf.computes = 1; + f.cstamp[member] = target; + pf.computes += 1; pf.n = n; + pf.pipe_n = pipe_n; pf.last_ct = target; pf.prev = Prev::Compute; Ok(()) } /// Encodes paired TA/FS work and the fragment's explicit TA dependency in one retained - /// pass unit. The preceding command already has a complete wire receipt. + /// pass unit. + #[expect( + clippy::too_many_arguments, + reason = "Encodes one render member into a shared flight and prefix state." + )] fn prefix_render( &mut self, job: &Arc, + resources: &super::resources::Prepared, + cmd_index: u32, cmd: &RenderCommand, + mut geometry: Geometry, pf: &mut Prefix, f: &mut Flight, + behind: bool, + class_behind: bool, ) -> Result { - let k = f.claims.pass[0] as usize; + let member = pf.renders as usize; + if member >= sizes::RENDER_SLOTS { + return Err(EAGAIN); + } + let k = f.claims.pass[member] as usize; let draw = super::recovery::logic::next_ordinal(pf.draw).ok_or(EOVERFLOW)?; let target = encode::stamp(draw); + let has_prior_render = class_behind || member > 0; + let prev_ta = if member > 0 { + pf.last_ta + } else { + self.engine.ta_target + }; + let prev_fs = if member > 0 { + pf.last_fs + } else { + self.engine.fs_target + }; + let order = job.command_order(cmd_index); + let staged = cmd.cmd.flags + & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES + != 0; + let ta_wait_compute = self.wait_compute_stamps_for( + job, + order.and_then(|o| o.ta_wait_through[super::command::COMPUTE]), + )?; + let fs_wait_compute = self.wait_compute_stamps_for( + job, + order.and_then(|o| o.wait_through[super::command::COMPUTE]), + )?; + let fs_wait_render = if has_prior_render { + match order { + Some(o) => self.wait_stamp_for_with( + job, + super::command::RENDER, + o.wait_through[super::command::RENDER], + Some(f), + )?, + None => Some(WaitTarget { + stamp: prev_fs, + initbm: false, + }), + } + } else { + None + }; + let ta_wait_fs = if has_prior_render && staged && params::early_tiling() { + self.wait_stamp_for_with( + job, + super::command::RENDER, + order.and_then(|o| o.ta_wait_through[super::command::RENDER]), + Some(f), + )? + } else { + None + }; + let cross_vm_prev = member == 0 + && class_behind + && self + .engine + .flights + .iter() + .rev() + .find(|fl| fl.renders != 0) + .is_some_and(|fl| !Arc::ptr_eq(&fl.job.vm, &job.vm)); + let plan_flags = if !staged + && job.fw_waits.iter().any(|w| { + w.last_ordinal[super::command::RENDER].is_some_and(|last| { + w.queue.completed[super::command::RENDER].load(Ordering::Acquire) < last + }) + }) + { + cmd.cmd.flags + & !kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS + } else { + cmd.cmd.flags + }; + let plan = plan_render_barriers( + plan_flags, + has_prior_render, + params::early_tiling(), + prev_fs, + fs_wait_render.map(|w| w.stamp), + ta_wait_fs.map(|w| w.stamp), + [ + ta_wait_compute.map(|w| w.map(|t| t.stamp)), + fs_wait_compute.map(|w| w.map(|t| t.stamp)), + ], + cross_vm_prev, + ); // Claim performs only a qualified per-use scrub, never allocator/list reset. - self.slots.claim_pass(job.resources.render()?, k)?; - self.slots.hold_vm(&f.claims, &job.vm)?; - let (refs, init_buffer) = self.render_refs(k, job, draw)?; - let p = &job.resources.render()?.passes[k]; + self.slots + .claim_pass_in(resources, k, Some(job.vm.id), geometry.tilemap_bytes)?; + self.slots.hold_render_pass(k, &job.vm, resources)?; + let (refs, init_buffer) = if member == 0 { + let (pb_mask, pb_home) = resources.pb_slot_mask()?; + let heap_blocks = resources.pb_heap_blocks()?; + let alloc_slot = self + .pools + .pick_slot_in_mask_blocks_mode( + &job.vm, + behind, + pb_mask, + pb_home, + heap_blocks, + resources.render_scs(), + ) + .ok_or(EAGAIN)?; + let slot_pipelined = self.pools.slot_inflight(alloc_slot) > 0; + let (refs, init_buffer, epoch, binding) = + self.render_refs(alloc_slot, job, draw, slot_pipelined, behind)?; + f.pb = Some(epoch); + f.pb_slot = alloc_slot as u32; + f.pb_binding = binding; + f.initbm = init_buffer; + (refs, init_buffer) + } else { + if f.initbm { + return Err(EAGAIN); + } + let epoch = f.pb.as_ref().ok_or(EINVAL)?; + let refs = self.render_refs_batched( + f.pb_slot as usize, + &f.job, + draw, + epoch, + f.uma_submitted, + )?; + (refs, false) + }; + f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); + f.heavy_render |= cmd.is_heavy_ta(); + f.msaa |= cmd.is_multisampled(); + let p = resources.render_pass(k)?; let pass = p.refs(); - let geometry = Geometry::new(&cmd.cmd, pass.heap_gva); + let heap_bytes = if cmd.cmd.layers > 1 { 0x1000 } else { 0x200 }; + geometry.layer_metadata = pass.heap_gva + if cmd.cmd.layers > 1 { 0x200 } else { 0 }; geometry.validate_capacity(p.tpc.size as u64, p.tilemap.size as u64)?; - job.resources - .render()? - .set_dirty(k, geometry.tpc_bytes, geometry.tilemap_bytes)?; + resources.set_pass_dirty(k, geometry.tpc_bytes, geometry.tilemap_bytes, heap_bytes)?; let scratch = self.engine.scratch.as_deref_mut().ok_or(ENOMEM)?; - encode::encode_ta( + let [vertex_rt, fragment_rt] = cmd.ray_query.map(|stage| stage_rt(&stage)); + encode::encode_ta_rt( + self.init.abi.ta(), &refs, &pass, &cmd.cmd, @@ -1281,10 +4024,12 @@ impl Firmware { target, &geometry, None, + &vertex_rt, image(&mut scratch.ta)?, image(&mut scratch.tas)?, ); - encode::encode_fs( + encode::encode_fs_rt( + self.init.abi.fs(), &refs, &pass, &cmd.cmd, @@ -1294,41 +4039,168 @@ impl Firmware { draw, target, &geometry, + &fragment_rt, image(&mut scratch.fs)?, &mut scratch.fss[..], ); encode::render_attachments(&mut scratch.tas[..], 0, &cmd.vertex_attachments); - encode::render_attachments(&mut scratch.fss[..], 1, &cmd.fragment_attachments); - encode::fill_scene(&refs, &pass, &mut scratch.scene[..]); - encode::scene_render( - &refs, - &pass, - &[0; 4], - job.vm.slot, - target, - init_buffer, - &mut scratch.scene[..], + encode::render_attachments_for( + &mut scratch.fss[..], + 1, + self.init.abi.fs().finalize, + &cmd.fragment_attachments, ); - p.ta_work.write(0, &scratch.ta[..])?; - p.fs_work.write(0, &scratch.fs[..])?; + let full_work = self.slots.render_needs_full_work(k); + if full_work { + encode::fill_scene(&refs, &pass, &mut scratch.scene[..]); + encode::scene_render( + &refs, + &pass, + &[0; 4], + job.vm.slot, + target, + init_buffer, + &mut scratch.scene[..], + ); + p.ta_work.write(0, &scratch.ta[..])?; + p.fs_work.write(0, &scratch.fs[..])?; + } else { + p.ta_work + .write(0, &scratch.ta[..work::ta::HEAD_ACTIVE_SIZE])?; + p.ta_work.write( + work::ta::TAIL_ACTIVE_START, + &scratch.ta[work::ta::TAIL_ACTIVE_START..], + )?; + p.fs_work + .write(0, &scratch.fs[..work::fs::HEAD_ACTIVE_SIZE])?; + p.fs_work.write( + work::fs::TAIL_ACTIVE_START, + &scratch.fs[work::fs::TAIL_ACTIVE_START..], + )?; + } p.ta_seq.write(0, &scratch.tas[..])?; p.fs_seq.write(0, &scratch.fss[..])?; - p.scene.write(0, &scratch.scene[..])?; + if full_work { + p.scene.write(0, &scratch.scene[..])?; + } else { + let hdr = encode::scene(&refs, &pass, 0); + let pfx = encode::scene_prefix(&refs, job.vm.slot, target, init_buffer); + p.scene.write(0, &hdr)?; + p.scene.fill(0x80, 0, 0x280)?; + p.scene.write(0x300, &pfx)?; + p.scene.w64(0x500, refs.uma_submitted)?; + // Zero TA/FS internal timestamp cells and targets so recovery FS execution + // proof and timestamp queries can never observe stale ticks from a prior pass. + p.scene.fill(0x600, 0, 0x40)?; + } // One retained descriptor is shared by TA and FS; its private submitted counter - // advances by two. Reused descriptors and their pool/list bytes remain intact. + // advances by two per pass. Reused descriptors and their pool/list bytes remain intact. f.uma_submitted = refs.uma_submitted; let r = &self.graph.render; let cap = sizes::QUEUE_CAP; if init_buffer { pf.initbm = true; let bm = encode::initbm(job.vm.slot, refs.parameter_id, refs.pb_mgr, target); - let epoch = job.resources.pb(job.progress.sent() as usize)?; + let epoch = f.pb.as_ref().ok_or(EINVAL)?; epoch.initbm.write(0, &bm)?; r.ring[0].w64(8 * pf.ta_head as usize, epoch.initbm.va)?; pf.ta_head = (pf.ta_head + 1) % cap; } - // Every previous command has its complete receipt before this publication. - // The paired fragment still requires the native explicit TA dependency. + // Pipelined render->render and cross-engine (CDM->TA, CDM->FS) barriers use + // `BarrierType::Stamp` (type 0) only when neither producer, any live flight, nor this + // consumer carries `InitBM`: G16 `FINALIZE` flushes producer caches before advancing + // `fw_stamp` (unlike G15's `CROSS_ENGINE_HOLD`; see `cross_engine_barrier_type`). + // Cold `InitBM` transitions and recovery paths drain completely before publishing. + let producer_initbm = pf.initbm + || self.engine.flights.iter().any(|fl| fl.initbm) + || ta_wait_compute.iter().flatten().any(|w| w.initbm) + || fs_wait_compute.iter().flatten().any(|w| w.initbm) + || fs_wait_render.is_some_and(|w| w.initbm) + || ta_wait_fs.is_some_and(|w| w.initbm); + let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer); + // Pipelined renders share TA/FS pipes across same-VM and cross-VM flights, so keep + // the TA(N-1)->TA(N) `prev_barrier` (matching G15) whenever `plan.ta_fs_wait` does not + // already serialize behind `prev_fs`. Emit `ta_fs_barrier` only when `plan.ta_fs_wait` + // names an in-flight FS stamp, and `fs_dep` when `plan.fs_render_wait` names an + // in-flight FS dependency (or cross-VM `prev_fs`) not already dominated by TA. + if plan.ta_prev_wait { + let prev = encode::barrier( + r.fw_stamp[0].va, + prev_ta, + 0x70, + target, + work::barrier::RENDER_WAIT_UUID, + render_bar, + ); + p.prev_barrier.write(0, &prev)?; + r.ring[0].w64(8 * pf.ta_head as usize, p.prev_barrier.va)?; + pf.ta_head = (pf.ta_head + 1) % cap; + } + if let Some(wait_fs) = plan.ta_fs_wait { + let ta_fs = encode::barrier( + r.fw_stamp[1].va, + wait_fs, + 0x71, + target, + work::barrier::RENDER_WAIT_UUID, + render_bar, + ); + p.ta_fs_barrier.write(0, &ta_fs)?; + r.ring[0].w64(8 * pf.ta_head as usize, p.ta_fs_barrier.va)?; + pf.ta_head = (pf.ta_head + 1) % cap; + } + if let Some(wait_fs) = plan.fs_render_wait { + let dep = encode::barrier( + r.fw_stamp[1].va, + wait_fs, + 0x71, + target, + work::barrier::RENDER_WAIT_UUID, + render_bar, + ); + p.fs_dep.write(0, &dep)?; + r.ring[1].w64(8 * pf.fs_head as usize, p.fs_dep.va)?; + pf.fs_head = (pf.fs_head + 1) % cap; + } + if plan.early { + self.engine.stats.early += 1; + } + for p_idx in 0..sizes::COMPUTE_PIPES { + let off = p_idx * work::barrier::SIZE; + if let Some(wait_c) = plan.ta_compute_wait[p_idx] { + let cbar = encode::barrier( + self.graph.compute[p_idx].fw_stamp.va, + wait_c, + work::compute::EVENTS[p_idx], + target, + work::barrier::RENDER_WAIT_UUID, + render_bar, + ); + p.compute_barrier.write(off, &cbar)?; + r.ring[0].w64(8 * pf.ta_head as usize, p.compute_barrier.va + off as u64)?; + pf.ta_head = (pf.ta_head + 1) % cap; + if render_bar == BarrierType::Stamp { + self.engine.stats.c2ta0 += 1; + } + } + if let Some(wait_c) = plan.fs_compute_wait[p_idx] { + let fcbar = encode::barrier( + self.graph.compute[p_idx].fw_stamp.va, + wait_c, + work::compute::EVENTS[p_idx], + target, + work::barrier::RENDER_WAIT_UUID, + render_bar, + ); + p.fs_compute_barrier.write(off, &fcbar)?; + r.ring[1].w64(8 * pf.fs_head as usize, p.fs_compute_barrier.va + off as u64)?; + pf.fs_head = (pf.fs_head + 1) % cap; + if render_bar == BarrierType::Stamp { + self.engine.stats.c2ta0 += 1; + } + } + } + // The paired fragment always requires the native explicit TA dependency. let own = encode::barrier( r.fw_stamp[0].va, target, @@ -1344,8 +4216,12 @@ impl Firmware { pf.fs_head = (pf.fs_head + 1) % cap; r.ring[1].w64(8 * pf.fs_head as usize, p.fs_work.va)?; pf.fs_head = (pf.fs_head + 1) % cap; - pf.renders = 1; + f.r_ta_stamp[member] = target; + f.r_fs_stamp[member] = target; + pf.renders += 1; + f.renders = pf.renders; pf.draw = draw; + pf.last_ta = target; pf.last_fs = target; pf.prev = Prev::Render; Ok(()) @@ -1356,6 +4232,10 @@ impl Firmware { let s = &mut self.engine.stats; s.pub_ns = now_ns(); f.published_ns = s.pub_ns; + if f.behind { + s.behind += 1; + s.overlaps += 1; + } s.prep_ns += s.pub_ns.wrapping_sub(s.prep_from_ns); if s.idle_from_ns != 0 { s.gap_ns += s.pub_ns.wrapping_sub(s.idle_from_ns); @@ -1369,3 +4249,35 @@ impl Firmware { self.power.utilization.busy(now); } } + +/// The compute register words of a validated command's ray state ([`super::rt`]) in a unit +/// whose UMA pool has `seeds` freelist entries, in a freelist of +/// [`super::rt::freelist_records`]. Without ray state in a base unit these are the words of +/// [`ComputeRt::DISABLED`]. +fn compute_rt(ray: &super::rt::ComputeRay, seeds: u32) -> ComputeRt { + ComputeRt { + intersection: ray.intersection.words(), + size: ray.scratch.size_word(), + tail: ray.scratch.compute_tail_word(), + stack: ray.scratch.stack_word(), + window: ray.scratch.window_word(), + driver: ray.scratch.driver_word(), + scs: ray.scratch.enabled(), + seeds, + records: super::rt::freelist_records(seeds), + } +} + +/// The TA or FS register words of a validated render stage's ray state. As the M4 Pro's +/// render programs, a stage's tail word is its scratch tail; its auxiliary intersection word +/// is validated but not written. +fn stage_rt(stage: &super::rt::RayQueryStage) -> StageRt { + StageRt { + intersection: stage.intersection.words(), + size: stage.scratch.size_word(), + tail: stage.scratch.tail_word(), + stack: stage.scratch.stack_word(), + window: stage.scratch.window_word(), + scs: stage.scratch.enabled(), + } +} diff --git a/drivers/gpu/drm/asahi/g16/event.rs b/drivers/gpu/drm/asahi/g16/event.rs index 26ef79a2c3a9a3..fa46695cb87684 100644 --- a/drivers/gpu/drm/asahi/g16/event.rs +++ b/drivers/gpu/drm/asahi/g16/event.rs @@ -3,18 +3,22 @@ //! M4 receive records. Events and statistics use complete 0x48-byte records. //! //! Type 1 carries 128 completion bits. The native runtime holds events 0x70 -//! (TA), 0x71 (fragment) and 15 (compute). Type 4 and statistics type 0x16 +//! (TA), 0x71 (fragment) and 15/16 (compute pipes 0/1). Type 4 and statistics type 0x16 //! announce the firmware's generation-based recovery; neither is a job receipt. use kernel::{bindings, device, prelude::*}; use super::channel::Ring; use super::fw::channels::{RING_SLOTS, STATE_READ, STATE_WRITE}; -use super::hw::rings; +use super::fw::work::compute; +use super::hw::{rings, sizes}; use super::regs::{mb, rmb, wmb}; pub(crate) const RECORD_WORDS: usize = 18; -pub(crate) const STAGE_EVENTS: [u32; 3] = [0x70, 0x71, 15]; +pub(crate) const STAGE_COUNT: usize = 2 + sizes::COMPUTE_PIPES; +const COMPUTE_EVENT_MASK: u32 = ((1u32 << sizes::COMPUTE_PIPES) - 1) << compute::EVENT; +const _: () = assert!(compute::EVENTS.len() == sizes::COMPUTE_PIPES); +const _: () = assert!(compute::EVENT as usize + sizes::COMPUTE_PIPES <= 32); /// Retained only for the allocator's pending-growth container. M4 does not /// interpret a G15 type-7 record as an allocator request. pub(crate) const GROW_QUEUE: usize = 8; @@ -36,6 +40,7 @@ impl ErrorEvent { pub(crate) struct Events { pub(crate) compute_events: u32, + pub(crate) fs_events: u32, pub(crate) stage_events: u32, pub(crate) errors: u32, pub(crate) last_error: Option, @@ -44,7 +49,7 @@ pub(crate) struct Events { /// First notification of the pending recovery, for its absolute deadline. pub(crate) recovery_started_ns: Option, pub(crate) channel_errors: u32, - pub(crate) event_ns: [u64; 3], + pub(crate) event_ns: [u64; STAGE_COUNT], pub(crate) grow: KVec<[u32; 14]>, #[allow(dead_code)] pub(crate) grow_lost: u32, @@ -54,6 +59,7 @@ impl Events { pub(crate) fn new() -> Self { Self { compute_events: 0, + fs_events: 0, stage_events: 0, errors: 0, last_error: None, @@ -61,7 +67,7 @@ impl Events { last_statistics: None, recovery_started_ns: None, channel_errors: 0, - event_ns: [0; 3], + event_ns: [0; STAGE_COUNT], grow: KVec::new(), grow_lost: 0, } @@ -87,33 +93,83 @@ impl Events { if producer >= RING_SLOTS || consumer >= RING_SLOTS { return Err(super::boot::eproto()); } - rmb(); + if consumer != producer { + rmb(); + } Ok((consumer, producer)) } /// Decode notifications, copying every record before returning its slot. pub(crate) fn drain(&mut self, dev: &device::Device, ring: &Ring) -> Result { let (mut read, producer) = Self::indices(ring)?; + if read == producer { + return Ok(()); + } // SAFETY: ktime_get has no preconditions. let now = unsafe { bindings::ktime_get() } as u64; let mut error = None; + let mut drained = false; + let flush_read = |ring: &Ring, read: u32| -> Result { + mb(); + ring.state.w32(STATE_READ, read)?; + wmb(); + Ok(()) + }; while read != producer { - let words = Self::words(ring, read)?; - match words[0] { + let base = read as usize * rings::EVENT_RECORD; + let kind = match ring.ring.r32(base) { + Ok(kind) => kind, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; + match kind { 1 => { - for (stage, event) in STAGE_EVENTS.iter().enumerate() { - let word = 1 + *event as usize / 32; - if words[word] & (1u32 << (*event % 32)) == 0 { - continue; + // Type 1 carries 128 completion bits across words 1..=4; compute pipe events + // (15..15+COMPUTE_PIPES) live in word 1 and TA/FS (0x70/0x71) live in word 4. + let (w1, w4) = match ring.ring.r32(base + 4).and_then(|w1| { + Ok((w1, ring.ring.r32(base + 16)?)) + }) { + Ok(pair) => pair, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); } - self.event_ns[stage] = now; + }; + if w4 & (1u32 << (0x70 % 32)) != 0 { + self.event_ns[0] = now; self.stage_events = self.stage_events.wrapping_add(1); - if stage == 2 { - self.compute_events = self.compute_events.wrapping_add(1); - } + } + if w4 & (1u32 << (0x71 % 32)) != 0 { + self.event_ns[1] = now; + self.stage_events = self.stage_events.wrapping_add(1); + self.fs_events = self.fs_events.wrapping_add(1); + } + let mut cbits = w1 & COMPUTE_EVENT_MASK; + while cbits != 0 { + let bit = cbits.trailing_zeros(); + cbits &= cbits - 1; + let pipe = (bit - compute::EVENT) as usize; + self.event_ns[2 + pipe] = now; + self.stage_events = self.stage_events.wrapping_add(1); + self.compute_events = self.compute_events.wrapping_add(1); } } 4 => { + let words = match Self::words(ring, read) { + Ok(words) => words, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; self.recovery_started_ns.get_or_insert(now); self.last_error = Some(ErrorEvent { kind: 4, @@ -124,6 +180,15 @@ impl Events { dev_warn!(dev, "M4 firmware recovery event: {:08x?}\n", words); } kind => { + let words = match Self::words(ring, read) { + Ok(words) => words, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; // The qualified M4 provider accepts only stage and recovery events. // Do not apply another firmware's context-kill or PB-growth protocol. dev_err!( @@ -137,19 +202,46 @@ impl Events { } } read = (read + 1) % RING_SLOTS; - mb(); - ring.state.w32(STATE_READ, read)?; - wmb(); + drained = true; } + flush_read(ring, read)?; error.map_or(Ok(()), Err) } /// Preserve recovery statistics instead of silently discarding their notification. pub(crate) fn drain_statistics(&mut self, dev: &device::Device, ring: &Ring) -> Result { let (mut read, producer) = Self::indices(ring)?; + if read == producer { + return Ok(()); + } + let mut drained = false; + let flush_read = |ring: &Ring, read: u32| -> Result { + mb(); + ring.state.w32(STATE_READ, read)?; + wmb(); + Ok(()) + }; while read != producer { - let words = Self::words(ring, read)?; - if words[0] == 0x16 { + let base = read as usize * rings::EVENT_RECORD; + let kind = match ring.ring.r32(base) { + Ok(kind) => kind, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; + if kind == 0x16 { + let words = match Self::words(ring, read) { + Ok(words) => words, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; // SAFETY: ktime_get has no preconditions. let now = unsafe { bindings::ktime_get() } as u64; self.recovery_started_ns.get_or_insert(now); @@ -158,10 +250,9 @@ impl Events { dev_warn!(dev, "M4 firmware recovery statistics: {:08x?}\n", words); } read = (read + 1) % RING_SLOTS; - mb(); - ring.state.w32(STATE_READ, read)?; - wmb(); + drained = true; } + flush_read(ring, read)?; Ok(()) } } diff --git a/drivers/gpu/drm/asahi/g16/feed.rs b/drivers/gpu/drm/asahi/g16/feed.rs new file mode 100644 index 00000000000000..f0c46b2d31bd27 --- /dev/null +++ b/drivers/gpu/drm/asahi/g16/feed.rs @@ -0,0 +1,413 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Detects sustained host refill gaps on G16 and temporarily raises CPU frequency +//! floors via `cpufreq` `FREQ_QOS_MIN` constraints (mirroring G17's feed actuator). +//! +//! Detector updates are lock-free and run in the monotonic nanosecond domain so they +//! work identically whether or not firmware microsequence timestamps are enabled. +//! The dedicated unbound feed worker and cpufreq policy notifier serialize frequency +//! requests under `Feed::requests`, never nesting inside `Shared::state`. + +pub(crate) mod detector; + +use core::{ + pin::Pin, + sync::atomic::{AtomicBool, Ordering}, +}; +use kernel::{ + prelude::*, + sync::Arc, + time::{delay::fsleep, ClockSource, Delta, Monotonic}, +}; + +#[cfg(CONFIG_CPU_FREQ)] +use core::ptr; +#[cfg(CONFIG_CPU_FREQ)] +use kernel::{bindings, new_mutex, sync::Mutex, types::Opaque}; + +use detector::Detector; + +const POLL_MS: i64 = 2; +#[cfg(CONFIG_CPU_FREQ)] +const FLOOR_PERCENT: u64 = 100; +const WAIT_UTIL_MIN: u32 = 512; +const WAIT_HINT_MS: u32 = 8; +#[cfg(CONFIG_CPU_FREQ)] +const MAX_POLICIES: usize = 8; + +#[cfg(CONFIG_CPU_FREQ)] +#[pin_data] +struct Requests { + #[pin] + requests: Opaque<[bindings::freq_qos_request; MAX_POLICIES]>, + policies: [*mut bindings::cpufreq_policy; MAX_POLICIES], + maxima: [u32; MAX_POLICIES], + applied: [u32; MAX_POLICIES], +} + +// SAFETY: Each nonnull policy owns a kobject reference. The device requests mutex +// serializes the pinned slots with the worker and policy callbacks. +#[cfg(CONFIG_CPU_FREQ)] +unsafe impl Send for Requests {} + +#[cfg(CONFIG_CPU_FREQ)] +impl Requests { + fn new() -> Self { + Self { + requests: Opaque::zeroed(), + policies: [ptr::null_mut(); MAX_POLICIES], + maxima: [0; MAX_POLICIES], + applied: [0; MAX_POLICIES], + } + } + + fn target_floor(maximum: u32, enabled: bool) -> u32 { + if enabled { + (u64::from(maximum) * FLOOR_PERCENT / 100) as u32 + } else { + bindings::FREQ_QOS_MIN_DEFAULT_VALUE as u32 + } + } + + /// Add a policy to the pinned requests. + /// + /// # Safety + /// + /// The caller holds the policy's read or write lock and keeps it alive. + /// Policy removal must subsequently pass through this device's notifier. + unsafe fn add(self: Pin<&mut Self>, policy: *mut bindings::cpufreq_policy) { + let this = self.project(); + if this.policies.contains(&policy) { + return; + } + let Some(index) = this.policies.iter().position(|entry| entry.is_null()) else { + return; + }; + // SAFETY: The caller keeps the initialized policy alive. The vacant request + // slot is pinned and exclusively owned under the requests mutex. + let result = unsafe { + bindings::freq_qos_add_request( + ptr::addr_of_mut!((*policy).constraints), + this.requests + .get() + .cast::() + .add(index), + bindings::freq_qos_req_type_FREQ_QOS_MIN, + bindings::FREQ_QOS_MIN_DEFAULT_VALUE as i32, + ) + }; + if result >= 0 { + // SAFETY: The caller's policy reference or CREATE callback keeps the + // kobject alive until REMOVE or shutdown removes this request. + unsafe { + bindings::kobject_get(ptr::addr_of_mut!((*policy).kobj)); + this.maxima[index] = (*policy).cpuinfo.max_freq; + } + this.policies[index] = policy; + this.applied[index] = bindings::FREQ_QOS_MIN_DEFAULT_VALUE; + } + } + + fn apply(self: Pin<&mut Self>, enabled: bool) -> bool { + let this = self.project(); + let mut applied = false; + for index in 0..MAX_POLICIES { + if this.policies[index].is_null() { + continue; + } + let value = Self::target_floor(this.maxima[index], enabled); + if this.applied[index] != value { + // SAFETY: This slot is registered, pinned and exclusively locked; + // the policy reference keeps its constraints alive through REMOVE. + let result = unsafe { + bindings::freq_qos_update_request( + this.requests + .get() + .cast::() + .add(index), + value as i32, + ) + }; + if result >= 0 { + this.applied[index] = value; + } + } + applied |= this.applied[index] != bindings::FREQ_QOS_MIN_DEFAULT_VALUE; + } + applied + } + + fn remove(self: Pin<&mut Self>, policy: *mut bindings::cpufreq_policy) { + let this = self.project(); + let Some(index) = this.policies.iter().position(|entry| *entry == policy) else { + return; + }; + // SAFETY: This registered pinned slot is exclusively locked. Keep all other + // request slots at their original addresses when releasing this slot. + unsafe { + bindings::freq_qos_remove_request( + this.requests + .get() + .cast::() + .add(index), + ); + bindings::cpufreq_cpu_put(policy); + } + this.policies[index] = ptr::null_mut(); + this.maxima[index] = 0; + this.applied[index] = bindings::FREQ_QOS_MIN_DEFAULT_VALUE; + } + + fn clear(mut self: Pin<&mut Self>) { + for index in 0..MAX_POLICIES { + let policy = self.policies[index]; + if !policy.is_null() { + self.as_mut().remove(policy); + } + } + } +} + +/// Only the blocking notifier core accesses this block after registration. +#[cfg(CONFIG_CPU_FREQ)] +#[pin_data] +struct PolicyNotifier { + #[pin] + block: Opaque, +} + +// SAFETY: The pinned notifier is registered once before publishing Feed and +// unregistered at shutdown. The blocking notifier core serializes its links; +// callbacks use only Feed's atomic state and request mutex. +#[cfg(CONFIG_CPU_FREQ)] +unsafe impl Send for PolicyNotifier {} +// SAFETY: As above; no Rust access mutates the registered block. +#[cfg(CONFIG_CPU_FREQ)] +unsafe impl Sync for PolicyNotifier {} + +#[pin_data(PinnedDrop)] +pub(crate) struct Feed { + detector: Detector, + #[cfg(CONFIG_CPU_FREQ)] + #[pin] + requests: Mutex, + #[cfg(CONFIG_CPU_FREQ)] + #[pin] + notifier: PolicyNotifier, + #[cfg(CONFIG_CPU_FREQ)] + registered: AtomicBool, + applied: AtomicBool, +} + +impl Feed { + pub(crate) fn new() -> Result> { + let feed = Arc::pin_init( + pin_init!(Self { + detector: Detector::new(), + #[cfg(CONFIG_CPU_FREQ)] + requests <- new_mutex!(Requests::new(), "G16 CPU feed"), + #[cfg(CONFIG_CPU_FREQ)] + notifier <- pin_init!(PolicyNotifier { + block: Opaque::new(bindings::notifier_block { + notifier_call: Some(Self::policy_event), + next: ptr::null_mut(), + priority: 0, + }), + }), + #[cfg(CONFIG_CPU_FREQ)] + registered: AtomicBool::new(false), + applied: AtomicBool::new(false), + }), + GFP_KERNEL, + )?; + #[cfg(CONFIG_CPU_FREQ)] + feed.register_policies(); + Ok(feed) + } + + /// Seed existing policies once; later creation/removal is event driven. + #[cfg(CONFIG_CPU_FREQ)] + fn register_policies(&self) { + // SAFETY: Feed is pinned in its Arc and has not been published. The + // notifier block lives until shutdown unregisters and joins callbacks. + let result = unsafe { + bindings::cpufreq_register_notifier( + self.notifier.block.get(), + bindings::CPUFREQ_POLICY_NOTIFIER, + ) + }; + if result < 0 { + return; + } + self.registered.store(true, Ordering::Release); + // SAFETY: nr_cpu_ids is initialized before driver probe. + let cpus = unsafe { bindings::nr_cpu_ids }; + for cpu in 0..cpus { + // SAFETY: The bounded CPU index is valid; a nonnull result owns a reference. + let policy = unsafe { bindings::cpufreq_cpu_get(cpu) }; + if policy.is_null() { + continue; + } + // SAFETY: The retained reference keeps the policy and rwsem alive. + unsafe { bindings::down_read(ptr::addr_of_mut!((*policy).rwsem)) }; + { + let mut requests = self.requests.lock(); + // SAFETY: The CPU index is valid; balance this extra reference below. + let current = unsafe { bindings::cpufreq_cpu_get(cpu) }; + // SAFETY: The policy read lock excludes unfinished CREATE. + let initialized = + current == policy && unsafe { !(*policy).max_freq_req.qos.is_null() }; + if initialized { + // SAFETY: The reference and read lock keep the policy alive. + unsafe { requests.as_mut().add(policy) }; + } + if !current.is_null() { + // SAFETY: Balances the second lookup. + unsafe { bindings::cpufreq_cpu_put(current) }; + } + } + // SAFETY: Balance the read lock and first lookup after releasing requests. + unsafe { + bindings::up_read(ptr::addr_of_mut!((*policy).rwsem)); + bindings::cpufreq_cpu_put(policy); + } + } + } + + /// Process a cpufreq policy notification. + /// + /// # Safety + /// + /// `block` must be this pinned Feed's registered notifier, and `data` must + /// point to the live policy supplied by the cpufreq notifier core. + #[cfg(CONFIG_CPU_FREQ)] + unsafe extern "C" fn policy_event( + block: *mut bindings::notifier_block, + event: c_ulong, + data: *mut core::ffi::c_void, + ) -> core::ffi::c_int { + // SAFETY: Installed only on Feed::notifier.block; owner stays pinned until unregister. + let notifier = + unsafe { kernel::container_of!(Opaque::cast_from(block), PolicyNotifier, block) }; + // SAFETY: The notifier is the embedded, pinned field of this live Feed. + let feed = unsafe { &*kernel::container_of!(notifier, Feed, notifier) }; + let policy = data.cast::(); + let mut requests = feed.requests.lock(); + if event == bindings::CPUFREQ_REMOVE_POLICY as c_ulong { + requests.as_mut().remove(policy); + } else if event == bindings::CPUFREQ_CREATE_POLICY as c_ulong + && !feed.detector.is_stopped_or_paused() + { + // SAFETY: CREATE supplies an initialized policy with its write lock held. + unsafe { requests.as_mut().add(policy) }; + } else { + return bindings::NOTIFY_DONE as i32; + } + let enabled = feed.detector.wanted(Self::now()); + let applied = requests.as_mut().apply(enabled); + feed.applied.store(applied, Ordering::Relaxed); + bindings::NOTIFY_OK as i32 + } + + fn now() -> u64 { + Monotonic::ktime_get() as u64 + } + + /// Records a completed flight's monotonic `[published_ns, retired_ns]` interval. + pub(crate) fn note_flight(&self, published_ns: u64, retired_ns: u64) { + if cfg!(CONFIG_CPU_FREQ) { + self.detector.note(published_ns, retired_ns, retired_ns); + } + } + + /// Consumes a pending boost request after a poll/submit pass outside `Shared::state`. + pub(crate) fn take_pending(&self) -> bool { + self.detector.take_pending() + } + + #[cfg(CONFIG_CPU_FREQ)] + fn apply(&self, enabled: bool) { + let mut requests = self.requests.lock(); + let enabled = enabled && !self.detector.is_stopped_or_paused(); + let applied = requests.as_mut().apply(enabled); + self.applied.store(applied, Ordering::Relaxed); + } + + #[cfg(not(CONFIG_CPU_FREQ))] + fn apply(&self, _enabled: bool) {} + + /// Worker context; keeps the CPU floor active until the linger deadline expires. + pub(crate) fn run(&self) { + loop { + if self.detector.wanted(Self::now()) { + self.apply(true); + fsleep(Delta::from_millis(POLL_MS)); + continue; + } + self.apply(false); + self.detector.clear_active(); + if self.detector.wanted(Self::now()) && self.detector.try_claim_active() { + continue; + } + return; + } + } + + pub(crate) fn wait_hint(&self) -> Option<(u32, u32)> { + if cfg!(CONFIG_UCLAMP_TASK) + && self.detector.wanted(Self::now()) + && self.applied.load(Ordering::Relaxed) + { + Some((WAIT_UTIL_MIN, WAIT_HINT_MS)) + } else { + None + } + } + + /// Pauses boosting before entering system sleep; call before draining `feed_wq`. + pub(crate) fn pause(&self) { + self.detector.pause(); + } + + /// Releases any active CPU floor after `feed_wq` has drained for system sleep. + pub(crate) fn release_floor(&self) { + self.apply(false); + self.detector.clear_active(); + } + + /// Resumes refill-pressure detection after system wake or a refused sleep. + pub(crate) fn resume(&self) { + self.detector.resume(); + } + + /// Closes the detector on fail-stop or teardown. + pub(crate) fn begin_shutdown(&self) { + self.detector.begin_shutdown(); + } + + /// Unregisters cpufreq policy callbacks and removes all frequency requests. + pub(crate) fn shutdown(&self) { + self.begin_shutdown(); + #[cfg(CONFIG_CPU_FREQ)] + { + if self.registered.swap(false, Ordering::AcqRel) { + // SAFETY: The block was registered successfully and remains pinned until return. + unsafe { + bindings::cpufreq_unregister_notifier( + self.notifier.block.get(), + bindings::CPUFREQ_POLICY_NOTIFIER, + ); + } + } + self.requests.lock().as_mut().clear(); + } + self.applied.store(false, Ordering::Relaxed); + } +} + +#[pinned_drop] +impl PinnedDrop for Feed { + fn drop(self: Pin<&mut Self>) { + self.shutdown(); + } +} diff --git a/drivers/gpu/drm/asahi/g16/feed/detector.rs b/drivers/gpu/drm/asahi/g16/feed/detector.rs new file mode 100644 index 00000000000000..3473faf8a3b549 --- /dev/null +++ b/drivers/gpu/drm/asahi/g16/feed/detector.rs @@ -0,0 +1,302 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Lock-free host-refill pressure detector for G16 CPU frequency boosting. +//! +//! Tracks monotonic flight `[published_ns, retired_ns]` intervals so detection works +//! identically whether or not firmware microsequence timestamps are enabled. + +use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; + +/// Maximum inter-flight idle gap (2 ms) that still counts as an active back-to-back burst +/// rather than paced desktop/compositor rendering (60 Hz = 16.67 ms, 120 Hz = 8.33 ms). +pub(crate) const MAX_REFILL_NS: u64 = 2_000_000; +/// Consecutive sub-`MAX_REFILL_NS` flight completions required before engaging CPU boost. +pub(crate) const STREAK_ON: u32 = 8; +/// Upper saturation bound on the consecutive-burst streak counter. +pub(crate) const STREAK_MAX: u32 = 64; +/// How long CPU capacity boost lingers after the most recent refill-pressure sample. +pub(crate) const LINGER_NS: u64 = 8_000_000; +/// EWMA busy-sum ceiling (~8x 600 us incremental flight time) below which overlapping +/// pipelined (`d >= 2`) flights are still host-recording-bound rather than GPU-bound. +pub(crate) const SHORT_PIPELINE_BUSY_SUM_NS: u64 = 4_800_000; + +/// Lock-free refill-gap detector shared between completion retirement and the feed worker. +pub(crate) struct Detector { + last_end: AtomicU64, + idle: AtomicU64, + busy: AtomicU64, + streak: AtomicU32, + until: AtomicU64, + bound_until: AtomicU64, + active: AtomicBool, + pending: AtomicBool, + paused: AtomicBool, + stopping: AtomicBool, +} + +impl Detector { + pub(crate) const fn new() -> Self { + Self { + last_end: AtomicU64::new(0), + idle: AtomicU64::new(0), + busy: AtomicU64::new(0), + streak: AtomicU32::new(0), + until: AtomicU64::new(0), + bound_until: AtomicU64::new(0), + active: AtomicBool::new(false), + pending: AtomicBool::new(false), + paused: AtomicBool::new(false), + stopping: AtomicBool::new(false), + } + } + + fn decay_add(sum: &AtomicU64, add: u64) -> u64 { + let mut value = sum.load(Ordering::Acquire); + loop { + let next = value - value / 8 + add; + match sum.compare_exchange_weak(value, next, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return next, + Err(observed) => value = observed, + } + } + } + + /// Records one completed flight's monotonic `[start_ns, end_ns]` span. + pub(crate) fn note(&self, start_ns: u64, end_ns: u64, now_ns: u64) { + if start_ns == 0 + || end_ns <= start_ns + || self.paused.load(Ordering::Acquire) + || self.stopping.load(Ordering::Acquire) + { + return; + } + let previous = self.last_end.fetch_max(end_ns, Ordering::AcqRel); + let overlapped = previous != 0 && start_ns < previous; + let (idle, busy, paced) = if previous == 0 { + (0, end_ns - start_ns, true) + } else if start_ns >= previous { + let gap = start_ns - previous; + if gap < MAX_REFILL_NS { + (gap, end_ns - start_ns, false) + } else { + (0, end_ns - start_ns, true) + } + } else if end_ns > previous { + (0, end_ns - previous, false) + } else { + (0, 0, false) + }; + let idle_sum = Self::decay_add(&self.idle, idle); + let busy_sum = Self::decay_add(&self.busy, busy); + let streak = if paced { + self.streak.store(0, Ordering::Release); + 0 + } else { + let mut value = self.streak.load(Ordering::Acquire); + loop { + let next = (value + 1).min(STREAK_MAX); + match self.streak.compare_exchange_weak( + value, + next, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => break next, + Err(observed) => value = observed, + } + } + }; + if streak < STREAK_ON { + return; + } + if idle_sum.saturating_mul(4) >= busy_sum + || (overlapped && busy_sum <= SHORT_PIPELINE_BUSY_SUM_NS) + { + self.until + .store(now_ns.saturating_add(LINGER_NS), Ordering::Release); + if !self.active.swap(true, Ordering::AcqRel) { + self.pending.store(true, Ordering::Release); + } + } else { + self.bound_until + .store(now_ns.saturating_add(LINGER_NS), Ordering::Release); + } + } + + pub(crate) fn wanted(&self, now_ns: u64) -> bool { + !self.stopping.load(Ordering::Acquire) + && !self.paused.load(Ordering::Acquire) + && now_ns < self.until.load(Ordering::Acquire) + } + + #[allow(dead_code)] + pub(crate) fn bound(&self, now_ns: u64) -> bool { + !self.stopping.load(Ordering::Acquire) + && !self.paused.load(Ordering::Acquire) + && now_ns < self.bound_until.load(Ordering::Acquire) + } + + pub(crate) fn take_pending(&self) -> bool { + self.pending.swap(false, Ordering::AcqRel) + } + + pub(crate) fn clear_active(&self) { + self.active.store(false, Ordering::SeqCst); + } + + pub(crate) fn try_claim_active(&self) -> bool { + !self.active.swap(true, Ordering::AcqRel) + } + + pub(crate) fn pause(&self) { + self.paused.store(true, Ordering::Release); + self.pending.store(false, Ordering::Release); + self.until.store(0, Ordering::Release); + self.bound_until.store(0, Ordering::Release); + self.streak.store(0, Ordering::Release); + } + + pub(crate) fn resume(&self) { + self.last_end.store(0, Ordering::Release); + self.idle.store(0, Ordering::Release); + self.busy.store(0, Ordering::Release); + self.streak.store(0, Ordering::Release); + self.paused.store(false, Ordering::Release); + } + + pub(crate) fn begin_shutdown(&self) { + self.stopping.store(true, Ordering::Release); + self.pending.store(false, Ordering::Release); + } + + pub(crate) fn is_stopped_or_paused(&self) -> bool { + self.stopping.load(Ordering::Acquire) || self.paused.load(Ordering::Acquire) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(detector: &Detector, flights: u64, busy_ns: u64, gap_ns: u64) -> u64 { + let mut start = 10_000_000; + for _ in 0..flights { + let end = start + busy_ns; + detector.note(start, end, end); + start = end + gap_ns; + } + start - gap_ns + } + + #[test] + fn cpu_refill_bound_burst_requests_boost_and_expires_after_linger() { + let d = Detector::new(); + // 170 us GPU flight with 450 us host recording gap (d=1 bindless_ubo / mdi). + let now = run(&d, 16, 170_000, 450_000); + assert!(d.wanted(now)); + assert!(d.take_pending()); + assert!(!d.take_pending()); + assert!(!d.bound(now)); + assert!(!d.wanted(now + LINGER_NS)); + } + + #[test] + fn gpu_bound_back_to_back_flights_do_not_boost_cpu() { + let d = Detector::new(); + // 2 ms GPU flights with 40 us host gaps: GPU-bound, not host-refill-bound. + let now = run(&d, 16, 2_000_000, 40_000); + assert!(d.bound(now)); + assert!(!d.wanted(now)); + assert!(!d.take_pending()); + assert!(!d.bound(now + LINGER_NS)); + } + + #[test] + fn desktop_60hz_and_120hz_pacing_never_triggers_boost() { + for period_ns in [16_666_667u64, 8_333_333u64] { + let d = Detector::new(); + let now = run(&d, 20, 1_500_000, period_ns - 1_500_000); + assert!(!d.wanted(now)); + assert!(!d.bound(now)); + assert!(!d.take_pending()); + } + } + + #[test] + fn short_runs_and_pause_resume_lifecycle_gate_boost_cleanly() { + let d = Detector::new(); + // Fewer than STREAK_ON back-to-back flights cannot arm boost. + let now = run(&d, u64::from(STREAK_ON), 100_000, 300_000); + assert!(!d.wanted(now)); + assert!(!d.take_pending()); + + // One more flight reaches streak == STREAK_ON and arms boost. + let start = now + 300_000; + let end = start + 100_000; + d.note(start, end, end); + assert!(d.wanted(end)); + assert!(d.take_pending()); + + // Suspend pause drops wanted immediately and ignores samples until resume. + assert!(!d.is_stopped_or_paused()); + assert!(!d.try_claim_active()); + d.pause(); + assert!(d.is_stopped_or_paused()); + assert!(!d.wanted(end)); + d.note(end + 100_000, end + 200_000, end + 200_000); + assert!(!d.wanted(end + 200_000)); + + // After resume + worker clear_active, try_claim_active works and a fresh burst re-arms. + d.clear_active(); + assert!(d.try_claim_active()); + d.clear_active(); + d.resume(); + assert!(!d.is_stopped_or_paused()); + let resumed_now = run(&d, 16, 150_000, 400_000); + assert!(d.wanted(resumed_now)); + assert!(d.take_pending()); + + // Shutdown permanently suppresses boost. + d.begin_shutdown(); + assert!(d.is_stopped_or_paused()); + assert!(!d.wanted(resumed_now)); + assert!(!d.take_pending()); + } + + #[test] + fn pipelined_d2_cpu_recording_burst_sustains_boost_and_expires_after_linger() { + let d = Detector::new(); + // Overlapping d=2 short flights (~300 us GPU duration, 200 us host submit cadence): + // idle gap is 0 while overlapping, so EWMA busy_sum (~1.6 ms) sustains CPU boost. + let mut start = 10_000_000u64; + let mut last_end = 0u64; + for _ in 0..20 { + let end = start + 300_000; + d.note(start, end, end); + last_end = end; + start += 200_000; + } + assert!(d.wanted(last_end)); + assert!(d.take_pending()); + assert!(!d.bound(last_end)); + assert!(!d.wanted(last_end + LINGER_NS)); + } + + #[test] + fn pipelined_d2_gpu_bound_flights_do_not_boost_cpu() { + let d = Detector::new(); + // Overlapping d=2 long GPU-bound flights (2 ms GPU duration, 1.8 ms cadence): + // EWMA busy_sum (~14.4 ms >> SHORT_PIPELINE_BUSY_SUM_NS) stays GPU-bound without boost. + let mut start = 10_000_000u64; + let mut last_end = 0u64; + for _ in 0..20 { + let end = start + 2_000_000; + d.note(start, end, end); + last_end = end; + start += 1_800_000; + } + assert!(d.bound(last_end)); + assert!(!d.wanted(last_end)); + assert!(!d.take_pending()); + } +} diff --git a/drivers/gpu/drm/asahi/g16/fence.rs b/drivers/gpu/drm/asahi/g16/fence.rs index 01ba768b313b72..60d76623523187 100644 --- a/drivers/gpu/drm/asahi/g16/fence.rs +++ b/drivers/gpu/drm/asahi/g16/fence.rs @@ -12,6 +12,7 @@ //! queue teardown). Fences of one context must signal in order, so a [`Timeline`] holds a //! completed fence back until every earlier fence of the queue has completed. +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use kernel::{ c_str, dma_fence::{Fence, FenceContexts, FenceObject, FenceOps, RawDmaFence, UserFence}, @@ -21,8 +22,59 @@ use kernel::{ sync::{Arc, LockClassKey, Mutex}, }; +use super::queue::QueueState; use crate::file::SyncItem; +/// Inline storage for the common 0-2 input fences, spilling to a heap `KVec` above 2. +pub(crate) enum InputFences { + Empty, + One([Fence; 1]), + Two([Fence; 2]), + Heap(KVec), +} + +impl InputFences { + pub(crate) const fn new() -> Self { + Self::Empty + } + + pub(crate) fn push(&mut self, fence: Fence) -> Result { + match self { + Self::Heap(vec) => vec.push(fence, GFP_KERNEL)?, + Self::Two(_) => { + // Allocate before moving inline entries so OOM leaves `self` intact. + let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; + if let Self::Two([a, b]) = core::mem::replace(self, Self::Empty) { + let _ = vec.push_within_capacity(a); + let _ = vec.push_within_capacity(b); + let _ = vec.push_within_capacity(fence); + } + *self = Self::Heap(vec); + } + Self::One(_) => { + if let Self::One([a]) = core::mem::replace(self, Self::Empty) { + *self = Self::Two([a, fence]); + } + } + Self::Empty => *self = Self::One([fence]), + } + Ok(()) + } +} + +impl core::ops::Deref for InputFences { + type Target = [Fence]; + + fn deref(&self) -> &[Fence] { + match self { + Self::Empty => &[], + Self::One(items) => items, + Self::Two(items) => items, + Self::Heap(vec) => vec, + } + } +} + /// Reads a retained dependency's completion status without waiting or invoking callbacks. pub(crate) fn dependency_status(fence: &Fence) -> i32 { // SAFETY: The Fence reference keeps its dma_fence alive throughout the status read. @@ -69,9 +121,153 @@ pub(crate) fn wait_dependencies(inputs: &[Fence]) -> Result { static TIMELINE_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); static ERROR_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); +static JOB_FENCE_OPS: AtomicUsize = AtomicUsize::new(0); + +/// Maximum distinct cross-queue firmware waits carried inline/on-heap by one job. +pub(crate) const MAX_FW_WAITS: usize = 8; + +/// Immutable origin and atomic lifecycle flags attached to every G16 job fence so another +/// logical queue on the same GPU and VM can resolve a binary or timeline semaphore into an +/// in-firmware ring barrier instead of round-tripping through `drm_sched` and CPU retirement. +pub(crate) struct FenceOrigin { + pub(crate) gpu_id: usize, + pub(crate) vm_id: u64, + pub(crate) queue: Arc, + pub(crate) last_ordinal: [Option; 2], + enqueued: AtomicBool, + failed: AtomicBool, +} + +impl FenceOrigin { + pub(crate) fn new( + gpu_id: usize, + vm_id: u64, + queue: Arc, + last_ordinal: [Option; 2], + ) -> Self { + Self { + gpu_id, + vm_id, + queue, + last_ordinal, + enqueued: AtomicBool::new(false), + failed: AtomicBool::new(false), + } + } + + pub(crate) fn mark_enqueued(&self) { + self.enqueued.store(true, Ordering::Release); + } + + pub(crate) fn is_enqueued(&self) -> bool { + self.enqueued.load(Ordering::Acquire) + } + + pub(crate) fn mark_failed(&self) { + self.failed.store(true, Ordering::Release); + } + + pub(crate) fn is_failed(&self) -> bool { + self.failed.load(Ordering::Acquire) + } +} + +/// One per-queue cross-queue firmware barrier target, coalescing multiple fences from the same +/// logical queue (e.g. from a timeline semaphore chain or repeated input syncs) to the highest +/// required render and compute ordinals on that queue. +pub(crate) struct FwWait { + pub(crate) queue: Arc, + pub(crate) last_ordinal: [Option; 2], + origin: Arc, +} + +impl FwWait { + pub(crate) fn is_failed(&self) -> bool { + self.origin.is_failed() + } +} + +/// Cross-queue firmware waits resolved at `SUBMIT` (inline for 0-1 queues, bounded to +/// [`MAX_FW_WAITS`] distinct logical queues). +pub(crate) enum FwWaits { + Empty, + One([FwWait; 1]), + Heap(KVec), +} + +impl FwWaits { + fn push_unique(&mut self, origin: Arc) -> Result { + let existing = match self { + Self::Empty => None, + Self::One(items) => items + .iter_mut() + .find(|wait| Arc::ptr_eq(&wait.queue, &origin.queue)), + Self::Heap(vec) => vec + .iter_mut() + .find(|wait| Arc::ptr_eq(&wait.queue, &origin.queue)), + }; + if let Some(wait) = existing { + let mut newer = false; + for engine in 0..2 { + if let Some(seq) = origin.last_ordinal[engine] { + match wait.last_ordinal[engine] { + Some(cur) if seq > cur => { + wait.last_ordinal[engine] = Some(seq); + newer = true; + } + None => { + wait.last_ordinal[engine] = Some(seq); + newer = true; + } + _ => {} + } + } + } + if newer { + wait.origin = origin; + } + return Ok(()); + } + if self.len() >= MAX_FW_WAITS { + return Err(E2BIG); + } + let wait = FwWait { + queue: origin.queue.clone(), + last_ordinal: origin.last_ordinal, + origin, + }; + match self { + Self::Empty => *self = Self::One([wait]), + Self::One(_) => { + let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; + if let Self::One([first]) = core::mem::replace(self, Self::Empty) { + let _ = vec.push_within_capacity(first); + let _ = vec.push_within_capacity(wait); + } + *self = Self::Heap(vec); + } + Self::Heap(vec) => vec.push(wait, GFP_KERNEL)?, + } + Ok(()) + } +} + +impl core::ops::Deref for FwWaits { + type Target = [FwWait]; + + fn deref(&self) -> &[FwWait] { + match self { + Self::Empty => &[], + Self::One(items) => items, + Self::Heap(vec) => vec, + } + } +} /// Fence operations of G16 job fences. -pub(crate) struct JobFenceOps; +pub(crate) struct JobFenceOps { + origin: Arc, +} #[vtable] impl FenceOps for JobFenceOps { @@ -84,6 +280,99 @@ impl FenceOps for JobFenceOps { } } +/// Fence operations of pre-signalled refused-submission fences (distinct vtable from +/// [`JobFenceOps`] so refused error fences never match [`origin_from_raw`]). +struct RefusedFenceOps; + +#[vtable] +impl FenceOps for RefusedFenceOps { + fn get_driver_name<'a>(self: &'a FenceObject) -> &'a CStr { + c_str!("aurora") + } + + fn get_timeline_name<'a>(self: &'a FenceObject) -> &'a CStr { + c_str!("g16-refused") + } +} + +/// Resolves a G16 [`FenceOrigin`] from a raw `dma_fence` pointer if and only if its vtable +/// pointer matches the registered [`JobFenceOps`] vtable. +/// +/// # Safety +/// +/// `raw` must be null or point to a live, initialized `dma_fence` whose reference is held for +/// the duration of this call. +unsafe fn origin_from_raw(raw: *mut kernel::bindings::dma_fence) -> Option> { + let expected = JOB_FENCE_OPS.load(Ordering::Acquire); + if expected == 0 || raw.is_null() { + return None; + } + // SAFETY: Caller retains a live dma_fence reference. `JobFenceOps` has a distinct timeline + // name and nontrivial payload drop (`Arc`). No cast precedes the exact + // registered vtable check, and `FenceObject` begins with its `dma_fence`. + let object = unsafe { + if (*raw).ops as usize != expected { + return None; + } + &*(raw as *const FenceObject) + }; + Some(object.origin.clone()) +} + +/// Resolves `inputs` into same-GPU, same-VM in-firmware cross-queue waits outside the device +/// lock. Returns `None` if any leaf is failed, foreign, cross-VM, not yet enqueued, or exceeds +/// [`MAX_FW_WAITS`], leaving the caller to retain normal `drm_sched` / `InputFences` waits. +pub(crate) fn resolve_fw_waits(inputs: &[Fence], gpu_id: usize, vm_id: u64) -> Option { + if inputs.is_empty() { + return Some(FwWaits::Empty); + } + let mut waits = FwWaits::Empty; + for input in inputs { + let status = dependency_status(input); + if status < 0 { + return None; + } + if status > 0 { + continue; + } + let leaves = crate::g17::sync_input::collect_coalesced(input)?; + for leaf in leaves.iter() { + if leaf.status < 0 { + return None; + } + if leaf.status > 0 { + continue; + } + // SAFETY: `leaf` retains an owned reference to `leaf.fence` until dropped. + let origin = unsafe { origin_from_raw(leaf.fence) }?; + if origin.gpu_id != gpu_id + || origin.vm_id != vm_id + || !origin.is_enqueued() + || origin.is_failed() + || origin.last_ordinal == [None, None] + { + return None; + } + waits.push_unique(origin).ok()?; + } + } + Some(waits) +} + +/// Stack batch size for signalling completed fences outside `Timeline::pending`. +const SIGNAL_BATCH: usize = 8; + +unsafe extern "C" { + fn asahi_g17_signal_fence(fence: *mut kernel::bindings::dma_fence); +} + +/// Signals a completed job fence, draining any attached cumulative output scopes on the +/// current CPU instead of bouncing each scope through `irq_work`. +fn signal_fence(fence: &UserFence) { + // SAFETY: `fence` is a live `dma_fence` reference kept alive for the call. + unsafe { asahi_g17_signal_fence(fence.raw()) }; +} + /// An accepted fence of a timeline that has not signalled yet. struct Pending { fence: UserFence, @@ -98,6 +387,11 @@ pub(crate) struct Timeline { jobs: FenceContexts, /// One context for the error fences of refused submissions, each signalled at creation. errors: FenceContexts, + /// Serializes dma-fence signalling outside `pending` so fences of this context always + /// signal in creation order without holding `pending` across callbacks. + /// Lock order: `signaller` -> `pending` (never reversed; `next()` locks only `pending`). + #[pin] + signaller: Mutex<()>, /// Accepted fences that have not signalled, oldest first. #[pin] pending: Mutex>, @@ -113,6 +407,7 @@ impl Timeline { try_pin_init!(Self { jobs: FenceContexts::new(1, c_str!("aurora_g16_queue"), TIMELINE_KEY)?, errors, + signaller <- new_mutex!((), "g16::Timeline::signaller"), pending <- new_mutex!(KVec::new(), "g16::Timeline::pending"), allocation_failure, }), @@ -122,11 +417,23 @@ impl Timeline { /// Creates the fence of the next accepted job. Fences are created in submission order: the /// caller holds the queue (SUBMIT is serialized per queue). - pub(crate) fn next(self: &Arc) -> Result { + pub(crate) fn next(self: &Arc, origin: Arc) -> Result { // SUBMIT already holds the logical queue, so allocating the next sequence before // taking pending preserves creation order. Fence completion needs pending too: // never enter reclaim while holding that mutex. - let fence: UserFence = self.jobs.new_fence(0, JobFenceOps)?.into(); + let fence: UserFence = self.jobs.new_fence(0, JobFenceOps { origin })?.into(); + // SAFETY: `fence` is a live `UserFence` whose `dma_fence::ops` is static. + let ops = unsafe { (*fence.raw()).ops as usize }; + let previous = JOB_FENCE_OPS.load(Ordering::Acquire); + if previous == 0 { + match JOB_FENCE_OPS.compare_exchange(0, ops, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => {} + Err(existing) if existing == ops => {} + Err(_) => return Err(EIO), + } + } else if previous != ops { + return Err(EIO); + } let mut pending = self.pending.lock(); pending.reserve(1, GFP_NOWAIT)?; pending @@ -141,32 +448,60 @@ impl Timeline { }) } - /// Records the result of `fence` and signals every completed fence at the head, in order. + /// Records the result of `fence` and signals every completed fence at the head, in order, + /// without holding `pending` across `dma_fence_signal` callbacks. fn complete(&self, fence: &UserFence, result: Result) { - let mut pending = self.pending.lock(); - let Some(entry) = pending - .iter_mut() - .find(|entry| entry.fence.raw() == fence.raw()) - else { - // Already signalled. - return; + let head_ready = { + let mut pending = self.pending.lock(); + let Some(entry) = pending + .iter_mut() + .find(|entry| entry.fence.raw() == fence.raw()) + else { + // Already signalled. + return; + }; + if entry.result.is_some() { + return; + } + entry.result = Some(result); + pending.first().is_some_and(|entry| entry.result.is_some()) }; - if entry.result.is_some() { + if !head_ready { return; } - entry.result = Some(result); - let mut signalled = 0; - for entry in pending.iter() { - let Some(result) = entry.result else { - break; + let _signaller = self.signaller.lock(); + loop { + let mut batch: [Option<(UserFence, Result)>; SIGNAL_BATCH] = + [const { None }; SIGNAL_BATCH]; + let (count, more) = { + let mut pending = self.pending.lock(); + let ready = pending + .iter() + .take(SIGNAL_BATCH) + .take_while(|entry| entry.result.is_some()) + .count(); + let mut idx = 0; + for entry in pending.drain(..ready) { + if let Some(res) = entry.result { + batch[idx] = Some((entry.fence, res)); + idx += 1; + } + } + let more = pending.first().is_some_and(|entry| entry.result.is_some()); + (idx, more) }; - if let Err(error) = result { - entry.fence.set_error(error); + for item in &mut batch[..count] { + if let Some((fence, res)) = item.take() { + if let Err(error) = res { + fence.set_error(error); + } + signal_fence(&fence); + } + } + if !more { + break; } - entry.fence.signal(); - signalled += 1; } - drop(pending.drain(..signalled)); } /// A signalled fence carrying `error`, for the output syncs of a refused submission. @@ -178,7 +513,7 @@ impl Timeline { /// A fence on `contexts` signalled with `error`. Every fence of an error context signals at /// creation, so the context's fences signal in order. fn error_fence(contexts: &FenceContexts, error: Error) -> Result { - let fence = contexts.new_fence(0, JobFenceOps)?; + let fence = contexts.new_fence(0, RefusedFenceOps)?; fence.set_error(error); fence.signal(); Ok(Fence::from_fence(&fence)) @@ -224,15 +559,22 @@ fn install(outputs: impl Iterator, fence: &Fence) { /// The syncs of one SUBMIT. Every output sync gets a fence: the job's fence once the job is /// accepted, a signalled error fence when the submission is refused (the shared `file.rs` -/// contract of `tracked_submission`). +/// contract of `tracked_submission`). Cumulative output bundles reuse the shared +/// `g17::sync_output::SignalBundle` scope chain. pub(crate) struct Syncs { - syncs: KVec, + syncs: KVVec, input_count: usize, + cumulative: Option, } impl Syncs { - pub(crate) fn new(syncs: KVec, input_count: usize) -> Self { - Self { syncs, input_count } + pub(crate) fn new(mut syncs: KVVec, input_count: usize) -> Self { + let cumulative = syncs.iter_mut().find_map(|sync| sync.cumulative.take()); + Self { + syncs, + input_count, + cumulative, + } } /// The input syncs (all resolved to fences or already signalled). @@ -240,14 +582,28 @@ impl Syncs { &self.syncs[..self.input_count.min(self.syncs.len())] } - /// Publishes the accepted job's fence in every output sync. - pub(crate) fn accept(mut self, fence: &Fence) { + /// Publishes the job's fence in every output sync before enqueuing the job. If publishing a + /// cumulative bundle fails (`ENOMEM`), the bundle remains unpublished so [`Self::refuse`] + /// installs a signalled error fence in every target. + pub(crate) fn publish(&mut self, fence: &Fence) -> Result { let first = self.input_count.min(self.syncs.len()); + if let Some(bundle) = &mut self.cumulative { + // G16 has its own power/DVFS path; never poke G17's non-M5 compute-waiter hook. + bundle.publish(fence, false)?; + self.cumulative = None; + self.syncs.truncate(first); + return Ok(()); + } install(self.syncs.drain(first..), fence); + Ok(()) } /// Publishes a signalled error fence in every output sync of a refused submission. pub(crate) fn refuse(mut self, timeline: &Timeline, error: Error) { + if let Some(mut bundle) = self.cumulative.take() { + bundle.fail(&timeline.refused(error)); + return; + } let first = self.input_count.min(self.syncs.len()); if first < self.syncs.len() { install(self.syncs.drain(first..), &timeline.refused(error)); diff --git a/drivers/gpu/drm/asahi/g16/fw/buffer.rs b/drivers/gpu/drm/asahi/g16/fw/buffer.rs index 813e52d886fdcb..f272c9a21c5d52 100644 --- a/drivers/gpu/drm/asahi/g16/fw/buffer.rs +++ b/drivers/gpu/drm/asahi/g16/fw/buffer.rs @@ -46,11 +46,73 @@ pub(crate) mod pb_manager { pub(crate) const COUNTER: usize = 0x64; pub(crate) const MAX_PAGES_A: usize = 0x7c; pub(crate) const MAX_PAGES_B: usize = 0x80; + + /// PB manager field offsets that differ between G16G (`0xc0`) and G15S 26B123 (`0x90`, + /// shifted `-4` bytes from `ID_A` onward). + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct Layout { + /// Primary parameter-buffer slot ID offset (`parameter_id` / PBID). + pub(crate) id_a: usize, + /// Secondary slot ID offset, when the record carries a second copy. + pub(crate) id_b: Option, + pub(crate) page_list_fw: usize, + pub(crate) page_list: usize, + pub(crate) page_list_bytes: usize, + pub(crate) pages: usize, + pub(crate) k: usize, + pub(crate) blocks: usize, + pub(crate) block_list: usize, + pub(crate) block_ctl: usize, + pub(crate) last_page: usize, + pub(crate) block_bytes: usize, + pub(crate) counter: usize, + pub(crate) max_pages_a: usize, + pub(crate) max_pages_b: usize, + } + + pub(crate) const V25G83: Layout = Layout { + id_a: ID_A, + id_b: Some(ID_B), + page_list_fw: PAGE_LIST_FW, + page_list: PAGE_LIST, + page_list_bytes: PAGE_LIST_BYTES, + pages: PAGES, + k: K, + blocks: BLOCKS, + block_list: BLOCK_LIST, + block_ctl: BLOCK_CTL, + last_page: LAST_PAGE, + block_bytes: BLOCK_BYTES, + counter: COUNTER, + max_pages_a: MAX_PAGES_A, + max_pages_b: MAX_PAGES_B, + }; + + /// G15S 26B123 uses one slot ID. The adjacent bank selector stays zero. + pub(crate) const V26B123_G15S: Layout = Layout { + id_a: 0x08, + id_b: None, + page_list_fw: 0x1c, + page_list: 0x24, + page_list_bytes: 0x2c, + pages: 0x30, + k: 0x34, + blocks: 0x38, + block_list: 0x40, + block_ctl: 0x48, + last_page: 0x50, + block_bytes: 0x54, + counter: 0x60, + max_pages_a: 0x78, + max_pages_b: 0x7c, + }; } pub(crate) mod uma_manager { pub(crate) const SIZE: usize = 0xa0; pub(crate) const COMPLETED: usize = 0x54; pub(crate) const SEEDS: u32 = 8192; + /// Freelist records of a base pool (+0x1c), its 0x20000-byte freelist. + pub(crate) const RECORDS: u32 = 16384; } pub(crate) mod uma_pools { pub(crate) const POOLS: usize = 16; @@ -82,7 +144,8 @@ fn put64(x: &mut [u8], off: usize, v: u64) { x[off..off + 8].copy_from_slice(&v.to_le_bytes()); } -/// Literal fresh M4 PB manager. The firmware and GPU page-list aliases share backing. +/// Literal fresh M4 PB manager sized to `heap_blocks` (1..=[`MAX_BLOCKS`]). +/// The firmware and GPU page-list aliases share backing. #[allow(clippy::too_many_arguments)] pub(crate) fn pb_manager_image( id: u32, @@ -91,45 +154,82 @@ pub(crate) fn pb_manager_image( blocks_fw: u64, ring_fw: u64, count_fw: u64, + heap_blocks: u32, +) -> [u8; pb_manager::SIZE] { + pb_manager_image_for( + &pb_manager::V25G83, + id, + pages_fw, + pages_gpu, + blocks_fw, + ring_fw, + count_fw, + heap_blocks, + ) +} + +/// Fresh PB manager encoded for `layout`'s firmware ABI, zero-padded to [`pb_manager::SIZE`]. +#[allow(clippy::too_many_arguments)] +pub(crate) fn pb_manager_image_for( + layout: &pb_manager::Layout, + id: u32, + pages_fw: u64, + pages_gpu: u64, + blocks_fw: u64, + ring_fw: u64, + count_fw: u64, + heap_blocks: u32, ) -> [u8; pb_manager::SIZE] { + let blocks = heap_blocks.clamp(1, MAX_BLOCKS); + let pages = blocks * PAGES_PER_BLOCK; let mut m = [0; pb_manager::SIZE]; - put32(&mut m, 0xc, id); - put32(&mut m, 0x10, id); - put64(&mut m, 0x20, pages_fw); - put64(&mut m, 0x28, pages_gpu); - put32(&mut m, 0x30, PAGE_LIST_SIZE as u32); - put32(&mut m, 0x34, MAX_PAGES); - put32(&mut m, 0x38, BLOCK_LIST_RECORDS); - put32(&mut m, 0x3c, MAX_BLOCKS); - put64(&mut m, 0x44, blocks_fw); - put64(&mut m, 0x4c, ring_fw); - put32(&mut m, 0x54, MAX_PAGES - 1); - put32(&mut m, 0x58, BLOCK_BYTES as u32); - put64(&mut m, 0x64, count_fw); - put32(&mut m, 0x7c, MAX_PAGES); - put32(&mut m, 0x80, MAX_PAGES); + put32(&mut m, layout.id_a, id); + if let Some(id_b) = layout.id_b { + put32(&mut m, id_b, id); + } + put64(&mut m, layout.page_list_fw, pages_fw); + put64(&mut m, layout.page_list, pages_gpu); + put32(&mut m, layout.page_list_bytes, PAGE_LIST_SIZE as u32); + put32(&mut m, layout.pages, pages); + put32(&mut m, layout.k, BLOCK_LIST_RECORDS); + put32(&mut m, layout.blocks, blocks); + put64(&mut m, layout.block_list, blocks_fw); + put64(&mut m, layout.block_ctl, ring_fw); + put32(&mut m, layout.last_page, pages - 1); + put32(&mut m, layout.block_bytes, BLOCK_BYTES as u32); + put64(&mut m, layout.counter, count_fw); + put32(&mut m, layout.max_pages_a, pages); + put32(&mut m, layout.max_pages_b, pages); m } /// One retained M4 UMA descriptor shared by TA and FS (slot 33..64). +/// A UMA manager whose freelist of `records` records (+0x1c) holds `seeds` entries (available +/// and total): [`uma_manager::SEEDS`] in [`uma_manager::RECORDS`] for a base pool. pub(crate) fn uma_manager_image( descriptor: u64, slot: u32, state_gpu: u64, list_gpu: u64, submitted_fw: u64, + seeds: u32, + records: u32, ) -> [u8; uma_manager::SIZE] { let mut m = [0; uma_manager::SIZE]; put64(&mut m, 0, descriptor); put32(&mut m, 8, slot); put32(&mut m, 0x10, 2); put64(&mut m, 0x14, state_gpu); - put32(&mut m, 0x1c, 16384); - put32(&mut m, 0x24, 8192); - put32(&mut m, 0x2c, 8192); + put32(&mut m, 0x1c, records); + put32(&mut m, 0x24, seeds); + put32(&mut m, 0x2c, seeds); put64(&mut m, 0x30, list_gpu); put32(&mut m, 0x40, 4); - put32(&mut m, 0x48, 128); + put32( + &mut m, + super::graph::manager::ROW_WORDS, + super::graph::pools::row_words(seeds), + ); put64(&mut m, 0x4c, submitted_fw); // +0x54 is the ASC completion count; +0x5c is the compute-exclusion flag. // Both start at zero for paired render engines and are never AP command serials. @@ -138,6 +238,24 @@ pub(crate) fn uma_manager_image( m } +/// One retained M4 compute UMA descriptor (`COMPUTE_UMA_SLOT + hw_slot`), identical to +/// [`uma_manager_image`] with `COMPUTE_EXCLUSION = 1` and `work_fw` at offset 0. +pub(crate) fn compute_uma_manager_image( + work_fw: u64, + slot: u32, + state_gpu: u64, + list_gpu: u64, + counter_fw: u64, + seeds: u32, + records: u32, +) -> [u8; uma_manager::SIZE] { + let mut m = uma_manager_image( + work_fw, slot, state_gpu, list_gpu, counter_fw, seeds, records, + ); + put32(&mut m, super::graph::manager::COMPUTE_EXCLUSION, 1); + m +} + #[cfg(test)] mod tests { use super::*; @@ -156,6 +274,7 @@ mod tests { 0xfffffc2000500000, 0xfffffc2000600000, 0xfffffc2000700000, + MAX_BLOCKS, ); assert_eq!(m.len(), 0xc0); assert_eq!((r32(&m, 0xc), r32(&m, 0x10)), (1, 1)); @@ -169,6 +288,26 @@ mod tests { assert_eq!(r32(&m, 0x54), 8191); assert_eq!(r32(&m, 0x7c), 8192); assert_eq!(r32(&m, 0x80), 8192); + // A 64 MiB heap (512 blocks / 2048 pages) describes only its backed blocks and pages. + let small = pb_manager_image( + 0, + 0xfffffc2000400000, + 0x701a040000, + 0xfffffc2000500000, + 0xfffffc2000600000, + 0xfffffc2000700000, + 512, + ); + assert_eq!( + ( + r32(&small, 0x34), + r32(&small, 0x3c), + r32(&small, 0x54), + r32(&small, 0x7c), + r32(&small, 0x80), + ), + (2048, 512, 2047, 2048, 2048) + ); let written = [ (0xc, 8), (0x20, 16), @@ -192,6 +331,12 @@ mod tests { 0x7012000000, 0x7012020000, 0xfffffc2000700000, + uma_manager::SEEDS, + uma_manager::RECORDS, + ); + assert_eq!( + (r32(&m, 0x1c), r32(&m, 0x24), r32(&m, 0x2c)), + (16384, 8192, 8192) ); assert_eq!(r64(&m, 0), 0xfffffc2000400000); assert_eq!(r32(&m, 8), 33); diff --git a/drivers/gpu/drm/asahi/g16/fw/channels.rs b/drivers/gpu/drm/asahi/g16/fw/channels.rs index 9b5ae1e7c4b08c..395b82134bcdb6 100644 --- a/drivers/gpu/drm/asahi/g16/fw/channels.rs +++ b/drivers/gpu/drm/asahi/g16/fw/channels.rs @@ -46,7 +46,10 @@ impl SubmitRecord { } } -/// Device-control opcodes of the qualified 25G83 M4 firmware. +/// Device-control opcodes of each supported M4 firmware ABI. +/// +/// The host advances its generation word alongside the device-control producer for each posted +/// record. pub(crate) mod devctl { /// Re-import Globals. pub(crate) const IMPORT_GLOBALS: u32 = 0x34; @@ -56,6 +59,31 @@ pub(crate) mod devctl { pub(crate) const NOP: u32 = 0x1a; /// PB growth reply. pub(crate) const GROW_REPLY: u32 = 7; + + /// The opcodes the host sends, in one firmware ABI. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct Opcodes { + pub(crate) import_globals: u32, + pub(crate) start: u32, + pub(crate) nop: u32, + pub(crate) grow_reply: u32, + } + + pub(crate) const V25G83: Opcodes = Opcodes { + import_globals: IMPORT_GLOBALS, + start: START, + nop: NOP, + grow_reply: GROW_REPLY, + }; + + /// 26B123 device-control opcodes (re-import Globals 0x35, start 0x0a, no-op 0x19, + /// PB growth reply 7). + pub(crate) const V26B123: Opcodes = Opcodes { + import_globals: 0x35, + start: 0x0a, + nop: 0x19, + grow_reply: 7, + }; } /// A device-control record (0x40 bytes, opcode first). diff --git a/drivers/gpu/drm/asahi/g16/fw/graph.rs b/drivers/gpu/drm/asahi/g16/fw/graph.rs index 344dd3da370615..44e49e4e06fed1 100644 --- a/drivers/gpu/drm/asahi/g16/fw/graph.rs +++ b/drivers/gpu/drm/asahi/g16/fw/graph.rs @@ -21,6 +21,60 @@ pub(crate) mod qinfo { /// u64 scheduling context VA, then u64 4. pub(crate) const SCHED_CTX: usize = 0xa4; pub(crate) const UNK_AC: usize = 0xac; + + /// The queue-info words that move between firmware ABIs. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct Layout { + /// Bytes of the firmware-owned header (what it invalidates on a new queue); the queue + /// scratch follows it in the same object. + pub(crate) header: usize, + /// u32 2, read as a byte by the firmware (row 2's `UNK_48`). + pub(crate) class_c: usize, + /// u32 `u32::MAX`. + pub(crate) unk_4c: usize, + pub(crate) uuid: usize, + /// u64 scheduling context VA. + pub(crate) sched_ctx: usize, + /// Firmware u32 busy flag: 1 from when the firmware takes a record until DONE (+0x20) + /// reaches the head (+0x28). + pub(crate) busy: usize, + /// Optional trailing `(offset, value)` u64 word in the firmware header. + pub(crate) tail_word: Option<(usize, u64)>, + } + + pub(crate) const V25G83: Layout = Layout { + header: 0xb0, + class_c: super::qinfo_row2::UNK_48, + unk_4c: UNK_4C, + uuid: UUID, + sched_ctx: SCHED_CTX, + busy: 0x80, + tail_word: None, + }; + + /// 26B123 queue-info header (0x80 bytes): class_c at 0x44, unk_4c at 0x48, uuid at 0x4c, + /// busy at 0x54, scheduling context aligned at 0x78, and queue scratch starting at 0x80. + pub(crate) const V26B123: Layout = Layout { + header: 0x80, + class_c: 0x44, + unk_4c: 0x48, + uuid: 0x4c, + sched_ctx: 0x78, + busy: 0x54, + tail_word: None, + }; + + /// G15S 26B123 queue-info header (0x88 bytes invalidated by the firmware): trailing u64 `4` + /// at `+0x80`, with queue scratch starting right after it at `+0x88`. + pub(crate) const V26B123_G15S: Layout = Layout { + header: 0x88, + class_c: 0x44, + unk_4c: 0x48, + uuid: 0x4c, + sched_ctx: 0x78, + busy: 0x54, + tail_word: Some((0x80, 4)), + }; } /// Queue-info scheduling rows (the firmware's recognized policy rows). @@ -100,6 +154,10 @@ pub(crate) mod manager { pub(crate) const COMPLETED: usize = 0x54; /// ASC compute-exclusion bookkeeping. AP initializes once; never a command serial. pub(crate) const COMPUTE_EXCLUSION: usize = 0x5c; + /// Eight per valid pool-table row ([`super::pools::row_words`]): macOS 27.2 on the J773g + /// writes 8 x rows on every pool (20, 24 and 108 rows seen) and counts a pool's growth + /// in the same unit. A 16-row base pool has 128. + pub(crate) const ROW_WORDS: usize = 0x48; } /// A private 32 MiB UMA pool: 8192 4 KiB freelist entries and sixteen 2 MiB rows. @@ -113,25 +171,45 @@ pub(crate) mod pools { pub(crate) const STATE_BYTES: usize = 0x20000; pub(crate) const TABLE_BYTES: usize = 0x4000; pub(crate) const SEEDS: usize = 8192; + /// [`super::manager::ROW_WORDS`] of a pool of `seeds` entries in whole rows: the u64 words + /// of its valid pool-table rows, eight per 0x40-byte row. + pub(crate) const fn row_words(seeds: u32) -> u32 { + let rows = seeds as u64 * SEED_BYTES / ROW_BYTES; + (rows * (TABLE_STRIDE / core::mem::size_of::()) as u64) as u32 + } + const _: () = assert!(row_words(SEEDS as u32) == 128); } -/// The nonzero queue header; the rest of the fresh 0x24c0 object remains zero. Keeping the -/// scratch inside this object is part of the M4 ABI, not a separate buffer allocation. +/// The nonzero 25G83 queue header; the rest of the fresh 0x24c0 object remains zero. Keeping +/// the scratch inside this object is part of the M4 ABI, not a separate buffer allocation. pub(crate) fn queue_image( state: u64, ring: u64, list: u64, queue: u64, context: u64, +) -> [u8; 0xb4] { + queue_image_for(&qinfo::V25G83, state, ring, list, queue, context) +} + +/// The nonzero queue header of `layout`'s ABI, zero-padded to 0xb4 bytes; the scratch starts +/// right after the firmware-owned header. The same 0x24c0 object holds either. +pub(crate) fn queue_image_for( + layout: &qinfo::Layout, + state: u64, + ring: u64, + list: u64, + queue: u64, + context: u64, ) -> [u8; 0xb4] { let mut q = [0; 0xb4]; for (at, value) in [ (0, state), (8, ring), (0x10, list), - (0x18, queue + 0xb0), + (0x18, queue + layout.header as u64), (0x38, qinfo_row2::MASK_VALUE), - (0xa4, context), + (layout.sched_ctx, context), ] { q[at..at + 8].copy_from_slice(&value.to_le_bytes()); } @@ -139,11 +217,14 @@ pub(crate) fn queue_image( (0x2c, u32::MAX), (0x30, 2u32), (0x34, 2), - (0x48, 2), - (0x4c, u32::MAX), + (layout.class_c, 2), + (layout.unk_4c, u32::MAX), ] { q[at..at + 4].copy_from_slice(&value.to_le_bytes()); } + if let Some((at, value)) = layout.tail_word { + q[at..at + 8].copy_from_slice(&value.to_le_bytes()); + } q } diff --git a/drivers/gpu/drm/asahi/g16/fw/initdata.rs b/drivers/gpu/drm/asahi/g16/fw/initdata.rs index 9acbb4ac763a5a..ab15e9d40e53bd 100644 --- a/drivers/gpu/drm/asahi/g16/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/fw/initdata.rs @@ -1,11 +1,13 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! J713/T8132 initdata for the qualified 25G83 firmware. +//! InitData for the qualified 25G83 and 26B123 classic GPU firmware. //! -//! This is a byte encoder for private, unpublished objects. Admission, mapping, -//! cache maintenance and publication belong to the owner. It has no kernel or -//! allocator dependency so a host harness can compare every byte with the C -//! bring-up encoder. +//! The encoder is written in 25G83 offsets; a [`Layout`] maps them to another firmware ABI +//! (26B123 inserts and removes words in several objects, renumbers the register map and +//! moves the FirmwareData words). This is a byte encoder for private, unpublished objects. +//! Admission, mapping, cache maintenance and publication belong to the owner. It has no kernel +//! or allocator dependency so a host harness can compare every byte with the C bring-up +//! encoder. pub(crate) const PAGE: u64 = 0x4000; pub(crate) const PA_MASK: u64 = 0x3ffffffc000; @@ -16,7 +18,6 @@ pub(crate) const BOOTSTRAP_SIZE: u64 = 0x2000000; pub(crate) const OBJECT_COUNT: usize = 31; pub(crate) const LOADER_COUNT: usize = 42; pub(crate) const LOADER_STRIDE: usize = 0x28; -pub(crate) const LOADER_BYTES: usize = LOADER_COUNT * LOADER_STRIDE; /// Stable positions in the firmware's object inventory. pub(crate) mod id { @@ -61,30 +62,828 @@ pub(crate) const OBJECT_SIZE: [usize; OBJECT_COUNT] = [ pub(crate) mod root { pub(crate) const SIZE: usize = super::OBJECT_SIZE[super::id::ROOT]; - pub(crate) const MAGIC: u64 = 0x0c89c357839204b8; } /// The small root.Control object is the READY acknowledgement. pub(crate) mod ready_control { pub(crate) const READY: usize = 0x14; } -/// Runtime is a distinct pointer graph, not the READY object. -pub(crate) mod runtime { - pub(crate) const SIZE: usize = super::OBJECT_SIZE[super::id::RUNTIME]; + +/// One run of a piecewise offset map: the 25G83 offsets `start..end` of an object are at +/// `+ delta` in another firmware ABI. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Run { + pub(crate) start: usize, + pub(crate) end: usize, + pub(crate) delta: usize, +} + +const fn run(start: usize, end: usize, delta: usize) -> Run { + Run { start, end, delta } +} + +/// Const counterpart of [`remap`] for compile-time layout validation. +const fn remap_const(runs: &[Run], at: usize, len: usize) -> Option { + let Some(end) = at.checked_add(len) else { + return None; + }; + let mut i = 0; + while i < runs.len() { + if runs[i].start <= at && end <= runs[i].end { + return at.checked_add(runs[i].delta); + } + i += 1; + } + None +} + +/// Where the `len`-byte field at 25G83 offset `at` lives under `runs`. A field outside every +/// run (an offset whose new position is not known, or the register map) is refused. +pub(crate) fn remap(runs: &[Run], at: usize, len: usize) -> Result { + remap_const(runs, at, len).ok_or(()) +} + +/// The FirmwareData (status B) words the host reads and writes. +#[derive(Clone, Copy, Debug)] +pub(crate) struct FirmwareData { + /// u64 VAs of the FWCTL state and, 8 bytes later, its ring (state + 0x40). + pub(crate) fwctl: usize, + /// u64 recovery generation. + pub(crate) generation: usize, + /// u32 recovery phase. + pub(crate) phase: usize, + /// u32 scheduler import word. + pub(crate) scheduler: usize, + /// The affected-work snapshot: `snapshot_entries` `{flags u32, target u32}` pairs. + pub(crate) snapshot: usize, + pub(crate) snapshot_entries: usize, +} + +/// Pointer geometry of the twelve TX channels and device-control channel. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum TxLayout { + /// Three state pointers spaced by 0x10 and a separate record buffer. + StateBlock, + /// Read and completion pointers spaced by eight. For the TX channels the + /// producer is the eight-byte header before the records. + RingHeader, +} + +impl TxLayout { + pub(crate) const fn completion(self) -> usize { + match self { + Self::StateBlock => 0x10, + Self::RingHeader => 8, + } + } + + pub(crate) const fn ring_header(self, control: bool) -> usize { + match self { + Self::RingHeader if !control => 8, + _ => 0, + } + } +} + +/// The InitData ABI of one firmware build: what differs from the 25G83 objects the encoder +/// writes. Offsets of every run are 25G83 offsets. +pub(crate) struct Layout { + pub(crate) name: &'static str, + /// Root +0: the interface version the firmware compares with its own. + pub(crate) version: u64, + pub(crate) object_size: [usize; OBJECT_COUNT], + /// RUNTIME (main config) offset of the unaligned power-config (POWER_PERFORMANCE) pointer. + pub(crate) power_config: usize, + pub(crate) tx: TxLayout, + /// Register-map slot in MAIN of each logical (25G83-numbered) loader record; `None` for a + /// record that is empty, and the number of slots of the map at MAIN + 0x640. + pub(crate) loader_slot: [Option; LOADER_COUNT], + pub(crate) register_slots: usize, + pub(crate) loaders: &'static [Loader; LOADER_COUNT], + /// Slots with an empty address and length but a default write-enabled mode. + pub(crate) empty_loader_modes: u64, + /// Physical core slots in MAIN where the firmware expects the topology count. + pub(crate) main_core_slots: Option, + /// MAIN (HW data) after the register map, GLOBALS (region C) and POWER_PERFORMANCE (power + /// config). Only runs whose new position is known are listed. + pub(crate) main: &'static [Run], + pub(crate) globals: &'static [Run], + pub(crate) power_performance: &'static [Run], + pub(crate) firmware_data: FirmwareData, + /// GLOBALS p-state selectors the host publishes at runtime (hundredths of a state). + pub(crate) pstate_selectors: [usize; 3], + /// MAIN offset of the u64 size of the host's crash copy buffer, where the build has one. + pub(crate) coredump_copy: Option, + /// Where the RETENTION object is published. + pub(crate) retention: Retention, + /// MAIN (HW data) words of this build that have no 25G83 position, at their own offsets. + pub(crate) main_policy: &'static [(usize, u32)], + /// GLOBALS (region C) words of this build that have no 25G83 position, at their own offsets. + pub(crate) globals_policy: &'static [(usize, u32)], + /// POWER_PERFORMANCE (power config) words of this build that have no 25G83 position, at + /// their own offsets. + pub(crate) power_policy: &'static [(usize, u32)], + /// POWER_PERFORMANCE words derived from the GPU power sample period and average-power + /// filter time constant, where the build has them. + pub(crate) power_sampling: Option, + /// POWER_PERFORMANCE words of the low-peak (PPM) power limiter derived from the machine's + /// ADT (`clpc` low-peak limiter properties and `sgx` sample period), where the build has + /// them. + pub(crate) power_limiter: Option, + /// POWER_PERFORMANCE u32 that must lie above every performance-state index, where the build + /// has one: the number of performance rows is written there. + pub(crate) state_bound: Option, +} + +/// POWER_PERFORMANCE offsets of the words derived from the GPU power sample period and +/// average-power filter time constant. +#[derive(Clone, Copy, Debug)] +pub(crate) struct PowerSampling { + /// The exact sample period in us (from `gpu-pwr-sample-period-aic-clks`), as u32. + pub(crate) period: &'static [usize], + /// The exact sample period in us, as f32. + pub(crate) period_f32: usize, + /// The average-power filter of `n` samples over the ADT's `cpu-avg-limiter-input-tc` + /// (`(tc_ms * 1000) / period_us`): u32 `n * 4`, f32 `(n - 1) / n` and f32 `1 / n`. + pub(crate) filter: [usize; 3], +} + +/// POWER_PERFORMANCE offsets of the low-peak (PPM) power limiter words derived from the +/// machine's ADT (`clpc` `cpu-lowpeak-limiter-*` and `sgx` `gpu-power-sample-period`). +#[derive(Clone, Copy, Debug)] +pub(crate) struct PowerLimiter { + /// Filter time constant in coarse sample periods, scaled by 4 (`periods * 4`). + pub(crate) filter_periods_x4: usize, + /// IIR filter pole `(periods - 1) / periods`, as f32. + pub(crate) filter_a_neg: usize, + /// IIR filter weight `1 / periods`, as f32. + pub(crate) filter_a: usize, + /// Integral gain scaled by the coarse sample period (`ki * period_s`), as f32. + pub(crate) ki_dt: usize, + /// PI integrator upper bound (`65536.0`, the fixed-point scale shared across M1-M5), as f32. + pub(crate) clamp: usize, + /// Proportional gain (`kp`), as f32. + pub(crate) kp: usize, + /// Filter time constant in ms (`cpu-lowpeak-limiter-input-tc`). + pub(crate) filter_tc_ms: usize, + /// Rounded filter time constant in system-counter ticks (`periods * period_ms * khz`). + pub(crate) filter_tc_clks: usize, +} + +/// IEEE-754 single-precision bits of `num / den` for `num` and `den` non-zero, rounded to +/// nearest, ties to even. The encoder runs where the kernel has no floating point. With 32-bit +/// inputs every step fits in 64 bits. +pub(crate) const fn f32_bits(num: u32, den: u32) -> u32 { + // +0.0: a zero numerator never normalizes (`n < d` would loop forever). + if num == 0 { + return 0; + } + let (mut n, mut d) = (num as u64, den as u64); + let mut exponent: i32 = 0; + while n >= 2 * d { + d *= 2; + exponent += 1; + } + while n < d { + n *= 2; + exponent -= 1; + } + let scaled = n << 23; + let (mut mantissa, rest) = (scaled / d, scaled % d); + if 2 * rest > d || (2 * rest == d && mantissa & 1 == 1) { + mantissa += 1; + } + if mantissa == 1 << 24 { + mantissa >>= 1; + exponent += 1; + } + (((exponent + 127) as u32) << 23) | (mantissa as u32 & 0x7f_ffff) +} +const _: () = assert!(f32_bits(28, 29) == 0x3f77_2c23 && f32_bits(1, 29) == 0x3d0d_3dcb); +const _: () = assert!(f32_bits(8333, 1) == 0x4602_3400 && f32_bits(65536, 1) == 0x4780_0000); +const _: () = assert!(f32_bits(0, 1) == 0 && f32_bits(1, 1) == 0x3f80_0000); + +/// Where the RETENTION object (0x4000 zeroed bytes) is published. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Retention { + /// MAIN's retention pointer (25G83 0xe88). + Main, + /// MAIN's retention pointer stays 0 so the firmware keeps that state in its own RAM, and + /// the zeroed object is instead the RUNTIME table this u64 pointer names. + Runtime(usize), +} + +impl Layout { + /// The register-map slot of logical loader record `slot`. + pub(crate) fn slot(&self, slot: usize) -> Option { + self.loader_slot + .get(slot) + .copied() + .flatten() + .map(usize::from) + } + + /// Register-map records from slot 0 through the highest slot the encoder fills. + pub(crate) fn loader_records(&self) -> usize { + (0..LOADER_COUNT) + .filter(|&slot| self.loaders[slot].length != 0) + .filter_map(|slot| self.slot(slot)) + .max() + .map_or(0, |slot| slot + 1) + } +} + +const fn identity_slots() -> [Option; LOADER_COUNT] { + let mut out = [None; LOADER_COUNT]; + let mut slot = 0; + while slot < LOADER_COUNT { + out[slot] = Some(slot as u8); + slot += 1; + } + out +} + +/// 26B123 renumbers the register map (53 -> 60 slots): 0-7, 9-20 and 22-24 keep their numbers, +/// 26-43 move up by five (seven region types were added). Slots 8, 21 and 25 are empty here. +const fn slots_26b123() -> [Option; LOADER_COUNT] { + let mut out = [None; LOADER_COUNT]; + let mut slot = 0; + while slot < LOADER_COUNT { + out[slot] = match slot { + 0..=7 | 9..=20 | 22..=24 => Some(slot as u8), + // Logical 36 (the protected power-transition block at PA 0x300e00000) stays empty + // on 26B123: the firmware maps that block itself and fills its own VA during + // InitData. + 36 => None, + 26..=43 => Some(slot as u8 + 5), + _ => None, + }; + slot += 1; + } + out +} + +/// The 25G83 InitData ABI. +pub(crate) const V25G83: Layout = Layout { + name: "25G83", + version: 0x0c89c357839204b8, + object_size: OBJECT_SIZE, + power_config: 0x469, + tx: TxLayout::StateBlock, + loader_slot: identity_slots(), + register_slots: 53, + loaders: &LOADERS, + empty_loader_modes: 0, + main_core_slots: None, + main: &[run(0, 0x640, 0), run(0xe88, 0x2658, 0)], + globals: &[run(0, 0xe48, 0)], + power_performance: &[run(0, 0x6578, 0)], + firmware_data: FirmwareData { + fwctl: 0x4f88, + generation: 0x4fa0, + phase: 0x4fb0, + scheduler: 0x4fd4, + snapshot: 0x40b8, + snapshot_entries: 448, + }, + pstate_selectors: [0x88, 0x8c, 0x98], + coredump_copy: None, + retention: Retention::Main, + main_policy: &[], + globals_policy: &[], + power_policy: &[], + power_sampling: None, + power_limiter: None, + state_bound: None, +}; + +/// The 26B123 InitData ABI: the same 31 objects and pointers, with +/// - the main-config power-config pointer 16 bytes later; +/// - a 60-slot register map in MAIN, then the retention pointer at 0xfa0, a new u64 at 0xfa8 +/// (the crash copy buffer size), the old 0xe90.. words +0x120, 0xec0.. +0x11c (one word +/// removed at 0xebc), 0x2600.. +0x120 and the last bytes +0x124 (new u32s at 0x275c, left +/// zero, and 0x277e, enabled via `main_policy`); +/// - a u32 inserted at GLOBALS 0x38, so every later word moves by four; +/// - POWER_PERFORMANCE with words inserted at 0x9c (0x10 bytes), 0x28b0 (0x18), 0x3b50 (0x28) +/// and 0x63cc (0x680), 8 bytes removed between 0x2d08 and 0x2f08 and 0x20 between 0x62c4 and +/// 0x6318; +/// - FirmwareData words 0x1e0 bytes later (a table was inserted before them); +/// - POWER (left all zero) grown to 0x698 bytes. +pub(crate) const V26B123: Layout = Layout { + name: "26B123", + version: 0x0c8a836f039204b8, + object_size: [ + 0xc8, 0x4000, 0x4b8, 0xe4c, 0x20, 0xedd0, 0x698, 0x4000, 0x2788, 0x6c48, 0x88, 0xc18, + 0x1248, 0xe10, 0x60, 0x1b0, 0x28800, 0x79800, 0x4000, 0x30, 0x4000, 0x30, 0x9000, 0x30, + 0x4800, 0x4, 0x30, 0x4800, 0x4000, 0x4000, 0x4000, + ], + power_config: 0x479, + tx: TxLayout::StateBlock, + loader_slot: slots_26b123(), + register_slots: 60, + loaders: &LOADERS, + empty_loader_modes: 0, + main_core_slots: None, + main: &[ + run(0, 0x640, 0), + run(0xe88, 0xe90, 0x118), + run(0xe90, 0xebc, 0x120), + run(0xec0, 0x25b4, 0x11c), + run(0x2600, 0x263c, 0x120), + run(0x263c, 0x2658, 0x124), + ], + globals: &[run(0, 0x38, 0), run(0x38, 0xe48, 4)], + power_performance: &[ + run(0, 0x9c, 0), + run(0x9c, 0x28b0, 0x10), + run(0x28b0, 0x2d08, 0x28), + run(0x2f08, 0x3b50, 0x20), + run(0x3b50, 0x62c4, 0x48), + run(0x6318, 0x63cc, 0x28), + run(0x63cc, 0x6578, 0x6a8), + ], + firmware_data: FirmwareData { + fwctl: 0x5168, + generation: 0x5180, + phase: 0x5190, + scheduler: 0x51b4, + snapshot: 0x4298, + snapshot_entries: 448, + }, + pstate_selectors: [0x8c, 0x90, 0x9c], + // HW data +0xfa8 holds the crash copy buffer's size, +0xfa0 stays 0, and the RETENTION + // object is published at RUNTIME +0x2c8. Publishing RETENTION at +0xfa0 with the size at + // +0xfa8 faulted on the first resume from idle power-off. + coredump_copy: Some(0xfa8), + retention: Retention::Runtime(0x2c8), + // macOS 27.2 writes 1 here; with 0 the firmware falsely flags long compute dispatches as + // stalled. + main_policy: &[(0x277e, 1)], + globals_policy: &[], + // The four u32s this build inserts at +0x9c, 1 each as macOS 27.2 writes them. 0xa4 selects + // the powered-up state; leaving 0 there keeps the GPU unpowered and triggers an SError on + // power-up. The firmware's warm restart after a deep sleep needs the other three as well: with + // only 0xa4 set it crashed in its power-up right after the RTKit handshake on the first wake. + // The low-peak (PPM) limiter words at +0xa80..+0xae0 are computed from the machine's ADT in + // `power_limiter`. + power_policy: &[(0x9c, 1), (0xa0, 1), (0xa4, 1), (0xa8, 1)], + // Exact power sample period (from `gpu-pwr-sample-period-aic-clks`, in us) and the + // average-power IIR filter over the ADT's `cpu-avg-limiter-input-tc`. + power_sampling: Some(PowerSampling { + period: &[0x2b48, 0x2c10], + period_f32: 0x2bbc, + filter: [0x29e4, 0x29f0, 0x29f8], + }), + // Low-peak (PPM) power limiter IIR filter and PI controller words (25G83 +0xa70..+0xad0, + // shifted +0x10 in 26B123), derived from `/arm-io/pmgr/clpc` (`cpu-lowpeak-limiter-*`) + // and `/arm-io/sgx` (`gpu-power-sample-period`). + power_limiter: Some(PowerLimiter { + filter_periods_x4: 0xa80, + filter_a_neg: 0xa8c, + filter_a: 0xa94, + ki_dt: 0xa9c, + clamp: 0xaa8, + kp: 0xaac, + filter_tc_ms: 0xad8, + filter_tc_clks: 0xae0, + }), + state_bound: None, +}; + +/// G15S 26B123 keeps the protocol layouts and ADT-derived power sampling/limiter encoding while +/// supplying its own HW data and register map. +pub(crate) const G15S_26B123: Layout = Layout { + name: "26B123 G15S", + version: 0x0c8a836f039404b8, + tx: TxLayout::RingHeader, + object_size: { + let mut sizes = V26B123.object_size; + sizes[id::MAIN] = 0x2790; + sizes + }, + loader_slot: slots_g15s(), + loaders: &G15S_LOADERS, + empty_loader_modes: (1 << 2) + | (0xf << 5) + | (7 << 25) + | (1 << 32) + | (1 << 35) + | (1 << 43) + | (3 << 46) + | (0xf << 52) + | (1 << 58), + main_core_slots: Some(20), + main_policy: &[(0x275c, 1), (0x2786, 1), (0x278a, 1)], + globals: &[run(0, 0x38, 0), run(0x38, 0xe28, 4), run(0xe28, 0xe47, 5)], + globals_policy: &[(0xe31, 1)], + ..V26B123 +}; + +/// G15G (T8122 C0) 26B123: the G16G 26B123 objects, register-map positions and protocol, with +/// the InitData version this image accepts (measured on the J615, linux#2781: the G16G version, +/// 0x0391, 0x0393 and 0x0395 in the differing field fault right after the root), the T8122 +/// register blocks, and the words the m3 27.2 runtime adds to the performance object. +pub(crate) const G15G_26B123: Layout = Layout { + name: "26B123 G15G", + version: 0x0c8a836f039404b8, + loaders: &G15G_LOADERS, + // 26.6.2 slots 2, 5-7, 30, 33, 34, 37, 38 and 41-43 carry write mode 2 while empty + // (`m3_mmio_26::empty_mode`); at their 26B123 positions (`slots_26b123`). + empty_loader_modes: (1 << 2) | (7 << 5) | (1 << 35) | (3 << 38) | (3 << 42) | (7 << 46), + // Two words this InitData family adds, 1 each as the G14 27.2 path sets them, next to the + // four power-up words (linux#2781 `relocate_26b123`). + power_policy: &[ + (0x9c, 1), + (0xa0, 1), + (0xa4, 1), + (0xa8, 1), + (0x2f34, 1), + (0x6ac8, 1), + ], + // The shared3 block's state word (+0x62ac + 8): with the block all zero the G15G firmware + // never takes the first device-control records. + state_bound: Some(0x62b4), + // GLOBALS as the G15 family's 26B123 InitData version lays it out (the same version as + // G15S): the words from 25G83 +0xe28 on sit 5 bytes up, not G16G's 4. With G16G's runs the + // soft-fault word (25G83 +0xe28 = 3) lands one byte low, the firmware reads 0 there and an + // unmapped shader write faults the context instead of being dropped. + globals: G15S_26B123.globals, + ..V26B123 +}; + +/// The T8122 register blocks behind each logical 26.6.2 slot (`m3_mmio_26::area` with the +/// T8122 blocks of `m3_adt_config::T8122_IO_MAPPINGS`). +const G15G_LOADERS: [Loader; LOADER_COUNT] = { + const SGX: u64 = 0x290000000; + let mut out = [EMPTY; LOADER_COUNT]; + out[0] = mmio(0x2d1014000, 0x4000, 0, 2); + // The memory cache, two banks, as on T8132. + out[3] = LOADERS[3]; + out[9] = mmio(0x2d03d0000, 0x1000, 0, 2); + out[10] = mmio(0x2d03c0000, 0x2000, 0, 0); + out[12] = mmio(0x31145c000, 0x4000, 0, 2); + out[14] = mmio(0x2d0280000, 0x8000, 0, 0); + out[17] = mmio(SGX, 0x20000, 0, 2); + out[26] = mmio(SGX + 0xd04000, 0x8000, 0xd04000, 2); + out[27] = mmio(SGX + 0xd0d000, 0x1000, 0xd0d000, 2); + out[28] = mmio(SGX + 0xd50000, 0x8000, 0xd50000, 2); + out[29] = mmio(SGX + 0xd10000, 0x4000, 0xd10000, 2); + out[31] = mmio(SGX + 0xd40000, 0x4000, 0xd40000, 2); + out[32] = mmio(SGX + 0xd60000, 0x8000, 0xd60000, 2); + out[35] = mmio(SGX + 0xe00000, 0x4000, 0xe00000, 2); + out[39] = mmio(SGX + 0xe08000, 0x8000, 0, 2); + out[40] = mmio(SGX + 0xe1c000, 0x4000, 0xe1c000, 2); + out +}; + +const fn slots_g15s() -> [Option; LOADER_COUNT] { + let mut slots = slots_26b123(); + // The final two named registers use G15S-specific slots. Slot 41 (G16G's + // firmware-owned power transition block) stays empty on G15S. + slots[35] = Some(40); + slots[41] = Some(48); + slots +} + +/// Runs are ordered, disjoint and land inside an object of `size` bytes. +const fn runs_fit(runs: &[Run], size: usize) -> bool { + let mut i = 0; + while i < runs.len() { + if runs[i].start >= runs[i].end + || runs[i].end + runs[i].delta > size + || (i > 0 && runs[i].start < runs[i - 1].end) + { + return false; + } + i += 1; + } + true +} + +/// Fixed 25G83 GLOBALS words remapped into every ABI; shared by `encode_for` and `layout_fits`. +const GLOBALS_FIXED: &[(usize, u32)] = &[ + (0x78, 1), + (0xe28, 3), + (0x24, 3000), + (0x998, 40), + (0x99c, 10), + (0x9a0, 250), + (0x9b8, 2), + (0x9bc, 40), + (0x9c0, 5), + // Firmware DM2 (compute) progress-watchdog thresholds (~4 ms/tick): + // - 0x9c8 (26B123 0x9cc): secondary DM2 soft-preempt watchdog, raised from 40 (~0.16 s) + // to 750 (~3.0 s) so legitimate long/contended compute dispatches (e.g. 1.5 s solo + // workloads) complete without premature kill while staying below the 5 s host fail-stop. + // - 0x9cc (26B123 0x9d0): primary DM2 recovery watchdog, raised from 50 (~0.20 s) to 800 + // (~3.2 s) so legitimate compute dispatches complete while real hangs still trigger + // firmware recovery well before the 5 s host fail-stop deadline. + (0x9c8, 750), + (0x9cc, 800), +]; + +/// Fixed 25G83 POWER_PERFORMANCE offsets remapped into every ABI; shared by `encode_for` and +/// `layout_fits` so compile-time collision checks cover every remapped write. +const POWER_TEMP_PTR: usize = 0x3b50; +const POWER_FIXED_U32: &[usize] = &[4, 8, 0x10, 0x14, 0x2c, 0x30]; +const POWER_CEILING_U32: &[usize] = &[ + 0x9f0, 0x9f4, 0xa38, 0xaa8, 0xaac, 0xaf0, 0xb78, 0xb7c, 0xb80, 0xbc0, 0x22b0, 0x22b4, 0x22f8, + 0x2210, 0x2870, 0x2a3c, 0x2b84, 0x2b88, 0x2b8c, 0x2bcc, 0x2c40, 0x2c44, 0x2c88, 0x279e, +]; + +const fn ranges_overlap(a: usize, a_len: usize, b: usize, b_len: usize) -> bool { + a < b + b_len && b < a + a_len +} + +/// Every `main_policy` word fits in MAIN and is disjoint from every other policy word, the +/// register map, `coredump_copy`, and every remapped 25G83 MAIN run. +const fn main_policy_fits(layout: &Layout) -> bool { + let size = layout.object_size[id::MAIN]; + let map_len = layout.register_slots * LOADER_STRIDE; + let mut i = 0; + while i < layout.main_policy.len() { + let at = layout.main_policy[i].0; + if at + 4 > size || ranges_overlap(at, 4, 0x640, map_len) { + return false; + } + if let Some(cc) = layout.coredump_copy { + if ranges_overlap(at, 4, cc, 8) { + return false; + } + } + let mut j = 0; + while j < i { + if ranges_overlap(at, 4, layout.main_policy[j].0, 4) { + return false; + } + j += 1; + } + let mut r = 0; + while r < layout.main.len() { + let run = layout.main[r]; + let start = run.start + run.delta; + let len = run.end - run.start; + if ranges_overlap(at, 4, start, len) { + return false; + } + r += 1; + } + i += 1; + } + true } -/// Recovery words belong to FirmwareData, not root.Control. -pub(crate) mod control { - pub(crate) const SIZE: usize = super::OBJECT_SIZE[super::id::FIRMWARE_DATA]; - pub(crate) const GENERATION: usize = 0x4fa0; - pub(crate) const PHASE: usize = 0x4fb0; - pub(crate) const SCHEDULER: usize = 0x4fd4; + +/// Every `globals_policy` word fits in GLOBALS and is disjoint from every other policy word, +/// every p-state selector, and every remapped 25G83 GLOBALS word. +const fn globals_policy_fits(layout: &Layout) -> bool { + let size = layout.object_size[id::GLOBALS]; + let mut i = 0; + while i < layout.globals_policy.len() { + let at = layout.globals_policy[i].0; + if at + 4 > size { + return false; + } + let mut j = 0; + while j < i { + if ranges_overlap(at, 4, layout.globals_policy[j].0, 4) { + return false; + } + j += 1; + } + let mut k = 0; + while k < layout.pstate_selectors.len() { + if ranges_overlap(at, 4, layout.pstate_selectors[k], 4) { + return false; + } + k += 1; + } + let mut m = 0; + while m < GLOBALS_FIXED.len() { + let Some(remapped) = remap_const(layout.globals, GLOBALS_FIXED[m].0, 4) else { + return false; + }; + if ranges_overlap(at, 4, remapped, 4) { + return false; + } + m += 1; + } + i += 1; + } + true +} + +/// A 4-byte POWER_PERFORMANCE slot fits and does not collide with any remapped 25G83 word. +const fn power_slot_clear(layout: &Layout, at: usize) -> bool { + let size = layout.object_size[id::POWER_PERFORMANCE]; + if at + 4 > size { + return false; + } + let Some(temp) = remap_const(layout.power_performance, POWER_TEMP_PTR, 8) else { + return false; + }; + if ranges_overlap(at, 4, temp, 8) { + return false; + } + let mut i = 0; + while i < POWER_FIXED_U32.len() { + let Some(remapped) = remap_const(layout.power_performance, POWER_FIXED_U32[i], 4) else { + return false; + }; + if ranges_overlap(at, 4, remapped, 4) { + return false; + } + i += 1; + } + let mut j = 0; + while j < POWER_CEILING_U32.len() { + let Some(remapped) = remap_const(layout.power_performance, POWER_CEILING_U32[j], 4) else { + return false; + }; + if ranges_overlap(at, 4, remapped, 4) { + return false; + } + j += 1; + } + true +} + +const fn power_policy_overlaps(policy: &[(usize, u32)], at: usize) -> bool { + let mut i = 0; + while i < policy.len() { + if ranges_overlap(at, 4, policy[i].0, 4) { + return false; + } + i += 1; + } + true +} + +const fn sampling_clear_of(sampling: Option, at: usize) -> bool { + let Some(s) = sampling else { + return true; + }; + if ranges_overlap(at, 4, s.period_f32, 4) { + return false; + } + let mut i = 0; + while i < s.period.len() { + if ranges_overlap(at, 4, s.period[i], 4) { + return false; + } + i += 1; + } + let mut j = 0; + while j < s.filter.len() { + if ranges_overlap(at, 4, s.filter[j], 4) { + return false; + } + j += 1; + } + true +} + +/// Every `power_policy`, `power_sampling` and `power_limiter` word fits in POWER_PERFORMANCE +/// and is disjoint from every remapped 25G83 word and from every other policy/sampling/limiter +/// word. +const fn power_policy_fits(layout: &Layout) -> bool { + let mut i = 0; + while i < layout.power_policy.len() { + let at = layout.power_policy[i].0; + if !power_slot_clear(layout, at) { + return false; + } + let mut j = 0; + while j < i { + if ranges_overlap(at, 4, layout.power_policy[j].0, 4) { + return false; + } + j += 1; + } + i += 1; + } + if let Some(s) = layout.power_sampling { + if !power_slot_clear(layout, s.period_f32) + || !power_policy_overlaps(layout.power_policy, s.period_f32) + { + return false; + } + let mut p = 0; + while p < s.period.len() { + let at = s.period[p]; + if !power_slot_clear(layout, at) + || !power_policy_overlaps(layout.power_policy, at) + || ranges_overlap(at, 4, s.period_f32, 4) + { + return false; + } + let mut prev = 0; + while prev < p { + if ranges_overlap(at, 4, s.period[prev], 4) { + return false; + } + prev += 1; + } + p += 1; + } + let mut f = 0; + while f < s.filter.len() { + let at = s.filter[f]; + if !power_slot_clear(layout, at) + || !power_policy_overlaps(layout.power_policy, at) + || ranges_overlap(at, 4, s.period_f32, 4) + { + return false; + } + let mut p2 = 0; + while p2 < s.period.len() { + if ranges_overlap(at, 4, s.period[p2], 4) { + return false; + } + p2 += 1; + } + let mut prev = 0; + while prev < f { + if ranges_overlap(at, 4, s.filter[prev], 4) { + return false; + } + prev += 1; + } + f += 1; + } + } + if let Some(lim) = layout.power_limiter { + let slots = [ + lim.filter_periods_x4, + lim.filter_a_neg, + lim.filter_a, + lim.ki_dt, + lim.clamp, + lim.kp, + lim.filter_tc_ms, + lim.filter_tc_clks, + ]; + let mut k = 0; + while k < slots.len() { + let at = slots[k]; + if !power_slot_clear(layout, at) + || !power_policy_overlaps(layout.power_policy, at) + || !sampling_clear_of(layout.power_sampling, at) + { + return false; + } + let mut prev = 0; + while prev < k { + if ranges_overlap(at, 4, slots[prev], 4) { + return false; + } + prev += 1; + } + k += 1; + } + } + true } -pub(crate) mod globals { - pub(crate) const SIZE: usize = super::OBJECT_SIZE[super::id::GLOBALS]; - pub(crate) const PSTATE_SELECTORS: [usize; 3] = [0x88, 0x8c, 0x98]; + +/// A layout's words fit its objects and do not overlap each other. +pub(crate) const fn layout_fits(layout: &Layout) -> bool { + let fd = &layout.firmware_data; + let size = &layout.object_size; + fd.snapshot + fd.snapshot_entries * 8 <= fd.fwctl + && fd.fwctl + 0x10 <= fd.generation + && fd.generation + 8 <= fd.phase + && fd.phase < fd.scheduler + && fd.scheduler + 4 <= size[id::FIRMWARE_DATA] + && layout.power_config + 8 <= size[id::RUNTIME] + // The register map ends where the MAIN words after it (the retention pointer) start. + && 0x640 + layout.register_slots * LOADER_STRIDE + == layout.main[1].start + layout.main[1].delta + && runs_fit(layout.main, size[id::MAIN]) + && runs_fit(layout.globals, size[id::GLOBALS]) + && runs_fit(layout.power_performance, size[id::POWER_PERFORMANCE]) + && retention_fits(layout) + && main_policy_fits(layout) + && globals_policy_fits(layout) + && power_policy_fits(layout) } -pub(crate) mod hwdata { - pub(crate) const SIZE: usize = super::OBJECT_SIZE[super::id::MAIN]; + +/// A RUNTIME retention table pointer is aligned, inside RUNTIME and clear of the power-config +/// pointer. +const fn retention_fits(layout: &Layout) -> bool { + match layout.retention { + Retention::Main => true, + Retention::Runtime(at) => { + at % 8 == 0 + && at + 8 <= layout.object_size[id::RUNTIME] + && (at + 8 <= layout.power_config || layout.power_config + 8 <= at) + } + } } +const _: () = assert!(layout_fits(&V25G83) && layout_fits(&V26B123) && layout_fits(&G15S_26B123)); +const _: () = assert!(layout_fits(&G15G_26B123)); +const _: () = assert!(match G15G_26B123.state_bound { + Some(at) => + power_slot_clear(&G15G_26B123, at) && power_policy_overlaps(G15G_26B123.power_policy, at), + None => false, +}); /// One logical loader record, including its page offset and exact PTE class. #[derive(Clone, Copy, Debug)] @@ -265,24 +1064,76 @@ const fn loaders() -> [Loader; LOADER_COUNT] { } pub(crate) const LOADERS: [Loader; LOADER_COUNT] = loaders(); -/// Actual mapped span: slot 3 has two discontiguous physical banks. -pub(crate) fn loader_span(slot: usize, bank: usize) -> Result<(u64, u32, u32), ()> { - let e = LOADERS.get(slot).ok_or(())?; - if e.length == 0 || bank > if slot == 3 { 1 } else { 0 } { - return Err(()); +const G15S_LOADERS: [Loader; LOADER_COUNT] = { + const SGX: u64 = 0x290000000; + let mut out = [EMPTY; LOADER_COUNT]; + out[0] = mmio(0x351014000, 0x4000, 0, 2); + out[1] = mmio(0x3502bc000, 0x4000, 0, 0); + out[3] = LOADERS[3]; + out[4] = mmio(0x35104c000, 0x4000, 0, 0); + out[9] = mmio(0x3503d0000, 0x4000, 0, 2); + out[10] = mmio(0x3503c0000, 0x4000, 0, 0); + out[11] = mmio(0x3503d8000, 0x4000, 0, 2); + out[12] = mmio(0x30945c000, 0x4000, 0, 2); + out[14] = mmio(0x350280000, 0x8000, 0, 0); + out[17] = mmio(SGX, 0x20000, 0, 2); + out[20] = mmio(0x293000000, 0x400000, 0, 2); + out[26] = mmio(SGX + 0xd04000, 0x8000, 0xd04000, 2); + out[28] = mmio(SGX + 0xd50000, 0x8000, 0xd50000, 2); + out[29] = mmio(SGX + 0xd10000, 0x4000, 0xd10000, 2); + out[31] = mmio(SGX + 0xd40000, 0x4000, 0xd40000, 2); + out[32] = mmio(SGX + 0xd60000, 0x20000, 0xd60000, 2); + out[33] = mmio(SGX + 0xd44000, 0x4000, 0xd44000, 2); + out[34] = mmio(SGX + 0xd4c000, 0x200, 0xd4c000, 2); + // The protected register block is explicitly supplied with mode 2 in G15S slot 40. + out[35] = mmio(SGX + 0xe00000, 0x4000, 0xe00000, 2); + out[37] = mmio(SGX + 0xe40000, 0x4000, 0xe40000, 2); + out[39] = mmio(SGX + 0xe08000, 0x8000, 0, 2); + out[40] = mmio(SGX + 0xe5c000, 0x4000, 0xe5c000, 2); + out[41] = mmio(SGX + 0xe60000, 0x50, 0xe60000, 2); + out +}; + +const fn mmio(pa: u64, length: u32, tag: u64, mode: u8) -> Loader { + Loader { + pa, + length, + requested: length, + tag, + mode, + attrs: if mode == 2 { MMIO_RW } else { MMIO_RO }, + } +} + +impl Loader { + /// Number of banks in this window. A banked record encodes the combined span + /// and the requested size of one bank. + pub(crate) fn banks(&self) -> usize { + if self.length > self.requested { + 2 + } else { + 1 + } + } + + /// Actual mapped span. The two banks have adjacent VAs and discontiguous PAs. + pub(crate) fn span(&self, bank: usize) -> Result<(u64, u32, u32), ()> { + if self.length == 0 || bank >= self.banks() { + return Err(()); + } + let offset = self.pa & (PAGE - 1); + let bytes = u64::from(self.requested); + let size = (offset + bytes + PAGE - 1) & !(PAGE - 1); + Ok(( + (self.pa & PA_MASK) + bank as u64 * 0x2000000, + size as u32, + bank as u32 * self.requested, + )) } - let offset = e.pa & (PAGE - 1); - let bytes = if slot == 3 { - 0x18000 - } else { - u64::from(e.length) - }; - let size = (offset + bytes + PAGE - 1) & !(PAGE - 1); - Ok(( - (e.pa & PA_MASK) + if bank != 0 { 0x2000000 } else { 0 }, - size as u32, - if bank != 0 { 0x18000 } else { 0 }, - )) +} + +pub(crate) fn loader_span(slot: usize, bank: usize) -> Result<(u64, u32, u32), ()> { + LOADERS.get(slot).ok_or(())?.span(bank) } fn put32(out: &mut [u8], at: usize, value: u32) -> Result<(), ()> { @@ -299,37 +1150,46 @@ fn put64(out: &mut [u8], at: usize, value: u64) -> Result<(), ()> { } pub(crate) fn loader_encode(slot: usize, va: u64, record: &mut [u8]) -> Result<(), ()> { - let e = LOADERS.get(slot).ok_or(())?; - let out = record.get_mut(..LOADER_STRIDE).ok_or(())?; - if e.length == 0 { - if va != 0 { + LOADERS.get(slot).ok_or(())?.encode(va, record) +} + +impl Loader { + fn encode(&self, va: u64, record: &mut [u8]) -> Result<(), ()> { + let e = self; + let out = record.get_mut(..LOADER_STRIDE).ok_or(())?; + if e.length == 0 { + if va != 0 { + return Err(()); + } + out.fill(0); + return Ok(()); + } + let offset = e.pa & (PAGE - 1); + let span = (offset + u64::from(e.length) + PAGE - 1) & !(PAGE - 1); + if !(HOST_START..HOST_END).contains(&va) + || va & (PAGE - 1) != offset + || span > HOST_END - (va - offset) + { return Err(()); } - out.fill(0); - return Ok(()); + put64(out, 0, e.pa)?; + put64(out, 8, va)?; + put32(out, 0x10, e.length)?; + put32(out, 0x14, e.requested)?; + put64(out, 0x18, e.tag)?; + put64(out, 0x20, u64::from(e.mode)) } - let offset = e.pa & (PAGE - 1); - let span = (offset + u64::from(e.length) + PAGE - 1) & !(PAGE - 1); - if !(HOST_START..HOST_END).contains(&va) - || va & (PAGE - 1) != offset - || span > HOST_END - (va - offset) - { - return Err(()); - } - put64(out, 0, e.pa)?; - put64(out, 8, va)?; - put32(out, 0x10, e.length)?; - put32(out, 0x14, e.requested)?; - put64(out, 0x18, e.tag)?; - put64(out, 0x20, u64::from(e.mode)) } -pub(crate) const PERF_STATES: usize = 10; +/// Capacity for the largest qualified table: J713 has ten rows, J773g eleven. +pub(crate) const PERF_STATES: usize = 11; /// Machine-specific values selected from the original ADT before firmware publication. /// Frequencies are exact MHz, voltages are millivolts. No reference-bin defaults exist. +/// Only the first `count` rows are used; the rest are zero. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Performance { + pub(crate) count: usize, pub(crate) frequency: [u32; PERF_STATES], pub(crate) auxiliary: [u32; PERF_STATES], pub(crate) voltage: [u32; PERF_STATES], @@ -338,7 +1198,19 @@ pub(crate) struct Performance { impl Performance { pub(crate) fn valid(&self) -> bool { - for i in 0..PERF_STATES { + if !(2..=PERF_STATES).contains(&self.count) { + return false; + } + for i in self.count..PERF_STATES { + if self.frequency[i] != 0 + || self.auxiliary[i] != 0 + || self.voltage[i] != 0 + || self.sram[i] != 0 + { + return false; + } + } + for i in 0..self.count { if self.frequency[i] > 3000 || self.auxiliary[i] > self.frequency[i] || ((i == 0) != (self.frequency[i] == 0)) @@ -370,7 +1242,36 @@ pub(crate) struct Input { pub(crate) lower_parameter: u64, pub(crate) ktrace_mask: u32, pub(crate) progress_recovery: u32, + pub(crate) enabled_cores: u32, pub(crate) performance: Performance, + /// Exact GPU power sample period in system-counter ticks (`gpu-pwr-sample-period-aic-clks`), + /// written to POWER_PERFORMANCE +4/+8. Non-zero is required. + pub(crate) power_sample_clks: u32, + /// Exact GPU power sample period in us (`power_sample_clks * 1_000_000 / timebase_hz`), + /// used instead of the coarse truncated ms property for the us period and average-power + /// sample count. 0 when absent, which a layout with [`Layout::power_sampling`] refuses. + pub(crate) power_sample_us: u32, + /// Coarse integer millisecond GPU power sample period (`gpu-power-sample-period`). 0 when + /// absent, which a layout with [`Layout::power_limiter`] refuses. + pub(crate) power_sample_period_ms: u32, + /// System counter frequency in kHz (`timebase_hz / 1000`). 0 is refused by + /// [`Layout::power_limiter`]. + pub(crate) timebase_khz: u32, + /// Average-power filter time constant in ms (`/arm-io/pmgr/clpc` `cpu-avg-limiter-input-tc`). + /// 0 when absent, which a layout with [`Layout::power_sampling`] refuses. + pub(crate) avg_power_filter_tc_ms: u32, + /// Low-peak (PPM) limiter filter time constant in ms (`cpu-lowpeak-limiter-input-tc`). + /// 0 when absent, which a layout with [`Layout::power_limiter`] refuses. + pub(crate) lowpeak_limiter_tc_ms: u32, + /// Low-peak (PPM) limiter integral gain in Q16.16 (`cpu-lowpeak-limiter-ki`). + /// 0 when absent, which a layout with [`Layout::power_limiter`] refuses. + pub(crate) lowpeak_limiter_ki_q16: u32, + /// Low-peak (PPM) limiter proportional gain in Q16.16 (`cpu-lowpeak-limiter-kp`). + /// 0 when absent, which a layout with [`Layout::power_limiter`] refuses. + pub(crate) lowpeak_limiter_kp_q16: u32, + /// Host crash copy buffer size in bytes (`/arm-io/gfx-asc/iop-gfx-nub` + /// `coredump-copy-buffer`). 0 or unaligned is refused by layouts with `coredump_copy`. + pub(crate) coredump_copy_size: u64, } pub(crate) fn object_va(va: u64, size: usize) -> bool { @@ -381,20 +1282,31 @@ fn bootstrap_alias(va: u64) -> bool { && va & (PAGE - 1) == 0 } +/// Encodes the 25G83 root. pub(crate) fn encode_root(out: &mut [u8], va: &[u64; OBJECT_COUNT]) -> Result<(), ()> { + encode_root_for(&V25G83, out, va) +} + +/// Encodes the root of `layout`'s ABI after checking every object VA and overlap. +pub(crate) fn encode_root_for( + layout: &Layout, + out: &mut [u8], + va: &[u64; OBJECT_COUNT], +) -> Result<(), ()> { + let size = &layout.object_size; for i in 0..OBJECT_COUNT { - if !object_va(va[i], OBJECT_SIZE[i]) { + if !object_va(va[i], size[i]) { return Err(()); } for j in 0..i { - if va[i] < va[j] + OBJECT_SIZE[j] as u64 && va[j] < va[i] + OBJECT_SIZE[i] as u64 { + if va[i] < va[j] + size[j] as u64 && va[j] < va[i] + size[i] as u64 { return Err(()); } } } let out = out.get_mut(..root::SIZE).ok_or(())?; out.fill(0); - put64(out, 0, root::MAGIC)?; + put64(out, 0, layout.version)?; for (at, i) in [ (0x08, id::BRN), (0x18, id::RUNTIME), @@ -425,7 +1337,22 @@ pub(crate) fn encode_channel( ring: u64, control: bool, ) -> Result<(), ()> { - let bytes = if control { 0x4000 } else { 0x1800 }; + encode_tx(TxLayout::StateBlock, out, state, ring, control) +} + +fn encode_tx( + layout: TxLayout, + out: &mut [u8], + state: u64, + ring: u64, + control: bool, +) -> Result<(), ()> { + let header = layout.ring_header(control) as u64; + let bytes = if control { + 0x4000 + } else { + 0x1800 + header as usize + }; if !object_va(state, 0x30) || !object_va(ring, bytes) || (state < ring + bytes as u64 && ring < state + 0x30) @@ -433,20 +1360,32 @@ pub(crate) fn encode_channel( return Err(()); } put64(out, 0, state)?; - put64(out, 8, state + 0x10)?; - put64(out, 0x10, state + 0x20)?; - put64(out, 0x18, ring) + put64(out, 8, state + layout.completion() as u64)?; + put64(out, 0x10, if header == 0 { state + 0x20 } else { ring })?; + put64(out, 0x18, ring + header) } -/// Encodes the complete private 31-object graph, byte-for-byte matching the +/// Encodes the complete private 31-object 25G83 graph, byte-for-byte matching the /// working M4 C encoder. No mapping or publication is performed here. pub(crate) fn encode( objects: &mut [&mut [u8]; OBJECT_COUNT], input: &Input, ceiling: u32, ) -> Result<(), ()> { - if !(1..=9).contains(&ceiling) - || !input.performance.valid() + encode_for(&V25G83, objects, input, ceiling) +} + +/// Encodes the complete private 31-object graph of `layout`'s ABI. Every input is checked +/// before the first byte is written. +pub(crate) fn encode_for( + layout: &Layout, + objects: &mut [&mut [u8]; OBJECT_COUNT], + input: &Input, + ceiling: u32, +) -> Result<(), ()> { + if !input.performance.valid() + || !(1..input.performance.count as u32).contains(&ceiling) + || input.power_sample_clks == 0 || !object_va(input.scratch, 0x8000) || !bootstrap_alias(input.lower_uma) || !bootstrap_alias(input.lower_parameter) @@ -455,14 +1394,67 @@ pub(crate) fn encode( { return Err(()); } + // Validate ADT-derived power sampling and limiter inputs before touching any output byte. + let sampling_values = if layout.power_sampling.is_some() { + if input.power_sample_us == 0 || input.avg_power_filter_tc_ms == 0 { + return Err(()); + } + let samples_u64 = + (u64::from(input.avg_power_filter_tc_ms) * 1000) / u64::from(input.power_sample_us); + let samples = u32::try_from(samples_u64).map_err(|_| ())?; + if samples < 2 || samples.checked_mul(4).is_none() { + return Err(()); + } + Some((input.power_sample_us, samples)) + } else { + None + }; + let limiter_values = if layout.power_limiter.is_some() { + if input.power_sample_period_ms == 0 + || input.timebase_khz == 0 + || input.lowpeak_limiter_tc_ms == 0 + || input.lowpeak_limiter_ki_q16 == 0 + || input.lowpeak_limiter_kp_q16 == 0 + { + return Err(()); + } + // The low-peak IIR filter spans `periods` sample periods. One period (the ADT's + // limiter time constant equals its sample period, as on the 15-inch M3 Air) is a valid + // filter: a_neg = (1 - 1) / 1 = +0.0 and a = 1 / 1 = +1.0, i.e. each sample is taken + // as is. Only a time constant shorter than one period is refused. + let periods = input.lowpeak_limiter_tc_ms / input.power_sample_period_ms; + if periods < 1 { + return Err(()); + } + let periods_x4 = periods.checked_mul(4).ok_or(())?; + let ki_num = input + .lowpeak_limiter_ki_q16 + .checked_mul(input.power_sample_period_ms) + .ok_or(())?; + let tc_clks = periods + .checked_mul(input.power_sample_period_ms) + .and_then(|ms| ms.checked_mul(input.timebase_khz)) + .ok_or(())?; + Some((periods, periods_x4, ki_num, tc_clks)) + } else { + None + }; + if layout.coredump_copy.is_some() + && (input.coredump_copy_size == 0 + || input.coredump_copy_size & 0xfff != 0 + || input.coredump_copy_size > 0x10_0000) + { + return Err(()); + } + let size = &layout.object_size; for (i, obj) in objects.iter().enumerate() { - if obj.len() < OBJECT_SIZE[i] { + if obj.len() < size[i] { return Err(()); } } - encode_root(objects[id::ROOT], &input.va)?; + encode_root_for(layout, objects[id::ROOT], &input.va)?; for i in 1..OBJECT_COUNT { - objects[i][..OBJECT_SIZE[i]].fill(0); + objects[i][..size[i]].fill(0); } let runtime = &mut objects[id::RUNTIME]; for (at, i) in [ @@ -483,58 +1475,68 @@ pub(crate) fn encode( (0x26c, id::ACTIVITY_RECOVERY), (0x2d8, id::PARAMETER), (0x2e8, id::UMA), - (0x469, id::POWER_PERFORMANCE), + (layout.power_config, id::POWER_PERFORMANCE), ] { put64(runtime, at, input.va[i])?; } + if layout.tx == TxLayout::RingHeader { + put64(runtime, 0x8, input.va[id::TIMER])?; + } put64(runtime, 0x18, input.scratch)?; put64(runtime, 0x2d0, input.lower_parameter)?; put64(runtime, 0x2e0, input.lower_uma)?; put32(runtime, 0x250, 1)?; put32(runtime, 0x2f8, 4)?; + if let Retention::Runtime(at) = layout.retention { + put64(runtime, at, input.va[id::RETENTION])?; + } for i in 0..12 { - encode_channel( + encode_tx( + layout.tx, &mut runtime[0x20 + i * 0x20..], input.channel_state[i], input.channel_ring[i], false, )?; } - encode_channel( + encode_tx( + layout.tx, &mut runtime[0x1a0..], input.va[id::DEVCTRL_STATE], input.va[id::DEVCTRL_RING], true, )?; + let fd = &layout.firmware_data; let fw = &mut objects[id::FIRMWARE_DATA]; - put64(fw, 0x4f88, input.va[id::FWCTL])?; - put64(fw, 0x4f90, input.va[id::FWCTL] + 0x40)?; - put32(fw, 0x4fd4, 1)?; + put64(fw, fd.fwctl, input.va[id::FWCTL])?; + put64(fw, fd.fwctl + 8, input.va[id::FWCTL] + 0x40)?; + put32(fw, fd.scheduler, 1)?; put32(objects[id::CONTROL], 0, input.ktrace_mask)?; put32(objects[id::ACTIVITY_FRAGMENT], 0xc18, 0xffffffff)?; put32(objects[id::ACTIVITY_FRAGMENT], 0xc30, 0xffffffff)?; let g = &mut objects[id::GLOBALS]; - for (at, value) in [ - (0x78, 1), - (0xe28, 3), - (0x24, 3000), - (0x998, 40), - (0x99c, 10), - (0x9a0, 250), - (0x9b8, 2), - (0x9bc, 40), - (0x9c0, 5), - (0x9c8, 40), - (0x9cc, 50), - ] { - put32(g, at, value)?; + for &(at, value) in GLOBALS_FIXED { + put32(g, remap(layout.globals, at, 4)?, value)?; } - for at in globals::PSTATE_SELECTORS { + for at in layout.pstate_selectors { put32(g, at, 100 * ceiling)?; } + for &(at, value) in layout.globals_policy { + put32(g, at, value)?; + } + let runs = layout.main; let main = &mut objects[id::MAIN]; - put64(main, 0x28, HOST_END)?; - put64(main, 0xe88, input.va[id::RETENTION])?; + put64(main, remap(runs, 0x28, 8)?, HOST_END)?; + if layout.retention == Retention::Main { + put64(main, remap(runs, 0xe88, 8)?, input.va[id::RETENTION])?; + } + if let Some(at) = layout.coredump_copy { + put64(main, at, input.coredump_copy_size)?; + } + for &(at, value) in layout.main_policy { + put32(main, at, value)?; + } + let core_slots = layout.main_core_slots; for (at, value) in [ (0xea0, 1), (0xee0, 1), @@ -542,62 +1544,127 @@ pub(crate) fn encode( (0xed0, 24000), (0xed4, 1), (0xed8, 8), - (0xfc0, 10), + (0xfc0, core_slots.unwrap_or(input.performance.count as u32)), (0x259c, 1), - (0x2544, 4), + (0x2544, if core_slots.is_some() { 5 } else { 4 }), (0x2548, 6), (0x254c, 3), (0x2550, 7), (0x2554, 7), - (0x2568, 8), - (0x2570, 1), + (0x2568, if core_slots.is_some() { 0 } else { 8 }), + (0x2570, core_slots.map_or(1, |_| input.enabled_cores)), ] { - put32(main, at, value)?; + put32(main, remap(runs, at, 4)?, value)?; } - put32(main, 0xea4, input.progress_recovery)?; - put64(main, 0xf24, 0x0000000607002004)?; - put32(main, 0xfc4, ceiling)?; + put32(main, remap(runs, 0xea4, 4)?, input.progress_recovery)?; + put64( + main, + remap(runs, 0xf24, 8)?, + if core_slots.is_some() { + 4 + } else { + 0x0000000607002004 + }, + )?; + put32(main, remap(runs, 0xfc4, 4)?, ceiling)?; for i in 0..=ceiling as usize { - put32(main, 0xfc8 + i * 4, input.performance.frequency[i])?; - put32(main, 0x1808 + i * 4, input.performance.auxiliary[i])?; + put32( + main, + remap(runs, 0xfc8 + i * 4, 4)?, + input.performance.frequency[i], + )?; + put32( + main, + remap(runs, 0x1808 + i * 4, 4)?, + input.performance.auxiliary[i], + )?; for core in 0..16 { put32( main, - 0x1008 + (i * 16 + core) * 4, + remap(runs, 0x1008 + (i * 16 + core) * 4, 4)?, input.performance.voltage[i], )?; put32( main, - 0x1408 + (i * 16 + core) * 4, + remap(runs, 0x1408 + (i * 16 + core) * 4, 4)?, input.performance.sram[i], )?; } } for slot in 0..LOADER_COUNT { - loader_encode( - slot, - input.loader_va[slot], - &mut main[0x640 + slot * LOADER_STRIDE..], - )?; + // This ABI has no slot for the record: the host must not have mapped it (`build` + // skips it), and it is not described. + let Some(at) = layout.slot(slot) else { + if input.loader_va[slot] != 0 { + return Err(()); + } + continue; + }; + if at >= layout.register_slots { + return Err(()); + } + let mut record = [0u8; LOADER_STRIDE]; + layout.loaders[slot].encode(input.loader_va[slot], &mut record)?; + let at = 0x640 + at * LOADER_STRIDE; + main.get_mut(at..at + LOADER_STRIDE) + .ok_or(())? + .copy_from_slice(&record); + } + for slot in 0..layout.register_slots { + if layout.empty_loader_modes & (1 << slot) != 0 { + put64(main, 0x640 + slot * LOADER_STRIDE + 0x20, 2)?; + } } + let runs = layout.power_performance; let p = &mut objects[id::POWER_PERFORMANCE]; - put64(p, 0x3b50, input.va[id::TEMPERATURE])?; - for (at, value) in [ - (4, 200000), - (8, 200000), - (0x10, 4), - (0x14, 0x3f800000), - (0x2c, ceiling), - (0x30, ceiling), - ] { + put64( + p, + remap(runs, POWER_TEMP_PTR, 8)?, + input.va[id::TEMPERATURE], + )?; + let power_fixed_values = [ + input.power_sample_clks, + input.power_sample_clks, + 4, + 0x3f800000, + ceiling, + ceiling, + ]; + for (&at, value) in POWER_FIXED_U32.iter().zip(power_fixed_values) { + put32(p, remap(runs, at, 4)?, value)?; + } + for &at in POWER_CEILING_U32 { + put32(p, remap(runs, at, 4)?, 100 * ceiling)?; + } + // Disjointness from every remapped 25G83 word, power_sampling, and power_limiter slot is + // proved at compile time by layout_fits(). + for &(at, value) in layout.power_policy { put32(p, at, value)?; } - for at in [ - 0x9f0, 0x9f4, 0xa38, 0xaa8, 0xaac, 0xaf0, 0xb78, 0xb7c, 0xb80, 0xbc0, 0x22b0, 0x22b4, - 0x22f8, 0x2210, 0x2870, 0x2a3c, 0x2b84, 0x2b88, 0x2b8c, 0x2bcc, 0x2c40, 0x2c44, 0x2c88, - 0x279e, - ] { - put32(p, at, 100 * ceiling)?; + if let Some(at) = layout.state_bound { + put32(p, at, input.performance.count as u32)?; + } + if let (Some(sampling), Some((period, samples))) = (layout.power_sampling, sampling_values) { + for &at in sampling.period { + put32(p, at, period)?; + } + put32(p, sampling.period_f32, f32_bits(period, 1))?; + let [count, keep, take] = sampling.filter; + put32(p, count, samples * 4)?; + put32(p, keep, f32_bits(samples - 1, samples))?; + put32(p, take, f32_bits(1, samples))?; + } + if let (Some(limiter), Some((periods, periods_x4, ki_num, tc_clks))) = + (layout.power_limiter, limiter_values) + { + put32(p, limiter.filter_periods_x4, periods_x4)?; + put32(p, limiter.filter_a_neg, f32_bits(periods - 1, periods))?; + put32(p, limiter.filter_a, f32_bits(1, periods))?; + put32(p, limiter.ki_dt, f32_bits(ki_num, 65536 * 1000))?; + put32(p, limiter.clamp, f32_bits(65536, 1))?; + put32(p, limiter.kp, f32_bits(input.lowpeak_limiter_kp_q16, 65536))?; + put32(p, limiter.filter_tc_ms, input.lowpeak_limiter_tc_ms)?; + put32(p, limiter.filter_tc_clks, tc_clks)?; } Ok(()) } diff --git a/drivers/gpu/drm/asahi/g16/fw/mod.rs b/drivers/gpu/drm/asahi/g16/fw/mod.rs index 77984b8cb57856..e48096a54232c7 100644 --- a/drivers/gpu/drm/asahi/g16/fw/mod.rs +++ b/drivers/gpu/drm/asahi/g16/fw/mod.rs @@ -4,15 +4,74 @@ reason = "Firmware layout catalog also describes fields used by host wire regressions." )] -//! M4 firmware 25G83 structures. +//! M4 firmware 25G83 and 26B123 structures. //! //! Layouts of the records, work images and objects the host shares with the qualified 25G83 firmware, //! in the style of `g17/fw`: `#[repr(C)]` structures with `static_assert!` offsets where the //! layout is a fixed record, and offset constants where the driver writes sparse words into a //! larger image. Nothing here allocates, locks or publishes. +//! +//! What differs in another firmware ABI is held per file as `V25G83` / `V26B123` constants; +//! [`FwAbi`] selects them. pub(crate) mod buffer; pub(crate) mod channels; pub(crate) mod graph; pub(crate) mod initdata; pub(crate) mod work; + +use super::hw::FwAbi; + +impl FwAbi { + /// The device-control opcodes the host sends. + pub(crate) const fn devctl(self) -> &'static channels::devctl::Opcodes { + match self { + FwAbi::V25G83 => &channels::devctl::V25G83, + FwAbi::V26B123 | FwAbi::V26B123G15S => &channels::devctl::V26B123, + } + } + + /// The parameter-buffer manager layout. + pub(crate) const fn pb_manager(self) -> &'static buffer::pb_manager::Layout { + match self { + FwAbi::V25G83 | FwAbi::V26B123 => &buffer::pb_manager::V25G83, + FwAbi::V26B123G15S => &buffer::pb_manager::V26B123_G15S, + } + } + + /// The queue-info header. + pub(crate) const fn qinfo(self) -> &'static graph::qinfo::Layout { + match self { + FwAbi::V25G83 => &graph::qinfo::V25G83, + FwAbi::V26B123 => &graph::qinfo::V26B123, + FwAbi::V26B123G15S => &graph::qinfo::V26B123_G15S, + } + } + + /// The TA work. + pub(crate) const fn ta(self) -> &'static work::ta::Layout { + match self { + FwAbi::V25G83 => &work::ta::V25G83, + FwAbi::V26B123 => &work::ta::V26B123, + FwAbi::V26B123G15S => &work::ta::V26B123_G15S, + } + } + + /// The FS work. + pub(crate) const fn fs(self) -> &'static work::fs::Layout { + match self { + FwAbi::V25G83 => &work::fs::V25G83, + FwAbi::V26B123 => &work::fs::V26B123, + FwAbi::V26B123G15S => &work::fs::V26B123_G15S, + } + } + + /// The compute work. + pub(crate) const fn compute(self) -> &'static work::compute::Layout { + match self { + FwAbi::V25G83 => &work::compute::V25G83, + FwAbi::V26B123 => &work::compute::V26B123, + FwAbi::V26B123G15S => &work::compute::V26B123_G15S, + } + } +} diff --git a/drivers/gpu/drm/asahi/g16/fw/work.rs b/drivers/gpu/drm/asahi/g16/fw/work.rs index ef54552540d7b5..2b8c74edd3c556 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work.rs @@ -5,6 +5,11 @@ //! Render records use 66 TA and 82 FS register records, 0x4c-byte //! timestamp commands and 0x40-byte dependencies. Each register is an //! unaligned little-endian `(u32 selector, u64 value)` pair. +//! +//! Each work type's `Layout` holds what moves between firmware ABIs: 26B123 widens the +//! per-work binding generation from 1 to 8 bytes at the same offset, shifting later fixed +//! fields by 7 bytes and leaving the 16-byte span between the completion target and the +//! auxiliary target zeroed by the host. /// Microsequence opcodes. pub(crate) mod op { @@ -60,6 +65,11 @@ pub(crate) mod compute; /// TA work image and microsequence. pub(crate) mod ta { pub(crate) const WORK_SIZE: usize = 0x940; + /// Active non-zero head (`0..HEAD_ACTIVE_SIZE`) and tail (`TAIL_ACTIVE_START..WORK_SIZE`) + /// spans of a TA work image (up to 74 G15S register records plus two optional SCS records). + /// The intervening zero gap is cleared on full scrubs and skipped on clean same-VM reuse. + pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x3e0; + pub(crate) const TAIL_ACTIVE_START: usize = 0x740; pub(crate) const SEQ_SIZE: usize = 0x300; pub(crate) const SEQ_OBJECT: usize = 0x1000; pub(crate) const REGS: usize = 0x40; @@ -70,6 +80,79 @@ pub(crate) mod ta { pub(crate) const TS_END: usize = 0x21c; pub(crate) const FINALIZE: usize = 0x268; pub(crate) const END: usize = 0x2fc; + /// u32 of the StartTA command: nonzero when the stage's register list enables SCS + /// (`compute::START_SCS`). + pub(crate) const START_SCS: usize = 0x60; + /// The binding generation. + pub(crate) const GENERATION: usize = 0x917; + + /// Hardware register list profile for TA work. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum RegProfile { + G16G, + G15S, + } + + /// TA work fields that move between firmware ABIs. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct Layout { + /// Width of the binding generation at [`GENERATION`]. + pub(crate) generation_bytes: usize, + /// Target of the finalize record's +0x85 pointer. + pub(crate) completion: usize, + /// Target of the timestamp records' +0x2c ("auxiliary") pointer. + pub(crate) auxiliary: usize, + /// Register-list profile. + pub(crate) profile: RegProfile, + /// Whether TA `+0x760` carries the client TPC GVA (`true`, G15S) or firmware VA + /// (`false`, G16G). + pub(crate) tpc_is_gva: bool, + /// Whether the inline UMA record ends with the extra engine byte at `+0x34`. + pub(crate) inline_uma_engine_byte: bool, + /// Byte at TA finalize `+0x8d`. + pub(crate) finalize_flag: u8, + } + + pub(crate) const V25G83: Layout = Layout { + generation_bytes: 1, + completion: 0x918, + auxiliary: 0x928, + profile: RegProfile::G16G, + tpc_is_gva: false, + inline_uma_engine_byte: true, + finalize_flag: 1, + }; + + pub(crate) const V26B123: Layout = Layout { + generation_bytes: 8, + completion: 0x91f, + auxiliary: 0x92f, + profile: RegProfile::G16G, + tpc_is_gva: false, + inline_uma_engine_byte: true, + finalize_flag: 1, + }; + + pub(crate) const V26B123_G15S: Layout = Layout { + generation_bytes: 8, + completion: 0x91f, + auxiliary: 0x92f, + profile: RegProfile::G15S, + tpc_is_gva: true, + inline_uma_engine_byte: false, + finalize_flag: 0, + }; + + const fn valid(l: &Layout) -> bool { + l.completion == GENERATION + l.generation_bytes + && l.auxiliary == l.completion + 0x10 + && l.auxiliary + 8 <= WORK_SIZE + } + const _: () = assert!(valid(&V25G83) && valid(&V26B123) && valid(&V26B123_G15S)); + const _: () = assert!(REGS + (SEL.len() + 2) * super::REG_RECORD <= HEAD_ACTIVE_SIZE); + const _: () = assert!(REGS + (SEL_G15S.len() + 2) * super::REG_RECORD <= HEAD_ACTIVE_SIZE); + const _: () = assert!(HEAD_ACTIVE_SIZE <= TAIL_ACTIVE_START); + const _: () = assert!(TAIL_ACTIVE_START <= WORK_SIZE); pub(crate) const SEL: [u32; 66] = [ 0x1748, 0x10141, 0x1c039, 0x1c9c8, 0x1c0a1, 0x1c031, 0x1c9c0, 0x1c051, 0x1c061, 0x10149, 0x10139, 0x10111, 0x1c9b0, 0x10119, 0x1c9b8, 0x1c958, 0x1c950, 0x1c930, 0x1c880, 0x1c079, @@ -79,11 +162,26 @@ pub(crate) mod ta { 0x1a0c9, 0x1a0d1, 0x101c9, 0xd471, 0x1a0f1, 0x10799, 0x1c830, 0x1ca30, 0x16c39, 0x1c910, 0xa5a1, 0xd419, 0x1ca10, 0x14a1, 0xa349, 0x10061, ]; + pub(crate) const SEL_G15S: [u32; 74] = [ + 0x10141, 0x1c039, 0x1c9c8, 0x1c041, 0x1c9d0, 0x1c0a1, 0x1c031, 0x1c9c0, 0x1c051, 0x1c061, + 0x10149, 0x10139, 0x10111, 0x1c9b0, 0x10119, 0x1c9b8, 0x1c958, 0x1c950, 0x1c930, 0x1c880, + 0x1c898, 0x1c948, 0x1c888, 0x1c890, 0x1c918, 0x1c079, 0x1c9d8, 0x1c089, 0x1c9e0, 0x16c41, + 0x1ca40, 0x1c9a8, 0x1c920, 0x10151, 0x1c199, 0x1c1a1, 0x1c1a9, 0x1c1b1, 0x1c1b9, 0x1c8f8, + 0x1c0b1, 0x1c850, 0x10131, 0x10121, 0x10129, 0x101b9, 0x1c069, 0x1c071, 0x1c081, 0x1c0a9, + 0x10171, 0x10169, 0x12099, 0x101e1, 0x1c9e8, 0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, + 0x1a0d1, 0x101c9, 0xd471, 0x1a0f1, 0x10799, 0xa5a1, 0xd419, 0x1ca10, 0x14a1, 0xa349, + 0x1c830, 0x1ca30, 0x16c39, 0x1c910, + ]; } /// FS work image and microsequence. pub(crate) mod fs { pub(crate) const WORK_SIZE: usize = 0xca0; + /// Active non-zero head (`0..HEAD_ACTIVE_SIZE`) and tail (`TAIL_ACTIVE_START..WORK_SIZE`) + /// spans of an FS work image (including two optional SCS register records). The intervening + /// zero gap is cleared on full scrubs and skipped on clean same-VM reuse. + pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x470; + pub(crate) const TAIL_ACTIVE_START: usize = 0x780; pub(crate) const SEQ_SIZE: usize = 0x380; pub(crate) const SEQ_OBJECT: usize = 0x1000; pub(crate) const REGS: usize = 0x80; @@ -92,6 +190,102 @@ pub(crate) mod fs { pub(crate) const TS_END: usize = 0x23c; pub(crate) const FINALIZE: usize = 0x288; pub(crate) const END: usize = 0x344; + /// u32 of the StartFS command: nonzero when the stage's register list enables SCS + /// (`compute::START_SCS`). + pub(crate) const START_SCS: usize = 0x78; + /// The binding generation. + pub(crate) const GENERATION: usize = 0xc5f; + + /// Hardware register list and work-header profile for FS work. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum RegProfile { + G16G, + G15S, + } + + /// FS work fields that move between firmware ABIs. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct Layout { + /// Width of the binding generation at [`GENERATION`]. + pub(crate) generation_bytes: usize, + /// Target of the finalize record's +0xa5 pointer. + pub(crate) completion: usize, + /// Target of the timestamp records' +0x2c ("auxiliary") pointer. + pub(crate) auxiliary: usize, + /// u8 flag the host sets to 1. + pub(crate) flag: usize, + /// Register-list and header profile. + pub(crate) profile: RegProfile, + /// Microsequence length advertised in FS work `+0x1c`. + pub(crate) seq_size: usize, + /// Scene offset written to StartFS `+0x34`. + pub(crate) scene_field_off: u64, + /// Whether the inline UMA record ends with the extra engine byte at `+0x34`. + pub(crate) inline_uma_engine_byte: bool, + /// Start timestamp record offset in the FS microsequence. + pub(crate) ts_start: usize, + /// Finalize command offset in the FS microsequence. + pub(crate) finalize: usize, + /// Whether FS finalize packs the event directly at `+0xad` with `END` at `+0xb4` (G15S), + /// rather than G16G's `+0xad/+0xb1/+0xb2` + `END` at `+0xbc`. + pub(crate) compact_finalize: bool, + } + + pub(crate) const V25G83: Layout = Layout { + generation_bytes: 1, + completion: 0xc60, + auxiliary: 0xc70, + flag: 0xc84, + profile: RegProfile::G16G, + seq_size: SEQ_SIZE, + scene_field_off: 0x54, + inline_uma_engine_byte: true, + ts_start: TS_START, + finalize: FINALIZE, + compact_finalize: false, + }; + + pub(crate) const V26B123: Layout = Layout { + generation_bytes: 8, + completion: 0xc67, + auxiliary: 0xc77, + flag: 0xc8b, + profile: RegProfile::G16G, + seq_size: SEQ_SIZE, + scene_field_off: 0x54, + inline_uma_engine_byte: true, + ts_start: TS_START, + finalize: FINALIZE, + compact_finalize: false, + }; + + pub(crate) const V26B123_G15S: Layout = Layout { + generation_bytes: 8, + completion: 0xc67, + auxiliary: 0xc77, + flag: 0xc8b, + profile: RegProfile::G15S, + seq_size: 0x340, + scene_field_off: 0x4c, + inline_uma_engine_byte: false, + ts_start: 0x1e4, + finalize: 0x280, + compact_finalize: true, + }; + + const fn valid(l: &Layout) -> bool { + l.completion == GENERATION + l.generation_bytes + && l.auxiliary == l.completion + 0x10 + && l.flag == l.completion + 0x24 + && l.flag < WORK_SIZE + && l.seq_size <= SEQ_SIZE + && l.finalize + if l.compact_finalize { 0xb8 } else { 0xc0 } <= l.seq_size + } + const _: () = assert!(valid(&V25G83) && valid(&V26B123) && valid(&V26B123_G15S)); + const _: () = assert!(REGS + (SEL.len() + 2) * super::REG_RECORD <= HEAD_ACTIVE_SIZE); + const _: () = assert!(REGS + (SEL_G15S.len() + 2) * super::REG_RECORD <= HEAD_ACTIVE_SIZE); + const _: () = assert!(HEAD_ACTIVE_SIZE <= TAIL_ACTIVE_START); + const _: () = assert!(TAIL_ACTIVE_START <= WORK_SIZE); pub(crate) const SEL: [u32; 82] = [ 0x1739, 0x10009, 0x15379, 0x15381, 0x15369, 0x15371, 0x15131, 0x15139, 0x100a1, 0x15069, 0x15071, 0x16058, 0x10019, 0x100b1, 0x16030, 0x100d9, 0xa301, 0x10791, 0x16098, 0x15109, @@ -103,6 +297,17 @@ pub(crate) mod fs { 0x1a0e1, 0x101c1, 0xd469, 0x1a0f9, 0xa5a9, 0xd429, 0x160e0, 0x1499, 0xa341, 0x1c838, 0x1ca28, 0x10069, ]; + pub(crate) const SEL_G15S: [u32; 82] = [ + 0x1739, 0x10009, 0x15379, 0x15381, 0x15369, 0x15371, 0x15131, 0x15139, 0x100a1, 0x15069, + 0x15071, 0x16058, 0x10019, 0x100b1, 0x16030, 0x100d9, 0x10791, 0x16098, 0x15109, 0x15101, + 0x15021, 0x15211, 0x15049, 0x10051, 0x15321, 0x15301, 0x15309, 0x15311, 0x15319, 0x15349, + 0x15351, 0x15329, 0x15331, 0x15339, 0x15341, 0x15231, 0x15221, 0x15239, 0x15229, 0x15401, + 0x15421, 0x15409, 0x15429, 0x153c1, 0x15411, 0x153c9, 0x15431, 0x153d1, 0x15419, 0x153d9, + 0x15439, 0x16429, 0x16060, 0x16431, 0x10039, 0x16020, 0x16451, 0x15359, 0x100b8, 0x16461, + 0x16090, 0x120a1, 0x101e9, 0x160a8, 0x16068, 0x160b8, 0x1a0a9, 0x1a0b1, 0x1a079, 0x1a081, + 0x1a0d9, 0x1a0e1, 0x101c1, 0xd469, 0x1a0f9, 0x1c838, 0x1ca28, 0xa5a9, 0xd429, 0x160e0, + 0x1499, 0xa341, + ]; pub(crate) const MAX_END_COPIES: usize = 8; pub(crate) const SEQ_CAPACITY: usize = SEQ_SIZE + MAX_END_COPIES * super::ts_record::SIZE; } @@ -137,4 +342,8 @@ pub(crate) mod initbm { /// Per-pass scene including UMA results and embedded prefix records. pub(crate) mod scene { pub(crate) const SIZE: usize = 0x4000; + /// Active prefix of a render scene touched by the host or firmware (`0x000..0x780`, + /// rounded up to 2 KiB). Full pass scrubs zero the entire `SIZE`; clean same-VM reuse only + /// rewrites `0..ACTIVE_SIZE`. + pub(crate) const ACTIVE_SIZE: usize = 0x800; } diff --git a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs index d7d9b40438b2e8..33b0f56a070456 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs @@ -3,6 +3,16 @@ //! J713/G16G 25G83 compute packet layout. All offsets are bytes. pub(crate) const WORK_SIZE: usize = 0x2000; +/// Active head span of a compute work image: header (`0x00..0x18`) plus up to 29 register +/// records (`0x20..0x17c`, including optional 0x12091, USC base and RT/SCS records), 16-byte +/// aligned. Bytes between `HEAD_ACTIVE_SIZE` and `BODY_ACTIVE_START` remain zeroed after a full +/// write. +pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x180; +/// First active body byte of a compute work image (`work_gva + 0x20` pointer at `0x720`). +pub(crate) const BODY_ACTIVE_START: usize = 0x720; +/// Exclusive end of the active body span of a compute work image (`0xf00..0xf08` tail). +/// Bytes `BODY_ACTIVE_END..WORK_SIZE` remain zeroed after a full write. +pub(crate) const BODY_ACTIVE_END: usize = 0xf08; pub(crate) const SEQ_SIZE: usize = 0x300; pub(crate) const SEQ_OBJECT: usize = 0x1000; pub(crate) const REGS: usize = 0x20; @@ -27,7 +37,119 @@ pub(crate) const CONTEXT_STORE_SIZE: usize = 0x40000; pub(crate) const POOL_SIZE: usize = 0x2000000; pub(crate) const POOL_STATE_SIZE: usize = 0x20000; pub(crate) const PAGE_LIST_SIZE: usize = 0x4000; +/// u32 of the StartCompute command: nonzero when the work's register list enables shader-context +/// scratch (SCS). The firmware then records the work's slot as an SCS user, appends +/// `0x017d9 = 1` to the kick's register list, and keeps the SCS state (`0x017e0`, the compute +/// and TA windows) through its idle teardown while the slot is busy. +pub(crate) const START_SCS: usize = 0x40; pub(crate) const EVENT: u32 = 15; +/// Firmware completion events for concurrent compute pipes `0..COMPUTE_PIPES`. +/// All events reside in type-1 event word 1 (`15..32`) so event draining reads only words 1 and 4. +pub(crate) const EVENTS: [u32; 8] = [EVENT, 16, 17, 18, 19, 20, 21, 22]; + +/// Resolves a firmware compute completion event back to its compute pipe index (`0..EVENTS.len()`). +pub(crate) const fn pipe_of_event(event: u32) -> Option { + if event >= EVENT && (event - EVENT) < EVENTS.len() as u32 { + Some((event - EVENT) as usize) + } else { + None + } +} +/// The binding generation. +pub(crate) const GENERATION: usize = 0x88b; + +/// Compute work fields that move between firmware ABIs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Layout { + /// Width of the binding generation at [`GENERATION`]. + pub(crate) generation_bytes: usize, + /// Target of the finalize record's +0x71 pointer. + pub(crate) completion: usize, + /// Target of the timestamp records' +0x2c ("auxiliary") pointer. + pub(crate) auxiliary: usize, + /// u32 target of the start record's +0x1a8 and the finalize record's +0x69 pointers. + pub(crate) target: usize, + /// Bytes of the work the firmware caches; the host's private parts lie beyond them. + pub(crate) cached: usize, + /// Optional `(start, end)` u64 tick offsets inside the work object when the firmware writes + /// compute GPU timestamps into work rather than the unit's ITS pair. + pub(crate) work_ticks: Option<(usize, usize)>, + /// Offset of the four preemption saved-state pointers (`0x1a4d0..0x1a4e8`) in the + /// preemption buffer. + pub(crate) preempt_tail: u64, + /// Whether to emit G15 register `0x12091 = 0x1c` immediately before `0x101d9`. + pub(crate) has_reg_12091: bool, + /// Whether to emit HAL200 USC-base register `0x10071`. + pub(crate) has_usc_base_reg: bool, + /// Four sub-offsets inside `context_store_gva` written at `StartCompute +0x188..+0x1a0`. + pub(crate) context_store_offsets: [u64; 4], + /// Pool threshold words written at compute work `+0x873` and `+0x87b`. + pub(crate) pool_words: [u64; 2], +} + +pub(crate) const V25G83: Layout = Layout { + generation_bytes: 1, + completion: 0x88c, + auxiliary: 0x89c, + target: 0x8ac, + cached: 0x8c0, + work_ticks: None, + preempt_tail: 0x1480, + has_reg_12091: false, + has_usc_base_reg: true, + context_store_offsets: [0, 0xf400, 0x1e800, 0x1f000], + pool_words: [0x1588000, 0xef8000], +}; + +pub(crate) const V26B123: Layout = Layout { + generation_bytes: 8, + completion: 0x893, + auxiliary: 0x8a3, + target: 0x8b3, + cached: 0x8e0, + work_ticks: Some((0x7ec, 0x7f4)), + preempt_tail: 0x1480, + has_reg_12091: false, + has_usc_base_reg: true, + context_store_offsets: [0, 0xf400, 0x1e800, 0x1f000], + pool_words: [0x1588000, 0xef8000], +}; + +pub(crate) const V26B123_G15S: Layout = Layout { + generation_bytes: 8, + completion: 0x893, + auxiliary: 0x8a3, + target: 0x8b3, + cached: 0x8e0, + work_ticks: Some((0x7ec, 0x7f4)), + preempt_tail: 0x1b80, + has_reg_12091: true, + has_usc_base_reg: false, + context_store_offsets: [0, 0x1e400, 0x3c800, 0x3d800], + pool_words: [0x31cc000, 0x2308000], +}; + +const fn valid(l: &Layout) -> bool { + l.completion == GENERATION + l.generation_bytes + && l.auxiliary == l.completion + 0x10 + && l.target == l.completion + 0x20 + && l.target + 4 <= l.cached + && l.cached <= SEQ_EMBEDDED + && SEQ_EMBEDDED + SEQ_SIZE <= NOTIFIER + && l.preempt_tail + 0x20 <= PREEMPT_SIZE as u64 + && l.context_store_offsets[3] + 0x1000 <= CONTEXT_STORE_SIZE as u64 +} +const _: () = assert!( + valid(&V25G83) + && valid(&V26B123) + && valid(&V26B123_G15S) + && REGS + (SEL.len() + 5) * 12 <= HEAD_ACTIVE_SIZE + && HEAD_ACTIVE_SIZE <= BODY_ACTIVE_START + && BODY_ACTIVE_START <= GENERATION + && DESCRIPTOR + DESCRIPTOR_SIZE <= BODY_ACTIVE_END + && 0xf08 <= BODY_ACTIVE_END + && BODY_ACTIVE_END <= WORK_SIZE +); pub(crate) const SEL: [u32; 24] = [ 0x1a510, 0x1a420, 0x1a4d0, 0x1a4d8, 0x1a4e0, 0x1a4e8, 0x1a440, 0x1a458, 0x101d9, 0x1a089, diff --git a/drivers/gpu/drm/asahi/g16/gate.rs b/drivers/gpu/drm/asahi/g16/gate.rs index 0de0aeb5bfdc0e..5010ab46dc97c8 100644 --- a/drivers/gpu/drm/asahi/g16/gate.rs +++ b/drivers/gpu/drm/asahi/g16/gate.rs @@ -17,10 +17,15 @@ use core::sync::atomic::{AtomicU32, Ordering}; use kernel::prelude::*; -use super::{command::cover, command::USC_WINDOW, params}; +use super::{ + command::{cover_locked, SpanProof, USC_WINDOW}, + params, +}; use crate::mmu; const VDM_ROOT: u32 = 0x21000960; +/// USC cache invalidate bit of the VDM root barrier (DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE). +const VDM_ROOT_USC_INVAL: u32 = 0x8; const CDM_TERMINATE: u32 = 0x40000000; const CDM_BARRIERS: [u32; 4] = [0x60000160, 0x600215fe, 0x60001560, 0x600201fe]; const CDM_LINK: u32 = 0x20000000; @@ -57,20 +62,33 @@ struct Window { impl Window { /// The `count` words at `va`, reading whole spans of up to 256 bytes (not past the page - /// unless the record crosses it). Unreadable memory: EFAULT. - fn words(&mut self, vm: &mmu::Vm, va: u64, count: usize) -> Result<[u32; 10]> { + /// or an optional root-stream `limit` unless the record crosses it) under an already-held + /// VM read lock. Unreadable memory: EFAULT. + fn words( + &mut self, + guard: &mut mmu::VmReadGuard<'_>, + epoch: Option, + proof: Option<&mut SpanProof>, + va: u64, + count: usize, + limit: Option, + ) -> Result<[u32; 10]> { let n = count.checked_mul(4).filter(|&n| n <= 40).ok_or(EINVAL)?; - cover(vm, va, va.checked_add(n as u64).ok_or(EINVAL)?, true, false)?; - let cached = self.len != 0 - && va >= self.va - && va - .checked_add(n as u64) - .is_some_and(|end| end <= self.va + self.len as u64); + let end = va.checked_add(n as u64).ok_or(EINVAL)?; + let cached = self.len != 0 && va >= self.va && end <= self.va + self.len as u64; if !cached { let in_page = mmu::UAT_PGSZ - (va as usize & mmu::UAT_PGMSK); - let len = n.max(self.bytes.len().min(in_page)); + let mut max_len = self.bytes.len().min(in_page); + if let Some(limit_va) = limit { + let rem = usize::try_from(limit_va.saturating_sub(va)).unwrap_or(usize::MAX); + max_len = max_len.min(rem); + } + let len = n.max(max_len); + let cover_end = va.checked_add(len as u64).ok_or(EINVAL)?; + cover_locked(guard, epoch, proof, va, cover_end, true, false)?; self.len = 0; - vm.read_user(va, &mut self.bytes[..len]) + guard + .read_user(va, &mut self.bytes[..len]) .map_err(|_| EFAULT)?; self.va = va; self.len = len; @@ -89,7 +107,14 @@ impl Window { /// A launch's program: inside the queue's 4 GiB USC window, 64-aligned, first block readable. /// `checked` caches the last proven program page. -fn program(vm: &mmu::Vm, usc: u64, address: u64, checked: &mut Option) -> Result { +fn program( + guard: &mut mmu::VmReadGuard<'_>, + epoch: Option, + proof: Option<&mut SpanProof>, + usc: u64, + address: u64, + checked: &mut Option, +) -> Result { if address < usc || address - usc >= USC_WINDOW || address & 63 != 0 { return Err(EINVAL); } @@ -98,31 +123,62 @@ fn program(vm: &mmu::Vm, usc: u64, address: u64, checked: &mut Option) -> R if *checked == Some(page) { return Ok(()); } - cover(vm, address, address + 64, true, false)?; + cover_locked(guard, epoch, proof, address, address + 64, true, false)?; *checked = Some(page); Ok(()) } -/// VDM admission: a normal root stream opens with exactly the G16 barrier. -pub(crate) fn vdm(vm: &mmu::Vm, va: u64) -> Result { - if !params::stream_gate() { +/// VDM admission for a batch of root streams under an already-held VM read lock. +/// Each root stream opens with the G16 barrier, with or without the USC cache invalidate. +/// Reads only the 4-byte root word for a single pass to minimize PoC cache maintenance, +/// and caches up to 256 intra-page bytes across multi-pass batches. Each normal root stream +/// opens with the G16 barrier, with or without the USC cache invalidate. +pub(crate) fn vdm_batch_locked(guard: &mut mmu::VmReadGuard<'_>, vas: &[u64]) -> Result { + if vas.is_empty() || !params::stream_gate() { return Ok(()); } - let mut bytes = [0u8; 4]; - vm.read_user(va, &mut bytes).map_err(|_| EFAULT)?; - let word = u32::from_le_bytes(bytes); - if word != VDM_ROOT { - return Err(reject("VDM root", va, &[word])); + let mut win_va = 0u64; + let mut win_len = 0usize; + let mut buf = [0u8; 256]; + let max_read = if vas.len() == 1 { 4 } else { buf.len() }; + for &va in vas { + let end = va.checked_add(4).ok_or(EINVAL)?; + let cached = win_len != 0 && va >= win_va && end <= win_va + win_len as u64; + if !cached { + let in_page = mmu::UAT_PGSZ - (va as usize & mmu::UAT_PGMSK); + let len = max_read.min(in_page); + if len < 4 { + return Err(EINVAL); + } + guard.read_user(va, &mut buf[..len]).map_err(|_| EFAULT)?; + win_va = va; + win_len = len; + } + let off = (va - win_va) as usize; + let word = u32::from_le_bytes([buf[off], buf[off + 1], buf[off + 2], buf[off + 3]]); + if word & !VDM_ROOT_USC_INVAL != VDM_ROOT { + return Err(reject("VDM root", va, &[word])); + } } Ok(()) } -/// CDM admission: walks the root and no-return linked streams to TERMINATE. +/// CDM admission: walks the root and no-return linked streams to TERMINATE under an optional +/// caller-held VM read lock, sharing both the lock and epoch-validated [`SpanProof`] across +/// span checks and stream gates. /// All requested bytes are proven readable; the root cannot end inside a record. /// Mode 0 has six inline grid words, mode 1 three inline local-size words and /// an indirect global grid, mode 2 an indirect six-word grid. The remaining /// launch-template payload words stay opaque, as in Mesa's raw AGX3 decoder. -pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { +pub(crate) fn cdm_locked<'a>( + vm: &'a mmu::Vm, + guard: &mut Option>, + epoch: &mut Option, + usc: u64, + base: u64, + end: u64, + mut proof: Option<&mut SpanProof>, +) -> Result { if !params::stream_gate() { return Ok(()); } @@ -144,7 +200,13 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { let mut distance = 0u64; let mut power = 1u64; let mut first = true; - let mut resched = 0; + // A caller that already holds `guard` checked signals before locking; reuse the + // held guard for the first window of records instead of dropping it on record 0. + let mut resched = if guard.is_some() { + CDM_RESCHED_RECORDS + } else { + 0 + }; loop { if first { first = false; @@ -160,10 +222,13 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { } } if resched == 0 { - // No VM lock is held between reads. Keep a long userspace stream - // preemptible and allow its submitting task to be interrupted. + // Release the VM lock and clear cached window/program proofs before + // rescheduling so any mapping change while unlocked is re-verified. // might_sleep() includes might_resched() (cond_resched on voluntary kernels). // It is a real scheduling point, not only a debug assertion. + *guard = None; + window.len = 0; + checked = None; kernel::task::might_sleep(); if kernel::current!().signal_pending() { return Err(ERESTARTSYS); @@ -171,14 +236,23 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { resched = CDM_RESCHED_RECORDS; } resched -= 1; + let active_guard = match guard.as_mut() { + Some(active) => active, + None => { + let active = guard.insert(vm.read_lock().map_err(|_| EFAULT)?); + *epoch = active.epoch(); + active + } + }; let root_bytes = |va: u64, bytes: u64| -> Result { if !linked && (va < base || va.checked_add(bytes).is_none_or(|at| at > end)) { return Err(EINVAL); } Ok(()) }; + let limit = (!linked).then_some(end); root_bytes(va, 4)?; - let w = window.words(vm, va, 1)?; + let w = window.words(active_guard, *epoch, proof.as_deref_mut(), va, 1, limit)?; if w[0] == CDM_TERMINATE { return Ok(()); } @@ -198,7 +272,7 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { } if w[0] & 0xffff0000 == CDM_LINK { root_bytes(va, 8)?; - let w = window.words(vm, va, 2)?; + let w = window.words(active_guard, *epoch, proof.as_deref_mut(), va, 2, limit)?; let target = (u64::from(w[0] & 0xffff) << 32) | u64::from(w[1]); if target & 3 != 0 || target == va { return Err(reject("CDM link", va, &w)); @@ -218,9 +292,23 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { _ => return Err(reject("CDM launch mode", va, &w)), }; root_bytes(va, (words * 4) as u64)?; - let w = window.words(vm, va, words)?; + let w = window.words( + active_guard, + *epoch, + proof.as_deref_mut(), + va, + words, + limit, + )?; let address = (u64::from(w[1] >> 22) << 38) | (u64::from(w[2]) << 6); - match program(vm, usc, address, &mut checked) { + match program( + active_guard, + *epoch, + proof.as_deref_mut(), + usc, + address, + &mut checked, + ) { Err(error) if error == EINVAL => return Err(reject("CDM program", va, &w)), result => result?, } @@ -240,8 +328,10 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { if indirect & 3 != 0 { return Err(reject("CDM indirect parameters", va, &w)); } - cover( - vm, + cover_locked( + active_guard, + *epoch, + proof.as_deref_mut(), indirect, indirect.checked_add(bytes).ok_or(EINVAL)?, true, diff --git a/drivers/gpu/drm/asahi/g16/glue.c b/drivers/gpu/drm/asahi/g16/glue.c index 368b56149acc78..583dbc61d78f8d 100644 --- a/drivers/gpu/drm/asahi/g16/glue.c +++ b/drivers/gpu/drm/asahi/g16/glue.c @@ -4,11 +4,14 @@ * and macros. The module pin is retain.c's. Built only with CONFIG_DRM_ASAHI_G16. */ #include +#include #include #include #include #include #include +#include +#include #include #include #include @@ -18,24 +21,46 @@ #include #include #include +#include #include #include #include #include #include #include +#include + +#include "glue.h" bool asahi_g16_board(void); -int asahi_g16_display_prepare(struct device *dev); int asahi_g16_hold_power(struct device *dev); bool asahi_g16_ram_disjoint(u64 start, u64 size); void __iomem *asahi_g16_ioremap_wc(u64 start, size_t size); bool asahi_g16_dma_unsupported(struct device *dev); /* Thermal-framework callbacks only publish requests. The Rust GPU owner - * samples the PMP provider and shared cooling policy under its device mutex; - * thermal callbacks never enter the GPU lock. + * samples the PMP provider (when apple,pmp is present) or cached SoC die + * thermal-zone readings (otherwise) under its device mutex; thermal callbacks + * never enter the GPU lock and SMC/zone polling runs outside it. */ +#define ASAHI_G16_ZONE_POLL_FAST_MS 250 +#define ASAHI_G16_ZONE_POLL_IDLE_MS 1000 +#define ASAHI_G16_ZONE_STALE_NS 3000000000ULL + +static const char * const asahi_g16_die_zones[] = { + "macsmc_soc_die", + "apple_pmp_hotspot", +}; + +struct asahi_g16_zone_trips { + long release_mc; + long hot_mc; + long critical_mc; + long max_passive_mc; + bool have_hot; + bool have_critical; +}; + struct asahi_g16_cooling { atomic_t state; struct apple_pmp_gpu *pmp; @@ -45,13 +70,28 @@ struct asahi_g16_cooling { /* The last reading from a sensor that was valid, and when. */ u64 valid_ns; long valid_mc; + /* Cached thermal-zone telemetry when no apple,pmp node is present. */ + spinlock_t zone_lock; + struct delayed_work zone_poll; + atomic_t zone_active; + atomic_t stopping; + u64 zone_seq; + u64 zone_ns; + long zone_mc; + long zone_release_mc; + long zone_hot_mc; + long zone_critical_mc; + bool zone_limits_valid; + int zone_err; }; struct asahi_g16_cooling *asahi_g16_cooling_register(struct device *dev); void asahi_g16_cooling_unregister(struct asahi_g16_cooling *cooling); int asahi_g16_cooling_sample(struct asahi_g16_cooling *cooling, u64 now, bool idle, - long *temperature, u32 *governor, u32 *power, - u32 *backstop); + long *temperature, u32 *governor, u32 *power, + u32 *backstop, u64 *zone_seq, long *release_mc, + long *hot_mc, long *critical_mc, + bool *limits_valid); int asahi_g16_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu **out); void asahi_g16_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active); void asahi_g16_clpc_gpu_put(struct apple_clpc_gpu *gpu); @@ -89,6 +129,132 @@ static const struct thermal_cooling_device_ops asahi_g16_cooling_ops = { .set_cur_state = asahi_g16_cooling_set, }; +static int asahi_g16_zone_trip_cb(struct thermal_trip *trip, void *data) +{ + struct asahi_g16_zone_trips *t = data; + long temp = trip->temperature; + long hyst = trip->hysteresis; + + if (temp == THERMAL_TEMP_INVALID || temp <= 0) + return 0; + + switch (trip->type) { + case THERMAL_TRIP_PASSIVE: + if (temp > t->max_passive_mc) + t->max_passive_mc = temp; + fallthrough; + case THERMAL_TRIP_ACTIVE: + if (!t->have_hot || temp < t->hot_mc) { + t->hot_mc = temp; + t->release_mc = (hyst >= 0 && hyst < temp) ? + temp - hyst : 0; + t->have_hot = true; + } + break; + case THERMAL_TRIP_HOT: + case THERMAL_TRIP_CRITICAL: + if (!t->have_critical || temp < t->critical_mc) { + t->critical_mc = temp; + t->have_critical = true; + } + break; + default: + break; + } + return 0; +} + +static bool asahi_g16_zone_limits_valid(struct asahi_g16_zone_trips *trips) +{ + if (!trips->have_critical && trips->have_hot && + trips->max_passive_mc > trips->hot_mc) { + trips->critical_mc = trips->max_passive_mc; + trips->have_critical = true; + } + return trips->have_hot && trips->have_critical && + trips->release_mc > 0 && trips->release_mc <= trips->hot_mc && + trips->critical_mc > trips->hot_mc; +} + +static void asahi_g16_zone_poll_fn(struct work_struct *work) +{ + struct asahi_g16_cooling *cooling = + container_of(to_delayed_work(work), struct asahi_g16_cooling, + zone_poll); + long hottest = 0; + long release_mc = 0; + long hot_mc = 0; + long critical_mc = 0; + bool found = false; + bool have_limits = false; + bool limits_valid = true; + int ret = -ENODEV; + unsigned int i; + unsigned int delay_ms; + + if (atomic_read(&cooling->stopping)) + return; + + for (i = 0; i < ARRAY_SIZE(asahi_g16_die_zones); i++) { + struct asahi_g16_zone_trips trips = {}; + int temp, err; + + err = thermal_zone_get_temp_and_trips(asahi_g16_die_zones[i], + &temp, asahi_g16_zone_trip_cb, + &trips); + + if (!err) { + if (!found || temp > hottest) + hottest = temp; + found = true; + + if (!asahi_g16_zone_limits_valid(&trips)) { + limits_valid = false; + } else if (!have_limits) { + release_mc = trips.release_mc; + hot_mc = trips.hot_mc; + critical_mc = trips.critical_mc; + have_limits = true; + } else { + release_mc = min(release_mc, trips.release_mc); + hot_mc = min(hot_mc, trips.hot_mc); + critical_mc = min(critical_mc, trips.critical_mc); + } + } else if (err != -ENODEV) { + ret = err; + found = false; + limits_valid = false; + break; + } + } + if (found) + ret = 0; + if (!found || !have_limits || !limits_valid || release_mc <= 0 || + release_mc > hot_mc || critical_mc <= hot_mc) + limits_valid = false; + + spin_lock(&cooling->zone_lock); + cooling->zone_seq++; + cooling->zone_ns = ktime_get_ns(); + cooling->zone_mc = found ? hottest : 0; + cooling->zone_release_mc = limits_valid ? release_mc : 0; + cooling->zone_hot_mc = limits_valid ? hot_mc : 0; + cooling->zone_critical_mc = limits_valid ? critical_mc : 0; + cooling->zone_limits_valid = limits_valid; + cooling->zone_err = ret; + spin_unlock(&cooling->zone_lock); + + if (atomic_read(&cooling->stopping)) + return; + + delay_ms = (ret || !limits_valid || atomic_read(&cooling->zone_active) || + hottest >= release_mc) ? + ASAHI_G16_ZONE_POLL_FAST_MS : + ASAHI_G16_ZONE_POLL_IDLE_MS; + queue_delayed_work(system_freezable_wq, &cooling->zone_poll, + msecs_to_jiffies(delay_ms)); +} + struct asahi_g16_cooling *asahi_g16_cooling_register(struct device *dev) { struct asahi_g16_cooling *cooling; @@ -97,64 +263,139 @@ struct asahi_g16_cooling *asahi_g16_cooling_register(struct device *dev) cooling = kzalloc_obj(*cooling); if (!cooling) return ERR_PTR(-ENOMEM); - atomic_set(&cooling->state, 8); apple_pmp_cooling_init(&cooling->policy); + spin_lock_init(&cooling->zone_lock); + INIT_DELAYED_WORK(&cooling->zone_poll, asahi_g16_zone_poll_fn); + cooling->zone_err = -ENODATA; cooling->pmp_node = of_parse_phandle(dev->of_node, "apple,pmp", 0); - if (!cooling->pmp_node) { - ret = -EINVAL; - goto free; + /* A disabled PMP node never probes, so it provides no telemetry. */ + if (cooling->pmp_node && !of_device_is_available(cooling->pmp_node)) { + of_node_put(cooling->pmp_node); + cooling->pmp_node = NULL; } - cooling->pmp = apple_pmp_gpu_get(dev); - if (IS_ERR(cooling->pmp)) { - ret = PTR_ERR(cooling->pmp); - goto put_node; + if (cooling->pmp_node) { + atomic_set(&cooling->state, 8); + cooling->pmp = apple_pmp_gpu_get(dev); + if (IS_ERR(cooling->pmp)) { + ret = dev_err_probe(dev, PTR_ERR(cooling->pmp), + "PMP telemetry from %pOF unavailable\n", + cooling->pmp_node); + goto put_node; + } + } else { + /* + * Without an available apple,pmp supplier, thermal-zone + * telemetry drives the fail-closed backstop (starting at maximum + * cooling) while the cooling device remains available to thermal + * policy. + */ + atomic_set(&cooling->state, 0); } cooling->cdev = thermal_of_cooling_device_register(dev->of_node, 0, "aurora-g16g", cooling, &asahi_g16_cooling_ops); if (IS_ERR(cooling->cdev)) { ret = PTR_ERR(cooling->cdev); - apple_pmp_gpu_put(cooling->pmp); + if (cooling->pmp) + apple_pmp_gpu_put(cooling->pmp); goto put_node; } + if (!cooling->pmp_node) + queue_delayed_work(system_freezable_wq, &cooling->zone_poll, 0); return cooling; put_node: of_node_put(cooling->pmp_node); -free: kfree(cooling); return ERR_PTR(ret); } void asahi_g16_cooling_unregister(struct asahi_g16_cooling *cooling) { + atomic_set(&cooling->stopping, 1); + if (!cooling->pmp_node) + cancel_delayed_work_sync(&cooling->zone_poll); thermal_cooling_device_unregister(cooling->cdev); - apple_pmp_gpu_put(cooling->pmp); + if (cooling->pmp) + apple_pmp_gpu_put(cooling->pmp); of_node_put(cooling->pmp_node); kfree(cooling); } +bool asahi_g16_cooling_has_pmp(const struct asahi_g16_cooling *cooling) +{ + return cooling->pmp_node != NULL; +} + /* Serialized by the GPU owner. Provider lifetime and MMIO access stay with * PMP: this consumer owns no SRAM mapping and cannot restart its firmware. * An idle GPU samples about twice a second and makes no heat, so with nothing * in flight the last cool reading stands for as long as the sensors stay dark. + * Without apple,pmp, return the latest cached SoC die thermal-zone reading and + * fail closed whenever no fresh reading is available. */ int asahi_g16_cooling_sample(struct asahi_g16_cooling *cooling, u64 now, bool idle, - long *temperature, u32 *governor, u32 *power, - u32 *backstop) + long *temperature, u32 *governor, u32 *power, + u32 *backstop, u64 *zone_seq, long *release_mc, + long *hot_mc, long *critical_mc, + bool *limits_valid) { int ret; *temperature = 0; + *zone_seq = 0; + *release_mc = 0; + *hot_mc = 0; + *critical_mc = 0; + *limits_valid = false; + if (!cooling->pmp_node) { + u64 seq, zone_ns; + long zone_mc, rel, hot, crit; + bool valid; + int zone_err; + + atomic_set(&cooling->zone_active, !idle); + spin_lock(&cooling->zone_lock); + seq = cooling->zone_seq; + zone_ns = cooling->zone_ns; + zone_mc = cooling->zone_mc; + rel = cooling->zone_release_mc; + hot = cooling->zone_hot_mc; + crit = cooling->zone_critical_mc; + valid = cooling->zone_limits_valid; + zone_err = cooling->zone_err; + spin_unlock(&cooling->zone_lock); + + *zone_seq = seq; + if (!zone_ns) + ret = -ENODATA; + else if (zone_err) + ret = zone_err; + else if (now > zone_ns && now - zone_ns > ASAHI_G16_ZONE_STALE_NS) + ret = -ETIMEDOUT; + else { + *temperature = zone_mc; + *release_mc = rel; + *hot_mc = hot; + *critical_mc = crit; + *limits_valid = valid; + ret = 0; + } + *governor = atomic_read(&cooling->state); + *power = 0; + *backstop = 8; + return ret; + } + ret = apple_pmp_telemetry_get_hotspot(cooling->pmp_node, temperature); if (!ret) { cooling->valid_ns = now; cooling->valid_mc = *temperature; - } else if (ret == -ENODATA && cooling->valid_ns && - (idle || now - cooling->valid_ns < APPLE_PMP_GATED_HOLD_NS) && - cooling->valid_mc < APPLE_PMP_GATED_HOLD_MC) { + } else if (ret == -ENODATA && + apple_pmp_hold_nodata(cooling->valid_ns, cooling->valid_mc, + now, idle)) { *temperature = cooling->valid_mc; /* Idle makes no heat: the 2 s with work in flight start with the work. */ - if (idle) + if (idle && cooling->valid_mc < APPLE_PMP_GATED_HOLD_MC) cooling->valid_ns = now; ret = 0; } @@ -200,10 +441,19 @@ int asahi_g16_tvm_enable(struct device *dev) return ret; } -/* Whether this is a qualified J713/T8132 board. */ +/* Whether this T8132 board's retained PMP carries the GPU's AGX vote. */ bool asahi_g16_board(void) { - return apple_pmp_j713_board(); + return apple_pmp_t8132_retained_board(); +} + +/* + * The system counter frequency the boot loader programmed, in Hz: the clock the + * ADT counts GPU power sample periods in. + */ +u32 asahi_g16_timebase_hz(void) +{ + return arch_timer_get_cntfrq(); } /* @@ -212,22 +462,25 @@ bool asahi_g16_board(void) * without one (no internal panel, or none qualified) starts on the boot * framebuffer. */ -int asahi_g16_display_prepare(struct device *dev) +int asahi_g16_display_prepare(struct device *dev, const char *display_compat) { struct device_node *np; bool handed_over; int ret; - np = of_find_compatible_node(NULL, NULL, "apple,t8132-display-subsystem"); + if (!display_compat || !*display_compat) + return -EINVAL; + np = of_find_compatible_node(NULL, NULL, display_compat); handed_over = np && of_device_is_available(np); - of_node_put(np); if (!handed_over) { + of_node_put(np); dev_info_once(dev, "G16: no native display this boot; starting on the boot framebuffer\n"); return 0; } - ret = apple_drm_t8132_link_device(dev); + ret = apple_drm_link_device(dev, np); + of_node_put(np); if (ret == -EPROBE_DEFER) - dev_info_once(dev, "G16: waiting for the T8132 native display to register\n"); + dev_info_once(dev, "G16: waiting for %s to register\n", display_compat); return ret; } diff --git a/drivers/gpu/drm/asahi/g16/glue.h b/drivers/gpu/drm/asahi/g16/glue.h new file mode 100644 index 00000000000000..c5cd057ef405ea --- /dev/null +++ b/drivers/gpu/drm/asahi/g16/glue.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _ASAHI_G16_GLUE_H +#define _ASAHI_G16_GLUE_H + +struct asahi_g16_cooling; +struct device; + +u32 asahi_g16_timebase_hz(void); +bool asahi_g16_cooling_has_pmp(const struct asahi_g16_cooling *cooling); +int asahi_g16_display_prepare(struct device *dev, const char *display_compat); + +#endif /* _ASAHI_G16_GLUE_H */ diff --git a/drivers/gpu/drm/asahi/g16/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index 19405185174d16..b3eaa19d7ee441 100644 --- a/drivers/gpu/drm/asahi/g16/graph.rs +++ b/drivers/gpu/drm/asahi/g16/graph.rs @@ -13,11 +13,20 @@ use kernel::{ use super::channel::Channel; use super::fw::graph::{self, job_list, notifier_page, qinfo, qstate, sched_ctx}; -use super::hw::{pte, sizes, tuning}; -use super::object::{Class, FwObject, Objects, Placement, Request}; +use super::hw::{pte, sizes, tuning, FwAbi}; +use super::object::{Class, Factory, FwObject, Objects, Placement, Request}; use super::Firmware; use crate::driver::AsahiDrmDevice; +/// Firmware-owned queue graph records initialized once before `register_context()`. +/// Firmware reads and writes them through the ASC-cached mapping after initialization; +/// host receipt checks authenticate on NC `qstate::READ` and submit-pipe cursors. +pub(crate) const fn graph_fw() -> Class { + Class::FwCached +} +pub(crate) const fn qinfo_cached() -> bool { + matches!(graph_fw(), Class::FwCached) +} pub(crate) const fn cmd_fw() -> Class { if tuning::FW_CACHED { Class::FwCached @@ -42,7 +51,7 @@ pub(crate) const fn manager_class(class: Class) -> Class { } #[allow(dead_code)] pub(crate) const fn queue_scratch() -> Class { - cmd_fw() + graph_fw() } /// A private client alias uses the working M4 driver's AttrIndex-2 NC policy. @@ -83,6 +92,7 @@ pub(crate) fn alloc( /// Work lists belong to the kernel GPU task. Firmware prepares them through the upper /// mapping and hardware reads the existing lower address; applications get no alias. /// Preserve the established cache classes and wire addresses while separating ownership. +#[allow(dead_code)] pub(crate) fn alloc_work( objects: &mut Objects, size: usize, @@ -117,26 +127,59 @@ pub(crate) struct ComputeGraph { pub(crate) fw_stamp: Arc, } -struct QueueObjects { +struct QueueSession { qinfo: Arc, qstate: Arc, - ring: Arc, user_stamp: Arc, fw_stamp: Arc, } -impl QueueObjects { +impl QueueSession { fn new(o: &mut Objects) -> Result { Ok(Self { - qinfo: alloc(o, qinfo::SIZE, cmd_fw(), None, 0, false)?, + qinfo: alloc(o, qinfo::SIZE, graph_fw(), None, 0, false)?, qstate: alloc(o, qstate::SIZE, Class::Fw, None, 0, false)?, - ring: alloc(o, sizes::QUEUE_CAP as usize * 8, cmd_fw(), None, 0, false)?, user_stamp: alloc(o, 8, Class::Shared, None, 0, false)?, fw_stamp: alloc(o, 8, Class::Shared, None, 0, false)?, }) } + /// Completes the queue with its firmware-cached work ring from a device-lifetime + /// [`Factory::persistent_objects`] allocator. The host only writes 64-bit work/barrier VAs + /// into the ring before advancing the uncached `qstate::WRITE` producer and never reads + /// back firmware writes, matching macOS 26B123's `0x443` command-ring mapping. + fn finish(self, rings: &mut Objects) -> Result { + Ok(QueueObjects { + qinfo: self.qinfo, + qstate: self.qstate, + ring: alloc( + rings, + sizes::QUEUE_CAP as usize * 8, + Class::FwCoherent, + None, + 0, + false, + )?, + user_stamp: self.user_stamp, + fw_stamp: self.fw_stamp, + }) + } +} + +struct QueueObjects { + qinfo: Arc, + qstate: Arc, + ring: Arc, + user_stamp: Arc, + fw_stamp: Arc, +} +impl QueueObjects { + #[allow(dead_code)] + fn new(o: &mut Objects, rings: &mut Objects) -> Result { + QueueSession::new(o)?.finish(rings) + } } fn init_queue( + abi: FwAbi, q: &FwObject, state: &FwObject, ring: &FwObject, @@ -145,7 +188,7 @@ fn init_queue( ) -> Result { q.write( 0, - &graph::queue_image(state.va, ring.va, list.va, q.va, context.va), + &graph::queue_image_for(abi.qinfo(), state.va, ring.va, list.va, q.va, context.va), )?; state.w32(qstate::CAP, sizes::QUEUE_CAP) } @@ -163,14 +206,30 @@ fn init_notifier(page: &FwObject, threshold: &FwObject) -> Result { Ok(()) } -impl ComputeGraph { - fn new(o: &mut Objects) -> Result { - let q = QueueObjects::new(o)?; +struct ComputeGraphSession { + sched_ctx: Arc, + notifier: Arc, + threshold: Arc, + job_list: Arc, + q: QueueSession, +} +impl ComputeGraphSession { + fn new(o: &mut Objects, sched_ctx: Arc) -> Result { Ok(Self { - sched_ctx: alloc(o, sched_ctx::SIZE, cmd_fw(), None, 0, false)?, + sched_ctx, notifier: alloc(o, 0x1000, Class::Fw, None, 0, false)?, threshold: alloc(o, 24, Class::Fw, None, 0, false)?, - job_list: alloc(o, job_list::SIZE, cmd_fw(), None, 0, false)?, + job_list: alloc(o, job_list::SIZE, graph_fw(), None, 0, false)?, + q: QueueSession::new(o)?, + }) + } + fn finish(self, rings: &mut Objects) -> Result { + let q = self.q.finish(rings)?; + Ok(ComputeGraph { + sched_ctx: self.sched_ctx, + notifier: self.notifier, + threshold: self.threshold, + job_list: self.job_list, qscratch: q.qinfo.clone(), qinfo: q.qinfo, qstate: q.qstate, @@ -179,13 +238,23 @@ impl ComputeGraph { fw_stamp: q.fw_stamp, }) } - fn init(&self) -> Result { - self.sched_ctx.write(0, &graph::context_image())?; +} + +impl ComputeGraph { + #[allow(dead_code)] + fn new(o: &mut Objects, rings: &mut Objects, sched_ctx: Arc) -> Result { + ComputeGraphSession::new(o, sched_ctx)?.finish(rings) + } + fn init(&self, abi: FwAbi, init_ctx: bool) -> Result { + if init_ctx { + self.sched_ctx.write(0, &graph::context_image())?; + } init_notifier(&self.notifier, &self.threshold)?; self.notifier .w64(notifier_page::COMPUTE_RECORD, self.threshold.va)?; self.job_list.w64(job_list::SELF, self.job_list.va)?; init_queue( + abi, &self.qinfo, &self.qstate, &self.ring, @@ -213,22 +282,27 @@ pub(crate) struct RenderGraph { pub(crate) legacy_empty: Arc, pub(crate) registration_barrier: Arc, } -impl RenderGraph { +struct RenderGraphSession { + ta: QueueSession, + fs: QueueSession, + sched_ctx: Arc, + notifier: Arc, + threshold: Arc, + job_list: [Arc; 2], + legacy_empty: Arc, + registration_barrier: Arc, +} +impl RenderGraphSession { fn new(o: &mut Objects, context: Arc) -> Result { - let [ta, fs] = [QueueObjects::new(o)?, QueueObjects::new(o)?]; Ok(Self { - qscratch: [ta.qinfo.clone(), fs.qinfo.clone()], - qinfo: [ta.qinfo, fs.qinfo], - qstate: [ta.qstate, fs.qstate], - ring: [ta.ring, fs.ring], - user_stamp: [ta.user_stamp, fs.user_stamp], - fw_stamp: [ta.fw_stamp, fs.fw_stamp], + ta: QueueSession::new(o)?, + fs: QueueSession::new(o)?, sched_ctx: context, notifier: alloc(o, 0x1000, Class::Fw, None, 0, false)?, threshold: alloc(o, 24, Class::Fw, None, 0, false)?, job_list: [ - alloc(o, job_list::SIZE, cmd_fw(), None, 0, false)?, - alloc(o, job_list::SIZE, cmd_fw(), None, 0, false)?, + alloc(o, job_list::SIZE, graph_fw(), None, 0, false)?, + alloc(o, job_list::SIZE, graph_fw(), None, 0, false)?, ], legacy_empty: alloc(o, 0x40, Class::Shared, None, 0, false)?, registration_barrier: alloc( @@ -241,11 +315,36 @@ impl RenderGraph { )?, }) } - fn init(&self) -> Result { + fn finish(self, rings: &mut Objects) -> Result { + let [ta, fs] = [self.ta.finish(rings)?, self.fs.finish(rings)?]; + Ok(RenderGraph { + qscratch: [ta.qinfo.clone(), fs.qinfo.clone()], + qinfo: [ta.qinfo, fs.qinfo], + qstate: [ta.qstate, fs.qstate], + ring: [ta.ring, fs.ring], + user_stamp: [ta.user_stamp, fs.user_stamp], + fw_stamp: [ta.fw_stamp, fs.fw_stamp], + sched_ctx: self.sched_ctx, + notifier: self.notifier, + threshold: self.threshold, + job_list: self.job_list, + legacy_empty: self.legacy_empty, + registration_barrier: self.registration_barrier, + }) + } +} + +impl RenderGraph { + #[allow(dead_code)] + fn new(o: &mut Objects, rings: &mut Objects, context: Arc) -> Result { + RenderGraphSession::new(o, context)?.finish(rings) + } + fn init(&self, abi: FwAbi) -> Result { init_notifier(&self.notifier, &self.threshold)?; for e in 0..2 { self.job_list[e].w64(job_list::SELF, self.job_list[e].va)?; init_queue( + abi, &self.qinfo[e], &self.qstate[e], &self.ring[e], @@ -258,31 +357,69 @@ impl RenderGraph { } } +/// Session-side queue graph allocations before sealing the session allocator and attaching +/// the firmware-cached work rings from a probe-time device-lifetime +/// [`Factory::persistent_objects_probe`] pool. +pub(crate) struct GraphSession { + compute: KVec, + render: RenderGraphSession, +} + pub(crate) struct Graphs { pub(crate) dev: ARef, - pub(crate) compute: ComputeGraph, + pub(crate) compute: KVec, pub(crate) render: RenderGraph, + /// Owns the firmware-cached work rings for the device lifetime (never dropped). + _ring_objects: core::mem::ManuallyDrop, } impl Graphs { - pub(crate) fn new(dev: &AsahiDrmDevice, o: &mut Objects) -> Result { - let compute = ComputeGraph::new(o)?; - let render = RenderGraph::new(o, compute.sched_ctx.clone())?; + #[inline(never)] + pub(crate) fn prepare(o: &mut Objects) -> Result { + // Host polls sched_ctx from WC during register_context(); keep uncached and share one + // scheduling context across all compute pipes and the render graph. + let sched_ctx = alloc(o, sched_ctx::SIZE, Class::Fw, None, 0, false)?; + let mut compute = KVec::with_capacity(sizes::COMPUTE_PIPES, GFP_KERNEL)?; + for _ in 0..sizes::COMPUTE_PIPES { + compute.push(ComputeGraphSession::new(o, sched_ctx.clone())?, GFP_KERNEL)?; + } + let render = RenderGraphSession::new(o, sched_ctx)?; + Ok(GraphSession { compute, render }) + } + + #[inline(never)] + pub(crate) fn finish( + dev: &AsahiDrmDevice, + session: GraphSession, + factory: &Factory, + ) -> Result { + // Never dropped even on partial failure: ASC-cached mappings have no qualified teardown. + let mut ring_objects = core::mem::ManuallyDrop::new(factory.persistent_objects_probe()); + let mut compute = KVec::with_capacity(sizes::COMPUTE_PIPES, GFP_KERNEL)?; + for c in session.compute { + compute.push(c.finish(&mut ring_objects)?, GFP_KERNEL)?; + } + let render = session.render.finish(&mut ring_objects)?; + ring_objects.finish_private()?; Ok(Self { dev: dev.as_ref().as_ref().into(), compute, render, + _ring_objects: ring_objects, }) } } impl Firmware { + #[inline(never)] pub(crate) fn init_graphs(&mut self) -> Result { for ch in [Channel::Ta, Channel::Fs, Channel::Compute] { if self.channels.read(ch)? != 0 || self.channels.write_cell(ch)? != 0 { return Err(Error::from_errno(-(kernel::bindings::EPROTO as i32))); } } - self.graph.compute.init()?; - self.graph.render.init()?; + for (pipe, compute) in self.graph.compute.iter().enumerate() { + compute.init(self.init.abi, pipe == 0)?; + } + self.graph.render.init(self.init.abi)?; self.slots.init()?; self.init_render_pools(false)?; super::engine::wmb(); diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 353199dea75a1b..2ea74d873e1276 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -4,29 +4,114 @@ reason = "Firmware layout catalog also describes fields used by host wire regressions." )] -//! T8132 (G16G) hardware and firmware-ABI constants (layout values are shared by several +//! Classic GPU hardware and firmware-ABI constants (layout values are shared by several //! modules; change one only together with its users). The tuned policy values are in //! [`tuning`]. use core::ops::Range; -/// Identification register values of a qualified G16G. +/// Identification register values of a qualified GPU. pub(crate) struct HwId { /// SGX identity word (`sgx + 0xd04000`). pub(crate) version: u32, /// SGX layout word (`sgx + 0xd04010`). pub(crate) counts: u32, + /// Bits of `version` and `counts` that must match; the others are not qualified. + pub(crate) version_mask: u32, + pub(crate) counts_mask: u32, +} + +impl HwId { + /// Mask both words exactly; rows give their values with `..HwId::EXACT`. + pub(crate) const EXACT: HwId = HwId { + version: 0, + counts: 0, + version_mask: u32::MAX, + counts_mask: u32::MAX, + }; + + /// Whether the identification registers read `version` and `counts`. + pub(crate) const fn matches(&self, version: u32, counts: u32) -> bool { + (version ^ self.version) & self.version_mask == 0 + && (counts ^ self.counts) & self.counts_mask == 0 + } } pub(crate) use crate::fwid::FirmwareBuild; -/// The J713/T8132 configuration. Hardware admission also checks the exact TEXT image. +/// Static configuration of a SoC supported by this backend. +pub(crate) struct Config { + /// SoC identifier reported to userspace. + pub(crate) chip_id: u32, + /// GPU generation reported to userspace. + pub(crate) gpu_generation: u32, + pub(crate) gpu_hal_generation: u32, + /// GPU variant reported to userspace. + pub(crate) gpu_variant: crate::hw::GpuVariant, + /// GPU revision reported to userspace. + pub(crate) gpu_revision: u32, + /// Input address bits translated by each UAT root. + pub(crate) uat_ias: u32, + /// Output (physical) address bits of the UAT. + pub(crate) uat_oas: u32, + /// Clusters and cores per cluster. + pub(crate) num_clusters: u32, + pub(crate) num_cores_per_cluster: u32, + /// Qualified identification register values. + pub(crate) hw_ids: &'static [HwId], + /// Compatible of the original ADT SGX node. + pub(crate) adt_compatible: &'static [u8], + /// NUL-terminated compatible of the native display subsystem supplier. + pub(crate) display_compatible: &'static [u8], + /// Qualified boot-loader handoffs. + pub(crate) layouts: &'static [&'static FwLayout], + /// Qualified firmware builds. + pub(crate) firmware: &'static [FirmwareBuild], + /// Whether this compatible also has a legacy driver. + pub(crate) needs_handoff_marker: bool, + /// GPU node property holding the boot loader's handoff version (the handoff marker). + pub(crate) handoff_property: &'static core::ffi::CStr, + /// `apple,firmware-compat` values this backend owns on a compatible that another backend + /// also serves; empty when the handoff layout alone selects the backend. + pub(crate) firmware_compat: &'static [[u32; 3]], + /// T8132 retains the PMP bridge even on firmware that does not send an AGX vote. + pub(crate) prepare_pmp: bool, + /// PMGR register offset of the GFX domain. + pub(crate) power_offset: u32, + /// Number of valid fault-bank selectors in the SGX status window. + pub(crate) fault_banks: usize, + /// GFXCAXI2AF needs host enable writes before the 27.2 firmware starts. + pub(crate) axi2af: bool, + /// Offsets to zero, in order, in the host block before InitData on 27.2. + pub(crate) host_block_zero_order: &'static [usize], + /// Whether the host probes scratch and raises the ready word after zeroing. + pub(crate) host_block_ready: bool, + /// Whether the TVM gate and firmware warm restart are supported. + pub(crate) deep_sleep: bool, + /// Whether render work accepts scratch for ray queries. + pub(crate) supports_render_scs: bool, + /// Whether FS->compute cross-engine barriers require `BarrierType::Hold` (type 1), as on G15. + pub(crate) cross_engine_hold: bool, + /// Largest tile buffer a render command may use, in bytes per tile (sample size times + /// utile width, utile height and samples). Reported as DRM_ASAHI_FEATURE_TILE_BUFFER_48K + /// when it reaches [`sizes::TILE_BUFFER_48K`]. + pub(crate) max_tile_buffer: u32, +} + +impl Config { + pub(crate) const fn core_slots(&self) -> u32 { + self.num_clusters * self.num_cores_per_cluster + } +} + +/// The J713/J773g T8132 configuration. Hardware admission also checks the exact TEXT image. pub(crate) mod t8132 { - use super::super::Config; - use super::{FirmwareBuild, HwId}; + use super::{Config, FirmwareBuild, HwId, FW_25G83, FW_26B123}; pub(crate) const CONFIG: Config = Config { chip_id: 0x8132, + gpu_generation: 16, + gpu_hal_generation: kernel::uapi::drm_asahi_gpu_hal_generation_DRM_ASAHI_GPU_HAL_200, gpu_variant: crate::hw::GpuVariant::G, gpu_revision: 0x10, uat_ias: 42, @@ -36,8 +121,31 @@ pub(crate) mod t8132 { hw_ids: &[HwId { version: 0x0a021100, counts: 0x0011010a, + ..HwId::EXACT }], + adt_compatible: b"gpu,t8132", + display_compatible: b"apple,t8132-display-subsystem\0", + layouts: &[&FW_25G83, &FW_26B123], firmware: &[ + FirmwareBuild { + // 25G83 (build 2 of armfw_g16g.im4p) as iBoot loads it on a T8132 Air. Besides + // the entropy, iBoot fills a header field, the record block the header points at + // (0x5c8df, 0x231) and the tunables block its TUNS/TUNZ records describe + // (0x5cb10, 0x6a0). With those zeroed, the loaded image hashes the same as the + // TEXT of the firmware file. + name: "Apple GFX 25G83 (normalized loaded image, boot-filled ranges)", + text_size: 0x60000, + data_size: 0x13c000, + entropy: &[[0x5c8df, 0x5c9c2]], + boot_filled: &[(0x23c, 8), (0x5c8df, 0x231), (0x5cb10, 0x6a0)], + text_sha256: [ + 0x3a, 0x41, 0xe4, 0x77, 0xb1, 0x2d, 0x48, 0x8d, 0x0c, 0x27, 0x7d, 0x1d, 0x30, + 0x6b, 0x60, 0x88, 0x5e, 0x67, 0x5e, 0xc7, 0x98, 0x54, 0xca, 0xaf, 0x90, 0x29, + 0x35, 0xc2, 0x7e, 0xf8, 0x76, 0x5e, + ], + }, + // The per-board entries below stay until an 8-core and a 10-core J713 on 26.6.2 + // have booted with only the normalized entry above. FirmwareBuild { name: "Apple GFX 25G83 (normalized loaded image)", text_size: 0x60000, @@ -79,10 +187,655 @@ pub(crate) mod t8132 { 0xc8, 0x29, 0x86, 0x8b, 0xc9, 0xcf, ], }, + FirmwareBuild { + // The 25G83 image as loaded by iBoot on a J773g (Mac mini). iBoot rewrites + // the header word at 0x224 and the 8-byte DILS payload at 0x5c917 on every + // boot there; they are zeroed before hashing. + name: "Apple GFX 25G83 (normalized loaded image, J773g)", + text_size: 0x60000, + data_size: 0x13c000, + entropy: &[[0x5c8df, 0x5c9c2]], + boot_filled: &[(0x224, 4), (0x5c917, 8)], + text_sha256: [ + 0x91, 0x54, 0xc7, 0xf8, 0x4b, 0xce, 0x32, 0x15, 0x1e, 0x8a, 0x97, 0x41, 0x7d, + 0x6a, 0x20, 0x7a, 0x9e, 0xaf, 0x03, 0x54, 0xb4, 0xb8, 0xd6, 0xf0, 0x2a, 0xf5, + 0x29, 0x95, 0x40, 0xd3, 0xe8, 0x5a, + ], + }, + FirmwareBuild { + // Build b000 (G16G B0) of armfw_g16g.im4p in 25G83, as iBoot loads it on any + // machine: the boot-filled ranges below are zeroed, which gives the digest of + // the shipped image with the same ranges zeroed. + name: "Apple GFX 25G83 (build b000, iBoot-filled ranges zeroed)", + text_size: 0x60000, + data_size: 0x13c000, + entropy: &[[0x5c8df, 0x5c9c2]], + boot_filled: BOOT_FILLED_25G83_B000, + text_sha256: [ + 0xb9, 0xea, 0x7e, 0x6b, 0x2a, 0xca, 0x70, 0xa2, 0x75, 0xa0, 0xb0, 0x68, 0xee, + 0x79, 0x1e, 0xd5, 0x05, 0x27, 0xe8, 0xdb, 0x76, 0x19, 0x64, 0xd2, 0x73, 0x3f, + 0xa4, 0x07, 0xa6, 0xf2, 0x22, 0x6c, + ], + }, + FirmwareBuild { + // The 26B123 (macOS 27.2; 26B131 carries the same image) build b000 as loaded + // on a J773g, with every range iBoot fills zeroed (`BOOT_FILLED_26B123_B000`). + // DATA is the `fw-data` region: __DATA (0xd0000) and its __DATA_SHARED_RO tail + // (0x8000), which the boot loader reserves as one. + name: "Apple GFX 26B123 (build b000, iBoot-filled ranges zeroed)", + text_size: 0x64000, + data_size: 0xd8000, + entropy: &[[0x60a1b, 0x60afe]], + boot_filled: BOOT_FILLED_26B123_B000, + text_sha256: [ + 0x48, 0x4c, 0x43, 0xcb, 0x79, 0x89, 0x00, 0xdd, 0x14, 0x65, 0x4e, 0xd5, 0x4e, + 0xfe, 0x16, 0x24, 0xb4, 0x3d, 0xe3, 0xce, 0x80, 0x28, 0xb7, 0x71, 0x42, 0x5d, + 0x63, 0xbc, 0xc6, 0xa7, 0x2c, 0x92, + ], + }, ], + needs_handoff_marker: false, + handoff_property: super::G16_HANDOFF_PROPERTY, + firmware_compat: &[], + prepare_pmp: true, + power_offset: 0x250, + fault_banks: 8, + axi2af: true, + host_block_zero_order: &super::start_27_2::HOST_BLOCK_ZERO_ORDER, + host_block_ready: true, + deep_sleep: true, + supports_render_scs: true, + cross_engine_hold: false, + // macOS 26B123 programs 48 KiB tiles (MSAA4, 32x16 utiles) on this GPU. + max_tile_buffer: super::sizes::TILE_BUFFER_48K, + }; + + /// What iBoot writes into the 25G83 build b000 TEXT it loads, in TEXT order: + /// - the header word at 0x224, which changes from boot to boot, and the DATA address at 0x23c; + /// - the value of each of the 39 boot parameter records the header at 0x22c places from + /// 0x5c8df to 0x5cb10 (a tag, a 32-bit length and the value: carveout addresses below the + /// top of DRAM, a per-boot slide, the entropy); + /// - the entry count and the 0x34c-byte body of the two tunable tables at 0x5cb10 and 0x5ce60, + /// which the shipped image leaves empty and iBoot populates per board. + pub(crate) const BOOT_FILLED_25G83_B000: &[(u32, u32)] = &[ + (0x224, 4), + (0x23c, 8), + (0x5c8e7, 8), + (0x5c8f7, 8), + (0x5c907, 8), + (0x5c917, 8), + (0x5c927, 8), + (0x5c937, 8), + (0x5c947, 8), + (0x5c957, 4), + (0x5c963, 1), + (0x5c96c, 8), + (0x5c97c, 8), + (0x5c98c, 4), + (0x5c998, 8), + (0x5c9a8, 1), + (0x5c9b1, 1), + (0x5c9ba, 8), + (0x5c9ca, 8), + (0x5c9da, 8), + (0x5c9ea, 8), + (0x5c9fa, 8), + (0x5ca0a, 8), + (0x5ca1a, 8), + (0x5ca2a, 8), + (0x5ca3a, 8), + (0x5ca4a, 8), + (0x5ca5a, 8), + (0x5ca6a, 8), + (0x5ca7a, 4), + (0x5ca86, 8), + (0x5ca96, 4), + (0x5caa2, 4), + (0x5caae, 8), + (0x5cabe, 8), + (0x5cace, 1), + (0x5cad7, 8), + (0x5cae7, 8), + (0x5caf7, 4), + (0x5cb03, 1), + (0x5cb0c, 4), + (0x5cb13, 1), + (0x5cb14, 0x34c), + (0x5ce63, 1), + (0x5ce64, 0x34c), + ]; + + /// What iBoot writes into the 26B123 build b000 TEXT it loads: the same two header words and + /// the same 39 boot parameter records and two tunable tables as 25G83, which the 26B123 image + /// places 0x413c bytes later (the parameter records from 0x60a1b, the tables from 0x60c4c). + pub(crate) const BOOT_FILLED_26B123_B000: &[(u32, u32)] = &[ + (0x224, 4), + (0x23c, 8), + (0x60a23, 8), + (0x60a33, 8), + (0x60a43, 8), + (0x60a53, 8), + (0x60a63, 8), + (0x60a73, 8), + (0x60a83, 8), + (0x60a93, 4), + (0x60a9f, 1), + (0x60aa8, 8), + (0x60ab8, 8), + (0x60ac8, 4), + (0x60ad4, 8), + (0x60ae4, 1), + (0x60aed, 1), + (0x60af6, 8), + (0x60b06, 8), + (0x60b16, 8), + (0x60b26, 8), + (0x60b36, 8), + (0x60b46, 8), + (0x60b56, 8), + (0x60b66, 8), + (0x60b76, 8), + (0x60b86, 8), + (0x60b96, 8), + (0x60ba6, 8), + (0x60bb6, 4), + (0x60bc2, 8), + (0x60bd2, 4), + (0x60bde, 4), + (0x60bea, 8), + (0x60bfa, 8), + (0x60c0a, 1), + (0x60c13, 8), + (0x60c23, 8), + (0x60c33, 4), + (0x60c3f, 1), + (0x60c48, 4), + (0x60c4f, 1), + (0x60c50, 0x34c), + (0x60f9f, 1), + (0x60fa0, 0x34c), + ]; +} + +/// T6030 (G15S), qualified with the b000 image loaded on J516s. +pub(crate) mod t6030 { + use super::super::fw::initdata; + use super::{Config, FirmwareBuild, FwLayout, HwId, Scratch, FW_26B123, HOST_BLOCK, UPPER}; + + pub(crate) const CONFIG: Config = Config { + chip_id: 0x6030, + gpu_generation: 15, + gpu_hal_generation: kernel::uapi::drm_asahi_gpu_hal_generation_DRM_ASAHI_GPU_HAL_LEGACY, + gpu_variant: crate::hw::GpuVariant::S, + gpu_revision: 0x11, + uat_ias: 42, + uat_oas: 42, + num_clusters: 2, + num_cores_per_cluster: 10, + hw_ids: &[HwId { + version: 0x07031100, + counts: 0x00110209, + ..HwId::EXACT + }], + adt_compatible: b"gpu,t6030", + display_compatible: b"apple,t6030-display-subsystem\0", + layouts: &[&LAYOUT], + firmware: &[FirmwareBuild { + name: "Apple GFX 26B123 G15S (build b000, iBoot-filled ranges zeroed)", + text_size: LAYOUT.text_size, + data_size: LAYOUT.data_size, + entropy: &[[0x5be64, 0x5bf47]], + boot_filled: BOOT_FILLED_B000, + text_sha256: [ + 0x31, 0xc7, 0xc7, 0x7a, 0x24, 0x85, 0x88, 0x7b, 0x66, 0x2e, 0xa2, 0x2d, 0xe6, 0xcc, + 0xc5, 0xf9, 0xf6, 0x87, 0xa2, 0x4b, 0x07, 0xbd, 0xbd, 0xdf, 0x95, 0x21, 0x1a, 0x06, + 0xcd, 0x5f, 0x57, 0x3b, + ], + }], + needs_handoff_marker: true, + handoff_property: super::G16_HANDOFF_PROPERTY, + firmware_compat: &[], + prepare_pmp: false, + power_offset: 0x110, + fault_banks: 2, + axi2af: false, + // Host-block control words zeroed read-before-write at cold 26B123 startup: + // +0x0000 is the host device-control generation word; +0x1808 and +0x3010 are the + // per-pipe host-block control words cleared before endpoints 0x20/0x21 start. + host_block_zero_order: &[0, 0x1808, 0x3010], + host_block_ready: false, + deep_sleep: false, + supports_render_scs: false, + cross_engine_hold: true, + max_tile_buffer: super::sizes::TILE_BUFFER_32K, + }; + + const LAYOUT: FwLayout = FwLayout { + name: "26B123 G15S", + segment_vas: &[UPPER, UPPER + 0x60000, UPPER + 0x18c000], + text_size: 0x60000, + data_size: 0x134000, + abi: super::FwAbi::V26B123G15S, + initdata: &initdata::G15S_26B123, + scratch: Scratch { + register: HOST_BLOCK, + // The G15S scratch window leaves an unmapped guard page at VA +0x14000 while the + // physical host-register window stays contiguous across the split (+0x14000..+0x20000). + spans: &[(0, 0, 0x14000), (0x18000, 0x14000, 0xc000)], + pointer: 0x12068, + }, + // Offset on the PPL handoff page where the G15S 26B123 firmware records + // whether the GPU is powered during idle power-gating. + powered: Some(0x638), + ..FW_26B123 + }; + + /// Fixed normalization ranges of the qualified G15S b000 image. Only the + /// values of iBoot's records, the two header fields and the tunable contents + /// are ignored. The digest still covers the tags, lengths and table headers. + const BOOT_FILLED_B000: &[(u32, u32)] = &[ + (0x224, 4), + (0x23c, 8), + (0x5be6c, 8), + (0x5be7c, 8), + (0x5be8c, 8), + (0x5be9c, 8), + (0x5beac, 8), + (0x5bebc, 8), + (0x5becc, 8), + (0x5bedc, 4), + (0x5bee8, 1), + (0x5bef1, 8), + (0x5bf01, 8), + (0x5bf11, 4), + (0x5bf1d, 8), + (0x5bf2d, 1), + (0x5bf36, 1), + (0x5bf3f, 8), + (0x5bf4f, 8), + (0x5bf5f, 8), + (0x5bf6f, 8), + (0x5bf7f, 8), + (0x5bf8f, 8), + (0x5bf9f, 8), + (0x5bfaf, 8), + (0x5bfbf, 8), + (0x5bfcf, 8), + (0x5bfdf, 8), + (0x5bfef, 1), + (0x5bff8, 8), + (0x5c008, 4), + (0x5c014, 8), + (0x5c024, 4), + (0x5c030, 4), + (0x5c03c, 4), + (0x5c048, 8), + (0x5c058, 8), + (0x5c068, 1), + (0x5c071, 8), + (0x5c081, 8), + (0x5c091, 4), + (0x5c098, 1), + (0x5c099, 0x2d4), + (0x5c370, 1), + (0x5c371, 0x2d4), + ]; +} + +/// The handoff marker aura publishes for the T8132 and T6030 GPUs. +pub(crate) const G16_HANDOFF_PROPERTY: &core::ffi::CStr = c"apple,g16-handoff-version"; + +/// T8122 (G15G), qualified with the C0 image the macOS 27.2 boot chain loads (26B123). +/// +/// The same compatible is served by the `m3` runtime for the 14.8.3 and 26.6.2 firmware, so this +/// row owns a device only when its `firmware-compat` is 27.2 and the handoff describes [`LAYOUT`] +/// ([`Config::firmware_compat`], `adt::claims`). Aura names the handoff version +/// `apple,m3-handoff-version` on this SoC (aura#448/#455). +pub(crate) mod t8122 { + use super::super::fw::initdata; + use super::{Config, FirmwareBuild, FwLayout, HwId, FW_26B123, UPPER}; + + pub(crate) const CONFIG: Config = Config { + chip_id: 0x8122, + gpu_generation: 15, + gpu_hal_generation: kernel::uapi::drm_asahi_gpu_hal_generation_DRM_ASAHI_GPU_HAL_LEGACY, + gpu_variant: crate::hw::GpuVariant::G, + // C0 (`crate::hw::GpuRevision::C0`), as the m3 runtime reports it. + gpu_revision: 0x20, + uat_ias: 42, + uat_oas: 42, + // One cluster of ten core slots; eight or ten are enabled. + num_clusters: 1, + num_cores_per_cluster: 10, + // Family 7, variant 2 (G15G), revision 0x20; one die and one cluster. The other bits + // of the two words are not qualified (`m3_soc::T8122.id`). + hw_ids: &[HwId { + version: 0x07022000, + counts: 0x00010100, + version_mask: 0xffffff00, + counts_mask: 0x000fff00, + }], + adt_compatible: b"gpu,t8122", + display_compatible: b"apple,t8122-display-subsystem\0", + layouts: &[&LAYOUT], + firmware: &[FirmwareBuild { + // GKTS/ECAP-normalized loaded TEXT, measured on the J615 over three boots + // (linux#2781, `m3_firmware::T8122_IMAGES_27`): only the two entropy values are + // zeroed, which is this backend's normalization with no boot-filled ranges. + name: "Apple GFX 26B123 G15G (C0, entropy zeroed)", + text_size: LAYOUT.text_size, + data_size: LAYOUT.data_size, + entropy: &[[0x60f60, 0x61043]], + boot_filled: &[], + text_sha256: [ + 0x74, 0x06, 0xa5, 0x68, 0x34, 0x28, 0x37, 0xa7, 0x9f, 0x22, 0xc0, 0x3f, 0x7d, 0x45, + 0x7f, 0x9f, 0x9d, 0x3e, 0x08, 0x8c, 0x4b, 0x78, 0xd7, 0x83, 0xe2, 0xdc, 0xad, 0x76, + 0x71, 0x6f, 0x16, 0xf5, + ], + }], + needs_handoff_marker: true, + handoff_property: c"apple,m3-handoff-version", + firmware_compat: &[[27, 2, 0]], + // The 27.2 start sends no PMP vote. + prepare_pmp: false, + // `ps_gfx` in t8122-pmgr.dtsi. + power_offset: 0x1e0, + fault_banks: 1, + // The m3 27.2 start on the J615 writes no GFXCAXI2AF enables (no slot 22 either). + axi2af: false, + host_block_zero_order: &super::start_27_2::HOST_BLOCK_ZERO_ORDER, + host_block_ready: true, + deep_sleep: false, + supports_render_scs: false, + cross_engine_hold: true, + max_tile_buffer: super::sizes::TILE_BUFFER_32K, }; + + /// 26B123 G15G: __TEXT 0x64000 as on G16G, __DATA 0xb4000 and the 0x8000 __DATA_SHARED_RO + /// tail, so the third segment is at UPPER + 0x118000 (aura's version-2 handoff). + pub(crate) const LAYOUT: FwLayout = FwLayout { + name: "26B123 G15G", + segment_vas: &[UPPER, UPPER + 0x64000, UPPER + 0x118000], + data_size: 0xbc000, + initdata: &initdata::G15G_26B123, + // The G15 family's 26B123 protocol: the J615 firmware installs root[1] at root + 3 + // pages with 0x403 attributes, the G15S convention, not G16G's. + abi: super::FwAbi::V26B123G15S, + // Not known for this firmware; the host keeps reading GPU registers while it runs, as + // the m3 runtime does. + powered: None, + ..FW_26B123 + }; +} + +/// Which part of the loaded image a firmware page-table leaf maps. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Segment { + Text, + Data, +} + +/// One range of leaves the boot loader builds in the firmware's own page tables: offsets from +/// [`UPPER`], the segment whose physical pages back them (at the same offset from the segment's +/// start), and the exact leaf attribute bits. +pub(crate) struct Leaves { + pub(crate) range: Range, + pub(crate) segment: Segment, + pub(crate) attrs: u64, +} + +/// The firmware ABI a build speaks to the host: its InitData, device-control, queue-info and +/// work-item layouts (`fw::{initdata, channels, graph, work}`, selected in `fw/mod.rs`). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum FwAbi { + V25G83, + V26B123, + V26B123G15S, +} + +impl FwAbi { + /// Offset of the table installed in root[1] after startup, and the + /// descriptor attributes the firmware uses for it and the shared L2. + pub(crate) const fn live_root_table(self) -> (u64, u64) { + match self { + Self::V25G83 | Self::V26B123 => (4 * PAGE, 0x00200000000004cb), + Self::V26B123G15S => (3 * PAGE, 0x403), + } + } +} + +/// How the firmware's MMIO register table in loaded DATA is filled. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum LoaderTable { + /// The host writes the HW data register-map records at this DATA offset before the + /// initdata doorbell (the firmware's table must be empty on cold entry). + Host(u64), + /// The host leaves loaded DATA alone: the firmware copies every named register-map slot + /// and the SGX window from HW data itself while it parses InitData, as the T6041 and M5 + /// G16-family firmware do. + Firmware, +} + +/// How the host starts a firmware build: RTKit and the MMIO around RUN and the endpoints. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Start { + /// 25G83, as qualified on hardware: RTKit wake (IOP power INIT first), the firmware's crash + /// buffer mapped without a reply, the host generation word zeroed after the endpoints start + /// and a 100 ms receive-ring drain before InitData. + Wake25G83, + /// 26B123 start sequence: see [`start_27_2`]. + MacOs27_2, +} + +/// Host-owned SGX register block. +pub(crate) const HOST_BLOCK: u64 = 0xd60000; + +/// The 26B123 start sequence up to the InitData doorbell: +/// 1. before RUN, bit 0 of GFXCAXI2AF `+0x104` and `+0x108` is set (read, then written); +/// 2. RTKit boots without an IOP power request: HELLO 12, the crash-log endpoint starts while +/// the endpoint map is handled, the firmware's own crash buffer request (its shared RO +/// segment) is sent back unchanged, the host hands it a 0x8000-byte log buffer of its own +/// ([`MSG_LOG_BUFFER`], 8 pages at a host-window VA), then AP power state ON (0x20); +/// 3. the host block at SGX+0xd60000 is zeroed in [`HOST_BLOCK_ZERO_ORDER`], the scratch word +/// at SGX+0xd640c0 is read, [`HOST_READY`] is read and set to 1; +/// 4. endpoints 0x20 and 0x21 start and the InitData doorbell follows at once. +pub(crate) mod start_27_2 { + /// GFXCAXI2AF registers (register-map slot 22, PA 0x301000000), from SGX. + pub(crate) const AXI2AF: usize = 0x1000000; + /// The two GFXCAXI2AF words whose bit 0 the host sets before RUN. + pub(crate) const AXI2AF_ENABLES: [usize; 2] = [0x104, 0x108]; + /// The 32-bit writes of zero to the host block (SGX+0xd60000). + pub(crate) const HOST_BLOCK_ZERO_ORDER: [usize; 13] = [ + 0x00, 0x20, 0x40, 0x08, 0x28, 0x48, 0x10, 0x30, 0x50, 0x18, 0x38, 0x58, 0x60, + ]; + /// The host block word read and then set to 1 before the endpoints start. + pub(crate) const HOST_READY: usize = 0x60; + /// The scratch word read between zeroing the host block and setting [`HOST_READY`] (SGX offset). + pub(crate) const SCRATCH_PROBE: usize = 0xd640c0; + /// RTKit crash-log endpoint. + pub(crate) const EP_CRASHLOG: u8 = 1; + /// Host log buffer message on the crash-log endpoint: the size in 4 KiB pages (from ADT + /// `coredump-copy-buffer`) at bit 44 and the buffer's address below it. + pub(crate) const MSG_LOG_BUFFER: u64 = 0x9 << 52; + pub(crate) const MSG_LOG_BUFFER_PAGES_SHIFT: u32 = 44; + pub(crate) const MSG_LOG_BUFFER_ADDR_MASK: u64 = (1 << 44) - 1; +} + +/// The two magic words of the PPL handoff page. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct PplMagic { + /// What the AP publishes at +0. + pub(crate) ap: u64, + /// The only non-zero value +8 may hold at cold admission: what the firmware leaves there + /// once it has run. + pub(crate) firmware: u64, + /// The firmware stores `firmware` at +8 from its MMU setup, before the RTKit handshake. + pub(crate) answers: bool, +} + +/// Firmware-visible alias of host registers, with the pointer InitData passes into it. +pub(crate) struct Scratch { + pub(crate) register: u64, + /// `(va_offset, pa_offset, bytes)` spans in ascending VA order. + pub(crate) spans: &'static [(u64, u64, u64)], + pub(crate) pointer: u64, +} + +const T8132_SCRATCH: Scratch = Scratch { + register: HOST_BLOCK, + spans: &[(0, 0, 0x8000)], + pointer: 0, +}; + +/// The loaded-image layout of one firmware ABI: the boot loader's handoff for it, the regions +/// it reserves, the leaves it builds in the firmware page tables, and where the boot path writes. +pub(crate) struct FwLayout { + pub(crate) name: &'static str, + /// `apple,g16-handoff-version`, `apple,firmware-segment-vas` and `-flags`. + pub(crate) handoff_version: u32, + pub(crate) segment_vas: &'static [u64], + pub(crate) segment_flags: &'static [u32], + /// Sizes of the reserved `fw-text` and `fw-data` regions (`fw-data` holds every segment + /// after TEXT). + pub(crate) text_size: u64, + pub(crate) data_size: u64, + /// The firmware ABI of the builds this layout holds. + pub(crate) abi: FwAbi, + /// InitData wire layout, including the version word of this firmware image. + pub(crate) initdata: &'static super::fw::initdata::Layout, + pub(crate) scratch: Scratch, + /// Every leaf the boot loader builds in the firmware's own page tables, in VA order, and + /// the only leaves cold admission accepts (none: the firmware builds its own tree at + /// start); `None` until known, which refuses the firmware. + pub(crate) leaves: Option<&'static [Leaves]>, + /// The PPL handoff page's magic words; `None` until known, which refuses the firmware. + pub(crate) ppl_magic: Option, + /// How the firmware's register table in loaded DATA is filled; `None` until known, which + /// refuses the firmware. + pub(crate) loader_table: Option, + /// How the host starts this firmware. + pub(crate) start: Start, + /// Where on the PPL handoff page the firmware records whether the GPU is powered, for a + /// firmware that powers it down while idle; `None` for one that keeps it powered while it + /// runs. While that byte is 0 the host reads no GPU register. + pub(crate) powered: Option, +} + +impl FwLayout { + /// Whether a boot loader's handoff describes this layout. + pub(crate) fn matches(&self, version: u32, vas: &[u64], flags: &[u32]) -> bool { + version == self.handoff_version && vas == self.segment_vas && flags == self.segment_flags + } + + /// What a firmware start needs that is not known for this layout yet; empty when the + /// firmware can be started. + pub(crate) fn unknown(&self) -> impl Iterator { + [ + self.leaves + .is_none() + .then_some("the leaves the boot loader builds in the firmware page tables"), + self.ppl_magic + .is_none() + .then_some("the PPL handoff magic words"), + self.loader_table.is_none().then_some( + "whether the host writes the register map into the firmware's table in \ + loaded DATA or the firmware copies it from HW data", + ), + ] + .into_iter() + .flatten() + } } +/// 25G83 (macOS 26.x): __TEXT 0x60000, __DATA 0x13c000. +pub(crate) const FW_25G83: FwLayout = FwLayout { + name: "25G83", + handoff_version: 1, + segment_vas: &[UPPER, UPPER + 0x60000], + segment_flags: &[1, 0], + text_size: 0x60000, + data_size: 0x13c000, + abi: FwAbi::V25G83, + initdata: &super::fw::initdata::V25G83, + scratch: T8132_SCRATCH, + leaves: Some(&[ + Leaves { + range: 0..0x50000, + segment: Segment::Text, + attrs: 0x4c3, + }, + Leaves { + range: 0x50000..0x58000, + segment: Segment::Text, + attrs: 0x483, + }, + Leaves { + range: 0x58000..0x60000, + segment: Segment::Text, + attrs: 0x4c3, + }, + Leaves { + range: 0x60000..0x6c000, + segment: Segment::Data, + attrs: 0x00200000000004c3, + }, + Leaves { + range: 0x6c000..0x19c000, + segment: Segment::Data, + attrs: 0x0460000000000443, + }, + ]), + // The 25G83 firmware never writes +8; the AP's magic there is accepted. + ppl_magic: Some(PplMagic { + ap: PPL_MAGIC, + firmware: PPL_MAGIC, + answers: false, + }), + loader_table: Some(LoaderTable::Host(0x1332f0)), + start: Start::Wake25G83, + // The GPU stays powered from START until the firmware stops. + powered: None, +}; + +/// 26B123 (macOS 27.2, also 26B131): __TEXT 0x64000, __DATA 0xd0000 and a __DATA_SHARED_RO +/// 0x8000 right after it (aura's handoff version 2; `fw-data` covers both, so the RTKit crash +/// log at the start of the shared read-only segment lies inside it). +/// +/// The boot loader leaves the page-table region zero and the firmware builds its own tree +/// (root, the L2 at +0x4000 and the L3 at +0x8000, with the TEXT and DATA leaves) when it +/// starts, so only an empty tree is admitted. Once it has set up its MMU the firmware leaves +/// 0x4b1d000000000003 at +8 of the PPL handoff page (the 25G83 firmware never wrote there). +/// The AP announces the same word at +0 before RUN, as the G14 firmware-27.2 path does on +/// hardware (linux#2544: AP and firmware exchange 0x4b1d000000000003 through these two words, +/// the firmware answering before the RTKit handshake). The host leaves loaded DATA alone: the +/// firmware takes the register map from HW data while it parses InitData, the T6041 build of +/// this firmware starts on hardware without any DATA write (linux#1954), and 27.2 marks DATA +/// data-isolated. Its register table is at DATA + 0xc72e8 (60 slots). +pub(crate) const FW_26B123: FwLayout = FwLayout { + name: "26B123", + handoff_version: 2, + segment_vas: &[UPPER, UPPER + 0x64000, UPPER + 0x134000], + segment_flags: &[1, 0x10, 0], + text_size: 0x64000, + data_size: 0xd8000, + abi: FwAbi::V26B123, + initdata: &super::fw::initdata::V26B123, + scratch: T8132_SCRATCH, + // The firmware builds its own tree at start; admit only an empty tree. + leaves: Some(&[]), + ppl_magic: Some(PplMagic { + ap: PPL_MAGIC_27_2, + firmware: PPL_MAGIC_27_2, + answers: true, + }), + loader_table: Some(LoaderTable::Firmware), + start: Start::MacOs27_2, + // The firmware powers the GPU down after its idle delay (region C 0x9c0) and back up for + // the next work, under the PPL handoff lock, and sets this byte to 1 after each power-up + // and to 0 after each power-down. + powered: Some(0x648), +}; + /// User VA range reported as `vm_start..vm_end`: 42 bits with the final two pages excluded. pub(crate) const USER_RANGE: Range = 0x4000..0x3ffffff8000; @@ -124,8 +877,10 @@ pub(crate) mod pte { pub(crate) const LEAF_PB_LIST: u64 = 0x00e0000000000c03; } -/// PPL handoff magic. +/// PPL handoff magic the AP publishes for the 25G83 firmware. pub(crate) const PPL_MAGIC: u64 = 0x4b1d000000000002; +/// The PPL handoff magic of the 27.2 (26B123) GPU firmware, published by both sides. +pub(crate) const PPL_MAGIC_27_2: u64 = 0x4b1d000000000003; /// UAT handoff region sizes of this firmware ABI (TTBAT page, TTBAT tables (the firmware kernel /// root), PPL handoff page, shared L2 page); the addresses come from the ADT. @@ -153,6 +908,9 @@ pub(crate) mod rings { pub(crate) const LOG_RINGS: usize = 9; pub(crate) const LOG_STATE_SIZE: usize = 0x1b0; pub(crate) const LOG_RING_SIZE: usize = 0x28800; + pub(crate) const LOG_PAYLOAD_SIZE: usize = 0xd8; + pub(crate) const LOG_PAYLOAD_TEXT_OFFSET: usize = 0x10; + pub(crate) const LOG_PAYLOAD_TEXT_SIZE: usize = 0xc8; pub(crate) const TRACE_RING_SIZE: usize = 0x9000; pub(crate) const STATS_RING_SIZE: usize = 0x4800; pub(crate) const FWCTL_RING_SIZE: usize = 0x4000; @@ -182,10 +940,18 @@ pub(crate) mod client { pub(crate) const CLIENT_APERTURE: Range = 0x7000000000..0x7100000000; pub(crate) const COMPACT_WINDOW: Range = 0x1000000000..0x9000000000; - // Two persistent compute units, each in its own 64 MiB interval and reused across - // application queues. Every alias is inside Mesa's reserved driver hole. + // Persistent compute units reused across application queues. Units 0 and 1 keep their + // original 64 MiB placement below the render allocators; extension units (2..COMPUTE_UNITS) + // pack at a 40 MiB stride from 0x7080000000 up to the SCS compute records (0x70b8000000), + // clear of [`DYNAMIC`] and [`SCS_POOLS`] and leaving 7.25 MiB guard above each unit's + // 32.75 MiB footprint (`0x20c0000`). Every alias is inside Mesa's reserved hole. + pub(crate) const EXT_COMPUTE_STRIDE: u64 = 0x02800000; pub(crate) const fn compute_base(k: u64) -> u64 { - 0x7001000000 + k * 0x04000000 + if k < 2 { + 0x7001000000 + k * 0x04000000 + } else { + 0x7080000000 + (k - 2) * EXT_COMPUTE_STRIDE + } } pub(crate) const fn compute_pool(k: u64) -> u64 { compute_base(k) @@ -209,9 +975,29 @@ pub(crate) mod client { pub(crate) const WORK_OFF: u64 = 0; pub(crate) const CWORK_STRIDE: u64 = 0x4000; - // Render allocator units contain one 32 MiB UMA pool and its persistent lists. + // SCS-capable compute units (ray-query scratch), one 64 MiB interval each after the last + // compute unit (0x70b7000000) and below the PB heap (0x70c0000000), holding the unit's + // list, preempt, auxiliary and context records at the base units' offsets from their + // state. Its UMA pool and freelist are in its SCS pool window ([`scs_compute_pool`]). + pub(crate) const fn scs_compute_records(k: u64) -> u64 { + 0x70b8000000 + k * 0x04000000 + } + /// Offsets of a compute unit's records from its state. + pub(crate) const COMPUTE_LIST_OFF: u64 = compute_list(0) - compute_state(0); + pub(crate) const COMPUTE_PREEMPT_OFF: u64 = compute_preempt(0) - compute_state(0); + pub(crate) const COMPUTE_AUX_OFF: u64 = compute_aux(0) - compute_state(0); + pub(crate) const COMPUTE_CONTEXT_OFF: u64 = compute_context(0) - compute_state(0); + + // Render allocator units contain one 32 MiB UMA pool and its persistent lists in a + // 64 MiB stride. Per-VM local slots 0..4 live in 0x7010000000..0x7020000000; local slots + // 4..MAX_VM_PB_SLOTS live in 0x7008000000..0x7010000000, above base compute units 0..2 + // (ending at 0x70070c0000) and below the render pass slot window (0x7020000000..0x7040000000). pub(crate) const fn render_base(k: u64) -> u64 { - 0x7010000000 + k * 0x08000000 + if k < 4 { + 0x7010000000 + k * 0x04000000 + } else { + 0x7008000000 + (k - 4) * 0x04000000 + } } pub(crate) const fn render_pool(k: u64) -> u64 { render_base(k) @@ -228,6 +1014,29 @@ pub(crate) mod client { pub(crate) const fn render_pb_pages(k: u64) -> u64 { render_base(k) + 0x2040000 } + // SCS-capable render allocators: the list and descriptor in their render unit's interval + // past its records, at the base allocator's offsets from its state. The UMA pool and + // freelist are in the allocator's SCS pool window ([`scs_render_pool`]). + pub(crate) const fn scs_render_records(k: u64) -> u64 { + render_base(k) + 0x2100000 + } + /// Kernel-placed client objects (PB page lists, `Objects::alloc_dynamic_client`). + pub(crate) const DYNAMIC: Range = 0x7040000000..0x7060000000; + /// SCS pool windows, after [`DYNAMIC`] and up to the CT window: each holds one + /// SCS-capable UMA pool and, right after it, its freelist (`rt::window_bytes`). Windows 0 + /// and 1 are the SCS compute units', 2 and 3 the SCS render allocators'. + pub(crate) const SCS_POOLS: u64 = 0x7060000000; + pub(crate) const SCS_POOL_WINDOW: u64 = 0x8000000; + pub(crate) const SCS_POOL_WINDOWS: u64 = 4; + pub(crate) const fn scs_compute_pool(k: u64) -> u64 { + SCS_POOLS + k * SCS_POOL_WINDOW + } + pub(crate) const fn scs_render_pool(k: u64) -> u64 { + SCS_POOLS + (2 + k) * SCS_POOL_WINDOW + } + /// Offsets of a render allocator's records from its state. + pub(crate) const RENDER_LIST_OFF: u64 = render_list(0) - render_state(0); + pub(crate) const RENDER_DESCRIPTOR_OFF: u64 = render_descriptor(0) - render_state(0); pub(crate) const PB_HEAP: u64 = 0x70c0000000; pub(crate) const PB_HEAP_SIZE: u64 = 0x10000000; pub(crate) const fn pb_heap(k: u64) -> u64 { @@ -237,13 +1046,23 @@ pub(crate) mod client { pub(crate) const PB_PAGE_LIST: u64 = 0x7012040000; pub(crate) const PB_PAGE_LIST_SIZE: u64 = 0x8000; - // Render pass resources, each in a distinct 256 MiB interval. + // Host-chosen client VA layout for render pass resources within 0x7020000000..0x7040000000 + // (512 MiB). Firmware takes explicit 64-bit VAs for each pass object rather than indexing + // by stride: + // - Base slots `0..BASE_RENDER_SLOTS` keep 32 MiB intervals with full 16 MiB TPC / 8 MiB + // tilemap capacity for worst-case geometries. + // - Extension slots `BASE_RENDER_SLOTS..RENDER_SLOTS` pack into 8 MiB intervals starting at + // `EXT_PASS_BASE` (`0x7024000000`) with 2 MiB TPC / 1 MiB tilemap capacity, fitting 48 + // total pass slots (`0x7020000000..0x703b000000`, leaving 80 MiB free below 0x7040000000). pub(crate) const FS_WORK_PAGE: u64 = 0x7020000000; pub(crate) const FS_WORK_OFF: u64 = 0; pub(crate) const TA_WORK_PAGE: u64 = 0x7020004000; pub(crate) const TA_WORK_OFF: u64 = 0; - pub(crate) const WORK_STRIDE: u64 = 0x10000000; + pub(crate) const WORK_STRIDE: u64 = 0x02000000; pub(crate) const PASS_STRIDE: u64 = WORK_STRIDE; + pub(crate) const EXT_PASS_STRIDE: u64 = 0x00800000; + pub(crate) const EXT_PASS_BASE: u64 = + FS_WORK_PAGE + (super::sizes::BASE_RENDER_SLOTS as u64) * PASS_STRIDE; pub(crate) const PRE0_PAGE: u64 = 0x7020080000; pub(crate) const PRE1_PAGE: u64 = 0x70200a0000; pub(crate) const PRE2_PAGE: u64 = 0x70200c0000; @@ -252,13 +1071,37 @@ pub(crate) mod client { pub(crate) const FS_SCRATCH: u64 = 0x7020140000; pub(crate) const AUX: u64 = 0x7020160000; pub(crate) const AUX_STRIDE: u64 = WORK_STRIDE; - pub(crate) const TPC: u64 = 0x7024000000; + pub(crate) const SCENE_LIST: u64 = 0x7020180000; + pub(crate) const TPC: u64 = 0x7020400000; pub(crate) const TPC_SIZE: u64 = 0x1000000; - pub(crate) const TILEMAP: u64 = 0x7026000000; + pub(crate) const TILEMAP: u64 = 0x7021400000; pub(crate) const TILEMAP_SIZE: u64 = 0x800000; - pub(crate) const TPC_SLOT_SIZE: u64 = TPC_SIZE; - pub(crate) const TILEMAP_SLOT_SIZE: u64 = TILEMAP_SIZE; + /// Extension pass slot TPC/tilemap sizes (2 MiB / 1 MiB, covering 4K multi-layer and 8K + /// passes); base slots keep full `TPC_SIZE` / `TILEMAP_SIZE` for worst-case geometries. + pub(crate) const TPC_SLOT_SIZE: u64 = 0x200000; + pub(crate) const TILEMAP_SLOT_SIZE: u64 = 0x100000; pub(crate) const TPC_SLOT_STRIDE: u64 = WORK_STRIDE; + pub(crate) const EXT_TILEMAP_OFF: u64 = (TPC - FS_WORK_PAGE) + TPC_SLOT_SIZE; + + pub(crate) const fn pass_base(i: u64) -> u64 { + if i < super::sizes::BASE_RENDER_SLOTS as u64 { + FS_WORK_PAGE + i * PASS_STRIDE + } else { + EXT_PASS_BASE + (i - super::sizes::BASE_RENDER_SLOTS as u64) * EXT_PASS_STRIDE + } + } + + pub(crate) const fn pass_off(i: u64) -> u64 { + pass_base(i) - FS_WORK_PAGE + } + + pub(crate) const fn pass_tilemap(i: u64) -> u64 { + if i < super::sizes::BASE_RENDER_SLOTS as u64 { + TILEMAP + i * PASS_STRIDE + } else { + pass_base(i) + EXT_TILEMAP_OFF + } + } pub(crate) const CT: u64 = 0x7080000000; pub(crate) const CT_STRIDE: u64 = 0x1000000; pub(crate) const CT_SIZE: u64 = 0x400000; @@ -266,29 +1109,202 @@ pub(crate) mod client { /// Sizes and counts of the engine's objects. pub(crate) mod sizes { + /// Tile buffer limits of [`super::Config::max_tile_buffer`]. + pub(crate) const TILE_BUFFER_32K: u32 = 32 * 1024; + pub(crate) const TILE_BUFFER_48K: u32 = 48 * 1024; pub(crate) const POOLS: usize = 16; pub(crate) const POOL_SIZE: u64 = 0x200000; pub(crate) const FREELIST_SEED: u32 = 8192; pub(crate) const QUEUE_CAP: u32 = 256; - pub(crate) const COMPUTE_SLOTS: usize = 2; - pub(crate) const RENDER_SLOTS: usize = 2; + /// Independent firmware compute workqueue pipes sharing `Channel::Compute` and `sched_ctx`. + /// Each pipe owns a disjoint `ComputeGraph` (`qinfo`, work ring, `qstate`, `fw_stamp`, + /// `notifier`, `threshold`, `job_list`) and completion event (`work::compute::EVENTS`) so + /// concurrent compute VMs lease disjoint workqueues instead of mixing ASIDs in one active + /// `qinfo`. Pipe 0 exclusively owns `0..PIPE1_COMPUTE_START` for base-only and SCS VMs; + /// secondary pipes `1..COMPUTE_PIPES` share `PIPE1_COMPUTE_START..COMPUTE_UNITS` (18 units + /// for 7 secondary pipes, leaving 11 active units beyond the 7 undisplaced retired leases). + pub(crate) const COMPUTE_PIPES: usize = 8; + /// Maximum concurrent compute pipes one VM may occupy at once, preserving the render + /// ring-entry bound (`MAX_RENDER_RING_ENTRIES = 5`) since cross-VM render/compute drains. + pub(crate) const MAX_VM_COMPUTE_PIPES: usize = 2; + const _: () = assert!(COMPUTE_PIPES >= 2 && COMPUTE_PIPES <= 16); + const _: () = assert!(MAX_VM_COMPUTE_PIPES >= 2 && MAX_VM_COMPUTE_PIPES <= COMPUTE_PIPES); + const _: () = assert!(COMPUTE_UNITS - PIPE1_COMPUTE_START >= (COMPUTE_PIPES - 1) * 2); + /// Compute units claimable in one batched compute prefix (matches `COMPUTE_UNITS`). + pub(crate) const COMPUTE_SLOTS: usize = COMPUTE_UNITS; + /// Base physical PB/UMA allocator slots allocated per VM on first render. + pub(crate) const BASE_PB_SLOTS: usize = 2; + /// Device-wide warm physical PB/UMA allocator slots (`parameter_id` `0..WARM_PB_SLOTS`, + /// hardware UMA slots `33..33 + WARM_PB_SLOTS`). Each VM maps two base units (`local_idx` + /// `0..BASE_PB_SLOTS`) bound to a rotating `[home, alt]` pair in this pool so up to + /// `WARM_PB_SLOTS` concurrent render VMs stay warm without extra per-VM memory. + pub(crate) const WARM_PB_SLOTS: usize = 16; + /// Lazily allocated recovery PB/UMA allocator slots (`WARM_PB_SLOTS..PB_SLOTS`, mapped at + /// per-VM local VA indices `BASE_PB_SLOTS..MAX_VM_PB_SLOTS`) claimed only after a render + /// hang permanently quarantines an allocator slot. + pub(crate) const EXT_PB_SLOTS: usize = 4; + /// Maximum PB/UMA allocator slots mapped in one VM's client VA space (`render_base(0..6)`). + pub(crate) const MAX_VM_PB_SLOTS: usize = BASE_PB_SLOTS + EXT_PB_SLOTS; + /// Total device-wide physical PB/UMA allocator slots (`parameter_id` `0..PB_SLOTS`, hardware + /// UMA slots `RENDER_UMA_SLOT..RENDER_UMA_SLOT + PB_SLOTS`). + pub(crate) const PB_SLOTS: usize = WARM_PB_SLOTS + EXT_PB_SLOTS; + const _: () = assert!(WARM_PB_SLOTS >= BASE_PB_SLOTS); + const _: () = assert!(MAX_VM_PB_SLOTS >= BASE_PB_SLOTS && MAX_VM_PB_SLOTS <= 6); + const _: () = assert!(PB_SLOTS <= 32); + const _: () = + assert!(super::client::compute_context(1) + 0x40000 <= super::client::render_base(4)); + const _: () = + assert!(super::client::render_descriptor(3) + 0x4000 <= super::client::FS_WORK_PAGE); + const _: () = + assert!(super::client::render_descriptor(5) + 0x4000 <= super::client::render_base(0)); + /// Worst-case firmware work-ring entries consumed per pipelined render pass on TA + /// (`prev_barrier`, `ta_fs_barrier`, up to `COMPUTE_PIPES` `compute_barrier` entries, + /// `ta_work`) and FS (`fs_dep`, up to `COMPUTE_PIPES` `fs_compute_barrier` entries, + /// `own_barrier`, `fs_work`). `InitBM` runs only on an idle engine (`initbm` + `ta_work` = 2 + /// entries). + pub(crate) const MAX_RENDER_RING_ENTRIES: usize = 5; + /// Worst-case firmware work-ring entries per compute command (`fs2c` barrier + cross-pipe + /// `c2c` barrier + `work`). + pub(crate) const MAX_COMPUTE_RING_ENTRIES: usize = 3; + /// Maximum unfinished TA passes kept in flight at once for heavy multi-layer or large-tilemap + /// renders so heavy bursts stay inside M4 firmware's `<= 4`-pass TA/scene pipeline. + pub(crate) const TA_WAVE_PASSES: usize = 4; + /// Maximum unfinished TA passes kept in flight at once for light single-layer renders + /// (`tilemap_bytes <= TA_LIGHT_TILEMAP_BYTES`), doubling the wave window for light render + /// bursts and deeper micro-coalesced batches. + pub(crate) const TA_WAVE_PASSES_LIGHT: usize = 8; + /// Tilemap byte threshold at or below which a single-layer render qualifies for + /// `TA_WAVE_PASSES_LIGHT`. + pub(crate) const TA_LIGHT_TILEMAP_BYTES: u64 = 64 * 1024; + /// Headroom below the active TA wave cap at which a TA-wave-paused render queue wakes to + /// launch the next wave, avoiding 1-pass stub drips. + pub(crate) const TA_WAVE_REFILL_HEADROOM: usize = 2; + /// Base render pass slots allocated on first render (full TPC/tilemap capacity). + pub(crate) const BASE_RENDER_SLOTS: usize = 2; + /// Retained render pass slots per VM at most. A slot is reused only after a later render + /// retired (displacing it), so `n` slots keep up to `n - 1` renders in flight. + /// + /// Sized inside both the host client-VA window (`0x7020000000..0x7040000000`) and firmware + /// queue/recovery capacities: `47` in-flight passes consume at most `47 * 4 = 188` entries of + /// each 256-entry TA/FS work ring (`QUEUE_CAP = 256`, 255 usable, ring cap `63`), use + /// per-allocator hardware UMA slots `RENDER_UMA_SLOT + slot` (`33..38`, strictly inside the + /// firmware render slot range `33..64`), post at most `FLIGHTS = 32` `SubmitRecord`s (vs + /// `AHEAD_RECORDS = 128` / `RING_SLOTS = 256`), and stay far below the firmware recovery + /// `snapshot_entries = 448` limit. + pub(crate) const RENDER_SLOTS: usize = 48; + const _: () = assert!(RENDER_SLOTS >= BASE_RENDER_SLOTS && RENDER_SLOTS <= 64); + const _: () = assert!(super::engine::RENDER_UMA_SLOT + (PB_SLOTS as u32) <= 65); + const _: () = assert!((RENDER_SLOTS - 1) * MAX_RENDER_RING_ENTRIES < QUEUE_CAP as usize); + const _: () = assert!(super::client::AUX + 0x20000 <= super::client::SCENE_LIST); + const _: () = assert!(super::client::SCENE_LIST + 0x4000 <= super::client::TPC); + const _: () = assert!(super::client::TPC + super::client::TPC_SIZE <= super::client::TILEMAP); + const _: () = assert!( + super::client::TILEMAP + super::client::TILEMAP_SIZE + <= super::client::FS_WORK_PAGE + super::client::PASS_STRIDE + ); + const _: () = assert!( + super::client::EXT_TILEMAP_OFF + super::client::TILEMAP_SLOT_SIZE + <= super::client::EXT_PASS_STRIDE + ); + const _: () = assert!(super::client::pass_base(RENDER_SLOTS as u64) <= 0x7040000000); pub(crate) const CT_BUFS: usize = 0; pub(crate) const CLUSTER_PB_PAGES: u32 = 0x3c; pub(crate) const MAX_ATTACHMENTS: usize = 16; - pub(crate) const MAX_CLIENT: usize = 320; + pub(crate) const MAX_CLIENT: usize = 512; pub(crate) const PB_PAGES: u32 = 8192; pub(crate) const PB_BLOCKS: u32 = 2048; pub(crate) const PB_LIST_RECORDS: u32 = 4096; pub(crate) const PB_GROW_STEP: u32 = 10; - /// The qualified M4 protocol permits only one published command at a time. - pub(crate) const FLIGHTS: usize = 1; - /// Inherited diagnostic histogram width; M4 does not fold jobs into a compute horizon. - pub(crate) const HORIZON_JOBS: u32 = 1; - /// Two jobs may be admitted per logical queue so exact prior-command dependencies can - /// advance independently of a preceding job's aggregate fence. Firmware stays serialized. - pub(crate) const SCHEDULER_CREDITS: u32 = 2; + /// Published prefixes at most. Warm render commands may pipeline across VMs on disjoint + /// hardware UMA slots, compute only behind its own VM's work, while cold `InitBM` renders + /// and recovery paths drain. + pub(crate) const FLIGHTS: usize = 32; + /// Retained compute units per VM at most; each unit owns its own hardware UMA slot + /// (`COMPUTE_UMA_SLOT + index`, fitting in `1..RENDER_UMA_SLOT = 33`). A unit is reused + /// only after a later publication retired (it displaced the unit), so `n` units keep up to + /// `n - 1` compute commands in flight (`23 * 2 = 46` entries of the 256-entry compute work + /// ring `QUEUE_CAP`, well inside `AHEAD_RECORDS = 128`, `RING_SLOTS = 256`, and recovery + /// `snapshot_entries = 448`). + pub(crate) const COMPUTE_UNITS: usize = 24; + const _: () = assert!(COMPUTE_UNITS >= 2); + const _: () = assert!((COMPUTE_UNITS - 1) * MAX_COMPUTE_RING_ENTRIES < QUEUE_CAP as usize); + const _: () = assert!( + super::client::compute_context(2) + 0x40000 <= super::client::compute_base(3) + ); + const _: () = assert!( + super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::PB_HEAP + ); + const _: () = assert!( + super::engine::COMPUTE_UMA_SLOT + (COMPUTE_UNITS as u32) + <= super::engine::RENDER_UMA_SLOT + ); + /// SCS-capable compute units per VM, bound dynamically to healthy compute ledger indices + /// (and UMA slots) preferring pipe-0-exclusive indices `0..PIPE1_COMPUTE_START`. + pub(crate) const SCS_COMPUTE_UNITS: usize = 2; + /// First hardware compute ledger index usable by secondary compute pipes (`pipe >= 1`). + /// Keeping `0..PIPE1_COMPUTE_START` exclusive to pipe 0 guarantees that pipe 1 never holds + /// an undisplaced lease on those units, so 2-unit base-only and SCS compute VMs always have + /// at least one claimable unit across up to `PIPE1_COMPUTE_START - 2` permanent quarantines. + pub(crate) const PIPE1_COMPUTE_START: usize = 6; + const _: () = assert!( + PIPE1_COMPUTE_START >= SCS_COMPUTE_UNITS && PIPE1_COMPUTE_START + 2 <= COMPUTE_UNITS + ); + /// Bytes of a base UMA pool (its seeds of 4 KiB). + pub(crate) const POOL_BYTES: u64 = 0x2000000; + const _: () = assert!( + super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::scs_compute_records(0) + && super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64 - 1) + + super::client::COMPUTE_CONTEXT_OFF + + 0x40000 + <= super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64) + && super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64) + <= super::client::PB_HEAP + && super::client::WORK_PAGE + + (COMPUTE_UNITS + SCS_COMPUTE_UNITS) as u64 * super::client::CWORK_STRIDE + <= super::client::compute_base(0) + ); + const _: () = assert!( + super::client::render_pb_pages(0) + super::client::PB_PAGE_LIST_SIZE + <= super::client::scs_render_records(0) + && super::client::scs_render_records(0) + super::client::RENDER_DESCRIPTOR_OFF + 0x4000 + <= super::client::render_base(1) + && super::client::scs_render_records(BASE_PB_SLOTS as u64 - 1) + + super::client::RENDER_DESCRIPTOR_OFF + + 0x4000 + <= super::client::render_base(BASE_PB_SLOTS as u64) + ); + // One window per SCS compute unit and render allocator, between the dynamic range and the + // CT window. + const _: () = assert!( + super::client::DYNAMIC.end <= super::client::scs_compute_pool(0) + && super::client::scs_compute_pool(SCS_COMPUTE_UNITS as u64) + == super::client::scs_render_pool(0) + && super::client::scs_render_pool(BASE_PB_SLOTS as u64) + == super::client::SCS_POOLS + + super::client::SCS_POOL_WINDOWS * super::client::SCS_POOL_WINDOW + && super::client::scs_render_pool(BASE_PB_SLOTS as u64) <= super::client::CT + && super::client::pass_base(RENDER_SLOTS as u64) <= super::client::DYNAMIC.start + ); + /// Maximum jobs folded into one barrier-free compute horizon prefix. + pub(crate) const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32; + /// Maximum commands accumulated in a busy-state horizon micro-coalescing batch before + /// immediate publication, and maximum hold window (18 us) while a queue already has >= 2 + /// active commands in flight. + pub(crate) const COALESCE_MAX_CMDS: usize = 6; + pub(crate) const COALESCE_WINDOW_US: u32 = 18; + pub(crate) const COALESCE_WINDOW_NS: u64 = (COALESCE_WINDOW_US as u64) * 1000; + /// Per-queue retired CDM execution EWMA threshold (microseconds) at or above which + /// barrier-free compute fans out across both CDM pipes instead of staying 1-pipe affine. + pub(crate) const COMPUTE_HEAVY_EMA_US: u32 = 200; + /// Elapsed wall-clock time (nanoseconds) on a sole active single-command compute flight + /// that immediately classifies the queue as heavy before its first retirement updates EWMA. + pub(crate) const COMPUTE_HEAVY_INFLIGHT_NS: u64 = 180_000; + /// Jobs admitted to the engine per logical queue: enough to keep deep queues (`d=64`) + /// queued back to back without scheduler backpressure stalls; exact prior-command + /// dependencies still gate each one. + pub(crate) const SCHEDULER_CREDITS: u32 = 64; /// Unconsumed records per 256-entry channel ring a prefix may be posted behind. - pub(crate) const AHEAD_RECORDS: u32 = 64; + pub(crate) const AHEAD_RECORDS: u32 = 128; /// Policy bound on logical queues reported in QUEUE_LIMITS (not a firmware limit). pub(crate) const MAX_QUEUES: u32 = 58; /// TTBAT user slots: user VMs hold one each for their lifetime (ASIDs 1..63). @@ -298,7 +1314,10 @@ pub(crate) mod sizes { /// Firmware channels, doorbells, seeds and identifiers. pub(crate) mod engine { pub(crate) const DOORBELL: u64 = 0x0083000000000000; + pub(crate) const DEVCTL_INIT_DOORBELL: u64 = DOORBELL | 0x11; pub(crate) const DEVCTL_DOORBELL: u64 = 0x0084000000000011; + pub(crate) const RECEIVE_DOORBELL: u64 = DOORBELL | 0x10; + pub(crate) const G15S_RECEIVE_DOORBELL: u64 = 0x0087000000000010; pub(crate) const EVENT_SLOT: u32 = 2; pub(crate) const COMPUTE_UMA_SLOT: u32 = 1; pub(crate) const RENDER_UMA_SLOT: u32 = 33; diff --git a/drivers/gpu/drm/asahi/g16/initdata.rs b/drivers/gpu/drm/asahi/g16/initdata.rs index ecdde0579133ab..0fedb4d9d0f8bd 100644 --- a/drivers/gpu/drm/asahi/g16/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/initdata.rs @@ -1,22 +1,26 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT //! Owned J713 initdata: 31 inventory objects, 12 submit channel pairs and the -//! exact 42-entry MMIO loader. All bytes are encoded in fresh GEM backing before -//! the boot owner publishes a root or loader address. Firmware-reachable -//! backing and mappings are retained by `Objects` until reboot. +//! exact MMIO register map, in the layout of the admitted firmware's ABI. All bytes are +//! encoded in fresh GEM backing before the boot owner publishes a root or loader address. +//! Firmware-reachable backing and mappings are retained by `Objects` until reboot. use kernel::{device, prelude::*, sync::Arc}; use super::adt::GpuAdt; use super::board; +use super::boot::glue; use super::channel::{Channels, Ring}; -use super::fw::initdata::{self as wire, control, globals, id, ready_control}; -use super::hw; +use super::fw::initdata::{self as wire, id, ready_control}; +use super::hw::{self, FwAbi}; use super::object::{Class, FwObject, Objects, Placement, Request}; /// Firmware graph handles. The small root.Control and large FirmwareData are /// intentionally separate: only the former carries the READY acknowledgement. pub(crate) struct InitData { + /// The firmware ABI these objects were encoded for. + pub(crate) abi: FwAbi, + pub(crate) layout: &'static wire::Layout, pub(crate) globals: Option>, /// Recovery/scheduler owner: root.FirmwareData, not the small Control. pub(crate) control: Option>, @@ -38,7 +42,10 @@ pub(crate) struct InitData { #[allow(dead_code)] pub(crate) parameter: Arc, root: Arc, - loader: [u8; wire::LOADER_BYTES], + /// Rows of the board's firmware performance table, including off. + pub(crate) rows: u32, + /// The register-map records, slot 0 through the highest filled one. + loader: KVec, /// The complete inventory, including firmware-only log and retention data. _graph: KVec>, } @@ -48,14 +55,24 @@ impl InitData { Ok(self.root.va) } - /// Exact Main loader records which the boot owner publishes to firmware DATA. - pub(crate) fn loader_bytes(&self) -> &[u8; wire::LOADER_BYTES] { + /// Exact Main register-map records, which the boot owner publishes to firmware DATA when + /// the layout has the host write them. + pub(crate) fn loader_bytes(&self) -> &[u8] { &self.loader } + /// The FirmwareData words of this ABI. + pub(crate) fn firmware_data(&self) -> &'static wire::FirmwareData { + &self.layout.firmware_data + } + /// A phase 1 or 3 stop is owned by the M4 recovery handshake. pub(crate) fn halted(&self) -> Result { - let phase = self.control.as_ref().ok_or(ENODEV)?.r32(control::PHASE)?; + let phase = self + .control + .as_ref() + .ok_or(ENODEV)? + .r32(self.firmware_data().phase)?; Ok(phase == 1 || phase == 3) } @@ -69,23 +86,34 @@ impl InitData { } fn pair(graph: &[Arc], state: usize, ring: usize) -> Ring { - Ring { - state: graph[state].clone(), - ring: graph[ring].clone(), - } + Ring::new( + graph[state].clone(), + graph[ring].clone(), + wire::TxLayout::StateBlock, + false, + ) } /// Builds the complete unpublished M4 graph. The return shape is shared with /// the other backend, while all object layouts and policy are M4-specific. +#[inline(never)] pub(crate) fn build( dev: &device::Device, adt: &GpuAdt, + cfg: &super::Config, + regs: &super::regs::Regs, + enabled_cores: u32, objects: &mut Objects, ) -> Result<(InitData, Channels, u32)> { + let abi = adt.layout.abi; + let layout = adt.layout.initdata; let performance = board::qualify(dev, adt)?; - let max_khz = performance.frequency[wire::PERF_STATES - 1] * 1000; + // The top row of the qualified table, excluding the off state. + let ceiling = performance.count as u32 - 1; + let rows = performance.count as u32; + let max_khz = performance.frequency[ceiling as usize] * 1000; let mut graph = KVec::with_capacity(wire::OBJECT_COUNT, GFP_KERNEL)?; - for (i, size) in wire::OBJECT_SIZE.iter().copied().enumerate() { + for (i, size) in layout.object_size.iter().copied().enumerate() { let lower = match i { id::UMA => Some(wire::BOOTSTRAP_START), id::PARAMETER => Some(wire::BOOTSTRAP_START + 0x8000), @@ -125,17 +153,91 @@ pub(crate) fn build( } let channels = Channels::alloc_submit_and_attach( objects, - pair(&graph, id::DEVCTRL_STATE, id::DEVCTRL_RING), + layout.tx, + Ring::new( + graph[id::DEVCTRL_STATE].clone(), + graph[id::DEVCTRL_RING].clone(), + layout.tx, + true, + ), pair(&graph, id::EVENT_STATE, id::EVENT_DATA), pair(&graph, id::LOG_STATE, id::LOG_ENTRIES), + graph[id::LOG_DATA].clone(), pair(&graph, id::KTRACE_STATE, id::KTRACE_DATA), pair(&graph, id::STATISTICS_STATE, id::STATISTICS_DATA), // FWCTL state and ring share one allocation (ring starts at+0x40). // The host never posts on this firmware-only control channel. pair(&graph, id::FWCTL, id::FWCTL), )?; + // The GPU power sample period: `gpu-pwr-sample-period-aic-clks` gives the exact hardware + // sample period in system-counter ticks (e.g. 200000 ticks at 24 MHz = 8333 us), whereas + // `gpu-power-sample-period` is the coarse truncated integer millisecond period (8 ms). + // Power config +4/+8 take the exact AIC ticks; the us sampling slots and average-power + // filter sample count use the exact us period, while the low-peak (PPM) limiter filter + // uses the coarse ms period, matching `drivers/gpu/drm/asahi/initdata.rs`. + let timebase_hz = glue::timebase_hz(); + let timebase_khz = timebase_hz / 1000; + let Some(power_sample_clks) = adt.performance.power_sample_clks else { + dev_err!( + dev, + "G16: the ADT gives no GPU power sample period (gpu-pwr-sample-period-aic-clks)\n" + ); + return Err(EINVAL); + }; + let power_sample_us = (u64::from(power_sample_clks) * 1_000_000) + .checked_div(u64::from(timebase_hz)) + .and_then(|us| u32::try_from(us).ok()) + .unwrap_or(0); + let power_sample_period_ms = adt.performance.power_sample_period_ms.unwrap_or(0); + let avg_power_filter_tc_ms = adt.performance.avg_power_filter_tc_ms.unwrap_or(0); + let lowpeak_limiter_tc_ms = adt.performance.lowpeak_limiter_tc_ms.unwrap_or(0); + let lowpeak_limiter_ki_q16 = adt.performance.lowpeak_limiter_ki_q16.unwrap_or(0); + let lowpeak_limiter_kp_q16 = adt.performance.lowpeak_limiter_kp_q16.unwrap_or(0); + if layout.power_sampling.is_some() && (power_sample_us == 0 || avg_power_filter_tc_ms == 0) { + dev_err!( + dev, + "G16: the ADT lacks GPU power sampling parameters (power_sample_us={}, cpu-avg-limiter-input-tc={})\n", + power_sample_us, + avg_power_filter_tc_ms + ); + return Err(EINVAL); + } + if layout.power_limiter.is_some() + && (power_sample_period_ms == 0 + || timebase_khz == 0 + || lowpeak_limiter_tc_ms == 0 + || lowpeak_limiter_ki_q16 == 0 + || lowpeak_limiter_kp_q16 == 0) + { + dev_err!( + dev, + "G16: the ADT lacks GPU low-peak power limiter parameters (period_ms={}, tc_ms={}, ki={}, kp={})\n", + power_sample_period_ms, + lowpeak_limiter_tc_ms, + lowpeak_limiter_ki_q16, + lowpeak_limiter_kp_q16 + ); + return Err(EINVAL); + } + let coredump_copy_size = u64::from(adt.performance.coredump_copy_size.unwrap_or(0)); + if layout.coredump_copy.is_some() && coredump_copy_size == 0 { + dev_err!( + dev, + "G16: the ADT gives no GPU crash copy buffer size (coredump-copy-buffer)\n" + ); + return Err(EINVAL); + } let mut input = wire::Input { performance, + power_sample_clks, + power_sample_us, + power_sample_period_ms, + timebase_khz, + avg_power_filter_tc_ms, + lowpeak_limiter_tc_ms, + lowpeak_limiter_ki_q16, + lowpeak_limiter_kp_q16, + coredump_copy_size, va: [0; wire::OBJECT_COUNT], channel_state: [0; 12], channel_ring: [0; 12], @@ -145,6 +247,7 @@ pub(crate) fn build( lower_parameter: wire::BOOTSTRAP_START + 0x8000, ktrace_mask: 0, progress_recovery: 1, + enabled_cores, }; for i in 0..wire::OBJECT_COUNT { input.va[i] = graph[i].va; @@ -153,28 +256,38 @@ pub(crate) fn build( input.channel_state[i] = channels.submit[i].state.va; input.channel_ring[i] = channels.submit[i].ring.va; } - for (slot, entry) in wire::LOADERS.iter().enumerate() { - if entry.length == 0 { + for (slot, entry) in layout.loaders.iter().enumerate() { + // An empty record, or one this ABI has no slot for, is neither mapped nor described. + if entry.length == 0 || layout.slot(slot).is_none() { continue; } let offset = entry.pa & (wire::PAGE - 1); let at = objects.reserve_io((offset + u64::from(entry.length)).next_multiple_of(wire::PAGE))?; input.loader_va[slot] = at + offset; - for bank in 0..if slot == 3 { 2 } else { 1 } { - let (pa, size, delta) = wire::loader_span(slot, bank).map_err(|()| EINVAL)?; + for bank in 0..entry.banks() { + let (pa, size, delta) = entry.span(bank).map_err(|()| EINVAL)?; objects.map_mmio_class(at + u64::from(delta), pa, u64::from(size), entry.attrs)?; } } - input.scratch = objects.reserve_io(0x8000)?; - // This scratch alias deliberately has firmware RAM attrs, matching the - // qualified owner, even though the target is an SGX register window. - objects.map_mmio_class(input.scratch, 0x300d60000, 0x8000, hw::pte::FW)?; + let scratch = &adt.layout.scratch; + let &(last, _, bytes) = scratch.spans.last().ok_or(EINVAL)?; + let at = objects.reserve_io(last + bytes)?; + input.scratch = at + scratch.pointer; + // The scratch alias uses firmware RAM attributes on these SGX registers. + for &(va_offset, pa_offset, bytes) in scratch.spans { + objects.map_mmio_class( + at + va_offset, + regs.sgx_pa() + scratch.register + pa_offset, + bytes, + hw::pte::FW, + )?; + } // Private CPU-side staging keeps the pure encoder independent of raw GEM // pointers. No staging references survive publication. let mut images = KVec::with_capacity(wire::OBJECT_COUNT, GFP_KERNEL)?; - for size in wire::OBJECT_SIZE { + for size in layout.object_size { images.push(KVVec::from_elem(0u8, size, GFP_KERNEL)?, GFP_KERNEL)?; } { @@ -184,22 +297,36 @@ pub(crate) fn build( } let array: &mut [&mut [u8]; wire::OBJECT_COUNT] = (&mut slices[..]).try_into().map_err(|_| EINVAL)?; - wire::encode(array, &input, 9).map_err(|()| EINVAL)?; + wire::encode_for(layout, array, &input, ceiling).map_err(|()| EINVAL)?; } - let mut loader = [0u8; wire::LOADER_BYTES]; - loader.copy_from_slice(&images[id::MAIN][0x640..0x640 + wire::LOADER_BYTES]); - // Host startup policy: Main and PowerPerformance contain S9, but the + let records = layout.loader_records(); + let mut loader = KVec::with_capacity(records * wire::LOADER_STRIDE, GFP_KERNEL)?; + loader.extend_from_slice( + images[id::MAIN] + .get(0x640..0x640 + records * wire::LOADER_STRIDE) + .ok_or(EINVAL)?, + GFP_KERNEL, + )?; + // Host startup policy: Main and PowerPerformance contain the top row, but the // published selectors remain S1 until the thermal owner admits a raise. - for at in globals::PSTATE_SELECTORS { + for at in layout.pstate_selectors { images[id::GLOBALS][at..at + 4].copy_from_slice(&100u32.to_le_bytes()); } for i in 0..wire::OBJECT_COUNT { graph[i].write(0, &images[i])?; } - dev_info!(dev, "M4 initdata: 31 objects, 12 submit channel pairs, 42 loader records, S1 startup (S9 tables)\n"); + dev_info!( + dev, + "M4 initdata ({}): 31 objects, 12 submit channel pairs, {} register-map slots, S1 startup (S{} tables)\n", + layout.name, + records, + ceiling + ); Ok(( InitData { + abi, + layout, globals: Some(graph[id::GLOBALS].clone()), control: Some(graph[id::FIRMWARE_DATA].clone()), ready_control: Some(graph[id::CONTROL].clone()), @@ -213,6 +340,7 @@ pub(crate) fn build( uma: graph[id::UMA].clone(), parameter: graph[id::PARAMETER].clone(), root: graph[id::ROOT].clone(), + rows, loader, _graph: graph, }, diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 31f06c80ab8bf5..a5dbc19b7d3e94 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -29,19 +29,23 @@ //! [`mmu::VmJobGuard`] keeps the VM's mappings and its VM state keeps the VM's TTBAT slot until //! the last `Arc` drops. -use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{ - c_str, device, + c_str, + cpu::CpuId, + cpumask::Cpumask, + device, dma_fence::Fence, drm::sched, new_mutex, prelude::*, sync::{Arc, Mutex}, + workqueue, }; use super::{ - command::{Command, Order}, - fence::JobFence, + command::{Command, Commands, Order, Orders}, + fence::{FenceOrigin, FwWaits, InputFences, JobFence}, hw, queue::QueueState, vm::VmState, @@ -93,18 +97,26 @@ pub(crate) struct Job { /// The job's VM (TTBAT slot, status). pub(crate) vm: Arc, /// Validated commands, in submission order (at most 64). - pub(crate) commands: KVec, + pub(crate) commands: Commands, + /// Any command traces rays or builds acceleration structures (`Command::long`). + long: bool, pub(crate) resources: super::resources::Prepared, /// Immutable dependency/order ledger, one entry for every accepted command. - orders: KVec, + orders: Orders, /// The job's hardware fence. pub(crate) fence: JobFence, /// The engine's bookkeeping; `progress.signaled` makes [`Job::complete`] act once. pub(crate) progress: super::engine::Progress, /// Inputs and resolved historical-prefix dependencies, held through every command. - inputs: KVec, - /// Consecutive commands with full owner-retirement proof; an aborted receipt never counts. - full_retired: AtomicU32, + inputs: InputFences, + /// Exported fence identity for same-GPU, same-VM cross-queue firmware handoff. + pub(crate) origin: Arc, + /// Same-GPU, same-VM cross-queue waits resolved into firmware ring barriers. + pub(crate) fw_waits: FwWaits, + /// Bitmask of commands (`0..MAX_COMMANDS`) with full owner-retirement proof; an aborted + /// receipt never sets its bit. Tracks per-command bits so concurrent compute/render + /// commands within one job may retire in either hardware completion order. + full_retired: AtomicU64, /// No future publication and every previously published owner fully retired. This proof /// is separate from an error result: an affected full receipt may still fail the job. terminal_retired: AtomicBool, @@ -129,16 +141,19 @@ impl Job { id: u64, queue: Arc, vm: Arc, - commands: KVec, - orders: KVec, + commands: Commands, + orders: Orders, resources: super::resources::Prepared, fence: JobFence, guard: mmu::VmJobGuard, - inputs: KVec, + inputs: InputFences, + origin: Arc, + fw_waits: FwWaits, ) -> Result> { if commands.len() != orders.len() { return Err(EINVAL); } + let long = commands.iter().any(Command::long); let progress = super::engine::Progress::new(commands.len()); let guard = MappingGuard { guard, @@ -150,12 +165,15 @@ impl Job { queue, vm, commands, + long, orders, resources, fence, progress, inputs, - full_retired: AtomicU32::new(0), + origin, + fw_waits, + full_retired: AtomicU64::new(0), terminal_retired: AtomicBool::new(false), // Scheduler free can race the final off-lock completion reference. // Prepare destruction work before acceptance; dropping a completed job @@ -169,9 +187,16 @@ impl Job { ) } + /// The job gets the long execution allowance (ray traversal or acceleration-structure + /// builds, `recovery::logic::LONG_DEADLINE_MS`). + pub(crate) fn long(&self) -> bool { + self.long + } + /// Latches a hardware/publication failure before any later work can be published. /// Called under the device lock; it deliberately does not signal the fence. pub(crate) fn latch_failure(&self, error: Error) { + self.origin.mark_failed(); if error == ECANCELED || (self.terminal_retired.load(Ordering::Acquire) && error != EIO @@ -211,6 +236,7 @@ impl Job { return; } if let Err(error) = result { + self.origin.mark_failed(); if error == ECANCELED || ((!engine || self.terminal_retired.load(Ordering::Acquire)) && error != EIO @@ -232,10 +258,48 @@ impl Job { self.fence.signal(result); } + /// Whether this job has already been handed to the engine (inline or by drm_sched). + pub(crate) fn is_started(&self) -> bool { + self.started.load(Ordering::Acquire) + } + + /// Attempts to submit a ready job directly from SUBMIT ioctl context, bypassing `drm_sched`. + /// Only runs when all input fences are already signalled, the device and VM are healthy, + /// and the GPU is neither sleeping nor recovering; returns `true` when the job was started + /// inline (accepted or already finished with error), or `false` to fall back to `drm_sched`. + pub(crate) fn try_start_inline(self: &Arc, shared: &Arc) -> bool { + if shared.crashed.load(Ordering::Acquire) + || shared.sleeping.load(Ordering::Acquire) + || shared.recovering.load(Ordering::Acquire) + || self.vm.status.get() != 0 + { + return false; + } + if let Some(order) = self.orders.first() { + if self.queue.check(order).is_err() { + return false; + } + } + if super::fence::check_dependencies(&self.inputs).is_err() { + return false; + } + if let Some(result) = shared.try_submit_inline(self.clone()) { + self.started.store(true, Ordering::Release); + if let Err(error) = result { + self.finish(Err(if error == ENODEV { EIO } else { error }), false); + } + true + } else { + false + } + } + /// Hands the job to the engine, or refuses a failed GPU or VM. A queued /// job may have been accepted before another command made its VM sticky. fn start(self: &Arc, shared: &Arc) { - self.started.store(true, Ordering::Release); + if self.started.swap(true, Ordering::AcqRel) { + return; + } if shared.crashed.load(Ordering::Acquire) { self.finish(Err(EIO), false); return; @@ -258,6 +322,7 @@ impl Job { // before signalling; later accepted ordinals must not jump this hole. self.queue.cancel(&self.orders, self.progress.sent()); self.finish(Err(ECANCELED), false); + shared.wake_publish(); return; } // `Shared::submit`: enqueue, publish and rearm under the device lock, @@ -268,6 +333,155 @@ impl Job { } } + /// Returns the immutable dependency order for command `index`. + pub(crate) fn command_order(&self, index: u32) -> Option { + self.orders.get(index as usize).copied() + } + + /// Whether command `index` is a ready, barrier-free compute command continuing a compute + /// horizon at queue-local compute ordinal `expected`. + pub(crate) fn can_fold_horizon_cmd(&self, index: u32, expected: u64) -> bool { + if !self.fw_waits.is_empty() + || self.terminal_retired.load(Ordering::Acquire) + || self.vm.status.get() != 0 + { + return false; + } + let Some(Command::Compute(_)) = self.commands.get(index as usize) else { + return false; + }; + let Some(order) = self.orders.get(index as usize) else { + return false; + }; + order.engine == super::command::COMPUTE + && order.sequence == expected + && order.wait_through == [None, None] + && self.queue.check(order).is_ok() + && super::fence::check_dependencies(&self.inputs).is_ok() + } + + /// Whether every command of this job is a ready, barrier-free compute command continuing + /// sequentially from `first_expected`. + pub(crate) fn can_fold_horizon_job(&self, first_expected: u64) -> bool { + let count = self.progress.count(); + if count == 0 + || !self.fw_waits.is_empty() + || self.progress.sent() != 0 + || self.terminal_retired.load(Ordering::Acquire) + || self.vm.status.get() != 0 + || super::fence::check_dependencies(&self.inputs).is_err() + { + return false; + } + for k in 0..count { + let Some(expected) = first_expected.checked_add(u64::from(k)) else { + return false; + }; + let Some(Command::Compute(_)) = self.commands.get(k as usize) else { + return false; + }; + let Some(order) = self.orders.get(k as usize) else { + return false; + }; + if order.engine != super::command::COMPUTE + || order.sequence != expected + || order.wait_through != [None, None] + || self.queue.check(order).is_err() + { + return false; + } + } + true + } + + /// Whether command `index` is a ready render command continuing a same-SUBMIT render batch + /// at queue-local render ordinal `expected` (treating `expected - 1` as already published + /// within the in-progress render flight). + pub(crate) fn can_fold_render_cmd(&self, index: u32, expected: u64) -> bool { + if !self.fw_waits.is_empty() + || self.terminal_retired.load(Ordering::Acquire) + || self.vm.status.get() != 0 + { + return false; + } + let Some(Command::Render(_)) = self.commands.get(index as usize) else { + return false; + }; + let Some(order) = self.orders.get(index as usize) else { + return false; + }; + if order.engine != super::command::RENDER + || order.sequence != expected + || self.queue.check(order).is_err() + || super::fence::check_dependencies(&self.inputs).is_err() + { + return false; + } + let completed = self + .queue + .completed + .each_ref() + .map(|value| value.load(Ordering::Acquire)); + let mut published = self + .queue + .published + .each_ref() + .map(|value| value.load(Ordering::Acquire)); + published[super::command::RENDER] = + published[super::command::RENDER].max(expected.saturating_sub(1)); + order.ready(completed, published) + } + + /// Whether every command of this job is a ready render command continuing a render + /// horizon sequentially from `first_expected` (treating earlier passes in the in-progress + /// render flight as already published). + pub(crate) fn can_fold_render_horizon_job(&self, first_expected: u64) -> bool { + let count = self.progress.count(); + if count == 0 + || !self.fw_waits.is_empty() + || self.progress.sent() != 0 + || self.terminal_retired.load(Ordering::Acquire) + || self.vm.status.get() != 0 + || super::fence::check_dependencies(&self.inputs).is_err() + { + return false; + } + let completed = self + .queue + .completed + .each_ref() + .map(|value| value.load(Ordering::Acquire)); + let base_published = self + .queue + .published + .each_ref() + .map(|value| value.load(Ordering::Acquire)); + for k in 0..count { + let Some(expected) = first_expected.checked_add(u64::from(k)) else { + return false; + }; + let Some(Command::Render(_)) = self.commands.get(k as usize) else { + return false; + }; + let Some(order) = self.orders.get(k as usize) else { + return false; + }; + if order.engine != super::command::RENDER + || order.sequence != expected + || self.queue.check(order).is_err() + { + return false; + } + let mut published = base_published; + published[super::command::RENDER] = + published[super::command::RENDER].max(expected.saturating_sub(1)); + if !order.ready(completed, published) { + return false; + } + } + true + } + /// Checks the retained dependency set for each command immediately before publication. /// Never waits or signals fences under the device lock. The scheduler and start() have /// already waited; a pending fence asks the engine to defer rather than publish early. @@ -285,12 +499,30 @@ impl Job { let order = self.orders.get(index as usize).ok_or(EINVAL)?; self.queue.check(order)?; super::fence::check_dependencies(&self.inputs)?; + for wait in self.fw_waits.iter() { + if wait.is_failed() { + return Err(ECANCELED); + } + for engine in 0..2 { + if let Some(seq) = wait.last_ordinal[engine] { + wait.queue.cancelled_through(engine, seq)?; + if wait.queue.published[engine].load(Ordering::Acquire) < seq { + return Err(EAGAIN); + } + } + } + } let completed = self .queue .completed .each_ref() .map(|value| value.load(Ordering::Acquire)); - if !order.ready(completed) { + let published = self + .queue + .published + .each_ref() + .map(|value| value.load(Ordering::Acquire)); + if !order.ready(completed, published) { return Err(EAGAIN); } Ok(()) @@ -299,31 +531,92 @@ impl Job { /// Advances exactly one queue-local engine ordinal after a full successful wire receipt. /// Called under the device lock before another command is considered. No allocation, /// fence callback or aggregate-job completion occurs here. + /// Advances the queue's published frontier past command `index` (under the device + /// lock, when its first producer became visible). + pub(crate) fn command_published(&self, index: u32) { + if let Some(order) = self.orders.get(index as usize) { + self.queue.published[order.engine].fetch_max(order.sequence, Ordering::AcqRel); + } + } + pub(crate) fn command_retired(&self, index: u32) -> Result { let order = self.orders.get(index as usize).ok_or(EINVAL)?; let previous = order.sequence.checked_sub(1).ok_or(EINVAL)?; - self.queue.completed[order.engine] - .compare_exchange( - previous, - order.sequence, - Ordering::AcqRel, - Ordering::Acquire, - ) - .map_err(|_| EIO)?; + if order.engine != super::command::COMPUTE { + self.queue.completed[order.engine] + .compare_exchange( + previous, + order.sequence, + Ordering::AcqRel, + Ordering::Acquire, + ) + .map_err(|_| EIO)?; + return Ok(()); + } + // Concurrent 2-pipe compute commands on the same logical queue may retire out of + // sequence order. Record published out-of-order full receipts above `completed + 1` + // in `compute_ooo` and advance `completed[COMPUTE]` across contiguous retired runs. + let completed = self.queue.completed[super::command::COMPUTE].load(Ordering::Acquire); + if order.sequence <= completed { + return Err(EIO); + } + if order.sequence == completed + 1 { + let mut next = order.sequence; + let mut ooo = self.queue.compute_ooo.load(Ordering::Acquire); + while ooo & 1 != 0 { + next += 1; + ooo >>= 1; + } + // Re-anchor remaining OOO bits above `next + 1` (since `next` advanced by at least 1 + // and bit 0 of `ooo` is now `next + 1`, which is 0). + ooo >>= 1; + self.queue.compute_ooo.store(ooo, Ordering::Release); + self.queue.completed[super::command::COMPUTE] + .compare_exchange(completed, next, Ordering::AcqRel, Ordering::Acquire) + .map_err(|_| EIO)?; + return Ok(()); + } + let published = self.queue.published[super::command::COMPUTE].load(Ordering::Acquire); + let shift = order.sequence - completed - 2; + if order.sequence > published || shift >= 64 { + return Err(EIO); + } + let bit = 1u64 << shift; + let ooo = self.queue.compute_ooo.load(Ordering::Acquire); + if ooo & bit != 0 { + return Err(EIO); + } + self.queue.compute_ooo.store(ooo | bit, Ordering::Release); Ok(()) } - /// Records a consecutive full owner receipt independently of success/error attribution. + /// Records a unique full owner receipt independently of success/error attribution. /// Only the receipt owner may call this after successful resource-ledger retirement. pub(crate) fn note_full_retirement(&self, first: u32, count: u32) -> Result { let end = first.checked_add(count).ok_or(EOVERFLOW)?; - if count == 0 || end > self.progress.sent() { + if count == 0 || end > self.progress.sent() || end > 64 { return Err(EINVAL); } - self.full_retired - .compare_exchange(first, end, Ordering::AcqRel, Ordering::Acquire) - .map_err(|_| EIO)?; - Ok(()) + let bits = if count == 64 { + u64::MAX + } else { + ((1u64 << count) - 1) << first + }; + let mut current = self.full_retired.load(Ordering::Acquire); + loop { + if current & bits != 0 { + return Err(EIO); + } + match self.full_retired.compare_exchange_weak( + current, + current | bits, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => return Ok(()), + Err(observed) => current = observed, + } + } } /// Certifies a terminal job before publishing its error. The caller first removes it @@ -332,9 +625,14 @@ impl Job { /// A never-published job has the same proof with all three counters equal to zero. pub(crate) fn mark_terminal_retired(&self) -> Result { let sent = self.progress.sent(); + let expected = if sent >= 64 { + u64::MAX + } else { + (1u64 << sent) - 1 + }; if self.progress.is_pending() || self.progress.next() != sent - || self.full_retired.load(Ordering::Acquire) != sent + || self.full_retired.load(Ordering::Acquire) != expected { return Err(EIO); } @@ -342,6 +640,11 @@ impl Job { Ok(()) } + /// Whether this job holds a cross-queue firmware wait on `queue`. + pub(crate) fn waits_on_queue(&self, queue: &Arc) -> bool { + self.fw_waits.iter().any(|w| Arc::ptr_eq(&w.queue, queue)) + } + /// Cancels a job the scheduler never ran (queue teardown, or a failed submission). fn cancel_unstarted(&self) { if self.started.swap(true, Ordering::AcqRel) { @@ -351,6 +654,7 @@ impl Job { self.finish(Err(ECANCELED), false); } else if !self.progress.signaled.swap(true, Ordering::AcqRel) { // A refused submission's job: its fence orders nothing and was never published. + self.origin.mark_failed(); self.fence.signal(Err(ECANCELED)); } } @@ -376,6 +680,10 @@ impl Completions { } } + pub(crate) fn is_empty(&self) -> bool { + self.head.is_none() + } + /// Queues the first completion of `job`; subsequent attempts have no effect. pub(crate) fn push(&mut self, job: &Arc, result: Result) { { @@ -422,6 +730,20 @@ pub(crate) fn complete_all(mut done: Completions) { struct SchedJob { job: Arc, shared: Arc, + /// Count of queued (unstarted) `drm_sched` jobs on this queue. Decremented once when + /// `run()`, `cancel()`, or `drop()` completes so inline submission preserves queue order + /// without retaining `Arc` in [`Scheduler`]. + pending_sched: Arc, + counted: bool, +} + +impl SchedJob { + fn finish_pending(&mut self) { + if self.counted { + self.counted = false; + self.pending_sched.fetch_sub(1, Ordering::AcqRel); + } + } } impl sched::JobImpl for SchedJob { @@ -435,6 +757,7 @@ impl sched::JobImpl for SchedJob { fn run(job: &mut Self) -> Result> { let fence = job.job.fence.fence(); job.job.start(&job.shared); + job.finish_pending(); Ok(Some(fence)) } @@ -445,6 +768,7 @@ impl sched::JobImpl for SchedJob { fn cancel(job: &mut Self) { job.job.cancel_unstarted(); + job.finish_pending(); } } @@ -452,6 +776,7 @@ impl Drop for SchedJob { fn drop(&mut self) { // Entity teardown frees jobs it never ran without calling `cancel`. self.job.cancel_unstarted(); + self.finish_pending(); } } @@ -461,31 +786,65 @@ pub(crate) struct Scheduler { // drains), and only then the scheduler is finalized. entity: sched::Entity, _scheduler: sched::Scheduler, + /// Number of jobs currently queued in `drm_sched` that have not yet started or cancelled. + /// Inline submit is permitted only when zero, preserving strict queue order without + /// retaining any `Arc` (or its `VmJobGuard` / prepared arenas). + pending_sched: Arc, } impl Scheduler { pub(crate) fn new(dev: &device::Device) -> Result { - let scheduler = sched::Scheduler::new( + // Keep drm_sched run/free work in the creating CPU's cluster (matching g17/job.rs). + // Completion work still follows the per-submit submitter_cpu, not queue creation, and + // an unbound workqueue restricted via apply_workqueue_attrs() falls back to + // wq_unbound_cpumask if the cluster goes offline (failing soft if restrict() errors). + let submit = workqueue::OwnedQueue::new_ordered_reclaim(c_str!("aurora_g16"))?; + let _ = submit.restrict(Cpumask::cluster_of(CpuId::current())); + let scheduler = sched::Scheduler::new_with_queues( dev, 1, hw::sizes::SCHEDULER_CREDITS, 0, hw::tuning::SCHED_TIMEOUT_MS, c_str!("aurora_g16"), + Some(submit), + None, )?; // With one run queue, only the kernel priority is valid. let entity = sched::Entity::new(&scheduler, sched::Priority::Kernel)?; + let pending_sched = Arc::new(core::sync::atomic::AtomicUsize::new(0), GFP_KERNEL)?; Ok(Self { entity, _scheduler: scheduler, + pending_sched, }) } - /// Pushes a job that waits for its retained inputs. On failure the job is cancelled (not counted as - /// submitted work of its VM) and the error is returned. + /// Pushes a job that waits for its retained inputs. When the predecessor has already + /// started and all inputs are signalled, submits directly inline and bypasses `drm_sched` + /// allocation and kworker wakeup. On failure the job is cancelled (not counted as submitted + /// work of its VM) and the error is returned. pub(crate) fn push(&mut self, job: Arc, shared: Arc) -> Result { + shared.note_submitter(); + let prev_started = self.pending_sched.load(Ordering::Acquire) == 0; let handle = job.clone(); - let mut pending = self.entity.new_job(1, SchedJob { job, shared })?; + if prev_started { + handle.accepted.store(true, Ordering::Release); + if handle.try_start_inline(&shared) { + return Ok(()); + } + handle.accepted.store(false, Ordering::Release); + } + self.pending_sched.fetch_add(1, Ordering::AcqRel); + let mut pending = self.entity.new_job( + 1, + SchedJob { + job, + shared, + pending_sched: self.pending_sched.clone(), + counted: true, + }, + )?; for fence in handle.inputs.iter() { pending.add_dependency(fence.clone())?; } diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index f161b218a0d06b..61aa199f8cb16c 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -1,11 +1,12 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! G16 GPU support (T8132, M4: J713; the qualified 25G83 firmware). +//! Classic GPU support for T8132 G16G (25G83 and 26B123), T6030 G15S (26B123) and T8122 G15G +//! (26B123). //! -//! G16 firmware is *classic*: one ring per engine (TA, FS, compute) and ordering expressed by +//! Classic firmware uses one ring per engine (TA, FS, compute) and expresses ordering through //! in-ring barrier records that wait on another queue's stamp, unlike the G17 kick-ring/QID //! model. The boot loader leaves the firmware loaded; this driver identifies the exact build, -//! adopts the inherited UAT handoff and builds the M4 initdata graph +//! adopts the inherited UAT handoff and builds the InitData graph //! and brings the firmware to READY. All logical queues and VMs share one persistent compute //! graph and one render graph; the commands of a submission are encoded into compute and pass //! slots and published as *prefixes* on the firmware's queues, then retired on their stamps. @@ -14,8 +15,10 @@ //! //! # Plugging into the shared driver //! -//! - [`Driver`] is a separate platform driver for `apple,agx-t8132` with a module alias. Its -//! probe waits for the PMP supplier and the native display before booting firmware. It calls +//! - [`Driver`] matches `apple,agx-t8132`, `apple,agx-t6030` and `apple,agx-t8122`. T6030 and +//! T8122 select this backend through the boot loader's handoff (marker, layout and, on +//! T8122, `apple,firmware-compat` 27.2; see [`adt::claims`]). Probe links a handed-over +//! native display and, on T8132, the PMP supplier before booting firmware. It calls //! [`crate::driver::AsahiPlatformDriver::probe_g16`]. //! - [`Gpu`] implements [`crate::gpu::Gpu`]: GET_PARAMS identity, VM creation (`new_vm`), //! queues (`new_queue`, see [`queue`]) and timestamp buffers. @@ -51,6 +54,7 @@ mod command; mod encode; mod engine; mod event; +mod feed; mod fence; pub(crate) mod fw; mod gate; @@ -67,6 +71,7 @@ mod queue; mod recovery; mod regs; mod resources; +mod rt; mod sleep; mod slots; mod timestamp; @@ -80,12 +85,13 @@ use core::sync::atomic::{AtomicBool, AtomicI32, AtomicPtr, AtomicU32, AtomicU64, use kernel::{ c_str, device::{self, Core}, - impl_has_delayed_work, new_delayed_work, new_mutex, of, platform, + impl_has_delayed_work, impl_has_work, new_delayed_work, new_mutex, new_spinlock, new_work, of, + platform, prelude::*, - sync::{aref::ARef, Arc, Mutex}, + sync::{aref::ARef, Arc, Mutex, SpinLock}, time::hrtimer::{ArcHrTimerHandle, HrTimer}, uapi, - workqueue::{DelayedWork, WorkItem}, + workqueue::{DelayedWork, OwnedQueue, Work, WorkItem}, }; use crate::driver::{AsahiDrmDevice, AsahiPlatformDriver}; @@ -94,45 +100,43 @@ use crate::{alloc, gem, gpu, mmu, regs as shared_regs}; /// Name of the G16 platform driver. pub(crate) const DRIVER_NAME: &CStr = c_str!("aurora-g16"); -/// GPU generation reported to userspace. -pub(crate) const GPU_GENERATION: u32 = 16; - -/// Static configuration of a SoC with a G16 GPU. -pub(crate) struct Config { - /// SoC identifier reported to userspace. - pub(crate) chip_id: u32, - /// GPU variant reported to userspace. - pub(crate) gpu_variant: crate::hw::GpuVariant, - /// GPU revision reported to userspace. - pub(crate) gpu_revision: u32, - /// Input address bits translated by each UAT root. - pub(crate) uat_ias: u32, - /// Output (physical) address bits of the UAT. - pub(crate) uat_oas: u32, - /// Clusters and cores per cluster. - pub(crate) num_clusters: u32, - pub(crate) num_cores_per_cluster: u32, - /// Qualified identification register values. - pub(crate) hw_ids: &'static [hw::HwId], - /// Qualified firmware builds. - pub(crate) firmware: &'static [hw::FirmwareBuild], -} +pub(crate) use hw::Config; /// OF match table of the G16 platform driver. -const OF_TABLE: kernel::device_id::IdArray = - kernel::device_id::IdArray::new([( - of::DeviceId::new(c_str!("apple,agx-t8132")), - &&hw::t8132::CONFIG, - )]); +const OF_TABLE: kernel::device_id::IdArray = + kernel::device_id::IdArray::new([ + ( + of::DeviceId::new(c_str!("apple,agx-t8132")), + &&hw::t8132::CONFIG, + ), + ( + of::DeviceId::new(c_str!("apple,agx-t6030")), + &&hw::t6030::CONFIG, + ), + ( + of::DeviceId::new(c_str!("apple,agx-t8122")), + &&hw::t8122::CONFIG, + ), + ]); // Probe admission waits for the PMP supplier and the native display before // firmware starts, so the module may be loaded at device creation. kernel::of_device_table!( AUTOLOAD_OF_TABLE, @none, - [of::DeviceId::new(c_str!("apple,agx-t8132"))] + [ + of::DeviceId::new(c_str!("apple,agx-t8132")), + of::DeviceId::new(c_str!("apple,agx-t6030")), + of::DeviceId::new(c_str!("apple,agx-t8122")), + ] ); +/// Whether this backend owns `dev` under the configuration of its compatible, so that another +/// backend serving the same compatible steps aside. +pub(crate) fn claims(dev: &device::Device, cfg: &Config) -> bool { + adt::claims(dev, cfg) +} + /// The G16 platform driver: the shared [`AsahiPlatformDriver`] probed through /// [`AsahiPlatformDriver::probe_g16`]. /// @@ -160,6 +164,9 @@ impl platform::Driver for Driver { info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound { let cfg = *info.ok_or(ENODEV)?; + if cfg.needs_handoff_marker && !adt::claims(pdev.as_ref(), cfg) { + return Err(ENODEV); + } dev_info!(pdev.as_ref(), "G16: probing\n"); match AsahiPlatformDriver::probe_g16(pdev, cfg) { Ok(driver) => Ok(Some(driver)), @@ -186,8 +193,49 @@ impl platform::Driver for Driver { } } -/// Work item ID of the poll work. +/// Work item ID of the backup delayed poll work. const POLL_WORK: u64 = 0; +/// Work item ID of the submitter-pinned fast event poll work. +const FAST_POLL_WORK: u64 = 1; +/// Work item ID of the asynchronous displaced pass-slot scrub work. +const SCRUB_WORK: u64 = 2; +/// Work item ID of the asynchronous CPU feed-boost work. +const FEED_WORK: u64 = 3; +/// Work item ID of the unbound fast event poll work used when pipelined (`active_flights >= 2`). +const UNBOUND_POLL_WORK: u64 = 4; +/// Capacity hint for `drm_syncobj_wait` during active submit bursts (mirroring G17's wait hint). +const WAIT_UTIL_MIN: u32 = 512; +const WAIT_HINT_MS: u32 = 8; +const WAIT_HINT_GAP_NS: u64 = 4_000_000; +const WAIT_HINT_STREAK_ON: u32 = 8; +const WAIT_HINT_LINGER_NS: u64 = 8_000_000; + +/// A firmware session retained until reboot after a failed boot or backend start. +pub(crate) enum Retained { + Orphan(KBox), + Booted(KBox), + Firmware(KBox), +} + +impl Retained { + fn drain(&mut self) -> Result { + match self { + Self::Orphan(orphan) => orphan.drain(), + Self::Booted(booted) => { + let booted = &mut **booted; + booted + .channels + .drain_rings(&booted.session.dev, &mut booted.events) + } + Self::Firmware(firmware) => { + let firmware = &mut **firmware; + firmware + .channels + .drain_rings(&firmware.session.dev, &mut firmware.events) + } + } + } +} /// Device state shared with the RTKit callbacks and the poll work. #[pin_data] @@ -203,6 +251,34 @@ pub(crate) struct Shared { pub(crate) crashed: AtomicBool, /// Set by the firmware's EP 0x20 event message; consumed by the poll work. pub(crate) evented: AtomicBool, + /// Set by external state changes (VM teardown, unstarted queue cancellation) so the next + /// `poll_step()` re-evaluates `publish_checked()` even while unrelated flights are active. + pub(crate) publish_wake: AtomicBool, + /// Set on VM close and when its last unpublished render reservation is released. + /// Re-armed while a closed VM still holds a lease awaiting reclaim. + pub(crate) closed_vm_reclaim: AtomicBool, + /// CPU that last submitted work, for placing the per-CPU completion worker. + pub(crate) submitter: AtomicU32, + /// CPU whose cluster currently restricts `events_unbound` (`u32::MAX` before first pin). + unbound_cluster_cpu: AtomicU32, + /// Serializes best-effort `events_unbound.restrict()` updates without blocking concurrent + /// submitters on `wq_pool_mutex`. + unbound_pinning: AtomicBool, + /// Number of flights currently active under `Shared::state`, for poll worker placement. + pub(crate) active_flights: AtomicU32, + /// Smoothed recent flight duration in microseconds (0 before first retirement), used to + /// shorten the fallback hrtimer interval on sub-100 us workloads. + pub(crate) ewma_flight_us: AtomicU32, + /// Monotonic timestamp (ns) of the previous submit, for active-burst wait hints. + pub(crate) last_submit_ns: AtomicU64, + /// Consecutive back-to-back submits within [`WAIT_HINT_GAP_NS`]. + pub(crate) wait_hint_streak: AtomicU32, + /// Monotonic deadline (ns) until which `syncobj_wait_hint` stays active (0 when expired). + pub(crate) wait_hint_until_ns: AtomicU64, + /// Next armed hrtimer expiry (monotonic ns, 0 when disarmed). + pub(crate) resnap_deadline_ns: AtomicU64, + /// Next 1-jiffy backup delayed-work schedule bound (monotonic ns). + pub(crate) backup_deadline_ns: AtomicU64, // --- RTKit callback state and a retained failed session. --- /// The first latched error, as a negative errno. pub(crate) error: AtomicI32, @@ -217,14 +293,48 @@ pub(crate) struct Shared { /// From a system sleep's `.prepare` until the firmware restarted: nothing reads its /// registers and nothing is published. pub(crate) sleeping: AtomicBool, + /// Firmware recovery is active under `Shared::state` (may sleep up to 1000 ms). + pub(crate) recovering: AtomicBool, + /// Whether any base compute unit (`0..BASE_COMPUTE_UNITS`) has been quarantined. + pub(crate) base_compute_quarantined: AtomicBool, + /// Bitmask of permanently quarantined device-wide compute units (`0..COMPUTE_UNITS`). + pub(crate) quarantined_compute_mask: AtomicU32, + /// Whether any base render pass slot (`0..BASE_RENDER_SLOTS`) has been quarantined. + pub(crate) base_render_quarantined: AtomicBool, + /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). + pub(crate) quarantined_pb_mask: AtomicU32, + /// Round-robin cursor assigning each rendering VM a `[home, alt]` pair in `0..WARM_PB_SLOTS`. + pub(crate) next_pb_slot: AtomicU32, + /// Live open VMs that own a `RenderArena`, used to size multi-VM pass-slot headroom. + pub(crate) active_render_vms: Arc, /// The GFX power state word from before a system sleep. sleep_ps: AtomicU32, /// The stop left to a system sleep's commit, until `.complete` finishes it. sleep_commit: AtomicPtr, + /// Dedicated high-priority per-CPU workqueue for immediate completion polling. + pub(crate) events: OwnedQueue, + /// Dedicated high-priority unbound workqueue for pipelined (`active_flights >= 2`) polling. + pub(crate) events_unbound: OwnedQueue, + /// Dedicated unbound workqueue for asynchronous off-lock pass-slot WC scrubbing. + pub(crate) scrub_wq: OwnedQueue, + /// Host-refill CPU frequency floor actuator (mirroring G17's feed worker). + pub(crate) feed: Arc, + /// Dedicated unbound workqueue for cpufreq `FREQ_QOS_MIN` updates outside `Shared::state`. + pub(crate) feed_wq: OwnedQueue, #[pin] - pub(crate) orphan: Mutex>>, + pub(crate) orphan: Mutex>, #[pin] pub(crate) poll: DelayedWork, + #[pin] + pub(crate) fast_poll: Work, + #[pin] + pub(crate) fast_poll_unbound: Work, + #[pin] + pub(crate) scrub_queue: SpinLock>, + #[pin] + pub(crate) scrub_work: Work, + #[pin] + pub(crate) feed_work: Work, // --- The completion/repoll hrtimer and the handle of its current expiry (dropping it // cancels the expiry; see `Shared::rearm`). --- #[pin] @@ -240,6 +350,22 @@ impl_has_delayed_work! { impl HasDelayedWork for Shared { self.poll } } +impl_has_work! { + impl HasWork for Shared { self.fast_poll } +} + +impl_has_work! { + impl HasWork for Shared { self.scrub_work } +} + +impl_has_work! { + impl HasWork for Shared { self.feed_work } +} + +impl_has_work! { + impl HasWork for Shared { self.fast_poll_unbound } +} + impl WorkItem for Shared { type Pointer = Arc; fn run(this: Arc) { @@ -251,17 +377,148 @@ impl WorkItem for Shared { } } +impl WorkItem for Shared { + type Pointer = Arc; + fn run(this: Arc) { + if this.orphaned.load(Ordering::Acquire) { + this.drain_orphan(); + return; + } + this.run_poll(); + } +} + +impl WorkItem for Shared { + type Pointer = Arc; + fn run(this: Arc) { + this.run_scrubs(); + } +} + +impl WorkItem for Shared { + type Pointer = Arc; + fn run(this: Arc) { + this.feed.run(); + } +} + +impl WorkItem for Shared { + type Pointer = Arc; + fn run(this: Arc) { + if this.orphaned.load(Ordering::Acquire) { + this.drain_orphan(); + return; + } + this.run_poll(); + } +} + impl Shared { + /// Records the submitting CPU and burst cadence for completion placement and wait hints. + /// Runs in process context during SUBMIT; keeps `events_unbound` pinned to the submitter's + /// CPU cluster so pipelined completion polls stay on the same cluster (avoiding E-core + /// wake bounces while still sparing the submitter CPU itself). + pub(crate) fn note_submitter(&self) { + let cpu = kernel::cpu::CpuId::current(); + self.submitter.store(cpu.as_u32(), Ordering::Relaxed); + let pinned = self.unbound_cluster_cpu.load(Ordering::Acquire); + if pinned != cpu.as_u32() + && !kernel::cpu::CpuId::from_u32(pinned) + .is_some_and(|p| kernel::cpumask::Cpumask::cluster_of(p).test(cpu)) + && self + .unbound_pinning + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed) + .is_ok() + { + if self + .events_unbound + .restrict(kernel::cpumask::Cpumask::cluster_of(cpu)) + .is_ok() + { + self.unbound_cluster_cpu + .store(cpu.as_u32(), Ordering::Release); + } + self.unbound_pinning.store(false, Ordering::Release); + } + let now = engine::now_ns(); + let prev = self.last_submit_ns.swap(now, Ordering::Relaxed); + if prev != 0 && now.wrapping_sub(prev) <= WAIT_HINT_GAP_NS { + let streak = self + .wait_hint_streak + .fetch_add(1, Ordering::Relaxed) + .saturating_add(1); + if streak >= WAIT_HINT_STREAK_ON { + self.wait_hint_until_ns + .store(now.saturating_add(WAIT_HINT_LINGER_NS), Ordering::Relaxed); + } + } else { + self.wait_hint_streak.store(1, Ordering::Relaxed); + } + } + + /// Updates the lock-free EWMA of recent retired flight durations (microseconds). + /// Decays faster downward than upward so transitions from heavy flights into short + /// bursts tighten the adaptive repoll window within a few completions. + pub(crate) fn note_flight_us(&self, us: u32) { + let prev = self.ewma_flight_us.load(Ordering::Relaxed); + let next = if prev == 0 { + us + } else if us < prev { + prev.saturating_add(us) / 2 + } else { + (prev.saturating_mul(3).saturating_add(us)) / 4 + }; + self.ewma_flight_us.store(next, Ordering::Relaxed); + } + + /// Temporary `drm_syncobj_wait` capacity hint while a client is submitting back to back. + pub(crate) fn syncobj_wait_hint(&self) -> Option<(u32, u32)> { + self.feed.wait_hint().or_else(|| { + let until = self.wait_hint_until_ns.load(Ordering::Relaxed); + if cfg!(CONFIG_UCLAMP_TASK) && until != 0 && engine::now_ns() <= until { + Some((WAIT_UTIL_MIN, WAIT_HINT_MS)) + } else { + None + } + }) + } + + /// Wakes the CPU feed-boost worker outside `Shared::state` when refill gaps cross threshold. + pub(crate) fn queue_feed(self: &Arc) { + if !self.sleeping.load(Ordering::Acquire) && self.feed.take_pending() { + let _ = self.feed_wq.enqueue::, FEED_WORK>(self.clone()); + } + } + + /// Last recorded submitting CPU, if valid. + pub(crate) fn submitter_cpu(&self) -> Option { + kernel::cpu::CpuId::from_u32(self.submitter.load(Ordering::Relaxed)) + } + /// Queues the poll work immediately. Callable from any context. pub(crate) fn kick(self: &Arc) { self.evented.store(true, Ordering::Release); - // `mod_delayed_work(.., 0)` so that a kick also runs a poll whose 1-jiffy backup is - // pending (a plain enqueue is refused then). self.poll_now(); } + /// Marks external publish-relevant state dirty and queues a poll so pending jobs re-evaluate + /// without waiting for the 1 ms housekeeping tick. + pub(crate) fn wake_publish(self: &Arc) { + self.publish_wake.store(true, Ordering::Release); + if self.started.load(Ordering::Acquire) && !self.sleeping.load(Ordering::Acquire) { + self.poll_now(); + } + } + + /// Arms and wakes the poll worker to reclaim closed VM leases. + pub(crate) fn wake_closed_vm_reclaim(self: &Arc) { + self.closed_vm_reclaim.store(true, Ordering::Release); + self.wake_publish(); + } + /// Latches the fail-stop state. pub(crate) fn fail_stop(&self, error: Error) { + self.feed.begin_shutdown(); let _ = self.error .compare_exchange(0, error.to_errno(), Ordering::AcqRel, Ordering::Acquire); @@ -288,36 +545,26 @@ impl Shared { /// Keeps a firmware session that did not complete until reboot; its receive rings stay /// drained by the poll work. - pub(crate) fn orphan(&self, orphan: boot::Orphan) { + #[cold] + #[inline(never)] + pub(crate) fn retain_failed(&self, retained: Retained) { let mut slot = self.orphan.lock(); if slot.is_some() { // Never replace and drop an already firmware-reachable session. - core::mem::forget(orphan); + core::mem::forget(retained); dev_err!( self.dev.as_ref(), "G16: additional failed session retained without drain\n" ); return; } - match KBox::::new_uninit(GFP_KERNEL) { - Ok(storage) => { - *slot = Some(KBox::write(storage, orphan)); - self.orphaned.store(true, Ordering::Release); - } - // Without memory for the box, leak the parts as they are. - Err(_) => { - core::mem::forget(orphan); - dev_err!( - self.dev.as_ref(), - "G16: cannot keep the failed session; leaked\n" - ); - } - } + *slot = Some(retained); + self.orphaned.store(true, Ordering::Release); } /// Drains the receive rings of an orphaned session. fn drain_orphan(&self) { - if let Some(orphan) = self.orphan.lock().as_deref_mut() { + if let Some(orphan) = &mut *self.orphan.lock() { let _ = orphan.drain(); } } @@ -329,6 +576,8 @@ impl Shared { /// be stopped, so dropping this structure leaks the firmware-visible parts on purpose /// ([`Gpu::retain`]). pub(crate) struct Firmware { + /// Static hardware configuration for this GPU instance. + pub(crate) cfg: &'static hw::Config, /// RTKit, MMIO, regions, the adopted UAT and the host window. pub(crate) session: boot::Session, /// The initdata graph and its live words (Globals, Control, HardwareData, ...). @@ -351,9 +600,13 @@ pub(crate) struct Firmware { /// PMP thermal vote and firmware DVFS ceiling state. pub(crate) power: power::Power, /// Render UMA/PB allocators, their spare set and parameter-buffer growth. - pub(crate) pools: pools::Pools, + pub(crate) pools: KBox, /// Live VMs and their exclusive TTBAT slots, and the client aliases of every user VM. pub(crate) vms: Arc, + /// Monotonic timestamp (ns) of the last full housekeeping pass (power, health, hang poll). + pub(crate) last_housekeeping_ns: u64, + /// Monotonic timestamp (ns) of the last auxiliary (log/ktrace/stats) ring drain. + pub(crate) last_aux_drain_ns: u64, } /// A G16 GPU. @@ -367,12 +620,16 @@ pub(crate) struct Gpu { pub(crate) shared: Arc, /// The adopted UAT, for creating and binding user VMs without the device lock. pub(crate) uat: Arc, + /// Live VM registry, kept directly on `Gpu` so `vm_closed()` still breaks resource-cache + /// cycles even if `shared.state` is absent (fail-stop or teardown). + vms: Arc, } impl Gpu { /// Admits and boots a G16 GPU: identity checks, PMP AGX vote, RTKit, UAT handoff, initdata, /// READY, then the compute and render graphs. On success the module is pinned: the /// firmware session lasts until reboot. + #[inline(never)] pub(crate) fn new( pdev: &platform::Device>, dev: &AsahiDrmDevice, @@ -386,6 +643,14 @@ impl Gpu { // pin_init exposes initialized fields by name, so `dev` is shadowed after // the platform-device field. Retain the typed DRM device before that point. let drm_device: ARef = dev.into(); + let events = OwnedQueue::new_percpu_reclaim(c_str!("aurora_g16_events"), true)?; + let events_unbound = + OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_events_unbound"), true)?; + let scrub_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)?; + let feed = feed::Feed::new()?; + let feed_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_feed"), false)?; + let active_render_vms = Arc::new(AtomicU32::new(0), GFP_KERNEL)?; + let scrub_queue = slots::ScrubQueue::new_boxed()?; let shared = Arc::pin_init( pin_init!(Shared { dev: dev.as_ref().as_ref().into(), @@ -394,16 +659,45 @@ impl Gpu { wedged_notified: AtomicBool::new(false), crashed: AtomicBool::new(false), evented: AtomicBool::new(false), + publish_wake: AtomicBool::new(false), + closed_vm_reclaim: AtomicBool::new(false), + submitter: AtomicU32::new(u32::MAX), + unbound_cluster_cpu: AtomicU32::new(u32::MAX), + unbound_pinning: AtomicBool::new(false), + active_flights: AtomicU32::new(0), + ewma_flight_us: AtomicU32::new(0), + last_submit_ns: AtomicU64::new(0), + wait_hint_streak: AtomicU32::new(0), + wait_hint_until_ns: AtomicU64::new(0), + resnap_deadline_ns: AtomicU64::new(0), + backup_deadline_ns: AtomicU64::new(0), error: AtomicI32::new(0), started: AtomicBool::new(false), data, rtkit_buffer: AtomicU64::new(0), orphaned: AtomicBool::new(false), sleeping: AtomicBool::new(false), + recovering: AtomicBool::new(false), + base_compute_quarantined: AtomicBool::new(false), + quarantined_compute_mask: AtomicU32::new(0), + base_render_quarantined: AtomicBool::new(false), + quarantined_pb_mask: AtomicU32::new(0), + next_pb_slot: AtomicU32::new(0), + active_render_vms, sleep_ps: AtomicU32::new(0), sleep_commit: AtomicPtr::new(core::ptr::null_mut()), + events, + events_unbound, + scrub_wq, + feed, + feed_wq, orphan <- new_mutex!(None, "g16::Shared::orphan"), poll <- new_delayed_work!("g16::Shared::poll"), + fast_poll <- new_work!("g16::Shared::fast_poll"), + fast_poll_unbound <- new_work!("g16::Shared::fast_poll_unbound"), + scrub_queue <- new_spinlock!(scrub_queue, "g16::Shared::scrub_queue"), + scrub_work <- new_work!("g16::Shared::scrub_work"), + feed_work <- new_work!("g16::Shared::feed_work"), resnap <- HrTimer::new(), resnap_handle <- new_mutex!(None, "g16::Shared::resnap_handle"), state <- new_mutex!(None, "g16::Shared::state"), @@ -414,7 +708,8 @@ impl Gpu { let uat = booted.session.uat(); let (id, max_frequency_khz) = (booted.id, booted.max_frequency_khz); // The backend: graphs, slots, pools, engine, recovery and VM registry. - let firmware = Firmware::start_backend(dev, booted, &shared, power)?; + let firmware = Firmware::start_backend(dev, cfg, booted, &shared, power)?; + let vms = firmware.vms.clone(); *shared.state.lock() = Some(firmware); // The engine's statistics file (a debugfs failure does not fail the probe). if let Err(error) = shared.start_engine() { @@ -428,6 +723,7 @@ impl Gpu { ids: Default::default(), shared, uat, + vms, }, GFP_KERNEL, )?; @@ -454,90 +750,88 @@ impl Firmware { #[inline(never)] fn start_backend( dev: &AsahiDrmDevice, - booted: boot::Booted, + cfg: &'static hw::Config, + mut booted: KBox, shared: &Arc, - power: power::Power, + mut power: power::Power, ) -> Result> { - let boot::Booted { - session, - init, - mut objects, - channels, - events, - .. - } = booted; dev_info!( dev.as_ref(), "G16: firmware at READY, starting the backend\n" ); - let orphan = |session: boot::Session, - objects: object::Objects, - channels: channel::Channels, - init: initdata::InitData, - events: event::Events, - error: Error| - -> Error { - dev_err!( - dev.as_ref(), - "G16: backend start failed ({:?}); firmware retained at READY until reboot\n", - error - ); - shared.orphan(boot::Orphan { - session, - _objects: objects, - channels: Some(channels), - _init: Some(init), - events, - }); - error - }; + power.set_table(booted.init.rows); let backend = (|| -> Result<_> { - let graph = graph::Graphs::new(dev, &mut objects)?; + let graph_session = graph::Graphs::prepare(&mut booted.objects)?; let slots = slots::Slots::new()?; - let pools = pools::Pools::new(dev); + let pools = pools::Pools::new_boxed(dev)?; let vms = vm::Registry::new()?; let engine = engine::Engine::new()?; + let recovery = recovery::Recovery::new()?; + let render_cmds = resources::RenderCmds::new()?; + let compute_cmds = resources::ComputeCmds::new()?; + let private_factory = booted.objects.private_factory(render_cmds, compute_cmds); + let graph = graph::Graphs::finish(dev, graph_session, &private_factory)?; let slot = KBox::::new_uninit(GFP_KERNEL)?; - Ok((graph, slots, pools, vms, engine, slot)) + Ok((graph, private_factory, slots, pools, vms, engine, recovery, slot)) })(); - let (graph, slots, pools, vms, engine, slot) = match backend { + let (graph, private_factory, slots, pools, vms, engine, recovery, slot) = match backend { Ok(backend) => backend, - Err(e) => return Err(orphan(session, objects, channels, init, events, e)), + Err(error) => { + dev_err!( + dev.as_ref(), + "G16: backend start failed ({:?}); firmware retained at READY until reboot\n", + error + ); + shared.retain_failed(Retained::Booted(booted)); + return Err(error); + } }; - let mut firmware = KBox::write( - slot, - Firmware { + let boot::Booted { + session, + init, + objects, + channels, + events, + .. + } = KBox::into_inner(booted); + let mut firmware = slot + .write_init(init!(Firmware { + cfg, session, init, - private_factory: objects.private_factory(), + private_factory, objects, channels, events, graph, slots, engine, - recovery: recovery::Recovery::new(), + recovery, power, pools, vms, - }, - ); - if let Err(e) = firmware.init_graphs() { - let Firmware { - session, - init, - objects, - channels, - events, - .. - } = KBox::into_inner(firmware); - return Err(orphan(session, objects, channels, init, events, e)); + last_housekeeping_ns: 0, + last_aux_drain_ns: 0, + })) + .unwrap_or_else(|e| match e {}); + if let Err(error) = firmware.init_graphs() { + dev_err!( + dev.as_ref(), + "G16: backend start failed ({:?}); firmware retained at READY until reboot\n", + error + ); + shared.retain_failed(Retained::Firmware(firmware)); + return Err(error); } Ok(firmware) } } impl gpu::Gpu for Gpu { + fn syncobj_wait_hint(&self) -> Option<(u32, u32)> { + self.shared.syncobj_wait_hint() + } + fn max_cmdbuf_size(&self) -> usize { command::MAX_CMDBUF } @@ -578,7 +872,7 @@ impl gpu::Gpu for Gpu { } fn queue_limits(&self) -> Option { - None + Some(params::queue_limits()) } fn base_clock_hz(&self) -> u32 { @@ -603,8 +897,10 @@ impl gpu::Gpu for Gpu { true } + /// G16 programs no fault mode into the firmware: an unmapped shader access behaves as the + /// firmware's default fault mode makes it. `fault_control` (default 0xb) stays the opt-out. fn soft_faults(&self) -> bool { - false + true } fn prepare_new_objects(&self) -> bool { @@ -623,15 +919,8 @@ impl gpu::Gpu for Gpu { vm::new_vm(self, kernel_range, file_id) } fn vm_closed(&self, vm: &mmu::Vm) { - let registry = self - .shared - .state - .lock() - .as_ref() - .map(|state| state.vms.clone()); - if let Some(registry) = registry { - registry.close(vm.id()); - } + self.vms.close(vm.id()); + self.shared.wake_closed_vm_reclaim(); } fn new_queue( @@ -653,6 +942,7 @@ impl gpu::Gpu for Gpu { &self, bo: gem::ObjectRef, range: Range, + _window: crate::timestamp::WindowPermit, ) -> Result { timestamp::map(self, bo, range) } diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 0f26cb32767384..cda6f6617e279e 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -46,6 +46,18 @@ pub(crate) enum Class { Shared, /// Firmware and GPU, ASC-cached. SharedCached, + /// ASC-cached (AttrIndex 0) behind a cacheable host mapping: the leaf macOS 26B123 gives its + /// per-queue command objects and the G13-G15 private-allocator contract (`PROT_FW_PRIV_RW` + /// behind `gem::new_kernel_object`). Only for device-lifetime command records with no client + /// alias ([`Factory::persistent_objects`]): an ASC-cached M4 mapping has no qualified + /// teardown, so its owner is never dropped. A kernel GPU task lower alias stays uncached, as + /// macOS maps its work items for the GPU; host stores to such an object are cleaned to the + /// point of coherency for it ([`FwObject::write`]). Host readback of any firmware- or + /// GPU-written field inside a `FwCoherent` record (such as 26B123 compute `work_ticks`) must + /// call [`FwObject::sync_for_cpu`] first to clean+invalidate the CPU lines to PoC; because + /// prior host stores were already cleaned to PoC before publication and no host store occurs + /// while in flight, clean+invalidate never overwrites firmware/GPU writes. + FwCoherent, /// Firmware device mapping. #[allow(dead_code)] Mmio, @@ -59,6 +71,7 @@ impl Class { Class::FwCached => pte::FW_CACHED, Class::Shared => pte::SHARED, Class::SharedCached => pte::SHARED_CACHED, + Class::FwCoherent => pte::FW_CACHED, Class::Mmio => pte::MMIO, } } @@ -100,6 +113,12 @@ pub(crate) struct FwObject { // Subrecords retain the owning WC vmap as well as their GEM. _parent: Option>, limit: Option, + /// Host stores go through a cacheable view the GPU reads through its uncached lower alias: + /// each store is cleaned to the point of coherency. + clean: bool, + /// Host CPU mapping is write-back cacheable (`Class::FwCoherent`): any post-publication CPU + /// readback of firmware- or GPU-written words must call [`Self::sync_for_cpu`] first. + cached_cpu: bool, } // SAFETY: The object only refers to kernel memory shared with the firmware; every host access @@ -148,17 +167,40 @@ impl FwObject { backing: gem::ObjectRef::new(object.gem()), _parent: Some(object.clone()), limit: Some(size), + clean: object.clean, + cached_cpu: object.cached_cpu, }, GFP_KERNEL, )?) } + /// Makes host stores to `len` bytes at `p` visible to an uncached GPU alias. + fn stored(&self, p: *const u8, len: usize) { + if self.clean { + crate::pgtable::clean_poc(p, len); + crate::pgtable::poc_barrier(); + } + } + + /// Invalidates CPU cache lines covering `len` bytes at `offset` when this object uses a + /// cacheable host mapping (`Class::FwCoherent`), ensuring subsequent CPU reads observe + /// firmware- or GPU-written words (e.g. 26B123 compute `work_ticks`) after publication. + pub(crate) fn sync_for_cpu(&self, offset: usize, len: usize) -> Result { + let p = self.ptr(offset, len)?; + if self.cached_cpu { + crate::pgtable::clean_invalidate_poc(p, len); + crate::pgtable::poc_barrier(); + } + Ok(()) + } + /// Copies bytes into the object before it is published, or into host-owned words. pub(crate) fn write(&self, offset: usize, bytes: &[u8]) -> Result { let p = self.ptr(offset, bytes.len())?; // SAFETY: `p` is valid for `bytes.len()` bytes of the object's mapping, which no Rust // reference aliases. unsafe { core::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()) }; + self.stored(p, bytes.len()); Ok(()) } @@ -167,6 +209,7 @@ impl FwObject { let p = self.ptr(offset, len)?; // SAFETY: As for `write`. unsafe { core::ptr::write_bytes(p, value, len) }; + self.stored(p, len); Ok(()) } @@ -176,6 +219,7 @@ impl FwObject { if p as usize % 4 == 0 { // SAFETY: `p` is valid and aligned for a u32. unsafe { p.cast::().write_volatile(value.to_le()) }; + self.stored(p, 4); Ok(()) } else { self.write(offset, &value.to_le_bytes()) @@ -188,6 +232,7 @@ impl FwObject { if p as usize % 8 == 0 { // SAFETY: `p` is valid and aligned for a u64. unsafe { p.cast::().write_volatile(value.to_le()) }; + self.stored(p, 8); Ok(()) } else { self.write(offset, &value.to_le_bytes()) @@ -214,9 +259,23 @@ impl FwObject { pub(crate) fn read(&self, offset: usize, out: &mut [u8]) -> Result { let p = self.ptr(offset, out.len())?; rmb(); - for (index, byte) in out.iter_mut().enumerate() { + let mut index = 0; + let len = out.len(); + while index < len && (p as usize + index) % 8 != 0 { // SAFETY: ptr() bounds the complete range; WC memory permits byte accesses. - *byte = unsafe { p.add(index).read_volatile() }; + out[index] = unsafe { p.add(index).read_volatile() }; + index += 1; + } + while index + 8 <= len { + // SAFETY: ptr() bounds the range and `p.add(index)` is 8-byte aligned. + let word = unsafe { p.add(index).cast::().read_volatile() }; + out[index..index + 8].copy_from_slice(&word.to_ne_bytes()); + index += 8; + } + while index < len { + // SAFETY: ptr() bounds the complete range; WC memory permits byte accesses. + out[index] = unsafe { p.add(index).read_volatile() }; + index += 1; } rmb(); Ok(()) @@ -232,6 +291,30 @@ impl FwObject { // SAFETY: ptr() bounds this naturally aligned 64-bit volatile receipt. return Ok(u64::from_le(unsafe { (p as *const u64).read_volatile() })); } + if p as usize % 4 == 0 { + // Packed 64-bit firmware fields such as compute::DESCRIPTOR_COUNTER (0xe4c) and + // DESCRIPTOR_COMPLETED (0xe54) are 4-byte aligned. Read aligned 32-bit word pairs + // rather than falling through to 16 single-byte WC loads in self.read(). + let pair = |words: *const u32| -> (u32, u32) { + rmb(); + // SAFETY: ptr() bounds 8 bytes and `words` is 4-byte aligned. + let lo = u32::from_le(unsafe { words.read_volatile() }); + // SAFETY: `words.add(1)` stays within the 8-byte range and is 4-byte aligned. + let hi = u32::from_le(unsafe { words.add(1).read_volatile() }); + (lo, hi) + }; + let words = p.cast::(); + let mut first = pair(words); + for _ in 0..3 { + let next = pair(words); + if first == next { + rmb(); + return Ok(u64::from(next.0) | (u64::from(next.1) << 32)); + } + first = next; + } + return Err(EAGAIN); + } let mut first = [0u8; 8]; let mut next = [0u8; 8]; self.read(offset, &mut first)?; @@ -282,11 +365,28 @@ pub(crate) struct Request { /// Private allocation coordinates. Only normal non-cacheable objects may be reclaimed. struct Private { - vm: mmu::Vm, + vm: Option, firmware: core::ops::Range, pending: Option>, } +/// VM-independent firmware-object lease whose backing and firmware/lower mappings stay alive +/// until a later command overwrites the same hardware table slot in firmware RAM. +/// +/// Dropping an `Arc` offloads unmap to `cleanup::Deferred`, so replacing a lease under +/// `Shared::state` never sleeps or blocks fence producers. +pub(crate) struct FwLease(crate::cleanup::Deferred); + +impl FwLease { + pub(crate) fn new(mut objects: Objects) -> Result> { + objects.finish_private()?; + Ok(Arc::new( + Self(crate::cleanup::Deferred::new(objects)?), + GFP_KERNEL, + )?) + } +} + /// Immutable factory shared by ioctl-side private arena construction. #[derive(Clone)] pub(crate) struct Factory { @@ -294,6 +394,8 @@ pub(crate) struct Factory { uat: Arc, window: Arc>, firmware: core::ops::Range, + render_cmds: Arc, + compute_cmds: Arc, } impl Factory { @@ -303,11 +405,61 @@ impl Factory { uat: self.uat.clone(), window: self.window.clone(), private: Some(Private { - vm: vm.clone(), + vm: Some(vm.clone()), + firmware: self.firmware.clone(), + pending: None, + }), + sealed: false, + persistent: false, + probe: false, + fw_next: self.firmware.start, + retained: KVec::new(), + clients: KVec::new(), + mappings: KVec::new(), + error: None, + pages: 0, + } + } + + /// Allocates firmware-only and context-0 lower-alias objects with no client VM binding. + pub(crate) fn fw_objects(&self) -> Objects { + Objects { + dev: self.dev.clone(), + uat: self.uat.clone(), + window: self.window.clone(), + private: Some(Private { + vm: None, + firmware: self.firmware.clone(), + pending: None, + }), + sealed: false, + persistent: false, + probe: false, + fw_next: self.firmware.start, + retained: KVec::new(), + clients: KVec::new(), + mappings: KVec::new(), + error: None, + pages: 0, + } + } + + /// Allocates the only objects that may hold [`Class::FwCoherent`] records: firmware-only, + /// with no client VM binding. The caller owns them for the device lifetime and never drops + /// them ([`super::resources::RenderCmds`]). + pub(crate) fn persistent_objects(&self) -> Objects { + Objects { + dev: self.dev.clone(), + uat: self.uat.clone(), + window: self.window.clone(), + private: Some(Private { + vm: None, firmware: self.firmware.clone(), pending: None, }), sealed: false, + persistent: true, + probe: false, fw_next: self.firmware.start, retained: KVec::new(), clients: KVec::new(), @@ -316,6 +468,27 @@ impl Factory { pages: 0, } } + + /// Probe-time variant of [`Self::persistent_objects`], called only from + /// [`super::graph::Graphs::finish`] during platform `probe()` before `drm_dev_register()` + /// makes `registration_guard()` available. + pub(crate) fn persistent_objects_probe(&self) -> Objects { + let mut objects = self.persistent_objects(); + objects.probe = true; + objects + } + + /// The device-lifetime render command records of pass slot `k`, shared by every VM's + /// [`super::slots::PassSlot`] `k`. + pub(crate) fn pass_cmds(&self, k: usize) -> Result { + self.render_cmds.get(self, k) + } + + /// The device-lifetime compute command records of hardware compute unit `k`, shared by every + /// VM's [`super::slots::ComputeSlot`] bound to hardware unit `k`. + pub(crate) fn compute_cmds(&self, k: usize) -> Result { + self.compute_cmds.get(self, k) + } } /// The firmware object allocator and the set of retained objects. @@ -326,6 +499,10 @@ pub(crate) struct Objects { pub(crate) window: Arc>, private: Option, sealed: bool, + /// A device-lifetime allocator that may map [`Class::FwCoherent`] records. + persistent: bool, + /// Runs during platform `probe()` before `drm_dev_register()` provides `registration_guard()`. + probe: bool, /// Next free VA of the firmware allocator window. fw_next: u64, /// Every object owned by this session or private arena. @@ -354,6 +531,8 @@ impl Objects { window: Arc::pin_init(new_mutex!(window, "g16::Objects::window"), GFP_KERNEL)?, private: None, sealed: false, + persistent: false, + probe: false, fw_next: hw::va::FW_ALLOC.start, retained: KVec::new(), clients: KVec::new(), @@ -364,19 +543,26 @@ impl Objects { } /// Freeze the session allocation boundary before making any private arenas. - pub(crate) fn private_factory(&mut self) -> Factory { + pub(crate) fn private_factory( + &mut self, + render_cmds: Arc, + compute_cmds: Arc, + ) -> Factory { self.sealed = true; Factory { dev: self.dev.clone(), uat: self.uat.clone(), window: self.window.clone(), firmware: self.fw_next..hw::va::FW_ALLOC.end, + render_cmds, + compute_cmds, } } /// Maps private backing into one client and unique kernel/firmware apertures. Mapping /// owners retain the GEM independently, including every partial construction failure. - /// All reclaimable objects are NC from creation; there is no ASC cache transition. + /// All reclaimable objects are NC from creation; there is no ASC cache transition. Only a + /// device-lifetime allocator maps [`Class::FwCoherent`] records, never reclaimed. fn alloc_private(&mut self, req: Request) -> Result> { self.alloc_private_in(req, None) } @@ -392,7 +578,7 @@ impl Objects { lower: None, cpu: true, }, - Some(0x7040000000..0x7080000000), + Some(hw::client::DYNAMIC), ) } @@ -402,45 +588,78 @@ impl Objects { client_range: Option>, ) -> Result> { if !matches!(req.placement, Placement::Anywhere) - || !matches!(req.class, Class::Fw | Class::Shared) + || !matches!(req.class, Class::Fw | Class::Shared | Class::FwCoherent) + || (req.class == Class::FwCoherent + && (!self.persistent || req.client.is_some() || client_range.is_some())) || req.size == 0 || req.offset >= hw::PAGE as usize { return Err(EINVAL); } - let private = self.private.as_ref().ok_or(EINVAL)?; let bytes = req .offset .checked_add(req.size) .and_then(|size| size.checked_add(hw::PAGE as usize - 1)) .ok_or(EOVERFLOW)? & !(hw::PAGE as usize - 1); + { + let private = self.private.as_ref().ok_or(EINVAL)?; + if client_range.is_some() { + if private.vm.is_none() { + return Err(EINVAL); + } + } else if let Some((gva, leaf)) = req.client { + if private.vm.is_none() { + return Err(EINVAL); + } + let end = gva.checked_add(bytes as u64).ok_or(EOVERFLOW)?; + if gva < hw::client::CLIENT_APERTURE.start + || end > hw::client::CLIENT_APERTURE.end + || gva & (hw::PAGE - 1) != 0 + || leaf != pte::LEAF_NC && leaf != pte::LEAF_PB_LIST + { + return Err(EINVAL); + } + } + } self.retained.reserve(1, GFP_KERNEL)?; self.mappings.reserve(3, GFP_KERNEL)?; - let mut backing = gem::new_kernel_object_wc(&self.dev, bytes)?; - let registered = self.dev.registration_guard().ok_or(ENODEV)?; - let parent: &kernel::platform::Device = registered.as_ref(); - gem::prepare_new_object(&backing.gem, parent.as_ref())?; + let object_slot = UniqueArc::::new_uninit(GFP_KERNEL)?; + // A firmware-cached record needs a cacheable host view of the same pages (the host and + // firmware caches are coherent, as for G13-G15 private objects); every other private + // class keeps its write-combined view. + let mut backing = if req.class == Class::FwCoherent { + gem::new_kernel_object(&self.dev, bytes)? + } else { + gem::new_kernel_object_wc(&self.dev, bytes)? + }; + if self.probe { + // SAFETY: `Factory::persistent_objects_probe()` is called only from + // `Graphs::finish()` during platform `probe()`, while the platform device is + // bound and before `drm_dev_register()` makes `registration_guard()` available. + let bound = unsafe { self.dev.as_ref().as_ref().as_bound() }; + gem::prepare_new_object(&backing.gem, bound)?; + } else { + let registered = self.dev.registration_guard().ok_or(ENODEV)?; + let parent: &kernel::platform::Device = registered.as_ref(); + gem::prepare_new_object(&backing.gem, parent.as_ref())?; + } + let clean = req.class == Class::FwCoherent && req.lower.is_some(); + let cached_cpu = req.class == Class::FwCoherent; let cpu = if req.cpu { let vmap = backing.vmap()?; let pointer = NonNull::new(vmap.addr.cast::()).ok_or(ENOMEM)?; - // SAFETY: Fresh private WC mapping spans bytes and has not been exposed. + // SAFETY: Fresh private mapping spans bytes and has not been exposed. unsafe { core::ptr::write_bytes(pointer.as_ptr(), 0, bytes) }; + if clean { + crate::pgtable::clean_poc(pointer.as_ptr(), bytes); + crate::pgtable::poc_barrier(); + } Some(pointer) } else { None }; - let firmware = self.uat.kernel_vm().map_in_range( - &backing.gem, - 0..bytes, - hw::PAGE, - private.firmware.clone(), - mmu::Prot::from_pte(req.class.pte()), - true, - )?; - let va = firmware.iova(); - self.mappings.push(firmware, GFP_KERNEL)?; - let lower_gva = if req.lower.is_some() { + let lower_mapping = if req.lower.is_some() { // No two live VMs share a context-0 work address. The self-check at 0x70ff... // and all fixed client aliases are outside this aperture. let lower = self.uat.kernel_lower_vm().map_in_range( @@ -451,76 +670,90 @@ impl Objects { mmu::Prot::from_pte(pte::LOWER), true, )?; - let address = lower.iova() + req.offset as u64; - self.mappings.push(lower, GFP_KERNEL)?; uat::clean_lower(&self.uat)?; - Some(address) + Some(lower) } else { None }; - let client_gva = if let Some(range) = client_range { - let mapping = private.vm.map_in_range( - &backing.gem, - 0..bytes, - hw::PAGE, - range, - mmu::Prot::from_pte(pte::LEAF_NC), - true, - )?; - let address = mapping.iova(); - self.mappings.push(mapping, GFP_KERNEL)?; - Some(address) - } else if let Some((gva, leaf)) = req.client { - let end = gva.checked_add(bytes as u64).ok_or(EOVERFLOW)?; - if gva < hw::client::CLIENT_APERTURE.start - || end > hw::client::CLIENT_APERTURE.end - || gva & (hw::PAGE - 1) != 0 - || leaf != pte::LEAF_NC && leaf != pte::LEAF_PB_LIST - { - return Err(EINVAL); + let (client_mapping, client_gva) = { + let private = self.private.as_ref().ok_or(EINVAL)?; + if let Some(range) = client_range { + let vm = private.vm.as_ref().ok_or(EINVAL)?; + let mapping = vm.map_in_range( + &backing.gem, + 0..bytes, + hw::PAGE, + range, + mmu::Prot::from_pte(pte::LEAF_NC), + true, + )?; + let address = mapping.iova(); + (Some(mapping), Some(address)) + } else if let Some((gva, leaf)) = req.client { + let vm = private.vm.as_ref().ok_or(EINVAL)?; + let mapping = + vm.map_at(gva, bytes, &backing.gem, mmu::Prot::from_pte(leaf), false)?; + (Some(mapping), Some(gva)) + } else { + (None, None) } - self.mappings.push( - private - .vm - .map_at(gva, bytes, &backing.gem, mmu::Prot::from_pte(leaf), false)?, - GFP_KERNEL, - )?; - Some(gva) - } else { - None }; - wmb(); - let private = self.private.as_mut().ok_or(EINVAL)?; - let end = va + bytes as u64; - private.pending = Some(match private.pending.take() { - Some(range) => range.start.min(va)..range.end.max(end), - None => va..end, - }); - let object = Arc::new( - FwObject { - va: va + req.offset as u64, - gva: client_gva.map(|gva| gva + req.offset as u64), - lower_gva, - size: req.size, - offset: req.offset, - bytes, - client_leaf: req.client.map_or(pte::LEAF_NC, |(_, leaf)| leaf), - cpu, - backing, - _parent: None, - limit: None, - }, - GFP_KERNEL, + let fw_range = self.private.as_ref().ok_or(EINVAL)?.firmware.clone(); + // Map the firmware aperture last: for `Class::FwCoherent` an ASC-cached mapping cannot + // be torn down on drop, so every fallible allocation, validation, and uncached alias + // must succeed before it is created. + let firmware = self.uat.kernel_vm().map_in_range( + &backing.gem, + 0..bytes, + hw::PAGE, + fw_range, + mmu::Prot::from_pte(req.class.pte()), + true, )?; - self.retained.push(object.clone(), GFP_KERNEL)?; + let va = firmware.iova(); + let lower_gva = lower_mapping.as_ref().map(|m| m.iova() + req.offset as u64); + let _ = self.mappings.push_within_capacity(firmware); + if let Some(lower) = lower_mapping { + let _ = self.mappings.push_within_capacity(lower); + } + if let Some(client) = client_mapping { + let _ = self.mappings.push_within_capacity(client); + } + wmb(); + if let Some(private) = self.private.as_mut() { + let end = va + bytes as u64; + private.pending = Some(match private.pending.take() { + Some(range) => range.start.min(va)..range.end.max(end), + None => va..end, + }); + } + let object = Arc::from(object_slot.write(FwObject { + va: va + req.offset as u64, + gva: client_gva.map(|gva| gva + req.offset as u64), + lower_gva, + size: req.size, + offset: req.offset, + bytes, + client_leaf: req.client.map_or(pte::LEAF_NC, |(_, leaf)| leaf), + cpu, + backing, + _parent: None, + limit: None, + clean, + cached_cpu, + })); + let _ = self.retained.push_within_capacity(object.clone()); self.pages += bytes / hw::PAGE as usize; Ok(object) } /// Publish a completed private arena in one shared-L2 transaction. pub(crate) fn finish_private(&mut self) -> Result { - if let Some(range) = self.private.as_mut().ok_or(EINVAL)?.pending.take() { + if let Some(range) = self.private.as_ref().ok_or(EINVAL)?.pending.clone() { self.window.lock().sync_range(&self.uat, range)?; + if let Some(private) = self.private.as_mut() { + private.pending = None; + } } Ok(()) } @@ -536,13 +769,14 @@ impl Objects { self.pages } - /// Bounded live UAT ownership checks; no user leaf walk and no firmware memory repair. + /// Bounded live checks of the host window; no user leaf walk and no firmware memory repair. + /// The UAT's context bindings are checked by [`super::boot::Session::check`], which every + /// caller runs just before this. pub(crate) fn health(&mut self) -> Result { if let Some(error) = self.error { return Err(error); } - self.window.lock().check()?; - self.uat.check_adopted_bindings() + self.window.lock().check() } /// Allocates and maps a zeroed firmware object. @@ -566,6 +800,10 @@ impl Objects { } return self.alloc_private(req); } + // Session objects are write-combined: they never give the firmware a cached record. + if req.class == Class::FwCoherent { + return Err(EINVAL); + } if self.sealed { return Err(EBUSY); } @@ -659,6 +897,8 @@ impl Objects { backing, _parent: None, limit: None, + clean: false, + cached_cpu: false, }) .into(); self.retained.push(object.clone(), GFP_KERNEL)?; diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index d2ef01e26b3a3d..1aef70eae06d72 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -3,14 +3,16 @@ //! Module parameters and the GET_PARAMS identity. //! //! With the shared `file.rs` additions (VM_STATUS and VM_STATUS_MIRROR from `supports_vm_status`, -//! SOFT_FAULTS suppressed by `soft_faults`), the feature word is 0x1c02: per-command input -//! readiness/errors and exact queue-local historical prefixes use explicit retained inputs -//! and successful command receipt frontiers. No independent hardware queue reservation, -//! fragment barriers or ray queries are advertised. +//! SOFT_FAULTS from `soft_faults` and `fault_control`, VDM_USC_INVALIDATE, and +//! `INDEPENDENT_QUEUES` from `queue_limits`), G16 advertises per-command input readiness/errors, +//! exact queue-local historical prefixes, fragment-only and staged render barriers +//! (`RENDER_STAGE_PREFIXES_V2`), independent logical queues, `FEW_PRIMITIVES`, +//! `COMPUTE_NO_QUERY_ACCESS`, render ray queries (`RENDER_RAY_QUERY`) and bounded AS builds +//! (`BOUNDED_AS_BUILD`). use kernel::{prelude::*, uapi}; -use super::{hw, Gpu, GPU_GENERATION}; +use super::{hw, Gpu}; use crate::module_parameters; /// Operations per VM_BIND batch at most: batches are atomic and may be large (sparse residency @@ -28,6 +30,40 @@ pub(crate) fn compute_deadline_ms() -> u32 { module_parameters::g16_compute_deadline_ms.value() } +/// PB heap blocks of a new render arena (64 MiB in 128 KiB blocks). +pub(crate) fn pb_heap_blocks() -> u32 { + 64 * 8 +} + +/// PB blocks posted to a fresh epoch of a heap of `heap_blocks`. +pub(crate) fn pb_posted_blocks(heap_blocks: u32) -> u32 { + 2048u32.min(heap_blocks) +} + +/// Compute units of a VM that submits compute back to back. +pub(crate) fn compute_units() -> usize { + hw::sizes::COMPUTE_UNITS +} + +/// Compute commands in flight at most. +pub(crate) fn compute_flights() -> usize { + 32usize.clamp(1, hw::sizes::FLIGHTS) +} + +/// Render commands in flight at most: bounded by both retained pass slots +/// (`RENDER_SLOTS - 1`, leaving one slot for displacement) and firmware TA/FS work-ring +/// capacity (`(QUEUE_CAP - 1) / MAX_RENDER_RING_ENTRIES`, worst case 5 ring entries per pass). +/// Decoupled from `hw::sizes::FLIGHTS` because multi-pass render batches pack multiple passes +/// into one `Flight`. +pub(crate) fn render_flights() -> usize { + let ring_cap = + (hw::sizes::QUEUE_CAP as usize).saturating_sub(1) / hw::sizes::MAX_RENDER_RING_ENTRIES; + hw::sizes::RENDER_SLOTS + .saturating_sub(1) + .min(ring_cap) + .max(1) +} + /// Repoll while a ready prefix waits for record consumption, us. pub(crate) fn repoll_us() -> u32 { module_parameters::g16_repoll_us.value().clamp(5, 100) @@ -48,21 +84,32 @@ pub(crate) fn stream_gate() -> bool { module_parameters::g16_stream_gate.value() != 0 } -/// Fragment-only dependency publication has not been qualified on this backend. +/// Fragment-only render barriers overlap a pipelined render's TA with the prior render's FS. pub(crate) fn early_tiling() -> bool { - false + true } /// Fills the generation part of GET_PARAMS group 0. pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Result { - // Match the working J713 C backend identity; SGX register revision fields are - // not the userspace BCD revision. - if gpu.cfg.chip_id != 0x8132 || gpu.cfg.gpu_revision != 0x10 { - return Err(ENODEV); - } params.features |= u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_PER_COMMAND_INPUT_SYNCS) - | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_EXACT_PRIOR_BARRIERS); - params.gpu_generation = GPU_GENERATION; + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_EXACT_PRIOR_BARRIERS) + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS) + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS) + | if gpu.cfg.gpu_generation >= 16 { + u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FEW_PRIMITIVES) + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_RENDER_RAY_QUERY) + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD) + } else { + 0 + } + | if gpu.cfg.max_tile_buffer >= hw::sizes::TILE_BUFFER_48K { + crate::file::DRM_ASAHI_FEATURE_TILE_BUFFER_48K + } else { + 0 + } + | crate::g17::sync_output::FEATURE_CUMULATIVE_SIGNALS + | crate::file::DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2; + params.gpu_generation = gpu.cfg.gpu_generation; params.gpu_variant = gpu.cfg.gpu_variant as u32; params.gpu_revision = gpu.cfg.gpu_revision; params.chip_id = gpu.cfg.chip_id; @@ -71,7 +118,7 @@ pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Res params.num_cores_per_cluster = gpu.cfg.num_cores_per_cluster; params.max_frequency_khz = gpu.max_frequency_khz; params.usc_generation = 3; - params.gpu_hal_generation = uapi::drm_asahi_gpu_hal_generation_DRM_ASAHI_GPU_HAL_200; + params.gpu_hal_generation = gpu.cfg.gpu_hal_generation; params.max_commands_per_submission = super::command::MAX_COMMANDS; params.max_attachments = hw::sizes::MAX_ATTACHMENTS as u32; for (i, mask) in gpu.id.core_masks.iter().enumerate() { @@ -79,3 +126,13 @@ pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Res } Ok(()) } + +/// QUEUE_LIMITS: a policy bound on logical queues (they own no firmware state) and the +/// number of prefixes in flight. +pub(crate) fn queue_limits() -> uapi::drm_asahi_queue_limits { + uapi::drm_asahi_queue_limits { + max_queues: hw::sizes::MAX_QUEUES, + max_in_flight_per_queue: hw::sizes::FLIGHTS as u32, + ..Default::default() + } +} diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 4e9bfaef02e12f..c767737ed560ef 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -4,14 +4,16 @@ //! //! Order of one pass, under the device lock: drain the receive rings; authenticate recovery; //! retire flights using stage stamps, NC queue READ/WRITE and submit-pipe frontiers, normal -//! notifier/UMA receipts and internal timestamps; renew the progress deadline. Up to four -//! trailing 5 us polls follow an EP 0x20 event. Then answer PB -//! growth ([`Firmware::answer_growth`]); check hangs and recover ([`Firmware::check_hangs`], -//! which calls [`Firmware::progress`]); publish ([`Firmware::publish`]). Then drop the lock -//! and complete the retired jobs ([`super::job::complete_all`]). Wakeups: the EP 0x20 event -//! kick, then an hrtimer re-poll every `g16_resnap_us` (100) while anything is published, or -//! `g16_repoll_us` (15) while a ready prefix waits for record consumption, with a 1-jiffy -//! delayed-work backup. +//! notifier/UMA receipts and internal timestamps; renew the progress deadline; answer PB +//! growth ([`Firmware::answer_growth`]); publish ([`Firmware::publish_checked`]). Then drop +//! the lock and complete retired jobs ([`super::job::complete_all`]) before periodic 1 ms +//! housekeeping (`session.check`, `objects.health`, `service_power`, administrative hang +//! checks). If an EP 0x20 event arrived with flights outstanding and nothing retired yet, up +//! to [`EVENT_RETIRE_POLLS`] trailing 5 us waits run with `Shared::state` dropped so concurrent +//! submissions are not blocked, stopping as soon as any flight retires. Wakeups: the EP 0x20 +//! event kick, then an hrtimer re-poll every `g16_resnap_us` (100) while anything is +//! published, or `g16_repoll_us` (8) while a ready prefix waits for record consumption or a +//! post-event receipt tail did not settle, with a 1-jiffy delayed-work backup. use core::sync::atomic::Ordering; @@ -31,14 +33,28 @@ use kernel::{ use super::channel::Channel; use super::engine::{complete, now_ns, rmb, Flight, Lap}; -use super::fw::graph::{notifier, notifier_page, qstate}; -use super::fw::work::compute; +use super::fw::graph::{manager, notifier, notifier_page, qstate}; use super::job::{self, Completions, Job}; -use super::recovery::logic::Retirement; +use super::recovery::logic::{Retirement, ABORT_GRACE_NS}; use super::regs::EngineState; -use super::{params, Firmware, Shared, POLL_WORK}; +use super::{params, Firmware, Shared, FAST_POLL_WORK, POLL_WORK, SCRUB_WORK, UNBOUND_POLL_WORK}; use crate::module_parameters; +/// Cadence of periodic housekeeping when idle or entering recovery (1 ms). +const HOUSEKEEPING_NS: u64 = 1_000_000; +/// Cadence of periodic housekeeping while flights are active (5 ms, aligned with +/// `power::policy::SAMPLE_NS` and far below the 100 ms minimum hang deadline). +const ACTIVE_HOUSEKEEPING_NS: u64 = 5_000_000; +/// Minimum interval between auxiliary log/ktrace/stats ring drains while flights are active. +const AUX_DRAIN_NS: u64 = 10_000_000; +/// Maximum trailing receipt polls after an EP 0x20 event (stepped 1/2/3/4/5 us, 45 us total). +const EVENT_RETIRE_POLLS: u32 = 11; +/// Maximum consecutive in-place EP 0x20 rechecks in `run_poll()` before yielding back to +/// the workqueue so short bursts avoid extra worker round-trips without starving housekeeping. +const MAX_EVENT_RECHECKS: u32 = 8; +/// Minimum interval between 1-jiffy delayed-work safety backup rearms (2 ms). +const BACKUP_REARM_NS: u64 = 2_000_000; + impl_has_hr_timer! { impl HasHrTimer for Shared { mode: RelativeMode, field: self.resnap @@ -51,6 +67,7 @@ impl HrTimerCallback for Shared { /// Runs the poll now. fn run(this: ArcBorrow<'_, Self>, _ctx: HrTimerCallbackContext<'_, Self>) -> HrTimerRestart { let this: Arc = this.into(); + this.resnap_deadline_ns.store(0, Ordering::Release); this.poll_now(); HrTimerRestart::NoRestart } @@ -66,6 +83,34 @@ fn stats_show(shared: &Arc, f: &mut fmt::Formatter<'_>) -> fmt::Result { } impl Shared { + /// Schedules a delayed poll while idle so DVFS utilization decays to S1 and a held CLPC + /// memory/fabric floor expires cleanly after all flights drain. + fn arm_idle_power_poll(self: &Arc, firmware: &Firmware) { + if firmware.recovery.failed().is_some() { + return; + } + let delay_ns = if firmware.power.clpc_holding() { + super::power::policy::CLPC_IDLE_HOLD_NS + } else if firmware.power.utilization.decaying() { + super::power::policy::WINDOW_NS + } else { + return; + }; + self.mod_poll(kernel::time::msecs_to_jiffies((delay_ns / 1_000_000) as u32).max(1)); + } + + /// Queues the backup poll for idle housekeeping that a pass skipped inside its cadence, at + /// the end of that cadence. It may replace a later idle power poll: that pass runs the + /// housekeeping, including `service_power()`, and arms the power poll again. + fn queue_owed_housekeeping(self: &Arc, firmware: &Firmware) { + if !firmware.engine.housekeeping_owed || firmware.recovery.failed().is_some() { + return; + } + let elapsed = now_ns().wrapping_sub(firmware.last_housekeeping_ns); + let ms = HOUSEKEEPING_NS.saturating_sub(elapsed).div_ceil(1_000_000) as u32; + self.mod_poll(kernel::time::msecs_to_jiffies(ms).max(1)); + } + /// One poll pass (the poll work item). pub(crate) fn run_poll(self: Arc) { // The domain may be off. The sleep's end queues a pass. @@ -73,67 +118,343 @@ impl Shared { return; } let signalling = kernel::dma_fence::SignallingGuard::new(); - let mut done = Completions::new(); - { - let mut state = self.state.lock(); - if let Some(firmware) = state.as_deref_mut() { + let mut evented = false; + let mut tail = 0u32; + let mut housekeeping_deferred = false; + let mut step = 0u32; + let mut rechecks = 0u32; + + loop { + if self.sleeping.load(Ordering::Acquire) { + break; + } + let mut done = Completions::new(); + let mut scrubs = super::slots::ScrubBatch::new(); + let mut retry_tail = false; + let mut poll_ok = true; + if let Some(firmware) = self.state.lock().as_deref_mut() { + if self.sleeping.load(Ordering::Acquire) { + return; + } if firmware.engine.shared.is_none() { firmware.engine.shared = Some(self.clone()); } - let evented = self.evented.swap(false, Ordering::AcqRel); - match firmware.poll(evented, &mut done) { - Ok(true) => self.rearm(firmware.engine.chan_wait), - // Idle: one more pass after a window gives the state back. A failed - // engine's poll no longer services power, so it has nothing to give back. - Ok(false) - if firmware.recovery.failed().is_none() - && firmware.power.utilization.decaying() => - { - self.mod_poll(kernel::time::msecs_to_jiffies( - (super::power::policy::WINDOW_NS / 1_000_000) as u32, - )) + if step == 0 { + evented = self.evented.swap(false, Ordering::AcqRel); + tail = if evented { EVENT_RETIRE_POLLS } else { 0 }; + } + match firmware.poll_step( + evented, + tail, + &mut retry_tail, + &mut housekeeping_deferred, + &mut done, + ) { + Ok(true) if retry_tail => {} + Ok(true) => { + let soon = firmware.engine.chan_wait || firmware.engine.short_repoll; + if firmware.engine.coalesce_deadline_ns != 0 && !soon { + let rem_us = (firmware + .engine + .coalesce_deadline_ns + .saturating_sub(now_ns()) + .div_ceil(1000) as u32) + .clamp(1, super::hw::sizes::COALESCE_WINDOW_US); + self.rearm_after(rem_us.min(self.rearm_us(false))); + } else { + self.rearm(soon); + } + } + // Idle: arm a delayed poll while DVFS utilization is decaying or a CLPC + // floor hold is still pending so both expire cleanly to idle power. + Ok(false) => { + self.arm_idle_power_poll(firmware); + self.queue_owed_housekeeping(firmware); + if firmware.recovery.failed().is_some() { + self.cancel_resnap(); + } else { + self.idle_resnap(); + } } - Ok(false) => {} Err(error) => { + poll_ok = false; + self.cancel_resnap(); + firmware.fail_stop(error, &mut done); + self.fail_stop(error); + } + } + let allow_stage = firmware.recovery.failed().is_none() + && !firmware.engine.frozen + && !self.sleeping.load(Ordering::Acquire); + scrubs = firmware.slots.stage_and_take_scrubs(allow_stage); + self.sync_active_flights(firmware); + } + job::complete_all(done); + self.enqueue_scrubs(scrubs); + self.queue_feed(); + if !retry_tail { + if poll_ok + && !self.sleeping.load(Ordering::Acquire) + && !self.crashed.load(Ordering::Acquire) + && self.evented.load(Ordering::Acquire) + { + if rechecks < MAX_EVENT_RECHECKS { + rechecks += 1; + step = 0; + evented = false; + tail = 0; + continue; + } + self.poll_now(); + } + break; + } + let delay_us = match step { + 0 => 1, + 1 => 2, + 2 => 3, + 3 => 4, + _ => 5, + }; + tail -= 1; + step += 1; + delay::udelay(Delta::from_micros(delay_us)); + } + + if housekeeping_deferred && !self.sleeping.load(Ordering::Acquire) { + let mut done = Completions::new(); + if let Some(firmware) = self.state.lock().as_deref_mut() { + if !self.sleeping.load(Ordering::Acquire) { + if let Err(error) = firmware.run_housekeeping(&mut done) { + self.cancel_resnap(); firmware.fail_stop(error, &mut done); self.fail_stop(error); + } else if firmware.recovery.needs_repoll() || firmware.engine.frozen { + self.rearm(false); + } else if firmware.engine.flights.is_empty() { + self.arm_idle_power_poll(firmware); } + self.sync_active_flights(firmware); } } + job::complete_all(done); } - job::complete_all(done); drop(signalling); self.notify_wedged(); } + fn submit_locked( + self: &Arc, + firmware: &mut Firmware, + job: Arc, + done: &mut Completions, + ) -> Result { + if firmware.engine.shared.is_none() { + firmware.engine.shared = Some(self.clone()); + } + let accepted = firmware.enqueue(job); + if accepted.is_ok() && !self.sleeping.load(Ordering::Acquire) { + let now = now_ns(); + let had_flights = !firmware.engine.flights.is_empty(); + let housekeeping_interval = if had_flights { + ACTIVE_HOUSEKEEPING_NS + } else { + HOUSEKEEPING_NS + }; + let housekeeping_due = + now.wrapping_sub(firmware.last_housekeeping_ns) >= housekeeping_interval; + let was_evented = had_flights && self.evented.swap(false, Ordering::AcqRel); + let recovery_pending = firmware.recovery_pending().unwrap_or(true); + let mut retired_any = false; + let mut restored_event = false; + let mut pub_res = Ok(()); + if had_flights + && (was_evented || recovery_pending || firmware.oldest_stamp_reached()) + { + let stage_before = firmware.events.stage_events; + let term_before = firmware.oldest_terminal_events(); + pub_res = firmware.session.transport().and_then(|()| { + retired_any = firmware.retire_once(done)?; + firmware.answer_growth()?; + if firmware.recovery.receipt_fault || recovery_pending { + firmware.check_hangs(done)?; + } + if was_evented && !retired_any && !firmware.engine.flights.is_empty() { + let non_terminal_only = term_before.is_some() + && firmware.events.stage_events != stage_before + && firmware.oldest_terminal_events() == term_before + && !firmware.oldest_stamp_reached() + && !firmware.recovery.receipt_fault + && !recovery_pending; + if !non_terminal_only { + self.evented.store(true, Ordering::Release); + restored_event = true; + } + } + Ok(()) + }); + } + let mut coalesce_us = None; + if pub_res.is_ok() { + if retired_any || !had_flights { + firmware.reclaim_closed_vm_slots(); + } + if !recovery_pending && !retired_any && !restored_event && had_flights { + coalesce_us = firmware.defer_busy_coalesce(now); + } + if coalesce_us.is_none() { + pub_res = if recovery_pending { + let r = firmware.publish(done); + if r.is_ok() { + firmware.last_housekeeping_ns = now; + firmware.last_aux_drain_ns = now; + } + r + } else { + firmware.publish_checked(done) + }; + } + } + if pub_res.is_ok() + && !firmware.engine.flights.is_empty() + && firmware.power.needs_ramp(now) + { + pub_res = firmware.service_power(); + } + if let Err(error) = pub_res { + firmware.fail_stop(error, done); + self.fail_stop(error); + } + if !firmware.engine.flights.is_empty() || firmware.engine.chan_wait { + // If an EP 0x20 event retired an older flight while later flights remain active, + // or arrived before the oldest receipt became visible, arm a short repoll so + // trailing completions never fall back to `resnap_us`. A ready job this + // publication left waiting on TA wave or slot headroom repolls as soon as + // `poll_step()` would rearm it, not a full `resnap_us` later. + if let Some(us) = coalesce_us { + self.rearm_after(us.min(self.rearm_us(false))); + } else { + let paced = !firmware.engine.frozen + && !firmware.engine.pending.is_empty() + && (firmware.engine.slot_wait + || firmware.engine.ta_wave_wait + || firmware.engine.held_wait); + self.rearm( + firmware.engine.chan_wait + || restored_event + || paced + || (was_evented && retired_any && !firmware.engine.flights.is_empty()), + ); + } + } else { + firmware.power.report_work(false); + self.arm_idle_power_poll(firmware); + } + if pub_res.is_ok() + && (restored_event || (housekeeping_due && !recovery_pending)) + { + self.poll_now(); + } + } + accepted + } + /// Hands a job to the engine and publishes what can be published. Err: the job was not /// accepted (the engine failed: EIO) and the caller fails it; once accepted, its fence is /// signalled by the engine, also on failure. pub(crate) fn submit(self: &Arc, job: Arc) -> Result { let signalling = kernel::dma_fence::SignallingGuard::new(); let mut done = Completions::new(); - let accepted = { + let (accepted, scrubs) = { let mut state = self.state.lock(); let firmware = state.as_deref_mut().ok_or(ENODEV)?; - if firmware.engine.shared.is_none() { - firmware.engine.shared = Some(self.clone()); + let res = self.submit_locked(firmware, job, &mut done); + let allow_stage = firmware.recovery.failed().is_none() + && !firmware.engine.frozen + && !self.sleeping.load(Ordering::Acquire); + self.sync_active_flights(firmware); + (res, firmware.slots.stage_and_take_scrubs(allow_stage)) + }; + job::complete_all(done); + self.enqueue_scrubs(scrubs); + self.queue_feed(); + drop(signalling); + self.notify_wedged(); + accepted + } + + /// Inline SUBMIT ioctl publication: acquires `Shared::state` directly when the GPU is + /// neither sleeping nor recovering so brief poll-lock overlap does not bounce ready + /// submissions onto `drm_sched` kworker wakeups. Returns `None` during sleep or recovery + /// so `drm_sched` handles those paths without stalling SUBMIT. + pub(crate) fn try_submit_inline(self: &Arc, job: Arc) -> Option { + if self.sleeping.load(Ordering::Acquire) || self.recovering.load(Ordering::Acquire) { + return None; + } + let signalling = kernel::dma_fence::SignallingGuard::new(); + let mut done = Completions::new(); + let mut scrubs = super::slots::ScrubBatch::new(); + let accepted = { + let mut state = self.state.lock(); + if self.sleeping.load(Ordering::Acquire) { + return None; } - let accepted = firmware.enqueue(job); - if accepted.is_ok() { - if let Err(error) = firmware.publish(&mut done) { - firmware.fail_stop(error, &mut done); - self.fail_stop(error); - } - if !firmware.engine.flights.is_empty() || firmware.engine.chan_wait { - self.rearm(firmware.engine.chan_wait); + match state.as_deref_mut() { + Some(firmware) => { + let res = self.submit_locked(firmware, job, &mut done); + let allow_stage = firmware.recovery.failed().is_none() + && !firmware.engine.frozen + && !self.sleeping.load(Ordering::Acquire); + scrubs = firmware.slots.stage_and_take_scrubs(allow_stage); + self.sync_active_flights(firmware); + res } + None => Err(ENODEV), } - accepted }; job::complete_all(done); + self.enqueue_scrubs(scrubs); + self.queue_feed(); drop(signalling); self.notify_wedged(); - accepted + Some(accepted) + } + + /// Hands staged displaced pass scrubs to the dedicated unbound scrub workqueue so SUBMIT + /// and completion polling never stall on write-combining zeroing. + pub(crate) fn enqueue_scrubs(self: &Arc, batch: super::slots::ScrubBatch) { + if batch.is_empty() { + return; + } + let mut queue = self.scrub_queue.lock(); + if self.sleeping.load(Ordering::Acquire) { + drop(queue); + drop(batch); + return; + } + if queue.push_batch(batch) { + // Queue under `scrub_queue` so `sleep.rs::join_workers()` cannot overlap + // `scrub_wq.drain()` with a concurrent enqueue once `sleeping` is set. + let _ = self + .scrub_wq + .enqueue::, SCRUB_WORK>(self.clone()); + } + } + + /// Drains queued displaced pass scrubs on the dedicated unbound scrub workqueue. + pub(crate) fn run_scrubs(self: &Arc) { + loop { + let Some(mut item) = self.scrub_queue.lock().pop() else { + break; + }; + if self.sleeping.load(Ordering::Acquire) { + drop(item); + break; + } + if item.run_one() && !self.sleeping.load(Ordering::Acquire) { + self.poll_now(); + } + } } /// Deliver userspace notification outside the device mutex and fence completion path. @@ -150,12 +471,62 @@ impl Shared { } } - /// Queues the poll work now, or brings a pending one forward. Callable from any context. + /// Publishes the active flight depth for lock-free completion worker placement. + fn sync_active_flights(&self, firmware: &Firmware) { + self.active_flights + .store(firmware.engine.flights.len() as u32, Ordering::Release); + } + + /// Queues fast completion polling: pinned to the submitting CPU for single-flight (`d=1`) + /// wakeups so the sleeping waiter stays cache-hot, and unbound when pipelined (`d>=2`) so + /// completion polling does not preempt an actively recording submitter. pub(crate) fn poll_now(self: &Arc) { - self.mod_poll(0); + if self.active_flights.load(Ordering::Acquire) >= 2 { + let _ = self + .events_unbound + .enqueue::, UNBOUND_POLL_WORK>(self.clone()); + return; + } + let _ = match self.submitter_cpu() { + Some(cpu) => self + .events + .enqueue_on::, FAST_POLL_WORK>(cpu, self.clone()), + None => self + .events + .enqueue::, FAST_POLL_WORK>(self.clone()), + }; + } + + /// Disarms the completion hrtimer when idle or entering system sleep. + /// + /// Always takes `resnap_handle` rather than checking a lock-free shadow flag so + /// `sleep::join_workers()` strictly orders with any concurrent `rearm()`: `sleep_down()` + /// stores `sleeping = true` before calling `cancel_resnap()`, and `rearm()` re-checks + /// `sleeping` under `resnap_handle.lock()` before installing a new handle. + pub(crate) fn cancel_resnap(&self) { + let mut handle = self.resnap_handle.lock(); + self.resnap_deadline_ns.store(0, Ordering::Release); + drop(handle.take()); + } + + /// Relaxes the completion hrtimer on healthy idle transitions without cancelling a + /// short (`<= resnap_us`) already-armed timer so back-to-back `d=1` bursts avoid + /// per-job cancel/restart mutex and hrtimer-rbtree churn. System sleep and fail-stop + /// paths still call [`Self::cancel_resnap`] unconditionally. + pub(crate) fn idle_resnap(&self) { + let armed_ns = self.resnap_deadline_ns.load(Ordering::Acquire); + if armed_ns == 0 { + return; + } + let now = now_ns(); + let keep_ns = u64::from(params::resnap_us()).saturating_mul(1000); + if armed_ns > now && armed_ns.saturating_sub(now) <= keep_ns { + return; + } + self.cancel_resnap(); } - /// Queues the poll on `system_highpri_wq` after `delay` jiffies, or moves an already + /// Queues the backup poll on `system_highpri_wq` after `delay` jiffies, or moves an already /// pending one to that expiry. fn mod_poll(self: &Arc, delay: Jiffies) { // SAFETY: The closure returns false only when `mod_delayed_work_on` found the work @@ -174,21 +545,59 @@ impl Shared { }; } - /// Re-checks a published command soon: hrtimer, with a one-jiffy backup; sooner while a - /// ready prefix waits for a channel record's consumption. - pub(crate) fn rearm(self: &Arc, chan_wait: bool) { - let mut us = params::resnap_us(); - if chan_wait && module_parameters::g16_repoll_us.value() != 0 { - us = params::repoll_us(); + /// Computes the hrtimer repoll delay in microseconds: `repoll_us` when `soon`, otherwise + /// adapts down to `clamp(ewma_flight_us / 2, repoll_us, resnap_us)` on sub-`2 * resnap_us` + /// bursts while respecting `g16_repoll_us == 0` as a full disable of shortened repolls. + pub(crate) fn rearm_us(&self, soon: bool) -> u32 { + let resnap = params::resnap_us(); + if module_parameters::g16_repoll_us.value() == 0 { + return resnap; } - { + let repoll = params::repoll_us(); + if soon { + return repoll; + } + let ewma = self.ewma_flight_us.load(Ordering::Relaxed); + if ewma != 0 && ewma < resnap.saturating_mul(2) { + (ewma / 2).clamp(repoll, resnap) + } else { + resnap + } + } + + /// Re-checks a published command soon: hrtimer, with a throttled 1-jiffy backup; sooner while + /// a ready prefix waits for record consumption or a post-event receipt tail is settling. + pub(crate) fn rearm(self: &Arc, soon: bool) { + self.rearm_after(self.rearm_us(soon)); + } + + /// Arms the poll hrtimer for `us` microseconds (coalescing with an already-armed deadline + /// within 5 us) plus the throttled 1-jiffy backup poll. + pub(crate) fn rearm_after(self: &Arc, us: u32) { + if self.sleeping.load(Ordering::Acquire) { + return; + } + let now = now_ns(); + let target_ns = now.saturating_add(u64::from(us) * 1000); + let armed_ns = self.resnap_deadline_ns.load(Ordering::Acquire); + if armed_ns == 0 || armed_ns <= now || target_ns.saturating_add(5_000) < armed_ns { let mut handle = self.resnap_handle.lock(); - // Dropping the previous handle cancels a still pending expiry before the timer - // is started again. - drop(handle.take()); - *handle = Some(self.clone().start(Delta::from_micros(i64::from(us)))); + if self.sleeping.load(Ordering::Acquire) { + return; + } + let armed_ns = self.resnap_deadline_ns.load(Ordering::Acquire); + if armed_ns == 0 || armed_ns <= now || target_ns.saturating_add(5_000) < armed_ns { + drop(handle.take()); + self.resnap_deadline_ns.store(target_ns, Ordering::Release); + *handle = Some(self.clone().start(Delta::from_micros(i64::from(us)))); + } + } + let backup_ns = self.backup_deadline_ns.load(Ordering::Acquire); + if now >= backup_ns { + self.backup_deadline_ns + .store(now.saturating_add(BACKUP_REARM_NS), Ordering::Release); + self.mod_poll(1); } - self.mod_poll(1); } /// Starts what the engine needs besides the firmware state: the `aurora-g16/stats` file. @@ -212,41 +621,148 @@ pub(crate) fn stamp_reached(obs: u32, own: u32, tail: u32) -> bool { } /// Cursor `c` of a ring of `m` entries passed end `h` of entries from `b`, within tail `t`. -#[allow(dead_code)] pub(crate) fn ring_passed(c: u32, b: u32, h: u32, t: u32, m: u32) -> bool { - let d = |x: u32| x.wrapping_add(m).wrapping_sub(b) % m; - let (dc, dh, dt) = (d(c), d(h), d(t)); - dh <= dc && dc <= dt + super::recovery::logic::ring_passed(c, b, h, t, m) } impl Firmware { - /// One poll pass under the device lock. Returns whether to re-arm the poll timers. - pub(crate) fn poll(&mut self, evented: bool, done: &mut Completions) -> Result { + /// Reclaims displaced slot leases belonging to closed VMs so dead processes do not keep + /// multi-hundred-MiB render/compute arenas and TTBAT ASIDs pinned while idle. + /// + /// Respects all hardware displacement contracts (active, in-flight, undisplaced, scrubbing, + /// and quarantined slots are preserved) and re-arms `Shared::closed_vm_reclaim` whenever a + /// non-quarantined slot still holds a closed VM awaiting retirement, displacement, or scrub. + pub(crate) fn reclaim_closed_vm_slots(&mut self) { + let Some(shared) = self.engine.shared.as_ref() else { + return; + }; + let armed = shared.closed_vm_reclaim.load(Ordering::Acquire) + && shared.closed_vm_reclaim.swap(false, Ordering::AcqRel); + // A closed VM's render retired and recorded its last epoch after the VM was closed. + if !self.pools.take_closed_vm_last() && !armed { + return; + } + let remaining = self.pools.reclaim_closed() | self.slots.reclaim_closed(); + if remaining { + shared.closed_vm_reclaim.store(true, Ordering::Release); + } + } + + /// One non-sleeping poll step under the device lock. + /// + /// Retires finished flights and publishes ready work before periodic 1 ms housekeeping so + /// completion fences wake userspace promptly. When an EP 0x20 event arrived with flights + /// outstanding and nothing retired yet, sets `*retry_tail` so [`Shared::run_poll`] drops + /// `Shared::state` across the 5 us receipt-tail delay instead of holding the device lock. + pub(crate) fn poll_step( + &mut self, + evented: bool, + tail: u32, + retry_tail: &mut bool, + housekeeping_deferred: &mut bool, + done: &mut Completions, + ) -> Result { if self.recovery.failed().is_some() { return Ok(false); } - self.session.check()?; - self.objects.health()?; - self.service_power()?; + self.engine.short_repoll = false; + self.session.transport()?; + let now = now_ns(); + let had_flights = !self.engine.flights.is_empty(); + let housekeeping_interval = if had_flights { + ACTIVE_HOUSEKEEPING_NS + } else { + HOUSEKEEPING_NS + }; + let housekeeping_due = + now.wrapping_sub(self.last_housekeeping_ns) >= housekeeping_interval; + let mut ran_housekeeping = false; // With nothing published only a pending firmware recovery notification needs this // pass: one that arrived after its prefix's receipts is answered // here (the firmware halted and waits for the resume) instead of being taken for a // failure of the next prefix. Drain the receive rings before deciding, published or // not, so the error count is current and idle log/trace/stats traffic is consumed. With // prefixes published the retirement loop below drains first. - if self.engine.flights.is_empty() { - self.drain_rings()?; + // + // Inside the housekeeping cadence, with no recovery pending, an idle pass drains only + // the event and statistics rings, which carry completion and recovery notifications. + // The session, object, power and auxiliary ring checks then wait for the cadence, so + // back-to-back shallow submissions do not repeat them, under the device lock, between + // one completion and the next SUBMIT. `run_poll()` queues a backup poll for them. + if !had_flights { + let full = housekeeping_due || self.recovery.receipt_fault || { + self.drain_events_and_stats()?; + self.recovery_pending()? + }; + if full { + self.session.check()?; + self.objects.health()?; + self.service_power()?; + self.last_housekeeping_ns = now; + self.last_aux_drain_ns = now; + ran_housekeeping = true; + self.engine.housekeeping_owed = false; + self.drain_rings()?; + } else { + self.engine.housekeeping_owed = true; + } + self.reclaim_closed_vm_slots(); if self.recovery_idle()? && self.engine.pending.is_empty() { + let _ = self.slots.take_scrub_woke(); + if let Some(shared) = self.engine.shared.as_ref() { + shared.publish_wake.store(false, Ordering::Release); + } return Ok(false); } } + let was_frozen = self.engine.frozen; + let stage_before = self.events.stage_events; + let term_before = self.oldest_terminal_events(); let mut lap = Lap::start(); let start = lap.on().then(now_ns); - self.retire(evented, done)?; + let retired_any = self.retire_once(done)?; lap.lap(&mut self.engine.prof.retire_ns); self.answer_growth()?; - self.check_hangs(done)?; - let published = self.publish(done); + let recovery_pending = self.recovery.receipt_fault || self.recovery_pending()?; + if recovery_pending { + self.check_hangs(done)?; + } + let unfrozen = was_frozen && !self.engine.frozen; + let scrub_woke = self.slots.take_scrub_woke(); + let publish_woke = self + .engine + .shared + .as_ref() + .is_some_and(|shared| shared.publish_wake.swap(false, Ordering::AcqRel)); + if retired_any || publish_woke || scrub_woke || housekeeping_due { + self.reclaim_closed_vm_slots(); + } + // Skip redundant `publish_checked()` walks on busy polls where nothing could have + // unblocked `engine.pending`. Standby release wakes `Cache::prepare` waiters, which + // enter `submit_locked()` directly. `publish_woke` covers external state changes + // including a closed VM's final reservation release. `ta_wave_ready()` wakes + // TA-wave-paced renders when a `0x70` TA pass finishes while FS is still running. + let coalesce_due = self.engine.coalesce_deadline_ns != 0 + && (!evented || now >= self.engine.coalesce_deadline_ns); + let should_publish = !self.engine.pending.is_empty() + && (retired_any + || !had_flights + || self.engine.flights.is_empty() + || self.engine.chan_wait + || unfrozen + || scrub_woke + || publish_woke + || self.ta_wave_ready() + || coalesce_due + || housekeeping_due); + let published = if should_publish { + self.publish_checked(done) + } else { + Ok(()) + }; + if self.engine.flights.is_empty() { + self.power.report_work(false); + } let s = &mut self.engine.stats; if self.engine.flights.is_empty() && s.idle_from_ns != 0 { // Idle with nothing ready is not a gap: the clients are late. @@ -258,43 +774,209 @@ impl Firmware { self.engine.prof.poll_ns += now_ns().wrapping_sub(start); } published?; + // A TA-only (0x70) EP 0x20 interrupt while FS is still running does not signal flight + // retirement: avoid burning the receipt-tail spin or arming a short repoll storm for it, + // unless a render queue is actively waiting on TA wave headroom (`ta_wave_wait`) or a + // ready job waits behind its own VM's flights (`held_wait`). + let non_terminal_only = !retired_any + && term_before.is_some() + && self.events.stage_events != stage_before + && self.oldest_terminal_events() == term_before + && !self.oldest_stamp_reached() + && !self.recovery.receipt_fault + && !recovery_pending + && !self.engine.ta_wave_wait + && !self.engine.held_wait; + // After an EP 0x20 event, retry up to `EVENT_RETIRE_POLLS` times (outside the device + // lock) only while no flight has retired yet and flights remain in flight. Once any + // flight retires, stop spinning so deeper queues do not burn tail waits per interrupt. + if evented + && had_flights + && !retired_any + && !non_terminal_only + && tail != 0 + && !self.engine.flights.is_empty() + && !self.recovery.receipt_fault + && !self.engine.frozen + && self.recovery.failed().is_none() + { + *retry_tail = true; + return Ok(true); + } + if !ran_housekeeping && housekeeping_due { + if !done.is_empty() || !self.engine.flights.is_empty() { + *housekeeping_deferred = true; + } else { + self.run_housekeeping(done)?; + } + } + // If a terminal EP 0x20 event arrived with flights outstanding and nothing retired within + // the trailing polls, or a ready same-VM pending job is blocked on slot/flight/work-ring + // or TA-wave headroom, or held behind its own VM's flights, repoll at `repoll_us` + // instead of sleeping `resnap_us`. + self.engine.short_repoll = !self.engine.flights.is_empty() + && !self.engine.frozen + && !non_terminal_only + && ((evented && had_flights && !retired_any) + || (!self.engine.pending.is_empty() + && (self.engine.slot_wait + || self.engine.ta_wave_wait + || self.engine.held_wait))); Ok(!self.engine.flights.is_empty() || self.engine.chan_wait || self.recovery.needs_repoll() || self.engine.frozen) } - /// Drains the rings and retires finished flights, with up to four trailing 5 us polls - /// after an event. A receipt fault is left in `Recovery::receipt_fault` for the hang - /// checks. - pub(crate) fn retire(&mut self, evented: bool, done: &mut Completions) -> Result { - // After an event, a few short trailing polls catch the final receipts. - let mut tail = if evented { 4 } else { 0 }; - let mut ret; - - loop { - let mut lap = Lap::start(); - self.drain_rings()?; - lap.lap(&mut self.engine.prof.drain_ns); - // Recovery may force stage progress: authenticate it before any receipt. + /// Periodic 1 ms housekeeping (session/object health, power governor, auxiliary log/trace + /// ring drain, administrative hang checks), run after retired completion fences have been + /// signalled when work retired. + pub(crate) fn run_housekeeping(&mut self, done: &mut Completions) -> Result { + if self.recovery.failed().is_some() { + return Ok(()); + } + self.session.transport()?; + self.session.check()?; + self.objects.health()?; + self.service_power()?; + let now = now_ns(); + let recovery_pending = self.recovery.receipt_fault || self.recovery_pending()?; + if self.engine.flights.is_empty() + || recovery_pending + || now.wrapping_sub(self.last_aux_drain_ns) >= AUX_DRAIN_NS + { + self.drain_auxiliary_rings()?; + self.last_aux_drain_ns = now; + } + self.last_housekeeping_ns = now; + self.engine.housekeeping_owed = false; + self.reclaim_closed_vm_slots(); + if !self.engine.flights.is_empty() || recovery_pending { self.check_hangs(done)?; - ret = self.retired(); - while let Ok(receipt) = ret { - if !receipt.complete() { - break; + } + Ok(()) + } + + /// Terminal completion-event counters for the oldest active flight of each class + /// (`(compute_events, fs_events)`), used to distinguish TA-only (0x70) non-terminal events. + fn oldest_terminal_events(&self) -> Option<(Option, Option)> { + if self.engine.flights.is_empty() + || self + .engine + .flights + .iter() + .any(|f| f.computes != 0 && f.renders != 0) + { + return None; + } + let compute = self + .engine + .flights + .iter() + .any(|f| f.computes != 0) + .then_some(self.events.compute_events); + let render = self + .engine + .flights + .iter() + .any(|f| f.renders != 0) + .then_some(self.events.fs_events); + Some((compute, render)) + } + + /// Whether a render job paused by TA wave pacing has enough TA headroom to publish + /// the next wave without dribbling 1-pass stub flights. + fn ta_wave_ready(&self) -> bool { + let cap = self.active_ta_wave_cap(); + self.engine.ta_wave_wait + && self.ta_pending_passes() + <= cap.saturating_sub(super::hw::sizes::TA_WAVE_REFILL_HEADROOM) + } + + /// Cheap single-stage stamp check for the oldest compute pipe 0/1 and oldest render flights' + /// terminal stages so `submit_locked()` can eagerly retire finished work without scanning + /// all rings when nothing has completed. + fn oldest_stamp_reached(&self) -> bool { + if self.engine.flights.is_empty() { + return false; + } + let mut oldest_compute: [Option<&Flight>; super::hw::sizes::COMPUTE_PIPES] = + [None; super::hw::sizes::COMPUTE_PIPES]; + let mut compute_behind = [false; super::hw::sizes::COMPUTE_PIPES]; + let mut oldest_render: Option<&Flight> = None; + let mut render_behind = false; + for f in self.engine.flights.iter() { + if f.computes != 0 { + let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + if oldest_compute[p].is_none() { + oldest_compute[p] = Some(f); + } else { + compute_behind[p] = true; } - let outcome = self.retire_outcome(receipt); - self.retire_oldest(receipt, outcome, done); - ret = self.retired(); } - if ret.is_err() || tail == 0 || self.engine.flights.is_empty() { - break; + if f.renders != 0 { + if oldest_render.is_none() { + oldest_render = Some(f); + } else { + render_behind = true; + } } - tail -= 1; - delay::udelay(Delta::from_micros(5)); + } + rmb(); + for p in 0..super::hw::sizes::COMPUTE_PIPES { + if let Some(f) = oldest_compute[p] { + if let Ok(obs) = self.graph.compute[p].fw_stamp.r32(0) { + let reached = if compute_behind[p] { + stamp_reached(obs, f.target, self.engine.target[p]) + } else { + obs == f.target + }; + if reached { + return true; + } + } + } + } + if let Some(f) = oldest_render { + if let Ok(obs) = self.graph.render.fw_stamp[1].r32(0) { + let reached = if render_behind { + stamp_reached(obs, f.fs_target, self.engine.fs_target) + } else { + obs == f.fs_target + }; + if reached { + return true; + } + } + } + false + } + + /// Drains the event/stats rings and retires all currently complete oldest compute and render + /// flights independently without sleeping. Returns whether at least one flight retired. A + /// receipt fault is left in `Recovery::receipt_fault` for the hang checks. + pub(crate) fn retire_once(&mut self, done: &mut Completions) -> Result { + let mut lap = Lap::start(); + self.drain_events_and_stats()?; + lap.lap(&mut self.engine.prof.drain_ns); + // Recovery may force stage progress: authenticate it before any receipt. + if self.recovery.receipt_fault || self.recovery_pending()? { + self.check_hangs(done)?; + } + if self.engine.flights.is_empty() { + return Ok(false); + } + let mut retired_any = false; + let (mut check_compute, mut check_render) = ([true; super::hw::sizes::COMPUTE_PIPES], true); + let mut ret = self.retired_flight_classes(&mut check_compute, &mut check_render); + while let Ok(Some((index, receipt))) = ret { + let outcome = self.retire_outcome_at(index, receipt); + self.retire_oldest(index, receipt, outcome, done); + retired_any = true; + ret = self.retired_flight_classes(&mut check_compute, &mut check_render); } self.recovery.receipt_fault = ret.is_err(); - Ok(()) + Ok(retired_any) } #[allow(dead_code)] @@ -302,17 +984,52 @@ impl Firmware { o.r32(offset) } - /// Exact M4 queue and submit-pipe proof for one serialized publication. Event - /// notifications are wakeups; neither an event nor elapsed time releases an owner. - pub(crate) fn queue_receipt( + /// A compute unit's GPU start and end ticks. 25G83 writes them into the unit's ITS pair; + /// ABIs with `work_ticks` leave ITS 0/0 and write them into the work object. Check + /// `work_ticks` first when the ABI defines them so 26B123 skips two always-zero WC reads + /// per command, invalidating the cacheable `FwCoherent` work lines to PoC before reading + /// (`sync_for_cpu`), and falling back to ITS if `work_ticks` holds no interval. + fn compute_ticks(&self, unit: &super::slots::ComputeSlot) -> Result<(u64, u64)> { + Self::compute_ticks_with(self.init.abi.compute().work_ticks, unit) + } + + fn compute_ticks_with( + work_ticks: Option<(usize, usize)>, + unit: &super::slots::ComputeSlot, + ) -> Result<(u64, u64)> { + if let Some((start_off, end_off)) = work_ticks { + let w = &unit.work; + let lo = start_off.min(end_off); + let hi = start_off.max(end_off).checked_add(8).ok_or(EINVAL)?; + w.sync_for_cpu(lo, hi - lo)?; + // Work tick offsets are 4-byte aligned (not 8-byte), so read hi/lo/hi to avoid tearing. + let at = |o: usize| -> Result { + for _ in 0..4 { + let hi1 = w.r32(o + 4)?; + let lo = w.r32(o)?; + let hi2 = w.r32(o + 4)?; + if hi1 == hi2 { + return Ok(u64::from(lo) | (u64::from(hi1) << 32)); + } + } + Err(EIO) + }; + let (start, end) = (at(start_off)?, at(end_off)?); + if start != 0 && end >= start { + return Ok((start, end)); + } + } + Ok((unit.its.r64(0)?, unit.its.r64(8)?)) + } + + /// Exact queue-ring proof for one serialized publication on its workqueue pipe. + fn queue_ring_receipt( &self, - channel: Channel, state: &super::object::FwObject, info: &super::object::FwObject, head: u32, - record: u32, ) -> Result { - if head >= 256 || record >= 256 { + if head >= 256 { return Err(EINVAL); } // M4's qualified NC cursors are READ and WRITE. Offset zero is not an M4 @@ -322,131 +1039,435 @@ impl Firmware { return Ok(false); } } - if !super::hw::tuning::FW_CACHED { + if !super::hw::tuning::FW_CACHED && !super::graph::qinfo_cached() { for offset in [0x20, 0x24, 0x28] { if info.r32(offset)? != head { return Ok(false); } } - if info.r32(0x80)? != 0 { + if info.r32(self.init.abi.qinfo().busy)? != 0 { return Ok(false); } } // With ASC-cached QI, its three consumers and busy flag can remain stale until // terminal CIVAC. The working M4 protocol substitutes the NC READ cursor above. - let pipe = self.channels.channel(channel); - if pipe.read()? != record || pipe.completion()? != record || pipe.write()? != record { + Ok(true) + } + + /// Passed queue-ring proof when later flights are queued behind `f` on the same pipe. + fn queue_ring_passed( + &self, + channel: Channel, + state: &super::object::FwObject, + info: &super::object::FwObject, + f: &Flight, + ) -> Result { + let cap = super::hw::sizes::QUEUE_CAP; + let (start, head, tail) = match channel { + Channel::Compute => { + let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + (f.c_start, f.head, self.engine.head[p]) + } + Channel::Ta => (f.ta_start, f.ta_head, self.engine.ta_head), + Channel::Fs => (f.fs_start, f.fs_head, self.engine.fs_head), + }; + if head >= cap || start >= cap || tail >= cap { + return Err(EINVAL); + } + if !ring_passed(state.r32(qstate::READ)?, start, head, tail, cap) { return Ok(false); } + if !super::hw::tuning::FW_CACHED && !super::graph::qinfo_cached() { + for offset in [0x20, 0x24, 0x28] { + if !ring_passed(info.r32(offset)?, start, head, tail, cap) { + return Ok(false); + } + } + } Ok(true) } + /// Submit-channel proof for `record`: exact when no later record exists on `channel`, + /// otherwise passed within the current channel producer frontier. + fn channel_receipt(&self, channel: Channel, record: u32, passed: bool) -> Result { + let slots = super::fw::channels::RING_SLOTS; + if record >= slots { + return Err(EINVAL); + } + let pipe = self.channels.channel(channel); + if passed { + let read = pipe.read()?; + let comp = pipe.completion()?; + if read >= slots || comp >= slots { + return Ok(false); + } + let first = (record + slots - 1) % slots; + let producer = self.channels.producer(channel); + Ok(ring_passed(read, first, record, producer, slots) + && ring_passed(comp, first, record, producer, slots)) + } else { + Ok(pipe.read()? == record && pipe.completion()? == record && pipe.write()? == record) + } + } + + /// Latches `Channel::Compute` read and completion proofs onto active compute flights before + /// the shared submit ring can lap them, so a long flight on one compute pipe stays retirable + /// even after other pipes wrap the 256-entry submit channel. + pub(crate) fn latch_compute_channel_receipts(&mut self) -> Result { + if !self + .engine + .flights + .iter() + .any(|f| f.computes != 0 && !f.chan_settled) + { + return Ok(()); + } + let slots = super::fw::channels::RING_SLOTS; + let pipe = self.channels.channel(Channel::Compute); + let read = pipe.read()?; + let comp = pipe.completion()?; + if read >= slots || comp >= slots { + return Ok(()); + } + let producer = self.channels.producer(Channel::Compute); + for f in self.engine.flights.iter_mut() { + if f.computes == 0 || f.chan_settled { + continue; + } + let record = f.rec[2]; + if record >= slots { + return Err(EINVAL); + } + let first = (record + slots - 1) % slots; + if ring_passed(read, first, record, producer, slots) + && ring_passed(comp, first, record, producer, slots) + { + f.chan_settled = true; + } + } + Ok(()) + } + + /// Exact M4 queue and submit-pipe proof for one serialized publication. Event + /// notifications are wakeups; neither an event nor elapsed time releases an owner. + pub(crate) fn queue_receipt( + &self, + channel: Channel, + state: &super::object::FwObject, + info: &super::object::FwObject, + head: u32, + record: u32, + ) -> Result { + Ok(self.queue_ring_receipt(state, info, head)? + && self.channel_receipt(channel, record, false)?) + } + + /// In-order receipt of flight `f` with later flights queued behind it: the NC READ cursor + /// (and with uncached queue info its consumers) passed its ring entries, and the submit + /// pipe's read and completion cursors passed its record. + fn queue_passed( + &self, + channel: Channel, + state: &super::object::FwObject, + info: &super::object::FwObject, + f: &Flight, + ) -> Result { + let record = match channel { + Channel::Compute => f.rec[2], + Channel::Ta => f.rec[0], + Channel::Fs => f.rec[1], + }; + Ok(self.queue_ring_passed(channel, state, info, f)? + && self.channel_receipt(channel, record, true)?) + } + /// A full receipt includes stage and notifier stamps, every physical consumer, /// the private allocator completion and the internal timestamp pair. An aborted /// receipt omits only the writes firmware does not make for an aborted command, /// after the recovery grace period and its queue/pipe/stage passed proof. pub(crate) fn retired(&mut self) -> Result { - match self.retired_snapshot() { + self.retired_at(0) + } + + fn retired_at(&mut self, index: usize) -> Result { + match self.retired_snapshot_at(index) { // A changing packed receipt is not an authenticated firmware failure. Err(error) if error == EAGAIN => Ok(Retirement::Pending), result => result, } } + /// Inspects the oldest compute flight per pipe and oldest render flight independently so any + /// pipe/class can retire as soon as its hardware receipt settles without waiting on another. + pub(crate) fn retired_flight(&mut self) -> Result> { + let (mut check_compute, mut check_render) = ([true; super::hw::sizes::COMPUTE_PIPES], true); + self.retired_flight_classes(&mut check_compute, &mut check_render) + } + + /// Like [`Self::retired_flight`], skipping pipes/classes that are inactive or already known + /// pending in the current [`Self::retire_once`] pass and never polling a mixed flight twice. + fn retired_flight_classes( + &mut self, + check_compute: &mut [bool; super::hw::sizes::COMPUTE_PIPES], + check_render: &mut bool, + ) -> Result> { + let mut compute_idx = [None; super::hw::sizes::COMPUTE_PIPES]; + let mut render_idx = None; + if check_compute.iter().any(|&c| c) || *check_render { + for (i, f) in self.engine.flights.iter().enumerate() { + if f.computes != 0 { + let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + if check_compute[p] && compute_idx[p].is_none() { + compute_idx[p] = Some(i); + } + } + if *check_render && render_idx.is_none() && f.renders != 0 { + render_idx = Some(i); + } + } + } + for p in 0..super::hw::sizes::COMPUTE_PIPES { + if compute_idx[p].is_none() { + check_compute[p] = false; + } + } + if render_idx.is_none() { + *check_render = false; + } + for p in 0..super::hw::sizes::COMPUTE_PIPES { + if let Some(index) = compute_idx[p] { + let receipt = self.retired_at(index)?; + if receipt.complete() { + return Ok(Some((index, receipt))); + } + check_compute[p] = false; + if render_idx == Some(index) { + *check_render = false; + render_idx = None; + } + } + } + if let Some(index) = render_idx { + let receipt = self.retired_at(index)?; + if receipt.complete() { + return Ok(Some((index, receipt))); + } + *check_render = false; + } + Ok(None) + } + fn retired_snapshot(&mut self) -> Result { - let Some(f) = self.engine.oldest() else { + self.retired_snapshot_at(0) + } + + fn retired_snapshot_at(&mut self, index: usize) -> Result { + let Some(f) = self.engine.flights.get(index) else { return Ok(Retirement::Pending); }; rmb(); let mut full = true; + let mut ticks = [0u64; 4]; + // Later flights of the same pipe/class queued behind this one: that pipe's queue and + // stamp cells already moved on, so its receipt is "passed", in order; the newest flight + // of a pipe keeps its exact queue receipt while Channel::Compute is checked independently + // against the shared submit-channel producer frontier. if f.computes != 0 { - let g = &self.graph.compute; - if g.fw_stamp.r32(0)? != f.target - || !self.queue_receipt(Channel::Compute, &g.qstate, &g.qinfo, f.head, f.rec[2])? - { - return Ok(Retirement::Pending); - } - let k = f.claims.slot[0] as usize; - let unit = f.job.resources.compute()?.compute.get(k).ok_or(EINVAL)?; - let submitted = unit.counter.r64(0)?; - let start = unit.its.r64(0)?; - let end = unit.its.r64(8)?; - full &= g.notifier.r32(notifier_page::COMPUTE_STAMP)? == f.target - && g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot - && submitted != 0 - && unit.work.r64(compute::DESCRIPTOR_COMPLETED)? == submitted - && unit.work.r64(compute::DESCRIPTOR_COUNTER)? == unit.counter.va - && start != 0 - && end > start; + let pipe = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + let pipe_behind = self + .engine + .flights + .iter() + .filter(|o| o.computes != 0 && o.compute_pipe == f.compute_pipe) + .nth(1) + .is_some(); + let chan_behind = self + .engine + .flights + .iter() + .filter(|o| o.computes != 0) + .nth(1) + .is_some() + || f.rec[2] != self.channels.producer(Channel::Compute); + let g = &self.graph.compute[pipe]; + if pipe_behind { + let tail = self.engine.target[pipe]; + if !stamp_reached(g.fw_stamp.r32(0)?, f.target, tail) + || !self.queue_ring_passed(Channel::Compute, &g.qstate, &g.qinfo, f)? + || !(f.chan_settled + || self.channel_receipt(Channel::Compute, f.rec[2], chan_behind)?) + { + return Ok(Retirement::Pending); + } + rmb(); + let stamp = g.notifier.r32(notifier_page::COMPUTE_STAMP)?; + full &= stamp_reached(stamp, f.target, tail) + && (stamp != f.target + || g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot); + } else { + if g.fw_stamp.r32(0)? != f.target + || !self.queue_ring_receipt(&g.qstate, &g.qinfo, f.head)? + || !(f.chan_settled + || self.channel_receipt(Channel::Compute, f.rec[2], chan_behind)?) + { + return Ok(Retirement::Pending); + } + rmb(); + full &= g.notifier.r32(notifier_page::COMPUTE_STAMP)? == f.target + && g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot; + } + let count = f.claims.slot_count as usize; + full &= count != 0 && count == f.computes as usize; + if full { + for m in 0..count { + let k = f.claims.slot[m] as usize; + let unit = f.job.resources.compute_unit(k)?; + let submitted = f.csubmitted[m]; + if submitted == 0 + || unit.counter.r64(0)? != submitted + || unit.descriptor.r64(manager::COMPLETED)? != submitted + || unit.descriptor.r64(manager::COUNTER)? != unit.counter.va + { + full = false; + break; + } + let (start, end) = self.compute_ticks(unit)?; + if start == 0 || end < start { + full = false; + break; + } + if m == 0 && count == 1 { + ticks = [start, end, 0, 0]; + } + } + } } if f.renders != 0 { + let render_behind = self + .engine + .flights + .iter() + .filter(|o| o.renders != 0) + .nth(1) + .is_some(); let g = &self.graph.render; - if g.fw_stamp[0].r32(0)? != f.ta_target - || g.fw_stamp[1].r32(0)? != f.fs_target - || !self.queue_receipt( - Channel::Ta, - &g.qstate[0], - &g.qinfo[0], - f.ta_head, - f.rec[0], - )? - || !self.queue_receipt( - Channel::Fs, - &g.qstate[1], - &g.qinfo[1], - f.fs_head, - f.rec[1], - )? - { - return Ok(Retirement::Pending); - } - let k = f.claims.pass[0] as usize; - let unit = f.job.resources.render()?.passes.get(k).ok_or(EINVAL)?; - let ta_start = unit.scene.r64(0x600)?; - let ta_end = unit.scene.r64(0x608)?; - let fs_start = unit.scene.r64(0x620)?; - let fs_end = unit.scene.r64(0x628)?; - full &= g.notifier.r32(notifier_page::TA_STAMP)? == f.ta_target - && g.notifier.r32(notifier_page::FS_STAMP)? == f.fs_target - && g.notifier.r32(notifier::CONTEXT)? == f.job.vm.slot - && g.notifier - .r32(notifier_page::FS_RECORD + notifier::CONTEXT)? - == f.job.vm.slot - && f.job.resources.render()?.pools.retired(k)? - && ta_start != 0 - && ta_end > ta_start - && fs_start != 0 - && fs_end > fs_start; + let a = f.pb_slot as usize; + if render_behind { + let e = &self.engine; + // Check FS (terminal stage) before TA so running renders fail fast on 1 WC read. + if !stamp_reached(g.fw_stamp[1].r32(0)?, f.fs_target, e.fs_target) + || !stamp_reached(g.fw_stamp[0].r32(0)?, f.ta_target, e.ta_target) + || !self.queue_passed(Channel::Ta, &g.qstate[0], &g.qinfo[0], f)? + || !self.queue_passed(Channel::Fs, &g.qstate[1], &g.qinfo[1], f)? + { + return Ok(Retirement::Pending); + } + rmb(); + let fs_stamp = g.notifier.r32(notifier_page::FS_STAMP)?; + let ta_stamp = g.notifier.r32(notifier_page::TA_STAMP)?; + full &= stamp_reached(fs_stamp, f.fs_target, e.fs_target) + && (fs_stamp != f.fs_target + || g.notifier + .r32(notifier_page::FS_RECORD + notifier::CONTEXT)? + == f.job.vm.slot) + && stamp_reached(ta_stamp, f.ta_target, e.ta_target) + && (ta_stamp != f.ta_target + || g.notifier.r32(notifier::CONTEXT)? == f.job.vm.slot) + && f.job + .resources + .pb_retired_at(a, f.uma_submitted)?; + } else { + // Check FS (terminal stage) before TA so running renders fail fast on 1 WC read. + if g.fw_stamp[1].r32(0)? != f.fs_target + || g.fw_stamp[0].r32(0)? != f.ta_target + || !self.queue_receipt( + Channel::Ta, + &g.qstate[0], + &g.qinfo[0], + f.ta_head, + f.rec[0], + )? + || !self.queue_receipt( + Channel::Fs, + &g.qstate[1], + &g.qinfo[1], + f.fs_head, + f.rec[1], + )? + { + return Ok(Retirement::Pending); + } + rmb(); + full &= g.notifier.r32(notifier_page::FS_STAMP)? == f.fs_target + && g.notifier.r32(notifier_page::TA_STAMP)? == f.ta_target + && g.notifier.r32(notifier::CONTEXT)? == f.job.vm.slot + && g.notifier + .r32(notifier_page::FS_RECORD + notifier::CONTEXT)? + == f.job.vm.slot + && f.job.resources.pb_retired(a)?; + } + if full { + let count = (f.renders as usize).min(f.claims.pass.len()); + for m in 0..count { + let k = f.claims.pass[m] as usize; + let unit = f.job.resources.render_pass(k)?; + let ta_start = unit.scene.r64(0x600)?; + let ta_end = unit.scene.r64(0x608)?; + let fs_start = unit.scene.r64(0x620)?; + let fs_end = unit.scene.r64(0x628)?; + if count == 1 && f.computes == 0 { + ticks = [ta_start, ta_end, fs_start, fs_end]; + } + full &= ta_start != 0 + && ta_end >= ta_start + && fs_start != 0 + && fs_end >= fs_start; + if !full { + break; + } + } + } } if full { + self.engine.retired_ticks = ticks; return Ok(Retirement::Full); } - if f.recovery_suspect && now_ns().saturating_sub(f.recovery_started_ns) >= 20_000_000 { - // Queues, pipes and every participating stage passed the retained command. - // The firmware recovered it without normal completion: fail and quarantine. - if let Some(f) = self.engine.flights.first_mut() { - f.doomed = true; + if f.recovery_suspect { + // Queues, pipes and every participating stage passed the retained command, yet normal + // receipts have not settled. Measure the abort grace from this first gate-passed poll + // and require a second unsettled poll so an innocent suspect flight finishing > 20 ms + // after recovery cannot race a transient WC/notifier write into a false abort. + let now = now_ns(); + let aborted = if let Some(f) = self.engine.flights.get_mut(index) { + let first = *f.gate_passed_ns.get_or_insert(now); + f.unsettled_polls = f.unsettled_polls.saturating_add(1); + if f.unsettled_polls >= 2 && now.saturating_sub(first) >= ABORT_GRACE_NS { + f.doomed = true; + true + } else { + false + } + } else { + false + }; + if aborted { + return Ok(Retirement::Aborted); } - return Ok(Retirement::Aborted); } Ok(Retirement::Pending) } - /// Logs the non-zero fault banks of `state`. - #[allow(dead_code)] + /// Logs the fault bank of `state` when it holds a fault. pub(crate) fn log_fault(&self, state: &EngineState) { - for bank in 0..2 { - let (f, va) = (state.status[bank], state.address[bank]); - if f == 0 { - continue; - } + let (bank, f, va) = (state.bank, state.status, state.address); + if f != 0 { let access = if (f >> 4) & 1 != 0 { "read" } else { "write" }; let reason = if (f >> 1) & 7 != 0 { "reason!=unmapped" } else { "unmapped" }; - dev_info!( + dev_warn!( self.graph.dev.as_ref(), "G16: fault bank {}: status {:#x} va {:#x} ({} {} level {} unit {:#x} ctx {})\n", bank, @@ -461,78 +1482,160 @@ impl Firmware { } } - /// Retire the oldest prefix's scheduling ownership. Only a full normal receipt retires - /// its storage; a passed abort quarantines it. Job failure independently drops remaining - /// unpublished commands even when the storage fully retired. + /// Publishes lockless quarantine hints so `SUBMIT` expands extension and recovery slots + /// immediately when a base or PB allocator slot has been permanently quarantined. + pub(crate) fn sync_quarantine_hints(&self) { + if let Some(shared) = &self.engine.shared { + shared + .base_compute_quarantined + .store(self.slots.base_compute_quarantined(), Ordering::Release); + shared + .quarantined_compute_mask + .store(self.slots.quarantined_compute_mask(), Ordering::Release); + shared + .base_render_quarantined + .store(self.slots.base_render_quarantined(), Ordering::Release); + shared + .quarantined_pb_mask + .store(self.pools.quarantined_mask(), Ordering::Release); + } + } + + /// Retire the flight at `index` (the oldest of its engine class). Only a full normal receipt + /// retires its storage; a passed abort quarantines it. Job failure independently drops + /// remaining unpublished commands even when the storage fully retired. + #[inline(never)] pub(crate) fn retire_oldest( &mut self, + index: usize, receipt: Retirement, result: Result, done: &mut Completions, ) { - if self.engine.flights.is_empty() { + if index >= self.engine.flights.len() { return; } - let Ok(mut f) = self.engine.flights.remove(0) else { + let Ok(mut f) = self.engine.flights.remove(index) else { return; }; let timestamp_claims = f.claims; + let retired_ticks = self.engine.retired_ticks; + self.engine.retired_ticks = [0; 4]; if result.is_ok() { - self.stat_retire(&f); + self.stat_retire(&f, retired_ticks); + if let Some(shared) = &self.engine.shared { + let now = now_ns(); + shared.feed.note_flight(f.published_ns, now); + if f.published_ns != 0 && now > f.published_ns { + let dur_us = ((now - f.published_ns) / 1000).clamp(1, 10_000) as u32; + shared.note_flight_us(dur_us); + } + } } if receipt.owner_retired() { if let Err(error) = self.slots.retire(&mut f.claims) { self.slots.quarantine(&mut f.claims); + self.sync_quarantine_hints(); self.retain(&f.job); complete(done, &f.job, Err(error)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, Err(error)); + } self.fail_stop(error, done); + core::mem::forget(f); return; } if f.computes != 0 { - self.recovery.last_retired[0] = Some(f.target); + let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + for &stamp in &f.cstamp[..(f.computes as usize).min(f.cstamp.len())] { + self.recovery.last_retired.push(p, stamp); + } } if f.renders != 0 { - self.recovery.last_retired[1] = Some(f.ta_target); - self.recovery.last_retired[2] = Some(f.fs_target); - let committed = f.job.resources.pb(f.first).and_then(|epoch| { - self.pools - .retire_binding(timestamp_claims.pass[0] as usize, epoch) + for m in 0..(f.renders as usize).min(f.r_ta_stamp.len()) { + self.recovery + .last_retired + .push(super::hw::sizes::COMPUTE_PIPES, f.r_ta_stamp[m]); + self.recovery + .last_retired + .push(super::hw::sizes::COMPUTE_PIPES + 1, f.r_fs_stamp[m]); + } + let committed = f.pb.as_ref().ok_or(EINVAL).and_then(|epoch| { + self.pools.retire_flight( + f.pb_slot as usize, + epoch, + f.pb_binding, + result.is_ok(), + ) }); if let Err(error) = committed { self.retain(&f.job); complete(done, &f.job, Err(error)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, Err(error)); + } self.fail_stop(error, done); + core::mem::forget(f); return; } } - if let Err(error) = f.job.note_full_retirement(f.first as u32, f.count as u32) { + let retired_ok = (|| -> Result { + f.job.note_full_retirement(f.first as u32, f.count as u32)?; + for j2 in f.group.iter() { + j2.note_full_retirement(0, j2.progress.count())?; + } + Ok(()) + })(); + if let Err(error) = retired_ok { self.retain(&f.job); complete(done, &f.job, Err(error)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, Err(error)); + } self.fail_stop(error, done); + core::mem::forget(f); return; } if result.is_err() { + self.slots.mark_dirty(×tamp_claims); self.recovery.affected_full_receipts = self.recovery.affected_full_receipts.saturating_add(1); } } else { // Only an actual passed abort lacks the full owner receipt. An affected job // with a full normal receipt fails its fence without poisoning healthy storage. + if f.renders != 0 { + // Quarantine the aborted allocator slot permanently and retain the aborted + // flight's epoch alongside the prior slot owner. + self.pools.quarantine_flight(f.pb_slot as usize, f.pb.take()); + } self.slots.quarantine(&mut f.claims); + self.sync_quarantine_hints(); self.retain(&f.job); + for j2 in f.group.iter() { + self.retain(j2); + } self.recovery.aborted_receipts = self.recovery.aborted_receipts.saturating_add(1); } if self.slots.compute_exhausted() { self.mark_class_unavailable(super::command::COMPUTE, EIO); } - if self.slots.render_exhausted() { + if self.slots.render_exhausted() || self.pools.exhausted() { self.mark_class_unavailable(super::command::RENDER, EIO); } if result.is_ok() { if let Err(error) = self.publish_timestamps(&f, ×tamp_claims) { self.retain(&f.job); complete(done, &f.job, Err(error)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, Err(error)); + } self.fail_stop(error, done); + core::mem::forget(f); return; } // Publish queue-local EXACT_PRIOR frontiers only after every normal hardware @@ -541,27 +1644,90 @@ impl Firmware { if let Err(error) = f.job.command_retired(index as u32) { self.retain(&f.job); complete(done, &f.job, Err(error)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, Err(error)); + } self.fail_stop(error, done); + core::mem::forget(f); return; } } + for j2 in f.group.iter() { + for index in 0..j2.progress.count() { + if let Err(error) = j2.command_retired(index) { + self.retain(&f.job); + complete(done, &f.job, Err(error)); + for j3 in f.group.iter() { + self.retain(j3); + complete(done, j3, Err(error)); + } + self.fail_stop(error, done); + core::mem::forget(f); + return; + } + } + } + if receipt.owner_retired() && f.renders != 0 { + self.slots.note_render_retired(); + } } if self.engine.flights.is_empty() { // Drained: a gap until the next publication. self.engine.stats.idle_from_ns = now_ns(); self.power.utilization.idle(self.engine.stats.idle_from_ns); + self.power.report_work(false); + } + // The next prefix on the retired flight's pipe/class starts executing about now. + if f.renders != 0 { + self.renew_render_deadline(); + } + if f.computes != 0 { + let pipe = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + self.renew_compute_pipe_deadline(pipe); } - // The next prefix starts executing about now. - self.renew_deadlines(); let job = f.job.clone(); let p = &job.progress; p.next.store(p.next() + f.count as u32, Ordering::Relaxed); + if result.is_err() { + // Later commands of this queue, and any cross-queue flights transitively waiting + // on it via firmware handoff, fail with it so no dependent command reports success + // after an upstream failure. + let mut changed = false; + for later in self.engine.flights.iter_mut() { + if !later.doomed + && (Arc::ptr_eq(&later.job.queue, &job.queue) + || later.job.waits_on_queue(&job.queue)) + { + later.doomed = true; + changed = true; + } + } + while changed { + changed = false; + for i in 0..self.engine.flights.len() { + if self.engine.flights[i].doomed { + continue; + } + let dep_doomed = self.engine.flights.iter().any(|other| { + other.doomed + && (Arc::ptr_eq(&other.job.queue, &self.engine.flights[i].job.queue) + || self.engine.flights[i].job.waits_on_queue(&other.job.queue)) + }); + if dep_doomed { + self.engine.flights[i].doomed = true; + changed = true; + } + } + } + } if let Err(error) = result { if p.is_pending() { // Drop its unpublished commands. p.pending.store(false, Ordering::Relaxed); self.engine.pending.retain(|j| !Arc::ptr_eq(j, &job)); p.count.store(p.sent(), Ordering::Relaxed); + job.resources.discard_unpublished_renders(); } if receipt.owner_retired() && self.engine.flights.iter().all(|other| { @@ -575,66 +1741,129 @@ impl Firmware { if let Err(proof_error) = job.mark_terminal_retired() { self.retain(&job); complete(done, &job, Err(proof_error)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, Err(proof_error)); + } self.fail_stop(proof_error, done); + core::mem::forget(f); return; } } complete(done, &job, Err(error)); } - if p.next() < p.sent() || p.sent() < p.count() { - return; // more of it published or still to publish - } - let s = &mut self.engine.stats; - if result.is_ok() { - s.jobs += 1; - s.job_cmds += u64::from(p.count()); - s.job_max = s.job_max.max(u64::from(p.count())); + let job_done = p.next() >= p.sent() && p.sent() >= p.count(); + if job_done { + let s = &mut self.engine.stats; + if result.is_ok() { + s.jobs += 1; + s.job_cmds += u64::from(p.count()); + s.job_max = s.job_max.max(u64::from(p.count())); + } + complete(done, &job, Ok(())); } - complete(done, &job, Ok(())); - // The rest of a compute horizon, after the first job (fence order). + // Complete folded horizon jobs unconditionally (even if an earlier command of `job` + // is still in flight; `Timeline` preserves queue fence order). for j2 in f.group.iter() { let p2 = &j2.progress; p2.next.store(p2.count(), Ordering::Relaxed); match result { - Err(error) => complete(done, j2, Err(error)), + Err(error) => { + if receipt.owner_retired() + && self.engine.flights.iter().all(|other| { + !Arc::ptr_eq(&other.job, j2) + && other.group.iter().all(|member| !Arc::ptr_eq(member, j2)) + }) + { + if let Err(proof_error) = j2.mark_terminal_retired() { + self.retain(j2); + complete(done, j2, Err(proof_error)); + self.fail_stop(proof_error, done); + core::mem::forget(f); + return; + } + } + complete(done, j2, Err(error)); + } Ok(()) => { + let s = &mut self.engine.stats; s.jobs += 1; s.job_cmds += u64::from(p2.count()); s.job_max = s.job_max.max(u64::from(p2.count())); + complete(done, j2, Ok(())); } } - complete(done, j2, Ok(())); } } - /// Progress of the oldest prefix: a FW stamp of an engine on which it still has unreached - /// work moved since the last poll (later prefixes' work on other engines does not count). - /// Renews the deadline; the first call for a prefix only records its position. + /// Progress of the oldest compute pipes and oldest render flights: a FW stamp of a pipe on + /// which its oldest flight still has unreached work moved since the last poll. Renews the + /// deadline; the first call for a flight only records its position. /// [`Self::check_hangs`] calls it while no firmware recovery notification is pending. pub(crate) fn progress(&mut self) { - let Some(f) = self.engine.oldest() else { + if self.engine.flights.is_empty() { return; - }; + } + const CP: usize = super::hw::sizes::COMPUTE_PIPES; let (g, r, e) = (&self.graph.compute, &self.graph.render, &self.engine); + let mut fc: [Option<&Flight>; CP] = [None; CP]; + let mut fr = None; + for f in e.flights.iter() { + if f.computes != 0 { + let p = (f.compute_pipe as usize).min(CP - 1); + if fc[p].is_none() { + fc[p] = Some(f); + } + } + if fr.is_none() && f.renders != 0 { + fr = Some(f); + } + } // None denotes an inactive/reached stage. A real unreached stamp may be zero // immediately after native wrap and must remain distinguishable from completion. let pending = |observed, own, tail| (!stamp_reached(observed, own, tail)).then_some(observed); - let (mut c, mut ta, mut fs) = (None, None, None); - if f.computes != 0 { - c = pending(g.fw_stamp.r32(0).unwrap_or(0), f.target, e.target); + let mut next_progress = [None; CP + 2]; + let mut published = [0u64; CP + 1]; + for p in 0..CP { + if let Some(f) = fc[p] { + next_progress[p] = pending( + g[p].fw_stamp.r32(0).unwrap_or(0), + f.target, + e.target[p], + ); + published[p] = f.published_ns; + } } - if f.renders != 0 { - ta = pending(r.fw_stamp[0].r32(0).unwrap_or(0), f.ta_target, e.ta_target); - fs = pending(r.fw_stamp[1].r32(0).unwrap_or(0), f.fs_target, e.fs_target); + if let Some(fr) = fr { + next_progress[CP] = pending( + r.fw_stamp[0].r32(0).unwrap_or(0), + fr.ta_target, + e.ta_target, + ); + next_progress[CP + 1] = + pending(r.fw_stamp[1].r32(0).unwrap_or(0), fr.fs_target, e.fs_target); + published[CP] = fr.published_ns; } - let moved = e.progress_flight == f.published_ns && [c, ta, fs] != e.progress; - let published = f.published_ns; - if moved { - self.renew_deadlines(); + let mut compute_moved = [false; CP]; + for p in 0..CP { + compute_moved[p] = fc[p].is_some() + && e.progress_flight[p] == published[p] + && next_progress[p] != e.progress[p]; + } + let render_moved = fr.is_some() + && e.progress_flight[CP] == published[CP] + && [next_progress[CP], next_progress[CP + 1]] != [e.progress[CP], e.progress[CP + 1]]; + for (p, moved) in compute_moved.into_iter().enumerate() { + if moved { + self.renew_compute_pipe_deadline(p); + } + } + if render_moved { + self.renew_render_deadline(); } self.engine.progress_flight = published; - self.engine.progress = [c, ta, fs]; + self.engine.progress = next_progress; } /// The device mutex still excludes slot reuse after owner-ledger retirement. Read the @@ -654,47 +1883,74 @@ impl Firmware { match command { super::command::Command::Compute(command) => { let index = *slots.get(compute).ok_or(EINVAL)? as usize; - let unit = flight - .job - .resources - .compute()? - .compute - .get(index) - .ok_or(EINVAL)?; - let ticks = [unit.its.r64(0)?, unit.its.r64(8)?, 0, 0]; - command - .timestamp_outputs - .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); + if !command.timestamp_outputs.is_empty() { + let unit = flight.job.resources.compute_unit(index)?; + let (start, end) = self.compute_ticks(unit)?; + let ticks = [start, end, 0, 0]; + command + .timestamp_outputs + .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); + } compute += 1; } super::command::Command::Render(command) => { let index = *passes.get(render).ok_or(EINVAL)? as usize; - let pass = flight - .job - .resources - .render()? - .passes - .get(index) - .ok_or(EINVAL)?; - let ticks = [ - pass.scene.r64(0x600)?, - pass.scene.r64(0x608)?, - pass.scene.r64(0x620)?, - pass.scene.r64(0x628)?, - ]; - command - .timestamp_outputs - .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); + if !command.timestamp_outputs.is_empty() { + let pass = flight.job.resources.render_pass(index)?; + let ticks = [ + pass.scene.r64(0x600)?, + pass.scene.r64(0x608)?, + pass.scene.r64(0x620)?, + pass.scene.r64(0x628)?, + ]; + command + .timestamp_outputs + .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); + } render += 1; } } } + for member in flight.group.iter() { + for command in member.commands.iter() { + match command { + super::command::Command::Compute(command) => { + let index = *slots.get(compute).ok_or(EINVAL)? as usize; + if !command.timestamp_outputs.is_empty() { + let unit = flight.job.resources.compute_unit(index)?; + let (start, end) = self.compute_ticks(unit)?; + let ticks = [start, end, 0, 0]; + command + .timestamp_outputs + .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); + } + compute += 1; + } + super::command::Command::Render(command) => { + let index = *passes.get(render).ok_or(EINVAL)? as usize; + if !command.timestamp_outputs.is_empty() { + let pass = flight.job.resources.render_pass(index)?; + let ticks = [ + pass.scene.r64(0x600)?, + pass.scene.r64(0x608)?, + pass.scene.r64(0x620)?, + pass.scene.r64(0x628)?, + ]; + command + .timestamp_outputs + .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); + } + render += 1; + } + } + } + } Ok(()) } /// A retired prefix: publication to retirement (including any wait behind its /// predecessor), event times, internal stage times of its members. - fn stat_retire(&mut self, f: &Flight) { + fn stat_retire(&mut self, f: &Flight, ticks: [u64; 4]) { let now = now_ns(); let d = now.wrapping_sub(f.published_ns); let kind = if f.computes != 0 && f.renders != 0 { @@ -706,69 +1962,113 @@ impl Firmware { }; let (mut lo, mut hi) = (u64::MAX, 0u64); let (mut first, mut last) = (u64::MAX, 0u64); + let mut cdm_flight_ticks = 0u64; + let mut cdm_counted = 0u32; + let work_ticks = self.init.abi.compute().work_ticks; let s = &mut self.engine.stats; - // Add one stage interval read from internal timestamp cells (start, end). - let mut stage = |o: &super::object::FwObject, - off: usize, - sum: &mut u64, - engine: crate::usage::Engine| { - let (Ok(start_lo), Ok(start_hi), Ok(end_lo), Ok(end_hi)) = - (o.r32(off), o.r32(off + 4), o.r32(off + 8), o.r32(off + 12)) - else { - return; - }; - let start = u64::from(start_hi) << 32 | u64::from(start_lo); - let end = u64::from(end_hi) << 32 | u64::from(end_lo); - if start == 0 || end < start { - return; - } - f.job - .queue - .usage - .add(engine, start, end, super::hw::COMMAND_TIMESTAMP_HZ as u32); - *sum = sum.saturating_add(end - start); - lo = lo.min(start); - hi = hi.max(end); - }; - for k in 0..f.renders as usize { - let Some(arena) = f.job.resources.render.as_ref() else { - return; + let mut add_interval = + |start: u64, end: u64, sum: &mut u64, engine: crate::usage::Engine| { + if start == 0 || end < start { + return; + } + f.job + .queue + .usage + .add_union(engine, start, end, super::hw::COMMAND_TIMESTAMP_HZ as u32); + *sum = sum.saturating_add(end - start); + lo = lo.min(start); + hi = hi.max(end); }; - let p = &arena.passes[f.claims.pass[k] as usize]; - stage( - &p.scene, - 0x600, + if f.renders == 1 && f.computes == 0 && ticks[0] != 0 { + add_interval( + ticks[0], + ticks[1], &mut s.ta_ticks, crate::usage::Engine::Vertex, ); - stage( - &p.scene, - 0x620, + add_interval( + ticks[2], + ticks[3], &mut s.fs_ticks, crate::usage::Engine::Fragment, ); - } - for k in 0..(f.computes as usize).min(f.claims.slot_count as usize) { - let Some(arena) = f.job.resources.compute.as_ref() else { - return; + } else if f.computes == 1 && f.renders == 0 && ticks[0] != 0 { + add_interval( + ticks[0], + ticks[1], + &mut s.cdm_ticks, + crate::usage::Engine::Compute, + ); + if ticks[1] >= ticks[0] { + cdm_flight_ticks = ticks[1] - ticks[0]; + cdm_counted = 1; + } + } else { + // Multi-command prefix fallback: read each member's internal timestamp cells. + let mut stage = |o: &super::object::FwObject, + off: usize, + sum: &mut u64, + engine: crate::usage::Engine| { + let (Ok(start_lo), Ok(start_hi), Ok(end_lo), Ok(end_hi)) = + (o.r32(off), o.r32(off + 4), o.r32(off + 8), o.r32(off + 12)) + else { + return; + }; + let start = u64::from(start_hi) << 32 | u64::from(start_lo); + let end = u64::from(end_hi) << 32 | u64::from(end_lo); + add_interval(start, end, sum, engine); }; - let c = &arena.compute[f.claims.slot[k] as usize]; - stage(&c.its, 0, &mut s.cdm_ticks, crate::usage::Engine::Compute); + for k in 0..f.renders as usize { + let Ok(p) = f.job.resources.render_pass(f.claims.pass[k] as usize) else { + return; + }; + stage( + &p.scene, + 0x600, + &mut s.ta_ticks, + crate::usage::Engine::Vertex, + ); + stage( + &p.scene, + 0x620, + &mut s.fs_ticks, + crate::usage::Engine::Fragment, + ); + } + for k in 0..(f.computes as usize).min(f.claims.slot_count as usize) { + let Ok(c) = f.job.resources.compute_unit(f.claims.slot[k] as usize) else { + return; + }; + if let Ok((start, end)) = Self::compute_ticks_with(work_ticks, c) { + add_interval(start, end, &mut s.cdm_ticks, crate::usage::Engine::Compute); + if start != 0 && end >= start { + cdm_flight_ticks = cdm_flight_ticks.saturating_add(end - start); + cdm_counted += 1; + } + } + } + } + if cdm_counted != 0 { + let per_cmd_ticks = cdm_flight_ticks / u64::from(cdm_counted); + let per_cmd_us = (per_cmd_ticks.saturating_mul(1_000_000) + / super::hw::COMMAND_TIMESTAMP_HZ) + .clamp(1, 100_000) as u32; + f.job.queue.note_compute_us(per_cmd_us); } if hi > lo { s.span_ticks = s.span_ticks.saturating_add(hi - lo); } - for b in 0..3 { - let t = self.events.event_ns[b]; - let skip = if b == 2 { - f.computes == 0 - } else { - f.renders == 0 - }; - if skip { - continue; + if f.renders != 0 { + for b in 0..2 { + let t = self.events.event_ns[b]; + first = first.min(t); + last = last.max(t); } + } + if f.computes != 0 { + let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + let t = self.events.event_ns[2 + p]; first = first.min(t); last = last.max(t); } @@ -790,27 +2090,43 @@ impl Firmware { /// readiness and Flags words). #[allow(dead_code)] pub(crate) fn report(&self, what: &str) { - let (g, r, e) = (&self.graph.compute, &self.graph.render, &self.engine); + let (r, e) = (&self.graph.render, &self.engine); let ch = &self.channels; let rd = |o: &super::object::FwObject, off| o.r32(off).unwrap_or(0xdeadbeef); - let state = self.session.regs.engine_state().unwrap_or_default(); + let state = self + .session + .engine_state() + .ok() + .flatten() + .unwrap_or_default(); let f = e.oldest(); + let pipe = f + .map_or(0, |f| { + if f.computes != 0 { + f.compute_pipe as usize + } else { + 0 + } + }) + .min(super::hw::sizes::COMPUTE_PIPES - 1); + let g = &self.graph.compute[pipe]; let ms = f.map_or(0, |f| now_ns().wrapping_sub(f.published_ns) / 1_000_000); dev_info!( self.graph.dev.as_ref(), - "G16: {}: ctx={} prefixes={} n={} target={:#x} user={:#x} fw={:#x} done={} read={} write={} head={} ch={}/{} events={}/{} errors={} busy={} fault={:#x} {}ms\n", + "G16: {}: ctx={} prefixes={} n={} pipe={} target={:#x} user={:#x} fw={:#x} done={} read={} write={} head={} ch={}/{} events={}/{} errors={} busy={} fault={:#x} {}ms\n", what, f.map_or(0, |f| f.job.vm.slot), e.flights.len(), e.ordinal, - e.target, + pipe, + e.target[pipe], rd(&g.user_stamp, 0), rd(&g.fw_stamp, 0), rd(&g.qstate, qstate::DONE), rd(&g.qstate, qstate::READ), rd(&g.qstate, qstate::WRITE), - e.head, + e.head[pipe], ch.read(Channel::Compute).unwrap_or(0xdeadbeef), ch.write_cell(Channel::Compute).unwrap_or(0xdeadbeef), self.events.compute_events, @@ -960,7 +2276,9 @@ impl Firmware { writeln!( f, "pass_scrub: passes {} tpc_clear_bytes {} tilemap_clear_bytes {}", - slots.pass_scrubs, slots.tpc_clear_bytes, slots.tilemap_clear_bytes + self.slots.pass_scrubs_total(), + slots.tpc_clear_bytes, + self.slots.tilemap_clear_bytes_total() )?; writeln!(f, "type0: fs2c {} c2ta {}", s.fs2c0, s.c2ta0)?; write!(f, "horizon:")?; @@ -990,6 +2308,24 @@ impl Firmware { s.span_ticks / 24 )?; // The phase timers of debug_flags bit 49, and the scrub flush waits. + { + let s = &self.engine.stats; + writeln!( + f, + "pipeline: behind {} max_flights {} compute_published {} hold {}/{}/{}", + s.behind, + s.max_flights, + self.slots.compute_published(), + s.hold[0], + s.hold[1], + s.hold[2] + )?; + write!(f, "hold_causes:")?; + for (name, n) in super::engine::HoldCause::NAMES.iter().zip(s.hold_causes) { + write!(f, " {} {}", name, n)?; + } + writeln!(f)?; + } let p = &self.engine.prof; writeln!( f, diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index d4a85cc6f3d361..0af1660bf25791 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -2,16 +2,21 @@ //! Private render UMA/heap backing and device-wide PB-slot leases. //! -//! Each VM keeps two persistent UMA/heap units. Each render command installs a fresh -//! PB manager with full InitBM and never reinitializes exposed cursors. The previous -//! PB-slot lease survives until the replacement's complete normal retirement. +//! Each VM keeps two persistent UMA units and one PB heap they share: a render is published +//! only while no other command is in flight and retires with its blocks returned, so the two +//! pass slots' PB managers never hand out heap blocks at the same time. A render reuses its +//! pass slot's lease, its VM's last successfully retired epoch of the slot, while the slot is +//! still bound to it, unchanged (the host writes nothing to it, no InitBM). Otherwise it +//! installs a fresh PB manager with full InitBM and never reinitializes exposed cursors. The +//! previous PB-slot lease survives until the replacement's complete normal retirement. #[path = "pools/lifetime.rs"] pub(crate) mod lifetime; use super::fw::buffer::{self, uma_manager}; -use super::hw::{client, engine, pte}; -use super::object::{Class, FwObject, Objects, Placement, Request}; +use super::hw::{client, engine, pte, sizes}; +use super::object::{Class, Factory, FwLease, FwObject, Objects, Request}; +use super::slots::Placement; use super::Firmware; use crate::driver::AsahiDrmDevice; use core::{ @@ -31,7 +36,6 @@ pub(crate) struct AllocatorRefs { pub(crate) uma_aux: [u64; 2], pub(crate) uma_gpu: u64, pub(crate) pb_mgr: u64, - pub(crate) scene_list: u64, pub(crate) mgr_misc: u64, pub(crate) init_blocks: u32, pub(crate) parameter_id: u32, @@ -43,7 +47,7 @@ pub(crate) struct AllocatorRefs { pub(crate) init_buffer: bool, } -struct Allocator { +pub(crate) struct Allocator { descriptor: Arc, auxiliary: Arc, #[allow(dead_code)] @@ -54,7 +58,9 @@ struct Allocator { list: Arc, submitted: Arc, heap: Arc, - scene_list: Arc, + /// VM-free firmware lease retaining `descriptor` and `submitted` across closed-VM reclaim + /// until a later render overwrites this hardware UMA slot in firmware RAM. + uma_lease: Arc, published: AtomicBool, id: u32, } @@ -67,10 +73,21 @@ pub(crate) struct PbStats { #[allow(dead_code)] pub(crate) refused: u64, pub(crate) bad: u64, + /// Pass slot bindings that reused a retired epoch / started a fresh one (a deferred + /// render counts again when it is retried). + pub(crate) reused: u64, + pub(crate) fresh: u64, + /// Retirements that replaced an open VM's owner epoch still kept as that VM's last epoch. + pub(crate) kept: u64, } pub(crate) struct PoolSet { units: KVec, + heap: Arc, + /// Blocks of the shared heap (the PB managers' lists cover the whole 256 MiB window). + heap_blocks: u32, + /// Freelist entries of every allocator's UMA pool. + seeds: u32, } fn alloc( @@ -83,7 +100,7 @@ fn alloc( o.alloc(Request { size, class, - placement: Placement::Anywhere, + placement: super::object::Placement::Anywhere, offset: 0, client, lower: None, @@ -122,53 +139,91 @@ fn write_records( Ok(()) } impl Allocator { - fn new(o: &mut Objects, k: u64) -> Result { - let base = client::render_base(k); + /// Render allocator at per-VM VA index `k` and matching device-wide hardware slot `k`. + pub(crate) fn new( + o: &mut Objects, + fw_factory: &Factory, + k: u64, + heap: &Arc, + placement: Placement, + ) -> Result { + Self::new_at(o, fw_factory, k, k as u32, heap, placement) + } + /// Render allocator mapped at per-VM local VA index `local_idx` (`0..MAX_VM_PB_SLOTS`) + /// and bound to device-wide hardware slot `hw_slot` (`parameter_id`, UMA slot + /// `RENDER_UMA_SLOT + hw_slot`). + pub(crate) fn new_at( + o: &mut Objects, + fw_factory: &Factory, + local_idx: u64, + hw_slot: u32, + heap: &Arc, + placement: Placement, + ) -> Result { + placement.check()?; + if local_idx >= sizes::MAX_VM_PB_SLOTS as u64 || (hw_slot as usize) >= sizes::PB_SLOTS { + return Err(EINVAL); + } + let (pool_va, state_va, freelist_va) = match placement { + Placement::Base => ( + client::render_pool(local_idx), + client::render_state(local_idx), + client::render_state(local_idx), + ), + Placement::Scs { .. } => { + if local_idx >= sizes::BASE_PB_SLOTS as u64 { + return Err(EINVAL); + } + let pool = client::scs_render_pool(local_idx); + ( + pool, + client::scs_render_records(local_idx), + pool + placement.pool_bytes() as u64, + ) + } + }; let nc = |va| Some((va, pte::LEAF_NC)); // Native UMA software metadata is ASC-owned and never needs a client GPU alias. - // In particular its firmware pointers, +0x54 completion and +0x5c exclusion flag - // must not share a writable GPU page with the engine auxiliary records. - let descriptor = alloc(o, uma_manager::SIZE, Class::Fw, None, true)?; + // Keep descriptor + submitted in a VM-free FwLease so firmware's global UMA table + // stays mapped across closed-VM reclaim without pinning the VM's ASID or pools. + let mut fw = fw_factory.fw_objects(); + let descriptor = alloc(&mut fw, uma_manager::SIZE, Class::Fw, None, true)?; + let submitted = alloc(&mut fw, 0x40, Class::Fw, None, true)?; + let uma_lease = FwLease::new(fw)?; let auxiliary = alloc( o, 0x4000, Class::Shared, - nc(client::render_descriptor(k)), + nc(state_va + client::RENDER_DESCRIPTOR_OFF), false, )?; - let pool = alloc( + let pool = alloc(o, placement.pool_bytes(), Class::Shared, nc(pool_va), false)?; + let state = alloc( o, - 0x2000000, + placement.freelist_bytes(), Class::Shared, - nc(client::render_pool(k)), - false, - )?; - let state = alloc(o, 0x20000, Class::Shared, nc(client::render_state(k)), true)?; - let list = alloc(o, 0x4000, Class::Shared, nc(client::render_list(k)), true)?; - let submitted = alloc(o, 0x40, Class::Fw, None, true)?; - let heap = alloc( - o, - client::PB_HEAP_SIZE as usize, - Class::Shared, - nc(client::pb_heap(k)), - false, + nc(freelist_va), + true, )?; - let scene_list = alloc( + let list = alloc( o, - buffer::SCENE_LIST_SIZE, + 0x4000, Class::Shared, - nc(base + 0x2070000), + nc(state_va + client::RENDER_LIST_OFF), true, )?; - super::slots::init_uma_pool(&state, &list, gva(&pool)?)?; + let heap = heap.clone(); + super::slots::init_uma_pool(&state, &list, gva(&pool)?, placement.seeds())?; descriptor.write( 0, &buffer::uma_manager_image( descriptor.va, - engine::RENDER_UMA_SLOT, + engine::RENDER_UMA_SLOT + hw_slot, gva(&state)?, gva(&list)?, submitted.va, + placement.seeds(), + super::rt::freelist_records(placement.seeds()), ), )?; Ok(Self { @@ -179,12 +234,20 @@ impl Allocator { list, submitted, heap, - scene_list, + uma_lease, published: AtomicBool::new(false), - id: k as u32, + id: hw_slot, }) } - fn refs(&self) -> Result { + /// Firmware-only lease retaining this allocator's UMA descriptor and submitted counter. + pub(crate) fn uma_lease(&self) -> Arc { + self.uma_lease.clone() + } + /// Device-wide hardware PB/UMA slot (`parameter_id`) owned by this allocator unit. + pub(crate) fn id(&self) -> u32 { + self.id + } + pub(crate) fn refs(&self) -> Result { let prior = read64(&self.submitted, 0)?; if prior & 1 != 0 { return Err(EINVAL); @@ -195,7 +258,6 @@ impl Allocator { uma_aux: [self.auxiliary.va + 0x100, self.auxiliary.va + 0x200], uma_gpu: gva(&self.auxiliary)?, pb_mgr: 0, - scene_list: gva(&self.scene_list)?, mgr_misc: 0, init_blocks: buffer::MAX_BLOCKS, parameter_id: self.id, @@ -205,86 +267,914 @@ impl Allocator { init_buffer: true, }) } - fn retired(&self) -> Result { + /// Prepares this UMA/PB allocator slot. When `pipelined` is true, earlier same-VM renders + /// are still in flight on the same active descriptor and PB manager, so the submitted + /// counter advances cumulatively while descriptor identity is still verified. + pub(crate) fn prepare_in_flight(&self, _draw: u64, pipelined: bool) -> Result { + if !pipelined && self.published.load(Ordering::Acquire) && !self.retired()? { + return Err(EBUSY); + } + // Descriptor pointer/counter and slot must still identify this exact retained unit. + if read64(&self.descriptor, 0)? != self.descriptor.va + || self.descriptor.r32(8)? != engine::RENDER_UMA_SLOT + self.id + || read64(&self.descriptor, 0x4c)? != self.submitted.va + { + return Err(EINVAL); + } + self.refs() + } + pub(crate) fn publish_batch(&self, submitted: u64, renders: u32) -> Result { + if renders == 0 { + return Err(EINVAL); + } + let delta = u64::from(renders).checked_mul(2).ok_or(EOVERFLOW)?; + if submitted + != read64(&self.submitted, 0)? + .checked_add(delta) + .ok_or(EOVERFLOW)? + { + return Err(EINVAL); + } + self.submitted.w64(0, submitted)?; + self.published.store(true, Ordering::Release); + Ok(()) + } + pub(crate) fn retired(&self) -> Result { let submitted = read64(&self.submitted, 0)?; let completed = read64(&self.descriptor, uma_manager::COMPLETED)?; Ok(submitted != 0 && submitted == completed) } + pub(crate) fn retired_at(&self, target: u64) -> Result { + let completed = read64(&self.descriptor, uma_manager::COMPLETED)?; + Ok(target != 0 && completed >= target) + } + pub(crate) fn heap_gva(&self) -> Result { + gva(&self.heap) + } } +/// Maps one contiguous PB heap extension chunk (`start_block..start_block + blocks`) inside the +/// VM's 256 MiB [`client::PB_HEAP_SIZE`] window so demand-grown heaps extend seamlessly after the +/// base [`PoolSet`] allocation without unmapping any in-flight base range. +#[allow(dead_code)] +pub(crate) fn alloc_pb_heap_chunk( + o: &mut Objects, + start_block: u32, + blocks: u32, +) -> Result> { + if blocks == 0 + || start_block + .checked_add(blocks) + .is_none_or(|end| end > buffer::MAX_BLOCKS) + { + return Err(EINVAL); + } + let gva = client::pb_heap(0) + u64::from(start_block) * buffer::BLOCK_BYTES; + alloc( + o, + blocks as usize * buffer::BLOCK_BYTES as usize, + Class::Shared, + Some((gva, pte::LEAF_NC)), + false, + ) +} + impl PoolSet { - pub(crate) fn new(o: &mut Objects) -> Result { - let mut units = KVec::with_capacity(2, GFP_KERNEL)?; - for k in 0..2 { - units.push(Allocator::new(o, k)?, GFP_KERNEL)?; + pub(crate) fn new(o: &mut Objects, fw_factory: &Factory) -> Result { + Self::new_with_slots(o, fw_factory, [0, 1]) + } + /// Base render allocator units mapped at per-VM local VA indices `0..BASE_PB_SLOTS` and + /// bound to device-wide physical PB/UMA slots `slots`. + pub(crate) fn new_with_slots( + o: &mut Objects, + fw_factory: &Factory, + slots: [usize; sizes::BASE_PB_SLOTS], + ) -> Result { + // The firmware copes with a full PB without the host (its overflow counters move and + // the scene completes), so the heap is sized well below the 256 MiB window. + let heap_blocks = super::params::pb_heap_blocks().min(buffer::MAX_BLOCKS); + let heap = alloc( + o, + heap_blocks as usize * buffer::BLOCK_BYTES as usize, + Class::Shared, + Some((client::pb_heap(0), pte::LEAF_NC)), + false, + )?; + let mut units = KVec::with_capacity(sizes::BASE_PB_SLOTS, GFP_KERNEL)?; + for (local, &hw_slot) in slots.iter().enumerate() { + units.push( + Allocator::new_at( + o, + fw_factory, + local as u64, + hw_slot as u32, + &heap, + Placement::Base, + )?, + GFP_KERNEL, + )?; } - Ok(Self { units }) + Ok(Self { + units, + heap, + heap_blocks, + seeds: Placement::Base.seeds(), + }) + } + /// The SCS-capable allocators of this set's VM (ray-query scratch): one per base PB slot, + /// sharing this set's PB heap and hardware slot IDs, each with a pool of `seeds` entries + /// ([`super::rt::pool_seeds`]). PB epoch reuse keeps base and SCS bindings strictly disjoint. + pub(crate) fn scs(&self, o: &mut Objects, fw_factory: &Factory, seeds: u32) -> Result { + let heap = self.heap.clone(); + let placement = Placement::Scs { seeds }; + let mut units = KVec::with_capacity(sizes::BASE_PB_SLOTS, GFP_KERNEL)?; + for (local, unit) in self.units.iter().enumerate() { + units.push( + Allocator::new_at(o, fw_factory, local as u64, unit.id(), &heap, placement)?, + GFP_KERNEL, + )?; + } + Ok(Self { + units, + heap, + heap_blocks: self.heap_blocks, + seeds, + }) + } + /// Freelist entries of the set's UMA pools. + pub(crate) fn seeds(&self) -> u32 { + self.seeds + } + #[allow(dead_code)] + pub(crate) fn unit(&self, k: usize) -> Option<&Allocator> { + self.units.get(k) + } + #[allow(dead_code)] + pub(crate) fn heap(&self) -> &Arc { + &self.heap } #[allow(dead_code)] pub(crate) fn allocator_refs_for(&self, k: usize) -> Result { self.units.get(k).ok_or(EINVAL)?.refs() } - pub(crate) fn prepare(&self, k: usize, _draw: u64) -> Result { - let u = self.units.get(k).ok_or(EINVAL)?; - if u.published.load(Ordering::Acquire) && !u.retired()? { - return Err(EBUSY); - } - // Descriptor pointer/counter and slot must still identify this exact retained unit. - if read64(&u.descriptor, 0)? != u.descriptor.va - || u.descriptor.r32(8)? != engine::RENDER_UMA_SLOT - || read64(&u.descriptor, 0x4c)? != u.submitted.va - { - return Err(EINVAL); - } - u.refs() + #[allow(dead_code)] + pub(crate) fn prepare(&self, k: usize, draw: u64) -> Result { + self.prepare_in_flight(k, draw, false) } - pub(crate) fn publish(&self, k: usize, submitted: u64) -> Result { - let u = self.units.get(k).ok_or(EINVAL)?; - if submitted != read64(&u.submitted, 0)?.checked_add(2).ok_or(EOVERFLOW)? { - return Err(EINVAL); - } - u.submitted.w64(0, submitted)?; - u.published.store(true, Ordering::Release); - Ok(()) + /// Prepares base UMA/PB allocator slot `k` (`0..BASE_PB_SLOTS`). + #[allow(dead_code)] + pub(crate) fn prepare_in_flight( + &self, + k: usize, + draw: u64, + pipelined: bool, + ) -> Result { + self.units + .get(k) + .ok_or(EINVAL)? + .prepare_in_flight(draw, pipelined) + } + #[allow(dead_code)] + pub(crate) fn publish_batch(&self, k: usize, submitted: u64, renders: u32) -> Result { + self.units + .get(k) + .ok_or(EINVAL)? + .publish_batch(submitted, renders) } + #[allow(dead_code)] pub(crate) fn retired(&self, k: usize) -> Result { self.units.get(k).ok_or(EINVAL)?.retired() } + #[allow(dead_code)] + pub(crate) fn retired_at(&self, k: usize, target: u64) -> Result { + self.units.get(k).ok_or(EINVAL)?.retired_at(target) + } + #[allow(dead_code)] pub(crate) fn heap_gva(&self, k: usize) -> Result { - gva(&self.units.get(k).ok_or(EINVAL)?.heap) + self.units.get(k).ok_or(EINVAL)?.heap_gva() + } + pub(crate) fn heap_blocks(&self) -> u32 { + self.heap_blocks } } -/// Device-wide physical PB-slot leases. Replacement requires a complete normal receipt. +/// Device-wide physical PB-slot leases (`parameter_id` `0..PB_SLOTS`, hardware UMA slot 33). +/// +/// Decoupled from per-pass storage (`PassSlot 0..RENDER_SLOTS`): same-VM renders stay on one +/// active `pb_slot` and reuse its exposed `PbEpoch` (including pipelined renders in flight), +/// while cross-VM switches or post-recovery/error renders drain and switch to a displaced or +/// fresh alternate `pb_slot` so the previous VM's UMA/PB storage remains mapped through +/// displacement. Under normal non-fault operation the working set stays on the two base slots; +/// recovery slots `BASE_PB_SLOTS..PB_SLOTS` are claimed only after a render hang permanently +/// quarantines a slot. pub(crate) struct Pools { pub(crate) dev: ARef, pub(crate) stats: PbStats, - owners: [Option>; 2], + /// The epoch whose manager `pb_mgr_table[k]` names, kept until a newer epoch retires on + /// slot `k`, also after its VM closed: it maps the manager's page and block lists and keeps + /// the VM's TTBAT slot bound, the context through which those lists are written. + owners: [Option>; sizes::PB_SLOTS], + /// VM-free firmware leases keeping each `parameter_id`'s `pb_manager` + `counter` page mapped + /// for firmware's global `pb_mgr_table[parameter_id]` across closed-VM reclaim until a newer + /// `InitBM` retires on that exact slot. + retained_pb: [Option>; sizes::PB_SLOTS], + #[allow(dead_code)] + owner_vms: [Option>; sizes::PB_SLOTS], + #[allow(dead_code)] + owner_arenas: [Option; sizes::PB_SLOTS], + /// VM-free firmware leases keeping each render UMA slot's `descriptor` + `submitted` page + /// mapped for firmware's global `uma_mgr_table[RENDER_UMA_SLOT + k]` across closed-VM reclaim + /// until a newer render retires on that exact slot. + retained_uma: [Option>; sizes::PB_SLOTS], + pending_vms: [Option>; sizes::PB_SLOTS], + pending_arenas: [Option; sizes::PB_SLOTS], + pending_uma: [Option>; sizes::PB_SLOTS], + /// Per allocator slot, a binding count, bumped by each fresh epoch (its InitBM rebinds the + /// slot) and by a firmware recovery or sleep restart. It identifies a binding without + /// holding the epoch. + binds: [u64; sizes::PB_SLOTS], + /// Per allocator slot: `owners[k]` may serve the next render of its VM without InitBM. + keep: [bool; sizes::PB_SLOTS], + /// Most recently published allocator slot (`0..PB_SLOTS`). + active: Option, + /// Most recently cleanly retired allocator slot (proves every other slot is displaced). + last_clean_retired: Option, + /// Live in-flight render count per allocator slot. + inflight: [u32; sizes::PB_SLOTS], + /// Permanently quarantined allocator slots after an aborted receipt. + quarantined: [bool; sizes::PB_SLOTS], + /// Fresh PB epoch retained when an aborted render had not yet replaced `owners[k]`. + quarantined_epochs: [Option>; sizes::PB_SLOTS], + /// Per TTBAT slot, the epoch of the last render its VM retired, kept until a newer render + /// of the same VM retires. The parameter manager writes back to the page list of the + /// manager a context used last, through that context, when the context's next InitBM + /// runs, also after another VM's epoch replaced `owners[k]` on the old slot. An entry + /// holds its VM and so the TTBAT slot that indexes it. + vm_last: [Option>; VM_LAST_ENTRIES], + /// A closed VM's [`Self::vm_last`] entry was recorded since the last reclaim pass. + closed_vm_last: bool, } +/// Entries of [`Pools::vm_last`]: one per TTBAT user slot (ASIDs `1..=MAX_VMS`). +const VM_LAST_ENTRIES: usize = sizes::MAX_VMS as usize + 1; impl Pools { + #[allow(dead_code)] pub(crate) fn new(dev: &AsahiDrmDevice) -> Self { Self { dev: dev.as_ref().as_ref().into(), stats: PbStats::default(), - owners: [None, None], + owners: [const { None }; sizes::PB_SLOTS], + retained_pb: [const { None }; sizes::PB_SLOTS], + owner_vms: [const { None }; sizes::PB_SLOTS], + owner_arenas: [const { None }; sizes::PB_SLOTS], + retained_uma: [const { None }; sizes::PB_SLOTS], + pending_vms: [const { None }; sizes::PB_SLOTS], + pending_arenas: [const { None }; sizes::PB_SLOTS], + pending_uma: [const { None }; sizes::PB_SLOTS], + binds: [0; sizes::PB_SLOTS], + keep: [false; sizes::PB_SLOTS], + active: None, + last_clean_retired: None, + inflight: [0; sizes::PB_SLOTS], + quarantined: [false; sizes::PB_SLOTS], + quarantined_epochs: [const { None }; sizes::PB_SLOTS], + vm_last: [const { None }; VM_LAST_ENTRIES], + closed_vm_last: false, + } + } + /// Allocates [`Pools`] directly on the heap so probe/backend bring-up does not stage the + /// per-slot lease arrays on the kernel stack. + #[allow(dead_code)] + #[inline(never)] + pub(crate) fn new_boxed(dev: &AsahiDrmDevice) -> Result> { + Ok(KBox::init( + init!(Self { + dev: dev.as_ref().as_ref().into(), + stats: PbStats::default(), + owners: [const { None }; sizes::PB_SLOTS], + retained_pb: [const { None }; sizes::PB_SLOTS], + owner_vms: [const { None }; sizes::PB_SLOTS], + owner_arenas: [const { None }; sizes::PB_SLOTS], + retained_uma: [const { None }; sizes::PB_SLOTS], + pending_vms: [const { None }; sizes::PB_SLOTS], + pending_arenas: [const { None }; sizes::PB_SLOTS], + pending_uma: [const { None }; sizes::PB_SLOTS], + binds: [0; sizes::PB_SLOTS], + keep: [false; sizes::PB_SLOTS], + active: None, + last_clean_retired: None, + inflight: [0; sizes::PB_SLOTS], + quarantined: [false; sizes::PB_SLOTS], + quarantined_epochs: [const { None }; sizes::PB_SLOTS], + vm_last: [const { None }; VM_LAST_ENTRIES], + closed_vm_last: false, + }), + GFP_KERNEL, + )?) + } + /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). + pub(crate) fn quarantined_mask(&self) -> u32 { + let mut mask = 0u32; + for k in 0..sizes::PB_SLOTS { + if self.quarantined[k] { + mask |= 1u32 << k; + } + } + mask + } + /// Number of contiguous PB/UMA allocator slots (`0..n`) each rendering VM should prepare + /// so at least [`sizes::BASE_PB_SLOTS`] healthy slots remain available across quarantines. + #[allow(dead_code)] + pub(crate) fn needed_slots(&self) -> usize { + let quarantined = self.quarantined.iter().filter(|&&q| q).count(); + sizes::BASE_PB_SLOTS + .saturating_add(quarantined) + .min(sizes::PB_SLOTS) + } + /// Number of in-flight render prefixes currently active on allocator slot `k`. + #[allow(dead_code)] + pub(crate) fn slot_inflight(&self, k: usize) -> u32 { + self.inflight.get(k).copied().unwrap_or(0) + } + /// Whether slot `k` is healthy, idle, not active, and either fresh or displaced by a clean + /// retirement of some other slot. + fn slot_displaced(&self, k: usize) -> bool { + !self.quarantined[k] + && self.inflight[k] == 0 + && self.active != Some(k) + && (self.owners[k].is_none() || self.last_clean_retired.is_some_and(|r| r != k)) + } + /// Whether at least one displaced physical PB allocator slot exists in `0..limit`. + fn has_displaced_slot_within(&self, limit: usize) -> bool { + let n = limit.min(sizes::PB_SLOTS); + (0..n).any(|k| self.slot_displaced(k)) + } + /// Whether at least one displaced physical PB allocator slot exists in `slot_mask`. + fn has_displaced_slot_in_mask(&self, slot_mask: u32) -> bool { + (0..sizes::PB_SLOTS).any(|k| (slot_mask & (1u32 << k)) != 0 && self.slot_displaced(k)) + } + /// Allocator slot `k`'s owner epoch, if its render retired normally while the slot was still + /// bound to it, it belongs to `vm` and was exposed (its InitBM ran). InitBM binds the + /// device-wide slot to one epoch and VM; a fresh epoch handed to the slot rebinds it, so + /// the owner is then stale and the render starts fresh. Adds no reference beyond the owner + /// lease itself. + pub(crate) fn reusable(&self, k: usize, vm: &Arc) -> Option> { + if *self.quarantined.get(k)? || !*self.keep.get(k)? { + return None; } + let owner = self.owners.get(k)?.as_ref()?; + (Arc::ptr_eq(&owner._vm, vm) && owner.exposed.load(Ordering::Acquire)) + .then(|| owner.clone()) } + /// Like [`Self::reusable`], but also requires the retired epoch's SCS mode to match + /// `want_scs` so a base render and an SCS render never share an active UMA descriptor slot. + pub(crate) fn reusable_mode( + &self, + k: usize, + vm: &Arc, + want_scs: bool, + ) -> Option> { + self.reusable(k, vm) + .filter(|owner| owner.scs() == want_scs) + } + /// Like [`Self::reusable_mode`], but forces a fresh `InitBM` epoch when the VM's PB heap grew + /// past the retired epoch's `heap_blocks` and a displaced slot in `slot_mask` is available + /// to rotate onto safely. + pub(crate) fn reusable_for_mask_mode( + &self, + k: usize, + vm: &Arc, + slot_mask: u32, + min_blocks: u32, + want_scs: bool, + ) -> Option> { + if k >= sizes::PB_SLOTS || (slot_mask & (1u32 << k)) == 0 { + return None; + } + let owner = self.reusable_mode(k, vm, want_scs)?; + if owner.heap_blocks() >= min_blocks || !self.has_displaced_slot_in_mask(slot_mask) { + Some(owner) + } else { + None + } + } + /// Like [`Self::reusable_mode`], but forces a fresh `InitBM` epoch when the VM's PB heap grew + /// past the retired epoch's `heap_blocks` and a displaced slot within `0..limit` is available + /// to rotate onto safely. + #[allow(dead_code)] + pub(crate) fn reusable_for_within_mode( + &self, + k: usize, + vm: &Arc, + limit: usize, + min_blocks: u32, + want_scs: bool, + ) -> Option> { + let owner = self.reusable_mode(k, vm, want_scs)?; + if owner.heap_blocks() >= min_blocks || !self.has_displaced_slot_within(limit) { + Some(owner) + } else { + None + } + } + /// Like [`Self::reusable`], but forces a fresh `InitBM` epoch when the VM's PB heap grew + /// past the retired epoch's `heap_blocks` and a displaced slot within `0..limit` is available + /// to rotate onto safely. + #[allow(dead_code)] + pub(crate) fn reusable_for_within( + &self, + k: usize, + vm: &Arc, + limit: usize, + min_blocks: u32, + ) -> Option> { + self.reusable_for_within_mode(k, vm, limit, min_blocks, false) + } + /// Selects a physical PB/UMA allocator slot in `slot_mask` for `vm` and `want_scs`, + /// preferring `home` when claiming an unused warm slot (`0..WARM_PB_SLOTS`) so up to + /// `WARM_PB_SLOTS` concurrent VMs bind disjoint warm slots regardless of arrival order. + pub(crate) fn pick_slot_in_mask_blocks_mode( + &self, + vm: &Arc, + behind: bool, + slot_mask: u32, + home: usize, + min_blocks: u32, + want_scs: bool, + ) -> Option { + let in_mask = |k: usize| k < sizes::PB_SLOTS && (slot_mask & (1u32 << k)) != 0; + if let Some(a) = self.active { + if in_mask(a) + && self + .reusable_for_mask_mode(a, vm, slot_mask, min_blocks, want_scs) + .is_some() + { + return Some(a); + } + } + if let Some(k) = (0..sizes::PB_SLOTS).find(|&k| { + in_mask(k) + && self + .reusable_for_mask_mode(k, vm, slot_mask, min_blocks, want_scs) + .is_some() + }) { + return Some(k); + } + if behind { + return None; + } + // Cold (drained): claim the VM's unused home slot first, then any unused warm slot, + // then a displaced warm slot (preferring home), and finally recovery spares. + if home < sizes::WARM_PB_SLOTS + && in_mask(home) + && self.slot_displaced(home) + && self.owners[home].is_none() + { + return Some(home); + } + if let Some(k) = (0..sizes::WARM_PB_SLOTS) + .find(|&k| in_mask(k) && self.slot_displaced(k) && self.owners[k].is_none()) + { + return Some(k); + } + if home < sizes::WARM_PB_SLOTS && in_mask(home) && self.slot_displaced(home) { + return Some(home); + } + if let Some(k) = + (0..sizes::WARM_PB_SLOTS).find(|&k| in_mask(k) && self.slot_displaced(k)) + { + return Some(k); + } + (sizes::WARM_PB_SLOTS..sizes::PB_SLOTS) + .find(|&k| in_mask(k) && self.slot_displaced(k) && self.owners[k].is_some()) + .or_else(|| { + (sizes::WARM_PB_SLOTS..sizes::PB_SLOTS) + .find(|&k| in_mask(k) && self.slot_displaced(k)) + }) + } + /// Whether `vm` has a warm reusable PB slot in `slot_mask` matching `want_scs` and + /// covering `min_blocks` so it can pipeline without InitBM. + pub(crate) fn can_pipeline_in_mask_blocks_mode( + &self, + vm: &Arc, + slot_mask: u32, + home: usize, + min_blocks: u32, + want_scs: bool, + ) -> bool { + self.pick_slot_in_mask_blocks_mode(vm, true, slot_mask, home, min_blocks, want_scs) + .is_some() + } + /// Whether no allocator slot in `slot_mask` can accept a render for `vm` and `want_scs` + /// once drained. + pub(crate) fn exhausted_for_mask_mode( + &self, + vm: &Arc, + slot_mask: u32, + home: usize, + want_scs: bool, + ) -> bool { + self.inflight.iter().all(|&c| c == 0) + && self + .pick_slot_in_mask_blocks_mode(vm, false, slot_mask, home, 0, want_scs) + .is_none() + } + /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm` and `want_scs`, + /// requiring any reused epoch to match `want_scs` and cover at least `min_blocks` when a + /// displaced slot is available for rotation. + /// + /// When `behind` is true (pipelining behind active flights), only a healthy warm reusable + /// slot already bound to `vm` with matching SCS mode (preferring `self.active`, then any + /// other slot in `0..limit`) is eligible; cold VMs, base<->SCS transitions, or VMs whose PB + /// heap expanded return `None` so the engine drains once before rotating onto a fresh + /// `InitBM` epoch. + /// When `behind` is false (engine drained), a qualifying warm reusable slot for `vm` is + /// preferred; otherwise an already-used displaced slot is chosen first (preserving the 2-slot + /// working set) or the lowest fresh slot is claimed. + #[allow(dead_code)] + pub(crate) fn pick_slot_within_blocks_mode( + &self, + vm: &Arc, + behind: bool, + limit: usize, + min_blocks: u32, + want_scs: bool, + ) -> Option { + let n = limit.min(sizes::PB_SLOTS); + if let Some(a) = self.active { + if a < n + && self + .reusable_for_within_mode(a, vm, n, min_blocks, want_scs) + .is_some() + { + return Some(a); + } + } + if let Some(k) = (0..n).find(|&k| { + self.reusable_for_within_mode(k, vm, n, min_blocks, want_scs) + .is_some() + }) { + return Some(k); + } + if behind { + return None; + } + // Prefer reusing a displaced slot over claiming a fresh recovery slot. + (0..n) + .find(|&k| self.slot_displaced(k) && self.owners[k].is_some()) + .or_else(|| (0..n).find(|&k| self.slot_displaced(k))) + } + /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`, requiring any reused + /// epoch to cover at least `min_blocks` when a displaced slot is available for rotation. + #[allow(dead_code)] + pub(crate) fn pick_slot_within_blocks( + &self, + vm: &Arc, + behind: bool, + limit: usize, + min_blocks: u32, + ) -> Option { + self.pick_slot_within_blocks_mode(vm, behind, limit, min_blocks, false) + } + /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`. + #[allow(dead_code)] + pub(crate) fn pick_slot_within( + &self, + vm: &Arc, + behind: bool, + limit: usize, + ) -> Option { + self.pick_slot_within_blocks(vm, behind, limit, 0) + } + /// Selects a physical PB/UMA allocator slot across all `0..PB_SLOTS` for `vm`. + #[allow(dead_code)] + pub(crate) fn pick_slot(&self, vm: &Arc, behind: bool) -> Option { + self.pick_slot_within(vm, behind, sizes::PB_SLOTS) + } + /// Whether `vm` has a warm reusable PB slot within `0..limit` matching `want_scs` and + /// covering `min_blocks` so it can pipeline without InitBM. + #[allow(dead_code)] + pub(crate) fn can_pipeline_within_blocks_mode( + &self, + vm: &Arc, + limit: usize, + min_blocks: u32, + want_scs: bool, + ) -> bool { + self.pick_slot_within_blocks_mode(vm, true, limit, min_blocks, want_scs) + .is_some() + } + /// Whether `vm` has a warm reusable PB slot within `0..limit` covering `min_blocks` and can + /// pipeline without InitBM. + #[allow(dead_code)] + pub(crate) fn can_pipeline_within_blocks( + &self, + vm: &Arc, + limit: usize, + min_blocks: u32, + ) -> bool { + self.can_pipeline_within_blocks_mode(vm, limit, min_blocks, false) + } + /// Whether `vm` has a warm reusable PB slot within `0..limit` and can pipeline without InitBM. + #[allow(dead_code)] + pub(crate) fn can_pipeline_within(&self, vm: &Arc, limit: usize) -> bool { + self.can_pipeline_within_blocks(vm, limit, 0) + } + /// Whether `vm` has a warm reusable PB slot and can pipeline without InitBM. + #[allow(dead_code)] + pub(crate) fn can_pipeline(&self, vm: &Arc) -> bool { + self.can_pipeline_within(vm, sizes::PB_SLOTS) + } + /// Whether no allocator slot can ever accept another render (even after draining). + #[allow(dead_code)] + pub(crate) fn exhausted(&self) -> bool { + if self.inflight.iter().any(|&c| c != 0) { + return false; + } + if (0..sizes::PB_SLOTS).any(|k| { + !self.quarantined[k] + && self.keep[k] + && self.owners[k] + .as_ref() + .is_some_and(|o| o.exposed.load(Ordering::Acquire)) + }) { + return false; + } + !(0..sizes::PB_SLOTS).any(|k| self.slot_displaced(k)) + } + /// Whether no allocator slot within `0..limit` can accept a render for `vm` and `want_scs` + /// once drained. + #[allow(dead_code)] + pub(crate) fn exhausted_for_within_mode( + &self, + vm: &Arc, + limit: usize, + want_scs: bool, + ) -> bool { + self.inflight.iter().all(|&c| c == 0) + && self + .pick_slot_within_blocks_mode(vm, false, limit, 0, want_scs) + .is_none() + } + /// Whether no allocator slot within `0..limit` can accept a render for `vm` once drained. + /// + /// When a VM prepared fewer PB slots than needed after a render hang (or when only one + /// surviving slot remains and belongs to another VM), that job must cancel immediately + /// instead of spinning on `EAGAIN` until the administrative publication deadline fails the GPU. + #[allow(dead_code)] + pub(crate) fn exhausted_for_within(&self, vm: &Arc, limit: usize) -> bool { + self.exhausted_for_within_mode(vm, limit, false) + } + /// Whether no allocator slot can accept a render for `vm` once the engine is drained. + #[allow(dead_code)] + pub(crate) fn exhausted_for(&self, vm: &Arc) -> bool { + self.exhausted_for_within(vm, sizes::PB_SLOTS) + } + /// Retains the candidate VM, owning render/recovery arena, and firmware UMA descriptor lease + /// before publication visibility. + #[allow(dead_code)] + pub(crate) fn hold_alloc( + &mut self, + k: usize, + vm: &Arc, + arena: Option, + uma_lease: Option>, + ) -> Result { + if k >= sizes::PB_SLOTS || self.quarantined[k] { + return Err(EINVAL); + } + self.pending_vms[k] = Some(vm.clone()); + self.pending_arenas[k] = arena; + self.pending_uma[k] = uma_lease; + Ok(()) + } + /// Cancels unpublished candidate retention for allocator slot `k`. + #[allow(dead_code)] + pub(crate) fn cancel_alloc(&mut self, k: usize) { + if k < sizes::PB_SLOTS { + self.pending_vms[k] = None; + self.pending_arenas[k] = None; + self.pending_uma[k] = None; + } + } + /// Records a render reaching firmware visibility on allocator slot `k`. + #[allow(dead_code)] + pub(crate) fn publish_flight(&mut self, k: usize) { + if k < sizes::PB_SLOTS { + self.active = Some(k); + self.inflight[k] = self.inflight[k].saturating_add(1); + } + } + /// Retires one render flight on allocator slot `k` after a full normal receipt. + #[allow(dead_code)] + pub(crate) fn retire_flight( + &mut self, + k: usize, + epoch: &Arc, + binding: u64, + completed: bool, + ) -> Result { + if k >= sizes::PB_SLOTS { + return Err(EINVAL); + } + self.inflight[k] = self.inflight[k].saturating_sub(1); + if self.quarantined[k] { + return Ok(()); + } + if self.owners[k].as_ref().is_some_and(|old| { + !Arc::ptr_eq(&old._vm, &epoch._vm) && !old._vm.vm.is_closed() && self.is_vm_last(old) + }) { + self.stats.kept += 1; + } + if completed { + self.note_vm_last(epoch); + } + self.owners[k] = Some(epoch.clone()); + self.retained_pb[k] = Some(epoch.records_lease()); + if let Some(vm) = self.pending_vms[k].take() { + self.owner_vms[k] = Some(vm); + } + if let Some(arena) = self.pending_arenas[k].take() { + self.owner_arenas[k] = Some(arena); + } + if let Some(uma) = self.pending_uma[k].take() { + self.retained_uma[k] = Some(uma); + } + self.last_clean_retired = Some(k); + self.retire_epoch(k, binding, completed); + Ok(()) + } + /// Whether `epoch` is the last retired epoch of its VM ([`Self::vm_last`]). + fn is_vm_last(&self, epoch: &Arc) -> bool { + self.vm_last + .get(epoch._vm.slot as usize) + .and_then(Option::as_ref) + .is_some_and(|last| Arc::ptr_eq(last, epoch)) + } + /// A render of `epoch` retired normally: its VM's context has run that render's InitBM (or + /// reused the epoch), so the VM's earlier epoch is no longer written and may go. A closed + /// VM keeps an entry only until [`Self::reclaim_closed`] finds nothing of it pending. + fn note_vm_last(&mut self, epoch: &Arc) { + let vm = &epoch._vm; + let closed = vm.vm.is_closed(); + let Some(entry) = self.vm_last.get_mut(vm.slot as usize) else { + return; + }; + if entry.as_ref().is_some_and(|last| Arc::ptr_eq(last, epoch)) { + return; + } + *entry = Some(epoch.clone()); + self.closed_vm_last |= closed; + } + /// Whether a closed VM's entry was recorded since the last call: [`Self::reclaim_closed`] + /// must run again to release it. + pub(crate) fn take_closed_vm_last(&mut self) -> bool { + core::mem::take(&mut self.closed_vm_last) + } + /// Quarantines allocator slot `k` permanently after a passed abort, retaining all leases + /// including any fresh epoch published on the aborted flight alongside `owners[k]`. + #[allow(dead_code)] + pub(crate) fn quarantine_flight(&mut self, k: usize, pb: Option>) { + if k < sizes::PB_SLOTS { + self.inflight[k] = self.inflight[k].saturating_sub(1); + self.quarantined[k] = true; + self.keep[k] = false; + if let Some(epoch) = pb { + if self.quarantined_epochs[k].is_none() { + self.quarantined_epochs[k] = Some(epoch); + } else { + // Already retaining an aborted epoch on this slot; never unmap an exposed + // epoch or allocate under the device lock. + core::mem::forget(epoch); + } + } + } else if let Some(epoch) = pb { + core::mem::forget(epoch); + } + } + /// Slot `k` is handed to a render's epoch, `reused` or fresh (with InitBM). Returns the + /// binding the render retires with. + pub(crate) fn bind(&mut self, k: usize, reused: bool) -> u64 { + let (Some(binds), Some(keep)) = (self.binds.get_mut(k), self.keep.get_mut(k)) else { + return 0; + }; + if !reused { + *binds = binds.wrapping_add(1); + *keep = false; + } + *binds + } + /// A render on slot `k` with `binding` retired, after its `retire_binding`. If no other + /// epoch was bound and no recovery or sleep restart happened since, the next render of the + /// same VM may reuse + /// its epoch after a `completed` render; after a failed one it starts fresh. + pub(crate) fn retire_epoch(&mut self, k: usize, binding: u64, completed: bool) { + if self.binds.get(k) == Some(&binding) { + if let Some(keep) = self.keep.get_mut(k) { + *keep = completed && !self.quarantined[k]; + } + } + } + /// Reuse nothing on slot `k` (its render was aborted). + #[allow(dead_code)] + pub(crate) fn forget(&mut self, k: usize) { + if let Some(keep) = self.keep.get_mut(k) { + *keep = false; + } + } + /// A firmware recovery started: no epoch bound so far is reused, also not by a render that + /// retires after it (its binding no longer matches); each slot's next render starts fresh. + pub(crate) fn invalidate(&mut self) { + for (binds, keep) in self.binds.iter_mut().zip(self.keep.iter_mut()) { + *binds = binds.wrapping_add(1); + *keep = false; + } + } + /// Releases the displaced render arenas and PB heaps of closed VMs while preserving active, + /// in-flight, undisplaced, and quarantined slots. Returns `true` if any non-quarantined + /// slot still holds such a closed-VM lease awaiting retirement or displacement. + /// + /// The owner epoch itself stays until a newer epoch retires on its slot + /// ([`Self::retire_flight`]): `pb_mgr_table[k]` keeps naming its manager, and the parameter + /// manager can still write that manager's page list through the context of the epoch's VM. + /// Also releases a closed VM's [`Self::vm_last`] entry once nothing of that VM is pending. + pub(crate) fn reclaim_closed(&mut self) -> bool { + let mut remaining = false; + for k in 0..sizes::PB_SLOTS { + if self.quarantined[k] { + continue; + } + let pending = self.pending_vms[k].is_some() + || self.pending_arenas[k].is_some() + || self.pending_uma[k].is_some(); + // Only the owner epoch is left; the next epoch to retire on the slot releases it. + if !pending && self.owner_vms[k].is_none() && self.owner_arenas[k].is_none() { + continue; + } + let closed = self.owner_vms[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()) + || self.owners[k] + .as_ref() + .is_some_and(|epoch| epoch._vm.vm.is_closed()) + || self.pending_vms[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + if !closed { + continue; + } + if self.slot_displaced(k) && !pending { + self.owner_vms[k] = None; + self.owner_arenas[k] = None; + self.keep[k] = false; + self.binds[k] = self.binds[k].wrapping_add(1); + } else { + remaining = true; + } + } + // A closed VM accepts no new render. Once none it accepted waits for publication or + // retirement, its context runs no further InitBM and its last epoch may go. A render + // left on a quarantined slot keeps its VM there anyway. + for i in 0..VM_LAST_ENTRIES { + let Some(vm) = self.vm_last[i].as_ref().map(|last| &last._vm) else { + continue; + }; + if !vm.vm.is_closed() { + continue; + } + let pending = (0..sizes::PB_SLOTS).any(|k| { + !self.quarantined[k] + && self.pending_vms[k].as_ref().is_some_and(|p| Arc::ptr_eq(p, vm)) + }); + if pending || vm.renders_unpublished() { + remaining = true; + } else { + self.vm_last[i] = None; + } + } + remaining + } + #[allow(dead_code)] pub(crate) fn retire_binding(&mut self, k: usize, epoch: &Arc) -> Result { *self.owners.get_mut(k).ok_or(EINVAL)? = Some(epoch.clone()); + *self.retained_pb.get_mut(k).ok_or(EINVAL)? = Some(epoch.records_lease()); Ok(()) } pub(crate) fn write_stats(&self, f: &mut impl fmt::Write) -> fmt::Result { writeln!( f, - "pb: M4 private allocators blocks {} requests {} bad {}", + "pb: M4 private allocators blocks {} requests {} bad {} reused {} fresh {} kept {}", buffer::MAX_BLOCKS, self.stats.requests, - self.stats.bad + self.stats.bad, + self.stats.reused, + self.stats.fresh, + self.stats.kept ) } } -/// One never-reinitialized PB manager installation. Even a same-VM command gets a fresh -/// manager and full InitBM; no host reset of exposed firmware cursors is required. +/// One never-reinitialized PB manager installation. Unless a same-VM command reuses its +/// slot's retired epoch, every command gets a fresh manager and full InitBM; no host reset of +/// exposed firmware cursors is required. pub(crate) struct PbEpoch(crate::cleanup::Deferred); impl core::ops::Deref for PbEpoch { type Target = PbEpochInner; @@ -301,7 +1191,15 @@ pub(crate) struct PbEpochInner { pub(crate) misc: Arc, pub(crate) initbm: Arc, assigned: AtomicU32, + heap_blocks: AtomicU32, + /// High-water block count previously written into the zero-allocated `pages`/`blocks` lists, + /// so fresh `InitBM` seeding writes only the active prefix (plus any shrink tail). + seeded_blocks: AtomicU32, + scs: AtomicBool, exposed: AtomicBool, + /// VM-free firmware lease keeping `records` (`manager`, `ring`, `counter`, `misc`, `initbm`) + /// mapped across closed-VM reclaim until a newer `InitBM` overwrites `pb_mgr_table[k]`. + records_lease: Arc, // Unmap private records before releasing the VM's aliases and ASID. _objects: Objects, _vm: Arc, @@ -314,8 +1212,10 @@ impl PbEpoch { vm: &Arc, permit: super::budget::Permit, ) -> Result> { + let mut fw = factory.fw_objects(); + let records = alloc(&mut fw, 0x500, Class::Fw, None, true)?; + let records_lease = FwLease::new(fw)?; let mut o = factory.objects(&vm.vm); - let records = alloc(&mut o, 0x500, Class::Fw, None, true)?; let mut inner = PbEpochInner { manager: FwObject::view(&records, 0, 0xc0)?, pages: o.alloc_dynamic_client(buffer::PAGE_LIST_SIZE)?, @@ -325,7 +1225,11 @@ impl PbEpoch { misc: FwObject::view(&records, 0x300, 0x40)?, initbm: FwObject::view(&records, 0x400, 0x20)?, assigned: AtomicU32::new(u32::MAX), + heap_blocks: AtomicU32::new(0), + seeded_blocks: AtomicU32::new(0), + scs: AtomicBool::new(false), exposed: AtomicBool::new(false), + records_lease, _objects: o, _vm: vm.clone(), _permit: permit, @@ -337,35 +1241,92 @@ impl PbEpoch { )?) } + /// Firmware-only lease retaining this epoch's `pb_manager` + `counter` page. + pub(crate) fn records_lease(&self) -> Arc { + self.records_lease.clone() + } + /// Seed only unpublished storage. A retry may choose another physical slot; after /// exposure neither the manager nor any of its firmware-mutated lists is reset. - pub(crate) fn prepare(&self, k: usize, heap: u64) -> Result { - if k >= 2 || self.exposed.load(Ordering::Acquire) { + #[allow(dead_code)] + pub(crate) fn prepare(&self, k: usize, heap: u64, heap_blocks: u32) -> Result { + self.prepare_with_scs(k, heap, heap_blocks, false) + } + + /// Like [`Self::prepare`], recording whether this epoch is bound to the VM's SCS-capable + /// render allocators (`scs == true`) or its base allocators (`scs == false`). + #[allow(dead_code)] + pub(crate) fn prepare_with_scs( + &self, + k: usize, + heap: u64, + heap_blocks: u32, + scs: bool, + ) -> Result { + self.prepare_with_scs_for(&buffer::pb_manager::V25G83, k, heap, heap_blocks, scs) + } + + /// Like [`Self::prepare_with_scs`], encoding the PB manager with `layout` for the active + /// firmware ABI. + pub(crate) fn prepare_with_scs_for( + &self, + layout: &buffer::pb_manager::Layout, + k: usize, + heap: u64, + heap_blocks: u32, + scs: bool, + ) -> Result { + if k >= sizes::PB_SLOTS + || self.exposed.load(Ordering::Acquire) + || heap_blocks == 0 + || heap_blocks > buffer::MAX_BLOCKS + { return Err(EINVAL); } - write_records(&self.pages, buffer::MAX_PAGES as usize, |i| { - buffer::page_record(heap, i as u32).to_le_bytes() + // Only the backed part of the heap is named; the rest of the zero-allocated lists stays + // zero. On an unpublished retry with fewer blocks, clear the previously seeded tail. + let prev_blocks = self.seeded_blocks.load(Ordering::Acquire); + let write_blocks = heap_blocks.max(prev_blocks); + self.seeded_blocks.store(write_blocks, Ordering::Release); + let pages = heap_blocks * buffer::PAGES_PER_BLOCK; + let write_pages = write_blocks * buffer::PAGES_PER_BLOCK; + write_records(&self.pages, write_pages as usize, |i| { + let i = i as u32; + (if i < pages { buffer::page_record(heap, i) } else { 0 }).to_le_bytes() })?; - write_records(&self.blocks, buffer::MAX_BLOCKS as usize, |i| { - u64::from(buffer::block_record(heap, i as u32)).to_le_bytes() + write_records(&self.blocks, write_blocks as usize, |i| { + let b = i as u32; + u64::from(if b < heap_blocks { buffer::block_record(heap, b) } else { 0 }).to_le_bytes() })?; - self.ring.w32(0, buffer::MAX_BLOCKS)?; - self.ring.w32(4, buffer::MAX_BLOCKS)?; + let posted = super::params::pb_posted_blocks(heap_blocks); + self.ring.w32(0, posted)?; + self.ring.w32(4, posted)?; self.counter.w64(0, 1)?; self.manager.write( 0, - &buffer::pb_manager_image( + &buffer::pb_manager_image_for( + layout, k as u32, self.pages.va, gva(&self.pages)?, self.blocks.va, self.ring.va, self.counter.va, + heap_blocks, ), )?; + self.seeded_blocks.store(heap_blocks, Ordering::Release); self.assigned.store(k as u32, Ordering::Release); + self.heap_blocks.store(heap_blocks, Ordering::Release); + self.scs.store(scs, Ordering::Release); Ok(()) } + pub(crate) fn heap_blocks(&self) -> u32 { + self.heap_blocks.load(Ordering::Acquire) + } + pub(crate) fn scs(&self) -> bool { + self.scs.load(Ordering::Acquire) + } pub(crate) fn check_assignment(&self, k: usize) -> Result { if self.assigned.load(Ordering::Acquire) != k as u32 { return Err(EINVAL); @@ -375,6 +1336,10 @@ impl PbEpoch { pub(crate) fn expose(&self) { self.exposed.store(true, Ordering::Release); } + /// Never handed to the firmware: its storage may serve another render of its VM. + pub(crate) fn unexposed(&self) -> bool { + !self.exposed.load(Ordering::Acquire) + } } impl Firmware { diff --git a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs index baf623b2722d78..d3cf6caf6084d3 100644 --- a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs +++ b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs @@ -1,7 +1,16 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! Bounded two-owner displacement ledger. A completion alone never makes an M4 UMA owner -//! reusable: a distinct, fully retired owner must replace it in the same hardware slot. +//! Bounded displacement ledger of the retained owners of one hardware UMA slot. A completion +//! alone never makes an M4 UMA owner reusable: a later, fully retired publication must have +//! replaced it in the same hardware slot. +//! +//! The firmware runs one queue's commands strictly in order, each to its Finalize, so a +//! publication that retired started after every earlier one finished and displaced it. Owners +//! therefore retire in publication order and an owner is reusable once any owner published +//! after it retired. With `pipelined`, owners may be published while earlier ones are still +//! in flight (the compute queue); without it, publication stays serialized against every +//! owner (the render pass slots). +//! //! Core-only so the transition system is executable in host tests. #[derive(Copy, Clone, Debug, Eq, PartialEq)] @@ -18,6 +27,7 @@ struct Unit { state: State, previous: State, generation: u8, + pipe: u8, publication: u64, } @@ -33,23 +43,24 @@ pub(crate) struct Counts { } #[derive(Clone)] -pub(crate) struct Lifetime { - units: [Unit; 2], +pub(crate) struct Lifetime { + units: [Unit; N], sequence: u64, - last_owner: Option, + pipelined: bool, } -impl Lifetime { - pub(crate) const fn new() -> Self { +impl Lifetime { + pub(crate) const fn new(pipelined: bool) -> Self { let unit = Unit { state: State::Fresh, previous: State::Fresh, generation: 0, + pipe: 0, publication: 0, }; Self { - units: [unit; 2], + units: [unit; N], sequence: 0, - last_owner: None, + pipelined, } } #[allow(dead_code)] @@ -70,16 +81,26 @@ impl Lifetime { } counts } + /// Published owners. + pub(crate) fn published(&self) -> u32 { + self.units + .iter() + .filter(|u| u.state == State::Published) + .count() as u32 + } pub(crate) fn available(&self, k: usize) -> bool { let Some(u) = self.units.get(k) else { return false; }; match u.state { State::Fresh => true, - State::Retired => self.last_owner.is_some_and(|b| { + // A later publication on the same hardware pipe retired: it started only after this + // owner finished on that pipe, and its load displaced this owner from the slot. + State::Retired => self.units.iter().enumerate().any(|(b, other)| { b != k - && self.units[b].state == State::Retired - && self.units[b].publication > u.publication + && other.state == State::Retired + && other.pipe == u.pipe + && other.publication > u.publication }), _ => false, } @@ -87,12 +108,51 @@ impl Lifetime { /// No amount of firmware progress can make a unit claimable. The caller must fail /// pending work rather than wait forever after abort/quarantine or sequence exhaustion. pub(crate) fn exhausted(&self) -> bool { - (0..2).all(|k| !self.available(k)) + self.exhausted_within(N) + } + /// [`Self::exhausted`] when only owners `0..n` exist. + pub(crate) fn exhausted_within(&self, n: usize) -> bool { + (0..n.min(N)).all(|k| !self.available(k)) && !self .units .iter() .any(|u| matches!(u.state, State::Preparing | State::Published)) } + /// [`Self::exhausted`] restricted to owners selected by `mask` (bit `k` -> owner `k`). + pub(crate) fn exhausted_in_mask(&self, mask: u32) -> bool { + let mut rem = mask; + while rem != 0 { + let k = rem.trailing_zeros() as usize; + rem &= rem - 1; + if k < N && self.available(k) { + return false; + } + } + !self + .units + .iter() + .any(|u| matches!(u.state, State::Preparing | State::Published)) + } + /// Bitmask of permanently quarantined owners in `0..N.min(32)`. + pub(crate) fn quarantined_mask(&self) -> u32 { + let mut mask = 0u32; + for k in 0..N.min(32) { + if self.units[k].state == State::Quarantined { + mask |= 1u32 << k; + } + } + mask + } + /// Whether any owner in `0..n` is permanently quarantined. + pub(crate) fn any_quarantined_within(&self, n: usize) -> bool { + (0..n.min(N)).any(|k| self.units[k].state == State::Quarantined) + } + /// Whether owner `k` is permanently quarantined. + pub(crate) fn is_quarantined(&self, k: usize) -> bool { + self.units + .get(k) + .is_some_and(|u| u.state == State::Quarantined) + } pub(crate) fn claim(&mut self, k: usize) -> bool { if !self.available(k) { return false; @@ -113,22 +173,43 @@ impl Lifetime { } } pub(crate) fn publish(&mut self, k: usize) -> bool { - if self.units[k].state != State::Preparing || self.sequence == u64::MAX { + self.publish_on(k, 0) + } + /// Publishes unit `k` onto hardware queue `pipe` (`0` for single-pipe engines, or the CDM + /// pipe index for dual-pipe compute). Each pipe enforces FIFO retirement and same-pipe + /// displacement independently while sharing a monotonic publication sequence. + pub(crate) fn publish_on(&mut self, k: usize, pipe: u8) -> bool { + if k >= N || self.units[k].state != State::Preparing || self.sequence == u64::MAX { return false; } - // Publication must be serialized against every owner of this hardware slot. - if self.units.iter().any(|u| u.state == State::Published) { + // Without pipelining, publication is serialized against every owner on the same pipe. + if !self.pipelined + && self + .units + .iter() + .any(|u| u.state == State::Published && u.pipe == pipe) + { return false; } self.sequence += 1; + self.units[k].pipe = pipe; self.units[k].publication = self.sequence; self.units[k].state = State::Published; - self.last_owner = Some(k); true } - /// Called only after the caller has established complete, exact wire retirement. + /// Called only after the caller has established complete, exact wire retirement. Owners + /// retire in publication order per pipe: `k` must be the oldest published owner on its pipe. pub(crate) fn retire(&mut self, k: usize) -> bool { - if self.units[k].state != State::Published || self.last_owner != Some(k) { + if k >= N || self.units[k].state != State::Published { + return false; + } + let publication = self.units[k].publication; + let pipe = self.units[k].pipe; + if self + .units + .iter() + .any(|u| u.state == State::Published && u.pipe == pipe && u.publication < publication) + { return false; } self.units[k].state = State::Retired; @@ -145,7 +226,7 @@ mod tests { use super::*; #[test] fn distinct_retired_displacement_is_required() { - let mut l = Lifetime::new(); + let mut l = Lifetime::<2>::new(false); assert!(l.claim(0)); assert!(l.publish(0)); assert!(!l.claim(0)); @@ -164,7 +245,7 @@ mod tests { } #[test] fn abort_does_not_recycle_or_authorize_displacement() { - let mut l = Lifetime::new(); + let mut l = Lifetime::<2>::new(false); assert!(l.claim(0)); assert!(l.publish(0)); assert!(l.retire(0)); @@ -185,7 +266,7 @@ mod tests { } #[test] fn preparation_cancel_preserves_retirement() { - let mut l = Lifetime::new(); + let mut l = Lifetime::<2>::new(false); assert!(l.claim(0)); l.cancel(0); assert_eq!(l.generation(0), 0); @@ -202,7 +283,7 @@ mod tests { } #[test] fn publication_is_serialized_and_command_count_is_not_binding_generation() { - let mut l = Lifetime::new(); + let mut l = Lifetime::<2>::new(false); assert!(l.claim(0)); assert!(l.publish(0)); assert!(l.claim(1)); @@ -219,4 +300,79 @@ mod tests { assert_eq!(l.generation(1), 1); assert!(l.claim(0)); } + #[test] + fn pipelined_owners_keep_n_minus_one_in_flight() { + let mut l = Lifetime::<4>::new(true); + // Fresh owners publish back to back. + for k in 0..4 { + assert!(l.claim(k)); + assert!(l.publish(k)); + } + assert_eq!(l.published(), 4); + // Out of order retirement is refused. + assert!(!l.retire(1)); + assert!(l.retire(0)); + // Owner 0 retired but nothing after it has: not displaced yet. + assert!(!l.claim(0)); + assert!(l.retire(1)); + assert!(l.claim(0)); // displaced by 1 + assert!(!l.claim(1)); // 2 still in flight + assert!(l.publish(0)); + assert!(l.retire(2)); + assert!(l.claim(1)); + assert!(l.publish(1)); + // Steady state: round robin with up to three in flight. + let mut next = 2; + for _ in 0..1000 { + let oldest = (0..4) + .filter(|&k| l.units[k].state == State::Published) + .min_by_key(|&k| l.units[k].publication) + .unwrap(); + assert!(l.retire(oldest)); + assert!(l.claim(next)); + assert!(l.publish(next)); + assert!(l.published() <= 3); + next = (next + 1) % 4; + } + } + #[test] + fn pipelined_newest_retired_owner_is_never_reusable() { + let mut l = Lifetime::<3>::new(true); + for k in 0..3 { + assert!(l.claim(k)); + assert!(l.publish(k)); + } + for k in 0..3 { + assert!(l.retire(k)); + } + assert!(l.available(0) && l.available(1)); + assert!(!l.available(2)); + assert!(l.claim(1)); + // 2 still proves 0 displaced although 1 is being prepared again. + assert!(l.available(0)); + assert!(!l.available(2)); + } + #[test] + fn two_pipes_retire_out_of_order_and_displace_independently() { + let mut l = Lifetime::<4>::new(true); + // Publish unit 0 on pipe 0, then unit 2 on pipe 1. + assert!(l.claim(0) && l.publish_on(0, 0)); + assert!(l.claim(2) && l.publish_on(2, 1)); + // Pipe 1 finishes ahead of pipe 0: out-of-order retirement across pipes must succeed. + assert!(l.retire(2)); + // Pipe 1's second publication (unit 3) retires and displaces unit 2 on pipe 1. + assert!(l.claim(3) && l.publish_on(3, 1)); + assert!(l.retire(3)); + assert!(l.available(2)); + assert!(!l.available(3)); + // Pipe 0's unit 0 now retires: unit 3 (pipe 1, higher publication) must NOT displace it. + assert!(l.retire(0)); + assert!(!l.available(0)); + // Pipe 0's next publication (unit 1) retires and displaces unit 0 on pipe 0. + assert!(l.claim(1) && l.publish_on(1, 0)); + assert!(l.retire(1)); + assert!(l.available(0)); + assert!(!l.available(1)); + assert!(!l.available(3)); + } } diff --git a/drivers/gpu/drm/asahi/g16/power.rs b/drivers/gpu/drm/asahi/g16/power.rs index 5e3346e3cf1e23..e476ccb497bb22 100644 --- a/drivers/gpu/drm/asahi/g16/power.rs +++ b/drivers/gpu/drm/asahi/g16/power.rs @@ -20,15 +20,20 @@ pub(crate) mod policy; use core::{ffi::c_void, ptr::NonNull}; use kernel::{device, prelude::*, sync::aref::ARef}; -use super::fw::initdata::globals; +use super::fw::initdata; use super::recovery::now_ns; use super::regs::wmb; use super::Firmware; -use policy::{COOLING_MAX, PSTATE_MAX}; +use policy::{COOLING_MAX, TOP_DEFAULT}; -static_assert!(globals::PSTATE_SELECTORS[0] == 0x88); -static_assert!(globals::PSTATE_SELECTORS[1] == 0x8c); -static_assert!(globals::PSTATE_SELECTORS[2] == 0x98); +// The three Globals p-state selectors: 0x88, 0x8c and 0x98 in 25G83; four bytes later in +// 26B123, which inserted a word at 0x38. +static_assert!(initdata::V25G83.pstate_selectors[0] == 0x88); +static_assert!(initdata::V25G83.pstate_selectors[1] == 0x8c); +static_assert!(initdata::V25G83.pstate_selectors[2] == 0x98); +static_assert!(initdata::V26B123.pstate_selectors[0] == 0x8c); +static_assert!(initdata::V26B123.pstate_selectors[1] == 0x90); +static_assert!(initdata::V26B123.pstate_selectors[2] == 0x9c); extern "C" { fn asahi_g16_clpc_gpu_get(dev: *mut c_void, out: *mut *mut c_void) -> core::ffi::c_int; @@ -36,6 +41,7 @@ extern "C" { fn asahi_g16_clpc_gpu_put(gpu: *mut c_void); fn asahi_g16_cooling_register(dev: *mut c_void) -> *mut c_void; fn asahi_g16_cooling_unregister(cooling: *mut c_void); + fn asahi_g16_cooling_has_pmp(cooling: *const c_void) -> bool; fn asahi_g16_cooling_sample( cooling: *mut c_void, now: u64, @@ -44,13 +50,20 @@ extern "C" { governor: *mut u32, power: *mut u32, backstop: *mut u32, + zone_seq: *mut u64, + release_mc: *mut core::ffi::c_long, + hot_mc: *mut core::ffi::c_long, + critical_mc: *mut core::ffi::c_long, + limits_valid: *mut bool, ) -> i32; } -/// Owns the cooling-device registration and PMP consumer. The C helpers only -/// bridge the PMP provider and shared cooling policy, with atomic governor requests. +/// Owns the cooling-device registration and thermal telemetry consumer (PMP when `apple,pmp` +/// is present, or SoC die thermal zones otherwise). The C helpers only bridge the provider and +/// atomic governor requests. struct Cooling { inner: NonNull, + is_pmp: bool, _dev: ARef, } @@ -67,14 +80,23 @@ impl Cooling { let inner = kernel::error::from_err_ptr(unsafe { asahi_g16_cooling_register(dev.as_raw().cast()) })?; + let inner = NonNull::new(inner).ok_or(ENOMEM)?; + // SAFETY: `inner` is the live cooling object returned above. + let is_pmp = unsafe { asahi_g16_cooling_has_pmp(inner.as_ptr()) }; Ok(Self { - inner: NonNull::new(inner).ok_or(ENOMEM)?, + inner, + is_pmp, _dev: dev.into(), }) } fn sample(&mut self, now: u64, idle: bool, power: &mut Sample) -> Result { let mut mc: core::ffi::c_long = 0; + let mut seq: u64 = 0; + let mut release_mc: core::ffi::c_long = 0; + let mut hot_mc: core::ffi::c_long = 0; + let mut critical_mc: core::ffi::c_long = 0; + let mut limits_valid = false; // SAFETY: The C allocation and PMP phandle outlive this call, all output // pointers are valid, and the caller holds the GPU device mutex. let ret = unsafe { @@ -86,9 +108,20 @@ impl Cooling { &mut power.governor, &mut power.budget, &mut power.backstop, + &mut seq, + &mut release_mc, + &mut hot_mc, + &mut critical_mc, + &mut limits_valid, ) }; power.temperature_mc = mc as i64; + power.zone_seq = seq; + power.zone_limits = limits_valid.then_some(policy::ZoneLimits { + release_mc: release_mc as i64, + hot_mc: hot_mc as i64, + critical_mc: critical_mc as i64, + }); kernel::error::to_result(ret) } } @@ -107,6 +140,8 @@ struct Sample { governor: u32, budget: u32, backstop: u32, + zone_seq: u64, + zone_limits: Option, } /// DT-selected memory-demand provider (`apple,clpc`), or none. Its @@ -150,11 +185,15 @@ impl Drop for Demand { /// provider sample the shared cooling policy keeps the ceiling at S1. pub(crate) struct Power { clpc: Demand, - /// The work-in-flight state last reported to `clpc`. - reported: Option, + /// Work-in-flight state and 2 ms idle-hold hysteresis reported to `clpc`. + clpc_hold: policy::ClpcHold, cooling: Cooling, + /// Fail-closed thermal-zone backstop used when the GPU DT node has no `apple,pmp`. + zone_backstop: policy::ZoneBackstop, sample: Sample, last_sample_ns: Option, + /// The board's top state: S9 on the ten-row tables, S10 on the J773g table. + pub(crate) top: u32, pub(crate) configured: u32, pub(crate) user: u32, pub(crate) effective: u32, @@ -170,27 +209,35 @@ pub(crate) struct Power { } impl Power { - /// The Main image initializes all nine active states. Initdata publishes - /// startup S1 before INIT; this object starts with that same effective state. + /// The Main image initializes every active state of the board's table. Initdata publishes + /// startup S1 before INIT; this object starts with that same effective state until live + /// thermal telemetry confirms a safe ceiling. pub(crate) fn new(dev: &device::Device) -> Result { + // First: a CLPC that has not probed yet defers before the PMP vote. + let clpc = Demand::new(dev)?; + let cooling = Cooling::new(dev)?; + let pmp_initial = if cooling.is_pmp { COOLING_MAX } else { 0 }; Ok(Self { - // First: a CLPC that has not probed yet defers before the PMP vote. - clpc: Demand::new(dev)?, - reported: None, - cooling: Cooling::new(dev)?, + clpc, + clpc_hold: policy::ClpcHold::new(), + cooling, + zone_backstop: policy::ZoneBackstop::new(), sample: Sample { temperature_mc: 0, - governor: COOLING_MAX, - budget: COOLING_MAX, + governor: pmp_initial, + budget: pmp_initial, backstop: COOLING_MAX, + zone_seq: 0, + zone_limits: None, }, last_sample_ns: None, - configured: PSTATE_MAX, - user: PSTATE_MAX, + top: TOP_DEFAULT, + configured: TOP_DEFAULT, + user: TOP_DEFAULT, effective: 1, temperature_mc: 0, - governor: COOLING_MAX, - budget: COOLING_MAX, + governor: pmp_initial, + budget: pmp_initial, sensor_error: None, updates: 0, sensor_errors: 0, @@ -200,15 +247,45 @@ impl Power { }) } + /// Adopts the board's firmware table, `rows` rows including off, before the first + /// governed publication: its top row is the governor's top state and configured + /// ceiling. The J773g table has eleven rows, so its top state is S10. + pub(crate) fn set_table(&mut self, rows: u32) { + let top = policy::top_of(rows); + self.top = top; + self.configured = top; + self.user = top; + self.utilization.top = top; + } + /// Reports a change of work in flight to the CLPC: the memory and fabric - /// floor follows it, not the GFX power state. + /// floor follows it, held for [`policy::CLPC_IDLE_HOLD_NS`] after drain. pub(crate) fn report_work(&mut self, in_flight: bool) { - if self.reported != Some(in_flight) { - self.clpc.set_active(in_flight); - self.reported = Some(in_flight); + if let Some(active) = self.clpc_hold.report(in_flight, now_ns()) { + self.clpc.set_active(active); } } + /// Immediately drops the CLPC memory and fabric floor (fail-stop or sleep). + pub(crate) fn release_clpc_now(&mut self) { + if self.clpc_hold.release_now() { + self.clpc.set_active(false); + } + } + + /// Whether the CLPC floor is held across an idle gap awaiting expiry. + pub(crate) fn clpc_holding(&self) -> bool { + self.clpc_hold.holding() + } + + /// Whether an active burst below the current ceiling can ramp early. + pub(crate) fn needs_ramp(&self, now: u64) -> bool { + let level = self.governor.max(self.budget).max(self.sample.backstop); + let ceiling = policy::cooling_ceiling(self.top, level); + let limit = policy::limit(self.configured, ceiling, self.user); + self.utilization.ramp_due(now, limit) + } + fn ceiling(&mut self, now: u64, idle: bool) -> (u32, bool) { if policy::read_due(self.last_sample_ns, now) { self.last_sample_ns = Some(now); @@ -216,12 +293,23 @@ impl Power { if self.sensor_error.is_some() { self.sensor_errors += 1; } + if !self.cooling.is_pmp { + self.zone_backstop.sample( + now, + self.sample.zone_seq, + self.sample.temperature_mc, + self.sample.zone_limits, + self.sensor_error.is_some(), + ); + self.zone_backstop.observe(now, self.sample.governor); + self.sample.backstop = self.zone_backstop.level(); + } self.temperature_mc = self.sample.temperature_mc; self.governor = self.sample.governor; self.budget = self.sample.budget; } let level = self.governor.max(self.budget).max(self.sample.backstop); - let ceiling = PSTATE_MAX - level.min(COOLING_MAX); + let ceiling = policy::cooling_ceiling(self.top, level); let limit = policy::limit(self.configured, ceiling, self.user); let decision = ( limit, @@ -251,6 +339,9 @@ impl Firmware { } let now = now_ns(); let idle = self.engine.flights.is_empty(); + if idle && self.power.clpc_hold.expire(now) { + self.power.clpc.set_active(false); + } let (limit, decision) = self.power.ceiling(now, idle); let target = self .power @@ -273,7 +364,7 @@ impl Firmware { return Ok(()); } let globals = self.init.globals.as_ref().ok_or(ENODEV)?; - for offset in globals::PSTATE_SELECTORS { + for offset in self.init.layout.pstate_selectors { globals.w32(offset, target * 100)?; } wmb(); diff --git a/drivers/gpu/drm/asahi/g16/power/policy.rs b/drivers/gpu/drm/asahi/g16/power/policy.rs index 0d127b8a5f8175..f901963045023b 100644 --- a/drivers/gpu/drm/asahi/g16/power/policy.rs +++ b/drivers/gpu/drm/asahi/g16/power/policy.rs @@ -6,11 +6,25 @@ //! Temperature decoding and regulation belong to the PMP provider and the //! shared C cooling policy. This module defines no temperature thresholds. -pub(crate) const PSTATE_MAX: u32 = 9; +/// Highest selector any M4 table can have: S9 on the ten-row J713/J604 tables, S10 on the +/// eleven-row J773g table. The board's own top state (`top`) bounds every request. +pub(crate) const PSTATE_MAX: u32 = 10; +/// Top state of the ten-row tables, used until the board's table is known. +pub(crate) const TOP_DEFAULT: u32 = 9; pub(crate) const COOLING_MAX: u32 = 8; pub(crate) const SAMPLE_NS: u64 = 5_000_000; -/// Utilization window of the governor. +/// Utilization window of the governor (slow decay cadence). pub(crate) const WINDOW_NS: u64 = 20_000_000; +/// Fast upward ramp window aligned with the PMP sampling cadence ([`SAMPLE_NS`], 5 ms = 1/4 +/// of [`WINDOW_NS`]) so active bursts step up before the full window closes without +/// overshooting on light periodic desktop frames. +pub(crate) const RAMP_WINDOW_NS: u64 = SAMPLE_NS; +/// Short idle hold before dropping the CLPC active hint between consecutive jobs. +/// `drivers/soc/apple/clpc.c` already holds DCS/fabric rails for `APPLE_CLPC_HOLD_MS` (32 ms) +/// on a `APPLE_CLPC_SAMPLE_MS` (4 ms) cadence; a 2 ms hold (half of `APPLE_CLPC_SAMPLE_MS`) +/// bridges sub-ms depth-1 inter-job gaps and avoids redundant `mod_delayed_work(..., 0)` +/// flushes without holding across 60 Hz (16.67 ms) or 120 Hz (8.33 ms) frame periods. +pub(crate) const CLPC_IDLE_HOLD_NS: u64 = 2_000_000; /// Lowest governed state. On the J713 S1-S3 draw under 0.1 W for a desktop /// load and S4 several times that; S3 runs at 2.4 times the clock of S1. pub(crate) const FLOOR: u32 = 3; @@ -21,11 +35,26 @@ pub(crate) fn read_due(last: Option, now: u64) -> bool { } /// Zero is not an unlimited selector in the firmware. Every published state -/// is 1..=9, bounded by the initialized Main table and the user ceiling. +/// is 1..=top, bounded by the initialized Main table and the user ceiling. pub(crate) fn limit(configured: u32, ceiling: u32, user: u32) -> u32 { ceiling.min(PSTATE_MAX).min(configured).min(user).max(1) } +/// The board's top state, from its firmware table's row count (row 0 is off). +pub(crate) fn top_of(rows: u32) -> u32 { + rows.saturating_sub(1).clamp(FLOOR, PSTATE_MAX) +} + +/// The cooling ceiling for a cooling `level` (0..=COOLING_MAX) under the board's `top` +/// state: one state per level below the top, and S1 at full cooling on every table. +pub(crate) fn cooling_ceiling(top: u32, level: u32) -> u32 { + if level >= COOLING_MAX { + 1 + } else { + top.saturating_sub(level).max(1) + } +} + /// Percentage of `window` ns the GPU was busy for. pub(crate) fn utilization(busy: u64, window: u64) -> u32 { if window == 0 { @@ -53,9 +82,10 @@ pub(crate) fn smooth(average: u32, util: u32, window: u64) -> u32 { /// The state to request from the `current` published one: up on the last /// window's utilization `util`, to the top state under heavy load, and down /// on the smoothed `average`, to the floor when idle. -pub(crate) fn demand(current: u32, util: u32, average: u32) -> u32 { +pub(crate) fn demand(current: u32, util: u32, average: u32, top: u32) -> u32 { + let top = top.clamp(FLOOR, PSTATE_MAX); let next = if util >= 70 { - PSTATE_MAX + top } else if util >= 40 { current.saturating_add(1) } else if average < 10 { @@ -65,17 +95,114 @@ pub(crate) fn demand(current: u32, util: u32, average: u32) -> u32 { } else { current }; - next.clamp(FLOOR, PSTATE_MAX) + next.clamp(FLOOR, top) +} + +/// Fast upward-only demand step for partial burst windows ([`RAMP_WINDOW_NS`]): +/// matches [`demand`]'s upward thresholds (`>= 70%` -> `top`, `>= 40%` -> `+1`) and +/// never decays, so light periodic frames cannot pump to `top` while sustained bursts +/// still reach `top` within one 5 ms sample. +pub(crate) fn ramp_demand(current: u32, util: u32, top: u32) -> u32 { + let top = top.clamp(FLOOR, PSTATE_MAX); + let next = if util >= 70 { + top + } else if util >= 40 { + current.saturating_add(1) + } else { + current + }; + next.max(current).clamp(FLOOR, top) +} + +/// CLPC active-floor hysteresis: keeps the memory and fabric floor raised for +/// [`CLPC_IDLE_HOLD_NS`] after flights drain so short `d=1` inter-job gaps do +/// not drop and re-raise CLPC on every submission. +pub(crate) struct ClpcHold { + reported: Option, + idle_since: Option, +} + +impl ClpcHold { + pub(crate) const fn new() -> Self { + Self { + reported: None, + idle_since: None, + } + } + + /// Updates work-in-flight state. Returns `Some(active)` only when the + /// CLPC provider must transition immediately. + pub(crate) fn report(&mut self, in_flight: bool, now: u64) -> Option { + if in_flight { + self.idle_since = None; + if self.reported != Some(true) { + self.reported = Some(true); + return Some(true); + } + return None; + } + if self.reported == Some(true) { + self.idle_since.get_or_insert(now); + None + } else if self.reported.is_none() { + self.reported = Some(false); + Some(false) + } else { + None + } + } + + /// Releases a held CLPC floor once [`CLPC_IDLE_HOLD_NS`] has elapsed idle. + pub(crate) fn expire(&mut self, now: u64) -> bool { + if self.reported == Some(true) + && self + .idle_since + .is_some_and(|since| now.wrapping_sub(since) >= CLPC_IDLE_HOLD_NS) + { + self.idle_since = None; + self.reported = Some(false); + return true; + } + false + } + + /// Immediately drops the CLPC floor (fail-stop or system sleep). + pub(crate) fn release_now(&mut self) -> bool { + self.idle_since = None; + if self.reported != Some(false) { + self.reported = Some(false); + true + } else { + false + } + } + + /// Whether the CLPC floor is currently being held across an idle gap. + pub(crate) fn holding(&self) -> bool { + self.reported == Some(true) && self.idle_since.is_some() + } } +/// Maximum inter-flight idle gap bridged for active-burst GPU demand. +/// Matches [`CLPC_IDLE_HOLD_NS`] (2 ms): back-to-back `d=1` CPU-recording bursts +/// sit well below 2 ms while 60 Hz (16.67 ms) and 120 Hz (8.33 ms) desktop frames +/// exceed it cleanly and stay at [`FLOOR`]. +const BURST_GAP_NS: u64 = CLPC_IDLE_HOLD_NS; +/// Consecutive sub-`BURST_GAP_NS` turnarounds required before bridging short gaps. +const BURST_STREAK_ON: u32 = 4; + /// Busy-time accounting over the governor's windows. The engine reports each /// publication and drain; each power service closes the window once it is due. pub(crate) struct Governor { /// The requested state and the smoothed utilization. pub(crate) demand: u32, pub(crate) average: u32, + /// The board's top state. + pub(crate) top: u32, window_ns: u64, busy_since: Option, + idle_since: Option, + burst_streak: u32, busy_ns: u64, } @@ -84,21 +211,38 @@ impl Governor { Self { demand: FLOOR, average: 0, + top: TOP_DEFAULT, window_ns: 0, busy_since: None, + idle_since: None, + burst_streak: 0, busy_ns: 0, } } /// The engine published work; it stays busy until [`Governor::idle`]. pub(crate) fn busy(&mut self, now: u64) { - self.busy_since.get_or_insert(now); + if self.busy_since.is_none() { + if let Some(idle_at) = self.idle_since.take() { + let gap = now.saturating_sub(idle_at); + if gap < BURST_GAP_NS { + self.burst_streak = self.burst_streak.saturating_add(1); + if self.burst_streak >= BURST_STREAK_ON { + self.busy_ns = self.busy_ns.saturating_add(gap); + } + } else { + self.burst_streak = 0; + } + } + self.busy_since = Some(now); + } } /// The engine drained. pub(crate) fn idle(&mut self, now: u64) { if let Some(since) = self.busy_since.take() { self.busy_ns += now.saturating_sub(since); + self.idle_since = Some(now); } } @@ -108,12 +252,34 @@ impl Governor { self.busy_since.is_none() && self.demand > FLOOR } + /// Whether a busy engine below its ceiling has enough partial-window + /// utilization to step up before the full [`WINDOW_NS`] window closes. + pub(crate) fn ramp_due(&self, now: u64, limit: u32) -> bool { + let cap = self.top.min(limit); + if self.demand >= cap || self.busy_since.is_none() { + return false; + } + let window = now.wrapping_sub(self.window_ns); + if window < RAMP_WINDOW_NS { + return false; + } + let active = self.busy_since.map_or(0, |s| now.saturating_sub(s)); + let util = utilization(self.busy_ns.saturating_add(active), window); + ramp_demand(self.demand, util, self.top).min(limit) > self.demand + } + /// Closes the window once it is due and returns the state to publish /// under the ceiling `limit`; `busy` is whether flights are outstanding. pub(crate) fn govern(&mut self, now: u64, limit: u32, busy: bool) -> u32 { // Recovery can drop flights without a drain. if !busy { self.idle(now); + if self + .idle_since + .is_some_and(|at| now.saturating_sub(at) >= BURST_GAP_NS) + { + self.burst_streak = 0; + } } let window = now.wrapping_sub(self.window_ns); if window >= WINDOW_NS { @@ -123,18 +289,185 @@ impl Governor { } let util = utilization(self.busy_ns, window); self.average = smooth(self.average, util, window); - self.demand = demand(self.demand.min(limit), util, self.average); + self.demand = demand(self.demand.min(limit), util, self.average, self.top); self.window_ns = now; self.busy_ns = 0; + } else if busy && window >= RAMP_WINDOW_NS && self.demand < self.top.min(limit) { + let active = self.busy_since.map_or(0, |since| now.saturating_sub(since)); + let util = utilization(self.busy_ns.saturating_add(active), window); + let next = ramp_demand(self.demand.min(limit), util, self.top).min(limit); + if next > self.demand { + self.demand = next; + } } self.demand.min(limit) } } +/// Startup/fault confirmation cadence (minimum spacing across 10 distinct sensor polls) +/// and gradual cooling-release step interval. +pub(crate) const ZONE_CONFIRM_NS: u64 = 20_000_000; +pub(crate) const ZONE_CONFIRM_READS: u32 = 10; +pub(crate) const ZONE_RELEASE_NS: u64 = 200_000_000; + +/// Machine-supplied thermal-zone trip limits (millidegrees Celsius) read from the kernel +/// thermal zone (`passive`/`active` trip with hysteresis, and `hot`/`critical` trip). +/// If the machine provides no valid limits, [`ZoneBackstop`] fails closed at [`COOLING_MAX`] (S1). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct ZoneLimits { + pub(crate) release_mc: i64, + pub(crate) hot_mc: i64, + pub(crate) critical_mc: i64, +} + +impl ZoneLimits { + pub(crate) const fn is_valid(&self) -> bool { + self.release_mc > 0 && self.release_mc <= self.hot_mc && self.critical_mc > self.hot_mc + } +} + +/// Cooling level for a measured thermal-zone die temperature against machine-supplied trip +/// limits: 0 below `hot_mc`, 1..=7 linearly across `hot_mc..critical_mc`, and [`COOLING_MAX`] +/// at or above `critical_mc` (or whenever `limits` are invalid). +pub(crate) fn zone_heat_level(mc: i64, limits: ZoneLimits) -> u32 { + if !limits.is_valid() { + return COOLING_MAX; + } + if mc < limits.hot_mc { + 0 + } else if mc >= limits.critical_mc { + COOLING_MAX + } else { + let span = limits.critical_mc - limits.hot_mc; + let delta = mc - limits.hot_mc; + let steps = (COOLING_MAX - 1) as i64; + (((delta * steps) / span) as u32 + 1).min(COOLING_MAX) + } +} + +/// Fail-closed thermal backstop driven by kernel SoC die thermal zones when a GPU DT node +/// has no `apple,pmp` telemetry bridge. Starts at [`COOLING_MAX`] (S1), requires +/// [`ZONE_CONFIRM_READS`] distinct fresh sensor polls with valid machine-supplied trip limits +/// before stepping down gradually, and immediately clamps back to [`COOLING_MAX`] on missing, +/// stale, unconfigured, or critical readings. +pub(crate) struct ZoneBackstop { + level: u32, + hard: bool, + good_reads: u32, + last_seq: u64, + good_ns: u64, + release_ns: u64, +} + +impl ZoneBackstop { + pub(crate) const fn new() -> Self { + Self { + level: COOLING_MAX, + hard: true, + good_reads: 0, + last_seq: 0, + good_ns: 0, + release_ns: 0, + } + } + + pub(crate) const fn level(&self) -> u32 { + self.level + } + + /// Incorporates one sampled temperature (millidegrees Celsius), poller sequence `seq`, + /// machine-supplied `limits`, or sensor `error` at `now`. + pub(crate) fn sample( + &mut self, + now: u64, + seq: u64, + mc: i64, + limits: Option, + error: bool, + ) -> u32 { + let Some(limits) = limits.filter(ZoneLimits::is_valid) else { + self.level = COOLING_MAX; + self.hard = true; + self.good_reads = 0; + if seq != 0 { + self.last_seq = seq; + } + self.good_ns = now; + self.release_ns = now; + return self.level; + }; + + if error || seq == 0 || mc <= 0 || mc >= limits.critical_mc { + self.level = COOLING_MAX; + self.hard = true; + self.good_reads = 0; + if seq != 0 { + self.last_seq = seq; + } + self.good_ns = now; + self.release_ns = now; + return self.level; + } + + let fresh = seq != self.last_seq; + if self.hard { + if mc < limits.hot_mc { + let due = self.good_reads == 0 || now.wrapping_sub(self.good_ns) >= ZONE_CONFIRM_NS; + if fresh && due { + self.last_seq = seq; + self.good_ns = now; + self.good_reads = self.good_reads.saturating_add(1).min(ZONE_CONFIRM_READS); + } + if self.good_reads >= ZONE_CONFIRM_READS { + self.hard = false; + } + } else { + self.last_seq = seq; + self.good_reads = 0; + self.good_ns = now; + } + self.release_ns = now; + if self.hard { + return self.level; + } + } + + if fresh { + self.last_seq = seq; + } + let target = zone_heat_level(mc, limits); + if target > self.level { + self.level = target; + self.release_ns = now; + } else if fresh + && mc < limits.release_mc + && now.wrapping_sub(self.release_ns) >= ZONE_RELEASE_NS + { + self.level = self.level.saturating_sub(1); + self.release_ns = now; + } else if mc >= limits.release_mc { + self.release_ns = now; + } + self.level + } + + /// Retains a cooling-device governor restriction inside the gradual release envelope. + pub(crate) fn observe(&mut self, now: u64, governor: u32) { + let clamped = governor.min(COOLING_MAX); + if clamped > self.level { + self.level = clamped; + self.release_ns = now; + } + } +} + #[cfg(test)] mod tests { use super::*; + /// The ten-row tables' top state; the J773g cases name theirs. + const TOP: u32 = TOP_DEFAULT; + #[test] fn provider_sampling_is_independent_of_completion_polling() { assert!(read_due(None, 0)); @@ -146,7 +479,7 @@ mod tests { #[test] fn initialized_selectors_and_user_caps_bound_every_request() { - assert_eq!(COOLING_MAX, PSTATE_MAX - 1); + assert_eq!(COOLING_MAX, TOP_DEFAULT - 1); for configured in [0, 1, 7, 9, 10, u32::MAX] { for ceiling in [0, 1, 5, 9, 10, u32::MAX] { for user in [0, 1, 3, 9, 10, u32::MAX] { @@ -180,7 +513,7 @@ mod tests { assert_eq!(smooth(u32::MAX, u32::MAX, w), 100); let mut average = 100; let mut windows = 0; - while demand(PSTATE_MAX, 0, average) != FLOOR { + while demand(TOP, 0, average, TOP) != FLOOR { average = smooth(average, 0, w); windows += 1; } @@ -189,23 +522,23 @@ mod tests { #[test] fn demand_rises_fast_and_falls_on_the_average() { - assert_eq!(demand(FLOOR, 100, 0), PSTATE_MAX); - assert_eq!(demand(FLOOR, 70, 0), PSTATE_MAX); - assert_eq!(demand(4, 50, 0), 5); - assert_eq!(demand(PSTATE_MAX, 50, 0), PSTATE_MAX); + assert_eq!(demand(FLOOR, 100, 0, TOP), TOP); + assert_eq!(demand(FLOOR, 70, 0, TOP), TOP); + assert_eq!(demand(4, 50, 0, TOP), 5); + assert_eq!(demand(TOP, 50, 0, TOP), TOP); // A short dip under a busy average holds the state. - assert_eq!(demand(PSTATE_MAX, 5, 80), PSTATE_MAX); - assert_eq!(demand(6, 30, 30), 6); - assert_eq!(demand(6, 20, 20), 5); - assert_eq!(demand(PSTATE_MAX, 0, 5), FLOOR); + assert_eq!(demand(TOP, 5, 80, TOP), TOP); + assert_eq!(demand(6, 30, 30, TOP), 6); + assert_eq!(demand(6, 20, 20, TOP), 5); + assert_eq!(demand(TOP, 0, 5, TOP), FLOOR); // A light 60 fps load near 25% busy settles on the floor. - assert_eq!(demand(FLOOR, 25, 24), FLOOR); - assert_eq!(demand(1, 30, 30), FLOOR); - for current in [0, 1, FLOOR, 7, PSTATE_MAX, u32::MAX] { + assert_eq!(demand(FLOOR, 25, 24, TOP), FLOOR); + assert_eq!(demand(1, 30, 30, TOP), FLOOR); + for current in [0, 1, FLOOR, 7, TOP, u32::MAX] { for util in [0, 20, 50, 70, 100, u32::MAX] { for average in [0, 9, 20, 30, 100, u32::MAX] { - let next = demand(current, util, average); - assert!((FLOOR..=PSTATE_MAX).contains(&next)); + let next = demand(current, util, average, TOP); + assert!((FLOOR..=TOP).contains(&next)); } } } @@ -216,7 +549,7 @@ mod tests { /// A governor whose first window closed idle at `T`. fn started() -> Governor { let mut governor = Governor::new(); - assert_eq!(governor.govern(T, PSTATE_MAX, false), FLOOR); + assert_eq!(governor.govern(T, TOP, false), FLOOR); assert_eq!(governor.average, 0); governor } @@ -232,10 +565,10 @@ mod tests { // A drain without a publication adds nothing. g.idle(T + 9_000_000); // A service before the window is due changes nothing. - assert_eq!(g.govern(T + w - 1, PSTATE_MAX, false), FLOOR); + assert_eq!(g.govern(T + w - 1, TOP, false), FLOOR); assert_eq!(g.average, 0); // 5 ms of 20 ms: 25%, a quarter of it in the average. - assert_eq!(g.govern(T + w, PSTATE_MAX, false), FLOOR); + assert_eq!(g.govern(T + w, TOP, false), FLOOR); assert_eq!(g.average, 6); } @@ -246,13 +579,13 @@ mod tests { g.busy(T); assert!(!g.decaying()); // Busy through the window: all of it counts, and the load gets the top state. - assert_eq!(g.govern(T + w, PSTATE_MAX, true), PSTATE_MAX); + assert_eq!(g.govern(T + w, TOP, true), TOP); assert_eq!(g.average, 25); // Busy above the floor: the engine's own polls govern it, not the idle re-arm. assert!(!g.decaying()); // The span carries on from the window's end, not from its publication. g.idle(T + w + w / 2); - assert_eq!(g.govern(T + 2 * w, PSTATE_MAX, false), PSTATE_MAX); + assert_eq!(g.govern(T + 2 * w, TOP, false), TOP); assert_eq!(g.average, (3 * 25 + 50) / 4); } @@ -263,15 +596,15 @@ mod tests { g.busy(T); // Recovery dropped the flights and reported no drain: the next service, // finding none outstanding, ends the span there. - assert_eq!(g.govern(T + w / 2, PSTATE_MAX, false), FLOOR); + assert_eq!(g.govern(T + w / 2, TOP, false), FLOOR); assert!(!g.decaying()); - assert_eq!(g.govern(T + w, PSTATE_MAX, false), FLOOR + 1); + assert_eq!(g.govern(T + w, TOP, false), FLOOR + 1); assert_eq!(g.average, 50 / 4); // Idle above the floor: the poll keeps coming back. assert!(g.decaying()); // A late drain report counts nothing more. g.idle(T + w + 1); - assert_eq!(g.govern(T + 2 * w, PSTATE_MAX, false), FLOOR); + assert_eq!(g.govern(T + 2 * w, TOP, false), FLOOR); assert!(!g.decaying()); } @@ -281,7 +614,7 @@ mod tests { let mut g = started(); g.busy(T); for n in 1..=8 { - assert_eq!(g.govern(T + n * w, PSTATE_MAX, true), PSTATE_MAX); + assert_eq!(g.govern(T + n * w, TOP, true), TOP); } let mut now = T + 8 * w; g.idle(now); @@ -289,21 +622,21 @@ mod tests { let mut passes = 0; while g.decaying() { now += w; - g.govern(now, PSTATE_MAX, false); + g.govern(now, TOP, false); passes += 1; assert!(passes <= 10); } assert_eq!(g.demand, FLOOR); assert!(passes > 1); // At the floor nothing re-arms, and a later service holds it there. - assert_eq!(g.govern(now + 10 * w, PSTATE_MAX, false), FLOOR); + assert_eq!(g.govern(now + 10 * w, TOP, false), FLOOR); assert!(!g.decaying()); // A long sleep between passes restarts the average and drops at once. let mut g = started(); g.busy(T); - assert_eq!(g.govern(T + w, PSTATE_MAX, true), PSTATE_MAX); + assert_eq!(g.govern(T + w, TOP, true), TOP); g.idle(T + w); - assert_eq!(g.govern(T + 6 * w, PSTATE_MAX, false), FLOOR); + assert_eq!(g.govern(T + 6 * w, TOP, false), FLOOR); assert!(!g.decaying()); } @@ -318,7 +651,7 @@ mod tests { assert_eq!(g.govern(T + 2 * w, 1, true), 1); assert_eq!(g.govern(T + 2 * w + 1, 2, true), 2); // Released, the load's request applies at once. - assert_eq!(g.govern(T + 2 * w + 2, PSTATE_MAX, true), PSTATE_MAX); + assert_eq!(g.govern(T + 2 * w + 2, TOP, true), TOP); // Idle under a ceiling below the floor: one window gives it all back. g.idle(T + 3 * w); assert!(g.decaying()); @@ -326,4 +659,367 @@ mod tests { assert_eq!(g.demand, FLOOR); assert!(!g.decaying()); } + + #[test] + fn the_board_table_sets_the_top_state() { + // J713/J604: ten rows, top S9. J773g: eleven rows, top S10 (1578 MHz on the Mac mini). + assert_eq!(top_of(10), 9); + assert_eq!(top_of(11), 10); + assert_eq!(top_of(12), PSTATE_MAX); + assert_eq!(top_of(0), FLOOR); + for top in [9, 10] { + assert_eq!(demand(FLOOR, 100, 0, top), top); + assert_eq!(demand(top, 50, 80, top), top); + assert_eq!(demand(top, 0, 5, top), FLOOR); + let mut g = Governor::new(); + g.top = top; + assert_eq!(g.govern(T, top, false), FLOOR); + g.busy(T); + assert_eq!(g.govern(T + WINDOW_NS, top, true), top); + // A ceiling still bounds the request. + assert_eq!(g.govern(T + 2 * WINDOW_NS, top - 1, true), top - 1); + } + } + + #[test] + fn cooling_keeps_one_state_per_level_and_s1_at_full_cooling() { + // Ten-row tables: unchanged, 9 - level, S1 at level 8. + for level in 0..=COOLING_MAX { + assert_eq!(cooling_ceiling(9, level), 9 - level); + } + // Eleven rows: S10..S3 for levels 0..7, S1 at full cooling. + assert_eq!(cooling_ceiling(10, 0), 10); + assert_eq!(cooling_ceiling(10, 7), 3); + assert_eq!(cooling_ceiling(10, COOLING_MAX), 1); + assert_eq!(cooling_ceiling(10, u32::MAX), 1); + assert_eq!(limit(10, cooling_ceiling(10, 0), 10), 10); + } + + #[test] + fn fast_ramp_raises_active_bursts_while_preserving_decay_and_cooling_ceiling() { + let mut g = started(); + g.top = PSTATE_MAX; + // Simulate d=1 back-to-back burst (80% busy) from FLOOR: reaches S10 at 5 ms. + let mut t = T; + for _ in 0..20 { + g.busy(t); + g.idle(t + 200_000); + t += 250_000; + } + assert_eq!(t, T + RAMP_WINDOW_NS); + g.busy(t); + assert!(g.ramp_due(t, PSTATE_MAX)); + assert_eq!(g.govern(t, PSTATE_MAX, true), PSTATE_MAX); + assert!(!g.ramp_due(t, PSTATE_MAX)); + + // Moderate 50% active load steps +1 (aligned with demand()), never jumps to top + // and never decays before the full 20 ms window. + let mut g = started(); + g.top = PSTATE_MAX; + g.busy(T); + g.idle(T + 2_500_000); + g.busy(T + RAMP_WINDOW_NS); + assert!(g.ramp_due(T + RAMP_WINDOW_NS, PSTATE_MAX)); + assert_eq!(g.govern(T + RAMP_WINDOW_NS, PSTATE_MAX, true), FLOOR + 1); + g.idle(T + RAMP_WINDOW_NS); + assert_eq!(g.govern(T + WINDOW_NS - 1, PSTATE_MAX, false), FLOOR + 1); + + // Light 60 Hz compositor frames (2.5 ms busy every 16.67 ms -> 15% over 20 ms) + // never pump to top and settle back at FLOOR. + let mut g = started(); + g.top = PSTATE_MAX; + let mut now = T; + for _ in 0..10 { + g.busy(now); + assert!(g.govern(now + 2_500_000, PSTATE_MAX, true) <= FLOOR + 1); + g.idle(now + 2_500_000); + now += 16_666_667; + let state = g.govern(now, PSTATE_MAX, false); + assert!(state <= FLOOR + 1); + } + assert_eq!(g.demand, FLOOR); + + // Thermal cooling ceiling clamps stored demand too: relaxing by one level steps + // cleanly to cap + 1 rather than jumping straight to top. + let mut g = started(); + g.top = PSTATE_MAX; + g.busy(T); + let cap = cooling_ceiling(PSTATE_MAX, 5); + assert_eq!(g.govern(T + RAMP_WINDOW_NS, cap, true), cap); + assert_eq!(g.demand, cap); + assert!(!g.ramp_due(T + RAMP_WINDOW_NS, cap)); + // Even if the ceiling opens to TOP right after the capped ramp, stored demand + // stays at `cap` until new utilization above `cap` is observed. + g.idle(T + RAMP_WINDOW_NS + 1); + assert_eq!(g.govern(T + RAMP_WINDOW_NS + 2, PSTATE_MAX, false), cap); + assert_eq!(g.demand, cap); + } + + #[test] + fn clpc_hold_keeps_floor_across_short_gaps_and_releases_on_expiry_or_reset() { + let mut hold = ClpcHold::new(); + assert!(!hold.holding()); + assert_eq!(hold.report(true, T), Some(true)); + assert!(!hold.holding()); + // Short idle gap (< 2 ms): CLPC stays active without toggling. + assert_eq!(hold.report(false, T + 200_000), None); + assert!(hold.holding()); + assert!(!hold.expire(T + 200_000 + CLPC_IDLE_HOLD_NS - 1)); + assert_eq!(hold.report(true, T + 500_000), None); + assert!(!hold.holding()); + // Full 2 ms idle expires and releases the CLPC floor (well below 60/120 Hz frames). + assert_eq!(hold.report(false, T + 1_000_000), None); + assert!(hold.holding()); + assert!(hold.expire(T + 1_000_000 + CLPC_IDLE_HOLD_NS)); + assert!(!hold.holding()); + assert!(!hold.expire(T + 1_000_000 + 2 * CLPC_IDLE_HOLD_NS)); + // Fail-stop / sleep drops CLPC immediately regardless of hold timer. + assert_eq!(hold.report(true, T + 30_000_000), Some(true)); + assert_eq!(hold.report(false, T + 30_100_000), None); + assert!(hold.holding()); + assert!(hold.release_now()); + assert!(!hold.holding()); + assert!(!hold.release_now()); + } + + #[test] + fn active_burst_demand_ramps_low_duty_d1_while_preserving_120hz_and_idle_decay() { + // Low-duty d=1 CPU-recording-bound burst: 170 us GPU + 600 us host gap (22% raw duty, + // < 2 ms turnaround). Bridges short refill gaps after BURST_STREAK_ON and ramps to top. + let mut g = started(); + g.top = PSTATE_MAX; + let mut t = T; + for _ in 0..8 { + g.busy(t); + g.idle(t + 170_000); + t += 770_000; + } + assert!(t - T >= RAMP_WINDOW_NS); + g.busy(t); + assert!(g.ramp_due(t, PSTATE_MAX)); + assert_eq!(g.govern(t, PSTATE_MAX, true), PSTATE_MAX); + + // Once idle, burst streak resets after 2 ms and demand decays cleanly back to FLOOR. + g.idle(t + 170_000); + let mut now = t + 170_000; + for _ in 0..20 { + now += WINDOW_NS; + let _ = g.govern(now, PSTATE_MAX, false); + } + assert_eq!(g.demand, FLOOR); + assert!(!g.decaying()); + + // 120 Hz desktop pacing (2 ms busy every 8.33 ms -> 6.33 ms gap >= 2 ms) never bridges + // gaps and stays bounded at FLOOR. + let mut g = started(); + g.top = PSTATE_MAX; + let mut now = T; + for _ in 0..16 { + g.busy(now); + assert!(g.govern(now + 2_000_000, PSTATE_MAX, true) <= FLOOR + 1); + g.idle(now + 2_000_000); + now += 8_333_333; + assert!(g.govern(now, PSTATE_MAX, false) <= FLOOR + 1); + } + assert_eq!(g.demand, FLOOR); + } + + #[test] + fn zone_backstop_starts_fail_closed_releases_gradually_and_clamps_on_heat_or_fault() { + let limits = ZoneLimits { + release_mc: 75_000, + hot_mc: 80_000, + critical_mc: 94_000, + }; + let mut z = ZoneBackstop::new(); + assert_eq!(z.level(), COOLING_MAX); + assert_eq!(cooling_ceiling(8, z.level()), 1); + + // Missing or invalid machine trip limits keep the GPU clamped at S1 forever. + for i in 1..=20u64 { + assert_eq!( + z.sample(T + i * ZONE_CONFIRM_NS, i, 55_000, None, false), + COOLING_MAX + ); + } + let bad_limits = ZoneLimits { + release_mc: 80_000, + hot_mc: 80_000, + critical_mc: 80_000, + }; + assert_eq!( + z.sample(T + 500_000_000, 21, 55_000, Some(bad_limits), false), + COOLING_MAX + ); + + // Sensor errors or non-positive readings keep the GPU clamped at S1. + assert_eq!( + z.sample(T + 1_000_000_000, 22, 0, Some(limits), true), + COOLING_MAX + ); + assert_eq!( + z.sample(T + 1_020_000_000, 23, 0, Some(limits), false), + COOLING_MAX + ); + + // Repeated reads of a single cached temperature (unchanged seq) CANNOT satisfy + // startup confirmation even as timestamps advance past 10 * ZONE_CONFIRM_NS. + let base = T + 2_000_000_000; + let cached_seq = 100u64; + for step in 0..50u64 { + assert_eq!( + z.sample( + base + step * ZONE_CONFIRM_NS, + cached_seq, + 55_000, + Some(limits), + false + ), + COOLING_MAX + ); + } + // Advancing past release interval with the same cached seq still stays at S1. + assert_eq!( + z.sample( + base + 60 * ZONE_CONFIRM_NS + ZONE_RELEASE_NS, + cached_seq, + 55_000, + Some(limits), + false + ), + COOLING_MAX + ); + + // 9 more distinct fresh sensor polls complete the 10-poll startup confirmation. + let fresh_base = base + 60 * ZONE_CONFIRM_NS + 2 * ZONE_RELEASE_NS; + for step in 1..ZONE_CONFIRM_READS as u64 { + assert_eq!( + z.sample( + fresh_base + step * ZONE_CONFIRM_NS, + cached_seq + step, + 55_000, + Some(limits), + false + ), + COOLING_MAX + ); + } + // Gradual release: one cooling level per fresh poll every 200 ms below release_mc. + let confirmed = fresh_base + (ZONE_CONFIRM_READS as u64 - 1) * ZONE_CONFIRM_NS; + let mut seq = cached_seq + ZONE_CONFIRM_READS as u64; + assert_eq!( + z.sample(confirmed + ZONE_RELEASE_NS - 1, seq, 55_000, Some(limits), false), + COOLING_MAX + ); + for step in 1..=COOLING_MAX as u64 { + seq += 1; + assert_eq!( + z.sample( + confirmed + step * ZONE_RELEASE_NS, + seq, + 55_000, + Some(limits), + false + ), + COOLING_MAX - step as u32 + ); + } + assert_eq!(z.level(), 0); + assert_eq!(cooling_ceiling(8, z.level()), 8); + + // Progressive heat throttling across hot_mc..critical_mc, hard clamp at >= critical_mc. + let hot_t = confirmed + 10 * ZONE_RELEASE_NS; + seq += 1; + assert_eq!(z.sample(hot_t, seq, 79_999, Some(limits), false), 0); + seq += 1; + assert_eq!(z.sample(hot_t + 10_000_000, seq, 80_000, Some(limits), false), 1); + seq += 1; + assert_eq!(z.sample(hot_t + 20_000_000, seq, 86_000, Some(limits), false), 4); + // Holding between release_mc and hot_mc does not release cooling. + seq += 1; + assert_eq!( + z.sample(hot_t + 500_000_000, seq, 75_000, Some(limits), false), + 4 + ); + seq += 1; + assert_eq!( + z.sample(hot_t + 1_000_000_000, seq, 79_000, Some(limits), false), + 4 + ); + // Critical heat immediately returns to hard COOLING_MAX (S1). + seq += 1; + assert_eq!( + z.sample( + hot_t + 1_010_000_000, + seq, + limits.critical_mc, + Some(limits), + false + ), + COOLING_MAX + ); + assert_eq!(cooling_ceiling(8, z.level()), 1); + + // Different machine-supplied trip limits govern dynamically without code constants. + let higher_limits = ZoneLimits { + release_mc: 85_000, + hot_mc: 90_000, + critical_mc: 104_000, + }; + let mut z2 = ZoneBackstop::new(); + for step in 1..=ZONE_CONFIRM_READS as u64 { + z2.sample( + base + step * ZONE_CONFIRM_NS, + step, + 84_000, + Some(higher_limits), + false, + ); + } + let c2 = base + (ZONE_CONFIRM_READS as u64) * ZONE_CONFIRM_NS; + for step in 1..=COOLING_MAX as u64 { + z2.sample( + c2 + step * ZONE_RELEASE_NS, + ZONE_CONFIRM_READS as u64 + step, + 84_000, + Some(higher_limits), + false, + ); + } + assert_eq!(z2.level(), 0); + // 89 C is still below higher_limits.hot_mc (90 C). + assert_eq!( + z2.sample( + c2 + 9 * ZONE_RELEASE_NS, + 100, + 89_000, + Some(higher_limits), + false + ), + 0 + ); + // Governor observation is retained in the release envelope. + z2.observe(c2 + 9 * ZONE_RELEASE_NS, 5); + assert_eq!(z2.level(), 5); + assert_eq!( + z2.sample( + c2 + 9 * ZONE_RELEASE_NS + 1, + 101, + 84_000, + Some(higher_limits), + false + ), + 5 + ); + assert_eq!( + z2.sample( + c2 + 10 * ZONE_RELEASE_NS, + 102, + 84_000, + Some(higher_limits), + false + ), + 4 + ); + } } diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 41da5b94c7c500..81d261a65042cb 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -3,10 +3,19 @@ //! Logical queues: `crate::queue::Queue` for G16. //! //! Logical queues own no firmware state: they are independent scheduling entities over the one -//! shared graph, executed in one total order across queues and VMs. QUEUE_CREATE validates +//! shared graph, sharing the device's compute and render engines across queues and VMs. A +//! per-file host credit bounds each open DRM file's live logical queues to the advertised +//! `MAX_QUEUES` (ENOSPC when full) while `file.rs`'s `queue_share::Share` bounds multi-file +//! hoarding per process, so one client cannot exhaust logical-queue creation for another +//! process (such as a compositor). It reserves no hardware graph or execution context. +//! QUEUE_CREATE validates //! `usc_exec_base` (4 GiB aligned, the window inside the user range) and refuses a failed VM or -//! GPU (EIO); HIGH/REALTIME are refused by the shared `file.rs`. Ray-query scratch layouts are -//! refused by the shared default `reserve_render_scs` (RENDER_RAY_QUERY is never advertised). +//! GPU (EIO); HIGH/REALTIME are refused by the shared `file.rs`. `render_scs_layout` (the +//! largest ray-query scratch layouts of the queue's render stages) is reserved at creation: +//! EINVAL for a malformed layout, E2BIG beyond the largest SCS-capable UMA pool; a render +//! whose scratch exceeds the reservation is refused (EINVAL), as on the M4 Pro. The +//! reservation also sizes the SCS-capable render pools its VM creates for it +//! ([`super::rt::pool_seeds`]). //! //! QUEUE_DESTROY (dropping the queue) drains: the scheduler entity is torn down first, which //! waits (killable) until every accepted job has been handed to the engine; the engine then runs @@ -25,11 +34,11 @@ //! ordinal, or depending on its failed prefix, cannot execute. The VM remains usable. use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; -use kernel::{dma_fence::Fence, prelude::*, sync::Arc, uapi, xarray}; +use kernel::{prelude::*, sync::Arc, uapi, xarray}; use super::{ command::{self, USC_WINDOW}, - fence::{Syncs, Timeline}, + fence::{InputFences, Syncs, Timeline}, hw, job::{Job, Scheduler}, params, @@ -43,7 +52,7 @@ pub(crate) struct QueueState { /// Host priority: `DRM_ASAHI_PRIORITY_REALTIME - priority` as `file.rs` passes it (MEDIUM 2, /// LOW 3; `file.rs` refuses HIGH and REALTIME). Smaller is served first. pub(crate) priority: u32, - /// Completed stage time of the DRM file that created this queue. + /// Completed stage time of the DRM file that created this queue (deduplicated per file). pub(crate) usage: Arc, /// USC executable window base. pub(crate) usc_base: u64, @@ -55,10 +64,21 @@ pub(crate) struct QueueState { /// Exact successful firmware receipts, independently for render and compute. These /// survive aggregate-fence publication and never advance on aborted/failed commands. pub(crate) completed: [AtomicU64; 2], + /// Out-of-order full compute receipts strictly above `completed[COMPUTE] + 1` (bit `k` + /// records ordinal `completed[COMPUTE] + 2 + k`), enabling concurrent 2-pipe completion. + pub(crate) compute_ooo: AtomicU64, + /// Published command frontier per engine. The firmware runs each queue pipe in + /// publication order, each command to its Finalize, so a compute command may follow its + /// published (not yet retired) compute predecessors (on the same pipe or via a cross-pipe + /// barrier). + pub(crate) published: [AtomicU64; 2], /// Owned-job counts at the queue's last 32 arrivals (compute horizon ahead), recorded by the /// engine when a job arrives. pub(crate) owned: [AtomicU32; 32], pub(crate) owned_index: AtomicU32, + /// EWMA of retired per-command CDM GPU execution duration (microseconds) for adaptive + /// 1-pipe affinity vs 2-pipe heavy compute fanout. + pub(crate) compute_ewma_us: AtomicU32, } impl QueueState { @@ -87,6 +107,62 @@ impl QueueState { } Ok(()) } + + /// Whether any accepted ordinal of `engine` at or before `seq` was cancelled. + pub(crate) fn cancelled_through(&self, engine: usize, seq: u64) -> Result { + let first = self.cancelled_at[engine].load(Ordering::Acquire); + if first != 0 && first <= seq { + return Err(ECANCELED); + } + Ok(()) + } + + /// Whether compute ordinal `seq` already has a full successful firmware receipt, either + /// at or below the contiguous `completed[COMPUTE]` frontier or recorded in `compute_ooo`. + pub(crate) fn is_compute_retired(&self, seq: u64) -> bool { + let completed = self.completed[command::COMPUTE].load(Ordering::Acquire); + if seq <= completed { + return true; + } + let shift = seq.wrapping_sub(completed).wrapping_sub(2); + shift < 64 && (self.compute_ooo.load(Ordering::Acquire) & (1u64 << shift)) != 0 + } + + /// Updates the lock-free EWMA of recent retired per-command CDM GPU execution duration + /// (microseconds) for this queue using a symmetric 50% step so transitions between light + /// and heavy compute streams adapt within 2-3 completions. + pub(crate) fn note_compute_us(&self, us: u32) { + let us = us.clamp(1, 100_000); + let prev = self.compute_ewma_us.load(Ordering::Relaxed); + let next = if prev == 0 { + us + } else { + prev.saturating_add(us) / 2 + }; + self.compute_ewma_us.store(next, Ordering::Relaxed); + } +} + +/// One per-file logical-queue credit, released after the queue scheduler drains. +struct QueueCredit { + usage: Arc, +} + +impl QueueCredit { + fn acquire(usage: &Arc) -> Result { + if !usage.try_acquire_queue(hw::sizes::MAX_QUEUES) { + return Err(ENOSPC); + } + Ok(Self { + usage: usage.clone(), + }) + } +} + +impl Drop for QueueCredit { + fn drop(&mut self) { + self.usage.release_queue(); + } } /// A G16 logical queue. @@ -96,9 +172,19 @@ pub(crate) struct Queue { pub(crate) state: Arc, /// Commands accepted per engine (render, compute) since creation (checked for accounting overflow). pub(crate) accepted: [u64; 2], + /// Epoch-validated GPUVM span cache reused across submits on this logical queue. + proof: KBox, vm: Arc, shared: Arc, timeline: Arc, + /// Enabled GPU cores, which SCS memory is sized for. + active_cores: u32, + /// Hardware capabilities for stream admission and scratch reservations. + cfg: &'static hw::Config, + /// Reserved render scratch pages per stage (`render_scs_layout`). + render_scs: [u16; 2], + // Last field: all preceding fields (especially scheduler) drop before capacity returns. + _credit: QueueCredit, } impl Queue { @@ -130,6 +216,7 @@ impl Queue { if vm_state.status.get() != 0 { return Err(EIO); } + let credit = QueueCredit::acquire(&usage)?; let timeline = Timeline::new()?; let scheduler = Scheduler::new(&gpu.shared.dev)?; let state = Arc::new( @@ -140,67 +227,117 @@ impl Queue { cancelled_at: [const { AtomicU64::new(0) }; 2], turn: AtomicU64::new(0), completed: [const { AtomicU64::new(0) }; 2], + compute_ooo: AtomicU64::new(0), + published: [const { AtomicU64::new(0) }; 2], owned: [const { AtomicU32::new(0) }; 32], owned_index: AtomicU32::new(0), + compute_ewma_us: AtomicU32::new(0), }, GFP_KERNEL, )?; + let proof = command::SpanProof::new_boxed()?; Ok(Self { scheduler, state, accepted: [0; 2], + proof, vm: vm_state, shared: gpu.shared.clone(), timeline, + active_cores: gpu.id.core_masks.iter().map(|mask| mask.count_ones()).sum(), + cfg: gpu.cfg, + render_scs: [0; 2], + _credit: credit, }) } - /// Validates a SUBMIT and pushes its job; returns the job's fence. + /// Validates a SUBMIT, publishes its output syncs, and pushes its job. fn submit_job( &mut self, id: u64, - syncs: &Syncs, + syncs: &mut Syncs, sync_count: usize, bytes: &[u8], objects: Pin<&xarray::XArray>>, - ) -> Result { + ) -> Result { if sync_count > command::MAX_SYNCS { return Err(EINVAL); } - command::check_stream(bytes, params::early_tiling())?; + let parsed = if self.cfg.gpu_generation < 16 { + command::parse_stream_for( + bytes, + params::early_tiling(), + self.cfg.num_clusters, + self.cfg.gpu_generation, + )? + } else { + command::parse_stream(bytes, params::early_tiling())? + }; if self.shared.crashed.load(Ordering::Acquire) { return Err(EIO); } if self.vm.status.get() != 0 { return Err(EIO); } - let prepared = command::prepare(bytes, self.accepted, objects)?; + let prepared = parsed.prepare(self.accepted, objects)?; // The job reference first, so that the mappings checked below stay retained. let guard = self.vm.vm.retain_first_job()?; - let submission = prepared.validate(&command::Context { - vm: &self.vm.vm, - usc_base: self.state.usc_base, - })?; + let submission = prepared.validate( + &command::Context { + vm: &self.vm.vm, + usc_base: self.state.usc_base, + active_cores: self.active_cores, + render_scs: self.render_scs, + max_tile_buffer: self.cfg.max_tile_buffer, + }, + &mut self.proof, + )?; // Refused jobs add no accepted ordinals; check every prepared dependency before // publishing a fence or extending the queue's accepted frontier. - for order in &submission.orders { + for order in submission.orders.iter() { self.state.check(order)?; } - let mut inputs = KVec::with_capacity(syncs.inputs().len(), GFP_KERNEL)?; + let mut inputs = InputFences::new(); for sync in syncs.inputs() { if let Some(fence) = &sync.fence { - inputs.push(fence.clone(), GFP_KERNEL)?; + inputs.push(fence.clone())?; } } // Allocate and map private backing before a fence or accepted ordinal exists. // No GPU completion lock is held; reclaim can wait for earlier hardware work. + let hints = super::resources::PrepareHints { + expand_compute_ext: self.shared.base_compute_quarantined.load(Ordering::Acquire), + quarantined_compute_mask: self.shared.quarantined_compute_mask.load(Ordering::Acquire), + expand_render_ext: self.shared.base_render_quarantined.load(Ordering::Acquire), + quarantined_pb_mask: self.shared.quarantined_pb_mask.load(Ordering::Acquire), + next_pb_slot: &self.shared.next_pb_slot, + active_render_vms: &self.shared.active_render_vms, + }; let resources = self .vm .resources .as_ref() .ok_or(EIO)? - .prepare(&self.vm, &submission.commands)?; - let fence = self.timeline.next()?; + .prepare(&self.vm, &submission.commands, hints)?; + let gpu_id = Arc::as_ptr(&self.shared) as usize; + // Record cumulative queue ordinals across both engines so coalescing multiple + // same-queue fences in a timeline semaphore chain to the latest fence preserves + // any earlier unretired render or compute command on that queue. + let total_render = self.accepted[command::RENDER] + submission.counts[command::RENDER]; + let total_compute = self.accepted[command::COMPUTE] + submission.counts[command::COMPUTE]; + let last_ordinal = [ + (total_render != 0).then_some(total_render), + (total_compute != 0).then_some(total_compute), + ]; + let origin = Arc::new( + super::fence::FenceOrigin::new(gpu_id, self.vm.id, self.state.clone(), last_ordinal), + GFP_KERNEL, + )?; + let (inputs, fw_waits) = match super::fence::resolve_fw_waits(&inputs, gpu_id, self.vm.id) { + Some(waits) => (InputFences::new(), waits), + None => (inputs, super::fence::FwWaits::Empty), + }; + let fence = self.timeline.next(origin.clone())?; let job = Job::new( id, self.state.clone(), @@ -211,33 +348,58 @@ impl Queue { fence, guard, inputs, + origin, + fw_waits, )?; let published = job.fence.fence(); + // Publish output syncs (including fallible cumulative scope allocation) before pushing + // to the scheduler so ENOMEM refuses cleanly without leaving an accepted job behind. + // If `scheduler.push` later fails, dropping `job` signals `published` with ECANCELED. + syncs.publish(&published)?; self.scheduler.push(job, self.shared.clone())?; // Accepted: retain bounded per-engine accounting for later submissions. self.accepted[command::RENDER] += submission.counts[command::RENDER]; self.accepted[command::COMPUTE] += submission.counts[command::COMPUTE]; - Ok(published) + Ok(()) } } impl crate::queue::Queue for Queue { + /// RENDER_RAY_QUERY: the largest scratch layouts of the queue's vertex and fragment stages. + /// A render's UMA pool serves both stages of one render at a time, so their extra pages add + /// up ([`super::rt::required_seeds`]). + fn reserve_render_scs(&mut self, layouts: [u64; 2]) -> Result { + if !self.cfg.supports_render_scs { + if layouts == [0; 2] { + return Ok(()); + } + return Err(Error::from_errno(-(kernel::bindings::EOPNOTSUPP as i32))); + } + if self.accepted != [0; 2] { + return Err(EBUSY); + } + let pages = [ + super::rt::ScratchRequest::new(layouts[0])?.pages(), + super::rt::ScratchRequest::new(layouts[1])?.pages(), + ]; + super::rt::required_seeds(self.active_cores, &pages)?; + self.render_scs = pages; + Ok(()) + } + fn submit( &mut self, _reg_data: &crate::driver::AsahiRegData<'_>, id: u64, - syncs: KVec, + syncs: KVVec, in_sync_count: usize, cmdbuf_raw: &[u8], objects: Pin<&xarray::XArray>>, ) -> Result { let sync_count = syncs.len(); - let syncs = Syncs::new(syncs, in_sync_count); - match self.submit_job(id, &syncs, sync_count, cmdbuf_raw, objects) { - Ok(fence) => { - syncs.accept(&fence); - Ok(()) - } + let mut syncs = Syncs::new(syncs, in_sync_count); + match self.submit_job(id, &mut syncs, sync_count, cmdbuf_raw, objects) { + Ok(()) => Ok(()), Err(error) => { // A refused submission leaves the VM usable unless the device is lost. self.vm.status.record_if_device_loss(error); diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index b0fc2ed96976cc..ee64e0e6876985 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -21,8 +21,13 @@ use kernel::{ use logic::{RecoveryAction, Retirement, SnapshotEntry}; use super::job::{Completions, Job}; +use super::regs::wmb; use super::{params, Firmware}; +/// S1, the lowest powered row of the firmware DVFS table, as the Globals p-state selectors +/// express it (hundredths of a state). The host starts the firmware there too. +const FLOOR_SELECTOR: u32 = 100; + /// Monotonic time, ns. pub(crate) fn now_ns() -> u64 { ::ktime_get() as u64 @@ -45,15 +50,22 @@ pub(crate) fn push_completion(done: &mut Completions, job: &Arc, result: Re done.push(job, result); } +const _: () = assert!(logic::RETIRED_COMPUTE_PIPES == super::hw::sizes::COMPUTE_PIPES); + pub(crate) struct Recovery { - pub(crate) deadline_ns: u64, - pub(crate) compute_deadline_ns: u64, - /// A long command warning is diagnostic, not evidence that the GPU has stopped. - warning_deadline_ns: u64, + /// Render host deadlines, ordinary and long-job ([`logic::Deadlines`]). + pub(crate) deadlines: logic::Deadlines, + /// Per-compute-pipe host deadlines, ordinary and long-job, so progress on one pipe + /// cannot mask a stalled flight on another compute pipe. + pub(crate) compute_deadlines: [logic::Deadlines; super::hw::sizes::COMPUTE_PIPES], + /// Render long-command warning deadline; diagnostic only. + warning_deadline_ns: [u64; 2], + /// Per-compute-pipe long-command warning deadlines; diagnostic only. + compute_warning_deadline_ns: [u64; super::hw::sizes::COMPUTE_PIPES], pub(crate) long_commands: u64, pub(crate) publication_wait_deadline: Option, - /// Last fully retired compute/TA/FS identity, for late recovery snapshots. - pub(crate) last_retired: [Option; 3], + /// Recently retired compute pipe and TA/FS stamps, heap-boxed off the probe stack. + pub(crate) last_retired: KBox, /// Queue engine order: render, compute. A quarantined/exhausted class stays offline. pub(crate) unavailable: [Option; 2], pub(crate) errors_seen: u32, @@ -69,17 +81,23 @@ pub(crate) struct Recovery { window_ns: u64, window_count: u32, running: bool, + pub(crate) fwlog_remaining: usize, } impl Recovery { - pub(crate) fn new() -> Self { - Self { - deadline_ns: logic::EXPIRED, - compute_deadline_ns: logic::EXPIRED, - warning_deadline_ns: u64::MAX, + pub(crate) fn new() -> Result { + let mut retired = KBox::::new_uninit(GFP_KERNEL)?; + logic::RetiredStamps::init_zero(&mut *retired); + // SAFETY: `init_zero` initialized the entire `RetiredStamps` in place. + let last_retired = unsafe { retired.assume_init() }; + Ok(Self { + deadlines: logic::Deadlines::EXPIRED, + compute_deadlines: [logic::Deadlines::EXPIRED; super::hw::sizes::COMPUTE_PIPES], + warning_deadline_ns: [u64::MAX; 2], + compute_warning_deadline_ns: [u64::MAX; super::hw::sizes::COMPUTE_PIPES], long_commands: 0, publication_wait_deadline: None, - last_retired: [None; 3], + last_retired, unavailable: [None; 2], errors_seen: 0, statistics_seen: 0, @@ -92,7 +110,8 @@ impl Recovery { window_ns: 0, window_count: 0, running: false, - } + fwlog_remaining: super::channel::RECOVERY_FWLOG_CAP, + }) } pub(crate) fn failed(&self) -> Option { @@ -109,15 +128,33 @@ impl Firmware { &self.pools.dev } + pub(crate) fn renew_render_deadline(&mut self) { + let now = now_ns(); + let renewed = logic::Deadlines::renew(now, params::deadline_ms(), 0); + self.recovery.deadlines.any = renewed.any; + self.recovery.deadlines.long_any = renewed.long_any; + self.recovery.warning_deadline_ns[super::command::RENDER] = + now.saturating_add(5_000_000_000); + } + + pub(crate) fn renew_compute_pipe_deadline(&mut self, pipe: usize) { + let pipe = pipe.min(super::hw::sizes::COMPUTE_PIPES - 1); + let now = now_ns(); + let renewed = logic::Deadlines::renew(now, 0, params::compute_deadline_ms()); + self.recovery.compute_deadlines[pipe].compute = renewed.compute; + self.recovery.compute_deadlines[pipe].long_compute = renewed.long_compute; + self.recovery.compute_warning_deadline_ns[pipe] = now.saturating_add(5_000_000_000); + } + + pub(crate) fn renew_compute_deadline(&mut self) { + for pipe in 0..super::hw::sizes::COMPUTE_PIPES { + self.renew_compute_pipe_deadline(pipe); + } + } + pub(crate) fn renew_deadlines(&mut self) { - let (deadline, compute) = logic::renew( - now_ns(), - params::deadline_ms(), - params::compute_deadline_ms(), - ); - self.recovery.deadline_ns = deadline; - self.recovery.compute_deadline_ns = compute; - self.recovery.warning_deadline_ns = now_ns().saturating_add(5_000_000_000); + self.renew_render_deadline(); + self.renew_compute_deadline(); } fn new_recovery(&self) -> bool { @@ -126,7 +163,9 @@ impl Firmware { } pub(crate) fn recovery_pending(&self) -> Result { - Ok(self.recovery.running || self.new_recovery() || self.firmware_r32(logic::PHASE)? != 0) + Ok(self.recovery.running + || self.new_recovery() + || self.firmware_r32(self.init.firmware_data().phase)? != 0) } pub(crate) fn recovery_idle(&self) -> Result { @@ -140,11 +179,11 @@ impl Firmware { /// A full hardware receipt still fails an explicitly affected job. Merely /// suspect work can complete normally; the poll owner separately proves an /// abort before retiring it without a full receipt. - pub(crate) fn retire_outcome(&mut self, receipt: Retirement) -> Result { + pub(crate) fn retire_outcome_at(&mut self, index: usize, receipt: Retirement) -> Result { let affected = self .engine .flights - .first() + .get(index) .is_some_and(|flight| flight.doomed); if receipt.job_failed(affected) { Err(EIO) @@ -156,6 +195,7 @@ impl Firmware { /// Protocol errors and transport loss always retain uncertain owners. /// A deadline without a firmware recovery notification is not permission /// to manipulate undocumented preemption controls. + #[inline(never)] pub(crate) fn check_hangs(&mut self, done: &mut Completions) -> Result { if let Some(error) = self.recovery.failed { return Err(error); @@ -181,23 +221,64 @@ impl Firmware { return Err(EIO); } if !self.engine.flights.is_empty() { + const CP: usize = super::hw::sizes::COMPUTE_PIPES; self.progress(); let now = now_ns(); - if logic::expired(now, self.recovery.warning_deadline_ns) { - self.recovery.warning_deadline_ns = u64::MAX; + let mut has_render = false; + let mut has_long_render = false; + let mut has_compute = [false; CP]; + let mut has_long_compute = [false; CP]; + for flight in &self.engine.flights { + if flight.renders != 0 { + has_render = true; + if flight.job.long() { + has_long_render = true; + } + } + if flight.computes != 0 { + let p = (flight.compute_pipe as usize).min(CP - 1); + if !has_compute[p] { + has_compute[p] = true; + has_long_compute[p] = flight.job.long(); + } + } + } + if has_render + && logic::expired( + now, + self.recovery.warning_deadline_ns[super::command::RENDER], + ) + { + self.recovery.warning_deadline_ns[super::command::RENDER] = u64::MAX; self.recovery.long_commands = self.recovery.long_commands.saturating_add(1); - dev_warn!(self.dev(), "M4 GPU command has no completion-stamp progress for 5s; execution may still be active\n"); + dev_warn!( + self.dev(), + "M4 GPU render command has no completion-stamp progress for 5s; execution may still be active\n" + ); } - let compute_only = self - .engine - .oldest() - .is_some_and(|flight| flight.computes != 0 && flight.renders == 0); - let deadline = if compute_only { - self.recovery.compute_deadline_ns - } else { - self.recovery.deadline_ns - }; - if logic::expired(now, deadline) { + let mut compute_expired = false; + for p in 0..CP { + if !has_compute[p] { + continue; + } + if logic::expired(now, self.recovery.compute_warning_deadline_ns[p]) { + self.recovery.compute_warning_deadline_ns[p] = u64::MAX; + self.recovery.long_commands = self.recovery.long_commands.saturating_add(1); + dev_warn!( + self.dev(), + "M4 GPU compute pipe {} command has no completion-stamp progress for 5s; execution may still be active\n", + p + ); + } + let pipe_deadline = self.recovery.compute_deadlines[p] + .select(true, has_long_compute[p]); + if logic::expired(now, pipe_deadline) { + compute_expired = true; + } + } + // Ray traversal and AS builds: every flight of such a job (`Job::long`). + let render_deadline = self.recovery.deadlines.select(false, has_long_render); + if (has_render && logic::expired(now, render_deadline)) || compute_expired { dev_err!( self.dev(), "M4 GPU administrative command deadline exceeded without firmware recovery; retaining owners and fail-stop (not proof of quiescence)\n" @@ -235,8 +316,10 @@ impl Firmware { pub(crate) fn fail_stop(&mut self, error: Error, done: &mut Completions) { if self.recovery.failed.is_none() { self.recovery.failed = Some(error); + self.floor_power(error); } self.engine.frozen = true; + self.engine.coalesce_deadline_ns = 0; self.events.grow.clear(); self.fail_flights(error, done); self.fail_all_vms(EIO); @@ -249,12 +332,66 @@ impl Firmware { } } + /// A failed device must not stay at its last performance request: the J773g idled at 98 C + /// after a fail-stop, against 83 C with the GPU idle. The Globals ceiling selectors are + /// host-owned (`service_power` writes them at runtime and stops after a failure): drop them + /// to S1 and log the one fail-stop summary. Nothing firmware-owned is touched, and no GPU + /// register is read. + fn floor_power(&mut self, error: Error) { + let before = self.power.effective; + let selectors = self.init.layout.pstate_selectors; + let mut ok = 0usize; + let mut failed = 0usize; + if let Some(globals) = self.init.globals.as_ref() { + // Write every selector without short-circuiting so a single write error cannot + // leave the remaining selectors unfloored. + for offset in selectors { + match globals.w32(offset, FLOOR_SELECTOR) { + Ok(()) => ok += 1, + Err(write_err) => { + failed += 1; + dev_err!( + self.dev(), + "G16: fail-stop: failed to floor Globals +{:#x}: {:?}\n", + offset, + write_err + ); + } + } + } + } + if ok != 0 { + wmb(); + } + let all_floored = ok == selectors.len() && failed == 0; + if all_floored { + self.power.effective = 1; + } + let outcome = if all_floored { + "S1" + } else if ok != 0 { + "partial S1" + } else { + "unchanged (Globals unwritable)" + }; + dev_err!( + self.dev(), + "G16: fail-stop ({:?}): host ceiling S{} -> {} ({}/{} selectors written), temperature {} mC\n", + error, + before, + outcome, + ok, + selectors.len(), + self.power.temperature_mc + ); + } + /// Flights own firmware-visible resources and slot claims. Failed-stop /// flights are retained whole, never released to the free slot lists. pub(crate) fn fail_flights(&mut self, error: Error, done: &mut Completions) { let flights = core::mem::take(&mut self.engine.flights); // A failed device never publishes again: release the memory floor now. - self.power.report_work(false); + self.power.release_clpc_now(); for flight in flights.iter() { for job in Iterator::chain(core::iter::once(&flight.job), flight.group.iter()) { push_completion(done, job, Err(error)); @@ -288,16 +425,23 @@ impl Firmware { fn firmware_generation(&self) -> Result { // The firmware is stopped while its published generation is consumed. - let lo = self.firmware_r32(logic::GENERATION)?; - let hi = self.firmware_r32(logic::GENERATION + 4)?; + let generation = self.init.firmware_data().generation; + let lo = self.firmware_r32(generation)?; + let hi = self.firmware_r32(generation + 4)?; Ok(u64::from(lo) | (u64::from(hi) << 32)) } /// Resolve the snapshot while the firmware is stopped. A missing retained /// owner prevents acknowledgement: its failure cannot safely be attributed. - fn mark_recovery(&mut self, stage: [u32; 3], event: u32, asid: Option) -> Result { - for i in 0..logic::SNAPSHOT_ENTRIES { - let offset = logic::SNAPSHOT + i * 8; + fn mark_recovery( + &mut self, + stage: [u32; 2 + super::hw::sizes::COMPUTE_PIPES], + event: u32, + asid: Option, + ) -> Result { + let data = self.init.firmware_data(); + for i in 0..data.snapshot_entries { + let offset = data.snapshot + i * 8; let flags = self.firmware_r32(offset)?; let target = self.firmware_r32(offset + 4)?; let Some(entry) = SnapshotEntry::decode(flags, target) else { @@ -308,42 +452,110 @@ impl Firmware { self.recovery_prepare_suspects(stage, event, asid) } + /// Decodes and logs every non-zero fault bank captured while firmware is halted in phase 1, + /// together with whether the faulting context matches any in-flight flight or open VM. + #[inline(never)] + fn log_recovery_faults(&self, scan: Option<&super::regs::FaultScan>, event: u32) { + let Some(scan) = scan else { + dev_warn!( + self.dev(), + "G16: fault_scan: GPU powered down (event={:#x}, flights={})\n", + event, + self.engine.flights.len() + ); + return; + }; + let mut nonzero = 0usize; + for entry in scan.banks() { + if entry.status == 0 { + continue; + } + nonzero += 1; + self.log_fault(entry); + let ctx = ((entry.status >> 17) & 0x3f) as u32; + let flight_matches = self + .engine + .flights + .iter() + .filter(|f| f.job.vm.slot == ctx) + .count(); + let live_vm = self.vms.find_by_slot(ctx); + dev_warn!( + self.dev(), + "G16: fault bank {} attribution: busy={} saved_bank={} ctx={} flight_matches={} live_vm={:?} event={:#x} flights={}\n", + entry.bank, + scan.busy, + scan.saved_bank, + ctx, + flight_matches, + live_vm, + event, + self.engine.flights.len() + ); + } + if nonzero == 0 { + dev_warn!( + self.dev(), + "G16: fault_scan: all {} banks zero (busy={}, saved_bank={}, event={:#x}, flights={})\n", + scan.banks().len(), + scan.busy, + scan.saved_bank, + event, + self.engine.flights.len() + ); + } + } + fn recover(&mut self) -> Result { - let start = self.events.recovery_started_ns.unwrap_or_else(now_ns); - if !logic::admit( - start, - &mut self.recovery.window_ns, - &mut self.recovery.window_count, - ) { - dev_err!(self.dev(), "M4 GPU recovery storm: fail-stop\n"); - return Err(EIO); + struct RecoveringGuard(Option>); + impl Drop for RecoveringGuard { + fn drop(&mut self) { + if let Some(shared) = &self.0 { + shared + .recovering + .store(false, core::sync::atomic::Ordering::Release); + } + } + } + if let Some(shared) = &self.engine.shared { + shared + .recovering + .store(true, core::sync::atomic::Ordering::Release); } + let _recovering = RecoveringGuard(self.engine.shared.clone()); + let start = self.events.recovery_started_ns.unwrap_or_else(now_ns); self.recovery.running = true; self.engine.frozen = true; - self.events.grow.clear(); - // These frontiers must be captured before the host answers 2: the - // firmware can force the stage target while aborting a work item. - let stage = self.recovery_snapshot()?; - let fault = self.session.regs.engine_state()?; - let asid = fault - .status - .iter() - .find(|status| **status & 1 != 0) - .map(|status| ((*status >> 17) & 0x3f) as u32) - .filter(|asid| *asid >= 1); let deadline = start.saturating_add(logic::RECOVERY_BUDGET_NS); let mut answered = false; let mut generation = 0; + let mut last_phase = 0; loop { if let Some(error) = self.transport_error() { return Err(error); } let now = now_ns(); if logic::expired(now, deadline) { - dev_err!(self.dev(), "M4 GPU recovery exceeded 1000 ms\n"); + let _ = self.drain_auxiliary_rings(); + // Which side stalled, and whether tiling or fragment work was left behind. + let stage = self + .recovery_snapshot() + .unwrap_or([0; 2 + super::hw::sizes::COMPUTE_PIPES]); + dev_err!( + self.dev(), + "M4 GPU recovery exceeded 1000 ms: {} (phase {}, TA {:#x}/{:#x}, FS {:#x}/{:#x}, {} flights)\n", + logic::Stall::of(last_phase, answered).describe(), + last_phase, + stage[0], + self.engine.ta_target, + stage[1], + self.engine.fs_target, + self.engine.flights.len() + ); return Err(ETIMEDOUT); } - let phase = self.firmware_r32(logic::PHASE)?; + let phase = self.firmware_r32(self.init.firmware_data().phase)?; + last_phase = phase; let current_generation = if phase == 1 || phase == 3 { self.firmware_generation()? } else { @@ -359,6 +571,14 @@ impl Firmware { poll_sleep(); continue; } + if !logic::admit( + now, + &mut self.recovery.window_ns, + &mut self.recovery.window_count, + ) { + dev_err!(self.dev(), "M4 GPU recovery storm: fail-stop\n"); + return Err(EIO); + } generation = current_generation; let event = if have_event { let event = self.events.last_error.ok_or(super::boot::eproto())?; @@ -370,22 +590,42 @@ impl Firmware { } else { u32::MAX }; + // Firmware is now halted in phase 1: invalidate bound PB state and + // force a full scrub on the next claim of every compute and render slot, + // then capture stage frontiers and fault-bank state before answering 2 + // (firmware may force stage targets while aborting work, and fault_scan + // writes the fault-bank selector so it must not run against active FW). + self.pools.invalidate(); + self.slots.invalidate_scrub(); + self.events.grow.clear(); + let stage = self.recovery_snapshot()?; + // Powered down, the GPU holds no fault to read. + let scan = self.session.fault_scan()?; + self.log_recovery_faults(scan.as_ref(), event); + let _ = self.drain_auxiliary_rings(); + let asid = scan + .as_ref() + .and_then(super::regs::FaultScan::first_latched) + .map(|fault| ((fault.status >> 17) & 0x3f) as u32) + .filter(|asid| *asid >= 1); self.mark_recovery(stage, event, asid)?; // Snapshot reads and all TPC repairs precede acknowledgement. barrier(); - self.firmware_w32(logic::PHASE, 2)?; + self.firmware_w32(self.init.firmware_data().phase, 2)?; barrier(); answered = true; } RecoveryAction::Resume => { + let _ = self.drain_auxiliary_rings(); barrier(); - self.firmware_w32(logic::PHASE, 0)?; + self.firmware_w32(self.init.firmware_data().phase, 0)?; barrier(); self.recovery.recoveries += 1; self.recovery.errors_seen = self.events.errors; self.recovery.statistics_seen = self.events.recovery_statistics; self.events.recovery_started_ns = None; self.recovery.running = false; + self.recovery.fwlog_remaining = super::channel::RECOVERY_FWLOG_CAP; self.engine.frozen = false; self.renew_deadlines(); dev_warn!( @@ -404,7 +644,27 @@ impl Firmware { ); return Err(super::boot::eproto()); } - RecoveryAction::Wait => {} + RecoveryAction::Wait => { + if logic::phantom_phase0( + phase, + answered, + self.engine.flights.is_empty(), + now.saturating_sub(start), + ) { + let _ = self.drain_auxiliary_rings(); + self.recovery.errors_seen = self.events.errors; + self.recovery.statistics_seen = self.events.recovery_statistics; + self.events.recovery_started_ns = None; + self.recovery.running = false; + self.recovery.fwlog_remaining = super::channel::RECOVERY_FWLOG_CAP; + self.engine.frozen = false; + dev_warn!( + self.dev(), + "M4 GPU idle recovery notification cleared without phase 1\n" + ); + return Ok(()); + } + } } self.drain_rings()?; poll_sleep(); diff --git a/drivers/gpu/drm/asahi/g16/recovery/logic.rs b/drivers/gpu/drm/asahi/g16/recovery/logic.rs index 4d8bcb716eda5b..a205d213bd2214 100644 --- a/drivers/gpu/drm/asahi/g16/recovery/logic.rs +++ b/drivers/gpu/drm/asahi/g16/recovery/logic.rs @@ -19,19 +19,21 @@ pub(crate) const fn stamp_reached(obs: u32, own: u32, tail: u32) -> bool { /// `CONFIG_RUST_OVERFLOW_CHECKS`). #[allow(dead_code)] pub(crate) const fn ring_passed(c: u32, b: u32, h: u32, t: u32, m: u32) -> bool { + if m == 0 || c >= m || b >= m || h >= m || t >= m { + return false; + } let dc = c.wrapping_add(m).wrapping_sub(b) % m; let dh = h.wrapping_add(m).wrapping_sub(b) % m; let dt = t.wrapping_add(m).wrapping_sub(b) % m; dh <= dc && dc <= dt } -/// FirmwareData words and affected-work snapshot geometry. -pub(crate) const SNAPSHOT: usize = 0x40b8; -pub(crate) const SNAPSHOT_ENTRIES: usize = 448; -pub(crate) const GENERATION: usize = 0x4fa0; -pub(crate) const PHASE: usize = 0x4fb0; +// The FirmwareData words (phase, generation, affected-work snapshot) are per firmware ABI: +// `fw::initdata::FirmwareData`. pub(crate) const RECOVERY_BUDGET_NS: u64 = 1_000_000_000; pub(crate) const EVENT_WAIT_NS: u64 = 50_000_000; +/// Bounded wait before dismissing a trailing phase-0 recovery notification on an idle GPU. +pub(crate) const PHANTOM_PHASE0_WAIT_NS: u64 = 50_000_000; pub(crate) const WINDOW_NS: u64 = 10_000_000_000; pub(crate) const WINDOW_LIMIT: u32 = 32; #[allow(dead_code)] @@ -80,6 +82,17 @@ pub(crate) enum RecoveryAction { ProtocolError, } +/// A type-4 or 0x16 notification drained after a completed recovery leaves phase at 0 with +/// no flights in flight. Consume it after a short bounded wait instead of spinning to fail-stop. +pub(crate) const fn phantom_phase0( + phase: u32, + answered: bool, + flights_empty: bool, + elapsed_ns: u64, +) -> bool { + phase == 0 && !answered && flights_empty && elapsed_ns >= PHANTOM_PHASE0_WAIT_NS +} + /// Only the host writes phases 2 and 0; the firmware publishes phases 1 and 3. /// An acknowledged recovery may not return to phase 0 or start a new phase 1. pub(crate) fn action(phase: u32, answered: bool, generation_matches: bool) -> RecoveryAction { @@ -92,6 +105,36 @@ pub(crate) fn action(phase: u32, answered: bool, generation_matches: bool) -> Re } } +/// Where a recovery that ran past [`RECOVERY_BUDGET_NS`] stopped, from the last phase the host +/// read and whether the host had acknowledged phase 1 ([`action`]'s inputs). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Stall { + /// The firmware announced a recovery but never published phase 1. + NotHalted, + /// The firmware published phase 1 and the host had not acknowledged it. + NotAcknowledged, + /// The host acknowledged phase 1 and the firmware never published phase 3. + NotResumed, +} + +impl Stall { + pub(crate) const fn of(phase: u32, answered: bool) -> Self { + match (phase, answered) { + (_, true) => Self::NotResumed, + (1, false) => Self::NotAcknowledged, + _ => Self::NotHalted, + } + } + + pub(crate) const fn describe(self) -> &'static str { + match self { + Self::NotHalted => "firmware never halted in phase 1", + Self::NotAcknowledged => "phase 1 not acknowledged", + Self::NotResumed => "firmware never published phase 3", + } + } +} + /// One valid-prefix entry of the firmware's snapshot. Invalid entries terminate it. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) struct SnapshotEntry { @@ -113,15 +156,63 @@ impl SnapshotEntry { } } -/// A late snapshot can name the last complete receipt even after its flight was removed. -pub(crate) fn last_retired_target(last: &[Option; 3], event: u32, target: u32) -> bool { - let index = match event { - 15 => 0, - 0x70 => 1, - 0x71 => 2, - _ => return false, - }; - last[index] == Some(target) +/// Bounded per-stage history of recently retired firmware stamps. +pub(crate) const RETIRED_STAMPS_CAP: usize = 64; +/// Number of compute pipes tracked by [`RetiredStamps`] (matches `hw::sizes::COMPUTE_PIPES`). +pub(crate) const RETIRED_COMPUTE_PIPES: usize = 8; +/// Total retired-stamp stages: compute pipes `0..RETIRED_COMPUTE_PIPES`, TA, FS. +pub(crate) const RETIRED_STAGES: usize = RETIRED_COMPUTE_PIPES + 2; + +/// Bounded per-stage ring of recently retired compute pipe and TA/FS firmware stamps +/// so a late recovery snapshot arriving after pipelined retirement resolves any recently +/// retired member, not only the single newest flight. +#[derive(Clone, Debug)] +pub(crate) struct RetiredStamps { + stamps: [[u32; RETIRED_STAMPS_CAP]; RETIRED_STAGES], + len: [u8; RETIRED_STAGES], + next: [u8; RETIRED_STAGES], +} + +impl RetiredStamps { + pub(crate) const fn new() -> Self { + Self { + stamps: [[0; RETIRED_STAMPS_CAP]; RETIRED_STAGES], + len: [0; RETIRED_STAGES], + next: [0; RETIRED_STAGES], + } + } + + /// Initializes an uninitialized heap slot to the empty zero state without materializing a + /// multi-kilobyte temporary on the caller's stack. + #[allow(dead_code)] + pub(crate) fn init_zero(slot: &mut core::mem::MaybeUninit) { + // SAFETY: All fields of `RetiredStamps` are integer arrays for which all-zeroes is valid + // and identical to `RetiredStamps::new()`. + unsafe { core::ptr::write_bytes(slot.as_mut_ptr(), 0, 1) }; + } + + pub(crate) fn push(&mut self, stage: usize, target: u32) { + if stage >= RETIRED_STAGES { + return; + } + let idx = self.next[stage] as usize; + self.stamps[stage][idx] = target; + self.next[stage] = ((idx + 1) % RETIRED_STAMPS_CAP) as u8; + if (self.len[stage] as usize) < RETIRED_STAMPS_CAP { + self.len[stage] += 1; + } + } + + pub(crate) fn contains(&self, event: u32, target: u32) -> bool { + let stage = match event { + e if (15..15 + RETIRED_COMPUTE_PIPES as u32).contains(&e) => (e - 15) as usize, + 0x70 => RETIRED_COMPUTE_PIPES, + 0x71 => RETIRED_COMPUTE_PIPES + 1, + _ => return false, + }; + let len = self.len[stage] as usize; + self.stamps[stage][..len].contains(&target) + } } pub(crate) const fn expired(now: u64, deadline: u64) -> bool { @@ -136,6 +227,67 @@ pub(crate) fn renew(now: u64, deadline_ms: u32, compute_deadline_ms: u32) -> (u6 ) } +/// Ray traversal and acceleration-structure builds can run past one administrative deadline +/// (CTS stress). As on the M4 Pro (g17 `timeout::select`: two-second polls plus four extra +/// ones), a job with such a command gets at least ten seconds per flight. Still bounded: +/// this is an allowance, not evidence of GPU progress. +pub(crate) const LONG_DEADLINE_MS: u32 = 10_000; + +/// The administrative deadline of a long job, ms: at least [`LONG_DEADLINE_MS`], unless the +/// deadline is disabled (zero). +pub(crate) const fn long_deadline_ms(milliseconds: u32) -> u32 { + if milliseconds == 0 || milliseconds >= LONG_DEADLINE_MS { + milliseconds + } else { + LONG_DEADLINE_MS + } +} + +/// The four host deadlines renewed together: ordinary and compute-only, each plain and for a +/// long job. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct Deadlines { + pub(crate) any: u64, + pub(crate) compute: u64, + pub(crate) long_any: u64, + pub(crate) long_compute: u64, +} + +impl Deadlines { + pub(crate) const EXPIRED: Self = Self { + any: EXPIRED, + compute: EXPIRED, + long_any: EXPIRED, + long_compute: EXPIRED, + }; + + /// All four from `now`. + pub(crate) fn renew(now: u64, deadline_ms: u32, compute_deadline_ms: u32) -> Self { + let (any, compute) = renew(now, deadline_ms, compute_deadline_ms); + let (long_any, long_compute) = renew( + now, + long_deadline_ms(deadline_ms), + long_deadline_ms(compute_deadline_ms), + ); + Self { + any, + compute, + long_any, + long_compute, + } + } + + /// The deadline of the oldest flight: compute-only or not, of a long job or not. + pub(crate) const fn select(&self, compute_only: bool, long: bool) -> u64 { + match (compute_only, long) { + (true, false) => self.compute, + (false, false) => self.any, + (true, true) => self.long_compute, + (false, true) => self.long_any, + } + } +} + /// Zero explicitly opts long-running work out of the host's administrative watchdog. /// Completion stamps cannot distinguish a running shader from a firmware-silent hang. fn host_deadline(now: u64, milliseconds: u32) -> u64 { @@ -166,17 +318,33 @@ mod tests { #[test] fn late_snapshot_requires_exact_stage_target_and_real_full_receipt() { - assert!(!last_retired_target(&[None; 3], 0x70, 0)); - let last = [Some(0x100), Some(0), Some(0x200)]; - for (event, target) in [(15, 0x100), (0x70, 0), (0x71, 0x200)] { - assert!(last_retired_target(&last, event, target)); - assert!(!last_retired_target( - &last, - event, - target.wrapping_add(0x100) - )); + let mut retired = RetiredStamps::new(); + assert!(!retired.contains(0x70, 0)); + retired.push(0, 0x100); + retired.push(1, 0x300); + retired.push(RETIRED_COMPUTE_PIPES - 1, 0x700); + retired.push(RETIRED_COMPUTE_PIPES, 0); + retired.push(RETIRED_COMPUTE_PIPES + 1, 0x200); + for (event, target) in [ + (15, 0x100), + (16, 0x300), + (15 + RETIRED_COMPUTE_PIPES as u32 - 1, 0x700), + (0x70, 0), + (0x71, 0x200), + ] { + assert!(retired.contains(event, target)); + assert!(!retired.contains(event, target.wrapping_add(0x100))); } - assert!(!last_retired_target(&last, 0x72, 0)); + assert!(!retired.contains(0x72, 0)); + // Pipelined bursts retain all recent stamps up to RETIRED_STAMPS_CAP and evict oldest. + let mut ring = RetiredStamps::new(); + for i in 0..(RETIRED_STAMPS_CAP as u32 + 4) { + ring.push(0, (i + 1) << 8); + } + assert!(!ring.contains(15, 0x100)); + assert!(!ring.contains(15, 0x400)); + assert!(ring.contains(15, 0x500)); + assert!(ring.contains(15, (RETIRED_STAMPS_CAP as u32 + 4) << 8)); } #[test] @@ -194,6 +362,24 @@ mod tests { assert_eq!(action(3, true, false), RecoveryAction::ProtocolError); } + #[test] + fn budget_overrun_names_the_phase_that_never_arrived() { + // dcp103b: a type-4 event and its statistics arrived, then 1000 ms passed. Which side + // stalled follows from the last phase read and whether the host had answered. + assert_eq!(Stall::of(0, false), Stall::NotHalted); + assert_eq!(Stall::of(1, false), Stall::NotAcknowledged); + assert_eq!(Stall::of(2, true), Stall::NotResumed); + for phase in [3, 4, u32::MAX] { + assert_eq!(Stall::of(phase, false), Stall::NotHalted); + } + let all = [Stall::NotHalted, Stall::NotAcknowledged, Stall::NotResumed]; + for (i, a) in all.iter().enumerate() { + for b in &all[i + 1..] { + assert_ne!(a.describe(), b.describe()); + } + } + } + #[test] fn affected_job_failure_does_not_erase_a_full_owner_receipt() { assert!(!Retirement::Pending.complete()); @@ -227,8 +413,6 @@ mod tests { .event, 15 ); - assert_eq!(SNAPSHOT + SNAPSHOT_ENTRIES * 8, 0x4eb8); - assert!(SNAPSHOT + SNAPSHOT_ENTRIES * 8 <= GENERATION); } #[test] @@ -246,12 +430,12 @@ mod tests { #[test] fn deadlines_are_absolute_and_do_not_wrap() { - assert_eq!(PHASE, 0x4fb0); let first_record_ns = 5_000_000_000; let deadline = first_record_ns + RECOVERY_BUDGET_NS; assert!(!expired(deadline, deadline)); assert!(expired(deadline + 1, deadline)); assert!(EVENT_WAIT_NS < RECOVERY_BUDGET_NS); + assert!(PHANTOM_PHASE0_WAIT_NS < RECOVERY_BUDGET_NS); assert!(ABORT_GRACE_NS < RECOVERY_BUDGET_NS); assert!(expired(1, EXPIRED)); assert_eq!(renew(7, 5000, 1000), (5_000_000_007, 1_000_000_007)); @@ -291,6 +475,16 @@ mod tests { } } + #[test] + fn phantom_phase0_clears_only_idle_unanswered_phase0_after_wait() { + assert!(!phantom_phase0(0, false, true, PHANTOM_PHASE0_WAIT_NS - 1)); + assert!(phantom_phase0(0, false, true, PHANTOM_PHASE0_WAIT_NS)); + assert!(!phantom_phase0(0, false, false, PHANTOM_PHASE0_WAIT_NS)); + assert!(!phantom_phase0(0, true, true, PHANTOM_PHASE0_WAIT_NS)); + assert!(!phantom_phase0(1, false, true, PHANTOM_PHASE0_WAIT_NS)); + assert!(!phantom_phase0(2, true, true, PHANTOM_PHASE0_WAIT_NS)); + } + #[test] fn stamps_and_wrapping_receipts() { assert!(!stamp_reached(0, 0x100, 0x300)); @@ -300,6 +494,8 @@ mod tests { assert!(stamp_reached(0x100, 0xffff_ff00, 0x200)); assert!(ring_passed(2, 0xfe, 1, 5, 256)); assert!(!ring_passed(0xff, 0xfe, 1, 5, 256)); + assert!(!ring_passed(256, 0, 1, 2, 256)); + assert!(!ring_passed(257, 0, 1, 2, 256)); assert!(!ring_passed(u32::MAX, 0, 1, 5, 256)); } } diff --git a/drivers/gpu/drm/asahi/g16/regs.rs b/drivers/gpu/drm/asahi/g16/regs.rs index e264e319c2a649..7c0c4628ae4d01 100644 --- a/drivers/gpu/drm/asahi/g16/regs.rs +++ b/drivers/gpu/drm/asahi/g16/regs.rs @@ -7,7 +7,8 @@ //! (`+0x1500` core mask, `+0x1000` pstate), status `+0xc000` //! (`+0x20`/`+0x120` busy, `+0x1800` bank select, `+0x18c0` fault status, `+0x18c8` fault //! address >> 6). ASC `+0x44` bit 4 is RUN (mapped from `asc` here; the shared layer does not -//! map it). No blind reads of unpowered blocks: read only after the AGX vote. +//! map it). No blind reads of unpowered blocks: read only after the AGX vote (25G83) or, on +//! 26B123, after admission holds the GPU's power domain and GFXCAXI2AF is enabled. //! //! The status window needs 64-bit stores (the fault bank select), which the shared accessors do //! not offer, so it is mapped here, as is `asc`. This module also holds the [`Mapping`] type the @@ -21,6 +22,8 @@ use kernel::{ prelude::*, }; +use core::sync::atomic::{AtomicU32, Ordering}; + use crate::regs::G16Resources; /// Write memory barrier (`wmb()`): `dsb st`. @@ -149,23 +152,51 @@ pub(crate) struct Identity { pub(crate) core_masks: [u32; 2], } -/// Engine receipts: busy bit and the two fault banks. +/// Maximum number of fault banks across the supported SGX status windows. +const MAX_FAULT_BANKS: usize = 8; + +/// Engine receipts: busy bit and one fault bank. #[derive(Copy, Clone, Default)] pub(crate) struct EngineState { /// Bit 0 of `+0xc020 | +0xc120`. #[allow(dead_code)] pub(crate) busy: u64, - /// `+0xd8c0` under fault-bank selectors 0 and 1. - pub(crate) status: [u64; 2], - /// `+0xd8c8 << 6` under fault-bank selectors 0 and 1. - pub(crate) address: [u64; 2], + /// The fault-bank selector (`+0xd800`) the status and address were read under. + pub(crate) bank: u64, + /// `+0xd8c0`: bit 0 set when the bank holds a fault. + pub(crate) status: u64, + /// `+0xd8c8 << 6`. + pub(crate) address: u64, } impl EngineState { - /// Fault status of both banks, OR-ed together. + /// Fault status of the bank read. #[allow(dead_code)] pub(crate) fn fault(&self) -> u64 { - self.status[0] | self.status[1] + self.status + } +} + +/// Fault-register snapshot taken while firmware is halted for recovery. +#[derive(Copy, Clone, Default)] +pub(crate) struct FaultScan { + /// Bit 0 of `+0xc020 | +0xc120`. + pub(crate) busy: u64, + /// Selector (`+0xd800`) observed before scanning and restored afterwards. + pub(crate) saved_bank: u64, + bank_count: usize, + /// Raw status (`+0xd8c0`) and address (`+0xd8c8 << 6`) of each fault bank. + banks: [EngineState; MAX_FAULT_BANKS], +} + +impl FaultScan { + pub(crate) fn banks(&self) -> &[EngineState] { + &self.banks[..self.bank_count] + } + + /// First bank whose latched fault bit (bit 0) is set. + pub(crate) fn first_latched(&self) -> Option<&EngineState> { + self.banks().iter().find(|entry| entry.status & 1 != 0) } } @@ -177,13 +208,26 @@ pub(crate) struct Regs { asc: Mapping, /// SGX status window (`sgx + 0xc000`, 0x4000). status: Mapping, + fault_banks: usize, /// Host-owned generation register page (SGX +0xd60000). generation: Mapping, + /// GFXCAXI2AF registers (SGX +0x1000000), written only by the 27.2 start. + axi2af: Option, + /// Highest firmware performance state the board's table holds: S9 until the table is + /// known (the ten-row J713/J604 tables), S10 on the eleven-row J773g table. + top: AtomicU32, } impl Regs { /// Maps the ASC control page and the SGX status window. - pub(crate) fn new(pdev: &platform::Device>, res: G16Resources) -> Result { + pub(crate) fn new( + pdev: &platform::Device>, + res: G16Resources, + cfg: &super::Config, + ) -> Result { + if !(1..=MAX_FAULT_BANKS).contains(&cfg.fault_banks) { + return Err(EINVAL); + } let window = |name: &CStr, offset: u64| -> Result { let r = pdev.resource_by_name(name).ok_or(EINVAL)?; let nonposted = r @@ -197,12 +241,23 @@ impl Regs { Ok(Self { asc: window(c_str!("asc"), 0)?, status: window(c_str!("sgx"), SGX_STATUS as u64)?, - generation: window(c_str!("sgx"), 0xd60000)?, + fault_banks: cfg.fault_banks, + generation: window(c_str!("sgx"), super::hw::HOST_BLOCK)?, + axi2af: cfg + .axi2af + .then(|| window(c_str!("sgx"), super::hw::start_27_2::AXI2AF as u64)) + .transpose()?, + top: AtomicU32::new(9), res, }) } - /// Reads the identification words and the enabled-core mask (after the AGX vote). + /// Physical base of the SGX resource. + pub(crate) fn sgx_pa(&self) -> u64 { + self.generation.phys - super::hw::HOST_BLOCK + } + + /// Reads the identification words and the enabled-core mask (after the AGX vote on 25G83). pub(crate) fn identity(&self) -> Result { let version = self.res.sgx_read32_at(SGX_ID)?; let counts = self.res.sgx_read32_at(SGX_ID + 0x10)?; @@ -216,10 +271,24 @@ impl Regs { }) } - /// Actual cold or running firmware pstate (zero is valid while stopped). + /// Adopts the board's firmware performance table, `rows` rows including off. + pub(crate) fn set_table(&self, rows: u32) { + let top = rows + .saturating_sub(1) + .clamp(1, super::fw::initdata::PERF_STATES as u32 - 1); + self.top.store(top, Ordering::Relaxed); + } + + /// Highest performance state the firmware may run in. + pub(crate) fn top(&self) -> u32 { + self.top.load(Ordering::Relaxed) + } + + /// Actual cold or running firmware pstate (zero is valid while stopped). A state above the + /// board table's top row is a protocol error. pub(crate) fn pstate(&self) -> Result { let state = self.res.sgx_read32_at(SGX_CORE + 0x1000)? & 0xf; - if state > 9 { + if state > self.top() { Err(super::boot::eproto()) } else { Ok(state) @@ -236,6 +305,41 @@ impl Regs { Ok(()) } + /// 26B123 before RUN: sets bit 0 of the two GFXCAXI2AF enables, each read first. + pub(crate) fn enable_axi2af(&self) -> Result { + let Some(axi2af) = &self.axi2af else { + return Ok(()); + }; + let r = axi2af.io(); + for offset in super::hw::start_27_2::AXI2AF_ENABLES { + let value = r.try_read32(offset)?; + r.try_write32(value | 1, offset)?; + } + mb(); + Ok(()) + } + + /// 26B123 after AP power-on and before the GPU endpoints start: reads then zeroes each + /// host-block control word, and on G16G reads the scratch word and raises the ready word. + pub(crate) fn publish_host_block(&self, cfg: &super::Config) -> Result> { + use super::hw::start_27_2 as s; + let g = self.generation.io(); + for &offset in cfg.host_block_zero_order { + let _ = g.try_read32(offset)?; + g.try_write32(0, offset)?; + } + let probe = if cfg.host_block_ready { + let probe = self.res.sgx_read32_at(s::SCRATCH_PROBE)?; + let _ = g.try_read32(s::HOST_READY)?; + g.try_write32(1, s::HOST_READY)?; + Some(probe) + } else { + None + }; + mb(); + Ok(probe) + } + /// ASC control word (`asc + 0x44`). pub(crate) fn asc_control(&self) -> Result { self.asc.io().try_read32(ASC_CONTROL) @@ -246,23 +350,56 @@ impl Regs { self.asc.io().try_write32(value, ASC_CONTROL) } - /// Engine receipts, under the device lock: busy is bit 0 of `C020 | C120`; the fault status - /// is `D8C0` under fault-bank selectors 0 and 1 (`D800`), with the saved selector restored. - /// 64-bit accesses. + /// Engine receipts for a running firmware, read only: busy is bit 0 of `C020 | C120`; the + /// fault status and address are `D8C0`/`D8C8` under the selector `D800` already holds. A + /// firmware that powers the GPU down while idle writes `D800` itself on the way down, so the + /// selector is not written here. 64-bit accesses. pub(crate) fn engine_state(&self) -> Result { let r = self.status.io(); - let mut state = EngineState { + Ok(EngineState { busy: (r.try_read64(0x20)? | r.try_read64(0x120)?) & 1, - ..Default::default() + bank: r.try_read64(0x1800)?, + status: r.try_read64(0x18c0)?, + address: r.try_read64(0x18c8)? << 6, + }) + } + + /// Engine receipts for a firmware halted for recovery and waiting on the host: reads all + /// supported fault banks in order, capturing status and address for every + /// non-zero bank, and restores the saved selector. + #[inline(never)] + pub(crate) fn fault_scan(&self) -> Result { + let r = self.status.io(); + let saved = r.try_read64(0x1800)?; + let busy = (r.try_read64(0x20)? | r.try_read64(0x120)?) & 1; + let mut scan = FaultScan { + busy, + saved_bank: saved, + bank_count: self.fault_banks, + banks: [EngineState::default(); MAX_FAULT_BANKS], }; - let sel = r.try_read64(0x1800)?; - for bank in 0..2 { - r.try_write64(bank as u64, 0x1800)?; - state.status[bank] = r.try_read64(0x18c0)?; - state.address[bank] = r.try_read64(0x18c8)? << 6; - } - r.try_write64(sel, 0x1800)?; - Ok(state) + let result = (|| -> Result { + for (idx, entry) in scan.banks[..scan.bank_count].iter_mut().enumerate() { + let bank = idx as u64; + r.try_write64(bank, 0x1800)?; + let status = r.try_read64(0x18c0)?; + let address = if status != 0 { + r.try_read64(0x18c8)? << 6 + } else { + 0 + }; + *entry = EngineState { + busy, + bank, + status, + address, + }; + } + Ok(()) + })(); + let restore = r.try_write64(saved, 0x1800); + result.and(restore)?; + Ok(scan) } } diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 77c47f0770492f..6b80ddcbf0570f 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -7,19 +7,159 @@ use super::{ command::Command, - object::{Factory, Objects}, + object::{Factory, FwObject, Objects}, pools::{PbEpoch, PoolSet}, - slots::{ComputeSlot, PassSlot}, + slots::{ComputeSlot, PassCmds, PassSlot, Placement, UnitCmds}, vm::VmState, + Shared, }; use crate::mmu; -use core::sync::atomic::{AtomicU64, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use kernel::{ - new_mutex, + new_condvar, new_mutex, new_spinlock_irq, prelude::*, - sync::{Arc, Mutex}, + sync::{Arc, CondVar, CondVarTimeoutResult, Mutex, SetOnce, SpinLockIrq}, }; +/// One pass slot index's device-lifetime render command records and the allocator that maps +/// them. The allocator is never dropped: an ASC-cached M4 mapping has no qualified teardown +/// (`mmu::KernelMapping::drop` refuses it), so even a failed construction keeps its mappings. +struct PersistentPassCmds { + objects: core::mem::ManuallyDrop, + cmds: Option, +} + +/// The firmware-cached render command records (work images, microsequences and barrier records) +/// of every pass slot index (`0..RENDER_SLOTS`), created on first use and kept until reboot. A +/// pass slot index is device-global and claimed by one flight at a time, so every VM's +/// [`PassSlot`] of an index shares its records, and closing a VM drops no firmware-cached +/// mapping. +#[pin_data] +pub(crate) struct RenderCmds { + #[pin] + sets: Mutex<[Option>; super::hw::sizes::RENDER_SLOTS]>, +} + +impl RenderCmds { + pub(crate) fn new() -> Result> { + Arc::pin_init( + pin_init!(Self { + sets <- new_mutex!( + [const { None }; super::hw::sizes::RENDER_SLOTS], + "g16::render_cmds" + ), + }), + GFP_KERNEL, + ) + } + + /// The records of pass slot index `k`, allocated from `factory` on first use. + pub(crate) fn get(&self, factory: &Factory, k: usize) -> Result { + let mut sets = self.sets.lock(); + let entry = sets.get_mut(k).ok_or(EINVAL)?; + if let Some(cmds) = entry.as_ref().and_then(|set| set.cmds.as_ref()) { + return Ok(cmds.clone()); + } + let mut set = KBox::new( + PersistentPassCmds { + objects: core::mem::ManuallyDrop::new(factory.persistent_objects()), + cmds: None, + }, + GFP_KERNEL, + )?; + // From here on a failure leaks the allocator with whatever it mapped. + let cmds = PassCmds::new(&mut set.objects, k as u64)?; + set.objects.finish_private()?; + set.cmds = Some(cmds.clone()); + *entry = Some(set); + Ok(cmds) + } +} + +/// One hardware compute unit's device-lifetime command records and the allocator that maps +/// them. The allocator is never dropped for the same reason as [`PersistentPassCmds`]; partial +/// allocations are retained in place so a retry finishes without leaking or duplicating pages. +struct PersistentUnitCmds { + objects: core::mem::ManuallyDrop, + work: Option>, + seq: Option>, + barrier: Option>, + finished: bool, +} + +/// The firmware-cached compute command records (work image, microsequence, and barrier records) +/// of every hardware compute unit (`0..COMPUTE_UNITS`), created on first use and kept until +/// reboot. A hardware compute unit is device-global and claimed by one flight at a time, so every +/// VM's [`ComputeSlot`] bound to hardware unit `k` shares its records, and closing a VM drops no +/// firmware-cached mapping. +#[pin_data] +pub(crate) struct ComputeCmds { + #[pin] + sets: Mutex<[Option>; super::hw::sizes::COMPUTE_UNITS]>, +} + +impl ComputeCmds { + pub(crate) fn new() -> Result> { + Arc::pin_init( + pin_init!(Self { + sets <- new_mutex!( + [const { None }; super::hw::sizes::COMPUTE_UNITS], + "g16::compute_cmds" + ), + }), + GFP_KERNEL, + ) + } + + /// The records of hardware compute unit `k`, allocated from `factory` on first use. + pub(crate) fn get(&self, factory: &Factory, k: usize) -> Result { + let mut sets = self.sets.lock(); + let entry = sets.get_mut(k).ok_or(EINVAL)?; + if entry.is_none() { + let slot = KBox::::new_uninit(GFP_KERNEL)?; + *entry = Some(KBox::write( + slot, + PersistentUnitCmds { + objects: core::mem::ManuallyDrop::new(factory.persistent_objects()), + work: None, + seq: None, + barrier: None, + finished: false, + }, + )); + } + let set: &mut PersistentUnitCmds = &mut **entry.as_mut().ok_or(EINVAL)?; + if set.finished { + if let (Some(work), Some(seq), Some(barrier)) = (&set.work, &set.seq, &set.barrier) { + return Ok(UnitCmds { + work: work.clone(), + seq: seq.clone(), + barrier: barrier.clone(), + }); + } + } + let cmds = UnitCmds::init_into( + &mut set.objects, + k as u64, + &mut set.work, + &mut set.seq, + &mut set.barrier, + )?; + set.objects.finish_private()?; + set.finished = true; + Ok(cmds) + } +} + +/// Never-exposed PB epochs an open VM keeps on standby after bursts drain. +/// +/// With PB epoch reuse most renders never expose a fresh epoch; keeping a +/// shared per-VM standby pool instead of attaching one epoch per queued job +/// avoids allocating and mapping fresh epochs whenever submission depth rises. +const SPARE_EPOCHS: usize = 32; + +/// Backing for one physical compute unit (`k`) of a VM, deferred-dropped independently so an +/// undisplaced last-retired owner lease on one CDM pipe never pins the VM's other compute units. pub(crate) struct ComputeArena(crate::cleanup::Deferred); impl core::ops::Deref for ComputeArena { type Target = ComputeInner; @@ -28,28 +168,54 @@ impl core::ops::Deref for ComputeArena { } } pub(crate) struct ComputeInner { - pub(crate) compute: KVec, + pub(crate) unit: ComputeSlot, _objects: Objects, // Mappings must disappear while their root still owns its ASID. _bind: mmu::VmBind, _live: Arc, } +/// Compute units every VM gets with its first compute command; more are added +/// ([`Cache::prepare`]) once it submits compute back to back. +pub(crate) const BASE_COMPUTE_UNITS: usize = 2; + +/// Back-to-back compute submissions (each within [`BURST_GAP_NS`] of the previous) after +/// which a VM gets its extension units; a single submission with [`BURST_COMMANDS`] compute +/// commands qualifies at once. +const BURST_SUBMITS: u32 = 3; +const BURST_GAP_NS: u64 = 2_000_000; +const BURST_COMMANDS: usize = 3; + impl ComputeArena { + /// Freelist entries of the unit's UMA pool. + pub(crate) fn seeds(&self) -> u32 { + self.unit.seeds + } + /// Allocates one self-contained compute unit at local VA index `local` bound to device-wide + /// hardware ledger slot `hw_slot` (`local` and `placement` fix its client addresses; `hw_slot` + /// selects its shared device-lifetime command records). fn new( factory: &Factory, bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, + local: usize, + hw_slot: usize, + placement: Placement, ) -> Result> { + let cmds = factory.compute_cmds(hw_slot)?; let mut objects = factory.objects(vm); - let mut compute = KVec::with_capacity(2, GFP_KERNEL)?; - for k in 0..2 { - compute.push(ComputeSlot::new(&mut objects, k)?, GFP_KERNEL)?; - } + let unit = ComputeSlot::new_in( + &mut objects, + factory, + local as u64, + hw_slot as u32, + placement, + &cmds, + )?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(ComputeInner { - compute, + unit, _objects: objects, _bind: bind.clone(), _live: live.clone(), @@ -59,6 +225,348 @@ impl ComputeArena { } } +/// Contiguous range of independently reference-counted [`ComputeArena`] units owned by a VM. +/// +/// Each unit `k` owns its own `Arc` so `Cache::close()` and +/// `Slots::reclaim_closed()` release all unused or displaced units immediately even while a +/// CDM pipe retains one undisplaced last-retired unit until displacement. +pub(crate) struct ComputeUnitSet { + units: KVec>, + /// Device-wide compute ledger indices bound to local SCS units `0..SCS_COMPUTE_UNITS`, or + /// `None` for contiguous base/extension sets whose local index equals the ledger index. + hw_slots: Option<[usize; super::hw::sizes::SCS_COMPUTE_UNITS]>, +} +impl ComputeUnitSet { + /// Units `range` (each index and `placement` fix its client addresses; the index fixes its + /// hardware UMA slot). + fn new( + factory: &Factory, + bind: &mmu::VmBind, + vm: &mmu::Vm, + live: &Arc, + range: core::ops::Range, + placement: Placement, + ) -> Result> { + let mut units = KVec::with_capacity(range.len(), GFP_KERNEL)?; + for k in range { + units.push( + ComputeArena::new(factory, bind, vm, live, k, k, placement)?, + GFP_KERNEL, + )?; + } + Ok(Arc::new( + Self { + units, + hw_slots: None, + }, + GFP_KERNEL, + )?) + } + /// SCS-capable compute units mapped at local VA indices `0..SCS_COMPUTE_UNITS` and bound to + /// device-wide healthy compute ledger indices `hw_slots`. + fn new_scs( + factory: &Factory, + bind: &mmu::VmBind, + vm: &mmu::Vm, + live: &Arc, + hw_slots: [usize; super::hw::sizes::SCS_COMPUTE_UNITS], + seeds: u32, + ) -> Result> { + let mut units = KVec::with_capacity(super::hw::sizes::SCS_COMPUTE_UNITS, GFP_KERNEL)?; + for (local, &hw_slot) in hw_slots.iter().enumerate() { + units.push( + ComputeArena::new( + factory, + bind, + vm, + live, + local, + hw_slot, + Placement::Scs { seeds }, + )?, + GFP_KERNEL, + )?; + } + Ok(Arc::new( + Self { + units, + hw_slots: Some(hw_slots), + }, + GFP_KERNEL, + )?) + } + fn len(&self) -> usize { + self.units.len() + } + /// Freelist entries of the set's UMA pools (all its units share a placement). + pub(crate) fn seeds(&self) -> u32 { + self.units.first().map_or(0, |arena| arena.seeds()) + } + fn unit(&self, idx: usize) -> Option<&ComputeSlot> { + self.units.get(idx).map(|arena| &arena.unit) + } + fn arena(&self, idx: usize) -> Option> { + self.units.get(idx).cloned() + } +} + +/// Render pass slots every VM gets with its first render command; extension slots +/// (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`) are grown lazily in bounded tiers once the VM +/// pipelines renders or submits multi-pass/burst frames. +pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; +/// Demand-grown extension render pass slot tiers (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`). +/// +/// Each extension `PassSlot` backs 3.44 MiB (2 MiB TPC + 1 MiB tilemap + 448 KiB metadata and +/// scratch; its work images, microsequences and barriers are the device-lifetime [`RenderCmds`] +/// of its index). Growing in four bounded chunks keeps compositor and shallow desktop VMs on +/// Tier 0 (~20.6 MiB), keeps 20-31 pass workloads on Tier 2 without paying for 48 slots, and +/// keeps every tier's client-object batch well below `MAX_CLIENT` (512): +/// - Tier 0 (`2..8`, 6 slots, +20.63 MiB / 20.63 MiB cum): compositors, 2-6 pass frames. +/// - Tier 1 (`8..18`, 10 slots, +34.38 MiB / 55.00 MiB cum): moderate multi-pass bursts. +/// - Tier 2 (`18..32`, 14 slots, +48.13 MiB / 103.13 MiB cum): 20-31 pass pipelined frames. +/// - Tier 3 (`32..RENDER_SLOTS`, 16 slots, +55.00 MiB / 158.13 MiB cum at 48 slots): deep +/// multi-pass bursts (160 client mappings <= `MAX_CLIENT`). +pub(crate) const EXT_RENDER_TIERS: [(usize, usize); 4] = [ + (BASE_RENDER_SLOTS, 8), + (8, 18), + (18, 32), + (32, super::hw::sizes::RENDER_SLOTS), +]; +const _: () = assert!(EXT_RENDER_TIERS[0].0 == BASE_RENDER_SLOTS); +const _: () = assert!(EXT_RENDER_TIERS[0].1 == EXT_RENDER_TIERS[1].0); +const _: () = assert!(EXT_RENDER_TIERS[1].1 == EXT_RENDER_TIERS[2].0); +const _: () = assert!(EXT_RENDER_TIERS[2].1 == EXT_RENDER_TIERS[3].0); +const _: () = assert!(EXT_RENDER_TIERS[3].1 == super::hw::sizes::RENDER_SLOTS); +const BASE_PB_SLOTS: usize = super::hw::sizes::BASE_PB_SLOTS; +const EXT_PB_SLOTS: usize = super::hw::sizes::EXT_PB_SLOTS; +/// Demand-grown contiguous PB heap extensions within the 256 MiB +/// [`super::hw::client::PB_HEAP_SIZE`] window so steady 60/120 Hz single-pass clients stay on +/// the 64 MiB base heap while multi-pass and heavy 3D workloads expand to 128 MiB (Tier 0) and +/// 256 MiB (Tier 1) without TVB partial-render spills. +pub(crate) const PB_HEAP_EXT_TIERS: [(u32, u32); 2] = + [(512, 1024), (1024, super::fw::buffer::MAX_BLOCKS)]; +const _: () = assert!(PB_HEAP_EXT_TIERS[0].1 == PB_HEAP_EXT_TIERS[1].0); +const _: () = assert!(PB_HEAP_EXT_TIERS[1].1 == super::fw::buffer::MAX_BLOCKS); +const _: () = assert!( + (PB_HEAP_EXT_TIERS[1].1 as u64) * super::fw::buffer::BLOCK_BYTES + <= super::hw::client::PB_HEAP_SIZE +); +/// Single-submission render command count that expands Tier 0 extension slots immediately: +/// `BASE_RENDER_SLOTS` holds only one active render once displacement occupies a slot. +const RENDER_BURST_COMMANDS: usize = BASE_RENDER_SLOTS; + +/// Device-wide hints read locklessly in `SUBMIT` to size per-VM extension backing. +#[derive(Copy, Clone)] +pub(crate) struct PrepareHints<'a> { + /// A base compute unit (`0..BASE_COMPUTE_UNITS`) is quarantined: allocate extension units. + pub(crate) expand_compute_ext: bool, + /// Bitmask of permanently quarantined device-wide compute units (`0..COMPUTE_UNITS`). + pub(crate) quarantined_compute_mask: u32, + /// A base render pass slot (`0..BASE_RENDER_SLOTS`) is quarantined: allocate extension slots. + pub(crate) expand_render_ext: bool, + /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). + pub(crate) quarantined_pb_mask: u32, + /// Round-robin cursor assigning a VM's `[home, alt]` base PB/UMA slots in `0..WARM_PB_SLOTS`. + pub(crate) next_pb_slot: &'a AtomicU32, + /// Live open VMs owning a `RenderArena`, used for multi-VM pass-slot headroom. + pub(crate) active_render_vms: &'a Arc, +} + +/// Selects `SCS_COMPUTE_UNITS` distinct hardware compute ledger indices for a VM's SCS compute +/// set, skipping permanently quarantined units in `quarantined_mask`. Scans from `0` up so +/// pipe-0-exclusive units (`0..PIPE1_COMPUTE_START`) are preferred before falling back to +/// `PIPE1_COMPUTE_START..max_units`. +fn pick_scs_compute_slots( + quarantined_mask: u32, + max_units: usize, +) -> [usize; super::hw::sizes::SCS_COMPUTE_UNITS] { + let limit = max_units + .min(super::hw::sizes::COMPUTE_UNITS) + .max(super::hw::sizes::SCS_COMPUTE_UNITS); + let mut out = [0usize; super::hw::sizes::SCS_COMPUTE_UNITS]; + let mut found = 0usize; + for k in 0..limit { + if (quarantined_mask & (1u32 << k)) == 0 { + out[found] = k; + found += 1; + if found == out.len() { + return out; + } + } + } + for k in 0..limit { + if !out[..found].contains(&k) { + out[found] = k; + found += 1; + if found == out.len() { + return out; + } + } + } + out +} + +/// Selects `[home, alt]` distinct physical PB/UMA allocator slots for a new `RenderArena`, +/// starting round-robin from `start % WARM_PB_SLOTS` and skipping permanently quarantined slots +/// in `quarantined_mask`. Scans `0..WARM_PB_SLOTS` first, then `WARM_PB_SLOTS..PB_SLOTS`, so +/// both base and `render_scs` VMs always start with two healthy PB slots after recovery. +fn pick_base_pb_slots(start: usize, quarantined_mask: u32) -> [usize; BASE_PB_SLOTS] { + let warm = super::hw::sizes::WARM_PB_SLOTS; + let total = super::hw::sizes::PB_SLOTS; + let mut out = [0usize; BASE_PB_SLOTS]; + let mut found = 0usize; + for i in 0..warm { + let slot = (start + i) % warm; + if (quarantined_mask & (1u32 << slot)) == 0 { + out[found] = slot; + found += 1; + if found == out.len() { + return out; + } + } + } + for slot in warm..total { + if (quarantined_mask & (1u32 << slot)) == 0 { + out[found] = slot; + found += 1; + if found == out.len() { + return out; + } + } + } + for i in 0..total { + let slot = (start + i) % total; + if !out[..found].contains(&slot) { + out[found] = slot; + found += 1; + if found == out.len() { + return out; + } + } + } + out +} + +/// Updates the consecutive-compute burst counter and reports whether this submission +/// qualifies to allocate extension compute units (`compute_ext`). +/// +/// If a base compute unit (`0..BASE_COMPUTE_UNITS`) has been permanently quarantined, fresh +/// single-command VMs must expand immediately so they can claim a healthy extension unit and +/// displace the remaining retired base unit rather than hitting `compute_exhausted_within(2)`. +fn should_expand_compute_ext( + last_compute_ns: &mut u64, + burst: &mut u32, + now: u64, + computes: usize, + base_quarantined: bool, +) -> bool { + *burst = if *last_compute_ns != 0 && now.wrapping_sub(*last_compute_ns) < BURST_GAP_NS { + burst.saturating_add(1) + } else { + 0 + }; + *last_compute_ns = now; + base_quarantined || *burst >= BURST_SUBMITS || computes >= BURST_COMMANDS +} + +/// Updates the consecutive-render burst counter and returns the target render pass slot count +/// (`BASE_RENDER_SLOTS..=hw::sizes::RENDER_SLOTS`) this VM should have backed before admission. +/// +/// Steady 60/120 Hz single-pass depth-1 clients finish each frame before the next arrives +/// (`active_passes == 0`, `render_count == 1`, inter-frame gap >= `BURST_GAP_NS`) and stay +/// on the two base pass slots (~48.9 MiB). Extension tiers grow on demand: Tier 0 (`2..8`, +/// +20.6 MiB) allocates when a base pass slot is quarantined, a VM overlaps an in-flight render, +/// submits a multi-pass command stream (`render_count >= BASE_RENDER_SLOTS`), or sustains a +/// sub-2 ms back-to-back burst; higher tiers allocate only when live passes plus this submission +/// and one displacement slot exceed the currently backed capacity. +fn target_render_slots( + last_render_ns: &mut u64, + render_burst: &mut u32, + now: u64, + render_count: usize, + active_passes: u32, + base_quarantined: bool, + current_slots: usize, +) -> usize { + *render_burst = if *last_render_ns != 0 && now.wrapping_sub(*last_render_ns) < BURST_GAP_NS { + render_burst.saturating_add(1) + } else { + 0 + }; + *last_render_ns = now; + let live_need = (active_passes as usize) + .saturating_add(render_count) + .saturating_add(1); + let want = if current_slots <= BASE_RENDER_SLOTS { + if base_quarantined + || active_passes != 0 + || *render_burst >= BURST_SUBMITS + || render_count >= RENDER_BURST_COMMANDS + { + live_need.max(BASE_RENDER_SLOTS + 1) + } else { + BASE_RENDER_SLOTS + } + } else { + live_need + }; + let mut target = current_slots.max(BASE_RENDER_SLOTS); + for &(start, end) in &EXT_RENDER_TIERS { + if target >= want { + break; + } + if target < end && want > start { + target = end; + } + } + target.min(super::hw::sizes::RENDER_SLOTS) +} + +/// Like [`target_render_slots`], returning `(effective_target, single_vm_target)`. +/// +/// When `active_render_vms` reaches Tier 0's pass-slot ceiling (`EXT_RENDER_TIERS[0].1 == 8`) +/// and this VM is already bursting (`single_vm_target > BASE_RENDER_SLOTS`), `effective_target` +/// expands up to Tier 1 (`EXT_RENDER_TIERS[1].1 == 18`) so up to 16 concurrent render VMs each +/// keep a warm pass slot without cross-VM full-scrub thrashing. Steady 60/120 Hz single-pass +/// clients stay at `BASE_RENDER_SLOTS`, and `single_vm_target` keeps `PB_HEAP_EXT_TIERS` gated +/// on actual single-VM pass demand so multi-VM light renders do not expand to 256 MiB PB heaps. +fn target_render_slots_for( + last_render_ns: &mut u64, + render_burst: &mut u32, + now: u64, + render_count: usize, + active_passes: u32, + base_quarantined: bool, + current_slots: usize, + single_vm_slots: usize, + active_render_vms: u32, +) -> (usize, usize) { + let single = target_render_slots( + last_render_ns, + render_burst, + now, + render_count, + active_passes, + base_quarantined, + single_vm_slots.max(BASE_RENDER_SLOTS), + ); + let mut target = current_slots.max(single); + if single > BASE_RENDER_SLOTS && (active_render_vms as usize) >= EXT_RENDER_TIERS[0].1 { + let multi_need = (active_render_vms as usize) + .saturating_add(1) + .min(EXT_RENDER_TIERS[1].1); + for &(start, end) in &EXT_RENDER_TIERS[..2] { + if target >= multi_need { + break; + } + if target < end && multi_need > start { + target = end; + } + } + } + (target.min(super::hw::sizes::RENDER_SLOTS), single) +} + pub(crate) struct RenderArena(crate::cleanup::Deferred); impl core::ops::Deref for RenderArena { type Target = RenderInner; @@ -66,35 +574,65 @@ impl core::ops::Deref for RenderArena { &self.0 } } +/// The SCS-capable render allocators of a render arena and the mappings they own. +pub(crate) struct ScsPools { + pub(crate) pools: PoolSet, + _objects: Objects, +} + pub(crate) struct RenderInner { pub(crate) passes: KVec, pub(crate) pools: PoolSet, - pub(crate) tpc_dirty: [AtomicU64; 2], - pub(crate) tilemap_dirty: [AtomicU64; 2], + /// Device-wide physical PB/UMA allocator slots `[home, alt]` bound to `pools.unit(0..2)`. + pub(crate) base_pb_slots: [usize; BASE_PB_SLOTS], + /// [`PoolSet::scs`], with the VM's first render that has scratch. Held with the arena, so + /// a pass slot's owner lease keeps it too. Dropped before the arena's own mappings. + pub(crate) scs: SetOnce, + pub(crate) tpc_dirty: [AtomicU64; BASE_RENDER_SLOTS], + pub(crate) tilemap_dirty: [AtomicU64; BASE_RENDER_SLOTS], + pub(crate) tilemap_last: [AtomicU64; BASE_RENDER_SLOTS], + pub(crate) tilemap_clean: [AtomicU64; BASE_RENDER_SLOTS], + pub(crate) heap_dirty: [AtomicU64; BASE_RENDER_SLOTS], _objects: Objects, _bind: mmu::VmBind, _live: Arc, } +/// Per-pass dirty and pre-cleaned WC byte spans for one render pass slot. +#[derive(Copy, Clone)] +pub(crate) struct PassDirty<'a> { + pub(crate) tpc: &'a AtomicU64, + pub(crate) tilemap: &'a AtomicU64, + pub(crate) tilemap_last: &'a AtomicU64, + pub(crate) tilemap_clean: &'a AtomicU64, + pub(crate) heap: &'a AtomicU64, +} impl RenderArena { fn new( factory: &Factory, bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, + base_pb_slots: [usize; BASE_PB_SLOTS], ) -> Result> { let mut objects = factory.objects(vm); - let mut passes = KVec::with_capacity(2, GFP_KERNEL)?; - for k in 0..2 { - passes.push(PassSlot::new(&mut objects, k, 1)?, GFP_KERNEL)?; + let mut passes = KVec::with_capacity(BASE_RENDER_SLOTS, GFP_KERNEL)?; + for k in 0..BASE_RENDER_SLOTS { + let cmds = factory.pass_cmds(k)?; + passes.push(PassSlot::new(&mut objects, k as u64, 1, &cmds)?, GFP_KERNEL)?; } - let pools = PoolSet::new(&mut objects)?; + let pools = PoolSet::new_with_slots(&mut objects, factory, base_pb_slots)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(RenderInner { passes, pools, - tpc_dirty: [const { AtomicU64::new(0) }; 2], - tilemap_dirty: [const { AtomicU64::new(0) }; 2], + base_pb_slots, + scs: SetOnce::new(), + tpc_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], + tilemap_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], + tilemap_last: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], + tilemap_clean: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], + heap_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], _objects: objects, _bind: bind.clone(), _live: live.clone(), @@ -102,6 +640,30 @@ impl RenderArena { GFP_KERNEL, )?) } + /// Creates the SCS-capable render allocators with pools of `seeds.pool` entries unless + /// they exist. Existing ones must hold `seeds.needed`: once the hardware may hold them they + /// cannot grow (E2BIG). Called under the VM cache's construction mutex, before any job uses + /// them. + fn ensure_scs(&self, factory: &Factory, vm: &mmu::Vm, seeds: super::rt::ScsSeeds) -> Result { + if let Some(scs) = self.scs.as_ref() { + return if scs.pools.seeds() >= seeds.needed { + Ok(()) + } else { + Err(E2BIG) + }; + } + let mut objects = factory.objects(vm); + let pools = self.pools.scs(&mut objects, factory, seeds.pool)?; + objects.finish_private()?; + // The construction mutex excludes a second populate. + if !self.scs.populate(ScsPools { + pools, + _objects: objects, + }) { + return Err(EBUSY); + } + Ok(()) + } pub(crate) fn set_dirty(&self, k: usize, tpc: u64, tilemap: u64) -> Result { let pass = self.passes.get(k).ok_or(EINVAL)?; if tpc > pass.tpc.size as u64 || tilemap > pass.tilemap.size as u64 { @@ -109,112 +671,1146 @@ impl RenderArena { } self.tpc_dirty[k].fetch_max(tpc, Ordering::Relaxed); self.tilemap_dirty[k].fetch_max(tilemap, Ordering::Relaxed); + self.tilemap_last[k].store(tilemap, Ordering::Relaxed); + self.tilemap_clean[k].store(0, Ordering::Relaxed); + self.heap_dirty[k].fetch_max(0x200, Ordering::Relaxed); Ok(()) } } +/// One demand-grown tier of extension render pass slots (`slots`), allocated lazily so idle, +/// single-pass, and shallow multi-pass VMs back only the tiers their concurrency requires. +pub(crate) struct RenderExtArena(crate::cleanup::Deferred); +impl core::ops::Deref for RenderExtArena { + type Target = RenderExtInner; + fn deref(&self) -> &Self::Target { + &self.0 + } +} +pub(crate) struct RenderExtInner { + pub(crate) start: usize, + pub(crate) passes: KVec, + pub(crate) tpc_dirty: KVec, + pub(crate) tilemap_dirty: KVec, + pub(crate) tilemap_last: KVec, + pub(crate) tilemap_clean: KVec, + pub(crate) heap_dirty: KVec, + _objects: Objects, + _bind: mmu::VmBind, + _live: Arc, +} +impl RenderExtArena { + fn new( + factory: &Factory, + bind: &mmu::VmBind, + vm: &mmu::Vm, + live: &Arc, + slots: core::ops::Range, + ) -> Result> { + let count = slots.len(); + let mut objects = factory.objects(vm); + let mut passes = KVec::with_capacity(count, GFP_KERNEL)?; + let mut tpc_dirty = KVec::with_capacity(count, GFP_KERNEL)?; + let mut tilemap_dirty = KVec::with_capacity(count, GFP_KERNEL)?; + let mut tilemap_last = KVec::with_capacity(count, GFP_KERNEL)?; + let mut tilemap_clean = KVec::with_capacity(count, GFP_KERNEL)?; + let mut heap_dirty = KVec::with_capacity(count, GFP_KERNEL)?; + for k in slots.clone() { + let cmds = factory.pass_cmds(k)?; + passes.push(PassSlot::new(&mut objects, k as u64, 1, &cmds)?, GFP_KERNEL)?; + tpc_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; + tilemap_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; + tilemap_last.push(AtomicU64::new(0), GFP_KERNEL)?; + tilemap_clean.push(AtomicU64::new(0), GFP_KERNEL)?; + heap_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; + } + objects.finish_private()?; + Ok(Arc::new( + Self(crate::cleanup::Deferred::new(RenderExtInner { + start: slots.start, + passes, + tpc_dirty, + tilemap_dirty, + tilemap_last, + tilemap_clean, + heap_dirty, + _objects: objects, + _bind: bind.clone(), + _live: live.clone(), + })?), + GFP_KERNEL, + )?) + } +} + +/// One lazily allocated recovery PB/UMA allocator slot (`WARM_PB_SLOTS..PB_SLOTS`), +/// mapped at per-VM local VA index `BASE_PB_SLOTS..MAX_VM_PB_SLOTS` and sharing the VM's base PB +/// heap so non-fault VMs pay zero extra allocator memory. +pub(crate) struct PoolExtArena(crate::cleanup::Deferred); +impl core::ops::Deref for PoolExtArena { + type Target = PoolExtInner; + fn deref(&self) -> &Self::Target { + &self.0 + } +} +pub(crate) struct PoolExtInner { + pub(crate) allocator: super::pools::Allocator, + _objects: Objects, + _bind: mmu::VmBind, + _live: Arc, +} +impl PoolExtArena { + fn new( + factory: &Factory, + bind: &mmu::VmBind, + vm: &mmu::Vm, + live: &Arc, + local_idx: usize, + hw_slot: usize, + heap: &Arc, + ) -> Result> { + let mut objects = factory.objects(vm); + let allocator = super::pools::Allocator::new_at( + &mut objects, + factory, + local_idx as u64, + hw_slot as u32, + heap, + Placement::Base, + )?; + objects.finish_private()?; + Ok(Arc::new( + Self(crate::cleanup::Deferred::new(PoolExtInner { + allocator, + _objects: objects, + _bind: bind.clone(), + _live: live.clone(), + })?), + GFP_KERNEL, + )?) + } +} + +/// One demand-grown contiguous PB heap chunk extending the VM's base [`PoolSet`] heap within the +/// 256 MiB `PB_HEAP_SIZE` GPU VA window without unmapping any in-flight lower range. +pub(crate) struct PbHeapExtArena(crate::cleanup::Deferred); +impl core::ops::Deref for PbHeapExtArena { + type Target = PbHeapExtInner; + fn deref(&self) -> &Self::Target { + &self.0 + } +} +pub(crate) struct PbHeapExtInner { + pub(crate) blocks: u32, + _heap: Arc, + _objects: Objects, + _bind: mmu::VmBind, + _live: Arc, +} +impl PbHeapExtArena { + fn new( + factory: &Factory, + bind: &mmu::VmBind, + vm: &mmu::Vm, + live: &Arc, + start_block: u32, + blocks: u32, + ) -> Result> { + let mut objects = factory.objects(vm); + let heap = super::pools::alloc_pb_heap_chunk(&mut objects, start_block, blocks)?; + objects.finish_private()?; + Ok(Arc::new( + Self(crate::cleanup::Deferred::new(PbHeapExtInner { + blocks, + _heap: heap, + _objects: objects, + _bind: bind.clone(), + _live: live.clone(), + })?), + GFP_KERNEL, + )?) + } +} + +/// Keeps the arenas owning a retained PB/UMA allocator slot and its backed PB heap tiers alive +/// through displacement. The wrapped `Arc`s are held solely for their `Drop` lifetime and never +/// read back. +#[derive(Clone)] +#[allow(dead_code)] +pub(crate) enum PbOwnerArena { + Base( + Arc, + [Option>; PB_HEAP_EXT_TIERS.len()], + ), + Ext( + Arc, + Arc, + [Option>; PB_HEAP_EXT_TIERS.len()], + ), +} + +/// Keeps the arena owning a retained pass slot alive through displacement. +#[derive(Clone)] +pub(crate) enum PassOwnerArena { + Base(Arc), + Ext(Arc), +} + +impl PassOwnerArena { + /// Returns the pass slot and its dirty/clean WC span trackers for global slot `k`. + pub(crate) fn pass_and_dirty(&self, k: usize) -> Option<(&PassSlot, PassDirty<'_>)> { + match self { + Self::Base(arena) => Some(( + arena.passes.get(k)?, + PassDirty { + tpc: arena.tpc_dirty.get(k)?, + tilemap: arena.tilemap_dirty.get(k)?, + tilemap_last: arena.tilemap_last.get(k)?, + tilemap_clean: arena.tilemap_clean.get(k)?, + heap: arena.heap_dirty.get(k)?, + }, + )), + Self::Ext(arena) => { + let idx = k.checked_sub(arena.start)?; + Some(( + arena.passes.get(idx)?, + PassDirty { + tpc: arena.tpc_dirty.get(idx)?, + tilemap: arena.tilemap_dirty.get(idx)?, + tilemap_last: arena.tilemap_last.get(idx)?, + tilemap_clean: arena.tilemap_clean.get(idx)?, + heap: arena.heap_dirty.get(idx)?, + }, + )) + } + } + } +} + #[derive(Default)] struct Ready { - compute: Option>, + compute: Option>, + /// Units from [`BASE_COMPUTE_UNITS`] on, for a VM that keeps compute queued. + compute_ext: Option>, + /// SCS-capable units, for jobs with compute scratch. + compute_scs: Option>, render: Option>, + /// Demand-grown extension render pass tiers (`EXT_RENDER_TIERS`). + render_ext: [Option>; EXT_RENDER_TIERS.len()], + /// Demand-grown contiguous PB heap extension tiers (`PB_HEAP_EXT_TIERS`). + pb_heap_ext: [Option>; PB_HEAP_EXT_TIERS.len()], + /// Recovery PB/UMA allocator slots (`WARM_PB_SLOTS..PB_SLOTS`), allocated lazily after hangs. + pb_ext: [Option>; EXT_PB_SLOTS], + /// Single-VM render pass slot target (excluding multi-VM Tier 1 expansion), gating + /// `PB_HEAP_EXT_TIERS` so concurrent light-render VMs do not allocate 256 MiB PB heaps. + single_vm_render_slots: usize, + /// Device-wide count of open rendering VMs; decremented once on `Cache::close()` or drop. + render_vm_counter: Option>, + /// Last compute submission and the back-to-back run it continues. + last_compute_ns: u64, + burst: u32, + /// Last render submission and the back-to-back run it continues. + last_render_ns: u64, + render_burst: u32, } +impl Drop for Ready { + fn drop(&mut self) { + if let Some(counter) = self.render_vm_counter.take() { + counter.fetch_sub(1, Ordering::AcqRel); + } + } +} +struct Standby { + /// Never-exposed epochs kept on standby for this VM's queued renders. + /// Invariant: while open or while `reserved > 0`, `epochs.len() >= reserved as usize`. + epochs: KVec>, + /// Accepted, not-yet-published render commands of this VM. + reserved: u32, + /// `SUBMIT` callers currently sleeping on `standby_available`. + waiters: u32, +} + #[pin_data] pub(crate) struct Cache { #[pin] ready: Mutex, + /// Shared per-VM standby pool of never-exposed PB epochs. Each holds the VM, which + /// holds this cache: [`Self::close`] drains surplus epochs immediately and the remaining + /// reserved epochs as accepted renders finish. + #[pin] + standby: SpinLockIrq, + /// Wakes `SUBMIT` callers waiting for standby reservation headroom. + #[pin] + standby_available: CondVar, + /// The VM's client closed: no arena or surplus spare is kept here any more. + closed: AtomicBool, + /// Render passes across prepared jobs on this VM that have not yet retired and dropped. + active_render_passes: AtomicU32, pub(crate) factory: Factory, bind: mmu::VmBind, live: Arc, budget: Arc, + shared: Arc, } impl Cache { pub(crate) fn new( factory: Factory, bind: mmu::VmBind, live: Arc, + shared: Arc, ) -> Result> { let budget = super::budget::Budget::new()?; + let epochs = KVec::with_capacity(super::budget::LIMIT as usize, GFP_KERNEL)?; Arc::pin_init( pin_init!(Self { ready <- new_mutex!(Ready::default(), "g16::resources"), - factory, bind, live, budget }), + standby <- new_spinlock_irq!( + Standby { + epochs, + reserved: 0, + waiters: 0, + }, + "g16::spare_epochs" + ), + standby_available <- new_condvar!(), + closed: AtomicBool::new(false), + active_render_passes: AtomicU32::new(0), + factory, bind, live, budget, shared }), GFP_KERNEL, ) } - pub(crate) fn prepare(&self, vm: &Arc, commands: &[Command]) -> Result { - let compute = commands.iter().any(|c| matches!(c, Command::Compute(_))); - let render_count = commands + + /// Pops one never-exposed standby epoch for a fresh InitBM publication. + fn take_standby(&self) -> Result> { + let mut standby = self.standby.lock(); + while let Some(epoch) = standby.epochs.pop() { + if epoch.unexposed() { + return Ok(epoch); + } + } + Err(EINVAL) + } + + /// Returns a never-exposed epoch whose publication was deferred or failed before visibility. + fn return_standby(&self, epoch: Arc) { + if !epoch.unexposed() { + return; + } + let overflow = { + let mut standby = self.standby.lock(); + let keep = if self.closed.load(Ordering::Acquire) { + standby.reserved as usize + } else { + super::budget::LIMIT as usize + }; + if standby.epochs.len() < keep { + standby.epochs.push_within_capacity(epoch).err().map(|e| e.0) + } else { + Some(epoch) + } + }; + drop(overflow); + } + + /// Releases `count` reserved render credits and trims any surplus standby epochs outside + /// the spinlock (each `PbEpoch` defers its own unmap, so dropping here never sleeps). + fn release_reserved(&self, count: u32) { + if count == 0 { + return; + } + let (mut wake, reclaim, excess) = { + let mut standby = self.standby.lock(); + standby.reserved = standby.reserved.saturating_sub(count); + let wake = standby.waiters != 0; + let closed = self.closed.load(Ordering::Acquire); + let reclaim = closed && standby.reserved == 0; + let keep = if closed { + standby.reserved as usize + } else { + (standby.reserved as usize).max(SPARE_EPOCHS) + }; + let excess = if standby.epochs.len() > keep { + standby.epochs.pop() + } else { + None + }; + (wake, reclaim, excess) + }; + if let Some(excess) = excess { + drop(excess); + // Subsequent iterations only trim remaining surplus; count was already subtracted. + loop { + let more = { + let mut standby = self.standby.lock(); + wake |= standby.waiters != 0; + let keep = if self.closed.load(Ordering::Acquire) { + standby.reserved as usize + } else { + (standby.reserved as usize).max(SPARE_EPOCHS) + }; + if standby.epochs.len() > keep { + standby.epochs.pop() + } else { + None + } + }; + if more.is_none() { + break; + } + drop(more); + } + } + if wake { + self.standby_available.notify_all(); + } + if reclaim { + self.shared.wake_closed_vm_reclaim(); + } + } + + fn release_render_passes(&self, count: u32) { + let previous = self.active_render_passes.fetch_sub(count, Ordering::AcqRel); + debug_assert!(previous >= count); + } + + /// Whether accepted renders still hold standby reservations, that is, are not yet + /// published ([`Prepared::commit_render`]) or dropped. + pub(crate) fn renders_unpublished(&self) -> bool { + self.standby.lock().reserved != 0 + } + + /// The VM's client closed. Lets go of the arenas and surplus standby epochs: accepted + /// renders keep only the exact standby count they reserved until they finish, and hardware + /// slots hold their own last-owner leases. + pub(crate) fn close(&self) { + self.closed.store(true, Ordering::Release); + loop { + let excess = { + let mut standby = self.standby.lock(); + let keep = standby.reserved as usize; + if standby.epochs.len() > keep { + standby.epochs.pop() + } else { + None + } + }; + if excess.is_none() { + break; + } + drop(excess); + } + self.standby_available.notify_all(); + let ready = { + let mut ready = self.ready.lock(); + if let Some(counter) = ready.render_vm_counter.take() { + counter.fetch_sub(1, Ordering::AcqRel); + } + ( + ready.compute.take(), + ready.compute_ext.take(), + ready.compute_scs.take(), + ready.render.take(), + core::mem::take(&mut ready.render_ext), + core::mem::take(&mut ready.pb_heap_ext), + core::mem::take(&mut ready.pb_ext), + ) + }; + drop(ready); + } + + pub(crate) fn prepare( + self: &Arc, + vm: &Arc, + commands: &[Command], + hints: PrepareHints<'_>, + ) -> Result { + let computes = commands .iter() - .filter(|c| matches!(c, Command::Render(_))) + .filter(|c| matches!(c, Command::Compute(_))) .count(); + let compute = computes != 0; + let render_count: u32 = commands + .iter() + .filter(|c| matches!(c, Command::Render(_))) + .count() + .try_into()?; let render = render_count != 0; - let mut epochs = super::budget::Budget::reserve(&self.budget, render_count.try_into()?)?; - let (compute, render) = { - // Never held by publication, completion, recovery or fence signalling. + // Scratch is sized on top of a pool's base pages: such a job runs on SCS-capable + // storage, for all its commands of that engine, whose pools hold the largest of them. + let scs = |engine: fn(&Command) -> bool| { + commands + .iter() + .filter(|&c| engine(c)) + .map(Command::scs) + .fold(super::rt::ScsSeeds::NONE, |a, b| super::rt::ScsSeeds { + needed: a.needed.max(b.needed), + pool: a.pool.max(b.pool).max(b.needed), + }) + }; + let compute_seeds = scs(|c| matches!(c, Command::Compute(_))); + let render_seeds = scs(|c| matches!(c, Command::Render(_))); + let compute_scs = compute_seeds.needed != 0; + let render_scs = render_seeds.needed != 0; + let (compute, compute_ext, render_arena, render_ext, pb_heap_ext, pb_ext) = { + // Never held by publication, completion, recovery, fence signalling or + // standby waits, so Cache::close() and same-VM compute SUBMITs never block. let mut ready = self.ready.lock(); - if vm.status.get() != 0 || vm.vm.is_closed() { + if vm.status.get() != 0 || vm.vm.is_closed() || self.closed.load(Ordering::Acquire) { return Err(EIO); } - if compute && ready.compute.is_none() { - ready.compute = Some(ComputeArena::new( + if compute && !compute_scs && ready.compute.is_none() { + ready.compute = Some(ComputeUnitSet::new( &self.factory, &self.bind, &vm.vm, &self.live, + 0..BASE_COMPUTE_UNITS, + Placement::Base, )?); } + if compute_scs { + match ready.compute_scs.as_ref().map(|set| set.seeds()) { + None => { + let hw_slots = pick_scs_compute_slots( + hints.quarantined_compute_mask, + super::params::compute_units(), + ); + ready.compute_scs = Some(ComputeUnitSet::new_scs( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + hw_slots, + compute_seeds.pool, + )?); + } + // The units cannot grow once the hardware may hold them. + Some(seeds) if seeds < compute_seeds.needed => return Err(E2BIG), + Some(_) => {} + } + } + if compute && !compute_scs && ready.compute_ext.is_none() { + let units = super::params::compute_units(); + if units > BASE_COMPUTE_UNITS { + // SAFETY: ktime_get has no preconditions. + let now = unsafe { kernel::bindings::ktime_get() } as u64; + let state = &mut *ready; + if should_expand_compute_ext( + &mut state.last_compute_ns, + &mut state.burst, + now, + computes, + hints.expand_compute_ext, + ) { + // Best effort: without them the VM keeps the base compute units. + state.compute_ext = ComputeUnitSet::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + BASE_COMPUTE_UNITS..units, + Placement::Base, + ) + .ok(); + } + } + } if render && ready.render.is_none() { + let start = hints.next_pb_slot.fetch_add(1, Ordering::Relaxed) as usize; + let base_pb_slots = pick_base_pb_slots(start, hints.quarantined_pb_mask); ready.render = Some(RenderArena::new( &self.factory, &self.bind, &vm.vm, &self.live, + base_pb_slots, )?); + if ready.render_vm_counter.is_none() { + hints.active_render_vms.fetch_add(1, Ordering::AcqRel); + ready.render_vm_counter = Some(hints.active_render_vms.clone()); + } } - // A concurrent fault retains even newly constructed backing in this VM cache. - if vm.status.get() != 0 || vm.vm.is_closed() { - return Err(EIO); + if render_scs { + ready.render.as_ref().ok_or(EINVAL)?.ensure_scs( + &self.factory, + &vm.vm, + render_seeds, + )?; } + if render { + if let Some(base) = ready.render.as_ref() { + let quarantined = hints.quarantined_pb_mask; + let mut healthy = base + .base_pb_slots + .iter() + .filter(|&&slot| (quarantined & (1u32 << slot)) == 0) + .count(); + for (idx, ext) in ready.pb_ext.iter().enumerate() { + let hw_slot = super::hw::sizes::WARM_PB_SLOTS + idx; + if ext.is_some() && (quarantined & (1u32 << hw_slot)) == 0 { + healthy += 1; + } + } + if healthy < BASE_PB_SLOTS { + let heap = base.pools.heap().clone(); + for idx in 0..EXT_PB_SLOTS { + if healthy >= BASE_PB_SLOTS { + break; + } + let hw_slot = super::hw::sizes::WARM_PB_SLOTS + idx; + if ready.pb_ext[idx].is_some() + || (quarantined & (1u32 << hw_slot)) != 0 + { + continue; + } + let local_idx = BASE_PB_SLOTS + idx; + // Best effort: without recovery slots, keep prior PB slots. + ready.pb_ext[idx] = PoolExtArena::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + local_idx, + hw_slot, + &heap, + ) + .ok(); + if ready.pb_ext[idx].is_some() { + healthy += 1; + } else { + break; + } + } + } + } + let current_slots = BASE_RENDER_SLOTS + + ready + .render_ext + .iter() + .take_while(|tier| tier.is_some()) + .flatten() + .map(|tier| tier.passes.len()) + .sum::(); + if current_slots < super::hw::sizes::RENDER_SLOTS { + // SAFETY: ktime_get has no preconditions. + let now = unsafe { kernel::bindings::ktime_get() } as u64; + let state = &mut *ready; + let active_passes = self.active_render_passes.load(Ordering::Acquire); + let active_vms = hints.active_render_vms.load(Ordering::Acquire); + let (target, single_target) = target_render_slots_for( + &mut state.last_render_ns, + &mut state.render_burst, + now, + render_count as usize, + active_passes, + hints.expand_render_ext, + current_slots, + state.single_vm_render_slots, + active_vms, + ); + state.single_vm_render_slots = state.single_vm_render_slots.max(single_target); + for (idx, &(start, end)) in EXT_RENDER_TIERS.iter().enumerate() { + if start >= target { + break; + } + if state.render_ext[idx].is_none() { + // Best effort: stop on allocation failure, keeping lower tiers. + state.render_ext[idx] = RenderExtArena::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + start..end, + ) + .ok(); + if state.render_ext[idx].is_none() { + break; + } + } + } + } + if let Some(base) = ready.render.as_ref() { + let base_blocks = base.pools.heap_blocks(); + let single_slots = ready.single_vm_render_slots; + for (idx, &(start, end)) in PB_HEAP_EXT_TIERS.iter().enumerate() { + if single_slots < EXT_RENDER_TIERS[idx].1 + || ready.render_ext[idx].is_none() + { + break; + } + if base_blocks >= end { + continue; + } + if ready.pb_heap_ext[idx].is_none() { + let chunk_start = start.max(base_blocks); + // Best effort: stop on failure so the backed PB VA stays contiguous. + ready.pb_heap_ext[idx] = PbHeapExtArena::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + chunk_start, + end - chunk_start, + ) + .ok(); + if ready.pb_heap_ext[idx].is_none() { + break; + } + } + } + } + } + let render_ext = if render { + core::array::from_fn(|idx| ready.render_ext[idx].clone()) + } else { + [const { None }; EXT_RENDER_TIERS.len()] + }; + let pb_heap_ext = if render { + core::array::from_fn(|idx| ready.pb_heap_ext[idx].clone()) + } else { + [const { None }; PB_HEAP_EXT_TIERS.len()] + }; + let pb_ext = if render { + core::array::from_fn(|idx| ready.pb_ext[idx].clone()) + } else { + [const { None }; EXT_PB_SLOTS] + }; ( - if compute { ready.compute.clone() } else { None }, - if render { ready.render.clone() } else { None }, - ) - }; - let mut pb = KVec::with_capacity(commands.len(), GFP_KERNEL)?; - for command in commands { - pb.push( - if matches!(command, Command::Render(_)) { - Some(PbEpoch::new(&self.factory, vm, epochs.take()?)?) + match (compute, compute_scs) { + (true, true) => ready.compute_scs.clone(), + (true, false) => ready.compute.clone(), + (false, _) => None, + }, + if compute && !compute_scs { + ready.compute_ext.clone() } else { None }, - GFP_KERNEL, - )?; + if render { ready.render.clone() } else { None }, + render_ext, + pb_heap_ext, + pb_ext, + ) + }; + if render { + if render_count > super::budget::LIMIT { + return Err(E2BIG); + } + let mut remaining = kernel::time::msecs_to_jiffies(10_000); + loop { + let deficit = { + let mut standby = self.standby.lock(); + if vm.status.get() != 0 + || vm.vm.is_closed() + || self.closed.load(Ordering::Acquire) + { + return Err(EIO); + } + if let Some(needed) = standby + .reserved + .checked_add(render_count) + .filter(|&n| n <= super::budget::LIMIT) + { + if standby.epochs.len() >= needed as usize { + standby.reserved = needed; + break; + } + needed - standby.epochs.len() as u32 + } else { + standby.waiters += 1; + let waited = self + .standby_available + .wait_interruptible_timeout(&mut standby, remaining); + standby.waiters -= 1; + match waited { + CondVarTimeoutResult::Woken { jiffies } => { + remaining = jiffies; + continue; + } + CondVarTimeoutResult::Signal { .. } => return Err(ERESTARTSYS), + CondVarTimeoutResult::Timeout => { + if vm.status.get() != 0 + || vm.vm.is_closed() + || self.closed.load(Ordering::Acquire) + { + return Err(EIO); + } + let needed = standby + .reserved + .checked_add(render_count) + .filter(|&n| n <= super::budget::LIMIT) + .ok_or(EBUSY)?; + if standby.epochs.len() >= needed as usize { + standby.reserved = needed; + break; + } + needed - standby.epochs.len() as u32 + } + } + } + }; + let mut epochs = super::budget::Budget::reserve(&self.budget, deficit)?; + let mut fresh = KVec::with_capacity(deficit as usize, GFP_KERNEL)?; + for _ in 0..deficit { + fresh.push(PbEpoch::new(&self.factory, vm, epochs.take()?)?, GFP_KERNEL)?; + } + let mut overflow = KVec::with_capacity(fresh.len(), GFP_KERNEL)?; + { + let mut standby = self.standby.lock(); + let closed = self.closed.load(Ordering::Acquire); + for epoch in fresh { + if closed { + let _ = overflow.push_within_capacity(epoch); + } else if let Err(err) = standby.epochs.push_within_capacity(epoch) { + let _ = overflow.push_within_capacity(err.0); + } + } + } + drop(overflow); + } } - if vm.status.get() != 0 || vm.vm.is_closed() { + // A concurrent fault or close retains even newly constructed backing in this VM cache. + if vm.status.get() != 0 || vm.vm.is_closed() || self.closed.load(Ordering::Acquire) { + if render { + self.release_reserved(render_count); + } return Err(EIO); } + let cache = if render_count != 0 { + self.active_render_passes + .fetch_add(render_count, Ordering::AcqRel); + Some(self.clone()) + } else { + None + }; Ok(Prepared { compute, - render, - pb, + compute_ext, + compute_scs, + render: render_arena, + render_scs, + render_ext, + pb_heap_ext, + pb_ext, + active_renders: AtomicU32::new(render_count), + unpublished_renders: AtomicU32::new(render_count), + cache, }) } } /// Immutable references carried by an accepted job. No fallible lazy work in the engine. pub(crate) struct Prepared { - pub(crate) compute: Option>, + pub(crate) compute: Option>, + /// The VM's extension compute units when the job was prepared. + pub(crate) compute_ext: Option>, + /// The job's computes use the VM's SCS-capable compute arena (`0..SCS_COMPUTE_UNITS`). + compute_scs: bool, pub(crate) render: Option>, - pb: KVec>>, + /// The job's renders use the arena's SCS-capable allocators (`render.scs`). + render_scs: bool, + /// The VM's demand-grown extension render pass tiers when the job was prepared. + pub(crate) render_ext: [Option>; EXT_RENDER_TIERS.len()], + /// The VM's demand-grown contiguous PB heap extension tiers when the job was prepared. + pub(crate) pb_heap_ext: [Option>; PB_HEAP_EXT_TIERS.len()], + /// The VM's lazily allocated recovery PB/UMA allocator slots when the job was prepared. + pub(crate) pb_ext: [Option>; EXT_PB_SLOTS], + /// Render commands still accounted against `Cache::active_render_passes`. + active_renders: AtomicU32, + /// Render commands of this job whose standby reservation has not yet been committed. + unpublished_renders: AtomicU32, + /// The VM cache holding the standby PB epoch pool. + cache: Option>, +} + +impl Drop for Prepared { + fn drop(&mut self) { + let Some(cache) = &self.cache else { + return; + }; + cache.release_render_passes(*self.active_renders.get_mut()); + cache.release_reserved(*self.unpublished_renders.get_mut()); + } } impl Prepared { - pub(crate) fn compute(&self) -> Result<&ComputeArena> { + /// Returns canceled render credits even if the job stays retained for its published work. + /// The device lock serializes suffix discard with publication. + pub(crate) fn discard_unpublished_renders(&self) { + let Some(cache) = &self.cache else { + return; + }; + let remaining = self.unpublished_renders.swap(0, Ordering::AcqRel); + if remaining != 0 { + self.active_renders.fetch_sub(remaining, Ordering::AcqRel); + cache.release_render_passes(remaining); + cache.release_reserved(remaining); + } + } + + pub(crate) fn compute(&self) -> Result<&ComputeUnitSet> { self.compute.as_deref().ok_or(EINVAL) } + /// Compute units this job can use. + #[allow(dead_code)] + pub(crate) fn compute_units(&self) -> Result { + Ok(self.compute()?.len() + self.compute_ext.as_deref().map_or(0, ComputeUnitSet::len)) + } + /// Hardware compute ledger bitmask (bit `k` -> unit `k`) this job can use. + pub(crate) fn compute_slot_mask(&self) -> Result { + let base = self.compute()?; + if let Some(slots) = base.hw_slots { + let mut mask = 0u32; + for slot in slots { + mask |= 1u32 << slot; + } + return Ok(mask); + } + let total = self.compute_units()?.min(super::hw::sizes::COMPUTE_UNITS); + Ok(if total >= 32 { + u32::MAX + } else { + (1u32 << total) - 1 + }) + } + /// The per-unit arena holding compute unit `k`. + pub(crate) fn compute_arena(&self, k: usize) -> Option> { + let base = self.compute.as_ref()?; + if let Some(slots) = base.hw_slots { + let local = slots.iter().position(|&slot| slot == k)?; + return base.arena(local); + } + if k < base.len() { + base.arena(k) + } else { + self.compute_ext + .as_ref() + .and_then(|ext| ext.arena(k - base.len())) + } + } + /// Whether this job's computes use SCS-capable compute units. + pub(crate) fn compute_scs(&self) -> bool { + self.compute_scs + } + /// Whether this job's renders use SCS-capable render allocators. + pub(crate) fn render_scs(&self) -> bool { + self.render_scs + } + /// Physical PB/UMA allocator slot bitmask and preferred home slot this job can use. + pub(crate) fn pb_slot_mask(&self) -> Result<(u32, usize)> { + let base = self.render()?; + let mut mask = 0u32; + for &slot in &base.base_pb_slots { + mask |= 1u32 << slot; + } + if !self.render_scs { + for (idx, ext) in self.pb_ext.iter().enumerate() { + if ext.is_some() { + mask |= 1u32 << (super::hw::sizes::WARM_PB_SLOTS + idx); + } + } + } + Ok((mask, base.base_pb_slots[0])) + } + fn pb_allocator(&self, k: usize) -> Result<&super::pools::Allocator> { + let base = self.render()?; + if let Some(local) = base.base_pb_slots.iter().position(|&slot| slot == k) { + return if self.render_scs { + base.scs + .as_ref() + .and_then(|scs| scs.pools.unit(local)) + .ok_or(EINVAL) + } else { + base.pools.unit(local).ok_or(EINVAL) + }; + } + if self.render_scs { + return Err(EINVAL); + } + let idx = k.checked_sub(super::hw::sizes::WARM_PB_SLOTS).ok_or(EINVAL)?; + self.pb_ext + .get(idx) + .and_then(|slot| slot.as_deref()) + .map(|arena| &arena.allocator) + .ok_or(EINVAL) + } + pub(crate) fn prepare_pb_in_flight( + &self, + k: usize, + draw: u64, + pipelined: bool, + ) -> Result { + self.pb_allocator(k)?.prepare_in_flight(draw, pipelined) + } + pub(crate) fn pb_allocator_refs(&self, k: usize) -> Result { + self.pb_allocator(k)?.refs() + } + pub(crate) fn publish_pb_batch(&self, k: usize, submitted: u64, renders: u32) -> Result { + self.pb_allocator(k)?.publish_batch(submitted, renders) + } + pub(crate) fn pb_retired(&self, k: usize) -> Result { + self.pb_allocator(k)?.retired() + } + pub(crate) fn pb_retired_at(&self, k: usize, target: u64) -> Result { + self.pb_allocator(k)?.retired_at(target) + } + pub(crate) fn pb_heap_gva(&self, k: usize) -> Result { + self.pb_allocator(k)?.heap_gva() + } + pub(crate) fn pb_heap_blocks(&self) -> Result { + let base = self.render()?.pools.heap_blocks(); + let ext: u32 = self + .pb_heap_ext + .iter() + .take_while(|tier| tier.is_some()) + .flatten() + .map(|tier| tier.blocks) + .sum(); + Ok(base.saturating_add(ext).min(super::fw::buffer::MAX_BLOCKS)) + } + /// The arenas owning PB/UMA allocator slot `k` and its backed PB heap tiers. + pub(crate) fn pb_owner_arena(&self, k: usize) -> Option { + let base = self.render.as_ref()?; + let heap_ext = core::array::from_fn(|idx| self.pb_heap_ext[idx].clone()); + if base.base_pb_slots.contains(&k) { + Some(PbOwnerArena::Base(base.clone(), heap_ext)) + } else { + let idx = k.checked_sub(super::hw::sizes::WARM_PB_SLOTS)?; + self.pb_ext + .get(idx) + .and_then(|slot| slot.as_ref()) + .map(|ext| PbOwnerArena::Ext(base.clone(), ext.clone(), heap_ext)) + } + } + /// VM-free firmware lease keeping PB/UMA allocator slot `k`'s `descriptor` + `submitted` + /// pages mapped in context-0 UAT across closed-VM reclaim. + pub(crate) fn pb_uma_lease(&self, k: usize) -> Option> { + self.pb_allocator(k) + .ok() + .map(super::pools::Allocator::uma_lease) + } + fn render_ext_for(&self, k: usize) -> Option<(&Arc, usize)> { + for tier in self.render_ext.iter().take_while(|t| t.is_some()).flatten() { + if let Some(idx) = k.checked_sub(tier.start) { + if idx < tier.passes.len() { + return Some((tier, idx)); + } + } + } + None + } + /// Render pass slots this job can use. + pub(crate) fn render_passes(&self) -> Result { + let ext: usize = self + .render_ext + .iter() + .take_while(|tier| tier.is_some()) + .flatten() + .map(|tier| tier.passes.len()) + .sum(); + Ok(self.render()?.passes.len() + ext) + } + /// Render pass slot `k`: the VM's base slots, then its demand-grown extension tiers. + pub(crate) fn render_pass(&self, k: usize) -> Result<&PassSlot> { + let base = &self.render()?.passes; + match base.get(k) { + Some(pass) => Ok(pass), + None => self + .render_ext_for(k) + .and_then(|(tier, idx)| tier.passes.get(idx)) + .ok_or(EINVAL), + } + } + /// The dirty high-water marks and clean prefix trackers for pass slot `k`. + pub(crate) fn render_pass_dirty(&self, k: usize) -> Result> { + let base = self.render()?; + if k < base.passes.len() { + Ok(PassDirty { + tpc: &base.tpc_dirty[k], + tilemap: &base.tilemap_dirty[k], + tilemap_last: &base.tilemap_last[k], + tilemap_clean: &base.tilemap_clean[k], + heap: &base.heap_dirty[k], + }) + } else { + let (tier, idx) = self.render_ext_for(k).ok_or(EINVAL)?; + Ok(PassDirty { + tpc: &tier.tpc_dirty[idx], + tilemap: &tier.tilemap_dirty[idx], + tilemap_last: &tier.tilemap_last[idx], + tilemap_clean: &tier.tilemap_clean[idx], + heap: &tier.heap_dirty[idx], + }) + } + } + /// Updates dirty high-water marks and last-used spans for pass slot `k` (base or extension). + pub(crate) fn set_pass_dirty(&self, k: usize, tpc: u64, tilemap: u64, heap: u64) -> Result { + let pass = self.render_pass(k)?; + if tpc > pass.tpc.size as u64 + || tilemap > pass.tilemap.size as u64 + || heap > pass.heap.size as u64 + { + return Err(E2BIG); + } + let dirty = self.render_pass_dirty(k)?; + dirty.tpc.fetch_max(tpc, Ordering::Relaxed); + dirty.tilemap.fetch_max(tilemap, Ordering::Relaxed); + dirty.tilemap_last.store(tilemap, Ordering::Relaxed); + dirty.tilemap_clean.store(0, Ordering::Relaxed); + dirty.heap.fetch_max(heap, Ordering::Relaxed); + Ok(()) + } + /// The arena owning render pass slot `k`. + pub(crate) fn pass_owner_arena(&self, k: usize) -> Option { + let base = self.render.as_ref()?; + if k < base.passes.len() { + Some(PassOwnerArena::Base(base.clone())) + } else { + self.render_ext_for(k) + .map(|(tier, _)| PassOwnerArena::Ext(tier.clone())) + } + } + /// Compute unit `k`: the VM's base/SCS units, then its extension units. + pub(crate) fn compute_unit(&self, k: usize) -> Result<&ComputeSlot> { + let base = self.compute()?; + if let Some(slots) = base.hw_slots { + let local = slots.iter().position(|&slot| slot == k).ok_or(EINVAL)?; + return base.unit(local).ok_or(EINVAL); + } + match base.unit(k) { + Some(unit) => Ok(unit), + None => self + .compute_ext + .as_deref() + .and_then(|e| e.unit(k - base.len())) + .ok_or(EINVAL), + } + } pub(crate) fn render(&self) -> Result<&RenderArena> { self.render.as_deref().ok_or(EINVAL) } - pub(crate) fn pb(&self, index: usize) -> Result<&Arc> { - self.pb.get(index).and_then(Option::as_ref).ok_or(EINVAL) + pub(crate) fn take_pb(&self) -> Result> { + self.cache.as_ref().ok_or(EINVAL)?.take_standby() + } + pub(crate) fn return_pb(&self, epoch: Arc) { + if let Some(cache) = &self.cache { + cache.return_standby(epoch); + } + } + /// Commits `count` render commands' standby reservations once they reach firmware visibility. + pub(crate) fn commit_render(&self, count: u32) { + if count == 0 { + return; + } + if let Some(cache) = &self.cache { + if let Ok(prev) = self.unpublished_renders.fetch_update( + Ordering::AcqRel, + Ordering::Acquire, + |n| Some(n.saturating_sub(count)), + ) { + let released = prev.min(count); + if released != 0 { + cache.release_reserved(released); + } + } + } } } diff --git a/drivers/gpu/drm/asahi/g16/rt.rs b/drivers/gpu/drm/asahi/g16/rt.rs new file mode 100644 index 00000000000000..5b42e6f2d1dcf4 --- /dev/null +++ b/drivers/gpu/drm/asahi/g16/rt.rs @@ -0,0 +1,534 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Hardware ray tracing on G16G (RENDER_RAY_QUERY and BOUNDED_AS_BUILD). +//! +//! The command state is the shared G17P UAPI: a compute command's packed shader-context +//! scratch (SCS) layout and intersection tables, a render's per-stage ray-query state, and the +//! compute AS-build flag. The validation, the register words they become and the SCS memory +//! sizing are those of the M4 Pro (T6041, the same G16 GPU generation) on its 26B123 firmware +//! (`g17::fw::variant::V26B123`), except where macOS 27.2 on the J773g (G16G, 26B123) has +//! been traced: a ray-query compute item's 0x017e1/0x017d9 records and 0xd479 tail +//! ([`super::encode`]), and the SCS pools' freelists (+0x1c, [`SCS_FREELIST_RECORDS`]) and +//! row words (+0x48). This module is pure: no kernel objects, no allocation. +//! +//! What neither settles for G16G stays off behind a named gate or is open, as trace questions +//! of mesa#577: +//! +//! - 0x017d9 (SCS enable) in a render stage, [`super::encode`]'s `RENDER_SCS_ENABLE` (T5, +//! T6): the M4 Pro's 25G83 render programs write it in a stage with SCS. No G16G render with +//! ray queries has been traced. +//! - 0x1a141 (SCS driver word), `COMPUTE_SCS_DRIVER_WORD` (T1): macOS's ray-query compute +//! items on the J773g do not write it. +//! - The SCS-enable bit (T6, g17's kick header bit 61) is a u32 of each start command: +//! StartCompute +0x40, StartTA +0x60, StartFS +0x78 (`fw::work`'s `START_SCS`). macOS 27.2 on +//! the J773g sets it on every compute item whose list opens with 0x017e1 and on no other. A +//! slot without it is not protected from the firmware's idle SCS teardown (0x017e0 = 0, +//! compute and TA windows 0xff0000), which runs while its dispatch is still executing. +//! - A traversal exclusion between clients (T8): the A18 Pro needs one (`g17::traversal`), the +//! M4 Pro's variants do not set it; G16G adds none. +//! - How macOS sizes the SCS pool for a given request (T3): it grows its compute pool beyond +//! the M4 Pro's extras ([`pool_seeds`]); one request size does not give the rule. + +use kernel::prelude::*; + +/// Validated per-command shader-context scratch request (g17 `fw::compute::ScratchRequest`). +/// +/// The layout word is Apple's packed SCS layout: depth (bits 0:15), levels (16:23), cliques +/// (24:31), user (32:47) and driver (48:63). The region the hardware needs is derived with the +/// Gen1 section model: fixed prefixes totalling [`Self::FIXED_BYTES`], then per-thread stack, +/// per-thread driver and per-thread user bytes, rounded up with a two-page guard. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ScratchRequest { + pages: u16, + window: u64, + stack: u64, + driver: u64, + tail: u64, +} + +impl ScratchRequest { + /// Native ScsLayoutGen1::getSectionEnd(4). + const FIXED_BYTES: u64 = 0x58000; + const THREADS_PER_CLIQUE: u64 = 32; + const BYTES_PER_STACK_ENTRY: u64 = 8; + const PAGE_SHIFT: u32 = 12; + const PAGE_SIZE: u64 = 1 << Self::PAGE_SHIFT; + const PAGES_PER_MIB: u64 = 1 << (20 - Self::PAGE_SHIFT); + /// Window word when enabled: bit 24 plus the clique count at 16:23. + const WINDOW_ENABLED: u64 = 1 << 24; + /// Disabled window word: the value G16G's work lists write today. + pub(crate) const WINDOW_DISABLED: u64 = 0xff_0000; + /// Disabled stack word: the value G16G's work lists write today. + pub(crate) const STACK_DISABLED: u64 = 8; + /// TA/FS tail reservation when enabled (0xd471, 0xd469), matching macOS 27.2's J773g + /// ray-query tail reservation (0x2c). + const TAIL_ENABLED: u64 = 0x2c; + /// Compute tail reservation when enabled (0xd479), as macOS 27.2 on the J773g writes it in + /// its ray-query compute work. + const COMPUTE_TAIL_ENABLED: u64 = 0x2c; + + /// No scratch. + pub(crate) const NONE: Self = Self { + pages: 0, + window: Self::WINDOW_DISABLED, + stack: Self::STACK_DISABLED, + driver: 0, + tail: 0, + }; + + /// Payload-free layouts request no scratch even if depth or cliques are set. + pub(crate) fn new(layout: u64) -> Result { + let depth = layout & u64::from(u16::MAX); + let cliques = (layout >> 24) & u64::from(u8::MAX); + let user = (layout >> 32) & u64::from(u16::MAX); + let driver = (layout >> 48) & u64::from(u16::MAX); + if user == 0 && driver == 0 { + return Ok(Self::NONE); + } + let threads = cliques + .checked_mul(Self::THREADS_PER_CLIQUE) + .ok_or(EINVAL)?; + let stack_bytes = threads + .checked_mul( + depth + .checked_mul(Self::BYTES_PER_STACK_ENTRY) + .ok_or(EINVAL)?, + ) + .ok_or(EINVAL)?; + let driver_bytes = threads.checked_mul(driver).ok_or(EINVAL)?; + let user_bytes = threads.checked_mul(user).ok_or(EINVAL)?; + let end = Self::FIXED_BYTES + .checked_add(stack_bytes) + .and_then(|bytes| bytes.checked_add(driver_bytes)) + .and_then(|bytes| bytes.checked_add(user_bytes)) + .and_then(|bytes| bytes.checked_add(2 * Self::PAGE_SIZE - 1)) + .ok_or(EINVAL)?; + let pages = end >> Self::PAGE_SHIFT; + Ok(Self { + pages: u16::try_from(pages).map_err(|_| EINVAL)?, + window: Self::WINDOW_ENABLED | (cliques << 16), + stack: depth & !7, + // The Gen1 register list publishes no level region: the word stays zero. + driver: 0, + tail: Self::TAIL_ENABLED, + }) + } + + pub(crate) fn enabled(self) -> bool { + self.pages != 0 + } + + /// Per-core 4-KiB pages of the request. + pub(crate) fn pages(self) -> u16 { + self.pages + } + + /// 0x101d1 (compute), 0x101c9 (TA), 0x101c1 (FS): the pages and their 1-MiB count. + pub(crate) fn size_word(self) -> u64 { + let pages = u64::from(self.pages); + pages | (pages.div_ceil(Self::PAGES_PER_MIB) << 16) + } + + /// 0x107a1 (compute), 0x10799 (TA); the FS 0x10791 also sets bit 9. + pub(crate) fn window_word(self) -> u64 { + self.window + } + + /// 0x1a0e9 (compute), 0x1a0f1 (TA), 0x1a0f9 (FS). + pub(crate) fn stack_word(self) -> u64 { + self.stack + } + + /// 0x1a141 (compute), written only with `COMPUTE_SCS_DRIVER_WORD`. + pub(crate) fn driver_word(self) -> u64 { + self.driver + } + + /// 0xd471 (TA), 0xd469 (FS). + pub(crate) fn tail_word(self) -> u64 { + self.tail + } + + /// 0xd479 (compute). + pub(crate) fn compute_tail_word(self) -> u64 { + if self.enabled() { + Self::COMPUTE_TAIL_ENABLED + } else { + 0 + } + } +} + +/// Validated intersection tables (g17 `fw::compute::IntersectionTables`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct IntersectionTables { + pub(crate) pool: u64, + pub(crate) pool_bytes: u64, + first: u32, + count: u32, + pub(crate) default_program: u64, + default_control: u64, +} + +impl IntersectionTables { + pub(crate) const NONE: Self = Self { + pool: 0, + pool_bytes: 0, + first: 0, + count: 0, + default_program: 0, + default_control: 0, + }; + + /// The HAL200 Gen1 table: a 16-KiB aligned pool of 16-KiB units below 2^48, a byte-sized + /// table length of 25 bits, 128-byte entries, and a default program whose 48-bit code + /// address is 64-byte aligned and whose control word has bit 40 set. + pub(crate) fn new( + pool: u64, + pool_bytes: u64, + first: u32, + count: u32, + default_program: u64, + default_control: u64, + ) -> Result { + if pool == 0 { + if pool_bytes != 0 + || first != 0 + || count != 0 + || default_program != 0 + || default_control != 0 + { + return Err(EINVAL); + } + return Ok(Self::NONE); + } + let end = pool.checked_add(pool_bytes).ok_or(EINVAL)?; + let blocks_end = u64::from(first) + u64::from(count); + let code = default_program & 0x0000_ffff_ffff_ffff; + if pool & 0x3fff != 0 + || pool_bytes == 0 + || pool_bytes & 0x3fff != 0 + || end > (1u64 << 48) + || (pool_bytes >> 14) >= (1u64 << 25) + || count == 0 + || count >= (1 << 18) + || blocks_end * 128 > pool_bytes + || code & 63 != 0 + || default_control & !0x0000_7fff_0000_3fff != 0 + || (code == 0 && (default_program != 0 || default_control != 0)) + || (code != 0 && default_control & (1u64 << 40) == 0) + { + return Err(EINVAL); + } + Ok(Self { + pool, + pool_bytes, + first, + count, + default_program, + default_control, + }) + } + + /// A render stage's 48-byte table: the auxiliary word (zero or 8..=32, only with a pool), + /// four MBZ bytes, then the fields of [`Self::new`]. Bytes past 48 must be zero. The + /// auxiliary word is validated only: the M4 Pro's render programs write the scratch tail + /// where its compute program would write it. + pub(crate) fn parse(bytes: &[u8]) -> Result { + if bytes + .get(48..) + .is_some_and(|tail| tail.iter().any(|&b| b != 0)) + { + return Err(EINVAL); + } + let mut tail = [0u8; 48]; + let count = bytes.len().min(tail.len()); + tail[..count].copy_from_slice(&bytes[..count]); + let u32_at = + |at: usize| u32::from_le_bytes([tail[at], tail[at + 1], tail[at + 2], tail[at + 3]]); + let u64_at = |at: usize| u64::from(u32_at(at)) | u64::from(u32_at(at + 4)) << 32; + let auxiliary = u32_at(0); + if u32_at(4) != 0 || (auxiliary != 0 && !(8..=32).contains(&auxiliary)) { + return Err(EINVAL); + } + let tables = Self::new( + u64_at(8), + u64_at(16), + u32_at(24), + u32_at(28), + u64_at(32), + u64_at(40), + )?; + if auxiliary != 0 && !tables.enabled() { + return Err(EINVAL); + } + Ok(tables) + } + + pub(crate) fn enabled(self) -> bool { + self.pool != 0 + } + + /// The 48-bit address of the default program, or zero. + pub(crate) fn default_code(self) -> u64 { + self.default_program & 0x0000_ffff_ffff_ffff + } + + /// The six table words: compute 0x1a089, 0x1a091, 0x1a059, 0x1a061, 0x1a0b9, 0x1a0c1; TA + /// 0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, 0x1a0d1; FS 0x1a0a9, 0x1a0b1, 0x1a079, + /// 0x1a081, 0x1a0d9, 0x1a0e1. The M4 Pro's encoding (AGXMetalG17P endComputePass): the + /// first entry, the byte length, and two fixed pool words. Zero without tables, the value + /// G16G's work lists write today. + pub(crate) fn words(self) -> [u64; 6] { + if !self.enabled() { + return [0; 6]; + } + [ + self.pool + u64::from(self.first) * 128, + 0xc000_0000 | (u64::from(self.count) << 7), + 0x6f_0000_0000, + 0x3feff, + self.default_program, + self.default_control, + ] + } +} + +/// The ray state of a compute command. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ComputeRay { + pub(crate) intersection: IntersectionTables, + pub(crate) scratch: ScratchRequest, +} + +impl ComputeRay { + #[allow(dead_code, reason = "The empty state of the host regressions.")] + pub(crate) const NONE: Self = Self { + intersection: IntersectionTables::NONE, + scratch: ScratchRequest::NONE, + }; + + /// As the M4 Pro (G17P command set): an auxiliary allocation is M5-only and must be zero, + /// as must the reserved word; tables and scratch are independent of each other. + #[allow(clippy::too_many_arguments)] + pub(crate) fn new( + scs_layout: u64, + auxiliary: u32, + reserved: u32, + pool: u64, + pool_bytes: u64, + first: u32, + count: u32, + default_program: u64, + default_control: u64, + ) -> Result { + if auxiliary != 0 || reserved != 0 { + return Err(EINVAL); + } + Ok(Self { + intersection: IntersectionTables::new( + pool, + pool_bytes, + first, + count, + default_program, + default_control, + )?, + scratch: ScratchRequest::new(scs_layout)?, + }) + } +} + +/// The ray state of one render stage (g17 `fw::render_rt::RayQueryStage`): index 0 the +/// vertex (tiling) stage, 1 the fragment stage. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct RayQueryStage { + pub(crate) intersection: IntersectionTables, + pub(crate) scratch: ScratchRequest, +} + +impl RayQueryStage { + /// Size of one `drm_asahi_render_ray_query_stage`. + pub(crate) const SIZE: usize = 56; + + #[allow(dead_code, reason = "The empty state of the host regressions.")] + pub(crate) const NONE: Self = Self { + intersection: IntersectionTables::NONE, + scratch: ScratchRequest::NONE, + }; + + fn parse(wire: &[u8; Self::SIZE]) -> Result { + let layout = u64::from_le_bytes([ + wire[0], wire[1], wire[2], wire[3], wire[4], wire[5], wire[6], wire[7], + ]); + let intersection = IntersectionTables::parse(&wire[8..])?; + let scratch = ScratchRequest::new(layout)?; + if scratch.enabled() != intersection.enabled() { + return Err(EINVAL); + } + Ok(Self { + intersection, + scratch, + }) + } + + /// Both stages from the render payload bytes after `prior_cdm`: shorter payloads are read + /// zero-filled, bytes past the two stages must be zero. + pub(crate) fn parse_pair(bytes: &[u8]) -> Result<[Self; 2]> { + if bytes + .get(2 * Self::SIZE..) + .is_some_and(|tail| tail.iter().any(|&b| b != 0)) + { + return Err(EINVAL); + } + let mut wire = [[0u8; Self::SIZE]; 2]; + for (index, stage) in wire.iter_mut().enumerate() { + let start = (index * Self::SIZE).min(bytes.len()); + let end = ((index + 1) * Self::SIZE).min(bytes.len()); + stage[..end - start].copy_from_slice(&bytes[start..end]); + } + Ok([Self::parse(&wire[0])?, Self::parse(&wire[1])?]) + } + + /// Whether the stage carries intersection tables. + pub(crate) fn traces(self) -> bool { + self.intersection.enabled() + } +} + +/// Only the explicit AS-build bit (bit 2) is accepted; reserved and unrelated compute flags +/// stay invalid on G16G, as on the M4 Pro (g17 `timeout::as_build`). +pub(crate) fn as_build(flags: u32) -> Option { + const AS_BUILD: u32 = 1 << 2; + if flags & !AS_BUILD != 0 { + None + } else { + Some(flags & AS_BUILD != 0) + } +} + +/// Whether a command needs the long execution allowance (g17 `timeout::select`): a compute +/// command with intersection tables, a render with tables in either stage, or an AS build. +pub(crate) fn select(compute_ray: bool, render_ray: [bool; 2], as_build: bool) -> bool { + compute_ray || render_ray.into_iter().any(|enabled| enabled) || as_build +} + +/// Freelist entries (4-KiB pages) of a UMA pool without SCS, the value G16G seeds today. +pub(crate) const BASE_SEEDS: u32 = 8192; +/// Records of a base UMA freelist: the capacity G16G's managers report at +0x1c for their +/// 0x20000-byte freelist (`UNK_1C_VALUE`). +pub(crate) const FREELIST_RECORDS: u32 = 16384; +/// Records of an SCS-capable pool's freelist: the +0x1c macOS 27.2 on the J773g writes on +/// every pool, over a 4-MiB freelist, whatever the pool's rows (20 to 108 seen). +pub(crate) const SCS_FREELIST_RECORDS: u32 = 0x80000; +/// Bytes of one freelist record, the 64-bit address of one 4-KiB seed. +pub(crate) const RECORD_BYTES: u64 = 8; +/// Bytes of one seed. +pub(crate) const SEED_BYTES: u64 = 0x1000; +/// Freelist entries of one 2-MiB pool-table row. +pub(crate) const SEEDS_PER_ROW: u32 = 512; +/// The most freelist entries of an SCS-capable UMA pool: the whole rows whose pool and +/// freelist fit one SCS pool window (62 rows, 124 MiB, and the 4-MiB freelist). The 256-row +/// pool table holds more. +pub(crate) const MAX_SCS_SEEDS: u32 = max_window_seeds(super::hw::client::SCS_POOL_WINDOW); +const _: () = assert!(BASE_SEEDS % SEEDS_PER_ROW == 0 && MAX_SCS_SEEDS % SEEDS_PER_ROW == 0); +const _: () = assert!(BASE_SEEDS < FREELIST_RECORDS && FREELIST_RECORDS < MAX_SCS_SEEDS); +const _: () = assert!(MAX_SCS_SEEDS < SCS_FREELIST_RECORDS); +const _: () = assert!(freelist_records(BASE_SEEDS) as u64 * RECORD_BYTES == 0x20000); + +/// The freelist records (+0x1c) of a UMA pool with `seeds` entries. +0x1c is the record count +/// of the freelist +0x14 points at. A base pool keeps the 16384 G16G has always written; an +/// SCS-capable pool (more than the base seeds) gets [`SCS_FREELIST_RECORDS`], as macOS 27.2 on +/// the J773g gives every pool. +pub(crate) const fn freelist_records(seeds: u32) -> u32 { + if seeds > BASE_SEEDS { + SCS_FREELIST_RECORDS + } else { + FREELIST_RECORDS + } +} + +/// Bytes of the freelist of a pool with `seeds` entries, in whole 16-KiB pages. +pub(crate) const fn freelist_bytes(seeds: u32) -> u64 { + (freelist_records(seeds) as u64 * RECORD_BYTES).next_multiple_of(0x4000) +} + +/// Bytes an SCS pool window needs for a pool of `seeds` entries and, after it, its freelist. +pub(crate) const fn window_bytes(seeds: u32) -> u64 { + seeds as u64 * SEED_BYTES + freelist_bytes(seeds) +} + +/// The most whole-row seeds whose pool and freelist fit `window` bytes. +const fn max_window_seeds(window: u64) -> u32 { + let mut seeds = (window / SEED_BYTES) as u32 / SEEDS_PER_ROW * SEEDS_PER_ROW; + while seeds != 0 && window_bytes(seeds) > window { + seeds -= SEEDS_PER_ROW; + } + seeds +} + +/// The 4-KiB pages one SCS request adds to a UMA pool for `active_cores` cores, as the M4 Pro +/// sizes its free list (g17 `fw::compute_pool::extra_bytes`): per core the request's pages, +/// their 1-MiB large-page inventory (pages / 256, rounded up) and eight tail pages. +pub(crate) fn extra_pages(active_cores: u32, scs_pages: u16) -> Result { + if active_cores == 0 { + return Err(EINVAL); + } + if scs_pages == 0 { + return Ok(0); + } + let small = u64::from(scs_pages); + small + .checked_add(small.div_ceil(256)) + .and_then(|pages| pages.checked_add(8)) + .and_then(|pages| pages.checked_mul(u64::from(active_cores))) + .ok_or(EOVERFLOW) +} + +/// Freelist entries a UMA pool needs to serve SCS requests of `pages` per stage at once (one +/// compute dispatch, or the two stages of one render): the base pool plus every stage's extra +/// pages, rounded up to whole pool-table rows. E2BIG beyond the largest SCS-capable pool +/// ([`MAX_SCS_SEEDS`]); without SCS it is [`BASE_SEEDS`]. +pub(crate) fn required_seeds(active_cores: u32, pages: &[u16]) -> Result { + let mut seeds = u64::from(BASE_SEEDS); + for &stage in pages { + seeds = seeds + .checked_add(extra_pages(active_cores, stage)?) + .ok_or(EOVERFLOW)?; + } + let row = u64::from(SEEDS_PER_ROW); + let seeds = seeds.checked_add(row - 1).ok_or(EOVERFLOW)? / row * row; + if seeds > u64::from(MAX_SCS_SEEDS) { + return Err(E2BIG); + } + u32::try_from(seeds).map_err(|_| E2BIG) +} + +/// The SCS-capable UMA pool a command runs on: one of at least `needed` freelist entries, or +/// if its VM has none yet, a new one of `pool` ([`pool_seeds`]). Both zero without scratch. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ScsSeeds { + pub(crate) needed: u32, + pub(crate) pool: u32, +} + +impl ScsSeeds { + /// No scratch. + pub(crate) const NONE: Self = Self { needed: 0, pool: 0 }; +} + +/// Freelist entries of the SCS-capable pools created for requests of `pages` per stage (a +/// render's two stages, or a compute dispatch and zero). The pools serve every later job of the +/// VM and cannot grow once the hardware may hold them, so they hold two stages at the larger +/// one where a window holds that, otherwise the request itself; E2BIG if neither fits. +/// +/// - A render pool then takes a later queue that reserves the other stage too (Mesa replaces +/// its queue to add one). +/// - A compute pool gets two dispatches' extras. One is less than macOS provisions: for its +/// own ray-query kernel of 1703 pages per core, macOS 27.2 on the J773g grew the compute pool +/// to 108 rows, about 2.6 times the extras of [`extra_pages`]. +pub(crate) fn pool_seeds(active_cores: u32, pages: [u16; 2]) -> Result { + let largest = pages[0].max(pages[1]); + required_seeds(active_cores, &[largest, largest]) + .or_else(|_| required_seeds(active_cores, &pages)) +} diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index a383a09b8d9711..b51556822b0759 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -54,11 +54,14 @@ impl Firmware { Ok(self.engine.flights.is_empty() && self.engine.pending.is_empty() && !self.engine.frozen + && !self.slots.scrubbing_active() && self.recovery_idle()?) } /// The run bit and the RTKit handshake, with the firmware's state as it was left. fn sleep_restart(&mut self) -> Result { + // Start the next render on each pass slot fresh after the firmware restarts. + self.pools.invalidate(); self.session.rtkit.warm_restart()?; let control = self.session.regs.asc_control()?; self.session.regs.set_asc_control(control | ASC_RUN)?; @@ -100,7 +103,7 @@ impl Shared { /// With the sleeping flag set, joins whatever may be reading the firmware's registers. fn join_workers(self: &Arc) { // Dropping the handle cancels an expiry that's still pending. - drop(self.resnap_handle.lock().take()); + self.cancel_resnap(); // SAFETY: An initialized, pinned delayed work of this Shared. A pending callback owned // one Arc that it can no longer reclaim. Later enqueues run into the sleeping check. let cancelled = unsafe { @@ -112,6 +115,22 @@ impl Shared { // SAFETY: See above. drop(unsafe { Arc::from_raw(Arc::as_ptr(self)) }); } + self.events.drain(); + self.events_unbound.drain(); + // `sleeping` is already set, so draining queued scrubs under `scrub_queue` + // guarantees no concurrent `enqueue_scrubs()` can still queue onto `scrub_wq` + // while `scrub_wq.drain()` runs. Drop each drained item outside the spinlock. + loop { + let item = self.scrub_queue.lock().pop(); + let Some(item) = item else { + break; + }; + drop(item); + } + self.scrub_wq.drain(); + self.feed.pause(); + self.feed_wq.drain(); + self.feed.release_floor(); } /// Waits for what's been published to retire. The poll work keeps running meanwhile. @@ -197,6 +216,8 @@ impl Shared { .and_then(|quiet| if quiet { Ok(()) } else { Err(EBUSY) }) .and_then(|_| { if self.leave_for_commit(firmware) { + firmware.power.release_clpc_now(); + self.active_flights.store(0, Ordering::Release); Ok(()) } else { Err(EBUSY) @@ -208,6 +229,7 @@ impl Shared { match left { Ok(()) => Ok(()), Err(error) => { + self.feed.resume(); self.sleeping.store(false, Ordering::Release); self.poll_now(); Err(error) @@ -248,6 +270,7 @@ impl Shared { "GPU firmware back in {} us\n", now_ns().saturating_sub(started) / 1000 ); + self.feed.resume(); self.poll_now(); Ok(()) } @@ -263,6 +286,9 @@ impl Shared { impl Gpu { /// Called before any device suspends. Only a sleep that powers the SoC down gets here. fn sleep_prepare(&self) -> Result { + if !self.cfg.deep_sleep { + return Err(EBUSY); + } let result = self.shared.sleep_down(); if let Err(error) = result { dev_warn!(self.shared.dev.as_ref(), "GPU refused sleep: {:?}\n", error); @@ -282,6 +308,7 @@ impl Gpu { self.shared.dev.as_ref(), "sleep refused before the commit: GPU firmware never stopped\n" ); + self.shared.feed.resume(); self.shared.sleeping.store(false, Ordering::Release); self.shared.poll_now(); return; @@ -329,6 +356,8 @@ unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { static SLEEP_OPS: SleepOps = SleepOps(bindings::dev_pm_ops { prepare: Some(sleep_prepare), complete: Some(sleep_complete), + suspend_noirq: Some(crate::driver::sleep_suspend_noirq), + resume_noirq: Some(crate::driver::sleep_resume_noirq), // SAFETY: All-zero is the absence of every other callback. ..unsafe { core::mem::zeroed() } }); diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index b4a48ed2907ae1..f938866ba2eb9c 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -2,21 +2,91 @@ //! Per-VM M4 command storage and device-wide displacement lifetime tracking. //! -//! Both compute units alternate hardware UMA slot 1; both render units alternate slot 33. -//! Firmware retirement and a later distinct retired owner are both required before reuse. +//! Each compute unit owns its own hardware UMA slot (`COMPUTE_UMA_SLOT + index`) and may be in +//! flight together, in publication order; both render units alternate slot 33, one at a time. Firmware retirement and a later +//! distinct retired owner are both required before reuse. //! Private backing and old VM leases survive until a distinct replacement fully retires. //! Aborted storage remains mapped and quarantined. Pool cursors are never scrubbed. -use core::sync::atomic::Ordering; +use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{prelude::*, sync::Arc}; use super::encode::{Geometry, PassRefs}; -use super::fw::work::{barrier, fs, ta}; -use super::graph::{alloc, alloc_work, cmd_fw, Client}; -use super::hw::{client, sizes}; -use super::object::{Class, FwObject, Objects}; +use super::fw::buffer; +use super::fw::work::{barrier, compute, fs, ta}; +use super::graph::{alloc, Client}; +use super::hw::{client, engine, sizes}; +use super::object::{Class, Factory, FwLease, FwObject, Objects}; use super::pools::lifetime::Lifetime; +/// The compute command records of one hardware compute unit index (work image, microsequence, and +/// barrier records), shared by every VM's [`ComputeSlot`] bound to that hardware unit: the unit +/// index is device-global and claimed by one flight at a time. The host writes them before +/// publication and they take the firmware-cached [`Class::FwCoherent`] view macOS 26B123 gives its +/// per-queue command objects; the work image keeps its uncached kernel GPU task lower alias and +/// cleans host stores to PoC for the GPU, matching [`PassCmds`]. +#[derive(Clone)] +pub(crate) struct UnitCmds { + pub(crate) work: Arc, + pub(crate) seq: Arc, + pub(crate) barrier: Arc, +} + +impl UnitCmds { + /// Allocates hardware compute unit `k`'s command records from a device-lifetime allocator + /// ([`Factory::persistent_objects`]), which the caller never drops. + #[allow(dead_code)] + pub(crate) fn new(o: &mut Objects, k: u64) -> Result { + let (mut work, mut seq, mut barrier) = (None, None, None); + Self::init_into(o, k, &mut work, &mut seq, &mut barrier) + } + + /// Populates any missing persistent command records for hardware compute unit `k` into the + /// caller-owned slots so partial failure retains already-mapped `FwCoherent` records instead + /// of leaking or re-allocating them on retry. + pub(crate) fn init_into( + o: &mut Objects, + k: u64, + work: &mut Option>, + seq: &mut Option>, + barrier: &mut Option>, + ) -> Result { + let coherent = Class::FwCoherent; + if work.is_none() { + *work = Some(o.alloc(super::object::Request { + size: compute::WORK_SIZE, + class: coherent, + placement: super::object::Placement::Anywhere, + offset: 0, + client: None, + lower: Some(client::WORK_PAGE + k * client::CWORK_STRIDE), + cpu: true, + })?); + } + if seq.is_none() { + *seq = Some(alloc(o, compute::SEQ_SIZE, coherent, None, 0, false)?); + } + if barrier.is_none() { + // Holds fs2c (+0x00) and per-pipe c2c (+(1 + pipe) * barrier::SIZE) barriers in 1 page. + *barrier = Some(alloc( + o, + barrier::SIZE * (1 + sizes::COMPUTE_PIPES), + coherent, + None, + 0, + false, + )?); + } + Ok(Self { + work: work.as_ref().ok_or(EINVAL)?.clone(), + seq: seq.as_ref().ok_or(EINVAL)?.clone(), + barrier: barrier.as_ref().ok_or(EINVAL)?.clone(), + }) + } +} + +const _: () = assert!(barrier::SIZE * (1 + sizes::COMPUTE_PIPES) <= super::hw::PAGE as usize); + /// One immutable allocation set. Mutable firmware pool cursors survive successful reuse. pub(crate) struct ComputeSlot { pub(crate) its: Arc, @@ -25,88 +95,248 @@ pub(crate) struct ComputeSlot { pub(crate) seq: Arc, #[allow(dead_code)] pub(crate) barrier: Arc, + pub(crate) descriptor: Arc, pub(crate) pool: Arc, pub(crate) pool_state: Arc, pub(crate) page_list: Arc, pub(crate) counter: Arc, pub(crate) context_store: Arc, pub(crate) aux: Arc, + /// Freelist entries of the unit's UMA pool, seeded once ([`init_uma_pool`]). + pub(crate) seeds: u32, + /// VM-free firmware lease keeping this unit's `descriptor` and `counter` mapped in context-0 + /// UAT until a later compute retirement overwrites firmware `uma_mgr_table[1 + k]`. + uma_lease: Arc, +} + +/// Where a compute unit lives and how large its UMA pool is. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Placement { + /// The VM's base units: a 32 MiB pool at the unit's original client addresses. + Base, + /// SCS-capable units (ray-query scratch): a pool of `seeds` 4-KiB entries + /// ([`super::rt::required_seeds`]) and its freelist in the unit's SCS pool window, the + /// other records at their own client addresses, sharing ledger index and UMA slot `1 + k` + /// with base unit k. + Scs { seeds: u32 }, +} + +impl Placement { + fn pool(self, k: u64) -> u64 { + match self { + Placement::Base => client::compute_pool(k), + Placement::Scs { .. } => client::scs_compute_pool(k), + } + } + /// The base of the unit's list, preempt, auxiliary and context records. + fn state(self, k: u64) -> u64 { + match self { + Placement::Base => client::compute_state(k), + Placement::Scs { .. } => client::scs_compute_records(k), + } + } + /// The unit's freelist: a base unit's at its state, an SCS unit's right after its pool. + fn freelist(self, k: u64) -> u64 { + match self { + Placement::Base => client::compute_state(k), + Placement::Scs { .. } => self.pool(k) + self.pool_bytes() as u64, + } + } + /// Freelist entries of the unit's pool. + pub(crate) fn seeds(self) -> u32 { + match self { + Placement::Base => super::rt::BASE_SEEDS, + Placement::Scs { seeds } => seeds, + } + } + /// Bytes of the unit's pool: its seeds of 4 KiB. + pub(crate) fn pool_bytes(self) -> usize { + (u64::from(self.seeds()) * super::rt::SEED_BYTES) as usize + } + /// Bytes of the unit's freelist ([`super::rt::freelist_bytes`]). + pub(crate) fn freelist_bytes(self) -> usize { + super::rt::freelist_bytes(self.seeds()) as usize + } + /// An SCS unit's pool fits [`super::rt::MAX_SCS_SEEDS`] in whole rows, so it and its + /// freelist fit its window. + pub(crate) fn check(self) -> Result { + match self { + Placement::Base => Ok(()), + Placement::Scs { seeds } => { + if seeds == 0 + || seeds % super::rt::SEEDS_PER_ROW != 0 + || seeds > super::rt::MAX_SCS_SEEDS + { + Err(E2BIG) + } else { + Ok(()) + } + } + } + } } +const _: () = assert!( + sizes::POOL_BYTES == super::rt::BASE_SEEDS as u64 * super::rt::SEED_BYTES + && super::rt::window_bytes(super::rt::MAX_SCS_SEEDS) <= client::SCS_POOL_WINDOW +); /// Initializes the private pool exactly once, before it is exposed. Never called on reuse. -pub(crate) fn init_uma_pool(state: &FwObject, list: &FwObject, pool: u64) -> Result { - if pool & 0x3fff != 0 { +/// `seeds` 4-KiB freelist entries and their 2-MiB pool-table rows; 8192 is the 32 MiB pool +/// every unit had before SCS. The freelist `state` holds every seed, the pool table `list` +/// every row. +pub(crate) fn init_uma_pool(state: &FwObject, list: &FwObject, pool: u64, seeds: u32) -> Result { + let seeds = seeds as usize; + let rows = seeds / super::rt::SEEDS_PER_ROW as usize; + if pool & 0x3fff != 0 + || seeds == 0 + || seeds % super::rt::SEEDS_PER_ROW as usize != 0 + || seeds * super::rt::RECORD_BYTES as usize > state.size + || rows * super::fw::buffer::uma_pools::POOL_TABLE_STRIDE > list.size + { return Err(EINVAL); } let mut chunk = [0u8; 512]; - for first in (0..8192).step_by(64) { + for first in (0..seeds).step_by(64) { for j in 0..64 { chunk[j * 8..j * 8 + 8] .copy_from_slice(&(pool + ((first + j) as u64) * 0x1000).to_le_bytes()); } state.write(first * 8, &chunk)?; } - for i in 0..16 { + for i in 0..rows { list.w64(i * 64, (1u64 << 61) | (pool + i as u64 * 0x200000))?; } Ok(()) } impl ComputeSlot { - pub(crate) fn new(o: &mut Objects, k: u64) -> Result { + #[allow(dead_code)] + pub(crate) fn new( + o: &mut Objects, + fw_factory: &Factory, + k: u64, + cmds: &UnitCmds, + ) -> Result { + Self::new_in(o, fw_factory, k, k as u32, Placement::Base, cmds) + } + + /// Unit `k` at `placement` bound to hardware ledger slot `hw_slot`, around the device-lifetime + /// command records `cmds` of `hw_slot`. + pub(crate) fn new_in( + o: &mut Objects, + fw_factory: &Factory, + k: u64, + hw_slot: u32, + placement: Placement, + cmds: &UnitCmds, + ) -> Result { + placement.check()?; let sh = Class::Shared; + let state = placement.state(k); + // Keep the per-VM UMA manager descriptor and submission counter in one VM-free Class::Fw + // page inside `uma_lease` (matching `pools::Allocator`) while `work`, `seq`, and `barrier` + // live in device-lifetime `Class::FwCoherent` `UnitCmds`. + let mut fw = fw_factory.fw_objects(); + let uma_page = alloc(&mut fw, 0x200, Class::Fw, None, 0, false)?; + let descriptor = FwObject::view(&uma_page, 0, compute::DESCRIPTOR_SIZE)?; + let counter = FwObject::view(&uma_page, 0x100, 0x80)?; + let uma_lease = FwLease::new(fw)?; let unit = Self { its: alloc(o, 16, sh, None, 0, false)?, preempt: alloc( o, 0x4000, sh, - Client::nc(client::compute_preempt(k)), + Client::nc(state + client::COMPUTE_PREEMPT_OFF), 0, false, )?, - work: alloc_work(o, 0x2000, client::WORK_PAGE + k * client::CWORK_STRIDE, 0)?, - seq: alloc(o, 0x300, cmd_fw(), None, 0, false)?, - barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, + work: cmds.work.clone(), + seq: cmds.seq.clone(), + barrier: cmds.barrier.clone(), + descriptor, pool: o.alloc(super::object::Request { - size: 0x2000000, + size: placement.pool_bytes(), class: sh, placement: super::object::Placement::Anywhere, offset: 0, - client: Some((client::compute_pool(k), super::hw::pte::LEAF_NC)), + client: Some((placement.pool(k), super::hw::pte::LEAF_NC)), lower: None, cpu: false, })?, pool_state: alloc( o, - 0x20000, + placement.freelist_bytes(), + sh, + Client::nc(placement.freelist(k)), + 0, + false, + )?, + page_list: alloc( + o, + 0x4000, sh, - Client::nc(client::compute_state(k)), + Client::nc(state + client::COMPUTE_LIST_OFF), 0, false, )?, - page_list: alloc(o, 0x4000, sh, Client::nc(client::compute_list(k)), 0, false)?, - counter: alloc(o, 0x80, sh, None, 0, false)?, + counter, context_store: alloc( o, 0x40000, sh, - Client::nc(client::compute_context(k)), + Client::nc(state + client::COMPUTE_CONTEXT_OFF), + 0, + false, + )?, + aux: alloc( + o, + 0x4000, + sh, + Client::nc(state + client::COMPUTE_AUX_OFF), 0, false, )?, - aux: alloc(o, 0x4000, sh, Client::nc(client::compute_aux(k)), 0, false)?, + seeds: placement.seeds(), + uma_lease, }; init_uma_pool( &unit.pool_state, &unit.page_list, unit.pool.gva.ok_or(EINVAL)?, + unit.seeds, + )?; + unit.descriptor.write( + 0, + &buffer::compute_uma_manager_image( + unit.work.va, + engine::COMPUTE_UMA_SLOT + hw_slot, + unit.pool_state.gva.ok_or(EINVAL)?, + unit.page_list.gva.ok_or(EINVAL)?, + unit.counter.va, + unit.seeds, + super::rt::freelist_records(unit.seeds), + ), )?; Ok(unit) } - /// Only command-local scratch is reset. Pool/list/counter/descriptor state is preserved. - fn scrub(&self) -> Result { + + /// VM-free firmware lease keeping this unit's `descriptor` and `counter` mapped in context-0 + /// UAT. + pub(crate) fn uma_lease(&self) -> Arc { + self.uma_lease.clone() + } + /// Resets command-local state before reuse. Pool/list/counter/descriptor state is preserved. + /// + /// Clean same-VM reuse only zeroes the 16-byte internal timestamp pair so retirement + /// checks cannot observe stale ticks; `work` and `seq` are overwritten by `prefix_compute`. + /// First use, cross-VM retarget, cancelled preparation, or post-recovery/error reuse runs + /// the full scrub of all scratch areas. + fn scrub(&self, full: bool) -> Result { self.its.fill(0, 0, 16)?; + if !full { + return Ok(()); + } self.seq.fill(0, 0, 0x300)?; self.aux.fill(0, 0, 0x4000)?; self.context_store.fill(0, 0, 0x40000)?; @@ -114,6 +344,84 @@ impl ComputeSlot { } } +/// The render command records of one pass slot index (TA and FS work images, microsequences and +/// barrier records), shared by every VM's [`PassSlot`] of that index: the index is device-global +/// and claimed by one flight at a time. The host writes them before publication and never reads +/// back what the firmware writes, so they take the firmware-cached [`Class::FwCoherent`] view +/// macOS 26B123 gives its per-queue command objects. The work images keep their uncached kernel +/// GPU task lower alias, as macOS maps its work items for the GPU. Each work image and +/// microsequence keeps its own page; the barrier records share one page, as the compute unit's +/// barriers do. +#[derive(Clone)] +pub(crate) struct PassCmds { + pub(crate) ta_work: Arc, + pub(crate) fs_work: Arc, + pub(crate) ta_seq: Arc, + pub(crate) fs_seq: Arc, + pub(crate) own_barrier: Arc, + pub(crate) prev_barrier: Arc, + pub(crate) ta_fs_barrier: Arc, + pub(crate) fs_dep: Arc, + pub(crate) compute_barrier: Arc, + pub(crate) fs_compute_barrier: Arc, +} + +impl PassCmds { + /// Barrier records in the shared page: own, prev, TA->FS, FS dependency (one record each), + /// then the per-pipe compute and FS-compute barriers. + const OWN: usize = 0; + const PREV: usize = barrier::SIZE; + const TA_FS: usize = 2 * barrier::SIZE; + const FS_DEP: usize = 3 * barrier::SIZE; + const COMPUTE: usize = 4 * barrier::SIZE; + const FS_COMPUTE: usize = Self::COMPUTE + barrier::SIZE * sizes::COMPUTE_PIPES; + const BARRIERS: usize = Self::FS_COMPUTE + barrier::SIZE * sizes::COMPUTE_PIPES; + + /// Allocates pass slot index `i`'s set from a device-lifetime allocator + /// ([`Factory::persistent_objects`]), which the caller never drops. + pub(crate) fn new(o: &mut Objects, i: u64) -> Result { + let coherent = Class::FwCoherent; + let off = client::pass_off(i); + let mut work = |size, page, offset| { + o.alloc(super::object::Request { + size, + class: coherent, + placement: super::object::Placement::Anywhere, + offset, + client: None, + lower: Some(page), + cpu: true, + }) + }; + let fs_work = work( + fs::WORK_SIZE, + client::FS_WORK_PAGE + off, + client::FS_WORK_OFF as usize, + )?; + let ta_work = work( + ta::WORK_SIZE, + client::TA_WORK_PAGE + off, + client::TA_WORK_OFF as usize, + )?; + let barriers = alloc(o, Self::BARRIERS, coherent, None, 0, false)?; + let record = |offset, size| FwObject::view(&barriers, offset, size); + Ok(Self { + ta_work, + fs_work, + ta_seq: alloc(o, ta::SEQ_OBJECT, coherent, None, 0, false)?, + fs_seq: alloc(o, fs::SEQ_OBJECT, coherent, None, 0, false)?, + own_barrier: record(Self::OWN, barrier::SIZE)?, + prev_barrier: record(Self::PREV, barrier::SIZE)?, + ta_fs_barrier: record(Self::TA_FS, barrier::SIZE)?, + fs_dep: record(Self::FS_DEP, barrier::SIZE)?, + compute_barrier: record(Self::COMPUTE, barrier::SIZE * sizes::COMPUTE_PIPES)?, + fs_compute_barrier: record(Self::FS_COMPUTE, barrier::SIZE * sizes::COMPUTE_PIPES)?, + }) + } +} + +const _: () = assert!(PassCmds::BARRIERS <= super::hw::PAGE as usize); + /// One render pass slot. pub(crate) struct PassSlot { pub(crate) aux: Arc, @@ -122,6 +430,7 @@ pub(crate) struct PassSlot { pub(crate) tilemap: Arc, pub(crate) heap: Arc, pub(crate) scene_user: Arc, + pub(crate) scene_list: Arc, pub(crate) fs_scratch: Arc, pub(crate) fs_work: Arc, pub(crate) ta_work: Arc, @@ -133,55 +442,50 @@ pub(crate) struct PassSlot { /// Part of the slot's firmware layout; the host does not use it. _uts: Arc, pub(crate) own_barrier: Arc, - #[allow(dead_code)] pub(crate) prev_barrier: Arc, - #[allow(dead_code)] + pub(crate) ta_fs_barrier: Arc, pub(crate) fs_dep: Arc, + pub(crate) compute_barrier: Arc, + pub(crate) fs_compute_barrier: Arc, } impl PassSlot { - /// Allocates pass slot `i`'s objects, with their client leaf classes. - pub(crate) fn new(o: &mut Objects, i: u64, pre_records: u32) -> Result { + /// Allocates pass slot `i`'s objects, with their client leaf classes, around the + /// device-lifetime command records `cmds` of index `i`. + pub(crate) fn new(o: &mut Objects, i: u64, pre_records: u32, cmds: &PassCmds) -> Result { let sh = Class::Shared; - let (ps, ws) = (i * client::PASS_STRIDE, i * client::WORK_STRIDE); - let tpc = if i != 0 { + let off = client::pass_off(i); + let tpc = if i >= sizes::BASE_RENDER_SLOTS as u64 { client::TPC_SLOT_SIZE } else { client::TPC_SIZE }; - let tilemap = if i != 0 { + let tilemap = if i >= sizes::BASE_RENDER_SLOTS as u64 { client::TILEMAP_SLOT_SIZE } else { client::TILEMAP_SIZE }; let _ = pre_records; - let aux = alloc( - o, - 0x20000, - sh, - Client::nc(client::AUX + i * client::AUX_STRIDE), - 0, - false, - )?; + let aux = alloc(o, 0x20000, sh, Client::nc(client::AUX + off), 0, false)?; let mut pre = KVec::with_capacity(3, GFP_KERNEL)?; pre.push( - alloc(o, 0x4000, sh, Client::nc(client::PRE0_PAGE + ps), 0, false)?, + alloc(o, 0x4000, sh, Client::nc(client::PRE0_PAGE + off), 0, false)?, GFP_KERNEL, )?; pre.push( - alloc(o, 0x4000, sh, Client::nc(client::PRE1_PAGE + ps), 0, false)?, + alloc(o, 0x4000, sh, Client::nc(client::PRE1_PAGE + off), 0, false)?, GFP_KERNEL, )?; pre.push( - alloc(o, 0x4000, sh, Client::nc(client::PRE2_PAGE + ps), 0, false)?, + alloc(o, 0x4000, sh, Client::nc(client::PRE2_PAGE + off), 0, false)?, GFP_KERNEL, )?; let tpc = alloc( o, tpc as usize, sh, - Client::nc(client::TPC + i * client::TPC_SLOT_STRIDE), + Client::nc(client::TPC + off), 0, false, )?; @@ -189,7 +493,7 @@ impl PassSlot { o, tilemap as usize, sh, - Client::nc(client::TILEMAP + i * client::TPC_SLOT_STRIDE), + Client::nc(client::pass_tilemap(i)), 0, false, )?; @@ -197,7 +501,7 @@ impl PassSlot { o, 0x4000, sh, - Client::nc(client::HEAP_META_PAGE + ps), + Client::nc(client::HEAP_META_PAGE + off), 0, false, )?; @@ -205,29 +509,25 @@ impl PassSlot { o, 0x10000, sh, - Client::nc(client::SCENE_USER + ps), + Client::nc(client::SCENE_USER + off), 0, false, )?; - let fs_scratch = alloc( + let scene_list = alloc( o, - 0x10000, + super::fw::buffer::SCENE_LIST_SIZE, sh, - Client::nc(client::FS_SCRATCH + ps), + Client::nc(client::SCENE_LIST + off), 0, false, )?; - let fs_work = alloc_work( - o, - fs::WORK_SIZE, - client::FS_WORK_PAGE + ws, - client::FS_WORK_OFF as usize, - )?; - let ta_work = alloc_work( + let fs_scratch = alloc( o, - ta::WORK_SIZE, - client::TA_WORK_PAGE + ws, - client::TA_WORK_OFF as usize, + 0x10000, + sh, + Client::nc(client::FS_SCRATCH + off), + 0, + false, )?; Ok(Self { aux, @@ -236,34 +536,69 @@ impl PassSlot { tilemap, heap, scene_user, + scene_list, fs_scratch, - fs_work, - ta_work, - ta_seq: alloc(o, ta::SEQ_OBJECT, cmd_fw(), None, 0, false)?, - fs_seq: alloc(o, fs::SEQ_OBJECT, cmd_fw(), None, 0, false)?, + fs_work: cmds.fs_work.clone(), + ta_work: cmds.ta_work.clone(), + ta_seq: cmds.ta_seq.clone(), + fs_seq: cmds.fs_seq.clone(), ta_scratch: alloc(o, 0x10000, sh, None, 0, false)?, scene: alloc(o, super::fw::work::scene::SIZE, sh, None, 0, false)?, // Internal TA start/end, FS start/end; legacy user cells likewise. its: alloc(o, 32, sh, None, 0, false)?, _uts: alloc(o, 32, Class::Fw, None, 0, false)?, - own_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, - prev_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, - fs_dep: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, + own_barrier: cmds.own_barrier.clone(), + prev_barrier: cmds.prev_barrier.clone(), + ta_fs_barrier: cmds.ta_fs_barrier.clone(), + fs_dep: cmds.fs_dep.clone(), + compute_barrier: cmds.compute_barrier.clone(), + fs_compute_barrier: cmds.fs_compute_barrier.clone(), }) } - /// Per-use reset of a pass slot's storage: work images, microsequences, scratch, stage - /// stamps, the TPC/tilemap spans its last use wrote, auxiliary, heap metadata and - /// scene-user and the preemption save areas. The slot is neither - /// published nor claimed; the dirty spans are passed in. + /// Per-use reset of a pass slot's storage. The slot is neither published nor claimed; the + /// dirty spans are passed in. + /// + /// Clean same-VM reuse skips the work/sequence images (immediately overwritten by + /// `prefix_render`), unused scratch objects (`ta_scratch`, `fs_scratch`, `its`), bulk + /// scratch (`aux`, `scene_user`), preemption save areas (`pre[0..2]`), and `tpc` + /// (overwritten by TA hardware), zeroing only the active `tilemap` delta span and the + /// active `heap` metadata header (`0x200` single-layer, `0x1000` multi-layer). First use, + /// cross-VM switch, cancelled preparation, or post-recovery/error reuse runs the full + /// scrub including `tpc_dirty`, `its`, `scene`, `pre[0..2]`, and full `heap`. + /// Clean same-VM reset of the active per-pass WC spans (used both synchronously on fallback + /// and off-lock after displacement). + pub(crate) fn scrub_clean( + &self, + tilemap_start: u64, + tilemap_len: u64, + heap_dirty: u64, + ) -> Result { + if tilemap_len != 0 { + self.tilemap + .fill(tilemap_start as usize, 0, tilemap_len as usize)?; + } + if heap_dirty != 0 { + self.heap.fill(0, 0, heap_dirty as usize)?; + } + Ok(()) + } + fn scrub( &self, - pre_records: u32, tpc_dirty: u64, - tilemap_dirty: u64, + tilemap_start: u64, + tilemap_len: u64, + heap_dirty: u64, + full: bool, stats: &mut SlotStats, ) -> Result { - let _ = pre_records; + if !full { + self.scrub_clean(tilemap_start, tilemap_len, heap_dirty)?; + stats.tilemap_clear_bytes = stats.tilemap_clear_bytes.saturating_add(tilemap_len); + stats.pass_scrubs = stats.pass_scrubs.saturating_add(1); + return Ok(()); + } self.ta_work.fill(0, 0, ta::WORK_SIZE)?; self.fs_work.fill(0, 0, fs::WORK_SIZE)?; @@ -274,12 +609,15 @@ impl PassSlot { self.its.fill(0, 0, 32)?; self.tpc.fill(0, 0, tpc_dirty as usize)?; stats.tpc_clear_bytes = stats.tpc_clear_bytes.saturating_add(tpc_dirty); - self.tilemap.fill(0, 0, tilemap_dirty as usize)?; - stats.tilemap_clear_bytes = stats.tilemap_clear_bytes.saturating_add(tilemap_dirty); + self.tilemap.fill(0, 0, tilemap_len as usize)?; + stats.tilemap_clear_bytes = stats.tilemap_clear_bytes.saturating_add(tilemap_len); self.aux.fill(0, 0, 0x20000)?; self.heap.fill(0, 0, 0x4000)?; + self.scene.fill(0, 0, super::fw::work::scene::SIZE)?; self.scene_user.fill(0, 0, 0x10000)?; - // Preemption save areas start zeroed on every use. + self.scene_list + .fill(0, 0, super::fw::buffer::SCENE_LIST_SIZE)?; + // Preemption save areas start zeroed on every full reset. self.pre[0].fill(0, 0, 0x4000)?; self.pre[1].fill(0, 0, 0x4000)?; self.pre[2].fill(0, 0, 0x4000)?; @@ -301,6 +639,7 @@ impl PassSlot { tilemap_gva: self.tilemap.gva.unwrap_or(0), heap_gva: self.heap.gva.unwrap_or(0), scene_user_gva: self.scene_user.gva.unwrap_or(0), + scene_list: self.scene_list.gva.unwrap_or(0), pre_gva: [ self.pre[0].gva.unwrap_or(0), self.pre[1].gva.unwrap_or(0), @@ -320,24 +659,32 @@ impl PassSlot { pub(crate) struct Claims { pub(crate) slot: [u32; sizes::COMPUTE_SLOTS], pub(crate) slot_count: u32, + pub(crate) compute_pipe: u8, pub(crate) pass: [u32; sizes::RENDER_SLOTS], - pub(crate) pass_mask: u32, + pub(crate) pass_count: u32, + pub(crate) pass_mask: u64, #[allow(dead_code)] pub(crate) ct: [u32; sizes::RENDER_SLOTS], pub(crate) ct_count: u32, #[allow(dead_code)] pub(crate) rotating: bool, + /// `Slots::scrub_gen` observed when these claims were published; a recovery invalidation + /// advances `scrub_gen` so in-flight slots still force a full scrub after retiring. + pub(crate) scrub_gen: u64, } impl Claims { pub(crate) const fn new() -> Self { Self { slot: [0; sizes::COMPUTE_SLOTS], slot_count: 0, + compute_pipe: 0, pass: [0; sizes::RENDER_SLOTS], + pass_count: 0, pass_mask: 0, ct: [0; sizes::RENDER_SLOTS], ct_count: 0, rotating: true, + scrub_gen: 0, } } } @@ -370,37 +717,319 @@ pub(crate) struct SlotStats { pub(crate) pass_scrubs: u64, } +/// Displacement ledger and VM leases of the compute units (see [`Slots`]). +pub(crate) struct ComputeOwners { + lifetime: Lifetime<{ sizes::COMPUTE_UNITS }>, + owner: [Option>; sizes::COMPUTE_UNITS], + pending_retarget: [Option; sizes::COMPUTE_UNITS], + pending_owner: [Option>; sizes::COMPUTE_UNITS], + /// The arena holding each owner's unit: the firmware may still write the unit's + /// descriptor when a later owner displaces it, after its VM's client closed. + arena: [Option>; sizes::COMPUTE_UNITS], + pending_arena: [Option>; sizes::COMPUTE_UNITS], + /// VM-free firmware leases keeping each hardware slot's `work` + `counter` mapped in + /// context-0 UAT across closed-VM reclaim until a later compute retirement overwrites + /// firmware `uma_mgr_table[1 + k]`. + retained_uma: [Option>; sizes::COMPUTE_UNITS], + pending_uma: [Option>; sizes::COMPUTE_UNITS], + /// Force a full scrub on next claim (first use, cancel, error, or firmware recovery). + scrub_full: [bool; sizes::COMPUTE_UNITS], + /// Whether the most recent claim of each compute unit required a full scrub/work write. + last_full: [bool; sizes::COMPUTE_UNITS], +} + +/// Bitmask of valid render pass slot indices (`0..sizes::RENDER_SLOTS`). +const PASS_MASK: u64 = u64::MAX >> (64 - sizes::RENDER_SLOTS); + +/// Shared atomic coordination between `Shared::state` slot selection/claims and off-lock +/// pre-scrubbing of displaced render pass slots. +struct ScrubState { + /// Pass slots currently being scrubbed outside `Shared::state`; never picked or claimed. + scrubbing: AtomicU64, + /// Displaced pass slots whose clean same-VM spans were zeroed off-lock. + clean_mask: AtomicU64, + /// Incremented by [`Self::clear_all_clean`] on recovery so an in-flight async scrub that + /// started before recovery can never publish a stale `clean_mask` bit afterwards. + generation: AtomicU64, + /// Set if slot selection found eligible slots blocked only by an in-flight off-lock scrub. + waiter: AtomicBool, + /// Set when an off-lock scrub finished while `waiter` was pending so the next `poll_step()` + /// retries `publish_checked()` even if no flight retired. + woke: AtomicBool, + /// Off-lock scrub counters folded into [`SlotStats`] on subsequent locked access. + pass_scrubs: AtomicU64, + tilemap_clear_bytes: AtomicU64, +} + +impl ScrubState { + const fn new() -> Self { + Self { + scrubbing: AtomicU64::new(0), + clean_mask: AtomicU64::new(0), + generation: AtomicU64::new(0), + waiter: AtomicBool::new(false), + woke: AtomicBool::new(false), + pass_scrubs: AtomicU64::new(0), + tilemap_clear_bytes: AtomicU64::new(0), + } + } + + fn is_scrubbing(&self, k: usize) -> bool { + self.scrubbing.load(Ordering::Acquire) & (1u64 << k) != 0 + } + + fn is_clean(&self, k: usize) -> bool { + self.clean_mask.load(Ordering::Acquire) & (1u64 << k) != 0 + } + + fn take_clean(&self, k: usize) -> bool { + let bit = 1u64 << k; + self.clean_mask.fetch_and(!bit, Ordering::AcqRel) & bit != 0 + } + + fn clear_clean(&self, k: usize) { + self.clean_mask.fetch_and(!(1u64 << k), Ordering::Release); + } + + fn clear_all_clean(&self) { + self.generation.fetch_add(1, Ordering::SeqCst); + self.clean_mask.store(0, Ordering::SeqCst); + } +} + +/// One displaced render pass slot staged for off-lock WC scrubbing. +pub(crate) struct PendingScrub { + slot: usize, + arena: super::resources::PassOwnerArena, + state: Arc, + generation: u64, + done: bool, +} + +impl PendingScrub { + pub(crate) fn run_one(&mut self) -> bool { + let bit = 1u64 << self.slot; + let ok = if self.state.generation.load(Ordering::Acquire) != self.generation { + false + } else if let Some((pass, d)) = self.arena.pass_and_dirty(self.slot) { + let dirty = d.tilemap.load(Ordering::Acquire); + let last = d.tilemap_last.load(Ordering::Acquire); + let already = d.tilemap_clean.load(Ordering::Acquire); + let heap = d.heap.load(Ordering::Acquire); + let target = if last != 0 { dirty.min(last) } else { dirty }; + let len = target.saturating_sub(already); + match pass.scrub_clean(already, len, heap) { + Ok(()) => { + // Order scrubbed WC bytes before clearing dirty / publishing clean_mask. + super::engine::wmb(); + d.heap.store(0, Ordering::Release); + if target >= dirty { + d.tilemap.store(0, Ordering::Release); + d.tilemap_clean.store(0, Ordering::Release); + } else { + d.tilemap_clean.store(target, Ordering::Release); + } + self.state.pass_scrubs.fetch_add(1, Ordering::Relaxed); + self.state + .tilemap_clear_bytes + .fetch_add(len, Ordering::Relaxed); + true + } + Err(_) => false, + } + } else { + false + }; + if ok && self.state.generation.load(Ordering::SeqCst) == self.generation { + self.state.clean_mask.fetch_or(bit, Ordering::SeqCst); + if self.state.generation.load(Ordering::SeqCst) != self.generation { + self.state.clean_mask.fetch_and(!bit, Ordering::SeqCst); + } + } + self.state.scrubbing.fetch_and(!bit, Ordering::SeqCst); + self.done = true; + let woke = self.state.waiter.swap(false, Ordering::SeqCst); + if woke { + self.state.woke.store(true, Ordering::Release); + } + woke + } +} + +impl Drop for PendingScrub { + fn drop(&mut self) { + if !self.done { + let bit = 1u64 << self.slot; + self.state.scrubbing.fetch_and(!bit, Ordering::SeqCst); + } + } +} + +/// Maximum displaced render pass slots staged in one stack-resident [`ScrubBatch`]. +/// Keeping the batch bounded avoids multi-kilobyte stack frames in poll/submit paths while +/// any additional displaced slots remain flagged for the next pass. +const MAX_SCRUB_BATCH: usize = 8; + +/// Zero-allocation batch of displaced render pass slots to scrub after dropping `Shared::state`. +pub(crate) struct ScrubBatch { + items: [Option; MAX_SCRUB_BATCH], + len: usize, +} + +impl ScrubBatch { + pub(crate) const fn new() -> Self { + Self { + items: [const { None }; MAX_SCRUB_BATCH], + len: 0, + } + } + + pub(crate) fn is_empty(&self) -> bool { + self.len == 0 + } + + fn is_full(&self) -> bool { + self.len >= MAX_SCRUB_BATCH + } + + fn push(&mut self, item: PendingScrub) -> bool { + if self.len >= MAX_SCRUB_BATCH { + return false; + } + self.items[self.len] = Some(item); + self.len += 1; + true + } +} + +/// Zero-allocation slot-indexed queue handed to the async pass-scrub workqueue. +/// +/// Each pass slot `0..sizes::RENDER_SLOTS` keeps its `scrubbing` bit set while a +/// [`PendingScrub`] is queued or running, so at most one entry per slot exists at once. +pub(crate) struct ScrubQueue { + slots: [Option; sizes::RENDER_SLOTS], +} + +impl ScrubQueue { + pub(crate) const fn new() -> Self { + Self { + slots: [const { None }; sizes::RENDER_SLOTS], + } + } + + /// Allocates an empty [`ScrubQueue`] directly on the heap to keep `Shared` setup off the + /// probe stack. + #[allow(dead_code)] + #[inline(never)] + pub(crate) fn new_boxed() -> Result> { + Ok(KBox::init( + init!(Self { + slots: [const { None }; sizes::RENDER_SLOTS], + }), + GFP_KERNEL, + )?) + } + + /// Moves every staged scrub from `batch` into the queue. Returns `true` if any was queued. + pub(crate) fn push_batch(&mut self, mut batch: ScrubBatch) -> bool { + let mut pushed = false; + for slot in &mut batch.items[..batch.len] { + if let Some(item) = slot.take() { + let idx = item.slot; + self.slots[idx] = Some(item); + pushed = true; + } + } + batch.len = 0; + pushed + } + + /// Pops the next queued pass scrub, if any. + pub(crate) fn pop(&mut self) -> Option { + for slot in &mut self.slots { + if slot.is_some() { + return slot.take(); + } + } + None + } +} + +/// Displacement ledger and VM leases of the render pass slots (see [`Slots`]). +pub(crate) struct RenderOwners { + lifetime: Lifetime<{ sizes::RENDER_SLOTS }>, + // Last-owner leases remain bound through retirement and displacement. Replaced only + // when the displaced unit is safely rebound to a new publication. + owner: [Option>; sizes::RENDER_SLOTS], + pending_retarget: [Option; sizes::RENDER_SLOTS], + pending_owner: [Option>; sizes::RENDER_SLOTS], + /// The render arena (base or extension) holding each pass slot's owner. + arena: [Option; sizes::RENDER_SLOTS], + pending_arena: [Option; sizes::RENDER_SLOTS], + /// Force a full scrub on next pass claim (first use, cancel, error, or firmware recovery). + scrub_full: [bool; sizes::RENDER_SLOTS], + /// Whether the most recent claim of each render pass slot required a full scrub/work write. + last_full: [bool; sizes::RENDER_SLOTS], + /// Displaced pass slots staged after publication to run once `Shared::state` is released. + staged: ScrubBatch, + /// A clean render retired since the last unlock; stage any remaining displaced pass slots + /// only after publication finishes so a freshly displaced slot never blocks immediate reuse. + scrub_pending: bool, +} + pub(crate) struct Slots { pub(crate) cursor: u32, - pub(crate) pass_busy: u32, + pub(crate) pass_busy: u64, pub(crate) pass_cursor: u32, + scrub_gen: u64, pub(crate) stats: SlotStats, - compute_lifetime: Lifetime, - pass_lifetime: Lifetime, - // Last-owner leases remain bound through retirement and displacement. Replaced only - // when the displaced unit is safely rebound to a new publication. - compute_owner: [Option>; 2], - pass_owner: [Option>; 2], - pending_compute_retarget: [Option; 2], - pending_pass_retarget: [Option; 2], - pending_compute_owner: [Option>; 2], - pending_pass_owner: [Option>; 2], + /// Shared atomic state for off-lock pre-scrubbing of displaced render pass slots. + scrub: Arc, + /// The compute and render owners, on the heap: `Firmware` (and so `Slots`) is built on the + /// probe's stack, which has no room for them. + compute: KBox, + render: KBox, } impl Slots { + #[inline(never)] pub(crate) fn new() -> Result { Ok(Self { cursor: 0, pass_busy: 0, pass_cursor: 0, + scrub_gen: 0, stats: SlotStats::default(), - compute_lifetime: Lifetime::new(), - pass_lifetime: Lifetime::new(), - compute_owner: [None, None], - pass_owner: [None, None], - pending_compute_retarget: [None, None], - pending_pass_retarget: [None, None], - pending_compute_owner: [None, None], - pending_pass_owner: [None, None], + scrub: Arc::new(ScrubState::new(), GFP_KERNEL)?, + compute: KBox::init( + init!(ComputeOwners { + lifetime: Lifetime::new(true), + owner: [const { None }; sizes::COMPUTE_UNITS], + pending_retarget: [None; sizes::COMPUTE_UNITS], + pending_owner: [const { None }; sizes::COMPUTE_UNITS], + arena: [const { None }; sizes::COMPUTE_UNITS], + pending_arena: [const { None }; sizes::COMPUTE_UNITS], + retained_uma: [const { None }; sizes::COMPUTE_UNITS], + pending_uma: [const { None }; sizes::COMPUTE_UNITS], + scrub_full: [true; sizes::COMPUTE_UNITS], + last_full: [true; sizes::COMPUTE_UNITS], + }), + GFP_KERNEL, + )?, + render: KBox::init( + init!(RenderOwners { + lifetime: Lifetime::new(true), + owner: [const { None }; sizes::RENDER_SLOTS], + pending_retarget: [None; sizes::RENDER_SLOTS], + pending_owner: [const { None }; sizes::RENDER_SLOTS], + arena: [const { None }; sizes::RENDER_SLOTS], + pending_arena: [const { None }; sizes::RENDER_SLOTS], + scrub_full: [true; sizes::RENDER_SLOTS], + last_full: [true; sizes::RENDER_SLOTS], + staged: ScrubBatch::new(), + scrub_pending: false, + }), + GFP_KERNEL, + )?, }) } pub(crate) fn init(&self) -> Result { @@ -408,94 +1037,783 @@ impl Slots { } #[allow(dead_code)] pub(crate) fn compute_generation(&self, k: usize) -> Result { - if k >= 2 { + if k >= sizes::COMPUTE_UNITS { return Err(EINVAL); } - Ok(self.compute_lifetime.generation(k)) + Ok(self.compute.lifetime.generation(k)) } #[allow(dead_code)] pub(crate) fn pass_generation(&self, k: usize) -> Result { - if k >= 2 { + if k >= sizes::RENDER_SLOTS { return Err(EINVAL); } - Ok(self.pass_lifetime.generation(k)) + Ok(self.render.lifetime.generation(k)) } pub(crate) fn compute_exhausted(&self) -> bool { - self.compute_lifetime.exhausted() + // Ledger indices above the most units a VM gets never have an owner. + self.compute + .lifetime + .exhausted_within(super::params::compute_units()) + } + /// Whether none of the first `n` compute units (a VM's own) can ever be claimed again. + #[allow(dead_code)] + pub(crate) fn compute_exhausted_within(&self, n: usize) -> bool { + self.compute.lifetime.exhausted_within(n) + } + /// Whether none of the compute units in `mask` (bit `k` -> unit `k`) can ever be claimed. + pub(crate) fn compute_exhausted_in_mask(&self, mask: u32) -> bool { + self.compute.lifetime.exhausted_in_mask(mask) + } + /// Bitmask of permanently quarantined compute units (`0..COMPUTE_UNITS`). + pub(crate) fn quarantined_compute_mask(&self) -> u32 { + self.compute.lifetime.quarantined_mask() } pub(crate) fn render_exhausted(&self) -> bool { - self.pass_lifetime.exhausted() + self.render.lifetime.exhausted() + } + /// Whether none of the first `n` render pass slots (a VM's own) can ever be claimed again. + pub(crate) fn render_exhausted_within(&self, n: usize) -> bool { + self.render.lifetime.exhausted_within(n) + } + /// Whether any base compute unit (`0..BASE_COMPUTE_UNITS`) is permanently quarantined. + pub(crate) fn base_compute_quarantined(&self) -> bool { + self.compute + .lifetime + .any_quarantined_within(super::resources::BASE_COMPUTE_UNITS) + } + /// Whether any base render pass slot (`0..BASE_RENDER_SLOTS`) is permanently quarantined. + pub(crate) fn base_render_quarantined(&self) -> bool { + self.render + .lifetime + .any_quarantined_within(super::resources::BASE_RENDER_SLOTS) } pub(crate) fn lifetime_counts(&self) -> [super::pools::lifetime::Counts; 2] { - [self.compute_lifetime.counts(), self.pass_lifetime.counts()] + [self.compute.lifetime.counts(), self.render.lifetime.counts()] + } + /// Whether one of the first `n` compute units can be claimed now. + #[allow(dead_code)] + pub(crate) fn compute_available(&self, n: usize) -> bool { + (0..n.min(sizes::COMPUTE_UNITS)).any(|k| self.compute.lifetime.available(k)) + } + /// Whether any compute unit in `mask` can be claimed now. + pub(crate) fn compute_available_in_mask(&self, mask: u32) -> bool { + let mut rem = mask; + while rem != 0 { + let k = rem.trailing_zeros() as usize; + rem &= rem - 1; + if k < sizes::COMPUTE_UNITS && self.compute.lifetime.available(k) { + return true; + } + } + false + } + /// Whether any compute unit in `mask` eligible for `pipe` can be claimed now. + /// Pipe 0 may claim any bit in `mask`; secondary pipes stay in + /// `PIPE1_COMPUTE_START..COMPUTE_UNITS` so `0..PIPE1_COMPUTE_START` only ever hold pipe-0 + /// leases. + pub(crate) fn compute_available_in_mask_for_pipe(&self, mask: u32, pipe: usize) -> bool { + let allowed = if pipe == 0 { + mask + } else { + mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) + }; + self.compute_available_in_mask(allowed) + } + /// Whether one of the first `n` compute units eligible for `pipe` can be claimed now. + #[allow(dead_code)] + pub(crate) fn compute_available_for_pipe(&self, n: usize, pipe: usize) -> bool { + let limit = n.min(sizes::COMPUTE_UNITS); + let mask = if limit >= 32 { + u32::MAX + } else { + (1u32 << limit) - 1 + }; + self.compute_available_in_mask_for_pipe(mask, pipe) + } + /// Whether one of the first `n` render pass slots can be claimed now. + #[allow(dead_code)] + pub(crate) fn pass_available(&self, n: usize) -> bool { + let mut saw_scrubbing = false; + let limit = n.min(sizes::RENDER_SLOTS); + for k in 0..limit { + if self.pass_busy & (1 << k) == 0 && self.render.lifetime.available(k) { + if !self.scrub.is_scrubbing(k) { + return true; + } + saw_scrubbing = true; + } + } + if saw_scrubbing { + self.scrub.waiter.store(true, Ordering::SeqCst); + for k in 0..limit { + if self.pass_busy & (1 << k) == 0 + && self.render.lifetime.available(k) + && !self.scrub.is_scrubbing(k) + { + return true; + } + } + } + false + } + /// Whether any render pass slot is currently being scrubbed off-lock. + pub(crate) fn scrubbing_active(&self) -> bool { + self.scrub.scrubbing.load(Ordering::Acquire) != 0 + } + /// Consumes the wakeup flag set when an off-lock scrub unblocks a waiting render submitter. + pub(crate) fn take_scrub_woke(&self) -> bool { + self.scrub.woke.swap(false, Ordering::AcqRel) + } + /// Total pass scrubs including completed off-lock pre-scrubs. + pub(crate) fn pass_scrubs_total(&self) -> u64 { + self.stats + .pass_scrubs + .saturating_add(self.scrub.pass_scrubs.load(Ordering::Relaxed)) + } + /// Total tilemap bytes cleared including completed off-lock pre-scrubs. + pub(crate) fn tilemap_clear_bytes_total(&self) -> u64 { + self.stats + .tilemap_clear_bytes + .saturating_add(self.scrub.tilemap_clear_bytes.load(Ordering::Relaxed)) + } + fn fold_scrub_stats(&mut self) { + let scrubs = self.scrub.pass_scrubs.swap(0, Ordering::Relaxed); + let bytes = self.scrub.tilemap_clear_bytes.swap(0, Ordering::Relaxed); + self.stats.pass_scrubs = self.stats.pass_scrubs.saturating_add(scrubs); + self.stats.tilemap_clear_bytes = self.stats.tilemap_clear_bytes.saturating_add(bytes); + } + /// Records that a clean render retired so displaced pass slots left idle after + /// publication are staged for off-lock pre-scrubbing right before dropping `Shared::state`. + pub(crate) fn note_render_retired(&mut self) { + self.render.scrub_pending = true; + } + /// Stages any newly displaced, cleanly retired render pass slots for off-lock pre-scrubbing, + /// scanning cursor-ordered from `pass_cursor` so the slots `pick_pass_in_for` will reach next + /// are scrubbed first. Never touches `Published` or undisplaced `Retired` slots. + pub(crate) fn stage_displaced_pass_scrubs(&mut self) { + self.render.scrub_pending = false; + self.fold_scrub_stats(); + let start = self.pass_cursor as usize % sizes::RENDER_SLOTS; + for i in 0..sizes::RENDER_SLOTS { + let k = (start + i) % sizes::RENDER_SLOTS; + let bit = 1u64 << k; + if self.pass_busy & bit != 0 + || !self.render.lifetime.available(k) + || self.render.scrub_full[k] + || self.scrub.is_scrubbing(k) + || self.scrub.is_clean(k) + || self.render.owner[k] + .as_ref() + .is_none_or(|vm| vm.vm.is_closed()) + { + continue; + } + let Some(arena) = self.render.arena[k].clone() else { + continue; + }; + if self.render.staged.is_full() { + self.render.scrub_pending = true; + break; + } + self.scrub.scrubbing.fetch_or(bit, Ordering::SeqCst); + let generation = self.scrub.generation.load(Ordering::Acquire); + let item = PendingScrub { + slot: k, + arena, + state: self.scrub.clone(), + generation, + done: false, + }; + if !self.render.staged.push(item) { + self.render.scrub_pending = true; + break; + } + } + } + /// Removes all staged off-lock pass scrubs so the caller can run them outside `Shared::state`. + pub(crate) fn take_staged_scrubs(&mut self) -> ScrubBatch { + core::mem::replace(&mut self.render.staged, ScrubBatch::new()) + } + /// Stages idle displaced render pass slots after publication (when `allow_stage` and a + /// clean render retired since the last unlock) and hands them off for off-lock execution. + pub(crate) fn stage_and_take_scrubs(&mut self, allow_stage: bool) -> ScrubBatch { + if allow_stage && core::mem::take(&mut self.render.scrub_pending) { + self.stage_displaced_pass_scrubs(); + } else if !allow_stage { + self.render.scrub_pending = false; + } + self.take_staged_scrubs() + } + /// Releases displaced compute-unit and render-pass leases owned by closed VMs while + /// preserving active, in-flight, undisplaced, scrubbing, and quarantined slots. + /// + /// Returns `true` if any non-quarantined slot still holds a closed-VM lease awaiting + /// retirement, displacement, or an in-progress off-lock pass scrub. + pub(crate) fn reclaim_closed(&mut self) -> bool { + let mut remaining = false; + for k in 0..sizes::COMPUTE_UNITS { + if self.compute.lifetime.is_quarantined(k) { + continue; + } + let owner_closed = self.compute.owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + let pending_closed = self.compute.pending_owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + if !owner_closed && !pending_closed { + continue; + } + if owner_closed + && self.compute.lifetime.available(k) + && self.compute.pending_owner[k].is_none() + && self.compute.pending_arena[k].is_none() + && self.compute.pending_uma[k].is_none() + { + self.compute.owner[k] = None; + self.compute.arena[k] = None; + self.compute.scrub_full[k] = true; + self.compute.last_full[k] = true; + } else { + remaining = true; + } + } + for k in 0..sizes::RENDER_SLOTS { + if self.render.lifetime.is_quarantined(k) { + continue; + } + let owner_closed = self.render.owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + let pending_closed = self.render.pending_owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + if !owner_closed && !pending_closed { + continue; + } + let bit = 1u64 << k; + if owner_closed + && self.pass_busy & bit == 0 + && self.render.lifetime.available(k) + && self.render.pending_owner[k].is_none() + && self.render.pending_arena[k].is_none() + { + if self.scrub.is_scrubbing(k) { + self.scrub.waiter.store(true, Ordering::SeqCst); + } + if !self.scrub.is_scrubbing(k) { + self.render.owner[k] = None; + self.render.arena[k] = None; + self.render.scrub_full[k] = true; + self.render.last_full[k] = true; + self.scrub.clear_clean(k); + } else { + remaining = true; + } + } else { + remaining = true; + } + } + remaining + } + /// Compute units published and not yet retired. + pub(crate) fn compute_published(&self) -> u32 { + self.compute.lifetime.published() + } + /// Render pass slots published and not yet retired. + #[allow(dead_code)] + pub(crate) fn render_published(&self) -> u32 { + self.render.lifetime.published() } #[allow(dead_code)] pub(crate) fn free_compute(&self) -> u32 { - (0..2) - .filter(|&k| self.compute_lifetime.available(k)) - .count() as u32 + self.free_compute_in(super::params::compute_units()) + } + /// Available compute units within the first `n` units (a VM's prepared count). + #[allow(dead_code)] + pub(crate) fn free_compute_in(&self, n: usize) -> u32 { + self.free_compute_in_for_pipe(n, 0) } + /// Available compute units in `mask` eligible for `pipe`. + pub(crate) fn free_compute_in_mask_for_pipe(&self, mask: u32, pipe: usize) -> u32 { + let mut rem = if pipe == 0 { + mask + } else { + mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) + }; + let mut count = 0u32; + while rem != 0 { + let k = rem.trailing_zeros() as usize; + rem &= rem - 1; + if k < sizes::COMPUTE_UNITS && self.compute.lifetime.available(k) { + count += 1; + } + } + count + } + /// Available compute units within the first `n` units eligible for `pipe`. + #[allow(dead_code)] + pub(crate) fn free_compute_in_for_pipe(&self, n: usize, pipe: usize) -> u32 { + let limit = n.min(sizes::COMPUTE_UNITS); + let mask = if limit >= 32 { + u32::MAX + } else { + (1u32 << limit) - 1 + }; + self.free_compute_in_mask_for_pipe(mask, pipe) + } + /// Forces a full scrub on the next claim of every slot (after firmware recovery). + #[allow(dead_code)] + pub(crate) fn invalidate_scrub(&mut self) { + self.scrub_gen = self.scrub_gen.wrapping_add(1); + self.compute.scrub_full = [true; sizes::COMPUTE_UNITS]; + self.render.scrub_full = [true; sizes::RENDER_SLOTS]; + self.render.scrub_pending = false; + self.scrub.clear_all_clean(); + } + + /// Forces a full scrub on the next claim of the units in `f` (after an affected error). + #[allow(dead_code)] + pub(crate) fn mark_dirty(&mut self, f: &Claims) { + for &k in &f.slot[..(f.slot_count as usize).min(f.slot.len())] { + if let Some(dirty) = self.compute.scrub_full.get_mut(k as usize) { + *dirty = true; + } + } + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + self.render.scrub_full[k] = true; + self.scrub.clear_clean(k); + } + } + + #[allow(dead_code)] pub(crate) fn claim_compute( &mut self, - arena: &super::resources::ComputeArena, + units: &super::resources::Prepared, f: &mut Claims, _j: u32, ) -> Result> { - if f.slot_count != 0 { + self.claim_compute_for(units, f, None) + } + + /// Whether the most recent claim of compute unit `k` requires writing the entire work + /// object (first use, cross-VM switch, cancelled preparation, error, or firmware recovery) + /// rather than only the active non-zero spans. + pub(crate) fn compute_needs_full_work(&self, k: usize) -> bool { + self.compute.last_full.get(k).copied().unwrap_or(true) + } + + #[allow(dead_code)] + pub(crate) fn claim_compute_for( + &mut self, + units: &super::resources::Prepared, + f: &mut Claims, + vm_id: Option, + ) -> Result> { + self.claim_compute_for_pipe(units, f, vm_id, 0) + } + + pub(crate) fn claim_compute_for_pipe( + &mut self, + units: &super::resources::Prepared, + f: &mut Claims, + vm_id: Option, + pipe: usize, + ) -> Result> { + if f.slot_count as usize >= f.slot.len() { return Ok(None); } - for i in 0..2 { - let k = (self.cursor as usize + i) % 2; - if self.compute_lifetime.claim(k) { - if let Err(e) = arena.compute[k].scrub() { - self.compute_lifetime.cancel(k); - return Err(e); + // Prefer a warm unit already owned by `vm_id` (`!scrub_full`), then an unowned unit, + // before falling back to round-robin over `allowed`: pipe 0 spans `mask`, while + // secondary pipes stay in `PIPE1_COMPUTE_START..COMPUTE_UNITS` so `0..PIPE1_COMPUTE_START` + // only ever hold pipe-0 leases and 2-unit base/SCS VMs never split across two pipes. + let mask = units.compute_slot_mask()?; + let allowed = if pipe == 0 { + mask + } else { + mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) + }; + if allowed == 0 { + return Ok(None); + } + let n = sizes::COMPUTE_UNITS; + let base_cursor = (self.cursor as usize) % n; + let p0_mask = (1u32 << sizes::PIPE1_COMPUTE_START) - 1; + // On pipe 0, prefer pipe-0-exclusive units (`0..PIPE1_COMPUTE_START`) before spilling + // into secondary-pipe units (`PIPE1_COMPUTE_START..COMPUTE_UNITS`) so concurrent + // secondary pipes keep maximum unit headroom. + let tiers: [u32; 2] = if pipe == 0 { + [allowed & p0_mask, allowed & !p0_mask] + } else { + [allowed, 0] + }; + let mut chosen = None; + if let Some(id) = vm_id { + // 1. Reuse a warm unit already owned by `vm_id` (preferring pipe-0-exclusive units). + 'warm: for tier in tiers { + if tier == 0 { + continue; + } + for i in 0..n { + let k = (base_cursor + i) % n; + if (tier & (1u32 << k)) != 0 + && !self.compute.scrub_full[k] + && self.compute.owner[k] + .as_ref() + .is_some_and(|prev| prev.id == id) + && self.compute.lifetime.claim(k) + { + chosen = Some(k); + break 'warm; + } + } + } + // 2. Claim an unowned unit before stealing another VM's warm unit. + if chosen.is_none() { + 'unowned: for tier in tiers { + if tier == 0 { + continue; + } + for i in 0..n { + let k = (base_cursor + i) % n; + if (tier & (1u32 << k)) != 0 + && self.compute.owner[k].is_none() + && self.compute.lifetime.claim(k) + { + chosen = Some(k); + break 'unowned; + } + } } - f.slot[0] = k as u32; - f.slot_count = 1; - self.cursor = (1 - k) as u32; - return Ok(Some(k)); } } - Ok(None) + // 3. Fall back to round-robin over any available unit (preferring pipe-0-exclusive). + if chosen.is_none() { + 'any: for tier in tiers { + if tier == 0 { + continue; + } + for i in 0..n { + let k = (base_cursor + i) % n; + if (tier & (1u32 << k)) != 0 && self.compute.lifetime.claim(k) { + chosen = Some(k); + break 'any; + } + } + } + } + let Some(k) = chosen else { + return Ok(None); + }; + let arena_changed = self.compute.arena[k] + .as_ref() + .zip(units.compute_arena(k).as_ref()) + .is_some_and(|(a, b)| !Arc::ptr_eq(a, b)); + let full = self.compute.scrub_full[k] + || arena_changed + || vm_id.is_none_or(|id| { + self.compute.owner[k] + .as_ref() + .is_none_or(|prev| prev.id != id) + }); + if let Err(e) = units.compute_unit(k).and_then(|unit| unit.scrub(full)) { + self.compute.lifetime.cancel(k); + return Err(e); + } + self.compute.last_full[k] = full; + f.slot[f.slot_count as usize] = k as u32; + f.slot_count += 1; + f.compute_pipe = pipe as u8; + self.cursor = ((k + 1) % n) as u32; + Ok(Some(k)) } + #[allow(dead_code)] pub(crate) fn pick_pass( &self, arena: &super::resources::RenderArena, geo: &Geometry, - picked: u32, + picked: u64, ) -> Option { - for i in 0..2 { - let k = (self.pass_cursor as usize + i) % 2; + let n = arena.passes.len().min(sizes::RENDER_SLOTS); + let mut fallback = None; + let mut saw_scrubbing = false; + for i in 0..n { + let k = (self.pass_cursor as usize + i) % n; let p = &arena.passes[k]; - if (self.pass_busy | picked) & (1 << k) == 0 - && self.pass_lifetime.available(k) + if (self.pass_busy | picked) & (1u64 << k) == 0 + && self.render.lifetime.available(k) + && geo.tpc_bytes <= p.tpc.size as u64 + && geo.tilemap_bytes <= p.tilemap.size as u64 + { + if self.scrub.is_scrubbing(k) { + saw_scrubbing = true; + continue; + } + if self.scrub.is_clean(k) { + return Some(k); + } + fallback.get_or_insert(k); + } + } + if fallback.is_some() { + return fallback; + } + if saw_scrubbing { + self.scrub.waiter.store(true, Ordering::SeqCst); + for i in 0..n { + let k = (self.pass_cursor as usize + i) % n; + let p = &arena.passes[k]; + if (self.pass_busy | picked) & (1u64 << k) == 0 + && self.render.lifetime.available(k) + && !self.scrub.is_scrubbing(k) + && geo.tpc_bytes <= p.tpc.size as u64 + && geo.tilemap_bytes <= p.tilemap.size as u64 + { + return Some(k); + } + } + } + None + } + #[allow(dead_code)] + pub(crate) fn pick_pass_in( + &self, + resources: &super::resources::Prepared, + geo: &Geometry, + picked: u64, + ) -> Option { + self.pick_pass_in_for(resources, geo, picked, None) + } + /// Selects a render pass slot in `resources` with capacity for `geo`, preferring slots + /// already owned by `vm_id` (clean before dirty) and unowned slots before retargeting + /// another VM's warm pass slot. + pub(crate) fn pick_pass_in_for( + &self, + resources: &super::resources::Prepared, + geo: &Geometry, + picked: u64, + vm_id: Option, + ) -> Option { + let n = resources.render_passes().ok()?.min(sizes::RENDER_SLOTS); + let mut same_clean_partial = None; + let mut same_dirty = None; + let mut unowned_clean = None; + let mut unowned_dirty = None; + let mut other_full_clean = None; + let mut other_clean_partial = None; + let mut other_dirty = None; + let mut saw_scrubbing = false; + for i in 0..n { + let k = (self.pass_cursor as usize + i) % n; + let Ok(p) = resources.render_pass(k) else { + continue; + }; + if (self.pass_busy | picked) & (1u64 << k) == 0 + && self.render.lifetime.available(k) && geo.tpc_bytes <= p.tpc.size as u64 && geo.tilemap_bytes <= p.tilemap.size as u64 { - return Some(k); + if self.scrub.is_scrubbing(k) { + saw_scrubbing = true; + continue; + } + let clean = self.scrub.is_clean(k); + let full_clean = clean + && resources.render_pass_dirty(k).is_ok_and(|d| { + let need = d.tilemap.load(Ordering::Acquire).min(geo.tilemap_bytes); + need <= d.tilemap_clean.load(Ordering::Acquire) + && d.heap.load(Ordering::Acquire) == 0 + }); + if let Some(id) = vm_id { + let same_vm = !self.render.scrub_full[k] + && self.render.owner[k].as_ref().is_some_and(|o| o.id == id); + if same_vm { + if full_clean { + return Some(k); + } + if clean { + same_clean_partial.get_or_insert(k); + } else { + same_dirty.get_or_insert(k); + } + } else if self.render.owner[k].is_none() { + if full_clean { + unowned_clean.get_or_insert(k); + } else { + unowned_dirty.get_or_insert(k); + } + } else if full_clean { + other_full_clean.get_or_insert(k); + } else if clean { + other_clean_partial.get_or_insert(k); + } else { + other_dirty.get_or_insert(k); + } + } else if full_clean { + return Some(k); + } else if clean { + other_clean_partial.get_or_insert(k); + } else { + other_dirty.get_or_insert(k); + } + } + } + if let Some(k) = same_clean_partial + .or(same_dirty) + .or(unowned_clean) + .or(unowned_dirty) + .or(other_full_clean) + .or(other_clean_partial) + .or(other_dirty) + { + return Some(k); + } + if saw_scrubbing { + self.scrub.waiter.store(true, Ordering::SeqCst); + for i in 0..n { + let k = (self.pass_cursor as usize + i) % n; + let Ok(p) = resources.render_pass(k) else { + continue; + }; + if (self.pass_busy | picked) & (1u64 << k) == 0 + && self.render.lifetime.available(k) + && !self.scrub.is_scrubbing(k) + && geo.tpc_bytes <= p.tpc.size as u64 + && geo.tilemap_bytes <= p.tilemap.size as u64 + { + return Some(k); + } } } None } + /// Whether the most recent claim of render pass slot `k` requires writing the entire + /// TA/FS work images (first use, cross-VM switch, cancelled preparation, error, or + /// firmware recovery) rather than only the active non-zero spans. + pub(crate) fn render_needs_full_work(&self, k: usize) -> bool { + self.render.last_full.get(k).copied().unwrap_or(true) + } + + #[allow(dead_code)] pub(crate) fn claim_pass(&mut self, arena: &super::resources::RenderArena, k: usize) -> Result { - if k >= 2 || !self.pass_lifetime.claim(k) { + self.claim_pass_for(arena, k, None) + } + + #[allow(dead_code)] + pub(crate) fn claim_pass_for( + &mut self, + arena: &super::resources::RenderArena, + k: usize, + vm_id: Option, + ) -> Result { + let n = arena.passes.len().min(sizes::RENDER_SLOTS); + if k >= n || self.scrub.is_scrubbing(k) || !self.render.lifetime.claim(k) { return Err(EBUSY); } + self.fold_scrub_stats(); // Only a retired displaced owner may reach here; no in-flight storage is reset. + let full = self.render.scrub_full[k] + || vm_id.is_none_or(|id| { + self.render.owner[k] + .as_ref() + .is_none_or(|prev| prev.id != id) + }); + let pre_cleaned = self.scrub.take_clean(k); let p = &arena.passes[k]; - if let Err(e) = p.scrub( - 1, - arena.tpc_dirty[k].load(Ordering::Relaxed), - arena.tilemap_dirty[k].load(Ordering::Relaxed), - &mut self.stats, - ) { - self.pass_lifetime.cancel(k); - return Err(e); + if full { + let prev_tpc = arena.tpc_dirty[k].load(Ordering::Acquire); + let prev_tilemap = arena.tilemap_dirty[k].load(Ordering::Acquire); + if let Err(e) = p.scrub(prev_tpc, 0, prev_tilemap, 0x4000, true, &mut self.stats) { + self.render.lifetime.cancel(k); + return Err(e); + } + arena.tpc_dirty[k].store(0, Ordering::Relaxed); + arena.tilemap_dirty[k].store(0, Ordering::Relaxed); + arena.tilemap_last[k].store(0, Ordering::Relaxed); + arena.tilemap_clean[k].store(0, Ordering::Relaxed); + arena.heap_dirty[k].store(0, Ordering::Relaxed); + } else { + let prev_dirty = arena.tilemap_dirty[k].load(Ordering::Acquire); + let already = arena.tilemap_clean[k].load(Ordering::Acquire); + let heap = arena.heap_dirty[k].load(Ordering::Acquire); + let delta = prev_dirty.saturating_sub(already); + if !(pre_cleaned && delta == 0 && heap == 0) { + if let Err(e) = p.scrub(0, already, delta, heap, false, &mut self.stats) { + self.render.lifetime.cancel(k); + return Err(e); + } + arena.heap_dirty[k].store(0, Ordering::Relaxed); + arena.tilemap_dirty[k].store(0, Ordering::Relaxed); + arena.tilemap_clean[k].store(0, Ordering::Relaxed); + } } - arena.tpc_dirty[k].store(0, Ordering::Relaxed); - arena.tilemap_dirty[k].store(0, Ordering::Relaxed); - self.pass_cursor = (1 - k) as u32; + self.render.last_full[k] = full; + self.pass_cursor = ((k + 1) % n) as u32; + Ok(()) + } + + #[allow(dead_code)] + pub(crate) fn claim_pass_in( + &mut self, + resources: &super::resources::Prepared, + k: usize, + vm_id: Option, + tilemap_bytes: u64, + ) -> Result { + let n = resources.render_passes()?.min(sizes::RENDER_SLOTS); + if k >= n || self.scrub.is_scrubbing(k) || !self.render.lifetime.claim(k) { + return Err(EBUSY); + } + self.fold_scrub_stats(); + let full = self.render.scrub_full[k] + || vm_id.is_none_or(|id| { + self.render.owner[k] + .as_ref() + .is_none_or(|prev| prev.id != id) + }); + let pre_cleaned = self.scrub.take_clean(k); + let p = resources.render_pass(k)?; + let d = resources.render_pass_dirty(k)?; + if full { + let prev_tpc = d.tpc.load(Ordering::Acquire); + let prev_tilemap = d.tilemap.load(Ordering::Acquire); + if let Err(e) = p.scrub(prev_tpc, 0, prev_tilemap, 0x4000, true, &mut self.stats) { + self.render.lifetime.cancel(k); + return Err(e); + } + d.tpc.store(0, Ordering::Relaxed); + d.tilemap.store(0, Ordering::Relaxed); + d.tilemap_last.store(0, Ordering::Relaxed); + d.tilemap_clean.store(0, Ordering::Relaxed); + d.heap.store(0, Ordering::Relaxed); + } else { + // On clean same-VM reuse, zero only the uncleaned overlap with the current pass's + // tilemap (`already..need`) and the active heap span; preserve the high-water mark + // in `d.tilemap` for cross-VM or recovery full scrubs. + let prev_dirty = d.tilemap.load(Ordering::Acquire); + let already = d.tilemap_clean.load(Ordering::Acquire); + let heap = d.heap.load(Ordering::Acquire); + let need = prev_dirty.min(tilemap_bytes); + let delta = need.saturating_sub(already); + if !(pre_cleaned && delta == 0 && heap == 0) { + if let Err(e) = p.scrub(0, already, delta, heap, false, &mut self.stats) { + self.render.lifetime.cancel(k); + return Err(e); + } + d.heap.store(0, Ordering::Relaxed); + if prev_dirty != 0 && need >= prev_dirty { + d.tilemap.store(0, Ordering::Relaxed); + d.tilemap_clean.store(0, Ordering::Relaxed); + } else if delta != 0 { + d.tilemap_clean.store(need, Ordering::Relaxed); + } + } + } + self.render.last_full[k] = full; + self.pass_cursor = ((k + 1) % n) as u32; Ok(()) } #[allow(dead_code)] @@ -522,131 +1840,317 @@ impl Slots { /// Full wire retirement is a separate condition for hardware qualification. pub(crate) fn note_published(&mut self, f: &Claims) { for &k in &f.slot[..f.slot_count as usize] { - if let Some(proof) = self.pending_compute_retarget[k as usize].take() { + if let Some(proof) = self.compute.pending_retarget[k as usize].take() { self.stats.cross_vm_retargets[0] = self.stats.cross_vm_retargets[0].saturating_add(1); self.stats.last_retarget[0] = proof; } } - for k in 0..2 { - if f.pass_mask & (1 << k) != 0 { - if let Some(proof) = self.pending_pass_retarget[k].take() { - self.stats.cross_vm_retargets[1] = - self.stats.cross_vm_retargets[1].saturating_add(1); - self.stats.last_retarget[1] = proof; + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + if let Some(proof) = self.render.pending_retarget[k].take() { + self.stats.cross_vm_retargets[1] = + self.stats.cross_vm_retargets[1].saturating_add(1); + self.stats.last_retarget[1] = proof; + } + } + } + + /// Retains one newly claimed compute unit's VM/ASID lease and owner arena in O(1). + pub(crate) fn hold_compute_slot( + &mut self, + k: usize, + vm: &Arc, + resources: &super::resources::Prepared, + ) -> Result { + if k >= sizes::COMPUTE_UNITS { + return Err(EINVAL); + } + self.compute.pending_retarget[k] = self.compute.owner[k] + .as_ref() + .and_then(|old| Self::vm_retarget(k, old, vm)); + self.compute.pending_owner[k] = Some(vm.clone()); + self.compute.pending_arena[k] = resources.compute_arena(k); + self.compute.pending_uma[k] = resources.compute_unit(k).ok().map(ComputeSlot::uma_lease); + Ok(()) + } + + /// Retains one newly claimed render pass slot's VM/ASID lease and owner arena in O(1). + pub(crate) fn hold_render_pass( + &mut self, + k: usize, + vm: &Arc, + resources: &super::resources::Prepared, + ) -> Result { + if k >= sizes::RENDER_SLOTS { + return Err(EINVAL); + } + self.render.pending_retarget[k] = self.render.owner[k] + .as_ref() + .and_then(|old| Self::vm_retarget(k, old, vm)); + self.render.pending_owner[k] = Some(vm.clone()); + self.render.pending_arena[k] = resources.pass_owner_arena(k); + Ok(()) + } + + /// Validates claim bounds/masks and confirms every claimed slot already holds a pending + /// VM lease without re-cloning `Arc` leases at publication time. + pub(crate) fn verify_held(&self, f: &Claims) -> Result { + if f.slot_count as usize > f.slot.len() + || f.pass_count as usize > f.pass.len() + || f.pass_mask & !PASS_MASK != 0 + { + return Err(EINVAL); + } + for &k in &f.slot[..f.slot_count as usize] { + let k = k as usize; + if k >= sizes::COMPUTE_UNITS || self.compute.pending_owner[k].is_none() { + return Err(EINVAL); + } + } + if f.pass_count != 0 { + let mut mask = 0u64; + for &k in &f.pass[..f.pass_count as usize] { + let k = k as usize; + if k >= sizes::RENDER_SLOTS || self.render.pending_owner[k].is_none() { + return Err(EINVAL); + } + let bit = 1u64 << k; + if mask & bit != 0 { + return Err(EINVAL); + } + mask |= bit; + } + if mask != f.pass_mask { + return Err(EINVAL); + } + } else { + let mut mask = f.pass_mask; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + if self.render.pending_owner[k].is_none() { + return Err(EINVAL); } } } + Ok(()) } /// Retains each actual owner's VM/ASID binding through the firmware's last-owner era. /// A previous lease is replaced only after the new publication fully retires. + #[allow(dead_code)] pub(crate) fn hold_vm(&mut self, f: &Claims, vm: &Arc) -> Result { - if f.slot_count > 2 - || f.slot[..f.slot_count as usize].iter().any(|&k| k >= 2) - || f.pass_mask & !3 != 0 + if f.slot_count as usize > f.slot.len() + || f.slot[..f.slot_count as usize] + .iter() + .any(|&k| k as usize >= sizes::COMPUTE_UNITS) + || f.pass_count as usize > f.pass.len() + || f.pass_mask & !PASS_MASK != 0 { return Err(EINVAL); } + if f.pass_count != 0 { + let mut mask = 0u64; + for &k in &f.pass[..f.pass_count as usize] { + if k as usize >= sizes::RENDER_SLOTS { + return Err(EINVAL); + } + let bit = 1u64 << k; + if mask & bit != 0 { + return Err(EINVAL); + } + mask |= bit; + } + if mask != f.pass_mask { + return Err(EINVAL); + } + } for &k in &f.slot[..f.slot_count as usize] { let k = k as usize; - self.pending_compute_retarget[k] = self.compute_owner[k] + self.compute.pending_retarget[k] = self.compute.owner[k] .as_ref() .and_then(|old| Self::vm_retarget(k, old, vm)); - self.pending_compute_owner[k] = Some(vm.clone()); + self.compute.pending_owner[k] = Some(vm.clone()); } - for k in 0..2 { - if f.pass_mask & (1 << k) != 0 { - self.pending_pass_retarget[k] = self.pass_owner[k] - .as_ref() - .and_then(|old| Self::vm_retarget(k, old, vm)); - self.pending_pass_owner[k] = Some(vm.clone()); - } + let mut mask = f.pass_mask; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + self.render.pending_retarget[k] = self.render.owner[k] + .as_ref() + .and_then(|old| Self::vm_retarget(k, old, vm)); + self.render.pending_owner[k] = Some(vm.clone()); } Ok(()) } + /// With [`Self::hold_vm`]: the claimed units' arenas, held with their VM leases. The VM's + /// own cache lets go of its arenas when its client closes. + #[allow(dead_code)] + pub(crate) fn hold_arenas(&mut self, f: &Claims, resources: &super::resources::Prepared) { + for &k in &f.slot[..(f.slot_count as usize).min(f.slot.len())] { + if let Some(cell) = self.compute.pending_arena.get_mut(k as usize) { + *cell = resources.compute_arena(k as usize); + } + if let Some(cell) = self.compute.pending_uma.get_mut(k as usize) { + *cell = resources + .compute_unit(k as usize) + .ok() + .map(ComputeSlot::uma_lease); + } + } + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + self.render.pending_arena[k] = resources.pass_owner_arena(k); + } + } + /// Reserve the actual same-slot publication. Call before producers become visible. - pub(crate) fn publish(&mut self, f: &Claims) -> Result { + pub(crate) fn publish(&mut self, f: &mut Claims) -> Result { // Validate on a private copy so a failure changes no ownership. - let mut c = self.compute_lifetime.clone(); - let mut p = self.pass_lifetime.clone(); + let mut c = self.compute.lifetime.clone(); + let mut p = self.render.lifetime.clone(); for &k in &f.slot[..f.slot_count as usize] { - if !c.publish(k as usize) { + if !c.publish_on(k as usize, f.compute_pipe) { return Err(EBUSY); } } - for k in 0..2 { - if f.pass_mask & (1 << k) != 0 && !p.publish(k) { - return Err(EBUSY); + if f.pass_count != 0 { + if f.pass_count as usize > f.pass.len() { + return Err(EINVAL); + } + for &k in &f.pass[..f.pass_count as usize] { + if k as usize >= sizes::RENDER_SLOTS || !p.publish(k as usize) { + return Err(EBUSY); + } + } + } else { + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + if !p.publish(k) { + return Err(EBUSY); + } } } - self.compute_lifetime = c; - self.pass_lifetime = p; + self.compute.lifetime = c; + self.render.lifetime = p; + f.scrub_gen = self.scrub_gen; Ok(()) } /// Full wire retirement is a precondition; completion fences alone are insufficient. pub(crate) fn retire(&mut self, f: &mut Claims) -> Result { - let mut c = self.compute_lifetime.clone(); - let mut p = self.pass_lifetime.clone(); + let mut c = self.compute.lifetime.clone(); + let mut p = self.render.lifetime.clone(); for &k in &f.slot[..f.slot_count as usize] { if !c.retire(k as usize) { return Err(EINVAL); } } - for k in 0..2 { - if f.pass_mask & (1 << k) != 0 && !p.retire(k) { + if f.pass_count != 0 { + if f.pass_count as usize > f.pass.len() { return Err(EINVAL); } + // Retire in submission order so displacement retains the newest hardware pass slot. + for &k in &f.pass[..f.pass_count as usize] { + if k as usize >= sizes::RENDER_SLOTS || !p.retire(k as usize) { + return Err(EINVAL); + } + } + } else { + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + if !p.retire(k) { + return Err(EINVAL); + } + } } - self.compute_lifetime = c; - self.pass_lifetime = p; + self.compute.lifetime = c; + self.render.lifetime = p; + let clean_scrub = f.scrub_gen == self.scrub_gen; for &k in &f.slot[..f.slot_count as usize] { - self.compute_owner[k as usize] = self.pending_compute_owner[k as usize].take(); + self.compute.owner[k as usize] = self.compute.pending_owner[k as usize].take(); + self.compute.arena[k as usize] = self.compute.pending_arena[k as usize].take(); + if let Some(lease) = self.compute.pending_uma[k as usize].take() { + self.compute.retained_uma[k as usize] = Some(lease); + } + if clean_scrub { + self.compute.scrub_full[k as usize] = false; + } } - for k in 0..2 { - if f.pass_mask & (1 << k) != 0 { - self.pass_owner[k] = self.pending_pass_owner[k].take(); + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + self.render.owner[k] = self.render.pending_owner[k].take(); + self.render.arena[k] = self.render.pending_arena[k].take(); + if clean_scrub { + self.render.scrub_full[k] = false; } } self.pass_busy &= !f.pass_mask; f.slot_count = 0; + f.compute_pipe = 0; + f.pass_count = 0; f.pass_mask = 0; f.ct_count = 0; Ok(()) } pub(crate) fn quarantine(&mut self, f: &mut Claims) { for &k in &f.slot[..f.slot_count as usize] { - self.compute_lifetime.quarantine(k as usize); - self.pending_compute_retarget[k as usize] = None; + self.compute.lifetime.quarantine(k as usize); + self.compute.pending_retarget[k as usize] = None; + self.compute.scrub_full[k as usize] = true; } - for k in 0..2 { - if f.pass_mask & (1 << k) != 0 { - self.pass_lifetime.quarantine(k); - self.pending_pass_retarget[k] = None; - } + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + self.render.lifetime.quarantine(k); + self.render.pending_retarget[k] = None; + self.render.scrub_full[k] = true; + self.scrub.clear_clean(k); } self.pass_busy &= !f.pass_mask; f.slot_count = 0; + f.compute_pipe = 0; + f.pass_count = 0; f.pass_mask = 0; f.ct_count = 0; } /// Cancels preparation only. Published units require retire() or quarantine(). pub(crate) fn release(&mut self, f: &mut Claims) { for &k in &f.slot[..f.slot_count as usize] { - self.compute_lifetime.cancel(k as usize); - self.pending_compute_retarget[k as usize] = None; - self.pending_compute_owner[k as usize] = None; + self.compute.lifetime.cancel(k as usize); + self.compute.pending_retarget[k as usize] = None; + self.compute.pending_owner[k as usize] = None; + self.compute.pending_arena[k as usize] = None; + self.compute.pending_uma[k as usize] = None; + self.compute.scrub_full[k as usize] = true; } - for k in 0..2 { - if f.pass_mask & (1 << k) != 0 { - self.pass_lifetime.cancel(k); - self.pending_pass_retarget[k] = None; - self.pending_pass_owner[k] = None; - } + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + self.render.lifetime.cancel(k); + self.render.pending_retarget[k] = None; + self.render.pending_owner[k] = None; + self.render.pending_arena[k] = None; + self.render.scrub_full[k] = true; + self.scrub.clear_clean(k); } self.pass_busy &= !f.pass_mask; f.slot_count = 0; + f.compute_pipe = 0; + f.pass_count = 0; f.pass_mask = 0; f.ct_count = 0; } diff --git a/drivers/gpu/drm/asahi/g16/uat.rs b/drivers/gpu/drm/asahi/g16/uat.rs index 72ca9cb94b8467..e43e453819281d 100644 --- a/drivers/gpu/drm/asahi/g16/uat.rs +++ b/drivers/gpu/drm/asahi/g16/uat.rs @@ -16,7 +16,13 @@ use core::ops::Range; use core::sync::atomic::Ordering; -use kernel::{device, io::Io, prelude::*, sync::Arc}; +use kernel::{ + device, + io::Io, + prelude::*, + sync::Arc, + time::{delay::fsleep, Delta, Instant, Monotonic}, +}; use super::hw; use super::regs::{mb, Mapping}; @@ -175,8 +181,14 @@ pub(crate) struct Window { /// Observed firmware-owned root words; only the exact qualified forward transition is /// accepted after RUN, never a rollback or an unrelated physical table. firmware_root: [u64; 2], + abi: hw::FwAbi, text_pa: u64, data_pa: u64, + /// The leaves the boot loader builds in this firmware's page tables (none for a firmware + /// that builds its own tree at start). + leaves: &'static [hw::Leaves], + /// The PPL handoff magic words of this firmware's layout. + ppl: hw::PplMagic, } impl Window { @@ -191,8 +203,12 @@ impl Window { snapshot: KVec::from_elem(0u64, ENTRIES, GFP_KERNEL)?, published: false, firmware_root: [0; 2], + abi: adt.layout.abi, text_pa: adt.text.start, data_pa: adt.data.start, + // Admission refuses a layout with either unknown; never guess them here. + leaves: adt.layout.leaves.ok_or(ENOTSUPP)?, + ppl: adt.layout.ppl_magic.ok_or(ENOTSUPP)?, }; window.admit_cold()?; Ok(window) @@ -220,9 +236,9 @@ impl Window { return Err(EBUSY); } let h = self.handoff.io(); - for offset in [0, 8] { + for (offset, expected) in [(0, self.ppl.ap), (8, self.ppl.firmware)] { let magic = h.try_read64(offset)?; - if magic != 0 && magic != hw::PPL_MAGIC { + if magic != 0 && magic != expected { return Err(EBUSY); } } @@ -293,24 +309,23 @@ impl Window { } else { let address = va | ((index as u64) << shift); let off = address.checked_sub(hw::UPPER).ok_or(EINVAL)?; - let expected = if off < 0x60000 { - (self.text_pa + off) - | if (0x50000..0x58000).contains(&off) { - 0x483 - } else { - 0x4c3 - } - } else if off < 0x19c000 { - let data_offset = off - 0x60000; - (self.data_pa + data_offset) - | if data_offset < 0xc000 { - 0x00200000000004c3 - } else { - 0x0460000000000443 - } - } else { - return Err(EINVAL); - }; + let leaf = self + .leaves + .iter() + .find(|leaf| leaf.range.contains(&off)) + .ok_or(EINVAL)?; + // TEXT starts at UPPER; every later segment is in DATA, contiguously. + let text_end = self + .leaves + .iter() + .filter(|l| l.segment == hw::Segment::Text) + .map(|l| l.range.end) + .max() + .ok_or(EINVAL)?; + let expected = match leaf.segment { + hw::Segment::Text => self.text_pa + off, + hw::Segment::Data => self.data_pa + (off - text_end), + } | leaf.attrs; if pte != expected { return Err(EINVAL); } @@ -327,6 +342,38 @@ impl Window { Ok(()) } + /// After RUN, waits up to 1 s for a firmware that answers at start ([`hw::PplMagic::answers`]) + /// to store its magic at +8, as GPU firmware 27.2 does on G14 (linux#2544). [`Self::bootstrap`] + /// clears +8 before RUN so a stale value can never satisfy the wait; a missing answer fails + /// with `ETIMEDOUT`. + pub(crate) fn await_firmware_magic(&self, dev: &device::Device) -> Result { + if !self.ppl.answers { + return Ok(()); + } + let start = Instant::::now(); + loop { + let magic = self.handoff.io().try_read64(8)?; + if magic == self.ppl.firmware { + dev_info!( + dev, + "G16: firmware PPL magic {:#x} after {} us\n", + magic, + start.elapsed().as_micros_ceil() + ); + return Ok(()); + } + if start.elapsed() >= Delta::from_millis(1000) { + dev_err!( + dev, + "G16: no firmware PPL magic within 1 s (+8 = {:#x})\n", + magic + ); + return Err(ETIMEDOUT); + } + fsleep(Delta::from_millis(1)); + } + } + /// Cold-start check: all 128 TTBAT words are zero. pub(crate) fn ttbat_is_clear(&self) -> Result { let t = self.ttbs.io(); @@ -353,12 +400,19 @@ impl Window { let lower = uat.kernel_lower_root(); let shadow_l2 = Self::shadow_l2(uat)?; let handoff = uat.lock_m4_handoff()?; - let fw_magic = self.handoff.io().try_read64(8)?; - self.handoff.io().try_write64(hw::PPL_MAGIC, 0)?; + let fw_magic = if self.ppl.answers { + // Clear any leftover firmware magic before RUN so await_firmware_magic() only + // accepts a fresh answer written by this boot's firmware. + self.handoff.io().try_write64(0, 8)?; + 0 + } else { + self.handoff.io().try_read64(8)? + }; + self.handoff.io().try_write64(self.ppl.ap, 0)?; // Cold admission proved both interests clear. The common guard now owns AP // interest; never reset either participant's lock words behind that guard. self.handoff.io().try_write32(0xffff, 0x18)?; - if fw_magic != hw::PPL_MAGIC { + if fw_magic != self.ppl.firmware { self.handoff.io().try_write8(1, 0x638)?; } for index in 0..65 * 3 { @@ -401,6 +455,7 @@ impl Window { /// Confirms the shared root still names the driver's reserved L2 and only recognizes /// the qualified firmware-owned forward transitions in root[0..1]. fn verify_root(&mut self) -> Result { + let (table_offset, attributes) = self.abi.live_root_table(); for index in 0..2 { let observed = self.root.io().try_read64(index * 8)?; if observed == self.firmware_root[index] { @@ -409,7 +464,7 @@ impl Window { let expected = if index == 0 { (self.root.phys() + hw::PAGE) | 0x403 } else { - (self.root.phys() + 0x10000) | 0x00200000000004cb + (self.root.phys() + table_offset) | attributes }; if self.firmware_root[index] != 0 || observed != expected { return Err(EIO); @@ -417,7 +472,7 @@ impl Window { self.firmware_root[index] = observed; } let root = self.root.io().try_read64(WINDOW_INDEX * 8)?; - if root != self.shared_l2.phys() | 3 && root != self.shared_l2.phys() | 0x00200000000004cb { + if root != self.shared_l2.phys() | 3 && root != self.shared_l2.phys() | attributes { return Err(EIO); } Ok(()) diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 5bb4f434454ccc..b7a76ee776ec4e 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -28,7 +28,7 @@ //! alike. use core::ops::Range; -use core::sync::atomic::{AtomicU32, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use kernel::{ drm::gem::BaseObject, new_mutex, @@ -134,10 +134,33 @@ pub(crate) struct VmStateInner { /// Private mappings are kept outside generic close's user GPUVA teardown. context_mappings: KVec, pub(crate) resources: Option>, + /// Set once a multisampled render pass of this VM becomes visible ([`Self::renders_msaa`]). + renders_msaa: AtomicBool, #[allow(dead_code)] pub(crate) live: Arc, } +impl VmStateInner { + /// Whether renders this VM's SUBMITs accepted are not yet published. + pub(crate) fn renders_unpublished(&self) -> bool { + self.resources + .as_ref() + .is_some_and(|cache| cache.renders_unpublished()) + } + + /// Whether this VM has published a multisampled render pass. Its later passes can still + /// read multisampled images (an attachmentless pass reading them as input attachments is + /// single-sampled), so the property is the VM's from then on. + pub(crate) fn renders_msaa(&self) -> bool { + self.renders_msaa.load(Ordering::Relaxed) + } + + /// Records that a multisampled render pass of this VM became visible to the firmware. + pub(crate) fn note_msaa_render(&self) { + self.renders_msaa.store(true, Ordering::Relaxed); + } +} + impl Drop for VmStateInner { fn drop(&mut self) { mod_pr_debug!("G16: VM {} releases context {}\n", self.id, self.slot); @@ -254,6 +277,11 @@ impl Registry { let index = vms.iter().position(|state| state.id == id); index.and_then(|index| vms.remove(index).ok()) }; + // Arenas still reachable by firmware stay with the slot leases and jobs that hold + // them; the rest (and the spare epochs, which hold the VM) go now. + if let Some(cache) = state.as_ref().and_then(|state| state.resources.as_ref()) { + cache.close(); + } drop(state); } @@ -268,8 +296,12 @@ impl Registry { let Some(closed) = closed else { break; }; - // No allocation while holding the registry lock, which fail_all() also needs. - // Final VM destruction is deferred independently of this caller's locks. + // Break the spare-epoch cycle before releasing the registry reference, matching + // close(). No allocation while holding the registry lock, which fail_all() also + // needs. Final VM destruction is deferred independently of this caller's locks. + if let Some(cache) = closed.resources.as_ref() { + cache.close(); + } drop(closed); } } @@ -332,6 +364,15 @@ impl Registry { .ok_or(ENOENT) } + /// The VM id of a live VM currently bound to TTBAT `slot`, if any. + pub(crate) fn find_by_slot(&self, slot: u32) -> Option { + self.vms + .lock() + .iter() + .find(|state| state.slot == slot) + .map(|state| state.id) + } + /// Latches `error` on every VM whose client handle is open. The fail-stop path calls it under /// the device lock. pub(crate) fn fail_all(&self, error: Error) { @@ -397,6 +438,7 @@ pub(crate) fn new_vm(gpu: &Gpu, kernel_range: Range, file_id: u64) -> Resul factory, live.bind.as_ref().ok_or(EIO)?.clone(), live.clone(), + gpu.shared.clone(), )?; let inner = VmStateInner { id, @@ -406,6 +448,7 @@ pub(crate) fn new_vm(gpu: &Gpu, kernel_range: Range, file_id: u64) -> Resul vm: vm.clone(), context_mappings: mappings, resources: Some(resources), + renders_msaa: AtomicBool::new(false), live, }; let state = Arc::new(VmState(crate::cleanup::Deferred::new(inner)?), GFP_KERNEL)?; diff --git a/drivers/gpu/drm/asahi/g17/availability.rs b/drivers/gpu/drm/asahi/g17/availability.rs index 9deaac406a5a2f..8d5a213bb4b2ea 100644 --- a/drivers/gpu/drm/asahi/g17/availability.rs +++ b/drivers/gpu/drm/asahi/g17/availability.rs @@ -7,6 +7,7 @@ //! lock round trip. use super::fence::{self, CompletionFence}; +use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{ c_str, dma_fence::{Fence, FenceContexts, RawDmaFence, UserFence}, @@ -21,12 +22,13 @@ struct Entry { } struct State { - generation: u64, waiters: Option>, } #[pin_data] pub(crate) struct Availability { + generation: AtomicU64, + has_waiters: AtomicBool, #[pin] state: Mutex, fences: FenceContexts, @@ -36,8 +38,10 @@ impl Availability { pub(crate) fn new() -> Result> { Arc::pin_init( try_pin_init!(Self { + generation: AtomicU64::new(0), + has_waiters: AtomicBool::new(false), state <- new_mutex!( - State { generation: 0, waiters: None }, + State { waiters: None }, "g17::Availability" ), fences: FenceContexts::new(1, c_str!("aurora_resource"), kernel::static_lock_class!())?, @@ -48,11 +52,11 @@ impl Availability { /// Sample before checking capacity under the resource's own synchronization. pub(crate) fn observe(&self) -> u64 { - self.state.lock().generation + self.generation.load(Ordering::Acquire) } pub(crate) fn has_waiters(&self) -> bool { - self.state.lock().waiters.is_some() + self.has_waiters.load(Ordering::Acquire) } /// A fence the next notification signals. None means capacity changed after the sample: @@ -69,7 +73,14 @@ impl Availability { GFP_KERNEL, )?; let mut state = self.state.lock(); - if state.generation != observed { + // Publish `has_waiters` with SeqCst before re-checking `generation` (SeqCst), + // pairing with `advance()`'s SeqCst fetch_add on `generation` followed by SeqCst + // load of `has_waiters` so no waiter can be lost on the lock-free fast path. + self.has_waiters.store(true, Ordering::SeqCst); + if self.generation.load(Ordering::SeqCst) != observed { + if state.waiters.is_none() { + self.has_waiters.store(false, Ordering::Release); + } return Ok(None); } entry.next = state.waiters.take(); @@ -115,11 +126,14 @@ impl Availability { /// Notifies, returning the generation before this notification. fn advance(&self) -> u64 { - let (previous, mut waiters) = { + let previous = self.generation.fetch_add(1, Ordering::SeqCst); + if !self.has_waiters.load(Ordering::SeqCst) { + return previous; + } + let mut waiters = { let mut state = self.state.lock(); - let previous = state.generation; - state.generation = previous.wrapping_add(1); - (previous, state.waiters.take()) + self.has_waiters.store(false, Ordering::Release); + state.waiters.take() }; while let Some(mut entry) = waiters { waiters = entry.next.take(); diff --git a/drivers/gpu/drm/asahi/g17/buffer.rs b/drivers/gpu/drm/asahi/g17/buffer.rs index 2e2c79ae15123f..0d9bdd33ba1ed7 100644 --- a/drivers/gpu/drm/asahi/g17/buffer.rs +++ b/drivers/gpu/drm/asahi/g17/buffer.rs @@ -9,6 +9,7 @@ use super::fw::buffer as fw; use crate::hw::t8140::resources as cfg; pub(crate) mod target; +pub(crate) mod compact; mod geometry; pub(crate) use geometry::BlockGeometry; mod layout; @@ -414,6 +415,18 @@ impl Tvb { } geometry.backing_bytes(blocks) } + /// Backing for `blocks` blocks to be mapped into `vm`. M5 blocks are mapped one by one in + /// the compact window, which is checked for room for all of them first, and the client's + /// passes and geometry size them, so they are charged to the client. + fn allocate(dev: &AsahiDrmDevice, vm: &mmu::Vm, geometry: BlockGeometry, blocks: usize) + -> Result { + let bytes = Self::backing_bytes(geometry, blocks)?; + if geometry == BlockGeometry::NEO { + return KernelObject::backing(dev, bytes, CpuMap::WriteCombined); + } + compact::PairObject::ParameterBlock.check_room(vm, geometry.block_bytes, blocks)?; + KernelObject::client_backing(dev, bytes, vm.memory_client()) + } fn map_block( object: &KernelObject, vm: &mmu::Vm, @@ -423,9 +436,8 @@ impl Tvb { if geometry != BlockGeometry::NEO { let start = relative.checked_mul(geometry.backing_stride).ok_or(EOVERFLOW)?; let source = start..start.checked_add(geometry.block_bytes).ok_or(EOVERFLOW)?; - let guard = geometry.stride - geometry.block_bytes; - let mapping = object.map_range(vm, source, geometry.base..geometry.end, - BlockGeometry::PAGE as u64, mmu::PROT_GPU_SHARED_RW, guard)?; + let mapping = compact::PairObject::ParameterBlock.map(object, vm, source, + mmu::PROT_GPU_SHARED_RW)?; geometry.compact_page(mapping.iova())?; return Ok(mapping); } @@ -458,8 +470,7 @@ impl Tvb { if blocks == 0 || blocks > geometry.max_blocks() { return Err(ERANGE); } - let backing = KernelObject::backing(dev, Self::backing_bytes(geometry, blocks)?, - CpuMap::WriteCombined)?; + let backing = Self::allocate(dev, vm, geometry, blocks)?; let mut mappings = KVec::with_capacity(blocks, GFP_KERNEL)?; let mut addresses = KVec::with_capacity(blocks, GFP_KERNEL)?; for index in 0..blocks { @@ -511,8 +522,7 @@ impl Tvb { let added = target - self.blocks(); self.extensions.reserve(1, GFP_KERNEL)?; self.addresses.reserve(added, GFP_KERNEL)?; - let backing = KernelObject::backing(dev, Self::backing_bytes(self.geometry, added)?, - CpuMap::WriteCombined)?; + let backing = Self::allocate(dev, vm, self.geometry, added)?; let mut mappings = KVec::with_capacity(added, GFP_KERNEL)?; let mut addresses = KVec::with_capacity(added, GFP_KERNEL)?; for relative in 0..added { @@ -568,15 +578,18 @@ impl MetricsIds { /// backing each lease is taken from. pub(crate) fn with_stride(scene_stride: usize) -> Result { if scene_stride < 4 || scene_stride % 4 != 0 { return Err(EINVAL); } - let entry_pitch = scene_stride.checked_mul(fw::SCENES) - .and_then(|bytes| bytes.checked_next_multiple_of(mmu::UAT_PGSZ)) - .ok_or(EOVERFLOW)?; Ok(Self { used: [AtomicU64::new(0), AtomicU64::new(0)], scene_stride, - entry_pitch, + entry_pitch: Self::entry_pitch(scene_stride)?, }) } + /// The pitch of entries of `scene_stride`-byte scenes: each starts its own pages. + pub(crate) fn entry_pitch(scene_stride: usize) -> Result { + scene_stride.checked_mul(fw::SCENES) + .and_then(|bytes| bytes.checked_next_multiple_of(mmu::UAT_PGSZ)) + .ok_or(EOVERFLOW) + } /// Backing required for every entry owned by this allocator. pub(crate) fn storage_bytes(&self) -> Result { self.entry_pitch.checked_mul(self.used.len() * u64::BITS as usize) @@ -607,14 +620,14 @@ impl MetricsLease { // window's start (InitData::bind_m5_metrics), so place the entry where its offset puts // it there. let fixed = super::J813_FORMS.load(Ordering::Relaxed).then(|| { - let at = BlockGeometry::M5_COMPACT.start + offset as u64; - self.backing.map_range(vm, offset..offset + pitch, at..at + pitch as u64, - mmu::UAT_PGSZ as u64, mmu::PROT_GPU_SHARED_RW, 0).ok() + let at = compact::WINDOW.start + offset as u64; + compact::PairObject::Metrics.map_at(&self.backing, vm, offset..offset + pitch, at, + mmu::PROT_GPU_SHARED_RW).ok() }).flatten(); let client = match fixed { Some(client) => client, - None => self.backing.map_range(vm, offset..offset + pitch, BlockGeometry::M5_COMPACT, - mmu::UAT_PGSZ as u64, mmu::PROT_GPU_SHARED_RW, 0)?, + None => compact::PairObject::Metrics.map(&self.backing, vm, offset..offset + pitch, + mmu::PROT_GPU_SHARED_RW)?, }; self.addresses.client = client.iova(); self.client = Some(client); @@ -704,6 +717,8 @@ pub(crate) struct ManagerArgs { pub(crate) buffer_id: u8, pub(crate) generation: u64, pub(crate) first_ordinal: u64, + /// The heap's normal maximum in blocks (`Variant::tvb_normal_blocks`); NEO heaps only. + pub(crate) normal_blocks: usize, } /// A retained parameter-buffer graph and all of its sparse backing. Client @@ -793,7 +808,13 @@ impl Manager { ) -> Result { let geometry = tvb.geometry; let neo = geometry == BlockGeometry::NEO; - let layout = if neo { layout::Layout::NEO } else { layout::Layout::m5(geometry)? }; + let mut layout = if neo { layout::Layout::NEO } else { layout::Layout::m5(geometry)? }; + if neo { + if args.normal_blocks == 0 || args.normal_blocks > geometry.max_blocks() { + return Err(EINVAL); + } + layout.normal_blocks = args.normal_blocks; + } if metrics.scene_stride != layout.metric_stride { return Err(EINVAL); } @@ -814,8 +835,7 @@ impl Manager { mmu::UAT_PGSZ, )? } else { - graph.map_range(vm, source, geometry.base..geometry.end, - cfg::TVB_PAGE, mmu::PROT_GPU_FW_SHARED_RW, mmu::UAT_PGSZ)? + compact::PairObject::PageList.map(&graph, vm, source, mmu::PROT_GPU_FW_SHARED_RW)? }; let address = graph.gpu_va(); let graph_args = fw::GraphArgs { @@ -827,6 +847,7 @@ impl Manager { discard: args.discard, buffer_id: args.buffer_id.into(), generation: args.generation, + normal_blocks: layout.normal_blocks, }; if neo { graph.initialize::(0, |view| view.init(&graph_args))?; diff --git a/drivers/gpu/drm/asahi/g17/buffer/compact.rs b/drivers/gpu/drm/asahi/g17/buffer/compact.rs new file mode 100644 index 00000000000000..af491dc8c7167e --- /dev/null +++ b/drivers/gpu/drm/asahi/g17/buffer/compact.rs @@ -0,0 +1,266 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The objects a render pair maps in its client's M5 compact window. +//! +//! The firmware addresses the window with 32-bit offsets, so it is 4 GiB, and every render pair +//! of the client maps its objects there. [`PairObject`] names each such object and fixes how it +//! is placed: every mapping of one goes through [`PairObject::map`] (or +//! [`PairObject::placement`]), and every room check before allocating one through +//! [`PairObject::check_room`]. SUBMIT's bound ([`PairSizes::window_bytes`]) counts the same +//! objects with the same placement, so an object cannot be mapped there without a size in the +//! bound, and the bound cannot disagree with a mapping on its alignment or guard. + +use super::BlockGeometry; +use crate::g17::object::{KernelObject, Placement}; +use crate::{ + hw::t8140::{queues, resources as cfg}, + mmu, +}; +use core::ops::Range; +use kernel::prelude::*; + +/// The client's M5 compact window. +pub(crate) const WINDOW: Range = BlockGeometry::M5_COMPACT; +/// Its size: 4 GiB. +pub(crate) const WINDOW_BYTES: u64 = WINDOW.end - WINDOW.start; + +const DEPTH: usize = queues::RENDER_DEPTH as usize; + +/// The task-stage mesh storage chunk: chunk bases are 64 KiB aligned, and the storage register +/// counts 64 KiB chunks. +pub(crate) const MESH_STORAGE_CHUNK: usize = 0x10000; + +/// The task-stage mesh storage a render pair maps on its first task-stage kick and keeps, as +/// (chunks, bytes); `None` when the module parameter disables the binding. +pub(crate) fn mesh_storage() -> Result> { + let chunks = crate::module_parameters::m5_mesh_storage_chunks.value(); + if chunks == 0 { + return Ok(None); + } + if chunks > 0xffff { + return Err(EINVAL); + } + let bytes = (chunks as usize).checked_mul(MESH_STORAGE_CHUNK).ok_or(EOVERFLOW)?; + Ok(Some((chunks, bytes))) +} + +/// Bytes of a pair's parameter-buffer scene scratch for `geometry`. +pub(crate) fn scratch_bytes(geometry: BlockGeometry) -> Result { + use crate::g17::fw::m5::pool; + pool::parameter_scratch_stride(geometry.capacity, 0) + .map_err(|_| EINVAL)? + .checked_mul(pool::SCENE_TABLE_ENTRIES) + .ok_or(EOVERFLOW) +} + +/// Bytes of the page list of a pair's block manager for `geometry`. +pub(crate) fn page_list_bytes(geometry: BlockGeometry) -> Result { + Ok(super::layout::Layout::m5(geometry)?.page_bytes) +} + +/// Bytes of a pair's metrics entry for `geometry`. +fn metrics_bytes(geometry: BlockGeometry) -> Result { + super::MetricsIds::entry_pitch(super::layout::Layout::m5(geometry)?.metric_stride) +} + +/// An object a render pair maps in its client's M5 compact window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PairObject { + /// The target records: one record stride for each command slot. + Records = 0, + /// The TPC object. + Tpc, + /// One parameter block, initial or grown, mapped at the M5 block stride. + ParameterBlock, + /// The context state of one command slot. + SlotState, + /// The parameter buffer's scene scratch. + Scratch, + /// The parameter buffer's discard. + Discard, + /// The block manager's page list. + PageList, + /// The pair's metrics entry. + Metrics, + /// The task-stage mesh storage, mapped on the pair's first task-stage kick and kept for the + /// pair's lifetime. + MeshStorage, +} + +impl PairObject { + /// Every object, in declaration order. + pub(crate) const ALL: [Self; 9] = [ + Self::Records, + Self::Tpc, + Self::ParameterBlock, + Self::SlotState, + Self::Scratch, + Self::Discard, + Self::PageList, + Self::Metrics, + Self::MeshStorage, + ]; + + /// The alignment it is placed at. + pub(crate) const fn align(self) -> u64 { + match self { + Self::MeshStorage => MESH_STORAGE_CHUNK as u64, + Self::Metrics => mmu::UAT_PGSZ as u64, + Self::ParameterBlock => BlockGeometry::PAGE as u64, + Self::Records + | Self::Tpc + | Self::SlotState + | Self::Scratch + | Self::Discard + | Self::PageList => cfg::TVB_PAGE, + } + } + + /// The unmapped guard that follows it. + pub(crate) const fn guard(self) -> usize { + match self { + Self::Metrics => 0, + Self::ParameterBlock => BlockGeometry::M5_BLOCK_STRIDE - BlockGeometry::M5_BLOCK_BYTES, + Self::Records + | Self::Tpc + | Self::SlotState + | Self::Scratch + | Self::Discard + | Self::PageList + | Self::MeshStorage => mmu::UAT_PGSZ, + } + } + + /// The bytes one mapping of an object of `bytes` takes in one hole: its pages and its guard. + fn mapped_bytes(self, bytes: usize) -> Result { + bytes + .checked_next_multiple_of(mmu::UAT_PGSZ) + .and_then(|n| n.checked_add(self.guard())) + .ok_or(EOVERFLOW) + } + + /// The window bytes an object of `bytes` can take: its pages and its guard, rounded up to + /// its alignment and at least to the 32 KiB most of these objects are placed at, plus, for + /// an object aligned beyond 32 KiB, the hole that alignment can leave before it. + pub(crate) fn window_bytes(self, bytes: usize) -> Result { + let base = cfg::TVB_PAGE as usize; + let align = (self.align() as usize).max(base); + self.mapped_bytes(bytes)? + .checked_next_multiple_of(align) + .and_then(|n| n.checked_add(align - base)) + .ok_or(EOVERFLOW) + } + + /// Maps `source` of `object` into `vm`'s window as this object. + pub(crate) fn map( + self, + object: &KernelObject, + vm: &mmu::Vm, + source: Range, + prot: mmu::Prot, + ) -> Result { + let mapping = object.map_range(vm, source, WINDOW, self.align(), prot, self.guard())?; + if mapping.iova() % self.align() != 0 { + return Err(EINVAL); + } + Ok(mapping) + } + + /// [`Self::map`] at `at`, where the firmware expects this object. + pub(crate) fn map_at( + self, + object: &KernelObject, + vm: &mmu::Vm, + source: Range, + at: u64, + prot: mmu::Prot, + ) -> Result { + let end = at.checked_add(self.mapped_bytes(source.len())? as u64).ok_or(EOVERFLOW)?; + if at < WINDOW.start || end > WINDOW.end { + return Err(EINVAL); + } + object.map_range(vm, source, at..end, self.align(), prot, self.guard()) + } + + /// The [`Placement`] of a [`KernelObject::new`] of this object in the window, whose guard is + /// one page. + pub(crate) fn placement(self) -> Result { + if self.guard() != mmu::UAT_PGSZ { + return Err(EINVAL); + } + Ok(Placement::In(WINDOW, self.align())) + } + + /// Refuses with ENOSPC, as the mapping would and before any backing is allocated, `count` + /// of this object of `bytes` each that `vm`'s window has no room for: a hole for one, and + /// room for all of them. The window is shared, so room seen here is no placement promise: + /// the mapping can still fail, but only after allocating backing that could fit. + pub(crate) fn check_room(self, vm: &mmu::Vm, bytes: usize, count: usize) -> Result { + let (used, largest) = vm.capacity(WINDOW)?; + let one = self.mapped_bytes(bytes)?; + let all = one.checked_mul(count).ok_or(EOVERFLOW)?; + if one as u64 > largest || all as u64 > WINDOW_BYTES.saturating_sub(used) { + return Err(ENOSPC); + } + Ok(()) + } +} + +// `PairObject::ALL` holds every object once, in order. +const _: () = { + let mut index = 0; + while index < PairObject::ALL.len() { + assert!(PairObject::ALL[index] as usize == index); + index += 1; + } + assert!(PairObject::ALL.len() == PairObject::MeshStorage as usize + 1); +}; + +/// The sizes of the objects a render pair built for one layout maps in the window. +pub(crate) struct PairSizes { + /// The target records object: one record stride for each command slot. + pub(crate) records: usize, + /// The TPC object. + pub(crate) tpc: usize, + /// The initial parameter blocks, of `geometry`'s block size. + pub(crate) blocks: usize, + /// The parameter-buffer geometry, which sizes the blocks, scratch, page list and metrics. + pub(crate) geometry: BlockGeometry, + /// One command slot's context state. + pub(crate) state: usize, + /// The task-stage mesh storage the pair may map ([`mesh_storage`]). + pub(crate) mesh_storage: Option, +} + +impl PairSizes { + /// How many of `object` the pair maps, and the bytes of each. + fn of(&self, object: PairObject) -> Result<(usize, usize)> { + Ok(match object { + PairObject::Records => (1, self.records), + PairObject::Tpc => (1, self.tpc), + PairObject::ParameterBlock => (self.blocks, self.geometry.block_bytes), + PairObject::SlotState => (DEPTH, self.state), + PairObject::Scratch => (1, scratch_bytes(self.geometry)?), + PairObject::Discard => (1, crate::g17::fw::m5::pool::DISCARD_BYTES), + PairObject::PageList => (1, page_list_bytes(self.geometry)?), + PairObject::Metrics => (1, metrics_bytes(self.geometry)?), + PairObject::MeshStorage => match self.mesh_storage { + Some(bytes) => (1, bytes), + None => (0, 0), + }, + }) + } + + /// The window bytes of `object` in the pair. + pub(crate) fn object_bytes(&self, object: PairObject) -> Result { + let (count, bytes) = self.of(object)?; + object.window_bytes(bytes)?.checked_mul(count).ok_or(EOVERFLOW) + } + + /// The window bytes of every object of the pair. + pub(crate) fn window_bytes(&self) -> Result { + PairObject::ALL.into_iter().try_fold(0usize, |sum, object| { + sum.checked_add(self.object_bytes(object)?).ok_or(EOVERFLOW) + }) + } +} diff --git a/drivers/gpu/drm/asahi/g17/buffer/geometry.rs b/drivers/gpu/drm/asahi/g17/buffer/geometry.rs index c871f470c1a153..71c5e18dc48f17 100644 --- a/drivers/gpu/drm/asahi/g17/buffer/geometry.rs +++ b/drivers/gpu/drm/asahi/g17/buffer/geometry.rs @@ -20,6 +20,9 @@ impl BlockGeometry { pub(crate) const PAGE: usize = 0x8000; /// M5 parameter resources use 32-bit offsets from this compact base. pub(crate) const M5_COMPACT: core::ops::Range = 0x10_0000_0000..0x11_0000_0000; + /// An M5 parameter block, and the stride it is mapped at, its guard included. + pub(crate) const M5_BLOCK_BYTES: usize = 0x80000; + pub(crate) const M5_BLOCK_STRIDE: usize = 0x88000; pub(crate) const NEO: Self = Self { base: cfg::USER_BASE, end: cfg::USER_END, @@ -40,9 +43,9 @@ impl BlockGeometry { Ok(Self { base: Self::M5_COMPACT.start, end: Self::M5_COMPACT.end, - block_bytes: 0x80000, - backing_stride: 0x80000, - stride: 0x88000, + block_bytes: Self::M5_BLOCK_BYTES, + backing_stride: Self::M5_BLOCK_BYTES, + stride: Self::M5_BLOCK_STRIDE, capacity, }) } diff --git a/drivers/gpu/drm/asahi/g17/buffer/target.rs b/drivers/gpu/drm/asahi/g17/buffer/target.rs index 8b87ccde7d9857..c037c9f7914d76 100644 --- a/drivers/gpu/drm/asahi/g17/buffer/target.rs +++ b/drivers/gpu/drm/asahi/g17/buffer/target.rs @@ -4,6 +4,7 @@ //! Larger targets replace only the objects that need more capacity. Every old //! backing keeps the exact commands that still reference it until retirement. +use super::compact::PairObject; use super::compact_alias; use crate::g17::{ fw::render::{RegisterPrograms, RenderPass}, @@ -35,6 +36,23 @@ const GTP_FIXED_SIZES: [usize; 4] = [0xc00, 0xa00, GTP6_SIZE, 0x80]; const GTP_SLOTS: usize = 64; const GTP6_SIZE: usize = GTP_SLOTS * (((cfg::TVB_MAX_BLOCKS * cfg::TVB_BLOCK_SIZE).div_ceil(0x8000) + 0x17ff) / 24 * 8 + 8); +/// Clustering metadata 2-4 (0x1c948, 0x1c888, 0x16c41/0x1ca40) on GPUs with more than two +/// clusters, at the sizes the M2 Pro/Max path gives them (`hw/t602x.rs` clustering config). +/// Metadata 1 (0x1c920) is sized per target there: [`META1_BLOCK_SIZE`] per block of tiles. +/// +/// macOS 26.6.2 on the J616C spaces a clustered pass's metadata 2, 3 and 4 0x1180, 0x1400 +/// and 0x1600 apart: metadata 2 needs 0x1180, more than the M2 Pro/Max 0xc00. +const GTP_MULTI_CLUSTER_SIZES: [usize; 3] = [0x1180, 0x280 * 16, 0x10 * 128]; +/// Floor for four-cluster metadata 1 (`0x1c920`, `gtp[7]`). +/// +/// The M2 Pro/Max per-block formula yields 0x100 (32x32 utiles) or 0x180 (16x16) on a +/// 3456x2234 Retina frame (Minecraft RD32) and 0x1100 on 10240x10240 (`point_size_10000`, +/// 16x16 utiles). Because metadata 1 is the last sub-buffer in the TPC object, neither +/// macOS's allocation size nor the hardware's written high-water mark was visible in the +/// J616C 26.6.2 capture; keep a conservative 16 KiB floor until a capture or hardware +/// high-water measurement shows the true upper bound. +const META1_MIN_SIZE: usize = 0x4000; +const META1_BLOCK_SIZE: usize = 0x44; /// Per-command geometry, independent of the capacity already allocated. #[derive(Copy, Clone, Debug)] @@ -116,15 +134,38 @@ impl Layout { let mut gtp = [None; 8]; let mut tpc_end = tpc_size; if programs == RegisterPrograms::V25G83 { + // The fixed sizes are the two-cluster M4 Pro's. With four clusters (M4 Max) clustered + // tiling outgrows them: the firmware then never starts a heavy render and kills it as + // no-progress (reason 0). Size them as the M2 Pro/Max path does. + let [meta2, meta3, meta4, meta1] = if clusters > 2 { + let meta1_blocks = aligned(tiles_x, 2)? + .checked_mul(aligned(tiles_y, 4)?) + .and_then(|v| v.checked_mul(utiles)) + .ok_or(EOVERFLOW)? + .div_ceil(0x1980); + [ + GTP_MULTI_CLUSTER_SIZES[0], + GTP_MULTI_CLUSTER_SIZES[1], + // Partial renders need the larger size here too. + GTP_MULTI_CLUSTER_SIZES[2].max(GTP6_SIZE), + aligned( + meta1_blocks.checked_mul(META1_BLOCK_SIZE).ok_or(EOVERFLOW)?, + 0x80, + )? + .max(META1_MIN_SIZE), + ] + } else { + GTP_FIXED_SIZES + }; let sizes = [ tpc_size, tilemap_size.checked_mul(64).ok_or(EOVERFLOW)?, if layers > 1 { 0x4000 } else { 0 }, 0, - GTP_FIXED_SIZES[0], - GTP_FIXED_SIZES[1], - GTP_FIXED_SIZES[2], - GTP_FIXED_SIZES[3], + meta2, + meta3, + meta4, + meta1, ]; let mut position = 0; for ((offset, size), alignment) in gtp.iter_mut().zip(sizes).zip(GTP_ALIGNMENTS) { @@ -197,14 +238,22 @@ struct Object { backing: KernelObject, } impl Object { - fn new(dev: &AsahiDrmDevice, vm: &mmu::Vm, size: usize, m5: bool) -> Result { - let backing = KernelObject::backing(dev, size, CpuMap::WriteCombined)?; - let prot = mmu::PROT_GPU_FW_SHARED_RW; - let mapping = if m5 { - backing.map_range(vm, 0..size, super::BlockGeometry::M5_COMPACT, - cfg::TVB_PAGE, prot, mmu::UAT_PGSZ)? + /// An object of `size` bytes, on M5 mapped in the client's compact window as `m5`. + fn new(dev: &AsahiDrmDevice, vm: &mmu::Vm, size: usize, m5: Option) + -> Result { + if let Some(object) = m5 { + object.check_room(vm, size, 1)?; + } + // An M5 target is sized by the client's pass: charge it to the client. + let backing = if m5.is_some() { + KernelObject::client_backing(dev, size, vm.memory_client())? } else { - compact_alias(&backing, vm, 0..size, cfg::TVB_PAGE, prot, mmu::UAT_PGSZ)? + KernelObject::backing(dev, size, CpuMap::WriteCombined)? + }; + let prot = mmu::PROT_GPU_FW_SHARED_RW; + let mapping = match m5 { + Some(object) => object.map(&backing, vm, 0..size, prot)?, + None => compact_alias(&backing, vm, 0..size, cfg::TVB_PAGE, prot, mmu::UAT_PGSZ)?, }; Ok(Self { address: mapping.iova(), @@ -241,8 +290,8 @@ impl Target { let stride = layout.record_stride()?; layout.check_capacity(stride)?; let m5 = layout.m5.is_some(); - let records = Object::new(dev, vm, stride * DEPTH, m5)?; - let tpc = Object::new(dev, vm, tpc, m5)?; + let records = Object::new(dev, vm, stride * DEPTH, m5.then_some(PairObject::Records))?; + let tpc = Object::new(dev, vm, tpc, m5.then_some(PairObject::Tpc))?; KBox::new( Self { records, @@ -347,7 +396,8 @@ impl Target { layout.check_capacity(stride)?; let mut grew = false; if tpc > self.tpc.backing.size() { - Self::replace(&mut self.retired, &mut self.tpc, dev, vm, tpc, owners, self.m5)?; + Self::replace(&mut self.retired, &mut self.tpc, dev, vm, tpc, owners, + self.m5.then_some(PairObject::Tpc))?; grew = true; } if stride > self.stride { @@ -358,7 +408,7 @@ impl Target { vm, stride * DEPTH, owners, - self.m5, + self.m5.then_some(PairObject::Records), )?; self.stride = stride; self.slots = [None; DEPTH]; @@ -373,7 +423,7 @@ impl Target { vm: &mmu::Vm, size: usize, owners: &[Option; DEPTH], - m5: bool, + m5: Option, ) -> Result { let retain = owners.iter().any(Option::is_some); if retain { @@ -476,4 +526,28 @@ mod tests { layout.tpc_end = layout.tpc_size; assert_eq!(layout.tpc_capacity(), Err(ERANGE)); } + + #[test] + fn four_cluster_v25g83_metadata_layout() { + let mut retina = pass(3456, 32); + retina.height = 2234; + for (target, utile) in [(retina, 32), (retina, 16), (pass(10240, 16), 16)] { + let mut p = target; + p.utile_width = utile; + p.utile_height = utile; + let layout = Layout::new(&p, 4, RegisterPrograms::V25G83).unwrap(); + let gtp4 = layout.gtp[4].unwrap(); + let gtp5 = layout.gtp[5].unwrap(); + let gtp6 = layout.gtp[6].unwrap(); + let gtp7 = layout.gtp[7].unwrap(); + assert_eq!(gtp5 - gtp4, GTP_MULTI_CLUSTER_SIZES[0]); + assert!(gtp6 - gtp5 >= GTP_MULTI_CLUSTER_SIZES[1]); + assert!(gtp7 - gtp6 >= GTP_MULTI_CLUSTER_SIZES[2].max(GTP6_SIZE)); + assert_eq!(layout.tpc_end - gtp7, META1_MIN_SIZE); + } + // Two-cluster V25G83 (M4 Pro) keeps its original fixed metadata sizes. + let two = Layout::new(&retina, 2, RegisterPrograms::V25G83).unwrap(); + assert_eq!(two.gtp[5].unwrap() - two.gtp[4].unwrap(), GTP_FIXED_SIZES[0]); + assert_eq!(two.tpc_end - two.gtp[7].unwrap(), GTP_FIXED_SIZES[3]); + } } diff --git a/drivers/gpu/drm/asahi/g17/channel.rs b/drivers/gpu/drm/asahi/g17/channel.rs index 00aff91fa0a1c2..214004f018f608 100644 --- a/drivers/gpu/drm/asahi/g17/channel.rs +++ b/drivers/gpu/drm/asahi/g17/channel.rs @@ -15,6 +15,10 @@ use super::fw::{channels::*, initdata::status}; use super::initdata::InitData; use super::Role; +// The busy-time rebase bound counts the statistics ring's records; `telemetry.rs` repeats the +// ring size so that it builds on its own for the host tests. +const _: () = assert!(super::telemetry::STATISTICS_RING_RECORDS == STATISTICS_SLOTS); + /// Device-control records published since the driver loaded. Counted across firmware /// restarts, so it only grows. static CONTROL_PUBLISHED: AtomicU64 = AtomicU64::new(0); @@ -99,12 +103,18 @@ pub(crate) struct Rings { } impl Rings { - /// `m5`: the firmware runs the M5 protocol ([`super::stats::protocol`]). - pub(crate) fn new(graph: super::fw::variant::InitGraph, m5: bool) -> Result { + /// `protocol`: the records the firmware sends beyond utilisation + /// ([`super::telemetry::Protocol`]). + /// `max_pstate`: highest valid performance state index for `0x1b` reports. + pub(crate) fn new( + graph: super::fw::variant::InitGraph, + protocol: super::telemetry::Protocol, + max_pstate: u32, + ) -> Result { Ok(Self { quarantined: [[false; 2]; 2], reports: super::reports::Reports::new()?, - telemetry: super::telemetry::Telemetry::new(super::stats::protocol(graph, m5)), + telemetry: super::telemetry::Telemetry::new(protocol, max_pstate), max_age_ns: super::stats::max_age_ns(graph), suspended: false, discard_statistics: [false; 2], @@ -174,7 +184,19 @@ impl Rings { } pub(super) fn read_statistics(&self, now_ns: u64) -> super::telemetry::Readout { - self.telemetry.read(now_ns, self.max_age_ns) + let mut view = self.telemetry.read(now_ns, self.max_age_ns); + // A quarantined statistics ring adds nothing more: the total is no longer current. + if view.busy_status == super::telemetry::VALID && self.statistics_quarantined() { + view.busy_status = super::telemetry::STALE; + } + view + } + + /// Either role's statistics ring is quarantined, which stops both roles' exports. + fn statistics_quarantined(&self) -> bool { + self.quarantined + .iter() + .any(|rings| rings[ReportRing::Statistics as usize]) } pub(super) fn write_reports(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result { @@ -205,13 +227,13 @@ impl Rings { return; } let statistics = matches!(ring, ReportRing::Statistics); - let accept = !self.suspended - && self.statistics_powered + // Suspend, a real invalidation's discard and quarantine keep every record out. + let accept_busy = !self.suspended && !self.discard_statistics[role as usize] - && !self - .quarantined - .iter() - .any(|rings| rings[ReportRing::Statistics as usize]); + && !self.statistics_quarantined(); + // A power boundary also keeps the records before it out of the averaging epoch; + // their own timestamps still place them for busy time (Telemetry::record_busy). + let accept = accept_busy && self.statistics_powered; if let Err(error) = Self::consume_report( init, role, @@ -220,6 +242,7 @@ impl Rings { &mut self.telemetry, self.max_age_ns, accept, + accept_busy, &mut self.statistics_cutoff[role as usize], ) { self.stop_report(dev, role, ring, error); @@ -250,6 +273,7 @@ impl Rings { telemetry: &mut super::telemetry::Telemetry, max_age_ns: u64, accept_statistics: bool, + accept_busy: bool, statistics_cutoff: &mut Option, ) -> Result { let (state, entries, capacity, allowed_types) = ring.geometry(init); @@ -289,6 +313,8 @@ impl Rings { reports.record(role, words, host_ns, allowed_types, admitted); if admitted { telemetry.record(&words, host_ns, max_age_ns); + } else if accept_busy { + telemetry.record_busy(&words); } } consumer = (consumer + 1) & (capacity - 1); diff --git a/drivers/gpu/drm/asahi/g17/clpc.c b/drivers/gpu/drm/asahi/g17/clpc.c index 58adaba19910f2..bfe26e5d91c14d 100644 --- a/drivers/gpu/drm/asahi/g17/clpc.c +++ b/drivers/gpu/drm/asahi/g17/clpc.c @@ -10,6 +10,12 @@ void asahi_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active) { apple_clpc_gpu_set_active(gpu, active); } + +void asahi_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille) +{ + apple_clpc_gpu_set_busy(gpu, permille); +} + void asahi_clpc_gpu_put(struct apple_clpc_gpu *gpu) { apple_clpc_gpu_put(gpu); diff --git a/drivers/gpu/drm/asahi/g17/clpc.h b/drivers/gpu/drm/asahi/g17/clpc.h index 372820ade7efff..6b16d5e8d58012 100644 --- a/drivers/gpu/drm/asahi/g17/clpc.h +++ b/drivers/gpu/drm/asahi/g17/clpc.h @@ -5,5 +5,6 @@ struct device; struct apple_clpc_gpu; int asahi_clpc_gpu_get(void *dev, struct apple_clpc_gpu **out); void asahi_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active); +void asahi_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille); void asahi_clpc_gpu_put(struct apple_clpc_gpu *gpu); #endif diff --git a/drivers/gpu/drm/asahi/g17/command.rs b/drivers/gpu/drm/asahi/g17/command.rs index da60d6b456d7eb..017e9ff09e6789 100644 --- a/drivers/gpu/drm/asahi/g17/command.rs +++ b/drivers/gpu/drm/asahi/g17/command.rs @@ -15,6 +15,26 @@ use super::render_resources::{ComputePrograms, Programs}; const _: () = assert!(uapi::drm_asahi_compute_flags_DRM_ASAHI_COMPUTE_AS_BUILD == 1 << 2); +/// The vertex, fragment and compute attachment lists a [`Parser`] keeps. +const ATTACHMENT_KINDS: usize = 3; +/// What a stream sets for the work commands after it: the attachment lists, the render +/// resources (either version) and the compute resources. +const SET_KINDS: usize = ATTACHMENT_KINDS + 2; + +/// The largest command stream in which every entry has an effect: as many work commands as +/// a submission may hold, each after at most one set of each kind, and every entry at its +/// largest. A set that a later one replaces before any work, or one after the last work +/// command, changes nothing, so a longer stream only repeats them. The submit ioctl refuses +/// a longer stream before copying it. +pub(crate) const MAX_STREAM: usize = crate::file::MAX_COMMANDS_PER_SUBMISSION as usize + * (1 + SET_KINDS) + * (size_of::() + u16::MAX as usize); +// kvmalloc() warns past INT_MAX. A plain kmalloc() copy warns past KMALLOC_MAX_SIZE, which depends +// on the architecture; on arm64 with 16K pages, as Apple GPUs run, it is 32 MiB. +const _: () = assert!(MAX_STREAM <= i32::MAX as usize); +#[cfg(CONFIG_ARM64)] +const _: () = assert!(MAX_STREAM <= kernel::bindings::KMALLOC_MAX_SIZE as usize); + const MAX_ATTACHMENTS: usize = crate::microseq::MAX_ATTACHMENTS; const USC_WINDOW_SIZE: u64 = 1 << 32; const MAX_SAMPLERS: u32 = 1024; @@ -184,7 +204,7 @@ pub(crate) struct Command { pub(crate) struct Parser<'a> { bytes: &'a [u8], counts: [u16; 2], - attachments: [Attachments; 3], + attachments: [Attachments; ATTACHMENT_KINDS], render_resources: Option>, compute_resources: Option>, } @@ -194,7 +214,7 @@ impl<'a> Parser<'a> { Self { bytes, counts: [0; 2], - attachments: [Attachments::EMPTY; 3], + attachments: [Attachments::EMPTY; ATTACHMENT_KINDS], render_resources: None, compute_resources: None, } @@ -290,19 +310,21 @@ impl<'a> Parser<'a> { return Err(EINVAL); } self.render_resources = if bytes.is_empty() { None } - else { Some(Arc::new(Programs::parse(bytes)?, GFP_KERNEL)?) }; + else { Some(Arc::new(Programs::parse(bytes)?, GFP_KERNEL_ACCOUNT)?) }; } uapi::drm_asahi_cmd_type_DRM_ASAHI_SET_RENDER_RESOURCES_V2 => { if barriers != [uapi::DRM_ASAHI_BARRIER_NONE as u16; 2] { return Err(EINVAL); } self.render_resources = if bytes.is_empty() { None } - else { Some(Arc::new(Programs::parse_v2(bytes)?, GFP_KERNEL)?) }; + else { Some(Arc::new(Programs::parse_v2(bytes)?, GFP_KERNEL_ACCOUNT)?) }; } uapi::drm_asahi_cmd_type_DRM_ASAHI_SET_COMPUTE_RESOURCES => { if barriers != [uapi::DRM_ASAHI_BARRIER_NONE as u16; 2] { return Err(EINVAL); } self.compute_resources = if bytes.is_empty() { None } - else { Some(Arc::new(ComputePrograms::parse(bytes)?, GFP_KERNEL)?) }; + else { + Some(Arc::new(ComputePrograms::parse(bytes)?, GFP_KERNEL_ACCOUNT)?) + }; } _ => return Err(EINVAL), } @@ -466,6 +488,9 @@ pub(crate) enum Validated { ray_query: [RayQueryStage; 2], resources: Option>, plan: Option, + /// Bytes of the client's M5 compact window that each render pair built for this render + /// reserves, from the layout SUBMIT derives with the plan (`None` without an M5 plan). + pair_window: Option, attachments: [Attachments; 2], timestamps: [uapi::drm_asahi_timestamps; 2], }, @@ -473,8 +498,9 @@ pub(crate) enum Validated { long_job: bool, intersection: IntersectionTables, matrix_ops: bool, - /// The command may copy or reset queries, so it must follow the host's - /// timestamp publication for earlier commands. + /// The command may read or write a timestamp or availability word whose + /// host publication for an earlier command is still pending, so it must + /// follow that publication (no DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS). query_access: bool, /// The command's writes are visible when it completes (M5). visible_completion: bool, @@ -510,6 +536,14 @@ impl Validated { Self::Render { long_job, .. } | Self::Compute { long_job, .. } => *long_job, } } + /// The compact-window bytes of each render pair kept by SUBMIT (`Render::pair_window`); + /// `None` for a compute command. + pub(crate) fn pair_window(&self) -> Option { + match self { + Self::Render { pair_window, .. } => *pair_window, + Self::Compute { .. } => None, + } + } pub(crate) fn allow_long_job(&mut self) { match self { Self::Render { long_job, .. } | Self::Compute { long_job, .. } => *long_job = true, @@ -738,6 +772,7 @@ impl Payload { ray_query: *ray_query, resources: resources.clone(), plan: None, + pair_window: None, attachments: *attachments, timestamps: [cmd.ts_vtx, cmd.ts_frag], }) @@ -878,3 +913,44 @@ mod attachment_tests { assert_eq!(list(&[]).validate_hint(), Ok(())); } } + +#[kunit_tests(asahi_g17_stream)] +mod stream_tests { + use super::*; + + const COMMANDS: usize = crate::file::MAX_COMMANDS_PER_SUBMISSION as usize; + + /// Appends a zeroed render command whose payload is `size` bytes long. + fn push_render(stream: &mut KVVec, size: u16) { + let render = uapi::drm_asahi_cmd_type_DRM_ASAHI_CMD_RENDER as u16; + // cmd_type, size, vdm_barrier, cdm_barrier. + for field in [render, size, 0, 0] { + stream.extend_from_slice(&field.to_le_bytes(), GFP_KERNEL).unwrap(); + } + stream.extend_with(size.into(), 0, GFP_KERNEL).unwrap(); + } + + fn parsed(stream: &[u8]) -> Result { + let mut parser = Parser::new(stream); + let mut count = 0; + while parser.next()?.is_some() { + count += 1; + } + parser.finish()?; + Ok(count) + } + + #[test] + fn the_largest_work_commands_a_submission_holds_fit_the_stream_bound() { + assert_eq!(size_of::(), 8); + let mut stream = KVVec::new(); + for _ in 0..COMMANDS { + push_render(&mut stream, u16::MAX); + } + assert_eq!(parsed(&stream), Ok(COMMANDS)); + assert!(stream.len() <= MAX_STREAM); + // One more work command is refused, so the bound counts every command it may hold. + push_render(&mut stream, size_of::() as u16); + assert_eq!(parsed(&stream), Err(EINVAL)); + } +} diff --git a/drivers/gpu/drm/asahi/g17/completion.rs b/drivers/gpu/drm/asahi/g17/completion.rs index 41e8b3c09fc9a4..8ae1c8be116d7f 100644 --- a/drivers/gpu/drm/asahi/g17/completion.rs +++ b/drivers/gpu/drm/asahi/g17/completion.rs @@ -35,7 +35,7 @@ pub(crate) use publication::{Prepared as PreparedPublication, Publication}; struct Destination { // The buffer keeps its GPU alias and its CPU mapping alive. - buffer: Arc, + buffer: Arc, offset: usize, /// The destination's address in the firmware timestamp window, if its buffer is mapped there. window_va: Option, @@ -128,9 +128,12 @@ const fn window_slot(index: usize) -> bool { /// one releases only a buffer reference; the buffer defers its own mapping release. pub(crate) struct Destinations { stamps: [Option; 4], - /// A render: the firmware gets its fragment end destination through the window. A compute - /// command's only stamp pair stays kernel-private (recovery trusts it). - render: bool, + /// A render whose fragment end destination may be written directly by + /// firmware through the timestamp window. Cleared when ordered behind + /// pending host timestamp predecessors so firmware cannot race with their + /// deferred host writes or bypass an inherited error. A compute command's + /// only stamp pair stays kernel-private (recovery trusts it). + allow_window: bool, /// The firmware was handed window destinations ([`Self::window_vas`]). handed: AtomicBool, } @@ -150,15 +153,19 @@ impl Destinations { } Ok(Self { stamps: destinations, - render: timestamps.len() == 2, + allow_window: timestamps.len() == 2, handed: AtomicBool::new(false), }) } + pub(crate) fn disable_window(&mut self) { + self.allow_window = false; + } + /// Window addresses for a render's vertex and fragment start/end destinations: the fragment /// end's if it is mapped in the window, 0 for the others. fn window_vas(&self) -> [u64; 4] { - if !self.render || WINDOW_MISSES.load(Ordering::Relaxed) >= WINDOW_GIVE_UP { + if !self.allow_window || WINDOW_MISSES.load(Ordering::Relaxed) >= WINDOW_GIVE_UP { return [0; 4]; } let vas: [u64; 4] = core::array::from_fn(|i| { @@ -175,6 +182,20 @@ impl Destinations { self.stamps.iter().any(Option::is_some) } + #[cfg(CONFIG_KUNIT = "y")] + pub(super) fn empty() -> Self { + Self { + stamps: core::array::from_fn(|_| None), + allow_window: false, + handed: AtomicBool::new(false), + } + } + + #[cfg(CONFIG_KUNIT = "y")] + pub(super) fn allows_window(&self) -> bool { + self.allow_window + } + fn iter(&self) -> core::slice::Iter<'_, Option> { self.stamps.iter() } @@ -201,35 +222,92 @@ struct Output { } impl Output { - fn publish(&self, result: Result<[u64; 4]>) { + /// `status` is the command's VM status. + fn publish(&self, result: Result<[u64; 4]>, status: &VmStatus) { match result { - Ok(ticks) => self.destinations.write(ticks), - Err(error) => self.fence.set_error(error), + Ok(ticks) => { + self.destinations.write(ticks); + self.fence.signal(); + } + Err(error) => status.signal_failure(|| { + self.fence.set_error(error); + self.fence.signal(); + }), } - self.fence.signal(); self.member.complete(result.map(|_| ())); } } -enum HostOutput { +enum HostOutputKind { Immediate(Output), Ordered(Arc), } +pub(super) struct HostOutput(HostOutputKind); + impl HostOutput { + /// Both render and compute commands use an ordered [`Publication`] when + /// they write host timestamps or inherit ordered host predecessors: + /// timestamp-writing compute must expose a [`Publication`] so overlapping + /// cross-engine consumers can chain behind it, and compute consumers with + /// host predecessors must chain behind theirs. When `host_predecessors` is + /// false, activation clears the sentinel immediately so `finish()` + /// publishes synchronously with no extra delay. + fn new( + output: Output, + status: Arc, + host_predecessors: bool, + has_outputs: bool, + ) -> Result { + if host_predecessors || has_outputs { + Ok(Self(HostOutputKind::Ordered(Publication::new( + output, status, has_outputs, + )?))) + } else { + Ok(Self(HostOutputKind::Immediate(output))) + } + } + fn output(&self) -> &Output { - match self { - Self::Immediate(output) => output, - Self::Ordered(publication) => publication.output(), + match &self.0 { + HostOutputKind::Immediate(output) => output, + HostOutputKind::Ordered(publication) => publication.output(), } } - fn finish(&self, result: Result<[u64; 4]>) { - match self { - Self::Immediate(output) => output.publish(result), - Self::Ordered(publication) => publication.finish(result), + pub(super) fn publication(&self) -> Option> { + match &self.0 { + HostOutputKind::Ordered(publication) => Some(publication.clone()), + HostOutputKind::Immediate(_) => None, + } + } + + pub(super) fn finish(&self, result: Result<[u64; 4]>, status: &VmStatus) { + match &self.0 { + HostOutputKind::Immediate(output) => output.publish(result, status), + HostOutputKind::Ordered(publication) => publication.finish(result), } } + + #[cfg(CONFIG_KUNIT = "y")] + pub(super) fn test_pair( + contexts: &FenceContexts, + status: &Arc, + host_predecessors: bool, + has_outputs: bool, + ) -> Result<(Self, Fence)> { + let fence = fence::independent(contexts)?; + let handle = Fence::from_fence(&fence); + let output = Output { + fence, + member: fence::Aggregate::test_member(contexts)?, + destinations: Destinations::empty(), + }; + Ok(( + Self::new(output, status.clone(), host_predecessors, has_outputs)?, + handle, + )) + } } /// Firmware writes two aligned words in a write-combined page of its own per @@ -370,7 +448,7 @@ impl M5ComputeTimestamps { pub(crate) struct Completion { status: Arc, output: HostOutput, - // Present only when this command's public result may wait for a render + // Present only when this command's public result may wait for a // predecessor's host writes. DRM credits must follow the terminal result. terminal: Option>, compute: Option, @@ -416,7 +494,7 @@ impl Completion { context: &Arc, member: Member, vm_job: mmu::VmJobGuard, - destinations: Destinations, + mut destinations: Destinations, compute: bool, host_predecessors: bool, feed: Option>, @@ -424,7 +502,10 @@ impl Completion { usage: Arc>>, ) -> Result> { let fence = fence::independent(contexts)?; - let ordered = !compute && (host_predecessors || destinations.iter().any(Option::is_some)); + let has_outputs = destinations.has_outputs(); + if host_predecessors { + destinations.disable_window(); + } let terminal = if host_predecessors { Some(fence::independent(contexts)?) } else { @@ -435,11 +516,12 @@ impl Completion { member, destinations, }; - let output = if ordered { - HostOutput::Ordered(Publication::new(output, context.status().clone())?) - } else { - HostOutput::Immediate(output) - }; + let output = HostOutput::new( + output, + context.status().clone(), + host_predecessors, + has_outputs, + )?; // M5 compute binds its timestamp pair in its physical queue's page at publication. let is_compute = compute; let compute = if compute && !context.is_m5() { @@ -485,10 +567,7 @@ impl Completion { .map_or_else(|| self.fence(), |fence| Fence::from_fence(fence)) } pub(crate) fn publication(&self) -> Option> { - match &self.output { - HostOutput::Ordered(publication) => Some(publication.clone()), - HostOutput::Immediate(_) => None, - } + self.output.publication() } fn signal_terminal(&self, result: Result<[u64; 4]>) { if let Some(fence) = &self.terminal { @@ -512,6 +591,12 @@ impl Completion { pub(super) fn is_input_source(&self, source: &Arc) -> bool { self.output.output().member.is_source(source) } + pub(crate) fn note_source_published(&self, published: super::fence::PublishedSource) { + self.output.output().member.note_published(published); + } + pub(crate) fn clear_source_published(&self) { + self.output.output().member.clear_published(); + } pub(super) fn set_source_ready(&self, ready: Fence) { self.output.output().member.set_source_ready(ready); } @@ -609,6 +694,7 @@ impl Completion { }) .is_ok(); if accepted { + self.clear_source_published(); self.replay_timeout.store(true, Ordering::Release); // Callers replay only work proven not to have started; the new // publication runs from the beginning and reports its own result. @@ -627,6 +713,7 @@ impl Completion { pub(crate) fn has_firmware_consumer(&self) -> bool { self.firmware_consumer.load(Ordering::Acquire) + || self.output.output().member.has_firmware_consumer() } pub(crate) fn take_replay_timeout(&self) -> bool { @@ -813,14 +900,17 @@ impl Completion { if let Some(sources) = &self.sources { sources.release(); } - drop(self.render.lock().take()); + if !self.is_compute { + drop(self.render.lock().take()); + } drop(self.vm_job.lock().take()); } /// Exact retirement permits the physical lease and VM pin to be released /// before waking userspace. A failure fence alone never establishes this. + /// Returns true if this call claimed signalling and released healthy pins. #[track_caller] - pub(crate) fn complete(&self, result: Result<[u64; 4]>) { + pub(crate) fn complete(&self, result: Result<[u64; 4]>) -> bool { // M5 compute feeds the refill detector only from its exact execution record // (RetiredCompute); M5 compute is the compute without pooled timestamps. let execution = if self.is_compute && self.compute.is_none() { @@ -828,20 +918,24 @@ impl Completion { } else { result.as_ref().ok().map(|ticks| [ticks[0], ticks[1]]) }; - self.complete_with_compute(result, execution); + self.complete_with_compute(result, execution) } /// Compute feedback is separate from public timestamps, which may contain /// a synthesized retirement envelope when the execution record is absent. #[track_caller] - fn complete_with_compute(&self, mut result: Result<[u64; 4]>, compute: Option<[u64; 2]>) { + fn complete_with_compute( + &self, + mut result: Result<[u64; 4]>, + compute: Option<[u64; 2]>, + ) -> bool { if result.is_ok() { if let Err(error) = self.check_source_inputs() { result = Err(error); } } if self.signalled.swap(true, Ordering::AcqRel) { - return; + return false; } if result.is_ok() && self.interrupted() { result = Err(ECANCELED); @@ -856,6 +950,15 @@ impl Completion { self.usage.add(Engine::Fragment, ticks[2], ticks[3], hz); } } + if let Err(error) = result { + // Spared work cancelled after another VM's recovery is not this client's device loss. + self.report(error); + } + self.release_healthy(); + self.signal_terminal(result); + self.output.finish(result, &self.status); + // Feed detector and busy-run tracking are internal host heuristics: update them + // after signalling the fence so their spinlocks stay off the wakeup critical path. if let (Some(feed), Ok(ticks)) = (&self.feed, &result) { // Compute reports its dispatch envelope in the first pair, a // render its fragment pass in the second. @@ -871,13 +974,7 @@ impl Completion { feed.note_work(self.context_id, start.unwrap_or(0), ticks[1].max(ticks[3])); } } - if let Err(error) = result { - // Spared work cancelled after another VM's recovery is not this client's device loss. - self.report(error); - } - self.release_healthy(); - self.signal_terminal(result); - self.output.finish(result); + true } /// A rejected, never-published command cannot poison the VM for contention. @@ -894,7 +991,7 @@ impl Completion { } self.release_healthy(); self.signal_terminal(Err(error)); - self.output.finish(Err(error)); + self.output.finish(Err(error), &self.status); } /// The physical queue must already be quarantined. Keep mappings pinned while @@ -915,7 +1012,7 @@ impl Completion { self.report(error); } self.signal_terminal(Err(error)); - self.output.finish(Err(error)); + self.output.finish(Err(error), &self.status); } } @@ -941,18 +1038,20 @@ impl Deferred { pub(crate) fn finish(self) { match self { Self::RetiredCompute(completion, ticks, execution) => { - completion.complete_with_compute(Ok(ticks), execution); - completion.release_after_retirement(); + if !completion.complete_with_compute(Ok(ticks), execution) { + completion.release_after_retirement(); + } } Self::Retired(completion, result) => { - completion.complete(result); // An earlier failure may already have signalled this fence while // retaining the pin. Retirement is a separate release witness. - completion.release_after_retirement(); + if !completion.complete(result) { + completion.release_after_retirement(); + } } Self::Drained(completion, result) => { completion.release_after_retirement(); - completion.complete(result); + let _ = completion.complete(result); } Self::FailedOwned(completion, error) => completion.fail_while_owned(error), Self::Unpublished(completion, error) => completion.fail_unpublished(error), @@ -976,4 +1075,18 @@ mod window_tests { assert_eq!(ticks_to_ns(24), 1_000); assert_eq!(ticks_to_ns(24_000_025), 1_000_001_041); } + + #[test] + fn disable_window_clears_allow_window_and_leaves_handed_false() { + let mut dest = Destinations { + stamps: core::array::from_fn(|_| None), + allow_window: true, + handed: AtomicBool::new(false), + }; + assert!(dest.allows_window()); + dest.disable_window(); + assert!(!dest.allows_window()); + assert_eq!(dest.window_vas(), [0; 4]); + assert!(!dest.handed.load(Ordering::Acquire)); + } } diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index 8e16a14f054886..f1170ee9a4cdf0 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -2,13 +2,14 @@ //! Host-only ordering of timestamp writes, independent of scheduler credits. //! -//! Links point from earlier logical render ordinals to later ones. They retain +//! Links point from earlier logical ordinals to later ones. They retain //! only public output state, never a packet, physical render lease or VM job pin. //! All link storage is allocated before acceptance. Completion neither allocates //! nor waits for another command; the last prerequisite publishes a ready result. use super::Output; use crate::g17::{dependency::PRODUCER_FAILED, status::VmStatus}; +use core::sync::atomic::{AtomicBool, Ordering}; use kernel::{new_mutex, prelude::*, sync::{Arc, Mutex}}; type Links = Option>; @@ -28,6 +29,9 @@ struct State { predecessor_error: Option, claimed: bool, published: Option, + // All predecessors published cleanly while this timestamp-free publication + // still has no result of its own; successors have already been released. + upstream_released: bool, successors: Links, } @@ -49,16 +53,27 @@ impl State { pub(crate) struct Publication { output: Output, status: Arc, + has_outputs: bool, + // True while this publication may still write host timestamps or deliver a + // deferred predecessor error. Cleared only once no host write or error + // remains, and never set again. + pending: AtomicBool, #[pin] state: Mutex, } impl Publication { - pub(super) fn new(output: Output, status: Arc) -> Result> { + pub(super) fn new( + output: Output, + status: Arc, + has_outputs: bool, + ) -> Result> { Arc::pin_init( pin_init!(Self { output, status, + has_outputs, + pending: AtomicBool::new(true), state <- new_mutex!(State { // Acceptance installs all links before releasing this sentinel. remaining: 1, @@ -66,6 +81,7 @@ impl Publication { predecessor_error: None, claimed: false, published: None, + upstream_released: false, successors: None, }, "G17 host timestamp publication"), }), @@ -77,8 +93,14 @@ impl Publication { &self.output } + /// Whether this publication still has an unpublished host timestamp write + /// or an unresolved or failed predecessor chain. + pub(crate) fn is_pending(&self) -> bool { + self.pending.load(Ordering::Acquire) + } + /// One terminal result, offered separately from its physical-retirement proof. - pub(super) fn finish(&self, result: Result<[u64; 4]>) { + pub(crate) fn finish(&self, result: Result<[u64; 4]>) { let ready = { let mut state = self.state.lock(); if state.claimed || state.result.is_some() { @@ -100,13 +122,16 @@ impl Publication { self.status.report_failure(error); } } - self.output.publish(result); + self.output.publish(result, &self.status); let result = result.map(|_| ()); let mut links = { let mut state = self.state.lock(); // A late link is acknowledged only after timestamp writes, the public // fence and aggregate membership have all been published off this lock. state.published = Some(result); + if result.is_ok() { + self.pending.store(false, Ordering::Release); + } state.successors.take() }; let mut next = links.as_mut(); @@ -118,31 +143,56 @@ impl Publication { } fn predecessor_done(&self, result: Result) -> Links { - let ready = { + let (ready, settled) = { let mut state = self.state.lock(); debug_assert!(state.remaining != 0); if result.is_err() && state.predecessor_error.is_none() { state.predecessor_error = Some(PRODUCER_FAILED); } state.remaining -= 1; - state.claim() + if let Some(ready) = state.claim() { + (Some(ready), None) + } else if state.remaining == 0 + && !self.has_outputs + && state.predecessor_error.is_none() + && !state.upstream_released + { + // Every predecessor published cleanly and this command writes + // no host timestamps, so downstream commands need not wait on + // or chain behind its GPU execution. + state.upstream_released = true; + self.pending.store(false, Ordering::Release); + (None, state.successors.take()) + } else { + (None, None) + } }; - ready.and_then(|result| self.publish(result)) + if let Some(result) = ready { + return self.publish(result); + } + let mut links = settled; + let mut next = links.as_mut(); + while let Some(link) = next { + link.result = Ok(()); + next = link.next.as_mut(); + } + links } fn add_successor(&self, mut link: KBox) { - let published = { + let immediate = { let mut state = self.state.lock(); - match state.published { - Some(result) => result, - None => { - link.next = state.successors.take(); - state.successors = Some(link); - return; - } + if let Some(result) = state.published { + result + } else if state.upstream_released { + Ok(()) + } else { + link.next = state.successors.take(); + state.successors = Some(link); + return; } }; - Self::drain(link.target.predecessor_done(published)); + Self::drain(link.target.predecessor_done(immediate)); } /// Iterative depth-first notification, O(nodes + links), with no stack growth. @@ -207,3 +257,145 @@ impl Prepared { Publication::drain(self.target.predecessor_done(Ok(()))); } } + +#[cfg(CONFIG_KUNIT = "y")] +impl Publication { + pub(crate) fn test_pair( + contexts: &kernel::dma_fence::FenceContexts, + status: &Arc, + has_outputs: bool, + ) -> Result<(Arc, kernel::dma_fence::Fence)> { + let fence = crate::g17::fence::independent(contexts)?; + let handle = kernel::dma_fence::Fence::from_fence(&fence); + let output = Output { + fence, + member: crate::g17::fence::Aggregate::test_member(contexts)?, + destinations: super::Destinations::empty(), + }; + Ok((Self::new(output, status.clone(), has_outputs)?, handle)) + } +} + +#[kunit_tests(asahi_g17_publication_order)] +mod tests { + use super::*; + use crate::g17::{ + completion::Destinations, + fence::{independent, Aggregate}, + job::fence_status, + }; + use kernel::{c_str, dma_fence::{Fence, FenceContexts}, sync::LockClassKey}; + + static KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); + + fn make_pub( + contexts: &FenceContexts, + status: &Arc, + has_outputs: bool, + ) -> (Arc, Fence) { + let fence = independent(contexts).unwrap(); + let handle = Fence::from_fence(&fence); + let output = Output { + fence, + member: Aggregate::test_member(contexts).unwrap(), + destinations: Destinations::empty(), + }; + (Publication::new(output, status.clone(), has_outputs).unwrap(), handle) + } + + #[test] + fn consumer_retiring_before_delayed_producer_failure_inherits_error() { + let contexts = FenceContexts::new(1, c_str!("asahi_pub_test"), KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + let (producer, prod_fence) = make_pub(&contexts, &status, true); + let (consumer, cons_fence) = make_pub(&contexts, &status, false); + let (downstream, down_fence) = make_pub(&contexts, &status, false); + + Prepared::new(producer.clone(), core::iter::empty()).unwrap().activate(); + Prepared::new(consumer.clone(), core::iter::once(&producer)).unwrap().activate(); + Prepared::new(downstream.clone(), core::iter::once(&consumer)).unwrap().activate(); + + // Consumer and its transitive successor retire before the producer's + // deferred failure runs: neither may signal success early. + consumer.finish(Ok([1, 2, 0, 0])); + downstream.finish(Ok([3, 4, 0, 0])); + assert_eq!(fence_status(&prod_fence), 0); + assert_eq!(fence_status(&cons_fence), 0); + assert_eq!(fence_status(&down_fence), 0); + + producer.finish(Err(EIO)); + assert_eq!(fence_status(&prod_fence), EIO.to_errno()); + assert_eq!(fence_status(&cons_fence), PRODUCER_FAILED.to_errno()); + assert_eq!(fence_status(&down_fence), PRODUCER_FAILED.to_errno()); + assert!(producer.is_pending()); + assert!(consumer.is_pending()); + assert!(downstream.is_pending()); + } + + #[test] + fn clean_producer_settles_timestamp_free_chain_while_in_flight() { + let contexts = FenceContexts::new(1, c_str!("asahi_pub_settle"), KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + let (producer, prod_fence) = make_pub(&contexts, &status, true); + let (consumer, cons_fence) = make_pub(&contexts, &status, false); + let (downstream, down_fence) = make_pub(&contexts, &status, false); + + Prepared::new(producer.clone(), core::iter::empty()).unwrap().activate(); + Prepared::new(consumer.clone(), core::iter::once(&producer)).unwrap().activate(); + Prepared::new(downstream.clone(), core::iter::once(&consumer)).unwrap().activate(); + + assert!(producer.is_pending()); + assert!(consumer.is_pending()); + assert!(downstream.is_pending()); + + // Producer completes cleanly while consumer and downstream are still + // executing on the GPU: both timestamp-free publications settle at once + // without signalling their own completion fences early. + producer.finish(Ok([1, 2, 0, 0])); + assert!(fence_status(&prod_fence) > 0); + assert!(!producer.is_pending()); + assert!(!consumer.is_pending()); + assert!(!downstream.is_pending()); + assert_eq!(fence_status(&cons_fence), 0); + assert_eq!(fence_status(&down_fence), 0); + + // Downstream finishing before consumer still publishes immediately. + downstream.finish(Ok([5, 6, 0, 0])); + assert!(fence_status(&down_fence) > 0); + assert_eq!(fence_status(&cons_fence), 0); + + consumer.finish(Ok([3, 4, 0, 0])); + assert!(fence_status(&cons_fence) > 0); + } + + #[test] + fn settled_publication_failing_later_delivers_error_to_late_successor() { + let contexts = FenceContexts::new(1, c_str!("asahi_pub_settle_err"), KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + let (producer, _) = make_pub(&contexts, &status, true); + let (consumer, cons_fence) = make_pub(&contexts, &status, false); + let (early, early_fence) = make_pub(&contexts, &status, false); + + Prepared::new(producer.clone(), core::iter::empty()).unwrap().activate(); + Prepared::new(consumer.clone(), core::iter::once(&producer)).unwrap().activate(); + Prepared::new(early.clone(), core::iter::once(&consumer)).unwrap().activate(); + + producer.finish(Ok([1, 2, 0, 0])); + assert!(!consumer.is_pending()); + assert!(!early.is_pending()); + + // Consumer's own GPU execution later fails: early successor was already + // released at settlement, while a late successor added after publish + // observes consumer's error. + consumer.finish(Err(EIO)); + assert_eq!(fence_status(&cons_fence), EIO.to_errno()); + + early.finish(Ok([3, 4, 0, 0])); + assert!(fence_status(&early_fence) > 0); + + let (late, late_fence) = make_pub(&contexts, &status, false); + Prepared::new(late.clone(), core::iter::once(&consumer)).unwrap().activate(); + late.finish(Ok([5, 6, 0, 0])); + assert_eq!(fence_status(&late_fence), PRODUCER_FAILED.to_errno()); + } +} diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 84b519795da736..d5b2e152247414 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -14,7 +14,7 @@ use super::{ status::VmStatus, }; use crate::mmu::{self, ExecutionContext, Vm, UAT_PGSZ}; -use core::sync::atomic::{fence, AtomicBool, AtomicU32, AtomicU8, AtomicUsize, Ordering}; +use core::sync::atomic::{fence, AtomicBool, AtomicU32, AtomicU64, AtomicU8, AtomicUsize, Ordering}; use identity::{Order, RenderSlots, WorkStates, FREE, NODE_STRIDE, STATE_COUNT}; /// Both of a context's render channels are bound to other pairs whose publications have not @@ -166,9 +166,9 @@ impl WorkStorage { } } -/// A context's scheduler page. The M5 firmware caches its mapping, so on M5 it -/// comes from the retention pool and stays mapped until firmware stop; elsewhere -/// it is an ordinary allocation. +/// A context's scheduler page. On M5 it comes from the retention pool so its +/// VA stays mapped and fenced across releases (uncached, because both firmware +/// and host write it on reuse); elsewhere it is an ordinary allocation. pub(crate) enum SchedulerStorage { Ordinary(KernelObject), Retained(PooledObject), @@ -214,9 +214,21 @@ pub(crate) struct Context { /// A kill of this context was published, through a compute queue or on its render pairs' /// behalf. A context is killed at most once. kill_published: AtomicBool, - /// Advisory only: publication still checks the physical binding under the - /// device mutex. False skips an inline attempt known to need admission. - compute_binding_hint: AtomicBool, + /// The host's recovery generation when it first saw the kill of this context done (its + /// scheduler page's killed state), `u64::MAX` before ([`Self::restarted_since_kill`]). + kill_seen: AtomicU64, + /// The host's recovery generation at this context's first close, `u64::MAX` while open + /// ([`Self::note_closed`], [`Self::restarted_since_close`]). + closed_generation: AtomicU64, + /// The kernel closed this context's queue on its client's behalf + /// (`Firmware::close_failed_owners`) and the client has not closed it yet. + closed_for_open_client: AtomicBool, + /// Advisory count of bound compute channels: publication still checks the physical binding + /// under the device mutex. Zero skips an inline attempt known to need admission. + compute_bindings: AtomicU32, + /// Shared monotonic compute completion ordinal / submit sequence across an M5 multi-channel + /// context's physical compute queues. + compute_ordinal: AtomicU32, /// Mixed-engine contexts keep the original inline publication path. render_seen: AtomicBool, qos: Arc, @@ -281,7 +293,7 @@ impl Context { alloc, Family::Scheduler, UAT_PGSZ, - UAT_PGSZ, + 0, kernel_prot, CpuMap::WriteCombined, )?) @@ -300,11 +312,19 @@ impl Context { fence(Ordering::SeqCst); let scheduler_generation = super::ids::OBJECTS.object()?; let scheduler = Arc::new(scheduler, GFP_KERNEL)?; + // Both firmware and host write work nodes (reused every 63 submissions + // and zeroed on pool reuse). M5 keeps the whole work-state object + // uncached. G17P maps the node page firmware-cached: the host rewrites + // a node only after `WorkStorage::drained` has read the firmware's + // final `completed` count from memory, and zeroes a returned object + // only once its pool fence is met, so it never rewrites a node the + // firmware is still updating. The counter page, which the host writes + // on every kick, stays uncached. let mut object = pool.allocate( alloc, Family::WorkState, 2 * UAT_PGSZ, - UAT_PGSZ, + if alloc.uat.is_m5() { 0 } else { UAT_PGSZ }, kernel_prot, CpuMap::WriteCombined, )?; @@ -346,7 +366,11 @@ impl Context { scheduler_generation, published: AtomicBool::new(false), kill_published: AtomicBool::new(false), - compute_binding_hint: AtomicBool::new(false), + kill_seen: AtomicU64::new(u64::MAX), + closed_generation: AtomicU64::new(u64::MAX), + closed_for_open_client: AtomicBool::new(false), + compute_bindings: AtomicU32::new(0), + compute_ordinal: AtomicU32::new(0), render_seen: AtomicBool::new(false), qos, owner_pid, @@ -373,7 +397,11 @@ impl Context { } pub(crate) fn compute_binding_hint(&self) -> bool { self.render_seen.load(Ordering::Acquire) - || self.compute_binding_hint.load(Ordering::Relaxed) + || self.compute_bindings.load(Ordering::Relaxed) != 0 + } + /// Advisory count of physical compute channels currently bound to this context. + pub(crate) fn compute_binding_count(&self) -> u32 { + self.compute_bindings.load(Ordering::Acquire) } /// This logical queue has submitted render work, so its compute may have a render prefix. pub(crate) fn render_seen(&self) -> bool { @@ -385,7 +413,27 @@ impl Context { } } pub(crate) fn note_compute_binding(&self, owned: bool) { - self.compute_binding_hint.store(owned, Ordering::Relaxed); + if owned { + self.compute_bindings.fetch_add(1, Ordering::AcqRel); + } else { + let _ = self + .compute_bindings + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| { + Some(n.saturating_sub(1)) + }); + } + } + /// Atomically allocates the next 1-based shared compute ordinal and packed + /// `(predecessor_id << 32) | current_id` descriptor object_ids pair for a multi-channel + /// M5 context, so concurrent direct submissions across sibling QIDs never collide on + /// `submit_sequence`, `completion_ordinal`, or `object_ids`. + pub(crate) fn next_compute_identity(&self) -> (u32, u64) { + let prev = self.compute_ordinal.fetch_add(1, Ordering::AcqRel); + let next = prev.wrapping_add(1); + let predecessor_id = if prev == 0 { 1 } else { prev }; + let current_id = if next == 0 { 1 } else { next }; + let object_ids = (u64::from(predecessor_id) << 32) | u64::from(current_id); + (next, object_ids) } pub(crate) fn compute_timestamps(&self) -> &Arc { &self.compute_timestamps @@ -535,6 +583,42 @@ impl Context { self.kill_published.load(Ordering::Acquire) } + /// This context's queue closed at the host's recovery `generation`, under the device mutex: + /// by its client (`release_queue`), or on its behalf once a GPU recovery failed its VM as + /// guilty (`Firmware::close_failed_owners`). Only the first close counts. A close notes it + /// only after its teardown entry is reserved, so a close that failed there can be redone. + pub(crate) fn note_closed(&self, generation: u64) { + close_once(&self.closed_generation, generation); + } + + /// This context's queue closed already ([`Self::note_closed`]). Under the device mutex. + pub(crate) fn is_closed(&self) -> bool { + self.closed_generation.load(Ordering::Acquire) != u64::MAX + } + + /// The kernel closed this context's queue for its still open client (`true`), or the client + /// closed it (`false`, `release_queue`). Under the device mutex. + pub(crate) fn note_open_client(&self, open: bool) { + self.closed_for_open_client.store(open, Ordering::Release); + } + + /// See [`Self::note_open_client`]: until the client closes its queue, that queue still holds + /// this context, so its scheduler is not released and the context not reclaimed. + pub(crate) fn held_by_open_client(&self) -> bool { + self.closed_for_open_client.load(Ordering::Acquire) + } + + /// The host accepted a GPU restart (`generation`) after this context's first close. + pub(crate) fn restarted_since_close(&self, generation: u64) -> bool { + restarted_after(self.closed_generation.load(Ordering::Acquire), generation) + } + + /// The firmware finished the kill of this context (`killed`, its scheduler page) and the + /// host accepted a GPU restart (`generation`) after it first saw that. See [`restarted_since`]. + pub(crate) fn restarted_since_kill(&self, killed: bool, generation: u64) -> bool { + restarted_since(&self.kill_seen, killed, generation) + } + pub(crate) fn is_published(&self) -> bool { self.published.load(Ordering::Acquire) } @@ -834,10 +918,70 @@ fn must_retain(head: Option<[u64; 2]>, head_va: u64, killed: u32) -> bool { killed == 0 && head.is_none_or(|head| head != [0, head_va]) } +/// A restart was accepted (`generation`) after the event recorded at generation `at` +/// (`u64::MAX`: never happened). +fn restarted_after(at: u64, generation: u64) -> bool { + at != u64::MAX && generation > at +} + +/// Records the recovery `generation` of a context's first close in `at`; true for that close. +fn close_once(at: &AtomicU64, generation: u64) -> bool { + at.compare_exchange(u64::MAX, generation, Ordering::AcqRel, Ordering::Acquire).is_ok() +} + +/// Records in `seen` the recovery `generation` of the first call that sees a kill done +/// (`killed`), and reports whether a later generation was accepted since. A restart accepted +/// after that sighting was raised after the firmware had finished the kill, so it dropped +/// whatever of the killed context was still running; a restart between the kill's +/// publication and its completion does not count. A late first sighting only asks for a later +/// restart. +fn restarted_since(seen: &AtomicU64, killed: bool, generation: u64) -> bool { + if !killed { + return false; + } + let first = match seen.compare_exchange(u64::MAX, generation, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => generation, + Err(first) => first, + }; + restarted_after(first, generation) +} + #[kunit_tests(asahi_g17_qos_capacity)] mod capacity_tests { use super::*; + #[test] + fn only_a_restart_after_the_kill_was_seen_done_counts() { + let seen = AtomicU64::new(u64::MAX); + // No acknowledged kill: never, whatever restarts happened. + assert!(!restarted_since(&seen, false, 3)); + assert!(!restarted_since(&seen, false, 9)); + // The kill seen done at generation 4 (a restart at 3 came before it): not yet. + assert!(!restarted_since(&seen, true, 4)); + assert!(!restarted_since(&seen, true, 4)); + // The next accepted restart. + assert!(restarted_since(&seen, true, 5)); + assert_eq!(seen.load(Ordering::Relaxed), 4); + } + + #[test] + fn only_the_first_close_counts() { + let at = AtomicU64::new(u64::MAX); + // Closed on its client's behalf at generation 5, then by the client at 9. + assert!(close_once(&at, 5)); + assert!(!close_once(&at, 9)); + assert_eq!(at.load(Ordering::Relaxed), 5); + // So the restart at 6 still counts for its kill. + assert!(restarted_after(at.load(Ordering::Relaxed), 6)); + } + + #[test] + fn only_a_restart_after_the_close_counts() { + assert!(!restarted_after(u64::MAX, u64::MAX - 1)); + assert!(!restarted_after(7, 7)); + assert!(restarted_after(7, 8)); + } + #[test] fn linked_unkilled_work_is_retained() { let va = 0xfffffc20_0000_4400; diff --git a/drivers/gpu/drm/asahi/g17/dependency.rs b/drivers/gpu/drm/asahi/g17/dependency.rs index 5a0ed611b1ddee..239963302b18bd 100644 --- a/drivers/gpu/drm/asahi/g17/dependency.rs +++ b/drivers/gpu/drm/asahi/g17/dependency.rs @@ -138,6 +138,65 @@ impl Frontier { } } +/// How a fence orders against an earlier-held one ([`FenceOrder::order`]). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum FenceOrdering { + /// Same context, and it signals after the held one. + Later, + /// Same context, and it signals no later. + NotLater, + /// Another context: neither stands for the other. + OtherContext, +} + +/// A fence that can be ordered against another, as `dma_fence_is_later()` on a shared context. +pub(crate) trait FenceOrder { + fn order(&self, earlier: &Self) -> FenceOrdering; +} + +/// What a consumer's scheduler job must wait for from the scheduled fences of the unfinished +/// producers of the other engine that firmware orders it after. +/// +/// The scheduled fences all come from that engine's one drm_sched entity, so they share a fence +/// context and the latest stands for every earlier one: drm_sched_job_add_dependency() and +/// dma_fence_unwrap_merge() would keep only it anyway, after comparing every pair of them. The +/// latest is kept by comparison, so the order producers come in does not matter, and a scheduled +/// fence of another context is waited for instead of dropped. +pub(crate) struct ProducerWaits<'a, F> { + latest_scheduled: Option<&'a F>, +} + +impl<'a, F: FenceOrder> ProducerWaits<'a, F> { + pub(crate) const fn new() -> Self { + Self { latest_scheduled: None } + } + + /// The next producer's scheduled fence: `wait` gets a held one of another context. + pub(crate) fn producer( + &mut self, + scheduled: &'a F, + wait: impl FnOnce(&'a F) -> Result, + ) -> Result { + match self.latest_scheduled { + Some(held) => match scheduled.order(held) { + FenceOrdering::Later => self.latest_scheduled = Some(scheduled), + FenceOrdering::NotLater => {} + FenceOrdering::OtherContext => { + wait(held)?; + self.latest_scheduled = Some(scheduled); + } + }, + None => self.latest_scheduled = Some(scheduled), + } + Ok(()) + } + + /// After the last producer: `wait` gets the latest scheduled fence, if there was a producer. + pub(crate) fn finish(self, wait: impl FnOnce(&'a F) -> Result) -> Result { + self.latest_scheduled.map_or(Ok(()), wait) + } +} + #[kunit_tests(asahi_g17_dependency)] mod tests { use super::*; @@ -202,6 +261,55 @@ mod tests { assert_eq!(earliest(&mut record), None); } + /// A fence on context `.0` with seqno `.1`. + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + struct Mock(u32, u32); + + impl FenceOrder for Mock { + fn order(&self, earlier: &Self) -> FenceOrdering { + if self.0 != earlier.0 { + FenceOrdering::OtherContext + } else if self.1 > earlier.1 { + FenceOrdering::Later + } else { + FenceOrdering::NotLater + } + } + } + + fn waits(producers: &[Mock]) -> KVec { + let mut waited = KVec::new(); + let mut waits = ProducerWaits::new(); + for scheduled in producers { + waits + .producer(scheduled, |fence| { + waited.push(*fence, GFP_KERNEL).map_err(|_| ENOMEM) + }) + .unwrap(); + } + waits + .finish(|fence| waited.push(*fence, GFP_KERNEL).map_err(|_| ENOMEM)) + .unwrap(); + waited + } + + #[test] + fn a_consumer_waits_for_the_latest_scheduled_producer_only() { + assert!(waits(&[]).is_empty()); + let (s10, s11, s12) = (Mock(1, 10), Mock(1, 11), Mock(1, 12)); + assert_eq!(waits(&[s10]), [s10]); + assert_eq!(waits(&[s10, s11, s12]), [s12]); + // Whatever the order they come in. + assert_eq!(waits(&[s12, s10, s11]), [s12]); + } + + #[test] + fn a_scheduled_fence_of_another_context_is_waited_for() { + // A producer from another entity is not stood for by this one's fences. + let (a5, b7, b8) = (Mock(1, 5), Mock(2, 7), Mock(2, 8)); + assert_eq!(waits(&[a5, b7, b8]), [a5, b8]); + } + #[test] fn failed_predecessor_cannot_be_bypassed() { let mut frontier = Frontier::new(); diff --git a/drivers/gpu/drm/asahi/g17/event.rs b/drivers/gpu/drm/asahi/g17/event.rs index 7cfcf2ad75283b..63655f8d56489d 100644 --- a/drivers/gpu/drm/asahi/g17/event.rs +++ b/drivers/gpu/drm/asahi/g17/event.rs @@ -2,8 +2,8 @@ //! Event service ordering under the device mutex. A restart ends its role's batch; a worker //! joins preparation leases and services it on a separate turn before continuing the rings. -//! On M5 only the event rings are consumed here: the firmware's trace and statistics reports -//! are drained after the completions this service retires have been signalled +//! Only the event rings are consumed here: the firmware's trace and statistics reports are +//! drained after the completions this service retires have been signalled //! (`Firmware::drain_reports`), so no report queued ahead of a completion delays its fence. use super::{ @@ -16,10 +16,6 @@ use kernel::prelude::*; pub(super) trait Transport { /// The firmware instances of this GPU: the primary, and the secondary where one exists. fn roles(&self) -> &'static [Role]; - fn trace(&mut self, role: Role); - fn statistics(&mut self, role: Role); - /// The reports are drained after the pass's completions are signalled (M5). - fn reports_after_signal(&self) -> bool; fn drain( &mut self, role: Role, @@ -111,14 +107,6 @@ pub(super) fn service(host: &mut H) -> Result { return Ok(Pending::default()); } host.observe_render_releases()?; - if !host.reports_after_signal() { - for &role in host.roles() { - host.trace(role); - } - for &role in host.roles() { - host.statistics(role); - } - } let mut masks = [0; 2]; if !host.recovery().pending() { let mut settled = false; diff --git a/drivers/gpu/drm/asahi/g17/fans.c b/drivers/gpu/drm/asahi/g17/fans.c index 6178a620686084..dbc63b68c4bccf 100644 --- a/drivers/gpu/drm/asahi/g17/fans.c +++ b/drivers/gpu/drm/asahi/g17/fans.c @@ -2,8 +2,10 @@ /* * The M5 thermal governor's sensor and fan calls (thermal.rs). The thermal * core and the SMC hwmon cell have stubs where they are not built; Rust - * reaches them through these. + * reaches them through these. All macsmc-hwmon device tree binding knowledge + * stays in drivers/hwmon/macsmc-hwmon.c. */ +#include #include #include #include @@ -22,3 +24,37 @@ int asahi_fans_request(struct device *dev, unsigned int permille, unsigned int m { return macsmc_hwmon_fans_request(dev, permille, min_step_rpm); } + +bool asahi_fans_hotspot_described(void) +{ + return macsmc_hwmon_hotspot_assist_available(); +} + +int asahi_fans_hotspot_policy(struct device *dev, int *trigger_mc, int *release_mc, + unsigned int *hold_ms) +{ + struct macsmc_hwmon_fan_assist policy; + int ret; + + ret = macsmc_hwmon_hotspot_assist_policy(dev, &policy); + if (ret) + return ret; + *trigger_mc = policy.trigger_mc; + *release_mc = policy.release_mc; + *hold_ms = policy.hold_ms; + return 0; +} + +/* + * A kernel fan request for hotspot fan assistance on the bound provider @dev: + * refused (-EPERM) unless the provider exposes a valid DT-configured hotspot + * assist policy, and only drives fans marked with apple,fan-manual-control. + * Handing the fans back (@permille 0) is always allowed. + */ +int asahi_fans_request_described(struct device *dev, unsigned int permille, + unsigned int min_step_rpm) +{ + if (permille && macsmc_hwmon_hotspot_assist_policy(dev, NULL)) + return -EPERM; + return macsmc_hwmon_fans_request_manual(dev, permille, min_step_rpm); +} diff --git a/drivers/gpu/drm/asahi/g17/fans.h b/drivers/gpu/drm/asahi/g17/fans.h index 4bc18d80d3fe07..a29b4228c4987d 100644 --- a/drivers/gpu/drm/asahi/g17/fans.h +++ b/drivers/gpu/drm/asahi/g17/fans.h @@ -1,7 +1,13 @@ /* SPDX-License-Identifier: GPL-2.0-only OR MIT */ #ifndef _ASAHI_G17_FANS_H #define _ASAHI_G17_FANS_H +#include struct device; int asahi_zone_temp(const char *name, int *temp); int asahi_fans_request(struct device *dev, unsigned int permille, unsigned int min_step_rpm); +bool asahi_fans_hotspot_described(void); +int asahi_fans_hotspot_policy(struct device *dev, int *trigger_mc, int *release_mc, + unsigned int *hold_ms); +int asahi_fans_request_described(struct device *dev, unsigned int permille, + unsigned int min_step_rpm); #endif diff --git a/drivers/gpu/drm/asahi/g17/feed.rs b/drivers/gpu/drm/asahi/g17/feed.rs index 974a926f8d6c3e..442ef38ae14728 100644 --- a/drivers/gpu/drm/asahi/g17/feed.rs +++ b/drivers/gpu/drm/asahi/g17/feed.rs @@ -11,7 +11,7 @@ //! notifier unregistration joins callbacks without holding that mutex. //! M5 requests full CPU capacity only while refill pressure keeps the detector //! active. Sustained demand can renew its deadline indefinitely; withdrawal -//! occurs on a later worker poll, not at an exact eight-millisecond boundary. +//! occurs on a later worker poll, not at an exact twenty-millisecond boundary. use crate::hw::t8140::qos::CLOCK_HZ; use core::{ @@ -40,12 +40,12 @@ const MAX_REFILL_TICKS: u64 = CLOCK_HZ / 500; const _: () = assert!(CLOCK_HZ == crate::hw::t8140::resources::COMMAND_TIMESTAMP_HZ); const STREAK_ON: u32 = 8; const STREAK_MAX: u32 = 64; -const LINGER_NS: u64 = 8_000_000; +const LINGER_NS: u64 = 20_000_000; const POLL_MS: i64 = 2; #[cfg(CONFIG_CPU_FREQ)] const FLOOR_PERCENT: u64 = 50; const WAIT_UTIL_MIN: u32 = 512; -const WAIT_HINT_MS: u32 = 8; +const WAIT_HINT_MS: u32 = 20; #[cfg(CONFIG_CPU_FREQ)] const MAX_POLICIES: usize = 8; @@ -526,10 +526,18 @@ impl Feed { } } + /// Temporary capacity hint for blocking syncobj waits on active GPU streams. + /// + /// Host-refill-bound streams (`wanted`) require an applied cpufreq floor, + /// while GPU-bound streams (`bound`) return the hint without raising the + /// cpufreq floor so EAS keeps the waiter on a P-core across long passes. pub(crate) fn wait_hint(&self) -> Option<(u32, u32)> { - if cfg!(CONFIG_UCLAMP_TASK) - && self.detector.wanted(Self::now()) - && self.applied.load(Ordering::Relaxed) + if !cfg!(CONFIG_UCLAMP_TASK) { + return None; + } + let now = Self::now(); + if (self.detector.wanted(now) && self.applied.load(Ordering::Relaxed)) + || self.detector.bound(now) { Some((WAIT_UTIL_MIN, WAIT_HINT_MS)) } else { @@ -595,9 +603,34 @@ mod detector_tests { let now = run(&detector, 16, CLOCK_HZ / 500, CLOCK_HZ / 25_000); assert!(detector.bound(now)); assert!(!detector.wanted(now)); + // Still bound across an 8-16 ms pass, then expires at the 20 ms linger boundary. + assert!(detector.bound(now + 15_000_000)); assert!(!detector.bound(now + LINGER_NS)); } + #[test] + fn gpu_bound_long_pass_lingers_for_full_frame() { + let detector = Detector::new(); + // 8 ms GPU passes with 1.7 ms host gaps stay GPU-bound without requesting a CPU floor, + // and linger across a 16 ms frame until the 20 ms boundary. + let busy = CLOCK_HZ / 125; + let gap = CLOCK_HZ * 17 / 10_000; + let step_ns = 9_700_000; + let mut start = 1000; + let mut now = 1_000_000; + for _ in 0..16 { + detector.note(start, start + busy, now); + start += busy + gap; + now += step_ns; + } + let last = now - step_ns; + assert!(detector.bound(last)); + assert!(!detector.wanted(last)); + assert!(detector.bound(last + 16_000_000)); + assert!(detector.bound(last + LINGER_NS - 1)); + assert!(!detector.bound(last + LINGER_NS)); + } + #[test] fn refill_gaps_stream_instead() { let detector = Detector::new(); @@ -613,6 +646,10 @@ mod detector_tests { // Each pass starts after a pause of at least the refill limit. let now = run(&detector, 16, CLOCK_HZ / 500, MAX_REFILL_TICKS); assert!(!detector.bound(now) && !detector.wanted(now)); + // 60 Hz paced frames (16.6 ms gap) keep resetting the streak. + let detector = Detector::new(); + let now = run(&detector, 16, CLOCK_HZ / 500, CLOCK_HZ * 166 / 10_000); + assert!(!detector.bound(now) && !detector.wanted(now)); // Fewer back-to-back passes than the streak needs. let detector = Detector::new(); let now = run(&detector, u64::from(STREAK_ON) - 1, CLOCK_HZ / 500, 0); diff --git a/drivers/gpu/drm/asahi/g17/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index df98a3410a50de..f31cd4164f05e9 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -63,8 +63,11 @@ pub(crate) fn allocation_failure(contexts: &FenceContexts) -> Result { pub(crate) struct ExportFence { source: Option>, scoped: bool, + compute_only: bool, /// A waiter enabled signalling on this ioctl output fence before it signalled ([`waiters`]). waited: AtomicBool, + /// A host waiter enabled signalling on this unscoped pure-compute output fence. + compute_waited: AtomicBool, } static EXPORT_OPS: AtomicUsize = AtomicUsize::new(0); @@ -72,6 +75,10 @@ static EXPORT_OPS: AtomicUsize = AtomicUsize::new(0); static WAITERS: AtomicU32 = AtomicU32::new(0); /// Waits begun on output fences, ever. static WAITS: AtomicU64 = AtomicU64::new(0); +/// Pure-compute output fences a host waiter is blocked on now. +static COMPUTE_WAITERS: AtomicU32 = AtomicU32::new(0); +/// Host waits begun on pure-compute output fences, ever. +static COMPUTE_WAITS: AtomicU64 = AtomicU64::new(0); /// The output fences a waiter is blocked on now, and the waits begun so far: the work a host /// thread waits for, which the M5 performance effort follows ([`super::power::Effort`]). @@ -79,6 +86,31 @@ pub(crate) fn waiters() -> (u32, u64) { (WAITERS.load(Ordering::Acquire), WAITS.load(Ordering::Acquire)) } +/// Pure-compute output fences a host thread is blocked on now, and total waits begun. +/// Scoped cumulative outputs count waits on their exported scope (excluding internal scope +/// chaining); unscoped outputs count waits directly on `ExportFence`. +pub(crate) fn compute_waiters() -> (u32, u64) { + ( + COMPUTE_WAITERS.load(Ordering::Acquire), + COMPUTE_WAITS.load(Ordering::Acquire), + ) +} + +/// Called from fence `enable_signaling` (atomic, under `dma_fence->lock` with IRQs off) when a +/// host thread begins waiting on a pure-compute output fence. +#[no_mangle] +pub(super) extern "C" fn asahi_g17_note_compute_waiter() { + COMPUTE_WAITERS.fetch_add(1, Ordering::AcqRel); + COMPUTE_WAITS.fetch_add(1, Ordering::AcqRel); + super::wake_for_compute_waiter(); +} + +/// Called once a previously waited pure-compute output fence signals or is released. +#[no_mangle] +pub(super) extern "C" fn asahi_g17_unnote_compute_waiter() { + COMPUTE_WAITERS.fetch_sub(1, Ordering::AcqRel); +} + /// The first waiter on an unsignalled output fence (the fence core calls this once, under the /// fence's lock). fn waited(flag: &AtomicBool) { @@ -95,9 +127,22 @@ fn unwaited(flag: &AtomicBool) { } } +fn compute_waited(flag: &AtomicBool) { + if !flag.swap(true, Ordering::AcqRel) { + asahi_g17_note_compute_waiter(); + } +} + +fn compute_unwaited(flag: &AtomicBool) { + if flag.swap(false, Ordering::AcqRel) { + asahi_g17_unnote_compute_waiter(); + } +} + impl Drop for ExportFence { fn drop(&mut self) { unwaited(&self.waited); + compute_unwaited(&self.compute_waited); } } @@ -111,6 +156,9 @@ impl FenceOps for ExportFence { } fn enable_signaling(self: &FenceObject) -> bool { waited(&self.waited); + if self.compute_only && !self.scoped { + compute_waited(&self.compute_waited); + } true } } @@ -122,7 +170,9 @@ fn export_fallback(contexts: &FenceContexts) -> Result> ExportFence { source: None, scoped: false, + compute_only: false, waited: AtomicBool::new(false), + compute_waited: AtomicBool::new(false), }, )?; // SAFETY: Unique, initialized and still private. Only this constructor @@ -172,9 +222,20 @@ pub(super) unsafe fn exported_source_raw(raw: *mut bindings::dma_fence) -> Optio .cloned() } +/// Immutable cross-QID kick metadata published once a compute source is committed in firmware. +/// Consumers on the same VM read this without acquiring the global device mutex. +#[derive(Clone)] +pub(crate) struct PublishedSource { + pub(crate) epoch: u64, + pub(crate) published: u64, + pub(crate) dependency: super::fw::kick::KickDependency, + pub(crate) readers: Arc, +} + struct State { work: Option>, ready: Option, + published: Option, } // One Member per parsed command, plus the enqueue guard. Exported references @@ -186,6 +247,8 @@ kernel::static_assert!(crate::file::MAX_COMMANDS_PER_SUBMISSION < u8::MAX as u32 pub(crate) struct Submission { #[pin] state: Mutex, + /// Immutable VM status of this submission, stored outside `state` so `same_vm()` is lock-free. + vm_status: Option>, remaining: AtomicU8, error: AtomicI32, /// Live Member objects, plus the enqueue guard, independently of signalling. @@ -195,22 +258,38 @@ pub(crate) struct Submission { /// is queued, before its fence is signalled off-lock: a consumer published /// in between needs no wait on it. retired: AtomicBool, + /// Non-zero encoded recovery epoch (`epoch.wrapping_add(1)`) while `state.published` holds a + /// live `PublishedSource` snapshot, or `0` when unpublished. + published_epoch: AtomicU64, + /// Set atomically when a firmware kick depends on this source so replay/retirement + /// observes consumers without scanning producer queues under the device mutex. + firmware_consumer: AtomicBool, } impl Submission { + fn encode_epoch(epoch: u64) -> u64 { + epoch.wrapping_add(1) + } fn new(context: Arc, firmware_source: bool) -> Result> { let work = Arc::new(WorkStateLease::deferred(context)?, GFP_KERNEL)?; Self::with_work(Some(work), firmware_source) } fn with_work(work: Option>, firmware_source: bool) -> Result> { + let vm_status = work.as_ref().map(|work| work.status().clone()); Arc::pin_init( pin_init!(Self { - state <- new_mutex!(State { work, ready: None }, "G17 submission work state"), + state <- new_mutex!( + State { work, ready: None, published: None }, + "G17 submission work state" + ), + vm_status, remaining: AtomicU8::new(1), error: AtomicI32::new(0), owners: AtomicU8::new(1), firmware_source, retired: AtomicBool::new(false), + published_epoch: AtomicU64::new(0), + firmware_consumer: AtomicBool::new(false), }), GFP_KERNEL, ) @@ -225,15 +304,55 @@ impl Submission { Ok(complete) } pub(super) fn same_vm(&self, status: &Arc) -> bool { - self.state - .lock() - .work + self.vm_status .as_ref() - .is_some_and(|work| Arc::ptr_eq(work.status(), status)) + .is_some_and(|vm| Arc::ptr_eq(vm, status)) } pub(super) fn ready(&self) -> Option { self.state.lock().ready.clone() } + pub(super) fn set_published(&self, source: PublishedSource) { + if !self.firmware_source { + return; + } + let tag = Self::encode_epoch(source.epoch); + let mut state = self.state.lock(); + if state.work.is_some() + && self.error.load(Ordering::Acquire) == 0 + && !self.retired.load(Ordering::Acquire) + { + state.published = Some(source); + self.published_epoch.store(tag, Ordering::Release); + } + } + pub(super) fn clear_published(&self) { + if self.published_epoch.swap(0, Ordering::AcqRel) == 0 { + return; + } + let old = self.state.lock().published.take(); + drop(old); + } + pub(super) fn published_source(&self, epoch: u64) -> Option { + if !self.has_published_epoch(epoch) { + return None; + } + let state = self.state.lock(); + state + .published + .as_ref() + .filter(|source| source.epoch == epoch) + .cloned() + } + pub(super) fn has_published_epoch(&self, epoch: u64) -> bool { + let tag = Self::encode_epoch(epoch); + self.firmware_source && tag != 0 && self.published_epoch.load(Ordering::Acquire) == tag + } + pub(super) fn note_firmware_consumer(&self) { + self.firmware_consumer.store(true, Ordering::Release); + } + pub(super) fn has_firmware_consumer(&self) -> bool { + self.firmware_consumer.load(Ordering::Acquire) + } fn set_ready(&self, ready: Fence) { if !self.firmware_source { return; @@ -244,14 +363,16 @@ impl Submission { } } fn note_error(&self, error: Error) -> bool { + self.clear_published(); self.error .compare_exchange(0, error.to_errno(), Ordering::AcqRel, Ordering::Acquire) .is_ok() } fn release_state(&self) { + self.published_epoch.store(0, Ordering::Release); let old = { let mut state = self.state.lock(); - (state.work.take(), state.ready.take()) + (state.work.take(), state.ready.take(), state.published.take()) }; drop(old); } @@ -280,6 +401,7 @@ impl Submission { fence.signal(); } unwaited(&fence.waited); + compute_unwaited(&fence.compute_waited); } } } @@ -314,6 +436,15 @@ impl Aggregate { self.source().member_done(&self.0, result); self.source().owner_done(); } + #[cfg(CONFIG_KUNIT = "y")] + pub(super) fn test_member(contexts: &FenceContexts) -> Result { + let mut fence = export_fallback(contexts)?; + fence.source = Some(Submission::with_work(None, false)?); + let aggregate = Self(fence.into()); + let member = aggregate.member(); + aggregate.finish_enqueue(Ok(())); + Ok(member) + } } pub(crate) struct Member { @@ -346,8 +477,18 @@ impl Member { let source = self.aggregate.source(); if source.firmware_source { source.retired.store(true, Ordering::Release); + source.clear_published(); } } + pub(super) fn note_published(&self, published: PublishedSource) { + self.aggregate.source().set_published(published); + } + pub(super) fn clear_published(&self) { + self.aggregate.source().clear_published(); + } + pub(super) fn has_firmware_consumer(&self) -> bool { + self.aggregate.source().has_firmware_consumer() + } pub(crate) fn complete(&self, result: Result) { if !self.complete.swap(true, Ordering::AcqRel) { self.aggregate @@ -466,7 +607,7 @@ fn install(outputs: impl Iterator, fence: &Fence) { pub(crate) struct Outputs { fallback: Option>, - syncs: KVec, + syncs: KVVec, input_count: usize, submission: Option, result: Result, @@ -475,7 +616,7 @@ pub(crate) struct Outputs { impl Outputs { pub(crate) fn new( contexts: &FenceContexts, - mut syncs: KVec, + mut syncs: KVVec, input_count: usize, allocation_failure: &Fence, ) -> Result { @@ -517,15 +658,17 @@ impl Outputs { &mut self, context: Arc, firmware_source: bool, + compute_only: bool, ) -> Result { let source = Submission::new(context, firmware_source)?; let mut fence = self.fallback.take().ok_or(EINVAL)?; fence.source = Some(source); fence.scoped = self.cumulative.is_some(); + fence.compute_only = compute_only; let submission = Aggregate(fence.into()); self.submission = Some(submission.clone()); if let Some(bundle) = &mut self.cumulative { - bundle.publish(&submission.fence())?; + bundle.publish(&submission.fence(), compute_only)?; self.syncs.truncate(self.input_count); } else { install(self.syncs.drain(self.input_count..), &submission.fence()); @@ -564,6 +707,7 @@ impl Drop for Outputs { ); fallback.signal(); unwaited(&fallback.waited); + compute_unwaited(&fallback.compute_waited); } } } diff --git a/drivers/gpu/drm/asahi/g17/freelist.rs b/drivers/gpu/drm/asahi/g17/freelist.rs index ff8592f2f9b18c..017f6d03b2013c 100644 --- a/drivers/gpu/drm/asahi/g17/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/freelist.rs @@ -78,10 +78,6 @@ impl RenderIds { }), GFP_KERNEL) } - pub(crate) fn availability(&self) -> &Arc { - &self.available - } - fn pin(self: &Arc, cell: &Arc, assigned: impl FnOnce()) -> Result { let mut state = self.state.lock(); let slot = cell.slot.load(Ordering::Acquire); @@ -1116,9 +1112,6 @@ impl ComputePool { pub(crate) fn descriptor(&self) -> Result { self.pages.as_ref().ok_or(EAGAIN)?.descriptor(self.id) } - pub(crate) fn completed_submissions(&self) -> Result { - Ok(u64::from_le_bytes(self.completed_bytes()?)) - } fn completed_bytes(&self) -> Result<[u8; 8]> { let offset = if self.m5 { super::fw::m5::pool::completed_offset() } else { FreeListControl::COMPLETED }; let pointer = self.control.pointer(offset, 8)?; @@ -1233,7 +1226,9 @@ pub(crate) struct Owner { #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum LeasePhase { - Preparing, + /// Active and/or preparing. `references == commands + preparing` with + /// `commands >= 2 * preparing`. When `references == 0`, `published` is + /// true and a final `FreeListRelease` is pending. Ready, /// No reference since the given time. The registration stays live so that /// the owner's next render reuses it without a control-ring release; the @@ -1256,6 +1251,8 @@ pub(crate) struct Lease { generation: u64, references: u32, commands: u32, + preparing: u32, + published: bool, phase: LeasePhase, previous_release: Option, } @@ -1271,7 +1268,9 @@ impl Lease { generation: 0, references: 3, commands: 2, - phase: LeasePhase::Preparing, + preparing: 1, + published: false, + phase: LeasePhase::Ready, previous_release: None, }); }; @@ -1294,6 +1293,7 @@ impl Lease { } let references = previous.references.checked_add(3).ok_or(EOVERFLOW)?; let commands = previous.commands.checked_add(2).ok_or(EOVERFLOW)?; + let preparing = previous.preparing.checked_add(1).ok_or(EOVERFLOW)?; Ok(Self { owner, generation: if overlapping { @@ -1303,7 +1303,9 @@ impl Lease { }, references, commands, - phase: LeasePhase::Preparing, + preparing, + published: overlapping && previous.published, + phase: LeasePhase::Ready, previous_release: previous.release_witness(), }) } @@ -1320,9 +1322,14 @@ impl Lease { LeasePhase::ReleaseSent(_) | LeasePhase::Released ) && self.references == 0 && self.commands == 0 + && self.preparing == 0 } pub(crate) fn released(&self) -> bool { - self.phase == LeasePhase::Released && self.previous_release.is_none() + self.phase == LeasePhase::Released + && self.previous_release.is_none() + && self.references == 0 + && self.commands == 0 + && self.preparing == 0 } pub(crate) fn release_witness(&self) -> Option { match self.phase { @@ -1333,13 +1340,47 @@ impl Lease { /// Publication retires preparation independently of the command references. pub(crate) fn retire_prepare(&mut self) -> Result { - if self.phase != LeasePhase::Preparing || self.references < 3 { + let reserved_refs = self.preparing.checked_mul(3).ok_or(EINVAL)?; + let reserved_cmds = self.preparing.checked_mul(2).ok_or(EINVAL)?; + if self.phase != LeasePhase::Ready + || self.preparing == 0 + || self.references < reserved_refs + || self.commands < reserved_cmds + { return Err(EINVAL); } + self.preparing -= 1; self.references -= 1; - self.phase = LeasePhase::Ready; + self.published = true; Ok(()) } + /// Rolls back one unpublished `acquire()` without disturbing sibling + /// completions or observed release witnesses that occurred meanwhile. + /// If the rolled-back preparation held the last reference on an already + /// published generation, its final release becomes pending. + pub(crate) fn cancel_prepare( + &mut self, + ) -> Result> { + let reserved_refs = self.preparing.checked_mul(3).ok_or(EINVAL)?; + let reserved_cmds = self.preparing.checked_mul(2).ok_or(EINVAL)?; + if self.phase != LeasePhase::Ready + || self.preparing == 0 + || self.references < reserved_refs + || self.commands < reserved_cmds + { + return Err(EINVAL); + } + self.preparing -= 1; + self.references -= 3; + self.commands -= 2; + if self.references == 0 && !self.published { + self.phase = match self.previous_release.take() { + Some(cursor) => LeasePhase::ReleaseSent(cursor), + None => LeasePhase::Released, + }; + } + Ok(self.pending_release()) + } /// Fixed prepopulated pools never submit an asynchronous growth request. /// An incoming growth completion therefore cannot name a live request. pub(crate) fn complete_grow( @@ -1355,7 +1396,13 @@ impl Lease { &mut self, linger: bool, ) -> Result> { - if self.phase != LeasePhase::Ready || self.references < 2 || self.commands < 2 { + let reserved_refs = self.preparing.checked_mul(3).ok_or(EINVAL)?; + let reserved_cmds = self.preparing.checked_mul(2).ok_or(EINVAL)?; + if self.phase != LeasePhase::Ready + || !self.published + || self.references < reserved_refs.saturating_add(2) + || self.commands < reserved_cmds.saturating_add(2) + { return Err(EINVAL); } self.references -= 2; @@ -1379,7 +1426,7 @@ impl Lease { } } pub(crate) fn pending_release(&self) -> Option { - (self.phase == LeasePhase::Ready && self.references == 0).then(|| { + (self.phase == LeasePhase::Ready && self.references == 0 && self.published).then(|| { super::fw::channels::FreeListRelease::new(self.generation, self.owner.buffer_slot) }) } @@ -1391,10 +1438,6 @@ impl Lease { self.phase = LeasePhase::ReleaseSent(cursor); Ok(()) } - /// Only sent releases and inherited release witnesses consume cursors. - pub(crate) fn needs_release_observation(&self) -> bool { - self.previous_release.is_some() || matches!(self.phase, LeasePhase::ReleaseSent(_)) - } /// Observes all older release records passed by one consumer snapshot. /// A sent release whose consumption [`Self::observe_releases`] has yet to witness. @@ -1454,4 +1497,81 @@ mod capacity_tests { assert_eq!(ids.used(), 0); } } + + fn owner(slot: u32, serial: u64) -> Owner { + Owner { + serial, + epoch: 1, + buffer_slot: slot, + control_va: 0x1000, + ring_va: 0x2000, + cookie: 0x3000, + } + } + + #[test] + fn sibling_render_completes_while_direct_prepare_is_lent() { + let owner = owner(129, 1); + let mut lease = Lease::acquire(None, owner).unwrap(); + // An unactivated preparation cannot complete as a render. + assert!(matches!(lease.complete_render(false), Err(EINVAL))); + lease.retire_prepare().unwrap(); + + // Sibling pair lends the same pool off-lock. + lease = Lease::acquire(Some(&lease), owner).unwrap(); + assert_eq!(lease.generation(), 0); + // Active sibling completes while the direct preparation is still lent. + assert!(lease.complete_render(false).unwrap().is_none()); + // No other published render remains until the lent preparation activates. + assert!(matches!(lease.complete_render(false), Err(EINVAL))); + + lease.retire_prepare().unwrap(); + let release = lease.complete_render(false).unwrap(); + assert!(release.is_some()); + assert!(lease.pending_release().is_some()); + } + + #[test] + fn rollback_after_sibling_completion_exposes_pending_release() { + let owner = owner(129, 1); + let mut lease = Lease::acquire(None, owner).unwrap(); + lease.retire_prepare().unwrap(); + + // Sibling prepares off-lock, active sibling retires, then preparation rolls back. + lease = Lease::acquire(Some(&lease), owner).unwrap(); + assert!(lease.complete_render(false).unwrap().is_none()); + let release = lease.cancel_prepare().unwrap(); + assert!(release.is_some()); + assert!(lease.pending_release().is_some()); + lease.mark_release_sent(4).unwrap(); + assert!(lease.reacquirable()); + } + + #[test] + fn rollback_of_unpublished_generation_preserves_release_witness() { + let owner = owner(129, 1); + let mut lease = Lease::acquire(None, owner).unwrap(); + assert!(lease.cancel_prepare().unwrap().is_none()); + assert!(lease.released()); + assert!(lease.pending_release().is_none()); + + // Publish and send release at cursor 5, then reacquire and observe consumption + // before rolling back the unpublished successor. + lease = Lease::acquire(Some(&lease), owner).unwrap(); + lease.retire_prepare().unwrap(); + assert!(lease.complete_render(false).unwrap().is_some()); + lease.mark_release_sent(5).unwrap(); + + let mut unconsumed = Lease::acquire(Some(&lease), owner).unwrap(); + assert!(unconsumed.cancel_prepare().unwrap().is_none()); + assert!(unconsumed.reacquirable()); + assert!(!unconsumed.released()); + assert_eq!(unconsumed.release_witness(), Some(5)); + + let mut consumed = Lease::acquire(Some(&lease), owner).unwrap(); + consumed.observe_releases(6, 6).unwrap(); + assert!(consumed.cancel_prepare().unwrap().is_none()); + assert!(consumed.released()); + assert_eq!(consumed.release_witness(), None); + } } diff --git a/drivers/gpu/drm/asahi/g17/fw/buffer.rs b/drivers/gpu/drm/asahi/g17/fw/buffer.rs index 9d430d50db365e..c6f9ef0819f756 100644 --- a/drivers/gpu/drm/asahi/g17/fw/buffer.rs +++ b/drivers/gpu/drm/asahi/g17/fw/buffer.rs @@ -22,6 +22,8 @@ pub(crate) const SIZE: usize = 0x48000; pub(crate) const METRICS_STRIDE: usize = SCENES * size_of::(); pub(crate) const METRICS_SLOTS: usize = cfg::METRICS_SIZE as usize / METRICS_STRIDE; pub(crate) const NORMAL_MAX_BLOCKS: usize = 0x45e; +/// The normal maximum of a four-cluster G17P heap: every slot of the block table. +pub(crate) const NORMAL_MAX_BLOCKS_FOUR_CLUSTERS: usize = cfg::TVB_MAX_BLOCKS; pub(crate) const GROW_BLOCKS: usize = 10; /// Firmware's active parameter-buffer state. Pointers at +0x44, +0x4c, @@ -136,6 +138,8 @@ pub(crate) struct GraphArgs<'a> { pub(crate) discard: u64, pub(crate) buffer_id: u32, pub(crate) generation: u64, + /// The heap's normal maximum in blocks (`Variant::tvb_normal_blocks`). + pub(crate) normal_blocks: usize, } pub(crate) fn compact_page(address: u64) -> Result { @@ -197,7 +201,7 @@ impl Graph { self.state.block_size = cfg::TVB_BLOCK_SIZE as u32; self.state.counter = offset_va(args.fw_va, COUNTER as u64)?; self.state.maximum_size = (cfg::TVB_BLOCK_SLOTS * 4) as u32; - self.state.normal_maximum_size = (NORMAL_MAX_BLOCKS * 4) as u32; + self.state.normal_maximum_size = (args.normal_blocks * 4) as u32; self.state.discard = discard; Ok(()) } diff --git a/drivers/gpu/drm/asahi/g17/fw/freelist.rs b/drivers/gpu/drm/asahi/g17/fw/freelist.rs index 56c1f2324e2a17..fe5981b439666a 100644 --- a/drivers/gpu/drm/asahi/g17/fw/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/fw/freelist.rs @@ -10,6 +10,12 @@ pub(crate) const RUN_LIST_SIZE: usize = 0x1_0000; pub(crate) const TABLE_SIZE: usize = PAGE_LIST_SIZE + RUN_LIST_SIZE; pub(crate) const CONTROL_SIZE: usize = 0x4000; pub(crate) const RENDER_BLOCKS: usize = 44; +/// Minimum render pool per active USC core (in 1 MiB blocks) on GPUs with more +/// than two clusters. With clustered tiling running vertex work across all +/// clusters concurrently with fragment work, 44 blocks run out under Vulkan +/// vertex load (reason-0 no-progress recoveries); three blocks per enabled core +/// yield 96 blocks on 32-core T6041 and scale linearly on larger parts. +pub(crate) const MULTI_CLUSTER_RENDER_BLOCKS_PER_CORE: usize = 3; pub(crate) const COMPUTE_BLOCKS: usize = 21; /// Render reserves eight run words per block; compute packs runs consecutively. diff --git a/drivers/gpu/drm/asahi/g17/fw/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/initdata.rs index a70b5763eac4d2..9c827c6d8c1885 100644 --- a/drivers/gpu/drm/asahi/g17/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/initdata.rs @@ -652,6 +652,7 @@ impl RegisterWindow { const RESERVED_SLOT_UNK_20: u32 = 2; /// One register-map slot of the hardware data. +#[derive(Debug)] #[repr(C)] pub(crate) struct RegisterMapEntry { /// Physical address of the window. diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/compute.rs b/drivers/gpu/drm/asahi/g17/fw/m5/compute.rs index a2d7205dfe9afe..fd326e708f2dda 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/compute.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/compute.rs @@ -48,10 +48,9 @@ pub(crate) fn explicit_dependency(board: &Board) -> u8 { /// Dependency class of a compute kick's implicit parent (the previous kick of its queue) on /// `board`. With the counted forms ([`counted_forms`]) it is class 1, which holds the kick until /// its parent has completed. On boards whose explicit waits take the completion class -/// ([`Board::completion_inputs`]) a parent the host has already retired (`parent_retired`) takes -/// the pipelined class instead, as macOS's late-published M5 Pro kicks do: there is nothing left -/// to hold for. Otherwise it is the pipelined class, with which a kick may start while its parent -/// still runs. +/// ([`Board::completion_inputs`]), a parent the host has already retired (`parent_retired`) takes +/// the pipelined class instead: there is nothing left on that physical QID to hold for. +/// Otherwise it is the pipelined class, with which a kick may start while its parent still runs. pub(crate) fn parent_dependency(board: &Board, parent_retired: bool) -> u8 { if !counted_forms(board) || (parent_retired && board.completion_inputs()) { COMPUTE_PIPELINED_DEPENDENCY @@ -60,6 +59,16 @@ pub(crate) fn parent_dependency(board: &Board, parent_retired: bool) -> u8 { } } +/// Whether `board` spreads a logical compute queue across multiple physical compute channels +/// ([`Board::compute_channels`]) sharing one context, QoS slot, scheduler page, and work-state +/// table, each with its own dedicated compute pool. Each physical QID still holds a +/// completion-class implicit parent while its own prior kick is active, preventing two kicks +/// from overlapping on one QID's single preemption/operand/usage state; concurrency comes +/// strictly from independent kicks running across distinct sibling QIDs. +pub(crate) fn multi_channel(board: &Board) -> bool { + board.compute_channels() > 1 +} + /// Whether compute kicks on `board` count their completion ordinal and hold for their parent: /// with the G17D forms, on boards whose explicit waits take the completion class /// ([`Board::completion_inputs`]), as macOS encodes M5 Pro compute, and on the J813, whose @@ -465,6 +474,8 @@ pub(crate) struct DescriptorArgs { pub(crate) stamp_va: [u64; 2], pub(crate) stamp_value: u32, pub(crate) qid: u32, + /// Per-context compute channel index (0, 1, 2 for a multi-channel owner; 0 otherwise). + pub(crate) channel_index: u32, pub(crate) kick_timestamp: u64, pub(crate) completion_ordinal: u32, pub(crate) status_va: [u64; 2], @@ -503,7 +514,8 @@ pub(crate) struct Descriptor { stamp_va: [u64; 2], stamp_value: u32, qid: u32, - reserved_f58: u64, + channel_index: u32, + reserved_f5c: u32, kick_timestamp: u64, current_id: u64, completion_ordinal: u32, @@ -574,6 +586,7 @@ impl Descriptor { self.stamp_va = args.stamp_va; self.stamp_value = args.stamp_value; self.qid = args.qid; + self.channel_index = args.channel_index; self.kick_timestamp = args.kick_timestamp; self.current_id = args.registers.object_ids as u32 as u64; self.completion_ordinal = args.completion_ordinal; diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs index ded8c30ac41fda..4f1de0142ba178 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs @@ -9,6 +9,7 @@ use core::ops::Range; use core::result::Result; +use crate::g17::fw::variant::M5Layouts; use crate::g17::fw::kick::{KickTimestamp, KICK_SLOTS}; pub(crate) const ROOT_SIZE_PRIMARY: usize = 0x0b8; @@ -37,6 +38,10 @@ pub(crate) enum RootProfile { J714G17S26A428, + /// The M5 graph of the macOS 27.2 firmware (26B123): the 26A428 graph with a larger power + /// policy and status config ([`ABI_ALLOCATION_SIZES_26B123_M5`]). + J714G17S26B123, + /// The common interface of macOS 27.2 (26B123, RTKit 3514.41.1): the /// [`Self::J873G18G26A428`] graph with a longer policy and status config /// ([`COMMON26B123_LAYOUTS`]). The J813's G17G build runs it as the J873's G18G one does. @@ -44,6 +49,27 @@ pub(crate) enum RootProfile { } impl RootProfile { + /// The M5 graph profile of a firmware build's InitData layouts. + pub(crate) const fn for_m5_layouts(layouts: super::super::variant::M5Layouts) -> Self { + use super::super::variant::M5Layouts; + match layouts { + M5Layouts::V26A428 => Self::J714G17S26A428, + M5Layouts::V26B123 => Self::J714G17S26B123, + } + } + + /// The layout of an M5 graph profile, `None` for the others. + pub(crate) const fn m5_layout(self) -> Option<&'static M5Layout> { + match self { + Self::J714G17S26A428 => Some(&M5_LAYOUT_26A428), + Self::J714G17S26B123 => Some(&M5_LAYOUT_26B123), + Self::J700G17P + | Self::J813G17G25G76 + | Self::J873G18G26A428 + | Self::J873G18G26B123 => None, + } + } + pub(crate) const fn version_word(self) -> u64 { match self { Self::J700G17P => INITDATA_VERSION_WORD, @@ -51,6 +77,7 @@ impl RootProfile { Self::J873G18G26A428 => COMMON26_INITDATA_VERSION_WORD, Self::J873G18G26B123 => COMMON26B123_INITDATA_VERSION_WORD, Self::J714G17S26A428 => M5_INITDATA_VERSION_WORD, + Self::J714G17S26B123 => M5_26B123_INITDATA_VERSION_WORD, } } @@ -64,14 +91,17 @@ impl RootProfile { match self { Self::J873G18G26A428 => Some(&COMMON26_LAYOUTS), Self::J873G18G26B123 => Some(&COMMON26B123_LAYOUTS), - Self::J700G17P | Self::J813G17G25G76 | Self::J714G17S26A428 => None, + Self::J700G17P + | Self::J813G17G25G76 + | Self::J714G17S26A428 + | Self::J714G17S26B123 => None, } } pub(crate) const fn root_size(self, role: InstanceRole) -> usize { match self { Self::J873G18G26A428 | Self::J873G18G26B123 => COMMON26_ROOT_SIZE, - Self::J714G17S26A428 => M5_ROOT_SIZE, + Self::J714G17S26A428 | Self::J714G17S26B123 => M5_ROOT_SIZE, Self::J700G17P | Self::J813G17G25G76 => root_size(role), } } @@ -84,8 +114,10 @@ impl RootProfile { (Self::J873G18G26A428 | Self::J873G18G26B123, InstanceRole::Secondary) => { COMMON26_CONTROL_OPENING_OPCODE_SECONDARY } - (Self::J714G17S26A428, InstanceRole::Primary) => M5_CONTROL_OPENING_OPCODE_PRIMARY, - (Self::J714G17S26A428, InstanceRole::Secondary) => { + (Self::J714G17S26A428 | Self::J714G17S26B123, InstanceRole::Primary) => { + M5_CONTROL_OPENING_OPCODE_PRIMARY + } + (Self::J714G17S26A428 | Self::J714G17S26B123, InstanceRole::Secondary) => { M5_CONTROL_OPENING_OPCODE_SECONDARY } (_, InstanceRole::Primary) => CONTROL_OPENING_OPCODE_PRIMARY, @@ -95,26 +127,33 @@ impl RootProfile { pub(crate) const fn control_register_opcode(self) -> Option { match self { - Self::J873G18G26A428 | Self::J873G18G26B123 | Self::J714G17S26A428 => None, + Self::J873G18G26A428 + | Self::J873G18G26B123 + | Self::J714G17S26A428 + | Self::J714G17S26B123 => None, Self::J700G17P | Self::J813G17G25G76 => Some(CONTROL_OPENING_PRIMARY_REGISTER_OPCODE), } } pub(crate) const fn bundle_view_offsets(self) -> [usize; 5] { + if let Some(layout) = self.m5_layout() { + return layout.bundle_view_offsets(); + } match self { Self::J873G18G26A428 => COMMON26_BUNDLE_VIEW_OFFSETS, Self::J873G18G26B123 => COMMON26B123_BUNDLE_VIEW_OFFSETS, - Self::J714G17S26A428 => M5_BUNDLE_VIEW_OFFSETS, - Self::J700G17P | Self::J813G17G25G76 => BUNDLE_VIEW_OFFSETS, + _ => BUNDLE_VIEW_OFFSETS, } } pub(crate) const fn bundle_view_extents(self) -> [usize; 5] { + if let Some(layout) = self.m5_layout() { + return layout.bundle_view_extents(); + } match self { // 26B123 grows only the policy and the status config; the five views keep their sizes. Self::J873G18G26A428 | Self::J873G18G26B123 => COMMON26_BUNDLE_VIEW_EXTENTS, - Self::J714G17S26A428 => M5_BUNDLE_VIEW_EXTENTS, - Self::J700G17P | Self::J813G17G25G76 => BUNDLE_VIEW_EXTENTS, + _ => BUNDLE_VIEW_EXTENTS, } } @@ -122,25 +161,43 @@ impl RootProfile { pub(crate) const fn region_view_low_addrs(self) -> [u64; 2] { match self { Self::J873G18G26A428 | Self::J873G18G26B123 => COMMON26_REGION_VIEW_LOW_ADDRS, - Self::J714G17S26A428 | Self::J700G17P | Self::J813G17G25G76 => REGION_VIEW_LOW_ADDRS, + Self::J714G17S26A428 | Self::J714G17S26B123 | Self::J700G17P | Self::J813G17G25G76 => { + REGION_VIEW_LOW_ADDRS + } } } pub(crate) const fn repeated_region_bundle_offset(self) -> usize { + if let Some(layout) = self.m5_layout() { + return layout.shared.block_88; + } match self { Self::J873G18G26A428 => COMMON26_SHARED_LAYOUT.block_88, Self::J873G18G26B123 => COMMON26B123_SHARED_LAYOUT.block_88, - Self::J714G17S26A428 => M5_SHARED_LAYOUT.block_88, - Self::J700G17P | Self::J813G17G25G76 => MAIN_REPEATED_REGION_BUNDLE_OFFSET, + _ => MAIN_REPEATED_REGION_BUNDLE_OFFSET, } } pub(crate) const fn work_ring_bundle_offsets(self) -> [usize; WORK_CHANNEL_COUNT] { + if let Some(layout) = self.m5_layout() { + return work_ring_offsets(&layout.shared); + } match self { Self::J873G18G26A428 => COMMON26_WORK_RING_BUNDLE_OFFSETS, Self::J873G18G26B123 => COMMON26B123_WORK_RING_BUNDLE_OFFSETS, - Self::J714G17S26A428 => M5_WORK_RING_BUNDLE_OFFSETS, - Self::J700G17P | Self::J813G17G25G76 => WORK_RING_BUNDLE_OFFSETS, + _ => WORK_RING_BUNDLE_OFFSETS, + } + } + + /// Status-config layout of the M5 graph built for this profile. + pub(crate) const fn m5_status_config(self) -> &'static M5StatusConfigMap { + match self { + Self::J714G17S26B123 => &M5_26B123_STATUS_CONFIG, + Self::J714G17S26A428 + | Self::J700G17P + | Self::J813G17G25G76 + | Self::J873G18G26A428 + | Self::J873G18G26B123 => &M5_26A428_STATUS_CONFIG, } } } @@ -884,7 +941,7 @@ pub(crate) fn encode_main_config_for_profile( put_u64(out, MAIN_REGION_VIEWS + 0x20, views.alias_high[1]); // J714's firmware takes both primary sentinels too; they are not // exclusive to the older J700 ABI. - if matches!(profile, RootProfile::J700G17P | RootProfile::J714G17S26A428) { + if profile == RootProfile::J700G17P || profile.m5_layout().is_some() { put_u32(out, MAIN_PRIMARY_SENTINEL_A, 1); put_u32(out, MAIN_PRIMARY_SENTINEL_B, 0xabcd_abcd); } @@ -900,13 +957,15 @@ pub(crate) fn encode_main_config_for_profile( RootProfile::J700G17P => MAIN_SECONDARY_KIND_VALUE, RootProfile::J813G17G25G76 => 0xc, - RootProfile::J873G18G26A428 | RootProfile::J873G18G26B123 - | RootProfile::J714G17S26A428 => COMMON26_MAIN_SECONDARY_KIND, + RootProfile::J873G18G26A428 + | RootProfile::J873G18G26B123 + | RootProfile::J714G17S26A428 + | RootProfile::J714G17S26B123 => COMMON26_MAIN_SECONDARY_KIND, }); - if profile == RootProfile::J714G17S26A428 { + if let Some(layout) = profile.m5_layout() { put_u64(out, COMMON26_MAIN_SECONDARY_POLICY_PTR, - bundle + M5_SHARED_LAYOUT.policy as u64); + bundle + layout.shared.policy as u64); } else if let Some(layouts) = profile.common26_layouts() { put_u64(out, COMMON26_MAIN_SECONDARY_POLICY_PTR, @@ -936,7 +995,7 @@ pub(crate) fn encode_region_c_for_profile( return encode_common26_region_c(out); } - if profile == RootProfile::J714G17S26A428 { + if profile.m5_layout().is_some() { return Err(InitdataError::BufferSize); } @@ -1454,6 +1513,36 @@ pub(crate) const COMMON26_STATUS_CONFIG_BANDS: &[LayoutBand] = &[ band(0x5cc, 0x628, 0x18, Evidence::ProducerChecked), ]; +/// Status config 26A428 -> 26B123 (macOS 27.2), in 26A428 offsets. The status config grows from 0x780 to 0x790 bytes (allocation size table entry 13). +/// +/// From +0x5b4 the object holds two controller blocks, at +0x5b4 and +0x610, of 0x5c bytes +/// each. 26B123 inserts two words into each block, an override slot at block +0x28 and its +/// value at block +0x58, so a block grows to 0x64 bytes and everything after the second one +/// moves by 0x10, the link word and pointer (0x774/0x778 -> 0x784/0x788) and the submission +/// history (0x73c/0x74c/0x750 -> 0x74c/0x75c/0x760) included. +/// +/// InitData captured from macOS 27.2 on a J716s shows the link pointer at 0x788 (the word at +/// 0x778, where 26A428 keeps it, is null) and the link word 1 at 0x784. The capture does not +/// separate a block of 0x64 bytes from one of 0x5c, so where inside the two blocks the 0x10 bytes +/// sit, and the history offsets that follow from the same shift, are not confirmed. +pub(crate) const M5_26B123_STATUS_CONFIG_BANDS: &[LayoutBand] = &[ + band(0x000, 0x5dc, 0, Evidence::Inferred), + band(0x5dc, 0x608, 0x4, Evidence::Inferred), + band(0x608, 0x638, 0x8, Evidence::Inferred), + band(0x638, 0x664, 0xc, Evidence::Inferred), + band(0x664, M5_STATUS_CONFIG_SIZE, 0x10, Evidence::Inferred), +]; + +/// Status-config size of 26B123 (entry 13 of its allocation size table). +pub(crate) const M5_26B123_STATUS_CONFIG_SIZE: usize = + ABI_ALLOCATION_SIZES_26B123_M5[ALLOC_STATUS_CONFIG]; + +/// The words 26B123 has and 26A428 does not, at 26B123 offsets: the override slot of each +/// controller block (0x5dc and 0x640, zero) and its value (0x60c = 5000 and 0x670 = 0), as read +/// from InitData captured from macOS 27.2 on a J716s. +pub(crate) const M5_26B123_STATUS_CONFIG_INSERTED: &[(usize, u32)] = + &[(0x5dc, 0), (0x60c, 5000), (0x640, 0), (0x670, 0)]; + fn write_relocated_words( words: &[(usize, u32)], source_base: usize, @@ -1696,6 +1785,10 @@ pub(crate) const M5_CONTROL_OPENING_OPCODE_SECONDARY: u32 = pub(crate) const M5_INITDATA_VERSION_WORD: u64 = 0x0c8e_0339_8728_04c0; +/// The interface version word, at root+0, of the 27.2 (26B123) M5 firmware: the 26A428 word with +/// bit 46 set. Both roots of InitData captured from macOS 27.2 on a J716s carry it. +pub(crate) const M5_26B123_INITDATA_VERSION_WORD: u64 = 0x0c8e_4339_8728_04c0; + pub(crate) const M5_ROOT_SIZE: usize = 0xc8; pub(crate) const ABI_ALLOCATION_SIZES_26A428_M5: [usize; 24] = [ @@ -1703,11 +1796,137 @@ pub(crate) const ABI_ALLOCATION_SIZES_26A428_M5: [usize; 24] = [ 0xe730, 0x0780, 0x0020, 0x01b0, 0x4800, 0x28800, 0x79800, 0x9000, 0x00a8, 0x0008, 0x1ca0, 0x00e4, ]; -pub(crate) const M5_SHARED_LAYOUT: SharedClusterLayout = - shared_cluster_layout(&ABI_ALLOCATION_SIZES_26A428_M5); +/// The allocation size table of the 27.2 (26B123) M5 firmware, indexed like +/// [`ABI_ALLOCATION_SIZES_26A428_M5`]. Only two entries differ from it: the power policy (index 4, +/// 0x126b0 -> 0x12728) and the status config (index 13, 0x780 -> 0x790). In InitData captured from +/// macOS 27.2 on a J716s, the spacing of all eight objects whose distance depends on these two +/// sizes matches this table and none matches 26A428's. +pub(crate) const ABI_ALLOCATION_SIZES_26B123_M5: [usize; 24] = [ + 0x2850, 0x0c18, 0x1048, 0x0e10, 0x12728, 0x0068, 0x0800, 0x0088, 0x1800, 0x04c0, 0x4000, + 0x0030, 0xe730, 0x0790, 0x0020, 0x01b0, 0x4800, 0x28800, 0x79800, 0x9000, 0x00a8, 0x0008, + 0x1ca0, 0x00e4, +]; + +const _: () = { + let mut index = 0; + while index < ABI_ALLOCATION_SIZES_26B123_M5.len() { + let same = ABI_ALLOCATION_SIZES_26B123_M5[index] == ABI_ALLOCATION_SIZES_26A428_M5[index]; + assert!(same == (index != ALLOC_POLICY && index != ALLOC_STATUS_CONFIG)); + index += 1; + } +}; + +/// The InitData layout of one M5 firmware build: its allocation size table and the packed +/// clusters derived from it. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5Layout { + /// The allocation size table. + pub(crate) sizes: [usize; 24], + /// The shared cluster (the HW data bundle). + pub(crate) shared: SharedClusterLayout, + /// The private cluster. + pub(crate) private: PrivateClusterLayout, +} + +impl M5Layout { + const fn new(sizes: [usize; 24]) -> Self { + Self { + sizes, + shared: shared_cluster_layout(&sizes), + private: private_cluster_layout(&sizes), + } + } + + pub(crate) const fn policy_size(&self) -> usize { + self.sizes[ALLOC_POLICY] + } + + pub(crate) const fn status_config_size(&self) -> usize { + self.sizes[ALLOC_STATUS_CONFIG] + } + + /// The bundle up to its BRN table: HW data, the four views and the power policy. + pub(crate) const fn shared_prefix_size(&self) -> usize { + self.shared.brn_table + } + + pub(crate) const fn bundle_view_offsets(&self) -> [usize; 5] { + [ + self.shared.block_c18, + self.shared.block_1048, + self.shared.block_e10, + self.shared.block_68, + self.shared.block_800, + ] + } + + pub(crate) const fn bundle_view_extents(&self) -> [usize; 5] { + [ + self.sizes[ALLOC_BLOCK_C18], + self.sizes[ALLOC_BLOCK_1048], + self.sizes[ALLOC_BLOCK_E10], + self.sizes[ALLOC_BLOCK_68], + self.sizes[ALLOC_BLOCK_800], + ] + } -pub(crate) const M5_PRIVATE_LAYOUT: PrivateClusterLayout = - private_cluster_layout(&ABI_ALLOCATION_SIZES_26A428_M5); + pub(crate) const fn private_status_a(&self) -> [usize; 2] { + [ + self.private.roles[0].status_a, + self.private.roles[1].status_a, + ] + } + + pub(crate) const fn private_state_grids(&self) -> [usize; 2] { + [ + self.private.dm_ring_states[0], + self.private.secondary_control_state - WORK_STATE_GRID_OFFSETS[CONTROL_CHANNEL_INDEX], + ] + } + + pub(crate) const fn status_config_in_status_b(&self) -> usize { + self.private.status_config - self.private.status_b + } + + pub(crate) const fn status_b_span(&self) -> usize { + self.private.roles[0].status_a - self.private.status_b + } +} + +/// The 27.0 (26A428) M5 layout. +pub(crate) const M5_LAYOUT_26A428: M5Layout = M5Layout::new(ABI_ALLOCATION_SIZES_26A428_M5); + +/// The 27.2 (26B123) M5 layout. +pub(crate) const M5_LAYOUT_26B123: M5Layout = M5Layout::new(ABI_ALLOCATION_SIZES_26B123_M5); + +const _: () = { + // The bundle and the private cluster keep the sizes of their fixed windows. + assert!(M5_LAYOUT_26B123.shared.total == M5_LAYOUT_26A428.shared.total); + assert!(M5_LAYOUT_26B123.private.total == M5_LAYOUT_26A428.private.total); +}; + +const _: () = { + use super::super::variant::M5Layouts; + // Every M5 build's policy map and status-config map fill the allocations of its size table, + // and the policy starts where the encoders write its 26A428 form. + let builds = [M5Layouts::V26A428, M5Layouts::V26B123]; + let mut index = 0; + while index < builds.len() { + let profile = RootProfile::for_m5_layouts(builds[index]); + let layout = match profile.m5_layout() { + Some(layout) => layout, + None => panic!("an M5 build without an M5 layout"), + }; + assert!(m5_policy_size(builds[index]) == layout.policy_size()); + assert!(profile.m5_status_config().size == layout.status_config_size()); + assert!(layout.shared.policy == M5_SHARED_LAYOUT.policy); + index += 1; + } +}; + +pub(crate) const M5_SHARED_LAYOUT: SharedClusterLayout = M5_LAYOUT_26A428.shared; + +pub(crate) const M5_PRIVATE_LAYOUT: PrivateClusterLayout = M5_LAYOUT_26A428.private; pub(crate) const M5_SHARED_CLUSTER_SIZE: usize = M5_SHARED_LAYOUT.total; @@ -1810,6 +2029,50 @@ pub(crate) const M5_STATUS_CONFIG_LINK_WORD: usize = 0x774; pub(crate) const M5_STATUS_CONFIG_LINK_PTR: usize = 0x778; +/// Submission-history period and slot count (two u64), its generation word and its per-slot +/// bytes in the status config, at 26A428 offsets. +pub(crate) const M5_STATUS_CONFIG_HISTORY: usize = 0x73c; +pub(crate) const M5_STATUS_CONFIG_HISTORY_GENERATION: usize = 0x74c; +pub(crate) const M5_STATUS_CONFIG_HISTORY_SLOTS: usize = 0x750; + +/// Where one firmware build keeps the status-config fields the driver knows by their 26A428 +/// offsets. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5StatusConfigMap { + /// Allocation size (entry 13 of the build's allocation size table). + pub(crate) size: usize, + /// 26A428 offset -> this build's offset; empty for 26A428 itself. + pub(crate) bands: &'static [LayoutBand], + /// Words this build has and 26A428 does not, at this build's offsets. + pub(crate) inserted: &'static [(usize, u32)], +} + +impl M5StatusConfigMap { + /// This build's offset of the 26A428 status-config offset `offset`. + pub(crate) const fn relocate(&self, offset: usize) -> Option { + if !self.bands.is_empty() { + return relocate_by_bands(self.bands, offset); + } + if offset < self.size { + Some(offset) + } else { + None + } + } +} + +pub(crate) const M5_26A428_STATUS_CONFIG: M5StatusConfigMap = M5StatusConfigMap { + size: M5_STATUS_CONFIG_SIZE, + bands: &[], + inserted: &[], +}; + +pub(crate) const M5_26B123_STATUS_CONFIG: M5StatusConfigMap = M5StatusConfigMap { + size: M5_26B123_STATUS_CONFIG_SIZE, + bands: M5_26B123_STATUS_CONFIG_BANDS, + inserted: M5_26B123_STATUS_CONFIG_INSERTED, +}; + pub(crate) const M5_HW_DATA_INSERT: usize = 0x267c; pub(crate) const M5_HW_DATA_INSERT_LEN: usize = 8; @@ -1857,7 +2120,7 @@ const COMMON26_POLICY_BOOT_TIMESTAMP: usize = 0x6c14; /// initPowerAndPerformanceData stores (the G18 backend's G18G_26A428_POLICY_BANDS). 26A428 /// inserts 0x680 bytes between the AON PTD pointer and the boot timestamp; the 25G76 words /// there have no place. -const COMMON26_POLICY_BANDS: &[LayoutBand] = &[ +pub(crate) const COMMON26_POLICY_BANDS: &[LayoutBand] = &[ band(0x0000, 0x009c, 0, Evidence::ProducerChecked), band(0x00a0, 0x0200, 0x10, Evidence::ProducerChecked), band(0x09b8, 0x295c, 0x10, Evidence::ProducerChecked), @@ -1935,6 +2198,31 @@ pub(crate) const M5_GRAPH: Graph = Graph { power_assert_tally: super::power::POWER_ASSERT_TALLY, }; +/// Select the M5 Pro/Max/Ultra graph from the identified firmware build. +pub(crate) const fn m5_graph(layouts: M5Layouts) -> &'static Graph { + match layouts { + M5Layouts::V26A428 => &M5_GRAPH, + M5Layouts::V26B123 => &M5_GRAPH_26B123, + } +} + +const fn graph_for_m5_layout(layouts: M5Layouts, layout: &M5Layout) -> Graph { + Graph { + profile: RootProfile::for_m5_layouts(layouts), + private: layout.private, + shared: layout.shared, + policy_size: layout.policy_size(), + bundle_view_offsets: layout.bundle_view_offsets(), + bundle_view_extents: layout.bundle_view_extents(), + work_ring_offsets: work_ring_offsets(&layout.shared), + state_grids: layout.private_state_grids(), + power_assert_tally: super::power::POWER_ASSERT_TALLY, + } +} + +pub(crate) const M5_GRAPH_26B123: Graph = + graph_for_m5_layout(M5Layouts::V26B123, &M5_LAYOUT_26B123); + /// The common 26A428 build (J873's interface; the J813). pub(crate) const COMMON26_GRAPH: Graph = Graph { profile: RootProfile::J873G18G26A428, @@ -2435,9 +2723,12 @@ pub(crate) struct Board { /// Whether the host encodings are the G17D ones measured on the M5 Ultra /// ([`Board::g17d_forms`]). g17d_forms: bool, - /// Whether explicit waits on other kicks take the completion class - /// ([`Board::completion_inputs`]). - completion_inputs: bool, + /// Whether firmware accepts tiling kicks without an entry signal and retained + /// render pairs kicked through the host port alone. + pub(crate) host_only_render_kicks: bool, + /// Firmware compute queues of one context over which a single command queue's independent + /// kicks may run ([`Board::compute_channels`]). + compute_channels: u8, } /// M5 Pro: two clusters of ten cores. @@ -2466,7 +2757,10 @@ pub(crate) const J714: Board = Board { hw_words: &[], fan_curve_start_mc: 84_000, g17d_forms: false, - completion_inputs: true, + host_only_render_kicks: false, + // macOS runs one M5 Pro command queue on up to three firmware compute queues of the same + // context, created on demand and sharing one completion ordinal (its own kicks under aura). + compute_channels: 3, }; /// M5 Max: four clusters of ten cores. @@ -2497,7 +2791,11 @@ pub(crate) const J716C: Board = Board { hw_words: &[], fan_curve_start_mc: 84_000, g17d_forms: false, - completion_inputs: false, + // Qualified on G17C's 26A428 image. G17S uses completion-class inputs, + // G17D has distinct kick encodings, and common 26A428 publishes descriptors + // on the item ring. Qualify those interfaces separately. + host_only_render_kicks: true, + compute_channels: 1, }; /// J775D's performance controllers run from P3. @@ -2538,7 +2836,8 @@ pub(crate) const J775D: Board = Board { // above the SMC's own start rather than below it. fan_curve_start_mc: 97_000, g17d_forms: true, - completion_inputs: false, + host_only_render_kicks: false, + compute_channels: 1, }; /// M5 (T8142, MacBook Air J813): one cluster of ten core slots, eight enabled. Values from the @@ -2577,7 +2876,8 @@ pub(crate) const J813: Board = Board { (0x10d4, 0x17), (0x1118, 0), (0x2660, 4), (0x2720, 1), (0x2724, 0)], fan_curve_start_mc: 84_000, g17d_forms: false, - completion_inputs: false, + host_only_render_kicks: false, + compute_channels: 1, }; /// The J813 on its macOS 27.2 (26B123) firmware: the same board on the common 26B123 graph. @@ -2586,6 +2886,17 @@ pub(crate) const J813_26B123: Board = Board { ..J813 }; +// Every board runs at least one compute channel per command queue and no more than the per-owner +// channel arrays hold. +const _: () = { + let mut boards = [&J714, &J716C, &J775D, &J813, &J813_26B123].as_slice(); + while let [board, rest @ ..] = boards { + assert!(board.compute_channels >= 1); + assert!(board.compute_channels as usize <= crate::g17::pairs::COMPUTE_CHANNELS_MAX); + boards = rest; + } +}; + const _: () = { use super::target::min_parameter_buffer_pages; assert!(J714.min_parameter_buffer as u64 == min_parameter_buffer_pages(J714.clusters) << 15); @@ -2593,6 +2904,14 @@ const _: () = { assert!(J775D.min_parameter_buffer as u64 == min_parameter_buffer_pages(J775D.clusters) << 15); }; +// Completion inputs follow the firmware interface and host encodings: the M5 graph's G17S and +// G17C boards take them, the G17D and the common-interface boards keep their own forms. +const _: () = { + assert!(J714.completion_inputs() && J716C.completion_inputs()); + assert!(!J775D.completion_inputs() && !J813.completion_inputs()); + assert!(!J813_26B123.completion_inputs()); +}; + /// Populate the enabled-USC count from the device's sampled core masks. /// This count covers the whole device, not one cluster. pub(crate) fn set_m5_enabled_cores(board: &Board, out: &mut [u8], enabled: u32) @@ -2612,6 +2931,221 @@ pub(crate) const M5_POLICY_STATE_PTR: usize = 0x8254; pub(crate) const M5_POLICY_AON_PTD_PTR: usize = 0x11a1c; +/// Power policy 26A428 -> 26B123 (macOS 27.2), in 26A428 offsets. The policy grows from 0x126b0 to 0x12728 bytes (allocation size table entry 4); five +/// inserts move the words above them: +/// +/// - +0x4910, 0x10 bytes (two u64 words). The three controller input words at 0x4910..0x4918 +/// (3500, 1000 and 3000 in the J714 defaults) move to 0x4920. +/// - +0x491c, 4 bytes: a controller input word, at 0x492c in 26B123 +/// ([`M5_26B123_POLICY_CONTROLLER_WORDS`]). +/// - 4 bytes between 0x494c and 0x49b8, and 0x18 bytes between 0x4a00 and 0x4a98, in space the M5 +/// encoders do not write: the bands start at the next written offset (0x4948 -> 0x495c, +/// 0x49b8 -> 0x49d0, 0x49fc -> 0x4a14, 0x4a98 -> 0x4ac8), and no word the M5 encoders write +/// falls in either range. +/// - +0x12668, 0x48 bytes: the table at +0x122f0 (24-byte entries) grows from 37 to 40 entries, +/// its trailing fields moving from +0x378/+0x37c/+0x37d/+0x380 to +0x3c0/+0x3c4/+0x3c5/+0x3c8. +/// The new entries are assumed to sit at the end. +/// +/// The state and AON PTD pointers move with their band, 0x8254 -> 0x8284 and 0x11a1c -> 0x11a4c. +/// The 26B123 policy may use words of its own at 0x94e4..0x954c, in space the M5 encoders do not +/// write in 26A428 (0x94b4..0x951c); they stay zero here. +/// +/// InitData captured from macOS 27.2 on a J716s shows the state pointer at 0x8284 and the AON PTD +/// pointer at 0x11a4c, and the maximum power word at 0xa18 where it was; the bands between them +/// follow from these anchors and the sizes and are not otherwise observed. +pub(crate) const M5_26B123_POLICY_BANDS: &[LayoutBand] = &[ + band(0x0000, 0x4910, 0, Evidence::Inferred), + band(0x4910, 0x491c, 0x10, Evidence::Inferred), + band(0x491c, 0x49b8, 0x14, Evidence::Inferred), + band(0x49b8, 0x4a98, 0x18, Evidence::Inferred), + band(0x4a98, 0x12668, 0x30, Evidence::Inferred), + band(0x12668, M5_POLICY_SIZE, 0x78, Evidence::Inferred), +]; + +/// Power-policy size of 26B123 (entry 4 of its allocation size table). +pub(crate) const M5_26B123_POLICY_SIZE: usize = ABI_ALLOCATION_SIZES_26B123_M5[ALLOC_POLICY]; + +/// The 26B123 policy controller input words the 26A428 controller defaults do not write, at 26B123 +/// offsets: +/// +/// - 0x492c, the word of the 4-byte insert at 26A428 +0x491c: 5000. +/// - 0x4a14 (26A428 0x49fc, which the J714 defaults write as 500): 1600. +/// +/// Both read as given in InitData captured from macOS 27.2 on a J716s (G17S). +pub(crate) const M5_26B123_POLICY_CONTROLLER_WORDS: &[(usize, u32)] = + &[(0x492c, 5000), (0x4a14, 1600)]; + +/// The 26B123 policy controller input words for the G17D core type (M5 Ultra), at 26B123 +/// offsets: 2500 at 0x4920 and 800 at 0x4928 (26A428 0x4910 and 0x4918, 3500 and 3000 in the J714 +/// defaults), 1100 at 0x492c, 0 at 0x49e4 (26A428 0x49cc, 1 in the J714 defaults) and 1600 at +/// 0x4a14. The J716s capture was taken on a G17S part (HW data core type 0x18) and does not cover +/// these values. +pub(crate) const M5_26B123_POLICY_CONTROLLER_WORDS_G17D: &[(usize, u32)] = &[ + (0x4920, 2500), + (0x4928, 800), + (0x492c, 1100), + (0x49e4, 0), + (0x4a14, 1600), +]; + +/// The HW-data core type of the G17D (M5 Ultra) parts. +const M5_CORE_TYPE_G17D: u32 = 0x1a; + +/// Where one firmware build keeps the power-policy words the M5 encoders write at their 26A428 +/// offsets. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5PolicyMap { + /// Allocation size (entry 4 of the build's allocation size table). + pub(crate) size: usize, + /// 26A428 offset -> this build's offset; empty for 26A428 itself. + pub(crate) bands: &'static [LayoutBand], + /// Words of this build's controller configuration the 26A428 controller defaults do not + /// write, at this build's offsets: for core types with words of their own, then for every + /// other core type. + pub(crate) controller_words_by_core: &'static [(u32, &'static [(usize, u32)])], + pub(crate) controller_words: &'static [(usize, u32)], +} + +impl M5PolicyMap { + /// This build's offset of the 26A428 policy offset `offset`. + pub(crate) const fn relocate(&self, offset: usize) -> Option { + if !self.bands.is_empty() { + return relocate_by_bands(self.bands, offset); + } + if offset < self.size { + Some(offset) + } else { + None + } + } + + /// This build's controller-configuration words for `board`. + fn controller_words_for(&self, board: &Board) -> &'static [(usize, u32)] { + for &(core, words) in self.controller_words_by_core { + if core == board.core_revision.0 { + return words; + } + } + self.controller_words + } +} + +pub(crate) const M5_26A428_POLICY: M5PolicyMap = M5PolicyMap { + size: M5_POLICY_SIZE, + bands: &[], + controller_words_by_core: &[], + controller_words: &[], +}; + +pub(crate) const M5_26B123_POLICY: M5PolicyMap = M5PolicyMap { + size: M5_26B123_POLICY_SIZE, + bands: M5_26B123_POLICY_BANDS, + controller_words_by_core: &[(M5_CORE_TYPE_G17D, M5_26B123_POLICY_CONTROLLER_WORDS_G17D)], + controller_words: M5_26B123_POLICY_CONTROLLER_WORDS, +}; + +/// The power-policy map of an M5 firmware build. +pub(crate) const fn m5_policy(layouts: M5Layouts) -> &'static M5PolicyMap { + match layouts { + M5Layouts::V26A428 => &M5_26A428_POLICY, + _ => &M5_26B123_POLICY, + } +} + +/// The power-policy allocation size of an M5 firmware build. +pub(crate) const fn m5_policy_size(layouts: M5Layouts) -> usize { + m5_policy(layouts).size +} + +/// Whether `bands` lay `source` bytes out over `target` bytes in place: contiguous from 0 to +/// `source`, with shifts that never shrink, ending at `target`. +const fn expands_in_place(bands: &[LayoutBand], source: usize, target: usize) -> bool { + let mut index = 0; + let mut end = 0; + let mut delta: isize = 0; + while index < bands.len() { + let band = bands[index]; + if band.start != end || band.end <= band.start || band.delta < delta { + return false; + } + end = band.end; + delta = band.delta; + index += 1; + } + end == source && (end as isize + delta) as usize == target +} + +const _: () = { + assert!(expands_in_place( + M5_26B123_POLICY_BANDS, + M5_POLICY_SIZE, + M5_26B123_POLICY_SIZE + )); + assert!(matches!( + M5_26B123_POLICY.relocate(M5_POLICY_STATE_PTR), + Some(0x8284) + )); + assert!(matches!( + M5_26B123_POLICY.relocate(M5_POLICY_AON_PTD_PTR), + Some(0x11a4c) + )); + assert!(matches!( + M5_26B123_POLICY.relocate(M5_POLICY_MAXIMUM_POWER), + Some(0xa18) + )); +}; + +/// Lays out the power policy the M5 encoders wrote at 26A428 offsets into `policy[..0x126b0]` +/// as `map` says, in place: every band moves, highest first, and the bytes no band covers are +/// zeroed. With `controller_defaults`, the build's controller-configuration words for `board` +/// follow. For 26A428 nothing changes. +pub(crate) fn relayout_m5_policy( + map: &M5PolicyMap, + board: &Board, + controller_defaults: bool, + policy: &mut [u8], +) -> Result<(), InitdataError> { + if policy.len() != map.size { + return Err(InitdataError::BufferSize); + } + if map.bands.is_empty() { + return Ok(()); + } + if !expands_in_place(map.bands, M5_POLICY_SIZE, map.size) { + return Err(InitdataError::BufferSize); + } + // A band's target lies over its own source and the higher bands, which have moved already. + for band in map.bands.iter().rev() { + let target = band + .start + .checked_add_signed(band.delta) + .ok_or(InitdataError::BufferSize)?; + policy.copy_within(band.start..band.end, target); + } + let mut end = 0; + for band in map.bands { + let target = band + .start + .checked_add_signed(band.delta) + .ok_or(InitdataError::BufferSize)?; + policy[end..target].fill(0); + end = target + (band.end - band.start); + } + policy[end..].fill(0); + if controller_defaults { + for &(offset, value) in map.controller_words_for(board) { + if offset + .checked_add(4) + .is_none_or(|word_end| word_end > policy.len()) + { + return Err(InitdataError::BufferSize); + } + put_u32(policy, offset, value); + } + } + Ok(()) +} + pub(crate) const J714_GPU_POWER_SAMPLE_PERIOD_AIC_CLOCKS: u32 = 200_000; pub(crate) const J714_GPU_PERF_BASE_PSTATE: u32 = 1; @@ -2952,8 +3486,30 @@ impl Board { /// producers) take the completion class, which holds them in firmware until those kicks /// complete. A wait on another queue's compute stays in firmware only for work that declares /// a visible completion (DRM_ASAHI_COMPUTE_VISIBLE_COMPLETION); others wait on the host. + /// + /// This keys on the board's static graph family and host encodings: every board on [`M5_GRAPH`] + /// (whose static profile is [`RootProfile::J714G17S26A428`]) without the G17D host encodings + /// (`!self.g17d_forms`) takes these waits, with the counted descriptor forms + /// [`super::compute::kick_tuple`] gives them. Any other graph family keeps them off until its + /// kicks are known to take that form. + /// - The common interface (the J813) encodes its kicks in its own forms + /// ([`Board::j813_forms`]): it already gives explicit dependencies the completion class, + /// but its kicks carry no submission sequence and no retired-parent relaxation, which the + /// M5 graph's form adds, so its waits stay on the host. + /// - The G17D host encodings ([`Board::g17d_forms`]) run compute only with the qualified + /// tuple and the entry-signal gate, and take their firmware waits in the pipelined class + /// ([`super::compute::explicit_dependency`]); the counted G17S form's tuple does not apply + /// there and has not been run on a G17D, where a wrong kick form never completes. pub(crate) const fn completion_inputs(&self) -> bool { - self.completion_inputs + matches!(self.graph.profile, RootProfile::J714G17S26A428) && !self.g17d_forms + } + + /// Firmware compute queues of one context over which a single command queue's independent + /// kicks may run, each with its own preemption, operand, usage, status and stamp state and all + /// of them sharing the context's completion ordinal. 1 where the board's own macOS driver has + /// not been seen to spread a command queue: one firmware compute queue per command queue. + pub(crate) const fn compute_channels(&self) -> u8 { + self.compute_channels } /// Whether this is the J813, whose register programs macOS 27.0 writes in the common 26A428 @@ -3196,41 +3752,93 @@ pub(crate) fn encode_m5_region_c(out: &mut [u8]) -> Result<(), InitdataError> { Ok(()) } -pub(crate) fn encode_m5_primary_status_b( +/// Encodes the primary status-B span (`out`, from status B to the primary status A) of a build +/// whose status config sits at `config` in the span and is laid out as `map` says. +pub(crate) fn encode_m5_primary_status_b_for( + map: &M5StatusConfigMap, + config: usize, fwctl_state: u64, fwctl_ring: u64, status_b: u64, out: &mut [u8], ) -> Result<(), InitdataError> { - if out.len() != M5_STATUS_B_SPAN { + let end = config + .checked_add(map.size) + .ok_or(InitdataError::BufferSize)?; + if end > out.len() { return Err(InitdataError::BufferSize); } + let link_word = map + .relocate(M5_STATUS_CONFIG_LINK_WORD) + .ok_or(InitdataError::BufferSize)?; + let link_ptr = map + .relocate(M5_STATUS_CONFIG_LINK_PTR) + .ok_or(InitdataError::BufferSize)?; required_address(fwctl_state)?; required_address(fwctl_ring)?; required_address(status_b)?; - let config = M5_STATUS_CONFIG_IN_STATUS_B; out.fill(0); encode_status_block(&mut out[..STATUS_BLOCK_SIZE])?; put_u64(out, COMMON26_STATUS_B_FWCTL_STATE, fwctl_state); put_u64(out, COMMON26_STATUS_B_FWCTL_RING, fwctl_ring); put_u32(out, COMMON26_STATUS_B_CONFIG_HEADER, 1); put_u32(out, COMMON26_STATUS_B_LINK_WORD, 0); - put_u64(out, COMMON26_STATUS_B_LINK_PTR, - status_b + (config + M5_STATUS_CONFIG_LINK_WORD) as u64); - write_relocated_words(M5_25G76_STATUS_CONFIG_WORDS, 0, COMMON26_STATUS_CONFIG_BANDS, - &mut out[config..config + M5_STATUS_CONFIG_SIZE])?; - put_u32(out, config + M5_STATUS_CONFIG_LINK_WORD, 1); - put_u64(out, config + M5_STATUS_CONFIG_LINK_PTR, - status_b + COMMON26_STATUS_B_LINK_WORD as u64); + put_u64( + out, + COMMON26_STATUS_B_LINK_PTR, + status_b + (config + link_word) as u64, + ); + write_m5_status_config_words(map, &mut out[config..end])?; + put_u32(out, config + link_word, 1); + put_u64( + out, + config + link_ptr, + status_b + COMMON26_STATUS_B_LINK_WORD as u64, + ); + Ok(()) +} + +/// Writes the 25G76 status-config words through the 26A428 bands and then `map`, followed by +/// the words the build inserted. For 26A428 this is +/// `write_relocated_words(M5_25G76_STATUS_CONFIG_WORDS, 0, COMMON26_STATUS_CONFIG_BANDS, out)`. +fn write_m5_status_config_words( + map: &M5StatusConfigMap, + out: &mut [u8], +) -> Result<(), InitdataError> { + if out.len() != map.size { + return Err(InitdataError::BufferSize); + } + for &(offset, value) in M5_25G76_STATUS_CONFIG_WORDS { + for (index, byte) in value.to_le_bytes().into_iter().enumerate() { + if byte == 0 { + continue; + } + let target = relocate_by_bands(COMMON26_STATUS_CONFIG_BANDS, offset + index) + .and_then(|source| map.relocate(source)); + if let Some(target) = target { + *out.get_mut(target).ok_or(InitdataError::BufferSize)? = byte; + } + } + } + for &(offset, value) in map.inserted { + if offset.checked_add(4).is_none_or(|end| end > out.len()) { + return Err(InitdataError::BufferSize); + } + put_u32(out, offset, value); + } Ok(()) } -pub(crate) fn encode_m5_private_cluster( +pub(crate) fn encode_m5_private_cluster_for_profile( + profile: RootProfile, private_base: u64, fwctl_state: u64, out: &mut [u8], ) -> Result<(), InitdataError> { - let layout = M5_PRIVATE_LAYOUT; + let layout = profile + .m5_layout() + .ok_or(InitdataError::InterfaceMismatch)? + .private; if out.len() != layout.total { return Err(InitdataError::BufferSize); } @@ -3250,8 +3858,14 @@ pub(crate) fn encode_m5_private_cluster( out.fill(0); let status_b = layout.status_b; let status_a = layout.roles[0].status_a; - encode_m5_primary_status_b(fwctl_state, fwctl_ring, private_base + status_b as u64, - &mut out[status_b..status_a])?; + encode_m5_primary_status_b_for( + profile.m5_status_config(), + layout.status_config - status_b, + fwctl_state, + fwctl_ring, + private_base + status_b as u64, + &mut out[status_b..status_a], + )?; for role in layout.roles { encode_status_block(&mut out[role.status_a..role.status_a + STATUS_BLOCK_SIZE])?; } @@ -3266,24 +3880,26 @@ pub(crate) fn encode_m5_private_cluster( Ok(()) } -pub(crate) fn encode_m5_bundle_policy( +pub(crate) fn encode_m5_bundle_policy_for_layout( + m5_layout: &M5Layout, bindings: M5PolicyBindings, out: &mut [u8], ) -> Result<(), InitdataError> { - let layout = M5_SHARED_LAYOUT; - if out.len() < M5_SHARED_PREFIX_SIZE { + let layout = m5_layout.shared; + let prefix = m5_layout.shared_prefix_size(); + if out.len() < prefix { return Err(InitdataError::BufferSize); } required_address(bindings.state)?; required_address(bindings.aon_ptd)?; - out[layout.block_c18..M5_SHARED_PREFIX_SIZE].fill(0); + out[layout.block_c18..prefix].fill(0); let m5 = M5_25G76_SHARED_LAYOUT; for &(offset, value) in M5_25G76_POLICY_WORDS { if (m5.block_1048..m5.block_e10).contains(&offset) { put_u32(out, layout.block_1048 + (offset - m5.block_1048), value); } } - let policy = &mut out[layout.policy..layout.policy + M5_POLICY_SIZE]; + let policy = &mut out[layout.policy..layout.policy + m5_layout.policy_size()]; put_u32(policy, 0x04, J714_GPU_POWER_SAMPLE_PERIOD_AIC_CLOCKS); put_u32(policy, 0x08, J714_GPU_POWER_SAMPLE_PERIOD_AIC_CLOCKS); @@ -3322,6 +3938,14 @@ pub(crate) fn encode_m5_bundle_policy( Ok(()) } +/// The power policy in `out` (a bundle) in its 26A428 form, which the controller defaults write +/// and [`relayout_m5_policy`] then lays out for the firmware build. Every M5 layout starts the +/// policy at the same offset. +fn m5_policy_source(out: &mut [u8]) -> Result<&mut [u8], InitdataError> { + out.get_mut(M5_SHARED_LAYOUT.policy..M5_SHARED_LAYOUT.policy + M5_POLICY_SIZE) + .ok_or(InitdataError::BufferSize) +} + /// Initial controller inputs for J714, applied on every part. The leakage inputs are those of the /// part they were read from (calibration words 0xd2035701 0xac3a1280 0x0a281d81). The firmware /// holds its power estimate, not the draw, to the maximum: a part that leaks more draws more than @@ -3343,7 +3967,7 @@ pub(crate) fn encode_m5_policy_controller_defaults(out: &mut [u8]) -> Result<(), 0x42b6ec22, 0x42c80000, 0x00000000, 0x00000000, ]; for (index, &value) in RELATIVE_POWER_AUX.iter().enumerate() { put_u32(out, 0x1a64 + index * 4, value); } - let policy = &mut out[M5_SHARED_LAYOUT.policy..M5_SHARED_LAYOUT.policy + M5_POLICY_SIZE]; + let policy = m5_policy_source(out)?; const INITIAL: &[(usize, u32)] = &[ (0xd4, 0x3f828f5c), (0xd8, 0x3f828f5c), @@ -3594,7 +4218,7 @@ pub(crate) fn encode_m5_policy_controller_defaults(out: &mut [u8]) -> Result<(), /// tags. pub(crate) fn encode_m5_policy_controller_defaults_j716c(out: &mut [u8]) -> Result<(), InitdataError> { encode_m5_policy_controller_defaults(out)?; - let policy = &mut out[M5_SHARED_LAYOUT.policy..M5_SHARED_LAYOUT.policy + M5_POLICY_SIZE]; + let policy = m5_policy_source(out)?; const MAXIMUM_POWER: u32 = 196_098; const MAXIMUM_POWER_F32: u32 = 0x483f_8080; for offset in [M5_POLICY_MAXIMUM_POWER, 0xad0, 0x44a4, 0x44a8, 0x44ac, 0x45e4] { @@ -3633,7 +4257,7 @@ pub(crate) fn encode_m5_policy_controller_defaults_j775d(out: &mut [u8]) -> Resu 0x421c_12dd, 0x4230_6915, 0x4250_6a36, 0x427d_e40c, 0x4294_0cc0, 0x42bd_bd8e, 0x42c8_0000, ]; for (index, &value) in RELATIVE_POWER_AUX.iter().enumerate() { put_u32(out, 0x1a64 + index * 4, value); } - let policy = &mut out[M5_SHARED_LAYOUT.policy..M5_SHARED_LAYOUT.policy + M5_POLICY_SIZE]; + let policy = m5_policy_source(out)?; const MAXIMUM_POWER: u32 = 345_262; const MAXIMUM_POWER_F32: u32 = 0x48a8_95c0; for offset in [M5_POLICY_MAXIMUM_POWER, 0xad0, 0x44a4, 0x44a8, 0x44ac, 0x45e4] { diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/pool.rs b/drivers/gpu/drm/asahi/g17/fw/m5/pool.rs index 7a457322fb64e7..6c1283f988b1c3 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/pool.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/pool.rs @@ -54,6 +54,8 @@ pub(crate) const SAVED_FIELDS: [usize; 8] = [0x28, 0x20, 0x24, 0x2c, 0x3c, 0x48, const GPU_PAGE: usize = 0x4000; const PRIVATE_TOP: u64 = 1 << 42; pub(crate) const SCENE_TABLE_ENTRIES: usize = 0x50; +/// Bytes of a render pair's parameter-buffer discard object. +pub(crate) const DISCARD_BYTES: usize = 0x8000; pub(crate) const SCENE_STRIDE: usize = 0x80; pub(crate) const SCENE_TRAILER_SIZE: usize = 0x40; diff --git a/drivers/gpu/drm/asahi/g17/fw/render.rs b/drivers/gpu/drm/asahi/g17/fw/render.rs index dc22354f9c2ded..023a633230c3c6 100644 --- a/drivers/gpu/drm/asahi/g17/fw/render.rs +++ b/drivers/gpu/drm/asahi/g17/fw/render.rs @@ -398,6 +398,9 @@ pub(crate) struct RenderArgs<'a> { pub(crate) programs: RegisterPrograms, /// Device/build policy for registers 0x1c890 and 0x1c918 in V25G83-format arrays. pub(crate) ta_mode_1: bool, + /// Clusters of the GPU: above two, clustered tiling takes the segment words of + /// `fw::m5::target::cluster_control` instead of the two-cluster capture. + pub(crate) clusters: u32, /// Deflake-buffer layout of the GPU. pub(crate) deflake: Deflake, } @@ -697,6 +700,13 @@ const T6041_TA_MODE_1: u64 = 1; /// Pages the tiler keeps out of a partial render's segments: without them the pages a pass /// returns shrink to none and the tiler can't advance. Fifteen blocks, macOS's minimum heap. const MIN_FREE_TVB_PAGES: u64 = 0x3c; +/// Free parameter-buffer pages (`0x1c9a8`) of a clustered V25G83 pass: `28 + 16 x clusters` +/// (`0x3c` for two clusters on M4 Pro, `0x5c` for four clusters on M4 Max as macOS 26.6.2 +/// writes it, four pages less than M5's `32 + 16 x clusters`). +const fn v25g83_clustered_free_pages(clusters: u32) -> u64 { + 0x1c + 0x10 * clusters as u64 +} +const _: () = assert!(v25g83_clustered_free_pages(2) == MIN_FREE_TVB_PAGES); /// The 25G83 tiling array: the A18 Pro's without 0x1748 and 0x1740 (and 0x17d9 unless the stage /// has SCS), with the tiler parameter sub-buffer registers and 0x10131 = 0x88, in the order the @@ -748,10 +758,20 @@ fn ta_registers_25g83( push(find(0x1c880, 0)?); push(RegisterWrite::new(0x1c948, gtp(4)?)); push(RegisterWrite::new(0x1c888, gtp(5)?)); - let (segment_control, segment_index) = if args.ta_mode_1 { - (T6041_TA_MODE_1, 0) - } else { - (VDM_SEGMENT_CONTROL, VDM_SEGMENT_INDEX) + let multi = (!args.ta_mode_1 && args.clusters > 2) + .then(|| { + super::m5::target::cluster_control( + args.clusters, + v25g83_clustered_free_pages(args.clusters), + ) + }) + .flatten(); + let (segment_control, segment_index, free_pages) = match (args.ta_mode_1, multi) { + (true, _) => (T6041_TA_MODE_1, 0, MIN_FREE_TVB_PAGES), + // Above two clusters (four-cluster M4 Max: 0x280540 / 4 / 0x5c): segment words from + // cluster_control() with the V25G83 free-page count (28 + 16 x clusters). + (false, Some([control, index, pages])) => (control, index, pages), + (false, None) => (VDM_SEGMENT_CONTROL, VDM_SEGMENT_INDEX, MIN_FREE_TVB_PAGES), }; push(RegisterWrite::new(0x1c890, segment_control)); push(RegisterWrite::new(0x1c918, segment_index)); @@ -761,7 +781,7 @@ fn ta_registers_25g83( push(RegisterWrite::new(0x1c9e0, gtp2)); push(RegisterWrite::new(0x16c41, gtp6)); push(RegisterWrite::new(0x1ca40, gtp6)); - push(RegisterWrite::new(0x1c9a8, MIN_FREE_TVB_PAGES)); + push(RegisterWrite::new(0x1c9a8, free_pages)); push(RegisterWrite::new(0x1c920, gtp(7)?)); for reg in [0x10151, 0x1c199, 0x1c1a1, 0x1c1a9, 0x1c1b1, 0x1c1b9, 0x1c8f8, 0x1c0b1, 0x1c850] { push(find(reg, 0)?); @@ -1753,49 +1773,69 @@ mod ta_mode_tests { } } - /// The variants of the builds T6041 admits: 25F84, then 25G83 and 26B123, each of which the - /// 40- and the 32-core configurations run with the same rules. - fn t6041_variants() -> [&'static Variant; 3] { + /// The variants of the builds T6041 admits: 25F84, 40-core 25G83, 32-core 25G83, and 26B123. + fn t6041_variants() -> [&'static Variant; 4] { let Firmware::Identified(builds) = crate::hw::t6041::CONFIG.firmware else { panic!("T6041 must identify its loaded firmware"); }; assert_eq!(builds.len(), 5); for (full, cut) in [(1, 2), (3, 4)] { let (full, cut) = (builds[full].variant, builds[cut].variant); - assert_eq!(full.ta_mode_1, cut.ta_mode_1); assert_eq!(full.compute, cut.compute); assert_eq!(full.programs, cut.programs); } - [builds[0].variant, builds[1].variant, builds[3].variant] + assert_eq!(builds[3].variant.ta_mode_1, builds[4].variant.ta_mode_1); + [ + builds[0].variant, + builds[1].variant, + builds[2].variant, + builds[3].variant, + ] } - /// The TA mode of every admitted T6041 build. + /// The TA mode of the non-clustered T6041 builds (25F84, 40-core 25G83, and 26B123). fn t6041_ta_mode_1() -> bool { - let [f84, g83, b123] = t6041_variants(); - assert_eq!(f84.ta_mode_1, g83.ta_mode_1); + let [f84, g83_40, _, b123] = t6041_variants(); + assert_eq!(f84.ta_mode_1, g83_40.ta_mode_1); assert_eq!(f84.ta_mode_1, b123.ta_mode_1); f84.ta_mode_1 } #[test] fn policy_is_local_to_the_admitted_t6041_builds() { - let [f84, g83, b123] = t6041_variants(); + let [f84, g83_40, g83_32, b123] = t6041_variants(); let pro = selected(&crate::hw::t6040::CONFIG.firmware); assert_eq!(f84.compute, crate::g17::fw::compute::ComputeProgram::V25F84); assert!(f84.split_firmware_area); // 25G83 keeps the M4 Pro's queue and compute rules on the M4 Max. - assert_eq!(g83.compute, pro.compute); - assert_eq!(g83.split_firmware_area, pro.split_firmware_area); - assert_eq!(g83.opening_record, pro.opening_record); - assert_eq!(g83.qid_floor, pro.qid_floor); - assert_eq!(g83.registration, pro.registration); + for g83 in [g83_40, g83_32] { + assert_eq!(g83.compute, pro.compute); + assert_eq!(g83.split_firmware_area, pro.split_firmware_area); + assert_eq!(g83.opening_record, pro.opening_record); + assert_eq!(g83.qid_floor, pro.qid_floor); + assert_eq!(g83.registration, pro.registration); + } // 26B123 runs 25F84's compute program with one firmware area. assert_eq!(b123.compute, f84.compute); assert!(!b123.split_firmware_area); - for max in [f84, g83, b123] { + for max in [f84, g83_40, g83_32, b123] { assert_eq!(max.programs, RegisterPrograms::V25G83); - assert!(max.ta_mode_1); } + // 25F84 and 40-core 25G83 keep TA mode 1; 32-core 25G83 tiles clustered with a heap that + // may fill the block table. + assert!(f84.ta_mode_1); + assert!(g83_40.ta_mode_1); + assert!(!g83_32.ta_mode_1); + assert_eq!( + g83_32.tvb_normal_blocks, + crate::g17::fw::buffer::NORMAL_MAX_BLOCKS_FOUR_CLUSTERS, + ); + assert_eq!(g83_40.tvb_normal_blocks, crate::g17::fw::buffer::NORMAL_MAX_BLOCKS); + assert_eq!(f84.tvb_normal_blocks, crate::g17::fw::buffer::NORMAL_MAX_BLOCKS); + assert_eq!(pro.tvb_normal_blocks, crate::g17::fw::buffer::NORMAL_MAX_BLOCKS); + // 26B123 keeps 25F84's TA mode 1 and heap maximum. + assert!(b123.ta_mode_1); + assert_eq!(b123.tvb_normal_blocks, crate::g17::fw::buffer::NORMAL_MAX_BLOCKS); assert!(!pro.ta_mode_1); assert!(!V25F84.ta_mode_1); assert!(!V25G83.ta_mode_1); @@ -1848,6 +1888,7 @@ mod ta_mode_tests { fragment: stage, programs: RegisterPrograms::V25G83, ta_mode_1: false, + clusters: 2, deflake: Deflake::FOUR_CLUSTERS, } } @@ -1892,6 +1933,38 @@ mod ta_mode_tests { } } + #[test] + fn four_clusters_take_the_four_cluster_segment_words() { + let (pass, resources) = fixture(); + let geometry = Geometry::new(&pass).unwrap(); + let words = PassWords::new(&pass).unwrap(); + let find = |a: &[RegisterWrite], reg: u32| a.iter().find(|w| w.reg == reg).map(|w| w.value); + let mut args = args(&pass, &resources, false); + let (two, count) = ta_registers_25g83(&args, &geometry, &words).unwrap(); + assert_eq!(find(&two[..count], 0x1c890), Some(VDM_SEGMENT_CONTROL)); + assert_eq!(find(&two[..count], 0x1c918), Some(VDM_SEGMENT_INDEX)); + assert_eq!(find(&two[..count], 0x1c9a8), Some(MIN_FREE_TVB_PAGES)); + args.clusters = 4; + let (four, count4) = ta_registers_25g83(&args, &geometry, &words).unwrap(); + assert_eq!(count4, count); + assert_eq!(find(&four[..count4], 0x1c890), Some(0x28_0540)); + assert_eq!(find(&four[..count4], 0x1c918), Some(4)); + assert_eq!(find(&four[..count4], 0x1c9a8), Some(0x5c)); + args.clusters = 8; + let (eight, count8) = ta_registers_25g83(&args, &geometry, &words).unwrap(); + assert_eq!(count8, count); + assert_eq!(find(&eight[..count8], 0x1c890), Some(0x30_0640)); + assert_eq!(find(&eight[..count8], 0x1c918), Some(4)); + assert_eq!(find(&eight[..count8], 0x1c9a8), Some(0x9c)); + // TA mode 1 is unaffected by the cluster count. + args.clusters = 4; + args.ta_mode_1 = true; + let (mode1, count1) = ta_registers_25g83(&args, &geometry, &words).unwrap(); + assert_eq!(count1, count); + assert_eq!(find(&mode1[..count1], 0x1c890), Some(T6041_TA_MODE_1)); + assert_eq!(find(&mode1[..count1], 0x1c9a8), Some(MIN_FREE_TVB_PAGES)); + } + #[test] fn mode_does_not_change_fragment_or_g17p_arrays() { let (pass, resources) = fixture(); diff --git a/drivers/gpu/drm/asahi/g17/fw/render_rt.rs b/drivers/gpu/drm/asahi/g17/fw/render_rt.rs index 666209690efde0..74679c34d18ae2 100644 --- a/drivers/gpu/drm/asahi/g17/fw/render_rt.rs +++ b/drivers/gpu/drm/asahi/g17/fw/render_rt.rs @@ -1,8 +1,11 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -use super::{compute::{IntersectionTables, ScratchRequest}, compute_pool, - freelist::{PAGE_LIST_SIZE, RENDER_BLOCKS}, - initdata::{FREE_LIST_BLOCK_PAGES, FREE_LIST_BLOCK_SIZE}}; +use super::{ + compute::{IntersectionTables, ScratchRequest}, + compute_pool, + freelist::{MULTI_CLUSTER_RENDER_BLOCKS_PER_CORE, PAGE_LIST_SIZE, RENDER_BLOCKS}, + initdata::{FREE_LIST_BLOCK_PAGES, FREE_LIST_BLOCK_SIZE}, +}; use kernel::prelude::*; #[derive(Clone, Copy)] @@ -33,18 +36,92 @@ impl RayQueryStage { } } +/// Minimum render pool in 1 MiB blocks for a GPU's cluster and active-core shape. +/// +/// One- and two-cluster parts (A18 Pro, M4 Pro) keep [`RENDER_BLOCKS`] (44), +/// which fits the narrow shared pool window and has been validated there. Above +/// two clusters, clustered tiling runs vertex shaders across every cluster +/// concurrently with fragment work, so the base pool scales linearly with +/// enabled cores at [`MULTI_CLUSTER_RENDER_BLOCKS_PER_CORE`] (3) blocks per +/// core, floored at [`RENDER_BLOCKS`]. +pub(crate) fn base_blocks(active_cores: u32, clusters: u32) -> Result { + if active_cores == 0 || clusters == 0 { + return Err(EINVAL); + } + if clusters <= 2 { + return Ok(RENDER_BLOCKS); + } + let scaled = usize::try_from(active_cores) + .ok() + .and_then(|cores| cores.checked_mul(MULTI_CLUSTER_RENDER_BLOCKS_PER_CORE)) + .ok_or(EOVERFLOW)?; + Ok(scaled.max(RENDER_BLOCKS)) +} + /// The render pool of an owner is shared by its `pairs` render pairs, each with -/// its own compute-pool extras. -pub(crate) fn required_blocks(active_cores: u32, pages: [u16; 2], pairs: u8) -> Result { +/// its own compute-pool extras on top of the GPU-shape base pool. +pub(crate) fn required_blocks( + active_cores: u32, + clusters: u32, + pages: [u16; 2], + pairs: u8, +) -> Result { + let base = base_blocks(active_cores, clusters)?; let extra = compute_pool::extra_bytes(active_cores, pages[0])? .checked_add(compute_pool::extra_bytes(active_cores, pages[1])?) .and_then(|bytes| bytes.checked_mul(u64::from(pairs))) .ok_or(EOVERFLOW)?; - let bytes = extra.checked_add((RENDER_BLOCKS * FREE_LIST_BLOCK_SIZE) as u64) + let base_bytes = u64::try_from(base) + .ok() + .and_then(|blocks| blocks.checked_mul(FREE_LIST_BLOCK_SIZE as u64)) .ok_or(EOVERFLOW)?; + let bytes = extra.checked_add(base_bytes).ok_or(EOVERFLOW)?; let blocks = usize::try_from(bytes.div_ceil(FREE_LIST_BLOCK_SIZE as u64)) .map_err(|_| EOVERFLOW)?; let maximum = PAGE_LIST_SIZE / (FREE_LIST_BLOCK_PAGES as usize * 8); - if blocks > maximum { return Err(E2BIG); } + if blocks > maximum { + return Err(E2BIG); + } Ok(blocks) } + +#[kernel::macros::kunit_tests(asahi_g17_render_pool)] +mod tests { + use super::*; + + #[test] + fn one_and_two_cluster_parts_keep_default_floor() { + for (cores, clusters) in [(5, 1), (6, 1), (8, 1), (10, 1), (16, 2), (20, 2)] { + assert_eq!(base_blocks(cores, clusters), Ok(RENDER_BLOCKS)); + assert_eq!(required_blocks(cores, clusters, [0, 0], 1), Ok(RENDER_BLOCKS)); + } + } + + #[test] + fn multi_cluster_parts_scale_with_active_cores() { + // 32-core J616C (4 clusters): 96 blocks; 40-core J614C/J575C (4 clusters): 120 blocks. + assert_eq!(required_blocks(32, 4, [0, 0], 1), Ok(96)); + assert_eq!(required_blocks(40, 4, [0, 0], 1), Ok(120)); + // A small hypothetical >2-cluster part stays floored at RENDER_BLOCKS. + assert_eq!(required_blocks(8, 4, [0, 0], 1), Ok(RENDER_BLOCKS)); + // Eight-cluster M5 Ultra topologies (M5 allocates its own pools, but queue creation + // still checks required_blocks): 192 / 240 blocks, well within the table limit. + assert_eq!(required_blocks(64, 8, [0, 0], 2), Ok(192)); + assert_eq!(required_blocks(80, 8, [0, 0], 2), Ok(240)); + } + + #[test] + fn ray_query_scratch_adds_on_top_of_base_pool() { + // 64 pages per stage -> per_core = 64 + 1 + 8 = 73 pages = 299,008 bytes/core/stage. + assert_eq!(required_blocks(20, 2, [64, 64], 1), Ok(44 + 12)); + assert_eq!(required_blocks(32, 4, [64, 64], 1), Ok(96 + 19)); + assert_eq!(required_blocks(40, 4, [64, 64], 1), Ok(120 + 23)); + } + + #[test] + fn rejects_invalid_shape_and_oversized_pools() { + assert_eq!(required_blocks(0, 4, [0, 0], 1), Err(EINVAL)); + assert_eq!(required_blocks(32, 0, [0, 0], 1), Err(EINVAL)); + assert_eq!(required_blocks(400, 4, [0, 0], 1), Err(E2BIG)); + } +} diff --git a/drivers/gpu/drm/asahi/g17/fw/variant.rs b/drivers/gpu/drm/asahi/g17/fw/variant.rs index 59e9a5382cf8c0..5bd78e1e376968 100644 --- a/drivers/gpu/drm/asahi/g17/fw/variant.rs +++ b/drivers/gpu/drm/asahi/g17/fw/variant.rs @@ -36,6 +36,17 @@ pub(crate) enum InitGraph { V25G83, } +/// The InitData layouts of an M5 firmware build ([`super::m5::initdata`]). A build names its +/// layouts; the M5 graph builds them, and a build that names none is refused. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum M5Layouts { + /// The 26A428 graph: version word 0x0c8e_0339_8728_04c0 and its allocation sizes. + V26A428, + /// The 27.2 (26B123) graph: version word 0x0c8e_4339_8728_04c0, a larger power policy + /// (0x12728) and status config (0x790), the 26A428 HW data. + V26B123, +} + #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) enum QueueRegistration { Firmware, @@ -84,6 +95,9 @@ pub(crate) struct Variant { pub(crate) programs: super::render::RegisterPrograms, /// Use 0x1c890 = 1, 0x1c918 = 0 in V25G83-format tiling arrays (device/build policy). pub(crate) ta_mode_1: bool, + /// The normal maximum of a G17P tiler heap in blocks, which bounds host growth and the + /// firmware's own (device/build policy). + pub(crate) tvb_normal_blocks: usize, pub(crate) compute: super::compute::ComputeProgram, pub(crate) opening_record: bool, pub(crate) split_firmware_area: bool, @@ -96,11 +110,13 @@ pub(crate) struct Variant { /// work. The bare-metal M5 firmware powers the cores for work by its own policy: under a /// hold, the M5 Ultra's core-power witness reads unpowered until the hold is released. pub(crate) registration_power_hold: bool, + /// The InitData layouts the M5 graph must build for this firmware; `None` off M5. + pub(crate) m5_layouts: Option, /// A context takes its render pool identity when it is created, not at its first render, /// so that identities held by render graphs kept until the firmware stops refuse new /// contexts with an error instead of failing a context's first render. Set for the A18 - /// Pro only: the M4 Pro and Max keep the first-render claim until the claim at creation has - /// been tested on that hardware. + /// Pro and M4 Max (`25G83`/`26B123`); M4 Pro and M4 Max `25F84` keep the first-render + /// claim until tested on that hardware. pub(crate) render_id_at_create: bool, /// Cached descriptor storage, queue records and queue configuration that come back /// after their owner's release was consumed are reused once the firmware has consumed @@ -109,6 +125,9 @@ pub(crate) struct Variant { /// an M4 Pro crash on a recycled work state; extending this needs a create/destroy-heavy /// queue test on that hardware. pub(crate) objects_after_release: bool, + /// What the firmware reports in its statistics ring beyond utilisation + /// ([`crate::g17::telemetry::Protocol`]). + pub(crate) telemetry_protocol: crate::g17::telemetry::Protocol, } /// A firmware build a SoC supports, identified by its loaded TEXT. @@ -156,14 +175,17 @@ pub(crate) const V26A428: Variant = Variant { lead_commands: false, programs: super::render::RegisterPrograms::G17P, ta_mode_1: false, + tvb_normal_blocks: super::buffer::NORMAL_MAX_BLOCKS, compute: super::compute::ComputeProgram::G17P, opening_record: true, split_firmware_area: false, v26b123: false, m5_commands: false, registration_power_hold: true, + m5_layouts: None, render_id_at_create: true, objects_after_release: true, + telemetry_protocol: crate::g17::telemetry::Protocol::PSTATE_16MS, }; /// The M4 Pro firmware (25G83, `mBoot-18000.161.10`). @@ -197,14 +219,17 @@ pub(crate) const V25G83: Variant = Variant { lead_commands: true, programs: super::render::RegisterPrograms::V25G83, ta_mode_1: false, + tvb_normal_blocks: super::buffer::NORMAL_MAX_BLOCKS, compute: super::compute::ComputeProgram::G17P, opening_record: true, split_firmware_area: false, v26b123: false, m5_commands: false, registration_power_hold: true, + m5_layouts: None, render_id_at_create: false, objects_after_release: false, + telemetry_protocol: crate::g17::telemetry::Protocol::NONE, }; /// The 26A428 firmware of the M5 GPUs, which runs the M5 protocol (the M5 graph, queues and @@ -215,11 +240,19 @@ pub(crate) const V26A428_M5: Variant = Variant { traversal_exclusion: false, render_ray_query: false, registration_power_hold: false, + m5_layouts: Some(M5Layouts::V26A428), render_id_at_create: false, objects_after_release: false, + telemetry_protocol: crate::g17::telemetry::Protocol::PSTATE_8MS, ..V26A428 }; +/// The 27.2 M5 firmware (26B123): the 26A428 M5 protocol with the 26B123 InitData layouts. +pub(crate) const V26B123_M5: Variant = Variant { + m5_layouts: Some(M5Layouts::V26B123), + ..V26A428_M5 +}; + pub(crate) const V25F84: Variant = Variant { qid_floor: 0, registration: QueueRegistration::Mailbox, diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index 66fe9d80558f89..046910905418bc 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -179,6 +179,10 @@ pub(super) struct InitData { active_effort: u32, /// The M5 firmware build's layout, where [`Self::m5`]. graph: &'static super::fw::m5::initdata::Graph, + /// Power-policy layout of the M5 firmware build. + m5_policy: &'static crate::g17::fw::m5::initdata::M5PolicyMap, + /// Status-config layout of the M5 firmware build. + m5_status_config: &'static crate::g17::fw::m5::initdata::M5StatusConfigMap, 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. @@ -300,6 +304,8 @@ impl InitData { v26b123: false, active_effort: 0, graph: &super::fw::m5::initdata::M5_GRAPH, + m5_policy: &crate::g17::fw::m5::initdata::M5_26A428_POLICY, + m5_status_config: &crate::g17::fw::m5::initdata::M5_26A428_STATUS_CONFIG, outer_credits: None, _single_publisher: core::marker::PhantomData, aliases: KVec::new(), @@ -675,15 +681,17 @@ impl InitData { } /// M5 TA, fragment and compute share the compute outer ring per priority. - /// The physical queue claim prevents reassignment while this credit lives. + /// The caller must hold `Port::m5_outer`; the physical queue claim prevents + /// reassignment while this credit lives. pub(crate) fn reserve_outer(&self, priority: u8, count: u32) -> Result { if !self.m5 { return Err(EINVAL); } let cursors = self.work_cursors(priority, super::fw::queue::DataMaster::Compute)?; self.outer_credits.as_ref().ok_or(EIO)?.reserve(priority, count, cursors) } - /// Hold the device mutex for this scope, including its Drop. The result - /// borrows only the claim, allowing the caller to publish through Firmware. + /// Hold the device mutex for this scope, including its Drop, and serialize entry + /// and Drop under `Port::m5_outer` via `Port::outer_scope`. The result borrows + /// only the claim, allowing the caller to publish through Firmware. pub(crate) fn outer_scope<'a>(&self, claim: &'a mut OuterClaim) -> Result> { self.outer_credits.as_ref().ok_or(EINVAL)?.scope(claim) } @@ -853,16 +861,8 @@ impl InitData { Ok(values) } - /// Publishes an M5 compute record on the shared compute ring under the device mutex. - pub(super) fn publish_work( - &self, - priority: u8, - record: &super::fw::channels::WorkSlot, - ) -> Result { - self.publish_work_at(priority, record, None) - } - - /// [`Self::publish_work`] against the cursors of a room check made earlier under the same + /// Publishes an M5 compute record on the shared compute ring under the device mutex, + /// against the cursors of a room check made earlier under the same /// hold of the device mutex ([`Self::m5_compute_room`]), or a fresh read for None. pub(super) fn publish_work_at( &self, @@ -1076,6 +1076,8 @@ impl InitData { // The word recovery_state() reads: the status block moves with the firmware build. recovery: self.object(self.cluster)?.word(self.recovery_state_offset())?, mailbox, + m5_credits: self.outer_credits.clone(), + m5_history: self.m5_history_view()?, }) } @@ -1681,24 +1683,39 @@ impl InitData { /// (16.16); without one, its own controller raises the state for work that queues up behind /// the running command and otherwise lets it fall to the base state. /// - /// M5 publishes none while work streams, except while a host thread waits for it (`waited`): - /// then the full effort, so a submit-and-wait loop runs at the top state. - /// - /// The other G17 SoCs publish the full effort while a client has kept the GPU running + /// M5 publishes none while paced work streams, and publishes the full effort while either a + /// host thread waits for submitted work (`waited`) or a client has kept the GPU running /// without going idle for longer than the effort hold (`bound`, [`super::power::BusyRuns`]): - /// a submit-and-wait loop queues nothing behind its command, so the firmware alone keeps it - /// at the bottom state however busy the GPU is. Other work streams with the lowest effort - /// that keeps it above the base performance state ([`active_effort`]), and leaves the rest - /// to the firmware: work that the firmware let fall to the base state stalled the GPU under - /// concurrent load (a firmware recovery with no fault), and a full effort on every - /// submission held the top state whatever the load. A waiter doesn't tell paced work from a - /// submit-and-wait loop, because paced work has one too (the compositor, or the next frame's - /// fence). - pub(super) fn submission_effort(&self, effort: u32, waited: bool, bound: bool) -> u32 { + /// pipelined compute and render loops that keep the GPU continuously busy without blocking on + /// an unsignalled fence would otherwise fall to the base performance state. + /// + /// The other G17 SoCs publish the full effort while `bound` or while a host thread is waiting + /// on a pure-compute submission (`compute_waited`): a submit-and-wait loop queues nothing + /// behind its command, so the firmware alone keeps it at the bottom state however busy the GPU + /// is, and a compute burst resuming after a CPU gap longer than the 2 ms firmware idle-off + /// delay would otherwise run at [`active_effort`] for 16 ms before `BusyRuns::bound` fires. + /// Other work streams with the lowest effort that keeps it above the base performance state + /// ([`active_effort`]), leaving the rest to the firmware: work that the firmware let fall to + /// the base state stalled the GPU under concurrent load (a firmware recovery with no fault), + /// and a full effort on every submission held the top state whatever the load. A generic + /// render waiter doesn't tell paced work from a submit-and-wait loop, because paced work has + /// one too (the compositor, or the next frame's fence); pure-compute waiters exclude paced + /// render compositors. + pub(super) fn submission_effort( + &self, + effort: u32, + waited: bool, + bound: bool, + compute_waited: bool, + ) -> u32 { if self.m5 { - return if waited { effort } else { 0 }; + return if waited || bound { effort } else { 0 }; + } + if bound || compute_waited { + effort + } else { + effort.min(self.active_effort) } - if bound { effort } else { effort.min(self.active_effort) } } /// Writes the effort input in firmware order, then cleans its cache line to coherency. diff --git a/drivers/gpu/drm/asahi/g17/initdata/m5.rs b/drivers/gpu/drm/asahi/g17/initdata/m5.rs index 7b641965cdc701..7fc5443f44a7f0 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/m5.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/m5.rs @@ -52,15 +52,38 @@ impl InitData { ring(0), ring(1), ring(2), ring(3), page(canonical.start)] } - /// Diagnostic-only read of an aligned word within the existing policy allocation. - /// Callers hold the device state mutex, retaining this mapping for the entire sample. - pub(crate) fn m5_policy_telemetry_word(&self, offset: usize) -> Result { - if !self.m5 || offset & 3 != 0 - || offset.checked_add(4).is_none_or(|end| end > self.graph.policy_size) { - return Err(EINVAL); + /// Direct-port view of the M5 submission-history table (none off M5 or on common 26A428). + pub(super) fn m5_history_view(&self) -> Result> { + if !self.m5 || self.graph.is_common26() { + return Ok(None); } - let at = self.graph.shared.policy.checked_add(offset).ok_or(EINVAL)?; - Ok(self.object(self.bundle)?.word(at)?.load(Ordering::Relaxed)) + let private = self.object(self.cluster)?; + let base = self.graph.private.status_config; + let field = |offset| { + self.m5_status_config + .relocate(offset) + .map(|at| base + at) + .ok_or(EINVAL) + }; + let history = field(m::M5_STATUS_CONFIG_HISTORY)?; + Ok(Some(crate::g17::port::M5HistoryView { + generation: private.word(field(m::M5_STATUS_CONFIG_HISTORY_GENERATION)?)?, + config: [ + private.word(history)?, + private.word(history + 4)?, + private.word(history + 8)?, + private.word(history + 12)?, + ], + slots: private.pointer(field(m::M5_STATUS_CONFIG_HISTORY_SLOTS)?, 256)?, + })) + } + + /// Selects the power-policy layout of the M5 firmware build `build_m5` encodes for. + pub(in crate::g17) fn set_m5_policy_layouts( + &mut self, + layouts: crate::g17::fw::variant::M5Layouts, + ) { + self.m5_policy = m::m5_policy(layouts); } /// Counts `submissions` in the firmware's submission history, in the slot of this moment. @@ -70,18 +93,27 @@ impl InitData { // 26A428 one (0x6d0 bytes) has no such table. if self.graph.is_common26() { return Ok(()); } let private = self.object(self.cluster)?; - let base = m::M5_PRIVATE_LAYOUT.status_config; + let base = self.graph.private.status_config; + let field = |offset| { + self.m5_status_config + .relocate(offset) + .map(|at| base + at) + .ok_or(EINVAL) + }; + let history = field(m::M5_STATUS_CONFIG_HISTORY)?; + let generation_at = field(m::M5_STATUS_CONFIG_HISTORY_GENERATION)?; + let slots = field(m::M5_STATUS_CONFIG_HISTORY_SLOTS)?; for _ in 0..64 { - let generation = private.word(base + 0x74c)?.load(Ordering::Acquire); + let generation = private.word(generation_at)?.load(Ordering::Acquire); if generation & 1 != 0 { core::hint::spin_loop(); continue; } // The firmware moves the generation around every change of the geometry: while it // reads as it did, the geometry read under it stands, without four more loads. let (period, count) = match self.history_geometry.get() { Some((seen, period, count)) if seen == generation => (period, count), _ => { - let config = private.read_words::<4>(base + 0x73c)?; + let config = private.read_words::<4>(history)?; fence(Ordering::Acquire); - if generation != private.word(base + 0x74c)?.load(Ordering::Acquire) { + if generation != private.word(generation_at)?.load(Ordering::Acquire) { core::hint::spin_loop(); continue; } let period = u64::from(config[0]) | u64::from(config[1]) << 32; @@ -96,7 +128,7 @@ impl InitData { // One slot per 25000 ticks of the period. let index = (ticks % period) / 25_000; if index >= count { return Err(ERANGE); } - let byte = private.pointer(base + 0x750 + index as usize, 1)?; + let byte = private.pointer(slots + index as usize, 1)?; // SAFETY: retained, bounds-checked WC byte, written as a single byte // after reading the even, stable generation, as the firmware expects. unsafe { @@ -130,13 +162,25 @@ impl InitData { } } - pub(crate) fn build_m5(&mut self, dev: &AsahiDrmDevice, uat: &mmu::Uat, - id: &crate::regs::G17Id, board: &m::Board) -> Result { + /// Builds the M5 graph in the InitData layouts the loaded firmware build (`variant`) names. + pub(crate) fn build_m5( + &mut self, + dev: &AsahiDrmDevice, + uat: &mmu::Uat, + id: &crate::regs::G17Id, + board: &m::Board, + variant: &crate::g17::fw::Variant, + ) -> Result { use mmu::{PROT_FW_SHARED_RW as RW, PROT_FW_SHARED_RO as RO, PROT_GPU_SHARED_RW as GPU}; - self.m5 = true; - self.graph = board.graph; + let layouts = variant.m5_layouts.ok_or(EINVAL)?; let common26 = board.graph.is_common26(); + self.graph = if common26 { board.graph } else { m::m5_graph(layouts) }; + let profile = self.graph.profile; + let layout = profile.m5_layout().unwrap_or(&m::M5_LAYOUT_26A428); + self.m5_status_config = profile.m5_status_config(); + self.set_m5_policy_layouts(layouts); + self.m5 = true; // TA, fragment and compute share the compute work ring per priority; every // preparation's claim on it is counted from the first publication on. self.outer_credits = Some(super::outer_credit::Credits::new()?); @@ -146,8 +190,8 @@ impl InitData { KernelObject::new(dev, uat.kernel_vm(), Placement::At(address), size, mmu::PROT_FW_PRIV_RW, CpuMap::WriteBack) }; - let private = board.graph.private; - let shared = board.graph.shared; + let private = self.graph.private; + let shared = self.graph.shared; self.cluster = self.add(fixed(PRIVATE, private.total, RW)?)?; self.region_c = self.add(fixed(REGION_C, mmu::UAT_PGSZ, RO)?)?; self.roots = self.add(fixed(ROOTS, 0xc000, RO)?)?; @@ -173,7 +217,7 @@ impl InitData { Placement::In(uat.kernel_dynamic_range(), mmu::UAT_PGSZ as u64), mmu::UAT_PGSZ, mmu::PROT_FW_SHARED_RW, CpuMap::WriteCombined)?)?; } - let views = board.graph.profile.region_view_low_addrs(); + let views = profile.region_view_low_addrs(); self.alias(self.pb, uat.kernel_lower_vm(), views[0], GPU)?; self.alias(self.page_pool, uat.kernel_lower_vm(), views[1], GPU)?; let (low, high) = if common26 { @@ -210,7 +254,7 @@ impl InitData { .map_err(|_| EINVAL)?; } else { m::encode_m5_region_c(self.object_mut(self.region_c)?.bytes_mut()).map_err(|_| EINVAL)?; - m::encode_m5_private_cluster(PRIVATE, FWCTL, + m::encode_m5_private_cluster_for_profile(profile, PRIVATE, FWCTL, &mut self.object_mut(self.cluster)?.bytes_mut()[..private.total]).map_err(|_| EINVAL)?; } let windows = board.register_windows(); @@ -253,15 +297,32 @@ impl InitData { if common26 { m::encode_common26_bundle_policy(board, bindings, self.object_mut(self.bundle)?.bytes_mut()) } else { - m::encode_m5_bundle_policy(bindings, self.object_mut(self.bundle)?.bytes_mut()) + m::encode_m5_bundle_policy_for_layout(layout, bindings, self.object_mut(self.bundle)?.bytes_mut()) }.map_err(|_| EINVAL)?; - if let Some(defaults) = board.controller_defaults { + let controller_defaults = board.controller_defaults; + if let Some(defaults) = controller_defaults { defaults(self.object_mut(self.bundle)?.bytes_mut()).map_err(|_| EINVAL)?; let maximum = self.object(self.bundle)?.word(shared.policy + m::M5_POLICY_MAXIMUM_POWER)? .load(Ordering::Relaxed); m::set_m5_region_maximum_power(self.object_mut(self.region_c)?.bytes_mut(), maximum) .map_err(|_| EINVAL)?; } + // The policy encoders write the 26A428 layout; a build with another one gets it laid out + // in place, within its own allocation. + if !common26 { + let policy = self.m5_policy; + let policy_end = shared.policy.checked_add(policy.size).ok_or(EINVAL)?; + if policy_end > shared.block_68 { + return Err(EINVAL); + } + m::relayout_m5_policy( + policy, + board, + controller_defaults.is_some(), + &mut self.object_mut(self.bundle)?.bytes_mut()[shared.policy..policy_end], + ) + .map_err(|_| EINVAL)?; + } if let Some(microseconds) = board.idle_standby_us { m::set_m5_region_idle_standby(self.object_mut(self.region_c)?.bytes_mut(), microseconds) .map_err(|_| EINVAL)?; @@ -276,9 +337,8 @@ impl InitData { [PRIVATE + private.status_config as u64, PRIVATE + private.secondary_extra_1 as u64] }, }; - let profile = board.graph.profile; let channels = m::derive_channel_table_for_profile(profile, role, - PRIVATE + board.graph.state_grids[index] as u64, + PRIVATE + self.graph.state_grids[index] as u64, instance.status_a, instance.main_config, BUNDLE); let offset = shared.main_config[index]; m::encode_main_config_for_profile(profile, role, &addresses, &instance, diff --git a/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs b/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs index 08804ff1fc4989..58d0822f53dde1 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs @@ -9,7 +9,7 @@ use kernel::{prelude::*, sync::Arc}; const PRIORITIES: usize = 4; -pub(super) struct Credits { +pub(crate) struct Credits { reserved: [AtomicU32; PRIORITIES], published: [AtomicU64; PRIORITIES], consumers: [AtomicU64; PRIORITIES], @@ -24,7 +24,8 @@ pub(crate) struct OuterClaim { } /// Borrows the claim only. The caller must hold the device mutex from entry -/// through Drop: its temporarily lent credits are available to that publisher. +/// through Drop and serialize entry and Drop under `Port::m5_outer` (via +/// `Port::outer_scope`): its temporarily lent credits are available to that publisher. pub(crate) struct OuterScope<'a> { claim: &'a mut OuterClaim, before: u64, @@ -49,19 +50,23 @@ impl Credits { }, GFP_KERNEL)?) } - pub(super) fn available(&self) -> Arc { self.available.clone() } + pub(crate) fn available(&self) -> Arc { self.available.clone() } pub(super) fn waiting(&self) -> bool { self.available.has_waiters() } - pub(super) fn capacity(&self, priority: u8, cursors: [u32; 3]) -> Result { + pub(crate) fn is_scoped(&self) -> bool { + self.scoped.load(Ordering::Acquire) + } + + pub(crate) fn capacity(&self, priority: u8, cursors: [u32; 3]) -> Result { let pending = self.reserved.get(usize::from(priority)).ok_or(EINVAL)? .load(Ordering::Acquire); Ok(free(cursors)?.saturating_sub(pending)) } - /// Reserve under the sole publisher mutex. Off-lock cancellation may only + /// Reserve under the outer-ring lock. Off-lock cancellation may only /// reduce reserved counts, so the sampled capacity is conservative. - pub(super) fn reserve(self: &Arc, priority: u8, count: u32, + pub(crate) fn reserve(self: &Arc, priority: u8, count: u32, cursors: [u32; 3]) -> Result { if count == 0 || count >= WORK_RING_SLOTS { return Err(EINVAL); } @@ -75,6 +80,26 @@ impl Credits { Ok(OuterClaim { domain: self.clone(), priority: index, remaining: count }) } + /// Consumes one reserved slot for a direct M5 publication without touching + /// `published[]`, so an enclosing device-mutex `OuterScope` never debits a direct slot. + pub(crate) fn consume_direct(&self, claim: &mut OuterClaim) -> Result { + self.consume_direct_count(claim, 1) + } + + /// Consumes `count` reserved slots for a direct M5 publication without touching + /// `published[]`, so an enclosing device-mutex `OuterScope` never debits direct slots. + pub(crate) fn consume_direct_count(&self, claim: &mut OuterClaim, count: u32) -> Result { + if count == 0 || !core::ptr::eq(self, &*claim.domain) { + return Err(EINVAL); + } + if claim.remaining < count { + return Err(EIO); + } + claim.remaining -= count; + self.reserved[claim.priority].fetch_sub(count, Ordering::AcqRel); + Ok(()) + } + pub(super) fn scope<'a>(self: &Arc, claim: &'a mut OuterClaim) -> Result> { if !Arc::ptr_eq(self, &claim.domain) { return Err(EINVAL); } if self.scoped.swap(true, Ordering::AcqRel) { return Err(EBUSY); } @@ -116,6 +141,11 @@ impl OuterClaim { pub(crate) fn remaining(&self) -> u32 { self.remaining } + + /// Priority class of the reserved outer work ring. + pub(crate) fn priority(&self) -> usize { + self.priority + } } impl Drop for OuterClaim { @@ -128,3 +158,108 @@ impl Drop for OuterClaim { } } } + +#[kernel::macros::kunit_tests(asahi_g17_outer_credit)] +mod tests { + use super::*; + + #[test] + fn direct_consumption_does_not_debit_outer_scope() { + let credits = Credits::new().unwrap(); + let cursors = [0, 0, 0]; + let full = free(cursors).unwrap(); + let mut scoped_claim = credits.reserve(1, 2, cursors).unwrap(); + let mut direct_claim = credits.reserve(1, 1, cursors).unwrap(); + let mut direct_pair = credits.reserve(1, 2, cursors).unwrap(); + assert_eq!(credits.capacity(1, cursors).unwrap(), full - 5); + + // Direct publish consumes only its own reserved slots and leaves published[] untouched. + assert!(!credits.is_scoped()); + credits.consume_direct(&mut direct_claim).unwrap(); + assert_eq!(direct_claim.remaining(), 0); + credits.consume_direct_count(&mut direct_pair, 2).unwrap(); + assert_eq!(direct_pair.remaining(), 0); + assert_eq!(credits.capacity(1, cursors).unwrap(), full - 2); + assert_eq!(credits.counter(1).unwrap().load(Ordering::Acquire), 0); + + // An OuterScope taken afterward keeps its full 2 credits when nothing published via it. + { + let _scope = credits.scope(&mut scoped_claim).unwrap(); + assert!(credits.is_scoped()); + assert!(credits.reserve(1, 1, cursors).is_err()); + } + assert!(!credits.is_scoped()); + assert_eq!(scoped_claim.remaining(), 2); + drop(direct_claim); + drop(direct_pair); + drop(scoped_claim); + assert_eq!(credits.capacity(1, cursors).unwrap(), full); + } + + #[test] + fn mixed_render_compute_wrap_and_generation_change_with_queued_claim() { + let credits = Credits::new().unwrap(); + let n = WORK_RING_SLOTS; + // Producer sits two slots before wrap while both consumers lag 4 slots behind + // (free = WORK_RING_SLOTS - 5). + let mut consumer_a = n - 6; + let mut consumer_b = n - 6; + let mut producer = n - 2; + let cursors = [consumer_a, consumer_b, producer]; + let initial_free = free(cursors).unwrap(); + assert_eq!(initial_free, n - 5); + + // Interleave a queued 2-slot render claim with 1-slot compute claims across ring wrap. + let mut queued_render = credits.reserve(2, 2, cursors).unwrap(); + let mut compute_a = credits.reserve(2, 1, cursors).unwrap(); + credits.consume_direct(&mut compute_a).unwrap(); + producer = (producer + 1) % n; // n - 1 + assert_eq!( + credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(), + initial_free - 3, + ); + + let mut compute_b = credits.reserve(2, 1, [consumer_a, consumer_b, producer]).unwrap(); + credits.consume_direct(&mut compute_b).unwrap(); + producer = (producer + 1) % n; // 0 (wrapped!) + assert_eq!(producer, 0); + + // Fill remaining capacity so exactly 1 free slot remains; 2-slot render must fail EBUSY + // while 1-slot compute still succeeds across the wrap boundary. + let rem = credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(); + let filler = credits.reserve(2, rem - 1, [consumer_a, consumer_b, producer]).unwrap(); + assert_eq!(credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(), 1); + assert_eq!(credits.reserve(2, 2, [consumer_a, consumer_b, producer]).err(), Some(EBUSY)); + let mut edge_compute = credits.reserve(2, 1, [consumer_a, consumer_b, producer]).unwrap(); + credits.consume_direct(&mut edge_compute).unwrap(); + producer = (producer + 1) % n; // 1 + assert_eq!(credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(), 0); + drop(filler); + + // Consumers advance across the wrap boundary and report progress. + consumer_a = 1; + consumer_b = 1; + let wrapped = [consumer_a, consumer_b, producer]; + assert!(credits.progressed(2, wrapped).unwrap()); + assert_eq!(credits.capacity(2, wrapped).unwrap(), (n - 1) - 2); + + // Simulate locked render / recovery entering OuterScope while a queued compute claim + // waits across a generation change: new reserves fail EBUSY and direct consumption never + // debits OuterScope's published counter; dropping the queued claim after the generation + // change releases its reserved credits cleanly. + let queued_compute = credits.reserve(2, 1, wrapped).unwrap(); + { + let _scope = credits.scope(&mut queued_render).unwrap(); + assert!(credits.is_scoped()); + assert_eq!(credits.reserve(2, 1, wrapped).err(), Some(EBUSY)); + credits.counter(2).unwrap().fetch_add(2, Ordering::AcqRel); + } + assert!(!credits.is_scoped()); + assert_eq!(queued_render.remaining(), 0); + // Generation changed before queued_compute published: dropping it returns its credit. + assert_eq!(queued_compute.remaining(), 1); + drop(queued_compute); + drop(queued_render); + assert_eq!(credits.capacity(2, wrapped).unwrap(), n - 1); + } +} diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index b6536c07b443f9..4d6f8678719e67 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -37,6 +37,13 @@ pub(crate) enum Engine { } impl Engine { + pub(crate) fn of(command: &Validated) -> Self { + match command { + Validated::Render { .. } => Self::Render, + Validated::Compute { .. } => Self::Compute, + } + } + pub(crate) fn index(self) -> usize { match self { Self::Render => 0, @@ -176,10 +183,7 @@ impl Packet { } pub(crate) fn engine(&self) -> Engine { - match &self.command { - Validated::Render { .. } => Engine::Render, - Validated::Compute { .. } => Engine::Compute, - } + Engine::of(&self.command) } /// Replay holds the device mutex. Its original inputs were satisfied before @@ -270,6 +274,7 @@ impl Packet { } pub(crate) fn request_cancel(&self) -> bool { self.cancelled.store(true, Ordering::Release); + self.completion.clear_source_published(); self.publication .compare_exchange(0, 3, Ordering::AcqRel, Ordering::Acquire) .is_ok() @@ -323,7 +328,7 @@ pub(crate) trait Backend: Send + Sync { /// The device accepts command submission (an M5 GPU before its queues take submission /// does not). fn supports_submission(&self) -> bool { true } - /// Whether this backend's scheduler workers run in their queue creator's cluster (M5). + /// Whether this backend's scheduler workers run in their queue creator's cluster. fn creator_cluster_scheduling(&self) -> bool { false } /// Whether to keep compute input completion waits and wait on the host for other-engine /// prefix producers: without the G17D forms an M5 kick may start while its ring @@ -541,6 +546,7 @@ pub(crate) struct Scheduler { #[derive(Clone)] pub(crate) struct Fences { pub(crate) ready: Fence, + pub(crate) scheduled: Fence, pub(crate) completed: Fence, pub(crate) publication: Option>, pub(crate) owner: Arc, @@ -553,6 +559,13 @@ impl super::dependency::Retention for Fences { } impl Fences { + /// The command has an ordered host publication, or writes host timestamps and so is ready + /// only once it has completed and the host has written them (see `Scheduler::enqueue`). + /// Only such a command can be a same-engine predecessor or host wait of a later one. + pub(crate) fn publishes(&self) -> bool { + self.publication.is_some() || self.ready.raw() == self.completed.raw() + } + /// Scheduler::enqueue always supplies our explicit completion fence here. /// It has no polling callback, so pending frontier checks need no lock. pub(crate) fn status(&self) -> i32 { @@ -578,16 +591,21 @@ impl Scheduler { Engine::Compute => (COMPUTE_CREDITS, c_str!("aurora_g17_compute")), }; let device = dev.as_ref().as_ref(); - let submit = if backend.creator_cluster_scheduling() { + // Run drm_sched's submit worker at WQ_HIGHPRI so host-waited jobs (such as + // query-access computes unblocked by completion events) are not delayed in + // CFS behind busy game/render threads. + let queue = workqueue::OwnedQueue::new_ordered_highpri_reclaim(name)?; + if backend.creator_cluster_scheduling() { // The run and free work stays in the creating CPU's cluster, as the event work // follows the submitter, instead of wherever an unbound worker last ran. - let queue = workqueue::OwnedQueue::new_ordered_reclaim(name)?; - queue.restrict(Cpumask::cluster_of(CpuId::current()))?; - Some(queue) - } else { - // drm_sched allocates its own ordered reclaim-safe queue. - None - }; + let cluster = Cpumask::cluster_of(CpuId::current()); + // Without a cpu-map in the device tree each CPU is its own cluster: the queue then + // stays unrestricted rather than tied to the one CPU that created it. + if cluster.weight() > 1 { + queue.restrict(cluster)?; + } + } + let submit = Some(queue); let scheduler = sched::Scheduler::new_with_queues( device, 1, credits, 0, TIMEOUT_MS, name, submit, Some(backend.fence_queue()), )?; @@ -611,14 +629,9 @@ impl Scheduler { super::trace::schedule(&packet, 0, dependency_count as i32); let completed = packet.completion.fence(); let host_timestamps = packet.completion.has_timestamps(); - // Only commands which actually write timestamps become host-prefix - // producers. Ordinary consumers retain the scheduled ready fence and - // their existing firmware dependency path for cross-engine overlap. - let host_publication = if host_timestamps { - packet.completion.publication() - } else { - None - }; + // Expose any ordered publication so later commands that overlap execution + // with this command still order their completion and error propagation. + let host_publication = packet.completion.publication(); if self.allowance_ms > super::timeout::DEFAULT_ALLOWANCE_MS { packet.allowance_end.store(u64::MAX, Ordering::Relaxed); } @@ -642,10 +655,11 @@ impl Scheduler { if let Some(publication) = publication { publication.activate(); } + let scheduled = job.fences().scheduled(); let ready = if host_timestamps { completed.clone() } else { - job.fences().scheduled() + scheduled.clone() }; // All fallible scheduler setup precedes early hardware publication. The // scheduler still owns watchdog, credits and cancellation after push. @@ -666,7 +680,7 @@ impl Scheduler { self.backend.count_backlog(&packet); } job.push(); - Ok(Fences { ready, completed, publication: host_publication, owner: packet.completion.clone() }) + Ok(Fences { ready, scheduled, completed, publication: host_publication, owner: packet.completion.clone() }) } } diff --git a/drivers/gpu/drm/asahi/g17/kick.rs b/drivers/gpu/drm/asahi/g17/kick.rs index 5f49bf1b5093d8..43e1115f221f09 100644 --- a/drivers/gpu/drm/asahi/g17/kick.rs +++ b/drivers/gpu/drm/asahi/g17/kick.rs @@ -56,8 +56,9 @@ const _: () = { assert!(queue_limit(0) == crate::mmu::MAX_EXECUTION_CONTEXTS); // Compute keeps this many channels even with every execution context open. assert!(QID_COUNT - FULL_RENDER_RESERVE >= 4); - // The reserve counts one pair per owner. A second pair of an owner comes - // only from surplus (g17::pairs), never from this reserve. + // Future queue headroom caps at one pair per execution context; compute + // reservation still protects current pair demand (including live siblings + // and teardown-held released pairs) above that cap. assert!(FULL_RENDER_RESERVE == 2 * crate::mmu::MAX_EXECUTION_CONTEXTS as usize + 2); }; @@ -130,7 +131,7 @@ impl QueueIds { engine: DataMaster, preferred: Option, ) -> Result { - self.reserve_for(owner, engine, preferred, crate::mmu::MAX_EXECUTION_CONTEXTS as usize) + self.reserve_for(owner, engine, preferred, queue_limit(self.floor) as usize) } fn render_ids(&self) -> usize { @@ -141,10 +142,18 @@ impl QueueIds { .count() } + /// Total dedicated render pairs the QID table can hold beside the + /// bootstrap reservations and installed compute channels. + pub(crate) fn render_pair_capacity(&self) -> usize { + (self.render_ids() + (QID_COUNT - self.floor - self.leased)) + .saturating_sub(2) + / 2 + } + /// Whether `queues` open logical queues can each still install a dedicated /// render pair, beside the bootstrap reservations and installed compute. pub(crate) fn render_fits(&self, queues: usize) -> bool { - self.render_ids() + (QID_COUNT - self.floor - self.leased) >= 2 * queues + 2 + self.render_pair_capacity() >= queues } /// Whether a render pair not yet built can still reserve both of its identities. @@ -155,22 +164,38 @@ impl QueueIds { /// Whether a fresh compute identity fits beside the render reserve of /// `queues` open logical queues, without reserving it. pub(crate) fn compute_fits(&self, queues: usize) -> bool { + self.compute_fits_with_reclaim(queues, 0) + } + + /// Whether a fresh compute identity fits once `reclaim_render_ids` + /// unpublished render identities are cancelled first. + pub(crate) fn compute_fits_with_reclaim( + &self, + queues: usize, + reclaim_render_ids: usize, + ) -> bool { let initial = self.leased == QID_COUNT - self.floor && self.initial_render.iter().flatten().any(|id| self.can_cancel_unpublished(*id)); - self.compute_room(queues, usize::from(initial)) + self.compute_room(queues, usize::from(initial).max(reclaim_render_ids)) } - fn compute_room(&self, queues: usize, replacement: usize) -> bool { + fn compute_room(&self, pairs: usize, replacement: usize) -> bool { // Existing render identities already satisfy this reservation. Counting // them twice can refuse compute even while physical QIDs remain free. // Replacing an initial reservation consumes one render identity. // Include that transition when protecting render's minimum, and // count the replacement as available compute capacity. + // + // Cap future queue headroom at `FULL_RENDER_RESERVE - self.floor`, but + // always protect every pair in current demand (`2 * pairs + 2`) so + // compute cannot strand an open queue when live siblings or + // teardown-held pairs push demand above `queue_limit(self.floor)`. let render = self.render_ids(); + let current = 2 * pairs + 2; + let with_headroom = render_reserve(pairs).min(FULL_RENDER_RESERVE - self.floor); + let reserve = current.max(with_headroom); QID_COUNT - self.floor - self.leased + replacement - > render_reserve(queues) - .min(FULL_RENDER_RESERVE - self.floor) - .saturating_sub(render - replacement) + > reserve.saturating_sub(render.saturating_sub(replacement)) } /// As [`Self::reserve`], with the compute reserve sized for `queues` open @@ -388,6 +413,46 @@ mod accounting_tests { assert_eq!(ids.leased, QID_COUNT); assert_eq!(ids.reserve(1002, DataMaster::Fragment, None), Err(EINVAL)); } + + #[test] + fn compute_reserve_protects_sibling_demand_above_context_limit() { + let mut ids = table(); + ids.reserve_initial_render().unwrap(); + let max = crate::mmu::MAX_EXECUTION_CONTEXTS as usize; + // 58 open queues + 1 live sibling = 59 pairs demand (above MAX_EXECUTION_CONTEXTS). + let demand = max + 1; + // Install 57 first pairs + 1 sibling = 58 pairs (116 render IDs) plus 2 bootstrap IDs. + let mut owner = 100u64; + for _ in 0..max { + let t = ids.reserve_for(owner, DataMaster::Tiling, None, demand).unwrap(); + ids.publish(t).unwrap(); + owner += 1; + let f = ids.reserve_for(owner, DataMaster::Fragment, None, demand).unwrap(); + ids.publish(f).unwrap(); + owner += 1; + } + // Compute takes all remaining QIDs except the 2 needed for the 58th queue's first pair. + let compute_budget = QID_COUNT - (2 * demand + 2); + for _ in 0..compute_budget { + let c = ids.reserve_for(owner, DataMaster::Compute, None, demand).unwrap(); + ids.publish(c).unwrap(); + owner += 1; + } + assert_eq!(ids.render_pair_capacity(), demand); + assert!(!ids.compute_fits(demand)); + assert_eq!( + ids.reserve_for(owner, DataMaster::Compute, None, demand), + Err(ENOSPC) + ); + // The last open queue can still install its first pair. + assert!(ids.render_pair_fits()); + let t = ids.reserve_for(owner, DataMaster::Tiling, None, demand).unwrap(); + let f = ids + .reserve_for(owner + 1, DataMaster::Fragment, None, demand) + .unwrap(); + ids.publish(t).unwrap(); + ids.publish(f).unwrap(); + } } // Aliases drop before their backing. A compute queue is allocated low first; @@ -410,7 +475,7 @@ struct RenderStorage { // The lower alias drops before its backing. low: mmu::KernelMapping, high: KernelObject, - /// The client VM the storage was created for, whose alias of it lasts as long as that VM. + /// The client VM the storage was created for, or last handed to. vm: u64, /// That VM's status, which tells when its client closed it. status: Option>, @@ -425,13 +490,11 @@ impl RenderStorage { /// Render ring storage outlives its rings for the life of the device. /// -/// A client VM keeps each render ring alias it installs until the VM closes, -/// while an installed pair whose identities were never published can be -/// reclaimed and its rings dropped. Freeing that storage would hand its shared -/// lower address to another ring; a client still aliasing the old pages there -/// that later receives the new ring could not alias it (`prepare_client_alias` -/// fails with EFAULT). Retired storage is therefore kept and reused by later -/// rings: an address keeps naming the same pages, so every alias stays valid. +/// An installed pair whose identities were never published can be reclaimed +/// and its rings dropped. Retired storage is kept and reused by later rings, so +/// a ring's shared lower address keeps naming the same pages. A client's views +/// of a ring belong to the render pair holding it (`Pair::client_kicks`), +/// which drops them before the ring, so no VM has a view of retired storage. #[pin_data] pub(crate) struct RenderRings { #[pin] @@ -461,8 +524,7 @@ impl RenderRings { } /// Reusable storage created for `client`, else storage whose VM its client has closed, - /// which then belongs to `client`. Storage of another open VM is never handed out: that VM - /// keeps its read-write alias of the pages, so it could read and write the new ring. + /// which then belongs to `client`. Storage of another open VM is never handed out. fn take(&self, client: &mmu::Vm) -> Option { let vm = client.id(); let mut stock = self.stock.lock(); @@ -518,8 +580,8 @@ impl Drop for RenderRing { } } -/// An installed queue's permanent ring. Client aliases are held by the bound -/// context graph and must be dropped before this object. +/// An installed queue's permanent ring. A render ring's client views are held by its pair +/// for its time in their VM and must be dropped before this object. pub(crate) struct Queue { backing: Backing, id: Id, @@ -587,9 +649,9 @@ impl Queue { }) } - /// Retired storage of a never-written ring is reused first. Its address - /// names the same pages in every client that aliases it, so an existing - /// alias in `client` is kept (None) and a missing one is created. + /// Retired storage of a never-written ring is reused first. The returned view of the ring + /// in `client` is new: views belong to the pair that holds the ring, which drops them before + /// the ring, so retired storage has none. pub(crate) fn render( alloc: &Allocator<'_>, id: Id, @@ -613,8 +675,9 @@ impl Queue { ring.storage .high .prepare_alias(client, address, CLIENT_KICK_PROT, false); - // On failure the storage returns to the stock and a fresh ring is built. - if let Ok(alias) = alias { + // On failure, or if `client` still had a view of the pages, the storage returns to + // the stock and a fresh ring is built. + if let Ok(Some(alias)) = alias { return Ok(( Self { backing: Backing::Render(ring), @@ -622,7 +685,7 @@ impl Queue { timestamp: KickTimestamp::FIRST, previous: None, }, - alias, + Some(alias), )); } } @@ -736,7 +799,7 @@ impl Queue { Ok(()) } - /// Reuse a permanent client view only when every page names this ring. + /// Reuse the pair's client view only when every page names this ring. pub(crate) fn prepare_client_alias(&self, vm: &mmu::Vm) -> Result> { let object = match &self.backing { Backing::Compute { low, .. } => low, diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index d923272a9a18d5..3a6430feaa1337 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -34,7 +34,7 @@ mod completion; pub(crate) mod context; mod data_segment; mod dependency; -mod sync_input; +pub(crate) mod sync_input; pub(crate) mod exec_share; pub(crate) mod sync_output; mod trace; @@ -85,7 +85,7 @@ use kernel::{ c_str, device::{self, Core}, drm::gem::shmem, - impl_has_delayed_work, impl_has_work, + impl_has_delayed_work, impl_has_hr_timer, impl_has_work, io::{ IoBase, IoSysMap, @@ -97,13 +97,19 @@ use kernel::{ sync::{ aref::ARef, Arc, + ArcBorrow, CondVar, Mutex, // }, time::{ delay::fsleep, + hrtimer::{ + ArcHrTimerHandle, HrTimer, HrTimerCallback, HrTimerCallbackContext, HrTimerPointer, + HrTimerRestart, RelativeMode, + }, msecs_to_jiffies, - Delta, // + Delta, + Monotonic, // }, types::{ForeignOwnable, Opaque}, uapi, @@ -273,15 +279,12 @@ pub(crate) struct CoreLayout { /// Where a G17 target's crash log buffers live. pub(crate) enum CrashBuffers { - /// One buffer per [`Role`] that the firmware requests at a fixed address of the kernel - /// lower root, mapped by the driver before the coprocessors start. - Fixed([FixedBuffer; 2]), /// The firmware places its crash log in its own data segment, the `fw-data` reserved /// region, and asks for it there by physical address. FirmwareData, /// As [`CrashBuffers::FirmwareData`] when the boot loader describes the data segment as - /// the `fw-data` region. A boot loader that does not gets the driver's own buffers, as - /// [`CrashBuffers::Fixed`], at the low bits of the physical address the firmware asks for; + /// the `fw-data` region. A boot loader that does not gets the driver's own buffers, one per + /// [`Role`], at the low bits of the physical address the firmware asks for; /// the firmware does not write its crash log there. FirmwareDataOrFixed([FixedBuffer; 2]), } @@ -369,12 +372,22 @@ pub(crate) struct CrashLog { /// The CPU mapping of a crash log buffer. enum CrashLogMap { - /// The driver's buffer ([`CrashBuffers::Fixed`]). + /// The driver's buffer ([`CrashBuffers::FirmwareDataOrFixed`]). Object(shmem::VMapOwned), /// A buffer in the firmware's data segment ([`CrashBuffers::FirmwareData`]). FirmwareData(data_segment::DataSegmentLog), } +impl CrashLog { + /// Map only the range firmware requested within its loader-reserved data. + pub(crate) fn from_firmware(dev: &device::Device, iova: usize, size: usize) -> Result { + Ok(Self { + iova, + map: CrashLogMap::FirmwareData(data_segment::DataSegmentLog::map(dev, iova, size)?), + }) + } +} + impl rtkit::Buffer for CrashLog { fn iova(&self) -> Result { Ok(self.iova) @@ -483,14 +496,7 @@ impl rtkit::Operations for RoleOps { }); } // The firmware places its buffers in its data segment, at their physical address. - Ok(CrashLog { - iova, - map: CrashLogMap::FirmwareData(data_segment::DataSegmentLog::map( - &data.shared.dev, - iova, - size, - )?), - }) + CrashLog::from_firmware(&data.shared.dev, iova, size) } } @@ -562,7 +568,6 @@ impl Coprocessor { ) -> Result { let index = role as usize; let fixed = match &cfg.crash_buffers { - CrashBuffers::Fixed(buffers) => Some(buffers), CrashBuffers::FirmwareData => None, CrashBuffers::FirmwareDataOrFixed(buffers) => { let described = data_segment::described(dev.as_ref().as_ref()); @@ -847,6 +852,7 @@ impl Drop for Firmware { } self.primary.stop(); self.port.set_effort_full(false); + self.primary.state.shared.set_full_effort_published(false); self.pool.stop_after_firmware(); // RTKit destruction releases the mailbox power references. Clear the bridge while // those references still keep the register block powered. @@ -855,6 +861,11 @@ impl Drop for Firmware { } impl Firmware { + /// The firmware's fixed timestamp window, on the older firmware graph; `None` on M5's graph. + fn timestamp_window(&self) -> Option> { + (!self.uat.is_m5()).then_some(hw::t8140::dynamic::TIMESTAMP_WINDOW) + } + /// The firmware instances this GPU runs. fn roles(&self) -> &'static [Role] { if self.secondary.is_some() { @@ -900,21 +911,10 @@ impl Firmware { power::release(self) } - /// Retry a temporarily unavailable transaction once under a registration - /// power hold. Other access errors propagate to the retained owner. - fn submit_m5_work(&mut self, submission: &fw::m5::queue::HardwareSubmission) -> Result { - match self.bridge.regs.submit_m5_work(submission) { - Err(error) if error == EAGAIN => { - self.acquire_registration_power()?; - self.bridge.regs.submit_m5_work(submission) - } - result => result, - } - } - /// Both outer slots and their capacity are checked before any host-port - /// write. An EAGAIN retry drops the old views and revalidates them under a - /// power hold. After a successful transaction, publication is infallible. + /// write. The host command port needs no core power, and its transaction + /// fails only once the register mapping is gone; the error propagates. + /// After a successful transaction, publication is infallible. fn submit_m5_render_pair( &mut self, priority: u8, @@ -925,36 +925,27 @@ impl Firmware { deferred: bool, cursors: Option<[u32; 3]>, ) -> Result<[u32; 2]> { - let mut commit_accounting = Some(commit_accounting); - let mut publish_inner = Some(publish_inner); - let mut cursors = cursors; - for attempt in 0..2 { - let pair = self.init.m5_work_pair(priority, &records[0], &records[1], cursors.take())?; - pair.prepare(); - if let Some(commit) = commit_accounting.take() { commit()?; } - match self.bridge.regs.submit_m5_work(submission) { - Err(error) if error == EAGAIN && attempt == 0 => { - drop(pair); - self.acquire_registration_power()?; - } - Err(error) => return Err(error), - Ok(()) => { - if let Some(publish) = publish_inner.take() { publish(); } - return Ok(if deferred { pair.next() } else { pair.publish() }); - } - } - } - Err(EAGAIN) + let pair = self.init.m5_work_pair(priority, &records[0], &records[1], cursors)?; + pair.prepare(); + commit_accounting()?; + self.bridge.regs.submit_m5_work(submission)?; + publish_inner(); + Ok(if deferred { pair.next() } else { pair.publish() }) } /// Called at actual submission publication, not while a queued job is merely being built. fn note_submission(&mut self) -> Result { + let now = now_ns(); self.primary.state.shared.note_submitter(); self.port.note_gpu_activity(); self.primary.state.shared.note_gpu_activity(); self.effort.submit(); - self.effort.note_waiters(now_ns(), fence::waiters()); + self.effort.note_waiters(now, fence::waiters()); + self.effort.note_compute_waiters(now, fence::compute_waiters()); self.effort.note_bound(self.primary.state.shared.feed.busy_run()); + if self.effort.bound() { + self.port.lift_busy_if_below_top(now); + } self.apply_effort(power::FULL_EFFORT) } @@ -974,6 +965,11 @@ impl Firmware { if self.effort.applied() != 0 && thermal::requested() { self.governor.note_activity(now); } + // Without the budget controller only the fan assistance runs (FanBoost::apply). + if !thermal::enabled() { + let busy = thermal::requested() && self.governor.recent_activity(now); + return (busy || fans, thermal::CpuAdvice::Release, busy); + } let Ok(current) = self.init.m5_power_budget() else { return (false, thermal::CpuAdvice::Release, false); }; @@ -1000,10 +996,17 @@ impl Firmware { } fn apply_effort(&mut self, effort: u32) -> Result { - Self::apply_shared_effort(&self.init, &mut self.effort, &self.port, effort) + Self::apply_shared_effort( + &self.primary.state.shared, + &self.init, + &mut self.effort, + &self.port, + effort, + ) } fn apply_shared_effort( + shared: &Shared, init: &initdata::InitData, state: &mut power::Effort, port: &port::Port, @@ -1011,8 +1014,14 @@ impl Firmware { ) -> Result { // The performance-controller demand follows the requested effort; the firmware is // given, and the state records, the published value (InitData::submission_effort). - let published = init.submission_effort(effort, state.waited(), state.bound()); + let published = init.submission_effort( + effort, + state.waited(), + state.bound(), + state.compute_waited(), + ); port.set_effort_full(effort == power::FULL_EFFORT); + shared.set_full_effort_published(published == power::FULL_EFFORT); if state.applied() == published { // M5 maps region C read-only to the firmware: once confirmed, the word holds // `applied` without reading it back. @@ -1053,11 +1062,18 @@ impl Firmware { self.effort.submit(); } // A waiter or a busy run that began or ended since the last note moves the effort while - // work streams. + // work streams. Skip a redundant Region C drop right before Effort::idle clears it to 0. if self.effort.streaming() { let waiters = self.effort.note_waiters(now_ns, fence::waiters()); + let compute_waiters = self + .effort + .note_compute_waiters(now_ns, fence::compute_waiters()); let bound = self.effort.note_bound(self.primary.state.shared.feed.busy_run()); - if waiters || bound { + if self.effort.bound() { + self.port.lift_busy_if_below_top(now_ns); + } + let active = in_flight || submitted; + if (waiters || compute_waiters || bound) && !self.effort.will_clear(now_ns, active) { self.apply_effort(power::FULL_EFFORT)?; } } @@ -1076,12 +1092,14 @@ impl Firmware { } power::IdleAction::Recheck(delay) => Some(delay), }; - Ok( - match (effort, self.idle_hold(now_ns, in_flight || submitted)) { - (Some(a), Some(b)) => Some(a.min(b)), - (a, b) => a.or(b), - }, - ) + let busy_recheck = if in_flight { + self.port.report_busy(now_ns); + self.port.busy_recheck_delay(now_ns) + } else { + None + }; + let hold = self.idle_hold(now_ns, in_flight || submitted); + Ok([effort, hold, busy_recheck].into_iter().flatten().min()) } /// Drives the idle hold (see power::Hold); returns the delay in ns for its next check. A @@ -1178,6 +1196,28 @@ const RETIRED_FEATURES: u64 = (uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE | uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES) as u64; const _: () = assert!(M5_FEATURES & RETIRED_FEATURES == 0); +/// The compute channel features of a GPU whose logical compute queues each hold up to `channels` +/// physical compute channels ([`pairs::compute_channels_per_owner`]): with more than one, the +/// kernel fans independent compute commands out itself. +fn compute_channel_features(channels: u8) -> u64 { + if channels > 1 { + crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL + } else { + 0 + } +} + +/// Whether the firmware keeps partial renders (tiler-heap overflow fragment passes) strictly +/// ordered behind earlier fragment work: advertised where `fragment_busy` drains an outstanding +/// fragment pass on the pair and each logical render queue uses a single physical render pair. +fn ordered_partial_renders_feature(fragment_busy: bool, render_pairs: u8) -> u64 { + if fragment_busy && render_pairs == 1 { + uapi::DRM_ASAHI_FEATURE_ORDERED_PARTIAL_RENDERS as u64 + } else { + 0 + } +} + /// Event work item ID. const EVENT_WORK: u64 = 0; /// Short control/retirement polls do not wait behind the longer idle deadline. @@ -1187,6 +1227,42 @@ const GROW_WORK: u64 = 3; const RECLAIM_WORK: u64 = 4; const FEED_WORK: u64 = 5; const GOVERNOR_WORK: u64 = 6; +/// Deferred housekeeping deadline when a completion drained the last in-flight work within +/// `HOUSEKEEPING_NS`. +const HOUSEKEEPING_WORK: u64 = 7; + +/// `CondVar` wrapper that tracks active waiters so `notify_all()` skips the waitqueue lock +/// in the common zero-waiter steady state. +#[pin_data] +struct TrackedCondVar { + #[pin] + condvar: CondVar, + waiters: AtomicU32, +} + +impl TrackedCondVar { + fn wait_timeout( + &self, + guard: &mut kernel::sync::MutexGuard<'_, T>, + timeout: kernel::time::Jiffies, + ) -> kernel::sync::CondVarTimeoutResult { + struct Waiter<'a>(&'a AtomicU32); + impl Drop for Waiter<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::Release); + } + } + self.waiters.fetch_add(1, Ordering::SeqCst); + let _waiter = Waiter(&self.waiters); + self.condvar.wait_timeout(guard, timeout) + } + + fn notify_all(&self) { + if self.waiters.load(Ordering::SeqCst) != 0 { + self.condvar.notify_all(); + } + } +} /// Device state shared with the coprocessor callbacks and the event worker. #[pin_data] @@ -1200,6 +1276,9 @@ struct Shared { clusters: u32, active_cores: u32, variant: &'static fw::Variant, + /// Highest valid performance state index for 0x1b telemetry reports, derived from the + /// state-frequency table. + max_pstate: u32, /// Layout of compute queues' operand-state buffers for this GPU's cores. operand_state: &'static fw::compute::OperandState, /// The M5 board ([`Config::m5`]) of an M5 profile. @@ -1255,10 +1334,25 @@ struct Shared { housekeeping_ns: AtomicU64, #[pin] poll: DelayedWork, + /// Active retirement rescan hrtimer, replacing 1-jiffy delayed-work waits while GPU work + /// stays in flight. + rescan_stopped: AtomicBool, + rescan_deadline_ns: AtomicU64, + #[pin] + rescan: HrTimer, + #[pin] + rescan_handle: Mutex>>, #[pin] idle: DelayedWork, + #[pin] + housekeeping_timer: DelayedWork, /// M5: the thermal governor runs (the firmware has the host power budget word). governs: bool, + /// Non-M5 submission-capable device registered for compute-waiter effort wakeups. + tracks_effort_wake: bool, + /// Region C currently holds FULL_EFFORT; mirrored with `BELOW_FULL_COUNT` under + /// `EFFORT_TARGETS` so steady-state compute waits take no lock. + full_effort_published: AtomicBool, #[pin] governor: DelayedWork, governor_armed: AtomicBool, @@ -1266,15 +1360,24 @@ struct Shared { /// step). Publishers without the device mutex set it too. governor_activity_ns: AtomicU64, /// The queue of all work that signals job fences: the event work, and every scheduler's - /// timeout work. Memory reclaim may wait on those fences, so it is reclaim-safe. On M5 it is - /// unbound, so the event work runs in the affinity pod (the L2) of the CPU that last - /// published work, not on whichever CPU the completion IRQ thread first ran on; on a two-die - /// part that keeps completion processing on the submitter's die. Elsewhere it is per-CPU and - /// high priority, as `system_highpri_wq`. + /// timeout work. Memory reclaim may wait on those fences, so it is reclaim-safe, and it is + /// high priority, as `system_highpri_wq`. The event work runs in the cluster of the CPU that + /// last published work (see `queue_event_records`); [`Self::new_events_queue`] says where in + /// it. events: Arc, - /// M5: the event work and the scheduler workers follow the submitting CPU. - follows_submitter: bool, - /// M5: the CPU of the last publication, `u32::MAX` before the first. + /// Preallocated completion collector owned exclusively by `run_runtime_events`. + #[pin] + worker_deferred: Mutex>, + /// Collector, as large as the event worker's, for the observation a render borrower owes the + /// pair it puts back (`Backend::render_direct`). Taken only with `try_lock`, so no borrower + /// waits for another, and finished after the device mutex is released. + #[pin] + render_collector: Mutex, + /// Restrict each scheduler's ordered submit queue to the creating CPU's cluster, beside the + /// event work. Single-die M5 parts leave schedulers unrestricted so queues created on one + /// thread do not contend on a single cluster under multi-queue load. + pin_scheduler_cluster: bool, + /// The CPU of the last publication, `u32::MAX` before the first. submitter: AtomicU32, #[pin] grow: Work, @@ -1295,7 +1398,7 @@ struct Shared { #[pin] actuators: Mutex, #[pin] - changed: CondVar, + changed: TrackedCondVar, /// The port of the session in `state`; null before boot and once detachment begins. port: core::sync::atomic::AtomicPtr, } @@ -1307,9 +1410,32 @@ impl_has_work! { impl_has_delayed_work! { impl HasDelayedWork for Shared { self.poll } } +impl_has_hr_timer! { + impl HasHrTimer for Shared { + mode: RelativeMode, field: self.rescan + } +} +impl HrTimerCallback for Shared { + type Pointer<'a> = Arc; + + fn run(this: ArcBorrow<'_, Self>, _ctx: HrTimerCallbackContext<'_, Self>) -> HrTimerRestart { + let this: Arc = this.into(); + this.rescan_deadline_ns.store(0, Ordering::Release); + if !this.sleeping() + && !this.rescan_stopped.load(Ordering::Acquire) + && !this.crashed.load(Ordering::Acquire) + { + this.queue_event_records(); + } + HrTimerRestart::NoRestart + } +} impl_has_delayed_work! { impl HasDelayedWork for Shared { self.idle } } +impl_has_delayed_work! { + impl HasDelayedWork for Shared { self.housekeeping_timer } +} impl_has_delayed_work! { impl HasDelayedWork for Shared { self.governor } } @@ -1397,6 +1523,15 @@ impl WorkItem for Shared { this.queue_events(); } } +impl WorkItem for Shared { + type Pointer = Arc; + fn run(this: Arc) { + if this.sleeping() { + return; + } + this.queue_events(); + } +} impl WorkItem for Shared { type Pointer = Arc; @@ -1406,7 +1541,167 @@ impl WorkItem for Shared { } } +/// Non-M5 G17 devices registered for immediate full-effort wakeups when a host thread begins +/// waiting on a pure-compute submission while Region C is below `FULL_EFFORT`. +/// +/// Lock order: `Shared::state` -> `EFFORT_TARGETS`; `dma_fence->lock` -> `EFFORT_TARGETS` -> +/// workqueue pool lock. Always acquired with `spin_lock_irqsave` so it nests safely inside C +/// `dma_fence->lock` (`spin_lock_irqsave`) without altering caller IRQ state. +const MAX_EFFORT_TARGETS: usize = 4; + +struct EffortTargets { + lock: Opaque, + slots: core::cell::UnsafeCell<[Option>; MAX_EFFORT_TARGETS]>, +} + +// SAFETY: Every access to `slots` holds `lock` with hardware IRQ save/restore. +unsafe impl Sync for EffortTargets {} + +struct EffortTargetsGuard<'a> { + targets: &'a EffortTargets, + flags: kernel::ffi::c_ulong, +} + +impl core::ops::Deref for EffortTargetsGuard<'_> { + type Target = [Option>; MAX_EFFORT_TARGETS]; + + fn deref(&self) -> &Self::Target { + // SAFETY: The guard holds `targets.lock` exclusively. + unsafe { &*self.targets.slots.get() } + } +} + +impl core::ops::DerefMut for EffortTargetsGuard<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { + // SAFETY: The guard holds `targets.lock` exclusively. + unsafe { &mut *self.targets.slots.get() } + } +} + +impl Drop for EffortTargetsGuard<'_> { + fn drop(&mut self) { + // SAFETY: `self.flags` came from `spin_lock_irqsave` on `self.targets.lock`. + unsafe { kernel::bindings::spin_unlock_irqrestore(self.targets.lock.get(), self.flags) }; + } +} + +impl EffortTargets { + const fn new() -> Self { + Self { + lock: Opaque::uninit(), + slots: core::cell::UnsafeCell::new([const { None }; MAX_EFFORT_TARGETS]), + } + } + + unsafe fn init(&self) { + // SAFETY: Called once during module init before any GPU adapter probes. + unsafe { + kernel::bindings::__spin_lock_init( + self.lock.get(), + c_str!("g17::EFFORT_TARGETS").as_char_ptr(), + kernel::static_lock_class!().as_ptr(), + ); + } + } + + fn lock(&self) -> EffortTargetsGuard<'_> { + // SAFETY: `self.lock` was initialized once in `g17::init` before any probe. + let flags = unsafe { kernel::bindings::spin_lock_irqsave(self.lock.get()) }; + EffortTargetsGuard { + targets: self, + flags, + } + } +} + +static EFFORT_TARGETS: EffortTargets = EffortTargets::new(); +/// Registered non-M5 devices whose Region C effort is currently below `FULL_EFFORT`. +static BELOW_FULL_COUNT: AtomicU32 = AtomicU32::new(0); + +/// # Safety +/// +/// Called exactly once per module instance, before any platform adapter is registered. +pub(crate) unsafe fn init() { + // SAFETY: Single-call module initialization invariant upheld by caller. + unsafe { EFFORT_TARGETS.init() }; +} + +fn register_effort_target(shared: &Arc) { + if !shared.tracks_effort_wake { + return; + } + let mut targets = EFFORT_TARGETS.lock(); + if let Some(slot) = targets.iter_mut().find(|slot| slot.is_none()) { + *slot = Some(shared.clone()); + if !shared.full_effort_published.load(Ordering::Acquire) { + BELOW_FULL_COUNT.fetch_add(1, Ordering::AcqRel); + } + } +} + +fn unregister_effort_target(shared: &Arc) { + if !shared.tracks_effort_wake { + return; + } + let removed = { + let mut targets = EFFORT_TARGETS.lock(); + let mut found = None; + for slot in targets.iter_mut() { + if slot + .as_ref() + .is_some_and(|entry| Arc::ptr_eq(entry, shared)) + { + found = slot.take(); + if !shared.full_effort_published.load(Ordering::Acquire) { + BELOW_FULL_COUNT.fetch_sub(1, Ordering::AcqRel); + } + break; + } + } + found + }; + // Drop outside the spinlock; caller also retains `shared`. + drop(removed); +} + +/// Wakes any non-M5 device still below `FULL_EFFORT` so a newly waited pure-compute dispatch +/// lifts Region C effort to `FULL_EFFORT` immediately instead of waiting 16 ms. +/// Safe in atomic `dma_fence->lock` context: lock-free once already at `FULL_EFFORT`, and +/// `EFFORT_TARGETS` keeps every `Arc` refcount >= 2 across `queue_event_records()`. +pub(super) fn wake_for_compute_waiter() { + if BELOW_FULL_COUNT.load(Ordering::Acquire) == 0 { + return; + } + let targets = EFFORT_TARGETS.lock(); + for shared in targets.iter().flatten() { + if !shared.full_effort_published.load(Ordering::Acquire) + && !shared.sleeping() + && !shared.crashed.load(Ordering::Acquire) + { + shared.queue_event_records(); + } + } +} + impl Shared { + fn set_full_effort_published(&self, full: bool) { + if !self.tracks_effort_wake || self.full_effort_published.load(Ordering::Relaxed) == full { + return; + } + let targets = EFFORT_TARGETS.lock(); + let registered = targets + .iter() + .flatten() + .any(|entry| core::ptr::eq(Arc::as_ptr(entry), self)); + if registered && self.full_effort_published.swap(full, Ordering::AcqRel) != full { + if full { + BELOW_FULL_COUNT.fetch_sub(1, Ordering::AcqRel); + } else { + BELOW_FULL_COUNT.fetch_add(1, Ordering::AcqRel); + } + } + } + fn drm(&self) -> Result { self.drm.lock().as_ref().cloned().ok_or(ENODEV) } @@ -1452,10 +1747,14 @@ impl Shared { if !self.submission_enabled { return; } - // Already queued if this fails, which is just as good. + // Here when the submitter shares this CPU's cluster: waking a worker elsewhere would only + // add a wakeup to every completion. Already queued if this fails, which is just as good. + let here = kernel::cpu::CpuId::current(); let _ = match self.submitter() { - Some(cpu) => self.events.enqueue_on::, EVENT_WORK>(cpu, self.clone()), - None => self.events.enqueue::, EVENT_WORK>(self.clone()), + Some(cpu) if !kernel::cpumask::Cpumask::cluster_of(here).test(cpu) => { + self.events.enqueue_on::, EVENT_WORK>(cpu, self.clone()) + } + _ => self.events.enqueue::, EVENT_WORK>(self.clone()), }; } @@ -1464,15 +1763,42 @@ impl Shared { self.events.clone() } - /// Whether the event work and the scheduler workers follow the submitting CPU (M5). - pub(super) fn follows_submitter(&self) -> bool { - self.follows_submitter + /// The queue of [`Self::events`]. + /// + /// On M5 the queue is unbound. [`Self::queue_event_records`] queues the event work where the + /// completion is taken when that is in the cluster of the CPU that last published work, and + /// aims it at that CPU otherwise. On an unbound queue either only selects the affinity pod, + /// the CPUs sharing that L2, and the scheduler wakes the worker on an idle CPU of the pod: + /// beside the submitter and on its die, wherever the completion interrupt was taken. On a + /// per-CPU queue the worker would run on the submitting CPU itself whenever the interrupt is + /// taken there and, with the higher priority, preempt the submitter for every completion, + /// often in the middle of a publication holding the locks the event work takes next. As + /// their owner would not be running, the worker could not spin on them: it would sleep until + /// the submitter unlocks and then preempt it again, two context switches of the submitter per + /// completion. + /// + /// Otherwise the queue is per-CPU and the event work runs on the CPU it is queued on, as on + /// `system_highpri_wq`. + fn new_events_queue(m5: bool) -> Result { + if m5 { + workqueue::OwnedQueue::new_unbound_reclaim(c"aurora_g17_events", true) + } else { + workqueue::OwnedQueue::new_percpu_reclaim(c"aurora_g17_events", true) + } + } + + /// Whether each scheduler's submit queue should be restricted to the creating CPU's cluster + /// (all but single-die M5). + pub(super) fn pin_scheduler_cluster(&self) -> bool { + self.pin_scheduler_cluster } - /// Records the publishing CPU for the event work's placement (M5). + /// Records the publishing CPU for the event work's placement. fn note_submitter(&self) { - if self.follows_submitter { - self.submitter.store(kernel::cpu::CpuId::current().as_u32(), Ordering::Relaxed); + let cpu = kernel::cpu::CpuId::current().as_u32(); + // The completion side reads this line; write it only when the submitter moves. + if self.submitter.load(Ordering::Relaxed) != cpu { + self.submitter.store(cpu, Ordering::Relaxed); } } @@ -1519,7 +1845,48 @@ impl Shared { } fn queue_poll(self: &Arc) { - self.queue_poll_after(1); + // Sub-ms retirement rescan hrtimer: avoids 1-jiffy (4 ms at HZ=250) stalls when a + // completion's stamps or ring cursors lag its event notification. + const RESCAN_POLL_US: i64 = 50; + const RESCAN_POLL_NS: u64 = (RESCAN_POLL_US as u64) * 1_000; + if !self.submission_enabled + || self.sleeping() + || self.rescan_stopped.load(Ordering::Acquire) + || self.crashed.load(Ordering::Acquire) + { + return; + } + let now = now_ns(); + let armed_ns = self.rescan_deadline_ns.load(Ordering::Acquire); + if armed_ns != 0 && armed_ns > now { + return; + } + let mut handle = self.rescan_handle.lock(); + if self.sleeping() + || self.rescan_stopped.load(Ordering::Acquire) + || self.crashed.load(Ordering::Acquire) + { + return; + } + let armed_ns = self.rescan_deadline_ns.load(Ordering::Acquire); + if armed_ns != 0 && armed_ns > now { + return; + } + drop(handle.take()); + self.rescan_deadline_ns + .store(now.saturating_add(RESCAN_POLL_NS), Ordering::Release); + *handle = Some(self.clone().start(Delta::from_micros(RESCAN_POLL_US))); + } + + fn cancel_rescan(&self) { + let mut handle = self.rescan_handle.lock(); + self.rescan_deadline_ns.store(0, Ordering::Release); + drop(handle.take()); + } + + fn disable_rescan(&self) { + self.rescan_stopped.store(true, Ordering::Release); + self.cancel_rescan(); } fn queue_poll_after(self: &Arc, delay_ms: u32) { @@ -1552,6 +1919,16 @@ impl Shared { .enqueue_delayed::, IDLE_WORK>(self.clone(), msecs_to_jiffies(delay_ms)); } + fn queue_housekeeping(self: &Arc, delay_ns: u64) { + let delay_ms = delay_ns + .div_ceil(1_000_000) + .clamp(1, u64::from(u32::MAX)) as u32; + let _ = workqueue::system_highpri().enqueue_delayed::, HOUSEKEEPING_WORK>( + self.clone(), + msecs_to_jiffies(delay_ms), + ); + } + fn disable_timer(self: &Arc, timer: &DelayedWork) { // SAFETY: Every caller passes one of this Shared's initialized pinned // timer fields. raw_as_work points into its delayed_work; the C call @@ -1655,6 +2032,16 @@ impl Gpu { } let m5 = cfg.profile.is_m5(); if m5 { + // The M5 graph builds the InitData layouts the firmware build names. A build that + // names none is refused here, before anything is written to the GPU. + if variant.m5_layouts.is_none() { + dev_err!( + dev.as_ref(), + "No M5 InitData layouts for this GPU firmware build ({:?})\n", + variant.m5_layouts + ); + return Err(ENODEV); + } let board = cfg.m5.ok_or(EINVAL)?; J813_FORMS.store(board.j813_forms(), core::sync::atomic::Ordering::Relaxed); // Hold the J813's GFX power domain for the session, as the G15 and G16 paths do @@ -1754,14 +2141,13 @@ impl Gpu { let render_policy = if m5 { Some(render_resources::M5Policy::new(&id)?) } else { None }; // The bare-metal M5 boot runs both engines; other M5 profiles take no submission. let submits = !m5 || cfg.profile == FirmwareProfile::M5PublishedRoots; - let events = Arc::new( - if m5 { - workqueue::OwnedQueue::new_unbound_reclaim(c"aurora_g17_events", true)? - } else { - workqueue::OwnedQueue::new_percpu_reclaim(c"aurora_g17_events", true)? - }, - GFP_KERNEL, - )?; + let events = Arc::new(Shared::new_events_queue(m5)?, GFP_KERNEL)?; + let frequencies = Self::state_frequencies(dev, cfg, variant, id.num_clusters)?; + let max_pstate = frequencies + .as_ref() + .map_or(0, stats::StateFrequencies::max_pstate); + let worker_deferred = runtime::DeferredBatch::worker()?; + let render_collector = runtime::DeferredBatch::worker()?; let shared = Arc::pin_init( pin_init!(Shared { drm <- new_mutex!(Some(dev.into()), "g17::Shared::drm"), @@ -1769,6 +2155,7 @@ impl Gpu { clusters: id.num_clusters, active_cores, variant, + max_pstate, operand_state: &cfg.core_layout.operand_state, m5_board: cfg.m5.filter(|_| m5), deflake: cfg.core_layout.deflake, @@ -1796,13 +2183,25 @@ impl Gpu { housekeeping: AtomicBool::new(true), housekeeping_ns: AtomicU64::new(0), poll <- new_delayed_work!("g17::Shared::poll"), + rescan_stopped: AtomicBool::new(false), + rescan_deadline_ns: AtomicU64::new(0), + rescan <- HrTimer::new(), + rescan_handle <- new_mutex!(None, "g17::Shared::rescan_handle"), idle <- new_delayed_work!("g17::Shared::idle"), + housekeeping_timer <- new_delayed_work!("g17::Shared::housekeeping_timer"), governs: m5, + tracks_effort_wake: !m5 && submits, + full_effort_published: AtomicBool::new(false), governor <- new_delayed_work!("g17::Shared::governor"), governor_armed: AtomicBool::new(false), governor_activity_ns: AtomicU64::new(0), events, - follows_submitter: m5, + worker_deferred <- new_mutex!( + Some(worker_deferred), + "g17::Shared::worker_deferred" + ), + render_collector <- new_mutex!(render_collector, "g17::Shared::render_collector"), + pin_scheduler_cluster: !m5 || id.num_dies > 1, submitter: AtomicU32::new(u32::MAX), grow <- new_work!("g17::Shared::grow"), reclaim_work <- new_work!("g17::Shared::reclaim_work"), @@ -1810,7 +2209,10 @@ impl Gpu { stop <- new_mutex!((), "g17::Shared::stop"), state <- new_mutex!(None, "g17::Shared::state"), actuators <- new_mutex!(thermal::Actuators::new(), "g17::Shared::actuators"), - changed <- new_condvar!("g17::Shared::changed"), + changed <- pin_init!(TrackedCondVar { + condvar <- new_condvar!("g17::Shared::changed"), + waiters: AtomicU32::new(0), + }), port: core::sync::atomic::AtomicPtr::new(core::ptr::null_mut()), }), GFP_KERNEL, @@ -1837,7 +2239,6 @@ impl Gpu { directory.read_only_file(c"hardware_data", reports::HardwareDataView(shared.clone())), GFP_KERNEL, )?; - let frequencies = Self::state_frequencies(dev, cfg, variant, id.num_clusters)?; let stats = Arc::new( crate::stats::StatsSnapshot { g17_reader: Some(stats::Reader(shared.clone(), frequencies)), @@ -1867,6 +2268,7 @@ impl Gpu { .port .store(Arc::as_ptr(&firmware.port).cast_mut(), Ordering::Release); *gpu.shared.state.lock() = Some(firmware); + register_effort_target(&gpu.shared); gpu.shared.queue_events(); Ok(gpu) } @@ -1897,11 +2299,15 @@ impl Gpu { let others = builds .iter() .filter(|build| Some(build.os_version) != version); + // Measure the loaded TEXT once and try each build against it. A build that is not this + // image is not an error while another one may be: only when none is, say what was + // measured and what is supported. + let mut measured = Self::measure_text(dev)?; let mut identified = None; for build in Iterator::chain(preferred, others) { - if Self::identify_image(dev, build).is_err() { + let Some(image) = measured.find(build.images) else { continue; - } + }; let admits = build.config.is_none_or(|config| { config .core_layout @@ -1909,15 +2315,32 @@ impl Gpu { .is_none_or(|measured| measured == cores) }); if admits { - identified = Some(build); + identified = Some((build, image)); break; } - identified.get_or_insert(build); + identified.get_or_insert((build, image)); } - if let Some(build) = identified { + if let Some((build, image)) = identified { + dev_info!(dev.as_ref(), "GPU firmware build: {}\n", image.name); dev_info!(dev.as_ref(), "GPU firmware: {}\n", build.name); return Ok((build.variant, build.config)); } + dev_err!( + dev.as_ref(), + "unsupported GPU firmware build: {}\n", + measured.identity(builds.iter().flat_map(|build| build.images)) + ); + // Builds that differ only in their core layout share an image: list each image once. + // Compare by name and digest; the address of a `const`-promoted entry is not unique. + let images = || builds.iter().flat_map(|build| build.images); + for (i, image) in images().enumerate() { + if !images() + .take(i) + .any(|seen| (seen.name, seen.text_sha256) == (image.name, image.text_sha256)) + { + dev_err!(dev.as_ref(), "supported: {}\n", image.name); + } + } dev_err!( dev.as_ref(), "Unsupported GPU firmware image (reported macOS version {:?})\n", @@ -1926,19 +2349,33 @@ impl Gpu { Err(ENODEV) } - /// Checks that the loaded TEXT (the `fw-text` region) is one of `build`'s images, with the DATA size - /// of the `fw-data` region. The version property is only a selection hint. - fn identify_image(dev: &AsahiDrmDevice, build: &'static fw::variant::Build) -> Result { - let node = dev.as_ref().as_ref().of_node().ok_or(EINVAL)?; - let text = node.reserved_mem_region_to_resource_byname(c_str!("fw-text"))?; - let data = node.reserved_mem_region_to_resource_byname(c_str!("fw-data"))?; - let start = text.start(); - let end = start.checked_add(text.size()).ok_or(EINVAL)?; - crate::fwid::identify(dev.as_ref().as_ref(), start..end, data.size(), build.images) - .inspect_err(|e| { - dev_err!(dev.as_ref(), "GPU firmware image not admitted: {:?}\n", e) - })?; - Ok(()) + /// Measures the loaded TEXT (the `fw-text` region), with the DATA size of the `fw-data` + /// region, for [`Self::firmware_variant`] to identify among the builds. The version + /// property is only a selection hint. + fn measure_text(dev: &AsahiDrmDevice) -> Result { + let measure = || { + let node = dev.as_ref().as_ref().of_node().ok_or(EINVAL)?; + let text = node.reserved_mem_region_to_resource_byname(c_str!("fw-text"))?; + let data = node.reserved_mem_region_to_resource_byname(c_str!("fw-data"))?; + let start = text.start(); + let end = start.checked_add(text.size()).ok_or(EINVAL)?; + crate::fwid::measure(start..end, data.size()) + }; + measure().inspect_err(|e| { + if *e == EAGAIN { + dev_err!( + dev.as_ref(), + "GPU firmware TEXT changed while it was measured\n" + ); + } else { + // A missing or bad fw-text/fw-data region: a DT or boot loader mismatch. + dev_err!( + dev.as_ref(), + "GPU firmware image not measured (fw-text/fw-data): {:?}\n", + e + ); + } + }) } /// The macOS version the boot loader reports for the boot firmware that loaded the GPU @@ -1952,18 +2389,21 @@ impl Gpu { } /// The frequency of each performance state the firmware reports - /// ([`stats::reports_pstate`]): M5's from its board, the A18 Pro's from the operating - /// points its performance table A names. The A18 Pro's records do not name the table, but - /// at its top state, where it runs while work is in flight, a sustained FP32 FMA load - /// completes faster than table B's frequency there allows. `None` where the firmware - /// reports no state. + /// ([`stats::reports_pstate`]): M5's from its board, the A18 Pro's and T6041's from the + /// operating points their performance table A names. Their records do not name the table; + /// on the A18 Pro, at the top state where the GPU runs while work is in flight, a sustained + /// FP32 FMA load completes faster than table B's frequency there allows. On T6041 both + /// tables map state 10 to OPP 15 (1578 MHz) and only differ on states 5..=9 on the + /// J616C (32-core; 40-core differs on 6..=9), so those mid-state frequencies are nominal + /// (taken from table A) until measured by a mid-state ALU benchmark. `None` where the + /// firmware reports no state. fn state_frequencies( dev: &AsahiDrmDevice, cfg: &'static Config, variant: &fw::variant::Variant, clusters: u32, ) -> Result> { - if !stats::reports_pstate(variant.graph, variant.m5_commands) { + if !stats::reports_pstate(variant.telemetry_protocol) { return Ok(None); } if let Some(board) = cfg.m5 { @@ -2088,7 +2528,11 @@ impl Gpu { shared.feed.clone(), )?, seen_submissions: 0, - rings: channel::Rings::new(shared.variant.graph, shared.variant.m5_commands)?, + rings: channel::Rings::new( + shared.variant.graph, + shared.variant.telemetry_protocol, + shared.max_pstate, + )?, recovery: recovery::State::new(), effort: power::Effort::new(), hold: power::Hold::new(), @@ -2149,7 +2593,7 @@ impl Gpu { .inspect_err(at("root adoption"))?; session .init - .build_m5(dev, &session.uat, id, board) + .build_m5(dev, &session.uat, id, board, shared.variant) .inspect_err(at("M5 graph"))?; session .init @@ -2292,7 +2736,11 @@ impl Gpu { shared.feed.clone(), )?, seen_submissions: 0, - rings: channel::Rings::new(shared.variant.graph, shared.variant.m5_commands)?, + rings: channel::Rings::new( + shared.variant.graph, + shared.variant.telemetry_protocol, + shared.max_pstate, + )?, recovery: recovery::State::new(), effort: power::Effort::new(), hold: power::Hold::new(), @@ -2452,11 +2900,14 @@ impl Gpu { /// Stops the firmware and releases everything it used. pub(crate) fn shutdown(&self) { + unregister_effort_target(&self.shared); self.shared.feed.begin_shutdown(); self.shared.preparations.remove(); self.shared.stop_queues(); + self.shared.disable_rescan(); self.shared.disable_timer(&self.shared.poll); self.shared.disable_timer(&self.shared.idle); + self.shared.disable_timer(&self.shared.housekeeping_timer); self.shared.disable_timer(&self.shared.governor); if let Some(firmware) = (*self.shared.state.lock()).as_deref_mut() { firmware.governor_restore(); @@ -2473,6 +2924,10 @@ impl Gpu { } impl gpu::Gpu for Gpu { + fn max_cmdbuf_size(&self) -> usize { + command::MAX_STREAM + } + fn syncobj_wait_hint(&self) -> Option<(u32, u32)> { self.shared.feed.wait_hint() } @@ -2505,15 +2960,34 @@ impl gpu::Gpu for Gpu { self.shared.crashed.load(Ordering::Acquire) } + /// A parked render pair keeps its views of the kick rings in the VM that last ran on it + /// while that VM is open. Once the client has closed the VM (its status says so before + /// this runs), they go, one pair at a time and dropped off the device lock, so they do not + /// keep the VM's page tables alive. A pair that parks or returns after this sees the + /// closed status itself. + fn vm_closed(&self, _vm: &mmu::Vm) { + loop { + let views = (*self.shared.state.lock()) + .as_deref_mut() + .and_then(|firmware| firmware.queues.take_closed_parked_views()); + let Some(views) = views else { break }; + drop(views); + } + } + fn get_params(&self, params: &mut uapi::drm_asahi_params_global) -> Result { params.features |= u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_PER_COMMAND_INPUT_SYNCS) | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_EXACT_PRIOR_BARRIERS) | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS) + | uapi::DRM_ASAHI_FEATURE_ORDERED_FRAGMENT_BARRIERS as u64 | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS) | sync_output::FEATURE_CUMULATIVE_SIGNALS - | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT; + | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT + | compute_channel_features(pairs::compute_channels_per_owner()); let variant = self.shared.variant; + params.features |= + ordered_partial_renders_feature(variant.fragment_busy, pairs::per_owner()); // The M5 command set has no AS-build flag: its validation refuses one. if !variant.m5_commands { params.features |= u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD); @@ -2696,48 +3170,50 @@ impl gpu::Gpu for Gpu { Ok(KBox::new(frontend, GFP_KERNEL)?) } + fn timestamp_window_size(&self) -> u64 { + let state = self.shared.state.lock(); + (*state) + .as_ref() + .and_then(|firmware| firmware.timestamp_window()) + .map_or(0, |window| window.end - window.start) + } + fn map_timestamp_buffer( &self, mut bo: gem::ObjectRef, range: Range, + window: crate::timestamp::WindowPermit, ) -> Result { - let (mapping, window) = { + let windowed = { let state = self.shared.state.lock(); let firmware = (*state).as_ref().ok_or(ENODEV)?; - // The timestamp window is part of the older firmware graph, not M5's graph. - let windowed = if firmware.uat.is_m5() { - None - } else { - bo.map_range_into_range( - firmware.uat.kernel_vm(), - range.clone(), - hw::t8140::dynamic::TIMESTAMP_WINDOW, - mmu::UAT_PGSZ as u64, - mmu::PROT_FW_SHARED_RW, - false, - ) - .ok() - }; - match windowed { - Some(mapping) => (mapping, true), - // A full window: this buffer's stamps are all host-written. - None => ( + // A file whose share of the window is used up gets a host-written buffer, as when + // the window is full. + if window.is_allowed() { + firmware.timestamp_window().and_then(|window| { bo.map_range_into_range( firmware.uat.kernel_vm(), - range, - firmware.uat.kernel_dynamic_range(), + range.clone(), + window, mmu::UAT_PGSZ as u64, mmu::PROT_FW_SHARED_RW, false, - )?, - false, - ), + ) + .ok() + }) + } else { + None } }; // The buffer's CPU mapping takes the reservation lock: not under the device mutex. - match window { - true => crate::timestamp::Buffer::firmware_window(mapping), - false => crate::timestamp::Buffer::firmware(mapping), + match windowed { + Some(mapping) => { + crate::timestamp::Buffer::firmware_window(mapping, window.into_share()) + } + // Outside the window the host writes every stamp, and the firmware never sees the + // buffer: give it no firmware alias, which would take kernel address space shared + // with every firmware object (queues, rings, pools) for as long as it is bound. + None => crate::timestamp::Buffer::host(&bo, range), } } } diff --git a/drivers/gpu/drm/asahi/g17/object.rs b/drivers/gpu/drm/asahi/g17/object.rs index 6922d130852244..b2b935e9e7daed 100644 --- a/drivers/gpu/drm/asahi/g17/object.rs +++ b/drivers/gpu/drm/asahi/g17/object.rs @@ -58,6 +58,8 @@ pub(crate) struct KernelObject { obj: gem::ObjectRef, ptr: NonNull, size: usize, + /// The client charge of backing from [`Self::client_backing`], released with the object. + charge: Option, } // SAFETY: The object only refers to kernel memory; concurrent access goes through `&self` @@ -108,6 +110,29 @@ impl KernelObject { }, size) } + /// Write-combined [`Self::backing`] that a client's commands size, charged to that client + /// (`client`) as a user buffer of the same size would be: admitted against its and the + /// device's memory limits before it is allocated, failing with ENOMEM over either, and then + /// counted as its held memory instead of kernel memory, until the object is dropped. + /// Without a client (a kernel VM's object) it is kernel memory, as [`Self::backing`]. + pub(crate) fn client_backing( + dev: &AsahiDrmDevice, + size: usize, + client: Option<&kernel::sync::Arc>, + ) -> Result { + let Some(client) = client else { + return Self::backing(dev, size, CpuMap::WriteCombined); + }; + let bytes = gem::checked_object_size(size)? as u64; + let commit = crate::memacct::LEDGER.admit(client, bytes)?; + let mut object = + Self::with_object(gem::new_kernel_object_wc_user_charged(dev, size)?, size)?; + let charge = crate::memacct::Charge::user(commit, None); + charge.set_held(true); + object.charge = Some(charge); + Ok(object) + } + fn with_object(mut obj: gem::ObjectRef, size: usize) -> Result { let vmap = obj.vmap()?; let ptr = NonNull::new(vmap.addr.cast::()).ok_or(ENOMEM)?; @@ -121,6 +146,7 @@ impl KernelObject { obj, ptr, size, + charge: None, }) } @@ -137,9 +163,9 @@ impl KernelObject { } else { error }) } - /// Reuses only a complete alias of this exact retained backing. Permanent - /// queue aliases stay owned by the client VM after a physical pair moves; - /// returning to that VM must not replace or duplicate those mappings. + /// Reuses only a complete alias of this exact retained backing. A render pair keeps its + /// views of its kick rings while it moves between contexts of one VM; preparing the view + /// for that VM again must not replace or duplicate them. pub(crate) fn prepare_alias( &self, vm: &mmu::Vm, @@ -700,15 +726,18 @@ impl Pool { ) } - /// Allocates or reuses a matching object. Capacity pressure leaves a fresh - /// mapping uncached, preserving allocation and submission concurrency. + /// Allocates or reuses a matching object. A non-zero `prefix` maps `[0..prefix)` + /// firmware-cached; `prefix == 0` keeps the whole mapping uncached (for objects + /// that both firmware and host write) while still retaining and fencing the VA + /// in the pool. Capacity pressure leaves a fresh mapping unpooled and uncached, + /// preserving allocation and submission concurrency. /// /// The firmware may still follow a previous owner's pointers into a returned object /// until it has processed that owner's release. Reuse takes the matching object /// returned longest ago once its fence is met (see `return_object`); a younger one is - /// reused only when the family has no room for a fresh cached object, because an - /// uncached one is unmapped as soon as its owner drops it. On the A18 Pro a work state is - /// never reused before its fence: with no room, a fresh one stays uncached instead. + /// reused only when the family has no room for a fresh pooled object, because an + /// unpooled one is unmapped as soon as its owner drops it. On the A18 Pro a work state is + /// never reused before its fence: with no room, a fresh one stays unpooled instead. pub(crate) fn allocate( self: &kernel::sync::Arc, alloc: &Allocator<'_>, @@ -808,6 +837,9 @@ impl Pool { if !reserved { return Ok(result); } + if prefix == 0 { + return Ok(result); + } let (proof, mutated) = match result.mapping.as_ref() { // SAFETY: The allocator just created the private mapping. No // pointer or alias has been published; its reserved lease retains diff --git a/drivers/gpu/drm/asahi/g17/pairs.rs b/drivers/gpu/drm/asahi/g17/pairs.rs index c7515c1c764171..bedb5ad3d40907 100644 --- a/drivers/gpu/drm/asahi/g17/pairs.rs +++ b/drivers/gpu/drm/asahi/g17/pairs.rs @@ -1,12 +1,22 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! Render pairs one logical render queue may hold: two on the G17D (M5 Ultra), one elsewhere. +//! Render pairs one logical render queue may hold: two on G17C and G17D (4+ clusters), +//! one elsewhere. //! //! A second pair lets one queue's depth run on two physical render rings. It comes only from -//! surplus: the QID budget ([`super::kick::render_reserve`]) keeps counting one pair per open -//! queue, admission claims a sibling only while a pair can still be built, and an unused -//! sibling is reassigned to an owner that needs a first pair. An owner's overlapping renders on -//! its two pairs are ordered in firmware ([`super::hazard::plan`]). +//! surplus: the QID budget ([`super::kick::render_reserve`]) reserves one pair for every live +//! render demand (open queues, non-reclaimable siblings, and teardown-held released pairs) plus +//! headroom for future queues, admission claims a released pair only while surplus first-pair +//! capacity remains and builds a fresh sibling only while a pair can also be built, and an unused +//! sibling is reclaimed before refusing a new logical queue or reassigned to an owner that needs a +//! first pair. An owner's overlapping renders on its two pairs are ordered in firmware +//! ([`super::hazard::plan`]). +//! +//! Two pairs are enabled at 4+ GPU clusters (40-core G17C and 80-core G17D, 8-16 GiB render-pool +//! inventory), where a single physical render ring underutilizes the wider shader array across +//! back-to-back deep renders. Narrower M5 parts (1-cluster J813, 2-cluster J714, 2-4 GiB +//! inventory) keep one pair per queue to avoid the extra per-pair ring/graph/PB footprint and +//! doubled ray-query render-pool extras (`fw::render_rt::required_blocks`) until measured. //! //! A queue samples the count once, when it is created ([`per_owner`]): its scheduler credits, //! render pool and pair limit all follow that one value. @@ -15,14 +25,27 @@ use core::sync::atomic::{AtomicU8, Ordering::Relaxed}; use crate::hw::t8140::queues::RENDER_PAIRS_MAX; -/// G17D's count. -const G17D_PAIRS: u8 = RENDER_PAIRS_MAX as u8; +/// Multi-pair count for large multi-cluster M5 parts (G17C/G17D). +const MULTI_PAIRS: u8 = RENDER_PAIRS_MAX as u8; + +/// Maximum physical compute channels one logical compute owner may hold: the most firmware +/// compute queues any board spreads one command queue over ([`Board::compute_channels`], three +/// on M5 Pro). It sizes the per-owner channel arrays and the compute waits of a render kick, so +/// every channel of an owner costs one dependency slot in each of its consumers. +/// +/// [`Board::compute_channels`]: crate::g17::fw::m5::initdata::Board::compute_channels +pub(crate) const COMPUTE_CHANNELS_MAX: usize = 3; static PAIRS: AtomicU8 = AtomicU8::new(1); +static COMPUTE_CHANNELS: AtomicU8 = AtomicU8::new(1); -/// The count for the probed board, set once at probe (one GPU per system). +/// The counts for the probed board, set once at probe (one GPU per system). pub(crate) fn select_board(board: &crate::g17::fw::m5::initdata::Board) { - PAIRS.store(if board.g17d_forms() { G17D_PAIRS } else { 1 }, Relaxed); + PAIRS.store( + if board.clusters >= 4 { MULTI_PAIRS } else { 1 }, + Relaxed, + ); + COMPUTE_CHANNELS.store(board.compute_channels(), Relaxed); } /// Render pairs a logical render queue created now may hold. @@ -30,6 +53,70 @@ pub(crate) fn per_owner() -> u8 { PAIRS.load(Relaxed) } +/// Physical compute channels a logical compute queue created now may hold. +pub(crate) fn compute_channels_per_owner() -> u8 { + COMPUTE_CHANNELS.load(Relaxed) +} + +/// GPU execution time of a compute kick, between the start and end timestamps of its firmware +/// execution record, from which the kick is worth a sibling channel. +/// +/// Measured on M5 Pro: one physical QID streams queued kicks back to back for about 11 us each; +/// the same kicks spread over three QIDs take about 16.4 us each, because every kick then pays +/// about 5 us of firmware arbitration between QIDs. A sibling only pays for itself through +/// overlapped execution, so the kick must run long enough for that cost to vanish into it: +/// 100 us is where the 5 us of arbitration falls to 5% of the kick, while a kick of a few +/// microseconds would spend more on arbitration than it runs. +pub(crate) const SIBLING_EXECUTION_NS: u64 = 100_000; + +/// [`SIBLING_EXECUTION_NS`] in the command timestamp ticks of an execution record. +const SIBLING_EXECUTION_TICKS: u64 = SIBLING_EXECUTION_NS + * crate::hw::t8140::resources::COMMAND_TIMESTAMP_HZ + / 1_000_000_000; + +/// Consecutive heavy kicks ([`SIBLING_EXECUTION_NS`]) after which a primary channel's execution is +/// sustained: a single long kick among short ones (a first dispatch, a cold pipeline) does not +/// fan its queue out. +pub(crate) const SIBLING_SUSTAINED_KICKS: u8 = 2; + +/// Kicks of an owner that must already be in flight on its compute channels before a new kick +/// may run beside them on a sibling channel. +/// +/// A kick queued behind one in flight on the same ring starts the moment its predecessor ends, +/// while the host turns that completion into the next submission (60 to 100 us). Two overlapped +/// kicks that each fill the shader cores share them and end together, both rings then wait for +/// the host, and every pair of kicks pays that turnaround. With two kicks already in flight the +/// primary ring keeps one queued behind the overlap, so a sibling only adds overlap and never +/// exposes the turnaround: an owner keeping at most two kicks in flight runs exactly as on one +/// ring. +pub(crate) const SIBLING_MIN_IN_FLIGHT: usize = 2; + +/// How long publication keeps to an owner's bound compute channels after no sibling could be found +/// (no reusable queue to bind or re-arm and no QID headroom) before it looks again. +pub(crate) const SIBLING_HEADROOM_BACKOFF_NS: u64 = 10_000_000; + +/// Whether a new kick of an owner with `in_flight` kicks in flight on its compute channels may +/// overlap them on a sibling channel ([`SIBLING_MIN_IN_FLIGHT`]). +pub(crate) fn overlaps(in_flight: usize) -> bool { + in_flight >= SIBLING_MIN_IN_FLIGHT +} + +/// Folds the execution record `[start, end]` of a retired compute kick into its channel's run of +/// consecutive heavy kicks. +pub(crate) fn heavy_run(run: u8, start: u64, end: u64) -> u8 { + if end.saturating_sub(start) >= SIBLING_EXECUTION_TICKS { + run.saturating_add(1) + } else { + 0 + } +} + +/// Whether a primary compute channel with this run of heavy kicks runs sustained heavy work, the +/// only work whose independent kicks fan out onto sibling channels. +pub(crate) fn sustained(run: u8) -> bool { + run >= SIBLING_SUSTAINED_KICKS +} + /// Renders a busy pair of a two-pair owner takes before its next render goes to /// an idle sibling: 1 keeps a queue at depth 1-2 on one pair. const SIBLING_BACKLOG: u8 = 1; @@ -45,3 +132,42 @@ pub(crate) fn sibling_backlog() -> u8 { pub(crate) fn set_sibling_backlog(renders: u8) { BACKLOG.store(renders, Relaxed); } + + +/// The pairs a queue of `queue` pairs uses for a render each of whose pairs reserves +/// `window_bytes` of the client's M5 compact window of `window` bytes (`None`: no M5 footprint). +/// Each pair maps its own copy of a layout's objects in that one window, so a second pair is +/// built and used only for a layout the window holds twice. Any other layout runs on one of the +/// queue's pairs, always the same one, as on a part with one pair per queue +/// (`Pool::acquire_render`). SUBMIT has already refused a layout that one pair cannot hold. +pub(crate) fn for_window(queue: u8, window_bytes: Option, window: u64) -> u8 { + match window_bytes { + Some(bytes) if queue > 1 && bytes.saturating_mul(u64::from(queue)) > window => 1, + _ => queue, + } +} + +#[kernel::macros::kunit_tests(asahi_g17_pair_count)] +mod tests { + use super::*; + + const WINDOW: u64 = 1 << 32; + + #[test] + fn a_layout_the_window_holds_twice_keeps_both_pairs() { + assert_eq!(for_window(2, Some(WINDOW / 2), WINDOW), 2); + assert_eq!(for_window(2, Some(64 << 20), WINDOW), 2); + } + + #[test] + fn a_larger_layout_runs_on_one_pair() { + assert_eq!(for_window(2, Some(WINDOW / 2 + 1), WINDOW), 1); + assert_eq!(for_window(2, Some(WINDOW), WINDOW), 1); + } + + #[test] + fn a_one_pair_queue_and_a_render_without_footprint_are_unchanged() { + assert_eq!(for_window(1, Some(WINDOW), WINDOW), 1); + assert_eq!(for_window(2, None, WINDOW), 2); + } +} diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index f9bd31f13bc7d5..7083cf028a403f 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -7,9 +7,9 @@ //! through a preparation lease ([`super::Shared::port`]): shutdown and device loss join every //! lease before they detach the session. Each piece below is atomic or has its own lock. //! -//! Lock order: device mutex -> compute queue cell -> the locks of this port. The render -//! publication lock comes first among the port's locks: device mutex -> render publication -//! lock -> admission pool, QoS, mailbox. Its holder never takes the device mutex. +//! Lock order: device mutex -> outer_{compute,render} -> compute queue cell -> the locks of +//! this port. Among the port's locks: render publication lock -> M5 outer-ring lock -> +//! admission pool, QoS, mailbox. None of their holders ever takes the device mutex. use super::{ fw::{ @@ -18,7 +18,7 @@ use super::{ }, qos, }; -use core::sync::atomic::{fence, AtomicBool, AtomicU32, AtomicU64, Ordering}; +use core::sync::atomic::{fence, AtomicBool, AtomicU32, AtomicU64, AtomicU8, Ordering}; use kernel::{ new_mutex, new_spinlock, prelude::*, @@ -35,6 +35,9 @@ const PRIORITIES: usize = Policy::PRIORITIES as usize; /// work bound by host refills. While the GPU is the bottleneck the burst gains nothing, and at the /// SoC's thermal limit the power it takes comes out of the GPU's clock. const RX_UTIL_MIN_GPU_BOUND: u32 = 256; +const RX_STATE_UNSET: u8 = 0; +const RX_STATE_DEFAULT: u8 = 1; +const RX_STATE_GPU_BOUND: u8 = 2; /// One priority class's compute work ring: its slot array and the cursors of its two firmware /// consumers and of the host producer. @@ -70,6 +73,14 @@ impl RingView { } } +/// Raw pointers to the M5 submission-history table in firmware-shared memory. +#[derive(Clone, Copy)] +pub(super) struct M5HistoryView { + pub(super) generation: *const AtomicU32, + pub(super) config: [*const AtomicU32; 4], + pub(super) slots: *mut u8, +} + /// Raw views of the session's firmware-shared memory, fixed once the firmware is built. pub(super) struct Views { pub(super) compute: [RingView; PRIORITIES], @@ -80,6 +91,8 @@ pub(super) struct Views { pub(super) qos: *mut u8, pub(super) recovery: *const AtomicU32, pub(super) mailbox: *const super::Mailbox, + pub(super) m5_credits: Option>, + pub(super) m5_history: Option, } // SAFETY: The views only name memory and a mailbox owned by the firmware session, which outlives @@ -104,11 +117,17 @@ pub(super) struct Port { /// The request last made, `None` before the first. #[pin] rx_applied: SpinLock>>, + /// Lock-free mirror of `rx_applied` (`RX_STATE_*`) so steady-state updates avoid locking. + rx_state: AtomicU8, /// Serializes every render publication, with or without the device mutex: the tiling /// and fragment work rings have one host producer at a time, and same-VM attachment /// overlaps are ordered by publication order (see hazard.rs). #[pin] render: Mutex<()>, + /// Serializes M5 shared outer-ring writes, host-port gating transactions, and submission + /// history geometry/updates across direct compute publishers and device-mutex publishers. + #[pin] + m5_outer: Mutex>, /// The accepted recovery generation, mirrored for publishers without the device mutex. generation: AtomicU64, /// Device publication order shared by compute and render commands. @@ -116,6 +135,13 @@ pub(super) struct Port { /// Full firmware effort is applied; cleared before an idle clear rechecks `submissions`. effort_full: AtomicBool, demand: super::power::Demand, + /// Serializes busy-share window accounting and CLPC busy updates. + #[pin] + busy: SpinLock, + /// Mirrored from `busy` and `qos` for a lock-free fast path in `note_gpu_activity()`. + busy_window_start: AtomicU64, + busy_below_top: AtomicBool, + oldest_in_flight_any: AtomicU64, statistics_epoch: AtomicU64, last_submission_ns: AtomicU64, submissions: AtomicU64, @@ -137,6 +163,37 @@ impl RenderRoom { } } +/// Room for two slots on M5's shared outer work ring of one priority, reserved under +/// both the render publication lock and `m5_outer`. +#[derive(Clone, Copy)] +pub(super) struct M5RenderRoom { + priority: u8, + start: u32, + next: [u32; 2], +} + +impl M5RenderRoom { + pub(super) fn priority(&self) -> u8 { + self.priority + } +} + +/// Serializes entry and Drop of an M5 [`super::initdata::OuterScope`] under `Port::m5_outer` +/// so `Credits::scoped` and `reserved[]` cannot race with direct M5 reservations or publications. +pub(super) struct PortOuterScope<'a> { + scope: Option>, + port: Arc, +} + +impl Drop for PortOuterScope<'_> { + fn drop(&mut self) { + if let Some(scope) = self.scope.take() { + let _m5_outer = self.port.m5_outer_lock(); + drop(scope); + } + } +} + /// A compute work-ring slot reserved before any command becomes visible. Dropping an unused /// claim returns the slot. pub(super) struct OuterClaim<'a> { @@ -169,11 +226,17 @@ impl Port { rx: SetOnce::new(), feed, rx_applied <- new_spinlock!(None, "g17::Port::rx_applied"), + rx_state: AtomicU8::new(RX_STATE_UNSET), render <- new_mutex!((), "g17::Port::render"), + m5_outer <- new_mutex!(None, "g17::Port::m5_outer"), generation: AtomicU64::new(0), publications: AtomicU64::new(0), effort_full: AtomicBool::new(false), demand, + busy <- new_spinlock!(super::power::BusyShare::new(), "g17::Port::busy"), + busy_window_start: AtomicU64::new(0), + busy_below_top: AtomicBool::new(false), + oldest_in_flight_any: AtomicU64::new(0), statistics_epoch: AtomicU64::new(0), last_submission_ns: AtomicU64::new(0), submissions: AtomicU64::new(0), @@ -296,6 +359,298 @@ impl Port { self.render.lock() } + /// Serializes M5 shared outer-ring and host-port updates with direct M5 compute publishers. + pub(super) fn m5_outer_lock(&self) -> MutexGuard<'_, Option<(u32, u64, u64)>> { + self.m5_outer.lock() + } + + /// Enters an M5 `OuterScope` under `m5_outer` and returns a guard that re-acquires + /// `m5_outer` around the inner scope's Drop, preventing races with direct M5 reservations. + pub(super) fn outer_scope<'a>( + self: &Arc, + init: &super::initdata::InitData, + claim: &'a mut super::initdata::OuterClaim, + ) -> Result> { + let _m5_outer = self.m5_outer.lock(); + let scope = init.outer_scope(claim)?; + Ok(PortOuterScope { + scope: Some(scope), + port: self.clone(), + }) + } + + /// Clears the cached M5 submission-history geometry after firmware recovery restarts. + pub(super) fn reset_m5_history(&self) { + *self.m5_outer.lock() = None; + } + + /// M5: the availability domain outer-ring claims wait on. None off M5 or before attach. + pub(super) fn outer_domain(&self) -> Option> { + self.views() + .ok()? + .m5_credits + .as_ref() + .map(|credits| credits.available()) + } + + /// Reserves `count` slots on M5's shared outer ring without taking the device mutex. + /// Returns EBUSY if a device-mutex OuterScope is active or fewer than `count` slots are free. + pub(super) fn reserve_m5_outer( + &self, + priority: u8, + count: u32, + ) -> Result { + let views = self.views()?; + let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; + let (_, ring) = self.ring(priority)?; + let _guard = self.m5_outer.lock(); + if credits.is_scoped() { + return Err(EBUSY); + } + let cursors = ring.cursors()?; + credits.reserve(priority, count, cursors) + } + + /// Reserves one slot on M5's shared outer ring for a direct compute publisher without + /// taking the device mutex. Returns EBUSY if a device-mutex OuterScope is active or full. + pub(super) fn reserve_m5_compute(&self, priority: u8) -> Result { + self.reserve_m5_outer(priority, 1) + } + + /// Publishes one compute slot on M5's shared outer ring while the caller holds `m5_outer`, + /// consuming the caller's direct reservation. + pub(super) fn publish_m5_compute_locked( + &self, + _guard: &MutexGuard<'_, Option<(u32, u64, u64)>>, + priority: u8, + claim: &mut super::initdata::OuterClaim, + record: &WorkSlot, + ) -> Result { + if record.data_master != DataMaster::Compute as u32 { + return Err(EINVAL); + } + let views = self.views()?; + let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; + let (_, ring) = self.ring(priority)?; + let [first, second, producer] = ring.cursors()?; + let next = (producer + 1) % WORK_RING_SLOTS; + if next == first || next == second { + return Err(EIO); + } + // SAFETY: The ring view spans WORK_RING_SLOTS records, checked when the session built + // it; `producer` is in range. The reservation proves firmware does not own this slot and + // `m5_outer` excludes every other host writer on M5's shared outer ring. + unsafe { + core::ptr::copy_nonoverlapping( + core::ptr::from_ref(record).cast::(), + ring.slots + .add(producer as usize * core::mem::size_of::()), + core::mem::size_of::(), + ); + } + fence(Ordering::SeqCst); + // SAFETY: As for `RingView::cursors`. + unsafe { (*ring.producer).store(next, Ordering::Relaxed) }; + fence(Ordering::SeqCst); + credits.consume_direct(claim)?; + Ok(next) + } + + /// Issues an M5 host-port compute submission with gating held off while `m5_outer` is held. + pub(super) fn submit_m5_work_held_locked( + &self, + _guard: &MutexGuard<'_, Option<(u32, u64, u64)>>, + submission: &super::fw::m5::queue::HardwareSubmission, + ) -> Result { + self.regs.as_ref().ok_or(ENODEV)?.submit_m5_work_held(submission) + } + + /// Counts `submissions` in the M5 submission-history table without taking the device mutex, + /// while the caller holds `m5_outer`. + pub(super) fn note_m5_submission_history_locked( + &self, + geometry: &mut MutexGuard<'_, Option<(u32, u64, u64)>>, + submissions: u8, + ) -> Result { + let Some(history) = self.views()?.m5_history else { + return Ok(()); + }; + for _ in 0..64 { + // SAFETY: Pointers name retained, bounds-checked firmware-shared words. + let generation = unsafe { (*history.generation).load(Ordering::Acquire) }; + if generation & 1 != 0 { + core::hint::spin_loop(); + continue; + } + let (period, count) = match **geometry { + Some((seen, period, count)) if seen == generation => (period, count), + _ => { + // SAFETY: As above; seqlock generation recheck validates consistency. + let c = unsafe { + [ + (*history.config[0]).load(Ordering::Relaxed), + (*history.config[1]).load(Ordering::Relaxed), + (*history.config[2]).load(Ordering::Relaxed), + (*history.config[3]).load(Ordering::Relaxed), + ] + }; + fence(Ordering::Acquire); + // SAFETY: As above. + if generation != unsafe { (*history.generation).load(Ordering::Acquire) } { + core::hint::spin_loop(); + continue; + } + let period = u64::from(c[0]) | (u64::from(c[1]) << 32); + let count = u64::from(c[2]) | (u64::from(c[3]) << 32); + **geometry = Some((generation, period, count)); + (period, count) + } + }; + if period == 0 || count == 0 || count > 256 { + return Err(EINVAL); + } + let (counter, frequency) = qos::clock(); + let ticks = qos::time_from_host(counter, frequency)?; + let index = (ticks % period) / 25_000; + if index >= count { + return Err(ERANGE); + } + // SAFETY: `slots` spans 256 WC bytes and `index < count <= 256`. + unsafe { + let byte = history.slots.add(index as usize); + let value = core::ptr::read_volatile(byte).wrapping_add(submissions); + core::ptr::write_volatile(byte, value); + } + fence(Ordering::SeqCst); + return Ok(()); + } + Err(EBUSY) + } + + /// Reserves two slots on M5's shared outer ring for a direct render pair while + /// `m5_outer` is already held. Returns EBUSY if a device-mutex OuterScope is active + /// or fewer than two slots are free. + pub(super) fn reserve_m5_render_locked( + &self, + _guard: &MutexGuard<'_, Option<(u32, u64, u64)>>, + priority: u8, + ) -> Result<(M5RenderRoom, super::initdata::OuterClaim)> { + let views = self.views()?; + let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; + let (_, ring) = self.ring(priority)?; + if credits.is_scoped() { + return Err(EBUSY); + } + let cursors = ring.cursors()?; + let start = cursors[2]; + let next = [(start + 1) % WORK_RING_SLOTS, (start + 2) % WORK_RING_SLOTS]; + if next.iter().any(|&p| p == cursors[0] || p == cursors[1]) { + return Err(EBUSY); + } + let claim = credits.reserve(priority, 2, cursors)?; + Ok(( + M5RenderRoom { + priority, + start, + next, + }, + claim, + )) + } + + /// Copies an M5 render pair's fragment, then tiling record into the two reserved slots + /// of M5's shared outer ring without exposing them, commits accounting, issues the + /// host-port advance, and publishes inner producers (as `Firmware::submit_m5_render_pair`). + #[expect( + clippy::too_many_arguments, + reason = "Mirrors write_render_pair with the held M5 outer lock." + )] + pub(super) fn write_m5_render_pair( + &self, + _render: &MutexGuard<'_, ()>, + _m5_outer: &MutexGuard<'_, Option<(u32, u64, u64)>>, + room: &M5RenderRoom, + fragment: &WorkSlot, + tiling: &WorkSlot, + commit_accounting: impl FnOnce() -> Result, + publish_inner: impl FnOnce(), + ) -> Result<[u32; 2]> { + if !matches!(fragment.data_master, 1 | 2) || !matches!(tiling.data_master, 0 | 2) { + return Err(EINVAL); + } + let regs = self.regs.as_ref().ok_or(ENODEV)?; + let (_, ring) = self.ring(room.priority)?; + let records = [ + WorkSlot::new( + DataMaster::Compute, + fragment.queue_va, + fragment.qid, + fragment.items_end, + fragment.first != 0, + )?, + WorkSlot::new( + DataMaster::Compute, + tiling.queue_va, + tiling.qid, + tiling.items_end, + tiling.first != 0, + )?, + ]; + let submission = super::fw::m5::queue::HardwareSubmission::advance_pair( + fragment.qid, + tiling.qid, + )?; + let destinations = [room.start, room.next[0]].map(|index| { + // SAFETY: The ring view spans WORK_RING_SLOTS records; `reserve_m5_render_locked` + // validated both indices are in range and host-owned while `m5_outer` stays held. + unsafe { + ring.slots + .add(index as usize * core::mem::size_of::()) + } + }); + for (record, destination) in records.iter().zip(destinations) { + // SAFETY: Both slots are distinct, reserved, and protected by `m5_outer`. + unsafe { + core::ptr::copy_nonoverlapping( + core::ptr::from_ref(record).cast::(), + destination, + core::mem::size_of::(), + ); + } + } + commit_accounting()?; + regs.submit_m5_work(&submission)?; + publish_inner(); + Ok(room.next) + } + + /// Exposes a retained M5 render pair written by `write_m5_render_pair` with one + /// producer update and consumes its two direct outer-ring credits. + pub(super) fn expose_m5_render_pair( + &self, + _render: &MutexGuard<'_, ()>, + _m5_outer: &MutexGuard<'_, Option<(u32, u64, u64)>>, + room: &M5RenderRoom, + claim: &mut super::initdata::OuterClaim, + next: [u32; 2], + ) -> Result { + if next != room.next { + return Err(EBUSY); + } + let views = self.views()?; + let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; + let (_, ring) = self.ring(room.priority)?; + if ring.cursors()?[2] != room.start { + return Err(EBUSY); + } + fence(Ordering::SeqCst); + // SAFETY: As for `RingView::cursors`; `m5_outer` has been held continuously + // since `reserve_m5_render_locked` and `write_m5_render_pair`. + unsafe { (*ring.producer).store(room.next[1], Ordering::Relaxed) }; + fence(Ordering::SeqCst); + credits.consume_direct_count(claim, 2) + } + fn render_rings(&self, priority: u8) -> Result<(RingView, RingView)> { let views = self.views()?; let index = usize::from(priority); @@ -427,10 +782,14 @@ impl Port { policy: Policy, ) -> Result { let view = self.qos_view()?; - let publication = self - .qos - .lock() - .publish(&view, owner, scheduler, policy, qos::clock)?; + let publication = { + let mut qos = self.qos.lock(); + let publication = + qos.publish(&view, owner, scheduler, policy, qos::clock, super::now_ns())?; + self.oldest_in_flight_any + .store(qos.oldest_in_flight_any(), Ordering::Relaxed); + publication + }; self.rx_update(); Ok(publication) } @@ -443,17 +802,31 @@ impl Port { policy: Policy, ) -> Result<[qos::Publication; 2]> { let view = self.qos_view()?; - let publications = - self.qos - .lock() - .publish_owners(&view, owners, scheduler, policy, qos::clock)?; + let publications = { + let mut qos = self.qos.lock(); + let publications = qos.publish_owners( + &view, + owners, + scheduler, + policy, + qos::clock, + super::now_ns(), + )?; + self.oldest_in_flight_any + .store(qos.oldest_in_flight_any(), Ordering::Relaxed); + publications + }; self.rx_update(); Ok(publications) } pub(super) fn qos_cancel(&self, publication: qos::Publication) -> Result { let view = self.qos_view()?; - self.qos.lock().cancel(&view, publication) + let mut qos = self.qos.lock(); + qos.cancel(&view, publication)?; + self.oldest_in_flight_any + .store(qos.oldest_in_flight_any(), Ordering::Relaxed); + Ok(()) } /// Clears the QoS table rows of released QoS IDs (`QosIds::forget_released`); returns @@ -468,7 +841,12 @@ impl Port { pub(super) fn qos_complete(&self, owners: &[qos::Owner]) -> Result { let view = self.qos_view()?; - self.qos.lock().complete(&view, owners)?; + { + let mut qos = self.qos.lock(); + qos.complete(&view, owners, super::now_ns())?; + self.oldest_in_flight_any + .store(qos.oldest_in_flight_any(), Ordering::Relaxed); + } self.rx_update(); Ok(()) } @@ -481,10 +859,33 @@ impl Port { let Some(rx) = self.rx.as_ref() else { return; }; - let want = self.feed.gpu_bound().then_some(RX_UTIL_MIN_GPU_BOUND); + let want_state = if self.feed.gpu_bound() { + RX_STATE_GPU_BOUND + } else { + RX_STATE_DEFAULT + }; + if self.rx_state.load(Ordering::SeqCst) == want_state { + return; + } let mut applied = self.rx_applied.lock(); - if *applied != Some(want) && rx.set(want).is_ok() { - *applied = Some(want); + // Publish the transitioning state before re-reading `feed.gpu_bound()`, + // so a concurrent caller observing a newer feed state cannot return + // early against the stale mirrored value while this update is in flight. + self.rx_state.store(RX_STATE_UNSET, Ordering::SeqCst); + let gpu_bound = self.feed.gpu_bound(); + let want = gpu_bound.then_some(RX_UTIL_MIN_GPU_BOUND); + let want_state = if gpu_bound { + RX_STATE_GPU_BOUND + } else { + RX_STATE_DEFAULT + }; + if *applied != Some(want) { + if rx.set(want).is_ok() { + *applied = Some(want); + self.rx_state.store(want_state, Ordering::Release); + } + } else { + self.rx_state.store(want_state, Ordering::Release); } } @@ -538,7 +939,15 @@ impl Port { pub(super) fn set_effort_full(&self, full: bool) { self.effort_full.store(full, Ordering::SeqCst); - self.demand.set_active(full); + if full { + self.demand.set_active(true); + } else { + let mut busy = self.busy.lock(); + self.demand.set_active(false); + busy.clear_active(); + self.busy_window_start.store(0, Ordering::Relaxed); + self.busy_below_top.store(false, Ordering::Relaxed); + } } /// The next statistics drain and reader discard what the decoder holds. @@ -550,20 +959,100 @@ impl Port { self.statistics_epoch.load(Ordering::Acquire) } + /// Reports the busiest GPU engine's share of the last window (including unretired + /// in-flight commands) to CLPC once a window elapses or an in-flight command + /// saturates its engine. Lock-free on the common in-window path. + pub(super) fn report_busy(&self, now_ns: u64) { + if !self.demand.has_provider() { + return; + } + let start = self.busy_window_start.load(Ordering::Relaxed); + let window_due = + start == 0 || now_ns.saturating_sub(start) >= super::power::BUSY_WINDOW_NS; + let long_due = !window_due + && self.busy_below_top.load(Ordering::Relaxed) + && { + let oldest = self.oldest_in_flight_any.load(Ordering::Relaxed); + oldest != 0 + && now_ns.saturating_sub(oldest) >= super::power::BUSY_LONG_COMMAND_NS + }; + if !window_due && !long_due { + return; + } + // Read retired time (Acquire) before qos (lock Acquire): retirement calls + // qos_complete() before usage::Client::add() Release-adds ENGINE_NS, so we + // never observe both the retired time and the old in-flight timestamp. + let retired = crate::usage::ENGINE_NS + .each_ref() + .map(|ns| ns.load(Ordering::Acquire)); + let oldest = self.qos.lock().oldest_in_flight(); + let now_ns = super::now_ns().max(now_ns); + let mut busy = self.busy.lock(); + if let Some(permille) = busy.sample(now_ns, retired, oldest) { + self.demand.set_busy(permille); + } + self.busy_window_start + .store(busy.window_start().map_or(0, |s| s.max(1)), Ordering::Relaxed); + self.busy_below_top + .store(busy.below_top(), Ordering::Relaxed); + } + + /// Lifts CLPC to the top memory/fabric column immediately when a sustained busy run + /// ([`super::power::BusyRuns::bound`]) begins while the last reported share is below + /// the top column. Lock-free once at the top column. + pub(super) fn lift_busy_if_below_top(&self, now_ns: u64) { + if !self.demand.has_provider() || !self.busy_below_top.load(Ordering::Relaxed) { + return; + } + let retired = crate::usage::ENGINE_NS + .each_ref() + .map(|ns| ns.load(Ordering::Acquire)); + let oldest = self.qos.lock().oldest_in_flight(); + let now_ns = super::now_ns().max(now_ns); + let mut busy = self.busy.lock(); + if let Some(permille) = busy.lift_saturated(now_ns, retired, oldest) { + self.demand.set_busy(permille); + } + self.busy_window_start + .store(busy.window_start().map_or(0, |s| s.max(1)), Ordering::Relaxed); + self.busy_below_top + .store(busy.below_top(), Ordering::Relaxed); + } + + /// Wake delay (ns) for `idle_check` while a solo long command is running below + /// the top CLPC busy column, or `None` when already at top or idle. + pub(super) fn busy_recheck_delay(&self, now_ns: u64) -> Option { + if !self.demand.has_provider() || !self.busy_below_top.load(Ordering::Relaxed) { + return None; + } + let oldest = self.oldest_in_flight_any.load(Ordering::Relaxed); + super::power::BusyShare::recheck_delay_for(now_ns, oldest) + } + pub(super) fn note_gpu_activity(&self) { - // Observe gating before activity can wake the cores. A lockless + let now = super::now_ns(); + // The firmware gates the cores only after they idled for its idle-off delay, which + // follows the last job, so a publication within that delay of the previous one cannot + // follow a gating: skip the power register read (a few hundred ns) on back-to-back work. + // A direct publisher notes itself before it may fall back to its scheduler; a fallback + // published past the delay can then miss a gating, costing one statistics sample. + let idle_off_ns = u64::from(super::power::FIRMWARE_IDLE_OFF_MS) * 1_000_000; + let previous = self.last_submission_ns.load(Ordering::Relaxed); + let recent = now.saturating_sub(previous) < idle_off_ns; + // Otherwise observe gating before activity can wake the cores. A lockless // publisher cannot clear the decoder under the device mutex; this // epoch makes both the next drain and the next reader discard it. - if self - .regs - .as_ref() - .is_some_and(|regs| regs.g17_core_power() & 0xf == 0) + if !recent + && self + .regs + .as_ref() + .is_some_and(|regs| regs.g17_core_power() & 0xf == 0) { self.statistics_epoch.fetch_add(1, Ordering::Release); } - self.last_submission_ns - .store(super::now_ns(), Ordering::Relaxed); + self.last_submission_ns.store(now, Ordering::Relaxed); self.demand.set_active(true); + self.report_busy(now); } pub(super) fn write_power(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result { diff --git a/drivers/gpu/drm/asahi/g17/power.rs b/drivers/gpu/drm/asahi/g17/power.rs index 8ae6e5d1808ebe..c4e1125a6dbd99 100644 --- a/drivers/gpu/drm/asahi/g17/power.rs +++ b/drivers/gpu/drm/asahi/g17/power.rs @@ -49,6 +49,13 @@ pub(super) struct Effort { seen_waits: u64, /// When a waiter was last seen. last_wait_ns: u64, + /// A host thread waits, or waited within [`IDLE_HOLD_NS`], for a pure-compute submission + /// ([`Self::note_compute_waiters`]). + compute_waited: bool, + /// Pure-compute waits begun when compute waiters were last noted. + seen_compute_waits: u64, + /// When a pure-compute waiter was last seen. + last_compute_wait_ns: u64, /// The GPU has run longer than [`IDLE_HOLD_NS`] without an idle gap ([`BusyRun`]). bound: bool, } @@ -64,6 +71,9 @@ impl Effort { waited: false, seen_waits: 0, last_wait_ns: 0, + compute_waited: false, + seen_compute_waits: 0, + last_compute_wait_ns: 0, bound: false, } } @@ -92,6 +102,40 @@ impl Effort { changed } + /// Whether a host thread waits for a pure-compute submission ([`Self::note_compute_waiters`]). + pub(super) fn compute_waited(&self) -> bool { + self.compute_waited + } + + /// Notes host waiters on pure-compute submissions at `now_ns` + /// ([`super::fence::compute_waiters`]). Holds for [`IDLE_HOLD_NS`] after the last compute + /// wait so depth-1 compute loops stay at full effort across host turnarounds and resume at + /// full effort immediately after CPU gaps without affecting paced render compositors. + pub(super) fn note_compute_waiters( + &mut self, + now_ns: u64, + (waiters, waits): (u32, u64), + ) -> bool { + if waiters > 0 || waits != self.seen_compute_waits { + self.last_compute_wait_ns = now_ns.max(1); + } + self.seen_compute_waits = waits; + let compute_waited = self.last_compute_wait_ns != 0 + && now_ns.saturating_sub(self.last_compute_wait_ns) < IDLE_HOLD_NS; + let changed = compute_waited != self.compute_waited; + self.compute_waited = compute_waited; + changed + } + + /// Whether [`Self::idle`] at `now_ns` with `in_flight` will clear the effort state. + pub(super) fn will_clear(&self, now_ns: u64, in_flight: bool) -> bool { + self.streaming + && !in_flight + && self + .idle_since + .is_some_and(|since| now_ns.saturating_sub(since) >= IDLE_HOLD_NS) + } + /// Whether the GPU has run without an idle gap for longer than the effort is held after /// work stops ([`BusyRun::bound`]). pub(super) fn bound(&self) -> bool { @@ -145,8 +189,10 @@ impl Effort { if idle >= IDLE_HOLD_NS { self.streaming = false; self.waited = false; + self.compute_waited = false; self.bound = false; self.last_wait_ns = 0; + self.last_compute_wait_ns = 0; self.idle_since = None; IdleAction::Clear } else { @@ -420,6 +466,168 @@ pub(super) fn release(control: &mut C) -> kernel::error::Result { result } +/// Busy-share window: long enough to span frames, short enough to follow a burst. +pub(super) const BUSY_WINDOW_NS: u64 = 200_000_000; +/// A longer gap between reports with no long command in flight was idle: start over +/// rather than average it in. +pub(super) const BUSY_WINDOW_MAX_NS: u64 = 2_000_000_000; +/// An unretired command that has been running continuously for this long saturates +/// its engine and immediately lifts the busy share to 1000 permille, without waiting +/// for it to retire or for the current window to end. +pub(super) const BUSY_LONG_COMMAND_NS: u64 = 50_000_000; + +/// Per-window busiest GPU engine share (0..=1000 permille), combining retired stage +/// execution time with unretired in-flight command time. +/// +/// The vertex, fragment and compute engines run in parallel, so their summed time is +/// not a share of the window: taking the busiest engine's share avoids double-counting +/// across engines. For each engine, `retired_ns + in_flight_age` is differenced across +/// window boundaries so a command spanning a boundary counts in the window it runs in +/// and is never double-counted when it later retires. Any engine with an unretired +/// command older than [`BUSY_LONG_COMMAND_NS`] lifts immediately to 1000 permille so +/// long compute or render work running beside a light compositor never sits at a low +/// memory floor waiting for retirement. In-flight age counts from publication, so time +/// a command waits in its queue or on dependencies, and a render's vertex and fragment +/// stages retiring together, err toward a higher share, which is the safe direction. +pub(super) struct BusyShare { + start_ns: Option, + retired_ns: [u64; crate::usage::NUM_ENGINES], + in_flight_ns: [u64; crate::usage::NUM_ENGINES], + below_top: bool, +} + +impl BusyShare { + pub(super) const fn new() -> Self { + Self { + start_ns: None, + retired_ns: [0; crate::usage::NUM_ENGINES], + in_flight_ns: [0; crate::usage::NUM_ENGINES], + below_top: false, + } + } + + /// CLPC cleared GPU activity (forgetting its last share so a new burst starts + /// at the top column). Only called once the GPU is idle: restart the window so + /// the first report of the next burst re-baselines instead of closing a window + /// diluted by the idle gap, which would drop the burst off the top column. + pub(super) fn clear_active(&mut self) { + self.start_ns = None; + self.in_flight_ns = [0; crate::usage::NUM_ENGINES]; + self.below_top = false; + } + + pub(super) fn below_top(&self) -> bool { + self.below_top + } + + /// Immediately lifts the reported share to 1000 permille when a sustained busy run + /// ([`BusyRuns::bound`]) begins while below the top CLPC column, and re-baselines the + /// measurement window at `now_ns` so short back-to-back commands are neither trapped + /// at a low memory/fabric floor for up to [`BUSY_WINDOW_NS`] nor diluted by prior + /// light activity. + pub(super) fn lift_saturated( + &mut self, + now_ns: u64, + retired_ns: [u64; crate::usage::NUM_ENGINES], + oldest_in_flight: [u64; crate::usage::NUM_ENGINES], + ) -> Option { + if !self.below_top { + return None; + } + self.start_ns = Some(now_ns); + self.retired_ns = retired_ns; + for (slot, &since) in self.in_flight_ns.iter_mut().zip(oldest_in_flight.iter()) { + *slot = if since != 0 { + now_ns.saturating_sub(since) + } else { + 0 + }; + } + self.below_top = false; + Some(1000) + } + + pub(super) fn window_start(&self) -> Option { + self.start_ns + } + + pub(super) fn is_long_in_flight( + now_ns: u64, + oldest_in_flight: [u64; crate::usage::NUM_ENGINES], + ) -> bool { + oldest_in_flight + .iter() + .any(|&since| since != 0 && now_ns.saturating_sub(since) >= BUSY_LONG_COMMAND_NS) + } + + /// Delay (ns) until an in-flight command reaches [`BUSY_LONG_COMMAND_NS`], at + /// least 1 ms. Retirement runs its own event pass, so this never delays idle + /// teardown. + pub(super) fn recheck_delay_for(now_ns: u64, oldest: u64) -> Option { + if oldest == 0 { + return None; + } + let age = now_ns.saturating_sub(oldest); + Some(BUSY_LONG_COMMAND_NS.saturating_sub(age).max(1_000_000)) + } + + pub(super) fn sample( + &mut self, + now_ns: u64, + retired_ns: [u64; crate::usage::NUM_ENGINES], + oldest_in_flight: [u64; crate::usage::NUM_ENGINES], + ) -> Option { + let long_in_flight = Self::is_long_in_flight(now_ns, oldest_in_flight); + let Some(start) = self.start_ns else { + self.start_ns = Some(now_ns); + self.retired_ns = retired_ns; + for (slot, &since) in self.in_flight_ns.iter_mut().zip(oldest_in_flight.iter()) { + *slot = if since != 0 { + now_ns.saturating_sub(since) + } else { + 0 + }; + } + return None; + }; + let elapsed = now_ns.saturating_sub(start); + if elapsed < BUSY_WINDOW_NS { + if self.below_top && long_in_flight { + self.below_top = false; + return Some(1000); + } + return None; + } + let mut busiest = 0u64; + for i in 0..crate::usage::NUM_ENGINES { + let now = retired_ns[i]; + let delta = now.saturating_sub(self.retired_ns[i]); + self.retired_ns[i] = now; + let since = oldest_in_flight[i]; + let age = if since != 0 { + now_ns.saturating_sub(since) + } else { + 0 + }; + let prev_age = self.in_flight_ns[i]; + self.in_flight_ns[i] = age; + let busy = delta.saturating_add(age).saturating_sub(prev_age); + busiest = busiest.max(busy); + } + self.start_ns = Some(now_ns); + if elapsed > BUSY_WINDOW_MAX_NS && !long_in_flight { + return None; + } + let permille = if long_in_flight { + 1000 + } else { + (busiest.saturating_mul(1000) / elapsed).min(1000) as u32 + }; + self.below_top = permille < 1000; + Some(permille) + } +} + #[cfg_attr(not(test), kernel::macros::kunit_tests(asahi_g17_idle_hold))] mod tests { use super::*; @@ -576,12 +784,212 @@ mod tests { hold.asserted(); assert_eq!(hold.step(1, false, 2, FIRMWARE_IDLE_OFF_MS), HoldAction::Release); } + + #[test] + fn long_in_flight_command_lifts_beside_light_submitter() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + // Establish light compositor baseline: ~50 permille (10 ms in 200 ms). + assert_eq!(share.sample(1000 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!( + share.sample(1200 * NS_MS, [2 * NS_MS, 10 * NS_MS, 0], [0, 0, 0]), + Some(50) + ); + assert!(share.below_top()); + // A 500 ms compute job starts at t=1250 ms; compositor submits at t=1410 ms. + assert_eq!( + share.sample( + 1410 * NS_MS, + [4 * NS_MS, 20 * NS_MS, 0], + [0, 0, 1250 * NS_MS], + ), + Some(1000) + ); + assert!(!share.below_top()); + // Still running across the next window at t=1610 ms: stays at 1000. + assert_eq!( + share.sample( + 1610 * NS_MS, + [6 * NS_MS, 30 * NS_MS, 0], + [0, 0, 1250 * NS_MS], + ), + Some(1000) + ); + // Retires at t=1750 ms (+500 ms retired); only the 140 ms in [1610, 1750] counts. + assert_eq!( + share.sample(1810 * NS_MS, [8 * NS_MS, 40 * NS_MS, 500 * NS_MS], [0, 0, 0]), + Some(700) + ); + // Next window returns cleanly to the light compositor share. + assert_eq!( + share.sample(2010 * NS_MS, [10 * NS_MS, 50 * NS_MS, 500 * NS_MS], [0, 0, 0]), + Some(50) + ); + } + + #[test] + fn late_long_command_lifts_mid_window_without_double_counting() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + assert_eq!(share.sample(1000 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(share.sample(1200 * NS_MS, [0, 10 * NS_MS, 0], [0, 0, 0]), Some(50)); + // Long compute starts at t=1390 ms; window closes at t=1410 ms (only 20 ms old). + assert_eq!( + share.sample(1410 * NS_MS, [0, 20 * NS_MS, 0], [0, 0, 1390 * NS_MS]), + Some(95) + ); + assert!(share.below_top()); + // At t=1440 ms (50 ms old, mid-window), early lift reports 1000 immediately. + assert_eq!( + share.sample(1440 * NS_MS, [0, 22 * NS_MS, 0], [0, 0, 1390 * NS_MS]), + Some(1000) + ); + assert!(!share.below_top()); + // Second mid-window submit does not spam CLPC. + assert_eq!( + share.sample(1460 * NS_MS, [0, 23 * NS_MS, 0], [0, 0, 1390 * NS_MS]), + None + ); + // Retires at t=1490 ms (+100 ms retired); window [1410, 1610] credits exact 80 ms. + assert_eq!( + share.sample(1610 * NS_MS, [0, 30 * NS_MS, 100 * NS_MS], [0, 0, 0]), + Some(400) + ); + } + + #[test] + fn straddling_short_command_and_long_gaps_behave_cleanly() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + assert_eq!(share.sample(1000 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + // 40 ms command [1170, 1210] straddles boundary 1200: 30 ms in first, 10 ms in second. + assert_eq!( + share.sample(1200 * NS_MS, [0, 0, 0], [0, 0, 1170 * NS_MS]), + Some(150) + ); + assert_eq!( + share.sample(1400 * NS_MS, [0, 0, 40 * NS_MS], [0, 0, 0]), + Some(50) + ); + // Multi-engine takes busiest engine rather than summing parallel engines. + assert_eq!( + share.sample(1600 * NS_MS, [0, 120 * NS_MS, 150 * NS_MS], [0, 0, 0]), + Some(600) + ); + // >2 s idle gap with a freshly-started command (age 0) restarts without reporting. + assert_eq!( + share.sample(5000 * NS_MS, [0, 120 * NS_MS, 150 * NS_MS], [0, 0, 5000 * NS_MS]), + None + ); + // >2 s active command still reports 1000. + assert_eq!( + share.sample(8000 * NS_MS, [0, 120 * NS_MS, 150 * NS_MS], [0, 0, 5000 * NS_MS]), + Some(1000) + ); + // Recheck delay wakes once at the long-command age (at least 1 ms), None when idle. + assert_eq!(BusyShare::recheck_delay_for(1010 * NS_MS, 0), None); + assert_eq!( + BusyShare::recheck_delay_for(1010 * NS_MS, 1000 * NS_MS), + Some(40 * NS_MS) + ); + assert_eq!( + BusyShare::recheck_delay_for(1045 * NS_MS, 1000 * NS_MS), + Some(5 * NS_MS) + ); + assert_eq!( + BusyShare::recheck_delay_for(1100 * NS_MS, 1000 * NS_MS), + Some(NS_MS) + ); + } + + #[test] + fn new_burst_after_idle_restarts_the_window() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + // Steady 600 permille fragment work. + assert_eq!(share.sample(900 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(share.sample(1100 * NS_MS, [0, 120 * NS_MS, 0], [0, 0, 0]), Some(600)); + assert_eq!(share.sample(1300 * NS_MS, [0, 240 * NS_MS, 0], [0, 0, 0]), Some(600)); + // Work continues to 1400 ms, then the GPU idles and CLPC clears its share. + share.clear_active(); + assert!(!share.below_top()); + // First submission after a 600 ms idle gap: closing [1300, 2000] would report + // a diluted 85 permille (60 ms in 700 ms); it re-baselines instead. + assert_eq!(share.sample(2000 * NS_MS, [0, 300 * NS_MS, 0], [0, 0, 0]), None); + assert!(!share.below_top()); + // No report until a fresh 200 ms window of the new burst completes. + assert_eq!(share.sample(2190 * NS_MS, [0, 414 * NS_MS, 0], [0, 0, 0]), None); + assert_eq!(share.sample(2200 * NS_MS, [0, 420 * NS_MS, 0], [0, 0, 0]), Some(600)); + } + + #[test] + fn sustained_busy_run_lifts_short_dispatches_mid_window() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + // Light compositor establishes a 50 permille floor (below top). + assert_eq!(share.sample(1000 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(share.sample(1200 * NS_MS, [0, 10 * NS_MS, 0], [0, 0, 0]), Some(50)); + assert!(share.below_top()); + // Short (<50 ms) compute dispatches saturate the GPU starting at t=1300 ms. + // At t=1316 ms BusyRuns::bound triggers lift_saturated(), lifting immediately. + assert_eq!( + share.lift_saturated(1316 * NS_MS, [0, 14 * NS_MS, 16 * NS_MS], [0, 0, 0]), + Some(1000) + ); + assert!(!share.below_top()); + // Repeated calls while already at top are a no-op. + assert_eq!( + share.lift_saturated(1332 * NS_MS, [0, 14 * NS_MS, 32 * NS_MS], [0, 0, 0]), + None + ); + // The re-baselined 200 ms window [1316, 1516] measures the burst cleanly (1000 permille). + assert_eq!( + share.sample(1516 * NS_MS, [0, 14 * NS_MS, 216 * NS_MS], [0, 0, 0]), + Some(1000) + ); + assert!(!share.below_top()); + // Once the burst ends, the next window returns cleanly to the light compositor share. + assert_eq!( + share.sample(1716 * NS_MS, [0, 24 * NS_MS, 216 * NS_MS], [0, 0, 0]), + Some(50) + ); + assert!(share.below_top()); + } + + #[test] + fn compute_waiters_lift_immediately_and_expire_while_streaming() { + const NS_MS: u64 = 1_000_000; + let mut effort = Effort::new(); + effort.submit(); + assert!(!effort.compute_waited()); + // Render waiter alone never marks compute_waited. + assert!(effort.note_waiters(10 * NS_MS, (1, 1))); + assert!(!effort.note_compute_waiters(10 * NS_MS, (0, 0))); + assert!(!effort.compute_waited()); + // A pure-compute waiter lifts immediately. + assert!(effort.note_compute_waiters(11 * NS_MS, (1, 1))); + assert!(effort.compute_waited()); + // Holds across a short host turnaround between depth-1 dispatches. + assert!(!effort.note_compute_waiters(15 * NS_MS, (0, 1))); + assert!(effort.compute_waited()); + // Expires cleanly after IDLE_HOLD_NS even while a compositor keeps streaming. + assert!(effort.note_compute_waiters(11 * NS_MS + IDLE_HOLD_NS, (0, 1))); + assert!(!effort.compute_waited()); + // Idle clear also resets compute_waited. + assert!(effort.note_compute_waiters(40 * NS_MS, (1, 2))); + assert!(effort.compute_waited()); + assert_eq!(effort.idle(40 * NS_MS, false), IdleAction::Recheck(IDLE_HOLD_NS)); + assert!(effort.will_clear(40 * NS_MS + IDLE_HOLD_NS, false)); + assert_eq!(effort.idle(40 * NS_MS + IDLE_HOLD_NS, false), IdleAction::Clear); + assert!(!effort.compute_waited()); + } } unsafe extern "C" { fn asahi_clpc_gpu_get(dev: *mut core::ffi::c_void, out: *mut *mut core::ffi::c_void) -> core::ffi::c_int; fn asahi_clpc_gpu_set_active(gpu: *mut core::ffi::c_void, active: bool); fn asahi_clpc_gpu_put(gpu: *mut core::ffi::c_void); + fn asahi_clpc_gpu_set_busy(gpu: *mut core::ffi::c_void, permille: core::ffi::c_uint); } /// DT-selected memory-demand provider. Its independent allocation outlives a @@ -605,10 +1013,19 @@ impl Demand { } } + pub(super) fn has_provider(&self) -> bool { + !self.0.is_null() + } + pub(super) fn set_active(&self, active: bool) { // SAFETY: the retained reference is live; NULL denotes no DT provider. unsafe { asahi_clpc_gpu_set_active(self.0, active) }; } + + pub(super) fn set_busy(&self, permille: u32) { + // SAFETY: the retained reference is live; NULL denotes no DT provider. + unsafe { asahi_clpc_gpu_set_busy(self.0, permille.min(1000) as core::ffi::c_uint) }; + } } impl Drop for Demand { diff --git a/drivers/gpu/drm/asahi/g17/qos.rs b/drivers/gpu/drm/asahi/g17/qos.rs index 5adccb14b5cad7..36a20a5e02d8fa 100644 --- a/drivers/gpu/drm/asahi/g17/qos.rs +++ b/drivers/gpu/drm/asahi/g17/qos.rs @@ -6,7 +6,10 @@ //! precedes submitted counters; retiring a final owner clears only its two row //! bytes. Cancellation balances host references without rewinding shared counts. -use super::fw::{qos as fw, queue::Policy}; +use super::fw::{ + qos as fw, + queue::{DataMaster, Policy}, +}; use crate::hw::t8140::qos as cfg; use core::{ mem::offset_of, @@ -14,6 +17,13 @@ use core::{ }; use kernel::prelude::*; +const _: () = { + assert!(fw::QUEUES <= 128); + assert!(DataMaster::Tiling as usize == crate::usage::Engine::Vertex as usize); + assert!(DataMaster::Fragment as usize == crate::usage::Engine::Fragment as usize); + assert!(DataMaster::Compute as usize == crate::usage::Engine::Compute as usize); +}; + /// Atomic views retain the allocation borrow and never borrow firmware words /// as ordinary mutable memory. The arrays are disjoint apart from the explicit /// data-master time/count indexing in `times_and_counts`. @@ -87,6 +97,11 @@ pub(crate) struct Accounting { in_flight: [u32; fw::QUEUES], dm_in_flight: [u64; fw::DATA_MASTERS], dm_by_qid: [u8; fw::QUEUES], + /// Bitmask of QIDs with `in_flight[qid] > 0`. + active_qids: u128, + /// Monotonic start timestamp (ns) of each active QID's oldest unretired command, + /// advanced when a command completes with more work still in flight on that QID. + qid_since_ns: [u64; fw::QUEUES], /// The table's rows and counts as last stored, indexed as in [`View`]. Only the host /// writes them, so a publication counts on from these instead of reading them back. rows: [[u8; 8]; fw::QUEUES], @@ -101,6 +116,8 @@ impl Accounting { in_flight: [0; fw::QUEUES], dm_in_flight: [0; fw::DATA_MASTERS], dm_by_qid: [0; fw::QUEUES], + active_qids: 0, + qid_since_ns: [0; fw::QUEUES], rows: [[0; 8]; fw::QUEUES], queue_submitted: [0; fw::QUEUES], owner_submitted: [0; fw::QUEUES], @@ -119,8 +136,9 @@ impl Accounting { scheduler: u64, policy: Policy, clock: impl FnOnce() -> (u64, u64), + now_ns: u64, ) -> Result { - let [publication] = self.publish_owners(view, [owner], scheduler, policy, clock)?; + let [publication] = self.publish_owners(view, [owner], scheduler, policy, clock, now_ns)?; Ok(publication) } @@ -136,6 +154,7 @@ impl Accounting { scheduler: u64, policy: Policy, clock: impl FnOnce() -> (u64, u64), + now_ns: u64, ) -> Result<[Publication; N]> { if scheduler == 0 { return Err(EINVAL); @@ -219,6 +238,10 @@ impl Accounting { let mut record = rows[index]; record[0] = owner.qos; record[1] = class; + if self.in_flight[qid] == 0 { + self.qid_since_ns[qid] = now_ns.max(1); + self.active_qids |= 1u128 << qid; + } self.in_flight[qid] += 1; self.dm_in_flight[dm] += 1; self.dm_by_qid[qid] = owner.data_master; @@ -243,7 +266,7 @@ impl Accounting { { return Err(EIO); } - self.complete(view, &[ticket.owner]) + self.complete_inner(view, &[ticket.owner], 0, true) } /// Clears the scheduler and share rows of the QoS IDs in `ids`, which no context holds: a @@ -271,7 +294,17 @@ impl Accounting { /// Preflights the entire set before clearing any final row. QID membership, /// scheduler mappings and monotonically increasing counts remain intact. - pub(crate) fn complete(&mut self, view: &View<'_>, owners: &[Owner]) -> Result { + pub(crate) fn complete(&mut self, view: &View<'_>, owners: &[Owner], now_ns: u64) -> Result { + self.complete_inner(view, owners, now_ns, false) + } + + fn complete_inner( + &mut self, + view: &View<'_>, + owners: &[Owner], + now_ns: u64, + cancelled: bool, + ) -> Result { let mut completed = [0u64; fw::DATA_MASTERS]; for (index, owner) in owners.iter().copied().enumerate() { let (qid, _, dm) = owner.indices()?; @@ -300,7 +333,14 @@ impl Accounting { } } for owner in owners { - self.in_flight[usize::from(owner.qid)] -= 1; + let qid = usize::from(owner.qid); + self.in_flight[qid] -= 1; + if self.in_flight[qid] == 0 { + self.qid_since_ns[qid] = 0; + self.active_qids &= !(1u128 << qid); + } else if !cancelled { + self.qid_since_ns[qid] = now_ns.max(1); + } } for (dm, count) in completed.iter().enumerate() { self.dm_in_flight[dm] -= count; @@ -308,6 +348,32 @@ impl Accounting { fence(Ordering::SeqCst); Ok(()) } + + /// Oldest unretired command timestamp (monotonic ns) per engine + /// (vertex, fragment, compute), or 0 when that engine has none in flight. + pub(crate) fn oldest_in_flight(&self) -> [u64; crate::usage::NUM_ENGINES] { + let mut oldest = [0u64; crate::usage::NUM_ENGINES]; + let mut mask = self.active_qids; + while mask != 0 { + let qid = mask.trailing_zeros() as usize; + mask &= mask - 1; + let dm = usize::from(self.dm_by_qid[qid]); + let since = self.qid_since_ns[qid]; + if dm < oldest.len() && since != 0 && (oldest[dm] == 0 || since < oldest[dm]) { + oldest[dm] = since; + } + } + oldest + } + + /// Oldest unretired command timestamp across all engines, or 0 if idle. + pub(crate) fn oldest_in_flight_any(&self) -> u64 { + self.oldest_in_flight() + .into_iter() + .filter(|&since| since != 0) + .min() + .unwrap_or(0) + } } /// Firmware accounting uses a 24 MHz domain independent of host timer speed. diff --git a/drivers/gpu/drm/asahi/g17/queue/admission.rs b/drivers/gpu/drm/asahi/g17/queue/admission.rs index cc93cb6167981b..2cdad54f1706bd 100644 --- a/drivers/gpu/drm/asahi/g17/queue/admission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/admission.rs @@ -65,6 +65,7 @@ fn wait_slice_ms(deadline_ns: u64, now_ns: u64) -> Result { struct State { active: u64, refs: [u8; cfg::RENDER_SLOTS], + /// The owner of each slot. Written only by [`Self::set_owner`], which keeps `wide` with it. owners: [u64; cfg::RENDER_SLOTS], epochs: [u64; cfg::RENDER_SLOTS], quarantined: u64, @@ -90,6 +91,19 @@ struct State { /// The physical queue table still has room for a pair built in an unowned slot. The /// runtime updates this whenever the table changes. build_room: bool, + /// Slots that take their owner's renders that run on one of a two-pair queue's pairs + /// ([`crate::g17::pairs::for_window`]), so the objects of a layout too large for two pairs + /// exist in that pair only: at most one per owner ([`Self::mark_wide`]). A mark belongs to its + /// owner's tenure of the slot: [`Self::set_owner`] drops it whenever the slot changes hands. + wide: u64, + /// Total dedicated render pairs the QID table can hold (installed plus buildable). + /// Updated alongside `build_room` so sibling admission preserves first-pair capacity. + render_capacity: usize, + /// Live slots on which the current owner has published (or started) a + /// firmware-visible render graph; unpublished siblings yield before + /// published ones, and reclaiming a published sibling keeps its installed + /// QIDs in the `released` state for `bind_owner()` reuse. + published: u64, released: u64, epoch: u64, footprints: KVec, @@ -112,12 +126,60 @@ impl State { killed_at: [0; cfg::RENDER_SLOTS], held: 0, build_room: true, + wide: 0, + render_capacity: cfg::RENDER_SLOTS - 1, + published: 0, released: 0, epoch: 0, footprints: KVec::new(), next_ticket: 1, } } + fn owns_live(&self, owner: u64, slot: usize) -> bool { + self.owners.get(slot) == Some(&owner) && self.released & (1u64 << slot) == 0 + } + fn has_live_owner(&self, owner: u64) -> bool { + (1..cfg::RENDER_SLOTS).any(|slot| self.owns_live(owner, slot)) + } + fn mark_published(&mut self, slot: u8) { + let index = usize::from(slot); + if index > 0 && index < cfg::RENDER_SLOTS { + let bit = 1u64 << index; + if self.owners[index] != 0 && self.released & bit == 0 { + self.published |= bit; + } + } + } + fn live_owners(&self) -> usize { + let mut count = 0usize; + for slot in 1..cfg::RENDER_SLOTS { + let owner = self.owners[slot]; + if owner == 0 || self.released & (1u64 << slot) != 0 { + continue; + } + if !(1..slot).any(|prev| { + self.owners[prev] == owner && self.released & (1u64 << prev) == 0 + }) { + count += 1; + } + } + count + } + fn live_siblings(&self) -> usize { + let mut siblings = 0usize; + for slot in 1..cfg::RENDER_SLOTS { + let owner = self.owners[slot]; + if owner == 0 || self.released & (1u64 << slot) != 0 { + continue; + } + if (1..slot).any(|prev| { + self.owners[prev] == owner && self.released & (1u64 << prev) == 0 + }) { + siblings += 1; + } + } + siblings + } fn exhausted(&self) -> bool { self.quarantined & Self::MASK == Self::MASK } @@ -127,11 +189,18 @@ impl State { /// sibling never bypasses it. fn owner_quarantine(&self, owner: u64) -> Option { let owned = (0..cfg::RENDER_SLOTS) - .filter(|slot| self.owners[*slot] == owner) + .filter(|slot| self.owns_live(owner, *slot)) .fold(0u64, |mask, slot| mask | 1u64 << slot); let quarantined = self.quarantined & owned; (quarantined != 0).then_some(quarantined & !self.spared == 0) } + /// Released means closed: by its client, or by the kernel for a client that keeps it open + /// (`Firmware::close_failed_owners`), which then never releases it again. A pair taken + /// back, or a sibling claimed, would clear `released` and leak. Owner IDs are never reused. + /// Checked where a lease is made only, so `admits_render` lets such a job fail at once. + fn owner_released(&self, owner: u64) -> bool { + (0..cfg::RENDER_SLOTS).any(|slot| self.owners[slot] == owner && self.released & (1u64 << slot) != 0) + } fn refusal(&self, owner: u64) -> Result { if self.exhausted() { return Err(EIO); @@ -139,43 +208,57 @@ impl State { if self.owner_quarantine(owner).is_some() { return Err(EIO); } - match self.owners.iter().position(|id| *id == owner) { - None if !self.owners[1..].contains(&0) - && self.released - & !self.active - & !self.quarantined - & !self.kill_hold + if !self.has_live_owner(owner) + && !self.owners[1..].contains(&0) + && self.released + & !self.active + & !self.quarantined + & !self.kill_hold & !self.held - & Self::MASK - == 0 => - { - Err(crate::g17::capacity::refused(crate::g17::capacity::Site::RenderSlots)) - } - _ => Ok(()), + & Self::MASK + == 0 + { + return Err(crate::g17::capacity::refused(crate::g17::capacity::Site::RenderSlots)); } + Ok(()) } fn advance(&mut self, slot: usize) { self.epoch = self.epoch.wrapping_add(1); self.epochs[slot] = self.epoch; } - fn take_idle(&mut self, slot: usize, owner: u64) -> u8 { + /// Gives `slot` to `owner` (0: to nobody): the one writer of `owners`. A new owner starts + /// without the slot's one-pair mark. + fn set_owner(&mut self, slot: usize, owner: u64) { if self.owners[slot] != owner { - crate::g17::trace::teardown( - 6, - slot as u64, - self.owners[slot], - owner | u64::from(self.killed & (1u64 << slot) != 0) << 63, - ); + self.wide &= !(1u64 << slot); + } + self.owners[slot] = owner; + } + fn take_idle(&mut self, slot: usize, owner: u64) -> u8 { + if self.owners[slot] != owner || self.released & (1u64 << slot) != 0 { + if self.owners[slot] != owner { + crate::g17::trace::teardown( + 6, + slot as u64, + self.owners[slot], + owner | u64::from(self.killed & (1u64 << slot) != 0) << 63, + ); + } self.killed &= !(1u64 << slot); + self.published &= !(1u64 << slot); } self.refs[slot] += 1; self.active |= 1u64 << slot; self.released &= !(1u64 << slot); - self.owners[slot] = owner; + self.set_owner(slot, owner); self.advance(slot); slot as u8 } + #[cfg(CONFIG_KUNIT = "y")] fn acquire(&mut self, owner: u64, pairs: usize) -> Option { + self.acquire_for(owner, pairs, 0) + } + fn acquire_for(&mut self, owner: u64, pairs: usize, open_queues: usize) -> Option { if owner == 0 { return None; } @@ -201,25 +284,26 @@ impl State { // only while this owner has no live kick, before constructing it. let idle = (0..cfg::RENDER_SLOTS) .filter(|slot| { - self.owners[*slot] == owner + self.owns_live(owner, *slot) && self.refs[*slot] == 0 && self.quarantined & (1u64 << slot) == 0 + && self.can_lease_slot(owner, *slot, open_queues) }) .max_by_key(|slot| (self.epochs[*slot], usize::MAX - *slot)); if let Some(slot) = idle { if !(0..cfg::RENDER_SLOTS) - .any(|other| self.owners[other] == owner && self.refs[other] != 0) + .any(|other| self.owns_live(owner, other) && self.refs[other] != 0) { - self.claim_sibling(owner, pairs); + self.claim_sibling(owner, pairs, open_queues); } return Some(self.take_idle(slot, owner)); } - if self.owners.contains(&owner) { + if self.has_live_owner(owner) { // Consecutive kicks are ordered by firmware dependencies. Stack // onto the least-loaded retained pair without a retirement wait. let slot = (0..cfg::RENDER_SLOTS) .filter(|slot| { - self.owners[*slot] == owner + self.owns_live(owner, *slot) && self.quarantined & (1u64 << slot) == 0 && self.active & (1u64 << slot) != 0 && self.refs[*slot] < cfg::RENDER_DEPTH @@ -249,12 +333,133 @@ impl State { }) .or_else(unowned)?; let first = self.take_idle(slot, owner); - self.claim_sibling(owner, pairs); + self.claim_sibling(owner, pairs, open_queues); Some(first) } - /// Claims another pair for an owner that may hold `pairs`. - fn claim_sibling(&mut self, owner: u64, pairs: usize) { - if self.owners.iter().filter(|id| **id == owner).count() >= pairs { + fn unavailable_released(&self) -> usize { + (self.released + & (self.active | self.quarantined | self.kill_hold | self.held) + & Self::MASK) + .count_ones() as usize + } + + /// Idle live siblings in `eligible` (unpublished or drained published) + /// that can be given back without taking any live owner's last usable pair. + fn reclaimable_siblings_in(&self, eligible: u64) -> usize { + let unavailable = self.quarantined | self.kill_hold | self.held; + let mut reclaimable = 0usize; + for slot in 1..cfg::RENDER_SLOTS { + let owner = self.owners[slot]; + if owner == 0 || self.released & (1u64 << slot) != 0 { + continue; + } + if (1..slot).any(|prev| { + self.owners[prev] == owner && self.released & (1u64 << prev) == 0 + }) { + continue; + } + let mut usable = 0usize; + let mut candidates = 0usize; + for s in slot..cfg::RENDER_SLOTS { + let bit = 1u64 << s; + if self.owners[s] != owner || self.released & bit != 0 { + continue; + } + if unavailable & bit == 0 { + usable += 1; + if eligible & bit != 0 + && self.refs[s] == 0 + && (self.active | self.killed) & bit == 0 + { + candidates += 1; + } + } + } + reclaimable += candidates.min(usable.saturating_sub(1)); + } + reclaimable + } + + fn reclaimable_siblings(&self) -> usize { + self.reclaimable_siblings_in(Self::MASK) + } + + /// Whether leasing `slot` for live `owner` would turn a reclaimable + /// sibling into protected (non-reclaimable) demand. + fn promotes_reclaimable_sibling(&self, owner: u64, slot: usize) -> bool { + if slot == 0 || slot >= cfg::RENDER_SLOTS || owner == 0 { + return false; + } + let bit = 1u64 << slot; + let unavailable = self.quarantined | self.kill_hold | self.held; + if self.owners[slot] != owner + || self.released & bit != 0 + || self.refs[slot] != 0 + || (unavailable | self.active | self.killed) & bit != 0 + { + return false; + } + let mut usable = 0usize; + let mut candidates = 0usize; + for s in 1..cfg::RENDER_SLOTS { + let sbit = 1u64 << s; + if self.owners[s] != owner || self.released & sbit != 0 { + continue; + } + if unavailable & sbit == 0 { + usable += 1; + if self.refs[s] == 0 && (self.active | self.killed) & sbit == 0 { + candidates += 1; + } + } + } + usable > 1 && candidates < usable + } + + /// Whether `owner` may take a lease on `slot` without pushing protected + /// demand above `render_capacity`. + fn can_lease_slot(&self, owner: u64, slot: usize, open_queues: usize) -> bool { + if !self.promotes_reclaimable_sibling(owner, slot) { + return true; + } + let cap = self.render_capacity.min(cfg::RENDER_SLOTS - 1); + self.pair_demand(open_queues).saturating_add(1) <= cap + } + + /// All render pairs currently spoken for, including reclaimable siblings + /// claimed from surplus. + fn total_pair_demand(&self, open_queues: usize) -> usize { + open_queues + .max(self.live_owners()) + .saturating_add(self.live_siblings()) + .saturating_add(self.unavailable_released()) + } + + /// Render pairs that cannot be given back: one first pair per open logical + /// queue, non-reclaimable live siblings (busy, quarantined, or held), and + /// teardown-held released pairs. + fn pair_demand(&self, open_queues: usize) -> usize { + open_queues + .max(self.live_owners()) + .saturating_add( + self.live_siblings() + .saturating_sub(self.reclaimable_siblings()), + ) + .saturating_add(self.unavailable_released()) + } + + /// Claims another pair for an owner that may hold `pairs`, while keeping + /// first-pair capacity for every open logical queue. + fn claim_sibling(&mut self, owner: u64, pairs: usize, open_queues: usize) { + if (1..cfg::RENDER_SLOTS) + .filter(|slot| self.owns_live(owner, *slot)) + .count() + >= pairs + { + return; + } + let needed = self.total_pair_demand(open_queues).saturating_add(1); + if needed > self.render_capacity.min(cfg::RENDER_SLOTS - 1) { return; } // A speculative sibling never takes a killed context's pair. @@ -277,19 +482,16 @@ impl State { }); if let Some(slot) = sibling { self.released &= !(1u64 << slot); - self.owners[slot] = owner; + self.published &= !(1u64 << slot); + self.set_owner(slot, owner); // A speculative sibling has no GPU-use recency yet. self.epochs[slot] = 0; } } - /// The device lock separately proves the physical graph was never published. - /// An open owner keeps another usable pair. Exclude every live borrower, - /// including off-lock sibling construction; a closed owner needs no spare. - /// A spare goes only to an owner without a pair: a second pair comes only - /// from surplus, through claim_sibling. - fn reassign_unused_spare( - &mut self, + /// Whether [`Self::reassign_unused_spare`] would accept `slot` right now. + fn can_reassign_unused_spare( + &self, slot: u8, expected: Option, owner: Option, @@ -297,16 +499,13 @@ impl State { let slot = usize::from(slot); if slot == 0 || slot >= cfg::RENDER_SLOTS - || owner.is_some_and(|owner| { - owner == 0 - || self.owners.contains(&owner) - }) + || owner.is_some_and(|owner| owner == 0 || self.has_live_owner(owner)) { return false; } let bit = 1u64 << slot; let old = self.owners[slot]; - if old == 0 + !(old == 0 || self.killed & bit != 0 || owner == Some(old) || expected.is_some_and(|expected| expected != old) @@ -316,16 +515,88 @@ impl State { && !self.owners.iter().enumerate().any(|(other, value)| { other != slot && *value == old + && self.released & (1u64 << other) == 0 && (self.quarantined | self.kill_hold | self.held) & (1u64 << other) == 0 - })) - { + }))) + } + /// The device lock separately proves the physical graph was never published. + /// An open owner keeps another usable pair. Exclude every live borrower, + /// including off-lock sibling construction; a closed owner needs no spare. + /// A spare goes only to an owner without a pair: a second pair comes only + /// from surplus, through claim_sibling. + fn reassign_unused_spare( + &mut self, + slot: u8, + expected: Option, + owner: Option, + ) -> bool { + if !self.can_reassign_unused_spare(slot, expected, owner) { return false; } - self.owners[slot] = owner.unwrap_or(0); + let slot = usize::from(slot); + let bit = 1u64 << slot; + self.set_owner(slot, owner.unwrap_or(0)); self.released &= !bit; + self.published &= !bit; self.epochs[slot] = 0; true } + /// Reclaims an idle live sibling. When `keep_installed` is true, its + /// physical slot retains installed render QIDs for reuse, so `owners[slot]` + /// stays set with `released` marked (the same invariant as `release_owner`); + /// otherwise the slot returns to the unowned state. + fn release_unused_sibling( + &mut self, + slot: u8, + expected: Option, + keep_installed: bool, + ) -> bool { + let index = usize::from(slot); + if index == 0 || index >= cfg::RENDER_SLOTS { + return false; + } + let bit = 1u64 << index; + if self.released & bit != 0 { + return false; + } + if !self.can_reassign_unused_spare(slot, expected, None) { + return false; + } + if keep_installed { + self.released |= bit; + } else { + self.set_owner(index, 0); + self.released &= !bit; + } + self.wide &= !bit; + self.published &= !bit; + self.epochs[index] = 0; + true + } + /// Takes back one idle live sibling in `eligible`, preferring unpublished + /// siblings before published ones and non-wide siblings before wide-marked + /// ones. Slots in `installed` or `published` keep `released` set so their + /// installed QIDs are reused first. + fn reclaim_sibling(&mut self, eligible: u64, installed: u64) -> Option { + for allow_published in [false, true] { + for allow_wide in [false, true] { + for slot in 1..cfg::RENDER_SLOTS { + let bit = 1u64 << slot; + if eligible & bit == 0 + || (!allow_published && self.published & bit != 0) + || (!allow_wide && self.wide & bit != 0) + { + continue; + } + let keep_installed = (installed | self.published) & bit != 0; + if self.release_unused_sibling(slot as u8, None, keep_installed) { + return Some(slot as u8); + } + } + } + } + None + } fn warmable_sibling(&self, owner: u64, publishing: u8) -> Option { if self.refs.get(usize::from(publishing)) != Some(&1) { return None; @@ -353,8 +624,9 @@ impl State { && self.refs[slot] == 1 && (self.quarantined | self.kill_hold | self.held) & bit == 0 { - self.owners[slot] = 0; + self.set_owner(slot, 0); self.released &= !bit; + self.published &= !bit; self.epochs[slot] = 0; true } else { @@ -384,14 +656,21 @@ impl State { } /// Whether `pick` would return a slot, without taking it. + #[cfg(CONFIG_KUNIT = "y")] fn can_pick(&self, owner: u64, plan: Plan) -> bool { - let usable = |slot: usize| self.usable(owner, slot); + self.can_pick_for(owner, 0, plan) + } + + /// Whether `pick_for` would return a slot, without taking it. + fn can_pick_for(&self, owner: u64, open_queues: usize, plan: Plan) -> bool { + let usable = + |slot: usize| self.usable(owner, slot) && self.can_lease_slot(owner, slot, open_queues); match plan { Plan::Wait => false, Plan::Pair(slot) => usable(usize::from(slot)), Plan::Join(_) => (0..cfg::RENDER_SLOTS).any(usable), Plan::Any if owner == 0 => false, - Plan::Any if self.owners.contains(&owner) => (0..cfg::RENDER_SLOTS).any(usable), + Plan::Any if self.has_live_owner(owner) => (0..cfg::RENDER_SLOTS).any(usable), Plan::Any => { let free = !self.active & Self::MASK & !self.quarantined & !self.kill_hold & !self.held; (0..cfg::RENDER_SLOTS).any(|slot| { @@ -402,28 +681,115 @@ impl State { } } + /// The one pair a one-pair render (`pairs` 1) of an owner holding two pairs goes to: the pair + /// its previous one-pair render took, while the owner holds it (`wide`). Its layout's objects + /// then exist in that pair only. + fn wide(&self, owner: u64, pairs: usize) -> Option { + if pairs != 1 + || (1..cfg::RENDER_SLOTS) + .filter(|slot| self.owns_live(owner, *slot)) + .count() + < 2 + { + return None; + } + (1..cfg::RENDER_SLOTS) + .find(|slot| self.wide & (1u64 << slot) != 0 && self.owns_live(owner, *slot)) + } + + /// Marks `slot` as taking its owner's one-pair renders, instead of any other slot. + fn mark_wide(&mut self, slot: usize) { + for other in 1..cfg::RENDER_SLOTS { + if self.owners[other] == self.owners[slot] { + self.wide &= !(1u64 << other); + } + } + self.wide |= 1u64 << slot; + } + + /// [`Self::can_pick`] for a render that may use `pairs` of the owner's pairs. + #[cfg(CONFIG_KUNIT = "y")] + fn can_pick_render(&self, owner: u64, pairs: usize, plan: Plan) -> bool { + self.can_pick_render_for(owner, pairs, 0, plan) + } + + /// [`Self::can_pick_for`] for a render that may use `pairs` of the owner's pairs. + fn can_pick_render_for( + &self, + owner: u64, + pairs: usize, + open_queues: usize, + plan: Plan, + ) -> bool { + match (self.wide(owner, pairs), plan) { + (None, plan) => self.can_pick_for(owner, open_queues, plan), + (Some(_), Plan::Wait) => false, + (Some(wide), Plan::Pair(slot)) if usize::from(slot) != wide => false, + (Some(wide), _) => { + self.usable(owner, wide) && self.can_lease_slot(owner, wide, open_queues) + } + } + } + + #[cfg(CONFIG_KUNIT = "y")] fn pick(&mut self, owner: u64, pairs: usize, plan: Plan) -> Option { - match plan { - Plan::Any => self.acquire(owner, pairs), + self.pick_for(owner, pairs, 0, plan) + } + + fn pick_for( + &mut self, + owner: u64, + pairs: usize, + open_queues: usize, + plan: Plan, + ) -> Option { + // A one-pair render of an owner holding two pairs goes only to the pair its previous + // one-pair render took, while the owner holds it (see `wide`). + if let Some(wide) = self.wide(owner, pairs) { + return match plan { + Plan::Wait => None, + Plan::Pair(slot) if usize::from(slot) != wide => None, + // The publication barrier orders a Join's overlap from this pair. + Plan::Any | Plan::Pair(_) | Plan::Join(_) => { + self.join_for(owner, wide, open_queues) + } + }; + } + let slot = match plan { + Plan::Any => self.acquire_for(owner, pairs, open_queues), Plan::Wait => None, - Plan::Pair(slot) => self.join(owner, usize::from(slot)), + Plan::Pair(slot) => self.join_for(owner, usize::from(slot), open_queues), // The preferred pair, else the owner's least-loaded other pair: // the publication barrier orders the overlap from there. - Plan::Join(slot) => self.join(owner, usize::from(slot)).or_else(|| { - let other = (0..cfg::RENDER_SLOTS) - .filter(|other| *other != usize::from(slot) && self.usable(owner, *other)) - .min_by_key(|other| (self.refs[*other], u64::MAX - self.epochs[*other]))?; - self.join(owner, other) - }), + Plan::Join(slot) => self + .join_for(owner, usize::from(slot), open_queues) + .or_else(|| { + let other = (0..cfg::RENDER_SLOTS) + .filter(|other| { + *other != usize::from(slot) + && self.usable(owner, *other) + && self.can_lease_slot(owner, *other, open_queues) + }) + .min_by_key(|other| (self.refs[*other], u64::MAX - self.epochs[*other]))?; + self.join_for(owner, other, open_queues) + }), + }?; + if pairs == 1 { + self.mark_wide(usize::from(slot)); } + Some(slot) } fn usable(&self, owner: u64, slot: usize) -> bool { - self.owners.get(slot) == Some(&owner) + self.owns_live(owner, slot) && (self.quarantined | self.kill_hold) & (1u64 << slot) == 0 && self.refs[slot] < cfg::RENDER_DEPTH } + #[cfg(CONFIG_KUNIT = "y")] fn join(&mut self, owner: u64, index: usize) -> Option { - if !self.usable(owner, index) { + self.join_for(owner, index, 0) + } + fn join_for(&mut self, owner: u64, index: usize, open_queues: usize) -> Option { + if !self.usable(owner, index) || !self.can_lease_slot(owner, index, open_queues) { return None; } if self.refs[index] == 0 { @@ -608,11 +974,79 @@ impl Pool { pub(crate) fn has_room(&self) -> bool { self.queues() < self.max_queues } + /// Render pairs needed so every open logical queue (plus `extra_queues`) + /// keeps a first pair alongside non-reclaimable sibling and teardown-held + /// pairs. + pub(crate) fn render_demand(&self, extra_queues: usize) -> usize { + let state = self.state.lock(); + let open = self.queues.load(Ordering::Acquire) as usize; + state.pair_demand(open).saturating_add(extra_queues) + } + /// Whether admitting one more logical queue requires reclaiming a warmed + /// (built, unpublished) sibling outside `reclaimable` before + /// [`Self::try_reserve_queue_reclaiming`] can succeed. + pub(crate) fn needs_warmed_sibling_reclaim( + &self, + render_capacity: usize, + reclaimable: u64, + ) -> bool { + let state = self.state.lock(); + let cap = render_capacity.min(cfg::RENDER_SLOTS - 1); + let open = self.queues.load(Ordering::Acquire) as usize; + let total = state.total_pair_demand(open).saturating_add(1); + total > cap && total.saturating_sub(state.reclaimable_siblings_in(reclaimable)) > cap + } + #[cfg(CONFIG_KUNIT = "y")] pub(crate) fn reserve_queue(self: &Arc) -> Result { + self.try_reserve_queue(cfg::RENDER_SLOTS - 1) + } + #[cfg(CONFIG_KUNIT = "y")] + pub(crate) fn try_reserve_queue( + self: &Arc, + render_capacity: usize, + ) -> Result { + self.try_reserve_queue_reclaiming(render_capacity, State::MASK, 0) + } + /// Reserves a logical queue slot if every open queue (including this one), + /// every non-reclaimable sibling, and every teardown-held released pair + /// fits within `render_capacity`, reclaiming idle unpublished siblings in + /// `reclaimable` first so eager sibling claims never reduce queue capacity. + pub(crate) fn try_reserve_queue_reclaiming( + self: &Arc, + render_capacity: usize, + reclaimable: u64, + installed: u64, + ) -> Result { + let mut state = self.state.lock(); + state.render_capacity = render_capacity; + let cap = render_capacity.min(cfg::RENDER_SLOTS - 1); let mut count = self.queues.load(Ordering::Acquire); + let mut reclaimed = false; loop { if count >= self.max_queues { - return Err(crate::g17::capacity::refused(crate::g17::capacity::Site::LogicalQueues)); + drop(state); + if reclaimed { + self.returned(); + } + return Err(crate::g17::capacity::refused( + crate::g17::capacity::Site::LogicalQueues, + )); + } + while state.total_pair_demand(count as usize).saturating_add(1) > cap { + if state.reclaim_sibling(reclaimable, installed).is_none() { + break; + } + reclaimed = true; + } + let needed = state.total_pair_demand(count as usize).saturating_add(1); + if needed > cap { + drop(state); + if reclaimed { + self.returned(); + } + return Err(crate::g17::capacity::refused( + crate::g17::capacity::Site::LogicalQueues, + )); } match self.queues.compare_exchange( count, @@ -620,17 +1054,53 @@ impl Pool { Ordering::AcqRel, Ordering::Acquire, ) { - Ok(_) => return Ok(QueueSlot { pool: self.clone() }), + Ok(_) => { + drop(state); + if reclaimed { + self.returned(); + } + return Ok(QueueSlot { pool: self.clone() }); + } Err(current) => count = current, } } } + /// Reserves a compute QID while holding admission's state lock so sibling + /// admission cannot race ahead of the updated render-pair capacity. + pub(crate) fn reserve_compute_with_budget( + &self, + reclaimable: u64, + installed: u64, + reserve: impl FnOnce(usize) -> Result<(T, bool, usize)>, + ) -> Result { + let mut state = self.state.lock(); + let open = self.queues.load(Ordering::Acquire) as usize; + let demand = state.pair_demand(open); + let (value, room, capacity) = reserve(demand)?; + let grew = (room && !state.build_room) || capacity > state.render_capacity; + state.build_room = room; + state.render_capacity = capacity; + let cap = capacity.min(cfg::RENDER_SLOTS - 1); + let mut reclaimed = false; + while state.total_pair_demand(open) > cap { + if state.reclaim_sibling(reclaimable, installed).is_none() { + break; + } + reclaimed = true; + } + drop(state); + if grew || reclaimed { + self.returned(); + } + Ok(value) + } /// The owner's pair is quarantined behind another VM's recovery (spared) and drains. pub(crate) fn spared_quarantined(&self, owner: u64) -> bool { self.state.lock().owner_quarantine(owner) == Some(true) } - /// For an owner that may hold `pairs` render pairs. + /// For an owner that may hold `pairs` render pairs: its queue's count, or 1 for a render + /// that runs on one of a two-pair queue's pairs ([`crate::g17::pairs::for_window`]). pub(crate) fn acquire_render( self: &Arc, owner: u64, @@ -676,6 +1146,9 @@ impl Pool { } continue; } + if state.owner_released(owner) { + return Err(ECANCELED); + } state.refusal(owner)?; expired |= now >= conflict_deadline; let plan = if expired { @@ -683,7 +1156,8 @@ impl Pool { } else { state.plan(owner, request, ticket) }; - if let Some(slot) = state.pick(owner, pairs, plan) { + let open_queues = self.queues.load(Ordering::Acquire) as usize; + if let Some(slot) = state.pick_for(owner, pairs, open_queues, plan) { state.forget_waiter(ticket.take()); let record = request.and_then(|request| state.record(owner, Some(slot), 0, request)); @@ -733,11 +1207,12 @@ impl Pool { return Ok(None); } let mut state = self.state.lock(); - if state.refusal(owner).is_err() || !state.owners.contains(&owner) { + if state.owner_released(owner) || state.refusal(owner).is_err() || !state.has_live_owner(owner) { return Ok(None); } let plan = state.plan(owner, request, None); - let Some(slot) = state.pick(owner, pairs, plan) else { + let open_queues = self.queues.load(Ordering::Acquire) as usize; + let Some(slot) = state.pick_for(owner, pairs, open_queues, plan) else { return Ok(None); }; let record = request.and_then(|request| state.record(owner, Some(slot), 0, request)); @@ -749,7 +1224,7 @@ impl Pool { } /// Whether `acquire_render` would admit this request now, without /// admitting it: the scheduler's prepare step waits for this. - pub(crate) fn admits_render(&self, owner: u64, request: Option>) -> bool { + pub(crate) fn admits_render(&self, owner: u64, pairs: usize, request: Option>) -> bool { let state = self.state.lock(); if owner == 0 || state.refusal(owner).is_err() { return false; @@ -758,7 +1233,8 @@ impl Pool { return false; } let plan = state.plan(owner, request, None); - state.can_pick(owner, plan) + let open_queues = self.queues.load(Ordering::Acquire) as usize; + state.can_pick_render_for(owner, pairs, open_queues, plan) } pub(crate) fn warmable_sibling( self: &Arc, @@ -766,6 +1242,11 @@ impl Pool { publishing: u8, ) -> Option { let mut state = self.state.lock(); + let open_queues = self.queues.load(Ordering::Acquire) as usize; + let candidate = state.warmable_sibling(owner, publishing)?; + if !state.can_lease_slot(owner, usize::from(candidate), open_queues) { + return None; + } let slot = state.borrow_warm_sibling(owner, publishing)?; // This is a host construction borrower, not a GPU-use epoch. In // particular it must not clear a logical close or age an unused spare. @@ -775,6 +1256,16 @@ impl Pool { record: None, }) } + pub(crate) fn can_reassign_unused_spare( + &self, + slot: u8, + expected: Option, + owner: Option, + ) -> bool { + self.state + .lock() + .can_reassign_unused_spare(slot, expected, owner) + } pub(crate) fn reassign_unused_spare( &self, slot: u8, @@ -785,14 +1276,42 @@ impl Pool { .lock() .reassign_unused_spare(slot, expected, owner) } + pub(crate) fn release_unused_sibling( + &self, + slot: u8, + expected: Option, + keep_installed: bool, + ) -> bool { + let released = self + .state + .lock() + .release_unused_sibling(slot, expected, keep_installed); + if released { + self.returned(); + } + released + } pub(crate) fn owns_slot(&self, owner: u64, slot: usize) -> bool { - self.state.lock().owners.get(slot) == Some(&owner) + self.state.lock().owns_live(owner, slot) + } + pub(crate) fn owns_live_slot(&self, owner: u64) -> bool { + self.state.lock().has_live_owner(owner) + } + pub(crate) fn is_wide(&self, slot: u8) -> bool { + let index = usize::from(slot); + index < cfg::RENDER_SLOTS && self.state.lock().wide & (1u64 << index) != 0 + } + pub(crate) fn note_published(&self, slot: u8) { + self.state.lock().mark_published(slot); } pub(crate) fn release_owner(&self, owner: u64) { let mut state = self.state.lock(); for slot in 0..cfg::RENDER_SLOTS { if state.owners[slot] == owner { - state.released |= 1u64 << slot; + let bit = 1u64 << slot; + state.released |= bit; + state.wide &= !bit; + state.published &= !bit; } } drop(state); @@ -805,11 +1324,12 @@ impl Pool { let released = state.released & !state.active; for slot in 1..cfg::RENDER_SLOTS { if released & (1u64 << slot) != 0 { - state.owners[slot] = 0; + state.set_owner(slot, 0); state.epochs[slot] = 0; } } state.released &= !released; + state.published &= !released; state.quarantined &= !released; state.spared &= !released; state.kill_hold = 0; @@ -862,11 +1382,14 @@ impl Pool { } } - /// Whether the physical queue table can hold another pair (see `State::build_room`). - pub(crate) fn note_build_room(&self, room: bool) { + /// Whether the physical queue table can hold another pair and how many + /// dedicated render pairs fit in total (see `State::build_room` and + /// `State::render_capacity`). + pub(crate) fn note_build_room(&self, room: bool, capacity: usize) { let mut state = self.state.lock(); - if state.build_room != room { + if state.build_room != room || state.render_capacity != capacity { state.build_room = room; + state.render_capacity = capacity; drop(state); self.returned(); } @@ -1090,10 +1613,11 @@ impl RenderLease { /// Called under the device mutex once the render's kicks are committed, /// including a replay, which supersedes the earlier kick. pub(crate) fn note_publication(&self, fragment: KickDependency) { + let mut state = self.pool.state.lock(); + state.mark_published(self.slot); let Some(record) = self.record else { return; }; - let mut state = self.pool.state.lock(); if let Some(index) = state.position(self.slot, record) { state.footprints[index].fragment = Some(fragment); } @@ -1180,7 +1704,8 @@ impl State { if slots & bit == 0 { continue; } - // A pair whose commands all ran is held with them (see `Pair::executed_for_kill`). + // A pair that only the kill releases is held with its commands (see + // `Pair::releasable_by_kill`: they all ran, or they are a guilty context's). if self.owners[slot] != owner || (executed & bit == 0 && (self.refs[slot] != 0 || self.active & bit != 0 || self.released & bit == 0)) @@ -1209,6 +1734,16 @@ impl Pool { self.returned(); } + /// Keep `slots` out of service until both processors stop: the killed guilty pairs + /// `detach_context` kept there still have their queues installed. The kill held only the + /// slots whose queues the scheduler page listed at the kill, so the hold is set here too. + pub(crate) fn hold_kept_slots(&self, slots: u64) { + if slots == 0 { + return; + } + self.state.lock().kill_hold |= slots & State::MASK; + } + /// End the kill hold of `slots` once their killed context's scheduler release was /// consumed (the firmware no longer names these pairs). A new owner takes them last. pub(crate) fn release_killed_slots(&self, slots: u64) { @@ -1299,6 +1834,30 @@ mod fault_capacity_tests { assert_eq!(state.quarantined | state.spared, 0); } + #[test] + fn a_released_owner_takes_no_pair_again() { + // The kernel closed a guilty owner for its open client, and its pair drained: an + // early publication that passed the status check before the failure asks again. + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + let queue = pool.reserve_queue().unwrap(); + let lease = pool.acquire_render(1, 1, None, u64::MAX, || Ok(())).unwrap(); + let slot = lease.slot(); + drop(lease); + pool.release_owner(1); + assert!(pool.try_acquire_render(1, 2, None).unwrap().is_none()); + assert!(matches!(pool.acquire_render(1, 2, None, u64::MAX, || Ok(())), Err(ECANCELED))); + // The scheduler's prepare step does not wait for it: publication fails the job at once. + assert!(pool.admits_render(1, 2, None)); + let state = pool.state.lock(); + // Its pair stays released, and it claims no sibling. + assert_ne!(state.released & (1u64 << slot), 0); + assert_eq!(state.owners.iter().filter(|id| **id == 1).count(), 1); + drop(state); + // Another owner takes the pair. + assert_eq!(pool.acquire_render(2, 1, None, u64::MAX, || Ok(())).unwrap().slot(), slot); + drop(queue); + } + #[test] fn closed_faulting_clients_return_leases_after_drain() { let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); @@ -1337,6 +1896,27 @@ mod fault_capacity_tests { assert_eq!(pool.state.lock().kill_hold, 0); } + #[test] + fn a_kept_slot_stays_out_of_service_without_a_kill_hold() { + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + let lease = pool.acquire_render(1, 1, None, u64::MAX, || Ok(())).unwrap(); + let slot = lease.slot(); + let bit = 1u64 << slot; + pool.release_owner(1); + drop(lease); + // The kill held nothing here (the scheduler page did not list the pair's queues). + assert_eq!(pool.state.lock().kill_hold, 0); + pool.hold_kept_slots(bit); + pool.release_killed_slots(0); + assert_eq!(pool.state.lock().kill_hold, bit); + assert!(!pool.reassign_unused_spare(slot, Some(1), Some(2))); + let next = pool.acquire_render(2, 1, None, u64::MAX, || Ok(())).unwrap(); + assert_ne!(next.slot(), slot); + drop(next); + pool.release_retained_owners_after_processor_stop(); + assert_eq!(pool.state.lock().kill_hold, 0); + } + #[test] fn consumed_scheduler_release_ends_the_kill_hold() { let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); @@ -1398,7 +1978,7 @@ mod fault_capacity_tests { let built = pool.acquire_render(1, 1, None, u64::MAX, || Ok(())).unwrap(); assert!(usize::from(built.slot()) >= 8); // Without room it takes the killed pair released longest ago. - pool.note_build_room(false); + pool.note_build_room(false, cfg::RENDER_SLOTS - 1); let reused = pool.acquire_render(2, 1, None, u64::MAX, || Ok(())).unwrap(); assert_eq!(reused.slot(), 7); assert_eq!(pool.state.lock().killed & (1u64 << 7), 0); @@ -1448,16 +2028,16 @@ mod owner_pair_tests { state.owners[1] = 1; state.owners[2] = 1; for _ in 0..cfg::RENDER_DEPTH { - assert_eq!(state.pick(1, 1, Plan::Pair(1)), Some(1)); + assert_eq!(state.pick(1, 2, Plan::Pair(1)), Some(1)); } assert!(!state.can_pick(1, Plan::Pair(1))); - assert_eq!(state.pick(1, 1, Plan::Pair(1)), None); + assert_eq!(state.pick(1, 2, Plan::Pair(1)), None); assert!(state.can_pick(1, Plan::Join(1))); - assert_eq!(state.pick(1, 1, Plan::Join(1)), Some(2)); + assert_eq!(state.pick(1, 2, Plan::Join(1)), Some(2)); // With one pair a preference is the pair. state.owners[2] = 0; assert!(!state.can_pick(1, Plan::Join(1))); - assert_eq!(state.pick(1, 1, Plan::Join(1)), None); + assert_eq!(state.pick(1, 2, Plan::Join(1)), None); } #[test] @@ -1576,6 +2156,176 @@ mod two_pair_tests { assert!(state.reassign_unused_spare(6, Some(3), Some(2))); } + #[test] + fn a_one_pair_render_of_a_two_pair_owner_stays_on_one_pair() { + crate::g17::pairs::set_sibling_backlog(1); + let mut state = State::new(); + // Small renders take the first pair and, with a backlog there, the sibling. + let first = state.pick(1, 2, Plan::Any).unwrap(); + assert_eq!(state.pick(1, 2, Plan::Any), Some(first)); + let sibling = state.pick(1, 2, Plan::Any).unwrap(); + assert_ne!(sibling, first); + // A render whose layout the window holds once takes one of them, and every later such + // render goes there too, even when the other pair is idle or less loaded. + let wide = state.pick(1, 1, Plan::Any).unwrap(); + let other = if wide == first { sibling } else { first }; + state.release(other); + for _ in state.refs[usize::from(wide)]..cfg::RENDER_DEPTH { + assert_eq!(state.pick(1, 1, Plan::Any), Some(wide)); + } + // At full depth it waits for that pair instead of taking the other. + assert!(state.can_pick(1, Plan::Any)); + assert!(!state.can_pick_render(1, 1, Plan::Any)); + assert!(state.can_pick_render(1, 2, Plan::Any)); + assert_eq!(state.pick(1, 1, Plan::Any), None); + assert_eq!(state.pick(1, 1, Plan::Join(other)), None); + state.release(wide); + assert_eq!(state.pick(1, 1, Plan::Join(other)), Some(wide)); + assert_eq!(state.pick(1, 1, Plan::Pair(other)), None); + state.release(wide); + assert_eq!(state.pick(1, 1, Plan::Pair(wide)), Some(wide)); + // A small render may still use either pair. + assert_eq!(state.pick(1, 2, Plan::Pair(other)), Some(other)); + } + + #[test] + fn a_two_pair_owner_whose_first_render_needs_one_pair_claims_no_sibling() { + let mut state = State::new(); + // Two large renders in flight on a new queue share its one pair. + let first = state.pick(1, 1, Plan::Any).unwrap(); + assert_eq!(state.pick(1, 1, Plan::Any), Some(first)); + assert_eq!(state.owners.iter().filter(|id| **id == 1).count(), 1); + } + + #[test] + fn a_slot_lost_and_claimed_back_drops_its_one_pair_mark() { + let mut state = State::new(); + // A one-pair render of owner 1 takes slot `a`; its build fails before publication and + // the slot goes back unowned. + let a = state.pick(1, 1, Plan::Any).unwrap(); + assert!(state.cancel_empty_slot(a, 1)); + state.release(a); + // Owner 2 takes `a` meanwhile, so owner 1's next one-pair render, which builds its + // large layout's objects there, takes a slot `b` above it. + state.build_room = false; + assert_eq!(state.pick(2, 2, Plan::Any), Some(a)); + state.build_room = true; + let b = state.pick(1, 1, Plan::Any).unwrap(); + assert!(b > a); + state.release(b); + // Owner 2 closes, and a small render of owner 1 claims `a` back as its sibling. + state.release(a); + state.released |= 1u64 << a; + assert_eq!(state.pick(1, 2, Plan::Any), Some(b)); + assert_eq!(state.owners[usize::from(a)], 1); + state.release(b); + // The large layout's objects are in `b` alone, and its one-pair renders stay there. + assert_eq!(state.pick(1, 1, Plan::Any), Some(b)); + assert!(state.can_pick_render(1, 1, Plan::Pair(b))); + assert!(!state.can_pick_render(1, 1, Plan::Pair(a))); + assert_eq!(state.pick(1, 1, Plan::Join(a)), Some(b)); + } + + #[test] + fn a_slot_given_to_another_owner_drops_its_one_pair_mark() { + let mut state = State::new(); + // Owner 1 holds two pairs, and its one-pair renders went to the lower one. + state.owners[1] = 1; + state.owners[2] = 1; + assert_eq!(state.pick(1, 1, Plan::Pair(1)), Some(1)); + state.release(1); + // That pair is given to owner 2 as its spare, and owner 1's next one-pair render, with + // one pair left, builds its layout in the other. + assert!(state.reassign_unused_spare(1, Some(1), Some(2))); + assert_eq!(state.pick(1, 1, Plan::Any), Some(2)); + state.release(2); + // Owner 2 closes, owner 1 claims the pair back, and its one-pair renders stay on the + // pair that holds the layout. + state.released |= 1u64 << 1; + assert_eq!(state.pick(1, 2, Plan::Any), Some(2)); + assert_eq!(state.owners[1], 1); + state.release(2); + assert_eq!(state.pick(1, 1, Plan::Any), Some(2)); + assert!(!state.can_pick_render(1, 1, Plan::Pair(1))); + } + + #[test] + fn reclaim_prefers_non_wide_sibling_and_clears_wide_on_detach() { + let mut state = State::new(); + // Owner 1 holds two published pairs; slot 1 holds its one-pair wide mark. + state.set_owner(1, 1); + state.set_owner(2, 1); + state.published = (1u64 << 1) | (1u64 << 2); + assert_eq!(state.pick(1, 1, Plan::Pair(1)), Some(1)); + state.release(1); + assert_ne!(state.wide & (1u64 << 1), 0); + // Reclaiming a sibling takes the non-wide slot (slot 2) instead of slot 1. + assert_eq!(state.reclaim_sibling(State::MASK, State::MASK), Some(2)); + assert_ne!(state.released & (1u64 << 2), 0); + assert_ne!(state.wide & (1u64 << 1), 0); + // Reattach slot 2 and explicitly detach the wide slot with keep_installed=true: + // the wide mark clears so reclaiming/re-acquiring slot 1 does not leave a stale mark. + state.released &= !(1u64 << 2); + assert!(state.release_unused_sibling(1, Some(1), true)); + assert_eq!(state.wide & (1u64 << 1), 0); + assert_ne!(state.released & (1u64 << 1), 0); + assert_eq!(state.owners[1], 1); + // With only slot 2 live, the next one-pair render moves to slot 2. + assert_eq!(state.pick(1, 1, Plan::Any), Some(2)); + state.release(2); + // Detach with keep_installed=false also clears the wide mark and owner. + state.set_owner(1, 1); + state.released &= !(1u64 << 1); + assert!(state.release_unused_sibling(2, Some(1), false)); + assert_eq!(state.owners[2], 0); + assert_eq!(state.wide & (1u64 << 2), 0); + } + + #[test] + fn wide_render_respects_open_queue_capacity_gate_and_release_owner() { + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 4); + let q1 = pool.try_reserve_queue(4).unwrap(); + let q2 = pool.try_reserve_queue(4).unwrap(); + let q3 = pool.try_reserve_queue(4).unwrap(); + // Owner 1 gets two pairs; mark `wide_slot` for one-pair renders, then leave it idle + // while the other pair stays busy and capacity shrinks to 3 (= open queues). + let a = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + let b = pool.acquire_render(1, 1, None, u64::MAX, || Ok(())).unwrap(); + let wide_slot = b.slot(); + assert!(pool.is_wide(wide_slot)); + drop(b); + drop(a); + let other = { + let mut state = pool.state.lock(); + let other = (1..cfg::RENDER_SLOTS) + .find(|s| *s != usize::from(wide_slot) && state.owns_live(1, *s)) + .unwrap(); + state.refs[other] = 1; + state.active |= 1u64 << other; + other as u8 + }; + pool.note_build_room(false, 3); + { + let mut state = pool.state.lock(); + // Promoting idle `wide_slot` would push pair_demand from 3 to 4 > cap 3. + assert!(!state.can_pick_render_for(1, 1, 3, Plan::Any)); + assert_eq!(state.pick_for(1, 1, 3, Plan::Any), None); + // With capacity 4, the marked slot is picked again. + state.render_capacity = 4; + assert!(state.can_pick_render_for(1, 1, 3, Plan::Any)); + assert_eq!(state.pick_for(1, 1, 3, Plan::Any), Some(wide_slot)); + state.release(wide_slot); + state.release(other); + } + // release_owner clears the wide mark. + pool.release_owner(1); + assert!(!pool.is_wide(wide_slot)); + drop(q3); + drop(q2); + drop(q1); + } + #[test] fn a_one_pair_owner_claims_no_sibling() { let mut state = State::new(); @@ -1583,6 +2333,372 @@ mod two_pair_tests { assert_eq!(state.owners.iter().filter(|id| **id == 1).count(), 1); assert_eq!(state.acquire(1, 1), Some(first)); } + + #[test] + fn sibling_claim_preserves_first_pair_capacity_for_open_queues() { + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 2); + let _q1 = pool.try_reserve_queue(2).unwrap(); + let _q2 = pool.try_reserve_queue(2).unwrap(); + // Two open queues and capacity for two pairs: neither an unowned slot + // nor a released pair may be claimed as a sibling. + { + let mut state = pool.state.lock(); + state.owners[5] = 99; + state.released |= 1u64 << 5; + } + let l1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_eq!( + pool.state.lock().owners.iter().filter(|id| **id == 1).count(), + 1 + ); + // The second open queue still gets its guaranteed first pair. + let l2 = pool.acquire_render(2, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_ne!(l1.slot(), l2.slot()); + assert_eq!( + pool.state.lock().owners.iter().filter(|id| **id == 2).count(), + 1 + ); + drop(l1); + drop(l2); + // Once capacity exceeds open queues, a sibling is claimed from surplus. + pool.note_build_room(true, 3); + let l1_again = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_eq!( + pool.state.lock().owners.iter().filter(|id| **id == 1).count(), + 2 + ); + // The idle unpublished sibling can still yield to a new queue. + assert_eq!(pool.render_demand(0), 2); + assert_eq!(pool.state.lock().total_pair_demand(2), 3); + drop(l1_again); + } + + #[test] + fn idle_siblings_yield_to_open_queues_up_to_full_capacity() { + use crate::g17::fw::kick::KickTimestamp; + + crate::g17::pairs::set_sibling_backlog(0); + let kick = KickDependency::new(10, KickTimestamp::new(1).unwrap()).unwrap(); + let cap = 8usize; + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, cap); + let mut queues = KVec::with_capacity(cap, GFP_KERNEL).unwrap(); + // First cap / 2 owners each publish on BOTH their primary and sibling + // pairs, filling all `cap` slots with published graphs, then go idle. + for owner in 1..=(cap / 2) as u64 { + queues.push(pool.try_reserve_queue(cap).unwrap(), GFP_KERNEL).unwrap(); + let first = pool + .acquire_render(owner, 2, None, u64::MAX, || Ok(())) + .unwrap(); + first.note_publication(kick); + let sibling = pool + .acquire_render(owner, 2, None, u64::MAX, || Ok(())) + .unwrap(); + assert_ne!(first.slot(), sibling.slot()); + sibling.note_publication(kick); + { + let state = pool.state.lock(); + assert_eq!( + (1..cfg::RENDER_SLOTS) + .filter(|slot| state.owns_live(owner, *slot)) + .count(), + 2 + ); + assert_ne!(state.published & (1u64 << sibling.slot()), 0); + } + drop(sibling); + drop(first); + } + assert_eq!(pool.state.lock().total_pair_demand(cap / 2), cap); + assert_eq!(pool.render_demand(0), cap / 2); + // Opening queues beyond cap / 2 detaches idle published siblings (marking + // them released while keeping their previous owner recorded) until full + // capacity is reached and each new owner reuses a detached slot. + for owner in (cap / 2 + 1) as u64..=cap as u64 { + assert!(pool.render_demand(1) <= cap); + queues.push(pool.try_reserve_queue(cap).unwrap(), GFP_KERNEL).unwrap(); + { + let state = pool.state.lock(); + assert_ne!(state.released & State::MASK, 0); + // Released slots retain their prior owner until rebound. + for slot in 1..cfg::RENDER_SLOTS { + if state.released & (1u64 << slot) != 0 { + assert_ne!(state.owners[slot], 0); + assert_eq!(state.published & (1u64 << slot), 0); + } + } + } + let lease = pool + .acquire_render(owner, 2, None, u64::MAX, || Ok(())) + .unwrap(); + lease.note_publication(kick); + { + let state = pool.state.lock(); + assert_eq!( + (1..cfg::RENDER_SLOTS) + .filter(|slot| state.owns_live(owner, *slot)) + .count(), + 1 + ); + } + drop(lease); + } + assert_eq!(pool.queues() as usize, cap); + assert!(matches!(pool.try_reserve_queue(cap), Err(ENOSPC))); + for owner in 1..=cap as u64 { + pool.release_owner(owner); + } + drop(queues); + crate::g17::pairs::set_sibling_backlog(1); + } + + #[test] + fn queue_and_compute_admission_account_for_non_reclaimable_siblings() { + crate::g17::pairs::set_sibling_backlog(0); + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 2); + let q1 = pool.try_reserve_queue(2).unwrap(); + let l1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_eq!( + pool.state.lock().owners.iter().filter(|id| **id == 1).count(), + 2 + ); + // An idle, unpublished sibling is reclaimable and does not inflate pair_demand. + assert_eq!(pool.render_demand(0), 1); + assert_eq!(pool.render_demand(1), 2); + // Once owner 1 actually acquires its sibling, it is busy/used and cannot be reclaimed. + let l2 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_ne!(l1.slot(), l2.slot()); + assert_eq!(pool.render_demand(0), 2); + assert_eq!(pool.render_demand(1), 3); + assert!(matches!(pool.try_reserve_queue(2), Err(ENOSPC))); + // Compute reservation observes demand including the non-reclaimable sibling. + let observed = pool + .reserve_compute_with_budget(State::MASK, 0, |demand| Ok((demand, false, 2))) + .unwrap(); + assert_eq!(observed, 2); + assert!(!pool.state.lock().build_room); + // Closing the sibling owner releases both pairs so a new queue fits. + drop(l2); + drop(l1); + pool.release_owner(1); + drop(q1); + assert_eq!(pool.render_demand(0), 0); + let _q2 = pool.try_reserve_queue(2).unwrap(); + crate::g17::pairs::set_sibling_backlog(1); + } + + #[test] + fn queue_admission_accounts_for_teardown_held_released_pairs() { + crate::g17::pairs::set_sibling_backlog(0); + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 3); + let q1 = pool.try_reserve_queue(3).unwrap(); + let l1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + // Owner 1 now holds a primary pair and an idle sibling; acquire the sibling so it is busy. + let l2 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_ne!(l1.slot(), l2.slot()); + // Simulate a third pair that was released but is still held for teardown. + let held_slot = (1..cfg::RENDER_SLOTS) + .find(|slot| pool.state.lock().owners[*slot] == 0) + .unwrap(); + { + let mut state = pool.state.lock(); + state.owners[held_slot] = 99; + state.released |= 1u64 << held_slot; + state.held |= 1u64 << held_slot; + } + assert_eq!(pool.render_demand(0), 3); + assert_eq!(pool.render_demand(1), 4); + // All 3 pairs are non-reclaimable (2 busy + 1 teardown-held): queue 2 is refused. + assert!(matches!(pool.try_reserve_queue(3), Err(ENOSPC))); + // Compute reservation observes demand including the teardown-held pair. + let observed = pool + .reserve_compute_with_budget(State::MASK, 0, |demand| Ok((demand, false, 3))) + .unwrap(); + assert_eq!(observed, 3); + // Once teardown finishes and clears `held`, the released pair becomes reusable. + pool.state.lock().held &= !(1u64 << held_slot); + assert_eq!(pool.render_demand(0), 2); + let _q2 = pool.try_reserve_queue(3).unwrap(); + drop(l2); + drop(l1); + drop(q1); + crate::g17::pairs::set_sibling_backlog(1); + } + + #[test] + fn unpublished_sibling_lease_drop_stays_reclaimable() { + use crate::g17::fw::kick::KickTimestamp; + + crate::g17::pairs::set_sibling_backlog(0); + let kick = KickDependency::new(10, KickTimestamp::new(1).unwrap()).unwrap(); + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 2); + let q1 = pool.try_reserve_queue(2).unwrap(); + let l1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + l1.note_publication(kick); + // Taking a sibling lease advances its epoch and protects it while busy. + let l2 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + let sib = l2.slot(); + assert_ne!(l1.slot(), sib); + assert_eq!(pool.render_demand(0), 2); + assert!(matches!(pool.try_reserve_queue(2), Err(ENOSPC))); + // Dropping the lease before publication leaves the sibling reclaimable. + drop(l2); + assert_ne!(pool.state.lock().epochs[usize::from(sib)], 0); + assert_eq!(pool.state.lock().published & (1u64 << sib), 0); + assert_eq!(pool.render_demand(0), 1); + let q2 = pool.try_reserve_queue(2).unwrap(); + assert_eq!( + pool.state.lock().owners.iter().filter(|id| **id == 1).count(), + 1 + ); + drop(q2); + drop(l1); + // A published sibling stays protected while busy, then yields once idle + // by detaching its owner into `released` so a new queue reuses its QIDs. + let l1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + let l2 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + let pub_sib = l2.slot(); + assert_ne!(l1.slot(), pub_sib); + l2.note_publication(kick); + assert_eq!(pool.render_demand(0), 2); + assert!(matches!(pool.try_reserve_queue(2), Err(ENOSPC))); + drop(l2); + assert_eq!(pool.render_demand(0), 1); + let q3 = pool.try_reserve_queue(2).unwrap(); + { + let state = pool.state.lock(); + assert_eq!(state.owners[usize::from(pub_sib)], 1); + assert_ne!(state.released & (1u64 << pub_sib), 0); + assert_eq!(state.published & (1u64 << pub_sib), 0); + } + // note_published() must not re-set `published` on a released slot. + pool.note_published(pub_sib); + assert_eq!(pool.state.lock().published & (1u64 << pub_sib), 0); + let l3 = pool.acquire_render(2, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_eq!(l3.slot(), pub_sib); + drop(l3); + drop(l1); + pool.release_owner(1); + pool.release_owner(2); + drop(q3); + drop(q1); + assert_eq!(pool.render_demand(0), 0); + crate::g17::pairs::set_sibling_backlog(1); + } + + #[test] + fn compute_shrink_gates_warmed_sibling_promotion() { + use crate::g17::fw::kick::KickTimestamp; + + crate::g17::pairs::set_sibling_backlog(0); + let kick = KickDependency::new(10, KickTimestamp::new(1).unwrap()).unwrap(); + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 5); + let q1 = pool.try_reserve_queue(5).unwrap(); + let q2 = pool.try_reserve_queue(5).unwrap(); + let q3 = pool.try_reserve_queue(5).unwrap(); + // Owners 1 and 2 publish primaries and claim siblings; owner 3 has not rendered yet. + let p1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + p1.note_publication(kick); + drop(p1); + let p2 = pool.acquire_render(2, 2, None, u64::MAX, || Ok(())).unwrap(); + p2.note_publication(kick); + drop(p2); + assert_eq!(pool.state.lock().total_pair_demand(3), 5); + assert_eq!(pool.render_demand(0), 3); + // Compute shrinks render_capacity from 5 to 4 while both siblings stay warmed + // (outside the lock-only reclaimable mask). + pool.reserve_compute_with_budget(0, 0, |demand| { + assert_eq!(demand, 3); + Ok(((), false, 4)) + }) + .unwrap(); + // One sibling can still be promoted up to the shrunk capacity of 4. + let p1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + let s1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_ne!(p1.slot(), s1.slot()); + s1.note_publication(kick); + assert_eq!(pool.render_demand(0), 4); + // While owner 1's sibling is busy, owner 2's warmed sibling cannot promote + // past capacity 4 and stays reclaimable for owner 3's guaranteed first pair. + let p2 = pool.acquire_render(2, 2, None, u64::MAX, || Ok(())).unwrap(); + let s2 = (1..cfg::RENDER_SLOTS) + .find(|slot| { + *slot != usize::from(p2.slot()) && pool.state.lock().owns_live(2, *slot) + }) + .unwrap() as u8; + assert!(pool.warmable_sibling(2, p2.slot()).is_none()); + let p2_stacked = pool.acquire_render(2, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_eq!(p2_stacked.slot(), p2.slot()); + { + let mut state = pool.state.lock(); + assert!(!state.can_pick_for(2, 3, Plan::Pair(s2))); + assert_eq!(state.pick_for(2, 2, 3, Plan::Pair(s2)), None); + assert_eq!(state.pick_for(2, 2, 3, Plan::Join(s2)), Some(p2.slot())); + state.release(p2.slot()); + } + drop(p2_stacked); + drop(p2); + assert_eq!(pool.render_demand(0), 4); + assert!(pool.release_unused_sibling(s2, Some(2), true)); + assert_eq!(pool.state.lock().owners[usize::from(s2)], 2); + assert_ne!(pool.state.lock().released & (1u64 << s2), 0); + let p3 = pool.acquire_render(3, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_eq!(p3.slot(), s2); + drop(p3); + drop(s1); + drop(p1); + for owner in 1..=3 { + pool.release_owner(owner); + } + drop(q3); + drop(q2); + drop(q1); + crate::g17::pairs::set_sibling_backlog(1); + } + + #[test] + fn render_lease_note_publication_ignores_released_slot() { + use crate::g17::fw::kick::KickTimestamp; + + let kick = KickDependency::new(10, KickTimestamp::new(1).unwrap()).unwrap(); + let mut footprint = Footprint::new(1, false); + footprint.push_vm(0, 0x1000); + let footprint = Arc::new(footprint, GFP_KERNEL).unwrap(); + let request = Request { + footprint: &footprint, + sequence: 1, + prefix: None, + }; + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 2); + let q1 = pool.try_reserve_queue(2).unwrap(); + let lease = pool + .acquire_render(1, 1, Some(request), u64::MAX, || Ok(())) + .unwrap(); + let slot = lease.slot(); + let bit = 1u64 << slot; + // Concurrent owner release while the pair is lent out off-lock must not + // have `published` re-set when `lease.note_publication()` acquires the lock. + pool.release_owner(1); + lease.note_publication(kick); + { + let state = pool.state.lock(); + assert_eq!(state.published & bit, 0); + assert_ne!(state.released & bit, 0); + assert_eq!(state.owners[usize::from(slot)], 1); + assert!(state + .footprints + .iter() + .any(|entry| entry.slot == Some(slot) && entry.fragment.is_some())); + } + drop(lease); + drop(q1); + } } #[kunit_tests(asahi_g17_admission_deadline)] diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 5492a740759e56..67c78957fb3643 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -47,9 +47,9 @@ const CONFIG: usize = 0; const ANNOUNCE: usize = 0x800; const PREDECESSOR: usize = 0x400; const POINTERS: usize = 0x100; -/// Producer/consumer words live on their own uncached page after the graph, -/// which the firmware reads through a cached mapping (queue record, job-list -/// head and item ring), as native does. +/// Producer/consumer words live on their own page after the graph. The whole +/// graph stays uncached because both the firmware and host write the queue +/// record (on owner rebinds) and item ring. const CURSORS: usize = GRAPH_SIZE; const ITEMS: usize = 0x4000; const STAMP: usize = 0x300; @@ -106,18 +106,24 @@ pub(crate) struct DescriptorRing { } impl DescriptorRing { - /// Firmware reads every descriptor through a cached kernel mapping, as it - /// does for render. The pool keeps that mapping until processor stop; the - /// hardware reads the same pages through an uncached canonical low alias. - /// On M5 the kernel mapping, in the upper half every execution context - /// includes, is firmware-only. + /// Both firmware and host write compute descriptors: the firmware updates + /// an accounting word near the end of each descriptor (`+0xfac` on M5), + /// and the host rewrites each slot every 32 kicks. M5 keeps them uncached + /// against the dirty-line writeback hazard of linux#3170, while retaining + /// their VA and fence in the pool. G17P maps them firmware-cached, as it + /// does render descriptors: the host rewrites a slot only after the kick + /// that last used it retired (at most `DESCRIPTORS` kicks are in flight), + /// by when that kick's accounting store is in memory. The hardware reads + /// the same pages through an uncached canonical low alias; on M5 the + /// kernel mapping, in the upper half every execution context includes, is + /// firmware-only. pub(crate) fn new(alloc: &Allocator<'_>, objects: &Arc) -> Result { let size = DESCRIPTORS * COMPUTE_DESCRIPTOR_SIZE; let object = objects.allocate( alloc, Family::Descriptor, size, - size, + if alloc.uat.is_m5() { 0 } else { size }, if alloc.uat.is_m5() { mmu::PROT_FW_SHARED_RW } else { mmu::PROT_GPU_FW_SHARED_RW }, CpuMap::WriteCombined, )?; @@ -141,7 +147,7 @@ struct Graph { operand: KernelObject, support: KernelObject, m5_timestamps: Option>, - graph: PooledObject, + graph: KernelObject, context_low: Option, context_high: Option, /// Announcements, which stay uncached for the firmware. @@ -191,14 +197,14 @@ impl Graph { support.write(0x110, 0x50u32)?; support.write(mmu::UAT_PGSZ + 4, 1u32)?; } - let mut graph = objects.allocate( - alloc, - Family::QueueState, - GRAPH_SIZE + mmu::UAT_PGSZ, - GRAPH_SIZE, - prot, - cpu, - )?; + // Keep the compute graph uncached: the firmware writes runtime state + // into the queue record while the host rewrites its owner fields on + // rebind (`Graph::set_owner`) and wraps the item ring. Firmware-cached + // G17 mappings are non-coherent with host writes and cannot be flushed, + // so dirty firmware lines would revert host updates. An installed + // compute graph lives until firmware stop and does not need the reuse + // pool. + let mut graph = alloc.kernel(GRAPH_SIZE + mmu::UAT_PGSZ, page, prot, cpu)?; let graph_va = graph.gpu_va(); graph.initialize::(0, |view| { view.pointers = PointerBlock::new(&pointers)?; @@ -268,7 +274,7 @@ impl Graph { &mut self, context: Arc, kick_alias: mmu::KernelMapping, - pool_alias: mmu::KernelMapping, + pool_alias: Option, ) -> Result { if !context.is_current() { return Err(EFAULT); @@ -290,7 +296,7 @@ impl Graph { .map(|context| context.alias_in(vm, private.clone(), page, prot)).transpose()?; Ok(Binding { _kick_alias: kick_alias, - pool_alias: Some(pool_alias), + pool_alias, descriptors: Some(descriptors), preempt, usage, @@ -308,8 +314,16 @@ impl Graph { .cast::(); // SAFETY: The checked packed record stays mapped. The device mutex // and idle witness exclude access by another owner during this update. - return unsafe { (*pointer).set_compute_owner(context.work_head_va(), - context.scheduler_va(), context.owner_pid(), context.policy()) }; + unsafe { + (*pointer).set_compute_owner( + context.work_head_va(), + context.scheduler_va(), + context.owner_pid(), + context.policy(), + ) + }?; + fence(Ordering::Release); + return Ok(()); } let pointer = self .graph @@ -325,6 +339,7 @@ impl Graph { context.policy(), ) }; + fence(Ordering::Release); Ok(()) } @@ -368,12 +383,8 @@ impl Graph { fn vacate_ring(&mut self) -> Option { self.ring.take() } - fn rearm_ring(&mut self, ring: DescriptorRing) -> Result { - if self.ring.is_some() { - return Err(EBUSY); - } - self.ring = Some(ring); - Ok(()) + fn rearm_ring(&mut self, ring: DescriptorRing) -> Option { + self.ring.replace(ring) } /// `cursors`: this publication's snapshot (M5), else a fresh read. fn ensure_record_slot(&self, slot: usize, cursors: Option) -> Result { @@ -648,6 +659,14 @@ pub(crate) struct AdmissionState { pub(crate) struct Queue { owner: Option, + /// Per-owner channel index (0 for primary, 1..COMPUTE_CHANNELS_MAX for M5 siblings). + channel_index: u8, + /// Whether this queue currently holds a `Context::note_compute_binding(true)` count. + binding_noted: bool, + /// Consecutive retired kicks of the bound owner whose firmware execution record ran at least + /// [`crate::g17::pairs::SIBLING_EXECUTION_NS`] ([`crate::g17::pairs::heavy_run`]); zero for a + /// new owner. + heavy_run: u8, /// Scheduler/work pages of an exited last owner whose context was dropped; /// the installed queue record still names them until the next owner binds. retained_owner: Option, @@ -739,19 +758,57 @@ impl Queue { program: ComputeProgram, m5: bool, mcache: bool, + ) -> Result { + Self::new_channel( + alloc, + objects, + backing, + owner, + context, + pointers, + operand_state, + board, + program, + m5, + mcache, + 0, + ) + } + + #[expect( + clippy::too_many_arguments, + reason = "A sibling compute queue takes the same physical graph inputs plus its channel \ + identity." + )] + pub(crate) fn new_channel( + alloc: &Allocator<'_>, + objects: &Arc, + backing: Backing, + owner: u64, + context: Arc, + pointers: PointerLayout, + operand_state: &'static OperandState, + board: Option<&'static Board>, + program: ComputeProgram, + m5: bool, + mcache: bool, + channel_index: u8, ) -> Result { let Backing { mut pool, mut kick } = backing; let (active, replays) = (Fifo::new()?, Fifo::new()?); let mut graph = Graph::new(alloc, objects, &context, pointers, operand_state, board, program, m5, mcache)?; let kick_alias = kick.map_client(context.vm())?; - let pool_alias = pool.map_client(context.vm())?; + let pool_alias = Some(pool.map_client(context.vm())?); let binding = graph.bind(context.clone(), kick_alias, pool_alias)?; context.mark_published(); context.note_compute_binding(true); crate::g17::trace::bind(crate::g17::trace::COMPUTE, kick.id().qid(), context.id(), 0); Ok(Self { owner: Some(owner), + channel_index, + binding_noted: true, + heavy_run: 0, retained_owner: None, pool_phase: PoolPhase::Populated, release_sent_ns: None, @@ -870,6 +927,46 @@ impl Queue { pub(crate) fn owner(&self) -> Option { self.owner } + pub(crate) fn channel_index(&self) -> u8 { + self.channel_index + } + pub(crate) fn is_primary(&self) -> bool { + self.channel_index == 0 + } + pub(crate) fn active_len(&self) -> usize { + self.active.len + } + pub(crate) fn has_replays(&self) -> bool { + self.replays.len != 0 + } + pub(crate) fn configuring(&self) -> bool { + self.configuration.is_some() + } + pub(crate) fn has_ring(&self) -> bool { + self.graph.ring.is_some() + } + /// The bound owner's recent kicks on this channel ran sustained heavy work + /// ([`crate::g17::pairs::sustained`]). + pub(crate) fn sustained(&self) -> bool { + crate::g17::pairs::sustained(self.heavy_run) + } + fn clear_binding_note(&mut self) { + if self.binding_noted { + if let Some(binding) = &self.binding { + binding.context.note_compute_binding(false); + } + self.binding_noted = false; + } + } + fn clear_owner(&mut self, stamp_released_at: bool) { + self.clear_binding_note(); + self.owner = None; + self.channel_index = 0; + self.heavy_run = 0; + if stamp_released_at { + self.released_at = now_ns(); + } + } /// The bound owner's context; `None` once an exited owner was detached. pub(crate) fn context(&self) -> Option<&Arc> { self.binding.as_ref().map(|binding| &binding.context) @@ -962,6 +1059,12 @@ impl Queue { visit(active.packet.completion.status()); } } + /// The context ID (UAT slot) of every in-flight packet. + pub(crate) fn visit_contexts(&self, visit: &mut dyn FnMut(u32)) { + for active in self.active.iter() { + visit(active.packet.context.id()); + } + } /// A recovery record names this queue and the completion stamp of the /// command it interrupted, `kick << 8` like the queue's stamp. Without a /// stamp match the oldest published command is marked. @@ -1039,6 +1142,18 @@ impl Queue { || self.retire_pending || masks.is_none_or(|m| m[self.qid() as usize / 64] & (1 << (self.qid() % 64)) != 0) } + + pub(crate) fn needs_scan_retire(&self, masks: Option<[u64; 2]>) -> bool { + self.configuration.is_some() || (!self.quarantined && self.selected(masks)) + } + + pub(crate) fn has_terminal(&self) -> bool { + self.terminal.is_some() + } + + pub(crate) fn awaiting_witness(&self) -> bool { + self.awaiting_witness + } /// Stage every unlatched exact identity before the device's single shared-ring scan, /// whichever queues the scan's batch retires. pub(crate) fn request_observations(&self, batch: &mut Batch) -> Result { @@ -1270,8 +1385,7 @@ impl Queue { drop(self.previous.take()); self.retirement_ready = self.active.len == 0; if self.released && self.retirement_ready { - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); } } // It was reported when it retired: step past it. @@ -1283,6 +1397,9 @@ impl Queue { self.active.get_mut(at).ok_or(EIO)?.qos_pending = false; } let front = self.active.get(at).ok_or(EIO)?; + // Only an exact execution record measures the kick: a recordless retirement + // carries a synthesized envelope. + let execution = front.observed.map(|record| record.timestamps); if let Some(ticket) = front.ticket { crate::g17::recovery::note_retired(); crate::g17::trace::complete( @@ -1306,6 +1423,9 @@ impl Queue { Err(error) => Deferred::Retired(completion, Err(error)), })?; self.retire_pending = false; + if let Some([start, end]) = execution { + self.heavy_run = crate::g17::pairs::heavy_run(self.heavy_run, start, end); + } if stampless || at != 0 { // A completion record is no witness that the firmware is done with the // descriptor: it can still store the stamp through it. Keep the command @@ -1328,8 +1448,7 @@ impl Queue { drop(self.previous.take()); self.retirement_ready = self.active.len == 0; if self.released && self.retirement_ready { - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); } } Ok(None) | Err(EAGAIN) => { @@ -1502,8 +1621,7 @@ impl Queue { self.retire_pending = false; self.retirement_ready = true; if self.released { - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); } } Ok(()) @@ -1868,6 +1986,27 @@ impl Queue { && !self.source_hint.has_readers(&self.source_readers) } pub(crate) fn bind_owner(&mut self, owner: u64, context: Arc) -> Result { + self.bind_owner_channel(owner, context, 0) + } + /// Binds a reusable physical queue with its own dedicated compute pool as an additional + /// compute channel of `owner`. + pub(crate) fn bind_sibling( + &mut self, + owner: u64, + context: Arc, + channel_index: u8, + ) -> Result { + if !self.graph.m5 || self.pool_phase != PoolPhase::Populated || self.graph.ring.is_none() { + return Err(EBUSY); + } + self.bind_owner_channel(owner, context, channel_index) + } + fn bind_owner_channel( + &mut self, + owner: u64, + context: Arc, + channel_index: u8, + ) -> Result { if !self.reusable() { return Err(EBUSY); } @@ -1915,7 +2054,7 @@ impl Queue { self.kick.clear_ring()?; let kick_alias = self.kick.map_client(context.vm())?; let pool_alias = self.pool.map_client(context.vm())?; - self.graph.bind(context.clone(), kick_alias, pool_alias) + self.graph.bind(context.clone(), kick_alias, Some(pool_alias)) })(); let binding = match moved { Ok(binding) => binding, @@ -1941,7 +2080,9 @@ impl Queue { self.retained_owner = None; } context.mark_published(); + self.clear_binding_note(); context.note_compute_binding(true); + self.binding_noted = true; crate::g17::trace::bind( crate::g17::trace::COMPUTE, self.qid(), @@ -1949,6 +2090,8 @@ impl Queue { if same_vm { 2 } else { 1 }, ); self.owner = Some(owner); + self.channel_index = channel_index; + self.heavy_run = 0; self.rearm_for = None; self.unpublished_binding = true; self.released = false; @@ -1959,10 +2102,9 @@ impl Queue { /// True allows the registry to cancel the never-published QID and drop this graph. An /// installed graph remains retained even after the logical owner exits without work. pub(crate) fn release_owner(&mut self) -> Result { - if let Some(binding) = &self.binding { - binding.context.note_compute_binding(false); - } + self.clear_binding_note(); if !self.installed && self.active.len == 0 && !self.quarantined && self.previous.is_none() { + self.clear_owner(false); return Ok(true); } self.released = true; @@ -1995,8 +2137,7 @@ impl Queue { self.retirement_ready = true; } if self.retirement_ready { - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); } } Ok(false) @@ -2024,6 +2165,27 @@ impl Queue { // exited owner's idle queue left a later command retired without a completion stamp. Some(binding) } + /// A recycled vacant sibling queue whose descriptor ring still awaits off-lock release + /// before re-arming with fresh backing. + pub(crate) fn take_recycled_ring(&mut self) -> Option { + if !self.recycled_pending() + || self.pool_phase != PoolPhase::Vacant + || self.graph.ring.is_none() + { + return None; + } + let descriptors = self + .binding + .as_mut() + .and_then(|binding| binding.descriptors.take()); + let ring = self.graph.vacate_ring(); + Some(Vacated { + _alias: None, + _pages: None, + _descriptors: descriptors, + _ring: ring, + }) + } /// An idle retained queue whose USC backing may be given back. pub(crate) fn vacate_candidate(&self) -> bool { self.pool_phase == PoolPhase::Populated @@ -2135,10 +2297,9 @@ impl Queue { self.replay_prepared = false; self.submitted = 0; self.kick.clear_parent_after_recovery(); - self.owner = None; + self.clear_owner(true); self.released = true; self.retirement_ready = true; - self.released_at = now_ns(); self.needs_fresh_backing = true; Ok(()) } @@ -2213,21 +2374,40 @@ impl Queue { })) } /// Installs fresh backing into a vacant pool; returns the descriptor row data - /// the caller writes before binding an owner. + /// the caller writes before binding an owner, plus any previous sibling descriptor + /// ring to drop off-lock. pub(crate) fn rearm( &mut self, pages: crate::g17::freelist::Pages, ring: DescriptorRing, - ) -> Result { + ) -> Result<(PoolDescriptor, Option)> { if !self.can_rearm() { return Err(EAGAIN); } - self.graph.rearm_ring(ring)?; - self.pool.rearm(pages)?; + let descriptors = self + .binding + .as_mut() + .and_then(|binding| binding.descriptors.take()); + let old_ring = self.graph.rearm_ring(ring); + if let Err(error) = self.pool.rearm(pages) { + if let Some(old) = old_ring { + let _ = self.graph.rearm_ring(old); + } + if let (Some(binding), Some(descriptors)) = (self.binding.as_mut(), descriptors) { + binding.descriptors = Some(descriptors); + } + return Err(error); + } self.pool_phase = PoolPhase::Populated; self.release_sent_ns = None; self.needs_fresh_backing = false; - self.pool.descriptor() + let vacated = (old_ring.is_some() || descriptors.is_some()).then_some(Vacated { + _alias: None, + _pages: None, + _descriptors: descriptors, + _ring: old_ring, + }); + Ok((self.pool.descriptor()?, vacated)) } pub(crate) fn pool_fits(&self, required: ComputeCapacity) -> bool { !self.growing && self.pool_phase == PoolPhase::Populated && self.pool.fits_capacity(required) @@ -2461,16 +2641,43 @@ impl Queue { status: &Arc, through: Option, recovery_state: u32, + ) -> Result> { + self.dependency_checked(owner, status, through, recovery_state, false) + } + + /// As [`Self::dependency`], additionally requiring every covered active kick to carry a + /// visible completion (`DRM_ASAHI_COMPUTE_VISIBLE_COMPLETION`) when `require_visible` is set. + /// A covered kick without visible completion returns `EAGAIN` so the consumer waits for it + /// to retire on the host. + pub(crate) fn dependency_checked( + &self, + owner: u64, + status: &Arc, + through: Option, + recovery_state: u32, + require_visible: bool, ) -> Result> { if through.is_none() || self.owner != Some(owner) { return Ok(None); } - let Some(active) = self + let mut newest = None; + for active in self .active .iter() .filter(|a| crate::g17::job::Order::contains(through, a.packet.order.sequence)) - .last() - else { + { + if require_visible { + let visible = matches!( + &active.packet.command, + crate::g17::command::Validated::Compute { visible_completion: true, .. } + ); + if !visible { + return Err(EAGAIN); + } + } + newest = Some(active); + } + let Some(active) = newest else { return Ok(None); }; if self.quarantined && self.spared_quarantine { @@ -2526,7 +2733,7 @@ impl Graph { (object, record_start(slot, offset, window, stride)?) } else { let start = record_start(0, offset, window, GRAPH_SIZE - 0x6800)?; - (&mut *self.graph, 0x6800 + start) + (&mut self.graph, 0x6800 + start) }; if core::mem::size_of::() > window { return Err(EINVAL); @@ -2777,13 +2984,22 @@ impl Queue { let predecessor = KickPredecessor::new(qid, kick_parent)?; let matrix_ops = self.graph.m5 && *requested_matrix_ops; let m5_board = if self.graph.m5 { Some(self.graph.board.ok_or(EINVAL)?) } else { None }; - // Every earlier kick of this queue has retired, so the parent has completed. + // Each physical QID owns a single preemption/operand/usage/status/stamp set: only take the + // pipelined parent class once every earlier kick on this physical channel has retired. + // On multi-channel boards (M5 Pro), concurrency comes strictly from independent kicks + // running across distinct sibling QIDs because they carry no barrier on each other. let parent_retired = self.active.len == 0 && self.replays.len == 0 && !self.quarantined && !self.awaiting_witness; let parent_class = m5_board .map(|board| crate::g17::fw::m5::compute::parent_dependency(board, parent_retired)); + let multi_channel = m5_board.is_some_and(crate::g17::fw::m5::compute::multi_channel); + let (m5_ordinal, m5_object_ids) = if multi_channel { + packet.context.next_compute_identity() + } else { + (self.ordinal, 0x0000_0001_0000_0001) + }; let m5_args = m5_board.zip(parent_class).map(|(board, parent_class)| { let tuple = crate::g17::fw::m5::compute::kick_tuple(board, parent_class); crate::g17::fw::m5::compute::DescriptorArgs { @@ -2795,7 +3011,7 @@ impl Queue { preempt_va: addresses.preempt, cdm_va: *cdm_va, operand_va: addresses.operand, usage_va: addresses.usage, free_list_slot: u32::from(self.pool.id()), context_id: args.context_id, work_state: work_word, - object_ids: 0x0000_0001_0000_0001, + object_ids: m5_object_ids, resource_policy: plan.map_or(0xf5_0040_0020, |p| u64::from(p.pressure) << 32 | 0x0040_0020), preempt_state_offset: tuple.preempt_state_offset, // The board's core layout sizes the operand state, as on G17P. @@ -2810,13 +3026,15 @@ impl Queue { }, common26_tail: board.graph.is_common26(), descriptor_va: descriptor_low, - // M5 Pro's descriptors carry the ordinal as the submission sequence too, as macOS's do. - submit_sequence: if board.completion_inputs() { u64::from(self.ordinal) } else { 0 }, + // M5 Pro's descriptors carry the shared context ordinal as both submit_sequence and + // completion_ordinal. + submit_sequence: if board.completion_inputs() { u64::from(m5_ordinal) } else { 0 }, work_state_va: work_node, cdm_end_va: *cdm_end_va, stamp_va: [args.stamp_va, args.aux_stamp_va], stamp_value: crate::g17::fw::stamp_value(kick_timestamp.get() as u32), qid: u32::from(qid), + channel_index: if multi_channel { u32::from(self.channel_index) } else { 0 }, kick_timestamp: kick_timestamp.get(), - completion_ordinal: crate::g17::fw::m5::compute::completion_ordinal(board, self.ordinal), + completion_ordinal: crate::g17::fw::m5::compute::completion_ordinal(board, m5_ordinal), status_va: args.status_va, timestamp_va: [timestamp_va, timestamp_va + 8], shared_control_va: self.pool.control_va(), event_metadata: crate::g17::fw::m5::compute::completion_forms(board).1, @@ -2937,7 +3155,8 @@ impl Queue { let target = self.pool.reserve_submission()?; let qos = host.qos_publish(qos::Owner { qid, qos: identity.qos, data_master: 2 }, identity.scheduler, policy).or_else(|error| { - self.pool.cancel_unpublished(target)?; Err(error) + self.pool.cancel_unpublished(target)?; + Err(error) })?; self.active.back_mut().ok_or(EIO)?.qos_pending = true; // `cursors` is this publication's snapshot: no second read of the ring. @@ -3125,6 +3344,23 @@ impl Queue { first || notify_activation)?)?; } host.notify((0x83 << 48) | 0x02 | u64::from(policy.priority()) << 2)?; + if !packet.cancel_requested() { + if let Some(dependency) = + crate::g17::fw::kick::KickDependency::new(qid, kick_timestamp) + { + packet.completion.note_source_published( + crate::g17::fence::PublishedSource { + epoch, + published, + dependency, + readers: self.source_readers.clone(), + }, + ); + if packet.cancel_requested() { + packet.completion.clear_source_published(); + } + } + } crate::g17::trace::publish(crate::g17::trace::COMPUTE, qid, ordinal, &packet); host.note_submission() })(); @@ -3155,7 +3391,7 @@ impl Queue { self.configuration.take().ok_or(EIO)?.release(); if self.ordinal == 0 && self.active.len == 0 && self.replays.len == 0 { self.retirement_ready = true; - if self.released { self.owner = None; } + if self.released { self.clear_owner(false); } } Ok(()) } @@ -3567,7 +3803,9 @@ impl Queue { { return Ok((false, None)); } + self.clear_binding_note(); if !self.installed { + self.clear_owner(false); return Ok((true, None)); } let mut retired = None; @@ -3589,12 +3827,17 @@ impl Queue { self.unpublished_binding = false; self.retirement_ready = true; self.released = true; - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); Ok((false, retired)) } } +impl Drop for Queue { + fn drop(&mut self) { + self.clear_binding_note(); + } +} + impl Queue { /// Same immutable singleton identity and current physical epoch. pub(crate) fn has_input_source( diff --git a/drivers/gpu/drm/asahi/g17/queue/compute/retirement.rs b/drivers/gpu/drm/asahi/g17/queue/compute/retirement.rs index e6d70105dae160..15a98a80ba482f 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute/retirement.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute/retirement.rs @@ -292,10 +292,14 @@ pub(crate) struct Batch { /// ([`NO_FRONTIER`] for a QID without a staged queue). A record at or past it belongs /// to a command published during the scan, which a later batch stages. frontiers: [u64; QIDS], + /// Bitmasks of QIDs touched in `slots` and `frontiers` so `clear()` touches only active QIDs. + touched_slots: u128, + touched_frontiers: u128, } const NO_FRONTIER: u64 = u64::MAX; const KICK_MASK: u64 = (1 << 40) - 1; +const _: () = assert!(QIDS <= 128); impl Batch { pub(crate) fn new() -> Result { @@ -311,19 +315,34 @@ impl Batch { unobserved: 0, covered: 0, frontiers: [NO_FRONTIER; QIDS], + touched_slots: 0, + touched_frontiers: 0, }) } pub(crate) fn clear(&mut self) { self.requests.clear(); - self.slots.fill((0, 0)); + let mut slots = self.touched_slots; + while slots != 0 { + let qid = slots.trailing_zeros() as usize; + slots &= slots - 1; + self.slots[qid] = (0, 0); + } + self.touched_slots = 0; self.open = None; self.unobserved = 0; self.covered = 0; - self.frontiers.fill(NO_FRONTIER); + let mut frontiers = self.touched_frontiers; + while frontiers != 0 { + let qid = frontiers.trailing_zeros() as usize; + frontiers &= frontiers - 1; + self.frontiers[qid] = NO_FRONTIER; + } + self.touched_frontiers = 0; } /// Records the first kick `qid`'s queue had not yet published when this batch was staged. pub(crate) fn stage_frontier(&mut self, qid: u8, next: u64) -> Result { *self.frontiers.get_mut(usize::from(qid)).ok_or(EINVAL)? = next & KICK_MASK; + self.touched_frontiers |= 1u128 << qid; Ok(()) } /// A record of `qid` with `kick` names a command published after this batch was staged. @@ -372,6 +391,7 @@ impl Batch { .map_err(|_| ENOSPC)?; *self.heads.get_mut(bucket).ok_or(EIO)? = index; *slot = (start, slot.1 + 1); + self.touched_slots |= 1u128 << ticket.qid; self.open = Some(ticket.qid); self.unobserved += 1; self.covered += usize::from(covered); @@ -813,4 +833,27 @@ mod index_tests { assert!(batch.fold_reader(|word| Ok(other[word])).unwrap()); assert!(!batch.complete() && !batch.covered_pending()); } + #[test] + fn clear_resets_touched_slots_and_frontiers_across_batches() { + let mut batch = Batch::new().unwrap(); + let low = ticket(0, 11, 0x1000); + let high = ticket((QIDS - 1) as u8, 22, 0x2000); + batch.stage_frontier(0, 12).unwrap(); + batch.stage_frontier((QIDS - 1) as u8, 23).unwrap(); + batch.request(&low, true).unwrap(); + batch.request(&high, false).unwrap(); + batch.clear(); + assert!(batch.complete() && !batch.covered_pending()); + assert_eq!(batch.touched_slots, 0); + assert_eq!(batch.touched_frontiers, 0); + assert!(!batch.published_after_staging(0, 12)); + assert!(!batch.published_after_staging(QIDS - 1, 23)); + // Re-staging the same QIDs with new kicks succeeds cleanly after clear(). + let next = ticket((QIDS - 1) as u8, 25, 0x3000); + batch.request(&next, true).unwrap(); + let words = record(&next, [50, 60]); + assert!(batch.fold_reader(|word| Ok(words[word])).unwrap()); + assert!(batch.complete()); + assert_eq!(batch.take(&next).unwrap().map(|obs| obs.timestamps), Some([50, 60])); + } } diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index d322c2710ab9e3..2bb536c65a68a4 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -8,7 +8,7 @@ pub(crate) mod render; use super::{ command::{Parser, UscWindow, Validated}, - completion::{Completion, Destinations, PreparedPublication}, + completion::{Completion, Destinations, PreparedPublication, Publication}, context::Context, dependency::FailureRecord, fence::Outputs, @@ -31,6 +31,15 @@ use kernel::{ static FENCE_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); pub(crate) mod admission; +mod outstanding; + +use outstanding::Outstanding; + +impl outstanding::Status for Fences { + fn status(&self) -> i32 { + Fences::status(self) + } +} /// Host identities for retained physical channels, separate from firmware object generations. /// The device mutex protects allocation; cancelled preparations never reuse IDs. @@ -100,10 +109,18 @@ pub(crate) struct Queue { variant: &'static crate::g17::fw::Variant, proof: Proof, sequence: [u64; 2], - frontiers: [KVec<(u64, Fences)>; 2], + /// Each engine's unfinished commands, as many as userspace keeps queued (thousands + /// under vkd3d-proton). + frontiers: [Outstanding; 2], + /// The frontiers' entries that publish on the host ([`Fences::publishes`]), again: the only + /// same-engine entries [`EnqueueOrdering`] and the compute source check look for. Few + /// commands publish, so those readers walk this instead of every unfinished command. + publishers: [Outstanding; 2], /// Finished frontier entries pruned during this ioctl. Their last references /// can tear a whole completion down; that waits until the ioctl has published. - finished: KVec, + /// Like the frontiers it needs no contiguous pages, and its growth must not fail + /// a submit on fragmentation. + finished: KVVec, failures: [FailureRecord; 2], // Closing the userspace queue releases admission even if firmware still // retains one of its execution contexts or installed physical graphs. @@ -137,6 +154,7 @@ impl Queue { Engine::Render, super::timeout::DEFAULT_ALLOWANCE_MS, )?); + let failures = context.status().failures().finished; Ok(Self { dev: dev.into(), context, @@ -152,8 +170,9 @@ impl Queue { variant, proof: Proof::new(), sequence: [0; 2], - frontiers: core::array::from_fn(|_| KVec::new()), - finished: KVec::new(), + frontiers: [Outstanding::new(failures), Outstanding::new(failures)], + publishers: [Outstanding::new(failures), Outstanding::new(failures)], + finished: KVVec::new(), failures: [FailureRecord::new(), FailureRecord::new()], _slot: slot, }) @@ -175,28 +194,21 @@ impl Queue { } fn prune_frontier(&mut self, index: usize) { - let failure = &mut self.failures[index]; - // Without room the entries are released here, as they always could be. - let mut finished = if self - .finished - .reserve(self.frontiers[index].len(), GFP_KERNEL) - .is_ok() - { - Some(&mut self.finished) - } else { - None - }; - self.frontiers[index].retain(|(sequence, fences)| { - let status = fences.status(); - if status == 0 { - return true; - } - if let Some(finished) = finished.as_mut() { - let _ = finished.push_within_capacity(fences.clone()); - } - failure.note(*sequence, status, fences); - false - }); + outstanding::prune_engine( + &mut self.frontiers[index], + &mut self.publishers[index], + self.context.status().failures(), + &mut self.failures[index], + &mut self.finished, + ); + } + + fn has_pending_publication(&self, order: &Order) -> bool { + self.publishers.iter().enumerate().any(|(index, publishers)| { + publishers + .prefix(order.wait_through[index]) + .any(|(_, fences)| fences.publication.as_ref().is_some_and(|p| p.is_pending()) && fences.status() <= 0) + }) } #[expect( @@ -213,11 +225,9 @@ impl Queue { inputs: &[file::SyncItem], destinations: Destinations, ) -> Result { - let engine = match &command { - Validated::Render { .. } => Engine::Render, - Validated::Compute { .. } => Engine::Compute, - }; + let engine = Engine::of(&command); let index = engine.index(); + let other = 1 - index; if let Validated::Render { ray_query, .. } = &command { let blocks = self .backend @@ -227,7 +237,7 @@ impl Queue { } } self.prune_frontier(index); - self.frontiers[index].reserve(1, GFP_KERNEL)?; + self.prune_frontier(other); if engine == Engine::Compute { self.ensure_compute(&command)?; } @@ -239,16 +249,21 @@ impl Queue { // Ring order completes a converted input only if a kick waits for its // ring predecessor; without that, keep the input's completion wait. let host_waits = self.backend.host_producer_waits(); + let has_outputs = destinations.has_outputs(); + let query_access = match &command { + Validated::Compute { query_access, .. } => *query_access, + Validated::Render { .. } => true, + }; let sources = if !host_waits && engine == Engine::Compute && !inputs.is_empty() - && !destinations.has_outputs() - && self.frontiers[0].iter().all(|(sequence, fences)| { - !Order::contains(order.wait_through[0], *sequence) || fences.status() > 0 - }) - && self.frontiers[1].iter().all(|(sequence, fences)| { - !Order::contains(order.wait_through[1], *sequence) - || fences.ready.raw() != fences.completed.raw() + && !has_outputs + && self.frontiers[0] + .prefix(order.wait_through[0]) + .all(|(_, fences)| fences.status() > 0) + && self.publishers[1].prefix(order.wait_through[1]).all(|(_, fences)| { + (fences.ready.raw() != fences.completed.raw() + && !fences.publication.as_ref().is_some_and(|p| p.is_pending())) || fences.status() > 0 }) && self.failures.iter_mut().enumerate().all(|(index, failure)| { @@ -270,65 +285,43 @@ impl Queue { ); } - // Only earlier render ordinals covered by the explicit logical prefix - // can delay host publication. These links never become GPU dependencies. - let host_predecessors = self.frontiers[index] - .iter() - .take_while(|(sequence, _)| { - engine == Engine::Render && Order::contains(order.wait_through[index], *sequence) - }) - .filter_map(|(_, fences)| fences.publication.as_ref()); - let completion = Completion::new( - &self.dev, - &self.fences, - &self.context, - aggregate.member(), - guard, - destinations, - engine == Engine::Compute, - host_predecessors.clone().next().is_some(), - self.backend.feed(), - sources.clone(), - self.usage.clone(), - )?; - let publication = completion - .publication() - .map(|target| PreparedPublication::new(target, host_predecessors)) - .transpose()?; - if engine == Engine::Compute { - self.prune_frontier(Engine::Render.index()); - } - let other = 1 - index; - let prefix = order.wait_through[other]; - let frontier = if prefix.is_some() { - let frontier = self.frontiers[other].as_slice(); - // Accepted sequences increase from one, and retain preserves their - // order, so all members of a logical prefix form one slice. - let end = frontier.partition_point(|(sequence, _)| Order::contains(prefix, *sequence)); - &frontier[..end] - } else { - &[] - }; - let count = frontier.len(); - // Only a command that copies or resets queries can observe timestamps the - // host has not yet published for its predecessors. - let query_access = match &command { - Validated::Compute { query_access, .. } => *query_access, - Validated::Render { .. } => true, - }; - let timestamp_prefix = order.wait_through[index]; - let timestamps = if engine == Engine::Compute && query_access && timestamp_prefix.is_some() { - let frontier = self.frontiers[index].as_slice(); - let end = frontier - .partition_point(|(sequence, _)| Order::contains(timestamp_prefix, *sequence)); - &frontier[..end] - } else { - &[] + // `build()` reads only this engine's publishers. A command of this engine that failed + // since the prune above without a publication is not among them, so prune again: any + // failure now visible makes it a full scan, and the failure record below has it. + self.prune_frontier(index); + let (completion, publication, ordering_host_waits, ordering_firmware_waits) = { + let ordering = EnqueueOrdering::build( + &self.publishers[index], + &self.frontiers[other], + order, + engine, + host_waits, + query_access, + )?; + let completion = Completion::new( + &self.dev, + &self.fences, + &self.context, + aggregate.member(), + guard, + destinations, + engine == Engine::Compute, + !ordering.predecessors.is_empty(), + self.backend.feed(), + sources.clone(), + self.usage.clone(), + )?; + let publication = completion + .publication() + .map(|target| PreparedPublication::new(target, ordering.predecessors.iter().copied())) + .transpose()?; + ( + completion, + publication, + ordering.host_waits, + ordering.firmware_waits, + ) }; - let timestamp_count = timestamps - .iter() - .filter(|(_, fences)| fences.ready.raw() == fences.completed.raw()) - .count(); let mut failures: [Option; 2] = [None, None]; for (index, failure) in self.failures.iter_mut().enumerate() { failures[index] = failure.earliest().and_then(|(sequence, fences)| { @@ -337,50 +330,37 @@ impl Queue { } let failure_count = failures.iter().flatten().count(); let mut dependencies = KVec::with_capacity( - inputs.len() + count + timestamp_count + failure_count, + // The firmware-ordered producers add one scheduled fence between them. + inputs.len() + + ordering_host_waits.len() + + usize::from(!ordering_firmware_waits.is_empty()) + + failure_count, GFP_KERNEL, )?; // Host-waited producers are checked on the host instead of in firmware. - let (host_count, firmware_count) = if host_waits { - (count, 0) - } else { - (0, count) - }; let mut checked_inputs = KVec::with_capacity( - inputs.len() + host_count + timestamp_count + failure_count, + inputs.len() + ordering_host_waits.len() + failure_count, GFP_KERNEL, )?; - let mut firmware = KVec::with_capacity(firmware_count, GFP_KERNEL)?; + let mut firmware = KVec::with_capacity(ordering_firmware_waits.len(), GFP_KERNEL)?; for fence in failures.into_iter().flatten() { checked_inputs.push(fence.clone(), GFP_KERNEL)?; dependencies.push(fence.clone(), GFP_KERNEL)?; } - // Same-engine parents order GPU execution, not the host's timestamp - // writes. Only timestamp publishers need these completion waits and - // status checks; ordinary compute keeps its existing queue ordering. - for (_, fences) in timestamps { - if fences.ready.raw() == fences.completed.raw() { - checked_inputs.push(fences.completed.clone(), GFP_KERNEL)?; - dependencies.push(fences.ready.clone(), GFP_KERNEL)?; - } + for fence in ordering_host_waits { + dependencies.push(fence.clone(), GFP_KERNEL)?; + checked_inputs.push(fence, GFP_KERNEL)?; } - for (_, fences) in frontier { - // Successful completion includes host timestamp publication. Its - // ready fence adds no ordering and would prevent shallow inline - // publication. Failed and pending producers still need checking. - if fences.status() > 0 { - continue; - } - if host_waits { - // Keep other-engine producers on the host until completion, and - // propagate their errors before publishing the consumer. - dependencies.push(fences.completed.clone(), GFP_KERNEL)?; - checked_inputs.push(fences.completed.clone(), GFP_KERNEL)?; - } else { - dependencies.push(fences.ready.clone(), GFP_KERNEL)?; - firmware.push(fences.completed.clone(), GFP_KERNEL)?; - } + // Firmware orders execution after each producer; the scheduler needs only the latest + // scheduled fence of them (dependency::ProducerWaits). + let mut producer_waits = super::dependency::ProducerWaits::new(); + for (scheduled, completed) in &ordering_firmware_waits { + producer_waits.producer(scheduled, |fence| { + Ok(dependencies.push(fence.clone(), GFP_KERNEL)?) + })?; + firmware.push(completed.clone(), GFP_KERNEL)?; } + producer_waits.finish(|fence| Ok(dependencies.push(fence.clone(), GFP_KERNEL)?))?; // Each command owns every input fence; independent engines may publish in // either order and must each consume an input's error status before running. for sync in inputs { @@ -431,9 +411,10 @@ impl Queue { .ok_or(ENODEV)? .enqueue(packet, dependencies, early, publication)?; self.sequence[index] = order.sequence; - self.frontiers[index] - .push_within_capacity((order.sequence, fences)) - .map_err(|_| ENOMEM)?; + if fences.publishes() { + self.publishers[index].push_within_capacity(order.sequence, fences.clone())?; + } + self.frontiers[index].push_within_capacity(order.sequence, fences)?; Ok(()) } /// Finish parsing, validation and VM pinning before entering publication. @@ -475,10 +456,7 @@ impl Queue { &command.payload, ) .map_err(|error| refused("the command's requirements", error))?; - let engine = match &payload { - Validated::Render { .. } => Engine::Render, - Validated::Compute { .. } => Engine::Compute, - }; + let engine = Engine::of(&payload); if !self.backend.supports_engine(engine) { return Err(ENOTSUPP); } self.backend .prepare_command(&mut payload) @@ -547,7 +525,7 @@ impl crate::queue::Queue for Queue { &mut self, _reg_data: &crate::driver::AsahiRegData<'_>, id: u64, - syncs: KVec, + syncs: KVVec, input_count: usize, bytes: &[u8], objects: Pin<&xarray::XArray>>, @@ -585,17 +563,31 @@ impl crate::queue::Queue for Queue { return Err(EIO); } let (mut pending, guards) = self.prepare_submission(bytes, objects)?; - if pending + let has_render = pending .iter() - .any(|(command, _, _)| matches!(command, Validated::Render { .. })) - { + .any(|(command, _, _)| matches!(command, Validated::Render { .. })); + if has_render { self.context.note_render(); } + let compute_only = !has_render && !pending.is_empty(); if super::timeout::select_submission(pending.iter().map(|(cmd, _, _)| cmd.long_job())) { for (command, _, _) in pending.iter_mut() { command.allow_long_job(); } } + // Room for every command's frontier entry, so that running out of memory fails + // the submission before any of it is queued. Userspace sets the frontier's + // length, so its memory is charged to the caller. + let mut room = [0; 2]; + for (command, _, _) in pending.iter() { + room[Engine::of(command).index()] += 1; + } + for (frontier, room) in self.frontiers.iter_mut().zip(room) { + frontier.reserve(room)?; + } + for (publishers, room) in self.publishers.iter_mut().zip(room) { + publishers.reserve(room)?; + } let mut guards = guards.into_iter(); // Where a firmware wait reports completion before a weak stream tail's writes are // visible, only a command that declares a visible completion is waited for there. @@ -603,8 +595,9 @@ impl crate::queue::Queue for Queue { let firmware_source = pending.len() == 1 && matches!(&pending[0].0, Validated::Compute { visible_completion, .. } if *visible_completion || !visible_required) - && !pending[0].2.has_outputs(); - let aggregate = outputs.publish(self.context.clone(), firmware_source)?; + && !pending[0].2.has_outputs() + && !self.has_pending_publication(&pending[0].1); + let aggregate = outputs.publish(self.context.clone(), firmware_source, compute_only)?; let output_fence = aggregate.fence(); super::trace::submit( 1, @@ -658,3 +651,700 @@ impl Drop for Queue { self.backend.release_owner(); } } + +/// Whether a cross-engine consumer must wait on the host for a covered +/// producer's completion fence before scheduling. +/// +/// Only query-accessing compute commands can read or reset timestamp words on +/// the GPU. Timestamp-writing renders (whose firmware timestamp window is +/// disabled whenever chained behind predecessors) and `NO_QUERY_ACCESS` compute +/// commands write all timestamps on the host inside ordered +/// [`Publication::publish`], so they overlap in firmware and chain publication +/// instead of draining the GPU. +const fn cross_engine_wait_completed( + host_waits: bool, + engine: Engine, + query_access: bool, + has_pending_publication: bool, +) -> bool { + if host_waits { + return true; + } + has_pending_publication && matches!(engine, Engine::Compute) && query_access +} + +/// Whether a cross-engine consumer overlaps execution with a producer that has +/// pending ordered host publication and therefore chains its completion behind it. +const fn cross_engine_chain_publication( + host_waits: bool, + engine: Engine, + query_access: bool, +) -> bool { + !host_waits && !(matches!(engine, Engine::Compute) && query_access) +} + +/// Whether a same-engine consumer must wait on the host for covered same-engine +/// predecessors with pending ordered host publication: query-accessing compute +/// may read or reset query words on the GPU whose host publication is still +/// pending. Timestamp-writing renders disable their firmware timestamp window +/// when chained behind predecessors and write on the host in publication order. +const fn same_engine_wait_completed(engine: Engine, query_access: bool) -> bool { + matches!(engine, Engine::Compute) && query_access +} + +trait FrontierEntry: outstanding::Status { + fn ready_is_completed(&self) -> bool; + fn publication(&self) -> Option<&Arc>; + fn pending_publication(&self) -> Option<&Arc> { + self.publication().filter(|publication| publication.is_pending()) + } + fn completed(&self) -> &Fence; + fn scheduled(&self) -> &Fence; +} + +impl FrontierEntry for Fences { + fn ready_is_completed(&self) -> bool { + self.ready.raw() == self.completed.raw() + } + + fn publication(&self) -> Option<&Arc> { + self.publication.as_ref() + } + + fn completed(&self) -> &Fence { + &self.completed + } + + fn scheduled(&self) -> &Fence { + &self.scheduled + } +} + +struct EnqueueOrdering<'a> { + predecessors: KVec<&'a Arc>, + host_waits: KVec, + firmware_waits: KVec<(Fence, Fence)>, +} + +impl<'a> EnqueueOrdering<'a> { + /// `same_publishers`: the publishers of this command's engine. Only those can be same-engine + /// predecessors or host waits, and the rest of that engine's frontier can be deep. + fn build( + same_publishers: &'a Outstanding, + other_frontier: &'a Outstanding, + order: Order, + engine: Engine, + host_waits: bool, + query_access: bool, + ) -> Result { + let index = engine.index(); + let other = 1 - index; + let same_covered = same_publishers.prefix(order.wait_through[index]); + let other_covered = other_frontier.prefix(order.wait_through[other]); + + let same_wait = same_engine_wait_completed(engine, query_access); + let same_chain = !same_wait; + let cross_chain = cross_engine_chain_publication(host_waits, engine, query_access); + + // Retain covered pending or failed publications (`status() <= 0`, not + // only `== 0`) that survived `prune_frontier()`: if a predecessor's + // deferred error published between pruning and link selection, + // `add_successor()` still delivers that failure immediately instead of + // letting the successor signal success. + let mut predecessors = KVec::new(); + let mut host = KVec::new(); + let mut firmware = KVec::new(); + if same_chain { + for (_, entry) in same_covered.clone() { + let status = entry.status(); + if status <= 0 { + if let Some(publication) = entry.pending_publication() { + predecessors.push(publication, GFP_KERNEL)?; + } else if status < 0 { + // Failed after `prune_frontier()` without an active + // publication: keep its already-signalled error fence. + host.push(entry.completed().clone(), GFP_KERNEL)?; + } + } + } + } + if cross_chain { + for (_, entry) in other_covered.clone() { + if entry.status() <= 0 { + if let Some(publication) = entry.pending_publication() { + predecessors.push(publication, GFP_KERNEL)?; + } + } + } + } + + if same_wait { + for (_, entry) in same_covered { + let status = entry.status(); + if status < 0 + || (status == 0 + && (entry.ready_is_completed() || entry.pending_publication().is_some())) + { + host.push(entry.completed().clone(), GFP_KERNEL)?; + } + } + } + + for (_, entry) in other_covered { + // Successful completion includes host timestamp publication. Its + // ready fence adds no ordering and would prevent shallow inline + // publication. Failed and pending producers still need checking. + if entry.status() > 0 { + continue; + } + if cross_engine_wait_completed( + host_waits, + engine, + query_access, + entry.pending_publication().is_some(), + ) { + host.push(entry.completed().clone(), GFP_KERNEL)?; + } else { + firmware.push( + (entry.scheduled().clone(), entry.completed().clone()), + GFP_KERNEL, + )?; + } + } + + Ok(Self { + predecessors, + host_waits: host, + firmware_waits: firmware, + }) + } +} + +#[kunit_tests(asahi_g17_cross_engine_timestamps)] +mod tests { + use super::*; + use crate::g17::{fence::independent, job::fence_status, status::VmStatus}; + use outstanding::Status as _; + + static TEST_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); + + struct TestEntry { + ready: Fence, + scheduled: Fence, + completed: Fence, + publication: Option>, + } + + impl outstanding::Status for TestEntry { + fn status(&self) -> i32 { + fence_status(&self.completed) + } + } + + impl FrontierEntry for TestEntry { + fn ready_is_completed(&self) -> bool { + self.ready.raw() == self.completed.raw() + } + + fn publication(&self) -> Option<&Arc> { + self.publication.as_ref() + } + + fn completed(&self) -> &Fence { + &self.completed + } + + fn scheduled(&self) -> &Fence { + &self.scheduled + } + } + + fn frontier(entries: [(u64, TestEntry); N]) -> Outstanding { + let mut frontier = Outstanding::new(0); + frontier.reserve(N).unwrap(); + for (sequence, entry) in entries { + frontier.push_within_capacity(sequence, entry).unwrap(); + } + frontier + } + + fn test_entry( + contexts: &FenceContexts, + status: &Arc, + pub_outputs: Option, + ) -> (TestEntry, Option>) { + let ready = Fence::from_fence(&independent(contexts).unwrap()); + let scheduled = Fence::from_fence(&independent(contexts).unwrap()); + if let Some(has_outputs) = pub_outputs { + let (publication, completed) = + Publication::test_pair(contexts, status, has_outputs).unwrap(); + ( + TestEntry { + ready, + scheduled, + completed, + publication: Some(publication.clone()), + }, + Some(publication), + ) + } else { + let completed = Fence::from_fence(&independent(contexts).unwrap()); + ( + TestEntry { + ready, + scheduled, + completed, + publication: None, + }, + None, + ) + } + } + + #[test] + fn transitive_render_chains_publication_without_host_wait() { + let none = frontier([]); + let contexts = FenceContexts::new(1, c_str!("asahi_q_ts_test"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + // Compute A writes a timestamp (has pending ordered host publication). + let (comp_a, pub_a) = test_entry(&contexts, &status, Some(true)); + let pub_a = pub_a.unwrap(); + PreparedPublication::new(pub_a.clone(), core::iter::empty()) + .unwrap() + .activate(); + let compute_frontier = frontier([(1, comp_a)]); + + // Render B has no timestamps and covers Compute A: overlaps A via + // firmware wait and chains its publication behind A. + let order_b = Order { + sequence: 1, + wait_through: [None, Some(1)], + tiling_wait_through: [None, None], + }; + let plan_b = EnqueueOrdering::build( + &none, + &compute_frontier, + order_b, + Engine::Render, + false, + true, + ) + .unwrap(); + assert!(plan_b.host_waits.is_empty()); + assert_eq!(plan_b.firmware_waits.len(), 1); + assert_eq!(plan_b.predecessors.len(), 1); + + let (rend_b, pub_b) = test_entry(&contexts, &status, Some(false)); + let pub_b = pub_b.unwrap(); + PreparedPublication::new(pub_b.clone(), plan_b.predecessors.iter().copied()) + .unwrap() + .activate(); + let render_frontier = frontier([(1, rend_b)]); + + // Render C writes a timestamp and covers only Render B: chains its + // publication behind B (disabling its firmware window in Completion::new) + // instead of stalling on the host, so C still cannot publish or write + // timestamps before A publishes through B. + let order_c = Order { + sequence: 2, + wait_through: [Some(1), None], + tiling_wait_through: [None, None], + }; + let plan_c = EnqueueOrdering::build( + &render_frontier, + &compute_frontier, + order_c, + Engine::Render, + false, + true, + ) + .unwrap(); + assert!(plan_c.host_waits.is_empty()); + assert!(plan_c.firmware_waits.is_empty()); + assert_eq!(plan_c.predecessors.len(), 1); + + let (pub_c, fence_c) = Publication::test_pair(&contexts, &status, true).unwrap(); + PreparedPublication::new(pub_c.clone(), plan_c.predecessors.iter().copied()) + .unwrap() + .activate(); + + pub_b.finish(Ok([3, 4, 0, 0])); + pub_c.finish(Ok([5, 6, 0, 0])); + assert_eq!(fence_status(&fence_c), 0); + + pub_a.finish(Err(EIO)); + assert!(fence_status(&fence_c) < 0); + } + + #[test] + fn predecessor_failing_after_prune_propagates_to_same_engine_successor() { + let contexts = FenceContexts::new(1, c_str!("asahi_q_fail_test"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let (comp_a, pub_a) = test_entry(&contexts, &status, Some(true)); + let pub_a = pub_a.unwrap(); + PreparedPublication::new(pub_a.clone(), core::iter::empty()) + .unwrap() + .activate(); + + let (rend_b, pub_b) = test_entry(&contexts, &status, Some(false)); + let pub_b = pub_b.unwrap(); + PreparedPublication::new(pub_b.clone(), core::iter::once(&pub_a)) + .unwrap() + .activate(); + + // Render B retires cleanly in hardware while waiting on Compute A, so + // prune_frontier() sees B pending (`status() == 0`). + pub_b.finish(Ok([1, 2, 0, 0])); + assert_eq!(rend_b.status(), 0); + + // Compute A's deferred error publishes B's PRODUCER_FAILED after + // prune_frontier() and before Render C selects its predecessors. + pub_a.finish(Err(EIO)); + assert!(rend_b.status() < 0); + + let render_frontier = frontier([(1, rend_b)]); + let compute_frontier = frontier([(1, comp_a)]); + let order_c = Order { + sequence: 2, + wait_through: [Some(1), None], + tiling_wait_through: [None, None], + }; + let plan_c = EnqueueOrdering::build( + &render_frontier, + &compute_frontier, + order_c, + Engine::Render, + false, + true, + ) + .unwrap(); + assert_eq!(plan_c.predecessors.len(), 1); + + let (pub_c, fence_c) = Publication::test_pair(&contexts, &status, false).unwrap(); + PreparedPublication::new(pub_c.clone(), plan_c.predecessors.iter().copied()) + .unwrap() + .activate(); + pub_c.finish(Ok([3, 4, 0, 0])); + assert!(fence_status(&fence_c) < 0); + } + + #[test] + fn query_access_waits_while_timestamped_overlap_chains_in_both_directions() { + let none = frontier([]); + let contexts = FenceContexts::new(1, c_str!("asahi_q_dir_test"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let (rend_a, pub_ra) = test_entry(&contexts, &status, Some(true)); + let pub_ra = pub_ra.unwrap(); + PreparedPublication::new(pub_ra.clone(), core::iter::empty()) + .unwrap() + .activate(); + let rend_a_scheduled = rend_a.scheduled.raw(); + let rend_a_completed = rend_a.completed.raw(); + let render_frontier = frontier([(1, rend_a)]); + + // Render(ts) -> NO_QUERY_ACCESS Compute: overlaps in firmware and chains + // ordered host publication instead of stalling on the host. + let plan_rc = EnqueueOrdering::build( + &none, + &render_frontier, + Order { + sequence: 1, + wait_through: [Some(1), None], + tiling_wait_through: [None, None], + }, + Engine::Compute, + false, + false, + ) + .unwrap(); + assert!(plan_rc.host_waits.is_empty()); + assert_eq!(plan_rc.firmware_waits.len(), 1); + assert_eq!(plan_rc.firmware_waits[0].0.raw(), rend_a_scheduled); + assert_eq!(plan_rc.firmware_waits[0].1.raw(), rend_a_completed); + assert_eq!(plan_rc.predecessors.len(), 1); + + // Render(ts) -> query-accessing Compute: must host-wait until A publishes. + let plan_rc_query = EnqueueOrdering::build( + &none, + &render_frontier, + Order { + sequence: 1, + wait_through: [Some(1), None], + tiling_wait_through: [None, None], + }, + Engine::Compute, + false, + true, + ) + .unwrap(); + assert_eq!(plan_rc_query.host_waits.len(), 1); + assert_eq!(plan_rc_query.host_waits[0].raw(), rend_a_completed); + assert!(plan_rc_query.firmware_waits.is_empty()); + + let (comp_a, pub_ca) = test_entry(&contexts, &status, Some(true)); + let pub_ca = pub_ca.unwrap(); + PreparedPublication::new(pub_ca.clone(), core::iter::empty()) + .unwrap() + .activate(); + let comp_a_scheduled = comp_a.scheduled.raw(); + let comp_a_completed = comp_a.completed.raw(); + let compute_frontier = frontier([(1, comp_a)]); + + // Compute(ts) -> Render: overlaps in firmware and chains publication. + let plan_cr = EnqueueOrdering::build( + &none, + &compute_frontier, + Order { + sequence: 1, + wait_through: [None, Some(1)], + tiling_wait_through: [None, None], + }, + Engine::Render, + false, + true, + ) + .unwrap(); + assert!(plan_cr.host_waits.is_empty()); + assert_eq!(plan_cr.firmware_waits.len(), 1); + assert_eq!(plan_cr.firmware_waits[0].0.raw(), comp_a_scheduled); + assert_eq!(plan_cr.firmware_waits[0].1.raw(), comp_a_completed); + assert_eq!(plan_cr.predecessors.len(), 1); + + pub_ra.finish(Ok([1, 2, 0, 0])); + pub_ca.finish(Ok([3, 4, 0, 0])); + } + + #[test] + fn settled_timestamp_free_publication_drops_contagion_and_host_waits() { + let none = frontier([]); + let contexts = FenceContexts::new(1, c_str!("asahi_q_settle"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let (rend_a, pub_a) = test_entry(&contexts, &status, Some(true)); + let pub_a = pub_a.unwrap(); + PreparedPublication::new(pub_a.clone(), core::iter::empty()) + .unwrap() + .activate(); + + let (comp_b, pub_b) = test_entry(&contexts, &status, Some(false)); + let pub_b = pub_b.unwrap(); + PreparedPublication::new(pub_b.clone(), core::iter::once(&pub_a)) + .unwrap() + .activate(); + + // While Render A is still pending, query-accessing Compute C must host-wait on B. + let comp_b_completed = comp_b.completed.raw(); + let compute_frontier = frontier([(1, comp_b)]); + let plan_before = EnqueueOrdering::build( + &compute_frontier, + &none, + Order { + sequence: 2, + wait_through: [None, Some(1)], + tiling_wait_through: [None, None], + }, + Engine::Compute, + false, + true, + ) + .unwrap(); + assert_eq!(plan_before.host_waits.len(), 1); + assert_eq!(plan_before.host_waits[0].raw(), comp_b_completed); + + // Once Render A finishes cleanly, Compute B settles while still in flight: + // neither a query-accessing Compute nor a cross-engine Render waits or + // chains behind B. + pub_a.finish(Ok([1, 2, 0, 0])); + assert_eq!(rend_a.status(), 1); + assert_eq!(compute_frontier.iter().next().unwrap().1.status(), 0); + assert!(!pub_b.is_pending()); + + let plan_query = EnqueueOrdering::build( + &compute_frontier, + &none, + Order { + sequence: 2, + wait_through: [None, Some(1)], + tiling_wait_through: [None, None], + }, + Engine::Compute, + false, + true, + ) + .unwrap(); + assert!(plan_query.host_waits.is_empty()); + assert!(plan_query.predecessors.is_empty()); + + let plan_render = EnqueueOrdering::build( + &none, + &compute_frontier, + Order { + sequence: 2, + wait_through: [None, Some(1)], + tiling_wait_through: [None, None], + }, + Engine::Render, + false, + true, + ) + .unwrap(); + assert!(plan_render.host_waits.is_empty()); + assert_eq!(plan_render.firmware_waits.len(), 1); + assert!(plan_render.predecessors.is_empty()); + + pub_b.finish(Ok([3, 4, 0, 0])); + } + + #[test] + fn failed_settled_same_engine_entry_adds_host_wait() { + let none = frontier([]); + let contexts = FenceContexts::new(1, c_str!("asahi_q_settled_err"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let (rend_a, pub_a) = test_entry(&contexts, &status, Some(true)); + let pub_a = pub_a.unwrap(); + PreparedPublication::new(pub_a.clone(), core::iter::empty()) + .unwrap() + .activate(); + + let (rend_b, pub_b) = test_entry(&contexts, &status, Some(false)); + let pub_b = pub_b.unwrap(); + let rend_b_completed = rend_b.completed.raw(); + PreparedPublication::new(pub_b.clone(), core::iter::once(&pub_a)) + .unwrap() + .activate(); + + // Render A completes cleanly, settling Render B; then Render B fails in + // hardware after frontier pruning. + pub_a.finish(Ok([1, 2, 0, 0])); + assert!(!pub_b.is_pending()); + pub_b.finish(Err(EIO)); + assert!(rend_b.status() < 0); + assert_eq!(rend_a.status(), 1); + + let render_frontier = frontier([(1, rend_b)]); + let plan_c = EnqueueOrdering::build( + &render_frontier, + &none, + Order { + sequence: 2, + wait_through: [Some(1), None], + tiling_wait_through: [None, None], + }, + Engine::Render, + false, + true, + ) + .unwrap(); + assert!(plan_c.predecessors.is_empty()); + assert_eq!(plan_c.host_waits.len(), 1); + assert_eq!(plan_c.host_waits[0].raw(), rend_b_completed); + } + + #[test] + fn compute_with_outputs_and_no_predecessors_publishes_on_finish() { + let contexts = FenceContexts::new(1, c_str!("asahi_q_comp_pub"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let empty = frontier([]); + let plan = EnqueueOrdering::build( + &empty, + &empty, + Order { + sequence: 1, + wait_through: [None, None], + tiling_wait_through: [None, None], + }, + Engine::Compute, + false, + false, + ) + .unwrap(); + assert!(plan.predecessors.is_empty()); + assert!(plan.host_waits.is_empty()); + assert!(plan.firmware_waits.is_empty()); + + let (host_output, completed) = crate::g17::completion::HostOutput::test_pair( + &contexts, + &status, + !plan.predecessors.is_empty(), + true, + ) + .unwrap(); + let publication = host_output + .publication() + .expect("compute with outputs uses ordered publication"); + PreparedPublication::new(publication, plan.predecessors.iter().copied()) + .unwrap() + .activate(); + + // Activation clears the sentinel with no predecessors, but does not + // signal until the command finishes. + assert_eq!(fence_status(&completed), 0); + + // Finishing publishes synchronously with no extra delay. + host_output.finish(Ok([1, 2, 0, 0]), &status); + assert!(fence_status(&completed) > 0); + } + + #[test] + fn no_query_access_compute_behind_render_chains_ordered_publication() { + let none = frontier([]); + let contexts = FenceContexts::new(1, c_str!("asahi_q_comp_chain"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let (rend_a, pub_a) = test_entry(&contexts, &status, Some(true)); + let pub_a = pub_a.unwrap(); + PreparedPublication::new(pub_a.clone(), core::iter::empty()) + .unwrap() + .activate(); + let rend_a_scheduled = rend_a.scheduled.raw(); + let rend_a_completed = rend_a.completed.raw(); + let render_frontier = frontier([(1, rend_a)]); + + // NO_QUERY_ACCESS compute with no timestamp outputs behind Render A: + // waits in firmware on A's scheduled fence and chains ordered publication. + let plan_b = EnqueueOrdering::build( + &none, + &render_frontier, + Order { + sequence: 1, + wait_through: [Some(1), None], + tiling_wait_through: [None, None], + }, + Engine::Compute, + false, + false, + ) + .unwrap(); + assert!(plan_b.host_waits.is_empty()); + assert_eq!(plan_b.firmware_waits.len(), 1); + assert_eq!(plan_b.firmware_waits[0].0.raw(), rend_a_scheduled); + assert_eq!(plan_b.firmware_waits[0].1.raw(), rend_a_completed); + assert_eq!(plan_b.predecessors.len(), 1); + + let (host_output_b, comp_b_completed) = crate::g17::completion::HostOutput::test_pair( + &contexts, + &status, + !plan_b.predecessors.is_empty(), + false, + ) + .unwrap(); + let pub_b = host_output_b + .publication() + .expect("compute consumer behind publication uses ordered publication"); + PreparedPublication::new(pub_b, plan_b.predecessors.iter().copied()) + .unwrap() + .activate(); + + // Compute B finishes first, but its completion stays pending until Render A publishes. + host_output_b.finish(Ok([3, 4, 0, 0]), &status); + assert_eq!(fence_status(&comp_b_completed), 0); + + pub_a.finish(Ok([1, 2, 0, 0])); + assert!(fence_status(&comp_b_completed) > 0); + } +} diff --git a/drivers/gpu/drm/asahi/g17/queue/outstanding.rs b/drivers/gpu/drm/asahi/g17/queue/outstanding.rs new file mode 100644 index 00000000000000..87bc1454699b01 --- /dev/null +++ b/drivers/gpu/drm/asahi/g17/queue/outstanding.rs @@ -0,0 +1,412 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! One engine's accepted commands that have not finished, oldest first. +//! +//! Commands mostly finish in order, so a prune takes finished entries from the front and stops at +//! the first unfinished one: it costs what it removes, not the length of the list. An entry that +//! finishes behind an older unfinished one stays until it reaches the front or a full scan, and +//! every reader skips it by its status. While it stays it keeps its command's resources, such as +//! a compute command's timestamp page, so a full scan also runs once there have been as many +//! prunes as entries were held after the last one. That target is fixed at each scan, as a stuck +//! front with one new entry per prune would otherwise keep the length ahead of the count. It +//! costs at most two more status reads per prune, amortized, and nothing finished waits longer +//! than one queue length of submissions. +//! +//! A failure must not wait at all, because later commands whose prefix covers it are cancelled: +//! a prune is given its VM's failure counts and scans the whole list from when a failure starts +//! until it has finished and one scan has run after that. + +use crate::g17::{ + dependency::{FailureRecord, Retention}, + job::Order, + status::Failures, +}; +use kernel::prelude::*; + +/// Prunes an engine's frontier and its list of publishers, a subset of it, with the same counts. +/// Each entry that leaves either list goes to `record` and then to `finished`. A publisher can +/// leave its own list while the frontier still holds it behind an older unfinished command, and +/// the readers of that list would then not see its failure, so it is recorded wherever it leaves. +/// One that leaves both lists is recorded twice until it retires. +pub(crate) fn prune_engine( + frontier: &mut Outstanding, + publishers: &mut Outstanding, + failures: Failures, + record: &mut FailureRecord, + finished: &mut KVVec, +) { + let mut left = |sequence, status, entry: T| { + record.note(sequence, status, &entry); + // Without room the entry is released here, as it always could be. + let _ = finished.push(entry, GFP_KERNEL_ACCOUNT); + }; + frontier.prune(failures, &mut left); + publishers.prune(failures, &mut left); +} + +/// A command's completion status, as `dma_fence_get_status()`: 0 while unfinished, then 1 or +/// a negative error. +pub(crate) trait Status { + fn status(&self) -> i32; +} + +pub(crate) struct Outstanding { + /// Entries before `head` have left the front and hold nothing. Every entry from `head` + /// on holds its command. It needs no contiguous pages, and its growth must not fail a + /// submit on fragmentation. + entries: KVVec<(u64, Option)>, + head: usize, + /// [`Failures::finished`] at the last full scan. + failures: u64, + /// Front-only prunes left before the next full scan: the length after the last one. + scan_in: usize, +} + +impl Outstanding { + /// `failures`: the VM's [`Failures::finished`] now. + pub(crate) const fn new(failures: u64) -> Self { + Self { + entries: KVVec::new(), + head: 0, + failures, + scan_in: 0, + } + } + + /// The entries still held. Some may have finished since the last prune. + pub(crate) fn len(&self) -> usize { + self.entries.len() - self.head + } + + /// The entries still held, oldest first. + pub(crate) fn iter(&self) -> impl Iterator + Clone { + Self::held(&self.entries[self.head..]) + } + + /// The entries still held whose sequence `prefix` covers ([`Order::contains`]). + pub(crate) fn prefix(&self, prefix: Option) -> impl Iterator + Clone { + let held = &self.entries[self.head..]; + // Accepted sequences increase from one, so the entries a prefix covers come first. + let end = held.partition_point(|(sequence, _)| Order::contains(prefix, *sequence)); + Self::held(&held[..end]) + } + + fn held(entries: &[(u64, Option)]) -> impl Iterator + Clone { + entries + .iter() + .filter_map(|(sequence, entry)| Some((*sequence, entry.as_ref()?))) + } + + /// Userspace sets how many commands are outstanding, so their room is charged to it. + pub(crate) fn reserve(&mut self, additional: usize) -> Result { + // Reuse the room in front instead of growing past it, once moving the held entries + // down costs at most two moves for each entry that left since the last move. + if self.entries.capacity() - self.entries.len() < additional && 2 * self.head >= self.len() + { + drop(self.entries.drain(..self.head)); + self.head = 0; + } + Ok(self.entries.reserve(additional, GFP_KERNEL_ACCOUNT)?) + } + + pub(crate) fn push_within_capacity(&mut self, sequence: u64, entry: T) -> Result { + self.entries + .push_within_capacity((sequence, Some(entry))) + .map_err(|_| ENOMEM) + } + + /// Removes finished entries and hands each to `finished` with its status, oldest first. + /// While no failure has started since the last full scan, only entries in front of the + /// oldest unfinished one leave, until there have been as many prunes as entries were held + /// after the last full scan. + pub(crate) fn prune(&mut self, failures: Failures, mut finished: impl FnMut(u64, i32, T)) { + if failures.started != self.failures || self.scan_in == 0 { + // Only a finished failure is sure to be seen by this scan. One still being signalled + // keeps `started` ahead, so the scans stay full until it has finished. + self.failures = failures.finished; + self.entries.retain(|(sequence, entry)| { + let Some(status) = entry.as_ref().map(Status::status) else { + return false; + }; + if status == 0 { + return true; + } + if let Some(entry) = entry.take() { + finished(*sequence, status, entry); + } + false + }); + self.head = 0; + self.scan_in = self.len(); + return; + } + self.scan_in -= 1; + while let Some((sequence, entry)) = self.entries.get_mut(self.head) { + let Some(status) = entry.as_ref().map(Status::status) else { + break; + }; + if status == 0 { + break; + } + if let Some(entry) = entry.take() { + finished(*sequence, status, entry); + } + self.head += 1; + } + } +} + +#[kunit_tests(asahi_g17_outstanding)] +mod tests { + use super::*; + use core::sync::atomic::{AtomicI32, AtomicUsize, Ordering}; + use kernel::sync::Arc; + + /// Status reads of every test command. KUnit runs a suite's cases one after another. + static READS: AtomicUsize = AtomicUsize::new(0); + + /// A command whose status the test sets. + #[derive(Clone)] + struct Command(Arc); + + impl Command { + fn new() -> Self { + Self(Arc::new(AtomicI32::new(0), GFP_KERNEL).unwrap()) + } + fn finish(&self, status: i32) { + self.0.store(status, Ordering::Relaxed); + } + } + + impl Retention for Command { + fn retained(&self) -> bool { + true + } + } + + impl Status for Command { + fn status(&self) -> i32 { + READS.fetch_add(1, Ordering::Relaxed); + self.0.load(Ordering::Relaxed) + } + } + + fn push(queue: &mut Outstanding, sequence: u64) -> Command { + let command = Command::new(); + queue.reserve(1).unwrap(); + queue + .push_within_capacity(sequence, command.clone()) + .unwrap(); + command + } + + fn queue(count: u64) -> (Outstanding, KVec) { + let mut queue = Outstanding::new(0); + let mut commands = KVec::new(); + for sequence in 1..=count { + let command = push(&mut queue, sequence); + commands.push(command, GFP_KERNEL).unwrap(); + } + // As a queue in use: every enqueue prunes before it pushes, so it has been scanned. + assert!(prune(&mut queue, 0).is_empty()); + (queue, commands) + } + + fn sequences<'a>(entries: impl Iterator) -> KVec { + let mut sequences = KVec::new(); + for (sequence, _) in entries { + sequences.push(sequence, GFP_KERNEL).unwrap(); + } + sequences + } + + /// A prune with `failures` failures started and finished. + fn prune(queue: &mut Outstanding, failures: u64) -> KVec<(u64, i32)> { + prune_counts(queue, failures, failures) + } + + fn prune_counts( + queue: &mut Outstanding, + started: u64, + finished: u64, + ) -> KVec<(u64, i32)> { + let mut left = KVec::new(); + queue.prune(Failures { started, finished }, |sequence, status, _| { + left.push((sequence, status), GFP_KERNEL).unwrap() + }); + left + } + + #[test] + fn finished_commands_leave_from_the_front_in_order() { + let (mut queue, commands) = queue(4); + commands[0].finish(1); + commands[1].finish(EIO.to_errno()); + assert_eq!(prune(&mut queue, 0), [(1u64, 1i32), (2, EIO.to_errno())]); + assert_eq!(sequences(queue.iter()), [3u64, 4]); + assert_eq!(queue.len(), 2); + assert!(prune(&mut queue, 0).is_empty()); + } + + #[test] + fn a_command_finished_behind_an_unfinished_one_waits_for_the_front() { + let (mut queue, commands) = queue(3); + commands[1].finish(1); + assert!(prune(&mut queue, 0).is_empty()); + assert_eq!(sequences(queue.iter()), [1u64, 2, 3]); + commands[0].finish(1); + assert_eq!(prune(&mut queue, 0), [(1u64, 1i32), (2, 1)]); + assert_eq!(sequences(queue.iter()), [3u64]); + } + + #[test] + fn a_command_finished_behind_an_unfinished_one_leaves_within_a_queue_length() { + let (mut queue, commands) = queue(4); + commands[2].finish(1); + let mut prunes = 0; + while prune(&mut queue, 0).is_empty() { + prunes += 1; + assert!(prunes <= 4); + } + assert_eq!(sequences(queue.iter()), [1u64, 2, 4]); + } + + #[test] + fn a_stuck_front_does_not_hold_finished_commands_past_a_queue_length() { + let (mut queue, commands) = queue(4); + commands[1].finish(1); + commands[2].finish(1); + commands[3].finish(1); + // Command 1 never finishes, and each prune comes with a new unfinished command, as a + // long command at the front of a busy queue. + let mut left = KVec::new(); + let mut prunes = 0; + for sequence in 5..=16u64 { + prunes += 1; + for (sequence, _) in prune(&mut queue, 0) { + left.push(sequence, GFP_KERNEL).unwrap(); + } + push(&mut queue, sequence); + if !left.is_empty() { + break; + } + } + // The 4 held at the last scan, then the scan itself. + assert_eq!(left, [2u64, 3, 4]); + assert_eq!(prunes, 4 + 1); + } + + #[test] + fn a_publisher_that_fails_behind_an_unfinished_command_is_recorded() { + // Command 1 is unfinished; command 2 publishes timestamps, so both lists hold it. + let (mut frontier, commands) = queue(2); + let mut publishers = Outstanding::new(0); + publishers.reserve(1).unwrap(); + publishers + .push_within_capacity(2, commands[1].clone()) + .unwrap(); + let mut record = FailureRecord::new(); + let mut finished = KVVec::new(); + let counts = Failures { + started: 0, + finished: 0, + }; + prune_engine( + &mut frontier, + &mut publishers, + counts, + &mut record, + &mut finished, + ); + // Command 2 fails after this prune read the counts, so they have not moved: the + // frontier keeps it behind command 1 and its own list lets it go first. + commands[1].finish(EIO.to_errno()); + prune_engine( + &mut frontier, + &mut publishers, + counts, + &mut record, + &mut finished, + ); + assert_eq!(sequences(frontier.iter()), [1u64, 2]); + assert!(publishers.iter().next().is_none()); + assert_eq!(record.earliest().map(|(sequence, _)| sequence), Some(2)); + } + + #[test] + fn a_moved_failure_count_scans_the_whole_queue() { + let (mut queue, commands) = queue(5); + commands[0].finish(1); + assert_eq!(prune(&mut queue, 0), [(1u64, 1i32)]); + commands[2].finish(ECANCELED.to_errno()); + commands[4].finish(1); + assert_eq!(prune(&mut queue, 1), [(3u64, ECANCELED.to_errno()), (5, 1)]); + assert_eq!(sequences(queue.iter()), [2u64, 4]); + commands[1].finish(1); + commands[3].finish(1); + assert_eq!(prune(&mut queue, 1), [(2u64, 1i32), (4, 1)]); + assert_eq!(queue.len(), 0); + } + + #[test] + fn a_failure_behind_an_unfinished_command_leaves_once_counted() { + let (mut queue, commands) = queue(3); + commands[1].finish(EIO.to_errno()); + // Not counted yet: like a success, it waits for the front. + assert!(prune(&mut queue, 0).is_empty()); + assert_eq!(prune(&mut queue, 1), [(2u64, EIO.to_errno())]); + // Only the prune that saw the count move looks behind the front. + commands[2].finish(1); + assert!(prune(&mut queue, 1).is_empty()); + assert_eq!(sequences(queue.iter()), [1u64, 3]); + } + + #[test] + fn a_failure_being_signalled_keeps_prunes_full_until_it_has_finished() { + let (mut queue, commands) = queue(4); + // Started, but its error is not visible yet. + assert!(prune_counts(&mut queue, 1, 0).is_empty()); + // Visible but not finished: the prune must still look behind the front for it. + commands[1].finish(EIO.to_errno()); + assert_eq!(prune_counts(&mut queue, 1, 0), [(2u64, EIO.to_errno())]); + // Its finish is scanned for once more, then prunes go back to the front. + commands[2].finish(1); + assert_eq!(prune_counts(&mut queue, 1, 1), [(3u64, 1i32)]); + commands[3].finish(1); + assert!(prune_counts(&mut queue, 1, 1).is_empty()); + assert_eq!(sequences(queue.iter()), [1u64, 4]); + } + + #[test] + fn a_prefix_covers_the_oldest_held_commands() { + let (mut queue, commands) = queue(4); + commands[0].finish(1); + prune(&mut queue, 0); + assert!(sequences(queue.prefix(None)).is_empty()); + assert!(sequences(queue.prefix(Some(1))).is_empty()); + assert_eq!(sequences(queue.prefix(Some(3))), [2u64, 3]); + assert_eq!(sequences(queue.prefix(Some(9))), [2u64, 3, 4]); + } + + #[test] + fn a_deep_steady_queue_reads_a_few_entries_per_prune_and_never_grows() { + // Commands queued deep, then one finishing for each new one, as under vkd3d-proton. + // A little over half of the room is held: moving down only once as many have left + // as are held would double it. + const DEPTH: u64 = 1100; + let (mut queue, mut commands) = queue(DEPTH); + let capacity = queue.entries.capacity(); + READS.store(0, Ordering::Relaxed); + for sequence in DEPTH + 1..=10 * DEPTH { + commands[(sequence - DEPTH - 1) as usize].finish(1); + assert_eq!(prune(&mut queue, 0), [(sequence - DEPTH, 1i32)]); + let command = push(&mut queue, sequence); + commands.push(command, GFP_KERNEL).unwrap(); + assert_eq!(queue.len(), DEPTH as usize); + assert_eq!(queue.entries.capacity(), capacity); + } + // Each prune read the one that left and the unfinished one behind it, and once per + // queue length a full scan read them all. + assert!(READS.load(Ordering::Relaxed) <= 3 * 9 * DEPTH as usize); + } +} diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 64d3f50a5df9d6..27dbcaab8ce7ec 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -53,8 +53,10 @@ pub(crate) struct RenderDependencies { pub(crate) render_tiling_count: usize, pub(crate) tiling: [KickDependency; 2], pub(crate) tiling_count: usize, - pub(crate) compute: Option, - pub(crate) fragment_compute: Option, + pub(crate) compute: [KickDependency; crate::g17::pairs::COMPUTE_CHANNELS_MAX], + pub(crate) compute_count: usize, + pub(crate) fragment_compute: [KickDependency; crate::g17::pairs::COMPUTE_CHANNELS_MAX], + pub(crate) fragment_compute_count: usize, /// Fragment kicks of other pairs' overlapping same-VM renders. pub(crate) hazards: [KickDependency; crate::g17::hazard::PUBLICATION_BARRIERS], pub(crate) hazard_count: usize, @@ -68,8 +70,10 @@ impl RenderDependencies { render_tiling_count: 0, tiling: [KickDependency::ZERO; 2], tiling_count: 0, - compute: None, - fragment_compute: None, + compute: [KickDependency::ZERO; crate::g17::pairs::COMPUTE_CHANNELS_MAX], + compute_count: 0, + fragment_compute: [KickDependency::ZERO; crate::g17::pairs::COMPUTE_CHANNELS_MAX], + fragment_compute_count: 0, hazards: [KickDependency::ZERO; crate::g17::hazard::PUBLICATION_BARRIERS], hazard_count: 0, }; @@ -206,6 +210,11 @@ pub(crate) struct Pair { /// acknowledgement: the pair keeps its owner and graph until then. channel_error: bool, kick_aliases: Option<[Option; 2]>, + /// The read-only views of the two kick rings in the VM of the pair's contexts, installed with + /// its first graph in that VM. They belong to the pair's time in that VM, not to the VM: they + /// go before the pair runs a context of another VM, so its previous owner cannot read the + /// new owner's kick entries. Dropped before `kicks`. + client_kicks: [Option; 2], memory: KBox, kicks: [kick::Queue; 2], free_list: Arc, @@ -232,6 +241,14 @@ pub(crate) struct Pair { /// Bit `p` set once a work slot of priority class `p` named the pair. outer_started: u8, quarantined: bool, + /// Its groups were released on the guilty proof after its context's kill + /// (`Pair::guilty_killed`): the firmware may never consume the ring entries of the groups + /// the kill unlinked, so the pair is released and detached on that proof + /// (`counts_idle`, `Pair::can_keep`), never parked for reuse while those entries remain. + guilty_released: bool, + /// The recovery generation of the first restart that blamed this pair's spared work as + /// collateral, until a group of it retires (`recovery::Queues::note_collateral`). + collateral_at: Option, terminal: Option<(Arc, Error)>, previous: Option, displaced: Option, @@ -342,7 +359,8 @@ impl Pair { if word == u32::MAX { return Err(EINVAL); } - let layout = m5_render_submission::layout(&first.command, clusters, variant.programs)?; + let layout = + m5_render_submission::layout(&first.command, clusters, variant.programs, board)?; let storage = KBox::::new_uninit(GFP_KERNEL)?; let (tiling, ta_alias) = kick::Queue::render(alloc, ids[0], context.vm(), rings)?; let (fragment, fragment_alias) = kick::Queue::render(alloc, ids[1], context.vm(), rings)?; @@ -363,6 +381,7 @@ impl Pair { storage.write_init(kernel::try_init!(Self { pool_pin, kick_aliases: Some([ta_alias, fragment_alias]), + client_kicks: [None, None], memory, kicks: [tiling, fragment], free_list, @@ -386,6 +405,8 @@ impl Pair { registered: None, outer_started: 0, quarantined: false, + guilty_released: false, + collateral_at: None, terminal: None, previous: None, displaced: None, @@ -533,7 +554,8 @@ impl Pair { let node = work.node_va()?; let word = work.word(); let layout = - m5_render_submission::layout(&packet.command, self.clusters, self.variant.programs)?; + m5_render_submission::layout(&packet.command, self.clusters, self.variant.programs, + self.board)?; let deflake_layout = self.deflake; let owners = self.memory.owners(); self.memory @@ -612,6 +634,7 @@ impl Pair { }, programs: self.variant.programs, ta_mode_1: self.variant.ta_mode_1, + clusters: self.clusters, deflake: deflake_layout, }; self.memory.graph.claim(ordinal)?; @@ -664,12 +687,14 @@ impl Pair { /// 1 the tiling encoder, 2 a full channel or compute completion, 3 the /// fragment encoder; the last class is the implicit parent's. struct RenderBarriers { - tiling: [KickDependency; 5], + tiling: [KickDependency; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX], tiling_count: usize, - fragment: [KickDependency; 4 + crate::g17::hazard::PUBLICATION_BARRIERS], + fragment: [KickDependency; + 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], fragment_count: usize, - tiling_types: [u8; 6], - fragment_types: [u8; 5 + crate::g17::hazard::PUBLICATION_BARRIERS], + tiling_types: [u8; 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX], + fragment_types: [u8; + 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], } /// The last fragment kick published on any pair, and the last one of a render with an API task @@ -736,12 +761,14 @@ fn render_barriers( compute_class: u8, ) -> RenderBarriers { let fragment_stage = fragment_stage || stage_prefixes; - let mut tiling_barriers = [KickDependency::ZERO; 5]; + let mut tiling_barriers = [KickDependency::ZERO; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX]; let mut tiling_count = 0; - let mut fragment_barriers = [own_tiling; 4 + crate::g17::hazard::PUBLICATION_BARRIERS]; + let mut fragment_barriers = [own_tiling; + 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; let mut fragment_count = 1; - let mut tiling_types = [1; 6]; - let mut fragment_types = [3; 5 + crate::g17::hazard::PUBLICATION_BARRIERS]; + let mut tiling_types = [1; 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX]; + let mut fragment_types = + [3; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; fragment_types[0] = 1; for dependency in &dependencies.render_tiling[..dependencies.render_tiling_count] { tiling_barriers[tiling_count] = *dependency; @@ -771,13 +798,13 @@ fn render_barriers( } } } - if let Some(compute) = dependencies.compute { - tiling_barriers[tiling_count] = compute; + for compute in &dependencies.compute[..dependencies.compute_count] { + tiling_barriers[tiling_count] = *compute; tiling_types[tiling_count] = compute_class; tiling_count += 1; } - if let Some(compute) = dependencies.fragment_compute { - fragment_barriers[fragment_count] = compute; + for compute in &dependencies.fragment_compute[..dependencies.fragment_compute_count] { + fragment_barriers[fragment_count] = *compute; fragment_types[fragment_count] = compute_class; fragment_count += 1; } @@ -968,6 +995,8 @@ impl Pair { // The J813's (common 26A428) items carry configuration, descriptor and announcement in // one publication; macOS 27.0 never publishes a configuration alone there. let j813 = crate::g17::J813_FORMS.load(Ordering::Relaxed); + let host_only_render_kicks = + m5 && !j813 && self.board.is_some_and(|board| board.host_only_render_kicks); if m5 && !j813 && self.registered.is_none() { if self.installed == [true; 2] { // The cold-install configuration pair must be consumed first. @@ -1095,9 +1124,8 @@ impl Pair { }, }, mcache, - // M5 tiling kicks also retain the last event of the mask, except on the J813, whose - // macOS 27.0 TA and 3D kicks name no event at all. - event_mask: if m5 && stage == 0 && !j813 { + // Common 26A428 and the host-only form use an empty tiling event mask. + event_mask: if m5 && stage == 0 && !j813 && !host_only_render_kicks { [0, 0, 0, 1u64 << 62] } else { abi::RENDER_KICK_EVENT_MASK @@ -1154,6 +1182,16 @@ impl Pair { let tiling_kick = tiling_kick.prepare_entry(&ta_args)?; let fragment_kick = fragment_kick.prepare_entry(&fragment_args)?; let memory = &mut *self.memory; + // For a firmware that supports host-only kicks, an installed render + // pair with work in flight can use the host-port kick alone: + // another item-ring notification has no new configuration or lead + // command to publish. Keep the ordinary inner publication for the + // first command, a drained restart, a rebind, and a class change. + let sparse_inner = host_only_render_kicks + && self.active.front().is_some() && self.previous.is_none() + && self.registered == Some(policy.priority()) && !self.context_update + && !self.identity_update && !present.into_iter().any(|value| value) + && !leads.into_iter().any(|value| value); let lanes = [ publication::Lane::new( &memory.graph, @@ -1164,6 +1202,7 @@ impl Pair { present[0], kicks[0], leads[0], + sparse_inner, )?, publication::Lane::new( &memory.graph, @@ -1174,6 +1213,7 @@ impl Pair { present[1], kicks[1], leads[1], + sparse_inner, )?, ]; let windows = [lanes[0].window, lanes[1].window]; @@ -1397,6 +1437,7 @@ impl Pair { true, kicks[0], false, + false, )?, publication::Lane::new( &self.memory.graph, @@ -1407,6 +1448,7 @@ impl Pair { true, kicks[1], false, + false, )?, ]; let ends = self.cursors.map(|base| (base + 1) % ITEM_RING_ENTRIES); @@ -1809,7 +1851,8 @@ impl Pair { /// keeps its current capacity and lets firmware request growth as needed. pub(crate) fn host_growth_target(&mut self, packet: &Packet) -> Result> { let mut required = - m5_render_submission::layout(&packet.command, self.clusters, self.variant.programs)? + m5_render_submission::layout(&packet.command, self.clusters, self.variant.programs, + self.board)? .tvb_blocks; // A mesh workgroup whose output is in flight when the tiler heap runs out loses part of // it, whether the firmware then grows the heap or partial-renders, and the tile-count @@ -1953,6 +1996,14 @@ impl Pair { } } + /// A restart before `generation` blamed this pair's spared work as collateral, and none of + /// it retired since. + pub(crate) fn collateral_before(&self, generation: u64) -> bool { + self.collateral_at.is_some_and(|at| at < generation) + } + pub(crate) fn note_collateral(&mut self, generation: u64) { + self.collateral_at.get_or_insert(generation); + } pub(crate) fn oldest_spared(&self) -> Option { self.active .front() @@ -1985,6 +2036,12 @@ impl Pair { visit(active.packet.completion.status()); } } + /// The context ID (UAT slot) of every in-flight packet. + pub(crate) fn visit_contexts(&self, visit: &mut dyn FnMut(u32)) { + for active in self.active.iter() { + visit(active.packet.context.id()); + } + } pub(crate) fn classify(&self, classify: &dyn Fn(&Arc) -> recovery::Class) { for active in self.active.iter() { active @@ -2010,10 +2067,10 @@ impl Pair { Some(observation::snapshot(&self.memory, front.ticket.ordinal).ok()?.untouched()) } - /// The owner of a published group whose tiler started and whose fragment end is unwritten. - /// Groups an earlier recovery listed or blamed are skipped: a restart drops started groups, - /// so their records stay half-written without anything running. - pub(crate) fn running_owner(&self) -> Option<&Arc> { + /// A published group whose tiler started and whose fragment end is unwritten, with its pass + /// record. Groups an earlier recovery listed or blamed are skipped: a restart drops started + /// groups, so their records stay half-written without anything running. + fn running(&self) -> Option<(&Active, [u64; 2])> { self.active .iter() .filter(|active| { @@ -2021,11 +2078,15 @@ impl Pair { && !active.packet.completion.interrupted() && !active.packet.completion.blamed() }) - .find(|active| { - observation::snapshot(&self.memory, active.ticket.ordinal) - .is_ok_and(|snapshot| snapshot.pass[0] != 0 && snapshot.pass[1] == 0) + .find_map(|active| { + let pass = observation::snapshot(&self.memory, active.ticket.ordinal).ok()?.pass; + (pass[0] != 0 && pass[1] == 0).then_some((active, pass)) }) - .map(|active| active.packet.completion.status()) + } + + /// The owner of the `running` group and its tiler start, read while firmware is halted. + pub(crate) fn running_start(&self) -> Option<(&Arc, u64)> { + self.running().map(|(active, pass)| (active.packet.completion.status(), pass[0])) } /// Firmware is halted and all graph borrowers have joined before this copy. @@ -2059,6 +2120,11 @@ impl Pair { error: Error, defer: &mut impl FnMut(Deferred) -> Result, ) -> Result { + // A killed guilty pair released on its proof holds no groups and only waits for its + // detach: quarantined again (another queue of its VM failed), it could never park. + if self.guilty_released { + return Ok(()); + } self.quarantined = true; // Its groups end here, without their own watchdogs: none of their fragment kicks may hold // the task-stage order of other clients. @@ -2226,6 +2292,8 @@ impl Pair { retirement::note_stampless(u16::from(self.slot), ordinal); } self.note_retirement(ordinal, context_update); + // Work of this pair retires: a later blame on it is collateral again. + self.collateral_at = None; let front = self.active.front_mut().ok_or(EIO)?; if !front.flist_completed { host.complete_render( @@ -2635,9 +2703,22 @@ impl Pair { } let counters = self.free_list.counters()?; let stamps = host.stamps(self.qids())?; - let (_, state) = host.epoch()?; + let (generation, state) = host.epoch()?; Ok(retirement::drained(self.ordinal, stamps, counters, state) - || (state == 0 && self.executed_unstamped() && self.context_killed())) + || (state == 0 && self.executed_unstamped() && self.context_killed()) + || self.guilty_killed(generation, state)) + } + + /// The pair's groups of a guilty context may go although they never retired: the firmware + /// finished the context's kill, and a GPU restart it raised after that has completed + /// (`state` 0). The kill unlinks the context's work list, but a group that was running at + /// the kill keeps running until a restart drops it, and only then is none of its memory + /// reachable. The pair itself, its ring and the context's work list stay held until the + /// context's scheduler release is consumed (detach, `release_killed_slots`). + fn guilty_killed(&self, generation: u64, state: u32) -> bool { + guilty_kill_done(self.guilty_unretired(generation), state, || { + self.memory.context.restarted_since_kill(self.context_killed(), generation) + }) } /// The firmware acknowledged a kill of this pair's context (scheduler page): it no longer @@ -2654,6 +2735,49 @@ impl Pair { Arc::ptr_eq(context, &self.memory.context) && self.executed_unstamped() } + /// A kill of the pair's context releases it with work that never retired: its commands all + /// ran unstamped (`executed_unstamped`), or a recovery found its VM guilty + /// (`guilty_unretired`). Its memory stays until the kill is done (`firmware_drained`). + pub(crate) fn releasable_by_kill(&self, context: &Arc, generation: u64) -> bool { + self.executed_for_kill(context) || self.guilty_for_kill(context, generation) + } + + /// The pair's context may be killed although its queued groups did not run: a recovery + /// found its VM guilty (`guilty_unretired`). + pub(crate) fn guilty_for_kill(&self, context: &Arc, generation: u64) -> bool { + Arc::ptr_eq(context, &self.memory.context) && self.guilty_unretired(generation) + } + + /// A GPU recovery failed the pair's VM as guilty (its status records the failure, so every + /// later submission and publication of it is refused) and quarantined the pair. Not on M5. + pub(crate) fn failed_guilty(&self) -> bool { + let status = self.memory.context.status(); + !self.memory.graph.is_m5() && self.quarantined && status.recovery_guilty() && status.get() != 0 + } + + /// A closed owner's quarantined pair holding published work of a VM that a GPU recovery + /// found guilty. Its started group hangs the GPU again after every restart, with its queued + /// groups behind it, so its work never retires like other work: on 25G83 the host cannot + /// take published groups back, and only a kill of the context unlinks them. Left alone, + /// the restarts reach the storm limit and every client loses the device (11-19 19:12 UTC). + /// + /// Only once the host accepted a restart (`generation`) since the context's first close: + /// the VM stays guilty, and a failed VM's pairs are all quarantined, but its groups queued + /// behind the one that hung may run and retire on their stamps. A kill then would unlink + /// those with nothing left to hang and so no restart to release them. A guilty group still + /// running hangs the GPU again within about 83 ms, which costs at most that one restart. + /// Not on M5, which takes published work back through its recovery target. + fn guilty_unretired(&self, generation: u64) -> bool { + !self.memory.graph.is_m5() + && self.memory.context.restarted_since_close(generation) + && self.quarantined + && self.owner.is_none() + && self.prepared.is_none() + && self.active.len() != 0 + && self.active.iter().all(|active| active.outer_published) + && self.memory.context.status().recovery_guilty() + } + /// Every command of this quarantined pair ran, its ring entries were consumed and its /// free-list blocks returned, yet the firmware never stores the stamp of the last one. /// On Neo this is the render work of a context whose compute command failed: it runs @@ -2693,7 +2817,8 @@ impl Pair { // Commands the firmware never unlinked are released only after it acknowledged the // kill of their context, on every path (see `firmware_drained`). let unstamped = self.executed_unstamped(); - let killed = unstamped && self.context_killed(); + let (generation, state) = host.epoch()?; + let killed = (unstamped && self.context_killed()) || self.guilty_killed(generation, state); let Some(active) = self.active.iter_mut().find(|a| !a.flist_completed) else { return Ok(false); }; @@ -2704,8 +2829,9 @@ impl Pair { }; let result = match retirement::poll(&mut active.ticket, &mut observer)? { retirement::Poll::Complete(ticks) => Ok(ticks), - // Its commands ran without a stamp (see `executed_unstamped`): they already failed - // with the quarantine, and the client sees them cancelled. + // Its commands ran without a stamp (see `executed_unstamped`), or its guilty context + // was killed (`guilty_killed`): they already failed with the quarantine, and the + // client sees them cancelled. retirement::Poll::Pending | retirement::Poll::Retry if killed => { crate::g17::trace::teardown(2, u64::from(self.slot), active.ticket.ordinal, 0); Err(ECANCELED) @@ -2752,6 +2878,12 @@ impl Pair { if self.active.iter().any(|a| !a.flist_completed) || !self.firmware_drained(host)? { return Ok(false); } + let (generation, state) = host.epoch()?; + let guilty = self.guilty_killed(generation, state); + if guilty { + pr_warn!("G17: render slot {}: {} groups of a killed guilty context released after a later restart (gen {})\n", + self.slot, self.active.len(), generation); + } while let Some(active) = self.active.front() { // A group retired on its pass record was reported then (`stamps_owed`): the pair-wide // proof above covers its stamps too (or the kill of its context), so only its @@ -2765,12 +2897,27 @@ impl Pair { self.active.pop().ok_or(EIO)?; } self.quarantined = false; + self.guilty_released |= guilty; self.drain_failures = 0; self.drain_retry_at = 0; self.resync(); Ok(true) } + /// While the firmware is halted for a restart: a finished kill of this pair's context + /// counts as seen done at `generation`, the one before that restart, at the latest. + pub(crate) fn note_kill_sighting(&self, generation: u64) { + let context = &self.memory.context; + if context.kill_published() { + context.restarted_since_kill(self.context_killed(), generation); + } + } + + /// See the `guilty_released` field. + pub(crate) fn guilty_released(&self) -> bool { + self.guilty_released + } + /// The registry first polls the completed prefix through this exact Arc. /// With successors, source policy quarantines every remaining group. A /// single unexecuted group may use the strict ownership witness instead. @@ -2920,10 +3067,13 @@ impl Pair { &mut self.memory, &mut self.pending_aliases, &mut self.kick_aliases, + &mut self.client_kicks, ) } } +/// Installs a graph's memory. The new kick ring views in `kick_aliases` go to `views`, the +/// pair's views in the graph's VM ([`Pair::client_kicks`]). fn install_memory( alloc: &Allocator<'_>, descriptors: &crate::g17::object::KernelObject, @@ -2931,6 +3081,7 @@ fn install_memory( memory: &mut memory::Memory, pending_aliases: &mut Option>, kick_aliases: &mut Option<[Option; 2]>, + views: &mut [Option; 2], ) -> Result { use core::sync::atomic::{fence, Ordering}; if pending_aliases.is_none() && kick_aliases.is_none() { @@ -2939,8 +3090,6 @@ fn install_memory( if !memory.context.is_current() || kick_aliases.is_none() { return Err(EIO); } - let mut driver = KVec::new(); - driver.reserve(2, GFP_KERNEL)?; let aliases = memory.take_persistent(pending_aliases.as_mut().ok_or(EIO)?)?; let context = memory.context.clone(); let vm = context.vm(); @@ -2969,10 +3118,11 @@ fn install_memory( } fence(Ordering::SeqCst); staged = Some(previous); - for mapping in kick_aliases.take().ok_or(EIO)?.into_iter().flatten() { - driver.push(mapping, GFP_KERNEL)?; + for (view, alias) in views.iter_mut().zip(kick_aliases.take().ok_or(EIO)?) { + if alias.is_some() { + *view = alias; + } } - vm.append_driver_mappings(driver)?; Ok(()) })(); if let Err(error) = result { @@ -3014,6 +3164,10 @@ pub(crate) struct PreparedBinding { /// The registry retains displaced backing until this exact context's release /// is acknowledged. A warm binding retains the old context without its graph. pub(crate) struct RetiredBinding { + /// Views of the kick rings in `context`'s VM that a pair parked after the VM's client + /// closed it gave up (`Pair::park`). Only held: declared first, they drop before the + /// memory and the context below. + _client_kicks: [Option; 2], memory: Option>, context: Arc, pool: Arc, @@ -3055,6 +3209,9 @@ impl Pair { } } } + pub(crate) fn graph_started(&self) -> bool { + self.graph_started + } pub(crate) fn forget_registration(&mut self) { self.registered = None; } @@ -3168,17 +3325,21 @@ impl Pair { .into_iter() .all(|c| c.done == c.read && c.read == c.write)) } - pub(crate) fn reusable(&self) -> Result { + /// Idle, drained, and free of pending retirement or channel errors so a + /// live owner's sibling can be detached or a closed owner's pair reused. + pub(crate) fn detachable(&self) -> Result { let previous_ready = self .previous .as_ref() .is_none_or(|p| p.memory.is_none() && self.context_update && !p.ready); Ok(!self.channel_error - && self.owner.is_none() && self.displaced.is_none() && previous_ready && self.idle_for_context(self.context())?) } + pub(crate) fn reusable(&self) -> Result { + Ok(self.owner.is_none() && self.detachable()?) + } /// An M5 pool may be replaced without changing the pair's live logical /// owner. Commands already using the pair must drain, and an earlier /// replacement must have retired, unless nothing was published since it: @@ -3252,11 +3413,27 @@ impl Pair { let buffer_id = buffer_id.ok_or(EINVAL)?; let pm_generation = pm_generation.ok_or(EINVAL)?; let layout = - m5_render_submission::layout(&first.command, self.clusters, self.variant.programs)?; + m5_render_submission::layout(&first.command, self.clusters, self.variant.programs, + self.board)?; + // A context of another VM gets the rings cleared before its VM is given its view, + // so it cannot read the entries earlier owners' commands left, as for a parked pair. + // The pair is bindable, hence idle: the firmware consumed every entry. + let other_vm = self.context().vm().id() != context.vm().id(); + if other_vm { + for kick in &mut self.kicks { + kick.clear_render_ring()?; + } + } let aliases = [ self.kicks[0].prepare_client_alias(context.vm())?, self.kicks[1].prepare_client_alias(context.vm())?, ]; + // A view the VM already has is the one this pair holds for it. + for (alias, view) in aliases.iter().zip(&self.client_kicks) { + if alias.is_none() && (other_vm || view.is_none()) { + return Err(EFAULT); + } + } let (memory, persistent) = memory::Memory::new( alloc, pool, @@ -3313,6 +3490,7 @@ impl Pair { } else { None }; + let mut views = [None, None]; let installed = install_memory( alloc, descriptors, @@ -3320,6 +3498,7 @@ impl Pair { memory, &mut binding.aliases, &mut binding.kicks, + &mut views, ); if let Err(error) = installed { if let Some((slot, mappings)) = moved { @@ -3328,6 +3507,16 @@ impl Pair { return Err(error); } drop(moved); + // The previous VM's views go before the new owner's first kick entry is written. + if self.context().vm().id() != binding.context.vm().id() { + drop(core::mem::replace(&mut self.client_kicks, views)); + } else { + for (view, alias) in self.client_kicks.iter_mut().zip(views) { + if alias.is_some() { + *view = alias; + } + } + } } else { // The same logical context keeps its M5 queue records: their host // words already name it, and a rewrite would store firmware-owned @@ -3346,6 +3535,7 @@ impl Pair { .take() .map(|memory| core::mem::replace(&mut self.memory, memory)); let retired = RetiredBinding { + _client_kicks: [None, None], memory: old_memory, context: old_context, pool: old_pool, @@ -3360,6 +3550,9 @@ impl Pair { self.previous = Some(retired); } self.memory.context = binding.context.clone(); + // The pair is reused in place: the collateral mark of a previous owner, which may have + // closed without retiring anything, must not make the next owner's first blame its second. + self.collateral_at = rebound_collateral(self.collateral_at, self.owner == Some(binding.owner)); self.owner = Some(binding.owner); self.initial_packet = binding.initial_packet; if foreign { @@ -3455,6 +3648,39 @@ mod completion_noted_tests { } } +/// A pair's collateral mark (`Pair::collateral_at`) when it is bound to an owner: kept for the +/// same owner (a pool rebind), dropped for a new one. Not at the owner's close: an exited +/// culprit's spared work stays published, and dropping its mark then would cost a restart. +pub(crate) fn rebound_collateral(mark: Option, same_owner: bool) -> Option { + mark.filter(|_| same_owner) +} + +/// See `Pair::guilty_killed`: a guilty pair (`guilty`) goes only with no restart in progress +/// (`state` 0) and once `restarted` (`Context::restarted_since_kill`) holds. `restarted` is only +/// asked of a guilty pair with no restart in progress, so that its first sighting of the kill +/// is recorded at a settled generation. +fn guilty_kill_done(guilty: bool, state: u32, restarted: impl FnOnce() -> bool) -> bool { + guilty && state == 0 && restarted() +} + +#[kunit_tests(asahi_g17_render_guilty_kill)] +mod guilty_kill_tests { + use super::guilty_kill_done; + + #[test] + fn a_guilty_pair_goes_only_after_its_kill_and_a_later_restart() { + // Kill not acknowledged, or acknowledged with no restart since: held. + assert!(!guilty_kill_done(true, 0, || false)); + // A restart in progress: held, and the kill's sighting is not recorded mid-restart. + assert!(!guilty_kill_done(true, 1, || panic!("asked during a restart"))); + assert!(!guilty_kill_done(true, 3, || panic!("asked during a restart"))); + // Acknowledged, restarted since, restart complete: released. + assert!(guilty_kill_done(true, 0, || true)); + // Not a guilty pair: this proof never applies. + assert!(!guilty_kill_done(false, 0, || panic!("asked for an innocent pair"))); + } +} + #[kunit_tests(asahi_g17_render_drain_retry)] mod drain_retry_tests { use super::{drain_retry_delay, DRAIN_RETRY_LIMIT}; diff --git a/drivers/gpu/drm/asahi/g17/queue/render/generation.rs b/drivers/gpu/drm/asahi/g17/queue/render/generation.rs index 4ebe4220921c0b..b2848b35b418b9 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/generation.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/generation.rs @@ -4,7 +4,7 @@ //! their backing owners; a generation is reusable only after paired retirement. use crate::g17::{ - buffer::{self, BlockGeometry}, + buffer::{self, compact::PairObject}, fw::{ m5::{initdata::Board, render_registers::ContextStore}, render::{storage, RenderPass}, @@ -101,10 +101,10 @@ pub(in crate::g17) struct Generation { impl Generation { pub(in crate::g17) fn allocate_state(alloc: &Allocator<'_>, vm: &mmu::Vm, board: Option<&'static Board>) -> Result { - let (range, layout) = if alloc.uat.is_m5() { - (BlockGeometry::M5_COMPACT, Layout::m5(board.ok_or(EINVAL)?)) - } else { (vm.client_private_range(), Layout::NEO) }; - KernelObject::new(alloc.dev, vm, Placement::In(range, cfg::TVB_PAGE), layout.bytes, + let (placement, layout) = if alloc.uat.is_m5() { + (PairObject::SlotState.placement()?, Layout::m5(board.ok_or(EINVAL)?)) + } else { (Placement::In(vm.client_private_range(), cfg::TVB_PAGE), Layout::NEO) }; + KernelObject::new(alloc.dev, vm, placement, layout.bytes, mmu::PROT_GPU_FW_SHARED_RW, CpuMap::WriteCombined) } @@ -168,10 +168,4 @@ impl Generation { } } } - - pub(in crate::g17) fn retire(&mut self, ordinal: u64) -> Result { - if self.ordinal != Some(ordinal) { return Err(EIO); } - self.ordinal = None; - Ok(()) - } } diff --git a/drivers/gpu/drm/asahi/g17/queue/render/m5_render_submission.rs b/drivers/gpu/drm/asahi/g17/queue/render/m5_render_submission.rs index 333846d3f83c6f..5b2afea2a8ca78 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/m5_render_submission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/m5_render_submission.rs @@ -3,7 +3,7 @@ use kernel::prelude::*; use crate::g17::fw::m5::{render as cmd, render_registers as regs}; -use crate::g17::{buffer::target, command::Validated, fw::render::{RenderArgs, RenderPass, RegisterPrograms}}; +use crate::g17::{buffer::{compact, target}, command::Validated, fw::render::{RenderArgs, RenderPass, RegisterPrograms}}; /// Compressed single-layer MSAA ZLS admission: D32 depth with optional plain /// stencil, and the compressed Z/S form. @@ -120,25 +120,83 @@ pub(crate) fn parameter_geometry(blocks: usize) -> Result Result { +/// The target layout of a render: G17P's for a command without an M5 plan. `board` is the M5 +/// board, which an M5 plan needs. +pub(crate) fn layout(command: &Validated, clusters: u32, programs: RegisterPrograms, + board: Option<&'static crate::g17::fw::m5::initdata::Board>) -> Result { + Ok(layout_and_window(command, clusters, programs, board)?.0) +} + +/// The target layout of a render and, for an M5 render, the bytes of the client's compact +/// window that each render pair built for it reserves. +pub(crate) fn layout_and_window(command: &Validated, clusters: u32, programs: RegisterPrograms, + board: Option<&'static crate::g17::fw::m5::initdata::Board>) + -> Result<(target::Layout, Option)> { let Validated::Render { pass, plan, .. } = command else { return Err(EINVAL); }; let layout = target::Layout::new(pass, clusters, programs)?; - if plan.is_none() { return Ok(layout); } + if plan.is_none() { return Ok((layout, None)); } validate(pass)?; + let geometry = parameter_geometry(layout.tvb_blocks)?; + let mesh_storage = compact::mesh_storage()?.map(|(_, bytes)| bytes); + // The context state a pair allocates for each command slot (`Generation::allocate_state`). + let state = super::generation::Layout::m5(board.ok_or(EINVAL)?).bytes; + let (layout, reserved) = m5_layout(layout, pass, clusters, geometry, mesh_storage, state)?; + Ok((layout, Some(reserved))) +} + +/// The M5 layout of `pass` from its G17P layout, and the compact-window bytes a pair built for +/// it reserves ([`pair_window_bytes`]) with `mesh_storage` bytes of task-stage mesh storage. +fn m5_layout(layout: target::Layout, pass: &RenderPass, clusters: u32, + geometry: crate::g17::buffer::BlockGeometry, mesh_storage: Option, state: usize) + -> Result<(target::Layout, usize)> { // One target group per cluster unless the pass asks for few primitives. // Both target storage and the segment controls use the physical cluster count. - let geometry = parameter_geometry(layout.tvb_blocks)?; // The auxiliary tables cover the complete parameter inventory, including // future growth, rather than just the initially resident physical blocks. let bytes = geometry.capacity.checked_mul(geometry.block_bytes).ok_or(EOVERFLOW)?; let groups = if pass.few_primitives { 1 } else { clusters }; - layout.with_m5_slices(pass, clusters, groups, 64, bytes) + let layout = layout.with_m5_slices(pass, clusters, groups, 64, bytes)?; + // A pair maps its objects in the client's compact window, whose 32-bit offsets make it + // 4 GiB. A layout whose pair does not fit there on its own can never be mapped: refuse it + // as memory that cannot be had, before any of it is allocated. SUBMIT derives the layout, + // so the refusal is the ioctl's. + let reserved = pair_window_bytes(&layout, geometry, state, mesh_storage)?; + if reserved as u64 > compact::WINDOW_BYTES { + return Err(ENOMEM); + } + Ok((layout, reserved)) +} + +/// The objects a render pair built for `layout` maps in the client's M5 compact window +/// ([`compact::PairObject`]): its target records (a page-rounded record for each command slot), +/// its TPC object and its initial parameter blocks, which the layout sizes, the context state +/// of each command slot (`state` bytes each), the parameter buffer's scratch, discard and page +/// list, its metrics entry, and, while the binding is enabled, the task-stage mesh storage. A +/// pair maps that storage on its first task-stage kick and keeps it for the passes that follow, +/// so every pair counts it, whether or not this pass has a task stage. +fn pair_sizes(layout: &target::Layout, geometry: crate::g17::buffer::BlockGeometry, + state: usize, mesh_storage: Option) -> Result { + let depth = crate::hw::t8140::queues::RENDER_DEPTH as usize; + Ok(compact::PairSizes { + records: layout.record_stride()?.checked_mul(depth).ok_or(EOVERFLOW)?, + tpc: layout.tpc_capacity()?, + blocks: layout.tvb_blocks, + geometry, + state, + mesh_storage, + }) +} + +/// Bytes of the client's M5 compact window that a render pair built for `layout` reserves +/// ([`pair_sizes`]). +fn pair_window_bytes(layout: &target::Layout, geometry: crate::g17::buffer::BlockGeometry, + state: usize, mesh_storage: Option) -> Result { + pair_sizes(layout, geometry, state, mesh_storage)?.window_bytes() } pub(crate) fn controls( @@ -216,3 +274,122 @@ pub(crate) fn inputs(args: &RenderArgs<'_>, usage: [u64; 2]) -> Result = Some(0x200 * compact::MESH_STORAGE_CHUNK); + /// The J775D's context state per command slot. + const STATE: usize = + super::super::generation::Layout::m5(&crate::g17::fw::m5::initdata::J775D).bytes; + + /// A single-sample pass as Borealis sends it: `utile` tiles, and few-primitives for a pass + /// of at most four primitives. + fn pass(size: u32, layers: u16, utile: u8, few: bool) -> RenderPass { + // SAFETY: RenderPass and its nested surfaces/programs contain only + // integers and bools, for which the all-zero representation is valid. + let mut pass: RenderPass = unsafe { core::mem::zeroed() }; + pass.width = size; + pass.height = size; + pass.layers = layers; + pass.utile_width = utile; + pass.utile_height = utile; + pass.few_primitives = few; + pass + } + + /// The window bytes of a pair for that pass with `mesh` bytes of mesh storage. + fn reserved_with(size: u32, layers: u16, utile: u8, few: bool, mesh: Option) + -> Result { + let pass = pass(size, layers, utile, few); + let layout = target::Layout::new(&pass, 8, RegisterPrograms::G17P)?; + let geometry = BlockGeometry::m5(RAM, + (layout.tvb_blocks * BlockGeometry::M5_BLOCK_BYTES) as u64)?; + m5_layout(layout, &pass, 8, geometry, mesh, STATE).map(|(_, bytes)| bytes) + } + + /// The same with the default mesh storage. + fn reserved(size: u32, layers: u16, utile: u8, few: bool) -> Result { + reserved_with(size, layers, utile, few, MESH) + } + + /// The pairs a two-pair queue uses for that pass. + fn pairs(size: u32, layers: u16, utile: u8, few: bool, mesh: Option) -> u8 { + let bytes = reserved_with(size, layers, utile, few, mesh).unwrap() as u64; + crate::g17::pairs::for_window(2, Some(bytes), compact::WINDOW_BYTES) + } + + #[test] + fn borealis_32x32_passes_of_more_than_four_primitives() { + assert!(reserved(16384, 21, 32, false).unwrap() <= WINDOW); + assert_eq!(reserved(16384, 22, 32, false), Err(ENOMEM)); + assert!(reserved(512, 2048, 32, false).unwrap() <= WINDOW); + assert!(reserved(1024, 2048, 32, false).unwrap() <= WINDOW); + assert_eq!(reserved(1152, 2048, 32, false), Err(ENOMEM)); + } + + #[test] + fn borealis_32x32_passes_of_few_primitives() { + assert!(reserved(16384, 53, 32, true).unwrap() <= WINDOW); + assert_eq!(reserved(16384, 54, 32, true), Err(ENOMEM)); + assert!(reserved(2048, 2047, 32, true).unwrap() <= WINDOW); + assert!(reserved(2048, 2048, 32, true).unwrap() <= WINDOW); + assert_eq!(reserved(2112, 2048, 32, true), Err(ENOMEM)); + assert!(reserved(1152, 2048, 32, true).unwrap() <= WINDOW); + } + + #[test] + fn passes_with_16x16_tiles() { + assert!(reserved(16384, 5, 16, false).unwrap() <= WINDOW); + assert_eq!(reserved(16384, 6, 16, false), Err(ENOMEM)); + assert!(reserved(512, 2048, 16, false).unwrap() <= WINDOW); + assert_eq!(reserved(1024, 2048, 16, false), Err(ENOMEM)); + } + + #[test] + fn mesh_storage_counts_at_the_4_gib_edge() { + // A pass that fits only without the mesh storage a pair keeps once it has run a + // task-stage pass is refused while the binding is enabled. + assert!(reserved_with(16384, 22, 32, false, None).unwrap() <= WINDOW); + assert_eq!(reserved_with(16384, 22, 32, false, MESH), Err(ENOMEM)); + let with = reserved_with(16384, 21, 32, false, MESH).unwrap(); + let without = reserved_with(16384, 21, 32, false, None).unwrap(); + assert_eq!(with - without, PairObject::MeshStorage.window_bytes(MESH.unwrap()).unwrap()); + assert!(with - without >= 32 * MIB); + } + + #[test] + fn mesh_storage_counts_at_the_2_gib_edge() { + // A pass whose pair the window holds twice only without mesh storage runs on one pair. + assert_eq!(pairs(16384, 17, 32, true, None), 2); + assert_eq!(pairs(16384, 17, 32, true, MESH), 1); + assert_eq!(pairs(16384, 16, 32, true, MESH), 2); + } + + #[test] + fn a_pair_counts_the_objects_its_layout_does_not_size() { + // A trace of a pair on the J775D found 3824 KiB of these objects, guards included and + // alignment holes not. + let geometry = BlockGeometry::m5(RAM, 32 * BlockGeometry::M5_BLOCK_BYTES as u64).unwrap(); + let sizes = compact::PairSizes { + records: 0, tpc: 0, blocks: 0, geometry, + state: STATE, mesh_storage: None, + }; + let sized = [PairObject::Records, PairObject::Tpc, PairObject::ParameterBlock] + .into_iter().map(|object| sizes.object_bytes(object).unwrap()).sum::(); + let fixed = sizes.window_bytes().unwrap() - sized; + assert!(fixed >= 3824 * 1024); + assert!(fixed <= 5 * MIB); + // Each block takes its stride, guard included. + assert_eq!(PairObject::ParameterBlock.window_bytes(geometry.block_bytes).unwrap(), + geometry.stride); + } +} diff --git a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs index f7698a7e3b0b73..dd9cf808544f70 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs @@ -5,7 +5,7 @@ use super::retirement::Cursors; use crate::g17::{ - buffer::{self, target}, + buffer::{self, compact::PairObject, target}, context::Context, fw::{ self, queue, @@ -145,11 +145,14 @@ impl Graph { context.vm(), TA_BYTES..TA_BYTES + FRAGMENT_BYTES, )?) }; + // Both firmware and host write queue records (in-place retargeting and + // work-slot binding on G17P, and zeroing on pool reuse everywhere). Keep + // the whole queue-state object uncached while retaining it in the pool. let mut queues = pool.allocate( alloc, Family::QueueState, GRAPH_SIZE, - 0x8000, + 0, prot, CpuMap::WriteCombined, )?; @@ -319,23 +322,19 @@ struct Compact { address: u64, _backing: KernelObject, } -/// The mesh storage chunk: chunk bases are 64 KiB aligned and the storage -/// register counts 64 KiB chunks. -const MESH_STORAGE_CHUNK: usize = 0x10000; impl Compact { - /// M5 shared-RW object in the compact window with an explicit VA alignment. - fn new_aligned(alloc: &Allocator<'_>, vm: &mmu::Vm, size: usize, align: u64) -> Result { - let size = size.checked_add(mmu::UAT_PGSZ - 1).ok_or(EOVERFLOW)? & !(mmu::UAT_PGSZ - 1); + /// M5: a shared-RW object of `size` bytes mapped in the client's compact window as `object`. + fn m5(alloc: &Allocator<'_>, vm: &mmu::Vm, object: PairObject, size: usize) -> Result { + let size = size.checked_next_multiple_of(mmu::UAT_PGSZ).ok_or(EOVERFLOW)?; let backing = KernelObject::backing(alloc.dev, size, CpuMap::WriteCombined)?; - let mapping = backing.map_range(vm, 0..size, buffer::BlockGeometry::M5_COMPACT, - align, mmu::PROT_GPU_SHARED_RW, mmu::UAT_PGSZ)?; - if mapping.iova() % align != 0 { return Err(EINVAL); } + let mapping = object.map(&backing, vm, 0..size, mmu::PROT_GPU_SHARED_RW)?; Ok(Self { address: mapping.iova(), mapping: Some(mapping), _backing: backing }) } + /// Off M5: a shared-RW object of `size` bytes in a compact alias range. fn new(alloc: &Allocator<'_>, vm: &mmu::Vm, size: usize) -> Result { if alloc.uat.is_m5() { - return Self::new_aligned(alloc, vm, size, cfg::TVB_PAGE); + return Err(EINVAL); } let backing = KernelObject::backing(alloc.dev, size, CpuMap::WriteCombined)?; let mapping = buffer::compact_alias( @@ -560,12 +559,10 @@ impl Memory { let state = Generation::allocate_state(alloc, vm, board)?; let (tvb, mappings, scratch, discard) = if m5 { let geometry = super::m5_render_submission::parameter_geometry(layout.tvb_blocks)?; - let bytes = fw::m5::pool::parameter_scratch_stride(geometry.capacity, 0) - .map_err(|_| EINVAL)?.checked_mul(fw::m5::pool::SCENE_TABLE_ENTRIES) - .ok_or(EOVERFLOW)?; + let bytes = buffer::compact::scratch_bytes(geometry)?; let (tvb, mappings) = buffer::Tvb::with_geometry(alloc.dev, vm, layout.tvb_blocks, geometry)?; - let scratch = Compact::new(alloc, vm, bytes)?; - let discard = Compact::new(alloc, vm, 0x8000)?; + let scratch = Compact::m5(alloc, vm, PairObject::Scratch, bytes)?; + let discard = Compact::m5(alloc, vm, PairObject::Discard, fw::m5::pool::DISCARD_BYTES)?; (tvb, mappings, scratch, discard) } else { let scratch = Compact::new(alloc, vm, cfg::SCENE_SIZE as usize)?; @@ -603,6 +600,7 @@ impl Memory { buffer_id: buffer_id.0, generation: pm_generation, first_ordinal: ordinal, + normal_blocks: variant.tvb_normal_blocks, }, )?; let predecessor = crate::g17::ids::OBJECTS.object()?; @@ -666,18 +664,17 @@ impl Memory { )) } /// The mesh storage register value of a task-stage kick. The buffer is - /// allocated on the queue's first such kick and kept for the queue's lifetime, + /// allocated on the pair's first such kick and kept for the pair's lifetime, /// so other contexts pay nothing. A failed allocation leaves no partial state. - /// A zero chunk parameter disables the binding. + /// A zero chunk parameter disables the binding. SUBMIT's compact-window bound + /// counts this buffer in every pair while the binding is enabled, since a pair + /// keeps it for the passes that follow. pub(super) fn mesh_storage_register(&mut self, alloc: &Allocator<'_>) -> Result { if self.mesh_storage.is_none() { - let chunks = crate::module_parameters::m5_mesh_storage_chunks.value(); - if chunks == 0 { return Ok(0); } - if chunks > 0xffff { return Err(EINVAL); } - let bytes = (chunks as usize).checked_mul(MESH_STORAGE_CHUNK).ok_or(EOVERFLOW)?; - let storage = Compact::new_aligned(alloc, self.context.vm(), bytes, - MESH_STORAGE_CHUNK as u64)?; - self.mesh_storage = Some(storage); + let Some((chunks, bytes)) = buffer::compact::mesh_storage()? else { return Ok(0); }; + let vm = self.context.vm(); + PairObject::MeshStorage.check_room(vm, bytes, 1)?; + self.mesh_storage = Some(Compact::m5(alloc, vm, PairObject::MeshStorage, bytes)?); self.mesh_storage_chunks = chunks; } let storage = self.mesh_storage.as_ref().ok_or(ENOMEM)?; @@ -1061,6 +1058,7 @@ impl Memory { pointer.write_unaligned(value); } } + core::sync::atomic::fence(Ordering::Release); return Ok(()); } let offsets = qids.map(|qid| usize::from(qid) * size_of::()); @@ -1105,6 +1103,7 @@ impl Memory { } } } + core::sync::atomic::fence(Ordering::Release); Ok(()) } } diff --git a/drivers/gpu/drm/asahi/g17/queue/render/parked.rs b/drivers/gpu/drm/asahi/g17/queue/render/parked.rs index 6313bf2ef5128a..349cbe1a60add1 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/parked.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/parked.rs @@ -18,6 +18,9 @@ use kernel::{prelude::*, sync::Arc}; /// without retaining that scheduler's execution context or client root. A prior /// context awaiting an executed replacement keeps its separate retirement owner. pub(crate) struct ParkedPair { + /// The pair's views of the kick rings in `vm` ([`Pair::client_kicks`]), dropped before + /// `kicks`. + client_kicks: [Option; 2], kicks: Option<[kick::Queue; 2]>, _scheduler: Arc, ids: [kick::Id; 2], @@ -40,6 +43,8 @@ pub(crate) struct ParkedPair { executed: u64, /// The VM of the context that last ran on these rings. vm: u64, + /// That VM's status, which tells when its client closed it ([`Self::take_closed_views`]). + status: Option>, } /// All new graph ownership stays separate from the installed kick storage until commit. @@ -49,6 +54,8 @@ pub(crate) struct Prepared { pool: Arc, aliases: Option>, kicks: Option<[Option; 2]>, + /// The new views of the kick rings, once installed. + views: [Option; 2], ids: [kick::Id; 2], slot: u8, ordinal: u64, @@ -71,7 +78,24 @@ impl Pair { } fn can_park_backing(&self, context: &Arc) -> Result { - Ok(Arc::ptr_eq(context, self.context()) + Ok(self.backing_detachable(context) && self.idle_for_context(context)?) + } + + /// A killed guilty pair whose groups went on the guilty proof (`guilty_released`) but whose + /// rings the firmware has not consumed: the entries of the groups the kill unlinked may + /// never be read. It cannot park, since a parked pair's rings go to the next owner with + /// those entries naming freed descriptors, so `detach_context` keeps it, and its slot, out of + /// service until the processors stop. + pub(crate) fn can_keep(&self, context: &Arc) -> bool { + self.guilty_released + && self.owner.is_none() + && self.prepared.is_none() + && self.active.len() == 0 + && self.backing_detachable(context) + } + + fn backing_detachable(&self, context: &Arc) -> bool { + Arc::ptr_eq(context, self.context()) && self .previous .as_ref() @@ -79,7 +103,11 @@ impl Pair { && self.displaced.is_none() && self.pending_aliases.is_none() && self.kick_aliases.is_none() - && self.idle_for_context(context)?) + } + + /// The pair's two ring cursors (`done`, `read`, `write`), for the detach log line. + pub(crate) fn ring_cursors(&self) -> Result<[crate::g17::queue::render::retirement::Cursors; 2]> { + self.memory.graph.cursors() } /// Consumes the pair only after can_park and all collector capacity checks succeeded @@ -87,10 +115,20 @@ impl Pair { pub(crate) fn park(self) -> (ParkedPair, RetiredBinding) { let context = self.memory.context.clone(); let vm = context.vm().id(); + let status = context.vm().status().cloned(); let scheduler = context.scheduler_owner(); let buffer_id = self.buffer_id(); + // A pair parked after its VM's client closed it keeps no views there: they go with the + // retired binding, whose context holds that VM anyway, and drop with it off the device + // lock. + let (client_kicks, retired_kicks) = if closed(status.as_ref()) { + ([None, None], self.client_kicks) + } else { + (self.client_kicks, [None, None]) + }; let parked = ParkedPair { ids: self.kicks.each_ref().map(|queue| queue.id()), + client_kicks, kicks: Some(self.kicks), _scheduler: scheduler, slot: self.slot, @@ -107,8 +145,10 @@ impl Pair { previous: self.previous, executed: self.executed, vm, + status, }; let retired = RetiredBinding { + _client_kicks: retired_kicks, memory: Some(self.memory), context, pool: self.free_list, @@ -121,21 +161,41 @@ impl Pair { } } +/// The client of the VM with this status closed it: nothing runs there again. +fn closed(status: Option<&Arc>) -> bool { + status.is_some_and(|status| status.client_closed()) +} + impl ParkedPair { - /// Clears both kick rings when the pair goes to a context of another VM than the one - /// that last ran on it, so the new owner cannot read the entries the previous owner's - /// commands left. The pair is parked, so the firmware consumed every entry. - pub(crate) fn clear_for_vm(&mut self, vm: u64) -> Result { - if self.vm == vm { + /// Removes the previous VM's views of both kick rings and clears the rings when the pair + /// goes to a context of another VM than the one that last ran on it, so neither owner can + /// read the entries the other's commands leave there. The pair is parked, so the firmware + /// consumed every entry and no longer reads the rings through those views. + pub(crate) fn clear_for_vm(&mut self, vm: &mmu::Vm) -> Result { + if self.vm == vm.id() { return Ok(()); } + self.client_kicks = [None, None]; for queue in self.kicks.as_mut().ok_or(EBUSY)?.iter_mut() { queue.clear_render_ring()?; } - self.vm = vm; + self.vm = vm.id(); + self.status = vm.status().cloned(); Ok(()) } + /// Takes the pair's views of the kick rings once the client of the VM they are in has + /// closed it, for the caller to drop off the device lock: each view holds that VM, whose + /// page tables would otherwise stay alive for as long as the pair stays parked. A later + /// context of the same VM gets new views, as one of another VM does. + pub(crate) fn take_closed_views(&mut self) -> [Option; 2] { + if closed(self.status.as_ref()) { + core::mem::take(&mut self.client_kicks) + } else { + [None, None] + } + } + /// The release of `scheduler` has been consumed: a later owner change no /// longer has to wait for it. pub(crate) fn release_consumed(&mut self, scheduler: u64) { @@ -181,11 +241,19 @@ impl ParkedPair { &first.command, self.clusters, self.variant.programs, + self.board, )?; let aliases = [ kicks[0].prepare_client_alias(context.vm())?, kicks[1].prepare_client_alias(context.vm())?, ]; + // A view the VM already has is the one this pair holds for it (`clear_for_vm` dropped + // those of any other VM). + for (alias, view) in aliases.iter().zip(&self.client_kicks) { + if alias.is_none() && view.is_none() { + return Err(EFAULT); + } + } let (memory, persistent) = memory::Memory::new( alloc, pool, @@ -206,6 +274,7 @@ impl ParkedPair { pool: free_list, aliases: Some(persistent), kicks: Some(aliases), + views: [None, None], ids: self.ids, slot: self.slot, ordinal: self.ordinal, @@ -248,10 +317,18 @@ impl ParkedPair { self.kicks = Some(kicks); return Err(EIO); }; + // The new views, else the ones this pair already held in the same VM. + let mut client_kicks = core::mem::take(&mut next.views); + for (view, held) in client_kicks.iter_mut().zip(self.client_kicks.iter_mut()) { + if view.is_none() { + *view = held.take(); + } + } storage.write_init(kernel::try_init!(Pair { pool_pin: next.pool_pin.take(), graph_started: false, kick_aliases: None, + client_kicks, memory, kicks, free_list: next.pool.clone(), @@ -274,6 +351,8 @@ impl ParkedPair { registered: self.registered, outer_started: self.outer_started, quarantined: false, + guilty_released: false, + collateral_at: None, terminal: None, previous: self.previous.take(), displaced: None, @@ -319,6 +398,7 @@ impl Prepared { self.memory.as_mut().ok_or(EIO)?, &mut self.aliases, &mut self.kicks, + &mut self.views, )?; self.installed = true; Ok(()) diff --git a/drivers/gpu/drm/asahi/g17/queue/render/publication.rs b/drivers/gpu/drm/asahi/g17/queue/render/publication.rs index 9ee23de8924011..e5cce1631f25a7 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/publication.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/publication.rs @@ -46,6 +46,7 @@ pub(super) struct Lane<'a> { prefix: usize, prefix_end: u32, pub(super) window: Window, + retained: bool, } impl<'a> Lane<'a> { #[expect( @@ -61,6 +62,7 @@ impl<'a> Lane<'a> { present: bool, timestamp: KickTimestamp, lead: bool, + retained: bool, ) -> Result { // macOS 27.0 on the J813 (common 26A428 interface) publishes the Neo form: its // TA, 3D and compute item rings carry [configuration], descriptor, KickAnnounce (tag 0xe) @@ -68,7 +70,11 @@ impl<'a> Lane<'a> { let j813 = crate::g17::J813_FORMS.load(core::sync::atomic::Ordering::Relaxed); let m5 = graph.is_m5() && !j813; // M5 items carry no descriptor: [configuration], notification. - let count = u32::from(present) + u32::from(lead) + if m5 { 1 } else { 2 }; + let count = if retained { + 0 + } else { + u32::from(present) + u32::from(lead) + if m5 { 1 } else { 2 } + }; let window = Window::new(base, count, ITEM_RING_ENTRIES)?; let offset = ordinal as usize % memory::RECORDS; let config_offset = memory::CONFIG[stage] + offset * memory::CONFIG_STRIDE; @@ -138,9 +144,10 @@ impl<'a> Lane<'a> { )?) }, announce_destination, - prefix: count as usize - 1, - prefix_end: (base + count - 1) % ITEM_RING_ENTRIES, + prefix: count.saturating_sub(1) as usize, + prefix_end: (base + count.saturating_sub(1)) % ITEM_RING_ENTRIES, window, + retained, }) } fn items(&self, range: core::ops::Range) { @@ -179,17 +186,26 @@ impl<'a> Lane<'a> { /// Fill the retained records without advancing the firmware-visible cursor. /// M5's host-port transaction must occur between this and publish_kick. pub(super) fn prepare(&self) { + if self.retained { + return; + } self.items(0..self.prefix + 1); self.config(); self.announce(); } pub(super) fn publish_prefix(&self) { + if self.retained { + return; + } self.items(0..self.prefix); self.config(); fence(Ordering::SeqCst); self.producer.store(self.prefix_end, Ordering::Relaxed); } pub(super) fn publish_kick(&self) { + if self.retained { + return; + } self.announce(); self.items(self.prefix..self.prefix + 1); fence(Ordering::SeqCst); @@ -202,6 +218,9 @@ impl<'a> Lane<'a> { inner: &AtomicU32, next_inner: u32, ) { + if self.retained { + return; + } self.items(0..self.prefix + 1); self.config(); self.announce(); diff --git a/drivers/gpu/drm/asahi/g17/queue/render/retirement.rs b/drivers/gpu/drm/asahi/g17/queue/render/retirement.rs index 19a2caabe68e10..1083aaa96d1e8d 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/retirement.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/retirement.rs @@ -39,7 +39,7 @@ pub(crate) struct Window { impl Window { pub(crate) fn new(base: u32, count: u32, capacity: u32) -> Result { - if base >= capacity || !(1..=MAX_GROUP_ITEMS).contains(&count) || count >= capacity { + if base >= capacity || count > MAX_GROUP_ITEMS || count >= capacity { return Err(EINVAL); } Ok(Self { diff --git a/drivers/gpu/drm/asahi/g17/recovery.rs b/drivers/gpu/drm/asahi/g17/recovery.rs index 422bfe06f9b607..51a92a0581cdaf 100644 --- a/drivers/gpu/drm/asahi/g17/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/recovery.rs @@ -11,8 +11,8 @@ mod attribution; mod slot; mod safety; pub(crate) use safety::{note_retired, since_retired}; -pub(crate) use attribution::{Record, Sources, PAGE_FAULT}; -use attribution::Attribution; +pub(crate) use attribution::{fault_qids, Record, Sources}; +pub(crate) use attribution::Attribution; pub(super) fn slot_key(slot: usize, slot_keys: Option) -> Option { slot::key(slot, slot_keys?).ok() @@ -49,6 +49,48 @@ pub(super) struct Entries { exact_qids: u128, /// QIDs with a valid record. queues: u128, + /// The first records, for the recovery's log line. + shown: Shown, +} + +/// Records of a recovery table shown in its one log line. +const SHOWN: usize = 24; + +/// The first [`SHOWN`] valid records of a recovery table as `q::/`, +/// the match being how the host found the command (`E` by exact stamp, `O` as the oldest +/// published work, `-` not found, `?` not matched on M5): which queues the restart listed, and +/// whether the firmware flagged them guilty, decide what the recovery fails and whether a +/// restart storm counts it. +#[derive(Default)] +struct Shown { + records: [(u32, u32, u8); SHOWN], + count: usize, + more: usize, +} + +impl Shown { + fn push(&mut self, flags: u32, stamp: u32, matched: u8) { + match self.records.get_mut(self.count) { + Some(record) => { + *record = (flags, stamp, matched); + self.count += 1; + } + None => self.more += 1, + } + } +} + +impl kernel::fmt::Display for Shown { + fn fmt(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result { + for (index, &(flags, stamp, matched)) in self.records[..self.count].iter().enumerate() { + let sep = if index == 0 { "" } else { " " }; + write!(f, "{}q{}:{:#x}:{:#x}/{}", sep, (flags >> 4) & 0x7f, stamp, flags, matched as char)?; + } + if self.more != 0 { + write!(f, " +{}", self.more)?; + } + Ok(()) + } } impl Entries { @@ -99,10 +141,11 @@ pub(super) trait Queues { fn render_pass_started(&self, qid: u8, stamp: u64) -> Option; /// Read while firmware is halted, like `render_pass_started`. The QIDs of every pair of a VM /// an earlier recovery found guilty with a render that started and did not finish. Without - /// one, and only when the oldest published render of the pair holding `blamed` had not - /// started, those of the one VM with such a render. None if no such VM, several, or any - /// other VM holds compute work, which these records cannot see. - fn render_culprit(&self, _blamed: u8) -> Option { None } + /// one, `Suspects` the VM whose such render started first, unless another VM holds compute + /// work, which these records cannot see. `NoCulprit` when the oldest published render of the + /// pair holding `blamed` had not started and no VM can be named; None keeps the firmware's + /// blame. + fn render_culprit(&self, _blamed: u8) -> Option { None } /// Copy every retained queue's live producer to its recovery target, then /// issue a full barrier. A failed graph must not skip subsequent queues. fn publish_recovery_targets(&self) -> Option; @@ -116,8 +159,30 @@ pub(super) trait Queues { fn note_interrupted(&mut self, qid: u8, stamp: u32) -> Interrupted; /// Optional diagnostics only; absence cannot alter attribution or release. fn report_blamed_render(&self, _qid: u8) {} - /// Optional diagnostics: logs the MMU fault banks while the firmware is halted. - fn report_mmu_fault(&self) {} + /// Read while firmware is halted: a restart before `generation` blamed the spared work of the + /// render pair that holds `qid` as collateral already, and none of that pair's work retired + /// since (`note_collateral`). Its spared work hung the GPU again after the restart that blamed + /// it, so the hang is its own. Never for a compute queue. + fn collateral_before(&self, _qid: u8, _generation: u64) -> bool { false } + /// The restart `generation` blamed the spared work of the render pair that holds `qid` as + /// collateral. Marks that pair, not the QID: a QID is reused once its owner closes, and the + /// next owner starts unmarked. A retirement of the pair's work clears the mark. + fn note_collateral(&mut self, _qid: u8, _generation: u64) {} + /// `note_collateral` keeps a mark for the queue that holds `qid`, so a repeated blame on it + /// can be told from a first one. Only G17P render pairs keep one. + fn marks_collateral(&self, _qid: u8) -> bool { false } + /// Read while firmware is halted for the restart the host accepted after `generation`: + /// every killed context whose kill the firmware finished counts as first seen done at + /// `generation` at the latest, so this restart releases its guilty pairs + /// (`Context::restarted_since_kill`). Without this, a kill finished just before a restart + /// that the host had not observed yet would wait for a restart that may never come. + fn note_kill_sightings(&self, _generation: u64) {} + /// Logs the MMU fault banks while the firmware is halted and returns the UAT slots + /// (context IDs) of the faulting accesses as a mask; 0 without a decodable user fault. + fn report_mmu_fault(&self) -> u64 { 0 } + /// Read while firmware is halted, like `render_pass_started`. The QIDs of every queue with + /// an in-flight packet whose context is in `slots`; None if there is none. + fn fault_culprit(&self, _slots: u64) -> Option { None } fn settle_blamed_render(&mut self, qid: u8, error: Error); fn settle_cancelled_renders(&mut self, qids: u128); fn rescan_compute(&mut self) -> Result; @@ -274,7 +339,7 @@ pub(super) fn service( let mut sources = host.fault_sources()?; sources.report(request.generation, super::queue::compute::retirement::stampless_total(), request.blamed); - host.report_mmu_fault(); + let fault_slots = host.report_mmu_fault(); if let Some(qid) = request.blamed { host.report_blamed_render(qid); } @@ -285,6 +350,11 @@ pub(super) fn service( |qid, stamp| host.render_pass_started(qid, stamp)); let attribution = sources.host_fallback(attribution, || host.render_culprit(request.blamed?)); + let attribution = sources.fault_override(attribution, request.blamed, fault_slots, + |slots| host.fault_culprit(slots)); + if let Attribution::Suspects(qids) = attribution { + pr_warn!("G17: recovery gen {} suspects queues {:#x}\n", request.generation, qids); + } if let Attribution::Queues(qids) = attribution { pr_warn!("G17: recovery gen {} blames queues {:#x}\n", request.generation, qids); } @@ -311,7 +381,10 @@ pub(super) fn service( // still retire it with stamps and records that look like success, so it is // marked before firmware resumes and never reports success. let entries = read_entries(host); + host.note_kill_sightings(host.recovery().accepted.wrapping_sub(1)); host.transition(3, 0)?; + // The records are copied: log them once the firmware runs again. + pr_warn!("G17: recovery gen {} table: {} records [{}]\n", request.generation, entries.listed, entries.shown); if host.recovery_state()? != 0 { return Err(EIO); } @@ -320,7 +393,7 @@ pub(super) fn service( let (listed, exact, fallback) = (entries.listed, entries.exact, entries.fallback); let (cancelled, blame, leftover, charged) = - classify(host, entries, request.blamed, attribution); + classify(host, entries, request.blamed, attribution, request.generation); if listed != 0 && host.is_m5() { // The M5 table only classifies (read_entries): each command is retired from its own // queue's records, replayed when it never ran. @@ -411,24 +484,37 @@ fn read_entries(host: &mut H) -> Entries { break; } if m5 { + entries.shown.push(flags, stamp, b'?'); continue; } let qid = ((flags >> 4) & 0x7f) as u8; - match host.note_interrupted(qid, stamp) { + let matched = match host.note_interrupted(qid, stamp) { Interrupted::Exact => { entries.exact += 1; entries.exact_qids |= 1u128 << qid; + b'E' } - Interrupted::Oldest => entries.fallback += 1, - Interrupted::None => {} - } + Interrupted::Oldest => { + entries.fallback += 1; + b'O' + } + Interrupted::None => b'-', + }; + entries.shown.push(flags, stamp, matched); } entries } /// Resolves guilty QIDs before changing any completion's classification. Unknown ownership or /// too many distinct guilty VMs leaves all prior classifications intact. The oldest spared work -/// of a QID makes later blame collateral to its previous recovery, rather than new VM guilt. +/// of a QID, or blame that no evidence confirmed (`Attribution::Firmware`), makes that blame +/// collateral rather than new VM guilt, once: +/// the restart `generation` marks the render pair it blamed so (`Queues::note_collateral`), and +/// when a later restart blames that pair again with none of its work retired in between, the +/// hang is its own and its VM is guilty (`Queues::collateral_before`). Otherwise a first blame +/// that landed on a starved bystander would leave the real culprit's spared work immune: never +/// guilty, never poisoned, never forgiven and never killed, until the restart storm limit +/// (2026-11-19 19:12 UTC, 2026-11-20 15:03 UTC). /// Also returns whether the firmware's blamed QID is still guilty after attribution: a blamed /// render that had not started while others had (or with no culprit at all) is innocent, and its /// work is spared like that of every other innocent VM instead of failing with EIO. @@ -438,15 +524,26 @@ fn read_entries(host: &mut H) -> Entries { /// the commands each holds): one client's faults or hangs then cost only that client, however /// many VMs it opens. A restart without a guilty VM, or one that keeps blaming a VM for more /// than the work it held, is the device's. -fn classify(queues: &mut Q, entries: Entries, blamed: Option, attribution: Attribution) -> (u128, bool, bool, bool) { +fn classify( + queues: &mut Q, + entries: Entries, + blamed: Option, + attribution: Attribution, + generation: u64, +) -> (u128, bool, bool, bool) { let mut guilty_qids = entries.guilty | blamed.map_or(0, |qid| 1u128 << qid); let cancelled = entries.cancelled; match attribution { Attribution::Firmware => {} - Attribution::Queues(qids) => guilty_qids = qids, + Attribution::Queues(qids) | Attribution::Suspects(qids) => guilty_qids = qids, Attribution::NoCulprit => guilty_qids = 0, } let no_culprit = attribution == Attribution::NoCulprit; + // Only the firmware, or the pass records' suspicion, names these queues. A reason-0 restart + // can land on a bystander whose render started and waits behind the culprit's (2026-11-23 + // 01:46 UTC, m4.179: t3code, then Hyprland), and a slow innocent render can be the oldest + // running one, so the first such blame is collateral and only a repeat makes the VM guilty. + let unconfirmed = matches!(attribution, Attribution::Firmware | Attribution::Suspects(_)); let blame = blamed.is_some_and(|qid| guilty_qids & (1u128 << qid) != 0); if guilty_qids == 0 && !no_culprit { return (0, blame, false, false); @@ -454,6 +551,8 @@ fn classify(queues: &mut Q, entries: Entries, blamed: Option, att let mut guilty: [Option>; MAX_GUILTY_VMS] = Default::default(); let mut count = 0; let mut collateral = 0u128; + // Spared or unconfirmed work blamed a second time (`collateral_before`): its VM is guilty now. + let mut repeated = 0u128; let mut unresolved = false; for qid in 0..QIDS { if guilty_qids & (1u128 << qid) == 0 { @@ -461,8 +560,19 @@ fn classify(queues: &mut Q, entries: Entries, blamed: Option, att } match queues.oldest_spared(qid) { None => unresolved = true, - Some(true) => collateral |= 1u128 << qid, - Some(false) => { + Some(spared) => { + // Blame on a VM an earlier recovery found guilty needs no confirmation. + let mut guilty_before = false; + queues.visit_owners(qid, &mut |status| guilty_before |= status.recovery_guilty()); + // Without a mark a repeat looks like a first blame forever: such blame stays guilty. + let suspect = spared || (unconfirmed && !guilty_before && queues.marks_collateral(qid)); + if suspect && !queues.collateral_before(qid, generation) { + collateral |= 1u128 << qid; + continue; + } + if suspect { + repeated |= 1u128 << qid; + } let mut found = false; queues.visit_owners(qid, &mut |status| { found = true; @@ -487,6 +597,9 @@ fn classify(queues: &mut Q, entries: Entries, blamed: Option, att if unresolved || (count == 0 && collateral == 0 && !no_culprit) { return (0, blame, false, false); } + for qid in (0..QIDS).filter(|qid| collateral & (1u128 << qid) != 0) { + queues.note_collateral(qid, generation); + } let known = |status: &Arc| guilty[..count].iter().flatten().any(|known| Arc::ptr_eq(known, status)); let mut dropped = false; for qid in (0..QIDS).filter(|qid| entries.exact_qids & (1u128 << qid) != 0) { @@ -494,6 +607,14 @@ fn classify(queues: &mut Q, entries: Entries, blamed: Option, att } let leftover = count != 0 && dropped && guilty[..count].iter().flatten().all(|status| status.get() != 0); guilty[..count].iter().flatten().for_each(|status| status.note_recovery_guilty()); + // Its work failed already, at the collateral blame or as commands earlier restarts listed, + // and failing it again changes nothing (`Pair::quarantine` skips failed work): nothing else + // poisons this VM. Poison it here, after `leftover` judged this restart on the VM's state + // before it, so that the restarts that only drop its work from now on are forgiven, and an + // open or closed culprit is killed (2026-11-20 17:52 UTC, m4.175). + for qid in (0..QIDS).filter(|qid| repeated & (1u128 << qid) != 0) { + queues.visit_owners(qid, &mut |status| status.record(EIO)); + } // Commands each guilty VM holds, counted as they are classified. let held: [core::cell::Cell; MAX_GUILTY_VMS] = Default::default(); let spared = queues.classify_work(&|status| { @@ -518,6 +639,26 @@ fn classify(queues: &mut Q, entries: Entries, blamed: Option, att } +#[kernel::macros::kunit_tests(asahi_g17_recovery_table_line)] +mod table_line_tests { + use super::{Shown, SHOWN}; + use kernel::{prelude::*, str::CString}; + + #[test] + fn the_table_line_shows_queue_stamp_flags_and_match_then_a_count() { + let mut shown = Shown::default(); + shown.push(1 | 2 | (41 << 4), 0x167a_1c00, b'E'); + shown.push(1 | (42 << 4), 0x7_9300, b'-'); + let line = CString::try_from_fmt(fmt!("{}", shown)).unwrap(); + assert_eq!(line.to_bytes(), b"q41:0x167a1c00:0x293/E q42:0x79300:0x2a1/-"); + for _ in 0..SHOWN { + shown.push(1, 0, b'O'); + } + let line = CString::try_from_fmt(fmt!("{}", shown)).unwrap(); + assert!(line.to_bytes().ends_with(b" +2")); + } +} + #[kernel::macros::kunit_tests(asahi_g17_recovery_snapshot)] mod tests { use super::*; @@ -730,7 +871,7 @@ mod tests { fn leftover(queues: &mut Owners, exact_qid: u8) -> bool { let entries = Entries { exact_qids: 1u128 << exact_qid, ..Entries::default() }; - classify(queues, entries, Some(40), Attribution::Queues(3u128 << 60)).2 + classify(queues, entries, Some(40), Attribution::Queues(3u128 << 60), 1).2 } #[test] @@ -748,7 +889,7 @@ mod tests { fn restarts_are_charged_to_their_guilty_clients_and_only_unblamed_ones_to_the_device() { let mut queues = owners(); let charged = |queues: &mut Owners, attribution| { - classify(queues, Entries::default(), None, attribution).3 + classify(queues, Entries::default(), None, attribution, 1).3 }; // Nobody to blame: the device's. assert!(!charged(&mut queues, Attribution::NoCulprit)); @@ -767,20 +908,379 @@ mod tests { assert!(!charged(&mut queues, Attribution::Queues(1u128 << 60))); } + #[test] + fn unconfirmed_blame_without_a_collateral_mark_is_guilty_at_once() { + // A compute queue, or any queue on M5, keeps no mark: a repeat could never be seen. + let mut queues = owners(); + let entries = Entries { exact_qids: 1u128 << 40, ..Entries::default() }; + classify(&mut queues, entries, Some(40), Attribution::Firmware, 1); + assert!(queues.0[0].1.recovery_guilty()); + assert_eq!(queues.1, [Some(Class::Guilty), Some(Class::Guilty), Some(Class::Spared), Some(Class::Spared)]); + } + #[test] fn a_guilty_vm_is_not_spared_by_another_vms_recovery() { let mut queues = owners(); let entries = || Entries { exact_qids: 1u128 << 40, ..Entries::default() }; // b failing for its own client does not make it guilty in a's recovery. queues.0[2].1.record(EIO); - classify(&mut queues, entries(), Some(40), Attribution::Queues(3u128 << 40)); + classify(&mut queues, entries(), Some(40), Attribution::Queues(3u128 << 40), 1); assert_eq!(queues.1, [Some(Class::Guilty), Some(Class::Guilty), Some(Class::Spared), Some(Class::Spared)]); // Once a recovery finds b guilty, a later recovery that blames a keeps b guilty. - classify(&mut queues, entries(), Some(60), Attribution::Queues(3u128 << 60)); - classify(&mut queues, entries(), Some(40), Attribution::Queues(3u128 << 40)); + classify(&mut queues, entries(), Some(60), Attribution::Queues(3u128 << 60), 1); + classify(&mut queues, entries(), Some(40), Attribution::Queues(3u128 << 40), 1); assert_eq!(queues.1, [Some(Class::Guilty); 4]); } + /// A render pair in a cascade of restarts (see [`Cascade`]). + struct CascadePair { + qids: [u8; 2], + status: Arc, + class: Option, + collateral: Option, + /// Its work failed already (a restart listed it, or it was blamed): failing it again + /// changes nothing, as `Pair::quarantine` skips failed work. + failed: bool, + } + + /// The render pairs across a cascade of restarts, with state: each pair keeps the class the + /// last recovery gave its work (`Pair::classify`) and its collateral mark + /// (`Pair::note_collateral`), which a retirement of its work clears. A blamed render fails as + /// `settle_blamed_render` fails it: guilty work poisons its VM, work an earlier recovery + /// spared fails without poisoning it (`Completion::poisons`), and work that failed already + /// is not failed again. + struct Cascade([Option; 4], u64); + + impl Cascade { + fn new(pairs: [([u8; 2], &Arc); 4]) -> Self { + Self( + pairs.map(|(qids, status)| { + Some(CascadePair { qids, status: status.clone(), class: None, collateral: None, failed: false }) + }), + 0, + ) + } + fn pair(&self, qid: u8) -> Option<&CascadePair> { + self.0.iter().flatten().find(|pair| pair.qids.contains(&qid)) + } + fn pair_mut(&mut self, qid: u8) -> Option<&mut CascadePair> { + self.0.iter_mut().flatten().find(|pair| pair.qids.contains(&qid)) + } + /// The pair that holds `qid` is bound to `status`'s owner in place, as `Pair::bind_owner` + /// rebinds a reusable pair: its mark goes as there (`rebound_collateral`), its work is new. + fn bind(&mut self, qid: u8, status: &Arc) { + if let Some(pair) = self.pair_mut(qid) { + let same = Arc::ptr_eq(&pair.status, status); + pair.collateral = crate::g17::queue::render::rebound_collateral(pair.collateral, same); + pair.status = status.clone(); + pair.class = None; + pair.failed = false; + } + } + /// The pair that holds `qid` submitted new work that no recovery has classified yet, and + /// it is now the pair's oldest in flight (its earlier work failed or retired). + fn submit(&mut self, qid: u8) { + if let Some(pair) = self.pair_mut(qid) { + pair.class = None; + pair.failed = false; + } + } + /// Work of the pair that holds `qid` retired (`Pair::retire_front_command`). + fn retire(&mut self, qid: u8) { + if let Some(pair) = self.pair_mut(qid) { + pair.collateral = None; + pair.failed = false; + } + } + /// One restart as `service` runs it: the firmware blames `blamed`, its table drops + /// `dropped` by exact stamp, the blamed render fails. Returns whether it was forgiven. + fn restart(&mut self, blamed: u8, dropped: u128) -> bool { + self.restart_as(blamed, dropped, Attribution::Firmware) + } + /// As [`Self::restart`], with render attribution (`render_culprit`) deciding the blame. + fn restart_as(&mut self, blamed: u8, dropped: u128, attribution: Attribution) -> bool { + let entries = Entries { exact_qids: dropped, ..Entries::default() }; + self.1 += 1; + let generation = self.1; + let (_, blame, leftover, _) = classify(self, entries, Some(blamed), attribution, generation); + // The listed commands fail: a guilty VM's poison it, others' are discarded. + for pair in self.0.iter_mut().flatten() { + if !pair.failed && pair.qids.iter().any(|qid| dropped & (1u128 << qid) != 0) { + if pair.class == Some(Class::Guilty) { + pair.status.record(EIO); + } + pair.failed = true; + } + } + if blame { + self.settle_blamed_render(blamed, EIO); + } + leftover + } + } + + impl Queues for Cascade { + fn render_scheduler_active(&self) -> bool { true } + fn render_pass_started(&self, _qid: u8, _stamp: u64) -> Option { None } + fn publish_recovery_targets(&self) -> Option { None } + fn oldest_spared(&self, qid: u8) -> Option { + self.pair(qid).map(|pair| pair.class == Some(Class::Spared)) + } + fn collateral_before(&self, qid: u8, generation: u64) -> bool { + self.pair(qid).is_some_and(|pair| pair.collateral.is_some_and(|at| at < generation)) + } + fn note_collateral(&mut self, qid: u8, generation: u64) { + if let Some(pair) = self.pair_mut(qid) { + pair.collateral.get_or_insert(generation); + } + } + fn marks_collateral(&self, qid: u8) -> bool { self.pair(qid).is_some() } + fn visit_owners(&self, qid: u8, visit: &mut dyn FnMut(&Arc)) { + if let Some(pair) = self.pair(qid) { + visit(&pair.status); + } + } + fn classify_work(&mut self, class: &dyn Fn(&Arc) -> Class) -> u128 { + let mut spared = 0; + for pair in self.0.iter_mut().flatten() { + pair.class = Some(class(&pair.status)); + if pair.class == Some(Class::Spared) { + spared |= (1u128 << pair.qids[0]) | (1u128 << pair.qids[1]); + } + } + spared + } + fn note_interrupted(&mut self, _qid: u8, _stamp: u32) -> Interrupted { Interrupted::Exact } + fn settle_blamed_render(&mut self, qid: u8, error: Error) { + let Some(pair) = self.pair_mut(qid) else { return }; + if pair.failed { + return; + } + pair.failed = true; + if pair.class == Some(Class::Spared) { + pair.status.report_failure(error); + } else { + pair.class = Some(Class::Guilty); + pair.status.record(error); + } + } + fn settle_cancelled_renders(&mut self, _qids: u128) {} + fn rescan_compute(&mut self) -> Result { Ok(()) } + fn release_retired_compute(&mut self) {} + } + + fn vm() -> Arc { + Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap() + } + + #[test] + fn a_culprit_spared_by_a_misattributed_first_restart_turns_guilty() { + // 11-20 15:03 UTC (m4.174), the 11-19 19:12 storm's shape: c spins on 40/41, and the + // first restart blames b (44/45), whose work c starved. Nothing confirms the blame: b's + // command fails without poisoning its VM; c's work is spared. + let (c, b, x) = (vm(), vm(), vm()); + let mut queues = Cascade::new([([40, 41], &c), ([44, 45], &b), ([60, 61], &x), ([62, 63], &x)]); + assert!(!queues.restart(45, (1 << 41) | (1 << 45))); + assert!(!b.recovery_guilty() && b.get() == 0); + // The next restart blames b again with nothing of b retired: the repeat makes b guilty. + // Blame alone cannot tell a bystander starved twice from a culprit. + assert!(!queues.restart(45, 1 << 45)); + assert!(b.recovery_guilty() && b.get() != 0); + assert!(queues.restart(45, 1 << 45)); + // Then every restart blames c's queue 41 and drops its running group by exact stamp. + // The first blame on work an earlier restart spared is collateral: c fails without + // poisoning its VM, and the restart counts. + assert!(!queues.restart(41, 1 << 41)); + assert!(!c.recovery_guilty() && c.get() == 0); + // Blamed again with nothing of it retired since: the hang is c's own. + assert!(!queues.restart(41, 1 << 41)); + assert!(c.recovery_guilty()); + assert_ne!(c.get(), 0); + // From now on a restart that only drops failed c's work is forgiven. + assert!(queues.restart(41, 1 << 41)); + } + + #[test] + fn a_bystander_that_retires_between_blames_stays_collateral() { + // c is blamed first, twice; b's work is spared, then blamed while it waits behind c's. + let (c, b, x) = (vm(), vm(), vm()); + let mut queues = Cascade::new([([40, 41], &c), ([44, 45], &b), ([60, 61], &x), ([62, 63], &x)]); + queues.restart(41, 1 << 41); + queues.restart(41, 1 << 41); + assert!(c.recovery_guilty()); + queues.restart(45, 1 << 45); + assert!(!b.recovery_guilty() && b.get() == 0); + // b's next command retires: blamed again, it is collateral again, its VM unpoisoned. + queues.retire(44); + queues.restart(45, 1 << 45); + assert!(!b.recovery_guilty() && b.get() == 0); + // Blamed a third time with nothing retired since: guilty. Its client already saw a + // lost device at each blame; now its VM is poisoned too. + queues.restart(45, 1 << 45); + assert!(b.recovery_guilty()); + assert_ne!(b.get(), 0); + } + + #[test] + fn a_retirement_on_another_queue_of_the_culprit_does_not_reset_it() { + // c owns two pairs, 40/41 (spinning) and 50/51; the first restart blames b. + let (c, b, x) = (vm(), vm(), vm()); + let mut queues = Cascade::new([([40, 41], &c), ([50, 51], &c), ([44, 45], &b), ([60, 61], &x)]); + queues.restart(45, (1 << 41) | (1 << 45)); + queues.restart(41, 1 << 41); + assert!(!c.recovery_guilty()); + // c's other pair keeps retiring: the blamed pair's mark stays. + queues.retire(50); + queues.restart(41, 1 << 41); + assert!(c.recovery_guilty()); + assert_ne!(c.get(), 0); + } + + #[test] + fn a_new_owner_of_a_reused_queue_starts_with_a_fresh_collateral() { + let (c, b, d, x) = (vm(), vm(), vm(), vm()); + let mut queues = Cascade::new([([40, 41], &c), ([44, 45], &b), ([60, 61], &x), ([62, 63], &x)]); + queues.restart(45, (1 << 41) | (1 << 45)); + queues.restart(41, 1 << 41); + assert!(!c.recovery_guilty()); + // c closes without retiring anything; its pair, reused in place, is bound to d. + queues.bind(41, &d); + // A restart that blames b again spares d's work; then one blames d's queue 41. + queues.restart(45, 1 << 45); + queues.restart(41, 1 << 41); + assert!(!d.recovery_guilty() && d.get() == 0); + // A rebind for the same owner (a pool change) keeps the mark: blamed again, d is guilty. + queues.bind(41, &d); + queues.restart(45, 1 << 45); + queues.restart(41, 1 << 41); + assert!(d.recovery_guilty()); + } + + #[test] + fn the_11_19_storm_ends_with_its_culprit_guilty_before_the_limit() { + // 2026-11-19 19:12 UTC (m4.171): deqp-vk (40/41) spins. Gen 0 blamed chromium (62/63), + // gen 1 deqp, gen 2 quickshell (42/43), gens 3-7 deqp again; every one counted until + // the storm limit stopped the GPU (8 in 30 s). + let (deqp, chromium, quickshell, x) = (vm(), vm(), vm(), vm()); + let mut queues = + Cascade::new([([40, 41], &deqp), ([62, 63], &chromium), ([42, 43], &quickshell), ([60, 61], &x)]); + let mut counted = 0; + for (blamed, dropped) in [(63, 1u128 << 63), (41, 1 << 41), (42, 1 << 42)] { + counted += usize::from(!queues.restart(blamed, dropped)); + } + // chromium's and quickshell's first blames were collateral: each saw one failed command, + // and their VMs stay usable. + assert!(!chromium.recovery_guilty() && chromium.get() == 0); + assert!(!quickshell.recovery_guilty() && quickshell.get() == 0); + // deqp's second blame makes it guilty, and later restarts that drop its work are forgiven. + for _ in 3..8 { + counted += usize::from(!queues.restart(41, 1 << 41)); + } + assert!(deqp.recovery_guilty() && deqp.get() != 0); + assert_eq!(counted, 4); + } + + #[test] + fn the_m4_175_cascade_fails_its_culprit_whose_work_already_failed() { + // 2026-11-20 17:52 UTC (m4.175): deqp-vk (61/62) spins and its commands fail as listed + // ones from the first restart on. Chromium's GPU process (58/59), then its next process + // on the same pair, then a third (63/64) are blamed first. + let (chromium, chromium2, chromium3, deqp) = (vm(), vm(), vm(), vm()); + let mut queues = + Cascade::new([([58, 59], &chromium), ([61, 62], &deqp), ([63, 64], &chromium3), ([60, 65], &chromium2)]); + let mut counted = 0; + counted += usize::from(!queues.restart(59, (1 << 59) | (1 << 62))); + queues.bind(58, &chromium2); + counted += usize::from(!queues.restart(58, 1 << 58)); + // The firmware blames deqp's 62; attribution moves it to chromium's failed pair. + counted += usize::from(!queues.restart_as(62, 3 << 58, Attribution::Queues(3 << 58))); + counted += usize::from(!queues.restart(64, (1 << 62) | (1 << 64))); + // deqp's 62, blamed once (collateral), then again: guilty and failed, although every + // command of it failed already as a listed one. + counted += usize::from(!queues.restart(62, 1 << 62)); + assert!(!deqp.recovery_guilty() && deqp.get() == 0); + counted += usize::from(!queues.restart(62, 1 << 62)); + assert!(deqp.recovery_guilty()); + assert_ne!(deqp.get(), 0); + // The next restarts drop only failed deqp's work: forgiven, under the storm limit. The + // chromium processes' first blames are collateral, so the restart that attribution moved + // to chromium2's pair (its second) counts too. + assert!(queues.restart_as(62, 1 << 62, Attribution::Queues(3 << 61))); + assert!(queues.restart(62, 1 << 62)); + assert!(!chromium.recovery_guilty() && chromium.get() == 0); + assert!(!chromium3.recovery_guilty() && chromium3.get() == 0); + assert_eq!(counted, 6); + } + + #[test] + fn a_culprit_blamed_first_is_guilty_at_its_second_blame() { + // 2026-11-20 02:18 UTC (m4.173, T72 run 2): the first restart blamed deqp's 59. Nothing + // confirmed that blame, so it is collateral: one failed command, the VM stays usable. + let (deqp, b, x) = (vm(), vm(), vm()); + let mut queues = Cascade::new([([58, 59], &deqp), ([44, 45], &b), ([60, 61], &x), ([62, 63], &x)]); + assert!(!queues.restart(59, 1 << 45)); + assert!(!deqp.recovery_guilty() && deqp.get() == 0); + // Its hang comes back with nothing of it retired: the blame is its own. + assert!(!queues.restart(59, 1 << 59)); + assert!(deqp.recovery_guilty() && deqp.get() != 0); + assert!(queues.restart(59, 1 << 59)); + assert!(!b.recovery_guilty() && b.get() == 0); + } + + #[test] + fn the_oldest_running_render_is_only_suspected_at_first() { + // An innocent slow render that started its tiler just before the hung one is the oldest + // running render. The pass records only suspect it: collateral once, its VM kept. + let (slow, deqp, x) = (vm(), vm(), vm()); + let mut queues = Cascade::new([([58, 59], &slow), ([60, 61], &deqp), ([62, 63], &x), ([64, 65], &x)]); + assert!(!queues.restart_as(59, 1 << 59, Attribution::Suspects(3 << 58))); + assert!(!slow.recovery_guilty() && slow.get() == 0); + // It retires; deqp's render is the oldest running one now and is suspected twice. + queues.retire(58); + queues.restart_as(59, 1 << 61, Attribution::Suspects(3 << 60)); + assert!(!deqp.recovery_guilty()); + queues.restart_as(59, 1 << 61, Attribution::Suspects(3 << 60)); + assert!(deqp.recovery_guilty() && deqp.get() != 0); + assert!(!slow.recovery_guilty() && slow.get() == 0); + } + + #[test] + fn a_confirmed_first_blame_is_guilty_at_once() { + // Evidence (slot identity, the host's pass records or a latched MMU fault) names the VM. + let (deqp, b, x) = (vm(), vm(), vm()); + let mut queues = Cascade::new([([58, 59], &deqp), ([44, 45], &b), ([60, 61], &x), ([62, 63], &x)]); + assert!(!queues.restart_as(59, 1 << 59, Attribution::Queues(3 << 58))); + assert!(deqp.recovery_guilty() && deqp.get() != 0); + assert!(queues.restart(59, 1 << 59)); + assert!(!b.recovery_guilty() && b.get() == 0); + } + + #[test] + fn the_m4_179_bystander_blames_poison_only_the_culprit() { + // 2026-11-23 01:46:44 UTC (m4.179, #2504 hang row run 7): deqp-vk (100/101) spins. Reason + // 0, no slot keys, and each bystander's front render had its tiler start written, so no + // evidence moved the blame. Gen 21 blamed t3code's 57, gen 22 Hyprland's 37, gen 23 + // deqp's 101; both bystanders were failed as guilty and Hyprland lost the session. + let (deqp, t3code, hyprland, x) = (vm(), vm(), vm(), vm()); + let mut queues = + Cascade::new([([100, 101], &deqp), ([56, 57], &t3code), ([36, 37], &hyprland), ([60, 61], &x)]); + let mut counted = 0; + counted += usize::from(!queues.restart(57, (3 << 56) | (1 << 101))); + assert!(!t3code.recovery_guilty() && t3code.get() == 0); + // Hyprland's next frame started after that restart: nothing spared it. + queues.submit(36); + counted += usize::from(!queues.restart(37, (3 << 36) | (1 << 101))); + assert!(!hyprland.recovery_guilty() && hyprland.get() == 0); + counted += usize::from(!queues.restart(101, 3 << 100)); + assert!(!deqp.recovery_guilty()); + counted += usize::from(!queues.restart(101, 1 << 101)); + assert!(deqp.recovery_guilty() && deqp.get() != 0); + assert!(queues.restart(101, 1 << 101)); + assert!(!t3code.recovery_guilty() && t3code.get() == 0); + assert!(!hyprland.recovery_guilty() && hyprland.get() == 0); + assert_eq!(counted, 4); + } + #[test] fn unknown_25g83_keys_still_preserve_firmware_blame() { let mut host = Halted::new(false); diff --git a/drivers/gpu/drm/asahi/g17/recovery/attribution.rs b/drivers/gpu/drm/asahi/g17/recovery/attribution.rs index c9572ff4561e09..0d3ed406b69ed2 100644 --- a/drivers/gpu/drm/asahi/g17/recovery/attribution.rs +++ b/drivers/gpu/drm/asahi/g17/recovery/attribution.rs @@ -58,12 +58,20 @@ pub(crate) struct Sources { mask: u32, records: [Source; SLOTS], count: usize, + /// `reason` reads PAGE_FAULT, but no MMU fault bank holds a fault (`check_fault_banks`). + stale_fault: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Attribution { +pub(crate) enum Attribution { + /// Only the firmware's blame: unconfirmed. Firmware, + /// Evidence names these queues: slot identity, a latched fault, or a VM an earlier recovery + /// found guilty. Queues(u128), + /// The host's pass records suspect these queues (the oldest running render): unconfirmed, + /// like the firmware's blame. + Suspects(u128), NoCulprit, } @@ -106,6 +114,7 @@ impl Sources { mask, records: [Source::default(); SLOTS], count: 0, + stale_fault: false, }; for slot in 0..SLOTS { if mask & (1 << slot) == 0 { @@ -132,6 +141,40 @@ impl Sources { self.reason.or(self.record.map(|record| record.reason)) } + /// Completes the reason of `InitData::fault_sources`. M5 attribution leaves the firmware + /// reason out: its latched MMU fault register (`mmu_fault`) gives reason 3. A reason read + /// from the firmware's reason word is checked against the MMU fault banks (`banks`, read + /// while the firmware is halted) on every firmware ([`Self::check_fault_banks`]). + pub(crate) fn settle_reason(&mut self, mmu_fault: bool, banks: impl FnOnce() -> Option<[(u64, u64); 2]>) { + if self.reason.is_some() { + if let Some(banks) = banks() { + self.check_fault_banks(&banks); + } + } else if mmu_fault { + self.reason = Some(PAGE_FAULT); + } + } + + /// The firmware writes its reason word only for some restarts, and nothing clears it: after + /// a page fault, every later restart it gives no reason for still reads PAGE_FAULT + /// (2026-11-18, 25G83: a deqp-vk spin read 0 before the boot's first page fault, 3 after + /// it). A page fault keeps its access latched in an MMU fault bank until the restart, so + /// when both banks read clear the reason is an earlier restart's and this one is no page + /// fault. + fn check_fault_banks(&mut self, banks: &[(u64, u64); 2]) { + if self.reason == Some(PAGE_FAULT) + && banks.iter().all(|&(status, address)| crate::regs::decode_fault(status, address, true).is_none()) + { + kernel::pr_warn!("G17: recovery reason {} without a latched MMU fault is left over from an earlier restart\n", + PAGE_FAULT); + self.stale_fault = true; + } + } + + fn page_fault(&self) -> bool { + self.reason == Some(PAGE_FAULT) && !self.stale_fault + } + pub(super) fn attribute( &mut self, blamed: Option, @@ -148,7 +191,7 @@ impl Sources { source.started = started(qid, source.stamp); } } - if self.reason == Some(PAGE_FAULT) || self.mask.count_ones() < 2 { + if self.page_fault() || self.mask.count_ones() < 2 { return Attribution::Firmware; } let Some(blamed) = blamed else { @@ -181,20 +224,56 @@ impl Sources { /// When slot identity cannot check a timeout's blame (25G83 reads every key as 0, and a /// single-slot mask has no peer), the host's own pass records still can: a blamed render - /// that never started was starved, not hung. `culprit` names the queues of the one VM whose - /// render started and did not finish; without one the firmware's blame stands. + /// that never started was starved, not hung. `culprit` gives their attribution + /// (`Queues::render_culprit`); without one the firmware's blame stands. pub(super) fn host_fallback( &self, attribution: Attribution, - culprit: impl FnOnce() -> Option, + culprit: impl FnOnce() -> Option, ) -> Attribution { - if attribution != Attribution::Firmware || self.reason.is_none_or(|reason| reason == PAGE_FAULT) { + if attribution != Attribution::Firmware || self.reason.is_none() || self.page_fault() { + return attribution; + } + culprit().unwrap_or(Attribution::Firmware) + } + + /// A page fault's MMU record names the UAT slots of the faulting accesses. Firmware blames + /// a queue it chose, which can be a bystander's (a compute write fault blamed on a render + /// queue of another VM). When the in-flight work of those slots (`culprit`) does not include + /// the blamed queue, that work is blamed instead; without such evidence the firmware's blame + /// stands. + pub(super) fn fault_override( + &self, + attribution: Attribution, + blamed: Option, + slots: u64, + culprit: impl FnOnce(u64) -> Option, + ) -> Attribution { + if !self.page_fault() || attribution != Attribution::Firmware || slots == 0 { + return attribution; + } + let Some(blamed) = blamed else { return attribution; + }; + match culprit(slots) { + Some(qids) if qids != 0 && qids & (1u128 << blamed) == 0 => Attribution::Queues(qids), + _ => attribution, } - culprit().map_or(Attribution::Firmware, Attribution::Queues) } } +/// The QIDs of every queue with an in-flight packet in one of the UAT `slots`. `visit` reports +/// each in-flight packet as its queue's QIDs and its context ID (the UAT slot it runs in). +pub(crate) fn fault_qids(slots: u64, visit: impl FnOnce(&mut dyn FnMut(u128, u32))) -> Option { + let mut qids = 0; + visit(&mut |queue, context| { + if 1u64.checked_shl(context).is_some_and(|bit| bit & slots != 0) { + qids |= queue; + } + }); + (qids != 0).then_some(qids) +} + #[kernel::macros::kunit_tests(asahi_g17_recovery_sources)] mod tests { use super::*; @@ -251,8 +330,10 @@ mod tests { sources.reason = Some(0); let attribution = sources.attribute(Some(36), |_, _| panic!("unknown key")); assert_eq!(attribution, Attribution::Firmware); - assert_eq!(sources.host_fallback(attribution, || Some(3 << 60)), Attribution::Queues(3 << 60)); + assert_eq!(sources.host_fallback(attribution, || Some(Attribution::Suspects(3 << 60))), Attribution::Suspects(3 << 60)); assert_eq!(sources.host_fallback(attribution, || None), Attribution::Firmware); + // The host's records clear every running render (the blamed one never started). + assert_eq!(sources.host_fallback(attribution, || Some(Attribution::NoCulprit)), Attribution::NoCulprit); } #[test] @@ -290,4 +371,132 @@ mod tests { assert_eq!(sources.host_fallback(Attribution::NoCulprit, || panic!("slot evidence")), Attribution::NoCulprit); } + + #[test] + fn a_page_fault_reason_without_a_latched_fault_is_judged_like_a_timeout() { + // 2026-11-18 16:39:57 UTC: deqp-vk's spinning renders (queues 84/85, failed by the + // first restart) kept hanging the GPU; the reason word still read the page fault of + // 04:30, both banks were clear, and the firmware blamed T3 Code's queue 40, then + // Hyprland's 36. Both lost their device. + let mut sources = Sources::sample(0b10, |_| Some((0, 2))); + sources.reason = Some(PAGE_FAULT); + sources.check_fault_banks(&[(0, 0); 2]); + let attribution = sources.attribute(Some(40), |_, _| panic!("unknown key")); + assert_eq!(attribution, Attribution::Firmware); + assert_eq!(sources.host_fallback(attribution, || Some(Attribution::Queues(3 << 84))), Attribution::Queues(3 << 84)); + assert_eq!(sources.fault_override(attribution, Some(40), 0, |_| panic!("no fault")), + Attribution::Firmware); + } + + #[test] + fn only_a_reason_from_the_firmware_word_is_checked_against_the_banks() { + // Any firmware's reason word: clear banks show a left-over page fault. + let mut sources = Sources::sample(0b10, |_| Some((0, 2))); + sources.reason = Some(PAGE_FAULT); + sources.settle_reason(false, || Some([(0, 0); 2])); + assert!(sources.stale_fault); + // Unreadable banks leave it a page fault. + let mut sources = Sources::sample(0b10, |_| Some((0, 2))); + sources.reason = Some(PAGE_FAULT); + sources.settle_reason(false, || None); + assert!(sources.page_fault()); + // M5 has no reason word: its latched fault register is the page fault, never judged + // by the banks. + let mut sources = Sources::sample(0b10, |_| None); + sources.settle_reason(true, || panic!("M5 fault checked against the banks")); + assert!(sources.page_fault()); + // No reason and no latched fault stays unknown. + let mut sources = Sources::sample(0b10, |_| None); + sources.settle_reason(false, || panic!("no reason to check")); + assert_eq!(sources.reason, None); + } + + #[test] + fn a_latched_fault_in_either_bank_keeps_the_page_fault() { + // 2026-11-17 18:27:07 UTC: reason 3, bank 0 clear, bank 1 an unmapped UL1C read. + for banks in [[(0, 0), (0x84e926e311, 0x40f00003d80 >> 6)], [(0x8f0779c411, 0), (0, 0)]] { + let mut sources = Sources::sample(0b10, |_| Some((0, 2))); + sources.reason = Some(PAGE_FAULT); + sources.check_fault_banks(&banks); + assert_eq!(sources.host_fallback(Attribution::Firmware, || panic!("page fault")), + Attribution::Firmware); + } + // Clear banks change no other reason. + let mut sources = Sources::sample(0b10, |_| Some((0, 2))); + sources.reason = Some(2); + sources.check_fault_banks(&[(0, 0); 2]); + assert!(!sources.stale_fault); + } + + /// The in-flight work of 2026-11-06 12:37:58: WoW's render pair (QIDs 65 and 66, four + /// renders in context 19) and a compute test's queue 60 in context 17. + fn incident(slots: u64) -> Option { + fault_qids(slots, |visit| { + for _ in 0..4 { + visit(3 << 65, 19); + } + visit(1 << 60, 17); + }) + } + + #[test] + fn a_page_fault_in_another_vm_moves_firmware_blame() { + // Both MMU banks: write ReadOnly, units CMP(2)/CMP(0), vm_slot 17. Firmware blamed + // queue 66; slot 5's key read 0, so slot identity could not check it. + let mut sources = Sources::sample(1 << 5, |_| Some((0, 0))); + sources.reason = Some(PAGE_FAULT); + let attribution = sources.attribute(Some(66), |_, _| panic!("unknown key")); + assert_eq!(attribution, Attribution::Firmware); + let attribution = sources.host_fallback(attribution, || panic!("page fault")); + assert_eq!(sources.fault_override(attribution, Some(66), 1 << 17, incident), + Attribution::Queues(1 << 60)); + } + + #[test] + fn a_page_fault_in_the_blamed_vm_keeps_firmware_blame() { + let mut sources = Sources::sample(1 << 5, |_| Some((0, 0))); + sources.reason = Some(PAGE_FAULT); + assert_eq!(sources.fault_override(Attribution::Firmware, Some(66), 1 << 19, incident), + Attribution::Firmware); + // Both VMs faulted: the blamed queue is among the culprits. + assert_eq!(sources.fault_override(Attribution::Firmware, Some(66), (1 << 17) | (1 << 19), + incident), Attribution::Firmware); + } + + #[test] + fn a_page_fault_without_slot_evidence_keeps_firmware_blame() { + let mut sources = Sources::sample(1 << 5, |_| Some((0, 0))); + sources.reason = Some(PAGE_FAULT); + // No decodable fault in either bank (reason 3 with clear status words). + assert_eq!(sources.fault_override(Attribution::Firmware, Some(66), 0, |_| panic!("no fault")), + Attribution::Firmware); + // No in-flight work runs in the faulting slot. + assert_eq!(sources.fault_override(Attribution::Firmware, Some(66), 1 << 23, incident), + Attribution::Firmware); + // Firmware blamed no queue: the recovery table alone decides, as before. + assert_eq!(sources.fault_override(Attribution::Firmware, None, 1 << 17, |_| panic!("no blame")), + Attribution::Firmware); + } + + #[test] + fn fault_slots_never_override_a_timeout_or_slot_evidence() { + let mut sources = Sources::sample(1 << 5, |_| Some((0, 0))); + sources.reason = Some(2); + assert_eq!(sources.fault_override(Attribution::Firmware, Some(66), 1 << 17, |_| panic!("timeout")), + Attribution::Firmware); + sources.reason = Some(PAGE_FAULT); + assert_eq!(sources.fault_override(Attribution::NoCulprit, Some(66), 1 << 17, |_| panic!("slots")), + Attribution::NoCulprit); + assert_eq!(sources.fault_override(Attribution::Queues(1 << 38), Some(66), 1 << 17, + |_| panic!("slots")), Attribution::Queues(1 << 38)); + } + + #[test] + fn fault_qids_match_contexts_by_uat_slot() { + assert_eq!(incident(1 << 17), Some(1 << 60)); + assert_eq!(incident(1 << 19), Some(3 << 65)); + assert_eq!(incident(0), None); + // A context ID beyond the mask's 64 slots never matches. + assert_eq!(fault_qids(u64::MAX, |visit| visit(1 << 7, 64)), None); + } } diff --git a/drivers/gpu/drm/asahi/g17/render_resources.rs b/drivers/gpu/drm/asahi/g17/render_resources.rs index fb9f6a2bfd5042..d5396935dc21a5 100644 --- a/drivers/gpu/drm/asahi/g17/render_resources.rs +++ b/drivers/gpu/drm/asahi/g17/render_resources.rs @@ -17,28 +17,29 @@ unsafe impl crate::util::AnyBitPattern for uapi::drm_asahi_render_program {} unsafe impl crate::util::AnyBitPattern for uapi::drm_asahi_render_program_v2 {} pub(crate) struct Programs { - entries: KVec, + /// As many as userspace sends in one command: charged to it, no contiguous pages. + entries: KVVec, } impl Programs { pub(crate) fn parse(bytes: &[u8]) -> Result { let stride = size_of::(); if bytes.is_empty() || bytes.len() % stride != 0 { return Err(EINVAL); } - let mut entries = KVec::with_capacity(bytes.len() / stride, GFP_KERNEL)?; + let mut entries = KVVec::with_capacity(bytes.len() / stride, GFP_KERNEL_ACCOUNT)?; let mut reader = Reader::new(bytes); for _ in 0..bytes.len() / stride { let entry: uapi::drm_asahi_render_program = reader.read()?; Self::validate(&entry)?; - entries.push(Self::wrap(entry), GFP_KERNEL)?; + entries.push(Self::wrap(entry), GFP_KERNEL_ACCOUNT)?; } Ok(Self { entries }) } pub(crate) fn from_entries(values: &[uapi::drm_asahi_render_program]) -> Result { if values.is_empty() { return Err(EINVAL); } - let mut entries = KVec::with_capacity(values.len(), GFP_KERNEL)?; + let mut entries = KVVec::with_capacity(values.len(), GFP_KERNEL_ACCOUNT)?; for entry in values { Self::validate(entry)?; - entries.push(Self::wrap(*entry), GFP_KERNEL)?; + entries.push(Self::wrap(*entry), GFP_KERNEL_ACCOUNT)?; } Ok(Self { entries }) } @@ -54,7 +55,7 @@ impl Programs { pub(crate) fn parse_v2(bytes: &[u8]) -> Result { let stride = size_of::(); if bytes.is_empty() || bytes.len() % stride != 0 { return Err(EINVAL); } - let mut entries = KVec::with_capacity(bytes.len() / stride, GFP_KERNEL)?; + let mut entries = KVVec::with_capacity(bytes.len() / stride, GFP_KERNEL_ACCOUNT)?; let mut reader = Reader::new(bytes); for _ in 0..bytes.len() / stride { let entry: uapi::drm_asahi_render_program_v2 = reader.read()?; @@ -76,7 +77,7 @@ impl Programs { || (!scratch.enabled() && (entry.scs_layout != 0 || entry.auxiliary_allocation != 0)) { return Err(EINVAL); } - entries.push(entry, GFP_KERNEL)?; + entries.push(entry, GFP_KERNEL_ACCOUNT)?; } let programs = Self { entries }; // A render kick has one SCS layout and one intersection-table binding @@ -304,19 +305,73 @@ impl M5Policy { unsafe impl crate::util::AnyBitPattern for uapi::drm_asahi_compute_program {} pub(crate) struct ComputePrograms { - entries: KVec, + /// As many as userspace sends in one command: charged to it, no contiguous pages. + entries: KVVec, } impl ComputePrograms { pub(crate) fn parse(bytes: &[u8]) -> Result { let stride = size_of::(); if bytes.is_empty() || bytes.len() % stride != 0 { return Err(EINVAL); } - let mut entries = KVec::with_capacity(bytes.len() / stride, GFP_KERNEL)?; + let mut entries = KVVec::with_capacity(bytes.len() / stride, GFP_KERNEL_ACCOUNT)?; let mut reader = Reader::new(bytes); for _ in 0..bytes.len() / stride { let entry: uapi::drm_asahi_compute_program = reader.read()?; if entry.flags != 0 || entry.threads == 0 { return Err(EINVAL); } - entries.push(entry, GFP_KERNEL)?; + entries.push(entry, GFP_KERNEL_ACCOUNT)?; } Ok(Self { entries }) } } + +#[kunit_tests(asahi_g17_render_resources)] +mod tests { + use super::*; + + /// The largest table a command can carry (its header's size is a u16), of zeroed records. + fn largest(stride: usize) -> KVVec { + let mut bytes = KVVec::new(); + bytes + .extend_with(u16::MAX as usize / stride * stride, 0, GFP_KERNEL) + .unwrap(); + bytes + } + + #[test] + fn the_largest_legacy_render_table_is_widened_whole() { + let stride = size_of::(); + let bytes = largest(stride); + let programs = Programs::parse(&bytes).unwrap(); + assert_eq!(programs.entries.len(), bytes.len() / stride); + // Widened to the v2 records: larger than the command that carried them. + assert!( + programs.entries.len() * size_of::() + > u16::MAX as usize + ); + assert_eq!(Programs::parse(&bytes[..stride + 1]).err(), Some(EINVAL)); + assert_eq!(Programs::parse(&[]).err(), Some(EINVAL)); + } + + #[test] + fn the_largest_v2_render_table_parses() { + let stride = size_of::(); + let bytes = largest(stride); + assert_eq!(Programs::parse_v2(&bytes).unwrap().entries.len(), bytes.len() / stride); + assert_eq!(Programs::parse_v2(&bytes[..stride - 1]).err(), Some(EINVAL)); + } + + #[test] + fn the_largest_compute_table_parses() { + let stride = size_of::(); + let mut bytes = largest(stride); + let threads = core::mem::offset_of!(uapi::drm_asahi_compute_program, threads); + for record in bytes.chunks_exact_mut(stride) { + record[threads..threads + 4].copy_from_slice(&1u32.to_le_bytes()); + } + let programs = ComputePrograms::parse(&bytes).unwrap(); + assert_eq!(programs.entries.len(), bytes.len() / stride); + // A program without threads is refused, wherever it is. + let last = bytes.len() - stride; + bytes[last + threads..last + threads + 4].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!(ComputePrograms::parse(&bytes).err(), Some(EINVAL)); + } +} diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index b3a51649a7b63a..35ec330a677d7b 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -72,6 +72,16 @@ struct ComputeEntry { queue: ComputeSlot, } +/// A compute queue taken out of the registry under the device mutex. Its empty entry keeps the +/// reservation's QID until [`Backend::finish_uninstalled_compute`] drops the queue (and its +/// aliases) after that mutex is released and then cancels the reservation. +type Uninstalled = (ComputeReservation, KBox); + +/// One place per compute channel of an owner. An owner holds at most `COMPUTE_CHANNELS_MAX` +/// channels, so what its channels give up under the device mutex is kept here without +/// allocating there, and is dropped or finished only after that mutex is released. +type PerChannel = [Option; super::pairs::COMPUTE_CHANNELS_MAX]; + /// A physical compute queue behind its own lock. Publication into a bound queue takes only /// this lock; device-mutex holders take it to observe or change the queue (device mutex -> /// cell). A logical queue may keep the cell after the registry gave the queue up: the cell is @@ -80,6 +90,17 @@ struct ComputeEntry { pub(super) struct ComputeCell { #[pin] queue: kernel::sync::Mutex>>, + /// Lock-free mirror of the installed queue's QID (`u8::MAX` when empty). + qid: core::sync::atomic::AtomicU8, + /// Lock-free mirror of `(configuring, active_len, last_published)` updated while the cell + /// mutex is held, so `compute_direct()` can keep single-in-flight work on channel 0 without + /// locking sibling cells and pick the least-loaded channel without extra mutex trips. + active_len: core::sync::atomic::AtomicU32, + configuring: core::sync::atomic::AtomicBool, + last_published: core::sync::atomic::AtomicU64, + /// Lock-free mirror of [`compute::Queue::sustained`], so `compute_direct()` keeps every kick + /// of an owner whose primary channel runs short kicks on that channel without a lock. + sustained: core::sync::atomic::AtomicBool, } impl ComputeCell { @@ -87,27 +108,83 @@ impl ComputeCell { Arc::pin_init( pin_init!(Self { queue <- kernel::new_mutex!(None, "g17::ComputeCell::queue"), + qid: core::sync::atomic::AtomicU8::new(u8::MAX), + active_len: core::sync::atomic::AtomicU32::new(0), + configuring: core::sync::atomic::AtomicBool::new(false), + last_published: core::sync::atomic::AtomicU64::new(0), + sustained: core::sync::atomic::AtomicBool::new(false), }), GFP_KERNEL, ) } + pub(super) fn qid(&self) -> Option { + let qid = self.qid.load(Ordering::Acquire); + (qid != u8::MAX).then_some(qid) + } + + fn sync_stats(&self, queue: Option<&compute::Queue>) { + match queue { + Some(queue) => { + self.active_len + .store(queue.active_len() as u32, Ordering::Release); + self.configuring + .store(queue.configuring(), Ordering::Release); + self.last_published + .store(queue.last_published(), Ordering::Release); + self.sustained.store(queue.sustained(), Ordering::Release); + } + None => { + self.active_len.store(0, Ordering::Release); + self.configuring.store(false, Ordering::Release); + self.last_published.store(0, Ordering::Release); + self.sustained.store(false, Ordering::Release); + } + } + } + + /// Lock-free routing hint `(configuring, active_len, last_published)`. + pub(super) fn load_hint(&self) -> (bool, u32, u64) { + ( + self.configuring.load(Ordering::Acquire), + self.active_len.load(Ordering::Acquire), + self.last_published.load(Ordering::Acquire), + ) + } + + /// Lock-free hint: this cell's queue runs sustained heavy work ([`compute::Queue::sustained`]). + pub(super) fn sustained(&self) -> bool { + self.sustained.load(Ordering::Acquire) + } + /// The installed queue, locked; None once the registry gave it up. pub(super) fn lock(&self) -> Option> { - QueueGuard::new(self.queue.lock()) + QueueGuard::new(self, self.queue.lock()) } } /// A locked installed queue. pub(super) struct QueueGuard<'a> { + cell: &'a ComputeCell, queue: core::ptr::NonNull, _guard: kernel::sync::MutexGuard<'a, Option>>, } impl<'a> QueueGuard<'a> { - fn new(mut guard: kernel::sync::MutexGuard<'a, Option>>) -> Option { + fn new( + cell: &'a ComputeCell, + mut guard: kernel::sync::MutexGuard<'a, Option>>, + ) -> Option { let queue = core::ptr::NonNull::from((*guard).as_deref_mut()?); - Some(Self { queue, _guard: guard }) + Some(Self { cell, queue, _guard: guard }) + } +} + +impl Drop for QueueGuard<'_> { + fn drop(&mut self) { + // SAFETY: `_guard` drops after `Drop::drop`, so `self.queue` remains locked and valid. + let queue = unsafe { self.queue.as_ref() }; + self.cell.sync_stats(Some(queue)); } } @@ -148,17 +225,32 @@ impl ComputeSlot { } /// Gives the queue up to the caller, which drops it outside the cell lock. fn take(&mut self) -> Option> { - self.0.queue.lock().take() + let mut guard = self.0.queue.lock(); + let queue = guard.take(); + self.0.qid.store(u8::MAX, Ordering::Release); + self.0.sync_stats(None); + queue } fn put(&mut self, queue: Option>) { - let old = core::mem::replace(&mut *self.0.queue.lock(), queue); + let qid = queue.as_ref().map_or(u8::MAX, |queue| queue.qid()); + let old = { + let mut guard = self.0.queue.lock(); + self.0.qid.store(qid, Ordering::Release); + self.0.sync_stats(queue.as_deref()); + core::mem::replace(&mut *guard, queue) + }; drop(old); } } impl Drop for ComputeSlot { fn drop(&mut self) { - let queue = self.0.queue.lock().take(); + let queue = { + let mut guard = self.0.queue.lock(); + let queue = guard.take(); + self.0.sync_stats(None); + queue + }; drop(queue); } } @@ -182,7 +274,6 @@ pub(super) struct Registry { completion_cursor: usize, /// Control word of each completion-ring slot as of the last scan that read it. completion_seen: KVVec, - worker_deferred: Option, teardown: super::teardown::Pending, } @@ -240,29 +331,359 @@ impl Registry { } seen }, - worker_deferred: Some(DeferredBatch::worker()?), teardown: super::teardown::Pending::new()?, }) } pub(super) fn compute(&self, owner: u64) -> Option> { + self.compute_primary(owner).or_else(|| { + self.compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .find(|queue| queue.owner() == Some(owner)) + }) + } + + pub(super) fn compute_primary(&self, owner: u64) -> Option> { + self.compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .find(|queue| queue.owner() == Some(owner) && queue.is_primary()) + } + + pub(super) fn compute_for_packet( + &self, + owner: u64, + packet: &Arc, + ) -> Option> { self.compute .iter() .flatten() .filter_map(|entry| entry.queue.as_deref()) - .find(|queue| queue.owner() == Some(owner)) + .find(|queue| queue.owner() == Some(owner) && queue.owns_packet(packet)) } - pub(super) fn compute_mut(&mut self, owner: u64) -> Option> { - self.compute(owner) + pub(super) fn compute_for_packet_mut( + &mut self, + owner: u64, + packet: &Arc, + ) -> Option> { + self.compute_for_packet(owner, packet) } - /// The cell of `owner`'s bound queue, which its publisher may lock without the device mutex. - pub(super) fn compute_cell(&self, owner: u64) -> Option> { - self.compute.iter().flatten().find_map(|entry| { - entry.queue.as_deref()?.owner().filter(|bound| *bound == owner)?; - Some(entry.queue.0.clone()) - }) + /// Count and used channel-index bitmask of `owner`'s bound compute channels. + fn compute_channels_of(&self, owner: u64) -> (usize, u8) { + let mut count = 0usize; + let mut mask = 0u8; + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + { + count += 1; + let idx = queue.channel_index(); + if idx < 8 { + mask |= 1u8 << idx; + } + } + (count, mask) + } + + fn next_sibling_index(&self, owner: u64, limit: u8) -> Option { + let (count, mask) = self.compute_channels_of(owner); + if count == 0 || count >= usize::from(limit) { + return None; + } + (1..limit).find(|idx| mask & (1u8 << idx) == 0) + } + + /// Where `owner`'s next sibling channel would come from, in the order [`Self::rebind_compute`] + /// gives a primary binding its channel: an idle reusable queue whose populated pool serves the + /// owner's VM and fits, else a vacant reusable queue no other owner is re-arming, else a fresh + /// QID, else an idle reusable queue whose pool still serves another VM (an exited owner's, + /// say), given back first while no other pool release is in flight. Only + /// [`compute::Queue::reusable`] queues whose scheduler release is not in flight qualify, so a + /// channel with an owner, work, a pending pool release or a closing context is never taken, + /// and neither is an open owner's idle channel, which only a primary binding may share. The + /// longest released queue goes first. None keeps the owner on its bound channels. + fn sibling_source( + &self, + owner: u64, + context: &Arc, + required: super::freelist::ComputeCapacity, + ) -> Option { + let teardown = &self.teardown; + let vm = context.vm(); + let (mut warm, mut vacant, mut foreign) = (None, None, None); + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.reusable()) + .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound))) + { + let best = if queue.pool_vacant() { + if !queue.rearm_open(owner) { + continue; + } + &mut vacant + } else if queue.pool_serves(vm) { + if queue.needs_fresh_backing() || !queue.pool_fits(required) || !queue.has_ring() { + continue; + } + &mut warm + } else { + &mut foreign + }; + let key = (queue.released_at(), queue.qid()); + if best.is_none_or(|old| key < old) { + *best = Some(key); + } + } + if let Some((_, qid)) = warm { + return Some(SiblingSource::Warm(qid)); + } + if let Some((_, qid)) = vacant { + return Some(SiblingSource::Vacant(qid)); + } + if self.qids.compute_fits(self.admission.render_demand(0)) { + return Some(SiblingSource::Fresh); + } + // A pool release in flight ends in a vacant queue; give back one at a time. + if self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .any(|queue| queue.vacancy_pending()) + { + return None; + } + foreign.map(|(_, qid)| SiblingSource::Foreign(qid)) + } + + /// Whether a sibling channel for `owner` is available now ([`Self::sibling_source`]). + fn has_compute_sibling_headroom( + &self, + owner: u64, + context: &Arc, + required: super::freelist::ComputeCapacity, + ) -> bool { + self.sibling_source(owner, context, required).is_some() + } + + /// Whether `owner` benefits from acquiring another compute channel now: its primary channel + /// runs sustained heavy work ([`compute::Queue::sustained`]), all currently bound channels are + /// busy with at least [`super::pairs::SIBLING_MIN_IN_FLIGHT`] kicks in flight between them, no + /// replay is pending on any of them, and a sibling source exists + /// ([`Self::has_compute_sibling_headroom`]). A primary channel streaming short kicks never + /// brings up a sibling: its ring runs them faster than several QIDs would. + fn wants_compute_sibling( + &self, + owner: u64, + context: &Arc, + limit: u8, + required: super::freelist::ComputeCapacity, + ) -> bool { + if limit <= 1 || self.next_sibling_index(owner, limit).is_none() { + return false; + } + let mut sustained_primary = false; + let mut all_busy = true; + let mut in_flight = 0usize; + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + { + if queue.has_replays() { + return false; + } + if queue.is_primary() { + sustained_primary = queue.sustained(); + } + if queue.active_len() == 0 && !queue.configuring() { + all_busy = false; + } + in_flight += queue.active_len(); + } + if !sustained_primary || !all_busy || !super::pairs::overlaps(in_flight) { + return false; + } + self.has_compute_sibling_headroom(owner, context, required) + } + + /// Binds a warm sibling source ([`SiblingSource::Warm`]) as an additional compute channel of + /// `owner`. Returns `Ok(Some(true))` if bound, `Ok(Some(false))` if no warm queue is ready (a + /// vacant queue to re-arm, a fresh QID or another VM's idle queue to give back is built or + /// released off the device mutex, [`Backend::try_add_compute_sibling`]), or `Ok(None)` if no + /// sibling slot is needed. + fn bind_reusable_sibling( + &mut self, + owner: u64, + context: &Arc, + limit: u8, + required: super::freelist::ComputeCapacity, + ) -> Result> { + let Some(channel_index) = self.next_sibling_index(owner, limit) else { + return Ok(None); + }; + let Some(SiblingSource::Warm(qid)) = self.sibling_source(owner, context, required) else { + return Ok(Some(false)); + }; + self.compute_queue_mut(qid) + .ok_or(EIO)? + .bind_sibling(owner, context.clone(), channel_index)?; + Ok(Some(true)) + } + + /// The installed compute queue with QID `qid`. + fn compute_queue_mut(&mut self, qid: u8) -> Option> { + self.compute + .iter_mut() + .flatten() + .filter_map(|entry| entry.queue.as_deref_mut()) + .find(|queue| queue.qid() == qid) + } + + /// Gives back the idle reusable queue `qid`, whose pool serves another VM, for fresh backing: + /// the next pool pass releases its pool ([`Self::vacate_idle_pools`]) and leaves it vacant, + /// ready to re-arm for the VM that asked. + fn give_back_foreign(&mut self, qid: u8) -> Result { + self.compute_queue_mut(qid).ok_or(EIO)?.require_fresh_backing(); + Ok(()) + } + + /// Picks the bound compute channel of `owner` for `packet`. A command with cross-queue input + /// sources always takes the primary channel, so a chain of semaphore hops between queues + /// stays on one ring per queue. Dependent commands stay on the sole active channel when only + /// one is active so the implicit parent covers them without cross-channel barriers. Other + /// commands take the primary channel unless it runs sustained heavy work + /// ([`compute::Queue::sustained`]) and enough kicks are in flight to overlap + /// ([`super::pairs::overlaps`]); then they spread across the least-loaded channel (oldest + /// `last_published` breaks ties). + fn select_compute_channel(&self, owner: u64, packet: &super::job::Packet) -> Option { + let primary = self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .find(|queue| queue.owner() == Some(owner) && queue.is_primary()) + .map(|queue| (queue.qid(), queue.sustained())); + if let Some((qid, _)) = primary.filter(|_| packet.completion.sources().is_some()) { + return Some(qid); + } + if packet.order.wait_through[1].is_some() { + let mut active_qid = None; + let mut active_channels = 0usize; + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + { + if queue.active_len() != 0 || queue.configuring() { + active_qid = Some(queue.qid()); + active_channels += 1; + } + } + if active_channels == 1 { + return active_qid; + } + } + if let Some((qid, false)) = primary { + return Some(qid); + } + let in_flight: usize = self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + .map(|queue| queue.active_len()) + .sum(); + if let Some((qid, _)) = primary.filter(|_| !super::pairs::overlaps(in_flight)) { + return Some(qid); + } + self.compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + .min_by_key(|queue| { + ( + queue.configuring(), + queue.active_len(), + queue.last_published(), + queue.channel_index(), + ) + }) + .map(|queue| queue.qid()) + } + + /// Appends covered active compute kicks from every compute channel of `owner` other than + /// `exclude_qid` into `frontier`. On boards whose firmware waits require visible completion + /// (`require_visible`), any covered kick on another channel without it returns `EAGAIN`. + pub(super) fn append_compute_prefix( + &self, + owner: u64, + exclude_qid: Option, + packet: &Arc, + recovery_state: u32, + require_visible: bool, + frontier: &mut super::dependency::Frontier, + ) -> Result { + let through = packet.order.wait_through[1]; + if through.is_none() { + return Ok(()); + } + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner) && Some(queue.qid()) != exclude_qid) + { + if let Some(dep) = queue.dependency_checked( + owner, + packet.completion.status(), + through, + recovery_state, + require_visible, + )? { + frontier.insert(0, dep).map_err(|_| EAGAIN)?; + } + } + Ok(()) + } + + /// The cells of `owner`'s bound compute channels, indexed by `channel_index`, which its + /// publisher may lock one at a time without the device mutex. + pub(super) fn compute_cells( + &self, + owner: u64, + ) -> [Option>; super::pairs::COMPUTE_CHANNELS_MAX] { + let mut cells = [const { None }; super::pairs::COMPUTE_CHANNELS_MAX]; + for entry in self.compute.iter().flatten() { + let Some(queue) = entry.queue.as_deref() else { + continue; + }; + if queue.owner() == Some(owner) { + let index = usize::from(queue.channel_index()); + if index < cells.len() { + cells[index] = Some(entry.queue.0.clone()); + } + } + } + cells } /// An installed idle queue keeps its original QID and backing. Mapping a @@ -276,8 +697,19 @@ impl Registry { pub(super) fn rebind_compute(&mut self, owner: u64, context: &Arc, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { admission.check()?; if let Some(queue) = self.compute(owner) { - return Ok(if queue.matches(owner, queue.qid(), context)? { - if queue.pool_fits(required) { Rebind::Done } else { Rebind::Grow } + let matches = queue.matches(owner, queue.qid(), context)?; + let fits = queue.pool_fits(required); + drop(queue); + let all_fit = fits + && self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + .all(|queue| queue.pool_fits(required)); + return Ok(if matches { + if all_fit { Rebind::Done } else { Rebind::Grow } } else { Rebind::Fresh }); @@ -288,7 +720,7 @@ impl Registry { if let Some(rebind) = self.bind_reusable(owner, context, required, admission)? { return Ok(rebind); } - if self.qids.compute_fits(self.admission.queues() as usize) { + if self.compute_qid_fits() { return Ok(Rebind::Fresh); } if self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()) @@ -311,13 +743,7 @@ impl Registry { .min_by_key(|(key, _)| *key) .map(|(_, qid)| qid); if let Some(qid) = foreign { - self.compute - .iter_mut() - .flatten() - .filter_map(|entry| entry.queue.as_deref_mut()) - .find(|queue| queue.qid() == qid) - .ok_or(EIO)? - .require_fresh_backing(); + self.give_back_foreign(qid)?; return Err(ENOSPC); } let idle = self @@ -353,9 +779,28 @@ impl Registry { Ok(self.bind_reusable(owner, context, required, admission)?.unwrap_or(Rebind::Fresh)) } + /// Whether a fresh compute QID fits beside current render demand, either + /// directly or after cancelling one idle unpublished render spare. + fn compute_qid_fits(&self) -> bool { + let demand = self.admission.render_demand(0); + self.qids.compute_fits(demand) + || (self.has_cancelable_render_spare().unwrap_or(false) + && self.qids.compute_fits_with_reclaim(demand, 2)) + } + /// Whether `owner` can bind a channel now, without changing any binding. Owner 0 asks /// only whether some channel is free for a new owner. fn compute_readiness(&self, owner: u64, query: Option<(&Arc, super::freelist::ComputeCapacity)>) -> Readiness { + if owner != 0 + && self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .any(|queue| queue.owner() == Some(owner) && queue.spared_pending()) + { + return Readiness::Progress; + } if let (Some((context, required)), Some(queue)) = (query, self.compute(owner).filter(|_| owner != 0)) { return if queue.spared_pending() { Readiness::Progress @@ -378,7 +823,7 @@ impl Registry { (queue.reusable() || queue.shareable() || queue.can_rearm()) && !queue.context().is_some_and(|bound| teardown.releasing(bound)) }); - if available || self.qids.compute_fits(self.admission.queues() as usize) { + if available || self.compute_qid_fits() { Readiness::Ready } else { Readiness::Channel @@ -432,7 +877,7 @@ impl Registry { qid: u8, pages: crate::g17::freelist::Pages, ring: compute::DescriptorRing, - ) -> Result { + ) -> Result<(super::freelist::PoolDescriptor, Option)> { let mut queue = self .compute .iter_mut() @@ -443,6 +888,13 @@ impl Registry { queue.rearm(pages, ring) } + /// Reserves the vacant queue `qid` for `owner`'s re-arm, as [`Self::bind_reusable`] does for a + /// primary binding. + fn reserve_rearm(&mut self, qid: u8, owner: u64) -> Result { + self.compute_queue_mut(qid).ok_or(EIO)?.reserve_rearm(owner); + Ok(()) + } + /// Ends `owner`'s re-arm reservation of `qid` when it did not bind the queue. pub(super) fn release_rearm(&mut self, qid: u8, owner: u64) { if let Some(mut queue) = self.compute.iter_mut().flatten() @@ -453,7 +905,15 @@ impl Registry { } } - pub(super) fn bind_rearmed(&mut self, qid: u8, owner: u64, context: &Arc) -> Result { + /// Binds the re-armed queue `qid` as `owner`'s compute channel `channel_index`: its primary + /// (0) or a sibling. + pub(super) fn bind_rearmed( + &mut self, + qid: u8, + owner: u64, + context: &Arc, + channel_index: u8, + ) -> Result { let teardown = &self.teardown; let mut queue = self .compute @@ -466,7 +926,11 @@ impl Registry { if queue.context().is_some_and(|bound| teardown.releasing(bound)) { return Err(EAGAIN); } - queue.bind_owner(owner, context.clone()) + if channel_index == 0 { + queue.bind_owner(owner, context.clone()) + } else { + queue.bind_sibling(owner, context.clone(), channel_index) + } } /// Delay before retrying pools a turn could not release. @@ -581,16 +1045,26 @@ impl Registry { } pub(super) fn reserve_compute(&mut self, owner: u64) -> Result { - if owner == 0 - || self.compute.iter().flatten().any(|entry| { - entry - .queue - .as_deref() - .map_or(entry.reservation.owner == owner, |queue| { - queue.owner() == Some(owner) - }) - }) - { + self.reserve_compute_channel(owner, 1) + } + + pub(super) fn reserve_compute_channel( + &mut self, + owner: u64, + limit: u8, + ) -> Result { + if owner == 0 || limit == 0 { + return Err(EINVAL); + } + let mut owned = 0usize; + for entry in self.compute.iter().flatten() { + match entry.queue.as_deref() { + None if entry.reservation.owner == owner => return Err(EINVAL), + Some(queue) if queue.owner() == Some(owner) => owned += 1, + _ => {} + } + } + if owned >= usize::from(limit) { return Err(EINVAL); } let slot = self @@ -600,12 +1074,20 @@ impl Registry { .ok_or_else(|| self.compute_admission_error( crate::g17::capacity::refused(crate::g17::capacity::Site::ComputeSlots)))?; let identity = self.identities.reserve(1)?.start; - let queues = self.admission.queues() as usize; + let (reclaimable, installed) = self.reclaimable_render_slots()?; + let qids = &mut self.qids; let id = self - .qids - .reserve_for(identity, DataMaster::Compute, Some(FIRST_COMPUTE_QID), queues) + .admission + .reserve_compute_with_budget(reclaimable, installed, |demand| { + let id = qids.reserve_for( + identity, + DataMaster::Compute, + Some(FIRST_COMPUTE_QID), + demand, + )?; + Ok((id, qids.render_pair_fits(), qids.render_pair_capacity())) + }) .map_err(|error| self.compute_admission_error(error))?; - self.note_build_room(); let reservation = ComputeReservation { slot, id, owner }; self.compute[slot] = Some(ComputeEntry { reservation, @@ -614,6 +1096,20 @@ impl Registry { Ok(reservation) } + /// Reserves a fresh compute channel, storing any cancelled unpublished + /// render spare in `reclaimed` so the caller drops its backing off-lock. + fn reserve_compute_reclaiming( + &mut self, + owner: u64, + reclaimed: &mut Option, + ) -> Result { + let demand = self.admission.render_demand(0); + if !self.qids.compute_fits(demand) && self.qids.compute_fits_with_reclaim(demand, 2) { + *reclaimed = self.reclaim_unused_render_spare(None, true)?; + } + self.reserve_compute(owner) + } + fn reserved(&mut self, reservation: ComputeReservation) -> Result<&mut ComputeEntry> { let entry = self .compute @@ -653,21 +1149,108 @@ impl Registry { Ok(()) } - pub(super) fn release_compute(&mut self, owner: u64) -> Result { - let Some(slot) = self.compute.iter().position(|entry| { - entry + /// Releases idle sibling channels of `owner` before primary pool growth. Returns `Err(EAGAIN)` + /// while any sibling still has active, replaying or configuring work. Each unpublished + /// sibling queue goes to `retired`, which starts empty, for off-lock alias drop and QID + /// cancellation; on failure it still holds every queue taken before it. + fn drain_compute_siblings( + &mut self, + owner: u64, + retired: &mut PerChannel, + ) -> Result { + let mut channel = 0; + for slot in 0..self.compute.len() { + let is_sibling = self.compute[slot] .as_ref() .and_then(|entry| entry.queue.as_deref()) - .is_some_and(|queue| queue.owner() == Some(owner)) - }) else { - return Ok(()); - }; - let entry = self.compute[slot].as_mut().ok_or(EIO)?; - let unpublished = entry.queue.as_deref_mut().ok_or(EIO)?.release_owner()?; - if unpublished { - self.qids.cancel_unpublished(entry.reservation.id)?; - self.compute[slot] = None; - self.note_build_room(); + .is_some_and(|queue| queue.owner() == Some(owner) && !queue.is_primary()); + if !is_sibling { + continue; + } + let busy = self.compute[slot] + .as_ref() + .and_then(|entry| entry.queue.as_deref()) + .is_some_and(|queue| { + queue.active_len() != 0 || queue.has_replays() || queue.configuring() + }); + if busy { + return Err(EAGAIN); + } + // Refuse before releasing a channel whose queue would have no place in `retired`. + let place = retired.get_mut(channel).filter(|place| place.is_none()).ok_or(EIO)?; + channel += 1; + let entry = self.compute[slot].as_mut().ok_or(EIO)?; + let unpublished = entry.queue.as_deref_mut().ok_or(EIO)?.release_owner()?; + if unpublished { + *place = entry.queue.take().map(|queue| (entry.reservation, queue)); + } + } + Ok(()) + } + + /// Rolls back `owner`'s unpublished bindings to `context` on every channel, siblings before + /// the primary for deterministic teardown. Each displaced binding goes to `bindings` and each + /// cancelled queue to `retired`, both starting empty, for the caller to drop (and finish) + /// after releasing the device mutex; on failure they still hold everything taken before it. + fn rollback_unpublished_compute( + &mut self, + owner: u64, + context: &Arc, + retired: &mut PerChannel, + bindings: &mut PerChannel, + ) -> Result { + let mut channel = 0; + for primary_pass in [false, true] { + for slot in 0..self.compute.len() { + let matches = self.compute[slot] + .as_ref() + .and_then(|entry| entry.queue.as_deref()) + .is_some_and(|queue| { + queue.owner() == Some(owner) && queue.is_primary() == primary_pass + }); + if !matches { + continue; + } + // Refuse before rolling back a channel whose binding or queue would have no place. + let binding = bindings.get_mut(channel).filter(|place| place.is_none()).ok_or(EIO)?; + let place = retired.get_mut(channel).filter(|place| place.is_none()).ok_or(EIO)?; + channel += 1; + let entry = self.compute[slot].as_mut().ok_or(EIO)?; + let (cancel, replaced) = entry + .queue + .as_deref_mut() + .ok_or(EIO)? + .rollback_unpublished(owner, context)?; + *binding = replaced; + if cancel { + *place = entry.queue.take().map(|queue| (entry.reservation, queue)); + } + } + } + Ok(()) + } + + pub(super) fn release_compute(&mut self, owner: u64) -> Result { + // Release sibling channels before the primary channel for deterministic teardown order. + for primary_pass in [false, true] { + for slot in 0..self.compute.len() { + let matches = self.compute[slot] + .as_ref() + .and_then(|entry| entry.queue.as_deref()) + .is_some_and(|queue| { + queue.owner() == Some(owner) && queue.is_primary() == primary_pass + }); + if !matches { + continue; + } + let entry = self.compute[slot].as_mut().ok_or(EIO)?; + let unpublished = entry.queue.as_deref_mut().ok_or(EIO)?.release_owner()?; + if unpublished { + self.qids.cancel_unpublished(entry.reservation.id)?; + self.compute[slot] = None; + self.note_build_room(); + } + } } Ok(()) } @@ -697,6 +1280,20 @@ pub(super) enum Rebind { Fresh, } +/// Where an owner's next sibling compute channel comes from ([`Registry::sibling_source`]). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(super) enum SiblingSource { + /// An idle reusable queue whose populated pool serves the owner's VM and fits: bind it. + Warm(u8), + /// A vacant reusable queue no other owner is re-arming: re-arm it with fresh backing. + Vacant(u8), + /// No reusable queue to bind or re-arm, but a fresh QID fits. + Fresh, + /// An idle reusable queue whose pool still serves another VM: give it back, so it is vacated + /// and can be re-armed. + Foreign(u8), +} + #[kunit_tests(asahi_g17_uninstalled_cleanup)] mod uninstalled_cleanup_tests { @@ -733,11 +1330,15 @@ pub(super) struct Backend { backlog: core::sync::atomic::AtomicU32, compute_backlog: core::sync::atomic::AtomicU32, closed: core::sync::atomic::AtomicBool, - /// The cell of the compute queue this owner last published to under the device mutex, - /// with the shared compute objects mapped into its VM. Direct publication revalidates the - /// binding under the cell lock; a stale cell only sends the packet back to that path. + /// The cells of the compute channels this owner last published to under the device mutex, + /// indexed by `channel_index`, with the shared compute objects mapped into its VM. Direct + /// publication revalidates each binding under its own cell lock; a stale cache only sends + /// the packet back to the device-mutex path. #[pin] - direct: kernel::sync::Mutex>>, + direct: kernel::sync::Mutex<[Option>; super::pairs::COMPUTE_CHANNELS_MAX]>, + /// Earliest monotonic timestamp (ns) at which `compute_direct()` may yield again to try + /// adding another sibling channel after a headroom miss. + sibling_backoff_until: core::sync::atomic::AtomicU64, /// The channel a prepared packet is about to publish into. Its claim keeps the idle /// channel from being shared away between prepare_job and run_job. #[pin] @@ -757,6 +1358,8 @@ pub(super) struct Backend { /// Render pairs this owner may hold, fixed at creation with its scheduler's /// credits and its render pool's sizing. pairs: u8, + /// Physical compute channels this owner may hold (up to three on M5 Pro, one elsewhere). + compute_channels: u8, } impl Backend { @@ -776,6 +1379,7 @@ impl Backend { let (lease, uat, pool, qos, execution, slot, share, render_id) = loop { let observed = shared.queues.observe(); let lease = shared.preparations.enter(true)?; + let mut reclaimed = None; let mut state = shared.state.lock(); let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; if shared.crashed.load(core::sync::atomic::Ordering::Acquire) { @@ -786,14 +1390,44 @@ impl Backend { // notifies the queue domain observed above, so the creator's own // wait would end at once and admission would spin on the device // mutex for the whole wait, starving the queues it waits for. - let admission = &firmware.queues.admission; - // Installed compute channels narrow render's QIDs: every open - // logical queue keeps a dedicated render pair within reach. - if !admission.has_room() - || !firmware.queues.qids.render_fits(admission.queues() as usize + 1) + // + // Installed compute channels and non-reclaimable sibling render + // pairs narrow render's QIDs: every open logical queue keeps a + // dedicated first render pair within reach, while idle unpublished + // siblings give way before refusing a new queue. + if !firmware.queues.admission.has_room() + || !firmware + .queues + .qids + .render_fits(firmware.queues.admission.render_demand(1)) { return Err(super::capacity::refused(super::capacity::Site::LogicalQueues)); } + let (mut reclaimable, mut installed) = firmware.queues.reclaimable_render_slots()?; + let mut render_capacity = firmware.queues.qids.render_pair_capacity(); + if firmware + .queues + .admission + .needs_warmed_sibling_reclaim(render_capacity, reclaimable) + { + reclaimed = firmware.queues.reclaim_unused_render_sibling()?; + if reclaimed.is_none() { + return Err(super::capacity::refused(super::capacity::Site::LogicalQueues)); + } + render_capacity = firmware.queues.qids.render_pair_capacity(); + (reclaimable, installed) = firmware.queues.reclaimable_render_slots()?; + if firmware + .queues + .admission + .needs_warmed_sibling_reclaim(render_capacity, reclaimable) + { + drop(state); + drop(reclaimed); + drop(lease); + continue; + } + } + let admission = &firmware.queues.admission; // A context that takes its render pool identity now is refused here, holding // nothing, when render graphs kept until the firmware stops hold the rest. let render_id = if shared.variant.render_id_at_create { @@ -806,18 +1440,31 @@ impl Backend { // G17P queues of one VM join its live execution context (super::exec_share). let joined = if firmware.uat.is_m5() { None } else { super::exec_share::join(vm) }; let attempt = if let Some((execution, share)) = joined { - Ok((execution, admission.reserve_queue()?, Some(share))) + Ok(( + execution, + admission.try_reserve_queue_reclaiming( + render_capacity, + reclaimable, + installed, + )?, + Some(share), + )) } else if firmware.uat.execution_contexts_used() < crate::mmu::MAX_EXECUTION_CONTEXTS { - // Creators hold the device mutex, so neither check above can - // have changed; the slot only fails on a broken invariant. - let slot = admission.reserve_queue()?; + // Creators hold the device mutex, and try_reserve_queue_reclaiming + // reclaims unbuilt/parked/reusable siblings and re-checks demand + // atomically against render_capacity before taking a slot. + let slot = admission.try_reserve_queue_reclaiming( + render_capacity, + reclaimable, + installed, + )?; firmware.uat.new_execution_context(vm, super::channel::control_witnessed()).map(|execution| (execution, slot, None)) } else { Err(ENOSPC) }; match attempt { Ok((execution, slot, share)) => { - break ( + let result = ( lease, firmware.uat.clone(), firmware.pool.clone(), @@ -826,7 +1473,10 @@ impl Backend { slot, share, render_id, - ) + ); + drop(state); + drop(reclaimed); + break result; } Err(error) if error == ENOSPC => { // Every open queue holds one context; this one holds no @@ -838,6 +1488,7 @@ impl Backend { } drop(render_id); drop(state); + drop(reclaimed); drop(lease); // Nothing is visible yet: a signalled creator restarts. if kernel::current!().signal_pending() { @@ -894,13 +1545,18 @@ impl Backend { backlog: core::sync::atomic::AtomicU32::new(0), compute_backlog: core::sync::atomic::AtomicU32::new(0), closed: core::sync::atomic::AtomicBool::new(false), - direct <- kernel::new_mutex!(None, "g17::Backend::direct"), + direct <- kernel::new_mutex!( + [const { None }; super::pairs::COMPUTE_CHANNELS_MAX], + "g17::Backend::direct" + ), + sibling_backoff_until: core::sync::atomic::AtomicU64::new(0), claimed <- kernel::new_mutex!(None, "g17::Backend::claimed"), outer_compute <- kernel::new_mutex!(None, "g17::Backend::outer_compute"), outer_render <- kernel::new_mutex!(None, "g17::Backend::outer_render"), admission, direct_slot: core::sync::atomic::AtomicU32::new(0), pairs: super::pairs::per_owner(), + compute_channels: super::pairs::compute_channels_per_owner(), }), GFP_KERNEL, )?, @@ -1058,12 +1714,30 @@ impl Backend { Ok(()) } + /// Finishes every queue in `retired` as [`Self::finish_uninstalled_compute`] finishes one, + /// going on past a failure so no other reservation stays behind; returns the first failure. + fn finish_retired_compute(&self, retired: &mut PerChannel) -> Result { + retired.iter_mut().fold(Ok(()), |result, item| { + let finished = self.finish_uninstalled_compute(item.take()); + result.and(finished) + }) + } + fn grow_compute(&self, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { admission.check()?; { let state = self.shared.state.lock(); let firmware = state.as_ref().ok_or(ENODEV)?; - if firmware.queues.compute(self.owner).is_some_and(|queue| queue.pool_fits(required)) { + if firmware.queues.compute(self.owner).is_some() + && firmware + .queues + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(self.owner)) + .all(|queue| queue.pool_fits(required)) + { return Ok(()); } } @@ -1080,6 +1754,7 @@ impl Backend { // Growth waits for this queue's retirement and for firmware to consume the pool // release; both are progress the event worker reports. let observed = self.shared.progress.observe(); + let mut retired_siblings: PerChannel = Default::default(); let result = (|| { let mut state = self.shared.state.lock(); admission.check()?; @@ -1087,7 +1762,10 @@ impl Backend { if !lease.is_current() { return Err(EAGAIN); } if self.shared.crashed.load(Ordering::Acquire) { return Err(EIO); } firmware.scan_compute(None, &mut deferred)?; - let mut queue = firmware.queues.compute_mut(self.owner).ok_or(EAGAIN)?; + // Release sibling channels before growing the primary channel so undersized + // sibling pools are detached and later re-acquired at the grown capacity. + firmware.queues.drain_compute_siblings(self.owner, &mut retired_siblings)?; + let mut queue = firmware.queues.compute_primary(self.owner).ok_or(EAGAIN)?; if queue.pool_fits(required) { return Ok(None); } if growth.is_none() { let notify = queue.begin_growth(&firmware.init, required)?; @@ -1101,6 +1779,7 @@ impl Backend { } queue.finish_growth(&firmware.init, &mut pages, &mut alias).map(Some) })(); + self.finish_retired_compute(&mut retired_siblings)?; deferred.finish(); match result { Ok(old) => { drop(old); return Ok(()); } @@ -1141,12 +1820,14 @@ impl Backend { } /// Re-arms the vacant queue `qid` reserved for this owner with fresh zeroed backing, built - /// without the device mutex, and binds it. Some(true): bound; Some(false): retry (the - /// preparation epoch changed or the queue is no longer re-armable); None: no memory for - /// the backing now. + /// without the device mutex, and binds it as compute channel `channel_index` (0: the primary; + /// a sibling only while that index is still the owner's next free one). Some(true): bound; + /// Some(false): retry (the preparation epoch changed, the queue is no longer re-armable or + /// the sibling index was taken); None: no memory for the backing now. fn rearm_vacant( &self, qid: u8, + channel_index: u8, required: super::freelist::ComputeCapacity, alloc: &super::object::Allocator<'_>, objects: &Arc, @@ -1173,16 +1854,21 @@ impl Backend { // rearm(). let ready = firmware.queues.compute.iter().flatten() .filter_map(|entry| entry.queue.as_deref()) - .any(|queue| queue.qid() == qid && queue.can_rearm() && queue.rearm_open(self.owner)); + .any(|queue| queue.qid() == qid && queue.can_rearm() && queue.rearm_open(self.owner)) + && (channel_index == 0 + || firmware.queues.next_sibling_index(self.owner, self.compute_channels) + == Some(channel_index)); if !ready { drop(state); return Ok(Some(false)); } - let descriptor = match firmware.queues.rearm_compute(qid, pages, ring) { + let (descriptor, vacated) = match firmware.queues.rearm_compute(qid, pages, ring) { Err(error) if error == EAGAIN => return Ok(Some(false)), result => result?, }; // The firmware consumed this slot's release before the backing // was dropped; the row is rewritten before the queue is kicked. firmware.init.install_compute_pool(descriptor)?; - firmware.queues.bind_rearmed(qid, self.owner, &self.context)?; + firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)?; + drop(state); + drop(vacated); Ok(Some(true)) } @@ -1204,6 +1890,7 @@ impl Backend { let observed = self.shared.channels.observe(); let lease = self.shared.preparations.enter_until(admission)?; let dev = self.shared.drm()?; + let mut reclaimed = None; let (uat, objects, reservation) = { let mut state = self.shared.state.lock(); admission.check()?; @@ -1230,24 +1917,33 @@ impl Backend { Rebind::Grow => { drop(state); drop(lease); return self.grow_compute(required, admission); } Rebind::Rearm(qid) => (firmware.uat.clone(), firmware.pool.clone(), Err(qid)), Rebind::Fresh => { - let reservation = match firmware.queues.reserve_compute(self.owner) { + let reservation = match firmware + .queues + .reserve_compute_reclaiming(self.owner, &mut reclaimed) + { Ok(reservation) => reservation, Err(error) if error == EAGAIN => { // All physical channels are occupied. Retain their // USC backing for exact-retirement handoff; releasing // it cannot create a QID and forces fresh allocation. drop(state); + drop(reclaimed); drop(lease); self.wait_channels(observed, admission, false)?; continue; } Err(error) if error == ENOSPC => { - let reclaimed = firmware.queues.reclaim_unused_render_spare(None, true)?; + let extra = if reclaimed.is_some() { + None + } else { + firmware.queues.reclaim_unused_render_spare(None, true)? + }; drop(state); - if reclaimed.is_none() { + drop(reclaimed); + if extra.is_none() { return Err(error); } - drop(reclaimed); + drop(extra); continue; } Err(error) => return Err(error), @@ -1256,6 +1952,7 @@ impl Backend { } } }; + drop(reclaimed); let alloc = super::object::Allocator { dev: &dev, uat: &uat, @@ -1265,7 +1962,8 @@ impl Backend { Err(qid) => { // bind_reusable reserved `qid` for this owner: any outcome but binding it // ends the reservation, so another owner may re-arm it. - let result = self.rearm_vacant(qid, required, &alloc, &objects, &lease, admission); + let result = + self.rearm_vacant(qid, 0, required, &alloc, &objects, &lease, admission); if !matches!(result, Ok(Some(true))) { if let Some(firmware) = self.shared.state.lock().as_deref_mut() { firmware.queues.release_rearm(qid, self.owner); @@ -1355,6 +2053,176 @@ impl Backend { if result != Err(EAGAIN) { return result; } } } + + /// Best-effort acquisition of an additional compute channel with its own dedicated compute + /// pool for a multi-channel M5 owner, from the source [`Registry::sibling_source`] names: a + /// warm reusable queue is bound at once, a vacant one is re-armed with fresh backing and + /// bound as [`Self::rearm_vacant`] re-arms a primary's, a fresh QID gets a new queue, and an + /// idle queue still holding another VM's pool is given back for the next attempt. An owner + /// waiting for its first channel goes first. Never blocks or fails the submission if no + /// sibling is available. + fn try_add_compute_sibling( + &self, + required: super::freelist::ComputeCapacity, + admission: &Admission<'_>, + ) -> Result { + if self.compute_channels <= 1 || !self.context.is_m5() { + return Ok(false); + } + admission.check()?; + let lease = self.shared.preparations.enter_until(admission)?; + let dev = self.shared.drm()?; + let (uat, objects, source, channel_index) = { + let mut state = self.shared.state.lock(); + admission.check()?; + let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; + if !lease.is_current() || self.shared.crashed.load(Ordering::Acquire) { + return Ok(false); + } + if self.admission_open().is_err() + || self.shared.channels.has_waiters() + || !firmware.queues.wants_compute_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + ) + { + return Ok(false); + } + let Some(channel_index) = firmware + .queues + .next_sibling_index(self.owner, self.compute_channels) + else { + return Ok(false); + }; + let source = match firmware.queues.sibling_source(self.owner, &self.context, required) { + None => return Ok(false), + Some(SiblingSource::Warm(_)) => { + return Ok(firmware.queues.bind_reusable_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + )? == Some(true)); + } + Some(SiblingSource::Foreign(qid)) => { + firmware.queues.give_back_foreign(qid)?; + drop(state); + // A full event pass releases its pool; a later kick re-arms it. + self.shared.queue_events(); + return Ok(false); + } + Some(SiblingSource::Vacant(qid)) => { + firmware.queues.reserve_rearm(qid, self.owner)?; + Err(qid) + } + Some(SiblingSource::Fresh) => match firmware + .queues + .reserve_compute_channel(self.owner, self.compute_channels) + { + Ok(reservation) => Ok(reservation), + Err(_) => return Ok(false), + }, + }; + ( + firmware.uat.clone(), + firmware.pool.clone(), + source, + channel_index, + ) + }; + let alloc = super::object::Allocator { + dev: &dev, + uat: &uat, + }; + let reservation = match source { + Ok(reservation) => reservation, + Err(qid) => { + // The reservation ends with any outcome but binding the queue. + let result = self.rearm_vacant( + qid, + channel_index, + required, + &alloc, + &objects, + &lease, + admission, + ); + let bound = matches!(result, Ok(Some(true))); + if !bound { + if let Some(firmware) = self.shared.state.lock().as_deref_mut() { + firmware.queues.release_rearm(qid, self.owner); + } + } + drop(lease); + // As for a fresh sibling, a failed re-arm leaves the owner on its bound channels. + admission.check()?; + return Ok(bound); + } + }; + let built = (|| { + let pool = compute::PoolBacking::new( + &alloc, + reservation.id, + required, + self.context.vm().memory_client(), + )?; + { + let mut state = self.shared.state.lock(); + admission.check()?; + let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; + if !lease.is_current() { + return Err(EAGAIN); + } + self.admission_open()?; + firmware.queues.reserved(reservation)?; + firmware.init.install_compute_pool(pool.pool_descriptor()?)?; + } + let backing = compute::Backing::new(&alloc, pool)?; + let queue = compute::Queue::new_channel( + &alloc, + &objects, + backing, + self.owner, + self.context.clone(), + self.shared.variant.pointers, + self.shared.operand_state, + self.shared.m5_board, + self.shared.variant.compute, + true, + self.shared.variant.mcache, + channel_index, + )?; + Ok(KBox::new(queue, GFP_KERNEL)?) + })(); + let (mut built, build_error) = match built { + Ok(queue) => (Some(queue), None), + Err(error) => (None, Some(error)), + }; + let result = { + let mut state = self.shared.state.lock(); + let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; + if let Err(error) = admission.check() { + Err(error) + } else if !lease.is_current() || self.admission_open().is_err() { + Err(EAGAIN) + } else if let Some(error) = build_error { + Err(error) + } else { + firmware.queues.install_compute(reservation, &mut built) + } + }; + drop(built); + if result.is_err() { + let mut state = self.shared.state.lock(); + if let Some(firmware) = (*state).as_deref_mut() { + let _ = firmware.queues.cancel_compute(reservation); + } + } + drop(lease); + Ok(result.is_ok()) + } } /// One device transaction can fail each retained kick once and then retire it. @@ -1383,7 +2251,7 @@ impl DeferredBatch { }; /// Reused by the sole event work item; no allocation on a completion pass. - fn worker() -> Result { + pub(super) fn worker() -> Result { Self::with_capacity(2 * QIDS * Self::DEPTH, QIDS) } /// One publication can quarantine only its selected physical queue/pair. @@ -1492,6 +2360,10 @@ impl DeferredBatch { pub(super) fn pending(&self) -> usize { self.values.len() } + /// Whether the preallocated batch still has room for at least `need` entries. + pub(super) fn has_room(&self, need: usize) -> bool { + self.values.capacity().saturating_sub(self.values.len()) >= need + } /// Called only after releasing the device mutex. pub(super) fn finish(&mut self) { use super::completion::Deferred; @@ -1536,6 +2408,7 @@ struct ComputeHost<'a> { regs: &'a crate::regs::G17Resources, port: &'a super::port::Port, outer: Option>, + m5_outer: Option>>, /// M5: the shared compute ring's room check of this publication, by priority. outer_cursors: Option<(u8, [u32; 3])>, effort: &'a mut super::power::Effort, @@ -1590,19 +2463,38 @@ impl compute::Host for ComputeHost<'_> { // Every M5 pipe-2 doorbell (0x83) is noted in the firmware's submission history first, // as the render doorbell notes its pair. if self.init.is_m5() && message >> super::MSG_TYPE_SHIFT == 0x83 && message & 3 == 2 { - if let Err(error) = self.init.note_m5_submission_history(1) { + if let Some(guard) = self.m5_outer.as_mut() { + if let Err(error) = self.port.note_m5_submission_history_locked(guard, 1) { + pr_warn!("asahi: M5 submission history skipped: {:?}\n", error); + } + // Drop `m5_outer` before ringing the mailbox doorbell so competing M5 submitters + // do not wait behind mailbox I/O. + self.m5_outer = None; + } else if let Err(error) = self.init.note_m5_submission_history(1) { pr_warn!("asahi: M5 submission history skipped: {:?}\n", error); } } self.port.notify(message) } fn note_submission(&mut self) -> Result { + let now = super::now_ns(); self.shared.note_submitter(); + self.port.note_gpu_activity(); self.shared.note_gpu_activity(); self.effort.submit(); - self.effort.note_waiters(super::now_ns(), super::fence::waiters()); + self.effort.note_waiters(now, super::fence::waiters()); + self.effort.note_compute_waiters(now, super::fence::compute_waiters()); self.effort.note_bound(self.shared.feed.busy_run()); - super::Firmware::apply_shared_effort(self.init, self.effort, self.port, super::power::FULL_EFFORT) + if self.effort.bound() { + self.port.lift_busy_if_below_top(now); + } + super::Firmware::apply_shared_effort( + self.shared, + self.init, + self.effort, + self.port, + super::power::FULL_EFFORT, + ) } fn submit_m5(&mut self, submission: &super::fw::m5::queue::HardwareSubmission) -> Result { // Compute only (publication and installation); render pairs submit through @@ -1616,6 +2508,9 @@ impl compute::Host for ComputeHost<'_> { struct DirectHost<'a> { port: &'a super::port::Port, outer: Option>, + m5_outer: Option<&'a mut super::initdata::OuterClaim>, + m5_outer_guard: Option>>, + m5: bool, generation: u64, } impl compute::Host for DirectHost<'_> { @@ -1646,18 +2541,44 @@ impl compute::Host for DirectHost<'_> { fn register_queue(&mut self, _queue: &super::fw::kick::KsmQueue) -> Result { Err(EAGAIN) } - fn publish_outer(&mut self, _priority: u8, slot: &super::fw::channels::WorkSlot) -> Result { + fn publish_outer(&mut self, priority: u8, slot: &super::fw::channels::WorkSlot) -> Result { + if self.m5 { + let claim = self.m5_outer.as_deref_mut().ok_or(EIO)?; + let guard = self + .m5_outer_guard + .get_or_insert_with(|| self.port.m5_outer_lock()); + return self + .port + .publish_m5_compute_locked(guard, priority, claim, slot) + .map(|_| ()); + } self.port.publish_compute(self.outer.take().ok_or(EIO)?, slot).map(|_| ()) } fn notify(&mut self, message: u64) -> Result { + if self.m5 && message >> super::MSG_TYPE_SHIFT == 0x83 && message & 3 == 2 { + let guard = self + .m5_outer_guard + .get_or_insert_with(|| self.port.m5_outer_lock()); + if let Err(error) = self.port.note_m5_submission_history_locked(guard, 1) { + pr_warn!("asahi: M5 submission history skipped: {:?}\n", error); + } + // Drop `m5_outer` before ringing the mailbox doorbell so competing M5 submitters + // do not wait behind mailbox I/O. + self.m5_outer_guard = None; + } self.port.notify(message) } fn note_submission(&mut self) -> Result { Ok(()) } - fn submit_m5(&mut self, _submission: &super::fw::m5::queue::HardwareSubmission) -> Result { - // M5 never publishes without the device mutex (see compute_direct). - Err(EINVAL) + fn submit_m5(&mut self, submission: &super::fw::m5::queue::HardwareSubmission) -> Result { + if !self.m5 { + return Err(EINVAL); + } + let guard = self + .m5_outer_guard + .get_or_insert_with(|| self.port.m5_outer_lock()); + self.port.submit_m5_work_held_locked(guard, submission) } } @@ -1666,16 +2587,53 @@ impl super::Firmware { fn publish_compute(&mut self, owner: u64, packet: Arc, dependencies: &[super::fw::kick::KickDependency], deferred: &mut DeferredBatch) -> Result { + self.publish_compute_on(owner, None, packet, dependencies, deferred) + } + + pub(super) fn publish_compute_on( + &mut self, + owner: u64, + target_qid: Option, + packet: Arc, + dependencies: &[super::fw::kick::KickDependency], + deferred: &mut DeferredBatch, + ) -> Result { + let qid = match target_qid { + Some(qid) => qid, + None => self.queues.select_compute_channel(owner, &packet).ok_or(EIO)?, + }; + let mut combined = super::dependency::Frontier::new(); + for dependency in dependencies { + combined.insert(0, *dependency)?; + } + if target_qid.is_none() && packet.order.wait_through[1].is_some() { + let recovery_state = super::recovery::Memory::recovery_state(&self.init)?; + let require_visible = self + .primary + .state + .shared + .m5_board + .is_some_and(|board| board.completion_inputs()); + self.queues.append_compute_prefix( + owner, + Some(qid), + &packet, + recovery_state, + require_visible, + &mut combined, + )?; + } if packet.completion.sources().is_some() { - self.publish_compute_inputs(owner, packet, dependencies, deferred) + self.publish_compute_inputs(owner, qid, packet, combined.as_slice(), deferred) } else { - self.publish_compute_raw(owner, packet, dependencies, &[], deferred) + self.publish_compute_raw(owner, qid, packet, combined.as_slice(), &[], deferred) } } #[inline(never)] - fn publish_compute_inputs(&mut self, owner: u64, packet: Arc, - dependencies: &[super::fw::kick::KickDependency], deferred: &mut DeferredBatch) -> Result + fn publish_compute_inputs(&mut self, owner: u64, target_qid: u8, + packet: Arc, dependencies: &[super::fw::kick::KickDependency], + deferred: &mut DeferredBatch) -> Result { if self.recovery.pending() || super::recovery::Memory::recovery_state(&self.init)? != 0 { return Err(EAGAIN); @@ -1704,6 +2662,13 @@ impl super::Firmware { let Some((sequence, dependency, stamp_va, event_slot, hold, same_execution)) = found else { return Err(EAGAIN); }; + if m5 && dependency.qid() == target_qid { + // Same physical QID in this epoch: the queue's implicit parent already strictly + // orders earlier kicks on this QID; drop the self-reader hold and skip adding a + // duplicate explicit barrier. + drop(hold); + continue; + } waited |= 1u128 << dependency.qid(); if m5 || same_execution { merged.insert(sequence, dependency)?; @@ -1722,7 +2687,7 @@ impl super::Firmware { } holds.push(hold, GFP_KERNEL)?; } - let result = self.publish_compute_raw(owner, packet.clone(), merged.as_slice(), + let result = self.publish_compute_raw(owner, target_qid, packet.clone(), merged.as_slice(), native.as_slice(), deferred); if packet.is_published() { for queue in self.queues.compute.iter().flatten() @@ -1741,6 +2706,7 @@ impl super::Firmware { fn publish_compute_raw( &mut self, owner: u64, + target_qid: u8, packet: Arc, dependencies: &[super::fw::kick::KickDependency], native: &[super::sync_input::NativeWait], @@ -1749,28 +2715,13 @@ impl super::Firmware { if self.recovery.pending() { return Err(EAGAIN); } - // No descriptor, accounting or inner producer changes precede this - // reservation; dropping it unused returns the work-ring slot. M5 compute takes its - // slot on the work ring M5 render shares, under this mutex (InitData::publish_work): - // a full ring is refused here, before a queue install or kick changes any state. - let mut outer_cursors = None; - let outer = if self.init.is_m5() { - let priority = packet.context.policy().priority(); - let Some(cursors) = self.init.m5_compute_room(priority)? else { - return Err(EAGAIN); - }; - outer_cursors = Some((priority, cursors)); - None - } else { - Some(self.port.reserve_compute(packet.context.policy().priority())?) - }; let queues = &mut self.queues; let mut queue = queues .compute .iter_mut() .flatten() .filter_map(|entry| entry.queue.as_deref_mut()) - .find(|queue| queue.owner() == Some(owner)) + .find(|queue| queue.qid() == target_qid && queue.owner() == Some(owner)) .ok_or(EIO)?; // The first command after an owner change waits while the scheduler // the queue was bound to is being released: a live previous owner may @@ -1781,12 +2732,29 @@ impl super::Firmware { { return Err(EAGAIN); } + // No descriptor, accounting or inner producer changes precede this + // reservation; dropping it unused returns the work-ring slot. M5 compute + // serializes the shared outer ring and host-port updates under `m5_outer` + // (after the compute cell lock, matching direct M5 publishers). + let m5_outer = self.init.is_m5().then(|| self.port.m5_outer_lock()); + let mut outer_cursors = None; + let outer = if self.init.is_m5() { + let priority = packet.context.policy().priority(); + let Some(cursors) = self.init.m5_compute_room(priority)? else { + return Err(EAGAIN); + }; + outer_cursors = Some((priority, cursors)); + None + } else { + Some(self.port.reserve_compute(packet.context.policy().priority())?) + }; let mut host = ComputeHost { shared: &self.primary.state.shared, init: &self.init, regs: &self.bridge.regs, port: &self.port, outer, + m5_outer, outer_cursors, effort: &mut self.effort, qids: &mut queues.qids, @@ -1829,12 +2797,31 @@ impl Registry { /// objects mapped into its VM, and its queue bound to `context` with a /// pool that fits and no spared witness to release. fn compute_bound(&self, owner: u64, context: &Arc, required: super::freelist::ComputeCapacity) -> Result { - let Some(queue) = self.compute(owner) else { + let Some(primary) = self.compute_primary(owner) else { return Ok(false); }; - Ok(!queue.spared_pending() - && queue.pool_fits(required) - && queue.matches(owner, queue.qid(), context)?) + if primary.spared_pending() + || !primary.pool_fits(required) + || !primary.matches(owner, primary.qid(), context)? + { + return Ok(false); + } + drop(primary); + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner) && !queue.is_primary()) + { + if queue.spared_pending() + || !queue.pool_fits(required) + || !queue.matches(owner, queue.qid(), context)? + { + return Ok(false); + } + } + Ok(true) } fn release_compute_witness( @@ -1844,24 +2831,26 @@ impl Registry { owner: u64, deferred: &mut DeferredBatch, ) -> Result { - let Some(mut queue) = self + let mut pending = false; + let recovery_state = super::recovery::Memory::recovery_state(init)?; + for mut queue in self .compute .iter_mut() .flatten() .filter_map(|entry| entry.queue.as_deref_mut()) - .find(|queue| queue.owner() == Some(owner)) - else { - return Ok(false); - }; - if !queue.spared_pending() { - return Ok(false); + .filter(|queue| queue.owner() == Some(owner)) + { + if !queue.spared_pending() { + continue; + } + queue.release_witnessed( + recovery_state, + |owner| port.qos_complete(&[owner]), + &mut |event| deferred.push(event), + )?; + pending |= queue.spared_pending(); } - queue.release_witnessed( - super::recovery::Memory::recovery_state(init)?, - |owner| port.qos_complete(&[owner]), - &mut |event| deferred.push(event), - )?; - Ok(queue.spared_pending()) + Ok(pending) } fn fail_compute_vm( @@ -1888,25 +2877,66 @@ impl Registry { } } +/// Post-scan compute state collected while `scan_compute_summary` already holds each cell lock, +/// allowing the event worker to avoid redundant full-registry cell scans. +#[derive(Clone, Copy, Default)] +pub(super) struct ComputeScan { + pub(super) in_flight: bool, + pub(super) replay: bool, + pub(super) polling: bool, +} + impl super::Firmware { + fn scan_compute(&mut self, masks: Option<[u64; 2]>, deferred: &mut DeferredBatch) -> Result { + self.scan_compute_summary(masks, deferred).map(|_| ()) + } + /// Latch one shared snapshot for all selected queues before settling any VM. /// A later queue's exact success in this batch wins over a peer's failure. - fn scan_compute(&mut self, masks: Option<[u64; 2]>, deferred: &mut DeferredBatch) -> Result { + fn scan_compute_summary( + &mut self, + masks: Option<[u64; 2]>, + deferred: &mut DeferredBatch, + ) -> Result { let state = super::recovery::Memory::recovery_state(&self.init)?; let generation = self.recovery.generation(); let registry = &mut self.queues; registry.observations.clear(); let mut requested = false; + let mut retire_mask = 0u128; + let mut terminal_mask = 0u128; + let mut witness_mask = 0u128; + let mut in_flight_mask = 0u128; + let mut replay_mask = 0u128; + let mut polling_mask = 0u128; // Every queue's pending identities are staged, not only the ones this batch // retires: the scan passes each new record once, and a queue retired by a later // batch finds its observation already latched. - for queue in registry - .compute - .iter() - .flatten() - .filter_map(|entry| entry.queue.as_deref()) - { - requested |= queue.request_observations(&mut registry.observations)?; + for (index, entry) in registry.compute.iter().enumerate() { + let Some(queue) = entry.as_ref().and_then(|entry| entry.queue.as_deref()) else { + continue; + }; + let bit = 1u128.checked_shl(index as u32).unwrap_or(0); + let slot_requested = queue.request_observations(&mut registry.observations)?; + requested |= slot_requested; + if slot_requested || queue.needs_scan_retire(masks) { + retire_mask |= bit; + } + if queue.has_terminal() { + terminal_mask |= bit; + } + if queue.awaiting_witness() { + witness_mask |= bit; + } + if queue.in_flight() { + in_flight_mask |= bit; + } + if queue.replay_commands() != 0 { + replay_mask |= bit; + } + if queue.retirement_polling() || queue.pool_release_pending() { + polling_mask |= bit; + } } // Completion records are appended in order: fold only the records written since // the previous scan. A request whose stamp already covers it has its record in the @@ -1928,14 +2958,21 @@ impl super::Firmware { let port = &self.port; let retired = deferred.pending(); let mut freed = false; - for mut queue in registry - .compute - .iter_mut() - .flatten() - .filter_map(|entry| entry.queue.as_deref_mut()) - { + let mut pending = retire_mask; + while pending != 0 { + let index = pending.trailing_zeros() as usize; + let bit = 1u128 << index; + pending &= !bit; + let Some(mut queue) = registry.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + else { + continue; + }; let busy = !queue.channel_free(); - queue.latch_observations(&mut registry.observations)?; + if requested { + queue.latch_observations(&mut registry.observations)?; + } queue.retire( masks, generation, @@ -1944,35 +2981,79 @@ impl super::Firmware { &mut |event| deferred.push(event), )?; freed |= busy && queue.channel_free(); + if queue.has_terminal() { + terminal_mask |= bit; + } + if queue.awaiting_witness() { + witness_mask |= bit; + } + if queue.in_flight() { + in_flight_mask |= bit; + } else { + in_flight_mask &= !bit; + } + if queue.replay_commands() != 0 { + replay_mask |= bit; + } else { + replay_mask &= !bit; + } + if queue.retirement_polling() || queue.pool_release_pending() { + polling_mask |= bit; + } else { + polling_mask &= !bit; + } } // All compute observations in this batch are latched before a VM // failure can settle its render peers. Exact successes win first. - for index in 0..self.queues.compute.len() { - let terminal = self.queues.compute[index] - .as_mut() - .and_then(|entry| entry.queue.as_deref_mut()) - .and_then(|mut queue| queue.take_terminal()); - if let Some((status, error)) = terminal { - status.record(error); - self.settle_render_vm(&status, error, deferred)?; - self.queues.fail_compute_vm(&status, error, deferred)?; + let had_terminal = terminal_mask != 0; + if had_terminal { + for index in 0..self.queues.compute.len() { + let terminal = self.queues.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + .and_then(|mut queue| queue.take_terminal()); + if let Some((status, error)) = terminal { + status.record(error); + self.settle_render_vm(&status, error, deferred)?; + self.queues.fail_compute_vm(&status, error, deferred)?; + } } } - let port = &self.port; - let registry = &mut self.queues; - for mut queue in registry - .compute - .iter_mut() - .flatten() - .filter_map(|entry| entry.queue.as_deref_mut()) - { - let busy = !queue.channel_free(); - queue.release_witnessed( - state, - |owner| port.qos_complete(&[owner]), - &mut |event| deferred.push(event), - )?; - freed |= busy && queue.channel_free(); + if witness_mask != 0 || had_terminal { + let port = &self.port; + let registry = &mut self.queues; + for (index, entry) in registry.compute.iter_mut().enumerate() { + let bit = 1u128.checked_shl(index as u32).unwrap_or(0); + if !had_terminal && (witness_mask & bit) == 0 { + continue; + } + let Some(mut queue) = entry.as_mut().and_then(|entry| entry.queue.as_deref_mut()) + else { + continue; + }; + let busy = !queue.channel_free(); + queue.release_witnessed( + state, + |owner| port.qos_complete(&[owner]), + &mut |event| deferred.push(event), + )?; + freed |= busy && queue.channel_free(); + if queue.in_flight() { + in_flight_mask |= bit; + } else { + in_flight_mask &= !bit; + } + if queue.replay_commands() != 0 { + replay_mask |= bit; + } else { + replay_mask &= !bit; + } + if queue.retirement_polling() || queue.pool_release_pending() { + polling_mask |= bit; + } else { + polling_mask &= !bit; + } + } } // Wake only the admission waits this batch can end. The fences gate // scheduler entities alone; their callbacks never take the device mutex. @@ -1983,7 +3064,11 @@ impl super::Firmware { if deferred.pending() != retired { shared.progress.notify(); } - Ok(()) + Ok(ComputeScan { + in_flight: in_flight_mask != 0, + replay: replay_mask != 0, + polling: polling_mask != 0, + }) } } @@ -2032,63 +3117,285 @@ impl Backend { } } - /// Steady-state publication into this owner's bound channel without the device mutex: only - /// the channel's own lock and the port's small locks are taken, and nothing device-wide is - /// scanned. None leaves the packet untouched for the device-mutex path, which owns binding, - /// first installation, input sources, render prefixes, replay and recovery. + /// Resolves same-VM cross-QID M5 compute sources lock-free from each producer's + /// `PublishedSource` snapshot under a live preparation lease. Sources already published on + /// `target_qid` in `generation` are ordered by this queue's implicit parent, so they skip the + /// duplicate explicit barrier, `Hold`, and `firmware_consumer` mark while still checking + /// `source_status()` (error propagation) and epoch validity. Any unpublished, errored, + /// cancelled, or epoch-mismatched source returns `None` so the device-mutex path handles it. + fn resolve_direct_sources( + &self, + port: &super::port::Port, + generation: u64, + target_qid: u8, + sources: &super::sync_input::Sources, + ) -> Option<(super::dependency::Frontier, KVec, u64)> { + sources.check().ok()?; + let mut frontier = super::dependency::Frontier::new(); + let mut holds = KVec::new(); + let mut cross_qid_mask = 0u64; + for (idx, source) in sources.sources.iter().enumerate() { + if source.submission.source_status().ok()? { + continue; + } + let published = source.submission.published_source(generation)?; + if published.dependency.qid() == target_qid { + if port.recovery_state().ok()? != 0 || port.generation() != generation { + return None; + } + if source.submission.source_status().ok()? { + continue; + } + if !source.submission.has_published_epoch(generation) { + return None; + } + continue; + } + let hold = super::sync_input::Hold::new(&published.readers).ok()?; + // Re-validate after taking the binding loan so the producer cannot have retired, + // faulted, cancelled, or crossed an epoch before `readers` became non-zero. + if port.recovery_state().ok()? != 0 || port.generation() != generation { + return None; + } + if source.submission.source_status().ok()? { + continue; + } + if !source.submission.has_published_epoch(generation) { + return None; + } + frontier + .insert(published.published, published.dependency) + .ok()?; + holds.push(hold, GFP_KERNEL).ok()?; + cross_qid_mask |= 1u64 << idx; + } + Some((frontier, holds, cross_qid_mask)) + } + + /// Whether `packet` may run on, or bring up, a sibling compute channel of this owner: only an + /// independent command (no in-queue barrier, no cross-queue input sources) of an owner whose + /// primary channel runs sustained heavy work (`primary_sustained`, asked last, from + /// [`compute::Queue::sustained`]). Every other command streams down the primary ring: short + /// kicks run faster there than spread over several QIDs, and a semaphore hop between queues + /// stays on one ring per queue. + fn fans_out( + &self, + packet: &super::job::Packet, + primary_sustained: impl FnOnce() -> bool, + ) -> bool { + self.compute_channels > 1 + && packet.order.wait_through[1].is_none() + && packet.completion.sources().is_none() + && primary_sustained() + } + + /// Steady-state publication into this owner's bound channel(s) without the device mutex: only + /// one channel's own lock at a time and the port's small locks are taken, and nothing + /// device-wide is scanned. On M5, same-VM cross-QID compute sources whose producers have + /// published their kick metadata also resolve directly, always onto the primary channel. + /// None leaves the packet untouched for the device-mutex path, which owns binding, first + /// installation, cross-channel barriers, non-M5 native-wait sources, render prefixes, replay + /// and recovery. fn compute_direct( &self, packet: &Arc, required: super::freelist::ComputeCapacity, deferred: &mut DeferredBatch, ) -> Option { - // M5 compute is a shared-ring submission on the ring M5 render shares: it is published only - // under the device mutex, never through the classic compute ring producer. - if self.context.is_m5() - || packet.completion.sources().is_some() + let m5 = self.context.is_m5(); + let has_sources = packet.completion.sources().is_some(); + let bound_count = self.context.compute_binding_count() as usize; + if (has_sources && !m5) || self.context.render_seen() + || bound_count == 0 + || bound_count > super::pairs::COMPUTE_CHANNELS_MAX + || (bound_count > 1 && packet.order.wait_through[1].is_some()) || packet.cancel_requested() || packet.completion.status().get() != 0 || self.admission_open().is_err() { return None; } - let cell = self.direct.lock().clone()?; + let cells = self.direct.lock().clone(); + let cached_count = cells.iter().filter(|cell| cell.is_some()).count(); + if cached_count != bound_count || cells[0].is_none() { + return None; + } + let target_qid = cells[0].as_ref()?.qid()?; let lease = self.shared.preparations.try_enter().ok()?; let port = self.shared.port(&lease)?; if self.shared.crashed.load(Ordering::Acquire) || port.recovery_state().ok()? != 0 { return None; } + let generation = port.generation(); + let (direct_frontier, direct_holds, cross_qid_mask) = + if let Some(sources) = packet.completion.sources() { + self.resolve_direct_sources(port, generation, target_qid, sources)? + } else { + (super::dependency::Frontier::new(), KVec::new(), 0) + }; + // Only an independent kick without input sources of an owner whose primary channel runs + // sustained heavy work may leave the primary ring ([`Self::fans_out`]); the primary + // cell's lock-free hint answers that without a lock. + let primary = cells[0].as_ref()?; + let fans_out = self.fans_out(packet, || primary.sustained()); + let can_add_sibling = fans_out + && cached_count < usize::from(self.compute_channels) + && now_ns() >= self.sibling_backoff_until.load(Ordering::Relaxed); + // Lock-free channel selection using each cell's atomic `(configuring, active_len, + // last_published)` mirror: + // - A kick that does not fan out, or finds primary channel 0 idle (`active == 0 && + // !configuring`), routes straight to channel 0 without locking any sibling cell mutexes + // at all, keeping short kicks, input sources and single-in-flight work streaming down + // the primary ring with zero extra mutex overhead. + // - Otherwise, scan bound cells' atomic hints lock-free. While fewer than + // `SIBLING_MIN_IN_FLIGHT` kicks are in flight the kick queues behind them on channel 0 + // ([`super::pairs::overlaps`]); from there it takes the least-loaded channel (oldest + // `last_published` breaks ties), falling back to add a sibling only when every bound + // channel already has >= 1 kick in flight (`all_busy`). + let target_idx = if cached_count == 1 || !fans_out { + 0 + } else { + let (primary_configuring, primary_active, _) = primary.load_hint(); + if primary_active == 0 && !primary_configuring { + 0 + } else { + let mut best: Option<(usize, (bool, u32, u64, usize))> = None; + let mut all_busy = true; + let mut in_flight = 0usize; + for (idx, cell) in cells.iter().enumerate() { + let Some(cell) = cell else { + continue; + }; + let (configuring, active, last_published) = cell.load_hint(); + if active == 0 && !configuring { + all_busy = false; + } + in_flight += active as usize; + let key = (configuring, active, last_published, idx); + if best.is_none_or(|(_, best_key)| key < best_key) { + best = Some((idx, key)); + } + } + if !super::pairs::overlaps(in_flight) { + 0 + } else if can_add_sibling && all_busy { + return None; + } else { + best?.0 + } + } + }; + let target_cell = cells[target_idx].as_ref()?; // Full effort is applied by the device-mutex path when it is not already. if !port.note_submission() { return None; } + self.shared.note_submitter(); self.shared.note_gpu_activity(); match packet.completion.work_state().ok()?.acquire(crate::g17::job::Engine::Compute) { Ok(_) => {} Err(error) if error == EBUSY => return None, Err(error) => return Some(Err(error)), } - let mut queue = cell.lock()?; - if !queue.installed() - || queue.spared_pending() - || !queue.pool_fits(required) - || queue.pending_switch_from().is_some() - || !matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)) - || !lease.is_current() - { - return None; + let priority = packet.context.policy().priority(); + // Reuse the M5 outer claim already reserved during prepare_compute() when present and + // matching priority, avoiding a redundant Port::m5_outer lock trip and unused-claim drop + // notification; otherwise reserve before locking the compute cell. + let (mut m5_outer, from_held) = if m5 { + let claimed = { + let mut held = self.outer_compute.lock(); + if held.as_ref().is_some_and(|claim| { + claim.remaining() != 0 && claim.priority() == usize::from(priority) + }) { + held.take() + } else { + None + } + }; + match claimed { + Some(claim) => (Some(claim), true), + None => (Some(port.reserve_m5_compute(priority).ok()?), false), + } + } else { + (None, false) + }; + let result = (|| { + let mut queue = target_cell.lock()?; + if !queue.installed() + || queue.spared_pending() + || !queue.pool_fits(required) + || queue.pending_switch_from().is_some() + || (has_sources && queue.qid() != target_qid) + || (m5 && queue.outer_slots() != 1) + || (cached_count == 1 + && can_add_sibling + && super::pairs::overlaps(queue.active_len())) + || !matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)) + || self.context.compute_binding_count() as usize != cached_count + || !lease.is_current() + { + return None; + } + let outer = if m5 { + None + } else { + Some(port.reserve_compute(priority).ok()?) + }; + let mut host = DirectHost { + port, + outer, + m5_outer: m5_outer.as_mut(), + m5_outer_guard: None, + m5, + generation, + }; + Some(queue.publish( + packet.clone(), + direct_frontier.as_slice(), + &mut host, + &mut |event| deferred.push(event), + )) + })(); + if packet.is_published() { + if let Some(sources) = packet.completion.sources() { + if cross_qid_mask != 0 { + for (idx, source) in sources.sources.iter().enumerate() { + if cross_qid_mask & (1u64 << idx) != 0 { + source.submission.note_firmware_consumer(); + } + } + sources.set_holds(direct_holds); + } else { + drop(direct_holds); + } + super::sync_input::note_published(); + super::sync_input::note_native(0); + } + } else { + drop(direct_holds); } - let outer = port.reserve_compute(packet.context.policy().priority()).ok()?; - let mut host = DirectHost { - port, - outer: Some(outer), - generation: port.generation(), + let outcome = match result { + None => None, + Some(Err(error)) if (error == EAGAIN || error == EBUSY) && !packet.is_published() => { + None + } + Some(result) => Some(result), }; - match queue.publish(packet.clone(), &[], &mut host, &mut |event| deferred.push(event)) { - Err(error) if (error == EAGAIN || error == EBUSY) && !packet.is_published() => None, - result => Some(result), + if outcome.is_none() && from_held { + if let Some(claim) = m5_outer.take().filter(|claim| claim.remaining() != 0) { + let mut held = self.outer_compute.lock(); + if !held.as_ref().is_some_and(|existing| existing.remaining() != 0) { + // Replace None or an already-spent claim (whose drop notifies nobody). + *held = Some(claim); + } else { + drop(held); + drop(claim); + } + } } + drop(m5_outer); + outcome } /// Scheduler admission of a compute packet. Shared capacity the packet lacks (a channel, a @@ -2130,7 +3437,34 @@ impl Backend { /// M5: the domain outer-ring claims wait on. None off M5 or without firmware. fn outer_domain(&self) -> Option> { - self.shared.state.lock().as_deref().and_then(|firmware| firmware.init.outer_available().ok()) + if !self.context.is_m5() { + return None; + } + let lease = self.shared.preparations.try_enter().ok()?; + self.shared.port(&lease)?.outer_domain() + } + + /// M5: holds this owner's compute outer-ring claim through `Port` without taking the device + /// mutex, for a channel already bound and installed. + fn claim_compute_outer_direct(&self, count: u32) -> Result { + let mut held = self.outer_compute.lock(); + if held.as_ref().is_some_and(|claim| claim.remaining() != 0) { + return Ok(true); + } + let Ok(lease) = self.shared.preparations.try_enter() else { + return Ok(true); + }; + let Some(port) = self.shared.port(&lease) else { + return Ok(true); + }; + match port.reserve_m5_outer(self.context.policy().priority(), count) { + Ok(claim) => { + *held = Some(claim); + Ok(true) + } + Err(error) if error == EBUSY => Ok(false), + Err(error) => Err(error), + } } /// M5: holds this owner's claim on the shared work ring for the next compute or render @@ -2142,10 +3476,19 @@ impl Backend { return Ok(true); } let (held, count) = match engine { - crate::g17::job::Engine::Compute => ( - &self.outer_compute, - firmware.queues.compute(self.owner).map_or(2, |queue| queue.outer_slots()), - ), + crate::g17::job::Engine::Compute => { + let slots = firmware + .queues + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(self.owner)) + .map(|queue| queue.outer_slots()) + .max() + .unwrap_or(2); + (&self.outer_compute, slots) + } // Tiling and fragment: one slot each. crate::g17::job::Engine::Render => (&self.outer_render, 2), }; @@ -2153,6 +3496,7 @@ impl Backend { if held.as_ref().is_some_and(|claim| claim.remaining() != 0) { return Ok(true); } + let _m5_outer = firmware.port.m5_outer_lock(); match firmware.init.reserve_outer(self.context.policy().priority(), count) { Ok(claim) => { // Replaces only a spent claim, whose drop notifies nobody. @@ -2172,11 +3516,14 @@ impl Backend { dependencies: &[super::fw::kick::KickDependency], deferred: &mut DeferredBatch, ) -> Result { + if !firmware.init.is_m5() { + return firmware.publish_compute(self.owner, packet.clone(), dependencies, deferred); + } let mut held = self.outer_compute.lock(); let _scope = (*held) .as_mut() .filter(|claim| claim.remaining() != 0) - .map(|claim| firmware.init.outer_scope(claim)) + .map(|claim| firmware.port.outer_scope(&firmware.init, claim)) .transpose()?; firmware.publish_compute(self.owner, packet.clone(), dependencies, deferred) } @@ -2184,6 +3531,9 @@ impl Backend { /// Returns an engine's unspent outer claim after its publication, cancellation or close. /// Outside the device mutex: returned credits notify waiters. pub(super) fn release_outer(&self, engine: crate::g17::job::Engine) { + if !self.context.is_m5() { + return; + } let held = match engine { crate::g17::job::Engine::Compute => &self.outer_compute, crate::g17::job::Engine::Render => &self.outer_render, @@ -2198,37 +3548,86 @@ impl Backend { Err(_) => return Readiness::Ready, Ok(_) => {} } - // The steady state: this owner's channel is bound and installed. - if packet.completion.sources().is_none() { - if let Some(cell) = self.direct.lock().clone() { - let bound = cell.lock().is_some_and(|mut queue| { - let bound = queue.installed() - && !queue.spared_pending() - && queue.pool_fits(required) - && matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)); - if bound { - queue.claim(); - } - bound - }); - if bound { - self.hold_claim(Some(cell)); - if !self.context.is_m5() { - return Readiness::Ready; + let sources_checked = if packet.completion.sources().is_some() { + match self.sources_published(packet) { + Ok(false) => return Readiness::Progress, + Err(_) => return Readiness::Ready, + Ok(true) => true, + } + } else { + false + }; + // The steady state: this owner's bound channel(s) are all cached and installed. + let bound_count = self.context.compute_binding_count() as usize; + if (!sources_checked || self.context.is_m5()) + && bound_count != 0 + && bound_count <= super::pairs::COMPUTE_CHANNELS_MAX + { + let cells = self.direct.lock().clone(); + let cached_count = cells.iter().filter(|cell| cell.is_some()).count(); + if cached_count == bound_count { + if let Some(primary) = cells[0].clone() { + // Validate siblings first so primary is claimed only once every channel passes. + let mut all_ok = true; + let mut outer_slots = 1u32; + for cell in cells[1..].iter().flatten() { + match cell.lock() { + Some(queue) + if queue.installed() + && !queue.spared_pending() + && queue.pool_fits(required) + && matches!( + queue.matches(self.owner, queue.qid(), &self.context), + Ok(true) + ) => + { + outer_slots = outer_slots.max(queue.outer_slots()); + } + _ => { + all_ok = false; + break; + } + } } - let state = self.shared.state.lock(); - let Some(firmware) = state.as_deref() else { return Readiness::Ready; }; - return match self.claim_outer(firmware, crate::g17::job::Engine::Compute) { - Ok(false) => Readiness::Outer, - _ => Readiness::Ready, + let bound = if all_ok { + primary.lock().and_then(|mut queue| { + let ok = queue.installed() + && !queue.spared_pending() + && queue.pool_fits(required) + && matches!( + queue.matches(self.owner, queue.qid(), &self.context), + Ok(true) + ) + && self.context.compute_binding_count() as usize == cached_count; + if ok { + queue.claim(); + Some(outer_slots.max(queue.outer_slots())) + } else { + None + } + }) + } else { + None }; + if let Some(outer_slots) = bound { + self.hold_claim(Some(primary)); + if !self.context.is_m5() { + return Readiness::Ready; + } + return match self.claim_compute_outer_direct(outer_slots) { + Ok(false) => Readiness::Outer, + _ => Readiness::Ready, + }; + } } } } - match self.sources_published(packet) { - Ok(false) => return Readiness::Progress, - Err(_) => return Readiness::Ready, - Ok(true) => {} + if !sources_checked { + match self.sources_published(packet) { + Ok(false) => return Readiness::Progress, + Err(_) => return Readiness::Ready, + Ok(true) => {} + } } let lease = match self.shared.preparations.try_enter() { Ok(lease) => lease, @@ -2267,18 +3666,18 @@ impl Backend { } } - /// Called with the device mutex held after a successful publication: remembers the bound - /// channel for direct publication. + /// Called with the device mutex held after a successful publication: remembers all bound + /// channels for direct publication. fn remember_direct(&self, registry: &Registry) { - let cell = registry.compute_cell(self.owner); + let cells = registry.compute_cells(self.owner); let mut direct = self.direct.lock(); - let current = match (&*direct, &cell) { + let current = direct.iter().zip(cells.iter()).all(|pair| match pair { (Some(old), Some(new)) => Arc::ptr_eq(old, new), (None, None) => true, _ => false, - }; + }); if !current { - let old = core::mem::replace(&mut *direct, cell); + let old = core::mem::replace(&mut *direct, cells); drop(direct); drop(old); } @@ -2379,6 +3778,37 @@ impl Backend { { return Err(render::FALLBACK); } + if self.fans_out(packet, || { + firmware.queues.compute_primary(self.owner).is_some_and(|queue| queue.sustained()) + }) { + if firmware.queues.wants_compute_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + ) { + // Bind a warm reusable sibling inline if one is ready; otherwise fall back once + // so `compute_packet` can build a fresh surplus sibling off-lock. + match firmware.queues.bind_reusable_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + )? { + Some(true) => self.sibling_backoff_until.store(0, Ordering::Relaxed), + Some(false) => return Err(render::FALLBACK), + None => {} + } + } else if !firmware + .queues + .has_compute_sibling_headroom(self.owner, &self.context, required) + { + self.sibling_backoff_until.store( + now_ns().saturating_add(super::pairs::SIBLING_HEADROOM_BACKOFF_NS), + Ordering::Relaxed, + ); + } + } if !self.claim_outer(firmware, crate::g17::job::Engine::Compute)? { return Err(render::FALLBACK); } @@ -2401,6 +3831,28 @@ impl Backend { fn sources_published(&self, packet: &super::job::Packet) -> Result { let Some(sources) = packet.completion.sources() else { return Ok(true); }; sources.check()?; + if let Ok(lease) = self.shared.preparations.try_enter() { + if let Some(port) = self.shared.port(&lease) { + if !self.shared.crashed.load(Ordering::Acquire) + && port.recovery_state().ok() == Some(0) + { + let generation = port.generation(); + let mut all_fast = true; + for source in &sources.sources { + if source.submission.source_status()? { + continue; + } + if !source.submission.has_published_epoch(generation) { + all_fast = false; + break; + } + } + if all_fast { + return Ok(true); + } + } + } + } let state = self.shared.state.lock(); let firmware = state.as_deref().ok_or(ENODEV)?; if firmware.recovery.pending() @@ -2435,6 +3887,7 @@ impl Backend { // progress (work states, ring room, replays) and the reopening of // publication after recovery both signal `progress`. let mut bound = true; + let mut sibling_tried = false; let mut demand = None; let deadline = now_ns().saturating_add(super::preparation::QUEUE_WAIT_NS); let check = || { @@ -2526,6 +3979,58 @@ impl Backend { drop(lease); continue; } + if !sibling_tried + && self.fans_out(packet, || { + firmware + .queues + .compute_primary(self.owner) + .is_some_and(|queue| queue.sustained()) + }) + { + if firmware.queues.wants_compute_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + ) { + sibling_tried = true; + match firmware.queues.bind_reusable_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + )? { + Some(true) => { + self.sibling_backoff_until.store(0, Ordering::Relaxed); + } + Some(false) => { + drop(state); + drop(lease); + if self.try_add_compute_sibling(required, &admission)? { + self.sibling_backoff_until.store(0, Ordering::Relaxed); + } else { + self.sibling_backoff_until.store( + now_ns().saturating_add( + super::pairs::SIBLING_HEADROOM_BACKOFF_NS, + ), + Ordering::Relaxed, + ); + } + continue; + } + None => {} + } + } else if !firmware + .queues + .has_compute_sibling_headroom(self.owner, &self.context, required) + { + sibling_tried = true; + self.sibling_backoff_until.store( + now_ns().saturating_add(super::pairs::SIBLING_HEADROOM_BACKOFF_NS), + Ordering::Relaxed, + ); + } + } let held = self.claim_outer(firmware, crate::g17::job::Engine::Compute)?; if let (false, Some(domain), Some(claimed)) = (held, &outer, claimed) { // The shared work ring has no unclaimed room: consumption or returned claims @@ -2665,6 +4170,7 @@ impl super::Shared { /// mappings owned in state. Only a later joined stop may detach/free them. pub(super) fn stop_runtime(&self) { let Some(_stopping) = self.stop.try_lock() else { return; }; + self.disable_rescan(); { let mut state = self.state.lock(); if let Some(firmware) = state.as_deref_mut() { @@ -2755,6 +4261,12 @@ impl super::Firmware { let busy = !queue.channel_free(); queue.recycle_killed()?; queue.recycle_quarantined_idle()?; + if deferred.vacated_room() { + if let Some(vacated) = queue.take_recycled_ring() { + deferred.defer_vacated(vacated); + freed = true; + } + } if let Some(binding) = queue.detach_exited_owner() { deferred.defer_binding(binding); } @@ -2832,7 +4344,7 @@ impl Registry { self.compute.iter().flatten().filter(|entry| entry.queue.is_none()).count())?; writeln!(f, "compute_channels used={} fresh_fits={}", self.compute.iter().flatten().count(), - u8::from(self.qids.compute_fits(self.admission.queues() as usize)))?; + u8::from(self.compute_qid_fits()))?; writeln!(f, "scheduler_teardown pending={}", self.teardown.len())?; for queue in self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()) { queue.write_capacity(f)?; @@ -3044,6 +4556,66 @@ mod shared_capacity_tests { assert!(registry.qids.render_fits(slots.len() + 24)); assert!(!registry.qids.render_fits(crate::mmu::MAX_EXECUTION_CONTEXTS as usize)); } + + #[test] + fn cancelable_siblings_do_not_block_compute_on_full_qid_table() { + let mut registry = KBox::init( + Registry::new(1, Deflake::ONE_CLUSTER, [0; 2], &V26A428), + GFP_KERNEL, + ) + .unwrap(); + let mut slots = KVec::with_capacity(32, GFP_KERNEL).unwrap(); + for owner in 1..=32u64 { + slots.push(registry.admission.reserve_queue().unwrap(), GFP_KERNEL).unwrap(); + let lease = registry + .admission + .acquire_render(owner, 2, None, u64::MAX, || Ok(())) + .unwrap(); + registry.ensure_render_ids(lease.slot(), owner).unwrap(); + registry.publish_render_ids(lease.slot()).unwrap(); + if owner <= 31 { + let sibling = registry + .admission + .warmable_sibling(owner, lease.slot()) + .unwrap(); + registry.ensure_render_ids(sibling.slot(), owner).unwrap(); + drop(sibling); + } + drop(lease); + } + // All 128 QIDs are now occupied: 32 published primaries (64), 31 idle + // unpublished siblings (62), and the two bootstrap render reservations. + assert!(!registry.qids.render_pair_fits()); + // Consume both bootstrap replacements with installed compute channels. + registry.reserve_compute(1000).unwrap(); + registry.reserve_compute(1001).unwrap(); + // Raw compute_fits() is false because no free or bootstrap QID remains, + // yet idle unpublished siblings can yield QIDs for fresh compute work. + assert!(!registry.qids.compute_fits(registry.admission.render_demand(0))); + assert!(registry.has_cancelable_render_spare().unwrap()); + assert!(registry.compute_qid_fits()); + assert!(matches!(registry.compute_readiness(1002, None), Readiness::Ready)); + let mut reclaimed = None; + registry.reserve_compute_reclaiming(1002, &mut reclaimed).unwrap(); + assert!(reclaimed.is_some()); + drop(reclaimed); + // Compute grows to the full budget left above render_reserve(32) = 114. + let mut count = 3usize; + let mut owner = 1003u64; + while registry.compute_qid_fits() { + let mut spare = None; + registry.reserve_compute_reclaiming(owner, &mut spare).unwrap(); + drop(spare); + count += 1; + owner += 1; + } + assert_eq!(count, super::super::kick::QID_COUNT - super::super::kick::render_reserve(32)); + assert!(matches!(registry.compute_readiness(owner, None), Readiness::Channel)); + let mut spare = None; + assert!(matches!(registry.reserve_compute_reclaiming(owner, &mut spare), Err(EAGAIN))); + assert!(spare.is_none()); + assert!(registry.qids.render_fits(slots.len() + 24)); + } } impl Backend { diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index f9d2999a4e1d59..89cbd0b7fcf741 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -2,10 +2,11 @@ //! Scheduler callbacks and the off-lock fence boundary of a logical queue. -use super::{Backend, DeferredBatch}; +use super::{Backend, DeferredBatch, PerChannel, Uninstalled}; use crate::g17::{ completion::Deferred, job::{self, Engine, Packet}, + queue::compute::Binding, }; use core::sync::atomic::Ordering; use kernel::{dma_fence::{Fence, RawDmaFence}, drm::sched, prelude::*, sync::Arc}; @@ -34,30 +35,21 @@ impl Backend { // No outer preparation lease survives compute_packet's return. Hold a // fresh epoch through alias destruction so recovery can join this work. loop { - let lease = self.shared.preparations.enter(false)?; - let mut retired = None; - let mut state = self.shared.state.lock(); - let firmware = state.as_deref_mut().ok_or(ENODEV)?; - if !lease.is_current() { drop(state); drop(lease); continue; } - let mut binding = None; - if let Some(index) = firmware.queues.compute.iter().position(|entry| { - entry.as_ref().and_then(|entry| entry.queue.as_deref()) - .is_some_and(|queue| queue.owner() == Some(self.owner)) - }) { - let entry = firmware.queues.compute[index].as_mut().ok_or(EIO)?; - let (cancel, replaced) = entry.queue.as_deref_mut().ok_or(EIO)? - .rollback_unpublished(self.owner, &self.context)?; - binding = replaced; - if cancel { - retired = entry.queue.take().map(|queue| (entry.reservation, queue)); - } - } - drop(state); - drop(binding); - self.finish_uninstalled_compute(retired)?; - self.shared.channels.notify(); - self.shared.queue_events(); - return Ok(()); + let lease = self.shared.preparations.enter(false)?; + let mut retired: PerChannel = Default::default(); + let mut bindings: PerChannel = Default::default(); + let mut state = self.shared.state.lock(); + let firmware = state.as_deref_mut().ok_or(ENODEV)?; + if !lease.is_current() { drop(state); drop(lease); continue; } + let result = firmware.queues.rollback_unpublished_compute( + self.owner, &self.context, &mut retired, &mut bindings); + drop(state); + // Off-lock, and after a failure too: no cancelled queue's reservation stays behind. + drop(bindings); + let finished = self.finish_retired_compute(&mut retired); + self.shared.channels.notify(); + self.shared.queue_events(); + return result.and(finished); } } @@ -97,22 +89,33 @@ impl Backend { self.release_outer(Engine::Compute); self.release_outer(Engine::Render); let mut state = self.shared.state.lock(); + // The client closes its queue itself now (see `Context::held_by_open_client`). + self.context.note_open_client(false); let Some(firmware) = (*state).as_deref_mut() else { return Ok(()); }; - // Retain a published scheduler before a never-kicked physical graph is - // removed. The teardown entry owns its root until control consumption. - firmware - .queues - .teardown - .close(&self.context, super::now_ns())?; - firmware.queues.release_compute(self.owner)?; - firmware.queues.release_render(self.owner)?; - // The armed release holds the owner's pairs from every other owner until it is - // consumed. Hold them before admission releases the owner: admission does not take - // the device mutex, so a slot released first could be taken in between. - firmware.queues.sync_render_holds(); - firmware.queues.admission.release_owner(self.owner); + // A pair of this context that holds guilty work counts for a kill only after a restart + // since this close (`Pair::guilty_for_kill`). Only the first close counts: the kernel + // may have closed this queue on its client's behalf already (`Firmware::close_failed_owners`), + // and its teardown entry may be released and reclaimed since. Closing it again would + // release its scheduler twice. + if !self.context.is_closed() { + // Retain a published scheduler before a never-kicked physical graph is + // removed. The teardown entry owns its root until control consumption. + firmware + .queues + .teardown + .close(&self.context, super::now_ns())?; + // Only now: a close that could not reserve its teardown entry is redone by the next. + self.context.note_closed(firmware.recovery.generation()); + firmware.queues.release_compute(self.owner)?; + firmware.queues.release_render(self.owner)?; + // The armed release holds the owner's pairs from every other owner until it is + // consumed. Hold them before admission releases the owner: admission does not take + // the device mutex, so a slot released first could be taken in between. + firmware.queues.sync_render_holds(); + firmware.queues.admission.release_owner(self.owner); + } drop(state); // Its idle channel, or its slot and never-published QID, is free. self.shared.channels.notify(); @@ -123,7 +126,7 @@ impl Backend { impl job::Backend for Backend { fn creator_cluster_scheduling(&self) -> bool { - self.shared.follows_submitter() + self.shared.pin_scheduler_cluster() } fn host_producer_waits(&self) -> bool { self.shared.m5_board.is_some_and(|board| !board.g17d_forms() && !board.completion_inputs()) @@ -144,11 +147,20 @@ impl job::Backend for Backend { let mut heads = KVec::new(); let mut sources: KVec = KVec::new(); let mut publication_waits = KVec::new(); + let mut unchecked: KVec = KVec::new(); + let lease = self.shared.preparations.try_enter().ok(); + let port_epoch = lease.as_ref().and_then(|lease| { + let port = self.shared.port(lease)?; + if self.shared.crashed.load(Ordering::Acquire) || port.recovery_state().ok()? != 0 { + return None; + } + Some(port.generation()) + }); for input in inputs.iter().filter_map(|input| input.fence.as_ref()) { let status = job::fence_status(input); if status > 0 { continue; } if status < 0 { return None; } - let leaves = sync_input::collect(input)?; + let leaves = sync_input::collect_coalesced(input)?; for leaf in &leaves { if leaf.status > 0 { continue; } if leaf.status < 0 { return None; } @@ -160,29 +172,52 @@ impl job::Backend for Backend { continue; } if sources.len() == crate::g17::fw::kick::KICK_BARRIERS_MAX { return None; } - let published = { - let state = self.shared.state.lock(); - let firmware = state.as_deref()?; - if self.shared.crashed.load(Ordering::Acquire) || firmware.recovery.pending() - || crate::g17::recovery::Memory::recovery_state(&firmware.init).ok()? != 0 - { return None; } - firmware.queues.compute.iter().flatten() - .filter_map(|entry| entry.queue.as_deref()) - .any(|queue| queue.has_input_source(&submission, self.context.status(), - firmware.recovery.generation())) - }; + let published_fast = + port_epoch.is_some_and(|epoch| submission.has_published_epoch(epoch)); + let idx = sources.len(); + sources.push(sync_input::Source { submission }, GFP_KERNEL).ok()?; + if !published_fast { + unchecked.push(idx, GFP_KERNEL).ok()?; + } + } + heads.push(input.clone(), GFP_KERNEL).ok()?; + } + drop(lease); + if sources.is_empty() { return None; } + if !unchecked.is_empty() { + // Hoist the device mutex outside the leaf loop when any source was not already + // confirmed via the lock-free `PublishedSource` snapshot. + let state = self.shared.state.lock(); + let firmware = state.as_deref()?; + if self.shared.crashed.load(Ordering::Acquire) + || firmware.recovery.pending() + || crate::g17::recovery::Memory::recovery_state(&firmware.init).ok()? != 0 + { + return None; + } + let generation = firmware.recovery.generation(); + for idx in unchecked { + let submission = &sources[idx].submission; + let published = firmware + .queues + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .any(|queue| { + queue.has_input_source(submission, self.context.status(), generation) + }); if !published { - if submission.source_status().ok()? { continue; } + if submission.source_status().ok()? { + continue; + } // The existing scheduler fence becomes ready after actual // publication, not GPU completion. No binding loan or // consumer hardware capacity is acquired while waiting. publication_waits.push(submission.ready()?, GFP_KERNEL).ok()?; } - sources.push(sync_input::Source { submission }, GFP_KERNEL).ok()?; } - heads.push(input.clone(), GFP_KERNEL).ok()?; } - if sources.is_empty() { return None; } sync_input::Sources::new(heads, sources, publication_waits).ok() } @@ -207,9 +242,15 @@ impl job::Backend for Backend { let programs = resources.as_deref().ok_or(EINVAL)?; *plan = Some(policy.plan(programs, priority)?); // The M5 target layout refuses the passes the M5 path cannot run. Derive it - // here, so that SUBMIT returns the refusal before anything is queued. - crate::g17::queue::render::m5_render_submission::layout( - command, self.shared.clusters, self.shared.variant.programs)?; + // here, so that SUBMIT returns the refusal before anything is queued, and keep + // the window its pairs reserve for choosing their count (`render_pairs`). + let (_, window) = + crate::g17::queue::render::m5_render_submission::layout_and_window( + command, self.shared.clusters, self.shared.variant.programs, + self.shared.m5_board)?; + if let Validated::Render { pair_window, .. } = command { + *pair_window = window; + } } Validated::Compute { resources, plan, m5_scratch, cdm_auxiliary_allocation, .. } => { if let Some(programs) = resources { @@ -225,7 +266,12 @@ impl job::Backend for Backend { } fn render_scs_blocks(&self, pages: [u16; 2]) -> Result { - crate::g17::fw::render_rt::required_blocks(self.shared.active_cores, pages, self.pairs) + crate::g17::fw::render_rt::required_blocks( + self.shared.active_cores, + self.shared.clusters, + pages, + self.pairs, + ) } fn ensure_compute(&self, command: &crate::g17::command::Validated) -> Result { diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs index 2bad8071087fd0..881caee85111e8 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs @@ -30,7 +30,7 @@ impl Backend { return Ok(Decision::Defer); } // Each queue is locked on its own: release this one before visiting the others. - let Some(own) = firmware.queues.compute(self.owner) + let Some(own) = firmware.queues.compute_for_packet(self.owner, packet) .filter(|queue| queue.can_classify_timeout(packet)) .and_then(|queue| queue.timeout_head()) else { return Ok(Decision::Own); @@ -48,7 +48,7 @@ impl Backend { } let decision = verdict.decision; if decision == Decision::Spare { - firmware.queues.compute(self.owner).ok_or(EIO)? + firmware.queues.compute_for_packet(self.owner, packet).ok_or(EIO)? .classify(&|_| Class::Spared); } if let Some(blocker) = verdict.reported_blocker(renewals, excuse) { @@ -73,13 +73,17 @@ impl Backend { deferred: &mut DeferredBatch) -> Result { use crate::g17::timeout::Decision; use core::sync::atomic::{AtomicU32, Ordering}; - let expired = firmware.queues.compute_mut(self.owner) + let expired = firmware.queues.compute_for_packet_mut(self.owner, packet) .is_some_and(|mut queue| queue.expire_stamp_wait(packet)); if !expired { return Ok(Decision::Own); } firmware.scan_compute(None, deferred)?; - if !firmware.queues.compute(self.owner).is_some_and(|queue| queue.retired_held(packet)) { + if !firmware + .queues + .compute_for_packet(self.owner, packet) + .is_some_and(|queue| queue.retired_held(packet)) + { return Ok(Decision::Own); } static REPORTED: AtomicU32 = AtomicU32::new(0); @@ -122,7 +126,7 @@ impl Backend { return Ok(None); }; firmware.scan_compute(None, &mut deferred)?; - let Some(mut queue) = firmware.queues.compute_mut(self.owner) else { + let Some(mut queue) = firmware.queues.compute_for_packet_mut(self.owner, packet) else { return Ok(None); }; // A command that retired in this pass has its result. @@ -150,7 +154,7 @@ impl Backend { return Ok(()); }; firmware.scan_compute(None, &mut deferred)?; - if let Some(mut queue) = firmware.queues.compute_mut(self.owner) { + if let Some(mut queue) = firmware.queues.compute_for_packet_mut(self.owner, packet) { queue.cancel(packet, &mut |event| deferred.push(event))?; } Ok(()) diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs index d19a52c6746328..e4fa40ed22f8c6 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs @@ -54,14 +54,24 @@ fn render_kill_target(listed: u128, own: u128) -> Option { (candidates != 0).then(|| candidates.trailing_zeros() as u8) } -/// A closed context may be killed on its render pairs' behalf once it has been closed for -/// [`RENDER_KILL_DELAY_NS`], it was never killed, a pair of it holds executed but unstamped -/// commands and no compute queue still runs it, switches away from it or killed it. A second kill -/// of a killed context made the firmware fault on the killed pair's own tiling queue within a -/// millisecond of acknowledging it: with the pair's release held back, a context killed through -/// its compute queue still looked like a render-only candidate. -fn render_kill_eligible(age: u64, killed: bool, executed: bool, compute_clear: bool) -> bool { - age >= RENDER_KILL_DELAY_NS && !killed && executed && compute_clear +/// A closed context may be killed on its render pairs' behalf once it was never killed, no +/// compute queue still runs it, switches away from it or killed it, and a pair of it holds +/// executed but unstamped commands (`executed`) once it has been closed for +/// [`RENDER_KILL_DELAY_NS`], or holds guilty work (`guilty`, `Pair::guilty_for_kill`) at once: +/// that work never retires, it hangs the GPU again about every 83 ms, and eight such restarts +/// stop the GPU for every client. A second kill of a killed context made the firmware fault on +/// the killed pair's own tiling queue within a millisecond of acknowledging it: with the +/// pair's release held back, a context killed through its compute queue still looked like a +/// render-only candidate. +fn render_kill_eligible(age: u64, killed: bool, executed: bool, guilty: bool, compute_clear: bool) -> bool { + !killed && compute_clear && (guilty || (executed && age >= RENDER_KILL_DELAY_NS)) +} + +/// A closed context's kill waits only for other contexts' compute to pause, not for their +/// render work, when its compute failed (`compute_failed`) or the kill releases render pairs +/// that nothing else releases (`releases_pairs`, `Firmware::kill_releases_render`). +fn waits_as_failed(compute_failed: bool, releases_pairs: bool) -> bool { + compute_failed || releases_pairs } /// How a closed context whose render pairs are idle for a kill (`teardown_idle`) is killed. @@ -166,13 +176,15 @@ impl super::Registry { /// ACK storage belongs to the already-retained transaction, so a full event /// batch cannot overflow a separate cache. No allocation or wait is needed. pub(super) fn acknowledge_compute_exit(&mut self, cookie: u64) { + let mut matched = false; for entry in self.compute.iter_mut().flatten() { if let Some(mut queue) = entry.queue.as_deref_mut() { - if queue.acknowledge_exit(cookie) { - return; - } + matched |= queue.acknowledge_exit(cookie); } } + if matched { + return; + } if self.teardown.acknowledge_render_kill(cookie) { RENDER_KILLS[RENDER_KILL_ACKNOWLEDGED].fetch_add(1, Ordering::Relaxed); crate::g17::trace::teardown(4, cookie, 0x100, 0); @@ -200,6 +212,7 @@ impl Firmware { return Ok(()); } let now = now_ns(); + self.close_failed_owners(now)?; // Publication has already retained each kill. Retry only the doorbell; // failed attempts do not extend its bounded polling window. for entry in self.queues.compute.iter_mut().flatten() { @@ -217,7 +230,7 @@ impl Firmware { let Some((context, age)) = self.queues.teardown.closed(index, now) else { continue; }; - if !self.queues.render.teardown_idle(&context)? { + if !self.queues.render.teardown_idle(&context, self.recovery.generation())? { self.queues.teardown.clear_kill_wait(index); continue; } @@ -253,7 +266,7 @@ impl Firmware { let Some((context, age)) = due else { continue; }; - if !self.queues.render.teardown_idle(&context)? { + if !self.queues.render.teardown_idle(&context, self.recovery.generation())? { continue; } if let Err(error) = self.publish_compute_exit(&context, age, now, &mut pressed) { @@ -269,6 +282,11 @@ impl Firmware { } fn publish_compute_exit(&mut self, context: &Arc, age: u64, now: u64, pressed: &mut bool) -> Result { + // A context is killed at most once: a multi-channel context records the single kill + // cookie across all of its exiting channels below. + if context.kill_published() { + return Ok(()); + } let Some(index) = self.queues.compute.iter().position(|entry| { entry .as_ref() @@ -345,7 +363,7 @@ impl Firmware { && !self .queues .admission - .hold_render_slots_for_exit_kill(owner, hold, self.queues.render.executed_slots(context) & hold) + .hold_render_slots_for_exit_kill(owner, hold, self.queues.render.kill_slots(context, self.recovery.generation()) & hold) { return Ok(()); } @@ -359,6 +377,7 @@ impl Firmware { // stop, and the held render identities until this context's scheduler release // is consumed or processors stop. context.note_kill_published(); + self.note_guilty_kill(context, hold, "compute exit"); let mut queue = self.queues.compute[index] .as_mut() .and_then(|entry| entry.queue.as_deref_mut()) @@ -374,8 +393,25 @@ impl Firmware { PRESSED_KILL_NS.store(now.max(1), Ordering::Relaxed); } queue.record_exit(cookie, now); + drop(queue); + // A single ContextKill tears down every queue of this context: attach the same + // cookie to any other exiting compute channel of `context` so they settle together. + for (other_index, entry) in self.queues.compute.iter_mut().enumerate() { + if other_index == index { + continue; + } + if let Some(mut other) = entry.as_mut().and_then(|entry| entry.queue.as_deref_mut()) { + if other.exit_candidate(context, age) { + other.record_exit(cookie, now); + } + } + } crate::g17::trace::teardown(3, cookie, u64::from(context.id()), hold | u64::from(beside)); fence(Ordering::SeqCst); + let mut queue = self.queues.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + .ok_or(EIO)?; if let Err(error) = queue.announce_exit(now, || self.primary.notify(MSG_CONTROL_NOTIFY)) { dev_warn!( self.primary.state.shared.dev.as_ref(), @@ -392,37 +428,96 @@ impl Firmware { kill_route( self.compute_failed(context), self.queues.render.teardown_pools_released(context), - self.kill_releases_executed_render(context), + self.kill_releases_render(context), self.compute_exit_pending(context), self.render_kill_candidate(index, context, age), ) } /// A kill of `context` would release render pairs of it whose commands all ran but were - /// never stamped (`Pair::executed_for_kill`), and no kill of it was published yet. Only that - /// kill releases them. Never a second time: a second kill of a killed context made the - /// firmware fault on the killed pair's own tiling queue (see `render_kill_eligible`). Not on - /// M5, which never kills a context on its render pairs' behalf. - fn kill_releases_executed_render(&self, context: &Arc) -> bool { - !self.init.is_m5() && !context.kill_published() && self.queues.render.executed_slots(context) != 0 + /// never stamped (`Pair::executed_for_kill`) or that hold guilty work + /// (`Pair::guilty_for_kill`), and no kill of it was published yet. Only that kill releases + /// them. Never a second time: a second kill of a killed context made the firmware fault on + /// the killed pair's own tiling queue (see `render_kill_eligible`). Not on M5, which never + /// kills a context on its render pairs' behalf. + fn kill_releases_render(&self, context: &Arc) -> bool { + !self.init.is_m5() && !context.kill_published() && self.queues.render.kill_slots(context, self.recovery.generation()) != 0 + } + + /// Closes, on its client's behalf, each queue whose VM a GPU recovery failed as guilty + /// (`Pair::failed_guilty`), as its client's close (`release_queue`) would. Nothing of that + /// VM can run again: its status refuses every later submission and publication. But a client + /// that keeps the queue open after the lost device (a process that ignores it, or waits in an + /// error dialog) would keep its guilty work published, and that work hangs the GPU again after + /// every restart until the storm limit stops the GPU for every client: a guilty pair is killed + /// only once its owner closed (`Pair::guilty_unretired`). Closed here, its context takes the + /// same kill, release and detach as an exited client's. The client's own close later finds the + /// queue closed (`Context::note_closed`) and leaves the teardown entry alone; the scheduler + /// release waits for that close (`Context::held_by_open_client`). Not on M5, which + /// takes published work back through its recovery target. + fn close_failed_owners(&mut self, now: u64) -> Result { + if self.init.is_m5() { + return Ok(()); + } + let generation = self.recovery.generation(); + for slot in 0..crate::hw::t8140::queues::RENDER_SLOTS { + let Some((owner, context)) = self.queues.render.failed_open_owner(slot) else { + continue; + }; + if context.is_closed() { + continue; + } + // In the order of the client's own close (`release_queue`): the context counts as + // closed only once its teardown entry is reserved. A close that could not reserve it + // closed nothing, and the next service pass retries it. + if let Err(error) = self.queues.teardown.close(&context, now) { + pr_err!("G17: scheduler {} close for its open client failed: {:?}\n", context.id(), error); + continue; + } + context.note_closed(generation); + context.note_open_client(true); + // Closed now, so no later close releases the owner: an error from here fails the + // event service, which stops the device, as the client's own close does. + self.queues.release_compute(owner)?; + self.queues.release_render(owner)?; + // As at a client's close: hold the owner's pairs before admission releases it. + self.queues.sync_render_holds(); + self.queues.admission.release_owner(owner); + pr_warn!("G17: scheduler {} closed for its open client at recovery gen {}: a GPU recovery failed its VM as guilty\n", + context.id(), generation); + } + Ok(()) + } + + /// Logs a published kill that releases guilty pairs (`Pair::guilty_for_kill`), with the + /// recovery generation, so a test shows whether the next restart dropped their work. + fn note_guilty_kill(&self, context: &Arc, hold: u64, route: &str) { + let generation = self.recovery.generation(); + let guilty = self.queues.render.guilty_slots(context, generation) & hold; + if guilty != 0 { + pr_warn!("G17: scheduler {} killed by its {} at recovery gen {}: render slots {:#x} hold guilty work\n", + context.id(), route, generation, guilty); + } } /// A compute exit of `context` waits only for other contexts' compute to pause /// ([`Self::foreign_compute_running`]), as a failed context's kill and a render-only kill /// do, instead of for all of their work ([`Self::kill_unsafe`]). That holds when its compute - /// failed ([`Self::compute_failed`]), and when the kill releases executed render pairs: - /// those are what a render-only kill releases, and nothing else does. `kill_unsafe` also - /// waits for other clients' render work, and it gives no warning and has no memory-pressure - /// escape. Under a steady render load the pairs, pools and memory would stay held. + /// failed ([`Self::compute_failed`]), and when the kill releases executed or guilty render + /// pairs: those are what a render-only kill releases, and nothing else does. `kill_unsafe` + /// also waits for other clients' render work, and it gives no warning and has no + /// memory-pressure escape. Under a steady render load the pairs, pools and memory would + /// stay held, and a guilty pair would hang the GPU until the restart storm limit. fn kill_waits_as_failed(&self, context: &Arc) -> bool { - self.compute_failed(context) || self.kill_releases_executed_render(context) + waits_as_failed(self.compute_failed(context), self.kill_releases_render(context)) } /// A closed context whose compute side is clean, with render pairs whose commands all ran /// but were never stamped (`Pair::executed_for_kill`). Its failed compute command was /// retired on the firmware's fault record, so no compute queue is left to carry a kill, /// yet those pairs are released only after one: without this the context, its pairs and - /// its memory stay until the processors stop. + /// its memory stay until the processors stop. Likewise a closed context with a pair holding + /// guilty work (`Pair::guilty_for_kill`), which only a kill stops hanging the GPU. /// /// M5 has none: it issues a context kill only from a compute queue's exit, so a /// render-only M5 context is never killed. @@ -431,6 +526,7 @@ impl Firmware { age, self.queues.teardown.render_kill_published(index) || context.kill_published(), self.queues.render.executed_slots(context) != 0, + self.queues.render.guilty_slots(context, self.recovery.generation()) != 0, self.queues.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()).all(|queue| { queue.idle_for_context(context) && !queue.switching_from(context) && !queue.exit_published(context) }), @@ -494,7 +590,7 @@ impl Firmware { if !self .queues .admission - .hold_render_slots_for_exit_kill(owner, hold, self.queues.render.executed_slots(context) & hold) + .hold_render_slots_for_exit_kill(owner, hold, self.queues.render.kill_slots(context, self.recovery.generation()) & hold) { refuse_render_kill(&mut self.queues.teardown, index, RENDER_KILL_HOLD); return Ok(()); @@ -508,6 +604,7 @@ impl Firmware { // can fail. The held pairs stay held until this context's scheduler release is // consumed (`release_killed_slots` at detach). context.note_kill_published(); + self.note_guilty_kill(context, hold, "render kill"); self.queues.teardown.record_render_kill(index, cookie, now)?; record_kill_wait(self.queues.teardown.take_kill_wait(index, now)); if beside { @@ -563,7 +660,7 @@ impl Firmware { self.queues.teardown.closed(index, now).is_some_and(|(context, _)| { !context.kill_published() && (self.compute_exit_pending(&context) - || self.queues.render.executed_slots(&context) != 0) + || self.queues.render.kill_slots(&context, self.recovery.generation()) != 0) }) }) .then_some(KILL_RETRY_NS) @@ -647,7 +744,10 @@ impl Firmware { #[kernel::macros::kunit_tests(asahi_g17_render_kill_target)] mod render_kill_target_tests { - use super::{hold_owner, kill_route, render_kill_eligible, render_kill_target, KillRoute, RENDER_KILL_DELAY_NS}; + use super::{ + hold_owner, kill_route, render_kill_eligible, render_kill_target, waits_as_failed, KillRoute, + RENDER_KILL_DELAY_NS, + }; #[test] fn executed_render_pairs_do_not_hold_back_their_compute_exit() { @@ -667,11 +767,42 @@ mod render_kill_target_tests { #[test] fn a_killed_context_is_never_killed_again() { - assert!(render_kill_eligible(RENDER_KILL_DELAY_NS, false, true, true)); - assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, true, true, true)); - assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS - 1, false, true, true)); - assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, false, false, true)); - assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, false, true, false)); + assert!(render_kill_eligible(RENDER_KILL_DELAY_NS, false, true, false, true)); + assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, true, true, false, true)); + assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS - 1, false, true, false, true)); + assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, false, false, false, true)); + assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, false, true, false, false)); + assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, true, false, true, true)); + } + + #[test] + fn a_closed_guilty_context_is_killed_on_its_render_pairs_behalf_at_once() { + // A pair holding a spinning group and never-started groups behind it: not executed, + // guilty. Eligible without the retirement delay, and the render pairs carry the kill + // when no compute queue will exit. + assert!(render_kill_eligible(0, false, false, true, true)); + assert_eq!(kill_route(false, false, true, false, render_kill_eligible(0, false, false, true, true)), + KillRoute::Render); + // A compute queue that will exit carries it instead, under the same rule as an + // executed pair (`releases` = executed or guilty). + assert_eq!(kill_route(false, false, true, true, false), KillRoute::Compute); + // Never a second time, and not while compute of the context still runs. + assert!(!render_kill_eligible(0, true, false, true, true)); + assert!(!render_kill_eligible(0, false, false, true, false)); + } + + #[test] + fn only_a_kill_that_releases_pairs_skips_the_wait_for_foreign_render_work() { + // Guilty or executed pairs, or failed compute: only foreign compute is waited for. + assert!(waits_as_failed(false, true)); + assert!(waits_as_failed(true, false)); + // A closed context that is neither, with queued work: `kill_unsafe` as before, which + // also waits for every foreign render. + assert!(!waits_as_failed(false, false)); + // Its route is unchanged too: before the delay, or with only queued work, no render kill. + assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS * 4, false, false, false, true)); + assert_eq!(kill_route(false, false, false, false, false), KillRoute::None); + assert_eq!(kill_route(false, true, false, true, false), KillRoute::Compute); } #[test] diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs index e72fc921834d93..f00e07a848eb06 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs @@ -124,15 +124,39 @@ impl Firmware { // backpressure uses the existing failed-replay retirement. Err(EBUSY) } else { (|| { - self.queues.compute[index] - .as_mut() - .and_then(|entry| entry.queue.as_deref_mut()) - .ok_or(EIO)? - .prepare_replay(&packet)?; + let qid = { + let mut queue = self.queues.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + .ok_or(EIO)?; + queue.prepare_replay(&packet)?; + queue.qid() + }; let owner = owner.ok_or(EIO)?; packet.check_replay_dependencies()?; - let dependencies = self.queues.render_prefix(owner, &packet)?; - self.publish_compute(owner, packet.clone(), dependencies.as_slice(), deferred) + let mut dependencies = self.queues.render_prefix(owner, &packet)?; + let recovery_state = recovery::Memory::recovery_state(&self.init)?; + let require_visible = self + .primary + .state + .shared + .m5_board + .is_some_and(|board| board.completion_inputs()); + self.queues.append_compute_prefix( + owner, + Some(qid), + &packet, + recovery_state, + require_visible, + &mut dependencies, + )?; + self.publish_compute_on( + owner, + Some(qid), + packet.clone(), + dependencies.as_slice(), + deferred, + ) })() }; let recovery_wait = matches!(result, Err(EAGAIN) | Err(EBUSY)) && (self.recovery.pending() diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index be13a089f7a0fb..d9923fb3fdce23 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -19,10 +19,50 @@ const SHRINK_WAKE_NS: u64 = 1_000_000_000; /// completion records alone keep the worker busy. const HOUSEKEEPING_NS: u64 = 1_000_000; +/// Whether an event pass must run full housekeeping now rather than deferring it to the +/// periodic cadence. Transient idle gaps between sparse submissions defer housekeeping until +/// `HOUSEKEEPING_NS` elapses (bounded by [`deferred_housekeeping_delay`]) so completions avoid +/// repeated report drains and uncached power-register reads. +fn housekeeping_due( + requested: bool, + recover: bool, + recovery_pending: bool, + teardown_pending: bool, + has_waiters: bool, + now: u64, + last_housekeeping_ns: u64, +) -> bool { + requested + || recover + || recovery_pending + || teardown_pending + || has_waiters + || now.saturating_sub(last_housekeeping_ns) >= HOUSEKEEPING_NS +} + +/// Remaining delay (ns) before deferred housekeeping must run when no work remains in flight. +/// Returns `None` while work stays in flight or when housekeeping ran on this pass. +fn deferred_housekeeping_delay( + in_flight: bool, + housekeeping_ran: bool, + now: u64, + last_housekeeping_ns: u64, +) -> Option { + if in_flight || housekeeping_ran { + return None; + } + Some( + HOUSEKEEPING_NS + .saturating_sub(now.saturating_sub(last_housekeeping_ns)) + .max(1), + ) +} + struct Service<'a> { firmware: &'a mut Firmware, deferred: &'a mut DeferredBatch, render_masks: [u64; 2], + compute_scan: Option, settlement_error: Option, } @@ -30,23 +70,6 @@ impl event::Transport for Service<'_> { fn roles(&self) -> &'static [Role] { self.firmware.roles() } - fn reports_after_signal(&self) -> bool { - self.firmware.init.is_m5() - } - fn trace(&mut self, role: Role) { - let firmware = &mut *self.firmware; - firmware - .rings - .drain_trace(&firmware.primary.state.shared.dev, &firmware.init, role); - } - fn statistics(&mut self, role: Role) { - let firmware = &mut *self.firmware; - firmware.observe_statistics_power(); - firmware - .rings - .drain_statistics(&firmware.primary.state.shared.dev, &firmware.init, role); - firmware.observe_statistics_power(); - } fn drain( &mut self, role: Role, @@ -117,15 +140,16 @@ impl event::Queues for Service<'_> { fn retain_render_completions(&mut self, masks: [u64; 2]) { // Inline timeout and drain callers may discard the worker hints. The // queue owner retains stamps until its borrowed pair returns to scan. - self.firmware.queues.retain_render_completions(masks); - self.render_masks[0] |= masks[0]; - self.render_masks[1] |= masks[1]; + let matched = self.firmware.queues.retain_render_completions(masks); + self.render_masks[0] |= matched[0]; + self.render_masks[1] |= matched[1]; } fn complete_compute(&mut self, masks: [u64; 2]) -> Result { // A batch without a queue identity still observes completions whose // notification was coalesced; identified batches retain QID filtering. let selected = (masks != [0; 2]).then_some(masks); - self.firmware.scan_compute(selected, self.deferred) + self.compute_scan = Some(self.firmware.scan_compute_summary(selected, self.deferred)?); + Ok(()) } } @@ -168,11 +192,7 @@ impl recovery::Memory for Service<'_> { } } let mut sources = self.firmware.init.fault_sources()?; - // M5 attribution leaves the firmware reason out (see InitData::fault_sources); a - // latched MMU fault is reason 3. - if mmu_fault && sources.reason.is_none() { - sources.reason = Some(recovery::PAGE_FAULT); - } + sources.settle_reason(mmu_fault, || self.firmware.port.fault_banks().ok()); Ok(sources) } @@ -194,9 +214,12 @@ impl recovery::Queues for Service<'_> { fn render_pass_started(&self, qid: u8, stamp: u64) -> Option { self.firmware.queues.render_pass_started(qid, stamp) } - fn render_culprit(&self, blamed: u8) -> Option { + fn render_culprit(&self, blamed: u8) -> Option { self.firmware.queues.render_culprit(blamed) } + fn fault_culprit(&self, slots: u64) -> Option { + self.firmware.queues.fault_culprit(slots) + } fn publish_recovery_targets(&self) -> Option { let mut failure = self.firmware.queues.publish_render_recovery_targets(); for queue in self @@ -229,6 +252,19 @@ impl recovery::Queues for Service<'_> { .and_then(|queue| queue.oldest_spared()) }) } + // Not on M5: it takes published work back through its recovery target, and its spared + // work keeps the old collateral rule. + fn collateral_before(&self, qid: u8, generation: u64) -> bool { + !self.firmware.init.is_m5() && self.firmware.queues.render_collateral_before(qid, generation) + } + fn note_collateral(&mut self, qid: u8, generation: u64) { + if !self.firmware.init.is_m5() { + self.firmware.queues.note_render_collateral(qid, generation); + } + } + fn marks_collateral(&self, qid: u8) -> bool { + !self.firmware.init.is_m5() && self.firmware.queues.render_oldest_spared(qid).is_some() + } fn visit_owners(&self, qid: u8, visit: &mut dyn FnMut(&Arc)) { self.firmware.queues.visit_render_owners(qid, visit); for queue in self @@ -273,32 +309,40 @@ impl recovery::Queues for Service<'_> { queue.note_interrupted(stamp) }) } + fn note_kill_sightings(&self, generation: u64) { + self.firmware.queues.note_render_kill_sightings(generation); + } fn report_blamed_render(&self, qid: u8) { self.firmware .queues .report_render_recovery(qid, &self.firmware.port); } - fn report_mmu_fault(&self) { + fn report_mmu_fault(&self) -> u64 { let banks = match self.firmware.port.fault_banks() { Ok(banks) => banks, Err(error) => { pr_warn!("G17: recovery MMU fault banks unreadable: {:?}\n", error); - return; + return 0; } }; + let mut slots = 0u64; for (bank, &(status, address)) in banks.iter().enumerate() { match crate::regs::decode_fault(status, address, true) { - Some(info) => pr_warn!( - "G17: recovery MMU fault bank {}: address {:#x} {} {:?} unit {:?} ({:#x}) level {} vm_slot {} sideband {:#x} (status {:#x})\n", - bank, info.address, if info.read { "read" } else { "write" }, info.reason, - info.unit, info.unit_code, info.level, info.vm_slot, info.sideband, status - ), - None => pr_info!( - "G17: recovery MMU fault bank {}: no fault (status {:#x})\n", - bank, status - ), + Some(info) => { + pr_warn!( + "G17: recovery MMU fault bank {}: address {:#x} {} {:?} unit {:?} ({:#x}) level {} vm_slot {} sideband {:#x} (status {:#x})\n", + bank, info.address, if info.read { "read" } else { "write" }, info.reason, + info.unit, info.unit_code, info.level, info.vm_slot, info.sideband, status + ); + // Slot 0 is the firmware's own context, never a client's. + if info.vm_slot != 0 { + slots |= 1u64.checked_shl(info.vm_slot).unwrap_or(0); + } + } + None => pr_info!("G17: recovery MMU fault bank {}: no fault (status {:#x})\n", bank, status), } } + slots } fn settle_blamed_render(&mut self, qid: u8, error: Error) { let result = self @@ -337,9 +381,10 @@ impl Firmware { Ok(()) } - /// Drains every role's trace ring, then their statistics rings. On M5 the event worker calls - /// this after it has signalled the completions of its pass: the reports are not scheduling - /// inputs. + /// Drains every role's trace ring, then their statistics rings. The event worker calls this + /// after it has signalled the completions of its pass: the reports are not scheduling inputs. + /// While work stays in flight it does so at the housekeeping cadence, and a recovery pass + /// does so before the restart resets the report rings. fn drain_reports(&mut self) { let dev = &self.primary.state.shared.dev; for &role in self.roles() { @@ -354,8 +399,8 @@ impl Firmware { } } - /// A step of the event pass is waiting on the firmware with no event to wake it. - fn runtime_polling(&self, now: u64) -> bool { + /// Non-compute checks of [`Self::runtime_polling`], reused on the single-lock fast path. + fn non_compute_runtime_polling(&self, now: u64) -> bool { self.render_control_backpressured() || self.init.outer_waiting() || self.queues.replay_outer_wait.is_some() @@ -363,6 +408,11 @@ impl Firmware { || self.queues.render.replay_polling() || self.queues.teardown.polling(now) || self.compute_exit_polling(now) + } + + /// A step of the event pass is waiting on the firmware with no event to wake it. + fn runtime_polling(&self, now: u64) -> bool { + self.non_compute_runtime_polling(now) || self .queues .compute @@ -412,10 +462,19 @@ impl Firmware { &mut self, deferred: &mut DeferredBatch, ) -> Result<(event::Pending, [u64; 2])> { + let (pending, masks, _) = self.service_runtime_events_scan(deferred)?; + Ok((pending, masks)) + } + + fn service_runtime_events_scan( + &mut self, + deferred: &mut DeferredBatch, + ) -> Result<(event::Pending, [u64; 2], Option)> { let mut service = Service { firmware: self, deferred, render_masks: [0; 2], + compute_scan: None, settlement_error: None, }; let pending = event::service(&mut service)?; @@ -427,7 +486,7 @@ impl Firmware { shared.preparations.close(); shared.queue_events(); } - Ok((pending, service.render_masks)) + Ok((pending, service.render_masks, service.compute_scan)) } /// Preparation admission is already closed and all builders have joined. @@ -438,6 +497,7 @@ impl Firmware { firmware: self, deferred, render_masks: [0; 2], + compute_scan: None, settlement_error: None, }; let result = recovery::service(&mut service, || { @@ -449,6 +509,7 @@ impl Firmware { .firmware .port .set_generation(service.firmware.recovery.generation()); + service.firmware.port.reset_m5_history(); service.firmware.rings.invalidate_statistics(); let result = result?; // Counted once the restart is classified, so the restart that reaches the limit has @@ -499,26 +560,16 @@ impl crate::g17::Shared { self.stop_runtime(); return; } - let mut deferred = { - let mut state = self.state.lock(); - let Some(firmware) = (*state).as_deref_mut() else { - return; - }; - let Some(deferred) = firmware.queues.worker_deferred.take() else { - drop(state); - self.lose_device_quietly(); - return; - }; - deferred + let Some(mut deferred) = self.worker_deferred.lock().take() else { + self.lose_device_quietly(); + return; }; crate::g17::trace::event(0); let result = self.runtime_event_turn(&mut deferred); deferred.finish(); crate::g17::trace::event(2); self.queue_feed(); - if let Some(firmware) = (*self.state.lock()).as_deref_mut() { - firmware.queues.worker_deferred = Some(deferred); - } + *self.worker_deferred.lock() = Some(deferred); if let Err(error) = result { dev_err!(self.dev.as_ref(), "GPU event service failed: {:?}\n", error); self.lose_device_quietly(); @@ -531,22 +582,137 @@ impl crate::g17::Shared { let requested = self .housekeeping .swap(false, core::sync::atomic::Ordering::AcqRel); - let (recover, masks) = { + let (recover, masks, fast_done, render_changed) = { + // Taken before `state` so single-lock render retirement observes a live preparation + // epoch and drops it before `wait_drained_until()` if recovery opens. + let fast_epoch = self.preparations.try_enter().ok(); let mut state = self.state.lock(); let Some(firmware) = (*state).as_deref_mut() else { return Ok(()); }; - let (pending, masks) = firmware.service_runtime_events(deferred)?; + let (pending, masks, compute_scan) = firmware.service_runtime_events_scan(deferred)?; let recover = pending.recovery || firmware.recovery.pending(); if recover { // Epoch closure and event consumption are serialized with every // publisher. Joining builders must happen after unlocking. self.preparations.close(); } - (recover, masks) + // Steady-state compute or render completions with no replays, no waiters and + // housekeeping not yet due finish in this single device-mutex hold; fences are + // signalled right after unlocking. Transient idle intervals defer housekeeping to the + // cadence timer rather than draining reports on every completion. + let mut fast_done = false; + let mut render_changed = false; + let mut rescan = false; + if !recover + && !requested + && !self.crashed.load(core::sync::atomic::Ordering::Acquire) + { + let needs_render = masks != [0; 2] || firmware.render_observation_needed(); + let render_clean = if !needs_render { + true + } else if fast_epoch.as_ref().is_some_and(|epoch| epoch.is_current()) { + let before = deferred.pending(); + match firmware.try_fast_observe_render(deferred)? { + super::render::observe::FastRenderOutcome::Done => { + render_changed = true; + true + } + super::render::observe::FastRenderOutcome::Idle => true, + // The full pass would find nothing more and arm the rescan poll. + super::render::observe::FastRenderOutcome::Rescan => { + render_changed = deferred.pending() != before; + rescan = true; + true + } + super::render::observe::FastRenderOutcome::Fallback => { + render_changed = deferred.pending() != before; + false + } + } + } else { + false + }; + // Render completions that found nothing to retire here (Idle) are owed to the + // borrowers of their pairs, which observe them on return. + if render_clean && (compute_scan.is_some() || render_changed || masks != [0; 2]) { + let scan = match compute_scan { + Some(scan) => scan, + None => { + let mut scan = super::ComputeScan::default(); + for queue in firmware + .queues + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + { + scan.in_flight |= queue.in_flight(); + scan.replay |= queue.replay_commands() != 0; + scan.polling |= + queue.retirement_polling() || queue.pool_release_pending(); + } + scan + } + }; + let now = super::now_ns(); + let in_flight = scan.in_flight || firmware.queues.render_in_flight(); + let no_replay = !scan.replay && !firmware.queues.render.replay_parked(); + let last_hk = self + .housekeeping_ns + .load(core::sync::atomic::Ordering::Relaxed); + let has_waiters = self.channels.has_waiters() + || self.progress.has_waiters() + || self.queues.has_waiters() + || self.renders.has_waiters(); + let no_housekeeping = !housekeeping_due( + false, + false, + false, + !firmware.queues.teardown.is_empty(), + has_waiters, + now, + last_hk, + ); + let no_outer_or_grow = + !firmware.init.outer_waiting() && !firmware.render_grow_ready(); + if no_replay && no_housekeeping && no_outer_or_grow { + if let Some(delay) = firmware.idle_check(now, in_flight)? { + self.queue_idle(delay); + } + if let Some(delay) = + deferred_housekeeping_delay(in_flight, false, now, last_hk) + { + self.queue_housekeeping(delay); + } + let polling = + rescan || scan.polling || firmware.non_compute_runtime_polling(now); + if polling { + self.queue_poll(); + if firmware.render_control_backpressured() { + self.queue_poll_after(1); + } + } + if channel::Events::pending(&firmware.init, Role::Primary)? + || (firmware.secondary.is_some() + && channel::Events::pending(&firmware.init, Role::Secondary)?) + { + self.queue_event_records(); + } + fast_done = true; + } + } + } + (recover, masks, fast_done, render_changed) }; + if render_changed { + self.note_changed(); + } deferred.finish(); crate::g17::trace::event(1); + if fast_done { + return Ok(()); + } if recover { self.preparations .wait_drained_until(super::now_ns().saturating_add(super::WORK_RING_WAIT_NS))?; @@ -558,11 +724,12 @@ impl crate::g17::Shared { if self.crashed.load(core::sync::atomic::Ordering::Acquire) { return Err(EIO); } - if firmware.init.is_m5() { - // The completions above are signalled; the reports that arrived with them come after. - firmware.drain_reports(); - } + // Capture pre-recovery trace/statistics reports before firmware restart resets the + // report rings, matching the non-throttled post-signal ordering. + let mut reports_drained = false; if recover { + firmware.drain_reports(); + reports_drained = true; firmware.service_runtime_recovery(deferred)?; if !firmware.recovery.pending() && !self.sleep_gate.load(core::sync::atomic::Ordering::Acquire) @@ -579,15 +746,24 @@ impl crate::g17::Shared { // Publication may service events but must never recurse into replay. firmware.replay_compute(deferred)?; firmware.replay_render(deferred)?; - drop(state); - self.observe_renders(masks, deferred)?; - let mut state = self.state.lock(); + // Skip dropping and re-acquiring the device mutex around a no-op render observation. + if masks != [0; 2] || firmware.render_observation_needed() { + firmware.drain_render_deferred(masks, deferred)?; + drop(state); + self.observe_renders(deferred)?; + state = self.state.lock(); + if self.crashed.load(core::sync::atomic::Ordering::Acquire) { + return Err(EIO); + } + if let Some(firmware) = (*state).as_deref() { + if !firmware.recovery.pending() && firmware.queues.render_needs_rescan() { + self.queue_poll(); + } + } + } let Some(firmware) = (*state).as_deref_mut() else { return Ok(()); }; - if self.crashed.load(core::sync::atomic::Ordering::Acquire) { - return Err(EIO); - } let now = super::now_ns(); let compute = firmware .queues @@ -598,24 +774,27 @@ impl crate::g17::Shared { .any(|queue| queue.in_flight()); let in_flight = compute || firmware.queues.render_in_flight(); let idle = firmware.idle_check(now, in_flight)?; - // Expiries, drained pairs, exits, pool and heap trimming and teardown give back what - // retirement freed; a completion needs none of them to retire or to signal. While work - // is in flight and nothing waits for capacity, a pass for firmware records alone skips - // them. Any requested pass, recovery, teardown, a waiter, the last retirement and, at - // the latest, the first pass after HOUSEKEEPING_NS run them all. - let housekeeping = requested - || recover - || !in_flight - || firmware.recovery.pending() - || !firmware.queues.teardown.is_empty() - || self.channels.has_waiters() + // Expiries, drained pairs, exits, pool and heap trimming, teardown and M5 report + // drains give back what retirement freed; a completion needs none of them to retire + // or to signal. While nothing waits for capacity and `HOUSEKEEPING_NS` has not elapsed, + // a pass for firmware records alone skips them; when no work stays in flight, a bounded + // housekeeping timer guarantees cleanup runs once the interval expires. + let last_hk = self + .housekeeping_ns + .load(core::sync::atomic::Ordering::Relaxed); + let has_waiters = self.channels.has_waiters() || self.progress.has_waiters() || self.queues.has_waiters() - || self.renders.has_waiters() - || now.saturating_sub( - self.housekeeping_ns - .load(core::sync::atomic::Ordering::Relaxed), - ) >= HOUSEKEEPING_NS; + || self.renders.has_waiters(); + let housekeeping = housekeeping_due( + requested, + recover, + firmware.recovery.pending(), + !firmware.queues.teardown.is_empty(), + has_waiters, + now, + last_hk, + ); let mut lingers = None; let mut drains = None; let mut kills = None; @@ -624,6 +803,11 @@ impl crate::g17::Shared { if housekeeping { self.housekeeping_ns .store(now, core::sync::atomic::Ordering::Relaxed); + if !reports_drained { + // The completions above are signalled; reports are throttled to the + // housekeeping cadence while work stays in flight. + firmware.drain_reports(); + } if !firmware.recovery.pending() { lingers = firmware.expire_render_lingers(now)?; } @@ -651,6 +835,9 @@ impl crate::g17::Shared { let polling = firmware.runtime_polling(now); if polling { self.queue_poll(); + if firmware.render_control_backpressured() { + self.queue_poll_after(1); + } } // A heap with growth to give back is re-evaluated at least once per // shrink period, also while the device is otherwise idle. @@ -672,11 +859,13 @@ impl crate::g17::Shared { if let Some(delay) = idle { self.queue_idle(delay); } + if let Some(delay) = deferred_housekeeping_delay(in_flight, housekeeping, now, last_hk) { + self.queue_housekeeping(delay); + } if firmware.recovery.pending() { self.preparations.close(); self.queue_events(); } else if !recover - && !polling && (channel::Events::pending(&firmware.init, Role::Primary)? || (firmware.secondary.is_some() && channel::Events::pending(&firmware.init, Role::Secondary)?)) diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index ab33c149ba96d3..08545e3097cdfe 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -8,7 +8,7 @@ mod exit; mod dependencies; mod direct; mod grow; -mod observe; +pub(super) mod observe; mod pools; mod prepare; mod recovery; @@ -79,6 +79,9 @@ pub(super) struct RenderState { /// Graphs of released contexts the firmware may still walk (see `detach_context`): kept /// until the firmware stops, when this state is dropped. kept_graphs: KVec, + /// Killed guilty pairs whose rings the firmware never consumed (see `detach_context`): + /// kept, with their slots out of service, until the firmware stops. + kept_pairs: KVec, next_pm_generation: u64, } @@ -106,6 +109,7 @@ impl RenderState { grow: grow::Grow::new()?, retired: KVec::with_capacity(128, GFP_KERNEL)?, kept_graphs: KVec::new(), + kept_pairs: KVec::new(), next_pm_generation: 1, }) } @@ -232,18 +236,89 @@ impl RenderState { } impl Registry { - /// Yield unused warming only when admission has run out of physical slots. - /// Previously published graphs keep their existing ownership and retirement - /// rules. The caller destroys returned backing after dropping the device lock. + /// Whether at least one unused render entry holds unpublished QIDs that + /// [`Self::reclaim_unused_render_spare`] can cancel for compute. + pub(super) fn has_cancelable_render_spare(&self) -> Result { + for slot in 1..RENDER_SLOTS { + let Some(entry) = self.render.entries[slot].as_ref() else { + continue; + }; + if entry.constructing + || entry.preparing.is_some() + || entry.growing + || entry.pending_error.is_some() + || entry.pending_timeout + { + continue; + } + if !entry + .reservation + .ids + .iter() + .all(|id| self.qids.can_cancel_unpublished(*id)) + { + continue; + } + let expected = if let Some(pair) = entry.pair.as_ref() { + if pair.can_yield_unused()? { + Some(entry.reservation.owner) + } else { + continue; + } + } else if entry.context.is_none() { + None + } else { + continue; + }; + if self + .admission + .can_reassign_unused_spare(slot as u8, expected, None) + { + return Ok(true); + } + } + Ok(false) + } + + /// Yield unused warming or idle drained published siblings when admission + /// has run out of physical slots. Compute only cancels unpublished + /// identities; render can also detach an idle drained published sibling so + /// a new owner reuses its installed QIDs via `bind_owner()`. The caller + /// destroys returned backing after dropping the device lock. pub(super) fn reclaim_unused_render_spare( &mut self, owner: Option, require_ids: bool, ) -> Result> { - // Prefer an empty reservation or an already parked channel. - for with_backing in [false, true] { + if owner.is_some_and(|owner| owner == 0 || self.admission.owns_live_slot(owner)) { + return Ok(None); + } + // Prefer an empty reservation or an already parked channel, then a + // reusable or warmed unpublished pair, then an idle drained published + // sibling (render only), preferring non-wide siblings before wide ones. + for pass in 0..4u8 { + if pass >= 2 && owner.is_none() { + break; + } + let with_backing = pass != 0; for slot in 1..RENDER_SLOTS { + if pass == 2 && self.admission.is_wide(slot as u8) { + continue; + } + if with_backing + && self.render.entries[slot].as_ref().is_some_and(|entry| { + entry.pair.is_some() + && !entry.constructing + && entry.preparing.is_none() + && !entry.growing + && entry.pending_error.is_none() + && !entry.pending_timeout + }) + { + self.render.collect_retired(slot)?; + } let mut warm = false; + let mut detach = false; let expected = if let Some(entry) = self.render.entries[slot].as_ref() { if entry.constructing || entry.preparing.is_some() @@ -269,10 +344,17 @@ impl Registry { if !with_backing { continue; } - if owner.is_some() && pair.reusable()? { - None - } else if pair.can_yield_unused()? { - warm = true; + if pass == 1 { + if owner.is_some() && pair.reusable()? { + None + } else if pair.can_yield_unused()? { + warm = true; + Some(entry.reservation.owner) + } else { + continue; + } + } else if pair.detachable()? && !self.teardown.releasing(pair.context()) { + detach = true; Some(entry.reservation.owner) } else { continue; @@ -289,13 +371,171 @@ impl Registry { } None }; + let claimed = if detach { + self.admission + .release_unused_sibling(slot as u8, expected, true) + } else { + self.admission + .reassign_unused_spare(slot as u8, expected, owner) + }; + if !claimed { + continue; + } + if owner.is_none() { + let entry = self.render.entries[slot].take(); + if let Some(entry) = entry.as_ref() { + for id in entry.reservation.ids { + self.qids.cancel_unpublished(id)?; + } + if let Some(pair) = entry.pair.as_ref() { + self.buffers.unreserve_owner(pair.buffer_id())?; + } + self.note_build_room(); + } + return Ok(Some(UnusedRenderSpare { + _entry: entry, + _binding: None, + })); + } + let mut binding = None; + if warm { + let entry = self.render.entries[slot].as_mut().ok_or(EIO)?; + let mut pair = entry.pair.take().ok_or(EIO)?; + self.buffers.unreserve_owner(pair.buffer_id())?; + pair.release_owner(); + let (parked, retired) = KBox::into_inner(pair).park(); + entry.parked = Some(parked); + entry.context = None; + entry.pool = None; + binding = Some(retired); + } else if detach { + let entry = self.render.entries[slot].as_mut().ok_or(EIO)?; + entry.pair.as_mut().ok_or(EIO)?.release_owner(); + self.hold_render_slot(slot); + } + return Ok(Some(UnusedRenderSpare { + _entry: None, + _binding: binding, + })); + } + } + Ok(None) + } + + /// Slots whose live-sibling claim can be dropped under admission's lock + /// without modifying `render.entries` or dropping backing off-lock: + /// `(reclaimable_mask, installed_mask)`. + pub(super) fn reclaimable_render_slots(&self) -> Result<(u64, u64)> { + let mut reclaimable = 0u64; + let mut installed = 0u64; + for slot in 1..RENDER_SLOTS { + let bit = 1u64 << slot; + let Some(entry) = self.render.entries[slot].as_ref() else { + reclaimable |= bit; + continue; + }; + if entry.constructing + || entry.preparing.is_some() + || entry.growing + || entry.pending_error.is_some() + || entry.pending_timeout + { + continue; + } + if let Some(pair) = entry.pair.as_ref() { + if pair.reusable()? { + reclaimable |= bit; + installed |= bit; + } + } else if entry.parked.is_some() && entry.context.is_none() { + reclaimable |= bit; + installed |= bit; + } + } + Ok((reclaimable, installed)) + } + + /// Reclaim one idle live sibling (unbuilt, parked, reusable, warmed + /// unpublished, or idle drained published) so a new logical queue can take + /// its first pair. Published siblings keep their installed QIDs and detach + /// only that slot's owner so the next queue reuses them via `bind_owner()`. + /// The caller destroys any returned backing after dropping the device lock. + pub(super) fn reclaim_unused_render_sibling(&mut self) -> Result> { + for pass in 0..4u8 { + let with_backing = pass != 0; + for slot in 1..RENDER_SLOTS { + if pass == 2 && self.admission.is_wide(slot as u8) { + continue; + } + if with_backing + && self.render.entries[slot].as_ref().is_some_and(|entry| { + entry.pair.is_some() + && !entry.constructing + && entry.preparing.is_none() + && !entry.growing + && entry.pending_error.is_none() + && !entry.pending_timeout + }) + { + self.render.collect_retired(slot)?; + } + let mut warm = false; + let mut detach = false; + let mut keep_installed = false; + let expected = if let Some(entry) = self.render.entries[slot].as_ref() { + if entry.constructing + || entry.preparing.is_some() + || entry.growing + || entry.pending_error.is_some() + || entry.pending_timeout + { + continue; + } + let cancelable = entry + .reservation + .ids + .iter() + .all(|id| self.qids.can_cancel_unpublished(*id)); + keep_installed = !cancelable; + if let Some(pair) = entry.pair.as_ref() { + if !with_backing { + continue; + } + if pass == 1 { + if pair.reusable()? { + None + } else if pair.can_yield_unused()? { + warm = true; + Some(entry.reservation.owner) + } else { + continue; + } + } else if pair.detachable()? && !self.teardown.releasing(pair.context()) { + detach = true; + keep_installed = true; + Some(entry.reservation.owner) + } else { + continue; + } + } else { + if with_backing || entry.context.is_some() { + continue; + } + None + } + } else { + if with_backing { + continue; + } + None + }; if !self .admission - .reassign_unused_spare(slot as u8, expected, owner) + .release_unused_sibling(slot as u8, expected, keep_installed) { continue; } - if owner.is_none() { + if !keep_installed { let entry = self.render.entries[slot].take(); if let Some(entry) = entry.as_ref() { for id in entry.reservation.ids { @@ -322,6 +562,10 @@ impl Registry { entry.context = None; entry.pool = None; binding = Some(retired); + } else if detach { + let entry = self.render.entries[slot].as_mut().ok_or(EIO)?; + entry.pair.as_mut().ok_or(EIO)?.release_owner(); + self.hold_render_slot(slot); } return Ok(Some(UnusedRenderSpare { _entry: None, @@ -364,7 +608,20 @@ impl Registry { /// Tell admission whether another render pair can still be built. pub(super) fn note_build_room(&self) { - self.admission.note_build_room(self.qids.render_pair_fits()); + self.admission.note_build_room( + self.qids.render_pair_fits(), + self.qids.render_pair_capacity(), + ); + } + + #[cfg(CONFIG_KUNIT = "y")] + pub(super) fn publish_render_ids(&mut self, slot: u8) -> Result { + let ids = self.render.entry(slot)?.reservation.ids; + for id in ids { + self.qids.publish(id)?; + } + self.admission.note_published(slot); + Ok(()) } pub(super) fn ensure_render_ids(&mut self, slot: u8, owner: u64) -> Result { @@ -629,6 +886,23 @@ impl Host<'_> { } } } +/// Encodes the G17 render mailbox doorbell (0x83, priority in bits 3:2, pipe in bits 1:0). +/// +/// Firmware queue contract across both locked and direct render publishers: +/// - Non-M5 G17 submits render pairs to the dedicated tiling/fragment rings and rings pipe 0. +/// - M5 Pro/Max/Ultra (!J813_FORMS) submits render pairs into the shared compute work ring paired +/// with host-port gating writes and submission-history accounting, and rings pipe 2. +/// - J813 (J813_FORMS, common 26A428 firmware) uses the mailbox-only G17P queue forms (no +/// host-port or KSM register writes) and rings pipe 0. +fn render_doorbell_message(m5: bool, priority: u8) -> u64 { + let pipe = if m5 && !crate::g17::J813_FORMS.load(core::sync::atomic::Ordering::Relaxed) { + 2 + } else { + 0 + }; + (0x83 << crate::g17::MSG_TYPE_SHIFT) | u64::from(priority) << 2 | pipe +} + impl crate::g17::queue::render::Host for Host<'_> { fn generation(&self) -> u64 { self.firmware.recovery.generation() @@ -792,11 +1066,10 @@ impl crate::g17::queue::render::Host for Host<'_> { self.firmware.bridge.regs.g17_core_power() }); } - let result = self.firmware.primary.notify( - (0x83 << crate::g17::MSG_TYPE_SHIFT) - | u64::from(priority) << 2 - | if m5 && !crate::g17::J813_FORMS.load(core::sync::atomic::Ordering::Relaxed) { 2 } else { 0 }, - ); + let result = self + .firmware + .primary + .notify(render_doorbell_message(m5, priority)); if result.is_err() { self.firmware.primary.state.shared.lose_device_quietly(); } @@ -921,6 +1194,29 @@ impl crate::g17::Firmware { }) } + /// Undoes an unpublished pool preparation and flushes any final release + /// exposed when sibling renders completed while the preparation was lent. + fn rollback_render_pool(&mut self, preparation: pools::Preparation) -> Result { + let pending = match self.queues.render.pools.rollback(preparation) { + Ok(pending) => pending, + Err(error) => { + self.primary.state.shared.lose_device_quietly(); + return Err(error); + } + }; + if pending { + match self.release_render_lists() { + Ok(()) => {} + Err(error) if error == EAGAIN => self.primary.state.shared.queue_events(), + Err(error) => { + self.primary.state.shared.lose_device_quietly(); + return Err(error); + } + } + } + Ok(()) + } + /// Events have already been consumed by the caller. Each healthy completion /// services its final pool release before examining the next retained job. fn retire_render_slot( @@ -1050,6 +1346,29 @@ impl Registry { .find(|pair| pair.qids().contains(&qid)) .and_then(|pair| pair.oldest_spared()) } + /// See `recovery::Queues::collateral_before`. + pub(in crate::g17) fn render_collateral_before(&self, qid: u8, generation: u64) -> bool { + self.render + .entries + .iter() + .flatten() + .filter_map(|entry| entry.pair.as_ref()) + .find(|pair| pair.qids().contains(&qid)) + .is_some_and(|pair| pair.collateral_before(generation)) + } + /// See `recovery::Queues::note_collateral`. + pub(in crate::g17) fn note_render_collateral(&mut self, qid: u8, generation: u64) { + if let Some(pair) = self + .render + .entries + .iter_mut() + .flatten() + .filter_map(|entry| entry.pair.as_mut()) + .find(|pair| pair.qids().contains(&qid)) + { + pair.note_collateral(generation); + } + } /// Marks the interrupted group of the pair that owns `qid`. pub(in crate::g17) fn note_render_interrupted( &self, @@ -1259,13 +1578,15 @@ impl Registry { ) }) } - pub(in crate::g17) fn retain_render_completions(&mut self, masks: [u64; 2]) { + pub(in crate::g17) fn retain_render_completions(&mut self, masks: [u64; 2]) -> [u64; 2] { + let mut matched = [0u64; 2]; for entry in self.render.entries.iter_mut().flatten() { let mut hit = false; for id in entry.reservation.ids { let qid = usize::from(id.qid()); let bit = masks[qid / 64] & (1u64 << (qid % 64)); entry.event_masks[qid / 64] |= bit; + matched[qid / 64] |= bit; hit |= bit != 0; } // Event passes skip a pair while preparation, growth or an @@ -1276,14 +1597,20 @@ impl Registry { entry.missed_event = true; } } + matched } pub(in crate::g17) fn render_needs_rescan(&self) -> bool { self.render.entries.iter().flatten().any(|entry| { + // A completion that arrived while the pair was borrowed (`missed_event`) is owed to + // its borrower, whose return observes the pair or requests an event pass: no + // rescan waits for it. let active = entry .pair .as_ref() .map_or( - (entry.preparing.is_some() || entry.growing) && entry.borrowed_active, + (entry.preparing.is_some() || entry.growing) + && entry.borrowed_active + && !entry.missed_event, |pair| pair.published_in_flight(), ); active @@ -1377,7 +1704,7 @@ impl Registry { impl RenderState { pub(super) fn write_capacity(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result { writeln!(f, "retired_render_bindings used={} total={}", self.retired.len(), self.retired.capacity())?; - writeln!(f, "firmware_linked_render_graphs kept={} leaked={}", self.kept_graphs.len(), + writeln!(f, "firmware_linked_render_graphs kept={} kept_guilty_pairs={} leaked={}", self.kept_graphs.len(), self.kept_pairs.len(), teardown::LEAKED_GRAPHS.load(core::sync::atomic::Ordering::Relaxed))?; let unsettled = self.entries.iter().flatten() .filter_map(|entry| entry.pair.as_ref()) @@ -1401,6 +1728,18 @@ impl RenderState { } impl Registry { + /// The kick-ring views of one parked pair whose VM's client has closed it + /// (`ParkedPair::take_closed_views`), for the caller to drop off the device lock; `None` + /// once no parked pair holds any. + pub(in crate::g17) fn take_closed_parked_views( + &mut self, + ) -> Option<[Option; 2]> { + self.render.entries.iter_mut().flatten().find_map(|entry| { + let views = entry.parked.as_mut()?.take_closed_views(); + views.iter().any(Option::is_some).then_some(views) + }) + } + /// Give idle private backing to another ready client under capacity pressure. /// Keep graph/QID/context ownership; the next use rearms the same pool after /// its consumed release, exactly as eviction-driven reclaim does. diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs index 117edccb28e350..7fa602e0b2c9ff 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs @@ -11,10 +11,11 @@ //! retirement can complete its commands or their free-list references. use super::super::{Backend, DeferredBatch}; +use super::observe::FastRenderOutcome; use crate::g17::{ job::Packet, object::Allocator, - port::{Port, RenderRoom}, + port::{M5RenderRoom, Port, RenderRoom}, queue::render::{Pair, PublicationLease, RenderAddresses}, }; use core::sync::atomic::Ordering; @@ -33,13 +34,20 @@ pub(in crate::g17::runtime) struct Loan { uat: Arc, } +enum DirectTarget { + Legacy(RenderRoom), + M5(M5RenderRoom), +} + /// Publication host of a lent pair. Registration, first-publication and /// growth paths never run here: the loan requires an installed, registered /// graph that needs no growth. struct DirectHost<'a> { port: &'a Port, - render: &'a MutexGuard<'a, ()>, - room: RenderRoom, + render: Option>, + m5_outer: Option>>, + m5_claim: Option<&'a mut crate::g17::initdata::OuterClaim>, + target: DirectTarget, generation: u64, activation: Option<(u16, u64)>, } @@ -83,11 +91,38 @@ impl crate::g17::queue::render::Host for DirectHost<'_> { commit: impl FnOnce() -> Result, late_tiling: impl FnOnce(), ) -> Result<[u32; 2]> { - if priority != self.room.priority() { - return Err(EINVAL); + match &self.target { + DirectTarget::Legacy(room) => { + if priority != room.priority() { + return Err(EINVAL); + } + let render = self.render.as_ref().ok_or(EIO)?; + self.port.write_render_pair( + render, + room, + fragment, + tiling, + commit, + late_tiling, + ) + } + DirectTarget::M5(room) => { + if priority != room.priority() { + return Err(EINVAL); + } + let render = self.render.as_ref().ok_or(EIO)?; + let m5_outer = self.m5_outer.as_ref().ok_or(EIO)?; + self.port.write_m5_render_pair( + render, + m5_outer, + room, + fragment, + tiling, + commit, + late_tiling, + ) + } } - self.port - .write_render_pair(self.render, &self.room, fragment, tiling, commit, late_tiling) } fn publish_configuration_pair( &mut self, @@ -96,7 +131,7 @@ impl crate::g17::queue::render::Host for DirectHost<'_> { _tiling: &crate::g17::fw::channels::WorkSlot, _prepare: impl FnOnce(), ) -> Result { - // Only M5 publishes configuration pairs, never on this path. + // Cold-install configuration pairs never run on an already-registered pair. Err(EINVAL) } fn activate_render_pool(&mut self, id: u16, generation: u64) -> Result { @@ -112,15 +147,42 @@ impl crate::g17::queue::render::Host for DirectHost<'_> { _tiling: &crate::g17::fw::channels::WorkSlot, next: [u32; 2], ) -> Result { - if priority != self.room.priority() { - return Err(EINVAL); + match &self.target { + DirectTarget::Legacy(room) => { + if priority != room.priority() { + return Err(EINVAL); + } + let render = self.render.as_ref().ok_or(EIO)?; + self.port.expose_render_pair(render, room, next) + } + DirectTarget::M5(room) => { + if priority != room.priority() { + return Err(EINVAL); + } + let render = self.render.as_ref().ok_or(EIO)?; + let m5_outer = self.m5_outer.as_ref().ok_or(EIO)?; + let claim = self.m5_claim.as_deref_mut().ok_or(EIO)?; + self.port + .expose_m5_render_pair(render, m5_outer, room, claim, next) + } } - self.port.expose_render_pair(self.render, &self.room, next) } - /// Pipe 0 (tiling) in bits 1:0, priority class in bits 3:2. + /// Rings the shared render doorbell contract ([`super::render_doorbell_message`]). fn notify_render(&mut self, priority: u8) -> Result { - self.port - .notify((0x83 << crate::g17::MSG_TYPE_SHIFT) | u64::from(priority) << 2) + let m5 = matches!(self.target, DirectTarget::M5(_)); + if m5 { + let geometry = self.m5_outer.as_mut().ok_or(EIO)?; + if let Err(error) = self.port.note_m5_submission_history_locked(geometry, 2) { + pr_warn!("asahi: M5 submission history skipped: {:?}\n", error); + } + // Drop `m5_outer` before ringing the mailbox doorbell so competing M5 submitters + // do not wait behind mailbox I/O. + self.m5_outer = None; + } + // Outer ring producers, credits, and hazard order are committed; drop the render + // publication lock before mailbox I/O as well. + self.render = None; + self.port.notify(super::render_doorbell_message(m5, priority)) } fn note_submission(&mut self) -> Result { // Counted, with full effort witnessed, before the pair was lent. @@ -178,13 +240,24 @@ impl crate::g17::Firmware { let qids = pair.qids(); let pool = pair.pool().clone(); let buffer_id = pair.buffer_id(); + // An M5 PB token is bound to the hardware context and PB state it names. + let buffer_context = pair + .m5_pb_state_va() + .map(|pb_va| (packet.context.id(), pb_va)); let addresses = RenderAddresses { stamps: [ self.init.stamp_addresses(qids[0])?, self.init.stamp_addresses(qids[1])?, ], }; - let (buffer, buffer_token) = self.queues.buffers.acquire_owner(buffer_id)?; + let (buffer, buffer_token) = match buffer_context { + Some((context, pb_va)) => { + self.queues + .buffers + .acquire_owner_bound(buffer_id, context, pb_va)? + } + None => self.queues.buffers.acquire_owner(buffer_id)?, + }; let preparation = match self.queues.render.pools.prepare(&self.init, &pool) { Ok(preparation) => preparation, Err(error) => { @@ -199,13 +272,14 @@ impl crate::g17::Firmware { let lease = PublicationLease { free_list_generation: preparation.generation, buffer_token, - buffer_context: None, + buffer_context: buffer_context.map(|(context, _)| context), }; let pair = match self.queues.render.take_pair(slot, owner, packet) { Ok(pair) => pair, Err(error) => { - self.queues.render.pools.rollback(preparation); + let rollback = self.rollback_render_pool(preparation); self.queues.buffers.release(buffer)?; + rollback?; return if error == EBUSY { Ok(None) } else { Err(error) }; } }; @@ -224,35 +298,38 @@ impl crate::g17::Firmware { /// Takes a lent pair back and settles what its publication held: the /// free-list preparation is activated once published, rolled back with the - /// parameter-buffer reference otherwise. + /// parameter-buffer reference otherwise. True when a completion of the pair + /// arrived while it was lent: the caller owes the pair that observation. fn return_render( &mut self, slot: u8, loan: &mut Loan, activation: Option<(u16, u64)>, packet: &Arc, - ) -> Result { + ) -> Result { self.queues.render.return_pair(slot, &mut loan.pair)?; - if self.queues.render.take_missed_event(slot) { - // The record is retired by the next pass's observation, like any completion. - self.primary.state.shared.queue_event_records(); - } + let missed = self.queues.render.take_missed_event(slot); let entry = self.queues.render.entry_mut(slot)?; // A failure or timeout recorded against the lent pair is settled by the // event worker's collector, as after any other loan. if entry.pending_error.is_some() || entry.pending_timeout { self.primary.state.shared.queue_events(); } + let closed = entry.closed; let pair = entry.pair.as_mut().ok_or(EIO)?; - if entry.closed { + if closed { pair.release_owner(); } if !packet.is_published() { pair.discard_prepared(packet)?; } + let published = packet.is_published() || pair.graph_started(); // A failed publication may have quarantined the lent pair, and its owner may have // closed while it was lent. self.queues.hold_render_slot(usize::from(slot)); + if published && !closed { + self.queues.admission.note_published(slot); + } if let Some((id, generation)) = activation { if self.queues.render.pools.activate(id, generation).is_err() { self.primary.state.shared.lose_device_quietly(); @@ -262,10 +339,11 @@ impl crate::g17::Firmware { if packet.is_published() { self.queues.render.entry_mut(slot)?.published = true; } else { - self.queues.render.pools.rollback(preparation); + let rollback = self.rollback_render_pool(preparation); self.queues.buffers.release(loan.buffer)?; + rollback?; } - Ok(()) + Ok(missed) } } @@ -280,10 +358,8 @@ impl Backend { deferred: &mut DeferredBatch, ) -> Option { // A compute prefix needs the compute queue's state; leave it to the - // device-mutex path. M5 renders publish through the device mutex - // only: their host-port transaction is part of the publication. - if packet.context.is_m5() - || packet.is_published() + // device-mutex path. + if packet.is_published() || packet.cancel_requested() || packet.completion.status().get() != 0 || packet.order.wait_through[1].unwrap_or(0) != 0 @@ -303,12 +379,14 @@ impl Backend { if !port.note_submission() { return None; } + self.shared.note_submitter(); self.shared.note_gpu_activity(); match packet.completion.work_state().ok()?.acquire(crate::g17::job::Engine::Render) { Ok(_) => {} Err(error) if error == EBUSY => return None, Err(error) => return Some(Err(error)), } + let m5 = packet.context.is_m5(); let priority = packet.context.policy().priority(); let generation = port.generation(); let dev = self.shared.drm().ok()?; @@ -325,6 +403,10 @@ impl Backend { } }; let mut activation = None; + let mut recovery_started = false; + // Declared outside the publication closure so any unspent M5 outer claim drops + // after `m5_outer` and `render` are released (dropping an unspent claim can wake fences). + let mut m5_claim = None; let result = (|| { let pair = loan.pair.as_mut().ok_or(EIO)?; let alloc = Allocator { @@ -336,7 +418,14 @@ impl Backend { if !lease.is_current() { return Err(EBUSY); } - let room = port.observe_render_room(&render, priority)?.ok_or(EBUSY)?; + let m5_outer = m5.then(|| port.m5_outer_lock()); + let target = if let Some(guard) = m5_outer.as_ref() { + let (room, claim) = port.reserve_m5_render_locked(guard, priority)?; + m5_claim = Some(claim); + DirectTarget::M5(room) + } else { + DirectTarget::Legacy(port.observe_render_room(&render, priority)?.ok_or(EBUSY)?) + }; let mut dependencies = pair.own_dependencies(self.owner, packet)?; if let Some(footprint) = packet.footprint.as_ref() { dependencies.hazard_count = self.admission.publication_barriers( @@ -349,8 +438,10 @@ impl Backend { } let mut host = DirectHost { port, - render: &render, - room, + render: Some(render), + m5_outer, + m5_claim: m5_claim.as_mut(), + target, generation, activation: None, }; @@ -362,20 +453,63 @@ impl Backend { &mut |event| deferred.push(event), ); activation = host.activation; + drop(host); result?; - // A recovery that started meanwhile may have discarded the commands. - if port.generation() != generation || port.recovery_state()? != 0 { + // A generation advance while lent means the commands belong to a closed epoch. + if port.generation() != generation { return Err(EIO); } + // If recovery started during publication while our preparation lease still held + // the same generation, return_render() hands the published pair back before lease + // drops so the existing recovery pass settles or replays it once without failing + // an unrelated client's VM. + if port.recovery_state()? != 0 { + recovery_started = true; + } Ok(()) })(); + drop(m5_claim); + // The collector of the observation the return may owe, taken without waiting. + let mut collector = None; let returned = { let mut state = self.shared.state.lock(); match (*state).as_deref_mut() { Some(firmware) => { let returned = firmware.return_render(slot, &mut loan, activation, packet); + let returned = match returned { + // A completion arrived while the pair was lent. The event pass it would + // request takes the device mutex from another CPU after this owner's + // next lend and finds the pair lent again: observe it here, in this + // hold, unless recovery, a crash or another borrower's observation + // leaves it to that pass. + Ok(true) => { + if !recovery_started + && lease.is_current() + && !self.shared.crashed.load(Ordering::Acquire) + { + collector = self.shared.render_collector.try_lock(); + } + match collector.as_deref_mut() { + Some(batch) => firmware.observe_returned_render(slot, batch), + None => Ok(FastRenderOutcome::Fallback), + } + .map(|outcome| match outcome { + // Retired by the next pass's observation, like any completion. + FastRenderOutcome::Fallback => self.shared.queue_event_records(), + FastRenderOutcome::Rescan => self.shared.queue_poll(), + FastRenderOutcome::Done | FastRenderOutcome::Idle => {} + }) + } + Ok(false) => Ok(()), + Err(error) => Err(error), + }; let grow_ready = firmware.render_grow_ready(); drop(state); + // Fences signal off the device mutex, before another borrower can collect. + if let Some(batch) = collector.as_deref_mut() { + batch.finish(); + } + drop(collector); if grow_ready { self.shared.queue_grow(); } @@ -388,6 +522,9 @@ impl Backend { }; self.shared.note_changed(); drop(lease); + if recovery_started { + self.shared.queue_events(); + } if let Err(error) = returned { self.shared.lose_device_quietly(); return Some(Err(error)); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/exit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/exit.rs index 6c58f728b3eb59..44231b6cec772f 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/exit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/exit.rs @@ -28,11 +28,34 @@ impl RenderState { /// Slots of `context`'s pairs whose commands all ran but stay unretired until its kill. pub(in crate::g17::runtime) fn executed_slots(&self, context: &Arc) -> u64 { + self.slots_where(|pair| pair.executed_for_kill(context)) + } + + /// Slots of `context`'s pairs whose guilty work stays unretired until its kill + /// (`Pair::guilty_for_kill`). + pub(in crate::g17::runtime) fn guilty_slots(&self, context: &Arc, generation: u64) -> u64 { + self.slots_where(|pair| pair.guilty_for_kill(context, generation)) + } + + /// Slots of `context`'s pairs that only its kill releases (`Pair::releasable_by_kill`). + pub(in crate::g17::runtime) fn kill_slots(&self, context: &Arc, generation: u64) -> u64 { + self.slots_where(|pair| pair.releasable_by_kill(context, generation)) + } + + /// The owner and context of `slot`'s pair while that owner is still open, its VM failed as + /// guilty (`Pair::failed_guilty`), and no builder or owner switch holds the slot. + pub(in crate::g17::runtime) fn failed_open_owner(&self, slot: usize) -> Option<(u64, Arc)> { + let entry = self.entries.get(slot)?.as_ref()?; + let pair = entry.pair.as_deref()?; + let open = !entry.closed && entry.preparing.is_none() && entry.pending_owner.is_none(); + (open && pair.owner() == Some(entry.reservation.owner) && pair.failed_guilty()) + .then(|| (entry.reservation.owner, pair.context().clone())) + } + + fn slots_where(&self, matches: impl Fn(&crate::g17::queue::render::Pair) -> bool) -> u64 { let mut slots = 0; for (slot, entry) in self.entries.iter().enumerate() { - if entry.as_ref().and_then(|entry| entry.pair.as_ref()) - .is_some_and(|pair| pair.executed_for_kill(context)) - { + if entry.as_ref().and_then(|entry| entry.pair.as_deref()).is_some_and(&matches) { slots |= 1u64 << slot; } } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs b/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs index 57543be54e8356..53a0029b37dd7d 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs @@ -7,15 +7,63 @@ use super::super::DeferredBatch; use core::sync::atomic::Ordering; use kernel::{prelude::*, sync::Arc}; +/// Outcome of attempting single-lock steady-state render completion in `runtime_event_turn()`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::g17::runtime) enum FastRenderOutcome { + /// Non-steady state or additional render work requires the full `observe_renders()` path. + Fallback, + /// Healthy render state with no ready observation to retire. + Idle, + /// Retired the single ready render observation cleanly with no further render work pending. + Done, + /// Retired every ready observation in steady state, while published work whose completion + /// was noted stays in flight (`render_needs_rescan`): its later completions are observed by + /// their own events or by the rescan poll, which is all the full `observe_renders()` pass + /// would add. + Rescan, +} + impl crate::g17::Firmware { + /// Whether `observe_renders` has any deferred settlement or in-flight render observation + /// pending. Pure compute passes can skip dropping and re-acquiring the device mutex when false. + pub(in crate::g17) fn render_observation_needed(&self) -> bool { + for slot in 1..self.queues.render.entries.len() { + let Some(entry) = self.queues.render.entries[slot].as_ref() else { + continue; + }; + let Some(pair) = entry.pair.as_ref() else { + continue; + }; + if entry.pending_error.is_some() || entry.pending_timeout || entry.closed { + return true; + } + if !self.recovery.pending() + && entry.preparing.is_none() + && !entry.growing + && pair.published_in_flight() + && (crate::g17::queue::render::completion_noted(pair.qids(), entry.event_masks) + || pair.stamp_waiting()) + { + return true; + } + } + false + } + /// The first slot from `start` whose pair has news to observe: published work in flight, the /// fragment queue's notification seen (`completion_noted`), and an observation the pair accepts. fn next_render_observation(&mut self, start: usize) -> Result> { + let end = self.queues.render.entries.len(); + self.next_render_observation_in(start, end) + } + + /// [`Self::next_render_observation`] among the slots `start..end`. + fn next_render_observation_in(&mut self, start: usize, end: usize) -> Result> { if self.recovery.pending() { return Ok(None); } let state = crate::g17::recovery::Memory::recovery_state(&self.init)?; - for slot in start..self.queues.render.entries.len() { + for slot in start..end.min(self.queues.render.entries.len()) { let Some(entry) = self.queues.render.entries[slot].as_ref() else { continue; }; @@ -57,7 +105,7 @@ impl crate::g17::Firmware { &mut self, slot: usize, deferred: &mut DeferredBatch, - ) -> Result { + ) -> Result { let terminal = self.queues.render.entries[slot] .as_mut() .and_then(|entry| entry.pair.as_mut()) @@ -67,40 +115,182 @@ impl crate::g17::Firmware { self.scan_compute(None, deferred)?; self.settle_render_vm(&status, error, deferred)?; self.queues.fail_compute_vm(&status, error, deferred)?; + return Ok(true); } - Ok(()) + Ok(false) } -} -impl crate::g17::Shared { - pub(in crate::g17) fn observe_renders( - self: &Arc, + /// Retains newly reported render masks and drains any deferred per-slot errors, timeouts, or + /// closes while the caller already holds the device mutex. + pub(in crate::g17::runtime) fn drain_render_deferred( + &mut self, masks: [u64; 2], deferred: &mut DeferredBatch, ) -> Result { + let _ = self.queues.retain_render_completions(masks); + // Returned preparers can have deferred a VM failure or timeout. + // Only this full worker collector runs their final observations. + for slot in 1..self.queues.render.entries.len() { + if self.queues.render.entries[slot] + .as_ref() + .is_some_and(|entry| { + entry.pair.is_some() + && (entry.pending_error.is_some() + || entry.pending_timeout + || entry.closed) + }) + { + self.apply_render_deferred(slot as u8, deferred)?; + } + } + Ok(()) + } + + /// Retires healthy steady-state render completions (across one or more coalesced ready slots, + /// bounded by `RENDER_SLOTS` and preallocated `deferred` room) under the event worker's + /// already-held device mutex with a live preparation lease. Any error, timeout, close, + /// growth, replay, terminal fault, deferred-room shortage, or remaining render work returns + /// `Fallback` so the full `observe_renders()` loop handles it. + pub(in crate::g17::runtime) fn try_fast_observe_render( + &mut self, + deferred: &mut DeferredBatch, + ) -> Result { + let end = self.queues.render.entries.len(); + self.fast_observe_renders(1, end, deferred) + } + + /// The observation a borrower owes the pair it has just put back into `slot`, in the hold + /// that put it back, with a live preparation lease and a collector of the event worker's size + /// (`deferred`): the event worker's single-lock retirement ([`Self::try_fast_observe_render`]) + /// of that slot alone. `Fallback` leaves the slot to the worker's full pass; otherwise its + /// ready completions are retired (`Rescan`: and the rescan poll covers what stays in flight). + /// + /// The event pass a completion of a lent pair would otherwise request runs on another CPU and + /// takes the device mutex after the borrower's next lend of the same pair, so it finds the + /// pair lent again; observing here retires every completion by the return of the loan it + /// arrived during. + pub(in crate::g17::runtime) fn observe_returned_render( + &mut self, + slot: u8, + deferred: &mut DeferredBatch, + ) -> Result { + let slot = usize::from(slot); + self.fast_observe_renders(slot, slot + 1, deferred) + } + + /// [`Self::try_fast_observe_render`] for the observations of the slots `start..end`; the + /// steady-state checks still cover every slot. + fn fast_observe_renders( + &mut self, + start: usize, + end: usize, + deferred: &mut DeferredBatch, + ) -> Result { + if self.recovery.pending() + || self.queues.render.replay_parked() + || self.render_grow_pending() + || self.render_grow_ready() { - let mut state = self.state.lock(); - let Some(firmware) = (*state).as_deref_mut() else { - return Ok(()); + return Ok(FastRenderOutcome::Fallback); + } + for slot in 1..self.queues.render.entries.len() { + let Some(entry) = self.queues.render.entries[slot].as_ref() else { + continue; }; - firmware.queues.retain_render_completions(masks); - // Returned preparers can have deferred a VM failure or timeout. - // Only this full worker collector runs their final observations. - for slot in 1..firmware.queues.render.entries.len() { - if firmware.queues.render.entries[slot] - .as_ref() - .is_some_and(|entry| { - entry.pair.is_some() - && (entry.pending_error.is_some() - || entry.pending_timeout - || entry.closed) + if entry.pending_error.is_some() + || entry.pending_timeout + || entry.closed + || entry.growing + { + return Ok(FastRenderOutcome::Fallback); + } + } + let mut retired_any = false; + for _ in 0..crate::hw::t8140::queues::RENDER_SLOTS { + let Some(slot) = self.next_render_observation_in(start, end)? else { + return Ok(if self.queues.render_needs_rescan() { + FastRenderOutcome::Rescan + } else if retired_any { + FastRenderOutcome::Done + } else { + FastRenderOutcome::Idle + }); + }; + if !deferred.has_room(2) { + return Ok(FastRenderOutcome::Fallback); + } + let observed = self.queues.render.entries[slot] + .as_ref() + .and_then(|entry| entry.pair.as_ref()) + .ok_or(EIO)? + .observe_front(); + let missed = self.queues.render.take_missed_event(slot as u8); + if missed || self.render_grow_pending() { + self.primary.state.shared.queue_event_records(); + } + let state = crate::g17::recovery::Memory::recovery_state(&self.init)?; + let progressed = match observed { + Ok(observed) => self.with_render(slot, |pair, host| { + pair.retire_observed(observed, state, host, &mut |event| { + deferred.push(event) }) - { - firmware.apply_render_deferred(slot as u8, deferred)?; + })?, + Err(error) if error == EAGAIN => false, + Err(error) => return Err(error), + }; + if progressed { + match self.release_render_lists() { + Err(error) if error == EAGAIN => {} + result => result?, } } + self.queues.render.collect_retired(slot)?; + let had_terminal = self.settle_render_terminal(slot, deferred)?; + if self + .queues + .render + .entry(slot as u8)? + .pair + .as_ref() + .is_some_and(|pair| !pair.in_flight()) + { + self.queues.render.entry_mut(slot as u8)?.event_masks = [0; 2]; + } + if !progressed + || missed + || had_terminal + || self.recovery.pending() + || self.render_grow_pending() + || self.render_grow_ready() + { + return Ok(FastRenderOutcome::Fallback); + } + // Work still in flight behind this front keeps its noted completion: retire whatever + // else is ready in this hold before deciding. + retired_any = true; + } + if self.next_render_observation_in(start, end)?.is_some() { + return Ok(FastRenderOutcome::Fallback); + } + if self.queues.render_needs_rescan() { + return Ok(FastRenderOutcome::Rescan); + } + Ok(if retired_any { + FastRenderOutcome::Done + } else { + FastRenderOutcome::Idle + }) + } +} + +impl crate::g17::Shared { + pub(in crate::g17) fn observe_renders( + self: &Arc, + deferred: &mut DeferredBatch, + ) -> Result { + if deferred.pending() != 0 { + deferred.finish(); } - deferred.finish(); let mut cursor = 1; let mut remaining = crate::hw::t8140::queues::RENDER_DEPTH; let mut retries = 0; @@ -161,7 +351,7 @@ impl crate::g17::Shared { // An observation of the old front is committed before a queued // exact timeout is permitted to advance that same tracker. firmware.apply_render_deferred(slot as u8, deferred)?; - firmware.settle_render_terminal(slot, deferred)?; + let _ = firmware.settle_render_terminal(slot, deferred)?; if firmware .queues .render @@ -190,14 +380,6 @@ impl crate::g17::Shared { retries = 0; } } - { - let state = self.state.lock(); - if (*state).as_deref().is_some_and(|firmware| { - !firmware.recovery.pending() && firmware.queues.render_needs_rescan() - }) { - self.queue_poll(); - } - } Ok(()) } } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs b/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs index 25d81a1976bba3..c3a66941cfbaec 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs @@ -24,10 +24,10 @@ pub(super) struct Pools { leases: KVec>, } -/// Undo state cannot leave the device-locked publication transaction. Rollback -/// is permitted only before the packet exposes its first firmware reference. +/// Undo handle for one unpublished `prepare()` call. Rollback undoes only +/// this preparation's references, preserving any sibling completions or +/// control-ring release observations that occurred while lent. pub(super) struct Preparation { - previous: Option, slot: usize, pub(super) generation: u64, } @@ -96,11 +96,7 @@ impl Pools { } let generation = next.generation(); self.leases[slot] = Some(next); - Ok(Preparation { - previous, - slot, - generation, - }) + Ok(Preparation { slot, generation }) } /// Warming validates the incoming owner and stages its descriptor without @@ -170,8 +166,15 @@ impl Pools { lease.retire_prepare() } - pub(super) fn rollback(&mut self, preparation: Preparation) { - self.leases[preparation.slot] = preparation.previous; + /// Rolls back one unpublished preparation without disturbing sibling + /// completions or release observations that occurred while it was lent. + /// Returns whether a final release is now pending on this pool. + pub(super) fn rollback(&mut self, preparation: Preparation) -> Result { + let lease = self.leases[preparation.slot].as_mut().ok_or(EIO)?; + if lease.generation() != preparation.generation { + return Err(EIO); + } + Ok(lease.cancel_prepare()?.is_some()) } /// Preflight a paired retirement before QoS or PB reference accounting. diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index dc05f1f0ef5ba1..1c57ed12adcef6 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -537,7 +537,7 @@ impl super::super::Backend { first, } = *ctx; let built = (|| -> Result<_> { - parked.clear_for_vm(self.context.vm().id())?; + parked.clear_for_vm(self.context.vm())?; let free_list = self.context.render_pool( alloc, &resources.ids, @@ -613,10 +613,15 @@ impl super::super::Backend { // returns, while the original installed kick owner stays live. drop(prepared); drop(storage); + // Views a returning pair gives up because its VM closed meanwhile; they drop after the + // device lock. Checked under the lock, so a VM closed before the pair is back is seen + // either here or by the close's own pass (`Registry::take_closed_parked_views`). + let mut closed_views = [None, None]; let grow_ready = { let mut state = self.shared.state.lock(); let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; if result.is_err() { + closed_views = parked.take_closed_views(); firmware.queues.render.entry_mut(slot)?.parked = Some(parked); firmware.queues.buffers.release(buffer.0)?; } else { @@ -634,6 +639,7 @@ impl super::super::Backend { } firmware.render_grow_ready() }; + drop(closed_views); self.shared.note_changed(); if grow_ready { self.shared.queue_grow(); @@ -717,11 +723,12 @@ impl super::super::Backend { return Err(crate::g17::capacity::refused(crate::g17::capacity::Site::RetiredRenderBindings)); } // A rebind of the same context (a render that needs a bigger pool) keeps its - // live scheduler state; only another context's is displaced. + // live scheduler state; only another context's is displaced. A detached sibling + // of a still-open owner stays in Deferred until that owner closes. if !pair.matches(self.owner, &self.context)? { firmware.queues.teardown.displace( pair.context(), - true, + entry.closed, super::super::now_ns(), )?; } @@ -816,8 +823,8 @@ impl super::super::Backend { pub(super) fn ensure_render(&self, packet: &Arc, slot: u8, sleep: bool) -> Result { self.build_render_pair(slot, packet, false, sleep)?; - // An owner held to one pair has no sibling to warm. - if self.pairs == 1 { + // An owner held to one pair, or running this layout on one, has no sibling to warm. + if self.render_pairs(packet) == 1 { return Ok(()); } let sibling = { @@ -834,8 +841,15 @@ impl super::super::Backend { // construction and its final device-locked install have finished. // An optional sibling may be borrowed or waiting for recovery. // The selected pair is revalidated by prepare_render before publication. + // A sibling for which the client's window or memory limit has no room now, as the + // queue's other objects hold it, is not built either: this render runs on its pair. match self.build_render_pair(sibling.slot(), packet, true, sleep) { - Err(error) if error == EBUSY || error == EAGAIN || error == super::submit::FALLBACK => {} + Err(error) + if error == EBUSY + || error == EAGAIN + || error == super::submit::FALLBACK + || error == ENOSPC + || error == ENOMEM => {} result => result?, } } @@ -987,7 +1001,7 @@ impl super::super::Backend { let _scope = (*held) .as_mut() .filter(|claim| claim.remaining() != 0) - .map(|claim| firmware.init.outer_scope(claim)) + .map(|claim| firmware.port.outer_scope(&firmware.init, claim)) .transpose()?; firmware.publish_render(self.owner, slot, packet, deferred) })(); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs b/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs index 02ece8cf4025b7..5f3423ac148a64 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs @@ -2,7 +2,7 @@ //! Recovery targets for retained render graphs while firmware is halted. -use crate::g17::{runtime::Registry, status::VmStatus}; +use crate::g17::{recovery::Attribution, runtime::Registry, status::VmStatus}; use kernel::{prelude::*, sync::Arc}; impl Registry { @@ -22,6 +22,13 @@ impl Registry { } } + /// See `recovery::Queues::note_kill_sightings`. + pub(in crate::g17::runtime) fn note_render_kill_sightings(&self, generation: u64) { + for pair in self.render.entries.iter().flatten().filter_map(|entry| entry.pair.as_ref()) { + pair.note_kill_sighting(generation); + } + } + pub(in crate::g17::runtime) fn render_pass_started(&self, qid: u8, stamp: u64) -> Option { self.render.entries.iter().flatten() .filter_map(|entry| entry.pair.as_ref()) @@ -30,12 +37,13 @@ impl Registry { } /// See `recovery::Queues::render_culprit`. - pub(in crate::g17::runtime) fn render_culprit(&self, blamed: u8) -> Option { + pub(in crate::g17::runtime) fn render_culprit(&self, blamed: u8) -> Option { let pairs = || self.render.entries.iter().flatten().filter_map(|entry| entry.pair.as_ref()); let untouched = pairs().find(|pair| pair.qids().contains(&blamed))?.front_untouched() == Some(true); let running = pairs().filter_map(|pair| { let qids = pair.qids().into_iter().fold(0, |mask, qid| mask | 1u128 << qid); - Some((qids, pair.running_owner()?)) + let (owner, start) = pair.running_start()?; + Some((qids, owner, start)) }); culprit(running, untouched, |culprit| { let mut foreign = false; @@ -46,6 +54,20 @@ impl Registry { }) } + /// See `recovery::Queues::fault_culprit`. + pub(in crate::g17::runtime) fn fault_culprit(&self, slots: u64) -> Option { + crate::g17::recovery::fault_qids(slots, |visit| { + for pair in self.render.entries.iter().flatten().filter_map(|entry| entry.pair.as_ref()) { + let qids = pair.qids().into_iter().fold(0, |mask, qid| mask | 1u128 << qid); + pair.visit_contexts(&mut |context| visit(qids, context)); + } + for queue in self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()) { + let qid = 1u128 << queue.qid(); + queue.visit_contexts(&mut |context| visit(qid, context)); + } + }) + } + pub(in crate::g17::runtime) fn publish_render_recovery_targets(&self) -> Option { let mut failure = None; for pair in self.render.entries.iter().flatten() @@ -59,31 +81,46 @@ impl Registry { } } -/// Picks the QIDs to blame from each pair's running owner. A VM an earlier recovery found guilty -/// comes first, even when the blamed render had started: its groups queued before that keep -/// hanging the GPU one per restart, while bystanders' renders whose tiler started wait behind -/// them, and that recovery failed its interrupted work. Otherwise the blamed render must be -/// `untouched`, exactly one VM may be running, and `foreign` must find no other VM's compute work. +/// Picks the QIDs to blame from each pair's running render: its QIDs, owner and tiler start. A VM +/// an earlier recovery found guilty comes first, even when the blamed render had started: its +/// groups queued before that keep hanging the GPU one per restart, while bystanders' renders whose +/// tiler started wait behind them, and that recovery failed its interrupted work. +/// +/// Otherwise the running render whose tiler started first is the hang: a later one, the blamed +/// one included, started only after it and waits behind it (2026-11-24 01:26 UTC, m4.183: the +/// firmware blamed quickshell twice behind a spinning deqp-vk, whose render was the oldest +/// running one in every recovery). Its VM's running pairs are suspected (`Suspects`), which is +/// not proof: a slow innocent render that started first looks the same, so `classify` treats it +/// like the firmware's blame, collateral once. A blamed render that never started (`untouched`) +/// is never the hang: without a running render, or when `foreign` finds another VM's compute +/// work, which these records cannot see, nobody is named (`NoCulprit`). A started blamed render +/// beside foreign compute keeps the firmware's blame (`None`). fn culprit<'a>( - running: impl Iterator)>, + running: impl Iterator, u64)> + Clone, untouched: bool, foreign: impl FnOnce(&Arc) -> bool, -) -> Option { - let (mut guilty, mut qids, mut several) = (0u128, 0u128, false); - let mut culprit: Option<&Arc> = None; - for (pair, owner) in running { +) -> Option { + let (mut guilty, mut oldest) = (0u128, None::<(&Arc, u64)>); + for (qids, owner, start) in running.clone() { if owner.recovery_guilty() { - guilty |= pair; + guilty |= qids; + } + if oldest.is_none_or(|(_, first)| start < first) { + oldest = Some((owner, start)); } - several |= culprit.is_some_and(|known| !Arc::ptr_eq(known, owner)); - culprit = Some(owner); - qids |= pair; } if guilty != 0 { - return Some(guilty); + return Some(Attribution::Queues(guilty)); + } + let unnamed = untouched.then_some(Attribution::NoCulprit); + let Some((culprit, _)) = oldest else { + return unnamed; + }; + if foreign(culprit) { + return unnamed; } - let culprit = culprit.filter(|_| untouched && !several)?; - (!foreign(culprit)).then_some(qids) + let qids = running.filter(|(_, owner, _)| Arc::ptr_eq(owner, culprit)).fold(0, |all, (qids, ..)| all | qids); + Some(Attribution::Suspects(qids)) } #[kernel::macros::kunit_tests(asahi_g17_render_culprit)] @@ -97,25 +134,41 @@ mod tests { #[test] fn a_guilty_vm_still_running_is_blamed_before_running_bystanders() { let (spinner, bystander) = (vm(), vm()); - let running = || [(0b11, &bystander), (0b1100, &spinner)].into_iter(); - // Two VMs running and no earlier guilt: the firmware's blame stands, even when one of - // them failed only for its own client. - bystander.record(EIO); - assert_eq!(culprit(running(), true, |_| false), None); + // The bystander's render started first here: earlier guilt still decides. + let running = || [(0b11, &bystander, 10), (0b1100, &spinner, 20)].into_iter(); spinner.note_recovery_guilty(); - assert_eq!(culprit(running(), true, |_| panic!("compute is not consulted")), Some(0b1100)); - // The bystander's blamed render whose tiler started is starved too. - assert_eq!(culprit(running(), false, |_| panic!("compute is not consulted")), Some(0b1100)); + assert_eq!(culprit(running(), true, |_| panic!("compute is not consulted")), Some(Attribution::Queues(0b1100))); + assert_eq!(culprit(running(), false, |_| panic!("compute is not consulted")), Some(Attribution::Queues(0b1100))); + } + + #[test] + fn the_oldest_running_render_is_the_culprit() { + // 2026-11-24 01:26 UTC (m4.183, #2504 hang row run 2, T93 fronts): in every recovery the + // spinning deqp-vk pair (51/52) held the running render with the oldest tiler start. + let (deqp, quickshell, hyprland) = (vm(), vm(), vm()); + let deqp_qids = (1u128 << 51) | (1u128 << 52); + // Gen 1: the firmware blamed deqp's own started render, the only one running. + assert_eq!(culprit([(deqp_qids, &deqp, 2583940972)].into_iter(), false, |_| false), Some(Attribution::Suspects(deqp_qids))); + // Gen 2: it blamed quickshell's render, whose tiler started after deqp's. + let gen2 = [(deqp_qids, &deqp, 2585948130), (3 << 42, &quickshell, 2587035310)]; + assert_eq!(culprit(gen2.into_iter(), false, |_| false), Some(Attribution::Suspects(deqp_qids))); + // Gen 3: it blamed quickshell's next render, which never started; Hyprland's started after + // deqp's by 5858 ticks. T94 failed quickshell's VM here for the repeat. + let gen3 = [(3 << 36, &hyprland, 2589025577), (deqp_qids, &deqp, 2589019719)]; + assert_eq!(culprit(gen3.into_iter(), true, |_| false), Some(Attribution::Suspects(deqp_qids))); } #[test] - fn one_running_vm_is_blamed_only_without_foreign_compute() { + fn an_unstarted_render_is_never_the_culprit() { let (a, b) = (vm(), vm()); - assert_eq!(culprit([(0b11, &a), (0b1100, &a)].into_iter(), true, |_| false), Some(0b1111)); - // A blamed render that had started may be the hang itself. - assert_eq!(culprit([(0b11, &a), (0b1100, &a)].into_iter(), false, |_| false), None); - assert_eq!(culprit([(0b11, &a)].into_iter(), true, |_| true), None); - assert_eq!(culprit([(0b11, &a), (0b1100, &b)].into_iter(), true, |_| false), None); - assert_eq!(culprit(core::iter::empty(), true, |_| false), None); + // Nothing runs, or other VMs' compute could be the hang: nobody is blamed. + assert_eq!(culprit(core::iter::empty(), true, |_| false), Some(Attribution::NoCulprit)); + assert_eq!(culprit([(0b11, &a, 5)].into_iter(), true, |_| true), Some(Attribution::NoCulprit)); + // A started blamed render beside foreign compute keeps the firmware's blame. + assert_eq!(culprit([(0b11, &a, 5)].into_iter(), false, |_| true), None); + assert_eq!(culprit(core::iter::empty(), false, |_| false), None); + // All running pairs of the oldest's VM are named, none of another VM. + let running = [(0b11, &a, 5), (0b1100, &b, 3), (0b110000, &b, 9)]; + assert_eq!(culprit(running.into_iter(), true, |_| false), Some(Attribution::Suspects(0b111100))); } } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index 70efc3cbb0f2b5..d06e91c804f980 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -37,6 +37,16 @@ impl Backend { }) } + /// The render pairs this queue uses for `packet`: its own count, or one for an M5 layout + /// whose pairs the client's compact window cannot hold side by side + /// ([`crate::g17::pairs::for_window`]). + pub(in crate::g17::runtime) fn render_pairs(&self, packet: &Packet) -> u8 { + // SUBMIT derived the layout and kept its window bytes on the command. + crate::g17::pairs::for_window(self.pairs, + packet.command.pair_window().map(|bytes| bytes as u64), + crate::g17::buffer::compact::WINDOW_BYTES) + } + pub(in crate::g17) fn render_packet( &self, packet: &Arc, @@ -87,7 +97,7 @@ impl Backend { if !sleep { return Err(FALLBACK); } - match pool.acquire_render(self.owner, self.pairs.into(), Request::of(packet), deadline_ns, || { + match pool.acquire_render(self.owner, self.render_pairs(packet).into(), Request::of(packet), deadline_ns, || { // Atomics only: the callback runs under the pool mutex. if packet.cancel_requested() || self.closed.load(Ordering::Acquire) { return Err(ECANCELED); @@ -190,11 +200,12 @@ impl Backend { Ok(_) => {} } let request = Request::of(packet); - if self.admission.admits_render(self.owner, request) { + let pairs = self.render_pairs(packet).into(); + if self.admission.admits_render(self.owner, pairs, request) { return None; } let observed = self.shared.renders.observe(); - if self.admission.admits_render(self.owner, request) { + if self.admission.admits_render(self.owner, pairs, request) { return None; } self.shared.queue_events(); @@ -411,7 +422,7 @@ impl Backend { Some(lease) => Some(lease), None if known != 0 => self .admission - .try_acquire_render(self.owner, self.pairs.into(), Request::of(packet)) + .try_acquire_render(self.owner, self.render_pairs(packet).into(), Request::of(packet)) .ok() .flatten(), None => None, @@ -574,7 +585,7 @@ impl Backend { if !self.traversal_inline(packet) { return false; } - let admission = match self.admission.try_acquire_render(self.owner, self.pairs.into(), Request::of(packet)) { + let admission = match self.admission.try_acquire_render(self.owner, self.render_pairs(packet).into(), Request::of(packet)) { Ok(Some(lease)) => lease, _ => return false, }; @@ -656,13 +667,26 @@ impl Registry { dependencies.tiling_count += 1; } } - if let Some(queue) = self.compute(owner) { - dependencies.compute = queue.dependency( + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + { + let tiling = queue.dependency( owner, packet.completion.status(), packet.order.tiling_wait_through[1], state, )?; + if let Some(dep) = tiling { + *dependencies + .compute + .get_mut(dependencies.compute_count) + .ok_or(EOVERFLOW)? = dep; + dependencies.compute_count += 1; + } if packet.order.tiling_wait_through[1] != packet.order.wait_through[1] { let whole = queue.dependency( owner, @@ -670,8 +694,12 @@ impl Registry { packet.order.wait_through[1], state, )?; - if whole != dependencies.compute { - dependencies.fragment_compute = whole; + if let Some(dep) = whole.filter(|dep| Some(*dep) != tiling) { + *dependencies + .fragment_compute + .get_mut(dependencies.fragment_compute_count) + .ok_or(EOVERFLOW)? = dep; + dependencies.fragment_compute_count += 1; } } } @@ -761,6 +789,7 @@ impl crate::g17::Firmware { // time and attachment overlaps are ordered by publication order. let port = self.port.clone(); let _render = port.render_lock(); + let _m5_outer = self.init.is_m5().then(|| port.m5_outer_lock()); // Both outer destinations must have room before pool accounting or // either inner queue becomes visible. On M5 both are the shared compute ring: one // check covers the pair, and the pair is written against its cursors (this hold @@ -828,10 +857,19 @@ impl crate::g17::Firmware { &mut |event| deferred.push(event), ) }); + let entry = self.queues.render.entry(slot)?; + let started = packet.is_published() + || entry + .pair + .as_ref() + .is_some_and(|pair| pair.graph_started()); + if started && !entry.closed { + self.queues.admission.note_published(slot); + } if packet.is_published() { self.queues.render.entry_mut(slot)?.published = true; } else if result.is_err() { - self.queues.render.pools.rollback(preparation); + let rollback = self.rollback_render_pool(preparation); self.queues.buffers.release(buffer_id)?; self.queues .render @@ -840,6 +878,7 @@ impl crate::g17::Firmware { .as_mut() .ok_or(EIO)? .discard_prepared(packet)?; + rollback?; } result } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/teardown.rs b/drivers/gpu/drm/asahi/g17/runtime/render/teardown.rs index 5b8379078b1511..38b14126e989ec 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/teardown.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/teardown.rs @@ -18,19 +18,23 @@ impl RenderState { /// Nothing of `context` still runs on its render pairs, so a kill of it may be published. /// A pair whose commands all ran unstamped (`Pair::executed_for_kill`) counts as idle: only - /// that kill releases it. - pub(in crate::g17::runtime) fn teardown_idle(&self, context: &Arc) -> Result { - self.idle_for(context, false) + /// that kill releases it. So does a pair holding guilty work (`Pair::guilty_for_kill`): it + /// runs only to hang the GPU again, and only the kill ends that. + pub(in crate::g17::runtime) fn teardown_idle(&self, context: &Arc, generation: u64) -> Result { + self.idle_for(context, Some(generation)) } /// As [`Self::teardown_idle`], for releasing `context`'s scheduler: a pair whose commands ran /// unstamped counts only once a kill of the context has been published, since until then - /// the firmware still links that work. + /// the firmware still links that work. A killed guilty pair counts once its groups went on + /// the guilty proof (`Pair::guilty_released`), whether or not its rings were consumed. pub(in crate::g17::runtime) fn release_idle(&self, context: &Arc) -> Result { - self.idle_for(context, true) + self.idle_for(context, None) } - fn idle_for(&self, context: &Arc, release: bool) -> Result { + /// `kill`: the host's recovery generation for a kill decision, `None` for the scheduler + /// release. See [`counts_idle`]. + fn idle_for(&self, context: &Arc, kill: Option) -> Result { // A pair that changed owner keeps running this scheduler's queues until // the new owner's first command leaves it, whichever context owns it now. let scheduler = Some(context.scheduler_va()); @@ -52,8 +56,10 @@ impl RenderState { return Ok(false); } if let Some(pair) = entry.pair.as_ref() { - if !pair.idle_for_context(context)? - && !((!release || context.kill_published()) && pair.executed_for_kill(context)) + let idle = pair.idle_for_context(context)?; + let guilty = kill.is_some_and(|generation| pair.guilty_for_kill(context, generation)); + if !counts_idle(kill.is_none(), context.kill_published(), idle, pair.executed_for_kill(context), + guilty, pair.guilty_released()) { return Ok(false); } @@ -112,13 +118,15 @@ impl RenderState { } /// Preflight the entire Context before detaching its first graph. Successor - /// graphs on the same VM have a different Arc and remain installed. + /// graphs on the same VM have a different Arc and remain installed. Returns the slots + /// whose killed guilty pairs were kept out of service (`Pair::can_keep`): their kill + /// hold stays. pub(in crate::g17::runtime) fn detach_context( &mut self, context: &Arc, buffers: &mut BufferIds, out: &mut ReclaimBatch, - ) -> Result { + ) -> Result { let mut count = self .retired .iter() @@ -136,7 +144,7 @@ impl RenderState { return Err(EBUSY); } if let Some(pair) = entry.pair.as_ref() { - if !pair.can_park(context)? { + if !pair.can_park(context)? && !pair.can_keep(context) { return Err(EBUSY); } count += 1; @@ -146,7 +154,11 @@ impl RenderState { return Err(EBUSY); } let linked = context.firmware_may_link(); - for entry in self.entries.iter_mut().flatten() { + let mut kept = 0u64; + for (slot, entry) in self.entries.iter_mut().enumerate() { + let Some(entry) = entry.as_mut() else { + continue; + }; if !entry .context .as_ref() @@ -157,10 +169,29 @@ impl RenderState { let Some(pair) = entry.pair.as_ref() else { continue; }; + // Either end state of a killed guilty pair is logged: the test of the kill fix + // reads from it whether the firmware consumed the unlinked groups' ring entries. + let keep = !pair.can_park(context)?; + if pair.guilty_released() { + pr_warn!("G17: render slot {}: killed guilty pair {} (cursors {:?})\n", slot, + if keep { "kept out of service until the GPU stops: its rings were not consumed" } + else { "parked: its rings were consumed" }, + pair.ring_cursors()); + } buffers.unreserve_owner(pair.buffer_id())?; let target = out.binding_slot()?; let pair = entry.pair.take().ok_or(EIO)?; let (mut parked, retired) = KBox::into_inner(pair).park(); + if keep { + // Neither the rings nor the graph their entries name are reused or freed, and + // the slot's kill hold stays, until the processors stop. + keep_graph(&mut self.kept_graphs, retired); + keep_pair(&mut self.kept_pairs, parked); + kept |= 1u64 << slot; + entry.context = None; + entry.pool = None; + continue; + } // This park follows the consumed release of `context`. parked.release_consumed(context.scheduler_va()); if linked { @@ -192,7 +223,7 @@ impl RenderState { *out.binding_slot()? = Some(retired); } } - Ok(()) + Ok(kept) } } @@ -216,6 +247,65 @@ impl Registry { } } +/// Whether a render pair of a closed context counts as idle: for the kill decision +/// (`release` false) or for the scheduler release, which lets the pair's ring and graph go. +/// - `idle`: nothing of it runs (`Pair::idle_for_context`). +/// - `executed`: its commands all ran unstamped (`Pair::executed_for_kill`); for the release +/// only once the kill was published (`kill_published`). +/// - `guilty`: it holds guilty work (`Pair::guilty_for_kill`); for the kill decision only. Its +/// started group may run until the restart after the kill, so counting it for the release +/// would free a running group's ring. +/// - `guilty_released`: its groups went on the guilty proof (`Pair::guilty_released`); for the +/// release, its rings may never be consumed. +fn counts_idle(release: bool, kill_published: bool, idle: bool, executed: bool, guilty: bool, guilty_released: bool) + -> bool +{ + idle + || (executed && (!release || kill_published)) + || (guilty && !release) + || (guilty_released && release && kill_published) +} + +/// Keeps a killed guilty pair until the firmware stops (see `detach_context`); if even that +/// cannot be recorded, it is leaked rather than dropped. +fn keep_pair(kept: &mut KVec, pair: crate::g17::queue::render::parked::ParkedPair) { + if kept.reserve(1, GFP_KERNEL).is_ok() { + if let Err(error) = kept.push_within_capacity(pair) { + LEAKED_GRAPHS.fetch_add(1, core::sync::atomic::Ordering::Relaxed); + core::mem::forget(error.0); + } + } else { + LEAKED_GRAPHS.fetch_add(1, core::sync::atomic::Ordering::Relaxed); + core::mem::forget(pair); + } +} + +#[kernel::macros::kunit_tests(asahi_g17_render_teardown_idle)] +mod idle_tests { + use super::counts_idle; + + #[test] + fn a_guilty_pair_never_counts_idle_for_the_scheduler_release_while_it_may_run() { + // The use-after-free guard: killed, guilty, not idle, not yet released on the proof. + assert!(!counts_idle(true, true, false, false, true, false)); + assert!(!counts_idle(true, false, false, false, true, false)); + // For the kill decision it counts. + assert!(counts_idle(false, false, false, false, true, false)); + // Released on the guilty proof: counts for the release once the kill was published. + assert!(counts_idle(true, true, false, false, false, true)); + assert!(!counts_idle(true, false, false, false, false, true)); + } + + #[test] + fn idle_and_executed_pairs_count_as_before() { + assert!(counts_idle(true, false, true, false, false, false)); + assert!(counts_idle(false, false, false, true, false, false)); + assert!(!counts_idle(true, false, false, true, false, false)); + assert!(counts_idle(true, true, false, true, false, false)); + assert!(!counts_idle(false, false, false, false, false, false)); + } +} + /// Graphs that could not be recorded in `kept_graphs` and were leaked instead, for debugfs. pub(super) static LEAKED_GRAPHS: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0); diff --git a/drivers/gpu/drm/asahi/g17/runtime/teardown.rs b/drivers/gpu/drm/asahi/g17/runtime/teardown.rs index e1862504135b25..2127f7dfc977c5 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/teardown.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/teardown.rs @@ -140,12 +140,15 @@ impl Host for Service<'_> { let linked = context.retain_linked_work(self.objects); let (_, _, slots) = self.render.exit_scope(context); crate::g17::trace::teardown(5, u64::from(context.id()), slots, u64::from(linked)); - self.render + let kept = self + .render .detach_context(context, self.buffers, self.reclaim)?; // The firmware consumed this context's scheduler release after its kill (if any) // was acknowledged and its pairs went idle: it no longer names these pairs, so - // their kill hold ends here rather than at the next processor stop. - self.admission.release_killed_slots(slots); + // their kill hold ends here rather than at the next processor stop. Pairs kept out + // of service keep theirs until then. + self.admission.release_killed_slots(slots & !kept); + self.admission.hold_kept_slots(kept); // detach_context preflights this slot together with every graph slot. // Retain it before Pending removes its reference under the device lock. self.reclaim.context(context) diff --git a/drivers/gpu/drm/asahi/g17/sleep.c b/drivers/gpu/drm/asahi/g17/sleep.c index 380e6662f14191..e62315b1eb2b57 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.c +++ b/drivers/gpu/drm/asahi/g17/sleep.c @@ -46,14 +46,13 @@ #define ASC_CPU_CONTROL 0x44 #define ASC_CPU_CONTROL_RUN BIT(4) -/* Only the M5 boards with a deep sleep need a wrapped provider translation here: the J714s - * and the J716c. Other G17 clients retain their established direct-domain methods below. +/* Only the M5 boards with a deep sleep need a wrapped provider translation here: those whose + * device tree describes it. Other G17 clients retain their established direct-domain methods + * below. */ static bool asahi_g17_m5_provider(struct device *dev) { - return (of_machine_is_compatible("apple,j714s") || - of_machine_is_compatible("apple,j716c")) && - of_machine_is_compatible("apple,t6050") && + return apple_t6050_sleep_described() && of_device_is_compatible(dev->of_node, "apple,agx-g17s"); } @@ -194,6 +193,24 @@ int asahi_g17_pmp_request(struct device *dev, bool enable) return ret; } +/* + * The node of the GPU's power state word. Where the GPU's first power domain is its PMP + * report entry (a small index for a reg, under the PMP), as in the J616C device tree the + * bring-up runs, the word is that entry's own domain. + */ +static struct device_node *asahi_g17_ps_node(struct device *dev) +{ + struct device_node *np, *next; + + np = of_parse_phandle(dev->of_node, "power-domains", 0); + if (np && of_device_is_compatible(np, "apple,t6000-pmp-v2-report-entry")) { + next = of_parse_phandle(np, "power-domains", 0); + of_node_put(np); + np = next; + } + return np; +} + static int asahi_g17_ps(struct device *dev, struct regmap **regmap, u32 *offset) { struct device_node *np; @@ -213,7 +230,7 @@ static int asahi_g17_ps(struct device *dev, struct regmap **regmap, u32 *offset) of_node_put(np); return ret; } - np = of_parse_phandle(dev->of_node, "power-domains", 0); + np = asahi_g17_ps_node(dev); if (!np) return -EINVAL; ret = of_property_read_u32(np, "reg", offset); @@ -623,7 +640,7 @@ struct asahi_g17_commit *asahi_g17_commit_prepare(struct device *dev, of_node_put(parent); of_node_put(np); } else { - np = of_parse_phandle(dev->of_node, "power-domains", 0); + np = asahi_g17_ps_node(dev); if (!np) goto err; if (!of_property_read_u32(np, "reg", &offset) && np->parent) diff --git a/drivers/gpu/drm/asahi/g17/sleep.rs b/drivers/gpu/drm/asahi/g17/sleep.rs index 28524b3bf68f62..17a21a88223a3c 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.rs +++ b/drivers/gpu/drm/asahi/g17/sleep.rs @@ -315,8 +315,10 @@ impl Shared { /// With the sleeping flag set, joins whatever may be reading firmware state. The growth work /// isn't joined: it may be waiting on the closed gate, and can't publish while it is closed. fn join_event_workers(self: &Arc) { + self.cancel_rescan(); self.cancel_timer(&self.poll); self.cancel_timer(&self.idle); + self.cancel_timer(&self.housekeeping_timer); // SAFETY: An initialized, pinned work field of this Shared. unsafe { bindings::flush_work(Work::raw_get(&self.work)) }; } diff --git a/drivers/gpu/drm/asahi/g17/stats.rs b/drivers/gpu/drm/asahi/g17/stats.rs index 5484c68fa62f77..958d6815f236f4 100644 --- a/drivers/gpu/drm/asahi/g17/stats.rs +++ b/drivers/gpu/drm/asahi/g17/stats.rs @@ -30,6 +30,11 @@ impl StateFrequencies { Some(Self { mhz: table, states }) } + /// Highest valid performance state index in this table (`0` when empty or off-only). + pub(crate) fn max_pstate(&self) -> u32 { + self.states.saturating_sub(1) as u32 + } + /// The frequency of `pstate` in Hz; `None` beyond the table or where it is unknown (0). fn hz(&self, pstate: u32) -> Option { let mhz = *self.mhz[..self.states].get(pstate as usize)?; @@ -72,10 +77,10 @@ impl Reader { } fn read_firmware(&self) -> Readout { - let m5 = self.0.variant.m5_commands; + let protocol = self.0.variant.telemetry_protocol; let mut state = self.0.state.lock(); let Some(firmware) = state.as_deref_mut() else { - return qualify(self.0.variant.graph, m5, Readout::default()); + return qualify(protocol, Readout::default()); }; if self.0.crashed.load(Ordering::Acquire) || firmware.recovery.pending() { firmware.rings.invalidate_statistics(); @@ -94,11 +99,7 @@ impl Reader { // export samples across an observed boundary. firmware.observe_statistics_power(); } - qualify( - self.0.variant.graph, - m5, - firmware.rings.read_statistics(super::now_ns()), - ) + qualify(protocol, firmware.rings.read_statistics(super::now_ns())) } pub(crate) fn suspend(&self, suspended: bool) { @@ -118,33 +119,23 @@ pub(super) const fn max_age_ns(graph: InitGraph) -> u64 { } } -/// The records `graph`'s firmware sends beyond utilisation; `m5`: it runs the M5 protocol, -/// with M5's performance states. -pub(super) const fn protocol(graph: InitGraph, m5: bool) -> super::telemetry::Protocol { - match graph { - InitGraph::G17P if m5 => super::telemetry::Protocol::M5, - InitGraph::G17P => super::telemetry::Protocol::A18_PRO, - InitGraph::V25G83 => super::telemetry::Protocol::NONE, - } -} - /// Whether the firmware reports its performance state. V25G83 and V26A428 accept -/// the logical pstate record (tag 0x10) but never emit it. V26A428, on the A18 Pro -/// as on M5, reports the state in its own records instead (tags 0x19 and 0x1b, -/// [`protocol`]); V25G83 sends no record carrying it, so it is unsupported there. -/// A firmware that reports it reads valid or stale. -pub(super) const fn reports_pstate(graph: InitGraph, m5: bool) -> bool { - protocol(graph, m5).reports_pstate() +/// the logical pstate record (tag 0x10) but never emit it. V26A428 (A18 Pro and +/// M5) and T6041's 25G83 report the state in tags 0x19 and 0x1b instead +/// (`Variant::telemetry_protocol`); T6040's 25G83 is left on `Protocol::NONE` +/// because it has not been measured yet, so it is unsupported there. A firmware +/// that reports it reads valid or stale. +pub(super) const fn reports_pstate(protocol: super::telemetry::Protocol) -> bool { + protocol.reports_pstate() } /// Apply the firmware's static capabilities to a decoded readout. The decoder /// and the debugfs diagnostic still keep any tag 0x10 that does arrive. pub(super) fn qualify( - graph: InitGraph, - m5: bool, + protocol: super::telemetry::Protocol, mut view: super::telemetry::Readout, ) -> super::telemetry::Readout { - if !reports_pstate(graph, m5) { + if !reports_pstate(protocol) { view.pstate_status = super::telemetry::UNSUPPORTED; view.pstate = 0; view.pstate_host_ns = 0; diff --git a/drivers/gpu/drm/asahi/g17/status.rs b/drivers/gpu/drm/asahi/g17/status.rs index de7b98bdbc553a..5c062f8a2c8e86 100644 --- a/drivers/gpu/drm/asahi/g17/status.rs +++ b/drivers/gpu/drm/asahi/g17/status.rs @@ -4,7 +4,7 @@ use crate::debug::*; use crate::gem; -use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}; use kernel::{new_mutex, prelude::*, str::BStr, sync::Mutex, task::Pid}; const DEBUG_CLASS: DebugFlags = DebugFlags::Errors; @@ -33,6 +33,10 @@ pub(crate) struct VmStatus { /// Further restarts that may find this VM guilty and still be charged to it /// ([`Self::charge_restart`]), or [`UNCHARGED`] before the first. restarts_left: AtomicU32, + /// Commands whose public fence is failing ([`Self::signal_failure`]): counted before + /// its error is set, and again once it has signalled. + failures_started: AtomicU64, + failures_finished: AtomicU64, /// The process that created the VM, named in the failure report. tgid: Pid, comm: [u8; 16], @@ -51,6 +55,14 @@ struct Mirror { // only accessed atomically through this pointer while the mutex is held. unsafe impl Send for Mirror {} +/// [`VmStatus::signal_failure`] counts: every failure in `finished` has signalled its error, +/// and those in `started` but not `finished` may be anywhere between. +#[derive(Clone, Copy)] +pub(crate) struct Failures { + pub(crate) started: u64, + pub(crate) finished: u64, +} + impl VmStatus { /// Called from the creating client's ioctl: the VM records who it belongs to. pub(crate) fn new() -> impl PinInit { @@ -69,6 +81,8 @@ impl VmStatus { warned: AtomicBool::new(false), recovery_guilty: AtomicBool::new(false), restarts_left: AtomicU32::new(UNCHARGED), + failures_started: AtomicU64::new(0), + failures_finished: AtomicU64::new(0), tgid, comm, mirror <- new_mutex!(None, "Asahi VM status mirror"), @@ -89,6 +103,24 @@ impl VmStatus { (BStr::from_bytes(&self.comm[..len]), self.tgid) } + /// Fails a command's public fence: `signal` sets its error and signals it. The failure + /// counts as started before anyone can see the error and as finished after the signal, so + /// a frontier prune that reads the counts in between can tell that one is in flight. + pub(crate) fn signal_failure(&self, signal: impl FnOnce()) { + // Relaxed: the fence's signal, a release, publishes it together with the error. + self.failures_started.fetch_add(1, Ordering::Relaxed); + signal(); + // Release: whoever sees this count also sees the signalled error. + self.failures_finished.fetch_add(1, Ordering::Release); + } + + /// This VM's failure counts, `finished` read first so that `started` covers it. + pub(crate) fn failures(&self) -> Failures { + let finished = self.failures_finished.load(Ordering::Acquire); + let started = self.failures_started.load(Ordering::Acquire); + Failures { started, finished } + } + pub(crate) fn note_recovery_guilty(&self) { self.recovery_guilty.store(true, Ordering::Release); } diff --git a/drivers/gpu/drm/asahi/g17/sync_input.c b/drivers/gpu/drm/asahi/g17/sync_input.c index 145a5955c87965..1b68be583ad4cc 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.c +++ b/drivers/gpu/drm/asahi/g17/sync_input.c @@ -8,19 +8,49 @@ static int collect_leaf(struct dma_fence *leaf, struct asahi_g17_fence_leaf *out, size_t capacity, - size_t *count) + size_t *count, bool coalesce_contexts) { + int status = dma_fence_get_status(leaf); + size_t i; + + /* Already-signalled non-error leaves need no further wait or barrier. */ + if (status > 0) + return 0; + + for (i = 0; i < *count; ++i) { + if (out[i].fence == leaf) { + if (status < 0 && out[i].status >= 0) + out[i].status = status; + return 0; + } + /* + * Coalesce healthy unsignaled leaves sharing a fence context (such + * as multiple points of one timeline chain), keeping only the + * latest seqno. Failed leaves are never coalesced, so errors are + * preserved, and neither is context 0, which names no timeline. + */ + if (coalesce_contexts && status == 0 && leaf->context != 0 && + out[i].status == 0 && out[i].fence->context == leaf->context) { + if (dma_fence_is_later(leaf, out[i].fence)) { + dma_fence_put(out[i].fence); + out[i].fence = dma_fence_get(leaf); + } + return 0; + } + } + if (*count == capacity) return -ENOSPC; out[*count].fence = dma_fence_get(leaf); - out[*count].status = dma_fence_get_status(leaf); + out[*count].status = status; ++*count; return 0; } /* Called without the device mutex: status polling may run fence callbacks. */ -int asahi_g17_collect_fences(struct dma_fence *head, - struct asahi_g17_fence_leaf *out, size_t capacity) +static int collect_fences(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, size_t capacity, + bool coalesce_contexts) { struct dma_fence *pending[128]; size_t count = 0, depth = 1; @@ -34,11 +64,19 @@ int asahi_g17_collect_fences(struct dma_fence *head, if (asahi_g17_is_scope(node)) { struct dma_fence *children[2]; - unsigned int n = asahi_g17_scope_children(node, children), i; + unsigned int n, i; + int status = dma_fence_get_status(node); + + if (status > 0) { + dma_fence_put(node); + continue; + } + n = asahi_g17_scope_children(node, children); if (!n) { /* Preserve a failed scope as a failed leaf, never drop its error. */ - if (dma_fence_get_status(node) < 0) - error = collect_leaf(node, out, capacity, &count); + if (status < 0) + error = collect_leaf(node, out, capacity, &count, + coalesce_contexts); } else if (depth + n > ARRAY_SIZE(pending)) { for (i = 0; i < n; ++i) dma_fence_put(children[i]); @@ -60,7 +98,8 @@ int asahi_g17_collect_fences(struct dma_fence *head, } else if (dma_fence_is_container(leaf)) { error = -EOPNOTSUPP; } else { - error = collect_leaf(leaf, out, capacity, &count); + error = collect_leaf(leaf, out, capacity, &count, + coalesce_contexts); } if (error) break; @@ -79,6 +118,19 @@ int asahi_g17_collect_fences(struct dma_fence *head, return count; } +int asahi_g17_collect_fences(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, size_t capacity) +{ + return collect_fences(head, out, capacity, false); +} + +int asahi_g17_collect_fences_coalesced(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, + size_t capacity) +{ + return collect_fences(head, out, capacity, true); +} + void asahi_g17_put_fence(struct dma_fence *fence) { dma_fence_put(fence); @@ -101,3 +153,15 @@ struct dma_fence *asahi_g17_merge_fences(struct dma_fence *const *fences, size_t kfree(cursors); return merged; } + +/* + * How @a orders against @b: 1 when it signals after it on their shared + * context, 0 when not, -1 when they are on different contexts, which + * dma_fence_is_later() would warn about. + */ +int asahi_g17_fence_order(struct dma_fence *a, struct dma_fence *b) +{ + if (a->context != b->context) + return -1; + return dma_fence_is_later(a, b); +} diff --git a/drivers/gpu/drm/asahi/g17/sync_input.h b/drivers/gpu/drm/asahi/g17/sync_input.h index 44d3e338c19778..9bd90b289de2c8 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.h +++ b/drivers/gpu/drm/asahi/g17/sync_input.h @@ -13,7 +13,11 @@ struct asahi_g17_fence_leaf { int asahi_g17_collect_fences(struct dma_fence *head, struct asahi_g17_fence_leaf *out, size_t capacity); +int asahi_g17_collect_fences_coalesced(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, + size_t capacity); void asahi_g17_put_fence(struct dma_fence *fence); struct dma_fence *asahi_g17_merge_fences(struct dma_fence *const *fences, size_t count); +int asahi_g17_fence_order(struct dma_fence *a, struct dma_fence *b); #endif diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index 33ac3f94d4f214..987d890069728b 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -6,19 +6,31 @@ use kernel::{bindings, dma_fence::{Fence, RawDmaFence}, prelude::*}; #[repr(C)] -pub(super) struct Leaf { - pub(super) fence: *mut bindings::dma_fence, - pub(super) status: i32, +pub(crate) struct Leaf { + pub(crate) fence: *mut bindings::dma_fence, + pub(crate) status: i32, } unsafe extern "C" { - fn asahi_g17_collect_fences(head: *mut bindings::dma_fence, + fn asahi_g17_collect_fences_coalesced(head: *mut bindings::dma_fence, out: *mut Leaf, capacity: usize) -> i32; fn asahi_g17_put_fence(fence: *mut bindings::dma_fence); + fn asahi_g17_fence_order(a: *mut bindings::dma_fence, b: *mut bindings::dma_fence) -> i32; fn asahi_g17_merge_fences(fences: *const *mut bindings::dma_fence, count: usize) -> *mut bindings::dma_fence; } +impl super::dependency::FenceOrder for Fence { + fn order(&self, earlier: &Self) -> super::dependency::FenceOrdering { + // SAFETY: Both fences are live references; the helper only reads them. + match unsafe { asahi_g17_fence_order(self.raw(), earlier.raw()) } { + 1 => super::dependency::FenceOrdering::Later, + 0 => super::dependency::FenceOrdering::NotLater, + _ => super::dependency::FenceOrdering::OtherContext, + } + } +} + /// One fence that signals once all of `fences` have (see `job::MERGED_DEPENDENCIES`). pub(super) fn merge(fences: &[Fence]) -> Result { let mut raw = KVec::with_capacity(fences.len(), GFP_KERNEL)?; @@ -42,27 +54,36 @@ impl Drop for Leaf { } } -/// Allocation, unsupported containers, or a large prefix retain normal waits. -pub(super) fn collect(input: &Fence) -> Option> { +fn collect_with( + input: &Fence, + collector: unsafe extern "C" fn(*mut bindings::dma_fence, *mut Leaf, usize) -> i32, +) -> Option> { let mut capacity = 4; loop { let mut leaves = KVec::with_capacity(capacity, GFP_KERNEL).ok()?; // SAFETY: The input owns its fence. The C helper writes at most capacity // fully initialized records and releases every reference on failure. - let count = unsafe { - asahi_g17_collect_fences(input.raw(), leaves.as_mut_ptr(), capacity) - }; + let count = unsafe { collector(input.raw(), leaves.as_mut_ptr(), capacity) }; if count == ENOSPC.to_errno() && capacity < 128 { capacity = (capacity * 4).min(128); continue; } - if count < 0 { return None; } + if count < 0 { + return None; + } // SAFETY: The helper returned this many initialized, owned records. unsafe { leaves.set_len(count as usize) }; return Some(leaves); } } +/// The leaves of `input`, coalescing unsignalled non-error leaves sharing a `dma_fence` context +/// to their latest sequence number so deep timeline chains stay bounded by distinct contexts. +/// Allocation, unsupported containers, or a large prefix retain normal waits. +pub(crate) fn collect_coalesced(input: &Fence) -> Option> { + collect_with(input, asahi_g17_collect_fences_coalesced) +} + use super::fence::Submission; use core::sync::atomic::{AtomicU32, Ordering}; @@ -76,7 +97,7 @@ pub(super) struct Source { /// processor stop until the last consumer releases its binding loan. pub(super) struct Hold(Arc); impl Hold { - fn new(readers: &Arc) -> Result { + pub(super) fn new(readers: &Arc) -> Result { readers.fetch_update(Ordering::AcqRel, Ordering::Acquire, |count| count.checked_add(1)).map_err(|_| EOVERFLOW)?; Ok(Self(readers.clone())) @@ -86,9 +107,8 @@ impl Drop for Hold { fn drop(&mut self) { self.0.fetch_sub(1, Ordering::AcqRel); } } -/// A new owner starts with no loans. Acquiring a loan requires exclusive access -/// and arms the hint; eligibility queries stay read-only. A validated owner -/// transition can clear the hint after all independent loans have been released. +/// Checks a physical queue's independent source-reader counter directly so lock-free +/// direct-path loans (`Hold::new`) are always observed by ownership, rearm, and share checks. #[repr(transparent)] pub(super) struct ReaderHint { possible: bool, @@ -103,7 +123,7 @@ impl ReaderHint { Ok(hold) } pub(super) fn has_readers(&self, count: &AtomicU32) -> bool { - self.possible && count.load(Ordering::Acquire) != 0 + count.load(Ordering::Acquire) != 0 } pub(super) fn reset_for_owner(&mut self, count: &AtomicU32) -> Result { if self.has_readers(count) { return Err(EBUSY); } diff --git a/drivers/gpu/drm/asahi/g17/sync_output.c b/drivers/gpu/drm/asahi/g17/sync_output.c index 08b4a95f26c9b4..191ebdfc04cdbc 100644 --- a/drivers/gpu/drm/asahi/g17/sync_output.c +++ b/drivers/gpu/drm/asahi/g17/sync_output.c @@ -98,7 +98,7 @@ static void asahi_g17_signal_install(struct asahi_g17_signal_target *target, } int asahi_g17_signals_publish(struct asahi_g17_signal_bundle *bundle, - struct dma_fence *submitted) + struct dma_fence *submitted, bool compute_only) { struct dma_fence *previous, *scope; size_t i; @@ -107,7 +107,8 @@ int asahi_g17_signals_publish(struct asahi_g17_signal_bundle *bundle, return -EINVAL; previous = drm_syncobj_fence_get(bundle->targets[bundle->anchor].syncobj); scope = asahi_g17_scope_create(previous, submitted, - bundle->targets[bundle->anchor].point); + bundle->targets[bundle->anchor].point, + compute_only); dma_fence_put(previous); if (!scope) return -ENOMEM; diff --git a/drivers/gpu/drm/asahi/g17/sync_output.h b/drivers/gpu/drm/asahi/g17/sync_output.h index a752d9ceaf4b0c..cee1146372fc64 100644 --- a/drivers/gpu/drm/asahi/g17/sync_output.h +++ b/drivers/gpu/drm/asahi/g17/sync_output.h @@ -17,7 +17,7 @@ asahi_g17_signals_new(const struct asahi_g17_signal_spec *specs, size_t count, size_t anchor, int *error); void asahi_g17_signals_free(struct asahi_g17_signal_bundle *bundle); int asahi_g17_signals_publish(struct asahi_g17_signal_bundle *bundle, - struct dma_fence *submitted); + struct dma_fence *submitted, bool compute_only); void asahi_g17_signals_fail(struct asahi_g17_signal_bundle *bundle, struct dma_fence *failure); #endif diff --git a/drivers/gpu/drm/asahi/g17/sync_output.rs b/drivers/gpu/drm/asahi/g17/sync_output.rs index 928ebe23193948..5bbc3467a40005 100644 --- a/drivers/gpu/drm/asahi/g17/sync_output.rs +++ b/drivers/gpu/drm/asahi/g17/sync_output.rs @@ -13,7 +13,7 @@ unsafe extern "C" { error: *mut i32) -> *mut core::ffi::c_void; fn asahi_g17_signals_free(bundle: *mut core::ffi::c_void); fn asahi_g17_signals_publish(bundle: *mut core::ffi::c_void, - current: *mut bindings::dma_fence) -> i32; + current: *mut bindings::dma_fence, compute_only: bool) -> i32; fn asahi_g17_signals_fail(bundle: *mut core::ffi::c_void, failure: *mut bindings::dma_fence); } @@ -48,10 +48,10 @@ impl SignalBundle { Ok(Self(raw)) } - pub(crate) fn publish(&mut self, current: &Fence) -> Result { + pub(crate) fn publish(&mut self, current: &Fence, compute_only: bool) -> Result { // SAFETY: The bundle and current fence are owned for this call; C takes // its own references on publication and reports failure before any store. - let error = unsafe { asahi_g17_signals_publish(self.0, current.raw()) }; + let error = unsafe { asahi_g17_signals_publish(self.0, current.raw(), compute_only) }; if error == 0 { Ok(()) } else { Err(Error::from_errno(error)) } } diff --git a/drivers/gpu/drm/asahi/g17/sync_scope.c b/drivers/gpu/drm/asahi/g17/sync_scope.c index 73dc096d119c98..6c4632c220d8c9 100644 --- a/drivers/gpu/drm/asahi/g17/sync_scope.c +++ b/drivers/gpu/drm/asahi/g17/sync_scope.c @@ -32,6 +32,8 @@ struct asahi_g17_scope_callback { struct asahi_g17_scope { struct dma_fence base; atomic_t pending; + atomic_t compute_waited; + bool compute_only; struct dma_fence *children[2]; struct asahi_g17_scope_callback callbacks[2]; struct irq_work work; @@ -43,11 +45,13 @@ struct asahi_g17_scope { static const struct dma_fence_ops scope_ops; static DEFINE_PER_CPU(struct llist_head *, active_scopes); +/* Suppresses internal scope chaining from counting as a host compute waiter. */ +static DEFINE_PER_CPU(struct dma_fence *, scope_chaining_fence); #define SCOPE_ATOMIC_BATCH 64 bool asahi_g17_is_scope(struct dma_fence *fence) { - return fence && fence->ops == &scope_ops; + return fence && rcu_access_pointer(fence->ops) == &scope_ops; } static struct asahi_g17_scope *to_scope(struct dma_fence *fence) @@ -76,8 +80,22 @@ static bool scope_signaled(struct dma_fence *fence) static bool scope_enable_signaling(struct dma_fence *fence) { + struct asahi_g17_scope *scope = to_scope(fence); + /* Child callbacks are already armed; no recursive callback installation. */ - return !scope_signaled(fence); + if (scope_signaled(fence)) + return false; + if (scope->compute_only && + __this_cpu_read(scope_chaining_fence) != fence && + !atomic_xchg(&scope->compute_waited, 1)) + asahi_g17_note_compute_waiter(); + return true; +} + +static void scope_unwait(struct asahi_g17_scope *scope) +{ + if (atomic_xchg(&scope->compute_waited, 0)) + asahi_g17_unnote_compute_waiter(); } unsigned int asahi_g17_scope_children(struct dma_fence *fence, @@ -118,6 +136,7 @@ static void scope_complete(struct asahi_g17_scope *scope) { cmpxchg(&scope->base.error, 1, 0); dma_fence_signal(&scope->base); + scope_unwait(scope); scope_release_completed(scope); } @@ -126,6 +145,7 @@ static void scope_work(struct irq_work *work) struct asahi_g17_scope *scope = container_of(work, struct asahi_g17_scope, work); cmpxchg(&scope->base.error, 1, 0); asahi_g17_signal_fence(&scope->base); + scope_unwait(scope); scope_release_completed(scope); } @@ -218,6 +238,7 @@ static void scope_release(struct dma_fence *fence) struct asahi_g17_scope *scope = to_scope(fence); unsigned int i; + scope_unwait(scope); for (i = 0; i < ARRAY_SIZE(scope->children); ++i) dma_fence_put(scope->children[i]); dma_fence_free(fence); @@ -268,7 +289,8 @@ void asahi_g17_scope_bind(struct dma_fence *fence, struct dma_fence *root) } struct dma_fence *asahi_g17_scope_create(struct dma_fence *previous, - struct dma_fence *submitted, u64 point) + struct dma_fence *submitted, u64 point, + bool compute_only) { struct dma_fence *contained = previous ? dma_fence_chain_contained(previous) : NULL; struct dma_fence *parent = NULL; @@ -304,6 +326,7 @@ struct dma_fence *asahi_g17_scope_create(struct dma_fence *previous, } dma_fence_init64(&scope->base, &scope_ops, NULL, context, point); init_irq_work(&scope->work, scope_work); + scope->compute_only = compute_only; scope->children[0] = parent; scope->children[1] = dma_fence_get(submitted); /* The constructor guard prevents completion while callbacks are being installed. */ @@ -311,13 +334,21 @@ struct dma_fence *asahi_g17_scope_create(struct dma_fence *previous, scope->base.error = 1; for (i = 0; i < ARRAY_SIZE(scope->children); ++i) { struct dma_fence *child = scope->children[i]; + int err; + if (!child) { scope_arrived(scope, 0); continue; } scope->callbacks[i].scope = scope; dma_fence_get(&scope->base); - if (dma_fence_add_callback(child, &scope->callbacks[i].callback, scope_callback)) { + preempt_disable(); + __this_cpu_write(scope_chaining_fence, child); + err = dma_fence_add_callback(child, &scope->callbacks[i].callback, + scope_callback); + __this_cpu_write(scope_chaining_fence, NULL); + preempt_enable(); + if (err) { scope_arrived(scope, child->error); dma_fence_put(&scope->base); } diff --git a/drivers/gpu/drm/asahi/g17/sync_scope.h b/drivers/gpu/drm/asahi/g17/sync_scope.h index e88b78aacdd7b5..1504fcb5effefc 100644 --- a/drivers/gpu/drm/asahi/g17/sync_scope.h +++ b/drivers/gpu/drm/asahi/g17/sync_scope.h @@ -8,10 +8,13 @@ void asahi_g17_signal_fence(struct dma_fence *fence); int asahi_g17_completion_fence_status(struct dma_fence *fence); struct dma_fence *asahi_g17_scope_create(struct dma_fence *previous, - struct dma_fence *submitted, u64 point); + struct dma_fence *submitted, u64 point, + bool compute_only); void asahi_g17_scope_bind(struct dma_fence *scope, struct dma_fence *root); bool asahi_g17_is_scope(struct dma_fence *fence); /* Returns owned child references, or zero once the scope is signalled. */ unsigned int asahi_g17_scope_children(struct dma_fence *fence, struct dma_fence *children[2]); +void asahi_g17_note_compute_waiter(void); +void asahi_g17_unnote_compute_waiter(void); #endif diff --git a/drivers/gpu/drm/asahi/g17/teardown.rs b/drivers/gpu/drm/asahi/g17/teardown.rs index 39208dc7b3f34b..84e36aaaeadc63 100644 --- a/drivers/gpu/drm/asahi/g17/teardown.rs +++ b/drivers/gpu/drm/asahi/g17/teardown.rs @@ -205,7 +205,11 @@ impl Pending { } continue; } + // A queue the kernel closed for its still open client holds the context until + // the client closes it: its scheduler is released, and the context reclaimed, only + // after that. Its guilty work went with the kill already. if entry.phase != Phase::Draining + || entry.context.held_by_open_client() || !host.render_idle(&entry.context)? || !host.flists_released(&entry.context) || !host.compute_idle(&entry.context) diff --git a/drivers/gpu/drm/asahi/g17/telemetry.rs b/drivers/gpu/drm/asahi/g17/telemetry.rs index 23f66a7fcced0b..bb439ee4acc76c 100644 --- a/drivers/gpu/drm/asahi/g17/telemetry.rs +++ b/drivers/gpu/drm/asahi/g17/telemetry.rs @@ -3,9 +3,11 @@ //! Qualified V25G83/V26A428 statistics, decoded from complete copied records. //! No record of these firmwares measures power or temperature. //! -//! The 26A428 firmware (the A18 Pro's, and the M5's) reports the performance state the -//! GPU runs at (tags 0x19 and 0x1b), and its utilisation records carry their own -//! timestamps, from which busy time is integrated ([`Protocol`]). 25G83 sends neither. +//! The 26A428 firmware (the A18 Pro's, and the M5's) and T6041's 25G83 +//! firmware report the performance state the GPU runs at (tags 0x19 and 0x1b), +//! and their utilisation records carry their own timestamps, from which busy +//! time is integrated ([`Protocol`]). T6040's 25G83 is left on `Protocol::NONE` +//! because it has not been measured yet. //! All state is protected by the device mutex. pub(super) const UNAVAILABLE: u32 = 0; @@ -46,49 +48,62 @@ const _: () = { }; const TIMER_HZ: u64 = 24_000_000; +/// Records a firmware statistics ring holds (`fw::channels::STATISTICS_SLOTS`), repeated +/// here so the decoder builds on its own (`tools/asahi/g17-telemetry-tests.rs`); the kernel +/// build asserts the two are equal in `channel.rs`. +pub(crate) const STATISTICS_RING_RECORDS: u32 = 256; /// What a firmware reports beyond utilisation. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct Protocol { - /// Highest performance state its state records (tags 0x19 and 0x1b) name; zero where it - /// sends none. State 0 is off. - pub(crate) max_pstate: u32, + /// Emits performance state reports in tags 0x19 (interval) and 0x1b (state). + pub(crate) reports_pstate: bool, /// Interval of its utilisation record (tag 0x13), in timer ticks, whose timestamps busy /// time is integrated from; zero where it is not integrated. pub(crate) util_period_ticks: u64, } impl Protocol { - /// 25G83: utilisation only. + /// Utilisation only: no 0x19/0x1b performance state reports and no busy-time integration. pub(crate) const NONE: Self = Self { - max_pstate: 0, + reports_pstate: false, util_period_ticks: 0, }; - /// M5: the device tree's operating points 1 to 13, utilisation every 8 ms. - pub(crate) const M5: Self = Self { - max_pstate: 13, + /// Performance state reports (tags 0x19/0x1b) and 8 ms timestamped utilisation records + /// (192000 ticks at 24 MHz), as emitted by V26A428 M5 and T6041 25G83. + pub(crate) const PSTATE_8MS: Self = Self { + reports_pstate: true, util_period_ticks: 192_000, }; - /// A18 Pro: states 1 to 10 of its eleven-state performance tables, utilisation every - /// 16 ms. - pub(crate) const A18_PRO: Self = Self { - max_pstate: 10, + /// Performance state reports (tags 0x19/0x1b) and 16 ms timestamped utilisation records + /// (384000 ticks at 24 MHz), as emitted by V26A428 on A18 Pro. + pub(crate) const PSTATE_16MS: Self = Self { + reports_pstate: true, util_period_ticks: 384_000, }; pub(crate) const fn reports_pstate(self) -> bool { - self.max_pstate != 0 + self.reports_pstate } fn integrates_busy(self) -> bool { self.util_period_ticks != 0 } - /// A utilisation record more than two intervals after the previous one follows a gap the - /// firmware did not report (gated or lost records): it only sets the baseline. + /// A utilisation record at most two intervals after the previous one closes the window + /// since it. One after a longer gap the firmware did not report (the GPU was gated, or + /// records were lost) closes only its own sampling period. fn max_window_ticks(self) -> u64 { 2 * self.util_period_ticks } + + /// How far a record can lag the busy mark and still have been queued: a full statistics + /// ring of the other role's utilisation records, one per interval, with a factor of two + /// for margin. A record further behind comes from a firmware clock that started again, + /// and only sets a new mark. + fn rebase_ticks(self) -> u64 { + 2 * u64::from(STATISTICS_RING_RECORDS) * self.util_period_ticks + } } #[derive(Default)] @@ -109,19 +124,25 @@ pub(super) struct Telemetry { gated: bool, /// The records decoded beyond utilisation. protocol: Protocol, - /// Timestamp of the latest utilisation record in this epoch: the start of the window the - /// next one closes. - busy_ts: Option, + /// Highest valid performance state index for tags 0x19/0x1b, derived from the device's + /// state-frequency table; zero fails closed and rejects all 0x1b states. + max_pstate: u32, + /// Firmware timestamp up to which busy time has been credited. It is kept across + /// epochs: power gates, suspend and restarts end the utilisation average, but never + /// let a record at or before this mark be credited again. + busy_mark: Option, busy_ns: u64, /// End of the latest performance state interval (tag 0x19), in timer ticks. pstate_interval_end: Option, } impl Telemetry { - /// Decoder for a firmware that also sends `protocol`'s records. - pub(super) fn new(protocol: Protocol) -> Self { + /// Decoder for a firmware that also sends `protocol`'s records, bounding 0x1b performance + /// state indices to `1..=max_pstate`. + pub(super) fn new(protocol: Protocol, max_pstate: u32) -> Self { Self { protocol, + max_pstate, ..Self::default() } } @@ -141,8 +162,7 @@ impl Telemetry { self.delivery_ns = None; self.delivery_intervals = [None; 2]; self.gated = false; - // Busy time keeps counting across epochs; only the window start is lost. - self.busy_ts = None; + // Busy time keeps counting across epochs, ordered by its own mark. self.pstate_interval_end = None; } @@ -235,16 +255,16 @@ impl Telemetry { self.view.pstate_status = if words[6] <= 10 { VALID } else { UNAVAILABLE }; self.view.pstate = words[6]; } - // 26A428: the interval [words 3-4, words 1-2] that just ended. Its end - // timestamps the state report that follows it. + // The interval [words 3-4, words 1-2] that just ended. Its end timestamps the + // state report that follows it. 0x19 if self.protocol.reports_pstate() => { self.pstate_interval_end = Some(u64::from(words[1]) | (u64::from(words[2]) << 32)); } - // 26A428: the performance state now in effect, in words 1 and 3. A report whose - // two words differ is not used. + // The performance state now in effect, in words 1 and 3. A report whose two + // words differ is not used. 0x1b if self.protocol.reports_pstate() => { let pstate = words[1]; - if pstate != words[3] || pstate == 0 || pstate > self.protocol.max_pstate { + if pstate != words[3] || pstate == 0 || pstate > self.max_pstate { self.view.pstate_status = UNAVAILABLE; return; } @@ -257,20 +277,47 @@ impl Telemetry { } } - /// Credits the window a utilisation record closes, at its device utilisation. The window - /// starts at the previous record of the epoch; a record after a longer gap than - /// [`Protocol::max_window_ticks`] (the GPU was gated or records were lost) or one whose - /// timestamp went back only sets the baseline, so an idle gap is never credited. + /// A utilisation record that is kept out of the utilisation average: one a power boundary + /// cut off, or one drained while the cores read gated. The firmware produced it before + /// the boundary, so it describes powered time, which its own timestamp places. Only busy + /// time takes it; the average, the delivery cadence and the performance state are left + /// as they are. + pub(super) fn record_busy(&mut self, words: &[u32; 18]) { + if !self.protocol.integrates_busy() + || words[0] != 0x13 + || [words[3], words[4], words[6]].iter().any(|&v| v > 100) + { + return; + } + self.integrate_busy(u64::from(words[1]) | (u64::from(words[2]) << 32), words[6]); + } + + /// Credits the window a utilisation record closes, at its device utilisation. + /// + /// Records are credited in firmware timestamp order, from both roles and across + /// epochs: a record at or before [`Self::busy_mark`] was already covered and gets + /// nothing, so a time interval is never credited twice. A later record closes the + /// window since the mark when that is at most [`Protocol::max_window_ticks`]; after a + /// longer gap (the cores were gated, or records were lost) it closes only its own + /// sampling period, which starts after the mark, so the gap itself is never credited. + /// The first record only sets the mark. fn integrate_busy(&mut self, timestamp: u64, device: u32) { - if let Some(last) = self.busy_ts { - let window = timestamp.wrapping_sub(last); - if timestamp > last && window <= self.protocol.max_window_ticks() { + match self.busy_mark { + Some(mark) if timestamp > mark => { + let gap = timestamp - mark; + let window = if gap <= self.protocol.max_window_ticks() { + gap + } else { + self.protocol.util_period_ticks + }; // At most two 16 ms periods (768000 ticks) x 100 x 10^9: no overflow. let ns = window * u64::from(device) * 1_000_000_000 / (100 * TIMER_HZ); self.busy_ns = self.busy_ns.saturating_add(ns); } + Some(mark) if mark - timestamp <= self.protocol.rebase_ticks() => return, + _ => {} } - self.busy_ts = Some(timestamp); + self.busy_mark = Some(timestamp); } pub(super) fn read(&self, now_ns: u64, max_age_ns: u64) -> Readout { @@ -533,7 +580,7 @@ mod tests { #[test] fn m5_state_reports_give_the_pstate() { - let mut stats = Telemetry::new(Protocol::M5); + let mut stats = Telemetry::new(Protocol::PSTATE_8MS, 13); stats.record(&M5_INTERVAL, 100, AGE); assert_eq!(stats.read(100, AGE).pstate_status, UNAVAILABLE); stats.record(&M5_STATE, 101, AGE); @@ -564,7 +611,7 @@ mod tests { #[test] fn m5_busy_time_integrates_utilisation_windows() { - let mut stats = Telemetry::new(Protocol::M5); + let mut stats = Telemetry::new(Protocol::PSTATE_8MS, 13); assert_eq!( (stats.read(0, AGE).busy_status, stats.read(0, AGE).busy_ns), (VALID, 0) @@ -584,27 +631,98 @@ mod tests { half[6] = 50; stats.record(&half, 103, AGE); assert_eq!(stats.read(103, AGE).busy_ns, windows + 4_000_000); - // A gate, a long gap or a timestamp going back only sets a new baseline. + // A gate ends the utilisation epoch, not the busy time: the next record still + // closes the window since the last one. let before = stats.read(103, AGE).busy_ns; stats.gate(); let mut after = half; after[1] += 192_000; stats.record(&after, 104, AGE); - assert_eq!(stats.read(104, AGE).busy_ns, before); - after[1] += 3 * 192_000; + assert_eq!(stats.read(104, AGE).busy_ns, before + 4_000_000); + // After a longer gap the record closes only its own 8 ms period. + let before = stats.read(104, AGE).busy_ns; + after[1] += 10 * 192_000; stats.record(&after, 105, AGE); - assert_eq!(stats.read(105, AGE).busy_ns, before); + assert_eq!(stats.read(105, AGE).busy_ns, before + 4_000_000); + // A record at or before the mark was already covered. + let before = stats.read(105, AGE).busy_ns; after[1] -= 1000; stats.record(&after, 106, AGE); + after[1] += 1000; + stats.record(&after, 106, AGE); assert_eq!(stats.read(106, AGE).busy_ns, before); - // An epoch boundary keeps the total. + // An epoch boundary keeps the total and the mark. stats.invalidate(); assert_eq!(stats.read(107, AGE).busy_ns, before); + stats.record(&after, 108, AGE); + assert_eq!(stats.read(108, AGE).busy_ns, before); + } + + fn m5_util(ticks: u64, device: u32) -> [u32; 18] { + let mut words = M5_U[0]; + (words[1], words[2], words[6]) = (ticks as u32, (ticks >> 32) as u32, device); + words + } + + #[test] + fn m5_busy_time_counts_through_frequent_gates() { + // A frame-paced load: one record per epoch, a gate between any two. + let mut stats = Telemetry::new(Protocol::PSTATE_8MS, 13); + let mut ticks = 0x59_0000_0000u64; + stats.record(&m5_util(ticks, 100), 1, AGE); + for n in 0..10u64 { + stats.gate(); + stats.invalidate(); + ticks += 250_000; // 10.4 ms: more than one period, at most two. + stats.record(&m5_util(ticks, 100), 2 + n, AGE); + } + assert_eq!(stats.read(20, AGE).busy_ns, 10 * ticks_ns(250_000)); + } + + #[test] + fn m5_records_kept_out_of_the_epoch_still_count_once() { + let base = 0x59_0000_0000u64; + let mut stats = Telemetry::new(Protocol::PSTATE_8MS, 13); + stats.record(&m5_util(base, 100), 1, AGE); + // Cut off by a boundary, decoded by its own timestamp. + stats.gate(); + stats.record_busy(&m5_util(base + 192_000, 100)); + assert_eq!(stats.read(2, AGE).busy_ns, 8_000_000); + // It does not start a utilisation sample in the new epoch. + assert_eq!(stats.read(2, AGE).util_samples, 0); + // A copy of it, from the queue or from the other role, is not counted again, + // nor an older record drained later. + stats.record(&m5_util(base + 192_000, 100), 3, AGE); + stats.record_busy(&m5_util(base + 100_000, 100)); + assert_eq!(stats.read(3, AGE).busy_ns, 8_000_000); + // Interleaved roles split the time between them and never overlap. + stats.record_busy(&m5_util(base + 288_000, 100)); + stats.record(&m5_util(base + 384_000, 100), 4, AGE); + stats.record_busy(&m5_util(base + 336_000, 100)); + assert_eq!(stats.read(4, AGE).busy_ns, 16_000_000); + // Records the decoder would refuse are ignored here too. + let mut bad = m5_util(base + 576_000, 100); + bad[4] = 101; + stats.record_busy(&bad); + let mut other = m5_util(base + 576_000, 100); + other[0] = 0x1b; + stats.record_busy(&other); + assert_eq!(stats.read(5, AGE).busy_ns, 16_000_000); + // A firmware clock that started again only sets a new mark. + stats.record_busy(&m5_util(1_000, 100)); + assert_eq!(stats.read(6, AGE).busy_ns, 16_000_000); + stats.record_busy(&m5_util(1_000 + 192_000, 50)); + assert_eq!(stats.read(7, AGE).busy_ns, 20_000_000); + // A firmware that integrates no busy time decodes none of it. + let mut legacy = Telemetry::default(); + legacy.record_busy(&m5_util(base, 100)); + legacy.record_busy(&m5_util(base + 192_000, 100)); + assert_eq!(legacy.read(8, AGE).busy_ns, 0); } #[test] fn a18_pro_state_reports_give_the_pstate() { - let mut stats = Telemetry::new(Protocol::A18_PRO); + let mut stats = Telemetry::new(Protocol::PSTATE_16MS, 10); let mut interval = M5_INTERVAL; let mut state = M5_STATE; (state[1], state[3]) = (10, 10); @@ -633,7 +751,7 @@ mod tests { #[test] fn a18_pro_busy_time_integrates_16_ms_windows() { - let mut stats = Telemetry::new(Protocol::A18_PRO); + let mut stats = Telemetry::new(Protocol::PSTATE_16MS, 10); let mut words = M5_U[0]; stats.record(&words, 100, AGE); // One full 16 ms window at 100%, then one at 25%. @@ -644,13 +762,88 @@ mod tests { words[6] = 25; stats.record(&words, 102, AGE); assert_eq!(stats.read(102, AGE).busy_ns, 20_000_000); - // Up to two periods is one window; longer is a gap the GPU spent gated. + // Up to two periods is one window; after a longer gap, which the GPU spent gated, + // a record closes only its own 16 ms period. words[1] += 768_000; stats.record(&words, 103, AGE); assert_eq!(stats.read(103, AGE).busy_ns, 28_000_000); words[1] += 768_001; stats.record(&words, 104, AGE); - assert_eq!(stats.read(104, AGE).busy_ns, 28_000_000); + assert_eq!(stats.read(104, AGE).busy_ns, 32_000_000); + } + + #[test] + fn t6041_state_reports_give_the_pstate() { + let mut stats = Telemetry::new(Protocol::PSTATE_8MS, 10); + let mut interval = M5_INTERVAL; + let mut state = M5_STATE; + (state[1], state[3]) = (10, 10); + stats.record(&interval, 100, AGE); + stats.record(&state, 101, AGE); + let view = stats.read(101, AGE); + assert_eq!((view.pstate_status, view.pstate), (VALID, 10)); + assert_eq!(view.pstate_timestamp, 0x59_3c04_2f8f); + // Mismatched words, off, or beyond state 10 (even though M5 shares PSTATE_8MS with + // max_pstate 13): not a state. + for (a, b) in [(1, 10), (0, 0), (11, 11), (13, 13)] { + (state[1], state[3]) = (a, b); + stats.record(&state, 102, AGE); + assert_eq!(stats.read(102, AGE).pstate_status, UNAVAILABLE); + } + // Tag 0x10 is not this firmware's state report. + interval[1] += 1; + stats.record(&interval, 103, AGE); + stats.record(&P1, 103, AGE); + assert_eq!(stats.read(103, AGE).pstate_status, UNAVAILABLE); + (state[1], state[3]) = (1, 1); + stats.record(&state, 104, AGE); + assert_eq!(stats.read(104, AGE).pstate, 1); + // Gated cores are off. + stats.gate(); + let view = stats.read(105, AGE); + assert_eq!((view.pstate_status, view.pstate), (VALID, 0)); + stats.invalidate(); + assert_eq!(stats.read(106, AGE).pstate_status, STALE); + } + + #[test] + fn t6041_busy_time_integrates_8_ms_windows() { + let mut stats = Telemetry::new(Protocol::PSTATE_8MS, 10); + let mut words = M5_U[0]; + stats.record(&words, 100, AGE); + // One full 8 ms window at 100%, then one at 50%. + words[1] += 192_000; + stats.record(&words, 101, AGE); + assert_eq!(stats.read(101, AGE).busy_ns, 8_000_000); + words[1] += 192_000; + words[6] = 50; + stats.record(&words, 102, AGE); + assert_eq!(stats.read(102, AGE).busy_ns, 12_000_000); + // Up to two periods (16 ms) is one window; after a longer gap only the record's own + // period (8 ms at 50%) is credited. + words[1] += 384_000; + stats.record(&words, 103, AGE); + assert_eq!(stats.read(103, AGE).busy_ns, 20_000_000); + words[1] += 384_001; + stats.record(&words, 104, AGE); + assert_eq!(stats.read(104, AGE).busy_ns, 24_000_000); + } + + #[test] + fn zero_max_pstate_fails_closed() { + for protocol in [Protocol::PSTATE_8MS, Protocol::PSTATE_16MS] { + let mut stats = Telemetry::new(protocol, 0); + stats.record(&M5_INTERVAL, 100, AGE); + for pstate in [0, 1, 10, 13] { + let mut words = M5_STATE; + (words[1], words[3]) = (pstate, pstate); + stats.record(&words, 101, AGE); + assert_eq!(stats.read(101, AGE).pstate_status, UNAVAILABLE); + } + // Tag 0x10 is still ignored when the protocol reports 0x19/0x1b. + stats.record(&P1, 102, AGE); + assert_eq!(stats.read(102, AGE).pstate_status, UNAVAILABLE); + } } #[test] diff --git a/drivers/gpu/drm/asahi/g17/thermal.rs b/drivers/gpu/drm/asahi/g17/thermal.rs index 6dd9bc7c2b15a6..45b267443ad2b6 100644 --- a/drivers/gpu/drm/asahi/g17/thermal.rs +++ b/drivers/gpu/drm/asahi/g17/thermal.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! GPU power budget governor for M5 (J714). +//! GPU thermal management for M5: opt-in host power budget governor (J714) and +//! DT-configured hotspot fan assistance. //! //! The firmware limits the GPU to the host power budget word in Region C within about a second //! (the calibrated maximum is written there at initialization). Left at that maximum under @@ -23,7 +24,7 @@ //! and at shutdown. Below the engage temperature nothing is written. use core::ffi::{c_char, c_int, c_uint, c_void, CStr}; -use core::sync::atomic::{AtomicI32, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicI32, Ordering}; use kernel::{bindings, prelude::*}; // fans.c: the SMC hwmon cell's fan requests and thermal zone reads, which have stubs where @@ -31,6 +32,15 @@ use kernel::{bindings, prelude::*}; extern "C" { fn asahi_zone_temp(name: *const c_char, temp: *mut c_int) -> c_int; fn asahi_fans_request(dev: *mut c_void, permille: c_uint, min_step_rpm: c_uint) -> c_int; + fn asahi_fans_hotspot_described() -> bool; + fn asahi_fans_hotspot_policy( + dev: *mut c_void, + trigger_mc: *mut c_int, + release_mc: *mut c_int, + hold_ms: *mut c_uint, + ) -> c_int; + fn asahi_fans_request_described(dev: *mut c_void, permille: c_uint, min_step_rpm: c_uint) + -> c_int; } /// SoC hotspot temperature computed by the SMC (registered as a thermal zone by the SMC driver): @@ -109,9 +119,24 @@ const GPU_SLACK_PERCENT: i64 = 70; const CPU_HEAT_MARGIN_MC: i32 = 2000; const CPU_HEAT_FLOOR_SLACK_MW: i64 = 1000; -fn enabled() -> bool { +pub(super) fn enabled() -> bool { crate::module_parameters::m5_thermal_governor.value() & 1 != 0 } + +/// Whether an available SMC hwmon node in the device tree describes hotspot fan assistance +/// (a single SoC die key, active trip thresholds and hold duration, and at least one settable +/// fan with apple,fan-manual-control, checked in macsmc-hwmon). Read at probe so a board +/// without a machine-supplied policy never arms the governor. +static HOTSPOT_FANS_DESCRIBED: AtomicBool = AtomicBool::new(false); + +/// Fan-only assistance: on wherever the SMC's device tree node describes fans a policy may set +/// and the hotspot, and the host power budget controller (m5_thermal_governor bit 0) is not +/// enabled. Whenever that controller is enabled it owns the fans with its own curve, so the +/// assistance never runs beside it; otherwise it leaves the firmware's power budget and CPU +/// policy in control. +pub(super) fn hotspot_fans_only() -> bool { + !enabled() && HOTSPOT_FANS_DESCRIBED.load(Ordering::Relaxed) +} fn cpu_balance_enabled() -> bool { crate::module_parameters::m5_thermal_governor.value() & 4 != 0 } @@ -122,8 +147,10 @@ fn fan_boost_enabled() -> bool { fn fan_curve_enabled() -> bool { crate::module_parameters::m5_thermal_governor.value() & 16 == 0 } +/// Whether the governor work runs for a busy GPU: for the budget controller or the fan +/// assistance. pub(super) fn requested() -> bool { - enabled() + enabled() || hotspot_fans_only() } fn target_mc() -> i32 { let parameter = crate::module_parameters::m5_thermal_target_mc.value(); @@ -194,6 +221,11 @@ fn zone_temperature_mc(_provider: &SensorProvider, name: &CStr) -> Option { /// lookups and sensor reads may sleep. pub(crate) fn hotspot_temperature_mc() -> Option { let provider = SensorProvider::acquire()?; + if hotspot_fans_only() { + // The assistance reads only the input that selected it: the SoC die zone, whose one key + // is the hotspot. Without it the fans go back to the SMC. + return zone_temperature_mc(&provider, SOC_DIE_ZONE); + } zone_temperature_mc(&provider, J714_HOTSPOT_ZONE) .or_else(|| zone_temperature_mc(&provider, SOC_DIE_ZONE)) .or_else(|| { @@ -224,6 +256,8 @@ const FAN_CURVE_STEP_RPM: u32 = 150; /// Selects the board's thermal settings at probe; J714's until then. pub(crate) fn select_board(board: &super::fw::m5::initdata::Board) { FAN_CURVE_START_MC.store(board.fan_curve_start_mc, Ordering::Relaxed); + // SAFETY: a device tree lookup without arguments; called from probe, which may sleep. + HOTSPOT_FANS_DESCRIBED.store(unsafe { asahi_fans_hotspot_described() }, Ordering::Relaxed); } /// The permille of the fan range the curve asks for at hotspot `temp_mc`. @@ -247,18 +281,71 @@ fn fan_curve_permille(temp_mc: i32, target_mc: i32) -> i32 { /// serializes with its unbinding). A fan whose target is within `min_step_rpm` of the new one /// keeps it. Returns the first fan's target rpm, 0 once handed back. fn request_fans(permille: u32, min_step_rpm: u32) -> Option { - let provider = SensorProvider::acquire()?; + let Some(provider) = SensorProvider::acquire() else { + // Unbinding restores the provider's fans. + return (permille == 0).then_some(0); + }; // SAFETY: the provider lock keeps the device bound, as the request requires. let rpm = unsafe { asahi_fans_request(provider.0.cast(), permille, min_step_rpm) }; u32::try_from(rpm).ok() } +/// Machine-supplied hotspot fan-assistance thresholds read from the bound +/// macsmc-hwmon provider (`macsmc_soc_die` active trip temperature, release +/// temperature from its hysteresis, and minimum hold duration). +struct HotspotPolicy { + trigger_mc: i32, + release_mc: i32, + hold_ns: u64, +} + +fn hotspot_assist_policy() -> Option { + let provider = SensorProvider::acquire()?; + let (mut trigger_mc, mut release_mc, mut hold_ms): (c_int, c_int, c_uint) = (0, 0, 0); + // SAFETY: the provider lock keeps the device bound, and all output pointers are valid. + let ret = unsafe { + asahi_fans_hotspot_policy( + provider.0.cast(), + &mut trigger_mc, + &mut release_mc, + &mut hold_ms, + ) + }; + if ret != 0 || trigger_mc <= release_mc || hold_ms == 0 { + return None; + } + Some(HotspotPolicy { + trigger_mc, + release_mc, + hold_ns: u64::from(hold_ms) * 1_000_000, + }) +} + +/// [`request_fans`] for hotspot fan assistance: verifies the bound provider's +/// policy under its device lock and only drives fans marked with +/// `apple,fan-manual-control` in `macsmc-hwmon`. +fn request_fans_described(permille: u32, min_step_rpm: u32) -> Option { + let Some(provider) = SensorProvider::acquire() else { + // Unbinding restores the provider's fans. + return (permille == 0).then_some(0); + }; + // SAFETY: the provider lock keeps the device and its node bound, as the request requires. + let rpm = + unsafe { asahi_fans_request_described(provider.0.cast(), permille, min_step_rpm) }; + u32::try_from(rpm).ok() +} + /// Fan boost: while the governor limits the GPU, every fan runs at its hardware maximum instead of /// the SMC's automatic curve, which settles near two thirds of the maximum at the governor's /// target. /// Released (automatic mode) when the governor releases or the GPU goes idle, after a hold. pub(crate) struct FanBoost { - boosted: bool, + /// Budget-governor full boost (`request_fans`), active or retrying release. + budget_boosted: bool, + budget_release_pending: bool, + /// Hotspot-assistance boost (`request_fans_described`), active or retrying release. + hotspot_boosted: bool, + hotspot_release_pending: bool, since_ns: u64, /// The fan target the curve last wrote (rpm), 0 while the fans are automatic. curve_rpm: u32, @@ -266,7 +353,14 @@ pub(crate) struct FanBoost { impl FanBoost { const fn new() -> Self { - Self { boosted: false, since_ns: 0, curve_rpm: 0 } + Self { + budget_boosted: false, + budget_release_pending: false, + hotspot_boosted: false, + hotspot_release_pending: false, + since_ns: 0, + curve_rpm: 0, + } } /// Puts every fan in manual mode at `permille` of its minimum-to-maximum range, or back in @@ -283,6 +377,11 @@ impl FanBoost { // The target rpm moves with the range only when it moved enough. if let Some(rpm) = self.set_curve_if_moved(permille) { self.curve_rpm = rpm; + self.budget_release_pending = false; + } else if self.curve_rpm == 0 { + // Drop any partial first curve request and keep release pending + // until unrestricted cleanup succeeds. + self.budget_release_pending = !self.set_budget(false); } } else if self.curve_rpm != 0 && (!busy || temp_mc.is_none_or(|t| t < FAN_CURVE_RELEASE_MC)) @@ -299,46 +398,150 @@ impl FanBoost { request_fans(permille.clamp(1, 1000) as u32, step) } - fn set(&mut self, boost: bool) -> bool { + fn set_budget(&self, boost: bool) -> bool { request_fans(if boost { 1000 } else { 0 }, 0).is_some() } + fn set_hotspot(&self, boost: bool, step: u32) -> bool { + request_fans_described(if boost { 1000 } else { 0 }, step).is_some() + } + + fn release_budget(&mut self) -> bool { + if self.budget_boosted || self.budget_release_pending || self.curve_rpm != 0 { + let released = self.set_budget(false); + self.budget_release_pending = !released; + self.budget_boosted = false; + if released { + self.curve_rpm = 0; + } + } + !self.budget_boosted && !self.budget_release_pending && self.curve_rpm == 0 + } + + fn release_hotspot(&mut self) -> bool { + if self.hotspot_boosted || self.hotspot_release_pending { + self.hotspot_release_pending = !self.set_hotspot(false, 0); + self.hotspot_boosted = false; + } + !self.hotspot_boosted && !self.hotspot_release_pending + } + /// Applies one governor step's request. Called from the governor work without driver locks: /// SMC accesses sleep. fn apply(&mut self, want: bool, temp_mc: Option, now_ns: u64) { + if !enabled() { + // Explicit handoff: finish releasing any unrestricted budget-governor + // request before running or releasing manual-only hotspot assistance. + let had_budget = + self.budget_boosted || self.budget_release_pending || self.curve_rpm != 0; + if !self.release_budget() { + if !hotspot_fans_only() { + let _ = self.release_hotspot(); + } + return; + } + if had_budget { + self.since_ns = 0; + } + if !hotspot_fans_only() { + // The device tree describes no fans for it. + let _ = self.release_hotspot(); + return; + } + // Only ever request the SMC's rated maximum or release manual-control fans. + // Thresholds and hold duration come strictly from the bound + // macsmc-hwmon provider's device tree; without them assistance stays off. + if self.hotspot_release_pending { + let _ = self.release_hotspot(); + return; + } + let Some(policy) = hotspot_assist_policy() else { + let _ = self.release_hotspot(); + return; + }; + let threshold = if self.hotspot_boosted { + policy.release_mc + } else { + policy.trigger_mc + }; + if want && temp_mc.is_some_and(|temp| temp >= threshold) { + self.since_ns = now_ns; + // Requested on every busy, hot step, not only the first: a fan already at its + // rated speed for this policy is left alone, and one the SMC took back (the + // hwmon cell was unbound and bound again between two such steps, which restores + // automatic mode) is set again. Steps in the hold do not request. + let step = if self.hotspot_boosted { FAN_CURVE_STEP_RPM } else { 0 }; + self.hotspot_boosted = self.set_hotspot(true, step); + if !self.hotspot_boosted { + // No provider, or a later fan refused after an earlier one accepted. + // Drop any partial manual-only request before retrying on the next tick. + self.hotspot_release_pending = !self.set_hotspot(false, 0); + } + } else if self.hotspot_boosted + && (temp_mc.is_none() + || now_ns.saturating_sub(self.since_ns) >= policy.hold_ns) + { + // A lost hotspot reading ends the boost at once rather than after the hold: + // without the input that started it, the SMC's own policy owns the fans. A step + // that finds no provider (an unbound hwmon cell) reads no hotspot either, so a + // provider gap ends the boost the same way, and a new one starts at + // policy.trigger_mc. + let _ = self.release_hotspot(); + } + return; + } + // Explicit handoff: release any manual-only hotspot request before the + // budget governor takes unrestricted fan ownership. + let had_hotspot = self.hotspot_boosted || self.hotspot_release_pending; + if !self.release_hotspot() { + return; + } + if had_hotspot { + self.since_ns = 0; + } + if self.budget_release_pending && !(want && fan_boost_enabled()) && !self.release_budget() { + return; + } if !fan_boost_enabled() { if fan_curve_enabled() { self.apply_curve(want, temp_mc, target_mc(), now_ns); - } else if self.curve_rpm != 0 && self.set_curve(None).is_some() { - self.curve_rpm = 0; + } else if self.curve_rpm != 0 { + let _ = self.release_budget(); } } let want = want && fan_boost_enabled(); if want { self.since_ns = now_ns; } - if want && !self.boosted { - self.boosted = self.set(true); - } else if !want && self.boosted + if want && !self.budget_boosted { + self.budget_boosted = self.set_budget(true); + if self.budget_boosted { + self.budget_release_pending = false; + } else { + // Drop any partial unrestricted request and keep release pending + // until unrestricted cleanup succeeds. + self.budget_release_pending = !self.set_budget(false); + } + } else if !want + && self.budget_boosted && (!fan_boost_enabled() || now_ns.saturating_sub(self.since_ns) >= FAN_HOLD_NS) + && self.set_budget(false) { - if self.set(false) { - self.boosted = false; - } + self.budget_boosted = false; } } pub(crate) fn release(&mut self) { - if self.boosted && self.set(false) { - self.boosted = false; - } - if self.curve_rpm != 0 && self.set_curve(None).is_some() { - self.curve_rpm = 0; - } + let _ = self.release_budget(); + let _ = self.release_hotspot(); } pub(crate) fn boosted(&self) -> bool { - self.boosted || self.curve_rpm != 0 + self.budget_boosted + || self.budget_release_pending + || self.hotspot_boosted + || self.hotspot_release_pending + || self.curve_rpm != 0 } } @@ -679,10 +882,13 @@ impl Governor { } } + pub(super) fn recent_activity(&self, now_ns: u64) -> bool { + self.last_activity_ns != 0 && now_ns.saturating_sub(self.last_activity_ns) < IDLE_RESTORE_NS + } + /// Whether the fans should be boosted: while the controller governs a busy GPU. pub(crate) fn fans_wanted(&self, now_ns: u64) -> bool { - self.maximum_mw != 0 && self.active - && now_ns.saturating_sub(self.last_activity_ns) < IDLE_RESTORE_NS + self.maximum_mw != 0 && self.active && self.recent_activity(now_ns) } /// One control step with the hotspot temperature, the GPU's current draw (mW) and whether the diff --git a/drivers/gpu/drm/asahi/g18/boot/compute_session.rs b/drivers/gpu/drm/asahi/g18/boot/compute_session.rs index 8af55d934298f9..a5c7d8b40900ba 100644 --- a/drivers/gpu/drm/asahi/g18/boot/compute_session.rs +++ b/drivers/gpu/drm/asahi/g18/boot/compute_session.rs @@ -8,8 +8,16 @@ impl G18Session { translated: &crate::g18::uapi::command::TranslatedComputeCommand) -> core::result::Result<(), Failure> { self.poll_idle_faults("application compute prepare")?; - let (command, pool, generation, knobs) = self.memory.as_mut().ok_or(EIO)? - .prepare_application_compute(&self.dev, vm, translated)?; + let memory = self.memory.as_mut().ok_or(EIO)?; + let (command, pool, generation, knobs) = + match memory.prepare_application_compute(&self.dev, vm, translated) { + Ok(prepared) => prepared, + // A refusal that left the owner retired and nothing + // published fails this job only. + Err(error) => return Err(if memory.application_compute_unpublished() { + Failure::Job(JobFailure::Refused(error)) + } else { Failure::Fatal(error) }), + }; if generation == 1 { self.queue_probe.as_mut().ok_or(EIO)?.prepare_initial_context(command.context_id)?; for phase in 1..=3 { diff --git a/drivers/gpu/drm/asahi/g18/boot/mod.rs b/drivers/gpu/drm/asahi/g18/boot/mod.rs index b05b6d95ef8526..85995224bb62c2 100644 --- a/drivers/gpu/drm/asahi/g18/boot/mod.rs +++ b/drivers/gpu/drm/asahi/g18/boot/mod.rs @@ -1053,6 +1053,8 @@ struct G18RoleSlot { struct G18Session { roles: [G18RoleSlot; 2], states: [Arc; 2], + /// The CLPC's GPU input: memory and fabric floor while jobs run. + demand: crate::g18::demand::G18Demand, memory: Option>, queue_probe: Option, render_job: Option>, @@ -2055,9 +2057,11 @@ fn prepare_firmware_session(pdev: &platform::Device>, probe: T8152Probe if roles[0].role != G18Role::Gfx || roles[1].role != G18Role::Gfx1 { return Err(EINVAL); } + let demand = probe.demand; let session = KBox::new(G18Session { roles, states, + demand, memory: None, queue_probe: None, render_job: None, diff --git a/drivers/gpu/drm/asahi/g18/boot/recovery.rs b/drivers/gpu/drm/asahi/g18/boot/recovery.rs index bd4718c804a168..fbdb4036c3f112 100644 --- a/drivers/gpu/drm/asahi/g18/boot/recovery.rs +++ b/drivers/gpu/drm/asahi/g18/boot/recovery.rs @@ -164,6 +164,11 @@ pub(super) enum JobFailure { Released, /// [`Self::Stranded`] as reported back to the submitting thread. Retained, + /// Refused while being prepared from the client's own state (its VM + /// closed, an address it names unmapped, an allocation it sized): nothing + /// of the job reached the firmware and its owner is back where the last + /// retirement left it. The session and the path keep serving. + Refused(Error), } /// How far a failed task reaches. @@ -395,6 +400,9 @@ impl G18Session { let mut since = Instant::::now(); let mut reported = 0u32; self.growth_refused = false; + // The job is running: the CLPC holds the memory and fabric floor + // until it ends, on every path out of here, and 16 ms past the last. + let _job = self.demand.job(); loop { if let Some(serviced) = self.poll_faults(label)? { if recovery.is_none() { diff --git a/drivers/gpu/drm/asahi/g18/boot/session.rs b/drivers/gpu/drm/asahi/g18/boot/session.rs index e0653fbd1b247b..cf03052bb7b81e 100644 --- a/drivers/gpu/drm/asahi/g18/boot/session.rs +++ b/drivers/gpu/drm/asahi/g18/boot/session.rs @@ -105,6 +105,7 @@ impl ApplicationOwner { Err(Failure::Fatal(error))=>error.to_errno(), Err(Failure::Job(JobFailure::Recovered(_) | JobFailure::Unbound(..) | JobFailure::Released))=>JobOutcome::Recovered as i32, Err(Failure::Job(JobFailure::Stranded(..) | JobFailure::Retained))=>JobOutcome::Stranded as i32, + Err(Failure::Job(JobFailure::Refused(error)))=>JobOutcome::Refused as i32-error.to_errno(), } } @@ -114,6 +115,8 @@ impl ApplicationOwner { 0 => Ok(()), code if code==JobOutcome::Recovered as i32 => Err(Failure::Job(JobFailure::Released)), code if code==JobOutcome::Stranded as i32 => Err(Failure::Job(JobFailure::Retained)), + code if code>JobOutcome::Refused as i32 => + Err(Failure::Job(JobFailure::Refused(Error::from_errno(JobOutcome::Refused as i32-code)))), errno => Err(Failure::Fatal(Error::from_errno(errno))), } } @@ -125,6 +128,8 @@ impl ApplicationOwner { match result { Ok(()) => Ok(()), Err(Failure::Job(JobFailure::Released)) | Err(Failure::Job(JobFailure::Recovered(_))) => Err(EIO), + // Nothing ran: the client's VM stays usable. + Err(Failure::Job(JobFailure::Refused(error))) => Err(error), Err(Failure::Job(_)) => {if let Some(status)=vm.status(){status.record(EIO);}Err(EIO)} Err(Failure::Fatal(error)) => {if let Some(status)=vm.status(){status.record(error);}Err(error)} } @@ -137,6 +142,8 @@ const TICKET_RUNNING: i32 = 1; enum JobOutcome { Recovered = 2, Stranded = 3, + /// Plus the errno: [`JobFailure::Refused`]. + Refused = 0x1000, } impl G18Runtime for ApplicationOwner { @@ -200,6 +207,9 @@ fn log_job_failure(session:&G18Session,failure:&JobFailure) { JobFailure::Unbound(r,path,unready) => dev_err!(session.device(), "G18_APP_JOB_FAILED error={:?} recovery epoch={} host={} us={} reason={:#x} slot-mask={:#x} queues=retired unbound={} path={:?} quarantined session=live recoveries={}\n", EIO,r.epoch,r.host,r.us,r.cause.reason,r.cause.slot_mask,unready,path,recovery::recoveries()), + // The submitter's own error, returned to it: not logged above debug level. + JobFailure::Refused(error) => dev_dbg!(session.device(), + "G18_APP_JOB_REFUSED error={:?} unpublished session=live\n",error), // Only the submitting thread's summaries; the worker logs the rest. JobFailure::Released | JobFailure::Retained => {} } @@ -213,7 +223,11 @@ impl G18Session { self.application_job=Some(ApplicationJob::new(self.render_job.take().ok_or(EIO)?)?); } let job=self.application_job.as_mut().ok_or(EIO)?; - job.prepare(&self.dev,&self.uat,vm,render)?; + if let Err(error)=job.prepare(&self.dev,&self.uat,vm,render) { + // Nothing is published before prepare() commits the frame: a + // job it refused leaves the owner retired, the session serves on. + return Err(if job.unpublished() {Failure::Job(JobFailure::Refused(error))} else {Failure::Fatal(error)}); + } if job.pool_aliases.is_empty() { job.pool_aliases=self.memory.as_mut().ok_or(EIO)?.application_aliases(vm)?; } diff --git a/drivers/gpu/drm/asahi/g18/buffer/pool.rs b/drivers/gpu/drm/asahi/g18/buffer/pool.rs index f080fecd7afc33..2c70e112d7f97c 100644 --- a/drivers/gpu/drm/asahi/g18/buffer/pool.rs +++ b/drivers/gpu/drm/asahi/g18/buffer/pool.rs @@ -86,6 +86,9 @@ pub(crate) struct G18UmaPoolMemory { low_bias: u64, hardware_slot: u32, block_stride: u64, + /// The client VM an application path last aliased the scratch blocks + /// into; None before the first. + client_vm: Option, } impl G18UmaPoolMemory { @@ -109,10 +112,29 @@ impl G18UmaPoolMemory { || !self.process_aliases.is_empty() { return Err(EINVAL); } + self.clear_scratch_for(vm)?; self.alias_into_process(dev, uat, vm)?; Ok(core::mem::replace(&mut self.process_aliases, KVec::new())) } + /// The scratch blocks hold the private memory of the last client VM's + /// threads. Storage released by that VM may still hold its data; clear + /// it before another VM maps it (construction leaves it zero). The + /// directory, block list, state and descriptor are kept: they name the + /// pool's own objects and the hardware owns their allocation cursors. + /// The caller proved the pool's last job retired and dropped the + /// previous VM's aliases. The same VM again clears nothing. + fn clear_scratch_for(&mut self, vm: &mmu::Vm) -> Result { + if self.client_vm.is_some_and(|id| id != vm.id()) { + for block in self.scratch.iter_mut() { + block.with_bytes_mut(|bytes| { bytes.fill(0); Ok(()) })?; + } + fence(Ordering::SeqCst); + } + self.client_vm = Some(vm.id()); + Ok(()) + } + /// The retained backing plan; application compute bounds its SMA pair by it. pub(crate) fn scratch_plan(&self) -> Option { self.scratch_plan @@ -283,6 +305,7 @@ impl G18UmaPoolMemory { descriptor_loaded: false, render: false, low_bias, hardware_slot, block_stride: if low_bias == 0 { BLOCK_DATA_STRIDE } else { 0x300000 }, + client_vm: None, }) } diff --git a/drivers/gpu/drm/asahi/g18/buffer/pool_application.rs b/drivers/gpu/drm/asahi/g18/buffer/pool_application.rs index 3e1e012966a0c5..cd27b47a180160 100644 --- a/drivers/gpu/drm/asahi/g18/buffer/pool_application.rs +++ b/drivers/gpu/drm/asahi/g18/buffer/pool_application.rs @@ -23,6 +23,7 @@ impl G18UmaPoolMemory { pub(crate) fn application_aliases(&mut self, uat: &mmu::Uat, vm: &mmu::Vm) -> Result> { if !self.render || self.scratch_plan.is_none() {return Err(EINVAL);} + self.clear_scratch_for(vm)?; let mut aliases=KVec::new(); for (index,page) in self.directory.iter_mut().enumerate() { let address=DIRECTORY_BASE+self.layout.page_offset(index as u32).ok_or(EINVAL)?; diff --git a/drivers/gpu/drm/asahi/g18/buffer/pool_shared_compute.rs b/drivers/gpu/drm/asahi/g18/buffer/pool_shared_compute.rs index f8e9a17cf7817d..6540fe263cb535 100644 --- a/drivers/gpu/drm/asahi/g18/buffer/pool_shared_compute.rs +++ b/drivers/gpu/drm/asahi/g18/buffer/pool_shared_compute.rs @@ -70,6 +70,8 @@ impl G18UmaPoolMemory { let mut pool = Self::new_layout(dev, uat, high.clone(), 12, true, false, bias, 1, G18_COMPUTE_BLOCK_BYTES)?; pool.prepare_shared_compute_retaining(dev, uat, high, plan, Some(self))?; + // The retained scratch objects carry the last client's data along. + pool.client_vm = self.client_vm; Ok(pool) } diff --git a/drivers/gpu/drm/asahi/g18/compat/e2e.rs b/drivers/gpu/drm/asahi/g18/compat/e2e.rs index d189df3eca289f..4c1b74c1801dd0 100644 --- a/drivers/gpu/drm/asahi/g18/compat/e2e.rs +++ b/drivers/gpu/drm/asahi/g18/compat/e2e.rs @@ -209,7 +209,9 @@ const PAGE: u64 = crate::pgtable::UAT_PGSZ as u64; fn map_power_sources() -> bool { let map_page = |slot: &AtomicPtr, link: u64| -> bool { if !slot.load(Ordering::Acquire).is_null() { return true; } - let physical = crate::g18::compat::g17p::g17p_gfx_link_to_physical(link); + let Some(physical) = crate::g18::compat::g17p::g17p_gfx_link_to_physical(link) else { + return false; + }; // SAFETY: same page as the existing bounded diag_knobs probe; WB // read-only use; retained until module unload. let ptr = unsafe { bindings::memremap(physical & !(PAGE - 1), PAGE as usize, @@ -232,7 +234,7 @@ fn map_power_sources() -> bool { fn read_firmware_word(page: &AtomicPtr, link: u64) -> Option { let base = page.load(Ordering::Acquire); if base.is_null() { return None; } - let physical = crate::g18::compat::g17p::g17p_gfx_link_to_physical(link); + let physical = crate::g18::compat::g17p::g17p_gfx_link_to_physical(link)?; let offset = (physical & (PAGE - 1)) as usize; // SAFETY: `base` maps the whole containing page for the module lifetime; // `offset` is 8-aligned (both links are) and below the page size. The diff --git a/drivers/gpu/drm/asahi/g18/compat/g17p.rs b/drivers/gpu/drm/asahi/g18/compat/g17p.rs index c1b26631234776..c6af8b95af9527 100644 --- a/drivers/gpu/drm/asahi/g18/compat/g17p.rs +++ b/drivers/gpu/drm/asahi/g18/compat/g17p.rs @@ -11,7 +11,7 @@ use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use core::ptr::NonNull; #[cfg(CONFIG_DEV_COREDUMP)] use kernel::{bindings, ffi::c_void}; -use kernel::{addr::PhysicalAddr, prelude::*}; +use kernel::{addr::PhysicalAddr, c_str, device, prelude::*}; use crate::pgtable::{UAT_PGMSK, UAT_PGSZ}; // diagnostic_accounting_clocks names the probe as `pgtable::LiveFirmwareU64Probe`. use crate::g18::compat::g17p as pgtable; @@ -25,12 +25,52 @@ const G17P_GFX_LINK_DATA_BASE: u64 = 0xffff_fc00_0004_c000; const G17P_GFX_LINK_DATA_END: u64 = 0xffff_fc00_0018_0000; -const G17P_GFX_PHYSICAL_DATA_BASE: u64 = 0x0000_0100_01d7_c000; +/// Physical base of the bound G17P GPU's GFX DATA segment, 0 while none is +/// bound. The module parameters that read firmware DATA exist on every Mac. +static G17P_GFX_PHYSICAL_DATA_BASE: AtomicU64 = AtomicU64::new(0); + +/// The `fw-data` region's start, if it holds the whole GFX DATA segment. The +/// region holds the data segments of both firmware roles, GFX (ADT sgx +/// gfx-data) first. +fn g17p_fw_data_start(dev: &device::Device) -> Option { + let resource = dev + .of_node()? + .reserved_mem_region_to_resource_byname(c_str!("fw-data")) + .ok()?; + let start = resource.start(); + if start == 0 + || start & (UAT_PGMSK as u64) != 0 + || resource.size() < G17P_GFX_LINK_DATA_END - G17P_GFX_LINK_DATA_BASE + { + return None; + } + Some(start) +} + +/// Publish the GFX DATA base of a probed G17P GPU from its `fw-data` region. +/// Without a usable region nothing is published and the diagnostics that read +/// firmware DATA report none. +pub(crate) fn g17p_publish_gfx_data(dev: &device::Device) { + let base = g17p_fw_data_start(dev).unwrap_or(0); + G17P_GFX_PHYSICAL_DATA_BASE.store(base, Ordering::Release); +} + +/// Withdraw the published GFX DATA base when the G17P GPU is unbound. +pub(crate) fn g17p_unpublish_gfx_data() { + G17P_GFX_PHYSICAL_DATA_BASE.store(0, Ordering::Release); +} /// Translate a GFX firmware LINK address into the physical address the host -/// can map. Same arithmetic the render status-page probes use. -pub(crate) fn g17p_gfx_link_to_physical(link: u64) -> u64 { - G17P_GFX_PHYSICAL_DATA_BASE + (link - G17P_GFX_LINK_DATA_BASE) +/// can map. Same arithmetic the render status-page probes use. None while no +/// G17P GPU is bound or for a LINK address outside the DATA segment. +pub(crate) fn g17p_gfx_link_to_physical(link: u64) -> Option { + if !(G17P_GFX_LINK_DATA_BASE..G17P_GFX_LINK_DATA_END).contains(&link) { + return None; + } + match G17P_GFX_PHYSICAL_DATA_BASE.load(Ordering::Acquire) { + 0 => None, + base => Some(base + (link - G17P_GFX_LINK_DATA_BASE)), + } } fn g17p_binding_row_address(base: u64, id: u32, stride: u64) -> Option { @@ -55,7 +95,7 @@ pub(crate) fn diagnostic_accounting_clocks() -> Result<[u64; 8]> { let read = |index: usize| -> Result { let link = 0xffff_fc00_0000_0000u64.checked_add(OFFSETS[index]).ok_or(EOVERFLOW)?; let start = g17p_binding_row_address(link, 0, 8).ok_or(EINVAL)?; - pgtable::LiveFirmwareU64Probe::new(g17p_gfx_link_to_physical(start)) + pgtable::LiveFirmwareU64Probe::new(g17p_gfx_link_to_physical(start).ok_or(ENODEV)?) .and_then(|probe| probe.observe_mask(u64::MAX, 1)) .map(|sample| sample.first) }; diff --git a/drivers/gpu/drm/asahi/g18/compat/timing_buffer.rs b/drivers/gpu/drm/asahi/g18/compat/timing_buffer.rs index 98a6c23df9670e..12fc7bf28c97d9 100644 --- a/drivers/gpu/drm/asahi/g18/compat/timing_buffer.rs +++ b/drivers/gpu/drm/asahi/g18/compat/timing_buffer.rs @@ -395,8 +395,11 @@ unsafe extern "C" fn diag_get(buf: *mut core::ffi::c_char, // 177838 idle-off policy (RegionC+0x30 copy), 128a68 keep-on bits. for (name, link) in [("powerups", 0xffff_fc00_0012_4ba0u64), ("state", 0xffff_fc00_0017_71f8), ("idleoff", 0xffff_fc00_0017_7838), ("keepon", 0xffff_fc00_0012_8a68)] { - let value = crate::g18::compat::g17p::LiveFirmwareU64Probe::new( - crate::g18::compat::g17p::g17p_gfx_link_to_physical(link)) + let Some(physical) = crate::g18::compat::g17p::g17p_gfx_link_to_physical(link) else { + let _ = writeln!(out, "{} none (no G17P fw-data region)", name); + continue; + }; + let value = crate::g18::compat::g17p::LiveFirmwareU64Probe::new(physical) .and_then(|probe| probe.observe_mask(u64::MAX, 1)) .map(|sample| sample.first); let _ = writeln!(out, "{} {:x?}", name, value); @@ -437,7 +440,10 @@ unsafe extern "C" fn peek_get(buf: *mut core::ffi::c_char, let address = PEEK_ADDR.load(Ordering::Relaxed); if address < PEEK_DATA_START { return 0; } let page = crate::pgtable::UAT_PGSZ as u64; - let physical = crate::g18::compat::g17p::g17p_gfx_link_to_physical(address); + let Some(physical) = crate::g18::compat::g17p::g17p_gfx_link_to_physical(address) else { + let _ = writeln!(out, "error: no G17P fw-data region"); + return out.used as core::ffi::c_int; + }; let room = ((page - (physical & (page - 1))) / 8).min(64) as usize; let room = room.min(((PEEK_DATA_END - address) / 8) as usize); let mut values = [0u64; 64]; diff --git a/drivers/gpu/drm/asahi/g18/demand.c b/drivers/gpu/drm/asahi/g18/demand.c new file mode 100644 index 00000000000000..ed8bdfe4d8cd9c --- /dev/null +++ b/drivers/gpu/drm/asahi/g18/demand.c @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * G18: the CLPC's GPU input. While the GPU has work, the CLPC holds the + * memory controller (DCS) and fabric floor at the top of its map, as the G17 + * backend reports its work. The T8152 CLPC otherwise raises that floor only + * for busy CPU clusters. Each job the driver waits for holds the request from + * its start until it ends, however long it runs; the request is dropped 16 ms + * after the last job ended. + */ + +#include +#include +#include +#include +#include +#include + +#define G18_DEMAND_IDLE_MS 16 + +struct g18_demand { + struct apple_clpc_gpu *gpu; + struct delayed_work idle; + /* Orders the request against the idle work, which drops it only with no job. */ + struct mutex lock; + unsigned int jobs; +}; + +int g18_demand_get(struct device *dev, struct g18_demand **out); +void g18_demand_begin(struct g18_demand *demand); +void g18_demand_end(struct g18_demand *demand); +void g18_demand_put(struct g18_demand *demand); + +static void g18_demand_idle(struct work_struct *work) +{ + struct g18_demand *demand = + container_of(to_delayed_work(work), struct g18_demand, idle); + + mutex_lock(&demand->lock); + if (!demand->jobs) + apple_clpc_gpu_set_active(demand->gpu, false); + mutex_unlock(&demand->lock); +} + +/* + * *out is NULL without an apple,clpc provider, or when the provider refuses the + * GPU input: the GPU then runs without the floor. -EPROBE_DEFER while the + * provider has not probed yet, and -ENOMEM, are returned for the probe to act + * on, before it touches the GPU. + */ +int g18_demand_get(struct device *dev, struct g18_demand **out) +{ + struct apple_clpc_gpu *gpu = NULL; + struct g18_demand *demand; + int ret = apple_clpc_gpu_get(dev, &gpu); + + *out = NULL; + if (ret == -EPROBE_DEFER || ret == -ENOMEM) + return ret; + if (ret || !gpu) { + if (ret) + dev_warn(dev, "G18: no CLPC GPU input: %d\n", ret); + return 0; + } + demand = kzalloc(sizeof(*demand), GFP_KERNEL); + if (!demand) { + apple_clpc_gpu_put(gpu); + return -ENOMEM; + } + demand->gpu = gpu; + INIT_DELAYED_WORK(&demand->idle, g18_demand_idle); + mutex_init(&demand->lock); + *out = demand; + return 0; +} + +/* A job started: hold the floor until it ends. */ +void g18_demand_begin(struct g18_demand *demand) +{ + if (!demand) + return; + mutex_lock(&demand->lock); + demand->jobs++; + apple_clpc_gpu_set_active(demand->gpu, true); + mutex_unlock(&demand->lock); +} + +/* A job ended: drop the floor 16 ms after the last one, unless another starts. */ +void g18_demand_end(struct g18_demand *demand) +{ + if (!demand) + return; + mutex_lock(&demand->lock); + if (!WARN_ON_ONCE(!demand->jobs)) + demand->jobs--; + mutex_unlock(&demand->lock); + mod_delayed_work(system_wq, &demand->idle, + msecs_to_jiffies(G18_DEMAND_IDLE_MS)); +} + +/* With no job left: stop the idle work, drop the request and the CLPC reference. */ +void g18_demand_put(struct g18_demand *demand) +{ + if (!demand) + return; + cancel_delayed_work_sync(&demand->idle); + apple_clpc_gpu_put(demand->gpu); + mutex_destroy(&demand->lock); + kfree(demand); +} diff --git a/drivers/gpu/drm/asahi/g18/demand.rs b/drivers/gpu/drm/asahi/g18/demand.rs new file mode 100644 index 00000000000000..a8e1ab0c75c52e --- /dev/null +++ b/drivers/gpu/drm/asahi/g18/demand.rs @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The CLPC's GPU input (`demand.c`): the memory controller and fabric floor +//! while the GPU has work. + +use core::ffi::c_void; +use core::ptr::NonNull; +use kernel::{error::to_result, prelude::*, sync::Arc}; + +extern "C" { + // `struct device *`: the bindings type has no fields Rust can see. + fn g18_demand_get(dev: *mut c_void, out: *mut *mut c_void) -> i32; + fn g18_demand_begin(demand: *mut c_void); + fn g18_demand_end(demand: *mut c_void); + fn g18_demand_put(demand: *mut c_void); +} + +/// The allocation from `g18_demand_get`, released when the last reference +/// (the session's or a running job's) goes. +struct Handle(NonNull); + +// SAFETY: the C side serializes on its own lock and queues a work item. +unsafe impl Send for Handle {} +// SAFETY: as above. +unsafe impl Sync for Handle {} + +impl Drop for Handle { + fn drop(&mut self) { + // SAFETY: a live allocation from `g18_demand_get`, released once, + // after every guard holding it has ended its job. + unsafe { g18_demand_put(self.0.as_ptr()) } + } +} + +/// Absent without an `apple,clpc` provider. +pub(crate) struct G18Demand(Option>); + +impl G18Demand { + /// `dev` is the GPU platform device, whose node may name `apple,clpc`. + /// EPROBE_DEFER while the provider has not probed yet: call it before + /// the probe touches the GPU. + pub(crate) fn new( + dev: &kernel::device::Device, + ) -> Result { + let mut demand = core::ptr::null_mut(); + // SAFETY: a live device; `demand` is written before the call returns. + to_result(unsafe { g18_demand_get(dev.as_raw().cast(), &mut demand) })?; + Ok(Self(match NonNull::new(demand) { + Some(demand) => Some(Arc::new(Handle(demand), GFP_KERNEL)?), + None => None, + })) + } + + /// A job is running: the floor is held until the returned guard is + /// dropped, and released 16 ms after the last job ended. The guard + /// holds its own reference, so it may outlive this value. + pub(crate) fn job(&self) -> G18DemandJob { + if let Some(handle) = &self.0 { + // SAFETY: a live allocation, held by `self`. + unsafe { g18_demand_begin(handle.0.as_ptr()) } + } + G18DemandJob(self.0.clone()) + } +} + +/// One job's hold on the floor, from [`G18Demand::job`] until dropped. +pub(crate) struct G18DemandJob(Option>); + +impl Drop for G18DemandJob { + fn drop(&mut self) { + if let Some(handle) = &self.0 { + // SAFETY: a live allocation, held by this guard's reference. + unsafe { g18_demand_end(handle.0.as_ptr()) } + } + } +} diff --git a/drivers/gpu/drm/asahi/g18/drm.rs b/drivers/gpu/drm/asahi/g18/drm.rs index e011c75f6ba2bd..102465bb006f42 100644 --- a/drivers/gpu/drm/asahi/g18/drm.rs +++ b/drivers/gpu/drm/asahi/g18/drm.rs @@ -24,7 +24,9 @@ use core::ops::Range; use core::sync::atomic::{AtomicI32, Ordering}; use kernel::{bindings, macros::vtable, new_condvar, new_mutex, prelude::*, static_lock_class, dma_fence::{Fence, FenceContexts, FenceObject, FenceOps, RawDmaFence, UserFence}, - sync::{Arc, CondVar, Mutex, SpinLock}, uapi, workqueue, xarray}; + sync::{Arc, CondVar, Mutex, SpinLock}, time::{Delta, Instant, Monotonic}, uapi, workqueue, + xarray}; +use crate::debug::{debug_enabled, DebugFlags}; use crate::{alloc, driver::AsahiRegData, file, g18::uapi::command as g17_uapi, g18::hw, g18::uapi::application::{self as g18_application, G18ApplicationRefusal, G18RenderJobSink, G18RenderRetirement}, gem, gpu, g18::fw::vm_layout as m5_vm, mmu, queue, stats, stats_raw, timestamp}; @@ -106,14 +108,14 @@ pub(crate) trait G18DrmRuntime: G18RenderJobSink { /// Adapter options fixed at registration. #[derive(Debug, Copy, Clone, Default)] pub(crate) struct G18DrmConfig { - /// Admit compute commands (module parameter `g18_admit_compute`, default 0). + /// Admit compute commands (module parameter `g18_admit_compute`, default 1). pub(crate) admit_compute: bool, /// Admit exactly the native 4x MSAA render set (module parameter - /// `g18_admit_msaa4`, default 0; msaa163). Off refuses every + /// `g18_admit_msaa4`, default 1; msaa163). Off refuses every /// multisampled render as before. pub(crate) admit_msaa4: bool, /// Admit renders carrying `DRM_ASAHI_RENDER_G18_RESOURCES` (module - /// parameter `g18_admit_graphics_scratch`, default 0). Off leaves the + /// parameter `g18_admit_graphics_scratch`, default 1). Off leaves the /// feature unadvertised and refuses the flag, so Mesa keeps refusing /// draws whose programs need a thread-private frame. pub(crate) admit_graphics_scratch: bool, @@ -154,6 +156,14 @@ impl G18DrmGpu { } } +impl Drop for G18DrmGpu { + /// Every file has let go of the device: finish the accepted jobs and + /// destroy the worker queue before the module can be unloaded. + fn drop(&mut self) { + self.jobs.shut_down(); + } +} + // Module 1134 reached G18 through its `DrmGpu` trait (drm_gpu.rs) and // computed GET_PARAMS in file.rs from `DrmGpu::params`; here the same facts // fill `drm_asahi_params_global` through `gpu::Gpu::get_params`. The shared @@ -187,7 +197,7 @@ impl gpu::Gpu for G18DrmGpu { params.max_frequency_khz = 0; params.usc_generation = G18_USC_GENERATION; params.gpu_hal_generation = G18_UAPI_HAL_GENERATION; - params.max_commands_per_submission = 1; + params.max_commands_per_submission = file::MAX_COMMANDS_PER_SUBMISSION; if self.config.admit_graphics_scratch { params.features |= uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_G18_GRAPHICS_SCRATCH as u64; } @@ -239,7 +249,7 @@ impl gpu::Gpu for G18DrmGpu { /// at screen creation and enables timer queries only if this works. G18 /// publishes timestamps from the CPU after retirement, so the buffer needs /// no firmware mapping. - fn map_timestamp_buffer(&self, bo: gem::ObjectRef, range: Range) + fn map_timestamp_buffer(&self, bo: gem::ObjectRef, range: Range, _window: crate::timestamp::WindowPermit) -> Result { if self.is_crashed() { return Err(ENODEV); } if range.is_empty() { return Err(EINVAL); } @@ -276,7 +286,7 @@ impl FenceOps for G18SubmissionFence { /// Dropped unaccepted, it signals the fence with `result` and installs it. struct OutputPublication { fence: Option>, - syncs: KVec, + syncs: KVVec, input_count: usize, result: Result, } @@ -340,6 +350,22 @@ impl Drop for JobFence { /// Accepted jobs a queue may have waiting or running; a further submit /// waits for the oldest. const QUEUE_DEPTH: usize = 32; +/// Jobs waiting to run on the device, over all its queues and files, counting +/// the submits that hold a [`Room`]; a further submit waits for room before +/// it publishes anything. A file may open any number of queues, and each may +/// hold [`QUEUE_DEPTH`]. A waiting job holds its translated commands, its +/// input fences and its VM job guard, which keeps the mappings it uses +/// pinned, so this bounds the kernel memory and the mappings that work not +/// yet run can hold. 256 is eight queues at [`QUEUE_DEPTH`]. +/// +/// The bound is device-wide, so a file that fills it makes another client's +/// submit wait in the ioctl. That is intended: one worker runs the jobs in +/// the order they were accepted, so that client's job would run after those +/// 256 anyway, and the cap only moves its wait from the output fence into +/// the ioctl. A per-file share would change who waits, not when work runs. +const DEVICE_DEPTH: usize = 256; +/// The shortest time between two reports of a failed asynchronous job. +const FAILURE_REPORT_INTERVAL: Delta = Delta::from_millis(1000); /// One accepted submission. Dropping it signals its output fence. struct G18Job { @@ -362,7 +388,7 @@ struct G18Job { } impl G18Job { - fn run(mut job: KBox) { + fn run(mut job: KBox, jobs: &JobQueue) { let result = job.execute(); // Release the mappings before the fence signals, as a synchronous // submit did. @@ -373,9 +399,14 @@ impl G18Job { // The ioctl returned long ago and cannot report this; the output // fence carries the error and the queue's next submit returns it. (None, Err(error)) => { - let len = job.comm.iter().position(|&c| c == 0).unwrap_or(job.comm.len()); - pr_warn!("G18 job failed: submission {} pid {} ({}): {:?}\n", job.submission, - job.pid, kernel::str::BStr::from_bytes(&job.comm[..len]), error); + if let Some(unreported) = jobs.failure_report() { + if unreported > 0 { + pr_warn!("G18: {} more failed jobs not reported\n", unreported); + } + let len = job.comm.iter().position(|&c| c == 0).unwrap_or(job.comm.len()); + pr_warn!("G18 job failed: submission {} pid {} ({}): {:?}\n", job.submission, + job.pid, kernel::str::BStr::from_bytes(&job.comm[..len]), error); + } let _ = job.queue_failed.compare_exchange(0, error.to_errno(), Ordering::AcqRel, Ordering::Acquire); } @@ -442,27 +473,59 @@ impl G18Job { struct JobQueue { #[pin] state: Mutex, - /// Notified whenever `completed` advances. + /// Notified whenever `completed` advances, or a [`Room`] is given back. #[pin] retired: CondVar, + /// The worker, queued on `workers` to drain `pending`. It is part of the + /// queue, so starting it allocates nothing under the state lock, which + /// the fence-signalling worker takes. + #[pin] + work: workqueue::Work, +} + +kernel::impl_has_work! { + impl HasWork for JobQueue { self.work } +} + +impl workqueue::WorkItem for JobQueue { + type Pointer = Arc; + + fn run(this: Arc) { + this.drain(); + } } struct JobQueueState { + /// Allocated for [`DEVICE_DEPTH`] jobs up front: nothing is allocated + /// under the state lock. pending: KVec>, /// A worker is draining `pending`. running: bool, /// Sequence numbers of the last accepted and the last finished job. submitted: u64, completed: u64, + /// Submits holding a [`Room`]: they may each add one job. + reserved: usize, + /// The device's own worker queue; taken, and so drained, when the device + /// goes away. Without it no job is accepted. Its jobs signal fences that + /// memory reclaim can wait for, so it has a rescuer (WQ_MEM_RECLAIM). + workers: Option, + /// When the last failed job was reported, and how many have not been since. + reported: Option>, + unreported: u32, } impl JobQueue { fn new() -> Result> { + let workers = workqueue::OwnedQueue::new_unbound_reclaim(c"aurora_g18_jobs", false)?; + let pending = KVec::with_capacity(DEVICE_DEPTH, GFP_KERNEL)?; Arc::pin_init(pin_init!(Self { state <- new_mutex!(JobQueueState { - pending: KVec::new(), running: false, submitted: 0, completed: 0, + pending, running: false, submitted: 0, completed: 0, + reserved: 0, workers: Some(workers), reported: None, unreported: 0, }, "G18 jobs"), retired <- new_condvar!("G18 job retired"), + work <- kernel::new_work!("G18 job worker"), }), GFP_KERNEL) } @@ -471,21 +534,24 @@ impl JobQueue { /// cannot be queued. The fence is installed under the lock, once the /// job has its place: a submission that finds it in a syncobj is /// accepted later and so runs after the job that signals it. - fn push(self: &Arc, publication: OutputPublication, + fn push(self: &Arc, room: Room, publication: OutputPublication, job: impl FnOnce(JobFence) -> KBox) - -> core::result::Result { + -> core::result::Result { + // On a refusal `room`, a parameter, is dropped after `state` and gives + // its slot back then; an accepted job takes it over under the lock. let mut state = self.state.lock(); - if state.pending.reserve(1, GFP_KERNEL).is_err() { return Err(publication); } + let Some(workers) = state.workers.as_ref() else { return Err((publication, ENODEV)) }; + // The room keeps pending.len() below DEVICE_DEPTH, the capacity. + if state.pending.len() >= state.pending.capacity() { return Err((publication, ENOMEM)); } if !state.running { - let this = self.clone(); - if workqueue::system_unbound().try_spawn(GFP_KERNEL, move || this.drain()).is_err() { - return Err(publication); - } + // Already queued means a drain is about to run anyway. + let _ = workers.enqueue(self.clone()); state.running = true; } let job = job(publication.accept()); - // Cannot fail: room was reserved above. + // Cannot fail: the capacity was checked above, under the same lock. let _ = state.pending.push_within_capacity(job); + room.consume(&mut state); state.submitted += 1; Ok(state.submitted) } @@ -499,12 +565,48 @@ impl JobQueue { Err(_) => { state.running = false; return; } } }; - G18Job::run(job); + G18Job::run(job, self); self.state.lock().completed += 1; self.retired.notify_all(); } } + /// Wait, interruptibly, until the jobs waiting to run and the [`Room`]s + /// taken are fewer than [`DEVICE_DEPTH`], then take one. Called before + /// anything is published, so a signal restarts the ioctl. + fn wait_room(self: &Arc) -> Result { + let mut state = self.state.lock(); + while state.pending.len() + state.reserved >= DEVICE_DEPTH { + if self.retired.wait_interruptible(&mut state) { return Err(ERESTARTSYS); } + } + state.reserved += 1; + Ok(Room(Some(self.clone()))) + } + + /// Whether to report a failed job now, with how many were not reported + /// since the last report: at most one report per [`FAILURE_REPORT_INTERVAL`]. + /// With `VerboseFaults` set every failure is reported, as GPU faults are. + fn failure_report(&self) -> Option { + let mut state = self.state.lock(); + let recent = state.reported.as_ref() + .is_some_and(|last| last.elapsed() < FAILURE_REPORT_INTERVAL); + if recent && !debug_enabled(DebugFlags::VerboseFaults) { + state.unreported = state.unreported.saturating_add(1); + return None; + } + state.reported = Some(Instant::now()); + Some(core::mem::take(&mut state.unreported)) + } + + /// Stop accepting jobs and wait for the worker to finish the accepted + /// ones, so that no work item of this module runs after it goes away. + fn shut_down(&self) { + let workers = self.state.lock().workers.take(); + // Dropping the queue destroys it, which drains it; the worker takes the + // state lock, so it must not be held here. + drop(workers); + } + /// Wait until job `seq` has finished and its fence has signalled. fn wait(&self, seq: u64, interruptible: bool) -> Result { let mut state = self.state.lock(); @@ -519,6 +621,28 @@ impl JobQueue { } } +/// A slot taken by [`JobQueue::wait_room`]: its submit may add one job. +/// [`JobQueue::push`] turns it into that job; dropping it gives the slot back. +struct Room(Option>); + +impl Room { + /// The job is in `pending` now and holds the slot itself: no waiter can + /// get in, so none is woken. + fn consume(mut self, state: &mut JobQueueState) { + state.reserved -= 1; + self.0 = None; + } +} + +impl Drop for Room { + fn drop(&mut self) { + if let Some(jobs) = self.0.take() { + jobs.state.lock().reserved -= 1; + jobs.retired.notify_all(); + } + } +} + struct UserAddressSpace<'a> { vm: &'a mmu::Vm } impl g17_uapi::GpuAddressSpace for UserAddressSpace<'_> { fn covers(&self, address: u64, size: u64, access: g17_uapi::GpuAccess) -> bool { @@ -583,7 +707,7 @@ impl queue::Queue for G18Queue { /// userspace nothing to wait on (Mesa's G18G split compute prepass reads /// GPU results after such submissions). fn submit(&mut self, _reg_data: &AsahiRegData<'_>, submission_id: u64, - syncs: KVec, + syncs: KVVec, in_sync_count: usize, cmdbuf_raw: &[u8], objects: Pin<&xarray::XArray>>) -> Result { if in_sync_count > syncs.len() { return Err(EINVAL); } @@ -593,6 +717,9 @@ impl queue::Queue for G18Queue { let fence: UserFence = self.fences.new_fence(0, G18SubmissionFence)?.into(); wait_foreign_inputs(&fence, &syncs[..in_sync_count])?; + // Taken after the foreign inputs, so that a submit waiting for + // another driver's fence holds no slot meanwhile. + let room = self.jobs.wait_room()?; let synchronous = !self.asynchronous || syncs.len() == in_sync_count; let mut publication = OutputPublication { fence: Some(fence), syncs, input_count: in_sync_count, result: Err(ECANCELED), @@ -611,6 +738,7 @@ impl queue::Queue for G18Queue { let (slot, result, inputs, vm_job, commands) = match accepted { Ok(accepted) => accepted, Err(error) => { + drop(room); // The runtime records and quarantines a failed published VM // before this output fence is installed/signalled by the // publication guard, after the queue's earlier fences. @@ -629,13 +757,13 @@ impl queue::Queue for G18Queue { fence, queue_failed: self.failed.clone(), submission: submission_id, pid: task.pid(), comm, }); - let seq = match self.jobs.push(publication, job) { + let seq = match self.jobs.push(room, publication, job) { Ok(seq) => seq, - Err(mut publication) => { + Err((mut publication, error)) => { // As above: the fence signals after the queue's earlier ones. - publication.result = Err(ENOMEM); + publication.result = Err(error); self.jobs.wait(self.last, false)?; - return Err(ENOMEM); + return Err(error); } }; self.recent[self.next] = seq; diff --git a/drivers/gpu/drm/asahi/g18/fw/graphics_payload.rs b/drivers/gpu/drm/asahi/g18/fw/graphics_payload.rs index ef70ea09af81a9..56f90cc6f860d3 100644 --- a/drivers/gpu/drm/asahi/g18/fw/graphics_payload.rs +++ b/drivers/gpu/drm/asahi/g18/fw/graphics_payload.rs @@ -116,17 +116,6 @@ fn fnv64_from(basis: u64, bytes: &[u8]) -> u64 { bytes.iter().fold(basis, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3)) } -/// [`fnv64`] of bytes in uncached (write-combined) memory. They are read in -/// wide copies: a byte load from such memory is a bus transaction each. -pub(crate) fn fnv64_uncached(bytes: &[u8]) -> u64 { - let mut chunk = [0u8; 256]; - bytes.chunks(chunk.len()).fold(0xcbf2_9ce4_8422_2325, |h, part| { - let copy = &mut chunk[..part.len()]; - copy.copy_from_slice(part); - fnv64_from(h, copy) - }) -} - impl<'a> GraphicsPayload<'a> { pub(crate) fn parse(bytes: &'a [u8]) -> Result { if bytes.len() < HEADER_BYTES { return Err(PayloadError::Length); } diff --git a/drivers/gpu/drm/asahi/g18/fw/render_assembly.rs b/drivers/gpu/drm/asahi/g18/fw/render_assembly.rs index 86ad9028ad3692..4385203fb81961 100644 --- a/drivers/gpu/drm/asahi/g18/fw/render_assembly.rs +++ b/drivers/gpu/drm/asahi/g18/fw/render_assembly.rs @@ -106,7 +106,13 @@ pub(crate) enum AssemblyError { Registers(regs::G18RenderError), Command(cmd::G1 impl From for AssemblyError { fn from(e: regs::G18RenderError) -> Self { Self::Registers(e) } } impl From for AssemblyError { fn from(e: cmd::G18RenderCommandError) -> Self { Self::Command(e) } } -pub(crate) struct EncodedJob { pub rce: [[M5SksmRce; 4]; 2], pub digests: [u64; 7] } +/// FNV digests of a TA and a 3D command and of their register blocks, in +/// [`DIGEST_NAMES`] order. +pub(crate) fn digests(ta: &[u8], fragment: &[u8]) -> [u64; 7] { + [fnv64(ta), fnv64(fragment), fnv64(&ta[0x60..0x60 + 91 * 12]), + fnv64(&fragment[0xa0..0xa0 + 92 * 12]), fnv64(&fragment[0x7c0..0x7c0 + 17 * 12]), + fnv64(&fragment[0xee0..0xee0 + 24 * 12]), fnv64(&fragment[0x1600..0x1600 + 12 * 12])] +} // Only integer fields: zero is a valid initial representation. Kept on the // heap by the kernel caller, including across the register-builder calls. @@ -122,7 +128,7 @@ pub(crate) fn encode( ta: &mut [u8; cmd::G18_TA_COMMAND_BYTES], fragment: &mut [u8; cmd::G18_3D_COMMAND_BYTES], p: &G17pRenderParameters, controls: ®s::G18RenderControls, inputs: &cmd::G18RenderCommandInputs, -) -> Result { +) -> Result<[[M5SksmRce; 4]; 2], AssemblyError> { let mut workspace = Workspace { ta: regs::G18Program::empty(), fragment: regs::G18FragmentPrograms { main: regs::G18Program::empty(), store: regs::G18Program::empty(), resume: regs::G18Program::empty(), load: regs::G18Program::empty() } }; @@ -134,7 +140,7 @@ pub(crate) fn encode_into( ta: &mut [u8; cmd::G18_TA_COMMAND_BYTES], fragment: &mut [u8; cmd::G18_3D_COMMAND_BYTES], p: &G17pRenderParameters, controls: ®s::G18RenderControls, inputs: &cmd::G18RenderCommandInputs, workspace: &mut Workspace, -) -> Result { +) -> Result<[[M5SksmRce; 4]; 2], AssemblyError> { ta.fill(0); fragment.fill(0); regs::build_g18_ta_program_into(&mut workspace.ta, p, controls)?; regs::build_g18_fragment_programs_into(&mut workspace.fragment, p, controls)?; @@ -147,10 +153,7 @@ pub(crate) fn encode_into( va::GRAPHICS_JOB_LOW + FRAGMENT_OFFSET as u64, inputs, &programs)?; // The linked 3D tuple in inputs is finalized before encoding TA. let ta_rce = cmd::encode_g18_ta_command(ta, va::GRAPHICS_JOB_LOW, inputs, &view(&t))?; - let digests = [fnv64(ta), fnv64(fragment), fnv64(&ta[0x60..0x60 + 91 * 12]), - fnv64(&fragment[0xa0..0xa0 + 92 * 12]), fnv64(&fragment[0x7c0..0x7c0 + 17 * 12]), - fnv64(&fragment[0xee0..0xee0 + 24 * 12]), fnv64(&fragment[0x1600..0x1600 + 12 * 12])]; - Ok(EncodedJob { rce: [ta_rce, fr_rce], digests }) + Ok([ta_rce, fr_rce]) } /// Runtime variants are deliberately a closed set. H2 repeats three frames; diff --git a/drivers/gpu/drm/asahi/g18/initdata/application_compute.rs b/drivers/gpu/drm/asahi/g18/initdata/application_compute.rs index 549324f6884671..28ca57d29cbd8f 100644 --- a/drivers/gpu/drm/asahi/g18/initdata/application_compute.rs +++ b/drivers/gpu/drm/asahi/g18/initdata/application_compute.rs @@ -455,6 +455,18 @@ impl G18FirmwareMemory { Ok((prepared, job.binding, generation, knobs)) } + /// Whether the compute owner is as the last retirement left it, with no + /// process, command or context published: a failed preparation that + /// leaves this true changed nothing the firmware uses. Before the owner + /// exists, its scheduler record must not be armed yet. + pub(crate) fn application_compute_unpublished(&self) -> bool { + self.compute.unpublished_idle() && match self.application_compute.as_ref() { + Some(job) => job.retired && job.guard.is_none() && job.aliases.is_empty() + && job.previous_pool.is_none() && job.previous_binding.is_none(), + None => self.scheduler.binding(0).is_err(), + } + } + /// The binding the firmware must still own before the next tag15. pub(crate) fn application_compute_previous_binding(&self) -> Result<(G18UmaPoolBinding, u32)> { let job = self.application_compute.as_ref().ok_or(EIO)?; diff --git a/drivers/gpu/drm/asahi/g18/mod.rs b/drivers/gpu/drm/asahi/g18/mod.rs index 23e6f2a76a62ce..15fc66d273e02f 100644 --- a/drivers/gpu/drm/asahi/g18/mod.rs +++ b/drivers/gpu/drm/asahi/g18/mod.rs @@ -12,6 +12,7 @@ pub(crate) mod address_map; pub(crate) mod boot; pub(crate) mod buffer; pub(crate) mod compat; +pub(crate) mod demand; #[allow(dead_code)] pub(crate) mod drm; pub(crate) mod fixture; diff --git a/drivers/gpu/drm/asahi/g18/probe.rs b/drivers/gpu/drm/asahi/g18/probe.rs index 26534683e1ed52..b91f5237c18843 100644 --- a/drivers/gpu/drm/asahi/g18/probe.rs +++ b/drivers/gpu/drm/asahi/g18/probe.rs @@ -133,6 +133,8 @@ pub(crate) struct T8152Probe { /// The DRM device, not yet registered. The live-boot module allocates /// its kernel objects on it; the shared probe registers it at stage 10. pub(crate) drm: ARef, + /// The CLPC's GPU input, taken before the probe touched the GPU. + pub(crate) demand: crate::g18::demand::G18Demand, } /// Loader receipts the G18G firmware stages require. The loader writes one @@ -286,6 +288,10 @@ fn prepare_t8152_device( let identity = identity::decode_gpu_identity(soc.hw_family, soc.hw_variant, soc.num_dies as u8) .ok_or(EINVAL)?; + // Before any GPU access: a CLPC that has not probed yet defers this probe + // here, while it can still be repeated, instead of the GPU running + // without the floor for the whole boot. + let demand = crate::g18::demand::G18Demand::new(pdev.as_ref())?; if soc.chip_id != 0x8152 || identity.gpu_gen != hw::GpuGen::G18 || identity.gpu_variant != identity::GpuVariant::G @@ -385,6 +391,7 @@ fn prepare_t8152_device( registers, observed, drm, + demand, }) } diff --git a/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs b/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs index 6420db72320253..5efb185812dfd4 100644 --- a/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs +++ b/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs @@ -242,6 +242,29 @@ impl G18ParameterBuffer { Ok(aliases) } + /// Storage the previous VM's renders wrote (every block, grown ones + /// included, the scene scratch and the discard page) may still hold its + /// data; clear it before another VM maps it. Construction leaves it zero. + /// The page list, block table, scene records, metrics and ring cursors + /// are kept: they name the PB's own objects and the PM owns their + /// progress. The caller proved the render retired and dropped the + /// previous VM's aliases. + pub(crate) fn clear_client_data(&mut self) -> Result { + let clear = |object: &mut MappedObject| { + object.with_bytes_mut(|bytes| { + bytes.fill(0); + Ok(()) + }) + }; + for block in self.blocks.iter_mut() { + clear(block)?; + } + clear(&mut self.scene_scratch)?; + clear(&mut self.discard)?; + fence(Ordering::SeqCst); + Ok(()) + } + /// Blocks backed so far: the initial ones plus every growth. fn backed_blocks(&self) -> Result { let bytes: usize = self.blocks.iter().map(|block| block.logical_size).sum(); diff --git a/drivers/gpu/drm/asahi/g18/runtime/graphics_job.rs b/drivers/gpu/drm/asahi/g18/runtime/graphics_job.rs index d897ef52749dea..9f846c17b6b261 100644 --- a/drivers/gpu/drm/asahi/g18/runtime/graphics_job.rs +++ b/drivers/gpu/drm/asahi/g18/runtime/graphics_job.rs @@ -8,10 +8,28 @@ use crate::{g18::buffer::object::MappedObject, g18::runtime::graphics_memory::G1 G18ParameterBuffer, G18PbAddresses, G18PbPolicy, G18QueuedPass, G18PbReadback}}; use crate::{driver::AsahiDrmDevice, g18::fw::render_params::G17pRenderParameters, g18::address_map as va, g18::fw::render as regs, g18::fw::render_command as cmd, - g18::fw::render_assembly::{self as assembly, EncodedJob, RenderVariant}, mmu}; + g18::fw::render_assembly::{self as assembly, RenderVariant}, g18::fw::sksm::M5SksmRce, mmu}; use core::sync::atomic::{fence, Ordering}; use kernel::prelude::*; +/// An encoded render: its RCE records and the cached copy of its TA and 3D +/// commands, as copied to the graph. The copy (`G18_TA_COMMAND_BYTES` + +/// `G18_3D_COMMAND_BYTES`, about 11 KiB) lives as long as the job, so the +/// audits can compare the graph's read-back with it. +pub(crate) struct EncodedJob { pub rce: [[M5SksmRce; 4]; 2], commands: KVec } + +impl EncodedJob { + /// The TA and the 3D command. + pub(crate) fn commands(&self) -> (&[u8], &[u8]) { + self.commands.split_at(cmd::G18_TA_COMMAND_BYTES) + } + /// The [`assembly::digests`] of the commands, for the logs. + pub(crate) fn digests(&self) -> [u64; 7] { + let (ta, fragment) = self.commands(); + assembly::digests(ta, fragment) + } +} + pub(crate) struct G18GraphicsJob { // Payload's context lease retracts before the additional job mappings drop. program: G18GraphicsMemory, @@ -225,15 +243,13 @@ impl G18GraphicsJob { let digest=self.program.terminated_digest(self.parameters.encoder)?; dev_info!(dev.as_ref(), "G18_RENDER_DIGEST name=terminated-vdm-page fnv={:#018x}\n",digest); } - let expected=self.encoded.as_ref().ok_or(EINVAL)?.digests; + let (ta_expected,fr_expected)=self.encoded.as_ref().ok_or(EINVAL)?.commands(); self.graph.with_bytes_mut(|bytes| { let ta=&bytes[..cmd::G18_TA_COMMAND_BYTES]; let fr=&bytes[assembly::FRAGMENT_OFFSET..assembly::FRAGMENT_OFFSET+cmd::G18_3D_COMMAND_BYTES]; - let f=crate::g18::fw::graphics_payload::fnv64; - let actual=[f(ta),f(fr),f(&ta[0x60..0x60+91*12]),f(&fr[0xa0..0xa0+92*12]), - f(&fr[0x7c0..0x7c0+17*12]),f(&fr[0xee0..0xee0+24*12]),f(&fr[0x1600..0x1600+12*12])]; - if actual!=expected {return Err(EIO);} - for (name,digest) in assembly::DIGEST_NAMES.iter().zip(actual) { + if ta!=ta_expected || fr!=fr_expected {return Err(EIO);} + // Equal to the read-back: hash the cached copy, not the write-combined graph. + for (name,digest) in assembly::DIGEST_NAMES.iter().zip(assembly::digests(ta_expected,fr_expected)) { dev_info!(dev.as_ref(), "G18_RENDER_DIGEST name={} fnv={:#018x}\n",name,digest); } Ok(()) @@ -304,11 +320,12 @@ impl G18GraphicsJob { unsafe { core::ptr::write_bytes(workspace.as_mut_ptr(), 0, 1); } let mut workspace = unsafe { workspace.assume_init() }; // Encode in cached memory and copy the commands to the write-combined - // graph at once: the encoder and its digests read what they write. + // graph at once: the encoder reads what it writes. The cached copy is + // kept for the audit's comparison. let mut commands = KVec::from_elem(0u8, cmd::G18_TA_COMMAND_BYTES + cmd::G18_3D_COMMAND_BYTES, GFP_KERNEL)?; let (ta, fragment) = commands.split_at_mut(cmd::G18_TA_COMMAND_BYTES); - let encoded = assembly::encode_into(ta.try_into().map_err(|_| EINVAL)?, + let rce = assembly::encode_into(ta.try_into().map_err(|_| EINVAL)?, fragment.try_into().map_err(|_| EINVAL)?, &self.parameters, &self.controls, inputs, &mut workspace).map_err(|_| EINVAL)?; self.graph.with_bytes_mut(|bytes| { @@ -317,7 +334,7 @@ impl G18GraphicsJob { rest[..cmd::G18_3D_COMMAND_BYTES].copy_from_slice(fragment); Ok(()) })?; - self.encoded = Some(encoded); + self.encoded = Some(EncodedJob { rce, commands }); fence(Ordering::SeqCst); Ok(()) } diff --git a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs index 4d9beac3e8b42e..de571e9c9f67c2 100644 --- a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs +++ b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs @@ -65,6 +65,9 @@ impl ApplicationJob { if let Some(status)=self.job.vm().status(){status.record(EIO);} } pub(crate) fn retired(&mut self) {self.retired=true;self.guard=None;} + /// No frame is committed: the last one retired and none was prepared + /// since, so the firmware holds nothing of this job beyond it. + pub(crate) fn unpublished(&self) -> bool {self.retired && self.guard.is_none()} /// One of the first frames of its client: logged even when job logging /// is sparse, so every isolated client leaves a kick/retirement pair. pub(crate) fn traced(&self) -> bool {self.client_frames<=3} @@ -89,8 +92,13 @@ impl ApplicationJob { if remap { self.job.program.rebind_retired(&self.storage)?; self.user_aliases.clear();self.pool_aliases.clear(); + // The last frame retired (checked above) and the previous VM's + // views are gone: clear what its renders left before this VM + // maps the PB. The pool scratch is cleared as it is aliased. + if new_client && self.generation!=0 {self.job.parameter_buffer.clear_client_data()?;} } - if self.generation==0 { + // Once: a first frame refused after this keeps the alias. + if self.generation==0 && self.job.aliases.is_empty() { let alias=self.job.graph.map_alias_at(uat.kernel_lower_vm(),va::GRAPHICS_JOB_LOW, mmu::PROT_GPU_SHARED_RW)?; self.job.aliases.push(alias,GFP_KERNEL)?; @@ -110,16 +118,19 @@ impl ApplicationJob { } } if remap { + // The job context only reads the commands' register lists here + // (the RCE addresses encode_into places at GRAPHICS_JOB_LOW); + // firmware uses GRAPHICS_JOB_HIGH. The client view is read-only, + // as g17 maps M5 command storage, so the client's own GPU work + // cannot rewrite commands after the kernel encoded and audited them. self.user_aliases.push(self.job.graph.map_alias_at(vm,va::GRAPHICS_JOB_LOW, - mmu::PROT_GPU_SHARED_RW)?,GFP_KERNEL)?; + mmu::PROT_GPU_SHARED_RO)?,GFP_KERNEL)?; let aliases=self.job.parameter_buffer.application_aliases(vm)?; for alias in aliases {self.user_aliases.push(alias,GFP_KERNEL)?;} } // Retract even an unchanged root before publish_h1's fresh lease // publication. Retain the mappings when the actual VM is unchanged. self.job.program.rebind_retired(vm)?; - self.guard=Some(guard);self.generation=frame.generation;self.retired=false; - self.client_frames=if new_client {1} else {self.client_frames.saturating_add(1)}; if remap { crate::g18_kick_info!(dev.as_ref(),"G18_APP_VM frame={} vm={} context={} target={}x{} aliases={}\n", frame.generation,vm.id(),self.job.context_id(),render.target.width,render.target.height,self.user_aliases.len()); @@ -144,6 +155,10 @@ impl ApplicationJob { self.job.signals.with_bytes_mut(|out| {out[0xc000..0xc020].fill(0);Ok(())})?; self.job.encoded=None; self.encode_application(dev,frame)?; + // Commit the frame only now: until here an error leaves the job + // retired, and the next prepare() rebuilds whatever this one changed. + self.guard=Some(guard);self.generation=frame.generation;self.retired=false; + self.client_frames=if new_client {1} else {self.client_frames.saturating_add(1)}; Ok(()) } @@ -220,13 +235,18 @@ impl ApplicationJob { pages+=uat.kernel_vm().translate_pages(address,bytes)?.len(); } } - let expected=self.job.encoded.as_ref().ok_or(EINVAL)?.digests; - self.job.graph.with_bytes_mut(|out| { - if crate::g18::fw::graphics_payload::fnv64_uncached(&out[..cmd::G18_TA_COMMAND_BYTES])!=expected[0] - || crate::g18::fw::graphics_payload::fnv64_uncached(&out[0x4000..0x4000+cmd::G18_3D_COMMAND_BYTES])!=expected[1] {return Err(EIO);}Ok(()) + // Compared byte for byte with the encoder's cached copy, which reads + // the write-combined graph in wide loads; hashing both every frame + // cost about 100 us between two jobs. + let job=&mut *self.job; + let encoded=job.encoded.as_ref().ok_or(EINVAL)?; + let (ta,fragment)=encoded.commands(); + job.graph.with_bytes_mut(|out| { + if out[..cmd::G18_TA_COMMAND_BYTES]!=*ta + || out[assembly::FRAGMENT_OFFSET..assembly::FRAGMENT_OFFSET+cmd::G18_3D_COMMAND_BYTES]!=*fragment {return Err(EIO);}Ok(()) })?; if frame.generation<=3 { - for (name,digest) in assembly::DIGEST_NAMES.iter().zip(expected) { + for (name,digest) in assembly::DIGEST_NAMES.iter().zip(encoded.digests()) { dev_info!(dev.as_ref(),"G18_APP_DIGEST frame={} name={} fnv={:#018x}\n",frame.generation,name,digest); } dev_info!(dev.as_ref(),"G18_APP_AUDIT frame={} pb=resident uma=match translations={} previous_stamp={:#x}\n",frame.generation,pages,frame.previous_stamp()); diff --git a/drivers/gpu/drm/asahi/g18/sync_input.c b/drivers/gpu/drm/asahi/g18/sync_input.c index f443ff776f11d5..53d50bae534db1 100644 --- a/drivers/gpu/drm/asahi/g18/sync_input.c +++ b/drivers/gpu/drm/asahi/g18/sync_input.c @@ -37,7 +37,11 @@ int asahi_g18_wait_foreign_fences(struct dma_fence *head, * too, or 0. A container does not carry its fences' errors: a * dma_fence_chain (a timeline point) never copies them, and a * dma_fence_array whose signalling was never enabled clears its pending - * error when it is found signalled. So each fence is checked itself. + * error when it is found signalled. So each fence the walk reaches is + * checked itself. Of a timeline, the walk reaches only the head point: + * dma_fence_chain_walk() unlinks the earlier points that have signalled, and + * a job's inputs have all signalled when it runs, so an error on an earlier + * point is not seen. */ int asahi_g18_fence_error(struct dma_fence *head) { diff --git a/drivers/gpu/drm/asahi/gem.rs b/drivers/gpu/drm/asahi/gem.rs index bad222981a6aef..9eb5bd283ac7fa 100644 --- a/drivers/gpu/drm/asahi/gem.rs +++ b/drivers/gpu/drm/asahi/gem.rs @@ -168,7 +168,7 @@ pub(crate) fn mapped_sg_table<'a>( /// VM-private BOs share their assigned VM's reservation object. Validate this /// before acquiring mapping state; generic GPUVM accepts external shareable BOs. pub(crate) fn validate_vm_binding(gem: &Object, vm: &mmu::Vm) -> Result { - if gem.flags & uapi::drm_asahi_gem_flags_DRM_ASAHI_GEM_VM_PRIVATE != 0 && vm.is_extobj(gem) { + if gem.is_vm_private() && vm.is_extobj(gem) { return Err(EINVAL); } Ok(()) @@ -291,6 +291,13 @@ pub(crate) fn new_kernel_object_wc(dev: &AsahiDrmDevice, size: usize) -> Result< new_kernel_object_mapped(dev, size, true, true) } +/// Create a new kernel-owned GEM object that is not counted as kernel memory: its owner holds a +/// user charge for it ([`memacct::Charge::user`]), and counting both would take its size twice +/// from the device limit. +pub(crate) fn new_kernel_object_user_charged(dev: &AsahiDrmDevice, size: usize) -> Result { + new_kernel_object_mapped(dev, size, false, false) +} + /// Create a new kernel-owned write-combined GEM object that is not counted as kernel memory: /// its owner holds a user charge for it ([`memacct::Charge::user`]), and counting both would /// take its size twice from the device limit. @@ -451,7 +458,14 @@ pub(crate) fn new_user_memory_object( } /// Pages of the calling process pinned as the backing of a user-memory object, and counted in its -/// mm's `pinned_vm` against RLIMIT_MEMLOCK. +/// mm's `pinned_vm`. +/// +/// RLIMIT_MEMLOCK does not bound them. The object is charged to the GPU memory limits instead +/// (`memacct`, by `gem_userptr()`), as an object of GEM_CREATE is: both kinds of backing are +/// unevictable pages that the GPU holds, so the limits bound one as well as the other, and an +/// application can choose either. GPU drivers that pin user memory for buffer objects (i915, +/// etnaviv) do not charge RLIMIT_MEMLOCK either. Its default of 8 MiB would leave +/// VK_EXT_external_memory_host unusable for buffers of ordinary size. pub(crate) struct UserPages { pages: KVVec<*mut kernel::bindings::page>, writable: bool, @@ -481,9 +495,9 @@ impl UserPages { /// be pinned: unmapped, a device or PFN mapping, or a writable pin of a mapping that is not /// writable or whose filesystem tracks writes (`FOLL_LONGTERM` refuses those). In a process /// whose page size is smaller than the native one, a native page is accepted only where the - /// process maps all of it, in order at consecutive addresses (`EFAULT` otherwise). Fails with - /// `ENOMEM` when the pages would take the process past RLIMIT_MEMLOCK without CAP_IPC_LOCK, - /// counting every page pinned this way or by other long-term pinners. + /// process maps all of it, in order at consecutive addresses (`EFAULT` otherwise). The pages + /// are added to the mm's `pinned_vm`, which other long-term pinners compare with + /// RLIMIT_MEMLOCK; this one does not (see [`UserPages`]). /// /// Anonymous pages pinned here stay with this process across fork(): the child gets copies. /// Pages unmapped by the process stay pinned, and backing the object, until it is freed. @@ -498,18 +512,8 @@ impl UserPages { .mm() .map(|mm| ARef::from(&**mm)) .ok_or(EFAULT)?; - let pinned_vm = Self::pinned_vm(&mm); let added = i64::try_from(count).map_err(|_| ENOMEM)?; - let total = pinned_vm - .fetch_add(added, Ordering::AcqRel) - .saturating_add(added); - if !memlock_allows(total, memlock_limit_pages()) { - // SAFETY: `capable()` has no preconditions. - if !unsafe { kernel::bindings::capable(kernel::bindings::CAP_IPC_LOCK as i32) } { - pinned_vm.fetch_sub(added, Ordering::AcqRel); - return Err(ENOMEM); - } - } + Self::pinned_vm(&mm).fetch_add(added, Ordering::AcqRel); // From here on, dropping `this` unpins what it holds and uncounts all `count` pages. let mut this = Self { pages: KVVec::new(), @@ -602,24 +606,6 @@ impl Drop for UserPages { } } -/// RLIMIT_MEMLOCK of the calling process, in pages. -fn memlock_limit_pages() -> u64 { - let task = kernel::current!().as_ptr(); - // SAFETY: The current task and its signal structure are live; the limit is read once, as - // `rlimit()` does. - let bytes = unsafe { - core::ptr::read_volatile(core::ptr::addr_of!( - (*(*task).signal).rlim[kernel::bindings::RLIMIT_MEMLOCK as usize].rlim_cur - )) - }; - (bytes >> kernel::page::PAGE_SHIFT) as u64 -} - -/// Whether `pinned` pages stay within a memlock limit of `limit` pages. -fn memlock_allows(pinned: i64, limit: u64) -> bool { - u64::try_from(pinned).is_ok_and(|pinned| pinned <= limit) -} - #[vtable] impl DriverObject for AsahiObject { type Driver = AsahiDrmDriver; @@ -722,6 +708,12 @@ impl AsahiObject { self.flags & uapi::drm_asahi_gem_flags_DRM_ASAHI_GEM_WRITEBACK != 0 } + /// Whether the backing belongs to the VM that created the object, so that only that VM may + /// map it. + pub(crate) fn is_vm_private(&self) -> bool { + self.flags & uapi::drm_asahi_gem_flags_DRM_ASAHI_GEM_VM_PRIVATE != 0 + } + pub(crate) fn idle_reclaim_candidate(&self) -> bool { !self.kernel && !self.exportable @@ -871,15 +863,6 @@ mod user_memory_tests { }) } - #[test] - fn memlock_limit_policy() { - assert!(memlock_allows(0, 0)); - assert!(memlock_allows(512, 512)); - assert!(!memlock_allows(513, 512)); - assert!(!memlock_allows(-1, 512)); - assert!(memlock_allows(i64::MAX, u64::MAX)); - } - #[test] fn pins_anonymous_memory() -> Result { let addr = map(4 * PAGE_SIZE, PROT_READ | PROT_WRITE)?; diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 4817bed0c20785..fb5359137b6683 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -106,6 +106,17 @@ const EP_DOORBELL: u8 = 0x21; const MSG_INIT: u64 = 0x81 << 48; const INIT_DATA_MASK: u64 = (1 << 44) - 1; +/// The firmware-endpoint message that hands the firmware its root at `address`. +pub(crate) const fn init_message(address: u64) -> u64 { + MSG_INIT | (address & INIT_DATA_MASK) +} + +/// The G14 firmware-27.2 root and the records only it uses. +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +mod v27_2; +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +pub(crate) use v27_2::*; + const RX_WORK_PENDING: u32 = 1 << 0; const RX_WORK_RUNNING: u32 = 1 << 1; @@ -127,6 +138,10 @@ const DOORBELL_DEVCTRL: u64 = 0x11; // Upper kernel half VA address ranges. /// Private (cached) firmware structure VA range base. const IOVA_KERN_PRIV_RANGE: Range = 0xffffffa000000000..0xffffffa600000000; +/// The G14 firmware-27.2 timestamp aperture, inside the private range: the private allocator +/// stays below it in that profile. +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +const IOVA_G14_V27_2_TIMESTAMP_RANGE: Range = 0xffffffa181400000..0xffffffa185400000; /// Private (cached) GPU-RO firmware structure VA range base. const IOVA_KERN_GPU_RO_RANGE: Range = 0xffffffa600000000..0xffffffa800000000; /// Shared (uncached) firmware structure VA range base. @@ -168,6 +183,36 @@ const MAX_FW_ALLOC_GARBAGE_BYTES: usize = 16 * 1024 * 1024; /// within the safe range for kmalloc (on 16K page systems). const MAX_FW_ALLOC_GARBAGE_OBJECTS: usize = 2048; +/// What [`GpuManager::alloc`] does with the freed firmware-private objects it holds. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +enum GarbageAction { + /// Under the collection limits: keep holding them. + Keep, + /// Over a limit: flush the firmware cache, then make them reusable. + Collect, + /// Over a limit, but this manager has no device-control channel to flush the firmware + /// cache with. Reusing the memory could hand the firmware stale cached lines, so it stays + /// held. + Hold, +} + +/// Decide the garbage action from the (count, bytes) held by the private and GPU read-only +/// allocators and whether this manager owns a device-control channel. +fn garbage_action( + private: (usize, usize), + gpu_ro: (usize, usize), + device_control: bool, +) -> GarbageAction { + let over = |(count, bytes): (usize, usize)| { + count > MAX_FW_ALLOC_GARBAGE_OBJECTS || bytes > MAX_FW_ALLOC_GARBAGE_BYTES + }; + match (over(private) || over(gpu_ro), device_control) { + (false, _) => GarbageAction::Keep, + (true, true) => GarbageAction::Collect, + (true, false) => GarbageAction::Hold, + } +} + /// Global allocators used for kernel-half structures. pub(crate) struct KernelAllocators { pub(crate) private: alloc::DefaultAllocator, @@ -178,6 +223,17 @@ pub(crate) struct KernelAllocators { pub(crate) gpu_ro: alloc::DefaultAllocator, } +/// What [`GpuManager::build_graph`] builds the records for. +#[derive(Copy, Clone)] +pub(crate) enum GraphProfile { + /// The manager's own firmware: map the registers, use the whole private range. + Native, + /// The G14 firmware-27.2 root (gpu/v27_2.rs) built on these records: no register + /// mappings, and the private range ends below that firmware's timestamp aperture. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + G14V27_2, +} + /// Receive (GPU->driver) ring buffer channels. #[versions(AGX)] #[pin_data] @@ -270,7 +326,11 @@ pub(crate) struct GpuManager { dyncfg: hw::DynConfig, pub(crate) initdata: fw::types::GpuObject, uat: mmu::Uat, + /// The firmware's timestamp aperture in the kernel VM, where timestamp buffers are bound. + timestamp_range: Range, crashed: AtomicBool, + /// Set once the over-limit firmware-private garbage was reported as held. + garbage_held: AtomicBool, #[pin] alloc: Mutex, io_mappings: KVec, @@ -465,12 +525,19 @@ pub(crate) trait Gpu: Send + Sync { usc_exec_base: u64, usage: Arc, ) -> Result>; - /// Bind a BO range as a firmware- or CPU-written timestamp buffer. + /// Bind a BO range as a firmware- or CPU-written timestamp buffer. With `WindowPermit::Denied` + /// the buffer must not be mapped in the firmware timestamp window (the file's share of it is + /// used up): a backend that can only alias it there fails with ENOSPC, as for a full window. fn map_timestamp_buffer( &self, bo: gem::ObjectRef, range: Range, + window: crate::timestamp::WindowPermit, ) -> Result; + /// Size of the fixed firmware range timestamp buffers are aliased in (0: none). + fn timestamp_window_size(&self) -> u64 { + 0 + } } /// Trait used to abstract the firmware/GPU-dependent variants of the GpuManager. @@ -663,13 +730,42 @@ impl GpuManager::ver { cfg: &'static hw::HwConfig, ) -> Result> { let uat = Self::make_uat(dev, cfg)?; + let mgr = Self::build_graph(dev, res, cfg, uat, GraphProfile::Native)?; + let rtkit = + rtkit::RtKit::::new(dev.as_ref().as_ref(), None, 0, mgr.clone())?; + + *mgr.rtkit.lock() = Some(rtkit); + + { + let mut rxc = mgr.rx_channels.lock(); + rxc.event.set_manager(mgr.clone()); + rxc.stats.set_manager(mgr.clone()); + } + + Ok(mgr) + } + + /// Build the manager and its firmware records without attaching RTKit. + #[inline(never)] + pub(crate) fn build_graph( + dev: &AsahiDrmDevice, + res: ®s::Resources<'_>, + cfg: &'static hw::HwConfig, + uat: KBox, + profile: GraphProfile, + ) -> Result> { let dyncfg = Self::make_dyncfg(dev, res, cfg, &uat)?; + let (private_end, timestamp_range) = match profile { + GraphProfile::Native => (IOVA_KERN_PRIV_RANGE.end, IOVA_KERN_TIMESTAMP_RANGE), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + GraphProfile::G14V27_2 => (IOVA_G14_V27_2_TIMESTAMP_RANGE.start, IOVA_G14_V27_2_TIMESTAMP_RANGE), + }; let mut alloc = KernelAllocators { private: alloc::DefaultAllocator::new( dev, uat.kernel_vm(), - IOVA_KERN_PRIV_RANGE, + IOVA_KERN_PRIV_RANGE.start..private_end, 0x80, mmu::PROT_FW_PRIV_RW, 1024 * 1024, @@ -741,7 +837,8 @@ impl GpuManager::ver { false, )?); - let mut mgr = Self::make_mgr(dev, cfg, dyncfg, uat, alloc, event_manager, initdata)?; + let mut mgr = Self::make_mgr(dev, cfg, dyncfg, uat, alloc, event_manager, initdata, + timestamp_range)?; { let fwctl = mgr.fwctl_channel.lock(); @@ -812,14 +909,16 @@ impl GpuManager::ver { } }); + // The 27.2 root publishes its own register table (gpu/v27_2.rs). + let map_registers = matches!(profile, GraphProfile::Native); for (i, map) in cfg.io_mappings.iter().enumerate() { - if let Some(map) = map.as_ref() { + if let Some(map) = map.as_ref().filter(|_| map_registers) { Self::iomap(&mut mgr, cfg, i, map)?; } } #[ver(V >= V13_0B4)] - if let Some(base) = cfg.sram_base { + if let Some(base) = cfg.sram_base.filter(|_| map_registers) { let size = cfg.sram_size.unwrap(); let iova = mgr.as_mut().alloc_mmio_iova(size); @@ -842,20 +941,7 @@ impl GpuManager::ver { mgr.as_mut().io_mappings_mut().push(mapping, GFP_KERNEL)?; } - let mgr = Arc::from(mgr); - - let rtkit = - rtkit::RtKit::::new(dev.as_ref().as_ref(), None, 0, mgr.clone())?; - - *mgr.rtkit.lock() = Some(rtkit); - - { - let mut rxc = mgr.rx_channels.lock(); - rxc.event.set_manager(mgr.clone()); - rxc.stats.set_manager(mgr.clone()); - } - - Ok(mgr) + Ok(Arc::from(mgr)) } /// Return a mutable reference to the initdata member @@ -929,6 +1015,7 @@ impl GpuManager::ver { /// /// Force disable inlining to avoid blowing up the stack. #[inline(never)] + #[allow(clippy::too_many_arguments)] fn make_mgr( dev: &AsahiDrmDevice, cfg: &'static hw::HwConfig, @@ -937,6 +1024,7 @@ impl GpuManager::ver { mut alloc: KernelAllocators, event_manager: Arc, initdata: KBox>, + timestamp_range: Range, ) -> Result>> { let mut pipes = PipeChannels::ver { vtx: KVec::new(), @@ -1037,10 +1125,12 @@ impl GpuManager::ver { dyncfg: KBox::::into_inner(dyncfg), initdata: KBox::>::into_inner(initdata), uat: KBox::::into_inner(uat), + timestamp_range, io_mappings: KVec::new(), next_mmio_iova: IOVA_KERN_MMIO_RANGE.start, rtkit <- new_mutex!(None, "rtkit"), crashed: AtomicBool::new(false), + garbage_held: AtomicBool::new(false), event_manager, stats: stats_snap.clone(), raw_stats: raw_stats_snap.clone(), @@ -1443,12 +1533,7 @@ impl GpuManager::ver { job.run(&mut pipe); mod_dev_dbg!(self.dev, "GPU: run_job: ring doorbell\n"); - let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); - rtk.send_message( - EP_DOORBELL, - MSG_TX_DOORBELL | pipe_type as u64 | ((index as u64) << 2), - )?; + self.ring_doorbell(MSG_TX_DOORBELL | pipe_type as u64 | ((index as u64) << 2))?; mod_dev_dbg!(self.dev, "GPU: run_job: done\n"); Ok(()) @@ -1514,15 +1599,7 @@ impl GpuManager::ver { mod_dev_dbg!(self.dev, "Context invalidation command: {:?}\n", &dc); let mut txch = self.tx_channels.lock(); - - let token = txch.device_control.send(&dc); - - { - let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); - rtk.send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL)?; - } - + let token = self.send_device_control(&mut txch, &dc)?; txch.device_control.wait_for(token)?; mod_dev_dbg!( @@ -1537,6 +1614,34 @@ impl GpuManager::ver { Ok(()) } + + /// Whether this manager drives its firmware over its own RTKit transport and device-control + /// channel. A manager whose records serve another runtime (the G14 firmware 27.2 graph) has + /// none: that firmware never reads the legacy channels. + fn has_device_control(&self) -> bool { + self.rtkit.lock().is_some() + } + + /// Ring a doorbell on this manager's RTKit transport, or fail with ENODEV without one. + fn ring_doorbell(&self, message: u64) -> Result { + let mut guard = self.rtkit.lock(); + let rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + rtk.send_message(EP_DOORBELL, message) + } + + /// Queue a device-control message and ring its doorbell. Without a transport nothing is + /// queued, so no caller waits for a firmware that will never answer. + fn send_device_control( + &self, + txch: &mut TxChannels::ver, + msg: &fw::channels::DeviceControlMsg::ver, + ) -> Result { + let mut guard = self.rtkit.lock(); + let rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + let token = txch.device_control.send(msg); + rtk.send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL)?; + Ok(token) + } } extern "C" { @@ -1545,10 +1650,12 @@ extern "C" { #[versions(AGX)] impl Gpu for GpuManager::ver { - /// Render commands may order their dependencies on earlier renders after - /// their vertex half only (DRM_ASAHI_RENDER_FRAGMENT_BARRIERS). + /// Render commands may make only their fragment half wait for earlier + /// renders (DRM_ASAHI_RENDER_FRAGMENT_BARRIERS), and the fragment half + /// does wait for them (DRM_ASAHI_FEATURE_ORDERED_FRAGMENT_BARRIERS). fn backend_feature_flags(&self) -> u64 { u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS) + | uapi::DRM_ASAHI_FEATURE_ORDERED_FRAGMENT_BARRIERS as u64 } /// A light submission completes in tens of microseconds, so its submitter @@ -1600,13 +1707,13 @@ impl Gpu for GpuManager::ver { let initdata = self.initdata.gpu_va().get(); let mut guard = self.rtkit.lock(); - let mut rtk = guard.as_mut().as_pin_mut().unwrap(); + let mut rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; rtk.as_mut().boot()?; rtk.as_mut().start_endpoint(EP_FIRMWARE)?; rtk.as_mut().start_endpoint(EP_DOORBELL)?; rtk.as_mut() - .send_message(EP_FIRMWARE, MSG_INIT | (initdata & INIT_DATA_MASK))?; + .send_message(EP_FIRMWARE, init_message(initdata))?; rtk.as_mut() .send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL)?; core::mem::drop(guard); @@ -1687,19 +1794,30 @@ impl Gpu for GpuManager::ver { )?) } + fn timestamp_window_size(&self) -> u64 { + self.timestamp_range.end - self.timestamp_range.start + } + fn map_timestamp_buffer( &self, mut bo: gem::ObjectRef, range: Range, + window: crate::timestamp::WindowPermit, ) -> Result { - crate::timestamp::Buffer::firmware(bo.map_range_into_range( - self.uat.kernel_vm(), - range, - IOVA_KERN_TIMESTAMP_RANGE, - mmu::UAT_PGSZ as u64, - mmu::PROT_FW_SHARED_RW, - false, - )?) + if !window.is_allowed() { + return Err(ENOSPC); + } + crate::timestamp::Buffer::firmware( + bo.map_range_into_range( + self.uat.kernel_vm(), + range, + self.timestamp_range.clone(), + mmu::UAT_PGSZ as u64, + mmu::PROT_FW_SHARED_RW, + false, + )?, + window.into_share(), + ) } } @@ -1770,24 +1888,39 @@ impl GpuManager for GpuManager::ver { let (garbage_count, garbage_bytes) = guard.private.garbage(); let (ro_garbage_count, ro_garbage_bytes) = guard.gpu_ro.garbage(); - if garbage_bytes > MAX_FW_ALLOC_GARBAGE_BYTES - || ro_garbage_bytes > MAX_FW_ALLOC_GARBAGE_BYTES - || garbage_count > MAX_FW_ALLOC_GARBAGE_OBJECTS - || ro_garbage_count > MAX_FW_ALLOC_GARBAGE_OBJECTS - { - mod_dev_dbg!( - self.dev, - "Collecting kalloc garbage (private: {} objects, {} bytes, gpuro: {} objects, {} bytes)\n", - garbage_count, - garbage_bytes, - ro_garbage_count, - ro_garbage_bytes - ); - if self.flush_fw_cache().is_err() { - dev_err!(self.dev.as_ref(), "Failed to flush FW cache\n"); - } else { - guard.private.collect_garbage(garbage_count); - guard.gpu_ro.collect_garbage(ro_garbage_count); + match garbage_action( + (garbage_count, garbage_bytes), + (ro_garbage_count, ro_garbage_bytes), + self.has_device_control(), + ) { + GarbageAction::Keep => {} + GarbageAction::Hold => { + if !self.garbage_held.swap(true, Ordering::Relaxed) { + dev_warn!( + self.dev.as_ref(), + "No firmware cache flush on this firmware: holding freed firmware memory (private: {} objects, {} bytes, gpuro: {} objects, {} bytes)\n", + garbage_count, + garbage_bytes, + ro_garbage_count, + ro_garbage_bytes + ); + } + } + GarbageAction::Collect => { + mod_dev_dbg!( + self.dev, + "Collecting kalloc garbage (private: {} objects, {} bytes, gpuro: {} objects, {} bytes)\n", + garbage_count, + garbage_bytes, + ro_garbage_count, + ro_garbage_bytes + ); + if self.flush_fw_cache().is_err() { + dev_err!(self.dev.as_ref(), "Failed to flush FW cache\n"); + } else { + guard.private.collect_garbage(garbage_count); + guard.gpu_ro.collect_garbage(ro_garbage_count); + } } } @@ -1803,11 +1936,7 @@ impl GpuManager for GpuManager::ver { return Err(ENODEV); } - let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); - rtk.send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_KICKFW)?; - - Ok(()) + self.ring_doorbell(MSG_TX_DOORBELL | DOORBELL_KICKFW) } fn flush_fw_cache(&self) -> Result { @@ -1841,14 +1970,7 @@ impl GpuManager for GpuManager::ver { }; let mut txch = self.tx_channels.lock(); - - let token = txch.device_control.send(&dc); - { - let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); - rtk.send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL)?; - } - + let token = self.send_device_control(&mut txch, &dc)?; txch.device_control.wait_for(token)?; Ok(()) } @@ -1978,26 +2100,16 @@ impl GpuManager for GpuManager::ver { mod_dev_dbg!(self.dev, "Recover Channel command: {:?}\n", &dc); let mut txch = self.tx_channels.lock(); - let token = txch.device_control.send(&dc); - { - let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); - if rtk - .send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL) - .is_err() - { - dev_err!( - self.dev.as_ref(), - "Failed to send Recover Channel command\n" - ); - } - } - - if txch.device_control.wait_for(token).is_err() { - dev_err!( + match self.send_device_control(&mut txch, &dc) { + Err(_) => dev_err!( + self.dev.as_ref(), + "Failed to send Recover Channel command\n" + ), + Ok(token) if txch.device_control.wait_for(token).is_err() => dev_err!( self.dev.as_ref(), "Timed out waiting for Recover Channel command\n" - ); + ), + Ok(_) => {} } if debug_enabled(DebugFlags::VerboseFaults) { @@ -2025,16 +2137,8 @@ impl GpuManager for GpuManager::ver { let mut txch = self.tx_channels.lock(); - txch.device_control.send(&dc); - { - let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); - if rtk - .send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL) - .is_err() - { - dev_err!(self.dev.as_ref(), "Failed to send TVB Grow Ack command\n"); - } + if self.send_device_control(&mut txch, &dc).is_err() { + dev_err!(self.dev.as_ref(), "Failed to send TVB Grow Ack command\n"); } } @@ -2044,12 +2148,13 @@ impl GpuManager for GpuManager::ver { } let mut fwctl = self.fwctl_channel.lock(); - let token = fwctl.send(&msg); - { + let token = { let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); + let rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + let token = fwctl.send(&msg); rtk.send_message(EP_DOORBELL, MSG_FWCTL)?; - } + token + }; fwctl.wait_for(token)?; Ok(()) } @@ -2103,3 +2208,48 @@ impl GpuManagerPriv for GpuManager::ver { unsafe { kernel::bindings::apple_pmp_agx_activity_end() }; } } + +#[kunit_tests(asahi_gpu_garbage)] +mod tests { + use super::*; + + const UNDER: (usize, usize) = (MAX_FW_ALLOC_GARBAGE_OBJECTS, MAX_FW_ALLOC_GARBAGE_BYTES); + const OVER_COUNT: (usize, usize) = (MAX_FW_ALLOC_GARBAGE_OBJECTS + 1, 0); + const OVER_BYTES: (usize, usize) = (1, MAX_FW_ALLOC_GARBAGE_BYTES + 1); + + #[test] + fn under_the_limits_keeps_holding() { + assert_eq!(garbage_action(UNDER, UNDER, true), GarbageAction::Keep); + assert_eq!(garbage_action(UNDER, UNDER, false), GarbageAction::Keep); + } + + #[test] + fn over_a_limit_collects_with_device_control() { + assert_eq!( + garbage_action(OVER_COUNT, UNDER, true), + GarbageAction::Collect + ); + assert_eq!( + garbage_action(UNDER, OVER_BYTES, true), + GarbageAction::Collect + ); + } + + /// The G14 firmware 27.2 graph has no device-control channel. Its scene allocations used + /// to reach the legacy cache flush here and panic on the missing RTKit transport. + #[test] + fn over_a_limit_holds_without_device_control() { + assert_eq!( + garbage_action(OVER_COUNT, UNDER, false), + GarbageAction::Hold + ); + assert_eq!( + garbage_action(UNDER, OVER_BYTES, false), + GarbageAction::Hold + ); + assert_eq!( + garbage_action(OVER_BYTES, OVER_COUNT, false), + GarbageAction::Hold + ); + } +} diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs new file mode 100644 index 00000000000000..78046f9abb0728 --- /dev/null +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -0,0 +1,1725 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The G14 root for GPU firmware 27.2, the boot compute job that starts the firmware's command +//! service, and the command pool the 27.2 compute runtime (`crate::g14_v27_2`) publishes from. +//! +//! The root is built on the records of a 13.5 G14 manager, made with +//! [`GraphProfile::G14V27_2`]: its hardware data supplies the calibrated values, and its +//! kernel UAT, allocators and buffer-manager control pages are shared. The firmware never sees +//! that manager's own root. + +use super::*; +use kernel::device; +use crate::g14_v27_2_abi::{self, EventKind, GrowRequest, QueueError}; +use crate::g17::fw::m5::initdata as abi; +use crate::hw::{RegisterBaseV27_2, RegisterV27_2}; +use crate::m3::m3_init_26 as directory26; + +/// The firmware build word this root carries in its version field. +const FIRMWARE_WORD: u64 = 0x0c8a_8342_8392_04c8; + +/// Kick message for the compute submission ring the root uses (group 2, compute). +pub(crate) const COMPUTE_KICK: u64 = MSG_TX_DOORBELL | (4 * PRIORITY_GROUP + COMPUTE) as u64; +/// Kick message for the device-control ring. +pub(crate) const DEVICE_CONTROL_KICK: u64 = MSG_FWCTL | DOORBELL_DEVCTRL; + +/// Data master of the root's queue, and its priority group: the legacy G14 priority row 2. +const COMPUTE: usize = 2; +const PRIORITY_GROUP: usize = 2; +const PRIORITY_ROW: usize = 2; +/// The submission descriptor the queue publishes on (three per group). +const RENDER_GROUP: usize = 0; +pub(crate) const TILER: usize = 0; +pub(crate) const FRAGMENT: usize = 1; +const SUBMISSION_RING: usize = 3 * PRIORITY_GROUP + COMPUTE; +/// Firmware event, log, trace and statistics rings in the 34-entry channel list. +const EVENT_RING: usize = 13; +const LOG_RINGS: usize = 14; +const TRACE_RING: usize = 15; +const STATISTICS_RING: usize = 16; +/// Ring geometries: the trace ring has 512 records of 0x48 bytes, the others 256. +const TRACE_RECORDS: u32 = 512; +const RING_RECORDS: u32 = 256; +use crate::g14_v27_2_abi::{ + RECOVERY_GENERATION as CONTROL_RECOVERY_GENERATION, RECOVERY_PHASE as CONTROL_RECOVERY_PHASE, + RECOVERY_SNAPSHOT as CONTROL_RECOVERY_SNAPSHOT, +}; +pub(crate) use crate::g14_v27_2_abi::{stopped_tiler, RECOVERY_SNAPSHOT_ENTRIES}; +/// Queue capacity at position block +0x50 (16 x the 0x50 channels). +const QUEUE_CAPACITY: u32 = 0x500; +/// Globals offsets of the 13.5 shared power tables (HwDataShared1 and HwDataShared2): the 27.2 +/// Globals carries them at these places, laid out field for field as in the 13.5 InitData. +const GLOBALS_SHARED1: usize = 0xec; +const GLOBALS_SHARED2: usize = 0x1b4; +const SHARED1_BYTES: usize = 0xa8; +const SHARED2_BYTES: usize = 0x510; +/// Power-record offset of the 13.5 HwDataShared3 (0x50 bytes). +const POWER_SHARED3: usize = 0x4f0; +const _: () = { + assert!(core::mem::size_of::() == SHARED1_BYTES); + assert!(core::mem::size_of::() == SHARED2_BYTES); + assert!(GLOBALS_SHARED1 + SHARED1_BYTES <= GLOBALS_SHARED2); + assert!(GLOBALS_SHARED2 + SHARED2_BYTES <= g14_v27_2_abi::GLOBALS_BYTES); + // The offsets put_shared1/put_shared2/put_curve write. + use core::mem::offset_of; + use fw::initdata::raw::{HwDataShared1 as S1, HwDataShared2 as S2, HwDataShared2Curve as C, + HwDataShared2G14 as G}; + assert!(offset_of!(S1, unk_44) == 0x40 && offset_of!(S1, unk_a4) == 0xa0 && offset_of!(S1, unk_a8) == 0xa4); + assert!(offset_of!(S2, unk_28) == 0x28 && offset_of!(S2, g14) == 0x38 && offset_of!(S2, unk_500) == 0x500); + assert!(offset_of!(G, unk_14) == 0x14 && offset_of!(G, unk_18) == 0x18); + assert!(offset_of!(G, curve1) == 0x38 && offset_of!(G, curve2) == 0x280); + assert!(offset_of!(C, t1) == 8 && offset_of!(C, t2) == 0x28 && offset_of!(C, t3) == 0x48); + assert!(core::mem::size_of::() == 0x248); + // The 13.5 HwDataB words copied at the chip id's distance land where the 27.2 block has + // them (power sample period +0xff4, fragment count +0x10a4). + use fw::initdata::raw::{HwDataBG14V13_5 as B13, HwDataBG14V27_2 as B27}; + assert!(offset_of!(B13, power_sample_period) + offset_of!(B27, chip_id) - offset_of!(B13, chip_id) == 0xff4); + assert!(offset_of!(B13, num_frags) + offset_of!(B27, chip_id) - offset_of!(B13, chip_id) == 0x10a4); + use fw::initdata::raw::HwDataShared3 as S3; + assert!(core::mem::size_of::() == 0x50 && offset_of!(S3, table) == 0xc && offset_of!(S3, unk_4c) == 0x4c); + assert!(POWER_SHARED3 + 0x50 <= 0x6a0); +}; + +/// Board facts the root needs, read from the device tree at probe. +pub(crate) struct BoardV27_2 { + /// The SGX register window (`reg` "sgx"). + pub(crate) sgx: u64, + pub(crate) sgx_size: u64, + /// Bytes of the firmware's crash copy buffer (`apple,coredump-copy-buffer`). + pub(crate) copy_bytes: u32, + /// The chip's 27.2 register table. + pub(crate) registers: &'static [RegisterV27_2], + /// Slots whose stock mode is read-write (bit per slot). + pub(crate) writable: u64, +} + +/// Firmware-visible facts of the root's queue that every compute command names. +#[derive(Copy, Clone)] +pub(crate) struct QueueInfo { + pub(crate) queue: u64, + pub(crate) slot: u32, + pub(crate) stamp: u64, + pub(crate) fw_stamp: u64, + pub(crate) compute_state: u64, +} + +/// One compute command, as the 26.x submission front end hands it over. +pub(crate) struct ComputeJob { + pub(crate) context: u32, + pub(crate) sequence: u64, + pub(crate) cdm_base: u64, + pub(crate) cdm_end: u64, + pub(crate) usc_base: u64, + /// VA of the preemption buffer in the same context (13.5 layout: buffer 1 at +0, + /// buffers 2 to 5 at +compute_preempt1_size + 8n). + pub(crate) preempt: u64, + /// Firmware VAs of the user start and end timestamps, or 0. + pub(crate) timestamps: [u64; 2], + /// The helper program (scratch and stack setup), or zero. + pub(crate) helper: crate::m3::agx_uapi::UapiHelperProgram, + /// The sampler heap and its sampler count, or zero. + pub(crate) sampler_heap: u64, + pub(crate) sampler_count: u32, +} + +fn put32(b: &mut [u8], at: usize, v: u32) { + b[at..at + 4].copy_from_slice(&v.to_le_bytes()); +} + +/// The 13.5 HwDataShared1, field for field. +fn put_shared1(b: &mut [u8], at: usize, s: &fw::initdata::raw::HwDataShared1) { + for (i, v) in s.table.iter().enumerate() { + put32(b, at + 4 * i, *v as u32); + } + b[at + 0x40..at + 0xa0].copy_from_slice(&(*s.unk_44)[..]); + put32(b, at + 0xa0, s.unk_a4); + put32(b, at + 0xa4, s.unk_a8); +} + +/// The 13.5 HwDataShared2 curve, field for field. +fn put_curve(b: &mut [u8], at: usize, c: &fw::initdata::raw::HwDataShared2Curve) { + put32(b, at, c.unk_0); + put32(b, at + 4, c.unk_4); + for (i, v) in c.t1.iter().enumerate() { + b[at + 8 + 2 * i..at + 10 + 2 * i].copy_from_slice(&v.to_le_bytes()); + } + for (i, v) in c.t2.iter().enumerate() { + b[at + 0x28 + 2 * i..at + 0x2a + 2 * i].copy_from_slice(&v.to_le_bytes()); + } + for (row, values) in c.t3.iter().enumerate() { + for (i, v) in values.iter().enumerate() { + put32(b, at + 0x48 + 0x40 * row + 4 * i, *v as u32); + } + } +} + +/// The 13.5 HwDataShared3, field for field. +fn put_shared3(b: &mut [u8], at: usize, s: &fw::initdata::raw::HwDataShared3) { + for (i, v) in [s.unk_0, s.unk_4, s.unk_8].into_iter().enumerate() { + put32(b, at + 4 * i, v); + } + for (i, v) in s.table.iter().enumerate() { + put32(b, at + 0xc + 4 * i, *v); + } + put32(b, at + 0x4c, s.unk_4c); +} + +/// The 13.5 HwDataShared2, field for field (G14 curves included). +fn put_shared2(b: &mut [u8], at: usize, s: &fw::initdata::raw::HwDataShared2) { + for (i, v) in s.table.iter().enumerate() { + put32(b, at + 4 * i, *v as u32); + } + b[at + 0x28..at + 0x38].copy_from_slice(&(*s.unk_28)[..]); + for (i, v) in s.g14.unk_0.iter().enumerate() { + put32(b, at + 0x38 + 4 * i, *v); + } + put32(b, at + 0x4c, s.g14.unk_14); + for (i, v) in s.g14.unk_18.iter().enumerate() { + put32(b, at + 0x50 + 4 * i, *v); + } + put_curve(b, at + 0x70, &s.g14.curve1); + put_curve(b, at + 0x2b8, &s.g14.curve2); + for (i, v) in [s.unk_500, s.unk_504, s.unk_508, s.unk_50c].into_iter().enumerate() { + put32(b, at + 0x500 + 4 * i, v); + } +} + +fn put64(b: &mut [u8], at: usize, v: u64) { + b[at..at + 8].copy_from_slice(&v.to_le_bytes()); +} + +/// Encodes a type-3 compute command (0x358 bytes, the 13.5 G14 job parameters inside the +/// 27.2 wrapper) and its start/finish stream. Both buffers must be zeroed. +#[allow(clippy::too_many_arguments)] +fn encode_compute( + cmd: &mut [u8], cmd_va: u64, stream: &mut [u8], stream_va: u64, tracking: u64, + timestamps: u64, preempt1: u64, q: &QueueInfo, stamp_value: u32, job: &ComputeJob, +) { + put32(cmd, 0, 3); + put64(cmd, 4, job.sequence); + put32(cmd, 0xc, job.context); + put64(cmd, 0x10, tracking); + // 13.5 JobParameters1 at +0x68. + let p2 = job.preempt + preempt1; + for (at, v) in [(0x00, job.preempt), (0x08, job.cdm_base), (0x10, p2), (0x18, p2 + 8), + (0x20, p2 + 16), (0x28, p2 + 24), (0x30, job.usc_base), (0x38, 0x8c60), (0x58, 1)] { + put64(cmd, 0x68 + at, v); + } + put64(cmd, 0x1e8, stream_va); + put32(cmd, 0x1f0, 0x2c0); + // 13.5 JobParameters2: preemption buffer and CDM end; EncoderParams mask. + put64(cmd, 0x220, job.preempt); + put64(cmd, 0x228, job.cdm_end); + put32(cmd, 0x270, u32::MAX); + put64(cmd, 0x298, q.stamp); + put64(cmd, 0x2a0, q.fw_stamp); + put32(cmd, 0x2a8, stamp_value); + put32(cmd, 0x2b0, q.slot); + // flush_stamps, as the render commands and the M3 27.2 compute command set it. + put32(cmd, g14_v27_2_abi::COMPUTE_FLUSH_STAMPS, 1); + put64(cmd, 0x2cc, timestamps); + put64(cmd, 0x2d4, timestamps + 8); + // Command-local dependency latch, enabled with seed 0; the firmware clears 0x10 bytes + // through the pointer at +0x334. + put32(cmd, 0x33c, 1); + put64(cmd, 0x334, timestamps + 0x20); + let user = g14_v27_2_abi::encode_compute_timestamps(cmd, cmd_va, job.timestamps); + g14_v27_2_abi::encode_compute_helper(cmd, job.helper.binary, job.helper.data, job.helper.config); + g14_v27_2_abi::encode_compute_samplers(cmd, job.sampler_heap, job.sampler_count); + + put32(stream, 0, 11); + // 13.5 StartCompute.unk_28, at the same place in this layout (the 13.5 G14 path writes 1). + put32(stream, 0x28, 1); + put64(stream, 0x160, job.sequence); + put64(stream, 0x04, cmd_va + 0x18); + put64(stream, 0x0c, cmd_va + 0x68); + put64(stream, 0x14, q.compute_state); + put64(stream, 0x1c, q.queue); + put32(stream, 0x24, job.context); + put32(stream, 0x34, q.slot); + put64(stream, 0x3c, cmd_va + 0x1f4); + put64(stream, 0x158, cmd_va + 0x340); + for (at, op, selected) in [(0x16c, 0x8000_0003u32, 0x2ccu64), (0x1bc, 3, 0x2d4)] { + put32(stream, at, op); + put64(stream, at + 0x04, cmd_va + 0x2c4); + put64(stream, at + 0x0c, cmd_va + 0x2cc); + put64(stream, at + 0x14, cmd_va + selected); + put64(stream, at + 0x1c, q.queue); + put64(stream, at + 0x24, user); + put64(stream, at + 0x2c, cmd_va + 0x314); + put64(stream, at + 0x34, cmd_va + 0x264); + } + put32(stream, 0x1b8, 0x0080_0000); + let finish = 0x208; + put32(stream, finish, 12); + put64(stream, finish + 4, q.compute_state); + put64(stream, finish + 0x0c, q.queue); + put32(stream, finish + 0x14, job.context); + put64(stream, finish + 0x18, cmd_va + 0x1f4); + put64(stream, finish + 0x2c, q.fw_stamp); + put32(stream, finish + 0x34, stamp_value); + put32(stream, finish + 0x5c, (-(finish as i32)) as u32); + put64(stream, finish + 0x71, cmd_va + 0x340); + put64(stream, finish + 0x79, cmd_va + 0x304); + put32(stream, finish + 0x84, 0x4000_0002); +} + +/// A persistent firmware queue with a separate scheduler context and stamp slot per data master. +struct DmQueue { + queue: fw::types::GpuArray, + positions: fw::types::GpuArray, + pointers: fw::types::GpuArray, + event: event::Event, + announced: core::sync::atomic::AtomicBool, + _scheduler: fw::types::GpuArray, + _stamps: fw::types::GpuArray, +} + +impl DmQueue { + fn new(alloc: &mut KernelAllocators, event: event::Event, priority: usize) -> Result { + let mut queue = alloc.private.array_empty::(0x2cc0)?; + let mut positions = alloc.shared.array_empty::(0x2860)?; + let pointers = alloc.private.array_empty::(0x2860)?; + let mut scheduler = alloc.private.array_empty::(0x40)?; + let mut queue_stamps = alloc.shared.array_empty::(0x18)?; + let queue_stamps_va = queue_stamps.gpu_va().get(); + put64(queue_stamps.as_mut_slice(), 8, queue_stamps_va); + let ctx = scheduler.as_mut_slice(); + ctx[..2].copy_from_slice(&u16::MAX.to_le_bytes()); + ctx[5] = 1; + ctx[0x27] = 0xff; + let queue_va = queue.gpu_va().get(); + let q = queue.as_mut_slice(); + for (offset, value) in [(0, positions.gpu_va().get()), (8, pointers.gpu_va().get()), + (0x10, queue_stamps_va), (0x18, queue_va + 0x90), + (0x7c, scheduler.gpu_va().get())] { + put64(q, offset, value); + } + // The kernel-owned queue has no owning process. + for offset in [0x2c, 0x4c, 0x50] { + put32(q, offset, u32::MAX); + } + let row = crate::fw::workqueue::raw::PRIORITY[priority]; + put32(q, 0x30, row.0); + put32(q, 0x34, row.1); + put64(q, 0x38, row.2.0); + put32(q, 0x40, row.3); + put32(q, 0x44, row.4); + // The current lane stays at the all-ones sentinel; the firmware assigns it. + put32(q, 0x48, u32::MAX); + crate::pgtable::clean_poc(q.as_ptr(), q.len()); + put32(positions.as_mut_slice(), 0x50, QUEUE_CAPACITY); + for mapping in [&positions, &pointers, &scheduler, &queue_stamps] { + crate::pgtable::clean_poc(mapping.as_slice().as_ptr(), mapping.as_slice().len()); + } + Ok(Self { queue, positions, pointers, event, + announced: core::sync::atomic::AtomicBool::new(false), + _scheduler: scheduler, _stamps: queue_stamps }) + } + + fn info(&self, engine_state: u64) -> QueueInfo { + QueueInfo { + queue: self.queue.gpu_va().get(), + slot: self.event.slot(), + stamp: u64::from(self.event.stamp_pointer()), + fw_stamp: u64::from(self.event.fw_stamp_pointer()), + compute_state: engine_state, + } + } +} + +/// A prepared submission has written only unowned ring entries. Publishing its cursors is +/// infallible, so a pair can be staged before either of its queues becomes firmware-visible. +pub(crate) struct Submission<'a> { + head: &'a core::sync::atomic::AtomicU32, + positions: &'a [u8], + target: u32, + producer: &'a core::sync::atomic::AtomicU32, + indices: &'a [u8], + next: u32, + announced: Option<&'a core::sync::atomic::AtomicBool>, +} + +impl Submission<'_> { + pub(crate) fn target(&self) -> u32 { self.target } + + pub(crate) fn publish(self) { + self.head.store(self.target, Ordering::Release); + crate::pgtable::clean_poc(self.positions.as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + self.producer.store(self.next, Ordering::Release); + crate::pgtable::clean_poc(self.indices.as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + if let Some(announced) = self.announced { + announced.store(true, Ordering::Release); + } + } +} + +/// The kernel-owned boot dispatch must retire before clients use the compute queue. +struct BootJob { + queue: fw::types::GpuArray, + positions: fw::types::GpuArray, + pointers: fw::types::GpuArray, + command: fw::types::GpuArray, + stream: fw::types::GpuArray, + tracking: fw::types::GpuArray, + timestamps: fw::types::GpuArray, + event: event::Event, + expected_stamp: u32, + _owners: KVec>, + /// The job's buffers in context 0: mapping before backing. + _client: (mmu::KernelMapping, gem::ObjectRef), + client_va: u64, + preempt1: u64, +} + +impl BootJob { + fn new(alloc: &mut KernelAllocators, event: event::Event, uat: &mmu::Uat, dev: &AsahiDevice, + cfg: &'static hw::HwConfig) -> Result { + let mut queue = alloc.private.array_empty::(0x2cc0)?; + let mut positions = alloc.shared.array_empty::(0x2860)?; + let pointers = alloc.private.array_empty::(0x2860)?; + let mut scheduler = alloc.private.array_empty::(0x40)?; + let mut queue_stamps = alloc.shared.array_empty::(0x18)?; + let command = alloc.private.array_empty::(0x400)?; + let stream = alloc.private.array_empty::(0x400)?; + // A command-buffer tracking slot (0x100 stride, 0xc8 bytes kept by the firmware) + // whose first word names its own cleared retirement cursor. + let mut tracking = alloc.private.array_empty::(0x100)?; + let cursor = alloc.shared.array_empty::(0x90)?; + put64(tracking.as_mut_slice(), 0, cursor.gpu_va().get()); + crate::pgtable::clean_poc(tracking.as_slice().as_ptr(), 0x100); + + let queue_stamps_va = queue_stamps.gpu_va().get(); + put64(queue_stamps.as_mut_slice(), 8, queue_stamps_va); + let ctx = scheduler.as_mut_slice(); + ctx[..2].copy_from_slice(&u16::MAX.to_le_bytes()); + ctx[5] = 1; + ctx[0x27] = 0xff; + let queue_va = queue.gpu_va().get(); + let q = queue.as_mut_slice(); + for (offset, value) in [(0, positions.gpu_va().get()), (8, pointers.gpu_va().get()), + (0x10, queue_stamps_va), (0x18, queue_va + 0x90), + (0x7c, scheduler.gpu_va().get())] { + put64(q, offset, value); + } + // The kernel-owned queue has no owning process. + for offset in [0x2c, 0x4c, 0x50] { + put32(q, offset, u32::MAX); + } + let row = crate::fw::workqueue::raw::PRIORITY[PRIORITY_ROW]; + put32(q, 0x30, row.0); + put32(q, 0x34, row.1); + put64(q, 0x38, row.2.0); + put32(q, 0x40, row.3); + put32(q, 0x44, row.4); + // The current lane stays at the all-ones sentinel; the firmware assigns it. + put32(q, 0x48, u32::MAX); + crate::pgtable::clean_poc(q.as_ptr(), q.len()); + put32(positions.as_mut_slice(), 0x50, QUEUE_CAPACITY); + + // The job's preemption buffer and control stream live in context 0 at a client VA. + let preempt1 = cfg.compute_preempt1_size; + let client_va = IOVA_KERN_GPU_BUFMGR_LOW + 0x10_0000; + let mut object = gem::new_kernel_object(dev, preempt1 + 0x4000)?; + let size = object.size(); + { + use kernel::io::Io; + let map = object.vmap()?; + for off in (0..size).step_by(8) { map.try_write64(0, off)?; } + // CDM control stream: one Stream Terminate block (block type 2 in bits 31:29). + map.try_write32(0x4000_0000, preempt1 + 0x2000)?; + } + let mapping = object.map_at(uat.kernel_lower_vm(), client_va, mmu::PROT_GPU_SHARED_RW, false)?; + let timestamps = alloc.shared.array_empty::(0x80)?; + + let mut owners = KVec::new(); + for owner in [&queue_stamps, &pointers, &scheduler] { + crate::pgtable::clean_poc(owner.as_slice().as_ptr(), owner.as_slice().len()); + } + for owner in [queue_stamps, scheduler, cursor] { + owners.push(owner, GFP_KERNEL)?; + } + let expected_stamp = event.current_noncoherent().next().raw(); + Ok(Self { queue, positions, pointers, command, stream, tracking, timestamps, event, + expected_stamp, _owners: owners, _client: (mapping, object), + client_va, preempt1: preempt1 as u64 }) + } + + fn info(&self, compute_state: u64) -> QueueInfo { + QueueInfo { + queue: self.queue.gpu_va().get(), + slot: self.event.slot(), + stamp: u64::from(self.event.stamp_pointer()), + fw_stamp: u64::from(self.event.fw_stamp_pointer()), + compute_state, + } + } + + /// Encodes the boot command and names it at queue position 0. + fn encode(&mut self, q: &QueueInfo) { + let cdm = self.client_va + self.preempt1 + 0x2000; + let job = ComputeJob { + context: 0, sequence: 0, cdm_base: cdm, cdm_end: cdm + 8, + usc_base: 0x11_0000_0000, preempt: self.client_va, timestamps: [0; 2], + helper: crate::m3::agx_uapi::UapiHelperProgram { binary: 0, config: 0, data: 0 }, + sampler_heap: 0, sampler_count: 0, + }; + let (cmd_va, stream_va) = (self.command.gpu_va().get(), self.stream.gpu_va().get()); + encode_compute(self.command.as_mut_slice(), cmd_va, self.stream.as_mut_slice(), stream_va, + self.tracking.gpu_va().get(), self.timestamps.gpu_va().get(), self.preempt1, + q, self.expected_stamp, &job); + crate::pgtable::clean_poc(self.stream.as_slice().as_ptr(), self.stream.as_slice().len()); + crate::pgtable::clean_poc(self.command.as_slice().as_ptr(), self.command.as_slice().len()); + put64(self.pointers.as_mut_slice(), 0, cmd_va); + crate::pgtable::clean_poc(self.pointers.as_slice().as_ptr(), 8); + crate::pgtable::poc_barrier(); + } +} + +/// Command slots for client compute work. They are allocated with the root, before the +/// firmware window's tables are mirrored, so every slot lies in a table the firmware already +/// translates. Slots are reused in order. +pub(crate) const POOL_SLOTS: usize = 48; + +const COMMAND_STRIDE: usize = 0x1000; +const STREAM_STRIDE: usize = 0x400; + +pub(crate) struct CommandPool { + /// Two command buffers per slot, used in turn (`g14_v27_2_abi::pool_command`). + commands: fw::types::GpuArray, + /// Which of its two command buffers each slot last published, one bit per slot. + published: u64, + streams: fw::types::GpuArray, + tracking: fw::types::GpuArray, + cursors: fw::types::GpuArray, + stamps: fw::types::GpuArray, + preempt1: u64, +} + +impl CommandPool { + pub(crate) fn new(alloc: &mut KernelAllocators, cfg: &'static hw::HwConfig) -> Result { + let commands = alloc.private.array_empty::(2 * POOL_SLOTS * COMMAND_STRIDE)?; + let streams = alloc.private.array_empty::(POOL_SLOTS * STREAM_STRIDE)?; + let mut tracking = alloc.private.array_empty::(POOL_SLOTS * 0x100)?; + // One 64-byte line per retirement cursor, so no firmware write can reach a neighbour. + let cursors = alloc.shared.array_empty::(POOL_SLOTS * 0x40)?; + let stamps = alloc.shared.array_empty::(POOL_SLOTS * 0x80)?; + let base = cursors.gpu_va().get(); + for (i, chunk) in tracking.as_mut_slice().chunks_mut(0x100).enumerate() { + put64(chunk, 0, base + 0x40 * i as u64); + } + crate::pgtable::clean_poc(tracking.as_slice().as_ptr(), tracking.as_slice().len()); + Ok(Self { commands, published: 0, streams, tracking, cursors, stamps, + preempt1: cfg.compute_preempt1_size as u64 }) + } + + /// Builds slot `i` for `job` and returns the command's firmware VA. + pub(crate) fn encode(&mut self, i: usize, q: &QueueInfo, stamp_value: u32, job: &ComputeJob) -> Result { + let preempt1 = self.preempt1; + self.encode_with(i, job.context, job.sequence, stamp_value, |cmd, stream, common| { + encode_compute(cmd, common.cmd_va, stream, common.stream_va, common.tracking, + common.timestamps, preempt1, q, stamp_value, job); + Ok(()) + }) + } + + pub(crate) fn encode_with( + &mut self, i: usize, context: u32, sequence: u64, stamp_value: u32, + encode: impl FnOnce(&mut [u8], &mut [u8], crate::g14_v27_2_render::Common) -> Result, + ) -> Result { + if i >= POOL_SLOTS { return Err(EINVAL); } + // The firmware may read a retired command's JobMeta after it has unlinked the slot + // (for the stamp stores it still has queued), so the slot's next command goes to its + // other buffer. A buffer is rewritten only after the slot has been retired and + // unlinked once more, which the firmware does in a later pass. Encoding always + // takes the spare; `published` moves it only once the firmware can see the command, + // so a publication that fails leaves the last published buffer alone. + let c = g14_v27_2_abi::pool_command(i, g14_v27_2_abi::spare_buffer(self.published, i)); + let cmd_va = self.commands.gpu_va().get() + (c * COMMAND_STRIDE) as u64; + let stream_va = self.streams.gpu_va().get() + (i * STREAM_STRIDE) as u64; + let tracking_va = self.tracking.gpu_va().get() + (i * 0x100) as u64; + let timestamps_va = self.stamps.gpu_va().get() + (i * 0x80) as u64; + let tracking = &mut self.tracking.as_mut_slice()[i * 0x100..(i + 1) * 0x100]; + tracking[8..].fill(0); + crate::pgtable::clean_poc(tracking.as_ptr(), tracking.len()); + let stamps = &mut self.stamps.as_mut_slice()[i * 0x80..(i + 1) * 0x80]; + stamps.fill(0); + crate::pgtable::clean_poc(stamps.as_ptr(), stamps.len()); + let cmd = &mut self.commands.as_mut_slice()[c * COMMAND_STRIDE..(c + 1) * COMMAND_STRIDE]; + cmd.fill(0); + let stream = &mut self.streams.as_mut_slice()[i * STREAM_STRIDE..(i + 1) * STREAM_STRIDE]; + stream.fill(0); + encode(cmd, stream, crate::g14_v27_2_render::Common { + cmd_va, stream_va, tracking: tracking_va, timestamps: timestamps_va, + context, sequence, stamp_value, + })?; + crate::pgtable::clean_poc(stream.as_ptr(), stream.len()); + crate::pgtable::clean_poc(cmd.as_ptr(), cmd.len()); + crate::pgtable::poc_barrier(); + Ok(cmd_va) + } + + /// Slot `i`'s command, encoded in its spare buffer, is now visible to the firmware: the + /// next encode of the slot takes the other buffer. + pub(crate) fn mark_published(&mut self, i: usize) { + if i < POOL_SLOTS { self.published ^= 1 << i; } + } + + /// Retirement: advance slot `i`'s cursor to the value the firmware recorded at + /// tracking +0xc, so its retirement scan unlinks the slot from the queue's list. + /// + /// The firmware records +0xc in its post-processing, which can run after the queue's + /// retired position has advanced. Until then +0xc reads 0 (the slot is cleared for each + /// use) and nothing is written: the cursor would stay behind and the firmware would keep + /// the slot linked for good. Returns whether the cursor was advanced; the caller retries a + /// slot that returned `false` on the firmware's next notification. + pub(crate) fn retire(&self, i: usize) -> Result { + if i >= POOL_SLOTS { return Err(EINVAL); } + crate::pgtable::clean_invalidate_poc(self.tracking.as_slice()[i * 0x100..].as_ptr(), 0x100); + crate::pgtable::poc_barrier(); + let expected = self.tracking.shared_index(i * 0x100 + 0xc)?.load(Ordering::Acquire); + if expected == 0 { return Ok(false); } + self.cursors.shared_index(i * 0x40)?.store(expected, Ordering::Release); + crate::pgtable::clean_poc(self.cursors.as_slice()[i * 0x40..].as_ptr(), 0x40); + crate::pgtable::poc_barrier(); + Ok(true) + } + + /// Slot `i`'s record count (+0xc), its retirement cursor and whether the firmware still + /// holds it in the queue's tracking list (+0x94), for a stall report. + pub(crate) fn describe(&self, i: usize) -> Result<(u32, u32, u32)> { + if i >= POOL_SLOTS { return Err(EINVAL); } + crate::pgtable::clean_invalidate_poc(self.tracking.as_slice()[i * 0x100..].as_ptr(), 0x100); + crate::pgtable::clean_invalidate_poc(self.cursors.as_slice()[i * 0x40..].as_ptr(), 0x40); + crate::pgtable::poc_barrier(); + Ok((self.tracking.shared_index(i * 0x100 + 0xc)?.load(Ordering::Acquire), + self.cursors.shared_index(i * 0x40)?.load(Ordering::Acquire), + self.tracking.shared_index(i * 0x100 + 0x94)?.load(Ordering::Acquire))) + } + + /// Whether the firmware still holds slot `i` in the queue's tracking list (+0x94). + pub(crate) fn registered(&self, i: usize) -> Result { + if i >= POOL_SLOTS { return Err(EINVAL); } + crate::pgtable::clean_invalidate_poc(self.tracking.as_slice()[i * 0x100..].as_ptr(), 0x100); + crate::pgtable::poc_barrier(); + Ok(self.tracking.shared_index(i * 0x100 + 0x94)?.load(Ordering::Acquire) != 0) + } +} + +pub(crate) enum FirmwareEvent { + /// Kind 0: the firmware stopped on a GPU fault and halted for recovery. + Fault, + /// Kind 4: the firmware timed out a command (the slot it names at +0xc) and halted for + /// recovery. + Timeout { slot: i32 }, + Grow(GrowRequest), + ChannelError, + Notification, +} + +pub(crate) struct ControlReply<'a> { + state: &'a fw::types::GpuArray, + ring: &'a fw::types::GpuArray, + cursor: u32, +} + +impl ControlReply<'_> { + pub(crate) fn grow(self, request: GrowRequest, granted: bool) -> Result { + let record = request.reply(granted); + let at = self.cursor as usize * core::mem::size_of_val(&record); + for (index, word) in record.into_iter().enumerate() { + self.ring.shared_index(at + index * 4)?.store(word, Ordering::Relaxed); + } + crate::pgtable::clean_poc(self.ring.as_slice()[at..].as_ptr(), core::mem::size_of_val(&record)); + crate::pgtable::poc_barrier(); + self.state.shared_index(0x20)?.store((self.cursor + 1) % RING_RECORDS, Ordering::Release); + crate::pgtable::clean_poc(self.state.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + Ok(()) + } +} + +/// The firmware 27.2 root and every record it names. +pub(crate) struct RootV27_2 { + graph: Arc, + boot: BootJob, + compute_state: u64, + render_states: [u64; 2], + render_queues: [DmQueue; 2], + channels: KVec>, + _owners: KVec>, + _register_mappings: KVec, + _controller: fw::types::GpuArray, + _directory: fw::types::GpuArray, + boot_page: fw::types::GpuArray, + globals: fw::types::GpuArray, + status: fw::types::GpuArray, + control: fw::types::GpuArray, + power: fw::types::GpuArray, + extra: fw::types::GpuArray, +} + +impl fw::types::GpuStruct for RootV27_2 { + type Raw<'a> = fw::initdata::raw::InitDataG14V27_2<'a>; +} + +impl GpuManagerG14V13_5 { + /// The kernel UAT these records live in. + pub(crate) fn kernel_uat(&self) -> &mmu::Uat { + &self.uat + } + + /// The firmware timestamp aperture that timestamp buffers are bound in. + pub(crate) fn timestamp_range(&self) -> Range { + self.timestamp_range.clone() + } +} + +impl RootV27_2 { + fn word(a: &fw::types::GpuArray, at: usize) -> Result { + Ok(a.shared_index(at)?.load(Ordering::Acquire)) + } + + /// The queue's identity for client commands, and the stamp value it last reached. + pub(crate) fn queue(&self) -> (QueueInfo, event::EventValue) { + (self.boot.info(self.compute_state), self.boot.event.current_noncoherent()) + } + + /// The queue's capacity (position block +0x50). + pub(crate) fn capacity(&self) -> Result { + Self::word(&self.boot.positions, 0x50) + } + + /// The queue head and the firmware's retired position, which it advances in order. + pub(crate) fn progress(&self) -> Result<(u32, u32)> { + let positions = self.boot.positions.as_slice(); + crate::pgtable::clean_invalidate_poc(positions.as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + Ok((Self::word(&self.boot.positions, 0x40)?, Self::word(&self.boot.positions, 0)?)) + } + + pub(crate) fn render_queue(&self, dm: usize) -> (QueueInfo, event::EventValue) { + let queue = &self.render_queues[dm]; + (queue.info(self.render_states[dm]), queue.event.current_noncoherent()) + } + + /// Whether the render queue's retired position reached `target`, stamp or not: a command + /// the firmware stopped for recovery leaves the queue without writing its stamp. + pub(crate) fn render_retired(&self, dm: usize, target: u32) -> Result { + let queue = &self.render_queues[dm]; + crate::pgtable::clean_invalidate_poc(queue.positions.as_slice().as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + Ok(Self::word(&queue.positions, 0)? == target) + } + + pub(crate) fn render_done(&self, dm: usize, target: u32, stamp: event::EventValue) -> Result { + let queue = &self.render_queues[dm]; + crate::pgtable::clean_invalidate_poc(queue.positions.as_slice().as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + Ok(Self::word(&queue.positions, 0)? == target && queue.event.current_noncoherent() >= stamp) + } + + fn log_queue( + dev: &device::Device, name: &str, positions: &fw::types::GpuArray, + queue: &fw::types::GpuArray, stamp: &event::Event, + ) { + crate::pgtable::clean_invalidate_poc(positions.as_slice().as_ptr(), 0x60); + crate::pgtable::clean_invalidate_poc(queue.as_slice().as_ptr(), 0x90); + crate::pgtable::poc_barrier(); + dev_err!(dev, "GPU: {} queue head={:?} fetched={:?} retired={:?} scheduler={:?} stamp={:#x}\n", + name, Self::word(positions, 0x40), Self::word(positions, 0x30), + Self::word(positions, 0), Self::word(queue, 0x74), stamp.current_noncoherent().raw()); + } + + pub(crate) fn log_timeout(&self, dev: &device::Device) { + Self::log_queue(dev, "compute", &self.boot.positions, &self.boot.queue, &self.boot.event); + for (name, queue) in ["tiler", "fragment"].into_iter().zip(&self.render_queues) { + Self::log_queue(dev, name, &queue.positions, &queue.queue, &queue.event); + } + let (generation, phase) = (self.halt_count(), self.recovery_phase()); + let (snapshot, entries) = self.recovery_snapshot(); + dev_err!(dev, "GPU: recovery generation={:?} phase={:?} snapshot ({} entries) {:x?}\n", + generation, phase, entries, &snapshot[..entries.min(snapshot.len())]); + } + + /// The first valid recovery snapshot entries, {flags, target} in hex, and how many valid + /// entries there are in all (the first invalid entry ends the snapshot). Logging only. + pub(crate) fn recovery_snapshot(&self) -> ([(u32, u32); 4], usize) { + let mut first = [(0, 0); 4]; + let mut entries = 0; + for i in 0..RECOVERY_SNAPSHOT_ENTRIES { + match self.recovery_entry(i) { + Ok((flags, target)) if flags & 1 != 0 => { + if let Some(slot) = first.get_mut(entries) { *slot = (flags, target); } + entries += 1; + } + _ => break, + } + } + (first, entries) + } + + pub(crate) fn render_kick(dm: usize) -> u64 { + MSG_TX_DOORBELL | (4 * RENDER_GROUP + dm) as u64 + } + + pub(crate) fn render_queue_announced(&self, dm: usize) -> bool { + self.render_queues[dm].announced.load(Ordering::Acquire) + } + + pub(crate) fn stage_render(&self, dm: usize, commands: &[u64]) -> Result> { + let queue = self.render_queues.get(dm).ok_or(EINVAL)?; + self.stage_work(&queue.positions, &queue.pointers, queue.info(0), + Some(&queue.announced), RENDER_GROUP, dm, commands) + } + + pub(crate) fn stage_compute(&self, command: u64) -> Result> { + self.stage_work(&self.boot.positions, &self.boot.pointers, self.boot.info(self.compute_state), + None, PRIORITY_GROUP, COMPUTE, &[command]) + } + + #[allow(clippy::too_many_arguments)] + fn stage_work<'a>( + &'a self, positions: &'a fw::types::GpuArray, pointers: &fw::types::GpuArray, + queue: QueueInfo, announced: Option<&'a core::sync::atomic::AtomicBool>, + group: usize, dm: usize, commands: &[u64], + ) -> Result> { + let ring_index = 3 * group + dm; + let indices = &self.channels[2 * ring_index]; + let ring = &self.channels[2 * ring_index + 1]; + crate::pgtable::clean_invalidate_poc(positions.as_slice().as_ptr(), 0x60); + crate::pgtable::clean_invalidate_poc(indices.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + + let head = positions.shared_index(0x40)?; + let old = head.load(Ordering::Acquire); + let capacity = Self::word(positions, 0x50)?; + let retired = Self::word(positions, 0)?; + let first = announced.is_some_and(|first| !first.load(Ordering::Acquire)); + if capacity as usize > pointers.len() / 8 || (first && old != retired) { + return Err(EIO); + } + let count = u32::try_from(commands.len()).map_err(|_| EINVAL)?; + let target = g14_v27_2_abi::queue_head(capacity, old, retired, count).map_err(|error| { + match error { + QueueError::Geometry => EIO, + QueueError::Full => EBUSY, + } + })?; + + let producer = indices.shared_index(0x20)?; + let w = producer.load(Ordering::Acquire); + let r = Self::word(indices, 0)?; + if w >= RING_RECORDS || r >= RING_RECORDS { return Err(EIO); } + let next = (w + 1) % RING_RECORDS; + if next == r { return Err(EBUSY); } + let slot = u8::try_from(queue.slot).map_err(|_| EINVAL)?; + let entry = crate::m3::submission_entry(dm as u32, queue.queue, + u16::try_from(target).map_err(|_| EINVAL)?, slot, first).map_err(|_| EINVAL)?; + let base = w as usize * entry.len(); + for (index, &command) in commands.iter().enumerate() { + let at = ((old as usize + index) % capacity as usize) * 8; + pointers.shared_index(at)?.store(command as u32, Ordering::Relaxed); + pointers.shared_index(at + 4)?.store((command >> 32) as u32, Ordering::Relaxed); + crate::pgtable::clean_poc(pointers.as_slice()[at..].as_ptr(), 8); + } + for (index, word) in entry.chunks_exact(4).enumerate() { + ring.shared_index(base + 4 * index)?.store( + u32::from_le_bytes([word[0], word[1], word[2], word[3]]), Ordering::Relaxed); + } + crate::pgtable::clean_poc(ring.as_slice()[base..].as_ptr(), entry.len()); + crate::pgtable::poc_barrier(); + Ok(Submission { head, positions: positions.as_slice(), target, producer, + indices: indices.as_slice(), next, announced }) + } + + /// Publishes the boot job, whose command and ring entry the root already holds. The GPU + /// must be held powered (`operating_point`: the Fender state, nonzero index, no request + /// pending) and the command service installed. + pub(crate) fn publish_boot_job(&self, operating_point: u32) -> Result { + let job = &self.boot; + let index = operating_point & 0xf; + if operating_point & 0x10 != 0 || index == 0 || index > self.graph.dyncfg.pwr.perf_max_pstate + || self.idle_progress()? != [1; 3] + || self.idle_acknowledgement()? != Self::word(&self.globals, 0xe40)? + || !self.commands_installed()? { + return Err(EAGAIN); + } + let producer = self.channels[2 * SUBMISSION_RING].shared_index(0x20)?; + let head = job.positions.shared_index(0x40)?; + if Self::word(&self.status, 0x14)? != 1 || producer.load(Ordering::Acquire) != 0 + || head.load(Ordering::Acquire) != 0 { + return Err(EAGAIN); + } + crate::pgtable::poc_barrier(); + head.store(1, Ordering::Release); + crate::pgtable::poc_barrier(); + producer.store(1, Ordering::Release); + crate::pgtable::poc_barrier(); + Ok(()) + } + + /// Whether the boot job has retired: ring consumed, queue read and retired, stamp reached. + pub(crate) fn boot_job_complete(&self) -> Result { + self.drain()?; + let job = &self.boot; + Ok(Self::word(&self.channels[2 * SUBMISSION_RING], 0)? == 1 + && Self::word(&job.positions, 0x30)? == 1 + && Self::word(&job.positions, 0)? == 1 + && job.event.current_noncoherent().raw() == job.expected_stamp) + } + + /// The record at the head of the event ring: its cursor, its raw kind word and its decoding. + pub(crate) fn peek_event(&self) -> Result> { + use crate::m3::m3_channel_format::RECEIVE_BYTES; + let state = &self.channels[2 * EVENT_RING]; + let ring = &self.channels[2 * EVENT_RING + 1]; + crate::pgtable::clean_invalidate_poc(state.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + let (read, write) = (Self::word(state, 0)?, Self::word(state, 0x20)?); + if read >= RING_RECORDS || write >= RING_RECORDS { return Err(EIO); } + if read == write { return Ok(None); } + let at = read as usize * RECEIVE_BYTES; + crate::pgtable::clean_invalidate_poc(ring.as_slice()[at..].as_ptr(), RECEIVE_BYTES); + crate::pgtable::poc_barrier(); + let word = |offset| Self::word(ring, at + offset); + let kind = word(0)?; + let event = match g14_v27_2_abi::event_kind(kind) { + EventKind::Grow => FirmwareEvent::Grow(GrowRequest::decode([ + word(4)?, word(8)?, word(0x0c)?, word(0x10)?, word(0x14)?, word(0x18)?, + ])), + EventKind::Fault => FirmwareEvent::Fault, + EventKind::Timeout => FirmwareEvent::Timeout { + slot: word(g14_v27_2_abi::TIMEOUT_SLOT_OFFSET)? as i32, + }, + EventKind::ChannelError => FirmwareEvent::ChannelError, + EventKind::Notification => FirmwareEvent::Notification, + }; + Ok(Some((read, kind, event))) + } + + /// Validates a byte range of the control object before it is sliced or cache-maintained. + fn control_range(control: &fw::types::GpuArray, from: usize, bytes: usize) -> Result { + match from.checked_add(bytes) { + Some(end) if end <= control.as_slice().len() && from % 4 == 0 => Ok(()), + _ => Err(EINVAL), + } + } + + /// Reads control words from `from` into `out`. + pub(crate) fn control_snapshot(&self, from: usize, out: &mut [u32]) -> Result { + Self::control_range(&self.control, from, out.len() * 4)?; + let at = self.control.as_slice()[from..].as_ptr(); + crate::pgtable::clean_invalidate_poc(at, out.len() * 4); + crate::pgtable::poc_barrier(); + for (i, w) in out.iter_mut().enumerate() { + *w = Self::word(&self.control, from + 4 * i)?; + } + Ok(()) + } + + /// Writes one control word and makes it visible to the firmware. + pub(crate) fn control_store(&self, at: usize, value: u32) -> Result { + Self::control_range(&self.control, at, 4)?; + self.control.shared_index(at)?.store(value, Ordering::Release); + crate::pgtable::clean_poc(self.control.as_slice()[at..].as_ptr(), 4); + crate::pgtable::poc_barrier(); + Ok(()) + } + + pub(crate) fn consume_event(&self, cursor: u32) -> Result { + let state = &self.channels[2 * EVENT_RING]; + state.shared_index(0)?.store((cursor + 1) % RING_RECORDS, Ordering::Release); + crate::pgtable::clean_poc(state.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + Ok(()) + } + + /// The recovery phase. The firmware publishes 1 after it reported a fault or a command + /// timeout and stopped every queue; it runs nothing until the host's answers. + pub(crate) fn recovery_phase(&self) -> Result { + let mut word = [0u32]; + self.control_snapshot(CONTROL_RECOVERY_PHASE, &mut word)?; + Ok(word[0]) + } + + /// Answers a recovery phase (2 at phase 1, 0 at phase 3). + pub(crate) fn answer_recovery(&self, phase: u32) -> Result { + self.control_store(CONTROL_RECOVERY_PHASE, phase) + } + + /// Snapshot entry `i` of the stopped work: (flags, target). Bit 0 of flags marks a valid + /// entry; the first invalid one ends the snapshot. + pub(crate) fn recovery_entry(&self, i: usize) -> Result<(u32, u32)> { + if i >= RECOVERY_SNAPSHOT_ENTRIES { return Err(EINVAL); } + let mut words = [0u32; 2]; + self.control_snapshot(CONTROL_RECOVERY_SNAPSHOT + 8 * i, &mut words)?; + Ok((words[0], words[1])) + } + + /// The recovery generation (u64). Growth requests carry the value current when sent. + pub(crate) fn halt_count(&self) -> Result { + const OFFSET: usize = CONTROL_RECOVERY_GENERATION; + crate::pgtable::clean_invalidate_poc(self.control.as_slice()[OFFSET..].as_ptr(), 8); + crate::pgtable::poc_barrier(); + Ok(u64::from(Self::word(&self.control, OFFSET)?) + | (u64::from(Self::word(&self.control, OFFSET + 4)?) << 32)) + } + + pub(crate) fn reserve_control_reply(&self) -> Result>> { + let state = &self.channels[2 * crate::m3::DEVICE_CONTROL]; + crate::pgtable::clean_invalidate_poc(state.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + let write = Self::word(state, 0x20)?; + let consumers = [Self::word(state, 0)?, Self::word(state, 0x10)?]; + if write >= RING_RECORDS || consumers.iter().any(|&cursor| cursor >= RING_RECORDS) { + return Err(EIO); + } + let next = (write + 1) % RING_RECORDS; + if consumers.contains(&next) { return Ok(None); } + Ok(Some(ControlReply { state, ring: &self.channels[2 * crate::m3::DEVICE_CONTROL + 1], + cursor: write })) + } + + /// Drain the telemetry rings. The event ring is consumed separately after servicing each event. + pub(crate) fn drain(&self) -> Result { + let consume = |state: &fw::types::GpuArray, base: usize, records: u32| -> Result { + let write = Self::word(state, base + 0x20)?; + let read = state.shared_index(base)?; + if write < records && read.load(Ordering::Acquire) != write { + read.store(write, Ordering::Release); + crate::pgtable::poc_barrier(); + } + Ok(()) + }; + consume(&self.channels[2 * STATISTICS_RING], 0, RING_RECORDS)?; + // One log ring per log thread, state blocks 0x30 apart. + for thread in 0..directory26::LOG_THREADS { + consume(&self.channels[2 * LOG_RINGS], thread * 0x30, RING_RECORDS)?; + } + consume(&self.channels[2 * TRACE_RING], 0, TRACE_RECORDS) + } + + /// Shared status +0x14: the firmware sets it to 1 once it has initialized. + pub(crate) fn initialized(&self) -> Result { + Ok(Self::word(&self.status, 0x14)? == 1) + } + + /// Shared status +0x10: nonzero while the firmware reports itself running. + pub(crate) fn firmware_running(&self) -> Result { + Self::word(&self.status, 0x10) + } + + /// Whether the machine's DT/ADT supplied the GPU power-controller tuning parameters. + pub(crate) fn has_pwr_controller(&self) -> bool { + self.graph.dyncfg.pwr.pwr_controller_from_dt + } + + /// Whether the firmware has installed its command handlers: it clears the installation + /// request (+0x4c24), which the root sets, once powered initialization has copied them. + /// Engine entries may be published only after that. + pub(crate) fn commands_installed(&self) -> Result { + Ok(Self::word(&self.control, 0x4c24)? == 0) + } + + pub(crate) fn idle_acknowledgement(&self) -> Result { + Self::word(&self.control, 0xe838) + } + + /// Device-control ring consumer, target and producer. + pub(crate) fn idle_progress(&self) -> Result<[u32; 3]> { + self.drain()?; + let ring = &self.channels[2 * crate::m3::DEVICE_CONTROL]; + Ok([Self::word(ring, 0)?, Self::word(ring, 0x10)?, Self::word(ring, 0x20)?]) + } + + /// Publishes an idle action and its acknowledged generation on an idle control channel. + pub(crate) fn publish_idle_policy(&self, allow_off: bool) -> Result<(u32, u32)> { + let host = self.globals.shared_index(0xe40)?; + let firmware = self.idle_acknowledgement()?; + let producer = self.channels[2 * crate::m3::DEVICE_CONTROL].shared_index(0x20)?; + if Self::word(&self.status, 0x14)? != 1 { return Err(EAGAIN); } + let cursor = crate::m3::idle_cursor(self.idle_progress()?).map_err(|_| EBUSY)?; + let action = crate::m3::Action::Idle { enabled: allow_off }; + let generation = action.generation(host.load(Ordering::Acquire), firmware).map_err(|_| EOVERFLOW)?; + let mut record = [0; crate::m3::CONTROL_BYTES]; + action.encode(&mut record).map_err(|_| EINVAL)?; + let ring = &self.channels[2 * crate::m3::DEVICE_CONTROL + 1]; + let at = cursor as usize * record.len(); + for (i, word) in record.chunks_exact(4).enumerate() { + ring.shared_index(at + i * 4)?.store( + u32::from_le_bytes([word[0], word[1], word[2], word[3]]), Ordering::Relaxed); + } + crate::pgtable::clean_poc(ring.as_slice()[at..].as_ptr(), record.len()); + host.store(generation, Ordering::Release); + crate::pgtable::poc_barrier(); + let next = (cursor + 1) % RING_RECORDS; + producer.store(next, Ordering::Release); + crate::pgtable::poc_barrier(); + Ok((next, generation)) + } + + /// Builds the root, the boot job and every record they name. + pub(crate) fn build(graph: &Arc, board: &BoardV27_2) -> Result> { + let cfg = graph.cfg; + let g13 = cfg.gpu_gen == hw::GpuGen::G13; + let pwr = &graph.dyncfg.pwr; + let states = &pwr.perf_states; + let id = &graph.dyncfg.id; + // Inputs the controller below is built from, all from the DT and the ID registers. + let [core_mask] = id.core_masks.as_slice() else { return Err(EINVAL); }; + if (!g13 && !pwr.power_zones.is_empty()) || pwr.power_zones.len() > 5 + || pwr.max_power_mw == 0 || pwr.max_power_mw > i32::MAX as u32 + || states.last().map(|s| s.pwr_mw) != Some(pwr.max_power_mw) + || pwr.power_sample_period == 0 + || (pwr.pwr_controller_from_dt && pwr.pwr_filter_time_constant == 0) + || pwr.ppm_filter_time_constant_ms < pwr.power_sample_period + || pwr.avg_power_filter_tc_ms < pwr.power_sample_period + || pwr.avg_power_target_filter_tc == 0 + || !(2..=abi::COMMON26_HW_PERF_ROWS).contains(&states.len()) + || states.windows(2).any(|s| s[1].pwr_mw <= s[0].pwr_mw || s[1].freq_hz <= s[0].freq_hz) + || pwr.perf_base_pstate == 0 || pwr.perf_base_pstate as usize >= states.len() + || core_mask.count_ones() != id.total_active_cores || id.total_active_cores == 0 + || (!g13 && cfg.shared3_tab.len() != 16) + || board.copy_bytes == 0 || board.sgx_size < 0xe14000 { + return Err(EINVAL); + } + // Alarm sensors: the chip's fast-die selection, also its sensor inventory. + let sensors = cfg.fast_sensor_mask[0]; + if sensors == 0 || sensors >> 32 != 0 || cfg.fast_sensor_mask_alt[0] != sensors { + return Err(EINVAL); + } + // The SRAM voltage of each operating point: published by the loader from the ADT on G14, + // or derived from apple,min-sram-microvolt on G13 where the ADT has no perf-states-sram. + let sram_table = Self::sram_table(states.len())?; + if !g13 && sram_table.is_none() { + return Err(EINVAL); + } + let min_sram_mv = pwr.min_sram_microvolt / 1000; + if sram_table.is_none() && min_sram_mv == 0 { + return Err(EINVAL); + } + + let mut alloc = graph.alloc(); + graph.event_manager.sync_initial_stamps(); + let mut boot = BootJob::new(&mut alloc, graph.event_manager.try_get_polled()?, + graph.kernel_uat(), &graph.dev, cfg)?; + // The 0x60-byte root child and the eight-byte temperature generation occupy + // consecutive, 64-byte-aligned shared suballocations. + let extra = alloc.shared.array_empty::(0x80 + 8)?; + + // The thirteen TX descriptors and four RX rings. + let mut channels = KVec::new(); + let mut addresses = [0; 34]; + for (index, address) in addresses.iter_mut().enumerate() { + let size = directory26::allocation(index).map_err(|_| EINVAL)?.size; + let owner = if index < 26 && index % 2 == 1 { + alloc.private.array_empty::(size)? + } else { + alloc.shared.array_empty::(size)? + }; + *address = owner.gpu_va().get(); + channels.push(owner, GFP_KERNEL)?; + } + { + // The boot job's entry is pending at index 0 of its empty ring. + let slot = u8::try_from(boot.event.slot()).map_err(|_| EINVAL)?; + let entry = crate::m3::submission_entry(COMPUTE as u32, boot.queue.gpu_va().get(), 1, slot, true) + .map_err(|_| EINVAL)?; + let ring = channels[2 * SUBMISSION_RING + 1].as_mut_slice(); + ring[..entry.len()].copy_from_slice(&entry); + crate::pgtable::clean_poc(ring.as_ptr(), ring.len()); + } + + + let mut directory = alloc.private.array_empty::(0x4c8)?; + let bytes = directory.as_mut_slice(); + directory26::write_channels(bytes, &addresses).map_err(|_| EINVAL)?; + let base = &graph.initdata.runtime_pointers; + + // Hardware data: the 27.2 inline block. + use fw::initdata::raw::HwDataBG14V27_2 as Hw; + use crate::m3::m3_mmio_26::{write_record, RECORD_BYTES, TABLE_OFFSET}; + let mut hardware = alloc.private.array_empty::(0x2788)?; + let hw = hardware.as_mut_slice(); + let mode = |slot: usize| if board.writable & (1 << slot) != 0 { 2 } else { 0 }; + for slot in 0..60 { + write_record(&mut hw[TABLE_OFFSET + RECORD_BYTES * slot..], 0, 0, 0, 0, 0, mode(slot)) + .map_err(|_| EINVAL)?; + } + let mut register_mappings = KVec::new(); + let mut io_va = IOVA_KERN_MMIO_RANGE.start; + for reg in board.registers { + let physical = match reg.base { + RegisterBaseV27_2::Physical(pa) => pa, + RegisterBaseV27_2::Sgx(offset) => board.sgx + offset, + }; + let Some(va_offset) = reg.install else { continue; }; + let subpage = physical as usize & mmu::UAT_PGMSK; + let span = (subpage + reg.size as usize + mmu::UAT_PGMSK) & !mmu::UAT_PGMSK; + let writable = mode(reg.slot) == 2; + let page_start = physical - subpage as u64; + let va = match va_offset { + 0 => io_va, + offset => IOVA_KERN_MMIO_RANGE.start + offset, + }; + let page = graph.uat.kernel_vm().map_io( + graph.dev.as_ref().as_ref(), va, page_start as usize, span, + if writable { mmu::PROT_FW_MMIO_RW } else { mmu::PROT_FW_MMIO_RO }, + )?; + if page.translate_offset(subpage)? != physical + || page.translate_offset(subpage + reg.size as usize - 1)? != physical + u64::from(reg.size) - 1 { + return Err(EINVAL); + } + write_record(&mut hw[TABLE_OFFSET + RECORD_BYTES * reg.slot..], physical, + page.iova() + subpage as u64, reg.size, reg.size, reg.relative, mode(reg.slot)) + .map_err(|_| EINVAL)?; + if va_offset == 0 { + io_va = io_va.checked_add(span as u64).ok_or(EOVERFLOW)?; + } + register_mappings.push(page, GFP_KERNEL)?; + } + const _: () = assert!(core::mem::offset_of!(Hw, coredump_copy_buffer_size) + 8 <= 0xfc0); + const _: () = assert!(core::mem::offset_of!(Hw, chip_id) + 16 <= 0xfc0); + let dump = core::mem::offset_of!(Hw, coredump_copy_buffer_size); + put64(hw, dump, u64::from(board.copy_bytes)); + base.hwdata_b.with(|old, _| { + for (offset, value) in [ + (0x00, old.unk_8.0), (0x08, old.unk_18.0), + (0x10, 0x11_00000000), (0x18, 0x11_00000000), + (0x20, 0x6f_ffff8000), (0x28, IOVA_G14_V27_2_TIMESTAMP_RANGE.start), + (0x10cc, old.uat_ttb_base.0), + ] { + put64(hw, offset, value); + } + for (offset, value) in [(0x10d4, old.gpu_core_id), (0x10d8, old.gpu_rev_id), + (0x10dc, id.total_active_cores), (0x10e0, old.max_pstate)] { + put32(hw, offset, value); + } + let chip = core::mem::offset_of!(Hw, chip_id); + for (i, word) in [old.chip_id, old.unk_454, old.unk_458, old.unk_45c].into_iter().enumerate() { + put32(hw, chip + 4 * i, word); + } + if !g13 { + // From the power sample period to the fragment count, the 27.2 block keeps the 13.5 + // HwDataB words in order, at the chip id's distance: the firmware's power sampling + // period, the cache-flush and feature enables and the fragment count. + use core::mem::offset_of; + type Old = fw::initdata::raw::HwDataBG14V13_5; + let shift = chip - offset_of!(Old, chip_id); + for (at, value) in [ + (offset_of!(Old, power_sample_period), old.power_sample_period), + (offset_of!(Old, unk_49c), old.unk_49c), (offset_of!(Old, unk_4a0), old.unk_4a0), + (offset_of!(Old, unk_4a4), old.unk_4a4), (offset_of!(Old, unk_4c0), old.unk_4c0), + (offset_of!(Old, unk_4f0), old.unk_4f0), (offset_of!(Old, unk_4f4), old.unk_4f4), + (offset_of!(Old, unk_504), old.unk_504), (offset_of!(Old, unk_524), old.unk_524), + (offset_of!(Old, unk_534), old.unk_534), (offset_of!(Old, num_frags), old.num_frags), + ] { + put32(hw, at + shift, value); + } + put64(hw, offset_of!(Old, unk_4e0) + shift, old.unk_4e0.0); + } + }); + if g13 { + // Inline words for G13G (T8103) firmware 27.2.1 (26B131): derived from the 13.5 + // configuration and the chip's register capabilities (no CRE on T8103). + for (at, v) in [ + // Sleep/wake handler and RTKit power callback enables matching G14. + (0xfc0, 1u32), (0xfc4, 1), (0xfd8, 1), (0xfdc, 1), (0xfe4, 1), (0xfec, 24000), + (0xff0, 1), (0xff4, pwr.power_sample_period), (0xffc, 1), (0x1000, 1), (0x1004, 1), + (0x1020, 0x1f), (0x1050, 1), (0x1054, 1), (0x1068, 0x31), (0x1088, 1), + (0x10a4, id.num_frags * id.num_clusters), (0x10a8, 1), + (0x2664, cfg.max_num_gps), (0x2668, 3), (0x266c, 7), (0x2670, 7), + (0x267c, 0), (0x2680, 0), (0x2684, id.total_active_cores), + (0x268c, 1), (0x26a8, 0xe_0000), + (0x26b0, 1), (0x26b4, 1), (0x26b8, 0), (0x26c0, 1), (0x26c4, 1), + (0x277c, 0x1_0000), (0x2780, 0x1_0000), + ] { + put32(hw, at, v); + } + hw[0x26d0..0x2700].fill(0xff); + } else { + // Inline words the stock host producer fixes for a gpu,t8112 node without model-slow. + for (offset, value) in [(0xfc8u32, 0u32), (0xfd8, 1), (0xfec, 24000), (0xff0, 1), + (0xffc, 1), (0x2724, 1), (0x2754, 1), + (0xfc4, 1), (0xfdc, 1), (0xfe0, 0), (0x1028, 0), + (0x109c, 0), (0x1064, 0), (0x2728, 0)] { + put32(hw, offset as usize, value); + } + // Per-engine kick masks. The firmware gives an engine a kick slot only for bits set + // here, so an engine whose mask is left zero is never scheduled. The tiler takes one + // bit per cluster; the fragment and compute engines take one bit per configured core. + let low_bits = |n: u32| if n < 32 { (1u32 << n) - 1 } else { u32::MAX }; + put32(hw, 0x2668, low_bits(id.num_clusters)); + for offset in [0x266c, 0x2670] { + put32(hw, offset, low_bits(id.total_active_cores)); + } + // Firmware-managed operating points, CRE and event-assisted operating-point completion. + for offset in [0xfc0, 0x26b8, 0x1054] { + put32(hw, offset, 1); + } + put64(hw, 0x267c, u64::from(*core_mask)); + put32(hw, 0x2684, id.total_active_cores); + } + // Operating points, in the 13.5 HwDataB order the 27.2 block keeps: power above the + // lowest state and frequency above the base state as f32 percentages, MHz, the per-lane + // core and SRAM voltages, the chip's SRAM power coefficient per state and the identity + // state index map. + let top = states.len() - 1; + if old_max_pstate(base)? as usize != top { return Err(EINVAL); } + let baseline = states[0].pwr_mw; + let span = crate::float::F32::from(states[top].pwr_mw - baseline); + for (i, state) in states.iter().enumerate() { + let percentage = crate::float::F32::from(state.pwr_mw - baseline) * crate::f32!(100.0) / span; + put32(hw, abi::COMMON26_HW_PERF_RELATIVE_A + i * 4, percentage.to_bits()); + } + let base_idx = pwr.perf_base_pstate as usize; + let base_hz = states[base_idx].freq_hz; + let span = crate::float::F32::from(states[top].freq_hz - base_hz); + for (i, state) in states.iter().enumerate().skip(base_idx + 1) { + let relative = crate::float::F32::from(state.freq_hz - base_hz) * crate::f32!(100.0) / span; + put32(hw, abi::COMMON26_HW_PERF_RELATIVE_B + 4 * i, relative.to_bits()); + } + for (i, state) in states.iter().enumerate() { + let [mv] = state.volt_mv.as_slice() else { return Err(EINVAL); }; + let sram_mv = if let Some(table) = sram_table.as_ref() { + let (freq, voltage) = table[i * 8..i * 8 + 8].split_at(4); + let value = u32::from_le_bytes(voltage.try_into().map_err(|_| EINVAL)?); + if u32::from_le_bytes(freq.try_into().map_err(|_| EINVAL)?) != state.freq_hz || value < *mv || value == 0 { + return Err(EINVAL); + } + value + } else { + (*mv).max(min_sram_mv) + }; + let mhz = state.freq_hz / 1_000_000; + put32(hw, abi::COMMON26_HW_PERF_FREQUENCY + i * 4, mhz); + put32(hw, abi::COMMON26_HW_PERF_SCALE + i * 4, cfg.sram_k.to_bits()); + let sram_lanes = if g13 { 1 } else { abi::COMMON26_HW_PERF_LANES }; + for lane in 0..abi::COMMON26_HW_PERF_LANES { + let row = i * abi::COMMON26_HW_PERF_ROW_STRIDE + lane * 4; + put32(hw, abi::COMMON26_HW_PERF_CORE_VOLTAGE + row, *mv); + if lane < sram_lanes { + put32(hw, abi::COMMON26_HW_PERF_SRAM_VOLTAGE + row, sram_mv); + } + } + } + for index in 0..abi::COMMON26_HW_PERF_ROWS { + put32(hw, abi::COMMON26_HW_PERF_INDEX_MAP + index * 4, index as u32); + } + crate::pgtable::clean_poc(hw.as_ptr(), hw.len()); + put64(bytes, 0, hardware.gpu_va().get()); + channels.push(hardware, GFP_KERNEL)?; + + // The directory's other records; +0x485 is the power controller. + let mut owners = KVec::new(); + let mut controller = None; + let mut compute_state = 0; + let mut render_states = [0; 2]; + for (offset, size) in [(0x10, 0x88), (0x254, 0x678), (0x25c, 0x760), + (0x264, 0x6d0), (0x26c, 0x60), (0x485, 0x6c48)] { + let mut owner = alloc.private.array_empty::(size)?; + if offset == 0x485 { + Self::controller(owner.as_mut_slice(), graph, &extra, sensors)?; + } + let address = owner.gpu_va().get(); + put64(bytes, offset, address); + if offset == 0x10 { + put64(bytes, 8, address); + } + if offset == 0x254 { render_states[TILER] = address; } + if offset == 0x25c { render_states[FRAGMENT] = address; } + if offset == 0x264 { + // The compute engine state the start and finish records name. + compute_state = address; + } + if offset == 0x485 { + controller = Some(owner); + } else { + owners.push(owner, GFP_KERNEL)?; + } + } + let controller = controller.ok_or(EINVAL)?; + let ids = alloc.private.array_empty::(0x134c)?; + for (slot, offset) in [(0x2c8, 0), (0x2d0, 0x1000), (0x2d8, 0x1300)] { + put64(bytes, slot, ids.gpu_va().get() + offset); + } + owners.push(ids, GFP_KERNEL)?; + let low = base.buffer_mgr_ctl_low_mapping.as_ref().ok_or(EINVAL)?; + let high = base.buffer_mgr_ctl_high_mapping.as_ref().ok_or(EINVAL)?; + if low.translate_offset(0)? != high.translate_offset(0)? { return Err(EINVAL); } + put64(bytes, 0x2e0, low.iova()); + put64(bytes, 0x2e8, high.iova()); + bytes[0x3e4] = 0xff; + let payload = alloc.shared.array_empty::( + directory26::LOG_THREADS * RING_RECORDS as usize * directory26::LOG_PAYLOAD_BYTES)?; + put64(bytes, 0x200, payload.gpu_va().get()); + owners.push(payload, GFP_KERNEL)?; + crate::pgtable::clean_poc(bytes.as_ptr(), bytes.len()); + + let status = alloc.shared.array_empty::(0x20)?; + let boot_page = { + let page = alloc.shared_ro.alloc_generic::(mmu::UAT_PGSZ, mmu::UAT_PGSZ, None)?; + fw::types::GpuArray::empty(page, mmu::UAT_PGSZ)? + }; + let mut globals = alloc.shared_ro.array_empty::(g14_v27_2_abi::GLOBALS_BYTES)?; + { + let data = globals.as_mut_slice(); + for (offset, value) in [(0x58, 0xffffu16), (0x5a, 0x28), (0x5c, 0xffff)] { + data[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); + } + put32(data, 0x6e, 1); + let ceiling = pwr.perf_max_pstate * 100; + if g13 { + for (at, value) in [ + (0x24, 3000u32), (0x30, 1), (0x38, 1), (0x40, 120), + (0x60, 0x1_0000), (0x64, 0x1_0000), (0x68, 0x3_0000), (0x78, 1), + (0x84, pwr.max_power_mw), (0x88, ceiling), (0x8c, ceiling), (0x98, ceiling), + (0x128, u32::MAX), (0x18c, 0xffff), (0x1b4, 0x800), (0x1b8, 0x1555), + (0x1d0, u32::MAX), (0x1e8, u32::MAX), (0x6bc, 0xc0_0007), + (0x7ec, 1), (0x7f0, 1), (0x7f4, 100), (0x7f8, 100), + (0x990, 400_000), (0x998, 40), (0x99c, 10), (0x9a0, 250), (0x9a4, 1), + (0x9b8, 2), (0x9bc, 40), (0x9c0, 5), (0x9c8, 40), (0x9cc, 50), + (0x9d0, 1), (0x9d8, 50), (0xe08, 250), (0xe28, 3), (0xe2c, 1), + ] { + put32(data, at, value); + } + data[0xec..0x128].fill(0xff); + data[0x1bc..0x1d0].fill(0xff); + data[0x1dc..0x1e8].fill(0xff); + } else { + for (at, value) in [(0x84, pwr.max_power_mw), (0x88, ceiling), (0x8c, ceiling), (0x98, ceiling)] { + put32(data, at, value); + } + // The shared power tables the 13.5 InitData built from the chip configuration and + // the DT operating points (the G14 curves scale with each state's frequency and + // voltage). Left zero, the firmware runs the upper states without them. + base.hwdata_a.with(|a, _| { + put_shared1(data, GLOBALS_SHARED1, &a.hws1); + put_shared2(data, GLOBALS_SHARED2, &a.hws2); + }); + // The firmware's progress checks and compute watchdog, as M3 and M4 27.2 set them. + for (at, value) in g14_v27_2_abi::GLOBALS_PROGRESS { + put32(data, at, value); + } + } + crate::pgtable::clean_poc(data.as_ptr(), data.len()); + } + let mut control = alloc.shared.array_empty::(0xe850)?; + { + // One shared backing: 0x20 bytes of indices, followed at +0x40 by 256 cache-flush + // requests. An empty ring still needs both VAs. + let flush = alloc.shared.array_empty::(0x40 + 256 * 0x18)?; + let state = flush.gpu_va().get(); + directory26::write_flush_ring(control.as_mut_slice(), 0x4be0, state, state + 0x40) + .map_err(|_| EINVAL)?; + // Request command-handler installation during powered initialization. + put32(control.as_mut_slice(), 0x4c24, 1); + owners.push(flush, GFP_KERNEL)?; + } + // The firmware window mirrors only the kernel page tables that exist when it is + // installed. Keep one allocation of the GPU read-write range alive from here, so the + // tables that later hold the parameter-buffer lists are already visible to the firmware. + owners.push(alloc.gpu.array_empty::(0x4000)?, GFP_KERNEL)?; + let mut power = alloc.shared.array_empty::(0x6a0)?; + { + let data = power.as_mut_slice(); + if g13 { + let period = pwr.power_sample_period; + let dt = crate::float::F32::from(period) / crate::f32!(1000.0); + let zone = pwr.power_zones.first(); + for (at, value) in [ + (0x0c, 0u32), + (0x10, pwr.avg_power_filter_tc_ms / period), + (0x14, (pwr.avg_power_ki_only * dt).to_bits()), + (0x18, pwr.avg_power_kp.to_bits()), + (0x1c, pwr.avg_power_min_duty_cycle), + (0x20, pwr.avg_power_target_filter_tc), + (0x24, zone.map_or(0, |z| z.target)), + (0x28, zone.map_or(0, |z| z.target.saturating_sub(z.target_offset))), + (0x2c, zone.map_or(0, |z| z.filter_tc)), + (0xc8, cfg.da.unk_8cc), + (0xcc, 8000), + (0xd0, cfg.da.unk_87c as u32), + (0xd8, pwr.fast_die0_proportional_gain.to_bits()), + (0xdc, (pwr.fast_die0_integral_gain * dt).to_bits()), + (0xf0, 9900), (0xf4, 200), + (0x108, crate::f32!(100.0).to_bits()), (0x10c, crate::f32!(400.0).to_bits()), + (0x110, 200), + (0x12c, pwr.max_power_mw), + (0x130, pwr.ppm_kp.to_bits()), + (0x134, (pwr.ppm_ki * dt).to_bits()), + (0x5e0, 1), (0x5e4, 0x1b), + (0x624, crate::f32!(15.0).to_bits()), (0x628, crate::f32!(5.0).to_bits()), + (0x62c, 32), (0x630, pwr.perf_max_pstate * 100), (0x640, 500), (0x68c, 1), + ] { + put32(data, at, value); + } + } else { + // Cold mirrors of the controller's power and temperature-loop values. + let gains = base.hwdata_a.with(|a, _| (a.ppm_kp.to_bits(), a.ppm_ki_dt.to_bits())); + for (at, value) in [(0x12c, pwr.max_power_mw), (0x130, gains.0), (0x134, gains.1)] { + put32(data, at, value); + } + // The average-power filter and the third shared power table, as the 13.5 Globals + // carries them (built from the DT power values and the chip configuration). + graph.initdata.globals.with(|g, _| { + for (at, value) in [ + (0x10, g.avg_power_filter_tc_periods), (0x14, g.avg_power_ki_dt.to_bits()), + (0x18, g.avg_power_kp.to_bits()), (0x1c, g.avg_power_min_duty_cycle), + (0x20, g.avg_power_target_filter_tc), + ] { + put32(data, at, value); + } + put_shared3(data, POWER_SHARED3, &g.hws3); + }); + let initial = controller.as_slice(); + for (dst, src) in [(0xc8, 0x22d4), (0xcc, 0x2280), (0xd0, 0x2284), + (0xd4, 0x22cc), (0xd8, 0x22b4), (0xdc, 0x22a4)] { + data[dst..dst + 4].copy_from_slice(&initial[src..src + 4]); + } + } + crate::pgtable::clean_poc(data.as_ptr(), data.len()); + } + + let render_queues = [ + DmQueue::new(&mut alloc, graph.event_manager.try_get_polled()?, RENDER_GROUP)?, + DmQueue::new(&mut alloc, graph.event_manager.try_get_polled()?, RENDER_GROUP)?, + ]; + boot.encode(&boot.info(compute_state)); + let (page_size, page_bits, levels, descriptors) = graph.initdata.with(|r, _| + (r.uat_page_size, r.uat_page_bits, r.uat_num_levels, r.uat_level_info)); + let root = alloc.shared_ro.alloc_generic::(mmu::UAT_PGSZ, mmu::UAT_PGSZ, None)?; + core::mem::drop(alloc); + let root = fw::types::GpuObject::::new_init_prealloc(root, + |_| try_init!(Self { + graph: graph.clone(), boot, compute_state, render_states, render_queues, channels, _owners: owners, + _register_mappings: register_mappings, _controller: controller, _directory: directory, + boot_page, globals, status, control, power, extra, + }), + |owners, _| { + try_init!(fw::initdata::raw::InitDataG14V27_2 { + ver_info: fw::types::Array::new(core::array::from_fn(|i| (FIRMWARE_WORD >> (16 * i)) as u16)), + unk_buf: owners.boot_page.gpu_pointer(), + unk_8: 0, + unk_c: 0, + runtime_pointers: owners._directory.gpu_pointer(), + globals: owners.globals.gpu_pointer(), + role: 0, + host_mapped_fw_allocations: 1, + uat_page_size: page_size, + uat_page_bits: page_bits, + uat_num_levels: levels, + uat_level_info: descriptors, + __pad0: Default::default(), + status_record: owners.status.gpu_pointer(), + control: owners.control.gpu_pointer(), + power: owners.power.gpu_pointer(), + extra: owners.extra.gpu_pointer(), + }) + }, + )?; + root.with(|r, _| crate::pgtable::clean_poc(core::ptr::from_ref(r).cast(), core::mem::size_of_val(r))); + Ok(root) + } + + /// The loader's `adt-perf-states-sram` table under `/chosen/aurora-gpu-resources/sgx` + /// (frequency and SRAM millivolts per state), if present. + fn sram_table(states: usize) -> Result>> { + let chosen = kernel::of::chosen().ok_or(ENODEV)?; + let is = |name: Option>, want: &[u8]| { + name.as_deref().is_some_and(|n| n.strip_suffix(b"\0").unwrap_or(n) == want) + }; + for parent in chosen.children() { + if !is(parent.get_opt_property::>(c"name")?, b"aurora-gpu-resources") { continue; } + for child in parent.children() { + if is(child.get_opt_property::>(c"name")?, b"sgx") { + let Some(table) = child.get_opt_property::>(c"adt-perf-states-sram")? else { + return Ok(None); + }; + if table.len() != states * 8 { return Err(EINVAL); } + return Ok(Some(table)); + } + } + } + Ok(None) + } + + /// The power and thermal controller (directory +0x485): the 13.5 calibrated values of the + /// hardware data A, moved to the 27.2 layout. + fn controller(policy: &mut [u8], graph: &GpuManagerG14V13_5, extra: &fw::types::GpuArray, + sensors: u64) -> Result { + let pwr = &graph.dyncfg.pwr; + let cfg = graph.cfg; + let base = &graph.initdata.runtime_pointers; + let max_state = (pwr.perf_states.len() as u32 - 1) * 100; + for offset in [0x222c, 0x2880] { + put32(policy, offset, max_state); + } + let generation = extra.gpu_va().get() + 0x80; + if generation & 0x3f != 0 || extra.as_slice()[0x80..] != [0; 8] { + return Err(EINVAL); + } + put64(policy, 0x3b98, generation); + // Secure metrology sensor set, and the fast-die release temperature, mask and gains. + put64(policy, 0x3ba0, sensors); + let (release, mask, integral, proportional) = base.hwdata_a.with(|old, _| + (old.fast_die0_release_temp_cc, old.fast_die0_sensor_mask.0, + old.fast_die0_ki_dt.to_bits(), old.fast_die0_kp.to_bits())); + for (source, value, width) in [(0x2270, u64::from(release), 4), (0x2268, mask, 8), + (0x2294, u64::from(integral), 4), (0x22a4, u64::from(proportional), 4)] { + let at = abi::relocate_by_bands(abi::COMMON26_POLICY_BANDS, source).ok_or(EINVAL)?; + policy.get_mut(at..at + width).ok_or(EINVAL)?.copy_from_slice(&value.to_le_bytes()[..width]); + } + // Thermal thresholds, then the SoC-hot alarm selection: the chip's values, as the 13.5 + // InitData writes them (HwDataA unk_8cc, unk_87c and unk_e24). + for (at, value) in [(0x22d4, cfg.da.unk_8cc), (0x2284, cfg.da.unk_87c as u32), + (0x2f30, cfg.da.unk_e24)] { + put32(policy, at, value); + } + // Controller constants the 13.5 InitData also sets (unk_880, unk_894 = 1.0, unk_e28). + const FILTER_STAGES: u32 = 4; + const ALARM_ENABLE: u32 = 1; + for (at, value) in [(0x2288, FILTER_STAGES), (0x229c, crate::f32!(1.0).to_bits()), + (0x2f34, ALARM_ENABLE)] { + put32(policy, at, value); + } + // Per-sensor corrections from the chip's coefficient tables (13.5 unk_coef_a/unk_coef_b), + // indexed from the first fast-die sensor id. G13 carries no per-sensor coefficient tables; + // on chips that do, a sensor without a coefficient refuses. + const FIRST_SENSOR: usize = 7; + if let (Some(coef_a), Some(coef_b)) = (cfg.unk_coef_a.first(), cfg.unk_coef_b.first()) { + for (at, coef) in [(0x2320, coef_a), (0x2420, coef_a), (0x2f38, coef_b), (0x3038, coef_b)] { + for sid in (0..64usize).filter(|sid| sensors & (1u64 << sid) != 0) { + let value = sid.checked_sub(FIRST_SENSOR).and_then(|index| coef.get(index)) + .ok_or(EINVAL)?; + put32(policy, at + 4 * sid, value.to_bits()); + } + } + } else if cfg.gpu_gen != hw::GpuGen::G13 { + return Err(EINVAL); + } + put64(policy, 0x2f28, sensors); + put32(policy, 0x3ba8, 1); + for (word, value) in policy[0x62b8..0x62f8].chunks_exact_mut(4).zip(cfg.shared3_tab) { + word.copy_from_slice(&value.to_le_bytes()); + } + // Warm-restart operands: base operating point and wake flags. + for (at, value) in [ + (0x9c, 1), + (0xa0, 1), + (0xa4, pwr.perf_base_pstate), + (0xa8, 1), + ] { + put32(policy, at, value); + } + for (source, bits) in [ + (4, pwr.pwr_sample_period_aic_clks), + (8, pwr.pwr_sample_period_aic_clks), + // Two initial state sources; the current state at +0x38 belongs to the firmware. + (0x2c, pwr.perf_base_pstate), + (0x30, pwr.perf_base_pstate), + (0x9f0, pwr.pwr_min_duty_cycle), + (0xb5c, pwr.perf_integral_gain.to_bits()), + (0xb60, pwr.perf_integral_gain2.to_bits()), + (0xb6c, pwr.perf_proportional_gain.to_bits()), + (0xb70, pwr.perf_proportional_gain2.to_bits()), + ] { + let target = abi::relocate_by_bands(abi::COMMON26_POLICY_BANDS, source).ok_or(EINVAL)?; + policy.get_mut(target..target + 4).ok_or(EINVAL)?.copy_from_slice(&bits.to_le_bytes()); + } + // The calibrated values of the 13.5 producer; only the layout and the peak length unit + // differ. No power zones. + if pwr.pwr_controller_from_dt { + // Power controller (reason 1): populated only when the machine's DT/ADT supplied + // the tuning parameters, so long power-off replays (deep sleep or idle-off) keep + // the limiter calibrated without falling back to built-in coefficients. + let pwr_fields = base.hwdata_a.with(|a, _| [ + (0x9c8, a.unk_64c), + (0x9d4, a.pwr_filter_a_neg.to_bits()), + (0x9dc, a.pwr_filter_a.to_bits()), + (0x9e4, a.pwr_integral_gain.to_bits()), + (0x9ec, a.pwr_integral_min_clamp.to_bits()), + (0x9f0, a.max_power_1.to_bits()), + (0x9f4, a.pwr_proportional_gain.to_bits()), + (0x9fc, a.pwr_pstate_related_k.to_bits()), + (0xa04, max_state), + (0xa08, a.max_pstate_scaled_2), + (0xa14, a.max_power_2), + ]); + for (at, value) in pwr_fields { + put32(policy, at, value); + } + } + let samples = pwr.ppm_filter_time_constant_ms / pwr.power_sample_period; + let fields = base.hwdata_a.with(|a, _| [ + (0x50, 100), (0xa80, a.ppm_filter_tc_periods_x4), + (0xa8c, a.ppm_filter_a_neg.to_bits()), (0xa94, a.ppm_filter_a.to_bits()), + (0xa9c, a.ppm_ki_dt.to_bits()), (0xaa8, a.unk_6fc.to_bits()), + (0xaac, a.ppm_kp.to_bits()), (0xab8, a.pwr_min_duty_cycle), + (0xabc, a.max_pstate_scaled_4), (0xacc, a.max_power_3), + (0xad8, samples), (0x2200, a.unk_6fc.to_bits()), + (0xa48, max_state), + (0xb38, a.perf_tgt_utilization), (0xb40, a.perf_boost_min_util), + (0xb44, a.perf_boost_ce_step), (0xb58, a.perf_filter_drop_threshold), + (0xb5c, a.perf_filter_a_neg.to_bits()), (0xb60, a.perf_filter_a2_neg.to_bits()), + (0xb64, a.perf_filter_a.to_bits()), (0xb68, a.perf_filter_a2.to_bits()), + (0xb74, a.perf_integral_min_clamp.to_bits()), (0xb78, a.unk_79c.to_bits()), + (0xb84, a.boost_state_unk_k.to_bits()), (0xb88, a.base_pstate_scaled_2), + (0xb8c, a.max_pstate_scaled_5), (0xb90, a.base_pstate_scaled_3), + (0xb9c, a.perf_tgt_utilization_2), (0xbd0, a.base_pstate_scaled_4), + (0x2204, a.pwr_min_duty_cycle_2.to_bits()), (0x2208, a.max_pstate_scaled_6.to_bits()), + (0x220c, pwr.max_freq_mhz), + (0x22b0, a.unk_8a8.to_bits()), (0x22c0, a.pwr_min_duty_cycle_4), + (0x22c4, a.max_pstate_scaled_8), (0x22c8, a.max_pstate_scaled_9), + (0x2308, a.max_pstate_scaled_10), + (0x28e8, 0), (0x28f0, a.max_power_4), + (0x28f4, a.max_power_5), (0x28f8, a.max_power_6), + (0x2904, a.avg_power_target_filter_a_neg.to_bits()), + (0x2908, a.avg_power_target_filter_a.to_bits()), + (0x29f0, a.avg_power_filter_a_neg.to_bits()), + (0x29f8, a.avg_power_filter_a.to_bits()), + (0x2a00, a.avg_power_ki_dt.to_bits()), (0x2a10, a.avg_power_kp.to_bits()), + (0x2a0c, a.unk_d20.to_bits()), (0x2a1c, a.avg_power_min_duty_cycle), + (0x2a20, a.max_pstate_scaled_12), (0x2a2c, a.max_power_7.to_bits()), + (0x2a30, a.max_power_8), + (0x2b80, a.unk_e10_0.gpu_se_filter_a_neg.to_bits()), + (0x2b84, a.unk_e10_0.gpu_se_filter_1_a_neg.to_bits()), + (0x2b88, a.unk_e10_0.gpu_se_filter_a.to_bits()), + (0x2b8c, a.unk_e10_0.gpu_se_filter_1_a.to_bits()), + (0x2b90, a.unk_e10_0.gpu_se_ki_dt.to_bits()), + (0x2b94, a.unk_e10_0.gpu_se_ki_1_dt.to_bits()), + (0x2b9c, a.unk_e10_0.unk_7c.to_bits()), + (0x2ba0, a.unk_e10_0.gpu_se_kp.to_bits()), + (0x2ba4, a.unk_e10_0.gpu_se_kp_1.to_bits()), + (0x2bac, a.unk_e10_0.unk_8c), (0x2bb0, a.unk_e10_0.max_pstate_scaled_1), + (0x2c10, a.unk_e10_0.unk_3c), (0x2c14, a.unk_e10_0.unk_38), + (0x2c28, a.unk_e10_0.gpu_se_reset_criteria), + (0x6ac8, 1), + ]); + for (at, value) in fields { + put32(policy, at, value); + } + put64(policy, 0xae0, u64::from(samples) * u64::from(pwr.pwr_sample_period_aic_clks)); + crate::pgtable::clean_poc(policy.as_ptr(), policy.len()); + Ok(()) + } +} + +/// The 13.5 hardware data's highest operating-point index. +fn old_max_pstate(base: &fw::initdata::RuntimePointersG14V13_5) -> Result { + Ok(base.hwdata_b.with(|old, _| old.max_pstate)) +} + +impl GpuManagerG14V13_5 { + pub(crate) fn new_render_buffer(&self, ualloc: Arc>, + ualloc_priv: Arc>) -> Result { + let mut alloc = self.alloc(); + buffer::BufferG14V13_5::new( + self, &mut alloc, ualloc, ualloc_priv, &self.buffer_mgr, + buffer::ParameterListPlacement::KernelGpu, + ) + } +} diff --git a/drivers/gpu/drm/asahi/hw/mod.rs b/drivers/gpu/drm/asahi/hw/mod.rs index a58fac5e12c372..67335112eef0bf 100644 --- a/drivers/gpu/drm/asahi/hw/mod.rs +++ b/drivers/gpu/drm/asahi/hw/mod.rs @@ -122,6 +122,30 @@ pub(crate) struct PowerZone { pub(crate) filter_tc: u32, } +/// Base of a window in the firmware 27.2 register table. +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +#[derive(Debug, Copy, Clone)] +pub(crate) enum RegisterBaseV27_2 { + /// A fixed physical address. + Physical(u64), + /// An offset into the GPU's SGX window (its `sgx` resource). + Sgx(u64), +} + +/// One record of the firmware 27.2 register table: 60 slots, each naming one window. +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +#[derive(Debug, Copy, Clone)] +pub(crate) struct RegisterV27_2 { + pub(crate) slot: usize, + pub(crate) base: RegisterBaseV27_2, + pub(crate) size: u32, + /// Offset of the window within the GPU's register space, as the record carries it. + pub(crate) relative: u64, + /// Where the window is mapped for the firmware: `None` leaves the record without a + /// mapping, `Some(0)` takes the next free MMIO VA, `Some(offset)` a fixed MMIO VA offset. + pub(crate) install: Option, +} + /// An MMIO mapping used by the firmware. #[derive(Debug, Copy, Clone)] pub(crate) struct IOMapping { @@ -448,6 +472,8 @@ pub(crate) struct PwrConfig { pub(crate) ppm_ki: F32, /// PPM (?) filter PID proportional gain. pub(crate) ppm_kp: F32, + /// Whether the board's DT/ADT explicitly supplied all four power-controller parameters. + pub(crate) pwr_controller_from_dt: bool, /// Power consumption filter time constant (periods?) pub(crate) pwr_filter_time_constant: u32, /// Power consumption filter PID integral gain. @@ -594,6 +620,34 @@ impl PwrConfig { }; let power_sample_period: u32 = prop!("apple,power-sample-period"); + let pwr_filter_tc_opt: Option = node + .get_opt_property(c_str!("apple,pwr-filter-time-constant")) + .map_err(|e| { + dev_err!(dev, "Error reading property apple,pwr-filter-time-constant: {:?}\n", e); + e + })?; + let pwr_ki_opt: Option = node + .get_opt_property(c_str!("apple,pwr-integral-gain")) + .map_err(|e| { + dev_err!(dev, "Error reading property apple,pwr-integral-gain: {:?}\n", e); + e + })?; + let pwr_clamp_opt: Option = node + .get_opt_property(c_str!("apple,pwr-integral-min-clamp")) + .map_err(|e| { + dev_err!(dev, "Error reading property apple,pwr-integral-min-clamp: {:?}\n", e); + e + })?; + let pwr_kp_opt: Option = node + .get_opt_property(c_str!("apple,pwr-proportional-gain")) + .map_err(|e| { + dev_err!(dev, "Error reading property apple,pwr-proportional-gain: {:?}\n", e); + e + })?; + let pwr_controller_from_dt = pwr_filter_tc_opt.is_some() + && pwr_ki_opt.is_some() + && pwr_clamp_opt.is_some() + && pwr_kp_opt.is_some(); Ok(PwrConfig { core_leak_coef, @@ -638,11 +692,12 @@ impl PwrConfig { ppm_filter_time_constant_ms: prop!("apple,ppm-filter-time-constant-ms"), ppm_ki: prop!("apple,ppm-ki"), ppm_kp: prop!("apple,ppm-kp"), - pwr_filter_time_constant: prop!("apple,pwr-filter-time-constant", 313), - pwr_integral_gain: prop!("apple,pwr-integral-gain", f32!(0.0202129)), - pwr_integral_min_clamp: prop!("apple,pwr-integral-min-clamp", 0), + pwr_controller_from_dt, + pwr_filter_time_constant: pwr_filter_tc_opt.unwrap_or(313), + pwr_integral_gain: pwr_ki_opt.unwrap_or(f32!(0.0202129)), + pwr_integral_min_clamp: pwr_clamp_opt.unwrap_or(0), pwr_min_duty_cycle: prop!("apple,pwr-min-duty-cycle"), - pwr_proportional_gain: prop!("apple,pwr-proportional-gain", f32!(5.2831855)), + pwr_proportional_gain: pwr_kp_opt.unwrap_or(f32!(5.2831855)), pwr_sample_period_aic_clks: prop!( "apple,pwr-sample-period-aic-clks", cfg.base_clock_hz / 1000 * power_sample_period diff --git a/drivers/gpu/drm/asahi/hw/t6040.rs b/drivers/gpu/drm/asahi/hw/t6040.rs index cfb369da993e9b..8b0ec17044b032 100644 --- a/drivers/gpu/drm/asahi/hw/t6040.rs +++ b/drivers/gpu/drm/asahi/hw/t6040.rs @@ -106,6 +106,18 @@ pub(crate) const CONFIG: Config = Config { 0x37, 0xee, 0x5d, 0x6e, 0x5e, 0x98, ], }, + crate::fwid::FirmwareBuild { + name: "Apple GFX 25G83 for T6040 (normalized loaded image, third alternate J616s fill)", + text_size: 0x60000, + data_size: 0x138000, + entropy: &[[0x59839, 0x5991c]], + boot_filled: &[], + text_sha256: [ + 0x19, 0xd9, 0x97, 0x49, 0x3e, 0x00, 0x76, 0x3d, 0xe3, 0x1f, 0x40, 0x0a, 0x59, + 0x2d, 0x8a, 0xea, 0xe6, 0xbd, 0x11, 0x72, 0xc5, 0x85, 0x96, 0x61, 0x78, 0x1b, + 0x42, 0x15, 0xde, 0xbc, 0x87, 0x0b, + ], + }, ], variant: &fw::variant::V25G83, config: None, diff --git a/drivers/gpu/drm/asahi/hw/t6041.rs b/drivers/gpu/drm/asahi/hw/t6041.rs index 30370e792e1695..4cce54372a3f81 100644 --- a/drivers/gpu/drm/asahi/hw/t6041.rs +++ b/drivers/gpu/drm/asahi/hw/t6041.rs @@ -79,9 +79,8 @@ const BUILDS: [fw::variant::Build; 5] = [ ..BUILD_25G83 }, fw::variant::Build { - name: "macOS 26.6.2 (25G83, iBoot mBoot-18000.161.10), 32 cores", config: Some(&super::t6041_25g83::CONFIG), - ..BUILD_25G83 + ..BUILD_25G83_32CORE }, fw::variant::Build { config: Some(&BASE), @@ -111,6 +110,7 @@ pub(super) const BUILD_26B123: fw::variant::Build = fw::variant::Build { }], variant: &fw::variant::Variant { ta_mode_1: true, + render_id_at_create: true, ..fw::variant::V26B123 }, config: None, @@ -141,8 +141,8 @@ const BUILD_25F84: fw::variant::Build = fw::variant::Build { /// The macOS 26.6.2 boot firmware (iBoot mBoot-18000.161.10) loads the 25G83 build the M4 Pro /// runs. iBoot fills part of the loaded TEXT for each Mac, so each admitted image is a -/// measurement. Four are listed: the 32-core J616C's, which runs with -/// [`super::t6041_25g83::CONFIG`], and the 40-core J614C's and J575C's, which run with +/// measurement. Four are listed: the 32-core J616C's, which runs via [`BUILD_25G83_32CORE`] +/// with [`super::t6041_25g83::CONFIG`], and the 40-core J614C's and J575C's, which run with /// [`CONFIG_25G83`]. The J575C's is measured with its boot-filled ranges zeroed, as is the /// J614C's under system firmware 27.2, whose iBoot fills the same ranges. pub(super) const BUILD_25G83: fw::variant::Build = fw::variant::Build { @@ -203,14 +203,37 @@ pub(super) const BUILD_25G83: fw::variant::Build = fw::variant::Build { ], }, ], - // Four clusters: the tiler segment values of 25F84 on this machine. + // 40-core T6041 parts (J614C, J575C) stay on TA mode 1 until clustered tiling is tested on + // 40-core hardware; 32-core parts run [`BUILD_25G83_32CORE`] below. + // T6041's 25G83 firmware emits pstate reports (tags 0x19/0x1b) and 8 ms + // timestamped utilisation records (tag 0x13). variant: &fw::variant::Variant { + // Tiling and fragment kicks wait on their own prefixes (host path, !m5_commands); + // unmeasured on the M4 Pro, which keeps false. + render_stage_prefixes: true, ta_mode_1: true, + telemetry_protocol: crate::g17::telemetry::Protocol::PSTATE_8MS, + render_id_at_create: true, ..fw::variant::V25G83 }, config: None, }; +/// 32-core T6041 (J616C) on 25G83: inherits the 25G83 image list (the 32- vs 40-core config +/// is chosen by probed core count) and tiles clustered with the four-cluster segment words +/// (`fw::m5::target::cluster_control`). A clustered RD32 Minecraft frame needs ~1600-2200 heap +/// blocks, past the 0x45e normal maximum, and at that maximum a four-cluster pass never starts +/// (reason 0 recoveries), so the heap may use every slot of the block table. +pub(super) const BUILD_25G83_32CORE: fw::variant::Build = fw::variant::Build { + name: "macOS 26.6.2 (25G83, iBoot mBoot-18000.161.10), 32 cores", + variant: &fw::variant::Variant { + ta_mode_1: false, + tvb_normal_blocks: crate::g17::fw::buffer::NORMAL_MAX_BLOCKS_FOUR_CLUSTERS, + ..*BUILD_25G83.variant + }, + ..BUILD_25G83 +}; + /// The 40-core M4 Max on 25G83: the 25F84 configuration with the 25G83 register map and /// [`CHIP_25G83`]. const CONFIG_25G83: Config = Config { @@ -218,6 +241,8 @@ const CONFIG_25G83: Config = Config { reserved_slots: &[], chip: Some(&CHIP_25G83), firmware: fw::variant::Firmware::Identified(&[BUILD_25G83]), + // The GPU is restarted after a real sleep, as on the 32-core part. + sleep_restart: true, ..BASE }; @@ -387,16 +412,33 @@ const CHIP: v25g83::Chip = v25g83::Chip { cs_perf_table: false, }; -/// [`CHIP`] for 25G83: its hardware data has 0 at `+0x2610`. +/// [`CHIP`] for 25G83: its hardware data has 0 at `+0x2610`, and its power configuration keeps +/// the 25G83 starting values of the performance limiter ([`POWER_CONFIG_WORDS_25G83`]). /// /// 25F84 runs with 1 there. On 25G83 the 40-core J614C then accepts work and marks it done, /// but the GPU never runs it: no completion, no fault, every job times out. With 0, which is /// also what the J616C's 25G83 contents have, compute and render work run. const CHIP_25G83: v25g83::Chip = v25g83::Chip { hw_data_words: HW_DATA_WORDS_25G83, + power_config_words: POWER_CONFIG_WORDS_25G83, ..CHIP }; +/// [`POWER_CONFIG_WORDS`] without its first three words, `+0x0 = 1`, `+0x44 = 0xc` and +/// `+0x9c = 338.0`. +/// +/// They are state the firmware writes into its performance limiter while it runs (it sets +/// `+0x44` to 0xc itself, and `+0x9c` reaches 338.0 once the limit is at its floor), measured +/// from a running 25F84. Started with them, the 25G83 firmware lowers the limit at `+0x48` +/// (1000 at boot) on cold GPU power-ups and never raises it again: on the 40-core J575C it +/// reached 162 after 6,000 short Vulkan clients and the GPU ran at 46 % of its speed until a +/// reboot. With the 25G83 starting values (`+0x44 = 1`, as the M4 Pro and the J616C run), +/// the limit stays at 1000. +const POWER_CONFIG_WORDS_25G83: &[(usize, u32, usize)] = match POWER_CONFIG_WORDS { + [(0x0, 0x1, 1), (0x44, 0xc, 1), (0x9c, 0x43a9_0000, 1), rest @ ..] => rest, + _ => panic!("the first T6041 power configuration words must be +0x0, +0x44 and +0x9c"), +}; + /// [`HW_DATA_WORDS`] without its last word, `+0x2610 = 1`. const HW_DATA_WORDS_25G83: &[(usize, u32, usize)] = match HW_DATA_WORDS.split_last() { Some((&(0x2610, 1, 1), rest)) => rest, diff --git a/drivers/gpu/drm/asahi/hw/t6041_25g83.rs b/drivers/gpu/drm/asahi/hw/t6041_25g83.rs index 955e45e14d2c3c..4afc2179f5632b 100644 --- a/drivers/gpu/drm/asahi/hw/t6041_25g83.rs +++ b/drivers/gpu/drm/asahi/hw/t6041_25g83.rs @@ -47,7 +47,7 @@ pub(super) const CONFIG: Config = Config { perf: Some(&PERF), region_c: Some(®ION_C), chip: Some(&CHIP), - firmware: fw::variant::Firmware::Identified(&[t6041::BUILD_25G83, t6041::BUILD_26B123]), + firmware: fw::variant::Firmware::Identified(&[t6041::BUILD_25G83_32CORE, t6041::BUILD_26B123]), core_layout: CoreLayout { cores: Some((4, 32)), alternate_core_masks: None, @@ -60,6 +60,8 @@ pub(super) const CONFIG: Config = Config { // hang this GPU's firmware on grids of more than ten workgroups. compute_blocks: 96, }, + // The GPU is restarted after a real sleep, as on T8140. + sleep_restart: true, ..t6041::BASE }; diff --git a/drivers/gpu/drm/asahi/hw/t6050.rs b/drivers/gpu/drm/asahi/hw/t6050.rs index 4ea3862efd4cbb..b8d783a6284249 100644 --- a/drivers/gpu/drm/asahi/hw/t6050.rs +++ b/drivers/gpu/drm/asahi/hw/t6050.rs @@ -43,33 +43,94 @@ pub(crate) const CONFIG: Config = Config { sleep_restart: false, recovery_slot_keys: None, gpu_generation: GpuGen::G17, - // The firmware in `fw-text` must be this build. iBoot loads the G17S build of both roles - // back to back: the primary's TEXT 0x50000, then the secondary's 0x54000, with the same - // entropy records and boot-filled ranges as the M5 Max. The digest is that of the - // firmware's TEXT with those ranges zeroed, measured on two J714s boots. - firmware: crate::g17::fw::variant::Firmware::Identified(&[crate::g17::fw::variant::Build { - os_version: [27, 0, 0], - name: "27.0 (26A428), G17S", - images: &[ - crate::fwid::FirmwareBuild { - name: "26A428 for T6050 G17S, primary then secondary", + // The firmware in `fw-text` must be one of these builds. iBoot loads the G17S build of both + // roles back to back: the primary's text at 0x50000 of `fw-text`, then the secondary's at + // 0x54000, with the same entropy records and boot-filled ranges as the M5 Max (27.2 moves the + // primary's records by a few bytes). Each digest is that of the firmware's text with + // those ranges zeroed, a loaded copy normalizing to it on every boot. Newest first. + firmware: crate::g17::fw::variant::Firmware::Identified(&[ + // The 27.2 build of the Mac17,10 to Mac17,13 restore image (K114, K116), which iBoot + // loads on the K116s: the a010 images whose Mach-O UUIDs are the ADT's iop-gfx-nub and + // iop-gfx1-nub uuid. Its records and sections sit where 26B123's do, and on the K116s + // both firmware roles accepted the 26B123 InitData (V26B123_M5) and ran it. + crate::g17::fw::variant::Build { + os_version: [27, 2, 0], + name: "27.2 (26B8125), G17S", + images: &[crate::fwid::FirmwareBuild { + name: "26B8125 for T6050 G17S, primary then secondary", text_size: 0xa4000, data_size: 0x184000, - entropy: &[[0x49e60, 0x49f43], [0x9d918, 0x9d9fb]], + entropy: &[[0x49ea4, 0x49f87], [0x9d92c, 0x9da0f]], boot_filled: &[ - (0x224, 4), (0x23c, 8), (0x49720, 0x740), (0x49e60, 0x231), - (0x50224, 4), (0x5023c, 8), (0x9d1d8, 0x740), (0x9d918, 0x231), + (0x224, 4), + (0x23c, 8), + (0x49764, 0x740), + (0x49ea4, 0x231), + (0x50224, 4), + (0x5023c, 8), + (0x9d1ec, 0x740), + (0x9d92c, 0x231), ], text_sha256: [ - 0x85, 0xd0, 0xfd, 0x82, 0x80, 0xf7, 0x24, 0x65, 0x5c, 0xa9, 0xa9, 0x71, 0x7b, - 0xc9, 0x1a, 0x8a, 0x5e, 0xf6, 0x09, 0x28, 0xd7, 0x72, 0x00, 0xf6, 0xd5, 0x3b, - 0xd0, 0x99, 0xb9, 0x47, 0x39, 0xc6, + 0xaf, 0x68, 0xd0, 0x34, 0xa3, 0xf0, 0x06, 0xb4, 0x3d, 0xab, 0x66, 0x1b, 0x82, + 0x5f, 0x12, 0x59, 0x8c, 0xb8, 0x6e, 0x4d, 0x2a, 0x0e, 0x38, 0x44, 0xf1, 0x4f, + 0xa5, 0x05, 0x9f, 0x38, 0xf6, 0xcb, ], - }, - ], - variant: &crate::g17::fw::variant::V26A428_M5, - config: None, - }]), + }], + variant: &crate::g17::fw::variant::V26B123_M5, + config: None, + }, + crate::g17::fw::variant::Build { + os_version: [27, 2, 0], + name: "27.2 (26B123), G17S", + images: &[crate::fwid::FirmwareBuild { + name: "26B123 for T6050 G17S, primary then secondary", + text_size: 0xa4000, + data_size: 0x184000, + entropy: &[[0x49ea4, 0x49f87], [0x9d92c, 0x9da0f]], + boot_filled: &[ + (0x224, 4), + (0x23c, 8), + (0x49764, 0x740), + (0x49ea4, 0x231), + (0x50224, 4), + (0x5023c, 8), + (0x9d1ec, 0x740), + (0x9d92c, 0x231), + ], + text_sha256: [ + 0x2b, 0x46, 0x13, 0xc6, 0x2a, 0x8a, 0x00, 0x7f, 0x22, 0xa9, 0x41, 0x01, 0x70, + 0x2c, 0x9a, 0xc6, 0xc4, 0xe9, 0x0f, 0x2e, 0x12, 0x3f, 0x3b, 0x36, 0xfb, 0xe6, + 0xff, 0xea, 0x91, 0x3f, 0x0f, 0xd9, + ], + }], + variant: &crate::g17::fw::variant::V26B123_M5, + config: None, + }, + crate::g17::fw::variant::Build { + os_version: [27, 0, 0], + name: "27.0 (26A428), G17S", + images: &[ + crate::fwid::FirmwareBuild { + name: "26A428 for T6050 G17S, primary then secondary", + text_size: 0xa4000, + data_size: 0x184000, + entropy: &[[0x49e60, 0x49f43], [0x9d918, 0x9d9fb]], + boot_filled: &[ + (0x224, 4), (0x23c, 8), (0x49720, 0x740), (0x49e60, 0x231), + (0x50224, 4), (0x5023c, 8), (0x9d1d8, 0x740), (0x9d918, 0x231), + ], + text_sha256: [ + 0x85, 0xd0, 0xfd, 0x82, 0x80, 0xf7, 0x24, 0x65, 0x5c, 0xa9, 0xa9, 0x71, + 0x7b, 0xc9, 0x1a, 0x8a, 0x5e, 0xf6, 0x09, 0x28, 0xd7, 0x72, 0x00, 0xf6, + 0xd5, 0x3b, 0xd0, 0x99, 0xb9, 0x47, 0x39, 0xc6, + ], + }, + ], + variant: &crate::g17::fw::variant::V26A428_M5, + config: None, + }, + ]), // Two clusters of ten cores. The buffers are sized for every core slot of the board, so the // board's cluster and slot counts admit the GPU, whichever cores are fused off. core_layout: CoreLayout { @@ -114,33 +175,64 @@ pub(crate) const CONFIG_MAX: Config = Config { sleep_restart: false, recovery_slot_keys: None, gpu_generation: GpuGen::G17, - // As on the M5 Ultra, the firmware in `fw-text` must be this build. The boot loader loads - // the G17C build of both roles back to back: the primary's TEXT 0x50000, then the + // As on the M5 Ultra, the firmware in `fw-text` must be one of these builds. The boot loader + // loads the G17C build of both roles back to back: the primary's TEXT 0x50000, then the // secondary's 0x54000. The digest is that of the firmware's TEXT with the boot-filled ranges // zeroed. - firmware: crate::g17::fw::variant::Firmware::Identified(&[crate::g17::fw::variant::Build { - os_version: [27, 0, 0], - name: "27.0 (26A428), G17C", - images: &[ - crate::fwid::FirmwareBuild { - name: "26A428 for T6050 G17C, primary then secondary", + firmware: crate::g17::fw::variant::Firmware::Identified(&[ + // The 27.2 (26B123) a000 images: the records and boot-filled ranges sit where the G17S + // build's do. The digest is that of the stock images with those ranges zeroed. + crate::g17::fw::variant::Build { + os_version: [27, 2, 0], + name: "27.2 (26B123), G17C", + images: &[crate::fwid::FirmwareBuild { + name: "26B123 for T6050 G17C, primary then secondary", text_size: 0xa4000, data_size: 0x184000, - entropy: &[[0x49e60, 0x49f43], [0x9d918, 0x9d9fb]], + entropy: &[[0x49ea4, 0x49f87], [0x9d92c, 0x9da0f]], boot_filled: &[ - (0x224, 4), (0x23c, 8), (0x49720, 0x740), (0x49e60, 0x231), - (0x50224, 4), (0x5023c, 8), (0x9d1d8, 0x740), (0x9d918, 0x231), + (0x224, 4), + (0x23c, 8), + (0x49764, 0x740), + (0x49ea4, 0x231), + (0x50224, 4), + (0x5023c, 8), + (0x9d1ec, 0x740), + (0x9d92c, 0x231), ], text_sha256: [ - 0x30, 0x4d, 0x85, 0x44, 0x66, 0x29, 0xbc, 0xdc, 0xa5, 0x95, 0x80, 0xb5, 0xff, - 0x00, 0x6d, 0xd8, 0x9f, 0x2c, 0xd8, 0xb4, 0xca, 0x60, 0x59, 0x9a, 0x0c, 0xb5, - 0x5c, 0x35, 0xec, 0xb0, 0x98, 0xf4, + 0x66, 0x48, 0xec, 0xe7, 0xe8, 0xc6, 0xb7, 0xb8, 0x28, 0x44, 0x36, 0x8f, 0x0e, + 0x07, 0x5a, 0x21, 0x80, 0xa0, 0x8c, 0xa3, 0x5f, 0xee, 0xd0, 0xb6, 0xe3, 0xf5, + 0x48, 0x71, 0x0d, 0x4d, 0xdb, 0x81, ], - }, - ], - variant: &crate::g17::fw::variant::V26A428_M5, - config: None, - }]), + }], + variant: &crate::g17::fw::variant::V26B123_M5, + config: None, + }, + crate::g17::fw::variant::Build { + os_version: [27, 0, 0], + name: "27.0 (26A428), G17C", + images: &[ + crate::fwid::FirmwareBuild { + name: "26A428 for T6050 G17C, primary then secondary", + text_size: 0xa4000, + data_size: 0x184000, + entropy: &[[0x49e60, 0x49f43], [0x9d918, 0x9d9fb]], + boot_filled: &[ + (0x224, 4), (0x23c, 8), (0x49720, 0x740), (0x49e60, 0x231), + (0x50224, 4), (0x5023c, 8), (0x9d1d8, 0x740), (0x9d918, 0x231), + ], + text_sha256: [ + 0x30, 0x4d, 0x85, 0x44, 0x66, 0x29, 0xbc, 0xdc, 0xa5, 0x95, 0x80, 0xb5, + 0xff, 0x00, 0x6d, 0xd8, 0x9f, 0x2c, 0xd8, 0xb4, 0xca, 0x60, 0x59, 0x9a, + 0x0c, 0xb5, 0x5c, 0x35, 0xec, 0xb0, 0x98, 0xf4, + ], + }, + ], + variant: &crate::g17::fw::variant::V26A428_M5, + config: None, + }, + ]), // Four clusters of ten cores. The buffers are sized for every core slot of the board, so the // board's cluster and slot counts admit the GPU, whichever cores are fused off. core_layout: CoreLayout { diff --git a/drivers/gpu/drm/asahi/hw/t8103.rs b/drivers/gpu/drm/asahi/hw/t8103.rs index a2a76600c0a3bb..261e51fbc4c83f 100644 --- a/drivers/gpu/drm/asahi/hw/t8103.rs +++ b/drivers/gpu/drm/asahi/hw/t8103.rs @@ -91,3 +91,60 @@ pub(crate) const HWCONFIG: super::HwConfig = HwConfig { sram_base: None, sram_size: None, }; + +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +const fn reg( + slot: usize, + base: RegisterBaseV27_2, + size: u32, + relative: u64, + install: Option, +) -> RegisterV27_2 { + RegisterV27_2 { + slot, + base, + size, + relative, + install, + } +} + +/// The firmware 27.2 register table for T8103 (G13G). Writable windows outside SGX and the +/// PMP/PMGR telemetry apertures (slots 2 and 5) are left unmapped. +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +pub(crate) const REGISTERS_V27_2: &[RegisterV27_2] = { + use RegisterBaseV27_2::{Physical, Sgx}; + &[ + reg(0, Physical(0x23b104000), 0x4000, 0, None), // AIC software interrupt + reg(1, Physical(0x23b2e8000), 0x1000, 0, Some(0)), // Analog temperature controller + reg(2, Physical(0x23bc00000), 0x1000, 0, Some(0)), // PMP doorbell + reg(3, Physical(0x200004000), 0x50000, 0, None), // Memory cache + reg(5, Physical(0x23b738000), 0x1000, 0, Some(0)), // PMGR scratch / PMP telemetry + reg(12, Physical(0x26b45c000), 0x4000, 0, None), // ANE doorbell + reg(17, Sgx(0), 0x20000, 0, Some(0)), // GPU core + reg(31, Sgx(0xd04000), 0xc000, 0xd04000, Some(0)), // Fender configuration + reg(32, Sgx(0xd61000), 0x1000, 0xd61000, Some(0)), // GIFAF + reg(34, Sgx(0xd10000), 0x4000, 0xd10000, Some(0)), // CPMS + reg(37, Sgx(0xe10000), 0x1000, 0xe10000, Some(0)), // Fender scratch RAM + reg(38, Sgx(0xd18000), 0x4000, 0xd18000, Some(0)), // Fender clock/power + reg(40, Sgx(0xd00000), 0x4000, 0xd00000, Some(0)), // Fender multi-GPU configuration + reg(44, Sgx(0xd80000), 0x5000, 0, Some(0)), // Metrology sensors + ] +}; + +/// Slots of the T8103 27.2 register table whose stock mode is read-write (no slot 9 telemetry). +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +pub(crate) const WRITABLE_V27_2: u64 = { + let mut mask = 0u64; + let mut slot = 0; + while slot < 60 { + if matches!( + slot, + 0 | 2 | 3 | 5..=8 | 12 | 17 | 25..=27 | 31..=40 | 42..=48 | 52..=55 | 58 + ) { + mask |= 1 << slot; + } + slot += 1; + } + mask +}; diff --git a/drivers/gpu/drm/asahi/hw/t8112.rs b/drivers/gpu/drm/asahi/hw/t8112.rs index bac2757175f2c2..d22238d90247b1 100644 --- a/drivers/gpu/drm/asahi/hw/t8112.rs +++ b/drivers/gpu/drm/asahi/hw/t8112.rs @@ -104,3 +104,47 @@ pub(crate) const HWCONFIG: super::HwConfig = HwConfig { sram_base: None, sram_size: None, }; + +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +const fn reg(slot: usize, base: RegisterBaseV27_2, size: u32, relative: u64, install: Option) -> RegisterV27_2 { + RegisterV27_2 { slot, base, size, relative, install } +} + +/// The firmware 27.2 register table. Writable windows outside SGX are left unmapped, except +/// the push-telemetry window (slot 9), which the firmware shares with the PMP; it is mapped +/// apart from the others. +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +pub(crate) const REGISTERS_V27_2: &[RegisterV27_2] = { + use RegisterBaseV27_2::{Physical, Sgx}; + &[ + reg(0, Physical(0x23b0c4000), 0x4000, 0, None), // AIC software interrupt + reg(1, Physical(0x23b2c0000), 0x1000, 0, Some(0)), // Analog temperature controller + reg(3, Physical(0x200f04000), 0x18000, 0, None), // Memory cache + reg(8, Physical(0x27d050000), 0x4000, 0, None), // Streaming codec + reg(9, Physical(0x23b3d0000), 0x1000, 0, Some(0x10_0000)), // Push telemetry + reg(10, Physical(0x23b3c0000), 0x1000, 0, Some(0)), // Push telemetry readback + reg(12, Physical(0x26b45c000), 0x4000, 0, None), // ANE doorbell + reg(17, Sgx(0), 0x20000, 0, Some(0)), // GPU core + reg(31, Sgx(0xd04000), 0xc000, 0xd04000, Some(0)), // Fender configuration + reg(32, Sgx(0xd61000), 0x1000, 0xd61000, Some(0)), // GIFAF + reg(33, Sgx(0xe0c000), 0x4000, 0xe0c000, Some(0)), // CRE + reg(34, Sgx(0xd10000), 0x4000, 0xd10000, Some(0)), // CPMS + reg(37, Sgx(0xe10000), 0x1000, 0xe10000, Some(0)), // Fender scratch RAM + reg(40, Sgx(0xd00000), 0x4000, 0xd00000, Some(0)), // Fender multi-GPU configuration + reg(44, Sgx(0xd80000), 0x8000, 0, Some(0)), // Metrology sensors + ] +}; + +/// Slots of the 27.2 register table whose stock mode is read-write. +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +pub(crate) const WRITABLE_V27_2: u64 = { + let mut mask = 0u64; + let mut slot = 0; + while slot < 60 { + if matches!(slot, 0 | 2 | 3 | 5..=9 | 12 | 17 | 25..=27 | 31..=40 | 42..=48 | 52..=55 | 58) { + mask |= 1 << slot; + } + slot += 1; + } + mask +}; diff --git a/drivers/gpu/drm/asahi/hw/t8140.rs b/drivers/gpu/drm/asahi/hw/t8140.rs index 01651405655678..bfa192d58d8ca2 100644 --- a/drivers/gpu/drm/asahi/hw/t8140.rs +++ b/drivers/gpu/drm/asahi/hw/t8140.rs @@ -453,7 +453,7 @@ pub(crate) mod queues { pub(crate) const RENDER_SLOTS: usize = 64; // The QID budget reserves one physical pair per logical owner, which // leaves room for every execution context in the shared 128-QID - // namespace. A second pair comes only from surplus, on G17D + // namespace. A second pair comes only from surplus, on G17C and G17D // (g17::pairs). Commands queue at RENDER_DEPTH per pair, as many as a pair // has command records (the render memory's RECORDS). pub(crate) const RENDER_PAIRS_MAX: usize = 2; diff --git a/drivers/gpu/drm/asahi/m3/agx_compute.rs b/drivers/gpu/drm/asahi/m3/agx_compute.rs index d58005c504f7ac..28c2cb592feb42 100644 --- a/drivers/gpu/drm/asahi/m3/agx_compute.rs +++ b/drivers/gpu/drm/asahi/m3/agx_compute.rs @@ -6,4 +6,14 @@ pub(crate) struct Control { pub base: u64, pub end: u64, pub usc_base: u64, + /// The helper program, zero unless the queue's command builder encodes it + /// (`m3_submit::Queue::samplers_and_helpers`). + #[cfg_attr(not(CONFIG_DRM_ASAHI_G14_V27_2), allow(dead_code))] + pub helper: crate::m3::agx_uapi::UapiHelperProgram, + /// The sampler heap and its sampler count, both zero unless the queue's command builder + /// encodes them (`m3_submit::Queue::samplers_and_helpers`). + #[cfg_attr(not(CONFIG_DRM_ASAHI_G14_V27_2), allow(dead_code))] + pub sampler_heap: u64, + #[cfg_attr(not(CONFIG_DRM_ASAHI_G14_V27_2), allow(dead_code))] + pub sampler_count: u32, } diff --git a/drivers/gpu/drm/asahi/m3/agx_status.rs b/drivers/gpu/drm/asahi/m3/agx_status.rs deleted file mode 100644 index 1d83086a1d155f..00000000000000 --- a/drivers/gpu/drm/asahi/m3/agx_status.rs +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT -//! CPU-owned sticky VM failure reporting. No GPU mapping or firmware access. -use core::sync::atomic::{AtomicI32, Ordering}; - -pub(crate) const PARAM_GROUP_VM_STATUS: u32 = 1; -pub(crate) const FEATURE_VM_STATUS: u64 = 1 << 1; -pub(crate) const VM_STATUS_SIZE: usize = 16; - -/// Shared by the VM and accepted jobs; never cleared by queue destruction or -/// successful work. A newly created VM receives a new status object. -pub(crate) struct VmStatus { error: AtomicI32 } -impl VmStatus { - pub(crate) fn new() -> Self { Self { error: AtomicI32::new(0) } } - pub(crate) fn record(&self, error: i32) { - if error < 0 { - let _ = self.error.compare_exchange(0, error, Ordering::AcqRel, Ordering::Acquire); - } - } - pub(crate) fn get(&self) -> i32 { self.error.load(Ordering::Acquire) } -} - -/// GET_PARAMS group 1 is an in/out request: vm_id, flags=0, error(out), pad=0. -/// Decode once, before lookup, so a racing userspace edit cannot change owner. -pub(crate) fn decode_request(bytes: &[u8; VM_STATUS_SIZE]) -> Option { - let word = |i| u32::from_ne_bytes(bytes[i..i+4].try_into().unwrap()); - if word(4) != 0 || word(12) != 0 { return None; } - Some(word(0)) -} -pub(crate) fn encode_response(vm_id: u32, error: i32) -> [u8; VM_STATUS_SIZE] { - let mut bytes = [0; VM_STATUS_SIZE]; - bytes[0..4].copy_from_slice(&vm_id.to_ne_bytes()); - bytes[8..12].copy_from_slice(&error.to_ne_bytes()); - bytes -} diff --git a/drivers/gpu/drm/asahi/m3/agx_uapi.rs b/drivers/gpu/drm/asahi/m3/agx_uapi.rs index 60107f8833edc2..64912fffadb99e 100644 --- a/drivers/gpu/drm/asahi/m3/agx_uapi.rs +++ b/drivers/gpu/drm/asahi/m3/agx_uapi.rs @@ -574,7 +574,7 @@ impl QueueUscWindow { } } -fn validate_sampler( +pub(crate) fn validate_sampler( address_space: &A, heap: u64, count: u32, @@ -599,6 +599,31 @@ fn validate_sampler( Ok(()) } +/// Validates a helper program descriptor for a queue whose commands encode helpers: either no +/// helper (all fields zero), or a tagged program offset that names a readable program in the +/// queue's USC window and an 8-byte-aligned argument block that the submitting VM maps +/// read-write. The configuration word is only accepted together with a program. +pub(crate) fn validate_helper( + queue: QueueUscWindow, + address_space: &A, + helper: UapiHelperProgram, +) -> Result<(), UapiTranslateError> { + if helper + == (UapiHelperProgram { + binary: 0, + config: 0, + data: 0, + }) + { + return Ok(()); + } + queue.full_program(address_space, helper.binary)?; + if helper.data & 7 != 0 { + return Err(UapiTranslateError::AddressAlignment); + } + require_range(address_space, helper.data, 8, GpuAccess::ReadWrite) +} + pub(crate) fn validate_attachments( address_space: &A, attachments: &UapiAttachmentList, diff --git a/drivers/gpu/drm/asahi/m3/hw.rs b/drivers/gpu/drm/asahi/m3/hw.rs index a774f5de6573f5..ae1041d70c3ec7 100644 --- a/drivers/gpu/drm/asahi/m3/hw.rs +++ b/drivers/gpu/drm/asahi/m3/hw.rs @@ -15,7 +15,6 @@ const MAX_POWERZONES: usize = 5; /// J516S runtime ADT perf-states-sram table floors SRAM at 810 mV (7.1.12 `hw::t6030`). const G15_MIN_SRAM_MICROVOLT: u32 = 810_000; -pub(crate) mod agx3; pub(crate) mod t8122; /// GPU revision enumeration. Note: Part of the UABI. diff --git a/drivers/gpu/drm/asahi/m3/hw/agx3.rs b/drivers/gpu/drm/asahi/m3/hw/agx3.rs deleted file mode 100644 index f5e6ad607ec25d..00000000000000 --- a/drivers/gpu/drm/asahi/m3/hw/agx3.rs +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT - - -#[cfg(not(test))] -use crate::m3::identity::{GpuGen, GpuVariant}; -#[cfg(test)] -#[path = "../identity.rs"] -mod identity; -#[cfg(test)] -use identity::{GpuGen, GpuVariant}; - -/// Identification-only configuration for one AGX3 SoC. -#[derive(Debug)] -pub(crate) struct SocConfig { - /// Chip ID in hex format (e.g. 0x6050 for t6050). - pub(crate) chip_id: u32, - /// Decoded design generation for this chip. - pub(crate) gpu_gen: GpuGen, - /// Decoded variant for this chip. - pub(crate) gpu_variant: GpuVariant, - /// Hardware family byte expected at `0xd04000[31:24]`. - pub(crate) hw_family: u8, - /// Hardware variant byte expected at `0xd04000[23:16]`. - pub(crate) hw_variant: u8, - /// Die count expected at `0xd04010[19:16]`. - pub(crate) num_dies: u32, - /// Input-address bits per UAT root (42 on every AGX3 part). - pub(crate) uat_ias: u8, - /// Output address space (42-bit on every AGX3 part). - pub(crate) uat_oas: u32, -} - -const fn agx3( - chip_id: u32, - gpu_gen: GpuGen, - gpu_variant: GpuVariant, - hw_family: u8, - hw_variant: u8, - num_dies: u32, -) -> SocConfig { - SocConfig { - chip_id, - gpu_gen, - gpu_variant, - hw_family, - hw_variant, - num_dies, - uat_ias: 42, - uat_oas: 42, - } -} - -pub(crate) const T8122: SocConfig = agx3(0x8122, GpuGen::G15, GpuVariant::G, 0x7, 2, 1); -/// Apple M3 Pro (G15S). -pub(crate) const T6030: SocConfig = agx3(0x6030, GpuGen::G15, GpuVariant::S, 0x7, 3, 1); -/// Apple M3 Max (G15C). -pub(crate) const T6031: SocConfig = agx3(0x6031, GpuGen::G15, GpuVariant::C, 0x7, 4, 1); -/// Apple M3 Ultra (G15D, two dies). -pub(crate) const T6032: SocConfig = agx3(0x6032, GpuGen::G15, GpuVariant::D, 0x7, 4, 2); diff --git a/drivers/gpu/drm/asahi/m3/hw/t8122.rs b/drivers/gpu/drm/asahi/m3/hw/t8122.rs index 5ba6b0ef6acd6f..555c65834fe1d4 100644 --- a/drivers/gpu/drm/asahi/m3/hw/t8122.rs +++ b/drivers/gpu/drm/asahi/m3/hw/t8122.rs @@ -76,7 +76,7 @@ pub(crate) const HWCONFIG_T8122: super::HwConfig = HwConfig { // The 24 MHz reference clock (HwDataB base_clock_khz = 24000). base_clock_hz: 24_000_000, - // 42-bit UAT roots and output addresses, as on every AGX3 part (hw::agx3::T8122). + // 42-bit UAT roots and output addresses, as on every AGX3 part. uat_ias: 42, uat_oas: 42, num_dies: 1, // ID_COUNTS_1[19:16] diff --git a/drivers/gpu/drm/asahi/m3/m3_board.rs b/drivers/gpu/drm/asahi/m3/m3_board.rs index 5d4ea4277b6181..12b8409296ef6c 100644 --- a/drivers/gpu/drm/asahi/m3/m3_board.rs +++ b/drivers/gpu/drm/asahi/m3/m3_board.rs @@ -23,11 +23,14 @@ pub(crate) fn board_is(compatible: &[u8]) -> bool { board.split(|b| *b == 0).any(|s| s == compatible) } -/// Whether this is a board the M3 runtime is validated on (`soc.validated_boards`). -/// `asahi.m3_expose=auto` registers the render node and `asahi.m3_backend=auto` starts the -/// runtime only on these. -pub(crate) fn runtime_validated_board(soc: &Soc) -> bool { - soc.validated_boards.iter().any(|board| board_is(board)) +/// Whether the boot loader handed this GPU over: the GPU node carries the boot loader's +/// description of the firmware it loaded (`SEGMENT_PROPS`). A boot loader publishes it only on +/// a Mac where it runs that firmware for Linux, so this follows what the machine describes, +/// not a list of boards. `asahi.m3_expose=auto` registers the render node, and the runtime +/// starts by default, only then; resource admission ([`admit`]) checks the rest of the handoff. +pub(crate) fn handed_over(dev: &device::Device) -> bool { + dev.of_node() + .is_some_and(|node| SEGMENT_PROPS.iter().all(|p| node.get_property::>(p).is_ok())) } /// The number of core slots of `soc` (2 x 10 on T6030, 4 x 10 on T6031). @@ -547,12 +550,12 @@ pub(crate) fn region_is_nomap(node: &of::Node, name: &CStr) -> bool { /// Whether the M3 render node is registered (`asahi.m3_expose`). /// -/// Userspace drivers pick up any registered render node. Until the M3 runtime is validated on a -/// board, a render node there would let a stock userspace driver submit work the board may not -/// run correctly. `auto` (-1) registers it only on the boards the runtime was validated on. -pub(crate) fn expose_render_node(soc: &Soc) -> bool { +/// Userspace drivers pick up any registered render node. Without a boot loader that handed the +/// GPU over, a render node would let a stock userspace driver submit work nothing can run. +/// `auto` (-1) registers it only where the boot loader handed the GPU over ([`handed_over`]). +pub(crate) fn expose_render_node(dev: &device::Device) -> bool { match crate::m3::m3_params::expose() { Some(expose) => expose, - None => runtime_validated_board(soc), + None => handed_over(dev), } } diff --git a/drivers/gpu/drm/asahi/m3/m3_channel_format.rs b/drivers/gpu/drm/asahi/m3/m3_channel_format.rs index 45eebda112b738..4d2217697cf62c 100644 --- a/drivers/gpu/drm/asahi/m3/m3_channel_format.rs +++ b/drivers/gpu/drm/asahi/m3/m3_channel_format.rs @@ -7,6 +7,30 @@ use super::m3_init_layout::Error; pub(crate) const CONTROL_BYTES: usize = 64; pub(crate) const RECEIVE_BYTES: usize = 72; pub(crate) const SLOTS: u32 = 256; +pub(crate) const SUBMISSION_BYTES: usize = 0x18; +/// Two firmware engine classes for each of the three data masters. +pub(crate) const ENGINE_CLASSES: u32 = 6; + +/// Submission-channel wire entry. The M3 runtime writes it for both of its +/// profiles (14.8.3 Legacy and 26.6.2 Extended) through `m3_config::submit_queue`, +/// which has no per-profile layout; the G14G firmware-27.2 path (26B123) writes the +/// same entry. The caller owns the queue and publishes its contents before +/// advancing the channel's shared write index. +pub(crate) fn submission_entry( + selector: u32, queue: u64, position: u16, stamp: u8, first: bool, +) -> Result<[u8; SUBMISSION_BYTES], Error> { + if selector > 2 { + return Err(Error::Bounds); + } + let mut entry = [0; SUBMISSION_BYTES]; + entry[8..16].copy_from_slice(&queue.to_le_bytes()); + entry[16..20].copy_from_slice(&selector.to_le_bytes()); + entry[20..22].copy_from_slice(&position.to_le_bytes()); + entry[22] = stamp; + entry[23] = u8::from(first); + Ok(entry) +} + #[derive(Clone, Copy, Debug)] pub(crate) enum Action { @@ -163,6 +187,18 @@ mod tests { assert!(payload_offset(9, 0).is_err()); } + #[test] + fn first_and_reused_compute_entries_match_the_26b123_wire_format() { + let expected = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0x40, 0x12, 0x34, 0xa0, 0xff, 0xff, + 0xff, 2, 0, 0, 0, 0x23, 1, 7, 1]; + let queue = 0xffff_ffa0_3412_4000; + assert_eq!(submission_entry(2, queue, 0x123, 7, true).unwrap(), expected); + let reused = submission_entry(2, queue, 0x123, 7, false).unwrap(); + assert_eq!(&reused[..23], &expected[..23]); + assert_eq!(reused[23], 0); + assert!(submission_entry(3, queue, 0, 0, true).is_err()); + } + #[test] fn release_uses_the_packed_owned_pointer() { let action = Action::Release { diff --git a/drivers/gpu/drm/asahi/m3/m3_client.rs b/drivers/gpu/drm/asahi/m3/m3_client.rs index c1a07d61120d13..7d9169fe1ecc0f 100644 --- a/drivers/gpu/drm/asahi/m3/m3_client.rs +++ b/drivers/gpu/drm/asahi/m3/m3_client.rs @@ -63,7 +63,7 @@ pub(crate) fn admit_vm_for( let refusals = REFUSALS.fetch_add(1, Ordering::Relaxed).saturating_add(1); if refusals <= REFUSALS_LOGGED { let task = kernel::current!(); - let comm = task_comm(task); + let comm = super::m3_submit::task_comm(task); let len = comm.iter().position(|&b| b == 0).unwrap_or(comm.len()); let name = core::str::from_utf8(&comm[..len]).unwrap_or("?"); let last = if refusals == REFUSALS_LOGGED { @@ -87,19 +87,6 @@ pub(crate) fn admit_vm_for( } } -/// The name of `task`, for log lines only. -pub(crate) fn task_comm(task: &kernel::task::Task) -> [u8; 16] { - let mut name = [0u8; 16]; - // SAFETY: `comm` is a fixed-size array inside the live task. It is read byte by byte with - // volatile loads because a concurrent rename may change it; a torn name is only printed. - unsafe { - let comm = core::ptr::addr_of!((*task.as_ptr()).comm).cast::(); - for (i, byte) in name.iter_mut().enumerate() { - *byte = comm.add(i).read_volatile(); - } - } - name -} /// Bytes at the start of a compute control stream whose launch records are checked. const LAUNCH_WINDOW: usize = 4096; diff --git a/drivers/gpu/drm/asahi/m3/m3_compute.rs b/drivers/gpu/drm/asahi/m3/m3_compute.rs index d49a311c506c2b..10dd602d0d500e 100644 --- a/drivers/gpu/drm/asahi/m3/m3_compute.rs +++ b/drivers/gpu/drm/asahi/m3/m3_compute.rs @@ -34,6 +34,12 @@ pub(crate) struct Compute { last_progress_ns: i64, head: u16, cached_views: KVec, + /// Quarantined client views retained after firmware-aborted computes so their + /// ASIDs and driver mappings are never evicted or recycled. + quarantined_views: KVec, + quarantine_active_vm: bool, + /// Cumulative computes aborted by recovery that did not advance pool+0x54. + pool_delta: u64, slot: usize, batch_count: usize, checkpoint: (u64,u16,usize), @@ -119,7 +125,7 @@ impl Compute { // the invalidation. crate::mem::sync();crate::mem::tlbi_all();crate::mem::sync(); unsafe {core::arch::asm!("isb",options(nostack,preserves_flags))}; - Ok(Self {_client_command:client_command.ok_or(EINVAL)?,objects,command_bytes,sequence_bytes,_binding:binding,stats,last_progress_ns:0,stamp_epoch:timeline::StampEpoch::default(),sequence:1,head:1,cached_views:KVec::new(),slot:0,batch_count:1,checkpoint:(0,0,0),barriers:None,registers,profile,_lower_tlbi:lower_tlbi}) + Ok(Self {_client_command:client_command.ok_or(EINVAL)?,objects,command_bytes,sequence_bytes,_binding:binding,stats,last_progress_ns:0,stamp_epoch:timeline::StampEpoch::default(),sequence:1,head:1,cached_views:KVec::new(),quarantined_views:KVec::new(),quarantine_active_vm:false,pool_delta:0,slot:0,batch_count:1,checkpoint:(0,0,0),barriers:None,registers,profile,_lower_tlbi:lower_tlbi}) } fn encode_command(objects: &mut [Buffer], bytes: &mut [u8], context: u32, control: crate::m3::agx_compute::Control, sequence: u64, stamp_value: u32, slot: usize, @@ -224,9 +230,13 @@ impl Compute { // Complete allocations before moving the active views. Eviction // drops only an idle cached view; no arena storage is duplicated. let old_views = KVec::with_capacity(next.views.len(), GFP_KERNEL)?; - self.cached_views.reserve(1, GFP_KERNEL)?; - if self.cached_views.len() == 3 { - drop(self.cached_views.remove(0).map_err(|_| EIO)?); + if self.quarantine_active_vm { + self.quarantined_views.reserve(1, GFP_KERNEL)?; + } else { + self.cached_views.reserve(1, GFP_KERNEL)?; + if self.cached_views.len() == 3 { + drop(self.cached_views.remove(0).map_err(|_| EIO)?); + } } let mut old = CachedViews { binding: core::mem::replace(&mut self._binding, next.binding), @@ -236,7 +246,12 @@ impl Compute { for (i, view) in next.views { old.views.push((i, self.objects[i].swap_gpu_view(view)?), GFP_KERNEL)?; } - self.cached_views.push(old, GFP_KERNEL)?; + if self.quarantine_active_vm { + self.quarantine_active_vm = false; + self.quarantined_views.push(old, GFP_KERNEL)?; + } else { + self.cached_views.push(old, GFP_KERNEL)?; + } } self.checkpoint=(self.sequence,self.head,self.batch_count); self.batch_count=0; @@ -434,10 +449,43 @@ impl Compute { && self.objects[storage::QUEUE_STATE].read_u32(queue::READ)? == u32::from(self.head); if !stamped { return Ok(false); } if self.profile == super::m3_profile::Profile::Extended { - return Ok(self.objects[storage::POOL].read_u64(0x54)? == self.sequence); + let actual = self.objects[storage::POOL].read_u64(0x54)?; + let expected = self.sequence.saturating_sub(self.pool_delta); + if actual < expected || actual > self.sequence { + return Ok(false); + } + if actual > expected { + self.pool_delta = self.sequence - actual; + } } Ok(true) } + /// Whether the firmware has drained the compute work ring to its current write head. + pub(crate) fn queues_drained(&mut self) -> Result { + Ok(self.objects[storage::QUEUE_STATE].read_u32(queue::DONE)? == u32::from(self.head) + && self.objects[storage::QUEUE_STATE].read_u32(queue::READ)? == u32::from(self.head)) + } + /// Re-synchronize compute stamps and pool expectations after firmware recovery + /// drained the stopped batch, and mark the faulting VM's binding for quarantine. + pub(crate) fn finish_recovery(&mut self, dev: &driver::AsahiDrmDevice) -> Result { + self.quarantine_active_vm = true; + let expected = self.stamp(); + let host = self.objects[storage::STAMP].read_u32(0)?; + let fw = self.objects[storage::FW_STAMP].read_u32(0)?; + let pool54 = self.objects[storage::POOL].read_u64(0x54)?; + dev_info!( + dev.as_ref(), + "M3 recovery compute post-drain: seq={} stamps={:#x}/{:#x} (want {:#x}) pool54={}\n", + self.sequence, host, fw, expected, pool54 + ); + if host != expected { self.objects[storage::STAMP].u32(0, expected)?; } + if fw != expected { self.objects[storage::FW_STAMP].u32(0, expected)?; } + if self.profile == super::m3_profile::Profile::Extended { + self.pool_delta = self.sequence.saturating_sub(pool54); + } + agx_memory::publish(); + Ok(()) + } pub(crate) fn log(&mut self,dev:&driver::AsahiDrmDevice)->Result { for off in (0..512).step_by(128) { let mut raw=[0u8;128]; self.objects[storage::COMMAND].read(off,&mut raw)?; diff --git a/drivers/gpu/drm/asahi/m3/m3_config.rs b/drivers/gpu/drm/asahi/m3/m3_config.rs index 88ca6f9c765afc..cda051e17b203f 100644 --- a/drivers/gpu/drm/asahi/m3/m3_config.rs +++ b/drivers/gpu/drm/asahi/m3/m3_config.rs @@ -54,6 +54,9 @@ pub(crate) struct Config { io_descriptors: Option>, _iomaps: KVec, pub(crate) completed_events: u64, + pending_recovery_event: Option<(u32, u32)>, + pending_recovery_stats: bool, + last_recovery_gen: Option, pstates: crate::m3::m3_adt_config::PstateWatch, thermal: crate::m3::m3_thermal::Governor, request_top: u32, @@ -74,6 +77,7 @@ impl Config { let thermal = crate::m3::m3_thermal::Governor::new(dev.as_ref().as_ref(), &contents.pstates)?; return Ok(Self { objects: owners.objects, _iomaps: owners.iomaps, profile: firmware.profile(), control_generation: 0, completed_events: 0, + pending_recovery_event: None, pending_recovery_stats: false, last_recovery_gen: None, io_descriptors: Some(owners.descriptors), pstates: crate::m3::m3_adt_config::PstateWatch::new(contents.pstates), thermal, request_top: 8, request_value: 0, request_checked: false, request_check_at: None, @@ -156,6 +160,7 @@ impl Config { let thermal = crate::m3::m3_thermal::Governor::new(dev.as_ref().as_ref(), &contents.pstates)?; Ok(Self { objects, profile: firmware.profile(), control_generation: 0, io_descriptors: None, _iomaps: iomaps, completed_events: 0, + pending_recovery_event: None, pending_recovery_stats: false, last_recovery_gen: None, pstates: crate::m3::m3_adt_config::PstateWatch::new(contents.pstates), thermal, request_top:contents.table.0,request_value:0,request_checked:false, request_check_at:None,request_writes:0,request_observed:0 }) @@ -299,12 +304,9 @@ impl Config { let state=kind*2;let ring=state+1; let w=self.objects[state].read_u32(0x20)?; if w>=256 || self.objects[state].read_u32(0)?!=w { return Err(EBUSY); } - let mut message=[0u8;0x18]; - message[8..16].copy_from_slice(&queue.to_le_bytes()); - message[16..20].copy_from_slice(&(kind as u32).to_le_bytes()); - message[20..22].copy_from_slice(&head.to_le_bytes()); - message[22]=event;message[23]=u8::from(new); // New queue; caller selected the event slot. - self.objects[ring].write(w as usize*0x18,&message)?; + let message = super::m3_channel_format::submission_entry(kind as u32, queue, head, event, new) + .map_err(|_| EINVAL)?; + self.objects[ring].write(w as usize * message.len(), &message)?; agx_memory::publish(); self.objects[state].u32(0x20,(w+1)%256)?; agx_memory::publish(); @@ -373,8 +375,13 @@ impl Config { /// Nothing is acknowledged, cleared or resumed here. pub(crate) fn log_recovery_state(&mut self, dev: &driver::AsahiDrmDevice, events: u64) -> Result { if self.profile == super::m3_profile::Profile::Extended { + let control_start = 0x4ebc + super::m3_init_26::control_shift(); + let control_size = self.objects[CONTROL_REGION].size(); for (owner, start, length) in [(super::m3_init_26::RECOVERY_ACTIVITY, 0, 0x60), - (CONTROL_REGION, 0x4ebc, 0x100)] { + (CONTROL_REGION, control_start, 0x100)] { + if owner == CONTROL_REGION && start.saturating_add(length) > control_size { + continue; + } for offset in (start..start + length).step_by(32) { let mut bytes = [0; 32]; self.objects[owner].read(offset, &mut bytes)?; @@ -538,14 +545,27 @@ impl Config { core::str::from_utf8(&text[..len]).unwrap_or("")); } } else if channel == storage::EVENT { - if kind != 1 { + if kind == 1 { + let flags = u32::from_le_bytes(record[4..8].try_into().map_err(|_| EIO)?); + self.completed_events = self.completed_events.saturating_add((flags & 7).count_ones().into()); + } else if kind == 0 || kind == 4 { + let word3 = u32::from_le_bytes(record[12..16].try_into().map_err(|_| EIO)?); + dev_err!(dev.as_ref(), "M3 firmware event {}: {:02x?}\n", kind, record); + if self.recovery_offsets().is_none() { + return Err(EIO); + } + self.pending_recovery_event.get_or_insert((kind, word3)); + } else { dev_err!(dev.as_ref(), "M3 firmware event {}: {:02x?}\n", kind, record); return Err(EIO); } - let flags = u32::from_le_bytes(record[4..8].try_into().map_err(|_| EIO)?); - self.completed_events = self.completed_events.saturating_add((flags & 7).count_ones().into()); - } else if (channel == storage::TRACE && kind != 5) - || (channel == storage::STATS && kind == 0x16) { + } else if channel == storage::STATS && kind == 0x16 { + dev_err!(dev.as_ref(), "M3 firmware channel {} record {}: {:02x?}\n", channel, kind, record); + if self.recovery_offsets().is_none() { + return Err(EIO); + } + self.pending_recovery_stats = true; + } else if channel == storage::TRACE && kind != 5 { dev_err!(dev.as_ref(), "M3 firmware channel {} record {}: {:02x?}\n", channel, kind, record); return Err(EIO); } @@ -558,6 +578,90 @@ impl Config { Ok(()) } + pub(crate) fn recovery_offsets(&self) -> Option { + if self.profile != super::m3_profile::Profile::Extended { + return None; + } + let offsets = super::m3_recovery::RecoveryOffsets::extended( + super::m3_init_26::control_shift(), + super::m3_init_26::control_region_bytes(), + ); + offsets + .valid_for(self.objects[CONTROL_REGION].size()) + .then_some(offsets) + } + + pub(crate) fn recovery_phase(&mut self) -> Result { + let offsets = self.recovery_offsets().ok_or(EOPNOTSUPP)?; + self.objects[CONTROL_REGION].read_u32(offsets.phase) + } + + pub(crate) fn recovery_generation(&mut self) -> Result { + let offsets = self.recovery_offsets().ok_or(EOPNOTSUPP)?; + let lo = self.objects[CONTROL_REGION].read_u32(offsets.generation)?; + let hi = self.objects[CONTROL_REGION].read_u32(offsets.generation + 4)?; + Ok(u64::from(lo) | (u64::from(hi) << 32)) + } + + pub(crate) fn write_recovery_phase(&mut self, phase: u32) -> Result { + let offsets = self.recovery_offsets().ok_or(EOPNOTSUPP)?; + agx_memory::publish(); + self.objects[CONTROL_REGION].u32(offsets.phase, phase)?; + agx_memory::publish(); + Ok(()) + } + + pub(crate) fn read_recovery_snapshot(&mut self, index: usize) -> Result<(u32, u32)> { + let offsets = self.recovery_offsets().ok_or(EOPNOTSUPP)?; + if index >= offsets.snapshot_entries { + return Err(ERANGE); + } + let at = offsets.snapshot + index * 8; + let flags = self.objects[CONTROL_REGION].read_u32(at)?; + let target = self.objects[CONTROL_REGION].read_u32(at + 4)?; + Ok((flags, target)) + } + + pub(crate) fn note_recovered(&mut self, generation: u64) { + self.last_recovery_gen = Some(generation); + self.pending_recovery_event = None; + self.pending_recovery_stats = false; + } + + /// Returns a recovery trigger error if the firmware reported a fault/timeout + /// or entered recovery phase != 0, ignoring trailing `EVENT 0`/`4` or + /// `STATS 0x16` notifications from the already-completed recovery generation. + pub(crate) fn take_recovery_trigger(&mut self) -> Result> { + if self.recovery_offsets().is_none() { + if let Some((kind, _word3)) = self.pending_recovery_event.take() { + self.pending_recovery_stats = false; + return Ok(Some(if kind == 4 { ETIMEDOUT } else { EIO })); + } + if core::mem::take(&mut self.pending_recovery_stats) { + return Ok(Some(EIO)); + } + return Ok(None); + } + let phase = self.recovery_phase()?; + if let Some((kind, _word3)) = self.pending_recovery_event.take() { + self.pending_recovery_stats = false; + let gen = self.recovery_generation()?; + if !super::m3_recovery::is_trailing_stats(phase, gen, self.last_recovery_gen) { + return Ok(Some(if kind == 4 { ETIMEDOUT } else { EIO })); + } + } + if core::mem::take(&mut self.pending_recovery_stats) { + let gen = self.recovery_generation()?; + if !super::m3_recovery::is_trailing_stats(phase, gen, self.last_recovery_gen) { + return Ok(Some(EIO)); + } + } + if phase != 0 { + return Ok(Some(EIO)); + } + Ok(None) + } + } /// All extended initialization owners, retained as one construction transaction. diff --git a/drivers/gpu/drm/asahi/m3/m3_coverage.rs b/drivers/gpu/drm/asahi/m3/m3_coverage.rs deleted file mode 100644 index 3ec1fac6834922..00000000000000 --- a/drivers/gpu/drm/asahi/m3/m3_coverage.rs +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT -//! Positive page-coverage results for one exclusively host-owned page table. -//! The page-table owner must invalidate before every possible table mutation. -//! This stores permissions only; it never proves physical backing identity. - -#[derive(Clone, Copy)] -struct Entry { start: u64, end: u64, read: bool, write: bool } -pub(crate) struct Cache { entries: [Option; 32], next: usize } -impl Cache { - pub(crate) const fn new() -> Self { Self { entries: [None; 32], next: 0 } } - pub(crate) fn invalidate(&mut self) { self.entries.fill(None); self.next = 0; } - pub(crate) fn covers(&self, start: u64, end: u64, read: bool, write: bool) -> bool { - start < end && self.entries.iter().flatten().any(|e| - e.start <= start && end <= e.end && (!read || e.read) && (!write || e.write)) - } - pub(crate) fn remember(&mut self, start: u64, end: u64, read: bool, write: bool) { - if start >= end { return; } - self.entries[self.next] = Some(Entry { start, end, read, write }); - self.next = (self.next + 1) % self.entries.len(); - } -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn permissions_holes_and_mutations() { - let mut c = Cache::new(); - c.remember(0x4000, 0x8000, true, false); - c.remember(0xc000, 0x10000, true, true); - assert!(c.covers(0x4001, 0x7fff, true, false)); - assert!(!c.covers(0x4000, 0x8000, false, true)); - assert!(!c.covers(0x4000, 0x10000, true, false)); - assert!(!c.covers(0x8000, 0x8000, false, false)); - assert!(!c.covers(u64::MAX, 0, false, false)); - assert!(c.covers(0xc000, 0x10000, true, true)); - // An unmap/remap or permission downgrade must discard all old proof. - c.invalidate(); - assert!(!c.covers(0xc000, 0x10000, false, true)); - c.remember(0xc000, 0x10000, true, false); - assert!(!c.covers(0xc000, 0x10000, false, true)); - for i in 0..100 { c.remember(0x20000+i*0x4000, 0x24000+i*0x4000, true, true); } - assert!(!c.covers(0xc000, 0x10000, true, false)); - } -} diff --git a/drivers/gpu/drm/asahi/m3/m3_device.rs b/drivers/gpu/drm/asahi/m3/m3_device.rs index 9897690d923dcc..ec0eec77aaa4ab 100644 --- a/drivers/gpu/drm/asahi/m3/m3_device.rs +++ b/drivers/gpu/drm/asahi/m3/m3_device.rs @@ -173,12 +173,70 @@ impl Device { self.sgx.try_access().ok_or(ENODEV)?.as_view().try_read32(0xe01000) } + /// Read-only MMU fault bank & engine busy snapshot for Extended (26.x/27.2) + /// profiles. Returns `Ok(true)` if any cluster fault bank has its valid bit set. + /// Does not acknowledge or clear hardware fault banks, and always restores + /// the bank selector register (`0xd800`) on exit. + pub(crate) fn log_extended_fault_banks(&self, vm: &crate::mmu::Vm) -> Result { + let sgx_guard = self.sgx.try_access().ok_or(ENODEV)?; + let sgx = sgx_guard.as_view(); + let pstate = sgx.try_read32(0xe01000)? & 0xf; + if pstate == 0 { + dev_info!( + self.dev.as_ref(), + "M3 {}: GPU is powered down; skipping fault-bank snapshot\n", + self.soc.gpu_name + ); + return Ok(false); + } + let check_busy = crate::m3::m3_params::retire_mmio(self.soc) + & crate::m3::m3_params::RETIRE_MMIO_BUSY + != 0; + let (c020, c120) = if check_busy { + (sgx.try_read64(0xc020)?, sgx.try_read64(0xc120)?) + } else { + (0, 0) + }; + let selector = sgx.try_read64(0xd800)?; + let result = (|| -> Result { + let mut any_fault = false; + for bank in 0..u64::from(self.soc.clusters) { + sgx.try_write64(bank, 0xd800)?; + let address = sgx.try_read64(0xd8c8)?; + let fault = sgx.try_read64(0xd8c0)?; + dev_info!( + self.dev.as_ref(), + "M3 {}: pstate={} busy={:#x}/{:#x} bank {} fault={:#x} address={:#x}\n", + self.soc.gpu_name, + pstate, + c020, + c120, + bank, + fault, + address << 6 + ); + if fault & 1 != 0 { + any_fault = true; + dev_info!( + self.dev.as_ref(), + "M3 fault mapping bank={} address={:#x} translation={:?}\n", + bank, + address << 6, + vm.translate_iova(address << 6) + ); + } + } + Ok(any_fault) + })(); + let _ = sgx.try_write64(selector, 0xd800); + result + } + /// Read-only snapshot. Do not select or acknowledge fault banks here; /// the firmware owns those registers until recovery is ported. pub(crate) fn log_engine_state(&self, vm: &crate::mmu::Vm) -> Result { if self.firmware.profile() == super::m3_profile::Profile::Extended { - // Adaptive clock gating can leave individual engine banks inaccessible - // even while the GPU performance-state register says powered up. + let _ = self.log_extended_fault_banks(vm)?; return Ok(()); } let sgx_guard = self.sgx.try_access().ok_or(ENODEV)?; diff --git a/drivers/gpu/drm/asahi/m3/m3_drm.rs b/drivers/gpu/drm/asahi/m3/m3_drm.rs index b11b612184ed9d..62b1df4fe02f15 100644 --- a/drivers/gpu/drm/asahi/m3/m3_drm.rs +++ b/drivers/gpu/drm/asahi/m3/m3_drm.rs @@ -110,8 +110,8 @@ impl Backend { ) -> Result> { // The runtime only exists to back its render node: without one (`asahi.m3_expose=0`) // nothing is started, rather than leaving a running firmware behind a failed probe. - if !crate::m3::m3_board::expose_render_node(soc) { - dev_info!(pdev.as_ref(), "M3: render node not registered on this board (asahi.m3_expose=1 registers it); GPU not started\n"); + if !crate::m3::m3_board::expose_render_node(pdev.as_ref()) { + dev_info!(pdev.as_ref(), "M3: render node not registered: the boot loader did not hand the GPU over (asahi.m3_expose=1 registers it); GPU not started\n"); return Err(ENODEV); } let resources = crate::m3::m3_resources::from_device(pdev, soc).inspect_err(|_| { @@ -268,8 +268,14 @@ impl gpu::Gpu for Backend { self.feature_flags() & uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_DEPENDENCY as u64 != 0, self.feature_flags() & uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE_WIDE_VISIBILITY as u64 != 0)?,GFP_KERNEL)?) } - fn map_timestamp_buffer(&self, bo: gem::ObjectRef, range: Range) -> Result { + fn timestamp_window_size(&self) -> u64 { + crate::m3::agx_memory::TIMESTAMP_RANGE.end - crate::m3::agx_memory::TIMESTAMP_RANGE.start + } + + fn map_timestamp_buffer(&self, bo: gem::ObjectRef, range: Range, window: crate::timestamp::WindowPermit) -> Result { + if !window.is_allowed() { return Err(ENOSPC); } crate::timestamp::Buffer::firmware( - Option::as_mut(&mut *self.shared.lock()).ok_or(ENODEV)?.map_timestamp(bo,range)?) + Option::as_mut(&mut *self.shared.lock()).ok_or(ENODEV)?.map_timestamp(bo,range)?, + window.into_share()) } } diff --git a/drivers/gpu/drm/asahi/m3/m3_init_26.rs b/drivers/gpu/drm/asahi/m3/m3_init_26.rs index a86432b2bbe2b5..a4ce845e4a6a4f 100644 --- a/drivers/gpu/drm/asahi/m3/m3_init_26.rs +++ b/drivers/gpu/drm/asahi/m3/m3_init_26.rs @@ -19,11 +19,36 @@ pub(crate) const LOG_THREADS: usize = 9; pub(crate) const RX_BYTES: usize = 0x48; pub(crate) const LOG_PAYLOAD_BYTES: usize = 0xd8; +/// Control-region byte size and offset shift for recovery/flush fields on this extended layout. +pub(crate) const CONTROL_REGION_BYTES: usize = 0xeaf0; +pub(crate) const CONTROL_SHIFT: usize = 0; + +pub(crate) const fn control_shift() -> usize { + CONTROL_SHIFT +} + +pub(crate) const fn control_region_bytes() -> usize { + CONTROL_REGION_BYTES +} + +/// The shared cache-flush ring has separate index and entry addresses on the wire. +pub(crate) fn write_flush_ring( + bytes: &mut [u8], offset: usize, state: u64, entries: u64, +) -> Result<(), Error> { + if state == 0 || entries == 0 || (state | entries) & 0x3f != 0 { + return Err(Error::Address); + } + let pair = bytes.get_mut(offset..).and_then(|s| s.get_mut(..16)).ok_or(Error::Size)?; + pair[..8].copy_from_slice(&state.to_le_bytes()); + pair[8..].copy_from_slice(&entries.to_le_bytes()); + Ok(()) +} + /// Extend the existing M3 owner indices instead of introducing another owner graph. pub(crate) fn allocation(index: usize) -> Result { let size = match index { 0..=23 if index % 2 == 0 => 0x30, - 0..=23 => 0x1800, + 0..=23 => super::m3_channel_format::SLOTS as usize * super::m3_channel_format::SUBMISSION_BYTES, 24 | 26 | 30 | 32 => 0x30, 25 => 0x4000, 27 | 33 => 0x4800, @@ -43,7 +68,7 @@ pub(crate) fn allocation(index: usize) -> Result { 44 => 0xe10, 45 => 0xe48, 46 => 0x670, - 47 => 0xeaf0, + 47 => CONTROL_REGION_BYTES, 48 => 0x20, DYNAMIC_STATE | RETENTION_STATE | GLOBAL_POOL | GLOBAL_PARAMETERS => 0x4000, PERFORMANCE_CONTROL => 0x6578, @@ -65,6 +90,30 @@ pub(crate) fn cached(index: usize) -> bool { matches!(index, 39 | PERFORMANCE_CONTROL) } +/// Thirteen TX descriptors and four RX state/ring pairs. Both the extended +/// M3 profile and the adjacent G14G profile use these directory offsets. +/// The caller owns all 34 buffers through firmware stop. +pub(crate) fn write_channels(bytes: &mut [u8], addresses: &[u64; 34]) -> Result<(), Error> { + if bytes.len() < 0x200 || addresses.contains(&0) { + return Err(Error::Bounds); + } + let pointer = |bytes: &mut [u8], offset, value: u64| { + bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); + }; + for channel in 0..13 { + let offset = 0x20 + channel * 0x20; + let state = addresses[channel * 2]; + pointer(bytes, offset, state); + pointer(bytes, offset + 8, state + 0x10); + pointer(bytes, offset + 16, state + 0x20); + pointer(bytes, offset + 24, addresses[channel * 2 + 1]); + } + for (index, &address) in addresses[26..].iter().enumerate() { + pointer(bytes, 0x1c0 + index * 8, address); + } + Ok(()) +} + pub(crate) struct PointerGraph<'a> { pub(crate) owners: &'a [Region; COUNT], pub(crate) scratch: Region, @@ -155,14 +204,6 @@ impl PointerGraph<'_> { for (offset, owner) in [ (0, storage::HARDWARE_DATA), (0x10, storage::UNKNOWN_PAIR), - (0x1c0, 26), - (0x1c8, 27), - (0x1d0, 28), - (0x1d8, 29), - (0x1e0, 30), - (0x1e8, 31), - (0x1f0, 32), - (0x1f8, 33), (0x200, storage::FWLOG_PAYLOAD), (0x254, storage::UNKNOWN_C0), (0x25c, storage::UNKNOWN_C1), @@ -174,14 +215,7 @@ impl PointerGraph<'_> { ] { pointer(bytes, offset, addresses[owner]); } - for channel in 0..13 { - let offset = 0x20 + channel * 0x20; - let state = addresses[channel * 2]; - pointer(bytes, offset, state); - pointer(bytes, offset + 8, state + 0x10); - pointer(bytes, offset + 16, state + 0x20); - pointer(bytes, offset + 24, addresses[channel * 2 + 1]); - } + write_channels(bytes, addresses[..34].try_into().map_err(|_| Error::Bounds)?)?; Ok(()) } @@ -191,8 +225,8 @@ impl PointerGraph<'_> { .get_mut(..allocation(storage::CONTROL_REGION)?.size) .ok_or(Error::Size)?; bytes.fill(0); - bytes[0x4f88..0x4f90].copy_from_slice(&addresses[storage::FW_CONTROL_STATE].to_le_bytes()); - bytes[0x4f90..0x4f98].copy_from_slice(&addresses[storage::FW_CONTROL_RING].to_le_bytes()); + write_flush_ring(bytes, 0x4f88, addresses[storage::FW_CONTROL_STATE], + addresses[storage::FW_CONTROL_RING])?; bytes[0x4fd4..0x4fd8].copy_from_slice(&1u32.to_le_bytes()); Ok(()) } @@ -202,6 +236,17 @@ impl PointerGraph<'_> { mod tests { use super::*; + #[test] + fn empty_flush_ring_publishes_both_views() { + let mut control = [0u8; 0x4bf8]; + let base = 0xffff_ffa8_0010_0000; + write_flush_ring(&mut control, 0x4be0, base, base + 0x40).unwrap(); + assert_eq!(&control[0x4be0..0x4be8], &base.to_le_bytes()); + assert_eq!(&control[0x4be8..0x4bf0], &(base + 0x40).to_le_bytes()); + assert_eq!(&control[0x4bf0..], &[0; 8]); + assert!(write_flush_ring(&mut control[..0x4be8], 0x4be0, base, base + 0x40).is_err()); + } + fn owners(delta: u64) -> [Region; COUNT] { core::array::from_fn(|index| { let item = allocation(index).unwrap(); diff --git a/drivers/gpu/drm/asahi/m3/m3_mmio_26.rs b/drivers/gpu/drm/asahi/m3/m3_mmio_26.rs index a17bc0ee399c34..31e463f6cd1ec0 100644 --- a/drivers/gpu/drm/asahi/m3/m3_mmio_26.rs +++ b/drivers/gpu/drm/asahi/m3/m3_mmio_26.rs @@ -142,6 +142,12 @@ pub(crate) fn encode( } _ => return Err(Error::Address), }; + write_record(output, physical, va, bytes, requested, register, mode) +} + +/// Common 0x28-byte record used by the single-role G14G and G15G interfaces. +pub(crate) fn write_record(output: &mut [u8], physical: u64, va: u64, bytes: u32, + requested: u32, register: u64, mode: u64) -> Result<(), Error> { let bytes_out = output.get_mut(..RECORD_BYTES).ok_or(Error::Size)?; bytes_out.fill(0); bytes_out[0..8].copy_from_slice(&physical.to_le_bytes()); diff --git a/drivers/gpu/drm/asahi/m3/m3_params.rs b/drivers/gpu/drm/asahi/m3/m3_params.rs index 85033c88e4192d..e2785c8ac1198e 100644 --- a/drivers/gpu/drm/asahi/m3/m3_params.rs +++ b/drivers/gpu/drm/asahi/m3/m3_params.rs @@ -205,8 +205,8 @@ pub(crate) fn render_internal_timestamps()->bool { // The runtime's boot-time module parameters. On 7.1.12 they were `module!` parameters; they // keep their names, and exist only with the T8122 runtime built in. -/// `asahi.m3_render_batch_size`: bounded ordered render batch size (1..16). -static M3_RENDER_BATCH_SIZE: AtomicU64 = AtomicU64::new(1); +/// `asahi.m3_render_batch_size`: bounded ordered render batch size (1..16, default 2). +static M3_RENDER_BATCH_SIZE: AtomicU64 = AtomicU64::new(2); m3_param!("m3_render_batch_size", M3_RENDER_BATCH_SIZE, parse_u64); /// `asahi.m3_compute_batch_size`: bounded ordered compute batch size (1..16). static M3_COMPUTE_BATCH_SIZE: AtomicU64 = AtomicU64::new(1); @@ -589,9 +589,9 @@ pub(crate) fn thermal_hot_param() -> (u64, bool) { /// Whether to start the runtime backend on a T8122 (`asahi.m3_backend`), and say why not. /// -/// The runtime starts only on the boards the T8122 table allows (the M3 MacBook Airs), with -/// `auto` and `runtime` alike: it has not run on any T8122, so nothing forces it onto another -/// board. The G15 manager backend is T6030-only. +/// The runtime starts only where the boot loader handed the GPU over +/// (`m3_board::handed_over`), with `auto` and `runtime` alike: nothing forces it onto a GPU +/// that was not handed over. The G15 manager backend is T6030-only. pub(crate) fn t8122_backend(pdev: &platform::Device>) -> bool { let dev = pdev.as_ref(); match M3_BACKEND.load(Ordering::Relaxed) { @@ -606,11 +606,11 @@ pub(crate) fn t8122_backend(pdev: &platform::Device>) -> bool { ); false } - _ if crate::m3::m3_board::runtime_validated_board(&crate::m3::m3_soc::T8122) => true, + _ if crate::m3::m3_board::handed_over(dev) => true, _ => { dev_info!( dev, - "M3: no GPU backend on this T8122 board: the runtime backend may start only on the M3 MacBook Airs (J613, J615)\n" + "M3: no GPU backend: the boot loader did not hand the GPU over (no firmware segment description on the GPU node)\n" ); false } diff --git a/drivers/gpu/drm/asahi/m3/m3_recovery.rs b/drivers/gpu/drm/asahi/m3/m3_recovery.rs new file mode 100644 index 00000000000000..1bb6eb84beedae --- /dev/null +++ b/drivers/gpu/drm/asahi/m3/m3_recovery.rs @@ -0,0 +1,235 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! M3 Extended (26.x / 27.2) per-client GPU fault recovery. +//! +//! Shares the 27.2 recovery phase state machine, snapshot decoder, and storm +//! admission window directly from `g16/recovery/logic.rs` (the same protocol +//! G16 and G14 27.2 answer) so no phase logic is duplicated across backends. + +#[path = "../g16/recovery/logic.rs"] +#[allow(dead_code)] +pub(crate) mod logic; + +pub(crate) use logic::{RecoveryAction, SnapshotEntry}; + +/// Maximum quarantined aborted flights per boot (half of the 63 user UAT +/// contexts). Exceeding this cap fails closed into device fail-stop rather +/// than leaking bindings/packets without bound across storm windows. +pub(crate) const QUARANTINE_LIMIT: usize = 31; + +/// Additional recovery rounds answered while stopped work drains from queues. +pub(crate) const FURTHER_RECOVERIES: u32 = 4; + +/// Maximum time to wait for stopped work to drain from work rings after phase 0. +pub(crate) const RECOVERY_DRAIN_MS: i64 = 1000; + +/// Overall wall-clock budget for starting recovery rounds under the runtime lock. +pub(crate) const RECOVERY_BUDGET_MS: i64 = 5000; + +/// Recovery control-object offsets derived from the `m3_init_26` layout shift +/// and validated against the exact expected `CONTROL_REGION` byte size. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct RecoveryOffsets { + pub(crate) snapshot: usize, + pub(crate) snapshot_entries: usize, + pub(crate) generation: usize, + pub(crate) phase: usize, + pub(crate) control_bytes: usize, +} + +/// 26.6.2 extended FirmwareData recovery offsets and affected-work snapshot geometry. +const EXTENDED_SNAPSHOT: usize = 0x40b8; +const EXTENDED_SNAPSHOT_ENTRIES: usize = 448; +const EXTENDED_GENERATION: usize = 0x4fa0; +const EXTENDED_PHASE: usize = 0x4fb0; + +impl RecoveryOffsets { + /// Extended control region offsets shifted by the profile's `m3_init_26` + /// control-table delta (`0` on 26.6.2 / `0xeaf0`, `0x1e0` on 27.2 / `0xedd0`). + pub(crate) const fn extended(shift: usize, control_bytes: usize) -> Self { + Self { + snapshot: EXTENDED_SNAPSHOT + shift, + snapshot_entries: EXTENDED_SNAPSHOT_ENTRIES, + generation: EXTENDED_GENERATION + shift, + phase: EXTENDED_PHASE + shift, + control_bytes, + } + } + + /// Verify `control_bytes` matches the expected layout size and every recovery + /// word and snapshot entry fits inside it (failing closed on mismatched layouts). + pub(crate) const fn valid_for(self, control_bytes: usize) -> bool { + if control_bytes != self.control_bytes { + return false; + } + let Some(snap_bytes) = self.snapshot_entries.checked_mul(8) else { + return false; + }; + let Some(snap_end) = self.snapshot.checked_add(snap_bytes) else { + return false; + }; + let Some(gen_end) = self.generation.checked_add(8) else { + return false; + }; + let Some(phase_end) = self.phase.checked_add(4) else { + return false; + }; + snap_end <= self.generation + && gen_end <= self.phase + && phase_end <= control_bytes + } +} + +/// A snapshot entry for a stopped tiler (valid + tiler bits): TPC storage must +/// be cleared before answering phase 2, matching G16 and G14 27.2. +pub(crate) const fn stopped_tiler(flags: u32) -> bool { + flags & 9 == 9 +} + +/// Whether the recovery snapshot proves a tiler-only stop (at least one stopped +/// tiler entry and no non-tiler/fragment entry). Only in this case does 27.2 +/// firmware discard the paired fragment command without advancing `FS.DONE`. +pub(crate) const fn tiler_only_stop(stopped_tiler_seen: bool, non_tiler_seen: bool) -> bool { + stopped_tiler_seen && !non_tiler_seen +} + +/// Trailing `STATS 0x16` notifications can arrive after the host already wrote +/// phase 0 for that recovery generation; do not treat them as a new fault. +pub(crate) const fn is_trailing_stats( + phase: u32, + current_gen: u64, + last_recovered_gen: Option, +) -> bool { + if phase != 0 { + return false; + } + match last_recovered_gen { + Some(prev) => prev == current_gen, + None => false, + } +} + +/// Cumulative per-boot bound on quarantined flights across recovery windows. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct QuarantineBudget { + count: usize, + limit: usize, +} + +impl QuarantineBudget { + pub(crate) const fn new(limit: usize) -> Self { + Self { count: 0, limit } + } + + pub(crate) const fn count(&self) -> usize { + self.count + } + + pub(crate) const fn can_admit(&self, flights: usize) -> bool { + match self.count.checked_add(flights) { + Some(total) => total <= self.limit, + None => false, + } + } + + pub(crate) fn charge(&mut self, flights: usize) -> bool { + if !self.can_admit(flights) { + return false; + } + self.count += flights; + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extended_offsets_match_shared_g16_and_272_layouts() { + assert!(FURTHER_RECOVERIES > 0); + assert!(RECOVERY_DRAIN_MS > 0); + assert!(RECOVERY_BUDGET_MS >= RECOVERY_DRAIN_MS); + + let base = RecoveryOffsets::extended(0, 0xeaf0); + assert_eq!(base.snapshot, 0x40b8); + assert_eq!(base.generation, 0x4fa0); + assert_eq!(base.phase, 0x4fb0); + assert!(base.valid_for(0xeaf0)); + assert!(!base.valid_for(0x4fb0)); + // Must fail closed if CONTROL_REGION grows to 27.2 without updating the shift. + assert!(!base.valid_for(0xedd0)); + + let v272 = RecoveryOffsets::extended(0x1e0, 0xedd0); + assert_eq!(v272.snapshot, 0x4298); + assert_eq!(v272.generation, 0x5180); + assert_eq!(v272.phase, 0x5190); + assert!(v272.valid_for(0xedd0)); + assert!(!v272.valid_for(0xeaf0)); + assert!(!v272.valid_for(0x5190)); + } + + #[test] + fn stopped_tiler_matches_observed_g15g_and_g14_flags() { + assert!(stopped_tiler(0xd)); + assert!(stopped_tiler(0x1f)); + assert!(!stopped_tiler(0x15)); + assert!(!stopped_tiler(0x27)); + assert!(!stopped_tiler(0x7)); + assert!(!stopped_tiler(0x8)); + assert!(!stopped_tiler(0x0)); + + assert!(tiler_only_stop(true, false)); + assert!(!tiler_only_stop(true, true)); + assert!(!tiler_only_stop(false, true)); + assert!(!tiler_only_stop(false, false)); + } + + #[test] + fn quarantine_budget_bounds_cumulative_retention() { + let mut budget = QuarantineBudget::new(QUARANTINE_LIMIT); + assert!(budget.can_admit(1)); + for i in 0..QUARANTINE_LIMIT { + assert_eq!(budget.count(), i); + assert!(budget.charge(1)); + } + assert_eq!(budget.count(), QUARANTINE_LIMIT); + assert!(!budget.can_admit(1)); + assert!(!budget.charge(1)); + assert_eq!(budget.count(), QUARANTINE_LIMIT); + } + + #[test] + fn trailing_stats_ignored_only_for_same_generation_at_phase_zero() { + assert!(!is_trailing_stats(0, 1, None)); + assert!(is_trailing_stats(0, 1, Some(1))); + assert!(!is_trailing_stats(0, 2, Some(1))); + assert!(!is_trailing_stats(1, 1, Some(1))); + assert!(!is_trailing_stats(1, 2, Some(1))); + } + + #[test] + fn shared_g16_phase_table_and_storm_window_work() { + assert_eq!(logic::action(0, false, true), RecoveryAction::Wait); + assert_eq!( + logic::action(1, false, true), + RecoveryAction::MarkAndAcknowledge + ); + assert_eq!(logic::action(2, true, true), RecoveryAction::Wait); + assert_eq!(logic::action(3, true, true), RecoveryAction::Resume); + assert_eq!(logic::action(3, true, false), RecoveryAction::ProtocolError); + assert_eq!( + SnapshotEntry::decode(0xd, 0x7a00_0200), + Some(SnapshotEntry { + flags: 0xd, + event: 0, + target: 0x7a00_0200, + }) + ); + let (mut win, mut count) = (0, 0); + for _ in 0..logic::WINDOW_LIMIT { + assert!(logic::admit(10, &mut win, &mut count)); + } + assert!(!logic::admit(11, &mut win, &mut count)); + } +} diff --git a/drivers/gpu/drm/asahi/m3/m3_render.rs b/drivers/gpu/drm/asahi/m3/m3_render.rs index a3ada4a349dfa4..f83a9cca36c6a2 100644 --- a/drivers/gpu/drm/asahi/m3/m3_render.rs +++ b/drivers/gpu/drm/asahi/m3/m3_render.rs @@ -30,6 +30,17 @@ pub(crate) struct Render { last_progress_ns:i64, stamp_epoch:timeline::StampEpoch, draw:u64, heads:[u16;2], cached_views:KVec, + /// Quarantined client views and replaced arena backing retained after + /// firmware-aborted draws so their ASIDs and driver mappings are never + /// evicted or recycled while quiescence is unproven. + quarantined_views:KVec, + quarantined_buffers:KVec, + quarantine_active_vm:bool, + /// Draw number whose batch was aborted by firmware recovery so `complete()` + /// does not reject the next draw with `EBUSY` on a firmware-discarded FS `DONE`. + recovery_aborted_draw:Option, + /// Cumulative draws aborted by recovery that did not advance pool+0x54. + pool_delta:[u64;2], slot:usize, batch_count:usize, early_count:u32, /// Measurement packets in the pass most recently appended to its queues. stage_timestamps:[bool;2], @@ -99,7 +110,7 @@ impl Render { tiler_bytes.resize(if profile==super::m3_profile::Profile::Extended {tiler::EXTENDED_SIZE} else {tiler::SIZE},0u8,GFP_KERNEL)?; let mut fragment_bytes=KVec::new(); fragment_bytes.resize(if profile==super::m3_profile::Profile::Extended {fragment::EXTENDED_SIZE} else {fragment::SIZE},0u8,GFP_KERNEL)?; - let mut job=Self{passes,init_bm,stats,profile,sequence_bytes,tiler_bytes,fragment_bytes,objects,_aliases:aliases,_binding:binding,last_progress_ns:0,stamp_epoch:timeline::StampEpoch::default(),draw:0,heads:[0;2],cached_views:KVec::new(),slot:0,batch_count:0,early_count:0,stage_timestamps:[true;2],base:0,checkpoint:(0,[0;2],0,0,0,0),clusters,registers,_lower_tlbi:lower_tlbi}; + let mut job=Self{passes,init_bm,stats,profile,sequence_bytes,tiler_bytes,fragment_bytes,objects,_aliases:aliases,_binding:binding,last_progress_ns:0,stamp_epoch:timeline::StampEpoch::default(),draw:0,heads:[0;2],cached_views:KVec::new(),quarantined_views:KVec::new(),quarantined_buffers:KVec::new(),quarantine_active_vm:false,recovery_aborted_draw:None,pool_delta:[0;2],slot:0,batch_count:0,early_count:0,stage_timestamps:[true;2],base:0,checkpoint:(0,[0;2],0,0,0,0),clusters,registers,_lower_tlbi:lower_tlbi}; // Lists and the matching manager are built before InitBM publication. job.initialize_parameter_buffer()?; for (index,pool) in UMA_POOLS.iter().enumerate() { @@ -557,8 +568,12 @@ impl Render { }; // Finish fallible allocations before replacing the current owner. let old_views=KVec::with_capacity(next.views.len(),GFP_KERNEL)?; - self.cached_views.reserve(1,GFP_KERNEL)?; - if self.cached_views.len()==3 {drop(self.cached_views.remove(0).map_err(|_|EIO)?);} + if self.quarantine_active_vm { + self.quarantined_views.reserve(1,GFP_KERNEL)?; + } else { + self.cached_views.reserve(1,GFP_KERNEL)?; + if self.cached_views.len()==3 {drop(self.cached_views.remove(0).map_err(|_|EIO)?);} + } let mut old=CachedViews { binding:core::mem::replace(&mut self._binding,next.binding), aliases:core::mem::replace(&mut self._aliases,next.aliases), @@ -567,7 +582,12 @@ impl Render { for (i,view) in next.views { old.views.push((i,self.view_owner(i).swap_gpu_view(view)?),GFP_KERNEL)?; } - self.cached_views.push(old,GFP_KERNEL)?; + if self.quarantine_active_vm { + self.quarantine_active_vm=false; + self.quarantined_views.push(old,GFP_KERNEL)?; + } else { + self.cached_views.push(old,GFP_KERNEL)?; + } } // Growth is legal only after exact retirement, and before append. // Cached VM mappings must be dropped before freeing the old backing. @@ -580,11 +600,14 @@ impl Render { for (field,base,bytes) in [(P::Tpc,s::TPC_LABEL,g.tpc_bytes),(P::Tilemap,s::TILEMAP_LABEL,g.tilemap_bytes)] { let size=usize::try_from(bytes).map_err(|_|EOVERFLOW)?; if size>self.passes[slot].get(field).size() { + let keep_old = !self.quarantined_views.is_empty() || self.quarantine_active_vm; + if keep_old { self.quarantined_buffers.reserve(1,GFP_KERNEL)?; } let buffer=Buffer::tiler(dev,uat.kernel_vm(),vm,size)?; self.cached_views.clear(); dev_info!(dev.as_ref(),"M3 render arena growth: slot={} object={} {} -> {} bytes GPU={:#x}\n", slot,base,self.passes[slot].get(field).size(),size,buffer.gpu_va()?); - *self.passes[slot].get_mut(field)=buffer; + let prev = core::mem::replace(self.passes[slot].get_mut(field), buffer); + if keep_old { let _ = self.quarantined_buffers.push(prev, GFP_KERNEL); } } } } @@ -768,19 +791,105 @@ impl Render { Ok(done) } pub(crate) fn complete(&mut self)->Result { - for (stamp,fw,pointers,value,head) in [(s::TA_STAMP,s::TA_FW_STAMP,s::TA_POINTERS,self.stamp_epoch.value(s::STAMP_TA - 256,self.draw),self.heads[0]), - (s::FRAGMENT_STAMP,s::FRAGMENT_FW_STAMP,s::FRAGMENT_POINTERS,self.stamp_epoch.value(s::STAMP_FRAGMENT - 256,self.draw),self.heads[1])] { + let recovered = self.recovery_aborted_draw == Some(self.draw); + for (stage,stamp,fw,pointers,value,head) in [(0usize,s::TA_STAMP,s::TA_FW_STAMP,s::TA_POINTERS,self.stamp_epoch.value(s::STAMP_TA - 256,self.draw),self.heads[0]), + (1usize,s::FRAGMENT_STAMP,s::FRAGMENT_FW_STAMP,s::FRAGMENT_POINTERS,self.stamp_epoch.value(s::STAMP_FRAGMENT - 256,self.draw),self.heads[1])] { + let allow_lagging_done = recovered && stage == 1; if self.objects[stamp].read_u32(0)?!=value || self.objects[fw].read_u32(0)?!=value - || self.objects[pointers].read_u32(queue::DONE)?!=u32::from(head) + || (!allow_lagging_done && self.objects[pointers].read_u32(queue::DONE)?!=u32::from(head)) || self.objects[pointers].read_u32(queue::READ)?!=u32::from(head) {return Ok(false);} } if self.profile==super::m3_profile::Profile::Extended && self.draw!=0 { - for pool in UMA_POOLS { - if self.objects[pool.manager].read_u64(0x54)?!=self.draw {return Ok(false);} + for (idx, pool) in UMA_POOLS.iter().enumerate() { + let actual = self.objects[pool.manager].read_u64(0x54)?; + let expected = self.draw.saturating_sub(self.pool_delta[idx]); + if actual < expected || actual > self.draw {return Ok(false);} + if actual > expected { + self.pool_delta[idx] = self.draw - actual; + } + } + } + Ok(true) + } + /// Clear TPC storage for all pass slots of an active batch before answering + /// recovery phase 2 when the firmware snapshot names a stopped tiler. + pub(crate) fn clear_active_tpc(&mut self, base: usize, count: usize) -> Result { + for index in 0..count { + let slot = Self::at(base, index); + self.passes[slot].get_mut(P::Tpc).fill(0)?; + } + crate::m3::agx_memory::publish(); + Ok(()) + } + /// Whether the firmware has drained both render work rings to their current write heads. + pub(crate) fn queues_drained(&mut self) -> Result { + for (pointers, head) in [(s::TA_POINTERS, self.heads[0]), (s::FRAGMENT_POINTERS, self.heads[1])] { + if self.objects[pointers].read_u32(queue::DONE)? != u32::from(head) + || self.objects[pointers].read_u32(queue::READ)? != u32::from(head) + { + return Ok(false); } } Ok(true) } + /// Whether TA aborted and retired its ring while fragment has `READ == head` + /// with `DONE != head` and neither the TA host stamp nor the fragment FW + /// stamp reached the expected draw value. + /// + /// On a tiler-only fault, 27.2 firmware advances `TA.DONE` (already before + /// phase 3) while leaving `TA_STAMP` behind and discarding the paired + /// fragment command without advancing `FRAGMENT_POINTERS.DONE` or + /// `FRAGMENT_FW_STAMP` (`READ` still reaches `head`); the next draw catches + /// `DONE` back up to `head`. + pub(crate) fn fragment_read_only_pending(&mut self) -> Result { + let ta_expected = self.stamp_epoch.value(s::STAMP_TA - 256, self.draw); + let fs_expected = self.stamp_epoch.value(s::STAMP_FRAGMENT - 256, self.draw); + let ta_host = self.objects[s::TA_STAMP].read_u32(0)?; + let fs_fw = self.objects[s::FRAGMENT_FW_STAMP].read_u32(0)?; + let ta_done = self.objects[s::TA_POINTERS].read_u32(queue::DONE)?; + let ta_read = self.objects[s::TA_POINTERS].read_u32(queue::READ)?; + let fs_done = self.objects[s::FRAGMENT_POINTERS].read_u32(queue::DONE)?; + let fs_read = self.objects[s::FRAGMENT_POINTERS].read_u32(queue::READ)?; + Ok(ta_done == u32::from(self.heads[0]) + && ta_read == u32::from(self.heads[0]) + && ta_host != ta_expected + && fs_read == u32::from(self.heads[1]) + && fs_done != u32::from(self.heads[1]) + && fs_fw != fs_expected) + } + /// Re-synchronize render stamps and pool expectations after firmware recovery + /// drained the stopped batch, and mark the faulting VM's binding for quarantine. + pub(crate) fn finish_recovery(&mut self, dev: &driver::AsahiDrmDevice) -> Result { + self.quarantine_active_vm = true; + self.recovery_aborted_draw = if self.fragment_read_only_pending()? { + Some(self.draw) + } else { + None + }; + let ta_expected = self.stamp_epoch.value(s::STAMP_TA - 256, self.draw); + let fs_expected = self.stamp_epoch.value(s::STAMP_FRAGMENT - 256, self.draw); + let ta_host = self.objects[s::TA_STAMP].read_u32(0)?; + let ta_fw = self.objects[s::TA_FW_STAMP].read_u32(0)?; + let fs_host = self.objects[s::FRAGMENT_STAMP].read_u32(0)?; + let fs_fw = self.objects[s::FRAGMENT_FW_STAMP].read_u32(0)?; + let pool0 = self.objects[UMA_POOLS[0].manager].read_u64(0x54)?; + let pool1 = self.objects[UMA_POOLS[1].manager].read_u64(0x54)?; + dev_info!( + dev.as_ref(), + "M3 recovery render post-drain: draw={} ta={:#x}/{:#x} (want {:#x}) fs={:#x}/{:#x} (want {:#x}) pool54={}/{}\n", + self.draw, ta_host, ta_fw, ta_expected, fs_host, fs_fw, fs_expected, pool0, pool1 + ); + if ta_host != ta_expected { self.objects[s::TA_STAMP].u32(0, ta_expected)?; } + if ta_fw != ta_expected { self.objects[s::TA_FW_STAMP].u32(0, ta_expected)?; } + if fs_host != fs_expected { self.objects[s::FRAGMENT_STAMP].u32(0, fs_expected)?; } + if fs_fw != fs_expected { self.objects[s::FRAGMENT_FW_STAMP].u32(0, fs_expected)?; } + if self.profile == super::m3_profile::Profile::Extended { + self.pool_delta[0] = self.draw.saturating_sub(pool0); + self.pool_delta[1] = self.draw.saturating_sub(pool1); + } + crate::m3::agx_memory::publish(); + Ok(()) + } pub(crate) fn log(&mut self,dev:&driver::AsahiDrmDevice)->Result { // Retain allocator state as well as payloads: an exhausted parameter // pool can stall TA without producing an MMU fault. diff --git a/drivers/gpu/drm/asahi/m3/m3_runtime.rs b/drivers/gpu/drm/asahi/m3/m3_runtime.rs index 8bd242a483432b..aadfb8f7d50bf0 100644 --- a/drivers/gpu/drm/asahi/m3/m3_runtime.rs +++ b/drivers/gpu/drm/asahi/m3/m3_runtime.rs @@ -40,9 +40,26 @@ struct GeometryTiming { } impl NativeJob { fn complete(&mut self)->Result {match self {Self::Compute(j)=>j.complete(),Self::Render(j)=>j.complete()}} + fn queues_drained(&mut self)->Result {match self {Self::Compute(j)=>j.queues_drained(),Self::Render(j)=>j.queues_drained()}} + fn finish_recovery(&mut self,dev:&driver::AsahiDrmDevice)->Result {match self {Self::Compute(j)=>j.finish_recovery(dev),Self::Render(j)=>j.finish_recovery(dev)}} fn log(&mut self,dev:&driver::AsahiDrmDevice)->Result {match self {Self::Compute(j)=>j.log(dev),Self::Render(j)=>j.log(dev)}} fn batch_gpu_span(&mut self)->Result<[u64;2]> {match self {Self::Compute(j)=>j.batch_gpu_span(),Self::Render(j)=>j.batch_gpu_span()}} } + +fn vm_failed(packet: &crate::m3::m3_submit::Packet) -> bool { + packet.vm.status().is_some_and(|status| status.get() != 0) +} + +fn latch_guilty(packet: &crate::m3::m3_submit::Packet, error: Error) { + if let Some(status) = packet.vm.status() { + status.note_recovery_guilty(); + status.record(error); + } +} + +fn now_ns() -> u64 { + ::ktime_get() as u64 +} struct Inner { transport: rtkit::RtKit, state: Arc, @@ -52,6 +69,13 @@ struct Inner { pending: KVec<(Arc,usize)>, /// Published batches, oldest first. More than one only with asahi.m3_pipeline_depth > 1. active: KVec, + /// Packets from firmware-aborted batches retained until teardown so their + /// quarantined VM job guards remain pinned; bounded by `quarantine_budget`. + quarantined_packets: KVec>, + quarantine_budget: crate::m3::m3_recovery::QuarantineBudget, + recovery_window_ns: u64, + recovery_window_count: u32, + recoveries: u64, gpu_pending: bool, active_power_last: Option>, active_power_samples: u32, @@ -191,6 +215,276 @@ impl Inner { for batch in self.active.drain_all() {Self::finish_all(&batch.entries,Err(error));} self.fail_pending(error); } + /// Answer the Extended (26.x / 27.2) firmware recovery phase handshake using + /// the shared `g16/recovery/logic.rs` state machine so only the guilty VM + /// loses its device while innocent bystanders and fresh clients continue. + fn recover_extended(&mut self, trigger: Error) -> Result { + use crate::m3::m3_recovery::{self as rec, logic, RecoveryAction, SnapshotEntry}; + let offsets = self.config.recovery_offsets().ok_or(EOPNOTSUPP)?; + if self.active.is_empty() || self.state.health.crashed() { + return Err(EIO); + } + let flights = self.active.len(); + if !self.quarantine_budget.can_admit(flights) { + dev_err!( + self.drm.as_ref(), + "M3 GPU quarantine limit reached ({}/{}); fail-stop\n", + self.quarantine_budget.count(), + rec::QUARANTINE_LIMIT + ); + return Err(EIO); + } + let start_ns = now_ns(); + if !logic::admit( + start_ns, + &mut self.recovery_window_ns, + &mut self.recovery_window_count, + ) { + dev_err!(self.drm.as_ref(), "M3 GPU recovery storm; fail-stop\n"); + return Err(EIO); + } + self.log_owners(trigger); + let vm = self.active[0].entries[0].0.vm.clone(); + let mut blame_err = trigger; + let overall = Instant::::now(); + let mut rounds = 0u32; + let mut prev_gen: Option = None; + let mut blamed = false; + loop { + if overall.elapsed() > Delta::from_millis(rec::RECOVERY_BUDGET_MS) { + dev_err!(self.drm.as_ref(), "M3 GPU recovery exceeded overall budget\n"); + return Err(ETIMEDOUT); + } + let wait_p1 = Instant::::now(); + loop { + if self.state.health.crashed() { + return Err(EIO); + } + let phase = self.config.recovery_phase()?; + match logic::action(phase, false, true) { + RecoveryAction::MarkAndAcknowledge => break, + RecoveryAction::Wait => { + if wait_p1.elapsed() > Delta::from_nanos(logic::EVENT_WAIT_NS as i64) { + dev_err!(self.drm.as_ref(), "M3 GPU recovery phase 1 did not arrive\n"); + return Err(ETIMEDOUT); + } + self.config.drain(&self.drm)?; + fsleep(Delta::from_millis(1)); + } + _ => { + dev_err!(self.drm.as_ref(), "M3 GPU recovery unexpected phase {}\n", phase); + return Err(EPROTO); + } + } + } + let generation = self.config.recovery_generation()?; + if prev_gen == Some(generation) { + dev_err!(self.drm.as_ref(), "M3 GPU recovery repeated generation {}\n", generation); + return Err(EPROTO); + } + prev_gen = Some(generation); + // Read MMU fault banks only once firmware has reached phase 1 (engines stopped + // and firmware waiting for host phase 2) so SGX+0xd800 cannot race with firmware. + if !blamed { + let mmu_fault = self.device.log_extended_fault_banks(&vm).unwrap_or(false); + if mmu_fault { + blame_err = EIO; + } + } + let mut entries = 0usize; + let mut clear_tpc = false; + let mut non_tiler_stop = false; + for idx in 0..offsets.snapshot_entries { + let (flags, target) = self.config.read_recovery_snapshot(idx)?; + let Some(entry) = SnapshotEntry::decode(flags, target) else { + break; + }; + if rec::stopped_tiler(entry.flags) { + clear_tpc = true; + } else { + non_tiler_stop = true; + } + if entries < 4 { + dev_info!( + self.drm.as_ref(), + "M3 recovery gen={} snapshot[{}]: flags={:#x} event={:#x} target={:#x}\n", + generation, + entries, + entry.flags, + entry.event, + entry.target + ); + } + entries += 1; + } + let tiler_only = rec::tiler_only_stop(clear_tpc, non_tiler_stop); + if clear_tpc { + for batch in self.active.iter() { + if let NativeJob::Render(j) = &mut self.jobs[batch.index] { + let renders = batch.mixed.as_ref().map_or(batch.entries.len(), |m| m.renders); + j.clear_active_tpc(batch.base, renders)?; + } + } + } + if !blamed { + for (packet, _) in self.active.iter().flat_map(|b| b.entries.iter()) { + latch_guilty(packet, blame_err); + } + blamed = true; + } + let ack_start = Instant::::now(); + self.config.write_recovery_phase(2)?; + let mut kicked = false; + loop { + if self.state.health.crashed() { + return Err(EIO); + } + let phase = self.config.recovery_phase()?; + let cur_gen = if phase == 3 { + self.config.recovery_generation()? + } else { + generation + }; + match logic::action(phase, true, cur_gen == generation) { + RecoveryAction::Resume => break, + RecoveryAction::Wait => { + let elapsed = ack_start.elapsed(); + if !kicked && elapsed > Delta::from_nanos((logic::RECOVERY_BUDGET_NS / 2) as i64) { + kicked = true; + dev_warn!(self.drm.as_ref(), "M3 GPU recovery: no phase 3 in 500 ms; ringing control doorbell\n"); + let _ = Pin::new(&mut self.transport).send_message(0x21, 0x0084_0000_0000_0011); + } + if elapsed > Delta::from_nanos(logic::RECOVERY_BUDGET_NS as i64) { + dev_err!(self.drm.as_ref(), "M3 GPU recovery phase 3 timed out (gen {})\n", generation); + return Err(ETIMEDOUT); + } + self.config.drain(&self.drm)?; + fsleep(Delta::from_millis(1)); + } + _ => { + dev_err!(self.drm.as_ref(), "M3 GPU recovery protocol error (phase={} gen={}/{})\n", phase, cur_gen, generation); + return Err(EPROTO); + } + } + } + self.config.write_recovery_phase(0)?; + self.config.note_recovered(generation); + dev_err!( + self.drm.as_ref(), + "M3 GPU recovery {} answered in {} ms ({} snapshot entries, clear_tpc={})\n", + generation, + ack_start.elapsed().as_millis(), + entries, + clear_tpc + ); + let check_busy = crate::m3::m3_params::retire_mmio(self.device.soc()) + & crate::m3::m3_params::RETIRE_MMIO_BUSY + != 0; + let drain_start = Instant::::now(); + let mut another_round = false; + loop { + self.config.drain(&self.drm)?; + let pipes_idle = self.config.pipes_idle()?; + let phase = self.config.recovery_phase()?; + let mut all_drained = pipes_idle; + if all_drained { + // Honor the SoC's retire_mmio mask: do not probe core-clock-gated busy + // registers (0xc020/0xc120) when RETIRE_MMIO_BUSY is omitted (e.g. G15G). + // Only allow the discarded-FS fallback on a snapshot-proven tiler-only stop + // once recovery is back in phase 0 (and fragment_read_only_pending verifies + // that TA aborted without advancing TA_STAMP and FS_FW_STAMP never advanced). + let engines_idle = tiler_only + && phase == 0 + && (!check_busy + || (self.device.pstate_register().unwrap_or(1) & 0xf) == 0 + || self.device.check_idle_parts(true, false).is_ok()); + for batch in self.active.iter() { + let batch_drained = match &mut self.jobs[batch.index] { + NativeJob::Render(j) => { + j.queues_drained()? + || (engines_idle && j.fragment_read_only_pending()?) + } + job => job.queues_drained()?, + }; + if !batch_drained { + all_drained = false; + break; + } + if let Some(mixed) = &batch.mixed { + if !self.jobs[mixed.compute_index].queues_drained()? { + all_drained = false; + break; + } + } + } + } + if all_drained { + self.config.note_recovered(generation); + break; + } + if self.state.health.crashed() { + return Err(EIO); + } + match logic::action(phase, false, true) { + RecoveryAction::Wait => {} + RecoveryAction::MarkAndAcknowledge => { + another_round = true; + break; + } + _ => { + dev_err!(self.drm.as_ref(), "M3 GPU recovery invalid phase {} during drain\n", phase); + return Err(EPROTO); + } + } + if drain_start.elapsed() > Delta::from_millis(rec::RECOVERY_DRAIN_MS) { + dev_err!(self.drm.as_ref(), "M3 GPU recovery stopped work did not drain\n"); + return Err(ETIMEDOUT); + } + fsleep(Delta::from_millis(1)); + } + if !another_round { + break; + } + rounds += 1; + if rounds > rec::FURTHER_RECOVERIES { + dev_err!(self.drm.as_ref(), "M3 GPU recovery exceeded further rounds ({})\n", rounds); + return Err(EIO); + } + } + // Re-sync stamps/pool counters and mark faulting VM views for quarantine. + for batch in self.active.iter() { + self.jobs[batch.index].finish_recovery(&self.drm)?; + if let Some(mixed) = &batch.mixed { + self.jobs[mixed.compute_index].finish_recovery(&self.drm)?; + } + } + // Reserve capacity before draining active batches; fail and pin every stopped packet. + let active_packets: usize = self.active.iter().map(|b| b.entries.len()).sum(); + let _ = self.quarantined_packets.reserve(active_packets, GFP_KERNEL); + self.quarantine_budget.charge(flights); + for batch in self.active.drain_all() { + for (packet, _) in batch.entries { + packet.finish(Err(blame_err)); + if !self.quarantined_packets.iter().any(|q| Arc::ptr_eq(q, &packet)) { + if self.quarantined_packets.push(packet.clone(), GFP_KERNEL).is_err() { + core::mem::forget(packet); + } + } + } + } + self.packets.clear(); + self.gpu_pending = false; + self.state.health.set_gpu_pending(false); + self.recoveries = self.recoveries.saturating_add(1); + dev_err!( + self.drm.as_ref(), + "M3 GPU recovered ({} so far, gen {}, blame {:?}); guilty VM isolated\n", + self.recoveries, + prev_gen.unwrap_or(0), + blame_err + ); + Ok(()) + } /// Name the processes whose published commands were in flight when the GPU failed. Batches /// in flight share one VM, so this is normally one process; a VM shared between processes /// names each submitter once (the first four). @@ -223,7 +517,7 @@ impl Inner { fn fail_front(&mut self,error:Error) { if let Ok((packet,_))=self.pending.remove(0) { if !self.packet_active(&packet) && !self.fault_captured {packet.release_guard();} - packet.finish(Err(error)); + packet.fail_packet(error); } } /// Signal every packet of `entries` (packets that continue past the batch included). @@ -321,6 +615,12 @@ impl Inner { fn publish_next(&mut self)->bool { let mut progress=false; while !self.pending.is_empty() && self.state.healthy() { + while let Some((packet,_))=self.pending.first() { + if !vm_failed(packet) {break;} + self.fail_front(EIO); + progress=true; + } + if self.pending.is_empty() {break;} match self.reseed_stamp_epochs() { Ok(true)=>{}, Ok(false)=>break, @@ -717,6 +1017,12 @@ impl Inner { if !self.state.healthy() || self.config.drain(&self.drm).is_err() { self.fail_active(EIO);return Err(EIO); } + if let Some(trigger) = self.config.take_recovery_trigger().unwrap_or(Some(EIO)) { + if let Err(e) = self.recover_extended(trigger) { + self.fail_active(e);return Err(e); + } + return Ok(true); + } // With later batches in flight, the oldest retires once its own last draw's stamps // have arrived; the last one is also checked for exact queue, event and engine idle. if self.active.len()>1 { @@ -735,6 +1041,12 @@ impl Inner { let (expired,previous)=self.active.first().map(|b|(b.start.elapsed()>=Delta::from_secs(2),b.previous_events)).ok_or(EIO)?; if expired { dev_err!(self.drm.as_ref(),"M3 pipelined completion events={} previous={}\n",self.config.completed_events,previous); + if self.config.recovery_phase() == Ok(1) { + if let Err(e) = self.recover_extended(ETIMEDOUT) { + self.fail_active(e);return Err(e); + } + return Ok(true); + } self.fail_active(ETIMEDOUT);return Err(ETIMEDOUT); } return Ok(false); @@ -853,6 +1165,12 @@ impl Inner { } if expired { dev_err!(self.drm.as_ref(),"M3 completion events={} previous={}\n",completed,previous); + if self.config.recovery_phase() == Ok(1) { + if let Err(e) = self.recover_extended(ETIMEDOUT) { + self.fail_active(e);return Err(e); + } + return Ok(true); + } self.fail_active(ETIMEDOUT);return Err(ETIMEDOUT); } Ok(false) @@ -1119,7 +1437,10 @@ impl Runtime { } }; Ok(Self { inner: ManuallyDrop::new(owner.write(Inner { transport, state, config, uat, window, drm, device, - jobs:KVec::new(),packets:KVec::new(),pending:KVec::new(),active:KVec::new(),gpu_pending:false,active_power_last:None,active_power_samples:0,fault_captured:false,timing:[[0;7];2],render_batches:[0;crate::m3::m3_pass_layout::SLOTS], + jobs:KVec::new(),packets:KVec::new(),pending:KVec::new(),active:KVec::new(), + quarantined_packets:KVec::new(),quarantine_budget:crate::m3::m3_recovery::QuarantineBudget::new(crate::m3::m3_recovery::QUARANTINE_LIMIT), + recovery_window_ns:0,recovery_window_count:0,recoveries:0, + gpu_pending:false,active_power_last:None,active_power_samples:0,fault_captured:false,timing:[[0;7];2],render_batches:[0;crate::m3::m3_pass_layout::SLOTS], geometry:[GeometryTiming::default();32],geometry_overflow:0,coalesced_packets:0,coalesced_render_stamps:0,mixed_batches:0,pass_cost:policy::PassCosts::default(),render_initialized:false,t8122_verdict:false, boot_step:crate::m3::t8122_start::BootStep::Publish })) }) } @@ -1160,6 +1481,7 @@ impl Runtime { let mut guard=shared.lock(); let inner=&mut *Option::as_mut(&mut *guard).ok_or(ENODEV)?.inner; if !inner.state.healthy() {return Err(EIO);} + if vm_failed(&packet) {return Err(EIO);} if packet.commands.is_empty() || packet.commands.len()>256 { pr_err!("M3 submit limit: commands={} maximum=256\n",packet.commands.len()); return Err(E2BIG); @@ -1214,6 +1536,9 @@ impl Runtime { if let Err(error)=inner.config.drain(&inner.drm) { inner.capture_fault(error);inner.fail_pending(EIO);return Service::Idle; } + if let Some(error) = inner.config.take_recovery_trigger().unwrap_or(Some(EIO)) { + inner.capture_fault(error);inner.fail_pending(EIO);return Service::Idle; + } return if inner.publish_next() {Service::Progress} else {Service::Idle}; } let messages=inner.state.event_messages.load(Ordering::Acquire); @@ -1293,6 +1618,7 @@ impl Runtime { while !self.inner.config.ready()? { let inner: &mut Inner = &mut *self.inner; inner.config.drain(&inner.drm)?; + if let Some(error) = inner.config.take_recovery_trigger()? { return Err(error); } if !inner.state.healthy() { return Err(EIO); } if deadline.elapsed() >= Delta::from_secs(2) { return Err(ETIMEDOUT); } fsleep(Delta::from_millis(1)); @@ -1300,7 +1626,7 @@ impl Runtime { self.retire_extended_control(first)?; self.inner.boot_step = BootStep::DeviceControl; // Each data master registers its two firmware engine classes. - for ordinal in 0..6 { + for ordinal in 0..super::m3_channel_format::ENGINE_CLASSES { let action = Action::Register { pipe: ordinal / 2, engine: ordinal % 2 + 1 }; self.send_extended_control(action)?; } @@ -1325,6 +1651,7 @@ impl Runtime { loop { let inner: &mut Inner = &mut *self.inner; inner.config.drain(&inner.drm)?; + if let Some(error) = inner.config.take_recovery_trigger()? { return Err(error); } if !inner.state.healthy() { return Err(EIO); } if inner.config.control_done(expected)? { return Ok(()); } if deadline.elapsed() >= Delta::from_secs(2) { return Err(ETIMEDOUT); } @@ -1407,7 +1734,7 @@ fn adopt_uat(drm: &driver::AsahiDrmDevice, soc: &'static crate::m3::m3_soc::Soc, let range = |r: crate::m3::agx_resources::Region| r.base..r.base + r.size; let geometry = mmu::UatGeometry { ias: cfg.uat_ias.into(), oas: cfg.uat_oas }; let regions = mmu::AdoptedRegions { handoff: range(handoff), ttbs: range(ttbs), kernel_root: tables.base }; - let uat = mmu::Uat::new_adopted_with_user_upper(drm, geometry, ®ions, + let uat = mmu::Uat::new_adopted_ram_with_user_upper(drm, geometry, ®ions, profile == super::m3_profile::Profile::Legacy)?; let mut window = crate::g15::uat::Window::from_regions(handoff.base, ttbs.base, tables.base, shared_l2.base)?; window.bootstrap(drm.as_ref().as_ref(), &uat)?; diff --git a/drivers/gpu/drm/asahi/m3/m3_soc.rs b/drivers/gpu/drm/asahi/m3/m3_soc.rs index 7500822c4124c5..80bd1c34310749 100644 --- a/drivers/gpu/drm/asahi/m3/m3_soc.rs +++ b/drivers/gpu/drm/asahi/m3/m3_soc.rs @@ -113,9 +113,6 @@ pub(crate) struct Soc { pub(crate) board: &'static str, /// GPU node compatible. pub(crate) gpu: &'static str, - /// Boards the runtime starts on by default and registers a render node on. On a T8122 it - /// starts on no other board, whatever `asahi.m3_backend` says (`m3_params::t8122_backend`). - pub(crate) validated_boards: &'static [&'static [u8]], /// GPU clusters, and core slots per cluster. pub(crate) clusters: u32, pub(crate) cores_per_cluster: u32, @@ -268,13 +265,13 @@ pub(crate) fn by_chip(chip_id: u32) -> Option<&'static Soc> { /// T8122 (M3, G15G): one die, one cluster of ten core slots (eight or ten of them active). /// -/// The compatibles, the mailbox and its interrupts are the T8122 device tree's. The identity is -/// the one the T8122 identity gate admits (`t8122_admission`: family 7, variant 2, revision 0x20, -/// core slots in the first core-mask word only), with the die count of the AGX3 identification -/// table (`hw::agx3::T8122`). The hardware configuration is `hw::t8122`; power configuration -/// comes from the boot loader. Startup uses the guarded `t8122_start` path, which selects this -/// table's values by default on admitted Air boards and adds a performance-state cap. Explicit -/// `asahi.t8122_start=0` disables startup; firmware, board and resource admission still apply. +/// The compatibles, the mailbox and its interrupts are the T8122 device tree's. The identity is the +/// one the T8122 identity gate admits (`t8122_admission`: family 7, variant 2, revision 0x20, core +/// slots in the first core-mask word only), with one die. The hardware configuration is +/// `hw::t8122`; power configuration comes from the boot loader. Startup uses the guarded +/// `t8122_start` path, which selects this table's values by default on admitted Air boards and adds +/// a performance-state cap. Explicit `asahi.t8122_start=0` disables startup; firmware, board and +/// resource admission still apply. pub(crate) static T8122: Soc = Soc { name: "T8122", gpu_name: "G15G", @@ -284,9 +281,8 @@ pub(crate) static T8122: Soc = Soc { gpu_revision_id: hw::GpuRevisionID::C0, board: "apple,t8122", gpu: "apple,agx-t8122", - // The M3 MacBook Airs (13" J613, 15" J615). Allowed, not validated: the runtime has not run - // on either, and starts only behind a boot loader that hands the GPU over. - validated_boards: &[b"apple,j613", b"apple,j615"], + // The runtime starts only behind a boot loader that hands the GPU over + // (`m3_board::handed_over`). clusters: 1, cores_per_cluster: 10, mailbox_compatibles: &[ diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 155bda714e9d9f..314e9da622c33d 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -1,8 +1,11 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT //! Bounded M3 compute and graphics submissions through the common DRM scheduler/syncobjs. use kernel::{c_str,dma_fence::*,drm::sched,prelude::*,sync::{Arc,Mutex},new_mutex,xarray}; -use crate::{file,m3::agx_uapi,mmu,queue,m3::m3_drm::Shared}; -use core::sync::atomic::{AtomicBool, Ordering}; +use crate::{file,m3::agx_uapi,mmu,queue}; +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +use crate::m3::m3_drm::Shared; +use crate::alloc::Allocator as _; +use core::sync::atomic::{AtomicBool, AtomicU8, Ordering}; #[derive(Default)] pub(crate) struct Completion; #[vtable] @@ -10,7 +13,7 @@ impl FenceOps for Completion { fn get_driver_name<'a>(self:&'a FenceObject)->&'a CStr {c_str!("asahi")} fn get_timeline_name<'a>(self:&'a FenceObject)->&'a CStr {c_str!("m3-native")} } -pub(crate) struct Destination { mapping: Arc, offset: usize } +pub(crate) struct Destination { _buffer: Arc, iova: u64 } impl Destination { fn resolve(objects: Pin<&xarray::XArray>>, timestamp: agx_uapi::UapiTimestamp) -> Result> { @@ -24,11 +27,12 @@ impl Destination { if offset & 7 != 0 || offset.checked_add(8).ok_or(EOVERFLOW)? > mapping.size() { return Err(EINVAL); } - Ok(Some(Self { mapping, offset })) + let iova = mapping.iova() + offset as u64; + Ok(Some(Self { _buffer: buffer.clone(), iova })) } } } - fn firmware_address(&self) -> u64 { self.mapping.iova() + self.offset as u64 } + fn firmware_address(&self) -> u64 { self.iova } } #[derive(Copy,Clone)] @@ -44,7 +48,11 @@ pub(crate) struct Packet { pub(crate) wide_visibility:KVec, pub(crate) render_attachments:KVec<[crate::m3::agx_attachments::Attachments;2]>, completion:UserFence, - finish_claimed: AtomicBool, + finish_state: AtomicU8, + /// Set once a terminal fault (`fail_vm == true`) quarantines `vm_job`; + /// thereafter `release_guard()` is a no-op so neither `fail_front()` nor + /// `withdraw()` can unmap a quarantined VM's pages. + guard_pinned: AtomicBool, /// Set before a batch with any of this packet's commands can change firmware-visible state, /// and never cleared. published: AtomicBool, @@ -53,6 +61,18 @@ pub(crate) struct Packet { /// Who submitted the packet, for the failure log only. pub(crate) owner:Owner, vm_job:Pin>>>, + /// G14 firmware 27.2: the compute preemption buffer in the packet's VM, kept until retirement. + pub(crate) preempt:Option>, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + pub(crate) render_queue: Option>, +} +/// The runtime a queue's packets go to: the M3 runtime or the G14 firmware-27.2 compute runtime. +#[derive(Clone)] +pub(crate) enum Sink { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + M3(Shared), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + G14V27_2(Arc), } /// The process and thread that submitted a packet, recorded in the submit ioctl. Only logged: /// a renamed task leaves a stale name, which is harmless. @@ -62,8 +82,7 @@ impl Owner { fn current()->Self { let task=kernel::current!(); let leader=task.group_leader(); - Self {pid:leader.pid(),process:crate::m3::m3_client::task_comm(leader), - thread:crate::m3::m3_client::task_comm(task)} + Self {pid:leader.pid(),process:task_comm(leader),thread:task_comm(task)} } fn name(comm:&[u8;16])->&str { let len=comm.iter().position(|&b|b==0).unwrap_or(comm.len()); @@ -72,6 +91,19 @@ impl Owner { pub(crate) fn process(&self)->&str {Self::name(&self.process)} pub(crate) fn thread(&self)->&str {Self::name(&self.thread)} } +/// The name of `task`, for log lines only. +pub(crate) fn task_comm(task: &kernel::task::Task) -> [u8; 16] { + let mut name = [0u8; 16]; + // SAFETY: `comm` is a fixed-size array inside the live task. It is read byte by byte with + // volatile loads because a concurrent rename may change it; a torn name is only printed. + unsafe { + let comm = core::ptr::addr_of!((*task.as_ptr()).comm).cast::(); + for (i, byte) in name.iter_mut().enumerate() { + *byte = comm.add(i).read_volatile(); + } + } + name +} impl Packet { pub(crate) fn profile_id(&self)->usize {self as *const Self as usize} pub(crate) fn timestamp_addresses(&self,index:usize)->[u64;2] { @@ -82,24 +114,90 @@ impl Packet { self.timestamps[index][stage*2+i].as_ref().map_or(0,Destination::firmware_address))) } /// Called only after all published commands retired or before any publication. - pub(crate) fn release_guard(&self) {drop(self.vm_job.lock().take());} + /// Never drops a guard that was pinned by a terminal fault quarantine. + pub(crate) fn release_guard(&self) { + let mut guard_slot = self.vm_job.lock(); + if self.guard_pinned.load(Ordering::Acquire) { + return; + } + drop(guard_slot.take()); + } /// Called before the first firmware-visible change of a batch that includes this packet. pub(crate) fn mark_published(&self) {self.published.store(true,Ordering::Relaxed);} /// Whether the firmware may have seen any of this packet's commands. pub(crate) fn may_be_published(&self)->bool {self.published.load(Ordering::Relaxed)} pub(crate) fn retired(&self) {self.release_guard();self.finish(Ok(()));} pub(crate) fn finish(&self,result:Result) { + self.complete(result, true); + } + /// Fail the fence without making a packet rejection or cancellation a VM error. + /// Terminal device-loss errors still record on `VmStatus`. + /// A published prefix still owns its mappings until the runtime retires it. + pub(crate) fn fail_packet(&self,error:Error) { + self.complete(Err(error), false); + } + fn complete(&self,result:Result,fail_vm:bool) { + const PENDING: u8 = 0; + const PACKET_FAILED: u8 = 1; + const TERMINAL: u8 = 2; // Retirement, cancellation and a queued scheduler timeout can race. - // Claim error/signal ownership once; this flag is NOT proof that the - // fence is signaled or that hardware DMA has stopped. - if self.finish_claimed.swap(true, Ordering::Relaxed) { return; } + // Claim fence error/signal ownership once while still allowing a later + // terminal GPU fault (`fail_vm == true`) on a published prefix to record + // on `VmStatus` after an earlier `fail_packet()`. + let record_vm = |e: Error| { + if let Some(status) = self.vm.status() { + if fail_vm { + status.record(e); + } else { + status.record_if_device_loss(e); + } + } + }; + match result { + Ok(()) => { + if self.finish_state.swap(TERMINAL, Ordering::AcqRel) != PENDING { + return; + } + } + Err(e) if fail_vm => match self.finish_state.swap(TERMINAL, Ordering::AcqRel) { + PENDING => {} + PACKET_FAILED => { + let guard_slot = self.vm_job.lock(); + if let Some(guard) = guard_slot.as_ref() { + self.guard_pinned.store(true, Ordering::Release); + guard.quarantine(); + } + drop(guard_slot); + record_vm(e); + return; + } + _ => return, + }, + Err(_) => { + if self + .finish_state + .compare_exchange(PENDING, PACKET_FAILED, Ordering::AcqRel, Ordering::Acquire) + .is_err() + { + return; + } + } + } if let Err(e)=result { // A guard still held here belongs to work the firmware may still run: block // mapping changes before the error fence is visible (as G15 does), so userspace - // can't unmap memory under it. It stays with the packet until the runtime drops - // the packet, after the firmware has provably stopped. - if let Some(guard)=self.vm_job.lock().as_ref() {guard.quarantine();} - if let Some(status) = self.vm.status() { status.record(e); } + // can't unmap memory under it. Terminal faults (`fail_vm`) also pin the guard + // against later `release_guard()` calls so it stays with the packet until the + // runtime drops it after the firmware has provably stopped. + let guard_slot = self.vm_job.lock(); + if let Some(guard) = guard_slot.as_ref() { + if fail_vm { + self.guard_pinned.store(true, Ordering::Release); + } + guard.quarantine(); + } + drop(guard_slot); + record_vm(e); self.completion.set_error(e); } // A scheduler job/fence and the runtime's last packet can outlive @@ -107,9 +205,12 @@ impl Packet { // nonzero: GEM closes otherwise accumulate across completed frames. // Signalling an error is not retirement. crate::m3::agx_memory::publish(); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] let profile=crate::debug::debug_enabled(crate::debug::DebugFlags::M3PassTiming); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] let before=if profile {crate::m3::m3_runtime::physical_counter()} else {0}; self.completion.signal(); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] if profile { let after=crate::m3::m3_runtime::physical_counter(); let status=match result {Ok(())=>0,Err(e)=>e.to_errno()}; @@ -118,9 +219,9 @@ impl Packet { } } } -pub(crate) struct Job {shared:Shared,packet:Arc} +pub(crate) struct Job {shared:Sink,packet:Arc} /// Timeout state of a [`Job`], owned by the scheduler's timeout worker. -pub(crate) struct JobTimeout {shared:Shared,packet:Arc} +pub(crate) struct JobTimeout {shared:Sink,packet:Arc} impl sched::JobImpl for Job { type TimeoutData = JobTimeout; fn timeout_data(&self)->JobTimeout { @@ -129,21 +230,55 @@ impl sched::JobImpl for Job { fn run(job:&mut Self)->Result> { // Queue the packet and return its fence; the completion worker publishes and retires // it, so the scheduler can hand over further ready jobs meanwhile. - if let Err(e)=crate::m3::m3_runtime::Runtime::submit(&job.shared,job.packet.clone()) { + let submitted=match &job.shared { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + Sink::M3(shared)=>crate::m3::m3_runtime::Runtime::submit(shared,job.packet.clone()), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + Sink::G14V27_2(runtime)=>runtime.submit(job.packet.clone()), + }; + if let Err(e)=submitted { pr_err!("M3 scheduler: submission failed {:?}\n",e); // submit() failed before this packet could be published. - job.packet.release_guard();job.packet.finish(Err(e)); + job.packet.release_guard();job.packet.fail_packet(e); } Ok(Some(Fence::from_fence(&job.packet.completion))) } fn timed_out(job:&mut JobTimeout,_finished:bool)->sched::Status { + match job.shared.clone() { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + Sink::M3(shared)=>Self::timed_out_m3(shared,job), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + Sink::G14V27_2(runtime)=>{ + // The runtime's own command timeout fails a hung GPU; a healthy one is late. + // Run its service once, so a hang is found without a notification. + runtime.wake(); + if runtime.healthy() {return sched::Status::NoHang;} + runtime.withdraw(&job.packet); + job.packet.finish(Err(EIO)); + sched::Status::NoDevice + } + } + } + fn cancel(job:&mut Self) { + match &job.shared { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + Sink::M3(shared)=>{crate::m3::m3_runtime::Runtime::withdraw(shared,&job.packet);} + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + Sink::G14V27_2(runtime)=>runtime.withdraw(&job.packet), + } + job.packet.fail_packet(ECANCELED); + } +} +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +impl Job { + fn timed_out_m3(shared:Shared,job:&mut JobTimeout)->sched::Status { // Retain the publishing branch's explicit diagnostic override. if !crate::m3::m3_params::timeout_nohang() { - if let Some(r)=Option::as_mut(&mut *job.shared.lock()) {r.health().mark_failed();} - crate::m3::m3_runtime::Runtime::withdraw(&job.shared,&job.packet); + if let Some(r)=Option::as_mut(&mut *shared.lock()) {r.health().mark_failed();} + crate::m3::m3_runtime::Runtime::withdraw(&shared,&job.packet); job.packet.finish(Err(ETIMEDOUT));return sched::Status::NoDevice; } - let guard=job.shared.lock(); + let guard=shared.lock(); let Some(runtime)=guard.as_ref() else { job.packet.finish(Err(ENODEV)); return sched::Status::NoDevice; @@ -154,14 +289,10 @@ impl sched::JobImpl for Job { // device loss or corrupting an already signaled fence. if runtime.health().healthy() { return sched::Status::NoHang; } drop(guard); - crate::m3::m3_runtime::Runtime::withdraw(&job.shared,&job.packet); + crate::m3::m3_runtime::Runtime::withdraw(&shared,&job.packet); job.packet.finish(Err(EIO)); sched::Status::NoDevice } - fn cancel(job:&mut Self) { - crate::m3::m3_runtime::Runtime::withdraw(&job.shared,&job.packet); - job.packet.finish(Err(ECANCELED)); - } } struct AddressSpace<'a>(&'a mmu::Vm); impl agx_uapi::GpuAddressSpace for AddressSpace<'_> { @@ -175,13 +306,27 @@ impl agx_uapi::GpuAddressSpace for AddressSpace<'_> { } pub(crate) struct Queue { entity:sched::Entity,_scheduler:Arc>, - shared:Shared,vm:mmu::Vm,usc:u64,fences:FenceContexts, + shared:Sink,vm:mmu::Vm,usc:u64,fences:FenceContexts, + /// G14 firmware 27.2: the VM's private allocator and the size of the per-packet + /// preemption buffer it provides. + preempt_alloc:Option<(Arc>,usize)>, /// Whether the SoC advertises early tiling (`m3_soc::Features::fragment_dependency`). + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + render_queue: Option>, early_tiling:bool, wide_visibility:bool, + /// Whether this queue's render command builder encodes depth and stencil compression + /// for every sample count and layer count. Otherwise only the single-sample, + /// single-layer compressed depth layout is admitted. + zls_compression_all_layouts:bool, + /// Whether this queue's command builders encode the render and compute sampler heaps and + /// helper programs, in the 13.5 places. Otherwise they are refused: the M3 26.x commands + /// stream their sampler state and carry no helper. + samplers_and_helpers:bool, urgency:u8, } impl Queue { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] pub(crate) fn new(shared:Shared,scheduler:Arc>,vm:mmu::Vm,priority:u32,usc:u64, early_tiling:bool, wide_visibility:bool)->Result { agx_uapi::QueueUscWindow{base:usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}.validate().map_err(|_|EINVAL)?; @@ -190,18 +335,51 @@ impl Queue { let priority=match priority {3=>sched::Priority::Low,2=>sched::Priority::Normal, 1=>sched::Priority::High,0=>sched::Priority::Kernel,_=>return Err(EINVAL)}; Ok(Self {entity:sched::Entity::new(&scheduler,priority)?,_scheduler:scheduler, - shared,vm,usc,fences:FenceContexts::new(1,c_str!("asahi_m3_queue"),kernel::static_lock_class!())?, - early_tiling,wide_visibility,urgency}) + shared:Sink::M3(shared),vm,usc,fences:FenceContexts::new(1,c_str!("asahi_m3_queue"),kernel::static_lock_class!())?, + early_tiling,wide_visibility,zls_compression_all_layouts:false,samplers_and_helpers:false,urgency,preempt_alloc:None, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + render_queue: None}) + } + /// A G14 firmware-27.2 compute queue: the same front end, published by that runtime. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + pub(crate) fn new_g14_v27_2(runtime:Arc,scheduler:Arc>,vm:mmu::Vm,priority:u32,usc:u64, + ualloc_priv:Arc>,preempt_bytes:usize, + render_queue: Arc)->Result { + agx_uapi::QueueUscWindow{base:usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}.validate().map_err(|_|EINVAL)?; + let urgency=3u8.saturating_sub(priority.min(3) as u8); + let priority=match priority {3=>sched::Priority::Low,2=>sched::Priority::Normal, + 1=>sched::Priority::High,0=>sched::Priority::Kernel,_=>return Err(EINVAL)}; + Ok(Self {entity:sched::Entity::new(&scheduler,priority)?,_scheduler:scheduler, + shared:Sink::G14V27_2(runtime),vm,usc,fences:FenceContexts::new(1,c_str!("asahi_g14_queue"),kernel::static_lock_class!())?, + early_tiling:false,wide_visibility:false, + // The G14 render command carries the depth and stencil load, store and partial + // compression words in every layout (g14_v27_2_render.rs). + zls_compression_all_layouts:true, + // Its render commands carry the sampler heap and both helper programs, and its + // compute command the 13.5 compute JobParameters1 with the helper and the sampler + // heap words the firmware loads for every command type (g14_v27_2_render.rs, + // g14_v27_2_abi.rs, gpu/v27_2.rs). + samplers_and_helpers:true, + urgency,preempt_alloc:Some((ualloc_priv,preempt_bytes)), + render_queue: Some(render_queue)}) } } impl queue::Queue for Queue { - fn submit(&mut self,_reg_data:&crate::driver::AsahiRegData<'_>,_id:u64,mut syncs:KVec,in_sync_count:usize, - raw:&[u8],objects:Pin<&xarray::XArray>>)->Result { + fn submit( + &mut self, + _reg_data: &crate::driver::AsahiRegData<'_>, + _id: u64, + mut syncs: KVVec, + in_sync_count: usize, + raw: &[u8], + objects: Pin<&xarray::XArray>>, + ) -> Result { let vm_job=self.vm.retain_job()?; let mut parser=agx_uapi::UapiCommandParser::new(raw);let mut commands=KVec::new();let mut timestamps=KVec::new();let mut flushes=KVec::new();let mut visibility=KVec::new();let mut render_attachments=KVec::new(); while let Some(command)=parser.next_hardware().map_err(|_|EINVAL)? { if let agx_uapi::ParsedHardwareCommand::Render{payload,vertex_attachments,fragment_attachments,..}=command { - if let Err(e)=validate_render(payload,self.usc,&AddressSpace(&self.vm),self.early_tiling) { + if let Err(e)=validate_render(payload,self.usc,&AddressSpace(&self.vm),self.early_tiling, + self.zls_compression_all_layouts,self.samplers_and_helpers) { pr_err!("M3 render rejected {:?}: flags={:#x} size={}x{} layers={} samples={} utile={}x{} sample_size={} depth={:#x} stencil={:#x} zls={:#x} samplers={} heap={:#x}\n",e,payload.flags,payload.width,payload.height,payload.layers,payload.samples,payload.utile_width,payload.utile_height,payload.sample_size,payload.depth.base,payload.stencil.base,payload.zls_control,payload.sampler_count,payload.sampler_heap); return Err(e); } @@ -221,7 +399,7 @@ impl queue::Queue for Queue { // Other engines and helpers need their own M3 firmware translation. let wide=kernel::uapi::drm_asahi_compute_flags_DRM_ASAHI_COMPUTE_WIDE_VISIBILITY as u32; if payload.flags & !wide !=0 || (!self.wide_visibility && payload.flags & wide != 0) - || payload.sampler_count!=0 || payload.sampler_heap!=0 { + || (!self.samplers_and_helpers && (payload.sampler_count!=0 || payload.sampler_heap!=0)) { pr_err!("M3 compute rejected: flags={:#x} samplers={} heap={:#x} attachments={} timestamps={}/{}\n",payload.flags,payload.sampler_count,payload.sampler_heap,attachments.as_slice().len(),payload.timestamps.start.handle,payload.timestamps.end.handle); return Err(ENOTSUPP); } @@ -229,23 +407,48 @@ impl queue::Queue for Queue { // The common translator validates the original command/attachment // addresses; this M3 scheduling hint changes none of them. payload.flags &= !wide; + // The common translator refuses helpers; a queue that encodes one validates and + // takes it here. + let empty=agx_uapi::UapiHelperProgram{binary:0,config:0,data:0}; + let helper=if self.samplers_and_helpers { + agx_uapi::validate_helper(agx_uapi::QueueUscWindow{base:self.usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}, + &AddressSpace(&self.vm),payload.helper).map_err(|e| { + pr_err!("M3 compute helper rejected {:?}: helper={:?}\n",e,payload.helper); + EINVAL + })?; + core::mem::replace(&mut payload.helper,empty) + } else {empty}; render_attachments.push([crate::m3::agx_attachments::Attachments::EMPTY;2],GFP_KERNEL)?; flushes.push(encode_attachments(&self.vm,&attachments)?,GFP_KERNEL)?; let c=agx_uapi::translate_compute_command(payload,attachments, agx_uapi::QueueUscWindow{base:self.usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}, &AddressSpace(&self.vm)).map_err(|e| { - pr_err!("M3 compute translation rejected {:?}: stream={:#x}..{:#x} helper={:?}\n",e,payload.control_stream_base,payload.control_stream_end,payload.helper); + pr_err!("M3 compute translation rejected {:?}: stream={:#x}..{:#x} helper={:?} samplers={} heap={:#x}\n",e,payload.control_stream_base,payload.control_stream_end,payload.helper,payload.sampler_count,payload.sampler_heap); EINVAL })?; - crate::m3::m3_client::check_compute_launches(&self.vm,&AddressSpace(&self.vm),c.control_stream_base,c.control_stream_end)?; + // The launch check decodes the 26.x G15 CDM launch format; G14 streams differ. + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + if self.preempt_alloc.is_none() { + crate::m3::m3_client::check_compute_launches(&self.vm,&AddressSpace(&self.vm),c.control_stream_base,c.control_stream_end)?; + } timestamps.push([Destination::resolve(objects,payload.timestamps.start)?, Destination::resolve(objects,payload.timestamps.end)?,None,None],GFP_KERNEL)?; - commands.push(Command::Compute(crate::m3::agx_compute::Control{base:c.control_stream_base,end:c.control_stream_end,usc_base:self.usc}),GFP_KERNEL)?; + // The translator checked the heap: at most 1024 samplers, both fields set or both zero, + // 8-byte aligned and readable in this VM. Only a queue that encodes it admits one. + commands.push(Command::Compute(crate::m3::agx_compute::Control{base:c.control_stream_base,end:c.control_stream_end,usc_base:self.usc,helper, + sampler_heap:c.sampler_heap,sampler_count:c.sampler_count}),GFP_KERNEL)?; } parser.finish().map_err(|_|EINVAL)?; - let packet=Arc::new(Packet{vm:self.vm.clone(),commands,timestamps,attachments:flushes,wide_visibility:visibility,render_attachments, + let preempt=match &self.preempt_alloc { + Some((alloc,bytes)) if commands.iter().any(|c| matches!(c, Command::Compute(_))) => + Some(alloc.lock().array_empty::(*bytes)?), + _ => None, + }; + let packet=Arc::new(Packet{preempt, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + render_queue: self.render_queue.clone(),vm:self.vm.clone(),commands,timestamps,attachments:flushes,wide_visibility:visibility,render_attachments, completion:self.fences.new_fence(0,Completion)?.into(), - finish_claimed:AtomicBool::new(false),published:AtomicBool::new(false),urgency:self.urgency,owner:Owner::current(), + finish_state:AtomicU8::new(0),guard_pinned:AtomicBool::new(false),published:AtomicBool::new(false),urgency:self.urgency,owner:Owner::current(), vm_job:KBox::pin_init(new_mutex!(Some(vm_job)),GFP_KERNEL)?},GFP_KERNEL)?; let mut job=self.entity.new_job(1,Job{shared:self.shared.clone(),packet})?; for sync in syncs.drain(0..in_sync_count) {if let Some(f)=sync.fence {job.add_dependency(f)?;}} @@ -277,20 +480,24 @@ fn encode_attachments(vm: &mmu::Vm, list: &agx_uapi::UapiAttachmentList) } fn validate_render(r: agx_uapi::UapiRenderCommand, usc: u64, space: &AddressSpace<'_>, - early_tiling: bool) -> Result { + early_tiling: bool, zls_compression_all_layouts: bool, samplers_and_helpers: bool) -> Result { use agx_uapi::{GpuAddressSpace, GpuAccess}; if r.sample_size % 8 != 0 {return Err(ENOTSUPP);} let empty = agx_uapi::UapiHelperProgram { binary:0, config:0, data:0 }; // Early tiling (render flag bit 5) only where it is advertised. + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] let stage_scope=if early_tiling && crate::m3::m3_params::early_tiling() {1<<5} else {0}; + #[cfg(not(CONFIG_DRM_ASAHI_M3_T8122))] + let stage_scope = { let _ = early_tiling; 0 }; if r.flags & !(2|16|(1<<18)|stage_scope) != 0 || !matches!(r.samples, 1 | 2 | 4) - || r.sampler_count != 0 || r.sampler_heap != 0 - || r.vertex_helper != empty || r.fragment_helper != empty - || r.stencil.compression_base != 0 || r.stencil.compression_stride != 0 + || (!samplers_and_helpers && (r.sampler_count != 0 || r.sampler_heap != 0 + || r.vertex_helper != empty || r.fragment_helper != empty)) + || (!zls_compression_all_layouts + && (r.stencil.compression_base != 0 || r.stencil.compression_stride != 0)) || r.ppp_control & !0x203 != 0 { return Err(ENOTSUPP); } // Native 26A428 descriptors witness the ZLS metadata registers and mirrors // for single-sample, single-layer depth. Keep other layouts unqualified. - if (r.depth.compression_base != 0 || r.stencil.compression_base != 0) + if !zls_compression_all_layouts && (r.depth.compression_base != 0 || r.stencil.compression_base != 0) && (r.samples != 1 || r.layers != 1) {return Err(ENOTSUPP);} // sample_size describes color tilebuffer storage. Depth/stencil-only // passes legitimately require zero bytes of color storage. @@ -299,6 +506,7 @@ fn validate_render(r: agx_uapi::UapiRenderCommand, usc: u64, space: &AddressSpac || u32::from(r.sample_size)*u32::from(r.utile_width)*u32::from(r.utile_height)*u32::from(r.samples)>32768 { return Err(EINVAL); } + agx_uapi::validate_sampler(space, r.sampler_heap, r.sampler_count.into()).map_err(|_| EINVAL)?; crate::m3::agx_render_state::compact(r.vdm_base).map_err(|_| EINVAL)?; if r.vdm_base & 3 != 0 || !space.covers(r.vdm_base,4,GpuAccess::Read) || r.scissor_base == 0 || r.scissor_base & 7 != 0 || !space.covers(r.scissor_base,8,GpuAccess::Read) { @@ -313,5 +521,9 @@ fn validate_render(r: agx_uapi::UapiRenderCommand, usc: u64, space: &AddressSpac window.full_program(space,p.usc).map_err(|_| EINVAL)?; if !space.covers(usc+u64::from(p.usc & !63),64,GpuAccess::Read) { return Err(EINVAL); } } + // Only a queue that encodes helpers gets here with one (refused above otherwise). + for helper in [r.vertex_helper,r.fragment_helper] { + agx_uapi::validate_helper(window,space,helper).map_err(|_| EINVAL)?; + } Ok(()) } diff --git a/drivers/gpu/drm/asahi/m3/m3_thermal_policy.rs b/drivers/gpu/drm/asahi/m3/m3_thermal_policy.rs index 2ae70634ff5567..1b2412b7f78092 100644 --- a/drivers/gpu/drm/asahi/m3/m3_thermal_policy.rs +++ b/drivers/gpu/drm/asahi/m3/m3_thermal_policy.rs @@ -271,6 +271,7 @@ mod zone_tests { } assert_eq!(required_zones(b"apple,j613\0"), 1); assert_eq!(required_zones(b"apple,j615\0"), 1); + assert_eq!(required_zones(b"apple,j504\0apple,t8122\0"), 1); } #[test] diff --git a/drivers/gpu/drm/asahi/m3/mod.rs b/drivers/gpu/drm/asahi/m3/mod.rs index eafd5732bceac8..fbb6e0852dc7e8 100644 --- a/drivers/gpu/drm/asahi/m3/mod.rs +++ b/drivers/gpu/drm/asahi/m3/mod.rs @@ -70,18 +70,17 @@ pub(crate) fn t8122_admitted(pdev: &platform::Device>) -> Result<&'stat } // The T8122 runtime, ported from the 7.1.12 release-20 kernel (c46d7dcdb871). -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] -mod agx_attachments; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] -mod agx_compute; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +// The 26.x submission front end, shared with the G14 firmware-27.2 runtime. +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] +pub(crate) mod agx_attachments; +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] +pub(crate) mod agx_compute; +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] mod agx_memory; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod agx_resources; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] -mod agx_status; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] -mod agx_uapi; +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] +pub(crate) mod agx_uapi; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod g15_raw; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] @@ -124,8 +123,8 @@ mod m3_resources; mod m3_rtkit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_runtime; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] -mod m3_submit; +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] +pub(crate) mod m3_submit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_thermal; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] @@ -141,8 +140,6 @@ mod m3_compute_sequence; mod m3_compute_storage; -mod m3_coverage; - mod m3_init_layout; mod m3_init_storage; @@ -201,11 +198,16 @@ pub(crate) mod m3_soc; mod t8122_hwdata; -mod m3_init_26; +pub(crate) mod m3_init_26; mod m3_profile; -mod m3_mmio_26; +mod m3_recovery; +pub(crate) mod m3_mmio_26; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_power_26; -mod m3_channel_format; +pub(crate) mod m3_channel_format; +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +pub(crate) use m3_channel_format::{idle_cursor, submission_entry, Action, CONTROL_BYTES}; +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +pub(crate) use m3_init_storage::DEVICE_CONTROL; diff --git a/drivers/gpu/drm/asahi/m3/t8122_knobs.rs b/drivers/gpu/drm/asahi/m3/t8122_knobs.rs index ca0f8a6d499ccd..f74cda0dc2ada3 100644 --- a/drivers/gpu/drm/asahi/m3/t8122_knobs.rs +++ b/drivers/gpu/drm/asahi/m3/t8122_knobs.rs @@ -132,11 +132,12 @@ pub(crate) fn start(raw: &Raw) -> Start { } } -/// The shipped board policy changes only an omitted start parameter. Explicit recovery-off, -/// explicit experimental start, and malformed values retain their original meanings. -/// Hardware resources and firmware identity are admitted separately by the caller. -pub(crate) fn start_for_board(raw: &Raw, admitted_board: bool) -> Start { - if raw.start == UNSET && admitted_board { +/// The shipped default changes only an omitted start parameter: it starts where the boot loader +/// handed the GPU over. Explicit recovery-off, explicit experimental start, and malformed values +/// retain their original meanings. Hardware resources and firmware identity are admitted +/// separately by the caller. +pub(crate) fn start_for_board(raw: &Raw, handed_over: bool) -> Start { + if raw.start == UNSET && handed_over { Start::On } else { start(raw) diff --git a/drivers/gpu/drm/asahi/m3/t8122_start.rs b/drivers/gpu/drm/asahi/m3/t8122_start.rs index 737034dd6f8c13..44487af7656448 100644 --- a/drivers/gpu/drm/asahi/m3/t8122_start.rs +++ b/drivers/gpu/drm/asahi/m3/t8122_start.rs @@ -3,7 +3,7 @@ //! T8122 (M3, G15G) board-default startup and bounded experiment values. //! //! The T8122 table (`m3_soc::T8122`) is complete. An omitted start parameter starts -//! automatically only on its listed Air boards; explicit `asahi.t8122_start=0` +//! automatically only where the boot loader handed the GPU over; explicit `asahi.t8122_start=0` //! remains the recovery opt-out. Resource and known-firmware admission still run. //! The same table values can be changed for a controlled experiment by //! rebooting with a parameter: @@ -237,16 +237,16 @@ pub(crate) fn mmio_prot(read_only: u32, slot: usize) -> Prot { /// Decide, after resource admission, whether `soc` starts with the experiment values. /// -/// Any SoC but T8122: Ok(None). On its listed Air boards, an omitted parameter -/// selects the table values; explicit 0 disables startup, and invalid values fail -/// closed. Existing backend admission still refuses an unlisted board, even -/// with an explicit start request. +/// Any SoC but T8122: Ok(None). Where the boot loader handed the GPU over, an +/// omitted parameter selects the table values; explicit 0 disables startup, and +/// invalid values fail closed. Backend admission still refuses a GPU that was not +/// handed over, even with an explicit start request. pub(crate) fn arm(dev: &device::Device, soc: &Soc) -> Result> { if !is_t8122(soc) { return Ok(None); } let raw = crate::m3::m3_params::t8122_params(); - match knobs::start_for_board(&raw, crate::m3::m3_board::runtime_validated_board(soc)) { + match knobs::start_for_board(&raw, crate::m3::m3_board::handed_over(dev)) { Start::On => {} Start::Off => { if raw.values_given() { @@ -301,8 +301,8 @@ pub(crate) fn arm(dev: &device::Device, soc: &Soc) -> Result> e.mapping_count(), storage::IOMAP_BASE ); - // J613/J615 have no SoC die temperature zone yet, so a cap above the no-feedback limit runs - // the fanless GPU without any temperature feedback (`m3_thermal` holds the cap but gets no + // J615 and J504 have no SoC die temperature zone yet, so a cap above the no-feedback limit + // runs the GPU without any temperature feedback (`m3_thermal` holds the cap but gets no // reading). The runtime cap and the firmware ceiling stay equal, because the cap is at most // the no-feedback limit. if v.pstate_cap > knobs::PSTATE_CAP { @@ -352,11 +352,11 @@ pub(crate) fn refused(dev: &device::Device, experiment: Option<&Experiment>, sta } } -/// Log that resource admission refused a T8122 start selected by board default or flag. +/// Log that resource admission refused a T8122 start selected by the handoff default or flag. pub(crate) fn not_admitted(dev: &device::Device, soc: &Soc) { if is_t8122(soc) && knobs::start_for_board( &crate::m3::m3_params::t8122_params(), - crate::m3::m3_board::runtime_validated_board(soc), + crate::m3::m3_board::handed_over(dev), ) == Start::On { dev_err!( dev, diff --git a/drivers/gpu/drm/asahi/m5/drm.rs b/drivers/gpu/drm/asahi/m5/drm.rs index 6ab2108d8813b2..4ee01fced03105 100644 --- a/drivers/gpu/drm/asahi/m5/drm.rs +++ b/drivers/gpu/drm/asahi/m5/drm.rs @@ -181,7 +181,7 @@ impl gpu::Gpu for M5DrmGpu { }; Ok(KBox::new(queue, GFP_KERNEL)?) } - fn map_timestamp_buffer(&self, _bo: gem::ObjectRef, _range: Range) + fn map_timestamp_buffer(&self, _bo: gem::ObjectRef, _range: Range, _window: crate::timestamp::WindowPermit) -> Result { Err(ENOTSUPP) } } @@ -196,7 +196,7 @@ impl FenceOps for M5SubmissionFence { /// allocation failure after userspace has already supplied its wait targets. struct OutputPublication { fence: UserFence, - syncs: KVec, + syncs: KVVec, input_count: usize, result: Result, } @@ -237,7 +237,7 @@ struct M5Queue { impl queue::Queue for M5Queue { fn submit(&mut self, _reg_data: &AsahiRegData<'_>, _submission_id: u64, - syncs: KVec, + syncs: KVVec, in_sync_count: usize, cmdbuf_raw: &[u8], _objects: Pin<&xarray::XArray>>) -> Result { if in_sync_count > syncs.len() { return Err(EINVAL); } diff --git a/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs b/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs index 0245811e9b5dbe..c21d700c8ef362 100644 --- a/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs +++ b/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs @@ -8,6 +8,7 @@ use super::parameter_buffer::{M5ParameterBuffer, BLOCK_BYTES, PAGE_LIST_BYTES, P use super::target_memory::M5TargetMemory; use crate::{driver::AsahiDrmDevice, m5::render_desc, m5::render, mmu}; use crate::m5::completion::MAX_GRAPHICS_GENERATION; +use core::sync::atomic::{fence, Ordering}; use kernel::prelude::*; const HIGH: u64 = 0xffff_fc20_c100_0000; @@ -271,8 +272,9 @@ impl M5GraphicsJob { /// for the new VM and the pools are aliased into it. The previous VM's /// render targets are not used in the new VM: they stay cached under the /// previous VM for its next turn, and the next application frame takes or - /// allocates targets in the new VM. The caller publishes the new roots - /// before the next draw. + /// allocates targets in the new VM. Pool data storage is cleared before + /// the new VM maps it; allocator and parameter-manager state is kept. The + /// caller publishes the new roots before the next draw. pub(super) fn rebind_vm(&mut self, dev: &AsahiDrmDevice, vm: &mmu::Vm) -> Result { if self.owns_vm(vm) { return Ok(()); } if self.scheduler_status()? != [2, 0] { return Err(EBUSY); } @@ -286,6 +288,12 @@ impl M5GraphicsJob { for alias in self.parameter_buffer.alias_into(vm)? { aliases.push(alias, GFP_KERNEL)?; } + // Compute operands and the preemption page released by the previous + // VM may still hold its data; clear them, and restore the zero + // robustness page, before another VM maps them. + self.compute_storage.with_bytes_mut(|out| { out.fill(0); Ok(()) })?; + // Order the clears before the new roots and the next draw are published. + fence(Ordering::SeqCst); let storage = self.compute_storage.iova(); if let Some(alias) = self.compute_storage.map_alias_at_with_guards( vm, storage, mmu::PROT_GPU_SHARED_RW, 2)? { diff --git a/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs b/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs index 1d5bd727ee719d..867ef48a346063 100644 --- a/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs +++ b/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs @@ -110,9 +110,17 @@ impl M5GraphicsUsc { /// addresses, reproducing each allocation's guard reservation, so every /// firmware record naming the directory, free list or blocks stays valid /// across a render client handoff. The returned aliases must be kept for - /// as long as that VM may submit. + /// as long as that VM may submit. The caller has verified that all work + /// using the pool has retired. pub(super) fn alias_into(&mut self, vm: &mmu::Vm) -> Result> { let range = crate::m5::vm_layout::auxiliary_range(&vm.kernel_range()).ok_or(EINVAL)?; + // Blocks released by the previous VM may still hold its shader stack + // and spill data; clear them before another VM maps them. The + // directory and free list are allocator state that the firmware's + // cursors refer to, so they are kept (see below). + for block in self.blocks.iter_mut() { + block.with_bytes_mut(|out| { out.fill(0); Ok(()) })?; + } let mut aliases = KVec::new(); let alias = |object: &mut MappedObject, size: usize, guards: usize, aliases: &mut KVec| -> Result { diff --git a/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs b/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs index 3c6b955b6c799e..901c099eac795e 100644 --- a/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs +++ b/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs @@ -90,9 +90,18 @@ impl M5ParameterBuffer { /// Map the retained pool into another application VM at the same compact /// addresses with the original two-page guard reservations, so the /// firmware's parameter-manager records keep naming valid pages after a - /// render client handoff. + /// render client handoff. The caller has verified that all work using + /// the pool has retired. pub(super) fn alias_into(&mut self, vm: &mmu::Vm) -> Result> { let range = vm_layout::compact_range(&vm.kernel_range()).ok_or(EINVAL)?; + // Blocks, scene scratch and the discard page released by the previous + // VM may still hold its scene data; clear them before another VM maps + // them. The page list and metrics are parameter-manager state named + // by the retained firmware records and are kept. + for object in Iterator::chain(self.blocks.iter_mut(), + [&mut self.scene_scratch, &mut self.discard]) { + object.with_bytes_mut(|out| { out.fill(0); Ok(()) })?; + } let mut aliases = KVec::new(); let alias = |object: &mut MappedObject, aliases: &mut KVec| -> Result { let end = object.iova() diff --git a/drivers/gpu/drm/asahi/mem.rs b/drivers/gpu/drm/asahi/mem.rs index 79071cbc434a04..1f4518be0bf29a 100644 --- a/drivers/gpu/drm/asahi/mem.rs +++ b/drivers/gpu/drm/asahi/mem.rs @@ -120,11 +120,6 @@ pub(crate) fn tlbi_range(asid: Asid, va: usize, len: usize) { let mut val: u64 = (u64::from(asid) << 48) | (2 << 46) | (start_pg as u64 & BADDR_MASK); let pages = end_pg - start_pg; - // Guess? It's possible that the page count is in terms of 4K pages - // when the CPU is in 4K mode... - #[cfg(CONFIG_ARM64_4K_PAGES)] - let pages = 4 * pages; - if pages == 1 { tlbi_page(asid, va); return; diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index fb2a796604e12c..665143e64751fc 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -207,6 +207,17 @@ impl Ledger { /// Reserves the bytes against both limits; the returned [`Commit`] gives /// them back when it is dropped. pub(crate) fn admit(&'static self, client: &Arc, bytes: u64) -> Result { + self.reserve(client, bytes)?; + Ok(Commit { + ledger: self, + client: client.clone(), + bytes, + }) + } + + /// Adds `bytes` to `client`'s and the device's committed totals if both stay within their + /// limits; otherwise counts a refusal and fails with `ENOMEM`, adding nothing. + fn reserve(&self, client: &Client, bytes: u64) -> Result { let client_limit = self.client_limit.load(Ordering::Relaxed); if !try_add_within(&client.committed, bytes, client_limit, 0) { self.refused.fetch_add(1, Ordering::Relaxed); @@ -224,11 +235,74 @@ impl Ledger { self.refused.fetch_add(1, Ordering::Relaxed); return Err(ENOMEM); } - Ok(Commit { - ledger: self, - client: client.clone(), - bytes, - }) + Ok(()) + } +} + +/// Kernel memory that grows with a client's requests and is freed with one of the client's +/// objects, such as the page tables of a VM: charged to the client as held user memory of the +/// same size would be, and released in full when this is dropped. +pub(crate) struct Usage { + ledger: &'static Ledger, + client: Arc, + bytes: u64, +} + +impl Usage { + pub(crate) fn new(ledger: &'static Ledger, client: Arc) -> Self { + Self { + ledger, + client, + bytes: 0, + } + } + + /// Charges `bytes` more if the client and the device stay within their limits, as a new + /// user object of that size would be admitted; otherwise fails with `ENOMEM` and charges + /// nothing. + pub(crate) fn try_add(&mut self, bytes: u64) -> Result { + self.ledger.reserve(&self.client, bytes)?; + self.hold(bytes); + Ok(()) + } + + /// Charges `bytes` more whatever the limits, for memory that already exists. + pub(crate) fn add(&mut self, bytes: u64) { + self.client.committed.fetch_add(bytes, Ordering::AcqRel); + self.ledger.user_committed.fetch_add(bytes, Ordering::AcqRel); + self.hold(bytes); + } + + /// Creates a new [`Usage`] on the same ledger and client holding the same number of bytes, + /// without checking limits: used to hand a removed record's charge to a surviving piece right + /// before the removed record is dropped. + pub(crate) fn transfer_copy(&self) -> Self { + let mut copy = Self::new(self.ledger, self.client.clone()); + copy.add(self.bytes); + copy + } + + /// Creates a new [`Usage`] on the same ledger and client charged `bytes` if both limits + /// admit it; otherwise fails with `ENOMEM` and charges nothing. + pub(crate) fn try_fork(&self, bytes: u64) -> Result { + let mut copy = Self::new(self.ledger, self.client.clone()); + copy.try_add(bytes)?; + Ok(copy) + } + + fn hold(&mut self, bytes: u64) { + self.client.resident.fetch_add(bytes, Ordering::AcqRel); + self.ledger.user_resident.fetch_add(bytes, Ordering::AcqRel); + self.bytes += bytes; + } +} + +impl Drop for Usage { + fn drop(&mut self) { + sub(&self.client.resident, self.bytes); + sub(&self.ledger.user_resident, self.bytes); + sub(&self.client.committed, self.bytes); + sub(&self.ledger.user_committed, self.bytes); } } @@ -238,6 +312,8 @@ pub(crate) struct Client { committed: AtomicU64, /// Size of those whose backing the GPU currently holds. resident: AtomicU64, + /// Bytes of the device's firmware timestamp window this client's bound buffers hold. + timestamp_window: AtomicU64, } impl Client { @@ -246,6 +322,7 @@ impl Client { Self { committed: AtomicU64::new(0), resident: AtomicU64::new(0), + timestamp_window: AtomicU64::new(0), }, GFP_KERNEL, )?) @@ -258,6 +335,37 @@ impl Client { pub(crate) fn resident(&self) -> u64 { self.resident.load(Ordering::Relaxed) } + + /// Bytes of the firmware timestamp window this client holds. + #[cfg(CONFIG_KUNIT = "y")] + pub(crate) fn timestamp_window(&self) -> u64 { + self.timestamp_window.load(Ordering::Relaxed) + } + + /// Takes `bytes` of the firmware timestamp window for `client` if its share stays within + /// `limit` (which must not be 0); the returned [`WindowShare`] gives them back when dropped. + /// Concurrent callers cannot overshoot. + pub(crate) fn take_window(client: &Arc, bytes: u64, limit: u64) -> Option { + if limit == 0 || !try_add_within(&client.timestamp_window, bytes, limit, 0) { + return None; + } + Some(WindowShare { + client: client.clone(), + bytes, + }) + } +} + +/// Bytes of the firmware timestamp window held by one bound buffer of a client. +pub(crate) struct WindowShare { + client: Arc, + bytes: u64, +} + +impl Drop for WindowShare { + fn drop(&mut self) { + sub(&self.client.timestamp_window, self.bytes); + } } /// Bytes of a user object reserved against the limits. @@ -623,6 +731,35 @@ mod tests { Ok(()) } + static USAGE: Ledger = Ledger::new(); + + #[test] + fn usage_grows_within_the_limits_and_is_released_whole() -> Result { + USAGE.set_limits(Limits { device: 100 * MIB, client: 60 * MIB }); + let a = Client::new()?; + let mut usage = Usage::new(&USAGE, a.clone()); + // Memory that already exists is counted whatever the limits. + usage.add(16 * MIB); + usage.try_add(40 * MIB)?; + // 4 MiB are left under a's limit: refused, and nothing more is counted. + assert_eq!(usage.try_add(8 * MIB), Err(ENOMEM)); + assert_eq!((a.committed(), a.resident()), (56 * MIB, 56 * MIB)); + assert_eq!(USAGE.refused.load(Ordering::Relaxed), 1); + assert_eq!(USAGE.user_resident.load(Ordering::Relaxed), 56 * MIB); + // The bytes count against the device limit for other clients as well. + let b = Client::new()?; + assert!(USAGE.admit(&b, 50 * MIB).is_err()); + let b1 = USAGE.admit(&b, 44 * MIB)?; + // Dropping releases everything it charged. + drop(usage); + assert_eq!((a.committed(), a.resident()), (0, 0)); + assert_eq!(USAGE.user_committed.load(Ordering::Relaxed), 44 * MIB); + assert_eq!(USAGE.user_resident.load(Ordering::Relaxed), 0); + drop(b1); + assert_eq!(USAGE.user_committed.load(Ordering::Relaxed), 0); + Ok(()) + } + #[test] fn imports_are_not_counted() { let charge = Charge::none(); diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index a3b98ca76fc1a6..be4d18f7cee350 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -511,12 +511,17 @@ fn lock_vm( Ok(VmExecGuard(unsafe { gpuvm.exec_lock(obj, interruptible)? })) } -#[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] -pub(crate) struct VmReadGuard(VmExecGuard); +#[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] +pub(crate) struct VmReadGuard<'a>(gpuvm::GpuVmInnerGuard<'a, VmInner>); -#[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] -impl VmReadGuard { - #[cfg(CONFIG_DRM_ASAHI_G15)] +#[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] +impl VmReadGuard<'_> { + #[cfg(CONFIG_DRM_ASAHI_G16)] + pub(crate) fn epoch(&self) -> Option { + self.0.epoch + } + + #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] pub(crate) fn covers_range(&mut self, address: u64, size: u64, read: bool, write: bool) -> bool { Vm::covers_range_locked(&mut self.0, address, size, read, write) } @@ -561,11 +566,17 @@ impl SgSegments { } } +/// Kernel memory one GPUVA takes: the node that records one mapping in a VM. +const GPUVA_BYTES: u64 = size_of::>() as u64; + /// Preallocated resources needed to execute a VM operation. /// /// VM operations may require allocating new GPUVA objects to track mappings. /// To avoid allocation failures during the operation, preallocate the -/// maximum number of GPUVAs that might be needed. +/// maximum number of GPUVAs that might be needed. They are charged to the +/// memory cgroup of the task that asks for the operation and, in a VM charged +/// to a client, to that client's memory limit: a GPUVA lasts as long as the +/// mapping it records. struct VmOpResources { /// Preallocated GPUVA objects for remap operations. /// @@ -574,23 +585,107 @@ struct VmOpResources { /// objects (one for the new mapping, and two for the previous and next /// mappings). preallocated_gpuvas: [Option>; 3], + /// Preallocated charge for the new mapping inserted by `sm_step_map`, taken + /// before the operation starts so that the map step cannot fail on memory + /// limits after modifying page tables. A recorded mapping keeps its charge + /// in its [`VmGpuVa`]; an unused charge goes back with this. + /// + /// Kept separate from `split_charge` so a map strictly inside an existing + /// mapping cannot have its remap step consume the new mapping's charge. + gpuva_charge: Option, + /// Preallocated charge for a deferred hole-punch unmap split, reserved before + /// accepting the unmap into quarantine so `drain_mappings()` cannot fail with + /// `ENOMEM` and quarantined splits cannot bypass limits. + split_charge: Option, } impl VmOpResources { + /// Three preallocated GPUVAs plus one charge for a new mapping, charged to `client` if the + /// VM has one. Fails with ENOMEM before anything changes if the client's or the device's + /// limit refuses it. + fn with_gpuvas(client: Option<&Arc>) -> Result { + Self::with_gpuvas_on(&crate::memacct::LEDGER, client) + } + + fn with_gpuvas_on( + ledger: &'static crate::memacct::Ledger, + client: Option<&Arc>, + ) -> Result { + let gpuva_charge = client + .map(|client| { + let mut usage = crate::memacct::Usage::new(ledger, client.clone()); + usage.try_add(GPUVA_BYTES)?; + Ok::<_, Error>(usage) + }) + .transpose()?; + Ok(Self { + preallocated_gpuvas: [ + Some(GpuVaAlloc::::new(GFP_KERNEL_ACCOUNT)?), + Some(GpuVaAlloc::::new(GFP_KERNEL_ACCOUNT)?), + Some(GpuVaAlloc::::new(GFP_KERNEL_ACCOUNT)?), + ], + gpuva_charge, + split_charge: None, + }) + } + + /// No GPUVAs, for operations that only remove whole mappings. + fn without_gpuvas() -> Self { + Self { + preallocated_gpuvas: [None, None, None], + gpuva_charge: None, + split_charge: None, + } + } + /// Resources for unmapping a range. /// /// An unmap splits at most the two mappings that straddle its ends. Each split takes two /// GPUVAs before it knows which pieces survive and returns the unused one, so cutting the tail /// of one mapping and the head of the next needs three GPUVAs at the second split. + /// + /// No memory-limit charge is reserved here: whole-mapping and truncating unmaps never + /// increase the node count and always succeed at the limit; an immediate hole-punch split + /// checks limits in `sm_step_remap` before changing any page table, while a deferred + /// hole-punch unmap reserves `split_charge` before acceptance via `reserve_split_charge()`. fn for_unmap() -> Result { Ok(Self { preallocated_gpuvas: [ - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - Some(GpuVaAlloc::::new(GFP_KERNEL)?), + Some(GpuVaAlloc::::new(GFP_KERNEL_ACCOUNT)?), + Some(GpuVaAlloc::::new(GFP_KERNEL_ACCOUNT)?), + Some(GpuVaAlloc::::new(GFP_KERNEL_ACCOUNT)?), ], + gpuva_charge: None, + split_charge: None, }) } + + /// Reserves one GPUVA charge for a deferred hole-punch unmap before it is accepted into + /// quarantine, failing with `ENOMEM` if the client or device limit refuses it. Idempotent. + pub(super) fn reserve_split_charge( + &mut self, + client: Option<&Arc>, + ) -> Result { + self.reserve_split_charge_on(&crate::memacct::LEDGER, client) + } + + fn reserve_split_charge_on( + &mut self, + ledger: &'static crate::memacct::Ledger, + client: Option<&Arc>, + ) -> Result { + if self.split_charge.is_some() { + return Ok(()); + } + self.split_charge = client + .map(|client| { + let mut usage = crate::memacct::Usage::new(ledger, client.clone()); + usage.try_add(GPUVA_BYTES)?; + Ok::<_, Error>(usage) + }) + .transpose()?; + Ok(()) + } } struct StepContext<'ctx> { @@ -627,6 +722,16 @@ impl<'ctx> StepContext<'ctx> { .ok_or(EINVAL) } + /// Takes the preallocated charge for the mapping `sm_step_map` is about to record. + fn preallocated_charge(&mut self) -> Option { + self.resources.gpuva_charge.take() + } + + /// Takes the preallocated split charge reserved for a deferred hole-punch unmap. + fn preallocated_split_charge(&mut self) -> Option { + self.resources.split_charge.take() + } + /// Returns an unused GPUVA object to the preallocated pool. /// If the pool is already full, the unused allocation is simply dropped. fn return_preallocated_gpuva(&mut self, gpuva: GpuVaAlloc) { @@ -642,10 +747,23 @@ impl<'ctx> StepContext<'ctx> { } /// Per-mapping metadata that survives backing eviction and GPUVA splits. -#[derive(Default, Clone)] struct VmGpuVa { prot: Option, bind_sequence: u64, + /// The GPUVA's charge against the VM's client, given back with the GPUVA. + _charge: Option, +} + +impl Clone for VmGpuVa { + /// Copies the mapping metadata for a snapshot (`next_private_mapping`). The live GPUVA in + /// the tree keeps the memory charge, so the snapshot carries none. + fn clone(&self) -> Self { + Self { + prot: self.prot, + bind_sequence: self.bind_sequence, + _charge: None, + } + } } impl gpuvm::DriverGpuVm for VmInner { @@ -671,9 +789,8 @@ impl gpuvm::DriverGpuVm for VmInner { ).map_err(|_| EOVERFLOW)? + 1; let _mutation = self.mapping_addition(); let (map_addr, map_length) = (op.addr(), op.length() as usize); - let mut iova = op.addr(); let mut left = op.length() as usize; - let mut offset = op.gem_offset() as usize; + let offset = op.gem_offset() as usize; let one_page = op.flags().contains(gpuvm::GpuVaFlag::REPEAT); @@ -696,7 +813,7 @@ impl gpuvm::DriverGpuVm for VmInner { if is_sparse_tile(op.flags()) { // Kernel tile fill: the GEM only anchors the GPUVA. let result = if one_page { - self.map_sparse_tile(iova..iova + left as u64, ctx.prot) + self.map_sparse_tile(map_addr..map_addr + left as u64, ctx.prot) } else { Err(EINVAL) }; @@ -710,53 +827,25 @@ impl gpuvm::DriverGpuVm for VmInner { // Never acquire the object reservation from inside the GPUVM map callback. let segments = op.vm_bo().data().segments.lock(); let sgt = segments.as_ref().ok_or(EFAULT)?; - for &(dma_address, dma_len) in sgt.iter() { - let mut addr = dma_address as usize; - let mut len = dma_len as usize; - - if left == 0 { - break; - } - - if offset > 0 { - let skip = len.min(offset); - addr += skip; - len -= skip; - offset -= skip; - } - if len == 0 { - continue; - } - - assert!(offset == 0); - - if one_page { - len = left; - } else { - len = len.min(left); - } - + if left > 0 { mod_dev_dbg!( self.dev, - "MMU: map: {:#x}:{:#x} -> {:#x} [OP={}]\n", - addr, - len, - iova, + "MMU: map_segments: {:#x}+{:#x} [OP={}]\n", + map_addr, + left, one_page ); - - if let Err(error) = self.page_table.map_pages( - iova..(iova + len as u64), - addr as PhysicalAddr, + if let Err(error) = self.page_table.map_segments( + map_addr..(map_addr + left as u64), + sgt.iter() + .map(|&(dma_address, dma_len)| (dma_address as PhysicalAddr, dma_len as usize)), + offset, ctx.prot, one_page, ) { self.rollback_failed_map(map_addr, map_length as u64); return Err(error); } - - left -= len; - iova += len as u64; } drop(segments); @@ -776,6 +865,7 @@ impl gpuvm::DriverGpuVm for VmInner { VmGpuVa { prot: Some(ctx.prot), bind_sequence, + _charge: ctx.preallocated_charge(), }, ); ctx.bind_sequence = bind_sequence; @@ -806,6 +896,8 @@ impl gpuvm::DriverGpuVm for VmInner { let orig_prot = op.va_to_unmap().data().prot.ok_or(EINVAL)?; let orig_bind_sequence = op.va_to_unmap().data().bind_sequence; let orig_invalidated = op.va_to_unmap().flags().contains(GpuVaFlag::INVALIDATED); + let has_prev = op.prev().is_some(); + let has_next = op.next().is_some(); // Only unmap the hole between prev/next, if they exist let unmap_start = if let Some(op) = op.prev() { @@ -843,6 +935,29 @@ impl gpuvm::DriverGpuVm for VmInner { } }; + // Splitting one mapping into two adds a net GPUVA node. Such a mapping strictly + // contains the operation's range, so it is the sole overlapping GPUVA and no page + // tables have changed yet: use a split charge already reserved when a quarantined + // unmap was accepted, or check memory limits here before unmapping anything. + let extra_charge = if has_prev && has_next { + match op.va_to_unmap().data()._charge.as_ref() { + Some(charge) => match ctx.preallocated_split_charge() { + Some(preallocated) => Some(preallocated), + None => match charge.try_fork(GPUVA_BYTES) { + Ok(forked) => Some(forked), + Err(error) => { + ctx.return_preallocated_gpuva(prev_gpuva); + ctx.return_preallocated_gpuva(next_gpuva); + return Err(error); + } + }, + }, + None => None, + } + } else { + None + }; + let _mutation = self.mapping_mutation(); if orig_invalidated { self.page_table @@ -866,21 +981,42 @@ impl gpuvm::DriverGpuVm for VmInner { self.tlbi_contexts_naming_root(unmap_start, unmap_range as usize); + // One surviving piece inherits the removed node's charge (net zero once + // `remap_ret.unmapped_va` drops below); if both pieces survive, the second + // takes the extra charge admitted above. + let inherited_charge = (has_prev || has_next) + .then(|| { + op.va_to_unmap() + .data() + ._charge + .as_ref() + .map(crate::memacct::Usage::transfer_copy) + }) + .flatten(); + let (prev_charge, next_charge) = match (has_prev, has_next) { + (true, true) => (inherited_charge, extra_charge), + (true, false) => (inherited_charge, None), + (false, true) => (None, inherited_charge), + (false, false) => (None, None), + }; let (op_remapped, remap_ret) = op.remap( [prev_gpuva, next_gpuva], VmGpuVa { prot: Some(orig_prot), bind_sequence: orig_bind_sequence, + _charge: prev_charge, }, VmGpuVa { prot: Some(orig_prot), bind_sequence: orig_bind_sequence, + _charge: next_charge, }, ); if let Some(unused_va) = remap_ret.unused_va { ctx.return_preallocated_gpuva(unused_va); } + drop(remap_ret.unmapped_va); Ok(op_remapped) } @@ -1140,7 +1276,7 @@ impl VmInner { /// Install only into the empty range reserved by `map_node`. fn map_node_prepared(&mut self, node: &mm::Node<(), KernelMappingInner>, prot: Prot) -> Result { - let mut iova = node.start(); + let iova = node.start(); let segments = node .bo .as_ref() @@ -1149,60 +1285,24 @@ impl VmInner { .data() .segments .lock(); - let mut offset = node.offset; - let mut left = node.mapped_size; if let Some(segments) = &*segments { - for (dma_address, dma_len) in segments.iter() { - if left == 0 { - break; - } - - // TODO: proper DMA address/length handling - let mut addr = *dma_address as usize; - let mut len: usize = *dma_len as usize; - - if (offset | addr | len | iova as usize) & UAT_PGMSK != 0 { - dev_err!( - self.dev.as_ref(), - "MMU: KernelMapping {:#x}:{:#x} -> {:#x} is not page-aligned\n", - addr, - len, - iova - ); - return Err(EINVAL); - } - - if offset > 0 { - let skip = len.min(offset); - addr += skip; - len -= skip; - offset -= skip; - } - - len = len.min(left); - - if len == 0 { - continue; - } - + if node.mapped_size > 0 { mod_dev_dbg!( self.dev, - "MMU: map: {:#x}:{:#x} -> {:#x}\n", - addr, - len, - iova + "MMU: map_node_prepared: {:#x}+{:#x}\n", + iova, + node.mapped_size ); - - self.page_table.map_pages( - iova..(iova + len as u64), - addr as PhysicalAddr, + self.page_table.map_segments( + iova..(iova + node.mapped_size as u64), + segments + .iter() + .map(|&(dma_address, dma_len)| (dma_address as PhysicalAddr, dma_len as usize)), + node.offset, prot, false, )?; - - iova += len as u64; - left -= len; } } @@ -2051,6 +2151,7 @@ struct UatShared { map_kernel_to_user: bool, handoff_rgn: UatRegion, ttbs_rgn: UatRegion, + clean_poc: bool, quirks: UatQuirks, } @@ -2080,9 +2181,11 @@ impl UatShared { } } - /// Writes back context-table slot `idx` after it changed, where this SoC needs it. + /// Writes back context-table slot `idx` after it changed, where the UAT + /// walker does not snoop the CPU caches (either an adopted UAT or a SoC + /// with `quirks.clean_tables`). fn publish_slot(&self, idx: usize) { - if self.quirks.clean_tables { + if self.clean_poc || self.quirks.clean_tables { let slot = core::ptr::from_ref(&self.ttbs()[idx]).cast::(); pgtable::clean_poc(slot, size_of::()); pgtable::poc_barrier(); @@ -2523,7 +2626,7 @@ impl Vm { GFP_KERNEL, )?; - let mapping_epoch = if uat_inner.firmware != UatFirmware::Handoff { + let mapping_epoch = if uat_inner.firmware != UatFirmware::Handoff || uat_inner.m4_adopted { Some(Arc::new(MappingEpoch::new(), GFP_KERNEL)?) } else { None @@ -2542,7 +2645,7 @@ impl Vm { page_table, mapping_epoch: mapping_epoch.clone(), bind_sequence: bind_sequence.clone(), - epoch: Some(0), + epoch: mapping_epoch.is_some().then_some(0), mm, uat_inner, binding: binding.clone(), @@ -2602,7 +2705,7 @@ impl Vm { /// Attach a status and job lifetime tracking before sharing a newly created user VM with /// queues, without the G17 canonical context views, shared-object footprints and idle /// residency reclaim of [`Self::with_status`]. Used by G15, whose user objects stay pinned. - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] pub(crate) fn with_tracked_status(mut self) -> Result { self.status = Some(Arc::pin_init( crate::g17::status::VmStatus::new(), @@ -2629,18 +2732,21 @@ impl Vm { /// Every page must be mapped GPU-readable and be RAM; otherwise EFAULT. The lines are cleaned /// and invalidated to the point of coherency first (never only invalidated: CPU-written lines /// may be dirty), so the copy sees what the GPU or a write-combined CPU view stored. The - /// mappings cannot change during the copy (GPUVM exec lock). - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + /// mappings cannot change during the copy (VM reservation lock). + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] pub(crate) fn read_user(&self, va: u64, buf: &mut [u8]) -> Result { self.read_lock()?.read_user(va, buf) } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] - pub(crate) fn read_lock(&self) -> Result { - Ok(VmReadGuard(lock_vm(&self.gpuvm, None, false)?)) + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] + pub(crate) fn read_lock(&self) -> Result> { + // Every mapping change holds the VM reservation, so read-only page-table walks and + // user-memory copies need only that reservation. The full exec lock would allocate a + // `drm_gpuvm_exec` context and lock every external BO, making each submit O(external BOs). + Ok(VmReadGuard(self.gpuvm.lock_inner())) } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] fn read_user_locked(inner: &mut VmInner, va: u64, buf: &mut [u8]) -> Result { let mut done = 0usize; while done < buf.len() { @@ -2657,7 +2763,7 @@ impl Vm { } let phys = inner.page_table.translate_iova(page).map_err(|_| EFAULT)?; // SAFETY: `phys` is checked to be a RAM page; it stays mapped (and its backing pinned) - // while the exec lock is held, and is only read here. + // while the VM reservation lock is held, and is only read here. let ram = unsafe { kernel::page::Page::borrow_phys(&phys) }.ok_or(EFAULT)?; let target = &mut buf[done..done + count]; ram.with_pointer_into_page(within, count, |p| { @@ -2674,8 +2780,13 @@ impl Vm { } /// Status shared by every queue using this VM, if enabled by its GPU. - /// Charges kernel memory sized by this VM's client to `client` ([`Self::memory_client`]). + /// Charges kernel memory sized by this VM's client to `client` ([`Self::memory_client`]), + /// starting with the VM's page tables. pub(crate) fn with_memory_client(mut self, client: Arc) -> Self { + self.gpuvm.lock_inner().page_table.charge_to(crate::memacct::Usage::new( + &crate::memacct::LEDGER, + client.clone(), + )); self.memory = Some(client); self } @@ -3070,13 +3181,7 @@ impl Vm { }))?; prepare_sgt_segments(dev, gem, &vm_bo, &_bind_lease)?; - let mut resources = VmOpResources { - preallocated_gpuvas: [ - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - ], - }; + let mut resources = VmOpResources::with_gpuvas(self.memory_client())?; // Mapping needs a complete context let mut ctx = StepContext::new(Some(device.as_ref().as_ref()), prot, &mut resources)?; @@ -3297,9 +3402,7 @@ impl Vm { fn drop_mappings_now(&self, gem: &gem::Object) -> Result { let _residency = self.enter_retirement_residency(); // Removing whole mappings only does unmaps, so no preallocated VAs - let mut resources = VmOpResources { - preallocated_gpuvas: [None, None, None], - }; + let mut resources = VmOpResources::without_gpuvas(); let mut ctx = StepContext::new(None, Prot::default(), &mut resources)?; // SAFETY: See `lock_vm()`. @@ -3334,9 +3437,7 @@ impl Vm { let _residency = self.enter_retirement_residency(); // Removing whole mappings only does unmaps, so no preallocated VAs // are needed for the indexed path. - let mut resources = VmOpResources { - preallocated_gpuvas: [None, None, None], - }; + let mut resources = VmOpResources::without_gpuvas(); let mut ctx = StepContext::new(None, Prot::default(), &mut resources)?; // The BO's newest sequence is checked under the same lock as binds. If @@ -3483,7 +3584,7 @@ impl Drop for VmInner { /// Physical regions of a UAT whose handoff the generation has already established itself /// ([`Uat::new_adopted`]). None of them needs to be in the kernel linear map. -#[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] +#[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] pub(crate) struct AdoptedRegions { /// The handoff region (PPL magic, lock and flush requests). pub(crate) handoff: Range, @@ -3506,7 +3607,7 @@ impl Uat { }) } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] /// Map a region given by its physical range, write-combined. fn map_physical( range: &Range, @@ -3527,7 +3628,7 @@ impl Uat { let res: io::resource::Resource = unsafe { core::mem::transmute(kernel::types::Opaque::new(raw)) }; let flags = io::mem::MemFlag::WC; - #[cfg(CONFIG_DRM_ASAHI_G15)] + #[cfg(CONFIG_DRM_ASAHI_UAT_ADOPTION)] let flags = if reserved_ram { // G15 admits only whole reserved RAM pages or wholly non-RAM carveouts. if crate::g15::memory_mode(range.start, size as u64)? @@ -3540,7 +3641,7 @@ impl Uat { } else { flags }; - #[cfg(not(CONFIG_DRM_ASAHI_G15))] + #[cfg(not(CONFIG_DRM_ASAHI_UAT_ADOPTION))] let _ = reserved_ram; // SAFETY: The UAT regions are only accessed through this mapping by the CPU; // the GPU reaches them through its own translation. @@ -3551,7 +3652,7 @@ impl Uat { }) } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] /// Creates a `Uat` for a handoff that the caller establishes itself (G15). /// /// This only maps the handoff and the TTBAT (write-combined); neither is written here. The @@ -3577,7 +3678,7 @@ impl Uat { /// Creates the same owned-RAM adopted UAT, choosing whether application contexts also /// name the firmware upper root. M4 qualifies only context 0 for firmware-upper access; /// its application TTBAT upper words stay zero. G15 preserves its existing shared upper. - #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G16)] pub(crate) fn new_adopted_with_user_upper( dev: &driver::AsahiDrmDevice, geometry: UatGeometry, @@ -3587,7 +3688,21 @@ impl Uat { Self::new_adopted_inner(dev, geometry, regions, map_kernel_to_user, false) } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + /// As [`Self::new_adopted_with_user_upper`], for regions that may be reserved System RAM: + /// each is mapped write-back when it is RAM and write-combined when it is a carveout, as + /// [`Self::new_adopted`] does. The M3 boot loaders leave the handoff and TTBAT regions in + /// the kernel's memory map as reserved RAM, which a write-combined mapping is refused for. + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + pub(crate) fn new_adopted_ram_with_user_upper( + dev: &driver::AsahiDrmDevice, + geometry: UatGeometry, + regions: &AdoptedRegions, + map_kernel_to_user: bool, + ) -> Result { + Self::new_adopted_inner(dev, geometry, regions, map_kernel_to_user, true) + } + + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] fn new_adopted_inner( dev: &driver::AsahiDrmDevice, geometry: UatGeometry, @@ -3631,6 +3746,7 @@ impl Uat { map_kernel_to_user, handoff_rgn, ttbs_rgn, + clean_poc: true, quirks: UatQuirks::DEFAULT, }, "uat_shared" @@ -3678,13 +3794,13 @@ impl Uat { }) } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] /// Root of the kernel lower `Vm`, for TTBAT context 0 of an adopted handoff. pub(crate) fn kernel_lower_root(&self) -> PhysicalAddr { self.kernel_lower_vm.ttb() } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] /// Root whose driver-window entry names the second-level table of [`Self::kernel_vm`]'s /// driver window. With [`Self::new_adopted`] this is the shadow root that no context names. pub(crate) fn kernel_window_root(&self) -> PhysicalAddr { @@ -3744,7 +3860,20 @@ impl Uat { /// Links the kernel lower root's tables for each range, with no mappings. A published-roots /// firmware samples that root's top-level entries only when it starts. pub(crate) fn prepare_lower_tables(&self, ranges: &[Range]) -> Result { - let mut inner = lock_vm(&self.kernel_lower_vm.gpuvm, None, false)?; + Self::prepare_tables(&self.kernel_lower_vm, ranges) + } + + /// Links the kernel window's tables for each range, with no mappings, for a firmware that + /// copies the window's second-level entries only when it starts + /// ([`FirmwareWindow::mirror`]). Page tables are only freed with their VM, so the leaf + /// tables stay where that copy names them. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + pub(crate) fn prepare_kernel_tables(&self, ranges: &[Range]) -> Result { + Self::prepare_tables(&self.kernel_vm, ranges) + } + + fn prepare_tables(vm: &Vm, ranges: &[Range]) -> Result { + let mut inner = lock_vm(&vm.gpuvm, None, false)?; for range in ranges { inner.page_table.alloc_pages(range.clone())?; } @@ -4240,6 +4369,7 @@ impl Uat { map_kernel_to_user: false, handoff_rgn, ttbs_rgn, + clean_poc: shared_quirks.clean_tables, quirks: shared_quirks, }, "uat_shared" @@ -4514,3 +4644,341 @@ mod execution_context_tests { assert!(pick_returned(core::iter::empty(), &returns, &fences, 0).is_none()); } } + +/// The word GPU firmware 27.2 on G14 exchanges through the handoff region's magic fields. +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +const MAGIC_G14_V27_2: u64 = 0x4b1d000000000003; + +/// The loader's UAT regions as GPU firmware 27.2 on G14 uses them. The driver mirrors its +/// kernel window into the firmware's shared second-level table and names its own trees in +/// TTBAT context 0 before the ASC starts. +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +pub(crate) struct FirmwareWindow { + handoff: UatRegion, + ttbs: UatRegion, + tables: UatRegion, + shared_l2: UatRegion, + entries: KVec, + lower_root: u64, + pa_mask: u64, +} + +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +impl FirmwareWindow { + /// Maps the four regions. Fails with `EBUSY` unless the handoff is idle and the shared + /// table and context 0 are empty. + pub(crate) fn reserve(dev: &device::Device, geometry: UatGeometry) -> Result { + let handoff = Uat::map_region(dev, c"handoff", HANDOFF_SIZE, true)?; + let ttbs = Uat::map_region(dev, c"ttbs", UAT_PGSZ, true)?; + let tables = Uat::map_region(dev, c"pagetables", UAT_PGSZ, true)?; + let shared_l2 = Uat::map_region(dev, c"shared-l2", UAT_PGSZ, true)?; + let this = Self { + handoff, ttbs, tables, shared_l2, + entries: KVec::from_elem(0u64, UAT_PGSZ / 8, GFP_KERNEL)?, + lower_root: 0, + pa_mask: ((1u64 << geometry.oas) - 1) & !(UAT_PGMSK as u64), + }; + let h = this.handoff(); + if h.magic_ap.load(Ordering::Acquire) != 0 || h.magic_fw.load(Ordering::Acquire) != 0 + || h.lock_ap.load(Ordering::Acquire) != 0 || h.lock_fw.load(Ordering::Acquire) != 0 + || !this.empty() { + return Err(EBUSY); + } + Ok(this) + } + + fn handoff(&self) -> &Handoff { + // SAFETY: map_region checked the size of the handoff reservation; only its aligned + // atomic fields are used. + unsafe { &*self.handoff.map.ptr().cast::() } + } + + fn shared(&self) -> &[AtomicU64; UAT_PGSZ / 8] { + // SAFETY: the shared-l2 reservation is one mapped 16 KiB table. + unsafe { &*self.shared_l2.map.ptr().cast::<[AtomicU64; UAT_PGSZ / 8]>() } + } + + fn context(&self) -> &SlotTTBS { + // SAFETY: the TTBAT reservation holds at least one aligned slot. + unsafe { &*self.ttbs.map.ptr().cast::() } + } + + fn empty(&self) -> bool { + let context = self.context(); + self.shared().iter().all(|w| w.load(Ordering::Acquire) == 0) + && context.ttb0.load(Ordering::Acquire) == 0 && context.ttb1.load(Ordering::Acquire) == 0 + } + + /// The regions to adopt the UAT from. + pub(crate) fn regions(&self) -> AdoptedRegions { + AdoptedRegions { + handoff: self.handoff.base..self.handoff.base + UAT_PGSZ as PhysicalAddr, + ttbs: self.ttbs.base..self.ttbs.base + UAT_PGSZ as PhysicalAddr, + kernel_root: self.tables.base, + } + } + + /// Copies the kernel window's second-level entries from `uat` and writes all of its tables + /// back. Call after the last allocation the firmware is to reach. + pub(crate) fn mirror(&mut self, uat: &Uat) -> Result { + let mask = self.pa_mask; + let root = uat.kernel_window_root(); + let entries = &mut self.entries; + // SAFETY: the adopted UAT's driver-owned window root and its second level are live + // RAM tables. + unsafe { + let upper = pgtable::with_root_entries(None, root, 3, |w| w[2].load(Ordering::Acquire))?; + if upper & 3 != 3 { return Err(EINVAL); } + pgtable::with_root_entries(None, upper & mask, entries.len(), |w| { + for (entry, word) in entries.iter_mut().zip(w) { + *entry = word.load(Ordering::Acquire); + } + })?; + } + // The window's last 4 GiB is the MMIO range: its register mappings use one table. + let first_io = (0xf_0000_0000u64 >> 25) as usize; + if entries[first_io..].iter().filter(|w| **w != 0).count() != 1 { return Err(EINVAL); } + for &w in entries.iter().filter(|w| **w != 0) { + if w & 3 != 3 { return Err(EINVAL); } + crate::g15::uat::clean_page(w & mask)?; + } + crate::g15::uat::clean_lower(uat)?; + self.lower_root = uat.kernel_lower_root(); + Ok(()) + } + + /// Installs the mirrored window and names the driver's trees in context 0. + pub(crate) fn install(&self) -> Result { + if !self.empty() || self.lower_root == 0 { return Err(EBUSY); } + for (word, value) in self.shared().iter().zip(self.entries.iter()) { + if *value != 0 { word.store(*value, Ordering::Release); } + } + let context = self.context(); + context.ttb0.store(self.lower_root | TTBR_VALID, Ordering::Release); + context.ttb1.store(self.tables.base | TTBR_VALID, Ordering::Release); + pgtable::clean_poc(self.ttbs.map.ptr(), size_of::()); + pgtable::clean_poc(self.shared_l2.map.ptr(), UAT_PGSZ); + pgtable::poc_barrier(); + Ok(()) + } + + /// Announces the host to the firmware; call just before starting the ASC. + pub(crate) fn announce(&self) { + self.handoff().magic_ap.store(MAGIC_G14_V27_2, Ordering::Release); + fence(Ordering::SeqCst); + } + + /// Whether the firmware has answered the announcement. + pub(crate) fn answered(&self) -> bool { + self.handoff().magic_fw.load(Ordering::Acquire) == MAGIC_G14_V27_2 + } + + /// Whether the firmware still names the shared table and context 0 as installed. + pub(crate) fn intact(&self) -> bool { + // SAFETY: the firmware's kernel root is one mapped 16 KiB table. + let root = unsafe { &*self.tables.map.ptr().cast::<[AtomicU64; 4]>() }; + let context = self.context(); + root[2].load(Ordering::Acquire) & self.pa_mask == self.shared_l2.base + && context.ttb0.load(Ordering::Acquire) == self.lower_root | TTBR_VALID + && context.ttb1.load(Ordering::Acquire) == self.tables.base | TTBR_VALID + } +} + +#[kernel::macros::kunit_tests(asahi_gpuva_charge)] +mod gpuva_charge_tests { + use super::*; + use crate::memacct::{ + Client, + Ledger, + Limits, // + }; + + static GPUVA_TABLES: Ledger = Ledger::new(); + + #[test] + fn preallocated_gpuvas_are_charged_to_the_vms_client() -> Result { + assert!(GPUVA_BYTES as usize >= size_of::()); + GPUVA_TABLES.set_limits(Limits { device: 0, client: 0 }); + let client = Client::new()?; + let mut resources = VmOpResources::with_gpuvas_on(&GPUVA_TABLES, Some(&client))?; + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + { + let mut ctx = StepContext::new(None, Prot::default(), &mut resources)?; + // A recorded mapping keeps its charge with its metadata. + let kept = VmGpuVa { + prot: None, + bind_sequence: 0, + _charge: ctx.preallocated_charge(), + }; + drop(ctx); + drop(resources); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + // Cloning metadata for a mapping snapshot carries no charge. + let snapshot = kept.clone(); + drop(snapshot); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + // Removing the mapping gives the charge back. + drop(kept); + } + assert_eq!((client.committed(), client.resident()), (0, 0)); + assert_eq!(GPUVA_TABLES.user_committed.load(Ordering::Relaxed), 0); + assert_eq!(GPUVA_TABLES.user_resident.load(Ordering::Relaxed), 0); + // A VM charged to no client takes no charge. + let unaccounted = VmOpResources::with_gpuvas_on(&GPUVA_TABLES, None)?; + assert!(unaccounted.gpuva_charge.is_none()); + Ok(()) + } + + static GPUVA_REFUSE: Ledger = Ledger::new(); + + #[test] + fn a_gpuva_past_the_client_limit_is_refused() -> Result { + GPUVA_REFUSE.set_limits(Limits { + device: 0, + client: GPUVA_BYTES, + }); + let client = Client::new()?; + let first = VmOpResources::with_gpuvas_on(&GPUVA_REFUSE, Some(&client))?; + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + assert_eq!( + VmOpResources::with_gpuvas_on(&GPUVA_REFUSE, Some(&client)).err(), + Some(ENOMEM) + ); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + assert_eq!(GPUVA_REFUSE.user_committed.load(Ordering::Relaxed), GPUVA_BYTES); + assert_eq!(GPUVA_REFUSE.user_resident.load(Ordering::Relaxed), GPUVA_BYTES); + assert_eq!(GPUVA_REFUSE.refused.load(Ordering::Relaxed), 1); + drop(first); + assert_eq!((client.committed(), client.resident()), (0, 0)); + assert_eq!(GPUVA_REFUSE.user_committed.load(Ordering::Relaxed), 0); + assert_eq!(GPUVA_REFUSE.user_resident.load(Ordering::Relaxed), 0); + Ok(()) + } + + static GPUVA_UNMAP: Ledger = Ledger::new(); + + #[test] + fn unmap_and_truncating_remap_succeed_at_the_client_limit() -> Result { + GPUVA_UNMAP.set_limits(Limits { + device: 0, + client: GPUVA_BYTES, + }); + let client = Client::new()?; + let mut resources = VmOpResources::with_gpuvas_on(&GPUVA_UNMAP, Some(&client))?; + let orig = resources.gpuva_charge.take().ok_or(EINVAL)?; + drop(resources); + + // Unmap preparation takes no charge and succeeds at the exact client limit. + let unmap = VmOpResources::for_unmap()?; + assert!(unmap.gpuva_charge.is_none()); + drop(unmap); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + assert_eq!(GPUVA_UNMAP.refused.load(Ordering::Relaxed), 0); + + // Truncating remap hands the removed node's charge to the surviving piece (net zero). + let transferred = orig.transfer_copy(); + drop(orig); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + assert_eq!(GPUVA_UNMAP.user_committed.load(Ordering::Relaxed), GPUVA_BYTES); + assert_eq!(GPUVA_UNMAP.user_resident.load(Ordering::Relaxed), GPUVA_BYTES); + assert_eq!(GPUVA_UNMAP.refused.load(Ordering::Relaxed), 0); + + // Splitting one mapping into two (net +1 node) refuses past the client limit. + assert_eq!(transferred.try_fork(GPUVA_BYTES).err(), Some(ENOMEM)); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + assert_eq!(GPUVA_UNMAP.user_committed.load(Ordering::Relaxed), GPUVA_BYTES); + assert_eq!(GPUVA_UNMAP.refused.load(Ordering::Relaxed), 1); + + // A deferred hole-punch unmap reserves its split charge before acceptance: refused + // with ENOMEM at the limit, admitted once headroom exists, idempotent on retry, and + // returned cleanly if unused at drain time. + let mut unmap_res = VmOpResources::for_unmap()?; + assert_eq!( + unmap_res + .reserve_split_charge_on(&GPUVA_UNMAP, Some(&client)) + .err(), + Some(ENOMEM) + ); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + assert_eq!(GPUVA_UNMAP.refused.load(Ordering::Relaxed), 2); + + // Once headroom exists, reserving the deferred split charge fills split_charge only + // (never gpuva_charge), is idempotent, and drops cleanly if unused. + GPUVA_UNMAP.set_limits(Limits { + device: 0, + client: 3 * GPUVA_BYTES, + }); + unmap_res.reserve_split_charge_on(&GPUVA_UNMAP, Some(&client))?; + unmap_res.reserve_split_charge_on(&GPUVA_UNMAP, Some(&client))?; + assert_eq!( + (client.committed(), client.resident()), + (2 * GPUVA_BYTES, 2 * GPUVA_BYTES) + ); + { + let mut ctx = StepContext::new(None, Prot::default(), &mut unmap_res)?; + assert!(ctx.preallocated_charge().is_none()); + let split = ctx.preallocated_split_charge(); + assert!(split.is_some()); + assert!(ctx.preallocated_split_charge().is_none()); + drop(split); + } + drop(unmap_res); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + + // A map strictly inside an existing charged mapping runs remap before map on the same + // StepContext: preallocated_split_charge() must be None so remap forks its own split + // charge instead of stealing gpuva_charge from sm_step_map(), leaving all 3 nodes charged. + let mut map_res = VmOpResources::with_gpuvas_on(&GPUVA_UNMAP, Some(&client))?; + assert_eq!( + (client.committed(), client.resident()), + (2 * GPUVA_BYTES, 2 * GPUVA_BYTES) + ); + let (extra, map_charge) = { + let mut ctx = StepContext::new(None, Prot::default(), &mut map_res)?; + assert!(ctx.preallocated_split_charge().is_none()); + let extra = transferred.try_fork(GPUVA_BYTES)?; + let map_charge = ctx.preallocated_charge(); + assert!(map_charge.is_some()); + (extra, map_charge) + }; + assert_eq!( + (client.committed(), client.resident()), + (3 * GPUVA_BYTES, 3 * GPUVA_BYTES) + ); + drop((map_res, map_charge, extra, transferred)); + assert_eq!((client.committed(), client.resident()), (0, 0)); + assert_eq!(GPUVA_UNMAP.user_committed.load(Ordering::Relaxed), 0); + assert_eq!(GPUVA_UNMAP.user_resident.load(Ordering::Relaxed), 0); + Ok(()) + } +} diff --git a/drivers/gpu/drm/asahi/mmu/bind.rs b/drivers/gpu/drm/asahi/mmu/bind.rs index 97483575610774..6b9cd7f61932d6 100644 --- a/drivers/gpu/drm/asahi/mmu/bind.rs +++ b/drivers/gpu/drm/asahi/mmu/bind.rs @@ -79,13 +79,7 @@ impl Vm { gem::validate_vm_binding(gem, self)?; let residency = self.enter_residency_metadata()?; let context = self.prepare_context_binding(addr, size, offset)?; - let resources = VmOpResources { - preallocated_gpuvas: [ - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - ], - }; + let resources = VmOpResources::with_gpuvas(self.memory_client())?; // SAFETY: As in `Vm::bind_object()`, the device is bound while its file can issue binds. let dev = unsafe { self.dev.as_bound() }; // Populate the scatter-gather table before any GPUVM lock is taken. diff --git a/drivers/gpu/drm/asahi/mmu/lifetime.rs b/drivers/gpu/drm/asahi/mmu/lifetime.rs index 9da7820dd92f65..92f273eb3709f9 100644 --- a/drivers/gpu/drm/asahi/mmu/lifetime.rs +++ b/drivers/gpu/drm/asahi/mmu/lifetime.rs @@ -62,6 +62,7 @@ struct State { commits: usize, blocked: bool, quarantined: bool, + quarantine_gen: u64, draining: bool, closed: bool, cleanup_failed: bool, @@ -74,6 +75,8 @@ struct State { pub(super) struct VmLifetime { #[pin] state: Mutex, + /// Lock-free mirror of `state.closed`, set once in [`Vm::unmap_user_ranges`]. + closed: AtomicBool, #[pin] changed: CondVar, #[pin] @@ -97,8 +100,10 @@ impl VmLifetime { Arc::pin_init( pin_init!(Self { state <- new_mutex!(State { active:0, commits:0, blocked:false, - quarantined:false, draining:false, closed:false, cleanup_failed:false, close_ranges:None, + quarantined:false, quarantine_gen:0, draining:false, closed:false, + cleanup_failed:false, close_ranges:None, unmaps:KVec::new(), objects:KVec::new() }, "VM job lifetime"), + closed: AtomicBool::new(false), changed <- new_condvar!("VM mapping admission"), driver <- new_mutex!(None, "VM driver mappings"), }), @@ -123,7 +128,10 @@ impl VmJobGuard { while state.commits != 0 { lifetime.changed.wait(&mut state); } - state.quarantined = true; + if !state.quarantined { + state.quarantine_gen = state.quarantine_gen.wrapping_add(1); + state.quarantined = true; + } } } } @@ -201,24 +209,6 @@ impl Vm { Ok(()) } - /// The graph identity whose pool mappings occupy `slot` in this - /// VM (0 when free). A second graph cannot install there until it leaves. - pub(crate) fn render_pool_owner(&self, slot: u8) -> u64 { - self.lifetime - .as_ref() - .and_then(|lifetime| { - lifetime - .driver - .lock() - .as_ref()? - .render - .get(usize::from(slot))? - .as_ref() - .map(|pool| pool.id) - }) - .unwrap_or(0) - } - pub(crate) fn render_pool_tvb_blocks(&self, slot: u8, id: u64) -> Option { if id == 0 { return None; @@ -393,11 +383,12 @@ impl Vm { } /// Whether the client's handle of this VM is gone ([`Self::unmap_user_ranges`] closed - /// admission for good). G15 releases its per-VM state after that. + /// admission for good). Lock-free so callers holding spinlocks (such as G16's standby + /// epoch lock) can test close state without sleeping. pub(crate) fn is_closed(&self) -> bool { self.lifetime .as_ref() - .is_some_and(|lifetime| lifetime.state.lock().closed) + .is_some_and(|lifetime| lifetime.closed.load(Ordering::Acquire)) } /// Tests mappings and reservations which userspace must never replace. @@ -538,49 +529,87 @@ impl Vm { let Some(lifetime) = self.lifetime.as_ref() else { return Ok(false); }; - let mut state = lifetime.state.lock(); - if !state.blocked { - return Ok(false); - } - if state.closed { - return Err(ENOENT); - } - if batch - .ops - .iter() - .skip(start) - .any(|op| matches!(op, PreparedUserBindOp::Map(_))) - { - return Err(EIO); - } - if !state.quarantined { - return Err(EBUSY); - } - // Reserve before accepting any range; a partial deferred batch must - // not leave canonical metadata ahead of the accepted cleanup. - state.unmaps.reserve(batch.ops.len() - start, GFP_KERNEL)?; - let retired = - self.untrack_context_ranges(batch.ops.iter().skip(start).filter_map(|op| match op { - PreparedUserBindOp::Unmap(unmap) => Some(unmap.iova..unmap.iova + unmap.size), - PreparedUserBindOp::Map(_) => None, - })); - // Transfer the preallocated split nodes along with each accepted range. - // Already-committed prefix operations must not be replayed: their nodes - // may have been consumed and another binding may now occupy the range. - for op in batch.ops.drain(start..) { - if let PreparedUserBindOp::Unmap(unmap) = op { - if !state - .unmaps + loop { + let gen = { + let state = lifetime.state.lock(); + if !state.blocked { + return Ok(false); + } + if state.closed { + return Err(ENOENT); + } + if batch + .ops .iter() - .any(|old| old.iova == unmap.iova && old.size == unmap.size) + .skip(start) + .any(|op| matches!(op, PreparedUserBindOp::Map(_))) { - state.unmaps.push(unmap, GFP_KERNEL)?; + return Err(EIO); + } + if !state.quarantined { + return Err(EBUSY); + } + state.quarantine_gen + }; + + // Reserve a split charge before accepting any deferred hole-punch unmap so + // drain_mappings() never hits ENOMEM after VM_BIND returned 0 and quarantined + // unmaps cannot bypass client/device limits. While quarantined, maps cannot + // commit, so any unmap that can split at drain time is already strictly inside + // an existing GPUVA here. + if let Some(client) = self.memory_client() { + let inner = self.gpuvm.lock_inner(); + for op in batch.ops.iter_mut().skip(start) { + if let PreparedUserBindOp::Unmap(unmap) = op { + if inner.range_strictly_inside_va(unmap.iova, unmap.size, |va| { + va.data()._charge.is_some() + }) { + unmap.resources.reserve_split_charge(Some(client))?; + } + } } } + + let mut state = lifetime.state.lock(); + if !state.blocked { + return Ok(false); + } + if state.closed { + return Err(ENOENT); + } + if !state.quarantined { + return Err(EBUSY); + } + if state.quarantine_gen != gen { + continue; + } + // Reserve before accepting any range; a partial deferred batch must + // not leave canonical metadata ahead of the accepted cleanup. + state.unmaps.reserve(batch.ops.len() - start, GFP_KERNEL)?; + let retired = + self.untrack_context_ranges(batch.ops.iter().skip(start).filter_map(|op| match op { + PreparedUserBindOp::Unmap(unmap) => Some(unmap.iova..unmap.iova + unmap.size), + PreparedUserBindOp::Map(_) => None, + })); + // Transfer the preallocated split nodes (and any reserved split charge) + // along with each accepted range. Already-committed prefix operations + // must not be replayed: their nodes may have been consumed and another + // binding may now occupy the range. + for op in batch.ops.drain(start..) { + if let PreparedUserBindOp::Unmap(unmap) = op { + if !state + .unmaps + .iter() + .any(|old| old.iova == unmap.iova && old.size == unmap.size) + { + state.unmaps.push(unmap, GFP_KERNEL)?; + } + } + } + drop(state); + drop(retired); + return Ok(true); } - drop(state); - drop(retired); - Ok(true) } /// Returns true if a quarantined owner requires this unmap to be deferred. @@ -588,43 +617,64 @@ impl Vm { let Some(lifetime) = self.lifetime.as_ref() else { return Ok(false); }; - let state = lifetime.state.lock(); - if state.closed { - return Err(ENOENT); - } - if !state.blocked { - return Ok(false); - } - if !state.quarantined { - return Err(EBUSY); - } - if state - .unmaps - .iter() - .any(|old| old.iova == iova && old.size == size) - { + let mut prepared: Option = None; + loop { + let gen = { + let state = lifetime.state.lock(); + if state.closed { + return Err(ENOENT); + } + if !state.blocked { + return Ok(false); + } + if !state.quarantined { + return Err(EBUSY); + } + if state + .unmaps + .iter() + .any(|old| old.iova == iova && old.size == size) + { + return Ok(true); + } + state.quarantine_gen + }; + + let unmap = match prepared.as_mut() { + Some(unmap) => unmap, + None => prepared.insert(self.prepare_user_unmap(iova, size)?), + }; + if let Some(client) = self.memory_client() { + let inner = self.gpuvm.lock_inner(); + if inner.range_strictly_inside_va(iova, size, |va| va.data()._charge.is_some()) { + unmap.resources.reserve_split_charge(Some(client))?; + } + } + + let mut state = lifetime.state.lock(); + if state.closed { + return Err(ENOENT); + } + if !state.blocked { + return Ok(false); + } + if !state.quarantined { + return Err(EBUSY); + } + if state.quarantine_gen != gen { + continue; + } + if !state + .unmaps + .iter() + .any(|old| old.iova == iova && old.size == size) + { + if let Some(unmap) = prepared.take() { + state.unmaps.push(unmap, GFP_KERNEL)?; + } + } return Ok(true); } - drop(state); - let unmap = self.prepare_user_unmap(iova, size)?; - let mut state = lifetime.state.lock(); - if state.closed { - return Err(ENOENT); - } - if !state.blocked { - return Ok(false); - } - if !state.quarantined { - return Err(EBUSY); - } - if !state - .unmaps - .iter() - .any(|old| old.iova == iova && old.size == size) - { - state.unmaps.push(unmap, GFP_KERNEL)?; - } - Ok(true) } /// Defers handle-close cleanup while any accepted job can still use the BO. @@ -666,6 +716,7 @@ impl Vm { lifetime.changed.wait(&mut state); } state.closed = true; + lifetime.closed.store(true, Ordering::Release); if state.active != 0 { state.close_ranges = Some((user, kernel)); return Ok(()); @@ -704,9 +755,7 @@ impl Drop for VmJobGuard { // Healthy last-job release need not close mapping/job admission when // there is no accepted cleanup to drain. Keep every recovery, close, // in-progress commit and failed-cleanup path on the existing drain. - // M5 only: other G17 GPUs keep the drain on every last release. - if self.vm.m5 - && !state.blocked + if !state.blocked && !state.quarantined && !state.draining && !state.closed diff --git a/drivers/gpu/drm/asahi/mmu/table.rs b/drivers/gpu/drm/asahi/mmu/table.rs index 53d6c30273b5e4..3f8a476ecb1587 100644 --- a/drivers/gpu/drm/asahi/mmu/table.rs +++ b/drivers/gpu/drm/asahi/mmu/table.rs @@ -7,15 +7,6 @@ use core::ops::Range; use kernel::{addr::PhysicalAddr, prelude::*, sync::Arc}; impl UatPageTable { - pub(super) fn visit_runs( - &self, - range: Range, - visit: impl FnMut(u64, u64, u8) -> Result, - ) -> Result { - let _ = (range, visit); - Err(EOPNOTSUPP) - } - /// Fill `range` from a sparse tile: its first (zeroed) page repeats across /// the range, as a SINGLE_PAGE bind repeats its GEM's first page. pub(super) fn map_tiled(&mut self, range: Range, tile: &Arc, prot: Prot) -> Result { diff --git a/drivers/gpu/drm/asahi/object.rs b/drivers/gpu/drm/asahi/object.rs index 0c9e6f62b5bbe2..620014c6f63b2e 100644 --- a/drivers/gpu/drm/asahi/object.rs +++ b/drivers/gpu/drm/asahi/object.rs @@ -45,8 +45,7 @@ use kernel::{ error::code::*, - prelude::*, - sync::Arc, // + prelude::*, // }; use core::fmt; @@ -108,7 +107,7 @@ impl<'a, T> GpuPointer<'a, T> { /// Create a GPU pointer from a KernelMapping and an offset. /// TODO: Change all GPU pointers to point to the raw types so size_of here is GPU-sound. pub(crate) fn from_mapping( - mapping: &'a Arc, + mapping: &'a mmu::KernelMapping, offset: usize, ) -> Result> { let addr = mapping.iova().checked_add(offset as u64).ok_or(EINVAL)?; @@ -697,6 +696,41 @@ impl> GpuArray { } } +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +impl> GpuArray { + /// Aligned index in a shared firmware ring, accessed without borrowing its payload. + pub(crate) fn shared_index(&self, offset: usize) -> Result<&core::sync::atomic::AtomicU32> { + if offset.checked_add(4).is_none_or(|end| end > self.len) { + return Err(EINVAL); + } + let ptr = self.raw.wrapping_add(offset).cast::(); + if !ptr.is_aligned() { + return Err(EINVAL); + } + // SAFETY: bounds and alignment checked; the shared ring ABI accesses + // this word only in aligned 32-bit transactions while the ring is live. + Ok(unsafe { core::sync::atomic::AtomicU32::from_ptr(ptr) }) + } + + /// Zeroes the first `bytes` through the raw CPU mapping, without creating a Rust reference + /// to the payload, and cleans them to the point of coherency for the GPU. + /// + /// # Safety + /// + /// No CPU reference into the range may be live, and no device may access it during the call. + pub(crate) unsafe fn zero_prefix(&self, bytes: usize) -> Result { + if bytes > self.len { + return Err(ERANGE); + } + // SAFETY: `raw` is valid for `len` bytes (type invariant) and `bytes <= len`; the caller + // guarantees that nothing else accesses the range meanwhile. + unsafe { core::ptr::write_bytes(self.raw, 0, bytes) }; + crate::pgtable::clean_poc(self.raw.cast_const(), bytes); + crate::pgtable::poc_barrier(); + Ok(()) + } +} + impl> Deref for GpuArray { type Target = GpuOnlyArray; diff --git a/drivers/gpu/drm/asahi/pgtable.rs b/drivers/gpu/drm/asahi/pgtable.rs index 9fb2d0652e01eb..381ad1acc71641 100644 --- a/drivers/gpu/drm/asahi/pgtable.rs +++ b/drivers/gpu/drm/asahi/pgtable.rs @@ -11,6 +11,7 @@ use core::mem::size_of; use core::ops::Range; use core::sync::atomic::{ AtomicU64, + AtomicUsize, Ordering, // }; @@ -54,10 +55,18 @@ const UAT_LEVELS: usize = 3; /// Number of address bits below the index of a top-level page table entry. pub(crate) const UAT_TOP_LEVEL_SHIFT: usize = UAT_PGBIT + (UAT_LEVELS - 1) * UAT_LVBIT; +/// Cached system-wide minimum CPU data cache line size (bytes), populated lazily from +/// the arm64 sanitized `CTR_EL0` feature register. +static DCACHE_LINE_SIZE: AtomicUsize = AtomicUsize::new(0); + /// The system-wide minimum CPU line size, including heterogeneous CPUs. A local /// CTR_EL0 read can select too large a stride if the task migrates during the loop. #[inline(always)] fn dcache_line_size() -> usize { + let cached = DCACHE_LINE_SIZE.load(Ordering::Relaxed); + if cached != 0 { + return cached; + } use kernel::bindings; let ctr = (bindings::SYS_CTR_EL0_Op0 << 19) | (bindings::SYS_CTR_EL0_Op1 << 16) @@ -65,9 +74,12 @@ fn dcache_line_size() -> usize { | (bindings::SYS_CTR_EL0_CRm << 8) | (bindings::SYS_CTR_EL0_Op2 << 5); // SAFETY: Read-only lookup of the arm64 sanitized feature register. DminLine - // uses the architecture's LOWER_SAFE merge policy across all admitted CPUs. + // uses the architecture's LOWER_SAFE merge policy across all admitted CPUs + // and remains constant once SMP boot has completed. let value = unsafe { bindings::read_sanitised_ftr_reg(ctr) }; - 4 << ((value >> bindings::CTR_EL0_DminLine_SHIFT) & 0xf) + let line = 4 << ((value >> bindings::CTR_EL0_DminLine_SHIFT) & 0xf); + DCACHE_LINE_SIZE.store(line, Ordering::Relaxed); + line } /// Cleans the CPU data cache lines covering `len` bytes at `ptr` to the point of coherency, for an @@ -369,7 +381,7 @@ impl Prot { /// The protection bits of a leaf with this protection (no address, table type or non-global /// bits), for checking that a firmware leaf word round-trips through [`Self::from_pte`]. - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] pub(crate) const fn leaf_bits(&self) -> u64 { self.as_pte() } @@ -448,6 +460,10 @@ pub(crate) struct UatPageTable { /// Clean new tables and changed entries to the point of coherency, for a UAT walker that does /// not snoop the CPU caches ([`Self::enable_clean_poc`]). clean_poc: bool, + /// Table pages the driver allocated below the root. + tables: usize, + /// The client these tables are charged to ([`Self::charge_to`]). + charge: Option, } impl UatPageTable { @@ -466,6 +482,8 @@ impl UatPageTable { ias_mask: (1u64 << ias) - 1, oas_mask: (1u64 << oas) - 1, clean_poc: false, + tables: 0, + charge: None, }) } @@ -548,9 +566,24 @@ impl UatPageTable { ias_mask: (1u64 << ias) - 1, oas_mask: (1u64 << oas) - 1, clean_poc: false, + tables: 0, + charge: None, }) } + /// Charges this page table's memory to a client from now on: the root and the tables + /// allocated so far at once, whatever the client's limits, and each further table once it is + /// allocated and ready to install. A table past the client's or the device's limit is freed + /// again and the map that needed it fails with `ENOMEM`; a table is charged only after every + /// step that can fail, so one that is not installed leaves no charge. The tables are also + /// allocated as memory of the calling task's memory cgroup from then on. Everything stays + /// charged until the page table is dropped, which frees the tables. + pub(crate) fn charge_to(&mut self, mut usage: crate::memacct::Usage) { + let pages = self.tables + usize::from(self.ttb_owned); + usage.add((pages * UAT_PGSZ) as u64); + self.charge = Some(usage); + } + /// Retains every physical table after an uncertain M4 handoff. No other agent may reclaim /// this tree merely because a userspace handle closed or a fence reported an error. pub(crate) fn retain(&mut self) { @@ -672,6 +705,8 @@ impl UatPageTable { as usize; mod_pr_debug!("UATPageTable::with_pages: borrowed phys {:#x}\n", phys); let driver_tables = &mut self.driver_tables; + let table_count = &mut self.tables; + let charge = &mut self.charge; let oas_mask = self.oas_mask; let firmware_tree = reserved.as_deref(); let entry = |p: *mut u8| -> Result> { @@ -682,7 +717,12 @@ impl UatPageTable { let mut upte_val = upte.load(Ordering::Relaxed); // Allocate if requested if upte_val == 0 && alloc { - let pt_page = Page::alloc_page(GFP_KERNEL | __GFP_ZERO)?; + let gfp = if charge.is_some() { + GFP_KERNEL_ACCOUNT + } else { + GFP_KERNEL + }; + let pt_page = Page::alloc_page(gfp | __GFP_ZERO)?; mod_pr_debug!( "UATPageTable::with_pages: alloc PT at {:#x}\n", pt_page.phys() @@ -696,9 +736,19 @@ impl UatPageTable { })?; } if let Some(tables) = driver_tables.as_mut() { - tables.push(pt_page.phys(), GFP_KERNEL)?; + tables.reserve(1, GFP_KERNEL)?; + } + // Charge last: nothing below can fail, so a table that is + // not installed is freed with no charge left behind. + if let Some(charge) = charge.as_mut() { + charge.try_add(UAT_PGSZ as u64)?; + } + if let Some(tables) = driver_tables.as_mut() { + // Cannot fail: the room was reserved above. + let _ = tables.push_within_capacity(pt_page.phys()); } let pt_paddr = Page::into_phys(pt_page); + *table_count += 1; upte_val = pt_paddr | PTE_TYPE_LEAF_TABLE; // Complete child-table initialization before a // concurrent device walk can follow its parent. @@ -884,6 +934,7 @@ impl UatPageTable { // SAFETY: Page tables allocated by the driver always come from Page::into_phys(). Without // `driver_tables`, every child table belongs to the driver. unsafe { Page::from_phys(phys) }; + self.tables = self.tables.saturating_sub(1); Ok(()) } @@ -1057,6 +1108,53 @@ impl UatPageTable { }) } + /// Maps a scatterlist of contiguous `(phys, len)` segments into `iova_range` in a single + /// page-table walk, emitting at most one point-of-coherency clean per leaf-table slice and + /// a single `dsb sy` barrier at the end instead of one walk and barrier per segment. + pub(crate) fn map_segments( + &mut self, + iova_range: Range, + segments: impl Iterator, + offset: usize, + prot: Prot, + one_page: bool, + ) -> Result { + if iova_range.is_empty() { + return Ok(()); + } + if (iova_range.start | iova_range.end) & (UAT_PGMSK as u64) != 0 || offset & UAT_PGMSK != 0 { + pr_err!( + "UATPageTable::map_segments: range {:#x?} or offset {:#x} not page-aligned\n", + iova_range, + offset + ); + return Err(EINVAL); + } + + let prot_bits = self.stored(prot).as_pte() | self.pte_bits(); + let mut cursor = SegmentCursor::new(segments, offset, one_page)?; + + self.walk(iova_range, true, false, true, |iova, ptes| { + for (idx, pte) in ptes.iter().enumerate() { + let phys = cursor.next_page(iova + (idx * UAT_PGSZ) as u64)?; + let ptev = pte.load(Ordering::Relaxed); + if ptev != 0 { + // Never replace a live leaf: it belongs to another mapping. The callers + // check their whole range first (`ensure_unmapped`), so this is reached + // only by a collision they missed. + pr_err!( + "UATPageTable::map_segments: Page at IOVA {:#x} is mapped (PTE: {:#x})\n", + iova + (idx * UAT_PGSZ) as u64, + ptev + ); + return Err(EBUSY); + } + pte.store(phys | prot_bits, Ordering::Relaxed); + } + Ok(()) + }) + } + /// Refuses with `EBUSY`, writing nothing, when any leaf of `iova_range` is live. /// /// Every PTE store writes either zero or a complete entry, so a nonzero leaf belongs to @@ -1162,3 +1260,232 @@ impl Drop for UatPageTable { } } } + +/// Streams page-aligned physical addresses out of a `(phys, len)` scatterlist iterator, +/// optionally repeating the first page after `offset` (`one_page`). +struct SegmentCursor { + segments: I, + cur_phys: PhysicalAddr, + cur_len: usize, + one_page: bool, +} + +impl> SegmentCursor { + fn new(mut segments: I, mut offset: usize, one_page: bool) -> Result { + if offset & UAT_PGMSK != 0 { + return Err(EINVAL); + } + let mut cur_phys: PhysicalAddr = 0; + let mut cur_len: usize = 0; + for (dma_addr, dma_len) in segments.by_ref() { + if (dma_addr & (UAT_PGMSK as PhysicalAddr)) != 0 || (dma_len & UAT_PGMSK) != 0 { + pr_err!( + "UATPageTable::map_segments: segment {:#x}:{:#x} not page-aligned\n", + dma_addr, + dma_len + ); + return Err(EINVAL); + } + let mut addr = dma_addr; + let mut len = dma_len; + if offset > 0 { + let skip = len.min(offset); + addr += skip as PhysicalAddr; + len -= skip; + offset -= skip; + } + if len > 0 { + cur_phys = addr; + cur_len = len; + break; + } + } + if cur_len == 0 { + return Err(EINVAL); + } + Ok(Self { + segments, + cur_phys, + cur_len, + one_page, + }) + } + + fn next_page(&mut self, iova: u64) -> Result { + if !self.one_page && self.cur_len == 0 { + loop { + let Some((dma_addr, dma_len)) = self.segments.next() else { + pr_err!( + "UATPageTable::map_segments: scatterlist ended before IOVA {:#x}\n", + iova + ); + return Err(EINVAL); + }; + if (dma_addr & (UAT_PGMSK as PhysicalAddr)) != 0 || (dma_len & UAT_PGMSK) != 0 { + pr_err!( + "UATPageTable::map_segments: segment {:#x}:{:#x} not page-aligned\n", + dma_addr, + dma_len + ); + return Err(EINVAL); + } + if dma_len > 0 { + self.cur_phys = dma_addr; + self.cur_len = dma_len; + break; + } + } + } + let phys = self.cur_phys; + if !self.one_page { + self.cur_phys += UAT_PGSZ as PhysicalAddr; + self.cur_len -= UAT_PGSZ; + } + Ok(phys) + } +} + +#[kernel::macros::kunit_tests(asahi_pgtable_segments)] +mod tests { + use super::*; + + const PG: usize = UAT_PGSZ; + const PGU: PhysicalAddr = UAT_PGSZ as PhysicalAddr; + + #[test] + fn streams_multi_segment_with_offset_and_zero_len() { + let segs = [ + (0x10_0000, 2 * PG), + (0x20_0000, 0), + (0x30_0000, PG), + (0x40_0000, 2 * PG), + ]; + let mut cursor = SegmentCursor::new(segs.into_iter(), PG, false).unwrap(); + assert_eq!(cursor.next_page(0), Ok(0x10_0000 + PGU)); + assert_eq!(cursor.next_page(PGU), Ok(0x30_0000)); + assert_eq!(cursor.next_page(2 * PGU), Ok(0x40_0000)); + assert_eq!(cursor.next_page(3 * PGU), Ok(0x40_0000 + PGU)); + assert_eq!(cursor.next_page(4 * PGU), Err(EINVAL)); + } + + #[test] + fn repeats_single_page_after_offset() { + let segs = [(0x10_0000, PG), (0x50_0000, 2 * PG)]; + let mut cursor = SegmentCursor::new(segs.into_iter(), 2 * PG, true).unwrap(); + for i in 0..4u64 { + assert_eq!(cursor.next_page(i * PGU), Ok(0x50_0000 + PGU)); + } + } + + #[test] + fn rejects_unaligned_and_short_inputs() { + let segs = [(0x10_0000, PG)]; + assert!(SegmentCursor::new(segs.into_iter(), 0x100, false).is_err()); + assert!(SegmentCursor::new([(0x10_0004, PG)].into_iter(), 0, false).is_err()); + assert!(SegmentCursor::new([(0x10_0000, PG + 4)].into_iter(), 0, false).is_err()); + assert!(SegmentCursor::new([(0x10_0000, PG)].into_iter(), PG, false).is_err()); + } +} + +#[kunit_tests(asahi_pgtable_charge)] +mod pgtable_charge_tests { + use super::*; + use crate::memacct::{ + Client, + Ledger, + Limits, + Usage, // + }; + + const PG: u64 = UAT_PGSZ as u64; + /// The span of one leaf table (32 MiB); a level-1 table spans 2048 of them. + const LEAF_SPAN: u64 = PG << UAT_LVBIT; + /// Only written into leaves, never accessed. + const PHYS: PhysicalAddr = 0x8_0000_0000; + + static TABLES: Ledger = Ledger::new(); + + #[test] + fn tables_are_charged_to_the_client_until_dropped() -> Result { + TABLES.set_limits(Limits { device: 0, client: 0 }); + let client = Client::new()?; + let mut pt = UatPageTable::new(42, 42)?; + let first = 64 * LEAF_SPAN..66 * LEAF_SPAN; + let second = 66 * LEAF_SPAN..67 * LEAF_SPAN; + // One page repeated over two leaf tables, below one level-1 table, before the charge. + pt.map_pages(first.clone(), PHYS, prot::PROT_GPU_SHARED_RW, true)?; + pt.charge_to(Usage::new(&TABLES, client.clone())); + // The root and the three tables are charged at once. + assert_eq!((client.committed(), client.resident()), (4 * PG, 4 * PG)); + // A further leaf table is charged as it is allocated. + pt.map_pages(second.clone(), PHYS, prot::PROT_GPU_SHARED_RW, true)?; + assert_eq!((client.committed(), client.resident()), (5 * PG, 5 * PG)); + // Unmapping keeps the tables, and their charge, until the page table is dropped. + pt.unmap_pages(first)?; + pt.unmap_pages(second)?; + assert_eq!(client.committed(), 5 * PG); + drop(pt); + assert_eq!((client.committed(), client.resident()), (0, 0)); + assert_eq!(TABLES.user_committed.load(Ordering::Relaxed), 0); + assert_eq!(TABLES.user_resident.load(Ordering::Relaxed), 0); + Ok(()) + } + + static REFUSE: Ledger = Ledger::new(); + + #[test] + fn a_table_past_the_client_limit_is_refused() -> Result { + // Room for the root, one level-1 table and one leaf table. + REFUSE.set_limits(Limits { device: 0, client: 3 * PG }); + let client = Client::new()?; + let mut pt = UatPageTable::new(42, 42)?; + pt.charge_to(Usage::new(&REFUSE, client.clone())); + let range = 64 * LEAF_SPAN..66 * LEAF_SPAN; + assert_eq!( + pt.map_pages(range.clone(), PHYS, prot::PROT_GPU_SHARED_RW, true), + Err(ENOMEM) + ); + assert_eq!(client.committed(), 3 * PG); + assert_eq!(pt.tables, 2); + assert_eq!(REFUSE.refused.load(Ordering::Relaxed), 1); + // The first leaf table's span was written before the refusal: clear it as a failed map + // does. + pt.discard_partial_map(range)?; + drop(pt); + assert_eq!(client.committed(), 0); + assert_eq!(REFUSE.user_committed.load(Ordering::Relaxed), 0); + Ok(()) + } + + static REFUSE_SHARED: Ledger = Ledger::new(); + + #[test] + fn a_refused_table_is_neither_charged_nor_recorded() -> Result { + // A borrowed root whose own tables are recorded one by one, as below a firmware root: + // the root is not the client's, so the limit leaves room for one level-1 and one leaf + // table. + REFUSE_SHARED.set_limits(Limits { device: 0, client: 2 * PG }); + let client = Client::new()?; + let ttb = Page::into_phys(Page::alloc_page(GFP_KERNEL | __GFP_ZERO)?); + let mut pt = UatPageTable::new_with_ttb(ttb, 0..1u64 << 42, 42, 42, true, None)?; + pt.charge_to(Usage::new(&REFUSE_SHARED, client.clone())); + let range = 64 * LEAF_SPAN..66 * LEAF_SPAN; + assert_eq!( + pt.map_pages(range.clone(), PHYS, prot::PROT_GPU_SHARED_RW, true), + Err(ENOMEM) + ); + // The charge matches the tables kept: the refused leaf table was freed, not recorded. + assert_eq!(client.committed(), 2 * PG); + assert_eq!(pt.tables, 2); + assert_eq!(pt.driver_tables.as_ref().map(|t| t.len()), Some(2)); + assert_eq!(REFUSE_SHARED.refused.load(Ordering::Relaxed), 1); + pt.discard_partial_map(range)?; + drop(pt); + assert_eq!(client.committed(), 0); + assert_eq!(REFUSE_SHARED.user_committed.load(Ordering::Relaxed), 0); + // SAFETY: The root came from Page::into_phys() above and the page table that borrowed + // it is gone. + unsafe { Page::from_phys(ttb) }; + Ok(()) + } +} diff --git a/drivers/gpu/drm/asahi/queue/common.rs b/drivers/gpu/drm/asahi/queue/common.rs index 20396f2e772252..953cff0217f0fa 100644 --- a/drivers/gpu/drm/asahi/queue/common.rs +++ b/drivers/gpu/drm/asahi/queue/common.rs @@ -28,12 +28,13 @@ pub(super) fn get_timestamp_object( #[allow(irrefutable_let_patterns)] if let file::Object::TimestampBuffer(mapping) = object { + let fw_mapping = mapping.firmware_mapping()?; let offset = timestamp.offset; - if (offset.checked_add(8).ok_or(EINVAL)?) as usize > mapping.size() { + if (offset.checked_add(8).ok_or(EINVAL)?) as usize > fw_mapping.size() { return Err(ERANGE); } Ok(Some(UserTimestamp { - mapping: mapping.firmware_mapping()?, + mapping, offset: offset as usize, })) } else { diff --git a/drivers/gpu/drm/asahi/queue/mod.rs b/drivers/gpu/drm/asahi/queue/mod.rs index d80395ca3431aa..d8621b2b367611 100644 --- a/drivers/gpu/drm/asahi/queue/mod.rs +++ b/drivers/gpu/drm/asahi/queue/mod.rs @@ -197,7 +197,7 @@ pub(crate) trait Queue: Send + Sync { &mut self, reg_data: &AsahiRegData<'_>, id: u64, - syncs: KVec, + syncs: KVVec, in_sync_count: usize, cmdbuf_raw: &[u8], objects: Pin<&xarray::XArray>>, @@ -724,7 +724,9 @@ impl Queue::ver { )?; let entity = sched::Entity::new(&sched, sched::Priority::Kernel)?; - let buffer = buffer::Buffer::ver::new(gpu, alloc, ualloc.clone(), ualloc_priv, mgr)?; + let buffer = buffer::Buffer::ver::new( + gpu, alloc, ualloc.clone(), ualloc_priv, mgr, buffer::ParameterListPlacement::VmPrivate, + )?; let gpu_context = Arc::new( workqueue::GpuContext::new(dev.clone(), alloc, buffer.any_ref())?, @@ -1008,7 +1010,7 @@ impl Queue for Queue::ver { &mut self, reg_data: &AsahiRegData<'drm>, id: u64, - mut syncs: KVec, + mut syncs: KVVec, in_sync_count: usize, cmdbuf_raw: &[u8], objects: Pin<&xarray::XArray>>, @@ -1278,10 +1280,9 @@ impl Queue for Queue::ver { // A render's wait for earlier renders is added once its flags are // known: without DRM_ASAHI_RENDER_FRAGMENT_BARRIERS it goes on the - // vertex queue; with it no barrier is added, since the wait names - // only earlier fragment work, which the fragment queue already runs - // first, so the vertex half can run beside it. Each fragment half - // still waits for its own vertex half. + // vertex queue; with it, it goes on the fragment queue, so the + // vertex half can run beside the earlier fragment work. Each + // fragment half also waits for its own vertex half. let is_render = u32::from(header.cmd_type) == uapi::drm_asahi_cmd_type_DRM_ASAHI_CMD_RENDER; let mut render_wait = None; @@ -1316,21 +1317,22 @@ impl Queue for Queue::ver { cls_pr_debug!(Errors, "Unsupported render command fields\n") })?; - // With FRAGMENT_BARRIERS the wait names only earlier fragment work of - // this queue (index 0 is its last fragment event, later indices are - // renders of this submission), which the fragment workqueue already - // runs first, so no barrier is needed at all. + // The wait names earlier fragment work of this queue (index 0 is its + // last fragment event, later indices are renders of this + // submission). The fragment workqueue runs that work first, but queue + // order alone does not make it finish first, so with FRAGMENT_BARRIERS + // the wait moves to the fragment half instead of being dropped. let fragment_only = render.flags & uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS != 0; - if let Some(event) = render_wait.take().filter(|_| !fragment_only) { + if let Some(event) = render_wait.take() { + let queue_job = if fragment_only { + job.get_frag()? + } else { + job.get_vtx()? + }; Self::add_explicit_barrier( - &self.dev, - &gpu, - job.get_vtx()?, - &event, - vm_slot, - id, + &self.dev, &gpu, queue_job, &event, vm_slot, id, )?; } diff --git a/drivers/gpu/drm/asahi/queue/render.rs b/drivers/gpu/drm/asahi/queue/render.rs index e84f4403d72d78..eb85d0e949e4b5 100644 --- a/drivers/gpu/drm/asahi/queue/render.rs +++ b/drivers/gpu/drm/asahi/queue/render.rs @@ -47,7 +47,7 @@ impl super::QueueInner::ver { /// This validates the flags and dimensions of the command first, so that every caller, /// including the submission-wide TVB sizing pass that runs before [`Self::submit_render`], /// rejects a malformed command with `EINVAL` before any arithmetic on its dimensions. - fn get_tiling_params( + pub(crate) fn get_tiling_params( cmdbuf: &uapi::drm_asahi_cmd_render, num_clusters: u32, ) -> Result { diff --git a/drivers/gpu/drm/asahi/regs.rs b/drivers/gpu/drm/asahi/regs.rs index 1fde883e6c6df4..bbe92ff8181bf9 100644 --- a/drivers/gpu/drm/asahi/regs.rs +++ b/drivers/gpu/drm/asahi/regs.rs @@ -349,6 +349,13 @@ impl Resources<'_> { .expect("64-bit read failed!") } + /// The G14 Fender operating-point word: requested index in bits 3:0, request pending in + /// bit 4. Sampled while the firmware holds the GPU powered. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + pub(crate) fn operating_point(&self) -> u32 { + self.sgx_read32::<0xd01000>() + } + /// Initialize the MMIO registers for the GPU. pub(crate) fn init_mmio(&self) -> Result { // Nothing to do for now... @@ -481,6 +488,16 @@ impl Resources<'_> { }) } + /// The MMU fault status registers of this GPU core: the status word, the address register + /// (`None` where the address is part of the status word) and whether it uses the G14X layout. + pub(crate) fn fault_registers(cfg: &'static hw::HwConfig) -> (usize, Option, bool) { + if cfg.gpu_core as u32 >= hw::GpuCore::G14S as u32 { + (FAULT_INFO_G14X, Some(FAULT_ADDR_G14X), true) + } else { + (FAULT_INFO, None, false) + } + } + /// Get the fault information from the MMU status register, if one occurred. pub(crate) fn get_fault_info(&self, cfg: &'static hw::HwConfig) -> Option { let g14x = cfg.gpu_core as u32 >= hw::GpuCore::G14S as u32; @@ -657,6 +674,26 @@ impl G17Resources { Ok(true) } + /// Writes an M5 host command-port transaction to the SGX register block. + /// Only the first and last writes carry the write barrier of an ordered + /// MMIO write; interior writes to the same non-posted register block stay + /// in program order without stalling on intermediate GPU round trips. + fn write_m5_submission( + sgx: &IoMem<'_, SGX_SIZE>, + submission: &crate::g17::fw::m5::queue::HardwareSubmission, + ) -> Result { + let sgx = sgx.as_view(); + let writes = submission.writes(); + for (index, &(offset, value)) in writes.iter().enumerate() { + if index != 0 && index + 1 != writes.len() { + sgx.relaxed().try_write64(value, offset)?; + } else { + sgx.try_write64(value, offset)?; + } + } + Ok(()) + } + /// Publishes through the M5 host command port, including the kick that /// makes an idle queue runnable. Core activity is not a prerequisite. pub(crate) fn submit_m5_work( @@ -667,11 +704,7 @@ impl G17Resources { return Ok(()); } let sgx = self.sgx.try_access().ok_or(ENODEV)?; - let sgx = (&*sgx).as_view(); - for &(offset, value) in submission.writes() { - sgx.try_write64(value, offset)?; - } - Ok(()) + Self::write_m5_submission(&*sgx, submission) } /// [`Self::submit_m5_work`] with core gating held off across the transaction, reading the @@ -686,17 +719,14 @@ impl G17Resources { return Ok(()); } let sgx = self.sgx.try_access().ok_or(ENODEV)?; - let sgx = (&*sgx).as_view(); - let gating = sgx.try_read32(G17_GATING_CONTROL)?; - sgx.try_write32(gating | G17_GATING_HOLD, G17_GATING_CONTROL)?; - sgx.try_read32(G17_GATING_CONTROL)?; - let result = submission - .writes() - .iter() - .try_for_each(|&(offset, value)| sgx.try_write64(value, offset)); - let gating = sgx.try_read32(G17_GATING_CONTROL)?; - sgx.try_write32(gating & !G17_GATING_HOLD, G17_GATING_CONTROL)?; - sgx.try_read32(G17_GATING_CONTROL)?; + let view = (&*sgx).as_view(); + let gating = view.try_read32(G17_GATING_CONTROL)?; + view.try_write32(gating | G17_GATING_HOLD, G17_GATING_CONTROL)?; + view.try_read32(G17_GATING_CONTROL)?; + let result = Self::write_m5_submission(&*sgx, submission); + let gating = view.try_read32(G17_GATING_CONTROL)?; + view.try_write32(gating & !G17_GATING_HOLD, G17_GATING_CONTROL)?; + view.try_read32(G17_GATING_CONTROL)?; result } @@ -718,23 +748,6 @@ impl G17Resources { ]) } - /// Sample only the two owned queue configuration words through the - /// host tag/data port. The caller holds the device mutex and power hold. - pub(crate) fn m5_queue_configurations(&self, qids: [u8; 2]) -> Result<[u64; 2]> { - let sgx = self.sgx.try_access().ok_or(ENODEV)?; - let sgx = (&*sgx).as_view(); - if sgx.relaxed().read32(G17_HOST_IRQ_SUMMARY) & G17_HOST_POWERED == 0 { - return Err(EAGAIN); - } - let mut values = [0; 2]; - for (value, qid) in values.iter_mut().zip(qids) { - let tag = crate::g17::fw::m5::queue::HardwareSubmission::configuration_tag(qid)?; - sgx.try_write64(tag, 0x4090)?; - *value = sgx.try_read64(0x4098)?; - } - Ok(values) - } - /// Registers a queue KSM slot through the firmware mailbox. pub(crate) fn register_ksm_queue(&self, qid: u8, descriptor: u64) -> Result { if qid > 127 { diff --git a/drivers/gpu/drm/asahi/rtkit_dump.c b/drivers/gpu/drm/asahi/rtkit_dump.c new file mode 100644 index 00000000000000..c7b147c35a286a --- /dev/null +++ b/drivers/gpu/drm/asahi/rtkit_dump.c @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include + +void asahi_save_rtkit_dump(struct device *dev, const void *data, size_t size); + +/* RTKit owns its immutable shadow only during the crash callback. */ +void asahi_save_rtkit_dump(struct device *dev, const void *data, size_t size) +{ + void *copy; + + if (!size) + return; + copy = vmalloc(size); + if (copy) { + memcpy(copy, data, size); + dev_coredumpv(dev, copy, size, GFP_KERNEL); + } +} diff --git a/drivers/gpu/drm/asahi/sleep_pd.c b/drivers/gpu/drm/asahi/sleep_pd.c new file mode 100644 index 00000000000000..f3612df8c6f916 --- /dev/null +++ b/drivers/gpu/drm/asahi/sleep_pd.c @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Hold the GPU's attached power domain across suspend-to-idle. + * + * When a system sleep does not hand control to platform firmware + * (!pm_suspend_via_firmware()), the GPU driver leaves its firmware running. + * genpd would otherwise power the GPU's domain (such as ps_gfx) off in + * genpd_suspend_noirq(), cutting power under the live coprocessor. + * + * Register a temporary GENPD_NOTIFY_PRE_OFF veto notifier on the GPU device's + * own genpd for the noirq sleep window, matching pcie-apple's consumer-side + * hold without changing any other power domain. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "sleep_pd.h" + +struct asahi_sleep_pd { + struct notifier_block nb; + bool active; +}; + +/* IRQ-safe domains invoke power notifiers in atomic context. */ +static int asahi_sleep_pd_notify(struct notifier_block *nb, + unsigned long action, void *data) +{ + if (action != GENPD_NOTIFY_PRE_OFF) + return NOTIFY_OK; + return notifier_from_errno(-EBUSY); +} + +static void asahi_sleep_pd_release(struct device *dev, void *res) +{ + struct asahi_sleep_pd *hold = res; + + if (hold->active) { + dev_pm_genpd_remove_notifier(dev); + hold->active = false; + } +} + +int asahi_sleep_pd_init(struct device *dev) +{ + struct asahi_sleep_pd *hold; + + hold = devres_alloc(asahi_sleep_pd_release, sizeof(*hold), GFP_KERNEL); + if (!hold) + return -ENOMEM; + + hold->nb.notifier_call = asahi_sleep_pd_notify; + devres_add(dev, hold); + return 0; +} + +int asahi_sleep_pd_suspend_noirq(struct device *dev) +{ + struct asahi_sleep_pd *hold; + int ret; + + if (pm_suspend_via_firmware()) + return 0; + + /* + * Every current GPU node attaches a single power domain (M2 attaches + * pmp_report_gfx with APPLE_USE_PMP, which keeps ps_gfx up as its + * parent), so dev->pm_domain is a single genpd that + * dev_pm_genpd_is_on() and dev_pm_genpd_add_notifier() target + * directly. For a multi-domain GPU node, genpd_dev_pm_attach() leaves + * dev->pm_domain unset, so dev_pm_genpd_is_on() would return false and + * genpd would power those domains off under live GPU firmware; refuse + * s2idle with -EBUSY rather than failing open. + */ + if (!dev->pm_domain) { + if (of_count_phandle_with_args(dev->of_node, "power-domains", + "#power-domain-cells") > 1) { + dev_warn_once(dev, + "GPU has multiple power domains; s2idle hold only supports a single genpd, refusing s2idle\n"); + return -EBUSY; + } + return 0; + } + + if (!dev_pm_genpd_is_on(dev)) + return 0; + + hold = devres_find(dev, asahi_sleep_pd_release, NULL, NULL); + if (WARN_ON_ONCE(!hold)) + return -EBUSY; + + if (hold->active) + return 0; + + ret = dev_pm_genpd_add_notifier(dev, &hold->nb); + if (ret == -EEXIST) { + dev_warn(dev, "genpd already has a power notifier; refusing s2idle\n"); + return -EBUSY; + } + if (ret) + return ret; + + hold->active = true; + return 0; +} + +int asahi_sleep_pd_resume_noirq(struct device *dev) +{ + struct asahi_sleep_pd *hold; + + hold = devres_find(dev, asahi_sleep_pd_release, NULL, NULL); + if (!hold || !hold->active) + return 0; + + dev_pm_genpd_remove_notifier(dev); + hold->active = false; + return 0; +} diff --git a/drivers/gpu/drm/asahi/sleep_pd.h b/drivers/gpu/drm/asahi/sleep_pd.h new file mode 100644 index 00000000000000..63fdcd662455f1 --- /dev/null +++ b/drivers/gpu/drm/asahi/sleep_pd.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ + +#ifndef _ASAHI_SLEEP_PD_H +#define _ASAHI_SLEEP_PD_H + +struct device; + +int asahi_sleep_pd_init(struct device *dev); +int asahi_sleep_pd_suspend_noirq(struct device *dev); +int asahi_sleep_pd_resume_noirq(struct device *dev); + +#endif diff --git a/drivers/gpu/drm/asahi/stats.rs b/drivers/gpu/drm/asahi/stats.rs index e0f68f14369803..1c2a16846586b9 100644 --- a/drivers/gpu/drm/asahi/stats.rs +++ b/drivers/gpu/drm/asahi/stats.rs @@ -85,7 +85,8 @@ impl StatsSnapshot { } /// The frequency the GPU runs at now, if the firmware reports it, and its highest, in - /// Hz, for fdinfo (`drm-curfreq-*`, `drm-maxfreq-*`): V26A428 (A18 Pro and M5) only. + /// Hz, for fdinfo (`drm-curfreq-*`, `drm-maxfreq-*`): V26A428 (A18 Pro and M5) and + /// T6041 (25G83). pub(crate) fn engine_frequency(&self) -> Option<(Option, u64)> { self.g17_reader.as_ref()?.frequency() } diff --git a/drivers/gpu/drm/asahi/sysfs.c b/drivers/gpu/drm/asahi/sysfs.c index fb0737c2693bd3..887c54c56545b0 100644 --- a/drivers/gpu/drm/asahi/sysfs.c +++ b/drivers/gpu/drm/asahi/sysfs.c @@ -94,30 +94,46 @@ static ssize_t agx_qualified_stats_show(struct asahi_stats_attribute *stats, cha "util_device_percent unsupported\n"); } /* - * unsupported comes from the firmware match data (g17::stats): V25G83 - * never emits a pstate record, so it is not a transient state. + * unsupported comes from the firmware match data (g17::stats): builds + * without a pstate telemetry protocol (such as T6040 25G83, left on + * Protocol::NONE pending measurement) have no qualified pstate support, + * so it is not a transient state. * unavailable keeps meaning "no qualified sample yet". */ n += sysfs_emit_at(buf, n, "pstate_status %s\n", asahi_stats_quality(snap.pstate_status)); + /* + * A pstate that is not valid reads its status word, so stale or + * unavailable is not mistaken for a missing feature. Where it is + * unsupported, the output is unchanged. + */ if (snap.pstate_status == 1) n += sysfs_emit_at(buf, n, "pstate %u\n", snap.pstate); else - n += sysfs_emit_at(buf, n, "pstate unsupported\n"); + n += sysfs_emit_at(buf, n, "pstate %s\n", + asahi_stats_quality(snap.pstate_status)); /* No host frequency request, measured power or temperature. */ n += sysfs_emit_at(buf, n, "requested_frequency_hz unsupported\n"); /* - * V26A428 reports the state the GPU runs at: its frequency is the - * achieved one. State 0 is off (gated cores) and runs at 0 Hz. + * Firmwares with a pstate protocol (V26A428, T6041 25G83) report + * the state the GPU runs at: its frequency is the achieved one. State 0 + * is off (gated cores) and runs at 0 Hz. */ if (snap.pstate_status == 1 && (snap.achieved_frequency_hz || !snap.pstate)) n += sysfs_emit_at(buf, n, "achieved_frequency_hz %llu\n", (unsigned long long)snap.achieved_frequency_hz); - else + else if (snap.pstate_status == 1) + /* A valid state with no frequency in the board's table. */ n += sysfs_emit_at(buf, n, "achieved_frequency_hz unsupported\n"); + else + n += sysfs_emit_at(buf, n, "achieved_frequency_hz %s\n", + asahi_stats_quality(snap.pstate_status)); if (snap.busy_status == 1) n += sysfs_emit_at(buf, n, "busy_ns %llu\n", (unsigned long long)snap.busy_ns); + else if (snap.busy_status == 2) + /* The total stopped (a statistics ring was quarantined). */ + n += sysfs_emit_at(buf, n, "busy_ns stale\n"); else n += sysfs_emit_at(buf, n, "busy_ns unsupported\n"); n += sysfs_emit_at(buf, n, "power_mw unsupported\n" diff --git a/drivers/gpu/drm/asahi/timestamp.rs b/drivers/gpu/drm/asahi/timestamp.rs index 2a18ebbeb5d9cc..a9e0dab483da97 100644 --- a/drivers/gpu/drm/asahi/timestamp.rs +++ b/drivers/gpu/drm/asahi/timestamp.rs @@ -2,24 +2,77 @@ //! Prepared timestamp destinations shared by native command completion paths. -use crate::mmu; -#[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] -use crate::{file, gem}; +use crate::{gem, mmu, no_debug}; #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] +use crate::file; use core::ops::Range; #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] use core::sync::atomic::{fence as barrier, Ordering}; -use kernel::{prelude::*, sync::Arc}; +use kernel::prelude::*; #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] -use kernel::{uapi, xarray}; +use kernel::{sync::Arc, uapi, xarray}; + +/// The size of a bound range: whole pages, not empty, inside an object of `object_size` bytes. +fn bound_size(range: &Range, object_size: usize) -> Result { + let size = range.end.checked_sub(range.start).ok_or(EINVAL)?; + if size == 0 || (range.start | size) & mmu::UAT_PGMSK != 0 || range.end > object_size { + return Err(EINVAL); + } + Ok(size) +} + +/// The object offset of the timestamp at `offset` of a host buffer bound at `start` for `size` +/// bytes: the whole stamp must lie inside the bound range, which lies inside the object +/// ([`Buffer::host`]). +fn host_offset(start: usize, size: usize, offset: usize) -> Result { + if offset.checked_add(size_of::()).ok_or(EOVERFLOW)? > size { + return Err(ERANGE); + } + start.checked_add(offset).ok_or(EOVERFLOW) +} + +/// Permission for a timestamp bind to alias in the backend's firmware timestamp window. +pub(crate) enum WindowPermit { + /// No per-file window share applies (the backend has no fixed window limit). + Unrestricted, + /// The file's reserved share of the firmware timestamp window, held until unmap. + Share(crate::memacct::WindowShare), + /// The file's window share is exhausted; fall back to host or refuse with ENOSPC. + Denied, +} + +impl WindowPermit { + pub(crate) fn is_allowed(&self) -> bool { + !matches!(self, Self::Denied) + } + + pub(crate) fn into_share(self) -> Option { + match self { + Self::Share(share) => Some(share), + Self::Unrestricted | Self::Denied => None, + } + } +} /// A firmware-mapped timestamp buffer with a kernel CPU mapping of its backing, kept for the /// buffer's lifetime so that commands need no mapping of their own. pub(crate) struct FirmwareBuffer { - mapping: Arc, + mapping: mmu::KernelMapping, cpu: mmu::TimestampVmap, /// Mapped in the firmware's timestamp window: the firmware may write stamps itself. window: bool, + /// The file's share of the firmware timestamp window, held as the last field so `mapping` + /// is unmapped on the cleanup queue before the quota is credited back. + _window_share: Option, +} + +/// A timestamp buffer only the host writes, through a kernel CPU mapping of its backing. It has +/// no firmware alias, so binding it takes no firmware address space. +pub(crate) struct HostBuffer { + cpu: mmu::TimestampVmap, + /// The bound range of the object. + start: usize, + size: usize, } /// A bound timestamp destination. Only backends which publish firmware writes need a UAT alias. @@ -29,6 +82,8 @@ pub(crate) enum Buffer { /// releasing the CPU mapping takes the reservation lock: the deferral runs the release /// on the cleanup queue. Firmware(crate::cleanup::Deferred), + /// Host-written, with the same deferred release as [`Self::Firmware`]. + Host(crate::cleanup::Deferred), #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Cpu { // The GEM pin keeps the object's held SG table alive through CPU publication. @@ -37,25 +92,100 @@ pub(crate) enum Buffer { }, } +/// A timestamp buffer bound to a file, holding the charge for the kernel memory its records take +/// (see `file::BOUND_OBJECT_BYTES`), so the charge is given back with the last reference. +pub(crate) struct Bound { + buffer: Buffer, + _charge: crate::memacct::Commit, +} + +impl Bound { + pub(crate) fn new(buffer: Buffer, charge: crate::memacct::Commit) -> Self { + Self { + buffer, + _charge: charge, + } + } +} + +impl core::ops::Deref for Bound { + type Target = Buffer; + + fn deref(&self) -> &Buffer { + &self.buffer + } +} + +no_debug!(Bound); + +/// The larger of two sizes, for the heap bound below. +const fn max(a: usize, b: usize) -> usize { + if a > b { a } else { b } +} + impl Buffer { - pub(crate) fn firmware(mapping: mmu::KernelMapping) -> Result { - Self::new_firmware(mapping, false) + /// Kernel heap bytes a buffer's own records take, at most: its deferred-release item. A CPU + /// buffer keeps its records inline. + pub(crate) const HEAP_BYTES: usize = max( + crate::cleanup::Deferred::::HEAP_BYTES, + crate::cleanup::Deferred::::HEAP_BYTES, + ); + + pub(crate) fn firmware( + mapping: mmu::KernelMapping, + window_share: Option, + ) -> Result { + Self::new_firmware(mapping, false, window_share) } /// A buffer aliased in the firmware's timestamp window. - pub(crate) fn firmware_window(mapping: mmu::KernelMapping) -> Result { - Self::new_firmware(mapping, true) + pub(crate) fn firmware_window( + mapping: mmu::KernelMapping, + window_share: Option, + ) -> Result { + Self::new_firmware(mapping, true, window_share) } - fn new_firmware(mapping: mmu::KernelMapping, window: bool) -> Result { - let cpu = mapping.timestamp_vmap()?; - Ok(Self::Firmware(crate::cleanup::Deferred::new(FirmwareBuffer { - mapping: Arc::new(mapping, GFP_KERNEL)?, - cpu, - window, + /// A buffer whose stamps the host writes: the bound range of a firmware-shareable object, + /// as for a firmware alias, with only a CPU mapping. Not under the device mutex (the CPU + /// mapping takes the reservation lock). + pub(crate) fn host(bo: &gem::ObjectRef, range: Range) -> Result { + let size = bound_size(&range, bo.size())?; + // A firmware alias refuses VM-private objects (gem::validate_vm_binding); so does this. + if bo.gem.is_vm_private() { + return Err(EINVAL); + } + Ok(Self::Host(crate::cleanup::Deferred::new(HostBuffer { + cpu: mmu::TimestampVmap::new(&bo.gem)?, + start: range.start, + size, })?)) } + fn new_firmware( + mapping: mmu::KernelMapping, + window: bool, + window_share: Option, + ) -> Result { + // Keep `window_share` behind `mapping` on error paths too: `mapping` must unmap + // before the window share is credited back. + let cpu = match mapping.timestamp_vmap() { + Ok(cpu) => cpu, + Err(err) => { + drop(mapping); + return Err(err); + } + }; + Ok(Self::Firmware(crate::cleanup::Deferred::new( + FirmwareBuffer { + mapping, + cpu, + window, + _window_share: window_share, + }, + )?)) + } + /// The window address of the timestamp at `offset`, for a window buffer and an aligned /// destination that lies wholly inside the mapping. pub(crate) fn window_va(&self, offset: usize) -> Option { @@ -72,6 +202,7 @@ impl Buffer { pub(crate) fn read_timestamp(&self, offset: usize) -> Option { match self { Self::Firmware(buffer) => buffer.cpu.read(offset), + Self::Host(buffer) => buffer.cpu.read(offset), #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { .. } => None, } @@ -80,10 +211,7 @@ impl Buffer { /// Retain a CPU-written byte range without publishing any firmware address. #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] pub(crate) fn cpu(bo: gem::ObjectRef, range: Range) -> Result { - let size = range.end.checked_sub(range.start).ok_or(EINVAL)?; - if size == 0 || (range.start | size) & mmu::UAT_PGMSK != 0 || range.end > bo.size() { - return Err(EINVAL); - } + bound_size(&range, bo.size())?; let gem = gem::KernelMappingPin::new(&bo.gem); let registered = bo.gem.dev().registration_guard().ok_or(ENODEV)?; let parent: &kernel::platform::Device = registered.as_ref(); @@ -94,6 +222,7 @@ impl Buffer { pub(crate) fn size(&self) -> usize { match self { Self::Firmware(buffer) => buffer.mapping.size(), + Self::Host(buffer) => buffer.size, #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { range, .. } => range.end - range.start, } @@ -103,6 +232,7 @@ impl Buffer { pub(crate) fn timestamp_mapping(&self, offset: usize) -> Result { match self { Self::Firmware(buffer) => buffer.mapping.timestamp_mapping(offset), + Self::Host(_) => Err(EINVAL), #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { gem, range, .. } => { if offset.checked_add(size_of::()).ok_or(EOVERFLOW)? > self.size() { @@ -113,11 +243,12 @@ impl Buffer { } } - /// The object offset of the timestamp at `offset` of a firmware buffer, for + /// The object offset of the timestamp at `offset` of a firmware or host buffer, for /// [`Self::write_timestamp`]. pub(crate) fn timestamp_offset(&self, offset: usize) -> Result { match self { Self::Firmware(buffer) => buffer.mapping.timestamp_offset(offset), + Self::Host(buffer) => host_offset(buffer.start, buffer.size, offset), #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { .. } => Err(EINVAL), } @@ -128,15 +259,19 @@ impl Buffer { pub(crate) fn write_timestamp(&self, offset: usize, value: u64) { match self { Self::Firmware(buffer) => buffer.cpu.write(offset, value), + Self::Host(buffer) => buffer.cpu.write(offset, value), #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { .. } => {} } } - /// Legacy command encoders publish firmware pointers and must never accept a CPU-only buffer. - pub(crate) fn firmware_mapping(&self) -> Result> { + /// Firmware-aliased command encoders publish firmware pointers and must never accept a + /// host- or CPU-only buffer. Returning a borrow keeps the mapping tied to [`Bound`] so no + /// command can retain the mapping without also keeping its bind charge and window share alive. + pub(crate) fn firmware_mapping(&self) -> Result<&mmu::KernelMapping> { match self { - Self::Firmware(buffer) => Ok(buffer.mapping.clone()), + Self::Firmware(buffer) => Ok(&buffer.mapping), + Self::Host(_) => Err(EINVAL), #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { .. } => Err(EINVAL), } @@ -159,7 +294,7 @@ fn checked_offset(offset: u64, size: usize, aligned: bool) -> Result { #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] struct Destination { // Retain the bound range and backing along with its prepared CPU view. - _mapping: Arc, + _mapping: Arc, cpu: mmu::TimestampMapping, } @@ -203,6 +338,20 @@ pub(crate) struct Destinations(Option Self { + Self(None) + } + + /// No timestamp is written for this command. + #[allow(dead_code)] + pub(crate) fn is_empty(&self) -> bool { + self.0 + .as_deref() + .is_none_or(|destinations| destinations.iter().all(Option::is_none)) + } + /// G16 retains its eight-byte destination alignment and EINVAL contract. #[cfg(CONFIG_DRM_ASAHI_G16)] pub(crate) fn resolve_aligned( @@ -261,3 +410,34 @@ impl Destinations { destinations.iter() } } + +#[kernel::macros::kunit_tests(asahi_timestamp_buffer)] +mod tests { + use super::*; + + const PAGE: usize = mmu::UAT_PGSZ; + + #[test] + fn a_bound_range_is_whole_pages_inside_the_object() { + assert_eq!(bound_size(&(0..PAGE), PAGE), Ok(PAGE)); + assert_eq!(bound_size(&(PAGE..3 * PAGE), 3 * PAGE), Ok(2 * PAGE)); + assert_eq!(bound_size(&(0..0), PAGE), Err(EINVAL)); + assert_eq!(bound_size(&(PAGE..0), PAGE), Err(EINVAL)); + assert_eq!(bound_size(&(0..PAGE / 2), PAGE), Err(EINVAL)); + assert_eq!(bound_size(&(PAGE / 2..PAGE + PAGE / 2), 2 * PAGE), Err(EINVAL)); + assert_eq!(bound_size(&(0..2 * PAGE), PAGE), Err(EINVAL)); + assert_eq!(bound_size(&(PAGE..usize::MAX & !(PAGE - 1)), 2 * PAGE), Err(EINVAL)); + } + + #[test] + fn a_host_stamp_lies_inside_the_bound_range() { + // A host buffer bound at the object's second page: offsets are within the bound range + // and come back as object offsets. + assert_eq!(host_offset(PAGE, PAGE, 0), Ok(PAGE)); + assert_eq!(host_offset(PAGE, PAGE, PAGE - 8), Ok(2 * PAGE - 8)); + // A stamp reaching past the bound range is refused, even if the object goes on. + assert_eq!(host_offset(PAGE, PAGE, PAGE - 4), Err(ERANGE)); + assert_eq!(host_offset(PAGE, PAGE, PAGE), Err(ERANGE)); + assert_eq!(host_offset(0, PAGE, usize::MAX - 2), Err(EOVERFLOW)); + } +} diff --git a/drivers/gpu/drm/asahi/usage.rs b/drivers/gpu/drm/asahi/usage.rs index aa817d2d417687..36a7f3ed17e691 100644 --- a/drivers/gpu/drm/asahi/usage.rs +++ b/drivers/gpu/drm/asahi/usage.rs @@ -9,7 +9,17 @@ //! A backend whose firmware overlaps the commands of one queue charges through a [`Lane`] //! per queue, so each engine of a queue counts the union of its stage intervals. -use core::sync::atomic::{AtomicU64, Ordering}; +use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + +/// Number of GPU engines tracked in [`Engine`]: vertex, fragment and compute. +pub(crate) const NUM_ENGINES: usize = 3; + +/// Engine time charged across all clients per [`Engine`], in ns, for the GPU busy share. +/// +/// Overlapping work from multiple clients on the same engine adds up here; consumers clamp +/// the resulting busy share to 1000 permille, which safely errs toward the higher floor. +pub(crate) static ENGINE_NS: [AtomicU64; NUM_ENGINES] = + [const { AtomicU64::new(0) }; NUM_ENGINES]; #[derive(Clone, Copy)] pub(crate) enum Engine { @@ -20,16 +30,50 @@ pub(crate) enum Engine { /// One ledger per DRM file, shared by all of its queues and VMs. pub(crate) struct Client { - ns: [AtomicU64; 3], + ns: [AtomicU64; NUM_ENGINES], + covered: [AtomicU64; NUM_ENGINES], + queues: AtomicU32, } impl Client { pub(crate) const fn new() -> Self { Self { - ns: [const { AtomicU64::new(0) }; 3], + ns: [const { AtomicU64::new(0) }; NUM_ENGINES], + covered: [const { AtomicU64::new(0) }; NUM_ENGINES], + queues: AtomicU32::new(0), + } + } + + /// Reserves one logical queue credit against this DRM file up to `limit`. + pub(crate) fn try_acquire_queue(&self, limit: u32) -> bool { + let mut count = self.queues.load(Ordering::Acquire); + loop { + if count >= limit { + return false; + } + match self.queues.compare_exchange_weak( + count, + count + 1, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => return true, + Err(value) => count = value, + } } } + /// Releases one logical queue credit previously acquired from this DRM file. + pub(crate) fn release_queue(&self) { + let previous = self.queues.fetch_sub(1, Ordering::AcqRel); + debug_assert!(previous != 0); + } + + #[cfg(test)] + pub(crate) fn queues(&self) -> u32 { + self.queues.load(Ordering::Acquire) + } + /// Called exactly once per retired stage, while its internal timestamps are retained. /// Missing, reversed or reset timestamps contribute nothing. Sub-nanosecond fractions /// are rounded down per stage. Saturation keeps fdinfo monotonic even on overflow. @@ -38,6 +82,9 @@ impl Client { return; } let ns = ticks_to_ns(end - start, frequency_hz); + // Release orders retirement's earlier qos_complete() before any reader + // that Acquire-loads ENGINE_NS and then reads qos.oldest_in_flight(). + ENGINE_NS[engine as usize].fetch_add(ns, Ordering::Release); let counter = &self.ns[engine as usize]; let mut old = counter.load(Ordering::Relaxed); loop { @@ -53,17 +100,48 @@ impl Client { } } + /// As [`Self::add`], deduplicating overlapping stage intervals across all queues of this + /// DRM file (including sibling queues running concurrently on multiple hardware pipes). + /// Only the part of `start..end` after the file's per-engine mark is charged, and the + /// mark advances to `end`. + pub(crate) fn add_union(&self, engine: Engine, start: u64, end: u64, frequency_hz: u32) { + if let Some(from) = union_mark(&self.covered[engine as usize], start, end, frequency_hz) { + self.add(engine, from, end, frequency_hz); + } + } + /// Vertex, fragment and compute, in ns. No cross-engine atomic snapshot is promised. - pub(crate) fn snapshot(&self) -> [u64; 3] { + pub(crate) fn snapshot(&self) -> [u64; NUM_ENGINES] { self.ns.each_ref().map(|ns| ns.load(Ordering::Relaxed)) } } -/// A stage this far behind its lane's mark is not an overlap, since no stage runs this -/// long: the timestamps jumped, so the mark restarts at the stage instead of holding every +/// A stage this far behind its mark is not an overlap, since no stage runs this long: +/// the timestamps jumped, so the mark restarts at the stage instead of holding every /// later charge back. const DISCONTINUITY_S: u64 = 60; +/// Advances `mark` to cover `start..end`, returning the uncovered sub-interval start `from` +/// when `from < end`, or `None` when the interval is invalid or already covered. +fn union_mark(mark: &AtomicU64, start: u64, end: u64, frequency_hz: u32) -> Option { + if start == 0 || end <= start || frequency_hz == 0 { + return None; + } + let limit = u64::from(frequency_hz).saturating_mul(DISCONTINUITY_S); + let mut covered = mark.load(Ordering::Relaxed); + loop { + let jumped = covered.saturating_sub(start) > limit; + let from = if jumped { start } else { start.max(covered) }; + if from >= end { + return None; + } + match mark.compare_exchange_weak(covered, end, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => return Some(from), + Err(value) => covered = value, + } + } +} + /// The engine time of one queue, charged to its file's [`Client`]. /// /// Firmware can run several commands of one queue at once. A queue that keeps several @@ -75,38 +153,23 @@ const DISCONTINUITY_S: u64 = 60; /// still add up, one union each. pub(crate) struct Lane

{ client: P, - covered: [AtomicU64; 3], + covered: [AtomicU64; NUM_ENGINES], } impl> Lane

{ pub(crate) fn new(client: P) -> Self { Self { client, - covered: [const { AtomicU64::new(0) }; 3], + covered: [const { AtomicU64::new(0) }; NUM_ENGINES], } } /// As [`Client::add`], for one retired stage of this lane's queue: only the part of /// `start..end` after the engine's mark is charged, and the mark moves to `end`. pub(crate) fn add(&self, engine: Engine, start: u64, end: u64, frequency_hz: u32) { - if start == 0 || end <= start || frequency_hz == 0 { - return; + if let Some(from) = union_mark(&self.covered[engine as usize], start, end, frequency_hz) { + self.client.add(engine, from, end, frequency_hz); } - let limit = u64::from(frequency_hz).saturating_mul(DISCONTINUITY_S); - let mark = &self.covered[engine as usize]; - let mut covered = mark.load(Ordering::Relaxed); - let from = loop { - let jumped = covered.saturating_sub(start) > limit; - let from = if jumped { start } else { start.max(covered) }; - if from >= end { - return; - } - match mark.compare_exchange_weak(covered, end, Ordering::Relaxed, Ordering::Relaxed) { - Ok(_) => break from, - Err(value) => covered = value, - } - }; - self.client.add(engine, from, end, frequency_hz); } } @@ -258,6 +321,33 @@ mod tests { assert_eq!(client.snapshot(), [0, 0, 4_000]); } + #[test] + fn client_union_deduplicates_dual_pipe_siblings_and_isolates_files() { + let file_a = Client::new(); + let file_b = Client::new(); + // Two sibling queues on the same DRM file overlapping across two CDM pipes + // (e.g., 543 us dispatches at depth 4). + const PERIOD: u64 = 13_032; // 543 us at 24 MHz + for i in 0..100u64 { + let p0_start = 1_000 + i * PERIOD; + let p1_start = p0_start + PERIOD / 4; + file_a.add_union(Engine::Compute, p0_start, p0_start + PERIOD, HZ); + file_a.add_union(Engine::Compute, p1_start, p1_start + PERIOD, HZ); + } + let wall = ticks_to_ns(99 * PERIOD + PERIOD / 4 + PERIOD, HZ); + assert_eq!(file_a.snapshot()[2], wall); + // Separate DRM file keeps its own union mark. + file_b.add_union(Engine::Compute, 1_000, 1_000 + PERIOD, HZ); + assert_eq!(file_b.snapshot()[2], ticks_to_ns(PERIOD, HZ)); + // Timestamp jump > 60 s behind the mark restarts the file mark cleanly. + let far = 61 * u64::from(HZ); + file_b.add_union(Engine::Compute, 1, far, HZ); + let before = file_b.snapshot()[2]; + file_b.add_union(Engine::Compute, 24, 48, HZ); + file_b.add_union(Engine::Compute, 36, 72, HZ); + assert_eq!(file_b.snapshot()[2] - before, 2_000); + } + #[test] fn a_timestamp_jump_restarts_the_mark() { let client = Client::new(); @@ -318,4 +408,23 @@ mod tests { } assert_eq!(client.snapshot(), [0, 0, 80_000_000]); } + + #[test] + fn per_file_queue_credits_are_bounded_and_isolated() { + let a = Client::new(); + let b = Client::new(); + for i in 0..4u32 { + assert!(a.try_acquire_queue(4)); + assert_eq!(a.queues(), i + 1); + } + assert!(!a.try_acquire_queue(4)); + assert_eq!(a.queues(), 4); + assert!(b.try_acquire_queue(4)); + assert_eq!(b.queues(), 1); + a.release_queue(); + assert_eq!(a.queues(), 3); + assert!(a.try_acquire_queue(4)); + b.release_queue(); + assert_eq!(b.queues(), 0); + } } diff --git a/drivers/gpu/drm/asahi/vm/mod.rs b/drivers/gpu/drm/asahi/vm/mod.rs deleted file mode 100644 index 63cf8a76cd5ce4..00000000000000 --- a/drivers/gpu/drm/asahi/vm/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT - -//! Virtual address space management - -mod range; diff --git a/drivers/gpu/drm/asahi/vm/range.rs b/drivers/gpu/drm/asahi/vm/range.rs deleted file mode 100644 index 727d29a5cccf02..00000000000000 --- a/drivers/gpu/drm/asahi/vm/range.rs +++ /dev/null @@ -1,125 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 or MIT - -// Copied from tyr's mmu/vm/range.rs - -//! Range allocator. -//! -//! This module allows you to search for unused ranges to store GEM objects. - -use kernel::alloc::Flags; -use kernel::maple_tree::MapleTreeAlloc; -use kernel::prelude::*; -use kernel::sync::Arc; - -use core::ops::Range; - -/// The actual storage for the ranges. -/// -/// All ranges must fit within the `range` field. -/// -/// The implementation is different on 32-bit and 64-bit cpus. On 64-bit, the 64-bit addresses are -/// stored directly in the maple tree, but on 32-bit, the maple tree stores the ranges translated -/// in the range zero until `range.end-range.start`. This is done because the maple tree uses -/// unsigned long as its address type, which is too small to store the 64-bit address directly on -/// 32-bit machines. -#[pin_data] -struct RangeAllocInner { - #[pin] - maple: MapleTreeAlloc<()>, - range: Range, -} - -/// This object allows you to allocate ranges on the inner maple tree. -pub(crate) struct RangeAlloc { - inner: Arc, -} - -/// Represents a live range in the maple tree. -/// -/// The destructor removes the range from the maple tree, allowing others to allocate it in the -/// future. -pub(crate) struct LiveRange { - inner: Arc, - offset: u64, - size: usize, -} - -impl RangeAlloc { - pub(crate) fn new(start: u64, end: u64, gfp: Flags) -> Result { - if end < start { - return Err(EINVAL); - } - - let inner = Arc::pin_init( - try_pin_init!(RangeAllocInner { - maple <- MapleTreeAlloc::new(), - range: start..end, - }), - gfp, - )?; - - Ok(RangeAlloc { inner }) - } - - pub(crate) fn allocate(&self, size: usize, gfp: Flags) -> Result { - let maple_start = self.inner.range.start as usize; - let maple_end = self.inner.range.end as usize; - - let offset = self - .inner - .maple - .alloc_range(size, (), maple_start..maple_end, gfp)?; - - Ok(LiveRange { - inner: self.inner.clone(), - offset: offset as u64, - size, - }) - } - - pub(crate) fn insert(&self, start: u64, end: u64, gfp: Flags) -> Result { - if end < start { - return Err(EINVAL); - } - if start < self.inner.range.start { - return Err(EINVAL); - } - if end > self.inner.range.end { - return Err(EINVAL); - } - - self.inner - .maple - .insert_range(start as usize..end as usize, (), gfp)?; - - Ok(LiveRange { - inner: self.inner.clone(), - offset: start, - size: (end - start) as usize, - }) - } -} - -impl LiveRange { - pub(crate) fn size(&self) -> usize { - self.size - } - - pub(crate) fn start(&self) -> u64 { - self.offset - } - - pub(crate) fn end(&self) -> u64 { - self.offset + self.size as u64 - } - - pub(crate) fn range(&self) -> Range { - self.start()..self.end() - } -} - -impl Drop for LiveRange { - fn drop(&mut self) { - self.inner.maple.erase(self.offset as usize); - } -} diff --git a/drivers/hid/dockchannel-hid/dockchannel-hid-parser-test.c b/drivers/hid/dockchannel-hid/dockchannel-hid-parser-test.c index 64fde481641cd2..eeec7cbf027027 100644 --- a/drivers/hid/dockchannel-hid/dockchannel-hid-parser-test.c +++ b/drivers/hid/dockchannel-hid/dockchannel-hid-parser-test.c @@ -21,6 +21,7 @@ static int dchid_parser_test_init(struct kunit *test) iface->out_flags = 0x80; iface->tx_seq = 7; init_completion(&iface->out_complete); + spin_lock_init(&iface->resp_lock); dchid->ifaces[1] = iface; test->priv = iface; return 0; @@ -170,6 +171,41 @@ static void dchid_init_descriptor_test(struct kunit *test) KUNIT_EXPECT_MEMEQ(test, iface->hid_desc, msg.descriptor, sizeof(msg.descriptor)); } +/* Repeated descriptors keep one copy, and none replaces a queued one. */ +static void dchid_init_descriptor_repeat_test(struct kunit *test) +{ + struct dchid_iface *iface = test->priv; + struct device *dev = iface->dchid->dev; + struct { + struct dchid_init_hdr hdr; + struct dchid_init_block_hdr block; + u8 descriptor[4]; + } __packed msg = { + .hdr = { .iface = 1, .more_packets = 1 }, + .block = { .type = INIT_HID_DESCRIPTOR, .length = 4 }, + .descriptor = { 0x05, 0x01, 0x09, 0x06 }, + }; + size_t resources = list_count_nodes(&dev->devres_head); + void *desc; + int i; + + for (i = 0; i < 3; i++) { + msg.descriptor[3] = i; + dchid_handle_init(iface->dchid, &msg, sizeof(msg)); + } + KUNIT_EXPECT_EQ(test, list_count_nodes(&dev->devres_head), resources + 1); + KUNIT_ASSERT_NOT_NULL(test, iface->hid_desc); + KUNIT_EXPECT_EQ(test, ((u8 *)iface->hid_desc)[3], 2); + + iface->creating = true; + desc = iface->hid_desc; + msg.descriptor[3] = 3; + dchid_handle_init(iface->dchid, &msg, sizeof(msg)); + KUNIT_EXPECT_PTR_EQ(test, iface->hid_desc, desc); + KUNIT_EXPECT_EQ(test, ((u8 *)iface->hid_desc)[3], 2); + KUNIT_EXPECT_EQ(test, list_count_nodes(&dev->devres_head), resources + 1); +} + static void dchid_packet_checksum_test(struct kunit *test) { struct dchid_hdr hdr = { .hdr_len = sizeof(hdr), .length = 8 }; @@ -265,6 +301,7 @@ static struct kunit_case dchid_parser_cases[] = { KUNIT_CASE(dchid_init_bounds_test), KUNIT_CASE(dchid_short_input_test), KUNIT_CASE(dchid_init_descriptor_test), + KUNIT_CASE(dchid_init_descriptor_repeat_test), KUNIT_CASE(dchid_packet_checksum_test), KUNIT_CASE(dchid_ring_wrap_test), KUNIT_CASE(dchid_ring_bad_header_test), diff --git a/drivers/hid/dockchannel-hid/dockchannel-hid-protocol-test.c b/drivers/hid/dockchannel-hid/dockchannel-hid-protocol-test.c index 2c4d18a9177a27..47f91ca6ee493c 100644 --- a/drivers/hid/dockchannel-hid/dockchannel-hid-protocol-test.c +++ b/drivers/hid/dockchannel-hid/dockchannel-hid-protocol-test.c @@ -62,11 +62,43 @@ static void dchid_pm2_power_off_test(struct kunit *test) KUNIT_EXPECT_MEMEQ(test, cmd, expected, sizeof(expected)); } +static void dchid_pm1_fallback_test(struct kunit *test) +{ + KUNIT_EXPECT_TRUE(test, + dchid_pm1_needs_pm2_fallback(-EIO, + DCHID_ERR_BAD_ARGUMENT, + false, false, true)); + KUNIT_EXPECT_FALSE(test, + dchid_pm1_needs_pm2_fallback(-EIO, + DCHID_ERR_BAD_ARGUMENT, + true, false, true)); + KUNIT_EXPECT_FALSE(test, + dchid_pm1_needs_pm2_fallback(-EIO, + DCHID_ERR_BAD_ARGUMENT, + false, true, true)); + KUNIT_EXPECT_FALSE(test, + dchid_pm1_needs_pm2_fallback(-EIO, + DCHID_ERR_BAD_ARGUMENT, + false, false, false)); + KUNIT_EXPECT_FALSE(test, + dchid_pm1_needs_pm2_fallback(-ETIMEDOUT, + DCHID_ERR_BAD_ARGUMENT, + false, false, true)); + KUNIT_EXPECT_FALSE(test, + dchid_pm1_needs_pm2_fallback(-EIO, 0xe00002bc, + false, false, true)); + KUNIT_EXPECT_FALSE(test, + dchid_pm1_needs_pm2_fallback(0, + DCHID_ERR_BAD_ARGUMENT, + false, false, true)); +} + static struct kunit_case dchid_protocol_test_cases[] = { KUNIT_CASE(dchid_pm1_command_test), KUNIT_CASE(dchid_pm2_will_change_test), KUNIT_CASE(dchid_pm2_has_changed_test), KUNIT_CASE(dchid_pm2_power_off_test), + KUNIT_CASE(dchid_pm1_fallback_test), {} }; diff --git a/drivers/hid/dockchannel-hid/dockchannel-hid-protocol.h b/drivers/hid/dockchannel-hid/dockchannel-hid-protocol.h index c73c911862ac05..96d3c07f1cc180 100644 --- a/drivers/hid/dockchannel-hid/dockchannel-hid-protocol.h +++ b/drivers/hid/dockchannel-hid/dockchannel-hid-protocol.h @@ -5,6 +5,7 @@ #ifndef _DOCKCHANNEL_HID_PROTOCOL_H #define _DOCKCHANNEL_HID_PROTOCOL_H +#include #include #include @@ -32,6 +33,18 @@ #define DCHID_PM1_CMD_SIZE 4 #define DCHID_PM2_CMD_SIZE 9 +/* IOKit kIOReturnBadArgument: returned when firmware rejects power method 1. */ +#define DCHID_ERR_BAD_ARGUMENT 0xe00002c2 + +static inline bool dchid_pm1_needs_pm2_fallback(int ret, u32 retcode, + bool pm_explicit, + bool use_ring, + bool has_afe_reset) +{ + return ret == -EIO && retcode == DCHID_ERR_BAD_ARGUMENT && + !pm_explicit && !use_ring && has_afe_reset; +} + static inline void dchid_pm1_command(u8 iface, u8 state, u8 cmd[DCHID_PM1_CMD_SIZE]) { diff --git a/drivers/hid/dockchannel-hid/dockchannel-hid.c b/drivers/hid/dockchannel-hid/dockchannel-hid.c index 9e0877ca2d496a..4a622ceced5717 100644 --- a/drivers/hid/dockchannel-hid/dockchannel-hid.c +++ b/drivers/hid/dockchannel-hid/dockchannel-hid.c @@ -185,6 +185,12 @@ struct dchid_iface { bool gpio_announced; struct mutex out_mutex; + /* + * Protects the pending command (out_flags, out_report, retcode, + * resp_buf, resp_size, tx_seq) against the receive path, which + * completes it without out_mutex. + */ + spinlock_t resp_lock; u32 out_flags; int out_report; u32 retcode; @@ -194,6 +200,7 @@ struct dchid_iface { u32 keyboard_layout_id; u32 power_method; + bool pm_explicit; bool firmware_managed_reset; }; @@ -251,6 +258,7 @@ static struct dchid_iface * dchid_get_interface(struct dockchannel_hid *dchid, int index, const char *name) { u32 power_method = DCHID_POWER_METHOD_1; + bool pm_explicit = false; bool firmware_managed_reset = false; struct device_node *of_node = NULL; struct dchid_iface *iface; @@ -279,7 +287,8 @@ dchid_get_interface(struct dockchannel_hid *dchid, int index, const char *name) return NULL; } - of_property_read_u32(of_node, "apple,power-method", &power_method); + pm_explicit = !of_property_read_u32(of_node, "apple,power-method", + &power_method); firmware_managed_reset = of_property_read_bool(of_node, "apple,firmware-managed-reset"); if (firmware_managed_reset && @@ -313,11 +322,13 @@ dchid_get_interface(struct dockchannel_hid *dchid, int index, const char *name) iface->dchid = dchid; iface->of_node = of_node; iface->power_method = power_method; + iface->pm_explicit = pm_explicit; iface->firmware_managed_reset = firmware_managed_reset; iface->out_report = -1; init_completion(&iface->out_complete); init_completion(&iface->ready); mutex_init(&iface->out_mutex); + spin_lock_init(&iface->resp_lock); iface->wq = alloc_ordered_workqueue("dchid-%s", WQ_MEM_RECLAIM, iface->name); if (!iface->wq) goto err_put_node; @@ -424,20 +435,25 @@ static int dchid_send(struct dchid_iface *iface, u32 flags, void *msg, size_t si return ret; } -static int dchid_cmd(struct dchid_iface *iface, u32 type, u32 req, - void *data, size_t size, void *resp_buf, size_t resp_size) +static int dchid_cmd_retcode(struct dchid_iface *iface, u32 type, u32 req, + void *data, size_t size, void *resp_buf, + size_t resp_size, u32 *retcode_out) { int ret; - int report_id = *(u8*)data; + int report_id = *(u8 *)data; + u32 fw_retcode = 0; mutex_lock(&iface->out_mutex); + spin_lock(&iface->resp_lock); WARN_ON(iface->out_report != -1); iface->out_report = report_id; iface->out_flags = FIELD_PREP(FLAGS_GROUP, type) | FIELD_PREP(FLAGS_REQ, req); iface->resp_buf = resp_buf; iface->resp_size = resp_size; + iface->retcode = 0; reinit_completion(&iface->out_complete); + spin_unlock(&iface->resp_lock); ret = dchid_send(iface, iface->out_flags, data, size); if (ret < 0) @@ -451,26 +467,50 @@ static int dchid_cmd(struct dchid_iface *iface, u32 type, u32 req, } ret = iface->resp_size; - if (iface->retcode) { + fw_retcode = iface->retcode; + if (fw_retcode) { dev_err(iface->dchid->dev, "output report 0x%x to iface %d (%s) failed with err 0x%x\n", - report_id, iface->index, iface->name, iface->retcode); + report_id, iface->index, iface->name, fw_retcode); ret = -EIO; } done: + /* + * Retire the command before the caller's buffer goes away: an + * acknowledgment that arrives from now on no longer matches it. + */ + spin_lock(&iface->resp_lock); iface->tx_seq++; iface->out_report = -1; iface->out_flags = 0; iface->resp_buf = NULL; iface->resp_size = 0; + spin_unlock(&iface->resp_lock); mutex_unlock(&iface->out_mutex); + if (retcode_out) + *retcode_out = fw_retcode; return ret; } +static int dchid_cmd(struct dchid_iface *iface, u32 type, u32 req, + void *data, size_t size, void *resp_buf, size_t resp_size) +{ + return dchid_cmd_retcode(iface, type, req, data, size, resp_buf, + resp_size, NULL); +} + +static int dchid_comm_cmd_retcode(struct dockchannel_hid *dchid, void *cmd, + size_t size, u32 *retcode_out) +{ + return dchid_cmd_retcode(dchid->comm, HID_FEATURE_REPORT, + REQ_SET_REPORT, cmd, size, NULL, 0, + retcode_out); +} + static int dchid_comm_cmd(struct dockchannel_hid *dchid, void *cmd, size_t size) { - return dchid_cmd(dchid->comm, HID_FEATURE_REPORT, REQ_SET_REPORT, cmd, size, NULL, 0); + return dchid_comm_cmd_retcode(dchid, cmd, size, NULL); } static int dchid_host_state(struct dockchannel_hid *dchid, u8 state) @@ -488,15 +528,20 @@ static int dchid_enable_interface(struct dchid_iface *iface) return dchid_comm_cmd(iface->dchid, msg, sizeof(msg)); } -static int dchid_reset_interface(struct dchid_iface *iface, int state) +static int dchid_reset_interface_retcode(struct dchid_iface *iface, int state, + u32 *retcode_out) { u8 msg[DCHID_PM1_CMD_SIZE]; u8 msg2[DCHID_PM2_CMD_SIZE]; int ret; + if (retcode_out) + *retcode_out = 0; + if (!iface->dchid->use_ring) { dchid_pm1_command(iface->index, state, msg); - return dchid_comm_cmd(iface->dchid, msg, sizeof(msg)); + return dchid_comm_cmd_retcode(iface->dchid, msg, sizeof(msg), + retcode_out); } /* @@ -531,7 +576,13 @@ static int dchid_reset_interface(struct dchid_iface *iface, int state) } #endif dchid_pm2_command(iface->index, state, true, msg2); - return dchid_comm_cmd(iface->dchid, msg2, sizeof(msg2)); + return dchid_comm_cmd_retcode(iface->dchid, msg2, sizeof(msg2), + retcode_out); +} + +static int dchid_reset_interface(struct dchid_iface *iface, int state) +{ + return dchid_reset_interface_retcode(iface, state, NULL); } static int dchid_register_ring(struct dockchannel_hid *dchid) @@ -595,7 +646,7 @@ static int dchid_pm2_set_power(struct dchid_iface *iface, u8 state) } else { bool off = state == DCHID_POWER_STATE_OFF; - ret = gpiod_set_value_cansleep(dchid->afe_reset, off); + ret = gpiod_direction_output(dchid->afe_reset, off); if (ret < 0) { dev_err(dchid->dev, "%s: failed to %s the AFE reset: %d\n", iface->name, off ? "assert" : "release", ret); @@ -721,9 +772,14 @@ static int dchid_request_gpio(struct dchid_iface *iface) dev_dbg(iface->dchid->dev, "Requesting GPIO %s#%d: %s\n", iface->name, iface->gpio_id, iface->gpio_name); - /* A power method 2 interface holds its reset line from probe on. */ - if (iface->power_method == DCHID_POWER_METHOD_2 && + /* Reuse the AFE reset line held from probe on. */ + if (iface->dchid->afe_reset && !strcmp(iface->gpio_name, "afe-reset")) { + if (iface->power_method == DCHID_POWER_METHOD_1) { + ret = gpiod_direction_output(iface->dchid->afe_reset, 0); + if (ret < 0) + return ret; + } iface->gpio = iface->dchid->afe_reset; return 0; } @@ -785,7 +841,7 @@ static int dchid_start_interface(struct dchid_iface *iface) ret = -EINVAL; goto err; } - ret = gpiod_set_value_cansleep(iface->dchid->afe_reset, 1); + ret = gpiod_direction_output(iface->dchid->afe_reset, 1); if (ret < 0) goto err; fsleep(50 * USEC_PER_MSEC); @@ -809,10 +865,44 @@ static int dchid_start_interface(struct dchid_iface *iface) if (ret < 0) goto err; } else { - ret = dchid_reset_interface(iface, DCHID_POWER_STATE_OFF); - /* After a failed AFE power-off the trackpad stays off: no retry. */ - if (ret >= 0 || !iface->dchid->afe_smc || iface->index != 1) + u32 fw_retcode = 0; + + ret = dchid_reset_interface_retcode(iface, + DCHID_POWER_STATE_OFF, + &fw_retcode); + if (dchid_pm1_needs_pm2_fallback(ret, fw_retcode, + iface->pm_explicit, + iface->dchid->use_ring, + !!iface->dchid->afe_reset)) { + dev_info(iface->dchid->dev, + "%s: power method 1 rejected (0x%x); retrying with power method 2\n", + iface->name, fw_retcode); + iface->power_method = DCHID_POWER_METHOD_2; + if (iface->dchid->inherited_mtp) { + ret = gpiod_direction_output(iface->dchid->afe_reset, 1); + if (ret < 0) + goto err; + fsleep(50 * USEC_PER_MSEC); + ret = dchid_send_firmware(iface, fw, size); + if (ret < 0) { + dev_err(iface->dchid->dev, + "Failed to resend %s firmware\n", + iface->name); + goto err; + } + } else { + ret = dchid_pm2_set_power(iface, + DCHID_POWER_STATE_OFF); + if (ret < 0) + goto err; + } + ret = dchid_pm2_set_power(iface, DCHID_POWER_STATE_ON); + if (ret < 0) + goto err; + } else if (ret >= 0 || !iface->dchid->afe_smc || iface->index != 1) { + /* After a failed AFE power-off the trackpad stays off: no retry. */ dchid_reset_interface(iface, DCHID_POWER_STATE_ON); + } } } @@ -1051,16 +1141,26 @@ static int dchid_create_interface(struct dchid_iface *iface) static void dchid_handle_descriptor(struct dchid_iface *iface, void *hid_desc, size_t desc_len) { - if (iface->hid) { + void *desc; + + /* + * Once the interface is queued for creation the HID core may be + * parsing its descriptor, which must then stay as it is. + */ + if (iface->hid || iface->creating) { dev_warn(iface->dchid->dev, "Tried to initialize already started interface %s!\n", iface->name); return; } - iface->hid_desc = devm_kmemdup(iface->dchid->dev, hid_desc, desc_len, GFP_KERNEL); - if (!iface->hid_desc) + desc = devm_kmemdup(iface->dchid->dev, hid_desc, desc_len, GFP_KERNEL); + if (!desc) return; + /* An interface has one descriptor: a repeated one replaces it. */ + if (iface->hid_desc) + devm_kfree(iface->dchid->dev, iface->hid_desc); + iface->hid_desc = desc; iface->hid_desc_len = desc_len; } @@ -1362,26 +1462,29 @@ static void dchid_handle_ack(struct dchid_iface *iface, struct dchid_hdr *hdr, v shdr->length, hdr->length - sizeof(*shdr)); return; } + + /* The command must not be retired between the checks and the copy. */ + spin_lock(&iface->resp_lock); if (shdr->flags != iface->out_flags) { dev_err(iface->dchid->dev, "Received unexpected flags 0x%x on ACK channel (expected 0x%x)\n", shdr->flags, iface->out_flags); - return; + goto out; } if (shdr->length < 1) { dev_err(iface->dchid->dev, "Received length 0 output report ack\n"); - return; + goto out; } if (iface->tx_seq != hdr->seq) { dev_err(iface->dchid->dev, "Received ACK with bad seq (expected %d, got %d)\n", iface->tx_seq, hdr->seq); - return; + goto out; } if (iface->out_report != payload[0]) { dev_err(iface->dchid->dev, "Received ACK with bad report (expected %d, got %d\n", iface->out_report, payload[0]); - return; + goto out; } /* @@ -1402,6 +1505,8 @@ static void dchid_handle_ack(struct dchid_iface *iface, struct dchid_hdr *hdr, v iface->out_report = -1; iface->retcode = shdr->retcode; complete(&iface->out_complete); +out: + spin_unlock(&iface->resp_lock); } /* @@ -1732,6 +1837,12 @@ static int dockchannel_hid_probe(struct platform_device *pdev) if (IS_ERR(dchid->afe_reset)) return dev_err_probe(dev, PTR_ERR(dchid->afe_reset), "Failed to request the AFE reset line\n"); + } else if (!firmware_managed_reset && !dchid->use_ring) { + dchid->afe_reset = devm_gpiod_get_optional(dev, "apple,afe-reset", + GPIOD_ASIS); + if (IS_ERR(dchid->afe_reset)) + return dev_err_probe(dev, PTR_ERR(dchid->afe_reset), + "Failed to request the AFE reset line\n"); } } diff --git a/drivers/hid/hid-apple-mtp-haptic.c b/drivers/hid/hid-apple-mtp-haptic.c index 6264241a655768..60f0709a77219d 100644 --- a/drivers/hid/hid-apple-mtp-haptic.c +++ b/drivers/hid/hid-apple-mtp-haptic.c @@ -99,6 +99,69 @@ EXPORT_SYMBOL_GPL(apple_taptic_switch_modes); #define APPLE_TAPTIC_WAVEFORM_STRENGTH 2 #define APPLE_TAPTIC_WAVEFORM_MAX 64 +/* + * The click waveform the firmware plays itself while device-controlled, + * for a host that plays the same click: the host's output report 0x53 takes + * the body of feature report 0x22 (press) or 0x23 (release) unchanged, a + * version byte, the strength, the softness and then the waveform's shape, + * which differs between machines. Copies the body (without the report ID) + * into @body and returns its length. + */ +int apple_taptic_get_waveform(struct hid_device *haptic_hdev, u16 effect_type, + u8 *body, size_t size) +{ + u8 *buf __free(kfree) = NULL; + u8 report; + int len; + + switch (effect_type) { + case HID_HP_WAVEFORMPRESS & HID_USAGE: + report = APPLE_TAPTIC_PRESS_WAVEFORM; + break; + case HID_HP_WAVEFORMRELEASE & HID_USAGE: + report = APPLE_TAPTIC_RELEASE_WAVEFORM; + break; + default: + return -EINVAL; + } + + buf = kzalloc(APPLE_TAPTIC_WAVEFORM_MAX, GFP_KERNEL); + if (!buf) + return -ENOMEM; + len = hid_hw_raw_request(haptic_hdev, report, buf, + APPLE_TAPTIC_WAVEFORM_MAX, HID_FEATURE_REPORT, + HID_REQ_GET_REPORT); + if (len < 0) + return len; + /* At least the version, the strength and the softness. */ + if (len < 4 || buf[0] != report || !buf[APPLE_TAPTIC_WAVEFORM_STRENGTH]) + return -EPROTO; + if (len - 1 > size) + return -EMSGSIZE; + + memcpy(body, buf + 1, len - 1); + return len - 1; +} +EXPORT_SYMBOL_GPL(apple_taptic_get_waveform); + +/* Play a waveform body from apple_taptic_get_waveform() from the host. */ +int apple_taptic_send_waveform(struct hid_device *haptic_hdev, const u8 *body, + size_t len) +{ + u8 msg[APPLE_TAPTIC_WAVEFORM_MAX]; + int ret; + + if (len < 3 || len + 1 > sizeof(msg)) + return -EINVAL; + msg[0] = 0x53; + memcpy(msg + 1, body, len); + ret = hid_hw_raw_request(haptic_hdev, msg[0], msg, len + 1, + HID_OUTPUT_REPORT, HID_REQ_SET_REPORT); + + return ret < 0 ? ret : 0; +} +EXPORT_SYMBOL_GPL(apple_taptic_send_waveform); + static int apple_taptic_set_strength(struct hid_device *haptic_hdev, u8 report, u8 strength) { diff --git a/drivers/hid/hid-apple.c b/drivers/hid/hid-apple.c index a71de3cd03c097..7b0590b9a7ead7 100644 --- a/drivers/hid/hid-apple.c +++ b/drivers/hid/hid-apple.c @@ -1295,9 +1295,28 @@ static const struct hid_device_id apple_devices[] = { }; MODULE_DEVICE_TABLE(hid, apple_devices); +/* + * Every interface of an internal SPI or DockChannel controller carries the + * controller's IDs. Only the keyboard is ours; leave the others to their own + * driver or to hid-generic. + */ +static bool apple_match(struct hid_device *hdev, bool ignore_special_driver) +{ + if (ignore_special_driver || + (hdev->quirks & HID_QUIRK_IGNORE_SPECIAL_DRIVER)) + return false; + + if ((hdev->bus == BUS_SPI || hdev->bus == BUS_HOST) && + hdev->vendor == SPI_VENDOR_ID_APPLE) + return hdev->type == HID_TYPE_SPI_KEYBOARD; + + return true; +} + static struct hid_driver apple_driver = { .name = "apple", .id_table = apple_devices, + .match = apple_match, .report_fixup = apple_report_fixup, .probe = apple_probe, .remove = apple_remove, diff --git a/drivers/hid/hid-generic.c b/drivers/hid/hid-generic.c index c2de916747dec8..2982206654b278 100644 --- a/drivers/hid/hid-generic.c +++ b/drivers/hid/hid-generic.c @@ -31,7 +31,15 @@ static int __check_hid_generic(struct device_driver *drv, void *data) if (hdrv == &hid_generic) return 0; - return hid_match_device(hdev, hdrv) != NULL; + if (!hid_match_device(hdev, hdrv)) + return 0; + + /* + * A driver with a match callback can decline a device its table + * covers. Ask it, so that a device no other driver will take is not + * left unbound. + */ + return !hdrv->match || hdrv->match(hdev, false); } static bool hid_generic_match(struct hid_device *hdev, diff --git a/drivers/hid/hid-magicmouse.c b/drivers/hid/hid-magicmouse.c index 4d8ffa36d77004..853642b33515e1 100644 --- a/drivers/hid/hid-magicmouse.c +++ b/drivers/hid/hid-magicmouse.c @@ -63,13 +63,13 @@ MODULE_PARM_DESC(report_undeciphered, "Report undeciphered multi-touch state fie /* * Waveform shaping, writable at runtime and applied on the next effect - * upload. Zero means "use the per-transport default": the MTP machines keep - * the values their firmware was tuned with, the SPI actuator in a J313 needs - * a much softer, weaker waveform. The SPI numbers were judged by feel there. + * upload. Zero means "use the default" (magicmouse_haptic_waveform()): on MTP + * the press and release follow the actuator firmware's own click, the SPI + * actuator in a J313 needs a much softer, weaker waveform. */ static u8 haptic_softness; module_param(haptic_softness, byte, 0644); -MODULE_PARM_DESC(haptic_softness, "softness of the press and release waveforms, 1-255 (0: 0xf0 on SPI, 0x90 on MTP)"); +MODULE_PARM_DESC(haptic_softness, "softness of the press and release waveforms, 1-255 (0: 0xf0 on SPI, the firmware click's on MTP)"); static u8 haptic_deep_softness; module_param(haptic_deep_softness, byte, 0644); @@ -77,7 +77,7 @@ MODULE_PARM_DESC(haptic_deep_softness, "softness of the deep-click waveform, 1-2 static u8 haptic_strength; module_param(haptic_strength, byte, 0644); -MODULE_PARM_DESC(haptic_strength, "strength at 100% intensity for press and release, 1-255 (0: 0x28 on SPI, 0xff on MTP)"); +MODULE_PARM_DESC(haptic_strength, "strength at 100% intensity for press and release, 1-255 (0: 0x28 on SPI, the firmware click's on MTP)"); static u8 haptic_deep_strength; module_param(haptic_deep_strength, byte, 0644); @@ -148,16 +148,18 @@ module_param(haptic_deep_gap_ms, byte, 0644); MODULE_PARM_DESC(haptic_deep_gap_ms, "milliseconds between deep-click pulses, 0 to use haptic_pulse_gap_ms (default 15)"); /* - * Linux has no key for a force click, so which one to send is the user's - * choice; nothing is sent unless one is named. It is held down for as long as + * Linux has no key for a force click. KEY_INFO (XF86Info) stands for it: the + * desktop binds that keysym to what a force click does there (in GNOME Files, + * the preview of the item clicked), and nothing binds it by default, so the + * key does nothing where no one asks for it. It is held down for as long as * the deep stage lasts. The key comes from a separate input device: libinput * drives a touchpad with its own dispatcher, which drops every key that is not * a button, so a key on the trackpad's own device never reaches userspace. It * is read at probe because that device is set up there. */ -static u16 haptic_deep_keycode; +static u16 haptic_deep_keycode = KEY_INFO; module_param(haptic_deep_keycode, ushort, 0444); -MODULE_PARM_DESC(haptic_deep_keycode, "key code held during a deep click on a separate \"Force Click\" input device, 0 for none (default 0)"); +MODULE_PARM_DESC(haptic_deep_keycode, "key code held during a deep click on a separate \"Force Click\" input device, 0 for none (default KEY_INFO)"); static u8 haptic_pulse_gap_ms = 25; module_param(haptic_pulse_gap_ms, byte, 0644); @@ -273,9 +275,21 @@ struct effect_job { * @tp26_button: Button state of the last Trackpad26 frame. * @mtp_c1fe: Whether the MTP trackpad sends the J700 C1FE report layout. * @mtp_palms: Whether the controller's contact classes are trusted for palms - * on the standard MTP report (T6041, J616s). + * on the standard MTP report (T6041, J616s, J813, J815). * @mtp_palm_size: Whether a tool area alone marks an MTP contact as a palm. * @mtp_palm_ids: MTP contact IDs reported as palms until they lift. + * @mtp_palm_debounce: Whether two consecutive palm classes mark an MTP contact + * as a palm whatever its tool area (apple,palm-debounce). + * @mtp_palm_classed: MTP contact IDs the controller classed as palms in the + * previous report. + * @mtp_palm_large: Whether only hand classes with a palm-sized tool area, on + * two consecutive reports, or a tool area wider than any + * finger mark an MTP contact as a palm (apple,palm-tool-area). + * @mtp_palm_area: The two tool areas of apple,palm-tool-area: hand-class palm + * size, and the size wider than any finger. + * @mtp_states: Whether the standard MTP records' touch states are trusted: + * only contacts on the surface are reported, each in the slot + * of its firmware path ID (apple,touch-states). * @ntouches: Number of touches in most recent touch report. * @scroll_accel: Number of consecutive scroll motions. * @scroll_jiffies: Time of last scroll motion. @@ -294,6 +308,9 @@ struct effect_job { * @haptic_button_down: The host-derived button is pressed. * @haptic_deep_down: The host-derived click is in its deep stage. * @haptic_suspended: The transport is suspending or suspended; send nothing. + * @fw_click: The MTP actuator firmware's own press and release waveforms + * (apple_taptic_get_waveform()), read on first use and again after + * resume; @len 0 when the firmware has none. * @hdev: Pointer to the underlying HID device. * @work: Workqueue to handle initialization retry for quirky devices. * @work_held: @work was pending at suspend and must run again on resume. @@ -310,6 +327,11 @@ struct magicmouse_sc { bool mtp_palms; bool mtp_palm_size; DECLARE_BITMAP(mtp_palm_ids, U8_MAX + 1); + bool mtp_palm_debounce; + DECLARE_BITMAP(mtp_palm_classed, U8_MAX + 1); + bool mtp_palm_large; + int mtp_palm_area[2]; + bool mtp_states; int ntouches; int scroll_accel; @@ -340,6 +362,11 @@ struct magicmouse_sc { bool haptic_button_down; bool haptic_deep_down; bool haptic_suspended; + struct { + bool read; + u8 len; + u8 body[63]; + } fw_click[2]; struct hid_device *hdev; struct delayed_work work; @@ -1008,27 +1035,151 @@ static u8 magicmouse_mtp_contact_id(const struct tp_finger *f) return le16_to_cpu(f->unknown1) & 0xff; } +/* + * The high byte of a standard MTP record's first word is the contact's + * touch state. Decoded on a J815 (MTP firmware 6300.85.6) against macOS's + * own contact labels for the same frames (matched by path ID, state, finger + * and hand ID on every record): 1 start in range, + * 2 hover in range, 3 make touch, 4 touching, 5 break touch, 6 linger in + * range, 7 out of range. A finger approaching or leaving the pad (1, 2, 5, + * 6) still has a position and nonzero sizes, so the touch-size test alone + * reports it as a touch; only make touch and touching are on the surface. + * Any other state, including the zero-size records in state 0 that the J813 + * sends between a contact's out of range and the next start under its path + * ID, is off the surface. + */ +#define MAGICMOUSE_MTP_STATE_MAKE_TOUCH 3 +#define MAGICMOUSE_MTP_STATE_TOUCHING 4 +#define MAGICMOUSE_MTP_STATE_OUT_OF_RANGE 7 + +static u8 magicmouse_mtp_state(const struct tp_finger *f) +{ + return le16_to_cpu(f->unknown1) >> 8; +} + +static bool magicmouse_mtp_on_surface(const struct magicmouse_sc *msc, + const struct tp_finger *f) +{ + if (msc->mtp_states) { + switch (magicmouse_mtp_state(f)) { + case MAGICMOUSE_MTP_STATE_MAKE_TOUCH: + case MAGICMOUSE_MTP_STATE_TOUCHING: + break; + default: + return false; + } + } + return le16_to_int(f->touch_major) != 0; +} + +/* + * The J813 (MacBook Air 13" M5) controller classes contacts the same way, but + * most of its palms stay below the classed tool area above: recorded on a J813 + * in normal use and while typing, 221 of 370 palm-classed contacts never passed + * 1400, and fingers reached 1560. Its class flickers to a palm for single + * reports on a finger (4 of 868 finger contacts), so there a contact also + * counts as a palm once two consecutive reports class it as one. That caught + * all 370 palms by their second report, and one finger, classed a palm for its + * last reports while lifting. + * + * On the J815 (MacBook Air 15" M5) the controller's classes were checked + * against macOS's own labels on 607 contacts (10 minutes of typing with + * resting palms, pointing, scrolling, gestures; 34 contacts mostly classed + * 6, 7, 8 or 12, the hand classes). Two contacts that were mostly classed as + * fingers were marked as palms until they lifted by the J813 rule (966 + * finger reports lost): a finger-sized one in the bottom-left corner, + * flickering between classes 10 and 12, and one whose class flipped between + * 3 and 7 for up to 17 reports with a tool area up to 1606. Requiring a hand + * class with a tool area above 1200 on two consecutive reports marked no + * finger-classed contact and 33 of the 34 hand contacts. With 1400, palms + * resting while typing on Linux peaked at 1325-1400 and were missed (4 of 25); + * at 1100, one finger in the macOS session would be marked. + * + * Some resting palms are never classed as hands (two in one typing run on + * Linux, 28 and 38 mm wide, reported as fingers for 0.6 s). On macOS no + * finger or thumb contact passed a tool area of 2097, while 21 of the 34 + * hands passed 2200, 11 of them in their first report, so a contact wider + * than that on the surface is a palm at once, whatever its class. A finger + * coming into range can be wider: a thumb's start-in-range record had a tool + * area of 2428, and the mark would have stayed for its 35 touching reports. + * + * The two areas are the pad's own (apple,palm-tool-area = <1200 2200> on the + * J815); the hand classes are the controller's. + */ + +static bool magicmouse_mtp_hand_class(u8 class) +{ + return (class >= 6 && class <= 8) || class == 12; +} + +/* + * A hand on a pad with apple,palm-tool-area, for the host-derived click: a + * contact marked as a palm, or one in a hand class past the palm tool area + * already in its first report (the palm mark waits for a second one), or one + * on the surface wider than any finger. + */ +static bool magicmouse_mtp_hand(const struct magicmouse_sc *msc, + const struct tp_finger *f) +{ + int tool = le16_to_int(f->tool_major); + + /* The same tests as magicmouse_mtp_update_palms(), without the wait. */ + return test_bit(magicmouse_mtp_contact_id(f), msc->mtp_palm_ids) || + (tool > msc->mtp_palm_area[1] && magicmouse_mtp_on_surface(msc, f)) || + (magicmouse_mtp_hand_class(le16_to_cpu(f->unknown2) & 0xff) && + tool > msc->mtp_palm_area[0]); +} + static void magicmouse_mtp_update_palms(struct magicmouse_sc *msc, const u8 *records, int count) { DECLARE_BITMAP(palms, U8_MAX + 1); + DECLARE_BITMAP(classed, U8_MAX + 1); const struct tp_finger *f; + bool palm_class; int i, tool; u8 id, class; bitmap_zero(palms, U8_MAX + 1); + bitmap_zero(classed, U8_MAX + 1); for (i = 0; i < count; i++) { f = (const struct tp_finger *)(records + i * sizeof(*f)); id = magicmouse_mtp_contact_id(f); class = le16_to_cpu(f->unknown2) & 0xff; tool = le16_to_int(f->tool_major); + /* + * Out of range ends the contact; the firmware may reuse its + * path ID for a new contact in the very next report (40 times + * in 10 minutes on a J815), which must not inherit the palm. + */ + if (msc->mtp_states && + magicmouse_mtp_state(f) == MAGICMOUSE_MTP_STATE_OUT_OF_RANGE) + continue; + if (msc->mtp_palm_large) { + palm_class = magicmouse_mtp_hand_class(class) && + tool > msc->mtp_palm_area[0]; + if (palm_class) + __set_bit(id, classed); + if ((palm_class && test_bit(id, msc->mtp_palm_classed)) || + (tool > msc->mtp_palm_area[1] && + magicmouse_mtp_on_surface(msc, f)) || + test_bit(id, msc->mtp_palm_ids)) + __set_bit(id, palms); + continue; + } + palm_class = class >= MAGICMOUSE_MTP_PALM_CLASS_MIN; + if (palm_class) + __set_bit(id, classed); if ((msc->mtp_palm_size && tool > MAGICMOUSE_MTP_PALM_TOOL_MAJOR) || - (class >= MAGICMOUSE_MTP_PALM_CLASS_MIN && + (palm_class && tool > MAGICMOUSE_MTP_CLASSED_PALM_TOOL_MAJOR) || + (msc->mtp_palm_debounce && palm_class && + test_bit(id, msc->mtp_palm_classed)) || test_bit(id, msc->mtp_palm_ids)) __set_bit(id, palms); } bitmap_copy(msc->mtp_palm_ids, palms, U8_MAX + 1); + bitmap_copy(msc->mtp_palm_classed, classed, U8_MAX + 1); } static void report_finger_data(struct input_dev *input, int slot, @@ -1319,7 +1470,7 @@ static int magicmouse_raw_event_mtp(struct hid_device *hdev, n = 0; for (i = 0; i < tp_hdr->num_fingers; i++) { f = (struct tp_finger *)(data + hdr_sz + i * touch_sz); - if (!msc->mtp_c1fe && le16_to_int(f->touch_major) == 0) + if (!msc->mtp_c1fe && !magicmouse_mtp_on_surface(msc, f)) continue; hid_dbg(hdev, "ev x:%04x y:%04x\n", le16_to_int(f->abs_x), @@ -1330,11 +1481,27 @@ static int magicmouse_raw_event_mtp(struct hid_device *hdev, n++; } - input_mt_assign_slots(input, msc->tracking_ids, msc->pos, n, 0); + if (!msc->mtp_states) + input_mt_assign_slots(input, msc->tracking_ids, msc->pos, n, 0); for (i = 0; i < n; i++) { int idx = map_contacs[i]; + f = (struct tp_finger *)(data + hdr_sz + idx * touch_sz); + if (msc->mtp_states) { + /* + * The firmware tracks each contact under a path ID + * until it leaves the pad, so keep it in that ID's + * slot: matching by distance hands a slot over when one + * finger lifts as another lands in the same frame. Look + * the slot up just before reporting it, so contacts + * landing in the same frame get different free slots. + */ + msc->tracking_ids[i] = + input_mt_get_slot_by_key(input, magicmouse_mtp_contact_id(f)); + if (msc->tracking_ids[i] < 0) + continue; + } if (msc->mtp_c1fe) { report_c1fe_finger_data(input, msc->tracking_ids[i], &msc->pos[i]); } else { @@ -1345,7 +1512,15 @@ static int magicmouse_raw_event_mtp(struct hid_device *hdev, tool = MT_TOOL_PALM; report_finger_data(input, msc->tracking_ids[i], &msc->pos[i], f, tool); - pressure += le16_to_int(f->pressure); + /* + * J815: a resting palm presses hard enough to reach the + * click threshold on its own. As on macOS, a resting + * hand neither clicks nor deepens a click, while a + * finger of the other hand still does: the hand's own + * force never counts. + */ + if (!(msc->mtp_palm_large && magicmouse_mtp_hand(msc, f))) + pressure += le16_to_int(f->pressure); } } @@ -1735,7 +1910,7 @@ static int magicmouse_setup_input_mtp(struct input_dev *input, /* * A palm's tool area on the T6041 and J616s trackpads exceeds * 5000 once scaled, so allow the full range of the record's - * 16-bit fields there. + * 16-bit fields on every trackpad whose palms are classed. */ int area_max = msc->mtp_palms ? 2 * S16_MAX : 5000; @@ -1762,7 +1937,7 @@ static int magicmouse_setup_input_mtp(struct input_dev *input, J314_TP_MAX_FINGER_ORIENTATION, 0, 0); } - /* The T6041, J616s and Trackpad26 controllers classify palms. */ + /* The T6041, J616s, J813, J815 and Trackpad26 controllers classify palms. */ if (msc->mtp_palms || msc->mtp_tp26) input_set_abs_params(input, ABS_MT_TOOL_TYPE, 0, MT_TOOL_MAX, 0, 0); @@ -1941,8 +2116,12 @@ static int magicmouse_switch_mode(struct input_dev *trackpad_idev, int mode) return apple_taptic_switch_modes(actuator, mode); } -static u8 magicmouse_haptic_softness(struct hid_device *hdev, bool deep); -static u8 magicmouse_haptic_strength(struct hid_device *hdev, bool deep); +static void magicmouse_haptic_waveform(struct magicmouse_sc *msc, + struct hid_device *actuator, u16 usage, + u8 *strength, u8 *softness); +static int magicmouse_taptic_play(struct magicmouse_sc *msc, + struct hid_device *actuator, u16 usage, + u8 strength, u8 softness); static void magicmouse_haptic_release_mode(struct magicmouse_sc *msc); static void magicmouse_haptic_release_mode_locked(struct magicmouse_sc *msc); @@ -1988,13 +2167,13 @@ static void magicmouse_haptic_pulses(struct magicmouse_sc *msc, u16 usage, hid_info(msc->hdev, "host-driven click feedback active\n"); } - strength = magicmouse_haptic_strength(msc->hdev, deep); - softness = magicmouse_haptic_softness(msc->hdev, deep); + magicmouse_haptic_waveform(msc, actuator, usage, &strength, &softness); gap = (deep && haptic_deep_gap_ms) ? haptic_deep_gap_ms : haptic_pulse_gap_ms; for (i = 0; i < pulses; i++) { - ret = apple_taptic_send(actuator, usage, strength, softness); + ret = magicmouse_taptic_play(msc, actuator, usage, strength, + softness); if (ret) { hid_warn(msc->hdev, "click waveform failed (%d); returning click feedback to the firmware\n", @@ -2257,6 +2436,8 @@ static void magicmouse_haptic_resume(struct magicmouse_sc *msc) } msc->haptic_suspended = false; } + /* The firmware may have been restarted with other strengths. */ + memset(msc->fw_click, 0, sizeof(msc->fw_click)); if (haptic_press || magicmouse_haptic_effects_loaded(msc)) mode = HID_HAPTIC_MODE_HOST; @@ -2452,34 +2633,96 @@ static void magicmouse_battery_timer_tick(struct timer_list *t) } #if IS_ENABLED(CONFIG_HID_APPLE_MTP_HAPTIC) -static bool magicmouse_effect_is_deep(const struct ff_effect *effect) +/* + * The firmware's own click waveform for a press or release on an MTP + * actuator, or NULL. A host click plays the same waveform: macOS leaves the + * actuator with these strengths at its default (Medium) click setting, and + * the shape differs between machines. Read once, and again after resume. + */ +static const u8 *magicmouse_fw_click(struct magicmouse_sc *msc, + struct hid_device *actuator, u16 usage, + u8 *len) { - return effect->u.haptic.hid_usage == - (APPLE_HP_WAVEFORMDEEPCLICK & HID_USAGE); + unsigned int i; + int ret; + + if (msc->hdev->bus == BUS_SPI || !actuator || + (usage != (HID_HP_WAVEFORMPRESS & HID_USAGE) && + usage != (HID_HP_WAVEFORMRELEASE & HID_USAGE))) + return NULL; + + i = usage == (HID_HP_WAVEFORMRELEASE & HID_USAGE); + if (!msc->fw_click[i].read) { + msc->fw_click[i].read = true; + ret = apple_taptic_get_waveform(actuator, usage, + msc->fw_click[i].body, + sizeof(msc->fw_click[i].body)); + msc->fw_click[i].len = ret > 0 ? ret : 0; + if (ret > 0) + hid_dbg(msc->hdev, + "%s waveform from the firmware: strength 0x%02x softness 0x%02x, %d bytes\n", + i ? "release" : "press", msc->fw_click[i].body[1], + msc->fw_click[i].body[2], ret); + else + hid_dbg(msc->hdev, "no firmware %s waveform (%d)\n", + i ? "release" : "press", ret); + } + *len = msc->fw_click[i].len; + return *len ? msc->fw_click[i].body : NULL; } -static u8 magicmouse_haptic_softness(struct hid_device *hdev, bool deep) +/* + * The strength and softness a host-played waveform uses. A module parameter + * wins; otherwise an MTP press or release takes the firmware click's own + * values (magicmouse_fw_click()). A full-scale host click felt firmer than + * macOS on every MTP Mac. The deep click has no firmware waveform and stays + * at full scale, as does a press or release the firmware does not report. + * The SPI actuator in a J313 needs a much softer, weaker waveform; its + * numbers were judged by feel there. + */ +static void magicmouse_haptic_waveform(struct magicmouse_sc *msc, + struct hid_device *actuator, u16 usage, + u8 *strength, u8 *softness) { - u8 configured = deep ? haptic_deep_softness : haptic_softness; + bool deep = usage == (APPLE_HP_WAVEFORMDEEPCLICK & HID_USAGE); + u8 set_strength = deep ? haptic_deep_strength : haptic_strength; + u8 set_softness = deep ? haptic_deep_softness : haptic_softness; + bool spi = msc->hdev->bus == BUS_SPI; + const u8 *fw; + u8 len; - if (configured) - return configured; - if (hdev->bus != BUS_SPI) - return 0x90; + *strength = spi && !deep ? 0x28 : 0xff; + *softness = spi ? (deep ? 0xd0 : 0xf0) : 0x90; - return deep ? 0xd0 : 0xf0; + fw = magicmouse_fw_click(msc, actuator, usage, &len); + if (fw) { + *strength = fw[1]; + *softness = fw[2]; + } + + if (set_strength) + *strength = set_strength; + if (set_softness) + *softness = set_softness; } -static u8 magicmouse_haptic_strength(struct hid_device *hdev, bool deep) +/* Play @usage: the firmware's own waveform where it has one, else ours. */ +static int magicmouse_taptic_play(struct magicmouse_sc *msc, + struct hid_device *actuator, u16 usage, + u8 strength, u8 softness) { - u8 configured = deep ? haptic_deep_strength : haptic_strength; + u8 body[sizeof(msc->fw_click[0].body)]; + const u8 *fw; + u8 len; - if (configured) - return configured; - if (hdev->bus != BUS_SPI) - return 0xff; + fw = magicmouse_fw_click(msc, actuator, usage, &len); + if (!fw) + return apple_taptic_send(actuator, usage, strength, softness); - return deep ? 0xff : 0x28; + memcpy(body, fw, len); + body[1] = strength; + body[2] = softness; + return apple_taptic_send_waveform(actuator, body, len); } static int apple_upload_effects(struct input_dev *trackpad_idev, @@ -2492,7 +2735,6 @@ static int apple_upload_effects(struct input_dev *trackpad_idev, struct effect_job *job = &msc->haptic_effects[effect->id]; unsigned long flags; u8 strength, softness; - bool deep; int ret; switch (effect->u.haptic.hid_usage) { @@ -2511,10 +2753,9 @@ static int apple_upload_effects(struct input_dev *trackpad_idev, if (!actuator) return -ENODEV; - deep = magicmouse_effect_is_deep(effect); - strength = min_t(u16, 100, effect->u.haptic.intensity) * - magicmouse_haptic_strength(trackpad_hdev, deep) / 100; - softness = magicmouse_haptic_softness(trackpad_hdev, deep); + magicmouse_haptic_waveform(msc, actuator, effect->u.haptic.hid_usage, + &strength, &softness); + strength = min_t(u16, 100, effect->u.haptic.intensity) * strength / 100; /* The actuator may have been rebound or reset since the last upload. */ ret = magicmouse_switch_mode(trackpad_idev, HID_HAPTIC_MODE_HOST); @@ -2565,7 +2806,7 @@ static void haptic_playback_worker(struct work_struct *ws) } WRITE_ONCE(job->msc->haptics->mode, HID_HAPTIC_MODE_HOST); } - if (apple_taptic_send(actuator, type, strength, softness)) + if (magicmouse_taptic_play(job->msc, actuator, type, strength, softness)) hid_warn(actuator, "cannot play the haptic effect\n"); } @@ -2728,9 +2969,6 @@ static int apple_taptic_init_mtp(struct magicmouse_sc *msc, INIT_WORK(&msc->haptic_deep_release_work, magicmouse_deep_release_worker); - if (haptic_deep_keycode) - magicmouse_setup_force_input(msc); - /* FF_HAPTIC has to be in ffbit before the FF device is created. */ input_set_capability(msc->input, EV_FF, FF_HAPTIC); @@ -2750,6 +2988,13 @@ static int apple_taptic_init_mtp(struct magicmouse_sc *msc, return ret; } + /* + * Only now: if the FF device could not be created there are no + * haptics, and no Force Click device must be left registered. + */ + if (haptic_deep_keycode) + magicmouse_setup_force_input(msc); + ff = msc->input->ff; ff->private = haptic_dev; ff->upload = apple_upload_effects; @@ -2871,20 +3116,52 @@ static int magicmouse_probe(struct hid_device *hdev, // conflicts with the report ID. if (id->bus == BUS_HOST) { struct device_node *np; + u32 palm_area[2]; /* The J700 trackpad sends a different report layout. */ np = of_get_child_by_name(dev_of_node(hdev->dev.parent), "multi-touch"); msc->mtp_c1fe = of_device_is_compatible(np, "apple,j700-multitouch"); msc->mtp_palm_size = !msc->mtp_c1fe && of_machine_is_compatible("apple,t6041"); + /* + * The J813 and J815 controllers class contacts the same way; + * the trackpad node says which palm rule its pad takes: two + * consecutive palm classes (J813), or hand classes with the + * pad's own tool areas (J815, checked against macOS's labels). + */ + msc->mtp_palm_debounce = !msc->mtp_c1fe && + of_property_read_bool(np, "apple,palm-debounce"); + msc->mtp_palm_large = !msc->mtp_c1fe && + !of_property_read_u32_array(np, "apple,palm-tool-area", + palm_area, 2); + /* + * The record's tool area is a signed 16-bit field, compared + * as an int: a larger value could never be passed. + */ + if (msc->mtp_palm_large && + (palm_area[0] >= palm_area[1] || palm_area[1] > S16_MAX)) { + hid_warn(hdev, "apple,palm-tool-area %u %u: the first must be below the second, and both at most %d, rule off\n", + palm_area[0], palm_area[1], S16_MAX); + msc->mtp_palm_large = false; + } else if (msc->mtp_palm_large) { + msc->mtp_palm_area[0] = palm_area[0]; + msc->mtp_palm_area[1] = palm_area[1]; + } /* * The J616s controller classes contacts the same way, but its * fingers reach a tool area of 2475, so only the class marks its * palms there. */ msc->mtp_palms = msc->mtp_palm_size || + msc->mtp_palm_debounce || msc->mtp_palm_large || (!msc->mtp_c1fe && of_machine_is_compatible("apple,j616s")); + /* + * The record's touch state and path ID (decoded on a J815 + * against macOS) are a property of the trackpad's firmware. + */ + msc->mtp_states = !msc->mtp_c1fe && + of_property_read_bool(np, "apple,touch-states"); of_node_put(np); /* @@ -3180,9 +3457,28 @@ static const struct hid_device_id magic_mice[] = { }; MODULE_DEVICE_TABLE(hid, magic_mice); +/* + * Every interface of an internal SPI or DockChannel controller carries the + * controller's IDs. Only the trackpad is ours; leave the others to their own + * driver or to hid-generic. + */ +static bool magicmouse_match(struct hid_device *hdev, bool ignore_special_driver) +{ + if (ignore_special_driver || + (hdev->quirks & HID_QUIRK_IGNORE_SPECIAL_DRIVER)) + return false; + + if ((hdev->bus == BUS_SPI || hdev->bus == BUS_HOST) && + hdev->vendor == SPI_VENDOR_ID_APPLE) + return hdev->type == HID_TYPE_SPI_MOUSE; + + return true; +} + static struct hid_driver magicmouse_driver = { .name = "magicmouse", .id_table = magic_mice, + .match = magicmouse_match, .probe = magicmouse_probe, .remove = magicmouse_remove, .report_fixup = magicmouse_report_fixup, diff --git a/drivers/hid/spi-hid/spi-hid-apple-core.c b/drivers/hid/spi-hid/spi-hid-apple-core.c index d2b62f57cd8c0b..1cfdbc7eae48a5 100644 --- a/drivers/hid/spi-hid/spi-hid-apple-core.c +++ b/drivers/hid/spi-hid/spi-hid-apple-core.c @@ -105,6 +105,8 @@ struct spihid_apple { wait_queue_head_t wait; struct mutex tx_lock; //< protects against concurrent SPI writes struct mutex get_report_lock; /* serializes synchronous GET_REPORTs */ + /* GETs a retry recovered after a bad status; get_report_lock */ + unsigned int get_report_recovered; spinlock_t reply_lock; /* protects reply state shared with the IRQ thread */ struct spi_message rx_msg; @@ -440,7 +442,7 @@ static int spihid_get_report(struct spihid_apple *spihid, { unsigned long flags; int attempt, ret; - unsigned int rejected = 0; + unsigned int rejected = 0, recovered = 0; bool bad_status, timed_out; ret = mutex_lock_interruptible(&spihid->get_report_lock); @@ -471,11 +473,16 @@ static int spihid_get_report(struct spihid_apple *spihid, /* * RX CRC validation can discard a reply even after a valid - * write status. A valid GET can also receive a bad status, - * including the first dimensions query after enabling MT. - * Retry either with a fresh ID, sharing the attempt limit. - * Keep SPI errors (even -EPROTO) and signals distinct from - * status mismatches so they are never replayed. + * write status. A valid GET can also receive a bad status: + * the M1 Pro trackpad answers 9c 17 e5 f8 to the first + * dimensions query after the multitouch SET on about one boot + * in four. That is the status a report the device does not + * have gets, so the mode switch may complete only after the + * SET is acknowledged; nothing here waits for it. The cause is + * not established (aurora-silicon/linux#2316), so retry either + * case with a fresh ID, sharing the attempt limit, and count + * the recoveries. Keep SPI errors (even -EPROTO) and signals + * distinct from status mismatches so they are never replayed. */ if (!timed_out && !bad_status) break; @@ -483,6 +490,8 @@ static int spihid_get_report(struct spihid_apple *spihid, rejected++; } + if (ret >= 0 && rejected) + recovered = ++spihid->get_report_recovered; mutex_unlock(&spihid->get_report_lock); if (ret < 0 && rejected) dev_err(&spihid->spidev->dev, @@ -493,8 +502,8 @@ static int spihid_get_report(struct spihid_apple *spihid, "get report %02x failed: %d\n", reportnum, ret); else if (rejected) dev_info_ratelimited(&spihid->spidev->dev, - "get report %02x recovered by retry (bad status: %u)\n", - reportnum, rejected); + "get report %02x recovered by retry (bad status: %u; %u GETs recovered since probe)\n", + reportnum, rejected, recovered); return ret; } @@ -776,7 +785,8 @@ static bool spihid_process_iface_hid_report_desc(struct spihid_apple *spihid, { struct spihid_interface *iface = spihid_get_iface(spihid, num); - if (!iface) + /* Only interfaces registered as HID devices have a descriptor buffer. */ + if (!iface || !iface->hid_desc) return false; if (iface->hid_desc_len == 0) { @@ -917,7 +927,11 @@ static void spihid_assemble_message(struct spihid_apple *spihid, remain = le16_to_cpu(pkt->remain); offset = le16_to_cpu(pkt->offset); - if (offset + length + remain > U16_MAX) { + /* The complete message has to fit the reassembly buffer. */ + if (offset + length + remain > SPIHID_MAX_INPUT_REPORT_SIZE) { + dev_warn_ratelimited(dev, + "dropping oversized report off:%zu len:%zu remain:%zu\n", + offset, length, remain); return; } diff --git a/drivers/hid/spi-hid/spi-hid-apple-test.c b/drivers/hid/spi-hid/spi-hid-apple-test.c index 2d9e394559aec5..d9545fe908f125 100644 --- a/drivers/hid/spi-hid/spi-hid-apple-test.c +++ b/drivers/hid/spi-hid/spi-hid-apple-test.c @@ -319,6 +319,86 @@ static void spihid_test_no_set_retry(struct kunit *test) KUNIT_EXPECT_EQ(test, ctx->writes, 1); } +static void spihid_test_fragment(struct spihid_apple *spihid, u16 offset, + u16 remain) +{ + struct spihid_transfer_packet *pkt = (void *)spihid->rx_buf; + + memset(pkt, 0, sizeof(*pkt)); + pkt->flags = SPIHID_READ_PACKET; + pkt->device = SPIHID_DEVICE_ID_TP; + pkt->offset = cpu_to_le16(offset); + pkt->remain = cpu_to_le16(remain); + pkt->length = cpu_to_le16(sizeof(pkt->data)); + memset(pkt->data, 0x5a, sizeof(pkt->data)); + pkt->crc16 = cpu_to_le16(crc16(0, (u8 *)pkt, + offsetof(struct spihid_transfer_packet, crc16))); + spihid_process_read(spihid); +} + +/* A fragmented message longer than the reassembly buffer is dropped. */ +static void spihid_test_oversized_message(struct kunit *test) +{ + struct spihid_test *ctx = test->priv; + struct spihid_apple *spihid = ctx->spihid; + const size_t frag = sizeof(((struct spihid_transfer_packet *)0)->data); + const size_t total = SPIHID_MAX_INPUT_REPORT_SIZE + 2 * frag; + const size_t guard = 2 * frag; + size_t offset, i; + u8 *buf; + + /* Room past the real buffer size, so an overrun is visible. */ + buf = kunit_kzalloc(test, SPIHID_MAX_INPUT_REPORT_SIZE + guard, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf + SPIHID_MAX_INPUT_REPORT_SIZE, 0xc3, guard); + spihid->report.buf = buf; + + /* Every fragment but the last, so the message never completes. */ + for (offset = 0; offset + frag < total; offset += frag) { + spihid_test_fragment(spihid, offset, total - offset - frag); + KUNIT_EXPECT_LE(test, spihid->report.length, + SPIHID_MAX_INPUT_REPORT_SIZE); + KUNIT_EXPECT_LE(test, spihid->report.offset, + SPIHID_MAX_INPUT_REPORT_SIZE); + } + + for (i = 0; i < guard; i++) + if (buf[SPIHID_MAX_INPUT_REPORT_SIZE + i] != 0xc3) + break; + KUNIT_EXPECT_EQ(test, i, guard); +} + +/* A message that fills the buffer exactly is still reassembled. */ +static void spihid_test_max_message(struct kunit *test) +{ + struct spihid_test *ctx = test->priv; + struct spihid_apple *spihid = ctx->spihid; + const size_t frag = sizeof(((struct spihid_transfer_packet *)0)->data); + const size_t total = SPIHID_MAX_INPUT_REPORT_SIZE; + size_t offset; + + for (offset = 0; offset + frag < total; offset += frag) { + spihid_test_fragment(spihid, offset, total - offset - frag); + KUNIT_EXPECT_EQ(test, spihid->report.offset, offset + frag); + KUNIT_EXPECT_EQ(test, spihid->report.length, total); + } +} + +/* The management interface has no descriptor buffer. */ +static void spihid_test_mngt_report_desc(struct kunit *test) +{ + struct spihid_test *ctx = test->priv; + u8 desc[16] = { 0x05, 0x01 }; + + KUNIT_EXPECT_NULL(test, ctx->spihid->mngt.hid_desc); + KUNIT_EXPECT_FALSE(test, + spihid_process_iface_hid_report_desc(ctx->spihid, + SPIHID_DEVICE_ID_MNGT, + desc, sizeof(desc))); + KUNIT_EXPECT_EQ(test, ctx->spihid->mngt.hid_desc_len, 0); +} + static struct kunit_case spihid_test_cases[] = { KUNIT_CASE(spihid_test_bad_status), KUNIT_CASE(spihid_test_later_get_bad_status), @@ -329,6 +409,9 @@ static struct kunit_case spihid_test_cases[] = { KUNIT_CASE(spihid_test_mixed_retry_limit), KUNIT_CASE(spihid_test_spi_error_no_retry), KUNIT_CASE(spihid_test_no_set_retry), + KUNIT_CASE(spihid_test_oversized_message), + KUNIT_CASE(spihid_test_max_message), + KUNIT_CASE(spihid_test_mngt_report_desc), {} }; diff --git a/drivers/hwmon/Kconfig b/drivers/hwmon/Kconfig index 7a2924b47839ce..7c8d62987f1d36 100644 --- a/drivers/hwmon/Kconfig +++ b/drivers/hwmon/Kconfig @@ -1261,6 +1261,7 @@ config SENSORS_LTQ_CPUTEMP config SENSORS_MACSMC_HWMON tristate "Apple SMC (Apple Silicon)" depends on MFD_MACSMC && OF + depends on ARM_APPLE_SOC_CPUFREQ || !ARM_APPLE_SOC_CPUFREQ help This driver enables hwmon support for current, power, temperature, and voltage sensors, as well as fan speed reporting and control diff --git a/drivers/hwmon/macsmc-hwmon-test.c b/drivers/hwmon/macsmc-hwmon-test.c index d2f1333f0571e8..93a6a9c0195d77 100644 --- a/drivers/hwmon/macsmc-hwmon-test.c +++ b/drivers/hwmon/macsmc-hwmon-test.c @@ -210,6 +210,9 @@ struct macsmc_fan_test { int manual_busy[2]; int target_writes; smc_key fail_key; + smc_key fail_read_key; + bool relock_stuck; + u8 relock_mode; }; static int fan_test_index(smc_key key) @@ -223,6 +226,9 @@ static int fan_test_read(struct apple_smc *smc, smc_key key, void *buf, size_t s u32 value; int i = fan_test_index(key); + if (key == t->fail_read_key) + return -EIO; + switch (key & 0xff00ffff) { case __SMC_KEY('F', 0, 'M', 'd'): t->mode_reads++; @@ -262,8 +268,10 @@ static int fan_test_write(struct apple_smc *smc, smc_key key, const void *buf, s for (i = 0; i < ARRAY_SIZE(t->mode); i++) { if (value && t->mode[i] == MACSMC_FAN_MODE_SYSTEM) t->mode[i] = MACSMC_FAN_MODE_AUTO; - else if (!value) + else if (!value && !t->relock_stuck) t->mode[i] = MACSMC_FAN_MODE_SYSTEM; + else if (!value) + t->mode[i] = t->relock_mode; } return size; } @@ -507,6 +515,127 @@ static void macsmc_fan_test_unlock_fails(struct kunit *test) KUNIT_EXPECT_EQ(test, t->refused, 0); } +static void fan_test_enable_controllable(struct macsmc_fan_test *t) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(t->fans); i++) + t->fans[i].attrs = HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX; +} + +/* A live AUTO write failure keeps ownership so the next release retries. */ +static void macsmc_fan_test_auto_write_fails(struct kunit *test) +{ + struct macsmc_fan_test *t = test->priv; + struct device dev = {}; + + dev_set_drvdata(&dev, &t->hwmon); + fan_test_enable_controllable(t); + + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + t->fail_key = SMC_KEY(F0Md); + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -EIO); + KUNIT_EXPECT_TRUE(test, t->fans[0].manual); + KUNIT_EXPECT_TRUE(test, t->fans[0].kernel); + KUNIT_EXPECT_FALSE(test, t->fans[1].manual); + KUNIT_EXPECT_FALSE(test, t->fans[1].kernel); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 1); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + + t->fail_key = 0; + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), 0); + fan_test_released(test, t); + + /* At suspend, failed AUTO writes still yield to the global relock. */ + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + t->fail_key = SMC_KEY(F0Md); + KUNIT_ASSERT_EQ(test, macsmc_hwmon_suspend(&dev), 0); + fan_test_released(test, t); + KUNIT_ASSERT_EQ(test, macsmc_hwmon_resume(&dev), 0); +} + +/* A failed relock write leaves unlocked set so the next release retries. */ +static void macsmc_fan_test_relock_write_fails(struct kunit *test) +{ + struct macsmc_fan_test *t = test->priv; + struct device dev = {}; + + dev_set_drvdata(&dev, &t->hwmon); + fan_test_enable_controllable(t); + + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + t->fail_key = SMC_KEY(Ftst); + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -EIO); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 0); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -EIO); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + + t->fail_key = 0; + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), 0); + fan_test_released(test, t); +} + +/* Relock stays pending across readback errors so repeated releases recheck. */ +static void macsmc_fan_test_relock_readback_fails(struct kunit *test) +{ + struct macsmc_fan_test *t = test->priv; + struct device dev = {}; + int ftst_writes; + + dev_set_drvdata(&dev, &t->hwmon); + fan_test_enable_controllable(t); + + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + t->fail_read_key = SMC_KEY(F1Md); + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -EIO); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 0); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + + /* Repeated release still fails and retries relock once while readback fails. */ + ftst_writes = t->ftst_writes; + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -EIO); + KUNIT_EXPECT_EQ(test, t->ftst_writes, ftst_writes + 1); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + + t->fail_read_key = 0; + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), 0); + fan_test_released(test, t); + + /* A fresh manual request after a readback failure re-unlocks Ftst. */ + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + t->fail_read_key = SMC_KEY(F1Md); + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -EIO); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + t->fail_read_key = 0; + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 2); + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), 0); + fan_test_released(test, t); +} + +/* A relock readback timeout keeps unlocked set until a later release confirms system mode. */ +static void macsmc_fan_test_relock_timeout(struct kunit *test) +{ + struct macsmc_fan_test *t = test->priv; + struct device dev = {}; + + dev_set_drvdata(&dev, &t->hwmon); + fan_test_enable_controllable(t); + + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + t->relock_stuck = true; + t->relock_mode = MACSMC_FAN_MODE_AUTO; + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 0); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + + t->relock_stuck = false; + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), 0); + fan_test_released(test, t); +} + /* A stopped fan may leave mode 3 before the manual-mode write is ready. */ static void macsmc_fan_test_stopped_manual_busy(struct kunit *test) { @@ -557,6 +686,65 @@ static void macsmc_fan_test_spinning(struct kunit *test) KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 0); } +/* Manual-only kernel fan request touches only apple,fan-manual-control fans. */ +static void macsmc_fan_test_manual_only_request(struct kunit *test) +{ + struct macsmc_fan_test *t = test->priv; + struct macsmc_hwmon_fan_assist policy = {}; + struct device dev = {}; + + dev_set_drvdata(&dev, &t->hwmon); + t->fans[0].attrs = HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX; + t->fans[1].attrs = HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX; + t->fans[0].manual_control = true; + t->fans[1].manual_control = false; + t->hwmon.fan_assist.trigger_mc = 98000; + t->hwmon.fan_assist.release_mc = 82000; + t->hwmon.fan_assist.hold_ms = 30000; + t->hwmon.fan_assist_valid = true; + + KUNIT_ASSERT_EQ(test, macsmc_hwmon_hotspot_assist_policy(&dev, &policy), 0); + KUNIT_EXPECT_EQ(test, policy.trigger_mc, 98000); + KUNIT_EXPECT_EQ(test, policy.release_mc, 82000); + KUNIT_EXPECT_EQ(test, policy.hold_ms, 30000U); + + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request_manual(&dev, 1000, 0), 5777); + KUNIT_EXPECT_EQ(test, t->mode[0], MACSMC_FAN_MODE_MANUAL); + KUNIT_EXPECT_EQ(test, t->target[0], FAN_TEST_F5777); + KUNIT_EXPECT_EQ(test, t->mode[1], MACSMC_FAN_MODE_AUTO); + KUNIT_EXPECT_EQ(test, t->target[1], 0); + KUNIT_EXPECT_TRUE(test, t->fans[0].kernel); + KUNIT_EXPECT_FALSE(test, t->fans[1].kernel); + KUNIT_EXPECT_FALSE(test, t->fans[1].manual); + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request_manual(&dev, 0, 0), 0); + fan_test_released(test, t); + + /* Manual-only release leaves a non-manual fan held by the unrestricted API. */ + KUNIT_ASSERT_GT(test, macsmc_hwmon_fans_request(&dev, 500, 0), 0); + KUNIT_EXPECT_TRUE(test, t->fans[0].kernel); + KUNIT_EXPECT_TRUE(test, t->fans[1].kernel); + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request_manual(&dev, 0, 0), 0); + KUNIT_EXPECT_FALSE(test, t->fans[0].kernel); + KUNIT_EXPECT_FALSE(test, t->fans[0].manual); + KUNIT_EXPECT_TRUE(test, t->fans[1].kernel); + KUNIT_EXPECT_TRUE(test, t->fans[1].manual); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 1); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), 0); + fan_test_released(test, t); + + /* Without any manual-control fan, policy and boost return -ENODEV. */ + t->fans[0].manual_control = false; + KUNIT_EXPECT_EQ(test, macsmc_hwmon_hotspot_assist_policy(&dev, NULL), -ENODEV); + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request_manual(&dev, 1000, 0), -ENODEV); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 0); + + /* Without DT-supplied trip thresholds, policy returns -ENODEV. */ + t->fans[0].manual_control = true; + t->hwmon.fan_assist_valid = false; + KUNIT_EXPECT_EQ(test, macsmc_hwmon_hotspot_assist_policy(&dev, NULL), -ENODEV); +} + static struct kunit_case macsmc_fan_test_cases[] = { KUNIT_CASE(macsmc_fan_test_stopped_manual_busy), KUNIT_CASE(macsmc_fan_test_manual_busy_timeout), @@ -572,6 +760,11 @@ static struct kunit_case macsmc_fan_test_cases[] = { KUNIT_CASE(macsmc_fan_test_untouched), KUNIT_CASE(macsmc_fan_test_suspend_manual), KUNIT_CASE(macsmc_fan_test_unlock_fails), + KUNIT_CASE(macsmc_fan_test_auto_write_fails), + KUNIT_CASE(macsmc_fan_test_relock_write_fails), + KUNIT_CASE(macsmc_fan_test_relock_readback_fails), + KUNIT_CASE(macsmc_fan_test_relock_timeout), + KUNIT_CASE(macsmc_fan_test_manual_only_request), {} }; diff --git a/drivers/hwmon/macsmc-hwmon.c b/drivers/hwmon/macsmc-hwmon.c index 50591b3d1d55b2..e577f9f018499d 100644 --- a/drivers/hwmon/macsmc-hwmon.c +++ b/drivers/hwmon/macsmc-hwmon.c @@ -21,6 +21,8 @@ */ #include +#include +#include #include #include #include @@ -33,9 +35,11 @@ #include #include #include +#include #include #include #include +#include #define MAX_LABEL_LENGTH 32 @@ -91,6 +95,9 @@ struct macsmc_hwmon_sensors { #define MACSMC_FAN_MODE_TIMEOUT_MS 10000 #define MACSMC_FAN_MODE_POLL_MS 100 +#define MACSMC_DIE_MIN_MC -40000 +#define MACSMC_DIE_MAX_MC 150000 + struct macsmc_hwmon_fans { struct hwmon_channel_info channel_info; struct macsmc_hwmon_fan *fans; @@ -126,6 +133,18 @@ struct macsmc_hwmon { /* SoC die temperature keys listed, and the ones present. */ u32 die_listed; u32 die_count; + /* DT-supplied hotspot fan-assistance trip on macsmc_soc_die. */ + struct macsmc_hwmon_fan_assist fan_assist; + bool fan_assist_valid; + /* DT-supplied passive and hot trips on macsmc_soc_die. */ + int die_passive_mc; + int die_hot_mc; + bool die_limits_valid; + /* CPU clusters (policy->cpu) whose higher states these zones own */ + struct delayed_work cpu_owner_work; + cpumask_t cpu_owned; + cpumask_t cpu_refused; + unsigned int cpu_owner_tries; }; static ssize_t thermal_pressure_level_show(struct device *dev, @@ -403,7 +422,6 @@ static int macsmc_hwmon_fans_relock(struct macsmc_hwmon *hwmon) dev_err(hwmon->dev, "cannot hand the fans back to the SMC (%d)\n", ret); return ret; } - hwmon->fan.unlocked = false; timeout = jiffies + msecs_to_jiffies(MACSMC_FAN_MODE_TIMEOUT_MS); for (i = 0; i < hwmon->fan.count; i++) { @@ -426,30 +444,44 @@ static int macsmc_hwmon_fans_relock(struct macsmc_hwmon *hwmon) } } + hwmon->fan.unlocked = false; return 0; } -/* Return a fan to firmware control. Called with the fan lock held. */ -static int macsmc_hwmon_fan_auto(struct macsmc_hwmon *hwmon, - struct macsmc_hwmon_fan *fan) +static int macsmc_hwmon_fan_set_auto(struct macsmc_hwmon *hwmon, + struct macsmc_hwmon_fan *fan) { - int ret, relock; + int ret; if (!fan->manual) return 0; ret = macsmc_hwmon_write_key(hwmon->smc, &fan->mode, MACSMC_FAN_MODE_AUTO); + /* + * At shutdown or suspend the final unlock-key relock hands all + * fans back, even if one fan refuses its individual AUTO write. + */ + if (ret < 0 && !(hwmon->fan.stopped && hwmon->fan.unlocked)) + return ret; fan->manual = false; fan->kernel = false; hwmon->fan.manual--; + return 0; +} - if (hwmon->fan.unlocked && !hwmon->fan.manual) { - relock = macsmc_hwmon_fans_relock(hwmon); - if (relock) - return relock; - } +/* Return a fan to firmware control. Called with the fan lock held. */ +static int macsmc_hwmon_fan_auto(struct macsmc_hwmon *hwmon, + struct macsmc_hwmon_fan *fan) +{ + int ret = macsmc_hwmon_fan_set_auto(hwmon, fan); - return ret < 0 ? ret : 0; + if (ret) + return ret; + + if (hwmon->fan.unlocked && !hwmon->fan.manual) + return macsmc_hwmon_fans_relock(hwmon); + + return 0; } /* @@ -480,7 +512,11 @@ static int macsmc_hwmon_fan_manual(struct macsmc_hwmon *hwmon, if (!hwmon->fan.unlock_key) return -EOPNOTSUPP; - if (!hwmon->fan.unlocked) { + /* + * Re-unlock when no fan is manual so a prior relock that wrote + * 0 but failed readback does not wait on a locked SMC. + */ + if (!hwmon->fan.unlocked || !hwmon->fan.manual) { ret = apple_smc_write_u8(hwmon->smc, hwmon->fan.unlock_key, 1); if (ret < 0) { /* The key may have been set anyway; clear it. */ @@ -576,27 +612,18 @@ static int macsmc_hwmon_set_fan(struct macsmc_hwmon *hwmon, int channel, long va return ret; } -/** - * macsmc_hwmon_fans_request() - set the fans for a kernel thermal policy - * @dev: the bound macsmc-hwmon device; the caller holds its device lock - * @permille: each fan's target as a share of its minimum-to-maximum range; - * 0 hands the fans this interface set back to the SMC - * @min_step_rpm: a fan already set by this interface whose target is closer - * than this to the new one keeps its target - * - * The fans go through the same manual mode as a userspace request, so the - * mode key has one owner: fans userspace holds are left alone, and every fan - * returns to the SMC at suspend, shutdown and unbind. Only fans whose device - * tree node names their mode, target, minimum and maximum keys take part. - * - * Return: the first such fan's target in rpm (0 once handed back), -ENODEV - * without such a fan, -EBUSY while stopped, or the first error. - */ -int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, - unsigned int min_step_rpm) +static bool macsmc_hwmon_fan_controllable(const struct macsmc_hwmon_fan *fan) +{ + return fan->mode.macsmc_key && + (fan->attrs & (HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX)) == + (HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX); +} + +static int __macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, + unsigned int min_step_rpm, bool manual_only) { struct macsmc_hwmon *hwmon = dev_get_drvdata(dev); - long first = -ENODEV; + long first = permille ? -ENODEV : 0; int ret = 0; u32 i; @@ -614,17 +641,15 @@ int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, long min, max, now, target; int err; - if (!fan->mode.macsmc_key || - (fan->attrs & (HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX)) != - (HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX)) + if (!macsmc_hwmon_fan_controllable(fan)) + continue; + if (manual_only && !fan->manual_control) continue; if (fan->manual && !fan->kernel) continue; if (!permille) { - if (first < 0) - first = 0; - err = macsmc_hwmon_fan_auto(hwmon, fan); + err = macsmc_hwmon_fan_set_auto(hwmon, fan); if (err && !ret) ret = err; continue; @@ -668,10 +693,205 @@ int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, } } + if (!permille && hwmon->fan.unlocked && !hwmon->fan.manual) { + int err = macsmc_hwmon_fans_relock(hwmon); + + if (err && !ret) + ret = err; + } + return ret ? ret : first; } + +/** + * macsmc_hwmon_fans_request() - set the fans for a kernel thermal policy + * @dev: the bound macsmc-hwmon device; the caller holds its device lock + * @permille: each fan's target as a share of its minimum-to-maximum range; + * 0 hands the fans this interface set back to the SMC + * @min_step_rpm: a fan already set by this interface whose target is closer + * than this to the new one keeps its target + * + * The fans go through the same manual mode as a userspace request, so the + * mode key has one owner: fans userspace holds are left alone, and every fan + * returns to the SMC at suspend, shutdown and unbind. Only fans whose device + * tree node names their mode, target, minimum and maximum keys take part. + * + * Return: the first such fan's target in rpm for a non-zero @permille, or 0 + * when @permille is 0 (even when no fan is kernel-owned); -ENODEV if @dev is + * unbound or for a non-zero @permille without such a fan; -EBUSY while + * stopped for a non-zero @permille; or the first error. + */ +int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, + unsigned int min_step_rpm) +{ + return __macsmc_hwmon_fans_request(dev, permille, min_step_rpm, false); +} EXPORT_SYMBOL_GPL(macsmc_hwmon_fans_request); +/** + * macsmc_hwmon_fans_request_manual() - set DT-manual fans for a kernel policy + * @dev: the bound macsmc-hwmon device; the caller holds its device lock + * @permille: each fan's target as a share of its minimum-to-maximum range; + * 0 hands the fans this interface set back to the SMC + * @min_step_rpm: minimum delta before updating an already kernel-owned target + * + * Like macsmc_hwmon_fans_request(), but only drives fans whose device tree + * node carries apple,fan-manual-control. Fans without apple,fan-manual-control + * are left alone. + */ +int macsmc_hwmon_fans_request_manual(struct device *dev, unsigned int permille, + unsigned int min_step_rpm) +{ + return __macsmc_hwmon_fans_request(dev, permille, min_step_rpm, true); +} +EXPORT_SYMBOL_GPL(macsmc_hwmon_fans_request_manual); + +static bool macsmc_hwmon_fan_settable(const struct device_node *fan) +{ + return of_property_present(fan, "apple,fan-mode") && + of_property_present(fan, "apple,fan-target") && + of_property_present(fan, "apple,fan-minimum") && + of_property_present(fan, "apple,fan-maximum"); +} + +/* + * Parse the DT-supplied hotspot fan-assistance thresholds for macsmc_soc_die: + * a single key in apple,soc-die-keys plus valid trigger temperature, + * hysteresis, and hold duration. + */ +static bool macsmc_hwmon_parse_fan_assist(const struct device_node *np, + struct macsmc_hwmon_fan_assist *policy) +{ + u32 trip, hyst, hold_ms; + + if (!np || of_property_count_strings(np, "apple,soc-die-keys") != 1) + return false; + if (of_property_read_u32(np, "apple,soc-die-fan-trip-millicelsius", &trip) || + of_property_read_u32(np, "apple,soc-die-fan-hysteresis-millicelsius", &hyst) || + of_property_read_u32(np, "apple,soc-die-fan-hold-ms", &hold_ms)) + return false; + if (!trip || trip > MACSMC_DIE_MAX_MC || !hyst || hyst >= trip || !hold_ms) + return false; + + if (policy) { + policy->trigger_mc = (int)trip; + policy->release_mc = (int)(trip - hyst); + policy->hold_ms = hold_ms; + } + return true; +} + +/* + * Parse the DT-supplied SoC die limits for macsmc_soc_die: the temperature + * from which power consumers shed performance (passive trip) and the one at + * which they hold their lowest state (hot trip). Both are required, and the + * hot trip must lie above the passive one. + */ +static bool macsmc_hwmon_parse_die_limits(const struct device_node *np, + int *passive_mc, int *hot_mc) +{ + u32 passive, hot; + + if (!np || + of_property_read_u32(np, "apple,soc-die-passive-millicelsius", &passive) || + of_property_read_u32(np, "apple,soc-die-hot-millicelsius", &hot)) + return false; + if (!passive || hot <= passive || hot > MACSMC_DIE_MAX_MC) + return false; + + *passive_mc = (int)passive; + *hot_mc = (int)hot; + return true; +} + +static bool macsmc_hwmon_node_hotspot_assist(const struct device_node *np, + struct macsmc_hwmon_fan_assist *policy) +{ + if (!macsmc_hwmon_parse_fan_assist(np, policy)) + return false; + for_each_child_of_node_with_prefix(np, child, "fan-") { + if (of_property_read_bool(child, "apple,fan-manual-control") && + macsmc_hwmon_fan_settable(child)) + return true; + } + return false; +} + +static bool macsmc_hwmon_node_path_available(const struct device_node *np) +{ + struct device_node *node = of_node_get((struct device_node *)np); + + while (node) { + struct device_node *parent; + + if (!of_device_is_available(node)) { + of_node_put(node); + return false; + } + parent = of_get_parent(node); + of_node_put(node); + node = parent; + } + return true; +} + +/** + * macsmc_hwmon_hotspot_assist_available() - whether the DT configures hotspot fan assistance + * + * Scans available apple,smc-hwmon nodes (with all parents available) for one + * describing a single SoC die key, valid hotspot fan-assistance trip + * thresholds and hold duration, and at least one settable fan with + * apple,fan-manual-control. + */ +bool macsmc_hwmon_hotspot_assist_available(void) +{ + struct device_node *np; + + for_each_compatible_node(np, NULL, "apple,smc-hwmon") { + if (macsmc_hwmon_node_path_available(np) && + macsmc_hwmon_node_hotspot_assist(np, NULL)) { + of_node_put(np); + return true; + } + } + return false; +} +EXPORT_SYMBOL_GPL(macsmc_hwmon_hotspot_assist_available); + +/** + * macsmc_hwmon_hotspot_assist_policy() - read hotspot fan-assistance policy from @dev + * @dev: the bound macsmc-hwmon device; the caller holds its device lock + * @policy: optional destination for trigger/release temperatures and hold time + * + * Return: 0 if @dev has a single present SoC die sensor, DT-supplied active + * trip thresholds and hold time, and at least one probed fan with + * apple,fan-manual-control; -ENODEV otherwise. + */ +int macsmc_hwmon_hotspot_assist_policy(struct device *dev, + struct macsmc_hwmon_fan_assist *policy) +{ + struct macsmc_hwmon *hwmon = dev_get_drvdata(dev); + bool has_manual = false; + u32 i; + + if (!hwmon || !hwmon->fan_assist_valid) + return -ENODEV; + for (i = 0; i < hwmon->fan.count; i++) { + const struct macsmc_hwmon_fan *fan = &hwmon->fan.fans[i]; + + if (fan->manual_control && macsmc_hwmon_fan_controllable(fan)) { + has_manual = true; + break; + } + } + if (!has_manual) + return -ENODEV; + if (policy) + *policy = hwmon->fan_assist; + return 0; +} +EXPORT_SYMBOL_GPL(macsmc_hwmon_hotspot_assist_policy); + static int macsmc_hwmon_write_fan(struct device *dev, u32 attr, int channel, long val) { @@ -698,7 +918,9 @@ static void macsmc_hwmon_fans_restore(struct macsmc_hwmon *hwmon) guard(mutex)(&hwmon->fan.lock); for (i = 0; i < hwmon->fan.count; i++) - macsmc_hwmon_fan_auto(hwmon, &hwmon->fan.fans[i]); + macsmc_hwmon_fan_set_auto(hwmon, &hwmon->fan.fans[i]); + if (hwmon->fan.unlocked && !hwmon->fan.manual) + macsmc_hwmon_fans_relock(hwmon); } static void macsmc_hwmon_fans_restore_action(void *data) @@ -1346,16 +1568,22 @@ static void macsmc_hwmon_populate_fan_configs(u32 *configs, const struct macsmc_ /* * The SoC die temperature zone: the hottest of the SoC die temperature * sensors, for in-kernel users that limit SoC power by temperature (they look - * the zone up by name). It has no trip points and is not polled; each read - * queries every SoC die sensor. A read fails if any of them cannot be read or - * reads outside -40..150 degrees Celsius, so users never act on a partial or - * implausible view. A sensor below its no-data threshold is powered down and - * left out. + * the zone up by name). It is not polled; each read queries every SoC die + * sensor. Its trips come from the DT: the hotspot fan-assistance active trip + * and the SoC die passive and hot limits, each only when configured. A read + * fails if any of the sensors cannot be read or reads outside -40..150 degrees + * Celsius, so users never act on a partial or implausible view. A sensor below + * its no-data threshold is powered down and left out. */ #if IS_ENABLED(CONFIG_THERMAL) #define MACSMC_SOC_DIE_ZONE "macsmc_soc_die" -#define MACSMC_DIE_MIN_MC -40000 -#define MACSMC_DIE_MAX_MC 150000 +/* + * The thermal sensor ID of the SoC die zone for a device tree thermal zone, on + * a node that discovers its temperatures and is a thermal sensor provider. It + * must stay above every temperature channel index the hwmon core registers; + * discovered channels are not bounded at build time, so probe checks it. + */ +#define MACSMC_SOC_DIE_SENSOR_ID 1000 static int macsmc_hwmon_die_hottest(struct macsmc_hwmon *hwmon, int *temp) { @@ -1404,8 +1632,10 @@ static void macsmc_hwmon_die_unregister(void *data) static int macsmc_hwmon_die_register(struct macsmc_hwmon *hwmon) { + struct thermal_trip trips[3]; struct thermal_zone_device *tz; char keys[16 * 5] = ""; + unsigned int n_trips = 0; size_t len = 0; u32 i; @@ -1425,14 +1655,70 @@ static int macsmc_hwmon_die_register(struct macsmc_hwmon *hwmon) key >> 24, (key >> 16) & 0xff, (key >> 8) & 0xff, key & 0xff); } - tz = thermal_tripless_zone_device_register(MACSMC_SOC_DIE_ZONE, hwmon, - &macsmc_hwmon_die_ops, NULL); + /* + * A board with a device tree zone on the die sensor gets that zone, with its trips and + * cooling maps. Its lifetime is managed by the OF helper. The named zone below + * is registered either way: the GPU drivers' governors look it up by its name. + */ + if (of_property_present(hwmon->dev->of_node, "#thermal-sensor-cells") && + hwmon->temp.count >= MACSMC_SOC_DIE_SENSOR_ID) { + dev_warn(hwmon->dev, "%u temperature channels reach the SoC die sensor ID %u\n", + hwmon->temp.count, MACSMC_SOC_DIE_SENSOR_ID); + } else if (of_property_present(hwmon->dev->of_node, "#thermal-sensor-cells")) { + tz = devm_thermal_of_zone_register(hwmon->dev, MACSMC_SOC_DIE_SENSOR_ID, hwmon, + &macsmc_hwmon_die_ops); + if (!IS_ERR(tz)) + dev_info(hwmon->dev, "SoC die zone %s (device tree): hottest of%s (%u of %u keys)\n", + thermal_zone_device_type(tz), keys, hwmon->die_count, + hwmon->die_listed); + else if (PTR_ERR(tz) != -ENODEV) + dev_warn(hwmon->dev, + "cannot register the device tree SoC die zone (%pe)\n", tz); + } + + if (hwmon->fan_assist_valid) + trips[n_trips++] = (struct thermal_trip) { + .temperature = hwmon->fan_assist.trigger_mc, + .hysteresis = hwmon->fan_assist.trigger_mc - + hwmon->fan_assist.release_mc, + .type = THERMAL_TRIP_ACTIVE, + }; + /* + * The hot trip only reports: the zone has no hot callback, so nothing + * here shuts the machine down. Consumers that read the trips (the GPU + * thermal backstop) shed performance from the passive trip and hold + * their lowest state at the hot one. + */ + if (hwmon->die_limits_valid) { + trips[n_trips++] = (struct thermal_trip) { + .temperature = hwmon->die_passive_mc, + .type = THERMAL_TRIP_PASSIVE, + }; + trips[n_trips++] = (struct thermal_trip) { + .temperature = hwmon->die_hot_mc, + .type = THERMAL_TRIP_HOT, + }; + } + + if (n_trips) + tz = thermal_zone_device_register_with_trips(MACSMC_SOC_DIE_ZONE, + trips, n_trips, hwmon, + &macsmc_hwmon_die_ops, + NULL, 0, 0); + else + tz = thermal_tripless_zone_device_register(MACSMC_SOC_DIE_ZONE, hwmon, + &macsmc_hwmon_die_ops, NULL); if (IS_ERR(tz)) { dev_warn(hwmon->dev, "cannot register the SoC die temperature zone (%pe)\n", tz); return 0; } - dev_info(hwmon->dev, "SoC die temperature zone %s: hottest of%s (%u of %u listed keys present)\n", - MACSMC_SOC_DIE_ZONE, keys, hwmon->die_count, hwmon->die_listed); + if (hwmon->die_limits_valid) + dev_info(hwmon->dev, "SoC die temperature zone %s: hottest of%s (%u of %u listed keys present), passive %d mC, hot %d mC\n", + MACSMC_SOC_DIE_ZONE, keys, hwmon->die_count, hwmon->die_listed, + hwmon->die_passive_mc, hwmon->die_hot_mc); + else + dev_info(hwmon->dev, "SoC die temperature zone %s: hottest of%s (%u of %u listed keys present)\n", + MACSMC_SOC_DIE_ZONE, keys, hwmon->die_count, hwmon->die_listed); return devm_add_action_or_reset(hwmon->dev, macsmc_hwmon_die_unregister, tz); } #else @@ -1442,6 +1728,193 @@ static int macsmc_hwmon_die_register(struct macsmc_hwmon *hwmon) } #endif +#if IS_ENABLED(CONFIG_THERMAL_OF) && IS_ENABLED(CONFIG_CPU_THERMAL) && \ + IS_REACHABLE(CONFIG_ARM_APPLE_SOC_CPUFREQ) +/* + * CPU cluster ownership + * + * A SoC whose cpufreq driver holds each cluster below its higher states until + * a board thermal policy protects it (T8152) gets that policy from this + * device's thermal zones: DT zones fed by these sensors whose cooling maps + * throttle a cluster's cpufreq cooling device. A cluster is handed over only + * when every such map is live: its zone is registered, the map's trip is + * passive, and the thermal core has bound that trip to the cluster's cooling + * device. Any map that is not keeps the cluster at its ceiling. Ownership is + * given back before the zones go away. + */ +#define MACSMC_CPU_OWNER_TRIES 120 + +struct macsmc_hwmon_cpu_map { + struct thermal_zone_device *tz; + struct device_node *trip_np; + struct thermal_cooling_device *cdev; + int ret; +}; + +static int macsmc_hwmon_cpu_map_trip(struct thermal_trip *trip, void *data) +{ + struct macsmc_hwmon_cpu_map *map = data; + + if (trip->priv != map->trip_np) + return 0; + if (trip->type != THERMAL_TRIP_PASSIVE) + map->ret = -EINVAL; + else if (!thermal_trip_is_bound_to_cdev(map->tz, trip, map->cdev)) + map->ret = -ENOLINK; + else + map->ret = 0; + return 1; +} + +/* + * The clusters (by policy->cpu) that the CPU cooling maps of this device's + * zones protect, in @ready, and those with a map that is not live, in + * @refused. -EPROBE_DEFER while a named cluster has no cpufreq policy or + * cooling device yet. + */ +static int macsmc_hwmon_cpu_maps(struct macsmc_hwmon *hwmon, struct cpumask *ready, + struct cpumask *refused) +{ + struct device_node *zones __free(device_node) = + of_find_node_by_path("/thermal-zones"); + int ret = 0; + + cpumask_clear(ready); + cpumask_clear(refused); + if (!zones) + return 0; + + for_each_available_child_of_node_scoped(zones, zone) { + struct device_node *maps __free(device_node) = NULL; + struct thermal_zone_device *tz; + struct of_phandle_args sensor; + + if (of_parse_phandle_with_args(zone, "thermal-sensors", + "#thermal-sensor-cells", 0, &sensor)) + continue; + of_node_put(sensor.np); + if (sensor.np != hwmon->dev->of_node) + continue; + maps = of_get_child_by_name(zone, "cooling-maps"); + if (!maps) + continue; + /* thermal_of registers a zone under its node name. */ + tz = thermal_zone_get_zone_by_name(zone->name); + + for_each_child_of_node_scoped(maps, map) { + struct device_node *trip_np __free(device_node) = + of_parse_phandle(map, "trip", 0); + struct of_phandle_args cooling; + int i; + + for (i = 0; !of_parse_phandle_with_args(map, "cooling-device", + "#cooling-cells", i, &cooling); i++) { + struct macsmc_hwmon_cpu_map check = { .ret = -ENOENT }; + struct cpufreq_policy *policy; + int cpu = of_cpu_node_to_id(cooling.np); + + of_node_put(cooling.np); + if (cpu < 0) + continue; + policy = cpufreq_cpu_get(cpu); + if (!policy || !policy->cdev) { + if (policy) + cpufreq_cpu_put(policy); + ret = -EPROBE_DEFER; + continue; + } + if (!IS_ERR(tz) && trip_np) { + check.tz = tz; + check.trip_np = trip_np; + check.cdev = policy->cdev; + for_each_thermal_trip(tz, macsmc_hwmon_cpu_map_trip, &check); + } + cpumask_set_cpu(policy->cpu, check.ret ? refused : ready); + cpufreq_cpu_put(policy); + } + } + } + cpumask_andnot(ready, ready, refused); + return ret; +} + +static void macsmc_hwmon_cpu_owner_work(struct work_struct *work) +{ + struct macsmc_hwmon *hwmon = container_of(to_delayed_work(work), struct macsmc_hwmon, + cpu_owner_work); + cpumask_t ready, refused; + int cpu, ret, pending; + + pending = macsmc_hwmon_cpu_maps(hwmon, &ready, &refused); + + for_each_cpu(cpu, &refused) { + if (cpumask_test_and_set_cpu(cpu, &hwmon->cpu_refused)) + continue; + dev_warn(hwmon->dev, + "CPU%d cluster keeps its cpufreq ceiling: a cooling map of its thermal zones is not bound\n", + cpu); + } + + for_each_cpu(cpu, &ready) { + struct cpufreq_policy *policy; + + if (cpumask_test_cpu(cpu, &hwmon->cpu_owned)) + continue; + policy = cpufreq_cpu_get(cpu); + if (!policy) + continue; + ret = apple_soc_cpufreq_set_thermal_owner(policy, true); + cpufreq_cpu_put(policy); + /* -ENODEV: this SoC does not hold the cluster back. */ + if (!ret) { + cpumask_set_cpu(cpu, &hwmon->cpu_owned); + dev_info(hwmon->dev, + "CPU%d cluster: higher states handed to its thermal zones\n", cpu); + } else if (ret != -ENODEV) { + dev_warn(hwmon->dev, "CPU%d cluster: ownership refused: %d\n", cpu, ret); + } + } + + if (pending != -EPROBE_DEFER) + return; + if (++hwmon->cpu_owner_tries < MACSMC_CPU_OWNER_TRIES) + schedule_delayed_work(&hwmon->cpu_owner_work, HZ); + else + dev_warn(hwmon->dev, + "CPU clusters without a cpufreq cooling device keep their ceiling\n"); +} + +static void macsmc_hwmon_cpu_release(void *data) +{ + struct macsmc_hwmon *hwmon = data; + int cpu; + + cancel_delayed_work_sync(&hwmon->cpu_owner_work); + for_each_cpu(cpu, &hwmon->cpu_owned) { + struct cpufreq_policy *policy = cpufreq_cpu_get(cpu); + + if (policy) { + apple_soc_cpufreq_set_thermal_owner(policy, false); + cpufreq_cpu_put(policy); + } + } + cpumask_clear(&hwmon->cpu_owned); +} + +/* Called once the zones are registered; released before they are removed. */ +static int macsmc_hwmon_cpu_owner_init(struct macsmc_hwmon *hwmon) +{ + INIT_DELAYED_WORK(&hwmon->cpu_owner_work, macsmc_hwmon_cpu_owner_work); + schedule_delayed_work(&hwmon->cpu_owner_work, 0); + return devm_add_action_or_reset(hwmon->dev, macsmc_hwmon_cpu_release, hwmon); +} +#else +static int macsmc_hwmon_cpu_owner_init(struct macsmc_hwmon *hwmon) +{ + return 0; +} +#endif + /* * debugfs "keys": every key the SMC reports, with its type, size and flags, and the value of the * readable 32-bit float keys whose names start with 'T' (temperatures, in millidegrees Celsius) @@ -1641,6 +2114,15 @@ static int macsmc_hwmon_probe(struct platform_device *pdev) if (ret) return dev_err_probe(hwmon->dev, ret, "Temperature discovery failed\n"); + if (hwmon->die_listed == 1 && hwmon->die_count == 1 && + macsmc_hwmon_parse_fan_assist(hwmon->dev->of_node, &hwmon->fan_assist)) + hwmon->fan_assist_valid = true; + + if (hwmon->die_count && + macsmc_hwmon_parse_die_limits(hwmon->dev->of_node, &hwmon->die_passive_mc, + &hwmon->die_hot_mc)) + hwmon->die_limits_valid = true; + if (!hwmon->curr.count && !hwmon->fan.count && !hwmon->power.count && !hwmon->temp.count && !hwmon->volt.count && !hwmon->pressure.macsmc_key) { @@ -1686,6 +2168,10 @@ static int macsmc_hwmon_probe(struct platform_device *pdev) if (ret) return ret; + ret = macsmc_hwmon_cpu_owner_init(hwmon); + if (ret) + return ret; + dev_dbg(hwmon->dev, "Registered SMC hwmon device. Sensors:\n"); dev_dbg(hwmon->dev, "Current: %d, Fans: %d, Power: %d, Temperature: %d, Voltage: %d", diff --git a/drivers/i2c/busses/i2c-pasemi-core.c b/drivers/i2c/busses/i2c-pasemi-core.c index 7105fc46064509..38bddbbcefd3b1 100644 --- a/drivers/i2c/busses/i2c-pasemi-core.c +++ b/drivers/i2c/busses/i2c-pasemi-core.c @@ -196,24 +196,29 @@ static int pasemi_smb_waitready(struct pasemi_smbus *smbus) return -ETIME; } - /* Still stuck in a transaction? */ - if (status & SMSTA_XIP) { - dev_err(smbus->dev, "Bus stuck, status 0x%08x\n", status); - return -EIO; - } - /* Arbitration loss? */ if (status & SMSTA_MTA) { dev_err(smbus->dev, "Arbitration loss, status 0x%08x\n", status); return -EBUSY; } - /* Got NACK? */ + /* + * Got NACK? The interrupt comes with the NACK, before the controller + * has put the STOP on the bus, so XIP is usually still set here: this + * is checked before XIP, and the transfer is over once the STOP is out + * (the next transfer waits for that). + */ if (status & SMSTA_MTN) { dev_err(smbus->dev, "NACK, status 0x%08x\n", status); return -ENXIO; } + /* Still stuck in a transaction? */ + if (status & SMSTA_XIP) { + dev_err(smbus->dev, "Bus stuck, status 0x%08x\n", status); + return -EIO; + } + /* Clear XEN */ reg_write(smbus, REG_SMSTA, SMSTA_XEN); diff --git a/drivers/iio/common/aop_sensors/aop_als.rs b/drivers/iio/common/aop_sensors/aop_als.rs index e64f7ff26a6e05..375cf57c793840 100644 --- a/drivers/iio/common/aop_sensors/aop_als.rs +++ b/drivers/iio/common/aop_sensors/aop_als.rs @@ -4,15 +4,25 @@ //! //! Copyright (C) The Asahi Linux Contributors +use core::{ + ffi::{c_int, c_void}, + ptr, +}; + use kernel::{ bindings, c_str, - device::Core, + device::{self, Core}, firmware::Firmware, iio::common::aop_sensors::{AopSensorData, IIORegistration, MessageProcessor, MICRO}, module_platform_driver, of, platform, prelude::*, soc::apple::aop::{EPICService, FakehidRegistration, AOP}, - sync::Arc, + sync::{ + aref::ARef, + atomic::{Atomic, Relaxed}, + Arc, + }, + types::Opaque, }; const EPIC_SUBTYPE_GET_AOP_PROPERTY: u16 = 0xa; @@ -97,6 +107,12 @@ fn enable_als( return Ok(()); } + arm_ct817(aop, dev.as_ref(), svc) +} + +/// Arms the CT817: interval zero, its configuration, then the interval that +/// starts the reports. +fn arm_ct817(aop: &dyn AOP, dev: &device::Device, svc: &EPICService) -> Result<()> { // The CT817 gets its calibration from the AOP driver over the setup port, // not as an ALS property. Only the transport can fail here; the sensor's // status words are logged, see the property comments above. Do not fetch @@ -105,15 +121,13 @@ fn enable_als( // wedges the AOP for the rest of the boot. let set = |tag: u32, val: u32, what: &str| -> Result<()> { let status = set_als_property(aop, svc, tag, &val.to_le_bytes())?; - dev_dbg!( - dev.as_ref(), - "{} = {:#x}: status {:#x}\n", - what, - val, - status - ); + dev_dbg!(dev, "{} = {:#x}: status {:#x}\n", what, val, status); Ok(()) }; + // The sensor arms only on a zero to non-zero transition of the interval. + // It is zero at boot and stopped after a sleep, but a previous driver + // instance may have left it running, so write zero first every time. + set(ALS_PROP_INTERVAL, 0, "interval")?; set(ALS_PROP_VERBOSITY, ALS_VERBOSITY, "verbosity")?; set( ALS_PROP_BATCH_INTERVAL, @@ -121,11 +135,182 @@ fn enable_als( "batch interval", )?; set(ALS_PROP_RAW_INTERVAL, ALS_RAW_INTERVAL, "raw interval")?; - // The interval is zero at probe, so this is the transition that arms the - // sensor. + // The transition that arms the sensor. set(ALS_PROP_INTERVAL, ALS_INTERVAL_US, "interval") } +/// Stops the reports for system sleep and starts them again after it. +/// +/// The sensor reports on its own every `ALS_INTERVAL_US`, and each report is +/// an AOP mailbox interrupt. In suspend-to-idle those interrupts go on and +/// wake a CPU for a reading nobody takes, so the reports stop before the +/// sleep, as the lid angle driver's do. +/// +/// The CT817 needs more after the sleep: the firmware stops its reports for +/// system sleep and does not start them again. On the J700 every read after +/// the first wake of a boot returned the last sample from before that sleep, +/// while the room's light changed. The sensor starts reporting only on a zero +/// to non-zero transition of its interval, so the wake repeats the arming of +/// the probe, which starts with an interval of zero. The other parts need only +/// their interval back. +#[repr(C)] +struct PmHook { + /// First, so that the callback finds the hook from it. + nb: Opaque, + dev: ARef, + aop: Arc, + service: EPICService, + /// The part arms only through the whole CT817 sequence. + ct817: bool, + /// A stop was tried for the sleep in progress. It is set before the + /// command goes out: a stop whose reply was lost may still have been + /// applied, so the wake restores the interval after every attempt. + stop_attempted: Atomic, + registered: Atomic, +} + +/// The PM notifier callback. +/// +/// # Safety +/// +/// `nb` is the notifier block of a registered [`PmHook`]. +unsafe extern "C" fn pm_event( + nb: *mut bindings::notifier_block, + action: usize, + _data: *mut c_void, +) -> c_int { + // SAFETY: `nb` is the first field of a registered `PmHook`. + let hook = unsafe { &*nb.cast::() }; + let aop = hook.aop.as_ref(); + match action as u32 { + bindings::PM_SUSPEND_PREPARE => { + // A sensor that keeps reporting only costs wakeups: never refuse + // the sleep over it. + hook.stop_attempted.store(true, Relaxed); + match set_als_property(aop, &hook.service, ALS_PROP_INTERVAL, &0u32.to_le_bytes()) { + Ok(_) => dev_dbg!(hook.dev, "reports off for sleep\n"), + Err(e) => dev_warn!(hook.dev, "reports may be left on for sleep: {:?}\n", e), + } + } + bindings::PM_POST_SUSPEND => { + let attempted = hook.stop_attempted.xchg(false, Relaxed); + // The CT817 is stopped by the firmware even when the host did not + // stop it, so it is armed again after every sleep. The other parts + // get their interval back after every attempted stop, whether or + // not the stop's reply arrived; writing the active interval to a + // sensor that kept reporting changes nothing. + let rearm = if hook.ct817 { + arm_ct817(aop, &hook.dev, &hook.service) + } else if attempted { + set_als_property( + aop, + &hook.service, + ALS_PROP_INTERVAL, + &ALS_INTERVAL_US.to_le_bytes(), + ) + .map(|_| ()) + } else { + Ok(()) + }; + match rearm { + Ok(()) => dev_dbg!(hook.dev, "reports back after sleep\n"), + Err(e) => dev_warn!(hook.dev, "reports not back after sleep: {:?}\n", e), + } + } + _ => return bindings::NOTIFY_DONE as c_int, + } + bindings::NOTIFY_OK as c_int +} + +/// # Safety +/// +/// `nb` stays valid and pinned until [`pm_unregister`] is called on it. +#[cfg(CONFIG_PM_SLEEP)] +unsafe fn pm_register(nb: *mut bindings::notifier_block) -> c_int { + // SAFETY: By the caller's contract. + unsafe { bindings::register_pm_notifier(nb) } +} + +/// # Safety +/// +/// `nb` was registered by [`pm_register`]. +#[cfg(CONFIG_PM_SLEEP)] +unsafe fn pm_unregister(nb: *mut bindings::notifier_block) { + // SAFETY: By the caller's contract. + unsafe { bindings::unregister_pm_notifier(nb) }; +} + +/// Without system sleep there is nothing to arm again. +/// +/// # Safety +/// +/// None; the signature matches the one with system sleep. +#[cfg(not(CONFIG_PM_SLEEP))] +unsafe fn pm_register(_nb: *mut bindings::notifier_block) -> c_int { + 0 +} + +/// # Safety +/// +/// None; the signature matches the one with system sleep. +#[cfg(not(CONFIG_PM_SLEEP))] +unsafe fn pm_unregister(_nb: *mut bindings::notifier_block) {} + +// SAFETY: The notifier block is only touched by the PM core, which +// serializes registration, removal and the callbacks itself. +unsafe impl Send for PmHook {} +// SAFETY: See above; the other fields are `Sync`. +unsafe impl Sync for PmHook {} + +impl PmHook { + fn new( + dev: &device::Device, + aop: Arc, + service: EPICService, + ct817: bool, + ) -> Result>> { + let hook = KBox::pin( + Self { + nb: Opaque::new(bindings::notifier_block { + notifier_call: Some(pm_event), + next: ptr::null_mut(), + priority: 0, + }), + dev: dev.into(), + aop, + service, + ct817, + stop_attempted: Atomic::new(false), + registered: Atomic::new(false), + }, + GFP_KERNEL, + )?; + // SAFETY: The block is pinned inside the hook, which unregisters it + // before it goes. + let ret = unsafe { pm_register(hook.nb.get()) }; + if ret < 0 { + return Err(Error::from_errno(ret)); + } + hook.registered.store(true, Relaxed); + Ok(hook) + } + + /// Returns once no callback is running any more; repeated calls do + /// nothing. + fn unregister(&self) { + if self.registered.xchg(false, Relaxed) { + // SAFETY: `nb` was registered by `new()`. + unsafe { pm_unregister(self.nb.get()) }; + } + } +} + +impl Drop for PmHook { + fn drop(&mut self) { + self.unregister(); + } +} + fn get_aop_property( aop: &dyn AOP, svc: &EPICService, @@ -206,9 +391,13 @@ enum AlsIio { } struct IIOAopAlsDriver { - /// Declared first: the subscription ends before the IIO device goes. + /// Fields are declared in teardown order: the sleep hook first, then the + /// subscription, which ends before the IIO device goes. + pm: Pin>, listener: FakehidRegistration, _iio: AlsIio, + aop: Arc, + service: EPICService, } fn register_channels( @@ -285,13 +474,29 @@ impl platform::Driver for IIOAopAlsDriver { }, ) }; + let pm = PmHook::new(dev, adata.clone(), service, offset == LUX_OFFSET_CT817)?; Ok(IIOAopAlsDriver { + pm, listener, _iio: iio, + aop: adata, + service, }) } - fn unbind(_dev: &platform::Device>, this: Pin<&Self>) { + fn unbind(dev: &platform::Device>, this: Pin<&Self>) { + this.pm.unregister(); + // The sensor keeps reporting until its interval is zero, and every + // report is an AOP mailbox interrupt. Stop it before the listener + // goes; a failure only costs those interrupts, so unbind goes on. + if let Err(e) = set_als_property( + this.aop.as_ref(), + &this.service, + ALS_PROP_INTERVAL, + &0u32.to_le_bytes(), + ) { + dev_warn!(dev.as_ref(), "reports not stopped at unbind: {:?}\n", e); + } this.listener.unregister(); } } diff --git a/drivers/iio/common/aop_sensors/aop_devmotion.rs b/drivers/iio/common/aop_sensors/aop_devmotion.rs index e392c1435bbd4d..cc524da287b27d 100644 --- a/drivers/iio/common/aop_sensors/aop_devmotion.rs +++ b/drivers/iio/common/aop_sensors/aop_devmotion.rs @@ -18,7 +18,7 @@ use kernel::{ bindings, c_str, device::{self, Core}, dma::Coherent, - module_platform_driver, new_delayed_work, new_mutex, new_spinlock, of, platform, + driver, new_delayed_work, new_mutex, new_spinlock, of, platform, prelude::*, soc::apple::aop::{EPICService, AOP}, sync::{ @@ -29,6 +29,7 @@ use kernel::{ time::{self, delay::fsleep, Delta}, types::{ForeignOwnable, Opaque}, workqueue::{self, impl_has_delayed_work, DelayedWork, Work, WorkItem}, + ThisModule, }; const SUBTYPE_GET_PROPERTY: u16 = 10; @@ -69,11 +70,24 @@ struct Sample { valid: bool, } -/// One buffer scan. A quaternion is aligned like `IIO_DECLARE_QUATERNION()`. +/// One buffer scan. A quaternion is aligned like `IIO_DECLARE_QUATERNION()`, +/// which rounds the scan up to a multiple of its 16 bytes. The IIO core +/// copies all of that, so the tail is a field that is written, not padding. #[repr(C, align(16))] struct Scan { quat: [i32; 4], timestamp: i64, + pad: u64, +} + +impl Scan { + fn new(quat: [i32; 4], timestamp: i64) -> Self { + Self { + quat, + timestamp, + pad: 0, + } + } } fn le_u32(data: &[u8], at: usize) -> Option { @@ -258,7 +272,7 @@ impl State { *self.sample.lock() = Sample { quat, valid: true }; // SAFETY: The polling work is disabled before the IIO device is freed. let timestamp = unsafe { bindings::iio_get_time_ns(self.iio.0) }; - let scan = Scan { quat, timestamp }; + let scan = Scan::new(quat, timestamp); // SAFETY: `scan` contains the complete only data channel followed by // the timestamp, and the IIO core copies it synchronously. unsafe { bindings::iio_push_to_buffers(self.iio.0, ptr::from_ref(&scan).cast()) }; @@ -989,10 +1003,74 @@ impl platform::Driver for IIOAopDevMotionDriver { } } -module_platform_driver! { - type: IIOAopDevMotionDriver, +/// The AOP core creates the device of a service, named after the service, +/// whenever the firmware announces that service. Registering the driver under +/// the same name lets the platform bus bind it on every machine whose AOP +/// offers the service, with or without a device tree node for it. +const SERVICE_NAME: &CStr = c_str!("devmotion6"); + +#[pin_data] +struct IIOAopDevMotionModule { + #[pin] + _driver: driver::Registration>, +} + +impl kernel::InPlaceModule for IIOAopDevMotionModule { + fn init(module: &'static ThisModule) -> impl PinInit { + try_pin_init!(Self { + _driver <- driver::Registration::new(SERVICE_NAME, module), + }) + } +} + +module! { + type: IIOAopDevMotionModule, name: "iio_aop_devmotion", description: "AOP device-motion fusion driver", license: "Dual MIT/GPL", - alias: ["platform:iio_aop_devmotion"], + alias: ["platform:devmotion6"], +} + +#[kunit_tests(iio_aop_devmotion)] +mod tests { + use super::*; + use core::mem::MaybeUninit; + + /// The bytes the IIO core takes for a scan of `channels`, all enabled: + /// each element at a multiple of its size, a repeated one counted to the + /// next power of two, and the total a multiple of the largest, as + /// `iio_compute_scan_bytes()` lays them out. + fn scan_bytes(channels: &[bindings::iio_chan_spec]) -> usize { + let mut bytes = 0usize; + let mut largest = 1; + for chan in channels { + // SAFETY: The channels of this driver use the plain scan type. + let scan_type = unsafe { chan.__bindgen_anon_1.scan_type }; + let repeat = usize::from(scan_type.repeat.max(1)).next_power_of_two(); + let len = usize::from(scan_type.storagebits) / 8 * repeat; + bytes = bytes.next_multiple_of(len) + len; + largest = largest.max(len); + } + bytes.next_multiple_of(largest) + } + + #[test] + fn scan_is_written_in_full() { + let size = scan_bytes(&[quaternion_channel(), timestamp_channel()]); + assert_eq!(mem::size_of::(), size); + + let written = mem::size_of::<[i32; 4]>() + mem::size_of::(); + let mut slot = MaybeUninit::::uninit(); + // SAFETY: `slot` is valid for a write of one `Scan`, first of a byte + // pattern and then of a scan built as `State::publish()` builds it. + unsafe { + ptr::write_bytes(slot.as_mut_ptr(), 0xa5, 1); + slot.as_mut_ptr().write(Scan::new([1, 2, 3, 4], 5)); + } + for at in written..size { + // SAFETY: `at` is within `slot`, all of which was written above. + let byte = unsafe { slot.as_ptr().cast::().add(at).read_volatile() }; + assert_eq!(byte, 0); + } + } } diff --git a/drivers/iio/common/aop_sensors/aop_motion.rs b/drivers/iio/common/aop_sensors/aop_motion.rs index fa72bce5dbecbd..788c15252cd1b9 100644 --- a/drivers/iio/common/aop_sensors/aop_motion.rs +++ b/drivers/iio/common/aop_sensors/aop_motion.rs @@ -8,10 +8,11 @@ //! three calibration packets and a report interval. //! //! The reports run only while someone reads them: while a buffer is enabled, -//! or for the length of one direct read. With nobody reading they stay off, -//! as macOS keeps them (its accel and gyro drivers sit at report interval 0 on -//! an idle desktop), so the AOP does not wake the application processor 50 -//! times a second per sensor. +//! or until direct reads go quiet for a short idle window. Calibration is sent +//! once per AOP boot (not on every start), and with nobody reading the reports +//! stay off, as macOS keeps them (its accel and gyro drivers sit at report +//! interval 0 on an idle desktop), so the AOP does not wake the application +//! processor 50 times a second per sensor. use core::{ ffi::{c_int, c_void}, @@ -21,8 +22,8 @@ use core::{ use kernel::{ bindings, c_str, - device::{self, Core}, - module_platform_driver, new_mutex, new_spinlock, of, platform, + device::{self, Bound, Core}, + devres, module_platform_driver, new_delayed_work, new_mutex, new_spinlock, of, platform, prelude::*, soc::apple::aop::{EPICService, FakehidListener, FakehidRegistration, AOP}, sync::{ @@ -30,8 +31,9 @@ use kernel::{ atomic::{Atomic, Relaxed}, Arc, Mutex, SpinLock, }, - time::{delay::fsleep, Delta}, + time::{self, delay::fsleep, Delta, Instant, Monotonic}, types::{ForeignOwnable, Opaque}, + workqueue::{self, impl_has_delayed_work, DelayedWork, Work, WorkItem}, }; /// The EPIC notification that writes a property of a sensor service. @@ -43,6 +45,10 @@ const INTERVAL_US: u32 = 20_000; /// How long a direct read waits for the first report of a fresh start. const FIRST_SAMPLE_MS: i64 = 200; const FIRST_SAMPLE_POLL_MS: i64 = 5; +/// How long reports stay on after the last direct read without a buffer, so +/// multi-axis X/Y/Z reads and polling callers share one running stream instead +/// of starting and stopping the service on every sysfs read. +const DIRECT_IDLE_MS: i64 = 2_000; /// The calibration properties of a service and the device tree properties the /// bootloader fills them from. They are written in this order, before the /// report interval. @@ -142,17 +148,101 @@ fn location0_packet(prop: &[u8]) -> Option<&[u8]> { None } -/// Who wants the reports of a service. -#[derive(Default)] -struct Stream { +/// What a stream state change requires from the service. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SyncAction { + None, + /// Enable reports; send calibration packets first when `calibrate` is true. + Start { + calibrate: bool, + }, + Stop, +} + +/// Outcome of checking the direct-read idle deadline. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum IdleStep { + /// No direct-read hold to expire. + Ignore, + /// More reads extended the deadline; re-arm the work for this many ms. + RearmMs(u32), + /// The deadline passed; stop the reports if nothing else wants them. + Expire, +} + +/// Who wants the reports of a service and whether calibration has already been +/// sent in this AOP boot. +struct Stream { + /// Calibration has been accepted or confirmed held in this AOP boot. + calibrated: bool, /// A buffer is enabled. buffer_on: bool, + /// Reports are held on for recent direct reads until this deadline. + direct_until: Option, + /// A start for a direct read failed with this error; direct reads return + /// it without another try until this deadline. + failed_until: Option<(T, Error)>, /// Set across system sleep and after unbind: no reports. parked: bool, - /// The reports were started for the buffer. + /// The reports are currently enabled (interval != 0). active: bool, } +impl Stream { + const fn new() -> Self { + Self { + calibrated: false, + buffer_on: false, + direct_until: None, + failed_until: None, + parked: false, + active: false, + } + } + + fn want(&self) -> bool { + !self.parked && (self.buffer_on || self.direct_until.is_some()) + } + + fn next_action(&self) -> SyncAction { + match (self.want(), self.active) { + (true, false) => SyncAction::Start { + calibrate: !self.calibrated, + }, + (false, true) => SyncAction::Stop, + _ => SyncAction::None, + } + } + + /// Evaluates the direct-read idle deadline given the milliseconds left + /// until it expires (`<= 0` once expired). + fn check_idle(&mut self, remaining_ms: i64) -> IdleStep { + if self.direct_until.is_none() { + return IdleStep::Ignore; + } + if self.parked || self.buffer_on { + self.direct_until = None; + return IdleStep::Ignore; + } + if remaining_ms > 0 { + IdleStep::RearmMs(remaining_ms.clamp(1, DIRECT_IDLE_MS) as u32) + } else { + self.direct_until = None; + IdleStep::Expire + } + } + + /// Returns the error of a failed start for as long as direct reads back + /// off from it, given the milliseconds left until they may try again + /// (`<= 0` once they may). + fn check_backoff(&mut self, remaining_ms: i64) -> Option { + if remaining_ms <= 0 { + self.failed_until = None; + } + self.failed_until.as_ref().map(|(_, e)| *e) + } +} + /// Starts and stops the reports of one service. #[pin_data] struct Control { @@ -162,7 +252,14 @@ struct Control { packets: [KVec; 3], /// Serializes starting and stopping the reports. #[pin] - stream: Mutex, + stream: Mutex>>, + /// Stops direct-read reports once reads go quiet. + #[pin] + idle_work: DelayedWork, +} + +impl_has_delayed_work! { + impl HasDelayedWork for Control { self.idle_work } } impl Control { @@ -190,7 +287,8 @@ impl Control { aop, service, packets, - stream <- new_mutex!(Stream::default()), + stream <- new_mutex!(Stream::new()), + idle_work <- new_delayed_work!("Control::idle_work"), }), GFP_KERNEL, ) @@ -206,6 +304,8 @@ impl Control { .epic_call(&self.service, SUBTYPE_SET_PROPERTY, &msg) } + /// Direct reads back off after a failed start, so they log this at most + /// once per `DIRECT_IDLE_MS`. fn refused(&self, prop: u32, status: u32) -> Error { dev_err!( self.dev, @@ -223,8 +323,10 @@ impl Control { } } - /// Sends the calibration, then the interval that starts the reports. - fn start(&self) -> Result { + /// Sends the three calibration packets. The firmware keeps calibration for + /// the whole AOP boot, so this runs once at probe and conservatively again + /// after firmware suspend, hibernation or restore. + fn calibrate(&self) -> Result { let mut held = 0; for ((prop, _), packet) in CALIBRATION.iter().zip(self.packets.iter()) { let status = self.write(*prop, packet)?; @@ -235,40 +337,88 @@ impl Control { } } if held > 0 { - dev_info!( + dev_dbg!( self.dev, "{} of {} calibration packets kept from an earlier start\n", held, CALIBRATION.len() ); } + Ok(()) + } + + fn start_reports(&self) -> Result { self.set(PROP_INTERVAL, &INTERVAL_US.to_le_bytes()) } - fn stop(&self) -> Result { + fn stop_reports(&self) -> Result { self.set(PROP_INTERVAL, &0u32.to_le_bytes()) } - /// Starts or stops the buffer's reports to match their users. The caller - /// holds the stream lock. - fn sync_locked(&self, s: &mut Stream) -> Result { - match (s.buffer_on && !s.parked, s.active) { - (true, false) => { - self.start()?; + /// Checks once at probe that the service accepts the calibration and the + /// report interval, then leaves the reports off until someone reads them. + fn probe_init(&self) -> Result { + let mut s = self.stream.lock(); + self.calibrate()?; + s.calibrated = true; + self.start_reports()?; + self.stop_reports() + } + + /// Starts or stops the reports to match their users. The caller holds the + /// stream lock. + fn sync_locked(&self, s: &mut Stream>) -> Result { + match s.next_action() { + SyncAction::Start { calibrate } => { + if calibrate { + self.calibrate()?; + s.calibrated = true; + } + self.start_reports()?; s.active = true; Ok(()) } - (false, true) => { + SyncAction::Stop => { + self.stop_reports()?; s.active = false; - self.stop() + Ok(()) } - _ => Ok(()), + SyncAction::None => Ok(()), + } + } + + fn schedule_idle(self: &Arc, delay_ms: u32) { + let _ = + workqueue::system_dfl().enqueue_delayed(self.clone(), time::msecs_to_jiffies(delay_ms)); + } + + fn stop_idle_sync(self: &Arc, disable: bool) { + // SAFETY: `idle_work` is initialized and pinned in this `Arc`. Both + // helpers cancel pending work and join a running callback; the disable + // variant also prevents any later requeue. + let cancelled = unsafe { + let work = Work::raw_get(DelayedWork::raw_as_work(ptr::addr_of!(self.idle_work))); + let delayed = kernel::container_of!(work, bindings::delayed_work, work); + if disable { + bindings::disable_delayed_work_sync(delayed) + } else { + bindings::cancel_delayed_work_sync(delayed) + } + }; + if cancelled { + // SAFETY: A cancelled pending callback owned exactly one `Arc` + // transferred by `enqueue_delayed`. + drop(unsafe { Arc::from_raw(Arc::as_ptr(self)) }); } } fn set_buffer(&self, on: bool) -> Result { let mut s = self.stream.lock(); s.buffer_on = on; + if on { + s.direct_until = None; + s.failed_until = None; + } let ret = self.sync_locked(&mut s); if on && ret.is_err() { // The IIO core does not call predisable after a failed enable. @@ -277,10 +427,56 @@ impl Control { ret } - fn set_parked(&self, parked: bool) -> Result { - let mut s = self.stream.lock(); - s.parked = parked; - self.sync_locked(&mut s) + fn set_parked(self: &Arc, parked: bool, reset_cal: bool) -> Result { + let ret = { + let mut s = self.stream.lock(); + s.parked = parked; + s.failed_until = None; + if parked { + s.direct_until = None; + } else if reset_cal { + s.calibrated = false; + s.active = false; + } + self.sync_locked(&mut s) + }; + if parked { + self.stop_idle_sync(false); + } + ret + } + + fn shutdown(self: &Arc) -> Result { + let ret = { + let mut s = self.stream.lock(); + s.parked = true; + s.direct_until = None; + s.failed_until = None; + self.sync_locked(&mut s) + }; + self.stop_idle_sync(true); + ret + } +} + +impl WorkItem for Control { + type Pointer = Arc; + + fn run(this: Arc) { + let mut s = this.stream.lock(); + let Some(deadline) = s.direct_until else { + return; + }; + let remaining_ms = (deadline - Instant::::now()).as_millis_ceil(); + match s.check_idle(remaining_ms) { + IdleStep::Ignore => {} + IdleStep::RearmMs(delay_ms) => this.schedule_idle(delay_ms), + IdleStep::Expire => { + if let Err(e) = this.sync_locked(&mut s) { + dev_warn!(this.dev, "reports not stopped after idle: {:?}\n", e); + } + } + } } } @@ -312,23 +508,49 @@ struct State { } impl State { - /// Returns the latest sample. Without a buffer the reports are started - /// only for this read and stopped again after it. + /// Returns the latest sample. Without a buffer the reports are started on + /// demand and kept running until direct reads go quiet for + /// `DIRECT_IDLE_MS`. A failed start is not tried again for as long; reads + /// in between return its error. fn read_now(&self) -> Result<[i32; 3]> { - let s = self.control.stream.lock(); - if !s.active { - if s.parked { - return Err(EBUSY); + let mut s = self.control.stream.lock(); + if s.parked { + return Err(EBUSY); + } + if let Some((until, _)) = s.failed_until { + let remaining_ms = (until - Instant::::now()).as_millis_ceil(); + if let Some(e) = s.check_backoff(remaining_ms) { + return Err(e); } + } + let started = !s.active; + if started { // A sample from an earlier start may be stale. self.sample.lock().valid = false; - self.control.start()?; + } + if !s.buffer_on { + s.direct_until = Some(Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS)); + } + if let Err(e) = self.control.sync_locked(&mut s) { + s.direct_until = None; + // Polling readers must not repeat a failing start at their rate. + let until = Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS); + s.failed_until = Some((until, e)); + return Err(e); + } + if started { let mut waited = 0; while waited < FIRST_SAMPLE_MS && !self.sample.lock().valid { fsleep(Delta::from_millis(FIRST_SAMPLE_POLL_MS)); waited += FIRST_SAMPLE_POLL_MS; } - self.control.stop()?; + if !s.buffer_on { + s.direct_until = + Some(Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS)); + } + } + if !s.buffer_on { + self.control.schedule_idle(DIRECT_IDLE_MS as u32); } let sample = *self.sample.lock(); if sample.valid { @@ -512,10 +734,40 @@ struct Spec { _p: PhantomPinned, } +/// Owns the IIO device and what it points to. +/// +/// It is handed to the platform device's resources right after the +/// allocation. Those are released in reverse order, so the IIO device is +/// freed after the trigger and the triggered buffer, whose release still +/// uses it, and after the driver's own data is gone. +struct IioAlloc { + dev: *mut bindings::iio_dev, + _spec: Pin>, +} + +impl Drop for IioAlloc { + fn drop(&mut self) { + // SAFETY: `self.dev` was allocated in `MotionIio::new()` with an + // `Arc` as its private data. `MotionIio` has unregistered it + // and the resources registered after this one are released, so + // nothing uses either after this. + unsafe { + drop(Arc::::from_foreign((*self.dev).priv_.cast())); + bindings::iio_device_free(self.dev); + } + } +} + +// SAFETY: The IIO device may be freed from any thread, and the channel +// table is only read. +unsafe impl Send for IioAlloc {} + /// The IIO device of a service, with its buffer. +/// +/// The device itself belongs to the platform device's resources, which are +/// released after the driver's data; this only takes it out of view again. struct MotionIio { dev: *mut bindings::iio_dev, - _spec: Pin>, registered: bool, } @@ -523,11 +775,10 @@ impl MotionIio { /// Allocates the device and its buffer; [`MotionIio::register`] makes it /// visible. fn new( - pdev: &platform::Device>, + dev: &device::Device, kind: &'static Kind, control: Arc, ) -> Result<(Self, Arc)> { - let dev = pdev.as_ref(); let spec = KBox::pin( Spec { channels: [ @@ -579,9 +830,20 @@ impl MotionIio { (*indio_dev).modes = bindings::INDIO_DIRECT_MODE as i32; (*indio_dev).available_scan_masks = SCAN_MASKS.as_ptr(); } + // From here the device, its private data and `spec` are freed with + // the resources of `dev`, also if this fails. It has to come before + // the trigger and the buffer: resources are released in reverse + // order, and the release of those two uses the IIO device. + devres::register( + dev, + IioAlloc { + dev: indio_dev, + _spec: spec, + }, + GFP_KERNEL, + )?; let this = Self { dev: indio_dev, - _spec: spec, registered: false, }; // The buffer fills as the AOP reports, so the trigger never fires. @@ -603,9 +865,9 @@ impl MotionIio { if trig.is_null() { return Err(ENOMEM); } - // SAFETY: `trig` was allocated above; it is unregistered and freed - // with the platform device's resources, after the IIO device that - // holds a reference to it. + // SAFETY: `trig` was allocated above; it is unregistered with the + // platform device's resources, before the IIO device is freed. The + // IIO device holds its own reference to it until then. let ret = unsafe { bindings::devm_iio_trigger_register(dev.as_raw(), trig) }; if ret < 0 { return Err(Error::from_errno(ret)); @@ -614,10 +876,11 @@ impl MotionIio { // here is dropped when the IIO device is released. unsafe { (*indio_dev).trig = bindings::iio_trigger_get(trig) }; // SAFETY: Both devices are valid. The buffer is released with the - // platform device's resources; the IIO device holds its own - // reference to it until it is freed. The poll function only stamps - // the time and completes the trigger; the report listener pushes the - // scans. The setup ops start the reports for the buffer. + // platform device's resources, before the IIO device, which that + // release reads the buffer and the poll function from. The poll + // function only stamps the time and completes the trigger; the + // report listener pushes the scans. The setup ops start the reports + // for the buffer. let ret = unsafe { bindings::devm_iio_triggered_buffer_setup_ext( dev.as_raw(), @@ -649,14 +912,11 @@ impl MotionIio { impl Drop for MotionIio { fn drop(&mut self) { - // SAFETY: `self.dev` was allocated in `new()` with an `Arc` - // as its private data, and nothing uses it after this. - unsafe { - if self.registered { - bindings::iio_device_unregister(self.dev); - } - drop(Arc::::from_foreign((*self.dev).priv_.cast())); - bindings::iio_device_free(self.dev); + if self.registered { + // SAFETY: `self.dev` was registered by `register()`. It is + // freed with the platform device's resources, which outlive + // this. + unsafe { bindings::iio_device_unregister(self.dev) }; } } } @@ -690,10 +950,22 @@ unsafe extern "C" fn pm_event( // SAFETY: `nb` is the first field of a registered `PmHook`. let hook = unsafe { &*nb.cast::() }; let ret = match action as u32 { - bindings::PM_SUSPEND_PREPARE | bindings::PM_HIBERNATION_PREPARE => { - hook.control.set_parked(true) + bindings::PM_SUSPEND_PREPARE + | bindings::PM_HIBERNATION_PREPARE + | bindings::PM_RESTORE_PREPARE => hook.control.set_parked(true, false), + // On s2idle the AOP core does nothing so calibration stays valid. + // Across firmware suspend, the AOP may have reset, so clear + // calibration conservatively; firmware that kept it answers packets + // 75/76 with STATUS_UNSUPPORTED once on the next start. + bindings::PM_POST_SUSPEND => { + // SAFETY: Reads the PM core's sleep-transition flag, which stays + // set until the next suspend entry. + let fw_sleep = unsafe { bindings::pm_suspend_via_firmware() }; + hook.control.set_parked(false, fw_sleep) + } + bindings::PM_POST_HIBERNATION | bindings::PM_POST_RESTORE => { + hook.control.set_parked(false, true) } - bindings::PM_POST_SUSPEND | bindings::PM_POST_HIBERNATION => hook.control.set_parked(false), _ => return bindings::NOTIFY_DONE as c_int, }; if let Err(e) = ret { @@ -829,14 +1101,17 @@ impl platform::Driver for IIOAopMotionDriver { let service = unsafe { *service }; let control = Control::new(dev, aop.clone(), service)?; - let (mut iio, state) = MotionIio::new(pdev, kind, control.clone())?; + let (mut iio, state) = MotionIio::new(dev, kind, control.clone())?; let listener = FakehidRegistration::new(aop, service, state)?; let pm = PmHook::new(control.clone())?; // Check once that the service takes the calibration and the interval, // then leave the reports off until someone reads them. - control.start()?; - control.stop()?; - iio.register()?; + control.probe_init()?; + if let Err(e) = iio.register() { + pm.unregister(); + let _ = control.shutdown(); + return Err(e); + } Ok(IIOAopMotionDriver { pm, listener, @@ -847,7 +1122,7 @@ impl platform::Driver for IIOAopMotionDriver { fn unbind(_dev: &platform::Device>, this: Pin<&Self>) { this.pm.unregister(); - let _ = this.control.set_parked(true); + let _ = this.control.shutdown(); this.listener.unregister(); } } @@ -859,3 +1134,155 @@ module_platform_driver! { license: "Dual MIT/GPL", alias: ["platform:iio_aop_motion"], } + +#[kunit_tests(iio_aop_motion)] +mod tests { + use super::*; + use kernel::{ + faux, + soc::apple::aop::{ReportListener, SourceRing}, + }; + + /// Stands in for the AOP core. The private data of the IIO device holds + /// the last reference to it once the test has dropped its own, so it + /// goes when that private data is freed, and notes that in `gone`. + struct FakeAop { + gone: Arc>, + } + + impl Drop for FakeAop { + fn drop(&mut self) { + self.gone.store(true, Relaxed); + } + } + + impl AOP for FakeAop { + fn epic_call(&self, _svc: &EPICService, _subtype: u16, _msg: &[u8]) -> Result { + Ok(0) + } + fn epic_call_ret( + &self, + _svc: &EPICService, + _subtype: u16, + _msg: &[u8], + _ret_len: usize, + ) -> Result<(u32, KVec)> { + Err(ENODEV) + } + fn add_fakehid_listener( + &self, + _svc: EPICService, + _listener: Arc, + ) -> Result<()> { + Err(ENODEV) + } + fn remove_fakehid_listener(&self, _svc: &EPICService) -> bool { + false + } + fn add_report_listener( + &self, + _svc: EPICService, + _subtype: u16, + _listener: Arc, + ) -> Result<()> { + Err(ENODEV) + } + fn remove_report_listener(&self, _svc: &EPICService, _subtype: u16) -> bool { + false + } + fn source_ring( + &self, + _dev: &device::Device, + _size: usize, + ) -> Result> { + Err(ENODEV) + } + fn bound_ring( + &self, + _dev: &device::Device, + _size: usize, + _bind: &mut dyn FnMut(u64, u64) -> Result<()>, + ) -> Result> { + Err(ENODEV) + } + fn remove(&self) {} + } + + /// A device resource registered after the IIO device is set up, so that + /// it is released first: it notes whether the IIO device's private data + /// was already freed when the release of the resources began. + struct ReleaseStart { + gone: Arc>, + ran: Arc>, + gone_before: Arc>, + } + + impl Drop for ReleaseStart { + fn drop(&mut self) { + self.gone_before.store(self.gone.load(Relaxed), Relaxed); + self.ran.store(true, Relaxed); + } + } + + /// The IIO device and its private data stay until the resources of the + /// parent device, among them the triggered buffer and the trigger, are + /// released; dropping `MotionIio`, as a failed probe and an unbind do + /// before that release, does not free them. + #[test] + fn iio_device_is_freed_with_the_device_resources() -> Result { + let gone = Arc::new(Atomic::new(false), GFP_KERNEL)?; + let ran = Arc::new(Atomic::new(false), GFP_KERNEL)?; + let gone_before = Arc::new(Atomic::new(false), GFP_KERNEL)?; + + let reg = faux::Registration::new(c"iio-aop-motion-kunit", None)?; + let fdev: &faux::Device = reg.as_ref(); + let dev: &device::Device = fdev.as_ref(); + let plain: &device::Device = dev; + let aop: Arc = Arc::new(FakeAop { gone: gone.clone() }, GFP_KERNEL)?; + let control = Arc::pin_init( + pin_init!(Control { + dev: plain.into(), + aop, + service: EPICService { + channel: 0, + endpoint: 0, + }, + packets: [KVec::new(), KVec::new(), KVec::new()], + stream <- new_mutex!(Stream::default()), + }), + GFP_KERNEL, + )?; + let (iio, state) = MotionIio::new(dev, &ACCEL, control.clone())?; + // The test's own reference keeps the memory of the IIO device valid + // whoever drops the allocation's reference, and whenever. + let indio_dev = iio.dev; + // SAFETY: `indio_dev` was just allocated and is live. + unsafe { bindings::get_device(&raw mut (*indio_dev).dev) }; + let started = devres::register( + dev, + ReleaseStart { + gone: gone.clone(), + ran: ran.clone(), + gone_before: gone_before.clone(), + }, + GFP_KERNEL, + ); + + drop(state); + drop(control); + drop(iio); + let gone_after_drop = gone.load(Relaxed); + // Unbinds the device, which releases its resources. + drop(reg); + let gone_after_release = gone.load(Relaxed); + // SAFETY: Drops the reference taken above. + unsafe { bindings::put_device(&raw mut (*indio_dev).dev) }; + + started?; + assert!(!gone_after_drop); + assert!(ran.load(Relaxed)); + assert!(!gone_before.load(Relaxed)); + assert!(gone_after_release); + Ok(()) + } +} diff --git a/drivers/iio/common/aop_sensors/aop_temp.rs b/drivers/iio/common/aop_sensors/aop_temp.rs index e74ddb231ec4ab..af4ba06224e523 100644 --- a/drivers/iio/common/aop_sensors/aop_temp.rs +++ b/drivers/iio/common/aop_sensors/aop_temp.rs @@ -6,6 +6,10 @@ //! Its fake-HID report carries a signed Q16.16 Celsius value and an AOP //! timestamp. Calibration data, when supplied by the bootloader, is sent //! unchanged before reports are enabled. +//! +//! The AOP core creates a device for the service whenever the firmware +//! announces it, and the driver binds to that device by name. A device tree +//! node for the service is optional; it only carries the calibration. use core::{ ffi::{c_int, c_void}, @@ -16,7 +20,7 @@ use core::{ use kernel::{ bindings, c_str, device::{self, Core}, - module_platform_driver, new_spinlock, of, platform, + driver, new_spinlock, of, platform, prelude::*, soc::apple::aop::{EPICService, FakehidListener, FakehidRegistration, AOP}, sync::{ @@ -25,6 +29,7 @@ use kernel::{ Arc, SpinLock, }, types::{ForeignOwnable, Opaque}, + ThisModule, }; const SUBTYPE_SET_PROPERTY: u16 = 4; @@ -81,23 +86,26 @@ struct Control { impl Control { fn new(dev: &device::Device, aop: Arc, service: EPICService) -> Result> { - let node = dev.fwnode().ok_or(ENODEV)?; let mut packets = KVec::new(); - for (prop, name) in CALIBRATION { - if !node.property_present(name) { - continue; + // Without a device tree node for the service there is no calibration + // to send; the sensor then runs on its defaults. + if let Some(node) = dev.fwnode() { + for (prop, name) in CALIBRATION { + if !node.property_present(name) { + continue; + } + let len = node.property_count_elem::(name)?; + let data = node + .property_read_array_vec::(name, len)? + .required_by(dev)?; + let Some(packet) = location0_packet(&data) else { + dev_err!(dev, "{:?} holds no calibration for location 0\n", name); + return Err(EINVAL); + }; + let mut owned = KVec::new(); + owned.extend_from_slice(packet, GFP_KERNEL)?; + packets.push((prop, owned), GFP_KERNEL)?; } - let len = node.property_count_elem::(name)?; - let data = node - .property_read_array_vec::(name, len)? - .required_by(dev)?; - let Some(packet) = location0_packet(&data) else { - dev_err!(dev, "{:?} holds no calibration for location 0\n", name); - return Err(EINVAL); - }; - let mut owned = KVec::new(); - owned.extend_from_slice(packet, GFP_KERNEL)?; - packets.push((prop, owned), GFP_KERNEL)?; } if packets.is_empty() { dev_dbg!( @@ -562,10 +570,30 @@ impl platform::Driver for IIOAopTempDriver { } } -module_platform_driver! { - type: IIOAopTempDriver, +/// The AOP core creates the device of a service, named after the service, +/// whenever the firmware announces that service. Registering the driver under +/// the same name lets the platform bus bind it on every machine whose AOP +/// offers the service, with or without a device tree node for it. +const SERVICE_NAME: &CStr = c_str!("als-temp"); + +#[pin_data] +struct IIOAopTempModule { + #[pin] + _driver: driver::Registration>, +} + +impl kernel::InPlaceModule for IIOAopTempModule { + fn init(module: &'static ThisModule) -> impl PinInit { + try_pin_init!(Self { + _driver <- driver::Registration::new(SERVICE_NAME, module), + }) + } +} + +module! { + type: IIOAopTempModule, name: "iio_aop_temp", description: "AOP temperature sensor driver", license: "Dual MIT/GPL", - alias: ["platform:iio_aop_temp"], + alias: ["platform:als-temp"], } diff --git a/drivers/input/misc/Kconfig b/drivers/input/misc/Kconfig index aad2bc5fb0eb63..d7844492bdec12 100644 --- a/drivers/input/misc/Kconfig +++ b/drivers/input/misc/Kconfig @@ -1034,4 +1034,19 @@ config INPUT_MACSMC_INPUT To compile this driver as a module, choose M here: the module will be called macsmc-input. +config INPUT_MACSMC_INPUT_KUNIT_TEST + bool "KUnit tests for the Apple SMC lid/buttons driver" if !KUNIT_ALL_TESTS + depends on INPUT_MACSMC_INPUT=y && KUNIT=y + depends on MFD_MACSMC_KUNIT_TEST && SUSPEND + default KUNIT_ALL_TESTS + help + Build tests for the Apple SMC input driver: the decoding of the + SMC's power button and lid notifications, and their handling as + wake events while the system goes to sleep, including the lid-open + check against MSLD and the settle time. A static stub replaces SMC + reads, so the tests need no Apple hardware. + The tests report power button presses and lid changes through an + input device and change global suspend state, so they run only at + boot, before user space, and skip when run later. + endif diff --git a/drivers/input/misc/macsmc-input-test.c b/drivers/input/misc/macsmc-input-test.c new file mode 100644 index 00000000000000..5e1dedd0ab3be9 --- /dev/null +++ b/drivers/input/misc/macsmc-input-test.c @@ -0,0 +1,414 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SMC input driver: decoding of the SMC's button + * and lid notifications into KEY_POWER and SW_LID, and the sleep window in + * which they are wake events instead, with the lid-open confirmation + * against MSLD and the settle time. + * + * MSLD reads go to a static stub on apple_smc_read() (see + * MFD_MACSMC_KUNIT_TEST). Events go to a registered input device; wakeups + * are seen on the device's wakeup source and, for hard wakeups, through + * pm_wakeup_pending(). + * + * The cases touch global PM state (pm_abort_suspend, the dark wake flag) + * and report KEY_POWER and SW_LID through a real input device, which a + * running system's logind would act on by powering off or suspending. So + * the suite runs only at boot, before user space; run later (from the + * kunit debugfs interface or a module) it skips every case. + * + * Included by macsmc-input.c. + */ + +#include +#include +#include + +#define INPUT_TEST_EV(type, hi, lo) (((type) << 16) | ((hi) << 8) | (lo)) +#define INPUT_TEST_BTN(button, state) INPUT_TEST_EV(SMC_EV_BTN, button, state) +#define INPUT_TEST_LID(closed, lo) INPUT_TEST_EV(SMC_EV_LID, closed, lo) + +struct macsmc_input_test { + struct apple_smc smc; + u8 shmem[256]; + struct macsmc_input smcin; + /* MSLD: 1 while the lid is closed, and what its read returns */ + u8 msld; + int msld_ret; + unsigned int msld_reads; + unsigned int saved_flags; +}; + +static int macsmc_input_test_read(struct apple_smc *smc, smc_key key, void *buf, + size_t size) +{ + struct macsmc_input_test *ctx = container_of(smc, struct macsmc_input_test, smc); + struct kunit *test = kunit_get_current_test(); + + KUNIT_EXPECT_EQ(test, key, SMC_KEY(MSLD)); + KUNIT_EXPECT_EQ(test, size, 1); + ctx->msld_reads++; + if (ctx->msld_ret < 0) + return ctx->msld_ret; + *(u8 *)buf = ctx->msld; + return size; +} + +static void macsmc_input_test_exit(void *data) +{ + struct macsmc_input_test *ctx = data; + + pm_suspend_global_flags = ctx->saved_flags; + pm_wakeup_clear(0); +} + +static struct macsmc_input_test *macsmc_input_test_setup(struct kunit *test) +{ + struct macsmc_input_test *ctx; + struct macsmc_input *smcin; + struct device *dev; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + mutex_init(&ctx->smc.mutex); + spin_lock_init(&ctx->smc.lock); + /* SMC commands other than the stubbed read fail: key_exists() is false. */ + ctx->smc.shmem.iomem = (void __force __iomem *)ctx->shmem; + ctx->saved_flags = pm_suspend_global_flags; + pm_wakeup_clear(0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_input_test_exit, ctx), 0); + + dev = kunit_device_register(test, "input"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + KUNIT_ASSERT_EQ(test, devm_device_init_wakeup(dev), 0); + + smcin = &ctx->smcin; + smcin->dev = dev; + smcin->smc = &ctx->smc; + smcin->nb.notifier_call = macsmc_input_event; + smcin->pm_nb.notifier_call = macsmc_input_pm_notify; + mutex_init(&smcin->lid_lock); + dev_set_drvdata(dev, smcin); + + smcin->input = devm_input_allocate_device(dev); + KUNIT_ASSERT_NOT_NULL(test, smcin->input); + smcin->input->name = "macsmc-input-test"; + input_set_capability(smcin->input, EV_SW, SW_LID); + input_set_capability(smcin->input, EV_KEY, KEY_POWER); + KUNIT_ASSERT_EQ(test, input_register_device(smcin->input), 0); + + kunit_activate_static_stub(test, apple_smc_read, macsmc_input_test_read); + return ctx; +} + +static int macsmc_input_test_event(struct macsmc_input_test *ctx, unsigned long event) +{ + return macsmc_input_event(&ctx->smcin.nb, event, NULL); +} + +static bool macsmc_input_test_key(struct macsmc_input_test *ctx) +{ + return test_bit(KEY_POWER, ctx->smcin.input->key); +} + +static bool macsmc_input_test_lid(struct macsmc_input_test *ctx) +{ + return test_bit(SW_LID, ctx->smcin.input->sw); +} + +static unsigned long macsmc_input_test_wake_events(struct macsmc_input_test *ctx) +{ + return ctx->smcin.dev->power.wakeup->event_count; +} + +/* Was a hard wakeup (one that aborts a suspend) asked for? Clears it. */ +static bool macsmc_input_test_hard_wake(void) +{ + bool pending = pm_wakeup_pending(); + + pm_wakeup_clear(0); + return pending; +} + +static void macsmc_input_test_sleep(struct macsmc_input_test *ctx, unsigned int settle_ms, + unsigned int slept_ms) +{ + ctx->smcin.lid_settle_ms = settle_ms; + ctx->smcin.wakeup_mode = true; + ctx->smcin.sleep_start = ktime_sub_ms(ktime_get_boottime(), slept_ms); +} + +/* Only the button and lid event types are this driver's. */ +static void macsmc_input_test_dispatch(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_EV(0x7202, 0x01, 0x01)), + NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_EV(0x7101, 0x01, 0x01)), + NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_EV(0x0000, 0x01, 0x01)), + NOTIFY_DONE); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_lid(ctx)); + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 0); + + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 1)), + NOTIFY_OK); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)), NOTIFY_OK); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); +} + +/* Power and Touch ID buttons: bits 15:8 the button, any nonzero low byte is down. */ +static void macsmc_input_test_power_button(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 1)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_key(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_TOUCHID, 0x80)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_key(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_TOUCHID, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + + /* Awake, presses are wakeup events but never hard wakeups. */ + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 4); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); +} + +/* "Held" notices and unknown buttons are not key presses. */ +static void macsmc_input_test_other_buttons(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER_HELD_SHORT, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + /* The long hold's release, never its press: that powers off. */ + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER_HELD_LONG, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(0x07, 1)); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(0x02, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 0); +} + +/* In the sleep window a press is a hard wakeup and no KEY_POWER. */ +static void macsmc_input_test_button_in_sleep(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_sleep(ctx, 0, 0); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_TOUCHID, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + + /* A release does not wake. */ + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_TOUCHID, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 2); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 0); +} + +/* Lid: bits 15:8 nonzero is closed; the low byte is not the state. */ +static void macsmc_input_test_lid_awake(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_lid(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0x80, 0)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 0xff)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_lid(ctx)); + + /* Awake, MSLD is not consulted and nothing is a hard wakeup. */ + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 0); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); +} + +/* Closing the lid in the sleep window is neither reported nor a wakeup. */ +static void macsmc_input_test_lid_close_in_sleep(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_sleep(ctx, 0, 0); + macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_lid(ctx)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 0); + KUNIT_EXPECT_FALSE(test, ctx->smcin.lid_held); +} + +/* An open report while MSLD still says closed is held, not a wakeup. */ +static void macsmc_input_test_lid_open_msld_closed(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)); + macsmc_input_test_sleep(ctx, 0, 5000); + ctx->msld = 1; + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 1); + KUNIT_EXPECT_TRUE(test, ctx->smcin.lid_held); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 1); +} + +/* With a settle time, an open within it is held; after it, it wakes. */ +static void macsmc_input_test_lid_open_settle(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)); + macsmc_input_test_sleep(ctx, LID_WAKE_SETTLE_MS_J716S, 0); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_TRUE(test, ctx->smcin.lid_held); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); + + ctx->smcin.lid_held = false; + ctx->smcin.sleep_start = ktime_sub_ms(ktime_get_boottime(), + LID_WAKE_SETTLE_MS_J716S + 500); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_FALSE(test, ctx->smcin.lid_held); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + /* Reported by .complete from MSLD, not here. */ + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 2); +} + +/* Without a settle time an open with MSLD open wakes at once. */ +static void macsmc_input_test_lid_open_wakes(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_sleep(ctx, 0, 0); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_FALSE(test, ctx->smcin.lid_held); + + /* An unreadable MSLD does not hold the report back. */ + ctx->msld_ret = -ETIMEDOUT; + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_FALSE(test, ctx->smcin.lid_held); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 2); +} + +/* The PM notifier opens the window at PM_SUSPEND_PREPARE and closes it after. */ +static void macsmc_input_test_pm_notify(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + struct macsmc_input *smcin = &ctx->smcin; + ktime_t before = ktime_get_boottime(); + + smcin->lid_held = true; + KUNIT_EXPECT_EQ(test, macsmc_input_pm_notify(&smcin->pm_nb, PM_SUSPEND_PREPARE, NULL), + NOTIFY_DONE); + KUNIT_EXPECT_TRUE(test, smcin->wakeup_mode); + KUNIT_EXPECT_FALSE(test, smcin->lid_held); + KUNIT_EXPECT_GE(test, ktime_to_ns(smcin->sleep_start), ktime_to_ns(before)); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + + smcin->dark = true; + smcin->lid_held = true; + KUNIT_EXPECT_EQ(test, macsmc_input_pm_notify(&smcin->pm_nb, PM_POST_SUSPEND, NULL), + NOTIFY_DONE); + KUNIT_EXPECT_FALSE(test, smcin->wakeup_mode); + KUNIT_EXPECT_FALSE(test, smcin->dark); + KUNIT_EXPECT_FALSE(test, smcin->lid_held); + + /* Other actions change nothing. */ + macsmc_input_pm_notify(&smcin->pm_nb, PM_HIBERNATION_PREPARE, NULL); + KUNIT_EXPECT_FALSE(test, smcin->wakeup_mode); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 1)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); +} + +/* .prepare opens the window; a full .complete closes it and drops a held open. */ +static void macsmc_input_test_pm_prepare_complete(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + struct macsmc_input *smcin = &ctx->smcin; + + pm_suspend_global_flags &= ~PM_SUSPEND_FLAG_DARK_WAKE; + KUNIT_EXPECT_EQ(test, macsmc_input_pm_prepare(smcin->dev), 0); + KUNIT_EXPECT_TRUE(test, smcin->wakeup_mode); + + smcin->lid_held = true; + macsmc_input_pm_complete(smcin->dev); + KUNIT_EXPECT_FALSE(test, smcin->wakeup_mode); + KUNIT_EXPECT_FALSE(test, smcin->lid_held); + KUNIT_EXPECT_FALSE(test, smcin->dark); +} + +/* + * A dark wake keeps the window and the held open, and marks the next + * .prepare to recheck the lid unless MSLD reads open. + */ +static void macsmc_input_test_pm_dark_wake(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + struct macsmc_input *smcin = &ctx->smcin; + + KUNIT_EXPECT_EQ(test, macsmc_input_pm_prepare(smcin->dev), 0); + smcin->lid_held = true; + pm_set_dark_wake(); + + ctx->msld = 1; + macsmc_input_pm_complete(smcin->dev); + KUNIT_EXPECT_TRUE(test, smcin->wakeup_mode); + KUNIT_EXPECT_TRUE(test, smcin->lid_held); + KUNIT_EXPECT_TRUE(test, smcin->dark); + + ctx->msld = 0; + macsmc_input_pm_complete(smcin->dev); + KUNIT_EXPECT_FALSE(test, smcin->dark); + + ctx->msld_ret = -EIO; + macsmc_input_pm_complete(smcin->dev); + KUNIT_EXPECT_TRUE(test, smcin->dark); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 3); + KUNIT_EXPECT_TRUE(test, smcin->wakeup_mode); +} + +static int macsmc_input_test_init(struct kunit *test) +{ + if (system_state == SYSTEM_RUNNING) + kunit_skip(test, "reports KEY_POWER/SW_LID and changes PM state: boot only"); + return 0; +} + +static struct kunit_case macsmc_input_test_cases[] = { + KUNIT_CASE(macsmc_input_test_dispatch), + KUNIT_CASE(macsmc_input_test_power_button), + KUNIT_CASE(macsmc_input_test_other_buttons), + KUNIT_CASE(macsmc_input_test_button_in_sleep), + KUNIT_CASE(macsmc_input_test_lid_awake), + KUNIT_CASE(macsmc_input_test_lid_close_in_sleep), + KUNIT_CASE(macsmc_input_test_lid_open_msld_closed), + KUNIT_CASE(macsmc_input_test_lid_open_settle), + KUNIT_CASE(macsmc_input_test_lid_open_wakes), + KUNIT_CASE(macsmc_input_test_pm_notify), + KUNIT_CASE(macsmc_input_test_pm_prepare_complete), + KUNIT_CASE(macsmc_input_test_pm_dark_wake), + {} +}; + +static struct kunit_suite macsmc_input_test_suite = { + .name = "macsmc-input", + .init = macsmc_input_test_init, + .test_cases = macsmc_input_test_cases, +}; + +kunit_test_suite(macsmc_input_test_suite); diff --git a/drivers/input/misc/macsmc-input.c b/drivers/input/misc/macsmc-input.c index 0971ac3085c29c..eaf7655832dbc0 100644 --- a/drivers/input/misc/macsmc-input.c +++ b/drivers/input/misc/macsmc-input.c @@ -401,3 +401,7 @@ MODULE_AUTHOR("Hector Martin "); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple SMC input driver"); MODULE_ALIAS("platform:macsmc-input"); + +#if IS_ENABLED(CONFIG_INPUT_MACSMC_INPUT_KUNIT_TEST) +#include "macsmc-input-test.c" +#endif diff --git a/drivers/input/misc/macsmc-input.kunitconfig b/drivers/input/misc/macsmc-input.kunitconfig new file mode 100644 index 00000000000000..7f809e65a57300 --- /dev/null +++ b/drivers/input/misc/macsmc-input.kunitconfig @@ -0,0 +1,15 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/input/misc/macsmc-input.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_PM=y +CONFIG_SUSPEND=y +CONFIG_INPUT=y +CONFIG_INPUT_MISC=y +CONFIG_INPUT_MACSMC_INPUT=y +CONFIG_INPUT_MACSMC_INPUT_KUNIT_TEST=y diff --git a/drivers/input/touchscreen/Kconfig b/drivers/input/touchscreen/Kconfig index 9b9ae8ac3f7fd3..b11e8c16c9aa99 100644 --- a/drivers/input/touchscreen/Kconfig +++ b/drivers/input/touchscreen/Kconfig @@ -115,6 +115,20 @@ config TOUCHSCREEN_APPLE_Z2 To compile this driver as a module, choose M here: the module will be called apple_z2. +config TOUCHSCREEN_APPLE_Z2_KUNIT_TEST + bool "KUnit tests for the Apple Z2 touchscreen driver" if !KUNIT_ALL_TESTS + depends on TOUCHSCREEN_APPLE_Z2=y && KUNIT=y + default KUNIT_ALL_TESTS + help + Build tests for the Apple Z2 touchscreen driver: the parsing of + touch reports into multitouch input events, including reports that + are shorter than their finger count claims, the framing of interrupt + data packets, and the firmware and calibration upload. A fake SPI + controller stands in for the touch controller and the firmware + images are synthetic, so the tests need no Apple hardware. + + If unsure, say N. + config TOUCHSCREEN_AR1021_I2C tristate "Microchip AR1020/1021 i2c touchscreen" depends on I2C && OF diff --git a/drivers/input/touchscreen/apple_z2-test.c b/drivers/input/touchscreen/apple_z2-test.c new file mode 100644 index 00000000000000..61ee4f201e8f0c --- /dev/null +++ b/drivers/input/touchscreen/apple_z2-test.c @@ -0,0 +1,1284 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the Apple Z2 touchscreen driver + * + * This file is included at the end of apple_z2.c so that it can call the + * driver's static functions. The device is replaced by a fake SPI controller + * registered on a KUnit device: its transfer_one() plays the touch controller + * (interrupt data command, packet read, firmware blobs). Touch reports end up + * in a real registered input device and an input handler captures the events. + * Firmware images are synthetic and handed to the upload as struct firmware, + * so no file system is needed. + */ + +#include +#include +#include +#include + +/* Size of the receive buffer that apple_z2_probe() allocates */ +#define Z2_TEST_RX_SIZE APPLE_Z2_RX_BUF_SIZE +/* + * The test's receive buffer is much larger than the driver's, so that a read + * with a hostile length stays inside the allocation and can be checked. + */ +#define Z2_TEST_RX_ALLOC (SZ_64K + SZ_4K) +#define Z2_TEST_MSG_ALLOC SZ_8K +/* Bytes in front of the touch report in an interrupt data packet */ +#define Z2_TEST_PKT_HDR 5 +#define Z2_TEST_FINGER_LEN 30 +#define Z2_TEST_MAX_EVENTS 4096 +#define Z2_TEST_MAX_XFERS 32 +#define Z2_TEST_TX_LOG 64 +#define Z2_TEST_STATE_LIFTED 7 + +struct z2_test_event { + u16 type; + u16 code; + s32 value; +}; + +struct z2_test_xfer { + unsigned int len; + u8 bpw; + bool has_tx; + bool has_rx; + u8 tx[Z2_TEST_TX_LOG]; +}; + +struct z2_test_cfg { + u32 size_x; + u32 size_y; + bool invert_x; + bool invert_y; + bool swap_x_y; + const u8 *cal; + size_t cal_len; +}; + +struct z2_test_finger { + u8 key; + u8 state; + u16 x; + u16 y; + u16 tool_major; + u16 tool_minor; + u16 orientation; + u16 touch_major; + u16 touch_minor; +}; + +struct z2_test_ctx { + struct apple_z2 z2; + struct input_handler handler; + struct input_handle handle; + struct software_node swnode; + struct property_entry props[8]; + + /* Touch report under construction */ + u8 *msg; + + /* Captured input events */ + struct z2_test_event *events; + unsigned int nevents; + + /* Fake device: log of the transfers it has seen */ + struct z2_test_xfer xfers[Z2_TEST_MAX_XFERS]; + unsigned int nxfers; + size_t max_rx_len; + /* Fail the transfer with this index, -1 for none */ + int fail_xfer; + /* Fake device: pending interrupt data packet */ + bool pkt_ready; + u16 pkt_wire_len; + u8 *pkt; + size_t pkt_len; +}; + +static const struct z2_test_cfg z2_test_cfg_plain = { + .size_x = 2000, + .size_y = 600, +}; + +/* The fake touch controller */ +static int z2_test_transfer_one(struct spi_controller *ctlr, + struct spi_device *spi, + struct spi_transfer *xfer) +{ + struct z2_test_ctx *ctx = spi_controller_get_devdata(ctlr); + unsigned int idx = ctx->nxfers++; + const u8 *tx = xfer->tx_buf; + u8 *rx = xfer->rx_buf; + + if (idx < Z2_TEST_MAX_XFERS) { + struct z2_test_xfer *rec = &ctx->xfers[idx]; + + rec->len = xfer->len; + rec->bpw = xfer->bits_per_word; + rec->has_tx = tx; + rec->has_rx = rx; + if (tx) + memcpy(rec->tx, tx, min(xfer->len, Z2_TEST_TX_LOG)); + } + + if (ctx->fail_xfer >= 0 && idx == ctx->fail_xfer) + return -EIO; + + if (tx && rx) { + /* Interrupt data command: answer with the pending length */ + memset(rx, 0, xfer->len); + if (tx[0] == APPLE_Z2_CMD_READ_INTERRUPT_DATA && + ctx->pkt_ready && xfer->len >= 3) { + rx[0] = APPLE_Z2_REPLY_INTERRUPT_DATA; + put_unaligned_le16(ctx->pkt_wire_len, rx + 1); + } + } else if (rx) { + /* Packet read: only the packet's own bytes are written */ + ctx->max_rx_len = max(ctx->max_rx_len, xfer->len); + memcpy(rx, ctx->pkt, + min3((size_t)xfer->len, ctx->pkt_len, + (size_t)Z2_TEST_RX_ALLOC)); + ctx->pkt_ready = false; + } else if (tx && xfer->len == 2) { + /* Firmware blob acknowledge: the device raises its interrupt */ + complete(&ctx->z2.boot_irq); + } + + return 0; +} + +static void z2_test_event(struct input_handle *handle, unsigned int type, + unsigned int code, int value) +{ + struct z2_test_ctx *ctx = handle->handler->private; + + if (ctx->nevents < Z2_TEST_MAX_EVENTS) { + ctx->events[ctx->nevents].type = type; + ctx->events[ctx->nevents].code = code; + ctx->events[ctx->nevents].value = value; + } + ctx->nevents++; +} + +static int z2_test_connect(struct input_handler *handler, + struct input_dev *dev, + const struct input_device_id *id) +{ + struct z2_test_ctx *ctx = handler->private; + int error; + + if (dev != ctx->z2.input_dev) + return -ENODEV; + + ctx->handle.dev = dev; + ctx->handle.handler = handler; + ctx->handle.name = "apple-z2-kunit"; + + error = input_register_handle(&ctx->handle); + if (error) + return error; + + error = input_open_device(&ctx->handle); + if (error) + input_unregister_handle(&ctx->handle); + + return error; +} + +static void z2_test_disconnect(struct input_handle *handle) +{ + input_close_device(handle); + input_unregister_handle(handle); +} + +static const struct input_device_id z2_test_ids[] = { + { + /* connect() picks the test's own device */ + .flags = INPUT_DEVICE_ID_MATCH_BUS, + .bustype = BUS_SPI, + }, + { } +}; + +KUNIT_DEFINE_ACTION_WRAPPER(z2_test_unregister_input, input_unregister_device, + struct input_dev *); +KUNIT_DEFINE_ACTION_WRAPPER(z2_test_unregister_handler, + input_unregister_handler, struct input_handler *); + +/* + * Build what apple_z2_probe() builds, minus the hardware: an SPI device on a + * fake controller, the driver state and the registered input device. + */ +static struct z2_test_ctx *z2_test_setup(struct kunit *test, + const struct z2_test_cfg *cfg) +{ + struct spi_board_info info = { .modalias = "apple-z2-kunit" }; + struct z2_test_ctx *ctx; + struct spi_controller *ctlr; + struct spi_device *spi; + struct input_dev *input; + struct device *parent; + unsigned int nprops = 0; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->fail_xfer = -1; + ctx->events = kunit_kcalloc(test, Z2_TEST_MAX_EVENTS, + sizeof(*ctx->events), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->events); + ctx->msg = kunit_kzalloc(test, Z2_TEST_MSG_ALLOC, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->msg); + ctx->pkt = kunit_kzalloc(test, Z2_TEST_RX_ALLOC, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->pkt); + ctx->z2.tx_buf = kunit_kzalloc(test, + sizeof(struct apple_z2_read_interrupt_cmd), + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->z2.tx_buf); + ctx->z2.rx_buf = kunit_kzalloc(test, Z2_TEST_RX_ALLOC, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->z2.rx_buf); + init_completion(&ctx->z2.boot_irq); + + ctx->props[nprops++] = PROPERTY_ENTRY_U32("touchscreen-size-x", + cfg->size_x); + ctx->props[nprops++] = PROPERTY_ENTRY_U32("touchscreen-size-y", + cfg->size_y); + if (cfg->invert_x) + ctx->props[nprops++] = + PROPERTY_ENTRY_BOOL("touchscreen-inverted-x"); + if (cfg->invert_y) + ctx->props[nprops++] = + PROPERTY_ENTRY_BOOL("touchscreen-inverted-y"); + if (cfg->swap_x_y) + ctx->props[nprops++] = + PROPERTY_ENTRY_BOOL("touchscreen-swapped-x-y"); + if (cfg->cal) + ctx->props[nprops++] = + PROPERTY_ENTRY_U8_ARRAY_LEN(CAL_PROP_NAME, cfg->cal, + cfg->cal_len); + ctx->swnode.properties = ctx->props; + + parent = kunit_device_register(test, "apple-z2-kunit"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, parent); + + ctlr = devm_spi_alloc_host(parent, 0); + KUNIT_ASSERT_NOT_NULL(test, ctlr); + spi_controller_set_devdata(ctlr, ctx); + ctlr->num_chipselect = 1; + ctlr->transfer_one = z2_test_transfer_one; + KUNIT_ASSERT_EQ(test, devm_spi_register_controller(parent, ctlr), 0); + + info.max_speed_hz = 1000000; + info.swnode = &ctx->swnode; + spi = spi_new_device(ctlr, &info); + KUNIT_ASSERT_NOT_NULL(test, spi); + ctx->z2.spidev = spi; + + input = input_allocate_device(); + KUNIT_ASSERT_NOT_NULL(test, input); + ctx->z2.input_dev = input; + input->name = "Apple Z2 KUnit"; + input->phys = "apple_z2"; + input->id.bustype = BUS_SPI; + input->dev.parent = &spi->dev; + + input_set_abs_params(input, ABS_MT_POSITION_X, 0, 0, 0, 0); + input_set_abs_params(input, ABS_MT_POSITION_Y, 0, 0, 0, 0); + touchscreen_parse_properties(input, true, &ctx->z2.props); + input_set_abs_params(input, ABS_MT_WIDTH_MAJOR, 0, 65535, 0, 0); + input_set_abs_params(input, ABS_MT_WIDTH_MINOR, 0, 65535, 0, 0); + input_set_abs_params(input, ABS_MT_TOUCH_MAJOR, 0, 65535, 0, 0); + input_set_abs_params(input, ABS_MT_TOUCH_MINOR, 0, 65535, 0, 0); + input_set_abs_params(input, ABS_MT_ORIENTATION, -32768, 32767, 0, 0); + if (input_mt_init_slots(input, 256, INPUT_MT_DIRECT) || + input_register_device(input)) { + input_free_device(input); + KUNIT_FAIL_AND_ABORT(test, "unable to set up the input device"); + } + KUNIT_ASSERT_EQ(test, + kunit_add_action_or_reset(test, + z2_test_unregister_input, + input), 0); + + ctx->handler.private = ctx; + ctx->handler.event = z2_test_event; + ctx->handler.connect = z2_test_connect; + ctx->handler.disconnect = z2_test_disconnect; + ctx->handler.name = "apple-z2-kunit"; + ctx->handler.id_table = z2_test_ids; + KUNIT_ASSERT_EQ(test, input_register_handler(&ctx->handler), 0); + KUNIT_ASSERT_EQ(test, + kunit_add_action_or_reset(test, + z2_test_unregister_handler, + &ctx->handler), 0); + KUNIT_ASSERT_PTR_EQ(test, ctx->handle.dev, input); + + return ctx; +} + +static void z2_test_clear_log(struct z2_test_ctx *ctx) +{ + ctx->nevents = 0; + ctx->nxfers = 0; + ctx->max_rx_len = 0; +} + +static unsigned int z2_test_count_events(struct z2_test_ctx *ctx, u16 type, + u16 code) +{ + unsigned int i, n = 0; + + for (i = 0; i < min(ctx->nevents, Z2_TEST_MAX_EVENTS); i++) + if (ctx->events[i].type == type && ctx->events[i].code == code) + n++; + + return n; +} + +static bool z2_test_has_event(struct z2_test_ctx *ctx, u16 type, u16 code, + s32 value) +{ + unsigned int i; + + for (i = 0; i < min(ctx->nevents, Z2_TEST_MAX_EVENTS); i++) + if (ctx->events[i].type == type && + ctx->events[i].code == code && + ctx->events[i].value == value) + return true; + + return false; +} + +/* The slot that tracks the finger with this key, or -1 if it is not down */ +static int z2_test_slot_of(struct z2_test_ctx *ctx, int key) +{ + struct input_mt *mt = ctx->z2.input_dev->mt; + int i; + + for (i = 0; i < mt->num_slots; i++) + if (input_mt_is_active(&mt->slots[i]) && + mt->slots[i].key == key) + return i; + + return -1; +} + +static unsigned int z2_test_active_slots(struct z2_test_ctx *ctx) +{ + struct input_mt *mt = ctx->z2.input_dev->mt; + unsigned int i, n = 0; + + for (i = 0; i < mt->num_slots; i++) + if (input_mt_is_active(&mt->slots[i])) + n++; + + return n; +} + +static int z2_test_slot_abs(struct z2_test_ctx *ctx, int slot, + unsigned int code) +{ + return input_mt_get_value(&ctx->z2.input_dev->mt->slots[slot], code); +} + +/* Length of a touch report that holds exactly @nfingers finger records */ +static size_t z2_test_msg_len(unsigned int nfingers) +{ + return APPLE_Z2_FINGERS_OFFSET + nfingers * Z2_TEST_FINGER_LEN; +} + +static void z2_test_put_finger(struct z2_test_ctx *ctx, unsigned int idx, + const struct z2_test_finger *f) +{ + u8 *rec = ctx->msg + z2_test_msg_len(idx); + + memset(rec, 0, Z2_TEST_FINGER_LEN); + rec[0] = f->key; + rec[1] = f->state; + put_unaligned_le16(f->x, rec + 4); + put_unaligned_le16(f->y, rec + 6); + put_unaligned_le16(f->tool_major, rec + 12); + put_unaligned_le16(f->tool_minor, rec + 14); + put_unaligned_le16(f->orientation, rec + 16); + put_unaligned_le16(f->touch_major, rec + 18); + put_unaligned_le16(f->touch_minor, rec + 20); +} + +static void z2_test_put_touch(struct z2_test_ctx *ctx, unsigned int idx, + u8 key, u8 state, u16 x, u16 y) +{ + struct z2_test_finger f = { + .key = key, .state = state, .x = x, .y = y, + }; + + z2_test_put_finger(ctx, idx, &f); +} + +static void z2_test_parse(struct z2_test_ctx *ctx, unsigned int nfingers, + size_t msg_len) +{ + ctx->msg[APPLE_Z2_NUM_FINGERS_OFFSET] = nfingers; + apple_z2_parse_touches(&ctx->z2, ctx->msg, msg_len); +} + +/* + * Make ctx->msg the fake device's next interrupt data packet. @wire_len is + * the length field of the device's reply; the device then sends that length + * plus eight, rounded down to a multiple of four. + */ +static void z2_test_queue_packet(struct z2_test_ctx *ctx, + unsigned int nfingers, u16 wire_len) +{ + ctx->msg[APPLE_Z2_NUM_FINGERS_OFFSET] = nfingers; + memset(ctx->pkt, 0, Z2_TEST_RX_ALLOC); + memcpy(ctx->pkt + Z2_TEST_PKT_HDR, ctx->msg, Z2_TEST_MSG_ALLOC); + ctx->pkt_wire_len = wire_len; + ctx->pkt_len = (wire_len + 8) & ~3; + ctx->pkt_ready = true; +} + +/* The smallest length field for a packet that holds @nfingers records */ +static u16 z2_test_wire_len(unsigned int nfingers) +{ + return round_up(Z2_TEST_PKT_HDR + z2_test_msg_len(nfingers), 4) - 8; +} + +/* + * Touch report parser + */ + +/* A finger record written byte by byte, to pin the record layout */ +static void z2_parse_raw_layout(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + static const u8 rec[Z2_TEST_FINGER_LEN] = { + [0] = 9, /* finger key */ + [1] = APPLE_Z2_TOUCH_STARTED, + [4] = 0x34, [5] = 0x02, /* x = 0x234 */ + [6] = 0x21, [7] = 0x01, /* y = 0x121 */ + [12] = 0x01, [13] = 0x10, /* tool major = 0x1001 */ + [14] = 0x02, [15] = 0x20, /* tool minor = 0x2002 */ + [16] = 0x03, [17] = 0x30, /* orientation = 0x3003 */ + [18] = 0x04, [19] = 0x40, /* touch major = 0x4004 */ + [20] = 0x05, [21] = 0x50, /* touch minor = 0x5005 */ + }; + int slot; + + KUNIT_ASSERT_EQ(test, sizeof(struct apple_z2_finger), + Z2_TEST_FINGER_LEN); + ctx->msg[16] = 1; + memcpy(ctx->msg + 24, rec, sizeof(rec)); + apple_z2_parse_touches(&ctx->z2, ctx->msg, 24 + sizeof(rec)); + + slot = z2_test_slot_of(ctx, 9); + KUNIT_ASSERT_GE(test, slot, 0); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 1); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_X), + 0x234); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_Y), + 0x121); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_POSITION_X, 0x234)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_POSITION_Y, 0x121)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_WIDTH_MAJOR, 0x1001)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_WIDTH_MINOR, 0x2002)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_ORIENTATION, 0x3003)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_TOUCH_MAJOR, 0x4004)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_TOUCH_MINOR, 0x5005)); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_TRACKING_ID), 1); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_KEY, BTN_TOUCH, 1)); + + /* The frame is closed */ + KUNIT_ASSERT_GT(test, ctx->nevents, 0); + KUNIT_EXPECT_EQ(test, ctx->events[ctx->nevents - 1].type, EV_SYN); + KUNIT_EXPECT_EQ(test, ctx->events[ctx->nevents - 1].code, SYN_REPORT); +} + +static void z2_parse_touch_move_release(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + int slot, id; + + z2_test_put_touch(ctx, 0, 4, APPLE_Z2_TOUCH_STARTED, 100, 50); + z2_test_parse(ctx, 1, z2_test_msg_len(1)); + slot = z2_test_slot_of(ctx, 4); + KUNIT_ASSERT_GE(test, slot, 0); + id = z2_test_slot_abs(ctx, slot, ABS_MT_TRACKING_ID); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_TRACKING_ID, id)); + + /* A moving finger keeps its slot and its tracking id */ + z2_test_clear_log(ctx); + z2_test_put_touch(ctx, 0, 4, APPLE_Z2_TOUCH_MOVED, 130, 60); + z2_test_parse(ctx, 1, z2_test_msg_len(1)); + KUNIT_EXPECT_EQ(test, z2_test_slot_of(ctx, 4), slot); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_TRACKING_ID), + id); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_TRACKING_ID), 0); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_POSITION_X, 130)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_POSITION_Y, 60)); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_SYN, SYN_REPORT), + 1); + + /* Any other state lifts the finger; its position is not reported */ + z2_test_clear_log(ctx); + z2_test_put_touch(ctx, 0, 4, Z2_TEST_STATE_LIFTED, 999, 99); + z2_test_parse(ctx, 1, z2_test_msg_len(1)); + KUNIT_EXPECT_EQ(test, z2_test_slot_of(ctx, 4), -1); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 0); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_TRACKING_ID, -1)); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_POSITION_X), 0); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_KEY, BTN_TOUCH, 0)); +} + +static void z2_parse_two_fingers(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + int slot_a, slot_b; + + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 10, 20); + z2_test_put_touch(ctx, 1, 200, APPLE_Z2_TOUCH_STARTED, 1500, 400); + z2_test_parse(ctx, 2, z2_test_msg_len(2)); + + slot_a = z2_test_slot_of(ctx, 1); + slot_b = z2_test_slot_of(ctx, 200); + KUNIT_ASSERT_GE(test, slot_a, 0); + KUNIT_ASSERT_GE(test, slot_b, 0); + KUNIT_EXPECT_NE(test, slot_a, slot_b); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 2); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot_a, ABS_MT_POSITION_X), + 10); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot_a, ABS_MT_POSITION_Y), + 20); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot_b, ABS_MT_POSITION_X), + 1500); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot_b, ABS_MT_POSITION_Y), + 400); + KUNIT_EXPECT_NE(test, + z2_test_slot_abs(ctx, slot_a, ABS_MT_TRACKING_ID), + z2_test_slot_abs(ctx, slot_b, ABS_MT_TRACKING_ID)); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_TRACKING_ID), 2); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_SYN, SYN_REPORT), + 1); + + /* One finger lifts, the other stays where it is */ + z2_test_put_touch(ctx, 0, 1, Z2_TEST_STATE_LIFTED, 10, 20); + z2_test_put_touch(ctx, 1, 200, APPLE_Z2_TOUCH_MOVED, 1500, 400); + z2_test_parse(ctx, 2, z2_test_msg_len(2)); + KUNIT_EXPECT_EQ(test, z2_test_slot_of(ctx, 1), -1); + KUNIT_EXPECT_EQ(test, z2_test_slot_of(ctx, 200), slot_b); +} + +/* Only "started" and "moved" put a finger down */ +static void z2_parse_other_states(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + unsigned int state; + + for (state = 0; state < 256; state++) { + bool down = state == APPLE_Z2_TOUCH_STARTED || + state == APPLE_Z2_TOUCH_MOVED; + + z2_test_put_touch(ctx, 0, 7, state, 300, 200); + z2_test_parse(ctx, 1, z2_test_msg_len(1)); + KUNIT_EXPECT_EQ_MSG(test, z2_test_slot_of(ctx, 7) >= 0, down, + "state %u", state); + } +} + +/* A report too short to hold the finger count is ignored altogether */ +static void z2_parse_short_msg(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + size_t len; + + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 10, 20); + for (len = 0; len <= APPLE_Z2_NUM_FINGERS_OFFSET; len++) + z2_test_parse(ctx, 1, len); + + KUNIT_EXPECT_EQ(test, ctx->nevents, 0); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 0); +} + +static void z2_parse_no_fingers(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + /* A record is present, but the count says there is none */ + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 10, 20); + z2_test_parse(ctx, 0, z2_test_msg_len(1)); + + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 0); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_TRACKING_ID), 0); +} + +static void z2_parse_inverted(struct kunit *test) +{ + static const struct z2_test_cfg cfg = { + .size_x = 2000, .size_y = 600, + .invert_x = true, .invert_y = true, + }; + struct z2_test_ctx *ctx = z2_test_setup(test, &cfg); + int slot; + + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 100, 50); + z2_test_parse(ctx, 1, z2_test_msg_len(1)); + + slot = z2_test_slot_of(ctx, 1); + KUNIT_ASSERT_GE(test, slot, 0); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_X), + 1999 - 100); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_Y), + 599 - 50); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_POSITION_X, 1899)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_POSITION_Y, 549)); +} + +static void z2_parse_swapped(struct kunit *test) +{ + static const struct z2_test_cfg cfg = { + .size_x = 2000, .size_y = 600, + .invert_y = true, .swap_x_y = true, + }; + struct z2_test_ctx *ctx = z2_test_setup(test, &cfg); + int slot; + + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 100, 50); + z2_test_parse(ctx, 1, z2_test_msg_len(1)); + + /* The y axis is inverted first, then the axes trade places */ + slot = z2_test_slot_of(ctx, 1); + KUNIT_ASSERT_GE(test, slot, 0); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_X), + 599 - 50); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_Y), + 100); +} + +/* The largest count a report can carry, with all its records present */ +static void z2_parse_255_fingers(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + unsigned int i; + + for (i = 0; i < 255; i++) + z2_test_put_touch(ctx, i, i, APPLE_Z2_TOUCH_STARTED, + i + 1, i + 2); + z2_test_parse(ctx, 255, z2_test_msg_len(255)); + + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 255); + for (i = 0; i < 255; i += 127) { + int slot = z2_test_slot_of(ctx, i); + + KUNIT_ASSERT_GE(test, slot, 0); + KUNIT_EXPECT_EQ(test, + z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_X), + i + 1); + KUNIT_EXPECT_EQ(test, + z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_Y), + i + 2); + } +} + +/* + * The report says it has 255 fingers but is only long enough for three. + * What lies behind the report (here: plausible finger records) is not part + * of it and must not turn into touches. + */ +static void z2_parse_count_beyond_report(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + unsigned int i, beyond = 0; + + for (i = 0; i < 255; i++) + z2_test_put_touch(ctx, i, i, APPLE_Z2_TOUCH_STARTED, + i + 1, i + 2); + z2_test_parse(ctx, 255, z2_test_msg_len(3)); + + for (i = 3; i < 255; i++) + if (z2_test_slot_of(ctx, i) >= 0) + beyond++; + KUNIT_EXPECT_EQ(test, beyond, 0); + /* ...while the three records the report holds are all reported */ + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 3); +} + +/* The report ends before the first finger record */ +static void z2_parse_count_without_records(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + size_t len; + + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 10, 20); + z2_test_put_touch(ctx, 1, 2, APPLE_Z2_TOUCH_STARTED, 30, 40); + for (len = APPLE_Z2_NUM_FINGERS_OFFSET + 1; + len <= APPLE_Z2_FINGERS_OFFSET; len++) + z2_test_parse(ctx, 2, len); + + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 0); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_TRACKING_ID), 0); +} + +/* The report ends in the middle of the second finger record */ +static void z2_parse_partial_record(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 10, 20); + z2_test_put_touch(ctx, 1, 2, APPLE_Z2_TOUCH_STARTED, 30, 40); + z2_test_parse(ctx, 2, z2_test_msg_len(2) - 1); + + KUNIT_EXPECT_EQ(test, z2_test_slot_of(ctx, 2), -1); + KUNIT_EXPECT_GE(test, z2_test_slot_of(ctx, 1), 0); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 1); +} + +/* + * Interrupt data packets + */ + +static void z2_read_command_framing(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + static const u8 counters[] = { 1, 2, 1, 2 }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(counters); i++) { + const struct z2_test_xfer *xfer = &ctx->xfers[0]; + + z2_test_clear_log(ctx); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + + /* No data pending: the command is the only transfer */ + KUNIT_ASSERT_EQ(test, ctx->nxfers, 1); + KUNIT_EXPECT_EQ(test, xfer->len, 16); + KUNIT_EXPECT_TRUE(test, xfer->has_tx); + KUNIT_EXPECT_TRUE(test, xfer->has_rx); + KUNIT_EXPECT_EQ(test, xfer->tx[0], 0xeb); + KUNIT_EXPECT_EQ(test, xfer->tx[1], counters[i]); + KUNIT_EXPECT_TRUE(test, !memchr_inv(xfer->tx + 2, 0, 12)); + /* The checksum is the sum of the bytes in front of it */ + KUNIT_EXPECT_EQ(test, get_unaligned_le16(xfer->tx + 14), + 0xeb + counters[i]); + } + KUNIT_EXPECT_EQ(test, ctx->nevents, 0); +} + +/* The packet read asks for the reply's length plus 8, rounded down to 4 */ +static void z2_read_length_rounding(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + static const struct { + u16 wire_len; + unsigned int read_len; + } cases[] = { + { 0, 8 }, { 1, 8 }, { 3, 8 }, { 4, 12 }, { 52, 60 }, + { 55, 60 }, { 56, 64 }, { 3991, 3996 }, { 3992, 4000 }, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cases); i++) { + z2_test_clear_log(ctx); + z2_test_queue_packet(ctx, 0, cases[i].wire_len); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + + KUNIT_ASSERT_EQ(test, ctx->nxfers, 2); + KUNIT_EXPECT_FALSE(test, ctx->xfers[1].has_tx); + KUNIT_EXPECT_TRUE(test, ctx->xfers[1].has_rx); + KUNIT_EXPECT_EQ_MSG(test, ctx->xfers[1].len, cases[i].read_len, + "length field %u", cases[i].wire_len); + } +} + +/* The touch report starts five bytes into the packet */ +static void z2_read_reports_touch(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + int slot; + + z2_test_put_touch(ctx, 0, 3, APPLE_Z2_TOUCH_STARTED, 700, 300); + z2_test_put_touch(ctx, 1, 5, APPLE_Z2_TOUCH_STARTED, 800, 310); + z2_test_queue_packet(ctx, 2, z2_test_wire_len(2)); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + + KUNIT_EXPECT_EQ(test, ctx->nxfers, 2); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 2); + slot = z2_test_slot_of(ctx, 3); + KUNIT_ASSERT_GE(test, slot, 0); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_X), + 700); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_Y), + 300); + slot = z2_test_slot_of(ctx, 5); + KUNIT_ASSERT_GE(test, slot, 0); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_X), + 800); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_Y), + 310); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_SYN, SYN_REPORT), + 1); +} + +static void z2_read_spi_errors(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + z2_test_put_touch(ctx, 0, 3, APPLE_Z2_TOUCH_STARTED, 700, 300); + + /* The command fails: no packet read follows */ + z2_test_queue_packet(ctx, 1, z2_test_wire_len(1)); + ctx->fail_xfer = 0; + KUNIT_EXPECT_EQ(test, apple_z2_read_packet(&ctx->z2), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 1); + + /* The packet read fails: whatever is in the buffer is not parsed */ + z2_test_clear_log(ctx); + memcpy(ctx->z2.rx_buf, ctx->pkt, 64); + ctx->fail_xfer = 1; + KUNIT_EXPECT_EQ(test, apple_z2_read_packet(&ctx->z2), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 2); + KUNIT_EXPECT_EQ(test, ctx->nevents, 0); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 0); +} + +/* The largest packet that fits the driver's receive buffer */ +static void z2_read_largest_packet(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + unsigned int nfingers = (Z2_TEST_RX_SIZE - Z2_TEST_PKT_HDR - + APPLE_Z2_FINGERS_OFFSET) / Z2_TEST_FINGER_LEN; + unsigned int i; + + for (i = 0; i < nfingers; i++) + z2_test_put_touch(ctx, i, i, APPLE_Z2_TOUCH_STARTED, + i + 1, i + 2); + z2_test_queue_packet(ctx, nfingers, Z2_TEST_RX_SIZE - 8); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + + KUNIT_EXPECT_EQ(test, ctx->max_rx_len, Z2_TEST_RX_SIZE); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), nfingers); +} + +/* + * The device's reply carries a 16-bit length. The driver must not read more + * than its receive buffer holds, whatever the device says. + */ +static void z2_read_oversize_length(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + static const u16 wire_lens[] = { + Z2_TEST_RX_SIZE - 7, Z2_TEST_RX_SIZE - 4, Z2_TEST_RX_SIZE, + 8192, 0xfff7, 0xffff, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(wire_lens); i++) { + /* The length the driver reads, as apple_z2_read_packet() rounds it */ + size_t pkt_len = (wire_lens[i] + 8) & ~3; + bool fits = pkt_len <= Z2_TEST_RX_SIZE; + + z2_test_clear_log(ctx); + z2_test_queue_packet(ctx, 0, wire_lens[i]); + KUNIT_EXPECT_EQ_MSG(test, apple_z2_read_packet(&ctx->z2), + fits ? 0 : -EMSGSIZE, + "length field %u", wire_lens[i]); + KUNIT_EXPECT_LE_MSG(test, ctx->max_rx_len, + (size_t)Z2_TEST_RX_SIZE, + "length field %u", wire_lens[i]); + /* A dropped packet is not parsed */ + if (!fits) + KUNIT_EXPECT_EQ_MSG(test, ctx->nevents, 0, + "length field %u", wire_lens[i]); + } +} + +/* + * A packet that is too short for its finger count must not report what an + * earlier, longer packet left in the receive buffer. + */ +static void z2_read_stale_finger(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + /* Two fingers down */ + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 100, 50); + z2_test_put_touch(ctx, 1, 2, APPLE_Z2_TOUCH_STARTED, 900, 300); + z2_test_queue_packet(ctx, 2, z2_test_wire_len(2)); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + KUNIT_ASSERT_EQ(test, z2_test_active_slots(ctx), 2); + + /* Finger 2 lifts, in a packet with one record */ + z2_test_put_touch(ctx, 0, 2, Z2_TEST_STATE_LIFTED, 900, 300); + z2_test_queue_packet(ctx, 1, z2_test_wire_len(1)); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + KUNIT_ASSERT_EQ(test, z2_test_slot_of(ctx, 2), -1); + + /* Finger 1 moves; the packet claims two records but holds one */ + z2_test_clear_log(ctx); + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_MOVED, 110, 55); + z2_test_queue_packet(ctx, 2, z2_test_wire_len(1)); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + + KUNIT_EXPECT_EQ(test, z2_test_slot_of(ctx, 2), -1); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_TRACKING_ID), 0); +} + +static void z2_irq_boot_and_data(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + /* Before the firmware runs, an interrupt only signals the boot */ + z2_test_put_touch(ctx, 0, 3, APPLE_Z2_TOUCH_STARTED, 700, 300); + z2_test_queue_packet(ctx, 1, z2_test_wire_len(1)); + KUNIT_EXPECT_EQ(test, apple_z2_irq(0, &ctx->z2), IRQ_HANDLED); + KUNIT_EXPECT_TRUE(test, try_wait_for_completion(&ctx->z2.boot_irq)); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 0); + KUNIT_EXPECT_EQ(test, ctx->nevents, 0); + + /* Afterwards it fetches a packet */ + ctx->z2.booted = true; + KUNIT_EXPECT_EQ(test, apple_z2_irq(0, &ctx->z2), IRQ_HANDLED); + KUNIT_EXPECT_FALSE(test, try_wait_for_completion(&ctx->z2.boot_irq)); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 2); + KUNIT_EXPECT_GE(test, z2_test_slot_of(ctx, 3), 0); +} + +/* + * Firmware upload + * + * The images below are synthetic and go straight to + * apple_z2_load_firmware(). Several entries share one image and differ in + * the size they declare. + */ + +static const __le32 z2_test_fw_good[] = { + cpu_to_le32(APPLE_Z2_FW_MAGIC), cpu_to_le32(1), + /* Six bytes for 8-bit transfer, then two bytes of padding */ + cpu_to_le32(LOAD_COMMAND_INIT_PAYLOAD), cpu_to_le32(6), + cpu_to_le32(0x04030201), cpu_to_le32(0xeeee0605), + cpu_to_le32(LOAD_COMMAND_SEND_BLOB), cpu_to_le32(8), + cpu_to_le32(0x14131211), cpu_to_le32(0x18171615), + cpu_to_le32(LOAD_COMMAND_SEND_CALIBRATION), cpu_to_le32(0x00123456), + /* Not part of the image except in the "trailing" entry */ + cpu_to_le32(LOAD_COMMAND_SEND_BLOB), +}; + +static const __le32 z2_test_fw_bad_magic[] = { + cpu_to_le32(APPLE_Z2_FW_MAGIC + 1), cpu_to_le32(1), + cpu_to_le32(LOAD_COMMAND_SEND_BLOB), cpu_to_le32(4), + cpu_to_le32(0x04030201), +}; + +static const __le32 z2_test_fw_bad_version[] = { + cpu_to_le32(APPLE_Z2_FW_MAGIC), cpu_to_le32(2), + cpu_to_le32(LOAD_COMMAND_SEND_BLOB), cpu_to_le32(4), + cpu_to_le32(0x04030201), +}; + +static const __le32 z2_test_fw_bad_command[] = { + cpu_to_le32(APPLE_Z2_FW_MAGIC), cpu_to_le32(1), + cpu_to_le32(LOAD_COMMAND_SEND_BLOB), cpu_to_le32(4), + cpu_to_le32(0x04030201), + cpu_to_le32(3), cpu_to_le32(4), + cpu_to_le32(0x14131211), +}; + +static const __le32 z2_test_fw_huge_blob[] = { + cpu_to_le32(APPLE_Z2_FW_MAGIC), cpu_to_le32(1), + cpu_to_le32(LOAD_COMMAND_SEND_BLOB), cpu_to_le32(0xfffffffc), + cpu_to_le32(0x04030201), cpu_to_le32(0x08070605), +}; + +struct z2_test_image { + const char *name; + const void *data; + size_t size; +}; + +#define Z2_TEST_FW(_name, _image, _size) \ + { "apple-z2-kunit/" _name ".bin", (_image), (_size) } + +static const struct z2_test_image z2_test_fw_table[] = { + Z2_TEST_FW("good", z2_test_fw_good, 48), + Z2_TEST_FW("header-only", z2_test_fw_good, 8), + Z2_TEST_FW("short-header", z2_test_fw_good, 4), + Z2_TEST_FW("unpadded-end", z2_test_fw_good, 22), + Z2_TEST_FW("cut-command", z2_test_fw_good, 28), + Z2_TEST_FW("cut-blob", z2_test_fw_good, 20), + Z2_TEST_FW("cut-calibration", z2_test_fw_good, 44), + Z2_TEST_FW("trailing", z2_test_fw_good, 52), + Z2_TEST_FW("bad-magic", z2_test_fw_bad_magic, + sizeof(z2_test_fw_bad_magic)), + Z2_TEST_FW("bad-version", z2_test_fw_bad_version, + sizeof(z2_test_fw_bad_version)), + Z2_TEST_FW("bad-command", z2_test_fw_bad_command, + sizeof(z2_test_fw_bad_command)), + Z2_TEST_FW("huge-blob", z2_test_fw_huge_blob, + sizeof(z2_test_fw_huge_blob)), +}; + +static const u8 z2_test_cal[] = { + 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0xff, +}; + +/* The blob the driver builds from z2_test_cal for address 0x00123456 */ +static const u8 z2_test_cal_blob[] = { + 0x01, 0x30, /* blob command */ + 0x02, 0x00, /* length in 32-bit words */ + 0x56, 0x34, 0x12, 0x00, /* address */ + 0x9e, 0x00, /* sum of the six bytes before */ + 0x00, 0x00, /* padding */ + 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0xff, + 0xbf, 0x02, 0x00, 0x00, /* sum of the calibration bytes */ +}; + +static const struct z2_test_cfg z2_test_cfg_cal = { + .size_x = 2000, + .size_y = 600, + .cal = z2_test_cal, + .cal_len = sizeof(z2_test_cal), +}; + +/* Upload one of the images above, as apple_z2_upload_firmware() would */ +static int z2_test_upload(struct z2_test_ctx *ctx, const char *name) +{ + struct firmware fw = {}; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(z2_test_fw_table); i++) { + if (strcmp(z2_test_fw_table[i].name, name)) + continue; + fw.data = z2_test_fw_table[i].data; + fw.size = z2_test_fw_table[i].size; + return apple_z2_load_firmware(&ctx->z2, &fw); + } + + /* Not one of ours: let the firmware loader fail to find it */ + ctx->z2.fw_name = name; + return apple_z2_upload_firmware(&ctx->z2); +} + +/* A firmware blob transfer and the acknowledge that follows it */ +static void z2_test_expect_blob(struct kunit *test, struct z2_test_ctx *ctx, + unsigned int idx, const void *data, + unsigned int len, unsigned int bpw) +{ + static const u8 ack[] = { 0x1a, 0xa1 }; + const struct z2_test_xfer *xfer = &ctx->xfers[idx]; + + KUNIT_ASSERT_LT(test, idx + 1, min(ctx->nxfers, Z2_TEST_MAX_XFERS)); + KUNIT_ASSERT_LE(test, len, Z2_TEST_TX_LOG); + KUNIT_EXPECT_EQ(test, xfer->len, len); + KUNIT_EXPECT_EQ(test, xfer->bpw, bpw); + KUNIT_EXPECT_TRUE(test, xfer->has_tx); + KUNIT_EXPECT_FALSE(test, xfer->has_rx); + KUNIT_EXPECT_MEMEQ(test, xfer->tx, data, len); + + xfer++; + KUNIT_EXPECT_EQ(test, xfer->len, sizeof(ack)); + KUNIT_EXPECT_EQ(test, xfer->bpw, 8); + KUNIT_EXPECT_TRUE(test, xfer->has_tx); + KUNIT_EXPECT_FALSE(test, xfer->has_rx); + KUNIT_EXPECT_MEMEQ(test, xfer->tx, ack, sizeof(ack)); +} + +static void z2_fw_upload(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_cal); + + KUNIT_ASSERT_EQ(test, z2_test_upload(ctx, "apple-z2-kunit/good.bin"), + 0); + KUNIT_EXPECT_TRUE(test, ctx->z2.booted); + + /* Three blobs with their acknowledges, then a first packet poll */ + KUNIT_ASSERT_EQ(test, ctx->nxfers, 7); + z2_test_expect_blob(test, ctx, 0, &z2_test_fw_good[4], 6, 8); + z2_test_expect_blob(test, ctx, 2, &z2_test_fw_good[8], 8, 16); + z2_test_expect_blob(test, ctx, 4, z2_test_cal_blob, + sizeof(z2_test_cal_blob), 16); + KUNIT_EXPECT_EQ(test, ctx->xfers[6].len, 16); + KUNIT_EXPECT_EQ(test, ctx->xfers[6].tx[0], 0xeb); +} + +/* Without a calibration property the calibration command is skipped */ +static void z2_fw_no_calibration(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + size_t size = 0; + + KUNIT_EXPECT_NULL(test, apple_z2_build_cal_blob(&ctx->z2, 0x123456, + &size)); + + KUNIT_ASSERT_EQ(test, z2_test_upload(ctx, "apple-z2-kunit/good.bin"), + 0); + KUNIT_EXPECT_TRUE(test, ctx->z2.booted); + KUNIT_ASSERT_EQ(test, ctx->nxfers, 5); + z2_test_expect_blob(test, ctx, 0, &z2_test_fw_good[4], 6, 8); + z2_test_expect_blob(test, ctx, 2, &z2_test_fw_good[8], 8, 16); + KUNIT_EXPECT_EQ(test, ctx->xfers[4].tx[0], 0xeb); +} + +static void z2_fw_cal_blob(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_cal); + size_t size = 0; + const u8 *blob; + + blob = apple_z2_build_cal_blob(&ctx->z2, 0x00123456, &size); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, blob); + KUNIT_EXPECT_EQ(test, size, sizeof(z2_test_cal_blob)); + if (size == sizeof(z2_test_cal_blob)) + KUNIT_EXPECT_MEMEQ(test, blob, z2_test_cal_blob, size); + kfree(blob); +} + +/* Images that end cleanly, with and without commands */ +static void z2_fw_clean_end(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + KUNIT_EXPECT_EQ(test, + z2_test_upload(ctx, "apple-z2-kunit/header-only.bin"), + 0); + KUNIT_EXPECT_TRUE(test, ctx->z2.booted); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 1); + + /* The last blob need not be padded */ + ctx->z2.booted = false; + z2_test_clear_log(ctx); + KUNIT_EXPECT_EQ(test, + z2_test_upload(ctx, "apple-z2-kunit/unpadded-end.bin"), + 0); + KUNIT_EXPECT_TRUE(test, ctx->z2.booted); + KUNIT_ASSERT_EQ(test, ctx->nxfers, 3); + z2_test_expect_blob(test, ctx, 0, &z2_test_fw_good[4], 6, 8); +} + +struct z2_test_fw_case { + const char *name; + /* Transfers that happen before the image is found malformed */ + unsigned int nxfers; +}; + +static void z2_test_fw_case_desc(const struct z2_test_fw_case *c, char *desc) +{ + strscpy(desc, c->name + strlen("apple-z2-kunit/"), + KUNIT_PARAM_DESC_SIZE); +} + +static const struct z2_test_fw_case z2_test_fw_rejected[] = { + { "apple-z2-kunit/bad-magic.bin", 0 }, + { "apple-z2-kunit/bad-version.bin", 0 }, + /* The image ends inside a command header */ + { "apple-z2-kunit/cut-command.bin", 2 }, + /* The image ends inside a blob */ + { "apple-z2-kunit/cut-blob.bin", 0 }, + /* The image ends in front of the calibration address */ + { "apple-z2-kunit/cut-calibration.bin", 4 }, + /* Four stray bytes after the last command */ + { "apple-z2-kunit/trailing.bin", 4 }, + { "apple-z2-kunit/bad-command.bin", 2 }, + { "apple-z2-kunit/huge-blob.bin", 0 }, +}; + +KUNIT_ARRAY_PARAM(z2_fw_rejected, z2_test_fw_rejected, z2_test_fw_case_desc); + +static void z2_fw_rejected(struct kunit *test) +{ + const struct z2_test_fw_case *c = test->param_value; + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + KUNIT_EXPECT_EQ(test, z2_test_upload(ctx, c->name), -EINVAL); + KUNIT_EXPECT_FALSE(test, ctx->z2.booted); + KUNIT_EXPECT_EQ(test, ctx->nxfers, c->nxfers); +} + +/* An image shorter than its own header has no magic and version to accept */ +static void z2_fw_short_header(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + KUNIT_EXPECT_EQ(test, + z2_test_upload(ctx, "apple-z2-kunit/short-header.bin"), + -EINVAL); + KUNIT_EXPECT_FALSE(test, ctx->z2.booted); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 0); +} + +static void z2_fw_missing(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + KUNIT_EXPECT_LT(test, + z2_test_upload(ctx, "apple-z2-kunit/missing.bin"), 0); + KUNIT_EXPECT_FALSE(test, ctx->z2.booted); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 0); +} + +static void z2_fw_spi_error(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_cal); + + /* The second blob fails: the upload stops there */ + ctx->fail_xfer = 2; + KUNIT_EXPECT_EQ(test, z2_test_upload(ctx, "apple-z2-kunit/good.bin"), + -EIO); + KUNIT_EXPECT_FALSE(test, ctx->z2.booted); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 3); +} + +static struct kunit_case apple_z2_test_cases[] = { + KUNIT_CASE(z2_parse_raw_layout), + KUNIT_CASE(z2_parse_touch_move_release), + KUNIT_CASE(z2_parse_two_fingers), + KUNIT_CASE(z2_parse_other_states), + KUNIT_CASE(z2_parse_short_msg), + KUNIT_CASE(z2_parse_no_fingers), + KUNIT_CASE(z2_parse_inverted), + KUNIT_CASE(z2_parse_swapped), + KUNIT_CASE(z2_parse_255_fingers), + KUNIT_CASE(z2_parse_count_beyond_report), + KUNIT_CASE(z2_parse_count_without_records), + KUNIT_CASE(z2_parse_partial_record), + KUNIT_CASE(z2_read_command_framing), + KUNIT_CASE(z2_read_length_rounding), + KUNIT_CASE(z2_read_reports_touch), + KUNIT_CASE(z2_read_spi_errors), + KUNIT_CASE(z2_read_largest_packet), + KUNIT_CASE(z2_read_oversize_length), + KUNIT_CASE(z2_read_stale_finger), + KUNIT_CASE(z2_irq_boot_and_data), + KUNIT_CASE(z2_fw_upload), + KUNIT_CASE(z2_fw_no_calibration), + KUNIT_CASE(z2_fw_cal_blob), + KUNIT_CASE(z2_fw_clean_end), + KUNIT_CASE_PARAM(z2_fw_rejected, z2_fw_rejected_gen_params), + KUNIT_CASE(z2_fw_short_header), + KUNIT_CASE(z2_fw_missing), + KUNIT_CASE(z2_fw_spi_error), + {} +}; + +static struct kunit_suite apple_z2_test_suite = { + .name = "apple-z2", + .test_cases = apple_z2_test_cases, +}; + +kunit_test_suite(apple_z2_test_suite); diff --git a/drivers/input/touchscreen/apple_z2.c b/drivers/input/touchscreen/apple_z2.c index 271ababf0ad559..32fde866a60d46 100644 --- a/drivers/input/touchscreen/apple_z2.c +++ b/drivers/input/touchscreen/apple_z2.c @@ -28,6 +28,7 @@ #define LOAD_COMMAND_SEND_BLOB 1 #define LOAD_COMMAND_SEND_CALIBRATION 2 #define CAL_PROP_NAME "apple,z2-cal-blob" +#define APPLE_Z2_RX_BUF_SIZE 4000 struct apple_z2 { struct spi_device *spidev; @@ -86,11 +87,16 @@ static void apple_z2_parse_touches(struct apple_z2 *z2, int nfingers; int slot; int slot_valid; + size_t max_fingers = 0; struct apple_z2_finger *fingers; if (msg_len <= APPLE_Z2_NUM_FINGERS_OFFSET) return; - nfingers = msg[APPLE_Z2_NUM_FINGERS_OFFSET]; + /* Only trust the finger records that the report has room for */ + if (msg_len > APPLE_Z2_FINGERS_OFFSET) + max_fingers = (msg_len - APPLE_Z2_FINGERS_OFFSET) / + sizeof(*fingers); + nfingers = min_t(size_t, msg[APPLE_Z2_NUM_FINGERS_OFFSET], max_fingers); fingers = (struct apple_z2_finger *)(msg + APPLE_Z2_FINGERS_OFFSET); for (i = 0; i < nfingers; i++) { slot = input_mt_get_slot_by_key(z2->input_dev, fingers[i].finger); @@ -147,6 +153,17 @@ static int apple_z2_read_packet(struct apple_z2 *z2) return 0; pkt_len = (get_unaligned_le16(z2->rx_buf + 1) + 8) & 0xfffffffc; + /* + * No valid packet is this long. Drop it unread rather than read it in + * pieces: a controller that sends one is misbehaving, and touch input + * stopping is the safe outcome. + */ + if (pkt_len > APPLE_Z2_RX_BUF_SIZE) { + dev_warn_ratelimited(&z2->spidev->dev, + "dropping oversized packet (%zu bytes)\n", + pkt_len); + return -EMSGSIZE; + } error = spi_read(z2->spidev, z2->rx_buf, pkt_len); if (error) @@ -253,7 +270,8 @@ static int apple_z2_send_firmware_blob(struct apple_z2 *z2, const u8 *data, return 0; } -static int apple_z2_upload_firmware(struct apple_z2 *z2) +static int apple_z2_load_firmware(struct apple_z2 *z2, + const struct firmware *fw) { const struct apple_z2_fw_hdr *fw_hdr; size_t fw_idx = sizeof(struct apple_z2_fw_hdr); @@ -263,15 +281,9 @@ static int apple_z2_upload_firmware(struct apple_z2 *z2) bool init; size_t size; - const struct firmware *fw __free(firmware) = NULL; - error = request_firmware(&fw, z2->fw_name, &z2->spidev->dev); - if (error) { - dev_err(&z2->spidev->dev, "unable to load firmware\n"); - return error; - } - fw_hdr = (const struct apple_z2_fw_hdr *)fw->data; - if (le32_to_cpu(fw_hdr->magic) != APPLE_Z2_FW_MAGIC || le32_to_cpu(fw_hdr->version) != 1) { + if (fw->size < sizeof(*fw_hdr) || + le32_to_cpu(fw_hdr->magic) != APPLE_Z2_FW_MAGIC || le32_to_cpu(fw_hdr->version) != 1) { dev_err(&z2->spidev->dev, "invalid firmware header\n"); return -EINVAL; } @@ -329,6 +341,20 @@ static int apple_z2_upload_firmware(struct apple_z2 *z2) return 0; } +static int apple_z2_upload_firmware(struct apple_z2 *z2) +{ + int error; + + const struct firmware *fw __free(firmware) = NULL; + error = request_firmware(&fw, z2->fw_name, &z2->spidev->dev); + if (error) { + dev_err(&z2->spidev->dev, "unable to load firmware\n"); + return error; + } + + return apple_z2_load_firmware(z2, fw); +} + static int apple_z2_boot(struct apple_z2 *z2) { int error; @@ -363,7 +389,7 @@ static int apple_z2_probe(struct spi_device *spi) if (!z2->tx_buf) return -ENOMEM; /* 4096 will end up being rounded up to 8192 due to devres header */ - z2->rx_buf = devm_kzalloc(dev, 4000, GFP_KERNEL); + z2->rx_buf = devm_kzalloc(dev, APPLE_Z2_RX_BUF_SIZE, GFP_KERNEL); if (!z2->rx_buf) return -ENOMEM; @@ -479,3 +505,7 @@ module_spi_driver(apple_z2_driver); MODULE_LICENSE("GPL"); MODULE_FIRMWARE("apple/dfrmtfw-*.bin"); MODULE_DESCRIPTION("Apple Z2 touchscreens driver"); + +#if IS_ENABLED(CONFIG_TOUCHSCREEN_APPLE_Z2_KUNIT_TEST) +#include "apple_z2-test.c" +#endif diff --git a/drivers/input/touchscreen/apple_z2.kunitconfig b/drivers/input/touchscreen/apple_z2.kunitconfig new file mode 100644 index 00000000000000..526ee9bead6680 --- /dev/null +++ b/drivers/input/touchscreen/apple_z2.kunitconfig @@ -0,0 +1,9 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/input/touchscreen/apple_z2.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_SPI=y +CONFIG_INPUT=y +CONFIG_INPUT_TOUCHSCREEN=y +CONFIG_FW_LOADER=y +CONFIG_TOUCHSCREEN_APPLE_Z2=y +CONFIG_TOUCHSCREEN_APPLE_Z2_KUNIT_TEST=y diff --git a/drivers/iommu/Kconfig b/drivers/iommu/Kconfig index 4233b253b06e2c..081f59673ccf18 100644 --- a/drivers/iommu/Kconfig +++ b/drivers/iommu/Kconfig @@ -81,6 +81,19 @@ config IOMMU_IO_PGTABLE_DART If unsure, say N here. +config IOMMU_IO_PGTABLE_DART_KUNIT_TEST + bool "KUnit tests for Apple DART page tables" if !KUNIT_ALL_TESTS + depends on IOMMU_IO_PGTABLE_DART && KUNIT=y + default KUNIT_ALL_TESTS + help + Enable KUnit tests for the Apple DART page table allocator. They + check the table layout chosen for each format, granule and input + size, the DART and DART2 PTE encodings, map/unmap/iova_to_phys + across table boundaries, rejection of invalid requests and that + teardown frees every table page. + + If unsure, say N here. + endmenu config IOMMU_DEBUGFS @@ -317,17 +330,19 @@ config APPLE_DART Say Y here if you are using an Apple SoC. config APPLE_DART_J713_DCP - bool "Retained J713 display DART support" + bool "Retained T8132 display DART support" depends on APPLE_DART=y && ARM64_16K_PAGES select MFD_SYSCON help - Adopt the qualified running J713 internal display DARTs. Their - firmware-visible allocations, page tables and noncoherent CPU - mappings remain pinned until platform reset. This limited bringup - profile requires the built-in ARM64 DMA implementation; its private - mapping/cache interfaces are not a modular DMA API. + Adopt the inherited T8132 (M4) display DARTs when the boot loader + hands over a qualified DCP firmware session. Their firmware-visible + allocations, page tables and noncoherent CPU mappings remain pinned + until platform reset, which requires the built-in ARM64 DMA + implementation (not APPLE_DART=m). - Leave this disabled for ordinary DART use, including APPLE_DART=m. + Say Y here to support native display and its dependent GPU bring-up + on T8132 Macs with a qualified DCP handoff (requires built-in + APPLE_DART and 16 KiB pages). config APPLE_DART_KUNIT_TEST bool "KUnit tests for Apple DART domains and commands" if !KUNIT_ALL_TESTS diff --git a/drivers/iommu/apple-dart-cio-power.h b/drivers/iommu/apple-dart-cio-power.h index 740b06671d54a9..faa6f489d8814a 100644 --- a/drivers/iommu/apple-dart-cio-power.h +++ b/drivers/iommu/apple-dart-cio-power.h @@ -27,8 +27,9 @@ static bool dart_cio_fault(void __iomem *regs, const struct dart_cio_power *s) static int dart_cio_idle(void __iomem *regs, const struct dart_cio_power *s) { - unsigned int ports = max(FIELD_GET(GENMASK(18, 16), s->params[1]), - FIELD_GET(GENMASK(22, 20), s->params[1])); + unsigned int rports = FIELD_GET(GENMASK(18, 16), s->params[1]); + unsigned int wports = FIELD_GET(GENMASK(22, 20), s->params[1]); + unsigned int ports = max(rports, wports); u32 value; int ret; diff --git a/drivers/iommu/apple-dart-dcp.h b/drivers/iommu/apple-dart-dcp.h index 49ed48c2f3de6e..b9239cd7405a62 100644 --- a/drivers/iommu/apple-dart-dcp.h +++ b/drivers/iommu/apple-dart-dcp.h @@ -139,7 +139,7 @@ static inline void apple_dart_pm_invalidate(struct apple_dart *dart, bool suspen * register used; its power-up flushes every translation, with these locks * held, before it enables the streams again. */ -static void apple_dart_host_lock(struct apple_dart *dart, unsigned long *flags) +static void __maybe_unused apple_dart_host_lock(struct apple_dart *dart, unsigned long *flags) { struct apple_dart_dcp *streams[] = { dart->dcp, dart->frontend[0], dart->frontend[1] }; unsigned int held = 0; @@ -150,7 +150,7 @@ static void apple_dart_host_lock(struct apple_dart *dart, unsigned long *flags) spin_lock_nested(&streams[i]->lock, held++); } -static void apple_dart_host_unlock(struct apple_dart *dart, unsigned long flags) +static void __maybe_unused apple_dart_host_unlock(struct apple_dart *dart, unsigned long flags) { struct apple_dart_dcp *streams[] = { dart->frontend[1], dart->frontend[0], dart->dcp }; @@ -517,8 +517,13 @@ static bool apple_dart_dcp_leaf_safe(const struct apple_dart_dcp *dcp, u64 leaf) IORES_DESC_NONE) == REGION_DISJOINT; } +/* + * Import SID @sid, whose tables live in [@start, @end); @firmware supplies the + * rest of the ADT description. Passed by reference: the tables are ~0.5 KiB. + */ static int apple_dart_dcp_import(struct apple_dart *dart, unsigned int sid, - struct dcp_adt_tables bounds, struct apple_dart_dcp **result) + const struct dcp_adt_tables *firmware, u64 start, u64 end, + struct apple_dart_dcp **result) { struct apple_dart_dcp *dcp; u64 root_pa; @@ -537,7 +542,7 @@ static int apple_dart_dcp_import(struct apple_dart *dart, unsigned int sid, "DCP admission: lock=%d type=%u streams=%u page=%u IAS/OAS=%u/%u range=%pad..%pad TCR%u=%08x enabled=%08x\n", dart->locked, dart->hw->type, dart->num_streams, dart->pgsize, dart->ias, dart->oas, &dart->dma_min, &dart->dma_max, sid, tcr, enabled); - ret = apple_dart_dcp_excluded(dart, bounds.start, bounds.end); + ret = apple_dart_dcp_excluded(dart, start, end); if (ret) return dev_err_probe(dart->dev, ret, "DCP table storage is not excluded memory\n"); dcp = apple_dart_retained_alloc(dart, sizeof(*dcp)); @@ -545,7 +550,9 @@ static int apple_dart_dcp_import(struct apple_dart *dart, unsigned int sid, return -ENOMEM; dcp->dart = dart; dcp->sid = sid; - dcp->firmware = bounds; + dcp->firmware = *firmware; + dcp->firmware.start = start; + dcp->firmware.end = end; ret = apple_dart_dcp_excluded_regions(dcp); if (ret) return dev_err_probe(dart->dev, ret, "invalid reserved-memory leaf exclusions\n"); @@ -559,17 +566,17 @@ static int apple_dart_dcp_import(struct apple_dart *dart, unsigned int sid, INIT_LIST_HEAD(&dcp->shared); dcp->ttbr = readl(dart->regs + DART_TTBR(dart, sid, 0)); root_pa = ((u64)dcp->ttbr >> 2) << 14; - if ((dcp->ttbr & 3) != 1 || (sid != 23 && root_pa != bounds.start) || - !dcp_dart_contains(bounds.start, bounds.end, root_pa, DCP_DART_PAGE)) + if ((dcp->ttbr & 3) != 1 || (sid != 23 && root_pa != start) || + !dcp_dart_contains(start, end, root_pa, DCP_DART_PAGE)) return dev_err_probe(dart->dev, -EINVAL, "DCP admission: TTBR%u=%08x root=%llx outside ADT [%llx,%llx) or invalid flags\n", - sid, dcp->ttbr, root_pa, bounds.start, bounds.end); - storage = apple_dart_retained_memremap(dart, bounds.start, bounds.end - bounds.start); + sid, dcp->ttbr, root_pa, start, end); + storage = apple_dart_retained_memremap(dart, start, end - start); if (IS_ERR(storage)) return PTR_ERR(storage); if (!storage) return -ENOMEM; - dcp->root = (u64 *)(storage + root_pa - bounds.start); + dcp->root = (u64 *)(storage + root_pa - start); for (unsigned int i = 0; i < DCP_DART_ENTRIES; i++) { u64 pte = READ_ONCE(dcp->root[i]); u64 pa = dcp_dart_pte_phys(pte); @@ -581,16 +588,16 @@ static int apple_dart_dcp_import(struct apple_dart *dart, unsigned int sid, dcp->entry[i] = pte; if (!pte) continue; - if (pa == root_pa || !dcp_dart_contains(bounds.start, bounds.end, pa, DCP_DART_PAGE)) + if (pa == root_pa || !dcp_dart_contains(start, end, pa, DCP_DART_PAGE)) return dev_err_probe(dart->dev, -EINVAL, "DCP admission: root[%u]=%016llx child=%llx outside ADT [%llx,%llx) or aliases root\n", - i, pte, pa, bounds.start, bounds.end); + i, pte, pa, start, end); for (unsigned int j = 0; j < i; j++) if (dcp->entry[j] && dcp_dart_pte_phys(dcp->entry[j]) == pa) return dev_err_probe(dart->dev, -EINVAL, "DCP admission: roots %u and %u alias child=%llx\n", j, i, pa); - dcp->table[i] = (u64 *)(storage + pa - bounds.start); + dcp->table[i] = (u64 *)(storage + pa - start); set_bit(i, dcp->foreign); if (sid != 23) { dcp->expected[i] = apple_dart_retained_alloc(dart, DCP_DART_PAGE); @@ -641,7 +648,7 @@ static int apple_dart_dcp_prepare(struct apple_dart *dart) if (ret) return dev_err_probe(dart->dev, ret, "cannot validate existing ADT table handoff\n"); - return apple_dart_dcp_import(dart, 23, tables, &dart->dcp); + return apple_dart_dcp_import(dart, 23, &tables, tables.start, tables.end, &dart->dcp); } static bool apple_dart_dcp_iova(u64 iova) @@ -863,7 +870,7 @@ static int apple_dart_frontend_validate(struct apple_dart_dcp *dcp, */ static int apple_dart_dispext_prepare(struct apple_dart *dart) { - struct dcp_adt_tables firmware, bounds; + struct dcp_adt_tables firmware; struct dcp_adt_frontend frontend; struct apple_dart_dcp *borrowed; int ret; @@ -878,10 +885,8 @@ static int apple_dart_dispext_prepare(struct apple_dart *dart) return dev_err_probe(dart->dev, ret, "tables not described\n"); if (!(frontend.seen & 4) || frontend.end[1] <= frontend.start[1]) return dev_err_probe(dart->dev, -ENODEV, "no SID16 table region\n"); - bounds = firmware; - bounds.start = frontend.start[1]; - bounds.end = frontend.end[1]; - ret = apple_dart_dcp_import(dart, 16, bounds, &borrowed); + ret = apple_dart_dcp_import(dart, 16, &firmware, frontend.start[1], frontend.end[1], + &borrowed); if (ret) return ret; if (!apple_dart_dcp_registers(borrowed)) @@ -902,10 +907,8 @@ static int apple_dart_dispext_prepare(struct apple_dart *dart) dev_info(dart->dev, "no SID0 table region: SID0 left alone\n"); return 0; } - bounds = firmware; - bounds.start = frontend.start[0]; - bounds.end = frontend.end[0]; - ret = apple_dart_dcp_import(dart, 0, bounds, &borrowed); + ret = apple_dart_dcp_import(dart, 0, &firmware, frontend.start[0], frontend.end[0], + &borrowed); if (ret || !apple_dart_dcp_registers(borrowed)) { dev_warn(dart->dev, "SID0 not adopted (%d); SID16 is\n", ret); return 0; @@ -981,12 +984,10 @@ static int apple_dart_frontend_prepare(struct apple_dart *dart) if (ret) return ret; for (unsigned int i = 0; i < 2; i++) { - struct dcp_adt_tables bounds = firmware; struct device_node *node; - bounds.start = frontend.start[i]; - bounds.end = frontend.end[i]; - ret = apple_dart_dcp_import(dart, i ? 16 : 0, bounds, &borrowed[i]); + ret = apple_dart_dcp_import(dart, i ? 16 : 0, &firmware, frontend.start[i], + frontend.end[i], &borrowed[i]); if (ret) return ret; node = of_find_node_by_path(i ? "disp0_piodma" : "disp0"); diff --git a/drivers/iommu/apple-dart-sleep.c b/drivers/iommu/apple-dart-sleep.c index 630e7101d5876d..b93338c4796ac7 100644 --- a/drivers/iommu/apple-dart-sleep.c +++ b/drivers/iommu/apple-dart-sleep.c @@ -364,8 +364,9 @@ static int apple_dart_sleep_idle(struct apple_dart_sleep_state *s) { struct apple_dart *dart = s->dart; u32 params = readl(dart->regs + DART_PARAMS2); - unsigned int ports = max(FIELD_GET(DART_T8110_PARAMS2_READ_PORTS, params), - FIELD_GET(DART_T8110_PARAMS2_WRITE_PORTS, params)); + unsigned int rports = FIELD_GET(DART_T8110_PARAMS2_READ_PORTS, params); + unsigned int wports = FIELD_GET(DART_T8110_PARAMS2_WRITE_PORTS, params); + unsigned int ports = max(rports, wports); int ret; if (!ports || ports > 4 || dart_power_fault_pending(dart->regs, &s->power)) diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index 0c474454ee82a3..9ddfd0c8093b9c 100644 --- a/drivers/iommu/apple-dart-test.c +++ b/drivers/iommu/apple-dart-test.c @@ -90,6 +90,161 @@ static void apple_dart_test_iommu_specifiers(struct kunit *test) } } +static void apple_dart_test_consumer_window(struct kunit *test) +{ + __be32 value[] = { cpu_to_be32(0x100), 0, cpu_to_be32(0x10), 0 }; + struct property property = { + .name = "apple,dma-range", + .length = sizeof(value), + .value = value, + }; + struct device_node node = { .properties = &property }; + struct of_phandle_args args = { .args_count = 1 }; + struct apple_dart *dart; + struct device *dev; + dma_addr_t dma_min, dma_max; + int i, ret; + + dev = kunit_device_register(test, "apple-dart-consumer-window-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + dart = kunit_kzalloc(test, sizeof(*dart), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dart); + dart->ias = 36; + dart->pgsize = SZ_16K; + dev->of_node = &node; + + /* + * J613's common scanout alias survives both DART defaults, but only + * inside each stream's own window: the external DART excludes its top + * 64 KiB, so the shared aperture must too. + */ + for (i = 0; i < 2; i++) { + dart->dma_min = i ? 0 : 0x10000000000; + dart->dma_max = i ? 0xffffeffff : 0x10fffffffff; + ret = apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, dma_min, (dma_addr_t)0x10000000000); + KUNIT_EXPECT_EQ(test, dma_max, + (dma_addr_t)(i ? 0x10ffffeffff : 0x10fffffffff)); + } + + /* A five-cell stream window narrows the consumer aperture the same way. */ + args.args_count = 5; + args.args[3] = 0xf; + args.args[4] = 0xffff0000; + ret = apple_dart_parse_dma_window(dev, dart, &args, &dma_min, &dma_max); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, dma_min, (dma_addr_t)0x10000000000); + KUNIT_EXPECT_EQ(test, dma_max, (dma_addr_t)0x10ffffeffff); + + /* An override must not make a malformed stream specifier acceptable. */ + args.args[3] = 0; + args.args[4] = 0; + KUNIT_EXPECT_EQ(test, apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max), -EINVAL); + + /* PIODMA is a different consumer of the same external display DART. */ + dev->of_node = NULL; + args.args_count = 1; + args.args[0] = 4; + ret = apple_dart_parse_dma_window(dev, dart, &args, &dma_min, &dma_max); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, dma_min, (dma_addr_t)0); + KUNIT_EXPECT_EQ(test, dma_max, (dma_addr_t)0xffffeffff); +} + +static void apple_dart_test_disjoint_consumer_window(struct kunit *test) +{ + /* 2 GiB at the 1 TiB alias; its low bits start at 2 GiB. */ + __be64 value[] = { cpu_to_be64(0x10080000000), cpu_to_be64(SZ_2G) }; + struct property property = { + .name = "apple,dma-range", + .length = sizeof(value), + .value = value, + }; + struct device_node node = { .properties = &property }; + struct of_phandle_args args = { .args_count = 1 }; + struct apple_dart *dart; + struct device *dev; + dma_addr_t dma_min, dma_max; + + dev = kunit_device_register(test, "apple-dart-disjoint-window-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + dart = kunit_kzalloc(test, sizeof(*dart), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dart); + dart->ias = 36; + dart->pgsize = SZ_16K; + dev->of_node = &node; + + /* The stream's window ends where the consumer's low bits begin. */ + dart->dma_min = 0; + dart->dma_max = SZ_2G - 1; + KUNIT_EXPECT_EQ(test, apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max), -EINVAL); + + /* The same holds for a stream window given by a five-cell specifier. */ + dart->dma_max = DMA_BIT_MASK(dart->ias); + args.args_count = 5; + args.args[1] = 0x100; + args.args[2] = 0; + args.args[3] = 0; + args.args[4] = 0x80000000; + KUNIT_EXPECT_EQ(test, apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max), -EINVAL); + + /* One page of overlap is enough, and only that page is returned. */ + args.args[4] = 0x80004000; + KUNIT_EXPECT_EQ(test, apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max), 0); + KUNIT_EXPECT_EQ(test, dma_min, (dma_addr_t)0x10080000000); + KUNIT_EXPECT_EQ(test, dma_max, (dma_addr_t)0x10080003fff); + dev->of_node = NULL; +} + +static void apple_dart_test_invalid_consumer_window(struct kunit *test) +{ + static const struct { + u64 base, size; + } windows[] = { + { 0, 0 }, + { U64_MAX - SZ_16K + 1, 2 * SZ_16K }, + { 1, SZ_16K }, + { 0, SZ_16K + 1 }, + { 0, BIT_ULL(37) }, + }; + __be64 value[2]; + struct property property = { + .name = "apple,dma-range", + .length = sizeof(value), + .value = value, + }; + struct device_node node = { .properties = &property }; + struct of_phandle_args args = { .args_count = 1 }; + struct apple_dart *dart; + struct device *dev; + dma_addr_t dma_min, dma_max; + int i; + + dev = kunit_device_register(test, "apple-dart-invalid-window-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + dart = kunit_kzalloc(test, sizeof(*dart), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dart); + dart->ias = 36; + dart->pgsize = SZ_16K; + dev->of_node = &node; + for (i = 0; i < ARRAY_SIZE(windows); i++) { + value[0] = cpu_to_be64(windows[i].base); + value[1] = cpu_to_be64(windows[i].size); + KUNIT_EXPECT_EQ(test, apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max), -EINVAL); + } + property.length = sizeof(__be32); + KUNIT_EXPECT_LT(test, apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max), 0); + dev->of_node = NULL; +} + static void apple_dart_test_before_attach(struct kunit *test) { struct apple_dart_master_cfg master = {}; @@ -1326,15 +1481,239 @@ static void apple_dart_test_host_power_tables(struct kunit *test) } #endif +/* A zeroed 16 KiB page marked reserved, as the firmware's tables are. */ +static void apple_dart_test_free_reserved(void *data) +{ + struct page *page = data; + + ClearPageReserved(page); + __free_pages(page, get_order(SZ_16K)); +} + +static u64 *apple_dart_test_reserved_table(struct kunit *test) +{ + struct page *page = alloc_pages(GFP_KERNEL | __GFP_ZERO, get_order(SZ_16K)); + + KUNIT_ASSERT_NOT_NULL(test, page); + SetPageReserved(page); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, apple_dart_test_free_reserved, page), + 0); + return page_address(page); +} + +/* + * fw_mirror from the DART's own state: a T8132 DART its handed-over internal + * DCP names mirrors when locked without reserved tables and not borrowed; any + * other locked T8132 DART (the PMP's) keeps the retained-root path. + */ +static void apple_dart_test_t8132_fw_mirror_selection(struct kunit *test) +{ + struct apple_dart dart = { .locked = true }; + + KUNIT_EXPECT_TRUE(test, apple_dart_selects_fw_mirror(&dart, NULL, true)); + /* A locked T8132 DART no display processor names: the PMP's. */ + KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(&dart, NULL, false)); + + dart.locked = false; + KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(&dart, NULL, true)); + dart.locked = true; + dart.fw_handoff = true; + KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(&dart, NULL, true)); + dart.fw_handoff = false; + dart.preserve_display = true; + KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(&dart, NULL, true)); +} + +/* + * A fw_mirror DART (here a T8132 internal display DART's layout): re-exported + * firmware segments take the protection of the live leaves that map them + * (read-only text, cacheable data); a region whose leaf maps another page + * keeps what it asked for. Any DART that is not fw_mirror is left alone. + */ +static void apple_dart_test_fw_mirror_prot(struct kunit *test) +{ + const u64 fields = GENMASK_ULL(51, 40) | BIT_ULL(0); + const phys_addr_t text_pa = 0x80000000ULL, data_pa = 0x80100000ULL; + const u64 dva = 0x10000000000ULL + (3ULL << 25); + struct iommu_resv_region text = {}, data = {}, moved = {}, mixed = {}, outside = {}; + struct apple_dart_master_cfg master = {}; + struct apple_dart *dart; + LIST_HEAD(head); + u64 *root, *leaf; + void *regs; + + if (PAGE_SIZE < SZ_16K) + kunit_skip(test, "needs kernel pages of at least 16 KiB"); + dart = kunit_kzalloc(test, sizeof(*dart), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dart); + dart->dev = kunit_device_register(test, "apple-dart-fw-mirror-prot-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dart->dev); + regs = vzalloc(APPLE_DART_TEST_REGS_SIZE); + KUNIT_ASSERT_NOT_NULL(test, regs); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, apple_dart_test_vfree, regs), 0); + dart->regs = (__force void __iomem *)regs; + dart->hw = &apple_dart_hw_t8110; + dart->pgsize = SZ_16K; + dart->num_streams = 32; + dart->oas = 42; + dart->locked = true; + dart->fw_mirror = true; + /* The display DARTs' window: 64 GiB at 1 TiB. */ + dart->locked_window[23] = 0x10000000000ULL; + root = apple_dart_test_reserved_table(test); + leaf = apple_dart_test_reserved_table(test); + KUNIT_ASSERT_TRUE(test, IS_ALIGNED(virt_to_phys(root) | virt_to_phys(leaf), SZ_16K)); + writel(((virt_to_phys(root) >> dart->hw->ttbr_shift) << dart->hw->ttbr_addr_field_shift) | + dart->hw->ttbr_valid, dart->regs + DART_TTBR(dart, 23, 0)); + root[3] = (virt_to_phys(leaf) >> 4) | BIT_ULL(0); + /* Text: two read-only pages; data: one read-write page; all cacheable. */ + leaf[0] = fields | (text_pa >> 4) | BIT_ULL(2); + leaf[1] = fields | ((text_pa + SZ_16K) >> 4) | BIT_ULL(2); + leaf[2] = fields | (data_pa >> 4); + /* Two pages that disagree: one read-only, one read-write. */ + leaf[4] = fields | ((data_pa + SZ_32K) >> 4) | BIT_ULL(2); + leaf[5] = fields | ((data_pa + SZ_32K + SZ_16K) >> 4); + text = (struct iommu_resv_region){ .start = text_pa, .dva = dva, .length = SZ_32K, + .prot = IOMMU_READ | IOMMU_WRITE, .type = IOMMU_RESV_TRANSLATED }; + data = (struct iommu_resv_region){ .start = data_pa, .dva = dva + SZ_32K, .length = SZ_16K, + .prot = IOMMU_READ | IOMMU_WRITE, .type = IOMMU_RESV_TRANSLATED }; + moved = (struct iommu_resv_region){ .start = data_pa + SZ_16K, .dva = dva + SZ_32K, + .length = SZ_16K, .prot = IOMMU_READ | IOMMU_WRITE, .type = IOMMU_RESV_TRANSLATED }; + mixed = (struct iommu_resv_region){ .start = data_pa + SZ_32K, .dva = dva + SZ_64K, + .length = SZ_32K, .prot = IOMMU_READ | IOMMU_WRITE, .type = IOMMU_RESV_TRANSLATED }; + /* 64 GiB higher: the same slot bits, outside the window. */ + outside = (struct iommu_resv_region){ .start = text_pa, .dva = dva + SZ_64G, + .length = SZ_32K, .prot = IOMMU_READ | IOMMU_WRITE, .type = IOMMU_RESV_TRANSLATED }; + list_add_tail(&text.list, &head); + list_add_tail(&data.list, &head); + list_add_tail(&moved.list, &head); + list_add_tail(&mixed.list, &head); + list_add_tail(&outside.list, &head); + master.stream_maps[0].dart = dart; + __set_bit(23, master.stream_maps[0].sidmap); + pm_runtime_set_active(dart->dev); + pm_runtime_enable(dart->dev); + + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_CACHE); + KUNIT_EXPECT_EQ(test, data.prot, IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE); + KUNIT_EXPECT_EQ(test, moved.prot, IOMMU_READ | IOMMU_WRITE); + KUNIT_EXPECT_EQ(test, mixed.prot, IOMMU_READ | IOMMU_WRITE); + KUNIT_EXPECT_EQ(test, outside.prot, IOMMU_READ | IOMMU_WRITE); + + /* A leaf table outside reserved RAM is never mapped: nothing changes. */ + text.prot = IOMMU_READ | IOMMU_WRITE; + ClearPageReserved(virt_to_page(leaf)); + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); + SetPageReserved(virt_to_page(leaf)); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); + + /* A four-level root is not walked: nothing changes. */ + text.prot = IOMMU_READ | IOMMU_WRITE; + writel(dart->hw->tcr_4level, dart->regs + DART_TCR(dart, 23)); + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); + writel(0, dart->regs + DART_TCR(dart, 23)); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); + + /* + * Not fw_mirror (a locked DART on the retained-root path, such as the + * T8132 PMP's), with reserved tables, or unlocked: nothing changes. + */ + text.prot = IOMMU_READ | IOMMU_WRITE; + dart->fw_mirror = false; + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); + dart->fw_mirror = true; + dart->fw_handoff = true; + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); + dart->fw_handoff = false; + dart->locked = false; + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); + dart->locked = true; + + /* The same DART back on fw_mirror takes the leaves' protection again. */ + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_CACHE); + pm_runtime_disable(dart->dev); +} + +static struct apple_dart *apple_dart_test_keep_dart(struct kunit *test, const char *name) +{ + struct apple_dart *dart; + + dart = kunit_kzalloc(test, sizeof(*dart), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dart); + dart->dev = kunit_device_register(test, name); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dart->dev); + dev_set_drvdata(dart->dev, dart); + dart->regs = (__force void __iomem *)kunit_kzalloc(test, SZ_16K, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dart->regs); + dart->hw = &apple_dart_hw_t8110; + dart->num_streams = 2; + return dart; +} + +static void apple_dart_test_display_keep(struct kunit *test) +{ + struct device *no_data; + struct apple_dart *unsaved; + struct apple_dart *darts[11]; + char name[32]; + unsigned int i; + + no_data = kunit_device_register(test, "apple-dart-keep-none"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, no_data); + KUNIT_EXPECT_EQ(test, apple_dart_display_keep(no_data, BIT(1), true), -ENODEV); + + unsaved = apple_dart_test_keep_dart(test, "apple-dart-keep-unsaved"); + KUNIT_EXPECT_EQ(test, apple_dart_display_keep(unsaved->dev, BIT(1), false), -ENOENT); + + for (i = 0; i < ARRAY_SIZE(darts); i++) { + snprintf(name, sizeof(name), "apple-dart-keep-%u", i); + darts[i] = apple_dart_test_keep_dart(test, name); + writel(DART_T8110_TCR_TRANSLATE_ENABLE, + darts[i]->regs + DART_TCR(darts[i], 1)); + writel(darts[i]->hw->ttbr_valid | (0x1000 + i), + darts[i]->regs + DART_TTBR(darts[i], 1, 0)); + } + + /* All 10 display DARTs (5 display processors x 2 DARTs) fit in keep[]. */ + for (i = 0; i < 10; i++) + KUNIT_ASSERT_EQ(test, apple_dart_display_keep(darts[i]->dev, BIT(1), true), 0); + + /* An 11th DART exceeds the table. */ + KUNIT_EXPECT_EQ(test, apple_dart_display_keep(darts[10]->dev, BIT(1), true), -ENOSPC); + + /* Clobber saved words and confirm every slot restores them cleanly. */ + for (i = 0; i < 10; i++) { + writel(0, darts[i]->regs + DART_TCR(darts[i], 1)); + writel(0, darts[i]->regs + DART_TTBR(darts[i], 1, 0)); + KUNIT_EXPECT_EQ(test, apple_dart_display_keep(darts[i]->dev, BIT(1), false), 2); + KUNIT_EXPECT_EQ(test, readl(darts[i]->regs + DART_TCR(darts[i], 1)), + DART_T8110_TCR_TRANSLATE_ENABLE); + KUNIT_EXPECT_EQ(test, readl(darts[i]->regs + DART_TTBR(darts[i], 1, 0)), + darts[i]->hw->ttbr_valid | (0x1000 + i)); + KUNIT_EXPECT_EQ(test, apple_dart_display_keep(darts[i]->dev, BIT(1), false), 0); + } +} + static struct kunit_case apple_dart_test_cases[] = { KUNIT_CASE(apple_dart_test_strict_engines), KUNIT_CASE(apple_dart_test_topology), KUNIT_CASE(apple_dart_test_iommu_specifiers), + KUNIT_CASE(apple_dart_test_consumer_window), + KUNIT_CASE(apple_dart_test_disjoint_consumer_window), + KUNIT_CASE(apple_dart_test_invalid_consumer_window), KUNIT_CASE(apple_dart_test_independent_remap_roots), KUNIT_CASE(apple_dart_test_before_attach), KUNIT_CASE(apple_dart_test_locked_handoff), KUNIT_CASE(apple_dart_test_sync_unknown_roots), KUNIT_CASE(apple_dart_test_firmware_roots), + KUNIT_CASE(apple_dart_test_t8132_fw_mirror_selection), + KUNIT_CASE(apple_dart_test_fw_mirror_prot), + KUNIT_CASE(apple_dart_test_display_keep), KUNIT_CASE(apple_dart_test_unmap_flush_after_publish_failure), KUNIT_CASE(apple_dart_test_gated_commands), KUNIT_CASE(apple_dart_test_resume_commands_failure), diff --git a/drivers/iommu/apple-dart-v27-admission.inc b/drivers/iommu/apple-dart-v27-admission.inc index 906be5ef222ef4..7b6c2be51b903e 100644 --- a/drivers/iommu/apple-dart-v27-admission.inc +++ b/drivers/iommu/apple-dart-v27-admission.inc @@ -10,9 +10,7 @@ static bool apple_dart_v27_provider(struct device *dev, resource_size_t base) unsigned int i; if (!IS_ENABLED(CONFIG_APPLE_SOC_SLEEP) || - !(of_machine_is_compatible("apple,j714s") || - (of_machine_is_compatible("apple,j716c") && - of_machine_is_compatible("apple,t6050"))) || + !apple_t6050_sleep_described() || !of_device_is_compatible(dev->of_node, "apple,t6050-dart")) return false; for (i = 0; i < ARRAY_SIZE(ids); i++) diff --git a/drivers/iommu/apple-dart-v27-late.inc b/drivers/iommu/apple-dart-v27-late.inc index 74e663b1e40641..965eaf0f17edc5 100644 --- a/drivers/iommu/apple-dart-v27-late.inc +++ b/drivers/iommu/apple-dart-v27-late.inc @@ -137,12 +137,12 @@ int apple_dart_v27_claim(struct device *dev, struct device *owner, return -EBUSY; } if (dev->driver != &apple_dart_driver.driver || !(d = dev_get_drvdata(dev)) || - !d->v27_provider || !mutex_trylock(&d->v27_lifecycle)) { + !d->v27_provider || down_trylock(&d->v27_lifecycle)) { device_unlock(dev); return -ENODEV; } if (!try_module_get(THIS_MODULE)) { - mutex_unlock(&d->v27_lifecycle); + up(&d->v27_lifecycle); device_unlock(dev); return -ENODEV; } @@ -340,7 +340,7 @@ free: unlock: module_put(THIS_MODULE); put_device(dev); - mutex_unlock(&d->v27_lifecycle); + up(&d->v27_lifecycle); return ret; } EXPORT_SYMBOL_GPL(apple_dart_v27_claim); @@ -459,7 +459,7 @@ int apple_dart_v27_finish(struct apple_dart_v27_lease *l, bool stopped) WRITE_ONCE(d->m5_sleep_owner, NULL); WRITE_ONCE(d->v27_restoring, false); pm_runtime_put_noidle(d->dev); - mutex_unlock(&d->v27_lifecycle); + up(&d->v27_lifecycle); module_put(l->module); put_device(provider); kfree(l); diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 33a29ce9beb045..98aeeb6ac5d796 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -49,6 +49,7 @@ #include #include #include +#include #include #include #include @@ -57,6 +58,9 @@ #include #include +#include +#include + #include "dma-iommu.h" #if IS_ENABLED(CONFIG_APPLE_DART_KUNIT_TEST) @@ -277,6 +281,8 @@ struct apple_dart; struct apple_dart_hw { enum dart_type type; + /* T8110 register layout, SPTM-owned TLB invalidation (T8152) */ + bool gen3; irqreturn_t (*irq_handler)(int irq, void *dev); int (*invalidate_tlb)(struct apple_dart_stream_map *stream_map); void (*enable_remap)(struct apple_dart *dart, int sid, int remap_to); @@ -356,6 +362,9 @@ struct apple_dart_fw_tree { #define APPLE_DART_GAPF_PROTECT BIT(4) struct apple_dart { + bool cold_gen3; + u32 cold_gen3_sids; + bool cold_gen3_pcie; struct device *dev; const struct apple_dart_hw *hw; @@ -379,7 +388,11 @@ struct apple_dart { u32 m5_disp_streams; /* the display pipe's streams before its domain went off */ bool m5_released, m5_changed, m5_display, m5_failed; /* Optional cached evidence; never a sleep-ownership grant. */ - struct mutex v27_lifecycle; + /* + * Held for as long as a sleep lease lasts: taken by the suspend that claims the lease and + * released by the resume that finishes it, in another task. So a semaphore, not a mutex. + */ + struct semaphore v27_lifecycle; struct list_head v27_clients; atomic_t v27_ops; bool v27_provider, v27_lost, v27_noirq_skip, v27_restoring; @@ -391,7 +404,12 @@ struct apple_dart { */ bool display_dark; bool display_tlb_stale; + unsigned int display_writers; + unsigned int display_dark_writers; DECLARE_BITMAP(display_tcr_four, DART_MAX_STREAMS); + /* T8020: its enabled streams and translations, saved at the display's power-down */ + u32 display_enable; + bool display_saved; /* The address filter the loader programs, from the device tree, replayed after a sleep. */ void __iomem *dapf; u64 *dapf_ranges; @@ -449,7 +467,7 @@ struct apple_dart { bool commands_gated; /* TLB commands written, counted under the lock: see apple_dart_t8110_tlb_wait(). */ unsigned long tlb_commands; - /* A handed-off DART a display subsystem scans out through: apple_dart_display_scanout(). */ + /* A locked DART a display subsystem scans out through: apple_dart_display_scanout(). */ bool display_scanout; /* * A real sleep took the ISP host streams' registers: the next runtime resume, its @@ -532,6 +550,17 @@ struct apple_dart { bool cold_ane; u16 managed_sids; bool managed_failed; + /* + * The one page the radio's SID16 may reach, or 0 to keep its bypass. + * Its table is kept for the lifetime of the binding unless probe + * fails and tears the narrowing down before releasing the device. + */ + u64 sid16_page; + struct io_pgtable_ops *sid16_ops; + u32 sid16_ttbr; + u32 sid16_init_tcr; + u32 sid16_init_ttbr; + bool sid16_init_enabled; /* Serialize owned TCR publication against IRQ quarantine. */ spinlock_t managed_lock; struct apple_dart_sleep *sleep_record; @@ -540,6 +569,10 @@ struct apple_dart { unsigned int sleep_writers; bool sleep_closed; + /* Gen3: shared TLBI aperture and this DART's route in it */ + void __iomem *tlbi; + u8 tlbi_route; + DECLARE_BITMAP(remapped, DART_MAX_STREAMS); u8 remap_target[DART_MAX_STREAMS]; @@ -835,9 +868,6 @@ struct apple_dart_domain { struct apple_dart_dcp *dcp; bool finalized; - bool has_dma_range; - dma_addr_t dma_min; - dma_addr_t dma_max; u64 mask; dma_addr_t dma_offset; struct mutex init_lock; @@ -887,16 +917,6 @@ static struct platform_driver apple_dart_driver; static const struct iommu_ops apple_dart_iommu_ops; static bool apple_dart_fault_pending(struct apple_dart *dart); -/* READY bring-up only: userspace must arm its watchdog before probing SID23. */ -static bool apple_dart_dcp_enabled; - -module_param_named(j713_dcp, apple_dart_dcp_enabled, bool, 0600); -MODULE_PARM_DESC(j713_dcp, "Enable explicit J713 DCP DART probe after arming watchdog"); - -static bool apple_dart_frontend_enabled; -module_param_named(j713_display, apple_dart_frontend_enabled, bool, 0600); -MODULE_PARM_DESC(j713_display, "Enable explicit J713 display DART admission after arming watchdog"); - /* The machine's first compatible string, for log lines that name the board. */ static const char *apple_dart_board(void) { @@ -1047,13 +1067,21 @@ static phys_addr_t apple_dart_pte_to_paddr(const struct apple_dart *dart, return (pte & GENMASK_ULL(37, 10)) << 4; } -/* Firmware table pages must remain outside Linux's page allocator. */ +/* + * Firmware table pages must remain outside Linux's page allocator. The boot + * loader says it reserved them with apple,firmware-root-handoff; the walker + * decodes them in the APPLE_DART2 PTE layout, and the handoff paths (retire, + * per-slot invalidate, locked map/unmap) need a DART whose probed version is + * at least 2.2. Only the T8110 family reports a version, so a T6000 DART, + * which shares the APPLE_DART2 layout, never takes the handoff. + */ static bool apple_dart_fw_handoff_enabled(const struct apple_dart *dart) { struct device_node *np = dart->dev->of_node; u32 handoff; - return dart->locked && of_device_is_compatible(np, "apple,t8140-dart") && + return dart->locked && dart->hw->fmt == APPLE_DART2 && + dart->version >= 0x0202 && of_property_count_u32_elems(np, "apple,firmware-root-handoff") == 1 && !of_property_read_u32(np, "apple,firmware-root-handoff", &handoff) && handoff == 1; @@ -1063,9 +1091,10 @@ static bool apple_dart_fw_handoff_enabled(const struct apple_dart *dart) * Whether an available display subsystem, the component master the DRM driver * binds and the loader walks for the scan-out DARTs it hands off, lists a * stream of @np in its iommus: the display pipe scans out through this DART. - * On J700 that is disp0 and dispext0. The DCP and DCPEXT firmware DARTs are - * named only by their coprocessors, and a PCIe device such as the Wi-Fi - * reaches its DART through its host bridge's iommu-map. + * On J700 that is disp0 and dispext0, on J815 disp0, dispext0 and dispext1. + * The DCP and DCPEXT firmware DARTs are named only by their coprocessors, and + * a PCIe device such as the Wi-Fi reaches its DART through its host bridge's + * iommu-map. */ static bool apple_dart_display_scanout(struct device_node *np) { @@ -1764,16 +1793,17 @@ static bool apple_dart_t8110_tlb_settled(struct apple_dart *dart, * held: before a command (@issued 0) until it is idle, after one until * command @issued finished. * - * On J700 the boot loader hands the display DARTs' roots off (fw_handoff). - * There a range invalidate of the internal display's stream 0 can stay busy - * well past DART_T8110_FLUSH_BUSY_TIMEOUT while the display pipe changes - * what it scans out (screen locker, panel power-off, after a resume), - * reading 0x8700e100, and it finishes on its own: the next commands work. - * Giving up fails the mapping of a framebuffer the compositor imports, and - * returns from an unmap while the TLB can still translate to the pages its - * caller frees next. So keep waiting on the DARTs the display subsystem - * scans out through (display_scanout: disp0 and dispext0), not on the - * handed-off DCP firmware DARTs or any other device's DART, for up to + * On J700 (whose boot loader hands the display DARTs' roots off) and on + * J815 (locked, no handoff) a range invalidate of the internal display's + * stream 0 can stay busy well past DART_T8110_FLUSH_BUSY_TIMEOUT while the + * display pipe changes what it scans out (compositor start, screen locker, + * panel power-off, after a resume), reading 0x8700e100, and it finishes on + * its own: the next commands work. Giving up fails the mapping of a + * framebuffer the compositor imports, and returns from an unmap while the + * TLB can still translate to the pages its caller frees next. So keep + * waiting on the locked DARTs the display subsystem scans out through + * (display_scanout: disp0, and dispext0 when the loader locked it), not on + * the DCP firmware DARTs or any other device's DART, for up to * DART_T8110_FLUSH_STALL_TIMEOUT more, without the lock and with interrupts * as the caller had them. Every command here waits for an idle engine * before it is written, so the engine needs no lock meanwhile (the @@ -1796,7 +1826,7 @@ static int apple_dart_t8110_tlb_wait(struct apple_dart *dart, unsigned long *fla !(*status & DART_T8110_TLB_CMD_BUSY), 1, DART_T8110_FLUSH_BUSY_TIMEOUT, false, dart, DART_T8110_TLB_CMD); - if (!ret || !range || !dart->fw_handoff || !dart->display_scanout || + if (!ret || !range || !dart->display_scanout || dart->ctc_flush || dart->sleep_restore.count) return ret; @@ -1998,6 +2028,59 @@ static int apple_dart_fw_invalidate(struct apple_dart_stream_map *stream_map, return 0; } +#define DART_GEN3_TLBI_ROUTE 0x4604 +#define DART_GEN3_TLBI_VALID BIT_ULL(60) +#define DART_GEN3_TLBI_ROUTE_FIELD GENMASK_ULL(59, 56) +#define DART_GEN3_TLBI_SID GENMASK_ULL(55, 48) + +/* + * Gen3 DARTs (T8152) are owned by the SPTM, and their TLB command register at + * 0x80 answers translation queries instead of flushing. A stream is + * invalidated the way iBoot does it: write a 128-bit payload (valid, route, + * SID) to the shared TLBI aperture, then broadcast a TLBI, which the DART + * snoops and applies to that stream. + */ +static int +apple_dart_gen3_hw_invalidate_tlb(struct apple_dart_stream_map *stream_map) +{ + struct apple_dart *dart = stream_map->dart; + unsigned long flags; + u64 hcr = 0; + int sid; + + spin_lock_irqsave(&dart->lock, flags); + /* + * The DART snoops an EL1&0 TLBI, as iBoot and aura (EL2 without VHE) + * issue it. A VHE kernel's TLBI VALE1OS targets EL2&0 while + * HCR_EL2.TGE is set, so clear TGE around it, as KVM does to reach + * the EL1&0 regime. + */ + if (is_kernel_in_hyp_mode()) { + hcr = read_sysreg(hcr_el2); + write_sysreg(hcr & ~HCR_TGE, hcr_el2); + isb(); + } + for_each_set_bit(sid, stream_map->sidmap, dart->num_streams) { + u64 lo = DART_GEN3_TLBI_VALID | + FIELD_PREP(DART_GEN3_TLBI_ROUTE_FIELD, dart->tlbi_route) | + FIELD_PREP(DART_GEN3_TLBI_SID, sid); + + dma_wmb(); + asm volatile("stp %0, xzr, [%1]\n" + "dsb ish\n" + ".inst 0xd50881bf\n" /* tlbi vale1os, xzr */ + "dsb osh\n" + : : "r"(lo), "r"(dart->tlbi) : "memory"); + } + if (is_kernel_in_hyp_mode()) { + write_sysreg(hcr, hcr_el2); + isb(); + } + spin_unlock_irqrestore(&dart->lock, flags); + + return 0; +} + static int apple_dart_t8020_hw_invalidate_tlb(struct apple_dart_stream_map *stream_map) { @@ -2168,6 +2251,15 @@ static int apple_dart_t8110_v2_unlock(struct apple_dart *dart) return -EPERM; if (!(readl(dart->regs + DART_T8110_DIAG_LOCK) & DART_T8110_DIAG_LOCK_ON_ERR)) return 0; + /* + * A Gen3 DART's TLB command register serves translation queries and + * cannot unlock it. Its streams stay stopped until the DART is reset. + */ + if (dart->hw->gen3) { + dev_err_ratelimited(dart->dev, + "locked on error; a Gen3 DART is not unlocked\n"); + return -EOPNOTSUPP; + } /* Unlock after acknowledging a lock-on-error exception. */ __set_bit(0, stream_map.sidmap); @@ -2354,6 +2446,160 @@ static bool apple_dart_managed_static_bypass(u32 tcr) return (tcr & ~DART_T8110_TCR_BYPASS_DAPF) == DART_T8110_TCR_BYPASS_DART; } +/* SID16 translates through the one-page table this driver published. */ +static bool apple_dart_managed_sid16_narrowed(struct apple_dart *dart) +{ + u32 tcr = apple_dart_readl(dart, DART_TCR(dart, 16)); + + return dart->sid16_ops && tcr == DART_T8110_TCR_TRANSLATE_ENABLE && + apple_dart_readl(dart, DART_TTBR(dart, 16, 0)) == dart->sid16_ttbr && + (apple_dart_readl(dart, dart->hw->enable_streams) & BIT(16)); +} + +/* + * SID16 needs no more than one page, but a bypassed stream reaches all of + * physical memory, and nothing routes a requester to it that admission can + * check. Translate it through a table that maps only that page. Called after + * admission and before any radio DMA is set up; the SID16 TLB is flushed after + * switching TCR to translate so no firmware entry survives. + */ +static int apple_dart_managed_narrow_sid16(struct apple_dart *dart) +{ + struct apple_dart_stream_map stream = { .dart = dart }; + struct io_pgtable_cfg cfg = { + .pgsize_bitmap = SZ_16K, + .ias = 36, + .oas = dart->oas, + .coherent_walk = 1, + .iommu_dev = dart->dev, + }; + struct io_pgtable_ops *ops; + size_t mapped = 0; + phys_addr_t root; + u32 tcr, ttbr, init_tcr, init_ttbr; + int ret; + + if (dart->hw->type != DART_T8110 || dart->num_streams <= 16 || + dart->hw->ttbr_count != 1 || dart->pgsize != SZ_16K || + dart->oas < 36 || dart->sid16_page >= BIT_ULL(dart->oas)) + return -EINVAL; + if (dart->sid16_ops) + return -EBUSY; + init_tcr = apple_dart_readl(dart, DART_TCR(dart, 16)); + init_ttbr = apple_dart_readl(dart, DART_TTBR(dart, 16, 0)); + if (init_tcr == dart->hw->tcr_disabled) { + if (init_ttbr & dart->hw->ttbr_valid) + return -EBUSY; + } else if (apple_dart_managed_static_bypass(init_tcr)) { + if (!dart->supports_bypass || !dart->hw->tcr_bypass) + return -EBUSY; + } else { + return -EBUSY; + } + ops = alloc_io_pgtable_ops(APPLE_DART2, &cfg, NULL); + if (!ops) + return -ENOMEM; + if (cfg.apple_dart_cfg.n_ttbrs != 1 || cfg.apple_dart_cfg.n_levels != 3) { + ret = -EINVAL; + goto err_free; + } + ret = ops->map_pages(ops, dart->sid16_page, dart->sid16_page, SZ_16K, 1, + IOMMU_READ | IOMMU_WRITE | IOMMU_MMIO, GFP_KERNEL, &mapped); + if (!ret && (mapped != SZ_16K || + ops->iova_to_phys(ops, dart->sid16_page) != dart->sid16_page)) + ret = -EIO; + if (ret) + goto err_free; + + dart->sid16_init_tcr = init_tcr; + dart->sid16_init_ttbr = init_ttbr; + dart->sid16_init_enabled = !!(apple_dart_readl(dart, dart->hw->enable_streams) & BIT(16)); + root = virt_to_phys(cfg.apple_dart_cfg.ttbr[0]); + dart->sid16_ttbr = dart->hw->ttbr_valid | + (root >> dart->hw->ttbr_shift) << dart->hw->ttbr_addr_field_shift; + /* From here on the table may be walked until torn down and flushed. */ + dart->sid16_ops = ops; + apple_dart_writel(dart, dart->sid16_ttbr, DART_TTBR(dart, 16, 0)); + ttbr = apple_dart_readl(dart, DART_TTBR(dart, 16, 0)); + if (ttbr != dart->sid16_ttbr) { + dev_err(dart->dev, "SID16 TTBR0 readback failed (TTBR0 %#x)\n", ttbr); + return -EIO; + } + /* Plain translation: sleep restore replays the TCR as it reads back. */ + apple_dart_writel(dart, DART_T8110_TCR_TRANSLATE_ENABLE, DART_TCR(dart, 16)); + tcr = apple_dart_readl(dart, DART_TCR(dart, 16)); + if (tcr != DART_T8110_TCR_TRANSLATE_ENABLE) { + dev_err(dart->dev, "SID16 narrowing readback failed (TCR %#x)\n", tcr); + return -EIO; + } + __set_bit(16, stream.sidmap); + ret = dart->hw->invalidate_tlb(&stream); + if (ret) { + dev_err(dart->dev, "SID16 TLB invalidation failed (%d)\n", ret); + return ret; + } + apple_dart_writel(dart, BIT(16), dart->hw->enable_streams); + if (!apple_dart_managed_sid16_narrowed(dart)) { + dev_err(dart->dev, "SID16 enable readback failed (ENABLE %#x)\n", + apple_dart_readl(dart, dart->hw->enable_streams)); + return -EIO; + } + dev_info(dart->dev, "SID16 bypass narrowed to page %#llx\n", dart->sid16_page); + return 0; + +err_free: + free_io_pgtable_ops(ops); + return ret; +} + +static void apple_dart_managed_unnarrow_sid16(struct apple_dart *dart) +{ + struct apple_dart_stream_map stream = { .dart = dart }; + u32 tcr, enabled, restore_tcr; + + if (!dart->sid16_ops) + return; + + __set_bit(16, stream.sidmap); + if (!dart->sid16_init_enabled) { + apple_dart_writel(dart, BIT(16), DART_T8110_DISABLE_STREAMS); + if (apple_dart_readl(dart, dart->hw->enable_streams) & BIT(16)) { + dev_warn(dart->dev, + "failed to tear down SID16 narrowing; keeping page table\n"); + return; + } + } + + /* + * Static bypass restores the documented bypass request (including DAPF) + * while checking exact readback against the saved entry TCR. + */ + restore_tcr = dart->sid16_init_tcr == dart->hw->tcr_disabled ? + dart->hw->tcr_disabled : dart->hw->tcr_bypass; + apple_dart_writel(dart, restore_tcr, DART_TCR(dart, 16)); + tcr = apple_dart_readl(dart, DART_TCR(dart, 16)); + if (tcr != dart->sid16_init_tcr) { + dev_warn(dart->dev, "failed to tear down SID16 narrowing; keeping page table\n"); + return; + } + + apple_dart_writel(dart, dart->sid16_init_ttbr, DART_TTBR(dart, 16, 0)); + enabled = apple_dart_readl(dart, dart->hw->enable_streams); + if (apple_dart_readl(dart, DART_TTBR(dart, 16, 0)) != dart->sid16_init_ttbr || + !!(enabled & BIT(16)) != dart->sid16_init_enabled || + dart->hw->invalidate_tlb(&stream)) { + dev_warn(dart->dev, "failed to tear down SID16 narrowing; keeping page table\n"); + return; + } + + free_io_pgtable_ops(dart->sid16_ops); + dart->sid16_ops = NULL; + dart->sid16_ttbr = 0; + dart->sid16_init_tcr = 0; + dart->sid16_init_ttbr = 0; + dart->sid16_init_enabled = false; +} + static ssize_t j713_radio_fault_state_show(struct device *dev, struct device_attribute *attr, char *buf) { @@ -2463,9 +2709,15 @@ static int apple_dart_managed_admit(struct apple_dart *dart, bool *init_bypass) return -EBUSY; } } - /* ADT assigns SID16 a static bypass role, independently of radio data. */ + /* + * ADT assigns SID16 a static bypass role, independently of radio data. + * Once narrowed to its one page by this driver, it stays so. + */ reserved_tcr = apple_dart_readl(dart, DART_TCR(dart, 16)); - if (!apple_dart_managed_static_bypass(reserved_tcr)) { + if (dart->sid16_ops) { + if (!apple_dart_managed_sid16_narrowed(dart)) + return -EBUSY; + } else if (!apple_dart_managed_static_bypass(reserved_tcr)) { if (reserved_tcr != dart->hw->tcr_disabled || !dart->supports_bypass) return -EBUSY; for (idx = 0; idx < dart->hw->ttbr_count; idx++) @@ -2590,6 +2842,39 @@ static int apple_dart_hw_reset(struct apple_dart *dart) struct apple_dart_stream_map stream_map; int i; + if (dart->cold_gen3) { + stream_map.dart = dart; + bitmap_zero(stream_map.sidmap, DART_MAX_STREAMS); + for (i = 0; i < 32; i++) + if (dart->cold_gen3_sids & BIT(i)) + __set_bit(i, stream_map.sidmap); + if (dart->cold_gen3_pcie) + bitmap_set(stream_map.sidmap, 0, 253); + apple_dart_hw_disable_dma(&stream_map); + apple_dart_hw_clear_all_ttbrs(&stream_map); + apple_dart_apply_own_tunables(dart); + apple_dart_writel(dart, apple_dart_readl(dart, dart->hw->enable_streams) | + dart->cold_gen3_sids, dart->hw->enable_streams); + if (dart->cold_gen3_pcie) { + /* ADT reserves 253/255 for host transactions, including MSI + * writes to AIC. Stream 254 belongs to firmware; preserve it. + */ + for (i = 253; i <= 255; i += 2) { + apple_dart_writel(dart, DART_T8110_TCR_BYPASS_DART, + DART_TCR(dart, i)); + __set_bit(i, stream_map.sidmap); + } + for (i = 0; i < 8; i++) { + u32 reg = dart->hw->enable_streams + i * 4; + u32 enabled = apple_dart_readl(dart, reg); + + enabled |= i == 7 ? (U32_MAX & ~BIT(30)) : U32_MAX; + apple_dart_writel(dart, enabled, reg); + } + } + return dart->hw->invalidate_tlb(&stream_map); + } + if (dart->isp_host) return apple_dart_isp_host_reset(dart); if (dart->managed_sids || dart->cold_ane) @@ -2691,6 +2976,9 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, * publishing the page table or powering another DART failed. */ for_each_stream_map(i, domain, map) { + unsigned long flags; + bool dark; + stream.dart = map->dart; for (j = 0; j < BITS_TO_LONGS(stream.dart->num_streams); j++) stream.sidmap[j] = atomic_long_read(&map->sidmap[j]); @@ -2700,10 +2988,21 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, * Its display is powered off: publish to memory only. With its streams off * nothing walks the tables, and the TLB is invalidated before they're on. */ - if (READ_ONCE(stream.dart->display_dark)) { + spin_lock_irqsave(&stream.dart->managed_lock, flags); + dark = stream.dart->display_dark; + if (dark) { + stream.dart->display_dark_writers++; + WRITE_ONCE(stream.dart->display_tlb_stale, true); + } else { + stream.dart->display_writers++; + } + spin_unlock_irqrestore(&stream.dart->managed_lock, flags); + if (dark) { ret = stream.dart->locked ? apple_dart_hw_sync_locked(cfg, &stream, true) : 0; - WRITE_ONCE(stream.dart->display_tlb_stale, true); + spin_lock_irqsave(&stream.dart->managed_lock, flags); + stream.dart->display_dark_writers--; + spin_unlock_irqrestore(&stream.dart->managed_lock, flags); err = err ?: ret; continue; } @@ -2715,12 +3014,18 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, ret = stream.dart->locked ? apple_dart_hw_sync_locked(cfg, &stream, true) : 0; apple_dart_sleep_writer_put(stream.dart, gate); + spin_lock_irqsave(&stream.dart->managed_lock, flags); + stream.dart->display_writers--; + spin_unlock_irqrestore(&stream.dart->managed_lock, flags); err = err ?: ret; continue; } ret = pm_runtime_resume_and_get(stream.dart->dev); if (ret < 0) { apple_dart_sleep_writer_put(stream.dart, gate); + spin_lock_irqsave(&stream.dart->managed_lock, flags); + stream.dart->display_writers--; + spin_unlock_irqrestore(&stream.dart->managed_lock, flags); dev_err_ratelimited(stream.dart->dev, "failed to power DART for TLB synchronization: %d\n", ret); err = err ?: ret; @@ -2736,8 +3041,11 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, /* The range registers take the DVA the device issues. */ start = first + domain->dma_offset; end = last + domain->dma_offset; - if (range && (stream.dart->fw_mirror || stream.dart->fw_handoff) && - stream.dart->version >= 0x0202) + /* Gen3 has no range command; invalidate the complete stream. */ + if (stream.dart->hw->gen3) + ret = stream.dart->hw->invalidate_tlb(&stream); + else if (range && (stream.dart->fw_mirror || stream.dart->fw_handoff) && + stream.dart->version >= 0x0202) ret = apple_dart_fw_invalidate(&stream, start, end); else if (range && stream.dart->locked && stream.dart->version >= 0x0202) ret = apple_dart_t8110_hw_tlb_command_range(&stream, op, true, @@ -2748,6 +3056,9 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, apple_dart_managed_quarantine(stream.dart); pm_runtime_put(stream.dart->dev); apple_dart_sleep_writer_put(stream.dart, gate); + spin_lock_irqsave(&stream.dart->managed_lock, flags); + stream.dart->display_writers--; + spin_unlock_irqrestore(&stream.dart->managed_lock, flags); err = err ?: ret; } return err; @@ -3000,6 +3311,91 @@ int apple_dart_fw_remote(struct device *dev, dma_addr_t iova, bool write, } EXPORT_SYMBOL_GPL(apple_dart_fw_remote); +/* + * Memory a co-processor's firmware may share with the host for a CPU mapping: DRAM, + * at or above the first System RAM (Apple SoCs place every device's registers below + * it), that isn't System RAM. That leaves the firmware's own carveouts, which the + * kernel doesn't use or map, and refuses memory the kernel allocates from, which its + * linear map also covers with other attributes. + */ +static bool apple_dart_fw_phys_shareable(phys_addr_t pa, size_t size) +{ + phys_addr_t page_start, page_end, end; + + if (!pa || !size || check_add_overflow(pa, (phys_addr_t)size, &end) || + end > (phys_addr_t)~(PAGE_SIZE - 1)) + return false; + page_start = ALIGN_DOWN(pa, PAGE_SIZE); + page_end = ALIGN(end, PAGE_SIZE); + return region_intersects(0, page_end, IORESOURCE_SYSTEM_RAM, + IORES_DESC_NONE) != REGION_DISJOINT && + region_intersects(page_start, page_end - page_start, + IORESOURCE_SYSTEM_RAM, + IORES_DESC_NONE) == REGION_DISJOINT; +} + +static phys_addr_t apple_dart_fw_range_page(struct device *dev, + struct iommu_domain *domain, + dma_addr_t iova, unsigned int flags) +{ + phys_addr_t phys = 0; + + /* + * On an identity domain iommu_iova_to_phys() returns iova verbatim: skip + * APPLE_DART_FW_LINUX there so an unmapped DVA is never treated as a + * translation and APPLE_DART_FW_RETAINED is still consulted. + */ + if ((flags & APPLE_DART_FW_LINUX) && (domain->type & __IOMMU_DOMAIN_PAGING)) + phys = iommu_iova_to_phys(domain, iova); + if (!phys && (flags & APPLE_DART_FW_RETAINED) && + apple_dart_fw_remote(dev, iova, false, &phys)) + phys = 0; + return phys; +} + +/* + * The physical range behind a buffer a co-processor's firmware names by its DVA, for + * a CPU mapping. @flags chooses what resolves a DVA: APPLE_DART_FW_LINUX, the + * mappings Linux made (on a paging domain), and APPLE_DART_FW_RETAINED, those the + * firmware kept from the boot loader (apple_dart_fw_remote()). Every IOMMU page the + * buffer touches is resolved, at the domain's smallest page and from page boundary + * to page boundary, as the buffer need not start on one. *@phys is set only when + * they translate to one contiguous range whose CPU-page-rounded span + * apple_dart_fw_phys_shareable() accepts. -EINVAL for an empty, wrapping or + * flagless request, -ENODEV without an IOMMU domain, -ENOENT when its first byte + * doesn't translate, -ERANGE when a later page lies elsewhere or doesn't translate, + * -EACCES when the range isn't such memory. + */ +int apple_dart_fw_range(struct device *dev, dma_addr_t iova, size_t size, + unsigned int flags, phys_addr_t *phys) +{ + struct iommu_domain *domain = iommu_get_domain_for_dev(dev); + unsigned long pgsize; + dma_addr_t addr, last; + phys_addr_t start, phys_last; + + if (!size || !(flags & (APPLE_DART_FW_LINUX | APPLE_DART_FW_RETAINED)) || + check_add_overflow(iova, (dma_addr_t)size - 1, &last)) + return -EINVAL; + if (!domain) + return -ENODEV; + start = apple_dart_fw_range_page(dev, domain, iova, flags); + if (!start) + return -ENOENT; + if (check_add_overflow(start, (phys_addr_t)size - 1, &phys_last)) + return -ERANGE; + pgsize = domain->pgsize_bitmap ? 1UL << __ffs(domain->pgsize_bitmap) : PAGE_SIZE; + for (addr = ALIGN_DOWN(iova, pgsize) + pgsize; addr && addr <= last; addr += pgsize) + if (apple_dart_fw_range_page(dev, domain, addr, flags) != + start + (addr - iova)) + return -ERANGE; + if (!apple_dart_fw_phys_shareable(start, size)) + return -EACCES; + *phys = start; + return 0; +} +EXPORT_SYMBOL_GPL(apple_dart_fw_range); + static phys_addr_t apple_dart_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova) { @@ -3256,8 +3652,9 @@ static int __apple_dart_finalize_domain(struct apple_dart_domain *dart_domain, { struct apple_dart *dart = cfg->stream_maps[0].dart; struct io_pgtable_cfg pgtbl_cfg; - dma_addr_t dma_min = dart_domain->has_dma_range ? dart_domain->dma_min : cfg->dma_min; - dma_addr_t dma_max = dart_domain->has_dma_range ? dart_domain->dma_max : cfg->dma_max; + /* of_xlate already narrowed this to any consumer apple,dma-range. */ + dma_addr_t dma_min = cfg->dma_min; + dma_addr_t dma_max = cfg->dma_max; u64 translated_max; u32 ias; int ret = 0; @@ -3319,6 +3716,17 @@ static int __apple_dart_finalize_domain(struct apple_dart_domain *dart_domain, .iommu_dev = dart->dev, }; + if (dart->cold_gen3) { + if ((dma_min ^ dma_max) & ~DMA_BIT_MASK(36)) { + ret = -ERANGE; + goto done; + } + /* Gen3 selects the high DMA window separately from its two-level + * 16K page-table indices, as with iBoot's display streams. + */ + pgtbl_cfg.ias = 36; + } + if (dart->locked) { unsigned long *sidmap; int sid; @@ -3775,22 +4183,8 @@ static struct iommu_domain *apple_dart_domain_alloc_paging(struct device *dev) if (dev) { struct apple_dart_master_cfg *cfg = dev_iommu_priv_get(dev); - u64 window[2]; int ret; - if (of_property_present(dev->of_node, "apple,dma-range")) { - ret = of_property_read_u64_array(dev->of_node, "apple,dma-range", - window, 2); - if (!ret) - ret = apple_dart_dma_window(window[0], window[1], - &dart_domain->dma_max); - if (ret) { - kfree(dart_domain); - return ERR_PTR(ret); - } - dart_domain->dma_min = window[0]; - dart_domain->has_dma_range = true; - } ret = apple_dart_finalize_domain(dart_domain, cfg); if (ret) { kfree(dart_domain); @@ -3871,10 +4265,40 @@ static void apple_dart_domain_free(struct iommu_domain *domain) kfree(dart_domain); } +static int apple_dart_validate_dma_window(struct device *dev, + const struct apple_dart *dart, + dma_addr_t dma_min, dma_addr_t length, + dma_addr_t *dma_max) +{ + if (!length) + return -EINVAL; + if (!IS_ALIGNED(dma_min, dart->pgsize) || !IS_ALIGNED(length, dart->pgsize)) { + dev_err(dev, "Unaligned DMA window %pad, %pad (0x%x)\n", + &dma_min, &length, dart->pgsize); + return -EINVAL; + } + if (check_add_overflow(dma_min, length - 1, dma_max)) { + dev_err(dev, "DMA window length (%pad) overflows range for start %pad\n", + &length, &dma_min); + return -EINVAL; + } + + /* High bits may select an alias, but the window must fit within it. */ + if ((dma_min ^ *dma_max) & ~DMA_BIT_MASK(dart->ias)) { + dev_err(dev, "Invalid DMA window for ias=%d\n", dart->ias); + return -EINVAL; + } + return 0; +} + /* * Work out the DMA window of one "iommus" specifier. One cell is the stream * ID alone and keeps the window of the DART node. Five cells add the 64-bit - * start and length of the window that the device uses. + * start and length of the window that the device uses. A consumer's + * apple,dma-range narrows either window: its bits above the DART's ias pick + * the alias the consumer uses, and its low bits are intersected with the + * stream's own window, masked the same way. The DART translates only the low + * bits, so an address outside the stream's window must never be handed out. */ static int apple_dart_parse_dma_window(struct device *dev, const struct apple_dart *dart, @@ -3882,43 +4306,47 @@ static int apple_dart_parse_dma_window(struct device *dev, dma_addr_t *dma_min, dma_addr_t *dma_max) { - dma_addr_t length; + dma_addr_t length, consumer_max, low_min, low_max; + u64 mask = DMA_BIT_MASK(dart->ias); + u64 window[2]; + int ret; + if (args->args_count != 1 && args->args_count != 5) + return -EINVAL; *dma_min = dart->dma_min; *dma_max = dart->dma_max; - if (args->args_count == 1) - return 0; - if (args->args_count != 5) - return -EINVAL; - - length = ((dma_addr_t)args->args[3] << 32) | args->args[4]; - if (!length) - return -EINVAL; - - if (*dma_min != 0 || *dma_max != DMA_BIT_MASK(dart->ias)) - dev_err(dev, "still using legacy \"apple,dma-range\" property\n"); - - *dma_min = ((dma_addr_t)args->args[1] << 32) | args->args[2]; - - if (!IS_ALIGNED(*dma_min, dart->pgsize) || - !IS_ALIGNED(length, dart->pgsize)) { - dev_err(dev, "Unaligned DMA window %pad, %pad (0x%x)\n", - dma_min, &length, dart->pgsize); - return -EINVAL; - } - if (check_add_overflow(*dma_min, length - 1, dma_max)) { - dev_err(dev, "DMA window length (%pad) overflows range for start %pad\n", - &length, dma_min); - return -EINVAL; + if (args->args_count == 5) { + if (*dma_min != 0 || *dma_max != DMA_BIT_MASK(dart->ias)) + dev_err(dev, "still using legacy \"apple,dma-range\" property\n"); + *dma_min = ((dma_addr_t)args->args[1] << 32) | args->args[2]; + length = ((dma_addr_t)args->args[3] << 32) | args->args[4]; + ret = apple_dart_validate_dma_window(dev, dart, *dma_min, length, dma_max); + if (ret) + return ret; } - /* Ensure that the DMA window does not exceed the DART's ias. */ - if ((*dma_min ^ *dma_max) & ~DMA_BIT_MASK(dart->ias)) { - dev_err(dev, "Invalid DMA window for ias=%d\n", dart->ias); + /* Narrow to the consumer aperture before intersecting its DART windows. */ + if (!of_property_present(dev->of_node, "apple,dma-range")) + return 0; + ret = of_property_read_u64_array(dev->of_node, "apple,dma-range", + window, ARRAY_SIZE(window)); + if (ret) + return ret; + ret = apple_dart_validate_dma_window(dev, dart, window[0], window[1], + &consumer_max); + if (ret) + return ret; + + low_min = max(window[0] & mask, *dma_min & mask); + low_max = min(consumer_max & mask, *dma_max & mask); + if (low_min > low_max) { + dev_err(dev, "DMA window %#llx..%#llx does not overlap stream window %pad..%pad\n", + window[0], (u64)consumer_max, dma_min, dma_max); return -EINVAL; } - + *dma_min = (window[0] & ~mask) | low_min; + *dma_max = (window[0] & ~mask) | low_max; return 0; } @@ -3940,6 +4368,9 @@ static int apple_dart_of_xlate(struct device *dev, return i; sid = args->args[0]; + if (dart->cold_gen3 && (dart->cold_gen3_pcie ? (sid < 0 || sid >= 253) : + (sid < 0 || sid >= 32 || !(dart->cold_gen3_sids & BIT(sid))))) + return -EPERM; if (dart->isp_host && sid != 0 && sid != 12) return -EINVAL; if (dart->cold_ane && sid != 0) @@ -4562,6 +4993,116 @@ static void apple_dart_get_fw_resv_regions(struct device *dev, } } +/* + * A fw_mirror DART (locked, no reserved-table handoff, not borrowed) on a + * three-level root: a boot loader may re-export the firmware's own segments + * as iommu-addresses, which the core maps read-write, and uncached for a + * non-coherent client such as a DCP. The firmware's leaves say what those + * pages are: its text read-only, all of it cacheable. A Linux table in a slot + * the firmware holds must mirror its leaves exactly (apple_dart_fw_slot_mirrors(), + * apple_dart_check_fw_map()), so give each such region the protection the + * live leaves give every one of its pages. A region whose pages are not mapped + * there, map elsewhere or disagree keeps its protection, and the attach then + * refuses it as before. A region whose protection already matches is left + * alone, so this changes only a mapping the attach would otherwise refuse. + */ +static void __apple_dart_fw_mirror_prot(struct apple_dart_master_cfg *cfg, + struct device *dev, struct list_head *head) +{ + const int mask = IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE; + struct iommu_resv_region *region; + struct apple_dart *dart; + phys_addr_t table; + u64 *root, span, base; + size_t entries; + u32 ttbr, tcr = 0; + int sid; + + if (!cfg || !cfg->stream_maps[0].dart || cfg->stream_maps[1].dart) + return; + dart = cfg->stream_maps[0].dart; + if (!dart->fw_mirror || dart->fw_handoff || !dart->locked || + dart->hw->fmt != APPLE_DART2) + return; + entries = dart->pgsize / sizeof(u64); + sid = find_first_bit(cfg->stream_maps[0].sidmap, dart->num_streams); + if (sid >= dart->num_streams || + bitmap_weight(cfg->stream_maps[0].sidmap, dart->num_streams) != 1) + return; + if (pm_runtime_resume_and_get(dart->dev) < 0) + return; + /* Read both registers while the DART is held powered. */ + ttbr = apple_dart_readl(dart, DART_TTBR(dart, sid, 0)); + if (dart->hw->tcr_4level) + tcr = apple_dart_readl(dart, DART_TCR(dart, sid)); + pm_runtime_put(dart->dev); + if (!(ttbr & dart->hw->ttbr_valid) || (tcr & dart->hw->tcr_4level)) + return; + ttbr &= ~dart->hw->ttbr_valid; + if (dart->hw->ttbr_addr_field_shift) + ttbr >>= dart->hw->ttbr_addr_field_shift; + table = ((phys_addr_t)ttbr) << dart->hw->ttbr_shift; + /* Only a firmware table in reserved RAM is mapped write-back, as elsewhere. */ + if (!apple_dart_fw_table_ram(dart, table)) + return; + root = memremap(table, dart->pgsize, MEMREMAP_WB); + if (!root) + return; + /* A three-level root walks one span of the stream's window (DVA bits 14..35). */ + span = BIT_ULL(ilog2(dart->pgsize) + 2 * ilog2(entries)); + base = READ_ONCE(dart->locked_window[sid]) & ~(span - 1); + + list_for_each_entry(region, head, list) { + u64 *leaf = NULL; + size_t mapped_slot = entries; + int prot = -1; + + if (region->type != IOMMU_RESV_TRANSLATED || !region->length || + !IS_ALIGNED(region->dva | region->start | region->length, dart->pgsize)) + continue; + /* Outside the window the slot bits would alias another region's leaves. */ + if (region->dva < base || region->length > span || + region->dva - base > span - region->length) + continue; + for (u64 off = 0; off < region->length; off += dart->pgsize) { + u64 dva = region->dva + off; /* bits 14..35: the 1 TiB base drops out */ + size_t slot = (dva >> (ilog2(dart->pgsize) + ilog2(entries))) & (entries - 1); + size_t idx = (dva >> ilog2(dart->pgsize)) & (entries - 1); + u64 entry = READ_ONCE(root[slot]); + phys_addr_t phys; + int page_prot; + + if (slot != mapped_slot) { + if (leaf) + memunmap(leaf); + leaf = apple_dart_fw_table_decode(dart, entry, &table) ? + memremap(table, dart->pgsize, MEMREMAP_WB) : NULL; + mapped_slot = slot; + } + if (!leaf || + !apple_dart_fw_leaf_decode(READ_ONCE(leaf[idx]), 0, &phys, &page_prot) || + phys != region->start + off || (prot >= 0 && page_prot != prot)) { + prot = -1; + break; + } + prot = page_prot; + } + if (leaf) + memunmap(leaf); + if (prot >= 0 && (region->prot & mask) != (prot & mask)) { + dev_info(dev, "firmware segment %pad+%#zx: protection %#x as its live leaves (asked %#x)\n", + ®ion->dva, region->length, prot & mask, region->prot & mask); + region->prot = (region->prot & ~mask) | (prot & mask); + } + } + memunmap(root); +} + +static void apple_dart_fw_mirror_prot(struct device *dev, struct list_head *head) +{ + __apple_dart_fw_mirror_prot(dev_iommu_priv_get(dev), dev, head); +} + static void apple_dart_get_resv_regions(struct device *dev, struct list_head *head) { @@ -4591,6 +5132,7 @@ static void apple_dart_get_resv_regions(struct device *dev, /* Keep the translated-domain requirement and inherited translations. */ iommu_dma_get_resv_regions(dev, head); + apple_dart_fw_mirror_prot(dev, head); apple_dart_get_fw_resv_regions(dev, head); } @@ -4946,11 +5488,13 @@ static irqreturn_t apple_dart_irq(int irq, void *dev) * faulting. Its line can be shared or still pending, so leave it alone; * apple_dart_host_power_off() waits for a handler already past this. */ - if (READ_ONCE(dart->commands_gated) || READ_ONCE(dart->host_off)) + if (READ_ONCE(dart->commands_gated) || READ_ONCE(dart->host_off) || + READ_ONCE(dart->display_dark)) return IRQ_NONE; if (pm_runtime_resume_and_get(dart->dev) < 0) return IRQ_NONE; - if (!READ_ONCE(dart->commands_gated) && !READ_ONCE(dart->host_off)) + if (!READ_ONCE(dart->commands_gated) && !READ_ONCE(dart->host_off) && + !READ_ONCE(dart->display_dark)) ret = dart->hw->irq_handler(irq, dev); pm_runtime_put(dart->dev); return ret; @@ -4958,6 +5502,14 @@ static irqreturn_t apple_dart_irq(int irq, void *dev) static bool apple_dart_is_locked(struct apple_dart *dart) { + /* + * apple,retain-translation: the bootloader left live stream tables + * that a co-processor's firmware depends on, but did not set the lock + * bit (T8152 dart-sbr: AOP and audio ADMAC streams). Treat it as + * locked so the tables are inherited rather than reset. + */ + if (of_property_read_bool(dart->dev->of_node, "apple,retain-translation")) + return true; return !!(apple_dart_readl(dart, dart->hw->lock) & dart->hw->lock_bit); } @@ -5349,6 +5901,67 @@ static bool apple_dart_is_available(struct device_node *np) return false; } +/* Whether @consumer names @dart_np in its iommus. */ +static bool apple_dart_np_is_iommu_of(const struct device_node *consumer, + const struct device_node *dart_np) +{ + struct of_phandle_args args; + + for (int i = 0; !of_parse_phandle_with_args(consumer, "iommus", "#iommu-cells", i, &args); + i++) { + bool match = args.np == dart_np; + + of_node_put(args.np); + if (match) + return true; + } + return false; +} + +/* + * Whether @dart_np serves an available T8132 internal display processor that + * the boot loader handed over with its firmware clocks (apple,clock-ids, from + * the ADT's /arm-io/disp0): its firmware DART (the processor's iommus) or its + * display DART (its PIODMA's). Those clocks are what the firmware-27 backend + * needs and what tells its handoff from the M4 26.6.2 one, whose DARTs are + * borrowed. The DART is keyed on what uses it, not on its address, the board + * or the firmware build: a PMP or external display DART is never named here, + * and an idle main DCP (a Mac mini's) is not handed over. + */ +static bool apple_dart_serves_t8132_dcp(const struct device_node *dart_np) +{ + struct device_node *np, *child; + bool serves = false; + + for_each_compatible_node(np, NULL, "apple,t8132-dcp") { + if (serves || !of_device_is_available(np) || + !of_property_present(np, "apple,clock-ids")) + continue; + serves = apple_dart_np_is_iommu_of(np, dart_np); + for_each_child_of_node(np, child) + if (!serves && apple_dart_np_is_iommu_of(child, dart_np)) + serves = true; + } + return serves; +} + +/* + * Whether a locked DART keeps its firmware's roots and mirrors Linux mappings + * into them (fw_mirror): it is locked, its boot loader handed over no reserved + * tables (fw_handoff), and no display driver borrows its live roots + * (preserve_display). That is the DART's own state; which DARTs take it is the + * SoC's (T6041, T6050, T8140, T8142: every one) or, on T8132, the DARTs of its + * handed-over internal display processor (@t8132_dcp). Other locked T8132 + * DARTs, the PMP's among them, keep the retained-root path they always had. + */ +static bool apple_dart_selects_fw_mirror(const struct apple_dart *dart, + const struct device_node *np, bool t8132_dcp) +{ + if (!dart->locked || dart->fw_handoff || dart->preserve_display) + return false; + return apple_dart_keeps_locked_roots(np) || t8132_dcp; +} + static int apple_dart_probe(struct platform_device *pdev) { int ret, sid; @@ -5361,17 +5974,32 @@ static int apple_dart_probe(struct platform_device *pdev) bool tunneled = dev->of_node->parent && of_node_name_prefix(dev->of_node->parent, "usb4-pcie-tunnel-"); - bool j713_display, j713_dcpext, j713_dispext, j713_radio; + bool j713_display, j713_dcpext, j713_dispext, j713_radio, t8132_dcp = false; + bool cold_avd = of_device_is_compatible(dev->of_node, "apple,t8152-avd-dart"); /* * The M4 internal display DARTs are live: DCP firmware (SID23) - * and the scanout/PIODMA frontend (SID0/SID16) keep using them. Leave - * both untouched until userspace, with its watchdog armed, opts in. + * and the scanout/PIODMA frontend (SID0/SID16) keep using them. + * Adopt them only when the internal DCP node carries the qualified + * firmware handoff; leave them untouched otherwise. */ res = platform_get_resource(pdev, IORESOURCE_MEM, 0); - j713_display = res && !tunneled && apple_t8132_firmware_path() && + j713_display = res && !tunneled && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && (res->start == 0x30a300000ULL || res->start == 0x30a340000ULL); + /* + * An internal DCP handed over with its firmware clocks runs the + * firmware-27 backend, which DMAs through ordinary domains (RTKit and + * IOMFB shared memory, PIODMA maps) as on T6041. Its two display DARTs + * are then not borrowed: they keep their firmware's locked roots the way + * T6041's do (fw_mirror below). The borrowed path admits only the 26.6.2 + * layout and reserves its whole SID23 window from generic DMA. + */ + t8132_dcp = res && !tunneled && + of_device_is_compatible(dev->of_node, "apple,t8132-dart") && + apple_dart_serves_t8132_dcp(dev->of_node); + if (t8132_dcp) + j713_display = false; /* The external DCP firmware DARTs (SID23) of dcpext0 and dcpext1. */ j713_dcpext = res && !tunneled && apple_t8132_firmware_path() && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && @@ -5382,28 +6010,23 @@ static int apple_dart_probe(struct platform_device *pdev) (res->start == 0x286300000ULL || res->start == 0x48a300000ULL); /* The radio DART's fault interrupt is not described by the loader. */ j713_radio = res && !tunneled && apple_t8132_managed_radio() && - of_machine_is_compatible("apple,t8132") && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && res->start == 0x490000000ULL; - /* - * Off the qualified firmware nothing hands the internal display DARTs - * over, but the running DCP still uses them: never reset them. - */ - if (res && !tunneled && !apple_t8132_firmware_path() && - of_machine_is_compatible("apple,t8132") && - of_device_is_compatible(dev->of_node, "apple,t8132-dart") && - (res->start == 0x30a300000ULL || res->start == 0x30a340000ULL)) { - dev_info(dev, "Leaving inherited display DART untouched off the qualified firmware\n"); - return -ENODEV; - } - if (j713_display && !IS_ENABLED(CONFIG_APPLE_DART_J713_DCP)) - return dev_err_probe(dev, -EOPNOTSUPP, - "retained J713 display requires CONFIG_APPLE_DART_J713_DCP=y\n"); - if (j713_display && - ((res->start == 0x30a300000ULL && !READ_ONCE(apple_dart_frontend_enabled)) || - (res->start == 0x30a340000ULL && !READ_ONCE(apple_dart_dcp_enabled)))) { - dev_info(dev, "Leaving inherited display DART untouched; explicit guarded probe required\n"); - return -ENODEV; + if (j713_display) { + struct device_node *owner = of_find_node_by_path("dcp"); + bool handed_over = owner && + of_device_is_available(owner) && + of_device_is_compatible(owner, "apple,t8132-dcp") && + apple_dart_dcp_firmware(owner); + + of_node_put(owner); + if (!handed_over) { + dev_info(dev, "Leaving inherited display DART untouched\n"); + return -ENODEV; + } + if (!IS_ENABLED(CONFIG_APPLE_DART_J713_DCP)) + return dev_err_probe(dev, -EOPNOTSUPP, + "retained T8132 display requires CONFIG_APPLE_DART_J713_DCP=y\n"); } if (j713_dcpext) { /* Its block is powered only if the loader handed the DCP over. */ @@ -5466,12 +6089,26 @@ static int apple_dart_probe(struct platform_device *pdev) dart->dev = dev; dart->hw = of_device_get_match_data(dev); dart->tunneled = tunneled; + /* Streams 0-2 of the AVD instance, the ones the decoder uses. */ + if (cold_avd) { + dart->cold_gen3 = true; + dart->cold_gen3_sids = 0x7; + } + if (of_device_is_compatible(dev->of_node, "apple,t8152-acio-dart")) { + dart->cold_gen3 = true; + dart->cold_gen3_sids = 0x0fff0fff; + } + if (of_device_is_compatible(dev->of_node, "apple,t8152-pciec-dart")) { + dart->cold_gen3 = true; + dart->cold_gen3_pcie = true; + dart->cold_gen3_sids = U32_MAX; + } dart->cold_ane = of_device_is_compatible(dev->of_node, "apple,t8140-ane-dart") || of_device_is_compatible(dev->of_node, "apple,t8142-ane-dart"); if (dart->cold_ane && !IS_BUILTIN(CONFIG_APPLE_DART)) return -EOPNOTSUPP; dart->isp_host = of_device_is_compatible(dev->of_node, "apple,t6050-isp-dart"); - dart->isp_sleep = dart->isp_host && of_machine_is_compatible("apple,j714s"); + dart->isp_sleep = dart->isp_host && apple_t6050_sleep_described(); dart->power_retained = dart->isp_host; dart->per_stream = dart->isp_host || of_device_is_compatible(dev->of_node, "apple,t8140-dart") || @@ -5488,6 +6125,12 @@ static int apple_dart_probe(struct platform_device *pdev) ids[0] != 1 || ids[1] != 2) return -EINVAL; dart->managed_sids = BIT(1) | BIT(2); + /* An identity-mapped page needs a 36-bit, 3-level table. */ + if (of_property_present(dev->of_node, "apple,sid16-page") && + (of_property_read_u64(dev->of_node, "apple,sid16-page", &dart->sid16_page) || + !dart->sid16_page || !IS_ALIGNED(dart->sid16_page, SZ_16K) || + dart->sid16_page >= BIT_ULL(36))) + return dev_err_probe(dev, -EINVAL, "invalid apple,sid16-page\n"); } spin_lock_init(&dart->managed_lock); ret = apple_dart_cio_init(dart, resource_size(res), j713_display); @@ -5525,7 +6168,7 @@ static int apple_dart_probe(struct platform_device *pdev) } } spin_lock_init(&dart->lock); - mutex_init(&dart->v27_lifecycle); + sema_init(&dart->v27_lifecycle, 1); INIT_LIST_HEAD(&dart->v27_clients); atomic_set(&dart->v27_ops, 0); dart->v27_provider = res && apple_dart_v27_provider(dev, res->start); @@ -5624,6 +6267,18 @@ static int apple_dart_probe(struct platform_device *pdev) * not admitted: never enable that level IRQ for one block alone. */ dart->irq = -1; + } else if (dart->hw->gen3) { + /* + * Gen3 reports a fault like a v2 DART: the per-SID exception + * bitmap and records, acknowledged by writing the bitmap back + * (apple_dart_t8110_v2_irq()). Only the unlock after a + * lock-on-error exception differs: see apple_dart_t8110_v2_unlock(). + */ + dart->irq = platform_get_irq_optional(pdev, 0); + if (dart->irq == -ENXIO) + dart->irq = -1; + else if (dart->irq < 0) + return dart->irq; } else if (dart->preserve_display || j713_radio) { dart->irq = platform_get_irq_optional(pdev, 0); if (dart->irq == -ENXIO) @@ -5660,7 +6315,7 @@ static int apple_dart_probe(struct platform_device *pdev) ret = devm_pm_runtime_enable(dev); if (ret) goto err_clk_disable; - if (tunneled && dart->tunables) { + if (tunneled && dart->tunables && !dart->cold_gen3) { dev_dbg(dev, "applying %zu PCIe-C DART tunables\n", dart->tunables->sz); apple_dart_apply_tunables(dart, dart->tunables); @@ -5676,7 +6331,15 @@ static int apple_dart_probe(struct platform_device *pdev) * pages, a 32-bit IOVA, a 36-bit PA and as many streams as its * register block describes. */ - if (dart->hw->type == DART_T8110) { + if (dart->cold_gen3_pcie) { + dart->pgsize = SZ_16K; + dart->supports_bypass = true; + dart->ias = 42; + dart->oas = 42; + dart->num_streams = 256; + dart->four_level = false; + dart->version = 0x300; + } else if (dart->hw->type == DART_T8110) { dart->pgsize = 1 << DART_PCIEC_PAGE_SHIFT; dart->supports_bypass = true; dart->ias = DART_PCIEC_ADDR_WIDTH; @@ -5873,58 +6536,119 @@ static int apple_dart_probe(struct platform_device *pdev) ret = -EBUSY; goto err_clk_disable; } + if (dart->hw->gen3) { + struct resource *tlbi; + + /* Cold setup only for the instances a T8152 compatible selects. */ + if (!dart->locked && !dart->cold_gen3) { + dev_err(dev, "Gen3 DART is not locked; cold setup is not supported\n"); + ret = -ENODEV; + goto err_clk_disable; + } + if (dart->cold_gen3 && + (dart->locked || dart->version != 0x300 || !dart->tunables || + (dart->cold_gen3_pcie ? (!tunneled || !dev->pm_domain) : + cold_avd ? (dart->num_streams != 16 || !dev->pm_domain) : + dart->num_streams != 32) || + (apple_dart_readl(dart, dart->hw->enable_streams) & dart->cold_gen3_sids))) { + ret = -EINVAL; + goto err_clk_disable; + } + if (dart->cold_gen3_pcie) { + for (sid = 0; sid < 8; sid++) { + u32 mask = sid == 7 ? GENMASK(28, 0) : U32_MAX; + u32 reg = dart->hw->enable_streams + sid * 4; + + if (apple_dart_readl(dart, reg) & mask) { + ret = -EBUSY; + goto err_clk_disable; + } + } + } + /* The aperture is shared by every Gen3 DART: map, do not claim. */ + tlbi = platform_get_resource_byname(pdev, IORESOURCE_MEM, "tlbi"); + if (!tlbi || resource_size(tlbi) < 16) { + dev_err(dev, "Gen3 DART needs its TLBI aperture\n"); + ret = -EINVAL; + goto err_clk_disable; + } + dart->tlbi = devm_ioremap(dev, tlbi->start, resource_size(tlbi)); + if (!dart->tlbi) { + ret = -ENOMEM; + goto err_clk_disable; + } + dart->tlbi_route = apple_dart_readl(dart, DART_GEN3_TLBI_ROUTE) & 0xf; + dev_info(dev, "Gen3 DART, version %#x, TLBI route %u\n", + dart->version, dart->tlbi_route); + } + apple_dart_parse_sleep_list(dart, res, "apple,sleep-prepare", &dart->sleep_prepare); apple_dart_parse_sleep_list(dart, res, "apple,sleep-restore", &dart->sleep_restore); apple_dart_parse_sleep_list(dart, res, "apple,sleep-restore-late", &dart->sleep_restore_late); /* Reserved table-page lifetime requires the matched three-level loader. */ dart->fw_handoff = apple_dart_fw_handoff_enabled(dart); - dart->display_scanout = dart->fw_handoff && apple_dart_display_scanout(dev->of_node); + /* Only a locked DART takes the range invalidates apple_dart_t8110_tlb_wait() waits out. */ + dart->display_scanout = dart->locked && apple_dart_display_scanout(dev->of_node); /* * Preserve our retained-root path when no reserved-table handoff exists. * T6050's boot loader leaves every display DART locked on four-level * roots of its own (dart-dcpextN SID 23, dart-dispextN SIDs 0 and 16). */ - dart->fw_mirror = dart->locked && !dart->fw_handoff && - (of_device_is_compatible(dev->of_node, "apple,t6041-dart") || - of_device_is_compatible(dev->of_node, "apple,t6050-dart") || - of_device_is_compatible(dev->of_node, "apple,t8140-dart") || - of_device_is_compatible(dev->of_node, "apple,t8142-dart")); + dart->fw_mirror = apple_dart_selects_fw_mirror(dart, dev->of_node, t8132_dcp); /* - * J614s may arrive with the MTP live after the boot keyboard used it. - * Do not reset its DART unless there is no advertised handoff. + * The firmware-27 backend runs on the locked roots alone: a DART that + * is not locked, or whose boot loader also handed over reserved tables, + * is not the handoff it was written for. Refuse either, saying which. */ - if (of_machine_is_compatible("apple,j614s") && - res->start == 0x514800000ULL) { + if (t8132_dcp && dart->fw_mirror) + dev_info(dev, "T8132 internal display DART: locked roots kept (mirror)\n"); + else if (t8132_dcp && !dart->locked) + dev_err(dev, "T8132 internal display DART: NOT locked: refusing\n"); + else if (t8132_dcp) + dev_err(dev, "T8132 internal display DART: locked with a reserved-table handoff: refusing\n"); + if (t8132_dcp && !dart->fw_mirror) { + ret = -EINVAL; + goto err_clk_disable; + } + /* + * A T6040/T6041 MTP (apple,t6041-mtp on both) may arrive live after the + * boot keyboard used it; its firmware cannot be restarted. Do not reset + * the DART it sits behind unless there is no advertised handoff. This + * follows the MTP node and its iommus link, so it holds on every board + * with that MTP. + */ + if (of_device_is_compatible(dev->of_node, "apple,t6041-dart")) { struct device_node *mtp, *iommu; const char *handoff; bool live, advertised; - mtp = of_find_node_by_path("/mtp@514600000"); + mtp = of_find_compatible_node(NULL, NULL, "apple,t6041-mtp"); iommu = mtp ? of_parse_phandle(mtp, "iommus", 0) : NULL; - advertised = mtp && of_find_property(mtp, "apple,rtkit-handoff", NULL); - live = advertised && of_device_is_compatible(mtp, "apple,t6041-mtp") && + advertised = iommu == dev->of_node && + of_find_property(mtp, "apple,rtkit-handoff", NULL); + live = advertised && !of_property_read_string(mtp, "apple,rtkit-handoff", &handoff) && !strcmp(handoff, "mtp-live-v1"); - if (advertised && (!live || iommu != dev->of_node || dart->hw->type != DART_T8110 || + if (advertised && (!live || dart->hw->type != DART_T8110 || dart->locked || tunneled || !dart->supports_bypass || !apple_dart_streams_bypassed(dart))) { of_node_put(iommu); of_node_put(mtp); - dev_err(dev, "Refusing invalid J614s live MTP DART handoff\n"); + dev_err(dev, "Refusing invalid live MTP DART handoff\n"); ret = -EINVAL; goto err_clk_disable; } if (live) { dart->retained_mtp = true; - dev_info(dev, "Retaining the live J614s MTP bypass\n"); + dev_info(dev, "Retaining the live MTP bypass\n"); } of_node_put(iommu); of_node_put(mtp); } dart->fw_tree = dart->fw_mirror && of_device_is_compatible(dev->of_node, "apple,t6050-dart"); - if (apple_t8132_live_mtp() && of_machine_is_compatible("apple,t8132") && + if (apple_t8132_live_mtp() && res->start == 0x394800000ULL && dart->hw->type == DART_T8110 && !dart->locked && !tunneled && dart->supports_bypass && apple_dart_streams_bypassed(dart)) { @@ -5991,7 +6715,8 @@ static int apple_dart_probe(struct platform_device *pdev) ret = apple_dart_retain_radio(dart); if (ret) goto err_clk_disable; - if (init_bypass) { + /* With a named page, a disabled SID16 is narrowed, never bypassed. */ + if (init_bypass && !dart->sid16_page) { struct apple_dart_stream_map stream = { .dart = dart }; u32 bypass_tcr; @@ -6005,6 +6730,13 @@ static int apple_dart_probe(struct platform_device *pdev) } apple_dart_writel(dart, BIT(16), dart->hw->enable_streams); } + if (dart->sid16_page) { + ret = apple_dart_managed_narrow_sid16(dart); + if (ret) { + ret = dev_err_probe(dev, ret, "cannot narrow the SID16 bypass\n"); + goto err_clk_disable; + } + } /* ENABLE is write-one-to-set; no foreign stream changes state. */ apple_dart_writel(dart, dart->managed_sids, dart->hw->enable_streams); } else if (!dart->locked && !dart->retained_mtp && !dart->live_mtp && !dart->preserve_display) { @@ -6014,7 +6746,7 @@ static int apple_dart_probe(struct platform_device *pdev) } /* Borrowed display state: never acknowledge someone else's fault. */ - if (dart->locked && !dart->preserve_display) + if (dart->locked && !dart->preserve_display && !dart->hw->gen3) apple_dart_drain_stale_exceptions(dart); /* Refuse an already pending inherited fault before joining the shared IRQ. */ @@ -6103,6 +6835,8 @@ static int apple_dart_probe(struct platform_device *pdev) err_clk_disable: if (dart->managed_sids && dart->retained && !READ_ONCE(dart->managed_failed)) apple_dart_managed_quarantine(dart); + if (dart->sid16_ops) + apple_dart_managed_unnarrow_sid16(dart); /* Do not schedule suspend on failed radio or display adoption. */ if (dart->retained || dart->preserve_display) pm_runtime_put_noidle(dev); @@ -6151,6 +6885,21 @@ int apple_dart_resume_commands(struct device *dev) } EXPORT_SYMBOL_GPL(apple_dart_resume_commands); +static bool apple_dart_tunables_lock(const struct apple_dart *dart) +{ + size_t i; + + if (!dart->tunables) + return false; + + for (i = 0; i < dart->tunables->sz; ++i) { + if (dart->tunables->values[i].offset == dart->hw->lock && + (dart->tunables->values[i].value & dart->hw->lock_bit)) + return true; + } + return false; +} + /* * System sleep has quiesced every downstream device. PCIe-C calls this * before stopping APPCLK because its domain reset also loses DART state, @@ -6162,7 +6911,7 @@ int apple_dart_save_tunnel_state(struct device *dev) unsigned int sid, idx; if (!dart || !dart->tunneled || dart->locked || - dart->hw->type != DART_T8020 || dart->tunables) + dart->hw->type != DART_T8020 || apple_dart_tunables_lock(dart)) return -EOPNOTSUPP; guard(spinlock_irqsave)(&dart->lock); @@ -6190,7 +6939,7 @@ int apple_dart_restore_tunnel_state(struct device *dev) int ret; if (!dart || !dart->tunneled || dart->locked || - dart->hw->type != DART_T8020 || dart->tunables) + dart->hw->type != DART_T8020 || apple_dart_tunables_lock(dart)) return -EOPNOTSUPP; if (!dart->tunnel_state_saved || READ_ONCE(dart->commands_gated)) return -EINVAL; @@ -6198,6 +6947,8 @@ int apple_dart_restore_tunnel_state(struct device *dev) ret = apple_dart_hw_reset(dart); if (ret) return ret; + if (dart->tunables) + apple_dart_apply_own_tunables(dart); for (sid = 0; sid < dart->num_streams; sid++) { for (idx = 0; idx < dart->hw->ttbr_count; idx++) @@ -6211,10 +6962,12 @@ int apple_dart_restore_tunnel_state(struct device *dev) } EXPORT_SYMBOL_GPL(apple_dart_restore_tunnel_state); +DEFINE_GUARD(apple_dart_v27_lifecycle, struct semaphore *, down(_T), up(_T)) + static void apple_dart_remove(struct platform_device *pdev) { struct apple_dart *dart = platform_get_drvdata(pdev); - guard(mutex)(&dart->v27_lifecycle); + guard(apple_dart_v27_lifecycle)(&dart->v27_lifecycle); if (dart->cold_ane) { dev_warn(&pdev->dev, "cold ANE DART retained until reset\n"); @@ -6269,11 +7022,11 @@ static void apple_dart_shutdown(struct platform_device *pdev) struct apple_dart *dart = platform_get_drvdata(pdev); /* - * A sleep lease that lost its retained state keeps this mutex for good, so that nothing + * A sleep lease that lost its retained state keeps this semaphore for good, so that nothing * reuses the DART before the platform reset. The reset is what follows here: waiting for - * the mutex would hang the shutdown. + * it would hang the shutdown. */ - if (!mutex_trylock(&dart->v27_lifecycle)) { + if (down_trylock(&dart->v27_lifecycle)) { dev_info(&pdev->dev, "shutdown: left as its sleep lease pinned it\n"); return; } @@ -6285,7 +7038,7 @@ static void apple_dart_shutdown(struct platform_device *pdev) */ if (apple_dart_has_borrowed(dart)) apple_dart_fail_borrowed(dart, "shutdown"); - mutex_unlock(&dart->v27_lifecycle); + up(&dart->v27_lifecycle); } static const struct apple_dart_hw apple_dart_hw_t8103 = { @@ -6369,6 +7122,33 @@ static const struct apple_dart_hw apple_dart_hw_t6000 = { .ttbr_count = 4, }; +static const struct apple_dart_hw apple_dart_hw_gen3 = { + .type = DART_T8110, + .gen3 = true, + .irq_handler = apple_dart_t8110_irq, + .invalidate_tlb = apple_dart_gen3_hw_invalidate_tlb, + .fmt = APPLE_DART2, + .max_sid_count = 256, + + .enable_streams = DART_T8110_ENABLE_STREAMS, + .lock = DART_T8110_PROTECT, + .lock_bit = DART_T8110_PROTECT_TTBR_TCR, + + .error = DART_T8110_ERROR, + + .tcr = DART_T8110_TCR, + .tcr_enabled = DART_T8110_TCR_TRANSLATE_ENABLE, + .tcr_disabled = 0, + .tcr_bypass = DART_T8110_TCR_BYPASS_DAPF | DART_T8110_TCR_BYPASS_DART, + .tcr_4level = DART_T8110_TCR_FOUR_LEVEL, + + .ttbr = DART_T8110_TTBR, + .ttbr_valid = DART_T8110_TTBR_VALID, + .ttbr_addr_field_shift = DART_T8110_TTBR_ADDR_FIELD_SHIFT, + .ttbr_shift = DART_T8110_TTBR_SHIFT, + .ttbr_count = 1, +}; + static const struct apple_dart_hw apple_dart_hw_t8110 = { .type = DART_T8110, .irq_handler = apple_dart_t8110_irq, @@ -7246,6 +8026,10 @@ static const struct dev_pm_ops apple_dart_pm_ops = { }; static const struct of_device_id apple_dart_of_match[] = { + { .compatible = "apple,t8152-dart-gen3", .data = &apple_dart_hw_gen3 }, + { .compatible = "apple,t8152-avd-dart", .data = &apple_dart_hw_gen3 }, + { .compatible = "apple,t8152-acio-dart", .data = &apple_dart_hw_gen3 }, + { .compatible = "apple,t8152-pciec-dart", .data = &apple_dart_hw_gen3 }, { .compatible = "apple,t8103-dart", .data = &apple_dart_hw_t8103 }, { .compatible = "apple,t8103-usb4-dart", .data = &apple_dart_hw_t8103_usb4 }, { .compatible = "apple,t8110-dart", .data = &apple_dart_hw_t8110 }, @@ -7288,8 +8072,9 @@ static int apple_dart_tlb_command(struct apple_dart *dart, u32 command) static int apple_dart_idle(struct apple_dart *dart) { u32 params = readl(dart->regs + DART_PARAMS2); - unsigned int ports = max(FIELD_GET(DART_T8110_PARAMS2_READ_PORTS, params), - FIELD_GET(DART_T8110_PARAMS2_WRITE_PORTS, params)); + unsigned int rports = FIELD_GET(DART_T8110_PARAMS2_READ_PORTS, params); + unsigned int wports = FIELD_GET(DART_T8110_PARAMS2_WRITE_PORTS, params); + unsigned int ports = max(rports, wports); if (!ports || ports > 4 || apple_dart_fault_pending(dart)) return -EIO; @@ -7686,6 +8471,198 @@ int apple_dart_gapf_ready(struct device *dev) } EXPORT_SYMBOL_GPL(apple_dart_gapf_ready); +/* + * T8020-type display DARTs, around their DCP's power-down. On the M1 both of them are + * in the DCP's CPU domain and share one interrupt, so from the power-down to the + * power-up neither is read (host_off), and maps go to memory only (display_dark). + * + * The DCP's power cycle resets the display DART, its lock included (measured on J313), + * while the boot loader's wake after a real sleep sets it up locked again. So at the + * power-up the translations saved at the power-down are written back when they were + * lost and the DART is unlocked; lost and still locked, it stays off. + */ +static int apple_dart_display_dark_exit(struct apple_dart *dart); + +/* + * Close admission to display DART MMIO and drain in-flight TLB flushes, map + * TCR readers, and fault IRQ handlers before the display domain powers down. + */ +static int apple_dart_display_dark_enter(struct apple_dart *dart) +{ + unsigned long flags; + unsigned int sid, tries; + bool entered = false; + + if (!READ_ONCE(dart->display_dark)) { + for (sid = 0; sid < dart->num_streams; sid++) + __assign_bit(sid, dart->display_tcr_four, + readl(dart->regs + DART_TCR(dart, sid)) & + dart->hw->tcr_4level); + spin_lock_irqsave(&dart->managed_lock, flags); + if (!dart->display_dark) { + WRITE_ONCE(dart->display_dark, true); + entered = true; + } + spin_unlock_irqrestore(&dart->managed_lock, flags); + } + + for (tries = 0; tries < 10000; tries++) { + bool busy; + + spin_lock_irqsave(&dart->managed_lock, flags); + busy = dart->display_writers != 0; + spin_unlock_irqrestore(&dart->managed_lock, flags); + if (!busy) + break; + usleep_range(10, 20); + } + if (tries == 10000) { + if (entered) + apple_dart_display_dark_exit(dart); + dev_err(dart->dev, "display DART TLB writers did not drain before power-down\n"); + return -EBUSY; + } + + /* Serialize with map paths reading DART_TCR under dart->lock. */ + spin_lock_irqsave(&dart->lock, flags); + spin_unlock_irqrestore(&dart->lock, flags); + + if (dart->irq > 0) + synchronize_irq(dart->irq); + return 0; +} + +static int apple_dart_display_dark_exit(struct apple_dart *dart) +{ + struct apple_dart_stream_map all = { .dart = dart }; + unsigned long flags; + unsigned int tries; + int ret; + + bitmap_fill(all.sidmap, dart->num_streams); + for (tries = 0; tries < 10000; tries++) { + bool stale = false; + + spin_lock_irqsave(&dart->managed_lock, flags); + if (!dart->display_dark) { + spin_unlock_irqrestore(&dart->managed_lock, flags); + return 0; + } + if (!dart->display_dark_writers) { + stale = READ_ONCE(dart->display_tlb_stale); + WRITE_ONCE(dart->display_tlb_stale, false); + if (!stale) { + WRITE_ONCE(dart->display_dark, false); + spin_unlock_irqrestore(&dart->managed_lock, flags); + return 0; + } + } + spin_unlock_irqrestore(&dart->managed_lock, flags); + if (stale) { + ret = dart->hw->invalidate_tlb(&all); + if (ret) { + spin_lock_irqsave(&dart->managed_lock, flags); + WRITE_ONCE(dart->display_tlb_stale, true); + spin_unlock_irqrestore(&dart->managed_lock, flags); + dev_err(dart->dev, "TLB invalidation at power-on failed: %d\n", + ret); + return ret; + } + continue; + } + usleep_range(10, 20); + } + dev_err(dart->dev, "display DART dark writers did not drain at power-on\n"); + return -EBUSY; +} + +static int apple_dart_t8020_display_streams(struct apple_dart *dart, u32 streams, bool on, + bool flush) +{ + struct apple_dart_stream_map map = { .dart = dart }; + void __iomem *enable = dart->regs + dart->hw->enable_streams; + unsigned long bits = streams; + unsigned int sid, idx; + u32 error; + int ret = 0; + + if (on) { + if (!READ_ONCE(dart->host_off) && !READ_ONCE(dart->display_dark)) + return 0; + if (dart->display_saved && !apple_dart_state_retained(dart)) { + /* Not rewritable: it stays off and dark, and its streams stay off. */ + if (apple_dart_is_locked(dart)) { + dev_err(dart->dev, "translations lost at the power-down, and locked\n"); + return -EIO; + } + /* Reset with its domain: set up as at a resume, with its translations */ + ret = apple_dart_hw_reset(dart); + if (ret && ret != -EBUSY) + dev_warn(dart->dev, "reset at power-on: %d\n", ret); + /* Keep target streams disabled until dark drain and TLB flush succeed. */ + writel(readl(enable) & ~streams, enable); + for (sid = 0; sid < dart->num_streams; sid++) { + for (idx = 0; idx < dart->hw->ttbr_count; idx++) + writel(dart->save_ttbr[sid][idx], + dart->regs + DART_TTBR(dart, sid, idx)); + writel(dart->save_tcr[sid], dart->regs + DART_TCR(dart, sid)); + } + ret = 0; + dev_dbg(dart->dev, "translations put back at power-on\n"); + } + error = readl(dart->regs + DART_T8020_ERROR); + if (error & DART_T8020_ERROR_FLAG) + writel(error, dart->regs + DART_T8020_ERROR); + /* + * Drain dark page-table writers and invalidate the TLB before + * enabling streams or reopening DMA. + */ + scoped_guard(spinlock_irqsave, &dart->managed_lock) + WRITE_ONCE(dart->display_tlb_stale, true); + ret = apple_dart_display_dark_exit(dart); + if (ret) + return ret; + if (dart->display_saved) + writel(readl(enable) | (dart->display_enable & streams), enable); + dart->host_off_slept = false; + dart->display_saved = false; + dart->sleep_flushed = false; + WRITE_ONCE(dart->host_off, false); + return 0; + } + + /* + * The first power-down call sets it off, flushed or not (the display DART's comes from + * its firmware, without a flush). A later one, as after a sleep that didn't reach the + * commit, may find the domains off already, and leaves it. + */ + if (READ_ONCE(dart->host_off)) + return 0; + if (!READ_ONCE(dart->display_dark)) { + apple_dart_save_state(dart); + dart->display_enable = readl(enable); + dart->display_saved = true; + } + ret = apple_dart_display_dark_enter(dart); + if (ret) + return ret; + writel(readl(enable) & ~streams, enable); + if (flush) { + for_each_set_bit(sid, &bits, dart->num_streams) + set_bit(sid, map.sidmap); + ret = dart->hw->invalidate_tlb(&map); + if (ret) { + dev_err(dart->dev, "flush for a power-down failed: %d\n", ret); + return ret; + } + dart->sleep_flushed = true; + } + /* Its interrupt handler checks this before it reads anything. */ + WRITE_ONCE(dart->host_off, true); + + return 0; +} + /* * What macOS writes to T8140's display DARTs around a display power cycle: * measured under aura, with the offsets the driver has no name for. It never @@ -7695,6 +8672,57 @@ EXPORT_SYMBOL_GPL(apple_dart_gapf_ready); * Stopping again after a sleep that never reached the commit does nothing: the * domains may be off by then. */ +/* + * T6041: a display DART is locked, so the driver neither saves nor restores its TCR / TTBR, and + * after a real sleep the panel stayed black with everything else up. Keep the words of @streams + * before the sleep (save), and after it write back what differs (!save). Returns how many words + * were written back. + */ +int apple_dart_display_keep(struct device *dev, u32 streams, bool save) +{ + /* Two DARTs (DCP and display) for each of the T6041's five display processors. */ + static struct { struct apple_dart *dart; u32 tcr[32]; u32 ttbr[32][4]; } keep[10]; + struct apple_dart *dart = dev_get_drvdata(dev); + unsigned long bits = streams; + unsigned int sid, idx, k, n = 0; + + if (!dart) + return -ENODEV; + for (k = 0; k < ARRAY_SIZE(keep) && keep[k].dart && keep[k].dart != dart; k++) + ; + if (k == ARRAY_SIZE(keep)) + return -ENOSPC; + if (!save && keep[k].dart != dart) + return -ENOENT; + keep[k].dart = dart; + for_each_set_bit(sid, &bits, 32) { + u32 tcr = readl(dart->regs + DART_TCR(dart, sid)); + + if (sid >= dart->num_streams) + break; + if (save) + keep[k].tcr[sid] = tcr; + for (idx = 0; idx < dart->hw->ttbr_count && idx < 4; idx++) { + u32 ttbr = readl(dart->regs + DART_TTBR(dart, sid, idx)); + + if (save) { + keep[k].ttbr[sid][idx] = ttbr; + continue; + } + if (ttbr != keep[k].ttbr[sid][idx]) { + writel(keep[k].ttbr[sid][idx], dart->regs + DART_TTBR(dart, sid, idx)); + n++; + } + } + if (!save && tcr != keep[k].tcr[sid]) { + writel(keep[k].tcr[sid], dart->regs + DART_TCR(dart, sid)); + n++; + } + } + return n; +} +EXPORT_SYMBOL_GPL(apple_dart_display_keep); + int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool flush) { struct apple_dart *dart = dev_get_drvdata(dev); @@ -7703,19 +8731,16 @@ int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool fl u32 status; int ret; + if (dart->hw->type == DART_T8020) + return apple_dart_t8020_display_streams(dart, streams, on, flush); + if (on) { apple_dart_gapf_protect(dart); dart->sleep_flushed = false; /* Maps or unmaps while it was dark left their invalidations here. */ - if (READ_ONCE(dart->display_tlb_stale)) { - struct apple_dart_stream_map all = { .dart = dart }; - - bitmap_fill(all.sidmap, dart->num_streams); - if (dart->hw->invalidate_tlb(&all)) - dev_err(dev, "TLB invalidation at power-on failed\n"); - WRITE_ONCE(dart->display_tlb_stale, false); - } - WRITE_ONCE(dart->display_dark, false); + ret = apple_dart_display_dark_exit(dart); + if (ret) + return ret; writel(0, dart->regs + 0x210); writel(0, dart->regs + 0x4060); writel(streams, dart->regs + DART_T8110_ENABLE_STREAMS); @@ -7725,13 +8750,9 @@ int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool fl if (flush && dart->sleep_flushed) return 0; - if (!READ_ONCE(dart->display_dark)) { - for (sid = 0; sid < dart->num_streams; sid++) - __assign_bit(sid, dart->display_tcr_four, - readl(dart->regs + DART_TCR(dart, sid)) & - dart->hw->tcr_4level); - WRITE_ONCE(dart->display_dark, true); - } + ret = apple_dart_display_dark_enter(dart); + if (ret) + return ret; writel(U32_MAX, dart->regs + 0x4060); writel(0, dart->regs + 0x4000); @@ -7758,35 +8779,43 @@ int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool fl } EXPORT_SYMBOL_GPL(apple_dart_display_streams); +/* + * The streams a T8110 display DART has enabled, read while its domain is up: what a DCP + * whose device tree names no streams stops and enables again around its power cycle. The + * mask holds streams 0 to 31; a DART with any stream above them enabled can't be described + * by it and reads 0, which its caller takes as no streams to stop. + */ +u32 apple_dart_enabled_streams(struct device *dev) +{ + struct apple_dart *dart = dev_get_drvdata(dev); + unsigned int i; + + if (!dart || dart->hw->type != DART_T8110) + return 0; + for (i = 1; i < DIV_ROUND_UP(dart->num_streams, 32); i++) { + if (readl(dart->regs + DART_T8110_ENABLE_STREAMS + 4 * i)) { + dev_warn_once(dart->dev, "streams above 31 enabled: not reported\n"); + return 0; + } + } + return readl(dart->regs + DART_T8110_ENABLE_STREAMS); +} +EXPORT_SYMBOL_GPL(apple_dart_enabled_streams); + /* * A DART whose domain goes off with its consumer's, at runtime, while other users still map * into it: dark, maps reach memory only and their invalidations wait; lit, those run. Its * streams are left as they are. Call it dark while it's still powered. */ -void apple_dart_power_dark(struct device *dev, bool dark) +int apple_dart_power_dark(struct device *dev, bool dark) { struct apple_dart *dart = dev_get_drvdata(dev); - unsigned int sid; - if (dark) { - if (READ_ONCE(dart->display_dark)) - return; - for (sid = 0; sid < dart->num_streams; sid++) - __assign_bit(sid, dart->display_tcr_four, - readl(dart->regs + DART_TCR(dart, sid)) & - dart->hw->tcr_4level); - WRITE_ONCE(dart->display_dark, true); - return; - } - if (READ_ONCE(dart->display_tlb_stale)) { - struct apple_dart_stream_map all = { .dart = dart }; - - bitmap_fill(all.sidmap, dart->num_streams); - if (dart->hw->invalidate_tlb(&all)) - dev_err(dev, "TLB invalidation at power-on failed\n"); - WRITE_ONCE(dart->display_tlb_stale, false); - } - WRITE_ONCE(dart->display_dark, false); + if (!dart) + return -ENODEV; + if (dark) + return apple_dart_display_dark_enter(dart); + return apple_dart_display_dark_exit(dart); } EXPORT_SYMBOL_GPL(apple_dart_power_dark); @@ -7868,8 +8897,9 @@ static bool apple_dart_m5_streams_unowned(struct apple_dart *dart, u32 allowed) static int apple_dart_m5_idle(struct apple_dart *dart) { u32 params = readl(dart->regs + DART_PARAMS2); - unsigned int port, ports = max(FIELD_GET(DART_T8110_PARAMS2_READ_PORTS, params), - FIELD_GET(DART_T8110_PARAMS2_WRITE_PORTS, params)); + unsigned int rports = FIELD_GET(DART_T8110_PARAMS2_READ_PORTS, params); + unsigned int wports = FIELD_GET(DART_T8110_PARAMS2_WRITE_PORTS, params); + unsigned int port, ports = max(rports, wports); if (!ports || ports > 4 || apple_dart_fault_pending(dart)) return -EIO; diff --git a/drivers/iommu/io-pgtable-dart-test.c b/drivers/iommu/io-pgtable-dart-test.c new file mode 100644 index 00000000000000..7a68c11003ebd9 --- /dev/null +++ b/drivers/iommu/io-pgtable-dart-test.c @@ -0,0 +1,793 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the Apple DART page table formats. + * + * Included by io-pgtable-dart.c so that the table walkers can be checked + * against hand-computed table indexes and PTE encodings. + */ +#include +#include +#include +#include +#include +#include + +/* Leaf subpage protection: start 0, end 0xfff (whole page). */ +#define DART_TEST_SUBPAGE_ALL (0xfffULL << 40) + +struct dart_test { + struct device *dev; + struct io_pgtable_cfg cfg; + struct io_pgtable_ops *ops; + unsigned int tlb_add_page; + unsigned int tlb_other; + unsigned long tlb_last_iova; + size_t tlb_last_granule; +}; + +static void dart_test_tlb_flush_all(void *cookie) +{ + struct dart_test *t = cookie; + + t->tlb_other++; +} + +static void dart_test_tlb_flush_walk(unsigned long iova, size_t size, + size_t granule, void *cookie) +{ + struct dart_test *t = cookie; + + t->tlb_other++; +} + +static void dart_test_tlb_add_page(struct iommu_iotlb_gather *gather, + unsigned long iova, size_t granule, + void *cookie) +{ + struct dart_test *t = cookie; + + t->tlb_add_page++; + t->tlb_last_iova = iova; + t->tlb_last_granule = granule; +} + +static const struct iommu_flush_ops dart_test_flush_ops = { + .tlb_flush_all = dart_test_tlb_flush_all, + .tlb_flush_walk = dart_test_tlb_flush_walk, + .tlb_add_page = dart_test_tlb_add_page, +}; + +KUNIT_DEFINE_ACTION_WRAPPER(dart_test_free_ops, free_io_pgtable_ops, + struct io_pgtable_ops *); + +/* Exact count of pages held by iommu_alloc_pages_sz(), including per-CPU deltas. */ +static long dart_test_iommu_pages(void) +{ + struct pglist_data *pgdat; + long pages = 0; + int cpu; + + for_each_online_pgdat(pgdat) { + pages += atomic_long_read(&pgdat->vm_stat[NR_IOMMU_PAGES]); + for_each_possible_cpu(cpu) + pages += per_cpu_ptr(pgdat->per_cpu_nodestats, + cpu)->vm_node_stat_diff[NR_IOMMU_PAGES]; + } + + return pages; +} + +/* Pages iommu_alloc_pages_sz() accounts for one table of a granule (4 for 16K on a 4K kernel). */ +static long dart_test_tbl_pages(size_t granule) +{ + return 1L << get_order(granule); +} + +static int dart_test_init(struct kunit *test) +{ + struct dart_test *t; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t); + t->dev = kunit_device_register(test, "io-pgtable-dart-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t->dev); + test->priv = t; + + return 0; +} + +static void dart_test_cfg(struct dart_test *t, size_t pgsize, u32 ias, u32 oas) +{ + t->cfg = (struct io_pgtable_cfg) { + .pgsize_bitmap = pgsize, + .ias = ias, + .oas = oas, + .coherent_walk = true, + .tlb = &dart_test_flush_ops, + .iommu_dev = t->dev, + }; +} + +static struct dart_io_pgtable *dart_test_alloc(struct kunit *test, + enum io_pgtable_fmt fmt, + size_t pgsize, u32 ias, u32 oas) +{ + struct dart_test *t = test->priv; + + dart_test_cfg(t, pgsize, ias, oas); + t->ops = alloc_io_pgtable_ops(fmt, &t->cfg, t); + KUNIT_ASSERT_NOT_NULL(test, t->ops); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, dart_test_free_ops, + t->ops), 0); + + return io_pgtable_ops_to_data(t->ops); +} + +static int dart_test_map(struct dart_test *t, unsigned long iova, + phys_addr_t paddr, size_t pgcount, int prot, + size_t *mapped) +{ + return t->ops->map_pages(t->ops, iova, paddr, t->cfg.pgsize_bitmap, + pgcount, prot, GFP_KERNEL, mapped); +} + +static size_t dart_test_unmap(struct dart_test *t, unsigned long iova, + size_t pgcount, struct iommu_iotlb_gather *gather) +{ + return t->ops->unmap_pages(t->ops, iova, t->cfg.pgsize_bitmap, pgcount, + gather); +} + +static phys_addr_t dart_test_phys(struct dart_test *t, unsigned long iova) +{ + return t->ops->iova_to_phys(t->ops, iova); +} + +/* Leaf PTE slot found by the driver's own walker. */ +static dart_iopte *dart_test_leaf(struct dart_io_pgtable *data, + unsigned long iova) +{ + dart_iopte *ptep = dart_get_last(data, iova); + + return ptep ? ptep + dart_get_last_index(data, iova) : NULL; +} + +/* Expected table PTE for a next-level table, encoded by hand. */ +static dart_iopte dart_test_table_pte(enum io_pgtable_fmt fmt, void *table) +{ + u64 pa = __pa(table); + + if (fmt == APPLE_DART) + return (pa & GENMASK_ULL(35, 12)) | 1; + return ((pa >> 4) & GENMASK_ULL(37, 10)) | 1; +} + +/* Decode a table PTE by hand. */ +static dart_iopte *dart_test_next(enum io_pgtable_fmt fmt, dart_iopte pte) +{ + if (fmt == APPLE_DART) + return __va(pte & GENMASK_ULL(35, 12)); + return __va((pte & GENMASK_ULL(37, 10)) << 4); +} + +struct dart_test_layout { + const char *name; + enum io_pgtable_fmt fmt; + size_t pgsize; + u32 ias, oas; + u32 n_ttbrs, n_levels; + int bits_per_level; +}; + +static const struct dart_test_layout dart_test_layouts[] = { + { "dart1-16k-ias32", APPLE_DART, SZ_16K, 32, 36, 1, 3, 11 }, + { "dart1-4k-ias32", APPLE_DART, SZ_4K, 32, 36, 4, 3, 9 }, + { "dart1-4k-ias30", APPLE_DART, SZ_4K, 30, 36, 1, 3, 9 }, + { "dart1-4k-ias36", APPLE_DART, SZ_4K, 36, 36, 1, 4, 9 }, + { "dart1-16k-ias36", APPLE_DART, SZ_16K, 36, 36, 1, 3, 11 }, + { "dart2-16k-ias36", APPLE_DART2, SZ_16K, 36, 42, 1, 3, 11 }, + { "dart2-16k-ias37", APPLE_DART2, SZ_16K, 37, 42, 1, 4, 11 }, + { "dart2-16k-ias42", APPLE_DART2, SZ_16K, 42, 42, 1, 4, 11 }, +}; + +static void dart_test_layout_desc(const struct dart_test_layout *l, char *desc) +{ + strscpy(desc, l->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(dart_test_layout, dart_test_layouts, dart_test_layout_desc); + +/* Each supported format/granule/ias picks the expected TTBR count and depth. */ +static void dart_test_alloc_layout(struct kunit *test) +{ + const struct dart_test_layout *l = test->param_value; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + u32 i; + + data = dart_test_alloc(test, l->fmt, l->pgsize, l->ias, l->oas); + KUNIT_EXPECT_EQ(test, data->iop.fmt, l->fmt); + KUNIT_EXPECT_EQ(test, t->cfg.apple_dart_cfg.n_ttbrs, l->n_ttbrs); + KUNIT_EXPECT_EQ(test, t->cfg.apple_dart_cfg.n_levels, l->n_levels); + KUNIT_EXPECT_EQ(test, data->bits_per_level, l->bits_per_level); + KUNIT_EXPECT_EQ(test, DART_GRANULE(data), l->pgsize); + + for (i = 0; i < DART_MAX_TABLES; i++) { + if (i >= l->n_ttbrs) { + KUNIT_EXPECT_NULL(test, data->pgd[i]); + continue; + } + KUNIT_ASSERT_NOT_NULL(test, data->pgd[i]); + KUNIT_EXPECT_PTR_EQ(test, t->cfg.apple_dart_cfg.ttbr[i], data->pgd[i]); + KUNIT_EXPECT_TRUE(test, IS_ALIGNED(__pa(data->pgd[i]), l->pgsize)); + KUNIT_EXPECT_TRUE(test, mem_is_zero(data->pgd[i], l->pgsize)); + } + KUNIT_EXPECT_EQ(test, t->tlb_other, 0U); +} + +struct dart_test_bad_cfg { + const char *name; + enum io_pgtable_fmt fmt; + size_t pgsize; + u32 ias, oas; + bool noncoherent; +}; + +static const struct dart_test_bad_cfg dart_test_bad_cfgs[] = { + { "noncoherent", APPLE_DART2, SZ_16K, 36, 42, true }, + { "oas40", APPLE_DART2, SZ_16K, 36, 40 }, + { "oas48", APPLE_DART2, SZ_16K, 36, 48 }, + { "ias-gt-oas", APPLE_DART, SZ_16K, 37, 36 }, + { "pgsize-64k", APPLE_DART2, SZ_64K, 36, 42 }, + { "pgsize-8k", APPLE_DART, SZ_8K, 32, 36 }, + { "pgsize-bitmap", APPLE_DART, SZ_4K | SZ_16K, 32, 36 }, + { "4k-ias42-too-deep", APPLE_DART2, SZ_4K, 42, 42 }, +}; + +static void dart_test_bad_cfg_desc(const struct dart_test_bad_cfg *b, char *desc) +{ + strscpy(desc, b->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(dart_test_bad_cfg, dart_test_bad_cfgs, dart_test_bad_cfg_desc); + +/* Unsupported walkers, widths and granules are refused without leaking pages. */ +static void dart_test_alloc_reject(struct kunit *test) +{ + const struct dart_test_bad_cfg *b = test->param_value; + struct dart_test *t = test->priv; + long before = dart_test_iommu_pages(); + struct io_pgtable_ops *ops; + + dart_test_cfg(t, b->pgsize, b->ias, b->oas); + t->cfg.coherent_walk = !b->noncoherent; + ops = alloc_io_pgtable_ops(b->fmt, &t->cfg, t); + KUNIT_EXPECT_NULL(test, ops); + if (ops) + free_io_pgtable_ops(ops); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages(), before); +} + +/* DART1 leaf PTEs: OA in bits 35:12, SP_DIS, NO_WRITE(7), NO_READ(8). */ +static void dart_test_pte_dart1(struct kunit *test) +{ + static const struct { + int prot; + dart_iopte bits; + } cases[] = { + { IOMMU_READ | IOMMU_WRITE, 0x003 }, + { IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE, 0x003 }, + { IOMMU_READ, 0x083 }, + { IOMMU_WRITE, 0x103 }, + }; + const phys_addr_t pa = 0x81234c000ULL; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + unsigned long iova; + dart_iopte *ptep; + int i; + + data = dart_test_alloc(test, APPLE_DART, SZ_16K, 32, 36); + for (i = 0; i < ARRAY_SIZE(cases); i++) { + iova = SZ_1M + i * SZ_16K; + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, pa, 1, cases[i].prot, NULL), 0); + ptep = dart_test_leaf(data, iova); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, DART_TEST_SUBPAGE_ALL | pa | cases[i].bits); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova + 0x123), pa + 0x123); + } + + /* 4 KiB granule DART1: same encoding, 4 KiB aligned output address. */ + data = dart_test_alloc(test, APPLE_DART, SZ_4K, 32, 36); + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0x3000, 0x876543000ULL, 1, + IOMMU_READ | IOMMU_WRITE, NULL), 0); + ptep = dart_test_leaf(data, 0x3000); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, 0x000fff0876543003ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x3fff), 0x876543fffULL); +} + +/* DART2 leaf PTEs: OA >> 4 in bits 37:10, NO_CACHE(1), NO_WRITE(2), NO_READ(3). */ +static void dart_test_pte_dart2(struct kunit *test) +{ + static const struct { + int prot; + dart_iopte bits; + } cases[] = { + { IOMMU_READ | IOMMU_WRITE, 0x3 }, + { IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE, 0x1 }, + { IOMMU_READ | IOMMU_CACHE, 0x5 }, + { IOMMU_WRITE | IOMMU_CACHE, 0x9 }, + { IOMMU_READ, 0x7 }, + }; + const phys_addr_t pa = 0x2abcdef4000ULL; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + unsigned long iova; + dart_iopte *ptep; + int i; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + for (i = 0; i < ARRAY_SIZE(cases); i++) { + iova = SZ_1M + i * SZ_16K; + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, pa, 1, cases[i].prot, NULL), 0); + ptep = dart_test_leaf(data, iova); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, 0x000fff2abcdef400ULL | cases[i].bits); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova + 0x3ff8), pa + 0x3ff8); + } + + /* The top of the 42-bit output space round-trips (bits 41:40 kept). */ + iova = SZ_2M; + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, 0x3ffffffc000ULL, 1, + IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE, NULL), 0); + ptep = dart_test_leaf(data, iova); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, 0x000fff3ffffffc01ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova + 1), 0x3ffffffc001ULL); +} + +/* Table PTEs carry only the next table's address and the valid bit. */ +static void dart_test_table_ptes(struct kunit *test) +{ + static const enum io_pgtable_fmt fmts[] = { APPLE_DART, APPLE_DART2 }; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *leaf, *l1; + int i; + + for (i = 0; i < ARRAY_SIZE(fmts); i++) { + data = dart_test_alloc(test, fmts[i], SZ_16K, 32, fmts[i] == APPLE_DART ? 36 : 42); + /* L1 index 3 (iova >> 25), leaf index 5 (iova >> 14). */ + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0x6014000, SZ_1G, 1, IOMMU_READ, NULL), 0); + l1 = data->pgd[0]; + leaf = dart_test_next(fmts[i], l1[3]); + KUNIT_ASSERT_NE(test, l1[3], 0ULL); + KUNIT_EXPECT_PTR_EQ(test, dart_test_leaf(data, 0x6014000), leaf + 5); + KUNIT_EXPECT_EQ(test, l1[3], dart_test_table_pte(fmts[i], leaf)); + KUNIT_EXPECT_EQ(test, l1[2], 0ULL); + KUNIT_EXPECT_EQ(test, l1[4], 0ULL); + KUNIT_EXPECT_NE(test, leaf[5], 0ULL); + KUNIT_EXPECT_EQ(test, leaf[4], 0ULL); + KUNIT_EXPECT_EQ(test, leaf[6], 0ULL); + } +} + +/* High L1 indexes on a 36-bit DART2 select their own tables (no aliasing). */ +static void dart_test_index_high_l1(struct kunit *test) +{ + const unsigned long hi = 0x802004000UL; /* L1 1025, leaf 1 */ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *l1, *leaf; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + KUNIT_ASSERT_EQ(test, dart_test_map(t, hi, 0x10000000, 1, IOMMU_READ, NULL), 0); + l1 = data->pgd[0]; + KUNIT_ASSERT_NE(test, l1[1025], 0ULL); + KUNIT_EXPECT_EQ(test, l1[1], 0ULL); + leaf = dart_test_next(APPLE_DART2, l1[1025]); + KUNIT_EXPECT_EQ(test, leaf[1], 0x000fff0001000007ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, hi), 0x10000000ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x2004000), 0ULL); + + /* The low alias is a different IOVA and maps independently. */ + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0x2004000, 0x20000000, 1, IOMMU_READ, NULL), 0); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x2004000), 0x20000000ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, hi), 0x10000000ULL); + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, hi, 1, NULL), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x2004000), 0x20000000ULL); +} + +/* 4-level DART2 (ias 42): three table levels below the TTBR. */ +static void dart_test_four_level(struct kunit *test) +{ + const unsigned long top = 0x3ffffffc000UL; /* L1 63, L2 2047, L3 2047 */ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *l1, *l2, *l3; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 42, 42); + KUNIT_ASSERT_EQ(test, t->cfg.apple_dart_cfg.n_levels, 4U); + KUNIT_ASSERT_EQ(test, dart_test_map(t, top, 0x4000, 1, IOMMU_READ | IOMMU_WRITE, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0, 0x8000, 1, IOMMU_READ | IOMMU_WRITE, NULL), 0); + + /* L1 = iova >> 36, L2 = (iova >> 25) & 2047, L3 = (iova >> 14) & 2047. */ + l1 = data->pgd[0]; + KUNIT_ASSERT_NE(test, l1[63], 0ULL); + KUNIT_ASSERT_NE(test, l1[0], 0ULL); + l2 = dart_test_next(APPLE_DART2, l1[63]); + KUNIT_ASSERT_NE(test, l2[2047], 0ULL); + KUNIT_EXPECT_EQ(test, l1[63], dart_test_table_pte(APPLE_DART2, l2)); + l3 = dart_test_next(APPLE_DART2, l2[2047]); + KUNIT_EXPECT_EQ(test, l3[2047], 0x000fff0000000403ULL); + KUNIT_EXPECT_PTR_EQ(test, dart_test_leaf(data, top), l3 + 2047); + + KUNIT_EXPECT_EQ(test, dart_test_phys(t, top + 0x10), 0x4010ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x10), 0x8010ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, top - SZ_16K), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, BIT(36)), 0ULL); + /* Beyond the single TTBR (iova >> 47 != 0). */ + KUNIT_EXPECT_EQ(test, dart_test_map(t, BIT(47), 0x4000, 1, IOMMU_READ, NULL), -ENOMEM); +} + +/* 4 KiB DART1 with ias 32 splits the space over four TTBRs at 1 GiB. */ +static void dart_test_four_ttbrs(struct kunit *test) +{ + const unsigned long iova = 0xc0203000UL; /* TTBR 3, L1 1, leaf 3 */ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *leaf; + size_t mapped = 0; + int i; + + data = dart_test_alloc(test, APPLE_DART, SZ_4K, 32, 36); + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, 0x87654000, 1, IOMMU_READ | IOMMU_WRITE, + &mapped), 0); + KUNIT_EXPECT_EQ(test, mapped, (size_t)SZ_4K); + for (i = 0; i < 3; i++) + KUNIT_EXPECT_TRUE(test, mem_is_zero(data->pgd[i], SZ_4K)); + KUNIT_ASSERT_NE(test, ((dart_iopte *)data->pgd[3])[1], 0ULL); + KUNIT_EXPECT_EQ(test, ((dart_iopte *)data->pgd[3])[0], 0ULL); + leaf = dart_test_next(APPLE_DART, ((dart_iopte *)data->pgd[3])[1]); + KUNIT_EXPECT_EQ(test, leaf[3], 0x000fff0087654003ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova + 0xabc), 0x87654abcULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova - SZ_1G), 0ULL); + + /* The last page of TTBR 0 and the first page of TTBR 1. */ + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_1G - SZ_4K, 0x1000, 1, IOMMU_READ, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_1G, 0x2000, 1, IOMMU_READ, NULL), 0); + KUNIT_EXPECT_NE(test, ((dart_iopte *)data->pgd[0])[511], 0ULL); + KUNIT_EXPECT_NE(test, ((dart_iopte *)data->pgd[1])[0], 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1G - 1), 0x1fffULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1G), 0x2000ULL); + + /* IOVA 4 GiB would need a fifth TTBR. */ + mapped = 0; + KUNIT_EXPECT_EQ(test, dart_test_map(t, BIT_ULL(32), 0x1000, 1, IOMMU_READ, &mapped), + -ENOMEM); + KUNIT_EXPECT_EQ(test, mapped, (size_t)0); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, BIT_ULL(32)), 0ULL); +} + +/* pgcount mappings fill consecutive PTEs and stop at the leaf table's end. */ +static void dart_test_map_multi(struct kunit *test) +{ + const unsigned long start = SZ_32M - 2 * SZ_16K; /* leaf 2046 of L1 0 */ + const phys_addr_t pa = 0x80000000; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + size_t mapped = SZ_1M, left = 5; + unsigned long iova = start; + int calls = 0, i; + dart_iopte *ptep; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + + /* *mapped accumulates; the first call stops after 2 pages. */ + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, pa, left, IOMMU_READ | IOMMU_WRITE, + &mapped), 0); + KUNIT_EXPECT_EQ(test, mapped, (size_t)SZ_1M + 2 * SZ_16K); + + /* Continue as iommu_map() does until all pages are in. */ + mapped -= SZ_1M; + while (left) { + calls++; + left -= mapped / SZ_16K; + iova += mapped; + mapped = 0; + if (!left) + break; + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, pa + (iova - start), left, + IOMMU_READ | IOMMU_WRITE, &mapped), 0); + KUNIT_ASSERT_GT(test, mapped, (size_t)0); + } + KUNIT_EXPECT_EQ(test, calls, 2); + KUNIT_EXPECT_NE(test, ((dart_iopte *)data->pgd[0])[0], 0ULL); + KUNIT_EXPECT_NE(test, ((dart_iopte *)data->pgd[0])[1], 0ULL); + + for (i = 0; i < 5; i++) { + ptep = dart_test_leaf(data, start + i * SZ_16K); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, 0x000fff0008000003ULL + i * (SZ_16K >> 4)); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, start + i * SZ_16K + 8), + pa + i * SZ_16K + 8); + } + KUNIT_EXPECT_EQ(test, dart_test_phys(t, start - SZ_16K), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, start + 5 * SZ_16K), 0ULL); + + /* A large run in an empty leaf table fills all 2048 slots at once. */ + mapped = 0; + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_64M, 0, 4096, IOMMU_READ, &mapped), 0); + KUNIT_EXPECT_EQ(test, mapped, (size_t)SZ_32M); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_64M + SZ_32M - 1), (phys_addr_t)SZ_32M - 1); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_64M + SZ_32M), 0ULL); +} + +/* Mapping over a valid PTE fails without touching any slot of the range. */ +static void dart_test_map_exists(struct kunit *test) +{ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte old, *ptep; + size_t mapped = 0; + int ret, i; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0x10008000, 0x40000000, 1, IOMMU_READ, NULL), 0); + ptep = dart_test_leaf(data, 0x10008000); + KUNIT_ASSERT_NOT_NULL(test, ptep); + old = *ptep; + + kunit_warning_suppress(test) { + ret = dart_test_map(t, 0x10008000, 0x50000000, 1, IOMMU_READ | IOMMU_WRITE, + &mapped); + KUNIT_EXPECT_EQ(test, ret, -EEXIST); + /* Slot 2 of [0, 4) is taken: nothing of the range is written. */ + ret = dart_test_map(t, 0x10000000, 0x60000000, 4, IOMMU_READ, &mapped); + KUNIT_EXPECT_EQ(test, ret, -EEXIST); + KUNIT_EXPECT_SUPPRESSED_WARNING_COUNT(test, 2); + } + KUNIT_EXPECT_EQ(test, mapped, (size_t)0); + KUNIT_EXPECT_EQ(test, *ptep, old); + for (i = 0; i < 4; i++) + if (i != 2) + KUNIT_EXPECT_EQ(test, *(ptep - 2 + i), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x10008000), 0x40000000ULL); + + /* After an unmap the same IOVA maps again. */ + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, 0x10008000, 1, NULL), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_map(t, 0x10008000, 0x50000000, 1, IOMMU_WRITE, NULL), 0); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x10008000), 0x50000000ULL); +} + +/* Bad sizes, protections and output addresses are rejected before any table is built. */ +static void dart_test_map_reject(struct kunit *test) +{ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + long pages; + size_t mapped = 0; + int ret; + + data = dart_test_alloc(test, APPLE_DART, SZ_16K, 32, 36); + pages = dart_test_iommu_pages(); + + /* Neither read nor write: refused without a warning. */ + KUNIT_EXPECT_EQ(test, dart_test_map(t, 0, 0x4000, 1, 0, &mapped), -EINVAL); + KUNIT_EXPECT_EQ(test, dart_test_map(t, 0, 0x4000, 1, IOMMU_CACHE, &mapped), -EINVAL); + + kunit_warning_suppress(test) { + /* Only the single configured page size is accepted. */ + ret = t->ops->map_pages(t->ops, 0, 0x4000, SZ_4K, 1, IOMMU_READ, + GFP_KERNEL, &mapped); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = t->ops->map_pages(t->ops, 0, 0x8000, SZ_32K, 1, IOMMU_READ, + GFP_KERNEL, &mapped); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + /* Output address at or past 2^oas. */ + ret = dart_test_map(t, 0, BIT_ULL(36), 1, IOMMU_READ, &mapped); + KUNIT_EXPECT_EQ(test, ret, -ERANGE); + /* A run that would cross 2^oas. */ + ret = dart_test_map(t, 0, BIT_ULL(36) - SZ_16K, 2, IOMMU_READ, &mapped); + KUNIT_EXPECT_EQ(test, ret, -ERANGE); + KUNIT_EXPECT_SUPPRESSED_WARNING_COUNT(test, 4); + } + + /* Beyond the single TTBR of a 16 KiB DART (iova >> 36). */ + KUNIT_EXPECT_EQ(test, dart_test_map(t, BIT_ULL(36), 0x4000, 1, IOMMU_READ, &mapped), + -ENOMEM); + KUNIT_EXPECT_EQ(test, mapped, (size_t)0); + KUNIT_EXPECT_TRUE(test, mem_is_zero(data->pgd[0], SZ_16K)); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages(), pages); + + /* The last page below 2^oas is fine. */ + KUNIT_EXPECT_EQ(test, dart_test_map(t, 0, BIT_ULL(36) - SZ_16K, 1, IOMMU_READ, &mapped), + 0); + KUNIT_EXPECT_EQ(test, mapped, (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x3fff), BIT_ULL(36) - 1); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages(), pages + dart_test_tbl_pages(SZ_16K)); +} + +/* Unmap clears exactly the requested PTEs and queues one TLB page each. */ +static void dart_test_unmap_range(struct kunit *test) +{ + struct iommu_iotlb_gather gather; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *ptep; + size_t mapped = 0; + + data = dart_test_alloc(test, APPLE_DART, SZ_16K, 32, 36); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_1M, SZ_1G, 4, IOMMU_READ | IOMMU_WRITE, + &mapped), 0); + KUNIT_ASSERT_EQ(test, mapped, (size_t)SZ_64K); + ptep = dart_test_leaf(data, SZ_1M); + KUNIT_ASSERT_NOT_NULL(test, ptep); + + iommu_iotlb_gather_init(&gather); + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, SZ_1M + SZ_16K, 2, &gather), (size_t)SZ_32K); + KUNIT_EXPECT_NE(test, ptep[0], 0ULL); + KUNIT_EXPECT_EQ(test, ptep[1], 0ULL); + KUNIT_EXPECT_EQ(test, ptep[2], 0ULL); + KUNIT_EXPECT_NE(test, ptep[3], 0ULL); + KUNIT_EXPECT_EQ(test, t->tlb_add_page, 2U); + KUNIT_EXPECT_EQ(test, t->tlb_last_iova, (unsigned long)SZ_1M + 2 * SZ_16K); + KUNIT_EXPECT_EQ(test, t->tlb_last_granule, (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1M), (phys_addr_t)SZ_1G); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1M + SZ_16K), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1M + 3 * SZ_16K), + (phys_addr_t)SZ_1G + 3 * SZ_16K); + + /* A queued gather defers invalidation to the caller. */ + gather.queued = true; + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, SZ_1M, 1, &gather), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, t->tlb_add_page, 2U); + KUNIT_EXPECT_EQ(test, ptep[0], 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, SZ_1M + 3 * SZ_16K, 1, NULL), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, t->tlb_add_page, 3U); + KUNIT_EXPECT_TRUE(test, mem_is_zero(ptep, 4 * sizeof(*ptep))); + KUNIT_EXPECT_EQ(test, t->tlb_other, 0U); +} + +/* Unmap of holes, missing tables and runs past a leaf table end. */ +static void dart_test_unmap_partial(struct kunit *test) +{ + const unsigned long end = SZ_32M - SZ_16K; /* last leaf slot of L1 0 */ + struct dart_test *t = test->priv; + size_t size; + + dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + KUNIT_ASSERT_EQ(test, dart_test_map(t, end, 0x40000000, 2, IOMMU_READ, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_32M, 0x40004000, 2, IOMMU_READ, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_64M, 0x50000000, 2, IOMMU_READ, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_64M + 3 * SZ_16K, 0x50000000, 1, IOMMU_READ, + NULL), 0); + + /* A run crossing the leaf table end stops at it. */ + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, end, 3, NULL), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M), 0x40004000ULL); + + kunit_warning_suppress(test) { + /* A hole at slot 2 ends the run after two pages. */ + size = dart_test_unmap(t, SZ_64M, 4, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)SZ_32K); + /* No leaf table at all. */ + size = dart_test_unmap(t, SZ_1G, 1, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)0); + /* Nothing to do and wrong page size. */ + size = dart_test_unmap(t, SZ_32M, 0, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)0); + size = t->ops->unmap_pages(t->ops, SZ_32M, SZ_4K, 1, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)0); + /* Beyond the TTBR. */ + size = dart_test_unmap(t, BIT_ULL(36), 1, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)0); + KUNIT_EXPECT_SUPPRESSED_WARNING_COUNT(test, 5); + } + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M), 0x40004000ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_64M), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_64M + 3 * SZ_16K), 0x50000000ULL); + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, SZ_32M, 2, NULL), (size_t)SZ_32K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M + SZ_16K), 0ULL); +} + +/* iova_to_phys() misses at each level of an otherwise populated table. */ +static void dart_test_iova_to_phys_miss(struct kunit *test) +{ + struct dart_test *t = test->priv; + + dart_test_alloc(test, APPLE_DART2, SZ_16K, 37, 42); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0), 0ULL); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_32M + SZ_16K, 0x12340000, 1, IOMMU_READ, + NULL), 0); + /* Same leaf table, empty slot. */ + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M), 0ULL); + /* Same L2 table, no leaf table. */ + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0), 0ULL); + /* No L2 table under L1 index 1. */ + KUNIT_EXPECT_EQ(test, dart_test_phys(t, BIT_ULL(36) + SZ_32M + SZ_16K), 0ULL); + /* The offset within the page is kept. */ + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M + SZ_16K + 0x3fff), 0x12343fffULL); +} + +struct dart_test_teardown { + const char *name; + enum io_pgtable_fmt fmt; + size_t pgsize; + u32 ias, oas; + unsigned long iova[4]; + long tables; /* tables held after alloc + the maps */ +}; + +static const struct dart_test_teardown dart_test_teardowns[] = { + /* 1 root + 2 leaf tables. */ + { "dart1-16k", APPLE_DART, SZ_16K, 32, 36, { 0, SZ_16K, SZ_32M, SZ_32M + SZ_16K }, 3 }, + /* 4 roots + 4 leaf tables, one per TTBR. */ + { "dart1-4k-4ttbr", APPLE_DART, SZ_4K, 32, 36, { 0, SZ_1G, 2UL * SZ_1G, 3UL * SZ_1G }, 8 }, + /* 1 root + 2 L2 + 3 leaf tables. */ + { "dart2-16k-4level", APPLE_DART2, SZ_16K, 42, 42, + { 0, SZ_32M, BIT(36), BIT(36) + SZ_16K }, 6 }, +}; + +static void dart_test_teardown_desc(const struct dart_test_teardown *td, char *desc) +{ + strscpy(desc, td->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(dart_test_teardown, dart_test_teardowns, dart_test_teardown_desc); + +/* Every table page allocated by map_pages() is released by free_io_pgtable_ops(). */ +static void dart_test_teardown_free(struct kunit *test) +{ + const struct dart_test_teardown *td = test->param_value; + struct dart_test *t = test->priv; + long before; + int i; + + before = dart_test_iommu_pages(); + dart_test_alloc(test, td->fmt, td->pgsize, td->ias, td->oas); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages() - before, + t->cfg.apple_dart_cfg.n_ttbrs * dart_test_tbl_pages(td->pgsize)); + for (i = 0; i < ARRAY_SIZE(td->iova); i++) + KUNIT_ASSERT_EQ(test, dart_test_map(t, td->iova[i], SZ_1G, 1, IOMMU_READ, NULL), 0); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages() - before, + td->tables * dart_test_tbl_pages(td->pgsize)); + + /* Unmap keeps the tables; the teardown frees them. */ + for (i = 0; i < ARRAY_SIZE(td->iova); i++) + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, td->iova[i], 1, NULL), td->pgsize); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages() - before, + td->tables * dart_test_tbl_pages(td->pgsize)); + + kunit_release_action(test, dart_test_free_ops, t->ops); + t->ops = NULL; + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages(), before); +} + +static struct kunit_case io_pgtable_dart_test_cases[] = { + KUNIT_CASE_PARAM(dart_test_alloc_layout, dart_test_layout_gen_params), + KUNIT_CASE_PARAM(dart_test_alloc_reject, dart_test_bad_cfg_gen_params), + KUNIT_CASE(dart_test_pte_dart1), + KUNIT_CASE(dart_test_pte_dart2), + KUNIT_CASE(dart_test_table_ptes), + KUNIT_CASE(dart_test_index_high_l1), + KUNIT_CASE(dart_test_four_level), + KUNIT_CASE(dart_test_four_ttbrs), + KUNIT_CASE(dart_test_map_multi), + KUNIT_CASE(dart_test_map_exists), + KUNIT_CASE(dart_test_map_reject), + KUNIT_CASE(dart_test_unmap_range), + KUNIT_CASE(dart_test_unmap_partial), + KUNIT_CASE(dart_test_iova_to_phys_miss), + KUNIT_CASE_PARAM(dart_test_teardown_free, dart_test_teardown_gen_params), + {} +}; + +static struct kunit_suite io_pgtable_dart_test_suite = { + .name = "io-pgtable-dart", + .init = dart_test_init, + .test_cases = io_pgtable_dart_test_cases, +}; + +kunit_test_suite(io_pgtable_dart_test_suite); diff --git a/drivers/iommu/io-pgtable-dart.c b/drivers/iommu/io-pgtable-dart.c index ad817bf76c310a..93d268710a11e2 100644 --- a/drivers/iommu/io-pgtable-dart.c +++ b/drivers/iommu/io-pgtable-dart.c @@ -483,3 +483,7 @@ struct io_pgtable_init_fns io_pgtable_apple_dart_init_fns = { .alloc = apple_dart_alloc_pgtable, .free = apple_dart_free_pgtable, }; + +#if IS_ENABLED(CONFIG_IOMMU_IO_PGTABLE_DART_KUNIT_TEST) +#include "io-pgtable-dart-test.c" +#endif diff --git a/drivers/iommu/io-pgtable-dart.kunitconfig b/drivers/iommu/io-pgtable-dart.kunitconfig new file mode 100644 index 00000000000000..3171f991a8f45f --- /dev/null +++ b/drivers/iommu/io-pgtable-dart.kunitconfig @@ -0,0 +1,4 @@ +CONFIG_KUNIT=y +CONFIG_IOMMU_SUPPORT=y +CONFIG_IOMMU_IO_PGTABLE_DART=y +CONFIG_IOMMU_IO_PGTABLE_DART_KUNIT_TEST=y diff --git a/drivers/irqchip/irq-apple-aic.c b/drivers/irqchip/irq-apple-aic.c index 52a892164c3a46..a13eb5c1fcb2c6 100644 --- a/drivers/irqchip/irq-apple-aic.c +++ b/drivers/irqchip/irq-apple-aic.c @@ -56,6 +56,7 @@ #include #include #include +#include #include #include #include @@ -101,6 +102,7 @@ #define AIC_TARGET_CPU 0x3000 +#define AIC_CPU_BLOCK(cpu) (0x5000 + ((cpu) << 7)) #define AIC_CPU_IPI_SET(cpu) (0x5008 + ((cpu) << 7)) #define AIC_CPU_IPI_CLR(cpu) (0x500c + ((cpu) << 7)) #define AIC_CPU_IPI_MASK_SET(cpu) (0x5024 + ((cpu) << 7)) @@ -278,8 +280,8 @@ struct aic_info { bool vm_timer_fiq_readonly; /* A firmware-driven suspend powers the controller down: aic_syscore_ops keep it. */ bool fw_suspend; - /* If set, fw_suspend holds on these boards only */ - const char *const *fw_suspend_boards; + /* If set, fw_suspend holds only where this says the sleep is described */ + bool (*fw_suspend_described)(void); }; static const struct aic_info aic1_info __initconst = { @@ -328,12 +330,9 @@ static const struct aic_info aic3_info __initconst = { /* * The M5 Pro's sleep: the last steps mask every interrupt and acknowledge events by hand. The - * save and restore are set up on the boards with a T6050 sleep, the J714s and the J716c; + * save and restore are set up on the boards whose device tree describes a T6050 sleep; * another T6050 board is as one without them. */ -static const char *const aic3_t6050_sleep_boards[] __initconst = { - "apple,j714s", "apple,j716c", NULL -}; static const struct aic_info aic3_t6050_info __initconst = { .version = 3, @@ -341,7 +340,7 @@ static const struct aic_info aic3_t6050_info __initconst = { .fast_ipi = true, .local_fast_ipi = true, .fw_suspend = true, - .fw_suspend_boards = aic3_t6050_sleep_boards, + .fw_suspend_described = apple_t6050_sleep_described, }; static const struct aic_info aic3_t8140_info __initconst = { @@ -352,11 +351,24 @@ static const struct aic_info aic3_t8140_info __initconst = { .fw_suspend = true, }; +/* + * T6041 (M4 Max): the AICv3 of T8122, with the state its sleep driver's firmware + * suspend loses saved and restored around it. + */ +static const struct aic_info aic3_t6041_info __initconst = { + .version = 3, + .irq_cfg = AIC3_IRQ_CFG, + .fast_ipi = true, + .local_fast_ipi = true, + .fw_suspend = true, +}; + static const struct aic_info aic3_t8132_info __initconst = { .version = 3, .irq_cfg = AIC3_IRQ_CFG, .fast_ipi = true, .local_fast_ipi = true, + .vm_timer_fiq_readonly = true, .fw_suspend = true, }; @@ -384,6 +396,10 @@ static const struct of_device_id aic_info_match[] = { .compatible = "apple,t8142-aic3", .data = &aic3_t8142_info, }, + { + .compatible = "apple,t6041-aic3", + .data = &aic3_t6041_info, + }, { .compatible = "apple,t8103-aic", .data = &aic1_local_fipi_info, @@ -421,6 +437,12 @@ struct aic_irq_chip { int max_die; u32 *sleep_masks; + /* AIC1: each line's target CPUs, which a firmware sleep's power cycle may take */ + u32 *sleep_targets; + /* AIC1: the global registers the boot loader set (0x10..0x3c), lost the same way */ + u32 sleep_globals[12]; + /* AIC1: each CPU block's first word, the CPU number WHOAMI reports there */ + u32 sleep_cpu_ids[32]; struct aic_info info; }; @@ -429,6 +451,9 @@ static DEFINE_PER_CPU(uint32_t, aic_fiq_unmasked); static struct aic_irq_chip *aic_irqc; +/* AIC1: each CPU's number as AIC knows it (WHOAMI), for line targets; the logical id until read */ +static DEFINE_PER_CPU(u32, aic_cpu_hwid); + /* CPUs that accept hardware IRQs, read from SIQ_CFG on AICv2+ at EL2 */ static struct cpumask aic_irq_cpus; @@ -453,6 +478,7 @@ void aic_sleep_mask_all(void) struct aic_irq_chip *ic = aic_irqc; u32 words = ic->max_irq >> 5, off = 0, reg, i; u32 *saved = ic->sleep_masks; + u32 *targets = ic->sleep_targets; int die; for (die = 0; die < ic->nr_die; die++, off += ic->info.die_stride) { @@ -461,7 +487,13 @@ void aic_sleep_mask_all(void) *saved++ = aic_ic_read(ic, reg); aic_ic_write(ic, reg, U32_MAX); } + for (i = 0; targets && i < ic->nr_irq; i++) + *targets++ = aic_ic_read(ic, ic->info.target_cpu + off + i * 4); } + for (i = 0; ic->sleep_targets && i < ARRAY_SIZE(ic->sleep_globals); i++) + ic->sleep_globals[i] = aic_ic_read(ic, AIC_CONFIG + i * 4); + for (i = 0; ic->sleep_targets && i < min(num_possible_cpus(), 32U); i++) + ic->sleep_cpu_ids[i] = aic_ic_read(ic, AIC_CPU_BLOCK(i)); } void aic_sleep_restore(void) @@ -469,9 +501,29 @@ void aic_sleep_restore(void) struct aic_irq_chip *ic = aic_irqc; u32 words = ic->max_irq >> 5, off = 0, i; u32 *saved = ic->sleep_masks; + u32 *targets = ic->sleep_targets; int die; + /* Delivery as a whole first: with the configuration gone, no line reaches a CPU. */ + for (i = 0; targets && i < ARRAY_SIZE(ic->sleep_globals); i++) { + if (aic_ic_read(ic, AIC_CONFIG + i * 4) != ic->sleep_globals[i]) + aic_ic_write(ic, AIC_CONFIG + i * 4, ic->sleep_globals[i]); + } + + /* The CPU numbers, before any CPU comes back up and reads its own */ + for (i = 0; targets && i < min(num_possible_cpus(), 32U); i++) { + if (aic_ic_read(ic, AIC_CPU_BLOCK(i)) != ic->sleep_cpu_ids[i]) + aic_ic_write(ic, AIC_CPU_BLOCK(i), ic->sleep_cpu_ids[i]); + } + for (die = 0; die < ic->nr_die; die++, off += ic->info.die_stride) { + /* Targets first: an unmasked line with none goes nowhere. */ + for (i = 0; targets && i < ic->nr_irq; i++, targets++) { + u32 reg = ic->info.target_cpu + off + i * 4; + + if (aic_ic_read(ic, reg) != *targets) + aic_ic_write(ic, reg, *targets); + } for (i = 0; i < words; i++, saved++) { aic_ic_write(ic, ic->info.mask_set + off + i * 4, *saved); aic_ic_write(ic, ic->info.mask_clr + off + i * 4, ~*saved); @@ -579,7 +631,8 @@ static int aic_irq_set_affinity(struct irq_data *d, else cpu = cpumask_any_and(mask_val, cpu_online_mask); - aic_ic_write(ic, ic->info.target_cpu + AIC_HWIRQ_IRQ(hwirq) * 4, BIT(cpu)); + aic_ic_write(ic, ic->info.target_cpu + AIC_HWIRQ_IRQ(hwirq) * 4, + BIT(per_cpu(aic_cpu_hwid, cpu))); irq_data_update_effective_affinity(d, cpumask_of(cpu)); return IRQ_SET_MASK_OK; @@ -656,8 +709,9 @@ static unsigned long aic_fiq_get_idx(struct irq_data *d) } /* - * T8142 traps writes to VM_TMR_FIQ_ENA_EL2. Mask the guest timers through - * their architectural EL02 controls instead, leaving the older SoCs alone. + * T8132 and T8142 trap writes to VM_TMR_FIQ_ENA_EL2 outside a CTXR execute + * window. Mask the guest timers through their architectural EL02 controls + * instead, leaving the older SoCs alone. */ static void aic_vm_timer_mask(u64 timers, bool mask) { @@ -1078,7 +1132,17 @@ static int aic_init_cpu(unsigned int cpu) * If we ever end up with a mismatch here, we will have to introduce * a mapping table similar to what other irqchip drivers do. */ - WARN_ON(aic_ic_read(aic_irqc, AIC_WHOAMI) != smp_processor_id()); + u32 whoami = aic_ic_read(aic_irqc, AIC_WHOAMI); + + /* + * The device tree's CPU order need not be AIC's (the E- and P-cores can + * interleave): a line's target is AIC's number for the CPU, so keep it. + */ + if (whoami < 32) + per_cpu(aic_cpu_hwid, smp_processor_id()) = whoami; + if (whoami != smp_processor_id()) + pr_info_once("AIC: CPU numbers differ from the device tree's order (CPU%d is AIC CPU %u)\n", + smp_processor_id(), whoami); /* * Always keep IPIs unmasked at the hardware level (except auto-masking @@ -1107,8 +1171,8 @@ static int aic_init_cpu(unsigned int cpu) */ static void aic_irq_cpus_update(unsigned int cpu, bool accepts) { - static struct cpumask aff; /* CPU hotplug is serialized */ struct aic_irq_chip *ic = aic_irqc; + const struct cpumask *aff; unsigned int die, i, virq; if (accepts == cpumask_test_cpu(cpu, &aic_irq_cpus)) @@ -1120,8 +1184,11 @@ static void aic_irq_cpus_update(unsigned int cpu, bool accepts) virq = irq_find_mapping(ic->hw_domain, AIC_IRQ_HWIRQ(die, i)); if (!virq || !irq_has_action(virq)) continue; - cpumask_copy(&aff, irq_get_affinity_mask(virq)); - irq_set_affinity(virq, &aff); + aff = irq_get_affinity_mask(virq); + if (!aff) + continue; + /* Read under the desc lock, so a concurrent smp_affinity write is kept */ + irq_set_affinity(virq, aff); } } } @@ -1298,8 +1365,7 @@ static struct syscore aic_syscore = { static void __init aic_sleep_init(struct aic_irq_chip *irqc) { if (!irqc->info.fw_suspend || - (irqc->info.fw_suspend_boards && - !of_machine_compatible_match(irqc->info.fw_suspend_boards))) + (irqc->info.fw_suspend_described && !irqc->info.fw_suspend_described())) return; aic_sleep.irq_cfg = kcalloc(irqc->nr_die * irqc->nr_irq, sizeof(u32), GFP_KERNEL); @@ -1316,7 +1382,7 @@ static void __init aic_sleep_init(struct aic_irq_chip *irqc) static int __init aic_of_ic_init(struct device_node *node, struct device_node *parent) { - int i, die; + int i, die, cpu; u32 off, start_off; void __iomem *regs; struct aic_irq_chip *irqc; @@ -1342,12 +1408,13 @@ static int __init aic_of_ic_init(struct device_node *node, struct device_node *p irqc->info = *(struct aic_info *)match->data; /* - * The VM_TMR_FIQ_ENA_EL2 write that traps on T8142 was seen under - * SPTM. A loader that runs the OS at EL2 in a CTXR execute window - * starts no SPTM and says so with this property, and there the - * register takes writes. Masking through the EL02 controls instead - * sets IMASK in the guest's own timer, which KVM then keeps as - * guest state: the guest gets no timer interrupt again. + * The VM_TMR_FIQ_ENA_EL2 write traps on T8142 under SPTM, and on T8132 + * booted by a stage 1 that arms no CTXR execute window. A loader that + * runs the OS at EL2 in a CTXR execute window starts no SPTM and says + * so with this property, and there the register takes writes. + * Masking through the EL02 controls instead sets IMASK in the guest's + * own timer, which KVM then keeps as guest state: the guest gets no + * timer interrupt again. */ if (irqc->info.vm_timer_fiq_readonly && is_kernel_in_hyp_mode() && of_property_present(of_chosen, "aurora,ctxr-exec-window")) @@ -1415,6 +1482,12 @@ static int __init aic_of_ic_init(struct device_node *node, struct device_node *p sizeof(*irqc->sleep_masks), GFP_KERNEL); if (WARN_ON(!irqc->sleep_masks)) goto err_unmap; + if (irqc->info.target_cpu) { + irqc->sleep_targets = kcalloc(irqc->nr_die * irqc->nr_irq, + sizeof(*irqc->sleep_targets), GFP_KERNEL); + if (WARN_ON(!irqc->sleep_targets)) + goto err_unmap; + } irqc->hw_domain = irq_domain_create_tree(of_fwnode_handle(node), &aic_irq_domain_ops, irqc); @@ -1435,6 +1508,9 @@ static int __init aic_of_ic_init(struct device_node *node, struct device_node *p } of_node_put(affs); + for_each_possible_cpu(cpu) + per_cpu(aic_cpu_hwid, cpu) = cpu; + set_handle_irq(aic_handle_irq); set_handle_fiq(aic_handle_fiq); diff --git a/drivers/media/platform/apple/avd/Kconfig b/drivers/media/platform/apple/avd/Kconfig index d3bb9763b6230e..4aa061da424e69 100644 --- a/drivers/media/platform/apple/avd/Kconfig +++ b/drivers/media/platform/apple/avd/Kconfig @@ -14,7 +14,9 @@ config VIDEO_APPLE_AVD help Support the Apple Silicon stateless video decoder. - Build the decoder firmware from https://github.com/aurora-silicon/avd-fw + T8152 uses host submission and does not need a firmware image. + + For earlier SoCs, build the decoder firmware from https://github.com/aurora-silicon/avd-fw and install it under /lib/firmware/apple/. J700/T8140 uses the avd-fw-v5-t0.bin image. Firmware is supplied separately from this driver. diff --git a/drivers/media/platform/apple/avd/Makefile b/drivers/media/platform/apple/avd/Makefile index 60560dbab592a1..7f9e92551b99fb 100644 --- a/drivers/media/platform/apple/avd/Makefile +++ b/drivers/media/platform/apple/avd/Makefile @@ -1,8 +1,10 @@ # SPDX-License-Identifier: GPL-2.0-only -apple-avd-y := avd-drv.o avd-v4l2.o avd-hw.o avd-pm.o avd-h264.o avd-vp9.o \ +apple-avd-y := avd-drv.o avd-v4l2.o avd-hw.o avd-pm.o avd-h264.o \ + avd-h264-parse.o avd-vp9.o \ avd-hevc.o avd-av1.o avd-av1-entropymode.o avd-queue.o avd-backend-open.o \ - avd-backend-apple.o avd-backend-queue.o -apple-avd-$(CONFIG_VIDEO_APPLE_AVD_KUNIT_TEST) += avd-h264-test.o avd-queue-test.o \ - avd-pm-test.o + avd-backend-apple.o avd-backend-queue.o avd-backend-kopsia.o +apple-avd-$(CONFIG_VIDEO_APPLE_AVD_KUNIT_TEST) += avd-h264-test.o \ + avd-queue-test.o avd-pm-test.o avd-hevc-test.o avd-job-test.o \ + avd-fmt-test.o avd-av1-test.o avd-v4l2-test.o avd-vp9-test.o obj-$(CONFIG_VIDEO_APPLE_AVD) += apple-avd.o diff --git a/drivers/media/platform/apple/avd/avd-av1-entropymode.c b/drivers/media/platform/apple/avd/avd-av1-entropymode.c index ca15e08259a909..de312d214a0245 100644 --- a/drivers/media/platform/apple/avd/avd-av1-entropymode.c +++ b/drivers/media/platform/apple/avd/avd-av1-entropymode.c @@ -75,7 +75,7 @@ static_assert(offsetof(struct avd_av1_cdfs, dc_sign_cdf) == 5214); static_assert(offsetof(struct avd_av1_cdfs, coeff_base_cdf) == 6646); static_assert(sizeof(struct avd_av1_cdfs) == 9166); -static const u16 default_palette_uv_mode_cdf[ PALETTE_UV_MODE_CONTEXTS ] = { +static const u16 default_palette_uv_mode_cdf[PALETTE_UV_MODE_CONTEXTS] = { AOM_CDF(32461, 21488) }; @@ -94,15 +94,15 @@ static const u16 default_angle_delta_cdf[DIRECTIONAL_MODES] static const u16 default_if_y_mode_cdf[BLOCK_SIZE_GROUPS][CDF_SIZE(AV1_INTRA_MODES)] = { { AOM_CDF(22801, 23489, 24293, 24756, 25601, 26123, - 26606, 27418, 27945, 29228, 29685, 30349) + 26606, 27418, 27945, 29228, 29685, 30349) }, { AOM_CDF(18673, 19845, 22631, 23318, 23950, 24649, - 25527, 27364, 28152, 29701, 29984, 30852) + 25527, 27364, 28152, 29701, 29984, 30852) }, { AOM_CDF(19770, 20979, 23396, 23939, 24241, 24654, - 25136, 27073, 27830, 29360, 29730, 30659) + 25136, 27073, 27830, 29360, 29730, 30659) }, { AOM_CDF(20155, 21301, 22838, 23178, 23261, 23533, @@ -717,7 +717,7 @@ static const u16 default_palette_y_mode_cdf[PALETTE_BLOCK_SIZES] { { AOM_CDF(32450) }, { AOM_CDF(7946) }, { AOM_CDF(129) } } }; -static const u16 default_palette_size_2_y_color_cdf[ PALETTE_COLOR_CONTEXTS ] = { +static const u16 default_palette_size_2_y_color_cdf[PALETTE_COLOR_CONTEXTS] = { AOM_CDF(28710), AOM_CDF(16384), AOM_CDF(10553), @@ -725,7 +725,7 @@ static const u16 default_palette_size_2_y_color_cdf[ PALETTE_COLOR_CONTEXTS ] = AOM_CDF(31603) }; -static const u16 default_palette_size_3_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 2 ] = { +static const u16 default_palette_size_3_y_color_cdf[PALETTE_COLOR_CONTEXTS][2] = { { AOM_CDF(27877, 30490) }, { AOM_CDF(11532, 25697) }, { AOM_CDF(6544, 30234) }, @@ -733,7 +733,7 @@ static const u16 default_palette_size_3_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 2 { AOM_CDF(31915, 32385) } }; -static const u16 default_palette_size_4_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 3 ] = { +static const u16 default_palette_size_4_y_color_cdf[PALETTE_COLOR_CONTEXTS][3] = { { AOM_CDF(25572, 28046, 30045) }, { AOM_CDF(9478, 21590, 27256) }, { AOM_CDF(7248, 26837, 29824) }, @@ -741,7 +741,7 @@ static const u16 default_palette_size_4_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 3 { AOM_CDF(31400, 31825, 32250) } }; -static const u16 default_palette_size_5_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 4 ] = { +static const u16 default_palette_size_5_y_color_cdf[PALETTE_COLOR_CONTEXTS][4] = { { AOM_CDF(24779, 26955, 28576, 30282) }, { AOM_CDF(8669, 20364, 24073, 28093) }, { AOM_CDF(4255, 27565, 29377, 31067) }, @@ -749,7 +749,7 @@ static const u16 default_palette_size_5_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 4 { AOM_CDF(31646, 31893, 32147, 32426) } }; -static const u16 default_palette_size_6_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 5 ] = { +static const u16 default_palette_size_6_y_color_cdf[PALETTE_COLOR_CONTEXTS][5] = { { AOM_CDF(23132, 25407, 26970, 28435, 30073) }, { AOM_CDF(7443, 17242, 20717, 24762, 27982) }, { AOM_CDF(6300, 24862, 26944, 28784, 30671) }, @@ -757,7 +757,7 @@ static const u16 default_palette_size_6_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 5 { AOM_CDF(31270, 31550, 31808, 32059, 32353) } }; -static const u16 default_palette_size_7_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 6 ] = { +static const u16 default_palette_size_7_y_color_cdf[PALETTE_COLOR_CONTEXTS][6] = { { AOM_CDF(23105, 25199, 26464, 27684, 28931, 30318) }, { AOM_CDF(6950, 15447, 18952, 22681, 25567, 28563) }, { AOM_CDF(7560, 23474, 25490, 27203, 28921, 30708) }, @@ -765,7 +765,7 @@ static const u16 default_palette_size_7_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 6 { AOM_CDF(31198, 31451, 31670, 31882, 32123, 32391) } }; -static const u16 default_palette_size_8_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 7 ] = { +static const u16 default_palette_size_8_y_color_cdf[PALETTE_COLOR_CONTEXTS][7] = { { AOM_CDF(21689, 23883, 25163, 26352, 27506, 28827, 30195) }, { AOM_CDF(6892, 15385, 17840, 21606, 24287, 26753, 29204) }, { AOM_CDF(5651, 23182, 25042, 26518, 27982, 29392, 30900) }, @@ -773,7 +773,7 @@ static const u16 default_palette_size_8_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 7 { AOM_CDF(31028, 31270, 31504, 31705, 31927, 32153, 32392) } }; -static const u16 default_palette_size_2_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 1 ] = { +static const u16 default_palette_size_2_uv_color_cdf[PALETTE_COLOR_CONTEXTS][1] = { { AOM_CDF(29089) }, { AOM_CDF(16384) }, { AOM_CDF(8713) }, @@ -781,7 +781,7 @@ static const u16 default_palette_size_2_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ { AOM_CDF(31610) } }; -static const u16 default_palette_size_3_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 2 ] = { +static const u16 default_palette_size_3_uv_color_cdf[PALETTE_COLOR_CONTEXTS][2] = { { AOM_CDF(25257, 29145) }, { AOM_CDF(12287, 27293) }, { AOM_CDF(7033, 27960) }, @@ -789,7 +789,7 @@ static const u16 default_palette_size_3_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ { AOM_CDF(30608, 31639) } }; -static const u16 default_palette_size_4_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 3 ] = { +static const u16 default_palette_size_4_uv_color_cdf[PALETTE_COLOR_CONTEXTS][3] = { { AOM_CDF(24210, 27175, 29903) }, { AOM_CDF(9888, 22386, 27214) }, { AOM_CDF(5901, 26053, 29293) }, @@ -797,7 +797,7 @@ static const u16 default_palette_size_4_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ { AOM_CDF(30459, 31136, 31926) } }; -static const u16 default_palette_size_5_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 4 ] = { +static const u16 default_palette_size_5_uv_color_cdf[PALETTE_COLOR_CONTEXTS][4] = { { AOM_CDF(22980, 25479, 27781, 29986) }, { AOM_CDF(8413, 21408, 24859, 28874) }, { AOM_CDF(2257, 29449, 30594, 31598) }, @@ -805,7 +805,7 @@ static const u16 default_palette_size_5_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ { AOM_CDF(31844, 32044, 32281, 32518) } }; -static const u16 default_palette_size_6_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 5 ] = { +static const u16 default_palette_size_6_uv_color_cdf[PALETTE_COLOR_CONTEXTS][5] = { { AOM_CDF(22217, 24567, 26637, 28683, 30548) }, { AOM_CDF(7307, 16406, 19636, 24632, 28424) }, { AOM_CDF(4441, 25064, 26879, 28942, 30919) }, @@ -813,7 +813,7 @@ static const u16 default_palette_size_6_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ { AOM_CDF(30674, 30953, 31396, 31735, 32207) } }; -static const u16 default_palette_size_7_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 6 ] = { +static const u16 default_palette_size_7_uv_color_cdf[PALETTE_COLOR_CONTEXTS][6] = { { AOM_CDF(21239, 23168, 25044, 26962, 28705, 30506) }, { AOM_CDF(6545, 15012, 18004, 21817, 25503, 28701) }, { AOM_CDF(3448, 26295, 27437, 28704, 30126, 31442) }, @@ -821,7 +821,7 @@ static const u16 default_palette_size_7_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ { AOM_CDF(30988, 31204, 31479, 31734, 31983, 32325) } }; -static const u16 default_palette_size_8_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 7 ] = { +static const u16 default_palette_size_8_uv_color_cdf[PALETTE_COLOR_CONTEXTS][7] = { { AOM_CDF(21442, 23288, 24758, 26246, 27649, 28980, 30563) }, { AOM_CDF(5863, 14933, 17552, 20668, 23683, 26411, 29273) }, { AOM_CDF(3415, 25810, 26877, 27990, 29223, 30394, 31618) }, @@ -4023,7 +4023,7 @@ void avd_av1_default_coeff_probs(u32 base_qindex, void *ptr) void avd_av1_set_default_cdfs(void *ptr) //, { - struct avd_av1_cdfs *cdfs = ((struct avd_av1_cdfs*)ptr); + struct avd_av1_cdfs *cdfs = ((struct avd_av1_cdfs *)ptr); memcpy(cdfs->partition_cdf_0, default_partition_cdf_0, sizeof(cdfs->partition_cdf_0)); diff --git a/drivers/media/platform/apple/avd/avd-av1-test.c b/drivers/media/platform/apple/avd/avd-av1-test.c new file mode 100644 index 00000000000000..c88815e38db479 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-av1-test.c @@ -0,0 +1,293 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the AV1 tile and frame size checks of the Apple video + * decoder. + */ + +#include +#include +#include + +#include "avd.h" + +#define AVD_TEST_PAYLOAD 4096 + +/* A rows x cols layout, entries in raster order, each tile 100 bytes. */ +static void avd_av1_test_layout(struct v4l2_ctrl_av1_tile_group_entry *e, + unsigned int rows, unsigned int cols) +{ + unsigned int r, c; + + for (r = 0; r < rows; r++) + for (c = 0; c < cols; c++, e++) { + e->tile_offset = (r * cols + c) * 100; + e->tile_size = 100; + e->tile_row = r; + e->tile_col = c; + } +} + +static void avd_av1_tiles_valid_test(struct kunit *test) +{ + struct v4l2_ctrl_av1_tile_group_entry e[6] = {}; + + avd_av1_test_layout(e, 2, 3); + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 6, + AVD_TEST_PAYLOAD), 0); + /* Entries past the frame's tiles are not looked at. */ + e[5].tile_row = U32_MAX; + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 1, 3, e, 6, + AVD_TEST_PAYLOAD), 0); + /* No tiles, no entries. */ + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 0, 0, e, 0, + AVD_TEST_PAYLOAD), 0); +} + +static void avd_av1_tiles_count_test(struct kunit *test) +{ + struct v4l2_ctrl_av1_tile_group_entry e[6] = {}; + + avd_av1_test_layout(e, 2, 3); + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 5, + AVD_TEST_PAYLOAD), -EINVAL); + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, V4L2_AV1_MAX_TILE_ROWS + 1, + 1, e, 6, AVD_TEST_PAYLOAD), + -EINVAL); + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 1, + V4L2_AV1_MAX_TILE_COLS + 1, + e, 6, AVD_TEST_PAYLOAD), + -EINVAL); +} + +static void avd_av1_tiles_extent_test(struct kunit *test) +{ + struct v4l2_ctrl_av1_tile_group_entry e[6] = {}; + + avd_av1_test_layout(e, 2, 3); + /* The last tile ends exactly at the payload's end. */ + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 6, 600), 0); + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 6, 599), + -EINVAL); + e[2].tile_offset = U32_MAX; + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 6, + AVD_TEST_PAYLOAD), -EINVAL); + e[2].tile_offset = 200; + e[2].tile_size = U32_MAX; + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 6, + AVD_TEST_PAYLOAD), -EINVAL); +} + +struct avd_av1_rowcol_case { + const char *desc; + unsigned int idx; + u32 tile_row; + u32 tile_col; + int ret; +}; + +/* Entry idx of a 2x3 layout gets tile_row/tile_col; every other entry is valid. */ +static const struct avd_av1_rowcol_case avd_av1_rowcol_cases[] = { + { "last row and column", 5, 1, 2, 0 }, + { "row equals tile_rows", 5, 2, 2, -EINVAL }, + { "column equals tile_cols", 5, 1, 3, -EINVAL }, + { "first entry, row equals tile_rows", 0, 2, 0, -EINVAL }, + { "row past the tile_info arrays", 3, V4L2_AV1_MAX_TILE_ROWS + 1, 0, -EINVAL }, + { "column past the tile_info arrays", 3, 0, V4L2_AV1_MAX_TILE_COLS + 1, -EINVAL }, + { "huge row", 1, 0x3fffffff, 0, -EINVAL }, + { "huge column", 1, 0, 0x3fffffff, -EINVAL }, + { "row U32_MAX", 4, U32_MAX, 1, -EINVAL }, + { "column U32_MAX", 4, 1, U32_MAX, -EINVAL }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_av1_rowcol, avd_av1_rowcol_cases, desc); + +static void avd_av1_tiles_rowcol_test(struct kunit *test) +{ + const struct avd_av1_rowcol_case *c = test->param_value; + struct v4l2_ctrl_av1_tile_group_entry e[6] = {}; + + avd_av1_test_layout(e, 2, 3); + e[c->idx].tile_row = c->tile_row; + e[c->idx].tile_col = c->tile_col; + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 6, + AVD_TEST_PAYLOAD), c->ret); +} + +/* + * The run takes its own copy of the tile-group entries: replacing and freeing + * the control's storage afterwards, as setting a larger array does, leaves + * the copy and its count intact. + */ +static void avd_av1_copy_tile_group_test(struct kunit *test) +{ + struct v4l2_ctrl_av1_tile_group_entry expect[6] = {}; + struct v4l2_ctrl_av1_tile_group_entry *src, *bigger, *copy; + struct v4l2_ctrl_handler *hdl; + struct v4l2_ctrl *ctrl; + unsigned int entries = 0; + + hdl = kunit_kzalloc(test, sizeof(*hdl), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, hdl); + ctrl = kunit_kzalloc(test, sizeof(*ctrl), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctrl); + KUNIT_ASSERT_EQ(test, v4l2_ctrl_handler_init(hdl, 0), 0); + + src = kcalloc(ARRAY_SIZE(expect), sizeof(*src), GFP_KERNEL); + bigger = kcalloc(V4L2_AV1_MAX_TILE_COUNT, sizeof(*bigger), GFP_KERNEL); + if (!src || !bigger) { + kfree(src); + kfree(bigger); + v4l2_ctrl_handler_free(hdl); + KUNIT_FAIL(test, "out of memory"); + return; + } + avd_av1_test_layout(expect, 2, 3); + memcpy(src, expect, sizeof(expect)); + ctrl->handler = hdl; + ctrl->elems = ARRAY_SIZE(expect); + ctrl->elem_size = sizeof(*src); + ctrl->p_cur.p = src; + + copy = avd_av1_copy_tile_group(ctrl, &entries); + KUNIT_EXPECT_EQ(test, entries, ARRAY_SIZE(expect)); + + /* A larger array replaces and frees the old storage. */ + memset(bigger, 0xff, V4L2_AV1_MAX_TILE_COUNT * sizeof(*bigger)); + ctrl->p_cur.p = bigger; + ctrl->elems = V4L2_AV1_MAX_TILE_COUNT; + memset(src, 0xff, sizeof(expect)); + kfree(src); + + if (copy) { + KUNIT_EXPECT_MEMEQ(test, copy, expect, sizeof(expect)); + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, copy, + entries, + AVD_TEST_PAYLOAD), 0); + } else { + KUNIT_FAIL(test, "no copy"); + } + KUNIT_EXPECT_EQ(test, entries, ARRAY_SIZE(expect)); + + kfree(copy); + kfree(bigger); + v4l2_ctrl_handler_free(hdl); +} + +struct avd_av1_size_case { + const char *desc; + u32 width; + u32 height; + u32 upscaled_width; + bool superres; + int ret; + u8 denom; +}; + +/* Frames for 1920x1088 CAPTURE buffers. */ +static const struct avd_av1_size_case avd_av1_size_cases[] = { + { "frame of the buffer size", 1920, 1088, 1920, false, 0 }, + { "smaller frame", 1280, 720, 1280, false, 0 }, + { "one sample", 1, 1, 1, false, 0 }, + { "superres to the buffer width", 960, 1080, 1920, true, 0, 16 }, + { "superres to a smaller width", 1000, 1080, 1280, true, 0, 16 }, + { "superres with equal widths", 1920, 1080, 1920, true, 0, 16 }, + { "frame wider than the buffer", 1921, 1080, 1921, false, -EINVAL }, + { "frame higher than the buffer", 1920, 1089, 1920, false, -EINVAL }, + { "frame width wraps", 0, 1080, 1920, false, -EINVAL }, + { "frame height wraps", 1920, 0, 1920, false, -EINVAL }, + { "no upscaled width", 1920, 1080, 0, false, -EINVAL }, + { "no upscaled width, superres", 1920, 1080, 0, true, -EINVAL, 16 }, + { "upscaled width below the frame's", 1920, 1080, 1919, true, -EINVAL, 16 }, + { "upscaled width past the buffer", 960, 1080, 1921, true, -EINVAL, 16 }, + { "huge upscaled width", 960, 1080, U32_MAX, true, -EINVAL, 16 }, + { "upscaled width without superres", 960, 1080, 1920, false, -EINVAL }, + { "superres, smallest denominator", 1072, 1080, 1920, true, 0, 9 }, + { "superres, no denominator", 960, 1080, 1920, true, -EINVAL, 0 }, + { "superres, denominator below 9", 960, 1080, 1920, true, -EINVAL, 8 }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_av1_size, avd_av1_size_cases, desc); + +static void avd_av1_frame_size_test(struct kunit *test) +{ + const struct avd_av1_size_case *c = test->param_value; + struct v4l2_ctrl_av1_frame *frame; + + frame = kunit_kzalloc(test, sizeof(*frame), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, frame); + frame->frame_width_minus_1 = c->width - 1; + frame->frame_height_minus_1 = c->height - 1; + frame->upscaled_width = c->upscaled_width; + frame->superres_denom = c->denom; + if (c->superres) + frame->flags |= V4L2_AV1_FRAME_FLAG_USE_SUPERRES; + + KUNIT_EXPECT_EQ(test, avd_av1_check_frame_size(frame, 1920, 1088), + c->ret); +} + +/* + * A frame that does not fit the CAPTURE format is refused when the control + * is set, once CAPTURE buffers are allocated and the format can no longer + * follow it. + */ +static void avd_av1_try_frame_size_test(struct kunit *test) +{ + static const struct v4l2_ctrl_config cfg = { + .id = V4L2_CID_STATELESS_AV1_FRAME, + }; + struct v4l2_m2m_ctx *m2m_ctx; + struct v4l2_ctrl_av1_frame *frame; + struct v4l2_ctrl *ctrl; + struct avd_ctx *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + m2m_ctx = kunit_kzalloc(test, sizeof(*m2m_ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, m2m_ctx); + ctx->fh.m2m_ctx = m2m_ctx; + ctx->decoded_fmt.fmt.pix_mp.width = 1920; + ctx->decoded_fmt.fmt.pix_mp.height = 1088; + + v4l2_ctrl_handler_init(&ctx->ctrl_hdl, 1); + ctrl = v4l2_ctrl_new_custom(&ctx->ctrl_hdl, &cfg, NULL); + KUNIT_ASSERT_EQ(test, ctx->ctrl_hdl.error, 0); + KUNIT_ASSERT_NOT_NULL(test, ctrl); + frame = ctrl->p_new.p_av1_frame; + + /* No buffers: the format may still be set to the stream's size. */ + frame->frame_width_minus_1 = 3839; + frame->frame_height_minus_1 = 2159; + frame->upscaled_width = 3840; + KUNIT_EXPECT_EQ(test, avd_av1_fmt_ops.try_ctrl(ctx, ctrl), 0); + + m2m_ctx->cap_q_ctx.q.is_busy = 1; + KUNIT_EXPECT_EQ(test, avd_av1_fmt_ops.try_ctrl(ctx, ctrl), -EINVAL); + frame->frame_width_minus_1 = 1919; + frame->frame_height_minus_1 = 1079; + KUNIT_EXPECT_EQ(test, avd_av1_fmt_ops.try_ctrl(ctx, ctrl), -EINVAL); + frame->upscaled_width = 1920; + KUNIT_EXPECT_EQ(test, avd_av1_fmt_ops.try_ctrl(ctx, ctrl), 0); + frame->upscaled_width = 0; + KUNIT_EXPECT_EQ(test, avd_av1_fmt_ops.try_ctrl(ctx, ctrl), -EINVAL); + + v4l2_ctrl_handler_free(&ctx->ctrl_hdl); +} + +static struct kunit_case avd_av1_test_cases[] = { + KUNIT_CASE(avd_av1_tiles_valid_test), + KUNIT_CASE(avd_av1_tiles_count_test), + KUNIT_CASE(avd_av1_tiles_extent_test), + KUNIT_CASE_PARAM(avd_av1_tiles_rowcol_test, avd_av1_rowcol_gen_params), + KUNIT_CASE(avd_av1_copy_tile_group_test), + KUNIT_CASE_PARAM(avd_av1_frame_size_test, avd_av1_size_gen_params), + KUNIT_CASE(avd_av1_try_frame_size_test), + {} +}; + +static struct kunit_suite avd_av1_test_suite = { + .name = "apple-avd-av1", + .test_cases = avd_av1_test_cases, +}; + +kunit_test_suite(avd_av1_test_suite); diff --git a/drivers/media/platform/apple/avd/avd-av1.c b/drivers/media/platform/apple/avd/avd-av1.c index 8b3c2f34c542ca..04d55dd7b0aad2 100644 --- a/drivers/media/platform/apple/avd/avd-av1.c +++ b/drivers/media/platform/apple/avd/avd-av1.c @@ -16,6 +16,7 @@ * Tomasz Figa */ +#include #include #include "avd.h" @@ -220,7 +221,12 @@ struct avd_av1_run { const struct v4l2_ctrl_av1_sequence *seq; const struct v4l2_ctrl_av1_frame *frame; - const struct v4l2_ctrl_av1_tile_group_entry *tile_group; + /* Private copy of the tile-group control, freed by avd_av1_run(). */ + struct v4l2_ctrl_av1_tile_group_entry *tile_group; + unsigned int tile_group_entries; + /* The tile grid tile_group was checked against */ + unsigned int tile_rows; + unsigned int tile_cols; const struct v4l2_ctrl_av1_film_grain *grain; }; @@ -267,6 +273,13 @@ struct avd_av1_stream { unsigned int nbanks; struct avd_av1_bank bank[AVD_AV1_BANKS]; struct avd_av1_bank *b; + + /* What the run being built took from the controls, see avd_ctrl_copy(). */ + struct { + struct v4l2_ctrl_av1_sequence seq; + struct v4l2_ctrl_av1_frame frame; + struct v4l2_ctrl_av1_film_grain grain; + } params; }; /* @@ -1138,12 +1151,12 @@ static void set_tiles(struct avd_ctx *ctx, struct avd_av1_run *run) seq->flags & V4L2_AV1_SEQUENCE_FLAG_USE_128X128_SUPERBLOCK ? 5 : 4; - av1_ctx->submit_num = tile_info->tile_cols * tile_info->tile_rows; + av1_ctx->submit_num = run->tile_cols * run->tile_rows; - for (row = 0; row < tile_info->tile_rows; row++) { - for (col = 0; col < tile_info->tile_cols; col++) { + for (row = 0; row < run->tile_rows; row++) { + for (col = 0; col < run->tile_cols; col++) { ctx->job.num++; - tile_id = row * tile_info->tile_cols + col; + tile_id = row * run->tile_cols + col; tile_group = &run->tile_group[tile_id]; push(AVD_OP_CODED_DATA | @@ -1396,34 +1409,67 @@ static void update_dec_buf_info(struct avd_decoded_buffer *buf, buf->av1.ref_frame_idx[i] = frame->ref_frame_idx[i]; } -/* The engine fetches each tile from these: bad values make it read wild addresses. */ -static int avd_av1_check_tiles(struct avd_ctx *ctx, struct avd_av1_run *run, - unsigned int entries) +/* + * The engine fetches each tile from these: bad values make it read wild + * addresses. set_tiles() also looks each entry's tile_row and tile_col up in + * the frame's tile_info arrays; in a conformant stream they are below + * TileRows and TileCols (AV1 5.11.1, tile_group_obu()), and TileRows and + * TileCols are at most MAX_TILE_ROWS and MAX_TILE_COLS (AV1 section 3). + */ +VISIBLE_IF_KUNIT int +avd_av1_check_tiles(struct device *dev, unsigned int tile_rows, + unsigned int tile_cols, + const struct v4l2_ctrl_av1_tile_group_entry *tile_group, + unsigned int entries, size_t payload) { - unsigned int tiles = run->frame->tile_info.tile_cols * - run->frame->tile_info.tile_rows; + unsigned int tiles = tile_cols * tile_rows; unsigned int t; - size_t payload; + if (tile_rows > V4L2_AV1_MAX_TILE_ROWS || + tile_cols > V4L2_AV1_MAX_TILE_COLS) + return -EINVAL; if (entries < tiles) { - dev_err_ratelimited(ctx->dev->dev, "AV1: %u tiles but %u tile entries\n", + dev_err_ratelimited(dev, "AV1: %u tiles but %u tile entries\n", tiles, entries); return -EINVAL; } - if (!tiles) - return 0; - payload = vb2_get_plane_payload(&run->base.bufs.src->vb2_buf, 0); for (t = 0; t < tiles; t++) { - const struct v4l2_ctrl_av1_tile_group_entry *e = &run->tile_group[t]; + const struct v4l2_ctrl_av1_tile_group_entry *e = &tile_group[t]; if ((u64)e->tile_offset + e->tile_size > payload) { - dev_err_ratelimited(ctx->dev->dev, "AV1: tile %u at %u+%u past %zu bytes\n", + dev_err_ratelimited(dev, "AV1: tile %u at %u+%u past %zu bytes\n", t, e->tile_offset, e->tile_size, payload); return -EINVAL; } + if (e->tile_row >= tile_rows || e->tile_col >= tile_cols) { + dev_err_ratelimited(dev, "AV1: tile %u at row %u col %u of %ux%u\n", + t, e->tile_row, e->tile_col, + tile_rows, tile_cols); + return -EINVAL; + } } return 0; } +EXPORT_SYMBOL_IF_KUNIT(avd_av1_check_tiles); + +/* + * Setting a larger tile-group array reallocates the control's storage and + * frees the old one under the control lock, which the run does not otherwise + * hold. Copy the entries under that lock; the run checks and uses the copy. + */ +VISIBLE_IF_KUNIT struct v4l2_ctrl_av1_tile_group_entry * +avd_av1_copy_tile_group(struct v4l2_ctrl *ctrl, unsigned int *entries) +{ + struct v4l2_ctrl_av1_tile_group_entry *copy; + + v4l2_ctrl_lock(ctrl); + *entries = ctrl->elems; + copy = kmemdup_array(ctrl->p_cur.p, ctrl->elems, ctrl->elem_size, + GFP_KERNEL); + v4l2_ctrl_unlock(ctrl); + return copy; +} +EXPORT_SYMBOL_IF_KUNIT(avd_av1_copy_tile_group); /* * Only the AV1 Main profile at 4:2:0 (8 and 10 bits) decodes. A High @@ -1433,6 +1479,14 @@ static int avd_av1_check_tiles(struct avd_ctx *ctx, struct avd_av1_run *run, * when the sequence is set and again when a frame runs, so it never * reaches the decoder. */ +static enum avd_image_fmt +avd_av1_seq_image_fmt(const struct v4l2_ctrl_av1_sequence *seq) +{ + /* avd_av1_validate_sequence() admits only Main profile 4:2:0. */ + return seq->bit_depth == 8 ? AVD_IMG_FMT_420_8BIT : + AVD_IMG_FMT_420_10BIT; +} + static int avd_av1_validate_sequence(struct avd_ctx *ctx, const struct v4l2_ctrl_av1_sequence *seq) { @@ -1451,8 +1505,46 @@ static int avd_av1_validate_sequence(struct avd_ctx *ctx, return 0; } +/* + * The map, CDFs and color data sit at the end of the CAPTURE buffer, sized by + * the frame, so the frame must fit the CAPTURE format. So must the width it + * is upscaled to, which goes into the header as it is and divides the scale + * factors: superres only widens the frame, from frame_width to upscaled_width + * (AV1 7.16), and without it the two are equal (AV1 5.9.8, superres_params()). + */ +VISIBLE_IF_KUNIT int +avd_av1_check_frame_size(const struct v4l2_ctrl_av1_frame *frame, u32 width, + u32 height) +{ + u32 frame_width; + + if (frame->frame_width_minus_1 >= width || + frame->frame_height_minus_1 >= height) + return -EINVAL; + + frame_width = frame->frame_width_minus_1 + 1; + if (frame->upscaled_width < frame_width || + frame->upscaled_width > width) + return -EINVAL; + if (!(frame->flags & V4L2_AV1_FRAME_FLAG_USE_SUPERRES) && + frame->upscaled_width != frame_width) + return -EINVAL; + /* + * With superres the denominator goes into the header less one; the + * stream codes it as 9 to 16 (AV1 5.9.8), the control core only + * bounds it from above. + */ + if ((frame->flags & V4L2_AV1_FRAME_FLAG_USE_SUPERRES) && + frame->superres_denom < 9) + return -EINVAL; + + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_av1_check_frame_size); + static int avd_av1_run_preamble(struct avd_ctx *ctx, struct avd_av1_run *run) { + struct avd_av1_stream *av1_ctx = ((struct avd_av1_ctx *)ctx->priv)->stream; struct v4l2_ctrl *ctrl; int dst_len, ret, tlb_len; @@ -1460,25 +1552,39 @@ static int avd_av1_run_preamble(struct avd_ctx *ctx, struct avd_av1_run *run) if (run->base.setup_err) return run->base.setup_err; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_AV1_SEQUENCE); - if (WARN_ON(!ctrl)) - return -EINVAL; - run->seq = ctrl->p_cur.p; + /* + * The checks below and the builders must see the same parameters, and + * the controls can be set again at any time: use copies. + */ + ret = avd_ctrl_copy(ctx, V4L2_CID_STATELESS_AV1_SEQUENCE, + &av1_ctx->params.seq, sizeof(av1_ctx->params.seq)); + if (!ret) + ret = avd_ctrl_copy(ctx, V4L2_CID_STATELESS_AV1_FRAME, + &av1_ctx->params.frame, + sizeof(av1_ctx->params.frame)); + if (!ret) + ret = avd_ctrl_copy(ctx, V4L2_CID_STATELESS_AV1_FILM_GRAIN, + &av1_ctx->params.grain, + sizeof(av1_ctx->params.grain)); + if (WARN_ON(ret)) + return ret; + run->seq = &av1_ctx->params.seq; + run->frame = &av1_ctx->params.frame; + run->grain = &av1_ctx->params.grain; /* The sequence may have been set, unchecked, while another codec was selected. */ ret = avd_av1_validate_sequence(ctx, run->seq); + if (!ret) + ret = avd_check_run_image_fmt(ctx, + avd_av1_seq_image_fmt(run->seq)); if (ret) return ret; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_AV1_FRAME); - if (WARN_ON(!ctrl)) - return -EINVAL; - run->frame = ctrl->p_cur.p; - - /* The map, CDFs and color data sit at the buffer's end, sized by the frame. */ - if (run->frame->frame_width_minus_1 + 1 > ctx->decoded_fmt.fmt.pix_mp.width || - run->frame->frame_height_minus_1 + 1 > ctx->decoded_fmt.fmt.pix_mp.height) - return -EINVAL; + ret = avd_av1_check_frame_size(run->frame, + ctx->decoded_fmt.fmt.pix_mp.width, + ctx->decoded_fmt.fmt.pix_mp.height); + if (ret) + return ret; /* * The CDF and segmentation map loads index the reference arrays with @@ -1497,17 +1603,17 @@ static int avd_av1_run_preamble(struct avd_ctx *ctx, struct avd_av1_run *run) V4L2_CID_STATELESS_AV1_TILE_GROUP_ENTRY); if (WARN_ON(!ctrl)) return -EINVAL; - run->tile_group = ctrl->p_cur.p; - ret = avd_av1_check_tiles(ctx, run, ctrl->elems); + run->tile_group = avd_av1_copy_tile_group(ctrl, &run->tile_group_entries); + if (!run->tile_group) + return -ENOMEM; + run->tile_rows = run->frame->tile_info.tile_rows; + run->tile_cols = run->frame->tile_info.tile_cols; + ret = avd_av1_check_tiles(ctx->dev->dev, run->tile_rows, run->tile_cols, + run->tile_group, run->tile_group_entries, + vb2_get_plane_payload(&run->base.bufs.src->vb2_buf, 0)); if (ret) return ret; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_AV1_FILM_GRAIN); - if (WARN_ON(!ctrl)) - return -EINVAL; - run->grain = ctrl->p_cur.p; - dst_len = run->base.bufs.dst->vb2_buf.planes[0].length; tlb_len = avd_color_size(run->frame->frame_width_minus_1 + 1, run->frame->frame_height_minus_1 + 1); @@ -1665,7 +1771,7 @@ static int avd_av1_alloc_work_bufs(struct avd_ctx *ctx, struct avd_av1_run *run) static int avd_av1_run(struct avd_ctx *ctx) { - struct avd_av1_run run; + struct avd_av1_run run = {}; struct avd_av1_stream *av1_ctx = ((struct avd_av1_ctx *)ctx->priv)->stream; struct avd_decoded_buffer *dst, *ref; int ret; @@ -1673,7 +1779,7 @@ static int avd_av1_run(struct avd_ctx *ctx) ret = avd_av1_run_preamble(ctx, &run); if (ret) { avd_run_postamble(ctx, &run.base); - return ret; + goto out; } /* The CDF and segmentation map copies need the CPU mappings. */ @@ -1687,7 +1793,8 @@ static int avd_av1_run(struct avd_ctx *ctx) if (!vb2_plane_vaddr(&dst->base.vb.vb2_buf, 0) || !vb2_plane_vaddr(&ref->base.vb.vb2_buf, 0)) { avd_run_postamble(ctx, &run.base); - return -ENOMEM; + ret = -ENOMEM; + goto out; } if (av1_ctx->nbanks > 1) { struct avd_av1_bank *bank = NULL; @@ -1699,7 +1806,8 @@ static int avd_av1_run(struct avd_ctx *ctx) } if (!bank) { avd_run_postamble(ctx, &run.base); - return -EBUSY; + ret = -EBUSY; + goto out; } av1_ctx->b = bank; smp_store_release(&ctx->priv, &bank->codec); @@ -1714,18 +1822,16 @@ static int avd_av1_run(struct avd_ctx *ctx) } ret = avd_init_job(ctx, AVD_CODEC_AV1, - run.frame->tile_info.tile_cols * - run.frame->tile_info.tile_rows + - 1); + run.tile_cols * run.tile_rows + 1); if (ret) { avd_run_postamble(ctx, &run.base); - return ret; + goto out; } ret = avd_av1_alloc_work_bufs(ctx, &run); if (ret) { avd_run_postamble(ctx, &run.base); - return ret; + goto out; } update_dec_buf_info(dst, run.seq, run.frame); @@ -1742,7 +1848,10 @@ static int avd_av1_run(struct avd_ctx *ctx) avd_run_postamble(ctx, &run.base); - return avd_submit_job(ctx); + ret = avd_submit_job(ctx); +out: + kfree(run.tile_group); + return ret; } @@ -1881,18 +1990,10 @@ static int avd_av1_start(struct avd_ctx *ctx) static enum avd_image_fmt avd_av1_get_image_fmt(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { -#define BIT_DEPTH(chroma) \ - (seq->bit_depth == 8 ? AVD_IMG_FMT_##chroma##_8BIT : \ - AVD_IMG_FMT_##chroma##_10BIT) - - const struct v4l2_ctrl_av1_sequence *seq = ctrl->p_new.p_av1_sequence; - if (ctrl->id != V4L2_CID_STATELESS_AV1_SEQUENCE) return AVD_IMG_FMT_ANY; - /* avd_av1_validate_sequence() admits only Main profile 4:2:0. */ - return BIT_DEPTH(420); -#undef BIT_DEPTH + return avd_av1_seq_image_fmt(ctrl->p_new.p_av1_sequence); } static unsigned int avd_av1_pp_kicks(struct avd_ctx *ctx) @@ -1935,10 +2036,25 @@ static void avd_av1_adjust_decoded_fmt(struct avd_ctx *ctx, static int avd_av1_try_ctrl(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { + struct vb2_queue *vq; + if (ctrl->id == V4L2_CID_STATELESS_AV1_SEQUENCE) return avd_av1_validate_sequence(ctx, ctrl->p_new.p_av1_sequence); /* width should also be > 8 */ + if (ctrl->id != V4L2_CID_STATELESS_AV1_FRAME) + return 0; + + /* + * The CAPTURE format is fixed while its buffers are allocated: a frame + * that does not fit them cannot be decoded, as the run finds too. + * Before that the format may still be set to the stream's. + */ + vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); + if (vb2_is_busy(vq)) + return avd_av1_check_frame_size(ctrl->p_new.p_av1_frame, + ctx->decoded_fmt.fmt.pix_mp.width, + ctx->decoded_fmt.fmt.pix_mp.height); return 0; } diff --git a/drivers/media/platform/apple/avd/avd-backend-kopsia.c b/drivers/media/platform/apple/avd/avd-backend-kopsia.c new file mode 100644 index 00000000000000..f242e90d4be8aa --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-backend-kopsia.c @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * T8152 Kopsia bring-up: host submission and polled VP/PP completion. + * + * Completion is polled because no decoder interrupt is described: the ADT's + * avd node lists only its PostOffice mailbox pair (AIC 308 and 268, mailbox + * 9's send-empty and recv-not-empty), and with the MCU halted nothing is known + * to raise them. The poll runs only while a frame is active. + */ +#include +#include +#include "avd.h" + +#define KOPSIA_STATUS(n) (0x194 + 4 * (n)) +#define KOPSIA_ERROR BIT(1) +#define KOPSIA_DONE BIT(2) +#define KOPSIA_PP 13 + +struct avd_kopsia_tunable { u32 off, mask, val; }; +#include "avd-kopsia-tunables.h" + +struct avd_kopsia { + struct avd_dev *avd; + void __iomem *wrap; + void __iomem *dma; + struct work_struct poll_work; + bool running; +}; + +static void kopsia_update(void __iomem *reg, u32 mask, u32 value) +{ + writel((readl(reg) & ~mask) | value, reg); +} + +static int avd_kopsia_boot(struct avd_dev *avd) +{ + struct avd_kopsia *k = avd->backend_priv; + unsigned int i; + + if (readl(avd->ctrl) != 0x40030) + return -ENODEV; + + /* Keep the MCU halted: this transport owns the hardware status bits. */ + writel(0xe, avd->mbox + 0x28); + kopsia_update(avd->mbox + 0x40, BIT(24), BIT(24)); + writel(0, avd->mbox + 0x104); + writel(1, k->wrap + 0x18); + writel(0, k->dma); + writel(0x20, avd->ctrl + 0x1cc); + writel(U32_MAX, avd->ctrl + 0xe6d0); + writel(U32_MAX, avd->ctrl + 0xe6d4); + writel(U32_MAX, avd->ctrl + 0xe710); + writel(U32_MAX, avd->ctrl + 0xe714); + for (i = 0; i < ARRAY_SIZE(kopsia_tunables); i++) { + const struct avd_kopsia_tunable *t = &kopsia_tunables[i]; + + kopsia_update(avd->ctrl + t->off, t->mask, t->val); + } + kopsia_update(k->wrap + 0x14, 1, 1); + kopsia_update(k->wrap + 0x18, 1, 1); + kopsia_update(k->wrap + 0x4c, 1, 1); + kopsia_update(k->dma, 2, 0); + kopsia_update(k->dma + 0x10, 0x1ff8000f, 2); + kopsia_update(k->dma + 0x14, 0x1ff8000f, 2); + kopsia_update(k->dma + 0x18, 0x1ff8000f, 3); + kopsia_update(k->dma + 0x1c, 0xf, 0); + kopsia_update(k->dma + 0x20, 0xf, 0); + for (i = 0; i <= KOPSIA_PP; i++) + writel(KOPSIA_DONE | KOPSIA_ERROR, avd->ctrl + KOPSIA_STATUS(i)); + k->running = true; + dev_info_once(avd->dev, "Kopsia host backend, decoder %#x (polled completion)\n", + readl(avd->ctrl)); + return 0; +} + +static void avd_kopsia_shutdown(struct avd_dev *avd) +{ + struct avd_kopsia *k = avd->backend_priv; + + /* Serialized against polling by queue_mutex or the idle PM reference. */ + WRITE_ONCE(k->running, false); +} + +static void avd_kopsia_poll(struct work_struct *work) +{ + struct avd_kopsia *k = container_of(work, struct avd_kopsia, poll_work); + struct avd_dev *avd = k->avd; + + for (;;) { + struct avd_frame *f; + u32 vp, status; + bool active; + + mutex_lock(&avd->queue_mutex); + f = avd->compat_active; + if (!READ_ONCE(k->running) || !f || avd->stopping || avd->faulted) { + mutex_unlock(&avd->queue_mutex); + break; + } + vp = avd->variant->vp_slot_base[f->cmd[0]]; + status = readl(avd->ctrl + KOPSIA_STATUS(vp)); + if (status & KOPSIA_ERROR) { + writel(KOPSIA_ERROR, avd->ctrl + KOPSIA_STATUS(vp)); + avd_status(avd, vp); + avd_open_complete(avd, vp); + mutex_unlock(&avd->queue_mutex); + break; + } + if (status & KOPSIA_DONE) { + writel(KOPSIA_DONE, avd->ctrl + KOPSIA_STATUS(vp)); + avd_open_complete(avd, 0x100 | vp); + } + status = readl(avd->ctrl + KOPSIA_STATUS(KOPSIA_PP)); + if (status & KOPSIA_DONE) { + writel(KOPSIA_DONE, avd->ctrl + KOPSIA_STATUS(KOPSIA_PP)); + avd_open_complete(avd, 0x1000); + } + active = avd->compat_active != NULL; + mutex_unlock(&avd->queue_mutex); + if (!active) + break; + usleep_range(100, 200); + } +} + +static int avd_kopsia_submit(struct avd_dev *avd, struct avd_frame *f) +{ + struct avd_kopsia *k = avd->backend_priv; + int ret = avd_open_submit(avd, f); + + if (!ret) + queue_work(system_dfl_wq, &k->poll_work); + return ret; +} + +static unsigned int avd_kopsia_max_inflight(struct avd_dev *avd) +{ + return 1; +} + +static void avd_kopsia_cleanup(void *data) +{ + struct avd_kopsia *k = data; + + WRITE_ONCE(k->running, false); + cancel_work_sync(&k->poll_work); +} + +static int avd_kopsia_probe(struct avd_dev *avd) +{ + struct avd_kopsia *k = devm_kzalloc(avd->dev, sizeof(*k), GFP_KERNEL); + + if (!k) + return -ENOMEM; + k->avd = avd; + k->wrap = devm_platform_ioremap_resource_byname(avd->pdev, "wrap"); + if (IS_ERR(k->wrap)) + return PTR_ERR(k->wrap); + k->dma = devm_platform_ioremap_resource_byname(avd->pdev, "dma"); + if (IS_ERR(k->dma)) + return PTR_ERR(k->dma); + INIT_WORK(&k->poll_work, avd_kopsia_poll); + avd->backend_priv = k; + return devm_add_action_or_reset(avd->dev, avd_kopsia_cleanup, k); +} + +const struct avd_backend_ops avd_kopsia_backend = { + .name = "kopsia-host", + .probe = avd_kopsia_probe, + .boot = avd_kopsia_boot, + .shutdown = avd_kopsia_shutdown, + .max_inflight = avd_kopsia_max_inflight, + .submit = avd_kopsia_submit, + .suspend = avd_pm_backend_suspend, + .resume = avd_pm_backend_resume, +}; diff --git a/drivers/media/platform/apple/avd/avd-backend-open.c b/drivers/media/platform/apple/avd/avd-backend-open.c index d2054d06f948b8..6f6028ad5895ee 100644 --- a/drivers/media/platform/apple/avd/avd-backend-open.c +++ b/drivers/media/platform/apple/avd/avd-backend-open.c @@ -29,6 +29,9 @@ int avd_open_build_program(struct avd_ctx *ctx) if (!f || !job->segments) return -EINVAL; + /* The builder ran past the table or a segment; nothing fits. */ + if (job->overflow || job->num >= job->max) + return -EOVERFLOW; for (i = 0; i <= job->num; i++) { if (job->segments[i].num > AVD_MAX_INST || check_add_overflow(count, job->segments[i].num + !!i, &count)) @@ -74,7 +77,7 @@ static unsigned int avd_open_max_inflight(struct avd_dev *avd) return 1; } -static int avd_open_submit(struct avd_dev *avd, struct avd_frame *f) +int avd_open_submit(struct avd_dev *avd, struct avd_frame *f) { struct avd_ctx *ctx = f->ctx; u32 codec = f->cmd[0], vp = 0; @@ -91,6 +94,9 @@ static int avd_open_submit(struct avd_dev *avd, struct avd_frame *f) if (codec > AVD_CODEC_AV1 || !words || !f->prog_words || f->prog_words > f->prog->size / sizeof(u32)) return -EINVAL; + /* The context FIFO only exists while the OUTPUT queue streams. */ + if (!ctx->inst.cpu) + return -EINVAL; if (!(avd->capabilities & BIT(codec))) return -EOPNOTSUPP; for (i = 0; i < codec; i++) @@ -131,13 +137,9 @@ static int avd_open_submit(struct avd_dev *avd, struct avd_frame *f) return 0; } -static irqreturn_t avd_open_irq(struct avd_dev *avd) +irqreturn_t avd_open_complete(struct avd_dev *avd, u32 status) { struct avd_frame *f = avd->compat_active; - u32 status; - - if (!avd_mbox_pop(avd, &status)) - return IRQ_HANDLED; if (!f) { /* * The old driver kicked PP for every VP DONE. A VP DONE with no @@ -177,6 +179,20 @@ static irqreturn_t avd_open_irq(struct avd_dev *avd) return IRQ_HANDLED; } +static irqreturn_t avd_open_irq(struct avd_dev *avd) +{ + u32 status; + + if (!avd_mbox_pop(avd, &status)) + return IRQ_HANDLED; + return avd_open_complete(avd, status); +} + +bool avd_backend_is_open(const struct avd_dev *avd) +{ + return avd->backend == &avd_open_backend; +} + const struct avd_backend_ops avd_open_backend = { .name = "open-compat", .boot = avd_boot, @@ -236,6 +252,13 @@ int avd_backend_select(struct avd_dev *avd) { int ret; + if (avd->variant->quirks & AVD_QUIRK_KOPSIA) { + avd->backend = &avd_kopsia_backend; + avd->capabilities = avd->variant->capabilities; + avd->fw_capabilities = avd->capabilities; + return avd->backend->probe(avd); + } + /* Apple probe returns -ENOENT only when no usable image is present. */ if (avd->variant->apple) { ret = avd_apple_backend.probe(avd); diff --git a/drivers/media/platform/apple/avd/avd-drv.c b/drivers/media/platform/apple/avd/avd-drv.c index 58ea3fc604d875..7dfe9a9dac2458 100644 --- a/drivers/media/platform/apple/avd/avd-drv.c +++ b/drivers/media/platform/apple/avd/avd-drv.c @@ -100,9 +100,11 @@ int avd_init_job(struct avd_ctx *ctx, enum avd_codec codec, size_t segments) job->codec = codec; job->num = 0; + job->overflow = false; /* A table that was built but never submitted still belongs to us. */ kvfree(job->segments); job->segments = kvcalloc(segments, sizeof(*job->segments), GFP_KERNEL); + job->max = job->segments ? segments : 0; if (!job->segments) ret = -ENOMEM; return ret; @@ -188,10 +190,6 @@ static int avd_open(struct file *filp) ctx->dev = avd; - ret = avd_buf_alloc(avd, &ctx->inst, fifo_size()); - if (ret) - goto err_free_ctx; - INIT_LIST_HEAD(&ctx->queue_node); ctx->next_dep = AVD_DEP_PREV_DONE; @@ -219,7 +217,6 @@ static int avd_open(struct file *filp) v4l2_m2m_ctx_release(ctx->fh.m2m_ctx); err_free_ctx: - avd_buf_free(avd, &ctx->inst); kfree(ctx); return ret; } @@ -280,7 +277,6 @@ static int avd_v4l2_init(struct avd_dev *avd) avd->mdev.dev = avd->dev; strscpy(avd->mdev.model, "avd", sizeof(avd->mdev.model)); - strscpy(avd->mdev.bus_info, "platform:avd", sizeof(avd->mdev.bus_info)); media_device_init(&avd->mdev); avd->mdev.ops = &avd_media_ops; avd->v4l2_dev.mdev = &avd->mdev; @@ -468,7 +464,7 @@ static const struct avd_variant avd_t8140_variant = { .submit_offset = 0x40, .submit_queue_max_offset = 0x44, .submit_queue_status_offset = 0x7c, - .quirks = AVD_QUIRK_HEVC_V5_HEADER | AVD_QUIRK_V5_QUEUE_PACING, + .quirks = AVD_QUIRK_HEVC_V5_HEADER, }; static const struct avd_variant avd_t8132_variant = { @@ -590,8 +586,35 @@ static const struct avd_variant avd_t8142_variant = { .quirks = AVD_QUIRK_HEVC_V5_HEADER | AVD_QUIRK_H264_MV_128, }; +static const struct avd_variant avd_t8152_variant = { + .vp_slots = { + [AVD_CODEC_HEVC] = 2, + [AVD_CODEC_H264] = 1, + [AVD_CODEC_VP9] = 1, + [AVD_CODEC_AV1] = 1, + }, + .vp_slot_base = { + [AVD_CODEC_HEVC] = 0, + [AVD_CODEC_H264] = 4, + [AVD_CODEC_VP9] = 8, + [AVD_CODEC_AV1] = 9, + }, + .fifo_slots = 7, + .configure_stream = t8122_configure_stream, + .capabilities = AVD_CAPABILITY_H264 | AVD_CAPABILITY_HEVC | + AVD_CAPABILITY_VP9 | AVD_CAPABILITY_AV1, + .revision = 4, + .vp_slot_offset = 0xc, + .submit_offset = 0x40, + .submit_queue_max_offset = 0x44, + .submit_queue_status_offset = 0x7c, + .quirks = AVD_QUIRK_HEVC_V5_HEADER | AVD_QUIRK_H264_MV_128 | + AVD_QUIRK_NO_RECOVERY_RESET | AVD_QUIRK_KOPSIA, +}; + /* can also be derived from a version register */ static const struct of_device_id avd_of_match[] = { + { .compatible = "apple,t8152-avd", .data = &avd_t8152_variant }, { .compatible = "apple,t8103-avd", .data = &avd_t8103_variant @@ -644,6 +667,57 @@ static void avd_release_open_firmware(void *data) release_firmware(avd->fw); } +static int avd_attach_power_domains(struct avd_dev *avd) +{ + static const char *const core_pd_names[] = { "core" }; + static const struct dev_pm_domain_attach_data core_pd_data = { + .pd_names = core_pd_names, + .num_pd_names = ARRAY_SIZE(core_pd_names), + .pd_flags = PD_FLAG_DEV_LINK_ON, + }; + static const struct dev_pm_domain_attach_data all_pd_data = { + .pd_flags = PD_FLAG_DEV_LINK_ON, + }; + struct device_node *np = avd->dev->of_node; + int num_pds, perf_idx, ret; + + /* + * A node may list a second power domain, "perf": a PMC or PMP + * performance floor that raises the SoC rail while the decoder works. + * With more than one domain the core attaches none. Link only "core" + * to avd->dev's runtime PM so light streams do not hold the floor on + * every frame, and manage "perf" separately on demand in avd-pm.c. + */ + num_pds = of_count_phandle_with_args(np, "power-domains", + "#power-domain-cells"); + if (num_pds <= 1) + return 0; + + perf_idx = of_property_match_string(np, "power-domain-names", "perf"); + if (perf_idx >= 0 && + of_property_match_string(np, "power-domain-names", "core") >= 0) { + ret = devm_pm_domain_attach_list(avd->dev, &core_pd_data, + &avd->pd_list); + if (ret < 0) + return dev_err_probe(avd->dev, ret, + "failed to attach core power domain\n"); + + ret = avd_pm_attach_perf(avd, perf_idx); + if (ret) + return dev_err_probe(avd->dev, ret, + "failed to attach perf power domain\n"); + + return 0; + } + + ret = devm_pm_domain_attach_list(avd->dev, &all_pd_data, &avd->pd_list); + if (ret < 0) + return dev_err_probe(avd->dev, ret, + "failed to attach power domains\n"); + + return 0; +} + static int avd_probe(struct platform_device *pdev) { struct avd_dev *avd; @@ -667,29 +741,14 @@ static int avd_probe(struct platform_device *pdev) match = of_match_node(avd_of_match, pdev->dev.of_node); avd->variant = match->data; - avd->rstc = devm_reset_control_get_exclusive(avd->dev, NULL); + avd->rstc = avd->variant->quirks & AVD_QUIRK_KOPSIA ? NULL : + devm_reset_control_get_exclusive(avd->dev, NULL); if (IS_ERR(avd->rstc)) return PTR_ERR(avd->rstc); - /* - * A node may list a second power domain, "perf": the PMC floor that - * holds the SoC rail at its performance level while the decoder works - * (decode runs at about half speed on the M4 Pro without it). With more - * than one domain the core attaches none, so attach them all with - * runtime PM device links: the floor is then held exactly while the - * decoder is runtime-active (frames in flight plus the autosuspend - * delay) and released when it idles, rests or is retired. - */ - if (of_count_phandle_with_args(pdev->dev.of_node, "power-domains", - "#power-domain-cells") > 1) { - static const struct dev_pm_domain_attach_data pd_data = { - .pd_flags = PD_FLAG_DEV_LINK_ON, - }; - - ret = devm_pm_domain_attach_list(avd->dev, &pd_data, &avd->pd_list); - if (ret < 0) - return dev_err_probe(avd->dev, ret, "failed to attach power domains\n"); - } + ret = avd_attach_power_domains(avd); + if (ret) + return ret; avd->code = devm_platform_ioremap_resource_byname(pdev, "code"); if (IS_ERR(avd->code)) @@ -705,13 +764,6 @@ static int avd_probe(struct platform_device *pdev) return ret; avd->domain = iommu_get_domain_for_dev(avd->dev); - if (avd->domain) { - avd->empty_domain = iommu_paging_domain_alloc(avd->dev); - if (IS_ERR(avd->empty_domain)) { - avd->empty_domain = NULL; - dev_warn(avd->dev, "cannot alloc new empty domain"); - } - } ret = avd_backend_select(avd); if (ret) @@ -720,6 +772,12 @@ static int avd_probe(struct platform_device *pdev) if (ret) return ret; + /* + * Neither width has a named source: the LSR encodings would allow 39 + * bits (compressed-plane addresses, addr >> 7 in one word) and 42 is + * unexplained for the Apple backend. See + * https://github.com/aurora-silicon/linux/issues/2451. + */ ret = dma_set_mask_and_coherent(avd->dev, DMA_BIT_MASK(avd_backend_is_apple(avd) ? 42 : (avd->variant->quirks & AVD_QUIRK_LSR) ? 38 : 64)); @@ -729,28 +787,38 @@ static int avd_probe(struct platform_device *pdev) return ret; } - irq = platform_get_irq(pdev, 1); - if (irq < 0) - return irq; - avd->pm.irq = irq; - ret = devm_request_threaded_irq(&pdev->dev, irq, NULL, - avd_irq_handler, IRQF_ONESHOT | IRQF_NO_AUTOEN, - dev_name(&pdev->dev), avd); - if (ret) { - dev_err(avd->dev, "Could not request IRQ 1"); - return ret; + /* Kopsia has no described completion interrupt; its backend polls. */ + if (!(avd->variant->quirks & AVD_QUIRK_KOPSIA)) { + irq = platform_get_irq(pdev, 1); + if (irq < 0) + return irq; + avd->pm.irq = irq; + ret = devm_request_threaded_irq(&pdev->dev, irq, NULL, + avd_irq_handler, IRQF_ONESHOT | IRQF_NO_AUTOEN, + dev_name(&pdev->dev), avd); + if (ret) { + dev_err(avd->dev, "Could not request IRQ 1"); + return ret; + } } /* * The domain links were added active, but the decoder starts - * suspended: settle that before enabling runtime PM, so the floor is - * not held until the first decode has come and gone. + * suspended: settle that before enabling runtime PM, so the attached + * domains are not held until the first decode has come and gone. */ if (avd->pd_list) { ret = pm_runtime_set_suspended(avd->dev); if (ret) return ret; } + if (avd->domain) { + avd->empty_domain = iommu_paging_domain_alloc(avd->dev); + if (IS_ERR(avd->empty_domain)) { + avd->empty_domain = NULL; + dev_warn(avd->dev, "cannot alloc new empty domain"); + } + } avd_pm_enable(avd); /* @@ -759,10 +827,15 @@ static int avd_probe(struct platform_device *pdev) * size their contexts before the first decode would power it up. */ ret = pm_runtime_resume_and_get(avd->dev); - if (ret < 0) + if (ret < 0) { + if (avd->variant->quirks & AVD_QUIRK_KOPSIA) { + dev_err_probe(avd->dev, ret, "Kopsia probe boot failed\n"); + goto err_disable_runtime_pm; + } dev_warn(avd->dev, "firmware probe boot failed: %d\n", ret); - else + } else { pm_runtime_put_autosuspend(avd->dev); + } ret = avd_v4l2_init(avd); if (ret) @@ -773,6 +846,9 @@ static int avd_probe(struct platform_device *pdev) err_disable_runtime_pm: pm_runtime_dont_use_autosuspend(&pdev->dev); pm_runtime_disable(&pdev->dev); + cancel_delayed_work_sync(&avd->queue_work); + if (avd->empty_domain) + iommu_domain_free(avd->empty_domain); return ret; } @@ -804,6 +880,9 @@ static struct platform_driver avd_driver = { }, }; module_platform_driver(avd_driver); +#if IS_REACHABLE(CONFIG_VIDEO_APPLE_AVD_KUNIT_TEST) +#include "avd-variant-test.c" +#endif MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("Apple avd v4l2 sl m2m"); diff --git a/drivers/media/platform/apple/avd/avd-fmt-test.c b/drivers/media/platform/apple/avd/avd-fmt-test.c new file mode 100644 index 00000000000000..63a935a2ab0478 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-fmt-test.c @@ -0,0 +1,150 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the run-time picture format check of the Apple video + * decoder. + */ + +#include +#include +#include + +#include "avd.h" + +static const struct avd_decoded_fmt_desc avd_fmt_test_decoded[] = { + { .fourcc = V4L2_PIX_FMT_NV12, .image_fmt = AVD_IMG_FMT_420_8BIT }, + { .fourcc = V4L2_PIX_FMT_P010, .image_fmt = AVD_IMG_FMT_420_10BIT }, + { .fourcc = V4L2_PIX_FMT_NV16, .image_fmt = AVD_IMG_FMT_422_8BIT }, +}; + +static const struct avd_coded_fmt_desc avd_fmt_test_desc = { + .num_decoded_fmts = ARRAY_SIZE(avd_fmt_test_decoded), + .decoded_fmts = avd_fmt_test_decoded, +}; + +/* A context whose CAPTURE format was negotiated for @sized as @fourcc. */ +static struct avd_ctx *avd_fmt_test_ctx(struct kunit *test, + enum avd_image_fmt sized, u32 fourcc) +{ + struct avd_ctx *ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + struct avd_dev *avd = kunit_kzalloc(test, sizeof(*avd), GFP_KERNEL); + struct v4l2_pix_format_mplane *pix; + + KUNIT_ASSERT_NOT_NULL(test, ctx); + KUNIT_ASSERT_NOT_NULL(test, avd); + avd->dev = kunit_device_register(test, "avd-fmt-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, avd->dev); + ctx->dev = avd; + ctx->coded_fmt_desc = &avd_fmt_test_desc; + ctx->image_fmt = sized; + pix = &ctx->decoded_fmt.fmt.pix_mp; + pix->pixelformat = fourcc; + pix->width = 64; + pix->height = 64; + fill_comp(&ctx->comp, sized, pix->width, pix->height); + return ctx; +} + +static void avd_fmt_any_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_fmt_test_ctx(test, AVD_IMG_FMT_ANY, + V4L2_PIX_FMT_NV12); + + /* Buffers sized for "any" are 8-bit 4:2:0. */ + KUNIT_EXPECT_EQ(test, avd_check_run_image_fmt(ctx, AVD_IMG_FMT_ANY), 0); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_8BIT), 0); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_10BIT), + -EINVAL); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_422_8BIT), + -EINVAL); +} + +/* "Any" with a 10-bit CAPTURE fourcc still has 8-bit sized storage. */ +static void avd_fmt_any_p010_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_fmt_test_ctx(test, AVD_IMG_FMT_ANY, + V4L2_PIX_FMT_P010); + + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_10BIT), + -EINVAL); +} + +static void avd_fmt_10bit_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_fmt_test_ctx(test, AVD_IMG_FMT_420_10BIT, + V4L2_PIX_FMT_P010); + + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_10BIT), 0); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_8BIT), + -EINVAL); +} + +static void avd_fmt_422_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_fmt_test_ctx(test, AVD_IMG_FMT_422_8BIT, + V4L2_PIX_FMT_NV16); + + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_422_8BIT), 0); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_8BIT), + -EINVAL); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_422_10BIT), + -EINVAL); +} + +/* Compressed storage laid out for another size does not fit either. */ +static void avd_fmt_comp_mismatch_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_fmt_test_ctx(test, AVD_IMG_FMT_420_8BIT, + V4L2_PIX_FMT_NV12); + + fill_comp(&ctx->comp, AVD_IMG_FMT_420_8BIT, 32, 32); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_8BIT), + -EINVAL); +} + +/* Scratch sized at STREAMON for 8 bits does not take a 10-bit picture. */ +static void avd_fmt_scratch_depth_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_fmt_test_ctx(test, AVD_IMG_FMT_420_10BIT, + V4L2_PIX_FMT_P010); + + ctx->scratch_sized = true; + ctx->scratch_fmt = AVD_IMG_FMT_ANY; + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_10BIT), + -EINVAL); + ctx->scratch_fmt = AVD_IMG_FMT_420_10BIT; + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_10BIT), 0); + /* Codecs that size no scratch from the format are not limited. */ + ctx->scratch_sized = false; + ctx->scratch_fmt = AVD_IMG_FMT_ANY; + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_10BIT), 0); +} + +static struct kunit_case avd_fmt_test_cases[] = { + KUNIT_CASE(avd_fmt_any_test), + KUNIT_CASE(avd_fmt_any_p010_test), + KUNIT_CASE(avd_fmt_10bit_test), + KUNIT_CASE(avd_fmt_422_test), + KUNIT_CASE(avd_fmt_comp_mismatch_test), + KUNIT_CASE(avd_fmt_scratch_depth_test), + {} +}; + +static struct kunit_suite avd_fmt_test_suite = { + .name = "apple-avd-fmt", + .test_cases = avd_fmt_test_cases, +}; + +kunit_test_suite(avd_fmt_test_suite); diff --git a/drivers/media/platform/apple/avd/avd-h264-parse.c b/drivers/media/platform/apple/avd/avd-h264-parse.c new file mode 100644 index 00000000000000..8c32933db8c55f --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-h264-parse.c @@ -0,0 +1,834 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Standalone H.264 Annex-B NALU scanner and ITU-T H.264 7.3.3 slice header + * parser for V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED on Apple AVD. + */ + +#include +#include +#include +#include +#include +#include + +#include "avd-h264-parse.h" + +#define AVD_H264_NAL_SLICE 1 +#define AVD_H264_NAL_DPA 2 +#define AVD_H264_NAL_DPB 3 +#define AVD_H264_NAL_DPC 4 +#define AVD_H264_NAL_IDR_SLICE 5 +#define AVD_H264_NAL_SEI 6 +#define AVD_H264_NAL_FILLER 12 +#define AVD_H264_NAL_PREFIX 14 +#define AVD_H264_NAL_EXT_SLICE 20 + +#define AVD_H264_MAX_MMCO_OPS 64 + +/* + * Scan an Annex-B byte stream for the next VCL slice NALU (types 1 and 5). + * Non-VCL NALUs (SEI, SPS, PPS, AUD, EOS, filler; types 6..12) are skipped. + * Forbidden-zero-bit violations, data partitioning (2..4), SVC/MVC (14, 20), + * and other unsupported NAL types return -EINVAL. + * + * Returns 1 when a slice NALU is written to @nalu, 0 at end of buffer, or + * -EINVAL on malformed Annex-B syntax or unsupported NAL unit types. + */ +int avd_h264_next_nalu(const u8 *buf, u32 len, u32 *cursor, + struct avd_h264_nalu *nalu) +{ + u32 pos; + + if (!cursor || !nalu) + return -EINVAL; + if (!buf) + return len ? -EINVAL : 0; + + pos = *cursor; + while (pos < len) { + u32 zeros = 0; + u32 nal_start, end, i; + u8 hdr, nal_type; + + while (pos < len && buf[pos] == 0x00) { + zeros++; + pos++; + } + if (pos == len) { + *cursor = len; + return 0; + } + if (zeros < 2 || buf[pos] != 0x01) + return -EINVAL; + + nal_start = pos + 1; + if (nal_start >= len) + return -EINVAL; + + /* Find the next 0x00 0x00 0x01 start code prefix. */ + end = len; + i = nal_start; + while (len >= 3 && i <= len - 3) { + if (buf[i + 2] > 0x01) { + i += 3; + continue; + } + if (buf[i + 2] == 0x01 && buf[i] == 0x00 && + buf[i + 1] == 0x00) { + end = i; + break; + } + i++; + } + + *cursor = end; + pos = end; + + /* Strip trailing zero bytes (4-byte start code prefix / padding). */ + while (end > nal_start && buf[end - 1] == 0x00) + end--; + if (end == nal_start) + return -EINVAL; + + hdr = buf[nal_start]; + if (hdr & 0x80) + return -EINVAL; + + nal_type = hdr & 0x1f; + switch (nal_type) { + case AVD_H264_NAL_SLICE: + case AVD_H264_NAL_IDR_SLICE: + nalu->off = nal_start; + nalu->len = end - nal_start; + nalu->nal_ref_idc = (hdr >> 5) & 0x03; + nalu->nal_unit_type = nal_type; + return 1; + case AVD_H264_NAL_SEI ... AVD_H264_NAL_FILLER: + continue; + case AVD_H264_NAL_DPA ... AVD_H264_NAL_DPC: + case AVD_H264_NAL_PREFIX: + case AVD_H264_NAL_EXT_SLICE: + default: + return -EINVAL; + } + } + + *cursor = len; + return 0; +} + +bool avd_h264_mode_supported(s32 decode_mode, s32 start_code) +{ + switch (decode_mode) { + case V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED: + return start_code == V4L2_STATELESS_H264_START_CODE_NONE; + case V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED: + return start_code == V4L2_STATELESS_H264_START_CODE_ANNEX_B || + start_code == V4L2_STATELESS_H264_START_CODE_NONE; + default: + return false; + } +} + +static bool avd_h264_has_annexb_start_code(const u8 *buf, u32 len) +{ + u32 pos = 0; + + while (pos < len && buf[pos] == 0x00) + pos++; + + return pos >= 2 && pos < len && buf[pos] == 0x01; +} + +/* + * Parse a single unprefixed ITU-T H.264 7.3.1 VCL slice NALU for + * FRAME_BASED + START_CODE_NONE. No Annex-B start code prefix is present + * and none may appear inside the EBSP payload. + */ +static int avd_h264_parse_raw_nalu(const u8 *buf, u32 len, + struct avd_h264_nalu *nalu) +{ + u32 end = len, i; + u8 hdr, nal_type; + + if (!buf || !nalu || !len) + return -EINVAL; + + while (end > 0 && buf[end - 1] == 0x00) + end--; + if (end < 2) + return -EINVAL; + + /* An EBSP must not contain an unescaped 0x00 0x00 0x01 start code. */ + for (i = 0; end >= 3 && i <= end - 3; i++) { + if (buf[i] == 0x00 && buf[i + 1] == 0x00 && buf[i + 2] == 0x01) + return -EINVAL; + } + + hdr = buf[0]; + if (hdr & 0x80) + return -EINVAL; + + nal_type = hdr & 0x1f; + if (nal_type != AVD_H264_NAL_SLICE && + nal_type != AVD_H264_NAL_IDR_SLICE) + return -EINVAL; + + nalu->off = 0; + nalu->len = end; + nalu->nal_ref_idc = (hdr >> 5) & 0x03; + nalu->nal_unit_type = nal_type; + return 1; +} + +/* + * Iterate VCL slice NALUs in a FRAME_BASED OUTPUT buffer according to + * V4L2_CID_STATELESS_H264_START_CODE: + * - START_CODE_ANNEX_B requires Annex-B start codes (0x000001 / 0x00000001). + * - START_CODE_NONE accepts a single unprefixed ITU-T H.264 7.3.1 VCL slice + * NALU. For compatibility with clients (such as Chromium's + * V4L2VideoDecoderDelegateH264) that set DECODE_MODE=FRAME_BASED without + * writing START_CODE, leaving it at this driver's START_CODE_NONE default + * while still emitting Annex-B start codes, a buffer starting with an + * Annex-B start code is dispatched to the Annex-B scanner. That cannot + * collide with valid START_CODE_NONE data because no valid 7.3.1 NALU + * begins with 0x00 (nal_unit_type 0 is invalid). + */ +int avd_h264_next_frame_nalu(const u8 *buf, u32 len, s32 start_code, + u32 *cursor, struct avd_h264_nalu *nalu) +{ + int ret; + + if (!cursor || !nalu) + return -EINVAL; + + if (start_code == V4L2_STATELESS_H264_START_CODE_ANNEX_B) + return avd_h264_next_nalu(buf, len, cursor, nalu); + + if (start_code != V4L2_STATELESS_H264_START_CODE_NONE) + return -EINVAL; + + if (!buf) + return len ? -EINVAL : 0; + if (avd_h264_has_annexb_start_code(buf, len)) + return avd_h264_next_nalu(buf, len, cursor, nalu); + if (*cursor >= len) + return 0; + + ret = avd_h264_parse_raw_nalu(buf, len, nalu); + if (ret > 0) + *cursor = len; + return ret; +} + +VISIBLE_IF_KUNIT void avd_h264_br_init(struct avd_h264_br *br, const u8 *data, + u32 len, u32 pos) +{ + br->data = data; + br->len = len; + br->pos = pos; + br->rbsp_bits = 0; + br->bit = 0; + br->zeros = 0; + br->err = false; +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_br_init); + +/* + * At a byte boundary immediately after two consecutive raw 0x00 bytes, an + * emulation prevention byte (0x03) belongs to the EBSP framing, not the RBSP. + */ +VISIBLE_IF_KUNIT void avd_h264_br_skip_epb(struct avd_h264_br *br) +{ + if (br->bit == 0 && br->zeros >= 2 && br->pos < br->len && + br->data[br->pos] == 0x03) { + br->pos++; + br->zeros = 0; + } +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_br_skip_epb); + +static u32 avd_h264_br_read_bit(struct avd_h264_br *br) +{ + u32 val; + u8 b; + + if (br->err) + return 0; + + if (br->bit == 0) { + avd_h264_br_skip_epb(br); + if (br->pos >= br->len) { + br->err = true; + return 0; + } + b = br->data[br->pos]; + if (b == 0x00) + br->zeros = min_t(u8, br->zeros + 1, 2); + else + br->zeros = 0; + } else { + b = br->data[br->pos]; + } + + val = (b >> (7 - br->bit)) & 1; + br->rbsp_bits++; + br->bit++; + if (br->bit == 8) { + br->bit = 0; + br->pos++; + } + + return val; +} + +VISIBLE_IF_KUNIT u32 avd_h264_br_read_bits(struct avd_h264_br *br, + unsigned int n) +{ + u32 val = 0; + + if (n == 0) + return 0; + if (n > 32) { + br->err = true; + return 0; + } + + while (n--) + val = (val << 1) | avd_h264_br_read_bit(br); + + return val; +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_br_read_bits); + +VISIBLE_IF_KUNIT u32 avd_h264_br_read_ue(struct avd_h264_br *br) +{ + unsigned int zeros = 0; + u32 suffix; + + while (!br->err && !avd_h264_br_read_bit(br)) { + zeros++; + if (zeros >= 32) { + br->err = true; + return 0; + } + } + if (br->err || zeros == 0) + return 0; + + suffix = avd_h264_br_read_bits(br, zeros); + if (br->err) + return 0; + + if (zeros == 31) { + if (suffix > BIT(31)) { + br->err = true; + return 0; + } + return (BIT(31) - 1) + suffix; + } + + return ((1U << zeros) - 1) + suffix; +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_br_read_ue); + +VISIBLE_IF_KUNIT s32 avd_h264_br_read_se(struct avd_h264_br *br) +{ + u32 code = avd_h264_br_read_ue(br); + + if (br->err) + return 0; + if (code == U32_MAX) { + br->err = true; + return 0; + } + if (code & 1) + return (s32)((code >> 1) + 1); + + return -(s32)(code >> 1); +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_br_read_se); + +static int avd_h264_find_short_term_dpb(const struct v4l2_h264_dpb_entry *dpb, + u32 cur_frame_num, u32 max_pic_num, + s32 target_pic_num) +{ + for (unsigned int i = 0; i < V4L2_H264_NUM_DPB_ENTRIES; i++) { + s32 dpb_pic_num; + + if (!(dpb[i].flags & V4L2_H264_DPB_ENTRY_FLAG_ACTIVE)) + continue; + if (dpb[i].flags & V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM) + continue; + if (dpb[i].frame_num >= max_pic_num) + continue; + + dpb_pic_num = dpb[i].frame_num; + if (dpb[i].frame_num > cur_frame_num) + dpb_pic_num -= (s32)max_pic_num; + + if (dpb_pic_num == target_pic_num) + return i; + } + + return -EINVAL; +} + +static int avd_h264_find_long_term_dpb(const struct v4l2_h264_dpb_entry *dpb, + u32 lt_pic_num) +{ + for (unsigned int i = 0; i < V4L2_H264_NUM_DPB_ENTRIES; i++) { + if (!(dpb[i].flags & V4L2_H264_DPB_ENTRY_FLAG_ACTIVE)) + continue; + if (!(dpb[i].flags & V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM)) + continue; + if (dpb[i].frame_num == lt_pic_num) + return i; + } + + return -EINVAL; +} + +/* H.264 7.3.3.1 & 8.2.4.3.1 for frame pictures (frame_mbs_only_flag == 1). */ +static int +avd_h264_parse_ref_list_mod(struct avd_h264_br *br, + const struct v4l2_ctrl_h264_sps *sps, + const struct v4l2_ctrl_h264_decode_params *decode, + u32 frame_num, struct v4l2_h264_reference *list, + u8 num_active_minus1) +{ + u32 max_pic_num = 1U << (sps->log2_max_frame_num_minus4 + 4); + u32 num_active = (u32)num_active_minus1 + 1; + s32 pic_num_pred = frame_num; + u32 ref_idx = 0; + + if (!avd_h264_br_read_bit(br)) + return br->err ? -EINVAL : 0; + + for (unsigned int ops = 0; ops < V4L2_H264_REF_LIST_LEN + 1; ops++) { + u32 idc = avd_h264_br_read_ue(br); + int target; + u32 c, n; + + if (br->err) + return -EINVAL; + if (idc == 3) + return 0; + if (idc > 3 || ref_idx >= num_active) + return -EINVAL; + + if (idc == 0 || idc == 1) { + u32 diff_minus1 = avd_h264_br_read_ue(br); + s32 diff, pic_num_no_wrap, pic_num; + + if (br->err || diff_minus1 >= max_pic_num) + return -EINVAL; + + diff = (s32)diff_minus1 + 1; + if (idc == 0) { + pic_num_no_wrap = pic_num_pred - diff; + if (pic_num_no_wrap < 0) + pic_num_no_wrap += (s32)max_pic_num; + } else { + pic_num_no_wrap = pic_num_pred + diff; + if (pic_num_no_wrap >= (s32)max_pic_num) + pic_num_no_wrap -= (s32)max_pic_num; + } + + pic_num_pred = pic_num_no_wrap; + if (pic_num_no_wrap > (s32)frame_num) + pic_num = pic_num_no_wrap - (s32)max_pic_num; + else + pic_num = pic_num_no_wrap; + + target = avd_h264_find_short_term_dpb(decode->dpb, + frame_num, + max_pic_num, + pic_num); + } else { + u32 lt_pic_num = avd_h264_br_read_ue(br); + + if (br->err) + return -EINVAL; + + target = avd_h264_find_long_term_dpb(decode->dpb, + lt_pic_num); + } + + if (target < 0) + return -EINVAL; + + for (c = num_active; c > ref_idx; c--) + list[c] = list[c - 1]; + + list[ref_idx].fields = V4L2_H264_FRAME_REF; + list[ref_idx].index = target; + ref_idx++; + + n = ref_idx; + for (c = ref_idx; c <= num_active; c++) { + if (list[c].index != target) + list[n++] = list[c]; + } + for (c = n; c <= num_active; c++) { + list[c].fields = 0; + list[c].index = 0xff; + } + } + + return -EINVAL; +} + +static int +avd_h264_parse_weight_entry(struct avd_h264_br *br, + struct v4l2_h264_weight_factors *wf, u32 i, + u32 luma_denom, u32 chroma_denom, bool chroma) +{ + if (avd_h264_br_read_bit(br)) { + s32 w = avd_h264_br_read_se(br); + s32 o = avd_h264_br_read_se(br); + + if (br->err || w < -128 || w > 127 || o < -128 || o > 127) + return -EINVAL; + wf->luma_weight[i] = w; + wf->luma_offset[i] = o; + } else { + wf->luma_weight[i] = 1 << luma_denom; + wf->luma_offset[i] = 0; + } + + if (!chroma) { + /* + * Keep monochrome chroma weights at the implicit identity + * (1 << 0) so stream_weights() does not emit chroma commands. + */ + wf->chroma_weight[i][0] = 1; + wf->chroma_weight[i][1] = 1; + wf->chroma_offset[i][0] = 0; + wf->chroma_offset[i][1] = 0; + return br->err ? -EINVAL : 0; + } + + if (!avd_h264_br_read_bit(br)) { + wf->chroma_weight[i][0] = 1 << chroma_denom; + wf->chroma_weight[i][1] = 1 << chroma_denom; + wf->chroma_offset[i][0] = 0; + wf->chroma_offset[i][1] = 0; + return br->err ? -EINVAL : 0; + } + + for (int j = 0; j < 2; j++) { + s32 w = avd_h264_br_read_se(br); + s32 o = avd_h264_br_read_se(br); + + if (br->err || w < -128 || w > 127 || o < -128 || o > 127) + return -EINVAL; + wf->chroma_weight[i][j] = w; + wf->chroma_offset[i][j] = o; + } + + return br->err ? -EINVAL : 0; +} + +/* H.264 7.3.3.2 prediction weight table. */ +static int +avd_h264_parse_pred_weight_table(struct avd_h264_br *br, + const struct v4l2_ctrl_h264_sps *sps, + const struct v4l2_ctrl_h264_slice_params *sl, + struct v4l2_ctrl_h264_pred_weights *weights) +{ + bool chroma = sps->chroma_format_idc != 0 && + !(sps->flags & V4L2_H264_SPS_FLAG_SEPARATE_COLOUR_PLANE); + u32 luma_denom, chroma_denom = 0; + int nlists = sl->slice_type == V4L2_H264_SLICE_TYPE_B ? 2 : 1; + + luma_denom = avd_h264_br_read_ue(br); + if (br->err || luma_denom > 7) + return -EINVAL; + weights->luma_log2_weight_denom = luma_denom; + + if (chroma) { + chroma_denom = avd_h264_br_read_ue(br); + if (br->err || chroma_denom > 7) + return -EINVAL; + weights->chroma_log2_weight_denom = chroma_denom; + } + + for (int l = 0; l < nlists; l++) { + struct v4l2_h264_weight_factors *wf = &weights->weight_factors[l]; + u32 count = (l == 0 ? sl->num_ref_idx_l0_active_minus1 : + sl->num_ref_idx_l1_active_minus1) + 1; + + for (u32 i = 0; i < count; i++) { + int ret = avd_h264_parse_weight_entry(br, wf, i, + luma_denom, + chroma_denom, + chroma); + if (ret) + return ret; + } + } + + return br->err ? -EINVAL : 0; +} + +/* H.264 7.3.3.3 decoded reference picture marking. */ +static int avd_h264_parse_dec_ref_pic_marking(struct avd_h264_br *br, + u8 nal_unit_type) +{ + if (nal_unit_type == AVD_H264_NAL_IDR_SLICE) { + avd_h264_br_read_bits(br, 2); + return br->err ? -EINVAL : 0; + } + + if (!avd_h264_br_read_bit(br)) + return br->err ? -EINVAL : 0; + + for (unsigned int ops = 0; ops < AVD_H264_MAX_MMCO_OPS; ops++) { + u32 op = avd_h264_br_read_ue(br); + + if (br->err) + return -EINVAL; + if (op == 0) + return 0; + if (op > 6) + return -EINVAL; + + if (op == 1 || op == 3) + avd_h264_br_read_ue(br); + if (op == 2) + avd_h264_br_read_ue(br); + if (op == 3 || op == 6) + avd_h264_br_read_ue(br); + if (op == 4) + avd_h264_br_read_ue(br); + + if (br->err) + return -EINVAL; + } + + return -EINVAL; +} + +int avd_h264_parse_slice_header(const u8 *nal, u32 nal_len, + u8 nal_ref_idc, u8 nal_unit_type, + const struct v4l2_ctrl_h264_sps *sps, + const struct v4l2_ctrl_h264_pps *pps, + const struct v4l2_ctrl_h264_decode_params *decode, + u8 num_init_refs, + const struct v4l2_h264_reference *init_p, + const struct v4l2_h264_reference *init_b0, + const struct v4l2_h264_reference *init_b1, + struct v4l2_ctrl_h264_slice_params *sl, + struct v4l2_ctrl_h264_pred_weights *weights, + u32 *slice_data_off, u8 *slice_bit_off) +{ + struct avd_h264_br br; + u32 total_mbs, slice_type, pps_id, frame_num; + s32 qp_delta; + u8 n_init; + int ret; + + memset(sl, 0, sizeof(*sl)); + memset(weights, 0, sizeof(*weights)); + for (unsigned int i = 0; i < V4L2_H264_REF_LIST_LEN; i++) { + sl->ref_pic_list0[i].index = 0xff; + sl->ref_pic_list1[i].index = 0xff; + } + + if (!nal || nal_len < 2 || !slice_data_off || !slice_bit_off) + return -EINVAL; + if (nal_unit_type != AVD_H264_NAL_SLICE && + nal_unit_type != AVD_H264_NAL_IDR_SLICE) + return -EINVAL; + if (!(sps->flags & V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY)) + return -EINVAL; + if (sps->log2_max_frame_num_minus4 > 12 || sps->pic_order_cnt_type > 2) + return -EINVAL; + if (sps->pic_order_cnt_type == 0 && + sps->log2_max_pic_order_cnt_lsb_minus4 > 12) + return -EINVAL; + if (pps->num_slice_groups_minus1 != 0) + return -EINVAL; + + avd_h264_br_init(&br, nal, nal_len, 1); + + sl->first_mb_in_slice = avd_h264_br_read_ue(&br); + total_mbs = (u32)(sps->pic_width_in_mbs_minus1 + 1) * + (u32)(sps->pic_height_in_map_units_minus1 + 1); + if (br.err || sl->first_mb_in_slice >= total_mbs) + return -EINVAL; + + slice_type = avd_h264_br_read_ue(&br); + if (br.err || slice_type > 9) + return -EINVAL; + slice_type %= 5; + if (slice_type != V4L2_H264_SLICE_TYPE_P && + slice_type != V4L2_H264_SLICE_TYPE_B && + slice_type != V4L2_H264_SLICE_TYPE_I) + return -EINVAL; + if (nal_unit_type == AVD_H264_NAL_IDR_SLICE && + slice_type != V4L2_H264_SLICE_TYPE_I) + return -EINVAL; + sl->slice_type = slice_type; + + pps_id = avd_h264_br_read_ue(&br); + if (br.err || pps_id > 255) + return -EINVAL; + + if (sps->flags & V4L2_H264_SPS_FLAG_SEPARATE_COLOUR_PLANE) + sl->colour_plane_id = avd_h264_br_read_bits(&br, 2); + + frame_num = avd_h264_br_read_bits(&br, sps->log2_max_frame_num_minus4 + 4); + + if (nal_unit_type == AVD_H264_NAL_IDR_SLICE) { + u32 idr_pic_id = avd_h264_br_read_ue(&br); + + if (br.err || idr_pic_id > 65535) + return -EINVAL; + } + + if (sps->pic_order_cnt_type == 0) { + avd_h264_br_read_bits(&br, + sps->log2_max_pic_order_cnt_lsb_minus4 + 4); + if (pps->flags & + V4L2_H264_PPS_FLAG_BOTTOM_FIELD_PIC_ORDER_IN_FRAME_PRESENT) + avd_h264_br_read_se(&br); + } else if (sps->pic_order_cnt_type == 1 && + !(sps->flags & V4L2_H264_SPS_FLAG_DELTA_PIC_ORDER_ALWAYS_ZERO)) { + avd_h264_br_read_se(&br); + if (pps->flags & + V4L2_H264_PPS_FLAG_BOTTOM_FIELD_PIC_ORDER_IN_FRAME_PRESENT) + avd_h264_br_read_se(&br); + } + + if (pps->flags & V4L2_H264_PPS_FLAG_REDUNDANT_PIC_CNT_PRESENT) { + u32 redundant_pic_cnt = avd_h264_br_read_ue(&br); + + if (br.err || redundant_pic_cnt > 0) + return -EINVAL; + sl->redundant_pic_cnt = redundant_pic_cnt; + } + + if (slice_type == V4L2_H264_SLICE_TYPE_B) { + if (avd_h264_br_read_bit(&br)) + sl->flags |= V4L2_H264_SLICE_FLAG_DIRECT_SPATIAL_MV_PRED; + } + + if (slice_type == V4L2_H264_SLICE_TYPE_P || + slice_type == V4L2_H264_SLICE_TYPE_B) { + u32 num_l0 = pps->num_ref_idx_l0_default_active_minus1; + u32 num_l1 = pps->num_ref_idx_l1_default_active_minus1; + + if (avd_h264_br_read_bit(&br)) { + num_l0 = avd_h264_br_read_ue(&br); + if (slice_type == V4L2_H264_SLICE_TYPE_B) + num_l1 = avd_h264_br_read_ue(&br); + } + if (br.err || num_l0 > 15) + return -EINVAL; + sl->num_ref_idx_l0_active_minus1 = num_l0; + + if (slice_type == V4L2_H264_SLICE_TYPE_B) { + if (num_l1 > 15) + return -EINVAL; + sl->num_ref_idx_l1_active_minus1 = num_l1; + } + } + + if (br.err) + return -EINVAL; + + n_init = min_t(u8, num_init_refs, V4L2_H264_REF_LIST_LEN); + if (slice_type == V4L2_H264_SLICE_TYPE_P) { + if (init_p && n_init) + memcpy(sl->ref_pic_list0, init_p, + n_init * sizeof(sl->ref_pic_list0[0])); + ret = avd_h264_parse_ref_list_mod(&br, sps, decode, frame_num, + sl->ref_pic_list0, + sl->num_ref_idx_l0_active_minus1); + if (ret) + return ret; + } else if (slice_type == V4L2_H264_SLICE_TYPE_B) { + if (init_b0 && n_init) + memcpy(sl->ref_pic_list0, init_b0, + n_init * sizeof(sl->ref_pic_list0[0])); + if (init_b1 && n_init) + memcpy(sl->ref_pic_list1, init_b1, + n_init * sizeof(sl->ref_pic_list1[0])); + ret = avd_h264_parse_ref_list_mod(&br, sps, decode, frame_num, + sl->ref_pic_list0, + sl->num_ref_idx_l0_active_minus1); + if (ret) + return ret; + ret = avd_h264_parse_ref_list_mod(&br, sps, decode, frame_num, + sl->ref_pic_list1, + sl->num_ref_idx_l1_active_minus1); + if (ret) + return ret; + } + + if (V4L2_H264_CTRL_PRED_WEIGHTS_REQUIRED(pps, sl)) { + ret = avd_h264_parse_pred_weight_table(&br, sps, sl, weights); + if (ret) + return ret; + } + + if (nal_ref_idc != 0) { + ret = avd_h264_parse_dec_ref_pic_marking(&br, nal_unit_type); + if (ret) + return ret; + } + + if ((pps->flags & V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE) && + slice_type != V4L2_H264_SLICE_TYPE_I) { + u32 cabac_init_idc = avd_h264_br_read_ue(&br); + + if (br.err || cabac_init_idc > 2) + return -EINVAL; + sl->cabac_init_idc = cabac_init_idc; + } + + qp_delta = avd_h264_br_read_se(&br); + if (br.err || qp_delta < S8_MIN || qp_delta > S8_MAX) + return -EINVAL; + sl->slice_qp_delta = qp_delta; + + if (pps->flags & V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT) { + u32 idc = avd_h264_br_read_ue(&br); + + if (br.err || idc > 2) + return -EINVAL; + sl->disable_deblocking_filter_idc = idc; + if (idc != 1) { + s32 alpha = avd_h264_br_read_se(&br); + s32 beta = avd_h264_br_read_se(&br); + + if (br.err || alpha < -6 || alpha > 6 || + beta < -6 || beta > 6) + return -EINVAL; + sl->slice_alpha_c0_offset_div2 = alpha; + sl->slice_beta_offset_div2 = beta; + } + } + + if (br.err) + return -EINVAL; + + sl->header_bit_size = 8 + br.rbsp_bits; + + if (pps->flags & V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE) { + if (br.bit) { + br.pos++; + br.bit = 0; + } + } + + avd_h264_br_skip_epb(&br); + if (br.pos >= nal_len) + return -EINVAL; + + *slice_data_off = br.pos; + *slice_bit_off = br.bit; + return 0; +} diff --git a/drivers/media/platform/apple/avd/avd-h264-parse.h b/drivers/media/platform/apple/avd/avd-h264-parse.h new file mode 100644 index 00000000000000..d8e507e73371eb --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-h264-parse.h @@ -0,0 +1,55 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * H.264 Annex-B NALU scanner and slice header parser for Apple AVD. + */ +#ifndef AVD_H264_PARSE_H +#define AVD_H264_PARSE_H + +#include +#include + +struct avd_h264_nalu { + u32 off; + u32 len; + u8 nal_ref_idc; + u8 nal_unit_type; +}; + +struct avd_h264_br { + const u8 *data; + u32 len; + u32 pos; + u32 rbsp_bits; + u8 bit; + u8 zeros; + bool err; +}; + +bool avd_h264_mode_supported(s32 decode_mode, s32 start_code); +int avd_h264_next_nalu(const u8 *buf, u32 len, u32 *cursor, + struct avd_h264_nalu *nalu); +int avd_h264_next_frame_nalu(const u8 *buf, u32 len, s32 start_code, + u32 *cursor, struct avd_h264_nalu *nalu); + +int avd_h264_parse_slice_header(const u8 *nal, u32 nal_len, + u8 nal_ref_idc, u8 nal_unit_type, + const struct v4l2_ctrl_h264_sps *sps, + const struct v4l2_ctrl_h264_pps *pps, + const struct v4l2_ctrl_h264_decode_params *decode, + u8 num_init_refs, + const struct v4l2_h264_reference *init_p, + const struct v4l2_h264_reference *init_b0, + const struct v4l2_h264_reference *init_b1, + struct v4l2_ctrl_h264_slice_params *sl, + struct v4l2_ctrl_h264_pred_weights *weights, + u32 *slice_data_off, u8 *slice_bit_off); + +#if IS_ENABLED(CONFIG_KUNIT) +void avd_h264_br_init(struct avd_h264_br *br, const u8 *data, u32 len, u32 pos); +u32 avd_h264_br_read_bits(struct avd_h264_br *br, unsigned int n); +u32 avd_h264_br_read_ue(struct avd_h264_br *br); +s32 avd_h264_br_read_se(struct avd_h264_br *br); +void avd_h264_br_skip_epb(struct avd_h264_br *br); +#endif + +#endif /* AVD_H264_PARSE_H */ diff --git a/drivers/media/platform/apple/avd/avd-h264-test.c b/drivers/media/platform/apple/avd/avd-h264-test.c index 54d2114f45e98d..3c8888f06bbbfd 100644 --- a/drivers/media/platform/apple/avd/avd-h264-test.c +++ b/drivers/media/platform/apple/avd/avd-h264-test.c @@ -1,12 +1,16 @@ // SPDX-License-Identifier: GPL-2.0 /* - * KUnit tests for the H.264 slice checks of the Apple video decoder. + * KUnit tests for the H.264 slice checks and Annex-B parser of the Apple + * video decoder. */ #include #include +#include +#include #include "avd.h" +#include "avd-h264-parse.h" struct avd_slice_data_case { const char *desc; @@ -107,6 +111,184 @@ static void avd_slice_fits_test(struct kunit *test) c->fits); } +/* The H.264 OUTPUT frame size limits in avd-v4l2.c */ +static const struct v4l2_frmsize_stepwise avd_test_h264_frmsize = { + .min_width = 64, .max_width = 4096, .step_width = 64, + .min_height = 64, .max_height = 4096, .step_height = 16, +}; + +struct avd_sps_size_case { + const char *desc; + /* OUTPUT format as the client asks for it */ + u32 width; + u32 height; + u16 width_mbs; + u16 height_map_units; + int ret; +}; + +static const struct avd_sps_size_case avd_sps_size_cases[] = { + { "1080p, OUTPUT 1920x1080", 1920, 1080, 120, 68, 0 }, + { "1080p, OUTPUT 1920x1088", 1920, 1088, 120, 68, 0 }, + { "720p", 1280, 720, 80, 45, 0 }, + { "720p, one row over", 1280, 720, 80, 46, -EINVAL }, + { "720p, one column over", 1280, 720, 81, 45, -EINVAL }, + { "picture smaller than the format", 1920, 1088, 40, 30, 0 }, + { "64x64, matching picture", 64, 64, 4, 4, 0 }, + { "64x64, 4096x4096 picture", 64, 64, 256, 256, -EINVAL }, + { "64x64, largest SPS size", 64, 64, U16_MAX, U16_MAX, -EINVAL }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_sps_size, avd_sps_size_cases, desc); + +static void avd_sps_size_test(struct kunit *test) +{ + const struct avd_sps_size_case *c = test->param_value; + struct v4l2_ctrl_h264_sps sps = { + .chroma_format_idc = 1, + .pic_width_in_mbs_minus1 = c->width_mbs - 1, + .pic_height_in_map_units_minus1 = c->height_map_units - 1, + .flags = V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY, + }; + struct avd_ctx *ctx; + u32 w = c->width, h = c->height; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + /* As S_FMT(OUTPUT) does */ + v4l2_apply_frmsize_constraints(&w, &h, &avd_test_h264_frmsize); + ctx->coded_fmt.fmt.pix_mp.width = w; + ctx->coded_fmt.fmt.pix_mp.height = h; + + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), c->ret); +} + +/* + * Pre-streaming format negotiation (e.g. Chromium V4L2VideoDecoder::SetExtCtrlsInit) + * supplies chroma_format_idc and bit depth with flags == 0 and zeroed dimensions + * before the first frame request carries the parsed SPS. Format validation accepts + * those controls while full SPS validation still rejects interlaced streams. + */ +static void avd_sps_fmt_init_test(struct kunit *test) +{ + struct v4l2_ctrl_h264_sps sps = { + .chroma_format_idc = 1, + }; + struct avd_dev *dev; + struct avd_ctx *ctx; + + dev = kunit_kzalloc(test, sizeof(*dev), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dev); + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->dev = dev; + ctx->coded_fmt.fmt.pix_mp.width = 1280; + ctx->coded_fmt.fmt.pix_mp.height = 720; + + /* 8-bit and 10-bit 4:2:0 pre-streaming init controls */ + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), 0); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, false), 0); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, true), -EINVAL); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), -EINVAL); + + sps.bit_depth_luma_minus8 = 2; + sps.bit_depth_chroma_minus8 = 2; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), 0); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, false), 0); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, true), -EINVAL); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), -EINVAL); + + /* Populated interlaced SPS must still be rejected pre-streaming */ + sps = (struct v4l2_ctrl_h264_sps) { + .chroma_format_idc = 1, + .pic_width_in_mbs_minus1 = 79, + .pic_height_in_map_units_minus1 = 22, + }; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, false), -EINVAL); + sps.pic_width_in_mbs_minus1 = 0; + sps.pic_height_in_map_units_minus1 = 0; + sps.flags = V4L2_H264_SPS_FLAG_MB_ADAPTIVE_FRAME_FIELD; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, false), -EINVAL); + + /* Unsupported formats remain rejected pre-streaming */ + sps = (struct v4l2_ctrl_h264_sps) { + .chroma_format_idc = 3, + .bit_depth_luma_minus8 = 2, + .bit_depth_chroma_minus8 = 2, + }; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), -EINVAL); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, false), -EINVAL); + sps.chroma_format_idc = 2; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), -EINVAL); + sps.chroma_format_idc = 1; + sps.bit_depth_luma_minus8 = 4; + sps.bit_depth_chroma_minus8 = 4; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), -EINVAL); + sps.bit_depth_luma_minus8 = 2; + sps.bit_depth_chroma_minus8 = 0; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), -EINVAL); +} + +static void avd_sps_range_test(struct kunit *test) +{ + struct v4l2_ctrl_h264_sps sps = { + .chroma_format_idc = 1, + .pic_width_in_mbs_minus1 = 3, + .pic_height_in_map_units_minus1 = 3, + .flags = V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY, + }; + struct avd_ctx *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->coded_fmt.fmt.pix_mp.width = 64; + ctx->coded_fmt.fmt.pix_mp.height = 64; + + sps.log2_max_frame_num_minus4 = 12; + sps.pic_order_cnt_type = 0; + sps.log2_max_pic_order_cnt_lsb_minus4 = 12; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), 0); + + sps.log2_max_frame_num_minus4 = 13; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), -EINVAL); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), 0); + + sps.log2_max_frame_num_minus4 = 0; + sps.pic_order_cnt_type = 3; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), -EINVAL); + + sps.pic_order_cnt_type = 0; + sps.log2_max_pic_order_cnt_lsb_minus4 = 13; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), -EINVAL); + + /* log2_max_pic_order_cnt_lsb_minus4 is ignored when poc_type != 0 */ + sps.pic_order_cnt_type = 1; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), 0); + sps.pic_order_cnt_type = 2; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), 0); +} + +static void avd_start_slices_test(struct kunit *test) +{ + struct v4l2_ctrl_h264_sps sps = { + .flags = V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY, + }; + + /* One slice per row */ + sps.pic_width_in_mbs_minus1 = 119; + sps.pic_height_in_map_units_minus1 = 67; + KUNIT_EXPECT_EQ(test, avd_h264_start_slices(&sps), 68); + + /* No more rows than macroblocks, and never more than the table */ + sps.pic_width_in_mbs_minus1 = 0; + sps.pic_height_in_map_units_minus1 = U16_MAX; + KUNIT_EXPECT_LE(test, avd_h264_start_slices(&sps), AVD_TEST_MAX_SLICES); + sps.pic_width_in_mbs_minus1 = U16_MAX; + KUNIT_EXPECT_LE(test, avd_h264_start_slices(&sps), AVD_TEST_MAX_SLICES); + sps.flags = 0; + KUNIT_EXPECT_LE(test, avd_h264_start_slices(&sps), AVD_TEST_MAX_SLICES); +} + static void avd_scaling_flat_test(struct kunit *test) { struct v4l2_ctrl_h264_pps pps = {}; @@ -130,10 +312,1247 @@ static void avd_scaling_flat_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, avd_h264_scaling_is_flat(&pps, m)); } +/* Simple bit writer for synthesizing H.264 slice header bitstreams in tests. */ +struct avd_test_bw { + u8 buf[256]; + u32 pos; + u8 bit; + u8 zeros; + bool epb; +}; + +static void bw_init(struct avd_test_bw *bw, u8 nal_hdr, bool epb) +{ + memset(bw, 0, sizeof(*bw)); + bw->buf[0] = nal_hdr; + bw->pos = 1; + bw->epb = epb; +} + +static void bw_put_byte(struct avd_test_bw *bw, u8 b) +{ + if (bw->epb && bw->zeros >= 2 && b <= 0x03) { + bw->buf[bw->pos++] = 0x03; + bw->zeros = 0; + } + bw->buf[bw->pos++] = b; + bw->zeros = b == 0x00 ? min_t(u8, bw->zeros + 1, 2) : 0; +} + +static void bw_put_bit(struct avd_test_bw *bw, u32 v) +{ + if (v & 1) + bw->buf[bw->pos] |= 1U << (7 - bw->bit); + bw->bit++; + if (bw->bit == 8) { + u8 finished = bw->buf[bw->pos]; + + bw->buf[bw->pos] = 0; + bw->bit = 0; + bw_put_byte(bw, finished); + } +} + +static void bw_put_bits(struct avd_test_bw *bw, u32 v, unsigned int n) +{ + while (n--) + bw_put_bit(bw, (v >> n) & 1); +} + +static void bw_put_ue(struct avd_test_bw *bw, u32 v) +{ + u32 code = v + 1; + unsigned int bits = fls(code); + unsigned int zeros = bits - 1; + + bw_put_bits(bw, 0, zeros); + bw_put_bits(bw, code, bits); +} + +static void bw_put_se(struct avd_test_bw *bw, s32 v) +{ + u32 code = v <= 0 ? (u32)(-2 * v) : (u32)(2 * v - 1); + + bw_put_ue(bw, code); +} + +static u32 bw_finish(struct avd_test_bw *bw, bool cabac, u8 tail_byte) +{ + if (cabac) { + while (bw->bit != 0) + bw_put_bit(bw, 1); + } else if (bw->bit != 0) { + u8 finished = bw->buf[bw->pos] | ((1U << (8 - bw->bit)) - 1); + + bw->buf[bw->pos] = 0; + bw->bit = 0; + bw_put_byte(bw, finished); + } + bw_put_byte(bw, tail_byte); + return bw->pos; +} + +static void avd_annexb_scanner_test(struct kunit *test) +{ + /* AUD(9), SPS(7), PPS(8), SEI(6), EOS(10/11), Filler(12), then 2 slices */ + static const u8 multi[] = { + 0x00, 0x00, 0x00, 0x00, 0x01, 0x09, 0x10, + 0x00, 0x00, 0x00, 0x01, 0x67, 0x4d, 0x40, + 0x00, 0x00, 0x01, 0x68, 0xee, + 0x00, 0x00, 0x01, 0x06, 0x05, 0x80, + 0x00, 0x00, 0x01, 0x0a, + 0x00, 0x00, 0x01, 0x0b, + 0x00, 0x00, 0x01, 0x0c, 0xff, 0x80, + 0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x01, 0x41, 0x9a, 0x20, 0x00, 0x00, + }; + struct avd_h264_nalu nalu = {}; + u32 cursor = 0; + + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(multi, sizeof(multi), + &cursor, &nalu), 1); + KUNIT_EXPECT_EQ(test, nalu.nal_unit_type, 5); + KUNIT_EXPECT_EQ(test, nalu.nal_ref_idc, 3); + KUNIT_EXPECT_EQ(test, nalu.len, 3); + KUNIT_EXPECT_EQ(test, multi[nalu.off], 0x65); + KUNIT_EXPECT_EQ(test, multi[nalu.off + nalu.len - 1], 0x84); + + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(multi, sizeof(multi), + &cursor, &nalu), 1); + KUNIT_EXPECT_EQ(test, nalu.nal_unit_type, 1); + KUNIT_EXPECT_EQ(test, nalu.nal_ref_idc, 2); + KUNIT_EXPECT_EQ(test, nalu.len, 3); + KUNIT_EXPECT_EQ(test, multi[nalu.off], 0x41); + KUNIT_EXPECT_EQ(test, multi[nalu.off + nalu.len - 1], 0x20); + + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(multi, sizeof(multi), + &cursor, &nalu), 0); + + /* Rejected cases: forbidden_zero_bit, DPA/B/C (2,3,4), SVC/MVC (14,20) */ + static const u8 bad_hdrs[] = { 0xe5, 0x89, 0x22, 0x23, 0x24, 0x2e, 0x34, 0x00 }; + + for (unsigned int i = 0; i < ARRAY_SIZE(bad_hdrs); i++) { + u8 buf[] = { 0x00, 0x00, 0x01, bad_hdrs[i], 0x80 }; + + cursor = 0; + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(buf, sizeof(buf), + &cursor, &nalu), -EINVAL); + } + + /* Missing start code, truncated start code, empty NALU between start codes */ + { + static const u8 no_sc[] = { 0x65, 0x88, 0x84 }; + static const u8 trunc_sc[] = { 0x00, 0x00, 0x01 }; + static const u8 empty_nal[] = { 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x65, 0x88 }; + static const u8 only_non_vcl[] = { 0x00, 0x00, 0x00, 0x01, 0x09, 0x10 }; + + cursor = 0; + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(no_sc, sizeof(no_sc), + &cursor, &nalu), -EINVAL); + cursor = 0; + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(trunc_sc, sizeof(trunc_sc), + &cursor, &nalu), -EINVAL); + cursor = 0; + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(empty_nal, sizeof(empty_nal), + &cursor, &nalu), -EINVAL); + cursor = 0; + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(only_non_vcl, sizeof(only_non_vcl), + &cursor, &nalu), 0); + } +} + +static void avd_bitreader_epb_test(struct kunit *test) +{ + /* + * EBSP: 00 00 03 00 00 03 03 00 00 03 01 + * RBSP: 00 00 00 00 03 00 00 01 + */ + static const u8 ebsp[] = { + 0x65, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x03, 0x01, + }; + struct avd_h264_br br; + + avd_h264_br_init(&br, ebsp, sizeof(ebsp), 1); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_bits(&br, 16), 0x0000); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_bits(&br, 16), 0x0000); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_bits(&br, 8), 0x03); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_bits(&br, 24), 0x000001); + KUNIT_EXPECT_FALSE(test, br.err); + /* Reading one more bit triggers truncation error. */ + avd_h264_br_read_bits(&br, 1); + KUNIT_EXPECT_TRUE(test, br.err); + + /* Exp-Golomb ue(v) and se(v) round-trip */ + { + struct avd_test_bw bw; + static const s32 se_vals[] = { 0, 1, -1, 2, -2, 127, -128 }; + u32 len; + + bw_init(&bw, 0x65, true); + bw_put_ue(&bw, 0); + bw_put_ue(&bw, 1); + bw_put_ue(&bw, 2); + bw_put_ue(&bw, 15); + bw_put_ue(&bw, 255); + for (unsigned int i = 0; i < ARRAY_SIZE(se_vals); i++) + bw_put_se(&bw, se_vals[i]); + len = bw_finish(&bw, true, 0xaa); + + avd_h264_br_init(&br, bw.buf, len, 1); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_ue(&br), 0); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_ue(&br), 1); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_ue(&br), 2); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_ue(&br), 15); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_ue(&br), 255); + for (unsigned int i = 0; i < ARRAY_SIZE(se_vals); i++) + KUNIT_EXPECT_EQ(test, avd_h264_br_read_se(&br), se_vals[i]); + KUNIT_EXPECT_FALSE(test, br.err); + } + + /* >= 32 leading zeros in ue(v) must error */ + { + static const u8 bad_ue[] = { + 0x65, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x80, + }; + + avd_h264_br_init(&br, bad_ue, sizeof(bad_ue), 1); + avd_h264_br_read_ue(&br); + KUNIT_EXPECT_TRUE(test, br.err); + } +} + +struct avd_parse_test_ctx { + struct v4l2_ctrl_h264_sps sps; + struct v4l2_ctrl_h264_pps pps; + struct v4l2_ctrl_h264_decode_params decode; + struct v4l2_ctrl_h264_slice_params sl; + struct v4l2_ctrl_h264_pred_weights weights; + struct v4l2_h264_reflist_builder builder; + struct v4l2_h264_reference init_p[V4L2_H264_REF_LIST_LEN]; + struct v4l2_h264_reference init_b0[V4L2_H264_REF_LIST_LEN]; + struct v4l2_h264_reference init_b1[V4L2_H264_REF_LIST_LEN]; + struct avd_test_bw bw; +}; + +static struct avd_parse_test_ctx *avd_parse_test_alloc(struct kunit *test) +{ + struct avd_parse_test_ctx *t; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t); + t->sps.pic_width_in_mbs_minus1 = 3; + t->sps.pic_height_in_map_units_minus1 = 3; + t->sps.flags = V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY; + return t; +} + +static void avd_slice_hdr_epb_boundary_test(struct kunit *test) +{ + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + struct avd_h264_br br; + u32 data_off, nal_len; + u8 bit_off; + + t->sps.log2_max_frame_num_minus4 = 12; + t->sps.pic_order_cnt_type = 0; + t->sps.log2_max_pic_order_cnt_lsb_minus4 = 12; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE; + + /* Direct byte-boundary EPB skip test */ + { + static const u8 boundary_epb[] = { 0x65, 0x00, 0x00, 0x03, 0x01 }; + static const u8 trunc_epb[] = { 0x65, 0x00, 0x00, 0x03 }; + + avd_h264_br_init(&br, boundary_epb, sizeof(boundary_epb), 1); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_bits(&br, 16), 0); + KUNIT_EXPECT_EQ(test, br.pos, 3); + KUNIT_EXPECT_EQ(test, br.bit, 0); + avd_h264_br_skip_epb(&br); + KUNIT_EXPECT_EQ(test, br.pos, 4); + KUNIT_EXPECT_EQ(test, br.data[br.pos], 0x01); + + avd_h264_br_init(&br, trunc_epb, sizeof(trunc_epb), 1); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_bits(&br, 16), 0); + avd_h264_br_skip_epb(&br); + KUNIT_EXPECT_EQ(test, br.pos, sizeof(trunc_epb)); + } + + /* Slice header containing EPBs in 16-bit frame_num & poc_lsb (CABAC) */ + bw_init(&t->bw, 0x65, true); + bw_put_ue(&t->bw, 0); /* first_mb_in_slice */ + bw_put_ue(&t->bw, 2); /* I slice */ + bw_put_ue(&t->bw, 0); /* pps_id */ + bw_put_bits(&t->bw, 0, 16); /* frame_num = 0 -> creates 00 00 03 */ + bw_put_ue(&t->bw, 0); /* idr_pic_id */ + bw_put_bits(&t->bw, 0, 16); /* pic_order_cnt_lsb = 0 -> creates 00 00 03 */ + bw_put_bits(&t->bw, 0, 2); /* dec_ref_pic_marking */ + bw_put_se(&t->bw, -3); /* slice_qp_delta */ + nal_len = bw_finish(&t->bw, true, 0xcd); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 3, 5, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_I); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, -3); + KUNIT_EXPECT_EQ(test, bit_off, 0); + KUNIT_EXPECT_EQ(test, data_off, nal_len - 1); + KUNIT_EXPECT_EQ(test, t->bw.buf[data_off], 0xcd); + + /* Same header with CAVLC preserves non-zero bit_off */ + t->pps.flags = 0; + bw_init(&t->bw, 0x65, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 2); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 0, 16); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 0, 16); + bw_put_bits(&t->bw, 0, 2); + bw_put_se(&t->bw, 0); /* 1+3+1+16+1+16+2+1 = 41 RBSP bits (bit_off=1) */ + nal_len = bw_finish(&t->bw, false, 0xef); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 3, 5, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 8 + 41); + KUNIT_EXPECT_EQ(test, bit_off, 1); + KUNIT_EXPECT_LT(test, data_off, nal_len); + + /* Header ending right at nal_len with no slice_data must fail */ + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, data_off, 3, 5, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); +} + +static void avd_slice_hdr_fields_test(struct kunit *test) +{ + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + u32 data_off, nal_len; + u8 bit_off; + + t->sps.pic_order_cnt_type = 1; + t->pps.num_ref_idx_l0_default_active_minus1 = 1; + t->pps.num_ref_idx_l1_default_active_minus1 = 0; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE | + V4L2_H264_PPS_FLAG_BOTTOM_FIELD_PIC_ORDER_IN_FRAME_PRESENT | + V4L2_H264_PPS_FLAG_REDUNDANT_PIC_CNT_PRESENT | + V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT; + + t->init_b0[0] = (struct v4l2_h264_reference){ + .fields = V4L2_H264_FRAME_REF, .index = 2, + }; + t->init_b0[1] = (struct v4l2_h264_reference){ + .fields = V4L2_H264_FRAME_REF, .index = 5, + }; + memcpy(t->init_b1, t->init_b0, sizeof(t->init_b1)); + + /* Pre-fill output structs with garbage to verify unconditional zeroing. */ + memset(&t->sl, 0x5a, sizeof(t->sl)); + memset(&t->weights, 0x5a, sizeof(t->weights)); + + /* Non-IDR B slice (type 6 -> normalized to B=1), POC type 1 + bottom, CABAC */ + bw_init(&t->bw, 0x21, true); + bw_put_ue(&t->bw, 4); /* first_mb_in_slice */ + bw_put_ue(&t->bw, 6); /* slice_type 6 -> B (1) */ + bw_put_ue(&t->bw, 12); /* pps_id */ + bw_put_bits(&t->bw, 3, 4); /* frame_num */ + bw_put_se(&t->bw, -4); /* delta_pic_order_cnt[0] */ + bw_put_se(&t->bw, 2); /* delta_pic_order_cnt[1] */ + bw_put_ue(&t->bw, 0); /* redundant_pic_cnt = 0 */ + bw_put_bit(&t->bw, 1); /* direct_spatial_mv_pred_flag */ + bw_put_bit(&t->bw, 1); /* num_ref_idx_active_override_flag */ + bw_put_ue(&t->bw, 1); /* num_ref_idx_l0_active_minus1 */ + bw_put_ue(&t->bw, 0); /* num_ref_idx_l1_active_minus1 */ + bw_put_bit(&t->bw, 0); /* ref_pic_list_modification_flag_l0 */ + bw_put_bit(&t->bw, 0); /* ref_pic_list_modification_flag_l1 */ + bw_put_bit(&t->bw, 0); /* adaptive_ref_pic_marking_mode_flag */ + bw_put_ue(&t->bw, 2); /* cabac_init_idc */ + bw_put_se(&t->bw, -5); /* slice_qp_delta */ + bw_put_ue(&t->bw, 2); /* disable_deblocking_filter_idc */ + bw_put_se(&t->bw, -6); /* slice_alpha_c0_offset_div2 */ + bw_put_se(&t->bw, 6); /* slice_beta_offset_div2 */ + nal_len = bw_finish(&t->bw, true, 0xaa); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 1, 1, + &t->sps, &t->pps, &t->decode, + 2, t->init_p, t->init_b0, t->init_b1, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 4); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_B); + KUNIT_EXPECT_EQ(test, t->sl.flags, V4L2_H264_SLICE_FLAG_DIRECT_SPATIAL_MV_PRED); + KUNIT_EXPECT_EQ(test, t->sl.num_ref_idx_l0_active_minus1, 1); + KUNIT_EXPECT_EQ(test, t->sl.num_ref_idx_l1_active_minus1, 0); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[0].index, 2); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[1].index, 5); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[2].index, 0xff); + KUNIT_EXPECT_EQ(test, t->sl.cabac_init_idc, 2); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, -5); + KUNIT_EXPECT_EQ(test, t->sl.disable_deblocking_filter_idc, 2); + KUNIT_EXPECT_EQ(test, t->sl.slice_alpha_c0_offset_div2, -6); + KUNIT_EXPECT_EQ(test, t->sl.slice_beta_offset_div2, 6); + KUNIT_EXPECT_EQ(test, t->weights.luma_log2_weight_denom, 0); + KUNIT_EXPECT_EQ(test, data_off, nal_len - 1); + KUNIT_EXPECT_EQ(test, bit_off, 0); + + /* Reject SP/SI slice types (3, 4, 8, 9) and > 9 */ + { + static const u32 bad_types[] = { 3, 4, 8, 9, 10 }; + + for (unsigned int i = 0; i < ARRAY_SIZE(bad_types); i++) { + bw_init(&t->bw, 0x21, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, bad_types[i]); + bw_put_ue(&t->bw, 0); + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 1, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + } + } + + /* Reject redundant_pic_cnt > 0 */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 2); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 0, 4); + bw_put_se(&t->bw, 0); + bw_put_se(&t->bw, 0); + bw_put_ue(&t->bw, 1); /* redundant_pic_cnt > 0 */ + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + + /* Reject out-of-range cabac_init_idc (3), num_ref_idx (16), alpha (-7) */ + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE | + V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT; + t->sps.pic_order_cnt_type = 2; + + /* num_ref_idx_l0_active_minus1 = 16 -> reject */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); /* P */ + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 1); /* override */ + bw_put_ue(&t->bw, 16); /* > 15 */ + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + + /* cabac_init_idc = 3 -> reject */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); /* P */ + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 0); /* no override */ + bw_put_bit(&t->bw, 0); /* no reflist mod */ + bw_put_ue(&t->bw, 3); /* invalid cabac_init_idc */ + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + + /* alpha = -7 -> reject */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 2); /* I */ + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_se(&t->bw, 0); + bw_put_ue(&t->bw, 0); /* deblock idc = 0 */ + bw_put_se(&t->bw, -7); /* out of [-6, 6] */ + bw_put_se(&t->bw, 0); + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); +} + +static void avd_slice_hdr_ref_mod_test(struct kunit *test) +{ + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + u32 data_off, nal_len; + u8 bit_off; + + t->sps.log2_max_frame_num_minus4 = 0; /* MaxPicNum = 16 */ + t->sps.pic_order_cnt_type = 2; + t->pps.num_ref_idx_l0_default_active_minus1 = 3; + t->pps.num_ref_idx_l1_default_active_minus1 = 1; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE; + t->decode.frame_num = 1; + t->decode.top_field_order_cnt = 10; + t->decode.bottom_field_order_cnt = 10; + + /* + * DPB with short-term wraparound (frame_num=15 -> PicNum=-1, 14 -> -2, + * 0 -> 0) and a long-term reference (long_term_frame_idx=3) at slot 6. + * Current frame_num = 1. + */ + t->decode.dpb[1] = (struct v4l2_h264_dpb_entry){ + .frame_num = 0, .top_field_order_cnt = 8, .bottom_field_order_cnt = 8, + .flags = V4L2_H264_DPB_ENTRY_FLAG_VALID | V4L2_H264_DPB_ENTRY_FLAG_ACTIVE, + }; + t->decode.dpb[3] = (struct v4l2_h264_dpb_entry){ + .frame_num = 15, .top_field_order_cnt = 6, .bottom_field_order_cnt = 6, + .flags = V4L2_H264_DPB_ENTRY_FLAG_VALID | V4L2_H264_DPB_ENTRY_FLAG_ACTIVE, + }; + t->decode.dpb[4] = (struct v4l2_h264_dpb_entry){ + .frame_num = 14, .top_field_order_cnt = 12, .bottom_field_order_cnt = 12, + .flags = V4L2_H264_DPB_ENTRY_FLAG_VALID | V4L2_H264_DPB_ENTRY_FLAG_ACTIVE, + }; + t->decode.dpb[6] = (struct v4l2_h264_dpb_entry){ + .frame_num = 3, .top_field_order_cnt = 2, .bottom_field_order_cnt = 2, + .flags = V4L2_H264_DPB_ENTRY_FLAG_VALID | V4L2_H264_DPB_ENTRY_FLAG_ACTIVE | + V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM, + }; + /* Inactive entry that must NOT be matched */ + t->decode.dpb[9] = (struct v4l2_h264_dpb_entry){ + .frame_num = 13, + .flags = V4L2_H264_DPB_ENTRY_FLAG_VALID, + }; + + v4l2_h264_init_reflist_builder(&t->builder, &t->decode, &t->sps, + t->decode.dpb); + v4l2_h264_build_p_ref_list(&t->builder, t->init_p); + v4l2_h264_build_b_ref_lists(&t->builder, t->init_b0, t->init_b1); + /* Initial P list: short-term descending (1, 3, 4), then long-term (6). */ + KUNIT_ASSERT_EQ(test, t->builder.num_valid, 4); + KUNIT_ASSERT_EQ(test, t->init_p[0].index, 1); + KUNIT_ASSERT_EQ(test, t->init_p[1].index, 3); + KUNIT_ASSERT_EQ(test, t->init_p[2].index, 4); + KUNIT_ASSERT_EQ(test, t->init_p[3].index, 6); + + /* + * Modify P L0: + * idc=2, lt=3 -> slot 6 at index 0 + * idc=0, diff_minus1=2 -> pred=1 - 3 = -2 -> wrap +16 = 14 -> slot 4 at index 1 + * idc=1, diff_minus1=0 -> pred=14 + 1 = 15 -> slot 3 at index 2 + * idc=3 -> end + * Expected final L0: [6, 4, 3, 1]. + */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); /* first_mb */ + bw_put_ue(&t->bw, 0); /* P */ + bw_put_ue(&t->bw, 0); /* pps_id */ + bw_put_bits(&t->bw, 1, 4); /* frame_num = 1 */ + bw_put_bit(&t->bw, 0); /* no num_ref_idx override (4 active) */ + bw_put_bit(&t->bw, 1); /* ref_pic_list_modification_flag_l0 */ + bw_put_ue(&t->bw, 2); /* long-term */ + bw_put_ue(&t->bw, 3); /* lt_pic_num = 3 -> slot 6 */ + bw_put_ue(&t->bw, 0); /* sub */ + bw_put_ue(&t->bw, 2); /* diff=3 -> pic_num_no_wrap=14 -> slot 4 */ + bw_put_ue(&t->bw, 1); /* add */ + bw_put_ue(&t->bw, 0); /* diff=1 -> pic_num_no_wrap=15 -> slot 3 */ + bw_put_ue(&t->bw, 3); /* end */ + bw_put_ue(&t->bw, 0); /* cabac_init_idc */ + bw_put_se(&t->bw, 0); /* qp_delta */ + nal_len = bw_finish(&t->bw, true, 0xaa); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + t->builder.num_valid, + t->init_p, t->init_b0, t->init_b1, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[0].index, 6); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[1].index, 4); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[2].index, 3); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[3].index, 1); + + /* Referencing an inactive DPB entry (frame_num=13, slot 9) must fail */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 0); + bw_put_bit(&t->bw, 1); /* mod L0 */ + bw_put_ue(&t->bw, 0); /* sub */ + bw_put_ue(&t->bw, 3); /* diff=4 -> 1 - 4 + 16 = 13 (inactive!) */ + bw_put_ue(&t->bw, 3); + bw_put_ue(&t->bw, 0); + bw_put_se(&t->bw, 0); + nal_len = bw_finish(&t->bw, true, 0xaa); + + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + t->builder.num_valid, + t->init_p, t->init_b0, t->init_b1, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + + /* B slice modifying both L0 and L1 */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 1); /* B */ + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 1); /* direct_spatial */ + bw_put_bit(&t->bw, 1); /* override */ + bw_put_ue(&t->bw, 1); /* L0 active = 2 */ + bw_put_ue(&t->bw, 1); /* L1 active = 2 */ + bw_put_bit(&t->bw, 1); /* mod L0 */ + bw_put_ue(&t->bw, 2); /* long-term 3 -> slot 6 */ + bw_put_ue(&t->bw, 3); + bw_put_ue(&t->bw, 3); /* end L0 */ + bw_put_bit(&t->bw, 1); /* mod L1 */ + bw_put_ue(&t->bw, 0); /* sub diff=1 -> frame_num=0 -> slot 1 */ + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 3); /* end L1 */ + bw_put_ue(&t->bw, 1); /* cabac_init_idc */ + bw_put_se(&t->bw, 2); /* qp_delta */ + nal_len = bw_finish(&t->bw, true, 0xbb); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + t->builder.num_valid, + t->init_p, t->init_b0, t->init_b1, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[0].index, 6); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list1[0].index, 1); + KUNIT_EXPECT_EQ(test, t->sl.cabac_init_idc, 1); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 2); +} + +static void avd_slice_hdr_pred_weights_test(struct kunit *test) +{ + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + u32 data_off, nal_len; + u8 bit_off; + + t->sps.chroma_format_idc = 1; + t->sps.pic_order_cnt_type = 2; + t->pps.num_ref_idx_l0_default_active_minus1 = 1; + t->pps.num_ref_idx_l1_default_active_minus1 = 0; + t->pps.weighted_bipred_idc = 1; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE | + V4L2_H264_PPS_FLAG_WEIGHTED_PRED; + + /* B slice with explicit weights (L0 has 2 refs: explicit + default; L1 has 1 ref) */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); /* first_mb */ + bw_put_ue(&t->bw, 1); /* B */ + bw_put_ue(&t->bw, 0); /* pps_id */ + bw_put_bits(&t->bw, 2, 4); /* frame_num */ + bw_put_bit(&t->bw, 1); /* direct_spatial */ + bw_put_bit(&t->bw, 0); /* no override (L0=2, L1=1) */ + bw_put_bit(&t->bw, 0); /* no L0 mod */ + bw_put_bit(&t->bw, 0); /* no L1 mod */ + /* pred_weight_table() */ + bw_put_ue(&t->bw, 5); /* luma_log2_weight_denom */ + bw_put_ue(&t->bw, 4); /* chroma_log2_weight_denom */ + /* L0[0]: explicit luma & chroma */ + bw_put_bit(&t->bw, 1); + bw_put_se(&t->bw, 40); + bw_put_se(&t->bw, -10); + bw_put_bit(&t->bw, 1); + bw_put_se(&t->bw, 20); + bw_put_se(&t->bw, 3); + bw_put_se(&t->bw, -128); + bw_put_se(&t->bw, 127); + /* L0[1]: default luma & chroma */ + bw_put_bit(&t->bw, 0); + bw_put_bit(&t->bw, 0); + /* L1[0]: explicit luma, default chroma */ + bw_put_bit(&t->bw, 1); + bw_put_se(&t->bw, 12); + bw_put_se(&t->bw, 5); + bw_put_bit(&t->bw, 0); + bw_put_ue(&t->bw, 0); /* cabac_init_idc */ + bw_put_se(&t->bw, 0); /* qp_delta */ + nal_len = bw_finish(&t->bw, true, 0xaa); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->weights.luma_log2_weight_denom, 5); + KUNIT_EXPECT_EQ(test, t->weights.chroma_log2_weight_denom, 4); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].luma_weight[0], 40); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].luma_offset[0], -10); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_weight[0][0], 20); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_offset[0][0], 3); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_weight[0][1], -128); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_offset[0][1], 127); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].luma_weight[1], 32); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].luma_offset[1], 0); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_weight[1][0], 16); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_weight[1][1], 16); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[1].luma_weight[0], 12); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[1].luma_offset[0], 5); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[1].chroma_weight[0][0], 16); + + /* Monochrome P slice: no chroma denom or chroma weight bits in stream */ + t->sps.chroma_format_idc = 0; + t->pps.num_ref_idx_l0_default_active_minus1 = 0; + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); /* P */ + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 0); /* no override */ + bw_put_bit(&t->bw, 0); /* no mod */ + bw_put_ue(&t->bw, 3); /* luma_denom only */ + bw_put_bit(&t->bw, 1); /* luma_flag */ + bw_put_se(&t->bw, 10); + bw_put_se(&t->bw, -2); + bw_put_ue(&t->bw, 0); /* cabac_init_idc */ + bw_put_se(&t->bw, 1); /* qp_delta */ + nal_len = bw_finish(&t->bw, true, 0xcc); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->weights.luma_log2_weight_denom, 3); + KUNIT_EXPECT_EQ(test, t->weights.chroma_log2_weight_denom, 0); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].luma_weight[0], 10); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].luma_offset[0], -2); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_weight[0][0], 1); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_weight[0][1], 1); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 1); + + /* Reject denom > 7 and weight > 127 */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 0); + bw_put_bit(&t->bw, 0); + bw_put_ue(&t->bw, 8); /* invalid denom */ + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 0); + bw_put_bit(&t->bw, 0); + bw_put_ue(&t->bw, 2); + bw_put_bit(&t->bw, 1); + bw_put_se(&t->bw, 128); /* out of [-128, 127] */ + bw_put_se(&t->bw, 0); + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); +} + +static void avd_slice_hdr_marking_test(struct kunit *test) +{ + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + u32 data_off, nal_len; + u8 bit_off; + + t->sps.pic_order_cnt_type = 2; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE; + + /* Adaptive MMCO with all opcodes 1..6 terminated by 0 */ + bw_init(&t->bw, 0x41, true); + bw_put_ue(&t->bw, 0); /* first_mb */ + bw_put_ue(&t->bw, 2); /* I (non-IDR) */ + bw_put_ue(&t->bw, 0); /* pps_id */ + bw_put_bits(&t->bw, 5, 4); /* frame_num */ + bw_put_bit(&t->bw, 1); /* adaptive_ref_pic_marking_mode_flag */ + bw_put_ue(&t->bw, 1); /* op 1: diff_minus1 */ + bw_put_ue(&t->bw, 2); + bw_put_ue(&t->bw, 2); /* op 2: lt_pic_num */ + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 3); /* op 3: diff_minus1, lt_frame_idx */ + bw_put_ue(&t->bw, 1); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 4); /* op 4: max_lt_frame_idx_plus1 */ + bw_put_ue(&t->bw, 2); + bw_put_ue(&t->bw, 5); /* op 5: no args */ + bw_put_ue(&t->bw, 6); /* op 6: lt_frame_idx */ + bw_put_ue(&t->bw, 1); + bw_put_ue(&t->bw, 0); /* end */ + bw_put_se(&t->bw, -4); /* slice_qp_delta */ + nal_len = bw_finish(&t->bw, true, 0xdd); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 2, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, -4); + KUNIT_EXPECT_EQ(test, data_off, nal_len - 1); + KUNIT_EXPECT_EQ(test, t->bw.buf[data_off], 0xdd); + + /* Reject MMCO op > 6 */ + bw_init(&t->bw, 0x41, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 2); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 5, 4); + bw_put_bit(&t->bw, 1); + bw_put_ue(&t->bw, 7); /* invalid MMCO op */ + nal_len = bw_finish(&t->bw, true, 0xaa); + + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 2, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + + /* Reject > 64 MMCO ops without terminator */ + bw_init(&t->bw, 0x41, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 2); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 5, 4); + bw_put_bit(&t->bw, 1); + for (unsigned int i = 0; i < 65; i++) + bw_put_ue(&t->bw, 5); + nal_len = bw_finish(&t->bw, true, 0xaa); + + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 2, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); +} + +static void avd_slice_hdr_real_annexb_test(struct kunit *test) +{ + /* + * Real Annex-B NALUs (64x64 4:2:0) produced by libx264: + * 1) Main profile CABAC: AUD + IDR I-slice, P-slice (weighted_pred=1), + * and non-ref B-slice (poc_type=0, deblocking=1). + * 2) Baseline profile CAVLC: 2-slice IDR and 2-slice P-frame + * (poc_type=2, deblocking=1). + */ + static const u8 cabac_idr[] = { + 0x00, 0x00, 0x00, 0x01, 0x09, 0x10, + 0x00, 0x00, 0x01, + 0x65, 0x88, 0x84, 0x00, 0x87, 0x69, 0xd7, 0xdc, + }; + static const u8 cabac_p[] = { + 0x00, 0x00, 0x00, 0x01, 0x09, 0x30, + 0x00, 0x00, 0x01, + 0x41, 0x9a, 0x29, 0xb1, 0x09, 0x7f, 0xd1, 0x64, + }; + static const u8 cabac_b[] = { + 0x00, 0x00, 0x00, 0x01, 0x09, 0x50, + 0x00, 0x00, 0x01, + 0x01, 0x9e, 0x45, 0xe4, 0x2d, 0xff, 0x90, 0x87, + }; + static const u8 cavlc_2slice_idr[] = { + 0x00, 0x00, 0x01, + 0x65, 0x88, 0x84, 0x08, 0x7c, 0x42, 0x22, 0xb0, + 0x00, 0x00, 0x01, + 0x65, 0x12, 0x22, 0x10, 0x77, 0xf1, 0xff, 0x87, + }; + static const u8 cavlc_2slice_p[] = { + 0x00, 0x00, 0x00, 0x01, + 0x41, 0x9a, 0x20, 0x21, 0xfc, 0x9c, 0x3e, 0xf7, + 0x00, 0x00, 0x01, + 0x41, 0x12, 0x68, 0x80, 0x87, 0xac, 0x21, 0xf8, + }; + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + struct avd_h264_nalu nalu; + u32 cursor, data_off; + u8 bit_off; + + t->sps.chroma_format_idc = 1; + t->sps.pic_order_cnt_type = 0; + t->pps.num_ref_idx_l0_default_active_minus1 = 1; + t->pps.num_ref_idx_l1_default_active_minus1 = 0; + t->pps.weighted_bipred_idc = 2; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE | + V4L2_H264_PPS_FLAG_WEIGHTED_PRED | + V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT; + + /* Main CABAC IDR */ + cursor = 0; + KUNIT_ASSERT_EQ(test, avd_h264_next_nalu(cabac_idr, sizeof(cabac_idr), + &cursor, &nalu), 1); + KUNIT_EXPECT_EQ(test, nalu.nal_unit_type, 5); + KUNIT_EXPECT_EQ(test, nalu.nal_ref_idc, 3); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cabac_idr + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_I); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 8); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 40); + KUNIT_EXPECT_EQ(test, data_off, 5); + KUNIT_EXPECT_EQ(test, bit_off, 0); + + /* Main CABAC P-slice (weighted_pred_flag=1) */ + cursor = 0; + KUNIT_ASSERT_EQ(test, avd_h264_next_nalu(cabac_p, sizeof(cabac_p), + &cursor, &nalu), 1); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cabac_p + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_P); + KUNIT_EXPECT_EQ(test, t->sl.num_ref_idx_l0_active_minus1, 0); + KUNIT_EXPECT_EQ(test, t->sl.cabac_init_idc, 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 9); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 44); + KUNIT_EXPECT_EQ(test, data_off, 6); + KUNIT_EXPECT_EQ(test, bit_off, 0); + + /* Main CABAC B-slice (nal_ref_idc=0) */ + cursor = 0; + KUNIT_ASSERT_EQ(test, avd_h264_next_nalu(cabac_b, sizeof(cabac_b), + &cursor, &nalu), 1); + KUNIT_EXPECT_EQ(test, nalu.nal_ref_idc, 0); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cabac_b + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_B); + KUNIT_EXPECT_EQ(test, t->sl.flags, V4L2_H264_SLICE_FLAG_DIRECT_SPATIAL_MV_PRED); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 11); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 42); + KUNIT_EXPECT_EQ(test, data_off, 6); + KUNIT_EXPECT_EQ(test, bit_off, 0); + + /* Baseline CAVLC 2-slice IDR */ + t->sps.pic_order_cnt_type = 2; + t->pps.num_ref_idx_l0_default_active_minus1 = 0; + t->pps.weighted_bipred_idc = 0; + t->pps.flags = V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT; + + cursor = 0; + KUNIT_ASSERT_EQ(test, + avd_h264_next_nalu(cavlc_2slice_idr, sizeof(cavlc_2slice_idr), + &cursor, &nalu), 1); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cavlc_2slice_idr + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_I); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 8); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 36); + KUNIT_EXPECT_EQ(test, data_off, 4); + KUNIT_EXPECT_EQ(test, bit_off, 4); + + KUNIT_ASSERT_EQ(test, + avd_h264_next_nalu(cavlc_2slice_idr, sizeof(cavlc_2slice_idr), + &cursor, &nalu), 1); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cavlc_2slice_idr + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 8); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 7); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 40); + KUNIT_EXPECT_EQ(test, data_off, 5); + KUNIT_EXPECT_EQ(test, bit_off, 0); + KUNIT_EXPECT_EQ(test, + avd_h264_next_nalu(cavlc_2slice_idr, sizeof(cavlc_2slice_idr), + &cursor, &nalu), 0); + + /* Baseline CAVLC 2-slice P-frame */ + cursor = 0; + KUNIT_ASSERT_EQ(test, + avd_h264_next_nalu(cavlc_2slice_p, sizeof(cavlc_2slice_p), + &cursor, &nalu), 1); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cavlc_2slice_p + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_P); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 8); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 34); + KUNIT_EXPECT_EQ(test, data_off, 4); + KUNIT_EXPECT_EQ(test, bit_off, 2); + + KUNIT_ASSERT_EQ(test, + avd_h264_next_nalu(cavlc_2slice_p, sizeof(cavlc_2slice_p), + &cursor, &nalu), 1); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cavlc_2slice_p + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 8); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 8); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 40); + KUNIT_EXPECT_EQ(test, data_off, 5); + KUNIT_EXPECT_EQ(test, bit_off, 0); +} + +static void avd_frame_mode_framing_test(struct kunit *test) +{ + /* Real libx264 CABAC IDR slice, unprefixed (7.3.1 NALU) and Annex-B. */ + static const u8 raw_idr[] = { + 0x65, 0x88, 0x84, 0x00, 0x87, 0x69, 0xd7, 0xdc, 0x00, 0x00, + }; + static const u8 annexb_two_slice[] = { + 0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x08, 0x7c, 0x42, 0x22, 0xb0, + 0x00, 0x00, 0x01, 0x65, 0x12, 0x22, 0x10, 0x77, 0xf1, 0xff, 0x87, + }; + static const u8 raw_with_embedded_sc[] = { + 0x65, 0x88, 0x84, 0x00, 0x00, 0x01, 0x65, 0x12, + }; + static const u8 bad_raw_hdrs[] = { + 0x00, 0x06, 0x09, 0x67, 0x68, 0x22, 0x23, 0x24, 0x2e, 0x34, 0xe5, + }; + static const u8 one_byte[] = { 0x65 }; + static const u8 trunc_zeros[] = { 0x00, 0x00 }; + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + struct avd_h264_nalu nalu; + u32 cursor, data_off; + u8 bit_off; + + /* Mode / start-code pairing matrix */ + KUNIT_EXPECT_TRUE(test, + avd_h264_mode_supported(V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED, + V4L2_STATELESS_H264_START_CODE_NONE)); + KUNIT_EXPECT_FALSE(test, + avd_h264_mode_supported(V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED, + V4L2_STATELESS_H264_START_CODE_ANNEX_B)); + KUNIT_EXPECT_TRUE(test, + avd_h264_mode_supported(V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED, + V4L2_STATELESS_H264_START_CODE_ANNEX_B)); + KUNIT_EXPECT_TRUE(test, + avd_h264_mode_supported(V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED, + V4L2_STATELESS_H264_START_CODE_NONE)); + KUNIT_EXPECT_FALSE(test, + avd_h264_mode_supported(-1, V4L2_STATELESS_H264_START_CODE_NONE)); + KUNIT_EXPECT_FALSE(test, + avd_h264_mode_supported(V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED, 2)); + + /* FRAME_BASED + START_CODE_ANNEX_B: accepts Annex-B, rejects raw NALU */ + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(annexb_two_slice, sizeof(annexb_two_slice), + V4L2_STATELESS_H264_START_CODE_ANNEX_B, + &cursor, &nalu), + 1); + KUNIT_EXPECT_EQ(test, nalu.nal_unit_type, 5); + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(annexb_two_slice, sizeof(annexb_two_slice), + V4L2_STATELESS_H264_START_CODE_ANNEX_B, + &cursor, &nalu), + 1); + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(annexb_two_slice, sizeof(annexb_two_slice), + V4L2_STATELESS_H264_START_CODE_ANNEX_B, + &cursor, &nalu), + 0); + + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(raw_idr, sizeof(raw_idr), + V4L2_STATELESS_H264_START_CODE_ANNEX_B, + &cursor, &nalu), + -EINVAL); + + /* FRAME_BASED + START_CODE_NONE: accepts unprefixed 7.3.1 VCL slice NALU */ + t->sps.chroma_format_idc = 1; + t->sps.pic_order_cnt_type = 0; + t->pps.num_ref_idx_l0_default_active_minus1 = 1; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE | + V4L2_H264_PPS_FLAG_WEIGHTED_PRED | + V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT; + + cursor = 0; + KUNIT_ASSERT_EQ(test, + avd_h264_next_frame_nalu(raw_idr, sizeof(raw_idr), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + 1); + KUNIT_EXPECT_EQ(test, nalu.off, 0); + KUNIT_EXPECT_EQ(test, nalu.len, sizeof(raw_idr) - 2); + KUNIT_EXPECT_EQ(test, nalu.nal_unit_type, 5); + KUNIT_EXPECT_EQ(test, nalu.nal_ref_idc, 3); + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(raw_idr, sizeof(raw_idr), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + 0); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(raw_idr + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_I); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 8); + KUNIT_EXPECT_EQ(test, data_off, 5); + KUNIT_EXPECT_EQ(test, bit_off, 0); + + /* FRAME_BASED + START_CODE_NONE: Chromium Annex-B compatibility path */ + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(annexb_two_slice, sizeof(annexb_two_slice), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + 1); + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(annexb_two_slice, sizeof(annexb_two_slice), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + 1); + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(annexb_two_slice, sizeof(annexb_two_slice), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + 0); + + /* Error paths for FRAME_BASED + START_CODE_NONE and invalid start_code */ + for (unsigned int i = 0; i < ARRAY_SIZE(bad_raw_hdrs); i++) { + u8 buf[] = { bad_raw_hdrs[i], 0x88, 0x84 }; + + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(buf, sizeof(buf), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + -EINVAL); + } + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(one_byte, sizeof(one_byte), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + -EINVAL); + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(trunc_zeros, sizeof(trunc_zeros), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + -EINVAL); + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(raw_with_embedded_sc, sizeof(raw_with_embedded_sc), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + -EINVAL); + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(raw_idr, sizeof(raw_idr), 2, + &cursor, &nalu), + -EINVAL); +} + static struct kunit_case avd_h264_test_cases[] = { KUNIT_CASE(avd_scaling_flat_test), KUNIT_CASE_PARAM(avd_slice_data_test, avd_slice_data_gen_params), KUNIT_CASE_PARAM(avd_slice_fits_test, avd_slice_fits_gen_params), + KUNIT_CASE_PARAM(avd_sps_size_test, avd_sps_size_gen_params), + KUNIT_CASE(avd_sps_fmt_init_test), + KUNIT_CASE(avd_sps_range_test), + KUNIT_CASE(avd_start_slices_test), + KUNIT_CASE(avd_annexb_scanner_test), + KUNIT_CASE(avd_frame_mode_framing_test), + KUNIT_CASE(avd_bitreader_epb_test), + KUNIT_CASE(avd_slice_hdr_epb_boundary_test), + KUNIT_CASE(avd_slice_hdr_fields_test), + KUNIT_CASE(avd_slice_hdr_ref_mod_test), + KUNIT_CASE(avd_slice_hdr_pred_weights_test), + KUNIT_CASE(avd_slice_hdr_marking_test), + KUNIT_CASE(avd_slice_hdr_real_annexb_test), {} }; diff --git a/drivers/media/platform/apple/avd/avd-h264.c b/drivers/media/platform/apple/avd/avd-h264.c index db4830e7aca222..ac02aa7b26844c 100644 --- a/drivers/media/platform/apple/avd/avd-h264.c +++ b/drivers/media/platform/apple/avd/avd-h264.c @@ -23,6 +23,7 @@ #include "avd.h" #include "avd-inst.h" #include "avd-h264-params.h" +#include "avd-h264-parse.h" #define H264_SCL_DIMS (0x1000000 | ((64 / 4) << 5) | (((16 / 4) << 5) - 1)) @@ -53,6 +54,8 @@ struct avd_h264_run { dma_addr_t mv_color; } addresses; + s32 decode_mode; + s32 start_code; s32 cur_poc; u8 num_valid; u32 slice_data_off; @@ -102,6 +105,16 @@ struct avd_h264_ctx { struct avd_bank bank[AVD_H264_BANKS]; /* bank of the picture being built */ struct avd_bank *b; + + /* What the run being built took from the controls, see avd_ctrl_copy(). */ + struct { + struct v4l2_ctrl_h264_decode_params decode_params; + struct v4l2_ctrl_h264_sps sps; + struct v4l2_ctrl_h264_pps pps; + struct v4l2_ctrl_h264_slice_params slice_params; + struct v4l2_ctrl_h264_scaling_matrix scaling_matrix; + struct v4l2_ctrl_h264_pred_weights pred_weights; + } params; }; /* ffmpeg submits wrong timestamp, use first_mb_in_slice as a workaround */ @@ -488,29 +501,22 @@ static u32 avd_h264_header_len(const struct avd_h264_run *run) return (run->slice_params->header_bit_size + (cabac ? 7 : 0)) / 8; } -static void stream_slice(struct avd_ctx *ctx, struct avd_h264_run *run) +static void stream_slice_data(struct avd_ctx *ctx, struct avd_h264_run *run, + dma_addr_t data_dma, u32 data_len, u8 bit_off) { const struct v4l2_ctrl_h264_decode_params *decode = run->decode_params; const struct v4l2_ctrl_h264_pps *pps = run->pps; const struct v4l2_ctrl_h264_sps *sps = run->sps; const struct v4l2_ctrl_h264_slice_params *sl = run->slice_params; - struct avd_h264_ctx *h264_ctx = ctx->priv; - u32 payload_len = h264_ctx->b->active_slice->size; - bool en_mode = (pps->flags & V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE) == - 0; - u32 off = run->slice_data_off; - - dma_addr_t slc_a84 = h264_ctx->b->active_slice->addr + off; push(AVD_OP_CODED_DATA | - AVD_OP_CODED_DATA_BIT_OFF( - en_mode ? (sl->header_bit_size % 8) : 0) | - AVD_OP_CODED_DATA_ADDR(slc_a84 >> 32), + AVD_OP_CODED_DATA_BIT_OFF(bit_off) | + AVD_OP_CODED_DATA_ADDR(data_dma >> 32), "slc_a7c_cmd_set_coded_slice"); - push((u32)(slc_a84 & 0xffffffff), "slc_a84_slice_addr_low"); + push((u32)(data_dma & 0xffffffff), "slc_a84_slice_addr_low"); /* should not include trailing 0? */ - push(payload_len - off, "slc_a88_slice_hdr_size"); + push(data_len, "slc_a88_slice_hdr_size"); push(AVD_OP_SL_LOC | AVD_OP_SL_LOC_Y(sl->first_mb_in_slice / @@ -599,6 +605,19 @@ static void stream_slice(struct avd_ctx *ctx, struct avd_h264_run *run) } } +static void stream_slice(struct avd_ctx *ctx, struct avd_h264_run *run) +{ + struct avd_h264_ctx *h264_ctx = ctx->priv; + u32 payload_len = h264_ctx->b->active_slice->size; + bool cavlc = !(run->pps->flags & + V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE); + u32 off = run->slice_data_off; + + stream_slice_data(ctx, run, h264_ctx->b->active_slice->addr + off, + payload_len - off, + cavlc ? (run->slice_params->header_bit_size % 8) : 0); +} + static int avd_h264_alloc_bufs(struct avd_ctx *ctx, struct avd_bank *bank) { struct avd_dev *dev = ctx->dev; @@ -672,9 +691,42 @@ static int avd_h264_validate_slice(struct avd_ctx *ctx, return 0; } -static int avd_h264_validate_sps(struct avd_ctx *ctx, - const struct v4l2_ctrl_h264_sps *sps) +static enum avd_image_fmt +avd_h264_sps_image_fmt(const struct v4l2_ctrl_h264_sps *sps) { + if (sps->bit_depth_luma_minus8 == 0) { + if (sps->chroma_format_idc == 2) + return AVD_IMG_FMT_422_8BIT; + else + return AVD_IMG_FMT_420_8BIT; + } else if (sps->bit_depth_luma_minus8 == 2) { + if (sps->chroma_format_idc == 2) + return AVD_IMG_FMT_422_10BIT; + else + return AVD_IMG_FMT_420_10BIT; + } + + return AVD_IMG_FMT_ANY; +} + +/* + * H.264 7.4.2.1.1: the picture is PicWidthInMbs macroblocks wide and + * FrameHeightInMbs = (2 - frame_mbs_only_flag) * PicHeightInMapUnits high. + * The decoded buffers and the per-row scratch are sized from the OUTPUT + * format, which S_FMT rounds up to whole macroblocks, so a picture must fit + * in it. + */ +VISIBLE_IF_KUNIT int +avd_h264_validate_sps_fmt(struct avd_ctx *ctx, + const struct v4l2_ctrl_h264_sps *sps) +{ + u32 width = (sps->pic_width_in_mbs_minus1 + 1) * 16; + u32 height = (sps->pic_height_in_map_units_minus1 + 1) * 16 * + (sps->flags & V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY ? 1 : 2); + + if (width > ctx->coded_fmt.fmt.pix_mp.width || + height > ctx->coded_fmt.fmt.pix_mp.height) + return -EINVAL; if (sps->chroma_format_idc > 2) /* Only 4:0:0, 4:2:0 and 4:2:2 are supported */ return -EINVAL; @@ -691,12 +743,48 @@ static int avd_h264_validate_sps(struct avd_ctx *ctx, if (sps->chroma_format_idc == 2 && sps->bit_depth_luma_minus8 == 2) /* 4:2:2 10 bit would need P210; P010 is too small for its chroma */ return -EINVAL; + + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_validate_sps_fmt); + +VISIBLE_IF_KUNIT int avd_h264_validate_sps(struct avd_ctx *ctx, + const struct v4l2_ctrl_h264_sps *sps) +{ + int ret = avd_h264_validate_sps_fmt(ctx, sps); + + if (ret) + return ret; if (!(sps->flags & V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY)) /* no interlaced support */ return -EINVAL; + if (sps->log2_max_frame_num_minus4 > 12 || sps->pic_order_cnt_type > 2) + return -EINVAL; + if (sps->pic_order_cnt_type == 0 && + sps->log2_max_pic_order_cnt_lsb_minus4 > 12) + return -EINVAL; return 0; } +EXPORT_SYMBOL_IF_KUNIT(avd_h264_validate_sps); + +static bool avd_h264_sps_is_fmt_init(const struct v4l2_ctrl_h264_sps *sps) +{ + return !sps->flags && !sps->pic_width_in_mbs_minus1 && + !sps->pic_height_in_map_units_minus1; +} + +VISIBLE_IF_KUNIT int +avd_h264_validate_sps_ctrl(struct avd_ctx *ctx, + const struct v4l2_ctrl_h264_sps *sps, + bool streaming) +{ + if (!streaming && avd_h264_sps_is_fmt_init(sps)) + return avd_h264_validate_sps_fmt(ctx, sps); + + return avd_h264_validate_sps(ctx, sps); +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_validate_sps_ctrl); /* Free the slices held for one bank's picture. */ static void avd_h264_drop_bank_slices(struct avd_ctx *ctx, struct avd_bank *bank) @@ -715,6 +803,7 @@ static void avd_h264_stop(struct avd_ctx *ctx) unsigned int i; ctx->max_frames = 1; + ctx->scratch_sized = false; if (!h264_ctx) return; @@ -736,6 +825,9 @@ static void avd_h264_stop(struct avd_ctx *ctx) ctx->priv = NULL; } +VISIBLE_IF_KUNIT size_t +avd_h264_start_slices(const struct v4l2_ctrl_h264_sps *sps); + static int avd_h264_start(struct avd_ctx *ctx) { struct avd_h264_ctx *h264_ctx; @@ -746,11 +838,19 @@ static int avd_h264_start(struct avd_ctx *ctx) if (!ctrl) return -EINVAL; - ret = avd_h264_validate_sps(ctx, ctrl->p_new.p_h264_sps); + /* + * Pre-streaming format-negotiation controls (for example Chromium's + * V4L2VideoDecoder::SetExtCtrlsInit) populate chroma format and bit + * depth with flags and dimensions zeroed before the first frame + * request supplies the parsed SPS. Allow that minimal init control + * here while rejecting populated interlaced SPS structs upfront; + * avd_h264_run() enforces full avd_h264_validate_sps() per frame. + */ + ret = avd_h264_validate_sps_ctrl(ctx, ctrl->p_cur.p_h264_sps, false); if (ret) return ret; - h264_ctx = kzalloc(sizeof(*h264_ctx), GFP_KERNEL); + h264_ctx = kzalloc(sizeof(*h264_ctx), GFP_KERNEL_ACCOUNT); if (!h264_ctx) return -ENOMEM; @@ -762,11 +862,10 @@ static int avd_h264_start(struct avd_ctx *ctx) for (unsigned int i = 0; i < h264_ctx->nbanks; i++) { struct avd_bank *bank = &h264_ctx->bank[i]; - /* assume one slice per row */ bank->alloc_slice_num = - ctrl->p_new.p_h264_sps->pic_height_in_map_units_minus1 + 1; + avd_h264_start_slices(ctrl->p_cur.p_h264_sps); bank->slices = kcalloc(bank->alloc_slice_num, - sizeof(*bank->slices), GFP_KERNEL); + sizeof(*bank->slices), GFP_KERNEL_ACCOUNT); if (!bank->slices) { ret = -ENOMEM; goto err_free_ctx; @@ -777,6 +876,9 @@ static int avd_h264_start(struct avd_ctx *ctx) goto err_free_ctx; } ctx->max_frames = h264_ctx->nbanks; + /* avd_h264_alloc_bufs() sized the scratch rows for this depth */ + ctx->scratch_fmt = ctx->image_fmt; + ctx->scratch_sized = true; return 0; @@ -785,28 +887,11 @@ static int avd_h264_start(struct avd_ctx *ctx) return ret; } -static void avd_h264_run_preamble(struct avd_ctx *ctx, struct avd_h264_run *run) +static int avd_h264_run_preamble(struct avd_ctx *ctx, struct avd_h264_run *run) { - struct v4l2_ctrl *ctrl; + struct avd_h264_ctx *h264_ctx = ctx->priv; u32 dst_len, mv_color_len; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_H264_DECODE_PARAMS); - run->decode_params = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_H264_SPS); - run->sps = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_H264_PPS); - run->pps = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_H264_SLICE_PARAMS); - run->slice_params = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_H264_SCALING_MATRIX); - run->scaling_matrix = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_H264_PRED_WEIGHTS); - run->pred_weights = ctrl ? ctrl->p_cur.p : NULL; - avd_run_preamble(ctx, &run->base); dst_len = run->base.bufs.dst->vb2_buf.planes[0].length; @@ -814,6 +899,50 @@ static void avd_h264_run_preamble(struct avd_ctx *ctx, struct avd_h264_run *run) mv_color_len = mv_color_size(ctx, fmt_width(ctx), fmt_height(ctx)); run->addresses.mv_color = run->base.y_out + (dst_len - mv_color_len); + + if (run->base.setup_err) + return run->base.setup_err; + + /* + * The checks in avd_h264_run() and the builders must see the same + * parameters, and the controls can be set again at any time: use + * copies. + */ + if (avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_DECODE_MODE, + &run->decode_mode, sizeof(run->decode_mode)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_START_CODE, + &run->start_code, sizeof(run->start_code)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_DECODE_PARAMS, + &h264_ctx->params.decode_params, + sizeof(h264_ctx->params.decode_params)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_SPS, + &h264_ctx->params.sps, + sizeof(h264_ctx->params.sps)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_PPS, + &h264_ctx->params.pps, + sizeof(h264_ctx->params.pps)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_SCALING_MATRIX, + &h264_ctx->params.scaling_matrix, + sizeof(h264_ctx->params.scaling_matrix))) + return -EINVAL; + + if (run->decode_mode == V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED && + (avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_SLICE_PARAMS, + &h264_ctx->params.slice_params, + sizeof(h264_ctx->params.slice_params)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_PRED_WEIGHTS, + &h264_ctx->params.pred_weights, + sizeof(h264_ctx->params.pred_weights)))) + return -EINVAL; + + run->decode_params = &h264_ctx->params.decode_params; + run->sps = &h264_ctx->params.sps; + run->pps = &h264_ctx->params.pps; + run->slice_params = &h264_ctx->params.slice_params; + run->scaling_matrix = &h264_ctx->params.scaling_matrix; + run->pred_weights = &h264_ctx->params.pred_weights; + + return 0; } static int avd_h264_realloc_slices(struct avd_ctx *ctx, size_t max_slices) @@ -854,6 +983,7 @@ static int avd_h264_realloc_slices(struct avd_ctx *ctx, size_t max_slices) memcpy(ctx->job.segments, tmp, sizeof(*ctx->job.segments) * (ctx->job.num + 1)); + ctx->job.max = alloc_slice_num + 1; kvfree(tmp); return 0; @@ -922,6 +1052,15 @@ static size_t avd_h264_max_slices(const struct v4l2_ctrl_h264_sps *sps) return min_t(size_t, mbs, MAX_SLICES); } +/* Slice table entries made at STREAMON: one slice per row to begin with. */ +VISIBLE_IF_KUNIT size_t +avd_h264_start_slices(const struct v4l2_ctrl_h264_sps *sps) +{ + return min_t(size_t, sps->pic_height_in_map_units_minus1 + 1, + avd_h264_max_slices(sps)); +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_start_slices); + /* * Coded data held for one picture. A picture of PCM macroblocks is about the * size of the decoded one and emulation prevention adds at most one byte for @@ -986,6 +1125,139 @@ static void avd_h264_abort_picture(struct avd_ctx *ctx, buf->bank = 0; } +static int avd_h264_run_frame(struct avd_ctx *ctx, struct avd_h264_run *run) +{ + struct avd_h264_ctx *h264_ctx = ctx->priv; + struct v4l2_h264_reflist_builder reflist_builder; + struct avd_h264_nalu nalu; + size_t max_slices, num_slices, slice_idx; + u32 payload_len, cursor, last_mb; + const u8 *data; + bool is_idr = false; + int ret; + + /* Abort any stale unfinished slice-based picture if mode switched. */ + if (h264_ctx->b->busy && !h264_ctx->b->submitted) { + struct avd_decoded_buffer *dst_buf = + vb2_to_avd_decoded_buf(&run->base.bufs.dst->vb2_buf); + + if (dst_buf->bank == h264_ctx->b - h264_ctx->bank + 1) + dst_buf->bank = 0; + avd_h264_drop_bank_slices(ctx, h264_ctx->b); + h264_ctx->b->busy = false; + } + kvfree(ctx->job.segments); + ctx->job.segments = NULL; + + if (run->base.bufs.src->flags & V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF) { + dev_dbg_ratelimited(ctx->dev->dev, + "HOLD_CAPTURE_BUF is unsupported in frame-based H.264 mode\n"); + return -EINVAL; + } + + payload_len = vb2_get_plane_payload(&run->base.bufs.src->vb2_buf, 0); + data = vb2_plane_vaddr(&run->base.bufs.src->vb2_buf, 0); + if (!data || !payload_len) + return -EINVAL; + + max_slices = avd_h264_max_slices(run->sps); + cursor = 0; + num_slices = 0; + while ((ret = avd_h264_next_frame_nalu(data, payload_len, + run->start_code, + &cursor, &nalu)) > 0) { + num_slices++; + if (num_slices > max_slices) { + dev_err_ratelimited(ctx->dev->dev, + "too many slices in H.264 frame, dropping it\n"); + return -EINVAL; + } + } + if (ret < 0 || !num_slices) { + dev_dbg_ratelimited(ctx->dev->dev, + "no valid H.264 slice NALUs in frame buffer\n"); + return -EINVAL; + } + + ret = avd_h264_pick_bank(ctx, run->base.bufs.dst); + if (ret) + return ret; + + h264_ctx->b->monochrome = run->sps->chroma_format_idc == 0; + + ret = avd_init_job(ctx, AVD_CODEC_H264, num_slices + 1); + if (ret) + return ret; + + v4l2_h264_init_reflist_builder(&reflist_builder, run->decode_params, + run->sps, run->decode_params->dpb); + run->num_valid = avd_h264_num_refs(run->decode_params); + run->cur_poc = reflist_builder.cur_pic_order_count; + + v4l2_h264_build_p_ref_list(&reflist_builder, h264_ctx->reflists.p); + v4l2_h264_build_b_ref_lists(&reflist_builder, h264_ctx->reflists.b0, + h264_ctx->reflists.b1); + + cursor = 0; + slice_idx = 0; + last_mb = 0; + while ((ret = avd_h264_next_frame_nalu(data, payload_len, + run->start_code, + &cursor, &nalu)) > 0) { + u32 slice_data_off; + u8 slice_bit_off; + + if (slice_idx == 0) + is_idr = nalu.nal_unit_type == 5; + else if ((nalu.nal_unit_type == 5) != is_idr) + return -EINVAL; + + ret = avd_h264_parse_slice_header(data + nalu.off, nalu.len, + nalu.nal_ref_idc, + nalu.nal_unit_type, + run->sps, run->pps, + run->decode_params, + reflist_builder.num_valid, + h264_ctx->reflists.p, + h264_ctx->reflists.b0, + h264_ctx->reflists.b1, + &h264_ctx->params.slice_params, + &h264_ctx->params.pred_weights, + &slice_data_off, + &slice_bit_off); + if (ret) + return ret; + + if (!avd_h264_slice_order_supported(slice_idx, last_mb, + run->slice_params->first_mb_in_slice)) { + dev_err_ratelimited(ctx->dev->dev, + "H.264 arbitrary slice order (ASO) is unsupported\n"); + return -EINVAL; + } + + if (!avd_h264_refs_valid(run)) { + dev_dbg_ratelimited(ctx->dev->dev, + "slice references an invalid DPB entry, dropping frame\n"); + return -EINVAL; + } + + if (slice_idx == 0) + stream_hdr(ctx, run); + + ctx->job.num++; + stream_slice_data(ctx, run, + run->base.coded_in + nalu.off + slice_data_off, + nalu.len - slice_data_off, slice_bit_off); + + last_mb = run->slice_params->first_mb_in_slice; + slice_idx++; + } + if (ret < 0 || slice_idx != num_slices) + return -EINVAL; + + return 0; +} + static int avd_h264_run(struct avd_ctx *ctx) { struct avd_h264_ctx *h264_ctx = ctx->priv; @@ -995,23 +1267,36 @@ static int avd_h264_run(struct avd_ctx *ctx) h264_ctx->b->slice_num : 0; int ret; - avd_h264_run_preamble(ctx, &run); - - if (run.base.setup_err) { - ret = run.base.setup_err; - goto err_free_jobs; - } - if (!run.sps || !run.pps || !run.slice_params || !run.decode_params) { - ret = -EINVAL; + ret = avd_h264_run_preamble(ctx, &run); + if (ret) goto err_free_jobs; - } /* Recheck controls applied from this request before building instructions. */ ret = avd_h264_validate_sps(ctx, run.sps); if (!ret) - ret = avd_h264_validate_pps(ctx, run.pps); + ret = avd_check_run_image_fmt(ctx, + avd_h264_sps_image_fmt(run.sps)); if (!ret) - ret = avd_h264_validate_slice(ctx, run.slice_params); + ret = avd_h264_validate_pps(ctx, run.pps); + if (ret) + goto err_free_jobs; + + if (!avd_h264_mode_supported(run.decode_mode, run.start_code)) { + ret = -EINVAL; + goto err_free_jobs; + } + + if (run.decode_mode == V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED) { + ret = avd_h264_run_frame(ctx, &run); + if (ret) + goto err_free_jobs; + avd_run_postamble(ctx, &run.base); + ctx->job_fifo = h264_ctx->b->bufs.inst.addr; + h264_ctx->b->submitted = true; + return avd_submit_job(ctx); + } + + ret = avd_h264_validate_slice(ctx, run.slice_params); if (ret) goto err_free_jobs; @@ -1166,24 +1451,10 @@ static void avd_h264_done(struct avd_ctx *ctx, struct vb2_v4l2_buffer *src_buf, static enum avd_image_fmt avd_h264_get_image_fmt(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { - const struct v4l2_ctrl_h264_sps *sps = ctrl->p_new.p_h264_sps; - if (ctrl->id != V4L2_CID_STATELESS_H264_SPS) return AVD_IMG_FMT_ANY; - if (sps->bit_depth_luma_minus8 == 0) { - if (sps->chroma_format_idc == 2) - return AVD_IMG_FMT_422_8BIT; - else - return AVD_IMG_FMT_420_8BIT; - } else if (sps->bit_depth_luma_minus8 == 2) { - if (sps->chroma_format_idc == 2) - return AVD_IMG_FMT_422_10BIT; - else - return AVD_IMG_FMT_420_10BIT; - } - - return AVD_IMG_FMT_ANY; + return avd_h264_sps_image_fmt(ctrl->p_new.p_h264_sps); } static void avd_h264_adjust_decoded_fmt(struct avd_ctx *ctx, @@ -1195,8 +1466,16 @@ static void avd_h264_adjust_decoded_fmt(struct avd_ctx *ctx, static int avd_h264_try_ctrl(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { - if (ctrl->id == V4L2_CID_STATELESS_H264_SPS) - return avd_h264_validate_sps(ctx, ctrl->p_new.p_h264_sps); + if (ctrl->id == V4L2_CID_STATELESS_H264_SPS) { + struct vb2_queue *vq = + ctx->fh.m2m_ctx ? + v4l2_m2m_get_vq(ctx->fh.m2m_ctx, + V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) : + NULL; + + return avd_h264_validate_sps_ctrl(ctx, ctrl->p_new.p_h264_sps, + vq && vb2_is_streaming(vq)); + } if (ctrl->id == V4L2_CID_STATELESS_H264_PPS) return avd_h264_validate_pps(ctx, ctrl->p_new.p_h264_pps); if (ctrl->id == V4L2_CID_STATELESS_H264_SLICE_PARAMS) diff --git a/drivers/media/platform/apple/avd/avd-hevc-test.c b/drivers/media/platform/apple/avd/avd-hevc-test.c new file mode 100644 index 00000000000000..09eac2716c7aa4 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-hevc-test.c @@ -0,0 +1,434 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the HEVC picture, tile and slice checks of the Apple video + * decoder. + */ + +#include + +#include "avd.h" + +/* 64x64 luma samples in 16x16 CTBs: 4x4 CTBs. */ +static void avd_hevc_test_sps(struct v4l2_ctrl_hevc_sps *sps) +{ + *sps = (struct v4l2_ctrl_hevc_sps) { + .pic_width_in_luma_samples = 64, + .pic_height_in_luma_samples = 64, + .log2_min_luma_coding_block_size_minus3 = 0, + .log2_diff_max_min_luma_coding_block_size = 1, + }; +} + +struct avd_hevc_geometry_case { + const char *desc; + u16 width; + u16 height; + u8 min_cb_minus3; + u8 diff; + int ret; +}; + +static const struct avd_hevc_geometry_case avd_hevc_geometry_cases[] = { + { "16x16 CTBs", 64, 64, 0, 1, 0 }, + { "32x32 CTBs", 1920, 1080, 0, 2, 0 }, + { "64x64 CTBs", 4096, 2160, 0, 3, 0 }, + { "64x64 CTBs from 16x16 coding blocks", 4096, 2160, 1, 2, 0 }, + { "8x8 CTBs", 64, 64, 0, 0, -EINVAL }, + { "128x128 CTBs", 64, 64, 0, 4, -EINVAL }, + { "coding block size beyond any CTB", 64, 64, 255, 255, -EINVAL }, + { "zero width", 0, 64, 0, 1, -EINVAL }, + { "zero height", 64, 0, 0, 1, -EINVAL }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_hevc_geometry, avd_hevc_geometry_cases, desc); + +static void avd_hevc_geometry_test(struct kunit *test) +{ + const struct avd_hevc_geometry_case *c = test->param_value; + struct v4l2_ctrl_hevc_sps sps = { + .pic_width_in_luma_samples = c->width, + .pic_height_in_luma_samples = c->height, + .log2_min_luma_coding_block_size_minus3 = c->min_cb_minus3, + .log2_diff_max_min_luma_coding_block_size = c->diff, + }; + + KUNIT_EXPECT_EQ(test, avd_hevc_check_sps_geometry(&sps), c->ret); +} + +/* + * Pre-streaming format negotiation (e.g. Chromium V4L2VideoDecoder::SetExtCtrlsInit) + * supplies coded dimensions, chroma_format_idc and bit depth with zeroed CTB size + * fields. Format validation accepts those while full geometry validation still + * requires 16x16..64x64 CTBs. + */ +static void avd_hevc_sps_fmt_init_test(struct kunit *test) +{ + struct v4l2_ctrl_hevc_sps sps = { + .pic_width_in_luma_samples = 1280, + .pic_height_in_luma_samples = 720, + .chroma_format_idc = 1, + }; + struct avd_dev *dev; + struct avd_ctx *ctx; + + dev = kunit_kzalloc(test, sizeof(*dev), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dev); + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->dev = dev; + ctx->coded_fmt.fmt.pix_mp.width = 1280; + ctx->coded_fmt.fmt.pix_mp.height = 720; + + /* 8-bit and 10-bit 4:2:0 pre-streaming init controls */ + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), 0); + KUNIT_EXPECT_EQ(test, avd_hevc_check_sps_geometry(&sps), -EINVAL); + + sps.bit_depth_luma_minus8 = 2; + sps.bit_depth_chroma_minus8 = 2; + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), 0); + + /* Oversized or unsupported formats remain rejected pre-streaming */ + sps.pic_width_in_luma_samples = 1920; + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), -EINVAL); + sps.pic_width_in_luma_samples = 1280; + sps.chroma_format_idc = 3; + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), -EINVAL); + sps.chroma_format_idc = 2; + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), -EINVAL); + sps.chroma_format_idc = 1; + sps.bit_depth_luma_minus8 = 4; + sps.bit_depth_chroma_minus8 = 4; + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), -EINVAL); + sps.bit_depth_luma_minus8 = 2; + sps.bit_depth_chroma_minus8 = 0; + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), -EINVAL); +} + +struct avd_hevc_tiles_case { + const char *desc; + bool uniform; + u8 cols_minus1; + u8 rows_minus1; + u8 col_width_minus1[2]; + u8 row_height_minus1[2]; + int ret; + /* tile id of every CTB in tile scan order, if accepted */ + u32 ids[16]; +}; + +static const struct avd_hevc_tiles_case avd_hevc_tiles_cases[] = { + { "explicit 2x2 tiles", false, 1, 1, { 0 }, { 1 }, 0, + { 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3 } }, + { "explicit 3x1 tiles", false, 2, 0, { 1, 0 }, { 0 }, 0, + { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2 } }, + { "uniform 3x1 tiles", true, 2, 0, { 0 }, { 0 }, 0, + { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2 } }, + { "uniform 4x4 tiles", true, 3, 3, { 0 }, { 0 }, 0, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } }, + { "explicit columns leave the last one empty", false, 1, 0, { 3 }, + { 0 }, -EINVAL }, + { "explicit columns wider than the picture", false, 1, 0, { 4 }, + { 0 }, -EINVAL }, + { "explicit columns far wider than the picture", false, 2, 0, + { 200, 200 }, { 0 }, -EINVAL }, + { "explicit rows taller than the picture", false, 0, 1, { 0 }, + { 4 }, -EINVAL }, + { "explicit rows leave the last one empty", false, 0, 2, { 0 }, + { 1, 1 }, -EINVAL }, + { "uniform, more columns than CTBs", true, 4, 0, { 0 }, { 0 }, + -EINVAL }, + { "uniform, more rows than CTBs", true, 0, 4, { 0 }, { 0 }, + -EINVAL }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_hevc_tiles, avd_hevc_tiles_cases, desc); + +static void avd_hevc_tiles_test(struct kunit *test) +{ + const struct avd_hevc_tiles_case *c = test->param_value; + struct v4l2_ctrl_hevc_sps sps; + struct v4l2_ctrl_hevc_pps pps = { + .flags = V4L2_HEVC_PPS_FLAG_TILES_ENABLED | + (c->uniform ? V4L2_HEVC_PPS_FLAG_UNIFORM_SPACING : 0), + .num_tile_columns_minus1 = c->cols_minus1, + .num_tile_rows_minus1 = c->rows_minus1, + }; + u32 ids[16]; + + avd_hevc_test_sps(&sps); + memcpy(pps.column_width_minus1, c->col_width_minus1, + sizeof(c->col_width_minus1)); + memcpy(pps.row_height_minus1, c->row_height_minus1, + sizeof(c->row_height_minus1)); + + KUNIT_EXPECT_EQ(test, avd_hevc_check_tiles(&sps, &pps), c->ret); + + /* The table builder must refuse the same layouts, before any write. */ + memset(ids, 0xff, sizeof(ids)); + KUNIT_ASSERT_EQ(test, + avd_hevc_kunit_compute_tiles(&sps, &pps, ids, + ARRAY_SIZE(ids)), + c->ret); + if (!c->ret) + KUNIT_EXPECT_MEMEQ(test, ids, c->ids, sizeof(ids)); +} + +/* + * More tile columns or rows than the PPS control has size entries for are + * refused by the check itself, even for a picture wide or tall enough. + */ +static void avd_hevc_tiles_array_test(struct kunit *test) +{ + struct v4l2_ctrl_hevc_sps sps; + struct v4l2_ctrl_hevc_pps pps = { + .flags = V4L2_HEVC_PPS_FLAG_TILES_ENABLED | + V4L2_HEVC_PPS_FLAG_UNIFORM_SPACING, + }; + + avd_hevc_test_sps(&sps); + sps.pic_width_in_luma_samples = 8192; + sps.pic_height_in_luma_samples = 4320; + + pps.num_tile_columns_minus1 = ARRAY_SIZE(pps.column_width_minus1) - 1; + pps.num_tile_rows_minus1 = ARRAY_SIZE(pps.row_height_minus1) - 1; + KUNIT_EXPECT_EQ(test, avd_hevc_check_tiles(&sps, &pps), 0); + + pps.num_tile_columns_minus1 = ARRAY_SIZE(pps.column_width_minus1); + KUNIT_EXPECT_EQ(test, avd_hevc_check_tiles(&sps, &pps), -EINVAL); + + pps.num_tile_columns_minus1 = ARRAY_SIZE(pps.column_width_minus1) - 1; + pps.num_tile_rows_minus1 = ARRAY_SIZE(pps.row_height_minus1); + KUNIT_EXPECT_EQ(test, avd_hevc_check_tiles(&sps, &pps), -EINVAL); +} + +static void avd_hevc_no_tiles_test(struct kunit *test) +{ + struct v4l2_ctrl_hevc_sps sps; + struct v4l2_ctrl_hevc_pps pps = {}; + u32 ids[16]; + + avd_hevc_test_sps(&sps); + KUNIT_EXPECT_EQ(test, avd_hevc_check_tiles(&sps, &pps), 0); + KUNIT_EXPECT_EQ(test, + avd_hevc_kunit_compute_tiles(&sps, &pps, ids, + ARRAY_SIZE(ids)), + 0); +} + +struct avd_hevc_slices_case { + const char *desc; + bool tiles; + u8 type; + u32 flags; + u32 addr; + u8 col_idx; + u8 l0_last; + u8 l0_ref; + u32 bytes; + u32 data_offset; + u32 num_entry_points; + u32 entry_point; + u32 available_entry_points; + u32 payload; + int ret; +}; + +#define AVD_TMVP V4L2_HEVC_SLICE_PARAMS_FLAG_SLICE_TEMPORAL_MVP_ENABLED + +static const struct avd_hevc_slices_case avd_hevc_slices_cases[] = { + { "I slice at the first CTB", .type = V4L2_HEVC_SLICE_TYPE_I, + .bytes = 100, .data_offset = 10, .payload = 100 }, + { "I slice at the last CTB", .type = V4L2_HEVC_SLICE_TYPE_I, + .addr = 15, .bytes = 100, .data_offset = 10, .payload = 100 }, + { "slice address past the picture", .type = V4L2_HEVC_SLICE_TYPE_I, + .addr = 16, .bytes = 100, .payload = 100, .ret = -EINVAL }, + { "slice address far past the picture", .type = V4L2_HEVC_SLICE_TYPE_I, + .addr = U32_MAX, .bytes = 100, .payload = 100, .ret = -EINVAL }, + { "slice data ends one byte after the payload", + .type = V4L2_HEVC_SLICE_TYPE_I, .bytes = 100, .data_offset = 10, + .payload = 99, .ret = -EINVAL }, + { "slice header longer than the slice", .type = V4L2_HEVC_SLICE_TYPE_I, + .bytes = 10, .data_offset = 11, .payload = 100, .ret = -EINVAL }, + { "payload beyond the 31-bit range", .type = V4L2_HEVC_SLICE_TYPE_I, + .bytes = 100, .payload = U32_MAX, .ret = -EINVAL }, + { "P slice, collocated picture in the list", + .type = V4L2_HEVC_SLICE_TYPE_P, .flags = AVD_TMVP, .col_idx = 1, + .l0_last = 1, .l0_ref = 15, .bytes = 100, .payload = 100 }, + { "P slice, collocated index past the active list", + .type = V4L2_HEVC_SLICE_TYPE_P, .flags = AVD_TMVP, .col_idx = 2, + .l0_last = 1, .bytes = 100, .payload = 100, .ret = -EINVAL }, + { "P slice without TMVP, unused collocated index", + .type = V4L2_HEVC_SLICE_TYPE_P, .col_idx = 2, .l0_last = 1, + .bytes = 100, .payload = 100 }, + { "P slice, collocated index past the list array", + .type = V4L2_HEVC_SLICE_TYPE_P, .col_idx = 16, .l0_last = 15, + .bytes = 100, .payload = 100, .ret = -EINVAL }, + { "P slice, missing reference marked past the DPB", + .type = V4L2_HEVC_SLICE_TYPE_P, .l0_ref = 255, .bytes = 100, + .payload = 100 }, + { "B slice, missing L1 reference marked past the DPB", + .type = V4L2_HEVC_SLICE_TYPE_B, .l0_ref = 255, .bytes = 100, + .payload = 100 }, + { "two tiles, entry point inside the slice", .tiles = true, + .type = V4L2_HEVC_SLICE_TYPE_I, .bytes = 100, .data_offset = 10, + .num_entry_points = 1, .entry_point = 40, + .available_entry_points = 1, .payload = 100 }, + { "two tiles, entry point past the payload", .tiles = true, + .type = V4L2_HEVC_SLICE_TYPE_I, .bytes = 100, .data_offset = 10, + .num_entry_points = 1, .entry_point = 91, + .available_entry_points = 1, .payload = 100, .ret = -EINVAL }, + { "two tiles, entry point far past the payload", .tiles = true, + .type = V4L2_HEVC_SLICE_TYPE_I, .bytes = 100, .data_offset = 10, + .num_entry_points = 1, .entry_point = U32_MAX, + .available_entry_points = 1, .payload = 100, .ret = -EINVAL }, + { "two tiles, more entry points than given", .tiles = true, + .type = V4L2_HEVC_SLICE_TYPE_I, .bytes = 100, .data_offset = 10, + .num_entry_points = 2, .entry_point = 40, + .available_entry_points = 1, .payload = 100, .ret = -EINVAL }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_hevc_slices, avd_hevc_slices_cases, desc); + +static void avd_hevc_slices_test(struct kunit *test) +{ + const struct avd_hevc_slices_case *c = test->param_value; + struct v4l2_ctrl_hevc_decode_params *decode; + struct v4l2_ctrl_hevc_slice_params *sl; + struct v4l2_ctrl_hevc_sps sps; + struct v4l2_ctrl_hevc_pps pps = {}; + u32 ep[2] = { c->entry_point, c->entry_point }; + + decode = kunit_kzalloc(test, sizeof(*decode), GFP_KERNEL); + sl = kunit_kzalloc(test, sizeof(*sl), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, decode); + KUNIT_ASSERT_NOT_NULL(test, sl); + + avd_hevc_test_sps(&sps); + if (c->tiles) { + pps.flags = V4L2_HEVC_PPS_FLAG_TILES_ENABLED | + V4L2_HEVC_PPS_FLAG_UNIFORM_SPACING; + pps.num_tile_columns_minus1 = 1; + } + decode->num_active_dpb_entries = 2; + sl->slice_type = c->type; + sl->flags = c->flags; + sl->slice_segment_addr = c->addr; + sl->collocated_ref_idx = c->col_idx; + sl->num_ref_idx_l0_active_minus1 = c->l0_last; + sl->num_ref_idx_l1_active_minus1 = c->l0_last; + memset(sl->ref_idx_l0, c->l0_ref, sizeof(sl->ref_idx_l0)); + memset(sl->ref_idx_l1, c->l0_ref, sizeof(sl->ref_idx_l1)); + sl->bit_size = c->bytes * 8; + sl->data_byte_offset = c->data_offset; + sl->num_entry_point_offsets = c->num_entry_points; + + KUNIT_EXPECT_EQ(test, + avd_hevc_check_slices(&sps, &pps, decode, sl, 1, ep, + c->available_entry_points, + c->payload), + c->ret); +} + +/* A slice only fits after the ones before it. */ +static void avd_hevc_two_slices_test(struct kunit *test) +{ + struct v4l2_ctrl_hevc_decode_params *decode; + struct v4l2_ctrl_hevc_slice_params *sl; + struct v4l2_ctrl_hevc_sps sps; + struct v4l2_ctrl_hevc_pps pps = {}; + u32 ep = 0; + + decode = kunit_kzalloc(test, sizeof(*decode), GFP_KERNEL); + sl = kunit_kcalloc(test, 2, sizeof(*sl), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, decode); + KUNIT_ASSERT_NOT_NULL(test, sl); + + avd_hevc_test_sps(&sps); + sl[0].slice_type = V4L2_HEVC_SLICE_TYPE_I; + sl[0].bit_size = 60 * 8; + sl[0].data_byte_offset = 5; + sl[1] = sl[0]; + sl[1].slice_segment_addr = 8; + + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 2, + &ep, 1, 120), 0); + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 2, + &ep, 1, 119), -EINVAL); +} + +/* + * The entry point offsets split a slice's data into its tiles; the last tile + * takes what the others leave. Offsets that add up to more than the slice + * holds leave it less than nothing, even when each one fits the payload. + */ +static void avd_hevc_entry_points_sum_test(struct kunit *test) +{ + struct v4l2_ctrl_hevc_decode_params *decode; + struct v4l2_ctrl_hevc_slice_params *sl; + struct v4l2_ctrl_hevc_sps sps; + struct v4l2_ctrl_hevc_pps pps = { + .flags = V4L2_HEVC_PPS_FLAG_TILES_ENABLED | + V4L2_HEVC_PPS_FLAG_UNIFORM_SPACING, + .num_tile_columns_minus1 = 3, + }; + u32 ep[6] = { 20, 20, 20, 20, 20, 20 }; + + decode = kunit_kzalloc(test, sizeof(*decode), GFP_KERNEL); + sl = kunit_kcalloc(test, 2, sizeof(*sl), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, decode); + KUNIT_ASSERT_NOT_NULL(test, sl); + + avd_hevc_test_sps(&sps); + sl[0].slice_type = V4L2_HEVC_SLICE_TYPE_I; + sl[0].bit_size = 100 * 8; + sl[0].data_byte_offset = 10; + sl[0].num_entry_point_offsets = 3; + sl[1] = sl[0]; + sl[1].slice_segment_addr = 8; + + /* 10 header bytes, three tiles of 20 bytes and a last one of 30. */ + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 1, + ep, 3, 100), 0); + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 2, + ep, 6, 200), 0); + + /* One byte more than the 90 data bytes of the slice. */ + ep[0] = 30; + ep[1] = 30; + ep[2] = 31; + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 1, + ep, 3, 100), -EINVAL); + /* + * The same in the first of two slices: every offset and their sum + * stay inside the payload, but not inside the slice. + */ + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 2, + ep, 6, 200), -EINVAL); + + /* And in the second slice. */ + ep[0] = 20; + ep[1] = 20; + ep[2] = 20; + ep[5] = 51; + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 2, + ep, 6, 200), -EINVAL); +} + +static struct kunit_case avd_hevc_test_cases[] = { + KUNIT_CASE_PARAM(avd_hevc_geometry_test, avd_hevc_geometry_gen_params), + KUNIT_CASE(avd_hevc_sps_fmt_init_test), + KUNIT_CASE_PARAM(avd_hevc_tiles_test, avd_hevc_tiles_gen_params), + KUNIT_CASE(avd_hevc_tiles_array_test), + KUNIT_CASE(avd_hevc_no_tiles_test), + KUNIT_CASE_PARAM(avd_hevc_slices_test, avd_hevc_slices_gen_params), + KUNIT_CASE(avd_hevc_two_slices_test), + KUNIT_CASE(avd_hevc_entry_points_sum_test), + {} +}; + +static struct kunit_suite avd_hevc_test_suite = { + .name = "apple-avd-hevc", + .test_cases = avd_hevc_test_cases, +}; + +kunit_test_suite(avd_hevc_test_suite); diff --git a/drivers/media/platform/apple/avd/avd-hevc.c b/drivers/media/platform/apple/avd/avd-hevc.c index 04d43b759f0d73..c72e4371f76ebd 100644 --- a/drivers/media/platform/apple/avd/avd-hevc.c +++ b/drivers/media/platform/apple/avd/avd-hevc.c @@ -13,6 +13,7 @@ * Tomasz Figa */ +#include #include #include "avd.h" @@ -598,8 +599,9 @@ static void stream_slice_mv(struct avd_ctx *ctx, struct avd_hevc_run *run, { const struct v4l2_ctrl_hevc_decode_params *decode = run->decode; struct avd_decoded_buffer *dst, *ref; - bool ref_valid; + bool ref_valid, col_in_dpb; const u8 *ref_list; + u8 col; if (sl->slice_type == V4L2_HEVC_SLICE_TYPE_I) { push(AVD_OP_SL_REF | @@ -616,11 +618,17 @@ static void stream_slice_mv(struct avd_ctx *ctx, struct avd_hevc_run *run, sl->ref_idx_l1; dst = vb2_to_avd_decoded_buf(&run->base.bufs.dst->vb2_buf); - ref = avd_get_ref_buf( - ctx, &dst->base.vb, - decode->dpb[ref_list[sl->collocated_ref_idx]].timestamp); + /* + * Clients mark a reference they do not have with an index past the + * DPB (0xff); there is no collocated picture to take MVs from then. + */ + col = ref_list[sl->collocated_ref_idx]; + col_in_dpb = col < ARRAY_SIZE(decode->dpb); + ref = col_in_dpb ? + avd_get_ref_buf(ctx, &dst->base.vb, decode->dpb[col].timestamp) : + dst; - ref_valid = !(sl->flags & + ref_valid = col_in_dpb && !(sl->flags & V4L2_HEVC_SLICE_PARAMS_FLAG_DEPENDENT_SLICE_SEGMENT) && (sl->flags & V4L2_HEVC_SLICE_PARAMS_FLAG_SLICE_TEMPORAL_MVP_ENABLED) && @@ -661,8 +669,7 @@ static void stream_slice_mv(struct avd_ctx *ctx, struct avd_hevc_run *run, mv_color_size(fmt_width(ctx), fmt_height(ctx)), AVD_ALIGN); pusha(mv_color_addr, "slc_bd4_sps_tile_addr2_lsb8", - decode->dpb[ref_list[sl->collocated_ref_idx]] - .pic_order_cnt_val); + decode->dpb[col].pic_order_cnt_val); } } @@ -832,20 +839,25 @@ static void compute_rs_to_ts(struct avd_hevc_run *run, u32 pic_in_ctbs_size, } } -static void compute_tile_ids(struct avd_hevc_run *run, u32 pic_in_ctbs_width, - u32 *col_bd, u32 *row_bd, u32 *ctb_addr_rs_to_ts, - u32 *tile_ids) +static void compute_tile_ids(struct avd_hevc_run *run, u32 pic_in_ctbs_size, + u32 pic_in_ctbs_width, u32 *col_bd, u32 *row_bd, + u32 *ctb_addr_rs_to_ts, u32 *tile_ids) { const struct v4l2_ctrl_hevc_pps *pps = run->pps; int j, i, y, x; - u32 tile_idx; + u32 tile_idx, rs, ts; + for (j = 0, tile_idx = 0; j <= pps->num_tile_rows_minus1; j++) for (i = 0; i <= pps->num_tile_columns_minus1; i++, tile_idx++) for (y = row_bd[j]; y < row_bd[j + 1]; y++) - for (x = col_bd[i]; x < col_bd[i + 1]; x++) - tile_ids[ctb_addr_rs_to_ts - [y * pic_in_ctbs_width + - x]] = tile_idx; + for (x = col_bd[i]; x < col_bd[i + 1]; x++) { + rs = y * pic_in_ctbs_width + x; + if (rs >= pic_in_ctbs_size) + continue; + ts = ctb_addr_rs_to_ts[rs]; + if (ts < pic_in_ctbs_size) + tile_ids[ts] = tile_idx; + } } struct sl_ctx { @@ -952,6 +964,10 @@ static int stream_slices(struct avd_ctx *ctx, struct avd_hevc_run *run) row = pos / num_cols; col = pos % num_cols; + /* More tiles than the boundary tables describe */ + if (tiles_enabled && (slice_flag & NEW_TILE_ID) && + row + 1 >= ARRAY_SIZE(tile_info->row_bd)) + return -EINVAL; /* * not a fan of this, in JCT-VC-HEVC_V1 only TILES_B_Cisco_1 @@ -1022,14 +1038,9 @@ static void avd_hevc_adjust_decoded_fmt(struct avd_ctx *ctx, mv_color_size(pix_mp->width, pix_mp->height); } -static enum avd_image_fmt avd_hevc_get_image_fmt(struct avd_ctx *ctx, - struct v4l2_ctrl *ctrl) +static enum avd_image_fmt +avd_hevc_sps_image_fmt(const struct v4l2_ctrl_hevc_sps *sps) { - const struct v4l2_ctrl_hevc_sps *sps = ctrl->p_new.p_hevc_sps; - - if (ctrl->id != V4L2_CID_STATELESS_HEVC_SPS) - return AVD_IMG_FMT_ANY; - /* avd_hevc_validate_sps() refuses 4:4:4 and depths other than 8/10. */ if (sps->bit_depth_luma_minus8 == 0) { if (sps->chroma_format_idc == 2) @@ -1046,9 +1057,166 @@ static enum avd_image_fmt avd_hevc_get_image_fmt(struct avd_ctx *ctx, return AVD_IMG_FMT_ANY; } -static int avd_hevc_validate_sps(struct avd_ctx *ctx, - const struct v4l2_ctrl_hevc_sps *sps) +static enum avd_image_fmt avd_hevc_get_image_fmt(struct avd_ctx *ctx, + struct v4l2_ctrl *ctrl) +{ + if (ctrl->id != V4L2_CID_STATELESS_HEVC_SPS) + return AVD_IMG_FMT_ANY; + + return avd_hevc_sps_image_fmt(ctrl->p_new.p_hevc_sps); +} + +/* + * The picture must have at least one sample in each direction and the CTB + * size must be one of those H.265 allows (CtbLog2SizeY 4 to 6, 7.4.3.2.1): + * the picture size in CTBs sizes the tile tables and divides slice addresses. + */ +VISIBLE_IF_KUNIT int +avd_hevc_check_sps_geometry(const struct v4l2_ctrl_hevc_sps *sps) +{ + unsigned int ctb_log2 = sps->log2_min_luma_coding_block_size_minus3 + 3 + + sps->log2_diff_max_min_luma_coding_block_size; + + if (!sps->pic_width_in_luma_samples || !sps->pic_height_in_luma_samples) + return -EINVAL; + if (ctb_log2 < 4 || ctb_log2 > 6) + return -EINVAL; + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_hevc_check_sps_geometry); + +static void avd_hevc_pic_in_ctbs(const struct v4l2_ctrl_hevc_sps *sps, + u32 *width, u32 *height) +{ + u32 ctb = 1 << (sps->log2_min_luma_coding_block_size_minus3 + 3 + + sps->log2_diff_max_min_luma_coding_block_size); + + *width = DIV_ROUND_UP(sps->pic_width_in_luma_samples, ctb); + *height = DIV_ROUND_UP(sps->pic_height_in_luma_samples, ctb); +} + +/* + * The tile columns and rows must cover the picture, each at least one CTB + * wide or high (H.265 7.4.3.3.1). Explicitly sized tiles give all but the + * last width and height; the last one takes the rest and must not be empty. + * avd_hevc_check_sps_geometry() must have accepted the SPS. + */ +VISIBLE_IF_KUNIT int avd_hevc_check_tiles(const struct v4l2_ctrl_hevc_sps *sps, + const struct v4l2_ctrl_hevc_pps *pps) +{ + u32 width, height, sum; + int i; + + if (!(pps->flags & V4L2_HEVC_PPS_FLAG_TILES_ENABLED)) + return 0; + + if (pps->num_tile_columns_minus1 >= ARRAY_SIZE(pps->column_width_minus1) || + pps->num_tile_rows_minus1 >= ARRAY_SIZE(pps->row_height_minus1)) + return -EINVAL; + + avd_hevc_pic_in_ctbs(sps, &width, &height); + if (pps->num_tile_columns_minus1 >= width || + pps->num_tile_rows_minus1 >= height) + return -EINVAL; + if (pps->flags & V4L2_HEVC_PPS_FLAG_UNIFORM_SPACING) + return 0; + + for (i = 0, sum = 0; i < pps->num_tile_columns_minus1; i++) + sum += pps->column_width_minus1[i] + 1; + if (sum >= width) + return -EINVAL; + + for (i = 0, sum = 0; i < pps->num_tile_rows_minus1; i++) + sum += pps->row_height_minus1[i] + 1; + if (sum >= height) + return -EINVAL; + + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_hevc_check_tiles); + +/* + * Check what the slice builder takes from the slice parameters before it + * uses them: the slice address must be a CTB of the picture, the collocated + * reference must be an entry of its reference list (H.265 7.4.7.1), and + * every slice segment's data must lie in the payload. The + * segment layout is the one stream_slices() programs. + * avd_hevc_check_sps_geometry() must have accepted the SPS. + */ +VISIBLE_IF_KUNIT int +avd_hevc_check_slices(const struct v4l2_ctrl_hevc_sps *sps, + const struct v4l2_ctrl_hevc_pps *pps, + const struct v4l2_ctrl_hevc_decode_params *decode, + const struct v4l2_ctrl_hevc_slice_params *slices, + u32 num_slices, const u32 *entry_points, + u32 num_entry_points, u32 payload) +{ + bool tiles = pps->flags & V4L2_HEVC_PPS_FLAG_TILES_ENABLED; + u32 width, height, ep = 0, s, i, to; + s64 offset = 0, seg_offset, size, next; + + if (payload > INT_MAX) + return -EINVAL; + avd_hevc_pic_in_ctbs(sps, &width, &height); + + for (s = 0; s < num_slices; s++) { + const struct v4l2_ctrl_hevc_slice_params *sl = &slices[s]; + s64 bytes = sl->bit_size / 8; + + if (sl->slice_segment_addr >= width * height) + return -EINVAL; + + if (sl->slice_type != V4L2_HEVC_SLICE_TYPE_I) { + bool l0 = sl->slice_type == V4L2_HEVC_SLICE_TYPE_P || + sl->flags & + V4L2_HEVC_SLICE_PARAMS_FLAG_COLLOCATED_FROM_L0; + u8 last = l0 ? sl->num_ref_idx_l0_active_minus1 : + sl->num_ref_idx_l1_active_minus1; + + if (sl->collocated_ref_idx >= ARRAY_SIZE(sl->ref_idx_l0)) + return -EINVAL; + if ((sl->flags & + V4L2_HEVC_SLICE_PARAMS_FLAG_SLICE_TEMPORAL_MVP_ENABLED) && + sl->collocated_ref_idx > last) + return -EINVAL; + } + + to = tiles ? sl->num_entry_point_offsets + 1 : 1; + if (tiles && sl->num_entry_point_offsets > + num_entry_points - ep) + return -EINVAL; + + seg_offset = 0; + for (i = 0; i < to; i++) { + if (to > 1 && i < sl->num_entry_point_offsets) { + size = entry_points[ep++]; + next = size; + } else if (to > 1) { + size = bytes - sl->data_byte_offset - seg_offset; + next = size + sl->data_byte_offset; + } else { + size = bytes - sl->data_byte_offset; + next = size + sl->data_byte_offset; + } + if (size < 0 || + offset + seg_offset + sl->data_byte_offset + size > + payload) + return -EINVAL; + seg_offset += next; + } + offset += bytes; + } + + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_hevc_check_slices); + +VISIBLE_IF_KUNIT int +avd_hevc_validate_sps_fmt(struct avd_ctx *ctx, + const struct v4l2_ctrl_hevc_sps *sps) { + if (!sps->pic_width_in_luma_samples || !sps->pic_height_in_luma_samples) + return -EINVAL; if (sps->pic_width_in_luma_samples > ctx->coded_fmt.fmt.pix_mp.width || sps->pic_height_in_luma_samples > ctx->coded_fmt.fmt.pix_mp.height) return -EINVAL; @@ -1075,6 +1243,16 @@ static int avd_hevc_validate_sps(struct avd_ctx *ctx, return 0; } +EXPORT_SYMBOL_IF_KUNIT(avd_hevc_validate_sps_fmt); + +static int avd_hevc_validate_sps(struct avd_ctx *ctx, + const struct v4l2_ctrl_hevc_sps *sps) +{ + if (avd_hevc_check_sps_geometry(sps)) + return -EINVAL; + + return avd_hevc_validate_sps_fmt(ctx, sps); +} static int avd_hevc_alloc_bufs(struct avd_ctx *ctx, struct avd_hevc_bank *bank) { @@ -1292,6 +1470,9 @@ static int avd_hevc_compute_tiles(struct avd_ctx *ctx, struct avd_hevc_run *run) tiles_enabled = !!(pps->flags & V4L2_HEVC_PPS_FLAG_TILES_ENABLED); + if (avd_hevc_check_tiles(sps, pps)) + return -EINVAL; + tile_info->ctb_addr_rs_to_ts = kzalloc( sizeof(*tile_info->ctb_addr_rs_to_ts) * pic_in_ctbs_size, GFP_KERNEL); @@ -1332,7 +1513,8 @@ static int avd_hevc_compute_tiles(struct avd_ctx *ctx, struct avd_hevc_run *run) tile_info->col_bd, tile_info->row_bd, tile_info->col_width, tile_info->row_height, tile_info->ctb_addr_rs_to_ts); - compute_tile_ids(run, pic_in_ctbs_width, tile_info->col_bd, + compute_tile_ids(run, pic_in_ctbs_size, pic_in_ctbs_width, + tile_info->col_bd, tile_info->row_bd, tile_info->ctb_addr_rs_to_ts, tile_info->tile_ids); @@ -1346,6 +1528,36 @@ static int avd_hevc_compute_tiles(struct avd_ctx *ctx, struct avd_hevc_run *run) return 0; } +#if IS_ENABLED(CONFIG_KUNIT) +/* Build the tile tables of a picture and copy out tile_ids in tile scan order. */ +int avd_hevc_kunit_compute_tiles(const struct v4l2_ctrl_hevc_sps *sps, + const struct v4l2_ctrl_hevc_pps *pps, + u32 *tile_ids, size_t n) +{ + struct avd_hevc_run *run; + u32 width, height; + int ret; + + run = kzalloc(sizeof(*run), GFP_KERNEL); + if (!run) + return -ENOMEM; + run->sps = sps; + run->pps = pps; + ret = avd_hevc_compute_tiles(NULL, run); + if (!ret) { + avd_hevc_pic_in_ctbs(sps, &width, &height); + memcpy(tile_ids, run->tile_info.tile_ids, + min_t(size_t, n, (size_t)width * height) * + sizeof(*tile_ids)); + } + kfree(run->tile_info.ctb_addr_rs_to_ts); + kfree(run->tile_info.tile_ids); + kfree(run); + return ret; +} +EXPORT_SYMBOL_IF_KUNIT(avd_hevc_kunit_compute_tiles); +#endif + /* * The slice builder below expects the GStreamer layout: the slices tile the * OUTPUT buffer as whole NALs, bit_size covers the whole NAL and @@ -1391,9 +1603,34 @@ static void avd_hevc_normalize_slices(struct avd_hevc_run *run, u32 payload) } } +/* + * A copy of a control's current value. The caller holds the control lock, + * so the control must have been looked up before (v4l2_ctrl_find() takes + * that lock too). + */ +static void *avd_hevc_ctrl_dup(struct v4l2_ctrl *ctrl) +{ + if (!ctrl) + return NULL; + return kmemdup(ctrl->p_cur.p, ctrl->elems * ctrl->elem_size, + GFP_KERNEL); +} + +static void avd_hevc_free_run(struct avd_hevc_run *run) +{ + kfree(run->tile_info.ctb_addr_rs_to_ts); + kfree(run->tile_info.tile_ids); + kfree(run->sl); + kfree(run->entry_point_offsets); + kfree(run->decode); + kfree(run->sps); + kfree(run->pps); + kfree(run->scaling_matrix); +} + static int avd_hevc_run_preamble(struct avd_ctx *ctx, struct avd_hevc_run *run) { - struct v4l2_ctrl *ctrl, *sl, *ep; + struct v4l2_ctrl *sl, *ep, *decode, *sps, *pps, *scaling; u32 dst_len, mv_color_len; if (!v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_SLICE_PARAMS) || @@ -1411,20 +1648,15 @@ static int avd_hevc_run_preamble(struct avd_ctx *ctx, struct avd_hevc_run *run) if (run->base.setup_err) return run->base.setup_err; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_HEVC_DECODE_PARAMS); - run->decode = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_SPS); - run->sps = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_PPS); - run->pps = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_HEVC_SCALING_MATRIX); - run->scaling_matrix = ctrl ? ctrl->p_cur.p : NULL; - sl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_SLICE_PARAMS); ep = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_ENTRY_POINT_OFFSETS); + decode = v4l2_ctrl_find(&ctx->ctrl_hdl, + V4L2_CID_STATELESS_HEVC_DECODE_PARAMS); + sps = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_SPS); + pps = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_PPS); + scaling = v4l2_ctrl_find(&ctx->ctrl_hdl, + V4L2_CID_STATELESS_HEVC_SCALING_MATRIX); /* * Setting a larger dynamic array on a queued request reallocates the @@ -1432,15 +1664,24 @@ static int avd_hevc_run_preamble(struct avd_ctx *ctx, struct avd_hevc_run *run) * the run needs while holding the control lock. */ v4l2_ctrl_lock(sl); + /* + * A plain VIDIOC_S_EXT_CTRLS can also change the picture controls + * while the job is built. The checks below and the builder must see + * the same values, so take copies of those too. + */ + run->decode = avd_hevc_ctrl_dup(decode); + run->sps = avd_hevc_ctrl_dup(sps); + run->pps = avd_hevc_ctrl_dup(pps); + run->scaling_matrix = avd_hevc_ctrl_dup(scaling); run->num_slices = sl->elems; run->sl = kmemdup(sl->p_cur.p, sl->elems * sl->elem_size, GFP_KERNEL); run->num_entry_point_offsets = ep->elems; run->entry_point_offsets = kmemdup(ep->p_cur.p, ep->elems * ep->elem_size, GFP_KERNEL); v4l2_ctrl_unlock(sl); - if (!run->sl || !run->entry_point_offsets) { - kfree(run->sl); - kfree(run->entry_point_offsets); + if (!run->sl || !run->entry_point_offsets || !run->decode || + !run->sps || !run->pps || !run->scaling_matrix) { + avd_hevc_free_run(run); avd_run_postamble(ctx, &run->base); return -ENOMEM; } @@ -1459,6 +1700,7 @@ static int avd_hevc_run(struct avd_ctx *ctx) struct avd_hevc_ctx *hevc_ctx = ctx->priv; struct avd_hevc_run run = {}; struct avd_decoded_buffer *dst; + u32 payload; int ret; ret = avd_hevc_run_preamble(ctx, &run); @@ -1467,11 +1709,19 @@ static int avd_hevc_run(struct avd_ctx *ctx) /* Also validate controls applied from a queued request before submission. */ ret = avd_hevc_validate_sps(ctx, run.sps); + if (!ret) + ret = avd_check_run_image_fmt(ctx, + avd_hevc_sps_image_fmt(run.sps)); if (ret) goto complete; - avd_hevc_normalize_slices(&run, - vb2_get_plane_payload(&run.base.bufs.src->vb2_buf, 0)); + payload = vb2_get_plane_payload(&run.base.bufs.src->vb2_buf, 0); + avd_hevc_normalize_slices(&run, payload); + ret = avd_hevc_check_slices(run.sps, run.pps, run.decode, run.sl, + run.num_slices, run.entry_point_offsets, + run.num_entry_point_offsets, payload); + if (ret) + goto complete; dst = vb2_to_avd_decoded_buf(&run.base.bufs.dst->vb2_buf); update_dec_buf_info(dst, &run.sl[0]); @@ -1505,17 +1755,33 @@ static int avd_hevc_run(struct avd_ctx *ctx) /* The request was applied; complete it on every way out. */ avd_run_postamble(ctx, &run.base); done: - kfree(run.tile_info.ctb_addr_rs_to_ts); - kfree(run.tile_info.tile_ids); - kfree(run.sl); - kfree(run.entry_point_offsets); + avd_hevc_free_run(&run); return ret; } static int avd_hevc_try_ctrl(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { - if (ctrl->id == V4L2_CID_STATELESS_HEVC_SPS) - return avd_hevc_validate_sps(ctx, ctrl->p_new.p_hevc_sps); + if (ctrl->id == V4L2_CID_STATELESS_HEVC_SPS) { + const struct v4l2_ctrl_hevc_sps *sps = ctrl->p_new.p_hevc_sps; + struct vb2_queue *vq = + ctx->fh.m2m_ctx ? + v4l2_m2m_get_vq(ctx->fh.m2m_ctx, + V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) : + NULL; + + /* + * Pre-streaming format negotiation (e.g. Chromium + * SetExtCtrlsInit) populates dimensions, chroma format and bit + * depth while leaving CTB size fields zeroed. Defer the CTB + * geometry check until streaming / avd_hevc_run(). + */ + if ((!vq || !vb2_is_streaming(vq)) && + !sps->log2_min_luma_coding_block_size_minus3 && + !sps->log2_diff_max_min_luma_coding_block_size) + return avd_hevc_validate_sps_fmt(ctx, sps); + + return avd_hevc_validate_sps(ctx, sps); + } return 0; } diff --git a/drivers/media/platform/apple/avd/avd-inst.h b/drivers/media/platform/apple/avd/avd-inst.h index dcdb205d793156..d35efe68ebd510 100644 --- a/drivers/media/platform/apple/avd/avd-inst.h +++ b/drivers/media/platform/apple/avd/avd-inst.h @@ -169,14 +169,24 @@ static inline bool boolify(u32 v) static inline void push(struct avd_ctx *ctx, u32 inst) { struct avd_job *job = &ctx->job; - struct avd_segment *seg = &job->segments[job->num]; + struct avd_segment *seg; + + if (job->num >= job->max) { + job->overflow = true; + return; + } + seg = &job->segments[job->num]; + if (seg->num >= AVD_MAX_INST) { + job->overflow = true; + return; + } seg->instructions[seg->num++] = inst; } static inline void push_address(struct avd_ctx *ctx, dma_addr_t addr) { if (ctx->dev->variant->quirks & AVD_QUIRK_LSR) { - push(ctx, (addr >> 8)); + push(ctx, (u32)((addr >> 8) & 0xffffffff)); } else { push(ctx, (u32)(addr & 0xffffffff)); push(ctx, (u32)(addr >> 32)); diff --git a/drivers/media/platform/apple/avd/avd-job-test.c b/drivers/media/platform/apple/avd/avd-job-test.c new file mode 100644 index 00000000000000..8263cddfd88ec8 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-job-test.c @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the instruction job table of the Apple video decoder. + */ + +#include + +#include "avd.h" +#include "avd-inst.h" + +static void avd_job_free(void *data) +{ + struct avd_ctx *ctx = data; + + kvfree(ctx->job.segments); +} + +static struct avd_ctx *avd_job_test_ctx(struct kunit *test, size_t segments) +{ + struct avd_ctx *ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, ctx); + KUNIT_ASSERT_EQ(test, avd_init_job(ctx, AVD_CODEC_H264, segments), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, avd_job_free, ctx), + 0); + KUNIT_EXPECT_EQ(test, ctx->job.max, segments); + KUNIT_EXPECT_FALSE(test, ctx->job.overflow); + return ctx; +} + +/* A full segment takes no more instructions. */ +static void avd_job_segment_full_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_job_test_ctx(test, 2); + int i; + + for (i = 0; i < AVD_MAX_INST; i++) + push(i, "fill"); + KUNIT_EXPECT_EQ(test, ctx->job.segments[0].num, AVD_MAX_INST); + KUNIT_EXPECT_FALSE(test, ctx->job.overflow); + + push(0xdeadbeef, "one too many"); + KUNIT_EXPECT_EQ(test, ctx->job.segments[0].num, AVD_MAX_INST); + KUNIT_EXPECT_TRUE(test, ctx->job.overflow); + /* The next segment was not written either. */ + KUNIT_EXPECT_EQ(test, ctx->job.segments[1].num, 0); +} + +/* Segments past the allocated table are never written. */ +static void avd_job_table_full_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_job_test_ctx(test, 2); + int i; + + push(1, "header"); + ctx->job.num++; + push(2, "first segment"); + KUNIT_EXPECT_FALSE(test, ctx->job.overflow); + + for (i = 0; i < 8; i++) { + ctx->job.num++; + push(3, "past the table"); + } + KUNIT_EXPECT_TRUE(test, ctx->job.overflow); + KUNIT_EXPECT_EQ(test, ctx->job.segments[0].num, 1); + KUNIT_EXPECT_EQ(test, ctx->job.segments[1].num, 1); + + /* A new job starts clean. */ + KUNIT_ASSERT_EQ(test, avd_init_job(ctx, AVD_CODEC_H264, 1), 0); + KUNIT_EXPECT_FALSE(test, ctx->job.overflow); + KUNIT_EXPECT_EQ(test, ctx->job.max, 1); +} + +static struct kunit_case avd_job_test_cases[] = { + KUNIT_CASE(avd_job_segment_full_test), + KUNIT_CASE(avd_job_table_full_test), + {} +}; + +static struct kunit_suite avd_job_test_suite = { + .name = "apple-avd-job", + .test_cases = avd_job_test_cases, +}; + +kunit_test_suite(avd_job_test_suite); diff --git a/drivers/media/platform/apple/avd/avd-kopsia-tunables.h b/drivers/media/platform/apple/avd/avd-kopsia-tunables.h new file mode 100644 index 00000000000000..95fb2d6d4792a9 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-kopsia-tunables.h @@ -0,0 +1,350 @@ +/* SPDX-License-Identifier: MIT */ +/* avd-fw v5/tier2 table, Copyright The Asahi Linux Contributors. */ +static const struct avd_kopsia_tunable kopsia_tunables[] = { + {0x0008, 0x80000000, 0x80000000}, /* MCTL_MODE */ + {0x1000, 0x80000000, 0x80000000}, /* HEVC_MODE */ + {0x1100, 0x80000000, 0x80000000}, /* HEVC_MODE */ + {0x1200, 0x80000000, 0x80000000}, /* HEVC_MODE */ + {0x1300, 0x80000000, 0x80000000}, /* HEVC_MODE */ + {0x1400, 0x80000000, 0x80000000}, /* H264_MODE */ + {0x1500, 0x80000000, 0x80000000}, /* H264_MODE */ + {0x1600, 0x80000000, 0x80000000}, /* H264_MODE */ + {0x1700, 0x80000000, 0x80000000}, /* H264_MODE */ + {0x1800, 0x80000000, 0x80000000}, /* VP9_MODE */ + {0x1900, 0x80000000, 0x80000000}, /* AV1_MODE */ + {0x1a00, 0x80000000, 0x80000000}, /* AV1_MODE */ + {0x1b00, 0x80000000, 0x80000000}, /* AV1_MODE */ + {0x4000, 0x80000000, 0x80000000}, /* QT_MODE */ + {0x4100, 0x80000000, 0x80000000}, /* IPMC_MODE */ + {0x4200, 0x80000000, 0x80000000}, /* LF_MODE */ + {0x4300, 0x80000000, 0x80000000}, /* MV_MODE */ + {0x4400, 0x80000000, 0x80000000}, /* TP_MODE */ + {0x4500, 0x80000000, 0x80000000}, /* PC_MODE */ + {0x4600, 0x80000000, 0x80000000}, /* SW_MODE */ + {0x4700, 0x80000000, 0x80000000}, /* LR_MODE */ + {0xc000, 0x00000001, 0x00000001}, /* VP_TOP_CLOCK_GATING */ + {0xc080, 0x800f0000, 0x80020000}, /* R_HEVC_BITS */ + {0xc084, 0x1fff1fff, 0x00000028}, /* BUF */ + {0xc090, 0x000000ff, 0x00000001}, /* EXT */ + {0xc0c0, 0x800f0000, 0x80020000}, /* R_HEVC_BITS */ + {0xc0c4, 0x1fff1fff, 0x00280028}, /* BUF */ + {0xc0d0, 0x000000ff, 0x00000002}, /* EXT */ + {0xc100, 0x800f0000, 0x80020000}, /* R_HEVC_BITS */ + {0xc104, 0x1fff1fff, 0x00500028}, /* BUF */ + {0xc110, 0x000000ff, 0x00000003}, /* EXT */ + {0xc140, 0x800f0000, 0x80020000}, /* R_HEVC_BITS */ + {0xc144, 0x1fff1fff, 0x00780028}, /* BUF */ + {0xc150, 0x000000ff, 0x00000004}, /* EXT */ + {0xc180, 0x800f0000, 0x80010000}, /* W_HEVC_INSN */ + {0xc184, 0x0fff0fff, 0x00be0028}, /* BUF */ + {0xc190, 0x000000ff, 0x00000056}, /* EXT */ + {0xc1c0, 0x800f0000, 0x80010000}, /* W_HEVC_INSN */ + {0xc1c4, 0x0fff0fff, 0x00e60028}, /* BUF */ + {0xc1d0, 0x000000ff, 0x00000057}, /* EXT */ + {0xc200, 0x800f0000, 0x80010000}, /* W_HEVC_INSN */ + {0xc204, 0x0fff0fff, 0x010e0028}, /* BUF */ + {0xc210, 0x000000ff, 0x00000058}, /* EXT */ + {0xc240, 0x800f0000, 0x80010000}, /* W_HEVC_INSN */ + {0xc244, 0x0fff0fff, 0x01360028}, /* BUF */ + {0xc250, 0x000000ff, 0x00000059}, /* EXT */ + {0xc280, 0x800f0000, 0x80020000}, /* R_H264_BITS */ + {0xc284, 0x1fff1fff, 0x00a00020}, /* BUF */ + {0xc290, 0x000000ff, 0x0000000d}, /* EXT */ + {0xc2c0, 0x800f0000, 0x80020000}, /* R_H264_BITS */ + {0xc2c4, 0x1fff1fff, 0x00c00020}, /* BUF */ + {0xc2d0, 0x000000ff, 0x0000000e}, /* EXT */ + {0xc300, 0x800f0000, 0x80020000}, /* R_H264_BITS */ + {0xc304, 0x1fff1fff, 0x00e00020}, /* BUF */ + {0xc310, 0x000000ff, 0x0000000f}, /* EXT */ + {0xc340, 0x800f0000, 0x80020000}, /* R_H264_BITS */ + {0xc344, 0x1fff1fff, 0x01000020}, /* BUF */ + {0xc350, 0x000000ff, 0x00000010}, /* EXT */ + {0xc380, 0x800f0000, 0x80020000}, /* W_H264_ABOVE_INFO */ + {0xc384, 0x0fff0fff, 0x00000004}, /* BUF */ + {0xc390, 0x000000ff, 0x00000011}, /* EXT */ + {0xc3c0, 0x800f0000, 0x80020000}, /* W_H264_ABOVE_INFO */ + {0xc3c4, 0x0fff0fff, 0x00040004}, /* BUF */ + {0xc3d0, 0x000000ff, 0x00000012}, /* EXT */ + {0xc400, 0x800f0000, 0x80020000}, /* W_H264_ABOVE_INFO */ + {0xc404, 0x0fff0fff, 0x00080004}, /* BUF */ + {0xc410, 0x000000ff, 0x00000013}, /* EXT */ + {0xc440, 0x800f0000, 0x80020000}, /* W_H264_ABOVE_INFO */ + {0xc444, 0x0fff0fff, 0x000c0004}, /* BUF */ + {0xc450, 0x000000ff, 0x00000014}, /* EXT */ + {0xc480, 0x800f0000, 0x80020000}, /* R_H264_ABOVE_INFO */ + {0xc484, 0x1fff1fff, 0x01200006}, /* BUF */ + {0xc490, 0x000000ff, 0x00000015}, /* EXT */ + {0xc4c0, 0x800f0000, 0x80020000}, /* R_H264_ABOVE_INFO */ + {0xc4c4, 0x1fff1fff, 0x01260006}, /* BUF */ + {0xc4d0, 0x000000ff, 0x00000016}, /* EXT */ + {0xc500, 0x800f0000, 0x80020000}, /* R_H264_ABOVE_INFO */ + {0xc504, 0x1fff1fff, 0x012c0006}, /* BUF */ + {0xc510, 0x000000ff, 0x00000017}, /* EXT */ + {0xc540, 0x800f0000, 0x80020000}, /* R_H264_ABOVE_INFO */ + {0xc544, 0x1fff1fff, 0x01320006}, /* BUF */ + {0xc550, 0x000000ff, 0x00000018}, /* EXT */ + {0xc580, 0x800f0000, 0x80010000}, /* W_H264_INSN */ + {0xc584, 0x0fff0fff, 0x015e0020}, /* BUF */ + {0xc590, 0x000000ff, 0x0000005a}, /* EXT */ + {0xc5c0, 0x800f0000, 0x80010000}, /* W_H264_INSN */ + {0xc5c4, 0x0fff0fff, 0x017e0020}, /* BUF */ + {0xc5d0, 0x000000ff, 0x0000005b}, /* EXT */ + {0xc600, 0x800f0000, 0x80010000}, /* W_H264_INSN */ + {0xc604, 0x0fff0fff, 0x019e0020}, /* BUF */ + {0xc610, 0x000000ff, 0x0000005c}, /* EXT */ + {0xc640, 0x800f0000, 0x80010000}, /* W_H264_INSN */ + {0xc644, 0x0fff0fff, 0x01be0020}, /* BUF */ + {0xc650, 0x000000ff, 0x0000005d}, /* EXT */ + {0xc680, 0x800f0000, 0x80020000}, /* R_VP9_BITS */ + {0xc684, 0x1fff1fff, 0x01380018}, /* BUF */ + {0xc690, 0x000000ff, 0x00000021}, /* EXT */ + {0xc6c0, 0x800f0000, 0x80020000}, /* W_VP9_ABOVE_INFO */ + {0xc6c4, 0x0fff0fff, 0x0010000a}, /* BUF */ + {0xc6d0, 0x000000ff, 0x00000022}, /* EXT */ + {0xc700, 0x800f0000, 0x80020000}, /* R_VP9_ABOVE_INFO */ + {0xc704, 0x1fff1fff, 0x0150000e}, /* BUF */ + {0xc710, 0x000000ff, 0x00000023}, /* EXT */ + {0xc740, 0x800f0000, 0x80020000}, /* W_VP9_SEG */ + {0xc744, 0x0fff0fff, 0x001a000a}, /* BUF */ + {0xc750, 0x000000ff, 0x00000024}, /* EXT */ + {0xc780, 0x800f0000, 0x80020000}, /* R_VP9_SEG */ + {0xc784, 0x1fff1fff, 0x015e000a}, /* BUF */ + {0xc790, 0x000000ff, 0x00000025}, /* EXT */ + {0xc7c0, 0x800f0000, 0x80020000}, /* W_VP9_COLOR */ + {0xc7c4, 0x0fff0fff, 0x0024000c}, /* BUF */ + {0xc7d0, 0x000000ff, 0x00000026}, /* EXT */ + {0xc800, 0x800f0000, 0x80020000}, /* R_VP9_COLOR */ + {0xc804, 0x1fff1fff, 0x01680012}, /* BUF */ + {0xc810, 0x000000ff, 0x00000027}, /* EXT */ + {0xc840, 0x800f0000, 0x80020000}, /* W_VP9_STATE */ + {0xc844, 0x0fff0fff, 0x0030000a}, /* BUF */ + {0xc850, 0x000000ff, 0x00000028}, /* EXT */ + {0xc880, 0x800f0000, 0x80020000}, /* R_VP9_STATE */ + {0xc884, 0x1fff1fff, 0x017a000a}, /* BUF */ + {0xc890, 0x000000ff, 0x00000029}, /* EXT */ + {0xc8c0, 0x800f0000, 0x80010000}, /* W_VP9_INSN */ + {0xc8c4, 0x0fff0fff, 0x01de0018}, /* BUF */ + {0xc8d0, 0x000000ff, 0x0000005e}, /* EXT */ + {0xc900, 0x800f0000, 0x80020000}, /* R_AV1_BITS */ + {0xc904, 0x1fff1fff, 0x01840016}, /* BUF */ + {0xc910, 0x000000ff, 0x0000002a}, /* EXT */ + {0xc940, 0x800f0000, 0x80020000}, /* R_AV1_BITS */ + {0xc944, 0x1fff1fff, 0x019a0016}, /* BUF */ + {0xc950, 0x000000ff, 0x0000002b}, /* EXT */ + {0xc980, 0x800f0000, 0x80020000}, /* R_AV1_BITS */ + {0xc984, 0x1fff1fff, 0x01b00016}, /* BUF */ + {0xc990, 0x000000ff, 0x0000002c}, /* EXT */ + {0xca00, 0x800f0000, 0x80020000}, /* W_AV1_ABOVE_INFO */ + {0xca04, 0x0fff0fff, 0x003a000a}, /* BUF */ + {0xca10, 0x000000ff, 0x0000002e}, /* EXT */ + {0xca40, 0x800f0000, 0x80020000}, /* W_AV1_ABOVE_INFO */ + {0xca44, 0x0fff0fff, 0x0044000a}, /* BUF */ + {0xca50, 0x000000ff, 0x0000002f}, /* EXT */ + {0xca80, 0x800f0000, 0x80020000}, /* W_AV1_ABOVE_INFO */ + {0xca84, 0x0fff0fff, 0x004e000a}, /* BUF */ + {0xca90, 0x000000ff, 0x00000030}, /* EXT */ + {0xcb00, 0x800f0000, 0x80020000}, /* R_AV1_ABOVE_INFO */ + {0xcb04, 0x1fff1fff, 0x01c60014}, /* BUF */ + {0xcb10, 0x000000ff, 0x00000032}, /* EXT */ + {0xcb40, 0x800f0000, 0x80020000}, /* R_AV1_ABOVE_INFO */ + {0xcb44, 0x1fff1fff, 0x01da0014}, /* BUF */ + {0xcb50, 0x000000ff, 0x00000033}, /* EXT */ + {0xcb80, 0x800f0000, 0x80020000}, /* R_AV1_ABOVE_INFO */ + {0xcb84, 0x1fff1fff, 0x01ee0014}, /* BUF */ + {0xcb90, 0x000000ff, 0x00000034}, /* EXT */ + {0xcc00, 0x800f0000, 0x80020000}, /* W_AV1_SEG */ + {0xcc04, 0x0fff0fff, 0x00580004}, /* BUF */ + {0xcc10, 0x000000ff, 0x00000036}, /* EXT */ + {0xcc40, 0x800f0000, 0x80020000}, /* W_AV1_SEG */ + {0xcc44, 0x0fff0fff, 0x005c0004}, /* BUF */ + {0xcc50, 0x000000ff, 0x00000037}, /* EXT */ + {0xcc80, 0x800f0000, 0x80020000}, /* W_AV1_SEG */ + {0xcc84, 0x0fff0fff, 0x00600004}, /* BUF */ + {0xcc90, 0x000000ff, 0x00000038}, /* EXT */ + {0xcd00, 0x800f0000, 0x80020000}, /* R_AV1_SEG */ + {0xcd04, 0x1fff1fff, 0x02020008}, /* BUF */ + {0xcd10, 0x000000ff, 0x0000003a}, /* EXT */ + {0xcd40, 0x800f0000, 0x80020000}, /* R_AV1_SEG */ + {0xcd44, 0x1fff1fff, 0x020a0008}, /* BUF */ + {0xcd50, 0x000000ff, 0x0000003b}, /* EXT */ + {0xcd80, 0x800f0000, 0x80020000}, /* R_AV1_SEG */ + {0xcd84, 0x1fff1fff, 0x02120008}, /* BUF */ + {0xcd90, 0x000000ff, 0x0000003c}, /* EXT */ + {0xce00, 0x800f0000, 0x80020000}, /* W_AV1_COLOR */ + {0xce04, 0x0fff0fff, 0x00640008}, /* BUF */ + {0xce10, 0x000000ff, 0x0000003e}, /* EXT */ + {0xce40, 0x800f0000, 0x80020000}, /* W_AV1_COLOR */ + {0xce44, 0x0fff0fff, 0x006c0008}, /* BUF */ + {0xce50, 0x000000ff, 0x0000003f}, /* EXT */ + {0xce80, 0x800f0000, 0x80020000}, /* W_AV1_COLOR */ + {0xce84, 0x0fff0fff, 0x00740008}, /* BUF */ + {0xce90, 0x000000ff, 0x00000040}, /* EXT */ + {0xcf00, 0x800f0000, 0x80020000}, /* R_AV1_COLOR0 */ + {0xcf04, 0x1fff1fff, 0x021a0010}, /* BUF */ + {0xcf10, 0x000000ff, 0x00000042}, /* EXT */ + {0xcf40, 0x800f0000, 0x80020000}, /* R_AV1_COLOR0 */ + {0xcf44, 0x1fff1fff, 0x022a0010}, /* BUF */ + {0xcf50, 0x000000ff, 0x00000043}, /* EXT */ + {0xcf80, 0x800f0000, 0x80020000}, /* R_AV1_COLOR0 */ + {0xcf84, 0x1fff1fff, 0x023a0010}, /* BUF */ + {0xcf90, 0x000000ff, 0x00000044}, /* EXT */ + {0xd000, 0x800f0000, 0x80020000}, /* R_AV1_COLOR1 */ + {0xd004, 0x1fff1fff, 0x024a0010}, /* BUF */ + {0xd010, 0x000000ff, 0x00000046}, /* EXT */ + {0xd040, 0x800f0000, 0x80020000}, /* R_AV1_COLOR1 */ + {0xd044, 0x1fff1fff, 0x025a0010}, /* BUF */ + {0xd050, 0x000000ff, 0x00000047}, /* EXT */ + {0xd080, 0x800f0000, 0x80020000}, /* R_AV1_COLOR1 */ + {0xd084, 0x1fff1fff, 0x026a0010}, /* BUF */ + {0xd090, 0x000000ff, 0x00000048}, /* EXT */ + {0xd100, 0x800f0000, 0x80020000}, /* R_AV1_COLOR2 */ + {0xd104, 0x1fff1fff, 0x027a0010}, /* BUF */ + {0xd110, 0x000000ff, 0x0000004a}, /* EXT */ + {0xd140, 0x800f0000, 0x80020000}, /* R_AV1_COLOR2 */ + {0xd144, 0x1fff1fff, 0x028a0010}, /* BUF */ + {0xd150, 0x000000ff, 0x0000004b}, /* EXT */ + {0xd180, 0x800f0000, 0x80020000}, /* R_AV1_COLOR2 */ + {0xd184, 0x1fff1fff, 0x029a0010}, /* BUF */ + {0xd190, 0x000000ff, 0x0000004c}, /* EXT */ + {0xd200, 0x800f0000, 0x80020000}, /* W_AV1_PROBS */ + {0xd204, 0x0fff0fff, 0x007c0016}, /* BUF */ + {0xd210, 0x000000ff, 0x0000004e}, /* EXT */ + {0xd240, 0x800f0000, 0x80020000}, /* W_AV1_PROBS */ + {0xd244, 0x0fff0fff, 0x00920016}, /* BUF */ + {0xd250, 0x000000ff, 0x0000004f}, /* EXT */ + {0xd280, 0x800f0000, 0x80020000}, /* W_AV1_PROBS */ + {0xd284, 0x0fff0fff, 0x00a80016}, /* BUF */ + {0xd290, 0x000000ff, 0x00000050}, /* EXT */ + {0xd300, 0x800f0000, 0x80020000}, /* R_AV1_PROBS */ + {0xd304, 0x1fff1fff, 0x02aa0074}, /* BUF */ + {0xd310, 0x000000ff, 0x00000052}, /* EXT */ + {0xd340, 0x800f0000, 0x80020000}, /* R_AV1_PROBS */ + {0xd344, 0x1fff1fff, 0x031e0074}, /* BUF */ + {0xd350, 0x000000ff, 0x00000053}, /* EXT */ + {0xd380, 0x800f0000, 0x80020000}, /* R_AV1_PROBS */ + {0xd384, 0x1fff1fff, 0x03920074}, /* BUF */ + {0xd390, 0x000000ff, 0x00000054}, /* EXT */ + {0xd400, 0x800f0000, 0x80010000}, /* W_AV1_INSN */ + {0xd404, 0x0fff0fff, 0x01f60016}, /* BUF */ + {0xd410, 0x000000ff, 0x0000005f}, /* EXT */ + {0xd440, 0x800f0000, 0x80010000}, /* W_AV1_INSN */ + {0xd444, 0x0fff0fff, 0x020c0016}, /* BUF */ + {0xd450, 0x000000ff, 0x00000060}, /* EXT */ + {0xd480, 0x800f0000, 0x80010000}, /* W_AV1_INSN */ + {0xd484, 0x0fff0fff, 0x02220016}, /* BUF */ + {0xd490, 0x000000ff, 0x00000061}, /* EXT */ + {0xd500, 0x800f3c00, 0x80011000}, /* R_PIPE_INSN */ + {0xd504, 0x1fff1fff, 0x040600f2}, /* BUF */ + {0xd510, 0x000000ff, 0x00000063}, /* EXT */ + {0xd540, 0x800f3c00, 0x80011000}, /* R_PIPE_INSN */ + {0xd544, 0x1fff1fff, 0x04f800f2}, /* BUF */ + {0xd550, 0x000000ff, 0x00000064}, /* EXT */ + {0xd580, 0x800f3c00, 0x80011000}, /* R_PIPE_INSN */ + {0xd584, 0x1fff1fff, 0x05ea00f2}, /* BUF */ + {0xd590, 0x000000ff, 0x00000065}, /* EXT */ + {0xd5c0, 0x800f3c00, 0x80011000}, /* R_PIPE_INSN */ + {0xd5c4, 0x1fff1fff, 0x06dc00f2}, /* BUF */ + {0xd5d0, 0x000000ff, 0x00000066}, /* EXT */ + {0xe000, 0x00000001, 0x00000001}, /* INTRA_TOP_CLOCK_GATING */ + {0xe080, 0x800f0000, 0x80020000}, /* W_IP_ABOVE_PIX */ + {0xe084, 0x0fff0fff, 0x0000001c}, /* BUF */ + {0xe090, 0x000000ff, 0x00000069}, /* EXT */ + {0xe0c0, 0x800f0000, 0x80020000}, /* R_IP_ABOVE_PIX */ + {0xe0c4, 0x1fff1fff, 0x0000002e}, /* BUF */ + {0xe0d0, 0x000000ff, 0x0000006a}, /* EXT */ + {0xe100, 0x800f0000, 0x80020000}, /* W_LF_ABOVE_PIX */ + {0xe104, 0x0fff0fff, 0x001c0054}, /* BUF */ + {0xe110, 0x000000ff, 0x00000071}, /* EXT */ + {0xe140, 0x800f0000, 0x80020000}, /* R_LF_ABOVE_PIX */ + {0xe144, 0x1fff1fff, 0x002e009e}, /* BUF */ + {0xe150, 0x000000ff, 0x00000072}, /* EXT */ + {0xe180, 0x800f0000, 0x80020000}, /* W_LF_ABOVE_INFO */ + {0xe184, 0x0fff0fff, 0x00700016}, /* BUF */ + {0xe190, 0x000000ff, 0x0000006f}, /* EXT */ + {0xe1c0, 0x800f0000, 0x80020000}, /* R_LF_ABOVE_INFO */ + {0xe1c4, 0x1fff1fff, 0x00cc0022}, /* BUF */ + {0xe1d0, 0x000000ff, 0x00000070}, /* EXT */ + {0xe200, 0x800f0000, 0x80020000}, /* W_LF_LEFT_PIX */ + {0xe204, 0x0fff0fff, 0x00860032}, /* BUF */ + {0xe210, 0x000000ff, 0x00000075}, /* EXT */ + {0xe240, 0x800f0000, 0x80020000}, /* R_LF_LEFT_PIX */ + {0xe244, 0x1fff1fff, 0x00ee0032}, /* BUF */ + {0xe250, 0x000000ff, 0x00000076}, /* EXT */ + {0xe280, 0x800f0000, 0x80020000}, /* W_LF_LEFT_INFO */ + {0xe284, 0x0fff0fff, 0x00b8000c}, /* BUF */ + {0xe290, 0x000000ff, 0x00000073}, /* EXT */ + {0xe2c0, 0x800f0000, 0x80020000}, /* R_LF_LEFT_INFO */ + {0xe2c4, 0x1fff1fff, 0x0120000c}, /* BUF */ + {0xe2d0, 0x000000ff, 0x00000074}, /* EXT */ + {0xe300, 0x800f0000, 0x80020000}, /* W_SR_LEFT_PIX */ + {0xe304, 0x0fff0fff, 0x00c40046}, /* BUF */ + {0xe310, 0x000000ff, 0x00000077}, /* EXT */ + {0xe340, 0x800f0000, 0x80020000}, /* R_SR_LEFT_PIX */ + {0xe344, 0x1fff1fff, 0x012c0046}, /* BUF */ + {0xe350, 0x000000ff, 0x00000078}, /* EXT */ + {0xe380, 0x800f0000, 0x80020000}, /* W_RF_ABOVE_INFO */ + {0xe384, 0x0fff0fff, 0x010a001a}, /* BUF */ + {0xe390, 0x000000ff, 0x00000079}, /* EXT */ + {0xe3c0, 0x800f0000, 0x80020000}, /* R_RF_ABOVE_INFO */ + {0xe3c4, 0x1fff1fff, 0x01720032}, /* BUF */ + {0xe3d0, 0x000000ff, 0x0000007a}, /* EXT */ + {0xe400, 0x800f0000, 0x80020000}, /* W_RF_LEFT_PIX */ + {0xe404, 0x0fff0fff, 0x0124002a}, /* BUF */ + {0xe410, 0x000000ff, 0x0000007d}, /* EXT */ + {0xe440, 0x800f0000, 0x80020000}, /* R_RF_LEFT_PIX */ + {0xe444, 0x1fff1fff, 0x01a4002a}, /* BUF */ + {0xe450, 0x000000ff, 0x0000007e}, /* EXT */ + {0xe480, 0x800f0000, 0x80020000}, /* W_RF_LEFT_INFO */ + {0xe484, 0x0fff0fff, 0x014e000a}, /* BUF */ + {0xe490, 0x000000ff, 0x0000007b}, /* EXT */ + {0xe4c0, 0x800f0000, 0x80020000}, /* R_RF_LEFT_INFO */ + {0xe4c4, 0x1fff1fff, 0x01ce000a}, /* BUF */ + {0xe4d0, 0x000000ff, 0x0000007c}, /* EXT */ + {0xe500, 0x800f7c00, 0x80027c00}, /* W_SW_PIX */ + {0xe504, 0x0fff0fff, 0x016800d0}, /* BUF */ + {0xe510, 0x000000ff, 0x00000085}, /* EXT */ + {0xe540, 0x800f0000, 0x80020000}, /* W_SW_LEFT */ + {0xe544, 0x0fff0fff, 0x015c000c}, /* BUF */ + {0xe550, 0x000000ff, 0x00000083}, /* EXT */ + {0xe580, 0x800f0000, 0x80020000}, /* R_SW_LEFT */ + {0xe584, 0x1fff1fff, 0x01d8000c}, /* BUF */ + {0xe590, 0x000000ff, 0x00000084}, /* EXT */ + {0xe5c0, 0x800f0000, 0x80020000}, /* W_AZ_ABOVE_PIX */ + {0xe5c4, 0x0fff0fff, 0x02380012}, /* BUF */ + {0xe5d0, 0x000000ff, 0x0000007f}, /* EXT */ + {0xe600, 0x800f0000, 0x80020000}, /* R_AZ_ABOVE_PIX */ + {0xe604, 0x1fff1fff, 0x01e40020}, /* BUF */ + {0xe610, 0x000000ff, 0x00000080}, /* EXT */ + {0xe640, 0x800f0000, 0x80020000}, /* W_AZ_LEFT_PIX */ + {0xe644, 0x0fff0fff, 0x024a006c}, /* BUF */ + {0xe650, 0x000000ff, 0x00000081}, /* EXT */ + {0xe680, 0x800f0000, 0x80020000}, /* R_AZ_LEFT_PIX */ + {0xe684, 0x1fff1fff, 0x02040060}, /* BUF */ + {0xe690, 0x000000ff, 0x00000082}, /* EXT */ + {0xe6c0, 0x800ff000, 0x80034000}, /* W_ZIP */ + {0xe6c8, 0x0fff0fff, 0x02ce009e}, /* BUF (CMP) */ + {0xe6cc, 0x0fff0fff, 0x02b6000c}, /* BUF (HDR) */ + {0xe6ec, 0x0000ffff, 0x00008789}, /* EXT */ + {0xe700, 0x800ff000, 0x80034000}, /* W_ZIP */ + {0xe708, 0x0fff0fff, 0x036c009e}, /* BUF (CMP) */ + {0xe70c, 0x0fff0fff, 0x02c2000c}, /* BUF (HDR) */ + {0xe72c, 0x0000ffff, 0x0000888a}, /* EXT */ + {0xe740, 0x800f0000, 0x80020000}, /* W_PIPE_STATS */ + {0xe744, 0x0fff0fff, 0x01580004}, /* BUF */ + {0xe750, 0x000000ff, 0x00000067}, /* EXT */ + {0xe800, 0x00000001, 0x00000001}, /* INTER_TOP_CLOCK_GATING */ + {0xe880, 0x800f0000, 0x80020000}, /* W_MV_ABOVE_INFO */ + {0xe884, 0x0fff0fff, 0x00000016}, /* BUF */ + {0xe890, 0x000000ff, 0x0000006b}, /* EXT */ + {0xe8c0, 0x800f0000, 0x80020000}, /* R_MV_ABOVE_INFO */ + {0xe8c4, 0x1fff1fff, 0x00000022}, /* BUF */ + {0xe8d0, 0x000000ff, 0x0000006c}, /* EXT */ + {0xe900, 0x800f0000, 0x80020000}, /* W_MV_COLOR */ + {0xe904, 0x0fff0fff, 0x00160022}, /* BUF */ + {0xe910, 0x000000ff, 0x0000006d}, /* EXT */ + {0xe940, 0x800f0000, 0x80020000}, /* R_MV_COLOR */ + {0xe944, 0x1fff1fff, 0x0022003e}, /* BUF */ + {0xe950, 0x000000ff, 0x0000006e}, /* EXT */ + {0xe980, 0x80ff0004, 0x80550004}, /* R_ZIP */ + {0xe9a8, 0xffffffff, 0x8d8f8c8e}, /* EXT */ +}; diff --git a/drivers/media/platform/apple/avd/avd-pm-test.c b/drivers/media/platform/apple/avd/avd-pm-test.c index 61b911e51c119d..aea64efc5aac25 100644 --- a/drivers/media/platform/apple/avd/avd-pm-test.c +++ b/drivers/media/platform/apple/avd/avd-pm-test.c @@ -14,9 +14,16 @@ struct avd_pm_test { unsigned int step; unsigned int unmap_step; unsigned int boot_step; + unsigned int shutdown_step; unsigned int resubmit_step; + unsigned int perf_put_step; unsigned int shutdowns; unsigned int submissions; + unsigned int perf_gets; + unsigned int perf_puts; + unsigned int perf_sync_puts; + unsigned int perf_suspends; + int perf_get_error; int boot_error; int suspend_error; bool unmapped_active; @@ -27,6 +34,51 @@ static struct avd_pm_test *avd_pm_fixture(struct avd_dev *avd) return container_of(avd, struct avd_pm_test, avd); } +static u64 avd_pm_test_now_ns; + +static u64 avd_pm_test_clock(void) +{ + return avd_pm_test_now_ns; +} + +static int avd_pm_test_perf_get(struct avd_dev *avd) +{ + struct avd_pm_test *fixture = avd_pm_fixture(avd); + + if (fixture->perf_get_error) + return fixture->perf_get_error; + fixture->perf_gets++; + return 0; +} + +static void avd_pm_test_perf_put(struct avd_dev *avd, bool sync) +{ + struct avd_pm_test *fixture = avd_pm_fixture(avd); + + fixture->perf_put_step = ++fixture->step; + fixture->perf_puts++; + if (sync) + fixture->perf_sync_puts++; +} + +static void avd_pm_test_perf_suspend(struct avd_dev *avd) +{ + avd_pm_fixture(avd)->perf_suspends++; +} + +static const struct avd_pm_perf_ops avd_pm_test_perf_ops = { + .get = avd_pm_test_perf_get, + .put = avd_pm_test_perf_put, + .suspend = avd_pm_test_perf_suspend, +}; + +static void avd_pm_test_enable_perf(struct avd_dev *avd) +{ + avd_pm_test_now_ns = 1000ULL * NSEC_PER_MSEC; + avd->pm.clock_ns = avd_pm_test_clock; + avd->pm.perf_ops = &avd_pm_test_perf_ops; +} + static bool avd_pm_test_idle(struct avd_dev *avd) { struct avd_pm_test *fixture = avd_pm_fixture(avd); @@ -49,7 +101,10 @@ static int avd_pm_test_boot(struct avd_dev *avd) static void avd_pm_test_shutdown(struct avd_dev *avd) { - avd_pm_fixture(avd)->shutdowns++; + struct avd_pm_test *fixture = avd_pm_fixture(avd); + + fixture->shutdown_step = ++fixture->step; + fixture->shutdowns++; } static int avd_pm_test_suspend(struct avd_dev *avd) @@ -291,9 +346,9 @@ static void avd_pm_open_boot_replay_test(struct kunit *test) avd->code = (__force void __iomem *)kunit_kzalloc(test, 0x100, GFP_KERNEL); avd->mbox = (__force void __iomem *)kunit_kzalloc(test, 0x100, GFP_KERNEL); avd->pm.piodma = (__force void __iomem *)kunit_kzalloc(test, 0x28, GFP_KERNEL); - KUNIT_ASSERT_NOT_NULL(test, avd->code); - KUNIT_ASSERT_NOT_NULL(test, avd->mbox); - KUNIT_ASSERT_NOT_NULL(test, avd->pm.piodma); + KUNIT_ASSERT_NOT_NULL(test, (__force void *)avd->code); + KUNIT_ASSERT_NOT_NULL(test, (__force void *)avd->mbox); + KUNIT_ASSERT_NOT_NULL(test, (__force void *)avd->pm.piodma); avd->pm.sram_phys = 0x123456780ULL; for (i = 0; i < 2; i++) { /* Model loss of both ITCM and PIODMA configuration between boots. */ @@ -376,6 +431,270 @@ static void avd_pm_parked_resume_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, avd->pm.irq_enabled); } +static void avd_pm_perf_low_demand_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + int stream_a; + unsigned int i; + + /* Without a "perf" domain every call is a no-op. */ + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + avd_pm_perf_idle(avd); + avd_pm_perf_suspend(avd); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 0U); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 0U); + + avd_pm_test_enable_perf(avd); + + /* Steady 1080p60 single-stream playback (~125 Mpx/s) stays off floor. */ + for (i = 0; i < 60; i++) { + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + avd_pm_perf_idle(avd); + avd_pm_test_now_ns += 16666667ULL; + } + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 0U); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 0U); +} + +static void avd_pm_perf_large_frame_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + int stream_a; + + avd_pm_test_enable_perf(avd); + + /* 4K engages on the first frame and does not double-acquire while held. */ + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 1U); + + avd_pm_test_now_ns += 5ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 2, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 1U); + + /* Idle releases asynchronously so inter-frame gaps reuse autosuspend. */ + avd_pm_perf_idle(avd); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 1U); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 0U); + + /* Power-off flushes any pending autosuspend timer synchronously. */ + KUNIT_ASSERT_EQ(test, avd_pm_power_off(avd), 0); + KUNIT_EXPECT_EQ(test, fixture->perf_suspends, 1U); + + /* 1440p also engages immediately; parking drops it synchronously. */ + avd->pm.dart_active = true; + avd_pm_perf_frame_start(avd, &stream_a, 2560, 1440, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 2U); + KUNIT_ASSERT_EQ(test, avd_pm_park(avd), 0); + KUNIT_EXPECT_LT(test, fixture->shutdown_step, fixture->perf_put_step); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 2U); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 1U); +} + +static void avd_pm_perf_rate_hysteresis_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + int stream_a; + unsigned int i; + + avd_pm_test_enable_perf(avd); + + /* Unthrottled 1080p burst (>180 Mpx/s) engages perf mid-window. */ + for (i = 0; i < 24; i++) { + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + avd_pm_test_now_ns += 3ULL * NSEC_PER_MSEC; + } + KUNIT_EXPECT_TRUE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 1U); + + /* Roll over into a 150 Mpx/s window (inside 135..180 Mpx/s hysteresis band). */ + avd_pm_test_now_ns += AVD_PERF_WINDOW_MS * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + for (i = 0; i < 17; i++) { + avd_pm_test_now_ns += 13ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + } + avd_pm_test_now_ns += 35ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + + /* Drop to 1080p30 (~63 Mpx/s): stays held through hold-down, then releases. */ + for (i = 0; i < 30; i++) { + avd_pm_test_now_ns += 33333333ULL; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + } + KUNIT_EXPECT_FALSE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 1U); +} + +static void avd_pm_perf_concurrency_and_backlog_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + int stream_a, stream_b; + + avd_pm_test_enable_perf(avd); + + /* Simultaneous multi-stream frames engage immediately. */ + avd_pm_perf_frame_start(avd, &stream_a, 1280, 720, 2, 2); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 1U); + avd_pm_perf_suspend(avd); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 1U); + + /* Alternating streams on a 1-slot backend also trigger within a window. */ + avd_pm_test_now_ns += 1000ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1280, 720, 1, 1); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + avd_pm_test_now_ns += 16ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_b, 1280, 720, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 2U); + avd_pm_perf_suspend(avd); + + /* Queue backlog (>= AVD_PERF_INFLIGHT_HIGH) engages immediately. */ + avd_pm_test_now_ns += 1000ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, + AVD_PERF_INFLIGHT_HIGH - 1, 1); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, + AVD_PERF_INFLIGHT_HIGH, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 3U); + avd_pm_perf_idle(avd); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); +} + +static void avd_pm_perf_clock_and_gap_reset_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + int stream_a, stream_b; + unsigned int i; + + avd_pm_test_enable_perf(avd); + + /* Engage high-rate and multi-stream demand inside one window. */ + for (i = 0; i < 24; i++) { + avd_pm_perf_frame_start(avd, (i & 1) ? &stream_b : &stream_a, + 1920, 1088, 1, 1); + avd_pm_test_now_ns += 3ULL * NSEC_PER_MSEC; + } + KUNIT_EXPECT_TRUE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_window_multi); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 1U); + + /* A gap >= 2 * window resets rate/multi state and releases on low load. */ + avd_pm_test_now_ns += 2ULL * AVD_PERF_WINDOW_MS * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_window_multi); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 1U); + + /* Re-engage high demand, then jump the clock backwards mid-window. */ + for (i = 0; i < 24; i++) { + avd_pm_perf_frame_start(avd, (i & 1) ? &stream_b : &stream_a, + 1920, 1088, 1, 1); + avd_pm_test_now_ns += 3ULL * NSEC_PER_MSEC; + } + KUNIT_EXPECT_TRUE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_window_multi); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 2U); + + avd_pm_test_now_ns = avd->pm.perf_window_start_ns - 50ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_window_multi); + KUNIT_EXPECT_EQ(test, avd->pm.perf_hold_until_ns, 0ULL); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 2U); +} + +static void avd_pm_perf_failed_park_and_recover_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + struct iommu_domain domain = {}; + int stream_a; + + avd_pm_test_enable_perf(avd); + + /* Early -EHOSTDOWN return from avd_pm_park() still drops perf_held. */ + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, avd_pm_park(avd), -EHOSTDOWN); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 1U); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 1U); + + /* Failed DART parking (-ENODEV) shuts down first, then drops perf_held. */ + avd->pm.dart_active = true; + avd->domain = &domain; + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, avd_pm_recover(avd), -ENODEV); + KUNIT_EXPECT_EQ(test, fixture->shutdowns, 1U); + KUNIT_EXPECT_LT(test, fixture->shutdown_step, fixture->perf_put_step); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 2U); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 2U); + + /* Failed recovery reboot re-parks without double-putting perf_held. */ + avd->domain = NULL; + fixture->boot_error = -ETIMEDOUT; + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, avd_pm_recover(avd), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, fixture->shutdowns, 3U); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 3U); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 3U); + KUNIT_EXPECT_EQ(test, fixture->perf_suspends, 1U); +} + +static void avd_pm_perf_error_handling_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + int stream_a; + + avd_pm_test_enable_perf(avd); + + /* Failed floor acquisition never sets perf_held or causes an unmatched put. */ + fixture->perf_get_error = -EIO; + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 0U); + avd_pm_perf_idle(avd); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 0U); + + /* Recovery once floor acquisition succeeds again. */ + fixture->perf_get_error = 0; + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 1U); + avd_pm_perf_suspend(avd); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 1U); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 1U); +} + static void avd_pm_test_exit(struct kunit *test) { struct avd_pm_test *fixture = test->priv; @@ -396,6 +715,13 @@ static struct kunit_case avd_pm_test_cases[] = { KUNIT_CASE(avd_pm_recovery_dart_gate_test), KUNIT_CASE(avd_pm_recovery_boot_test), KUNIT_CASE(avd_pm_parked_resume_test), + KUNIT_CASE(avd_pm_perf_low_demand_test), + KUNIT_CASE(avd_pm_perf_large_frame_test), + KUNIT_CASE(avd_pm_perf_rate_hysteresis_test), + KUNIT_CASE(avd_pm_perf_concurrency_and_backlog_test), + KUNIT_CASE(avd_pm_perf_clock_and_gap_reset_test), + KUNIT_CASE(avd_pm_perf_failed_park_and_recover_test), + KUNIT_CASE(avd_pm_perf_error_handling_test), {} }; diff --git a/drivers/media/platform/apple/avd/avd-pm.c b/drivers/media/platform/apple/avd/avd-pm.c index d6b45ba78e8443..183e49d28859d2 100644 --- a/drivers/media/platform/apple/avd/avd-pm.c +++ b/drivers/media/platform/apple/avd/avd-pm.c @@ -2,8 +2,11 @@ #include #include #include +#include #include +#include #include +#include #include #include #include @@ -12,6 +15,11 @@ /* [C] Keep Linux's existing default until the idle-timer capture is available. */ #define AVD_AUTOSUSPEND_MS 100 +#define AVD_PERF_AUTOSUSPEND_MS 100 +#define AVD_PERF_WINDOW_NS (AVD_PERF_WINDOW_MS * NSEC_PER_MSEC) +#define AVD_PERF_WINDOW_ENTER_PIXELS \ + (AVD_PERF_ENTER_PX_PER_MS * AVD_PERF_WINDOW_MS) +#define AVD_PERF_HOLD_NS (AVD_PERF_HOLD_MS * NSEC_PER_MSEC) #define AVD_DRAIN_TIMEOUT_MS 5000 #define AVD_PIODMA_SRAM_BASE 0x24 @@ -182,10 +190,229 @@ const struct avd_queue_pm_ops avd_pm_queue_ops = { .resubmit = avd_pm_resubmit, }; +static int avd_pm_perf_get_pd(struct avd_dev *avd) +{ + return pm_runtime_resume_and_get(avd->pm.perf_dev); +} + +static void avd_pm_perf_put_pd(struct avd_dev *avd, bool sync) +{ + if (sync) { + pm_runtime_put_sync_suspend(avd->pm.perf_dev); + return; + } + pm_runtime_mark_last_busy(avd->pm.perf_dev); + pm_runtime_put_autosuspend(avd->pm.perf_dev); +} + +static void avd_pm_perf_suspend_pd(struct avd_dev *avd) +{ + pm_runtime_suspend(avd->pm.perf_dev); +} + +static const struct avd_pm_perf_ops avd_pm_perf_runtime_ops = { + .get = avd_pm_perf_get_pd, + .put = avd_pm_perf_put_pd, + .suspend = avd_pm_perf_suspend_pd, +}; + +static u64 avd_pm_clock_ns(struct avd_dev *avd) +{ + return avd->pm.clock_ns ? avd->pm.clock_ns() : ktime_get_ns(); +} + +static void avd_pm_perf_reset_demand(struct avd_pm *pm) +{ + pm->perf_rate_high = false; + pm->perf_window_valid = false; + pm->perf_window_multi = false; + pm->perf_window_stream = NULL; + pm->perf_window_start_ns = 0; + pm->perf_window_pixels = 0; + pm->perf_hold_until_ns = 0; +} + +static void avd_pm_detach_perf(void *data) +{ + struct avd_dev *avd = data; + struct device *perf_dev = avd->pm.perf_dev; + + if (!perf_dev) + return; + + avd_pm_perf_suspend(avd); + mutex_lock(&avd->pm.perf_lock); + WRITE_ONCE(avd->pm.perf_ops, NULL); + avd->pm.perf_dev = NULL; + mutex_unlock(&avd->pm.perf_lock); + pm_runtime_dont_use_autosuspend(perf_dev); + dev_pm_domain_detach(perf_dev, false); +} + +int avd_pm_attach_perf(struct avd_dev *avd, unsigned int index) +{ + struct device *perf_dev; + int ret; + + perf_dev = dev_pm_domain_attach_by_id(avd->dev, index); + if (IS_ERR(perf_dev)) + return PTR_ERR(perf_dev); + if (!perf_dev) + return 0; + + pm_runtime_set_autosuspend_delay(perf_dev, AVD_PERF_AUTOSUSPEND_MS); + pm_runtime_use_autosuspend(perf_dev); + + mutex_lock(&avd->pm.perf_lock); + avd->pm.perf_dev = perf_dev; + WRITE_ONCE(avd->pm.perf_ops, &avd_pm_perf_runtime_ops); + mutex_unlock(&avd->pm.perf_lock); + + ret = devm_add_action_or_reset(avd->dev, avd_pm_detach_perf, avd); + if (ret) + return ret; + + return 0; +} + +/* + * Engage the optional "perf" floor only when active decode demand requires it: + * frames larger than 1080p, multiple concurrent active streams, queue backlog, + * or sustained high pixel throughput with Schmitt-trigger hysteresis and a + * hold-down window to prevent floor thrashing. + */ +void avd_pm_perf_frame_start(struct avd_dev *avd, const void *stream_id, + u32 width, u32 height, unsigned int inflight, + unsigned int concurrent_streams) +{ + const struct avd_pm_perf_ops *ops; + struct avd_pm *pm = &avd->pm; + u64 frame_pixels = (u64)width * height; + u64 now_ns; + bool high_demand, need_perf; + + if (!READ_ONCE(pm->perf_ops)) + return; + + mutex_lock(&pm->perf_lock); + ops = pm->perf_ops; + if (!ops) + goto unlock; + + now_ns = avd_pm_clock_ns(avd); + + if (!pm->perf_window_valid || now_ns < pm->perf_window_start_ns) { + pm->perf_window_valid = true; + pm->perf_window_start_ns = now_ns; + pm->perf_window_pixels = frame_pixels; + pm->perf_window_stream = stream_id; + pm->perf_window_multi = false; + pm->perf_rate_high = false; + pm->perf_hold_until_ns = 0; + } else { + u64 dt_ns = now_ns - pm->perf_window_start_ns; + + if (dt_ns >= 2 * AVD_PERF_WINDOW_NS) { + pm->perf_rate_high = false; + pm->perf_window_start_ns = now_ns; + pm->perf_window_pixels = frame_pixels; + pm->perf_window_stream = stream_id; + pm->perf_window_multi = false; + } else if (dt_ns >= AVD_PERF_WINDOW_NS) { + u64 dt_ms = div_u64(dt_ns, NSEC_PER_MSEC); + u64 px_per_ms = div_u64(pm->perf_window_pixels, dt_ms); + + if (px_per_ms >= AVD_PERF_ENTER_PX_PER_MS) + pm->perf_rate_high = true; + else if (px_per_ms < AVD_PERF_EXIT_PX_PER_MS) + pm->perf_rate_high = false; + + pm->perf_window_start_ns = now_ns; + pm->perf_window_pixels = frame_pixels; + pm->perf_window_stream = stream_id; + pm->perf_window_multi = false; + } else { + pm->perf_window_pixels += frame_pixels; + if (pm->perf_window_stream && stream_id && + pm->perf_window_stream != stream_id) + pm->perf_window_multi = true; + else if (!pm->perf_window_stream) + pm->perf_window_stream = stream_id; + if (pm->perf_window_pixels >= AVD_PERF_WINDOW_ENTER_PIXELS) + pm->perf_rate_high = true; + } + } + + high_demand = frame_pixels > AVD_PERF_FRAME_PIXELS || + concurrent_streams > 1 || + pm->perf_window_multi || + inflight >= AVD_PERF_INFLIGHT_HIGH || + pm->perf_rate_high; + + if (high_demand) + pm->perf_hold_until_ns = now_ns + AVD_PERF_HOLD_NS; + + need_perf = high_demand || + (pm->perf_hold_until_ns && now_ns < pm->perf_hold_until_ns); + + if (need_perf) { + /* Best effort: decode still completes without the floor. */ + if (!pm->perf_held && ops->get(avd) >= 0) + pm->perf_held = true; + } else { + pm->perf_hold_until_ns = 0; + if (pm->perf_held) { + pm->perf_held = false; + ops->put(avd, false); + } + } + +unlock: + mutex_unlock(&pm->perf_lock); +} + +void avd_pm_perf_idle(struct avd_dev *avd) +{ + const struct avd_pm_perf_ops *ops; + + if (!READ_ONCE(avd->pm.perf_ops)) + return; + + mutex_lock(&avd->pm.perf_lock); + ops = avd->pm.perf_ops; + if (ops && avd->pm.perf_held) { + avd->pm.perf_held = false; + ops->put(avd, false); + } + mutex_unlock(&avd->pm.perf_lock); +} + +void avd_pm_perf_suspend(struct avd_dev *avd) +{ + const struct avd_pm_perf_ops *ops; + + if (!READ_ONCE(avd->pm.perf_ops)) + return; + + mutex_lock(&avd->pm.perf_lock); + ops = avd->pm.perf_ops; + avd_pm_perf_reset_demand(&avd->pm); + if (ops) { + if (avd->pm.perf_held) { + avd->pm.perf_held = false; + ops->put(avd, true); + } else if (ops->suspend) { + ops->suspend(avd); + } + } + mutex_unlock(&avd->pm.perf_lock); +} + void avd_pm_init(struct avd_dev *avd, const struct avd_backend_ops *backend, const struct avd_queue_pm_ops *queue) { mutex_init(&avd->pm.lock); + mutex_init(&avd->pm.perf_lock); INIT_LIST_HEAD(&avd->pm.deferred_unmaps); init_waitqueue_head(&avd->pm.idle_wait); avd->pm.dart_active = false; @@ -194,6 +421,11 @@ void avd_pm_init(struct avd_dev *avd, const struct avd_backend_ops *backend, mutex_init(&avd->pm.hw_lock); avd->pm.hw_on = false; avd->pm.irq_gen = 0; + avd->pm.perf_dev = NULL; + avd->pm.perf_ops = NULL; + avd->pm.perf_held = false; + avd->pm.clock_ns = NULL; + avd_pm_perf_reset_demand(&avd->pm); avd->backend = backend; avd->pm.queue = queue; } @@ -248,6 +480,7 @@ void avd_pm_disable(struct avd_dev *avd) pm_runtime_disable(avd->dev); /* Also close the host IRQ if the final hardware transition failed. */ avd_pm_disable_irq(avd); + avd_pm_perf_suspend(avd); /* No queue_mutex is held here: let a woken handler thread finish. */ if (avd->pm.irq >= 0) synchronize_irq(avd->pm.irq); @@ -293,27 +526,34 @@ int avd_pm_backend_resume(struct avd_dev *avd) /* Caller holds a runtime PM reference and queue_mutex. */ int avd_pm_park(struct avd_dev *avd) { - int ret; + int ret = 0; - if (!avd->pm.dart_active) + if (!avd->pm.dart_active) { + avd_pm_perf_suspend(avd); return -EHOSTDOWN; + } avd_pm_disable_irq(avd); dev_warn(avd->dev, "recover: stop firmware\n"); avd->backend->shutdown(avd); if (avd->domain && !avd->pm.dma_parked) { - if (!avd->empty_domain) - return -ENODEV; + if (!avd->empty_domain) { + ret = -ENODEV; + goto out_perf; + } dev_warn(avd->dev, "recover: block DMA\n"); ret = iommu_attach_device(avd->empty_domain, avd->dev); if (ret) { dev_err(avd->dev, "recover: DART empty attach failed: %d\n", ret); - return ret; + goto out_perf; } avd->pm.dma_parked = true; /* Outstanding transfers drain into faults before any reset/free. */ usleep_range(5000, 6000); } - return 0; +out_perf: + /* Drop the perf floor only after firmware shutdown and DMA parking. */ + avd_pm_perf_suspend(avd); + return ret; } int avd_pm_recover(struct avd_dev *avd) @@ -339,7 +579,8 @@ int avd_pm_recover(struct avd_dev *avd) /* * On the J616C the machine hangs right after this reset, while the * decoder's DART domain is restored. The cause is not known yet, so - * stay parked: players fall back to software. + * stay parked: players fall back to software. Tracked in + * https://github.com/aurora-silicon/linux/issues/2450. */ if (avd->variant && avd->variant->quirks & AVD_QUIRK_NO_RECOVERY_RESET) { dev_err(avd->dev, "recover: staying parked, no reset on this SoC\n"); @@ -428,6 +669,7 @@ int avd_pm_power_off(struct avd_dev *avd) avd_pm_drain_unmaps(avd); avd->pm.dart_active = false; mutex_unlock(&avd->pm.lock); + avd_pm_perf_suspend(avd); return 0; } @@ -450,6 +692,8 @@ static int avd_system_suspend(struct device *dev) ret = avd->pm.queue->drain(avd); if (!ret) ret = pm_runtime_force_suspend(dev); + if (!ret) + avd_pm_perf_suspend(avd); if (ret) v4l2_m2m_resume(avd->m2m_dev); return ret; diff --git a/drivers/media/platform/apple/avd/avd-pm.h b/drivers/media/platform/apple/avd/avd-pm.h index 10e3a0ffbe9362..31c6e36301b483 100644 --- a/drivers/media/platform/apple/avd/avd-pm.h +++ b/drivers/media/platform/apple/avd/avd-pm.h @@ -8,8 +8,25 @@ #include "avd-queue.h" +#define AVD_PERF_FRAME_PIXELS 2200000ULL +#define AVD_PERF_WINDOW_MS 250ULL +#define AVD_PERF_ENTER_PX_PER_MS 180000ULL +#define AVD_PERF_EXIT_PX_PER_MS 135000ULL +#define AVD_PERF_HOLD_MS 500ULL +/* + * Tier-1 backends expose 15 FIFO slots (7 on tier-0) and single-stream 1080p + * players often decode-ahead 2-3 frames; engage on >= 4 frames in flight. + */ +#define AVD_PERF_INFLIGHT_HIGH 4U + struct avd_dma_release; +struct avd_pm_perf_ops { + int (*get)(struct avd_dev *avd); + void (*put)(struct avd_dev *avd, bool sync); + void (*suspend)(struct avd_dev *avd); +}; + struct avd_queue_pm_ops { /* Snapshot under the queue lock: all FREE, no context draining. */ bool (*idle)(struct avd_dev *avd); @@ -49,6 +66,20 @@ struct avd_pm { /* Protected by queue_lock; counts drain operations, not stopped streams. */ unsigned int draining; const struct avd_queue_pm_ops *queue; + /* Optional "perf" floor domain, engaged only under high decode demand. */ + struct device *perf_dev; + const struct avd_pm_perf_ops *perf_ops; + /* Serializes perf-floor demand state and votes. */ + struct mutex perf_lock; + bool perf_held; + bool perf_rate_high; + bool perf_window_valid; + bool perf_window_multi; + const void *perf_window_stream; + u64 perf_window_start_ns; + u64 perf_window_pixels; + u64 perf_hold_until_ns; + u64 (*clock_ns)(void); }; /* The caller holds the queue lock, including the draining-context count. */ @@ -56,6 +87,12 @@ bool avd_pm_can_suspend(const struct avd_frame *frames, unsigned int draining); void avd_pm_init(struct avd_dev *avd, const struct avd_backend_ops *backend, const struct avd_queue_pm_ops *queue); +int avd_pm_attach_perf(struct avd_dev *avd, unsigned int index); +void avd_pm_perf_frame_start(struct avd_dev *avd, const void *stream_id, + u32 width, u32 height, unsigned int inflight, + unsigned int concurrent_streams); +void avd_pm_perf_idle(struct avd_dev *avd); +void avd_pm_perf_suspend(struct avd_dev *avd); void avd_pm_enable(struct avd_dev *avd); int avd_pm_map_piodma(struct avd_dev *avd); void avd_pm_prepare_piodma(struct avd_dev *avd); diff --git a/drivers/media/platform/apple/avd/avd-queue-test.c b/drivers/media/platform/apple/avd/avd-queue-test.c index 8d343b1b933995..7de5e49bdae261 100644 --- a/drivers/media/platform/apple/avd/avd-queue-test.c +++ b/drivers/media/platform/apple/avd/avd-queue-test.c @@ -207,6 +207,48 @@ static void avd_submit_order(struct kunit *test) KUNIT_EXPECT_FALSE(test, avd_slot_submit_first(pool, &pool[1])); } +/* + * The legacy transport programs the context FIFO, which only exists while + * the OUTPUT queue streams. With no codec capability the submission stops + * before it touches the hardware either way. + */ +static void avd_open_submit_needs_fifo(struct kunit *test) +{ + static const struct avd_coded_fmt_desc desc = {}; + struct avd_dev *avd; + struct avd_ctx *ctx; + struct avd_frame *f; + struct avd_buf *prog; + u32 *words; + + avd = kunit_kzalloc(test, sizeof(*avd), GFP_KERNEL); + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); + prog = kunit_kzalloc(test, sizeof(*prog), GFP_KERNEL); + words = kunit_kcalloc(test, 4, sizeof(*words), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, avd); + KUNIT_ASSERT_NOT_NULL(test, ctx); + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, prog); + KUNIT_ASSERT_NOT_NULL(test, words); + + ctx->dev = avd; + ctx->coded_fmt_desc = &desc; + prog->cpu = words; + prog->size = 4 * sizeof(*words); + f->ctx = ctx; + f->prog = prog; + f->prog_words = 1; + f->cmd[0] = AVD_CODEC_H264; + + KUNIT_EXPECT_EQ(test, avd_open_backend.submit(avd, f), -EINVAL); + KUNIT_EXPECT_NULL(test, avd->compat_active); + + ctx->inst.cpu = words; + KUNIT_EXPECT_EQ(test, avd_open_backend.submit(avd, f), -EOPNOTSUPP); + KUNIT_EXPECT_NULL(test, avd->compat_active); +} + static struct kunit_case avd_queue_cases[] = { KUNIT_CASE(avd_slots_and_tags), KUNIT_CASE(avd_retirement_order), @@ -215,6 +257,7 @@ static struct kunit_case avd_queue_cases[] = { KUNIT_CASE(avd_command_builders), KUNIT_CASE(avd_dispatch_reservation), KUNIT_CASE(avd_submit_order), + KUNIT_CASE(avd_open_submit_needs_fifo), {} }; diff --git a/drivers/media/platform/apple/avd/avd-queue.c b/drivers/media/platform/apple/avd/avd-queue.c index 22e40b631a5270..19ac0c17bf495a 100644 --- a/drivers/media/platform/apple/avd/avd-queue.c +++ b/drivers/media/platform/apple/avd/avd-queue.c @@ -106,7 +106,12 @@ static void avd_retire(struct avd_dev *avd) f->dst = NULL; f->state = AVD_FRAME_FREE; avd->inflight--; - spin_unlock_irqrestore(&avd->queue_lock, flags); + if (!avd->inflight) { + spin_unlock_irqrestore(&avd->queue_lock, flags); + avd_pm_perf_idle(avd); + } else { + spin_unlock_irqrestore(&avd->queue_lock, flags); + } avd_pm_queue_changed(avd); pm_runtime_mark_last_busy(avd->dev); pm_runtime_put_autosuspend(avd->dev); @@ -352,6 +357,30 @@ int avd_queue_ready(void *priv) return ready; } +static void avd_active_stream_stats(struct avd_dev *avd, unsigned int *inflight, + unsigned int *streams) +{ + struct avd_ctx *seen[AVD_MAX_FRAMES]; + unsigned int i, j, count = 0; + unsigned long flags; + + spin_lock_irqsave(&avd->queue_lock, flags); + *inflight = avd->inflight; + for (i = 0; i < AVD_MAX_FRAMES; i++) { + struct avd_ctx *ctx = avd->frames[i].ctx; + + if (avd->frames[i].state == AVD_FRAME_FREE || !ctx) + continue; + for (j = 0; j < count; j++) + if (seen[j] == ctx) + break; + if (j == count) + seen[count++] = ctx; + } + spin_unlock_irqrestore(&avd->queue_lock, flags); + *streams = count; +} + static void avd_queue_submit_work(struct work_struct *work) { struct avd_ctx *ctx = container_of(work, struct avd_ctx, submit_work); @@ -359,7 +388,7 @@ static void avd_queue_submit_work(struct work_struct *work) const struct avd_codec_frame_ops *ops = ctx->coded_fmt_desc->frame_ops; struct avd_frame *f = NULL; unsigned long flags; - unsigned int i; + unsigned int i, inflight, streams; int ret; mutex_lock(&avd->queue_mutex); @@ -491,7 +520,12 @@ static void avd_queue_submit_work(struct work_struct *work) f->state = AVD_FRAME_FREE; f->ctx = NULL; avd->inflight--; - spin_unlock_irqrestore(&avd->queue_lock, flags); + if (!avd->inflight) { + spin_unlock_irqrestore(&avd->queue_lock, flags); + avd_pm_perf_idle(avd); + } else { + spin_unlock_irqrestore(&avd->queue_lock, flags); + } avd_pm_queue_changed(avd); pm_runtime_mark_last_busy(avd->dev); pm_runtime_put_autosuspend(avd->dev); @@ -500,6 +534,11 @@ static void avd_queue_submit_work(struct work_struct *work) goto unlock; } v4l2_m2m_buf_copy_metadata(f->src, f->dst); + if (READ_ONCE(avd->pm.perf_ops)) { + avd_active_stream_stats(avd, &inflight, &streams); + avd_pm_perf_frame_start(avd, ctx, fmt_width(ctx), + fmt_height(ctx), inflight, streams); + } ret = avd_send_frame(avd, f); if (ret && ret != -EBUSY) { spin_lock_irqsave(&avd->queue_lock, flags); diff --git a/drivers/media/platform/apple/avd/avd-v4l2-test.c b/drivers/media/platform/apple/avd/avd-v4l2-test.c new file mode 100644 index 00000000000000..3b2e09b6f6d9c6 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-v4l2-test.c @@ -0,0 +1,277 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the format ioctls and the control helpers of the Apple + * video decoder. + */ + +#include +#include +#include +#include +#include + +#include "avd.h" + +static const struct avd_coded_fmt_ops avd_test_ops = {}; + +static const struct avd_decoded_fmt_desc avd_test_decoded_fmts[] = { + { .fourcc = V4L2_PIX_FMT_NV12, .image_fmt = AVD_IMG_FMT_420_8BIT }, +}; + +static const struct avd_coded_fmt_desc avd_test_coded_desc = { + .fourcc = V4L2_PIX_FMT_H264_SLICE, + .frmsize = { + .min_width = 64, .max_width = 4096, .step_width = 64, + .min_height = 64, .max_height = 4096, .step_height = 16, + }, + .ops = &avd_test_ops, + .num_decoded_fmts = ARRAY_SIZE(avd_test_decoded_fmts), + .decoded_fmts = avd_test_decoded_fmts, +}; + +struct avd_test_fmt { + struct avd_ctx *ctx; + struct file *file; + struct vb2_queue *cap_q; +}; + +/* A 64x64 context with its default CAPTURE format, as after open(). */ +static void avd_test_fmt_init(struct kunit *test, struct avd_test_fmt *t) +{ + struct v4l2_m2m_ctx *m2m_ctx; + + t->ctx = kunit_kzalloc(test, sizeof(*t->ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->ctx); + m2m_ctx = kunit_kzalloc(test, sizeof(*m2m_ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, m2m_ctx); + t->file = kunit_kzalloc(test, sizeof(*t->file), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->file); + + t->ctx->fh.m2m_ctx = m2m_ctx; + t->file->private_data = &t->ctx->fh; + t->cap_q = &m2m_ctx->cap_q_ctx.q; + + t->ctx->coded_fmt_desc = &avd_test_coded_desc; + t->ctx->coded_fmt.fmt.pix_mp.width = 64; + t->ctx->coded_fmt.fmt.pix_mp.height = 64; + t->ctx->image_fmt = AVD_IMG_FMT_420_8BIT; + avd_reset_decoded_fmt(t->ctx); +} + +static void avd_test_capture_fmt(struct v4l2_format *f, u32 width, u32 height) +{ + memset(f, 0, sizeof(*f)); + f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + f->fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12; + f->fmt.pix_mp.width = width; + f->fmt.pix_mp.height = height; +} + +static void avd_test_expect_comp(struct kunit *test, + const struct avd_comp *got, + const struct avd_comp *want) +{ + KUNIT_EXPECT_EQ(test, got->size, want->size); + KUNIT_EXPECT_EQ(test, got->start_offset, want->start_offset); + KUNIT_EXPECT_MEMEQ(test, got->offsets, want->offsets, + sizeof(want->offsets)); +} + +/* TRY_FMT(CAPTURE) must leave the context's buffer layout alone. */ +static void avd_try_capture_fmt_test(struct kunit *test) +{ + struct avd_test_fmt t; + struct v4l2_format f, decoded; + struct avd_comp comp; + + avd_test_fmt_init(test, &t); + comp = t.ctx->comp; + decoded = t.ctx->decoded_fmt; + KUNIT_ASSERT_NE(test, comp.size, 0); + + /* CAPTURE buffers allocated, as when streaming. */ + t.cap_q->is_busy = 1; + avd_test_capture_fmt(&f, 4096, 4096); + KUNIT_EXPECT_EQ(test, avd_try_capture_fmt(t.file, NULL, &f), 0); + KUNIT_EXPECT_EQ(test, f.fmt.pix_mp.width, 4096); + KUNIT_EXPECT_GT(test, f.fmt.pix_mp.plane_fmt[0].sizeimage, + decoded.fmt.pix_mp.plane_fmt[0].sizeimage); + avd_test_expect_comp(test, &t.ctx->comp, &comp); + KUNIT_EXPECT_MEMEQ(test, &t.ctx->decoded_fmt, &decoded, sizeof(decoded)); + + /* S_FMT is refused on the busy queue and changes nothing either. */ + avd_test_capture_fmt(&f, 4096, 4096); + KUNIT_EXPECT_EQ(test, avd_s_capture_fmt(t.file, NULL, &f), -EBUSY); + avd_test_expect_comp(test, &t.ctx->comp, &comp); + + /* The same holds with no buffers. */ + t.cap_q->is_busy = 0; + avd_test_capture_fmt(&f, 1920, 1088); + KUNIT_EXPECT_EQ(test, avd_try_capture_fmt(t.file, NULL, &f), 0); + avd_test_expect_comp(test, &t.ctx->comp, &comp); + KUNIT_EXPECT_MEMEQ(test, &t.ctx->decoded_fmt, &decoded, sizeof(decoded)); +} + +/* S_FMT(CAPTURE) lays out the compressed area for the format it sets. */ +static void avd_s_capture_fmt_test(struct kunit *test) +{ + struct avd_test_fmt t; + struct v4l2_format f; + struct avd_comp want = {}; + + avd_test_fmt_init(test, &t); + + avd_test_capture_fmt(&f, 1920, 1088); + KUNIT_ASSERT_EQ(test, avd_s_capture_fmt(t.file, NULL, &f), 0); + + want.start_offset = 1920 * 1088 * 3 / 2; + fill_comp(&want, AVD_IMG_FMT_420_8BIT, 1920, 1088); + avd_test_expect_comp(test, &t.ctx->comp, &want); + KUNIT_EXPECT_EQ(test, t.ctx->decoded_fmt.fmt.pix_mp.width, 1920); + KUNIT_EXPECT_EQ(test, t.ctx->decoded_fmt.fmt.pix_mp.height, 1088); + KUNIT_EXPECT_EQ(test, + t.ctx->decoded_fmt.fmt.pix_mp.plane_fmt[0].sizeimage, + want.start_offset + want.size); + + /* A later TRY_FMT reports its own layout but stores nothing. */ + avd_test_capture_fmt(&f, 4096, 2176); + KUNIT_EXPECT_EQ(test, avd_try_capture_fmt(t.file, NULL, &f), 0); + avd_test_expect_comp(test, &t.ctx->comp, &want); +} + +/* A context whose control handler holds the VP9 frame control. */ +static struct v4l2_ctrl *avd_test_ctrl_init(struct kunit *test, + struct avd_ctx **ctxp) +{ + static const struct v4l2_ctrl_config cfg = { + .id = V4L2_CID_STATELESS_VP9_FRAME, + }; + struct avd_ctx *ctx; + struct v4l2_ctrl *ctrl; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + v4l2_ctrl_handler_init(&ctx->ctrl_hdl, 1); + ctrl = v4l2_ctrl_new_custom(&ctx->ctrl_hdl, &cfg, NULL); + KUNIT_ASSERT_EQ(test, ctx->ctrl_hdl.error, 0); + KUNIT_ASSERT_NOT_NULL(test, ctrl); + + *ctxp = ctx; + return ctrl; +} + +static int avd_test_set_vp9_width(struct v4l2_ctrl *ctrl, u16 width) +{ + struct v4l2_ctrl_vp9_frame frame = *ctrl->p_cur.p_vp9_frame; + + frame.frame_width_minus_1 = width - 1; + frame.frame_height_minus_1 = width - 1; + return v4l2_ctrl_s_ctrl_compound(ctrl, V4L2_CTRL_TYPE_VP9_FRAME, + &frame); +} + +/* A copy keeps the value it was taken from when the control is set again. */ +static void avd_ctrl_copy_test(struct kunit *test) +{ + struct v4l2_ctrl_vp9_frame *copy; + struct v4l2_ctrl *ctrl; + struct avd_ctx *ctx; + + ctrl = avd_test_ctrl_init(test, &ctx); + copy = kunit_kzalloc(test, sizeof(*copy) + 1, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, copy); + + KUNIT_ASSERT_EQ(test, avd_test_set_vp9_width(ctrl, 64), 0); + KUNIT_ASSERT_EQ(test, avd_ctrl_copy(ctx, V4L2_CID_STATELESS_VP9_FRAME, + copy, sizeof(*copy)), 0); + KUNIT_EXPECT_MEMEQ(test, copy, ctrl->p_cur.p, sizeof(*copy)); + KUNIT_EXPECT_TRUE(test, avd_vp9_frame_fits(copy, 64, 64)); + + KUNIT_ASSERT_EQ(test, avd_test_set_vp9_width(ctrl, 4096), 0); + KUNIT_EXPECT_FALSE(test, avd_vp9_frame_fits(ctrl->p_cur.p_vp9_frame, + 64, 64)); + KUNIT_EXPECT_EQ(test, copy->frame_width_minus_1, 63); + KUNIT_EXPECT_EQ(test, copy->frame_height_minus_1, 63); + KUNIT_EXPECT_TRUE(test, avd_vp9_frame_fits(copy, 64, 64)); + + /* Only a destination of the control's own size is filled. */ + memset(copy, 0, sizeof(*copy)); + KUNIT_EXPECT_EQ(test, avd_ctrl_copy(ctx, V4L2_CID_STATELESS_VP9_FRAME, + copy, sizeof(*copy) - 1), -EINVAL); + KUNIT_EXPECT_EQ(test, avd_ctrl_copy(ctx, V4L2_CID_STATELESS_VP9_FRAME, + copy, sizeof(*copy) + 1), -EINVAL); + KUNIT_EXPECT_EQ(test, copy->frame_width_minus_1, 0); + /* So is a control that the handler does not have. */ + KUNIT_EXPECT_EQ(test, + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_VP9_COMPRESSED_HDR, + copy, sizeof(*copy)), -EINVAL); + + v4l2_ctrl_handler_free(&ctx->ctrl_hdl); +} + +struct avd_test_copy_work { + struct work_struct work; + struct completion done; + struct v4l2_ctrl *ctrl; + struct v4l2_ctrl_vp9_frame copy; + int ret; +}; + +static void avd_test_copy_work_fn(struct work_struct *work) +{ + struct avd_test_copy_work *w = + container_of(work, struct avd_test_copy_work, work); + + w->ret = avd_ctrl_copy_value(w->ctrl, &w->copy, sizeof(w->copy)); + complete(&w->done); +} + +/* The copy waits for whoever holds the control lock and sees its whole update. */ +static void avd_ctrl_copy_locked_test(struct kunit *test) +{ + struct avd_test_copy_work *w; + struct v4l2_ctrl *ctrl; + struct avd_ctx *ctx; + + ctrl = avd_test_ctrl_init(test, &ctx); + w = kunit_kzalloc(test, sizeof(*w), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, w); + w->ctrl = ctrl; + w->ret = -EINPROGRESS; + init_completion(&w->done); + INIT_WORK(&w->work, avd_test_copy_work_fn); + + KUNIT_ASSERT_EQ(test, avd_test_set_vp9_width(ctrl, 64), 0); + + v4l2_ctrl_lock(ctrl); + ctrl->p_cur.p_vp9_frame->frame_width_minus_1 = 4095; + schedule_work(&w->work); + KUNIT_EXPECT_EQ(test, + wait_for_completion_timeout(&w->done, + msecs_to_jiffies(200)), 0); + KUNIT_EXPECT_EQ(test, w->ret, -EINPROGRESS); + ctrl->p_cur.p_vp9_frame->frame_height_minus_1 = 4095; + v4l2_ctrl_unlock(ctrl); + + flush_work(&w->work); + KUNIT_EXPECT_EQ(test, w->ret, 0); + KUNIT_EXPECT_EQ(test, w->copy.frame_width_minus_1, 4095); + KUNIT_EXPECT_EQ(test, w->copy.frame_height_minus_1, 4095); + + v4l2_ctrl_handler_free(&ctx->ctrl_hdl); +} + +static struct kunit_case avd_v4l2_test_cases[] = { + KUNIT_CASE(avd_try_capture_fmt_test), + KUNIT_CASE(avd_s_capture_fmt_test), + KUNIT_CASE(avd_ctrl_copy_test), + KUNIT_CASE(avd_ctrl_copy_locked_test), + {} +}; + +static struct kunit_suite avd_v4l2_test_suite = { + .name = "apple-avd-v4l2", + .test_cases = avd_v4l2_test_cases, +}; + +kunit_test_suite(avd_v4l2_test_suite); diff --git a/drivers/media/platform/apple/avd/avd-v4l2.c b/drivers/media/platform/apple/avd/avd-v4l2.c index 2a4903ee76aafb..17205b5e172bd8 100644 --- a/drivers/media/platform/apple/avd/avd-v4l2.c +++ b/drivers/media/platform/apple/avd/avd-v4l2.c @@ -11,6 +11,7 @@ * Copyright (C) 2011 Samsung Electronics Co., Ltd. */ +#include #include #include @@ -18,6 +19,7 @@ #include #include "avd.h" +#include "avd-inst.h" static bool avd_image_fmt_match(enum avd_image_fmt fmt1, enum avd_image_fmt fmt2) @@ -65,6 +67,41 @@ static bool avd_image_fmt_fits_capture(struct avd_ctx *ctx, !memcmp(comp.offsets, ctx->comp.offsets, sizeof(comp.offsets)); } +/* + * Whether a job may program @image_fmt, the picture format that the current + * value of the codec's format control describes. The CAPTURE buffers and the + * per-context scratch were sized for ctx->image_fmt (ANY sizes them as 8-bit + * 4:2:0), and the control's value can differ from it: it may have been set + * while another codec was selected, or kept over an OUTPUT format change, and + * an unchanged value never reaches s_ctrl. Refuse the job unless both are the + * same and the CAPTURE buffers fit it, and unless the scratch a codec sized at + * STREAMON has the bit depth of the picture (s_ctrl only refuses a change + * while CAPTURE buffers are allocated, not while OUTPUT streams). + */ +static bool avd_image_fmt_10bit(enum avd_image_fmt fmt) +{ + return fmt == AVD_IMG_FMT_420_10BIT || fmt == AVD_IMG_FMT_422_10BIT; +} + +int avd_check_run_image_fmt(struct avd_ctx *ctx, enum avd_image_fmt image_fmt) +{ + enum avd_image_fmt sized = ctx->image_fmt; + + if (sized == AVD_IMG_FMT_ANY) + sized = AVD_IMG_FMT_420_8BIT; + if (image_fmt == AVD_IMG_FMT_ANY) + image_fmt = AVD_IMG_FMT_420_8BIT; + if (image_fmt != sized || !avd_image_fmt_fits_capture(ctx, image_fmt) || + (ctx->scratch_sized && + avd_image_fmt_10bit(ctx->scratch_fmt) != avd_image_fmt_10bit(image_fmt))) { + dev_dbg_ratelimited(ctx->dev->dev, + "picture format %d does not fit the buffers (%d)\n", + image_fmt, ctx->image_fmt); + return -EINVAL; + } + return 0; +} + static u32 avd_enum_decoded_fmt(struct avd_ctx *ctx, int index, enum avd_image_fmt image_fmt) { @@ -103,15 +140,21 @@ static bool avd_is_valid_fmt(struct avd_ctx *ctx, u32 fourcc, return false; } +/* + * Lay out a decoded buffer: the picture, then the compressed reference area + * described by @comp, then any codec specific tail. Only @pix_mp and @comp + * are written, so TRY_FMT can use it on a context that is streaming. + */ static void avd_fill_decoded_pixfmt(struct avd_ctx *ctx, - struct v4l2_pix_format_mplane *pix_mp) + struct v4l2_pix_format_mplane *pix_mp, + struct avd_comp *comp) { v4l2_fill_pixfmt_mp(pix_mp, pix_mp->pixelformat, pix_mp->width, pix_mp->height); - ctx->comp.start_offset = pix_mp->plane_fmt[0].sizeimage; - fill_comp(&ctx->comp, ctx->image_fmt, pix_mp->width, pix_mp->height); - pix_mp->plane_fmt[0].sizeimage += ctx->comp.size; + comp->start_offset = pix_mp->plane_fmt[0].sizeimage; + fill_comp(comp, ctx->image_fmt, pix_mp->width, pix_mp->height); + pix_mp->plane_fmt[0].sizeimage += comp->size; if (ctx->coded_fmt_desc->ops->adjust_decoded_fmt) ctx->coded_fmt_desc->ops->adjust_decoded_fmt(ctx, pix_mp); } @@ -138,7 +181,7 @@ void avd_reset_decoded_fmt(struct avd_ctx *ctx) f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; f->fmt.pix_mp.width = ctx->coded_fmt.fmt.pix_mp.width; f->fmt.pix_mp.height = ctx->coded_fmt.fmt.pix_mp.height; - avd_fill_decoded_pixfmt(ctx, &f->fmt.pix_mp); + avd_fill_decoded_pixfmt(ctx, &f->fmt.pix_mp, &ctx->comp); } static int avd_try_ctrl(struct v4l2_ctrl *ctrl) @@ -289,13 +332,13 @@ static const struct avd_ctrl_desc avd_h264_ctrl_descs[] = { { .cfg.id = V4L2_CID_STATELESS_H264_DECODE_MODE, .cfg.min = V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED, - .cfg.max = V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED, + .cfg.max = V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED, .cfg.def = V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED, }, { .cfg.id = V4L2_CID_STATELESS_H264_START_CODE, .cfg.min = V4L2_STATELESS_H264_START_CODE_NONE, - .cfg.max = V4L2_STATELESS_H264_START_CODE_NONE, + .cfg.max = V4L2_STATELESS_H264_START_CODE_ANNEX_B, .cfg.def = V4L2_STATELESS_H264_START_CODE_NONE, }, { @@ -396,6 +439,7 @@ static const struct avd_ctrl_desc avd_av1_ctrl_descs[] = { }, { .cfg.id = V4L2_CID_STATELESS_AV1_FRAME, + .cfg.ops = &avd_ctrl_ops, }, { .cfg.id = V4L2_CID_STATELESS_AV1_FILM_GRAIN, @@ -561,16 +605,13 @@ static int avd_querycap(struct file *file, void *priv, strscpy(cap->driver, avd->dev->driver->name, sizeof(cap->driver)); strscpy(cap->card, vdev->name, sizeof(cap->card)); - snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s", - avd->dev->driver->name); return 0; } -static int avd_try_capture_fmt(struct file *file, void *priv, - struct v4l2_format *f) +static int avd_try_decoded_fmt(struct avd_ctx *ctx, struct v4l2_format *f, + struct avd_comp *comp) { struct v4l2_pix_format_mplane *pix_mp = &f->fmt.pix_mp; - struct avd_ctx *ctx = file_to_ctx(file); const struct avd_coded_fmt_desc *coded_desc; /* @@ -594,12 +635,21 @@ static int avd_try_capture_fmt(struct file *file, void *priv, v4l2_apply_frmsize_constraints(&pix_mp->width, &pix_mp->height, &coded_desc->frmsize); - avd_fill_decoded_pixfmt(ctx, pix_mp); + avd_fill_decoded_pixfmt(ctx, pix_mp, comp); pix_mp->field = V4L2_FIELD_NONE; return 0; } +VISIBLE_IF_KUNIT int avd_try_capture_fmt(struct file *file, void *priv, + struct v4l2_format *f) +{ + struct avd_comp comp; + + return avd_try_decoded_fmt(file_to_ctx(file), f, &comp); +} +EXPORT_SYMBOL_IF_KUNIT(avd_try_capture_fmt); + static int avd_try_output_fmt(struct file *file, void *priv, struct v4l2_format *f) { @@ -627,10 +677,11 @@ static int avd_try_output_fmt(struct file *file, void *priv, return 0; } -static int avd_s_capture_fmt(struct file *file, void *priv, - struct v4l2_format *f) +VISIBLE_IF_KUNIT int avd_s_capture_fmt(struct file *file, void *priv, + struct v4l2_format *f) { struct avd_ctx *ctx = file_to_ctx(file); + struct avd_comp comp; struct vb2_queue *vq; int ret; @@ -640,13 +691,15 @@ static int avd_s_capture_fmt(struct file *file, void *priv, if (vb2_is_busy(vq)) return -EBUSY; - ret = avd_try_capture_fmt(file, priv, f); + ret = avd_try_decoded_fmt(ctx, f, &comp); if (ret) return ret; ctx->decoded_fmt = *f; + ctx->comp = comp; return 0; } +EXPORT_SYMBOL_IF_KUNIT(avd_s_capture_fmt); static int avd_s_output_fmt(struct file *file, void *priv, struct v4l2_format *f) @@ -928,14 +981,21 @@ static int avd_start_streaming(struct vb2_queue *q, unsigned int count) goto err_return_buffers; } + /* The context's instruction FIFO is only used while OUTPUT streams. */ + ret = avd_buf_alloc(ctx->dev, &ctx->inst, fifo_size()); + if (ret) + goto err_return_buffers; + if (desc->ops->start) { ret = desc->ops->start(ctx); if (ret) - goto err_return_buffers; + goto err_free_inst; } return 0; +err_free_inst: + avd_buf_free(ctx->dev, &ctx->inst); err_return_buffers: /* Keep requests queued for a later STREAMON retry. */ while ((vbuf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx))) @@ -977,6 +1037,7 @@ static void avd_stop_streaming(struct vb2_queue *q) if (desc->ops->stop) desc->ops->stop(ctx); + avd_buf_free(ctx->dev, &ctx->inst); /* Drop a job table left over from a frame that never finished. */ kvfree(ctx->job.segments); @@ -1054,6 +1115,40 @@ void avd_run_postamble(struct avd_ctx *ctx, struct avd_run *run) v4l2_ctrl_request_complete(src_req, &ctx->ctrl_hdl); } +/* + * Copy the current value of a fixed-size control for a run. Requests are + * applied to the controls before a run reads them, but a control can also be + * set directly at any time, which rewrites its value under the control lock + * only. A run that checks a value and then reads it again from the control + * may see two different values. Take one copy under the lock; the run checks + * and uses that copy. @size must be the size of the control's value. + */ +VISIBLE_IF_KUNIT int avd_ctrl_copy_value(struct v4l2_ctrl *ctrl, void *dst, + size_t size) +{ + int ret = -EINVAL; + + v4l2_ctrl_lock(ctrl); + if ((size_t)ctrl->elems * ctrl->elem_size == size) { + memcpy(dst, ctrl->p_cur.p, size); + ret = 0; + } + v4l2_ctrl_unlock(ctrl); + + return ret; +} +EXPORT_SYMBOL_IF_KUNIT(avd_ctrl_copy_value); + +/* v4l2_ctrl_find() takes the control lock itself, so look up before copying. */ +int avd_ctrl_copy(struct avd_ctx *ctx, u32 id, void *dst, size_t size) +{ + struct v4l2_ctrl *ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, id); + + if (!ctrl) + return -EINVAL; + return avd_ctrl_copy_value(ctrl, dst, size); +} + static int avd_add_ctrls(struct avd_ctx *ctx, const struct avd_ctrls *ctrls) { unsigned int i; diff --git a/drivers/media/platform/apple/avd/avd-variant-test.c b/drivers/media/platform/apple/avd/avd-variant-test.c new file mode 100644 index 00000000000000..3ed43b1a7d74c6 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-variant-test.c @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Included by avd-drv.c to use the same OF table as avd_probe(). */ +#include + +static void avd_t8112_of_variant(struct kunit *test) +{ + static const char compatible[] = "apple,t8112-avd"; + struct property prop = { + .name = "compatible", + .length = sizeof(compatible), + .value = (void *)compatible, + }; + struct device_node node = { .properties = &prop }; + const struct of_device_id *match; + const struct avd_variant *variant; + + match = of_match_node(avd_of_match, &node); + KUNIT_ASSERT_NOT_NULL(test, match); + variant = match->data; + KUNIT_ASSERT_NOT_NULL(test, variant); + + /* Both stubs use the same independently supplied decoder image. */ + KUNIT_EXPECT_STREQ(test, variant->fw_name, "apple/avd-fw-v3-t1.bin"); + KUNIT_EXPECT_NULL(test, variant->fw_name_fallback); + KUNIT_EXPECT_NULL(test, variant->apple); + KUNIT_EXPECT_PTR_EQ(test, variant->configure_stream, &t8112_configure_stream); + KUNIT_EXPECT_EQ(test, variant->revision, 4); + KUNIT_EXPECT_EQ(test, variant->quirks, (u32)AVD_QUIRK_LSR); + KUNIT_EXPECT_EQ(test, variant->capabilities, + (u32)(AVD_CAPABILITY_H264 | AVD_CAPABILITY_HEVC | AVD_CAPABILITY_VP9)); +} + +static struct kunit_case avd_variant_cases[] = { + KUNIT_CASE(avd_t8112_of_variant), + {} +}; + +static struct kunit_suite avd_variant_suite = { + .name = "apple-avd-variant", + .test_cases = avd_variant_cases, +}; + +kunit_test_suite(avd_variant_suite); diff --git a/drivers/media/platform/apple/avd/avd-vp9-test.c b/drivers/media/platform/apple/avd/avd-vp9-test.c new file mode 100644 index 00000000000000..7bf89193a8f404 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-vp9-test.c @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the VP9 frame checks of the Apple video decoder. + */ + +#include +#include + +#include "avd.h" + +struct avd_vp9_tiling_case { + const char *desc; + u16 width; + u8 tile_rows_log2; + u8 tile_cols_log2; + int ret; +}; + +static const struct avd_vp9_tiling_case avd_vp9_tiling_cases[] = { + { "one tile", 1920, 0, 0, 0 }, + { "two tile rows", 1920, 1, 0, 0 }, + { "four tile rows", 1920, 2, 0, 0 }, + { "eight tile rows", 1920, 3, 0, -EINVAL }, + { "2^26 tile rows", 4096, 26, 6, -EINVAL }, + { "2^31 tile rows", 4096, 31, 1, -EINVAL }, + { "255 tile rows log2", 1920, 255, 0, -EINVAL }, + { "four tile columns at 1920", 1920, 0, 2, 0 }, + { "eight tile columns at 1920", 1920, 0, 3, -EINVAL }, + { "sixteen tile columns at 4096", 4096, 2, 4, 0 }, + { "32 tile columns at 4096", 4096, 0, 5, -EINVAL }, + { "64 tile columns at 4096", 4096, 0, 6, -EINVAL }, + { "two tile columns at 64", 64, 0, 1, -EINVAL }, + { "one tile column at 8192", 8192, 0, 0, -EINVAL }, + { "two tile columns at 8192", 8192, 0, 1, 0 }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_vp9_tiling, avd_vp9_tiling_cases, desc); + +static void avd_vp9_tiling_test(struct kunit *test) +{ + const struct avd_vp9_tiling_case *c = test->param_value; + struct v4l2_ctrl_vp9_frame frame = { + .frame_width_minus_1 = c->width - 1, + .frame_height_minus_1 = 1079, + .tile_rows_log2 = c->tile_rows_log2, + .tile_cols_log2 = c->tile_cols_log2, + }; + + KUNIT_EXPECT_EQ(test, avd_vp9_check_tiling(&frame), c->ret); +} + +#define AVD_TEST_MAX_TILES 2 + +struct avd_vp9_tiles_case { + const char *desc; + const u8 *data; + u32 payload; + u32 header; + unsigned int tiles; + int ret; + u32 offsets[AVD_TEST_MAX_TILES]; + u32 sizes[AVD_TEST_MAX_TILES]; +}; + +/* Two tiles after a 2-byte header: a 3-byte tile, then the rest. */ +static const u8 avd_test_two_tiles[] = { + 0xaa, 0xbb, 0x00, 0x00, 0x00, 0x03, 0x01, 0x02, 0x03, 0x04, 0x05, +}; + +/* The first tile's size reaches one byte past the payload. */ +static const u8 avd_test_long_tile[] = { + 0xaa, 0xbb, 0x00, 0x00, 0x00, 0x06, 0x01, 0x02, 0x03, 0x04, 0x05, +}; + +/* The first tile's size is the largest u32. */ +static const u8 avd_test_huge_tile[] = { + 0xaa, 0xbb, 0xff, 0xff, 0xff, 0xff, 0x01, 0x02, 0x03, 0x04, 0x05, +}; + +/* The first tile fills the payload and leaves nothing for the last one. */ +static const u8 avd_test_no_last_tile[] = { + 0xaa, 0xbb, 0x00, 0x00, 0x00, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05, +}; + +/* An empty first tile. */ +static const u8 avd_test_empty_tile[] = { + 0xaa, 0xbb, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, +}; + +static const struct avd_vp9_tiles_case avd_vp9_tiles_cases[] = { + { "one tile", avd_test_two_tiles, 11, 2, 1, 0, { 2 }, { 9 } }, + { "two tiles", avd_test_two_tiles, 11, 2, 2, 0, { 6, 9 }, { 3, 2 } }, + { "headers beyond the payload", avd_test_two_tiles, 11, 12, 1, -EINVAL }, + { "headers fill the payload", avd_test_two_tiles, 11, 11, 1, -EINVAL }, + { "headers beyond the payload, two tiles", avd_test_two_tiles, 11, + 0xffff + 0xffff, 2, -EINVAL }, + { "three bytes for a tile size", avd_test_two_tiles, 5, 2, 2, -EINVAL }, + { "no bytes for a tile size", avd_test_two_tiles, 2, 2, 2, -EINVAL }, + { "tile beyond the payload", avd_test_long_tile, 11, 2, 2, -EINVAL }, + { "tile size wraps", avd_test_huge_tile, 11, 2, 2, -EINVAL }, + { "no data for the last tile", avd_test_no_last_tile, 11, 2, 2, -EINVAL, + { 6 }, { 5 } }, + { "empty tile", avd_test_empty_tile, 11, 2, 2, -EINVAL }, + { "no mapping", NULL, 11, 2, 1, -EINVAL }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_vp9_tiles, avd_vp9_tiles_cases, desc); + +/* Walks the tiles as set_tiles() does. */ +static void avd_vp9_tiles_test(struct kunit *test) +{ + const struct avd_vp9_tiles_case *c = test->param_value; + u32 offset = c->header, size; + int ret = 0; + + for (unsigned int i = 0; i < c->tiles; i++) { + ret = avd_vp9_next_tile(c->data, c->payload, i == c->tiles - 1, + &offset, &size); + if (ret) + break; + KUNIT_EXPECT_EQ(test, offset, c->offsets[i]); + KUNIT_EXPECT_EQ(test, size, c->sizes[i]); + KUNIT_EXPECT_LE(test, (u64)offset + size, (u64)c->payload); + offset += size; + } + KUNIT_EXPECT_EQ(test, ret, c->ret); +} + +/* The frame size against a 1920x1088 coded format. */ +static void avd_vp9_frame_fits_test(struct kunit *test) +{ + struct v4l2_ctrl_vp9_frame frame = { + .frame_width_minus_1 = 1919, + .frame_height_minus_1 = 1079, + }; + + KUNIT_EXPECT_TRUE(test, avd_vp9_frame_fits(&frame, 1920, 1088)); + frame.frame_height_minus_1 = 1087; + KUNIT_EXPECT_TRUE(test, avd_vp9_frame_fits(&frame, 1920, 1088)); + frame.frame_width_minus_1 = 959; + frame.frame_height_minus_1 = 539; + KUNIT_EXPECT_TRUE(test, avd_vp9_frame_fits(&frame, 1920, 1088)); + + frame.frame_width_minus_1 = 1920; + frame.frame_height_minus_1 = 1079; + KUNIT_EXPECT_FALSE(test, avd_vp9_frame_fits(&frame, 1920, 1088)); + frame.frame_width_minus_1 = 1919; + frame.frame_height_minus_1 = 1088; + KUNIT_EXPECT_FALSE(test, avd_vp9_frame_fits(&frame, 1920, 1088)); + frame.frame_width_minus_1 = 4095; + frame.frame_height_minus_1 = 2175; + KUNIT_EXPECT_FALSE(test, avd_vp9_frame_fits(&frame, 64, 64)); + frame.frame_width_minus_1 = 0xffff; + frame.frame_height_minus_1 = 0xffff; + KUNIT_EXPECT_FALSE(test, avd_vp9_frame_fits(&frame, 4096, 4096)); +} + +/* + * A frame larger than the OUTPUT format is refused when the control is set, + * once the OUTPUT queue streams and the format can no longer follow it. + */ +static void avd_vp9_try_frame_size_test(struct kunit *test) +{ + static const struct v4l2_ctrl_config cfg = { + .id = V4L2_CID_STATELESS_VP9_FRAME, + }; + struct v4l2_m2m_ctx *m2m_ctx; + struct v4l2_ctrl_vp9_frame *frame; + struct v4l2_ctrl *ctrl; + struct avd_ctx *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + m2m_ctx = kunit_kzalloc(test, sizeof(*m2m_ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, m2m_ctx); + ctx->fh.m2m_ctx = m2m_ctx; + ctx->coded_fmt.fmt.pix_mp.width = 1920; + ctx->coded_fmt.fmt.pix_mp.height = 1088; + + v4l2_ctrl_handler_init(&ctx->ctrl_hdl, 1); + ctrl = v4l2_ctrl_new_custom(&ctx->ctrl_hdl, &cfg, NULL); + KUNIT_ASSERT_EQ(test, ctx->ctrl_hdl.error, 0); + KUNIT_ASSERT_NOT_NULL(test, ctrl); + frame = ctrl->p_new.p_vp9_frame; + + /* Not streaming: the format may still be set to the stream's size. */ + frame->frame_width_minus_1 = 4095; + frame->frame_height_minus_1 = 2159; + KUNIT_EXPECT_EQ(test, avd_vp9_fmt_ops.try_ctrl(ctx, ctrl), 0); + + m2m_ctx->out_q_ctx.q.streaming = 1; + KUNIT_EXPECT_EQ(test, avd_vp9_fmt_ops.try_ctrl(ctx, ctrl), -EINVAL); + frame->frame_width_minus_1 = 1919; + frame->frame_height_minus_1 = 1088; + KUNIT_EXPECT_EQ(test, avd_vp9_fmt_ops.try_ctrl(ctx, ctrl), -EINVAL); + frame->frame_height_minus_1 = 1087; + KUNIT_EXPECT_EQ(test, avd_vp9_fmt_ops.try_ctrl(ctx, ctrl), 0); + frame->frame_width_minus_1 = 1279; + frame->frame_height_minus_1 = 719; + KUNIT_EXPECT_EQ(test, avd_vp9_fmt_ops.try_ctrl(ctx, ctrl), 0); + + v4l2_ctrl_handler_free(&ctx->ctrl_hdl); +} + +static struct kunit_case avd_vp9_test_cases[] = { + KUNIT_CASE(avd_vp9_frame_fits_test), + KUNIT_CASE(avd_vp9_try_frame_size_test), + KUNIT_CASE_PARAM(avd_vp9_tiling_test, avd_vp9_tiling_gen_params), + KUNIT_CASE_PARAM(avd_vp9_tiles_test, avd_vp9_tiles_gen_params), + {} +}; + +static struct kunit_suite avd_vp9_test_suite = { + .name = "apple-avd-vp9", + .test_cases = avd_vp9_test_cases, +}; + +kunit_test_suite(avd_vp9_test_suite); diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index bf2d8b80854e60..df04fcc26b2b71 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -14,6 +14,7 @@ * Alpha Lin */ +#include #include #include @@ -159,6 +160,8 @@ struct avd_vp9_frame_info { u32 tx_mode : 3; u32 interpolation_filter : 3; u32 flags; + u32 width; + u32 height; u64 timestamp; dma_addr_t color; struct v4l2_vp9_segmentation seg; @@ -189,7 +192,6 @@ struct avd_vp9_bank { struct avd_buf lf_left_info; struct avd_buf lf_left; struct avd_buf color; - struct avd_buf seg; struct avd_buf pipe_state; struct avd_buf counts; struct avd_buf probs; @@ -205,6 +207,18 @@ struct avd_vp9_ctx { unsigned int nbanks; struct avd_vp9_bank bank[AVD_VP9_BANKS]; struct avd_vp9_bank *b; + /* The size changed, and no frame has updated the segmentation map since. */ + bool seg_reset; + /* + * The segmentation map, one per stream. A frame reads the map the frame + * before it left (temporal prediction, or a frame without a map update), + * so the two banks of the queued transport must share it: with one + * buffer per bank, a frame read the map of the frame before last. A size + * change moves to the other, cleared buffer (avd_vp9_run_preamble()): the frame + * still in flight keeps reading the old one. + */ + struct avd_buf seg_buf[2]; + unsigned int seg_cur; }; static bool avd_vp9_needs_counts(u32 flags) @@ -260,20 +274,32 @@ static void set_refs(struct avd_ctx *ctx, struct avd_vp9_run *run) dst->vp9.width; yscale = (ref_buf[i]->vp9.height << VP9_REF_SCALE_SHIFT) / dst->vp9.height; - push(AVD_HDR_HEIGHT(xscale) | AVD_HDR_WIDTH(yscale), + push(AVD_HDR_HEIGHT(yscale) | AVD_HDR_WIDTH(xscale), "ref_scale"); push_comp(ctx, addr, ref_buf[i]->comp.offsets); } } -/* Temporal MV input is the previous shown inter picture, not the new bank. */ -static bool avd_vp9_uses_prev_mv(u32 flags, const struct avd_vp9_frame_info *last) +static bool avd_vp9_same_size(const struct v4l2_ctrl_vp9_frame *frame, + const struct avd_vp9_frame_info *last) +{ + return last->width == frame->frame_width_minus_1 + 1 && + last->height == frame->frame_height_minus_1 + 1; +} + +/* + * Temporal MV input is the previous shown inter picture, not the new bank. + * VP9 uses it only if that picture has the same frame size. + */ +static bool avd_vp9_uses_prev_mv(const struct v4l2_ctrl_vp9_frame *frame, + const struct avd_vp9_frame_info *last) { - return !(flags & V4L2_VP9_FRAME_FLAG_ERROR_RESILIENT) && - !(flags & V4L2_VP9_FRAME_FLAG_KEY_FRAME) && last->valid && + return !(frame->flags & V4L2_VP9_FRAME_FLAG_ERROR_RESILIENT) && + !(frame->flags & V4L2_VP9_FRAME_FLAG_KEY_FRAME) && last->valid && (last->flags & V4L2_VP9_FRAME_FLAG_SHOW_FRAME) && - !(last->flags & V4L2_VP9_FRAME_FLAG_KEY_FRAME); + !(last->flags & V4L2_VP9_FRAME_FLAG_KEY_FRAME) && + avd_vp9_same_size(frame, last); } static u32 make_flags1(struct avd_ctx *ctx, struct avd_vp9_run *run) @@ -327,11 +353,12 @@ static u32 make_flags1(struct avd_ctx *ctx, struct avd_vp9_run *run) flags |= VP9_SEG_ENABLED(frame->seg.flags & V4L2_VP9_SEGMENTATION_FLAG_ENABLED); - flags |= VP9_HAS_REF(avd_vp9_uses_prev_mv(frame->flags, &vp9_ctx->last)); + flags |= VP9_HAS_REF(avd_vp9_uses_prev_mv(frame, &vp9_ctx->last)); flags |= VP9_SEG_RESET( frame->seg.flags & V4L2_VP9_SEGMENTATION_FLAG_ENABLED && (frame->flags & V4L2_VP9_FRAME_FLAG_KEY_FRAME || + vp9_ctx->seg_reset || (vp9_ctx->last.valid && !(vp9_ctx->last.seg.flags & V4L2_VP9_SEGMENTATION_FLAG_ENABLED) && @@ -422,10 +449,10 @@ static void set_header(struct avd_ctx *ctx, struct avd_vp9_run *run) pusha(vp9_ctx->b->bufs.counts.addr, "counts", 0); pusha(vp9_ctx->b->bufs.probs.addr, "probs", 0); pusha(vp9_ctx->b->bufs.above_info.addr, "above_info", 0); - pusha(vp9_ctx->b->bufs.seg.addr, "seg", 1); - pusha(vp9_ctx->b->bufs.seg.addr, "seg", 2); + pusha(vp9_ctx->seg_buf[vp9_ctx->seg_cur].addr, "seg", 1); + pusha(vp9_ctx->seg_buf[vp9_ctx->seg_cur].addr, "seg", 2); pusha(vp9_ctx->b->bufs.color.addr, "color", 3); - pusha(avd_vp9_uses_prev_mv(frame->flags, &vp9_ctx->last) ? + pusha(avd_vp9_uses_prev_mv(frame, &vp9_ctx->last) ? vp9_ctx->last.color : vp9_ctx->b->bufs.color.addr, "color", 4); @@ -492,19 +519,53 @@ static void set_header(struct avd_ctx *ctx, struct avd_vp9_run *run) set_refs(ctx, run); } -static void set_tiles(struct avd_ctx *ctx, struct avd_vp9_run *run) +/* + * Find the next tile in the frame (VP9 6.4 decode_tiles()): at @offset each + * tile but the last starts with its size as a 32-bit big-endian word, the + * last one takes the rest of the payload. Returns the tile's data offset in + * @offset and its size in @size, both within @payload. A tile holds at least + * one byte (9.2.1: sz is at least 1). + */ +VISIBLE_IF_KUNIT int avd_vp9_next_tile(const u8 *data, u32 payload, bool last, + u32 *offset, u32 *size) +{ + u32 off = *offset, tile_size; + + if (!data || off > payload) + return -EINVAL; + + if (last) { + tile_size = payload - off; + } else { + if (payload - off < 4) + return -EINVAL; + tile_size = get_unaligned_be32(&data[off]); + off += 4; + if (tile_size > payload - off) + return -EINVAL; + } + if (!tile_size) + return -EINVAL; + + *offset = off; + *size = tile_size; + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_vp9_next_tile); + +static int set_tiles(struct avd_ctx *ctx, struct avd_vp9_run *run) { const struct v4l2_ctrl_vp9_frame *frame = run->decode_params; struct avd_vp9_ctx *vp9_ctx = ctx->priv; struct vb2_v4l2_buffer *src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); const u8 *data = vb2_plane_vaddr(&src->vb2_buf, 0); - + u32 payload = vb2_get_plane_payload(&src->vb2_buf, 0); u32 offset = frame->uncompressed_header_size + frame->compressed_header_size; - u32 size = vb2_get_plane_payload(&src->vb2_buf, 0) - offset; u32 num_tile_rows = 1 << frame->tile_rows_log2; u32 num_tile_cols = 1 << frame->tile_cols_log2; u32 tile_size; + int ret; /* 6.2.6 Compute image size syntax */ u32 sb_64_cols = (((frame->frame_width_minus_1 + 8) >> 3) + 7) >> 3; @@ -512,18 +573,15 @@ static void set_tiles(struct avd_ctx *ctx, struct avd_vp9_run *run) for (int row = 0; row < num_tile_rows; row++) for (int col = 0; col < num_tile_cols; col++) { + /* Every tile lies within the payload. */ + ret = avd_vp9_next_tile(data, payload, + row == num_tile_rows - 1 && + col == num_tile_cols - 1, + &offset, &tile_size); + if (ret) + return ret; + ctx->job.num++; - if (row == num_tile_rows - 1 && - col == num_tile_cols - 1) { - tile_size = size; - } else { - tile_size = get_unaligned_be32(&data[offset]); - /* i have crashed my computer because of this */ - if (tile_size > size - 4) - return; - offset += 4; - size -= 4; - } push(AVD_OP_CODED_DATA | AVD_OP_CODED_DATA_ADDR( run->base.coded_in >> 32), @@ -546,9 +604,10 @@ static void set_tiles(struct avd_ctx *ctx, struct avd_vp9_run *run) "til_ac0_tile_dims"); offset += tile_size; - size -= tile_size; vp9_ctx->b->submit_num++; } + + return 0; } static void update_dec_buf_info(struct avd_decoded_buffer *buf, @@ -567,6 +626,8 @@ static void update_ctx_cur_info(struct avd_vp9_ctx *vp9_ctx, vp9_ctx->b->cur.reference_mode = dec_params->reference_mode; vp9_ctx->b->cur.interpolation_filter = dec_params->interpolation_filter; vp9_ctx->b->cur.flags = dec_params->flags; + vp9_ctx->b->cur.width = dec_params->frame_width_minus_1 + 1; + vp9_ctx->b->cur.height = dec_params->frame_height_minus_1 + 1; vp9_ctx->b->cur.timestamp = buf->base.vb.vb2_buf.timestamp; vp9_ctx->b->cur.color = vp9_ctx->b->bufs.color.addr; vp9_ctx->b->cur.seg = dec_params->seg; @@ -576,6 +637,14 @@ static void update_ctx_cur_info(struct avd_vp9_ctx *vp9_ctx, static void update_ctx_last_info(struct avd_vp9_ctx *vp9_ctx) { vp9_ctx->last = vp9_ctx->b->cur; + /* + * The decoder does not carry a reset map forward: a frame that keeps the + * map after one with VP9_SEG_RESET reads the old map again. So the reset + * stays until a frame has written a new map. + */ + if ((vp9_ctx->last.seg.flags & V4L2_VP9_SEGMENTATION_FLAG_ENABLED) && + (vp9_ctx->last.seg.flags & V4L2_VP9_SEGMENTATION_FLAG_UPDATE_MAP)) + vp9_ctx->seg_reset = false; } static void copy_vp9_frame_mv(struct avd_vp9_probs *avd_probs, @@ -665,24 +734,69 @@ static void init_probs(struct avd_ctx *ctx, const struct avd_vp9_run *run) sizeof(avd_probs->seg.tree_probs)); } +static enum avd_image_fmt +avd_vp9_frame_image_fmt(const struct v4l2_ctrl_vp9_frame *frame) +{ + /* avd_vp9_try_ctrl() admits only 4:2:0 (profiles 0 and 2). */ + return frame->bit_depth == 8 ? AVD_IMG_FMT_420_8BIT : + AVD_IMG_FMT_420_10BIT; +} + +/* + * The row and column scratch is sized at STREAMON from the OUTPUT (coded) + * format, which cannot change while it streams. The CAPTURE format can be + * larger and can change meanwhile, so the frame must fit the coded size. + */ +VISIBLE_IF_KUNIT bool +avd_vp9_frame_fits(const struct v4l2_ctrl_vp9_frame *frame, u32 width, + u32 height) +{ + return frame->frame_width_minus_1 + 1 <= width && + frame->frame_height_minus_1 + 1 <= height; +} +EXPORT_SYMBOL_IF_KUNIT(avd_vp9_frame_fits); + static int validate_dec_params(struct avd_ctx *ctx, const struct v4l2_ctrl_vp9_frame *dec_params) { - unsigned int aligned_width, aligned_height; + unsigned int aligned_width, aligned_height, width, height; - if (dec_params->frame_height_minus_1 + 1 < 64 || - dec_params->frame_width_minus_1 + 1 < 64) + /* + * The CAPTURE format is at least 64x64, the minimum of the VP9 frame + * size range, so a smaller frame is decoded into a 64x64 buffer, as + * H.264, HEVC and AV1 frames are. That is measured on the legacy + * transport only. The firmware transports keep the 64-pixel floor + * until it is measured there: an input their firmware does not + * expect can reset the engine instead of failing the frame. + */ + if (!avd_backend_is_open(ctx->dev) && + (dec_params->frame_width_minus_1 + 1 < 64 || + dec_params->frame_height_minus_1 + 1 < 64)) + return -EINVAL; + + if (!avd_vp9_frame_fits(dec_params, fmt_width(ctx), fmt_height(ctx))) return -EINVAL; - aligned_width = round_up(dec_params->frame_width_minus_1 + 1, 64); - aligned_height = round_up(dec_params->frame_height_minus_1 + 1, 16); + aligned_width = max_t(unsigned int, + round_up(dec_params->frame_width_minus_1 + 1, 64), + 64); + aligned_height = max_t(unsigned int, + round_up(dec_params->frame_height_minus_1 + 1, 16), + 64); /* - * Userspace should update the capture/decoded format when the - * resolution changes. + * A larger frame needs a new capture format. On the legacy transport + * a smaller one is decoded into the current buffers with their + * stride: VP9 inter frames can change size and keep predicting from + * references of the old size, which set_refs() scales, so userspace + * may keep the buffers. The firmware transports keep requiring the + * format's size until that is measured there, as for the floor above. */ - if (aligned_width != ctx->decoded_fmt.fmt.pix_mp.width || - aligned_height != ctx->decoded_fmt.fmt.pix_mp.height) { + width = ctx->decoded_fmt.fmt.pix_mp.width; + height = ctx->decoded_fmt.fmt.pix_mp.height; + if (avd_backend_is_open(ctx->dev) ? + (aligned_width > width || aligned_height > height) : + (aligned_width != width || aligned_height != height)) { dev_err(ctx->dev->dev, "unexpected bitstream resolution %dx%d\n", aligned_width, aligned_height); @@ -738,10 +852,6 @@ static int avd_vp9_alloc_bufs(struct avd_ctx *ctx, struct avd_vp9_bank *bank) if (ret) return ret; - ret = avd_buf_alloc(avd, &bank->bufs.seg, DIV_ROUND_UP(w, 8) * 24); - if (ret) - return ret; - ret = avd_buf_alloc(avd, &bank->bufs.lf_left, DIV_ROUND_UP(h, 8) * 16 * bit_depth); if (ret) @@ -767,6 +877,40 @@ static int avd_vp9_alloc_bufs(struct avd_ctx *ctx, struct avd_vp9_bank *bank) return 0; } +/* + * VP9 6.2.13 tile_info(): tile_rows_log2 is 0, 1 or 2, and tile_cols_log2 + * lies between calc_min_log2_tile_cols() and calc_max_log2_tile_cols() of + * 6.2.14, which follow from the frame width. The job has one segment per + * tile and the per-column scratch is sized for the column count this allows. + */ +#define VP9_MIN_TILE_WIDTH_B64 4 +#define VP9_MAX_TILE_WIDTH_B64 64 +#define VP9_MAX_TILE_ROWS_LOG2 2 + +VISIBLE_IF_KUNIT int +avd_vp9_check_tiling(const struct v4l2_ctrl_vp9_frame *frame) +{ + /* 6.2.6 Compute image size syntax */ + u32 sb_64_cols = (((frame->frame_width_minus_1 + 8) >> 3) + 7) >> 3; + u32 min_log2 = 0, max_log2 = 1; + + if (frame->tile_rows_log2 > VP9_MAX_TILE_ROWS_LOG2) + return -EINVAL; + + while ((VP9_MAX_TILE_WIDTH_B64 << min_log2) < sb_64_cols) + min_log2++; + while ((sb_64_cols >> max_log2) >= VP9_MIN_TILE_WIDTH_B64) + max_log2++; + max_log2--; + + if (frame->tile_cols_log2 < min_log2 || + frame->tile_cols_log2 > max_log2) + return -EINVAL; + + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_vp9_check_tiling); + /* * Only VP9 profiles 0 and 2 (4:2:0, 8 and 10 bits) decode. A profile 1 * frame (4:2:2 or 4:4:4) is never completed: it times out and the whole @@ -783,12 +927,12 @@ static int avd_vp9_validate_frame(struct avd_ctx *ctx, if (frame->bit_depth != (frame->profile == 2 ? 10 : 8)) return -EINVAL; - return 0; + return avd_vp9_check_tiling(frame); } static int avd_vp9_run_preamble(struct avd_ctx *ctx, struct avd_vp9_run *run) { - struct v4l2_ctrl *ctrl; + struct v4l2_ctrl *ctrl, *hdr; const struct v4l2_ctrl_vp9_frame *dec_params; struct avd_vp9_ctx *vp9_ctx = ctx->priv; unsigned int fctx_idx; @@ -798,16 +942,25 @@ static int avd_vp9_run_preamble(struct avd_ctx *ctx, struct avd_vp9_run *run) if (run->base.setup_err) return run->base.setup_err; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_VP9_COMPRESSED_HDR); - if (WARN_ON(!ctrl)) - return -EINVAL; - run->prob_updates = ctrl->p_cur.p; - + hdr = v4l2_ctrl_find(&ctx->ctrl_hdl, + V4L2_CID_STATELESS_VP9_COMPRESSED_HDR); ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_VP9_FRAME); - if (WARN_ON(!ctrl)) + if (WARN_ON(!hdr || !ctrl)) return -EINVAL; - dec_params = ctrl->p_cur.p; + + /* + * A plain VIDIOC_S_EXT_CTRLS can change the controls while the job is + * built; check and build from copies taken under the control lock. + */ + v4l2_ctrl_lock(ctrl); + run->prob_updates = kmemdup(hdr->p_cur.p, sizeof(*run->prob_updates), + GFP_KERNEL); + run->decode_params = kmemdup(ctrl->p_cur.p, + sizeof(*run->decode_params), GFP_KERNEL); + v4l2_ctrl_unlock(ctrl); + if (!run->prob_updates || !run->decode_params) + return -ENOMEM; + dec_params = run->decode_params; ret = validate_dec_params(ctx, dec_params); if (ret) @@ -815,11 +968,12 @@ static int avd_vp9_run_preamble(struct avd_ctx *ctx, struct avd_vp9_run *run) /* The frame may have been set, unchecked, while another codec was selected. */ ret = avd_vp9_validate_frame(ctx, dec_params); + if (!ret) + ret = avd_check_run_image_fmt(ctx, + avd_vp9_frame_image_fmt(dec_params)); if (ret) return ret; - run->decode_params = dec_params; - if (avd_backend_is_qfw(ctx->dev)) { struct avd_vp9_bank *bank = NULL; @@ -838,6 +992,24 @@ static int avd_vp9_run_preamble(struct avd_ctx *ctx, struct avd_vp9_run *run) bank - vp9_ctx->bank + 1; } + /* + * VP9 clears the segmentation map when the frame size changes, and the + * decoder carries part of it over in the seg buffer. The frame in the + * other bank may still be reading the old map, so move to the other + * buffer and clear that one: at most one frame is in flight besides this + * one, and it uses the current buffer. The map reset goes to every frame + * that uses segmentation until one updates the map (make_flags1(), + * update_ctx_last_info()). + */ + if (vp9_ctx->last.valid && !avd_vp9_same_size(dec_params, &vp9_ctx->last)) { + struct avd_buf *seg; + + vp9_ctx->seg_cur ^= 1; + seg = &vp9_ctx->seg_buf[vp9_ctx->seg_cur]; + memset(seg->cpu, 0, seg->size); + vp9_ctx->seg_reset = true; + } + vp9_ctx->b->cur.tx_mode = run->prob_updates->tx_mode; fctx_idx = v4l2_vp9_reset_frame_ctx(dec_params, vp9_ctx->frame_context); @@ -856,7 +1028,7 @@ static void avd_vp9_update_probs(struct avd_ctx *ctx, static int avd_vp9_run(struct avd_ctx *ctx) { - struct avd_vp9_run run; + struct avd_vp9_run run = {}; struct avd_vp9_ctx *vp9_ctx; struct avd_decoded_buffer *dst; int ret; @@ -864,17 +1036,16 @@ static int avd_vp9_run(struct avd_ctx *ctx) ret = avd_vp9_run_preamble(ctx, &run); if (ret) { avd_run_postamble(ctx, &run.base); - return ret; + goto out; } - ret = avd_init_job( - ctx, AVD_CODEC_VP9, - (1 << run.decode_params->tile_rows_log2) * - (1 << run.decode_params->tile_cols_log2) + - 1); + /* One segment per tile, bounded by avd_vp9_check_tiling(), and the header. */ + ret = avd_init_job(ctx, AVD_CODEC_VP9, + ((size_t)1 << (run.decode_params->tile_rows_log2 + + run.decode_params->tile_cols_log2)) + 1); if (ret) { avd_run_postamble(ctx, &run.base); - return ret; + goto out; } init_probs(ctx, &run); @@ -886,8 +1057,10 @@ static int avd_vp9_run(struct avd_ctx *ctx) set_header(ctx, &run); vp9_ctx->b->submit_num = 0; - set_tiles(ctx, &run); + ret = set_tiles(ctx, &run); avd_run_postamble(ctx, &run.base); + if (ret) + goto out; if (avd_backend_is_qfw(ctx->dev)) { /* Forward updates need no hardware result; publish before next prepare. */ @@ -896,7 +1069,11 @@ static int avd_vp9_run(struct avd_ctx *ctx) update_ctx_last_info(vp9_ctx); ctx->job_fifo = vp9_ctx->b->bufs.inst.addr; } - return avd_submit_job(ctx); + ret = avd_submit_job(ctx); +out: + kfree(run.decode_params); + kfree(run.prob_updates); + return ret; } #define copy_tx_and_skip(p1, p2) \ @@ -1119,6 +1296,8 @@ static void avd_vp9_free(struct avd_ctx *ctx, struct avd_vp9_ctx *vp9_ctx) struct avd_dev *avd = ctx->dev; ctx->max_frames = 1; + avd_buf_free(avd, &vp9_ctx->seg_buf[0]); + avd_buf_free(avd, &vp9_ctx->seg_buf[1]); for (unsigned int i = 0; i < vp9_ctx->nbanks; i++) { struct avd_vp9_bank *bank = &vp9_ctx->bank[i]; @@ -1126,7 +1305,6 @@ static void avd_vp9_free(struct avd_ctx *ctx, struct avd_vp9_ctx *vp9_ctx) avd_buf_free(avd, &bank->bufs.inst); avd_buf_free(avd, &bank->bufs.probs); avd_buf_free(avd, &bank->bufs.counts); - avd_buf_free(avd, &bank->bufs.seg); avd_buf_free(avd, &bank->bufs.color); avd_buf_free(avd, &bank->bufs.ip_above); avd_buf_free(avd, &bank->bufs.lf_above); @@ -1144,6 +1322,7 @@ static void avd_vp9_stop(struct avd_ctx *ctx) /* drain() excludes readiness callbacks before private storage is freed. */ avd_vp9_free(ctx, ctx->priv); ctx->priv = NULL; + ctx->scratch_sized = false; } static int avd_vp9_start(struct avd_ctx *ctx) @@ -1157,6 +1336,12 @@ static int avd_vp9_start(struct avd_ctx *ctx) vp9_ctx->nbanks = avd_qfw_has_vp_done(ctx->dev) ? AVD_VP9_BANKS : 1; vp9_ctx->b = &vp9_ctx->bank[0]; + for (unsigned int i = 0; i < ARRAY_SIZE(vp9_ctx->seg_buf); i++) { + ret = avd_buf_alloc(ctx->dev, &vp9_ctx->seg_buf[i], + DIV_ROUND_UP(fmt_width(ctx), 8) * 24); + if (ret) + goto err_free_ctx; + } for (unsigned int i = 0; i < vp9_ctx->nbanks; i++) { ret = avd_vp9_alloc_bufs(ctx, &vp9_ctx->bank[i]); if (ret) @@ -1164,6 +1349,9 @@ static int avd_vp9_start(struct avd_ctx *ctx) avd_init_v4l2_vp9_count_tbl(&vp9_ctx->bank[i]); } ctx->max_frames = vp9_ctx->nbanks; + /* avd_vp9_alloc_bufs() sized the scratch for this depth */ + ctx->scratch_fmt = ctx->image_fmt; + ctx->scratch_sized = true; /* job_ready can run while STREAMON is still initializing this codec. */ smp_store_release(&ctx->priv, vp9_ctx); @@ -1177,25 +1365,31 @@ static int avd_vp9_start(struct avd_ctx *ctx) static enum avd_image_fmt avd_vp9_get_image_fmt(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { -#define BIT_DEPTH(chroma) \ - (frame->bit_depth == 8 ? AVD_IMG_FMT_##chroma##_8BIT : \ - AVD_IMG_FMT_##chroma##_10BIT) - const struct v4l2_ctrl_vp9_frame *frame = ctrl->p_new.p_vp9_frame; - if (ctrl->id != V4L2_CID_STATELESS_VP9_FRAME) return AVD_IMG_FMT_ANY; - /* avd_vp9_try_ctrl() admits only 4:2:0 (profiles 0 and 2). */ - return BIT_DEPTH(420); -#undef BIT_DEPTH + return avd_vp9_frame_image_fmt(ctrl->p_new.p_vp9_frame); } static int avd_vp9_try_ctrl(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { - if (ctrl->id == V4L2_CID_STATELESS_VP9_FRAME) - return avd_vp9_validate_frame(ctx, ctrl->p_new.p_vp9_frame); + const struct v4l2_ctrl_vp9_frame *frame = ctrl->p_new.p_vp9_frame; + struct vb2_queue *vq; - return 0; + if (ctrl->id != V4L2_CID_STATELESS_VP9_FRAME) + return 0; + + /* + * The OUTPUT format is fixed while its queue streams and the scratch + * is sized from it: a larger frame cannot be decoded, as the run + * finds too. Before that the format may still be set to the stream's. + */ + vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE); + if (vb2_is_streaming(vq) && + !avd_vp9_frame_fits(frame, fmt_width(ctx), fmt_height(ctx))) + return -EINVAL; + + return avd_vp9_validate_frame(ctx, frame); } static unsigned int avd_vp9_pp_kicks(struct avd_ctx *ctx) diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 568cbfc6d06f8d..6bd4b9e6dbc1ba 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -34,18 +34,35 @@ #define AVD_CAPABILITY_VP9 BIT(2) #define AVD_CAPABILITY_AV1 BIT(3) -/* Shifts addreses right and bytesperline?? */ +/* + * Shifted addressing of the first decoders (T8103, T6000, T8112): every + * address in the instruction stream is one word in 256-byte units (addr >> 8), + * a compressed-plane address one word in 128-byte units (addr >> 7), the + * instruction FIFO base one register (addr >> 8, no IOVA_HI), and + * a plane pitch is in 16-byte units (bytesperline >> 4). Later decoders take + * byte addresses as two words and byte pitches. + */ #define AVD_QUIRK_LSR BIT(0) +/* + * The decoder takes no pipe state buffer (T8103, T6000): the frame header + * carries no pipe_state address, its PIPE_STATE op flag and H.264/HEVC + * PIPE_STATE_EN feature field stay clear, and H.264 and VP9 allocate no + * pipe_state buffer. + */ #define AVD_QUIRK_NO_PIPE_STATE BIT(1) /* HEVC DMA configuration and extended scratch-address table. */ #define AVD_QUIRK_HEVC_V5_HEADER BIT(2) -/* T8140: pace only HEVC submissions, with a shorter back-off. */ -#define AVD_QUIRK_V5_QUEUE_PACING BIT(3) /* H.264 co-located motion vectors take 128 bytes per macroblock, not 64. */ #define AVD_QUIRK_H264_MV_128 BIT(4) -/* A reset after a timeout hangs the machine: stay parked and retire the decoder */ +/* + * A reset after a timeout hangs the machine: stay parked and retire the + * decoder. Cause unknown, see avd_pm_recover() and + * https://github.com/aurora-silicon/linux/issues/2450. + */ #define AVD_QUIRK_NO_RECOVERY_RESET BIT(5) +#define AVD_QUIRK_KOPSIA BIT(6) + #define VP_SLOT_NONE 255 #define INST_FIFO_SLOT_NONE 255 @@ -212,7 +229,7 @@ struct avd_variant { unsigned int fw_caps_required; void (*configure_stream)(struct avd_dev *avd, dma_addr_t addr, u8 fifo_idx, u32 vp_slot); - const char* fw_name; + const char *fw_name; /* Older image tried when fw_name is not installed (legacy transport). */ const char *fw_name_fallback; unsigned char revision; /* the same as the device tree */ @@ -241,7 +258,7 @@ struct avd_dev { struct iommu_domain *domain; struct iommu_domain *empty_domain; - /* Core and perf-floor domains when the node lists more than one. */ + /* Power domains linked to runtime PM when the node lists more than one. */ struct dev_pm_domain_list *pd_list; struct mutex vdev_lock; @@ -300,7 +317,12 @@ struct avd_segment { struct avd_job { enum avd_codec codec; + /* index of the segment being written */ size_t num; + /* segments allocated */ + size_t max; + /* an instruction did not fit; the job must not be submitted */ + bool overflow; struct avd_segment *segments; }; @@ -338,6 +360,12 @@ struct avd_ctx { void *priv; struct avd_comp comp; + /* + * Picture format the codec sized its per-stream scratch for at + * STREAMON, if it sizes any from the picture format. + */ + bool scratch_sized; + enum avd_image_fmt scratch_fmt; int fifo_idx; /* Pictures of this context the queue may hold at once (0 or 1: one). */ unsigned int max_frames; @@ -361,15 +389,55 @@ void avd_job_finish_no_pm(struct avd_ctx *ctx, enum vb2_buffer_state result); void avd_job_finish(struct avd_ctx *ctx, enum vb2_buffer_state result); void avd_run_preamble(struct avd_ctx *ctx, struct avd_run *run); +int avd_check_run_image_fmt(struct avd_ctx *ctx, enum avd_image_fmt image_fmt); void avd_run_postamble(struct avd_ctx *ctx, struct avd_run *run); +int avd_ctrl_copy(struct avd_ctx *ctx, u32 id, void *dst, size_t size); #if IS_ENABLED(CONFIG_KUNIT) +int avd_ctrl_copy_value(struct v4l2_ctrl *ctrl, void *dst, size_t size); bool avd_h264_find_slice_data(const u8 *data, u32 len, u32 header_len, u32 *off); bool avd_h264_slice_fits(const struct v4l2_ctrl_h264_sps *sps, size_t held, size_t held_bytes, u32 len, size_t decoded_size); bool avd_h264_scaling_is_flat(const struct v4l2_ctrl_h264_pps *pps, const struct v4l2_ctrl_h264_scaling_matrix *scaling); +int avd_hevc_check_sps_geometry(const struct v4l2_ctrl_hevc_sps *sps); +int avd_hevc_check_tiles(const struct v4l2_ctrl_hevc_sps *sps, + const struct v4l2_ctrl_hevc_pps *pps); +int avd_hevc_check_slices(const struct v4l2_ctrl_hevc_sps *sps, + const struct v4l2_ctrl_hevc_pps *pps, + const struct v4l2_ctrl_hevc_decode_params *decode, + const struct v4l2_ctrl_hevc_slice_params *slices, + u32 num_slices, const u32 *entry_points, + u32 num_entry_points, u32 payload); +int avd_hevc_kunit_compute_tiles(const struct v4l2_ctrl_hevc_sps *sps, + const struct v4l2_ctrl_hevc_pps *pps, + u32 *tile_ids, size_t n); +int avd_av1_check_tiles(struct device *dev, unsigned int tile_rows, + unsigned int tile_cols, + const struct v4l2_ctrl_av1_tile_group_entry *tile_group, + unsigned int entries, size_t payload); +struct v4l2_ctrl_av1_tile_group_entry * +avd_av1_copy_tile_group(struct v4l2_ctrl *ctrl, unsigned int *entries); +int avd_av1_check_frame_size(const struct v4l2_ctrl_av1_frame *frame, + u32 width, u32 height); +int avd_h264_validate_sps_fmt(struct avd_ctx *ctx, + const struct v4l2_ctrl_h264_sps *sps); +int avd_h264_validate_sps(struct avd_ctx *ctx, + const struct v4l2_ctrl_h264_sps *sps); +int avd_h264_validate_sps_ctrl(struct avd_ctx *ctx, + const struct v4l2_ctrl_h264_sps *sps, + bool streaming); +int avd_hevc_validate_sps_fmt(struct avd_ctx *ctx, + const struct v4l2_ctrl_hevc_sps *sps); +size_t avd_h264_start_slices(const struct v4l2_ctrl_h264_sps *sps); +int avd_try_capture_fmt(struct file *file, void *priv, struct v4l2_format *f); +int avd_s_capture_fmt(struct file *file, void *priv, struct v4l2_format *f); +int avd_vp9_check_tiling(const struct v4l2_ctrl_vp9_frame *frame); +int avd_vp9_next_tile(const u8 *data, u32 payload, bool last, u32 *offset, + u32 *size); +bool avd_vp9_frame_fits(const struct v4l2_ctrl_vp9_frame *frame, u32 width, + u32 height); #endif extern const struct avd_coded_fmt_ops avd_h264_fmt_ops; @@ -410,6 +478,9 @@ void avd_queue_add_ctx(struct avd_ctx *ctx); void avd_queue_del_ctx(struct avd_ctx *ctx); int avd_open_build_program(struct avd_ctx *ctx); extern const struct avd_backend_ops avd_open_backend; +extern const struct avd_backend_ops avd_kopsia_backend; +int avd_open_submit(struct avd_dev *avd, struct avd_frame *f); +irqreturn_t avd_open_complete(struct avd_dev *avd, u32 status); extern const struct avd_backend_ops avd_apple_backend; extern const struct avd_backend_ops avd_qfw_backend; struct avd_qfw; @@ -418,6 +489,7 @@ void avd_qfw_select(struct avd_dev *avd); void avd_qfw_prepare_boot(struct avd_dev *avd); void avd_qfw_debug(struct avd_dev *avd, struct avd_frame *f, const char *where); bool avd_backend_is_qfw(const struct avd_dev *avd); +bool avd_backend_is_open(const struct avd_dev *avd); bool avd_qfw_has_vp_done(const struct avd_dev *avd); unsigned int avd_qfw_picture_banks(const struct avd_dev *avd, unsigned int codec); int avd_backend_select(struct avd_dev *avd); diff --git a/drivers/media/platform/apple/avd/tests/av1-test.py b/drivers/media/platform/apple/avd/tests/av1-test.py index b073c8929fe69e..df9a0e4ae1afe2 100644 --- a/drivers/media/platform/apple/avd/tests/av1-test.py +++ b/drivers/media/platform/apple/avd/tests/av1-test.py @@ -77,7 +77,14 @@ static unsigned long vb2_get_plane_payload(struct vb2_buffer *b,unsigned int p){(void)b;(void)p;return 1UL<<20;} static struct vb2_v4l2_buffer *current_src,*current_dst; static struct vb2_v4l2_buffer *v4l2_m2m_next_src_buf(void *m){(void)m;return current_src;} -struct v4l2_ctrl {unsigned int id; unsigned int elems; union {void *p;} p_cur;}; +struct device; +struct v4l2_ctrl {unsigned int id; unsigned int elems, elem_size; union {void *p;} p_cur;}; +static void v4l2_ctrl_lock(struct v4l2_ctrl *c){(void)c;} +static void v4l2_ctrl_unlock(struct v4l2_ctrl *c){(void)c;} +static void *kmemdup_array(const void *p,size_t n,size_t size,int f){ + (void)f;void *d=calloc(n?n:1,size);if(d)memcpy(d,p,n*size);return d;} +/* The run-time format check has its own KUnit suite (avd-fmt-test.c). */ +static int avd_check_run_image_fmt(struct avd_ctx *ctx,int f){(void)ctx;(void)f;return 0;} struct v4l2_ctrl_ref {struct v4l2_ctrl_ref *next; struct v4l2_ctrl *ctrl; bool p_req_valid; union {void *p;} p_req;}; struct v4l2_ctrl_handler {struct v4l2_ctrl_ref *ctrl_refs;}; #define list_for_each_entry(ref,head,node) for((ref)=*(head);(ref);(ref)=(ref)->next) @@ -92,12 +99,14 @@ static struct v4l2_ctrl_handler *v4l2_ctrl_request_hdl_find(void *req,void *h){(void)h;assert(req==&request_hdl);request_gets++;return &request_hdl;} static void v4l2_ctrl_request_hdl_put(struct v4l2_ctrl_handler *h){assert(h==&request_hdl);request_puts++;} static struct v4l2_ctrl *v4l2_ctrl_find(void *h,u32 id){ - (void)h;controls[0].p_cur.p=&seq;controls[1].p_cur.p=¶ms;controls[2].p_cur.p=&tile;controls[2].elems=1;controls[3].p_cur.p=&grain; + (void)h;controls[0].p_cur.p=&seq;controls[1].p_cur.p=¶ms;controls[2].p_cur.p=&tile;controls[2].elems=1;controls[2].elem_size=sizeof(tile);controls[3].p_cur.p=&grain; if(id==V4L2_CID_STATELESS_AV1_SEQUENCE)return &controls[0]; if(id==V4L2_CID_STATELESS_AV1_FRAME)return &controls[1]; if(id==V4L2_CID_STATELESS_AV1_TILE_GROUP_ENTRY)return &controls[2]; return &controls[3]; } +static int avd_ctrl_copy(struct avd_ctx *ctx,u32 id,void *dst,size_t size){ + (void)ctx;memcpy(dst,v4l2_ctrl_find(NULL,id)->p_cur.p,size);return 0;} static void avd_run_preamble(struct avd_ctx *ctx,struct avd_run *run){ (void)ctx;memset(run,0,sizeof(*run));run->bufs.src=current_src;run->bufs.dst=current_dst; run->coded_in=current_src->vb2_buf.dma;run->comp_out=current_dst->vb2_buf.dma; @@ -106,7 +115,7 @@ static void avd_run_postamble(struct avd_ctx *ctx,struct avd_run *run){(void)ctx;(void)run;} static int avd_init_job(struct avd_ctx *ctx,int codec,size_t segments){ free(ctx->job.segments);ctx->job.codec=codec;ctx->job.num=0; - ctx->job.segments=calloc(segments,sizeof(*ctx->job.segments));return ctx->job.segments?0:-ENOMEM; + ctx->job.segments=calloc(segments,sizeof(*ctx->job.segments));ctx->job.overflow=false;ctx->job.max=ctx->job.segments?segments:0;return ctx->job.segments?0:-ENOMEM; } static int avd_submit_job(struct avd_ctx *ctx); ''' diff --git a/drivers/media/platform/apple/avd/tests/dispatch-test.py b/drivers/media/platform/apple/avd/tests/dispatch-test.py index 4a46a45e141002..6bd1496fc19eff 100755 --- a/drivers/media/platform/apple/avd/tests/dispatch-test.py +++ b/drivers/media/platform/apple/avd/tests/dispatch-test.py @@ -92,6 +92,7 @@ const struct format *coded_fmt_desc; struct work_struct submit_work; bool draining,broken; unsigned int hw_errors,max_frames; enum avd_frame_dep next_dep; bool session_started; u64 session_generation; + u32 width,height; int ctrl_hdl; }; struct avd_variant { size_t fp_size; }; @@ -106,6 +107,7 @@ struct avd_ctx *deferred_ctx; struct avd_frame *building; unsigned int inflight; u64 frame_seq; bool compat_held,stopping,faulted; unsigned long rest_until,last_recover; unsigned int storm_count; + struct { const void *perf_ops; } pm; int queue_lock,queue_mutex,queue_work; void *dev,*m2m_dev; }; static struct avd_ctx *running; @@ -147,6 +149,20 @@ static void pm_runtime_mark_last_busy(void *d) { (void)d; } static void pm_runtime_put_autosuspend(void *d) { (void)d; assert(pm_refs);pm_refs--; } static void avd_pm_queue_changed(struct avd_dev *d) { (void)d; } +static unsigned int perf_starts,perf_idles; +static const void *last_perf_stream; +static u32 last_perf_width,last_perf_height; +static unsigned int last_perf_inflight,last_perf_streams; +static u32 fmt_width(struct avd_ctx *c) { return c->width ? c->width : 1920; } +static u32 fmt_height(struct avd_ctx *c) { return c->height ? c->height : 1080; } +static void avd_pm_perf_frame_start(struct avd_dev *d,const void *stream_id, + u32 width,u32 height,unsigned int inflight,unsigned int concurrent_streams) +{ + assert(d && d->pm.perf_ops); perf_starts++; + last_perf_stream=stream_id; last_perf_width=width; last_perf_height=height; + last_perf_inflight=inflight; last_perf_streams=concurrent_streams; +} +static void avd_pm_perf_idle(struct avd_dev *d) { assert(d && !d->inflight); perf_idles++; } static void mod_delayed_work(void *w,void *v,int t) { (void)w;(void)v;(void)t; } static int avd_buf_alloc(struct avd_dev *d,struct avd_buf *b,size_t n) { (void)d;(void)b;(void)n;return -ENOMEM; } static void *devm_kzalloc(void *d,size_t n,int f) { (void)d;(void)f;return calloc(1,n); } @@ -285,6 +301,28 @@ m[0].src=&src[18];m[0].dst=&dst[18];submit(&c[0]); assert(!running&&wakes==old_wakes+1&&irq_enables==1&&!d.rest_until&&!d.storm_count); complete(&d,&c[0],0);assert(!pm_refs); + /* Perf floor hooks stay silent without perf_ops and track streams when enabled. */ + assert(!perf_starts&&perf_idles); + { + static const int fake_perf_ops; + struct vb2_v4l2_buffer perf_src[3]={},perf_dst[3]={}; + unsigned int old_idles=perf_idles; + d.pm.perf_ops=&fake_perf_ops; + c[0].width=3840;c[0].height=2160;c[1].width=1920;c[1].height=1080; + m[0].src=&perf_src[0];m[0].dst=&perf_dst[0];submit(&c[0]); + assert(perf_starts==1&&last_perf_stream==&c[0]&&last_perf_width==3840&&last_perf_height==2160); + assert(last_perf_inflight==1&&last_perf_streams==1&&perf_idles==old_idles); + m[1].src=&perf_src[1];m[1].dst=&perf_dst[1];submit(&c[1]); + assert(perf_starts==2&&last_perf_stream==&c[1]&&last_perf_width==1920&&last_perf_height==1080); + assert(last_perf_inflight==2&&last_perf_streams==2&&perf_idles==old_idles); + complete(&d,&c[0],0);assert(perf_idles==old_idles); + complete(&d,&c[1],0);assert(perf_idles==old_idles+1&&!d.inflight&&!pm_refs); + perf_src[2].flags=V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF; + m[0].src=&perf_src[2];m[0].dst=&perf_dst[2];submit(&c[0]); + assert(perf_starts==2&&perf_idles==old_idles+2&&!d.inflight&&!pm_refs); + m[0].dst=NULL; + d.pm.perf_ops=NULL; + } /* A failed wake retires the decoder and never opens IRQs or posts a frame. */ d.rest_until=jiffies;wake_error=-EIO;m[0].src=&src[19];m[0].dst=&dst[19]; unsigned int old_sent=send_count;submit(&c[0]);assert(d.faulted&&irq_enables==1&&send_count==old_sent); @@ -413,7 +451,9 @@ def main(): function(CORE.read_text(), 'v4l2_m2m_buf_done_and_job_finish') + function(legacy, 'avd_job_finish_no_pm') + function(legacy, 'avd_job_finish') + function(source, 'avd_send_frame') + - function(source, 'avd_retire') + function(source, 'avd_queue_submit_work') + + function(source, 'avd_retire') + + function(source, 'avd_active_stream_stats') + + function(source, 'avd_queue_submit_work') + function(source, 'avd_frame_vp_complete') + function(source, 'avd_retire_vp') + function(source, 'avd_queue_ready') + VP_MAIN + MAIN.replace(' puts("PASS: production dispatch', ' check_vp_events();\n puts("PASS: production dispatch')) exe = out / 'dispatch-test' diff --git a/drivers/media/platform/apple/avd/tests/host_source.py b/drivers/media/platform/apple/avd/tests/host_source.py index b473b65e3c4edf..0251d1e3b833cc 100644 --- a/drivers/media/platform/apple/avd/tests/host_source.py +++ b/drivers/media/platform/apple/avd/tests/host_source.py @@ -4,7 +4,8 @@ def function(source, name): - match = re.search(r"^[A-Za-z_][\w *]*\b" + re.escape(name) + + # The return type may sit on the line before the name. + match = re.search(r"^(?:[A-Za-z_][\w *]*\n)?(?:[A-Za-z_][\w *]*\b)?" + re.escape(name) + r"\([^;{}]*?\)\n\{", source, re.M) if not match: raise ValueError(name) diff --git a/drivers/media/platform/apple/avd/tests/program-test.py b/drivers/media/platform/apple/avd/tests/program-test.py index 5502470ca6aaed..842d75ecb7d081 100755 --- a/drivers/media/platform/apple/avd/tests/program-test.py +++ b/drivers/media/platform/apple/avd/tests/program-test.py @@ -55,8 +55,8 @@ #define AVD_MAX_INST 512 #define AVD_CODEC_AV1 3 #define AVD_MAX_FRAMES 16 -#define AVD_IMG_FMT_420_10BIT 1 -#define AVD_IMG_FMT_422_10BIT 2 +enum avd_image_fmt { AVD_IMG_FMT_ANY, AVD_IMG_FMT_420_8BIT, AVD_IMG_FMT_420_10BIT, + AVD_IMG_FMT_422_8BIT, AVD_IMG_FMT_422_10BIT }; #define AVD_FRAME_SUBMITTED 2 #define AVD_FRAME_DONE 3 #define IRQ_HANDLED 1 @@ -91,7 +91,7 @@ dma_addr_t fifo_iova; u32 cmd[24], tag; unsigned long deadline; int state,status; struct avd_ctx *ctx; }; struct avd_segment { u32 instructions[AVD_MAX_INST]; size_t num; }; -struct avd_job { struct avd_segment *segments; unsigned int num, codec; }; +struct avd_job { struct avd_segment *segments; unsigned int num, codec; size_t max; bool overflow; }; struct avd_dev; struct avd_variant { unsigned int quirks, revision, fifo_slots, vp_slots[4], vp_slot_base[4]; void (*configure_stream)(struct avd_dev *,dma_addr_t,u8,u32); }; @@ -265,7 +265,7 @@ decode.flags=idx%3?0:V4L2_H264_DECODE_PARAM_FLAG_IDR_PIC; decode.dpb[0].flags=idx%3?V4L2_H264_DPB_ENTRY_FLAG_VALID:0; sl.slice_type=idx%3==0?V4L2_H264_SLICE_TYPE_I:idx%3==1?V4L2_H264_SLICE_TYPE_P:V4L2_H264_SLICE_TYPE_B; - ctx.job.segments=calloc(3,sizeof(*ctx.job.segments)); assert(ctx.job.segments); + ctx.job.segments=calloc(3,sizeof(*ctx.job.segments)); assert(ctx.job.segments); ctx.job.max=3; stream_hdr(&ctx,&run); ctx.job.num=1;sl.first_mb_in_slice=0;slice.addr=0x200800000ULL; stream_slice(&ctx,&run); size_t continuation=1+ctx.job.segments[0].num+ctx.job.segments[1].num; @@ -418,15 +418,18 @@ def h264_prelude(): static struct vb2_v4l2_buffer *v4l2_m2m_next_src_buf(void *m) { (void)m;return fixture_run.base.bufs.src; } static size_t vb2_get_plane_payload(struct vb2_buffer *b,int p) { (void)b;(void)p;return valid_data?16:2; } static void *vb2_plane_vaddr(struct vb2_buffer *b,int p) { (void)b;(void)p;static u8 data[16];return data; } -static void avd_h264_run_preamble(struct avd_ctx *ctx,struct avd_h264_run *r) { (void)ctx;*r=fixture_run; } +static int avd_h264_run_preamble(struct avd_ctx *ctx,struct avd_h264_run *r) { (void)ctx;*r=fixture_run;return 0; } +/* The run-time format check has its own KUnit suite (avd-fmt-test.c). */ +static int avd_check_run_image_fmt(struct avd_ctx *ctx,int f) { (void)ctx;(void)f;return 0; } static void avd_run_postamble(struct avd_ctx *ctx,struct avd_run *r) { (void)ctx;(void)r;postambles++; } static bool avd_h264_slice_fits(const struct v4l2_ctrl_h264_sps *s,size_t n,size_t b,u32 l,size_t z) { (void)s;(void)b;(void)l;(void)z;return n<20; } static size_t avd_h264_max_slices(const struct v4l2_ctrl_h264_sps *s) { (void)s;return 20; } static int avd_h264_realloc_slices(struct avd_ctx *c,size_t n) { (void)c;(void)n;abort(); } static int avd_init_job(struct avd_ctx *c,unsigned int codec,size_t n) { - free(c->job.segments);c->job.codec=codec;c->job.num=0; - c->job.segments=calloc(n,sizeof(*c->job.segments));return c->job.segments?0:-ENOMEM; + free(c->job.segments);c->job.codec=codec;c->job.num=0;c->job.overflow=false; + c->job.segments=calloc(n,sizeof(*c->job.segments));c->job.max=c->job.segments?n:0; + return c->job.segments?0:-ENOMEM; } static void avd_job_finish(struct avd_ctx *c,enum vb2_buffer_state s) { (void)c;assert(s==VB2_BUF_STATE_DONE);held_finishes++; } static int avd_submit_job(struct avd_ctx *c) { submissions++;return avd_open_build_program(c); } @@ -457,6 +460,7 @@ def h264_prelude(): } /* Applied SPS controls reject unequal depths for both codecs. */ struct v4l2_ctrl_hevc_sps hevc={.chroma_format_idc=1, + .log2_min_luma_coding_block_size_minus3=1,.log2_diff_max_min_luma_coding_block_size=2, .pic_width_in_luma_samples=1920,.pic_height_in_luma_samples=1088}; ctx.coded_fmt.fmt.pix_mp.width=1920;ctx.coded_fmt.fmt.pix_mp.height=1088; for(unsigned int luma=0;luma<5;luma++) for(unsigned int chroma=0;chroma<5;chroma++) { @@ -475,7 +479,7 @@ def h264_prelude(): assert(!avd_h264_run(&ctx));assert(submissions==1&&hc.bank[0].submitted&&dst[0].bank==1); /* Compare the complete header to one built with the emitted VALID count. */ struct avd_segment expected={0};struct avd_job saved=ctx.job; - ctx.job=(struct avd_job){.segments=&expected};fixture_run.num_valid=2;fixture_run.cur_poc=40; + ctx.job=(struct avd_job){.segments=&expected,.max=1};fixture_run.num_valid=2;fixture_run.cur_poc=40; stream_hdr(&ctx,&fixture_run); assert(!memcmp((u32 *)programs[0].cpu+1,expected.instructions,expected.num*sizeof(u32))); ctx.job=saved; @@ -535,19 +539,27 @@ def prepare_regressions(out): inst = re.sub(r'^#include.*\n', '', (ROOT / 'avd-inst.h').read_text(), flags=re.M) helpers = re.sub(r'^#include.*\n', '', (ROOT / 'avd-h264-params.h').read_text(), flags=re.M) pre = h264_prelude().replace('struct vb2_v4l2_buffer *dst; } bufs;', 'struct vb2_v4l2_buffer *src,*dst; } bufs;') + pre = pre.replace('dma_addr_t comp_out, y_out, uv_out;', 'dma_addr_t coded_in, comp_out, y_out, uv_out;') pre = pre.replace('struct { struct { struct { struct { u32 bytesperline; } plane_fmt[1]; } pix_mp; } fmt; } decoded_fmt;', 'struct { struct { struct v4l2_pix_format_mplane pix_mp; } fmt; } decoded_fmt,coded_fmt;') pre = pre.replace('struct vb2_buffer vb2_buf; };', 'struct vb2_buffer vb2_buf; unsigned int flags; };') pre = pre.replace('unsigned int bank; };', 'unsigned int bank; size_t grey_chroma_offset; bool grey_chroma_10bit; };') + pre += '#define S8_MIN (-128)\n#define S8_MAX 127\n#define U32_MAX UINT32_MAX\n' + pre += '#define IS_ENABLED(x) 0\n' pre += 'enum vb2_buffer_state { VB2_BUF_STATE_DONE, VB2_BUF_STATE_ERROR };\n' - code = pre + helpers + inst + h264 - for name in ('avd_h264_alloc_bufs', 'avd_h264_validate_sps', 'avd_h264_validate_pps', + parse_h = re.sub(r'^#include.*\n', '', (ROOT / 'avd-h264-parse.h').read_text(), flags=re.M) + parse_c = re.sub(r'^#include.*\n', '', (ROOT / 'avd-h264-parse.c').read_text(), flags=re.M) + code = pre + helpers + parse_h + parse_c + inst + h264 + for name in ('avd_h264_alloc_bufs', 'avd_h264_validate_sps_fmt', 'avd_h264_validate_sps', + 'avd_h264_validate_pps', 'avd_h264_validate_slice', 'avd_h264_drop_bank_slices', 'avd_h264_pick_bank', 'avd_h264_abort_picture', 'avd_h264_refs_valid', 'avd_h264_done'): code += function(source, name) code += function((ROOT / 'avd-backend-open.c').read_text(), 'avd_open_build_program') + code += function((ROOT / 'avd-hevc.c').read_text(), 'avd_hevc_check_sps_geometry') + code += function((ROOT / 'avd-hevc.c').read_text(), 'avd_hevc_validate_sps_fmt') code += function((ROOT / 'avd-hevc.c').read_text(), 'avd_hevc_validate_sps') - code += RUN_FIXTURE + function(source, 'avd_h264_run') + RUN_MAIN + code += RUN_FIXTURE + function(source, 'avd_h264_sps_image_fmt') + function(source, 'avd_h264_run_frame') + function(source, 'avd_h264_run') + RUN_MAIN dest = out / 'prepare.c' dest.write_text(code) exe = dest.with_suffix('') @@ -568,7 +580,7 @@ def prepare_regressions(out): struct avd_decoded_buffer destination = {0}; struct avd_segment segments[2]; struct avd_ctx ctx_storage = { .priv = &hc, .dev = &dev, - .fh.m2m_ctx = &m2m, .job.segments = segments, .decomp = true }; + .fh.m2m_ctx = &m2m, .job.segments = segments, .job.max = 2, .decomp = true }; struct avd_ctx *ctx = &ctx_storage; struct v4l2_ctrl_h264_decode_params dec = {0}; struct v4l2_ctrl_h264_sps sps = { .chroma_format_idc = 1, diff --git a/drivers/media/platform/apple/avd/tests/recovery-test.py b/drivers/media/platform/apple/avd/tests/recovery-test.py index 66c7e0cdd84536..e78070c2d1a76f 100755 --- a/drivers/media/platform/apple/avd/tests/recovery-test.py +++ b/drivers/media/platform/apple/avd/tests/recovery-test.py @@ -24,6 +24,7 @@ #define AVD_RECOVER_GAP_MS 20 #define AVD_STORM_MAX 2 #define AVD_STORM_WINDOW 60000 +#define AVD_QUIRK_NO_RECOVERY_RESET (1U << 5) #define msecs_to_jiffies(x) (x) #define jiffies_to_msecs(x) ((unsigned int)(x)) #define time_before(a,b) ((long)((a)-(b))<0) @@ -41,6 +42,7 @@ struct avd_dev; struct avd_ctx { bool session_started; }; struct frame { int state,status; }; +struct avd_variant { unsigned int quirks; }; struct avd_backend_ops { void (*shutdown)(struct avd_dev *); int (*resume)(struct avd_dev *); @@ -53,6 +55,7 @@ struct avd_dev { void *dev,*domain,*empty_domain,*rstc,*compat_active; const struct avd_backend_ops *backend; + const struct avd_variant *variant; struct { bool dart_active,dma_parked,irq_enabled,hw_on; int irq,hw_lock,lock;unsigned int irq_gen; @@ -65,7 +68,7 @@ static unsigned long jiffies=100; static void *attached; static int reset_error,boot_error,attach_error; -static unsigned int resets,boots,attaches,detaches,shutdowns,resubmits,drains,irq_opens,irq_closes,step,block_step,reset_step; +static unsigned int resets,boots,attaches,detaches,shutdowns,resubmits,drains,irq_opens,irq_closes,perf_suspends,step,block_step,reset_step; static bool pm_runtime_suspended(void *dev) { (void)dev;return false; } static void disable_irq_nosync(int irq) { assert(irq==1);irq_closes++; } static void enable_irq(int irq) { assert(irq==1);assert(!d.pm.dma_parked);irq_opens++; } @@ -94,42 +97,53 @@ } static void resubmit(struct avd_dev *avd) { (void)avd;resubmits++; } static void avd_pm_drain_unmaps(struct avd_dev *avd) { assert(avd->pm.dart_active);drains++; } +static void avd_pm_perf_suspend(struct avd_dev *avd) { + assert(avd==&d); + if(avd->pm.dart_active) assert(!d.pm.hw_on&&!d.pm.irq_enabled); + perf_suspends++; +} ''' MAIN = r''' static const struct avd_backend_ops backend={.shutdown=shutdown_backend}; +static const struct avd_variant no_recovery_reset = { .quirks = AVD_QUIRK_NO_RECOVERY_RESET }; static const struct queue queue={.idle=idle,.resubmit=resubmit}; static int domain_token,empty_token; static void init(void) { d=(struct avd_dev){.dev=&d,.domain=&domain_token,.empty_domain=&empty_token,.backend=&backend, .pm={.dart_active=true,.irq_enabled=true,.hw_on=true,.irq=1,.queue=&queue}}; attached=d.domain;reset_error=boot_error=attach_error=0; - resets=boots=attaches=detaches=shutdowns=resubmits=drains=irq_opens=irq_closes=step=0; + resets=boots=attaches=detaches=shutdowns=resubmits=drains=irq_opens=irq_closes=perf_suspends=step=0; } int main(void) { - init();assert(!avd_pm_recover(&d));assert(resets==1&&boots==1&&attaches==1&&detaches==1); + init();assert(!avd_pm_recover(&d));assert(resets==1&&boots==1&&attaches==1&&detaches==1&&perf_suspends==1); assert(!d.pm.dma_parked&&!d.pm.irq_enabled&&attached==d.domain); avd_pm_enable_irq(&d);assert(irq_opens==1); + init(); + d.variant = &no_recovery_reset; + assert(avd_pm_recover(&d) == -EIO); + assert(attaches == 1 && !resets && !boots && !detaches && perf_suspends == 1); + assert(d.pm.dma_parked && !d.pm.irq_enabled && attached == d.empty_domain); init();reset_error=-EIO;d.frames[0].state=AVD_FRAME_SUBMITTED;avd_reset_queue(&d,-ETIMEDOUT); - assert(d.faulted&&resets==1&&!boots&&!detaches&&d.pm.dma_parked&&attached==d.empty_domain); + assert(d.faulted&&resets==1&&!boots&&!detaches&&d.pm.dma_parked&&attached==d.empty_domain&&perf_suspends==1); assert(d.frames[0].state==AVD_FRAME_DONE&&!d.pm.irq_enabled); d.frames[0].state=AVD_FRAME_FREE; assert(!avd_pm_power_off(&d)&&!avd_pm_power_on(&d)); - assert(!boots&&!resubmits&&!d.pm.irq_enabled&&attached==d.empty_domain); + assert(!boots&&!resubmits&&!d.pm.irq_enabled&&attached==d.empty_domain&&perf_suspends==2); init();boot_error=-ETIMEDOUT;avd_reset_queue(&d,-ETIMEDOUT); - assert(d.faulted&&resets==1&&boots==1&&attaches==2&&detaches==1&&d.pm.dma_parked); + assert(d.faulted&&resets==1&&boots==1&&attaches==2&&detaches==1&&d.pm.dma_parked&&perf_suspends==2); assert(attached==d.empty_domain&&!d.pm.irq_enabled); init();avd_reset_queue(&d,-EIO);avd_reset_queue(&d,-EIO);avd_reset_queue(&d,-EIO); - assert(resets==2&&boots==2&&attaches==3&&detaches==2&&!d.faulted&&d.rest_until); + assert(resets==2&&boots==2&&attaches==3&&detaches==2&&!d.faulted&&d.rest_until&&perf_suspends==3); assert(d.pm.dma_parked&&attached==d.empty_domain&&!d.pm.irq_enabled); unsigned int old_boots=boots,old_resets=resets; assert(!avd_pm_power_off(&d)&&!avd_pm_power_on(&d)); - assert(boots==old_boots&&resets==old_resets&&!resubmits&&!d.pm.irq_enabled); + assert(boots==old_boots&&resets==old_resets&&!resubmits&&!d.pm.irq_enabled&&perf_suspends==4); /* The expiry path (dispatch-test) calls recover under a PM reference. */ - jiffies=d.rest_until;assert(!avd_pm_recover(&d));assert(resets==3&&!d.pm.dma_parked); - init();attach_error=-EIO;assert(avd_pm_recover(&d)==-EIO);assert(!resets&&!boots&&!detaches); - init();d.pm.dart_active=false;assert(avd_pm_park(&d)==-EHOSTDOWN);assert(!shutdowns&&!resets&&!attaches); - puts("PASS: production recovery/PM: park before reset, failed reset/boot stays blocked, budget rests, parked resume never boots, expiry recovery"); + jiffies=d.rest_until;assert(!avd_pm_recover(&d));assert(resets==3&&!d.pm.dma_parked&&perf_suspends==5); + init();attach_error=-EIO;assert(avd_pm_recover(&d)==-EIO);assert(!resets&&!boots&&!detaches&&perf_suspends==1); + init();d.pm.dart_active=false;assert(avd_pm_park(&d)==-EHOSTDOWN);assert(!shutdowns&&!resets&&!attaches&&perf_suspends==1); + puts("PASS: production recovery/PM: park before reset, no-reset variant stays parked, failed reset/boot stays blocked, budget rests, parked resume never boots, expiry recovery"); } ''' diff --git a/drivers/media/platform/apple/avd/tests/vp9-test.py b/drivers/media/platform/apple/avd/tests/vp9-test.py index 7c60bbb1688439..f5c934261d27c4 100644 --- a/drivers/media/platform/apple/avd/tests/vp9-test.py +++ b/drivers/media/platform/apple/avd/tests/vp9-test.py @@ -32,7 +32,7 @@ 'struct vb2_buffer { struct { size_t length; } planes[1]; dma_addr_t dma; void *cpu; size_t payload; u64 timestamp; };') pre = pre.replace('struct avd_comp comp; unsigned int bank;', 'struct avd_comp comp; unsigned int bank; struct { unsigned int width,height,bit_depth; } vp9;') pre = pre.replace('struct vb2_v4l2_buffer *dst; } bufs;', 'struct vb2_v4l2_buffer *src,*dst; } bufs;') -pre = pre.replace('unsigned int fifo_idx, pp_total;', 'unsigned int fifo_idx, pp_total, max_frames; int ctrl_hdl;') +pre = pre.replace('unsigned int fifo_idx, pp_total;', 'unsigned int fifo_idx, pp_total, max_frames; int ctrl_hdl; bool scratch_sized; enum avd_image_fmt scratch_fmt;') pre = pre.replace('static int avd_buf_alloc(struct avd_dev *d, struct avd_buf *b, size_t n)', '#ifdef AVD_TEST_VP_READY\nstatic struct avd_ctx *allocating_ctx;\nstatic int fail_alloc_after;\nstatic bool avd_vp9_ready(struct avd_ctx *);\n#endif\nstatic int avd_buf_alloc(struct avd_dev *d, struct avd_buf *b, size_t n)') pre = pre.replace('{ (void)d; free(b->cpu); b->cpu = calloc(1,n);', @@ -59,9 +59,10 @@ enum vb2_buffer_state { STATE_DUMMY }; #define dev_err(d,...) ((void)(d)) #define kzalloc(n,f) calloc(1,n) -#define kfree free +#define kfree(p) free((void *)(p)) static bool vp_feature = true; static bool avd_qfw_has_vp_done(const struct avd_dev *d) { return d->queued && vp_feature; } +static bool avd_backend_is_open(const struct avd_dev *d) { return !d->queued; } static void *vb2_plane_vaddr(struct vb2_buffer *b,int p) { (void)p;return b->cpu; } static size_t vb2_get_plane_payload(struct vb2_buffer *b,int p) { (void)p;return b->payload; } static struct vb2_v4l2_buffer *current_src,*current_dst; @@ -71,6 +72,32 @@ static struct v4l2_ctrl_vp9_frame params; static struct v4l2_ctrl_vp9_compressed_hdr updates; static struct v4l2_ctrl frame_ctrl,update_ctrl; +static struct v4l2_ctrl *locked_ctrl; + +static void v4l2_ctrl_lock(struct v4l2_ctrl *ctrl) +{ + assert(!locked_ctrl); + locked_ctrl = ctrl; +} + +static void v4l2_ctrl_unlock(struct v4l2_ctrl *ctrl) +{ + assert(locked_ctrl == ctrl); + locked_ctrl = NULL; +} + +static void *kmemdup(const void *source, size_t size, int flags) +{ + void *copy; + + (void)flags; + assert(locked_ctrl); + copy = malloc(size); + if (copy) + memcpy(copy, source, size); + return copy; +} + static struct v4l2_ctrl *v4l2_ctrl_find(void *h,u32 id) { (void)h;frame_ctrl.p_cur.p=¶ms;update_ctrl.p_cur.p=&updates; return id==V4L2_CID_STATELESS_VP9_FRAME?&frame_ctrl:&update_ctrl; @@ -80,10 +107,15 @@ run->coded_in=current_src->vb2_buf.dma;run->comp_out=current_dst->vb2_buf.dma; run->y_out=run->comp_out+0x100000;run->uv_out=run->comp_out+0x300000; } +/* avd-fmt-test.c independently exercises the run image format check. */ +static int avd_check_run_image_fmt(struct avd_ctx *ctx, int fmt) +{ + (void)ctx;(void)fmt;return 0; +} static void avd_run_postamble(struct avd_ctx *ctx,struct avd_run *run) { (void)ctx;(void)run; } static int avd_init_job(struct avd_ctx *ctx,int codec,size_t segments) { free(ctx->job.segments);ctx->job.codec=codec;ctx->job.num=0; - ctx->job.segments=calloc(segments,sizeof(*ctx->job.segments));return ctx->job.segments?0:-ENOMEM; + ctx->job.segments=calloc(segments,sizeof(*ctx->job.segments));ctx->job.overflow=false;ctx->job.max=ctx->job.segments?segments:0;return ctx->job.segments?0:-ENOMEM; } static int avd_submit_job(struct avd_ctx *ctx); ''' @@ -183,8 +215,7 @@ def without_includes(s): assert(!memcmp(&adapted,&p->bank[1].probability_tables,sizeof(adapted))); write_program(argv[1],"vp9-adaptive-1",&frame); assert(!avd_vp9_ready(&ctx)); - struct avd_vp9_run attempt; - current_dst=&dst[2].base.vb;assert(avd_vp9_run_preamble(&ctx,&attempt)==-EBUSY);assert(!dst[2].bank); + current_dst=&dst[2].base.vb;assert(avd_vp9_run(&ctx)==-EBUSY);assert(!dst[2].bank); /* PP(0) retires while b points to bank 1: only bank 0 may be released. */ avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE); assert(!p->bank[0].busy&&p->bank[1].busy&&!dst[0].bank); @@ -208,12 +239,96 @@ def without_includes(s): assert(p->bank[0].busy&&p->bank[1].busy); avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE);avd_vp9_done(&ctx,&src,&dst[1].base.vb,VB2_BUF_STATE_DONE); } + /* After a frame size change the temporal-MV input is not the prior bank. */ + params=(struct v4l2_ctrl_vp9_frame){.flags=V4L2_VP9_FRAME_FLAG_SHOW_FRAME, + .frame_width_minus_1=1919,.frame_height_minus_1=1087,.bit_depth=8}; + current_dst=&dst[0].base.vb;frame.idx=0;assert(!avd_vp9_run(&ctx)); + struct avd_vp9_bank *shown=p->b; + params.frame_width_minus_1=1899;params.frame_height_minus_1=1079; + current_dst=&dst[1].base.vb;frame.idx=1;assert(!avd_vp9_run(&ctx)); + assert(p->b!=shown&&p->last.width==1900&&p->last.height==1080); + {bool prior_color=false;u32 *words=program.cpu; + for(size_t j=0;jbufs.color.addr>>8))prior_color=true; + assert(!prior_color);} + avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE);avd_vp9_done(&ctx,&src,&dst[1].base.vb,VB2_BUF_STATE_DONE); + /* A 1440x1088 reference of a 1920x1088 frame: vertical scale high, horizontal low. */ + params.frame_width_minus_1=1919;params.frame_height_minus_1=1087;reference.vp9.width=1440; + current_dst=&dst[0].base.vb;frame.idx=0;assert(!avd_vp9_run(&ctx)); + {bool scale=false;u32 *words=program.cpu; + for(size_t j=0;jnbanks;i++)memset(p->bank[i].bufs.seg.cpu,0xa5,p->bank[i].bufs.seg.size); + /* Frame A writes a map, so no reset is owed from the earlier size changes. */ + params.seg.flags=V4L2_VP9_SEGMENTATION_FLAG_ENABLED|V4L2_VP9_SEGMENTATION_FLAG_UPDATE_MAP; + current_dst=&dst[0].base.vb;frame.idx=0;assert(!avd_vp9_run(&ctx)); + assert(p->b==&p->bank[0]&&((u8 *)p->bank[0].bufs.seg.cpu)[0]==0xa5&&!p->seg_reset); + /* Bank 0 stays busy; the next frame is smaller and has no segmentation. */ + params.seg.flags=0;params.frame_width_minus_1=1899;params.frame_height_minus_1=1079; + current_dst=&dst[1].base.vb;frame.idx=1;assert(!avd_vp9_run(&ctx)); + assert(p->b==&p->bank[1]&&p->seg_reset&&p->bank[0].seg_clear&&!p->bank[1].seg_clear); + {u8 *seg=p->bank[1].bufs.seg.cpu;for(size_t j=0;jbank[1].bufs.seg.size;j++)assert(!seg[j]);} + assert(((u8 *)p->bank[0].bufs.seg.cpu)[0]==0xa5); + avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE); + avd_vp9_done(&ctx,&src,&dst[1].base.vb,VB2_BUF_STATE_DONE); + /* Same size again, segmentation on without a map update: the reset is still owed, and it stays + * owed after that frame, as the decoder would read the old map again. */ + params.seg.flags=V4L2_VP9_SEGMENTATION_FLAG_ENABLED;current_dst=&dst[0].base.vb; + {struct avd_vp9_run r={.decode_params=¶ms};r.base.bufs.dst=current_dst; + assert(make_flags1(&ctx,&r)&VP9_SEG_RESET(1));} + frame.idx=0;assert(!avd_vp9_run(&ctx)); + assert(p->b==&p->bank[0]&&!p->bank[0].seg_clear&&p->seg_reset); + {u8 *seg=p->bank[0].bufs.seg.cpu;for(size_t j=0;jbank[0].bufs.seg.size;j++)assert(!seg[j]);} + avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE); + /* The next frame updates the map: it still gets the reset, and after it the reset is gone. */ + params.seg.flags=V4L2_VP9_SEGMENTATION_FLAG_ENABLED|V4L2_VP9_SEGMENTATION_FLAG_UPDATE_MAP; + current_dst=&dst[1].base.vb; + {struct avd_vp9_run r={.decode_params=¶ms};r.base.bufs.dst=current_dst; + assert(make_flags1(&ctx,&r)&VP9_SEG_RESET(1));} + frame.idx=1;assert(!avd_vp9_run(&ctx));assert(!p->seg_reset); + {struct avd_vp9_run r={.decode_params=¶ms};r.base.bufs.dst=current_dst; + assert(!(make_flags1(&ctx,&r)&VP9_SEG_RESET(1)));} + avd_vp9_done(&ctx,&src,&dst[1].base.vb,VB2_BUF_STATE_DONE);params.seg.flags=0; + /* The firmware transport still needs the format's size: smaller and larger frames are refused. */ + params.frame_width_minus_1=959;params.frame_height_minus_1=539; + current_dst=&dst[0].base.vb;frame.idx=0;assert(avd_vp9_run(&ctx)==-EINVAL); + params.frame_width_minus_1=1983;params.frame_height_minus_1=1087; + current_dst=&dst[1].base.vb;frame.idx=1;assert(avd_vp9_run(&ctx)==-EINVAL); + /* The firmware transport keeps the 64-pixel floor. */ + ctx.decoded_fmt.fmt.pix_mp.width=64;ctx.decoded_fmt.fmt.pix_mp.height=64; + ctx.decoded_fmt.fmt.pix_mp.plane_fmt[0].bytesperline=64; + params=(struct v4l2_ctrl_vp9_frame){.flags=V4L2_VP9_FRAME_FLAG_KEY_FRAME|V4L2_VP9_FRAME_FLAG_SHOW_FRAME, + .frame_width_minus_1=31,.frame_height_minus_1=15,.bit_depth=8}; + current_dst=&dst[0].base.vb;frame.idx=0;assert(avd_vp9_run(&ctx)==-EINVAL); avd_vp9_stop(&ctx);assert(!avd_vp9_ready(&ctx)); /* Old firmware and the legacy transport allocate only one bank. */ for(unsigned int mode=0;mode<2;mode++) { dev.queued=mode;vp_feature=false;assert(!avd_vp9_start(&ctx));p=ctx.priv; assert(p->nbanks==1&&ctx.max_frames==1);avd_vp9_stop(&ctx); } + /* On the legacy transport a frame below 64x64 decodes into a 64x64 CAPTURE buffer. */ + dev.queued=false;vp_feature=false;assert(!avd_vp9_start(&ctx));p=ctx.priv; + current_dst=&dst[0].base.vb;frame.idx=0;assert(!avd_vp9_run(&ctx)); + avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE); + /* A frame larger than the CAPTURE format is still refused. */ + params.frame_width_minus_1=1919;params.frame_height_minus_1=1087; + assert(avd_vp9_run(&ctx)==-EINVAL); + avd_vp9_stop(&ctx); + /* On the legacy transport a frame smaller than the capture format runs in it, a larger one is refused. */ + ctx.decoded_fmt.fmt.pix_mp.width=1920;ctx.decoded_fmt.fmt.pix_mp.height=1088; + ctx.decoded_fmt.fmt.pix_mp.plane_fmt[0].bytesperline=1920; + dev.queued=false;vp_feature=false;assert(!avd_vp9_start(&ctx));p=ctx.priv; + params=(struct v4l2_ctrl_vp9_frame){.flags=V4L2_VP9_FRAME_FLAG_KEY_FRAME|V4L2_VP9_FRAME_FLAG_SHOW_FRAME, + .frame_width_minus_1=959,.frame_height_minus_1=539,.bit_depth=8}; + current_dst=&dst[0].base.vb;frame.idx=0;assert(!avd_vp9_run(&ctx)); + assert(dst[0].vp9.width==960&&dst[0].vp9.height==540); + avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE); + params.frame_width_minus_1=1983;params.frame_height_minus_1=1087; + current_dst=&dst[0].base.vb;frame.idx=0;assert(avd_vp9_run(&ctx)==-EINVAL); + avd_vp9_stop(&ctx); dev.queued=true;vp_feature=true;fail_alloc_after=13;allocating_ctx=&ctx; assert(avd_vp9_start(&ctx)==-ENOMEM);allocating_ctx=NULL; assert(!ctx.priv&&!avd_vp9_ready(&ctx)&&ctx.max_frames==1); diff --git a/drivers/media/platform/apple/ave/Kconfig b/drivers/media/platform/apple/ave/Kconfig index 0924ce46210276..e71449b2d9564b 100644 --- a/drivers/media/platform/apple/ave/Kconfig +++ b/drivers/media/platform/apple/ave/Kconfig @@ -35,7 +35,8 @@ config VIDEO_APPLE_AVE_KUNIT_TEST config VIDEO_APPLE_AVE_CMD_KUNIT_TEST bool "KUnit tests for Apple AVE firmware ABIs" if !KUNIT_ALL_TESTS - depends on KUNIT && VIDEO_APPLE_AVE=y + depends on VIDEO_APPLE_AVE && KUNIT + depends on KUNIT=y || VIDEO_APPLE_AVE=m default KUNIT_ALL_TESTS help Compare AVC/HEVC 9003 Start and Process images byte for byte with @@ -44,3 +45,17 @@ config VIDEO_APPLE_AVE_CMD_KUNIT_TEST entropy interleave, alignment refusal, seven-channel discovery and encoding refusal. These tests run without firmware or encoder hardware. + +config VIDEO_APPLE_AVE_IPC_KUNIT_TEST + bool "KUnit tests for Apple AVE firmware and userspace input checks" if !KUNIT_ALL_TESTS + depends on KUNIT=y && VIDEO_APPLE_AVE=y + default KUNIT_ALL_TESTS + help + Feed malformed firmware input to the AVE IPC layer: hello words, + channel tables with overlapping or out-of-range rings, ring index + wrap, full and empty rings, command acks and messages outside the + shared window, log lines and shared-memory requests. Also test that + the 6070 Start and Process builders refuse out-of-range session + counts, unaligned buffers and short codec state before writing. + The tests use kernel memory for the shared window and the mailbox + and run without firmware or encoder hardware. diff --git a/drivers/media/platform/apple/ave/Makefile b/drivers/media/platform/apple/ave/Makefile index 03d3b1bba4978b..c8468b07606e37 100644 --- a/drivers/media/platform/apple/ave/Makefile +++ b/drivers/media/platform/apple/ave/Makefile @@ -4,4 +4,5 @@ obj-$(CONFIG_VIDEO_APPLE_AVE) += apple-ave.o obj-$(CONFIG_VIDEO_APPLE_AVE) += apple-ave-dma.o apple-ave-y := ave-drv.o ave-fw.o ave-ipc.o ave-cmd.o ave-writer.o ave-abi.o ave-layout.o ave-image.o ave-sess.o ave-v4l2.o ave-vb2.o ave-mctf.o ave-mctf-v4l2.o ave-cmp420.o obj-$(CONFIG_VIDEO_APPLE_AVE_KUNIT_TEST) += ave-sizes-test.o ave-recovery-test.o -obj-$(CONFIG_VIDEO_APPLE_AVE_CMD_KUNIT_TEST) += ave-abi-test.o ave-mctf-test.o ave-cmp420-test.o +apple-ave-$(CONFIG_VIDEO_APPLE_AVE_CMD_KUNIT_TEST) += ave-abi-test.o ave-mctf-test.o ave-cmp420-test.o +apple-ave-$(CONFIG_VIDEO_APPLE_AVE_IPC_KUNIT_TEST) += ave-writer-test.o diff --git a/drivers/media/platform/apple/ave/ave-abi-test.c b/drivers/media/platform/apple/ave/ave-abi-test.c index 4b5f60f4d11b81..1698e8a97ec94e 100644 --- a/drivers/media/platform/apple/ave/ave-abi-test.c +++ b/drivers/media/platform/apple/ave/ave-abi-test.c @@ -2,7 +2,6 @@ /* Byte equality against the pre-ABI-refactor 9003 command builders. */ #include #include -#include #include #include #include @@ -269,6 +268,64 @@ static void ave_9003_hevc_main10(struct kunit *test) } } +/* + * HEVC Main 10 on the counted layouts: 26A428, which T8142 encodes with, and + * 26B123 (the M3/M4 27.2 build), which shares its Start. The words that change + * with bit depth take the 9003 capture's Main 10 values (the host tests in + * tests/test.c check the same words). + */ +static void ave_26a428_hevc_main10(struct kunit *test) +{ + static const struct ave_fw_layout *const layouts[] = { + &ave_layout_26a428, &ave_layout_26b123, + }; + + for (unsigned int l = 0; l < ARRAY_SIZE(layouts); l++) { + struct ave_dev *ave = kunit_kzalloc(test, sizeof(*ave), GFP_KERNEL); + struct ave_ctx *ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + struct ave_session *sess = kunit_kzalloc(test, sizeof(*sess), GFP_KERNEL); + u8 *main8, *main10; + size_t len; + + KUNIT_ASSERT_NOT_NULL(test, ave); + KUNIT_ASSERT_NOT_NULL(test, ctx); + KUNIT_ASSERT_NOT_NULL(test, sess); + ave->layout = layouts[l]; + ctx->ave = ave; + ctx->sess = sess; + len = ave->layout->bytes[AVE_CODEC_HEVC - 1][AVE_IMAGE_START]; + main8 = kunit_kzalloc(test, len, GFP_KERNEL); + main10 = kunit_kzalloc(test, len, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, main8); + KUNIT_ASSERT_NOT_NULL(test, main10); + + ave_test_session(sess, AVE_CODEC_HEVC, 1920, 1080, true); + KUNIT_ASSERT_EQ(test, ave_build_start(ctx, main8, len), 0); + ave_test_session(sess, AVE_CODEC_HEVC, 1920, 1080, true); + sess->p.min_qp = -12; + sess->p.profile = 2; + sess->p.bit_depth = 10; + KUNIT_ASSERT_EQ(test, ave_build_start(ctx, main10, len), 0); + + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(main10 + 0x35e8), 0x10040, + "layout %u", l); + KUNIT_EXPECT_NE_MSG(test, get_unaligned_le32(main8 + 0x35e8), 0x10040, + "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(main8 + 0x37c0), 8, "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(main10 + 0x37c0), 10, "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, (s32)get_unaligned_le32(main10 + 0x3678), -12, + "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, (s32)get_unaligned_le32(main10 + 0x3740), -12, + "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(main10 + 0x3a60), 0x01000101, + "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(main10 + 0x6530), 0x01000000, + "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(main10 + 0x66dc), 2, "layout %u", l); + KUNIT_EXPECT_NE_MSG(test, get_unaligned_le32(main8 + 0x66dc), 2, "layout %u", l); + } +} + /* One 1080p HEVC Start or first Process image, with speed mode @speed. */ static void ave_speed_image(struct kunit *test, struct ave_ctx *ctx, enum ave_image image, bool bframes, bool main10, @@ -1473,6 +1530,8 @@ static void ave_26b123_layout(struct kunit *test) { const struct ave_fw_layout *a = &ave_layout_26a428; const struct ave_fw_layout *b = ave_layout_for_crc(0x99fc929a); + struct ave_start_layout *start = kunit_kzalloc(test, sizeof(a->start), GFP_KERNEL); + struct ave_proc_layout *process = kunit_kzalloc(test, sizeof(a->process), GFP_KERNEL); KUNIT_ASSERT_PTR_EQ(test, b, &ave_layout_26b123); KUNIT_EXPECT_TRUE(test, b->encode_ready); @@ -1486,33 +1545,147 @@ static void ave_26b123_layout(struct kunit *test) } KUNIT_EXPECT_EQ(test, b->bytes[0][AVE_IMAGE_PROCESS], 0x6e08); KUNIT_EXPECT_EQ(test, b->bytes[1][AVE_IMAGE_PROCESS], 0x78c8); - KUNIT_EXPECT_EQ(test, memcmp(b->start, a->start, sizeof(a->start)), 0); - KUNIT_EXPECT_EQ(test, memcmp(b->process, a->process, sizeof(a->process)), 0); + /* Apart from the two words only the M5 26A428 sessions were run with. */ + KUNIT_ASSERT_NOT_NULL(test, start); + KUNIT_ASSERT_NOT_NULL(test, process); + memcpy(start, a->start, sizeof(a->start)); + memcpy(process, a->process, sizeof(a->process)); + for (unsigned int c = 0; c < 2; c++) { + KUNIT_EXPECT_EQ(test, b->start[c].fps_int_copy, 0U); + start[c].fps_int_copy = 0; + } + KUNIT_EXPECT_EQ(test, b->process[1].low_delay, 0U); + process[1].low_delay = 0; + KUNIT_EXPECT_EQ(test, memcmp(b->start, start, sizeof(a->start)), 0); + KUNIT_EXPECT_EQ(test, memcmp(b->process, process, sizeof(a->process)), 0); KUNIT_EXPECT_EQ(test, memcmp(b->result, a->result, sizeof(a->result)), 0); KUNIT_EXPECT_EQ(test, b->hdr_bytes, a->hdr_bytes); KUNIT_EXPECT_EQ(test, b->max_slots, a->max_slots); KUNIT_EXPECT_EQ(test, b->process_subtype, a->process_subtype); - /* Both counted; only the 27.2 build runs sessions without B-frames and at any rate. */ + /* Both counted, and both run sessions without B-frames and at any rate. */ KUNIT_EXPECT_TRUE(test, a->counted && b->counted); - KUNIT_EXPECT_FALSE(test, a->any_gop); + KUNIT_EXPECT_TRUE(test, a->any_gop); KUNIT_EXPECT_TRUE(test, b->any_gop); KUNIT_EXPECT_PTR_EQ(test, ave_layout_for_crc(AVE_FW_TEXT_CRC_T8122_26B123), b); } +/* + * The M2 with the 27.2 stub: the reserved segment sizes select the 27.2 + * build's own start (device 12, handshake type 12) and the 26B123 layout; + * the 13.5 build keeps the M2's 6070 start. Other sizes fall back to + * ave_t8112, whose size check in ave_fw_probe() then refuses them. + */ +static void ave_t8112_26b123_build(struct kunit *test) +{ + const struct ave_variant *n = ave_t8112.next_build; + + KUNIT_ASSERT_NOT_NULL(test, n); + KUNIT_EXPECT_PTR_EQ(test, ave_fw_select_build(&ave_t8112, 0xd0000, 0x128000), + &ave_t8112); + KUNIT_EXPECT_PTR_EQ(test, ave_fw_select_build(&ave_t8112, 0x11c000, 0x128000), n); + KUNIT_EXPECT_PTR_EQ(test, ave_fw_select_build(&ave_t8112, 0x11c000, 0x12c000), + &ave_t8112); + KUNIT_EXPECT_PTR_EQ(test, ave_fw_select_build(&ave_t8112, 0x134000, 0x128000), + &ave_t8112); + /* The near misses are refused: no variant of the chain pins them. */ + KUNIT_EXPECT_FALSE(test, ave_fw_sizes_match(&ave_t8112, 0x11c000, 0x12c000)); + KUNIT_EXPECT_FALSE(test, ave_fw_sizes_match(&ave_t8112, 0x134000, 0x128000)); + KUNIT_EXPECT_FALSE(test, ave_fw_sizes_match(n, 0x11c000, 0x12c000)); + KUNIT_EXPECT_TRUE(test, ave_fw_sizes_match(&ave_t8112, 0xd0000, 0x128000)); + KUNIT_EXPECT_TRUE(test, ave_fw_sizes_match(n, 0x11c000, 0x128000)); + KUNIT_EXPECT_NULL(test, n->next_build); + KUNIT_EXPECT_TRUE(test, n->boot_qualified); + KUNIT_EXPECT_PTR_EQ(test, n->regs, ave_t8112.regs); + KUNIT_EXPECT_EQ(test, n->boot_device_id, 12U); + KUNIT_EXPECT_EQ(test, n->device_type, 12U); + KUNIT_EXPECT_EQ(test, n->boot_arg_value, 0x10000U); + KUNIT_EXPECT_EQ(test, n->timebase_multiplier, 1U); + KUNIT_EXPECT_EQ(test, n->mbox_idle, 0x38U); + KUNIT_EXPECT_TRUE(test, n->restore_data_first); + KUNIT_EXPECT_EQ(test, n->text_link_cell, 0U); + /* The Mac mini's loader sets the word at TEXT 0x4224 on every boot. */ + KUNIT_ASSERT_EQ(test, n->build_count, 1U); + KUNIT_EXPECT_EQ(test, n->builds[0].text_boot_word, 0x4224U); + /* The 27.2 builds' reference buffer sizing, as on the M3 and M4. */ + KUNIT_EXPECT_EQ(test, n->lfs_ref_scale, 2U); + KUNIT_EXPECT_EQ(test, ave_t8112.lfs_ref_scale, 1U); + KUNIT_EXPECT_EQ(test, n->extra0_size, 0U); + KUNIT_EXPECT_EQ(test, n->vcbar_flags, (u64)AVE_COPROC_VCBAR_VALID); + KUNIT_EXPECT_EQ(test, ave_fw_vcbar(n, 0x800000000ULL), 0x800000001ULL); + KUNIT_EXPECT_EQ(test, n->builds[0].text_crc, AVE_FW_TEXT_CRC_T8112_26B123); + { + const u32 off = n->builds[0].text_boot_word, size = off + 0x40; + u8 *text = kunit_kzalloc(test, size, GFP_KERNEL); + u32 zeroed, a, b; + + KUNIT_ASSERT_NOT_NULL(test, text); + zeroed = crc32_le(~0U, text, size) ^ ~0U; + put_unaligned_le32(0x003d0000, text + off); + KUNIT_EXPECT_EQ(test, ave_fw_text_boot_crc(text, size, off, &a), 0); + put_unaligned_le32(0x00a10000, text + off); + KUNIT_EXPECT_EQ(test, ave_fw_text_boot_crc(text, size, off, &b), 0); + /* Any per-boot value gives the zeroed-word CRC. */ + KUNIT_EXPECT_EQ(test, a, zeroed); + KUNIT_EXPECT_EQ(test, b, zeroed); + } + KUNIT_EXPECT_PTR_EQ(test, ave_layout_for_crc(n->builds[0].text_crc), &ave_layout_26b123); + KUNIT_EXPECT_PTR_EQ(test, ave_layout_for_crc(ave_t8112.text_crc), + &ave_layout_6070_11_1); +} + +/* + * HEVC B flag with a PPS whose num_extra_slice_header_bits is 2. The PPS + * comes with the IDR access unit; the B slice after it has two extra bits + * before slice_type, and reads as an I slice if they are not skipped. + */ +static void ave_hevc_bframe_extra_bits(struct kunit *test) +{ + static const u8 idr_au[] = { + 0, 0, 0, 1, 0x44, 0x01, 0xc5, 0x80, /* PPS: ids 0/0, 2 extra bits */ + 0, 0, 1, 0x26, 0x01, 0xa3, 0x80, /* IDR_W_RADL slice, I */ + }; + static const u8 b_au[] = { + 0, 0, 0, 1, 0x02, 0x01, 0xdc, 0x80, /* TRAIL_R slice, extra bits 01, B */ + }; + u8 bits = 0; + + KUNIT_EXPECT_FALSE(test, ave_au_bframe(idr_au, sizeof(idr_au), true, true, &bits)); + KUNIT_EXPECT_EQ(test, bits, 2); + KUNIT_EXPECT_TRUE(test, ave_au_bframe(b_au, sizeof(b_au), true, false, &bits)); + /* Without the PPS's bits the same slice reads as I. */ + bits = 0; + KUNIT_EXPECT_FALSE(test, ave_au_bframe(b_au, sizeof(b_au), true, false, &bits)); +} + static void ave_t6041_text_boot_word(struct kunit *test) { - const u32 off = ave_t6041.text_boot_word, size = off + 0x100; + const struct ave_fw_build *m4 = ave_t6041.builds; + const u32 off = m4[0].text_boot_word, size = off + 0x100; u8 *text = kunit_kzalloc(test, size, GFP_KERNEL); u32 image, a, b; KUNIT_ASSERT_NOT_NULL(test, text); KUNIT_EXPECT_EQ(test, off, 0x4224U); - KUNIT_EXPECT_EQ(test, ave_t6041.fw_data_size_alt, 0x130000U); + /* The M4 Pro and M4 Max builds: the same word, the Max with a larger DATA. */ + KUNIT_ASSERT_EQ(test, ave_t6041.build_count, 2U); + KUNIT_EXPECT_EQ(test, m4[1].data_size, 0x130000U); + KUNIT_EXPECT_EQ(test, m4[1].text_boot_word, off); KUNIT_EXPECT_EQ(test, ave_t6041.text_link_cell, 0U); /* The M4 27.2 build: the same word, set per boot by some loaders. */ - KUNIT_EXPECT_EQ(test, ave_t8132.text_boot_word, off); - KUNIT_EXPECT_EQ(test, ave_t8132.text_crc, AVE_FW_TEXT_CRC_T8132_26B123); + KUNIT_ASSERT_EQ(test, ave_t8132.build_count, 1U); + KUNIT_EXPECT_EQ(test, ave_t8132.builds[0].text_boot_word, off); + KUNIT_EXPECT_EQ(test, ave_t8132.builds[0].text_crc, AVE_FW_TEXT_CRC_T8132_26B123); KUNIT_EXPECT_EQ(test, ave_t8132.text_link_cell, 0U); + /* + * The M5 Pro/Max 26A428 build: the same word, which differs per boot on + * the J775D. The 26C5035 build has none set: its CRC matches as it is. + */ + KUNIT_ASSERT_EQ(test, ave_t6050.build_count, 2U); + KUNIT_EXPECT_EQ(test, ave_t6050.builds[0].text_boot_word, off); + KUNIT_EXPECT_EQ(test, ave_t6050.builds[0].text_crc, AVE_FW_TEXT_CRC_T6050_26A428); + KUNIT_EXPECT_EQ(test, ave_t6050.builds[1].text_boot_word, 0U); + KUNIT_EXPECT_EQ(test, ave_t6050.builds[1].text_crc, AVE_FW_TEXT_CRC_T6050_26C5035); + KUNIT_EXPECT_EQ(test, ave_t6050.text_link_cell, 0U); for (u32 i = 0; i < size; i++) text[i] = i * 7 + 3; memset(text + off, 0, 4); @@ -1558,6 +1731,7 @@ static void ave_m3_probe_only(struct kunit *test) static struct kunit_case ave_abi_cases[] = { KUNIT_CASE(ave_t6041_text_boot_word), KUNIT_CASE(ave_9003_byte_equality), KUNIT_CASE(ave_9003_hevc_main10), + KUNIT_CASE(ave_26a428_hevc_main10), KUNIT_CASE(ave_9003_speed), KUNIT_CASE(ave_cq_table), KUNIT_CASE(ave_6070_images), KUNIT_CASE(ave_6070_replies), KUNIT_CASE(ave_6070_frame_result), @@ -1572,6 +1746,8 @@ static struct kunit_case ave_abi_cases[] = { KUNIT_CASE(ave_6070_smalloc), KUNIT_CASE(ave_m3_probe_only), KUNIT_CASE(ave_26b123_layout), + KUNIT_CASE(ave_t8112_26b123_build), + KUNIT_CASE(ave_hevc_bframe_extra_bits), {} }; @@ -1580,5 +1756,3 @@ static struct kunit_suite ave_abi_suite = { .test_cases = ave_abi_cases, }; kunit_test_suite(ave_abi_suite); - -MODULE_LICENSE("GPL"); diff --git a/drivers/media/platform/apple/ave/ave-cmp420-test.c b/drivers/media/platform/apple/ave/ave-cmp420-test.c index 1fb59e6a6c8158..e350f62c2f2164 100644 --- a/drivers/media/platform/apple/ave/ave-cmp420-test.c +++ b/drivers/media/platform/apple/ave/ave-cmp420-test.c @@ -9,7 +9,6 @@ * Copyright The Aurora Silicon Contributors */ #include -#include #include #include @@ -462,6 +461,3 @@ static struct kunit_suite ave_cmp420_suite = { .test_cases = ave_cmp420_cases, }; kunit_test_suite(ave_cmp420_suite); - -MODULE_DESCRIPTION("Apple AVE compressed 4:2:0 surface tests"); -MODULE_LICENSE("GPL"); diff --git a/drivers/media/platform/apple/ave/ave-drv.c b/drivers/media/platform/apple/ave/ave-drv.c index 8cc10edd82900c..bd3568d34deaeb 100644 --- a/drivers/media/platform/apple/ave/ave-drv.c +++ b/drivers/media/platform/apple/ave/ave-drv.c @@ -68,6 +68,37 @@ const struct ave_variant ave_t6000 = { .boot_qualified = true, }; +/* + * The M2 (T8112) with the macOS 27.2 (26B123) stub, as on the Mac mini + * (J473): the bootloader preloads TEXT 0x11c000 and DATA 0x128000. Like the + * M4's 27.2 loaders, it sets the word at TEXT 0x4224 on every boot; with that + * word zeroed the TEXT CRC is 077a3444. It is the M2 encoder's build of the + * firmware version the M3 runs on 27.2, and it starts the same way: the boot + * configuration handshake as device 12 with handshake type 12, the 26B123 + * command layout, codec clocks ungated by clearing the mailbox idle word, + * the bootloader's code base (marked valid) left as it is, and DATA restored + * from the boot snapshot before every start. + */ +static const struct ave_fw_build ave_t8112_26b123_builds[] = { + { "26B123", 0x11c000, 0x128000, AVE_FW_TEXT_CRC_T8112_26B123, 0x4224 }, +}; + +static const struct ave_variant ave_t8112_26b123 = { + .regs = &ave_coproc_6070, + .builds = ave_t8112_26b123_builds, + .build_count = ARRAY_SIZE(ave_t8112_26b123_builds), + .boot_device_id = 12, + .boot_arg_value = AVE_COPROC_BOOT_ARG_VALUE, + .timebase_multiplier = 1, + .vcbar_mask = GENMASK_ULL(41, 11), + .vcbar_flags = AVE_COPROC_VCBAR_VALID, + .device_type = 12, + .lfs_ref_scale = 2, + .mbox_idle = 0x38, + .restore_data_first = true, + .boot_qualified = true, +}; + const struct ave_variant ave_t8112 = { .regs = &ave_coproc_6070, .fw_text_size = 0xd0000, @@ -84,6 +115,7 @@ const struct ave_variant ave_t8112 = { .extra0_size = 0x4000, .boot_qualified = true, + .next_build = &ave_t8112_26b123, }; /* @@ -93,12 +125,16 @@ const struct ave_variant ave_t8112 = { * with soc-id t6040, the same way; iBoot 25G83 preloads it with a 0x130000 * DATA and sets a word at TEXT 0x4224 differently on every boot. */ +static const struct ave_fw_build ave_t6041_builds[] = { + { "25G83", 0x14c000, 0x12c000, 0, 0x4224 }, + /* The M4 Max's first encoder */ + { "25G83", 0x14c000, 0x130000, 0, 0x4224 }, +}; + const struct ave_variant ave_t6041 = { .regs = &ave_coproc_v40, - .fw_text_size = 0x14c000, - .fw_data_size = 0x12c000, - .fw_data_size_alt = 0x130000, - .text_boot_word = 0x4224, + .builds = ave_t6041_builds, + .build_count = ARRAY_SIZE(ave_t6041_builds), .boot_device_id = 27, .boot_arg_value = AVE_COPROC_BOOT_ARG_VALUE, .timebase_multiplier = 1, @@ -144,10 +180,14 @@ static const struct ave_variant ave_t8122 = { * unknown CRC is retried with it zeroed. The coprocessor and its start are * the M4 Pro's; this build boots as device 23 and takes handshake type 23. */ +static const struct ave_fw_build ave_t8132_builds[] = { + { "26B123", 0x154000, 0x12c000, AVE_FW_TEXT_CRC_T8132_26B123, 0x4224 }, +}; + const struct ave_variant ave_t8132 = { .regs = &ave_coproc_v40, - .fw_text_size = 0x154000, - .fw_data_size = 0x12c000, + .builds = ave_t8132_builds, + .build_count = ARRAY_SIZE(ave_t8132_builds), .boot_device_id = 23, .boot_arg_value = AVE_COPROC_BOOT_ARG_VALUE, .timebase_multiplier = 1, @@ -155,8 +195,6 @@ const struct ave_variant ave_t8132 = { .vcbar_flags = AVE_COPROC_VCBAR_VALID, .device_type = 23, .lfs_ref_scale = 2, - .text_crc = AVE_FW_TEXT_CRC_T8132_26B123, - .text_boot_word = 0x4224, .boot_qualified = true, }; @@ -179,10 +217,12 @@ static const struct ave_variant ave_t8140 = { * 0x154000 and DATA 0x134000 (ADT ave0 segment-ranges). macOS starts the coprocessor as on the * A18 Pro, after clearing the SVE idle word at mailbox +0x118. Its boot configuration names * device 28, and so does its handshake's device type. The macOS 27.3 beta 1 build is admitted - * beside it. + * beside it. As on the M4 Max, the 26A428 build's TEXT word at 0x4224 differs on every boot + * (the Mac Studio, J775D), so an unknown TEXT CRC of that build is retried with the word zeroed. + * The 26C5035 build has not been checked for such a word, so its CRC must match as it is. */ static const struct ave_fw_build ave_t6050_builds[] = { - { "26A428", 0x154000, 0x134000, AVE_FW_TEXT_CRC_T6050_26A428 }, + { "26A428", 0x154000, 0x134000, AVE_FW_TEXT_CRC_T6050_26A428, 0x4224 }, /* * macOS 27.3 beta 1 (iBoot 20457.60.65): TEXT is 0x4000 larger, DATA * keeps its size. It starts as 26A428 does and takes 26A428's command @@ -191,10 +231,8 @@ static const struct ave_fw_build ave_t6050_builds[] = { { "26C5035", 0x158000, 0x134000, AVE_FW_TEXT_CRC_T6050_26C5035 }, }; -static const struct ave_variant ave_t6050 = { +const struct ave_variant ave_t6050 = { .regs = &ave_coproc_v40, - .fw_text_size = 0x154000, - .fw_data_size = 0x134000, .builds = ave_t6050_builds, .build_count = ARRAY_SIZE(ave_t6050_builds), .boot_device_id = 28, @@ -204,7 +242,6 @@ static const struct ave_variant ave_t6050 = { .vcbar_flags = AVE_COPROC_VCBAR_VALID, .device_type = 28, .lfs_ref_scale = 2, - .text_crc = AVE_FW_TEXT_CRC_T6050_26A428, .mbox_idle = 0x118, .boot_qualified = true, }; diff --git a/drivers/media/platform/apple/ave/ave-fw.c b/drivers/media/platform/apple/ave/ave-fw.c index 0ff259ca96275b..95226720407119 100644 --- a/drivers/media/platform/apple/ave/ave-fw.c +++ b/drivers/media/platform/apple/ave/ave-fw.c @@ -44,6 +44,7 @@ static const u32 ave_known_text_crc[] = { AVE_FW_TEXT_CRC_T6050_26C5035, /* encoder firmware macOS 27.3 26C5035r / T6050 */ AVE_FW_TEXT_CRC_T8142_26A428, /* encoder firmware 9013.45.1, macOS 27.0 26A428 / T8142 */ AVE_FW_TEXT_CRC_T8122_26B123, /* encoder firmware macOS 27.2 26B123 / T8122 */ + AVE_FW_TEXT_CRC_T8112_26B123, /* encoder firmware macOS 27.2 26B123 / T8112 */ AVE_FW_TEXT_CRC_T8132_26B123, /* encoder firmware macOS 27.2 26B123 / T8132 */ AVE_FW_TEXT_CRC_T8142_26B123, /* encoder firmware 9013.55.1, macOS 27.2 26B123 / T8142 */ 0x460c7a7c, /* encoder firmware 6070.11.1 / T6000 */ @@ -184,9 +185,9 @@ int ave_fw_text_boot_crc(const void *text, size_t size, u32 word_off, /* * A known TEXT CRC (the M4 Pro build) stays as it is; any other is retried - * with the per-boot word zeroed (the M4 Max and M4 27.2 builds). + * with the build's per-boot word at @word_off zeroed. */ -static int ave_fw_text_boot_id(struct ave_dev *ave, u32 *crc) +static int ave_fw_text_boot_id(struct ave_dev *ave, u32 word_off, u32 *crc) { void *va; int ret; @@ -196,20 +197,20 @@ static int ave_fw_text_boot_id(struct ave_dev *ave, u32 *crc) va = memremap(ave->text.phys, ave->text.size, MEMREMAP_WB); if (!va) return -ENOMEM; - ret = ave_fw_text_boot_crc(va, ave->text.size, - ave->variant->text_boot_word, crc); + ret = ave_fw_text_boot_crc(va, ave->text.size, word_off, crc); memunmap(va); return ret; } -static int ave_fw_text_id(struct ave_dev *ave, u32 *crc) +static int ave_fw_text_id(struct ave_dev *ave, const struct ave_fw_build *build, + u32 *crc) { void *va; int ret; if (!ave->variant->text_link_cell) - return ave->variant->text_boot_word ? - ave_fw_text_boot_id(ave, crc) : 0; + return build && build->text_boot_word ? + ave_fw_text_boot_id(ave, build->text_boot_word, crc) : 0; va = memremap(ave->text.phys, ave->text.size, MEMREMAP_WB); if (!va) return -ENOMEM; @@ -234,6 +235,32 @@ static const struct ave_fw_build *ave_fw_find_build(const struct ave_variant *v, return NULL; } +/* + * Whether TEXT/DATA segments of these sizes are a build the variant pins. + * ave_fw_probe() refuses the firmware when they are not. + */ +bool ave_fw_sizes_match(const struct ave_variant *v, size_t text, size_t data) +{ + if (v->build_count) + return ave_fw_find_build(v, text, data, 0); + return text == v->fw_text_size && data == v->fw_data_size; +} + +/* + * The variant for the build the bootloader preloaded: the matched one, or + * the first of its later builds whose segment sizes these are. Sizes alone + * pick the variant; ave_fw_probe() then refuses a TEXT CRC that is not the + * picked build's, so later builds of one encoder need sizes of their own. + */ +const struct ave_variant *ave_fw_select_build(const struct ave_variant *v, + size_t text, size_t data) +{ + for (const struct ave_variant *n = v; n; n = n->next_build) + if (ave_fw_sizes_match(n, text, data)) + return n; + return v; +} + /* * Find the firmware, check that it is a build we speak to and that DATA is * still as the bootloader left it, and keep a copy of DATA for restarts. @@ -242,8 +269,8 @@ int ave_fw_probe(struct ave_dev *ave) { struct device *dev = ave->dev; const struct ave_fw_build *build = NULL; - u32 text_crc, data_crc, want, want_crc = ave->variant->text_crc; - bool known = !ave->variant->boot_qualified; + u32 text_crc, data_crc, want, want_crc; + bool known; int ret; if (of_count_phandle_with_args(dev->of_node, "memory-region", NULL) != @@ -256,6 +283,10 @@ int ave_fw_probe(struct ave_dev *ave) if (ret) return dev_err_probe(dev, ret, "bad firmware reservation\n"); + ave->variant = ave_fw_select_build(ave->variant, ave->text.size, + ave->data.size); + want_crc = ave->variant->text_crc; + known = !ave->variant->boot_qualified; if (ave->variant->build_count) { build = ave_fw_find_build(ave->variant, ave->text.size, ave->data.size, 0); @@ -266,12 +297,11 @@ int ave_fw_probe(struct ave_dev *ave) want_crc = build->text_crc; } else if (!ave->variant->boot_qualified && !ave->variant->fw_text_size) { /* A probe-only variant that pins no build takes any segment sizes. */ - } else if (ave->text.size != ave->variant->fw_text_size || - (ave->data.size != ave->variant->fw_data_size && - (!ave->variant->fw_data_size_alt || - ave->data.size != ave->variant->fw_data_size_alt))) { + } else if (!ave_fw_sizes_match(ave->variant, ave->text.size, + ave->data.size)) { return dev_err_probe(dev, -EINVAL, - "unexpected firmware segment sizes\n"); + "unexpected firmware segment sizes (TEXT %#zx DATA %#zx)\n", + ave->text.size, ave->data.size); } if ((ave->text.phys < ave->data.phys + ave->data.size && ave->data.phys < ave->text.phys + ave->text.size) || @@ -305,7 +335,7 @@ int ave_fw_probe(struct ave_dev *ave) if (ret || text_crc != want) return dev_err_probe(dev, -ENODEV, "firmware text differs from loader CRC\n"); - ret = ave_fw_text_id(ave, &text_crc); + ret = ave_fw_text_id(ave, build, &text_crc); if (ret) return dev_err_probe(dev, ret, "firmware text link cell is not the DATA address\n"); diff --git a/drivers/media/platform/apple/ave/ave-ipc-test.c b/drivers/media/platform/apple/ave/ave-ipc-test.c new file mode 100644 index 00000000000000..40f32562ff3b94 --- /dev/null +++ b/drivers/media/platform/apple/ave/ave-ipc-test.c @@ -0,0 +1,1129 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the AVE IPC parsers and bounds checks: everything the + * firmware writes into the shared window (hello words, channel tables, ring + * slots, acks, messages, shared-memory requests) must stay inside it. + * + * Included at the end of ave-ipc.c to reach its static helpers. The shared + * window and the mailbox are plain kernel memory; no hardware is touched. + * + * Copyright The Aurora Silicon Contributors + */ +#include +#include + +#define T_FW_BASE 0x100000000ULL +/* Large enough to hold the whole 6070 command area. */ +#define T_IPC_BYTES 0x160000 +/* Bytes past ipc.size kept as a canary: nothing may write there. */ +#define T_CANARY_BYTES SZ_16K +#define T_CANARY 0xa5 + +struct t_ipc { + struct ave_dev *ave; + struct ave_fw_transport *t; + struct ave_fw_abi *abi; + struct ave_fw_layout *layout; +}; + +/* A device with a private copy of @base's layout, ABI and transport. */ +static void t_ipc_init(struct kunit *test, struct t_ipc *ti, + const struct ave_fw_layout *base, size_t ipc_bytes) +{ + struct ave_dev *ave = kunit_kzalloc(test, sizeof(*ave), GFP_KERNEL); + static atomic_t seq = ATOMIC_INIT(0); + char name[32]; + + KUNIT_ASSERT_NOT_NULL(test, ave); + ti->ave = ave; + ti->t = kunit_kmalloc(test, sizeof(*ti->t), GFP_KERNEL); + ti->abi = kunit_kmalloc(test, sizeof(*ti->abi), GFP_KERNEL); + ti->layout = kunit_kmalloc(test, sizeof(*ti->layout), GFP_KERNEL); + KUNIT_ASSERT_TRUE(test, ti->t && ti->abi && ti->layout); + *ti->layout = *base; + *ti->abi = *base->abi; + *ti->t = *base->abi->transport; + ti->abi->transport = ti->t; + ti->layout->abi = ti->abi; + ave->layout = ti->layout; + ave->variant = &ave_t6000; + + /* Several devices per case; names must be unique. */ + snprintf(name, sizeof(name), "apple-ave-ipc-%d", atomic_inc_return(&seq)); + ave->dev = kunit_device_register(test, name); + KUNIT_ASSERT_FALSE(test, IS_ERR(ave->dev)); + ave->ipc.cpu = kunit_kzalloc(test, ipc_bytes + T_CANARY_BYTES, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ave->ipc.cpu); + memset(ave->ipc.cpu + ipc_bytes, T_CANARY, T_CANARY_BYTES); + ave->ipc.size = ipc_bytes; + ave->ipc_fw_base = T_FW_BASE; + ave->mbox = (void __iomem __force *)kunit_kzalloc(test, SZ_4K, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, (void __force *)ave->mbox); + spin_lock_init(&ave->irq_lock); + init_waitqueue_head(&ave->irq_wait); + ave->fw_state = AVE_FW_RUNNING; +} + +static void t_canary_intact(struct kunit *test, struct ave_dev *ave) +{ + KUNIT_EXPECT_NULL(test, memchr_inv(ave->ipc.cpu + ave->ipc.size, + T_CANARY, T_CANARY_BYTES)); +} + +static __le64 *t_slot(struct ave_dev *ave, const struct ave_ring *r, + unsigned int n) +{ + return ave->ipc.cpu + r->offset + n * AVE_RING_SLOT_BYTES; +} + +/* Lay out one ring as ave_ipc_parse_channels() leaves it. */ +static void t_ring(struct ave_dev *ave, unsigned int id, u32 offset, + u32 slots, u32 doorbell, bool to_host) +{ + struct ave_ring *r = &ave->ring[id]; + + *r = (struct ave_ring){ + .mode = to_host ? 0 : 1, + .doorbell = doorbell, + .slots = slots, + .offset = AVE_IPC_CHANNEL_OFF + offset, + .consumer = to_host ? 0 : -1, + .producer = to_host ? -1 : 0, + }; + /* + * Bit 0 set: a host-to-firmware slot is free for the host, a + * firmware-to-host slot still belongs to the firmware. + */ + for (unsigned int n = 0; n < slots; n++) + *t_slot(ave, r, n) = cpu_to_le64(1); +} + +/* IO and IO_T2H with four slots each, as on 6070. */ +static void t_rings(struct ave_dev *ave) +{ + memset(ave->ring, 0, sizeof(ave->ring)); + t_ring(ave, AVE_RING_IO, 0x800, 4, 1, false); + t_ring(ave, AVE_RING_T2H, 0xa00, 4, 3, true); +} + +/* Play the firmware: post @addr/@len to the host in ring slot @n. */ +static void t_fw_post(struct ave_dev *ave, unsigned int id, unsigned int n, + u64 addr, u64 len) +{ + __le64 *slot = t_slot(ave, &ave->ring[id], n); + + slot[1] = cpu_to_le64(len); + slot[2] = 0; + /* Host-to-firmware slots are acked by setting bit 0, others by clearing it. */ + slot[0] = cpu_to_le64(addr | ave->ring[id].mode); +} + +static void t_ring_indices_valid(struct kunit *test, const struct ave_ring *r) +{ + KUNIT_EXPECT_GE(test, r->consumer, -1); + KUNIT_EXPECT_LT(test, r->consumer, (int)r->slots); + KUNIT_EXPECT_GE(test, r->producer, -1); + KUNIT_EXPECT_LT(test, r->producer, (int)r->slots); +} + +/* 9003 hello: the descriptor area and the heap are both bounded. */ +static void ave_ipc_test_hello_9003(struct kunit *test) +{ + const struct ave_fw_transport *t = ave_abi_9003.transport; + u32 min = t->descriptors * AVE_CHAN_DESC_STRIDE; + u32 max = AVE_IPC_HANDSHAKE_OFF - AVE_IPC_CHANNEL_OFF; + u32 hello[4] = { t->hello[0], min, t->hello[2], SZ_1M }; + + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), 0); + hello[1] = min - 1; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[1] = max; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), 0); + /* A channel area running into the handshake block. */ + hello[1] = max + 1; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[1] = U32_MAX; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[1] = min; + /* 9003 always asks for a heap, never more than 4 MiB. */ + hello[3] = 0; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[3] = 4 * SZ_1M; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), 0); + hello[3] = 4 * SZ_1M + 1; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[3] = U32_MAX; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[3] = SZ_1M; + hello[0] = t->hello[0] + 1; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[0] = t->hello[0]; + hello[2] = 0; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); +} + +/* A bad hello is refused before the mailbox or the window are touched. */ +static void ave_ipc_test_negotiate_bad_hello(struct kunit *test) +{ + struct t_ipc ti; + u32 hello[4]; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + memcpy(hello, ti.t->hello, sizeof(hello)); + hello[1]++; + KUNIT_EXPECT_EQ(test, ave_ipc_negotiate(ti.ave, hello), -EPROTO); + KUNIT_EXPECT_EQ(test, readl(ti.ave->mbox + AVE_MBOX_DOORBELL), 0U); + KUNIT_EXPECT_EQ(test, ti.ave->channel_bytes, 0U); + /* A heap larger than 4 MiB is not allocated either. */ + memcpy(hello, ti.t->hello, sizeof(hello)); + hello[3] = 4 * SZ_1M + 1; + KUNIT_EXPECT_EQ(test, ave_ipc_negotiate(ti.ave, hello), -EPROTO); + KUNIT_EXPECT_NULL(test, ti.ave->heap.cpu); +} + +/* + * The fake mailbox answers with the words the host wrote, so the IPC window + * address the "firmware" reports is ipc.dma. It must be 16 KiB aligned and + * the whole window must fit below 2^64. + */ +static void ave_ipc_test_negotiate_window(struct kunit *test) +{ + static const u64 bad[] = { + 0, T_FW_BASE + SZ_4K, 0xffffffffffffc000ULL, + }; + struct t_ipc ti; + u8 *hs; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + hs = ti.ave->ipc.cpu + AVE_IPC_HANDSHAKE_OFF; + for (unsigned int i = 0; i < ARRAY_SIZE(bad); i++) { + ti.ave->ipc.dma = bad[i]; + memset(ti.ave->ipc.cpu + AVE_IPC_CHANNEL_OFF, T_CANARY, 0x100); + KUNIT_EXPECT_EQ(test, ave_ipc_negotiate(ti.ave, ti.t->hello), + -EPROTO); + /* Nothing was cleared or handed to the firmware. */ + KUNIT_EXPECT_EQ(test, + *(u8 *)(ti.ave->ipc.cpu + AVE_IPC_CHANNEL_OFF), + T_CANARY); + } + + /* + * A good window gets the handshake block, but the echoed handshake + * address is not the channel area: refused before any channel is parsed. + */ + ti.ave->ipc.dma = T_FW_BASE; + KUNIT_EXPECT_EQ(test, ave_ipc_negotiate(ti.ave, ti.t->hello), -EPROTO); + KUNIT_EXPECT_EQ(test, ti.ave->ipc_fw_base, T_FW_BASE); + KUNIT_EXPECT_EQ(test, ti.ave->channel_bytes, ti.t->hello[1]); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(hs + AVE_HS_CHANNELS), + T_FW_BASE + AVE_IPC_CHANNEL_OFF); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(hs + AVE_HS_DEVICE_TYPE), + ave_t6000.device_type); + KUNIT_EXPECT_EQ(test, ti.ave->ring[AVE_RING_IO].slots, 0U); + t_canary_intact(test, ti.ave); +} + +/* A two-descriptor (9003-style) table: IO then IO_T2H. */ +#define T_CHAN_BYTES 0x1000 + +static u8 *t_desc(struct ave_dev *ave, unsigned int i) +{ + return ave->ipc.cpu + AVE_IPC_CHANNEL_OFF + i * AVE_CHAN_DESC_STRIDE; +} + +static void t_write_desc(struct ave_dev *ave, unsigned int i, const char *name, + u32 dir, u32 doorbell, u32 slots, u64 addr) +{ + u8 *desc = t_desc(ave, i); + + memset(desc, 0, AVE_CHAN_DESC_STRIDE); + strscpy(desc, name, AVE_CHAN_DESC_NAME_LEN); + put_unaligned_le32(dir, desc + AVE_CHAN_DESC_DIR); + put_unaligned_le32(doorbell, desc + AVE_CHAN_DESC_IRQ); + put_unaligned_le32(slots, desc + AVE_CHAN_DESC_SLOTS); + put_unaligned_le64(addr, desc + AVE_CHAN_DESC_ADDR); +} + +static u64 t_chan_addr(u32 off) +{ + return T_FW_BASE + AVE_IPC_CHANNEL_OFF + off; +} + +static void t_table_9003(struct ave_dev *ave) +{ + t_write_desc(ave, 0, "IO", 0, 1, 8, t_chan_addr(0x200)); + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, t_chan_addr(0x400)); +} + +static void t_channels_init(struct kunit *test, struct t_ipc *ti) +{ + t_ipc_init(test, ti, &ave_layout_9003_78_0, T_IPC_BYTES); + ti->ave->channel_bytes = T_CHAN_BYTES; + t_table_9003(ti->ave); + KUNIT_ASSERT_EQ(test, ave_ipc_parse_channels(ti->ave), 0); +} + +static void ave_ipc_test_channels_9003(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + + t_channels_init(test, &ti); + ave = ti.ave; + KUNIT_EXPECT_STREQ(test, ave->ring[AVE_RING_IO].name, "IO"); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].offset, + AVE_IPC_CHANNEL_OFF + 0x200); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].mode, 1U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].producer, 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].consumer, -1); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_T2H].mode, 0U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_T2H].producer, -1); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_T2H].consumer, 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_SMALLOC].slots, 0U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_LOG].slots, 0U); + for (unsigned int n = 0; n < 8; n++) + KUNIT_EXPECT_EQ(test, + le64_to_cpu(*t_slot(ave, &ave->ring[AVE_RING_IO], n)), + 1ULL); + /* The slot after the ring is not handed over. */ + KUNIT_EXPECT_EQ(test, + le64_to_cpu(*t_slot(ave, &ave->ring[AVE_RING_IO], 8)), + 0ULL); + + /* The last ring may end exactly at the end of the channel area. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(T_CHAN_BYTES - 8 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + /* Doorbell 31 is the last mailbox bit. */ + t_write_desc(ave, 1, "IO_T2H", 1, 31, 8, t_chan_addr(0x400)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_T2H].doorbell, 31U); + /* Order does not matter on a table with no fixed indices. */ + t_write_desc(ave, 0, "IO_T2H", 1, 3, 8, t_chan_addr(0x400)); + t_write_desc(ave, 1, "IO", 0, 1, 8, t_chan_addr(0x200)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].offset, + AVE_IPC_CHANNEL_OFF + 0x200); +} + +/* Every malformed descriptor the firmware could write is refused. */ +static void ave_ipc_test_channels_malformed(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + u8 *desc; + + t_channels_init(test, &ti); + ave = ti.ave; + desc = t_desc(ave, 0); + + /* A name with no terminating NUL in its 64 bytes. */ + memset(desc, 'A', AVE_CHAN_DESC_NAME_LEN); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* A two-channel table has no room for unknown channels. */ + t_write_desc(ave, 0, "DEBUG", 0, 1, 8, t_chan_addr(0x200)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* Wrong direction. */ + put_unaligned_le32(1, desc + AVE_CHAN_DESC_DIR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(2, desc + AVE_CHAN_DESC_DIR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* Doorbells outside the 32-bit doorbell register, or none for IO. */ + put_unaligned_le32(32, desc + AVE_CHAN_DESC_IRQ); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(U32_MAX, desc + AVE_CHAN_DESC_IRQ); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(0, desc + AVE_CHAN_DESC_IRQ); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* No slots. */ + put_unaligned_le32(0, desc + AVE_CHAN_DESC_SLOTS); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* More slots than the channel area holds (slots * 64 wraps in u32). */ + put_unaligned_le32(T_CHAN_BYTES / AVE_RING_SLOT_BYTES + 1, + desc + AVE_CHAN_DESC_SLOTS); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(0x04000000, desc + AVE_CHAN_DESC_SLOTS); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(U32_MAX, desc + AVE_CHAN_DESC_SLOTS); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* Two IO channels and no IO_T2H. */ + t_write_desc(ave, 1, "IO", 0, 1, 8, t_chan_addr(0x400)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Two IO_T2H channels and no IO. */ + t_write_desc(ave, 0, "IO_T2H", 1, 3, 8, t_chan_addr(0x200)); + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, t_chan_addr(0x400)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); +} + +/* Ring addresses must land inside the channel area, past the descriptors. */ +static void ave_ipc_test_channels_out_of_range(struct kunit *test) +{ + static const u64 bad[] = { + /* Below the window, and far below it (u64 wrap). */ + T_FW_BASE - AVE_RING_SLOT_BYTES, + 0, + /* Not slot aligned. */ + T_FW_BASE + AVE_IPC_CHANNEL_OFF + 0x208, + /* On top of the descriptor table. */ + T_FW_BASE + AVE_IPC_CHANNEL_OFF, + T_FW_BASE + AVE_IPC_CHANNEL_OFF + 2 * AVE_CHAN_DESC_STRIDE - + AVE_RING_SLOT_BYTES, + /* One slot past the end of the channel area. */ + T_FW_BASE + AVE_IPC_CHANNEL_OFF + T_CHAN_BYTES - + 7 * AVE_RING_SLOT_BYTES, + /* Inside the window but past the channel area. */ + T_FW_BASE + AVE_IPC_HANDSHAKE_OFF, + /* Past the window, and at the top of the address space. */ + T_FW_BASE + T_IPC_BYTES, + U64_MAX & ~(u64)(AVE_RING_SLOT_BYTES - 1), + }; + struct ave_dev *ave; + struct t_ipc ti; + + t_channels_init(test, &ti); + ave = ti.ave; + for (unsigned int i = 0; i < ARRAY_SIZE(bad); i++) { + for (unsigned int d = 0; d < 2; d++) { + t_table_9003(ave); + put_unaligned_le64(bad[i], t_desc(ave, d) + AVE_CHAN_DESC_ADDR); + KUNIT_EXPECT_EQ_MSG(test, ave_ipc_parse_channels(ave), -EPROTO, + "descriptor %u at %#llx", d, bad[i]); + } + } + t_canary_intact(test, ave); +} + +/* Rings may touch but not share a slot. */ +static void ave_ipc_test_channels_overlap(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + + t_channels_init(test, &ti); + ave = ti.ave; + /* IO_T2H starting in IO's last slot. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x200 + 7 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Same place. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, t_chan_addr(0x200)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* A one-slot ring inside the other. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 1, + t_chan_addr(0x200 + 3 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Back to back, either way round. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x200 + 8 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + /* IO further up, so that IO_T2H can sit right below it. */ + t_write_desc(ave, 0, "IO", 0, 1, 8, t_chan_addr(0x600)); + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x600 - 8 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + /* IO_T2H ending in IO's first slot. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x600 - 7 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* IO_T2H starting in IO's last slot. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x600 + 7 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); +} + +/* The 6070 table: unknown channels are skipped but still bounds checked. */ +static const struct { + const char *name; + u32 dir, doorbell, slots, offset; +} t_6070_desc[] = { + { "TERMINAL", 2, 0, 512, 0x700 }, { "IO", 0, 1, 32, 0x8700 }, + { "DEBUG", 0, 1, 8, 0x8f00 }, { "BUF_H2T", 0, 2, 1, 0x9100 }, + { "BUF_T2H", 1, 3, 1, 0x9140 }, { "SHAREDMALLOC", 1, 3, 8, 0x9180 }, + { "IO_T2H", 1, 3, 32, 0x9380 }, +}; + +static void t_table_6070(struct ave_dev *ave) +{ + for (unsigned int i = 0; i < ARRAY_SIZE(t_6070_desc); i++) + t_write_desc(ave, i, t_6070_desc[i].name, t_6070_desc[i].dir, + t_6070_desc[i].doorbell, t_6070_desc[i].slots, + t_chan_addr(t_6070_desc[i].offset)); +} + +static void ave_ipc_test_channels_6070_unknown(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + u8 *debug; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + ave->channel_bytes = ti.t->hello[1]; + t_table_6070(ave); + KUNIT_ASSERT_EQ(test, ave_ipc_parse_channels(ave), 0); + + debug = t_desc(ave, 2); + /* An unused channel pointing past the channel area. */ + put_unaligned_le64(t_chan_addr(ave->channel_bytes), debug + AVE_CHAN_DESC_ADDR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Or outside the window altogether. */ + put_unaligned_le64(T_FW_BASE + T_IPC_BYTES, debug + AVE_CHAN_DESC_ADDR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Or with an unterminated name. */ + t_table_6070(ave); + memset(debug, 'D', AVE_CHAN_DESC_NAME_LEN); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_6070(ave); + /* IO must be exactly where this firmware puts it. */ + put_unaligned_le64(t_chan_addr(0x8700 + AVE_RING_SLOT_BYTES), + t_desc(ave, 1) + AVE_CHAN_DESC_ADDR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_6070(ave); + put_unaligned_le32(2, t_desc(ave, 6) + AVE_CHAN_DESC_IRQ); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_6070(ave); + /* With no shared-memory pool, SHAREDMALLOC is an unknown channel. */ + ti.t->smalloc_bytes = 0; + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_SMALLOC].slots, 0U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_LOG].slots, 512U); + t_canary_intact(test, ave); +} + +/* Host-to-firmware ring: fill, refuse when full, wrap, drain to empty. */ +static void ave_ipc_test_ring_h2f(struct kunit *test) +{ + struct ave_ring *r; + struct ave_dev *ave; + struct t_ipc ti; + u64 addr; + u32 len; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + t_rings(ave); + r = &ave->ring[AVE_RING_IO]; + + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), -EAGAIN); + for (unsigned int n = 0; n < 4; n++) { + KUNIT_ASSERT_EQ(test, ave_ring_send(ave, r, 0x1000 * (n + 1), 0x40 + n), 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, n)[0]), + 0x1000ULL * (n + 1)); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, n)[1]), + 0x40ULL + n); + t_ring_indices_valid(test, r); + } + KUNIT_EXPECT_EQ(test, readl(ave->mbox + AVE_MBOX_DOORBELL), BIT(1)); + /* Full: a fifth command must not overwrite one the firmware owns. */ + KUNIT_EXPECT_EQ(test, r->producer, -1); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x9000, 0x99), -ENOSPC); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 0)[0]), 0x1000ULL); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 0)[1]), 0x40ULL); + + /* Not acked yet. */ + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), -EAGAIN); + /* The ack of slot 0 frees exactly that slot. */ + t_fw_post(ave, AVE_RING_IO, 0, 0x1000, 0); + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), 0); + KUNIT_EXPECT_EQ(test, addr, 0x1000ULL); + KUNIT_EXPECT_EQ(test, len, 0U); + KUNIT_EXPECT_EQ(test, r->producer, 0); + KUNIT_EXPECT_EQ(test, r->consumer, 1); + /* Wrap into slot 0; the ring is full again. */ + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x5000, 0x44), 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 0)[0]), 0x5000ULL); + KUNIT_EXPECT_EQ(test, r->producer, -1); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x9000, 0x99), -ENOSPC); + + /* Acks come back in ring order 1, 2, 3, 0. */ + for (unsigned int k = 0; k < 4; k++) { + unsigned int n = (k + 1) % 4; + u64 want = n ? 0x1000ULL * (n + 1) : 0x5000ULL; + + t_fw_post(ave, AVE_RING_IO, n, want, 0); + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), 0); + KUNIT_EXPECT_EQ(test, addr, want); + t_ring_indices_valid(test, r); + } + /* Empty. */ + KUNIT_EXPECT_EQ(test, r->consumer, -1); + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), -EAGAIN); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x6000, 0x40), 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 1)[0]), 0x6000ULL); +} + +/* Firmware-to-host ring: the two low bits never reach the address. */ +static void ave_ipc_test_ring_f2h(struct kunit *test) +{ + struct ave_ring *r; + struct ave_dev *ave; + struct t_ipc ti; + u64 addr; + u32 len; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + t_rings(ave); + r = &ave->ring[AVE_RING_T2H]; + + /* Every slot still belongs to the firmware. */ + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), -EAGAIN); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x1000, 0x40), -ENOSPC); + for (unsigned int k = 0; k < 6; k++) { + unsigned int n = k % 4; + + t_fw_post(ave, AVE_RING_T2H, n, 0x2000 * (k + 1) | 2, 0x40); + KUNIT_ASSERT_EQ(test, ave_ring_recv(ave, r, &addr, &len), 0); + KUNIT_EXPECT_EQ(test, addr, 0x2000ULL * (k + 1)); + KUNIT_EXPECT_EQ(test, len, 0x40U); + /* Next to read is the following slot, next to give back this one. */ + KUNIT_EXPECT_EQ(test, r->consumer, (int)((n + 1) % 4)); + KUNIT_EXPECT_EQ(test, r->producer, (int)n); + /* Give it back: bit 0 set hands the slot to the firmware. */ + KUNIT_ASSERT_EQ(test, ave_ring_send(ave, r, addr, len), 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, n)[0]), addr | 1); + KUNIT_EXPECT_EQ(test, r->consumer, (int)((n + 1) % 4)); + KUNIT_EXPECT_EQ(test, r->producer, -1); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, addr, len), -ENOSPC); + } + KUNIT_EXPECT_EQ(test, readl(ave->mbox + AVE_MBOX_DOORBELL), BIT(3)); +} + +/* Every command buffer maps to its own offset and back; nothing else does. */ +static void ave_ipc_test_buf_of(struct kunit *test) +{ + const struct ave_fw_layout *layouts[] = { + &ave_layout_9003_78_0, &ave_layout_6070_11_1, + }; + + for (unsigned int l = 0; l < ARRAY_SIZE(layouts); l++) { + const struct ave_fw_transport *t; + struct ave_dev *ave; + struct t_ipc ti; + size_t max, prev_end = 0; + int off; + + t_ipc_init(test, &ti, layouts[l], SZ_4K); + ave = ti.ave; + t = ti.t; + for (unsigned int buf = 0; buf < AVE_BUF_COUNT; buf++) { + off = ave_ipc_buf_offset(ave, buf, &max); + KUNIT_EXPECT_GE(test, off, (int)t->command_offset); + KUNIT_EXPECT_GE(test, (size_t)off, prev_end); + KUNIT_EXPECT_LE(test, off + max, ave_ipc_command_end(ave)); + prev_end = off + max; + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, T_FW_BASE + off), + (int)buf); + /* Inside a buffer is not a buffer. */ + KUNIT_EXPECT_EQ(test, + ave_ipc_buf_of(ave, T_FW_BASE + off + 4), + -EPROTO); + } + KUNIT_EXPECT_EQ(test, prev_end, (size_t)ave_ipc_command_end(ave)); + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, 0), -EPROTO); + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, T_FW_BASE - 1), -EPROTO); + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, T_FW_BASE), -EPROTO); + KUNIT_EXPECT_EQ(test, + ave_ipc_buf_of(ave, T_FW_BASE + t->command_offset - 4), + -EPROTO); + KUNIT_EXPECT_EQ(test, + ave_ipc_buf_of(ave, T_FW_BASE + ave_ipc_command_end(ave)), + -EPROTO); + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, U64_MAX), -EPROTO); + /* A buffer offset with no window base under it. */ + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, t->command_offset), -EPROTO); + } +} + +/* A command buffer is only handed out when it fits the window. */ +static void ave_ipc_test_cmd_bounds(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + size_t max; + int off; + u8 *cmd; + + /* A window that ends half way into the first Process buffer. */ + t_ipc_init(test, &ti, &ave_layout_6070_11_1, + ave_layout_6070_11_1.abi->transport->process_offset + SZ_32K); + ave = ti.ave; + + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_COUNT, 4)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, U32_MAX, 4)); + off = ave_ipc_buf_offset(ave, AVE_BUF_CMD, &max); + memset(ave->ipc.cpu + off, 0x5a, 0x100); + cmd = ave_ipc_cmd(ave, AVE_BUF_CMD, 0x80); + KUNIT_ASSERT_PTR_EQ(test, (void *)cmd, ave->ipc.cpu + off); + KUNIT_EXPECT_NULL(test, memchr_inv(cmd, 0, 0x80)); + KUNIT_EXPECT_EQ(test, cmd[0x80], 0x5a); + KUNIT_EXPECT_NOT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_CMD, max)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_CMD, max + 1)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_SCALAR(0), + AVE_IPC_SCALAR_BYTES + 1)); + KUNIT_EXPECT_NOT_NULL(test, + ave_ipc_cmd(ave, AVE_BUF_SCALAR(AVE_IPC_SCALAR_BUFS - 1), + AVE_IPC_SCALAR_BYTES)); + /* A buffer the firmware still owns is not handed out. */ + ave->unacked = BIT(AVE_BUF_SCALAR(3)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_SCALAR(3), 4)); + ave->unacked = 0; + /* Process buffer 0 fits up to the end of the window, not past it. */ + KUNIT_EXPECT_NOT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_PROC(0), SZ_32K)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_PROC(0), SZ_32K + 4)); + /* Process buffer 1 starts past the window. */ + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_PROC(1), 4)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_COUNT - 1, 4)); + t_canary_intact(test, ave); + + /* Submit applies the same bounds before it reads the command. */ + mutex_init(&ave->hw_lock); + mutex_lock(&ave->hw_lock); + KUNIT_EXPECT_EQ(test, ave_ipc_submit(ave, AVE_BUF_PROC(0), SZ_32K + 4, 0, false), + -EINVAL); + KUNIT_EXPECT_EQ(test, ave_ipc_submit(ave, AVE_BUF_PROC(1), 0x40, 0, false), + -EINVAL); + KUNIT_EXPECT_EQ(test, ave_ipc_submit(ave, AVE_BUF_COUNT, 0x40, 0, false), + -EINVAL); + mutex_unlock(&ave->hw_lock); + KUNIT_EXPECT_EQ(test, ave->unacked, 0U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].slots, 0U); +} + +/* Command acks: only the exact address of a buffer the firmware holds. */ +static void ave_ipc_test_poll_acks(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + u64 good; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + good = T_FW_BASE + ti.t->scalar_offset + 2 * AVE_IPC_SCALAR_BYTES; + + /* Nothing pending. */ + t_rings(ave); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 0); + + /* A good ack clears exactly its buffer. */ + ave->unacked = BIT(AVE_BUF_SCALAR(2)) | BIT(AVE_BUF_CMD); + KUNIT_ASSERT_EQ(test, ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40), 0); + t_fw_post(ave, AVE_RING_IO, 0, good, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 1); + KUNIT_EXPECT_EQ(test, ave->unacked, (u32)BIT(AVE_BUF_CMD)); + + /* An ack with a payload. */ + t_rings(ave); + ave->unacked = BIT(AVE_BUF_SCALAR(2)); + ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40); + t_fw_post(ave, AVE_RING_IO, 0, good, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + KUNIT_EXPECT_EQ(test, ave->unacked, (u32)BIT(AVE_BUF_SCALAR(2))); + /* An ack inside a buffer. */ + t_rings(ave); + ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40); + t_fw_post(ave, AVE_RING_IO, 0, good + 0x40, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + /* An ack outside the window. */ + t_rings(ave); + ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40); + t_fw_post(ave, AVE_RING_IO, 0, good - T_FW_BASE - 0x1000000, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + /* An ack for a buffer the host never sent. */ + t_rings(ave); + ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40); + t_fw_post(ave, AVE_RING_IO, 0, + T_FW_BASE + ti.t->scalar_offset + 3 * AVE_IPC_SCALAR_BYTES, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + KUNIT_EXPECT_EQ(test, ave->unacked, (u32)BIT(AVE_BUF_SCALAR(2))); +} + +/* Play the firmware: a 6070 lifecycle reply at window offset @off. */ +static void t_reply(struct t_ipc *ti, u32 off, enum ave_opcode op, u32 client, + u32 subtype, u32 status) +{ + u8 *msg = ti->ave->ipc.cpu + off; + + memset(msg, 0, 0x40); + put_unaligned_le16(ti->abi->reply_id[op], msg); + put_unaligned_le32(client, msg + 0x10); + put_unaligned_le32(subtype, msg + 0x1c); + put_unaligned_le32(status, msg + 0x38); +} + +#define T_MSG_OFF AVE_IPC_SHARED_OFF +#define T_REPLY_OK 0x00ee0000 + +static void t_msg_init(struct kunit *test, struct t_ipc *ti) +{ + struct ave_dev *ave; + + t_ipc_init(test, ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti->ave; + t_rings(ave); + ave->want[AVE_OP_OPEN] = 1; + ave->expected[AVE_OP_OPEN].client = 10; + ave->expected[AVE_OP_OPEN].subtype = ti->abi->semantic[AVE_OP_OPEN]; + t_reply(ti, T_MSG_OFF, AVE_OP_OPEN, 10, ti->abi->semantic[AVE_OP_OPEN], + T_REPLY_OK); + memset(ave->msg, 0x5a, sizeof(ave->msg)); +} + +/* The message is copied only when it lies inside the window, outside the commands. */ +static void ave_ipc_test_poll_msg_bounds(struct kunit *test) +{ + const struct ave_fw_transport *t = ave_layout_6070_11_1.abi->transport; + static const struct { + u64 off; + u64 len; + } bad[] = { + /* Larger than the host's message buffer. */ + { T_MSG_OFF, AVE_MSG_MAX + 1 }, + { T_MSG_OFF, U32_MAX }, + /* Running off the end of the window. */ + { T_IPC_BYTES - 0x20, 0x40 }, + { T_IPC_BYTES, 0x40 }, + /* In, or straddling into or out of, the command buffers. */ + { 0x40000, 0x40 }, + { 0x40000 - 0x20, 0x40 }, + { 0x78000 + AVE_IPC_PROC_BUFS * 0x10000 - 0x20, 0x40 }, + }; + struct t_ipc ti; + + /* The offsets above are the 6070 command area. */ + KUNIT_ASSERT_EQ(test, t->command_offset, 0x40000U); + KUNIT_ASSERT_EQ(test, t->process_offset + AVE_IPC_PROC_BUFS * t->process_bytes, + 0x78000U + AVE_IPC_PROC_BUFS * 0x10000); + for (unsigned int i = 0; i < ARRAY_SIZE(bad); i++) { + t_msg_init(test, &ti); + t_fw_post(ti.ave, AVE_RING_T2H, 0, T_FW_BASE + bad[i].off, bad[i].len); + KUNIT_EXPECT_EQ_MSG(test, ave_ipc_poll_once(ti.ave), -EPROTO, + "message %#llx/%#llx", bad[i].off, bad[i].len); + KUNIT_EXPECT_NULL(test, memchr_inv(ti.ave->msg, 0x5a, sizeof(ti.ave->msg))); + KUNIT_EXPECT_EQ(test, ti.ave->want[AVE_OP_OPEN], 1); + } + /* Below the window, and an address that only wraps into it. */ + t_msg_init(test, &ti); + t_fw_post(ti.ave, AVE_RING_T2H, 0, T_FW_BASE - 0x40, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ti.ave), -EPROTO); + t_msg_init(test, &ti); + t_fw_post(ti.ave, AVE_RING_T2H, 0, T_MSG_OFF - T_FW_BASE, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ti.ave), -EPROTO); + KUNIT_EXPECT_NULL(test, memchr_inv(ti.ave->msg, 0x5a, sizeof(ti.ave->msg))); + + /* Right below the command area is fine. */ + t_msg_init(test, &ti); + t_reply(&ti, 0x40000 - 0x40, AVE_OP_OPEN, 10, + ti.abi->semantic[AVE_OP_OPEN], T_REPLY_OK); + t_fw_post(ti.ave, AVE_RING_T2H, 0, T_FW_BASE + 0x40000 - 0x40, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ti.ave), 1); + KUNIT_EXPECT_EQ(test, ti.ave->want[AVE_OP_OPEN], 0); + /* So is right after it. */ + t_msg_init(test, &ti); + t_reply(&ti, 0x78000 + AVE_IPC_PROC_BUFS * 0x10000, AVE_OP_OPEN, 10, + ti.abi->semantic[AVE_OP_OPEN], T_REPLY_OK); + t_fw_post(ti.ave, AVE_RING_T2H, 0, + T_FW_BASE + 0x78000 + AVE_IPC_PROC_BUFS * 0x10000, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ti.ave), 1); + t_canary_intact(test, ti.ave); +} + +/* Replies are matched to what the host waits for, and the slot handed back. */ +static void ave_ipc_test_poll_dispatch(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + __le64 *slot; + + t_msg_init(test, &ti); + ave = ti.ave; + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 1); + KUNIT_EXPECT_EQ(test, ave->want[AVE_OP_OPEN], 0); + KUNIT_EXPECT_EQ(test, ave->reply_err, 0); + KUNIT_EXPECT_EQ(test, ave->msg_len, 0x40U); + KUNIT_EXPECT_MEMEQ(test, ave->msg, ave->ipc.cpu + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave->msg[0x40], 0x5a); + slot = t_slot(ave, &ave->ring[AVE_RING_T2H], 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(slot[0]), (T_FW_BASE + T_MSG_OFF) | 1); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 0); + + /* The same reply again: nobody waits for it. */ + t_fw_post(ave, AVE_RING_T2H, 1, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + + /* A reply for another client. */ + t_msg_init(test, &ti); + ave = ti.ave; + t_reply(&ti, T_MSG_OFF, AVE_OP_OPEN, 11, ti.abi->semantic[AVE_OP_OPEN], + T_REPLY_OK); + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + KUNIT_EXPECT_EQ(test, ave->want[AVE_OP_OPEN], 1); + + /* A reply of the wrong length or with an unknown id. */ + t_msg_init(test, &ti); + ave = ti.ave; + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x3c); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + t_msg_init(test, &ti); + ave = ti.ave; + put_unaligned_le16(0xffff, ave->ipc.cpu + T_MSG_OFF); + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + KUNIT_EXPECT_EQ(test, ave->want[AVE_OP_OPEN], 1); + + /* A refusal is answered but recorded. */ + t_msg_init(test, &ti); + ave = ti.ave; + t_reply(&ti, T_MSG_OFF, AVE_OP_OPEN, 10, ti.abi->semantic[AVE_OP_OPEN], 1); + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 1); + KUNIT_EXPECT_EQ(test, ave->want[AVE_OP_OPEN], 0); + KUNIT_EXPECT_EQ(test, ave->reply_err, -EIO); + + /* A frame result on a firmware build that cannot encode. */ + t_msg_init(test, &ti); + ave = ti.ave; + ti.layout->encode_ready = false; + t_reply(&ti, T_MSG_OFF, AVE_OP_PROCESS, 10, 0, T_REPLY_OK); + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x48); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); +} + +/* Log lines: every slot is handed back, wherever the line claims to be. */ +static void ave_ipc_test_drain_log(struct kunit *test) +{ + struct ave_ring *r; + struct ave_dev *ave; + struct t_ipc ti; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + memset(ave->ring, 0, sizeof(ave->ring)); + t_ring(ave, AVE_RING_LOG, 0x1000, 4, 0, true); + r = &ave->ring[AVE_RING_LOG]; + memcpy(ave->ipc.cpu + T_MSG_OFF, "line\n", 5); + memset(ave->ipc.cpu + T_IPC_BYTES - AVE_LOG_LINE_MAX, 'x', + AVE_LOG_LINE_MAX); + + /* Nothing written yet. */ + ave_ipc_drain_log(ave); + KUNIT_EXPECT_EQ(test, r->consumer, 0); + + t_fw_post(ave, AVE_RING_LOG, 0, T_FW_BASE + T_MSG_OFF, 5); + /* Running off the end of the window. */ + t_fw_post(ave, AVE_RING_LOG, 1, T_FW_BASE + T_IPC_BYTES - 4, 0x100); + /* An oversized line at the very end: clamped, so it fits. */ + t_fw_post(ave, AVE_RING_LOG, 2, + T_FW_BASE + T_IPC_BYTES - AVE_LOG_LINE_MAX, U32_MAX); + ave_ipc_drain_log(ave); + for (unsigned int n = 0; n < 3; n++) + KUNIT_EXPECT_EQ(test, le64_to_cpu(*t_slot(ave, r, n)), + (u64)AVE_LOG_SLOT_FREE); + KUNIT_EXPECT_EQ(test, le64_to_cpu(*t_slot(ave, r, 3)), 1ULL); + KUNIT_EXPECT_EQ(test, r->consumer, 3); + + /* Below the window, then a NULL line; the index wraps. */ + t_fw_post(ave, AVE_RING_LOG, 3, T_FW_BASE - 0x100, 0x10); + t_fw_post(ave, AVE_RING_LOG, 0, 0, 0x10); + ave_ipc_drain_log(ave); + KUNIT_EXPECT_EQ(test, r->consumer, 1); + KUNIT_EXPECT_EQ(test, le64_to_cpu(*t_slot(ave, r, 3)), + (u64)AVE_LOG_SLOT_FREE); + KUNIT_EXPECT_EQ(test, le64_to_cpu(*t_slot(ave, r, 0)), + (u64)AVE_LOG_SLOT_FREE); + + /* A full ring is read once round, not forever. */ + for (unsigned int n = 0; n < 4; n++) + t_fw_post(ave, AVE_RING_LOG, n, T_FW_BASE + T_MSG_OFF, 5); + ave_ipc_drain_log(ave); + KUNIT_EXPECT_EQ(test, r->consumer, 1); + t_canary_intact(test, ave); + + /* No TERMINAL channel: nothing to read. */ + memset(ave->ring, 0, sizeof(ave->ring)); + ave_ipc_drain_log(ave); +} + +/* A shared-memory pool of 48 granules, sized down for the test. */ +#define T_POOL_OFF 0x20000 +#define T_POOL_BYTES 0x30000 + +static void t_pool_init(struct kunit *test, struct t_ipc *ti) +{ + t_ipc_init(test, ti, &ave_layout_6070_11_1, T_POOL_OFF + T_POOL_BYTES); + ti->t->smalloc_offset = T_POOL_OFF; + ti->t->smalloc_bytes = T_POOL_BYTES; +} + +/* Every block lies inside the pool, and only blocks lent can be returned. */ +static void ave_ipc_test_smalloc_bounds(struct kunit *test) +{ + const u64 start = T_FW_BASE + T_POOL_OFF; + struct ave_dev *ave; + struct t_ipc ti; + u64 addr, a, b; + + t_pool_init(test, &ti); + ave = ti.ave; + memset(ave->ipc.cpu + T_POOL_OFF, 0x77, T_POOL_BYTES); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 0, &addr), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, T_POOL_BYTES + 1, &addr), -EINVAL); + /* The whole pool in one block, zeroed, and not a byte more. */ + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, T_POOL_BYTES, &addr), 0); + KUNIT_EXPECT_EQ(test, addr, start); + KUNIT_EXPECT_NULL(test, memchr_inv(ave->ipc.cpu + T_POOL_OFF, 0, T_POOL_BYTES)); + t_canary_intact(test, ave); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 1, &addr), -ENOMEM); + + /* Returns that are not a lent block. */ + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start - AVE_SMALLOC_GRANULE), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start + T_POOL_BYTES), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, U64_MAX & ~(u64)(SZ_4K - 1)), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, 0), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start + 1), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start + AVE_SMALLOC_GRANULE), -ENOENT); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start), 0); + /* Twice. */ + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start), -ENOENT); + + /* Partial granules round up; the last block ends at the pool's end. */ + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, 1, &a), 0); + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, T_POOL_BYTES - AVE_SMALLOC_GRANULE, &b), 0); + KUNIT_EXPECT_EQ(test, a, start); + KUNIT_EXPECT_EQ(test, b, start + AVE_SMALLOC_GRANULE); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 1, &addr), -ENOMEM); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, a), 0); + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, AVE_SMALLOC_GRANULE, &addr), 0); + KUNIT_EXPECT_EQ(test, addr, start); + t_canary_intact(test, ave); +} + +/* The host tracks at most AVE_SMALLOC_MAX blocks, even with room left. */ +static void ave_ipc_test_smalloc_slots(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + u64 addr, first = 0; + + t_pool_init(test, &ti); + ave = ti.ave; + KUNIT_ASSERT_GT(test, T_POOL_BYTES / AVE_SMALLOC_GRANULE, AVE_SMALLOC_MAX); + for (unsigned int i = 0; i < AVE_SMALLOC_MAX; i++) { + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, 1, &addr), 0); + KUNIT_EXPECT_EQ(test, addr, T_FW_BASE + T_POOL_OFF + i * AVE_SMALLOC_GRANULE); + if (!i) + first = addr; + } + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 1, &addr), -ENOSPC); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, first), 0); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 1, &addr), 0); + KUNIT_EXPECT_EQ(test, addr, first); +} + +/* The SHAREDMALLOC ring: unknown returns are answered, bad sizes stop serving. */ +static void ave_ipc_test_serve_smalloc(struct kunit *test) +{ + struct ave_ring *r; + struct ave_dev *ave; + struct t_ipc ti; + __le64 *slot; + + t_pool_init(test, &ti); + ave = ti.ave; + memset(ave->ring, 0, sizeof(ave->ring)); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), 0); + t_ring(ave, AVE_RING_SMALLOC, 0x800, 4, 3, true); + r = &ave->ring[AVE_RING_SMALLOC]; + + /* A block the host never lent: answered with no size. */ + t_fw_post(ave, AVE_RING_SMALLOC, 0, T_FW_BASE + T_POOL_OFF + SZ_64K, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), 1); + slot = t_slot(ave, r, 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(slot[0]), (T_FW_BASE + T_POOL_OFF + SZ_64K) | 1); + KUNIT_EXPECT_EQ(test, le64_to_cpu(slot[1]), 0ULL); + /* An address outside the window is answered the same way. */ + t_fw_post(ave, AVE_RING_SMALLOC, 1, 0x1000, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), 1); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 1)[1]), 0ULL); + /* A request with no size, then one larger than the pool. */ + t_fw_post(ave, AVE_RING_SMALLOC, 2, 0, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), -EINVAL); + t_ring(ave, AVE_RING_SMALLOC, 0x800, 4, 3, true); + t_fw_post(ave, AVE_RING_SMALLOC, 0, 0, T_POOL_BYTES + 1); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), -EINVAL); + t_ring_indices_valid(test, r); + t_canary_intact(test, ave); +} + +/* + * Request sizes near 4 GiB: rounding them up to granules must not wrap to + * zero granules, which would lend nothing while telling the firmware it + * has the whole size, at an address the next request gets again. + */ +static void ave_ipc_test_smalloc_huge(struct kunit *test) +{ + static const u32 huge[] = { + U32_MAX - AVE_SMALLOC_GRANULE + 1, + U32_MAX - AVE_SMALLOC_GRANULE + 2, + U32_MAX, + }; + struct ave_dev *ave; + struct t_ipc ti; + u64 addr; + + t_pool_init(test, &ti); + ave = ti.ave; + for (unsigned int i = 0; i < ARRAY_SIZE(huge); i++) + KUNIT_EXPECT_EQ_MSG(test, ave_smalloc_get(ave, huge[i], &addr), -EINVAL, + "request of %#x bytes", huge[i]); + + /* Through the ring: the request must not be answered with a block. */ + memset(ave->ring, 0, sizeof(ave->ring)); + t_ring(ave, AVE_RING_SMALLOC, 0x800, 4, 3, true); + t_fw_post(ave, AVE_RING_SMALLOC, 0, 0, U32_MAX); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), -EINVAL); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, &ave->ring[AVE_RING_SMALLOC], 0)[0]), + 0ULL); +} + +static struct kunit_case ave_ipc_test_cases[] = { + KUNIT_CASE(ave_ipc_test_hello_9003), + KUNIT_CASE(ave_ipc_test_negotiate_bad_hello), + KUNIT_CASE(ave_ipc_test_negotiate_window), + KUNIT_CASE(ave_ipc_test_channels_9003), + KUNIT_CASE(ave_ipc_test_channels_malformed), + KUNIT_CASE(ave_ipc_test_channels_out_of_range), + KUNIT_CASE(ave_ipc_test_channels_overlap), + KUNIT_CASE(ave_ipc_test_channels_6070_unknown), + KUNIT_CASE(ave_ipc_test_ring_h2f), + KUNIT_CASE(ave_ipc_test_ring_f2h), + KUNIT_CASE(ave_ipc_test_buf_of), + KUNIT_CASE(ave_ipc_test_cmd_bounds), + KUNIT_CASE(ave_ipc_test_poll_acks), + KUNIT_CASE(ave_ipc_test_poll_msg_bounds), + KUNIT_CASE(ave_ipc_test_poll_dispatch), + KUNIT_CASE(ave_ipc_test_drain_log), + KUNIT_CASE(ave_ipc_test_smalloc_bounds), + KUNIT_CASE(ave_ipc_test_smalloc_slots), + KUNIT_CASE(ave_ipc_test_serve_smalloc), + KUNIT_CASE(ave_ipc_test_smalloc_huge), + {} +}; + +static struct kunit_suite ave_ipc_test_suite = { + .name = "apple-ave-ipc", + .test_cases = ave_ipc_test_cases, +}; + +kunit_test_suite(ave_ipc_test_suite); diff --git a/drivers/media/platform/apple/ave/ave-ipc.c b/drivers/media/platform/apple/ave/ave-ipc.c index 518604147cc17d..09f218a8462e24 100644 --- a/drivers/media/platform/apple/ave/ave-ipc.c +++ b/drivers/media/platform/apple/ave/ave-ipc.c @@ -100,22 +100,34 @@ static bool ave_rings_overlap(const struct ave_ring *a, int ave_ipc_parse_channels(struct ave_dev *ave) { + const struct ave_fw_transport *t = ave->layout->abi->transport; + /* Validated host-to-firmware rings by descriptor; zero slots: none. */ + struct { + u32 slots; + u32 offset; + } h2t[AVE_IPC_MAX_CHANNELS] = {}; bool found[AVE_RINGS] = {}; + if (t->descriptors > ARRAY_SIZE(h2t)) + return -EPROTO; memset(ave->ring, 0, sizeof(ave->ring)); - for (unsigned int i = 0; i < ave->layout->abi->transport->descriptors; - i++) { - u8 *desc = ave->ipc.cpu + AVE_IPC_CHANNEL_OFF + - i * AVE_CHAN_DESC_STRIDE; - u32 dir = get_unaligned_le32(desc + AVE_CHAN_DESC_DIR); - u32 doorbell = get_unaligned_le32(desc + AVE_CHAN_DESC_IRQ); - u32 slots = get_unaligned_le32(desc + AVE_CHAN_DESC_SLOTS); - u64 addr = get_unaligned_le64(desc + AVE_CHAN_DESC_ADDR); + for (unsigned int i = 0; i < t->descriptors; i++) { + /* + * The firmware may write the channel area at any time: take one + * copy of the descriptor and use only that copy from here on. + */ + u8 desc[AVE_CHAN_DESC_ADDR + sizeof(u64)]; + u32 dir, doorbell, slots, offset; struct ave_ring *r; + u64 addr; int id; - u32 offset; - const struct ave_fw_transport *t = ave->layout->abi->transport; + memcpy(desc, ave->ipc.cpu + AVE_IPC_CHANNEL_OFF + + i * AVE_CHAN_DESC_STRIDE, sizeof(desc)); + dir = get_unaligned_le32(desc + AVE_CHAN_DESC_DIR); + doorbell = get_unaligned_le32(desc + AVE_CHAN_DESC_IRQ); + slots = get_unaligned_le32(desc + AVE_CHAN_DESC_SLOTS); + addr = get_unaligned_le64(desc + AVE_CHAN_DESC_ADDR); if (!memchr(desc, 0, AVE_CHAN_DESC_NAME_LEN) || slots > ave->channel_bytes / AVE_RING_SLOT_BYTES || @@ -128,7 +140,11 @@ int ave_ipc_parse_channels(struct ave_dev *ave) offset + slots * AVE_RING_SLOT_BYTES > AVE_IPC_CHANNEL_OFF + ave->channel_bytes) return -EPROTO; - id = ave_ring_id(desc); + if (!dir) { + h2t[i].slots = slots; + h2t[i].offset = offset; + } + id = ave_ring_id((const char *)desc); /* Channels the host has no use for are left alone. */ if (id == AVE_RING_SMALLOC && !t->smalloc_bytes) id = -ENOENT; @@ -148,7 +164,7 @@ int ave_ipc_parse_channels(struct ave_dev *ave) found[id] = true; r = &ave->ring[id]; - strscpy(r->name, desc, sizeof(r->name)); + strscpy(r->name, (const char *)desc, sizeof(r->name)); /* * Host-to-firmware rings start empty, firmware-to-host rings * full. Bit 0 of a slot's first word says whose turn it is: @@ -172,22 +188,12 @@ int ave_ipc_parse_channels(struct ave_dev *ave) /* * Hand every slot of every host-to-firmware ring to the host, the ones * the host never uses too: ownership is bit 0, and a slot left at zero - * reads to the firmware as a message posted to it. + * reads to the firmware as a message posted to it. Only the values + * validated above are used; the descriptors are not read again. */ - for (unsigned int i = 0; i < ave->layout->abi->transport->descriptors; - i++) { - u8 *desc = ave->ipc.cpu + AVE_IPC_CHANNEL_OFF + - i * AVE_CHAN_DESC_STRIDE; - u32 slots = get_unaligned_le32(desc + AVE_CHAN_DESC_SLOTS); - u32 offset; - - if (get_unaligned_le32(desc + AVE_CHAN_DESC_DIR)) - continue; - /* Checked above. */ - ave_fw_offset(ave, get_unaligned_le64(desc + AVE_CHAN_DESC_ADDR), - (size_t)slots * AVE_RING_SLOT_BYTES, &offset); - for (unsigned int n = 0; n < slots; n++) { - __le64 *slot = ave->ipc.cpu + offset + + for (unsigned int i = 0; i < t->descriptors; i++) { + for (unsigned int n = 0; n < h2t[i].slots; n++) { + __le64 *slot = ave->ipc.cpu + h2t[i].offset + n * AVE_RING_SLOT_BYTES; slot[0] = cpu_to_le64(1); @@ -389,7 +395,8 @@ static int ave_smalloc_get(struct ave_dev *ave, u32 bytes, u64 *addr) const struct ave_fw_transport *t = ave->layout->abi->transport; u32 total = min_t(u32, t->smalloc_bytes / AVE_SMALLOC_GRANULE, AVE_SMALLOC_UNITS); - u32 units = DIV_ROUND_UP(bytes, AVE_SMALLOC_GRANULE); + /* In 64 bits: a request near 4 GiB must not round up to 0 units */ + u32 units = DIV_ROUND_UP_ULL(bytes, AVE_SMALLOC_GRANULE); unsigned long first; unsigned int i; @@ -1000,3 +1007,7 @@ int ave_ipc_settle(struct ave_dev *ave, unsigned int wait_ms) ave->reply_err = 0; return ret; } + +#if IS_ENABLED(CONFIG_VIDEO_APPLE_AVE_IPC_KUNIT_TEST) +#include "ave-ipc-test.c" +#endif diff --git a/drivers/media/platform/apple/ave/ave-layout.c b/drivers/media/platform/apple/ave/ave-layout.c index 190d91415a009e..b05103511532ff 100644 --- a/drivers/media/platform/apple/ave/ave-layout.c +++ b/drivers/media/platform/apple/ave/ave-layout.c @@ -281,9 +281,11 @@ const struct ave_fw_layout ave_layout_9003_78_0 = { /* * The macOS 27.0 (26A428) command layout. The macOS 27.2 (26B123) build * keeps every field where 26A428 has it; only the Process commands grow - * (ave_layout_26b123). + * (ave_layout_26b123). rate_copy is the Start's second integer frame rate + * and hevc_low_delay the HEVC Process low-delay word, 0 where a build's + * sessions have not been run with them. */ -#define AVE_LAYOUT_26A428_FIELDS \ +#define AVE_LAYOUT_26A428_FIELDS(rate_copy, hevc_low_delay) \ .abi = &ave_abi_9003, \ .kind = AVE_LAYOUT_26A428, \ .encode_ready = true, \ @@ -335,6 +337,7 @@ const struct ave_fw_layout ave_layout_9003_78_0 = { .const_214 = 0x35f4, \ .const_218 = 0x35f8, \ .fps = { .numerator = 0x3600 }, \ + .fps_int_copy = rate_copy, \ .rc_mode = 0x3614, \ .bitrate = 0x3618, \ .init_qp = 0x3620, \ @@ -423,6 +426,7 @@ const struct ave_fw_layout ave_layout_9003_78_0 = { .const_214 = 0x35f4, \ .const_218 = 0x35f8, \ .fps = { .numerator = 0x3600 }, \ + .fps_int_copy = rate_copy, \ .rc_mode = 0x3614, \ .bitrate = 0x3618, \ .init_qp = 0x3620, \ @@ -524,6 +528,7 @@ const struct ave_fw_layout ave_layout_9003_78_0 = { .meta_size = 0x6060, \ .extra = 0x6068, \ .crop = 0x3190, \ + .low_delay = hevc_low_delay, \ }, \ }, \ .result = { \ @@ -541,7 +546,14 @@ const struct ave_fw_layout ave_layout_9003_78_0 = { const struct ave_fw_layout ave_layout_26a428 = { .name = "26A428", .bytes = { { 0x3b40, 0x6df8 }, { 0x13ee0, 0x78b8 } }, - AVE_LAYOUT_26A428_FIELDS + /* + * macOS 27.2.1 on the M5 writes the rate a second time at Start + * +0x320c (60 at 60 fps), and 3 at Process +0xce4 for HEVC without + * B-frames. + */ + AVE_LAYOUT_26A428_FIELDS(0x320c, 0xce4) + /* 60 fps and sessions without B-frames encode on the M5 (J815). */ + .any_gop = true, }; /* @@ -553,7 +565,7 @@ const struct ave_fw_layout ave_layout_26a428 = { const struct ave_fw_layout ave_layout_26b123 = { .name = "26B123", .bytes = { { 0x3b40, 0x6e08 }, { 0x13ee0, 0x78c8 } }, - AVE_LAYOUT_26A428_FIELDS + AVE_LAYOUT_26A428_FIELDS(0, 0) .any_gop = true, }; @@ -995,7 +1007,8 @@ const struct ave_fw_layout *ave_layout_for_crc(u32 crc) if (crc == AVE_FW_TEXT_CRC_T6050_26C5035) return &ave_layout_26a428; if (crc == AVE_FW_TEXT_CRC_T8132_26B123 || - crc == AVE_FW_TEXT_CRC_T8122_26B123) + crc == AVE_FW_TEXT_CRC_T8122_26B123 || + crc == AVE_FW_TEXT_CRC_T8112_26B123) return &ave_layout_26b123; /* * The M5's macOS 27.2 build (9013.55.1), between 26A428 and the 27.3 diff --git a/drivers/media/platform/apple/ave/ave-layout.h b/drivers/media/platform/apple/ave/ave-layout.h index e5cb20074d2764..d499102fb2adbe 100644 --- a/drivers/media/platform/apple/ave/ave-layout.h +++ b/drivers/media/platform/apple/ave/ave-layout.h @@ -135,6 +135,8 @@ struct ave_start_layout { u32 const_214; u32 const_218; struct ave_rational_layout fps; + /* A second copy of the integer frame rate (26A428 Start). */ + u32 fps_int_copy; u32 rc_mode; /* Optional ABI-specific wire value for the driver's fixed-QP mode. */ u32 rc_mode_fixed_qp; diff --git a/drivers/media/platform/apple/ave/ave-mctf-test.c b/drivers/media/platform/apple/ave/ave-mctf-test.c index 519d1d09043b30..b75001659f882c 100644 --- a/drivers/media/platform/apple/ave/ave-mctf-test.c +++ b/drivers/media/platform/apple/ave/ave-mctf-test.c @@ -9,7 +9,6 @@ * Copyright The Aurora Silicon Contributors */ #include -#include #include #include #include @@ -439,6 +438,3 @@ static struct kunit_suite ave_mctf_suite = { .test_cases = ave_mctf_cases, }; kunit_test_suite(ave_mctf_suite); - -MODULE_DESCRIPTION("Apple AVE MCTF command image tests"); -MODULE_LICENSE("GPL"); diff --git a/drivers/media/platform/apple/ave/ave-recovery-test.c b/drivers/media/platform/apple/ave/ave-recovery-test.c index a5166265d826c8..7b0c3fbf414fa7 100644 --- a/drivers/media/platform/apple/ave/ave-recovery-test.c +++ b/drivers/media/platform/apple/ave/ave-recovery-test.c @@ -116,4 +116,5 @@ static struct kunit_suite ave_recovery_suite = { kunit_test_suite(ave_recovery_suite); +MODULE_DESCRIPTION("Apple AVE firmware recovery window tests"); MODULE_LICENSE("GPL"); diff --git a/drivers/media/platform/apple/ave/ave-sess.c b/drivers/media/platform/apple/ave/ave-sess.c index ddf95b2b129699..85e3fae75fab44 100644 --- a/drivers/media/platform/apple/ave/ave-sess.c +++ b/drivers/media/platform/apple/ave/ave-sess.c @@ -194,9 +194,6 @@ static int ave_sess_params(struct ave_ctx *ctx, struct ave_params *p) return -EOPNOTSUPP; p->bit_depth = 8; if (p->sample_bytes == 2) { - /* Only the 9003 layout's Main 10 fields are mapped. */ - if (ctx->ave->layout->counted) - return -EOPNOTSUPP; p->profile = AVE_HEVC_MAIN_10; p->bit_depth = 10; p->min_qp -= AVE_QP_BD_OFFSET_10; @@ -764,6 +761,10 @@ static void ave_note_copy(struct ave_ctx *ctx, u32 stride, const char *how) * buffer with their own, smaller line size instead, which shows in the * payload size; such frames are copied to a per-slot buffer in the * encoder's layout. + * + * The encoder reads a whole coded frame (p->ch lines, the size S_FMT + * reports) from the address it is given, so every address handed out here + * has that much memory behind it. */ int ave_sess_input(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buffer *src, dma_addr_t *input) @@ -775,6 +776,7 @@ int ave_sess_input(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buffe u32 used = vb2_get_plane_payload(vb, 0) - min(off, vb2_get_plane_payload(vb, 0)); u32 crows = DIV_ROUND_UP(p->height, 2), rows = p->height + crows; u32 width = ALIGN(p->width, 2) * p->sample_bytes, stride; + size_t frame = (size_t)p->stride * p->ch * 3 / 2; struct ave_buf *b = &sess->slot[slot].bounce; const u8 *from; u8 *to; @@ -782,6 +784,12 @@ int ave_sess_input(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buffe *input = vb2_dma_contig_plane_dma_addr(vb, 0) + off; if (!used || used >= p->stride * rows || used % rows || used / rows < width) { + if ((size_t)off + frame > vb2_plane_size(vb, 0)) { + dev_err_ratelimited(ctx->ave->dev, + "OUTPUT plane has no %zu byte frame after offset %u\n", + frame, off); + return -EINVAL; + } if (IS_ALIGNED(*input, 64)) return 0; dev_err(ctx->ave->dev, "OUTPUT plane at %pad is not 64-byte aligned\n", input); @@ -801,10 +809,11 @@ int ave_sess_input(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buffe * Buffers the driver allocated (MMAP) are large enough for the * encoder's layout: spread the lines out in place, last line first, * so no extra DMA space is needed. Imported buffers may be shared - * with other users and get a copy instead. + * with other users and get a copy instead, and so does a buffer whose + * data_offset leaves the picture off the encoder's 64-byte alignment. */ - if (vb->memory == VB2_MEMORY_MMAP && - vb2_plane_size(vb, 0) >= off + (size_t)p->stride * rows) { + if (vb->memory == VB2_MEMORY_MMAP && IS_ALIGNED(*input, 64) && + vb2_plane_size(vb, 0) >= (size_t)off + frame) { to = (u8 *)from; for (u32 y = rows; y-- > 0;) memmove(to + y * p->stride, from + y * stride, width); @@ -812,7 +821,7 @@ int ave_sess_input(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buffe return 0; } - ret = ave_alloc(ctx->ave, b, p->stride * rows, 0); + ret = ave_alloc(ctx->ave, b, frame, 0); if (ret) { dev_err(ctx->ave->dev, "no room to copy %u byte stride input\n", stride); return ret; @@ -1093,6 +1102,155 @@ static bool ave_starts_annexb(const u8 *p, size_t len) (len >= 4 && !p[0] && !p[1] && !p[2] && p[3] == 1); } +/* + * Slice type of the first slice of an access unit, for the CAPTURE buffer's + * B/P flag: the firmware reorders B-frames itself, so the driver learns a + * picture's type from its bitstream. Only the first few bytes after the NAL + * header are read (emulation-prevention bytes removed); anything unexpected + * gives "not B". + */ +struct ave_rbsp { + u8 b[24]; + unsigned int n, pos; /* bytes in b; next bit */ +}; + +static void ave_rbsp_init(struct ave_rbsp *r, const u8 *p, size_t len) +{ + unsigned int zeros = 0; + + r->n = 0; + r->pos = 0; + for (size_t i = 0; i < len && r->n < sizeof(r->b); i++) { + if (zeros >= 2 && p[i] == 3) { + zeros = 0; + continue; + } + zeros = p[i] ? 0 : zeros + 1; + r->b[r->n++] = p[i]; + } +} + +static int ave_rbsp_bit(struct ave_rbsp *r) +{ + int bit; + + if (r->pos >= r->n * 8) + return -1; + bit = (r->b[r->pos / 8] >> (7 - r->pos % 8)) & 1; + r->pos++; + return bit; +} + +/* ue(v), or -1 past the bytes read or above 31 leading zeros. */ +static s64 ave_rbsp_ue(struct ave_rbsp *r) +{ + unsigned int zeros = 0; + u64 v = 0; + int bit; + + while ((bit = ave_rbsp_bit(r)) == 0) + if (++zeros > 31) + return -1; + if (bit < 0) + return -1; + for (unsigned int i = 0; i < zeros; i++) { + bit = ave_rbsp_bit(r); + if (bit < 0) + return -1; + v = v << 1 | bit; + } + return (s64)((1ULL << zeros) - 1 + v); +} + +/* HEVC PPS: num_extra_slice_header_bits, needed to reach slice_type. */ +static int ave_hevc_pps_extra_bits(const u8 *nal, size_t len) +{ + struct ave_rbsp r; + int v = 0; + + ave_rbsp_init(&r, nal + 2, len - 2); + if (ave_rbsp_ue(&r) < 0 || ave_rbsp_ue(&r) < 0) /* pps id, sps id */ + return -1; + if (ave_rbsp_bit(&r) < 0 || ave_rbsp_bit(&r) < 0) /* dependent slices, output flag */ + return -1; + for (unsigned int i = 0; i < 3; i++) { + int bit = ave_rbsp_bit(&r); + + if (bit < 0) + return -1; + v = v << 1 | bit; + } + return v; +} + +static bool ave_slice_is_b(const u8 *nal, size_t len, bool hevc, u8 extra_bits) +{ + u32 nal_type = (nal[0] >> 1) & 0x3f; + struct ave_rbsp r; + s64 type; + + if (!hevc) { + ave_rbsp_init(&r, nal + 1, len - 1); + if (ave_rbsp_ue(&r) < 0) /* first_mb_in_slice */ + return false; + type = ave_rbsp_ue(&r); + return type == 1 || type == 6; /* B, B (all slices) */ + } + + ave_rbsp_init(&r, nal + 2, len - 2); + if (ave_rbsp_bit(&r) != 1) /* first_slice_segment_in_pic_flag */ + return false; + if (nal_type >= 16 && nal_type <= 23 && ave_rbsp_bit(&r) < 0) + return false; + if (ave_rbsp_ue(&r) < 0) /* slice_pic_parameter_set_id */ + return false; + for (unsigned int i = 0; i < extra_bits; i++) + if (ave_rbsp_bit(&r) < 0) + return false; + type = ave_rbsp_ue(&r); + return type == 0; /* HEVC: 0 = B, 1 = P, 2 = I */ +} + +/* Whether the access unit's first slice is a B slice; learns the PPS bits. */ +static bool ave_au_is_b(const u8 *p, size_t len, bool hevc, u8 *extra_bits) +{ + for (size_t i = 0; i + 3 < len; i++) { + const u8 *nal; + size_t room; + u32 type; + + if (p[i] || p[i + 1] || p[i + 2] != 1) + continue; + nal = p + i + 3; + room = len - i - 3; + if (room < (hevc ? 3 : 2)) + break; + type = hevc ? (nal[0] >> 1) & 0x3f : nal[0] & 0x1f; + if (hevc && type == 34) { + int bits = ave_hevc_pps_extra_bits(nal, room); + + if (bits >= 0) + *extra_bits = bits; + } else if (hevc ? type <= 21 : type == 1 || type == 5) { + return ave_slice_is_b(nal, room, hevc, *extra_bits); + } + i += 2; + } + return false; +} + +/* + * Whether a coded access unit is a B picture. Key frames are scanned too: + * they carry the parameter sets, and the PPS's extra slice header bits are + * needed for every later B/P decision. + */ +bool ave_au_bframe(const u8 *p, size_t len, bool hevc, bool key, u8 *extra_bits) +{ + bool b = ave_au_is_b(p, len, hevc, extra_bits); + + return !key && b; +} + /* NAL unit types in an Annex B buffer: key frame, parameter sets, filler? */ static void ave_scan_nals(const u8 *p, size_t len, bool hevc, bool *key, bool *params, bool *filler) @@ -1300,6 +1458,7 @@ int ave_sess_output(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buff int at, ret; *keyframe = false; + s->bframe = false; if (!out) return -EFAULT; if (s->status) { @@ -1366,6 +1525,7 @@ int ave_sess_output(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buff if (!ave_starts_annexb(out, len)) ave_sess_dump(ctx, s, "not Annex B"); ave_scan_nals(out, len, hevc, keyframe, ¶ms, &filler); + s->bframe = ave_au_bframe(out, len, hevc, *keyframe, &sess->hevc_extra_bits); if (!ctx->dst_sequence && !params) ave_sess_dump(ctx, s, "first frame has no parameter sets"); len = ave_sess_cbr_fill(ctx, out, len, room, filler); diff --git a/drivers/media/platform/apple/ave/ave-v4l2.c b/drivers/media/platform/apple/ave/ave-v4l2.c index 1f2e933ed893a6..5d73737fe6624a 100644 --- a/drivers/media/platform/apple/ave/ave-v4l2.c +++ b/drivers/media/platform/apple/ave/ave-v4l2.c @@ -77,17 +77,20 @@ static bool ave_fmt_listed(const u32 *list, unsigned int n, u32 fourcc) return false; } -/* HEVC Main 10 (P010 input) is mapped for the 9003 layout only. */ +/* + * HEVC Main 10 (P010 input): the 9003 and the counted (26A428) layouts, + * whose Starts map every field that changes with bit depth. The 6070 + * layout has none. + */ static bool ave_main10_supported(const struct ave_dev *ave) { - return ave->layout && ave->layout->kind == AVE_LAYOUT_9003 && - !ave->layout->counted; + return ave->layout && (ave->layout->counted || + ave->layout->kind == AVE_LAYOUT_9003); } /* * Whether raw @fourcc can be encoded to @coded on @ave. P010 is only the - * input of HEVC Main 10: H.264 has no 10-bit profile here, and the 6070 - * and 26A428 layouts have no Main 10 fields. + * input of HEVC Main 10: H.264 has no 10-bit profile here. */ static bool ave_raw_fmt_ok(const struct ave_dev *ave, u32 coded, u32 fourcc) { @@ -1152,7 +1155,8 @@ static bool ave_deliver(struct ave_ctx *ctx) v4l2_m2m_buf_copy_metadata(s->src, dst); dst->flags &= ~(V4L2_BUF_FLAG_KEYFRAME | V4L2_BUF_FLAG_PFRAME | V4L2_BUF_FLAG_BFRAME | V4L2_BUF_FLAG_LAST); - dst->flags |= key ? V4L2_BUF_FLAG_KEYFRAME : V4L2_BUF_FLAG_PFRAME; + dst->flags |= key ? V4L2_BUF_FLAG_KEYFRAME : + s->bframe ? V4L2_BUF_FLAG_BFRAME : V4L2_BUF_FLAG_PFRAME; dst->sequence = ctx->dst_sequence++; sess->done_head = (sess->done_head + 1) % AVE_MAX_SLOTS; diff --git a/drivers/media/platform/apple/ave/ave-writer-test.c b/drivers/media/platform/apple/ave/ave-writer-test.c new file mode 100644 index 00000000000000..1228eba62da1a3 --- /dev/null +++ b/drivers/media/platform/apple/ave/ave-writer-test.c @@ -0,0 +1,438 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the checks the 6070 Start and Process builders make on + * session parameters and buffers before they write a command: counts that + * index the session arrays, every surface the firmware is told about, and + * the codec state copied into Process. + * + * Copyright The Aurora Silicon Contributors + */ +#include +#include +#include +#include +#include + +#include "ave.h" +#include "ave-layout.h" + +#define T_FILL 0xa5 + +struct t_wr { + struct ave_dev *ave; + struct ave_ctx *ctx; + struct ave_session *sess; + struct ave_fw_layout *fw; + u8 *start, *process; + size_t start_len, process_len; +}; + +/* Synthetic, 16 KiB aligned DMA addresses, one window per buffer. */ +static void t_buf(struct ave_buf *b, unsigned int *index) +{ + b->dma = 0x820000000ULL + (u64)(*index) * 0x2000000; + b->size = SZ_16K * (1 + (*index)++); +} + +static void t_wr_init(struct kunit *test, struct t_wr *t, enum ave_codec codec) +{ + struct ave_session *sess; + struct ave_params *p; + unsigned int index = 0; + + t->ave = kunit_kzalloc(test, sizeof(*t->ave), GFP_KERNEL); + t->ctx = kunit_kzalloc(test, sizeof(*t->ctx), GFP_KERNEL); + t->sess = kunit_kzalloc(test, sizeof(*t->sess), GFP_KERNEL); + t->fw = kunit_kmalloc(test, sizeof(*t->fw), GFP_KERNEL); + KUNIT_ASSERT_TRUE(test, t->ave && t->ctx && t->sess && t->fw); + *t->fw = ave_layout_6070_11_1; + t->fw->encode_ready = true; + t->ave->layout = t->fw; + t->ctx->ave = t->ave; + t->ctx->sess = t->sess; + sess = t->sess; + p = &sess->p; + + *p = (struct ave_params){ + .codec = codec, + .width = 1920, + .height = 1080, + .cw = 1920, + .ch = ALIGN(1080, 16), + .stride = ALIGN(1920, 64), + .fps_num = 30, + .fps_den = 1, + .fps_int = 30, + .bframes = true, + .slots = 5, + .refs = 5, + .gop = 30, + .rc_mode = 3, + .bitrate = 4000000, + .initial_qp = 33, + .min_qp = 0, + .max_qp = 48, + .profile = codec == AVE_CODEC_H264 ? 4 : 1, + .level = codec == AVE_CODEC_H264 ? 13 : 7, + .bit_depth = 8, + }; + p->mbs = p->cw / 16 * (p->ch / 16); + p->coded_cap = ALIGN(3 * p->cw * p->ch, SZ_16K); + sess->token = 400; + sess->client = 10; + t_buf(&sess->hdr, &index); + t_buf(&sess->client_mem, &index); + sess->client_mem.size = AVE_6070_CLIENT_MEM_BYTES; + t_buf(&sess->param_sets, &index); + for (unsigned int i = 0; i < AVE_MAX_REFS; i++) { + t_buf(&sess->ref_a[i], &index); + t_buf(&sess->ref_b[i], &index); + t_buf(&sess->ref_c[i], &index); + t_buf(&sess->ref_d[i], &index); + } + t_buf(&sess->mb, &index); + for (unsigned int set = 0; set < AVE_NEIGHBOUR_SETS; set++) { + t_buf(&sess->row_a[set], &index); + t_buf(&sess->row_b[set], &index); + t_buf(&sess->fixed[set], &index); + t_buf(&sess->neighbour_fw[set], &index); + } + for (unsigned int set = 0; set < AVE_ENTROPY_SETS; set++) + for (unsigned int i = 0; i < AVE_TILE_BUFS; i++) { + t_buf(&sess->tile[set][i], &index); + t_buf(&sess->tile_aux[set][i], &index); + } + for (unsigned int i = 0; i < 2; i++) { + t_buf(&sess->hevc_extra[i], &index); + t_buf(&sess->hevc_transcoded[i], &index); + } + sess->hevc_transcoded[1].size = sess->hevc_transcoded[0].size; + for (unsigned int i = 0; i < AVE_MAX_SLOTS; i++) { + t_buf(&sess->slot[i].coded, &index); + t_buf(&sess->slot[i].meta, &index); + t_buf(&sess->slot[i].aux, &index); + } + sess->codec_state_bytes = t->fw->codec_state_bytes[codec - 1]; + sess->codec_state = kunit_kzalloc(test, sess->codec_state_bytes, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sess->codec_state); + KUNIT_ASSERT_EQ(test, ave_init_codec_state(sess), 0); + + t->start_len = t->fw->bytes[codec - 1][AVE_IMAGE_START]; + t->process_len = t->fw->bytes[codec - 1][AVE_IMAGE_PROCESS]; + t->start = kunit_kmalloc(test, t->start_len + 1, GFP_KERNEL); + t->process = kunit_kmalloc(test, t->process_len + 1, GFP_KERNEL); + KUNIT_ASSERT_TRUE(test, t->start && t->process); +} + +/* Build Start into a filled buffer; a refusal must leave it untouched. */ +static int t_start(struct kunit *test, struct t_wr *t) +{ + int ret; + + memset(t->start, T_FILL, t->start_len + 1); + ret = ave_build_start(t->ctx, t->start, t->start_len); + if (ret) + KUNIT_EXPECT_NULL(test, memchr_inv(t->start, T_FILL, t->start_len)); + KUNIT_EXPECT_EQ(test, t->start[t->start_len], T_FILL); + return ret; +} + +static int t_process(struct kunit *test, struct t_wr *t, unsigned int slot, + dma_addr_t input) +{ + memset(t->process, T_FILL, t->process_len + 1); + return ave_build_process(t->ctx, t->process, t->process_len, slot, input, + t->sess->p.bitrate, false, false); +} + +#define T_INPUT 0x8f0000000ULL + +/* Counts that index the session's arrays are bounded before any is read. */ +static void ave_writer_test_start_counts(struct kunit *test) +{ + struct ave_params *p; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_H264); + p = &t.sess->p; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + + p->refs = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->refs = AVE_MAX_REFS + 1; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->refs = U32_MAX; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->refs = AVE_MAX_REFS; + p->slots = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->slots = t.fw->max_slots + 1; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->slots = U32_MAX; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->slots = t.fw->max_slots; + KUNIT_EXPECT_EQ(test, t_start(test, &t), 0); + + /* A command buffer of any other size. */ + memset(t.start, T_FILL, t.start_len + 1); + KUNIT_EXPECT_EQ(test, ave_build_start(t.ctx, t.start, t.start_len - 4), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_build_start(t.ctx, t.start, t.start_len + 1), -EINVAL); + KUNIT_EXPECT_NULL(test, memchr_inv(t.start, T_FILL, t.start_len + 1)); + /* A layout that cannot encode builds nothing. */ + t.fw->encode_ready = false; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EOPNOTSUPP); +} + +/* + * Each buffer the firmware gets must be mapped and 16 KiB aligned. Flip + * the alignment of one at a time: the last one of each array counts too. + */ +static void ave_writer_test_start_buffers(struct kunit *test) +{ + struct ave_session *s; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_H264); + s = t.sess; +#define T_BAD(field) \ + do { \ + dma_addr_t keep = (field).dma; \ + (field).dma = keep + SZ_4K; \ + KUNIT_EXPECT_EQ_MSG(test, t_start(test, &t), -EINVAL, \ + "misaligned " #field); \ + (field).dma = 0; \ + KUNIT_EXPECT_EQ_MSG(test, t_start(test, &t), -EINVAL, \ + "unmapped " #field); \ + (field).dma = keep; \ + } while (0) + T_BAD(s->hdr); + T_BAD(s->client_mem); + T_BAD(s->param_sets); + T_BAD(s->ref_a[0]); + T_BAD(s->ref_a[AVE_MAX_REFS - 1]); + T_BAD(s->ref_b[AVE_MAX_REFS - 1]); + T_BAD(s->ref_c[AVE_MAX_REFS - 1]); + T_BAD(s->ref_d[AVE_6070_LOWRES_RESULTS - 1]); + T_BAD(s->slot[0].coded); + T_BAD(s->slot[4].coded); + T_BAD(s->slot[4].meta); + T_BAD(s->row_a[AVE_NEIGHBOUR_SETS - 1]); + T_BAD(s->row_b[AVE_NEIGHBOUR_SETS - 1]); + T_BAD(s->fixed[AVE_NEIGHBOUR_SETS - 1]); + T_BAD(s->neighbour_fw[AVE_NEIGHBOUR_SETS - 1]); + T_BAD(s->tile[AVE_ENTROPY_SETS - 1][AVE_6070_AVC_ENTROPY_TILES - 1]); + T_BAD(s->tile_aux[AVE_ENTROPY_SETS - 1][AVE_6070_AVC_ENTROPY_TILES - 1]); +#undef T_BAD + KUNIT_EXPECT_EQ(test, t_start(test, &t), 0); + + /* The client memory has the size the firmware expects, no other. */ + s->client_mem.size = AVE_6070_CLIENT_MEM_BYTES - SZ_16K; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->client_mem.size = AVE_6070_CLIENT_MEM_BYTES; + s->param_sets.size = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->param_sets.size = SZ_16K; + + /* Buffers this session does not use are not looked at. */ + s->slot[5].coded.dma = 0; + s->tile[0][AVE_6070_AVC_ENTROPY_TILES].dma = 1; + s->hevc_extra[1].dma = 1; + s->hevc_transcoded[0].dma = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), 0); +} + +/* HEVC uses four entropy tiles and the transcode buffers too. */ +static void ave_writer_test_start_buffers_hevc(struct kunit *test) +{ + struct ave_session *s; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_HEVC); + s = t.sess; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + s->tile[AVE_ENTROPY_SETS - 1][3].dma += SZ_4K; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->tile[AVE_ENTROPY_SETS - 1][3].dma -= SZ_4K; + s->tile_aux[0][3].dma = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->tile_aux[0][3].dma = 0x8e0000000ULL; + s->hevc_extra[1].dma += SZ_4K; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->hevc_extra[1].dma -= SZ_4K; + s->hevc_transcoded[1].dma = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->hevc_transcoded[1].dma = 0x8e0004000ULL; + /* The fifth tile is not used. */ + s->tile[0][4].dma = 1; + KUNIT_EXPECT_EQ(test, t_start(test, &t), 0); +} + +/* general_level_idc is 30 times the level (H.265 A.4); other levels are 0. */ +static void ave_writer_test_hevc_level_idc(struct kunit *test) +{ + static const u32 idc[] = { 0, 30, 60, 63, 90, 93, 120, 123, 150, 153, 0 }; + const struct ave_start_layout *l; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_HEVC); + l = &t.fw->start[AVE_CODEC_HEVC - 1]; + KUNIT_ASSERT_NE(test, l->hevc_level_a, 0U); + KUNIT_ASSERT_NE(test, l->hevc_level_b, 0U); + KUNIT_ASSERT_LE(test, l->hevc_level_a + 4, (u32)t.start_len); + KUNIT_ASSERT_LE(test, l->hevc_level_b + 4, (u32)t.start_len); + for (unsigned int level = 0; level < ARRAY_SIZE(idc); level++) { + t.sess->p.level = level; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(t.start + l->hevc_level_a), + idc[level], "level %u", level); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(t.start + l->hevc_level_b), + idc[level], "level %u", level); + } + t.sess->p.level = U32_MAX; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(t.start + l->hevc_level_a), 0U); +} + +/* H.264 level_idc (Table A-1) for every level the controls can select. */ +static void ave_writer_test_h264_level_idc(struct kunit *test) +{ + static const u32 idc[] = { + 10, 9, 11, 12, 13, 20, 21, 22, 30, 31, 32, 40, 41, 42, 50, 51, 52, + }; + const struct ave_start_layout *l; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_H264); + l = &t.fw->start[AVE_CODEC_H264 - 1]; + KUNIT_ASSERT_NE(test, l->h264_level, 0U); + for (unsigned int i = 0; i < ARRAY_SIZE(idc); i++) { + t.sess->p.level = i + 1; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(t.start + l->h264_level), + idc[i], "level %u", i + 1); + } +} + +/* Process: the slot, the input and the slot's buffers are checked first. */ +static void ave_writer_test_process_refusal(struct kunit *test) +{ + struct ave_session *s; + struct ave_params *p; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_H264); + s = t.sess; + p = &s->p; + KUNIT_ASSERT_EQ(test, t_process(test, &t, 0, T_INPUT), 0); + KUNIT_EXPECT_EQ(test, t.process[t.process_len], T_FILL); + KUNIT_ASSERT_EQ(test, t_process(test, &t, p->slots - 1, T_INPUT), 0); + +#define T_REFUSED(expr) \ + do { \ + KUNIT_EXPECT_EQ_MSG(test, (expr), -EINVAL, #expr); \ + KUNIT_EXPECT_NULL_MSG(test, \ + memchr_inv(t.process, T_FILL, t.process_len + 1), \ + #expr " wrote the command"); \ + } while (0) + T_REFUSED(t_process(test, &t, p->slots, T_INPUT)); + T_REFUSED(t_process(test, &t, AVE_MAX_SLOTS, T_INPUT)); + T_REFUSED(t_process(test, &t, U32_MAX, T_INPUT)); + T_REFUSED(t_process(test, &t, 0, T_INPUT + SZ_4K)); + T_REFUSED(t_process(test, &t, 0, T_INPUT + 1)); + p->slots = t.fw->max_slots + 1; + T_REFUSED(t_process(test, &t, 0, T_INPUT)); + p->slots = 5; + s->slot[2].coded.dma += SZ_4K; + T_REFUSED(t_process(test, &t, 2, T_INPUT)); + s->slot[2].coded.dma -= SZ_4K; + s->slot[2].meta.dma = 0; + T_REFUSED(t_process(test, &t, 2, T_INPUT)); + s->slot[2].meta.dma = 0x8e0000000ULL; + s->slot[2].aux.dma += 4; + T_REFUSED(t_process(test, &t, 2, T_INPUT)); + s->slot[2].aux.dma -= 4; + /* No codec state to copy into the command. */ + s->codec_state = NULL; + T_REFUSED(t_process(test, &t, 2, T_INPUT)); +#undef T_REFUSED + memset(t.process, T_FILL, t.process_len + 1); + KUNIT_EXPECT_EQ(test, + ave_build_process(t.ctx, t.process, t.process_len - 4, 0, + T_INPUT, p->bitrate, false, false), + -EINVAL); + KUNIT_EXPECT_NULL(test, memchr_inv(t.process, T_FILL, t.process_len + 1)); +} + +/* The codec state copied into Process may not be read past its end. */ +static void ave_writer_test_process_state_bounds(struct kunit *test) +{ + const enum ave_codec codecs[] = { AVE_CODEC_H264, AVE_CODEC_HEVC }; + + for (unsigned int c = 0; c < ARRAY_SIZE(codecs); c++) { + struct ave_session *s; + struct t_wr t; + size_t full; + + t_wr_init(test, &t, codecs[c]); + s = t.sess; + full = s->codec_state_bytes; + KUNIT_ASSERT_EQ(test, t_process(test, &t, 0, T_INPUT), 0); + /* The same state in a buffer one byte short. */ + s->codec_state_bytes = full - 1; + s->codec_state = kunit_kzalloc(test, full - 1, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, s->codec_state); + KUNIT_EXPECT_EQ(test, t_process(test, &t, 0, T_INPUT), -EINVAL); + s->codec_state_bytes = 1; + KUNIT_EXPECT_EQ(test, t_process(test, &t, 0, T_INPUT), -EINVAL); + s->codec_state_bytes = 0; + KUNIT_EXPECT_EQ(test, t_process(test, &t, 0, T_INPUT), -EINVAL); + } +} + +/* The codec state is only set up at the size this firmware uses. */ +static void ave_writer_test_codec_state(struct kunit *test) +{ + struct ave_session *s; + struct t_wr t; + u8 *state; + + t_wr_init(test, &t, AVE_CODEC_H264); + s = t.sess; + state = s->codec_state; + s->codec_state = NULL; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), -EINVAL); + s->codec_state = state; + s->codec_state_bytes = t.fw->codec_state_bytes[0] - 4; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), -EINVAL); + /* An H.264 state where HEVC is set up, and the other way round. */ + s->codec_state_bytes = t.fw->codec_state_bytes[0]; + s->p.codec = AVE_CODEC_HEVC; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), -EINVAL); + s->p.codec = 0; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), -EINVAL); + s->p.codec = AVE_CODEC_H264; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(state), (u32)s->codec_state_bytes); +} + +static struct kunit_case ave_writer_test_cases[] = { + KUNIT_CASE(ave_writer_test_start_counts), + KUNIT_CASE(ave_writer_test_start_buffers), + KUNIT_CASE(ave_writer_test_start_buffers_hevc), + KUNIT_CASE(ave_writer_test_hevc_level_idc), + KUNIT_CASE(ave_writer_test_h264_level_idc), + KUNIT_CASE(ave_writer_test_process_refusal), + KUNIT_CASE(ave_writer_test_process_state_bounds), + KUNIT_CASE(ave_writer_test_codec_state), + {} +}; + +static struct kunit_suite ave_writer_test_suite = { + .name = "apple-ave-writer", + .test_cases = ave_writer_test_cases, +}; + +kunit_test_suite(ave_writer_test_suite); + +MODULE_DESCRIPTION("KUnit tests for Apple AVE command builder input checks"); +MODULE_LICENSE("GPL"); diff --git a/drivers/media/platform/apple/ave/ave-writer.c b/drivers/media/platform/apple/ave/ave-writer.c index 8dbc0192a778a7..fe621ab833e001 100644 --- a/drivers/media/platform/apple/ave/ave-writer.c +++ b/drivers/media/platform/apple/ave/ave-writer.c @@ -783,6 +783,8 @@ static void ave_start_config(const struct ave_params *p, u8 *cmd, } else { ave_start_put32(cmd, l->fps.numerator, p->fps_int); } + /* A second copy of the integer rate: macOS 27.2.1 writes 60 at 60 fps (M5). */ + ave_start_put32(cmd, l->fps_int_copy, p->fps_int); /* Rate control */ /* diff --git a/drivers/media/platform/apple/ave/ave.h b/drivers/media/platform/apple/ave/ave.h index e86c3735086610..331c8663813993 100644 --- a/drivers/media/platform/apple/ave/ave.h +++ b/drivers/media/platform/apple/ave/ave.h @@ -54,6 +54,8 @@ struct ave_mctf_layout; #define AVE_IPC_BYTES (20 * SZ_1M) #define AVE_IPC_CHANNEL_OFF 0x4000 #define AVE_IPC_HANDSHAKE_OFF 0x24000 +/* Most channel descriptors any firmware publishes (the 6070 one: 7). */ +#define AVE_IPC_MAX_CHANNELS 8 #define AVE_IPC_SHARED_OFF 0x28000 #define AVE_IPC_SHARED_BYTES SZ_64K #define AVE_IPC_CMD_OFF 0x40000 @@ -182,6 +184,11 @@ enum ave_opcode { #define AVE_FW_TEXT_CRC_T8132_26B123 0x99fc929a /* The M3 (T8122) build preloaded by the macOS 27.2 (26B123) stub. */ #define AVE_FW_TEXT_CRC_T8122_26B123 0x918d70d3 +/* + * The M2 (T8112) build preloaded by the macOS 27.2 (26B123) stub, with the + * per-boot word at TEXT 0x4224 zeroed. + */ +#define AVE_FW_TEXT_CRC_T8112_26B123 0x077a3444 /* * The M5 build of macOS 27.2 (26B123; 27.2.1 26B131 ships it unchanged), * AppleAVE2FW 9013.55.1: TEXT 0x154000, DATA 0x12c000, as 26A428's. @@ -206,15 +213,20 @@ struct ave_fw_build { const char *name; u32 text_size; u32 data_size; + /* 0: any build in the known list */ u32 text_crc; + /* + * TEXT offset of a 32-bit word this build's loader sets differently on + * every boot; a TEXT CRC that is not a known build is retried with it + * zeroed. 0 when there is none, and the CRC must match as it is. + */ + u32 text_boot_word; }; struct ave_variant { const struct ave_coproc_regs *regs; u32 fw_text_size; u32 fw_data_size; - /* A second DATA size the variant accepts (the M4 Max build), or 0 */ - u32 fw_data_size_alt; /* * When set, the builds the variant admits. They replace fw_text_size, * fw_data_size and text_crc: the segment sizes select the build, and @@ -235,12 +247,6 @@ struct ave_variant { * address; it is zero in the firmware image. 0 when there is none. */ u32 text_link_cell; - /* - * TEXT offset of a 32-bit word the loader sets differently on every - * boot; a TEXT CRC that is not a known build is retried with it zeroed. - * 0 when there is none. - */ - u32 text_boot_word; /* * Mailbox offset of the SVE idle (clock gating) word that must read 0 * before the firmware starts, or 0 when the variant has none. @@ -248,6 +254,16 @@ struct ave_variant { u32 mbox_idle; /* Restore DATA from the boot snapshot before every start, the first included. */ bool restore_data_first; + /* + * The same encoder running another firmware build that a newer + * bootloader preloads, with a start and command protocol of its own. + * The firmware segment sizes the bootloader reserved select it. + * NULL when there is none. Use builds[] when the builds differ only + * in TEXT CRC, boot word (and command layout) but start the same way; + * use next_build when a build needs other start fields (boot device, + * handshake type, DATA handling) and has sizes of its own. + */ + const struct ave_variant *next_build; size_t extra0_size; /* Register sequence and boot/hello configuration have been qualified. */ @@ -424,6 +440,7 @@ struct ave_slot { u32 status; bool busy; /* Process sent, reply pending */ bool done; /* reply in, output not delivered yet */ + bool bframe; /* the delivered picture is a B picture (its slice type) */ }; struct ave_frame_result { @@ -451,6 +468,7 @@ struct ave_frame_result { struct ave_session { struct ave_session *failed_next; struct ave_params p; + u8 hevc_extra_bits; /* PPS num_extra_slice_header_bits, for the B flag */ struct ave_buf hdr; struct ave_buf client_mem; /* 6070: per-session firmware-generated VPS/SPS/PPS output. */ @@ -560,12 +578,15 @@ static inline struct ave_ctx *ave_file_to_ctx(struct file *file) return container_of(file_to_v4l2_fh(file), struct ave_ctx, fh); } -extern const struct ave_variant ave_t6000, ave_t6041, ave_t8112, ave_t8132, - ave_m3; +extern const struct ave_variant ave_t6000, ave_t6041, ave_t6050, ave_t8112, + ave_t8132, ave_m3; /* ave-fw.c */ u64 ave_fw_vcbar(const struct ave_variant *variant, u64 text_iova); int ave_fw_probe(struct ave_dev *ave); +bool ave_fw_sizes_match(const struct ave_variant *v, size_t text, size_t data); +const struct ave_variant *ave_fw_select_build(const struct ave_variant *v, + size_t text, size_t data); int ave_fw_text_id_crc(const void *text, size_t size, u32 cell_off, u64 data_iova, u32 *crc); int ave_fw_text_boot_crc(const void *text, size_t size, u32 word_off, @@ -623,6 +644,7 @@ int ave_build_process(struct ave_ctx *ctx, u8 *cmd, size_t len, unsigned int slot, dma_addr_t input, u32 bitrate, bool force_key, bool last); int ave_init_codec_state(struct ave_session *sess); +bool ave_au_bframe(const u8 *p, size_t len, bool hevc, bool key, u8 *extra_bits); /* ave-cmd.c */ int ave_cmd_config(struct ave_dev *ave); diff --git a/drivers/media/platform/apple/ave/tests/README b/drivers/media/platform/apple/ave/tests/README index c084c14ff414f2..9d0ba50c2373c1 100644 --- a/drivers/media/platform/apple/ave/tests/README +++ b/drivers/media/platform/apple/ave/tests/README @@ -58,6 +58,31 @@ expiry boundaries, with staggered attempts and across jiffies wrap. Run with ../.kunitconfig using tools/testing/kunit/kunit.py. The existing tools/asahi/ave-pm-tests.py also checks the #651 sleep rollback contract. +OUTPUT input address +-------------------- + +Run python3 run-input.py for ASan/UBSan checks of the production +ave_sess_input(). The fake DMA boundary makes each DART address the host +address of the memory behind it, and the test reads the picture there as the +encoder does (p->ch luma lines, then p->ch / 2 chroma lines after p->height +luma lines). It sweeps every 64-byte data_offset vb2 accepts, for MMAP and +imported buffers, and checks that each accepted address has the whole read +inside the OUTPUT buffer or the slot's bounce copy, that a whole picture +after a non-zero data_offset is still used in place, and that tightly packed +lines are moved to the encoder's stride unchanged. + +Channel descriptor checks +------------------------- + +Run python3 run-ipc.py for ASan/UBSan checks of the production channel parser +(ave_ipc_parse_channels with the 6070 transport). ipc-boundary.h routes every +read of the channel area through a fake firmware that rewrites a descriptor +field (ring size, ring address or name) right after the host has read it, and +can assert that no descriptor byte is fetched twice. Each case must parse the +rings a well-behaved firmware publishes and hand over exactly the validated +host-to-firmware slots; the rest of the IPC window must stay untouched. +An argument (slots, addr, name or once) runs a single case. + MCTF streaming tool ------------------- diff --git a/drivers/media/platform/apple/ave/tests/input-boundary.h b/drivers/media/platform/apple/ave/tests/input-boundary.h new file mode 100644 index 00000000000000..b4a62754b88469 --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/input-boundary.h @@ -0,0 +1,72 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* + * vb2 and DMA boundary for the production ave_sess_input(). A DMA address + * is the host address of the memory behind it, so the simulated encoder + * read below touches exactly what the hardware would and AddressSanitizer + * reports a read past the buffer. + */ +#define PAGE_SIZE 4096UL +#define PAGE_ALIGN(x) ALIGN((size_t)(x), PAGE_SIZE) +#define min(x, y) ((x) < (y) ? (x) : (y)) +#define SZ_16K_ALIGNED 0x4000UL + +#define VB2_MAX_PLANES 8 + +enum vb2_memory { VB2_MEMORY_MMAP = 1, VB2_MEMORY_DMABUF = 4 }; + +struct vb2_plane { + void *mem; + unsigned int bytesused, length, data_offset; +}; + +struct vb2_buffer { + enum vb2_memory memory; + struct vb2_plane planes[VB2_MAX_PLANES]; +}; + +struct vb2_v4l2_buffer { struct vb2_buffer vb2_buf; }; +struct ave_vb2_mem; + +static unsigned long vb2_get_plane_payload(struct vb2_buffer *vb, unsigned int p) +{ + return vb->planes[p].bytesused; +} + +static unsigned long vb2_plane_size(struct vb2_buffer *vb, unsigned int p) +{ + return vb->planes[p].length; +} + +static void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int p) +{ + return vb->planes[p].mem; +} + +static dma_addr_t vb2_dma_contig_plane_dma_addr(struct vb2_buffer *vb, unsigned int p) +{ + return (uintptr_t)vb->planes[p].mem; +} + +struct device { int unused; }; + +static unsigned int dma_allocs; + +static void *dma_alloc_attrs(struct device *dev, size_t size, dma_addr_t *dma, int gfp, + unsigned long attrs) +{ + void *p = NULL; + + assert(!posix_memalign(&p, SZ_16K_ALIGNED, size)); + memset(p, 0, size); + *dma = (uintptr_t)p; + dma_allocs++; + return p; +} + +static void dma_free_attrs(struct device *dev, size_t size, void *cpu, dma_addr_t dma, + unsigned long attrs) +{ + assert((uintptr_t)cpu == dma); + free(cpu); + dma_allocs--; +} diff --git a/drivers/media/platform/apple/ave/tests/input-session.h b/drivers/media/platform/apple/ave/tests/input-session.h new file mode 100644 index 00000000000000..f5f53b0a7b3291 --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/input-session.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Only the session state ave_sess_input() reads. */ +struct ave_session { + struct ave_params p; + struct ave_slot slot[1]; + bool copy_noted; +}; + +struct ave_dev { struct device *dev; }; +struct ave_ctx { struct ave_dev *ave; struct ave_session *sess; }; diff --git a/drivers/media/platform/apple/ave/tests/input-test.c b/drivers/media/platform/apple/ave/tests/input-test.c new file mode 100644 index 00000000000000..43aca7c1428e51 --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/input-test.c @@ -0,0 +1,233 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * ave_sess_input() hands the encoder one DART address per frame. The + * encoder reads p->ch luma lines from it and p->ch / 2 chroma lines from + * p->height lines further on (ave_build_process()). Every accepted address + * must have all of that inside the OUTPUT buffer or the slot's bounce copy, + * for any data_offset and payload vb2 lets through + * (data_offset < bytesused <= length). + */ +static struct device dev; +static struct ave_dev ave = { .dev = &dev }; +static struct ave_session sess; +static struct ave_ctx ctx = { .ave = &ave, .sess = &sess }; +/* Not static: the simulated encoder reads must not be optimised away. */ +u8 sink; + +static void geometry(u32 width, u32 height) +{ + memset(&sess, 0, sizeof(sess)); + sess.p.width = width; + sess.p.height = height; + sess.p.cw = ALIGN(width, 16); + sess.p.ch = ALIGN(height, 16); + sess.p.stride = ALIGN(width, 64); + sess.p.sample_bytes = 1; +} + +static size_t sizeimage(void) +{ + return (size_t)sess.p.stride * sess.p.ch * 3 / 2; +} + +static size_t encoder_extent(void) +{ + const struct ave_params *p = &sess.p; + + return max((size_t)p->stride * p->ch, + (size_t)p->stride * (p->height + p->ch / 2)); +} + +static bool inside(dma_addr_t a, size_t n, const void *base, size_t len) +{ + uintptr_t b = (uintptr_t)base; + + return base && a >= b && a - b <= len && n <= len - (a - b); +} + +/* What the encoder does with the address: read the whole picture. */ +static void encoder_read(dma_addr_t input) +{ + const struct ave_params *p = &sess.p; + const u8 *y = (const u8 *)(uintptr_t)input; + const u8 *uv = y + (size_t)p->stride * p->height; + u8 sum = 0; + + for (size_t i = 0; i < (size_t)p->stride * p->ch; i++) + sum += y[i]; + for (size_t i = 0; i < (size_t)p->stride * (p->ch / 2); i++) + sum += uv[i]; + sink = sum; +} + +static struct vb2_v4l2_buffer *buffer(enum vb2_memory memory, size_t length) +{ + struct vb2_v4l2_buffer *b = calloc(1, sizeof(*b)); + + assert(b); + b->vb2_buf.memory = memory; + b->vb2_buf.planes[0].length = length; + /* Exactly @length bytes, so AddressSanitizer sees a read past the end. */ + assert(!posix_memalign(&b->vb2_buf.planes[0].mem, SZ_16K_ALIGNED, length)); + memset(b->vb2_buf.planes[0].mem, 0x5a, length); + return b; +} + +static void put(struct vb2_v4l2_buffer *b) +{ + free(b->vb2_buf.planes[0].mem); + free(b); +} + +static void release_bounce(void) +{ + ave_free(&ave, &sess.slot[0].bounce); +} + +/* + * Feed one buffer through the production code; if it is accepted, check + * the address and read the picture there as the encoder would. + */ +static int submit(struct vb2_v4l2_buffer *b, unsigned int off, unsigned int used) +{ + struct vb2_plane *pl = &b->vb2_buf.planes[0]; + const struct ave_buf *bounce = &sess.slot[0].bounce; + dma_addr_t input = 0; + int ret; + + assert(off < used && used <= pl->length); + pl->data_offset = off; + pl->bytesused = used; + ret = ave_sess_input(&ctx, 0, b, &input); + if (ret) + return ret; + if (!inside(input, encoder_extent(), pl->mem, pl->length) && + !inside(input, encoder_extent(), bounce->cpu, bounce->size)) { + fprintf(stderr, + "FAIL: data_offset %u payload %u (%s, %u byte buffer): encoder input %#llx reads %zu bytes outside the buffer\n", + off, used, b->vb2_buf.memory == VB2_MEMORY_MMAP ? "MMAP" : "DMABUF", + pl->length, (unsigned long long)input, encoder_extent()); + exit(1); + } + if (!IS_ALIGNED(input, 64)) { + fprintf(stderr, + "FAIL: data_offset %u payload %u (%s, %u byte buffer): encoder input %#llx is not 64-byte aligned\n", + off, used, b->vb2_buf.memory == VB2_MEMORY_MMAP ? "MMAP" : "DMABUF", + pl->length, (unsigned long long)input); + exit(1); + } + encoder_read(input); + return 0; +} + +/* Every 64-byte data_offset vb2 accepts, for both payload extremes. */ +static void sweep(enum vb2_memory memory, size_t length) +{ + struct vb2_v4l2_buffer *b = buffer(memory, length); + unsigned int accepted = 0, refused = 0; + + for (unsigned int k = 0; k < 2; k++) { + unsigned int used = k ? length : sizeimage(); + + for (unsigned int off = 0; off < used; off += 64) { + if (submit(b, off, used)) + refused++; + else + accepted++; + release_bounce(); + } + } + /* Offset 0 with the S_FMT payload always works. */ + assert(accepted); + assert(refused); + put(b); +} + +/* A whole picture after a non-zero data_offset still goes straight in. */ +static void offset_with_room(enum vb2_memory memory) +{ + unsigned int off = 4 * SZ_16K_ALIGNED; + struct vb2_v4l2_buffer *b = buffer(memory, off + sizeimage()); + dma_addr_t input; + + b->vb2_buf.planes[0].data_offset = off; + b->vb2_buf.planes[0].bytesused = off + sizeimage(); + assert(!ave_sess_input(&ctx, 0, b, &input)); + assert(input == (uintptr_t)b->vb2_buf.planes[0].mem + off); + assert(!sess.slot[0].bounce.cpu); + put(b); +} + +/* Tightly packed lines are moved to the encoder's stride, unchanged. */ +static void packed(enum vb2_memory memory, unsigned int off, bool in_place) +{ + const struct ave_params *p = &sess.p; + u32 rows = p->height + DIV_ROUND_UP(p->height, 2), line = p->width; + struct vb2_v4l2_buffer *b = buffer(memory, sizeimage()); + u8 *from = (u8 *)b->vb2_buf.planes[0].mem + off; + const u8 *to; + + for (u32 y = 0; y < rows; y++) + for (u32 x = 0; x < line; x++) + from[y * line + x] = (u8)(y * 7 + x); + assert(!submit(b, off, off + rows * line)); + to = in_place ? from : sess.slot[0].bounce.cpu; + assert(to && (bool)sess.slot[0].bounce.cpu == !in_place); + for (u32 y = 0; y < rows; y++) + for (u32 x = 0; x < line; x++) + assert(to[(size_t)y * p->stride + x] == (u8)(y * 7 + x)); + release_bounce(); + put(b); +} + +/* + * Packed lines at every byte data_offset of a buffer with room to spare: + * each picture is accepted at an aligned address (submit() checks) and + * its lines arrive there unchanged, in place or in the copy. + */ +static void packed_any_offset(enum vb2_memory memory) +{ + const struct ave_params *p = &sess.p; + u32 rows = p->height + DIV_ROUND_UP(p->height, 2), line = p->width; + struct vb2_v4l2_buffer *b = buffer(memory, sizeimage() + 2 * 64); + + for (unsigned int off = 0; off < 2 * 64; off++) { + u8 *from = (u8 *)b->vb2_buf.planes[0].mem + off; + const u8 *to; + + for (u32 y = 0; y < rows; y++) + for (u32 x = 0; x < line; x++) + from[y * line + x] = (u8)(y * 7 + x + off); + assert(!submit(b, off, off + rows * line)); + to = sess.slot[0].bounce.cpu ? sess.slot[0].bounce.cpu : from; + for (u32 y = 0; y < rows; y++) + for (u32 x = 0; x < line; x++) + assert(to[(size_t)y * p->stride + x] == (u8)(y * 7 + x + off)); + release_bounce(); + } + put(b); +} + +int main(void) +{ + static const u32 sizes[][2] = { { 128, 64 }, { 100, 60 }, { 320, 180 } }; + + for (unsigned int i = 0; i < ARRAY_SIZE(sizes); i++) { + geometry(sizes[i][0], sizes[i][1]); + sweep(VB2_MEMORY_MMAP, sizeimage()); + sweep(VB2_MEMORY_DMABUF, sizeimage()); + sweep(VB2_MEMORY_MMAP, sizeimage() + 3 * 64); + offset_with_room(VB2_MEMORY_MMAP); + offset_with_room(VB2_MEMORY_DMABUF); + } + geometry(100, 60); + packed(VB2_MEMORY_MMAP, 0, true); + packed(VB2_MEMORY_MMAP, 64, false); + packed(VB2_MEMORY_DMABUF, 0, false); + packed(VB2_MEMORY_DMABUF, 128, false); + packed_any_offset(VB2_MEMORY_MMAP); + packed_any_offset(VB2_MEMORY_DMABUF); + assert(!dma_allocs && jiffies); + puts("ok: OUTPUT data_offset sweep (MMAP, DMABUF), offset with room, packed repack at any offset"); + return 0; +} diff --git a/drivers/media/platform/apple/ave/tests/ipc-boundary.h b/drivers/media/platform/apple/ave/tests/ipc-boundary.h new file mode 100644 index 00000000000000..c5b1b1c18eb948 --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/ipc-boundary.h @@ -0,0 +1,134 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* + * Fake device and shared-memory boundary for the production channel parser. + * Every read the parser makes is routed through fw_read(), which plays a + * firmware that rewrites a descriptor field as soon as the host has read it. + */ +typedef u64 __le64; +#define cpu_to_le64(x) ((u64)(x)) +#define dma_wmb() ((void)0) +#ifndef AVE_IPC_MAX_CHANNELS +#define AVE_IPC_MAX_CHANNELS 8 +#endif + +struct ave_dev { + const struct ave_fw_layout *layout; + struct ave_buf ipc; + u64 ipc_fw_base; + u32 channel_bytes; + struct ave_ring ring[AVE_RINGS]; +}; + +enum { + FW_SLOTS = BIT(0), /* grow the ring past the IPC window */ + FW_ADDR = BIT(1), /* move the ring to the start of the window */ + FW_NAME = BIT(2), /* rename the channel */ + FW_ONCE = BIT(3), /* assert no descriptor byte is fetched twice */ +}; + +static struct ave_dev *fw_ave; +static unsigned int fw_mode, fw_descriptors; +static unsigned char fw_fetched[AVE_IPC_MAX_CHANNELS * AVE_CHAN_DESC_STRIDE]; + +static bool fw_overlaps(long a, size_t len, long b, size_t blen) +{ + return a < b + (long)blen && b < a + (long)len; +} + +static void fw_read(const void *p, size_t len) +{ + const u8 *table = (const u8 *)fw_ave->ipc.cpu + AVE_IPC_CHANNEL_OFF; + size_t bytes = fw_descriptors * AVE_CHAN_DESC_STRIDE; + size_t start; + + if ((const u8 *)p < table || (const u8 *)p >= table + bytes) + return; + start = (const u8 *)p - table; + assert(start + len <= bytes); + for (size_t b = start; b < start + len; b++) { + if (fw_mode & FW_ONCE) + assert(!fw_fetched[b]); + fw_fetched[b]++; + } + for (unsigned int i = start / AVE_CHAN_DESC_STRIDE; + i * AVE_CHAN_DESC_STRIDE < start + len; i++) { + long at = (long)start - (long)(i * AVE_CHAN_DESC_STRIDE); + u8 *desc = (u8 *)table + i * AVE_CHAN_DESC_STRIDE; + + if (fw_mode & FW_SLOTS && + fw_overlaps(at, len, AVE_CHAN_DESC_SLOTS, 4)) + put_unaligned_le32(0x100000, desc + AVE_CHAN_DESC_SLOTS); + if (fw_mode & FW_ADDR && + fw_overlaps(at, len, AVE_CHAN_DESC_ADDR, 8)) + put_unaligned_le64(fw_ave->ipc_fw_base, + desc + AVE_CHAN_DESC_ADDR); + if (fw_mode & FW_NAME && + fw_overlaps(at, len, 0, AVE_CHAN_DESC_NAME_LEN)) + (memcpy)(desc, "X", 2); + } +} + +static inline u32 fw_le32(const void *p) +{ + u32 v = get_unaligned_le32(p); + + fw_read(p, 4); + return v; +} + +static inline u64 fw_le64(const void *p) +{ + u64 v = get_unaligned_le64(p); + + fw_read(p, 8); + return v; +} + +static void *fw_memcpy(void *d, const void *s, size_t n) +{ + (memcpy)(d, s, n); + fw_read(s, n); + return d; +} + +static void *fw_memchr(const void *s, int c, size_t n) +{ + void *r = (memchr)(s, c, n); + + fw_read(s, r ? (size_t)((const u8 *)r - (const u8 *)s) + 1 : n); + return r; +} + +static int fw_strcmp(const char *a, const char *b) +{ + size_t n = 0; + int r; + + while (a[n] && a[n] == b[n]) + n++; + r = (unsigned char)a[n] - (unsigned char)b[n]; + fw_read(a, n + 1); + fw_read(b, n + 1); + return r; +} + +static long fw_strscpy(char *d, const char *s, size_t n) +{ + size_t len = strnlen(s, n); + + fw_read(s, len < n ? len + 1 : n); + if (len == n) { + (memcpy)(d, s, n - 1); + d[n - 1] = 0; + return -E2BIG; + } + (memcpy)(d, s, len + 1); + return len; +} + +#define get_unaligned_le32(p) fw_le32(p) +#define get_unaligned_le64(p) fw_le64(p) +#define memcpy(d, s, n) fw_memcpy(d, s, n) +#define memchr(s, c, n) fw_memchr(s, c, n) +#define strcmp(a, b) fw_strcmp(a, b) +#define strscpy(d, s, n) fw_strscpy(d, s, n) diff --git a/drivers/media/platform/apple/ave/tests/ipc-test.c b/drivers/media/platform/apple/ave/tests/ipc-test.c new file mode 100644 index 00000000000000..38f16061ad155b --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/ipc-test.c @@ -0,0 +1,151 @@ +// SPDX-License-Identifier: GPL-2.0-only +#undef get_unaligned_le32 +#undef get_unaligned_le64 +#undef memcpy +#undef memchr +#undef strcmp +#undef strscpy + +/* The channels the 6070 firmware publishes (as in the KUnit suite). */ +static const struct { + const char *name; + u32 dir, doorbell, slots, offset; +} channels[] = { + { "TERMINAL", 2, 0, 512, 0x700 }, { "IO", 0, 1, 32, 0x8700 }, + { "DEBUG", 0, 1, 8, 0x8f00 }, { "BUF_H2T", 0, 2, 1, 0x9100 }, + { "BUF_T2H", 1, 3, 1, 0x9140 }, { "SHAREDMALLOC", 1, 3, 8, 0x9180 }, + { "IO_T2H", 1, 3, 32, 0x9380 }, +}; + +static const struct ave_fw_abi abi = { .transport = &ave_transport_6070 }; +static const struct ave_fw_layout layout = { .abi = &abi }; +static struct ave_dev ave; +static u8 *expect; + +static void setup(unsigned int mode) +{ + fw_ave = &ave; + fw_mode = mode; + fw_descriptors = ARRAY_SIZE(channels); + memset(fw_fetched, 0, sizeof(fw_fetched)); + free(ave.ipc.cpu); + memset(&ave, 0, sizeof(ave)); + ave.layout = &layout; + ave.ipc.size = ave_transport_6070.ipc_bytes; + /* Exactly the window: ASan reports any write past its end. */ + ave.ipc.cpu = malloc(ave.ipc.size); + assert(ave.ipc.cpu); + memset(ave.ipc.cpu, 0x5a, ave.ipc.size); + ave.ipc_fw_base = 0x100000000ULL; + ave.channel_bytes = ave_transport_6070.hello[1]; + for (unsigned int i = 0; i < ARRAY_SIZE(channels); i++) { + u8 *desc = (u8 *)ave.ipc.cpu + AVE_IPC_CHANNEL_OFF + + i * AVE_CHAN_DESC_STRIDE; + + memset(desc, 0, AVE_CHAN_DESC_STRIDE); + memcpy(desc, channels[i].name, strlen(channels[i].name) + 1); + put_unaligned_le32(channels[i].dir, desc + AVE_CHAN_DESC_DIR); + put_unaligned_le32(channels[i].doorbell, desc + AVE_CHAN_DESC_IRQ); + put_unaligned_le32(channels[i].slots, desc + AVE_CHAN_DESC_SLOTS); + put_unaligned_le64(ave.ipc_fw_base + AVE_IPC_CHANNEL_OFF + + channels[i].offset, desc + AVE_CHAN_DESC_ADDR); + } +} + +static void check_ring(unsigned int id, const char *name, u32 mode, + u32 doorbell, u32 slots, u32 offset) +{ + const struct ave_ring *r = &ave.ring[id]; + + assert(!strcmp(r->name, name)); + assert(r->mode == mode && r->doorbell == doorbell); + assert(r->slots == slots && r->offset == AVE_IPC_CHANNEL_OFF + offset); + assert(r->consumer == (mode ? -1 : 0) && r->producer == (mode ? 0 : -1)); +} + +static void check_result(void) +{ + size_t table = AVE_IPC_CHANNEL_OFF; + size_t table_end = table + ARRAY_SIZE(channels) * AVE_CHAN_DESC_STRIDE; + const u8 *ipc = ave.ipc.cpu; + + check_ring(AVE_RING_IO, "IO", 1, 1, 32, 0x8700); + check_ring(AVE_RING_T2H, "IO_T2H", 0, 3, 32, 0x9380); + check_ring(AVE_RING_SMALLOC, "SHAREDMALLOC", 0, 3, 8, 0x9180); + check_ring(AVE_RING_LOG, "TERMINAL", 0, 0, 512, 0x700); + /* + * Outside the descriptors (the firmware's to change) the window holds + * exactly the hand-over of the validated host-to-firmware rings. + */ + for (size_t b = 0; b < ave.ipc.size; b++) { + if (b >= table && b < table_end) + continue; + if (ipc[b] != expect[b]) { + fprintf(stderr, "FAIL: byte %#zx is %#x, want %#x\n", b, + ipc[b], expect[b]); + abort(); + } + } +} + +static void well_behaved(void) +{ + setup(0); + expect = malloc(ave.ipc.size); + assert(expect); + memcpy(expect, ave.ipc.cpu, ave.ipc.size); + for (unsigned int i = 0; i < ARRAY_SIZE(channels); i++) { + if (channels[i].dir) + continue; + for (unsigned int n = 0; n < channels[i].slots; n++) { + u8 *slot = expect + AVE_IPC_CHANNEL_OFF + + channels[i].offset + n * AVE_RING_SLOT_BYTES; + + put_unaligned_le64(1, slot); + put_unaligned_le64(0, slot + 8); + put_unaligned_le64(0, slot + 16); + } + } + assert(ave_ipc_parse_channels(&ave) == 0); + check_result(); + /* Every descriptor field the parser depends on was read. */ + for (unsigned int i = 0; i < ARRAY_SIZE(channels); i++) + for (unsigned int b = AVE_CHAN_DESC_DIR; + b < AVE_CHAN_DESC_ADDR + 8; b++) + assert(fw_fetched[i * AVE_CHAN_DESC_STRIDE + b]); +} + +/* The firmware rewrites a field right after the host has read it. */ +static const struct { + const char *name, *what; + unsigned int mode; +} cases[] = { + { "slots", "ring size changed after its check", FW_SLOTS }, + { "addr", "ring address changed after its check", FW_ADDR }, + { "name", "channel name changed after its check", FW_NAME }, + { "once", "descriptor bytes fetched more than once", FW_ONCE }, +}; + +int main(int argc, char **argv) +{ + well_behaved(); + for (unsigned int c = 0; c < ARRAY_SIZE(cases); c++) { + int ret; + + if (argc > 1 && strcmp(argv[1], cases[c].name)) + continue; + setup(cases[c].mode); + ret = ave_ipc_parse_channels(&ave); + if (ret) { + fprintf(stderr, "FAIL: %s: parse returned %d\n", + cases[c].what, ret); + abort(); + } + check_result(); + printf("ok: %s\n", cases[c].what); + } + free(ave.ipc.cpu); + free(expect); + puts("ok: channel descriptors read once, hand-over only to validated rings"); + return 0; +} diff --git a/drivers/media/platform/apple/ave/tests/run-input.py b/drivers/media/platform/apple/ave/tests/run-input.py new file mode 100644 index 00000000000000..61db7ff3425cf9 --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/run-input.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Check the production OUTPUT picture address against the buffer behind it.""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +# python3 -I leaves the script directory off sys.path; run.py sits next to this file. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from run import declaration, function, source + + +def main(): + here = Path(__file__).resolve().parent + src = here.parent + header = (src / 'ave.h').read_text() + code = (here / 'shim.h').read_text() + code += (here / 'input-boundary.h').read_text() + for name in ('ave_codec', 'ave_buf', 'ave_params', 'ave_slot'): + code += declaration(header, name) + code += (here / 'input-session.h').read_text() + code += function((src / 'ave-fw.c').read_text(), 'ave_free') + code += function((src / 'ave-fw.c').read_text(), 'ave_alloc_padded') + code += function((src / 'ave-fw.c').read_text(), 'ave_alloc') + sess = (src / 'ave-sess.c').read_text() + code += function(sess, 'ave_note_copy') + code += function(sess, 'ave_sess_input') + code += (here / 'input-test.c').read_text() + with tempfile.TemporaryDirectory(prefix='ave-input-') as tmp: + path = Path(tmp) + (path / 'test.c').write_text(code) + subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu11', '-O1', '-g', + '-Wall', '-Wextra', '-Werror', '-Wno-unused-parameter', + '-Wno-unused-function', '-fsanitize=address,undefined', + '-fno-omit-frame-pointer', str(path / 'test.c'), + '-o', str(path / 'test')], check=True) + subprocess.run([str(path / 'test')], check=True) + + +if __name__ == '__main__': + main() diff --git a/drivers/media/platform/apple/ave/tests/run-ipc.py b/drivers/media/platform/apple/ave/tests/run-ipc.py new file mode 100644 index 00000000000000..9600890c05f7fe --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/run-ipc.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the production AVE channel parser against a firmware that rewrites +the channel descriptors while the host reads them. + +An optional argument (slots, addr, name or once) runs only that case after +the well-behaved one. +""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +# python3 -I leaves the script directory off sys.path; run.py sits next to this file. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from run import declaration, function, source + + +def block(text, start): + begin = text.index(start) + return text[begin:text.index('\n};', begin) + 3] + '\n' + + +def main(): + here = Path(__file__).resolve().parent + src = here.parent + header = (src / 'ave.h').read_text() + code = (here / 'shim.h').read_text() + code += source((src / 'ave-regs.h').read_text()) + for name in ('AVE_IPC_CHANNEL_OFF', 'AVE_IPC_MAX_CHANNELS'): + match = re.search(r'^#define ' + name + r'\s+[^\n]+', header, re.M) + if match: + code += match[0] + '\n' + code += block(header, 'enum {\n\tAVE_RING_IO,') + for name in ('ave_codec', 'ave_buf', 'ave_ring', 'ave_image', 'ave_opcode'): + code += declaration(header, name) + code += source((src / 'ave-layout.h').read_text()) + code += (here / 'ipc-boundary.h').read_text() + code += block((src / 'ave-abi.c').read_text(), + 'static const struct ave_fw_transport ave_transport_6070 =') + text = (src / 'ave-ipc.c').read_text() + code += block(text, 'static const struct {\n\tconst char *name;\n\tu32 dir;') + for name in ('ave_fw_offset', 'ave_ring_id', 'ave_rings_overlap', + 'ave_ipc_parse_channels'): + code += function(text, name) + code += (here / 'ipc-test.c').read_text() + with tempfile.TemporaryDirectory(prefix='ave-ipc-') as tmp: + path = Path(tmp) + (path / 'test.c').write_text(code) + subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu11', '-O1', '-g', + '-Wall', '-Wextra', '-Werror', '-Wno-unused-parameter', + '-Wno-unused-function', '-Wno-unused-variable', + '-Wno-pointer-sign', + '-Wno-sign-compare', '-fsanitize=address,undefined', + '-fno-sanitize-recover=all', + '-fno-omit-frame-pointer', str(path / 'test.c'), + '-o', str(path / 'test')], check=True) + subprocess.run([str(path / 'test')] + sys.argv[1:], check=True) + + +if __name__ == '__main__': + main() diff --git a/drivers/media/platform/apple/ave/tests/shim.h b/drivers/media/platform/apple/ave/tests/shim.h index f0a723c4894135..389ca5a4305087 100644 --- a/drivers/media/platform/apple/ave/tests/shim.h +++ b/drivers/media/platform/apple/ave/tests/shim.h @@ -74,6 +74,7 @@ static inline void sort(void *p, size_t n, size_t size, } #define dev_err(...) test_log(__VA_ARGS__) +#define dev_err_ratelimited(...) test_log(__VA_ARGS__) #define dev_info(...) test_log(__VA_ARGS__) #define dev_dbg(...) test_log(__VA_ARGS__) #define dev_warn(...) test_log(__VA_ARGS__) diff --git a/drivers/media/platform/apple/isp/isp-drv-test.c b/drivers/media/platform/apple/isp/isp-drv-test.c index 7ec962b8100341..ff4398ea654d60 100644 --- a/drivers/media/platform/apple/isp/isp-drv-test.c +++ b/drivers/media/platform/apple/isp/isp-drv-test.c @@ -220,9 +220,11 @@ static void isp_test_sensor_sysfs(struct kunit *test) { struct device *dev = kunit_device_register(test, "apple-isp-sensor-test"); struct apple_isp *isp; - char buf[32]; + /* sysfs_emit() wants the page-aligned buffer sysfs hands to show(). */ + char *buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + KUNIT_ASSERT_NOT_NULL(test, buf); KUNIT_EXPECT_EQ(test, sensor_show(dev, &dev_attr_sensor, buf), -ENODATA); isp = kunit_kzalloc(test, sizeof(*isp), GFP_KERNEL); diff --git a/drivers/media/platform/apple/isp/isp-drv.h b/drivers/media/platform/apple/isp/isp-drv.h index 411041d8e82fc1..b3dccaf9a75089 100644 --- a/drivers/media/platform/apple/isp/isp-drv.h +++ b/drivers/media/platform/apple/isp/isp-drv.h @@ -101,13 +101,16 @@ struct isp_surf { struct isp_message { u64 arg0; - u64 arg1; - u64 arg2; - u64 arg3; - u64 arg4; - u64 arg5; - u64 arg6; - u64 arg7; + /* Written before arg0, which marks the message valid. */ + struct_group(payload, + u64 arg1; + u64 arg2; + u64 arg3; + u64 arg4; + u64 arg5; + u64 arg6; + u64 arg7; + ); } __packed; static_assert(sizeof(struct isp_message) == ISP_IPC_MESSAGE_SIZE); diff --git a/drivers/media/platform/apple/isp/isp-ipc.c b/drivers/media/platform/apple/isp/isp-ipc.c index 77ef0016a34de8..922e990010487b 100644 --- a/drivers/media/platform/apple/isp/isp-ipc.c +++ b/drivers/media/platform/apple/isp/isp-ipc.c @@ -97,7 +97,7 @@ static inline void chan_write_msg_index(struct apple_isp *isp, struct isp_message *msg, u32 index) { u64 *p0 = chan_msg_virt(chan, index); - memcpy(p0 + 1, &msg->arg1, sizeof(*msg) - 8); + memcpy(p0 + 1, &msg->payload, sizeof(msg->payload)); /* Make sure we write arg0 last, since that indicates message validity. */ diff --git a/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c b/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c index 2a1b2b636241e9..c2e4468e88aa4e 100644 --- a/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c +++ b/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c @@ -2,7 +2,8 @@ /* * Apple Silicon JPEG encoder, V4L2 memory-to-memory. * - * Takes full-range YUV in one buffer (NV12 for 4:2:0, NV16 for 4:2:2) and + * Takes full-range YUV in one buffer (NV12 for 4:2:0, NV16 for 4:2:2; NV24 + * for 4:4:4 and GREY where the engine's job layout has them) and * produces baseline JPEG with the standard Huffman tables. One job runs at * a time; the engine is reset before each job and the completion interrupt * ends it. Register layout: see apple-jpeg-hw.h. @@ -54,6 +55,7 @@ struct apple_jpeg { struct apple_jpeg_ctx *active; bool broken; u32 status, int_status, bytes; + unsigned long deadline; /* when the active job times out, in jiffies */ struct delayed_work watchdog; struct apple_jpeg_write writes[APPLE_JPEG_MAX_WRITES]; }; @@ -214,7 +216,11 @@ static void aj_watchdog(struct work_struct *work) spin_lock_irqsave(&jpeg->hw_lock, flags); ctx = jpeg->active; - jpeg->active = NULL; + /* An expiry from an earlier job that was already running: not this job's. */ + if (ctx && time_before(jiffies, jpeg->deadline)) + ctx = NULL; + else + jpeg->active = NULL; if (ctx) { aj_write(jpeg, AJ_MAIN_RUN, 0); aj_write(jpeg, AJ_IRQ_MASK, 0); @@ -227,6 +233,21 @@ static void aj_watchdog(struct work_struct *work) } } +/* The raw formats, in apple_jpeg_subsampling order. */ +static const u32 aj_raw_fmts[] = { + V4L2_PIX_FMT_NV12, V4L2_PIX_FMT_NV16, V4L2_PIX_FMT_NV24, V4L2_PIX_FMT_GREY, +}; + +/* The subsampling of a raw format this engine takes; 4:2:0 for any other. */ +static enum apple_jpeg_subsampling aj_subsampling(const struct apple_jpeg *jpeg, u32 fourcc) +{ + for (unsigned int s = 0; s < ARRAY_SIZE(aj_raw_fmts); s++) + if (aj_raw_fmts[s] == fourcc && + apple_jpeg_has_subsampling(jpeg->variant->layout, s)) + return s; + return AJ_SUBSAMPLING_420; +} + static void aj_device_run(void *priv) { struct apple_jpeg_ctx *ctx = priv; @@ -235,8 +256,8 @@ static void aj_device_run(void *priv) struct apple_jpeg_layout layout; struct apple_jpeg_job job; unsigned long flags; + enum apple_jpeg_subsampling ss; dma_addr_t y; - bool is422; int n, ret; src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); @@ -249,16 +270,17 @@ static void aj_device_run(void *priv) } y = vb2_dma_contig_plane_dma_addr(&src->vb2_buf, 0); - is422 = ctx->src.pixelformat == V4L2_PIX_FMT_NV16; - apple_jpeg_raw_layout(ctx->src.width, ctx->src.height, is422, &layout); + ss = aj_subsampling(jpeg, ctx->src.pixelformat); + apple_jpeg_raw_layout(ctx->src.width, ctx->src.height, ss, &layout); job = (struct apple_jpeg_job){ .width = ctx->src.width, .height = ctx->src.height, - .is422 = is422, + .subsampling = ss, .luma_stride = layout.bytesperline, - .chroma_stride = layout.bytesperline, + .chroma_stride = layout.chroma_stride, .luma = y, - .chroma = y + layout.chroma_offset, + /* GREY has no chroma plane: point plane 1 at the luma. */ + .chroma = ss == AJ_SUBSAMPLING_GREY ? y : y + layout.chroma_offset, /* The engine's single input bound: the end of the negotiated surface. */ .input_end = y + layout.sizeimage - 1, .output = vb2_dma_contig_plane_dma_addr(&dst->vb2_buf, 0), @@ -284,12 +306,19 @@ static void aj_device_run(void *priv) return; } jpeg->active = ctx; + /* + * Arm the watchdog before the start command, so that the completion + * cannot precede it, and give this job its full timeout even if an + * earlier job's expiry is still pending. + */ + jpeg->deadline = jiffies + msecs_to_jiffies(AJ_JOB_TIMEOUT_MS); + mod_delayed_work(system_percpu_wq, &jpeg->watchdog, + msecs_to_jiffies(AJ_JOB_TIMEOUT_MS)); /* Buffers must be visible before the start command, the last write. */ dma_wmb(); for (int i = 0; i < n; i++) writel(jpeg->writes[i].value, jpeg->regs + jpeg->writes[i].offset); spin_unlock_irqrestore(&jpeg->hw_lock, flags); - schedule_delayed_work(&jpeg->watchdog, msecs_to_jiffies(AJ_JOB_TIMEOUT_MS)); } static const struct v4l2_m2m_ops aj_m2m_ops = { @@ -298,17 +327,43 @@ static const struct v4l2_m2m_ops aj_m2m_ops = { /* ---- formats ---------------------------------------------------------- */ -/* Raw input: Y rows then interleaved CbCr rows in one buffer, full range. */ +/* + * The engine encodes the samples as they arrive: it converts neither range + * nor matrix, so the colorimetry of the raw input is the client's to state, + * as for any stateful encoder, and CAPTURE reports the same. A client that + * gives none gets what JPEG itself carries, full-range BT.601. Refusing + * every other description makes clients fail: GStreamer's v4l2jpegenc + * passes the camera's colorimetry through and gives up when S_FMT returns + * another one. + */ +static void aj_fill_colorimetry(struct v4l2_pix_format_mplane *pix) +{ + if (pix->colorspace == V4L2_COLORSPACE_DEFAULT || + pix->colorspace > V4L2_COLORSPACE_DCI_P3) { + pix->colorspace = V4L2_COLORSPACE_SRGB; + pix->ycbcr_enc = V4L2_YCBCR_ENC_601; + pix->quantization = V4L2_QUANTIZATION_FULL_RANGE; + pix->xfer_func = V4L2_XFER_FUNC_SRGB; + return; + } + if (pix->ycbcr_enc > V4L2_YCBCR_ENC_SMPTE240M) + pix->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT; + if (pix->quantization > V4L2_QUANTIZATION_LIM_RANGE) + pix->quantization = V4L2_QUANTIZATION_DEFAULT; + if (pix->xfer_func > V4L2_XFER_FUNC_SMPTE2084) + pix->xfer_func = V4L2_XFER_FUNC_DEFAULT; +} + +/* Raw input: Y rows then interleaved CbCr rows in one buffer. */ static void aj_fill_raw(const struct apple_jpeg *jpeg, struct v4l2_pix_format_mplane *pix) { - bool is422 = pix->pixelformat == V4L2_PIX_FMT_NV16 && - apple_jpeg_has_422(jpeg->variant->layout); + enum apple_jpeg_subsampling ss = aj_subsampling(jpeg, pix->pixelformat); u32 w = clamp_t(u32, ALIGN(pix->width, 2), AJ_MIN_SIZE, AJ_MAX_SIZE); u32 h = clamp_t(u32, pix->height, AJ_MIN_SIZE, AJ_MAX_SIZE); struct apple_jpeg_layout layout; - apple_jpeg_raw_layout(w, h, is422, &layout); - pix->pixelformat = is422 ? V4L2_PIX_FMT_NV16 : V4L2_PIX_FMT_NV12; + apple_jpeg_raw_layout(w, h, ss, &layout); + pix->pixelformat = aj_raw_fmts[ss]; pix->width = w; pix->height = h; pix->field = V4L2_FIELD_NONE; @@ -319,11 +374,7 @@ static void aj_fill_raw(const struct apple_jpeg *jpeg, struct v4l2_pix_format_mp /* Chroma follows the visible luma rows; the tail covers the MCU rows. */ pix->plane_fmt[0].bytesperline = layout.bytesperline; pix->plane_fmt[0].sizeimage = layout.sizeimage; - /* JPEG carries full-range BT.601; the engine does no range conversion. */ - pix->colorspace = V4L2_COLORSPACE_SRGB; - pix->ycbcr_enc = V4L2_YCBCR_ENC_601; - pix->quantization = V4L2_QUANTIZATION_FULL_RANGE; - pix->xfer_func = V4L2_XFER_FUNC_SRGB; + aj_fill_colorimetry(pix); } /* @@ -350,13 +401,18 @@ static int aj_querycap(struct file *file, void *priv, struct v4l2_capability *ca static int aj_enum_fmt_out(struct file *file, void *priv, struct v4l2_fmtdesc *f) { - static const u32 fmts[] = { V4L2_PIX_FMT_NV12, V4L2_PIX_FMT_NV16 }; const struct apple_jpeg *jpeg = aj_file_to_ctx(file)->jpeg; - - if (f->index >= (apple_jpeg_has_422(jpeg->variant->layout) ? ARRAY_SIZE(fmts) : 1)) - return -EINVAL; - f->pixelformat = fmts[f->index]; - return 0; + unsigned int n = 0; + + for (unsigned int s = 0; s < ARRAY_SIZE(aj_raw_fmts); s++) { + if (!apple_jpeg_has_subsampling(jpeg->variant->layout, s)) + continue; + if (n++ == f->index) { + f->pixelformat = aj_raw_fmts[s]; + return 0; + } + } + return -EINVAL; } static int aj_enum_fmt_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f) @@ -371,11 +427,10 @@ static int aj_enum_fmt_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f static int aj_enum_framesizes(struct file *file, void *priv, struct v4l2_frmsizeenum *fs) { const struct apple_jpeg *jpeg = aj_file_to_ctx(file)->jpeg; - bool nv16 = apple_jpeg_has_422(jpeg->variant->layout); + bool raw = aj_subsampling(jpeg, fs->pixel_format) != AJ_SUBSAMPLING_420 || + fs->pixel_format == V4L2_PIX_FMT_NV12; - if (fs->index || (fs->pixel_format != V4L2_PIX_FMT_JPEG && - fs->pixel_format != V4L2_PIX_FMT_NV12 && - (fs->pixel_format != V4L2_PIX_FMT_NV16 || !nv16))) + if (fs->index || (fs->pixel_format != V4L2_PIX_FMT_JPEG && !raw)) return -EINVAL; fs->type = V4L2_FRMSIZE_TYPE_STEPWISE; fs->stepwise = (struct v4l2_frmsize_stepwise){ diff --git a/drivers/media/platform/apple/jpeg/apple-jpeg-hw.c b/drivers/media/platform/apple/jpeg/apple-jpeg-hw.c index 4746b480449c6c..0c0f85d323f3a8 100644 --- a/drivers/media/platform/apple/jpeg/apple-jpeg-hw.c +++ b/drivers/media/platform/apple/jpeg/apple-jpeg-hw.c @@ -649,10 +649,62 @@ int apple_jpeg_defaults(const struct apple_jpeg_reg_layout *layout, bool encode, EXPORT_SYMBOL_IF_KUNIT(apple_jpeg_defaults); /* - * The T6050 sequence, in AppleJPEGDriver's order (per the macOS register - * trace). Unlike the earlier revisions it has no plane size or pipe limit - * registers, takes 16-bit quantisation tables and two-bit Huffman table - * selectors, and needs 0x08c, 0x334 and IO flag bit 7. Only 4:2:0 is known. + * T6050 per-subsampling programming. The engine reads the input in MCUs: + * each plane's tile is its share of one MCU, in 8-byte columns and rows + * (plane 1 holds interleaved CbCr, so a 4:4:4 chroma tile is twice as wide + * as the luma one). The IO flags take the JPEG's own subsampling code, + * which sets the frame header's sampling factors. + * + * Every entry was checked on the J815 (T8142): the engine's JPEG decodes + * with the expected sampling factors at 640x480, 642x482, 1366x766 and + * 1920x1080, 42.8-47.5 dB PSNR against the source frame. + */ +struct aj_t6050_mode { + u8 codec; + u8 px_mode; + u8 io; + u8 mcu_w, mcu_h; + u8 tile0_w, tile0_h; + u8 tile1_w, tile1_h; /* 0: no plane 1 */ + u8 enc_ctrl; +}; + +static const struct aj_t6050_mode aj_t6050_modes[] = { + [AJ_SUBSAMPLING_420] = { + .codec = AJ_CODEC_420, .px_mode = AJ_CODEC_420, .io = AJ_IO_FLAGS_420, + .mcu_w = 16, .mcu_h = 16, .tile0_w = 2, .tile0_h = 16, .tile1_w = 2, .tile1_h = 8, + .enc_ctrl = AJ_T6050_ENC_CTRL_ENCODE, + }, + [AJ_SUBSAMPLING_422] = { + .codec = AJ_CODEC_422, .px_mode = AJ_CODEC_422, .io = AJ_IO_FLAGS_422, + .mcu_w = 16, .mcu_h = 8, .tile0_w = 2, .tile0_h = 8, .tile1_w = 2, .tile1_h = 8, + .enc_ctrl = AJ_T6050_ENC_CTRL_ENCODE, + }, + [AJ_SUBSAMPLING_444] = { + .codec = AJ_CODEC_444, .px_mode = AJ_CODEC_444, .io = AJ_IO_FLAGS_444, + .mcu_w = 8, .mcu_h = 8, .tile0_w = 1, .tile0_h = 8, .tile1_w = 2, .tile1_h = 8, + .enc_ctrl = AJ_T6050_ENC_CTRL_ENCODE, + }, + [AJ_SUBSAMPLING_GREY] = { + .codec = AJ_CODEC_GREY, .px_mode = AJ_CODEC_GREY, .io = AJ_IO_FLAGS_GREY, + .mcu_w = 8, .mcu_h = 8, .tile0_w = 1, .tile0_h = 8, + .enc_ctrl = AJ_T6050_ENC_CTRL_ENCODE, + }, +}; + +bool apple_jpeg_has_subsampling(const struct apple_jpeg_reg_layout *layout, + enum apple_jpeg_subsampling s) +{ + if (!layout->t6050_job) + return s <= AJ_SUBSAMPLING_422; + return s < ARRAY_SIZE(aj_t6050_modes); +} +EXPORT_SYMBOL_IF_KUNIT(apple_jpeg_has_subsampling); + +/* + * The T6050 job. Unlike the earlier revisions it has no plane size or pipe + * limit registers, takes 16-bit quantisation tables and two-bit Huffman + * table selectors, and needs 0x08c, 0x334 and IO flag bit 7. */ static int aj_build_t6050(struct aj_list *l, const struct apple_jpeg_reg_layout *layout, const struct apple_jpeg_job *job, u64 output_end) @@ -669,10 +721,12 @@ static int aj_build_t6050(struct aj_list *l, const struct apple_jpeg_reg_layout job->luma, job->chroma, job->input_end, job->output, job->output, output_end, }; u32 width = job->width, height = job->height; + const struct aj_t6050_mode *m; u8 q[2][64]; - if (job->is422) - return -EOPNOTSUPP; + if (job->subsampling >= ARRAY_SIZE(aj_t6050_modes)) + return -EINVAL; + m = &aj_t6050_modes[job->subsampling]; aj_put(l, AJ_MODE, AJ_MODE_SETUP); aj_put(l, AJ_MAIN_RUN, 0); @@ -682,19 +736,21 @@ static int aj_build_t6050(struct aj_list *l, const struct apple_jpeg_reg_layout aj_put(l, AJ_ENCODE_ENABLE, 1); aj_put(l, AJ_CODEC_MODE, 1); aj_put(l, AJ_DECODE_ENABLE, 0); - aj_put(l, AJ_CODEC, AJ_CODEC_420); + aj_put(l, AJ_CODEC, m->codec); aj_put(l, layout->image_width, width); aj_put(l, layout->image_height, height); - aj_put(l, AJ_T6050_PX_MODE, AJ_CODEC_420); - aj_put(l, AJ_PX_USE_PLANE1, 1); + aj_put(l, AJ_T6050_PX_MODE, m->px_mode); + aj_put(l, AJ_PX_USE_PLANE1, !!m->tile1_w); aj_put(l, layout->timeout, apple_jpeg_timeout(width, height)); - aj_put(l, AJ_PX_MCUS_W, DIV_ROUND_UP(width, 16)); - aj_put(l, AJ_PX_MCUS_H, DIV_ROUND_UP(height, 16)); - aj_put(l, AJ_PX_PLANE0_TILE_H, 2); - aj_put(l, AJ_PX_PLANE0_TILE_V, 16); - aj_put(l, AJ_PX_PLANE1_TILE_H, 2); - aj_put(l, AJ_PX_PLANE1_TILE_V, 8); - aj_put(l, AJ_T6050_ENC_CTRL, AJ_T6050_ENC_CTRL_ENCODE); + aj_put(l, AJ_PX_MCUS_W, DIV_ROUND_UP(width, m->mcu_w)); + aj_put(l, AJ_PX_MCUS_H, DIV_ROUND_UP(height, m->mcu_h)); + aj_put(l, AJ_PX_PLANE0_TILE_H, m->tile0_w); + aj_put(l, AJ_PX_PLANE0_TILE_V, m->tile0_h); + if (m->tile1_w) { + aj_put(l, AJ_PX_PLANE1_TILE_H, m->tile1_w); + aj_put(l, AJ_PX_PLANE1_TILE_V, m->tile1_h); + } + aj_put(l, AJ_T6050_ENC_CTRL, m->enc_ctrl); /* Two planes, Y then interleaved Cb, Cr. */ aj_put(l, layout->encode_format, AJ_PIXEL_FORMAT_YUV_PLANES); @@ -714,7 +770,7 @@ static int aj_build_t6050(struct aj_list *l, const struct apple_jpeg_reg_layout aj_put(l, AJ_T6050_PRE_ENCODE, 0); aj_put(l, AJ_MODE, AJ_MODE_ENCODE); - aj_put(l, AJ_JPEG_IO_FLAGS, AJ_IO_FLAGS_T6050 | AJ_IO_FLAGS_ORDER | AJ_IO_FLAGS_420); + aj_put(l, AJ_JPEG_IO_FLAGS, AJ_IO_FLAGS_T6050 | AJ_IO_FLAGS_ORDER | m->io); aj_put(l, AJ_JPEG_WIDTH, width); aj_put(l, AJ_JPEG_HEIGHT, height); aj_put(l, AJ_RST_INTERVAL, job->restart_interval); @@ -733,16 +789,19 @@ static int aj_build_t6050(struct aj_list *l, const struct apple_jpeg_reg_layout } /* - * Every register write of one baseline encode of two-plane (NV12 or NV16) - * full-range input, in order, ending with the start command. + * Every register write of one baseline encode of full-range input (NV12 or + * NV16; with the T6050 job layout also NV24 and GREY), in order, ending with + * the start command. */ int apple_jpeg_build_job(const struct apple_jpeg_reg_layout *layout, const struct apple_jpeg_job *job, struct apple_jpeg_write *w, unsigned int max) { u32 width = job->width, height = job->height; - u32 mcu_h = job->is422 ? 8 : 16; - u32 crows = job->is422 ? height : DIV_ROUND_UP(height, 2); + bool is422 = job->subsampling == AJ_SUBSAMPLING_422; + u32 mcu_h = apple_jpeg_mcu_rows(job->subsampling); + u32 crows = is422 ? height : DIV_ROUND_UP(height, 2); + u32 min_cstride; struct aj_list l = { .w = w, .max = max }; u8 luma[64], chroma[64]; u64 output_end, addr_mask = DMA_BIT_MASK(layout->dma_addr_bits); @@ -750,7 +809,21 @@ int apple_jpeg_build_job(const struct apple_jpeg_reg_layout *layout, if (!width || !height || width > U16_MAX || height > U16_MAX) return -EINVAL; - if (job->luma_stride < width || job->chroma_stride < ALIGN(width, 2)) + if (!apple_jpeg_has_subsampling(layout, job->subsampling) || + job->subsampling > AJ_SUBSAMPLING_GREY) + return -EOPNOTSUPP; + switch (job->subsampling) { + case AJ_SUBSAMPLING_444: + min_cstride = 2 * width; + break; + case AJ_SUBSAMPLING_GREY: + min_cstride = 0; + break; + default: + min_cstride = ALIGN(width, 2); + break; + } + if (job->luma_stride < width || job->chroma_stride < min_cstride) return -EINVAL; if ((job->luma | job->chroma) & 3 || job->output & 31 || !job->output_size) return -EINVAL; @@ -779,7 +852,7 @@ int apple_jpeg_build_job(const struct apple_jpeg_reg_layout *layout, aj_put(&l, AJ_ENCODE_ENABLE, 1); aj_put(&l, AJ_CODEC_MODE, 1); aj_put(&l, AJ_DECODE_ENABLE, 0); - aj_put(&l, AJ_CODEC, job->is422 ? AJ_CODEC_422 : AJ_CODEC_420); + aj_put(&l, AJ_CODEC, is422 ? AJ_CODEC_422 : AJ_CODEC_420); aj_put(&l, AJ_PX_USE_PLANE1, 1); aj_put(&l, AJ_PX_MCUS_W, DIV_ROUND_UP(width, 16)); @@ -804,8 +877,8 @@ int apple_jpeg_build_job(const struct apple_jpeg_reg_layout *layout, aj_put_addr(&l, layout, layout->output_start0, job->output); aj_put_addr(&l, layout, layout->output_start1, job->output); aj_put_addr(&l, layout, layout->output_end, output_end); - aj_put(&l, layout->pipe_limit0, job->is422 ? 8 : 3); - aj_put(&l, layout->pipe_limit1, job->is422 ? 2 : 1); + aj_put(&l, layout->pipe_limit0, is422 ? 8 : 3); + aj_put(&l, layout->pipe_limit1, is422 ? 2 : 1); /* Two planes, Y then interleaved Cb, Cr; no colour conversion. */ aj_put(&l, layout->encode_format, AJ_PIXEL_FORMAT_YUV_PLANES); @@ -821,7 +894,7 @@ int apple_jpeg_build_job(const struct apple_jpeg_reg_layout *layout, aj_put(&l, AJ_MODE, AJ_MODE_ENCODE); aj_put(&l, AJ_JPEG_IO_FLAGS, AJ_IO_FLAGS_ORDER | - (job->is422 ? AJ_IO_FLAGS_422 : AJ_IO_FLAGS_420)); + (is422 ? AJ_IO_FLAGS_422 : AJ_IO_FLAGS_420)); aj_put(&l, AJ_JPEG_WIDTH, width); aj_put(&l, AJ_JPEG_HEIGHT, height); aj_put(&l, AJ_RST_INTERVAL, job->restart_interval); diff --git a/drivers/media/platform/apple/jpeg/apple-jpeg-hw.h b/drivers/media/platform/apple/jpeg/apple-jpeg-hw.h index 429d25086d281e..8b83b309ad7cab 100644 --- a/drivers/media/platform/apple/jpeg/apple-jpeg-hw.h +++ b/drivers/media/platform/apple/jpeg/apple-jpeg-hw.h @@ -36,6 +36,8 @@ #define AJ_CODEC 0x028 #define AJ_CODEC_422 1 #define AJ_CODEC_420 3 +#define AJ_CODEC_444 0 +#define AJ_CODEC_GREY 4 #define AJ_CODEC_MODE 0x02c /* 1 encode */ #define AJ_DECODE_ENABLE 0x034 #define AJ_ENCODE_ENABLE 0x038 @@ -52,7 +54,7 @@ #define AJ_PX_PLANE1_TILE_H 0x080 #define AJ_PX_PLANE1_TILE_V 0x084 #define AJ_PX_PLANE1_STRIDE 0x088 -#define AJ_T6050_PX_MODE 0x08c /* T6050: the CODEC value for 4:2:0 */ +#define AJ_T6050_PX_MODE 0x08c /* T6050: the input's chroma layout */ #define AJ_PIXEL_FORMAT_YUV_PLANES 4 #define AJ_T6050_PRE_ENCODE 0x1dc /* T6050: cleared before MODE_ENCODE */ #define AJ_T6050_ENC_CTRL 0x334 @@ -61,6 +63,8 @@ #define AJ_IO_FLAGS_ORDER (BIT(4) | BIT(5)) #define AJ_IO_FLAGS_422 1 #define AJ_IO_FLAGS_420 2 +#define AJ_IO_FLAGS_444 0 +#define AJ_IO_FLAGS_GREY 3 #define AJ_IO_FLAGS_T6050 BIT(7) #define AJ_COMMAND 0x1004 #define AJ_QTBL_SEL 0x100c @@ -139,10 +143,21 @@ extern const struct apple_jpeg_variant apple_jpeg_t8112; extern const struct apple_jpeg_variant apple_jpeg_t8122; extern const struct apple_jpeg_variant apple_jpeg_t8140; -/* T6050's 4:2:2 job programming is not known yet. */ -static inline bool apple_jpeg_has_422(const struct apple_jpeg_reg_layout *layout) +/* Chroma subsampling of the raw input, which the JPEG keeps. */ +enum apple_jpeg_subsampling { + AJ_SUBSAMPLING_420, /* NV12 */ + AJ_SUBSAMPLING_422, /* NV16 */ + AJ_SUBSAMPLING_444, /* NV24, T6050 job layout only */ + AJ_SUBSAMPLING_GREY, /* GREY, T6050 job layout only */ +}; + +bool apple_jpeg_has_subsampling(const struct apple_jpeg_reg_layout *layout, + enum apple_jpeg_subsampling s); + +/* MCU height: 16 rows for 4:2:0, 8 for the others. */ +static inline u32 apple_jpeg_mcu_rows(enum apple_jpeg_subsampling s) { - return !layout->t6050_job; + return s == AJ_SUBSAMPLING_420 ? 16 : 8; } static inline bool @@ -156,7 +171,7 @@ apple_jpeg_hwrev_supported(const struct apple_jpeg_variant *variant, u32 hwrev) struct apple_jpeg_job { u32 width; u32 height; - bool is422; /* NV16: 4:2:2; NV12: 4:2:0 */ + enum apple_jpeg_subsampling subsampling; u32 luma_stride; u32 chroma_stride; u64 luma; @@ -169,28 +184,49 @@ struct apple_jpeg_job { }; /* - * Raw input: one buffer, the luma rows, then the interleaved CbCr rows at - * the same stride (V4L2 NV12/NV16). The engine prefetches its input up to - * AJ_INPUT_END, so both planes must sit in one buffer that ends there: with - * separate plane buffers it read past the end of whichever plane lies lower - * and faulted. It also fetches whole MCU rows (16 for 4:2:0, 8 for 4:2:2); - * the luma overrun lands in the chroma rows, and the buffer carries the - * chroma rows up to the MCU boundary after the visible ones. + * Raw input: one buffer, the luma rows, then the interleaved CbCr rows + * (V4L2 NV12/NV16/NV24; GREY has no chroma). The CbCr rows have the luma + * stride, twice it for NV24, whose chroma is full width. The engine + * prefetches its input up to AJ_INPUT_END, so both planes must sit in one + * buffer that ends there: with separate plane buffers it read past the end + * of whichever plane lies lower and faulted. It also fetches whole MCU rows + * (16 for 4:2:0, 8 otherwise); the luma overrun lands in the chroma rows, and + * the buffer carries the chroma rows up to the MCU boundary after the + * visible ones. Without chroma, the luma rows themselves are padded to it. */ struct apple_jpeg_layout { u32 bytesperline; + u32 chroma_stride; u32 chroma_offset; u32 sizeimage; }; -static inline void apple_jpeg_raw_layout(u32 width, u32 height, bool is422, +static inline void apple_jpeg_raw_layout(u32 width, u32 height, + enum apple_jpeg_subsampling s, struct apple_jpeg_layout *l) { - u32 rows = ALIGN(height, is422 ? 8 : 16); + u32 rows = ALIGN(height, apple_jpeg_mcu_rows(s)); l->bytesperline = ALIGN(width, 16); l->chroma_offset = l->bytesperline * height; - l->sizeimage = l->chroma_offset + l->bytesperline * (is422 ? rows : rows / 2); + switch (s) { + case AJ_SUBSAMPLING_420: + l->chroma_stride = l->bytesperline; + l->sizeimage = l->chroma_offset + l->chroma_stride * (rows / 2); + break; + case AJ_SUBSAMPLING_422: + l->chroma_stride = l->bytesperline; + l->sizeimage = l->chroma_offset + l->chroma_stride * rows; + break; + case AJ_SUBSAMPLING_444: + l->chroma_stride = 2 * l->bytesperline; + l->sizeimage = l->chroma_offset + l->chroma_stride * rows; + break; + default: + l->chroma_stride = 0; + l->sizeimage = l->bytesperline * rows; + break; + } } /* A kept CAPTURE size above the worst case is honoured up to this. */ diff --git a/drivers/media/platform/apple/jpeg/apple-jpeg-test.c b/drivers/media/platform/apple/jpeg/apple-jpeg-test.c index 7f325d331ec44a..87da054d7e2ae5 100644 --- a/drivers/media/platform/apple/jpeg/apple-jpeg-test.c +++ b/drivers/media/platform/apple/jpeg/apple-jpeg-test.c @@ -115,7 +115,7 @@ static void apple_jpeg_job_422_test(struct kunit *test) int n; KUNIT_ASSERT_NOT_NULL(test, w); - job.is422 = true; + job.subsampling = AJ_SUBSAMPLING_422; job.width = 641; /* odd width: chroma rounds up */ job.luma_stride = 656; job.chroma_stride = 656; @@ -250,8 +250,13 @@ static void apple_jpeg_t6050_layout_test(struct kunit *test) KUNIT_EXPECT_EQ(test, w[6].value, 8); KUNIT_EXPECT_EQ(test, w[11].value, 16); KUNIT_EXPECT_EQ(test, apple_jpeg_dma_ids(l, 0, w, 11), -ENOSPC); - KUNIT_EXPECT_FALSE(test, apple_jpeg_has_422(l)); - KUNIT_EXPECT_TRUE(test, apple_jpeg_has_422(wide)); + /* The T6050 job takes every subsampling; the older ones 4:2:0 and 4:2:2. */ + KUNIT_EXPECT_TRUE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_420)); + KUNIT_EXPECT_TRUE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_422)); + KUNIT_EXPECT_TRUE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_444)); + KUNIT_EXPECT_TRUE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_GREY)); + KUNIT_EXPECT_TRUE(test, apple_jpeg_has_subsampling(wide, AJ_SUBSAMPLING_422)); + KUNIT_EXPECT_FALSE(test, apple_jpeg_has_subsampling(wide, AJ_SUBSAMPLING_444)); } /* The first write to @offset at or after @from, or -1. */ @@ -263,6 +268,16 @@ static int apple_jpeg_index(const struct apple_jpeg_write *w, int n, int from, u return -1; } +/* The T6050 programming of the subsamplings besides 4:2:0, as checked on a J815 */ +static const struct apple_jpeg_t6050_case { + enum apple_jpeg_subsampling subsampling; + u32 codec, io, mcu_w, mcu_h, tile0_w, tile1_w; +} apple_jpeg_t6050_cases[] = { + { AJ_SUBSAMPLING_422, AJ_CODEC_422, AJ_IO_FLAGS_422, 16, 8, 2, 2 }, + { AJ_SUBSAMPLING_444, AJ_CODEC_444, AJ_IO_FLAGS_444, 8, 8, 1, 2 }, + { AJ_SUBSAMPLING_GREY, AJ_CODEC_GREY, AJ_IO_FLAGS_GREY, 8, 8, 1, 0 }, +}; + /* T6050 jobs: macOS's sequence, with 16-bit tables and no plane size registers. */ static void apple_jpeg_t6050_job_test(struct kunit *test) { @@ -315,9 +330,30 @@ static void apple_jpeg_t6050_job_test(struct kunit *test) KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_QTBL16(1)), 0x00110012); KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_QTBL16(1) + 0x7c), 0x00630063); - job.is422 = true; - KUNIT_EXPECT_EQ(test, apple_jpeg_build_job(l, &job, w, APPLE_JPEG_MAX_WRITES), - -EOPNOTSUPP); + /* The other subsamplings: codec, chroma layout, MCU grid, tiles, header */ + for (unsigned int i = 0; i < ARRAY_SIZE(apple_jpeg_t6050_cases); i++) { + const struct apple_jpeg_t6050_case *c = &apple_jpeg_t6050_cases[i]; + + job.subsampling = c->subsampling; + /* NV24's chroma rows are full width: twice the luma stride */ + job.chroma_stride = c->subsampling == AJ_SUBSAMPLING_444 ? 2 * job.width : job.width; + n = apple_jpeg_build_job(l, &job, w, APPLE_JPEG_MAX_WRITES); + KUNIT_ASSERT_GT(test, n, 0); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_CODEC), c->codec); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_T6050_PX_MODE), c->codec); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_PX_MCUS_W), + DIV_ROUND_UP(job.width, c->mcu_w)); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_PX_MCUS_H), + DIV_ROUND_UP(job.height, c->mcu_h)); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_PX_PLANE0_TILE_H), c->tile0_w); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_PX_USE_PLANE1), !!c->tile1_w); + if (c->tile1_w) + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_PX_PLANE1_TILE_H), + c->tile1_w); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_JPEG_IO_FLAGS), + AJ_IO_FLAGS_T6050 | AJ_IO_FLAGS_ORDER | c->io); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_T6050_ENC_CTRL), 0x35); + } } static void apple_jpeg_older_hwrev_test(struct kunit *test) @@ -361,7 +397,7 @@ static void apple_jpeg_legacy_job_test(struct kunit *test) job.input_end = 0x4ffff8; job.output = 0x1000000; for (unsigned int is422 = 0; is422 < 2; is422++) { - job.is422 = is422; + job.subsampling = is422 ? AJ_SUBSAMPLING_422 : AJ_SUBSAMPLING_420; n = apple_jpeg_build_job(apple_jpeg_t6000.layout, &job, w, APPLE_JPEG_MAX_WRITES); KUNIT_ASSERT_GT(test, n, 0); @@ -519,23 +555,27 @@ static void apple_jpeg_raw_layout_test(struct kunit *test) { static const struct { u32 w, h; - bool is422; + enum apple_jpeg_subsampling s; u32 bpl, chroma, size; } cases[] = { - { 1920, 1080, false, 1920, 1920 * 1080, 1920 * (1080 + 544) }, - { 1280, 720, false, 1280, 1280 * 720, 1280 * (720 + 360) }, - { 640, 480, false, 640, 640 * 480, 640 * (480 + 240) }, - { 3840, 2160, false, 3840, 3840 * 2160, 3840 * (2160 + 1080) }, + { 1920, 1080, AJ_SUBSAMPLING_420, 1920, 1920 * 1080, 1920 * (1080 + 544) }, + { 1280, 720, AJ_SUBSAMPLING_420, 1280, 1280 * 720, 1280 * (720 + 360) }, + { 640, 480, AJ_SUBSAMPLING_420, 640, 640 * 480, 640 * (480 + 240) }, + { 3840, 2160, AJ_SUBSAMPLING_420, 3840, 3840 * 2160, 3840 * (2160 + 1080) }, /* Odd height and a width that pads the stride to 16. */ - { 642, 481, false, 656, 656 * 481, 656 * (481 + 248) }, + { 642, 481, AJ_SUBSAMPLING_420, 656, 656 * 481, 656 * (481 + 248) }, /* 4:2:2 MCUs are 8 rows high and chroma has every row. */ - { 1920, 1084, true, 1920, 1920 * 1084, 1920 * (1084 + 1088) }, + { 1920, 1084, AJ_SUBSAMPLING_422, 1920, 1920 * 1084, 1920 * (1084 + 1088) }, + /* 4:4:4: full-width interleaved chroma, twice the luma stride. */ + { 640, 480, AJ_SUBSAMPLING_444, 640, 640 * 480, 640 * 480 + 1280 * 480 }, + /* GREY: the luma rows alone, padded to the 8-row MCU. */ + { 640, 481, AJ_SUBSAMPLING_GREY, 640, 640 * 481, 640 * 488 }, }; for (unsigned int i = 0; i < ARRAY_SIZE(cases); i++) { struct apple_jpeg_layout l; - apple_jpeg_raw_layout(cases[i].w, cases[i].h, cases[i].is422, &l); + apple_jpeg_raw_layout(cases[i].w, cases[i].h, cases[i].s, &l); KUNIT_EXPECT_EQ(test, l.bytesperline, cases[i].bpl); KUNIT_EXPECT_EQ(test, l.chroma_offset, cases[i].chroma); KUNIT_EXPECT_EQ(test, l.sizeimage, cases[i].size); diff --git a/drivers/media/platform/apple/prores/Kconfig b/drivers/media/platform/apple/prores/Kconfig index 27ffadcfcad5f9..f600080612f276 100644 --- a/drivers/media/platform/apple/prores/Kconfig +++ b/drivers/media/platform/apple/prores/Kconfig @@ -1,31 +1,31 @@ # SPDX-License-Identifier: GPL-2.0-only config VIDEO_APPLE_PRORES - tristate "Apple Silicon ProRes encoder" + tristate "Apple Silicon ProRes codec" depends on VIDEO_DEV depends on ARCH_APPLE || (COMPILE_TEST && 64BIT) depends on OF && IOMMU_API && PM select V4L2_MEM2MEM_DEV select VIDEOBUF2_DMA_CONTIG help - V4L2 memory-to-memory driver for the ProRes encoder engine (APR) + V4L2 memory-to-memory driver for the ProRes codec engine (APR) in Apple M1 Pro (T6000), M4 (T8132), M4 Pro (T6041), M5 (T8142), M5 Pro/Max (T6050) and A18 Pro (T8140) SoCs. On T6041, T8142 and T6050 a per-machine apple/prores--init.bin takes the place of the built-in initialization rows; T8132 has no built-in rows and binds only with apple/prores-t8132-init.bin. It encodes 8 and 16 bit 4:2:2 and 4:4:4 frames to ProRes 422 Proxy, LT, 422, HQ, - 4444 and 4444 XQ. + 4444 and 4444 XQ, and decodes those profiles, on every engine. To compile this driver as a module, choose M here: the module will be called apple-prores. config VIDEO_APPLE_PRORES_KUNIT_TEST - tristate "KUnit tests for the Apple ProRes encoder" if !KUNIT_ALL_TESTS + tristate "KUnit tests for the Apple ProRes codec" if !KUNIT_ALL_TESTS depends on KUNIT && VIDEO_APPLE_PRORES default KUNIT_ALL_TESTS help Check the APRI firmware parser, quantisation tables, DC scale table, - and job descriptors. APRI fixtures are wholly synthetic and contain - no vendor initialization values. The parser cases cover the complete - container shape and every row constraint. No hardware is needed. + encode/decode job descriptors, ProRes frame parser and ring + accounting. APRI fixtures are wholly synthetic and contain no vendor + initialization values. No hardware is needed. diff --git a/drivers/media/platform/apple/prores/apple-prores-desc.c b/drivers/media/platform/apple/prores/apple-prores-desc.c index 82abe6acce3f9b..f73923e5848069 100644 --- a/drivers/media/platform/apple/prores/apple-prores-desc.c +++ b/drivers/media/platform/apple/prores/apple-prores-desc.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -333,7 +334,7 @@ static int apr_build_desc_common(const struct apr_frame *f, u8 *desc) is444 != apr_profile_is_444(f->profile)) return -EINVAL; if (!f->width || !f->height || f->width > U16_MAX || f->height > U16_MAX || - f->width & 1) + (!is444 && f->width & 1)) return -EINVAL; min_luma = f->width * (deep ? 2 : 1); min_chroma = min_luma * (is444 ? 2 : 1); @@ -473,6 +474,343 @@ int apr_build_desc_v0(const struct apr_frame *f, u8 *desc) } EXPORT_SYMBOL_IF_KUNIT(apr_build_desc_v0); +/* Non-RAW decode descriptor version 0, used on every APR variant. */ +#define DD_COMMAND 0x000 +#define DD_COMMAND_BFF BIT(14) +#define DD_COMMAND_IRQ BIT(12) +#define DD_COMMAND_COLOR (2 << 8) +#define DD_COMMAND_CHROMA_422 (2 << 2) +#define DD_COMMAND_CHROMA_444 (3 << 2) +#define DD_COMMAND_DEPTH_16 3 +#define DD_COMMAND_EXT 0x004 +#define DD_INPUT 0x008 +#define DD_INPUT_X 0x010 +#define DD_INPUT_Y 0x012 +#define DD_INPUT_WIDTH 0x014 +#define DD_INPUT_HEIGHT 0x016 +#define DD_OUTPUT_X 0x018 +#define DD_OUTPUT_Y 0x01a +#define DD_OUTPUT_WIDTH 0x01c +#define DD_OUTPUT_HEIGHT 0x01e +#define DD_LUMA_STRIDE 0x020 +#define DD_CHROMA_STRIDE 0x022 +#define DD_ALPHA_STRIDE 0x024 +#define DD_LUMA 0x028 +#define DD_LUMA_METADATA 0x030 +#define DD_CHROMA 0x038 +#define DD_CHROMA_METADATA 0x040 +#define DD_ALPHA 0x048 +#define DD_ALPHA_METADATA 0x050 +#define DD_CRC_CONTROL 0x090 + +int apr_build_decode_desc(const struct apr_decode_frame *f, u8 *desc) +{ + bool is444 = apr_input_is_444(f->output); + bool deep = f->output == APR_INPUT_422_16 || + f->output == APR_INPUT_444_16; + u32 min_luma, min_chroma, command; + + if ((unsigned int)f->output > APR_INPUT_444_16 || !f->width || + !f->height || f->width > U16_MAX || f->height > U16_MAX || + (!is444 && f->width & 1)) + return -EINVAL; + min_luma = f->width * (deep ? 2 : 1); + min_chroma = min_luma * (is444 ? 2 : 1); + if (f->luma_stride % 64 || f->chroma_stride % 64 || + f->luma_stride < min_luma || f->chroma_stride < min_chroma || + f->luma_stride / 64 > U16_MAX || + f->chroma_stride / 64 > U16_MAX || !f->input || !f->luma || + !f->chroma) + return -EINVAL; + + memset(desc, 0, APR_DECODE_DESC_BYTES); + command = (u32)f->job_id << 16 | DD_COMMAND_IRQ | DD_COMMAND_COLOR | + (is444 ? DD_COMMAND_CHROMA_444 : DD_COMMAND_CHROMA_422); + if (deep) + command |= DD_COMMAND_DEPTH_16; + if (f->bottom_field_first) + command |= DD_COMMAND_BFF; + put_unaligned_le32(command, desc + DD_COMMAND); + put_unaligned_le32(0, desc + DD_COMMAND_EXT); + put_unaligned_le64(f->input, desc + DD_INPUT); + put_unaligned_le16(0, desc + DD_INPUT_X); + put_unaligned_le16(0, desc + DD_INPUT_Y); + put_unaligned_le16(f->width, desc + DD_INPUT_WIDTH); + put_unaligned_le16(f->height, desc + DD_INPUT_HEIGHT); + put_unaligned_le16(0, desc + DD_OUTPUT_X); + put_unaligned_le16(0, desc + DD_OUTPUT_Y); + put_unaligned_le16(f->width, desc + DD_OUTPUT_WIDTH); + put_unaligned_le16(f->height, desc + DD_OUTPUT_HEIGHT); + put_unaligned_le16(f->luma_stride / 64, desc + DD_LUMA_STRIDE); + put_unaligned_le16(f->chroma_stride / 64, desc + DD_CHROMA_STRIDE); + put_unaligned_le16(0, desc + DD_ALPHA_STRIDE); + put_unaligned_le64(f->luma, desc + DD_LUMA); + put_unaligned_le64(0, desc + DD_LUMA_METADATA); + put_unaligned_le64(f->chroma, desc + DD_CHROMA); + put_unaligned_le64(0, desc + DD_CHROMA_METADATA); + put_unaligned_le64(0, desc + DD_ALPHA); + put_unaligned_le64(0, desc + DD_ALPHA_METADATA); + put_unaligned_le32(3, desc + DD_CRC_CONTROL); + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(apr_build_decode_desc); + +/* Slice-size entries copied per block; 256 bytes of stack. */ +#define APR_SLICE_CHUNK 128 +/* + * Slices per picture, which bounds the CPU walk of the slice table. Both + * fields of an interlaced frame have the same geometry and the same bound. + */ +#define APR_MAX_SLICES 262144 + +/* + * The decode descriptor carries no input length: the engine follows the + * frame's own sizes. Every size it consumes must therefore be checked against + * the payload here, before the engine is programmed, and on a copy userspace + * cannot write (see apr_fill_decode_frame()). Each field is read once into a + * local, so that a parse of a buffer that changes under it, as at QBUF, still + * stays in bounds. + */ +static int apr_parse_picture(const u8 *data, u32 bytes, u32 width, + u32 height, bool interlaced, bool alpha, + u32 max_slices, u32 *picture_size, u32 *slices) +{ + u32 header, size, table_bytes, pos, min_size, coded, count; + u32 log2_slice, field_height, slice_header, i; + + if (bytes < 8) + return -EINVAL; + header = data[0] >> 3; + size = get_unaligned_be32(data + 1); + count = get_unaligned_be16(data + 5); + log2_slice = data[7] >> 4; + if (header < 8 || header > size || size > bytes || log2_slice > 3 || + (data[7] & 0xf)) + return -EINVAL; + field_height = interlaced ? DIV_ROUND_UP(height, 2) : height; + *slices = apr_slice_count(width, field_height, log2_slice); + /* Our encoder writes 0 here; anything else must match the geometry. */ + if (count && count != *slices) + return -EINVAL; + if (*slices < 9 || *slices > max_slices || + check_mul_overflow(*slices, 2U, &table_bytes) || + check_add_overflow(header, table_bytes, &min_size) || + min_size > size) + return -EINVAL; + /* + * The decoder's source buffers are mapped uncached, where each load is + * a fabric round trip: copy the table in blocks, then walk the copy. + * A slice header gives the coded Y and Cb sizes, and the Cr size too + * when the frame has alpha; the rest of the slice is Cr (or alpha). + */ + slice_header = alpha ? 8 : 6; + pos = min_size; + for (i = 0; i < *slices; i += APR_SLICE_CHUNK) { + __be16 chunk[APR_SLICE_CHUNK]; + u32 n = min(*slices - i, (u32)APR_SLICE_CHUNK), j; + + memcpy(chunk, data + header + 2 * i, 2 * n); + for (j = 0; j < n; j++) { + u32 slice = be16_to_cpu(chunk[j]), hdr; + u8 sh[8]; + + if (slice < slice_header || slice > size - pos) + return -EINVAL; + memcpy(sh, data + pos, slice_header); + hdr = sh[0] >> 3; + coded = get_unaligned_be16(sh + 2) + + get_unaligned_be16(sh + 4); + if (alpha) + coded += get_unaligned_be16(sh + 6); + if (hdr < slice_header || hdr > slice || + coded > slice - hdr) + return -EINVAL; + pos += slice; + } + } + *picture_size = size; + return 0; +} + +int apr_parse_frame(const u8 *data, size_t bytes, struct apr_prores_info *info) +{ + const u8 *header; + u32 frame_size, header_size, min_header, offset; + u64 pixels; + unsigned int i; + int ret; + + if (!data || !info || bytes < 28 || bytes > U32_MAX) + return -EINVAL; + frame_size = get_unaligned_be32(data); + if (frame_size != bytes || memcmp(data + 4, "icpf", 4)) + return -EINVAL; + header = data + 8; + header_size = get_unaligned_be16(header); + if (header_size < 20 || header_size > frame_size - 8 || + get_unaligned_be16(header + 2) > 1) + return -EINVAL; + min_header = 20 + 64 * hweight8(header[19] & 3); + if (header_size < min_header) + return -EINVAL; + + memset(info, 0, sizeof(*info)); + info->frame_size = frame_size; + info->width = get_unaligned_be16(header + 8); + info->height = get_unaligned_be16(header + 10); + info->chroma = header[12] >> 6; + info->frame_type = (header[12] >> 2) & 3; + info->alpha = header[17] & 0xf; + info->primaries = header[14]; + info->transfer = header[15]; + info->matrix = header[16]; + pixels = (u64)info->width * info->height; + if (info->width < 16 || info->height < 16 || pixels > 0x10000000 || + (info->chroma != 2 && info->chroma != 3) || info->frame_type > 2 || + (info->chroma == 2 && info->width & 1) || info->alpha > 2 || + (info->alpha && info->chroma != 3)) + return -EINVAL; + info->pictures = info->frame_type ? 2 : 1; + offset = 8 + header_size; + for (i = 0; i < info->pictures; i++) { + if (offset > frame_size) + return -EINVAL; + info->picture_offset[i] = offset; + ret = apr_parse_picture(data + offset, frame_size - offset, + info->width, info->height, + info->pictures == 2, info->alpha, + APR_MAX_SLICES, &info->picture_size[i], + &info->slices[i]); + if (ret) + return ret; + if (check_add_overflow(offset, info->picture_size[i], &offset)) + return -EINVAL; + } + return offset == frame_size ? 0 : -EINVAL; +} +EXPORT_SYMBOL_IF_KUNIT(apr_parse_frame); + +u32 apr_ring_advance(u32 ptr, u32 bytes, u32 ring_bytes) +{ + u32 offset = ptr & APR_RING_OFFSET_MASK; + u32 generation = ptr & APR_RING_GENERATION; + + offset += bytes; + if (offset >= ring_bytes) { + offset -= ring_bytes; + generation ^= APR_RING_GENERATION; + } + return generation | offset; +} +EXPORT_SYMBOL_IF_KUNIT(apr_ring_advance); + +/* + * Ring pointers carry a generation bit above the offset, so a pointer names + * one of 2 * ring_bytes positions and a full ring differs from an empty one. + */ +static u32 apr_ring_pos(u32 ptr, u32 ring_bytes) +{ + return (ptr & APR_RING_OFFSET_MASK) + + (ptr & APR_RING_GENERATION ? ring_bytes : 0); +} + +/* Bytes from @from forward to @to. */ +u32 apr_ring_distance(u32 from, u32 to, u32 ring_bytes) +{ + u32 span = 2 * ring_bytes; + + return (apr_ring_pos(to, ring_bytes) + span - + apr_ring_pos(from, ring_bytes)) % span; +} +EXPORT_SYMBOL_IF_KUNIT(apr_ring_distance); + +/* Bytes the producer may still write; @done is what the engine consumed. */ +u32 apr_ring_free(u32 done, u32 head, u32 ring_bytes) +{ + u32 used = apr_ring_distance(done, head, ring_bytes); + + return used < ring_bytes ? ring_bytes - used : 0; +} +EXPORT_SYMBOL_IF_KUNIT(apr_ring_free); + +/* + * Has the consumer @tail moved past the descriptor that ends at @end? @done + * is the start of the oldest descriptor still owned by the engine. + */ +bool apr_ring_passed(u32 done, u32 end, u32 tail, u32 ring_bytes) +{ + return apr_ring_distance(done, end, ring_bytes) <= + apr_ring_distance(done, tail, ring_bytes); +} +EXPORT_SYMBOL_IF_KUNIT(apr_ring_passed); + +/* A tail the engine reports must lie between what it consumed and the head. */ +bool apr_ring_tail_valid(u32 done, u32 tail, u32 head, u32 ring_bytes) +{ + return !(tail & ~APR_RING_PTR_MASK) && + (tail & APR_RING_OFFSET_MASK) < ring_bytes && + apr_ring_distance(done, tail, ring_bytes) <= + apr_ring_distance(done, head, ring_bytes); +} +EXPORT_SYMBOL_IF_KUNIT(apr_ring_tail_valid); + +/* + * Decode job ids are device-wide and never 0: the engine reports the id of + * the last job it finished, and that report reads 0 after a reset, before + * any job has run. + */ +u16 apr_next_job_id(u16 id) +{ + return id == U16_MAX ? 1 : id + 1; +} +EXPORT_SYMBOL_IF_KUNIT(apr_next_job_id); + +/* + * Has the engine finished job @id, given the last finished id @done_id? + * Jobs finish in ring order and far fewer than 2^15 are ever outstanding, + * so the signed distance decides, across the wrap as well. + */ +bool apr_job_id_done(u16 done_id, u16 id) +{ + return (u16)(done_id - id) < 0x8000; +} +EXPORT_SYMBOL_IF_KUNIT(apr_job_id_done); + +/* + * Classify @done_id, the last finished id ST1 reports, against @next_id, the + * id the next decode job gets. 0 is what ST1 reads before any job finished + * since the reset. Ids from @next_id on, half the id space, are not issued + * yet; the other half are issued ids, finished or still in the ring. + */ +enum apr_done_id apr_job_id_check(u16 done_id, u16 next_id) +{ + if (!done_id) + return APR_DONE_ID_NONE; + if (apr_job_id_done(done_id, next_id)) + return APR_DONE_ID_FUTURE; + return APR_DONE_ID_ISSUED; +} +EXPORT_SYMBOL_IF_KUNIT(apr_job_id_check); + +/* No further job may enter the ring with @jobs in it, @encodes of them encodes. */ +bool apr_jobs_full(unsigned int jobs, unsigned int encodes) +{ + return jobs >= APR_MAX_INFLIGHT || encodes >= APR_ENCODE_MAX_INFLIGHT; +} +EXPORT_SYMBOL_IF_KUNIT(apr_jobs_full); + +void apr_ring_write(u8 *ring, u32 ring_bytes, u32 ptr, const u8 *desc, + u32 desc_bytes) +{ + u32 offset = ptr & APR_RING_OFFSET_MASK; + u32 first = min(desc_bytes, ring_bytes - offset); + + memcpy(ring + offset, desc, first); + if (first != desc_bytes) + memcpy(ring, desc + first, desc_bytes - first); +} +EXPORT_SYMBOL_IF_KUNIT(apr_ring_write); + /* * A finished frame starts with its big-endian length, which counts the whole * frame, followed by the 'icpf' frame identifier. diff --git a/drivers/media/platform/apple/prores/apple-prores-drv.c b/drivers/media/platform/apple/prores/apple-prores-drv.c index f75dd6d5b3d2a5..76ee4183c0124a 100644 --- a/drivers/media/platform/apple/prores/apple-prores-drv.c +++ b/drivers/media/platform/apple/prores/apple-prores-drv.c @@ -1,15 +1,26 @@ // SPDX-License-Identifier: GPL-2.0-only /* - * Apple ProRes (APR) V4L2 memory-to-memory encoder. + * Apple ProRes (APR) V4L2 memory-to-memory codec. * - * One job runs at a time. The driver writes a descriptor into a 128 KiB DMA - * ring, advances the producer head and waits for the completion interrupt. - * Raw frames come in on the OUTPUT queue as semi-planar 4:2:2 or 4:4:4 (8 or - * 16 bits per sample) and complete ProRes frames go out on CAPTURE. + * The driver writes job descriptors into a 128 KiB DMA ring and advances the + * producer head; the engine works through the ring and reports progress with + * a consumer tail and a completion interrupt. Up to APR_MAX_INFLIGHT decode + * jobs sit in the ring at once: a job's buffers leave the m2m queues when its + * descriptor is published, so v4l2-m2m can run the next job while the engine + * is busy. The tail moves when the engine fetches a descriptor, not when it + * has finished the frame, so decode jobs complete in ring order once the + * engine reports their job id as finished in ST1. An encode descriptor + * carries no job id: it only enters an empty ring and completes on its + * interrupt, as a lone job. + * The encoder consumes semi-planar 4:2:2 or 4:4:4 frames and produces one + * complete ProRes frame per buffer. The decoder exposes a second stateful + * node with the queue directions reversed and linear color output. * * Based on Acelogic's J700 ProRes diagnostic, which first encoded on this * engine under Linux, and on the m1n1 proxyclient ProRes experiment (MIT). */ +#include +#include #include #include #include @@ -25,9 +36,11 @@ #include #include #include +#include #include #include #include +#include #include #include @@ -44,8 +57,9 @@ #define APR_NAME "apple-prores" #define APR_MIN_W 16 #define APR_MIN_H 16 -#define APR_MAX_W 8192 -#define APR_MAX_H 8192 +#define APR_MAX_W U16_MAX +#define APR_MAX_H U16_MAX +#define APR_MAX_PIXELS 0x10000000 #define APR_TIMEOUT_MS 1000 #define APR_POLL_MS 4 #define APR_AUTOSUSPEND_MS 500 @@ -1009,7 +1023,7 @@ static const struct apr_variant apr_t8140 = { .num_regs = 2, .num_irqs = 2, .ring_bytes = APR_RING_BYTES, - .desc_bytes = APR_DESC_BYTES, + .desc_bytes = APR_ENCODE_DESC_BYTES, }; static const struct apr_variant apr_t6000 = { @@ -1021,7 +1035,7 @@ static const struct apr_variant apr_t6000 = { .num_regs = 2, .num_irqs = 1, .ring_bytes = APR_RING_BYTES, - .desc_bytes = APR_DESC_BYTES, + .desc_bytes = APR_ENCODE_DESC_BYTES, }; static const struct apr_variant apr_t6041 = { @@ -1109,6 +1123,49 @@ static const struct apr_variant apr_t8142 = { .apri = &apri_t8142, }; +struct apr_ctx; + +/* + * A source buffer of the decoder. The frame is parsed once, when it is + * queued, for the source-change check and to fail a malformed frame early. + * The engine never reads this buffer: userspace may still write it, so + * device_run copies the frame and parses and programs the copy. + */ +struct apr_buf { + struct v4l2_m2m_buffer m2m; /* first: vb2 and m2m embed this */ + struct apr_prores_info info; + int parse_err; +}; + +static struct apr_buf *to_apr_buf(struct vb2_v4l2_buffer *vbuf) +{ + return container_of(vbuf, struct apr_buf, m2m.vb); +} + +/* + * A driver-owned copy of one decoder source frame, the only input the engine + * reads. The decode descriptor has no input length: the engine follows the + * frame's in-band sizes, which are checked on this copy, out of userspace's + * reach, before the descriptor points at it. + */ +struct apr_bounce { + struct sg_table *sgt; + void *vaddr; + size_t size; +}; + +/* A job in the ring; its buffers left the m2m queues when it was published. */ +struct apr_job { + struct apr_ctx *ctx; + struct vb2_v4l2_buffer *src; + struct vb2_v4l2_buffer *dst; + u32 end; /* ring pointer just past its descriptor */ + u16 id; /* decode job id in the descriptor */ + u32 sequence; + u32 bytes; /* decoded payload */ + int err; /* forced result: engine error or cancellation */ +}; + struct apr_dev { const struct apr_variant *variant; struct device *dev; @@ -1125,7 +1182,8 @@ struct apr_dev { int irq[2]; struct v4l2_device v4l2_dev; - struct video_device vdev; + struct video_device enc_vdev; + struct video_device dec_vdev; struct v4l2_m2m_dev *m2m_dev; struct mutex vdev_lock; /* serialises ioctls and queue state */ @@ -1138,12 +1196,30 @@ struct apr_dev { size_t stats_size; spinlock_t hw_lock; /* protects the fields below */ - struct apr_ctx *active; /* job in the engine, or NULL */ + struct apr_job jobs[APR_MAX_INFLIGHT]; /* in ring order */ + /* + * Source copy of the decode job in the jobs[] slot of the same index. + * Not under hw_lock: only device_run, which m2m runs one at a time, + * fills the next free slot's copy, and completions free slots in order + * without changing which slot is next. + */ + struct apr_bounce bounce[APR_MAX_INFLIGHT]; + unsigned int job_first; /* oldest job in jobs[] */ + unsigned int njobs; /* jobs the engine owns */ + unsigned int nencodes; /* encode jobs among them */ + struct apr_ctx *held; /* m2m job left running while the ring is full */ u32 head; /* next free ring offset */ + u32 done; /* the engine has consumed the ring up to here */ + u16 next_id; /* id for the next decode job, never 0 */ bool ring_ready; /* engine registers programmed since power-up */ bool broken; /* timed out with no way to reset */ - unsigned long started; /* jiffies at submission */ + bool hung; /* ring state is inconsistent, reset now */ + bool resetting; /* the watchdog is resetting the engine */ + unsigned long progress; /* jiffies of the last start or completion */ struct delayed_work watchdog; + + atomic_t outstanding; /* jobs not yet given back to vb2 */ + wait_queue_head_t idle_wq; /* woken when jobs are given back */ }; struct apr_ctx { @@ -1154,6 +1230,12 @@ struct apr_ctx { struct v4l2_pix_format_mplane src_fmt; struct v4l2_pix_format_mplane dst_fmt; const struct apr_fmt *raw; + bool decode; + bool source_valid; + bool decode_444; + /* LAST went out for a resolution change: wait for CAPTURE to restart. */ + bool drc_pending; + atomic_t inflight; /* jobs in the ring not yet given back to vb2 */ enum apr_profile stream_profile; /* fixed while OUTPUT streams */ u32 sequence; }; @@ -1234,6 +1316,8 @@ static void apr_hw_init(struct apr_dev *apr) /* Order the setup before any descriptor publication. */ wmb(); apr->head = 0; + apr->next_id = 1; + apr->done = 0; apr->ring_ready = true; } @@ -1314,18 +1398,127 @@ static void apr_fill_frame(struct apr_ctx *ctx, struct vb2_v4l2_buffer *src, }; } -static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) +static void apr_bounce_free(struct apr_dev *apr, struct apr_bounce *b) { + if (!b->sgt) + return; + dma_vunmap_noncontiguous(apr->dev, b->vaddr); + dma_free_noncontiguous(apr->dev, b->size, b->sgt, DMA_TO_DEVICE); + *b = (struct apr_bounce){}; +} + +/* Called once no job is in the ring, from runtime suspend and removal. */ +static void apr_bounce_free_all(struct apr_dev *apr) +{ + unsigned int i; + + for (i = 0; i < APR_MAX_INFLIGHT; i++) + apr_bounce_free(apr, &apr->bounce[i]); +} + +/* + * Make @b hold at least @bytes. Frame sizes vary within a stream, so a copy + * that grows keeps a quarter in hand and is rarely reallocated. CPU access + * is cached; the engine sees one IOVA range through its DART. + */ +static int apr_bounce_reserve(struct apr_dev *apr, struct apr_bounce *b, + size_t bytes) +{ + size_t size; + + if (b->size >= bytes) + return 0; + apr_bounce_free(apr, b); + size = PAGE_ALIGN(max_t(size_t, SZ_1M, bytes + bytes / 4)); + b->sgt = dma_alloc_noncontiguous(apr->dev, size, DMA_TO_DEVICE, + GFP_KERNEL, 0); + if (!b->sgt) + return -ENOMEM; + b->size = size; + b->vaddr = dma_vmap_noncontiguous(apr->dev, size, b->sgt); + if (!b->vaddr || b->sgt->nents != 1) { + if (b->vaddr) + dma_vunmap_noncontiguous(apr->dev, b->vaddr); + dma_free_noncontiguous(apr->dev, size, b->sgt, DMA_TO_DEVICE); + *b = (struct apr_bounce){}; + return -ENOMEM; + } + return 0; +} + +/* + * Copy @src's frame into @b, parse the copy and describe a decode of it. + * Userspace keeps write access to @src while it is queued, so the sizes + * checked when it was queued are only a hint: everything the engine follows + * comes from the copy, which nothing but the engine reads from now on. + */ +static int apr_fill_decode_frame(struct apr_ctx *ctx, + struct vb2_v4l2_buffer *src, + struct vb2_v4l2_buffer *dst, + struct apr_bounce *b, + struct apr_decode_frame *f) +{ + const struct v4l2_pix_format_mplane *d = &ctx->dst_fmt; + struct apr_dev *apr = ctx->apr; + struct apr_prores_info info; + u32 offset = src->vb2_buf.planes[0].data_offset; + u32 payload = vb2_get_plane_payload(&src->vb2_buf, 0); + dma_addr_t output; + u32 luma_stride; + u8 *data; + int ret; + + ret = to_apr_buf(src)->parse_err; + if (ret) + return ret; + if (vb2_plane_size(&dst->vb2_buf, 0) < d->plane_fmt[0].sizeimage) + return -EINVAL; + data = vb2_plane_vaddr(&src->vb2_buf, 0); + if (!data || offset > payload) + return -EINVAL; + ret = apr_bounce_reserve(apr, b, payload - offset); + if (ret) + return ret; + memcpy(b->vaddr, data + offset, payload - offset); + ret = apr_parse_frame(b->vaddr, payload - offset, &info); + if (ret) + return ret; + /* The non-RAW descriptor accepts one picture; field repacking is later. */ + if (info.pictures != 1) + return -EOPNOTSUPP; + if (info.width != d->width || info.height != d->height || + info.chroma == 3 != ctx->raw->is444) + return -EINVAL; + dma_sync_sgtable_for_device(apr->dev, b->sgt, DMA_TO_DEVICE); + + luma_stride = d->plane_fmt[0].bytesperline; + output = vb2_dma_contig_plane_dma_addr(&dst->vb2_buf, 0); + *f = (struct apr_decode_frame){ + .width = info.width, + .height = info.height, + .output = ctx->raw->input, + .luma_stride = luma_stride, + .chroma_stride = luma_stride * (ctx->raw->is444 ? 2 : 1), + .input = sg_dma_address(b->sgt->sgl), + .luma = output, + .chroma = output + (u64)luma_stride * d->height, + }; + return 0; +} + +/* + * Give a job's buffers back to vb2. Safe in interrupt context. Not inlined, + * so ftrace can time completions against apr_device_run and apr_irq. + */ +static noinline void apr_complete(struct apr_dev *apr, struct apr_job *job) +{ + struct apr_ctx *ctx = job->ctx; struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; - struct vb2_v4l2_buffer *src, *dst; + struct vb2_v4l2_buffer *src = job->src, *dst = job->dst; + int err = job->err; u32 bytes = 0; - src = v4l2_m2m_src_buf_remove(m2m); - dst = v4l2_m2m_dst_buf_remove(m2m); - if (WARN_ON(!src || !dst)) - goto out; - - if (!err) { + if (!err && !ctx->decode) { u8 *out = vb2_plane_vaddr(&dst->vb2_buf, 0); /* The engine wrote the frame through the DART; see it now. */ @@ -1335,9 +1528,14 @@ static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) if (err) dev_err_ratelimited(apr->dev, "engine returned no frame\n"); } + if (!err && ctx->decode) { + /* The ACK and tail read complete before output ownership returns. */ + dma_rmb(); + bytes = job->bytes; + } vb2_set_plane_payload(&dst->vb2_buf, 0, err ? 0 : bytes); v4l2_m2m_buf_copy_metadata(src, dst); - dst->sequence = ctx->sequence++; + dst->sequence = job->sequence; dst->flags |= V4L2_BUF_FLAG_KEYFRAME; if (v4l2_m2m_is_last_draining_src_buf(m2m, src)) { static const struct v4l2_event eos = { .type = V4L2_EVENT_EOS }; @@ -1348,94 +1546,269 @@ static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) } v4l2_m2m_buf_done(src, err ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE); v4l2_m2m_buf_done(dst, err ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE); -out: +} + +/* + * Give back jobs taken off the ring, in ring order. A context may be freed + * as soon as its in-flight count drops, so it is not touched after that. + */ +static void apr_retire(struct apr_dev *apr, struct apr_job *jobs, + unsigned int n) +{ + unsigned int i; + + for (i = 0; i < n; i++) { + apr_complete(apr, &jobs[i]); + pm_runtime_mark_last_busy(apr->dev); + pm_runtime_put_autosuspend(apr->dev); + atomic_dec(&jobs[i].ctx->inflight); + atomic_dec(&apr->outstanding); + } + if (n) + wake_up_all(&apr->idle_wq); +} + +/* + * Fail the current m2m job before its descriptor reached the ring. Earlier + * jobs of the context may still be in the ring: they are given back first, + * so this one cannot overtake them. That matters most when it is the drain's + * last source buffer, whose LAST flag and EOS end the stream. Sleeps. + */ +static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) +{ + struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; + struct apr_job job = { + .ctx = ctx, + .err = err, + }; + unsigned long flags; + + wait_event(apr->idle_wq, !atomic_read(&ctx->inflight)); + /* Buffers move under hw_lock, which apr_stop_cmd() relies on. */ + spin_lock_irqsave(&apr->hw_lock, flags); + job.sequence = ctx->sequence++; + job.src = v4l2_m2m_src_buf_remove(m2m); + job.dst = v4l2_m2m_dst_buf_remove(m2m); + spin_unlock_irqrestore(&apr->hw_lock, flags); + if (!WARN_ON(!job.src || !job.dst)) + apr_complete(apr, &job); pm_runtime_mark_last_busy(apr->dev); pm_runtime_put_autosuspend(apr->dev); v4l2_m2m_job_finish(apr->m2m_dev, m2m); } /* - * Claim the active job if the engine has finished it. Returns the context to - * finish, or NULL. Called with hw_lock held. + * The ring state is inconsistent: no completion may be trusted until the + * watchdog has reset the engine. Called with hw_lock held. */ -static struct apr_ctx *apr_take_done(struct apr_dev *apr, int *err) +static void apr_set_hung(struct apr_dev *apr) { - struct apr_ctx *ctx = apr->active; - u32 status, tail; + apr->hung = true; + apr_write(apr, APR_REG_IRQ_ENABLE, 0); +} - if (!ctx) - return NULL; +/* + * Move the jobs the engine has finished, oldest first, to @out (room for + * APR_MAX_INFLIGHT). Returns false if the engine raised nothing. Called with + * hw_lock held and the engine powered. + * + * DONE and ERROR are latched per engine, not per descriptor: the status and + * detail registers do not say which descriptor failed. An ERROR therefore + * fails every job in the ring at that moment; the engine keeps running and + * the watchdog resets it if no job finishes for APR_TIMEOUT_MS. Several + * descriptors may finish behind one interrupt. + * + * A decode job is finished once ST1 reports its id. ST1 reads 0 before any + * job finished since the reset, which is no progress; an id the driver has + * not issued yet means the engine and the ring disagree, so the ring is + * declared hung and the watchdog resets the engine before any buffer goes + * back. From then on nothing is taken off the ring here: the engine's + * interrupt is masked, and the watchdog fails every job after the reset. + * An encode has no id and retires on DONE once the tail passed it. + * A DONE still latched after the last job was taken here would make a new + * encode look finished as soon as it is fetched, so device_run clears the + * status before it publishes into an empty ring. + */ +static bool apr_take_done(struct apr_dev *apr, struct apr_job *out, + unsigned int *n) +{ + u32 ring_bytes = apr->variant->ring_bytes; + u32 status, tail, st0, st1, st2; + u32 detail[6]; + enum apr_done_id state; + unsigned int i; + u16 done_id; + + *n = 0; + if (apr->hung) + return false; status = apr_read(apr, APR_REG_IRQ_STATUS); - if (!status) - return NULL; + if (!(status & (APR_IRQ_DONE | APR_IRQ_ERROR))) + return false; + /* Snapshot before the W1C, as for a single job. */ + st0 = apr_read(apr, APR_REG_ST0); + st1 = apr_read(apr, APR_REG_ST1); + st2 = apr_read(apr, APR_REG_ST2); + detail[0] = apr_read(apr, APR_REG_DETAIL0); + detail[1] = apr_read(apr, APR_REG_DETAIL1_LO); + detail[2] = apr_read(apr, APR_REG_DETAIL1_HI); + detail[3] = apr_read(apr, APR_REG_DETAIL2_LO); + detail[4] = apr_read(apr, APR_REG_DETAIL2_HI); + detail[5] = apr_read(apr, APR_REG_DETAIL3); + if (status & APR_IRQ_ERROR) { + dev_err_ratelimited(apr->dev, + "job failed: irq %#x head %#x done %#x jobs %u st %#x/%#x/%#x detail %#x/%#x/%#x/%#x/%#x/%#x\n", + status, apr->head, apr->done, apr->njobs, + st0, st1, st2, detail[0], detail[1], detail[2], + detail[3], detail[4], detail[5]); + for (i = 0; i < apr->njobs; i++) { + struct apr_job *job = &apr->jobs[(apr->job_first + i) % + APR_MAX_INFLIGHT]; + + if (!job->err) + job->err = -EIO; + } + } apr_write(apr, APR_REG_IRQ_STATUS, status); + /* The tail read flushes the posted W1C before buffers are released. */ tail = apr_read(apr, APR_REG_RING_TAIL) & APR_RING_PTR_MASK; - *err = 0; - if (status != APR_IRQ_DONE || tail != apr->head) { - dev_err_ratelimited(apr->dev, - "job failed: status %#x tail %#x head %#x st %#x/%#x\n", - status, tail, apr->head, - apr_read(apr, APR_REG_ST0), apr_read(apr, APR_REG_ST1)); - *err = -EIO; + if (!apr_ring_tail_valid(apr->done, tail, apr->head, ring_bytes)) { + dev_err_ratelimited(apr->dev, "tail %#x outside %#x..%#x\n", + tail, apr->done, apr->head); + apr_set_hung(apr); + return true; } - apr->active = NULL; + /* Read after the W1C: a job finishing later raises DONE again. */ + done_id = FIELD_GET(APR_ST1_DONE_ID, apr_read(apr, APR_REG_ST1)); + state = apr_job_id_check(done_id, apr->next_id); + if (state == APR_DONE_ID_FUTURE && apr->njobs > apr->nencodes) { + dev_err_ratelimited(apr->dev, "finished id %#x not issued yet, next %#x\n", + done_id, apr->next_id); + apr_set_hung(apr); + return true; + } + while (apr->njobs) { + struct apr_job *job = &apr->jobs[apr->job_first]; + + if (job->ctx->decode ? + state != APR_DONE_ID_ISSUED || + !apr_job_id_done(done_id, job->id) : + !(status & (APR_IRQ_DONE | APR_IRQ_ERROR)) || + !apr_ring_passed(apr->done, job->end, tail, ring_bytes)) + break; + out[(*n)++] = *job; + apr->done = job->end; + apr->job_first = (apr->job_first + 1) % APR_MAX_INFLIGHT; + apr->njobs--; + if (!job->ctx->decode) + apr->nencodes--; + } + if (*n) + apr->progress = jiffies; + return true; +} + +/* + * The m2m job left running because the ring was full may finish once there + * is room again. Called with hw_lock held; the caller finishes it unlocked. + */ +static struct apr_ctx *apr_take_held(struct apr_dev *apr) +{ + struct apr_ctx *ctx = apr->held; + + if (!ctx || apr_jobs_full(apr->njobs, apr->nencodes)) + return NULL; + apr->held = NULL; return ctx; } static irqreturn_t apr_irq(int irq, void *data) { struct apr_dev *apr = data; - struct apr_ctx *ctx; - int err = 0; + struct apr_job done[APR_MAX_INFLIGHT]; + struct apr_ctx *held = NULL; + unsigned int n = 0; + bool handled = false, hung; spin_lock(&apr->hw_lock); - ctx = apr_take_done(apr, &err); + /* + * Registers are only reachable while the engine is powered. A hung + * ring masked the interrupt; one already in flight is ours. + */ + if (apr->ring_ready) + handled = apr_take_done(apr, done, &n) || apr->hung; + held = apr_take_held(apr); + hung = apr->hung; + if (!apr->njobs && !hung) + cancel_delayed_work(&apr->watchdog); spin_unlock(&apr->hw_lock); - if (!ctx) - return IRQ_NONE; - cancel_delayed_work(&apr->watchdog); - apr_finish_job(apr, ctx, err); - return IRQ_HANDLED; + if (hung) + mod_delayed_work(system_wq, &apr->watchdog, 0); + apr_retire(apr, done, n); + if (held) + v4l2_m2m_job_finish(apr->m2m_dev, held->fh.m2m_ctx); + return handled ? IRQ_HANDLED : IRQ_NONE; } /* - * Backstop for a lost interrupt and for hangs. A hung engine is reset - * through its power domain and reprogrammed; without a reset line the - * device refuses further jobs rather than reuse memory it may still own. + * Backstop for a lost interrupt and for hangs. When no job finishes for + * APR_TIMEOUT_MS, every job in the ring fails. A hung engine is reset through its + * power domain and reprogrammed; without a reset line the device refuses + * further jobs rather than reuse memory it may still own. */ static void apr_watchdog(struct work_struct *work) { struct apr_dev *apr = container_of(work, struct apr_dev, watchdog.work); - struct apr_ctx *ctx; + struct apr_job done[APR_MAX_INFLIGHT]; + struct apr_ctx *held; unsigned long flags; - int err = 0; + unsigned int n = 0; spin_lock_irqsave(&apr->hw_lock, flags); - ctx = apr_take_done(apr, &err); - if (ctx) { + /* A hung ring is reset even when no job is left in it. */ + if (!apr->njobs && !apr->hung) { spin_unlock_irqrestore(&apr->hw_lock, flags); - dev_warn_once(apr->dev, "completion found without an interrupt\n"); - apr_finish_job(apr, ctx, err); return; } - ctx = apr->active; - if (!ctx) { + if (!apr->hung && apr->ring_ready && apr_take_done(apr, done, &n) && n) + dev_warn_once(apr->dev, "completion found without an interrupt\n"); + if (!apr->hung && (!apr->njobs || + time_before(jiffies, apr->progress + + msecs_to_jiffies(APR_TIMEOUT_MS)))) { + held = apr_take_held(apr); + if (apr->njobs) + schedule_delayed_work(&apr->watchdog, + msecs_to_jiffies(APR_POLL_MS)); spin_unlock_irqrestore(&apr->hw_lock, flags); + apr_retire(apr, done, n); + if (held) + v4l2_m2m_job_finish(apr->m2m_dev, held->fh.m2m_ctx); return; } - if (time_before(jiffies, apr->started + msecs_to_jiffies(APR_TIMEOUT_MS))) { - spin_unlock_irqrestore(&apr->hw_lock, flags); - schedule_delayed_work(&apr->watchdog, msecs_to_jiffies(APR_POLL_MS)); - return; + dev_err(apr->dev, "%s: head %#x done %#x tail %#x jobs %u st %#x/%#x\n", + apr->hung ? "ring state invalid" : "job timed out", + apr->head, apr->done, apr_read(apr, APR_REG_RING_TAIL), + apr->njobs, apr_read(apr, APR_REG_ST0), apr_read(apr, APR_REG_ST1)); + /* Every job still in the ring fails; the engine may own none of them. */ + while (apr->njobs) { + struct apr_job *job = &apr->jobs[apr->job_first]; + + done[n] = *job; + if (!done[n].err) + done[n].err = -ETIMEDOUT; + n++; + apr->job_first = (apr->job_first + 1) % APR_MAX_INFLIGHT; + apr->njobs--; } - dev_err(apr->dev, "job timed out: head %#x tail %#x st %#x/%#x\n", - apr->head, apr_read(apr, APR_REG_RING_TAIL), - apr_read(apr, APR_REG_ST0), apr_read(apr, APR_REG_ST1)); - apr->active = NULL; + apr->nencodes = 0; + apr->hung = false; + held = apr->held; + apr->held = NULL; apr_write(apr, APR_REG_IRQ_ENABLE, 0); apr_write(apr, APR_REG_MODE, APR_MODE_OFF); apr->ring_ready = false; - /* No new job can start until this one is finished below. */ + /* device_run waits until the reset below is over. */ + apr->resetting = true; spin_unlock_irqrestore(&apr->hw_lock, flags); if (!apr->reset || reset_control_reset(apr->reset)) { dev_err(apr->dev, "engine cannot be reset, refusing further jobs\n"); @@ -1443,21 +1816,129 @@ static void apr_watchdog(struct work_struct *work) apr->broken = true; spin_unlock_irqrestore(&apr->hw_lock, flags); } - apr_finish_job(apr, ctx, -ETIMEDOUT); + spin_lock_irqsave(&apr->hw_lock, flags); + apr->resetting = false; + spin_unlock_irqrestore(&apr->hw_lock, flags); + apr_retire(apr, done, n); + /* apr_retire() woke idle_wq only if there was a job to give back. */ + wake_up_all(&apr->idle_wq); + if (held) + v4l2_m2m_job_finish(apr->m2m_dev, held->fh.m2m_ctx); +} + +static const struct v4l2_event apr_source_change = { + .type = V4L2_EVENT_SOURCE_CHANGE, + .u.src_change.changes = V4L2_EVENT_SRC_CH_RESOLUTION, +}; + +static void apr_decode_set_source(struct apr_ctx *ctx, + const struct apr_prores_info *info); + +/* Does a parsed source frame need other CAPTURE buffers than the format's? */ +static bool apr_decode_differs(const struct apr_ctx *ctx, + const struct apr_prores_info *info) +{ + return info->width != ctx->dst_fmt.width || + info->height != ctx->dst_fmt.height || + (info->chroma == 3) != ctx->raw->is444; +} + +/* + * Decode reached a frame whose geometry differs from the CAPTURE format: + * the stateful decoder's dynamic resolution change. Every frame from before + * it is given back first; the next CAPTURE buffer then goes back empty with + * LAST, the formats switch to the new geometry and SOURCE_CHANGE is queued. + * The frame stays first on OUTPUT, and no job runs until CAPTURE is + * restarted (STREAMOFF and STREAMON) or a START command resumes decoding. + * Called from device_run; sleeps. + */ +static void apr_decode_resolution_change(struct apr_ctx *ctx, + struct vb2_v4l2_buffer *src) +{ + struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; + struct apr_dev *apr = ctx->apr; + struct vb2_v4l2_buffer *dst; + unsigned long flags; + + wait_event(apr->idle_wq, !atomic_read(&ctx->inflight)); + /* Formats change under hw_lock for the G_FMT and TRY_FMT readers. */ + spin_lock_irqsave(&apr->hw_lock, flags); + apr_decode_set_source(ctx, &to_apr_buf(src)->info); + WRITE_ONCE(ctx->drc_pending, true); + dst = v4l2_m2m_dst_buf_remove(m2m); + spin_unlock_irqrestore(&apr->hw_lock, flags); + /* A query after the event sees the new format. */ + v4l2_event_queue_fh(&ctx->fh, &apr_source_change); + if (!WARN_ON(!dst)) { + vb2_set_plane_payload(&dst->vb2_buf, 0, 0); + dst->field = V4L2_FIELD_NONE; + dst->flags |= V4L2_BUF_FLAG_LAST; + v4l2_m2m_buf_done(dst, VB2_BUF_STATE_DONE); + } + v4l2_m2m_job_finish(apr->m2m_dev, m2m); } +/* + * The next CAPTURE buffer predates a resolution change and cannot hold a + * frame of the current format: give it back with ERROR and no payload, + * after the context's frames in the ring, and leave the source frame queued + * for a buffer that fits. Called from device_run; sleeps. + */ +static void apr_decode_small_dst(struct apr_ctx *ctx) +{ + struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; + struct apr_dev *apr = ctx->apr; + struct vb2_v4l2_buffer *dst; + unsigned long flags; + + wait_event(apr->idle_wq, !atomic_read(&ctx->inflight)); + spin_lock_irqsave(&apr->hw_lock, flags); + dst = v4l2_m2m_dst_buf_remove(m2m); + spin_unlock_irqrestore(&apr->hw_lock, flags); + if (!WARN_ON(!dst)) { + vb2_set_plane_payload(&dst->vb2_buf, 0, 0); + dst->field = V4L2_FIELD_NONE; + v4l2_m2m_buf_done(dst, VB2_BUF_STATE_ERROR); + } + v4l2_m2m_job_finish(apr->m2m_dev, m2m); +} + +/* + * Publish one job and, while the ring has room for another, finish the m2m + * job at once so the next one is prepared while the engine works. When the + * ring is full the m2m job stays running until a completion makes room, so + * device_run is only entered with room for one more descriptor. + */ static void apr_device_run(void *priv) { struct apr_ctx *ctx = priv; struct apr_dev *apr = ctx->apr; + struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; + u32 ring_bytes = apr->variant->ring_bytes; struct vb2_v4l2_buffer *src, *dst; struct apr_frame f; + struct apr_decode_frame decode; + struct apr_job *job; + u8 desc[APR_ENCODE_DESC_BYTES]; + u32 desc_bytes; unsigned long flags; + unsigned int slot; + bool hold; void *out; int ret; - src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); - dst = v4l2_m2m_next_dst_buf(ctx->fh.m2m_ctx); + src = v4l2_m2m_next_src_buf(m2m); + dst = v4l2_m2m_next_dst_buf(m2m); + if (ctx->decode && !to_apr_buf(src)->parse_err && + apr_decode_differs(ctx, &to_apr_buf(src)->info)) { + apr_decode_resolution_change(ctx, src); + return; + } + if (ctx->decode && vb2_plane_size(&dst->vb2_buf, 0) < + ctx->dst_fmt.plane_fmt[0].sizeimage) { + apr_decode_small_dst(ctx); + return; + } ret = pm_runtime_resume_and_get(apr->dev); if (ret < 0) { @@ -1465,46 +1946,143 @@ static void apr_device_run(void *priv) apr_finish_job(apr, ctx, ret); return; } - apr_fill_frame(ctx, src, dst, &f); - /* Mark the output invalid so a frame the engine never wrote is caught. */ - out = vb2_plane_vaddr(&dst->vb2_buf, 0); - if (!out) { - apr_finish_job(apr, ctx, -EINVAL); + /* device_run is entered with room in jobs[]; see apr_dev.bounce. */ + spin_lock_irqsave(&apr->hw_lock, flags); + slot = (apr->job_first + apr->njobs) % APR_MAX_INFLIGHT; + spin_unlock_irqrestore(&apr->hw_lock, flags); + if (ctx->decode) { + ret = apr_fill_decode_frame(ctx, src, dst, &apr->bounce[slot], + &decode); + desc_bytes = APR_DECODE_DESC_BYTES; + } else { + apr_fill_frame(ctx, src, dst, &f); + ret = 0; + desc_bytes = apr->variant->desc_bytes; + /* Mark output invalid so a frame the engine never wrote is caught. */ + out = vb2_plane_vaddr(&dst->vb2_buf, 0); + if (!out) + ret = -EINVAL; + else + memset(out, 0, 8); + } + if (ret) { + apr_finish_job(apr, ctx, ret); return; } - memset(out, 0, 8); spin_lock_irqsave(&apr->hw_lock, flags); + /* + * Nothing enters a hung ring or one being reset; the watchdog clears + * both and wakes idle_wq. An encode has no job id, so it only runs + * alone in the ring. + */ + while (apr->hung || apr->resetting || (!ctx->decode && apr->njobs)) { + spin_unlock_irqrestore(&apr->hw_lock, flags); + wait_event(apr->idle_wq, !READ_ONCE(apr->hung) && + !READ_ONCE(apr->resetting) && + (ctx->decode || !READ_ONCE(apr->njobs))); + spin_lock_irqsave(&apr->hw_lock, flags); + } if (apr->broken) { spin_unlock_irqrestore(&apr->hw_lock, flags); apr_finish_job(apr, ctx, -EIO); return; } - /* - * The engine's ring wrap protocol is not known, so start again at the - * beginning of the ring instead of wrapping. The engine is idle here. - */ - if (!apr->ring_ready || - apr->head + apr->variant->desc_bytes > apr->variant->ring_bytes) + if (!apr->ring_ready && !WARN_ON(apr->njobs)) apr_hw_init(apr); - ret = apr->variant->build_desc(&f, apr->ring + apr->head); + if (WARN_ON(apr_jobs_full(apr->njobs, apr->nencodes) || + apr_ring_free(apr->done, apr->head, ring_bytes) <= desc_bytes)) { + spin_unlock_irqrestore(&apr->hw_lock, flags); + apr_finish_job(apr, ctx, -EBUSY); + return; + } + if (ctx->decode) + decode.job_id = apr->next_id; + ret = ctx->decode ? apr_build_decode_desc(&decode, desc) : + apr->variant->build_desc(&f, desc); if (ret) { spin_unlock_irqrestore(&apr->hw_lock, flags); apr_finish_job(apr, ctx, ret); return; } - apr->head += apr->variant->desc_bytes; - apr->active = ctx; - apr->started = jiffies; + /* + * With the ring empty the engine is idle, so a DONE or ERROR still + * latched belongs to a job already given back. Clear it before this + * job can be taken for finished on it. The clear reaches the engine + * before the head write below. + */ + if (!apr->njobs) + apr_write(apr, APR_REG_IRQ_STATUS, APR_IRQ_DONE | APR_IRQ_ERROR); + apr_ring_write(apr->ring, ring_bytes, apr->head, desc, desc_bytes); + apr->head = apr_ring_advance(apr->head, desc_bytes, ring_bytes); + job = &apr->jobs[(apr->job_first + apr->njobs) % APR_MAX_INFLIGHT]; + WARN_ON(job != &apr->jobs[slot]); + *job = (struct apr_job){ + .ctx = ctx, + .src = v4l2_m2m_src_buf_remove(m2m), + .dst = v4l2_m2m_dst_buf_remove(m2m), + .end = apr->head, + .id = ctx->decode ? apr->next_id : 0, + .sequence = ctx->sequence++, + .bytes = ctx->dst_fmt.plane_fmt[0].sizeimage, + }; + WARN_ON(job->src != src || job->dst != dst); + if (!apr->njobs) + apr->progress = jiffies; + apr->njobs++; + if (!ctx->decode) + apr->nencodes++; + if (ctx->decode) + apr->next_id = apr_next_job_id(apr->next_id); + atomic_inc(&ctx->inflight); + atomic_inc(&apr->outstanding); /* Descriptor and buffers must be visible before the head moves. */ dma_wmb(); writel(apr->head, apr->regs + APR_REG_RING_HEAD); - spin_unlock_irqrestore(&apr->hw_lock, flags); + hold = apr_jobs_full(apr->njobs, apr->nencodes); + if (hold) + apr->held = ctx; schedule_delayed_work(&apr->watchdog, msecs_to_jiffies(APR_POLL_MS)); + spin_unlock_irqrestore(&apr->hw_lock, flags); + if (!hold) + v4l2_m2m_job_finish(apr->m2m_dev, m2m); +} + +/* A frame of another geometry is device_run's resolution change. */ +static int apr_job_ready(void *priv) +{ + struct apr_ctx *ctx = priv; + + return !READ_ONCE(ctx->drc_pending); +} + +static void apr_job_abort(void *priv) +{ + struct apr_ctx *ctx = priv; + struct apr_dev *apr = ctx->apr; + unsigned long flags; + unsigned int i; + + /* + * There is no cancellation opcode: the context's jobs still run to the + * end of the ring and only report cancelled. stop_streaming waits for + * them; other contexts' jobs in the same ring are not touched. + */ + spin_lock_irqsave(&apr->hw_lock, flags); + for (i = 0; i < apr->njobs; i++) { + struct apr_job *job = &apr->jobs[(apr->job_first + i) % + APR_MAX_INFLIGHT]; + + if (job->ctx == ctx) + job->err = -ECANCELED; + } + spin_unlock_irqrestore(&apr->hw_lock, flags); } static const struct v4l2_m2m_ops apr_m2m_ops = { .device_run = apr_device_run, + .job_ready = apr_job_ready, + .job_abort = apr_job_abort, }; /* ---- formats ----------------------------------------------------------- */ @@ -1526,12 +2104,22 @@ static const struct apr_fmt *apr_find_raw(u32 fourcc) */ static void apr_fill_raw(struct v4l2_pix_format_mplane *pix, const struct apr_fmt *fmt) { - u32 width = clamp_t(u32, ALIGN(pix->width, 2), APR_MIN_W, APR_MAX_W); + u32 width = clamp_t(u32, pix->width, APR_MIN_W, APR_MAX_W); u32 height = clamp_t(u32, pix->height, APR_MIN_H, APR_MAX_H); - u32 min_stride = ALIGN(width * fmt->bytes, 64); - u32 stride = ALIGN(pix->plane_fmt[0].bytesperline, 64); + u32 stride_align; + u32 min_stride; + u32 stride; u32 cstride; + if (!fmt->is444) + width = min_t(u32, ALIGN(width, 2), APR_MAX_W - 1); + if ((u64)width * height > APR_MAX_PIXELS) + height = APR_MAX_PIXELS / width; + /* An odd row count needs a 128-byte stride to align plane 1. */ + stride_align = height & 1 ? 128 : 64; + min_stride = ALIGN(width * fmt->bytes, stride_align); + stride = ALIGN(pix->plane_fmt[0].bytesperline, stride_align); + /* Accept padding up to one extra row width, as other drivers do. */ if (stride < min_stride || stride > 2 * min_stride) stride = min_stride; @@ -1566,25 +2154,63 @@ static void apr_fill_coded(struct v4l2_pix_format_mplane *dst, dst->plane_fmt[0].sizeimage = apr_coded_size(src->width, src->height, is444); } +static void apr_fill_decode_coded(struct v4l2_pix_format_mplane *pix) +{ + u32 size = pix->plane_fmt[0].sizeimage; + + pix->width = clamp_t(u32, pix->width, APR_MIN_W, APR_MAX_W); + pix->height = clamp_t(u32, pix->height, APR_MIN_H, APR_MAX_H); + if ((u64)pix->width * pix->height > APR_MAX_PIXELS) + pix->height = APR_MAX_PIXELS / pix->width; + pix->pixelformat = V4L2_PIX_FMT_PRORES; + pix->field = V4L2_FIELD_NONE; + pix->num_planes = 1; + pix->flags = 0; + memset(pix->reserved, 0, sizeof(pix->reserved)); + memset(pix->plane_fmt, 0, sizeof(pix->plane_fmt)); + pix->plane_fmt[0].sizeimage = clamp_t(u32, size, SZ_4K, SZ_256M); +} + static void apr_reset_fmts(struct apr_ctx *ctx) { - ctx->raw = &apr_raw_fmts[0]; + ctx->raw = ctx->decode ? &apr_raw_fmts[1] : &apr_raw_fmts[0]; memset(&ctx->src_fmt, 0, sizeof(ctx->src_fmt)); ctx->src_fmt.width = 1920; ctx->src_fmt.height = 1080; - apr_fill_raw(&ctx->src_fmt, ctx->raw); - apr_fill_coded(&ctx->dst_fmt, &ctx->src_fmt, ctx->raw->is444); + if (ctx->decode) { + ctx->src_fmt.plane_fmt[0].sizeimage = + apr_coded_size(1920, 1080, false); + apr_fill_decode_coded(&ctx->src_fmt); + ctx->dst_fmt = ctx->src_fmt; + apr_fill_raw(&ctx->dst_fmt, ctx->raw); + } else { + apr_fill_raw(&ctx->src_fmt, ctx->raw); + apr_fill_coded(&ctx->dst_fmt, &ctx->src_fmt, ctx->raw->is444); + } } static int apr_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { + struct apr_ctx *ctx = apr_file_to_ctx(file); + strscpy(cap->driver, APR_NAME, sizeof(cap->driver)); - strscpy(cap->card, "Apple ProRes encoder", sizeof(cap->card)); + strscpy(cap->card, ctx->decode ? "Apple ProRes decoder" : + "Apple ProRes encoder", sizeof(cap->card)); return 0; } static int apr_enum_fmt_out(struct file *file, void *priv, struct v4l2_fmtdesc *f) { + struct apr_ctx *ctx = apr_file_to_ctx(file); + + if (ctx->decode) { + if (f->index) + return -EINVAL; + f->pixelformat = V4L2_PIX_FMT_PRORES; + /* Size and chroma changes are reported with SOURCE_CHANGE. */ + f->flags = V4L2_FMT_FLAG_COMPRESSED | V4L2_FMT_FLAG_DYN_RESOLUTION; + return 0; + } if (f->index >= ARRAY_SIZE(apr_raw_fmts)) return -EINVAL; f->pixelformat = apr_raw_fmts[f->index].fourcc; @@ -1593,6 +2219,14 @@ static int apr_enum_fmt_out(struct file *file, void *priv, struct v4l2_fmtdesc * static int apr_enum_fmt_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f) { + struct apr_ctx *ctx = apr_file_to_ctx(file); + + if (ctx->decode) { + if (f->index >= ARRAY_SIZE(apr_raw_fmts)) + return -EINVAL; + f->pixelformat = apr_raw_fmts[f->index].fourcc; + return 0; + } if (f->index) return -EINVAL; f->pixelformat = V4L2_PIX_FMT_PRORES; @@ -1603,32 +2237,54 @@ static int apr_enum_fmt_cap(struct file *file, void *priv, struct v4l2_fmtdesc * static int apr_enum_framesizes(struct file *file, void *priv, struct v4l2_frmsizeenum *fs) { + const struct apr_fmt *fmt = apr_find_raw(fs->pixel_format); + if (fs->index || (fs->pixel_format != V4L2_PIX_FMT_PRORES && - !apr_find_raw(fs->pixel_format))) + !fmt)) return -EINVAL; fs->type = V4L2_FRMSIZE_TYPE_STEPWISE; fs->stepwise = (struct v4l2_frmsize_stepwise){ - APR_MIN_W, APR_MAX_W, 2, APR_MIN_H, APR_MAX_H, 1, + APR_MIN_W, APR_MAX_W, fmt && !fmt->is444 ? 2 : 1, + APR_MIN_H, APR_MAX_H, 1, }; return 0; } +/* + * A decoder's resolution change rewrites the formats from device_run, which + * does not hold vdev_lock; it holds hw_lock. + */ static int apr_g_fmt_out(struct file *file, void *priv, struct v4l2_format *f) { - f->fmt.pix_mp = apr_file_to_ctx(file)->src_fmt; + struct apr_ctx *ctx = apr_file_to_ctx(file); + unsigned long flags; + + spin_lock_irqsave(&ctx->apr->hw_lock, flags); + f->fmt.pix_mp = ctx->src_fmt; + spin_unlock_irqrestore(&ctx->apr->hw_lock, flags); return 0; } static int apr_g_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) { - f->fmt.pix_mp = apr_file_to_ctx(file)->dst_fmt; + struct apr_ctx *ctx = apr_file_to_ctx(file); + unsigned long flags; + + spin_lock_irqsave(&ctx->apr->hw_lock, flags); + f->fmt.pix_mp = ctx->dst_fmt; + spin_unlock_irqrestore(&ctx->apr->hw_lock, flags); return 0; } static int apr_try_fmt_out(struct file *file, void *priv, struct v4l2_format *f) { + struct apr_ctx *ctx = apr_file_to_ctx(file); const struct apr_fmt *fmt = apr_find_raw(f->fmt.pix_mp.pixelformat); + if (ctx->decode) { + apr_fill_decode_coded(&f->fmt.pix_mp); + return 0; + } apr_fill_raw(&f->fmt.pix_mp, fmt ?: &apr_raw_fmts[0]); return 0; } @@ -1637,7 +2293,24 @@ static int apr_try_fmt_out(struct file *file, void *priv, struct v4l2_format *f) static int apr_try_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) { struct apr_ctx *ctx = apr_file_to_ctx(file); - + const struct apr_fmt *fmt; + + if (ctx->decode) { + unsigned long flags; + bool valid, is444; + + spin_lock_irqsave(&ctx->apr->hw_lock, flags); + valid = ctx->source_valid; + is444 = ctx->decode_444; + f->fmt.pix_mp.width = ctx->src_fmt.width; + f->fmt.pix_mp.height = ctx->src_fmt.height; + spin_unlock_irqrestore(&ctx->apr->hw_lock, flags); + fmt = apr_find_raw(f->fmt.pix_mp.pixelformat); + if (!fmt || (valid && fmt->is444 != is444)) + fmt = &apr_raw_fmts[is444 ? 3 : 1]; + apr_fill_raw(&f->fmt.pix_mp, fmt); + return 0; + } apr_fill_coded(&f->fmt.pix_mp, &ctx->src_fmt, ctx->raw->is444); return 0; } @@ -1652,6 +2325,8 @@ static int apr_s_fmt_out(struct file *file, void *priv, struct v4l2_format *f) return -EBUSY; apr_try_fmt_out(file, priv, f); ctx->src_fmt = f->fmt.pix_mp; + if (ctx->decode) + return 0; ctx->raw = apr_find_raw(ctx->src_fmt.pixelformat); apr_fill_coded(&ctx->dst_fmt, &ctx->src_fmt, ctx->raw->is444); /* Keep the profile consistent with the chroma format. */ @@ -1670,6 +2345,8 @@ static int apr_s_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) return -EBUSY; apr_try_fmt_cap(file, priv, f); ctx->dst_fmt = f->fmt.pix_mp; + if (ctx->decode) + ctx->raw = apr_find_raw(ctx->dst_fmt.pixelformat); return 0; } @@ -1677,9 +2354,75 @@ static int apr_subscribe_event(struct v4l2_fh *fh, const struct v4l2_event_subsc { if (sub->type == V4L2_EVENT_EOS) return v4l2_event_subscribe(fh, sub, 0, NULL); + if (sub->type == V4L2_EVENT_SOURCE_CHANGE) + return v4l2_src_change_event_subscribe(fh, sub); return v4l2_ctrl_subscribe_event(fh, sub); } +/* + * A STOP with no OUTPUT buffer left in the m2m queue makes the m2m helper + * mark the next CAPTURE buffer LAST at once. With this context's jobs still + * in the ring their frames would follow that LAST buffer, so wait for them + * first. The check and the helper run under hw_lock: device_run moves a + * job's buffers into the ring under the same lock, so the helper sees the + * last OUTPUT buffer either queued or already given back. + */ +static int apr_stop_cmd(struct file *file, struct apr_ctx *ctx, void *cmd) +{ + struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; + struct apr_dev *apr = ctx->apr; + unsigned long flags; + int ret; + + for (;;) { + spin_lock_irqsave(&apr->hw_lock, flags); + if (v4l2_m2m_num_src_bufs_ready(m2m) || + !atomic_read(&ctx->inflight)) + break; + spin_unlock_irqrestore(&apr->hw_lock, flags); + wait_event(apr->idle_wq, !atomic_read(&ctx->inflight)); + } + ret = ctx->decode ? v4l2_m2m_decoder_cmd(file, m2m, cmd) : + v4l2_m2m_encoder_cmd(file, m2m, cmd); + spin_unlock_irqrestore(&apr->hw_lock, flags); + return ret; +} + +static int apr_encoder_cmd(struct file *file, void *priv, + struct v4l2_encoder_cmd *ec) +{ + struct apr_ctx *ctx = apr_file_to_ctx(file); + int ret; + + ret = v4l2_m2m_ioctl_try_encoder_cmd(file, priv, ec); + if (ret) + return ret; + if (ec->cmd == V4L2_ENC_CMD_STOP) + return apr_stop_cmd(file, ctx, ec); + return v4l2_m2m_ioctl_encoder_cmd(file, priv, ec); +} + +static int apr_decoder_cmd(struct file *file, void *priv, + struct v4l2_decoder_cmd *dc) +{ + struct apr_ctx *ctx = apr_file_to_ctx(file); + int ret; + + ret = v4l2_m2m_ioctl_try_decoder_cmd(file, priv, dc); + if (ret) + return ret; + if (dc->cmd == V4L2_DEC_CMD_STOP) + return apr_stop_cmd(file, ctx, dc); + ret = v4l2_m2m_ioctl_decoder_cmd(file, priv, dc); + if (ret) + return ret; + /* START resumes after a drain or a resolution change. */ + WRITE_ONCE(ctx->drc_pending, false); + vb2_clear_last_buffer_dequeued(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx)); + v4l2_m2m_try_schedule(ctx->fh.m2m_ctx); + return 0; +} + static const struct v4l2_ioctl_ops apr_ioctl_ops = { .vidioc_querycap = apr_querycap, .vidioc_enum_fmt_vid_out = apr_enum_fmt_out, @@ -1703,7 +2446,36 @@ static const struct v4l2_ioctl_ops apr_ioctl_ops = { .vidioc_streamoff = v4l2_m2m_ioctl_streamoff, .vidioc_try_encoder_cmd = v4l2_m2m_ioctl_try_encoder_cmd, - .vidioc_encoder_cmd = v4l2_m2m_ioctl_encoder_cmd, + .vidioc_encoder_cmd = apr_encoder_cmd, + + .vidioc_subscribe_event = apr_subscribe_event, + .vidioc_unsubscribe_event = v4l2_event_unsubscribe, +}; + +static const struct v4l2_ioctl_ops apr_decoder_ioctl_ops = { + .vidioc_querycap = apr_querycap, + .vidioc_enum_fmt_vid_out = apr_enum_fmt_out, + .vidioc_enum_fmt_vid_cap = apr_enum_fmt_cap, + .vidioc_enum_framesizes = apr_enum_framesizes, + .vidioc_g_fmt_vid_out_mplane = apr_g_fmt_out, + .vidioc_g_fmt_vid_cap_mplane = apr_g_fmt_cap, + .vidioc_try_fmt_vid_out_mplane = apr_try_fmt_out, + .vidioc_try_fmt_vid_cap_mplane = apr_try_fmt_cap, + .vidioc_s_fmt_vid_out_mplane = apr_s_fmt_out, + .vidioc_s_fmt_vid_cap_mplane = apr_s_fmt_cap, + + .vidioc_reqbufs = v4l2_m2m_ioctl_reqbufs, + .vidioc_querybuf = v4l2_m2m_ioctl_querybuf, + .vidioc_qbuf = v4l2_m2m_ioctl_qbuf, + .vidioc_dqbuf = v4l2_m2m_ioctl_dqbuf, + .vidioc_prepare_buf = v4l2_m2m_ioctl_prepare_buf, + .vidioc_create_bufs = v4l2_m2m_ioctl_create_bufs, + .vidioc_expbuf = v4l2_m2m_ioctl_expbuf, + .vidioc_streamon = v4l2_m2m_ioctl_streamon, + .vidioc_streamoff = v4l2_m2m_ioctl_streamoff, + + .vidioc_try_decoder_cmd = v4l2_m2m_ioctl_try_decoder_cmd, + .vidioc_decoder_cmd = apr_decoder_cmd, .vidioc_subscribe_event = apr_subscribe_event, .vidioc_unsubscribe_event = v4l2_event_unsubscribe, @@ -1735,22 +2507,96 @@ static int apr_buf_prepare(struct vb2_buffer *vb) struct apr_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); u32 size = apr_q_fmt(ctx, vb->type)->plane_fmt[0].sizeimage; - if (vb2_plane_size(vb, 0) < size) + /* + * A decoder's CAPTURE format may grow at a resolution change before + * the client has seen SOURCE_CHANGE, and the old buffers must still + * queue: the LAST buffer of the change is one of them. queue_setup + * sized them for the format of their time; device_run gives back one + * too small for the current format instead of decoding into it. + */ + if (vb2_plane_size(vb, 0) < size && + !(ctx->decode && !V4L2_TYPE_IS_OUTPUT(vb->type))) return -EINVAL; if (V4L2_TYPE_IS_OUTPUT(vb->type)) { - /* The engine always reads the whole padded surface. */ - vb2_set_plane_payload(vb, 0, size); + if (ctx->decode) { + struct apr_buf *buf = to_apr_buf(to_vb2_v4l2_buffer(vb)); + u32 payload = vb2_get_plane_payload(vb, 0); + u32 offset = vb->planes[0].data_offset; + u8 *data = vb2_plane_vaddr(vb, 0); + + if (payload < 28 || offset > payload) + return -EINVAL; + /* A frame that does not parse fails its job, not QBUF. */ + buf->parse_err = data ? + apr_parse_frame(data + offset, payload - offset, + &buf->info) : -EINVAL; + } else { + /* The encoder always reads the whole padded surface. */ + vb2_set_plane_payload(vb, 0, size); + } } else { vb2_set_plane_payload(vb, 0, 0); } return 0; } +/* Make a parsed frame's geometry the stream's. Called with hw_lock held. */ +static void apr_decode_set_source(struct apr_ctx *ctx, + const struct apr_prores_info *info) +{ + unsigned int i; + + ctx->source_valid = true; + ctx->decode_444 = info->chroma == 3; + ctx->src_fmt.width = info->width; + ctx->src_fmt.height = info->height; + for (i = 0; i < ARRAY_SIZE(apr_raw_fmts); i++) { + if (apr_raw_fmts[i].is444 == ctx->decode_444 && + apr_raw_fmts[i].bytes == ctx->raw->bytes) { + ctx->raw = &apr_raw_fmts[i]; + break; + } + } + /* A new geometry starts from the minimum stride. */ + if (ctx->dst_fmt.width != info->width || + ctx->dst_fmt.height != info->height) + ctx->dst_fmt.plane_fmt[0].bytesperline = 0; + ctx->dst_fmt.width = info->width; + ctx->dst_fmt.height = info->height; + apr_fill_raw(&ctx->dst_fmt, ctx->raw); +} + +/* + * Before CAPTURE streams, the next frame to decode sets the formats, and a + * new geometry is reported at once (initial setup, or a change while CAPTURE + * is stopped). While CAPTURE streams, device_run handles a change when + * decode reaches the frame, after the frames queued before it. + */ +static void apr_decode_source_change(struct apr_ctx *ctx, + struct vb2_v4l2_buffer *vbuf) +{ + struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; + struct apr_buf *buf = to_apr_buf(vbuf); + unsigned long flags; + + if (buf->parse_err || vb2_is_streaming(v4l2_m2m_get_dst_vq(m2m))) + return; + if (ctx->source_valid && (v4l2_m2m_num_src_bufs_ready(m2m) || + !apr_decode_differs(ctx, &buf->info))) + return; + spin_lock_irqsave(&ctx->apr->hw_lock, flags); + apr_decode_set_source(ctx, &buf->info); + spin_unlock_irqrestore(&ctx->apr->hw_lock, flags); + v4l2_event_queue_fh(&ctx->fh, &apr_source_change); +} + static void apr_buf_queue(struct vb2_buffer *vb) { struct apr_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); + if (ctx->decode && V4L2_TYPE_IS_OUTPUT(vb->type)) + apr_decode_source_change(ctx, vbuf); if (!V4L2_TYPE_IS_OUTPUT(vb->type) && vb2_is_streaming(vb->vb2_queue) && v4l2_m2m_dst_buf_is_last(ctx->fh.m2m_ctx)) { @@ -1766,7 +2612,7 @@ static int apr_start_streaming(struct vb2_queue *q, unsigned int count) { struct apr_ctx *ctx = vb2_get_drv_priv(q); - if (V4L2_TYPE_IS_OUTPUT(q->type)) { + if (V4L2_TYPE_IS_OUTPUT(q->type) && !ctx->decode) { if (ctx->raw->is444 != apr_profile_is_444(v4l2_ctrl_g_ctrl(ctx->profile))) { struct vb2_v4l2_buffer *vbuf; @@ -1787,6 +2633,12 @@ static void apr_stop_streaming(struct vb2_queue *q) struct apr_ctx *ctx = vb2_get_drv_priv(q); struct vb2_v4l2_buffer *vbuf; + /* + * The engine still owns this context's jobs in the ring. The m2m core + * cancelled the job being prepared; wait for the ring ones, which the + * watchdog completes or fails within APR_TIMEOUT_MS of no progress. + */ + wait_event(ctx->apr->idle_wq, !atomic_read(&ctx->inflight)); for (;;) { vbuf = V4L2_TYPE_IS_OUTPUT(q->type) ? v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx) : @@ -1795,8 +2647,11 @@ static void apr_stop_streaming(struct vb2_queue *q) break; v4l2_m2m_buf_done(vbuf, VB2_BUF_STATE_ERROR); } + /* Restarting CAPTURE ends a resolution change. */ + if (!V4L2_TYPE_IS_OUTPUT(q->type)) + WRITE_ONCE(ctx->drc_pending, false); v4l2_m2m_update_stop_streaming_state(ctx->fh.m2m_ctx, q); - if (V4L2_TYPE_IS_OUTPUT(q->type)) + if (V4L2_TYPE_IS_OUTPUT(q->type) && !ctx->decode) v4l2_ctrl_grab(ctx->profile, false); if (V4L2_TYPE_IS_OUTPUT(q->type) && v4l2_m2m_has_stopped(ctx->fh.m2m_ctx)) { static const struct v4l2_event eos = { .type = V4L2_EVENT_EOS }; @@ -1821,7 +2676,7 @@ static int apr_queue_init(void *priv, struct vb2_queue *src, struct vb2_queue *d src->type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; src->io_modes = VB2_MMAP | VB2_DMABUF; src->drv_priv = ctx; - src->buf_struct_size = sizeof(struct v4l2_m2m_buffer); + src->buf_struct_size = sizeof(struct apr_buf); src->ops = &apr_qops; src->mem_ops = &vb2_dma_contig_memops; src->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY; @@ -1859,7 +2714,11 @@ static int apr_init_ctrls(struct apr_ctx *ctx) { struct v4l2_ctrl_handler *hdl = &ctx->hdl; - v4l2_ctrl_handler_init(hdl, 1); + v4l2_ctrl_handler_init(hdl, ctx->decode ? 0 : 1); + if (ctx->decode) { + ctx->fh.ctrl_handler = hdl; + return 0; + } /* The profile must match the raw format's chroma; checked at STREAMON. */ ctx->profile = v4l2_ctrl_new_std_menu(hdl, &apr_ctrl_ops, V4L2_CID_MPEG_VIDEO_PRORES_PROFILE, @@ -1885,6 +2744,7 @@ static int apr_open(struct file *file) if (!ctx) return -ENOMEM; ctx->apr = apr; + ctx->decode = video_devdata(file) == &apr->dec_vdev; apr_reset_fmts(ctx); v4l2_fh_init(&ctx->fh, video_devdata(file)); ret = apr_init_ctrls(ctx); @@ -1937,10 +2797,16 @@ static int apr_runtime_suspend(struct device *dev) struct apr_dev *apr = dev_get_drvdata(dev); unsigned long flags; - /* Registers do not survive the power domain going off. */ + /* + * Registers do not survive the power domain going off, which resets + * the engine: a ring found hung with no job left needs nothing more. + */ spin_lock_irqsave(&apr->hw_lock, flags); apr->ring_ready = false; + apr->hung = false; spin_unlock_irqrestore(&apr->hw_lock, flags); + /* Every job holds a runtime PM reference, so no copy is in use. */ + apr_bounce_free_all(apr); return 0; } @@ -1954,6 +2820,8 @@ static int apr_suspend(struct device *dev) struct apr_dev *apr = dev_get_drvdata(dev); v4l2_m2m_suspend(apr->m2m_dev); + /* No new job starts now; let the ring drain. */ + wait_event(apr->idle_wq, !atomic_read(&apr->outstanding)); return pm_runtime_force_suspend(dev); } @@ -1982,6 +2850,7 @@ static void apr_cleanup(void *data) if (apr->m2m_dev) v4l2_m2m_release(apr->m2m_dev); v4l2_device_unregister(&apr->v4l2_dev); + apr_bounce_free_all(apr); } /* @@ -2062,6 +2931,9 @@ static int apr_probe(struct platform_device *pdev) mutex_init(&apr->vdev_lock); spin_lock_init(&apr->hw_lock); INIT_DELAYED_WORK(&apr->watchdog, apr_watchdog); + init_waitqueue_head(&apr->idle_wq); + /* The ring always has room for every job the driver keeps in flight. */ + BUILD_BUG_ON(APR_MAX_INFLIGHT * APR_ENCODE_DESC_BYTES >= APR_RING_BYTES); platform_set_drvdata(pdev, apr); for (i = 0; i < apr->variant->num_regs; i++) { @@ -2151,10 +3023,10 @@ static int apr_probe(struct platform_device *pdev) return dev_err_probe(dev, -EINVAL, "statistics area larger than %zu bytes\n", apr->stats_size); } - dev_info(dev, "ProRes encoder, id %#x\n", apr_read(apr, APR_REG_ID)); + dev_info(dev, "ProRes codec, id %#x\n", apr_read(apr, APR_REG_ID)); pm_runtime_put_autosuspend(dev); - vdev = &apr->vdev; + vdev = &apr->enc_vdev; strscpy(vdev->name, APR_NAME, sizeof(vdev->name)); vdev->fops = &apr_fops; vdev->ioctl_ops = &apr_ioctl_ops; @@ -2164,14 +3036,36 @@ static int apr_probe(struct platform_device *pdev) vdev->vfl_dir = VFL_DIR_M2M; vdev->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING; video_set_drvdata(vdev, apr); - return video_register_device(vdev, VFL_TYPE_VIDEO, APPLE_M2M_VIDEO_NR); + ret = video_register_device(vdev, VFL_TYPE_VIDEO, APPLE_M2M_VIDEO_NR); + if (ret) + return ret; + + /* + * Every APR engine is a ProRes encode and decode engine (the decode + * descriptor shares the encoder's ring), so each one gets a decoder node. + */ + vdev = &apr->dec_vdev; + strscpy(vdev->name, APR_NAME "-decode", sizeof(vdev->name)); + vdev->fops = &apr_fops; + vdev->ioctl_ops = &apr_decoder_ioctl_ops; + vdev->release = video_device_release_empty; + vdev->lock = &apr->vdev_lock; + vdev->v4l2_dev = &apr->v4l2_dev; + vdev->vfl_dir = VFL_DIR_M2M; + vdev->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING; + video_set_drvdata(vdev, apr); + ret = video_register_device(vdev, VFL_TYPE_VIDEO, APPLE_M2M_VIDEO_NR); + if (ret) + video_unregister_device(&apr->enc_vdev); + return ret; } static void apr_remove(struct platform_device *pdev) { struct apr_dev *apr = platform_get_drvdata(pdev); - video_unregister_device(&apr->vdev); + video_unregister_device(&apr->dec_vdev); + video_unregister_device(&apr->enc_vdev); } static const struct of_device_id apr_of_match[] = { @@ -2196,7 +3090,7 @@ static struct platform_driver apr_driver = { }; module_platform_driver(apr_driver); -MODULE_DESCRIPTION("Apple ProRes encoder"); +MODULE_DESCRIPTION("Apple ProRes codec"); MODULE_LICENSE("GPL"); MODULE_FIRMWARE(APRI_T6041_FIRMWARE_NAME); MODULE_FIRMWARE(APRI_T6050_FIRMWARE_NAME); diff --git a/drivers/media/platform/apple/prores/apple-prores-test.c b/drivers/media/platform/apple/prores/apple-prores-test.c index 7e6fdd60199f8f..b2f1f22c75d82c 100644 --- a/drivers/media/platform/apple/prores/apple-prores-test.c +++ b/drivers/media/platform/apple/prores/apple-prores-test.c @@ -605,6 +605,608 @@ static void apr_test_apri_row_rejects(struct kunit *test) apr_test_apri_rows_reject(test, APRI_SYSTEM_BLOCK, 0, 8, 0x100); } +static void apr_test_decode_desc(struct kunit *test) +{ + struct apr_decode_frame f = { + .width = 320, .height = 240, .output = APR_INPUT_422_16, + .luma_stride = 640, .chroma_stride = 640, + .input = 0x10000100000ULL, .luma = 0x10000200000ULL, + .chroma = 0x10000300000ULL, .job_id = 0x1234, + }; + u8 *d = kunit_kmalloc(test, APR_DECODE_DESC_BYTES + 1, GFP_KERNEL); + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, d); + memset(d, 0xa5, APR_DECODE_DESC_BYTES + 1); + KUNIT_ASSERT_EQ(test, apr_build_decode_desc(&f, d), 0); + KUNIT_EXPECT_EQ(test, d[APR_DECODE_DESC_BYTES], 0xa5); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(d), 0x1234120b); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(d + 4), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(d + 8), f.input); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x14), 320); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x16), 240); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x1c), 320); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x1e), 240); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x20), 10); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x22), 10); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(d + 0x28), f.luma); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(d + 0x30), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(d + 0x38), f.chroma); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(d + 0x40), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(d + 0x48), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(d + 0x90), 3); + for (i = 0x94; i < APR_DECODE_DESC_BYTES; i++) + KUNIT_EXPECT_EQ_MSG(test, d[i], 0, "reserved byte %#x", i); + + f.output = APR_INPUT_444_16; + f.chroma_stride = 1280; + f.bottom_field_first = true; + KUNIT_ASSERT_EQ(test, apr_build_decode_desc(&f, d), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(d), 0x1234520f); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x22), 20); + f.luma_stride = 600; + KUNIT_EXPECT_EQ(test, apr_build_decode_desc(&f, d), -EINVAL); +} + +static u8 *apr_test_bitstream_size(struct kunit *test, u32 width, u32 height, + bool interlaced, size_t *bytes) +{ + u32 slices = apr_slice_count(width, interlaced ? + DIV_ROUND_UP(height, 2) : height, 3); + u32 picture_size = 8 + 2 * slices + 6 * slices; + u32 pictures = interlaced ? 2 : 1; + u32 frame_size = 28 + pictures * picture_size; + u8 *frame = kunit_kzalloc(test, frame_size, GFP_KERNEL); + u32 offset = 28; + unsigned int i, p; + + if (!frame) + return NULL; + put_unaligned_be32(frame_size, frame); + memcpy(frame + 4, "icpf", 4); + put_unaligned_be16(20, frame + 8); + put_unaligned_be16(0, frame + 10); + memcpy(frame + 12, "kunt", 4); + put_unaligned_be16(width, frame + 16); + put_unaligned_be16(height, frame + 18); + frame[20] = 2 << 6 | (interlaced ? 1 << 2 : 0); + frame[22] = 1; + frame[23] = 1; + frame[24] = 1; + for (p = 0; p < pictures; p++) { + u8 *picture = frame + offset; + + picture[0] = 8 << 3; + put_unaligned_be32(picture_size, picture + 1); + put_unaligned_be16(slices, picture + 5); + picture[7] = 3 << 4; + for (i = 0; i < slices; i++) { + put_unaligned_be16(6, picture + 8 + 2 * i); + /* A 6-byte slice header with empty Y and Cb data. */ + picture[8 + 2 * slices + 6 * i] = 6 << 3; + } + offset += picture_size; + } + *bytes = frame_size; + return frame; +} + +static u8 *apr_test_bitstream(struct kunit *test, bool interlaced, size_t *bytes) +{ + return apr_test_bitstream_size(test, 320, 240, interlaced, bytes); +} + +static void apr_test_parse_frame(struct kunit *test) +{ + struct apr_prores_info info; + size_t bytes; + u8 *frame = apr_test_bitstream(test, false, &bytes); + + KUNIT_ASSERT_NOT_NULL(test, frame); + KUNIT_ASSERT_EQ(test, apr_parse_frame(frame, bytes, &info), 0); + KUNIT_EXPECT_EQ(test, info.frame_size, (u32)bytes); + KUNIT_EXPECT_EQ(test, info.width, 320U); + KUNIT_EXPECT_EQ(test, info.height, 240U); + KUNIT_EXPECT_EQ(test, info.chroma, (u8)2); + KUNIT_EXPECT_EQ(test, info.pictures, (u8)1); + KUNIT_EXPECT_EQ(test, info.slices[0], 45U); + KUNIT_EXPECT_EQ(test, info.picture_offset[0], 28U); + + put_unaligned_be32(bytes - 1, frame); + KUNIT_EXPECT_EQ(test, apr_parse_frame(frame, bytes, &info), -EINVAL); + put_unaligned_be32(bytes, frame); + frame[4] = 'x'; + KUNIT_EXPECT_EQ(test, apr_parse_frame(frame, bytes, &info), -EINVAL); +} + +static void apr_test_parse_interlaced(struct kunit *test) +{ + struct apr_prores_info info; + size_t bytes; + u8 *frame = apr_test_bitstream(test, true, &bytes); + + KUNIT_ASSERT_NOT_NULL(test, frame); + KUNIT_ASSERT_EQ(test, apr_parse_frame(frame, bytes, &info), 0); + KUNIT_EXPECT_EQ(test, info.frame_type, (u8)1); + KUNIT_EXPECT_EQ(test, info.pictures, (u8)2); + KUNIT_EXPECT_EQ(test, info.slices[0], 24U); + KUNIT_EXPECT_EQ(test, info.slices[1], 24U); + KUNIT_EXPECT_EQ(test, info.picture_offset[1], + info.picture_offset[0] + info.picture_size[0]); +} + +/* 1080p has 1020 slices: the table is read in several blocks. */ +static void apr_test_parse_many_slices(struct kunit *test) +{ + struct apr_prores_info info; + size_t bytes; + u8 *frame = apr_test_bitstream_size(test, 1920, 1080, false, &bytes); + u8 *table; + + KUNIT_ASSERT_NOT_NULL(test, frame); + KUNIT_ASSERT_EQ(test, apr_parse_frame(frame, bytes, &info), 0); + KUNIT_EXPECT_EQ(test, info.slices[0], 1020U); + table = frame + 28 + 8; + /* A bad size in the last, partial block is still found. */ + put_unaligned_be16(5, table + 2 * 1019); + KUNIT_EXPECT_EQ(test, apr_parse_frame(frame, bytes, &info), -EINVAL); + put_unaligned_be16(6, table + 2 * 1019); + /* So is one just past the first block. */ + put_unaligned_be16(0, table + 2 * 128); + KUNIT_EXPECT_EQ(test, apr_parse_frame(frame, bytes, &info), -EINVAL); + put_unaligned_be16(6, table + 2 * 128); + /* And slices that together overrun the picture. */ + put_unaligned_be16(7, table + 2 * 500); + KUNIT_EXPECT_EQ(test, apr_parse_frame(frame, bytes, &info), -EINVAL); + put_unaligned_be16(6, table + 2 * 500); + KUNIT_EXPECT_EQ(test, apr_parse_frame(frame, bytes, &info), 0); +} + +/* + * The decode descriptor has no input length, so the engine reads as far as the + * frame's own sizes say. Each of these frames points past its payload and + * must be rejected before a descriptor is built. Every frame is parsed from an + * allocation exactly as long as the payload, so an over-read is a KASAN error. + * + * Progressive fixture: frame header at 8, picture at 28 (8-byte header, + * 45-entry slice table, 45 slices of 6 bytes), 396 bytes in all. + */ +#define APR_TP_PIC 28U +#define APR_TP_SLICES 45U +#define APR_TP_TABLE (APR_TP_PIC + 8) +#define APR_TP_DATA (APR_TP_TABLE + 2 * APR_TP_SLICES) +#define APR_TP_SIZE (8 + 8 * APR_TP_SLICES) +#define APR_TP_BYTES (APR_TP_PIC + APR_TP_SIZE) + +/* Parse the first @bytes of @frame from a buffer exactly that long. */ +static int apr_test_parse_at(struct kunit *test, const u8 *frame, size_t bytes) +{ + struct apr_prores_info info; + u8 *copy = kunit_kmalloc(test, bytes, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, copy); + memcpy(copy, frame, bytes); + return apr_parse_frame(copy, bytes, &info); +} + +/* A progressive fixture with @extra zero bytes of room after it. */ +static u8 *apr_test_room(struct kunit *test, size_t extra, size_t *bytes) +{ + u8 *frame = apr_test_bitstream(test, false, bytes); + u8 *room; + + KUNIT_ASSERT_NOT_NULL(test, frame); + KUNIT_ASSERT_EQ(test, *bytes, (size_t)APR_TP_BYTES); + room = kunit_kzalloc(test, *bytes + extra, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, room); + memcpy(room, frame, *bytes); + return room; +} + +static void apr_test_oob_exact_fit(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 1, &bytes); + struct apr_prores_info info; + u8 *last = frame + APR_TP_TABLE + 2 * (APR_TP_SLICES - 1); + + /* Header, table and slices fill the picture and the frame exactly. */ + KUNIT_ASSERT_EQ(test, apr_parse_frame(frame, bytes, &info), 0); + KUNIT_EXPECT_EQ(test, info.picture_offset[0] + info.picture_size[0], + info.frame_size); + KUNIT_EXPECT_EQ(test, info.picture_size[0], APR_TP_SIZE); + + /* One more byte in the last slice, the picture and the frame fits too. */ + put_unaligned_be16(7, last); + put_unaligned_be32(APR_TP_SIZE + 1, frame + APR_TP_PIC + 1); + put_unaligned_be32(APR_TP_BYTES + 1, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes + 1), 0); + + /* An encoder may leave the deprecated slice count at 0. */ + put_unaligned_be16(0, frame + APR_TP_PIC + 5); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes + 1), 0); +} + +static void apr_test_oob_frame_size(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 4096, &bytes); + + /* The frame claims more bytes than were queued. */ + put_unaligned_be32(bytes + 1, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be32(bytes + 4096, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be32(U32_MAX, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* bytesused one short of an otherwise valid frame. */ + put_unaligned_be32(bytes, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes - 1), -EINVAL); + + /* Truncated by one byte with the frame size rewritten to match. */ + put_unaligned_be32(bytes - 1, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes - 1), -EINVAL); + + /* Shorter than any frame header. */ + put_unaligned_be32(27, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, 27), -EINVAL); +} + +static void apr_test_oob_frame_header(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 0, &bytes); + + /* Frame header one byte past the frame, then filling it entirely. */ + put_unaligned_be16(bytes - 8 + 1, frame + 8); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(bytes - 8, frame + 8); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(U16_MAX, frame + 8); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* Quantisation matrices flagged but not inside the frame header. */ + put_unaligned_be16(20, frame + 8); + frame[8 + 19] = 3; + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + frame[8 + 19] = 0; + + /* Picture header shorter than its fixed fields. */ + frame[APR_TP_PIC] = 7 << 3; + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); +} + +static void apr_test_oob_picture_size(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 0, &bytes); + u8 *size = frame + APR_TP_PIC + 1; + + /* The picture runs one byte, 64 KiB and 4 GiB past the payload. */ + put_unaligned_be32(APR_TP_SIZE + 1, size); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be32(APR_TP_SIZE + SZ_64K, size); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be32(U32_MAX, size); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* Its slices must fit a picture one byte shorter. */ + put_unaligned_be32(APR_TP_SIZE - 1, size); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* Pictures must account for every byte of the frame. */ + frame = apr_test_room(test, 1, &bytes); + put_unaligned_be32(bytes + 1, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes + 1), -EINVAL); +} + +static void apr_test_oob_slice_table(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 0, &bytes); + u32 table_end = 8 + 2 * APR_TP_SLICES; + + /* The slice table ends one byte past the picture (and the frame). */ + put_unaligned_be32(table_end - 1, frame + APR_TP_PIC + 1); + put_unaligned_be32(APR_TP_PIC + table_end - 1, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, APR_TP_PIC + table_end - 1), + -EINVAL); + + /* The in-band slice count asks for one more table entry. */ + frame = apr_test_room(test, 0, &bytes); + put_unaligned_be16(APR_TP_SLICES + 1, frame + APR_TP_PIC + 5); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(U16_MAX, frame + APR_TP_PIC + 5); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* + * Smaller slices mean more of them (75 at 320x240): the table the + * engine walks grows with log2_slice even with no in-band count. + */ + put_unaligned_be16(0, frame + APR_TP_PIC + 5); + frame[APR_TP_PIC + 7] = 2 << 4; + KUNIT_EXPECT_EQ(test, apr_slice_count(320, 240, 2), 75U); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); +} + +static void apr_test_oob_slice_sizes(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 0, &bytes); + u8 *table = frame + APR_TP_TABLE; + + /* The last slice ends one byte past the picture and the payload. */ + put_unaligned_be16(7, table + 2 * (APR_TP_SLICES - 1)); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(U16_MAX, table + 2 * (APR_TP_SLICES - 1)); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* A large early slice pushes every later one past the end. */ + put_unaligned_be16(6, table + 2 * (APR_TP_SLICES - 1)); + put_unaligned_be16(U16_MAX, table); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* A slice too short for its own header. */ + put_unaligned_be16(5, table); + put_unaligned_be16(7, table + 2); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); +} + +static void apr_test_oob_slice_headers(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 0, &bytes); + u8 *last = frame + APR_TP_DATA + 6 * (APR_TP_SLICES - 1); + + /* Coded Y and Cb data run one byte past the last slice. */ + put_unaligned_be16(1, last + 2); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(0, last + 2); + put_unaligned_be16(U16_MAX, last + 4); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(0, last + 4); + + /* A slice header longer than the slice. */ + last[0] = 7 << 3; + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + last[0] = 6 << 3; + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), 0); + + /* With alpha the Cr size is in the header too: 6 bytes is too short. */ + frame[8 + 12] = 3 << 6; + frame[8 + 17] = 1; + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); +} + +static void apr_test_oob_second_field(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_bitstream(test, true, &bytes); + struct apr_prores_info info; + u32 second; + + KUNIT_ASSERT_NOT_NULL(test, frame); + KUNIT_ASSERT_EQ(test, apr_parse_frame(frame, bytes, &info), 0); + second = info.picture_offset[1]; + + /* The bottom field runs one byte past the payload. */ + put_unaligned_be32(info.picture_size[1] + 1, frame + second + 1); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be32(U32_MAX, frame + second + 1); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be32(info.picture_size[1], frame + second + 1); + + /* Its last slice ends one byte past the payload. */ + put_unaligned_be16(7, frame + second + 8 + 2 * (info.slices[1] - 1)); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(6, frame + second + 8 + 2 * (info.slices[1] - 1)); + + /* The frame stops one byte into, and right at, the bottom field. */ + put_unaligned_be32(second + 1, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, second + 1), -EINVAL); + put_unaligned_be32(second, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, second), -EINVAL); + put_unaligned_be32(bytes, frame); + + /* The top field grows by a byte, so the bottom one is misplaced. */ + put_unaligned_be32(info.picture_size[0] + 1, frame + info.picture_offset[0] + 1); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); +} + +static void apr_test_ring_accounting(struct kunit *test) +{ + u8 *ring = kunit_kzalloc(test, APR_RING_BYTES, GFP_KERNEL); + u8 *desc = kunit_kmalloc(test, APR_ENCODE_DESC_BYTES, GFP_KERNEL); + u32 ptr = APR_RING_BYTES - 0x100; + u32 next; + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, ring); + KUNIT_ASSERT_NOT_NULL(test, desc); + next = apr_ring_advance(0, APR_DECODE_DESC_BYTES, APR_RING_BYTES); + KUNIT_EXPECT_EQ(test, next, 0x100U); + next = apr_ring_advance(0x100, APR_ENCODE_DESC_BYTES, APR_RING_BYTES); + KUNIT_EXPECT_EQ(test, next, 0x280U); + next = apr_ring_advance(ptr, APR_ENCODE_DESC_BYTES, APR_RING_BYTES); + KUNIT_EXPECT_EQ(test, next, APR_RING_GENERATION | 0x80U); + next = apr_ring_advance(APR_RING_GENERATION | APR_RING_BYTES - 0x80, + APR_DECODE_DESC_BYTES, APR_RING_BYTES); + KUNIT_EXPECT_EQ(test, next, 0x80U); + for (i = 0; i < APR_ENCODE_DESC_BYTES; i++) + desc[i] = i; + apr_ring_write(ring, APR_RING_BYTES, ptr, desc, APR_ENCODE_DESC_BYTES); + KUNIT_EXPECT_MEMEQ(test, ring + ptr, desc, 0x100); + KUNIT_EXPECT_MEMEQ(test, ring, desc + 0x100, 0x80); +} + +static void apr_test_ring_space(struct kunit *test) +{ + const u32 r = APR_RING_BYTES, g = APR_RING_GENERATION; + + KUNIT_EXPECT_EQ(test, apr_ring_distance(0, 0x100, r), 0x100U); + KUNIT_EXPECT_EQ(test, apr_ring_distance(0x100, 0x100, r), 0U); + /* Across the end of the ring, in either generation. */ + KUNIT_EXPECT_EQ(test, apr_ring_distance(r - 0x80, g | 0x80, r), 0x100U); + KUNIT_EXPECT_EQ(test, apr_ring_distance(g | (r - 0x80), 0x80, r), 0x100U); + /* Same offset, other generation: a whole ring apart. */ + KUNIT_EXPECT_EQ(test, apr_ring_distance(0x100, g | 0x100, r), r); + + KUNIT_EXPECT_EQ(test, apr_ring_free(0, 0, r), r); + KUNIT_EXPECT_EQ(test, apr_ring_free(0, 0x800, r), r - 0x800); + KUNIT_EXPECT_EQ(test, apr_ring_free(r - 0x80, g | 0x80, r), r - 0x100); + KUNIT_EXPECT_EQ(test, apr_ring_free(g | 0x100, 0x100, r), 0U); + /* The deepest ring the driver builds still has room. */ + KUNIT_EXPECT_GT(test, apr_ring_free(0, APR_MAX_INFLIGHT * + APR_ENCODE_DESC_BYTES, r), + (u32)APR_ENCODE_DESC_BYTES); +} + +static void apr_test_ring_tail(struct kunit *test) +{ + const u32 r = APR_RING_BYTES, g = APR_RING_GENERATION; + + KUNIT_EXPECT_TRUE(test, apr_ring_passed(0, 0x100, 0x100, r)); + KUNIT_EXPECT_TRUE(test, apr_ring_passed(0, 0x100, 0x300, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_passed(0, 0x100, 0x80, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_passed(0, 0x100, 0, r)); + KUNIT_EXPECT_TRUE(test, apr_ring_passed(r - 0x80, g | 0x80, g | 0x80, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_passed(r - 0x80, g | 0x80, r - 0x40, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_passed(g | (r - 0x80), 0x80, 0x40, r)); + KUNIT_EXPECT_TRUE(test, apr_ring_passed(g | (r - 0x80), 0x80, 0x80, r)); + + KUNIT_EXPECT_TRUE(test, apr_ring_tail_valid(0x100, 0x100, 0x400, r)); + KUNIT_EXPECT_TRUE(test, apr_ring_tail_valid(0x100, 0x400, 0x400, r)); + KUNIT_EXPECT_TRUE(test, apr_ring_tail_valid(0x100, 0x280, 0x400, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_tail_valid(0x100, 0x500, 0x400, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_tail_valid(0x100, 0x80, 0x400, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_tail_valid(0x100, g | 0x200, 0x400, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_tail_valid(0, r, 0x400, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_tail_valid(0, BIT(25), 0x400, r)); + KUNIT_EXPECT_TRUE(test, apr_ring_tail_valid(r - 0x80, g | 0x40, g | 0x80, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_tail_valid(r - 0x80, 0x40, g | 0x80, r)); +} + +static void apr_test_inflight(struct kunit *test) +{ + const u32 r = APR_RING_BYTES; + u32 ends[APR_MAX_INFLIGHT], done, head, tail; + unsigned int i, retired; + + KUNIT_EXPECT_FALSE(test, apr_jobs_full(0, 0)); + KUNIT_EXPECT_FALSE(test, apr_jobs_full(APR_MAX_INFLIGHT - 1, 0)); + KUNIT_EXPECT_TRUE(test, apr_jobs_full(APR_MAX_INFLIGHT, 0)); + /* Encode stays alone at the end of the ring. */ + KUNIT_EXPECT_TRUE(test, apr_jobs_full(1, 1)); + KUNIT_EXPECT_TRUE(test, apr_jobs_full(3, 1)); + + /* + * Ring space and tail arithmetic for a full ring straddling the wrap. + * Only the lone encode retires on the tail; decode jobs retire on + * their ids (apr_test_job_id). + */ + done = r - 3 * APR_DECODE_DESC_BYTES - 0x80; + head = done; + for (i = 0; i < APR_MAX_INFLIGHT; i++) { + KUNIT_ASSERT_GT(test, apr_ring_free(done, head, r), + (u32)APR_DECODE_DESC_BYTES); + head = apr_ring_advance(head, APR_DECODE_DESC_BYTES, r); + ends[i] = head; + } + KUNIT_EXPECT_EQ(test, apr_ring_distance(done, head, r), + (u32)(APR_MAX_INFLIGHT * APR_DECODE_DESC_BYTES)); + /* The tail stops inside the fifth descriptor: four jobs are done. */ + tail = apr_ring_advance(ends[3], 0x40, r); + KUNIT_ASSERT_TRUE(test, apr_ring_tail_valid(done, tail, head, r)); + for (retired = 0; retired < APR_MAX_INFLIGHT; retired++) { + if (!apr_ring_passed(done, ends[retired], tail, r)) + break; + done = ends[retired]; + } + KUNIT_EXPECT_EQ(test, retired, 4U); + KUNIT_EXPECT_EQ(test, done, ends[3]); + /* Then the engine drains the ring. */ + tail = head; + KUNIT_ASSERT_TRUE(test, apr_ring_tail_valid(done, tail, head, r)); + for (; retired < APR_MAX_INFLIGHT; retired++) { + if (!apr_ring_passed(done, ends[retired], tail, r)) + break; + done = ends[retired]; + } + KUNIT_EXPECT_EQ(test, retired, (unsigned int)APR_MAX_INFLIGHT); + KUNIT_EXPECT_EQ(test, done, head); + KUNIT_EXPECT_EQ(test, apr_ring_free(done, head, r), r); +} + +static void apr_test_job_id(struct kunit *test) +{ + /* Ids are never 0, which ST1 reads after a reset. */ + KUNIT_EXPECT_EQ(test, apr_next_job_id(1), 2); + KUNIT_EXPECT_EQ(test, apr_next_job_id(U16_MAX), 1); + KUNIT_EXPECT_FALSE(test, apr_job_id_done(0, 1)); + KUNIT_EXPECT_TRUE(test, apr_job_id_done(1, 1)); + KUNIT_EXPECT_TRUE(test, apr_job_id_done(5, 3)); + KUNIT_EXPECT_FALSE(test, apr_job_id_done(3, 5)); + /* Across the wrap: 65535 finishes before 1 and 2. */ + KUNIT_EXPECT_TRUE(test, apr_job_id_done(1, U16_MAX)); + KUNIT_EXPECT_FALSE(test, apr_job_id_done(U16_MAX, 1)); + KUNIT_EXPECT_FALSE(test, apr_job_id_done(U16_MAX - 1, 2)); + + /* ST1 = 0 is no progress, never "everything in 0x8001..0xffff done". */ + KUNIT_EXPECT_EQ(test, apr_job_id_check(0, 9), APR_DONE_ID_NONE); + KUNIT_EXPECT_EQ(test, apr_job_id_check(0, 0x8005), APR_DONE_ID_NONE); + KUNIT_EXPECT_TRUE(test, apr_job_id_done(0, 0x8001)); + /* Ids 1..8 outstanding: ids already issued, finished or not. */ + KUNIT_EXPECT_EQ(test, apr_job_id_check(1, 9), APR_DONE_ID_ISSUED); + KUNIT_EXPECT_EQ(test, apr_job_id_check(8, 9), APR_DONE_ID_ISSUED); + /* The other half of the id space reads as old ids: nothing retires. */ + for (u32 d = 0x8009; d <= U16_MAX; d += 0x7ff) { + KUNIT_EXPECT_EQ(test, apr_job_id_check(d, 9), APR_DONE_ID_ISSUED); + for (u16 id = 1; id < 9; id++) + KUNIT_EXPECT_FALSE(test, apr_job_id_done(d, id)); + } + KUNIT_EXPECT_EQ(test, apr_job_id_check(U16_MAX, 9), APR_DONE_ID_ISSUED); + KUNIT_EXPECT_FALSE(test, apr_job_id_done(U16_MAX, 1)); + /* An id not issued yet: the ring is hung, nothing retires. */ + KUNIT_EXPECT_EQ(test, apr_job_id_check(9, 9), APR_DONE_ID_FUTURE); + KUNIT_EXPECT_EQ(test, apr_job_id_check(10, 9), APR_DONE_ID_FUTURE); + KUNIT_EXPECT_EQ(test, apr_job_id_check(0x8008, 9), APR_DONE_ID_FUTURE); + /* First job after a reset: id 1 not issued until next_id moves on. */ + KUNIT_EXPECT_EQ(test, apr_job_id_check(1, 1), APR_DONE_ID_FUTURE); + + /* Eight jobs across the wrap: 0xfffc..0xffff, then 1..4 (0 skipped). */ + { + u16 ids[APR_MAX_INFLIGHT], next = 0xfffc; + unsigned int i, retired = 0; + + for (i = 0; i < APR_MAX_INFLIGHT; i++) { + ids[i] = next; + next = apr_next_job_id(next); + } + KUNIT_EXPECT_EQ(test, ids[4], 1); + KUNIT_EXPECT_EQ(test, next, 5); + /* ST1 skips ahead to 2: six jobs finished, in ring order. */ + KUNIT_EXPECT_EQ(test, apr_job_id_check(2, next), APR_DONE_ID_ISSUED); + while (retired < APR_MAX_INFLIGHT && + apr_job_id_done(2, ids[retired])) + retired++; + KUNIT_EXPECT_EQ(test, retired, 6U); + /* The same id again retires nothing more. */ + while (retired < APR_MAX_INFLIGHT && + apr_job_id_done(2, ids[retired])) + retired++; + KUNIT_EXPECT_EQ(test, retired, 6U); + /* A stale id from before the wrap retires nothing more either. */ + KUNIT_EXPECT_FALSE(test, apr_job_id_done(0xfffe, ids[6])); + KUNIT_EXPECT_EQ(test, apr_job_id_check(4, next), APR_DONE_ID_ISSUED); + KUNIT_EXPECT_TRUE(test, apr_job_id_done(4, ids[7])); + /* 5 = next_id: not issued, hung. */ + KUNIT_EXPECT_EQ(test, apr_job_id_check(5, next), APR_DONE_ID_FUTURE); + KUNIT_EXPECT_EQ(test, apr_job_id_check(0x8004, next), APR_DONE_ID_FUTURE); + KUNIT_EXPECT_EQ(test, apr_job_id_check(0x8005, next), APR_DONE_ID_ISSUED); + } +} + static struct kunit_case apr_test_cases[] = { KUNIT_CASE(apr_test_qmat_regs), KUNIT_CASE(apr_test_dc_scale), @@ -624,6 +1226,23 @@ static struct kunit_case apr_test_cases[] = { KUNIT_CASE(apr_test_apri_header_rejects), KUNIT_CASE(apr_test_apri_shape_rejects), KUNIT_CASE(apr_test_apri_row_rejects), + KUNIT_CASE(apr_test_decode_desc), + KUNIT_CASE(apr_test_parse_frame), + KUNIT_CASE(apr_test_parse_interlaced), + KUNIT_CASE(apr_test_parse_many_slices), + KUNIT_CASE(apr_test_oob_exact_fit), + KUNIT_CASE(apr_test_oob_frame_size), + KUNIT_CASE(apr_test_oob_frame_header), + KUNIT_CASE(apr_test_oob_picture_size), + KUNIT_CASE(apr_test_oob_slice_table), + KUNIT_CASE(apr_test_oob_slice_sizes), + KUNIT_CASE(apr_test_oob_slice_headers), + KUNIT_CASE(apr_test_oob_second_field), + KUNIT_CASE(apr_test_ring_accounting), + KUNIT_CASE(apr_test_ring_space), + KUNIT_CASE(apr_test_ring_tail), + KUNIT_CASE(apr_test_inflight), + KUNIT_CASE(apr_test_job_id), {} }; @@ -633,6 +1252,6 @@ static struct kunit_suite apr_test_suite = { }; kunit_test_suite(apr_test_suite); -MODULE_DESCRIPTION("KUnit tests for the Apple ProRes encoder"); +MODULE_DESCRIPTION("KUnit tests for the Apple ProRes codec"); MODULE_LICENSE("GPL"); MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING"); diff --git a/drivers/media/platform/apple/prores/apple-prores.h b/drivers/media/platform/apple/prores/apple-prores.h index 67bf19c93370cd..58808ed515c550 100644 --- a/drivers/media/platform/apple/prores/apple-prores.h +++ b/drivers/media/platform/apple/prores/apple-prores.h @@ -1,11 +1,11 @@ /* SPDX-License-Identifier: GPL-2.0-only */ /* - * Apple ProRes (APR) encoder: register map and job descriptor. + * Apple ProRes (APR) codec: register map and job descriptors. * - * The APR is a register-driven engine with no firmware. Jobs are fixed-size - * descriptors placed in a DMA ring; the driver installs the ring, advances a - * producer head and the engine reports completion through a status register - * and a consumer tail. + * The APR is a register-driven engine with no firmware. Jobs are typed, + * variable-size descriptors placed in a DMA ring; the driver installs the + * ring, advances a producer head and the engine reports completion through a + * status register and a consumer tail. * * Register names and descriptor fields follow the m1n1 proxyclient ProRes * experiment (MIT), proxyclient/m1n1/hw/prores.py and @@ -29,12 +29,23 @@ #define APR_IRQ_ERROR BIT(1) #define APR_REG_ST0 0x0014 #define APR_REG_ST1 0x0018 +/* Job id of the last descriptor the engine has finished (decode command 31:16). */ +#define APR_ST1_DONE_ID GENMASK(31, 16) +#define APR_REG_ST2 0x001c +#define APR_REG_DETAIL0 0x003c +#define APR_REG_DETAIL1_LO 0x0040 +#define APR_REG_DETAIL1_HI 0x0044 +#define APR_REG_DETAIL2_LO 0x0048 +#define APR_REG_DETAIL2_HI 0x0050 +#define APR_REG_DETAIL3 0x0054 #define APR_REG_RING_SIZE 0x0100 #define APR_REG_RING_LO 0x0104 #define APR_REG_RING_HI 0x0108 #define APR_REG_RING_HEAD 0x010c #define APR_REG_RING_TAIL 0x0110 -#define APR_RING_PTR_MASK GENMASK(23, 0) +#define APR_RING_OFFSET_MASK GENMASK(23, 0) +#define APR_RING_GENERATION BIT(24) +#define APR_RING_PTR_MASK GENMASK(24, 0) /* One statistics area, given to two consumers; their capacity reads back. */ #define APR_REG_STATS0_LO 0x038c #define APR_REG_STATS0_HI 0x0390 @@ -51,7 +62,25 @@ #define APR_DC_SCALE_ENTRIES 112 #define APR_RING_BYTES SZ_128K -#define APR_DESC_BYTES 0x180 +#define APR_ENCODE_DESC_BYTES 0x180 +#define APR_DECODE_DESC_BYTES 0x100 +/* Kept for the encode descriptor tests and callers. */ +#define APR_DESC_BYTES APR_ENCODE_DESC_BYTES + +/* + * Jobs the driver keeps in the ring at once. The ring itself holds hundreds + * of descriptors; the limit bounds the buffers and runtime-PM references a + * timeout has to fail and the latency of a stream-off. Eight covers the + * decode gap to VideoToolbox (several frames outstanding) with slack for the + * scheduling delay between jobs. + */ +#define APR_MAX_INFLIGHT 8 +/* + * Encode stays at one job in the ring: every encode job uses the one shared + * statistics area, and nothing public shows that two encodes may overlap in + * it. Encode already runs at macOS speed with one job outstanding. + */ +#define APR_ENCODE_MAX_INFLIGHT 1 #define APRI_T6041_FIRMWARE_NAME "apple/prores-t6041-init.bin" #define APRI_T6041_FIRMWARE_SIZE 2728 @@ -158,6 +187,35 @@ struct apr_frame { u8 matrix; }; +struct apr_decode_frame { + u32 width; + u32 height; + enum apr_input output; + u32 luma_stride; /* bytes, multiple of 64 */ + u32 chroma_stride; /* bytes, multiple of 64 */ + u64 input; + u64 luma; + u64 chroma; + u16 job_id; + bool bottom_field_first; +}; + +struct apr_prores_info { + u32 frame_size; + u32 width; + u32 height; + u32 slices[2]; + u32 picture_offset[2]; + u32 picture_size[2]; + u8 pictures; + u8 chroma; + u8 frame_type; + u8 alpha; + u8 primaries; + u8 transfer; + u8 matrix; +}; + /* Matrices are 8x8 in raster order, as carried in the ProRes frame header. */ extern const u8 *const apr_qmat_luma[APR_QTABLES]; extern const u8 *const apr_qmat_chroma[APR_QTABLES]; @@ -172,6 +230,8 @@ void apr_frame_budget(enum apr_profile profile, u32 width, u32 height, u32 apr_slice_count(u32 width, u32 height, u32 log2_slice); int apr_build_desc(const struct apr_frame *f, u8 *desc); int apr_build_desc_v0(const struct apr_frame *f, u8 *desc); +int apr_build_decode_desc(const struct apr_decode_frame *f, u8 *desc); +int apr_parse_frame(const u8 *data, size_t bytes, struct apr_prores_info *info); int apr_check_output(const u8 *out, size_t capacity, u32 *frame_bytes); extern const struct apri_layout apri_t6041; extern const struct apri_layout apri_t6050; @@ -185,5 +245,23 @@ static inline int apr_parse_t6041_init(const u8 *data, size_t size, { return apr_parse_init(&apri_t6041, data, size, init); } +u32 apr_ring_advance(u32 ptr, u32 bytes, u32 ring_bytes); +u32 apr_ring_distance(u32 from, u32 to, u32 ring_bytes); +u32 apr_ring_free(u32 done, u32 head, u32 ring_bytes); +bool apr_ring_passed(u32 done, u32 end, u32 tail, u32 ring_bytes); +bool apr_ring_tail_valid(u32 done, u32 tail, u32 head, u32 ring_bytes); +u16 apr_next_job_id(u16 id); +bool apr_job_id_done(u16 done_id, u16 id); + +enum apr_done_id { + APR_DONE_ID_NONE, /* nothing finished since the reset */ + APR_DONE_ID_ISSUED, /* an id the driver issued */ + APR_DONE_ID_FUTURE, /* an id not issued yet: the ring is hung */ +}; + +enum apr_done_id apr_job_id_check(u16 done_id, u16 next_id); +bool apr_jobs_full(unsigned int jobs, unsigned int encodes); +void apr_ring_write(u8 *ring, u32 ring_bytes, u32 ptr, const u8 *desc, + u32 desc_bytes); #endif diff --git a/drivers/media/platform/apple/scaler/Kconfig b/drivers/media/platform/apple/scaler/Kconfig index dcfb18859d6890..4abf05a8d9902a 100644 --- a/drivers/media/platform/apple/scaler/Kconfig +++ b/drivers/media/platform/apple/scaler/Kconfig @@ -7,11 +7,13 @@ config VIDEO_APPLE_SCALER depends on OF_ADDRESS && IOMMU_API && PM select V4L2_MEM2MEM_DEV select VIDEOBUF2_DMA_CONTIG + select CRC32 help V4L2 memory-to-memory driver for the image scaler and - colour-space converter (MSR) in Apple silicon SoCs (M1 to M4 + colour-space converter (MSR) in Apple silicon SoCs (M1 to M5 generations and A18 Pro). It converts between Y'CbCr (NV12, - P010) and 32-bit RGB at the same size; scaling follows. + P010) and 32-bit RGB; on M5 it also scales, crops, rotates and + mirrors. To compile this driver as a module, choose M here: the module will be called apple-scaler. @@ -21,6 +23,6 @@ config VIDEO_APPLE_SCALER_KUNIT_TEST depends on KUNIT && VIDEO_APPLE_SCALER default KUNIT_ALL_TESTS help - Check the colour-conversion matrices, offsets, scale ratios and - format encodings the scaler driver programs. No hardware is - needed. + Check the colour-conversion matrices, offsets, scale ratios, + format encodings and M5 job images the scaler driver programs. + No hardware is needed. diff --git a/drivers/media/platform/apple/scaler/Makefile b/drivers/media/platform/apple/scaler/Makefile index d6a9dcbe9b33ef..64288df5253dc9 100644 --- a/drivers/media/platform/apple/scaler/Makefile +++ b/drivers/media/platform/apple/scaler/Makefile @@ -1,5 +1,5 @@ # SPDX-License-Identifier: GPL-2.0-only obj-$(CONFIG_VIDEO_APPLE_SCALER) += apple-scaler.o -apple-scaler-y := apple-scaler-drv.o apple-scaler-hw.o +apple-scaler-y := apple-scaler-drv.o apple-scaler-hw.o apple-scaler-msr23.o obj-$(CONFIG_VIDEO_APPLE_SCALER_KUNIT_TEST) += apple-scaler-test.o diff --git a/drivers/media/platform/apple/scaler/apple-scaler-drv.c b/drivers/media/platform/apple/scaler/apple-scaler-drv.c index d9707d2aec0687..3b266744d89c10 100644 --- a/drivers/media/platform/apple/scaler/apple-scaler-drv.c +++ b/drivers/media/platform/apple/scaler/apple-scaler-drv.c @@ -6,14 +6,22 @@ * scalers with a programmable colour-space converter, chroma resampling, * flip/rotate and alpha fill. Hardware-version 10 (M1) through 22 (A18 Pro) * are programmed directly through MMIO and report completion with an - * interrupt; later generations front the engine with firmware and are not - * handled here. + * interrupt. Hardware-version 23 (M5) fronts the engine with firmware: the + * driver builds each job's register image and queues it to the firmware. * * The OUTPUT queue takes the source image, the CAPTURE queue the result. - * This version converts between formats at the same size: Y'CbCr <-> + * The MMIO engines convert between formats at the same size: Y'CbCr <-> * R'G'B' with the colorimetry of the Y'CbCr side, chroma resampling and - * alpha fill. Scaling comes once the filter path is qualified. + * alpha fill. MSR23 converts and scales (up to 4x either way per axis). It + * also reads a crop of the source (OUTPUT crop selection), writes into a + * rectangle of the destination (CAPTURE compose selection), rotates in + * quarter turns and mirrors (V4L2_CID_ROTATE, _HFLIP, _VFLIP: the mirrors + * apply to the rotated picture). */ +#include +#include +#include +#include #include #include #include @@ -22,10 +30,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -41,6 +51,7 @@ #include "../apple-video-nr.h" #include "apple-scaler-hw.h" +#include "apple-scaler-msr23.h" #include "apple-scaler-regs.h" #define ASC_NAME "apple-scaler" @@ -56,15 +67,29 @@ * @hw_version: MSR hardware-version of this SoC (from the hardware description) * @num_reg: number of register apertures the binding describes * @msr20: the engine has the MSR20-generation control block + * @fw_fronted: hardware-version 23 and later: jobs go through firmware queues + * (see asc_v23_probe()) + * @fw_name: fw_fronted: the core's image, uploaded only when the SRAM holds none + * @powerup: fw_fronted: the register writes that prepare the engine before its + * core starts + * @num_powerup: the number of @powerup writes */ struct apple_scaler_variant { u32 hw_version; unsigned int num_reg; bool msr20; + bool fw_fronted; + const char *fw_name; + const struct msr23_wr *powerup; + unsigned int num_powerup; }; +struct msr23; +struct msr23_wr; + struct apple_scaler { struct device *dev; + struct msr23 *msr; /* MSR23 (fw_fronted): firmware core and job queues */ void __iomem *regs; resource_size_t regs_size; const struct apple_scaler_variant *variant; @@ -90,7 +115,21 @@ struct apple_scaler_ctx { struct apple_scaler *asc; struct v4l2_pix_format_mplane src; /* OUTPUT queue */ struct v4l2_pix_format_mplane dst; /* CAPTURE queue */ + /* + * The CAPTURE colorimetry asked for (an RGB -> YUV conversion target), + * whichever queue is set first. + */ + u32 dst_ycbcr_req, dst_quant_req; u32 sequence; + + /* MSR23 geometry: the source region read, the destination region written. */ + struct v4l2_rect crop, compose; + struct v4l2_ctrl_handler hdl; + struct v4l2_ctrl *rotate_ctrl; + /* fixed while either queue streams: msr23_work() reads them without asc->lock */ + struct v4l2_ctrl *job_ctrl[3]; + u16 rotate; + bool hflip, vflip; }; static struct apple_scaler_ctx *asc_file_to_ctx(struct file *file) @@ -110,7 +149,6 @@ static void asc_write(struct apple_scaler *asc, u32 reg, u32 val) /* ---- hardware --------------------------------------------------------- */ - /* * After power-up or a failed job: wait for idle, pulse the engine reset * (no register may be read while it is held), clear stale status and @@ -260,6 +298,8 @@ static void asc_image(struct asc_image *img, const struct v4l2_pix_format_mplane } } +static void msr23_device_run(struct apple_scaler *asc, struct apple_scaler_ctx *ctx); + static void asc_device_run(void *priv) { struct apple_scaler_ctx *ctx = priv; @@ -270,6 +310,10 @@ static void asc_device_run(void *priv) unsigned long flags; int n, ret; + if (asc->variant->fw_fronted) { + msr23_device_run(asc, ctx); + return; + } src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); dst = v4l2_m2m_next_dst_buf(ctx->fh.m2m_ctx); ret = pm_runtime_resume_and_get(asc->dev); @@ -349,17 +393,52 @@ static const struct v4l2_m2m_ops asc_m2m_ops = { * colorimetry; the R'G'B' side is full range with the same primaries and * transfer function, since the engine converts only the encoding. */ -static void asc_fill(struct v4l2_pix_format_mplane *pix, const struct v4l2_pix_format_mplane *ref, - u32 default_fourcc) +/* + * MSR23 builds its jobs (apple-scaler-msr23.c) for B,G,R,A, NV12, NV16, NV24, + * P010 and GREY. The older engines never offer the MSR23-only formats. + */ +static bool asc_fmt_ok(const struct apple_scaler *asc, const struct asc_format *f) +{ + if (!f) + return false; + if (asc->variant->fw_fronted) { + switch (f->fourcc) { + case V4L2_PIX_FMT_ABGR32: + case V4L2_PIX_FMT_NV12: + case V4L2_PIX_FMT_NV12M: + case V4L2_PIX_FMT_NV16: + case V4L2_PIX_FMT_NV24: + case V4L2_PIX_FMT_P010: + case V4L2_PIX_FMT_GREY: + return true; + } + return false; + } + return !f->msr23_only; +} + +static void asc_fill(const struct apple_scaler *asc, struct v4l2_pix_format_mplane *pix, + const struct v4l2_pix_format_mplane *ref, u32 default_fourcc) { const struct asc_format *f = asc_find_format(pix->pixelformat); - u32 w = ref ? ref->width : pix->width, h = ref ? ref->height : pix->height; + /* MSR23 scales: its CAPTURE side keeps its own size. */ + bool own = asc->variant->fw_fronted || !ref; + u32 w = own ? pix->width : ref->width, h = own ? pix->height : ref->height; struct v4l2_pix_format_mplane in = *pix; - if (!f) + if (!asc_fmt_ok(asc, f) && asc->variant->fw_fronted) + f = asc_find_format(default_fourcc == V4L2_PIX_FMT_ARGB32 ? + V4L2_PIX_FMT_ABGR32 : V4L2_PIX_FMT_NV12); + else if (!asc_fmt_ok(asc, f)) f = asc_find_format(default_fourcc); - w = clamp_t(u32, ALIGN(w, f->hsub), ASC_MIN_SIZE, ASC_MAX_SIZE); - h = clamp_t(u32, ALIGN(h, f->vsub), ASC_MIN_SIZE, ASC_MAX_SIZE); + if (asc->variant->fw_fronted) { + /* the builder's range: even sizes, 64 to 4096 */ + w = clamp_t(u32, ALIGN(w, 2), MSR23_MIN_SIZE, MSR23_MAX_WIDTH); + h = clamp_t(u32, ALIGN(h, 2), MSR23_MIN_SIZE, MSR23_MAX_WIDTH); + } else { + w = clamp_t(u32, ALIGN(w, f->hsub), ASC_MIN_SIZE, ASC_MAX_SIZE); + h = clamp_t(u32, ALIGN(h, f->vsub), ASC_MIN_SIZE, ASC_MAX_SIZE); + } memset(pix, 0, sizeof(*pix)); if (f->lossless) { @@ -373,7 +452,12 @@ static void asc_fill(struct v4l2_pix_format_mplane *pix, const struct v4l2_pix_f pix->plane_fmt[0].bytesperline = g.y_pitch; pix->plane_fmt[0].sizeimage = g.bytes; } else { - v4l2_fill_pixfmt_mp_aligned(pix, f->fourcc, w, h, ASC_STRIDE_ALIGN); + /* + * MSR23: 16-byte aligned strides (NV12 1440 wide: 1440 bytes); + * the engine takes them. + */ + v4l2_fill_pixfmt_mp_aligned(pix, f->fourcc, w, h, + asc->variant->fw_fronted ? 16 : ASC_STRIDE_ALIGN); } pix->field = V4L2_FIELD_NONE; @@ -407,6 +491,27 @@ static void asc_fill(struct v4l2_pix_format_mplane *pix, const struct v4l2_pix_f pix->xfer_func = V4L2_MAP_XFER_FUNC_DEFAULT(pix->colorspace); } +static struct v4l2_rect asc_full_rect(const struct v4l2_pix_format_mplane *pix) +{ + return (struct v4l2_rect){ 0, 0, pix->width, pix->height }; +} + +/* + * After a format change: a rectangle that covered the whole old picture + * covers the whole new one; one set by the application stays while it fits + * (v4l2-ctl sets the CAPTURE format again after the selection, when it starts + * streaming). + */ +static void asc_fit_rect(struct v4l2_rect *r, u32 old_w, u32 old_h, + const struct v4l2_pix_format_mplane *pix) +{ + bool whole = !r->left && !r->top && r->width == old_w && r->height == old_h; + + if (whole || (u64)r->left + r->width > pix->width || + (u64)r->top + r->height > pix->height) + *r = asc_full_rect(pix); +} + static int asc_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { strscpy(cap->driver, ASC_NAME, sizeof(cap->driver)); @@ -416,24 +521,37 @@ static int asc_querycap(struct file *file, void *priv, struct v4l2_capability *c static int asc_enum_fmt(struct file *file, void *priv, struct v4l2_fmtdesc *f) { - const struct asc_format *fmt = asc_format_by_index(f->index); - - if (!fmt) - return -EINVAL; - f->pixelformat = fmt->fourcc; - return 0; + const struct apple_scaler *asc = asc_file_to_ctx(file)->asc; + const struct asc_format *fmt; + unsigned int i, n = 0; + + for (i = 0; (fmt = asc_format_by_index(i)); i++) { + if (!asc_fmt_ok(asc, fmt)) + continue; + if (n++ == f->index) { + f->pixelformat = fmt->fourcc; + return 0; + } + } + return -EINVAL; } static int asc_enum_framesizes(struct file *file, void *priv, struct v4l2_frmsizeenum *fs) { + const struct apple_scaler *asc = asc_file_to_ctx(file)->asc; const struct asc_format *f = asc_find_format(fs->pixel_format); - if (fs->index || !f) + if (fs->index || !asc_fmt_ok(asc, f)) return -EINVAL; fs->type = V4L2_FRMSIZE_TYPE_STEPWISE; - fs->stepwise = (struct v4l2_frmsize_stepwise){ - ASC_MIN_SIZE, ASC_MAX_SIZE, f->hsub, ASC_MIN_SIZE, ASC_MAX_SIZE, f->vsub, - }; + if (asc->variant->fw_fronted) + fs->stepwise = (struct v4l2_frmsize_stepwise){ + MSR23_MIN_SIZE, MSR23_MAX_WIDTH, 2, MSR23_MIN_SIZE, MSR23_MAX_WIDTH, 2, + }; + else + fs->stepwise = (struct v4l2_frmsize_stepwise){ + ASC_MIN_SIZE, ASC_MAX_SIZE, f->hsub, ASC_MIN_SIZE, ASC_MAX_SIZE, f->vsub, + }; return 0; } @@ -451,37 +569,130 @@ static int asc_g_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) static int asc_try_fmt_out(struct file *file, void *priv, struct v4l2_format *f) { - asc_fill(&f->fmt.pix_mp, NULL, V4L2_PIX_FMT_NV12M); + asc_fill(asc_file_to_ctx(file)->asc, &f->fmt.pix_mp, NULL, V4L2_PIX_FMT_NV12M); return 0; } static int asc_try_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) { - asc_fill(&f->fmt.pix_mp, &asc_file_to_ctx(file)->src, V4L2_PIX_FMT_ARGB32); + struct apple_scaler_ctx *ctx = asc_file_to_ctx(file); + + asc_fill(ctx->asc, &f->fmt.pix_mp, &ctx->src, V4L2_PIX_FMT_ARGB32); return 0; } static int asc_s_fmt_out(struct file *file, void *priv, struct v4l2_format *f) { struct apple_scaler_ctx *ctx = asc_file_to_ctx(file); + u32 w, h; if (vb2_is_busy(v4l2_m2m_get_src_vq(ctx->fh.m2m_ctx)) || vb2_is_busy(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx))) return -EBUSY; - asc_fill(&f->fmt.pix_mp, NULL, V4L2_PIX_FMT_NV12M); + asc_fill(asc_file_to_ctx(file)->asc, &f->fmt.pix_mp, NULL, V4L2_PIX_FMT_NV12M); + w = ctx->src.width; + h = ctx->src.height; ctx->src = f->fmt.pix_mp; - asc_fill(&ctx->dst, &ctx->src, V4L2_PIX_FMT_ARGB32); + asc_fit_rect(&ctx->crop, w, h, &ctx->src); + /* + * Re-derive CAPTURE from the new source, with the matrix and range it was asked for: a + * CAPTURE format set before this (v4l2-ctl sets CAPTURE first) took them from the previous + * source, the open-time NV12 default. + */ + ctx->dst.ycbcr_enc = ctx->dst_ycbcr_req; + ctx->dst.quantization = ctx->dst_quant_req; + w = ctx->dst.width; + h = ctx->dst.height; + asc_fill(ctx->asc, &ctx->dst, &ctx->src, V4L2_PIX_FMT_ARGB32); + asc_fit_rect(&ctx->compose, w, h, &ctx->dst); return 0; } static int asc_s_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) { struct apple_scaler_ctx *ctx = asc_file_to_ctx(file); + u32 w, h; if (vb2_is_busy(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx))) return -EBUSY; - asc_fill(&f->fmt.pix_mp, &ctx->src, V4L2_PIX_FMT_ARGB32); + ctx->dst_ycbcr_req = f->fmt.pix_mp.ycbcr_enc; + ctx->dst_quant_req = f->fmt.pix_mp.quantization; + asc_fill(ctx->asc, &f->fmt.pix_mp, &ctx->src, V4L2_PIX_FMT_ARGB32); + w = ctx->dst.width; + h = ctx->dst.height; ctx->dst = f->fmt.pix_mp; + asc_fit_rect(&ctx->compose, w, h, &ctx->dst); + return 0; +} + +/* + * MSR23: crop on the OUTPUT queue is the part of the source read, compose on + * the CAPTURE queue the part of the destination written. The engine leaves + * the rest of the CAPTURE buffer as it is, so COMPOSE_PADDED is the compose + * rectangle. Rectangles are even and at least 64 pixels, like the formats. + */ +static int asc_g_selection(struct file *file, void *priv, struct v4l2_selection *s) +{ + struct apple_scaler_ctx *ctx = asc_file_to_ctx(file); + bool out = s->type == V4L2_BUF_TYPE_VIDEO_OUTPUT; + + if (!out && s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) + return -EINVAL; + switch (s->target) { + case V4L2_SEL_TGT_CROP: + if (!out) + return -EINVAL; + s->r = ctx->crop; + return 0; + case V4L2_SEL_TGT_CROP_DEFAULT: + case V4L2_SEL_TGT_CROP_BOUNDS: + if (!out) + return -EINVAL; + s->r = asc_full_rect(&ctx->src); + return 0; + case V4L2_SEL_TGT_COMPOSE: + case V4L2_SEL_TGT_COMPOSE_PADDED: + if (out) + return -EINVAL; + s->r = ctx->compose; + return 0; + case V4L2_SEL_TGT_COMPOSE_DEFAULT: + case V4L2_SEL_TGT_COMPOSE_BOUNDS: + if (out) + return -EINVAL; + s->r = asc_full_rect(&ctx->dst); + return 0; + } + return -EINVAL; +} + +static int asc_s_selection(struct file *file, void *priv, struct v4l2_selection *s) +{ + struct apple_scaler_ctx *ctx = asc_file_to_ctx(file); + bool out = s->type == V4L2_BUF_TYPE_VIDEO_OUTPUT; + const struct v4l2_pix_format_mplane *pix = out ? &ctx->src : &ctx->dst; + struct v4l2_rect r; + bool le; + + if (out ? s->target != V4L2_SEL_TGT_CROP : + (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE || s->target != V4L2_SEL_TGT_COMPOSE)) + return -EINVAL; + if (vb2_is_streaming(v4l2_m2m_get_src_vq(ctx->fh.m2m_ctx)) || + vb2_is_streaming(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx))) + return -EBUSY; + /* even: round outwards, or inwards when only V4L2_SEL_FLAG_LE is set */ + le = (s->flags & (V4L2_SEL_FLAG_LE | V4L2_SEL_FLAG_GE)) == V4L2_SEL_FLAG_LE; + r.width = clamp_t(u32, le ? ALIGN_DOWN(s->r.width, 2) : ALIGN(s->r.width, 2), + MSR23_MIN_SIZE, pix->width); + r.height = clamp_t(u32, le ? ALIGN_DOWN(s->r.height, 2) : ALIGN(s->r.height, 2), + MSR23_MIN_SIZE, pix->height); + r.left = clamp_t(s32, le ? ALIGN(s->r.left, 2) : s->r.left & ~1, 0, pix->width - r.width); + r.top = clamp_t(s32, le ? ALIGN(s->r.top, 2) : s->r.top & ~1, 0, pix->height - r.height); + if (out) + ctx->crop = r; + else + ctx->compose = r; + s->r = r; return 0; } @@ -496,6 +707,8 @@ static const struct v4l2_ioctl_ops asc_ioctl_ops = { .vidioc_try_fmt_vid_cap_mplane = asc_try_fmt_cap, .vidioc_s_fmt_vid_out_mplane = asc_s_fmt_out, .vidioc_s_fmt_vid_cap_mplane = asc_s_fmt_cap, + .vidioc_g_selection = asc_g_selection, + .vidioc_s_selection = asc_s_selection, .vidioc_reqbufs = v4l2_m2m_ioctl_reqbufs, .vidioc_querybuf = v4l2_m2m_ioctl_querybuf, @@ -563,10 +776,58 @@ static void asc_buf_queue(struct vb2_buffer *vb) v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, to_vb2_v4l2_buffer(vb)); } +static void asc_return_bufs(struct vb2_queue *q, enum vb2_buffer_state state) +{ + struct apple_scaler_ctx *ctx = vb2_get_drv_priv(q); + struct vb2_v4l2_buffer *vbuf; + + for (;;) { + vbuf = V4L2_TYPE_IS_OUTPUT(q->type) ? v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx) : + v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx); + if (!vbuf) + break; + v4l2_m2m_buf_done(vbuf, state); + } +} + +static int msr23_job_of(const struct apple_scaler_ctx *ctx, struct msr23_job *job); + +static void asc_grab_ctrls(struct apple_scaler_ctx *ctx, bool grab) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(ctx->job_ctrl); i++) + if (ctx->job_ctrl[i]) + v4l2_ctrl_grab(ctx->job_ctrl[i], grab); +} + static int asc_start_streaming(struct vb2_queue *q, unsigned int count) { struct apple_scaler_ctx *ctx = vb2_get_drv_priv(q); + struct vb2_queue *other = V4L2_TYPE_IS_OUTPUT(q->type) ? + v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx) : + v4l2_m2m_get_src_vq(ctx->fh.m2m_ctx); + struct msr23_job job; + /* + * MSR23: both formats are fixed once both queues stream; refuse here a + * pair the job builder does not cover (size ratio, area, conversion) + * rather than fail every job. + */ + if (ctx->asc->variant->fw_fronted && vb2_is_streaming(other) && + msr23_job_of(ctx, &job)) { + dev_dbg(ctx->asc->dev, "MSR23: %.4s %ux%u -> %.4s %ux%u not supported\n", + (char *)&ctx->src.pixelformat, ctx->src.width, ctx->src.height, + (char *)&ctx->dst.pixelformat, ctx->dst.width, ctx->dst.height); + asc_return_bufs(q, VB2_BUF_STATE_QUEUED); + return -EINVAL; + } + /* + * Every control a job reads is fixed while either queue streams: a + * rotation changes which sizes fit, a mirror can make a checked pair + * invalid, and msr23_work() reads them without asc->lock. + */ + asc_grab_ctrls(ctx, true); if (V4L2_TYPE_IS_OUTPUT(q->type)) ctx->sequence = 0; return 0; @@ -575,15 +836,13 @@ static int asc_start_streaming(struct vb2_queue *q, unsigned int count) static void asc_stop_streaming(struct vb2_queue *q) { struct apple_scaler_ctx *ctx = vb2_get_drv_priv(q); - struct vb2_v4l2_buffer *vbuf; + struct vb2_queue *other = V4L2_TYPE_IS_OUTPUT(q->type) ? + v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx) : + v4l2_m2m_get_src_vq(ctx->fh.m2m_ctx); - for (;;) { - vbuf = V4L2_TYPE_IS_OUTPUT(q->type) ? v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx) : - v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx); - if (!vbuf) - break; - v4l2_m2m_buf_done(vbuf, VB2_BUF_STATE_ERROR); - } + asc_return_bufs(q, VB2_BUF_STATE_ERROR); + if (!vb2_is_streaming(other)) + asc_grab_ctrls(ctx, false); } static const struct vb2_ops asc_qops = { @@ -615,6 +874,52 @@ static int asc_queue_init(void *priv, struct vb2_queue *src, struct vb2_queue *d return ret ?: asc_init_queue(priv, dst, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); } +/* ---- controls --------------------------------------------------------- */ + +static int asc_s_ctrl(struct v4l2_ctrl *c) +{ + struct apple_scaler_ctx *ctx = container_of(c->handler, struct apple_scaler_ctx, hdl); + + switch (c->id) { + case V4L2_CID_ROTATE: + ctx->rotate = c->val; + return 0; + case V4L2_CID_HFLIP: + ctx->hflip = c->val; + return 0; + case V4L2_CID_VFLIP: + ctx->vflip = c->val; + return 0; + } + return -EINVAL; +} + +static const struct v4l2_ctrl_ops asc_ctrl_ops = { + .s_ctrl = asc_s_ctrl, +}; + +/* MSR23: rotation in quarter turns and the mirrors (of the rotated picture). */ +static int asc_ctrls_init(struct apple_scaler_ctx *ctx) +{ + struct v4l2_ctrl_handler *hdl = &ctx->hdl; + + v4l2_ctrl_handler_init(hdl, 3); + ctx->rotate_ctrl = v4l2_ctrl_new_std(hdl, &asc_ctrl_ops, V4L2_CID_ROTATE, 0, 270, 90, 0); + ctx->job_ctrl[0] = ctx->rotate_ctrl; + ctx->job_ctrl[1] = v4l2_ctrl_new_std(hdl, &asc_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); + ctx->job_ctrl[2] = v4l2_ctrl_new_std(hdl, &asc_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); + if (hdl->error) { + int ret = hdl->error; + + v4l2_ctrl_handler_free(hdl); + ctx->rotate_ctrl = NULL; + memset(ctx->job_ctrl, 0, sizeof(ctx->job_ctrl)); + return ret; + } + ctx->fh.ctrl_handler = hdl; + return 0; +} + /* ---- file operations -------------------------------------------------- */ static int asc_open(struct file *file) @@ -630,15 +935,28 @@ static int asc_open(struct file *file) ctx->src.width = 1920; ctx->src.height = 1080; ctx->src.pixelformat = V4L2_PIX_FMT_NV12M; - asc_fill(&ctx->src, NULL, V4L2_PIX_FMT_NV12M); + asc_fill(ctx->asc, &ctx->src, NULL, V4L2_PIX_FMT_NV12M); + ctx->dst.width = 1920; + ctx->dst.height = 1080; ctx->dst.pixelformat = V4L2_PIX_FMT_ARGB32; - asc_fill(&ctx->dst, &ctx->src, V4L2_PIX_FMT_ARGB32); + asc_fill(ctx->asc, &ctx->dst, &ctx->src, V4L2_PIX_FMT_ARGB32); + ctx->crop = asc_full_rect(&ctx->src); + ctx->compose = asc_full_rect(&ctx->dst); v4l2_fh_init(&ctx->fh, video_devdata(file)); + if (asc->variant->fw_fronted) { + ret = asc_ctrls_init(ctx); + if (ret) { + v4l2_fh_exit(&ctx->fh); + kfree(ctx); + return ret; + } + } ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(asc->m2m_dev, ctx, asc_queue_init); if (IS_ERR(ctx->fh.m2m_ctx)) { ret = PTR_ERR(ctx->fh.m2m_ctx); v4l2_fh_exit(&ctx->fh); + v4l2_ctrl_handler_free(&ctx->hdl); kfree(ctx); return ret; } @@ -656,6 +974,7 @@ static int asc_release(struct file *file) mutex_unlock(&asc->lock); v4l2_fh_del(&ctx->fh, file); v4l2_fh_exit(&ctx->fh); + v4l2_ctrl_handler_free(&ctx->hdl); kfree(ctx); return 0; } @@ -689,10 +1008,14 @@ static int asc_suspend(struct device *dev) { struct apple_scaler *asc = dev_get_drvdata(dev); - v4l2_m2m_suspend(asc->m2m_dev); + /* MSR23: the core loses its state; asc_resume() restarts it. */ + if (asc->m2m_dev) + v4l2_m2m_suspend(asc->m2m_dev); return pm_runtime_force_suspend(dev); } +static void msr23_restart(struct msr23 *m); + static int asc_resume(struct device *dev) { struct apple_scaler *asc = dev_get_drvdata(dev); @@ -700,7 +1023,10 @@ static int asc_resume(struct device *dev) if (ret) return ret; - v4l2_m2m_resume(asc->m2m_dev); + if (asc->variant->fw_fronted && asc->msr) + msr23_restart(asc->msr); + if (asc->m2m_dev) + v4l2_m2m_resume(asc->m2m_dev); return 0; } @@ -735,21 +1061,940 @@ static int asc_identify(struct apple_scaler *asc) return 0; } +/* + * MSR23 (M5): firmware-fronted. + * + * - The engine is fronted by a Cortex-M core (the "MSR ASE core", power + * domain msr-ase-core). Its code is __TEXT of the "msrf" image (0x11650 + * bytes, linked at 0x100000) in SRAM at reg[5] + 0x0; its data RAM + * (0x10000000 in the core's view) is reg[5] + 0x80000; its mailbox and + * control registers (0x50000000) are reg[5] + 0x100000. + * - iBoot pre-loads __TEXT (ADT scaler0: pre-loaded = 1, segment-ranges). + * - Start-up: the engine's power-up register writes, then the core starts + * with reg[5]+0x100028 = 0xe then 0 and reports reg[0]+0x78 = 2, sends a + * hello through the mailbox, takes one init message and four shared + * pages, and writes "LIVE", later "STAR", to reg[5]+0x80038. + * + * The driver checks the image iBoot left in SRAM (S0), uploads the variant's + * firmware file only when the SRAM holds none and the core has never run + * (S1), then starts the core (S2) and sends the init pages (S3). + */ + +#define MSR23_TEXT_SIZE 0x11650 +#define MSR23_SRAM_TEXT_MAX 0x80000 +#define MSR23_SP_INIT 0x1000fffc +#define MSR23_TEXT_BASE 0x100000 +#define MSR23_DRAM 0x80000 /* reg[5]: core data RAM */ +#define MSR23_DRAM_MAGIC (MSR23_DRAM + 0x38) /* "LIVE", "STAR" */ +#define MSR23_LOG_WPTR (MSR23_DRAM + 0x80) +#define MSR23_LOG (MSR23_DRAM + 0x200) +#define MSR23_CPU_START 0x100028 +#define MSR23_STATUS 0x100124 +#define MSR23_A2I_CTRL 0x108110 +#define MSR23_I2A_CTRL 0x108114 +#define MSR23_A2I_SEND 0x108800 +#define MSR23_I2A_RECV 0x108830 +#define MSR23_MBOX_EMPTY BIT(17) +#define MSR23_FW_STATE 0x78 /* reg[0] */ +#define MSR23_MAGIC_LIVE 0x4556494c +#define MSR23_MAGIC_STAR 0x52415453 +#define MSR23_SHMEM_SIZE SZ_16K +#define MAGIC_FDBE 0xfdbefdbe + +struct msr23_wr { + u8 win; + u32 off; + u32 val; + u16 settle_us; /* wait this long after the write */ +}; + +/* + * T8142: the writes that prepare the engine before its core starts, in order. + * The ADT names no fields; by aperture: + * - reg[0] (engine control): a reset pulse at +0x4 (the core needs ~1 ms + * after it, so the release write carries settle_us), then +0x48/+0x50 + * and, at the end, +0x28..+0x54 and the +0x10288.. and +0x10688.. tables; + * - reg[3]: +0x0..+0x34, +0x100.., +0x300.., +0x404.. and +0x4008..; + * - reg[8] and reg[6]: one group each. + */ +static const struct msr23_wr msr23_t8142_powerup[] = { + {0, 0x00004, 0x00000001}, {0, 0x00004, 0x00000000, 1000}, {0, 0x00050, 0x00000000}, + {0, 0x00048, 0x00000000}, {0, 0x00050, 0x00000003}, + {3, 0x00000, 0x8000001b}, {3, 0x00004, 0x800c000d}, {3, 0x00008, 0x800c000d}, + {3, 0x0000c, 0x800c000d}, {3, 0x00010, 0x80000003}, {3, 0x00014, 0x80000003}, + {3, 0x00018, 0x80000011}, {3, 0x0001c, 0x80000014}, {3, 0x00020, 0x8014000c}, + {3, 0x00024, 0x80000004}, {3, 0x00028, 0x80000004}, {3, 0x0002c, 0x80000015}, + {3, 0x00030, 0x9000000f}, {3, 0x00034, 0x9000000f}, {3, 0x00100, 0x000000ff}, + {3, 0x00104, 0x00010003}, {3, 0x00108, 0x000413b1}, {3, 0x00300, 0x1c000211}, + {3, 0x00304, 0x04040000}, {3, 0x00314, 0x80000002}, {3, 0x0031c, 0x80000009}, + {3, 0x00404, 0x00100071}, {3, 0x00748, 0x00200000}, {3, 0x00848, 0x02000120}, + {3, 0x00a00, 0x7fffffff}, {3, 0x00a04, 0x00000101}, {3, 0x04008, 0x00000000}, + {3, 0x0400c, 0x00000000}, {3, 0x04014, 0x00000000}, {3, 0x04018, 0x00000000}, + {3, 0x0401c, 0x00000001}, + {8, 0x00000, 0x00000000}, {8, 0x00010, 0x0001fbf2}, {8, 0x00014, 0x0001fbf2}, + {8, 0x00018, 0x0001fbf3}, {8, 0x0001c, 0x0001fbf0}, {8, 0x00020, 0x0001fbf0}, + {6, 0x00000, 0x00100011}, + {0, 0x00028, 0x0101005f}, {0, 0x0002c, 0x0000005e}, {0, 0x00030, 0x0000015c}, + {0, 0x0004c, 0x01ffffff}, {0, 0x00050, 0x00000003}, {0, 0x00054, 0x00000003}, + {0, 0x10288, 0x0000000c}, {0, 0x1028c, 0x00000006}, {0, 0x10290, 0x00000004}, + {0, 0x10294, 0x00000002}, {0, 0x10298, 0x00000001}, + {0, 0x10688, 0x00010012}, {0, 0x1068c, 0x0002001c}, {0, 0x10690, 0x00040030}, + {0, 0x10694, 0x00080042}, {0, 0x106a4, 0x4ec20040}, {0, 0x106b8, 0x4ec20040}, + {0, 0x106cc, 0x4ec20040}, {0, 0x106e0, 0x4ec20040}, {0, 0x106e4, 0x00200028}, + {0, 0x106f4, 0x4ec2004c}, {0, 0x106f8, 0x0040003c}, {0, 0x10708, 0x4ec20040}, + {0, 0x1070c, 0x0020000c}, {0, 0x1071c, 0x4ec20010}, {0, 0x10720, 0x0020000c}, + {0, 0x10730, 0x4ec20040}, {0, 0x10744, 0x4ec20040}, {0, 0x10758, 0x4ec2006c}, + {0, 0x1075c, 0x00400054}, {0, 0x1076c, 0x4ec200d8}, {0, 0x10770, 0x008000a4}, + {0, 0x10780, 0x4ec200b0}, {0, 0x10784, 0x00400088}, {0, 0x10794, 0x4ec20040}, + {0, 0x107a8, 0x4ec20040}, {0, 0x107bc, 0x4ec200ac}, {0, 0x107c0, 0x00400084}, + {0, 0x107d0, 0x4ec20040}, {0, 0x107d4, 0x00400024}, {0, 0x107e4, 0x4ec20040}, + {0, 0x107f8, 0x4ec20040}, {0, 0x107fc, 0x00400014}, {0, 0x1080c, 0x4ec20034}, + {0, 0x10810, 0x00400028}, {0, 0x10820, 0x4ec2001c}, {0, 0x10824, 0x00400014}, + {0, 0x10834, 0x4ec20040}, {0, 0x10848, 0x4ec20040}, +}; + +/* + * Jobs. + * Everything the firmware reads is DMA memory addressed by its offset in the + * DART window that starts at 1 << 40: + * - a ring of block-list records in shared page 0x02 (0x400 words); the AP + * writes a record, then reg[4]+0x10038 = its write pointer in words + * (bit 31 flips on wrap). A record: 0xfdbefdbe, seq << 8 | 2, a job word, + * pair count << 16, then (block word, size word) pairs. A block word is + * (offset >> 7) << 8 | block id; a size word holds the size in 32-byte + * units from bit 20; + * - the blocks: a register image (80 KiB) and a spill buffer. The job word + * 0x72000000 has the firmware tile the job; with bit 31, the AP builds the + * tile array (block 15) instead, which this driver does not; + * - completion: the status ring at reg[5]+0x83a00 (0x200 words, 20-word + * entries), its write pointer reg[4]+0x30008, the AP acknowledges with + * reg[4]+0x10010. + * The driver builds the register image from the job's parameters + * (apple-scaler-msr23.c). + */ +#define MSR23_WIN BIT_ULL(40) +#define MSR23_WIN_SPAN SZ_2G /* block words hold offset >> 7 in 24 bits */ +#define MSR23_RING_WORDS 0x400 +#define MSR23_STS_BASE 0x83a00 /* reg[5] */ +#define MSR23_STS_WORDS 0x200 +#define MSR23_STS_ENTRY 0x14 +#define MSR23_STS_OK0 0x00140007 /* status words 0 and 2 of a job that completed */ +#define MSR23_STS_OK2 0x00000200 +#define MSR23_Q_SUBMIT 0x10038 /* reg[4], 64-bit */ +#define MSR23_Q_STAMP 0x100f8 +#define MSR23_Q_STS_READ 0x10010 +#define MSR23_Q_STS_WRITE 0x30008 +#define MSR23_Q_SUB_DONE 0x30040 +#define MSR23_JOB_TIMEOUT_US 1000000 + +struct msr23 { + struct device *dev; + struct apple_scaler *asc; + void __iomem *w[10]; + void __iomem *dart; /* read only: the window registers and the error word */ + resource_size_t w5_phys; + /* shared pages, in the order of S3's messages (ids 0x10, 0x01, 0x02, 0x23) */ + void *page[4]; + dma_addr_t page_iova[4]; + bool window; /* IOVAs are inside the 1 << 40 window */ + bool started; /* S3 saw LIVE/STAR */ + u64 ring_wptr, sts_rptr; + u32 seq; + struct work_struct work; + struct apple_scaler_ctx *ctx; +}; + +/* + * The DART window the firmware addresses through: dart+0x300 = 1, +0x308 = + * 0x10000000 (base 1 << 40 in 4K pages), +0x310 = 0x3fffffff. + */ +static void msr23_dart(struct msr23 *m, const char *when) +{ + if (!m->dart) + return; + dev_dbg(m->dev, + "MSR23 %s: dart +0x300 %#x +0x308 %#x +0x310 %#x error +0x100 %#x tcr0/1 %#x %#x ttbr0/1 %#x %#x\n", + when, readl(m->dart + 0x300), readl(m->dart + 0x308), readl(m->dart + 0x310), + readl(m->dart + 0x100), readl(m->dart + 0x1000), readl(m->dart + 0x1004), + readl(m->dart + 0x1400), readl(m->dart + 0x1404)); +} + +static bool msr23_text_valid(const u32 *vec) +{ + return vec[0] == MSR23_SP_INIT && vec[1] >= MSR23_TEXT_BASE && + vec[1] < MSR23_TEXT_BASE + MSR23_SRAM_TEXT_MAX; +} + +/* S0: what the SRAM holds. Returns 1 (valid, matches the file or no file), 0 (absent/different). */ +static int msr23_s0(struct msr23 *m, const struct firmware *fw) +{ + void __iomem *w0 = m->w[0], *w5 = m->w[5]; + size_t len; + u32 vec[2], crc_sram, crc_file = 0; + bool valid, same = false; + void *buf; + + /* a file shorter than the vector or larger than the SRAM is no image: compare nothing */ + if (fw && (fw->size < sizeof(vec) || fw->size > MSR23_SRAM_TEXT_MAX)) { + dev_warn(m->dev, "MSR23 S0: %s has %zu bytes: not an MSR __TEXT image, ignored\n", + m->asc->variant->fw_name, fw->size); + fw = NULL; + } + len = fw ? fw->size : MSR23_TEXT_SIZE; + buf = kvmalloc(len, GFP_KERNEL); + if (!buf) + return -ENOMEM; + memcpy_fromio(buf, w5, len); + memcpy(vec, buf, sizeof(vec)); + valid = msr23_text_valid(vec); + crc_sram = crc32_le(0, buf, len); + if (fw) { + crc_file = crc32_le(0, fw->data, fw->size); + same = !memcmp(buf, fw->data, fw->size); + } + kvfree(buf); + + dev_dbg(m->dev, + "MSR23 S0: SRAM vector SP %#x reset %#x (%s), crc32 %#x over %#zx; file %s crc32 %#x: %s\n", + vec[0], vec[1], valid ? "an MSR image" : "no image", crc_sram, len, + fw ? m->asc->variant->fw_name : "(none)", crc_file, + !fw ? "no file to compare" : + same ? "SRAM == file (pre-loaded by iBoot)" : + valid ? "SRAM holds a different image" : "SRAM empty"); + dev_dbg(m->dev, + "MSR23 S0: state +0x78 %#x status %#x magic %#x log wptr %#x mbox a2i %#x i2a %#x/%#x %#x/%#x (before the start: 0, -, -, -, 0x20001 x4)\n", + readl(w0 + MSR23_FW_STATE), readl(w5 + MSR23_STATUS), readl(w5 + MSR23_DRAM_MAGIC), + readl(w5 + MSR23_LOG_WPTR), readl(w5 + MSR23_A2I_CTRL), readl(w5 + MSR23_I2A_CTRL), + readl(w5 + 0x124110), readl(w5 + 0x124114), readl(w5 + 0x100058)); + return valid && (same || !fw); +} + +/* S1: write __TEXT into the SRAM and read it back. */ +static int msr23_s1(struct msr23 *m, const struct firmware *fw) +{ + void *buf; + int ret = 0; + + if (fw->size < 2 * sizeof(u32) || fw->size > MSR23_SRAM_TEXT_MAX || + !msr23_text_valid((const u32 *)fw->data)) { + dev_err(m->dev, "MSR23 S1: %s is not an MSR __TEXT image (%zu bytes)\n", + m->asc->variant->fw_name, fw->size); + return -EINVAL; + } + memcpy_toio(m->w[5], fw->data, fw->size); + /* the ring record before the write pointer that hands it over */ + wmb(); + buf = kvmalloc(fw->size, GFP_KERNEL); + if (!buf) + return -ENOMEM; + memcpy_fromio(buf, m->w[5], fw->size); + if (memcmp(buf, fw->data, fw->size)) { + size_t i; + + for (i = 0; i < fw->size && ((u8 *)buf)[i] == fw->data[i]; i++) + ; + dev_err(m->dev, + "MSR23 S1: upload FAILED: readback differs from %#zx (the SRAM is not AP-writable this way)\n", + i); + ret = -EIO; + } else { + dev_dbg(m->dev, "MSR23 S1: uploaded %#zx bytes of %s to SRAM, readback ok\n", + fw->size, m->asc->variant->fw_name); + } + kvfree(buf); + return ret; +} + +static void msr23_log_tail(struct msr23 *m, const char *when) +{ + void __iomem *w5 = m->w[5]; + u32 e[4]; + int i; + + dev_dbg(m->dev, + "MSR23 %s: magic %#x status %#x log wptr %#x/%#x dram+0x18 %#x %#x %#x %#x +0x30 %#x %#x\n", + when, readl(w5 + MSR23_DRAM_MAGIC), readl(w5 + MSR23_STATUS), + readl(w5 + MSR23_LOG_WPTR), readl(w5 + MSR23_LOG_WPTR + 4), + readl(w5 + MSR23_DRAM + 0x18), readl(w5 + MSR23_DRAM + 0x1c), + readl(w5 + MSR23_DRAM + 0x20), readl(w5 + MSR23_DRAM + 0x24), + readl(w5 + MSR23_DRAM + 0x30), readl(w5 + MSR23_DRAM + 0x34)); + for (i = 0; i < 8; i++) { + memcpy_fromio(e, w5 + MSR23_LOG + 16 * i, sizeof(e)); + if (!e[0] && !e[1]) + break; + dev_dbg(m->dev, "MSR23 %s: log[%d] %08x %08x %08x %08x\n", when, i, e[0], e[1], + e[2], e[3]); + } +} + +static int msr23_recv(struct msr23 *m, u32 msg[4], unsigned int timeout_us) +{ + u32 ctl; + int ret; + + ret = readl_poll_timeout(m->w[5] + MSR23_I2A_CTRL, ctl, !(ctl & MSR23_MBOX_EMPTY), 100, + timeout_us); + if (ret) + return ret; + msg[0] = readl(m->w[5] + MSR23_I2A_RECV + 0x0); + msg[1] = readl(m->w[5] + MSR23_I2A_RECV + 0x4); + msg[2] = readl(m->w[5] + MSR23_I2A_RECV + 0x8); + msg[3] = readl(m->w[5] + MSR23_I2A_RECV + 0xc); /* the last read pops */ + return 0; +} + +static int msr23_send(struct msr23 *m, u64 msg0, u64 msg1) +{ + u32 ctl = readl(m->w[5] + MSR23_A2I_CTRL); + + writel(lower_32_bits(msg0), m->w[5] + MSR23_A2I_SEND + 0x0); + writel(upper_32_bits(msg0), m->w[5] + MSR23_A2I_SEND + 0x4); + writel(lower_32_bits(msg1), m->w[5] + MSR23_A2I_SEND + 0x8); + writel(upper_32_bits(msg1), m->w[5] + MSR23_A2I_SEND + 0xc); + dev_dbg(m->dev, "MSR23 S3: sent %#018llx %#llx (a2i before %#x after %#x)\n", msg0, msg1, + ctl, readl(m->w[5] + MSR23_A2I_CTRL)); + return 0; +} + +/* S2: power-up table, then the start handshake. */ +static int msr23_s2(struct msr23 *m) +{ + static const u32 mbox[] = { MSR23_A2I_CTRL, MSR23_I2A_CTRL, 0x124110, 0x124114 }; + void __iomem *w0 = m->w[0], *w5 = m->w[5]; + const struct apple_scaler_variant *var = m->asc->variant; + u32 v, a, b, msg[4]; + unsigned int i; + int ret; + + for (i = 0; i < var->num_powerup; i++) { + const struct msr23_wr *wr = &var->powerup[i]; + + writel(wr->val, m->w[wr->win] + wr->off); + if (wr->settle_us) + usleep_range(wr->settle_us, 2 * wr->settle_us); + } + + for (i = 0; i < ARRAY_SIZE(mbox); i++) { + v = readl(w5 + mbox[i]); + writel(v & ~1U, w5 + mbox[i]); + } + v = readl(w0 + MSR23_FW_STATE); + writel(0xe, w5 + MSR23_CPU_START); + a = readl(w5 + 0x100058); + b = readl(w5 + 0x10005c); + writel(0, w0 + MSR23_FW_STATE); + writel(0, w5 + MSR23_CPU_START); + ret = readl_poll_timeout(w0 + MSR23_FW_STATE, v, v == 2, 100, 200000); + dev_dbg(m->dev, + "MSR23 S2: start: +0x58/+0x5c %#x %#x (want 1 1), state +0x78 -> %#x: %s\n", a, b, + v, ret ? "NO ANSWER in 200 ms" : "core running (2)"); + if (ret) { + msr23_log_tail(m, "S2"); + return ret; + } + ret = msr23_recv(m, msg, 100000); + if (ret) + dev_warn(m->dev, "MSR23 S2: no hello in the mailbox (i2a %#x)\n", + readl(w5 + MSR23_I2A_CTRL)); + else + dev_dbg(m->dev, + "MSR23 S2: hello %08x %08x %08x %08x (want 00000100 0 0 00100100)\n", + msg[0], msg[1], msg[2], msg[3]); + msr23_log_tail(m, "S2"); + return 0; +} + +/* S3: the init message and the four shared pages. */ +/* The firmware's view of an IOVA: its offset in the 1 << 40 window. */ +static u32 msr23_off(dma_addr_t iova) +{ + return lower_32_bits(iova - MSR23_WIN); +} + +static bool msr23_in_window(dma_addr_t iova, size_t len) +{ + return iova >= MSR23_WIN && iova + len <= MSR23_WIN + MSR23_WIN_SPAN; +} + +/* every plane of a buffer, over its whole mapped length */ +static bool msr23_vb_in_window(struct vb2_buffer *vb) +{ + unsigned int p; + + for (p = 0; p < vb->num_planes; p++) + if (!msr23_in_window(vb2_dma_contig_plane_dma_addr(vb, p), vb2_plane_size(vb, p))) + return false; + return true; +} + +static int msr23_s3(struct msr23 *m) +{ + static const u8 page_id[] = { 0x10, 0x01, 0x02, 0x23 }; + u64 dram = m->w5_phys + MSR23_DRAM; + u32 msg[4], v; + unsigned int i; + int ret; + + m->window = true; + for (i = 0; i < ARRAY_SIZE(page_id); i++) { + if (!m->page[i]) /* a restart after sleep reuses them */ + m->page[i] = dmam_alloc_coherent(m->dev, MSR23_SHMEM_SIZE, &m->page_iova[i], + GFP_KERNEL); + if (!m->page[i]) + return -ENOMEM; + memset(m->page[i], 0, MSR23_SHMEM_SIZE); + if (!msr23_in_window(m->page_iova[i], MSR23_SHMEM_SIZE)) + m->window = false; + } + /* + * Boot 35740333 sent raw IOVAs below 4 GiB (0xffffc000...): the firmware + * took them (STAR) but never touched the pages. The job path needs the + * window (1 << 40 + 0x0/0x8000/0x10000/0x18000 work). + */ + if (!m->window) + dev_warn(m->dev, "MSR23 S3: pages outside the 1 << 40 window (%pad): no job path\n", + &m->page_iova[0]); + msr23_dart(m, "S3 before"); + /* init message 0x00080200 on endpoint 3; the high word is the core RAM's address. */ + msr23_send(m, ((u64)lower_32_bits(dram) << 32) | 0x00080200, 3); + for (i = 0; i < ARRAY_SIZE(page_id); i++) { + u32 off = m->window ? msr23_off(m->page_iova[i]) : lower_32_bits(m->page_iova[i]); + + msr23_send(m, ((u64)off << 32) | 0x40000500 | (page_id[i] << 16), 0x100); + } + for (i = 0; i < 4; i++) { + if (msr23_recv(m, msg, 100000)) + break; + dev_dbg(m->dev, "MSR23 S3: reply %08x %08x %08x %08x\n", msg[0], msg[1], msg[2], + msg[3]); + } + ret = readl_poll_timeout(m->w[5] + MSR23_DRAM_MAGIC, v, + v == MSR23_MAGIC_LIVE || v == MSR23_MAGIC_STAR, 1000, 500000); + dev_dbg(m->dev, "MSR23 S3: pages %pad %pad %pad %pad (window %s); magic %#x: %s\n", + &m->page_iova[0], &m->page_iova[1], &m->page_iova[2], &m->page_iova[3], + m->window ? "yes" : "NO", v, + ret ? "no LIVE/STAR in 500 ms" : v == MSR23_MAGIC_STAR ? "STAR (started)" : "LIVE"); + msr23_log_tail(m, "S3"); + msr23_dart(m, "S3 after"); + m->started = !ret; + return ret; +} + +/* ---- MSR23 jobs ----------------------------------------------------------- */ + +static void msr23_cancel_work(void *data) +{ + struct msr23 *m = data; + + cancel_work_sync(&m->work); +} + +/* + * Chroma subsampling of a MSR23 format (not v4l2_format_info(): it gives P010 + * vdiv 1). 0: no chroma plane (R'G'B' or grey). + */ +static void msr23_sub(u32 v4l2, u32 *hs, u32 *vs) +{ + switch (v4l2) { + case V4L2_PIX_FMT_NV12: + case V4L2_PIX_FMT_NV12M: + case V4L2_PIX_FMT_P010: + *hs = 2; + *vs = 2; + return; + case V4L2_PIX_FMT_NV16: + *hs = 2; + *vs = 1; + return; + case V4L2_PIX_FMT_NV24: + *hs = 1; + *vs = 1; + return; + } + *hs = 0; + *vs = 0; +} + +static void msr23_pic(struct msr23_pic *p, const struct v4l2_pix_format_mplane *f) +{ + u32 hs, vs; + + msr23_sub(f->pixelformat, &hs, &vs); + p->fourcc = f->pixelformat; + p->width = f->width; + p->height = f->height; + p->stride[0] = f->plane_fmt[0].bytesperline; + if (!hs) + p->stride[1] = 0; + else if (f->num_planes > 1) + p->stride[1] = f->plane_fmt[1].bytesperline; + else + p->stride[1] = f->plane_fmt[0].bytesperline * 2 / hs; +} + +static enum v4l2_ycbcr_encoding msr23_enc(const struct v4l2_pix_format_mplane *f) +{ + if (f->ycbcr_enc == V4L2_YCBCR_ENC_601 || f->ycbcr_enc == V4L2_YCBCR_ENC_BT2020) + return f->ycbcr_enc; + return V4L2_YCBCR_ENC_709; +} + +static bool msr23_full(const struct v4l2_pix_format_mplane *f) +{ + return f->quantization == V4L2_QUANTIZATION_FULL_RANGE; +} + +/* + * The job for a context's formats. The Y'CbCr side carries the matrix and the + * range. Y'CbCr to Y'CbCr only scales: a matrix or range change is a + * conversion the engine would do through R'G'B', which the builder does not + * cover. + */ +static int msr23_job_of(const struct apple_scaler_ctx *ctx, struct msr23_job *job) +{ + const struct v4l2_pix_format_mplane *s = &ctx->src, *d = &ctx->dst; + bool ys = v4l2_is_format_yuv(v4l2_format_info(s->pixelformat)); + bool yd = v4l2_is_format_yuv(v4l2_format_info(d->pixelformat)); + const struct v4l2_pix_format_mplane *y = ys ? s : d; + + if (ys && yd && (msr23_enc(s) != msr23_enc(d) || msr23_full(s) != msr23_full(d))) + return -EINVAL; + memset(job, 0, sizeof(*job)); + msr23_pic(&job->src, s); + msr23_pic(&job->dst, d); + job->enc = msr23_enc(y); + job->full = msr23_full(y); + job->crop = ctx->crop; + job->compose = ctx->compose; + job->rotate = ctx->rotate; + job->hflip = ctx->hflip; + job->vflip = ctx->vflip; + return msr23_check(job); +} + +static dma_addr_t msr23_plane(const struct v4l2_pix_format_mplane *pix, struct vb2_buffer *vb, + unsigned int p) +{ + if (pix->num_planes > 1) + return vb2_dma_contig_plane_dma_addr(vb, p); + return vb2_dma_contig_plane_dma_addr(vb, 0) + + (dma_addr_t)p * pix->plane_fmt[0].bytesperline * pix->height; +} + +static void msr23_ptr(u32 *img, u32 at, u64 a) +{ + img[at / 4] = lower_32_bits(a); + img[at / 4 + 1] = upper_32_bits(a); +} + +static u64 msr23_advance(u64 ptr, u32 n, u32 size) +{ + u64 idx = (ptr & 0x7fffffff) + n; + + if (idx >= size) { + idx -= size; + ptr ^= BIT_ULL(31); + } + return (ptr & BIT_ULL(31)) | idx; +} + +/* One job, synchronous: build it at our IOVAs, submit, wait for its status entry. */ +static int msr23_run(struct msr23 *m, struct apple_scaler_ctx *ctx, struct vb2_buffer *src, + struct vb2_buffer *dst) +{ + void __iomem *w4 = m->w[4], *w5 = m->w[5]; + u32 *ring = m->page[2], *img, st[MSR23_STS_ENTRY], rec[4 + 2 * MSR23_NBLOCKS]; + char id[40]; + struct msr23_job job; + struct msr23_built out; + dma_addr_t img_iova, spill_iova; + void *spill = NULL; + size_t spill_len = 0; + u32 k, seq, err0, idx, nwords; + u64 wptr, sts; + int ret; + + snprintf(id, sizeof(id), "%.4s %ux%u -> %.4s %ux%u", (char *)&ctx->src.pixelformat, + ctx->src.width, ctx->src.height, (char *)&ctx->dst.pixelformat, ctx->dst.width, + ctx->dst.height); + ret = msr23_job_of(ctx, &job); + if (ret) { + dev_warn_ratelimited(m->dev, "MSR23 job %s: not supported\n", id); + return ret; + } + /* zeroed: the builder writes only the words a job sets */ + img = dma_alloc_coherent(m->dev, MSR23_IMG_LEN, &img_iova, GFP_KERNEL); + if (!img) + return -ENOMEM; + ret = msr23_build(&job, img, &out); + if (ret) + goto out; + spill_len = (size_t)(out.nc0 + out.nc1) * MSR23_NC_PAGE; + spill = dma_alloc_coherent(m->dev, spill_len, &spill_iova, GFP_KERNEL); + ret = -ENOMEM; + if (!spill) + goto out; + ret = -ERANGE; + if (!msr23_in_window(img_iova, MSR23_IMG_LEN) || + !msr23_in_window(spill_iova, spill_len) || + !msr23_vb_in_window(src) || !msr23_vb_in_window(dst)) { + dev_err_ratelimited(m->dev, "MSR23 job: a buffer is outside the 1 << 40 window\n"); + goto out; + } + + /* NC0 at the start of the spill buffer, NC1 after it */ + msr23_ptr(img, MSR23_PTR_NC0, spill_iova); + msr23_ptr(img, MSR23_PTR_NC1, spill_iova + (dma_addr_t)out.nc0 * MSR23_NC_PAGE); + for (k = 0; k < out.planes[0]; k++) + msr23_ptr(img, MSR23_PTR_SRC(k), msr23_plane(&ctx->src, src, k)); + for (k = 0; k < out.planes[1]; k++) + msr23_ptr(img, MSR23_PTR_DST(k), msr23_plane(&ctx->dst, dst, k) + out.dst_off[k]); + /* + * Block 0 +0x60 is the frame id too: it must equal the record's word 1 + * (the tiler refuses a job where they differ). + */ + seq = ++m->seq & 0xffffff; + img[MSR23_FRAME_ID / 4] = seq << 8 | 2; + + /* The record: header, then the block list. */ + rec[0] = MAGIC_FDBE; + rec[1] = seq << 8 | 2; + rec[2] = MSR23_HDR2_FW_TILING; + rec[3] = (2 * MSR23_NBLOCKS) << 16; + for (k = 0; k < MSR23_NBLOCKS; k++) { + u32 off = msr23_off(img_iova + msr23_blocks[k].off); + + rec[4 + 2 * k] = (off >> 7) << 8 | msr23_blocks[k].id; + rec[5 + 2 * k] = msr23_blocks[k].size; + } + nwords = ARRAY_SIZE(rec); + wptr = m->ring_wptr; + idx = wptr & 0x7fffffff; + for (k = 0; k < nwords; k++) + ring[(idx + k) % MSR23_RING_WORDS] = rec[k]; + + err0 = m->dart ? readl(m->dart + 0x100) : 0; + dma_wmb(); + m->ring_wptr = msr23_advance(wptr, nwords, MSR23_RING_WORDS); + writeq(ktime_get_ns() & 0xffffffff, w4 + MSR23_Q_STAMP); + writeq(m->ring_wptr, w4 + MSR23_Q_SUBMIT); + /* around each submission: interrupt acknowledge/unmask */ + writel(0x80000000, w5 + 0x100170); + writel(1, w5 + 0x100178); + writel(0x80000000, w5 + 0x100178); + + ret = readq_poll_timeout(w4 + MSR23_Q_STS_WRITE, sts, sts != m->sts_rptr, 200, + MSR23_JOB_TIMEOUT_US); + if (ret) { + dev_err(m->dev, + "MSR23 job %s seq %u: no status in 1 s (submit %#llx, firmware took %#llx, status %#llx/%#llx, dart error %#x, magic %#x)\n", + id, seq, m->ring_wptr, readq(w4 + MSR23_Q_SUB_DONE), + readq(w4 + MSR23_Q_STS_WRITE), m->sts_rptr, + m->dart ? readl(m->dart + 0x100) : 0, readl(w5 + MSR23_DRAM_MAGIC)); + msr23_log_tail(m, "job"); + /* + * The firmware may still be working on this job and DMA into its buffers later: + * keep them (leak them) and take the core out of service, so no further job reaches + * it until a resume restarts it. + */ + m->started = false; + img = NULL; + spill = NULL; + dev_err(m->dev, + "MSR23: job timed out; core out of service, job buffers kept (leaked) until reboot\n"); + goto out; + } + for (k = 0; k < MSR23_STS_ENTRY; k++) + st[k] = readl(w5 + MSR23_STS_BASE + + 4 * (((m->sts_rptr & 0x7fffffff) + k) % MSR23_STS_WORDS)); + m->sts_rptr = msr23_advance(m->sts_rptr, MSR23_STS_ENTRY, MSR23_STS_WORDS); + writeq(m->sts_rptr, w4 + MSR23_Q_STS_READ); + if (m->dart && readl(m->dart + 0x100) != err0) { + dev_err(m->dev, "MSR23 job %s: DART error %#x\n", id, readl(m->dart + 0x100)); + ret = -EIO; + } else if ((st[1] & 0xffffff00) != (seq << 8)) { + /* + * The firmware is out of step: after a job it aborted, every later + * status entry was the previous one or zeros and the outputs were + * untouched. It may still own this job's buffers: keep them, as on a + * timeout, and take the core out of service rather than return + * empty frames as done. + */ + dev_err(m->dev, + "MSR23 job %s: status entry %08x %08x %08x %08x is not for seq %u; core out of service\n", + id, st[0], st[1], st[2], st[3], seq); + msr23_log_tail(m, "job"); + m->started = false; + img = NULL; + spill = NULL; + ret = -EIO; + } else if (st[0] != MSR23_STS_OK0 || st[2] != MSR23_STS_OK2) { + /* + * Every completed job ends 00140007 00000200. A job the + * engine aborted ended 0015000f 00001201, and the firmware + * wrote no status entry after it. + */ + dev_err(m->dev, + "MSR23 job %s seq %u: error status %08x %08x %08x %08x; core out of service\n", + id, seq, st[0], st[1], st[2], st[3]); + msr23_log_tail(m, "job"); + m->started = false; + ret = -EIO; + } else { + dev_dbg(m->dev, "MSR23 job %s seq %u done (NC %u + %u pages)\n", id, seq, + out.nc0, out.nc1); + } +out: + if (spill) + dma_free_coherent(m->dev, spill_len, spill, spill_iova); + if (img) + dma_free_coherent(m->dev, MSR23_IMG_LEN, img, img_iova); + return ret; +} + +static void msr23_work(struct work_struct *work) +{ + struct msr23 *m = container_of(work, struct msr23, work); + struct apple_scaler_ctx *ctx = m->ctx; + struct vb2_v4l2_buffer *src, *dst; + int ret; + + src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); + dst = v4l2_m2m_next_dst_buf(ctx->fh.m2m_ctx); + if (!m->started) + ret = -EIO; /* the core did not come back (resume): fail, never touch it */ + else + ret = src && dst ? msr23_run(m, ctx, &src->vb2_buf, &dst->vb2_buf) : -EINVAL; + m->ctx = NULL; + asc_finish(m->asc, ctx, ret); +} + +/* After system sleep: start the core again from what the SRAM holds (never an upload here). */ +static void msr23_restart(struct msr23 *m) +{ + u32 vec[2]; + + memcpy_fromio(vec, m->w[5], sizeof(vec)); + if (!msr23_text_valid(vec)) { + dev_warn(m->dev, + "MSR23: resumed with no image in the SRAM (SP %#x): the core stays down\n", + vec[0]); + m->started = false; + return; + } + if (msr23_s2(m) || msr23_s3(m)) { + dev_warn(m->dev, "MSR23: restart after resume failed\n"); + m->started = false; + return; + } + m->ring_wptr = readq(m->w[4] + MSR23_Q_SUBMIT); + m->sts_rptr = readq(m->w[4] + MSR23_Q_STS_READ); + m->seq = 0; + dev_dbg(m->dev, "MSR23: restarted after resume (submit %#llx, status %#llx)\n", + m->ring_wptr, m->sts_rptr); +} + +static void msr23_device_run(struct apple_scaler *asc, struct apple_scaler_ctx *ctx) +{ + /* asc_finish() drops one runtime-PM reference per job. */ + pm_runtime_get_noresume(asc->dev); + asc->msr->ctx = ctx; + queue_work(system_dfl_wq, &asc->msr->work); +} + +static void msr23_put(void *data) +{ + pm_runtime_put_sync_suspend(data); +} + +static int asc_register_video(struct apple_scaler *asc); + +static int asc_v23_probe(struct apple_scaler *asc, struct platform_device *pdev) +{ + struct device *dev = asc->dev; + const struct firmware *fw = NULL; + struct msr23 *m; + unsigned int i; + int ret, have; + + m = devm_kzalloc(dev, sizeof(*m), GFP_KERNEL); + if (!m) + return -ENOMEM; + m->dev = dev; + m->asc = asc; + asc->msr = m; + INIT_WORK(&m->work, msr23_work); + ret = devm_add_action_or_reset(dev, msr23_cancel_work, m); + if (ret) + return ret; + for (i = 0; i < ARRAY_SIZE(m->w); i++) { + struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, i); + + if (!res) + return dev_err_probe(dev, -EINVAL, "MSR23: no reg[%u]\n", i); + /* reg[1] and reg[8] are the same window: map without claiming. */ + m->w[i] = devm_ioremap(dev, res->start, resource_size(res)); + if (!m->w[i]) + return -ENOMEM; + if (i == 5) + m->w5_phys = res->start; + } + { + struct device_node *dn = of_parse_phandle(dev->of_node, "iommus", 0); + struct resource dr; + + if (dn && !of_address_to_resource(dn, 0, &dr)) + m->dart = devm_ioremap(dev, dr.start, 0x2000); + of_node_put(dn); + } + /* + * Every address a job holds is an offset in the DART window at 1 << 40 + * (dart +0x308 = 0x10000000), and block words keep offset >> 7 in 24 + * bits: top-down IOVA allocation below this limit lands in + * [1 << 40, 1 << 40 + 2 GiB). + */ + ret = dma_set_mask_and_coherent(dev, MSR23_WIN + MSR23_WIN_SPAN - 1); + if (ret) + return ret; + ret = devm_pm_runtime_enable(dev); + if (ret) + return ret; + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) + return dev_err_probe(dev, ret, "MSR23: failed to power up\n"); + + if (firmware_request_nowarn(&fw, m->asc->variant->fw_name, dev)) + fw = NULL; + dev_dbg(dev, "MSR23: version %#x, %s %s\n", readl(m->w[0]), m->asc->variant->fw_name, + fw ? "loaded" : "not found"); + + msr23_dart(m, "S0"); + have = msr23_s0(m, fw); + if (have < 0) { + ret = have; + goto out_put; + } + if (!have) { + u32 state = readl(m->w[0] + MSR23_FW_STATE); + u32 magic = readl(m->w[5] + MSR23_DRAM_MAGIC); + + /* + * Never write the SRAM under a core that has run since power-up: + * an upload after a module reload (state 2, magic "ABRT") hung + * the machine. Only a cold core (state 0, no magic) can take an + * image. + */ + if (state || magic) { + dev_warn(dev, + "MSR23: the core has run (state %#x magic %#x), not uploading; starting what the SRAM holds\n", + state, magic); + goto start; + } + if (!fw) { + dev_err(dev, "MSR23: the SRAM holds no image and %s is missing\n", + m->asc->variant->fw_name); + ret = -ENOENT; + goto out_put; + } + ret = msr23_s1(m, fw); + if (ret) + goto out_put; + } + +start: + ret = msr23_s2(m); + if (ret) + goto out_put; + ret = msr23_s3(m); + if (ret) + dev_warn(dev, "MSR23: init incomplete (%d)\n", ret); + release_firmware(fw); + /* Keep the runtime-PM reference while bound (SRAM and core stay up); drop it on unbind. */ + ret = devm_add_action_or_reset(dev, msr23_put, dev); + if (ret) + return ret; + if (!m->started || !m->window) { + dev_warn(dev, + "MSR23: firmware core up but not ready (started %d, window %d): no job path\n", + m->started, m->window); + return 0; + } + m->ring_wptr = readq(m->w[4] + MSR23_Q_SUBMIT); + m->sts_rptr = readq(m->w[4] + MSR23_Q_STS_READ); + dev_dbg(dev, + "MSR23 queues: submit %#llx (firmware took %#llx), status read %#llx (firmware wrote %#llx)\n", + m->ring_wptr, readq(m->w[4] + MSR23_Q_SUB_DONE), m->sts_rptr, + readq(m->w[4] + MSR23_Q_STS_WRITE)); + ret = asc_register_video(asc); + if (ret) + return ret; + dev_info(dev, "MSR23: job path up: %s\n", video_device_node_name(&asc->vdev)); + return 0; + +out_put: + release_firmware(fw); + pm_runtime_put_sync_suspend(dev); + return ret; +} + static void asc_cleanup(void *data) { struct apple_scaler *asc = data; cancel_delayed_work_sync(&asc->watchdog); + /* + * devres unwinds in reverse: this runs before msr23_put() powers the + * core down and before msr23_cancel_work(). A job still queued or + * running would touch the m2m device and the registers after them. + */ + if (asc->msr) + cancel_work_sync(&asc->msr->work); if (asc->m2m_dev) v4l2_m2m_release(asc->m2m_dev); v4l2_device_unregister(&asc->v4l2_dev); } +static int asc_register_video(struct apple_scaler *asc) +{ + struct device *dev = asc->dev; + struct video_device *vdev; + int ret; + + ret = v4l2_device_register(dev, &asc->v4l2_dev); + if (ret) + return ret; + ret = devm_add_action_or_reset(dev, asc_cleanup, asc); + if (ret) + return ret; + asc->m2m_dev = v4l2_m2m_init(&asc_m2m_ops); + if (IS_ERR(asc->m2m_dev)) { + ret = PTR_ERR(asc->m2m_dev); + asc->m2m_dev = NULL; + return ret; + } + + vdev = &asc->vdev; + strscpy(vdev->name, ASC_NAME, sizeof(vdev->name)); + vdev->fops = &asc_fops; + vdev->ioctl_ops = &asc_ioctl_ops; + vdev->release = video_device_release_empty; + vdev->lock = &asc->lock; + vdev->v4l2_dev = &asc->v4l2_dev; + vdev->vfl_dir = VFL_DIR_M2M; + vdev->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING; + /* crop and compose: MSR23 only (the MMIO engines convert at the same size) */ + if (!asc->variant->fw_fronted) { + v4l2_disable_ioctl(vdev, VIDIOC_G_SELECTION); + v4l2_disable_ioctl(vdev, VIDIOC_S_SELECTION); + } + video_set_drvdata(vdev, asc); + return video_register_device(vdev, VFL_TYPE_VIDEO, APPLE_M2M_VIDEO_NR); +} + static int asc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct apple_scaler *asc; - struct video_device *vdev; struct resource *res; int ret; @@ -789,6 +2034,8 @@ static int asc_probe(struct platform_device *pdev) if (!platform_get_resource(pdev, IORESOURCE_MEM, asc->variant->num_reg - 1)) return dev_err_probe(dev, -EINVAL, "expected %u register ranges\n", asc->variant->num_reg); + if (asc->variant->fw_fronted) + return asc_v23_probe(asc, pdev); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (resource_size(res) < ASC_MIN_REG_SIZE) return dev_err_probe(dev, -EINVAL, "MSR aperture too small\n"); @@ -823,30 +2070,7 @@ static int asc_probe(struct platform_device *pdev) if (ret) return ret; - ret = v4l2_device_register(dev, &asc->v4l2_dev); - if (ret) - return ret; - ret = devm_add_action_or_reset(dev, asc_cleanup, asc); - if (ret) - return ret; - asc->m2m_dev = v4l2_m2m_init(&asc_m2m_ops); - if (IS_ERR(asc->m2m_dev)) { - ret = PTR_ERR(asc->m2m_dev); - asc->m2m_dev = NULL; - return ret; - } - - vdev = &asc->vdev; - strscpy(vdev->name, ASC_NAME, sizeof(vdev->name)); - vdev->fops = &asc_fops; - vdev->ioctl_ops = &asc_ioctl_ops; - vdev->release = video_device_release_empty; - vdev->lock = &asc->lock; - vdev->v4l2_dev = &asc->v4l2_dev; - vdev->vfl_dir = VFL_DIR_M2M; - vdev->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING; - video_set_drvdata(vdev, asc); - return video_register_device(vdev, VFL_TYPE_VIDEO, APPLE_M2M_VIDEO_NR); + return asc_register_video(asc); } static void asc_remove(struct platform_device *pdev) @@ -891,6 +2115,17 @@ static const struct apple_scaler_variant apple_scaler_t8140 = { .msr20 = true, }; +/* M5: MSR23, firmware-fronted: the driver builds each job and queues it to the firmware. */ +static const struct apple_scaler_variant apple_scaler_t8142 = { + .hw_version = 23, + .num_reg = 10, + .msr20 = true, + .fw_fronted = true, + .fw_name = "apple/msr-t8142.bin", + .powerup = msr23_t8142_powerup, + .num_powerup = ARRAY_SIZE(msr23_t8142_powerup), +}; + static const struct of_device_id asc_of_match[] = { { .compatible = "apple,t8103-scaler", .data = &apple_scaler_t8103 }, { .compatible = "apple,t6000-scaler", .data = &apple_scaler_t6000 }, @@ -898,6 +2133,7 @@ static const struct of_device_id asc_of_match[] = { { .compatible = "apple,t8132-scaler", .data = &apple_scaler_t8132 }, { .compatible = "apple,t6041-scaler", .data = &apple_scaler_t6041 }, { .compatible = "apple,t8140-scaler", .data = &apple_scaler_t8140 }, + { .compatible = "apple,t8142-scaler", .data = &apple_scaler_t8142 }, { } }; MODULE_DEVICE_TABLE(of, asc_of_match); @@ -915,3 +2151,4 @@ module_platform_driver(asc_driver); MODULE_DESCRIPTION("Apple silicon scaler and colour-space converter"); MODULE_LICENSE("GPL"); +MODULE_FIRMWARE("apple/msr-t8142.bin"); diff --git a/drivers/media/platform/apple/scaler/apple-scaler-hw.c b/drivers/media/platform/apple/scaler/apple-scaler-hw.c index bc766c47e19481..7730716b81d0f5 100644 --- a/drivers/media/platform/apple/scaler/apple-scaler-hw.c +++ b/drivers/media/platform/apple/scaler/apple-scaler-hw.c @@ -52,6 +52,32 @@ static const struct asc_format asc_formats[] = { .fourcc = V4L2_PIX_FMT_P010, .layout = 0xc, .code = 0x2, .sampling = 0x12, .swizzle = ASC_SWIZZLE_CBCR, .planes = 2, .bpp = { 2, 4 }, .hsub = 2, .vsub = 2, .yuv = true, .wide = true, + }, { + /* + * Bytes B, G, R, A with the alpha carried through (V4L2 ABGR32). + * MSR23 (M5) only: its jobs write the source's alpha byte to a + * BGRA output (J815 outputs matched the reference byte for byte, + * alpha included). How the earlier engines treat alpha is not + * checked, so they offer only ARGB32 and XRGB32. + */ + .fourcc = V4L2_PIX_FMT_ABGR32, .layout = 0x1, .code = 0x1e, + .sampling = 0x0, .swizzle = ASC_SWIZZLE_IDENTITY, .planes = 1, + .bpp = { 4 }, .hsub = 1, .vsub = 1, .alpha = true, .msr23_only = true, + }, { + /* + * MSR23 only. .code is the MSR23 plane code; MSR23 uses neither + * sampling nor swizzle, and .layout only keeps the table's rule + * (0x1 for one plane of R'G'B' or grey, 0xc for two planes). + */ + .fourcc = V4L2_PIX_FMT_NV16, .layout = 0xc, .code = 0x1, .planes = 2, + .bpp = { 1, 2 }, .hsub = 2, .vsub = 1, .yuv = true, .msr23_only = true, + }, { + .fourcc = V4L2_PIX_FMT_NV24, .layout = 0xc, .code = 0x1, .planes = 2, + .bpp = { 1, 2 }, .hsub = 1, .vsub = 1, .yuv = true, .msr23_only = true, + }, { + /* One 8-bit component, no colorimetry: GREY to GREY only. */ + .fourcc = V4L2_PIX_FMT_GREY, .layout = 0x1, .code = 0x1, .planes = 1, + .bpp = { 1 }, .hsub = 1, .vsub = 1, .msr23_only = true, }, { /* The AVE temporal filter's picture form; one buffer, four regions. */ .fourcc = V4L2_PIX_FMT_APPLE_L8V0, .layout = 0xc, .code = 0x78, diff --git a/drivers/media/platform/apple/scaler/apple-scaler-hw.h b/drivers/media/platform/apple/scaler/apple-scaler-hw.h index 46410b78eae4fc..b1106ca1dcf0ca 100644 --- a/drivers/media/platform/apple/scaler/apple-scaler-hw.h +++ b/drivers/media/platform/apple/scaler/apple-scaler-hw.h @@ -58,6 +58,7 @@ struct asc_csc { * @alpha: carries an alpha channel * @wide: samples are 16 bits in memory (more than 8 significant bits) * @lossless: Apple lossless compressed 4:2:0 in one buffer (asc_lossless_geom()) + * @msr23_only: offered only by the firmware-fronted MSR23 engine */ struct asc_format { u32 fourcc; @@ -73,6 +74,7 @@ struct asc_format { bool alpha; bool wide; bool lossless; + bool msr23_only; }; /** diff --git a/drivers/media/platform/apple/scaler/apple-scaler-msr23.c b/drivers/media/platform/apple/scaler/apple-scaler-msr23.c new file mode 100644 index 00000000000000..bdf79fedf9c70d --- /dev/null +++ b/drivers/media/platform/apple/scaler/apple-scaler-msr23.c @@ -0,0 +1,712 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Apple silicon scaler (MSR23, M5): job builder. + * + * The engine's firmware streams a register image into the hardware for each + * job: one block per register group (pipe, source and destination DMA, + * chroma resampling, colour matrix, scaler, dither). This builds that image + * from the job's parameters: the words that depend on the sizes, formats and + * matrix are computed, the others hold the fixed values below. + * + * Crop is the source region's size and origin, rotation and mirroring a + * field of the pipe word; the reader rotates, so the rest of the pipe works + * in the destination's orientation. Compose writes a picture of the + * rectangle's size at an offset into the destination. + * + * The firmware tiles the job itself, so no tile array is built. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "apple-scaler-hw.h" +#include "apple-scaler-msr23.h" + +/* + * The blocks of every job, in list order. Blocks 0, 1 and 14 hold the pipe, + * the source and the destination. + */ +const struct msr23_block msr23_blocks[MSR23_NBLOCKS] = { + { 0, MSR23_B0, 0x00c00200 }, { 1, MSR23_B1, 0x00c00200 }, { 3, 0x1e00, 0x00400200 }, + { 4, 0x1e80, 0x31c00200 }, { 5, 0x8200, 0x00400200 }, { 8, 0x9080, 0x03c00200 }, + { 11, 0xa600, 0x23c00200 }, { 12, 0xed80, 0x01400200 }, { 13, 0xf000, 0x09000200 }, + { 14, MSR23_B14, 0x00c00200 }, +}; +EXPORT_SYMBOL_IF_KUNIT(msr23_blocks); + +#define MSR23_B3 0x1e00 +#define MSR23_B8 0x9080 +#define MSR23_B11 0xa600 +#define MSR23_B12 0xed80 + +struct msr23_default { + u8 block; + u16 off; + u32 val; +}; + +#define MSR23_FILTER_BINS 8 +#define MSR23_FILTER_TAPS 144 + +struct msr23_filter { + u32 ratio; + s16 extra; + s16 taps[MSR23_FILTER_TAPS]; +}; + +/* + * Register defaults: words every firmware-tiled job carries with the same + * value (block, offset, value). + */ +static const struct msr23_default msr23_defaults[] = { + { 1, 0x84, 0x7d35d }, { 1, 0x88, 0x7d35d }, { 1, 0x8c, 0x7d35d }, { 1, 0x90, 0x7d35d }, + { 1, 0x94, 0x708 }, { 1, 0x98, 0x708 }, { 1, 0x9c, 0x708 }, { 1, 0xa0, 0x708 }, + { 1, 0xa4, 0x20 }, { 1, 0xa8, 0x20 }, { 1, 0xac, 0x20 }, { 1, 0xb0, 0x20 }, + { 1, 0xd4, 0x1 }, { 1, 0xe4, 0xffffffff }, { 1, 0x10c, 0x12345678 }, { 14, 0xc, 0x8000 }, + { 14, 0x64, 0xac25d }, { 14, 0x68, 0xac25d }, { 14, 0x6c, 0xac25d }, + { 14, 0x70, 0xc0ac208 }, { 14, 0x74, 0xc0ac208 }, { 14, 0x78, 0xc0ac208 }, + { 14, 0x7c, 0x4000600 }, { 14, 0x80, 0x4000600 }, { 14, 0x84, 0x4000600 }, + { 14, 0xe4, 0x4048 }, { 14, 0xe8, 0x4048 }, { 14, 0xec, 0x4048 }, { 14, 0xf0, 0x4048 }, + { 14, 0xf4, 0x4048 }, { 14, 0xf8, 0x4048 }, { 14, 0xfc, 0x4048 }, { 14, 0x100, 0x4048 }, + { 14, 0x104, 0x4048 }, { 14, 0x108, 0x4048 }, { 14, 0x10c, 0x4048 }, { 14, 0x110, 0x4048 }, + { 14, 0x114, 0x12402046 }, { 14, 0x118, 0x2000 }, { 14, 0x168, 0x12345678 }, + { 3, 0x24, 0xc }, { 3, 0x64, 0x12345678 }, { 4, 0x6300, 0x2804008 }, + { 4, 0x6304, 0xa0a0a0a0 }, { 4, 0x6308, 0x2550000 }, { 4, 0x630c, 0x2550255 }, + { 4, 0x6314, 0x100008 }, { 4, 0x6318, 0x2550000 }, { 5, 0x20, 0xff }, { 11, 0x0, 0xe0000 }, + { 11, 0x4, 0xc }, { 11, 0x50, 0x44000 }, { 11, 0x54, 0x44000 }, { 11, 0x58, 0x44000 }, + { 11, 0x68, 0x12345678 }, { 11, 0x6c, 0xc }, { 11, 0xac, 0xc }, { 11, 0xec, 0x3d0 }, + { 11, 0xf0, 0x6186318 }, { 11, 0xf4, 0x18 }, { 11, 0x134, 0xc30c00 }, + { 11, 0x138, 0xffffffff }, { 11, 0x13c, 0x80000001 }, { 11, 0x140, 0x80000001 }, + { 11, 0x144, 0x80000001 }, { 11, 0x148, 0x7fffffff }, { 11, 0x14c, 0x7fffffff }, + { 11, 0x150, 0x7fffffff }, { 11, 0x154, 0x80000001 }, { 11, 0x158, 0x80000001 }, + { 11, 0x15c, 0x80000001 }, { 11, 0x160, 0x7fffffff }, { 11, 0x164, 0x7fffffff }, + { 11, 0x168, 0x7fffffff }, { 11, 0x16c, 0xffffffff }, { 11, 0x170, 0xffffffff }, + { 11, 0x174, 0xffffffff }, { 11, 0x178, 0xffffffff }, { 11, 0x17c, 0xffffffff }, + { 11, 0x180, 0xffffffff }, { 11, 0x184, 0x80000001 }, { 11, 0x188, 0x80000001 }, + { 11, 0x18c, 0x80000001 }, { 11, 0x190, 0x7fffffff }, { 11, 0x194, 0x7fffffff }, + { 11, 0x198, 0x7fffffff }, { 11, 0x19c, 0x80000001 }, { 11, 0x1a0, 0x80000001 }, + { 11, 0x1a4, 0x80000001 }, { 11, 0x1a8, 0x7fffffff }, { 11, 0x1ac, 0x7fffffff }, + { 11, 0x1b0, 0x7fffffff }, { 11, 0x1b4, 0x80000001 }, { 11, 0x1b8, 0x80000001 }, + { 11, 0x1bc, 0x80000001 }, { 11, 0x1c0, 0x7fffffff }, { 11, 0x1c4, 0x7fffffff }, + { 11, 0x1c8, 0x7fffffff }, { 11, 0x1cc, 0x183c }, { 11, 0x1fc, 0x1 }, { 11, 0x200, 0xc }, + { 11, 0x240, 0xc }, { 11, 0x280, 0xc }, { 11, 0x2c0, 0x80000001 }, + { 11, 0x2c4, 0x80000001 }, { 11, 0x2c8, 0x80000001 }, { 11, 0x2cc, 0x7fffffff }, + { 11, 0x2d0, 0x7fffffff }, { 11, 0x2d4, 0x7fffffff }, { 11, 0x2d8, 0x80000001 }, + { 11, 0x2dc, 0x80000001 }, { 11, 0x2e0, 0x80000001 }, { 11, 0x2e4, 0x7fffffff }, + { 11, 0x2e8, 0x7fffffff }, { 11, 0x2ec, 0x7fffffff }, { 11, 0x2f0, 0x80000001 }, + { 11, 0x2f4, 0x80000001 }, { 11, 0x2f8, 0x80000001 }, { 11, 0x2fc, 0x7fffffff }, + { 11, 0x300, 0x7fffffff }, { 11, 0x304, 0x7fffffff }, { 11, 0x308, 0x80000001 }, + { 11, 0x30c, 0x80000001 }, { 11, 0x310, 0x80000001 }, { 11, 0x314, 0x7fffffff }, + { 11, 0x318, 0x7fffffff }, { 11, 0x31c, 0x7fffffff }, { 11, 0x320, 0x80000001 }, + { 11, 0x324, 0x80000001 }, { 11, 0x328, 0x80000001 }, { 11, 0x32c, 0x7fffffff }, + { 11, 0x330, 0x7fffffff }, { 11, 0x334, 0x7fffffff }, { 11, 0x338, 0x80000001 }, + { 11, 0x33c, 0x80000001 }, { 11, 0x340, 0x80000001 }, { 11, 0x344, 0x7fffffff }, + { 11, 0x348, 0x7fffffff }, { 11, 0x34c, 0x7fffffff }, { 11, 0x37c, 0x1 }, + { 11, 0x2e80, 0x40000000 }, { 12, 0x4, 0x1 }, { 12, 0x120, 0x12345678 }, + { 12, 0x184, 0xffff }, { 12, 0x188, 0xffff }, { 12, 0x18c, 0xffff }, { 12, 0x190, 0xffff }, + { 12, 0x194, 0xffff }, { 12, 0x198, 0xffff }, { 12, 0x19c, 0xffff }, { 12, 0x1a0, 0xffff }, + { 12, 0x1a4, 0xffff }, { 12, 0x1a8, 0xffff }, { 12, 0x1ac, 0xffff }, { 12, 0x1b0, 0xffff }, + { 12, 0x1b4, 0xffff }, { 12, 0x1b8, 0xffff }, { 12, 0x1bc, 0xffff }, { 12, 0x1c0, 0xffff }, + { 12, 0x1c4, 0xffff }, { 12, 0x1c8, 0xffff }, { 12, 0x1cc, 0xffff }, { 12, 0x1d0, 0xffff }, + { 12, 0x1d4, 0xffff }, { 12, 0x1d8, 0xffff }, { 12, 0x1dc, 0xffff }, { 12, 0x1e0, 0xffff }, + { 12, 0x1e4, 0xffff }, { 12, 0x1e8, 0xffff }, { 12, 0x1ec, 0xffff }, { 12, 0x1f0, 0xffff }, + { 12, 0x1f4, 0xffff }, { 12, 0x1f8, 0xffff }, { 12, 0x1fc, 0xffff }, + { 12, 0x240, 0xfff00000 }, { 12, 0x244, 0xfff00000 }, { 13, 0x80, 0x18e0 }, + { 13, 0xc4, 0x80000001 }, { 13, 0xc8, 0x80000001 }, { 13, 0xcc, 0x80000001 }, + { 13, 0xd0, 0x7fffffff }, { 13, 0xd4, 0x7fffffff }, { 13, 0xd8, 0x7fffffff }, + { 13, 0xdc, 0x80000001 }, { 13, 0xe0, 0x80000001 }, { 13, 0xe4, 0x80000001 }, + { 13, 0xe8, 0x7fffffff }, { 13, 0xec, 0x7fffffff }, { 13, 0xf0, 0x7fffffff }, +}; + +/* + * The scaler's polyphase filters, one set per ratio bin (src/dst in Q19; a + * step uses the first bin whose ratio is at least the step). Each set is a + * symmetric kernel sampled at 9 source pixels around the output position, + * 32 phases per pixel, in Q12 (4096 = 1.0), every phase summing to 4096: + * + * - downscaling (ratio s > 1): sinc(x / s), a low-pass at the output's + * Nyquist frequency, under a Kaiser window of radius 3.5 s, beta 6.5; + * - upscaling (steps below 1): an interpolating 4-tap kernel, sinc(x) under + * a Kaiser window of radius 31/16, beta 5; + * - 1:1: the source passes through (centre tap 1.0, extra word 1.0). + * + * Phases 1-15 are stored as they are (index tap * 16 + phase); 17-31 are + * their mirror images. Column 0 holds two phases: taps 4-8 are phase 0, taps + * 0-3 are taps 1-4 of phase 16 (half a pixel), and .extra is that phase's + * tap 0. + * + * Generated by tools/media/apple-scaler/msr23_filters.py, which documents + * the design; regenerate rather than edit. + */ +static const struct msr23_filter msr23_filters[MSR23_FILTER_BINS] = { + { .ratio = 0x7ffff, .extra = 0, .taps = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, -177, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2225, -63, -116, -160, -196, -223, -242, -255, -261, -262, -259, -251, + -240, -227, -211, -194, 4096, 4086, 4056, 4015, 3953, 3873, 3776, 3665, + 3540, 3402, 3256, 3098, 2933, 2762, 2586, 2406, 0, 73, 156, 250, + 353, 467, 591, 724, 866, 1017, 1174, 1339, 1509, 1684, 1862, 2043, + 0, 0, 0, -9, -14, -21, -29, -38, -49, -61, -75, -90, + -106, -123, -141, -159, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + } }, + { .ratio = 0x80000, .extra = 4096, .taps = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 4096, 4096, 4096, 4096, 4096, 4096, 4096, 4096, + 4096, 4096, 4096, 4096, 4096, 4096, 4096, 4096, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + } }, + { .ratio = 0x92492, .extra = 0, .taps = { + -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 79, 50, 45, 40, 35, 30, 25, 21, + 17, 13, 10, 7, 4, 2, -1, -2, -468, -181, -156, -130, + -106, -83, -61, -40, -20, -2, 14, 29, 42, 54, 64, 72, + 2442, 312, 217, 128, 45, -32, -103, -167, -225, -276, -321, -360, + -393, -420, -441, -457, 3578, 3575, 3560, 3535, 3500, 3457, 3404, 3341, + 3268, 3189, 3101, 3006, 2905, 2796, 2682, 2564, 412, 518, 629, 745, + 865, 989, 1116, 1246, 1379, 1512, 1647, 1782, 1917, 2051, 2184, 2313, + -208, -235, -261, -288, -314, -339, -363, -386, -407, -426, -442, -456, + -466, -473, -475, -474, 55, 61, 66, 71, 76, 80, 84, 88, + 91, 93, 94, 95, 94, 92, 89, 85, 0, -4, -4, -5, + -5, -6, -6, -7, -7, -7, -7, -7, -7, -6, -6, -5, + } }, + { .ratio = 0xaaaaa, .extra = -5, .taps = { + 47, -1, -3, -4, -4, -5, -5, -6, -6, -6, -6, -6, + -6, -6, -5, -5, -79, 79, 80, 81, 81, 80, 79, 77, + 75, 72, 69, 66, 63, 59, 55, 51, -242, -354, -339, -323, + -306, -288, -269, -250, -231, -211, -191, -172, -152, -133, -115, -97, + 2325, 712, 625, 540, 458, 379, 304, 232, 164, 99, 38, -18, + -71, -120, -165, -205, 3072, 3068, 3059, 3044, 3019, 2991, 2956, 2917, + 2870, 2819, 2762, 2700, 2632, 2562, 2487, 2408, 802, 895, 989, 1084, + 1182, 1280, 1378, 1478, 1577, 1675, 1773, 1870, 1965, 2059, 2150, 2239, + -367, -379, -389, -397, -403, -406, -407, -406, -401, -393, -382, -368, + -350, -329, -304, -275, 77, 74, 71, 66, 61, 55, 47, 39, + 30, 19, 8, -4, -17, -32, -47, -63, 0, 2, 3, 5, + 8, 10, 13, 15, 18, 22, 25, 28, 32, 36, 40, 43, + } }, + { .ratio = 0xccccc, .extra = 15, .taps = { + 57, 54, 51, 49, 46, 43, 41, 38, 35, 32, 30, 27, + 25, 22, 20, 18, -274, -54, -43, -32, -22, -13, -3, 5, + 13, 21, 27, 34, 39, 45, 49, 53, 137, -320, -327, -333, + -336, -338, -339, -338, -335, -332, -326, -320, -313, -304, -295, -285, + 2120, 1023, 956, 889, 822, 757, 693, 630, 568, 508, 450, 393, + 338, 284, 233, 184, 2552, 2552, 2546, 2536, 2525, 2509, 2489, 2467, + 2441, 2412, 2379, 2341, 2304, 2263, 2218, 2171, 1092, 1160, 1229, 1298, + 1367, 1435, 1503, 1571, 1637, 1703, 1767, 1831, 1892, 1952, 2011, 2067, + -310, -299, -286, -270, -253, -233, -211, -187, -160, -131, -100, -66, + -30, 8, 48, 91, -66, -78, -90, -103, -116, -129, -143, -157, + -170, -184, -198, -211, -225, -238, -250, -263, 56, 58, 60, 62, + 63, 65, 66, 67, 67, 67, 67, 67, 66, 64, 62, 60, + } }, + { .ratio = 0x100000, .extra = 53, .taps = { + -121, 6, 11, 16, 20, 25, 29, 32, 36, 39, 42, 44, + 46, 48, 50, 51, -254, -244, -238, -231, -224, -216, -208, -200, + -192, -183, -175, -166, -157, -148, -139, -130, 545, -25, -49, -71, + -92, -112, -131, -149, -165, -180, -194, -207, -219, -229, -238, -247, + 1852, 1208, 1164, 1119, 1074, 1029, 984, 939, 894, 849, 804, 760, + 716, 673, 630, 587, 2092, 2090, 2088, 2082, 2077, 2067, 2055, 2044, + 2029, 2012, 1996, 1975, 1956, 1931, 1905, 1879, 1252, 1296, 1339, 1382, + 1424, 1465, 1506, 1545, 1584, 1622, 1658, 1694, 1728, 1761, 1793, 1823, + 0, 26, 53, 82, 111, 142, 174, 207, 241, 276, 312, 349, + 386, 425, 464, 505, -250, -255, -260, -265, -269, -272, -274, -276, + -277, -277, -277, -275, -273, -270, -265, -260, 0, -6, -12, -18, + -25, -32, -39, -46, -54, -62, -70, -78, -87, -95, -104, -112, + } }, + { .ratio = 0x155555, .extra = -115, .taps = { + -200, -182, -179, -175, -171, -167, -163, -158, -154, -149, -145, -140, + -135, -130, -125, -120, 82, -131, -139, -146, -153, -160, -166, -171, + -177, -181, -185, -189, -192, -195, -197, -199, 789, 382, 360, 337, + 315, 294, 272, 251, 231, 211, 191, 171, 153, 134, 116, 99, + 1433, 1154, 1131, 1109, 1086, 1063, 1039, 1015, 991, 966, 941, 916, + 891, 865, 840, 814, 1550, 1550, 1549, 1547, 1543, 1538, 1535, 1527, + 1522, 1513, 1504, 1496, 1485, 1475, 1461, 1449, 1175, 1196, 1217, 1237, + 1256, 1275, 1293, 1311, 1327, 1344, 1359, 1374, 1388, 1401, 1413, 1425, + 405, 428, 452, 475, 499, 523, 547, 571, 595, 619, 644, 668, + 692, 716, 741, 765, -122, -113, -104, -94, -83, -72, -61, -48, + -36, -23, -9, 5, 19, 34, 50, 65, -185, -188, -191, -194, + -196, -198, -200, -202, -203, -204, -204, -205, -205, -204, -203, -202, + } }, + { .ratio = 0x200000, .extra = -72, .taps = { + 106, -5, -11, -16, -21, -26, -31, -36, -40, -45, -49, -53, + -57, -61, -65, -69, 392, 229, 220, 211, 203, 194, 186, 177, + 169, 161, 152, 144, 136, 129, 121, 113, 695, 536, 527, 517, + 507, 498, 488, 479, 469, 459, 450, 440, 430, 421, 411, 402, + 891, 802, 796, 789, 783, 776, 769, 762, 755, 748, 741, 733, + 726, 718, 711, 703, 912, 912, 912, 912, 910, 910, 908, 908, + 905, 905, 904, 902, 901, 898, 896, 894, 808, 814, 820, 826, + 832, 838, 843, 849, 854, 859, 864, 869, 873, 878, 882, 887, + 546, 555, 565, 574, 584, 593, 603, 612, 622, 631, 640, 650, + 659, 668, 677, 686, 238, 247, 256, 266, 275, 284, 294, 303, + 313, 323, 332, 342, 352, 362, 372, 382, 0, 6, 11, 17, + 23, 29, 36, 42, 49, 55, 62, 69, 76, 83, 91, 98, + } }, +}; + +/* De-ringing constants of a scaled axis, in pairs (two channels): downscale and upscale. */ +static const u32 msr23_dering[2][13] = { + { 0xcd, 0x266, 0x39a, 0x4cd, 0x355e3a6, 0x400, 0xb33, 0x266, 0x733, 0x11c79b, + 0x1aa98e, 0x666, 0x333 }, + { 0xcd, 0x266, 0x39a, 0x99a, 0xaaaaab, 0x400, 0xb33, 0x266, 0x733, 0x11c79b, + 0x1aa98e, 0x666, 0x333 }, +}; + +/* + * The 2x2 ordered dither (Bayer [[0, 2], [3, 1]], tiled 4x4) for a 10-bit + * source written at 8 bits. + */ +static const u32 msr23_dither[16] = { 0, 2, 0, 2, 3, 1, 3, 1, 0, 2, 0, 2, 3, 1, 3, 1 }; + +/** + * struct msr23_fmt - a pixel format as the engine sees it + * @fourcc: V4L2 pixel format + * @rgb: R'G'B' (else Y'CbCr or grey) + * @grey: luma only + * @sub: chroma subsampling code (0 4:4:4, 1 4:2:2, 3 4:2:0) + * @code: memory format code of plane 0 and of the chroma plane + * @swizzle: component order (0 identity, else CbCr) + * @hs: horizontal chroma subsampling + * @vs: vertical chroma subsampling + * @bits: bits per component of the four channels (0: 8) + */ +struct msr23_fmt { + u32 fourcc; + bool rgb, grey; + u8 sub; + u8 code[2]; + u8 swizzle, hs, vs; + u8 bits[4]; +}; + +static const struct msr23_fmt msr23_fmts[] = { + { V4L2_PIX_FMT_ABGR32, .rgb = true, .code = { 0x1e } }, + { V4L2_PIX_FMT_NV12, .sub = 3, .code = { 1, 6 }, .swizzle = 2, .hs = 2, .vs = 2 }, + { V4L2_PIX_FMT_NV12M, .sub = 3, .code = { 1, 6 }, .swizzle = 2, .hs = 2, .vs = 2 }, + { V4L2_PIX_FMT_NV16, .sub = 1, .code = { 1, 6 }, .swizzle = 2, .hs = 2, .vs = 1 }, + { V4L2_PIX_FMT_NV16M, .sub = 1, .code = { 1, 6 }, .swizzle = 2, .hs = 2, .vs = 1 }, + { V4L2_PIX_FMT_NV24, .code = { 1, 6 }, .swizzle = 2, .hs = 1, .vs = 1 }, + { V4L2_PIX_FMT_P010, .sub = 3, .code = { 2, 0x12 }, .swizzle = 2, .hs = 2, .vs = 2, + .bits = { 10, 10, 10, 0 } }, + { V4L2_PIX_FMT_GREY, .grey = true, .code = { 1 }, .swizzle = 2 }, +}; + +static const struct msr23_fmt *msr23_fmt(u32 fourcc) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(msr23_fmts); i++) + if (msr23_fmts[i].fourcc == fourcc) + return &msr23_fmts[i]; + return NULL; +} + +bool msr23_format_ok(u32 fourcc) +{ + return msr23_fmt(fourcc); +} +EXPORT_SYMBOL_IF_KUNIT(msr23_format_ok); + +static u8 msr23_bits(const struct msr23_fmt *f, unsigned int c) +{ + return f->bits[c] ?: 8; +} + +#define W(img, o, v) ((img)[(o) / 4] = (v)) + +/* + * One side's DMA words: plane codes, strides, the region's size and its + * origin per plane, the planes' sizes, swizzle (block 1 for the source, block + * 14 for the destination). The origins are in samples of each plane (y << 16 + * | x); the plane pointers stay at the start of the planes. + */ +static void msr23_side(u32 *img, const struct msr23_pic *p, const struct v4l2_rect *r, + const struct msr23_fmt *f, bool dst) +{ + u32 b = dst ? MSR23_B14 : MSR23_B1; + u32 so = dst ? 0x40 : 0x58, wo = dst ? 0x5c : 0x7c, oo = dst ? 0x4c : 0x68; + u32 po = dst ? 0x88 : 0xb4, ho = dst ? 0x94 : 0xc4; + bool chroma = !f->rgb && !f->grey; + u32 cw = chroma ? p->width / f->hs : p->width, ch = chroma ? p->height / f->vs : p->height; + unsigned int i; + + for (i = 0; i < 2; i++) + W(img, b + 4 + 4 * i, (dst ? 0x8000 : 0) | f->code[i]); + W(img, b + so, p->stride[0]); + W(img, b + so + 4, chroma ? p->stride[1] : 0); + W(img, b + wo, r->width); + W(img, b + wo + 4, r->height); + W(img, b + oo, (u32)r->top << 16 | r->left); + if (chroma) + W(img, b + oo + 4, (u32)r->top / f->vs << 16 | (u32)r->left / f->hs); + for (i = 0; i < 3; i++) { + W(img, b + po + 4 * i, i == 1 ? cw : p->width); + W(img, b + ho + 4 * i, i == 1 ? ch : p->height); + } + W(img, b + (dst ? 0x58 : 0x78), f->swizzle ? 0x03000102 : 0x03020100); +} + +static u32 msr23_dup(s16 v) +{ + return (u16)v | (u32)(u16)v << 16; +} + +/* + * One axis of the scaler (block 8: the vertical half at +0x80, the + * horizontal half at +0x400): step and inverse in Q22 (the vertical half at + * 20-bit precision), initial phase when upscaling, de-ringing, and the filter + * of the first bin whose ratio is at least the step. + * A Y'CbCr source at 1:1 runs no filter. + */ +static int msr23_axis(u32 *img, u32 src, u32 dst, bool horizontal, bool yuv_src) +{ + u32 b = MSR23_B8 + (horizontal ? 0x400 : 0x80); + unsigned int prec = horizontal ? 22 : 20, i; + u32 step = (u32)div_u64((u64)src << prec, dst) << (22 - prec); + u32 inv = (u32)div_u64((u64)dst << prec, src) << (22 - prec); + bool scaled = src != dst; + + W(img, b, yuv_src ? 2 : 0); + if (step < BIT(22)) { + s32 init = ((s32)step - (s32)BIT(22)) >> 1; + + W(img, b + 0x4, init & 0xffffff); + W(img, b + 0x8, (yuv_src ? init >> 1 : init) & 0xffffff); + } + W(img, b + 0xc, step); + W(img, b + 0x10, step); + W(img, b + 0x14, inv); + W(img, b + 0x18, inv); + if (scaled) + for (i = 0; i < ARRAY_SIZE(msr23_dering[0]); i++) { + W(img, b + 0x1c + 8 * i, msr23_dering[step < BIT(22)][i]); + W(img, b + 0x20 + 8 * i, msr23_dering[step < BIT(22)][i]); + } + W(img, b + (horizontal ? 0xe0 : 0xfc), 0x12345678); + if (scaled || !yuv_src) { + const struct msr23_filter *f = NULL; + + for (i = 0; i < MSR23_FILTER_BINS; i++) + if (msr23_filters[i].ratio >= step >> 3) { + f = &msr23_filters[i]; + break; + } + if (!f) + return -EINVAL; + for (i = 0; i < MSR23_FILTER_TAPS; i++) + W(img, b + 0x100 + 4 * i, msr23_dup(f->taps[i])); + W(img, b + 0x340, msr23_dup(f->extra)); + } + return 0; +} + +/* + * Block 0 +0x78..+0x84: the channels' component sizes, source in the low + * half, destination in the high half. A conversion at 1:1 (the matrix in + * block 3) takes 0x30 on the source side; without a conversion, as with a + * scaled one, the source's own sizes (with 0x30, values above half scale + * come out 1 lower: v * 255 / 256). + */ +static void msr23_map(u32 *img, const struct msr23_fmt *s, const struct msr23_fmt *d, bool csc11) +{ + unsigned int c; + + for (c = 0; c < 4; c++) { + u32 lo, hi; + + if (csc11) + lo = 0x30; + else if (!s->rgb) + lo = c ? 0x20 | (c < 3 ? msr23_bits(s, c) : 0) : msr23_bits(s, c); + else + lo = s->bits[0] ? msr23_bits(s, c) : 8; + if (d->rgb) + hi = 8; + else + hi = c ? 0x20 | (c < 3 ? msr23_bits(d, c) : 0) : msr23_bits(d, c); + W(img, MSR23_B0 + 0x78 + 4 * c, hi << 16 | lo); + } +} + +/* The colour matrix: block 3 at 1:1, block 11 when the job also scales. */ +static int msr23_matrix(u32 *img, const struct msr23_job *job, bool to_yuv, bool scaled) +{ + struct asc_csc csc; + unsigned int r, c; + u32 b; + + if (asc_csc_compute(job->enc, + job->full ? V4L2_QUANTIZATION_FULL_RANGE : V4L2_QUANTIZATION_LIM_RANGE, + !to_yuv, &csc)) + return -EINVAL; + b = scaled ? MSR23_B11 + 0x14 : MSR23_B3 + 0x34; + for (r = 0; r < 3; r++) + for (c = 0; c < 3; c++) + W(img, b + 12 * r + 4 * c, (u16)csc.coef[r][c]); + for (r = 0; r < 3; r++) { + /* offsets: block 11 in 2^-24 of full scale (26 bits), block 3 in 2^-16 (17 bits) */ + if (to_yuv) + W(img, b + 0x24 + 4 * r, scaled ? (u32)csc.post[r] : (u32)csc.post[r] >> 8); + else + W(img, b - 0xc + 4 * r, scaled ? (u32)csc.pre[r] & 0x3ffffff : + (u32)(csc.pre[r] >> 8) & 0x1ffff); + } + return 0; +} + +static bool msr23_size_ok(const struct msr23_pic *p) +{ + return !((p->width | p->height) & 1) && min(p->width, p->height) >= MSR23_MIN_SIZE && + p->width <= MSR23_MAX_WIDTH && (u64)p->width * p->height <= MSR23_MAX_PIXELS; +} + +/* A job's crop or compose rectangle: all of the picture when its width is 0. */ +static void msr23_region(const struct msr23_pic *p, const struct v4l2_rect *r, + struct v4l2_rect *out) +{ + if (r->width) + *out = *r; + else + *out = (struct v4l2_rect){ 0, 0, p->width, p->height }; +} + +/* Even, at least the minimum size, and inside the picture. */ +static bool msr23_region_ok(const struct msr23_pic *p, const struct v4l2_rect *r) +{ + return r->left >= 0 && r->top >= 0 && !((r->left | r->top | r->width | r->height) & 1) && + min(r->width, r->height) >= MSR23_MIN_SIZE && + (u64)r->left + r->width <= p->width && (u64)r->top + r->height <= p->height; +} + +/* + * Block 0 +0x64 bits 3-6: the rotation (bits 3-4: 1, 2, 3 quarter turns + * clockwise), then a mirror of the result left to right (bit 5) and top to + * bottom (bit 6). A mirror both ways is a half turn, and a half turn and one + * mirror is the other mirror: each orientation is sent in one form only. + */ +static u32 msr23_orient(const struct msr23_job *job) +{ + unsigned int rot = job->rotate / 90; + bool h = job->hflip, v = job->vflip; + + if (h && v) { + rot = (rot + 2) & 3; + h = false; + v = false; + } + if (rot == 2 && (h || v)) { + rot = 0; + swap(h, v); + } + return rot << 3 | h << 5 | v << 6; +} + +/* The source region's size as the pipe sees it: after the rotation. */ +static void msr23_turned(const struct msr23_job *job, const struct v4l2_rect *c, u32 *w, u32 *h) +{ + bool quarter = job->rotate == 90 || job->rotate == 270; + + *w = quarter ? c->height : c->width; + *h = quarter ? c->width : c->height; +} + +/** + * msr23_check - whether the builder covers a job + * @job: the conversion + * + * Return: 0, or -EINVAL for a format, size, rectangle, rotation or ratio the + * builder was not checked over. + */ +int msr23_check(const struct msr23_job *job) +{ + const struct msr23_pic *sp = &job->src, *dp = &job->dst; + const struct msr23_fmt *s = msr23_fmt(sp->fourcc), *d = msr23_fmt(dp->fourcc); + struct v4l2_rect c, o; + u32 sw, sh, dw, dh; + + if (!s || !d || !msr23_size_ok(sp) || !msr23_size_ok(dp) || s->grey != d->grey) + return -EINVAL; + if (job->rotate % 90 || job->rotate > 270) + return -EINVAL; + /* a quarter turn of 4:2:2 moves its subsampling to the other axis: not checked */ + if (job->rotate % 180 && (s->sub == 1 || d->sub == 1)) + return -EINVAL; + msr23_region(sp, &job->crop, &c); + msr23_region(dp, &job->compose, &o); + if (!msr23_region_ok(sp, &c) || !msr23_region_ok(dp, &o)) + return -EINVAL; + msr23_turned(job, &c, &sw, &sh); + dw = o.width; + dh = o.height; + if (sw > MSR23_MAX_RATIO * dw || dw > MSR23_MAX_RATIO * sw || + sh > MSR23_MAX_RATIO * dh || dh > MSR23_MAX_RATIO * sh) + return -EINVAL; + /* + * A conversion at 1:1 with a mirror or a half turn: not checked on + * hardware (with a quarter turn it is; see msr23_build()). + */ + if (s->rgb != d->rgb && sw == dw && sh == dh && !(job->rotate % 180) && + (msr23_orient(job) & 0x70)) + return -EINVAL; + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(msr23_check); + +/** + * msr23_build - the register image of a job + * @job: the conversion + * @img: MSR23_IMG_LEN bytes, zeroed by the caller + * @out: NC sizes and plane counts + * + * The pointers and the frame id are left zero: the caller writes them + * (MSR23_PTR_*, MSR23_FRAME_ID). + * + * Return: 0, or -EINVAL for a job the builder does not cover. + */ +int msr23_build(const struct msr23_job *job, u32 *img, struct msr23_built *out) +{ + const struct msr23_pic *sp = &job->src, *dp = &job->dst; + const struct msr23_fmt *s = msr23_fmt(sp->fourcc), *d = msr23_fmt(dp->fourcc); + struct v4l2_rect c, o, whole; + struct msr23_pic sub; + u32 sw, sh, dw, dh, ybpp; + bool yuv_src, yuv_dst, csc_on, scaled, csc_pre, ups, wide; + u64 px; + u32 cds, k, rows; + unsigned int i; + int ret; + + ret = msr23_check(job); + if (ret) + return ret; + /* + * The source is read rotated: from the reader on, the pipe (scaler, + * window) works in the destination's orientation. + */ + msr23_region(sp, &job->crop, &c); + msr23_region(dp, &job->compose, &o); + msr23_turned(job, &c, &sw, &sh); + dw = o.width; + dh = o.height; + + yuv_src = !s->rgb; + yuv_dst = !d->rgb; + csc_on = yuv_src != yuv_dst; + scaled = sw != dw || sh != dh; + /* + * A conversion at 1:1 runs its matrix in block 3, ahead of the scaler; + * with a quarter turn it runs where a scaled job's does (block 11): in + * block 3 the rotated output is wrong. + */ + csc_pre = csc_on && !scaled && !(job->rotate % 180); + /* chroma upsampling: a subsampled Y'CbCr source */ + ups = yuv_src && (s->hs > 1 || s->vs > 1); + px = max((u64)sw * sh, (u64)dw * dh); + + for (i = 0; i < ARRAY_SIZE(msr23_defaults); i++) { + const struct msr23_block *b = NULL; + unsigned int j; + + for (j = 0; j < MSR23_NBLOCKS && !b; j++) + if (msr23_blocks[j].id == msr23_defaults[i].block) + b = &msr23_blocks[j]; + W(img, b->off + msr23_defaults[i].off, msr23_defaults[i].val); + } + + /* Block 0: the pipe. */ + W(img, MSR23_B0 + 0xc, 0xffff | (yuv_src && csc_on ? BIT(31) : 0)); + /* a time budget: 40e6 (80e6 above 1080p) + 8/15 per pixel of the larger side */ + W(img, MSR23_B0 + 0x18, 40000000U * (px > 1920 * 1080 ? 2 : 1) + (u32)div_u64(px * 8, 15)); + W(img, MSR23_B0 + 0x64, 0x38d800 | s->rgb | s->sub << 1 | d->rgb << 7 | d->sub << 8 | + (csc_pre ? BIT(16) : 0) | (ups ? BIT(13) : 0) | msr23_orient(job)); + /* scaler enables per axis: off at 1:1, the low 3 bits upscaling, all 5 downscaling */ + W(img, MSR23_B0 + 0x68, (sw == dw ? 0 : (dw > sw ? 0x7 : 0x1f) << 11) | + (sh == dh ? 0 : (dh > sh ? 0x7 : 0x1f) << 6)); + /* chroma downsampling of a subsampled Y'CbCr destination */ + cds = 0xc | (yuv_dst && d->hs == 2 ? 1 : 0) | (yuv_dst && d->vs == 2 ? 2 : 0); + W(img, MSR23_B0 + 0x6c, cds << 16 | (csc_on && !csc_pre ? 3 : 0)); + W(img, MSR23_B0 + 0x70, (dh - 1) << 16 | (dw - 1)); + msr23_map(img, s, d, csc_pre); + + msr23_side(img, sp, &c, s, false); + /* + * The destination rectangle is written as a picture of its own: its + * size, at an offset into the planes the caller adds to the pointers. + */ + sub = *dp; + sub.width = o.width; + sub.height = o.height; + whole = (struct v4l2_rect){ 0, 0, o.width, o.height }; + msr23_side(img, &sub, &whole, d, true); + ybpp = d->rgb ? 4 : msr23_bits(d, 0) > 8 ? 2 : 1; + out->dst_off[0] = (u32)o.top * dp->stride[0] + (u32)o.left * ybpp; + out->dst_off[1] = d->rgb || d->grey ? 0 : + (u32)o.top / d->vs * dp->stride[1] + (u32)o.left / d->hs * 2 * ybpp; + + ret = msr23_axis(img, sh, dh, false, yuv_src); + if (!ret) + ret = msr23_axis(img, sw, dw, true, yuv_src); + if (ret) + return ret; + W(img, MSR23_B8 + 0x4e4, 1); + + /* + * Block 3: chroma upsampling terms; the matrix at 1:1. Block 11: the + * matrix when scaling too. + */ + for (i = 0; i < 4; i++) + W(img, MSR23_B3 + (i < 2 ? 0x8 : 0x10) + 4 * i, ups ? 0x800 : 0); + if (csc_on) { + ret = msr23_matrix(img, job, yuv_dst, !csc_pre); + if (ret) + return ret; + } + + /* + * Block 12: chroma downsampling per subsampled axis, and the dither of a + * 10-bit source written at 8 bits. + */ + W(img, MSR23_B12 + 0xc, yuv_dst && d->hs == 2 ? 0x1000 : 0); + W(img, MSR23_B12 + 0x1c, yuv_dst && d->vs == 2 ? 0x1000 : 0); + if (msr23_bits(s, 0) > msr23_bits(d, 0)) { + W(img, MSR23_B12 + 0x180, 0x02020200); + for (i = 0; i < ARRAY_SIZE(msr23_dither); i++) + W(img, MSR23_B12 + 0x200 + 4 * i, msr23_dither[i]); + } + + /* + * Spill (NC) buffers in 16 KiB pages, for the units' line buffers: + * about 0.018 page per source row and 0.004 per destination row at + * 8 bits (24 pages at 1080p, 43 for 4K -> 1080p), twice that with + * 16-bit samples. Larger than needed is harmless (the jobs give the + * same output), so round generously, and never below 48 pages per + * byte of sample. + */ + wide = s->bits[0] || d->bits[0]; + k = wide ? 2 : 1; + rows = 320 * sh + 64 * dh; + out->nc0 = max(DIV_ROUND_UP(rows * k, MSR23_NC_PAGE) + 2, 48 * k); + out->nc1 = wide ? 8 : 4; + W(img, MSR23_B0 + 0xec, out->nc1 << 16 | out->nc0); + out->planes[0] = s->code[1] ? 2 : 1; + out->planes[1] = d->code[1] ? 2 : 1; + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(msr23_build); diff --git a/drivers/media/platform/apple/scaler/apple-scaler-msr23.h b/drivers/media/platform/apple/scaler/apple-scaler-msr23.h new file mode 100644 index 00000000000000..67cc2d678e76a9 --- /dev/null +++ b/drivers/media/platform/apple/scaler/apple-scaler-msr23.h @@ -0,0 +1,119 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* + * Apple silicon scaler (MSR23, M5): job builder. + * + * A MSR23 job is a register image the engine's firmware streams into the + * hardware, described by a list of blocks. This builds the image for a + * conversion from its parameters. The pointers (surfaces, spill buffer) and + * the frame id are left to the caller. + */ +#ifndef _APPLE_SCALER_MSR23_H_ +#define _APPLE_SCALER_MSR23_H_ + +#include +#include + +/* The image: every block of a job lives in it. */ +#define MSR23_IMG_LEN 0x14000 + +/* Block list record word 2: the firmware tiles the job itself (no tile array). */ +#define MSR23_HDR2_FW_TILING 0x72000000 + +/* Offsets in the image of the blocks the caller writes into. */ +#define MSR23_B0 0x80 +#define MSR23_B1 0x200 +#define MSR23_B14 0x380 + +/* 64-bit pointers in the image (low word, then high word). */ +#define MSR23_PTR_NC0 (MSR23_B0 + 0x50) /* spill buffer, NC0 pages */ +#define MSR23_PTR_NC1 (MSR23_B0 + 0x58) /* spill buffer after NC0 */ +#define MSR23_PTR_SRC(p) (MSR23_B1 + 0x18 + 8 * (p)) +#define MSR23_PTR_DST(p) (MSR23_B14 + 0x10 + 8 * (p)) +/* Block 0 +0x60: the frame id, as in the record's word 1. */ +#define MSR23_FRAME_ID (MSR23_B0 + 0x60) + +/* + * The sizes the builder was checked over on hardware: even, 64 pixels to + * 4096 wide and 4K UHD in area, at most 4x down or up per axis. The same + * holds for the crop and compose rectangles. + */ +#define MSR23_MIN_SIZE 64 +#define MSR23_MAX_WIDTH 4096 +#define MSR23_MAX_PIXELS (3840 * 2160) +#define MSR23_MAX_RATIO 4 + +/* NC buffer pages. */ +#define MSR23_NC_PAGE 0x4000 + +/** + * struct msr23_block - one block of a job + * @id: block (register group) id + * @off: offset in the image + * @size: size word of the block list (size in 32-byte units at bit 20) + */ +struct msr23_block { + u8 id; + u32 off; + u32 size; +}; + +#define MSR23_NBLOCKS 10 +extern const struct msr23_block msr23_blocks[MSR23_NBLOCKS]; + +/** + * struct msr23_pic - one side of a job + * @fourcc: V4L2 pixel format + * @width: width in pixels + * @height: height in pixels + * @stride: bytes per line of plane 0 and of the chroma plane (0 if none) + */ +struct msr23_pic { + u32 fourcc; + u32 width, height; + u32 stride[2]; +}; + +/** + * struct msr23_job - a conversion + * @src: source picture + * @dst: destination picture + * @crop: the part of the source read (a zero width: all of it) + * @compose: the part of the destination written (a zero width: all of it); + * the rest of the destination is left as it is. The caller adds + * &msr23_built.dst_off to the destination pointers. + * @rotate: clockwise rotation in degrees: 0, 90, 180 or 270 + * @hflip: mirror the result left to right, after the rotation + * @vflip: mirror the result top to bottom, after the rotation + * @enc: Y'CbCr encoding of the Y'CbCr side (both sides: the same) + * @full: that side is full range + * + * The rectangles are in pixels, with even origins and sizes. + */ +struct msr23_job { + struct msr23_pic src, dst; + struct v4l2_rect crop, compose; + u16 rotate; + bool hflip, vflip; + enum v4l2_ycbcr_encoding enc; + bool full; +}; + +/** + * struct msr23_built - what the builder computed besides the image + * @nc0: NC0 spill pages (16 KiB each) + * @nc1: NC1 spill pages + * @planes: number of planes of the source and of the destination + * @dst_off: bytes to add to each destination plane's pointer (the compose + * rectangle's origin) + */ +struct msr23_built { + u32 nc0, nc1; + u8 planes[2]; + u32 dst_off[2]; +}; + +bool msr23_format_ok(u32 fourcc); +int msr23_check(const struct msr23_job *job); +int msr23_build(const struct msr23_job *job, u32 *img, struct msr23_built *out); + +#endif diff --git a/drivers/media/platform/apple/scaler/apple-scaler-test.c b/drivers/media/platform/apple/scaler/apple-scaler-test.c index 763d8a40109829..bca3331c6026ac 100644 --- a/drivers/media/platform/apple/scaler/apple-scaler-test.c +++ b/drivers/media/platform/apple/scaler/apple-scaler-test.c @@ -9,9 +9,11 @@ #include #include #include +#include #include #include "apple-scaler-hw.h" +#include "apple-scaler-msr23.h" #include "apple-scaler-regs.h" struct asc_csc_case { @@ -638,6 +640,312 @@ static void asc_test_job_rejects(struct kunit *test) KUNIT_EXPECT_EQ(test, asc_job_build(&job, w, ASC_JOB_MAX_WRITES), -EINVAL); } +/* ---- MSR23 job builder ---- */ + +static u32 msr23_word(const u32 *img, u32 off) +{ + return img[off / 4]; +} + +static void msr23_pic(struct msr23_pic *p, u32 fourcc, u32 w, u32 h, u32 bpp, u32 cstride_mul) +{ + *p = (struct msr23_pic){ fourcc, w, h, { w * bpp, cstride_mul * w } }; +} + +/* + * BGRA -> NV12 BT.709 at 1080p: sizes, plane codes and the matrix of block 3 + * as asc_csc_compute() gives it. + */ +static void asc_test_msr23_csc(struct kunit *test) +{ + u32 *img = kunit_kzalloc(test, MSR23_IMG_LEN, GFP_KERNEL); + struct msr23_job job = { .enc = V4L2_YCBCR_ENC_709 }; + struct msr23_built out; + struct asc_csc csc; + unsigned int r, c; + + KUNIT_ASSERT_NOT_NULL(test, img); + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x70), 1079 << 16 | 1919); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x58), 7680); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x7c), 1920); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x4), 0x8001); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x8), 0x8006); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x8c), 960); /* chroma width */ + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x98), 540); /* chroma height */ + KUNIT_ASSERT_EQ(test, asc_csc_compute(V4L2_YCBCR_ENC_709, V4L2_QUANTIZATION_LIM_RANGE, + false, &csc), 0); + for (r = 0; r < 3; r++) + for (c = 0; c < 3; c++) + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x1e00 + 0x34 + 12 * r + 4 * c), + (u16)csc.coef[r][c]); + /* the output offsets: limited-range black and the chroma midpoint */ + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x1e00 + 0x58), 0x1010); + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x1e00 + 0x5c), 0x8020); + KUNIT_EXPECT_EQ(test, out.planes[0], 1); + KUNIT_EXPECT_EQ(test, out.planes[1], 2); + /* no scaling: both filter axes at unit step */ + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x8c), BIT(22)); + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x40c), BIT(22)); +} + +/* + * BGRA 4K -> 1080p: Q22 steps and inverses per axis; 1080p -> 4K: the centre + * initial phase -1/4. + */ +static void asc_test_msr23_scale(struct kunit *test) +{ + u32 *img = kunit_kzalloc(test, MSR23_IMG_LEN, GFP_KERNEL); + struct msr23_job job = {}; + struct msr23_built out; + + KUNIT_ASSERT_NOT_NULL(test, img); + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 3840, 2160, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x8c), 2 << 22); /* vertical step */ + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x94), 1 << 21); /* its inverse */ + /* horizontal step */ + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x40c), 2 << 22); + /* no initial phase when downscaling */ + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x84), 0); + KUNIT_EXPECT_GE(test, out.nc0, 43); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0xec), out.nc1 << 16 | out.nc0); + + memset(img, 0, MSR23_IMG_LEN); + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 3840, 2160, 4, 0); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x8c), 1 << 21); + /* -1/4 in 24-bit Q22 */ + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x84), 0xf00000); + /* one axis only: the other stays at a unit step */ + memset(img, 0, MSR23_IMG_LEN); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 960, 1080, 4, 0); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x8c), BIT(22)); + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x40c), 2 << 22); +} + +/* What the builder does not cover. */ +static void asc_test_msr23_rejects(struct kunit *test) +{ + u32 *img = kunit_kzalloc(test, MSR23_IMG_LEN, GFP_KERNEL); + struct msr23_job job = {}; + struct msr23_built out; + + KUNIT_ASSERT_NOT_NULL(test, img); + msr23_pic(&job.src, V4L2_PIX_FMT_GREY, 1920, 1080, 1, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + /* grey only to grey */ + KUNIT_EXPECT_EQ(test, msr23_build(&job, img, &out), -EINVAL); + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 3840, 2160, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 480, 270, 4, 0); + KUNIT_EXPECT_EQ(test, msr23_build(&job, img, &out), -EINVAL); /* 8x down */ + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1919, 1080, 4, 0); + KUNIT_EXPECT_EQ(test, msr23_build(&job, img, &out), -EINVAL); /* odd width */ + msr23_pic(&job.dst, V4L2_PIX_FMT_ARGB2101010, 1920, 1080, 4, 0); + KUNIT_EXPECT_EQ(test, msr23_build(&job, img, &out), -EINVAL); /* no 2:10:10:10 */ + KUNIT_EXPECT_FALSE(test, msr23_format_ok(V4L2_PIX_FMT_ARGB2101010)); + KUNIT_EXPECT_TRUE(test, msr23_format_ok(V4L2_PIX_FMT_P010)); + /* above 4K UHD in area, and 4x up per axis (allowed) */ + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 4096, 2304, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 480, 270 * 2, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + KUNIT_EXPECT_EQ(test, msr23_check(&job), 0); + + /* geometry: odd, outside, too small; rotations other than quarter turns */ + msr23_pic(&job.src, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 960, 540, 1, 1); + job.crop = (struct v4l2_rect){ 101, 50, 960, 540 }; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + job.crop = (struct v4l2_rect){ 1000, 50, 960, 540 }; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + job.crop = (struct v4l2_rect){ -2, 0, 960, 540 }; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + job.crop = (struct v4l2_rect){}; + job.compose = (struct v4l2_rect){ 0, 0, 960, 32 }; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + job.compose = (struct v4l2_rect){}; + job.rotate = 45; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + /* the ratio is the rotated source's: 1080 -> 256 is beyond 4x */ + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 256, 1920, 1, 1); + job.rotate = 0; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + job.rotate = 90; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 540, 960, 1, 1); + KUNIT_EXPECT_EQ(test, msr23_check(&job), 0); + /* 4:2:2 turns only by half turns */ + msr23_pic(&job.src, V4L2_PIX_FMT_NV16, 1920, 1080, 1, 1); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV16, 1080, 1920, 1, 1); + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV16, 1920, 1080, 1, 1); + job.rotate = 180; + KUNIT_EXPECT_EQ(test, msr23_check(&job), 0); +} + +/* Crop, compose, rotation and mirrors: region sizes, origins and the pipe word's orientation. */ +static void asc_test_msr23_geometry(struct kunit *test) +{ + static const struct { + u16 rotate; + bool hflip, vflip; + u32 code; + } orient[] = { + { 0, false, false, 0 }, { 0, true, false, 0x20 }, + { 0, false, true, 0x40 }, { 0, true, true, 0x10 }, + { 90, false, false, 0x08 }, { 90, true, false, 0x28 }, + { 90, false, true, 0x48 }, { 90, true, true, 0x18 }, + { 180, false, false, 0x10 }, { 180, true, false, 0x40 }, + { 180, false, true, 0x20 }, { 270, false, false, 0x18 }, + { 270, true, false, 0x38 }, { 270, false, true, 0x58 }, + }; + u32 *img = kunit_kzalloc(test, MSR23_IMG_LEN, GFP_KERNEL); + u32 *ref = kunit_kzalloc(test, MSR23_IMG_LEN, GFP_KERNEL); + struct msr23_job job = {}; + struct msr23_built out; + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, img); + KUNIT_ASSERT_NOT_NULL(test, ref); + + /* 960x540 at (100, 50) of an NV12 1080p source: origins per plane, planes whole */ + msr23_pic(&job.src, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 960, 540, 1, 1); + job.crop = (struct v4l2_rect){ 100, 50, 960, 540 }; + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x68), 50 << 16 | 100); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x6c), 25 << 16 | 50); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x7c), 960); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x80), 540); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0xb4), 1920); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0xb8), 960); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0xc4), 1080); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x68), 0); /* no scaling */ + + /* 1920x1080 into 1280x720 at (0, 280) of 1280x1280: the scaler of 1280x720 */ + job = (struct msr23_job){}; + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1280, 720, 4, 0); + KUNIT_ASSERT_EQ(test, msr23_build(&job, ref, &out), 0); + memset(img, 0, MSR23_IMG_LEN); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1280, 1280, 4, 0); + job.compose = (struct v4l2_rect){ 0, 280, 1280, 720 }; + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + /* written as a 1280x720 picture 280 rows into the planes */ + KUNIT_EXPECT_EQ(test, out.dst_off[0], 280 * 1280 * 4); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x4c), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x40), 1280 * 4); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x5c), 1280); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x60), 720); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x94), 720); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x70), 719 << 16 | 1279); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x68), msr23_word(ref, MSR23_B0 + 0x68)); + KUNIT_EXPECT_MEMEQ(test, img + 0x9080 / 4, ref + 0x9080 / 4, 0x500); + /* NV12: the chroma plane's offset is in CbCr pairs and chroma rows */ + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1280, 1280, 1, 1); + job.compose = (struct v4l2_rect){ 64, 280, 1152, 720 }; + job.enc = V4L2_YCBCR_ENC_709; + memset(img, 0, MSR23_IMG_LEN); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, out.dst_off[0], 280 * 1280 + 64); + KUNIT_EXPECT_EQ(test, out.dst_off[1], 140 * 1280 + 64); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x8c), 576); /* chroma width */ + + /* the source side of the channel map: 0x30 for a conversion at 1:1 only */ + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x78) & 0xffff, 8); + job = (struct msr23_job){}; + msr23_pic(&job.src, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + memset(img, 0, MSR23_IMG_LEN); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x78) & 0xffff, 8); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x7c) & 0xffff, 0x28); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + job.enc = V4L2_YCBCR_ENC_709; + memset(img, 0, MSR23_IMG_LEN); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x78) & 0xffff, 0x30); + + /* a quarter turn: the source keeps its own size, the pipe the destination's */ + job = (struct msr23_job){}; + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1080, 1920, 4, 0); + job.rotate = 90; + memset(img, 0, MSR23_IMG_LEN); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x7c), 1920); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x58), 7680); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x68), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x70), 1919 << 16 | 1079); + + /* a conversion at 1:1 with a quarter turn: the matrix where a scaled job has it */ + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1080, 1920, 1, 1); + job.enc = V4L2_YCBCR_ENC_709; + memset(img, 0, MSR23_IMG_LEN); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x64) & BIT(16), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x6c) & 3, 3); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x78) & 0xffff, 8); + /* ... and with a mirror or half turn it is refused, unless the job scales */ + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + job.rotate = 0; + job.hflip = true; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + job.hflip = false; + job.rotate = 180; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1280, 720, 1, 1); + KUNIT_EXPECT_EQ(test, msr23_check(&job), 0); + job.rotate = 0; + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + job.hflip = true; + KUNIT_EXPECT_EQ(test, msr23_check(&job), 0); /* same format */ + + /* the orientation codes */ + for (i = 0; i < ARRAY_SIZE(orient); i++) { + bool quarter = orient[i].rotate % 180; + + job = (struct msr23_job){ .rotate = orient[i].rotate, .hflip = orient[i].hflip, + .vflip = orient[i].vflip }; + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, quarter ? 1080 : 1920, + quarter ? 1920 : 1080, 4, 0); + memset(img, 0, MSR23_IMG_LEN); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ_MSG(test, msr23_word(img, MSR23_B0 + 0x64) & 0x78, orient[i].code, + "rotate %u hflip %d vflip %d", orient[i].rotate, + orient[i].hflip, orient[i].vflip); + } +} + +/* + * The block list: each block inside the image, at a 128-byte boundary (block + * words hold offset >> 7), and no two overlapping. + */ +static void asc_test_msr23_blocks(struct kunit *test) +{ + unsigned int i, j; + + for (i = 0; i < MSR23_NBLOCKS; i++) { + u32 a = msr23_blocks[i].off, end = a + (msr23_blocks[i].size >> 20) * 32; + + KUNIT_EXPECT_LE(test, end, MSR23_IMG_LEN); + KUNIT_EXPECT_EQ(test, a % 0x80, 0); + for (j = 0; j < i; j++) { + u32 b = msr23_blocks[j].off, bend = b + (msr23_blocks[j].size >> 20) * 32; + + KUNIT_EXPECT_TRUE(test, end <= b || bend <= a); + } + } +} + static struct kunit_case asc_test_cases[] = { KUNIT_CASE_PARAM(asc_test_csc, asc_csc_gen_params), KUNIT_CASE(asc_test_csc_rejects), @@ -648,6 +956,11 @@ static struct kunit_case asc_test_cases[] = { KUNIT_CASE(asc_test_job_rejects), KUNIT_CASE(asc_test_lossless_geom), KUNIT_CASE(asc_test_job_lossless), + KUNIT_CASE(asc_test_msr23_csc), + KUNIT_CASE(asc_test_msr23_scale), + KUNIT_CASE(asc_test_msr23_rejects), + KUNIT_CASE(asc_test_msr23_geometry), + KUNIT_CASE(asc_test_msr23_blocks), {} }; diff --git a/drivers/media/v4l2-core/v4l2-ctrls-core.c b/drivers/media/v4l2-core/v4l2-ctrls-core.c index 648b88c868bc6d..18718345a7ddd6 100644 --- a/drivers/media/v4l2-core/v4l2-ctrls-core.c +++ b/drivers/media/v4l2-core/v4l2-ctrls-core.c @@ -634,6 +634,10 @@ validate_vp9_frame(struct v4l2_ctrl_vp9_frame *frame) if (frame->tile_cols_log2 > 6) return -EINVAL; + /* tile_rows_log2 is coded as up to two one-bit increments. */ + if (frame->tile_rows_log2 > 2) + return -EINVAL; + if (frame->reference_mode > V4L2_VP9_REFERENCE_MODE_SELECT) return -EINVAL; diff --git a/drivers/mfd/macsmc-test.c b/drivers/mfd/macsmc-test.c index 2dec0920f982dc..7d3e8f46848e23 100644 --- a/drivers/mfd/macsmc-test.c +++ b/drivers/mfd/macsmc-test.c @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* Included by macsmc.c; the command and SRAM transports are stubbed. */ +#include #include struct macsmc_test_context { @@ -14,6 +15,9 @@ struct macsmc_test_context { unsigned int seen_count; int ap_power_result; u64 record; + smc_key last_write_key; + size_t last_write_size; + u8 last_write_byte; }; #define MACSMC_TEST_AP_IDLE 0 @@ -26,6 +30,11 @@ static int macsmc_test_command(struct apple_smc *smc, u64 cmd, u64 arg, KUNIT_EXPECT_TRUE(kunit_get_current_test(), mutex_is_locked(&smc->mutex)); ctx->calls++; + if (cmd == SMC_MSG_WRITE_KEY) { + ctx->last_write_key = arg; + ctx->last_write_size = size; + ctx->last_write_byte = ctx->shmem[0]; + } if (ctx->seen_count < ARRAY_SIZE(ctx->seen)) ctx->seen[ctx->seen_count++] = cmd == SMC_MSG_WRITE_KEY ? get_unaligned((u32 *)ctx->shmem) : arg; @@ -352,6 +361,9 @@ static void macsmc_lid_wake_test(struct kunit *test) static void macsmc_wake_reason_test(struct kunit *test) { + static const struct apple_smc_wake_reason j714s[] = { + { 8, "lid" }, { 9, "sdconn" }, { 13, "wifibt" }, { } + }; struct macsmc_test_context *ctx = test->priv; char names[128]; @@ -371,8 +383,8 @@ static void macsmc_wake_reason_test(struct kunit *test) KUNIT_EXPECT_EQ(test, apple_smc_wake_reason_bit(&ctx->smc, "lid"), 8); KUNIT_EXPECT_EQ(test, apple_smc_wake_reason_bit(&ctx->smc, "ipd_touch"), -1); - /* The J714s's: T8132's lid and radio bits, its SD reader at bit 9. */ - ctx->smc.wake_reasons = apple_smc_j714s_wake_reasons; + /* A device tree's own, here the J714s's: its SD reader at bit 9. */ + ctx->smc.wake_reasons = j714s; apple_smc_wake_reason_names(&ctx->smc, BIT_ULL(8) | BIT_ULL(9) | BIT_ULL(10) | BIT_ULL(13), names, sizeof(names)); KUNIT_EXPECT_STREQ(test, names, "lid sdconn wifibt"); @@ -395,6 +407,142 @@ static void macsmc_port_reasons_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, apple_smc_port_reasons_only(&ctx->smc, BIT_ULL(43))); } +/* + * The SMC's first message may come as soon as its endpoint is started: the + * state the probe sets up before the RTKit is enough to take it. + */ +static void macsmc_early_message_test(struct kunit *test) +{ + struct macsmc_test_context *ctx = test->priv; + struct resource sram = DEFINE_RES_MEM(0x10000, SMC_SHMEM_SIZE); + struct apple_smc *smc; + + smc = kunit_kzalloc(test, sizeof(*smc), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, smc); + apple_smc_init_state(smc); + smc->sram = &sram; + smc->sram_base = (void __iomem *)ctx->shmem; + + KUNIT_EXPECT_EQ(test, smc->boot_stage, APPLE_SMC_BOOTING); + KUNIT_EXPECT_FALSE(test, completion_done(&smc->init_done)); + + KUNIT_EXPECT_TRUE(test, apple_smc_rtkit_recv_early(smc, SMC_ENDPOINT, sram.start)); + KUNIT_EXPECT_EQ(test, smc->boot_stage, APPLE_SMC_INITIALIZED); + KUNIT_EXPECT_TRUE(test, completion_done(&smc->init_done)); + KUNIT_EXPECT_PTR_EQ(test, smc->shmem.iomem, smc->sram_base); +} + +static struct device *macsmc_test_attach_dev(struct kunit *test, + struct macsmc_test_context *ctx) +{ + struct device *dev = kunit_device_register(test, "macsmc-test"); + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + dev_set_drvdata(dev, &ctx->smc); + ctx->smc.dev = dev; + return dev; +} + +static void macsmc_wktp_probe_test(struct kunit *test) +{ + struct macsmc_test_context *ctx = test->priv; + const u8 ro_wire[] = { 1, 'u', 'i', '8', ' ', APPLE_SMC_READABLE }; + const u8 wide_wire[] = { 2, 'u', 'i', '1', '6', + APPLE_SMC_READABLE | APPLE_SMC_WRITABLE }; + const u8 valid_wire[] = { 1, 'u', 'i', '8', ' ', + APPLE_SMC_READABLE | APPLE_SMC_WRITABLE | + APPLE_SMC_FUNCTION }; + + macsmc_test_attach_dev(test, ctx); + + /* Absent WKTP leaves has_wktp clear and issues no write. */ + ctx->result = -EIO; + apple_smc_probe_wktp(&ctx->smc); + KUNIT_EXPECT_FALSE(test, ctx->smc.has_wktp); + KUNIT_EXPECT_EQ(test, ctx->calls, 1U); + + /* Read-only or wrong-sized WKTP is ignored. */ + ctx->result = 0; + ctx->calls = 0; + memcpy(ctx->shmem, ro_wire, sizeof(ro_wire)); + apple_smc_probe_wktp(&ctx->smc); + KUNIT_EXPECT_FALSE(test, ctx->smc.has_wktp); + KUNIT_EXPECT_EQ(test, ctx->calls, 1U); + + ctx->calls = 0; + memcpy(ctx->shmem, wide_wire, sizeof(wide_wire)); + apple_smc_probe_wktp(&ctx->smc); + KUNIT_EXPECT_FALSE(test, ctx->smc.has_wktp); + KUNIT_EXPECT_EQ(test, ctx->calls, 1U); + + /* Valid 1-byte writable WKTP enables tracking and writes full wake (0). */ + ctx->calls = 0; + memcpy(ctx->shmem, valid_wire, sizeof(valid_wire)); + apple_smc_probe_wktp(&ctx->smc); + KUNIT_EXPECT_TRUE(test, ctx->smc.has_wktp); + KUNIT_EXPECT_EQ(test, ctx->calls, 2U); + KUNIT_EXPECT_EQ(test, ctx->last_write_key, SMC_KEY(WKTP)); + KUNIT_EXPECT_EQ(test, ctx->last_write_size, sizeof(u8)); + KUNIT_EXPECT_EQ(test, ctx->last_write_byte, (u8)SMC_WAKE_TYPE_FULL); +} + +static void macsmc_wktp_full_wake_test(struct kunit *test) +{ + struct macsmc_test_context *ctx = test->priv; + struct device *dev = macsmc_test_attach_dev(test, ctx); + + pm_suspend_clear_flags(); + + /* Without WKTP capability, complete() issues no write. */ + apple_smc_complete(dev); + KUNIT_EXPECT_EQ(test, ctx->calls, 0U); + + /* Full wake writes WKTP = 0 to exit Silent Running / Power Nap. */ + ctx->smc.has_wktp = true; + ctx->shmem[0] = 0xa5; + apple_smc_complete(dev); + KUNIT_EXPECT_EQ(test, ctx->calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_write_key, SMC_KEY(WKTP)); + KUNIT_EXPECT_EQ(test, ctx->last_write_size, sizeof(u8)); + KUNIT_EXPECT_EQ(test, ctx->last_write_byte, (u8)SMC_WAKE_TYPE_FULL); +} + +static void macsmc_wktp_dark_wake_test(struct kunit *test) +{ + struct macsmc_test_context *ctx = test->priv; + struct device *dev = macsmc_test_attach_dev(test, ctx); + + if (!IS_ENABLED(CONFIG_PM_SLEEP)) + kunit_skip(test, "CONFIG_PM_SLEEP disabled"); + + ctx->smc.has_wktp = true; + pm_suspend_clear_flags(); + pm_set_dark_wake(); + apple_smc_complete(dev); + pm_suspend_clear_flags(); + + KUNIT_EXPECT_EQ(test, ctx->calls, 0U); +} + +static void macsmc_wktp_quarantined_test(struct kunit *test) +{ + struct macsmc_test_context *ctx = test->priv; + struct device *dev = macsmc_test_attach_dev(test, ctx); + + pm_suspend_clear_flags(); + ctx->smc.has_wktp = true; + ctx->smc.saved_enabled = true; + ctx->smc.saved_recovery = true; + + apple_smc_complete(dev); + KUNIT_EXPECT_EQ(test, ctx->calls, 0U); + + ctx->smc.saved_recovery = false; + ctx->smc.saved_fault = -EIO; + apple_smc_complete(dev); + KUNIT_EXPECT_EQ(test, ctx->calls, 0U); +} + static struct kunit_case macsmc_parser_cases[] = { KUNIT_CASE(macsmc_key_info_lock_test), KUNIT_CASE(macsmc_key_index_test), @@ -412,6 +560,11 @@ static struct kunit_case macsmc_parser_cases[] = { KUNIT_CASE(macsmc_lid_wake_test), KUNIT_CASE(macsmc_wake_reason_test), KUNIT_CASE(macsmc_port_reasons_test), + KUNIT_CASE(macsmc_early_message_test), + KUNIT_CASE(macsmc_wktp_probe_test), + KUNIT_CASE(macsmc_wktp_full_wake_test), + KUNIT_CASE(macsmc_wktp_dark_wake_test), + KUNIT_CASE(macsmc_wktp_quarantined_test), {} }; diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index ad4d84f9c3dd2b..7f4d7f9c9f3699 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -55,6 +55,9 @@ /* Restart and power-off go through atomic writes; give the SMC time. */ #define SMC_ATOMIC_TIMEOUT_MS 5000 +/* WKTP wake type: 0 exits Silent Running / Power Nap for a full wake. */ +#define SMC_WAKE_TYPE_FULL 0U + static const struct mfd_cell apple_smc_devs[] = { MFD_CELL_NAME("macsmc-input"), MFD_CELL_NAME("macsmc-power"), @@ -83,12 +86,15 @@ static const struct mfd_cell apple_smc_described_devs[] = { /* * T6050's reboot/power-off and RTC, for a kernel that owns the machine (J775D, booted bare - * metal). Registered only where the device tree describes them, so a T6050 device tree without - * them registers what it did before. + * metal), and the gP GPIO bank, which carries the J716s's N1 power line (gP13, the pwren-gpios + * of its Wi-Fi/Bluetooth port). Registered only where the device tree describes them, so a T6050 + * device tree without them registers what it did before. The gP bank has a cell name of its own: + * "macsmc-gpio" is the PCIO bank's, and the driver binds both by compatible. */ static const struct mfd_cell apple_smc_t6050_described_devs[] = { MFD_CELL_OF("macsmc-reboot", NULL, NULL, 0, 0, "apple,smc-reboot"), MFD_CELL_OF("macsmc-rtc", NULL, NULL, 0, 0, "apple,smc-rtc"), + MFD_CELL_OF("macsmc-gp-gpio", NULL, NULL, 0, 0, "apple,smc-gpio"), }; static int apple_smc_add_described_devices(struct apple_smc *smc, const struct mfd_cell *cells, @@ -113,9 +119,15 @@ static int apple_smc_add_described_devices(struct apple_smc *smc, const struct m return 0; } -/* T8152 currently exposes read-only telemetry; firmware owns fan control. */ +/* + * T8152: temperatures and fans (hwmon; the fan keys are read-only unless the + * unsafe fan_control parameter is set) and power off/restart (reboot, which + * only writes the MBSE key). Notifications, GPIO and the power supply are not + * qualified there yet. + */ static const struct mfd_cell apple_smc_telemetry_devs[] = { MFD_CELL_OF("macsmc-hwmon", NULL, NULL, 0, 0, "apple,smc-hwmon"), + MFD_CELL_OF("macsmc-reboot", NULL, NULL, 0, 0, "apple,smc-reboot"), }; static void apple_smc_read_sram(struct apple_smc *smc, void *buf, size_t size) @@ -629,9 +641,86 @@ static const struct apple_smc_wake_reason apple_smc_j714s_wake_reasons[] = { { 43, "USB2_plug" }, { 44, "USB2_wake" }, { 45, "aupo" }, { 48, "rtc" }, { } }; +/* + * The state the RTKit callbacks use. A message can arrive as soon as the + * RTKit is initialised, so this is set up before that. + */ +static void apple_smc_init_state(struct apple_smc *smc) +{ + mutex_init(&smc->mutex); + spin_lock_init(&smc->lock); + init_completion(&smc->init_done); + init_completion(&smc->cmd_done); + BLOCKING_INIT_NOTIFIER_HEAD(&smc->event_handlers); + smc->boot_stage = APPLE_SMC_BOOTING; +} + +/* A board's own numbering, from its device tree (apple,wake-reasons and their names) */ +static const struct apple_smc_wake_reason *apple_smc_dt_wake_reasons(struct device *dev) +{ + struct device_node *np = dev->of_node; + struct apple_smc_wake_reason *r; + int i, n; + + n = of_property_count_u32_elems(np, "apple,wake-reasons"); + if (n <= 0 || n != of_property_count_strings(np, "apple,wake-reason-names")) + return NULL; + r = devm_kcalloc(dev, n + 1, sizeof(*r), GFP_KERNEL); + if (!r) + return NULL; + for (i = 0; i < n; i++) { + u32 bit; + + if (of_property_read_u32_index(np, "apple,wake-reasons", i, &bit) || bit > 63 || + of_property_read_string_index(np, "apple,wake-reason-names", i, &r[i].name)) + return NULL; + r[i].bit = bit; + } + return r; +} + +static void apple_smc_write_full_wake(struct apple_smc *smc) +{ + int ret; + + ret = apple_smc_write_u8(smc, SMC_KEY(WKTP), SMC_WAKE_TYPE_FULL); + if (ret < 0) + dev_warn(smc->dev, "Failed to write WKTP = %u: %d\n", + SMC_WAKE_TYPE_FULL, ret); +} + +static void apple_smc_probe_wktp(struct apple_smc *smc) +{ + struct apple_smc_key_info info; + int ret; + + ret = apple_smc_get_key_info(smc, SMC_KEY(WKTP), &info); + if (ret < 0 || info.size != sizeof(u8) || + !(info.flags & APPLE_SMC_WRITABLE)) + return; + + smc->has_wktp = true; + apple_smc_write_full_wake(smc); +} + +/* pmVC as the boot left it, next to what apple,sleep-pmvc has the sleep commit write. */ +static void apple_smc_sleep_pmvc_report(struct apple_smc *smc) +{ + u32 cur; + int ret = apple_smc_read_u32(smc, SMC_KEY(pmVC), &cur); + + if (ret) + dev_dbg(smc->dev, "pmVC unreadable (%d); the sleep commit writes %#x\n", ret, + smc->sleep_pmvc); + else + dev_dbg(smc->dev, "pmVC %#x at boot; the sleep commit writes %#x\n", cur, + smc->sleep_pmvc); +} + static int apple_smc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; + const struct apple_smc_wake_reason *dt_reasons; struct apple_smc *smc; __be32 count = 0; bool t6050; @@ -640,20 +729,29 @@ static int apple_smc_probe(struct platform_device *pdev) smc = devm_kzalloc(dev, sizeof(*smc), GFP_KERNEL); if (!smc) return -ENOMEM; - smc->wake_reasons = of_device_is_compatible(dev->of_node, "apple,t8132-smc") ? - apple_smc_t8132_wake_reasons : apple_smc_t8140_wake_reasons; - - mutex_init(&smc->mutex); - spin_lock_init(&smc->lock); + dt_reasons = apple_smc_dt_wake_reasons(dev); + smc->wake_reasons = dt_reasons; + if (!smc->wake_reasons) + smc->wake_reasons = of_device_is_compatible(dev->of_node, "apple,t8132-smc") ? + apple_smc_t8132_wake_reasons : apple_smc_t8140_wake_reasons; + smc->sleep_wake_type = of_property_read_bool(dev->of_node, "apple,sleep-wake-type"); + smc->sleep_pmvc_set = !of_property_read_u32(dev->of_node, "apple,sleep-pmvc", + &smc->sleep_pmvc); + + apple_smc_init_state(smc); smc->dev = &pdev->dev; - smc->saved_enabled = of_machine_is_compatible("apple,t6050") && - (of_machine_is_compatible("apple,j714s") || - of_machine_is_compatible("apple,j716c")) && + smc->saved_enabled = apple_t6050_sleep_described() && of_device_is_compatible(dev->of_node, "apple,t6050-smc"); - if (smc->saved_enabled && of_machine_is_compatible("apple,j714s")) + smc->port_dark_wake = smc->saved_enabled && of_machine_is_compatible("apple,j714s"); + /* A J714s device tree from before apple,wake-reasons */ + if (smc->port_dark_wake && !dt_reasons) smc->wake_reasons = apple_smc_j714s_wake_reasons; - /* J813's late notice needs the bounded, IRQ-independent transport too. */ - if (of_machine_is_compatible("apple,j813")) + /* + * J813's late notice needs the bounded, IRQ-independent transport too, as does T8103's: + * its SMC hears last, after SEP and the other coprocessors stopped. + */ + if (of_machine_is_compatible("apple,j813") || + of_device_is_compatible(dev->of_node, "apple,t8103-smc")) smc->saved_enabled = true; smc->sram_base = devm_platform_get_and_ioremap_resource(pdev, 1, &smc->sram); if (IS_ERR(smc->sram_base)) @@ -666,7 +764,6 @@ static int apple_smc_probe(struct platform_device *pdev) if (IS_ERR(smc->rtk)) return dev_err_probe(dev, PTR_ERR(smc->rtk), "Failed to initialize RTKit"); - smc->boot_stage = APPLE_SMC_BOOTING; ret = apple_rtkit_wake(smc->rtk); if (ret) return dev_err_probe(dev, ret, "Failed to wake up SMC"); @@ -679,9 +776,6 @@ static int apple_smc_probe(struct platform_device *pdev) if (ret) return dev_err_probe(dev, ret, "Failed to start SMC endpoint"); - init_completion(&smc->init_done); - init_completion(&smc->cmd_done); - ret = apple_rtkit_send_message(smc->rtk, SMC_ENDPOINT, FIELD_PREP(SMC_MSG, SMC_MSG_INITIALIZE), NULL, false); if (ret) @@ -698,7 +792,6 @@ static int apple_smc_probe(struct platform_device *pdev) } dev_set_drvdata(&pdev->dev, smc); - BLOCKING_INIT_NOTIFIER_HEAD(&smc->event_handlers); ret = apple_smc_read(smc, SMC_KEY(#KEY), &count, sizeof(count)); if (ret >= 0 && ret != sizeof(count)) { @@ -709,7 +802,10 @@ static int apple_smc_probe(struct platform_device *pdev) return dev_err_probe(smc->dev, ret, "Failed to get key count"); smc->key_count = be32_to_cpu(count); - /* Notifications, GPIO and power management are not qualified on T8152. */ + if (smc->sleep_pmvc_set) + apple_smc_sleep_pmvc_report(smc); + + /* T8152: key reads and writes are qualified; notifications and GPIO are not. */ if (of_device_is_compatible(dev->of_node, "apple,t8152-smc")) return devm_mfd_add_devices(smc->dev, PLATFORM_DEVID_NONE, apple_smc_telemetry_devs, @@ -726,6 +822,8 @@ static int apple_smc_probe(struct platform_device *pdev) if (ret) return ret; + apple_smc_probe_wktp(smc); + t6050 = of_device_is_compatible(dev->of_node, "apple,t6050-smc"); if (t6050) ret = devm_mfd_add_devices(smc->dev, PLATFORM_DEVID_NONE, @@ -830,6 +928,70 @@ int apple_smc_write_noirq(struct apple_smc *smc, smc_key key, const void *buf, s } EXPORT_SYMBOL_GPL(apple_smc_write_noirq); +int apple_smc_warm_reset_parse(struct device_node *np, struct apple_smc_warm_reset *wr) +{ + struct of_phandle_args fn; + int count, i; + + memset(wr, 0, sizeof(*wr)); + if (!np || of_parse_phandle_with_fixed_args(np, "apple,function-warm-reset", 2, 0, &fn)) + return -ENODEV; + wr->smc = of_find_device_by_node(fn.np); + of_node_put(fn.np); + if (!wr->smc) + return -ENODEV; + count = of_property_count_u32_elems(np, "apple,warm-reset-writes"); + if (count < 2 || count % 2 || count > ARRAY_SIZE(wr->writes) || + of_property_read_u32_array(np, "apple,warm-reset-writes", wr->writes, count)) + goto bad; + for (i = 1; i < count; i += 2) + if (wr->writes[i] > 100 * USEC_PER_MSEC) + goto bad; + wr->key = fn.args[0]; + wr->count = count / 2; + return 0; +bad: + apple_smc_warm_reset_put(wr); + return -EINVAL; +} +EXPORT_SYMBOL_GPL(apple_smc_warm_reset_parse); + +void apple_smc_warm_reset_put(struct apple_smc_warm_reset *wr) +{ + if (wr->smc) + put_device(&wr->smc->dev); + memset(wr, 0, sizeof(*wr)); +} +EXPORT_SYMBOL_GPL(apple_smc_warm_reset_put); + +int apple_smc_warm_reset(const struct apple_smc_warm_reset *wr, bool noirq) +{ + struct apple_smc *smc = wr->smc ? platform_get_drvdata(wr->smc) : NULL; + unsigned int i; + int ret = 0; + + if (!smc || !wr->count) + return -ENODEV; + for (i = 0; i < wr->count && !ret; i++) { + __be32 value = cpu_to_be32(wr->writes[2 * i]); + u32 wait = wr->writes[2 * i + 1]; + + if (noirq) { + ret = apple_smc_write_noirq(smc, wr->key, &value, sizeof(value)); + if (!ret) { + mdelay(wait / USEC_PER_MSEC); + udelay(wait % USEC_PER_MSEC); + } + } else { + ret = apple_smc_write(smc, wr->key, &value, sizeof(value)); + if (!ret) + fsleep(wait); + } + } + return ret; +} +EXPORT_SYMBOL_GPL(apple_smc_warm_reset); + static void apple_smc_write_mbse(struct apple_smc *smc, smc_key value) { int ret; @@ -869,10 +1031,56 @@ static int apple_smc_notice_idle(struct apple_smc *smc) return ret; } +/* + * WKTP, one byte: 2 at the sleep commit, 0 again once a wake is a full one. With the + * key left at 2 the SMC treats all the time awake as a power nap: it keeps its own fan + * policy against a fan request (the write times out and the fans stay at its idle + * speed), and under thermal load it requests a sleep once a second. #1910 does the same + * on the M4 Pro. + */ +#define SMC_WKTP_SLEEP 2 +#define SMC_WKTP_AWAKE 0 + +/* WKTP back to 0 after a full wake, or after a sleep that ended in a refusal. */ +static void apple_smc_wake_full(struct apple_smc *smc) +{ + int ret; + + if (!smc->wake_silent) + return; + smc->wake_silent = false; + ret = apple_smc_write_u8(smc, SMC_KEY(WKTP), SMC_WKTP_AWAKE); + if (ret) + dev_err(smc->dev, "Failed to write WKTP = %u: %d\n", SMC_WKTP_AWAKE, ret); +} + static int apple_smc_sleep_commit(struct apple_smc *smc) { int ret; + /* + * apple,sleep-wake-type and apple,sleep-pmvc (T6041): macOS writes WKTP = 2, going to + * sleep, and pmVC, the VDD_CIO rail mask (bit 8 set, bit n keeping port n's CIO rail + * powered across sleep so rails the sleep engine polls active remain up), before its + * sleep notice. Either failing refuses the sleep before slpa; .complete then tells the + * SMC the sleep is off and writes WKTP back. + */ + if (smc->sleep_wake_type) { + /* Whatever came of the write, the SMC may run silent until it is told. */ + smc->wake_silent = true; + ret = apple_smc_write_u8(smc, SMC_KEY(WKTP), SMC_WKTP_SLEEP); + if (ret) { + dev_err(smc->dev, "Failed to write WKTP = %u: %d\n", SMC_WKTP_SLEEP, ret); + return ret; + } + } + if (smc->sleep_pmvc_set) { + ret = apple_smc_write_u32(smc, SMC_KEY(pmVC), smc->sleep_pmvc); + if (ret) { + dev_err(smc->dev, "Failed to write pmVC = %#x: %d\n", smc->sleep_pmvc, ret); + return ret; + } + } apple_smc_write_mbse(smc, SMC_KEY(slpa)); /* Device interrupts are off here. */ mdelay(SMC_SLEEP_ARM_MS); @@ -1035,14 +1243,14 @@ static void apple_smc_dark_wake(struct apple_smc *smc) const char *why = is_radio ? "wifibt" : "USB-C_plug"; s64 asleep_ms; - /* The J714s's rule alone: other boards with a sleep policy keep these wakes full. */ - if (smc->wake_reasons != apple_smc_j714s_wake_reasons) - return; /* Already dark (a port's wake with the lid closed): counted, so the re-entry waits as after ours. */ if (pm_dark_wake()) { smc->dark_wakes++; return; } + /* The J714s's rule alone: other boards with a sleep policy keep these wakes full. */ + if (!smc->port_dark_wake) + return; if (!is_radio && (port < 0 || smc->wake_record != BIT_ULL(port))) return; asleep_ms = ktime_ms_delta(ktime_get_boottime(), smc->sleep_entry_boot) - @@ -1125,6 +1333,9 @@ static void apple_smc_sleep_wake(struct apple_smc *smc, bool woken) } if (apple_smc_port_reasons_only(smc, smc->wake_record)) apple_sleep_debug_link_cut_wake(); + /* A dark wake sleeps again, and its commit writes the key anyway. */ + if (!pm_dark_wake()) + apple_smc_wake_full(smc); /* A dark wake isn't one: with wakeup_count in use, it would abort the sleep after it. */ if (smc->wake_record && !pm_dark_wake()) pm_wakeup_event(smc->dev, 0); @@ -1210,7 +1421,8 @@ static int apple_smc_saved_drain(struct apple_smc *smc) return -ENOBUFS; } -static int apple_smc_saved_write_u32(struct apple_smc *smc, smc_key key, u32 value) +static int apple_smc_saved_write(struct apple_smc *smc, smc_key key, const void *buf, + size_t size) { u64 msg; int ret; @@ -1226,10 +1438,10 @@ static int apple_smc_saved_write_u32(struct apple_smc *smc, smc_key key, u32 val if (ret) return ret; /* Guard precedes the copy. Timeout keeps both this ID and this SRAM. */ - memcpy_toio(smc->shmem.iomem, &value, sizeof(value)); + memcpy_toio(smc->shmem.iomem, buf, size); smc->msg_id = (smc->msg_id + 1) & 0xf; msg = FIELD_PREP(SMC_MSG, SMC_MSG_WRITE_KEY) | - FIELD_PREP(SMC_SIZE, sizeof(value)) | + FIELD_PREP(SMC_SIZE, size) | FIELD_PREP(SMC_ID, smc->msg_id) | FIELD_PREP(SMC_DATA, key); smp_store_release(&smc->saved_pending, true); ret = apple_rtkit_m5_saved_send(smc->rtk, msg); @@ -1246,6 +1458,11 @@ static int apple_smc_saved_write_u32(struct apple_smc *smc, smc_key key, u32 val return FIELD_GET(SMC_SIZE, smc->cmd_ret) ? -EPROTO : 0; } +static int apple_smc_saved_write_u32(struct apple_smc *smc, smc_key key, u32 value) +{ + return apple_smc_saved_write(smc, key, &value, sizeof(value)); +} + static u64 apple_smc_saved_stamp(void) { return __arch_counter_get_cntpct(); @@ -1516,9 +1733,11 @@ static const struct apple_sleep_smc_saved_ops apple_smc_saved_ops = { }; /* - * J813 retains its existing MBSE/AP sequence and delay floors. The transport - * is the saved lane: no scheduler, jiffies, IRQ worker or SRAM reuse is needed - * after the peer stops. Unrelated notifications are retained until resume. + * J813 and T8103 retain their existing MBSE/AP sequence and delay floors. The + * transport is the saved lane: no scheduler, jiffies, IRQ worker or SRAM reuse + * is needed after the peer stops. Unrelated notifications are retained until + * resume, except on gen 1, whose are drained once the AP's power-down is + * answered. */ static int apple_smc_sleep_after_peers(void *data, u64 *sent, u64 *ack) { @@ -1532,14 +1751,26 @@ static int apple_smc_sleep_after_peers(void *data, u64 *sent, u64 *ack) return -EINVAL; smc->saved_committed = true; + /* Gen 1 (T8103): WKTP between slpw and slpa; this SMC has no pmVC. */ + if (apple_sleep_smc_gen1_keys()) { + u8 wktp = 2; + + ret = apple_smc_saved_write(smc, SMC_KEY(WKTP), &wktp, sizeof(wktp)); + if (ret) + goto out; + } ret = apple_smc_saved_write_u32(smc, SMC_KEY(MBSE), SMC_KEY(slpa)); if (ret) goto out; mdelay(SMC_SLEEP_ARM_MS); smc->ap_notified = true; ret = apple_rtkit_m5_saved_ap_power(smc->rtk, false, sent, ack); - if (!ret) + if (!ret) { + /* Gen 1: what the SMC posted with its answer, out of the mailbox first */ + if (apple_sleep_smc_gen1_keys()) + apple_smc_saved_drain(smc); mdelay(SMC_SLEEP_IDLE_MS); + } out: smc->saved_notice_error = ret; return ret; @@ -1583,7 +1814,7 @@ static int apple_smc_prepare_policy(struct apple_smc *smc) /* * The saved-context guard, under the command mutex, without waiting for it: a sleep a user asks - * for doesn't wait on a stuck command. The re-entry right after a J714s dark wake does, for at + * for doesn't wait on a stuck command. The re-entry right after a counted dark wake does, for at * most SMC_DARK_REENTRY_MS: the notification of the event that woke it is still being handled * then, its ordinary command in flight, and refusing ended every dark wake in a full one. */ @@ -1717,6 +1948,12 @@ static void apple_smc_complete(struct device *dev) smc->sleep_warned = false; } smc->sleep_policy = NULL; + if (smc->has_wktp && !pm_dark_wake()) { + smc->wake_silent = false; + apple_smc_write_full_wake(smc); + } + /* A commit the SMC refused, or dark wakes that ended in a refusal. */ + apple_smc_wake_full(smc); } /* @@ -1770,6 +2007,9 @@ static int apple_smc_suspend_noirq(struct device *dev) struct apple_smc *smc = dev_get_drvdata(dev); int ret; + if (!pm_suspend_via_firmware()) + return 0; + /* For the time asleep a dark wake logs: boot time counts the sleep, monotonic doesn't. */ smc->sleep_entry_boot = ktime_get_boottime(); smc->sleep_entry_mono = ktime_get(); @@ -1788,7 +2028,12 @@ static int apple_smc_suspend_noirq(struct device *dev) static int apple_smc_resume_noirq(struct device *dev) { struct apple_smc *smc = dev_get_drvdata(dev); - bool woken = smc->woken_done; + bool woken; + + if (!pm_suspend_via_firmware()) + return 0; + + woken = smc->woken_done; /* This wake's own: never left for another attempt's resume */ smc->woken_done = false; diff --git a/drivers/mfd/macsmc.kunitconfig b/drivers/mfd/macsmc.kunitconfig new file mode 100644 index 00000000000000..936dd1cab03136 --- /dev/null +++ b/drivers/mfd/macsmc.kunitconfig @@ -0,0 +1,11 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_POWER_SUPPLY=y +CONFIG_MACSMC_POWER=y +CONFIG_MACSMC_POWER_KUNIT_TEST=y diff --git a/drivers/mux/apple-display-crossbar.c b/drivers/mux/apple-display-crossbar.c index f45d296eebef4c..7740922e7f316e 100644 --- a/drivers/mux/apple-display-crossbar.c +++ b/drivers/mux/apple-display-crossbar.c @@ -106,6 +106,8 @@ struct apple_dpxbar_hw { bool t6030_flow; /* no UNK_TUNABLE write at probe */ bool no_tunable; + /* DP IN tunnels enable the ATC at 0x38; 0x34 selects UHBR (T604X) */ + bool t604x_dpin_atc; /* power domain held only while an output is selected */ bool runtime_pm; /* T8142 layout: a connection status still busy after its poll is only logged */ @@ -236,6 +238,14 @@ static void t602x_dump(struct apple_dpxbar *xbar, const char *tag) #define T602X_DISPEXT_ENABLE 0x02c #define T602X_MUX_SELECT 0x030 #define T602X_ATC_ENABLE 0x034 +/* + * T604X, when a connection comes up: 0x34 holds a per-clock UHBR select + * (bit n set when the link rate is UHBR, cleared when it is not) and the ATC + * is enabled at 0x38 (its bit ORed in); neither is cleared at teardown. Used + * for DP IN tunnels only: the DP alt mode output keeps the T6030 write. + */ +#define T604X_ATC_UHBR_SELECT 0x034 +#define T604X_ATC_ENABLE 0x038 /* * Field of a T6030 output in the gate, select and enable registers. DP IN 0, @@ -285,7 +295,13 @@ static void apple_dpxbar_t6030_link(struct apple_dpxbar *xbar, dpxbar_set32(xbar, T602X_FIFO_WR_DPTX_CLK_EN, u); dpxbar_set32(xbar, rd, u); dpxbar_set32(xbar, out, d); - dpxbar_set32(xbar, T602X_ATC_ENABLE, d); + if (xbar->hw->t604x_dpin_atc && index != MUX_DPPHY) { + /* DP IN tunnels carry DP 1.x rates only: no UHBR select. */ + dpxbar_clear32(xbar, T604X_ATC_UHBR_SELECT, d); + dpxbar_set32(xbar, T604X_ATC_ENABLE, d); + } else { + dpxbar_set32(xbar, T602X_ATC_ENABLE, d); + } dpxbar_set32(xbar, T602X_DISPEXT_ENABLE, u); } else { dpxbar_clear32(xbar, T602X_DISPEXT_ENABLE, u); @@ -1380,6 +1396,9 @@ static int apple_dpxbar_resume(struct device *dev) u32 shift = apple_dpxbar_t6030_shift(i); u32 mask = (0xfU << shift) | (0xfU << (shift + 12)); u32 route = (state << shift) | (state << (shift + 12)); + /* Where apple_dpxbar_t6030_link() set the ATC enable of this output. */ + u32 atc_enable_reg = xbar->hw->t604x_dpin_atc && i != MUX_DPPHY ? + T604X_ATC_ENABLE : T602X_ATC_ENABLE; if (state < 0) continue; @@ -1388,7 +1407,7 @@ static int apple_dpxbar_resume(struct device *dev) restored |= BIT(i); } if (xbar->tunnel_link_up[i] && - (!(readl(xbar->regs + T602X_ATC_ENABLE) & BIT(shift)) || + (!(readl(xbar->regs + atc_enable_reg) & BIT(shift)) || !(readl(xbar->regs + T602X_DISPEXT_ENABLE) & BIT(state)))) { xbar->tunnel_link_up[i] = false; restored |= BIT(i); @@ -1438,6 +1457,8 @@ static const struct apple_dpxbar_hw apple_dpxbar_hw_t6020 = { * compact register map and flow: the status mirrors at 0x804/0x810/0x81c * follow 0x004/0x014/0x024 and 0x808/0x818 follow 0x00c/0x020, as on T6030. * The ADT lists nine UFP endpoints (dispext0-3, scodec0 and the DP IN ports). + * The ATC USB domain switches off at runtime, so it is only held while an + * output is selected; probe touches no register. */ static const struct apple_dpxbar_hw apple_dpxbar_hw_t6041 = { .n_mux = MUX_MAX, @@ -1445,6 +1466,8 @@ static const struct apple_dpxbar_hw apple_dpxbar_hw_t6041 = { .ops = &apple_dpxbar_t602x_ops, .t6030_flow = true, .no_tunable = true, + .t604x_dpin_atc = true, + .runtime_pm = true, }; /* diff --git a/drivers/net/ethernet/realtek/r8169_main.c b/drivers/net/ethernet/realtek/r8169_main.c index ee1bc9bd04470c..d3cef6016c410f 100644 --- a/drivers/net/ethernet/realtek/r8169_main.c +++ b/drivers/net/ethernet/realtek/r8169_main.c @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -5598,6 +5599,10 @@ static void rtl_init_mac_address(struct rtl8169_private *tp) /* register is set if system vendor successfully tested ASPM 1.2 */ static bool rtl_aspm_is_safe(struct rtl8169_private *tp) { + if (device_property_read_bool(&tp->pci_dev->dev, + "realtek,aspm-safe")) + return true; + if (tp->mac_version >= RTL_GIGA_MAC_VER_46 && r8168_mac_ocp_read(tp, 0xc0b2) & 0xf) return true; diff --git a/drivers/net/wireless/apple/Kconfig b/drivers/net/wireless/apple/Kconfig index d9b13a9785de26..d1dcc1211f1551 100644 --- a/drivers/net/wireless/apple/Kconfig +++ b/drivers/net/wireless/apple/Kconfig @@ -10,6 +10,7 @@ config APPLE_CENTAURI tristate "Apple N1 Centauri experimental J813 Wi-Fi" depends on ARCH_APPLE || COMPILE_TEST depends on PCI && CFG80211 && DEBUG_FS + depends on MFD_MACSMC select FW_LOADER help Experimental Apple N1 PCIe and ACIPC Wi-Fi support for the J813 @@ -23,6 +24,17 @@ config APPLE_CENTAURI To build as a module, choose M; the module is apple_centauri. +config APPLE_CENTAURI_KUNIT_TEST + bool "KUnit tests for the N1 Centauri Wi-Fi reply parsing" if !KUNIT_ALL_TESTS + depends on APPLE_CENTAURI && KUNIT=y + default KUNIT_ALL_TESTS + help + Build tests that pass statistics replies to the Centauri Wi-Fi + reply handler and check the recorded counter lengths. They need no + N1 hardware. + + If unsure, say N. + config APPLE_CENTAURI_T6050 tristate "Apple N1 Centauri T6050 firmware and IPC transport" depends on ARCH_APPLE || COMPILE_TEST diff --git a/drivers/net/wireless/apple/centauri/centauri.h b/drivers/net/wireless/apple/centauri/centauri.h index fa937c1c4e2e3b..17abbfb8352f29 100644 --- a/drivers/net/wireless/apple/centauri/centauri.h +++ b/drivers/net/wireless/apple/centauri/centauri.h @@ -6,6 +6,7 @@ #include #include #include +#include #define CEN_ALPHA_SCRATCH_OFFSET SZ_8M #define CEN_ALPHA_SCRATCH_SIZE (5 * SZ_1M) @@ -23,7 +24,7 @@ struct centauri { void __iomem *bar; resource_size_t size; u32 stage_offset; - struct dentry *debug; + struct dentry *debug, *crash_file; struct mutex boot_lock; void *firmware, *descriptor, *msi_page; dma_addr_t firmware_dma, descriptor_dma, msi_dma; @@ -35,6 +36,14 @@ struct centauri { bool link_ready; struct centauri_ipc *ipc; struct centauri_wifi *wifi; + /* Restart of a stopped firmware: requested by the Wi-Fi code, confirmed and run here */ + struct delayed_work recover_work; + unsigned long recover_at[3]; + bool removing; + bool recover_gave_up; /* restart limit reached: requests are ignored */ + bool restart_failed; /* the last restart failed with the link up: try again */ + bool warm_reset; /* the root port describes the N1's warm reset: restart on a stop */ + bool inject_stall; /* debugfs test: the next check finds the firmware stopped */ }; /* One row per machine with an N1: the FTAB file name, the word written to BAR+0x807c, @@ -92,8 +101,10 @@ static inline const struct centauri_board *centauri_board(void) return NULL; } -int centauri_port_cycle(struct pci_dev *pdev); +int centauri_port_cycle(struct pci_dev *pdev, int *reset_ret); +bool centauri_warm_reset_described(struct pci_dev *pdev); int centauri_start_ipc(struct centauri *c); +bool centauri_beta_running(struct centauri *c); void centauri_free_ipc(struct centauri *c); int centauri_alpha_resources(struct centauri *c, struct cen_alpha_resources *resources); int centauri_alpha_log_buffer(struct centauri *c, void **cpu, dma_addr_t *dma, size_t *size); @@ -102,4 +113,6 @@ void centauri_wifi_unregister(struct centauri *c); int centauri_wifi_suspend(struct centauri *c); int centauri_wifi_resume(struct centauri *c); void centauri_wifi_kick(struct centauri *c); +bool centauri_wifi_stalled(struct centauri *c); +void centauri_recovery_request(struct centauri *c, const char *why); #endif diff --git a/drivers/net/wireless/apple/centauri/centauri_ipc.c b/drivers/net/wireless/apple/centauri/centauri_ipc.c index 6f96041c772902..2905a7e56e8ced 100644 --- a/drivers/net/wireless/apple/centauri/centauri_ipc.c +++ b/drivers/net/wireless/apple/centauri/centauri_ipc.c @@ -33,6 +33,7 @@ struct centauri_ipc { struct list_head buffers; struct pci_dev *function[3]; void __iomem *bar[3]; + bool enabled[3]; struct cen_context control, alpha; struct cen_buffer *secondary, *window, *cchi_rx, *cchi_tx, *debug_rx; struct cen_buffer *alpha_log; @@ -169,7 +170,13 @@ static int secondary_init(struct centauri *c) pci_write_config_dword(c->pdev, 0xf8c, upper_32_bits(c->ipc->secondary->dma)); pci_write_config_dword(c->pdev, 0xf90, required); dev_info(&c->pdev->dev, "secondary memory: seed=%u required=%u\n", length, required); - debugfs_create_file("firmware_crash", 0400, c->debug, c, &firmware_crash_fops); + /* + * Created once and kept across restarts: its reader looks up c->ipc under boot_lock, + * and removing it here, under boot_lock, would wait for a reader blocked on that lock. + */ + if (!c->crash_file) + c->crash_file = debugfs_create_file("firmware_crash", 0400, c->debug, c, + &firmware_crash_fops); return 0; } @@ -233,7 +240,7 @@ static int message(struct cen_context *ctx, void __iomem *doorbell, { u16 head = ctx->message_head; u8 *descriptor; - u16 tail; + __le16 tail; int ret; if (head >= 15 || !length || length > 512) @@ -274,7 +281,7 @@ static int cchi_init(struct centauri *c) { struct centauri_ipc *ipc = c->ipc; u8 config[4] = {9, 0, 0xff, 0xff}, *entry; - u16 tail; + __le16 tail; int i, ret; ipc->cchi_rx = buffer_alloc(c, 0, SZ_32K); @@ -420,7 +427,7 @@ static int enumerate_functions(struct centauri *c) { struct centauri_ipc *ipc = c->ipc; u16 control; - int i, cap; + int i, cap, ret; dma_addr_t msi; pci_lock_rescan_remove(); @@ -436,6 +443,14 @@ static int enumerate_functions(struct centauri *c) return -ENODEV; if (!(pci_resource_flags(ipc->function[i], 0) & IORESOURCE_MEM)) return -ENODEV; + if (i) { + device_lock(&ipc->function[i]->dev); + ret = pci_enable_device_mem(ipc->function[i]); + device_unlock(&ipc->function[i]->dev); + if (ret) + return ret; + ipc->enabled[i] = true; + } ipc->bar[i] = pci_iomap(ipc->function[i], 0, 0); if (!ipc->bar[i]) return -ENOMEM; @@ -546,6 +561,19 @@ int centauri_start_ipc(struct centauri *c) return ret; } +/* + * Whether Beta's (Bluetooth's) firmware runs with its IPC still unowned: the state + * btcentauri needs to take function 2. Called with the boot lock held. + */ +bool centauri_beta_running(struct centauri *c) +{ + struct centauri_ipc *ipc = c->ipc; + + if (!ipc || !ipc->enabled[2] || !ipc->bar[2]) + return false; + return readl(ipc->bar[2] + 0x18) == 2 && !readl(ipc->bar[2]); +} + void centauri_free_ipc(struct centauri *c) { struct centauri_ipc *ipc = c->ipc; @@ -578,6 +606,11 @@ void centauri_free_ipc(struct centauri *c) for (i = 0; i < 3; i++) { if (ipc->bar[i]) pci_iounmap(ipc->function[i], ipc->bar[i]); + if (ipc->enabled[i]) { + device_lock(&ipc->function[i]->dev); + pci_disable_device(ipc->function[i]); + device_unlock(&ipc->function[i]->dev); + } pci_dev_put(ipc->function[i]); } kfree(ipc); diff --git a/drivers/net/wireless/apple/centauri/centauri_pci.c b/drivers/net/wireless/apple/centauri/centauri_pci.c index 598671387565a8..b2b1cd434a6577 100644 --- a/drivers/net/wireless/apple/centauri/centauri_pci.c +++ b/drivers/net/wireless/apple/centauri/centauri_pci.c @@ -15,6 +15,7 @@ #include #include #include +#include #include "centauri.h" @@ -28,6 +29,8 @@ static int centauri_status_show(struct seq_file *s, void *unused) { struct centauri *c = s->private; + /* A restart cycles the link: no BAR read while it runs */ + mutex_lock(&c->boot_lock); seq_printf(s, "pci=%s vendor=%04x device=%04x\n", pci_name(c->pdev), c->pdev->vendor, c->pdev->device); if (c->link_ready) @@ -38,6 +41,7 @@ static int centauri_status_show(struct seq_file *s, void *unused) seq_printf(s, "transport=hardware-pci firmware_boot=%s image_response=%#x wifi=%s\n", c->boot_attempted ? "attempted" : "not-started", c->image_response, READ_ONCE(c->wifi) ? "registered" : "not-owned-by-this-function"); + mutex_unlock(&c->boot_lock); return 0; } DEFINE_SHOW_ATTRIBUTE(centauri_status); @@ -156,6 +160,188 @@ static int centauri_rom_boot(struct centauri *c) return ret; } +/* + * Restart the N1 from a running or stopped firmware, without the bootloader: release + * everything the firmware could write to, then a port cycle with the SMC warm reset + * (PERST# alone leaves the firmware running), which leaves the chip in its ROM (stage 0), + * then the boot steps 1-3 as at probe. btcentauri is released first: it drives function 2 + * over the IPC that is freed here. + * + * Not safe against function 0 being removed under the PCI rescan lock (sysfs remove, host + * unbind, hot unplug) while a restart runs: remove waits for the restart, which waits for the + * rescan lock. The debugfs boot steps have the same limit. + */ +static int centauri_recover(struct centauri *c) +{ + struct device *dev = &c->pdev->dev; + u32 stage = readl(c->bar + 0x8000); + struct pci_dev *beta; + int ret, reset_ret, i; + + if (!c->warm_reset) + return -EOPNOTSUPP; + if (!c->link_ready || PCI_FUNC(c->pdev->devfn)) + return -EBUSY; + dev_info(dev, "recovery: stage %#x, releasing the firmware's buffers\n", stage); + beta = pci_get_slot(c->pdev->bus, PCI_DEVFN(PCI_SLOT(c->pdev->devfn), 2)); + if (beta) + device_release_driver(&beta->dev); + pci_dev_put(beta); + centauri_free_boot(c); + /* + * The warm reset puts the chip back in its single-function ROM personality and wipes + * functions 1 and 2. Remove them now; the IPC start's rescan adds them again, as at + * probe. A stale function's BAR read after the reset hangs the fabric. + */ + pci_lock_rescan_remove(); + for (i = 2; i >= 1; i--) { + struct pci_dev *fn = pci_get_slot(c->pdev->bus, + PCI_DEVFN(PCI_SLOT(c->pdev->devfn), i)); + + if (fn) + pci_stop_and_remove_bus_device(fn); + pci_dev_put(fn); + } + pci_unlock_rescan_remove(); + c->boot_attempted = false; + c->image_response = 0; + c->link_ready = false; + ret = centauri_port_cycle(c->pdev, &reset_ret); + if (ret) { + dev_err(dev, "recovery: reset port cycle failed: %d\n", ret); + return ret; + } + c->link_ready = true; + if (reset_ret) { + dev_err(dev, "recovery: warm reset failed: %d\n", reset_ret); + return reset_ret; + } + stage = readl(c->bar + 0x8000); + dev_info(dev, "recovery: stage %#x after the warm reset\n", stage); + if (stage != 0) + return -EIO; + /* Returns once the ROM reports the image loaded (stage 4), as the boot step does. */ + ret = centauri_rom_boot(c); + if (ret) { + dev_err(dev, "recovery: ROM boot failed: %d\n", ret); + return ret; + } + c->link_ready = false; + ret = centauri_port_cycle(c->pdev, NULL); + if (ret) { + dev_err(dev, "recovery: boot port cycle failed: %d\n", ret); + return ret; + } + c->link_ready = true; + /* The IPC start needs the image's first stage (1) after the port cycle. */ + ret = readl_poll_timeout(c->bar + 0x8000, stage, stage == 1, 20 * USEC_PER_MSEC, + 5 * USEC_PER_SEC); + dev_info(dev, "recovery: post-reset execution stage=%#x\n", stage); + if (ret) + return ret; + ret = centauri_start_ipc(c); + dev_info(dev, "recovery: IPC start %d\n", ret); + return ret; +} + +/* Ordered and freezable: a restart never runs during a system sleep or beside another one. */ +static struct workqueue_struct *centauri_wq; + +/* + * The Wi-Fi code saw a sign of a stopped firmware: an Alpha execution stage other than 2, + * a command ring the firmware no longer drains, or a command timeout. The worker looks + * again 2 s later and restarts the chip only if the firmware is still stopped. + */ +void centauri_recovery_request(struct centauri *c, const char *why) +{ + if (!c->warm_reset || READ_ONCE(c->removing) || READ_ONCE(c->recover_gave_up)) + return; + if (queue_delayed_work(centauri_wq, &c->recover_work, 2 * HZ)) + dev_warn(&c->pdev->dev, "firmware fault (%s); checking again in 2 s\n", why); +} + +static bool centauri_beta_up(struct centauri *c) +{ + bool up; + + mutex_lock(&c->boot_lock); + up = READ_ONCE(c->removing) || centauri_beta_running(c); + mutex_unlock(&c->boot_lock); + return up; +} + +/* + * The IPC start's rescan adds the Beta (Bluetooth) function before Beta's firmware runs, + * so btcentauri cannot take it then. Wait for that firmware and attach the function. + * Called without the boot lock and outside the PCI rescan lock. Returns 1 when + * function 2 has a driver, 0 when none took it, or a negative error. + */ +static int centauri_attach_beta(struct centauri *c) +{ + struct pci_dev *beta; + bool up; + int ret; + + beta = pci_get_slot(c->pdev->bus, PCI_DEVFN(PCI_SLOT(c->pdev->devfn), 2)); + if (!beta) + return -ENODEV; + ret = 1; + if (!READ_ONCE(beta->dev.driver)) { + ret = read_poll_timeout(centauri_beta_up, up, up, 20 * USEC_PER_MSEC, + 10 * USEC_PER_SEC, false, c); + if (!ret) + ret = READ_ONCE(c->removing) ? -ENODEV : device_attach(&beta->dev); + } + pci_dev_put(beta); + return ret; +} + +static void centauri_recover_worker(struct work_struct *work) +{ + struct centauri *c = container_of(to_delayed_work(work), struct centauri, recover_work); + struct device *dev = &c->pdev->dev; + unsigned long now = jiffies; + int ret; + + mutex_lock(&c->boot_lock); + if (READ_ONCE(c->removing) || (!c->ipc && !c->restart_failed)) { + mutex_unlock(&c->boot_lock); + return; + } + if (!xchg(&c->inject_stall, false) && !c->restart_failed && !centauri_wifi_stalled(c)) { + mutex_unlock(&c->boot_lock); + dev_info(dev, "firmware fault cleared; no restart\n"); + return; + } + /* Three restarts in 30 minutes: the chip is left down rather than reset in a loop. */ + if (c->recover_at[0] && time_before(now, c->recover_at[0] + 30 * 60 * HZ)) { + WRITE_ONCE(c->recover_gave_up, true); + mutex_unlock(&c->boot_lock); + dev_err(dev, "firmware stopped again after 3 restarts in 30 min; leaving Wi-Fi down until the driver is reloaded\n"); + return; + } + memmove(c->recover_at, c->recover_at + 1, sizeof(c->recover_at) - sizeof(c->recover_at[0])); + c->recover_at[ARRAY_SIZE(c->recover_at) - 1] = now; + dev_warn(dev, "firmware stopped; restarting the N1\n"); + ret = centauri_recover(c); + /* With the link up the chip can be reset again; without it nothing more can be done. */ + c->restart_failed = ret && c->link_ready; + mutex_unlock(&c->boot_lock); + if (ret && !c->restart_failed) { + dev_err(dev, "restart failed: %d, and the link is down; Wi-Fi stays down until a reboot\n", + ret); + return; + } + if (ret) { + /* Counts against the same limit: at most three attempts in 30 minutes. */ + dev_err(dev, "restart failed: %d; trying again in 10 s\n", ret); + if (!READ_ONCE(c->removing)) + queue_delayed_work(centauri_wq, &c->recover_work, 10 * HZ); + return; + } + dev_info(dev, "restarted; Bluetooth function attach: %d\n", centauri_attach_beta(c)); +} + static ssize_t centauri_boot_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { @@ -163,18 +349,25 @@ static ssize_t centauri_boot_write(struct file *file, const char __user *buffer, u32 value; int ret = kstrtou32_from_user(buffer, count, 0, &value); - if (ret || value < 1 || value > 3) + if (ret || value < 1 || value > 6) return ret ?: -EINVAL; mutex_lock(&c->boot_lock); if (value == 1) { ret = centauri_rom_boot(c); } else if (value == 3) { ret = centauri_start_ipc(c); + } else if (value == 4) { + ret = centauri_recover(c); + } else if (value == 5 || value == 6) { + /* Test the fault path: 5 as a stopped firmware, 6 as a fault that clears. */ + WRITE_ONCE(c->inject_stall, value == 5); + centauri_recovery_request(c, value == 5 ? "debugfs: stopped" : "debugfs: spurious"); + ret = 0; } else if (!c->firmware || !c->link_ready || readl(c->bar + 0x8000) != 4) { ret = -EBUSY; } else { c->link_ready = false; - ret = centauri_port_cycle(c->pdev); + ret = centauri_port_cycle(c->pdev, NULL); if (!ret) { c->link_ready = true; dev_info(&c->pdev->dev, "post-reset execution stage=%#x\n", @@ -182,6 +375,14 @@ static ssize_t centauri_boot_write(struct file *file, const char __user *buffer, } } mutex_unlock(&c->boot_lock); + if (value == 3 && !ret) { + int attached = centauri_attach_beta(c); + + if (attached == 1) + dev_info(&c->pdev->dev, "Bluetooth function attached\n"); + else + dev_warn(&c->pdev->dev, "Bluetooth function not attached: %d\n", attached); + } return ret ?: count; } @@ -210,6 +411,8 @@ static int centauri_probe(struct pci_dev *pdev, const struct pci_device_id *id) c->pdev = pdev; c->link_ready = true; mutex_init(&c->boot_lock); + INIT_DELAYED_WORK(&c->recover_work, centauri_recover_worker); + c->warm_reset = centauri_warm_reset_described(pdev); c->stage_offset = id->driver_data; ret = pcim_enable_device(pdev); if (ret) @@ -246,6 +449,9 @@ static void centauri_remove(struct pci_dev *pdev) { struct centauri *c = pci_get_drvdata(pdev); + /* Disabled, not only cancelled: a request racing this remove can no longer queue it */ + WRITE_ONCE(c->removing, true); + disable_delayed_work_sync(&c->recover_work); centauri_wifi_unregister(c); debugfs_remove_recursive(c->debug); centauri_free_boot(c); @@ -282,9 +488,10 @@ static int centauri_resume(struct device *dev) static DEFINE_SIMPLE_DEV_PM_OPS(centauri_pm_ops, centauri_suspend, centauri_resume); -/* 0x1903 is the Beta (Bluetooth) function: btcentauri claims it. This driver needs functions - * 0 and 1 (1 is enabled here, its BAR is used by the Wi-Fi code) and reaches function 2 only - * through config space and its struct device for DMA. +/* 0x1903 is the Beta (Bluetooth) function: btcentauri claims it. This driver binds functions + * 0 and 1 (1 is enabled here, its BAR is used by the Wi-Fi code) and enables function 2's + * memory space during IPC bootstrap so centauri_beta_running() can poll Beta's BAR0 safely + * even when btcentauri has not probed yet. */ static const struct pci_device_id centauri_ids[] = { { PCI_DEVICE(PCI_VENDOR_ID_APPLE, 0x1900), .driver_data = 0x8000 }, @@ -306,10 +513,15 @@ static int __init centauri_init(void) { int ret; + centauri_wq = alloc_ordered_workqueue("apple_centauri", WQ_FREEZABLE); + if (!centauri_wq) + return -ENOMEM; centauri_debug = debugfs_create_dir("apple_centauri", NULL); ret = pci_register_driver(¢auri_driver); - if (ret) + if (ret) { debugfs_remove_recursive(centauri_debug); + destroy_workqueue(centauri_wq); + } return ret; } @@ -317,6 +529,7 @@ static void __exit centauri_exit(void) { pci_unregister_driver(¢auri_driver); debugfs_remove_recursive(centauri_debug); + destroy_workqueue(centauri_wq); } module_init(centauri_init); module_exit(centauri_exit); diff --git a/drivers/net/wireless/apple/centauri/centauri_port.c b/drivers/net/wireless/apple/centauri/centauri_port.c index 59eadc3f8521c0..55964946895e7b 100644 --- a/drivers/net/wireless/apple/centauri/centauri_port.c +++ b/drivers/net/wireless/apple/centauri/centauri_port.c @@ -11,7 +11,10 @@ #include #include #include +#include +#include #include +#include #include "centauri.h" static void update(void __iomem *base, u32 offset, u32 clear, u32 set) @@ -26,7 +29,64 @@ static bool wait_bits(void __iomem *address, u32 mask, u32 wanted, u32 us) return !readl_poll_timeout(address, value, (value & mask) == wanted, 100, us); } -int centauri_port_cycle(struct pci_dev *pdev) +/* + * The N1's warm reset, as the root port describes it (bindings/pci/apple,pcie.yaml, as on the + * T6050 boards): "apple,function-warm-reset" names the SMC and the key (the ADT's pci-bridge0 + * function-warm_reset), "apple,warm-reset-writes" the writes. + */ +static int warm_reset_parse(struct pci_dev *pdev, struct apple_smc_warm_reset *wr) +{ + struct pci_dev *bridge = pdev->bus->self; + + if (!IS_REACHABLE(CONFIG_MFD_MACSMC) || !bridge) + return -ENODEV; + return apple_smc_warm_reset_parse(pci_device_to_OF_node(bridge), wr); +} + +/* + * The root port describes a warm reset, and centauri_port_cycle() can cycle this port: only + * then does the driver restart a stopped N1, so a restart never tears the functions down on a + * board whose port cycle would refuse. + */ +bool centauri_warm_reset_described(struct pci_dev *pdev) +{ + const struct centauri_board *board = centauri_board(); + struct pci_dev *bridge = pdev->bus->self; + struct apple_smc_warm_reset wr; + + if (!board || !board->port || !bridge || bridge->vendor != PCI_VENDOR_ID_APPLE || + (board->bridge_id && bridge->device != board->bridge_id)) + return false; + if (warm_reset_parse(pdev, &wr)) + return false; + apple_smc_warm_reset_put(&wr); + return true; +} + +/* + * Given while the port is down and not set up: the link then trains a chip that was just + * reset. PERST# alone leaves the firmware running. + */ +static int warm_reset(struct pci_dev *pdev) +{ + struct apple_smc_warm_reset wr; + int ret; + + ret = warm_reset_parse(pdev, &wr); + if (!ret) { + ret = apple_smc_warm_reset(&wr, false); + apple_smc_warm_reset_put(&wr); + } + dev_info(&pdev->dev, "warm reset through the SMC: %d\n", ret); + return ret; +} + +/* + * Take the N1's port down and train it again. With @reset_ret, the N1 is warm reset while + * the port is down and the reset's result is stored there; the link comes up either way. + * Returns the link's result. + */ +int centauri_port_cycle(struct pci_dev *pdev, int *reset_ret) { static const u32 reset[][2] = { {0x88, 0x110}, {0x100, ~0U}, {0x148, ~0U}, {0x210, ~0U}, @@ -141,6 +201,8 @@ int centauri_port_cycle(struct pci_dev *pdev) writel(0, port + 0x3800 + 4 * i); for (i = 0; i < ARRAY_SIZE(tune); i++) writel(tune[i][1], port + tune[i][0]); + if (reset_ret) + *reset_ret = warm_reset(pdev); update(port, 0x800, 0, 1); udelay(10); update(phy, 0, 0, 1); diff --git a/drivers/net/wireless/apple/centauri/centauri_wifi.c b/drivers/net/wireless/apple/centauri/centauri_wifi.c index de0d4d872932a0..baa22f48895646 100644 --- a/drivers/net/wireless/apple/centauri/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/centauri_wifi.c @@ -160,6 +160,7 @@ struct centauri_wifi { u8 country[3]; bool country_valid; u8 station_stats[0x378]; + u16 station_stats_len; bool station_stats_valid; u8 rx_crypto_stats[64]; bool rx_crypto_stats_valid; @@ -549,6 +550,43 @@ static void drain_data_tx(struct centauri_wifi *wifi) netif_wake_queue(wifi->netdev); } +/* Record a reply to the statistics command 0xb0001. */ +static void record_stats_reply(struct centauri_wifi *wifi, const u8 *packet, + u16 size, u16 status) +{ + wifi->stats_reply_size = size; + wifi->stats_tag = size >= 28 ? get_unaligned_le16(packet + 24) : 0; + wifi->stats_length = size >= 28 ? get_unaligned_le16(packet + 26) : 0; + if (!status && wifi->stats_tag == 0xf928 && + (wifi->stats_length == 752 || wifi->stats_length == 888) && + size >= 28 + wifi->stats_length) { + /* Native firmware returns the older 752-byte counter record. */ + memset(wifi->station_stats, 0, sizeof(wifi->station_stats)); + memcpy(wifi->station_stats, packet + 28, wifi->stats_length); + /* A later reply can change stats_length; keep this record's own. */ + wifi->station_stats_len = wifi->stats_length; + wifi->station_stats_valid = true; + } + if (!status && wifi->stats_tag == 0xf921 && + wifi->stats_length == sizeof(wifi->rx_crypto_stats) && + size >= 28 + sizeof(wifi->rx_crypto_stats)) { + memcpy(wifi->rx_crypto_stats, packet + 28, sizeof(wifi->rx_crypto_stats)); + wifi->rx_crypto_stats_valid = true; + } + if (!status && wifi->stats_tag == 0xf91b && + wifi->stats_length == sizeof(wifi->dot11_mib_stats) && + size >= 28 + sizeof(wifi->dot11_mib_stats)) { + memcpy(wifi->dot11_mib_stats, packet + 28, sizeof(wifi->dot11_mib_stats)); + wifi->dot11_mib_stats_valid = true; + } + if (!status && wifi->stats_tag == 0xf920 && + wifi->stats_length == sizeof(wifi->tx_power_report) && + size >= 28 + sizeof(wifi->tx_power_report)) { + memcpy(wifi->tx_power_report, packet + 28, sizeof(wifi->tx_power_report)); + wifi->tx_power_report_valid = true; + } +} + static void drain_control(struct centauri_wifi *wifi, bool pm_command) { unsigned int ring; @@ -673,37 +711,8 @@ static void drain_control(struct centauri_wifi *wifi, bool pm_command) pos += 4 + length; } } - if (command == 0xb0001) { - wifi->stats_reply_size = size; - wifi->stats_tag = size >= 28 ? get_unaligned_le16(packet + 24) : 0; - wifi->stats_length = size >= 28 ? get_unaligned_le16(packet + 26) : 0; - } - if (command == 0xb0001 && !status && wifi->stats_tag == 0xf928 && - (wifi->stats_length == 752 || wifi->stats_length == 888) && - size >= 28 + wifi->stats_length) { - /* Native firmware returns the older 752-byte counter record. */ - memset(wifi->station_stats, 0, sizeof(wifi->station_stats)); - memcpy(wifi->station_stats, packet + 28, wifi->stats_length); - wifi->station_stats_valid = true; - } - if (command == 0xb0001 && !status && wifi->stats_tag == 0xf921 && - wifi->stats_length == sizeof(wifi->rx_crypto_stats) && - size >= 28 + sizeof(wifi->rx_crypto_stats)) { - memcpy(wifi->rx_crypto_stats, packet + 28, sizeof(wifi->rx_crypto_stats)); - wifi->rx_crypto_stats_valid = true; - } - if (command == 0xb0001 && !status && wifi->stats_tag == 0xf91b && - wifi->stats_length == sizeof(wifi->dot11_mib_stats) && - size >= 28 + sizeof(wifi->dot11_mib_stats)) { - memcpy(wifi->dot11_mib_stats, packet + 28, sizeof(wifi->dot11_mib_stats)); - wifi->dot11_mib_stats_valid = true; - } - if (command == 0xb0001 && !status && wifi->stats_tag == 0xf920 && - wifi->stats_length == sizeof(wifi->tx_power_report) && - size >= 28 + sizeof(wifi->tx_power_report)) { - memcpy(wifi->tx_power_report, packet + 28, sizeof(wifi->tx_power_report)); - wifi->tx_power_report_valid = true; - } + if (command == 0xb0001) + record_stats_reply(wifi, packet, size, status); if (command == 0xf0025) { wifi->pmk_seen = !status && size >= 60; wifi->pmk_matches = wifi->pmk_seen && @@ -745,8 +754,10 @@ static int command_control(struct centauri_wifi *wifi, u32 id, const void *paylo return -EBUSY; if (size + 24 > BUFFER_SIZE) return -EMSGSIZE; - if ((slot + 1) % ring_size[1] == index_read(wifi, 1, 1)) + if ((slot + 1) % ring_size[1] == index_read(wifi, 1, 1)) { + centauri_recovery_request(wifi->control, "command ring full"); return -ENOSPC; + } packet = wifi->a.window + TX_BUFFER + slot * BUFFER_SIZE; memset(packet, 0, 24 + size); put_unaligned_le16(24 + size, packet + 0x10); @@ -766,8 +777,10 @@ static int command_control(struct centauri_wifi *wifi, u32 id, const void *paylo writel(1, wifi->a.bar + 0x1004); do { drain_control(wifi, pm_command); - if (readl(wifi->a.bar + 8) != 2) + if (readl(wifi->a.bar + 8) != 2) { + centauri_recovery_request(wifi->control, "command: Alpha stage"); return -EIO; + } /* Bit 30 is more-data-pending, not part of the command identity. * Scan/connect replies set it before their later completion event. */ @@ -782,9 +795,26 @@ static int command_control(struct centauri_wifi *wifi, u32 id, const void *paylo usleep_range(500, 1000); } while (time_before(jiffies, deadline)); dev_err(&wifi->control->pdev->dev, "Wi-Fi command %#x timed out (rx=%u)\n", id, wifi->rx_seen[2]); + centauri_recovery_request(wifi->control, "command timeout"); return -ETIMEDOUT; } +/* + * The firmware has stopped: Alpha left execution stage 2, or the command ring stays full + * (a running firmware drains each command before the next is queued). Not while the + * transport is paused for a system sleep. + */ +bool centauri_wifi_stalled(struct centauri *c) +{ + struct centauri_wifi *wifi = c->wifi; + + if (!wifi || READ_ONCE(wifi->transport_paused) || READ_ONCE(wifi->stopping)) + return false; + if (readl(wifi->a.bar + 8) != 2) + return true; + return (READ_ONCE(wifi->command_head) + 1) % ring_size[1] == index_read(wifi, 1, 1); +} + static int command(struct centauri_wifi *wifi, u32 id, const void *payload, size_t size) { return command_control(wifi, id, payload, size, false); @@ -913,6 +943,49 @@ static size_t build_scan(struct centauri_wifi *wifi, unsigned int chunk, u8 *buf return size; } +static bool scan_transport_stopped(struct centauri_wifi *wifi) +{ + return READ_ONCE(wifi->stopping) || + READ_ONCE(wifi->transport_paused) || + readl(wifi->a.bar + 8) != 2; +} + +static int scan_wait_stop(struct centauri_wifi *wifi, u32 done) +{ + unsigned long deadline = jiffies + msecs_to_jiffies(1000); + + do { + if (scan_transport_stopped(wifi)) + return -EIO; + drain(wifi); + if (wifi->scans_done != done) + return 0; + mutex_unlock(&wifi->lock); + usleep_range(1000, 2000); + mutex_lock(&wifi->lock); + } while (time_before(jiffies, deadline)); + if (scan_transport_stopped(wifi)) + return -EIO; + drain(wifi); + return wifi->scans_done != done ? 0 : -ETIMEDOUT; +} + +static int scan_stop_chunk(struct centauri_wifi *wifi, u32 done) +{ + int ret; + + if (scan_transport_stopped(wifi)) + return -EIO; + ret = command(wifi, 65537, NULL, 0); + if (wifi->scans_done != done) + return 0; + if (ret == -EREMOTEIO && wifi->reply_status == 342) + return 0; + if (ret) + return ret; + return scan_wait_stop(wifi, done); +} + static void scan_worker(struct work_struct *work) { struct centauri_wifi *wifi = container_of(work, struct centauri_wifi, scan_work); @@ -934,6 +1007,14 @@ static void scan_worker(struct work_struct *work) unsigned long deadline, progress; bool stopped = false, refused = false; + if (scan_transport_stopped(wifi)) { + ret = -EIO; + break; + } + if (READ_ONCE(wifi->scan_abort)) { + ret = -ECANCELED; + break; + } scan_size = build_scan(wifi, chunk, scan); ret = command(wifi, 65551, scan, scan_size); if (ret) @@ -953,17 +1034,21 @@ static void scan_worker(struct work_struct *work) msecs_to_jiffies(max(8000U, count * 2 * SCAN_PASSIVE_DWELL_MS + 2000)); progress = jiffies; do { - drain(wifi); - if (readl(wifi->a.bar + 8) != 2) { + if (scan_transport_stopped(wifi)) { + if (!READ_ONCE(wifi->stopping) && !READ_ONCE(wifi->transport_paused) && + readl(wifi->a.bar + 8) != 2) + centauri_recovery_request(wifi->control, "scan: Alpha stage"); ret = -EIO; break; } + drain(wifi); if (wifi->scans_done != done) break; if (READ_ONCE(wifi->scan_abort)) { - if (!stopped) - command(wifi, 65537, NULL, 0); - ret = -ECANCELED; + int stop_ret = stopped ? scan_wait_stop(wifi, done) : + scan_stop_chunk(wifi, done); + + ret = stop_ret == -EIO ? -EIO : -ECANCELED; break; } if (wifi->channels_seen != seen) { @@ -989,18 +1074,28 @@ static void scan_worker(struct work_struct *work) /* The stop's own scan event ends the wait. */ deadline = jiffies + msecs_to_jiffies(1000); } + mutex_unlock(&wifi->lock); usleep_range(1000, 2000); + mutex_lock(&wifi->lock); } while (time_before(jiffies, deadline)); if (!ret && !refused && wifi->scans_done == done) { - dev_warn(&wifi->control->pdev->dev, - "Wi-Fi scan chunk %u: %u of %u channels, no scan event%s\n", chunk, - wifi->channels_seen - channels, count, - stopped ? " after the stop" : ""); - if (!stopped) - command(wifi, 65537, NULL, 0); + if (scan_transport_stopped(wifi)) { + ret = -EIO; + } else { + drain(wifi); + if (wifi->scans_done == done) { + dev_warn(&wifi->control->pdev->dev, + "Wi-Fi scan chunk %u: %u of %u channels, no scan event%s\n", + chunk, wifi->channels_seen - channels, count, + stopped ? " after the stop" : ""); + ret = stopped ? -ETIMEDOUT : + scan_stop_chunk(wifi, done); + } + } } } - info.aborted = !!ret; + info.aborted = !!ret || READ_ONCE(wifi->scan_abort) || + READ_ONCE(wifi->stopping); request = wifi->scan_request; wifi->scan_request = NULL; mutex_unlock(&wifi->lock); @@ -1246,6 +1341,9 @@ static void connect_worker(struct work_struct *work) } } host_setup_commands(wifi); + drain(wifi); + wifi->connect_event = false; + wifi->disconnect_event = false; slot = wifi->command_head; ret = command(wifi, 131072, wifi->connect_payload, wifi->connect_size); command_status = wifi->reply_status; @@ -1280,9 +1378,10 @@ static void connect_worker(struct work_struct *work) probe_ret = query_station_stats(wifi); dev_info(&wifi->control->pdev->dev, "connection counters: complete=%d rc=%d valid=%d length=%u\n", - wifi->connect_event, probe_ret, wifi->station_stats_valid, wifi->stats_length); + wifi->connect_event, probe_ret, wifi->station_stats_valid, + wifi->station_stats_len); if (!probe_ret && wifi->station_stats_valid) - for (i = 0; i < wifi->stats_length; i += 4) { + for (i = 0; i < wifi->station_stats_len; i += 4) { u32 value = get_unaligned_le32(wifi->station_stats + i); if (value) @@ -2276,6 +2375,7 @@ static int query_station_stats(struct centauri_wifi *wifi) put_unaligned_le16(363, payload + 9); put_unaligned_le16(9, payload + 11); wifi->station_stats_valid = false; + wifi->station_stats_len = 0; wifi->stats_reply_size = wifi->stats_tag = wifi->stats_length = 0; ret = wifi->configured ? command(wifi, 0xb0001, payload, sizeof(payload)) : -ENETDOWN; if (!ret) { @@ -2293,10 +2393,11 @@ static int station_stats_show(struct seq_file *seq, void *unused) mutex_lock(&wifi->lock); ret = query_station_stats(wifi); - seq_printf(seq, "rc=%d valid=%d size=%u tag=%#x length=%u\n", ret, - wifi->station_stats_valid, wifi->stats_reply_size, wifi->stats_tag, wifi->stats_length); + seq_printf(seq, "rc=%d valid=%d size=%u tag=%#x length=%u counters=%u\n", ret, + wifi->station_stats_valid, wifi->stats_reply_size, wifi->stats_tag, + wifi->stats_length, wifi->station_stats_len); if (!ret && wifi->station_stats_valid) - for (i = 0; i < wifi->stats_length; i += 4) { + for (i = 0; i < wifi->station_stats_len; i += 4) { u32 value = get_unaligned_le32(wifi->station_stats + i); if (value) @@ -2814,3 +2915,7 @@ void centauri_wifi_unregister(struct centauri *c) kfree(wifi); c->wifi = NULL; } + +#if IS_ENABLED(CONFIG_APPLE_CENTAURI_KUNIT_TEST) +#include "centauri_wifi_test.c" +#endif diff --git a/drivers/net/wireless/apple/centauri/centauri_wifi_test.c b/drivers/net/wireless/apple/centauri/centauri_wifi_test.c new file mode 100644 index 00000000000000..9602e219a61e3e --- /dev/null +++ b/drivers/net/wireless/apple/centauri/centauri_wifi_test.c @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Included by centauri_wifi.c to exercise the statistics reply handler. */ +#include + +/* A reply to command 0xb0001 carrying one TLV of @length bytes. */ +static void centauri_stats_reply(struct centauri_wifi *wifi, u8 *packet, + u16 size, u16 tag, u16 length) +{ + memset(packet, 0, size); + put_unaligned_le16(tag, packet + 24); + put_unaligned_le16(length, packet + 26); + record_stats_reply(wifi, packet, size, 0); +} + +static void centauri_station_stats_len_test(struct kunit *test) +{ + struct centauri_wifi *wifi = kunit_kzalloc(test, sizeof(*wifi), GFP_KERNEL); + u8 *packet = kunit_kzalloc(test, BUFFER_SIZE, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, wifi); + KUNIT_ASSERT_NOT_NULL(test, packet); + + centauri_stats_reply(wifi, packet, 28 + 752, 0xf928, 752); + KUNIT_ASSERT_TRUE(test, wifi->station_stats_valid); + KUNIT_EXPECT_EQ(test, wifi->station_stats_len, 752); + + /* A later reply with another record leaves the counters as they were. */ + centauri_stats_reply(wifi, packet, 28, 0xf921, U16_MAX); + KUNIT_EXPECT_EQ(test, wifi->stats_length, U16_MAX); + KUNIT_EXPECT_TRUE(test, wifi->station_stats_valid); + KUNIT_EXPECT_EQ(test, wifi->station_stats_len, 752); + KUNIT_EXPECT_LE(test, wifi->station_stats_len, sizeof(wifi->station_stats)); + + centauri_stats_reply(wifi, packet, 28 + 888, 0xf928, 888); + KUNIT_EXPECT_EQ(test, wifi->station_stats_len, 888); + + /* An unsupported counter record length is not recorded. */ + centauri_stats_reply(wifi, packet, 28 + 900, 0xf928, 900); + KUNIT_EXPECT_EQ(test, wifi->station_stats_len, 888); +} + +static struct kunit_case centauri_wifi_cases[] = { + KUNIT_CASE(centauri_station_stats_len_test), + {} +}; + +static struct kunit_suite centauri_wifi_suite = { + .name = "apple-centauri-wifi", + .test_cases = centauri_wifi_cases, +}; + +kunit_test_suite(centauri_wifi_suite); diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_ipc.c b/drivers/net/wireless/apple/centauri/t6050/centauri_ipc.c index 0210363889d024..b4b1cc5941601d 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_ipc.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_ipc.c @@ -191,7 +191,7 @@ static int message(struct cen_context *ctx, void __iomem *doorbell, { u16 head = ctx->message_head; u8 *descriptor; - u16 tail; + __le16 tail; int ret; if (head >= 15 || !length || length > 512) @@ -232,7 +232,7 @@ static int cchi_init(struct centauri_t6050 *c) { struct centauri_t6050_ipc *ipc = c->ipc; u8 config[4] = {9, 0, 0xff, 0xff}, *entry; - u16 tail; + __le16 tail; int i, ret; ipc->cchi_rx = buffer_alloc(c, 0, SZ_32K); @@ -378,7 +378,8 @@ static int enumerate_functions(struct centauri_t6050 *c) return 0; } -static int centauri_t6050_start_ipc_locked(struct centauri_t6050 *c) +static int centauri_t6050_start_ipc_locked(struct centauri_t6050 *c, + struct pci_dev **beta) { struct centauri_t6050_ipc *ipc; u32 stage; @@ -450,9 +451,7 @@ static int centauri_t6050_start_ipc_locked(struct centauri_t6050 *c) /* Publish usable shared firmware before the Beta consumer probes. */ smp_store_release(&c->ready, true); - ret = device_attach(&ipc->function[2]->dev); - if (ret < 0) - dev_warn(&c->pdev->dev, "Beta driver attachment failed: %d\n", ret); + *beta = pci_dev_get(ipc->function[2]); return 0; failed: dev_err(&c->pdev->dev, "IPC bootstrap failed: %d (Control stage=%#x)\n", @@ -468,15 +467,31 @@ static int centauri_t6050_start_ipc_locked(struct centauri_t6050 *c) return ret; } -int centauri_t6050_start_ipc(struct centauri_t6050 *c) +/* On success *beta may hold a reference to the Beta function, for centauri_t6050_attach_beta(). */ +int centauri_t6050_start_ipc(struct centauri_t6050 *c, struct pci_dev **beta) { int ret; if (!pci_trylock_rescan_remove()) return -EAGAIN; - ret = READ_ONCE(c->removing) ? -ECANCELED : centauri_t6050_start_ipc_locked(c); + ret = READ_ONCE(c->removing) ? -ECANCELED : + centauri_t6050_start_ipc_locked(c, beta); pci_unlock_rescan_remove(); - return ret; + return *beta ? 0 : ret; +} + +/* + * Under neither the rescan lock nor boot_lock: the Beta driver's probe + * registers a PM notifier, a suspend's notifiers wait for a rescan, and a + * rescan's holder (the rewake) takes boot_lock. + */ +void centauri_t6050_attach_beta(struct centauri_t6050 *c, struct pci_dev *beta) +{ + int ret = device_attach(&beta->dev); + + if (ret < 0) + dev_warn(&c->pdev->dev, "Beta driver attachment failed: %d\n", ret); + pci_dev_put(beta); } void centauri_t6050_free_ipc(struct centauri_t6050 *c) diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c b/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c index 5932cc65720c45..2586efa6b6d6fb 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c @@ -401,7 +401,8 @@ static int centauri_t6050_port_cycle(struct pci_dev *endpoint) if (ret) goto stopped; ret = pcibios_err_to_errno(pci_write_config_word(endpoint, pm + PCI_PM_CTRL, - (pmctrl & ~PCI_PM_CTRL_STATE_MASK) | PCI_D3hot | PCI_PM_CTRL_PME_ENABLE)); + (pmctrl & ~PCI_PM_CTRL_STATE_MASK) | (__force u16)PCI_D3hot | + PCI_PM_CTRL_PME_ENABLE)); if (ret) goto stopped; usleep_range(10000, 11000); @@ -454,6 +455,7 @@ static int centauri_t6050_cycle(struct centauri_t6050 *c) static void centauri_t6050_boot_worker(struct work_struct *work) { struct centauri_t6050 *c = container_of(to_delayed_work(work), struct centauri_t6050, boot_work); + struct pci_dev *beta = NULL; bool retry = false; int ret; @@ -472,7 +474,7 @@ static void centauri_t6050_boot_worker(struct work_struct *work) c->boot_phase = CEN_BOOT_IPC; break; case CEN_BOOT_IPC: - ret = centauri_t6050_start_ipc(c); + ret = centauri_t6050_start_ipc(c, &beta); if (!ret) c->boot_phase = CEN_BOOT_READY; break; @@ -495,6 +497,8 @@ static void centauri_t6050_boot_worker(struct work_struct *work) if (READ_ONCE(c->removing)) c->boot_phase = CEN_BOOT_STOPPED; mutex_unlock(&c->boot_lock); + if (beta) + centauri_t6050_attach_beta(c, beta); if (retry && !READ_ONCE(c->removing)) queue_delayed_work(system_long_wq, &c->boot_work, msecs_to_jiffies(20)); } @@ -598,10 +602,10 @@ static void centauri_t6050_remove(struct pci_dev *pdev) } /* - * On a healthy firmware sleep, Beta (fn 2), Alpha (fn 1), and Control (fn 0) enter ACIPC - * host-sleep, save PCI config state, enter D3hot with PME_En, and ask pcie-apple to skip - * the wake warm reset so the N1 firmware, Bluetooth, and (when armed) Wi-Fi association - * survive across PERST#. + * On a healthy firmware sleep (WoWLAN-armed or unassociated), Beta (fn 2), Alpha (fn 1), + * and Control (fn 0) enter ACIPC host-sleep, save PCI config state, enter D3hot (with + * PME_En only when wake is armed), and ask pcie-apple to skip the wake warm reset so the + * N1 firmware, Bluetooth, and (when armed) Wi-Fi association survive across PERST#. * * If any function fails host-sleep or wake, or firmware is unhealthy, the driver falls back * to teardown and warm-reset recovery: @@ -763,8 +767,22 @@ static bool centauri_t6050_domain_fence(struct centauri_t6050_rewake *rw) pci_clear_master(fn[i]); } for (i = 0; i < 3; i++) { - if (fn[i] && !centauri_t6050_stop_dma(fn[i])) + bool fn_stopped = !fn[i] || centauri_t6050_stop_dma(fn[i]); + + if (!fn_stopped) stopped = false; + /* + * Refresh any keep-alive PCI state saved before Control fell + * back to teardown so an aborted suspend cannot restore Bus + * Master or the old header onto a quiesced function whose DMA + * arena was freed. Never save an unreadable/gone function + * (which would snapshot 0xffff); clearing state_saved hands + * suspend_noirq state save and power-state selection back to + * the PCI core. + */ + if (fn[i] && i > 0 && fn[i]->state_saved && + (!fn_stopped || pci_save_state(fn[i]))) + fn[i]->state_saved = false; pci_dev_put(fn[i]); } return stopped; @@ -1021,16 +1039,18 @@ void apple_centauri_sleep_mark_fallback(struct pci_dev *fn) } EXPORT_SYMBOL_GPL(apple_centauri_sleep_mark_fallback); -static void centauri_t6050_set_d3hot(struct pci_dev *pdev) +static void centauri_t6050_set_d3hot(struct pci_dev *pdev, bool pme_enable) { u16 pmctrl; if (!pdev || !pdev->pm_cap) return; if (!pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmctrl)) { - pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, - (pmctrl & ~PCI_PM_CTRL_STATE_MASK) | - PCI_D3hot | PCI_PM_CTRL_PME_ENABLE); + pmctrl &= ~(PCI_PM_CTRL_STATE_MASK | PCI_PM_CTRL_PME_ENABLE); + pmctrl |= (__force u16)PCI_D3hot; + if (pme_enable) + pmctrl |= PCI_PM_CTRL_PME_ENABLE; + pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, pmctrl); mdelay(pdev->d3hot_delay); } } @@ -1042,7 +1062,7 @@ static void centauri_t6050_ensure_d0(struct pci_dev *pdev) if (!pdev || !pdev->pm_cap) return; if (!pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmctrl) && - (pmctrl & PCI_PM_CTRL_STATE_MASK) != PCI_D0) { + (pmctrl & PCI_PM_CTRL_STATE_MASK) != (__force u16)PCI_D0) { pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, pmctrl & ~PCI_PM_CTRL_STATE_MASK); mdelay(pdev->d3hot_delay); @@ -1127,19 +1147,26 @@ static int centauri_t6050_suspend(struct device *dev) c->firmware_kept = false; c->control_sleep_sent = false; + c->keep_alive_pme = false; if (!beta_fallback && c->boot_phase == CEN_BOOT_READY && c->ipc && c->wifi && !centauri_t6050_wifi_pm_error(c) && + !centauri_t6050_wifi_pm_disconnected(c) && readl(c->bar + 0x8000) == 2 && readl(c->bar + 0x8050) == 2) { + bool wifi_sleep_sent = false; + int unwind_err = 0, wake_ret; u32 id0 = 0, id1 = 0; fn1 = centauri_t6050_ipc_alpha_dev(c); if (!fn1 || pci_read_config_dword(pdev, PCI_VENDOR_ID, &id0) || pci_read_config_dword(fn1, PCI_VENDOR_ID, &id1) || (id0 & 0xffff) != pdev->vendor || (id1 & 0xffff) != fn1->vendor || - id0 == ~0U || id1 == ~0U) + id0 == ~0U || id1 == ~0U) { ret = -ENODEV; - else + } else { ret = centauri_t6050_wifi_suspend(c); + if (!ret) + wifi_sleep_sent = true; + } if (!ret) { ret = centauri_t6050_ipc_control_sleep(c, true); if (!ret) @@ -1155,13 +1182,38 @@ static int centauri_t6050_suspend(struct device *dev) centauri_t6050_save_memswap(pdev, c->saved_memswap[0]); centauri_t6050_save_memswap(fn1, c->saved_memswap[1]); apple_pcie_t6050_sleep_keep_alive(pdev->bus->self); + c->keep_alive_pme = centauri_t6050_wifi_wowlan_armed(c); c->firmware_kept = true; dev_dbg(dev, "N1 kept alive for firmware sleep\n"); return 0; } dev_warn(dev, "N1 keep-alive suspend failed (%d); falling back to warm-reset sleep\n", ret); - c->control_sleep_sent = false; + if (c->control_sleep_sent) { + wake_ret = centauri_t6050_ipc_control_sleep(c, false); + if (wake_ret) { + dev_warn(dev, + "Control ACIPC host wake failed during fallback (%d)\n", + wake_ret); + unwind_err = wake_ret; + } + c->control_sleep_sent = false; + } + if (wifi_sleep_sent) { + wake_ret = centauri_t6050_wifi_resume(c); + if (wake_ret) { + dev_warn(dev, + "Alpha host wake failed during fallback (%d)\n", + wake_ret); + if (!unwind_err) + unwind_err = wake_ret; + } + } + if (unwind_err) { + centauri_t6050_wifi_mark_failed(c); + /* Also covers an aborted suspend where resume/rewake may not run. */ + apple_centauri_sleep_recovery_needed(pdev, unwind_err); + } } ret = centauri_t6050_quiesce(c); @@ -1188,8 +1240,8 @@ static int centauri_t6050_suspend_noirq(struct device *dev) if (!c->firmware_kept || !pm_suspend_via_firmware()) return 0; fn1 = centauri_t6050_ipc_alpha_dev(c); - centauri_t6050_set_d3hot(fn1); - centauri_t6050_set_d3hot(pdev); + centauri_t6050_set_d3hot(fn1, c->keep_alive_pme); + centauri_t6050_set_d3hot(pdev, c->keep_alive_pme); return 0; } diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_t6050.h b/drivers/net/wireless/apple/centauri/t6050/centauri_t6050.h index 17a92ca333985c..6659e601c0603c 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_t6050.h +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_t6050.h @@ -62,6 +62,7 @@ struct centauri_t6050 { /* Kept alive across a firmware sleep via ACIPC host-sleep */ bool firmware_kept; bool control_sleep_sent; + bool keep_alive_pme; u32 saved_pci_id[2]; u32 saved_memswap[2][3]; struct centauri_t6050_ipc *ipc; @@ -72,7 +73,8 @@ int centauri_t6050_request_irqs(struct centauri_t6050_irqs *irqs, struct pci_dev unsigned int count, irq_handler_t handler, void *data); void centauri_t6050_free_irqs(struct centauri_t6050_irqs *irqs); -int centauri_t6050_start_ipc(struct centauri_t6050 *c); +int centauri_t6050_start_ipc(struct centauri_t6050 *c, struct pci_dev **beta); +void centauri_t6050_attach_beta(struct centauri_t6050 *c, struct pci_dev *beta); void centauri_t6050_free_ipc(struct centauri_t6050 *c); void centauri_t6050_release_ipc(struct centauri_t6050_ipc *ipc); bool centauri_t6050_ipc_fenced(struct centauri_t6050_ipc *ipc); @@ -88,6 +90,9 @@ int centauri_t6050_wifi_register(struct centauri_t6050 *c); void centauri_t6050_wifi_unregister(struct centauri_t6050 *c); void centauri_t6050_wifi_pm_prepare(struct centauri_t6050 *c); int centauri_t6050_wifi_pm_error(struct centauri_t6050 *c); +bool centauri_t6050_wifi_pm_disconnected(struct centauri_t6050 *c); +bool centauri_t6050_wifi_wowlan_armed(struct centauri_t6050 *c); +void centauri_t6050_wifi_mark_failed(struct centauri_t6050 *c); void centauri_t6050_wifi_pm_complete(struct centauri_t6050 *c); int centauri_t6050_wifi_suspend(struct centauri_t6050 *c); int centauri_t6050_wifi_resume(struct centauri_t6050 *c); @@ -113,6 +118,20 @@ static inline int centauri_t6050_wifi_pm_error(struct centauri_t6050 *c) return 0; } +static inline bool centauri_t6050_wifi_pm_disconnected(struct centauri_t6050 *c) +{ + return false; +} + +static inline bool centauri_t6050_wifi_wowlan_armed(struct centauri_t6050 *c) +{ + return false; +} + +static inline void centauri_t6050_wifi_mark_failed(struct centauri_t6050 *c) +{ +} + static inline void centauri_t6050_wifi_pm_complete(struct centauri_t6050 *c) { } diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index 61a421a58ec206..7e338ac938a8a1 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -7,10 +7,12 @@ #include #include #include +#include #include #include #include #include +#include #include "centauri_t6050.h" #define CR_BASE 0x100000 @@ -26,7 +28,22 @@ #define DATA_TX_BUFFER (SZ_16M + SZ_8M) #define DATA_RX_SLOTS 2048 #define DATA_TX_SLOTS 2048 -#define DATA_TX_QUEUE_LIMIT DATA_TX_SLOTS +/* + * Frames waiting for a ring slot, and frames the firmware holds until it + * reports them sent. Both queues are first-in first-out and shared by every + * flow, so what does not fit waits in the qdisc instead, where it is + * scheduled per flow. 512 frames are about 25 ms at ~240 Mbit/s; the ring + * itself holds 2047 (about 100 ms). + */ +#define DATA_TX_QUEUE_LIMIT 128 +#define DATA_TX_INFLIGHT_MAX 512 +/* + * TCP sizes its bursts, its small-queue budget and (BBR) the extra + * congestion window it allows for them at 1 ms of its pacing rate (shift + * 10). Aggregation on a shared Wi-Fi channel wants more: mac80211 sets 8 ms + * (shift 7) on every socket it transmits for, and so does this driver. + */ +#define DATA_TX_PACING_SHIFT 7 static_assert(DATA_TX_BUFFER >= CEN_ALPHA_SCRATCH_OFFSET + CEN_ALPHA_SCRATCH_SIZE); @@ -72,12 +89,15 @@ struct centauri_t6050_wifi { size_t reply_capacity, reply_size; bool stopping, command_failed; bool tx_paused, transport_paused, host_sleep_sent, transport_sleep_sent; + bool regulatory_deferred; + u8 country_deferred[3]; + bool host_events_fallback_logged; bool scan_abort, connect_abort; u8 scan_sequence; bool connecting, connected, connect_event, disconnect_event; bool disconnect_pending; /* PM callbacks and the normal disconnect producer serialize on lock. */ - bool pm_prepared; + bool pm_prepared, pm_wowlan_armed; struct centauri_wifi_disconnect_receipt pm_disconnect; u16 connect_status, scan_status, disconnect_status; struct ieee80211_channel *connect_channel; @@ -90,6 +110,8 @@ struct centauri_t6050_wifi { bool data_tx_busy[DATA_TX_SLOTS]; u32 data_tx_submitted, data_tx_completed, data_tx_failed; u32 data_tx_coalesced, data_tx_bad; + u32 data_tx_capped, data_tx_cap_bypassed; + unsigned long data_tx_completed_at; s8 station_signal; bool station_signal_valid; unsigned long station_signal_at, connected_at; @@ -111,6 +133,9 @@ struct centauri_t6050_wifi { u8 avoid_ssid[IEEE80211_MAX_SSID_LEN]; size_t avoid_ssid_len; unsigned long avoid_until; + /* Received frames wait here for rx_napi, whose poll hands them to GRO. */ + struct napi_struct rx_napi; + struct sk_buff_head rx_gro_queue; }; static int query_link_status(struct centauri_t6050_wifi *wifi); @@ -253,10 +278,131 @@ static bool avoided(struct centauri_t6050_wifi *wifi, !memcmp(ssid, wifi->avoid_ssid, ssid_len); } +/* + * The skip-th entry of the avoided network's 6 GHz BSSes that may go, and how + * many there are. An entry may not go when its set holds @keep, or a BSS of + * @cur_ssid: the network being joined or used, when that is not the avoided + * one. + */ +struct avoid_find { + struct centauri_t6050_wifi *wifi; + const u8 *keep, *cur_ssid; + size_t cur_ssid_len; + unsigned int skip, count; + u8 bssid[ETH_ALEN]; + struct ieee80211_channel *channel; +}; + +/* Whether @bss is one to keep. Under cfg80211's BSS lock. */ +static bool avoid_keep_bss(const struct avoid_find *find, + struct cfg80211_bss *bss) +{ + const struct element *ssid; + bool same; + + if (find->keep && ether_addr_equal(bss->bssid, find->keep)) + return true; + if (!find->cur_ssid) + return false; + rcu_read_lock(); + ssid = ieee80211_bss_get_elem(bss, WLAN_EID_SSID); + same = ssid && ssid->datalen == find->cur_ssid_len && + !memcmp(ssid->data, find->cur_ssid, find->cur_ssid_len); + rcu_read_unlock(); + return same; +} + +/* + * Whether @bss's set holds a BSS to keep: the beacon's own BSS and those of + * its multiple-BSSID element, which cfg80211 unlinks together. + */ +static bool avoid_keep_set(const struct avoid_find *find, + struct cfg80211_bss *bss) +{ + struct cfg80211_bss *set = bss->transmitted_bss ?: bss, *member; + + if (avoid_keep_bss(find, set)) + return true; + list_for_each_entry(member, &set->nontrans_list, nontrans_list) + if (avoid_keep_bss(find, member)) + return true; + return false; +} + +/* Called for every BSS entry, under cfg80211's BSS lock. */ +static void avoid_find_one(struct wiphy *wiphy, struct cfg80211_bss *bss, + void *data) +{ + struct avoid_find *find = data; + const struct element *ssid; + bool same; + + rcu_read_lock(); + ssid = ieee80211_bss_get_elem(bss, WLAN_EID_SSID); + same = ssid && avoided(find->wifi, bss->channel, ssid->data, + ssid->datalen); + rcu_read_unlock(); + if (!same || avoid_keep_set(find, bss)) + return; + if (find->count++ == find->skip) { + ether_addr_copy(find->bssid, bss->bssid); + find->channel = bss->channel; + } +} + +/* + * Unlink the avoided network's 6 GHz BSSes but @keep. cfg80211 keeps the + * networks one beacon describes, its own and those of its multiple-BSSID + * element, as one set, and unlinking any of them unlinks the set. So an + * entry whose set holds @keep, or a BSS of the network being joined or used + * (unless that is the avoided one), stays, and the others go with their + * sets. The iterator may not unlink, so each pass looks up one entry and + * unlinks it; one that cfg80211 does not return or unlink is passed over, + * with one more walk to find the entry after it. Each entry the first walk + * found gets one pass. + * + * This runs after every 6 GHz beacon while the window is open: one walk of + * the whole BSS list under cfg80211's BSS lock, with bottom halves off, plus + * one more walk for each entry it unlinks or passes over. + */ +static void avoid_unlink(struct centauri_t6050_wifi *wifi, const u8 *keep) +{ + struct avoid_find find = { .wifi = wifi, .keep = keep }; + struct cfg80211_bss *bss; + unsigned int passes, count; + + if ((wifi->connecting || wifi->connected) && wifi->ssid_len && + !(wifi->ssid_len == wifi->avoid_ssid_len && + !memcmp(wifi->ssid, wifi->avoid_ssid, wifi->ssid_len))) { + find.cur_ssid = wifi->ssid; + find.cur_ssid_len = wifi->ssid_len; + } + cfg80211_bss_iter(wifi->wiphy, NULL, avoid_find_one, &find); + for (passes = find.count; passes && find.skip < find.count; passes--) { + count = find.count; + bss = cfg80211_get_bss(wifi->wiphy, find.channel, find.bssid, + wifi->avoid_ssid, wifi->avoid_ssid_len, + IEEE80211_BSS_TYPE_ANY, + IEEE80211_PRIVACY_ANY); + if (bss) { + cfg80211_unlink_bss(wifi->wiphy, bss); + cfg80211_put_bss(wifi->wiphy, bss); + } + find.count = 0; + cfg80211_bss_iter(wifi->wiphy, NULL, avoid_find_one, &find); + if (find.count < count) + continue; + /* Not unlinked: pass it over and look up the entry after it. */ + find.skip++; + find.count = 0; + cfg80211_bss_iter(wifi->wiphy, NULL, avoid_find_one, &find); + } +} + static void report_beacon(struct centauri_t6050_wifi *wifi, const u8 *payload, size_t size) { - const u8 *frame, *ie, *end, *ssid = NULL; + const u8 *frame, *ie, *end; struct ieee80211_channel *channel; struct cfg80211_bss *bss; u16 frame_size; @@ -274,8 +420,6 @@ static void report_beacon(struct centauri_t6050_wifi *wifi, const u8 *payload, end = frame + frame_size; for (ie = frame + 36; ie + 2 <= end && ie + 2 + ie[1] <= end; ie += 2 + ie[1]) { - if (ie[0] == WLAN_EID_SSID && !ssid) - ssid = ie; if ((ie[0] == WLAN_EID_DS_PARAMS || ie[0] == WLAN_EID_HT_OPERATION) && ie[1]) { @@ -300,22 +444,20 @@ static void report_beacon(struct centauri_t6050_wifi *wifi, const u8 *payload, return; frequency = ieee80211_channel_to_frequency(number, band); channel = ieee80211_get_channel(wifi->wiphy, frequency); - if (!channel) + if (!channel || channel->flags & IEEE80211_CHAN_DISABLED) return; signal = max_t(s8, payload[0x16], payload[0x17]); if (signal >= 0 || signal < -127) signal = -95; - if (ssid && avoided(wifi, channel, ssid + 2, ssid[1]) && - !((wifi->connecting || wifi->connected) && - ether_addr_equal(((struct ieee80211_mgmt *)frame)->bssid, - wifi->bssid))) - return; bss = cfg80211_inform_bss_frame(wifi->wiphy, channel, (struct ieee80211_mgmt *)frame, frame_size, signal * 100, GFP_KERNEL); if (bss) { wifi->beacons_seen++; cfg80211_put_bss(wifi->wiphy, bss); + if (channel->band == NL80211_BAND_6GHZ && wifi->avoid_valid) + avoid_unlink(wifi, wifi->connecting || wifi->connected ? + wifi->bssid : NULL); } } @@ -353,10 +495,30 @@ static bool data_rx_frame(const u8 *packet, unsigned int capacity, return *offset <= capacity && *frame_length <= capacity - *offset; } +static int rx_poll(struct napi_struct *napi, int budget) +{ + struct centauri_t6050_wifi *wifi = + container_of(napi, struct centauri_t6050_wifi, rx_napi); + struct sk_buff *skb; + int done = 0; + + while (done < budget && (skb = skb_dequeue(&wifi->rx_gro_queue))) { + napi_gro_receive(napi, skb); + done++; + } + if (done < budget && napi_complete_done(napi, done) && + !skb_queue_empty(&wifi->rx_gro_queue)) + napi_schedule(napi); + return done; +} + static void drain_data_rx(struct centauri_t6050_wifi *wifi) { u16 head, tail, post; unsigned int processed = 0; + struct sk_buff_head frames; + + __skb_queue_head_init(&frames); if (!(wifi->data_rings_open & BIT(4)) || readl(wifi->a.bar + 8) != 2) return; @@ -408,7 +570,7 @@ static void drain_data_rx(struct centauri_t6050_wifi *wifi) skb->ip_summed = CHECKSUM_NONE; wifi->netdev->stats.rx_packets++; wifi->netdev->stats.rx_bytes += frame_length; - netif_rx(skb); + __skb_queue_tail(&frames, skb); } else { wifi->netdev->stats.rx_dropped++; } @@ -431,6 +593,19 @@ static void drain_data_rx(struct centauri_t6050_wifi *wifi) dma_wmb(); writel(1, wifi->a.bar + 0x1050); } + /* + * Hand the batch to the NAPI context, so that GRO coalesces a flow's + * segments (and TCP acknowledges each coalesced run once, not every + * other segment) before they reach the stack. + */ + if (!skb_queue_empty(&frames)) { + spin_lock_bh(&wifi->rx_gro_queue.lock); + skb_queue_splice_tail_init(&frames, &wifi->rx_gro_queue); + spin_unlock_bh(&wifi->rx_gro_queue.lock); + local_bh_disable(); + napi_schedule(&wifi->rx_napi); + local_bh_enable(); + } } static bool data_tx_completion_span(u16 cookie, u16 wire_count, u8 flags, @@ -486,6 +661,7 @@ static void drain_data_tx(struct centauri_t6050_wifi *wifi) } if (count > 1) wifi->data_tx_coalesced++; + wifi->data_tx_completed_at = jiffies; for (i = 0; i < count; i++) { unsigned int slot = (first + i) % DATA_TX_SLOTS; @@ -515,9 +691,28 @@ static void drain_data_tx(struct centauri_t6050_wifi *wifi) u8 *descriptor = wifi->a.window + 0x540000 + post * 32; struct sk_buff *skb; u64 metadata = 6ULL << 27; + u32 inflight = wifi->data_tx_submitted - wifi->data_tx_completed; if (wifi->data_tx_busy[post] || next == index_read(wifi, 1, 25)) break; + /* + * Keep at most DATA_TX_INFLIGHT_MAX frames with the firmware. A + * completion that never comes would hold its frame's place for + * good, so the cap gives way once no completion has arrived for + * half a second (beacon reports keep this path running). + */ + if (inflight >= DATA_TX_INFLIGHT_MAX && + !skb_queue_empty(&wifi->data_tx_queue)) { + if (time_before(jiffies, + wifi->data_tx_completed_at + HZ / 2)) { + wifi->data_tx_capped++; + break; + } + if (!wifi->data_tx_cap_bypassed++) + dev_warn(&wifi->control->pdev->dev, + "Wi-Fi TX: no completion for %u in-flight frames; posting past the cap\n", + inflight); + } skb = skb_dequeue(&wifi->data_tx_queue); if (!skb) break; @@ -535,10 +730,12 @@ static void drain_data_tx(struct centauri_t6050_wifi *wifi) metadata |= 4ULL << 15; put_unaligned_le64(metadata, descriptor + 16); put_unaligned_le64(2000000, descriptor + 24); + if (wifi->data_tx_submitted == wifi->data_tx_completed) + wifi->data_tx_completed_at = jiffies; wifi->data_tx_length[post] = skb->len; wifi->data_tx_busy[post] = true; wifi->data_tx_submitted++; - dev_kfree_skb_any(skb); + dev_consume_skb_any(skb); post = next; posted = true; } @@ -685,7 +882,7 @@ static int command_reply(struct centauri_t6050_wifi *wifi, u32 id, const void *payload, size_t size, void *reply, size_t *reply_size, bool *submitted) { - u16 slot = wifi->command_head, sequence = ++wifi->sequence; + u16 slot = wifi->command_head, sequence; int ret; u32 stage; u8 *packet, *descriptor; @@ -693,6 +890,10 @@ static int command_reply(struct centauri_t6050_wifi *wifi, u32 id, if (submitted) *submitted = false; + /* The PCI link can go down after the host-sleep command. */ + if (wifi->host_sleep_sent) + return -EHOSTDOWN; + sequence = ++wifi->sequence; if (wifi->command_failed) return -EIO; if (size > BUFFER_SIZE - 24) @@ -895,6 +1096,18 @@ static void channels_apply(struct centauri_t6050_wifi *wifi) counted[0], counted[1], counted[2], list[0]); } +static void country_set(struct centauri_t6050_wifi *wifi, const u8 country[3]) +{ + int ret = command(wifi, 9, country, 3); + + if (ret) + dev_err(&wifi->control->pdev->dev, + "firmware country update failed: %d\n", ret); + else + firmware_report(wifi, 19, wifi->hw_channels, + &wifi->hw_channels_blob); +} + /* * 6 GHz needs HE: the station's HE capabilities element as the firmware * reports it (capabilities TLV 0xff), with the 6 GHz band capabilities taken @@ -1044,6 +1257,44 @@ static int radio_start(struct centauri_t6050_wifi *wifi) #define SCAN_ACTIVE_MIN_MS 40 #define SCAN_LISTEN_MS 110 +static bool scan_transport_stopped(struct centauri_t6050_wifi *wifi) +{ + return READ_ONCE(wifi->stopping) || wifi->command_failed || + wifi->host_sleep_sent || readl(wifi->a.bar + 8) != 2; +} + +static int scan_stop_chunk(struct centauri_t6050_wifi *wifi, u32 done) +{ + unsigned long deadline; + int ret; + + lockdep_assert_held(&wifi->lock); + if (scan_transport_stopped(wifi)) + return -EIO; + ret = command(wifi, 65537, NULL, 0); + if (wifi->scans_done != done) + return 0; + if (ret == -EREMOTEIO && wifi->reply_status == 342) + return 0; + if (ret) + return ret; + deadline = jiffies + msecs_to_jiffies(1000); + do { + if (scan_transport_stopped(wifi)) + return -EIO; + drain(wifi); + if (wifi->scans_done != done) + return 0; + mutex_unlock(&wifi->lock); + usleep_range(1000, 2000); + mutex_lock(&wifi->lock); + } while (time_before(jiffies, deadline)); + if (scan_transport_stopped(wifi)) + return -EIO; + drain(wifi); + return wifi->scans_done != done ? 0 : -ETIMEDOUT; +} + static int scan_profile27(struct centauri_t6050_wifi *wifi) { struct cfg80211_scan_request *request = wifi->scan_request; @@ -1060,8 +1311,9 @@ static int scan_profile27(struct centauri_t6050_wifi *wifi) size_t size = 14; unsigned long deadline; int ret; - bool abort_sent = false; + if (scan_transport_stopped(wifi)) + return -EIO; if (READ_ONCE(wifi->scan_abort)) return -ECANCELED; memset(scan, 0, sizeof(scan)); @@ -1132,28 +1384,32 @@ static int scan_profile27(struct centauri_t6050_wifi *wifi) deadline = jiffies + msecs_to_jiffies(max(8000U, count * 220 + 2000)); do { - drain(wifi); - if (READ_ONCE(wifi->stopping) || - readl(wifi->a.bar + 8) != 2) + if (scan_transport_stopped(wifi)) return -EIO; + drain(wifi); if (wifi->scans_done != done) break; - if (READ_ONCE(wifi->scan_abort) && !abort_sent) { - ret = command(wifi, 65537, NULL, 0); - if (ret) - return ret; - abort_sent = true; + if (READ_ONCE(wifi->scan_abort)) { + ret = scan_stop_chunk(wifi, done); + return ret == -EIO ? -EIO : -ECANCELED; } + mutex_unlock(&wifi->lock); usleep_range(1000, 2000); + mutex_lock(&wifi->lock); } while (time_before(jiffies, deadline)); + if (wifi->scans_done == done) { + if (scan_transport_stopped(wifi)) + return -EIO; + drain(wifi); + } if (wifi->scans_done == done) { dev_warn(&wifi->control->pdev->dev, "Wi-Fi scan of %u channels: no completion event\n", count); - command(wifi, 65537, NULL, 0); - return -ETIMEDOUT; + ret = scan_stop_chunk(wifi, done); + return ret == -EIO ? -EIO : -ETIMEDOUT; } - if (wifi->scan_status && !abort_sent) + if (wifi->scan_status) dev_warn(&wifi->control->pdev->dev, "Wi-Fi scan of %u channels ended with firmware status %u\n", count, wifi->scan_status); @@ -1709,78 +1965,44 @@ static int join_timeout(u16 status) */ #define AVOID_SECONDS 120 -struct avoid_entry { - u8 bssid[ETH_ALEN]; - struct ieee80211_channel *channel; -}; - -struct avoid_list { +struct avoid_band { struct centauri_t6050_wifi *wifi; bool other_band; - unsigned int count; - struct avoid_entry entry[16]; }; /* Called for every BSS entry, under cfg80211's BSS lock. */ -static void avoid_collect(struct wiphy *wiphy, struct cfg80211_bss *bss, - void *data) +static void avoid_other_band(struct wiphy *wiphy, struct cfg80211_bss *bss, + void *data) { - struct avoid_list *list = data; - struct centauri_t6050_wifi *wifi = list->wifi; + struct avoid_band *band = data; + struct centauri_t6050_wifi *wifi = band->wifi; const struct element *ssid; - bool same; + if (band->other_band || bss->channel->band == NL80211_BAND_6GHZ) + return; rcu_read_lock(); ssid = ieee80211_bss_get_elem(bss, WLAN_EID_SSID); - same = ssid && ssid->datalen == wifi->ssid_len && - !memcmp(ssid->data, wifi->ssid, wifi->ssid_len); + band->other_band = ssid && ssid->datalen == wifi->ssid_len && + !memcmp(ssid->data, wifi->ssid, wifi->ssid_len); rcu_read_unlock(); - if (!same) - return; - if (bss->channel->band != NL80211_BAND_6GHZ) { - list->other_band = true; - } else if (list->count < ARRAY_SIZE(list->entry)) { - ether_addr_copy(list->entry[list->count].bssid, bss->bssid); - list->entry[list->count++].channel = bss->channel; - } } /* The 6 GHz join to wifi->bssid failed. Called with wifi->lock held. */ static void join_avoid_6ghz(struct centauri_t6050_wifi *wifi) { - struct avoid_list list = { .wifi = wifi }; - struct cfg80211_bss *bss; - unsigned int i, pass; - - /* Entries can share a BSSID, and the iterator may not unlink. */ - for (pass = 0; pass < 8; pass++) { - list.count = 0; - cfg80211_bss_iter(wifi->wiphy, NULL, avoid_collect, &list); - if (!list.other_band) - return; - if (!pass) { - memcpy(wifi->avoid_ssid, wifi->ssid, wifi->ssid_len); - wifi->avoid_ssid_len = wifi->ssid_len; - wifi->avoid_until = jiffies + AVOID_SECONDS * HZ; - wifi->avoid_valid = true; - dev_info(&wifi->control->pdev->dev, - "6 GHz join to %pM failed: not reporting this network's 6 GHz BSSes for %u s\n", - wifi->bssid, AVOID_SECONDS); - } - for (i = 0; i < list.count; i++) { - bss = cfg80211_get_bss(wifi->wiphy, - list.entry[i].channel, - list.entry[i].bssid, NULL, 0, - IEEE80211_BSS_TYPE_ANY, - IEEE80211_PRIVACY_ANY); - if (!bss) - continue; - cfg80211_unlink_bss(wifi->wiphy, bss); - cfg80211_put_bss(wifi->wiphy, bss); - } - if (!list.count) - break; - } + struct avoid_band band = { .wifi = wifi }; + + cfg80211_bss_iter(wifi->wiphy, NULL, avoid_other_band, &band); + if (!band.other_band) + return; + memcpy(wifi->avoid_ssid, wifi->ssid, wifi->ssid_len); + wifi->avoid_ssid_len = wifi->ssid_len; + wifi->avoid_until = jiffies + AVOID_SECONDS * HZ; + wifi->avoid_valid = true; + dev_info(&wifi->control->pdev->dev, + "6 GHz join to %pM failed: not reporting this network's 6 GHz BSSes for %u s\n", + wifi->bssid, AVOID_SECONDS); + avoid_unlink(wifi, NULL); } static void connect_worker(struct work_struct *work) @@ -1798,6 +2020,9 @@ static void connect_worker(struct work_struct *work) return; } host_setup_commands(wifi); + drain(wifi); + wifi->connect_event = false; + wifi->disconnect_event = false; slot = wifi->command_head; ret = command(wifi, 131072, wifi->connect_payload, wifi->connect_size); memzero_explicit(wifi->connect_payload, sizeof(wifi->connect_payload)); @@ -1942,6 +2167,32 @@ static int wait_disconnect(struct centauri_t6050_wifi *wifi) return 0; } +static bool data_tx_in_flight(struct centauri_t6050_wifi *wifi) +{ + unsigned int i; + + for (i = 0; i < DATA_TX_SLOTS; i++) + if (wifi->data_tx_busy[i]) + return true; + return false; +} + +static void drain_tx_in_flight(struct centauri_t6050_wifi *wifi) +{ + unsigned long deadline = jiffies + msecs_to_jiffies(100); + + lockdep_assert_held(&wifi->lock); + while (data_tx_in_flight(wifi) && time_before(jiffies, deadline)) { + drain(wifi); + if (!data_tx_in_flight(wifi) || wifi->command_failed || + READ_ONCE(wifi->stopping) || readl(wifi->a.bar + 8) != 2) + break; + usleep_range(500, 1000); + } + if (data_tx_in_flight(wifi)) + drain(wifi); +} + static int wifi_disconnect(struct wiphy *wiphy, struct net_device *netdev, u16 reason) { @@ -1988,6 +2239,8 @@ static int wifi_disconnect(struct wiphy *wiphy, struct net_device *netdev, wifi->connected = false; netif_stop_queue(netdev); skb_queue_purge(&wifi->data_tx_queue); + if (!READ_ONCE(wifi->stopping)) + drain_tx_in_flight(wifi); netif_carrier_off(netdev); if (connected) cfg80211_disconnected(netdev, reason, NULL, 0, true, @@ -2006,6 +2259,7 @@ void centauri_t6050_wifi_pm_prepare(struct centauri_t6050 *c) return; mutex_lock(&wifi->lock); wifi->pm_disconnect = (struct centauri_wifi_disconnect_receipt) {}; + wifi->pm_wowlan_armed = false; wifi->pm_prepared = true; mutex_unlock(&wifi->lock); } @@ -2024,6 +2278,46 @@ int centauri_t6050_wifi_pm_error(struct centauri_t6050 *c) return ret; } +bool centauri_t6050_wifi_pm_disconnected(struct centauri_t6050 *c) +{ + struct centauri_t6050_wifi *wifi = c->wifi; + bool disconnected = false; + + if (!wifi) + return false; + mutex_lock(&wifi->lock); + if (wifi->pm_prepared) + disconnected = wifi->pm_disconnect.seen; + mutex_unlock(&wifi->lock); + return disconnected; +} + +bool centauri_t6050_wifi_wowlan_armed(struct centauri_t6050 *c) +{ + struct centauri_t6050_wifi *wifi = c->wifi; + bool armed = false; + + if (!wifi) + return false; + mutex_lock(&wifi->lock); + if (wifi->pm_prepared) + armed = wifi->pm_wowlan_armed; + mutex_unlock(&wifi->lock); + return armed; +} + +void centauri_t6050_wifi_mark_failed(struct centauri_t6050 *c) +{ + struct centauri_t6050_wifi *wifi = c->wifi; + + if (!wifi) + return; + mutex_lock(&wifi->lock); + WRITE_ONCE(wifi->stopping, true); + wifi->command_failed = true; + mutex_unlock(&wifi->lock); +} + void centauri_t6050_wifi_pm_complete(struct centauri_t6050 *c) { struct centauri_t6050_wifi *wifi = c->wifi; @@ -2032,6 +2326,7 @@ void centauri_t6050_wifi_pm_complete(struct centauri_t6050 *c) return; mutex_lock(&wifi->lock); /* Keep the receipt until the next prepare; it is not a sleep proof. */ + wifi->pm_wowlan_armed = false; wifi->pm_prepared = false; mutex_unlock(&wifi->lock); } @@ -2076,14 +2371,21 @@ static int alpha_transport_state(struct centauri_t6050_wifi *wifi, bool asleep) return ret; } -static int alpha_host_power(struct centauri_t6050_wifi *wifi, bool asleep) +#define CEN_HOST_EVENTS_LEGACY 85 +#define CEN_HOST_EVENTS_FULL 91 + +static int alpha_host_power_send(struct centauri_t6050_wifi *wifi, bool asleep, + u8 event_count) { static const u8 sleep_events[] = { 24, 26, 27, 15, 51, 8, 9, 10, 84 }; - u8 payload[98] = {}, events[86] = {}, sleep_option = 1; + u8 payload[3 + 5 + 4 + 1 + CEN_HOST_EVENTS_FULL] = {}; + u8 events[1 + CEN_HOST_EVENTS_FULL] = {}; + u8 sleep_option = 1; u16 state = 0; u8 hint = 0; size_t size = 3; - int i, ret; + unsigned int i; + int ret; lockdep_assert_held(&wifi->lock); if (readl(wifi->a.bar + 8) != 2) @@ -2097,33 +2399,48 @@ static int alpha_host_power(struct centauri_t6050_wifi *wifi, bool asleep) events[0] = ARRAY_SIZE(sleep_events); memcpy(events + 1, sleep_events, sizeof(sleep_events)); } else { - events[0] = sizeof(events) - 1; - for (i = 0; i < events[0]; i++) + events[0] = event_count; + for (i = 0; i < event_count; i++) events[i + 1] = i; } - append_tlv(payload, &size, 280, events, sizeof(events)); + append_tlv(payload, &size, 280, events, 1 + event_count); ret = command(wifi, 6, payload, size); dev_dbg(&wifi->control->pdev->dev, - "Alpha firmware host %s (connected=%d state=%u): ret=%d status=%u exec=%u\n", - asleep ? "sleep" : "awake", wifi->connected, state, ret, - wifi->reply_status, readl(wifi->a.bar + 8)); + "Alpha firmware host %s (connected=%d state=%u events=%u tlv280=%u): ret=%d status=%u exec=%u\n", + asleep ? "sleep" : "awake", wifi->connected, state, + events[0], 1 + event_count, ret, wifi->reply_status, + readl(wifi->a.bar + 8)); return ret; } -static bool data_tx_in_flight(struct centauri_t6050_wifi *wifi) +static int alpha_host_power(struct centauri_t6050_wifi *wifi, bool asleep) { - unsigned int i; + u16 full_status; + int ret; - for (i = 0; i < DATA_TX_SLOTS; i++) - if (wifi->data_tx_busy[i]) - return true; - return false; + if (asleep) + return alpha_host_power_send(wifi, true, CEN_HOST_EVENTS_LEGACY); + + ret = alpha_host_power_send(wifi, false, CEN_HOST_EVENTS_FULL); + if (ret == -EREMOTEIO && readl(wifi->a.bar + 8) == 2) { + full_status = wifi->reply_status; + ret = alpha_host_power_send(wifi, false, CEN_HOST_EVENTS_LEGACY); + if (!ret && !wifi->host_events_fallback_logged) { + wifi->host_events_fallback_logged = true; + dev_info(&wifi->control->pdev->dev, + "Alpha host wake fell back from %u to %u events (status=%u)\n", + CEN_HOST_EVENTS_FULL, CEN_HOST_EVENTS_LEGACY, + full_status); + } + } + return ret; } static int alpha_resume_locked(struct centauri_t6050_wifi *wifi) { int ret; + ASSERT_RTNL(); lockdep_assert_held(&wifi->lock); if (wifi->transport_sleep_sent) { ret = alpha_transport_state(wifi, false); @@ -2132,10 +2449,22 @@ static int alpha_resume_locked(struct centauri_t6050_wifi *wifi) wifi->transport_sleep_sent = false; } if (wifi->host_sleep_sent) { + /* Under the mutex, only the wake command can pass the gate. */ + wifi->host_sleep_sent = false; ret = alpha_host_power(wifi, false); - if (ret) + if (ret) { + wifi->host_sleep_sent = true; return ret; - wifi->host_sleep_sent = false; + } + } + if (wifi->regulatory_deferred) { + if (wifi->configured && wifi->country_deferred[0]) + country_set(wifi, wifi->country_deferred); + memset(wifi->country_deferred, 0, sizeof(wifi->country_deferred)); + wifi->regulatory_deferred = false; + channels_apply(wifi); + if (wifi->command_failed) + return -EIO; } WRITE_ONCE(wifi->transport_paused, false); WRITE_ONCE(wifi->tx_paused, false); @@ -2152,7 +2481,6 @@ static int alpha_resume_locked(struct centauri_t6050_wifi *wifi) int centauri_t6050_wifi_suspend(struct centauri_t6050 *c) { struct centauri_t6050_wifi *wifi = c->wifi; - unsigned long deadline; unsigned int i; int ret; @@ -2178,16 +2506,7 @@ int centauri_t6050_wifi_suspend(struct centauri_t6050 *c) mutex_unlock(&wifi->lock); return -EIO; } - deadline = jiffies + msecs_to_jiffies(100); - while (data_tx_in_flight(wifi) && time_before(jiffies, deadline)) { - drain(wifi); - if (!data_tx_in_flight(wifi) || wifi->command_failed || - READ_ONCE(wifi->stopping) || readl(wifi->a.bar + 8) != 2) - break; - usleep_range(500, 1000); - } - if (data_tx_in_flight(wifi)) - drain(wifi); + drain_tx_in_flight(wifi); if (data_tx_in_flight(wifi) || wifi->command_failed || READ_ONCE(wifi->stopping) || readl(wifi->a.bar + 8) != 2) { ret = data_tx_in_flight(wifi) ? -EBUSY : -EIO; @@ -2207,15 +2526,24 @@ int centauri_t6050_wifi_suspend(struct centauri_t6050 *c) synchronize_irq(pci_irq_vector(c->alpha_irqs.pdev, i)); cancel_work_sync(&wifi->link_work); + /* Match the regulatory notifier's lock order for suspend unwind. */ + rtnl_lock(); mutex_lock(&wifi->lock); ret = alpha_transport_state(wifi, true); if (!ret) { wifi->transport_sleep_sent = true; mutex_unlock(&wifi->lock); + rtnl_unlock(); return 0; } - alpha_resume_locked(wifi); + if (alpha_resume_locked(wifi)) { + dev_warn(&c->pdev->dev, + "Alpha host wake failed during suspend unwind\n"); + WRITE_ONCE(wifi->stopping, true); + wifi->command_failed = true; + } mutex_unlock(&wifi->lock); + rtnl_unlock(); return ret; out_unpause: @@ -2235,9 +2563,11 @@ int centauri_t6050_wifi_resume(struct centauri_t6050 *c) if (!wifi) return 0; + rtnl_lock(); mutex_lock(&wifi->lock); ret = alpha_resume_locked(wifi); mutex_unlock(&wifi->lock); + rtnl_unlock(); return ret; } @@ -2252,9 +2582,11 @@ static int wifi_suspend(struct wiphy *wiphy, struct cfg80211_wowlan *wowlan) ret = (wowlan->any && wifi->connected && !wifi->connecting && !wifi->disconnect_pending && !wifi->command_failed && !READ_ONCE(wifi->stopping)) ? 0 : 1; + wifi->pm_wowlan_armed = !ret; mutex_unlock(&wifi->lock); return ret; } + wifi->pm_wowlan_armed = false; /* cfg80211 already called normal leave; do not send another command. */ if (wifi->pm_prepared) ret = wifi->pm_disconnect.error; @@ -2292,20 +2624,19 @@ static void wifi_regulatory(struct wiphy *wiphy, u8 country[3] = { request->alpha2[0], request->alpha2[1], 1 }; bool named = country[0] >= 'A' && country[0] <= 'Z' && country[1] >= 'A' && country[1] <= 'Z'; - int ret; mutex_lock(&wifi->lock); - if (wifi->configured && named) { - ret = command(wifi, 9, country, sizeof(country)); - if (ret) - dev_err(&wifi->control->pdev->dev, - "firmware country update failed: %d\n", ret); - else - firmware_report(wifi, 19, wifi->hw_channels, - &wifi->hw_channels_blob); + if (wifi->host_sleep_sent) { + /* Keep the last named country across cfg80211's world updates. */ + if (named) + memcpy(wifi->country_deferred, country, sizeof(country)); + wifi->regulatory_deferred = true; + } else { + if (wifi->configured && named) + country_set(wifi, country); + /* cfg80211 has just recomputed the channel flags. */ + channels_apply(wifi); } - /* cfg80211 has just recomputed the channel flags from its own rules. */ - channels_apply(wifi); mutex_unlock(&wifi->lock); } @@ -2313,7 +2644,8 @@ static void fill_station(struct centauri_t6050_wifi *wifi, struct station_info * { const struct net_device_stats *stats = &wifi->netdev->stats; - if (time_after_eq(jiffies, wifi->station_signal_at + HZ)) { + if (!wifi->scan_request && + time_after_eq(jiffies, wifi->station_signal_at + HZ)) { wifi->station_signal_valid = false; wifi->station_signal_at = jiffies; query_link_status(wifi); @@ -2392,9 +2724,13 @@ static int net_open(struct net_device *netdev) netif_carrier_off(netdev); netif_stop_queue(netdev); + skb_queue_purge(&wifi->rx_gro_queue); + napi_enable(&wifi->rx_napi); mutex_lock(&wifi->lock); ret = wifi->configured ? data_start(wifi) : -ENETDOWN; mutex_unlock(&wifi->lock); + if (ret) + napi_disable(&wifi->rx_napi); return ret; } @@ -2406,6 +2742,8 @@ static int net_stop(struct net_device *netdev) cancel_scan(wifi); netif_stop_queue(netdev); skb_queue_purge(&wifi->data_tx_queue); + napi_disable(&wifi->rx_napi); + skb_queue_purge(&wifi->rx_gro_queue); return 0; } @@ -2428,6 +2766,7 @@ static netdev_tx_t net_transmit(struct sk_buff *skb, struct net_device *netdev) netif_stop_queue(netdev); return NETDEV_TX_BUSY; } + sk_pacing_shift_update(skb->sk, DATA_TX_PACING_SHIFT); skb_queue_tail(&wifi->data_tx_queue, skb); if (skb_queue_len(&wifi->data_tx_queue) >= DATA_TX_QUEUE_LIMIT) netif_stop_queue(netdev); @@ -2635,6 +2974,27 @@ static int query_link_status(struct centauri_t6050_wifi *wifi) return ret; } +static int data_stats_show(struct seq_file *m, void *unused) +{ + struct centauri_t6050_wifi *wifi = m->private; + + mutex_lock(&wifi->lock); + seq_printf(m, + "rx received %u reposted %u bad %u\n" + "tx submitted %u completed %u in_flight %u failed %u bad %u coalesced %u\n" + "tx queued %u capped %u cap_bypassed %u\n", + wifi->data_rx_received, wifi->data_rx_reposted, + wifi->data_rx_bad, wifi->data_tx_submitted, + wifi->data_tx_completed, + wifi->data_tx_submitted - wifi->data_tx_completed, + wifi->data_tx_failed, wifi->data_tx_bad, + wifi->data_tx_coalesced, skb_queue_len(&wifi->data_tx_queue), + wifi->data_tx_capped, wifi->data_tx_cap_bypassed); + mutex_unlock(&wifi->lock); + return 0; +} +DEFINE_SHOW_ATTRIBUTE(data_stats); + int centauri_t6050_wifi_register(struct centauri_t6050 *c) { struct centauri_t6050_wifi *wifi; @@ -2647,6 +3007,7 @@ int centauri_t6050_wifi_register(struct centauri_t6050 *c) wifi->control = c; mutex_init(&wifi->lock); skb_queue_head_init(&wifi->data_tx_queue); + skb_queue_head_init(&wifi->rx_gro_queue); INIT_WORK(&wifi->scan_work, scan_worker); INIT_WORK(&wifi->connect_work, connect_worker); INIT_WORK(&wifi->link_work, link_worker); @@ -2662,6 +3023,7 @@ int centauri_t6050_wifi_register(struct centauri_t6050 *c) } *(struct centauri_t6050_wifi **)wiphy_priv(wifi->wiphy) = wifi; *(struct centauri_t6050_wifi **)netdev_priv(wifi->netdev) = wifi; + netif_napi_add(wifi->netdev, &wifi->rx_napi, rx_poll); set_wiphy_dev(wifi->wiphy, &c->pdev->dev); wifi->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION); wifi->wiphy->max_scan_ssids = 1; @@ -2680,6 +3042,13 @@ int centauri_t6050_wifi_register(struct centauri_t6050 *c) * on the preferred scanning channels and those the 2.4/5 GHz APs report. */ wifi->wiphy->flags |= WIPHY_FLAG_SPLIT_SCAN_6GHZ; + /* + * An AP serving several networks on one radio, the rule at 6 GHz, + * beacons one of them and describes the others in a multiple-BSSID + * element. cfg80211 makes scan entries for those nontransmitted BSSes + * only with this set; the firmware joins any of them by its BSSID. + */ + wifi->wiphy->support_mbssid = true; wifi->wiphy->signal_type = CFG80211_SIGNAL_TYPE_MBM; wifi->wiphy->reg_notifier = wifi_regulatory; wifi->wiphy->cipher_suites = cipher_suites; @@ -2727,6 +3096,8 @@ int centauri_t6050_wifi_register(struct centauri_t6050 *c) &wifi->hw_channels_blob); debugfs_create_blob("system_caps", 0400, wifi->wiphy->debugfsdir, &wifi->system_caps_blob); + debugfs_create_file("data_stats", 0400, wifi->wiphy->debugfsdir, wifi, + &data_stats_fops); rtnl_lock(); channels_apply(wifi); rtnl_unlock(); @@ -2776,6 +3147,7 @@ void centauri_t6050_wifi_unregister(struct centauri_t6050 *c) skb_queue_purge(&wifi->data_tx_queue); if (wifi->netdev && wifi->netdev->reg_state == NETREG_REGISTERED) unregister_netdev(wifi->netdev); + skb_queue_purge(&wifi->rx_gro_queue); if (wifi->registered) wiphy_unregister(wifi->wiphy); if (wifi->wiphy) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Kconfig b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Kconfig index d158f95bb1800b..0556460739c8ad 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Kconfig +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Kconfig @@ -12,13 +12,14 @@ config BRCMFMAC_PROTO_BCDC bool config BRCMFMAC_KUNIT_TEST - tristate "KUnit tests for brcmfmac scan timeout" if !KUNIT_ALL_TESTS + tristate "KUnit tests for brcmfmac scan timeout and PCIe TCM bounds" if !KUNIT_ALL_TESTS depends on KUNIT && BRCMFMAC default KUNIT_ALL_TESTS help Test channel-based scan deadline calculation without Wi-Fi hardware. Covers passive and active scan budgets, all-band scans, minimum - deadlines and saturation for oversized channel counts. + deadlines and saturation for oversized channel counts. Also test + the bounds check for firmware-supplied offsets into the PCIe TCM. These tests run under KUnit and are not needed for normal operation. config BRCMFMAC_PROTO_MSGBUF diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Makefile b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Makefile index 8e9556579508a9..a77be645839e7d 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Makefile +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Makefile @@ -10,7 +10,7 @@ ccflags-y += \ -I $(src)/../include obj-$(CONFIG_BRCMFMAC) += brcmfmac.o -obj-$(CONFIG_BRCMFMAC_KUNIT_TEST) += scan_timeout_test.o +obj-$(CONFIG_BRCMFMAC_KUNIT_TEST) += scan_timeout_test.o pcie_tcm_test.o brcmfmac-objs += \ cfg80211.o \ chip.o \ diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/bus.h b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/bus.h index 840f81ff6c7ff2..4a0148d6aed04d 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/bus.h +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/bus.h @@ -165,6 +165,8 @@ struct brcmf_bus_stats { * @always_use_fws_queue: bus wants use queue also when fwsignal is inactive. * @wowl_transport: bus can keep the firmware running during system sleep. * @wowl_wake: platform can route a wake signal from the device. + * @wowl_s2idle_only: the wake signal only works while the link stays up (in-band + * MSI): there is no WoWLAN in a system sleep deeper than suspend-to-idle. * @ops: callbacks for this bus instance. * @msgbuf: msgbuf protocol parameters provided by bus layer. * @list: member used to add this bus instance to linked list. @@ -187,6 +189,7 @@ struct brcmf_bus { bool always_use_fws_queue; bool wowl_transport; bool wowl_wake; + bool wowl_s2idle_only; bool removing; /* device removal in progress; quiesce async work */ struct mutex bus_reset_lock; diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c index eac1261258c45d..157b54a776fd74 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -1680,12 +1681,13 @@ static int brcmf_set_pmk(struct brcmf_if *ifp, const u8 *pmk_data, u16 pmk_len) return brcmf_set_wsec(ifp, pmk_data, pmk_len, 0); } -static void brcmf_link_down(struct brcmf_cfg80211_vif *vif, u16 reason, +static bool brcmf_link_down(struct brcmf_cfg80211_vif *vif, u16 reason, bool locally_generated) { struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(vif->wdev.wiphy); struct brcmf_pub *drvr = cfg->pub; bool bus_up = drvr->bus_if->state == BRCMF_BUS_UP; + bool disassoc_sent = false; s32 err = 0; brcmf_dbg(TRACE, "Enter\n"); @@ -1698,6 +1700,8 @@ static void brcmf_link_down(struct brcmf_cfg80211_vif *vif, u16 reason, if (err) bphy_err(drvr, "WLC_DISASSOC failed (%d)\n", err); + else + disassoc_sent = true; } if ((vif->wdev.iftype == NL80211_IFTYPE_STATION) || @@ -1716,6 +1720,7 @@ static void brcmf_link_down(struct brcmf_cfg80211_vif *vif, u16 reason, vif->profile.use_fwsup = BRCMF_PROFILE_FWSUP_NONE; } brcmf_dbg(TRACE, "Exit\n"); + return disassoc_sent; } static s32 brcmf_cfg80211_join_ibss(struct wiphy *wiphy, @@ -5264,6 +5269,19 @@ static s32 brcmf_cfg80211_suspend(struct wiphy *wiphy, if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) brcmf_abort_scanning(cfg); + /* An in-band MSI cannot wake the host once the link goes down, so + * refuse WoWLAN for a deeper sleep than suspend-to-idle instead of + * failing the whole system suspend. cfg80211 then leaves every + * interface (AP and P2P-GO included) and suspends again without it. + */ + if (wowl && cfg->pub->bus_if->wowl_s2idle_only && + pm_suspend_target_state != PM_SUSPEND_TO_IDLE) { + bphy_info_once(cfg->pub, + "WoWLAN wakes only from suspend-to-idle here, sleeping without it\n"); + cfg->scan_status = 0; + return 1; + } + if (wowl == NULL) { brcmf_bus_wowl_config(cfg->pub->bus_if, false); list_for_each_entry(vif, &cfg->vif_list, list) { @@ -5273,12 +5291,13 @@ static s32 brcmf_cfg80211_suspend(struct wiphy *wiphy, * disassociate from AP to save power while system is * in suspended state */ - brcmf_link_down(vif, WLAN_REASON_UNSPECIFIED, true); - /* Make sure WPA_Supplicant receives all the event - * generated due to DISASSOC call to the fw to keep - * the state fw and WPA_Supplicant state consistent - */ - brcmf_delay(500); + if (brcmf_link_down(vif, WLAN_REASON_UNSPECIFIED, true)) { + /* Make sure WPA_Supplicant receives all the event + * generated due to DISASSOC call to the fw to keep + * the state fw and WPA_Supplicant state consistent + */ + brcmf_delay(500); + } } /* Configure MPC */ brcmf_set_mpc(ifp, 1); @@ -8565,8 +8584,11 @@ static void brcmf_update_vht_cap(struct ieee80211_supported_band *band, } static void brcmf_update_he_cap(struct ieee80211_supported_band *band, - struct ieee80211_sband_iftype_data *data) + struct ieee80211_sband_iftype_data *data, + u32 bw_cap[4]) { + bool has_160 = band->band != NL80211_BAND_2GHZ && + (bw_cap[band->band] & WLC_BW_160MHZ_BIT); int idx = 1; struct ieee80211_sta_he_cap *he_cap = &data->he_cap; struct ieee80211_he_cap_elem *he_cap_elem = &he_cap->he_cap_elem; @@ -8600,12 +8622,27 @@ static void brcmf_update_he_cap(struct ieee80211_supported_band *band, he_cap_elem->mac_cap_info[4] = IEEE80211_HE_MAC_CAP4_AMSDU_IN_AMPDU; - /* HE PHY Capabilities Information */ - he_cap_elem->phy_cap_info[0] = - IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_IN_2G | - IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_80MHZ_IN_5G | - IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_160MHZ_IN_5G; - ; + /* + * HE PHY Capabilities Information. + * + * The channel width set is per band (IEEE 802.11ax 9.4.2.248.3): + * B0 is the 2.4 GHz bit, B1 and B2 apply to 5 GHz and 6 GHz. + * 40/80 MHz stays on in 5 GHz and 6 GHz as before (80 MHz is + * mandatory there, see brcmf_update_vht_cap()). 160 MHz follows the + * firmware's per-band "bw_cap", the same source the VHT capability + * uses, so it is only reported when the radio can use it. This runs + * again when the wiphy bands are rebuilt, so set the field whole. + */ + if (band->band == NL80211_BAND_2GHZ) { + he_cap_elem->phy_cap_info[0] = + IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_IN_2G; + } else { + he_cap_elem->phy_cap_info[0] = + IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_80MHZ_IN_5G; + if (has_160) + he_cap_elem->phy_cap_info[0] |= + IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_160MHZ_IN_5G; + } he_cap_elem->phy_cap_info[1] = IEEE80211_HE_PHY_CAP1_LDPC_CODING_IN_PAYLOAD; @@ -8646,10 +8683,14 @@ static void brcmf_update_he_cap(struct ieee80211_supported_band *band, IEEE80211_HE_PHY_CAP7_MAX_NC_1; he_cap_elem->phy_cap_info[8] = - IEEE80211_HE_PHY_CAP8_HE_ER_SU_PPDU_4XLTF_AND_08_US_GI | - IEEE80211_HE_PHY_CAP8_20MHZ_IN_40MHZ_HE_PPDU_IN_2G | - IEEE80211_HE_PHY_CAP8_20MHZ_IN_160MHZ_HE_PPDU | - IEEE80211_HE_PHY_CAP8_80MHZ_IN_160MHZ_HE_PPDU; + IEEE80211_HE_PHY_CAP8_HE_ER_SU_PPDU_4XLTF_AND_08_US_GI; + if (band->band == NL80211_BAND_2GHZ) + he_cap_elem->phy_cap_info[8] |= + IEEE80211_HE_PHY_CAP8_20MHZ_IN_40MHZ_HE_PPDU_IN_2G; + if (has_160) + he_cap_elem->phy_cap_info[8] |= + IEEE80211_HE_PHY_CAP8_20MHZ_IN_160MHZ_HE_PPDU | + IEEE80211_HE_PHY_CAP8_80MHZ_IN_160MHZ_HE_PPDU; he_cap_elem->phy_cap_info[9] = IEEE80211_HE_PHY_CAP9_TX_1024_QAM_LESS_THAN_242_TONE_RU | @@ -8660,8 +8701,9 @@ static void brcmf_update_he_cap(struct ieee80211_supported_band *band, /* HE Supported MCS and NSS Set */ he_mcs->rx_mcs_80 = cpu_to_le16(0xfffa); he_mcs->tx_mcs_80 = cpu_to_le16(0xfffa); - he_mcs->rx_mcs_160 = cpu_to_le16(0xfffa); - he_mcs->tx_mcs_160 = cpu_to_le16(0xfffa); + /* 0xffff: no spatial stream is supported at 160 MHz */ + he_mcs->rx_mcs_160 = cpu_to_le16(has_160 ? 0xfffa : 0xffff); + he_mcs->tx_mcs_160 = cpu_to_le16(has_160 ? 0xfffa : 0xffff); /* HE 6 GHz band capabilities */ if (band->band == NL80211_BAND_6GHZ) { u16 capa = 0; @@ -8790,7 +8832,7 @@ static int brcmf_setup_wiphybands(struct brcmf_cfg80211_info *cfg) txbf_bfe_cap, txbf_bfr_cap, ldpc_cap, stbc_rx, stbc_tx); if (he_enable) - brcmf_update_he_cap(band, &sdata[band->band]); + brcmf_update_he_cap(band, &sdata[band->band], bw_cap); } return 0; @@ -9284,13 +9326,13 @@ static s32 __brcmf_cfg80211_down(struct brcmf_if *ifp) * from AP to save power */ if (check_vif_up(ifp->vif)) { - brcmf_link_down(ifp->vif, WLAN_REASON_UNSPECIFIED, true); - - /* Make sure WPA_Supplicant receives all the event - generated due to DISASSOC call to the fw to keep - the state fw and WPA_Supplicant state consistent - */ - brcmf_delay(500); + if (brcmf_link_down(ifp->vif, WLAN_REASON_UNSPECIFIED, true)) { + /* Make sure WPA_Supplicant receives all the events + * generated due to DISASSOC call to the fw to keep + * the fw and WPA_Supplicant state consistent. + */ + brcmf_delay(500); + } } brcmf_abort_scanning(cfg); diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index 2bfee245f43312..0992446c01b22d 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -307,6 +307,8 @@ static const struct brcmf_firmware_mapping brcmf_pcie_fwnames[] = { #define BRCMF_SHARED_FLAGS3_OFFSET 108 #define BRCMF_SHARED_HOST_CAP2_OFFSET 112 #define BRCMF_SHARED_HOST_CAP3_OFFSET 116 +/* The end of the last shared RAM field the driver reads or writes */ +#define BRCMF_SHARED_SIZE (BRCMF_SHARED_HOST_CAP2_OFFSET + 4) #define BRCMF_RING_H2D_RING_COUNT_OFFSET 0 #define BRCMF_RING_D2H_RING_COUNT_OFFSET 1 @@ -429,6 +431,7 @@ struct brcmf_pciedev_info { const struct brcmf_pcie_reginfo *reginfo; void __iomem *regs; void __iomem *tcm; + size_t tcm_size; u32 fw_size; bool skip_reset_vector; struct brcmf_chip *ci; @@ -779,6 +782,8 @@ static void brcmf_pcie_reset_device(struct brcmf_pciedev_info *devinfo) BRCMF_PCIE_CFGREG_REG_BAR2_CONFIG, BRCMF_PCIE_CFGREG_REG_BAR3_CONFIG }; + bool fn_reset = false; + bool saved = false; u32 i; u32 val; u32 lsc; @@ -786,6 +791,28 @@ static void brcmf_pcie_reset_device(struct brcmf_pciedev_info *devinfo) if (!devinfo->ci) return; + /* + * On chipcommon rev >= 65 the watchdog below also resets PCIe function + * 0 (CC_WD_SSRESET_PCIE_F0_EN), which puts its config space back to the + * chip defaults: e.g. the resizable BAR 2 drops from the size the PCI + * core assigned to 8 MiB. Save what the PCI core programmed, before + * ASPM is turned off for the reset, so it can be put back afterwards. + * Older chips keep their config space, so save nothing there: a saved + * state left behind would stand in for the live one at the next + * suspend. + */ + core = brcmf_chip_get_chipcommon(devinfo->ci); + if (core->rev >= 65) { + int err = pci_save_state(devinfo->pdev); + + if (err) { + pci_err(devinfo->pdev, "failed to save PCI state: %d\n", err); + devinfo->pdev->state_saved = false; + } else { + saved = true; + } + } + /* Disable ASPM */ brcmf_pcie_select_core(devinfo, BCMA_CORE_PCIE2); pci_read_config_dword(devinfo->pdev, BRCMF_PCIE_REG_LINK_STATUS_CTRL, @@ -801,6 +828,8 @@ static void brcmf_pcie_reset_device(struct brcmf_pciedev_info *devinfo) if (core->rev >= 65) { u32 mask = CC_WD_SSRESET_PCIE_F0_EN; + fn_reset = true; + core = brcmf_chip_get_core(devinfo->ci, BCMA_CORE_PCIE2); if (core->rev < 66) mask |= CC_WD_SSRESET_PCIE_ALL_FN_EN; @@ -826,6 +855,16 @@ static void brcmf_pcie_reset_device(struct brcmf_pciedev_info *devinfo) pci_write_config_dword(devinfo->pdev, BRCMF_PCIE_REG_LINK_STATUS_CTRL, lsc); + /* + * Put the PCI core's configuration back. Otherwise the function runs + * with the reset defaults while the core still holds the assigned + * values, and the next pci_restore_state() (system resume) rewrites + * them on a live, bus-mastering function: BAR 2 changes size under + * running firmware. Only a state saved above is put back. + */ + if (fn_reset && saved) + pci_restore_state(devinfo->pdev); + core = brcmf_chip_get_core(devinfo->ci, BCMA_CORE_PCIE2); if (core->rev <= 13) { for (i = 0; i < ARRAY_SIZE(cfg_offset); i++) { @@ -1056,9 +1095,13 @@ static void brcmf_pcie_ctl_stall(struct device *dev, u32 stalls) addr = brcmf_pcie_read_tcm32(devinfo, shared->tcm_base_address + BRCMF_SHARED_TRAP_ADDR_OFFSET); /* trap type, then the exception pc */ - brcmf_err(bus, "firmware trap 0x%x at 0x%08x\n", - brcmf_pcie_read_tcm32(devinfo, addr), - brcmf_pcie_read_tcm32(devinfo, addr + 4)); + if (brcmf_pcie_tcm_range_valid(devinfo->tcm_size, addr, 8)) + brcmf_err(bus, "firmware trap 0x%x at 0x%08x\n", + brcmf_pcie_read_tcm32(devinfo, addr), + brcmf_pcie_read_tcm32(devinfo, addr + 4)); + else + brcmf_err(bus, "firmware trap record at 0x%08x is outside the TCM\n", + addr); reason = "trap in shared RAM"; } else if ((flags & BRCMF_PCIE_SHARED_ASSERT_BUILT) && (flags & BRCMF_PCIE_SHARED_ASSERT)) { @@ -1133,14 +1176,33 @@ static void brcmf_pcie_bus_console_init(struct brcmf_pciedev_info *devinfo) console = &shared->console; addr = shared->tcm_base_address + BRCMF_SHARED_CONSOLE_ADDR_OFFSET; console->base_addr = brcmf_pcie_read_tcm32(devinfo, addr); + console->bufsize = 0; + console->read_idx = 0; + console->log_idx = 0; + console->scan_idx = 0; + console->scan_len = 0; + if (!console->base_addr || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->base_addr, + BRCMF_CONSOLE_WRITEIDX_OFFSET + 4)) { + console->base_addr = 0; + return; + } addr = console->base_addr + BRCMF_CONSOLE_BUFADDR_OFFSET; console->buf_addr = brcmf_pcie_read_tcm32(devinfo, addr); addr = console->base_addr + BRCMF_CONSOLE_BUFSIZE_OFFSET; console->bufsize = brcmf_pcie_read_tcm32(devinfo, addr); + if (!console->bufsize || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->buf_addr, + console->bufsize)) { + console->base_addr = 0; + console->bufsize = 0; + return; + } addr = console->base_addr + BRCMF_CONSOLE_WRITEIDX_OFFSET; console->scan_idx = brcmf_pcie_read_tcm32(devinfo, addr); - console->scan_len = 0; + if (console->scan_idx >= console->bufsize) + console->scan_idx = 0; brcmf_dbg(FWCON, "Console: base %x, buf %x, size %d\n", console->base_addr, console->buf_addr, console->bufsize); @@ -1170,6 +1232,8 @@ static void brcmf_pcie_bus_console_read(struct brcmf_pciedev_info *devinfo, return; addr = console->base_addr + BRCMF_CONSOLE_WRITEIDX_OFFSET; newidx = brcmf_pcie_read_tcm32(devinfo, addr); + if (newidx >= console->bufsize || console->read_idx >= console->bufsize) + return; while (newidx != console->read_idx) { addr = console->buf_addr + console->read_idx; ch = brcmf_pcie_read_tcm8(devinfo, addr); @@ -1286,6 +1350,7 @@ static int brcmf_pcie_request_irq(struct brcmf_pciedev_info *devinfo) brcmf_pcie_intr_disable(devinfo); bus->wowl_wake = pci_pme_capable(pdev, PCI_D3hot); + bus->wowl_s2idle_only = false; brcmf_dbg(PCIE, "Enter\n"); @@ -1320,6 +1385,7 @@ static int brcmf_pcie_request_irq(struct brcmf_pciedev_info *devinfo) } devinfo->wowl_irq = true; bus->wowl_wake = true; + bus->wowl_s2idle_only = true; } devinfo->irq_allocated = true; return 0; @@ -1351,6 +1417,7 @@ static void brcmf_pcie_release_irq(struct brcmf_pciedev_info *devinfo) devinfo->wakeup_created = false; } devinfo->wowl_irq = false; + bus->wowl_s2idle_only = false; brcmf_pcie_intr_disable(devinfo); free_irq(pdev->irq, devinfo); pci_disable_msi(pdev); @@ -1431,11 +1498,20 @@ static int brcmf_pcie_ring_mb_update_rptr(void *ctx) struct brcmf_pcie_ringbuf *ring = (struct brcmf_pcie_ringbuf *)ctx; struct brcmf_pciedev_info *devinfo = ring->devinfo; struct brcmf_commonring *commonring = &ring->commonring; + u16 ptr; if (devinfo->state != BRCMFMAC_PCIE_STATE_UP) return -EIO; - commonring->r_ptr = devinfo->read_ptr(devinfo, ring->r_idx_addr); + /* The dongle's index is only used inside the ring; keep the last good one */ + ptr = devinfo->read_ptr(devinfo, ring->r_idx_addr); + if (ptr >= commonring->depth) { + brcmf_err(dev_get_drvdata(&devinfo->pdev->dev), + "ring %d: r_ptr %u outside depth %u\n", ring->id, ptr, + commonring->depth); + return -EIO; + } + commonring->r_ptr = ptr; brcmf_dbg(PCIE, "R r_ptr %d (%d), ring %d\n", commonring->r_ptr, commonring->w_ptr, ring->id); @@ -1449,11 +1525,20 @@ static int brcmf_pcie_ring_mb_update_wptr(void *ctx) struct brcmf_pcie_ringbuf *ring = (struct brcmf_pcie_ringbuf *)ctx; struct brcmf_pciedev_info *devinfo = ring->devinfo; struct brcmf_commonring *commonring = &ring->commonring; + u16 ptr; if (devinfo->state != BRCMFMAC_PCIE_STATE_UP) return -EIO; - commonring->w_ptr = devinfo->read_ptr(devinfo, ring->w_idx_addr); + /* The dongle's index is only used inside the ring; keep the last good one */ + ptr = devinfo->read_ptr(devinfo, ring->w_idx_addr); + if (ptr >= commonring->depth) { + brcmf_err(dev_get_drvdata(&devinfo->pdev->dev), + "ring %d: w_ptr %u outside depth %u\n", ring->id, ptr, + commonring->depth); + return -EIO; + } + commonring->w_ptr = ptr; brcmf_dbg(PCIE, "R w_ptr %d (%d), ring %d\n", commonring->w_ptr, commonring->r_ptr, ring->id); @@ -1582,6 +1667,8 @@ static int brcmf_pcie_init_ringbuffers(struct brcmf_pciedev_info *devinfo) u32 h2d_w_idx_ptr; u32 h2d_r_idx_ptr; u32 ring_mem_ptr; + u32 h2d_idx_len; + u32 d2h_idx_len; u32 i; u64 address; u32 bufsz; @@ -1607,8 +1694,24 @@ static int brcmf_pcie_init_ringbuffers(struct brcmf_pciedev_info *devinfo) brcmf_err(bus, "invalid max_flowrings(%d)\n", max_flowrings); return -EIO; } + if (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + le32_to_cpu(ringinfo.ringmem), + BRCMF_NROF_COMMON_MSGRINGS * + BRCMF_RING_MEM_SZ)) { + brcmf_err(bus, "ring memory outside the TCM\n"); + return -EINVAL; + } if (devinfo->dma_idx_sz != 0) { + /* The host index arrays hold one index per ring the driver uses */ + if (max_submissionrings < + BRCMF_NROF_H2D_COMMON_MSGRINGS + max_flowrings || + max_completionrings < BRCMF_NROF_D2H_COMMON_MSGRINGS) { + brcmf_err(bus, "invalid ring counts: %u submission, %u completion, %u flowrings\n", + max_submissionrings, max_completionrings, + max_flowrings); + return -EINVAL; + } bufsz = (max_submissionrings + max_completionrings) * devinfo->dma_idx_sz * 2; devinfo->idxbuf = dma_alloc_coherent(&devinfo->pdev->dev, bufsz, @@ -1624,6 +1727,21 @@ static int brcmf_pcie_init_ringbuffers(struct brcmf_pciedev_info *devinfo) h2d_w_idx_ptr = le32_to_cpu(ringinfo.h2d_w_idx_ptr); h2d_r_idx_ptr = le32_to_cpu(ringinfo.h2d_r_idx_ptr); idx_offset = sizeof(u32); + /* One index per common ring and flowring, each way */ + h2d_idx_len = (BRCMF_NROF_H2D_COMMON_MSGRINGS + max_flowrings) * + idx_offset; + d2h_idx_len = BRCMF_NROF_D2H_COMMON_MSGRINGS * idx_offset; + if (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + h2d_w_idx_ptr, h2d_idx_len) || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + h2d_r_idx_ptr, h2d_idx_len) || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + d2h_w_idx_ptr, d2h_idx_len) || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + d2h_r_idx_ptr, d2h_idx_len)) { + brcmf_err(bus, "ring indices outside the TCM\n"); + return -EINVAL; + } devinfo->write_ptr = brcmf_pcie_write_tcm16; devinfo->read_ptr = brcmf_pcie_read_tcm16; brcmf_dbg(PCIE, "Using TCM indices\n"); @@ -2014,6 +2132,12 @@ brcmf_pcie_init_share_ram_info(struct brcmf_pciedev_info *devinfo, u32 addr; shared = &devinfo->shared; + if (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, sharedram_addr, + BRCMF_SHARED_SIZE)) { + brcmf_err(bus, "shared RAM at 0x%08x is outside the TCM\n", + sharedram_addr); + return -EINVAL; + } shared->tcm_base_address = sharedram_addr; shared->flags = brcmf_pcie_read_tcm32(devinfo, sharedram_addr + @@ -2053,6 +2177,17 @@ brcmf_pcie_init_share_ram_info(struct brcmf_pciedev_info *devinfo, addr = sharedram_addr + BRCMF_SHARED_RING_INFO_ADDR_OFFSET; shared->ring_info_addr = brcmf_pcie_read_tcm32(devinfo, addr); + if (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + shared->htod_mb_data_addr, 4) || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + shared->dtoh_mb_data_addr, 4) || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + shared->ring_info_addr, + sizeof(struct brcmf_pcie_dhi_ringinfo))) { + brcmf_err(bus, "shared RAM addresses outside the TCM\n"); + return -EINVAL; + } + brcmf_dbg(PCIE, "max rx buf post %d, rx dataoffset %d\n", shared->max_rxbufpost, shared->rx_dataoffset); @@ -2392,6 +2527,7 @@ static int brcmf_pcie_get_resource(struct brcmf_pciedev_info *devinfo) devinfo->regs = ioremap(bar0_addr, BRCMF_PCIE_REG_MAP_SIZE); devinfo->tcm = ioremap(bar1_addr, bar1_size); + devinfo->tcm_size = bar1_size; if (!devinfo->regs || !devinfo->tcm) { brcmf_err(bus, "ioremap() failed (%p,%p)\n", devinfo->regs, @@ -3103,22 +3239,6 @@ brcmf_pcie_probe(struct pci_dev *pdev, const struct pci_device_id *id) brcmf_dbg(PCIE, "Enter %x:%x\n", pdev->vendor, pdev->device); - /* - * T8132's BCM4388 IOVA aperture starts above 1 TiB and the message-buffer - * ABI carries full 64-bit host addresses, so do not retain PCI's - * conservative 32-bit default DMA mask on this platform. - */ - if (pdev->device == BRCM_PCIE_4388_DEVICE_ID && - of_machine_is_compatible("apple,t8132")) { - ret = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(42)); - if (ret) { - pci_err(pdev, "failed to enable 42-bit DMA: %d\n", ret); - return ret; - } - pci_info(pdev, "using 42-bit DMA addresses\n"); - } - - ret = -ENOMEM; devinfo = kzalloc_obj(*devinfo); if (devinfo == NULL) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.h b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.h index 8e6c227e8315c8..172175d7129a01 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.h +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.h @@ -5,10 +5,18 @@ #ifndef BRCMFMAC_PCIE_H #define BRCMFMAC_PCIE_H +#include struct brcmf_pciedev { struct brcmf_bus *bus; struct brcmf_pciedev_info *devinfo; }; +/* Whether @len bytes at @offset lie within a TCM mapping of @tcm_size bytes. */ +static inline bool brcmf_pcie_tcm_range_valid(size_t tcm_size, u32 offset, + u32 len) +{ + return len <= tcm_size && offset <= tcm_size - len; +} + #endif /* BRCMFMAC_PCIE_H */ diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie_tcm_test.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie_tcm_test.c new file mode 100644 index 00000000000000..877327f20809b2 --- /dev/null +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie_tcm_test.c @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: ISC +#include +#include + +#include "pcie.h" + +static void brcmf_pcie_tcm_range(struct kunit *test) +{ + static const struct { + size_t tcm_size; + u32 offset; + u32 len; + bool valid; + } cases[] = { + { SZ_4M, 0, 8, true }, + { SZ_4M, SZ_4M - 8, 8, true }, + { SZ_4M, SZ_4M - 7, 8, false }, + { SZ_4M, SZ_4M, 8, false }, + { SZ_4M, SZ_4M, 0, true }, + { SZ_4M, U32_MAX - 3, 8, false }, + { SZ_4M, U32_MAX, 8, false }, + { 4, 0, 8, false }, + { 0, 0, 1, false }, + }; + int i; + + for (i = 0; i < ARRAY_SIZE(cases); i++) + KUNIT_EXPECT_EQ_MSG(test, + brcmf_pcie_tcm_range_valid(cases[i].tcm_size, + cases[i].offset, + cases[i].len), + cases[i].valid, "case %d", i); +} + +static struct kunit_case brcmf_pcie_tcm_cases[] = { + KUNIT_CASE(brcmf_pcie_tcm_range), + {} +}; + +static struct kunit_suite brcmf_pcie_tcm_suite = { + .name = "brcmfmac-pcie-tcm", + .test_cases = brcmf_pcie_tcm_cases, +}; + +kunit_test_suite(brcmf_pcie_tcm_suite); + +MODULE_DESCRIPTION("KUnit tests for brcmfmac PCIe TCM bounds"); +MODULE_LICENSE("Dual BSD/GPL"); diff --git a/drivers/net/wireless/mediatek/mt7932/association-test.c b/drivers/net/wireless/mediatek/mt7932/association-test.c index 08dc14c6f89e49..8f828f2b299858 100644 --- a/drivers/net/wireless/mediatek/mt7932/association-test.c +++ b/drivers/net/wireless/mediatek/mt7932/association-test.c @@ -176,6 +176,7 @@ enum mt_auth_change { MT_AUTH_NO_PASSWORD, MT_AUTH_WPA, MT_AUTH_PAIR_COUNT, MT_AUTH_PAIR, MT_AUTH_GROUP, MT_AUTH_NO_AKM, MT_AUTH_PSK_FIRST, MT_AUTH_SAE_FIRST, MT_AUTH_OTHER_FIRST, MT_AUTH_OTHER_AKM, MT_AUTH_PSK, + MT_AUTH_OWE, }; static void mt_connect_auth_test(struct kunit *test) @@ -189,6 +190,13 @@ static void mt_connect_auth_test(struct kunit *test) { "pure PSK", MT_AUTH_PSK, 0, WLAN_AKM_SUITE_PSK }, { "PSK missing PMK", MT_AUTH_PSK, 1, -EOPNOTSUPP }, { "PSK required MFP", MT_AUTH_PSK, 2, WLAN_AKM_SUITE_PSK }, + { "PSK TKIP group", MT_AUTH_PSK, 3, WLAN_AKM_SUITE_PSK }, + { "PSK TKIP pairwise", MT_AUTH_PSK, 4, -EOPNOTSUPP }, + { "PSK WEP group", MT_AUTH_PSK, 5, -EOPNOTSUPP }, + { "PSK TKIP group missing PMK", MT_AUTH_PSK, 6, -EOPNOTSUPP }, + { "PSK TKIP group WPA1", MT_AUTH_PSK, 7, -EOPNOTSUPP }, + { "OWE", MT_AUTH_OWE, WLAN_CIPHER_SUITE_CCMP, WLAN_AKM_SUITE_OWE }, + { "OWE TKIP group", MT_AUTH_OWE, WLAN_CIPHER_SUITE_TKIP, -EOPNOTSUPP }, { "pure SAE", MT_AUTH_NONE, 0, WLAN_AKM_SUITE_SAE }, { "optional MFP", MT_AUTH_MFP, NL80211_MFP_OPTIONAL, WLAN_AKM_SUITE_SAE }, { "no MFP", MT_AUTH_MFP, NL80211_MFP_NO, -EOPNOTSUPP }, @@ -213,7 +221,7 @@ static void mt_connect_auth_test(struct kunit *test) { "no pairwise", MT_AUTH_PAIR_COUNT, 0, -EOPNOTSUPP }, { "multiple pairwise", MT_AUTH_PAIR_COUNT, 2, -EOPNOTSUPP }, { "TKIP pairwise", MT_AUTH_PAIR, WLAN_CIPHER_SUITE_TKIP, -EOPNOTSUPP }, - { "TKIP group", MT_AUTH_GROUP, WLAN_CIPHER_SUITE_TKIP, -EOPNOTSUPP }, + { "SAE TKIP group", MT_AUTH_GROUP, WLAN_CIPHER_SUITE_TKIP, -EOPNOTSUPP }, { "no AKM", MT_AUTH_NO_AKM, 0, -EOPNOTSUPP }, { "SAE EXT KEY", MT_AUTH_OTHER_AKM, SUITE(0x000fac, 24), -EOPNOTSUPP }, { "PSK SHA256", MT_AUTH_OTHER_AKM, WLAN_AKM_SUITE_PSK_SHA256, -EOPNOTSUPP }, @@ -226,6 +234,8 @@ static void mt_connect_auth_test(struct kunit *test) { "PSK first mixed versions", MT_AUTH_PSK_FIRST, 4, WLAN_AKM_SUITE_PSK }, { "PSK first VERSION_3 only", MT_AUTH_PSK_FIRST, 5, -EOPNOTSUPP }, { "SAE first mixed versions", MT_AUTH_SAE_FIRST, 2, WLAN_AKM_SUITE_SAE }, + { "SAE first TKIP group", MT_AUTH_SAE_FIRST, 3, -EOPNOTSUPP }, + { "PSK first TKIP group", MT_AUTH_PSK_FIRST, 6, WLAN_AKM_SUITE_PSK }, { "unsupported AKM before SAE", MT_AUTH_OTHER_FIRST, 0, -EOPNOTSUPP }, }; u8 password[64] = {}, pmk[32] = {}; @@ -287,11 +297,26 @@ static void mt_connect_auth_test(struct kunit *test) case MT_AUTH_PSK: p.crypto.wpa_versions = NL80211_WPA_VERSION_2; p.crypto.akm_suites[0] = WLAN_AKM_SUITE_PSK; - p.crypto.psk = value == 1 ? NULL : pmk; + p.crypto.psk = value == 1 || value == 6 ? NULL : pmk; p.crypto.sae_pwd = NULL; p.crypto.sae_pwd_len = 0; p.auth_type = NL80211_AUTHTYPE_AUTOMATIC; p.mfp = value == 2 ? NL80211_MFP_REQUIRED : NL80211_MFP_NO; + if (value == 3 || value == 4 || value == 6 || value == 7) + p.crypto.cipher_group = WLAN_CIPHER_SUITE_TKIP; + if (value == 4) + p.crypto.ciphers_pairwise[0] = WLAN_CIPHER_SUITE_TKIP; + if (value == 5) + p.crypto.cipher_group = WLAN_CIPHER_SUITE_WEP40; + if (value == 7) + p.crypto.wpa_versions = NL80211_WPA_VERSION_1; + break; + case MT_AUTH_OWE: + p.crypto.akm_suites[0] = WLAN_AKM_SUITE_OWE; + p.crypto.cipher_group = value; + p.crypto.sae_pwd = NULL; + p.crypto.sae_pwd_len = 0; + p.auth_type = NL80211_AUTHTYPE_OPEN_SYSTEM; break; case MT_AUTH_PSK_FIRST: p.crypto.wpa_versions = value == 5 ? NL80211_WPA_VERSION_3 : @@ -305,6 +330,8 @@ static void mt_connect_auth_test(struct kunit *test) p.auth_type = NL80211_AUTHTYPE_OPEN_SYSTEM; p.mfp = value == 2 ? NL80211_MFP_REQUIRED : value == 3 ? NL80211_MFP_NO : NL80211_MFP_OPTIONAL; + if (value == 6) + p.crypto.cipher_group = WLAN_CIPHER_SUITE_TKIP; break; case MT_AUTH_SAE_FIRST: p.crypto.n_akm_suites = 2; @@ -314,6 +341,8 @@ static void mt_connect_auth_test(struct kunit *test) p.crypto.sae_pwd = NULL; if (value == 2) p.crypto.wpa_versions |= NL80211_WPA_VERSION_2; + if (value == 3) + p.crypto.cipher_group = WLAN_CIPHER_SUITE_TKIP; p.mfp = NL80211_MFP_OPTIONAL; break; case MT_AUTH_OTHER_FIRST: diff --git a/drivers/net/wireless/mediatek/mt7932/association.h b/drivers/net/wireless/mediatek/mt7932/association.h index 78189eab6b279e..e6e161c84700bf 100644 --- a/drivers/net/wireless/mediatek/mt7932/association.h +++ b/drivers/net/wireless/mediatek/mt7932/association.h @@ -42,6 +42,7 @@ static inline int mt7932_connect_auth(const struct cfg80211_connect_params *p) { u32 versions = p->crypto.wpa_versions; + bool tkip_group = p->crypto.cipher_group == WLAN_CIPHER_SUITE_TKIP; /* SAE offload clients use VERSION_3; older clients use VERSION_2. * A transition request can carry both. The selected AKM still owns @@ -51,7 +52,7 @@ mt7932_connect_auth(const struct cfg80211_connect_params *p) (versions & ~(NL80211_WPA_VERSION_2 | NL80211_WPA_VERSION_3)) || p->crypto.n_ciphers_pairwise != 1 || p->crypto.ciphers_pairwise[0] != WLAN_CIPHER_SUITE_CCMP || - p->crypto.cipher_group != WLAN_CIPHER_SUITE_CCMP || + (p->crypto.cipher_group != WLAN_CIPHER_SUITE_CCMP && !tkip_group) || p->crypto.n_akm_suites < 1) return -EOPNOTSUPP; @@ -60,6 +61,13 @@ mt7932_connect_auth(const struct cfg80211_connect_params *p) p->crypto.sae_pwe)) return -EOPNOTSUPP; + /* WPA/WPA2 mixed-mode APs pair a CCMP unicast key with a TKIP group + * key. The firmware owns the handshake and both keys. Only plain + * WPA2-PSK may do this; pairwise TKIP stays refused. + */ + if (tkip_group && p->crypto.akm_suites[0] != WLAN_AKM_SUITE_PSK) + return -EOPNOTSUPP; + switch (p->crypto.akm_suites[0]) { case WLAN_AKM_SUITE_PSK: /* iwd and wpa_supplicant both send REQUIRED once they have @@ -119,6 +127,9 @@ static inline int mt7932_connect_psk_akm(u8 *body, size_t length, u32 akm) /* Validate the entire RSN payload before using capabilities for admission. * The group management suite defaults to BIP-CMAC-128 when omitted. Reject * unsupported explicit suites rather than letting firmware choose one. + * A WPA/WPA2 mixed-mode AP advertises a TKIP group cipher. Admit it for + * WPA2-PSK (AKM 2) only, as mt7932_connect_auth() does; the pairwise list + * must still offer CCMP. */ static inline int mt7932_rsn_admit(const u8 *rsn, size_t length, u32 akm, enum nl80211_mfp mfp, bool *pmf) @@ -126,11 +137,15 @@ static inline int mt7932_rsn_admit(const u8 *rsn, size_t length, u32 akm, unsigned int count, i; u16 caps = 0; bool selected = false, ccmp = false; + u32 group; *pmf = false; if (mfp > NL80211_MFP_OPTIONAL || length < 8 || - get_unaligned_le16(rsn) != 1 || - get_unaligned_be32(rsn + 2) != WLAN_CIPHER_SUITE_CCMP) + get_unaligned_le16(rsn) != 1) + return -EINVAL; + group = get_unaligned_be32(rsn + 2); + if (group != WLAN_CIPHER_SUITE_CCMP && + (group != WLAN_CIPHER_SUITE_TKIP || akm != WLAN_AKM_SUITE_PSK)) return -EINVAL; rsn += 6; length -= 6; diff --git a/drivers/net/wireless/mediatek/mt7932/mt7932.c b/drivers/net/wireless/mediatek/mt7932/mt7932.c index 2ecffad3201ec3..85eed2c4de3eb6 100644 --- a/drivers/net/wireless/mediatek/mt7932/mt7932.c +++ b/drivers/net/wireless/mediatek/mt7932/mt7932.c @@ -1239,8 +1239,8 @@ static int mt_probe(struct pci_dev *pdev, const struct pci_device_id *id) struct iommu_domain *domain; int ret; - if (!of_machine_is_compatible("apple,j700") || - !of_machine_is_compatible("apple,t8140") || pdev->devfn != 0 || + /* The radio's DT node, behind a T8140 PCIe host. */ + if (pdev->devfn != 0 || !of_device_is_compatible(pdev->dev.of_node, "pci14c3,7932") || !bridge->dev.parent || !of_device_is_compatible(bridge->dev.parent->of_node, diff --git a/drivers/net/wireless/mediatek/mt7932/pmf-lpi-test.c b/drivers/net/wireless/mediatek/mt7932/pmf-lpi-test.c index 59c9633c954df0..2dfa0eb23d00d7 100644 --- a/drivers/net/wireless/mediatek/mt7932/pmf-lpi-test.c +++ b/drivers/net/wireless/mediatek/mt7932/pmf-lpi-test.c @@ -146,6 +146,72 @@ static void mt_pmf_admission_test(struct kunit *test) 0); } +/* WPA/WPA2 mixed mode: TKIP group, CCMP and TKIP pairwise, AKMs 2, 6 and 8, + * MFPC set so that only the group cipher decides admission. + */ +static const u8 mixed_rsn[] = { + 48, 32, 1, 0, 0, 15, 172, 2, 2, 0, 0, 15, 172, 4, 0, 15, 172, 2, + 3, 0, 0, 15, 172, 2, 0, 15, 172, 6, 0, 15, 172, 8, 128, 0, +}; + +static void mt_tkip_group_admission_test(struct kunit *test) +{ + static const u32 akms[] = { WLAN_AKM_SUITE_PSK_SHA256, + WLAN_AKM_SUITE_SAE }; + u8 ies[sizeof(mixed_rsn)]; + unsigned int i; + bool pmf; + + KUNIT_EXPECT_EQ(test, + mt7932_connect_admit(mixed_rsn, sizeof(mixed_rsn), + WLAN_AKM_SUITE_PSK, + NL80211_MFP_OPTIONAL, &pmf), + 0); + KUNIT_EXPECT_TRUE(test, pmf); + memcpy(ies, mixed_rsn, sizeof(ies)); + ies[32] = 0; /* no MFPC, as most mixed-mode APs */ + KUNIT_EXPECT_EQ(test, + mt7932_connect_admit(ies, sizeof(ies), + WLAN_AKM_SUITE_PSK, + NL80211_MFP_NO, &pmf), + 0); + KUNIT_EXPECT_FALSE(test, pmf); + /* A TKIP group stays refused for every other AKM; with a CCMP group + * the same element admits them, so the group cipher is the reason. + */ + for (i = 0; i < ARRAY_SIZE(akms); i++) { + KUNIT_EXPECT_EQ(test, + mt7932_connect_admit(mixed_rsn, + sizeof(mixed_rsn), akms[i], + NL80211_MFP_OPTIONAL, + &pmf), + -EINVAL); + memcpy(ies, mixed_rsn, sizeof(ies)); + ies[7] = 4; /* CCMP group */ + KUNIT_EXPECT_EQ(test, + mt7932_connect_admit(ies, sizeof(ies), akms[i], + NL80211_MFP_OPTIONAL, + &pmf), + 0); + } + /* The pairwise list must still offer CCMP. */ + memcpy(ies, mixed_rsn, sizeof(ies)); + ies[13] = 2; + KUNIT_EXPECT_EQ(test, + mt7932_connect_admit(ies, sizeof(ies), + WLAN_AKM_SUITE_PSK, + NL80211_MFP_OPTIONAL, &pmf), + -EINVAL); + /* WEP-40 and other group suites stay refused on AKM 2. */ + memcpy(ies, mixed_rsn, sizeof(ies)); + ies[7] = 1; + KUNIT_EXPECT_EQ(test, + mt7932_connect_admit(ies, sizeof(ies), + WLAN_AKM_SUITE_PSK, + NL80211_MFP_OPTIONAL, &pmf), + -EINVAL); +} + static void mt_pmf_body_test(struct kunit *test) { static const struct mt7932_peer_ids ids = { { 1, 2 }, { 3, 4, 5, 6 } }; @@ -442,6 +508,7 @@ static void mt_6g_tpe_golden_test(struct kunit *test) static struct kunit_case mt_pmf_lpi_cases[] = { KUNIT_CASE(mt_pmf_admission_test), + KUNIT_CASE(mt_tkip_group_admission_test), KUNIT_CASE(mt_pmf_body_test), KUNIT_CASE(mt_6g_ap_test), KUNIT_CASE(mt_6g_tpe_body_test), diff --git a/drivers/net/wireless/mediatek/mt7932/startup.c b/drivers/net/wireless/mediatek/mt7932/startup.c index 7f72432235a2cf..44135f806803fd 100644 --- a/drivers/net/wireless/mediatek/mt7932/startup.c +++ b/drivers/net/wireless/mediatek/mt7932/startup.c @@ -820,6 +820,7 @@ int mt_register_regulatory_gate(struct mt7932 *m) { static const int rates[] = {10,20,55,110,60,90,120,180,240,360,480,540}; static const u32 ciphers[] = { WLAN_CIPHER_SUITE_CCMP, + WLAN_CIPHER_SUITE_TKIP, WLAN_CIPHER_SUITE_AES_CMAC }; static const u32 akms[] = { WLAN_AKM_SUITE_PSK, diff --git a/drivers/nvme/host/apple-m5-sleep.h b/drivers/nvme/host/apple-m5-sleep.h index f22d6902bf2567..50bcaeabde6043 100644 --- a/drivers/nvme/host/apple-m5-sleep.h +++ b/drivers/nvme/host/apple-m5-sleep.h @@ -167,10 +167,8 @@ static int apple_nvme_m5_attach(struct apple_nvme *anv) { int ret; - /* Both boards use T6050 ANS2's split NVMe/NVMMU layout and retained SART. */ - if (!of_machine_is_compatible("apple,t6050") || - (!of_machine_is_compatible("apple,j714s") && - !of_machine_is_compatible("apple,j716c"))) + /* T6050 ANS2's split NVMe/NVMMU layout and retained SART, where the sleep is described. */ + if (!apple_t6050_sleep_described()) return -EOPNOTSUPP; /* The wait before the restart after a sleep comes from the DT; without it, no sleep. */ if (of_property_read_u32(anv->dev->of_node, "apple,sleep-wake-delay-ms", diff --git a/drivers/nvme/host/apple.c b/drivers/nvme/host/apple.c index e4522195f9a23c..e29dd701a84844 100644 --- a/drivers/nvme/host/apple.c +++ b/drivers/nvme/host/apple.c @@ -58,6 +58,11 @@ #define APPLE_ANS_COPROC_CPU_CONTROL 0x44 #define APPLE_ANS_COPROC_CPU_CONTROL_RUN BIT(4) #define APPLE_ANS_COPROC_CPU_STATUS 0x48 +/* + * A word of the NVMe block that gates its SART (measured on M1). The boot loader leaves 1 + * here, and a firmware sleep, which takes ANS's power, leaves 0: put back before ANS runs again. + */ +#define APPLE_ANS_SART_POWER 0x13e8 #define APPLE_ANS_ACQ_DB 0x1004 #define APPLE_ANS_IOCQ_DB 0x100c @@ -75,6 +80,15 @@ #define APPLE_ANS_LINEAR_ASQ_DB 0x2490c #define APPLE_ANS_LINEAR_IOSQ_DB 0x24910 +/* + * ADT nvme-secure-reg-layout (T8152, macOS AppleANS2NVMeController with its + * 0x92a flag set): AQA/ASQ/ACQ and the I/O queue registers move up by + * 0x4000 and LINEAR_SQ_CTRL moves into the NVMMU block. CC/CSTS, the + * doorbells and the NVMMU TCB registers stay where they are. + */ +#define APPLE_ANS_SECURE_QREG_SHIFT 0x4000 +#define APPLE_ANS_SECURE_LINEAR_SQ_CTRL 0x2813c + #define APPLE_NVMMU_NUM_TCBS 0x28100 #define APPLE_NVMMU_ASQ_TCB_BASE 0x28108 #define APPLE_NVMMU_IOSQ_TCB_BASE 0x28110 @@ -183,11 +197,6 @@ static inline void apple_nvme_enable_queue(struct apple_nvme_queue *q) smp_store_release(&q->enabled, true); } -static inline void apple_nvme_disable_queue(struct apple_nvme_queue *q) -{ - WRITE_ONCE(q->enabled, false); -} - /* * The apple_nvme_iod describes the data in an I/O. * @@ -203,6 +212,7 @@ struct apple_nvme_iod { dma_addr_t first_dma; unsigned int dma_len; /* length of single DMA segment mapping */ struct scatterlist *sg; + bool irq_counted; }; struct apple_nvme_hw { @@ -231,6 +241,11 @@ struct apple_nvme_hw { u32 sleep_shn; /* The ANS is never reset through PMGR here, so no reset is named. */ bool reset_optional; + /* Pre-M4 controller that warm-idles and warm-restarts across deep sleep. */ + bool warm_sleep; + bool secure_reg_layout; + /* Also send the NVMe shutdown notification (CC.SHN) on removal. */ + bool shutdown_notify; u32 max_queue_depth; unsigned long quirks; }; @@ -262,11 +277,18 @@ struct apple_nvme { u32 sleep_csts; /* ANS came back across a sleep, or failed to. reset_work picks these up. */ bool sleep_restarted; + /* A firmware sleep took ANS's power: its next start is from that power-on */ + bool fw_sleep_restart; + /* This suspend idled ANS for a firmware sleep, whether or not the sleep happened */ + bool fw_sleep_idled; + /* The SART power word as it was before that sleep */ + u32 sart_power; bool sleep_failed; /* Run bit set after a sleep, and not yet reported on. */ bool sleep_restarting; ktime_t sleep_run_time; bool sleep_registered; + bool t8122_warm_sleep; unsigned long recovery_flags; void __iomem *mmio_coproc; @@ -300,6 +322,10 @@ struct apple_nvme { int irq; spinlock_t lock; + /* Non-polled (admin + interrupt I/O) requests submitted to hardware. */ + unsigned int irq_inflight; + /* A poller consumed completions the CQ interrupt was raised for. */ + bool polled_cqes; /* * Delayed cache flush handling state @@ -439,6 +465,17 @@ static int apple_nvme_read_handoff(struct apple_nvme *anv) return apple_nvme_can_adopt_rtkit(anv) ? 0 : -EIO; } +static u32 apple_nvme_qreg(const struct apple_nvme *anv, u32 reg) +{ + return anv->hw->secure_reg_layout ? reg + APPLE_ANS_SECURE_QREG_SHIFT : reg; +} + +static u32 apple_nvme_lsq_ctrl(const struct apple_nvme *anv) +{ + return anv->hw->secure_reg_layout ? APPLE_ANS_SECURE_LINEAR_SQ_CTRL : + APPLE_ANS_LINEAR_SQ_CTRL; +} + static inline struct apple_nvme *queue_to_apple_nvme(struct apple_nvme_queue *q) { if (q->is_adminq) @@ -447,6 +484,41 @@ static inline struct apple_nvme *queue_to_apple_nvme(struct apple_nvme_queue *q) return container_of(q, struct apple_nvme, ioq); } +static inline void apple_nvme_disable_queue(struct apple_nvme_queue *q) +{ + struct apple_nvme *anv = queue_to_apple_nvme(q); + unsigned long flags; + + spin_lock_irqsave(&anv->lock, flags); + WRITE_ONCE(q->enabled, false); + spin_unlock_irqrestore(&anv->lock, flags); +} + +static inline void apple_nvme_account_irq_submit(struct apple_nvme_queue *q, + struct request *req) +{ + struct apple_nvme *anv = queue_to_apple_nvme(q); + struct apple_nvme_iod *iod = blk_mq_rq_to_pdu(req); + + lockdep_assert_held(&anv->lock); + if (q->is_adminq || !(req->cmd_flags & REQ_POLLED)) { + iod->irq_counted = true; + anv->irq_inflight++; + } +} + +static inline void apple_nvme_account_irq_done(struct apple_nvme *anv, + struct request *req) +{ + struct apple_nvme_iod *iod = blk_mq_rq_to_pdu(req); + + lockdep_assert_held(&anv->lock); + if (iod->irq_counted) { + iod->irq_counted = false; + anv->irq_inflight--; + } +} + static unsigned int apple_nvme_queue_depth(struct apple_nvme_queue *q) { struct apple_nvme *anv = queue_to_apple_nvme(q); @@ -633,7 +705,8 @@ static void apple_nvmmu_inval(struct apple_nvme_queue *q, unsigned int tag) } static void apple_nvme_submit_cmd_t8015(struct apple_nvme_queue *q, - struct nvme_command *cmd) + struct nvme_command *cmd, + struct request *req) { struct apple_nvme *anv = queue_to_apple_nvme(q); @@ -648,6 +721,7 @@ static void apple_nvme_submit_cmd_t8015(struct apple_nvme_queue *q, if (++q->sq_tail == apple_nvme_queue_depth(q)) q->sq_tail = 0; + apple_nvme_account_irq_submit(q, req); writel(q->sq_tail, q->sq_db); spin_unlock_irq(&anv->lock); } @@ -697,6 +771,7 @@ static void apple_nvme_submit_cmd_t8103(struct apple_nvme_queue *q, * and the final CQ update. */ spin_lock_irq(&anv->lock); + apple_nvme_account_irq_submit(q, req); writel(tag, q->sq_db); spin_unlock_irq(&anv->lock); } @@ -964,6 +1039,22 @@ static void apple_nvme_complete_batch(struct io_comp_batch *iob) nvme_complete_batch(iob, apple_nvme_unmap_rq); } +static void apple_nvme_complete_direct(struct rq_list *list) +{ + struct request *req; + + while ((req = rq_list_pop(list)) != NULL) + apple_nvme_complete_rq(req); +} + +static void apple_nvme_finish_completions(struct io_comp_batch *iob, + struct rq_list *direct) +{ + if (!rq_list_empty(&iob->req_list)) + apple_nvme_complete_batch(iob); + apple_nvme_complete_direct(direct); +} + static inline bool apple_nvme_cqe_pending(struct apple_nvme_queue *q) { struct nvme_completion *hcqe = &q->cqes[q->cq_head]; @@ -981,7 +1072,8 @@ apple_nvme_queue_tagset(struct apple_nvme *anv, struct apple_nvme_queue *q) } static inline void apple_nvme_handle_cqe(struct apple_nvme_queue *q, - struct io_comp_batch *iob, u16 idx) + struct io_comp_batch *iob, + struct rq_list *direct, u16 idx) { struct apple_nvme *anv = queue_to_apple_nvme(q); struct nvme_completion *cqe = &q->cqes[idx]; @@ -997,11 +1089,13 @@ static inline void apple_nvme_handle_cqe(struct apple_nvme_queue *q, return; } + apple_nvme_account_irq_done(anv, req); + if (!nvme_try_complete_req(req, cqe->status, cqe->result) && !blk_mq_add_to_batch(req, iob, nvme_req(req)->status != NVME_SC_SUCCESS, apple_nvme_complete_batch)) - apple_nvme_complete_rq(req); + rq_list_add_tail(direct, req); } static inline void apple_nvme_update_cq_head(struct apple_nvme_queue *q) @@ -1017,7 +1111,8 @@ static inline void apple_nvme_update_cq_head(struct apple_nvme_queue *q) } static bool apple_nvme_poll_cq(struct apple_nvme_queue *q, - struct io_comp_batch *iob) + struct io_comp_batch *iob, + struct rq_list *direct) { bool found = false; @@ -1029,7 +1124,7 @@ static bool apple_nvme_poll_cq(struct apple_nvme_queue *q, * the cqe requires a full read memory barrier */ dma_rmb(); - apple_nvme_handle_cqe(q, iob, q->cq_head); + apple_nvme_handle_cqe(q, iob, direct, q->cq_head); apple_nvme_update_cq_head(q); } @@ -1039,27 +1134,39 @@ static bool apple_nvme_poll_cq(struct apple_nvme_queue *q, return found; } -static bool apple_nvme_handle_cq(struct apple_nvme_queue *q, bool force) +static bool apple_nvme_drain_cq(struct apple_nvme_queue *q, bool force, + struct io_comp_batch *iob, + struct rq_list *direct) { - bool found; - DEFINE_IO_COMP_BATCH(iob); - if (!apple_nvme_queue_enabled(q) && !force) return false; - found = apple_nvme_poll_cq(q, &iob); + return apple_nvme_poll_cq(q, iob, direct); +} - if (!rq_list_empty(&iob.req_list)) - apple_nvme_complete_batch(&iob); +static bool apple_nvme_handle_cq(struct apple_nvme_queue *q, bool force) +{ + struct apple_nvme *anv = queue_to_apple_nvme(q); + DEFINE_IO_COMP_BATCH(iob); + struct rq_list direct = {}; + unsigned long flags; + bool found; + spin_lock_irqsave(&anv->lock, flags); + found = apple_nvme_drain_cq(q, force, &iob, &direct); + spin_unlock_irqrestore(&anv->lock, flags); + + apple_nvme_finish_completions(&iob, &direct); return found; } -static bool apple_nvme_handle_queues(struct apple_nvme *anv) +static bool apple_nvme_handle_queues(struct apple_nvme *anv, + struct io_comp_batch *iob, + struct rq_list *direct) { - bool found = apple_nvme_handle_cq(&anv->ioq, false); + bool found = apple_nvme_drain_cq(&anv->ioq, false, iob, direct); - found |= apple_nvme_handle_cq(&anv->adminq, false); + found |= apple_nvme_drain_cq(&anv->adminq, false, iob, direct); return found; } @@ -1072,7 +1179,9 @@ static bool apple_nvme_handle_queues(struct apple_nvme *anv) */ #define APPLE_NVME_LATE_CQE_US 100 -static bool apple_nvme_wait_late_cqe(struct apple_nvme *anv) +static bool apple_nvme_wait_late_cqe(struct apple_nvme *anv, + struct io_comp_batch *iob, + struct rq_list *direct) { ktime_t end; @@ -1083,7 +1192,7 @@ static bool apple_nvme_wait_late_cqe(struct apple_nvme *anv) end = ktime_add_us(ktime_get(), APPLE_NVME_LATE_CQE_US); do { udelay(1); - if (apple_nvme_handle_queues(anv)) + if (apple_nvme_handle_queues(anv, iob, direct)) return true; } while (ktime_before(ktime_get(), end)); @@ -1093,17 +1202,30 @@ static bool apple_nvme_wait_late_cqe(struct apple_nvme *anv) static irqreturn_t apple_nvme_irq(int irq, void *data) { struct apple_nvme *anv = data; + DEFINE_IO_COMP_BATCH(iob); + struct rq_list direct = {}; unsigned long flags; - bool handled; + bool handled, polled; if (apple_nvme_m5_fenced(anv)) return IRQ_NONE; spin_lock_irqsave(&anv->lock, flags); - handled = apple_nvme_handle_queues(anv); - if (!handled) - handled = apple_nvme_wait_late_cqe(anv); + handled = apple_nvme_handle_queues(anv, &iob, &direct); + polled = anv->polled_cqes; + anv->polled_cqes = false; + /* + * The CQ keeps its interrupt when the queue is also polled, and a + * poller usually reaps the entry before this handler runs. Skip the + * late-CQE wait only when no interrupt-driven or admin command is in + * flight, and still claim the interrupt if a poller reaped entries. + */ + if (!handled && (anv->irq_inflight || !polled)) + handled = apple_nvme_wait_late_cqe(anv, &iob, &direct); + if (!handled && polled) + handled = true; spin_unlock_irqrestore(&anv->lock, flags); + apple_nvme_finish_completions(&iob, &direct); return handled ? IRQ_HANDLED : IRQ_NONE; } @@ -1210,6 +1332,7 @@ static blk_status_t apple_nvme_queue_rq(struct blk_mq_hw_ctx *hctx, iod->npages = -1; iod->nents = 0; + iod->irq_counted = false; /* * We should not need to do this, but we're still using this to @@ -1257,7 +1380,7 @@ static blk_status_t apple_nvme_queue_rq(struct blk_mq_hw_ctx *hctx, if (anv->hw->has_lsq_nvmmu) apple_nvme_submit_cmd_t8103(q, cmnd, req); else - apple_nvme_submit_cmd_t8015(q, cmnd); + apple_nvme_submit_cmd_t8015(q, cmnd, req); return BLK_STS_OK; @@ -1349,14 +1472,17 @@ static void apple_nvme_disable_legacy(struct apple_nvme *anv, bool shutdown) nvme_quiesce_admin_queue(&anv->ctrl); /* last chance to complete any requests before nvme_cancel_request */ - spin_lock_irqsave(&anv->lock, flags); apple_nvme_handle_cq(&anv->ioq, true); apple_nvme_handle_cq(&anv->adminq, true); - spin_unlock_irqrestore(&anv->lock, flags); nvme_cancel_tagset(&anv->ctrl); nvme_cancel_admin_tagset(&anv->ctrl); + spin_lock_irqsave(&anv->lock, flags); + anv->irq_inflight = 0; + anv->polled_cqes = false; + spin_unlock_irqrestore(&anv->lock, flags); + /* * The driver will not be starting up queues again if shutting down so * must flush all entered requests to their failed completion to avoid @@ -1429,10 +1555,13 @@ static int apple_nvme_disable_locked(struct apple_nvme *anv, bool shutdown) * The final system shutdown is the exception for SHN: without it the * controller counts every Linux shutdown as unsafe (SMART * unsafe_shutdowns) and recovers on the next start, which slows the - * loader and the first seconds of I/O. A failed SHN changes nothing: - * the CC.EN clear below still runs. + * loader and the first seconds of I/O. Where the firmware handles it, + * removal sends it too. A failed SHN changes nothing: the CC.EN clear + * below still runs. */ - if (READ_ONCE(anv->final_shutdown) && !apple_rtkit_is_crashed(anv->rtk)) { + if ((READ_ONCE(anv->final_shutdown) || + (shutdown && anv->hw->shutdown_notify && READ_ONCE(anv->removing))) && + !apple_rtkit_is_crashed(anv->rtk)) { ret = nvme_disable_ctrl(&anv->ctrl, true); if (ret) dev_warn(anv->dev, "shutdown notification failed: %d\n", ret); @@ -1443,12 +1572,14 @@ static int apple_nvme_disable_locked(struct apple_nvme *anv, bool shutdown) return ret; } - spin_lock_irqsave(&anv->lock, flags); apple_nvme_handle_cq(&anv->ioq, true); apple_nvme_handle_cq(&anv->adminq, true); - spin_unlock_irqrestore(&anv->lock, flags); nvme_cancel_tagset(&anv->ctrl); nvme_cancel_admin_tagset(&anv->ctrl); + spin_lock_irqsave(&anv->lock, flags); + anv->irq_inflight = 0; + anv->polled_cqes = false; + spin_unlock_irqrestore(&anv->lock, flags); if (shutdown) { nvme_unquiesce_io_queues(&anv->ctrl); nvme_unquiesce_admin_queue(&anv->ctrl); @@ -1534,7 +1665,6 @@ static enum blk_eh_timer_return apple_nvme_timeout(struct request *req) struct apple_nvme *anv = queue_to_apple_nvme(q); struct nvme_completion *cqe = &q->cqes[q->cq_head]; enum nvme_ctrl_state state = nvme_ctrl_state(&anv->ctrl); - unsigned long flags; u32 cc, csts; if (blk_mq_request_completed(req)) @@ -1550,9 +1680,7 @@ static enum blk_eh_timer_return apple_nvme_timeout(struct request *req) * interrupt cannot turn a completed initialization command into a reset. */ if (!apple_rtkit_is_crashed(anv->rtk) && !(csts & NVME_CSTS_CFS)) { - spin_lock_irqsave(&anv->lock, flags); apple_nvme_handle_cq(q, false); - spin_unlock_irqrestore(&anv->lock, flags); if (blk_mq_request_completed(req)) { dev_warn(anv->dev, "I/O %d(aq:%d) timeout in state %d: completion polled\n", @@ -1626,6 +1754,11 @@ static enum blk_eh_timer_return apple_nvme_timeout(struct request *req) READ_ONCE(cqe->command_id)); if (blk_mq_request_started(req) && !blk_mq_request_completed(req)) { + unsigned long flags; + + spin_lock_irqsave(&anv->lock, flags); + apple_nvme_account_irq_done(anv, req); + spin_unlock_irqrestore(&anv->lock, flags); nvme_req(req)->status = NVME_SC_HOST_ABORTED_CMD; nvme_req(req)->flags |= NVME_REQ_CANCELLED; blk_mq_complete_request(req); @@ -1653,19 +1786,41 @@ static int apple_nvme_poll(struct blk_mq_hw_ctx *hctx, { struct apple_nvme_queue *q = hctx->driver_data; struct apple_nvme *anv = queue_to_apple_nvme(q); - bool found; + struct rq_list direct = {}; + bool found = false; unsigned long flags; - if (apple_nvme_m5_retained(anv) || READ_ONCE(anv->detached) || - apple_nvme_m5_fenced(anv)) - return 0; spin_lock_irqsave(&anv->lock, flags); - found = apple_nvme_poll_cq(q, iob); + if (!apple_nvme_m5_retained(anv) && !READ_ONCE(anv->detached) && + !apple_nvme_m5_fenced(anv)) { + found = apple_nvme_drain_cq(q, false, iob, &direct); + if (found) + anv->polled_cqes = true; + } spin_unlock_irqrestore(&anv->lock, flags); + apple_nvme_complete_direct(&direct); return found; } +/* + * There is one I/O queue. Map a second hardware context (HCTX_TYPE_POLL) onto + * it with shared tags so polled I/O (io_uring IOPOLL, RWF_HIPRI) works while + * keeping tags unique across both contexts as the NVMMU requires. + */ +static void apple_nvme_map_queues(struct blk_mq_tag_set *set) +{ + set->map[HCTX_TYPE_DEFAULT].nr_queues = 1; + set->map[HCTX_TYPE_DEFAULT].queue_offset = 0; + blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]); + if (set->nr_maps <= HCTX_TYPE_POLL) + return; + set->map[HCTX_TYPE_READ].nr_queues = 0; + set->map[HCTX_TYPE_POLL].nr_queues = 1; + set->map[HCTX_TYPE_POLL].queue_offset = 1; + blk_mq_map_queues(&set->map[HCTX_TYPE_POLL]); +} + static const struct blk_mq_ops apple_nvme_mq_admin_ops = { .queue_rq = apple_nvme_queue_rq, .complete = apple_nvme_complete_rq, @@ -1681,6 +1836,7 @@ static const struct blk_mq_ops apple_nvme_mq_ops = { .init_request = apple_nvme_init_request, .timeout = apple_nvme_timeout, .poll = apple_nvme_poll, + .map_queues = apple_nvme_map_queues, }; static void apple_nvme_init_queue(struct apple_nvme_queue *q) @@ -1755,6 +1911,8 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) container_of(work, struct apple_nvme, ctrl.reset_work); enum nvme_ctrl_state state = nvme_ctrl_state(&anv->ctrl); bool inherited = !anv->owns_rtkit; + bool fw_sleep; + bool warm_restarted = false; if (anv->hw->needs_ioq_registers) { mutex_lock(&anv->disable_lock); @@ -1861,6 +2019,11 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) goto out; goto rtkit_ready; } + if (READ_ONCE(anv->sleep_restarted)) { + WRITE_ONCE(anv->sleep_restarted, false); + warm_restarted = true; + goto rtkit_ready; + } /* reset the controller if it is enabled */ if (anv->ctrl.ctrl_config & NVME_CC_ENABLE) apple_nvme_disable_legacy(anv, false); @@ -1895,6 +2058,9 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) goto booted; } + fw_sleep = READ_ONCE(anv->fw_sleep_restart); + WRITE_ONCE(anv->fw_sleep_restart, false); + ret = reset_control_assert(anv->reset); if (ret) goto out; @@ -1907,10 +2073,31 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) if (ret) goto out; + /* + * After a firmware sleep, out of reset and before the run bit: the SART's + * power word, and the mailbox's enables, which went with ANS's power. + * On T8122 (which shares the ANS reset with SART), replay saved SART + * entries before starting ANS (no-op on cold boot when replay_valid is false). + */ + if (fw_sleep) { + if (readl(anv->mmio_nvme + APPLE_ANS_SART_POWER) != anv->sart_power) + writel(anv->sart_power, anv->mmio_nvme + APPLE_ANS_SART_POWER); + /* Only after a sleep that didn't happen: the wake wrote them already. */ + if (anv->sart) + apple_sart_restore_early(anv->sart); + ret = apple_rtkit_mbox_restore(anv->rtk); + if (ret) + goto out; + } else if (anv->sart) { + apple_sart_replay(anv->sart); + } + writel(APPLE_ANS_COPROC_CPU_CONTROL_RUN, anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL); ret = apple_rtkit_boot(anv->rtk); + if (fw_sleep && !ret) + dev_info(anv->dev, "ANS: on after the sleep\n"); } else { ret = apple_rtkit_wake(anv->rtk); } @@ -1946,12 +2133,14 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) * queues. Woken this way, it would ignore the queue registers below, * which may only change while CC.EN is clear. Disable it first. */ - if (inherited && !anv->hw->needs_ioq_registers) { + if ((inherited || warm_restarted) && !anv->hw->needs_ioq_registers) { anv->ctrl.cap = readq(anv->mmio_nvme + NVME_REG_CAP); anv->ctrl.ctrl_config = readl(anv->mmio_nvme + NVME_REG_CC); if (anv->ctrl.ctrl_config & NVME_CC_ENABLE) { dev_info(anv->dev, - "controller handed over enabled, disabling it\n"); + "controller %s enabled, disabling it\n", + warm_restarted ? "retained after warm restart" : + "handed over"); ret = nvme_disable_ctrl(&anv->ctrl, false); if (ret) goto out; @@ -1976,10 +2165,10 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) */ if (!anv->lsq_in_nvmmu) { writel(APPLE_ANS_LINEAR_SQ_EN, - anv->mmio_nvme + APPLE_ANS_LINEAR_SQ_CTRL); + anv->mmio_nvme + apple_nvme_lsq_ctrl(anv)); if (anv->hw->needs_ioq_registers) { u32 lsq_ctrl = readl(anv->mmio_nvme + - APPLE_ANS_LINEAR_SQ_CTRL); + apple_nvme_lsq_ctrl(anv)); if (!(lsq_ctrl & APPLE_ANS_LINEAR_SQ_EN)) { dev_err(anv->dev, @@ -2002,9 +2191,11 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) if (anv->hw->needs_ioq_registers) ioqa_depth--; ioqa = ioqa_depth | (ioqa_depth << 16); - writel(ioqa, anv->mmio_nvme + APPLE_ANS_MAX_PEND_CMDS_CTRL); + writel(ioqa, anv->mmio_nvme + + apple_nvme_qreg(anv, APPLE_ANS_MAX_PEND_CMDS_CTRL)); if (anv->hw->needs_ioq_registers && - readl(anv->mmio_nvme + APPLE_ANS_MAX_PEND_CMDS_CTRL) != ioqa) { + readl(anv->mmio_nvme + + apple_nvme_qreg(anv, APPLE_ANS_MAX_PEND_CMDS_CTRL)) != ioqa) { dev_err(anv->dev, "failed to program I/O queue aperture\n"); ret = -EIO; goto out; @@ -2018,11 +2209,11 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) /* Setup the admin queue */ aqa = APPLE_NVME_AQ_DEPTH - 1; aqa |= aqa << 16; - writel(aqa, anv->mmio_nvme + NVME_REG_AQA); + writel(aqa, anv->mmio_nvme + apple_nvme_qreg(anv, NVME_REG_AQA)); apple_nvme_writeq(anv, anv->adminq.sq_dma_addr, - anv->mmio_nvme + NVME_REG_ASQ); + anv->mmio_nvme + apple_nvme_qreg(anv, NVME_REG_ASQ)); apple_nvme_writeq(anv, anv->adminq.cq_dma_addr, - anv->mmio_nvme + NVME_REG_ACQ); + anv->mmio_nvme + apple_nvme_qreg(anv, NVME_REG_ACQ)); if (anv->hw->has_lsq_nvmmu) { /* Setup NVMMU for both queues */ @@ -2094,10 +2285,10 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) * dedicated registers. Without them it crashes and its crash log * reports null I/O SQ and CQ addresses. */ - apple_nvme_writeq(anv, anv->ioq.cq_dma_addr, - anv->mmio_nvme + APPLE_ANS_IOCQ_REGISTER); - apple_nvme_writeq(anv, anv->ioq.sq_dma_addr, - anv->mmio_nvme + APPLE_ANS_IOSQ_REGISTER); + apple_nvme_writeq(anv, anv->ioq.cq_dma_addr, anv->mmio_nvme + + apple_nvme_qreg(anv, APPLE_ANS_IOCQ_REGISTER)); + apple_nvme_writeq(anv, anv->ioq.sq_dma_addr, anv->mmio_nvme + + apple_nvme_qreg(anv, APPLE_ANS_IOSQ_REGISTER)); } nr_io_queues = 1; if (anv->hw->has_queue_count) { @@ -2135,7 +2326,7 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) } else { nvme_wait_freeze(&anv->ctrl); } - blk_mq_update_nr_hw_queues(&anv->tagset, 1); + blk_mq_update_nr_hw_queues(&anv->tagset, anv->tagset.nr_hw_queues); if (!READ_ONCE(anv->m5.rebuild_active)) { nvme_unfreeze(&anv->ctrl); if (anv->hw->m5_sleep) @@ -2328,8 +2519,8 @@ static int apple_nvme_alloc_tagsets(struct apple_nvme *anv) return ret; anv->tagset.ops = &apple_nvme_mq_ops; - anv->tagset.nr_hw_queues = 1; - anv->tagset.nr_maps = 1; + anv->tagset.nr_hw_queues = 2; + anv->tagset.nr_maps = HCTX_MAX_TYPES; /* * Tags are used as an index to the NVMMU and must be unique across * both queues. The admin queue gets the first APPLE_NVME_AQ_DEPTH which @@ -2348,8 +2539,11 @@ static int apple_nvme_alloc_tagsets(struct apple_nvme *anv) * dispatched from a kblockd worker instead of the submitting task, * which adds a context switch to each I/O. Start without a scheduler, * as PCIe NVMe controllers do; one can still be selected through sysfs. + * Share tags across the default and poll hardware contexts so every + * tag maps to a unique NVMMU TCB slot. */ - anv->tagset.flags = BLK_MQ_F_NO_SCHED_BY_DEFAULT; + anv->tagset.flags = BLK_MQ_F_TAG_HCTX_SHARED | + BLK_MQ_F_NO_SCHED_BY_DEFAULT; ret = blk_mq_alloc_tag_set(&anv->tagset); if (ret) @@ -2572,6 +2766,8 @@ static struct apple_nvme *apple_nvme_alloc(struct platform_device *pdev) return ERR_PTR(ret); anv->adminq.is_adminq = true; platform_set_drvdata(pdev, anv); + /* Its resume waits on the coprocessor (0.2 to 0.9 s after a real sleep): not in the others' way. */ + device_enable_async_suspend(&pdev->dev); anv->hw = of_device_get_match_data(&pdev->dev); if (!anv->hw) { @@ -2988,6 +3184,36 @@ static void apple_nvme_shutdown(struct platform_device *pdev) * macOS. The wait for on doesn't: macOS rings the SEP a few ms after ANS's HELLO, before ANS * reports on, so the reset work waits, after the SEP's own resume has had its turn. */ +static void apple_nvme_t8122_warm_resume(struct apple_nvme *anv) +{ + void __iomem *control = anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL; + int ret; + + if (!xchg(&anv->t8122_warm_sleep, false)) + return; + + /* + * A sleep refused before the commit left ANS powered, so a warm + * restart without a power cycle can hang; fall back to the cold PMGR + * reset path in apple_nvme_reset_work_impl(). + */ + if (!pm_resume_via_firmware()) + return; + + apple_sleep_restore_pins(); + if (anv->sart) + apple_sart_replay(anv->sart); + apple_rtkit_set_warm_epmap_mask(anv->rtk, BIT(0)); + anv->sleep_run_time = ktime_get(); + ret = apple_rtkit_sleep_return_start(anv->rtk, control); + if (ret) { + dev_err(anv->dev, "ANS warm restart failed: %d\n", ret); + anv->sleep_failed = true; + } else { + WRITE_ONCE(anv->sleep_restarting, true); + } +} + static int apple_nvme_resume_early(struct device *dev) { struct apple_nvme *anv = dev_get_drvdata(dev); @@ -2998,7 +3224,11 @@ static int apple_nvme_resume_early(struct device *dev) READ_ONCE(anv->m5.phase) != APPLE_M5_ANS_LIVE) return apple_nvme_m5_resume_early(anv); - if (!anv->hw->needs_ioq_registers || !anv->suspended || !anv->sleep_idled) + if (!anv->hw->needs_ioq_registers) { + apple_nvme_t8122_warm_resume(anv); + return 0; + } + if (!anv->suspended || !anv->sleep_idled) return 0; anv->sleep_idled = false; if (anv->sleep_stop) @@ -3083,6 +3313,22 @@ static int apple_nvme_resume(struct device *dev) WRITE_ONCE(anv->suspended, false); return nvme_try_sched_reset(&anv->ctrl); } + if (anv->hw->warm_sleep) { + apple_nvme_t8122_warm_resume(anv); + if (READ_ONCE(anv->sleep_failed)) { + dev_crit(dev, "holding all I/O: ANS is down after the sleep, reboot to recover\n"); + return 0; + } + } else { + /* + * A firmware sleep took ANS's power: the reset work starts it from that power-on. + * A sleep that didn't happen after ANS was idled for it leaves it idle with its + * SART gated: the same start, from its reset, with the SART's entries written back. + */ + if (anv->rtk && (pm_resume_via_firmware() || anv->fw_sleep_idled)) + WRITE_ONCE(anv->fw_sleep_restart, true); + anv->fw_sleep_idled = false; + } return nvme_reset_ctrl(&anv->ctrl); } @@ -3243,9 +3489,49 @@ static int apple_nvme_suspend(struct device *dev) } if (apple_rtkit_is_running(anv->rtk)) { - ret = apple_rtkit_shutdown(anv->rtk); + if (anv->hw->warm_sleep && + pm_suspend_target_state == PM_SUSPEND_MEM && + pm_suspend_via_firmware() && + !apple_sleep_dry_run()) { + anv->sleep_failed = false; + anv->sleep_restarted = false; + ret = apple_rtkit_idle(anv->rtk); + if (ret) { + dev_err(dev, "ANS warm idle failed: %d\n", ret); + return ret; + } + writel(0, anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL); + WRITE_ONCE(anv->t8122_warm_sleep, true); + return 0; + } + if (!anv->hw->warm_sleep && + pm_suspend_target_state == PM_SUSPEND_MEM && + pm_suspend_via_firmware()) { + /* + * A firmware sleep takes ANS's power. ANS is put in IDLE, both + * the AP's state and its own, as for a sleep it is woken from: + * after its power-on it then brings its flash links back itself. + * In IDLE it gates its SART, so the SART's entries and the word + * that gates it are read before that. + */ + anv->sart_power = readl(anv->mmio_nvme + APPLE_ANS_SART_POWER); + if (anv->sart) + apple_sart_save_now(anv->sart); + anv->fw_sleep_idled = true; + ret = apple_rtkit_idle(anv->rtk); + if (!ret) + ret = apple_rtkit_reinit(anv->rtk); + } else { + ret = apple_rtkit_shutdown(anv->rtk); + } writel(0, anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL); + /* Refused here, so no resume follows: ANS starts again now, from its reset. */ + if (ret && anv->fw_sleep_idled) { + anv->fw_sleep_idled = false; + WRITE_ONCE(anv->fw_sleep_restart, true); + nvme_reset_ctrl(&anv->ctrl); + } } return ret; @@ -3268,6 +3554,13 @@ static const struct apple_nvme_hw apple_nvme_t8103_hw = { .max_queue_depth = 64, }; +static const struct apple_nvme_hw apple_nvme_t8122_hw = { + .has_lsq_nvmmu = true, + .has_queue_count = true, + .warm_sleep = true, + .max_queue_depth = 64, +}; + /* * The post-M4 (T8132 and later) I/O queue setup follows Yureka Lilian's T8132 * support in m1n1 (commit 53f8ee9b54ba, "nvme: support T8132"). @@ -3333,6 +3626,10 @@ static const struct apple_nvme_hw apple_nvme_t6040_hw = { .needs_ioq_registers = true, .lsq_in_nvmmu = true, .max_queue_depth = 64, + /* ANS takes part in a firmware sleep, whole endpoint map echoed. */ + .sleep_traced = true, + .sleep_flush_max_nsid = 1, + .sleep_shn = NVME_CC_SHN_MASK, .quirks = NVME_QUIRK_NO_APST, }; @@ -3354,14 +3651,32 @@ static const struct apple_nvme_hw apple_nvme_t6050_hw = { .quirks = NVME_QUIRK_NO_APST | NVME_QUIRK_BROKEN_FUA, }; +/* + * T8152 uses the post-M4 queue setup, but its NVMe registers and NVMMU share + * one window (0x325cc0000 on J873) like T8103, with the secure register + * layout. There is no T8152 PMGR driver yet, so the controller has no reset + * line in the DT. + */ +static const struct apple_nvme_hw apple_nvme_t8152_hw = { + .has_lsq_nvmmu = true, + .needs_ioq_registers = true, + .reset_optional = true, + .secure_reg_layout = true, + .shutdown_notify = true, + .max_queue_depth = 64, + .quirks = NVME_QUIRK_BROKEN_FUA, +}; + static const struct of_device_id apple_nvme_of_match[] = { { .compatible = "apple,t6041-nvme-ans2", .data = &apple_nvme_t6040_hw }, { .compatible = "apple,t6050-nvme-ans2", .data = &apple_nvme_t6050_hw }, { .compatible = "apple,t8015-nvme-ans2", .data = &apple_nvme_t8015_hw }, { .compatible = "apple,t8103-nvme-ans2", .data = &apple_nvme_t8103_hw }, + { .compatible = "apple,t8122-nvme-ans2", .data = &apple_nvme_t8122_hw }, { .compatible = "apple,t8132-nvme-ans2", .data = &apple_nvme_t8132_hw }, { .compatible = "apple,t8140-nvme-ans2", .data = &apple_nvme_t8140_hw }, { .compatible = "apple,t8142-nvme-ans2", .data = &apple_nvme_t8142_hw }, + { .compatible = "apple,t8152-nvme-ans2", .data = &apple_nvme_t8152_hw }, { .compatible = "apple,nvme-ans2", .data = &apple_nvme_t8103_hw }, {}, }; diff --git a/drivers/nvmem/Kconfig b/drivers/nvmem/Kconfig index c36c2a4c2a0b72..0da6ce8f75c77c 100644 --- a/drivers/nvmem/Kconfig +++ b/drivers/nvmem/Kconfig @@ -151,6 +151,16 @@ config NVMEM_APPLE_EFUSES This driver can also be built as a module. If so, the module will be called nvmem-apple-efuses. +config NVMEM_APPLE_EFUSES_KUNIT_TEST + bool "KUnit tests for the Apple eFuse driver" if !KUNIT_ALL_TESTS + depends on NVMEM_APPLE_EFUSES=y && KUNIT=y + default KUNIT_ALL_TESTS + help + Build tests for the Apple eFuse driver: the nvmem read callback's + word reads, offsets and sizes against the fuse range, and word and + bit-field cell reads through a registered nvmem device. The fuses + are kernel memory, so the tests need no Apple hardware. + config NVMEM_APPLE_SPMI tristate "Apple SPMI NVMEM" depends on ARCH_APPLE || COMPILE_TEST @@ -164,6 +174,16 @@ config NVMEM_APPLE_SPMI This driver can also be built as a module. If so, the module will be called apple-nvmem-spmi. +config NVMEM_APPLE_SPMI_KUNIT_TEST + bool "KUnit tests for the Apple SPMI NVMEM driver" if !KUNIT_ALL_TESTS + depends on NVMEM_APPLE_SPMI=y && NVMEM_SYSFS && KUNIT=y + default KUNIT_ALL_TESTS + help + Check, on a register map in memory, that the PMIC's whole-device + sysfs file cannot be written, even with force_ro cleared, while + the kernel still writes its byte and bit-field cells. No Apple + hardware is needed. + config NVMEM_BCM_OCOTP tristate "Broadcom On-Chip OTP Controller support" depends on ARCH_BCM_IPROC || COMPILE_TEST diff --git a/drivers/nvmem/apple-efuses-test.c b/drivers/nvmem/apple-efuses-test.c new file mode 100644 index 00000000000000..c5474b13287f6f --- /dev/null +++ b/drivers/nvmem/apple-efuses-test.c @@ -0,0 +1,331 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the Apple SoC eFuse driver: the nvmem read callback's + * word reads, offsets and sizes against the fuse range, and reads through + * a real nvmem device registered with the driver's callback, including + * bit-field cells as the PHY calibration users read them. + * + * The fuse range is kernel memory, so the tests need no Apple hardware. + * + * Included by apple-efuses.c. + */ + +#include +#include +#include +#include + +/* Fuse range of the fake block, in words. */ +#define APPLE_EFUSES_TEST_WORDS 16 +#define APPLE_EFUSES_TEST_SIZE (APPLE_EFUSES_TEST_WORDS * sizeof(u32)) +/* The fake block is followed by guard words a read must never reach. */ +#define APPLE_EFUSES_TEST_GUARD 4 +/* Destination bytes a read has not written. */ +#define APPLE_EFUSES_TEST_POISON 0x5a + +struct apple_efuses_test { + struct apple_efuses_priv priv; + u32 *fuses; + struct device *dev; +}; + +static u32 apple_efuses_test_word(unsigned int i) +{ + return 0x10203040 + i * 0x01010101; +} + +static int apple_efuses_test_init(struct kunit *test) +{ + struct apple_efuses_test *ctx; + unsigned int i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->fuses = kunit_kcalloc(test, APPLE_EFUSES_TEST_WORDS + APPLE_EFUSES_TEST_GUARD, + sizeof(u32), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->fuses); + for (i = 0; i < APPLE_EFUSES_TEST_WORDS; i++) + ctx->fuses[i] = cpu_to_le32(apple_efuses_test_word(i)); + for (; i < APPLE_EFUSES_TEST_WORDS + APPLE_EFUSES_TEST_GUARD; i++) + ctx->fuses[i] = cpu_to_le32(0xbad0bad0); + ctx->priv.fuses = (void __iomem __force *)ctx->fuses; + + return 0; +} + +/* One word at offset 0. */ +static void apple_efuses_test_read_word(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + u32 val = 0; + + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, 0, &val, sizeof(val)), 0); + KUNIT_EXPECT_EQ(test, val, apple_efuses_test_word(0)); +} + +/* Each word at its own offset. */ +static void apple_efuses_test_read_each_offset(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + unsigned int i; + u32 val; + + for (i = 0; i < APPLE_EFUSES_TEST_WORDS; i++) { + val = 0; + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, i * sizeof(u32), + &val, sizeof(val)), 0); + KUNIT_EXPECT_EQ_MSG(test, val, apple_efuses_test_word(i), "word %u", i); + } +} + +/* A multi-word read from an offset walks consecutive words. */ +static void apple_efuses_test_read_run(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + u32 val[5]; + unsigned int i; + + memset(val, APPLE_EFUSES_TEST_POISON, sizeof(val)); + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, 3 * sizeof(u32), val, + sizeof(val)), 0); + for (i = 0; i < ARRAY_SIZE(val); i++) + KUNIT_EXPECT_EQ_MSG(test, val[i], apple_efuses_test_word(3 + i), "word %u", i); +} + +/* The whole range in one read, ending exactly at its last word. */ +static void apple_efuses_test_read_all(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + u32 val[APPLE_EFUSES_TEST_WORDS + 1]; + unsigned int i; + + memset(val, APPLE_EFUSES_TEST_POISON, sizeof(val)); + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, 0, val, + APPLE_EFUSES_TEST_SIZE), 0); + for (i = 0; i < APPLE_EFUSES_TEST_WORDS; i++) + KUNIT_EXPECT_EQ_MSG(test, val[i], apple_efuses_test_word(i), "word %u", i); + /* Nothing written past the requested size. */ + KUNIT_EXPECT_EQ(test, val[APPLE_EFUSES_TEST_WORDS], 0x5a5a5a5aU); +} + +/* The last word of the range alone. */ +static void apple_efuses_test_read_last(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + u32 val = 0; + + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, APPLE_EFUSES_TEST_SIZE - 4, + &val, sizeof(val)), 0); + KUNIT_EXPECT_EQ(test, val, apple_efuses_test_word(APPLE_EFUSES_TEST_WORDS - 1)); +} + +/* + * The callback copies whole words only: a tail shorter than a word is not + * read or written, so the destination never overflows. The nvmem core + * rounds cell and sysfs reads to the 4-byte word size before it calls in. + */ +static void apple_efuses_test_partial_tail(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + u8 val[12]; + u32 word; + + memset(val, APPLE_EFUSES_TEST_POISON, sizeof(val)); + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, 8, val, 6), 0); + memcpy(&word, val, sizeof(word)); + KUNIT_EXPECT_EQ(test, word, apple_efuses_test_word(2)); + KUNIT_EXPECT_EQ(test, val[4], APPLE_EFUSES_TEST_POISON); + KUNIT_EXPECT_EQ(test, val[5], APPLE_EFUSES_TEST_POISON); + KUNIT_EXPECT_EQ(test, val[6], APPLE_EFUSES_TEST_POISON); +} + +/* Reads of zero or fewer than four bytes write nothing and succeed. */ +static void apple_efuses_test_short_reads(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + size_t bytes; + u8 val[4]; + + for (bytes = 0; bytes < sizeof(u32); bytes++) { + memset(val, APPLE_EFUSES_TEST_POISON, sizeof(val)); + KUNIT_EXPECT_EQ(test, apple_efuses_read(&ctx->priv, 0, val, bytes), 0); + KUNIT_EXPECT_MEMEQ(test, val, "\x5a\x5a\x5a\x5a", sizeof(val)); + } +} + +/* The fuses are read, never written. */ +static void apple_efuses_test_source_untouched(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + u32 val[APPLE_EFUSES_TEST_WORDS]; + unsigned int i; + + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, 0, val, sizeof(val)), 0); + for (i = 0; i < APPLE_EFUSES_TEST_WORDS; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->fuses[i]), apple_efuses_test_word(i)); + for (; i < APPLE_EFUSES_TEST_WORDS + APPLE_EFUSES_TEST_GUARD; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->fuses[i]), 0xbad0bad0U); +} + +static struct nvmem_device *apple_efuses_test_register(struct kunit *test, + struct apple_efuses_test *ctx) +{ + /* as apple_efuses_probe(), with the fake range as the resource */ + struct nvmem_config config = { + .add_legacy_fixed_of_cells = true, + .read_only = true, + .reg_read = apple_efuses_read, + .stride = sizeof(u32), + .word_size = sizeof(u32), + .name = "apple_efuses_nvmem_test", + .id = NVMEM_DEVID_AUTO, + .root_only = true, + }; + struct nvmem_device *nvmem; + + ctx->dev = kunit_device_register(test, "apple-efuses-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + + config.dev = ctx->dev; + config.priv = &ctx->priv; + config.size = APPLE_EFUSES_TEST_SIZE; + + nvmem = devm_nvmem_register(ctx->dev, &config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, nvmem); + + return nvmem; +} + +/* A registered device reports the fuse range and reads it through the driver. */ +static void apple_efuses_test_nvmem_read(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + struct nvmem_device *nvmem = apple_efuses_test_register(test, ctx); + u32 val[3]; + + KUNIT_EXPECT_EQ(test, nvmem_dev_size(nvmem), APPLE_EFUSES_TEST_SIZE); + + KUNIT_ASSERT_EQ(test, nvmem_device_read(nvmem, 0x14, sizeof(val), val), + (int)sizeof(val)); + KUNIT_EXPECT_EQ(test, val[0], apple_efuses_test_word(5)); + KUNIT_EXPECT_EQ(test, val[1], apple_efuses_test_word(6)); + KUNIT_EXPECT_EQ(test, val[2], apple_efuses_test_word(7)); + + KUNIT_ASSERT_EQ(test, nvmem_device_read(nvmem, APPLE_EFUSES_TEST_SIZE - 4, 4, val), 4); + KUNIT_EXPECT_EQ(test, val[0], apple_efuses_test_word(APPLE_EFUSES_TEST_WORDS - 1)); +} + +/* The device is read-only: a write is refused and leaves the fuses alone. */ +static void apple_efuses_test_nvmem_read_only(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + struct nvmem_device *nvmem = apple_efuses_test_register(test, ctx); + u32 val = 0x12345678; + + KUNIT_EXPECT_LT(test, nvmem_device_write(nvmem, 0, sizeof(val), &val), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->fuses[0]), apple_efuses_test_word(0)); +} + +/* + * An 8-bit field at bit 16 of a fuse word: the core reads the whole word + * through the driver, then shifts the field down to byte 0. + */ +static void apple_efuses_test_cell_byte(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + struct nvmem_device *nvmem = apple_efuses_test_register(test, ctx); + struct nvmem_cell_info info = { + .name = "byte", + .offset = 0x8, + .bit_offset = 16, + .nbits = 8, + }; + u8 buf[4]; + + memset(buf, APPLE_EFUSES_TEST_POISON, sizeof(buf)); + /* bytes = DIV_ROUND_UP(16 + 8, 8), read as one 4-byte word */ + KUNIT_ASSERT_EQ(test, nvmem_device_cell_read(nvmem, &info, buf), 3); + KUNIT_EXPECT_EQ(test, buf[0], (u8)(apple_efuses_test_word(2) >> 16)); + KUNIT_EXPECT_EQ(test, buf[1], 0); + KUNIT_EXPECT_EQ(test, buf[2], 0); +} + +/* A bit field spanning two fuse words, as the PHY calibration cells use. */ +static void apple_efuses_test_cell_bits(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + struct nvmem_device *nvmem = apple_efuses_test_register(test, ctx); + struct nvmem_cell_info info = { + .name = "bits", + .offset = 0x20, + .bit_offset = 26, + .nbits = 12, + }; + u64 both; + u8 buf[8]; + + memset(buf, APPLE_EFUSES_TEST_POISON, sizeof(buf)); + /* bytes = DIV_ROUND_UP(26 + 12, 8), read as two 4-byte words */ + KUNIT_ASSERT_EQ(test, nvmem_device_cell_read(nvmem, &info, buf), 5); + both = apple_efuses_test_word(8) | (u64)apple_efuses_test_word(9) << 32; + KUNIT_EXPECT_EQ(test, get_unaligned_le16(buf), (u16)((both >> 26) & GENMASK(11, 0))); +} + +/* A cell in the last fuse word reads it without touching what follows. */ +static void apple_efuses_test_cell_last_word(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + struct nvmem_device *nvmem = apple_efuses_test_register(test, ctx); + struct nvmem_cell_info info = { + .name = "last", + .offset = APPLE_EFUSES_TEST_SIZE - 4, + .bytes = 4, + }; + u32 val = 0; + + KUNIT_ASSERT_EQ(test, nvmem_device_cell_read(nvmem, &info, &val), 4); + KUNIT_EXPECT_EQ(test, val, apple_efuses_test_word(APPLE_EFUSES_TEST_WORDS - 1)); +} + +/* The core refuses a cell that is not on the driver's 4-byte stride. */ +static void apple_efuses_test_cell_unaligned(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + struct nvmem_device *nvmem = apple_efuses_test_register(test, ctx); + struct nvmem_cell_info info = { + .name = "unaligned", + .offset = 0x6, + .bytes = 2, + }; + u16 val = 0; + + KUNIT_EXPECT_EQ(test, nvmem_device_cell_read(nvmem, &info, &val), -EINVAL); +} + +static struct kunit_case apple_efuses_test_cases[] = { + KUNIT_CASE(apple_efuses_test_read_word), + KUNIT_CASE(apple_efuses_test_read_each_offset), + KUNIT_CASE(apple_efuses_test_read_run), + KUNIT_CASE(apple_efuses_test_read_all), + KUNIT_CASE(apple_efuses_test_read_last), + KUNIT_CASE(apple_efuses_test_partial_tail), + KUNIT_CASE(apple_efuses_test_short_reads), + KUNIT_CASE(apple_efuses_test_source_untouched), + KUNIT_CASE(apple_efuses_test_nvmem_read), + KUNIT_CASE(apple_efuses_test_nvmem_read_only), + KUNIT_CASE(apple_efuses_test_cell_byte), + KUNIT_CASE(apple_efuses_test_cell_bits), + KUNIT_CASE(apple_efuses_test_cell_last_word), + KUNIT_CASE(apple_efuses_test_cell_unaligned), + {} +}; + +static struct kunit_suite apple_efuses_test_suite = { + .name = "apple-efuses", + .init = apple_efuses_test_init, + .test_cases = apple_efuses_test_cases, +}; + +kunit_test_suite(apple_efuses_test_suite); diff --git a/drivers/nvmem/apple-efuses.c b/drivers/nvmem/apple-efuses.c index 9913e77b8ff067..7caf4e0f5c2434 100644 --- a/drivers/nvmem/apple-efuses.c +++ b/drivers/nvmem/apple-efuses.c @@ -79,3 +79,7 @@ module_platform_driver(apple_efuses_driver); MODULE_AUTHOR("Sven Peter "); MODULE_DESCRIPTION("Apple SoC eFuse driver"); MODULE_LICENSE("GPL"); + +#if IS_ENABLED(CONFIG_NVMEM_APPLE_EFUSES_KUNIT_TEST) +#include "apple-efuses-test.c" +#endif diff --git a/drivers/nvmem/apple-efuses.kunitconfig b/drivers/nvmem/apple-efuses.kunitconfig new file mode 100644 index 00000000000000..b2ced815094df8 --- /dev/null +++ b/drivers/nvmem/apple-efuses.kunitconfig @@ -0,0 +1,6 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/nvmem/apple-efuses.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_NVMEM=y +CONFIG_NVMEM_APPLE_EFUSES=y +CONFIG_NVMEM_APPLE_EFUSES_KUNIT_TEST=y diff --git a/drivers/nvmem/apple-spmi-nvmem-test.c b/drivers/nvmem/apple-spmi-nvmem-test.c new file mode 100644 index 00000000000000..1990e1f4562405 --- /dev/null +++ b/drivers/nvmem/apple-spmi-nvmem-test.c @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by apple-spmi-nvmem.c: the provider as the driver registers it, on a + * register map in memory. Userspace cannot write the PMIC's registers through + * the whole-device sysfs file, whatever force_ro says, while the kernel still + * writes the cells its consumers declare. + */ +#include +#include +#include + +#include "internals.h" + +struct apple_spmi_nvmem_test { + u8 regs[0x10000]; +}; + +static int apple_spmi_nvmem_test_reg_read(void *context, unsigned int reg, unsigned int *val) +{ + struct apple_spmi_nvmem_test *t = context; + + *val = t->regs[reg]; + return 0; +} + +static int apple_spmi_nvmem_test_reg_write(void *context, unsigned int reg, unsigned int val) +{ + struct apple_spmi_nvmem_test *t = context; + + t->regs[reg] = val; + return 0; +} + +/* The driver's register layout (apple_spmi_regmap_config), on the array above */ +static const struct regmap_config apple_spmi_nvmem_test_regmap_config = { + .reg_bits = 16, + .val_bits = 8, + .max_register = 0xffff, + .reg_read = apple_spmi_nvmem_test_reg_read, + .reg_write = apple_spmi_nvmem_test_reg_write, +}; + +static struct nvmem_device *apple_spmi_nvmem_test_register(struct kunit *test, + struct apple_spmi_nvmem_test **regs) +{ + struct apple_spmi_nvmem_test *t; + struct nvmem_device *nvmem; + struct regmap *regmap; + struct device *dev; + + dev = kunit_device_register(test, "apple-spmi-nvmem-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t); + + regmap = devm_regmap_init(dev, NULL, t, &apple_spmi_nvmem_test_regmap_config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, regmap); + + nvmem = apple_spmi_nvmem_register(dev, regmap); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, nvmem); + *regs = t; + return nvmem; +} + +/* + * The whole-device file: root reads it, nobody writes it, not with read_only + * cleared either, and force_ro is shown but cannot be stored. + */ +static void apple_spmi_nvmem_sysfs_read_only_test(struct kunit *test) +{ + u8 offset[6] = { 1, 2, 3, 4, 5, 6 }, out[6] = {}; + const struct attribute_group *group; + const struct bin_attribute *raw; + struct device_attribute *force_ro; + struct apple_spmi_nvmem_test *t; + struct nvmem_device *nvmem; + struct kobject *kobj; + int i; + + nvmem = apple_spmi_nvmem_test_register(test, &t); + kobj = &nvmem->dev.kobj; + KUNIT_ASSERT_NOT_NULL(test, nvmem->dev.groups); + group = nvmem->dev.groups[0]; + raw = group->bin_attrs[0]; + KUNIT_ASSERT_STREQ(test, raw->attr.name, "nvmem"); + + KUNIT_EXPECT_EQ(test, group->is_bin_visible(kobj, raw, 0), (umode_t)0400); + + t->regs[0x2100] = 0x5a; + KUNIT_EXPECT_EQ(test, raw->write(NULL, kobj, raw, (char *)offset, 0x2100, sizeof(offset)), + (ssize_t)-EPERM); + KUNIT_EXPECT_EQ(test, t->regs[0x2100], 0x5a); + + for (i = 0; group->attrs[i]; i++) + if (!strcmp(group->attrs[i]->name, "force_ro")) + break; + KUNIT_ASSERT_NOT_NULL(test, group->attrs[i]); + KUNIT_EXPECT_EQ(test, group->is_visible(kobj, group->attrs[i], i), (umode_t)0444); + force_ro = container_of(group->attrs[i], struct device_attribute, attr); + KUNIT_EXPECT_EQ(test, force_ro->store(&nvmem->dev, force_ro, "0", 1), (ssize_t)-EPERM); + + /* As if read_only were cleared, by force_ro or otherwise */ + nvmem->read_only = false; + KUNIT_EXPECT_EQ(test, group->is_bin_visible(kobj, raw, 0), (umode_t)0400); + KUNIT_EXPECT_EQ(test, raw->write(NULL, kobj, raw, (char *)offset, 0x2100, sizeof(offset)), + (ssize_t)-EPERM); + KUNIT_EXPECT_EQ(test, t->regs[0x2100], 0x5a); + + KUNIT_EXPECT_EQ(test, raw->read(NULL, kobj, raw, (char *)out, 0x2100, sizeof(out)), + (ssize_t)sizeof(out)); + KUNIT_EXPECT_EQ(test, out[0], 0x5a); +} + +/* + * The kernel's consumers still write their cells: a byte cell (the RTC offset) + * and a bit-field cell sharing its byte (the panic count above the boot error + * count). + */ +static void apple_spmi_nvmem_cell_write_test(struct kunit *test) +{ + struct nvmem_cell_info rtc_offset = { + .name = "rtc-offset", .offset = 0x2100, .bytes = 6, + }; + struct nvmem_cell_info panic_count = { + .name = "panic-count", .offset = 0xf802, .bytes = 1, .bit_offset = 4, .nbits = 4, + }; + u8 offset[6] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66 }; + struct apple_spmi_nvmem_test *t; + struct nvmem_device *nvmem; + u8 count = 3; + + nvmem = apple_spmi_nvmem_test_register(test, &t); + + KUNIT_EXPECT_EQ(test, nvmem_device_cell_write(nvmem, &rtc_offset, offset), 6); + KUNIT_EXPECT_MEMEQ(test, &t->regs[0x2100], offset, sizeof(offset)); + + t->regs[0xf802] = 0x05; + KUNIT_EXPECT_EQ(test, nvmem_device_cell_write(nvmem, &panic_count, &count), 1); + KUNIT_EXPECT_EQ(test, t->regs[0xf802], 0x35); +} + +static struct kunit_case apple_spmi_nvmem_test_cases[] = { + KUNIT_CASE(apple_spmi_nvmem_sysfs_read_only_test), + KUNIT_CASE(apple_spmi_nvmem_cell_write_test), + {} +}; + +static struct kunit_suite apple_spmi_nvmem_test_suite = { + .name = "apple-spmi-nvmem", + .test_cases = apple_spmi_nvmem_test_cases, +}; + +kunit_test_suite(apple_spmi_nvmem_test_suite); diff --git a/drivers/nvmem/apple-spmi-nvmem.c b/drivers/nvmem/apple-spmi-nvmem.c index b31b8212d3fcc0..8c933bd83dd669 100644 --- a/drivers/nvmem/apple-spmi-nvmem.c +++ b/drivers/nvmem/apple-spmi-nvmem.c @@ -35,37 +35,48 @@ static int apple_spmi_nvmem_write(void *priv, unsigned int offset, void *val, return regmap_bulk_write(map, offset, val, bytes); } -static int apple_spmi_nvmem_probe(struct spmi_device *sdev) +/* + * The PMIC's register file. Its kernel consumers (the RTC, the reboot and boot + * state) write the cells the device tree declares; through sysfs, only root may + * read the registers, and nobody may write them. + */ +static struct nvmem_device *apple_spmi_nvmem_register(struct device *dev, struct regmap *regmap) { - struct regmap *regmap; - struct nvmem_device *provider; struct nvmem_config nvmem_cfg = { - .dev = &sdev->dev, + .dev = dev, .name = "spmi_nvmem", .id = NVMEM_DEVID_AUTO, .word_size = 1, .stride = 1, .size = 0xffff, - /* PMIC registers: only root may read them through sysfs. */ .root_only = true, + .sysfs_read_only = true, .reg_read = apple_spmi_nvmem_read, .reg_write = apple_spmi_nvmem_write, + .priv = regmap, }; + return devm_nvmem_register(dev, &nvmem_cfg); +} + +static int apple_spmi_nvmem_probe(struct spmi_device *sdev) +{ + struct regmap *regmap; + struct nvmem_device *provider; + regmap = devm_regmap_init_spmi_ext(sdev, &apple_spmi_regmap_config); if (IS_ERR(regmap)) return PTR_ERR(regmap); - nvmem_cfg.priv = regmap; - - provider = devm_nvmem_register(&sdev->dev, &nvmem_cfg); + provider = apple_spmi_nvmem_register(&sdev->dev, regmap); if (IS_ERR(provider)) return PTR_ERR(provider); if (!of_device_is_compatible(sdev->dev.of_node, "apple,baku-pmic") && !of_device_is_compatible(sdev->dev.of_node, "apple,abbey-pmic") && !of_device_is_compatible(sdev->dev.of_node, "apple,chapel-pmic") && !of_device_is_compatible(sdev->dev.of_node, "apple,maverick-pmic") && - !of_device_is_compatible(sdev->dev.of_node, "apple,stowe-pmic")) + !of_device_is_compatible(sdev->dev.of_node, "apple,stowe-pmic") && + !of_device_is_compatible(sdev->dev.of_node, "apple,sera-pmic")) return 0; return devm_of_platform_populate(&sdev->dev); @@ -90,3 +101,7 @@ module_spmi_driver(apple_spmi_nvmem_driver); MODULE_LICENSE("Dual MIT/GPL"); MODULE_AUTHOR("Hector Martin "); MODULE_DESCRIPTION("Apple SPMI NVMEM driver"); + +#if IS_ENABLED(CONFIG_NVMEM_APPLE_SPMI_KUNIT_TEST) +#include "apple-spmi-nvmem-test.c" +#endif diff --git a/drivers/nvmem/apple-spmi-nvmem.kunitconfig b/drivers/nvmem/apple-spmi-nvmem.kunitconfig new file mode 100644 index 00000000000000..f6c1e1f3eef14f --- /dev/null +++ b/drivers/nvmem/apple-spmi-nvmem.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_SPMI=y +CONFIG_NVMEM=y +CONFIG_NVMEM_SYSFS=y +CONFIG_NVMEM_APPLE_SPMI=y +CONFIG_NVMEM_APPLE_SPMI_KUNIT_TEST=y diff --git a/drivers/nvmem/core.c b/drivers/nvmem/core.c index b4e5069d9e3802..bd5b53d317b223 100644 --- a/drivers/nvmem/core.c +++ b/drivers/nvmem/core.c @@ -204,8 +204,13 @@ static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct nvmem_device *nvmem = to_nvmem_device(dev); - int ret = kstrtobool(buf, &nvmem->read_only); + int ret; + + /* It would only govern the kernel's cell writes. */ + if (nvmem->sysfs_read_only) + return -EPERM; + ret = kstrtobool(buf, &nvmem->read_only); if (ret < 0) return ret; @@ -266,6 +271,10 @@ static ssize_t bin_attr_nvmem_write(struct file *filp, struct kobject *kobj, dev = kobj_to_dev(kobj); nvmem = to_nvmem_device(dev); + /* Whatever the file's mode, and whatever force_ro says */ + if (nvmem->sysfs_read_only) + return -EPERM; + if (!IS_ALIGNED(pos, nvmem->stride)) return -EINVAL; @@ -296,7 +305,7 @@ static umode_t nvmem_bin_attr_get_umode(struct nvmem_device *nvmem) if (!nvmem->root_only) mode |= 0044; - if (!nvmem->read_only) + if (!nvmem->read_only && !nvmem->sysfs_read_only) mode |= 0200; if (!ops->reg_write) @@ -345,6 +354,10 @@ static umode_t nvmem_attr_is_visible(struct kobject *kobj, if (attr == &dev_attr_force_ro.attr && !ops->reg_write) return 0; /* Attribute not visible */ + /* Shown, but it cannot make the device's file writable. */ + if (attr == &dev_attr_force_ro.attr && nvmem->sysfs_read_only) + return 0444; + return attr->mode; } @@ -945,6 +958,7 @@ struct nvmem_device *nvmem_register(const struct nvmem_config *config) nvmem->word_size = config->word_size ?: 1; nvmem->size = config->size; nvmem->root_only = config->root_only; + nvmem->sysfs_read_only = config->sysfs_read_only; nvmem->priv = config->priv; nvmem->type = config->type; nvmem->keepout = config->keepout; diff --git a/drivers/nvmem/internals.h b/drivers/nvmem/internals.h index 4e610deeaa7b3c..df8b25fd39369f 100644 --- a/drivers/nvmem/internals.h +++ b/drivers/nvmem/internals.h @@ -23,6 +23,8 @@ struct nvmem_device { size_t size; bool read_only; bool root_only; + /* See nvmem_config.sysfs_read_only */ + bool sysfs_read_only; int flags; enum nvmem_type type; struct bin_attribute eeprom; diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 66b1cbe9366371..f21ca71bcb9461 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -99,7 +99,6 @@ static int t6050_sd_port_wake = 2; module_param(t6050_sd_port_wake, int, 0644); MODULE_PARM_DESC(t6050_sd_port_wake, "T6050: the SD card reader's port after a firmware sleep: back once the resume is over (2, default), back in the early resume (1), or parked until a restart (0)"); - /* T8103 (original M1) and related SoCs */ #define CORE_RC_PHYIF_CTL 0x00024 #define CORE_RC_PHYIF_CTL_RUN BIT(0) @@ -155,6 +154,11 @@ MODULE_PARM_DESC(t6050_sd_port_wake, #define PORT_INT_LINK_DOWN 14 #define PORT_INT_LINK_UP 12 #define PORT_INT_LINK_BWMGMT 11 +/* + * The root port received a PME message (it sets its Root Status PME bit too). + * The root port does not raise its own MSI for a PME (measured on T8132). + */ +#define PORT_INT_PME 8 #define PORT_INT_AER_MASK (15 << 4) #define PORT_INT_PORT_ERR 4 #define PORT_INT_INTx(i) i @@ -302,6 +306,12 @@ struct hw_info { bool pipe_rst; bool no_port_reset; bool mps_timers; + /* + * Keep endpoints at their reset Max_Read_Request_Size (512 bytes). + * On T8152 an RTL8127 at MRRS 4096 (what r8169 asks for) transmits + * 9000-byte frames at 7.0 Gbit/s; at 512 it reaches 9.93. + */ + bool no_inc_mrrs; }; static const struct hw_info t8103_hw = { @@ -357,6 +367,7 @@ static const struct hw_info t8152_hw = { .max_rid2sid = 512, .refbuf_off = true, .pipe_rst = true, + .no_inc_mrrs = true, }; /* @@ -474,6 +485,38 @@ static const struct hw_info t6050_pciec_hw = { .s2idle_hold_domain = true, }; +/* T8142 shares this register layout, with its own three-cell AIC MSI slice. */ +static const struct hw_info t8142_pciec_hw = { + .port_msiaddr = PORT_MSIADDR, + .port_msiaddr_hi = PORT_MSIADDR + 4, + .port_perst = PORT_PERST, + .port_rid2sid = PORT_RID2SID, + .port_msimap = PORT_T602X_MSIMAP, + .port_tunctrl = PORT_T6050_TUNCTRL, + .max_rid2sid = 256, + .tunneled = true, + .tunnel_intr2axi = true, + .no_port_reset = true, + .msimap_by_vector = true, + .mps_timers = true, +}; + +/* T8152 PCIe-C: the T8142 layout, with a third PCIe-C bridge (CIO3). */ +static const struct hw_info t8152_pciec_hw = { + .port_msiaddr = PORT_MSIADDR, + .port_msiaddr_hi = PORT_MSIADDR + 4, + .port_perst = PORT_PERST, + .port_rid2sid = PORT_RID2SID, + .port_msimap = PORT_T602X_MSIMAP, + .port_tunctrl = PORT_T6050_TUNCTRL, + .max_rid2sid = 256, + .tunneled = true, + .tunnel_intr2axi = true, + .no_port_reset = true, + .msimap_by_vector = true, + .mps_timers = true, +}; + static const struct of_device_id apple_pcie_of_match[]; /** @@ -522,7 +565,6 @@ struct apple_pcie_pd { struct apple_radio_sleep; -#define APPLE_PCIE_T6050_WARM_WRITES 4 struct apple_pcie { struct mutex lock; @@ -545,10 +587,7 @@ struct apple_pcie { /* Those ports back, and their functions looked for, once the resume is over */ struct work_struct t6050_unpark_work; /* The endpoint's warm reset, given by this host while the port is down */ - struct platform_device *t6050_smc; - u32 t6050_warm_key; - u32 t6050_warm_writes[2 * APPLE_PCIE_T6050_WARM_WRITES]; - unsigned int t6050_warm_count; + struct apple_smc_warm_reset t6050_warm; bool t6050_warm_done; /* When this wake's bring-up of that port had the link up and its 100 ms over; 0 before */ ktime_t t6050_link_up; @@ -615,6 +654,8 @@ struct apple_pcie { const struct hw_info *hw; unsigned long *bitmap; struct list_head ports; + struct list_head hib_fns; + bool hib_saved; struct completion event; struct irq_fwspec fwspec; struct irq_domain *msi_domain; @@ -638,11 +679,16 @@ struct apple_pcie_port { struct apple_tunable *tunable; unsigned int irq; unsigned int link_irqs[2]; + /* PORT_INT_PME's interrupt (0: none), see apple_pcie_port_pme_thread() */ + unsigned int pme_irq; u32 saved_intmask; int sid_map_sz; struct gpio_desc *perst_gpio; struct gpio_desc *pwren_gpio; int idx; + /* Conventional port: link up when the sleep began, and found down after it */ + bool hib_link_up; + bool hib_cold; bool started; bool needs_stop; bool link_failed; @@ -1096,6 +1142,59 @@ static irqreturn_t apple_pcie_port_irq(int irq, void *data) return IRQ_HANDLED; } +/* + * A PME message reached the root port. Because the root port does not raise + * its own PCIe port services MSI for a PME (measured on T8132), forward the + * port's PME interrupt to that vector by hand: the PME service reads Root + * Status, resumes or wakes the requester, and while the system sleeps the wake + * that interrupt is armed for (enable_irq_wake() at the PME service's suspend) + * takes place. This is how a Wake-on-LAN packet ends suspend-to-idle. + */ +static irqreturn_t apple_pcie_port_pme_thread(int irq, void *data) +{ + struct apple_pcie_port *port = data; + struct pci_host_bridge *bridge = dev_get_drvdata(port->pcie->dev); + struct pci_dev *rp; + int vector; + + if (!bridge || !bridge->bus) + return IRQ_NONE; + rp = pci_get_slot(bridge->bus, PCI_DEVFN(port->idx, 0)); + if (!rp) + return IRQ_NONE; + vector = rp->msi_enabled || rp->msix_enabled ? pci_irq_vector(rp, 0) : rp->irq; + if (vector > 0) + generic_handle_irq_safe(vector); + else + dev_warn_ratelimited(port->pcie->dev, "%pOF: PME, but %s has no interrupt\n", + port->np, pci_name(rp)); + pci_dev_put(rp); + return IRQ_HANDLED; +} + +static int apple_pcie_port_register_pme(struct apple_pcie_port *port) +{ + struct irq_fwspec fwspec = { + .fwnode = &port->np->fwnode, + .param_count = 1, + .param = { [0] = PORT_INT_PME, }, + }; + int irq, ret; + + irq = irq_domain_alloc_irqs(port->domain, 1, NUMA_NO_NODE, &fwspec); + if (irq <= 0) + return irq ?: -ENOMEM; + /* Runs through suspend: it is what ends a suspend-to-idle for a PME. */ + ret = request_threaded_irq(irq, NULL, apple_pcie_port_pme_thread, + IRQF_ONESHOT | IRQF_NO_SUSPEND, "PME", port); + if (ret) { + irq_domain_free_irqs(irq, 1); + return ret; + } + port->pme_irq = irq; + return 0; +} + static int apple_pcie_port_register_irqs(struct apple_pcie_port *port) { static struct { @@ -1105,7 +1204,7 @@ static int apple_pcie_port_register_irqs(struct apple_pcie_port *port) { PORT_INT_LINK_UP, "Link up", }, { PORT_INT_LINK_DOWN, "Link down", }, }; - int i; + int i, ret; for (i = 0; i < ARRAY_SIZE(port_irqs); i++) { struct irq_fwspec fwspec = { @@ -1115,7 +1214,7 @@ static int apple_pcie_port_register_irqs(struct apple_pcie_port *port) [0] = port_irqs[i].hwirq, }, }; - int irq, ret; + int irq; irq = irq_domain_alloc_irqs(port->domain, 1, NUMA_NO_NODE, &fwspec); @@ -1132,6 +1231,10 @@ static int apple_pcie_port_register_irqs(struct apple_pcie_port *port) port->link_irqs[i] = irq; } + ret = apple_pcie_port_register_pme(port); + if (ret) + dev_warn(port->pcie->dev, "%pOF: no PME interrupt: %d\n", port->np, ret); + return 0; } @@ -1147,6 +1250,11 @@ static void apple_pcie_port_unregister_irqs(struct apple_pcie_port *port) irq_domain_free_irqs(port->link_irqs[i], 1); port->link_irqs[i] = 0; } + if (port->pme_irq) { + free_irq(port->pme_irq, port); + irq_domain_free_irqs(port->pme_irq, 1); + port->pme_irq = 0; + } } /* @@ -1964,6 +2072,7 @@ static int apple_pcie_adopt_link(struct apple_pcie_port *port) void __iomem *rp, *ep; char name[16]; u32 value, bus; + u16 tls; u8 cap; bool msi = false; int ret, i; @@ -2030,7 +2139,7 @@ static int apple_pcie_adopt_link(struct apple_pcie_port *port) port->perst = NULL; } - /* The currently qualified handoff is Gen3 x1, with no retrain in progress. */ + /* The qualified handoff is x1, with no retrain in progress. */ cap = readb(rp + PCI_CAPABILITY_LIST); for (i = 0; cap && i < 48; i++) { if (cap < 0x40 || (cap & 3)) @@ -2042,13 +2151,17 @@ static int apple_pcie_adopt_link(struct apple_pcie_port *port) if (!cap || i == 48) return -EINVAL; /* - * x1 at up to the Gen3 target the bootloader set. The endpoint picks the speed: the N1's - * ROM personality links at Gen1 and comes back at Gen3 after its root-port reset. + * x1 at up to the target link speed the bootloader set in the root port, which + * it takes from the port's ADT bridge: 8 GT/s where that sets 3 (the N1, the + * USB-A controller), the root port's fastest where it sets none (the J775D's + * 10 Gb Ethernet). The endpoint picks the speed within it: the N1's ROM + * personality links at Gen1 and comes back at Gen3 after its root-port reset. */ value = readw(rp + cap + PCI_EXP_LNKSTA); + tls = readw(rp + cap + PCI_EXP_LNKCTL2) & PCI_EXP_LNKCTL2_TLS; if ((value & (PCI_EXP_LNKSTA_NLW | PCI_EXP_LNKSTA_LT)) != (1 << PCI_EXP_LNKSTA_NLW_SHIFT) || (value & PCI_EXP_LNKSTA_CLS) < PCI_EXP_LNKSTA_CLS_2_5GB || - (value & PCI_EXP_LNKSTA_CLS) > PCI_EXP_LNKSTA_CLS_8_0GB) + (value & PCI_EXP_LNKSTA_CLS) > tls) return -ENOLINK; /* Refuse an active endpoint or malformed capability chain. */ @@ -2089,10 +2202,10 @@ static int apple_pcie_adopt_link(struct apple_pcie_port *port) /* * T6050 port bring-up, for an adopted port whose endpoint must come back on a * retrained link: port disable, the port reset table, port enable, root complex - * configuration for Gen3 x1, then the lane PHY, PERST# and the LTSSM. The port's - * registers are its port, phy and intr2axi blocks; the root complex's - * are the root port's config space. The boot loader copies the port's tunables - * onto its node. + * configuration (an x1 link at the port's max-link-speed), then the lane PHY, + * PERST# and the LTSSM. The port's registers are its port, phy and + * intr2axi blocks; the root complex's are the root port's config space. The + * boot loader copies the port's tunables onto its node. */ static const struct apple_pcie_reset_reg apple_pcie_t6050_reset_regs[] = { { 0x088, 0x00000110 }, @@ -2304,7 +2417,12 @@ static int apple_pcie_t6050_port_enable(struct apple_pcie_port *port) 250000); } -/* Root complex tunables and a Gen3 x1 link, with the read-only registers opened for it */ +/* + * Root complex tunables and an x1 link at the port's DT "max-link-speed" (which the + * boot loader fills in from the ADT), 8 GT/s without one, with the read-only + * registers opened for it. A speed above the root port's fastest is lowered to it, + * as the boot loader does. + */ static int apple_pcie_t6050_port_configure(struct apple_pcie_port *port) { static const char * const shadow[] = { @@ -2315,11 +2433,16 @@ static int apple_pcie_t6050_port_configure(struct apple_pcie_port *port) static const u32 shadow_sel[] = { 0, BIT(24), 0 }; void __iomem *dbi = apple_pcie_t6050_dbi(port); int cap = apple_pcie_t6050_exp_cap(dbi); + int speed = of_pci_get_max_link_speed(port->np); + int top; + u32 sls; u16 ctl2; int ret, i; if (!cap) return -EIO; + if (speed <= 0) + speed = PCI_EXP_LNKCTL2_TLS_8_0GT; apple_pcie_t6050_dbi_rmw(dbi, RC_T6050_MISC_CONTROL_1, 0, RC_T6050_DBI_RO_WR_EN); ret = apple_pcie_t6050_tune(port, dbi, "apple,pcie-rc-tunables"); for (i = 0; !ret && i < ARRAY_SIZE(shadow); i++) { @@ -2329,13 +2452,19 @@ static int apple_pcie_t6050_port_configure(struct apple_pcie_port *port) } if (!ret) { apple_pcie_t6050_dbi_rmw(dbi, 0x194, 0, BIT(0)); - if (!(readl(dbi + cap + PCI_EXP_LNKCAP2) & PCI_EXP_LNKCAP2_SLS_8_0GB)) + sls = readl(dbi + cap + PCI_EXP_LNKCAP2) & PCI_EXP_LNKCAP2_SLS; + top = sls ? __fls(sls) : 0; + if (top && speed > top) { + dev_info(port->pcie->dev, "port %d: max-link-speed %d above the root port's %d\n", + port->idx, speed, top); + speed = top; + } + if (!top || !(sls & BIT(speed))) ret = -EIO; } if (!ret) { ctl2 = readw(dbi + cap + PCI_EXP_LNKCTL2); - writew((ctl2 & ~PCI_EXP_LNKCTL2_TLS) | PCI_EXP_LNKCTL2_TLS_8_0GT, - dbi + cap + PCI_EXP_LNKCTL2); + writew((ctl2 & ~PCI_EXP_LNKCTL2_TLS) | speed, dbi + cap + PCI_EXP_LNKCTL2); apple_pcie_t6050_dbi_rmw(dbi, RC_T6050_PORT_LINK_CTRL, RC_T6050_LINK_MODE, FIELD_PREP(RC_T6050_LINK_MODE, 1)); apple_pcie_t6050_dbi_rmw(dbi, RC_T6050_LINK_WIDTH_SPEED_CTRL, RC_T6050_LINK_WIDTH, @@ -2761,8 +2890,9 @@ static int apple_pcie_t6050_port_routes(struct apple_pcie_port *port, const u32 * Root-port reset of an adopted T6050 port, for an endpoint that must come back on a * retrained link (the N1 after its ROM boot): PME_Turn_Off to L2, PERST# asserted, the * port disabled, reset, enabled and configured, its routes and MSI map rewritten, then the - * lane PHY, PERST# release and LTSSM to a Gen3 x1 link. The caller has quiesced the - * endpoint and saved the root port's state; the PCI core restores it. + * lane PHY, PERST# release and LTSSM to an x1 link at the port's max-link-speed. The + * caller has quiesced the endpoint and saved the root port's state; the PCI core + * restores it. */ static int apple_pcie_t6050_reset_root_port(struct pci_host_bridge *bridge, struct pci_dev *rp) @@ -3387,8 +3517,26 @@ static int apple_msi_init(struct apple_pcie *pcie) * 32-vector slice. Keep endpoint MSI data local, and route its table * entry to the corresponding shared-window vector. */ - if (pcie->hw == &t8122_pciec_hw || pcie->hw == &t8132_pciec_hw || - pcie->hw == &t6040_pciec_hw) { + if (pcie->hw == &t8132_pciec_hw || pcie->hw == &t8142_pciec_hw || + pcie->hw == &t8152_pciec_hw) { + /* + * msi-ranges names the AIC input of global vector + * apple,msi-vector-base in a linear window, so the slice is + * checked by its shape only: an edge-rising SPI, 32 vectors, + * 32-aligned, above the internal port's vectors and inside the + * 8-bit map target. + */ + if (args.args_count != 3 || args.args[0] != 0 || + args.args[2] != IRQ_TYPE_EDGE_RISING || + of_property_read_u32(to_of_node(fwnode), + "apple,msi-vector-base", + &pcie->msi_vector_base) || + args.args[1] < pcie->msi_vector_base || + !apple_t6030_msi_slice_valid(pcie->msi_vector_base, + pcie->nvecs, args.args[1], + args.args[1] - pcie->msi_vector_base)) + goto invalid_slice; + } else if (pcie->hw == &t8122_pciec_hw || pcie->hw == &t6040_pciec_hw) { struct resource ecam; u32 expected_base, aic_base; @@ -3425,19 +3573,6 @@ static int apple_msi_init(struct apple_pcie *pcie) default: goto invalid_slice; } - } else if (of_machine_is_compatible("apple,t8132")) { - aic_base = 1506; - switch (ecam.start) { - /* The internal port's bridges own vectors 0..95. */ - case 0x1c50000000ULL: - expected_base = 0x60; - break; - case 0x1c60000000ULL: - expected_base = 0x80; - break; - default: - goto invalid_slice; - } } else { goto invalid_slice; } @@ -3471,7 +3606,8 @@ static int apple_msi_init(struct apple_pcie *pcie) /* Keep map targets within the supported 8-bit range. */ if ((pcie->hw == &t8122_pciec_hw || pcie->hw == &t8132_pciec_hw || - pcie->hw == &t6040_pciec_hw) && + pcie->hw == &t6040_pciec_hw || pcie->hw == &t8142_pciec_hw || + pcie->hw == &t8152_pciec_hw) && (!pcie->nvecs || pcie->nvecs > 256 || pcie->msi_vector_base > FIELD_MAX(PORT_MSIMAP_TARGET) + 1 - pcie->nvecs)) { @@ -3691,6 +3827,25 @@ static int apple_pcie_adopted_no_clkpm_walk(struct pci_dev *pdev, void *data) return 0; } +/* + * An adopted port with an endpoint power GPIO (pwren-gpios) is trained by + * Linux. Match the root port itself as well as functions below it. + * If no port matches, neither kind of training can be established. + */ +static bool apple_pcie_adopted_link_trained_by(struct apple_pcie *pcie, + struct pci_dev *pdev, bool bootloader) +{ + struct pci_dev *rp = pcie_find_root_port(pdev); + struct apple_pcie_port *port; + + if (!pcie->hw->adopt_link || !rp) + return false; + list_for_each_entry(port, &pcie->ports, entry) + if (port->idx == PCI_SLOT(rp->devfn)) + return bootloader == !port->pwren; + return false; +} + static int apple_pcie_enable_device(struct pci_host_bridge *bridge, struct pci_dev *pdev) { struct apple_pcie *pcie = pci_host_bridge_priv(bridge); @@ -3711,6 +3866,14 @@ static int apple_pcie_enable_device(struct pci_host_bridge *bridge, struct pci_d if (pcie->hw->tunneled) pdev->dev_flags |= PCI_DEV_FLAGS_NO_D3; + /* + * Firmware owns the power of a boot-trained adopted link, and s2idle + * requires the port and everything below it to stay accessible in D0. + * Keep the PCI core's suspend paths from putting them in D3hot. + */ + if (apple_pcie_adopted_link_trained_by(pcie, pdev, true)) + pdev->dev_flags |= PCI_DEV_FLAGS_NO_D3; + /* * Endpoint BARs share PCIe-C's tunneled, non-posted MMIO fabric. Mark * them before the function driver maps its BAR so pci_iomap() selects @@ -3996,7 +4159,7 @@ static int apple_pcie_config_write(struct pci_bus *bus, unsigned int devfn, if (pcie->hw->mps_timers && where == PCIEC_RP_DEVCTL) apple_pcie_update_mps_timers(pcie, FIELD_GET(PCI_EXP_DEVCTL_PAYLOAD, val)); - if (!pcie->kernel_init) + if (!(pcie->kernel_init || pcie->tunnel_cold_init)) return ret; /* Root-port prefetchable window. The port block has to be told too. */ if (where < 0x24 || where >= 0x30) @@ -5380,35 +5543,14 @@ static int apple_pcie_t6050_pm_notify(struct notifier_block *nb, unsigned long a static void apple_pcie_t6050_warm_reset_probe(struct platform_device *pdev, struct apple_pcie *pcie, struct apple_pcie_port *port) { - struct of_phandle_args fn; - int count, i; - if (!IS_REACHABLE(CONFIG_MFD_MACSMC) || - of_parse_phandle_with_fixed_args(port->np, "apple,function-warm-reset", 2, 0, &fn)) - return; - pcie->t6050_smc = of_find_device_by_node(fn.np); - of_node_put(fn.np); - if (!pcie->t6050_smc) + apple_smc_warm_reset_parse(port->np, &pcie->t6050_warm)) return; - count = of_property_count_u32_elems(port->np, "apple,warm-reset-writes"); - if (count < 2 || count % 2 || count > ARRAY_SIZE(pcie->t6050_warm_writes) || - of_property_read_u32_array(port->np, "apple,warm-reset-writes", - pcie->t6050_warm_writes, count)) - goto drop; - for (i = 1; i < count; i += 2) - if (pcie->t6050_warm_writes[i] > 100 * USEC_PER_MSEC) - goto drop; /* The SMC's noirq resume comes before this host's: the reset is written from there */ - if (!device_link_add(&pdev->dev, &pcie->t6050_smc->dev, DL_FLAG_STATELESS)) { + if (!device_link_add(&pdev->dev, &pcie->t6050_warm.smc->dev, DL_FLAG_STATELESS)) { dev_warn(&pdev->dev, "no warm reset after a sleep: no link to the SMC\n"); - goto drop; + apple_smc_warm_reset_put(&pcie->t6050_warm); } - pcie->t6050_warm_key = fn.args[0]; - pcie->t6050_warm_count = count / 2; - return; -drop: - put_device(&pcie->t6050_smc->dev); - pcie->t6050_smc = NULL; } /* @@ -5419,34 +5561,15 @@ static void apple_pcie_t6050_warm_reset_probe(struct platform_device *pdev, stru */ static int apple_pcie_t6050_warm_reset(struct apple_pcie *pcie, bool noirq) { - struct apple_smc *smc; - unsigned int i; - int ret = 0; + int ret; pcie->t6050_warm_done = false; - if (!IS_REACHABLE(CONFIG_MFD_MACSMC) || !pcie->t6050_warm_count) + if (!IS_REACHABLE(CONFIG_MFD_MACSMC) || !pcie->t6050_warm.count) return -ENODEV; - smc = platform_get_drvdata(pcie->t6050_smc); - if (!smc) { + ret = apple_smc_warm_reset(&pcie->t6050_warm, noirq); + if (ret == -ENODEV) { dev_warn(pcie->dev, "no warm reset: the SMC isn't bound\n"); - return -ENODEV; - } - for (i = 0; i < pcie->t6050_warm_count && !ret; i++) { - __be32 value = cpu_to_be32(pcie->t6050_warm_writes[2 * i]); - u32 wait = pcie->t6050_warm_writes[2 * i + 1]; - smc_key key = pcie->t6050_warm_key; - - if (noirq) { - ret = apple_smc_write_noirq(smc, key, &value, sizeof(value)); - if (!ret) { - mdelay(wait / USEC_PER_MSEC); - udelay(wait % USEC_PER_MSEC); - } - } else { - ret = apple_smc_write(smc, key, &value, sizeof(value)); - if (!ret) - fsleep(wait); - } + return ret; } pcie->t6050_warm_done = !ret; if (ret) @@ -5465,8 +5588,7 @@ static void apple_pcie_t6050_sleep_probe(struct platform_device *pdev, struct ap { struct apple_pcie_port *port; - if (pcie->managed_sids || !(of_machine_is_compatible("apple,j714s") || - of_machine_is_compatible("apple,j716c"))) + if (pcie->managed_sids || !apple_t6050_sleep_described()) return; /* The one port a boot loader trained; an endpoint Linux powers is parked instead. */ list_for_each_entry(port, &pcie->ports, entry) @@ -5646,7 +5768,7 @@ void apple_pcie_t6050_sleep_reset(struct pci_dev *bridge) { struct apple_pcie *pcie = apple_pcie_t6050_from_bridge(bridge); - if (pcie && pcie->t6050_warm_count) { + if (pcie && pcie->t6050_warm.count) { pcie->t6050_keep_alive = false; pcie->t6050_reset_before_sleep = true; } @@ -5711,7 +5833,7 @@ int apple_pcie_t6050_port_recycle(struct pci_dev *bridge) if (!pcie) return -ENODEV; - if (!pcie->t6050_warm_count || pcie->t6050_lost || READ_ONCE(pcie->t6050_down)) + if (!pcie->t6050_warm.count || pcie->t6050_lost || READ_ONCE(pcie->t6050_down)) return -EBUSY; pci_save_state(bridge); ret = apple_pcie_t6050_sleep_down(pcie); @@ -5727,11 +5849,25 @@ int apple_pcie_t6050_port_recycle(struct pci_dev *bridge) } EXPORT_SYMBOL_GPL(apple_pcie_t6050_port_recycle); +/* + * An adopting host must keep the bootloader's bus numbers: the handed-over + * device tree's iommu-map names each adopted endpoint by the RID the + * bootloader gave it, and the RID-to-SID routes are programmed for that RID. + * Reassigning bus numbers over only the adopted root ports changes the + * secondary bus whenever the bootloader numbered a port that Linux does not + * adopt (for example after a reset where only a subset of links trained), + * leaving the endpoint unreachable because config cycles go only to the + * adopted bus. + */ static int apple_pcie_host_init(struct platform_device *pdev, struct pci_host_bridge *bridge) { struct apple_pcie *pcie = pci_host_bridge_priv(bridge); - int ret = pci_host_common_init(pdev, bridge, &apple_pcie_cfg_ecam_ops); + int ret; + if (pcie->hw->adopt_link) + bridge->no_reassign_bus = true; + + ret = pci_host_common_init(pdev, bridge, &apple_pcie_cfg_ecam_ops); if (!ret && pcie->hw->adopt_link) pci_walk_bus(bridge->bus, apple_pcie_adopted_no_clkpm_walk, NULL); return ret; @@ -5747,6 +5883,9 @@ static int apple_pcie_probe(struct platform_device *pdev) struct device *piodma_supplier = NULL; int ret; + /* Setting the ports up again after a real sleep takes ~0.75 s: resume in parallel. */ + device_enable_async_suspend(&pdev->dev); + hw = of_device_get_match_data(dev); if (!hw) return -ENODEV; @@ -5812,6 +5951,7 @@ static int apple_pcie_probe(struct platform_device *pdev) if (ret) return dev_err_probe(dev, ret, "Failed to attach power domains\n"); + bridge->no_inc_mrrs = hw->no_inc_mrrs; if (of_property_present(dev->of_node, "apple,managed-sids")) { u32 ids[15]; int count = of_property_count_u32_elems(dev->of_node, "apple,managed-sids"); @@ -5869,6 +6009,7 @@ static int apple_pcie_probe(struct platform_device *pdev) mutex_init(&pcie->lock); INIT_LIST_HEAD(&pcie->ports); + INIT_LIST_HEAD(&pcie->hib_fns); /* Resolve PM dependencies before publishing the PCI hierarchy. */ if (pcie->hw->tunneled) { @@ -6101,7 +6242,8 @@ static int apple_pcie_tunnel_other_driver(struct pci_dev *pdev, void *data) { struct device_driver *drv = READ_ONCE(pdev->dev.driver); - if (!drv || !strcmp(drv->name, "nvme") || !strcmp(drv->name, "pcieport")) + if (!drv || !strcmp(drv->name, "nvme") || !strcmp(drv->name, "pcieport") || + !strcmp(drv->name, "igc")) return 0; *(const char **)data = drv->name; return 1; @@ -6115,13 +6257,14 @@ static int apple_pcie_tunnel_other_driver(struct pci_dev *pdev, void *data) * For a sleep that takes the tunnel's router down. Unlike apple_pcie_tunnel_quiesce(), which * marks the functions disconnected first (their drivers then treat them as gone), the * functions are removed while they still answer: an NVMe controller's driver stops its - * queues and gives the controller its normal shutdown, as at a power-off. Nothing is written + * queues and gives the controller its normal shutdown, as at a power-off, and igc + * unregisters its netdev cleanly without touching PM notifiers. Nothing is written * to a disk that has no opener. apple_pcie_tunnel_quiesce() then takes the ports down and * apple_pcie_tunnel_restore() enumerates the hierarchy again. * * Returns 0 when the hierarchy is removed (or was already), -EBUSY when a disk is open and - * @in_use_too is false, -EOPNOTSUPP when a function has a driver other than nvme or the PCIe - * port driver. Nothing is removed on an error. + * @in_use_too is false, -EOPNOTSUPP when a function has a driver other than nvme, igc, or + * the PCIe port driver. Nothing is removed on an error. */ int apple_pcie_tunnel_remove_orderly(struct device *dev, bool in_use_too) { @@ -6789,22 +6932,9 @@ static void apple_pcie_stop_for_sleep(struct device *dev) static void apple_pcie_neo_save_functions(struct apple_pcie *pcie); -/* Whether Linux trained the port above pdev itself (cold train), rather than adopting it */ -static bool apple_pcie_below_kernel_trained_port(struct pci_dev *pdev) -{ - struct pci_config_window *cfg = pdev->sysdata; - struct apple_pcie *pcie = apple_pcie_lookup(cfg->parent); - struct pci_dev *rp = pcie_find_root_port(pdev); - struct apple_pcie_port *port; - - if (!rp) - return false; - list_for_each_entry(port, &pcie->ports, entry) - if (port->idx == PCI_SLOT(rp->devfn)) - return !!port->pwren; - return false; -} - +static bool apple_pcie_s2r_reinit(struct apple_pcie *pcie); +static void apple_pcie_hib_save(struct apple_pcie *pcie); +static void apple_pcie_hib_restore_noirq(struct apple_pcie *pcie, const char *what); /* * The J716c radio drivers save PCI state without entering D3. The PCI core * keeps the root port in D0 as well. Its host and DART have no switchable @@ -6816,6 +6946,8 @@ static bool apple_pcie_below_kernel_trained_port(struct pci_dev *pdev) */ static int apple_pcie_check_d0(struct pci_dev *pdev, void *data) { + struct pci_config_window *cfg = pdev->sysdata; + struct apple_pcie *pcie = apple_pcie_lookup(cfg->parent); int *error = data; u16 value; @@ -6826,7 +6958,7 @@ static int apple_pcie_check_d0(struct pci_dev *pdev, void *data) * asked to stay awake need to remain in D0. */ if (!device_awake_path(&pdev->dev) && - apple_pcie_below_kernel_trained_port(pdev)) + apple_pcie_adopted_link_trained_by(pcie, pdev, false)) return 0; if (pci_read_config_word(pdev, PCI_VENDOR_ID, &value) || @@ -6842,22 +6974,16 @@ static int apple_pcie_check_d0(struct pci_dev *pdev, void *data) return *error; } -static int apple_pcie_check_adopted_s2idle(struct apple_pcie *pcie) +/* + * Every host whose links the boot loader trained (hw->adopt_link) keeps them + * across suspend-to-idle: the root complex and every port's link must still + * be up, read from the hardware. Deeper sleep remains unqualified. + */ +static int apple_pcie_adopted_links_ready(struct apple_pcie *pcie) { - struct pci_host_bridge *bridge = pci_host_bridge_from_priv(pcie); struct apple_pcie_port *port; - int error = 0; - /* - * Qualified on the J716c, the K114c, the K116s and the J714s: the same - * T6050 host with the N1 adopted on port 0. The K116s and the J714s - * (16- and 14-inch M5 Pro) also have a kernel-trained SD reader port. - * Other adopted platforms and deeper sleep remain unqualified. - */ - if (!(of_machine_is_compatible("apple,j716c") || - of_machine_is_compatible("apple,k114c") || - of_machine_is_compatible("apple,k116s") || - of_machine_is_compatible("apple,j714s")) || !pm_suspend_no_platform()) + if (!pm_suspend_no_platform()) return -EBUSY; if (!(readl(pcie->base + CORE_RC_CTL) & CORE_RC_CTL_RUN) || @@ -6865,6 +6991,9 @@ static int apple_pcie_check_adopted_s2idle(struct apple_pcie *pcie) return -ENOLINK; list_for_each_entry(port, &pcie->ports, entry) { + /* Parked for this sleep: held down on purpose, and may not answer */ + if (pcie->t6050_parked & BIT(port->idx)) + continue; if (READ_ONCE(port->link_failed) || !(apple_pcie_port_readl(port, PORT_STATUS) & PORT_STATUS_READY) || (apple_pcie_port_readl(port, PORT_LINKSTS) & @@ -6872,6 +7001,35 @@ static int apple_pcie_check_adopted_s2idle(struct apple_pcie *pcie) (apple_pcie_port_readl(port, PORT_INTSTAT) & BIT(PORT_INT_LINK_DOWN))) return -ENOLINK; } + return 0; +} + +/* + * An adopted host that apple_pcie_suspend_noirq() puts to sleep itself, given + * that it passed the CIO-DART refusal: not in a CIO or NEO sleep transaction, + * not a managed radio, and up. For suspend-to-idle it ends in + * apple_pcie_check_adopted_s2idle(); for a firmware suspend in + * apple_pcie_t6050_sleep_down(). apple_pcie_prepare() refuses on the same terms. + */ +static bool apple_pcie_adopted_sleep_host(struct apple_pcie *pcie) +{ + return !pcie->cio_prepared && !pcie->neo_sleep_armed && !pcie->managed_sids && + pcie->hw->adopt_link && !READ_ONCE(pcie->t6050_down); +} + +static bool apple_pcie_adopted_s2idle_checked(struct apple_pcie *pcie) +{ + return apple_pcie_adopted_sleep_host(pcie) && !pm_suspend_via_firmware(); +} + +/* ... and the devices below must still be in D0, before and after the sleep. */ +static int apple_pcie_check_adopted_s2idle(struct apple_pcie *pcie) +{ + struct pci_host_bridge *bridge = pci_host_bridge_from_priv(pcie); + int error = apple_pcie_adopted_links_ready(pcie); + + if (error) + return error; pci_walk_bus(bridge->bus, apple_pcie_check_d0, &error); return error; } @@ -6922,24 +7080,37 @@ static int apple_pcie_suspend_noirq(struct device *dev) if (!pcie->managed_sids && pcie->hw->adopt_link) { int ret; + if (apple_pcie_adopted_s2idle_checked(pcie)) { + ret = apple_pcie_check_adopted_s2idle(pcie); + pcie->link_kept = !ret; + return ret; + } /* Down since a wake that failed: nothing to keep or shut down, nothing read */ if (READ_ONCE(pcie->t6050_down)) return 0; - if (pm_suspend_via_firmware()) { - /* The root ports below are suspended: from here a parked port's is not read */ - WRITE_ONCE(pcie->t6050_cold_lost, pcie->t6050_parked); - ret = apple_pcie_t6050_sleep_down(pcie); - if (!ret && pcie->t6050_reset_before_sleep) - ret = apple_pcie_t6050_reset_for_sleep(pcie); - return ret; - } - ret = apple_pcie_check_adopted_s2idle(pcie); - - pcie->link_kept = !ret; + /* + * A firmware suspend. The root ports below are suspended: from here a + * parked port's is not read. + */ + WRITE_ONCE(pcie->t6050_cold_lost, pcie->t6050_parked); + ret = apple_pcie_t6050_sleep_down(pcie); + if (!ret && pcie->t6050_reset_before_sleep) + ret = apple_pcie_t6050_reset_for_sleep(pcie); return ret; } if (!pcie->hw->tunneled) { - if (pm_suspend_no_platform() && pcie->num_pds) + bool s2r_reinit = apple_pcie_s2r_reinit(pcie) && pm_suspend_via_firmware(); + + if (s2r_reinit) + apple_pcie_hib_save(pcie); + /* + * Keep the host's power domains on across genpd noirq suspend + * for s2idle and firmware sleeps: on an abandoned or dry-run + * firmware sleep the commit never runs, so gating the domain + * here would leave the controller unprogrammed with no wake + * sequence to reinitialize it. A real commit powers it down. + */ + if ((pm_suspend_no_platform() || s2r_reinit) && pcie->num_pds) return apple_pcie_hold_domains(pcie); return 0; } @@ -7442,7 +7613,7 @@ static int apple_pcie_resume_noirq(struct device *dev) /* Up, and reset unless kept alive: nothing takes it down again */ pcie->t6050_woke = !READ_ONCE(pcie->t6050_down) && !pcie->t6050_lost && (!warm_reset || pcie->t6050_warm_done || - !pcie->t6050_warm_count); + !pcie->t6050_warm.count); list_for_each_entry(port, &pcie->ports, entry) if (pcie->t6050_parked & BIT(port->idx)) dev_dbg(dev, "port %d at the wake: parked since before the sleep, power off, PERST# low, no functions, root port %s, DART %s; %s\n", @@ -7470,8 +7641,19 @@ static int apple_pcie_resume_noirq(struct device *dev) } return ret; } - if (!pcie->hw->tunneled) + if (!pcie->hw->tunneled) { + if (pcie->hib_saved) { + if (pm_resume_via_firmware()) { + apple_pcie_hib_restore_noirq(pcie, "S2R"); + } else { + /* Refused before commit: registers are intact. */ + pcie->hib_saved = false; + list_for_each_entry(port, &pcie->ports, entry) + apple_pcie_port_enable_irq(port); + } + } return 0; + } if (pcie->resume_failed) return -EIO; /* @@ -7538,6 +7720,220 @@ static int apple_pcie_resume_noirq(struct device *dev) return ret; } +/* + * A conventional host (the internal ports with the radio and the SD reader) loses its power + * in a real sleep: the endpoints sit unpowered or in reset behind a link that is down. The + * resume then does what probe did. From aurora-silicon/linux#1477 (0ab1a6603). + */ +struct apple_pcie_hib_fn { + struct list_head entry; + struct pci_dev *pdev; + struct pci_saved_state *state; +}; + +/* A real sleep takes a conventional host's power: its ports are set up again as at probe. */ +static bool apple_pcie_s2r_reinit(struct apple_pcie *pcie) +{ + return !pcie->hw->tunneled && !pcie->managed_sids && !pcie->piodma_supplier && + !pcie->hw->root_bus_only; +} + +/* What only the port registers hold. */ +static void apple_pcie_hib_save(struct apple_pcie *pcie) +{ + struct apple_pcie_port *port; + int i; + + mutex_lock(&pcie->lock); + list_for_each_entry(port, &pcie->ports, entry) { + /* + * A chained port interrupt stays unmasked across suspend_device_irqs(). + * Mask and gate it before firmware sleep so a complex whose boot-time + * reinit leaves PORT_INTMSK clear cannot storm at AIC resume before + * apple_pcie_resume() masks and restores the port. + */ + apple_pcie_port_disable_irq(port); + port->hib_link_up = apple_pcie_port_readl(port, PORT_LINKSTS) & PORT_LINKSTS_UP; + port->hib_cold = false; + port->saved_intmask = apple_pcie_port_readl(port, PORT_INTMSK); + for_each_set_bit(i, port->sid_map, port->sid_map_sz) + port->saved_rid2sid[i] = + apple_pcie_port_readl(port, port_rid2sid_offset(port, i)); + } + pcie->hib_saved = true; + mutex_unlock(&pcie->lock); +} + +static void apple_pcie_hib_free_fns(struct apple_pcie *pcie) +{ + struct apple_pcie_hib_fn *fn, *tmp; + + list_for_each_entry_safe(fn, tmp, &pcie->hib_fns, entry) { + list_del(&fn->entry); + kfree(fn->state); + pci_dev_put(fn->pdev); + kfree(fn); + } +} + +/* + * The PCI core's noirq resume spends the functions' saved state on a link that is down + * ("device inaccessible"). A copy taken first goes back once the link is. + */ +static int apple_pcie_hib_keep_fn(struct pci_dev *pdev, void *data) +{ + struct apple_pcie *pcie = data; + struct apple_pcie_port *port; + struct apple_pcie_hib_fn *fn; + + if (pci_is_root_bus(pdev->bus) || !pdev->state_saved) + return 0; + port = apple_pcie_get_port(pdev); + if (!port || !port->hib_cold) + return 0; + fn = kzalloc(sizeof(*fn), GFP_ATOMIC); + if (!fn) + return 0; + fn->state = pci_store_saved_state(pdev); + if (!fn->state) { + kfree(fn); + return 0; + } + fn->pdev = pci_dev_get(pdev); + list_add_tail(&fn->entry, &pcie->hib_fns); + return 0; +} + +/* Before the PCI core restores the functions; nothing is written to a port in this phase. */ +static void apple_pcie_hib_restore_noirq(struct apple_pcie *pcie, const char *what) +{ + struct pci_host_bridge *bridge = pci_host_bridge_from_priv(pcie); + struct apple_pcie_port *port; + bool cold = false; + + apple_pcie_hib_free_fns(pcie); + list_for_each_entry(port, &pcie->ports, entry) { + if (!port->hib_link_up) + continue; + if (apple_pcie_port_readl(port, PORT_LINKSTS) & PORT_LINKSTS_UP) + continue; + port->hib_cold = true; + cold = true; + dev_info(pcie->dev, "%s: %pOF lost its link, setting it up again\n", + what, port->np); + } + if (cold && bridge->bus) + pci_walk_bus(bridge->bus, apple_pcie_hib_keep_fn, pcie); +} + +static void apple_pcie_hib_rid2sid(struct apple_pcie *pcie, struct apple_pcie_port *port) +{ + int i; + + mutex_lock(&pcie->lock); + for (i = 0; i < port->sid_map_sz; i++) + apple_pcie_rid2sid_write(port, i, test_bit(i, port->sid_map) ? + port->saved_rid2sid[i] : 0); + mutex_unlock(&pcie->lock); +} + +/* Probe's bring-up of a conventional port, with the state this kernel had programmed. */ +static int apple_pcie_hib_port_up(struct apple_pcie *pcie, struct apple_pcie_port *port) +{ + u32 stat; + int ret; + + ret = apple_pcie_setup_link(pcie, port, port->np); + if (ret) + return ret; + if (!pcie->hw->retain_clocks) { + if (pcie->hw->port_refclk) + rmw_clear(PORT_REFCLK_CGDIS, port->base + pcie->hw->port_refclk); + else if (port->phy) + rmw_set(PHY_LANE_CFG_REFCLKCGEN, port->phy + PHY_LANE_CFG); + rmw_clear(PORT_APPCLK_CGDIS, port->base + PORT_APPCLK); + } + /* All port interrupts masked and cleared, MSI routing as at probe. */ + apple_pcie_tunnel_restore_irq_hw(port); + apple_pcie_hib_rid2sid(pcie, port); + apple_pcie_port_writel(port, PORT_LTSSMCTL_START, PORT_LTSSMCTL); + ret = readl_relaxed_poll_timeout(port->base + PORT_LINKSTS, stat, + stat & PORT_LINKSTS_UP, 100, link_up_timeout * 1000); + if (ret) { + dev_err(pcie->dev, "S2R: %pOF status %#x link %#x after training\n", port->np, + apple_pcie_port_readl(port, PORT_STATUS), stat); + return ret; + } + apple_pcie_port_writel(port, BIT(PORT_INT_LINK_UP), PORT_INTSTAT); + apple_pcie_port_writel(port, port->saved_intmask, PORT_INTMSK); + /* 100 ms after the link before configuration requests (PCIe r5.0, 6.6.1). */ + msleep(100); + return 0; +} + +/* The normal phase, after the SMC (the PWREN GPIOs are its) and before the functions. */ +static int apple_pcie_resume(struct device *dev) +{ + struct apple_pcie *pcie = apple_pcie_lookup(dev); + struct apple_pcie_port *port; + struct apple_pcie_hib_fn *fn; + int ret; + + if (!pcie->hib_saved) + return 0; + pcie->hib_saved = false; + if (!apple_pcie_s2r_reinit(pcie) || !pm_resume_via_firmware()) { + list_for_each_entry(port, &pcie->ports, entry) + apple_pcie_port_enable_irq(port); + return 0; + } + list_for_each_entry(port, &pcie->ports, entry) { + if (!port->hib_link_up) { + apple_pcie_port_writel(port, ~0, PORT_INTMSK); + apple_pcie_port_writel(port, ~0, PORT_INTSTAT); + apple_pcie_port_enable_irq(port); + continue; + } + if (!port->hib_cold) { + apple_pcie_hib_rid2sid(pcie, port); + apple_pcie_port_enable_irq(port); + continue; + } + ret = apple_pcie_hib_port_up(pcie, port); + if (ret) { + dev_err(dev, "S2R: %pOF link not back (%d), its functions stay unreachable\n", + port->np, ret); + apple_pcie_port_writel(port, ~0, PORT_INTMSK); + apple_pcie_port_writel(port, ~0, PORT_INTSTAT); + port->hib_cold = false; + apple_pcie_port_enable_irq(port); + continue; + } + apple_pcie_port_enable_irq(port); + dev_info(dev, "S2R: %pOF link back, PWREN and PERST# cycled as at probe\n", + port->np); + } + list_for_each_entry(fn, &pcie->hib_fns, entry) { + port = apple_pcie_get_port(fn->pdev); + if (!port || !port->hib_cold) + continue; + /* + * The PCI core's noirq power-up ran with the link down and left the function + * marked D3: the reset brought it up in D0, so record that before the + * restore, or its driver's resume can't enable MSI again (-EINVAL). + */ + pci_set_power_state(fn->pdev, PCI_D0); + if (pci_load_saved_state(fn->pdev, fn->state)) + pci_warn(fn->pdev, "S2R: saved configuration not taken back\n"); + else + pci_restore_state(fn->pdev); + } + apple_pcie_hib_free_fns(pcie); + list_for_each_entry(port, &pcie->ports, entry) + port->hib_cold = false; + return 0; +} + static int apple_pcie_prepare(struct device *dev) { struct apple_pcie *pcie = apple_pcie_lookup(dev); @@ -7553,6 +7949,29 @@ static int apple_pcie_prepare(struct device *dev) dev_warn(dev, "no CIO sleep transaction from the NHI; refusing sleep\n"); return -EBUSY; } + /* + * An adopted link that apple_pcie_suspend_noirq() would already refuse to + * keep: refuse now. Refused there, the root ports and endpoints below have + * already suspended to D3hot, this host gets no noirq resume, and nothing + * retrains their links before their drivers resume. A link that drops + * after this is still refused only there. + */ + if (pcie && pm_suspend_target_state != PM_SUSPEND_ON && + apple_pcie_adopted_sleep_host(pcie)) { + int ret; + + /* A firmware suspend: the port and DART apple_pcie_t6050_sleep_down() takes down */ + if (pm_suspend_via_firmware()) + ret = pcie->t6050_port && pcie->t6050_dart ? 0 : -EBUSY; + else + ret = apple_pcie_adopted_links_ready(pcie); + + if (ret) { + dev_warn(dev, "adopted link not kept for this sleep (%d); refusing\n", + ret); + return ret; + } + } return apple_radio_prepare(dev); } @@ -7561,12 +7980,15 @@ static const struct dev_pm_ops apple_pcie_pm_ops = { .complete = apple_radio_complete, .suspend_noirq = apple_pcie_suspend_noirq, .resume_noirq = apple_pcie_resume_noirq, + .resume = apple_pcie_resume, .resume_early = apple_pcie_resume_early, }; static const struct of_device_id apple_pcie_of_match[] = { { .compatible = "apple,t6040-pciec", .data = &t6040_pciec_hw }, { .compatible = "apple,t6050-pciec", .data = &t6050_pciec_hw }, + { .compatible = "apple,t8142-pciec", .data = &t8142_pciec_hw }, + { .compatible = "apple,t8152-pciec", .data = &t8152_pciec_hw }, { .compatible = "apple,t8132-pciec", .data = &t8132_pciec_hw }, { .compatible = "apple,t8122-pciec", .data = &t8122_pciec_hw }, { .compatible = "apple,t8112-pciec", .data = &t8112_pciec_hw }, diff --git a/drivers/pci/pcie/aspm.c b/drivers/pci/pcie/aspm.c index 3b02e794dbd740..417d5b45868399 100644 --- a/drivers/pci/pcie/aspm.c +++ b/drivers/pci/pcie/aspm.c @@ -923,14 +923,41 @@ static void pcie_aspm_override_default_link_state(struct pcie_link_state *link) link->aspm_default |= PCIE_LINK_STATE_L0S; if (link->aspm_support & PCIE_LINK_STATE_L1) link->aspm_default |= PCIE_LINK_STATE_L1; + /* + * L1 PM Substates need CLKREQ# between the two ports. Enable + * them by default only on links whose devicetree node says the + * signal is routed. + */ + if (pcie_link_has_aspm_override(link, "supports-clkreq")) + link->aspm_default |= link->aspm_support & PCIE_LINK_STATE_L1SS; override = link->aspm_default & ~link->aspm_enabled; if (override) - pci_info(pdev, "ASPM: default states%s%s\n", + pci_info(pdev, "ASPM: default states%s%s%s%s%s%s\n", FLAG(override, L0S, " L0s"), - FLAG(override, L1, " L1")); + FLAG(override, L1, " L1"), + FLAG(override, L1_1, " ASPM-L1.1"), + FLAG(override, L1_2, " ASPM-L1.2"), + FLAG(override, L1_1_PCIPM, " PCI-PM-L1.1"), + FLAG(override, L1_2_PCIPM, " PCI-PM-L1.2")); } } +/* + * Clock PM, like the L1 PM Substates, needs CLKREQ#. On devicetree platforms, + * enable it by default on links whose node says the signal is routed. + */ +static void pcie_clkpm_override_default_link_state(struct pcie_link_state *link) +{ + if (!of_have_populated_dt() || !link->clkpm_capable || + link->clkpm_disable || link->clkpm_default) + return; + if (!pcie_link_has_aspm_override(link, "supports-clkreq")) + return; + + link->clkpm_default = 1; + pci_dbg(link->downstream, "ASPM: default Clock PM (supports-clkreq)\n"); +} + static void pcie_aspm_cap_init(struct pcie_link_state *link, int blacklist) { struct pci_dev *child = link->downstream, *parent = link->pdev; @@ -1256,6 +1283,7 @@ void pcie_aspm_init_link_state(struct pci_dev *pdev) /* Setup initial Clock PM state */ pcie_clkpm_cap_init(link, blacklist); + pcie_clkpm_override_default_link_state(link); /* * At this stage drivers haven't had an opportunity to change the diff --git a/drivers/pci/probe.c b/drivers/pci/probe.c index d625dd5e778a83..c38a60df06d81d 100644 --- a/drivers/pci/probe.c +++ b/drivers/pci/probe.c @@ -1402,6 +1402,8 @@ static int pci_scan_bridge_extend(struct pci_bus *bus, struct pci_dev *dev, u8 primary, secondary, subordinate; int broken = 0; bool fixed_buses; + bool reassign = pcibios_assign_all_busses() && + !pci_find_host_bridge(bus)->no_reassign_bus; u8 fixed_sec, fixed_sub; int next_busnr; @@ -1449,7 +1451,7 @@ static int pci_scan_bridge_extend(struct pci_bus *bus, struct pci_dev *dev, } if ((secondary || subordinate) && - !pcibios_assign_all_busses() && !broken) { + !reassign && !broken) { unsigned int cmax, buses; /* @@ -1491,7 +1493,7 @@ static int pci_scan_bridge_extend(struct pci_bus *bus, struct pci_dev *dev, * do in the second pass. */ if (!pass) { - if (pcibios_assign_all_busses() || broken) + if (reassign || broken) /* * Temporarily disable forwarding of the diff --git a/drivers/perf/Kconfig b/drivers/perf/Kconfig index 245e7bb763b994..1263c9f5ac8dbb 100644 --- a/drivers/perf/Kconfig +++ b/drivers/perf/Kconfig @@ -264,6 +264,18 @@ config APPLE_M1_CPU_PMU Provides support for the non-architectural CPU PMUs present on the Apple M1 SoCs and derivatives. +config APPLE_M1_CPU_PMU_KUNIT_TEST + bool "KUnit tests for the Apple M1 CPU PMU driver" if !KUNIT_ALL_TESTS + depends on APPLE_M1_CPU_PMU && KUNIT=y + default KUNIT_ALL_TESTS + help + Build tests for the Apple CPU PMU driver's event logic: generic, + cache and raw event mapping per core type, counter allocation + under each event's counter affinity, the user/kernel/host/guest + filter bits, the PMUv3 event map used by KVM and the sysfs event + strings. No counter is programmed and no PMU is registered, so + the tests need no Apple hardware. + config ALIBABA_UNCORE_DRW_PMU tristate "Alibaba T-Head Yitian 710 DDR Sub-system Driveway PMU driver" depends on (ARM64 && ACPI) || COMPILE_TEST diff --git a/drivers/perf/apple_m1_cpu_pmu-test.c b/drivers/perf/apple_m1_cpu_pmu-test.c new file mode 100644 index 00000000000000..c7017ae5a79cdc --- /dev/null +++ b/drivers/perf/apple_m1_cpu_pmu-test.c @@ -0,0 +1,930 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the Apple M1 CPU PMU driver's event logic. + * + * Included at the end of apple_m1_cpu_pmu.c. The tests build an arm_pmu + * with each match-table init function and then only call the callbacks + * that never touch a register: map_event, set_event_filter, + * get_event_idx, clear_event_idx and map_pmuv3_event, plus the sysfs show + * helpers. Nothing is registered with perf and no Apple system register + * is accessed, so the tests run on any arm64 machine. + */ + +#include +#include + +/* A dynamic perf type: anything past the generic PERF_TYPE_* range. */ +#define M1PMU_TEST_PMU_TYPE (PERF_TYPE_MAX + 7) + +#define M1PMU_CACHE(type, op, result) \ + ((u64)PERF_COUNT_HW_CACHE_##type | \ + ((u64)PERF_COUNT_HW_CACHE_OP_##op << 8) | \ + ((u64)PERF_COUNT_HW_CACHE_RESULT_##result << 16)) + +static armpmu_init_fn m1pmu_test_init_fn(struct kunit *test, const char *compat) +{ + const struct of_device_id *id; + + for (id = m1_pmu_of_device_ids; id->compatible[0]; id++) + if (!strcmp(id->compatible, compat)) + return id->data; + + KUNIT_FAIL(test, "%s not in the match table", compat); + return NULL; +} + +static struct arm_pmu *m1pmu_test_pmu(struct kunit *test, const char *compat) +{ + struct arm_pmu *pmu; + armpmu_init_fn init; + + init = m1pmu_test_init_fn(test, compat); + KUNIT_ASSERT_NOT_NULL(test, init); + + pmu = kunit_kzalloc(test, sizeof(*pmu), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, pmu); + pmu->pmu.type = M1PMU_TEST_PMU_TYPE; + + KUNIT_ASSERT_EQ(test, init(pmu), 0); + return pmu; +} + +static struct pmu_hw_events *m1pmu_test_cpuc(struct kunit *test) +{ + struct pmu_hw_events *cpuc; + + cpuc = kunit_kzalloc(test, sizeof(*cpuc), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, cpuc); + return cpuc; +} + +static struct perf_event *m1pmu_test_event(struct kunit *test, + struct arm_pmu *pmu, + u32 type, u64 config) +{ + struct perf_event *event; + + event = kunit_kzalloc(test, sizeof(*event), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, event); + event->pmu = &pmu->pmu; + event->attr.type = type; + event->attr.config = config; + event->attr.exclude_guest = 1; + event->hw.idx = -1; + return event; +} + +static int m1pmu_test_map(struct kunit *test, struct arm_pmu *pmu, + u32 type, u64 config) +{ + return pmu->map_event(m1pmu_test_event(test, pmu, type, config)); +} + +static int m1pmu_test_hw(struct kunit *test, struct arm_pmu *pmu, u64 config) +{ + return m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, config); +} + +static int m1pmu_test_cache(struct kunit *test, struct arm_pmu *pmu, + u64 config) +{ + return m1pmu_test_map(test, pmu, PERF_TYPE_HW_CACHE, config); +} + +/* + * The steps of the arm_pmu core's event init and add that reach the + * driver: map the event, apply the mode filter, then pick a counter. + * Returns the counter index or a negative errno. + */ +static int m1pmu_test_add(struct kunit *test, struct arm_pmu *pmu, + struct pmu_hw_events *cpuc, u32 type, u64 config, + struct perf_event **out) +{ + struct perf_event *event = m1pmu_test_event(test, pmu, type, config); + int mapping, ret; + + mapping = pmu->map_event(event); + if (mapping < 0) + return mapping; + + event->hw.config_base = 0; + ret = pmu->set_event_filter(&event->hw, &event->attr); + if (ret) + return ret; + event->hw.config_base |= mapping; + + ret = pmu->get_event_idx(cpuc, event); + if (ret >= 0) + event->hw.idx = ret; + if (out) + *out = event; + return ret; +} + +static int m1pmu_test_raw(struct kunit *test, struct arm_pmu *pmu, + struct pmu_hw_events *cpuc, u64 config) +{ + return m1pmu_test_add(test, pmu, cpuc, PERF_TYPE_RAW, config, NULL); +} + +/* Match table: every compatible, its name, counters and callbacks. */ +struct m1pmu_test_variant { + const char *compat; + const char *name; + u64 cntr_mask; + int (*map_event)(struct perf_event *event); + int (*get_event_idx)(struct pmu_hw_events *cpuc, + struct perf_event *event); + int (*map_pmuv3_event)(unsigned int eventsel); + void (*enable)(struct perf_event *event); + const struct attribute_group *events; + const struct attribute_group *formats; + u32 evt_flag; +}; + +static const struct m1pmu_test_variant m1pmu_test_variants[] = { + { "apple,icestorm-pmu", "apple_icestorm_pmu", GENMASK(9, 0), + m1_pmu_map_event, m1_pmu_get_event_idx, m1_pmu_map_pmuv3_event, + m1_pmu_enable_event, &m1_pmu_events_attr_group, + &m1_pmu_format_attr_group, ARMPMU_EVT_47BIT }, + { "apple,firestorm-pmu", "apple_firestorm_pmu", GENMASK(9, 0), + m1_pmu_map_event, m1_pmu_get_event_idx, m1_pmu_map_pmuv3_event, + m1_pmu_enable_event, &m1_pmu_events_attr_group, + &m1_pmu_format_attr_group, ARMPMU_EVT_47BIT }, + { "apple,avalanche-pmu", "apple_avalanche_pmu", GENMASK(9, 0), + m2_pmu_map_event, m1_pmu_get_event_idx, m1_pmu_map_pmuv3_event, + m1_pmu_enable_event, &m1_pmu_events_attr_group, + &m1_pmu_format_attr_group, ARMPMU_EVT_63BIT }, + { "apple,blizzard-pmu", "apple_blizzard_pmu", GENMASK(9, 0), + m2_pmu_map_event, m1_pmu_get_event_idx, m1_pmu_map_pmuv3_event, + m1_pmu_enable_event, &m1_pmu_events_attr_group, + &m1_pmu_format_attr_group, ARMPMU_EVT_63BIT }, + { "apple,t8140-pmu", "apple_t8140_pmu", GENMASK(7, 0), + m4_pmu_map_event, m4_pmu_get_event_idx, m4_pmu_map_pmuv3_event, + m4_pmu_enable_event, &m4_pmu_events_attr_group, + &m4_pmu_format_attr_group, ARMPMU_EVT_63BIT }, + { "apple,t6040-pmu", "apple_t6040_pmu", GENMASK(7, 0), + m4_pmu_map_event, m4_pmu_get_event_idx, m4_pmu_map_pmuv3_event, + m4_pmu_enable_event, &m4_pmu_events_attr_group, + &m4_pmu_format_attr_group, ARMPMU_EVT_63BIT }, + { "apple,t6050-pmu", "apple_t6050_pmu", GENMASK(9, 0), + t6050_pmu_map_event, t6050_pmu_get_event_idx, + t6050_pmu_map_pmuv3_event, m4_pmu_enable_event, + &t6050_pmu_events_attr_group, &m4_pmu_format_attr_group, + ARMPMU_EVT_63BIT }, + { "apple,t8142-pmu", "apple_t8142_pmu", GENMASK(9, 0), + t6050_pmu_map_event, t6050_pmu_get_event_idx, + t6050_pmu_map_pmuv3_event, m4_pmu_enable_event, + &t6050_pmu_events_attr_group, &m4_pmu_format_attr_group, + ARMPMU_EVT_63BIT }, +}; + +static void m1pmu_test_variant_desc(const struct m1pmu_test_variant *v, + char *desc) +{ + strscpy(desc, v->compat, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(m1pmu_test_variant, m1pmu_test_variants, + m1pmu_test_variant_desc); + +static void m1pmu_test_match_table_complete(struct kunit *test) +{ + const struct of_device_id *id; + size_t n = 0, i; + + for (id = m1_pmu_of_device_ids; id->compatible[0]; id++) { + bool found = false; + + KUNIT_EXPECT_NOT_NULL(test, id->data); + for (i = 0; i < ARRAY_SIZE(m1pmu_test_variants); i++) + found |= !strcmp(id->compatible, + m1pmu_test_variants[i].compat); + KUNIT_EXPECT_TRUE_MSG(test, found, "%s has no test variant", + id->compatible); + n++; + } + KUNIT_EXPECT_EQ(test, n, ARRAY_SIZE(m1pmu_test_variants)); +} + +/* Each init function wires its own callbacks, counters and sysfs groups. */ +static void m1pmu_test_variant_init(struct kunit *test) +{ + const struct m1pmu_test_variant *v = test->param_value; + struct arm_pmu *pmu = m1pmu_test_pmu(test, v->compat); + DECLARE_BITMAP(want, ARMPMU_MAX_HWEVENTS); + struct perf_event *event; + + KUNIT_EXPECT_STREQ(test, pmu->name, v->name); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->map_event, (void *)v->map_event); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->get_event_idx, + (void *)v->get_event_idx); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->map_pmuv3_event, + (void *)v->map_pmuv3_event); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->enable, (void *)v->enable); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->clear_event_idx, + (void *)m1_pmu_clear_event_idx); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->set_event_filter, + (void *)m1_pmu_set_event_filter); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->disable, + (void *)m1_pmu_disable_event); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->reset, (void *)m1_pmu_reset); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->handle_irq, + (void *)m1_pmu_handle_irq); + KUNIT_EXPECT_PTR_EQ(test, pmu->attr_groups[ARMPMU_ATTR_GROUP_EVENTS], + v->events); + KUNIT_EXPECT_PTR_EQ(test, pmu->attr_groups[ARMPMU_ATTR_GROUP_FORMATS], + v->formats); + + bitmap_zero(want, ARMPMU_MAX_HWEVENTS); + bitmap_from_u64(want, v->cntr_mask); + KUNIT_EXPECT_TRUE(test, bitmap_equal(pmu->cntr_mask, want, + ARMPMU_MAX_HWEVENTS)); + KUNIT_EXPECT_EQ(test, bitmap_weight(pmu->cntr_mask, + ARMPMU_MAX_HWEVENTS), + hweight64(v->cntr_mask)); + + /* map_event advertises the overflow bit width. */ + event = m1pmu_test_event(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_CPU_CYCLES); + KUNIT_EXPECT_GE(test, pmu->map_event(event), 0); + KUNIT_EXPECT_EQ(test, event->hw.flags & (ARMPMU_EVT_47BIT | + ARMPMU_EVT_63BIT | + ARMPMU_EVT_64BIT), + v->evt_flag); +} + +/* Cycles and instructions always land on fixed counters 0 and 1. */ +static void m1pmu_test_variant_fixed_counters(struct kunit *test) +{ + const struct m1pmu_test_variant *v = test->param_value; + struct arm_pmu *pmu = m1pmu_test_pmu(test, v->compat); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + + KUNIT_EXPECT_EQ(test, m1pmu_test_add(test, pmu, cpuc, + PERF_TYPE_HARDWARE, + PERF_COUNT_HW_CPU_CYCLES, NULL), 0); + KUNIT_EXPECT_EQ(test, m1pmu_test_add(test, pmu, cpuc, + PERF_TYPE_HARDWARE, + PERF_COUNT_HW_INSTRUCTIONS, NULL), + 1); +} + +/* Filling the PMU with events of the default affinity uses each counter once. */ +static void m1pmu_test_variant_fill(struct kunit *test) +{ + const struct m1pmu_test_variant *v = test->param_value; + struct arm_pmu *pmu = m1pmu_test_pmu(test, v->compat); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + DECLARE_BITMAP(used, ARMPMU_MAX_HWEVENTS); + unsigned int i, n; + int idx; + + /* Event 0xf0 has no special affinity on any variant. */ + bitmap_zero(used, ARMPMU_MAX_HWEVENTS); + for (n = 0; n < ARMPMU_MAX_HWEVENTS; n++) { + idx = m1pmu_test_raw(test, pmu, cpuc, 0xf0); + if (idx < 0) + break; + KUNIT_EXPECT_GE(test, idx, 2); + KUNIT_EXPECT_TRUE(test, test_bit(idx, pmu->cntr_mask)); + KUNIT_EXPECT_FALSE(test, test_bit(idx, used)); + __set_bit(idx, used); + } + KUNIT_EXPECT_EQ(test, idx, -EAGAIN); + + /* Every counter the PMU exposes, minus the two fixed ones. */ + KUNIT_EXPECT_EQ(test, n, hweight64(v->cntr_mask & ~GENMASK_ULL(1, 0))); + for (i = 0; i < n; i++) + KUNIT_EXPECT_TRUE(test, test_bit(i + 2, used)); +} + +/* Generic hardware events, per variant event numbering. */ +static void m1pmu_test_hw_map_m1(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,firestorm-pmu"); + struct arm_pmu *m2 = m1pmu_test_pmu(test, "apple,blizzard-pmu"); + struct arm_pmu *p[] = { pmu, m2 }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(p); i++) { + KUNIT_EXPECT_EQ(test, m1pmu_test_hw(test, p[i], + PERF_COUNT_HW_CPU_CYCLES), + 0x02); + KUNIT_EXPECT_EQ(test, m1pmu_test_hw(test, p[i], + PERF_COUNT_HW_INSTRUCTIONS), + 0x8c); + KUNIT_EXPECT_EQ(test, + m1pmu_test_hw(test, p[i], + PERF_COUNT_HW_BRANCH_INSTRUCTIONS), + 0x8d); + KUNIT_EXPECT_EQ(test, m1pmu_test_hw(test, p[i], + PERF_COUNT_HW_BRANCH_MISSES), + 0xcb); + } +} + +static void m1pmu_test_hw_map_m4(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,t6040-pmu"); + + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_CPU_CYCLES), 0x02); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_INSTRUCTIONS), 0x08); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_BRANCH_INSTRUCTIONS), + 0x21); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_BRANCH_MISSES), 0x22); +} + +static void m1pmu_test_hw_map_t6050(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,t6050-pmu"); + + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_CPU_CYCLES), 0x011); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_INSTRUCTIONS), 0x008); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_BRANCH_INSTRUCTIONS), + 0x021); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_BRANCH_MISSES), 0x022); +} + +/* Generic events with no mapping, and out-of-range configs. */ +static void m1pmu_test_hw_map_unsupported(struct kunit *test) +{ + static const u64 unmapped[] = { + PERF_COUNT_HW_CACHE_REFERENCES, + PERF_COUNT_HW_CACHE_MISSES, + PERF_COUNT_HW_BUS_CYCLES, + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND, + PERF_COUNT_HW_STALLED_CYCLES_BACKEND, + PERF_COUNT_HW_REF_CPU_CYCLES, + }; + unsigned int i, j; + + for (i = 0; i < ARRAY_SIZE(m1pmu_test_variants); i++) { + struct arm_pmu *pmu = + m1pmu_test_pmu(test, m1pmu_test_variants[i].compat); + + for (j = 0; j < ARRAY_SIZE(unmapped); j++) + KUNIT_EXPECT_EQ(test, + m1pmu_test_hw(test, pmu, unmapped[j]), + -ENOENT); + KUNIT_EXPECT_EQ(test, m1pmu_test_hw(test, pmu, PERF_COUNT_HW_MAX), + -EINVAL); + /* A type that is neither generic nor this PMU's. */ + KUNIT_EXPECT_EQ(test, + m1pmu_test_map(test, pmu, PERF_TYPE_TRACEPOINT, 0), + -ENOENT); + } +} + +/* + * Generic cache events. Only the L1D read miss may ever be mapped (it is + * the one event with a known counter on every core), so leave it out. + */ +static void m1pmu_test_cache_map(struct kunit *test) +{ + static const u64 unmapped[] = { + M1PMU_CACHE(L1D, READ, ACCESS), + M1PMU_CACHE(L1D, WRITE, MISS), + M1PMU_CACHE(L1I, READ, MISS), + M1PMU_CACHE(LL, READ, MISS), + M1PMU_CACHE(DTLB, READ, MISS), + M1PMU_CACHE(ITLB, READ, MISS), + M1PMU_CACHE(BPU, READ, ACCESS), + M1PMU_CACHE(NODE, PREFETCH, MISS), + }; + unsigned int i, j; + + for (i = 0; i < ARRAY_SIZE(m1pmu_test_variants); i++) { + struct arm_pmu *pmu = + m1pmu_test_pmu(test, m1pmu_test_variants[i].compat); + + for (j = 0; j < ARRAY_SIZE(unmapped); j++) + KUNIT_EXPECT_EQ(test, + m1pmu_test_cache(test, pmu, unmapped[j]), + -ENOENT); + KUNIT_EXPECT_EQ(test, + m1pmu_test_cache(test, pmu, + PERF_COUNT_HW_CACHE_MAX), + -EINVAL); + KUNIT_EXPECT_EQ(test, + m1pmu_test_cache(test, pmu, + (u64)PERF_COUNT_HW_CACHE_OP_MAX << 8), + -EINVAL); + KUNIT_EXPECT_EQ(test, + m1pmu_test_cache(test, pmu, + (u64)PERF_COUNT_HW_CACHE_RESULT_MAX << 16), + -EINVAL); + } +} + +/* Raw events: 8-bit selectors on M1/M2, 16-bit from M4 on. */ +static void m1pmu_test_raw_mask(struct kunit *test) +{ + struct arm_pmu *m1 = m1pmu_test_pmu(test, "apple,icestorm-pmu"); + struct arm_pmu *m2 = m1pmu_test_pmu(test, "apple,avalanche-pmu"); + struct arm_pmu *m4 = m1pmu_test_pmu(test, "apple,t8140-pmu"); + struct arm_pmu *m5 = m1pmu_test_pmu(test, "apple,t8142-pmu"); + + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m1, PERF_TYPE_RAW, 0x1a3), + 0xa3); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m2, PERF_TYPE_RAW, + 0xffff00cb), 0xcb); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m1, M1PMU_TEST_PMU_TYPE, + 0x38c), 0x8c); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m4, PERF_TYPE_RAW, + 0x30008), 0x0008); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m4, M1PMU_TEST_PMU_TYPE, + 0xabcd), 0xabcd); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m5, PERF_TYPE_RAW, + 0x105a3), 0x5a3); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m5, M1PMU_TEST_PMU_TYPE, + 0x895), 0x895); +} + +/* exclude_* bits become the count-user/kernel/host/guest config bits. */ +static void m1pmu_test_event_filter(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,firestorm-pmu"); + struct perf_event_attr attr = { }; + struct hw_perf_event hw = { }; + + attr.exclude_guest = 1; + KUNIT_ASSERT_EQ(test, pmu->set_event_filter(&hw, &attr), 0); + KUNIT_EXPECT_EQ(test, hw.config_base, + (unsigned long)(M1_PMU_CFG_COUNT_KERNEL | + M1_PMU_CFG_COUNT_USER | + M1_PMU_CFG_COUNT_HOST)); + + attr.exclude_kernel = 1; + KUNIT_ASSERT_EQ(test, pmu->set_event_filter(&hw, &attr), 0); + KUNIT_EXPECT_EQ(test, hw.config_base, + (unsigned long)(M1_PMU_CFG_COUNT_USER | + M1_PMU_CFG_COUNT_HOST)); + + attr.exclude_kernel = 0; + attr.exclude_user = 1; + KUNIT_ASSERT_EQ(test, pmu->set_event_filter(&hw, &attr), 0); + KUNIT_EXPECT_EQ(test, hw.config_base, + (unsigned long)(M1_PMU_CFG_COUNT_KERNEL | + M1_PMU_CFG_COUNT_HOST)); + + attr.exclude_host = 1; + attr.exclude_kernel = 1; + KUNIT_ASSERT_EQ(test, pmu->set_event_filter(&hw, &attr), 0); + KUNIT_EXPECT_EQ(test, hw.config_base, 0UL); + + /* Counting the guest needs VHE; without it, refuse. */ + memset(&attr, 0, sizeof(attr)); + hw.config_base = 0x5a; + if (is_kernel_in_hyp_mode()) { + KUNIT_ASSERT_EQ(test, pmu->set_event_filter(&hw, &attr), 0); + KUNIT_EXPECT_EQ(test, hw.config_base, + (unsigned long)(M1_PMU_CFG_COUNT_KERNEL | + M1_PMU_CFG_COUNT_USER | + M1_PMU_CFG_COUNT_HOST | + M1_PMU_CFG_COUNT_GUEST)); + } else { + KUNIT_EXPECT_EQ(test, pmu->set_event_filter(&hw, &attr), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, hw.config_base, 0x5aUL); + } +} + +/* The filter bits must not change which counter an event gets. */ +static void m1pmu_test_idx_ignores_filter_bits(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,icestorm-pmu"); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + struct perf_event *event; + + event = m1pmu_test_event(test, pmu, PERF_TYPE_RAW, 0); + event->hw.config_base = M1_PMU_CFG_COUNT_USER | + M1_PMU_CFG_COUNT_KERNEL | + M1_PMU_CFG_COUNT_HOST | + M1_PMU_CFG_COUNT_GUEST | + M1_PMU_PERFCTR_RETIRE_UOP; + KUNIT_EXPECT_EQ(test, pmu->get_event_idx(cpuc, event), 7); + + pmu = m1pmu_test_pmu(test, "apple,t6050-pmu"); + cpuc = m1pmu_test_cpuc(test); + event->pmu = &pmu->pmu; + event->hw.config_base = M1_PMU_CFG_COUNT_USER | + M1_PMU_CFG_COUNT_HOST | 0x897; + KUNIT_EXPECT_EQ(test, pmu->get_event_idx(cpuc, event), 7); +} + +/* M1/M2 per-event affinities from m1_pmu_event_affinity. */ +static void m1pmu_test_m1_affinity(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,firestorm-pmu"); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + + /* RETIRE_UOP only counts on counter 7. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x01), 7); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x01), -EAGAIN); + + /* INST_ALL: counter 1, then 7, which is now taken. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x8c), 1); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x8c), -EAGAIN); + + /* Branch events are confined to 5-7; only 5 and 6 are left. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x8d), 5); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xcb), 6); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xc5), -EAGAIN); + + /* 0xf5-0xf7 and 0xfd count on 2, 4, 6. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xf5), 2); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xfd), 4); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xf6), -EAGAIN); + + /* 0xf8 counts on 2-7: only 3 is free there. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xf8), 3); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xf8), -EAGAIN); + + /* Anything else goes on 8 and 9, never on 0. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xa3), 8); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x00), 9); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xa3), -EAGAIN); + + /* Cycles still has its fixed counter, then nowhere to go. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x02), 0); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x02), -EAGAIN); + KUNIT_EXPECT_EQ(test, bitmap_weight(cpuc->used_mask, + ARMPMU_MAX_HWEVENTS), 10); +} + +/* Only cycles and instructions may use counters 0 and 1 on M1. */ +static void m1pmu_test_m1_fixed_reserved(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,blizzard-pmu"); + unsigned int evt; + + for (evt = 0; evt <= M1_PMU_PERFCTR_LAST; evt++) { + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + int first = m1pmu_test_raw(test, pmu, cpuc, evt); + + KUNIT_EXPECT_GE(test, first, 0); + if (evt == M1_PMU_PERFCTR_CORE_ACTIVE_CYCLE) + KUNIT_EXPECT_EQ(test, first, 0); + else if (evt == M1_PMU_PERFCTR_INST_ALL) + KUNIT_EXPECT_EQ(test, first, 1); + else + KUNIT_EXPECT_GE_MSG(test, first, 2, "event 0x%x", evt); + kunit_kfree(test, cpuc); + } +} + +/* A freed counter is handed out again; others stay taken. */ +static void m1pmu_test_clear_idx(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,icestorm-pmu"); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + struct perf_event *a, *b, *c; + + KUNIT_ASSERT_EQ(test, m1pmu_test_add(test, pmu, cpuc, PERF_TYPE_RAW, + 0xa3, &a), 2); + KUNIT_ASSERT_EQ(test, m1pmu_test_add(test, pmu, cpuc, PERF_TYPE_RAW, + 0xa3, &b), 3); + KUNIT_ASSERT_EQ(test, m1pmu_test_add(test, pmu, cpuc, PERF_TYPE_RAW, + 0x01, &c), 7); + + pmu->clear_event_idx(cpuc, a); + KUNIT_EXPECT_FALSE(test, test_bit(2, cpuc->used_mask)); + KUNIT_EXPECT_TRUE(test, test_bit(3, cpuc->used_mask)); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xa3), 2); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x01), -EAGAIN); + + pmu->clear_event_idx(cpuc, c); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x01), 7); + + pmu->clear_event_idx(cpuc, b); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x8d), 5); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xf0), 3); +} + +/* M4: cycles only on 0, instructions on 1 or 2-7, the rest on 2-7. */ +static void m1pmu_test_m4_affinity(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,t8140-pmu"); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + unsigned int i; + + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x02), 0); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x02), -EAGAIN); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x08), 1); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x08), 2); + + /* 16-bit selectors: 0x1008 is not INST_ALL. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x1008), 3); + /* The M1 RETIRE_UOP pin to counter 7 does not apply here. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x01), 4); + + for (i = 5; i <= 7; i++) + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x03), i); + /* Counters 8 and 9 are never handed out. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x03), -EAGAIN); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x08), -EAGAIN); + KUNIT_EXPECT_FALSE(test, test_bit(8, cpuc->used_mask)); + KUNIT_EXPECT_FALSE(test, test_bit(9, cpuc->used_mask)); +} + +/* T6050: cycles on 0 or 2-9, the instruction classes on 2-7 or only 7. */ +static void m1pmu_test_t6050_affinity(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,t6050-pmu"); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + unsigned int i, ev; + + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x011), 0); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x011), 2); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x008), 1); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x008), 3); + + /* The counter-7-only list. */ + for (i = 0; i < ARRAY_SIZE(t6050_pmu_pmc7_events); i++) { + ev = t6050_pmu_pmc7_events[i]; + KUNIT_EXPECT_EQ(test, t6050_pmu_event_affinity(ev), BIT(7)); + } + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x8a4), 7); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x897), -EAGAIN); + + /* The 2-7 list: 4, 5, 6 left, then full even with 8 and 9 free. */ + for (i = 0; i < ARRAY_SIZE(t6050_pmu_pmc2_7_events); i++) { + ev = t6050_pmu_pmc2_7_events[i]; + KUNIT_EXPECT_EQ(test, t6050_pmu_event_affinity(ev), + GENMASK(7, 2) | + (ev == T6050_PMU_PERFCTR_INST_ALL ? BIT(1) : 0)); + } + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x895), 4); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x022), 5); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x8ca), 6); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x88e), -EAGAIN); + + /* Unlisted events, such as the L1D load miss, may use 8 and 9. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x5a3), 8); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x011), 9); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x5a3), -EAGAIN); + KUNIT_EXPECT_EQ(test, bitmap_weight(cpuc->used_mask, + ARMPMU_MAX_HWEVENTS), 10); +} + +/* The 2-7 and 7-only lists must not overlap, or the order would matter. */ +static bool m1pmu_test_in_pmc2_7(unsigned int event) +{ + return t6050_pmu_event_in(t6050_pmu_pmc2_7_events, + ARRAY_SIZE(t6050_pmu_pmc2_7_events), event); +} + +static void m1pmu_test_t6050_lists_disjoint(struct kunit *test) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(t6050_pmu_pmc7_events); i++) + KUNIT_EXPECT_FALSE(test, + m1pmu_test_in_pmc2_7(t6050_pmu_pmc7_events[i])); + KUNIT_EXPECT_FALSE(test, m1pmu_test_in_pmc2_7(0x011)); + KUNIT_EXPECT_EQ(test, t6050_pmu_event_affinity(0x5a3), GENMASK(9, 2)); + KUNIT_EXPECT_EQ(test, t6050_pmu_event_affinity(0x8c8), GENMASK(7, 2)); + KUNIT_EXPECT_EQ(test, t6050_pmu_event_affinity(0x8c9), GENMASK(9, 2)); +} + +/* Every hardware event a variant maps can be placed on an empty PMU. */ +static void m1pmu_test_hw_events_placeable(struct kunit *test) +{ + unsigned int i, cfg; + + for (i = 0; i < ARRAY_SIZE(m1pmu_test_variants); i++) { + struct arm_pmu *pmu = + m1pmu_test_pmu(test, m1pmu_test_variants[i].compat); + + for (cfg = 0; cfg < PERF_COUNT_HW_MAX; cfg++) { + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + int idx; + + if (m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + cfg) < 0) + continue; + idx = m1pmu_test_add(test, pmu, cpuc, + PERF_TYPE_HARDWARE, cfg, NULL); + KUNIT_EXPECT_GE_MSG(test, idx, 0, "%s hw %u", + m1pmu_test_variants[i].compat, cfg); + if (idx >= 0) + KUNIT_EXPECT_TRUE(test, + test_bit(idx, pmu->cntr_mask)); + kunit_kfree(test, cpuc); + } + } +} + +/* PMUv3 events KVM exposes to guests, and the PMCEID bitmap built from them. */ +static void m1pmu_test_pmuv3_map(struct kunit *test) +{ + struct arm_pmu *m1 = m1pmu_test_pmu(test, "apple,firestorm-pmu"); + struct arm_pmu *m4 = m1pmu_test_pmu(test, "apple,t6040-pmu"); + struct arm_pmu *m5 = m1pmu_test_pmu(test, "apple,t6050-pmu"); + + KUNIT_EXPECT_EQ(test, m1->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_CPU_CYCLES), + 0x02); + KUNIT_EXPECT_EQ(test, m1->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_INST_RETIRED), + 0x8c); + KUNIT_EXPECT_EQ(test, m1->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_BR_RETIRED), + 0x8d); + KUNIT_EXPECT_EQ(test, + m1->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_BR_MIS_PRED_RETIRED), + 0xcb); + KUNIT_EXPECT_EQ(test, m1->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_L1D_CACHE), + -EOPNOTSUPP); + + KUNIT_EXPECT_EQ(test, m4->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_CPU_CYCLES), + 0x02); + KUNIT_EXPECT_EQ(test, m4->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_INST_RETIRED), + 0x08); + KUNIT_EXPECT_EQ(test, m4->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_BR_RETIRED), + 0x21); + + KUNIT_EXPECT_EQ(test, m5->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_CPU_CYCLES), + 0x011); + KUNIT_EXPECT_EQ(test, m5->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_INST_RETIRED), + 0x008); + KUNIT_EXPECT_EQ(test, + m5->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_BR_MIS_PRED_RETIRED), + 0x022); + + /* Past the common event space. */ + KUNIT_EXPECT_EQ(test, m1->map_pmuv3_event(ARMV8_PMUV3_MAX_COMMON_EVENTS), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, m5->map_pmuv3_event(0xffff), -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, m4->map_pmuv3_event(UINT_MAX), -EOPNOTSUPP); + + /* PMCEID advertises exactly the mapped events. */ + KUNIT_EXPECT_EQ(test, bitmap_weight(m1->pmceid_bitmap, + ARMV8_PMUV3_MAX_COMMON_EVENTS), 4); + KUNIT_EXPECT_TRUE(test, test_bit(ARMV8_PMUV3_PERFCTR_CPU_CYCLES, + m1->pmceid_bitmap)); + KUNIT_EXPECT_TRUE(test, test_bit(ARMV8_PMUV3_PERFCTR_BR_MIS_PRED_RETIRED, + m1->pmceid_bitmap)); + KUNIT_EXPECT_EQ(test, bitmap_weight(m4->pmceid_bitmap, + ARMV8_PMUV3_MAX_COMMON_EVENTS), 3); + KUNIT_EXPECT_FALSE(test, test_bit(ARMV8_PMUV3_PERFCTR_BR_MIS_PRED_RETIRED, + m4->pmceid_bitmap)); + KUNIT_EXPECT_EQ(test, bitmap_weight(m5->pmceid_bitmap, + ARMV8_PMUV3_MAX_COMMON_EVENTS), 4); + KUNIT_EXPECT_TRUE(test, bitmap_empty(m1->pmceid_ext_bitmap, + ARMV8_PMUV3_MAX_COMMON_EVENTS)); +} + +/* Each PMUv3 event KVM maps can be placed on the PMU that maps it. */ +static void m1pmu_test_pmuv3_placeable(struct kunit *test) +{ + unsigned int i, ev; + + for (i = 0; i < ARRAY_SIZE(m1pmu_test_variants); i++) { + struct arm_pmu *pmu = + m1pmu_test_pmu(test, m1pmu_test_variants[i].compat); + + for_each_set_bit(ev, pmu->pmceid_bitmap, + ARMV8_PMUV3_MAX_COMMON_EVENTS) { + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + int raw = pmu->map_pmuv3_event(ev); + + KUNIT_ASSERT_GE(test, raw, 0); + KUNIT_EXPECT_GE_MSG(test, + m1pmu_test_raw(test, pmu, cpuc, raw), + 0, "%s pmuv3 0x%x", + m1pmu_test_variants[i].compat, ev); + kunit_kfree(test, cpuc); + } + } +} + +static const char *m1pmu_test_show(struct kunit *test, + const struct attribute_group *grp, + const char *name) +{ + struct attribute **a; + char *page; + + page = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + if (!page) + return ""; + + for (a = grp->attrs; *a; a++) { + struct device_attribute *da; + + if (strcmp((*a)->name, name)) + continue; + da = container_of(*a, struct device_attribute, attr); + if (da->show(NULL, da, page) <= 0) + return ""; + return page; + } + return ""; +} + +static void m1pmu_test_expect_show(struct kunit *test, + const struct attribute_group *grp, + const char *name, const char *want) +{ + KUNIT_EXPECT_STREQ_MSG(test, m1pmu_test_show(test, grp, name), want, + "%s/%s", grp->name, name); +} + +/* sysfs events and format strings that perf tools parse. */ +static void m1pmu_test_sysfs(struct kunit *test) +{ + m1pmu_test_expect_show(test, &m1_pmu_events_attr_group, "cycles", + "event=0x0002\n"); + m1pmu_test_expect_show(test, &m1_pmu_events_attr_group, + "instructions", "event=0x008c\n"); + m1pmu_test_expect_show(test, &m1_pmu_events_attr_group, "branches", + ""); + m1pmu_test_expect_show(test, &m4_pmu_events_attr_group, + "l1d-load-misses", "event=0x0003\n"); + m1pmu_test_expect_show(test, &m4_pmu_events_attr_group, + "branch-misses", "event=0x0022\n"); + m1pmu_test_expect_show(test, &t6050_pmu_events_attr_group, + "l1d-load-misses", "event=0x05a3\n"); + m1pmu_test_expect_show(test, &t6050_pmu_events_attr_group, "loads", + "event=0x0895\n"); + m1pmu_test_expect_show(test, &t6050_pmu_events_attr_group, "cycles", + "event=0x0011\n"); + + m1pmu_test_expect_show(test, &m1_pmu_format_attr_group, "event", + "config:0-7\n"); + m1pmu_test_expect_show(test, &m4_pmu_format_attr_group, "event", + "config:0-15\n"); +} + +/* Every named sysfs event maps back to itself as a raw event. */ +static void m1pmu_test_sysfs_events_round_trip(struct kunit *test) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(m1pmu_test_variants); i++) { + const struct m1pmu_test_variant *v = &m1pmu_test_variants[i]; + struct arm_pmu *pmu = m1pmu_test_pmu(test, v->compat); + struct attribute **a; + + for (a = v->events->attrs; *a; a++) { + struct perf_pmu_events_attr *pa; + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + + pa = container_of(*a, struct perf_pmu_events_attr, + attr.attr); + KUNIT_EXPECT_EQ(test, + m1pmu_test_map(test, pmu, + M1PMU_TEST_PMU_TYPE, + pa->id), + (int)pa->id); + KUNIT_EXPECT_GE_MSG(test, + m1pmu_test_raw(test, pmu, cpuc, pa->id), + 0, "%s %s", v->compat, (*a)->name); + kunit_kfree(test, cpuc); + } + } +} + +static struct kunit_case m1pmu_test_cases[] = { + KUNIT_CASE(m1pmu_test_match_table_complete), + KUNIT_CASE_PARAM(m1pmu_test_variant_init, + m1pmu_test_variant_gen_params), + KUNIT_CASE_PARAM(m1pmu_test_variant_fixed_counters, + m1pmu_test_variant_gen_params), + KUNIT_CASE_PARAM(m1pmu_test_variant_fill, + m1pmu_test_variant_gen_params), + KUNIT_CASE(m1pmu_test_hw_map_m1), + KUNIT_CASE(m1pmu_test_hw_map_m4), + KUNIT_CASE(m1pmu_test_hw_map_t6050), + KUNIT_CASE(m1pmu_test_hw_map_unsupported), + KUNIT_CASE(m1pmu_test_cache_map), + KUNIT_CASE(m1pmu_test_raw_mask), + KUNIT_CASE(m1pmu_test_event_filter), + KUNIT_CASE(m1pmu_test_idx_ignores_filter_bits), + KUNIT_CASE(m1pmu_test_m1_affinity), + KUNIT_CASE(m1pmu_test_m1_fixed_reserved), + KUNIT_CASE(m1pmu_test_clear_idx), + KUNIT_CASE(m1pmu_test_m4_affinity), + KUNIT_CASE(m1pmu_test_t6050_affinity), + KUNIT_CASE(m1pmu_test_t6050_lists_disjoint), + KUNIT_CASE(m1pmu_test_hw_events_placeable), + KUNIT_CASE(m1pmu_test_pmuv3_map), + KUNIT_CASE(m1pmu_test_pmuv3_placeable), + KUNIT_CASE(m1pmu_test_sysfs), + KUNIT_CASE(m1pmu_test_sysfs_events_round_trip), + {} +}; + +static struct kunit_suite m1pmu_test_suite = { + .name = "apple-m1-cpu-pmu", + .test_cases = m1pmu_test_cases, +}; + +kunit_test_suite(m1pmu_test_suite); diff --git a/drivers/perf/apple_m1_cpu_pmu.c b/drivers/perf/apple_m1_cpu_pmu.c index d1aadc27164fb9..f66462f13f9a3f 100644 --- a/drivers/perf/apple_m1_cpu_pmu.c +++ b/drivers/perf/apple_m1_cpu_pmu.c @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -273,6 +274,24 @@ static const unsigned int t6050_pmu_perf_map[PERF_COUNT_HW_MAX] = { [PERF_COUNT_HW_BRANCH_MISSES] = T6050_PMU_PERFCTR_BRANCH_MISPRED_NONSPEC, }; +/* + * The generic L1D read-miss event, for in-kernel users such as the + * scheduler: the same counter as each core's l1d-load-misses event. + */ +static const unsigned int t6050_pmu_cache_map[PERF_COUNT_HW_CACHE_MAX] + [PERF_COUNT_HW_CACHE_OP_MAX] + [PERF_COUNT_HW_CACHE_RESULT_MAX] = { + PERF_CACHE_MAP_ALL_UNSUPPORTED, + [C(L1D)][C(OP_READ)][C(RESULT_MISS)] = T6050_PMU_PERFCTR_L1D_CACHE_MISS_LD, +}; + +static const unsigned int m4_pmu_cache_map[PERF_COUNT_HW_CACHE_MAX] + [PERF_COUNT_HW_CACHE_OP_MAX] + [PERF_COUNT_HW_CACHE_RESULT_MAX] = { + PERF_CACHE_MAP_ALL_UNSUPPORTED, + [C(L1D)][C(OP_READ)][C(RESULT_MISS)] = M4_PMU_PERFCTR_L1D_CACHE_MISS_LD, +}; + static const unsigned int m4_pmu_perf_map[PERF_COUNT_HW_MAX] = { PERF_MAP_ALL_UNSUPPORTED, [PERF_COUNT_HW_CPU_CYCLES] = M4_PMU_PERFCTR_CORE_ACTIVE_CYCLE, @@ -281,6 +300,19 @@ static const unsigned int m4_pmu_perf_map[PERF_COUNT_HW_MAX] = { [PERF_COUNT_HW_BRANCH_MISSES] = M4_PMU_PERFCTR_BRANCH_MISPRED, }; +/* + * As above, for M1 and M2: their L1D load-miss event, 0xa3 in the M1 event + * list above (M1_PMU_PERFCTR_L1D_CACHE_MISS_LD), which came with this + * driver from the Asahi Linux project's public event documentation. M2 + * uses the same table. + */ +static const unsigned int m1_pmu_cache_map[PERF_COUNT_HW_CACHE_MAX] + [PERF_COUNT_HW_CACHE_OP_MAX] + [PERF_COUNT_HW_CACHE_RESULT_MAX] = { + PERF_CACHE_MAP_ALL_UNSUPPORTED, + [C(L1D)][C(OP_READ)][C(RESULT_MISS)] = M1_PMU_PERFCTR_L1D_CACHE_MISS_LD, +}; + static const unsigned m1_pmu_perf_map[PERF_COUNT_HW_MAX] = { PERF_MAP_ALL_UNSUPPORTED, [PERF_COUNT_HW_CPU_CYCLES] = M1_PMU_PERFCTR_CORE_ACTIVE_CYCLE, @@ -770,14 +802,26 @@ static void __m1_pmu_set_mode(u8 mode) isb(); } +#ifdef CONFIG_ARCH_APPLE +static void apple_pmu_wfi_freeze_set(bool active) +{ + this_cpu_write(apple_pmu_wfi_freeze, active); +} +#else +static void apple_pmu_wfi_freeze_set(bool active) { } +#endif + static void m1_pmu_start(struct arm_pmu *cpu_pmu) { + /* arm_pmu only starts the PMU with at least one event on it. */ + apple_pmu_wfi_freeze_set(true); __m1_pmu_set_mode(PMCR0_IMODE_FIQ); } static void m1_pmu_stop(struct arm_pmu *cpu_pmu) { __m1_pmu_set_mode(PMCR0_IMODE_OFF); + apple_pmu_wfi_freeze_set(false); } static int m1_pmu_map_event(struct perf_event *event) @@ -788,7 +832,7 @@ static int m1_pmu_map_event(struct perf_event *event) * being 47bit wide to mimick the behaviour of the ARM PMU. */ event->hw.flags |= ARMPMU_EVT_47BIT; - return armpmu_map_event(event, &m1_pmu_perf_map, NULL, M1_PMU_CFG_EVENT); + return armpmu_map_event(event, &m1_pmu_perf_map, &m1_pmu_cache_map, M1_PMU_CFG_EVENT); } static int m2_pmu_map_event(struct perf_event *event) @@ -799,20 +843,22 @@ static int m2_pmu_map_event(struct perf_event *event) * Yes, this is getting awkward. */ event->hw.flags |= ARMPMU_EVT_63BIT; - return armpmu_map_event(event, &m1_pmu_perf_map, NULL, M1_PMU_CFG_EVENT); + return armpmu_map_event(event, &m1_pmu_perf_map, &m1_pmu_cache_map, M1_PMU_CFG_EVENT); } static int m4_pmu_map_event(struct perf_event *event) { /* 64bit counters, overflow flag on bit 63, as on M2. */ event->hw.flags |= ARMPMU_EVT_63BIT; - return armpmu_map_event(event, &m4_pmu_perf_map, NULL, M4_PMU_CFG_EVENT); + return armpmu_map_event(event, &m4_pmu_perf_map, &m4_pmu_cache_map, + M4_PMU_CFG_EVENT); } static int t6050_pmu_map_event(struct perf_event *event) { event->hw.flags |= ARMPMU_EVT_63BIT; - return armpmu_map_event(event, &t6050_pmu_perf_map, NULL, M4_PMU_CFG_EVENT); + return armpmu_map_event(event, &t6050_pmu_perf_map, &t6050_pmu_cache_map, + M4_PMU_CFG_EVENT); } static int __m1_pmu_map_pmuv3_event(const u16 *map, unsigned int eventsel) @@ -856,6 +902,7 @@ static void m1_pmu_reset(void *info) int i; __m1_pmu_set_mode(PMCR0_IMODE_OFF); + apple_pmu_wfi_freeze_set(false); for (i = 0; i < M1_PMU_NR_COUNTERS; i++) { m1_pmu_disable_counter(i); @@ -1040,3 +1087,7 @@ static struct platform_driver m1_pmu_driver = { }; module_platform_driver(m1_pmu_driver); + +#if IS_ENABLED(CONFIG_APPLE_M1_CPU_PMU_KUNIT_TEST) +#include "apple_m1_cpu_pmu-test.c" +#endif diff --git a/drivers/perf/apple_m1_cpu_pmu.kunitconfig b/drivers/perf/apple_m1_cpu_pmu.kunitconfig new file mode 100644 index 00000000000000..efa2818f6209b9 --- /dev/null +++ b/drivers/perf/apple_m1_cpu_pmu.kunitconfig @@ -0,0 +1,8 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/perf/apple_m1_cpu_pmu.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_PERF_EVENTS=y +CONFIG_ARM_PMU=y +CONFIG_APPLE_M1_CPU_PMU=y +CONFIG_APPLE_M1_CPU_PMU_KUNIT_TEST=y diff --git a/drivers/phy/apple/atc-j700-dp.h b/drivers/phy/apple/atc-j700-dp.h index a07f1125c2c43f..55cd6fdeb4b7e3 100644 --- a/drivers/phy/apple/atc-j700-dp.h +++ b/drivers/phy/apple/atc-j700-dp.h @@ -483,7 +483,7 @@ static int j700_dp_configure(struct apple_atcphy *p, const struct phy_configure_ if (p->mode != APPLE_ATCPHY_MODE_DP && p->mode != APPLE_ATCPHY_MODE_USB3_DP) return -EINVAL; mode = atcphy_get_mode_config(p, p->mode); - pmas = !!mode->dp_lane[0] | (!!mode->dp_lane[1] << 1); + pmas = mode->dp_lane[0] | (mode->dp_lane[1] << 1); capacity = 2 * hweight32(pmas); if (o->lanes > capacity || (o->set_lanes && o->lanes != 1 && o->lanes != 2 && o->lanes != 4)) diff --git a/drivers/phy/apple/atc-t6050-combo.h b/drivers/phy/apple/atc-t6050-combo.h index 584680e398ed87..83f97bc8356688 100644 --- a/drivers/phy/apple/atc-t6050-combo.h +++ b/drivers/phy/apple/atc-t6050-combo.h @@ -122,13 +122,13 @@ static void combo_pipe_fault(struct t6050_dp *dp, const char *what, int ret) /* * What the combo PHY gained for a deep sleep outside its sleep callbacks (a wrapper domain * still held at a stop is released, a safe state with a domain still held is stopped again, - * the always-on domain's hold over the sleep) is in force on the boards with a T6050 sleep, - * the J714s and the J716c. On another T6050 board the stop, the safe state and the probe are + * the always-on domain's hold over the sleep) is in force on the boards whose device tree + * describes a T6050 sleep. On another T6050 board the stop, the safe state and the probe are * as before. */ static bool combo_sleep_board(void) { - return of_machine_is_compatible("apple,j714s") || of_machine_is_compatible("apple,j716c"); + return apple_t6050_sleep_described(); } static bool combo_domains_held(struct t6050_dp *dp) @@ -241,6 +241,8 @@ static int combo_orientation(struct t6050_dp *dp, enum typec_orientation orienta int ret; guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (dp->faulted) return -EIO; if (orientation != TYPEC_ORIENTATION_NONE && orientation != TYPEC_ORIENTATION_NORMAL && @@ -308,6 +310,8 @@ static int combo_mux(struct t6050_dp *dp, struct typec_mux_state *state) return -EOPNOTSUPP; } guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (dp->faulted) return -EIO; /* SAFE with a domain still held: a sleep kept it, and nothing came back on the port. */ @@ -403,6 +407,61 @@ static void combo_resume(struct t6050_dp *dp) dev_info(dp->dev, "mode %d back: the sleep did not happen\n", dp->sleep_mode); } +/* + * Suspend-to-idle leaves an active combo PHY running: t6050_dp_suspend_late() + * only quiesces for firmware sleep. Hold the active virtual genpd devices out + * of genpd_suspend_noirq() so phymxwrap (and common/usb/dp gates) are not + * powered off under the running PHY CPU. Close PHY mode and clock changes + * under the same mutex as the late snapshot, including work that can still + * run after the freezer. Reopen after noirq on resume or suspend unwind. + */ +static void combo_s2idle_hold(struct t6050_dp *dp) +{ + guard(mutex)(&dp->lock); + dp->s2idle_frozen = true; + if (dp->faulted || dp->combo_mode == COMBO_SAFE) + return; + for (unsigned int i = 0; i < dp->ndomains; i++) { + if (dp->domain[i].active && + !(i == 0 && dp->aon_syscore) && + !(dp->s2idle_domain_syscore & BIT(i))) { + dev_pm_syscore_device(dp->domain[i].dev, true); + dp->s2idle_domain_syscore |= BIT(i); + } + } + if (dp->dp_gates) { + for (unsigned int i = 0; i < ATC_DP_TUNNELS; i++) { + if (dp->dp_gate[i].active && + !(dp->s2idle_gate_syscore & BIT(i))) { + dev_pm_syscore_device(dp->dp_gate[i].dev, true); + dp->s2idle_gate_syscore |= BIT(i); + } + } + } +} + +static void combo_s2idle_release(struct t6050_dp *dp) +{ + guard(mutex)(&dp->lock); + if (dp->s2idle_domain_syscore) { + for (unsigned int i = 0; i < dp->ndomains; i++) { + if (dp->s2idle_domain_syscore & BIT(i)) + dev_pm_syscore_device(dp->domain[i].dev, false); + } + dp->s2idle_domain_syscore = 0; + } + if (dp->s2idle_gate_syscore) { + for (unsigned int i = 0; i < ATC_DP_TUNNELS; i++) { + if (dp->s2idle_gate_syscore & BIT(i)) + dev_pm_syscore_device(dp->dp_gate[i].dev, false); + } + dp->s2idle_gate_syscore = 0; + } + dp->s2idle_frozen = false; + if (dp->s2idle_clock_stops) + queue_work(system_freezable_wq, &dp->s2idle_clock_work); +} + /* * A port in use keeps its always-on domain through a deep sleep: held out of the system * transition from before its prepare to after its complete, so the power domain is not @@ -741,7 +800,11 @@ static int combo_setup(struct platform_device *pdev, struct t6050_dp *dp) return PTR_ERR(dp->combo_phy[i]); phy_set_drvdata(dp->combo_phy[i], dp); } - /* A deep sleep's hold of the always-on domain: see combo_sleep_board(). */ + /* + * Deep-sleep hold of the always-on domain (board gate left for the + * deep-sleep pass); s2idle hold runs for all T6050 combo PHYs in + * t6050_dp_suspend_late() / t6050_dp_resume_early(). + */ if (!combo_sleep_board()) return 0; dp->pm_nb.notifier_call = combo_pm_notify; diff --git a/drivers/phy/apple/atc-t6050-dp.c b/drivers/phy/apple/atc-t6050-dp.c index 352fca52c54fb4..35dd18fa970367 100644 --- a/drivers/phy/apple/atc-t6050-dp.c +++ b/drivers/phy/apple/atc-t6050-dp.c @@ -28,6 +28,7 @@ #include #include #include +#include enum atc_operation { ATC_MASK, ATC_TUNABLE, ATC_DELAY, ATC_POLL, ATC_POWER, ATC_FIRMWARE }; struct atc_op { @@ -135,6 +136,11 @@ struct t6050_dp { enum combo_mode sleep_mode; /* the mode the sleep's stop took down */ bool sleep_stopped; /* stopped for a sleep that has not been accounted for yet */ bool aon_syscore; /* the always-on domain is held out of this system transition */ + struct work_struct s2idle_clock_work; + u8 s2idle_clock_stops; + bool s2idle_frozen; /* serialize mode and gate changes with system sleep */ + u8 s2idle_domain_syscore; /* active domains held out of s2idle genpd suspend */ + u8 s2idle_gate_syscore; /* active DP tunnel gates held out of s2idle genpd suspend */ bool aon_kept; /* the stop left the always-on domain's reference in place */ /* A USB4 router's sleep in place: its host stops and restarts the port, see the end. */ bool cio_sleep; /* asked for: the PHY's own stop for the sleep is skipped */ @@ -618,6 +624,8 @@ static void atc_dp_tunnels_stop(struct t6050_dp *dp) bool running = memchr_inv(dp->tunnel_rate, 0, sizeof(dp->tunnel_rate)); memset(dp->tunnel_rate, 0, sizeof(dp->tunnel_rate)); + /* Every clock is stopped here: no stop deferred across s2idle is left. */ + dp->s2idle_clock_stops = 0; if (running) { atc_dp_tunnels_apply(dp, 0, NULL); return; @@ -634,6 +642,8 @@ static int t6050_dp_set_mode(struct phy *phy, enum phy_mode mode, int submode) struct t6050_dp *dp = phy_get_drvdata(phy); guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (mode == PHY_MODE_DP) return dp->typec ? (dp->enabled ? 0 : -ENOLINK) : atc_start(dp); if (mode == PHY_MODE_INVALID) @@ -681,6 +691,8 @@ static int t6050_dp_configure(struct phy *phy, union phy_configure_opts *opts) if (cfg->set_voltages && cfg->set_rate && rate < 0 && cfg->lanes) return -EINVAL; guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (dp->faulted) return -EIO; if (!dp->enabled) @@ -741,26 +753,14 @@ EXPORT_SYMBOL_GPL(apple_dp_phy_link_config); * never given another rate in place. Every change applies all four clocks in * order (atc_dp_tunnels_apply()). */ -int apple_t6050_dp_tunnel_clock(struct phy *phy, unsigned int clock, u8 rate) +static int atc_dp_tunnel_clock_locked(struct t6050_dp *dp, unsigned int clock, + u8 rate, int src) { - struct t6050_dp *dp; unsigned int i = clock - 1; - int src = 0, ret; u32 v = 0; + int ret; - if (!phy || phy->ops != &t6050_dp_ops) - return -EOPNOTSUPP; - if (clock < 1 || clock > ATC_DP_TUNNELS) - return -EINVAL; - if (rate) { - src = atc_dp_source(rate); - if (src < 0) - return src; - } - dp = phy_get_drvdata(phy); - guard(mutex)(&dp->lock); - if (!dp->combo || !dp->dp_clk_src) - return -EOPNOTSUPP; + lockdep_assert_held(&dp->lock); if (dp->tunnel_rate[i] == rate) { /* A failed start or gate suspend can leave a held domain at rate zero. */ if (!rate && dp->dp_gates) @@ -804,6 +804,91 @@ int apple_t6050_dp_tunnel_clock(struct phy *phy, unsigned int clock, u8 rate) clock, rate, src, v); return 0; } + +static int atc_s2idle_clock_stop(struct t6050_dp *dp, unsigned int i) +{ + int ret; + + lockdep_assert_held(&dp->lock); + dp->tunnel_rate[i] = 0; + /* + * The switches are written only in USB4 mode. If the PHY left it (or + * faulted) since the stop was deferred, the clock no longer runs: only + * its gate can still be held. + */ + if (dp->faulted || dp->combo_mode != COMBO_CIO) { + ret = dp->dp_gates ? atc_domain_set(&dp->dp_gate[i], false) : 0; + } else { + ret = atc_dp_tunnels_apply(dp, i + 1, NULL); + } + if (!ret) + dp->s2idle_clock_stops &= ~BIT(i); + return ret; +} + +static void atc_s2idle_clock_work(struct work_struct *work) +{ + struct t6050_dp *dp = container_of(work, struct t6050_dp, s2idle_clock_work); + unsigned int i; + int ret; + + guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return; + for (i = 0; i < ATC_DP_TUNNELS; i++) { + if (!(dp->s2idle_clock_stops & BIT(i))) + continue; + ret = atc_s2idle_clock_stop(dp, i); + if (ret) + dev_warn(dp->dev, "Deferred DP tunnel clock %u stop failed: %d\n", + i + 1, ret); + } +} + +static void atc_s2idle_clock_cancel(void *data) +{ + struct t6050_dp *dp = data; + + cancel_work_sync(&dp->s2idle_clock_work); +} + +int apple_t6050_dp_tunnel_clock(struct phy *phy, unsigned int clock, u8 rate) +{ + struct t6050_dp *dp; + unsigned int stop; + int src = 0, ret; + + if (!phy || phy->ops != &t6050_dp_ops) + return -EOPNOTSUPP; + if (clock < 1 || clock > ATC_DP_TUNNELS) + return -EINVAL; + if (rate) { + src = atc_dp_source(rate); + if (src < 0) + return src; + } + dp = phy_get_drvdata(phy); + guard(mutex)(&dp->lock); + if (!dp->combo || !dp->dp_clk_src) + return -EOPNOTSUPP; + + stop = BIT(clock - 1); + if (dp->s2idle_frozen) { + if (rate) { + dev_dbg(dp->dev, "DP tunnel clock %u start refused across s2idle\n", clock); + return -EBUSY; + } + /* DCP may discard the route once it asks us to stop this clock. */ + dp->s2idle_clock_stops |= stop; + return 0; + } + if (dp->s2idle_clock_stops & stop) { + ret = atc_s2idle_clock_stop(dp, clock - 1); + if (ret || !rate) + return ret; + } + return atc_dp_tunnel_clock_locked(dp, clock, rate, src); +} EXPORT_SYMBOL_GPL(apple_t6050_dp_tunnel_clock); /* The connector sets orientation before changing the alternate-mode mux. */ @@ -1068,6 +1153,9 @@ static int t6050_dp_probe(struct platform_device *pdev) } if (ndomains != 3 && !(dp->combo && ndomains == 4)) return -EINVAL; + BUILD_BUG_ON(ATC_DP_TUNNELS > BITS_PER_TYPE(dp->s2idle_gate_syscore)); + if (ndomains > BITS_PER_TYPE(dp->s2idle_domain_syscore)) + return -EINVAL; dp->ndomains = ndomains; for (unsigned int i = 0; i < dp->ndomains; i++) { dp->domain[i].dev = dev_pm_domain_attach_by_name(dev, domains[i]); @@ -1122,6 +1210,10 @@ static int t6050_dp_probe(struct platform_device *pdev) return PTR_ERR(phy); phy_set_drvdata(phy, dp); dp->combo_phy[2] = phy; + INIT_WORK(&dp->s2idle_clock_work, atc_s2idle_clock_work); + ret = devm_add_action_or_reset(dev, atc_s2idle_clock_cancel, dp); + if (ret) + return ret; provider = devm_of_phy_provider_register(dev, dp->combo ? combo_xlate : of_phy_simple_xlate); if (IS_ERR(provider)) return PTR_ERR(provider); @@ -1141,7 +1233,13 @@ static int t6050_dp_suspend_late(struct device *dev) { struct t6050_dp *dp = dev_get_drvdata(dev); - if (!dp->combo || !pm_suspend_via_firmware()) + if (!dp->combo) + return 0; + if (pm_suspend_no_platform()) { + combo_s2idle_hold(dp); + return 0; + } + if (!pm_suspend_via_firmware()) return 0; /* A router sleeping in place still uses the link: its host stops the PHY after it. */ scoped_guard(mutex, &dp->lock) { @@ -1154,6 +1252,15 @@ static int t6050_dp_suspend_late(struct device *dev) return combo_suspend_late(dp); } +static int t6050_dp_resume_early(struct device *dev) +{ + struct t6050_dp *dp = dev_get_drvdata(dev); + + if (dp->combo) + combo_s2idle_release(dp); + return 0; +} + static int t6050_dp_resume_noirq(struct device *dev) { struct t6050_dp *dp = dev_get_drvdata(dev); @@ -1195,6 +1302,8 @@ int apple_t6050_phy_cio_prepare(struct device *dev) if (!dp || !dp->combo) return -EOPNOTSUPP; guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (dp->cio_sleep || dp->faulted || dp->combo_mode != COMBO_CIO || !dp->cio_prepared) return -EBUSY; dp->cio_sleep = true; @@ -1212,6 +1321,8 @@ int apple_t6050_phy_cio_off(struct device *dev) if (!dp) return -EOPNOTSUPP; guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (!dp->cio_sleep || dp->cio_sleep_off || dp->faulted || dp->combo_mode != COMBO_CIO) return -EBUSY; atc_dp_tunnels_stop(dp); @@ -1247,6 +1358,8 @@ int apple_t6050_phy_cio_on(struct device *dev) if (!dp) return -EOPNOTSUPP; guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (!dp->cio_sleep) return -EINVAL; if (!dp->cio_sleep_off) @@ -1261,6 +1374,14 @@ int apple_t6050_phy_cio_on(struct device *dev) } EXPORT_SYMBOL_GPL(apple_t6050_phy_cio_on); +/* + * Not fenced by s2idle_frozen, unlike the CIO calls above: this and + * apple_t6050_phy_cio_lost() write no PHY register and change no mode, + * clock or domain. They only update the sleep-in-place bookkeeping, under + * dp->lock. Their only caller, the Thunderbolt host's CIO sleep in + * drivers/thunderbolt/apple-cio-sleep.c, runs them only for a + * suspend-to-RAM it prepared (PM_SUSPEND_MEM), never across s2idle. + */ int apple_t6050_phy_cio_finish(struct device *dev) { struct t6050_dp *dp = t6050_dp_from_dev(dev); @@ -1321,6 +1442,8 @@ int apple_t6050_phy_cio_usb(struct device *dev, enum apple_t6050_cio_usb step) if (!dp || !dp->combo) return -EOPNOTSUPP; guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; /* TEST (sv6t11): the PIPE handler, the controller's bank, read while it holds its domain. */ if (step == APPLE_T6050_CIO_USB_PARK && dp->cio_usb_kept && !dp->cio_usb_parked) { mux = readl(dp->banks[44] + 0xc); @@ -1382,6 +1505,7 @@ EXPORT_SYMBOL_GPL(apple_t6050_phy_cio_usb); static const struct dev_pm_ops t6050_dp_pm_ops = { .suspend_late = pm_sleep_ptr(t6050_dp_suspend_late), .resume_noirq = pm_sleep_ptr(t6050_dp_resume_noirq), + .resume_early = pm_sleep_ptr(t6050_dp_resume_early), .resume = pm_sleep_ptr(t6050_dp_resume), }; diff --git a/drivers/phy/apple/atc-test.c b/drivers/phy/apple/atc-test.c index 09eec7f9d6185f..1e1e1a9b853680 100644 --- a/drivers/phy/apple/atc-test.c +++ b/drivers/phy/apple/atc-test.c @@ -104,6 +104,83 @@ static void atcphy_test_target_mode_t8132(struct kunit *test) KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_OFF); } +/* + * SuperSpeed device mode is not supported by this driver on T8132: a device + * role keeps the lanes on USB2 while preserving the partner's requested mode. + */ +static void atcphy_test_t8132_device_role_usb2(struct kunit *test) +{ + struct typec_altmode dp = { .svid = USB_TYPEC_DP_SID }; + struct typec_mux_state state = { .mode = TYPEC_STATE_USB }; + struct apple_atcphy *atcphy = atcphy_test_alloc_dev(test, false); + + atcphy->hw = &atcphy_hw_t8132; + atcphy->t8132_ss = true; + atcphy->ss_tunables = true; + atcphy->t8132_dp_alt = true; + KUNIT_EXPECT_EQ(test, atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_USB3), + APPLE_ATCPHY_MODE_USB2); + KUNIT_EXPECT_EQ(test, atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_USB3_DP), + APPLE_ATCPHY_MODE_USB2); + KUNIT_EXPECT_EQ(test, atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_DP), + APPLE_ATCPHY_MODE_DP); + KUNIT_EXPECT_EQ(test, atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_USB2), + APPLE_ATCPHY_MODE_USB2); + KUNIT_EXPECT_EQ(test, atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_OFF), + APPLE_ATCPHY_MODE_OFF); + + /* Target mode preserves the partner's request so a host swap can restore SuperSpeed. */ + atcphy->t8132_device = true; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_USB3); + atcphy->mode = APPLE_ATCPHY_MODE_USB2; + KUNIT_EXPECT_TRUE(test, atcphy_mux_in_mode(atcphy, APPLE_ATCPHY_MODE_USB3)); + KUNIT_EXPECT_TRUE(test, atcphy_mux_in_mode(atcphy, APPLE_ATCPHY_MODE_USB3_DP)); + KUNIT_EXPECT_FALSE(test, atcphy_mux_in_mode(atcphy, APPLE_ATCPHY_MODE_OFF)); + atcphy->t8132_device = false; + KUNIT_EXPECT_FALSE(test, atcphy_mux_in_mode(atcphy, APPLE_ATCPHY_MODE_USB3)); + + state.alt = &dp; + state.mode = TYPEC_DP_STATE_C; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_DP); + state.alt = NULL; + state.mode = TYPEC_STATE_SAFE; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_OFF); +} + +/* Without the CIO calibration, a T8132 port serves a USB4 or TBT partner's USB2 */ +static void atcphy_test_target_mode_t8132_cio(struct kunit *test) +{ + struct typec_altmode tbt = { .svid = USB_TYPEC_TBT_SID }; + struct enter_usb_data eusb = { + .eudo = FIELD_PREP(EUDO_USB_MODE_MASK, EUDO_USB_MODE_USB4), + }; + struct typec_mux_state state = { .mode = TYPEC_MODE_USB4, .data = &eusb }; + struct apple_atcphy *atcphy = atcphy_test_alloc_dev(test, false); + + atcphy->hw = &atcphy_hw_t8132; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_USB2); + state.alt = &tbt; + state.mode = TYPEC_TBT_MODE; + state.data = NULL; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_USB2); + /* The same on a SuperSpeed port. */ + atcphy->t8132_ss = true; + atcphy->ss_tunables = true; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_USB2); + state.alt = NULL; + state.mode = TYPEC_MODE_USB4; + state.data = &eusb; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_USB2); + + /* With the calibration, the link itself is served. */ + atcphy->cio_tunables = true; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_USB4); + state.alt = &tbt; + state.mode = TYPEC_TBT_MODE; + state.data = NULL; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_TBT); +} + static void atcphy_test_noop_same_mode(struct kunit *test) { struct apple_atcphy *atcphy = atcphy_test_alloc(test, true); @@ -1391,6 +1468,8 @@ static struct kunit_case atcphy_mux_test_cases[] = { KUNIT_CASE(atcphy_test_target_mode), KUNIT_CASE(atcphy_test_target_mode_fixed_hub), KUNIT_CASE(atcphy_test_target_mode_t8132), + KUNIT_CASE(atcphy_test_t8132_device_role_usb2), + KUNIT_CASE(atcphy_test_target_mode_t8132_cio), KUNIT_CASE(atcphy_test_noop_same_mode), KUNIT_CASE(atcphy_test_noop_needs_work), KUNIT_CASE(atcphy_test_usb3_port_ready), @@ -1450,3 +1529,270 @@ static struct kunit_suite atcphy_t8132_pm_test_suite = { }; kunit_test_suite(atcphy_t8132_pm_test_suite); + +#define ATCPHY_TEST_T8152_LANE0_UP \ + (ACIOPHY_T8152_AON_LANE_SLEEP_SMALL | ACIOPHY_T8152_AON_LANE_SLEEP_BIG | \ + ACIOPHY_T8152_AON_LANE_AHB_RESET_N) + +/* + * A T8152 fixed-USB3 PHY over zeroed memory in place of its ATC window, up to + * the sync reset. Its USB controller's DARTs sit at the T8103 offsets of the + * power and reset block: mark those words to see that nothing writes them. + */ +static struct apple_atcphy *atcphy_test_alloc_t8152(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_dev(test, false); + void *core = kunit_kzalloc(test, ATCPHY_T8152_SYNC_RESET + 4, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, core); + atcphy->regs.core = (__force void __iomem *)core; + atcphy->hw = &atcphy_hw_t8152; + atcphy->fixed_usb3 = true; + writel(0xdeadbeef, atcphy->regs.core + ATCPHY_POWER_CTRL); + writel(0xdeadbeef, atcphy->regs.core + ATCPHY_MISC); + + return atcphy; +} + +static void atcphy_test_t8152_untouched(struct kunit *test, struct apple_atcphy *atcphy) +{ + KUNIT_EXPECT_EQ(test, readl(atcphy->regs.core + ATCPHY_POWER_CTRL), 0xdeadbeefU); + KUNIT_EXPECT_EQ(test, readl(atcphy->regs.core + ATCPHY_MISC), 0xdeadbeefU); +} + +/* USB3: lane 0 powered up, crossbar 0x110, no lane mode register, lane swap bit 1 */ +static void atcphy_test_t8152_lanes(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + + writel(ACIOPHY_T8152_AON_LANE_CLAMP_EN, core + ACIOPHY_T8152_AON_LANE0); + writel(ATCPHY_T8152_MISC_LANE_SWAP, core + ATCPHY_T8152_CFG_OFFSET + ATCPHY_MISC); + + atcphy_lanes_up_t8152(atcphy, APPLE_ATCPHY_MODE_USB3); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE0), ATCPHY_TEST_T8152_LANE0_UP); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_SLEEP_CTRL2), + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL(0) | + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG(0)); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), 0x110U); + + KUNIT_EXPECT_EQ(test, atcphy_configure_lanes(atcphy, APPLE_ATCPHY_MODE_USB3), 0); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), 0x110U); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_LANE_MODE_T8103), 0U); + KUNIT_EXPECT_EQ(test, readl(core + ATCPHY_T8152_CFG_OFFSET + ATCPHY_MISC), 0U); + atcphy_test_t8152_untouched(test, atcphy); +} + +/* Power-up and power-down go to the block at 0x60000 and the sync reset at 0x60030 */ +static void atcphy_test_t8152_power(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + u32 ctrl = ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_CTRL; + u32 stat = ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_STAT; + + writel(ATCPHY_POWER_CLAMP_EN, core + ctrl); + writel(ATCPHY_POWER_SLEEP_SMALL | ATCPHY_POWER_SLEEP_BIG, core + stat); + KUNIT_EXPECT_EQ(test, atcphy_power_on(atcphy), 0); + KUNIT_EXPECT_EQ(test, readl(core + ctrl), ATCPHY_POWER_SLEEP_SMALL | + ATCPHY_POWER_SLEEP_BIG | ATCPHY_POWER_APB_RESET_N); + KUNIT_EXPECT_EQ(test, readl(core + ATCPHY_T8152_SYNC_RESET), ATCPHY_MISC_RESET_N); + atcphy_test_t8152_untouched(test, atcphy); + + writel(ATCPHY_TEST_T8152_LANE0_UP, core + ACIOPHY_T8152_AON_LANE0); + writel(0, core + stat); + KUNIT_EXPECT_EQ(test, atcphy_power_off(atcphy), 0); + KUNIT_EXPECT_EQ(test, readl(core + ctrl), ATCPHY_POWER_CLAMP_EN); + KUNIT_EXPECT_EQ(test, readl(core + ATCPHY_T8152_SYNC_RESET), 0U); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE0), + ACIOPHY_T8152_AON_LANE_CLAMP_EN); + atcphy_test_t8152_untouched(test, atcphy); +} + +/* + * The T8152 PIPE handler does not acknowledge the lock: the request is made + * and the PIPE changes under it without waiting. Its release then finds the + * acknowledge clear at once. + */ +static void atcphy_test_t8152_pipe_lock(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void *pipehandler = kunit_kzalloc(test, PIPEHANDLER_NONSELECTED_OVERRIDE + 4, + GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, pipehandler); + atcphy->regs.pipehandler = (__force void __iomem *)pipehandler; + KUNIT_EXPECT_EQ(test, atcphy_pipehandler_lock(atcphy), 0); + KUNIT_EXPECT_EQ(test, readl(atcphy->regs.pipehandler + PIPEHANDLER_LOCK_REQ), + PIPEHANDLER_LOCK_EN); + KUNIT_EXPECT_EQ(test, atcphy_pipehandler_unlock(atcphy), 0); + KUNIT_EXPECT_EQ(test, readl(atcphy->regs.pipehandler + PIPEHANDLER_LOCK_REQ), 0U); +} + +/* + * Without its tunables (a loader that copies none) a T8152 PHY runs USB2 + * alone: every other mode is refused before a register is written. + */ +static void atcphy_test_t8152_no_tunables(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + static const enum atcphy_mode refused[] = { + APPLE_ATCPHY_MODE_USB3, APPLE_ATCPHY_MODE_USB3_DP, APPLE_ATCPHY_MODE_USB4, + APPLE_ATCPHY_MODE_TBT, APPLE_ATCPHY_MODE_DP, + }; + + atcphy->ss_tunables = false; + writel(ACIOPHY_T8152_AON_LANE_CLAMP_EN, core + ACIOPHY_T8152_AON_LANE0); + mutex_init(&atcphy->lock); + guard(mutex)(&atcphy->lock); + for (size_t i = 0; i < ARRAY_SIZE(refused); i++) + KUNIT_EXPECT_EQ(test, atcphy_configure(atcphy, refused[i]), -EOPNOTSUPP); + /* USB4 from the Type-C mux: refused before the power domains come up */ + KUNIT_EXPECT_EQ(test, atcphy_cio_start(atcphy, APPLE_ATCPHY_MODE_USB4), -EOPNOTSUPP); + KUNIT_EXPECT_FALSE(test, atcphy->cio_powered); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE0), + ACIOPHY_T8152_AON_LANE_CLAMP_EN); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), 0U); + atcphy_test_t8152_untouched(test, atcphy); +} + +/* Both LFPS receivers of a lane on */ +static u32 atcphy_test_t8152_lfps(unsigned int lane) +{ + return ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL(lane) | + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG(lane); +} + +/* + * CIO on a rear port: both lanes powered up one after the other, the USB4 + * crossbar by the orientation, the lane swap for a reversed plug too, and on + * the way down both lanes clamped, their LFPS receivers off and AUX clamped. + */ +static void atcphy_test_t8152_cio_lanes(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + u32 ctrl = ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_CTRL; + u32 misc = ATCPHY_T8152_CFG_OFFSET + ATCPHY_MISC; + + atcphy->fixed_usb3 = false; + atcphy->cio_only = true; + for (int reversed = 0; reversed < 2; reversed++) { + atcphy->swap_lanes = reversed; + writel(ACIOPHY_T8152_AON_LANE_CLAMP_EN, core + ACIOPHY_T8152_AON_LANE(0)); + writel(ACIOPHY_T8152_AON_LANE_CLAMP_EN, core + ACIOPHY_T8152_AON_LANE(1)); + writel(ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_CLAMP_EN, + core + ACIOPHY_T8152_AON_SLEEP_CTRL2); + writel(reversed ? 0 : ATCPHY_T8152_MISC_LANE_SWAP, core + misc); + writel(ACIOPHY_CROSSBAR_DP_SINGLE_PMA_UNK100 << 5 | ACIOPHY_CROSSBAR_DP_BOTH_PMA, + core + ACIOPHY_CROSSBAR_T8103); + + atcphy_lanes_up_t8152(atcphy, APPLE_ATCPHY_MODE_USB4); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE(0)), + ATCPHY_TEST_T8152_LANE0_UP); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE(1)), + ATCPHY_TEST_T8152_LANE0_UP); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_SLEEP_CTRL2), + ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_CLAMP_EN | + atcphy_test_t8152_lfps(0) | atcphy_test_t8152_lfps(1)); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), + (u32)ACIOPHY_CROSSBAR_DP_BOTH_PMA | reversed); + + KUNIT_EXPECT_EQ(test, atcphy_configure_lanes(atcphy, APPLE_ATCPHY_MODE_USB4), 0); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), (u32)reversed); + KUNIT_EXPECT_EQ(test, readl(core + misc), + reversed ? ATCPHY_T8152_MISC_LANE_SWAP : 0U); + + atcphy->mode = APPLE_ATCPHY_MODE_USB4; + writel(ATCPHY_POWER_APB_RESET_N, core + ctrl); + atcphy_lanes_down_t8152(atcphy); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE(0)), + ACIOPHY_T8152_AON_LANE_CLAMP_EN); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE(1)), + ACIOPHY_T8152_AON_LANE_CLAMP_EN); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_SLEEP_CTRL2), + ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_CLAMP_EN); + atcphy->mode = APPLE_ATCPHY_MODE_OFF; + atcphy_test_t8152_untouched(test, atcphy); + } +} + +/* A lane power-down with the register bus in reset leaves the lanes alone */ +static void atcphy_test_t8152_lanes_bus_reset(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + + writel(ATCPHY_TEST_T8152_LANE0_UP, core + ACIOPHY_T8152_AON_LANE0); + writel(ATCPHY_POWER_CLAMP_EN, core + ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_CTRL); + atcphy_lanes_down_t8152(atcphy); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE0), ATCPHY_TEST_T8152_LANE0_UP); +} + +/* Only USB4 in its own mode, and Thunderbolt, ask a CIO-only PHY for CIO */ +static void atcphy_test_cio_target_mode(struct kunit *test) +{ + struct typec_altmode dp = { .svid = USB_TYPEC_DP_SID }; + struct typec_altmode tbt = { .svid = USB_TYPEC_TBT_SID }; + struct enter_usb_data usb4 = { .eudo = FIELD_PREP(EUDO_USB_MODE_MASK, EUDO_USB_MODE_USB4) }; + struct enter_usb_data usb3 = { .eudo = FIELD_PREP(EUDO_USB_MODE_MASK, EUDO_USB_MODE_USB3) }; + struct typec_mux_state state = { .mode = TYPEC_MODE_USB4, .data = &usb4 }; + + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_USB4); + state.data = &usb3; + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_OFF); + state.data = NULL; + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_OFF); + state.alt = &tbt; + state.mode = TYPEC_TBT_MODE; + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_TBT); + state.alt = &dp; + state.mode = TYPEC_DP_STATE_D; + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_OFF); + state.alt = NULL; + state.mode = TYPEC_STATE_USB; + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_OFF); + state.mode = TYPEC_STATE_SAFE; + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_OFF); +} + +/* The PHY is idle only as its power-up leaves it */ +static void atcphy_test_t8152_cio_idle(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + u32 ctrl = ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_CTRL; + u32 stat = ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_STAT; + + writel(ATCPHY_POWER_CLAMP_EN, core + ctrl); + KUNIT_EXPECT_TRUE(test, atcphy_cio_idle(atcphy)); + /* the display driver's DisplayPort setup */ + writel(0x1b, core + ctrl); + KUNIT_EXPECT_FALSE(test, atcphy_cio_idle(atcphy)); + writel(ATCPHY_POWER_CLAMP_EN, core + ctrl); + writel(ATCPHY_POWER_SLEEP_SMALL, core + stat); + KUNIT_EXPECT_FALSE(test, atcphy_cio_idle(atcphy)); + writel(0, core + stat); + writel(ATCPHY_MISC_RESET_N, core + ATCPHY_T8152_SYNC_RESET); + KUNIT_EXPECT_FALSE(test, atcphy_cio_idle(atcphy)); +} + +static struct kunit_case atcphy_t8152_test_cases[] = { + KUNIT_CASE(atcphy_test_t8152_lanes), + KUNIT_CASE(atcphy_test_t8152_no_tunables), + KUNIT_CASE(atcphy_test_t8152_power), + KUNIT_CASE(atcphy_test_t8152_pipe_lock), + KUNIT_CASE(atcphy_test_t8152_cio_lanes), + KUNIT_CASE(atcphy_test_t8152_lanes_bus_reset), + KUNIT_CASE(atcphy_test_cio_target_mode), + KUNIT_CASE(atcphy_test_t8152_cio_idle), + {} +}; + +static struct kunit_suite atcphy_t8152_test_suite = { + .name = "phy-apple-atc-t8152", + .test_cases = atcphy_t8152_test_cases, +}; + +kunit_test_suite(atcphy_t8152_test_suite); diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c index 34d3aa12b8f4c8..62dfb5728a3231 100644 --- a/drivers/phy/apple/atc.c +++ b/drivers/phy/apple/atc.c @@ -249,6 +249,48 @@ enum atcphy_lane_mode { #define ACIOPHY_BIST_MAC_USBPHY_CFG_OV2_LN0_RESET_N_OV 0x200 #define ACIOPHY_BIST_MAC_USBPHY_CFG_OV2_LN0_PWR_DOWN_OV 0x20 +/* T8152 BIST block (ACIOPHY_BIST_BLK) */ +#define ACIOPHY_T8152_BIST_CFG0 0x2400 +#define ACIOPHY_T8152_BIST_CFG0_CLOCK_EN BIT(0) +#define ACIOPHY_T8152_BIST_CFG0_USB_REGSYNC BIT(6) + +#define ACIOPHY_T8152_BIST_CFG2 0x240c +#define ACIOPHY_T8152_BIST_CFG2_LN0_PHY_STATUS_RE BIT(0) + +#define ACIOPHY_T8152_BIST_STATUS1 0x24a0 +#define ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS BIT(6) +#define ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS2 BIT(7) + +#define ACIOPHY_T8152_BIST_OV1 0x24b0 +#define ACIOPHY_T8152_BIST_OV1_LN0_PIPE_RESET_N BIT(0) +#define ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN GENMASK(8, 5) + +#define ACIOPHY_T8152_BIST_OV2 0x24b8 +#define ACIOPHY_T8152_BIST_OV2_LN0_PIPE_RESET_N_OV BIT(5) +#define ACIOPHY_T8152_BIST_OV2_LN0_UNK6 BIT(6) +#define ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV BIT(9) +#define ACIOPHY_T8152_BIST_OV2_LN0_UNK10 BIT(10) +#define ACIOPHY_T8152_BIST_OV2_LN0 \ + (ACIOPHY_T8152_BIST_OV2_LN0_PIPE_RESET_N_OV | \ + ACIOPHY_T8152_BIST_OV2_LN0_UNK6 | \ + ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV | \ + ACIOPHY_T8152_BIST_OV2_LN0_UNK10) + +/* T8152 lane power controls in the always-on top block (ACIOPHY_TOP_AON_BLK) */ +#define ACIOPHY_T8152_AON_LANE(n) (0x1e18 + 4 * (n)) +#define ACIOPHY_T8152_AON_LANE0 ACIOPHY_T8152_AON_LANE(0) +#define ACIOPHY_T8152_AON_LANE_CLAMP_EN BIT(0) +#define ACIOPHY_T8152_AON_LANE_SLEEP_SMALL BIT(1) +#define ACIOPHY_T8152_AON_LANE_SLEEP_BIG BIT(2) +#define ACIOPHY_T8152_AON_LANE_AHB_RESET_N BIT(5) + +#define ACIOPHY_T8152_AON_SLEEP_CTRL2 0x1e24 +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_SLEEP_BIG BIT(6) +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_SLEEP_SMALL BIT(8) +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_CLAMP_EN BIT(10) +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL(n) BIT(12 + 2 * (n)) +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG(n) BIT(16 + 2 * (n)) + #define ACIOPHY_SLEEP_CTRL 0x1b0 #define ACIOPHY_SLEEP_CTRL_TX_BIG GENMASK(1, 0) #define ACIOPHY_SLEEP_CTRL_TX_BIG_OV GENMASK(3, 2) @@ -274,6 +316,16 @@ enum atcphy_lane_mode { #define ATCPHY_MISC_RESET_N BIT(0) #define ATCPHY_MISC_LANE_SWAP BIT(2) +/* + * T8152 has the USB controller's DARTs at 0x20000 and 0x40000 of its ATC + * window, and the power and reset block (ATCPHY_CFG_BLK) follows at 0x60000. + * There the lane swap is bit 1 of 0x60008, and the reset the power-up releases + * first is bit 0 of the always-on sync reset at 0x60030. + */ +#define ATCPHY_T8152_CFG_OFFSET 0x40000 +#define ATCPHY_T8152_MISC_LANE_SWAP BIT(1) +#define ATCPHY_T8152_SYNC_RESET 0x60030 + #define ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0 0x7000 #define DP_PMA_BYTECLK_RESET BIT(0) #define DP_MAC_DIV20_CLK_SEL BIT(1) @@ -596,6 +648,7 @@ enum atcphy_generation { ATCPHY_GENERATION_T8103, ATCPHY_GENERATION_T8122, ATCPHY_GENERATION_T8132, + ATCPHY_GENERATION_T8152, }; enum atcphy_dp_link_rate { @@ -675,10 +728,22 @@ struct apple_atcphy; /** * struct atcphy_hw - SoC-specific PHY description - * @configure_post_tunable: Generation-specific setup after the tunables + * @configure_post_tunable: Generation-specific setup after the tunables, if any * @gen: Register programming generation - * @aciophy_lane_mode: Lane mode register offset + * @aciophy_lane_mode: Lane mode register offset, or zero to leave the lane + * mode alone (T8152 sets its lanes up through the crossbar) * @aciophy_crossbar: Crossbar register offset + * @cfg_offset: Offset of the power and reset block (ATCPHY_POWER_CTRL, + * ATCPHY_POWER_STAT, ATCPHY_MISC) from where those definitions + * place it + * @sync_reset: Register whose bit 0 is the reset the PHY's power-up releases + * first and its power-down asserts last, instead of + * ATCPHY_MISC_RESET_N, or zero + * @lane_swap: Lane swap bit in ATCPHY_MISC, or zero for ATCPHY_MISC_LANE_SWAP + * @cio_lane_swap: CIO (USB4) mode sets @lane_swap for a reversed plug as well, + * next to the swapped crossbar + * @typec_cio_only: On a Type-C port the PHY runs only CIO (USB4) mode, see + * apple_atcphy.cio_only * @has_usb4: A USB4/Thunderbolt controller sits behind the PHY * @usb2_only: Uses the USB2 subset unless its banked SuperSpeed resources exist * @usb2phy_sig_host: Host role field mask, or zero for the original layout @@ -686,11 +751,15 @@ struct apple_atcphy; * @pipe_mux_data: PIPE data selection field mask * @has_usb2phy_reg: The PHY has the secondary eUSB2 register bank (T8140) * @has_t8140_dp: Uses the T8140 DisplayPort tunable bundle - * @optional_tunables: The bootloader may leave out the common-a tunables (this - * generation has none) and the SuperSpeed tunables; USB2 - * still works without the latter + * @optional_tunables: The bootloader may leave out the common-a tunables (T8122 + * has none) and the SuperSpeed tunables (an older loader + * copies no T8152 ones); the PHY still probes, and USB2 + * works without the latter * @park_pipe_unlocked: A stopped controller may park without a PIPE handshake * @clear_boot_hold: Release the boot PIPE hold before dummy backend selection + * @pipe_lock_unacked: The PIPE handler takes the lock request but never + * acknowledges it, so the PIPE changes under the request + * without waiting for the acknowledge * @dp_banked_tunables: DisplayPort requires separate LIOA/common calibration * @dp_t8122: DisplayPort runs the T8122 AUX, AUSPLL and lane sequences * @park_dummy_phy: Enable the dummy PIPE backend whenever the PIPE is parked on @@ -700,6 +769,9 @@ struct apple_atcphy; * sleep, or at runtime with @idle_power_off, which * resets the block; bring the tracked state back once * the domain is on again + * @sleep_drops_common: Deep sleep lowers the common power domain behind + * genpd's back, so resume must mark @pd_was_off even + * without a genpd power-off notification * @idle_power_off: Let an idle PHY runtime-suspend, so that its power domain * can also drop while the system runs, see atcphy_rpm_get(). * Only for PHYs without DisplayPort, whose phy ops and tunnel @@ -710,6 +782,11 @@ struct atcphy_hw { enum atcphy_generation gen; int aciophy_lane_mode; int aciophy_crossbar; + u32 cfg_offset; + u32 sync_reset; + u32 lane_swap; + bool cio_lane_swap; + bool typec_cio_only; bool has_usb4; bool usb2_only; u32 usb2phy_sig_host; @@ -723,7 +800,9 @@ struct atcphy_hw { bool park_pipe_unlocked; bool park_dummy_phy; bool clear_boot_hold; + bool pipe_lock_unacked; bool restore_after_pd_off; + bool sleep_drops_common; bool idle_power_off; }; @@ -796,6 +875,21 @@ struct atcphy_cio_sleep { * behind the T6030 HDMI port; it maps only its core window * @fixed_usb2: The USB2 pairs go to a fixed hub on the USB controller, which * stays in host mode; the PHY provides USB2 from probe on + * @fixed_usb3: The SuperSpeed lanes go straight to a USB3 device or hub, with + * no Type-C mux in between (apple,fixed-usb3): the PHY runs USB3 + * on lane 0 from probe on and provides only the USB3 PHY of the + * controller, which is a host; its USB2 side and its reset are + * left to the bootloader + * @cio_only: A Type-C port on which the PHY runs CIO (USB4) mode alone + * (atcphy_hw.typec_cio_only): its DisplayPort mode is the display + * driver's, which powers the DP PHY while it drives the PHY itself, + * and its USB2 side is left to the bootloader. See + * atcphy_cio_mux_set(). + * @cio_pds: The power domains of a @cio_only PHY, in power-up order + * @cio_powered: The PHY holds @cio_pds for CIO mode + * @display_owned: The display driver drives a @cio_only PHY and holds @cio_pds + * through the DP PHY, or the bootloader left it driving a + * display, which the display driver takes over * @typec_mode: Mode the Type-C mux last asked for; a fixed-hub port returns to * it when the PHY is brought back up after a power-off * @host_active: dwc3 has selected host mode on the USB3 PHY; a fixed-hub port @@ -881,6 +975,13 @@ struct apple_atcphy { const struct atcphy_hw *hw; /* T8132 keeps USB2 support when its optional SuperSpeed banks are absent. */ bool t8132_ss; + /* + * SuperSpeed device mode is not supported by this driver on T8132: + * while the controller holds the device role, the lanes run USB2 + * instead of a partner's SuperSpeed mode. Cleared when the USB3 PHY + * powers off or the controller switches to host mode. + */ + bool t8132_device; /* Only this driver's admitted common-power epoch may be stopped. */ bool t8132_common_owned; /* A touched failure has no qualified partial rollback or retry. */ @@ -910,6 +1011,11 @@ struct apple_atcphy { bool dp_presets_valid[5]; bool dp_only; bool fixed_usb2; + bool fixed_usb3; + bool cio_only; + struct dev_pm_domain_list *cio_pds; + bool cio_powered; + bool display_owned; enum atcphy_mode typec_mode; bool host_active; /* @@ -1276,6 +1382,115 @@ static inline u32 core_read32(struct apple_atcphy *atcphy, u32 reg) return readl(atcphy->regs.core + reg); } +/* A register of the power and reset block, see atcphy_hw.cfg_offset */ +static inline u32 atcphy_cfg(const struct apple_atcphy *atcphy, u32 reg) +{ + return reg + atcphy->hw->cfg_offset; +} + +static inline u32 atcphy_lane_swap(const struct apple_atcphy *atcphy) +{ + return atcphy->hw->lane_swap ?: ATCPHY_MISC_LANE_SWAP; +} + +/* T8152: the lanes a mode runs on, lane 0 for USB3, both for CIO (USB4) */ +static unsigned int atcphy_lanes_t8152(enum atcphy_mode mode) +{ + return mode == APPLE_ATCPHY_MODE_USB4 || mode == APPLE_ATCPHY_MODE_TBT ? 2 : 1; +} + +/* + * T8152 keeps a lane's registers in AHB reset until the lane is powered up on + * its own, and they drop their tunables meanwhile. Power the lanes of the mode + * up after the common-a tunables, one after the other: lane 0, the USB3 lane + * of a fixed-USB3 port, and in CIO mode lane 1 too. Each gets its LFPS + * receivers, then goes out of sleep, unclamped and out of AHB reset. Set the + * crossbar right after, before the remaining tunables, as the T8152 sequence + * does: 0x110 for USB3, i.e. USB3+DP with single PMA 0x008, and 0 or 1 for + * CIO by the plug orientation. atcphy_configure_lanes() writes the same value + * again later. + */ +static void atcphy_lanes_up_t8152(struct apple_atcphy *atcphy, enum atcphy_mode mode) +{ + const struct atcphy_mode_configuration *mode_cfg = atcphy_get_mode_config(atcphy, mode); + + for (unsigned int lane = 0; lane < atcphy_lanes_t8152(mode); lane++) { + u32 ctrl = ACIOPHY_T8152_AON_LANE(lane); + + core_set32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL(lane)); + udelay(1); + core_set32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG(lane)); + udelay(1); + core_set32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_SLEEP_SMALL); + udelay(1); + core_set32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_SLEEP_BIG); + udelay(1); + core_clear32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_CLAMP_EN); + udelay(1); + core_set32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_AHB_RESET_N); + udelay(1); + } + + core_mask32(atcphy, atcphy->hw->aciophy_crossbar, + ACIOPHY_CROSSBAR_PROTOCOL | ACIOPHY_CROSSBAR_DP_SINGLE_PMA, + FIELD_PREP(ACIOPHY_CROSSBAR_PROTOCOL, mode_cfg->crossbar) | + FIELD_PREP(ACIOPHY_CROSSBAR_DP_SINGLE_PMA, + mode_cfg->crossbar_dp_single_pma)); +} + +/* + * T8152: power the lanes of the current mode down as the PHY powers down, the + * reverse of the above, while the register bus is still out of reset (a + * failed power-up may not have released it). A CIO-only PHY only ever runs + * CIO mode, so both of its lanes, also after a failed CIO power-up. Leaving + * CIO mode also clamps AUX and drops both lanes' LFPS receivers first, as the + * T8152 CIO shutdown does; the lanes' power controls are always-on and keep + * what they are left with across the common block's power-down. + */ +static void atcphy_lanes_down_t8152(struct apple_atcphy *atcphy) +{ + unsigned int lanes = atcphy->cio_only ? 2 : atcphy_lanes_t8152(atcphy->mode); + + if (!(core_read32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL)) & + ATCPHY_POWER_APB_RESET_N)) + return; + + if (lanes > 1) { + core_set32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_CLAMP_EN); + udelay(1); + core_clear32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_SLEEP_BIG); + udelay(1); + core_clear32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_SLEEP_SMALL); + udelay(1); + for (unsigned int lane = 0; lane < lanes; lane++) { + core_clear32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL(lane)); + udelay(1); + core_clear32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG(lane)); + udelay(1); + } + } + + for (unsigned int lane = 0; lane < lanes; lane++) { + u32 ctrl = ACIOPHY_T8152_AON_LANE(lane); + + core_clear32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_AHB_RESET_N); + udelay(1); + core_set32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_CLAMP_EN); + udelay(1); + core_clear32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_SLEEP_BIG); + udelay(1); + core_clear32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_SLEEP_SMALL); + udelay(1); + } +} + /* Static configuration fields already read/modified by the public DP path. */ static void j700_dp_tunables(struct apple_atcphy *atcphy) { @@ -1305,6 +1520,8 @@ static void atcphy_apply_tunables(struct apple_atcphy *atcphy, enum atcphy_mode } apple_tunable_apply(atcphy->regs.core, atcphy->tunables.common[0]); + if (atcphy->hw->gen == ATCPHY_GENERATION_T8152) + atcphy_lanes_up_t8152(atcphy, mode); apple_tunable_apply(atcphy->regs.axi2af, atcphy->tunables.axi2af); apple_tunable_apply(atcphy->regs.core, atcphy->tunables.common[1]); @@ -1389,6 +1606,10 @@ static int atcphy_pipehandler_lock(struct apple_atcphy *atcphy) if (IS_ENABLED(CONFIG_PHY_APPLE_ATC_KUNIT_TEST)) KUNIT_STATIC_STUB_REDIRECT(atcphy_pipehandler_lock, atcphy); + if (atcphy->hw->pipe_lock_unacked) { + set32(atcphy->regs.pipehandler + PIPEHANDLER_LOCK_REQ, PIPEHANDLER_LOCK_EN); + return 0; + } return atcphy_pipehandler_lock_timeout(atcphy, atcphy->hw->gen == ATCPHY_GENERATION_T8132 ? 6000 : PIPEHANDLER_LOCK_ACK_TIMEOUT_US); @@ -1631,6 +1852,77 @@ static int atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *atc return ret; } +/* T8152: latch the BIST override registers into the USB side of the PHY */ +static void atcphy_t8152_bist_sync(struct apple_atcphy *atcphy) +{ + core_set32(atcphy, ACIOPHY_T8152_BIST_CFG0, ACIOPHY_T8152_BIST_CFG0_USB_REGSYNC); + core_read32(atcphy, ACIOPHY_T8152_BIST_CFG0); + core_clear32(atcphy, ACIOPHY_T8152_BIST_CFG0, ACIOPHY_T8152_BIST_CFG0_USB_REGSYNC); +} + +static void atcphy_t8152_bist_ack(struct apple_atcphy *atcphy) +{ + core_set32(atcphy, ACIOPHY_T8152_BIST_CFG2, ACIOPHY_T8152_BIST_CFG2_LN0_PHY_STATUS_RE); + core_clear32(atcphy, ACIOPHY_T8152_BIST_CFG2, ACIOPHY_T8152_BIST_CFG2_LN0_PHY_STATUS_RE); +} + +/* + * T8152: while the PIPE moves from the dummy PHY to this one, the BIST + * overrides hold lane 0's PIPE reset and power-down, the power-down stepping + * from P2 to P3, and the non-selected PHY override is released under them. + */ +static int atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *atcphy) +{ + void __iomem *status = atcphy->regs.core + ACIOPHY_T8152_BIST_STATUS1; + int ret, error = 0; + u32 reg; + + core_set32(atcphy, ACIOPHY_T8152_BIST_CFG0, ACIOPHY_T8152_BIST_CFG0_CLOCK_EN); + core_mask32(atcphy, ACIOPHY_T8152_BIST_OV1, ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN, + ACIOPHY_T8152_BIST_OV1_LN0_PIPE_RESET_N | + FIELD_PREP(ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN, 2)); + core_mask32(atcphy, ACIOPHY_T8152_BIST_OV2, ACIOPHY_T8152_BIST_OV2_LN0, + ACIOPHY_T8152_BIST_OV2_LN0_PIPE_RESET_N_OV | + ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV); + atcphy_t8152_bist_sync(atcphy); + ret = readl_poll_timeout(status, reg, !(reg & ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS2), + 10, 20000); + if (ret) { + error = ret; + dev_warn(atcphy->dev, "T8152 USB3 BIST: PHY status stuck in P2 (%#x)\n", reg); + } + atcphy_t8152_bist_ack(atcphy); + + core_mask32(atcphy, ACIOPHY_T8152_BIST_OV1, ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN, + FIELD_PREP(ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN, 3)); + core_mask32(atcphy, ACIOPHY_T8152_BIST_OV2, + ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV | ACIOPHY_T8152_BIST_OV2_LN0_UNK10, + ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV); + atcphy_t8152_bist_sync(atcphy); + ret = readl_poll_timeout(status, reg, reg & ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS, + 10, 130000); + if (ret) { + if (!error) + error = ret; + dev_warn(atcphy->dev, "T8152 USB3 BIST: no PHY status in P3 (%#x)\n", reg); + } + ret = readl_poll_timeout(status, reg, !(reg & ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS2), + 10, 1000); + if (ret) { + if (!error) + error = ret; + dev_warn(atcphy->dev, "T8152 USB3 BIST: PHY status stuck in P3 (%#x)\n", reg); + } + atcphy_t8152_bist_ack(atcphy); + + atcphy_clear_nonselected_phy_reset(atcphy); + + core_clear32(atcphy, ACIOPHY_T8152_BIST_OV2, ACIOPHY_T8152_BIST_OV2_LN0); + atcphy_t8152_bist_sync(atcphy); + core_clear32(atcphy, ACIOPHY_T8152_BIST_CFG0, ACIOPHY_T8152_BIST_CFG0_CLOCK_EN); + return error; +} + static int atcphy_configure_pipehandler_usb3_host_t8103(struct apple_atcphy *atcphy) { int ret, error = 0; @@ -1738,6 +2030,8 @@ static int atcphy_configure_pipehandler_usb3(struct apple_atcphy *atcphy, bool h ret = atcphy_configure_pipehandler_usb3_host_t8103(atcphy); else if (atcphy->hw->gen == ATCPHY_GENERATION_T8132) ret = atcphy_configure_pipehandler_usb3_host_t8132(atcphy); + else if (atcphy->hw->gen == ATCPHY_GENERATION_T8152) + ret = atcphy_configure_pipehandler_usb3_host_t8152(atcphy); else ret = atcphy_configure_pipehandler_usb3_host_t8122(atcphy); if (ret) { @@ -2147,21 +2441,24 @@ static int atcphy_configure_lanes(struct apple_atcphy *atcphy, enum atcphy_mode mode == APPLE_ATCPHY_MODE_DP)) return j700_dp_route(atcphy, mode == APPLE_ATCPHY_MODE_DP); - core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_RX0, - FIELD_PREP(ACIOPHY_LANE_MODE_RX0, mode_cfg->lane_mode[0])); - core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_TX0, - FIELD_PREP(ACIOPHY_LANE_MODE_TX0, mode_cfg->lane_mode[0])); - core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_RX1, - FIELD_PREP(ACIOPHY_LANE_MODE_RX1, mode_cfg->lane_mode[1])); - core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_TX1, - FIELD_PREP(ACIOPHY_LANE_MODE_TX1, mode_cfg->lane_mode[1])); + if (atcphy->hw->aciophy_lane_mode) { + core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_RX0, + FIELD_PREP(ACIOPHY_LANE_MODE_RX0, mode_cfg->lane_mode[0])); + core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_TX0, + FIELD_PREP(ACIOPHY_LANE_MODE_TX0, mode_cfg->lane_mode[0])); + core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_RX1, + FIELD_PREP(ACIOPHY_LANE_MODE_RX1, mode_cfg->lane_mode[1])); + core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_TX1, + FIELD_PREP(ACIOPHY_LANE_MODE_TX1, mode_cfg->lane_mode[1])); + } core_mask32(atcphy, atcphy->hw->aciophy_crossbar, ACIOPHY_CROSSBAR_PROTOCOL, FIELD_PREP(ACIOPHY_CROSSBAR_PROTOCOL, mode_cfg->crossbar)); - if (mode_cfg->set_swap) - core_set32(atcphy, ATCPHY_MISC, ATCPHY_MISC_LANE_SWAP); + if (mode_cfg->set_swap || + (atcphy->hw->cio_lane_swap && atcphy_mode_is_cio(mode) && atcphy->swap_lanes)) + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_MISC), atcphy_lane_swap(atcphy)); else - core_clear32(atcphy, ATCPHY_MISC, ATCPHY_MISC_LANE_SWAP); + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_MISC), atcphy_lane_swap(atcphy)); core_mask32(atcphy, atcphy->hw->aciophy_crossbar, ACIOPHY_CROSSBAR_DP_SINGLE_PMA, FIELD_PREP(ACIOPHY_CROSSBAR_DP_SINGLE_PMA, mode_cfg->crossbar_dp_single_pma)); @@ -2173,8 +2470,10 @@ static int atcphy_configure_lanes(struct apple_atcphy *atcphy, enum atcphy_mode /* * The PMA FSM override below is for the T8103 generation. T8122 DP lanes * are started by the link rate sequence, see atcphy_dp_set_rate_t8122(). + * T8152 runs USB3 or CIO alone. */ - if (atcphy->hw->gen == ATCPHY_GENERATION_T8122) + if (atcphy->hw->gen == ATCPHY_GENERATION_T8122 || + atcphy->hw->gen == ATCPHY_GENERATION_T8152) return 0; if (mode_cfg->dp_lane[0]) { @@ -2707,34 +3006,44 @@ static int atcphy_power_off(struct apple_atcphy *atcphy) u32 reg; int ret; - if (atcphy->hw->gen != ATCPHY_GENERATION_T8132) { + /* A fixed-USB3 port has no DisplayPort side, a CIO-only port leaves it alone */ + if (atcphy->hw->gen != ATCPHY_GENERATION_T8132 && !atcphy->fixed_usb3 && + !atcphy->cio_only) { ret = atcphy_disable_dp_aux(atcphy); if (ret) return ret; } /* Enable all reset lines */ - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_PHY_RESET_N); - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_CLAMP_EN); - core_clear32(atcphy, ATCPHY_MISC, ATCPHY_MISC_RESET_N | ATCPHY_MISC_LANE_SWAP); - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_APB_RESET_N); - - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_SLEEP_BIG); - ret = readl_poll_timeout(atcphy->regs.core + ATCPHY_POWER_STAT, reg, + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_PHY_RESET_N); + if (atcphy->hw->gen == ATCPHY_GENERATION_T8152) + atcphy_lanes_down_t8152(atcphy); + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_CLAMP_EN); + if (!atcphy->hw->sync_reset) + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_MISC), + ATCPHY_MISC_RESET_N | ATCPHY_MISC_LANE_SWAP); + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_APB_RESET_N); + + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_SLEEP_BIG); + ret = readl_poll_timeout(atcphy->regs.core + atcphy_cfg(atcphy, ATCPHY_POWER_STAT), reg, !(reg & ATCPHY_POWER_SLEEP_BIG), 10, 1000); if (ret) { dev_err(atcphy->dev, "Failed to sleep atcphy \"big\"\n"); return ret; } - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_SLEEP_SMALL); - ret = readl_poll_timeout(atcphy->regs.core + ATCPHY_POWER_STAT, reg, + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_SLEEP_SMALL); + ret = readl_poll_timeout(atcphy->regs.core + atcphy_cfg(atcphy, ATCPHY_POWER_STAT), reg, !(reg & ATCPHY_POWER_SLEEP_SMALL), 10, 1000); if (ret) { dev_err(atcphy->dev, "Failed to sleep atcphy \"small\"\n"); return ret; } + /* A separate sync reset is asserted last, once the block sleeps */ + if (atcphy->hw->sync_reset) + core_clear32(atcphy, atcphy->hw->sync_reset, ATCPHY_MISC_RESET_N); + return 0; } @@ -2792,29 +3101,30 @@ static int atcphy_power_on(struct apple_atcphy *atcphy) u32 reg; int ret; - if (!atcphy->dp_only) + if (!atcphy->dp_only && !atcphy->fixed_usb3 && !atcphy->cio_only) atcphy_usb2_power_on(atcphy); - core_set32(atcphy, ATCPHY_MISC, ATCPHY_MISC_RESET_N); + core_set32(atcphy, atcphy->hw->sync_reset ?: atcphy_cfg(atcphy, ATCPHY_MISC), + ATCPHY_MISC_RESET_N); - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_SLEEP_SMALL); - ret = readl_poll_timeout(atcphy->regs.core + ATCPHY_POWER_STAT, reg, + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_SLEEP_SMALL); + ret = readl_poll_timeout(atcphy->regs.core + atcphy_cfg(atcphy, ATCPHY_POWER_STAT), reg, reg & ATCPHY_POWER_SLEEP_SMALL, 100, 100000); if (ret) { dev_err(atcphy->dev, "failed to wakeup atcphy \"small\"\n"); return ret; } - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_SLEEP_BIG); - ret = readl_poll_timeout(atcphy->regs.core + ATCPHY_POWER_STAT, reg, + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_SLEEP_BIG); + ret = readl_poll_timeout(atcphy->regs.core + atcphy_cfg(atcphy, ATCPHY_POWER_STAT), reg, reg & ATCPHY_POWER_SLEEP_BIG, 100, 100000); if (ret) { dev_err(atcphy->dev, "failed to wakeup atcphy \"big\"\n"); return ret; } - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_CLAMP_EN); - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_APB_RESET_N); + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_CLAMP_EN); + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_APB_RESET_N); return 0; } @@ -3620,6 +3930,19 @@ static bool atcphy_t8132_dp_on(const struct apple_atcphy *atcphy) return atcphy->hw->gen == ATCPHY_GENERATION_T8132 && atcphy->t8132_dp_alt; } +/* + * The mode a T8132 port runs in while its controller is a USB device: + * SuperSpeed device mode is not supported by this driver, so USB3 and pin-D + * USB3+DP fall back to USB2. Four-lane DisplayPort (pin C/E) keeps USB2 on its + * own wires and is unchanged. + */ +static enum atcphy_mode atcphy_t8132_device_mode(enum atcphy_mode mode) +{ + if (mode == APPLE_ATCPHY_MODE_USB3 || mode == APPLE_ATCPHY_MODE_USB3_DP) + return APPLE_ATCPHY_MODE_USB2; + return mode; +} + /* * The T8132 lane start differs from the T8122 one: both blocks start at swing * 0 / pre-emphasis 0, the RX block's VREF filter is held until both DTVREG @@ -4170,6 +4493,10 @@ static int atcphy_configure(struct apple_atcphy *atcphy, enum atcphy_mode mode) return -EBUSY; if (atcphy->hw->gen == ATCPHY_GENERATION_T8132) return atcphy_configure_t8132(atcphy, mode); + /* T8152 without its tunables (an older loader): the lanes stay off, USB2 only */ + if (atcphy->hw->gen == ATCPHY_GENERATION_T8152 && !atcphy->ss_tunables && + mode != APPLE_ATCPHY_MODE_OFF && mode != APPLE_ATCPHY_MODE_USB2) + return -EOPNOTSUPP; if (atcphy->pipe_pending) return -EBUSY; if (atcphy->usb_off_pending && mode != APPLE_ATCPHY_MODE_OFF) @@ -4265,7 +4592,8 @@ static int atcphy_configure(struct apple_atcphy *atcphy, enum atcphy_mode mode) apple_tunable_apply(atcphy->regs.lioa, atcphy->tunables.dp_lioa); apple_tunable_apply(atcphy->regs.lpdptx, atcphy->tunables.dp_common_config); } - atcphy->hw->configure_post_tunable(atcphy, mode); + if (atcphy->hw->configure_post_tunable) + atcphy->hw->configure_post_tunable(atcphy, mode); /* Setup AUX channel if DP altmode is requested */ if (atcphy_modes[mode].enable_dp_aux) { @@ -4284,7 +4612,7 @@ static int atcphy_configure(struct apple_atcphy *atcphy, enum atcphy_mode mode) return ret; /* Take the USB3 PHY out of reset */ - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_PHY_RESET_N); + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_PHY_RESET_N); /* * NOTE: Not what macos does, it takes the phy out of reset right before * writing to ACIOPHY_CFG0_COMMON_SMALL, does lane configuration with phy @@ -4552,8 +4880,13 @@ static int atcphy_usb2_init(struct phy *phy) /* A delayed shutdown may have completed after the last Type-C event. */ if (!atcphy->fixed_usb2) { - if (atcphy->mode == APPLE_ATCPHY_MODE_OFF || atcphy->mode_dirty) - return atcphy_configure(atcphy, atcphy->typec_mode); + if (atcphy->mode == APPLE_ATCPHY_MODE_OFF || atcphy->mode_dirty) { + enum atcphy_mode mode = atcphy->t8132_device ? + atcphy_t8132_device_mode(atcphy->typec_mode) : + atcphy->typec_mode; + + return atcphy_configure(atcphy, mode); + } /* * Reset assertion stops USB2 even when a DisplayPort mode keeps * the common block running. An aborted suspend need not produce @@ -4627,10 +4960,11 @@ static int atcphy_usb3_power_off(struct phy *phy) atcphy_restore_after_pd_off(atcphy); /* - * dwc3 has left host mode: nothing drives the PIPE any more, and the + * dwc3 has left its role: nothing drives the PIPE any more, and the * next host powers its SuperSpeed port on as it starts. */ atcphy->host_active = false; + atcphy->t8132_device = false; atcphy->usb3_port_off = false; ret = atcphy_park_pipehandler(atcphy, true); @@ -4638,14 +4972,16 @@ static int atcphy_usb3_power_off(struct phy *phy) return ret; atcphy->t8103_usb3_retry = false; /* - * T8132 keeps DWC3 on the dummy PIPE while USB4/Thunderbolt owns the - * lanes. Stopping that USB host must not take the dock's PCIe and DP - * tunnels down before their drivers suspend. The Type-C mux owns the - * CIO mode and releases it when the connection ends. A CIO mode whose - * last transition failed is still taken down, as before. + * In USB4/Thunderbolt the router owns the lanes: dwc3 only had its PIPE + * on the router's USB3 adapter (or on the dummy backend), and that is + * parked above. Stopping the USB host, for a cable change or only for a + * data role swap, must not take the router's link down with it: that + * drops a host-to-host link, and a dock's PCIe and DP tunnels, before + * their drivers know. The Type-C mux owns the CIO mode and releases it + * when the connection ends. A CIO mode whose last transition failed is + * still taken down, as before. */ - if (atcphy->hw->gen == ATCPHY_GENERATION_T8132 && atcphy_mode_is_cio(atcphy->mode) && - !atcphy->mode_dirty) + if (atcphy_mode_is_cio(atcphy->mode) && !atcphy->mode_dirty) return 0; /* * dwc3 can tear its host down while a DisplayPort alt mode link is up, @@ -4714,6 +5050,8 @@ static int atcphy_usb3_route(struct apple_atcphy *atcphy, bool host) return atcphy_configure_pipehandler(atcphy, host); } +static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode target_mode); + static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode) { struct apple_atcphy *atcphy = phy_get_drvdata(phy); @@ -4725,18 +5063,51 @@ static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode if (atcphy->usb_off_pending) return -EBUSY; - if (atcphy->t8132_ss && - (atcphy->mode == APPLE_ATCPHY_MODE_USB3 || atcphy->mode == APPLE_ATCPHY_MODE_USB3_DP) && - mode == PHY_MODE_USB_DEVICE) - return -EOPNOTSUPP; - switch (mode) { case PHY_MODE_USB_HOST: + if (atcphy->t8132_device) { + enum atcphy_mode target = atcphy->typec_mode; + + /* + * Leaving the device role lifts the USB2 fallback: + * restore the partner's SuperSpeed mode before + * host_active blocks T8132 lane reconfiguration. + */ + atcphy->t8132_device = false; + if (atcphy->mode == APPLE_ATCPHY_MODE_USB2 && + atcphy_t8132_device_mode(target) != target) { + ret = atcphy_mux_switch(atcphy, target); + if (ret) { + atcphy->t8132_device = true; + return ret; + } + } + } atcphy->host_active = true; /* A host that starts up powers the ports of its root hubs itself. */ atcphy->usb3_port_off = false; break; case PHY_MODE_USB_DEVICE: + if (atcphy->t8132_ss) { + enum atcphy_mode usb2 = atcphy_t8132_device_mode(atcphy->mode); + + /* + * SuperSpeed device mode is not supported by this + * driver on T8132: serve the device role on USB2 + * instead of failing it. Keep typec_mode intact so a + * later host role can restore SuperSpeed. + */ + if (usb2 != atcphy->mode) { + enum atcphy_mode saved_typec_mode = atcphy->typec_mode; + + dev_info(atcphy->dev, + "USB device role: SuperSpeed device mode not supported by driver, using USB2\n"); + ret = atcphy_mux_switch(atcphy, usb2); + atcphy->typec_mode = saved_typec_mode; + if (ret) + return ret; + } + } atcphy->host_active = false; break; default: @@ -4744,6 +5115,8 @@ static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode } ret = atcphy_usb3_route(atcphy, mode == PHY_MODE_USB_HOST); + if (!ret && atcphy->t8132_ss && mode == PHY_MODE_USB_DEVICE) + atcphy->t8132_device = true; if (atcphy->hw->gen == ATCPHY_GENERATION_T8132) dev_dbg(atcphy->dev, "USB %s route: mode=%u ss=%u calibration=%u common=%u dirty=%u pipe=%u pending=%u ret=%d mux=%#x override=%#x config=%#x\n", @@ -4753,7 +5126,7 @@ static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode readl(atcphy->regs.pipehandler + PIPEHANDLER_MUX_CTRL), readl(atcphy->regs.pipehandler + PIPEHANDLER_NONSELECTED_OVERRIDE), readl(atcphy->regs.pipehandler + PIPEHANDLER_T8132_USB2_CONFIG)); - if (!ret || !atcphy->fixed_usb2 || mode != PHY_MODE_USB_HOST) + if (!ret || !(atcphy->fixed_usb2 || atcphy->fixed_usb3) || mode != PHY_MODE_USB_HOST) return ret; /* @@ -4761,7 +5134,8 @@ static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode * fails, xHCI registers neither of its root hubs. Let it start, with * the PIPE parked if that works: the Type-C mux update that restores * the lanes or retries the handoff routes the PIPE, with the - * SuperSpeed port off. + * SuperSpeed port off. On a fixed-USB3 port the controller's next + * power-on of this PHY tries again. */ if (atcphy_park_pipehandler(atcphy, false)) dev_warn(atcphy->dev, "Host starts with its PIPE not parked\n"); @@ -4770,6 +5144,35 @@ static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode return 0; } +/* + * A fixed-USB3 port's controller is a host by construction. It powers this + * PHY on after its core reset, before the host starts: route the PIPE to the + * USB3 PHY then, bringing the PHY up in USB3 again first if a power-off took + * it down. A failure here would stop the controller altogether, and with it + * the USB2 side of the same device, so the host then starts with its PIPE + * parked instead. + */ +static int atcphy_usb3_power_on(struct phy *phy) +{ + struct apple_atcphy *atcphy = phy_get_drvdata(phy); + int ret = 0; + + guard(mutex)(&atcphy->lock); + atcphy->host_active = true; + if (atcphy->mode != APPLE_ATCPHY_MODE_USB3 || atcphy->mode_dirty) + ret = atcphy_configure(atcphy, APPLE_ATCPHY_MODE_USB3); + if (!ret) + ret = atcphy_usb3_route(atcphy, true); + if (!ret) + return 0; + + if (atcphy_park_pipehandler(atcphy, false)) + dev_warn(atcphy->dev, "Host starts with its PIPE not parked\n"); + else + dev_warn(atcphy->dev, "Host starts without USB3: %d\n", ret); + return 0; +} + static int atcphy_usb3_exit(struct phy *phy) { struct apple_atcphy *atcphy = phy_get_drvdata(phy); @@ -4817,6 +5220,17 @@ static const struct phy_ops apple_atc_usb3_phy_ops = { .set_mode = atcphy_rpm_usb3_set_mode, }; +/* + * A fixed-USB3 port also routes its PIPE at power-on. Its PHY never + * runtime-suspends (see atcphy_rpm_get()), so it needs no runtime PM wrappers. + */ +static const struct phy_ops apple_atc_fixed_usb3_phy_ops = { + .owner = THIS_MODULE, + .power_on = atcphy_usb3_power_on, + .power_off = atcphy_usb3_power_off, + .set_mode = atcphy_usb3_set_mode, +}; + /* * The T8132 PHY has no DisplayPort alternate mode: its DP PHY only exists so * that a DisplayPort tunnel can get its pixel clock, see @@ -4949,9 +5363,18 @@ static int atcphy_dpphy_configure(struct phy *phy, union phy_configure_opts *opt if (atcphy->hw->dp_t8122) return atcphy_dpphy_configure_t8122(atcphy, opts); - if (opts->set_voltages) - return -EINVAL; - if (opts->set_lanes) + /* + * These PHYs have no drive level control: the lanes keep the levels + * their tunables set up, as the T8132 branch above does. A drive-only + * request succeeds, so DCP's link training goes on with those levels; + * drive levels together with a rate change are not a request DCP makes. + */ + if (opts->set_voltages && !opts->set_rate && !opts->set_lanes) { + dev_dbg(atcphy->dev, "DP drive request ignored (lane 0 swing %u pre %u)\n", + opts->voltage[0], opts->pre[0]); + return 0; + } + if (opts->set_voltages || opts->set_lanes) return -EINVAL; if (opts->set_rate) { @@ -5188,6 +5611,200 @@ int apple_atc_dp_tunnel_open(struct phy *phy) } EXPORT_SYMBOL_GPL(apple_atc_dp_tunnel_open); +/* + * T8152's rear USB-C ports (atcphy_hw.typec_cio_only, apple_atcphy.cio_only): + * the PHY runs CIO mode for a USB4 partner and is left alone otherwise. + * + * Their DisplayPort alt mode is still driven by the display driver, which + * programs the PHY's power and reset block, lanes and display crossbar + * itself. The two take turns on the PHY: + * + * - The display driver powers the DP PHY on before it touches the PHY and + * off once it has let go of it. The DP PHY then holds the PHY's power + * domains for it, and keeps the PHY out of CIO mode: a USB4 mode change + * fails with -ETIMEDOUT, which the Type-C port driver retries (the mux + * declares its timeouts transient) until the display driver is done. + * - A DP PHY power-on is refused with -EBUSY while the PHY runs CIO mode. + * - Either takes the PHY only from its idle state: the power and reset block + * as the power-up leaves it, clamped and asleep, its sync reset asserted. + * Anything else means another user still has it, and CIO mode is refused. + * - A display the bootloader brought up keeps running for the display + * driver: such a PHY has all its domains on and is not idle at probe, and + * the domains are held for the display driver until its DP PHY goes off. + * + * Once the DisplayPort mode moves into this driver, the DP PHY programs it + * itself, both modes switch under the PHY's lock, and this arbitration goes. + */ +static int atcphy_cio_pds_on(struct apple_atcphy *atcphy) +{ + struct dev_pm_domain_list *pds = atcphy->cio_pds; + int ret; + + for (unsigned int i = 0; i < pds->num_pds; i++) { + ret = pm_runtime_resume_and_get(pds->pd_devs[i]); + if (ret < 0) { + while (i--) + pm_runtime_put_sync(pds->pd_devs[i]); + return ret; + } + } + return 0; +} + +/* Synchronously: the next CIO mode or display must find them off. */ +static void atcphy_cio_pds_off(struct apple_atcphy *atcphy) +{ + struct dev_pm_domain_list *pds = atcphy->cio_pds; + + for (unsigned int i = pds->num_pds; i > 0; i--) + pm_runtime_put_sync(pds->pd_devs[i - 1]); +} + +/* The power and reset block as its power-up leaves it, with its domains on */ +static bool atcphy_cio_idle(struct apple_atcphy *atcphy) +{ + return core_read32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL)) == + ATCPHY_POWER_CLAMP_EN && + !(core_read32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_STAT)) & + (ATCPHY_POWER_SLEEP_SMALL | ATCPHY_POWER_SLEEP_BIG)) && + !core_read32(atcphy, atcphy->hw->sync_reset); +} + +/* + * The CIO shutdown, then the power domains: the common block goes cold, so + * that the next partner, in either orientation, starts from a cold PHY. With + * the common block left powered, the next link training asserted in the + * router's firmware. A failed shutdown keeps the domains for the next try. + */ +static int atcphy_cio_stop(struct apple_atcphy *atcphy) +{ + int ret; + + lockdep_assert_held(&atcphy->lock); + ret = atcphy_configure(atcphy, APPLE_ATCPHY_MODE_OFF); + if (ret) { + dev_err(atcphy->dev, "CIO shutdown failed: %d\n", ret); + return ret; + } + atcphy_cio_pds_off(atcphy); + atcphy->cio_powered = false; + dev_dbg(atcphy->dev, "CIO mode off\n"); + return 0; +} + +static int atcphy_cio_start(struct apple_atcphy *atcphy, enum atcphy_mode mode) +{ + int ret; + + lockdep_assert_held(&atcphy->lock); + /* + * Without its tunables (an older loader) atcphy_configure() refuses CIO: + * leave the power domains alone instead of cycling them for nothing. + */ + if (atcphy->hw->gen == ATCPHY_GENERATION_T8152 && !atcphy->ss_tunables) { + dev_info(atcphy->dev, "USB4 needs the bootloader's PHY tunables; the port stays USB2\n"); + return -EOPNOTSUPP; + } + /* The router's Thunderbolt mode is not qualified on these ports. */ + if (mode != APPLE_ATCPHY_MODE_USB4) { + dev_info(atcphy->dev, "Thunderbolt alt mode is not supported on this port\n"); + return -ENODEV; + } + if (atcphy->display_owned) { + dev_dbg(atcphy->dev, "USB4 waits for the display driver to release the PHY\n"); + return -ETIMEDOUT; + } + ret = atcphy_cio_pds_on(atcphy); + if (ret) + return ret; + if (!atcphy_cio_idle(atcphy)) { + dev_warn(atcphy->dev, "PHY not idle (power control %#x), USB4 refused\n", + core_read32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL))); + atcphy_cio_pds_off(atcphy); + return -EBUSY; + } + atcphy->cio_powered = true; + ret = atcphy_configure(atcphy, mode); + if (ret) { + dev_err(atcphy->dev, "CIO mode failed: %d\n", ret); + atcphy_cio_stop(atcphy); + return ret; + } + dev_dbg(atcphy->dev, "CIO mode on, %s\n", atcphy->swap_lanes ? "reversed" : "normal"); + return 0; +} + +/* USB4 asks for CIO mode; every other state leaves the PHY to its other users. */ +static enum atcphy_mode atcphy_cio_target_mode(const struct typec_mux_state *state) +{ + const struct enter_usb_data *data = state->data; + + if (state->alt && state->alt->svid == USB_TYPEC_TBT_SID) + return APPLE_ATCPHY_MODE_TBT; + if (!state->alt && state->mode == TYPEC_MODE_USB4 && data && + FIELD_GET(EUDO_USB_MODE_MASK, data->eudo) == EUDO_USB_MODE_USB4) + return APPLE_ATCPHY_MODE_USB4; + return APPLE_ATCPHY_MODE_OFF; +} + +/* + * The Type-C port driver sets the mux before it starts the USB4 router and + * after it stops it, so CIO mode comes up before the router starts and goes + * down after it stopped. + */ +static int atcphy_cio_mux_set(struct typec_mux_dev *mux, struct typec_mux_state *state) +{ + struct apple_atcphy *atcphy = typec_mux_get_drvdata(mux); + enum atcphy_mode mode = atcphy_cio_target_mode(state); + int ret; + + guard(mutex)(&atcphy->lock); + if (atcphy->cio_powered) { + if (atcphy->mode == mode && !atcphy->mode_dirty) + return 0; + ret = atcphy_cio_stop(atcphy); + if (ret) + return ret; + } + if (mode == APPLE_ATCPHY_MODE_OFF) + return 0; + return atcphy_cio_start(atcphy, mode); +} + +/* The display driver takes the PHY of a CIO-only port, see above. */ +static int atcphy_cio_dp_power_on(struct phy *phy) +{ + struct apple_atcphy *atcphy = phy_get_drvdata(phy); + int ret; + + guard(mutex)(&atcphy->lock); + if (atcphy->display_owned) + return 0; + if (atcphy->cio_powered) + return -EBUSY; + ret = atcphy_cio_pds_on(atcphy); + if (!ret) + atcphy->display_owned = true; + return ret; +} + +static int atcphy_cio_dp_power_off(struct phy *phy) +{ + struct apple_atcphy *atcphy = phy_get_drvdata(phy); + + guard(mutex)(&atcphy->lock); + if (atcphy->display_owned) + atcphy_cio_pds_off(atcphy); + atcphy->display_owned = false; + return 0; +} + +static const struct phy_ops apple_atc_cio_dp_phy_ops = { + .owner = THIS_MODULE, + .power_on = atcphy_cio_dp_power_on, + .power_off = atcphy_cio_dp_power_off, +}; + static struct phy *atcphy_xlate(struct device *dev, const struct of_phandle_args *args) { struct apple_atcphy *atcphy = dev_get_drvdata(dev); @@ -5206,7 +5823,7 @@ static struct phy *atcphy_xlate(struct device *dev, const struct of_phandle_args default: return ERR_PTR(-ENODEV); } - /* A DisplayPort-only or USB2-only instance omits the other PHYs. */ + /* A DisplayPort-, USB2- or USB3-only instance omits the other PHYs. */ return phy ?: ERR_PTR(-ENODEV); } @@ -5217,18 +5834,22 @@ static int atcphy_probe_phy(struct apple_atcphy *atcphy) const struct phy_ops *ops; } phys[] = { { &atcphy->phys.usb2, &apple_atc_usb2_phy_ops }, - { &atcphy->phys.usb3, &apple_atc_usb3_phy_ops }, - { &atcphy->phys.dp, &apple_atc_dp_phy_ops }, + { &atcphy->phys.usb3, atcphy->fixed_usb3 ? &apple_atc_fixed_usb3_phy_ops : + &apple_atc_usb3_phy_ops }, + { &atcphy->phys.dp, atcphy->cio_only ? &apple_atc_cio_dp_phy_ops : + &apple_atc_dp_phy_ops }, }; /* * A T8132 PHY with its USB3/USB4 banks gets a DP PHY for DisplayPort * tunnels only (see atcphy_dpphy_set_mode_t8132()); creating it does - * not touch the hardware. + * not touch the hardware. A fixed-USB3 PHY gets its USB3 PHY only, a + * CIO-only PHY the DP PHY through which the display driver takes it. */ for (int i = 0; i < ARRAY_SIZE(phys); i++) { - if ((atcphy->dp_only && phys[i].phy != &atcphy->phys.dp) || - (atcphy_usb2_only(atcphy) && i != 0)) + if (((atcphy->dp_only || atcphy->cio_only) && phys[i].phy != &atcphy->phys.dp) || + (atcphy_usb2_only(atcphy) && i != 0) || + (atcphy->fixed_usb3 && phys[i].phy != &atcphy->phys.usb3)) continue; *phys[i].phy = devm_phy_create(atcphy->dev, NULL, phys[i].ops); if (IS_ERR(*phys[i].phy)) @@ -5772,10 +6393,24 @@ static enum atcphy_mode atcphy_typec_target_mode(struct apple_atcphy *atcphy, * its USB on the other wires: USB2 next to four DP lanes (pin * assignments C and E), USB3 next to two (D). Serve that USB rather * than refuse the mode, which would leave the port without USB at all. + * + * The same goes for USB4 and Thunderbolt on a port without the CIO + * calibration, such as those of the Mac mini (J773g). Its port + * controller enters USB4 or Thunderbolt 3 by itself with a USB4 dock + * or another Mac, and USB 2.0 on D+/D- does not depend on that link. + * Do this first, so that the DisplayPort fallback below starts from + * the mode actually served rather than putting USB4 back. */ if (atcphy->hw->gen == ATCPHY_GENERATION_T8132) { - enum atcphy_mode usb_mode = target_mode; + enum atcphy_mode usb_mode; + if (atcphy_mode_is_cio(target_mode) && !atcphy->cio_tunables) { + dev_info(atcphy->dev, + "USB4/Thunderbolt is not available on this port: serving its USB2 only\n"); + target_mode = APPLE_ATCPHY_MODE_USB2; + } + + usb_mode = target_mode; /* 4-lane DP stays DP only on a port wired for DP alt mode */ if (target_mode == APPLE_ATCPHY_MODE_DP && !atcphy_t8132_dp_on(atcphy)) usb_mode = APPLE_ATCPHY_MODE_USB2; @@ -5823,6 +6458,8 @@ static enum atcphy_mode atcphy_typec_target_mode(struct apple_atcphy *atcphy, */ static bool atcphy_mux_in_mode(const struct apple_atcphy *atcphy, enum atcphy_mode target_mode) { + if (atcphy->t8132_device) + target_mode = atcphy_t8132_device_mode(target_mode); if (atcphy->mode != target_mode || atcphy->mode_dirty || atcphy->t8103_dummy_pending || atcphy->t8103_usb3_retry) return false; @@ -5907,9 +6544,12 @@ static int atcphy_mux_check(const struct apple_atcphy *atcphy, enum atcphy_mode static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode target_mode) { + enum atcphy_mode requested_mode = target_mode; int ret; lockdep_assert_held(&atcphy->lock); + if (atcphy->t8132_device) + target_mode = atcphy_t8132_device_mode(target_mode); if (atcphy->t8103_dummy_pending) { ret = atcphy_park_live_t8103_pipehandler(atcphy); if (ret) @@ -5917,7 +6557,7 @@ static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode targe } if (atcphy->mode == target_mode && !atcphy->mode_dirty) { - atcphy->typec_mode = target_mode; + atcphy->typec_mode = requested_mode; /* A canceled lane change owes the old USB3 backend its reconnect. */ if (atcphy->t8103_usb3_retry) { if (atcphy_pipe_state_for(atcphy, target_mode) == @@ -5947,7 +6587,7 @@ static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode targe ret = atcphy_mux_check(atcphy, target_mode); if (ret) return ret; - atcphy->typec_mode = target_mode; + atcphy->typec_mode = requested_mode; if (atcphy->fixed_usb2) { enum atcphy_pipehandler_state pipe_state; @@ -6069,7 +6709,8 @@ static int atcphy_mux_update_to(struct apple_atcphy *atcphy, enum atcphy_mode ta return 0; } /* Turn down a mode the PHY cannot run before USB3 goes down for it. */ - ret = atcphy_mux_check(atcphy, target_mode); + ret = atcphy_mux_check(atcphy, atcphy->t8132_device ? + atcphy_t8132_device_mode(target_mode) : target_mode); if (ret) return ret; in_mode = atcphy_mux_in_mode(atcphy, target_mode); @@ -6194,9 +6835,10 @@ static int atcphy_probe_mux(struct apple_atcphy *atcphy) struct typec_mux_desc mux_desc = { .drvdata = atcphy, .fwnode = atcphy->dev->fwnode, - .set = atcphy_mux_set, + .set = atcphy->cio_only ? atcphy_cio_mux_set : atcphy_mux_set, .safe_after_role = !atcphy->fixed_usb2, - .transient_timeouts = atcphy_mux_transient_timeouts(atcphy), + /* A CIO-only PHY times out while the display driver has it. */ + .transient_timeouts = atcphy->cio_only || atcphy_mux_transient_timeouts(atcphy), }; mux = typec_mux_register(atcphy->dev, &mux_desc); @@ -6220,8 +6862,12 @@ static int atcphy_load_t8140_dp(struct apple_atcphy *atcphy) { "apple,tunable-dp-common-post", atcphy->res.core, &atcphy->tunables.dp_common_post }, }; - if (!of_machine_is_compatible("apple,j700")) - return -EOPNOTSUPP; + + /* + * Only the PHY's compatible (has_t8140_dp) and the bootloader's DT + * data select this bundle. A node without the lists fails below, the + * caller warns, and dp_tunables stays false. + */ for (unsigned int i = 0; i < ARRAY_SIZE(lists); i++) { struct property *property = of_find_property(atcphy->np, lists[i].name, NULL); @@ -6412,6 +7058,23 @@ static int atcphy_load_tunables(struct apple_atcphy *atcphy) bool lane_dp = tunables[i].tunable == &atcphy->tunables.lane_dp[0] || tunables[i].tunable == &atcphy->tunables.lane_dp[1]; + /* a fixed-USB3 port runs USB3 on lane 0 alone and has no axi2af window */ + if (atcphy->fixed_usb3 && + tunables[i].tunable != &atcphy->tunables.common[0] && + tunables[i].tunable != &atcphy->tunables.common[1] && + tunables[i].tunable != &atcphy->tunables.lane_usb3[0]) { + *tunables[i].tunable = NULL; + continue; + } + /* a CIO-only port has its common and CIO lane tunables alone */ + if (atcphy->cio_only && + tunables[i].tunable != &atcphy->tunables.common[0] && + tunables[i].tunable != &atcphy->tunables.common[1] && + tunables[i].tunable != &atcphy->tunables.lane_usb4[0] && + tunables[i].tunable != &atcphy->tunables.lane_usb4[1]) { + *tunables[i].tunable = NULL; + continue; + } if (!atcphy->hw->has_usb4 && (tunables[i].tunable == &atcphy->tunables.lane_usb4[0] || tunables[i].tunable == &atcphy->tunables.lane_usb4[1])) { @@ -6450,8 +7113,9 @@ static int atcphy_load_tunables(struct apple_atcphy *atcphy) tunables[i].dt_name, PTR_ERR(tunable)); return PTR_ERR(tunable); } - /* The common-a tunables do not exist on this generation */ - if (tunables[i].tunable != &atcphy->tunables.common[0]) + /* T8122 has no common-a tunables; T8152's calibrate the lanes too */ + if (tunables[i].tunable != &atcphy->tunables.common[0] || + atcphy->hw->gen == ATCPHY_GENERATION_T8152) ss_missing = true; if (tunables[i].tunable == &atcphy->tunables.axi2af || tunables[i].tunable == &atcphy->tunables.common[1]) @@ -6516,6 +7180,31 @@ static int atcphy_map_resources(struct platform_device *pdev, struct apple_atcph struct resource *res; void __iomem *addr; + /* + * A fixed-USB3 PHY has its core and PIPE windows only, a CIO-only PHY its + * core window. On T8152 the core window also holds the USB controller's + * DARTs, and the display driver maps it too, so it is mapped without + * claiming it. + */ + if (atcphy->fixed_usb3 || atcphy->cio_only) { + res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "core"); + if (!res) + return dev_err_probe(atcphy->dev, -EINVAL, "Missing core regs\n"); + atcphy->regs.core = devm_ioremap(&pdev->dev, res->start, resource_size(res)); + if (!atcphy->regs.core) + return -ENOMEM; + atcphy->res.core = res; + if (atcphy->cio_only) + return 0; + + addr = devm_platform_ioremap_resource_byname(pdev, "pipehandler"); + if (IS_ERR(addr)) + return dev_err_probe(atcphy->dev, PTR_ERR(addr), + "Unable to map pipehandler regs\n"); + atcphy->regs.pipehandler = addr; + return 0; + } + if (atcphy->hw->gen == ATCPHY_GENERATION_T8132 && platform_get_resource_byname(pdev, IORESOURCE_MEM, "common-config")) { static const char * const names[] = { @@ -6743,6 +7432,92 @@ static int atcphy_probe_finalize_dp_only(struct apple_atcphy *atcphy) return 0; } +/* + * A fixed-USB3 port: the bootloader hands its controller over running, with + * the controller's reset and its USB2 side its own, and no Type-C mux sits in + * front of the lanes, so there is no reset controller, mux or switch to + * register. Take the PHY from the state the bootloader left it in to USB3; the + * PIPE follows when the controller powers its USB3 PHY on, which also tries + * again if this fails, see atcphy_usb3_power_on(). + */ +static int atcphy_probe_finalize_fixed_usb3(struct apple_atcphy *atcphy) +{ + int ret; + + lockdep_assert_held(&atcphy->lock); + + atcphy_power_off(atcphy); + atcphy_setup_pipehandler(atcphy); + ret = atcphy_configure(atcphy, APPLE_ATCPHY_MODE_USB3); + if (ret) + dev_warn(atcphy->dev, "USB3 not up yet: %d\n", ret); + + ret = atcphy_probe_phy(atcphy); + if (ret) { + atcphy_configure(atcphy, APPLE_ATCPHY_MODE_OFF); + return dev_err_probe(atcphy->dev, ret, "Probing phy failed"); + } + return 0; +} + +/* Let go of the PHY of a CIO-only port on unbind, see atcphy_cio_mux_set(). */ +static void atcphy_cio_release(void *data) +{ + struct apple_atcphy *atcphy = data; + + guard(mutex)(&atcphy->lock); + if (atcphy->cio_powered) + atcphy_cio_stop(atcphy); + if (atcphy->display_owned) + atcphy_cio_pds_off(atcphy); + atcphy->display_owned = false; +} + +/* + * A CIO-only port: probe leaves the hardware as it is. A display the + * bootloader brought up on the port has all of the PHY's power domains on, + * and the PHY is not idle: hold the domains for the display driver, which + * takes it over, until its DP PHY goes off. Otherwise the domains are left to + * their power domain driver. Then register the mux, the orientation switch + * and the DP PHY. + */ +static int atcphy_probe_finalize_cio_only(struct apple_atcphy *atcphy) +{ + struct dev_pm_domain_list *pds = atcphy->cio_pds; + bool all_on = true; + int ret; + + lockdep_assert_held(&atcphy->lock); + + ret = devm_add_action(atcphy->dev, atcphy_cio_release, atcphy); + if (ret) + return ret; + for (unsigned int i = 0; i < pds->num_pds; i++) + all_on &= dev_pm_genpd_is_on(pds->pd_devs[i]); + if (all_on) { + ret = atcphy_cio_pds_on(atcphy); + if (ret) + return dev_err_probe(atcphy->dev, ret, "Failed to power the PHY\n"); + if (atcphy_cio_idle(atcphy)) { + atcphy_cio_pds_off(atcphy); + } else { + atcphy->display_owned = true; + dev_info(atcphy->dev, "PHY in use at boot, held for the display driver\n"); + } + } + + ret = atcphy_probe_mux(atcphy); + if (ret) + return dev_err_probe(atcphy->dev, ret, "Probing mux failed\n"); + ret = atcphy_probe_switch(atcphy); + if (ret) + return dev_err_probe(atcphy->dev, ret, "Probing switch failed\n"); + ret = atcphy_probe_phy(atcphy); + if (ret) + return dev_err_probe(atcphy->dev, ret, "Probing phy failed\n"); + return 0; +} + static int atcphy_probe_finalize(struct apple_atcphy *atcphy) { int ret; @@ -6751,6 +7526,10 @@ static int atcphy_probe_finalize(struct apple_atcphy *atcphy) if (atcphy->dp_only) return atcphy_probe_finalize_dp_only(atcphy); + if (atcphy->fixed_usb3) + return atcphy_probe_finalize_fixed_usb3(atcphy); + if (atcphy->cio_only) + return atcphy_probe_finalize_cio_only(atcphy); /* Reset dwc3 on probe, let dwc3 (consumer) deassert it */ _atcphy_dwc3_reset_assert(atcphy); @@ -6882,6 +7661,37 @@ static bool atcphy_has_t8103_usb3_workaround(const struct atcphy_hw *hw, of_device_is_compatible(root, "apple,t8103"); } +/* + * The driver core attaches a single power domain. A fixed-USB3 PHY may list + * several, like T8152's ATC power states and PSD service: hold them all on + * while it is bound, powered up in the order they are listed. + */ +static int atcphy_probe_power_domains(struct apple_atcphy *atcphy) +{ + struct dev_pm_domain_attach_data pd_data = { .pd_flags = PD_FLAG_DEV_LINK_ON }; + struct dev_pm_domain_list *pd_list; + int ret; + + /* + * A CIO-only PHY powers its domains only while it runs CIO mode or the + * display driver has it, see atcphy_cio_mux_set(). + */ + if (atcphy->cio_only) { + pd_data.pd_flags = PD_FLAG_NO_DEV_LINK; + ret = devm_pm_domain_attach_list(atcphy->dev, &pd_data, &atcphy->cio_pds); + if (ret <= 0) + return dev_err_probe(atcphy->dev, ret ?: -EINVAL, + "Failed to attach power domains\n"); + return 0; + } + if (!atcphy->fixed_usb3 || atcphy->dev->pm_domain) + return 0; + ret = devm_pm_domain_attach_list(atcphy->dev, &pd_data, &pd_list); + if (ret < 0) + return dev_err_probe(atcphy->dev, ret, "Failed to attach power domains\n"); + return 0; +} + static void atcphy_sleep_finish_work(struct work_struct *work); static int atcphy_probe(struct platform_device *pdev) @@ -6904,6 +7714,8 @@ static int atcphy_probe(struct platform_device *pdev) atcphy->np = dev->of_node; atcphy->t8132_dp_alt = atcphy->hw->gen == ATCPHY_GENERATION_T8132 && of_property_read_bool(dev->of_node, "apple,dp-alt-mode"); + atcphy->fixed_usb3 = of_property_read_bool(dev->of_node, "apple,fixed-usb3"); + atcphy->cio_only = atcphy->hw->typec_cio_only && !atcphy->fixed_usb3; apple_atc_tunnel_wiring(atcphy); mutex_init(&atcphy->lock); platform_set_drvdata(pdev, atcphy); @@ -6912,6 +7724,9 @@ static int atcphy_probe(struct platform_device *pdev) if (ret) return ret; ret = atcphy_load_tunables(atcphy); + if (ret) + return ret; + ret = atcphy_probe_power_domains(atcphy); if (ret) return ret; @@ -7399,6 +8214,7 @@ static int atcphy_suspend_noirq(struct device *dev) static void atcphy_sleep_lost_common(struct apple_atcphy *atcphy) { if ((!atcphy->hw->has_t8140_dp && + !atcphy->hw->sleep_drops_common && !of_device_is_compatible(atcphy->np, "apple,t8142-atcphy")) || !atcphy->hw->restore_after_pd_off || !pm_resume_via_firmware()) return; @@ -7928,6 +8744,9 @@ static const struct atcphy_hw atcphy_hw_t8103 = { .pipe_mux_data = PIPEHANDLER_MUX_CTRL_DATA_T8103, .has_usb4 = true, .park_pipe_unlocked = true, + .park_dummy_phy = true, + .restore_after_pd_off = true, + .sleep_drops_common = true, }; static const struct atcphy_hw atcphy_hw_t8122 = { @@ -7983,12 +8802,52 @@ static const struct atcphy_hw atcphy_hw_t8142 = { .clear_boot_hold = true, }; +/* + * T8152 as the USB3 PHY of a fixed-USB3 port, or as a Type-C port's PHY in CIO + * mode alone (see atcphy_cio_mux_set()): no DisplayPort mode, no lane mode + * register and nothing to wake after the tunables. A fixed-USB3 port does not + * follow its power domains: the controller's power-off and power-on of the + * PHY, as around a system sleep, take it down and up again. + */ +static const struct atcphy_hw atcphy_hw_t8152 = { + .gen = ATCPHY_GENERATION_T8152, + .aciophy_crossbar = ACIOPHY_CROSSBAR_T8103, + .cfg_offset = ATCPHY_T8152_CFG_OFFSET, + .sync_reset = ATCPHY_T8152_SYNC_RESET, + .lane_swap = ATCPHY_T8152_MISC_LANE_SWAP, + .pipe_mux_clk = PIPEHANDLER_MUX_CTRL_CLK_T8142, + .pipe_mux_data = PIPEHANDLER_MUX_CTRL_DATA_T8142, + .has_usb4 = true, + .park_dummy_phy = true, + .clear_boot_hold = true, + /* + * The bootloader copies the tunables from the Mac's own ADT. Without + * them (an older loader) the PHY still probes, so that its consumers do + * not wait for it, and refuses every mode but USB2. + */ + .optional_tunables = true, + /* + * With the controller out of reset, the J873g front port's PIPE handler + * left the lock unacknowledged for 150 ms in both directions, while the + * PIPE moved to USB3 and back to the dummy PHY under the request. + */ + .pipe_lock_unacked = true, + /* + * Its Type-C ports run CIO mode alone; a reversed plug takes the + * swapped crossbar and the lane swap, with which the J873g's rear ports + * trained USB4 at 2 x 20 Gb/s. + */ + .typec_cio_only = true, + .cio_lane_swap = true, +}; + static const struct of_device_id atcphy_match[] = { { .compatible = "apple,t8103-atcphy", .data = &atcphy_hw_t8103 }, { .compatible = "apple,t8122-atcphy", .data = &atcphy_hw_t8122 }, { .compatible = "apple,t8132-atcphy", .data = &atcphy_hw_t8132 }, { .compatible = "apple,t8142-atcphy", .data = &atcphy_hw_t8142 }, { .compatible = "apple,t8140-atcphy", .data = &atcphy_hw_t8140 }, + { .compatible = "apple,t8152-atcphy", .data = &atcphy_hw_t8152 }, {}, }; MODULE_DEVICE_TABLE(of, atcphy_match); diff --git a/drivers/phy/apple/dptx.c b/drivers/phy/apple/dptx.c index f191efe4c62866..7405b7d1c7ad0f 100644 --- a/drivers/phy/apple/dptx.c +++ b/drivers/phy/apple/dptx.c @@ -23,6 +23,7 @@ #include #include #include +#include #include #include @@ -75,6 +76,8 @@ struct apple_dptx_phy { u32 source_select; bool pclkdrv_select; bool active; + /* T6050: the domain reference taken at probe, until the first mode switch */ + bool boot_hold; u32 rate; /* Mbit/s; 0: none programmed */ struct phy *phy_dp; @@ -932,14 +935,55 @@ static int dptx_phy_set_mode(struct phy *phy, enum phy_mode mode, int submode) struct apple_dptx_phy *dptx_phy = phy_get_drvdata(phy); if (dptx_phy->hw.type == DPTX_PHY_T6050) { - int ret = -EINVAL; + struct device *dev = dptx_phy->dev; + bool was_active, boot_hold; + int pm_ret, ret = -EINVAL; + + if (mode != PHY_MODE_DP && mode != PHY_MODE_INVALID) + return -EINVAL; mutex_lock(&dptx_phy->lock); - if (mode == PHY_MODE_INVALID) + /* An active link holds the PHY's power domain, see dptx_phy_probe(). */ + if (mode == PHY_MODE_DP && dptx_phy->active) { + mutex_unlock(&dptx_phy->lock); + return 0; + } + if (mode == PHY_MODE_DP) { + ret = phy_pm_runtime_get_sync(phy); + if (ret < 0) { + mutex_unlock(&dptx_phy->lock); + return ret; + } + } + was_active = dptx_phy->active; + if (mode == PHY_MODE_INVALID) { ret = t6050_deactivate(dptx_phy); - else if (mode == PHY_MODE_DP) - ret = dptx_phy->active ? 0 : t6050_activate(dptx_phy); + } else if (mode == PHY_MODE_DP) { + ret = t6050_activate(dptx_phy); + if (ret) + t6050_deactivate(dptx_phy); + } + boot_hold = dptx_phy->boot_hold; + dptx_phy->boot_hold = false; mutex_unlock(&dptx_phy->lock); + + /* + * t6050_deactivate() powers the blocks down and clears ->active + * even when the PLL power-down reports an error, so an active + * link's reference goes with it whatever it returned. A put that + * fails after the PHY is already down is only reported: failing + * the mode switch would leave the PHY core's mode at DP. + */ + pm_ret = 0; + if (mode == PHY_MODE_DP && ret) + pm_ret = phy_pm_runtime_put_sync(phy); + else if (mode == PHY_MODE_INVALID && was_active) + pm_ret = phy_pm_runtime_put_sync(phy); + if (pm_ret < 0) + dev_warn(dev, "runtime PM put failed: %d\n", pm_ret); + /* The DCP owns the link from its first mode switch on. */ + if (boot_hold) + pm_runtime_put(dev); return ret; } @@ -1045,10 +1089,25 @@ static const struct phy_ops apple_atc_dp_phy_ops = { .set_mode = dptx_phy_set_mode, }; +static void dptx_phy_drop_boot_hold(void *data) +{ + struct apple_dptx_phy *dptx_phy = data; + bool drop; + + mutex_lock(&dptx_phy->lock); + drop = dptx_phy->boot_hold; + dptx_phy->boot_hold = false; + mutex_unlock(&dptx_phy->lock); + + if (drop) + pm_runtime_put_noidle(dptx_phy->dev); +} + static int dptx_phy_probe(struct platform_device *pdev) { struct apple_dptx_phy *dptx_phy; struct device *dev = &pdev->dev; + int ret; dptx_phy = devm_kzalloc(dev, sizeof(*dptx_phy), GFP_KERNEL); if (!dptx_phy) @@ -1070,6 +1129,38 @@ static int dptx_phy_probe(struct platform_device *pdev) if (IS_ERR(dptx_phy->regs.dptx)) return PTR_ERR(dptx_phy->regs.dptx); + /* + * The T6050 PHY powers its blocks up and down with the link + * (t6050_activate(), t6050_deactivate()); runtime PM lets its power + * domain follow. + */ + if (dptx_phy->hw.type == DPTX_PHY_T6050) { + /* + * The boot loader may leave an HDMI link up for simplefb, and + * nothing else holds the domain before the DCP's first mode + * switch, which can come late (or never, if the DCP fails). + * Start active with a reference which that switch drops, so + * genpd's unused power-off cannot take the domain from a live + * link before then. + */ + pm_runtime_get_noresume(dev); + ret = pm_runtime_set_active(dev); + if (ret) { + pm_runtime_put_noidle(dev); + return ret; + } + ret = devm_pm_runtime_enable(dev); + if (ret) { + pm_runtime_put_noidle(dev); + return ret; + } + dptx_phy->boot_hold = true; + ret = devm_add_action_or_reset(dev, dptx_phy_drop_boot_hold, + dptx_phy); + if (ret) + return ret; + } + /* create phy */ dptx_phy->phy_dp = devm_phy_create(dptx_phy->dev, NULL, &apple_atc_dp_phy_ops); diff --git a/drivers/phy/apple/t6040-usb2.c b/drivers/phy/apple/t6040-usb2.c index 50d82116aac2d1..66e41fe9ab252b 100644 --- a/drivers/phy/apple/t6040-usb2.c +++ b/drivers/phy/apple/t6040-usb2.c @@ -44,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -293,6 +294,9 @@ struct t6040_usb2_phy { bool usb3_lent; /* DP mode took the lanes of this Type-C port */ bool pipe_switched; /* the controller's PIPE runs on this PHY */ bool cio_up; /* the lanes run USB4/Thunderbolt */ + u8 tun_rate[2]; /* DP tunnel link rate per DP IN adapter, 0 = off */ + bool tun_pre; /* switch 1 is held for DP IN 1 alone */ + bool tun_pll; /* AUSPLL programmed for DP tunnels */ /* DisplayPort; dp_ok is false when the DT lacks a DP route */ struct phy *dp; @@ -1769,11 +1773,14 @@ static int t6040_cio_up_locked(struct t6040_usb2_phy *tphy) return ret; } +static void t6040_tun_stop_all_locked(struct t6040_usb2_phy *tphy); + static void t6040_cio_down_locked(struct t6040_usb2_phy *tphy) { lockdep_assert_held(&tphy->lock); if (!tphy->cio_up) return; + t6040_tun_stop_all_locked(tphy); t6040_phy_tx_cmn_down(tphy); t6040_cio_rx_down(tphy); fsleep(200); @@ -1879,6 +1886,8 @@ static int t6040_dp_validate(struct phy *phy, enum phy_mode mode, int submode, return 0; } +static int t6040_tun_rate_locked(struct t6040_usb2_phy *tphy, unsigned int dpin, u8 rate); + static int t6040_dp_configure(struct phy *phy, union phy_configure_opts *opts_) { struct t6040_usb2_phy *tphy = phy_get_drvdata(phy); @@ -1887,6 +1896,13 @@ static int t6040_dp_configure(struct phy *phy, union phy_configure_opts *opts_) int ret; guard(mutex)(&tphy->lock); + /* A DP tunnel's pixel clock, PHY in CIO: see "DP tunnels" below. */ + if (opts->set_tunnel_rate) { + if (opts->set_rate || opts->set_lanes || opts->set_voltages || + opts->tunnel_dpin > 1) + return -EINVAL; + return t6040_tun_rate_locked(tphy, opts->tunnel_dpin, opts->tunnel_rate); + } if (!tphy->dp_up) return -EINVAL; if ((opts->set_lanes || opts->set_voltages) && @@ -1949,6 +1965,298 @@ static const struct phy_ops t6040_dp_phy_ops = { .set_mode = t6040_dp_set_mode, }; +/* ---- DP tunnels: the pixel clocks of the router's DP IN adapters (PHY in CIO) ---- + * + * The DP 1.4 tunnel's init, update and shutdown and the DP clock + * configuration: one fixed AUSPLL frequency feeds the DPTX pixel clocks, + * whose select field divides it per link rate. DP IN adapter 0 is taken to + * use PCLK1 and clock switch 1, adapter 1 PCLK2 and switch 2 (the PHY does + * not choose: the index is the display controller's). Driven only by + * appledrm, through phy_configure() with the DP options' set_tunnel_rate + * (t6040_dp_configure()), and only while the PHY is in CIO. + */ +#define T6040_CORE_RCAL1 0x804 /* AUS40CMN_DIG RCAL1 */ +#define T6040_CORE_RCAL1_DONE BIT(0) +#define T6040_CORE_AUSPLL_CMD 0x3000 /* AUSPLL_TOP_APB_CMD_CMDOVERRIDE */ +#define T6040_CORE_AUSPLL_CMD_REQ BIT(0) +#define T6040_CORE_AUSPLL_CMD_ACK BIT(1) +#define T6040_CORE_AUSPLL_FREQDESC_A 0x3080 +#define T6040_CORE_AUSPLL_FREQDESC_B 0x3084 +#define T6040_CORE_AUSPLL_FREQDESC_C 0x3088 +#define T6040_CORE_AUSPLL_CLKOUT_MASTER 0x3200 +#define T6040_CORE_AUSPLL_CLKOUT_DIV 0x3208 +#define T6040_CORE_AUSPLL_BGR 0x3218 +#define T6040_CORE_AUSPLL_FREQINIT_1 0x3234 +#define T6040_CORE_TX_DP_CTRL0 0x7000 +#define T6040_CORE_TX_DP_CTRL0_ENABLES GENMASK(18, 16) +#define T6040_CORE_DP_PCLK_STATUS 0x7034 +#define T6040_CORE_DP_PCLK_STATUS_LOCK BIT(3) /* AUSPLL_LOCK */ + +static const struct t6040_tun_pclk { + u8 sel_shift; /* TX_DP_CTRL0 select field */ + u32 en; /* TX_DP_CTRL0 enable */ + u32 sw_mask, sw_gate, sw_on; /* clock switch: cleared, set, status when on */ + u32 req[2], req_stat[2], sw_off; /* PMGR requests, their status, cleared at off */ +} t6040_tun_pclk[2] = { + { 4, BIT(16), 0x473, 0x10, BIT(0), { 0x20, 0x40 }, { BIT(1), BIT(2) }, 0x403 }, + { 8, BIT(17), 0xb8c, 0x80, BIT(3), { 0x100, 0x200 }, { BIT(4), BIT(5) }, 0x80c }, +}; + +/* The pixel clock select: RBR, HBR, HBR2, HBR3; UHBR is not tunnelled on this path. */ +static int t6040_tun_select(u8 rate) +{ + switch (rate) { + case 0x06: + return 4; + case 0x0a: + return 3; + case 0x14: + return 1; + case 0x1e: + return 0; + default: + return -EINVAL; + } +} + +/* DP IN 1 runs on PCLK2 and needs PCLK1 as well: without it its video stops. */ +static u32 t6040_tun_enables(struct t6040_usb2_phy *tphy) +{ + return ((tphy->tun_rate[0] || tphy->tun_rate[1]) ? t6040_tun_pclk[0].en : 0) | + (tphy->tun_rate[1] ? t6040_tun_pclk[1].en : 0); +} + +/* AUSPLL_TOP command override: request @req with the toggle protocol, then wait for @ack. */ +static int t6040_tun_pll_cmd(struct t6040_usb2_phy *tphy, u32 val, bool ack_set) +{ + void __iomem *cmd = t6040_core(tphy) + T6040_CORE_AUSPLL_CMD; + u32 v; + + writel((readl(cmd) & 0xe0000006) | val, cmd); + return readl_poll_timeout(cmd, v, !!(v & T6040_CORE_AUSPLL_CMD_ACK) == ack_set, + 10, 500 * USEC_PER_MSEC); +} + +/* The DP 1.4 tunnel shutdown: pixel clocks off, AUSPLL released. */ +static void t6040_tun_pll_stop(struct t6040_usb2_phy *tphy) +{ + void __iomem *core = t6040_core(tphy); + bool ack = readl(core + T6040_CORE_AUSPLL_CMD) & T6040_CORE_AUSPLL_CMD_ACK; + u32 v; + + t6040_usb2_clear32(core + T6040_CORE_TX_DP_CTRL0, T6040_CORE_TX_DP_CTRL0_ENABLES); + t6040_usb2_clear32(core + T6040_CORE_TX_DP_CTRL0, 0xc); + if (t6040_tun_pll_cmd(tphy, (ack ? 0 : T6040_CORE_AUSPLL_CMD_REQ) | 0x10000000, !ack) || + t6040_tun_pll_cmd(tphy, (ack ? T6040_CORE_AUSPLL_CMD_REQ : 0) | 0x10000018, ack) || + readl_poll_timeout(core + T6040_CORE_DP_PCLK_STATUS, v, + !(v & T6040_CORE_DP_PCLK_STATUS_LOCK), 10, 500 * USEC_PER_MSEC)) + dev_warn(tphy->dev, "DP tunnel: AUSPLL release timed out (cmd %#x, pclk status %#x)\n", + readl(core + T6040_CORE_AUSPLL_CMD), + readl(core + T6040_CORE_DP_PCLK_STATUS)); + /* Both outputs the start set: a stale 0x800 reads as "in use" next time. */ + t6040_usb2_clear32(core + T6040_CORE_AUSPLL_CLKOUT_MASTER, 0x808); + tphy->tun_pll = false; +} + +/* The common block's init, then the fixed AUSPLL program of the DP 1.4 tunnel init. */ +static int t6040_tun_pll_start(struct t6040_usb2_phy *tphy) +{ + void __iomem *core = t6040_core(tphy); + bool ack; + u32 v; + + if ((readl(core + T6040_CORE_AUSPLL_CLKOUT_MASTER) & 0x808) || + (readl(core + T6040_CORE_AUSPLL_CMD) & T6040_CORE_AUSPLL_CMD_REQ)) { + dev_warn(tphy->dev, "DP tunnel: AUSPLL already in use (master %#x, cmd %#x)\n", + readl(core + T6040_CORE_AUSPLL_CLKOUT_MASTER), + readl(core + T6040_CORE_AUSPLL_CMD)); + return -EBUSY; + } + t6040_usb2_clear32(core + T6040_CORE_TX_DP_CTRL0, T6040_CORE_TX_DP_CTRL0_ENABLES); + + t6040_usb2_set32(core + T6040_CORE_CMN_OVRD, 0x4); + t6040_usb2_set32(core + T6040_CORE_CMN_OVRD, 0x8); + udelay(1); + t6040_usb2_set32(core + T6040_CORE_CMN_OVRD, 0x1); + t6040_usb2_set32(core + T6040_CORE_CMN_OVRD, 0x2); + udelay(1); + t6040_usb2_clear32(core + T6040_CORE_CMN_OVRD, T6040_CORE_CMN_OVRD_CLAMP); + t6040_usb2_set32(core + T6040_CORE_CMN_OVRD, 0x20); + udelay(1); + t6040_usb2_set32(core + T6040_CORE_CMN_BIAS, T6040_CORE_CMN_BIAS_BGBIAS_EN_OV); + udelay(15); + if (readl_poll_timeout(core + T6040_CORE_RCAL1, v, v & T6040_CORE_RCAL1_DONE, 1, 100)) + dev_dbg(tphy->dev, "DP tunnel: RCAL not done (%#x)\n", v); + + t6040_usb2_clear32(core + T6040_CORE_AUSPLL_FREQINIT_1, 0x3); + writel(0x1e0e021c, core + T6040_CORE_AUSPLL_FREQDESC_A); + t6040_usb2_mask32(core + T6040_CORE_AUSPLL_FREQDESC_B, 0x0fffffff, 0); + t6040_usb2_mask32(core + T6040_CORE_AUSPLL_FREQDESC_C, 0x007fffff, 0x644a00); + t6040_usb2_mask32(core + T6040_CORE_AUSPLL_CLKOUT_DIV, 0x001f0000, 0x10000); + t6040_usb2_set32(core + T6040_CORE_AUSPLL_BGR, 0x1); + t6040_usb2_set32(core + T6040_CORE_AUSPLL_CLKOUT_MASTER, 0x808); + tphy->tun_pll = true; + + /* + * Toggle protocol, as in the stop: the request flips REQ and waits for + * ACK to follow, whichever level a PHY reset left it at. The pixel + * clock must lock either way. + */ + ack = readl(core + T6040_CORE_AUSPLL_CMD) & T6040_CORE_AUSPLL_CMD_ACK; + if (t6040_tun_pll_cmd(tphy, (ack ? 0 : T6040_CORE_AUSPLL_CMD_REQ) | 0x10000000, !ack) || + readl_poll_timeout(core + T6040_CORE_DP_PCLK_STATUS, v, + v & T6040_CORE_DP_PCLK_STATUS_LOCK, + 10, 500 * USEC_PER_MSEC) || + t6040_tun_pll_cmd(tphy, (ack ? T6040_CORE_AUSPLL_CMD_REQ : 0) | 0x10010000, ack)) { + dev_err(tphy->dev, "DP tunnel: AUSPLL did not lock (cmd %#x, pclk status %#x)\n", + readl(core + T6040_CORE_AUSPLL_CMD), + readl(core + T6040_CORE_DP_PCLK_STATUS)); + t6040_tun_pll_stop(tphy); + return -ETIMEDOUT; + } + t6040_usb2_set32(core + T6040_CORE_TX_DP_CTRL0, 0xc); + return 0; +} + +static void t6040_tun_select_field(u32 *v, const struct t6040_tun_pclk *p, int sel, bool en) +{ + if (!!(*v & p->en) != en || ((*v >> p->sel_shift) & 0xf) != sel) + *v = (*v & ~(p->en | (0xf << p->sel_shift))) | (sel << p->sel_shift); +} + +/* The DP 1.4 tunnel update for one pclk: select with its enable off, then the enables. */ +static void t6040_tun_select_write(struct t6040_usb2_phy *tphy, unsigned int dpin, int sel) +{ + void __iomem *ctrl0 = t6040_core(tphy) + T6040_CORE_TX_DP_CTRL0; + u32 v = readl(ctrl0); + + t6040_tun_select_field(&v, &t6040_tun_pclk[dpin], sel, !!tphy->tun_rate[dpin]); + /* PCLK1 is DP IN 1's prerequisite at its own rate, unless DP IN 0 runs on it. */ + if (dpin == 1 && !tphy->tun_rate[0]) + t6040_tun_select_field(&v, &t6040_tun_pclk[0], sel, true); + /* Retuning DP IN 0 must not gate PCLK1 under a running DP IN 1. */ + if (dpin == 0 && tphy->tun_rate[1]) + v |= t6040_tun_pclk[0].en; + writel(v, ctrl0); + writel((v & ~T6040_CORE_TX_DP_CTRL0_ENABLES) | t6040_tun_enables(tphy), ctrl0); +} + +/* The DP clock configuration for one DP 1.x switch: pixel-clock gate on, or off. */ +static int t6040_tun_switch(struct t6040_usb2_phy *tphy, unsigned int dpin, bool on) +{ + const struct t6040_tun_pclk *p = &t6040_tun_pclk[dpin]; + void __iomem *cfg = t6040_cfg(tphy); + unsigned int i; + u32 s; + + if (on) { + t6040_usb2_mask32(cfg + T6040_CFG_DP_CLKSWITCH_CTRL, p->sw_mask, p->sw_gate); + return readl_poll_timeout(cfg + T6040_CFG_DP_CLKSWITCH_STAT, s, s & p->sw_on, + 10, 5 * USEC_PER_MSEC); + } + t6040_usb2_set32(cfg + T6040_CFG_DP_CLKSWITCH_CTRL, p->sw_gate); + for (i = 0; i < 2; i++) { + if (!(readl(cfg + T6040_CFG_DP_CLKSWITCH_CTRL) & p->req[i])) + continue; + t6040_usb2_clear32(cfg + T6040_CFG_DP_CLKSWITCH_CTRL, p->req[i]); + if (readl_poll_timeout(cfg + T6040_CFG_DP_CLKSWITCH_STAT, s, !(s & p->req_stat[i]), + 10, 5 * USEC_PER_MSEC)) + dev_dbg(tphy->dev, "DP tunnel %u: request %#x not released (%#x)\n", + dpin, p->req[i], s); + } + t6040_usb2_clear32(cfg + T6040_CFG_DP_CLKSWITCH_CTRL, p->sw_off); + return 0; +} + +/* All tunnel clocks down, which the PHY's shutdown of mode 2 starts with. */ +static void t6040_tun_stop_all_locked(struct t6040_usb2_phy *tphy) +{ + unsigned int dpin; + + lockdep_assert_held(&tphy->lock); + if (!tphy->tun_pll) + return; + for (dpin = 0; dpin < 2; dpin++) { + if (!tphy->tun_rate[dpin]) + continue; + tphy->tun_rate[dpin] = 0; + t6040_tun_switch(tphy, dpin, false); + } + if (tphy->tun_pre) { + tphy->tun_pre = false; + t6040_tun_switch(tphy, 0, false); + } + t6040_tun_pll_stop(tphy); + dev_info(tphy->dev, "DP tunnel clocks off\n"); +} + +static int t6040_tun_rate_locked(struct t6040_usb2_phy *tphy, unsigned int dpin, u8 rate) +{ + int sel, ret; + u8 old = tphy->tun_rate[dpin]; + + lockdep_assert_held(&tphy->lock); + if (!rate) { + if (!old) + return 0; + tphy->tun_rate[dpin] = 0; + if (dpin == 0 && tphy->tun_rate[1]) { + /* DP IN 1 keeps PCLK1 and its switch, now at its own rate. */ + tphy->tun_pre = true; + t6040_tun_select_write(tphy, 1, t6040_tun_select(tphy->tun_rate[1])); + } else { + t6040_tun_switch(tphy, dpin, false); + if (dpin == 1 && tphy->tun_pre) { + tphy->tun_pre = false; + t6040_tun_switch(tphy, 0, false); + } + } + t6040_usb2_mask32(t6040_core(tphy) + T6040_CORE_TX_DP_CTRL0, + T6040_CORE_TX_DP_CTRL0_ENABLES, t6040_tun_enables(tphy)); + if (!tphy->tun_rate[!dpin]) + t6040_tun_pll_stop(tphy); + dev_dbg(tphy->dev, "DP tunnel %u off\n", dpin); + return 0; + } + sel = t6040_tun_select(rate); + if (sel < 0) + return sel; + if (!tphy->cio_up) + return -EBUSY; + if (old == rate) + return 0; + if (!tphy->tun_pll) { + ret = t6040_tun_pll_start(tphy); + if (ret) + return ret; + } + tphy->tun_rate[dpin] = rate; + t6040_tun_select_write(tphy, dpin, sel); + /* DP IN 1 alone: switch 1 passes PCLK1, its prerequisite. */ + if (dpin == 1 && !tphy->tun_rate[0] && !tphy->tun_pre) { + /* Owned before it is gated on, so a timeout below also releases it. */ + tphy->tun_pre = true; + ret = t6040_tun_switch(tphy, 0, true); + if (ret) + goto switch_failed; + } else if (dpin == 0) { + tphy->tun_pre = false; /* DP IN 0 owns switch 1 again */ + } + ret = t6040_tun_switch(tphy, dpin, true); +switch_failed: + if (ret) { + dev_err(tphy->dev, "DP tunnel %u: clock switch timed out (ctrl %#x status %#x)\n", + dpin, readl(t6040_cfg(tphy) + T6040_CFG_DP_CLKSWITCH_CTRL), + readl(t6040_cfg(tphy) + T6040_CFG_DP_CLKSWITCH_STAT)); + t6040_tun_rate_locked(tphy, dpin, 0); + return ret; + } + dev_info(tphy->dev, "DP tunnel %u: rate %#x, select %d (ctrl0 %#x, pclk status %#x)\n", + dpin, rate, sel, readl(t6040_core(tphy) + T6040_CORE_TX_DP_CTRL0), + readl(t6040_core(tphy) + T6040_CORE_DP_PCLK_STATUS)); + return 0; +} + /* ---- Type-C mode switch: the Type-C controller asks for DP on a USB-C port ---- */ static int t6040_dp_mux_set(struct typec_mux_dev *mux, struct typec_mux_state *state) @@ -2128,6 +2436,65 @@ static void t6040_rtkit_cleanup(void *data) t6040_rtkit_stop_transport(data); } +/* + * Suspend-to-idle leaves the Type-C link up: the USB4/Thunderbolt router keeps + * its own domains out of the system transition while a cable is set up, and a + * running PHY coprocessor is not stopped either. genpd would still power off + * common_dp (and with it phymxwrap) in its noirq phase under the running + * coprocessor: the link then dies after resume and the next detach finds a + * coprocessor that no longer answers (AP idle -62). Put this device on the + * awake path while its coprocessor runs, so genpd keeps the domains on + * (common_dp carries apple,sleep-wakeup-path). The decision is taken again in + * every suspend pass, dark wakes included, and once more in noirq for a + * coprocessor started after .suspend. A sleep the platform takes part in + * (firmware suspend) is left as it was. + */ +static void t6040_keep_running_cpu_awake(struct t6040_usb2_phy *tphy, bool noirq) +{ + bool running; + + if (!pm_suspend_no_platform()) + return; + + if (noirq) { + /* + * An attach or detach holding the lock may wait for a coprocessor + * reply that cannot arrive now. Its outcome is unknown: keep the + * domains on for this sleep. + */ + if (!mutex_trylock(&tphy->lock)) { + device_set_awake_path(tphy->dev); + return; + } + } else { + mutex_lock(&tphy->lock); + } + running = tphy->rtk && apple_rtkit_is_running(tphy->rtk); + mutex_unlock(&tphy->lock); + + if (running) { + device_set_awake_path(tphy->dev); + dev_dbg(tphy->dev, "PHY coprocessor running: domains kept on for s2idle\n"); + } +} + +static int t6040_usb2_suspend(struct device *dev) +{ + t6040_keep_running_cpu_awake(dev_get_drvdata(dev), false); + return 0; +} + +static int t6040_usb2_suspend_noirq(struct device *dev) +{ + t6040_keep_running_cpu_awake(dev_get_drvdata(dev), true); + return 0; +} + +static const struct dev_pm_ops t6040_usb2_pm_ops = { + .suspend = t6040_usb2_suspend, + .suspend_noirq = t6040_usb2_suspend_noirq, +}; + static void t6040_mbox_dev_put(void *data) { put_device(data); @@ -2295,6 +2662,12 @@ static int t6040_usb3_probe(struct t6040_usb2_phy *tphy, struct platform_device ret = devm_add_action_or_reset(dev, t6040_rtkit_cleanup, tphy); if (ret) return ret; + /* + * Stop the transport after verifying the mailbox so it drops its + * runtime-PM reference while the port is idle; the first attach + * starts it again in t6040_usb3_cpu_start(). + */ + t6040_rtkit_stop_transport(tphy); ret = t6040_debugfs_init(tphy); if (ret) @@ -2505,6 +2878,7 @@ static struct platform_driver t6040_usb2_driver = { .driver = { .name = "phy-apple-t6040-usb2", .of_match_table = t6040_usb2_of_match, + .pm = pm_sleep_ptr(&t6040_usb2_pm_ops), }, }; module_platform_driver(t6040_usb2_driver); diff --git a/drivers/phy/apple/usb-t6050/apple_t6050_cio_phy.h b/drivers/phy/apple/usb-t6050/apple_t6050_cio_phy.h index 4af28f8c2ccff7..0b529afca00e30 100644 --- a/drivers/phy/apple/usb-t6050/apple_t6050_cio_phy.h +++ b/drivers/phy/apple/usb-t6050/apple_t6050_cio_phy.h @@ -14,176 +14,176 @@ /* The power-up and reset release, identical to the USB recipes. */ #define APPLE_T6050_CIO_POWERUP \ - { T6050_MASK, 39, 0x0, 0x1, 0x1, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_POLL, 39, 0x4, 0x1, 0x1, 1000, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 39, 0x0, 0x2, 0x2, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_POLL, 39, 0x4, 0x2, 0x2, 1000, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 39, 0x0, 0x4, 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_POWER, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 39, 0x2c, 0x1, 0x0, 0, 0 }, \ - { T6050_POLL, 39, 0x4, 0x100, 0x0, 1000, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 39, 0x0, 0x8, 0x8, 0, 0 } + { T6050_MASK, 39, 0x0, 0x1, 0x1, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_POLL, 39, 0x4, 0x1, 0x1, 1000, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 39, 0x0, 0x2, 0x2, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_POLL, 39, 0x4, 0x2, 0x2, 1000, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 39, 0x0, 0x4, 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_POWER, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 39, 0x2c, 0x1, 0x0, 0, NULL }, \ + { T6050_POLL, 39, 0x4, 0x100, 0x0, 1000, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 39, 0x0, 0x8, 0x8, 0, NULL } /* The common tunables, then the CIO set and the CIO80 set. An absent CIO80 * tunable is skipped. */ #define APPLE_T6050_CIO_TUNABLES \ - { T6050_TUNABLE, 41, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF" }, \ - { T6050_TUNABLE, 40, 0x0, 0x0, 0x0, 0, "tunable_ATC_FABRIC" }, \ - { T6050_TUNABLE, 43, 0x0, 0x0, 0x0, 0, "tunable_ATC_COMMON_CFG" }, \ - { T6050_TUNABLE, 42, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF_LIOA" }, \ - { T6050_TUNABLE, 20, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_CFG_TX_OF_RXCLK" }, \ - { T6050_TUNABLE, 29, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_CFG_TX_OF_RXCLK" }, \ - { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_DFLT" }, \ - { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_DFLT" }, \ - { T6050_TUNABLE, 5, 0x0, 0x0, 0x0, 0, "tunable_AUS40CMN_SHM" }, \ - { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, \ - { T6050_TUNABLE, 10, 0x0, 0x0, 0x0, 0, "tunable_CIO4PLL_CORE" }, \ - { T6050_TUNABLE, 3, 0x0, 0x0, 0x0, 0, "tunable_UC_REGS_CIO_DFLT" }, \ - { T6050_TUNABLE, 16, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_TOP_CIO_DFLT" }, \ - { T6050_TUNABLE, 25, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_TOP_CIO_DFLT" }, \ - { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_CIO_DFLT" }, \ - { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_CIO_DFLT" } + { T6050_TUNABLE, 41, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF" }, \ + { T6050_TUNABLE, 40, 0x0, 0x0, 0x0, 0, "tunable_ATC_FABRIC" }, \ + { T6050_TUNABLE, 43, 0x0, 0x0, 0x0, 0, "tunable_ATC_COMMON_CFG" }, \ + { T6050_TUNABLE, 42, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF_LIOA" }, \ + { T6050_TUNABLE, 20, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_CFG_TX_OF_RXCLK" }, \ + { T6050_TUNABLE, 29, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_CFG_TX_OF_RXCLK" }, \ + { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_DFLT" }, \ + { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_DFLT" }, \ + { T6050_TUNABLE, 5, 0x0, 0x0, 0x0, 0, "tunable_AUS40CMN_SHM" }, \ + { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, \ + { T6050_TUNABLE, 10, 0x0, 0x0, 0x0, 0, "tunable_CIO4PLL_CORE" }, \ + { T6050_TUNABLE, 3, 0x0, 0x0, 0x0, 0, "tunable_UC_REGS_CIO_DFLT" }, \ + { T6050_TUNABLE, 16, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_TOP_CIO_DFLT" }, \ + { T6050_TUNABLE, 25, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_TOP_CIO_DFLT" }, \ + { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_CIO_DFLT" }, \ + { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_CIO_DFLT" } /* The crossbar: clear the lane selects, set the orientation bit (+0x78) * and select CIO. */ #define APPLE_T6050_CIO_XBAR(reverse) \ - { T6050_MASK, 2, 0x6c, 0xfc, 0x0, 0, 0 }, \ - { T6050_MASK, 2, 0x78, 0x1f, (reverse), 0, 0 }, \ - { T6050_MASK, 2, 0x6c, 0x3, 0x2, 0, 0 } + { T6050_MASK, 2, 0x6c, 0xfc, 0x0, 0, NULL }, \ + { T6050_MASK, 2, 0x78, 0x1f, (reverse), 0, NULL }, \ + { T6050_MASK, 2, 0x6c, 0x3, 0x2, 0, NULL } /* Power a lane's receiver up, then release its transmitter overrides. */ #define APPLE_T6050_CIO_LANE(l) \ - { T6050_MASK, 2, 0x10, 0x10 << (l), 0x10 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x10, 0x40 << (l), 0x40 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x10, 0x1 << (l), 0x1 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x10, 0x4 << (l), 0x4 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x400 << (l), 0x400 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x1000 << (l), 0x1000 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x40 << (l), 0x40 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x100 << (l), 0x100 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x4000 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x10000 << (l), 0x10000 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x120, 0x40 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x120, 0x4 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x120, 0x400 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 } + { T6050_MASK, 2, 0x10, 0x10 << (l), 0x10 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x10, 0x40 << (l), 0x40 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x10, 0x1 << (l), 0x1 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x10, 0x4 << (l), 0x4 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x400 << (l), 0x400 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x1000 << (l), 0x1000 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x40 << (l), 0x40 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x100 << (l), 0x100 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x4000 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x10000 << (l), 0x10000 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x120, 0x40 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x120, 0x4 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x120, 0x400 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL } /* The sleep-control release: the common block's overrides, then both lanes. */ #define APPLE_T6050_CIO_SLPCTRL \ - { T6050_MASK, 2, 0xc, 0x2a, 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - APPLE_T6050_CIO_LANE(0), \ - APPLE_T6050_CIO_LANE(1) + { T6050_MASK, 2, 0xc, 0x2a, 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + APPLE_T6050_CIO_LANE(0), \ + APPLE_T6050_CIO_LANE(1) /* Start the PHY firmware, wait for UC_TNBL_DONE and * deassert the ACIOPHY reset. No PIPE BIST and no ATCPHY_CFG +0x8 write. */ #define APPLE_T6050_CIO_START \ - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, \ - { T6050_MASK, 38, 0x40, 0x1, 0x1, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, \ - { T6050_FIRMWARE, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, 0 }, \ - { T6050_POLL, 2, 0x260, 0x400, 0x400, 1000000, 0 }, \ - { T6050_MASK, 39, 0x0, 0x10, 0x10, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x64, 0, 0 } + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, \ + { T6050_MASK, 38, 0x40, 0x1, 0x1, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, \ + { T6050_FIRMWARE, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, NULL }, \ + { T6050_POLL, 2, 0x260, 0x400, 0x400, 1000000, NULL }, \ + { T6050_MASK, 39, 0x0, 0x10, 0x10, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x64, 0, NULL } static const struct apple_t6050_usb_step apple_t6050_cio_init_normal[] = { - APPLE_T6050_CIO_POWERUP, - APPLE_T6050_CIO_TUNABLES, - APPLE_T6050_CIO_XBAR(0x0), - APPLE_T6050_CIO_SLPCTRL, - APPLE_T6050_CIO_START, + APPLE_T6050_CIO_POWERUP, + APPLE_T6050_CIO_TUNABLES, + APPLE_T6050_CIO_XBAR(0x0), + APPLE_T6050_CIO_SLPCTRL, + APPLE_T6050_CIO_START, }; static const struct apple_t6050_usb_step apple_t6050_cio_init_reverse[] = { - APPLE_T6050_CIO_POWERUP, - APPLE_T6050_CIO_TUNABLES, - APPLE_T6050_CIO_XBAR(0x1), - APPLE_T6050_CIO_SLPCTRL, - APPLE_T6050_CIO_START, + APPLE_T6050_CIO_POWERUP, + APPLE_T6050_CIO_TUNABLES, + APPLE_T6050_CIO_XBAR(0x1), + APPLE_T6050_CIO_SLPCTRL, + APPLE_T6050_CIO_START, }; /* Power a lane's transmitter down. */ #define APPLE_T6050_CIO_TX_DOWN(l) \ - { T6050_MASK, 2, 0x120, 0x100 << (l), 0x100 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x120, 0x1 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x120, 0x10 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 } + { T6050_MASK, 2, 0x120, 0x100 << (l), 0x100 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x120, 0x1 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x120, 0x10 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL } /* Power a lane's receiver down; CIO powers the receivers down, USB does not. */ #define APPLE_T6050_CIO_RX_DOWN(l) \ - { T6050_MASK, 2, 0xc, 0x4000 << (l), 0x4000 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x40 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x400 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x10, 0x1 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x10, 0x10 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 } + { T6050_MASK, 2, 0xc, 0x4000 << (l), 0x4000 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x40 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x400 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x10, 0x1 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x10, 0x10 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL } /* The shutdown: both lanes down without the PIPE BIST, the firmware * power-down, then the USB recipes' sleep, clamp and reset sequence. */ static const struct apple_t6050_usb_step apple_t6050_cio_shutdown[] = { - APPLE_T6050_CIO_TX_DOWN(0), - APPLE_T6050_CIO_TX_DOWN(1), - { T6050_MASK, 5, 0x0, 0x2, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x10, 0x10, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x4, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - APPLE_T6050_CIO_RX_DOWN(0), - APPLE_T6050_CIO_RX_DOWN(1), - { T6050_DELAY, 0, 0x0, 0x0, 0xc8, 0, 0 }, - { T6050_FIRMWARE, 0, 0x0, 0x0, 0x0, 0, 0 }, - { T6050_POWER, 0, 0x0, 0x0, 0x0, 0, 0 }, - { T6050_MASK, 39, 0x2c, 0x1, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x100, 0x100, 1000, 0 }, - { T6050_MASK, 39, 0x0, 0x10, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x8, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x4, 0x4, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x2, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x2, 0x0, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x1, 0x0, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x8, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, + APPLE_T6050_CIO_TX_DOWN(0), + APPLE_T6050_CIO_TX_DOWN(1), + { T6050_MASK, 5, 0x0, 0x2, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x10, 0x10, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x4, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + APPLE_T6050_CIO_RX_DOWN(0), + APPLE_T6050_CIO_RX_DOWN(1), + { T6050_DELAY, 0, 0x0, 0x0, 0xc8, 0, NULL }, + { T6050_FIRMWARE, 0, 0x0, 0x0, 0x0, 0, NULL }, + { T6050_POWER, 0, 0x0, 0x0, 0x0, 0, NULL }, + { T6050_MASK, 39, 0x2c, 0x1, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x100, 0x100, 1000, NULL }, + { T6050_MASK, 39, 0x0, 0x10, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x8, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x4, 0x4, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x2, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x2, 0x0, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x1, 0x0, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x8, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, }; #endif diff --git a/drivers/phy/apple/usb-t6050/apple_t6050_usb_phy.h b/drivers/phy/apple/usb-t6050/apple_t6050_usb_phy.h index 5c96da7d82c2d2..e0e7102831191c 100644 --- a/drivers/phy/apple/usb-t6050/apple_t6050_usb_phy.h +++ b/drivers/phy/apple/usb-t6050/apple_t6050_usb_phy.h @@ -4,263 +4,272 @@ #define APPLE_T6050_USB_PHY_H #include "apple_t6050_usb3_bist.h" struct apple_t6050_usb_platform { - const struct apple_t6050_usb_io *io; - void *context; - int (*wrapper_power)(void *, unsigned int); - int (*firmware)(void *, unsigned int); - int (*tunable)(void *, unsigned int, const char *); - void (*pause_ns)(void *, unsigned int); + const struct apple_t6050_usb_io *io; + void *context; + int (*wrapper_power)(void *, unsigned int); + int (*firmware)(void *, unsigned int); + int (*tunable)(void *, unsigned int, const char *); + void (*pause_ns)(void *, unsigned int); }; enum apple_t6050_usb_op { T6050_MASK, T6050_POLL, T6050_DELAY, - T6050_POWER, T6050_FIRMWARE, T6050_TUNABLE }; + T6050_POWER, T6050_FIRMWARE, T6050_TUNABLE }; struct apple_t6050_usb_step { - unsigned int op, bank, offset, mask, value, timeout; - const char *name; + unsigned int op, bank, offset, mask, value, timeout; + const char *name; }; static const struct apple_t6050_usb_step apple_t6050_usb2_host[] = { - { T6050_TUNABLE, 0, 0x0, 0x0, 0x0, 0, "tunable_USB2PHY_DFLT" }, - { T6050_TUNABLE, 0, 0x0, 0x0, 0x0, 0, "tunable_USB2PHY_HOST" }, - { T6050_DELAY, 0, 0x0, 0x0, 0x2710, 0, 0 }, - { T6050_MASK, 0, 0x4, 0x8, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_MASK, 0, 0x4, 0x1, 0x0, 0, 0 }, - { T6050_MASK, 0, 0x4, 0x2, 0x0, 0, 0 }, - { T6050_MASK, 1, 0x0, 0x9, 0x9, 0, 0 }, - { T6050_MASK, 0, 0x4, 0x4, 0x4, 0, 0 }, - { T6050_MASK, 0, 0x1c, 0x20000000, 0x0, 0, 0 }, - { T6050_MASK, 0, 0x1c, 0x40000000, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1e, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, 0 }, - { T6050_MASK, 0, 0x0, 0x7, 0x2, 0, 0 }, + { T6050_TUNABLE, 0, 0x0, 0x0, 0x0, 0, "tunable_USB2PHY_DFLT" }, + { T6050_TUNABLE, 0, 0x0, 0x0, 0x0, 0, "tunable_USB2PHY_HOST" }, + { T6050_DELAY, 0, 0x0, 0x0, 0x2710, 0, NULL }, + { T6050_MASK, 0, 0x4, 0x8, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_MASK, 0, 0x4, 0x1, 0x0, 0, NULL }, + { T6050_MASK, 0, 0x4, 0x2, 0x0, 0, NULL }, + { T6050_MASK, 1, 0x0, 0x9, 0x9, 0, NULL }, + { T6050_MASK, 0, 0x4, 0x4, 0x4, 0, NULL }, + { T6050_MASK, 0, 0x1c, 0x20000000, 0x0, 0, NULL }, + { T6050_MASK, 0, 0x1c, 0x40000000, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1e, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, NULL }, + { T6050_MASK, 0, 0x0, 0x7, 0x2, 0, NULL }, }; static const struct apple_t6050_usb_step apple_t6050_usb3_init_normal[] = { - { T6050_MASK, 39, 0x0, 0x1, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x1, 0x1, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x2, 0x2, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x2, 0x2, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x4, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POWER, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x2c, 0x1, 0x0, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x100, 0x0, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x8, 0x8, 0, 0 }, - { T6050_TUNABLE, 41, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF" }, - { T6050_TUNABLE, 40, 0x0, 0x0, 0x0, 0, "tunable_ATC_FABRIC" }, - { T6050_TUNABLE, 43, 0x0, 0x0, 0x0, 0, "tunable_ATC_COMMON_CFG" }, - { T6050_TUNABLE, 42, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF_LIOA" }, - { T6050_TUNABLE, 20, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_CFG_TX_OF_RXCLK" }, - { T6050_TUNABLE, 29, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_CFG_TX_OF_RXCLK" }, - { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_DFLT" }, - { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_DFLT" }, - { T6050_TUNABLE, 5, 0x0, 0x0, 0x0, 0, "tunable_AUS40CMN_SHM" }, - { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, - { T6050_TUNABLE, 10, 0x0, 0x0, 0x0, 0, "tunable_CIO4PLL_CORE" }, - { T6050_MASK, 4, 0x0, 0x3f0, 0x1c0, 0, 0 }, - { T6050_MASK, 4, 0x18, 0xf000, 0x3000, 0, 0 }, - { T6050_MASK, 9, 0x88, 0xff, 0x27, 0, 0 }, - { T6050_MASK, 33, 0x4, 0x38, 0x8, 0, 0 }, - { T6050_MASK, 10, 0xdc, 0x3ff0, 0x1760, 0, 0 }, - { T6050_MASK, 21, 0xcc, 0x1f80000, 0x380000, 0, 0 }, - { T6050_MASK, 30, 0xcc, 0x1f80000, 0x380000, 0, 0 }, - { T6050_MASK, 20, 0x90, 0x1f80000, 0x380000, 0, 0 }, - { T6050_MASK, 29, 0x90, 0x1f80000, 0x380000, 0, 0 }, - { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, - { T6050_MASK, 2, 0x6c, 0x28000fc, 0x44, 0, 0 }, - { T6050_MASK, 2, 0x78, 0x1ffff, 0x110, 0, 0 }, - { T6050_MASK, 2, 0x6c, 0x3, 0x2, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x2a, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x10, 0x4, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x10, 0x40, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x10000, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x100, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x1000, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x40, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x4, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x400, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x8, 0x2, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_MASK, 38, 0x40, 0x1, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_FIRMWARE, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, 0 }, - { T6050_POLL, 2, 0x260, 0x400, 0x400, 1000000, 0 }, - { T6050_MASK, 39, 0x0, 0x10, 0x10, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x64, 0, 0 }, + { T6050_MASK, 39, 0x0, 0x1, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x1, 0x1, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x2, 0x2, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x2, 0x2, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x4, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POWER, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x2c, 0x1, 0x0, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x100, 0x0, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x8, 0x8, 0, NULL }, + { T6050_TUNABLE, 41, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF" }, + { T6050_TUNABLE, 40, 0x0, 0x0, 0x0, 0, "tunable_ATC_FABRIC" }, + { T6050_TUNABLE, 43, 0x0, 0x0, 0x0, 0, "tunable_ATC_COMMON_CFG" }, + { T6050_TUNABLE, 42, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF_LIOA" }, + { T6050_TUNABLE, 20, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_CFG_TX_OF_RXCLK" }, + { T6050_TUNABLE, 29, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_CFG_TX_OF_RXCLK" }, + { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_DFLT" }, + { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_DFLT" }, + { T6050_TUNABLE, 5, 0x0, 0x0, 0x0, 0, "tunable_AUS40CMN_SHM" }, + { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, + { T6050_TUNABLE, 10, 0x0, 0x0, 0x0, 0, "tunable_CIO4PLL_CORE" }, + { T6050_MASK, 4, 0x0, 0x3f0, 0x1c0, 0, NULL }, + { T6050_MASK, 4, 0x18, 0xf000, 0x3000, 0, NULL }, + { T6050_MASK, 9, 0x88, 0xff, 0x27, 0, NULL }, + { T6050_MASK, 33, 0x4, 0x38, 0x8, 0, NULL }, + { T6050_MASK, 10, 0xdc, 0x3ff0, 0x1760, 0, NULL }, + { T6050_MASK, 21, 0xcc, 0x1f80000, 0x380000, 0, NULL }, + { T6050_MASK, 30, 0xcc, 0x1f80000, 0x380000, 0, NULL }, + { T6050_MASK, 20, 0x90, 0x1f80000, 0x380000, 0, NULL }, + { T6050_MASK, 29, 0x90, 0x1f80000, 0x380000, 0, NULL }, + { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, + { T6050_MASK, 2, 0x6c, 0x28000fc, 0x44, 0, NULL }, + { T6050_MASK, 2, 0x78, 0x1ffff, 0x110, 0, NULL }, + { T6050_MASK, 2, 0x6c, 0x3, 0x2, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x2a, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x10, 0x4, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x10, 0x40, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x10000, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x100, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x1000, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x40, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x4, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x400, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x8, 0x2, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_MASK, 38, 0x40, 0x1, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_FIRMWARE, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, NULL }, + { T6050_POLL, 2, 0x260, 0x400, 0x400, 1000000, NULL }, + { T6050_MASK, 39, 0x0, 0x10, 0x10, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x64, 0, NULL }, }; static const struct apple_t6050_usb_step apple_t6050_usb3_init_reverse[] = { - { T6050_MASK, 39, 0x0, 0x1, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x1, 0x1, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x2, 0x2, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x2, 0x2, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x4, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POWER, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x2c, 0x1, 0x0, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x100, 0x0, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x8, 0x8, 0, 0 }, - { T6050_TUNABLE, 41, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF" }, - { T6050_TUNABLE, 40, 0x0, 0x0, 0x0, 0, "tunable_ATC_FABRIC" }, - { T6050_TUNABLE, 43, 0x0, 0x0, 0x0, 0, "tunable_ATC_COMMON_CFG" }, - { T6050_TUNABLE, 42, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF_LIOA" }, - { T6050_TUNABLE, 20, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_CFG_TX_OF_RXCLK" }, - { T6050_TUNABLE, 29, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_CFG_TX_OF_RXCLK" }, - { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_DFLT" }, - { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_DFLT" }, - { T6050_TUNABLE, 5, 0x0, 0x0, 0x0, 0, "tunable_AUS40CMN_SHM" }, - { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, - { T6050_TUNABLE, 10, 0x0, 0x0, 0x0, 0, "tunable_CIO4PLL_CORE" }, - { T6050_MASK, 4, 0x0, 0x3f0, 0x1c0, 0, 0 }, - { T6050_MASK, 4, 0x18, 0xf000, 0x3000, 0, 0 }, - { T6050_MASK, 9, 0x88, 0xff, 0x27, 0, 0 }, - { T6050_MASK, 33, 0x4, 0x38, 0x8, 0, 0 }, - { T6050_MASK, 10, 0xdc, 0x3ff0, 0x1760, 0, 0 }, - { T6050_MASK, 21, 0xcc, 0x1f80000, 0x380000, 0, 0 }, - { T6050_MASK, 30, 0xcc, 0x1f80000, 0x380000, 0, 0 }, - { T6050_MASK, 20, 0x90, 0x1f80000, 0x380000, 0, 0 }, - { T6050_MASK, 29, 0x90, 0x1f80000, 0x380000, 0, 0 }, - { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, - { T6050_MASK, 2, 0x6c, 0x14000fc, 0x28, 0, 0 }, - { T6050_MASK, 2, 0x78, 0x1ffff, 0x111, 0, 0 }, - { T6050_MASK, 2, 0x6c, 0x3, 0x2, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x2a, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x10, 0x8, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x10, 0x80, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x20000, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x200, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x2000, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x80, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x8, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x800, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x8, 0x2, 0x2, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_MASK, 38, 0x40, 0x1, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_FIRMWARE, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, 0 }, - { T6050_POLL, 2, 0x260, 0x400, 0x400, 1000000, 0 }, - { T6050_MASK, 39, 0x0, 0x10, 0x10, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x64, 0, 0 }, + { T6050_MASK, 39, 0x0, 0x1, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x1, 0x1, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x2, 0x2, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x2, 0x2, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x4, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POWER, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x2c, 0x1, 0x0, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x100, 0x0, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x8, 0x8, 0, NULL }, + { T6050_TUNABLE, 41, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF" }, + { T6050_TUNABLE, 40, 0x0, 0x0, 0x0, 0, "tunable_ATC_FABRIC" }, + { T6050_TUNABLE, 43, 0x0, 0x0, 0x0, 0, "tunable_ATC_COMMON_CFG" }, + { T6050_TUNABLE, 42, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF_LIOA" }, + { T6050_TUNABLE, 20, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_CFG_TX_OF_RXCLK" }, + { T6050_TUNABLE, 29, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_CFG_TX_OF_RXCLK" }, + { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_DFLT" }, + { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_DFLT" }, + { T6050_TUNABLE, 5, 0x0, 0x0, 0x0, 0, "tunable_AUS40CMN_SHM" }, + { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, + { T6050_TUNABLE, 10, 0x0, 0x0, 0x0, 0, "tunable_CIO4PLL_CORE" }, + { T6050_MASK, 4, 0x0, 0x3f0, 0x1c0, 0, NULL }, + { T6050_MASK, 4, 0x18, 0xf000, 0x3000, 0, NULL }, + { T6050_MASK, 9, 0x88, 0xff, 0x27, 0, NULL }, + { T6050_MASK, 33, 0x4, 0x38, 0x8, 0, NULL }, + { T6050_MASK, 10, 0xdc, 0x3ff0, 0x1760, 0, NULL }, + { T6050_MASK, 21, 0xcc, 0x1f80000, 0x380000, 0, NULL }, + { T6050_MASK, 30, 0xcc, 0x1f80000, 0x380000, 0, NULL }, + { T6050_MASK, 20, 0x90, 0x1f80000, 0x380000, 0, NULL }, + { T6050_MASK, 29, 0x90, 0x1f80000, 0x380000, 0, NULL }, + { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, + { T6050_MASK, 2, 0x6c, 0x14000fc, 0x28, 0, NULL }, + { T6050_MASK, 2, 0x78, 0x1ffff, 0x111, 0, NULL }, + { T6050_MASK, 2, 0x6c, 0x3, 0x2, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x2a, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x10, 0x8, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x10, 0x80, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x20000, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x200, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x2000, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x80, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x8, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x800, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x8, 0x2, 0x2, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_MASK, 38, 0x40, 0x1, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_FIRMWARE, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, NULL }, + { T6050_POLL, 2, 0x260, 0x400, 0x400, 1000000, NULL }, + { T6050_MASK, 39, 0x0, 0x10, 0x10, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x64, 0, NULL }, }; static const struct apple_t6050_usb_step apple_t6050_usb3_shutdown[] = { - { T6050_MASK, 35, 0x4, 0x1, 0x1, 0, 0 }, - { T6050_MASK, 35, 0x10c, 0x100000, 0x0, 0, 0 }, - { T6050_MASK, 35, 0x110, 0x60, 0x20, 0, 0 }, - { T6050_MASK, 35, 0x4, 0x8, 0x8, 0, 0 }, - { T6050_MASK, 35, 0x4, 0x8, 0x0, 0, 0 }, - { T6050_POLL, 35, 0x104, 0x100, 0x100, 1000000, 0 }, - { T6050_MASK, 35, 0x10c, 0x1e000000, 0x4000000, 0, 0 }, - { T6050_MASK, 35, 0x110, 0x600, 0x200, 0, 0 }, - { T6050_MASK, 35, 0x4, 0x8, 0x8, 0, 0 }, - { T6050_MASK, 35, 0x4, 0x8, 0x0, 0, 0 }, - { T6050_POLL, 35, 0x104, 0x100, 0x100, 1000000, 0 }, - { T6050_MASK, 35, 0x4, 0x1, 0x0, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x100, 0x100, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x10, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x200, 0x200, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x2, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x20, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 5, 0x0, 0x2, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x10, 0x10, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x4, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xc8, 0, 0 }, - { T6050_FIRMWARE, 0, 0x0, 0x0, 0x0, 0, 0 }, - { T6050_POWER, 0, 0x0, 0x0, 0x0, 0, 0 }, - { T6050_MASK, 39, 0x2c, 0x1, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x100, 0x100, 1000, 0 }, - { T6050_MASK, 39, 0x0, 0x10, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x8, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x4, 0x4, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x2, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x2, 0x0, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x1, 0x0, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x8, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, + { T6050_MASK, 35, 0x4, 0x1, 0x1, 0, NULL }, + { T6050_MASK, 35, 0x10c, 0x100000, 0x0, 0, NULL }, + { T6050_MASK, 35, 0x110, 0x60, 0x20, 0, NULL }, + { T6050_MASK, 35, 0x4, 0x8, 0x8, 0, NULL }, + { T6050_MASK, 35, 0x4, 0x8, 0x0, 0, NULL }, + { T6050_POLL, 35, 0x104, 0x100, 0x100, 1000000, NULL }, + { T6050_MASK, 35, 0x10c, 0x1e000000, 0x4000000, 0, NULL }, + { T6050_MASK, 35, 0x110, 0x600, 0x200, 0, NULL }, + { T6050_MASK, 35, 0x4, 0x8, 0x8, 0, NULL }, + { T6050_MASK, 35, 0x4, 0x8, 0x0, 0, NULL }, + { T6050_POLL, 35, 0x104, 0x100, 0x100, 1000000, NULL }, + { T6050_MASK, 35, 0x4, 0x1, 0x0, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x100, 0x100, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x10, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x200, 0x200, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x2, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x20, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 5, 0x0, 0x2, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x10, 0x10, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x4, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xc8, 0, NULL }, + { T6050_FIRMWARE, 0, 0x0, 0x0, 0x0, 0, NULL }, + { T6050_POWER, 0, 0x0, 0x0, 0x0, 0, NULL }, + { T6050_MASK, 39, 0x2c, 0x1, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x100, 0x100, 1000, NULL }, + { T6050_MASK, 39, 0x0, 0x10, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x8, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x4, 0x4, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x2, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x2, 0x0, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x1, 0x0, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x8, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, }; static inline int apple_t6050_usb_phy_run(const struct apple_t6050_usb_platform *p, - const struct apple_t6050_usb_step *steps, unsigned int count) + const struct apple_t6050_usb_step *steps, unsigned int count) { - if (!p || !p->io || !p->io->read || !p->io->write || - !p->io->poll || !p->io->delay || !p->wrapper_power || - !p->firmware || !p->tunable) - return -1; - for (unsigned int i = 0; i < count; i++) { - const struct apple_t6050_usb_step *s = &steps[i]; - int ret = 0; - switch (s->op) { - case T6050_MASK: - apple_t6050_usb_mask(p->io, s->bank, s->offset, s->mask, s->value); - break; - case T6050_POLL: - ret = p->io->poll(p->io->context, s->bank, s->offset, - s->mask, s->value, s->timeout); - break; - case T6050_DELAY: p->io->delay(p->io->context, s->value); break; - case T6050_POWER: ret = p->wrapper_power(p->context, s->value); break; - case T6050_FIRMWARE: ret = p->firmware(p->context, s->value); break; - case T6050_TUNABLE: ret = p->tunable(p->context, s->bank, s->name); break; - default: return -1; - } - if (ret) - return ret; - } - return 0; + if (!p || !p->io || !p->io->read || !p->io->write || + !p->io->poll || !p->io->delay || !p->wrapper_power || + !p->firmware || !p->tunable) + return -1; + for (unsigned int i = 0; i < count; i++) { + const struct apple_t6050_usb_step *s = &steps[i]; + int ret = 0; + switch (s->op) { + case T6050_MASK: + apple_t6050_usb_mask(p->io, s->bank, s->offset, s->mask, s->value); + break; + case T6050_POLL: + ret = p->io->poll(p->io->context, s->bank, s->offset, + s->mask, s->value, s->timeout); + break; + case T6050_DELAY: + p->io->delay(p->io->context, s->value); + break; + case T6050_POWER: + ret = p->wrapper_power(p->context, s->value); + break; + case T6050_FIRMWARE: + ret = p->firmware(p->context, s->value); + break; + case T6050_TUNABLE: + ret = p->tunable(p->context, s->bank, s->name); + break; + default: + return -1; + } + if (ret) + return ret; + } + return 0; } #define APPLE_T6050_USB_RUN(p, steps) \ - apple_t6050_usb_phy_run((p), (steps), sizeof(steps) / sizeof((steps)[0])) + apple_t6050_usb_phy_run((p), (steps), sizeof(steps) / sizeof((steps)[0])) /* Native shutdown first asserts PORT_RESET only if it was not already set. * The 5 ms wait belongs to that transition, not every redundant stop call. @@ -268,19 +277,19 @@ apple_t6050_usb_phy_run(const struct apple_t6050_usb_platform *p, */ static inline int apple_t6050_usb2_stop(const struct apple_t6050_usb_platform *p) { - if (!p || !p->io || !p->io->read || !p->io->write || - !p->io->delay || !p->pause_ns) - return -1; - if (!(p->io->read(p->io->context, 0, 4) & 2)) { - apple_t6050_usb_mask(p->io, 0, 4, 2, 2); - p->io->delay(p->io->context, 5000); - } - apple_t6050_usb_mask(p->io, 0, 0, 7, 4); - apple_t6050_usb_mask(p->io, 0, 4, 8, 8); - apple_t6050_usb_mask(p->io, 0, 4, 1, 1); - apple_t6050_usb_mask(p->io, 0, 0x1c, 0x20000000, 0x20000000); - apple_t6050_usb_mask(p->io, 0, 0x1c, 0x40000000, 0x40000000); - p->pause_ns(p->context, 500); - return 0; + if (!p || !p->io || !p->io->read || !p->io->write || + !p->io->delay || !p->pause_ns) + return -1; + if (!(p->io->read(p->io->context, 0, 4) & 2)) { + apple_t6050_usb_mask(p->io, 0, 4, 2, 2); + p->io->delay(p->io->context, 5000); + } + apple_t6050_usb_mask(p->io, 0, 0, 7, 4); + apple_t6050_usb_mask(p->io, 0, 4, 8, 8); + apple_t6050_usb_mask(p->io, 0, 4, 1, 1); + apple_t6050_usb_mask(p->io, 0, 0x1c, 0x20000000, 0x20000000); + apple_t6050_usb_mask(p->io, 0, 0x1c, 0x40000000, 0x40000000); + p->pause_ns(p->context, 500); + return 0; } #endif diff --git a/drivers/pinctrl/pinctrl-apple-gpio.c b/drivers/pinctrl/pinctrl-apple-gpio.c index 6b96948767a80a..7089aac3bbe2e9 100644 --- a/drivers/pinctrl/pinctrl-apple-gpio.c +++ b/drivers/pinctrl/pinctrl-apple-gpio.c @@ -341,6 +341,15 @@ static void apple_gpio_irq_unmask(struct irq_data *data) gpiochip_enable_irq(gc, data->hwirq); apple_gpio_set_reg(pctl, data->hwirq, apple_gpio_mode_mask(), FIELD_PREP(REG_GPIOx_MODE, irqtype)); + /* + * On T6041 a level interrupt fired again at once every time it was unmasked although its + * line was inactive (J616c speaker amps, pin 55: mode 3, data 1, ~140 interrupts a second + * from boot until the core disabled the line as unhandled). Switching the mode back from + * "off" leaves the status bit set. Clear it once more: a level that really is active sets + * it again. + */ + if (irqd_get_trigger_type(data) & IRQ_TYPE_LEVEL_MASK) + apple_gpio_irq_ack(data); } static unsigned int apple_gpio_irq_startup(struct irq_data *data) diff --git a/drivers/pmdomain/apple/Kconfig b/drivers/pmdomain/apple/Kconfig index 118bcd17362426..0d67b542b97fae 100644 --- a/drivers/pmdomain/apple/Kconfig +++ b/drivers/pmdomain/apple/Kconfig @@ -26,6 +26,18 @@ config APPLE_PMGR_PWRSTATE_KUNIT_TEST and need no Apple hardware. Also check the T6000 GFX missing-parent wait, its timeout, and the separate actual-state acknowledgment. +config APPLE_PMGR_PSD + bool "Apple T8152 PMGR service power domains" + depends on ARCH_APPLE || COMPILE_TEST + depends on PM && OF + select PM_GENERIC_DOMAINS + default ARCH_APPLE + help + The T8152 PMGR switches some blocks, the video decoder and the + USB4 routers and their PHYs, through service power states (PSD) + rather than PMGR power state registers. This driver offers each + service as a generic power domain. + config APPLE_T6041_CIO_RECONFIG bool "Apple T6041 CIO cluster reconfiguration" depends on OF @@ -117,7 +129,9 @@ config APPLE_PMP_REPORT_START_KUNIT_TEST failed checks, a PMP driver that does not bind, a PMP that does not report ready or acknowledge its startup requests, consumers that time out, and the teardown of the report and its entries while a - start or a consumer waits. The report region is simulated in + start or a consumer waits. Also reads the fast die-temperature + effort of a report: its lanes, reports that have none or do not + run, and the T8142 layout. The report region is simulated in memory. Only useful for kernel developers. endif diff --git a/drivers/pmdomain/apple/Makefile b/drivers/pmdomain/apple/Makefile index 351773930cb845..34b8898eff9111 100644 --- a/drivers/pmdomain/apple/Makefile +++ b/drivers/pmdomain/apple/Makefile @@ -8,3 +8,4 @@ obj-$(CONFIG_APPLE_PMP_DRAM_KUNIT_TEST) += pmp-dram-test.o obj-$(CONFIG_APPLE_PMC) += pmc.o obj-$(CONFIG_APPLE_PMP_ANE_KUNIT_TEST) += pmp-ane-test.o obj-$(CONFIG_APPLE_PMP_FLOOR_KUNIT_TEST) += pmp-floor-gov-test.o +obj-$(CONFIG_APPLE_PMGR_PSD) += pmgr-psd.o diff --git a/drivers/pmdomain/apple/pmc-test.c b/drivers/pmdomain/apple/pmc-test.c index 4e7f19d47317a1..fbdba523cfaf5e 100644 --- a/drivers/pmdomain/apple/pmc-test.c +++ b/drivers/pmdomain/apple/pmc-test.c @@ -170,11 +170,16 @@ static void apple_pmc_test_release_restores_ap_vote(struct kunit *test) static void apple_pmc_test_pending_floor(struct kunit *test) { struct apple_pmc *pmc = apple_pmc_test_alloc(test); - struct device dev = {}; + struct device dev = { .driver = &apple_pmc_driver.driver }; + struct device foreign = {}; + int dummy = 0x1234; void __iomem *reg; pmc->hw = &apple_pmc_hw_t8132; dev_set_drvdata(&dev, pmc); + dev_set_drvdata(&foreign, &dummy); + KUNIT_EXPECT_EQ(test, apple_pmc_rail_count(&foreign), 0U); + KUNIT_EXPECT_EQ(test, apple_pmc_rail_count(&dev), pmc->hw->rails); reg = pmc->voters + pmc->hw->ap_agent * pmc->hw->agent_stride; writel(0xa500, reg); writel(BIT(pmc->hw->ap_agent), reg + 4); @@ -543,6 +548,72 @@ static void apple_pmc_test_interface_boot_state(struct kunit *test) KUNIT_EXPECT_EQ(test, readl(pmc->rails + hw->boost_enable), BIT(0) | BIT(1)); } +/* + * The AP's DCS vote waits for the PMC to take the previous vote, as other + * floor writes do, instead of writing over it. + */ +static void apple_pmc_test_dcs_floor_pending(struct kunit *test) +{ + struct apple_pmc *pmc = apple_pmc_test_alloc(test); + struct apple_pmc_domain *dom; + void __iomem *reg; + + INIT_LIST_HEAD(&pmc->domains); + pmc->hw = &apple_pmc_hw_t8132; + reg = pmc->voters + pmc->hw->ap_agent * pmc->hw->agent_stride; + writel(BIT(pmc->hw->ap_agent), reg + 4); + dom = apple_pmc_test_floor(test, pmc, pmc->hw->dcs_rail, 2); + KUNIT_EXPECT_EQ(test, apple_pmc_floor_set(dom, true), -ETIMEDOUT); + KUNIT_EXPECT_FALSE(test, dom->on); + KUNIT_EXPECT_EQ(test, apple_pmc_ap_dcs_read(pmc), 0U); + writel(0, reg + 4); + KUNIT_EXPECT_EQ(test, apple_pmc_floor_set(dom, true), 0); + KUNIT_EXPECT_EQ(test, apple_pmc_ap_dcs_read(pmc), 2U); +} + +/* + * Leaving a DCS limit when the AP's vote is still pending rolls back the + * rail enable so dcs_state and hardware stay in sync until a retry clears it. + */ +static void apple_pmc_test_dcs_limit_release_pending(struct kunit *test) +{ + struct apple_pmc *pmc = apple_pmc_test_alloc(test); + const struct apple_pmc_hw *hw = &apple_pmc_hw_t8132; + struct thermal_cooling_device cdev = { .devdata = pmc }; + void __iomem *reg; + + pmc->hw = hw; + INIT_DELAYED_WORK(&pmc->dcs_work, apple_pmc_dcs_work); + apple_pmc_test_set_dcs_vote(pmc, hw->ap_agent, 1); + apple_pmc_test_set_dcs_vote(pmc, 0, hw->dcs_max); + pmc->ap_dcs_vote = apple_pmc_ap_dcs_read(pmc); + pmc->enable[hw->dcs_rail] = BIT(0) | BIT(hw->ap_agent); + writel(pmc->enable[hw->dcs_rail], + pmc->rails + hw->rail_enable + 4 * hw->dcs_rail); + + KUNIT_ASSERT_EQ(test, apple_pmc_dcs_set_cur_state(&cdev, 2), 0); + KUNIT_EXPECT_EQ(test, pmc->dcs_state, 2UL); + KUNIT_EXPECT_EQ(test, apple_pmc_enable_read(pmc, hw->dcs_rail), + BIT(hw->ap_agent)); + KUNIT_EXPECT_EQ(test, apple_pmc_ap_dcs_read(pmc), hw->dcs_max - 2); + + reg = pmc->voters + hw->ap_agent * hw->agent_stride; + writel(BIT(hw->ap_agent), reg + 4); + KUNIT_EXPECT_EQ(test, apple_pmc_dcs_set_cur_state(&cdev, 0), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, pmc->dcs_state, 2UL); + KUNIT_EXPECT_EQ(test, apple_pmc_enable_read(pmc, hw->dcs_rail), + BIT(hw->ap_agent)); + KUNIT_EXPECT_EQ(test, apple_pmc_ap_dcs_read(pmc), hw->dcs_max - 2); + + writel(0, reg + 4); + KUNIT_EXPECT_EQ(test, apple_pmc_dcs_set_cur_state(&cdev, 0), 0); + KUNIT_EXPECT_EQ(test, pmc->dcs_state, 0UL); + KUNIT_EXPECT_EQ(test, apple_pmc_enable_read(pmc, hw->dcs_rail), + BIT(0) | BIT(hw->ap_agent)); + KUNIT_EXPECT_EQ(test, apple_pmc_ap_dcs_read(pmc), 1U); + cancel_delayed_work_sync(&pmc->dcs_work); +} + static struct kunit_case apple_pmc_test_cases[] = { KUNIT_CASE(apple_pmc_test_dcs_floor), KUNIT_CASE(apple_pmc_test_partial_enable), @@ -553,6 +624,8 @@ static struct kunit_case apple_pmc_test_cases[] = { KUNIT_CASE(apple_pmc_test_dcs_limit_restores_ap_vote), KUNIT_CASE(apple_pmc_test_floor_aggregate), KUNIT_CASE(apple_pmc_test_floor_pending_timeout), + KUNIT_CASE(apple_pmc_test_dcs_floor_pending), + KUNIT_CASE(apple_pmc_test_dcs_limit_release_pending), KUNIT_CASE(apple_pmc_test_interface), KUNIT_CASE(apple_pmc_test_interface_stuck), KUNIT_CASE(apple_pmc_test_interface_consumer), diff --git a/drivers/pmdomain/apple/pmc.c b/drivers/pmdomain/apple/pmc.c index e93dc40bc10c1b..7949216808a765 100644 --- a/drivers/pmdomain/apple/pmc.c +++ b/drivers/pmdomain/apple/pmc.c @@ -85,6 +85,8 @@ * @agent_rails: rails on which an agent is enabled; 0 for every rail * @ap_agent: voter agent of the application processor, which a DCS limit * votes through + * @has_pending: true if the PMC exposes a per-agent pending word at reg + 4 + * after each voter floor word (BIT(agent) set while a vote is pending) * @bwr_enable: offset of the bandwidth request (BWR) interface enable word * in the "rails" region; 0 if the PMC has none * @boost_enable: offset of the boost interface enable word in the "rails" @@ -275,9 +277,13 @@ static int apple_pmc_agent_enable(struct apple_pmc *pmc, unsigned int agent, return ret; } +static struct platform_driver apple_pmc_driver; + static struct apple_pmc *apple_pmc_from_dev(struct device *dev) { - return dev ? dev_get_drvdata(dev) : NULL; + if (!dev || dev->driver != &apple_pmc_driver.driver) + return NULL; + return dev_get_drvdata(dev); } /** @@ -425,24 +431,21 @@ static unsigned int apple_pmc_ap_dcs_read(struct apple_pmc *pmc) * Caller holds pmc->lock. Vote through the AP's agent for what the other * agents ask for and the DCS floors held, capped by the limit; without a * limit, the vote the AP's agent had before probe or the floors, if higher. + * Like any other floor write, wait out a vote the PMC has not taken yet. */ -static void apple_pmc_dcs_vote(struct apple_pmc *pmc) +static int apple_pmc_dcs_vote(struct apple_pmc *pmc) { const struct apple_pmc_hw *hw = pmc->hw; - void __iomem *reg = pmc->voters + hw->ap_agent * hw->agent_stride; - u32 mask = APPLE_PMC_RAIL_MASK(hw->dcs_rail); unsigned int state = max(pmc->ap_dcs_vote, pmc->dcs_floor); - u32 old, val; if (pmc->dcs_state) state = min_t(unsigned int, max(apple_pmc_dcs_demand(pmc), pmc->dcs_floor), hw->dcs_max - pmc->dcs_state); - old = readl(reg); - val = (old & ~mask) | (state << APPLE_PMC_RAIL_SHIFT(hw->dcs_rail)); - if (val != old) - writel(val, reg); + return __apple_pmc_floor_update(pmc, hw->ap_agent, + APPLE_PMC_RAIL_MASK(hw->dcs_rail), + state << APPLE_PMC_RAIL_SHIFT(hw->dcs_rail)); } static void apple_pmc_dcs_work(struct work_struct *work) @@ -489,18 +492,42 @@ static int apple_pmc_dcs_get_cur_state(struct thermal_cooling_device *cdev, static int apple_pmc_dcs_limit(struct apple_pmc *pmc, unsigned long state) { unsigned int rail = pmc->hw->dcs_rail; + unsigned long old = pmc->dcs_state; int ret; WRITE_ONCE(pmc->dcs_state, state); if (state) { - apple_pmc_dcs_vote(pmc); - return apple_pmc_enable_write(pmc, rail); + ret = apple_pmc_dcs_vote(pmc); + if (ret) { + WRITE_ONCE(pmc->dcs_state, old); + return ret; + } + ret = apple_pmc_enable_write(pmc, rail); + if (ret) { + WRITE_ONCE(pmc->dcs_state, old); + apple_pmc_dcs_vote(pmc); + } + return ret; } ret = apple_pmc_enable_write(pmc, rail); - if (!ret) - apple_pmc_dcs_vote(pmc); + if (ret) { + WRITE_ONCE(pmc->dcs_state, old); + return ret; + } + ret = apple_pmc_dcs_vote(pmc); + if (ret) { + /* + * All agents are already enabled, while the AP still holds + * the old capped vote. Re-restrict rail_enable so dcs_state + * stays synchronized with hardware; if that fails too, leave + * dcs_state at 0 to match the uncapped rail_enable. + */ + WRITE_ONCE(pmc->dcs_state, old); + if (apple_pmc_enable_write(pmc, rail)) + WRITE_ONCE(pmc->dcs_state, 0); + } return ret; } @@ -508,7 +535,7 @@ static int apple_pmc_dcs_set_cur_state(struct thermal_cooling_device *cdev, unsigned long state) { struct apple_pmc *pmc = cdev->devdata; - unsigned long flags, old; + unsigned long flags; bool limited; int ret = 0; @@ -516,17 +543,8 @@ static int apple_pmc_dcs_set_cur_state(struct thermal_cooling_device *cdev, return -EINVAL; raw_spin_lock_irqsave(&pmc->lock, flags); - old = pmc->dcs_state; - if (state != old) { + if (state != pmc->dcs_state) ret = apple_pmc_dcs_limit(pmc, state); - /* - * The rail enable did not change, so neither did the limit: - * go back to the old state, which the next call then retries - * to leave. - */ - if (ret) - apple_pmc_dcs_limit(pmc, old); - } limited = pmc->dcs_state; raw_spin_unlock_irqrestore(&pmc->lock, flags); @@ -659,8 +677,7 @@ static int apple_pmc_floor_apply(struct apple_pmc *pmc, unsigned int rail) /* The AP's DCS vote also carries the DCS limit; it combines both. */ if (rail == pmc->hw->dcs_rail) { pmc->dcs_floor = level; - apple_pmc_dcs_vote(pmc); - return 0; + return apple_pmc_dcs_vote(pmc); } return __apple_pmc_floor_update(pmc, pmc->hw->ap_agent, @@ -1557,8 +1574,10 @@ static int apple_pmc_resume_early(struct device *dev) * The AP agent's word also holds its DCS vote, which a deep sleep's commit zeroes * (apple-sleep, T8132 and T8142). Cast it again: a no-op if it stayed. */ - if (!(pmc->floor_rails & BIT(pmc->hw->dcs_rail))) - apple_pmc_dcs_vote(pmc); + if (!(pmc->floor_rails & BIT(pmc->hw->dcs_rail))) { + err = apple_pmc_dcs_vote(pmc); + ret = ret ?: err; + } raw_spin_unlock_irqrestore(&pmc->lock, flags); if (ret) dev_err(dev, "state not restored after sleep: %d\n", ret); diff --git a/drivers/pmdomain/apple/pmgr-psd.c b/drivers/pmdomain/apple/pmgr-psd.c new file mode 100644 index 00000000000000..04bbf0d35e9486 --- /dev/null +++ b/drivers/pmdomain/apple/pmgr-psd.c @@ -0,0 +1,151 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Apple T8152 PMGR2 PSD services as power domains. + * + * Each service has a 0x100 byte register block: the target state at +0x90, + * the acknowledge in bit 0 of +0xbc, and the current state in bits 2:0 of + * +0x80 (0 powered, 6 cold). Reading the state consumes the acknowledge, so + * the state is read only once the acknowledge is set. + * + * The consumers include IRQ-safe devices (DARTs), so the domains are IRQ-safe + * and a transition is polled atomically, as for the PMGR power states. + */ +#include +#include +#include +#include +#include +#include +#include + +#define APPLE_PSD_STATE 0x80 +#define APPLE_PSD_STATE_CUR GENMASK(2, 0) +#define APPLE_PSD_TARGET 0x90 +#define APPLE_PSD_ACK 0xbc +#define APPLE_PSD_ACK_DONE BIT(0) + +#define APPLE_PSD_ON 0 +#define APPLE_PSD_COLD 6 + +#define APPLE_PSD_TIMEOUT_US 10000 + +struct apple_psd { + struct generic_pm_domain genpd; + struct device *dev; + void __iomem *regs; +}; + +static u32 apple_psd_state(struct apple_psd *psd) +{ + return readl(psd->regs + APPLE_PSD_STATE) & APPLE_PSD_STATE_CUR; +} + +static bool apple_psd_reached(struct apple_psd *psd, u32 target, u32 *ack, + u32 *state) +{ + *ack = readl(psd->regs + APPLE_PSD_ACK); + if (!(*ack & APPLE_PSD_ACK_DONE)) + return false; + *state = apple_psd_state(psd); + return *state == target; +} + +static int apple_psd_set_state(struct generic_pm_domain *genpd, u32 target) +{ + struct apple_psd *psd = container_of(genpd, struct apple_psd, genpd); + u32 ack = 0, state; + bool done; + int ret; + + state = apple_psd_state(psd); + if (state == target) + return 0; + writel(target, psd->regs + APPLE_PSD_TARGET); + ret = read_poll_timeout_atomic(apple_psd_reached, done, done, 1, + APPLE_PSD_TIMEOUT_US, false, psd, target, + &ack, &state); + if (ret) { + dev_err(psd->dev, "%s: state %u not reached: ack %#x, state %u\n", + genpd->name, target, ack, state); + return ret; + } + return 0; +} + +static int apple_psd_power_on(struct generic_pm_domain *genpd) +{ + return apple_psd_set_state(genpd, APPLE_PSD_ON); +} + +static int apple_psd_power_off(struct generic_pm_domain *genpd) +{ + return apple_psd_set_state(genpd, APPLE_PSD_COLD); +} + +static void apple_psd_remove_provider(void *data) +{ + struct apple_psd *psd = data; + + of_genpd_del_provider(psd->dev->of_node); + pm_genpd_remove(&psd->genpd); +} + +static int apple_psd_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct device_node *np = dev->of_node; + struct apple_psd *psd; + bool is_off; + int ret; + + psd = devm_kzalloc(dev, sizeof(*psd), GFP_KERNEL); + if (!psd) + return -ENOMEM; + psd->dev = dev; + psd->regs = devm_platform_ioremap_resource(pdev, 0); + if (IS_ERR(psd->regs)) + return PTR_ERR(psd->regs); + + if (of_property_read_string(np, "label", &psd->genpd.name)) + psd->genpd.name = dev_name(dev); + psd->genpd.power_on = apple_psd_power_on; + psd->genpd.power_off = apple_psd_power_off; + psd->genpd.flags = GENPD_FLAG_IRQ_SAFE; + + if (of_property_read_bool(np, "apple,always-on")) { + psd->genpd.flags |= GENPD_FLAG_ALWAYS_ON; + ret = apple_psd_power_on(&psd->genpd); + if (ret) + return ret; + } + is_off = apple_psd_state(psd) != APPLE_PSD_ON; + + ret = pm_genpd_init(&psd->genpd, NULL, is_off); + if (ret) + return ret; + ret = of_genpd_add_provider_simple(np, &psd->genpd); + if (ret) { + pm_genpd_remove(&psd->genpd); + return ret; + } + return devm_add_action_or_reset(dev, apple_psd_remove_provider, psd); +} + +static const struct of_device_id apple_psd_match[] = { + { .compatible = "apple,t8152-psd" }, + {} +}; +MODULE_DEVICE_TABLE(of, apple_psd_match); + +static struct platform_driver apple_psd_driver = { + .probe = apple_psd_probe, + .driver = { + .name = "apple-pmgr-psd", + .of_match_table = apple_psd_match, + .suppress_bind_attrs = true, + }, +}; +module_platform_driver(apple_psd_driver); + +MODULE_LICENSE("Dual MIT/GPL"); +MODULE_DESCRIPTION("Apple T8152 PMGR2 PSD power domains"); diff --git a/drivers/pmdomain/apple/pmgr-pwrstate-test.c b/drivers/pmdomain/apple/pmgr-pwrstate-test.c index 66fb065523dee0..e7449c1dbee8ab 100644 --- a/drivers/pmdomain/apple/pmgr-pwrstate-test.c +++ b/drivers/pmdomain/apple/pmgr-pwrstate-test.c @@ -18,6 +18,9 @@ struct pmgr_ps_test_reg { bool latched; /* bit 11 latched: on stops at clock-gated, off still reaches 0 */ bool latch_sticky; /* not even a PS reset clears it */ unsigned int reset_writes; /* writes with the PS reset bit */ + unsigned int flag_writes; /* writes that would clear a WAS_*GATED flag */ + unsigned int nwrites; /* every write; the first of them are in @writes */ + u32 writes[8]; }; static int pmgr_ps_test_read(void *ctx, unsigned int reg, unsigned int *val) @@ -46,6 +49,9 @@ static int pmgr_ps_test_write(void *ctx, unsigned int reg, unsigned int val) u32 parent = r->val & APPLE_PMGR_BUSY; u32 actual; + if (r->nwrites < ARRAY_SIZE(r->writes)) + r->writes[r->nwrites] = val; + r->nwrites++; if (val & APPLE_PMGR_PS_RESET) { r->reset_writes++; if (r->latched && !r->latch_sticky) { @@ -69,6 +75,8 @@ static int pmgr_ps_test_write(void *ctx, unsigned int reg, unsigned int val) r->busy_writes++; if (val & APPLE_PMGR_AUTO_ENABLE) r->auto_writes++; + if (val & APPLE_PMGR_FLAGS) + r->flag_writes++; r->val = (val & ~(APPLE_PMGR_PS_ACTUAL | APPLE_PMGR_BUSY)) | parent | FIELD_PREP(APPLE_PMGR_PS_ACTUAL, actual); return 0; @@ -83,11 +91,11 @@ static const struct regmap_config pmgr_ps_test_regmap = { .fast_io = true, }; -/* A domain in power state @pstate, actual and target, on a device of its own */ -static struct apple_pmgr_ps *pmgr_ps_test_domain(struct kunit *test, u32 pstate, - bool no_auto_pm, struct pmgr_ps_test_reg **reg) +/* A domain in power state @pstate, actual and target, on a device of its own, @name */ +static struct apple_pmgr_ps *pmgr_ps_test_named_domain(struct kunit *test, const char *name, + u32 pstate, bool no_auto_pm, + struct pmgr_ps_test_reg **reg) { - static const char *const names[] = { "apple-pmgr-ps-auto", "apple-pmgr-ps-no-auto" }; struct pmgr_ps_test_reg *r; struct apple_pmgr_ps *ps; struct device *dev; @@ -96,7 +104,7 @@ static struct apple_pmgr_ps *pmgr_ps_test_domain(struct kunit *test, u32 pstate, KUNIT_ASSERT_NOT_NULL(test, r); r->val = FIELD_PREP(APPLE_PMGR_PS_TARGET, pstate) | FIELD_PREP(APPLE_PMGR_PS_ACTUAL, pstate); - dev = kunit_device_register(test, names[no_auto_pm]); + dev = kunit_device_register(test, name); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); ps = kunit_kzalloc(test, sizeof(*ps), GFP_KERNEL); KUNIT_ASSERT_NOT_NULL(test, ps); @@ -109,6 +117,14 @@ static struct apple_pmgr_ps *pmgr_ps_test_domain(struct kunit *test, u32 pstate, return ps; } +static struct apple_pmgr_ps *pmgr_ps_test_domain(struct kunit *test, u32 pstate, + bool no_auto_pm, struct pmgr_ps_test_reg **reg) +{ + static const char *const names[] = { "apple-pmgr-ps-auto", "apple-pmgr-ps-no-auto" }; + + return pmgr_ps_test_named_domain(test, names[no_auto_pm], pstate, no_auto_pm, reg); +} + /* Powering on enables automatic PM, unless the domain is apple,no-auto-pm. */ static void pmgr_ps_power_on_test(struct kunit *test) { @@ -544,6 +560,272 @@ static void pmgr_ps_consumer_refused_test(struct kunit *test) APPLE_PMGR_PS_ACTIVE); } +/* + * A powered-on domain with its reset controller, as probe registers it, on + * a device called @name. + */ +static struct apple_pmgr_ps *pmgr_ps_test_reset_domain(struct kunit *test, const char *name, + struct pmgr_ps_test_reg **reg) +{ + struct apple_pmgr_ps *ps = pmgr_ps_test_named_domain(test, name, APPLE_PMGR_PS_ACTIVE, + false, reg); + + spin_lock_init(&ps->genpd.slock); + ps->genpd.status = GENPD_STATE_ON; + ps->offset = 0x100; + ps->rcdev.ops = &apple_pmgr_reset_ops; + ps->rcdev.nr_resets = 1; + ps->rcdev.of_xlate = apple_pmgr_reset_xlate; + return ps; +} + +/* + * The register writes since the log was last cleared were exactly two, with + * DEV_DISABLE and RESET as in @first and then as in @second. Clears the log. + */ +static void pmgr_ps_test_expect_writes(struct kunit *test, struct pmgr_ps_test_reg *r, + u32 first, u32 second) +{ + const u32 mask = APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET; + + KUNIT_EXPECT_EQ(test, r->nwrites, 2u); + KUNIT_EXPECT_EQ(test, r->writes[0] & mask, first); + KUNIT_EXPECT_EQ(test, r->writes[1] & mask, second); + r->nwrites = 0; + memset(r->writes, 0, sizeof(r->writes)); +} + +/* + * Assert quiesces, then resets; deassert releases the reset, then the + * quiesce; status reads the reset back. + */ +static void pmgr_ps_reset_assert_deassert_test(struct kunit *test) +{ + const struct of_phandle_args no_args = {}; + const struct of_phandle_args args = { .args_count = 2, .args = { 7, 9 } }; + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, "apple-pmgr-ps-reset", &r); + + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 0); + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), 0); + /* DEV_DISABLE in a write of its own, before the one that sets RESET. */ + pmgr_ps_test_expect_writes(test, r, APPLE_PMGR_DEV_DISABLE, + APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET); + KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_DEV_DISABLE); + KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_RESET); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 1); + /* The power state is left alone. */ + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_TARGET, r->val), APPLE_PMGR_PS_ACTIVE); + + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + /* RESET released while the block is still quiesced, DEV_DISABLE after. */ + pmgr_ps_test_expect_writes(test, r, APPLE_PMGR_DEV_DISABLE, 0); + KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_DEV_DISABLE); + KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_RESET); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 0); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_TARGET, r->val), APPLE_PMGR_PS_ACTIVE); + KUNIT_EXPECT_EQ(test, r->reset_writes, 0u); + + /* A pulse ends deasserted; the T8132 deassert delay changes nothing else. */ + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), 0); + KUNIT_EXPECT_FALSE(test, r->val & (APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET)); + ps->reset_time_us = APPLE_PMGR_T8132_RESET_TIME; + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), 0); + KUNIT_EXPECT_FALSE(test, r->val & (APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET)); + + /* + * A domain has one reset line, 0. Probe registers the controller with + * no reset cells, so the core passes no arguments; xlate would not + * read any either. + */ + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_xlate(&ps->rcdev, &no_args), 0); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_xlate(&ps->rcdev, &args), 0); +} + +/* The WAS_*GATED flags are write-one-to-clear: reset writes never set them. */ +static void pmgr_ps_reset_keeps_flags_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, "apple-pmgr-ps-reset", &r); + + r->val |= APPLE_PMGR_FLAGS; + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), 0); + KUNIT_EXPECT_EQ(test, r->flag_writes, 0u); + r->val |= APPLE_PMGR_FLAGS; + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + KUNIT_EXPECT_EQ(test, r->flag_writes, 0u); + r->val |= APPLE_PMGR_FLAGS; + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), 0); + KUNIT_EXPECT_EQ(test, r->flag_writes, 0u); +} + +/* A domain the boot loader or firmware owns refuses every reset operation. */ +static void pmgr_ps_reset_refused_test(struct kunit *test) +{ + static const char *const names[] = { + "apple-pmgr-ps-reset-firmware", "apple-pmgr-ps-reset-inherited", + }; + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps; + unsigned int owner; + u32 val; + + for (owner = 0; owner < 2; owner++) { + ps = pmgr_ps_test_reset_domain(test, names[owner], &r); + if (owner) + ps->inherited_on = true; + else + ps->firmware_owned = true; + r->val |= APPLE_PMGR_RESET; + val = r->val; + + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), -EPERM); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), -EPERM); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), -EPERM); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), -EPERM); + KUNIT_EXPECT_EQ(test, r->val, val); + KUNIT_EXPECT_EQ(test, r->nwrites, 0u); + } +} + +/* + * With the idle wait before reset (T8132), the reset goes in only once the + * block is idle; a block that stays busy is never reset. + */ +static void pmgr_ps_reset_idle_wait_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, "apple-pmgr-ps-reset", &r); + + ps->needs_reset_idle_wait = true; + /* Idle: the wait passes and the reset goes in. */ + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), 0); + KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_RESET); + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + + /* + * Busy until the third read, which is the second of the wait (the + * quiesce write reads the register first): the wait polls, and the + * write that sets RESET follows the read that found the block idle. + */ + r->nwrites = 0; + r->val |= APPLE_PMGR_BUSY; + r->parent_reads = 3; + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), 0); + KUNIT_EXPECT_EQ(test, r->parent_reads, 0u); + KUNIT_EXPECT_TRUE(test, r->writes[0] & APPLE_PMGR_BUSY); + KUNIT_EXPECT_FALSE(test, r->writes[1] & APPLE_PMGR_BUSY); + pmgr_ps_test_expect_writes(test, r, APPLE_PMGR_DEV_DISABLE, + APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET); + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + + /* Busy for good: quiesced, but not reset, and the lock is released. */ + r->nwrites = 0; + r->parent_stuck = true; + r->val |= APPLE_PMGR_BUSY; + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, r->nwrites, 1u); + KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_DEV_DISABLE); + KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_RESET); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 0); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), -ETIMEDOUT); + KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_RESET); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_DEV_DISABLE); +} + +/* Without the idle wait, a block that stays busy is reset all the same. */ +static void pmgr_ps_reset_busy_no_idle_wait_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, "apple-pmgr-ps-reset", &r); + + r->parent_stuck = true; + r->val |= APPLE_PMGR_BUSY; + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), 0); + pmgr_ps_test_expect_writes(test, r, APPLE_PMGR_DEV_DISABLE, + APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET); + KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_BUSY); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 1); + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), 0); + KUNIT_EXPECT_FALSE(test, r->val & (APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET)); +} + +/* Forced-on auto-managed words write target 0xf, wait for actual 0xf, then AUTO_ENABLE. */ +static void pmgr_ps_auto_enable_test(struct kunit *test) +{ + static const u32 seq[][2] = { + { 0, 0x0f0000ff }, + { 0, 0x1f0000ff }, + }; + struct pmgr_ps_test_bank *b; + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps; + + ps = pmgr_ps_test_consumer(test, 0x0f0003ff, &b); + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_auto_enable(ps->regmap, 0), 1); + pmgr_ps_test_expect_log(test, b, seq, ARRAY_SIZE(seq)); + KUNIT_EXPECT_TRUE(test, b->word[0] & APPLE_PMGR_AUTO_ENABLE); + + /* Delayed actual-state ACK completes before AUTO_ENABLE is written. */ + ps = pmgr_ps_test_domain(test, APPLE_PMGR_PS_CLKGATE, false, &r); + r->val = FIELD_PREP(APPLE_PMGR_PS_TARGET, APPLE_PMGR_PS_ACTIVE) | + FIELD_PREP(APPLE_PMGR_PS_ACTUAL, APPLE_PMGR_PS_CLKGATE) | + APPLE_PMGR_FLAGS; + r->active_reads = 3; + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_auto_enable(ps->regmap, 0), 1); + KUNIT_EXPECT_EQ(test, r->active_reads, 0U); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_ACTUAL, r->val), APPLE_PMGR_PS_ACTIVE); + KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_AUTO_ENABLE); + KUNIT_EXPECT_EQ(test, r->auto_writes, 1U); + KUNIT_EXPECT_EQ(test, r->busy_writes, 0U); +} + +/* Fused-off, already-AUTO, and reset/disabled words are left completely untouched. */ +static void pmgr_ps_auto_enable_skip_test(struct kunit *test) +{ + static const u32 skipped[] = { + 0x0f000300, /* fused off (J616c dcs_24-31) */ + 0x1f0000ff, /* already on AUTO_ENABLE */ + 0x0f0000ff | APPLE_PMGR_RESET, /* held in reset */ + 0x0f0000ff | APPLE_PMGR_PS_RESET, /* PS reset set */ + 0x0f0000ff | APPLE_PMGR_DEV_DISABLE, /* device disabled */ + }; + struct pmgr_ps_test_bank *b; + struct apple_pmgr_ps *ps; + + for (unsigned int i = 0; i < ARRAY_SIZE(skipped); i++) { + ps = pmgr_ps_test_consumer(test, skipped[i], &b); + KUNIT_EXPECT_EQ_MSG(test, apple_pmgr_ps_auto_enable(ps->regmap, 0), 0, + "word %#x", skipped[i]); + KUNIT_EXPECT_EQ_MSG(test, b->nr_log, 0U, "word %#x", skipped[i]); + KUNIT_EXPECT_EQ_MSG(test, b->word[0], skipped[i], "word %#x", skipped[i]); + } +} + +/* Stuck actual state times out without setting AUTO_ENABLE; read errors propagate. */ +static void pmgr_ps_auto_enable_fail_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps; + + ps = pmgr_ps_test_named_domain(test, "apple-pmgr-ps-auto-stuck", + APPLE_PMGR_PS_CLKGATE, false, &r); + r->val = FIELD_PREP(APPLE_PMGR_PS_TARGET, APPLE_PMGR_PS_ACTIVE) | + FIELD_PREP(APPLE_PMGR_PS_ACTUAL, APPLE_PMGR_PS_CLKGATE); + r->stuck = true; + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_auto_enable(ps->regmap, 0), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, r->auto_writes, 0U); + KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_AUTO_ENABLE); + + ps = pmgr_ps_test_named_domain(test, "apple-pmgr-ps-auto-err", + APPLE_PMGR_PS_ACTIVE, false, &r); + r->parent_read_error = true; + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_auto_enable(ps->regmap, 0), -EIO); + KUNIT_EXPECT_EQ(test, r->auto_writes, 0U); +} + static struct kunit_case pmgr_ps_test_cases[] = { KUNIT_CASE(pmgr_ps_power_on_test), KUNIT_CASE(pmgr_ps_power_off_undo_test), @@ -563,6 +845,14 @@ static struct kunit_case pmgr_ps_test_cases[] = { KUNIT_CASE(pmgr_ps_consumer_retention_mask_test), KUNIT_CASE(pmgr_ps_consumer_plain_test), KUNIT_CASE(pmgr_ps_consumer_refused_test), + KUNIT_CASE(pmgr_ps_reset_assert_deassert_test), + KUNIT_CASE(pmgr_ps_reset_keeps_flags_test), + KUNIT_CASE(pmgr_ps_reset_refused_test), + KUNIT_CASE(pmgr_ps_reset_idle_wait_test), + KUNIT_CASE(pmgr_ps_reset_busy_no_idle_wait_test), + KUNIT_CASE(pmgr_ps_auto_enable_test), + KUNIT_CASE(pmgr_ps_auto_enable_skip_test), + KUNIT_CASE(pmgr_ps_auto_enable_fail_test), {} }; diff --git a/drivers/pmdomain/apple/pmgr-pwrstate.c b/drivers/pmdomain/apple/pmgr-pwrstate.c index 6745b4916365b6..1b7295fbe243c9 100644 --- a/drivers/pmdomain/apple/pmgr-pwrstate.c +++ b/drivers/pmdomain/apple/pmgr-pwrstate.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -79,6 +80,8 @@ struct apple_pmgr_ps { bool sleep_wakeup_path; /* Never enable automatic power management (apple,no-auto-pm). */ bool no_auto_pm; + /* Hardware auto-managed domain armed early at boot (apple,auto-managed). */ + bool auto_managed; bool inherited_on; bool no_auto_enable; bool needs_reset_idle_wait; @@ -437,7 +440,7 @@ static int apple_pmgr_ps_power_off(struct generic_pm_domain *genpd) if (ps->firmware_owned) return 0; - if (ps->inherited_on) + if (ps->inherited_on || ps->auto_managed) return -EBUSY; /* A live coprocessor keeps this domain through system sleep. */ if (ps->sleep_retained && ps->system_sleep) @@ -478,7 +481,7 @@ int apple_pmgr_ps_verify_state(struct device *domain_dev, bool on) !(genpd->flags & GENPD_FLAG_IRQ_SAFE)) return -EOPNOTSUPP; ps = genpd_to_apple_pmgr_ps(genpd); - if (ps->firmware_owned || ps->inherited_on) + if (ps->firmware_owned || ps->inherited_on || ps->auto_managed) return -EPERM; if (!on) mask |= APPLE_PMGR_AUTO_ENABLE; @@ -516,7 +519,7 @@ int apple_pmgr_ps_cycle(struct device_node *np) ret = -EPROBE_DEFER; goto out; } - if (ps->firmware_owned || ps->inherited_on) { + if (ps->firmware_owned || ps->inherited_on || ps->auto_managed) { ret = -EPERM; goto out; } @@ -591,7 +594,7 @@ static int apple_pmgr_ps_suspend_noirq(struct device *dev) u32 reg; ps->sleep_raised_by_other = false; - if (ps->firmware_owned || ps->inherited_on) + if (ps->firmware_owned || ps->inherited_on || ps->auto_managed) return 0; spin_lock_irqsave(&ps->genpd.slock, flags); @@ -639,8 +642,27 @@ static int apple_pmgr_ps_resume_noirq(struct device *dev) u32 reg; int ret; - if (!pm_resume_via_firmware() || ps->firmware_owned || ps->inherited_on || - ps->sleep_driver_owned || apple_sleep_domain_is_down(dev->of_node)) + if (!pm_resume_via_firmware() || ps->firmware_owned) + return 0; + + /* + * The wake resets each word's minimum state with the rest, and probe is the only + * place that sets apple,min-state: put it back, whoever owns the domain now. With + * AUTO_ENABLE on and a minimum of 0, the hardware power-gates a domain whose + * coprocessor is only waiting in WFI, as a display coprocessor's CPU does. + */ + if (ps->min_state && ps->min_state <= APPLE_PMGR_PS_ACTIVE) { + spin_lock_irqsave(&ps->genpd.slock, flags); + if (!regmap_read(ps->regmap, ps->offset, ®) && + FIELD_GET(APPLE_PMGR_PS_MIN, reg) != ps->min_state) + regmap_update_bits(ps->regmap, ps->offset, + APPLE_PMGR_FLAGS | APPLE_PMGR_PS_MIN, + FIELD_PREP(APPLE_PMGR_PS_MIN, ps->min_state)); + spin_unlock_irqrestore(&ps->genpd.slock, flags); + } + + if (ps->inherited_on || ps->auto_managed || ps->sleep_driver_owned || + apple_sleep_domain_is_down(dev->of_node)) return 0; spin_lock_irqsave(&ps->genpd.slock, flags); @@ -680,7 +702,7 @@ static int apple_pmgr_reset_assert(struct reset_controller_dev *rcdev, unsigned int ret; u32 reg; - if (ps->firmware_owned || ps->inherited_on) + if (ps->firmware_owned || ps->inherited_on || ps->auto_managed) return -EPERM; spin_lock_irqsave(&ps->genpd.slock, flags); @@ -718,7 +740,7 @@ static int apple_pmgr_reset_deassert(struct reset_controller_dev *rcdev, unsigne struct apple_pmgr_ps *ps = rcdev_to_apple_pmgr_ps(rcdev); unsigned long flags; - if (ps->firmware_owned || ps->inherited_on) + if (ps->firmware_owned || ps->inherited_on || ps->auto_managed) return -EPERM; if (ps->reset_time_us == APPLE_PMGR_T8132_RESET_TIME) @@ -760,7 +782,7 @@ static int apple_pmgr_reset_status(struct reset_controller_dev *rcdev, unsigned struct apple_pmgr_ps *ps = rcdev_to_apple_pmgr_ps(rcdev); u32 reg = 0; - if (ps->firmware_owned || ps->inherited_on) + if (ps->firmware_owned || ps->inherited_on || ps->auto_managed) return -EPERM; regmap_read(ps->regmap, ps->offset, ®); @@ -855,12 +877,15 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) t8132 = of_device_is_compatible(node, "apple,t8132-pmgr-pwrstate"); /* - * On the M4 firmware path some domains are the firmware's, which Linux - * cannot access. The early compatibility adapter supplies the explicit - * status and ownership before population; fail closed if it was not - * enabled. Other firmware keeps the tree's own domain descriptions. + * Some T8132 power states are the firmware's, which Linux cannot + * access. The platform handoff supplies the explicit status and + * ownership of every one before population, on any firmware: fail + * closed on a state it did not mark. Keep the same protection for + * qualified firmware and the Airs even without the handoff. */ - if (t8132 && apple_t8132_firmware_path() && !of_property_present(node, "status")) + if (t8132 && (IS_ENABLED(CONFIG_APPLE_T8132_PLATFORM_HANDOFF) || + apple_t8132_firmware_path()) && + !of_property_present(node, "status")) return dev_err_probe(dev, -ENODEV, "missing M4 power-domain policy\n"); tvm = of_parse_phandle(node, "power-domains", 0); @@ -951,6 +976,9 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) ps->sleep_retained = of_property_read_bool(node, "apple,sleep-retained"); ps->sleep_driver_owned = of_property_read_bool(node, "apple,sleep-driver-owned"); ps->sleep_wakeup_path = of_property_read_bool(node, "apple,sleep-wakeup-path"); + /* A cold-started coprocessor CPU must not be gated behind its firmware. */ + ps->no_auto_pm = of_property_read_bool(node, "apple,no-auto-pm"); + ps->auto_managed = of_property_read_bool(node, "apple,auto-managed"); /* * Only T8132 hands over inherited-on domains with this contract. Older * M3 device trees carry the property with another meaning; keep them @@ -958,7 +986,7 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) */ ps->inherited_on = t8132 && of_property_read_bool(node, "apple,inherited-on"); if (ps->inherited_on && - (ps->firmware_owned || ps->sleep_retained || + (ps->firmware_owned || ps->sleep_retained || ps->auto_managed || of_property_present(node, "apple,min-state") || of_property_present(node, "apple,always-on") || of_property_present(node, "apple,force-disable") || @@ -966,8 +994,13 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) of_property_present(node, "apple,externally-clocked"))) return dev_err_probe(dev, -EINVAL, "conflicting inherited power policy\n"); + if (ps->auto_managed && + (ps->firmware_owned || ps->no_auto_pm || ps->no_auto_enable || t8132)) + return dev_err_probe(dev, -EINVAL, "conflicting auto-managed power policy\n"); + ret = of_property_read_u32(node, "apple,min-state", &ps->min_state); - if (ret == 0 && ps->min_state <= APPLE_PMGR_PS_ACTIVE && !ps->firmware_owned) + if (ret == 0 && ps->min_state <= APPLE_PMGR_PS_ACTIVE && + !ps->firmware_owned && !ps->auto_managed) regmap_update_bits(regmap, ps->offset, APPLE_PMGR_FLAGS | APPLE_PMGR_PS_MIN, FIELD_PREP(APPLE_PMGR_PS_MIN, ps->min_state)); @@ -980,9 +1013,6 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) if (of_property_read_bool(node, "apple,externally-clocked")) ps->externally_clocked = true; - /* A cold-started coprocessor CPU must not be gated behind its firmware. */ - ps->no_auto_pm = of_property_read_bool(node, "apple,no-auto-pm"); - /* * An inherited-on domain has readable state but no transition ownership. * A firmware-owned domain need not have a CPU-accessible state register; @@ -1003,9 +1033,19 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) return dev_err_probe(dev, ret, "cannot read power state\n"); active = ret; } - /* Legacy handoff DTs must also keep the throttle controller powered. */ - if (!ps->firmware_owned && !ps->inherited_on && - apple_pmgr_ps_always_on(node, ps->offset, name)) { + if (ps->auto_managed) { + if (!active) { + if (apple_pmgr_ps_always_on(node, ps->offset, name)) + return dev_err_probe(dev, -EIO, + "always-on auto-managed domain %s is off at boot\n", + name); + dev_dbg(dev, "auto-managed domain %s is off at boot, skipping\n", name); + return -ENODEV; + } + ps->genpd.flags |= GENPD_FLAG_ALWAYS_ON; + } else if (!ps->firmware_owned && !ps->inherited_on && + apple_pmgr_ps_always_on(node, ps->offset, name)) { + /* Legacy handoff DTs must also keep the throttle controller powered. */ ps->genpd.flags |= GENPD_FLAG_ALWAYS_ON; if (!active) { /* @@ -1035,7 +1075,8 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) } /* Turn on auto-PM if the domain is already on, unless it must stay off */ - if (active && !ps->firmware_owned && !ps->inherited_on && !ps->no_auto_enable) + if (active && !ps->firmware_owned && !ps->inherited_on && + !ps->no_auto_enable && !ps->auto_managed) regmap_update_bits(regmap, ps->offset, APPLE_PMGR_FLAGS | APPLE_PMGR_AUTO_ENABLE, ps->no_auto_pm ? 0 : APPLE_PMGR_AUTO_ENABLE); @@ -1390,6 +1431,124 @@ static const struct of_device_id apple_pmgr_ps_of_match[] = { MODULE_DEVICE_TABLE(of, apple_pmgr_ps_of_match); +/* + * Switch a power-state word left forced on by the boot loader (target 0xf, + * AUTO_ENABLE clear) to hardware automatic power management, early at boot, + * before the PMP starts: write target 0xf, wait for actual 0xf, then set + * AUTO_ENABLE. Words that are fused off, not forced on, held in reset, or + * already on AUTO_ENABLE are left untouched (returns 0). Returns 1 if + * switched, or a negative errno on read/write error or timeout. + */ +static int apple_pmgr_ps_auto_enable(struct regmap *regmap, u32 offset) +{ + u32 v; + int ret; + + ret = regmap_read(regmap, offset, &v); + if (ret) + return ret; + + if (FIELD_GET(APPLE_PMGR_PS_TARGET, v) != APPLE_PMGR_PS_ACTIVE || + (v & (APPLE_PMGR_AUTO_ENABLE | APPLE_PMGR_RESET | + APPLE_PMGR_PS_RESET | APPLE_PMGR_DEV_DISABLE))) + return 0; + + ret = regmap_write(regmap, offset, + (v & ~(APPLE_PMGR_FLAGS | APPLE_PMGR_BUSY | + APPLE_PMGR_PS_TARGET)) | + FIELD_PREP(APPLE_PMGR_PS_TARGET, APPLE_PMGR_PS_ACTIVE)); + if (ret) + return ret; + + ret = regmap_read_poll_timeout_atomic(regmap, offset, v, + FIELD_GET(APPLE_PMGR_PS_ACTUAL, v) == + APPLE_PMGR_PS_ACTIVE, + 1, APPLE_PMGR_PS_PARENT_TIMEOUT); + if (ret) + return ret; + + ret = regmap_write(regmap, offset, + (v & ~(APPLE_PMGR_FLAGS | APPLE_PMGR_BUSY)) | + APPLE_PMGR_AUTO_ENABLE); + return ret ?: 1; +} + +static const struct of_device_id apple_pmgr_of_match[] __initconst = { + { .compatible = "apple,t8103-pmgr" }, + { .compatible = "apple,pmgr" }, + {} +}; + +static bool __init apple_pmgr_ps_node_is_auto_managed(struct device_node *np) +{ + return of_match_node(apple_pmgr_ps_of_match, np) && + of_property_read_bool(np, "apple,auto-managed") && + !of_property_read_bool(np, "apple,no-auto-pm") && + !of_property_read_bool(np, "apple,firmware-owned") && + !of_property_read_bool(np, "apple,inherited-on") && + !of_device_is_compatible(np, "apple,t8132-pmgr-pwrstate"); +} + +/* + * Arm hardware automatic power management for DT-marked domains early at + * boot, before platform drivers (in particular the PMP) start: enabling + * AUTO_ENABLE on memory and fabric domains after the PMP is running freezes + * the SoC. + */ +static int __init apple_pmgr_ps_auto_init(void) +{ + struct device_node *pmgr_np; + unsigned int done = 0, failed = 0; + + for_each_matching_node(pmgr_np, apple_pmgr_of_match) { + struct regmap *regmap = NULL; + struct device_node *child; + + if (!of_device_is_available(pmgr_np)) + continue; + + for_each_available_child_of_node(pmgr_np, child) { + u32 offset; + int ret; + + if (!apple_pmgr_ps_node_is_auto_managed(child)) + continue; + + if (of_property_read_u32(child, "reg", &offset)) { + pr_warn("apple-pmgr-pwrstate: %pOF: missing reg property\n", + child); + continue; + } + + if (!regmap) { + regmap = syscon_node_to_regmap(pmgr_np); + if (IS_ERR(regmap)) { + pr_warn("apple-pmgr-pwrstate: %pOF: cannot map PMGR: %ld\n", + pmgr_np, PTR_ERR(regmap)); + of_node_put(child); + break; + } + } + + ret = apple_pmgr_ps_auto_enable(regmap, offset); + if (ret > 0) { + done++; + } else if (ret < 0) { + failed++; + pr_warn("apple-pmgr-pwrstate: %pOF: auto-enable failed: %d\n", + child, ret); + } + } + } + + if (done || failed) + pr_info("apple-pmgr-pwrstate: %u auto-managed domains enabled, %u failed\n", + done, failed); + + return 0; +} +arch_initcall(apple_pmgr_ps_auto_init); + static const struct dev_pm_ops apple_pmgr_ps_pm_ops = { LATE_SYSTEM_SLEEP_PM_OPS(apple_pmgr_ps_suspend_late, apple_pmgr_ps_resume_early) NOIRQ_SYSTEM_SLEEP_PM_OPS(apple_pmgr_ps_suspend_noirq, apple_pmgr_ps_resume_noirq) diff --git a/drivers/pmdomain/apple/pmp-report-start-test.c b/drivers/pmdomain/apple/pmp-report-start-test.c index 36cf2c87eb128a..b6a8daa78ec745 100644 --- a/drivers/pmdomain/apple/pmp-report-start-test.c +++ b/drivers/pmdomain/apple/pmp-report-start-test.c @@ -6,6 +6,9 @@ * bind, no ready status, no acknowledgment), a consumer's own timeout and * the teardown of the provider can be driven without Apple hardware. * + * The fast die-temperature effort is read from a report in memory, too: its + * lanes, the reports that have none or do not run, and the T8142 layout. + * * Included by pmp-report.c. */ @@ -407,4 +410,196 @@ static struct kunit_suite pmp_start_suite = { .test_cases = pmp_start_cases, }; -kunit_test_suite(pmp_start_suite); +/* + * A report in memory with the PMP's status in its first word and the fast + * die-temperature efforts in an entry of its own: 16 bytes, of which the + * low 32 bits hold the lanes. + */ +#define PFD_STATUS 0x08 +#define PFD_EFFORT 0x10 +#define PFD_LANES 0xa4c30f5aU +#define PFD_OTHER 0x1122334400000000ULL + +struct pfd { + struct apple_pmp_report rep; + struct apple_pmp_report_offsets offsets; + struct device dev; + struct device_node node; + u64 regs[4]; +}; + +static void pfd_remove(void *data) +{ + struct pfd *t = data; + + mutex_lock(&apple_pmp_reports_lock); + list_del_rcu(&t->rep.list); + mutex_unlock(&apple_pmp_reports_lock); + synchronize_rcu(); +} + +/* A running report with @lanes fast-die lanes, published as probe does. */ +static struct pfd *pfd_new(struct kunit *test, u32 lanes) +{ + struct pfd *t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, t); + t->offsets.status = PFD_STATUS; + t->offsets.fast_die = lanes ? PFD_EFFORT : 0; + t->offsets.fast_die_lanes = lanes; + t->dev.of_node = &t->node; + t->rep.dev = &t->dev; + t->rep.offsets = &t->offsets; + t->rep.base = (__force void __iomem *)t->regs; + spin_lock_init(&t->rep.lock); + + t->regs[PFD_STATUS / sizeof(u64)] = PMP_REPORT_READY; + t->regs[PFD_EFFORT / sizeof(u64)] = PFD_OTHER | PFD_LANES; + t->regs[PFD_EFFORT / sizeof(u64) + 1] = ~0ULL; + + mutex_lock(&apple_pmp_reports_lock); + list_add_tail_rcu(&t->rep.list, &apple_pmp_reports); + mutex_unlock(&apple_pmp_reports_lock); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, pfd_remove, t), 0); + return t; +} + +static int pfd_effort(struct pfd *t, unsigned int lane, u8 *effort) +{ + *effort = 0xee; + return apple_pmp_report_fast_die_effort(&t->node, lane, effort); +} + +/* Each lane is one byte of the low word, read 32 or 64 bits wide. */ +static void pmp_fast_die_lanes_test(struct kunit *test) +{ + struct pfd *t = pfd_new(test, 3); + u8 effort; + int wide; + + for (wide = 0; wide < 2; wide++) { + t->offsets.fast_die_wide = wide; + t->offsets.fast_die_lanes = 3; + KUNIT_EXPECT_EQ(test, pfd_effort(t, 0, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x5a); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 1, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x0f); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 2, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0xc3); + + /* Past the report's lanes: refused, nothing is stored. */ + KUNIT_EXPECT_EQ(test, pfd_effort(t, 3, &effort), -EINVAL); + KUNIT_EXPECT_EQ(test, effort, 0xee); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 4, &effort), -EINVAL); + KUNIT_EXPECT_EQ(test, pfd_effort(t, UINT_MAX, &effort), -EINVAL); + + t->offsets.fast_die_lanes = 4; + KUNIT_EXPECT_EQ(test, pfd_effort(t, 3, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0xa4); + } +} + +/* A stopped PMP reads 0, which would ask for no limit: no effort then. */ +static void pmp_fast_die_running_test(struct kunit *test) +{ + struct pfd *t = pfd_new(test, 2); + u64 *status = &t->regs[PFD_STATUS / sizeof(u64)]; + u8 effort; + + WRITE_ONCE(*status, 0); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 0, &effort), -EAGAIN); + KUNIT_EXPECT_EQ(test, effort, 0xee); + t->offsets.running_any = true; + KUNIT_EXPECT_EQ(test, pfd_effort(t, 0, &effort), -EAGAIN); + KUNIT_EXPECT_EQ(test, effort, 0xee); + + /* Status bits other than "ready" only count where the SoC says so. */ + WRITE_ONCE(*status, BIT_ULL(36)); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 1, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x0f); + t->offsets.running_any = false; + KUNIT_EXPECT_EQ(test, pfd_effort(t, 1, &effort), -EAGAIN); + + WRITE_ONCE(*status, BIT_ULL(36) | PMP_REPORT_READY); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 1, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x0f); + + /* A lane the report does not have is the caller's error, running or not. */ + WRITE_ONCE(*status, 0); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 2, &effort), -EINVAL); +} + +/* The report is found by its node; one without the entry says so. */ +static void pmp_fast_die_lookup_test(struct kunit *test) +{ + struct pfd *none = pfd_new(test, 0); + struct pfd *a = pfd_new(test, 2); + struct pfd *b = pfd_new(test, 2); + struct device_node *unbound; + u8 effort = 0xee; + + unbound = kunit_kzalloc(test, sizeof(*unbound), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, unbound); + KUNIT_EXPECT_EQ(test, apple_pmp_report_fast_die_effort(unbound, 0, &effort), + -EPROBE_DEFER); + KUNIT_EXPECT_EQ(test, effort, 0xee); + + b->regs[PFD_EFFORT / sizeof(u64)] = 0x7781; + KUNIT_EXPECT_EQ(test, pfd_effort(a, 0, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x5a); + KUNIT_EXPECT_EQ(test, pfd_effort(b, 0, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x81); + KUNIT_EXPECT_EQ(test, pfd_effort(b, 1, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x77); + + /* No entry: unsupported whatever the lane and the PMP's state. */ + KUNIT_EXPECT_EQ(test, pfd_effort(none, 0, &effort), -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, effort, 0xee); + none->regs[PFD_STATUS / sizeof(u64)] = 0; + KUNIT_EXPECT_EQ(test, pfd_effort(none, 0, &effort), -EOPNOTSUPP); +} + +/* + * The T8142 report as its PMP's table of PTD entries gives it: PMP-STATUS 1, + * FAST-DIE-CE 15 (E, P), SOC-DEV-PS-REQ 39, SOC-DEV-PS-ACK 47 and + * SOC-DEV-DVFS 55 to 70. An entry is read in 16 bytes from the base and + * written in 8 bytes from the update aperture. + */ +static void pmp_fast_die_t8142_test(struct kunit *test) +{ + const struct apple_pmp_report_offsets *offs = NULL; + const struct of_device_id *id; + + for (id = apple_pmp_report_of_match; id->compatible[0]; id++) + if (!strcmp(id->compatible, "apple,t8142-pmp-v2-report")) + offs = id->data; + KUNIT_ASSERT_NOT_NULL(test, offs); + + KUNIT_EXPECT_EQ(test, offs->status, 1 * 16); + KUNIT_EXPECT_EQ(test, offs->fast_die, 15 * 16); + KUNIT_EXPECT_EQ(test, offs->fast_die_lanes, 2); + KUNIT_EXPECT_TRUE(test, offs->fast_die_wide); + KUNIT_EXPECT_EQ(test, offs->tgt_read, 39 * 16); + KUNIT_EXPECT_EQ(test, offs->tgt_write, offs->update + 39 * 8); + KUNIT_EXPECT_EQ(test, offs->actual, 47 * 16); + KUNIT_EXPECT_EQ(test, offs->dvfs_first, 55); + KUNIT_EXPECT_EQ(test, offs->dvfs_first + offs->dvfs_count - 1, 70); + KUNIT_EXPECT_TRUE(test, offs->running_any); + KUNIT_EXPECT_TRUE(test, offs->defer_requests); + KUNIT_EXPECT_FALSE(test, offs->starts_pmp); +} + +static struct kunit_case pmp_fast_die_cases[] = { + KUNIT_CASE(pmp_fast_die_lanes_test), + KUNIT_CASE(pmp_fast_die_running_test), + KUNIT_CASE(pmp_fast_die_lookup_test), + KUNIT_CASE(pmp_fast_die_t8142_test), + {} +}; + +static struct kunit_suite pmp_fast_die_suite = { + .name = "apple-pmp-fast-die", + .test_cases = pmp_fast_die_cases, +}; + +kunit_test_suites(&pmp_start_suite, &pmp_fast_die_suite); diff --git a/drivers/pmdomain/apple/pmp-report.c b/drivers/pmdomain/apple/pmp-report.c index a96a9d57fa7368..76e72185bfbab9 100644 --- a/drivers/pmdomain/apple/pmp-report.c +++ b/drivers/pmdomain/apple/pmp-report.c @@ -35,7 +35,6 @@ #include #include #include -#include #include #include #include @@ -702,6 +701,43 @@ static int apple_pmp_report_wait_t6030_14(struct device *supplier, unsigned int return ret; } +/* + * A T8122 PMP (apple,t8122-pmp-v2, chosen by the dispatch below) behind the GPU + * on its 14.8.3 firmware, for the M3 runtime (APPLE_T8122_GPU_PMP_LINK): the + * unique T8122 report linked to this PMP, and + * its display request (DISP, reg 7) READY and acknowledged before AGX, as on + * the 7.1.12 kernel that runtime was qualified with. + */ +static int apple_pmp_report_wait_t8122_14(struct device *supplier, unsigned int timeout_ms) +{ + struct device_node *np, *report = NULL, *pmp, *entry; + int ret; + + if (!IS_ENABLED(CONFIG_APPLE_T8122_GPU_PMP_LINK)) + return -ENODEV; + for_each_compatible_node(np, NULL, "apple,t8122-pmp-v2-report") { + if (report) { + of_node_put(np); + of_node_put(report); + return -ENODEV; + } + report = of_node_get(np); + } + if (!report || !of_device_is_available(report) || + of_property_count_u32_elems(report, "apple,pmp") != 1) { + of_node_put(report); + return -ENODEV; + } + pmp = of_parse_phandle(report, "apple,pmp", 0); + entry = apple_pmp_report_t6030_entry(report); + ret = pmp == supplier->of_node && entry ? + apple_pmp_report_wait_ready(entry, msecs_to_jiffies(timeout_ms)) : -ENODEV; + of_node_put(entry); + of_node_put(pmp); + of_node_put(report); + return ret; +} + /* The native 25G83 PMP starts through its supplier topology, after requests * are seeded. Its report is pinned against removal while readiness is read. */ @@ -711,13 +747,15 @@ int apple_pmp_report_wait_supplier_ready(struct device *supplier, unsigned int t struct platform_device *pdev; struct apple_pmp_report *rep; u64 status; - bool t8132 = apple_t8132_firmware_path() && - of_device_is_compatible(supplier->of_node, "apple,t8132-pmp-v2"); + bool t8132 = of_device_is_compatible(supplier->of_node, "apple,t8132-pmp-v2"); int ret; /* A declared report always takes the existing native25 path below. */ - if (!np && !of_property_present(supplier->of_node, "apple,pmp-report")) + if (!np && !of_property_present(supplier->of_node, "apple,pmp-report")) { + if (of_device_is_compatible(supplier->of_node, "apple,t8122-pmp-v2")) + return apple_pmp_report_wait_t8122_14(supplier, timeout_ms); return apple_pmp_report_wait_t6030_14(supplier, timeout_ms); + } if (!np || !of_device_is_compatible(np, t8132 ? "apple,t8132-pmp-v2-report" : "apple,j613-25g83-pmp-report")) { of_node_put(np); diff --git a/drivers/power/reset/Kconfig b/drivers/power/reset/Kconfig index bce996bbef28f5..3cc66edaf551a9 100644 --- a/drivers/power/reset/Kconfig +++ b/drivers/power/reset/Kconfig @@ -149,6 +149,19 @@ config POWER_RESET_MACSMC Say Y here if you have an Apple Silicon Mac. +config POWER_RESET_MACSMC_KUNIT_TEST + bool "KUnit tests for the Apple SMC reboot driver" if !KUNIT_ALL_TESTS + depends on POWER_RESET_MACSMC=y && KUNIT=y + depends on MFD_MACSMC_KUNIT_TEST && NVMEM + default KUNIT_ALL_TESTS + help + Build tests for the Apple SMC reboot driver: the MBSE key and the + boot_stage and shutdown_flag writes before a restart or power off, + the clearing of the boot error and panic counters, and the + ac_power_mode attribute's read-modify-write of the power-on policy + byte. A static stub replaces SMC writes and a RAM-backed NVMEM + device holds the PMU cells, so the tests need no Apple hardware. + config POWER_RESET_MSM bool "Qualcomm MSM power-off driver" depends on ARCH_QCOM diff --git a/drivers/power/reset/macsmc-reboot-test.c b/drivers/power/reset/macsmc-reboot-test.c new file mode 100644 index 00000000000000..e4db004ec6ec19 --- /dev/null +++ b/drivers/power/reset/macsmc-reboot-test.c @@ -0,0 +1,454 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SMC reboot driver: the MBSE key and NVMEM flag + * sequence before a restart or power off, the boot error and panic counters, + * and the ac_power_mode attribute over the PMU's power-on policy byte. + * + * SMC writes go to a static stub on apple_smc_write() (see + * MFD_MACSMC_KUNIT_TEST). The PMU cells are real NVMEM cells of a RAM-backed + * NVMEM device, found through a cell lookup table. + * + * Included by macsmc-reboot.c. + */ + +#include +#include +#include +#include +#include + +enum { + REBOOT_TEST_SHUTDOWN_FLAG, + REBOOT_TEST_BOOT_STAGE, + REBOOT_TEST_BOOT_ERROR_COUNT, + REBOOT_TEST_PANIC_COUNT, + REBOOT_TEST_PM_SETTING, + REBOOT_TEST_NR_CELLS, +}; + +static const char * const macsmc_reboot_test_cells[] = { + [REBOOT_TEST_SHUTDOWN_FLAG] = "shutdown_flag", + [REBOOT_TEST_BOOT_STAGE] = "boot_stage", + [REBOOT_TEST_BOOT_ERROR_COUNT] = "boot_error_count", + [REBOOT_TEST_PANIC_COUNT] = "panic_count", + [REBOOT_TEST_PM_SETTING] = "pm_setting", +}; + +struct macsmc_reboot_test_write { + u32 where; /* SMC key, or NVMEM offset */ + size_t size; + u32 val; +}; + +struct macsmc_reboot_test { + struct apple_smc smc; + u8 shmem[256]; + struct macsmc_reboot reboot; + struct device *dev; + u8 nvmem[REBOOT_TEST_NR_CELLS]; + /* NVMEM writes and SMC writes, each in order */ + struct macsmc_reboot_test_write nv_writes[8]; + unsigned int nr_nv_writes; + struct macsmc_reboot_test_write smc_writes[4]; + unsigned int nr_smc_writes; + int smc_ret; + int fail_offset; + struct nvmem_cell_lookup lookups[REBOOT_TEST_NR_CELLS]; +}; + +static int macsmc_reboot_test_smc_write(struct apple_smc *smc, smc_key key, + const void *buf, size_t size) +{ + struct macsmc_reboot_test *ctx = container_of(smc, struct macsmc_reboot_test, smc); + struct macsmc_reboot_test_write *w; + + if (ctx->nr_smc_writes < ARRAY_SIZE(ctx->smc_writes)) { + w = &ctx->smc_writes[ctx->nr_smc_writes]; + w->where = key; + w->size = size; + w->val = 0; + memcpy(&w->val, buf, min(size, sizeof(w->val))); + } + ctx->nr_smc_writes++; + return ctx->smc_ret; +} + +static int macsmc_reboot_test_reg_read(void *priv, unsigned int offset, void *val, + size_t bytes) +{ + struct macsmc_reboot_test *ctx = priv; + + memcpy(val, ctx->nvmem + offset, bytes); + return 0; +} + +static int macsmc_reboot_test_reg_write(void *priv, unsigned int offset, void *val, + size_t bytes) +{ + struct macsmc_reboot_test *ctx = priv; + struct macsmc_reboot_test_write *w; + + if (offset == ctx->fail_offset) + return -EIO; + if (ctx->nr_nv_writes < ARRAY_SIZE(ctx->nv_writes)) { + w = &ctx->nv_writes[ctx->nr_nv_writes]; + w->where = offset; + w->size = bytes; + w->val = *(u8 *)val; + } + ctx->nr_nv_writes++; + memcpy(ctx->nvmem + offset, val, bytes); + return 0; +} + +static void macsmc_reboot_test_del_lookups(void *data) +{ + struct macsmc_reboot_test *ctx = data; + + nvmem_del_cell_lookups(ctx->lookups, ARRAY_SIZE(ctx->lookups)); +} + +KUNIT_DEFINE_ACTION_WRAPPER(macsmc_reboot_test_cell_put, nvmem_cell_put, + struct nvmem_cell *); + +static struct nvmem_cell *macsmc_reboot_test_cell(struct kunit *test, + struct macsmc_reboot_test *ctx, + unsigned int idx) +{ + struct nvmem_cell *cell = nvmem_cell_get(ctx->dev, macsmc_reboot_test_cells[idx]); + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cell); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_reboot_test_cell_put, + cell), 0); + return cell; +} + +/* A reboot handler with every cell, as macsmc_reboot_probe() leaves it. */ +static struct macsmc_reboot_test *macsmc_reboot_test_setup(struct kunit *test) +{ + struct nvmem_config config = {}; + struct nvmem_cell_info *cells; + struct macsmc_reboot_test *ctx; + struct nvmem_device *nvmem; + struct device *provider; + int i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + cells = kunit_kcalloc(test, REBOOT_TEST_NR_CELLS, sizeof(*cells), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, cells); + ctx->fail_offset = -1; + mutex_init(&ctx->smc.mutex); + spin_lock_init(&ctx->smc.lock); + /* Any SMC command fails: the SMC never booted. */ + ctx->smc.shmem.iomem = (void __force __iomem *)ctx->shmem; + + for (i = 0; i < REBOOT_TEST_NR_CELLS; i++) { + cells[i].name = macsmc_reboot_test_cells[i]; + cells[i].offset = i; + cells[i].bytes = 1; + } + + provider = kunit_device_register(test, "nvmem"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, provider); + config.dev = provider; + config.name = "macsmc-reboot-test"; + config.id = NVMEM_DEVID_AUTO; + config.cells = cells; + config.ncells = REBOOT_TEST_NR_CELLS; + config.ignore_wp = true; + config.reg_read = macsmc_reboot_test_reg_read; + config.reg_write = macsmc_reboot_test_reg_write; + config.size = REBOOT_TEST_NR_CELLS; + config.priv = ctx; + nvmem = devm_nvmem_register(provider, &config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, nvmem); + + ctx->dev = kunit_device_register(test, "reboot"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + for (i = 0; i < REBOOT_TEST_NR_CELLS; i++) { + ctx->lookups[i].nvmem_name = nvmem_dev_name(nvmem); + ctx->lookups[i].cell_name = macsmc_reboot_test_cells[i]; + ctx->lookups[i].dev_id = dev_name(ctx->dev); + ctx->lookups[i].con_id = macsmc_reboot_test_cells[i]; + } + nvmem_add_cell_lookups(ctx->lookups, ARRAY_SIZE(ctx->lookups)); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_reboot_test_del_lookups, + ctx), 0); + + ctx->reboot.dev = ctx->dev; + ctx->reboot.smc = &ctx->smc; + mutex_init(&ctx->reboot.pm_setting_lock); + for (i = 0; i < ARRAY_SIZE(nvmem_names); i++) { + KUNIT_ASSERT_STREQ(test, nvmem_names[i], macsmc_reboot_test_cells[i]); + ctx->reboot.nvm_cells[i] = macsmc_reboot_test_cell(test, ctx, i); + } + ctx->reboot.pm_setting = macsmc_reboot_test_cell(test, ctx, REBOOT_TEST_PM_SETTING); + ctx->reboot.reboot_notify.notifier_call = macsmc_reboot_notify; + dev_set_drvdata(ctx->dev, &ctx->reboot); + + kunit_activate_static_stub(test, apple_smc_write, macsmc_reboot_test_smc_write); + return ctx; +} + +static int macsmc_reboot_test_notify(struct macsmc_reboot_test *ctx, unsigned long action) +{ + return macsmc_reboot_notify(&ctx->reboot.reboot_notify, action, NULL); +} + +static void macsmc_reboot_test_expect_nv(struct kunit *test, struct macsmc_reboot_test *ctx, + unsigned int idx, unsigned int cell, u8 val) +{ + KUNIT_ASSERT_LT(test, idx, ctx->nr_nv_writes); + KUNIT_EXPECT_EQ_MSG(test, ctx->nv_writes[idx].where, cell, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, ctx->nv_writes[idx].size, 1, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, ctx->nv_writes[idx].val, val, "write %u", idx); +} + +static void macsmc_reboot_test_expect_mbse(struct kunit *test, struct macsmc_reboot_test *ctx, + smc_key val) +{ + KUNIT_ASSERT_EQ(test, ctx->nr_smc_writes, 1); + KUNIT_EXPECT_EQ(test, ctx->smc_writes[0].where, SMC_KEY(MBSE)); + KUNIT_EXPECT_EQ(test, ctx->smc_writes[0].size, sizeof(u32)); + KUNIT_EXPECT_EQ(test, ctx->smc_writes[0].val, val); +} + +/* Restart: MBSE = rest, a clean boot_stage and shutdown_flag 0 (power back on). */ +static void macsmc_reboot_test_notify_restart(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_BOOT_STAGE] = BOOT_STAGE_KERNEL_STARTED; + ctx->nvmem[REBOOT_TEST_SHUTDOWN_FLAG] = 1; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_RESTART), NOTIFY_OK); + macsmc_reboot_test_expect_mbse(test, ctx, SMC_KEY(rest)); + KUNIT_ASSERT_EQ(test, ctx->nr_nv_writes, 2); + macsmc_reboot_test_expect_nv(test, ctx, 0, REBOOT_TEST_BOOT_STAGE, BOOT_STAGE_SHUTDOWN); + macsmc_reboot_test_expect_nv(test, ctx, 1, REBOOT_TEST_SHUTDOWN_FLAG, 0); +} + +/* Power off: MBSE = offw, a clean boot_stage and shutdown_flag 1 (stay off). */ +static void macsmc_reboot_test_notify_power_off(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_BOOT_STAGE] = BOOT_STAGE_KERNEL_STARTED; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_POWER_OFF), NOTIFY_OK); + macsmc_reboot_test_expect_mbse(test, ctx, SMC_KEY(offw)); + KUNIT_ASSERT_EQ(test, ctx->nr_nv_writes, 2); + macsmc_reboot_test_expect_nv(test, ctx, 0, REBOOT_TEST_BOOT_STAGE, BOOT_STAGE_SHUTDOWN); + macsmc_reboot_test_expect_nv(test, ctx, 1, REBOOT_TEST_SHUTDOWN_FLAG, 1); +} + +/* A halt is not ours to prepare: nothing is written. */ +static void macsmc_reboot_test_notify_other(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_HALT), NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_DOWN + 100), NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, ctx->nr_smc_writes, 0); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); +} + +/* Missing cells are skipped; MBSE is still written. */ +static void macsmc_reboot_test_notify_no_cells(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->reboot.nvm.shutdown_flag = NULL; + ctx->reboot.nvm.boot_stage = NULL; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_POWER_OFF), NOTIFY_OK); + macsmc_reboot_test_expect_mbse(test, ctx, SMC_KEY(offw)); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); +} + +/* A failed MBSE write does not stop the PMU flags from being written. */ +static void macsmc_reboot_test_notify_mbse_error(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->smc_ret = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_POWER_OFF), NOTIFY_OK); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 2); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_SHUTDOWN_FLAG], 1); + + /* Nor does a failed boot_stage write stop shutdown_flag. */ + ctx->smc_ret = 0; + ctx->fail_offset = REBOOT_TEST_BOOT_STAGE; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_RESTART), NOTIFY_OK); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_SHUTDOWN_FLAG], 0); +} + +/* Logged boot errors and panics are cleared: panic_count first. */ +static void macsmc_reboot_test_error_counts(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_BOOT_ERROR_COUNT] = 2; + ctx->nvmem[REBOOT_TEST_PANIC_COUNT] = 0; + macsmc_power_init_error_counts(&ctx->reboot); + KUNIT_ASSERT_EQ(test, ctx->nr_nv_writes, 2); + macsmc_reboot_test_expect_nv(test, ctx, 0, REBOOT_TEST_PANIC_COUNT, 0); + macsmc_reboot_test_expect_nv(test, ctx, 1, REBOOT_TEST_BOOT_ERROR_COUNT, 0); + + ctx->nr_nv_writes = 0; + ctx->nvmem[REBOOT_TEST_PANIC_COUNT] = 0xff; + macsmc_power_init_error_counts(&ctx->reboot); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 2); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PANIC_COUNT], 0); + + /* Nothing logged: nothing written. */ + ctx->nr_nv_writes = 0; + macsmc_power_init_error_counts(&ctx->reboot); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); +} + +/* Without both counter cells the counters are left alone. */ +static void macsmc_reboot_test_error_counts_missing(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_BOOT_ERROR_COUNT] = 3; + ctx->nvmem[REBOOT_TEST_PANIC_COUNT] = 4; + ctx->reboot.nvm.panic_count = NULL; + macsmc_power_init_error_counts(&ctx->reboot); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_BOOT_ERROR_COUNT], 3); +} + +/* Bit 5 clear powers on at connect; otherwise bit 0 picks off or restore. */ +static void macsmc_reboot_test_ac_mode_decode(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0x21), AC_POWER_OFF); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0xff), AC_POWER_OFF); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0x20), AC_POWER_RESTORE); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0xfe), AC_POWER_RESTORE); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0x01), AC_POWER_ALWAYS); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0x00), AC_POWER_ALWAYS); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0xde), AC_POWER_ALWAYS); +} + +static void macsmc_reboot_test_expect_show(struct kunit *test, struct macsmc_reboot_test *ctx, + u8 setting, const char *expect) +{ + char *buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + ctx->nvmem[REBOOT_TEST_PM_SETTING] = setting; + KUNIT_EXPECT_EQ(test, ac_power_mode_show(ctx->dev, &dev_attr_ac_power_mode, buf), + strlen(expect)); + KUNIT_EXPECT_STREQ(test, buf, expect); +} + +static void macsmc_reboot_test_ac_mode_show(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + macsmc_reboot_test_expect_show(test, ctx, 0x21, "[off] restore always\n"); + macsmc_reboot_test_expect_show(test, ctx, 0xa0, "off [restore] always\n"); + macsmc_reboot_test_expect_show(test, ctx, 0x80, "off restore [always]\n"); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); +} + +static ssize_t macsmc_reboot_test_store(struct macsmc_reboot_test *ctx, const char *buf) +{ + return ac_power_mode_store(ctx->dev, &dev_attr_ac_power_mode, buf, strlen(buf)); +} + +/* A store changes bits 0 and 5 only, and only when the mode changes. */ +static void macsmc_reboot_test_ac_mode_store(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_PM_SETTING] = 0x80 | PM_SETTING_AC_POWER_MASK; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "restore\n"), 8); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PM_SETTING], 0xa0); + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "always"), 6); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PM_SETTING], 0x81); + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "off"), 3); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PM_SETTING], 0xa1); + KUNIT_ASSERT_EQ(test, ctx->nr_nv_writes, 3); + macsmc_reboot_test_expect_nv(test, ctx, 0, REBOOT_TEST_PM_SETTING, 0xa0); + + /* Unchanged: no write. */ + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "off\n"), 4); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 3); +} + +static void macsmc_reboot_test_ac_mode_store_errors(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_PM_SETTING] = 0x21; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "on"), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, ""), -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); + + ctx->fail_offset = REBOOT_TEST_PM_SETTING; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "always"), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PM_SETTING], 0x21); +} + +/* ac_power_mode exists only with a pm_setting cell. */ +static void macsmc_reboot_test_ac_mode_visible(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + struct attribute *attr = &dev_attr_ac_power_mode.attr; + + KUNIT_EXPECT_EQ(test, macsmc_reboot_attr_visible(&ctx->dev->kobj, attr, 0), 0644); + ctx->reboot.pm_setting = NULL; + KUNIT_EXPECT_EQ(test, macsmc_reboot_attr_visible(&ctx->dev->kobj, attr, 0), 0); + dev_set_drvdata(ctx->dev, NULL); + KUNIT_EXPECT_EQ(test, macsmc_reboot_attr_visible(&ctx->dev->kobj, attr, 0), 0); +} + +/* + * off1 and phra are atomic writes. On a booted SMC that has not entered + * atomic mode they are refused, and the handlers return at once instead of + * waiting for the power to go (mdelay(100), then a warning). + */ +static void macsmc_reboot_test_atomic_refused(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + struct sys_off_data data = { .cb_data = &ctx->reboot }; + ktime_t start; + + ctx->smc.boot_stage = APPLE_SMC_INITIALIZED; + ctx->smc.atomic_mode = false; + /* What refuses is the atomic mode check, not the boot stage. */ + KUNIT_ASSERT_EQ(test, apple_smc_write_u32_atomic(&ctx->smc, SMC_KEY(MBSE), + SMC_KEY(off1)), -EIO); + + start = ktime_get(); + KUNIT_EXPECT_EQ(test, macsmc_power_off(&data), NOTIFY_OK); + KUNIT_EXPECT_LT(test, ktime_ms_delta(ktime_get(), start), 50); + start = ktime_get(); + KUNIT_EXPECT_EQ(test, macsmc_restart(&data), NOTIFY_OK); + KUNIT_EXPECT_LT(test, ktime_ms_delta(ktime_get(), start), 50); +} + +static struct kunit_case macsmc_reboot_test_cases[] = { + KUNIT_CASE(macsmc_reboot_test_notify_restart), + KUNIT_CASE(macsmc_reboot_test_notify_power_off), + KUNIT_CASE(macsmc_reboot_test_notify_other), + KUNIT_CASE(macsmc_reboot_test_notify_no_cells), + KUNIT_CASE(macsmc_reboot_test_notify_mbse_error), + KUNIT_CASE(macsmc_reboot_test_error_counts), + KUNIT_CASE(macsmc_reboot_test_error_counts_missing), + KUNIT_CASE(macsmc_reboot_test_ac_mode_decode), + KUNIT_CASE(macsmc_reboot_test_ac_mode_show), + KUNIT_CASE(macsmc_reboot_test_ac_mode_store), + KUNIT_CASE(macsmc_reboot_test_ac_mode_store_errors), + KUNIT_CASE(macsmc_reboot_test_ac_mode_visible), + KUNIT_CASE(macsmc_reboot_test_atomic_refused), + {} +}; + +static struct kunit_suite macsmc_reboot_test_suite = { + .name = "macsmc-reboot", + .test_cases = macsmc_reboot_test_cases, +}; + +kunit_test_suite(macsmc_reboot_test_suite); diff --git a/drivers/power/reset/macsmc-reboot.c b/drivers/power/reset/macsmc-reboot.c index a2e1422e05bd82..247036bc11b19b 100644 --- a/drivers/power/reset/macsmc-reboot.c +++ b/drivers/power/reset/macsmc-reboot.c @@ -98,7 +98,9 @@ static int nvmem_cell_get_u8(struct nvmem_cell *cell) static int nvmem_cell_set_u8(struct nvmem_cell *cell, u8 val) { - return nvmem_cell_write(cell, &val, sizeof(val)); + int ret = nvmem_cell_write(cell, &val, sizeof(val)); + + return ret < 0 ? ret : 0; } /* @@ -413,3 +415,7 @@ module_platform_driver(macsmc_reboot_driver); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple SMC reboot/poweroff driver"); MODULE_AUTHOR("Hector Martin "); + +#if IS_ENABLED(CONFIG_POWER_RESET_MACSMC_KUNIT_TEST) +#include "macsmc-reboot-test.c" +#endif diff --git a/drivers/power/reset/macsmc-reboot.kunitconfig b/drivers/power/reset/macsmc-reboot.kunitconfig new file mode 100644 index 00000000000000..3af2e4d04a7eb2 --- /dev/null +++ b/drivers/power/reset/macsmc-reboot.kunitconfig @@ -0,0 +1,13 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/power/reset/macsmc-reboot.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_NVMEM=y +CONFIG_POWER_RESET=y +CONFIG_POWER_RESET_MACSMC=y +CONFIG_POWER_RESET_MACSMC_KUNIT_TEST=y diff --git a/drivers/power/supply/macsmc-power-test.c b/drivers/power/supply/macsmc-power-test.c index e3cf46b0f8d6f9..40993afb2be420 100644 --- a/drivers/power/supply/macsmc-power-test.c +++ b/drivers/power/supply/macsmc-power-test.c @@ -807,4 +807,70 @@ static struct kunit_suite macsmc_charge_test_suite = { .test_cases = macsmc_charge_test_cases, }; -kunit_test_suites(&macsmc_power_test_suite, &macsmc_charge_test_suite); +/* The adapter's input power, PDTR, a float in watts reported in microwatts */ +struct macsmc_ac_test { + struct apple_smc smc; + struct macsmc_power power; + u32 pdtr; + int err; +}; + +static int ac_test_read(struct apple_smc *smc, smc_key key, void *buf, size_t size) +{ + struct macsmc_ac_test *t = container_of(smc, struct macsmc_ac_test, smc); + + if (key != SMC_KEY(PDTR) || size != sizeof(u32)) + return -EINVAL; + if (t->err) + return t->err; + memcpy(buf, &t->pdtr, size); + return size; +} + +static int macsmc_ac_test_init(struct kunit *test) +{ + struct macsmc_ac_test *t; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + if (!t) + return -ENOMEM; + t->power.smc = &t->smc; + test->priv = t; + kunit_activate_static_stub(test, apple_smc_read, ac_test_read); + return 0; +} + +static void macsmc_ac_power_now_test(struct kunit *test) +{ + struct macsmc_ac_test *t = test->priv; + int uw = -1; + + t->pdtr = 0x414eb021; /* 12.918 W */ + KUNIT_EXPECT_EQ(test, macsmc_ac_read_power_now(&t->power, &uw), 0); + KUNIT_EXPECT_EQ(test, uw, 12918000); + + t->pdtr = 0x430b8000; /* 139.5 W */ + KUNIT_EXPECT_EQ(test, macsmc_ac_read_power_now(&t->power, &uw), 0); + KUNIT_EXPECT_EQ(test, uw, 139500000); + + t->pdtr = 0; /* adapter idle or unplugged */ + KUNIT_EXPECT_EQ(test, macsmc_ac_read_power_now(&t->power, &uw), 0); + KUNIT_EXPECT_EQ(test, uw, 0); + + t->err = -EIO; + KUNIT_EXPECT_EQ(test, macsmc_ac_read_power_now(&t->power, &uw), -EIO); +} + +static struct kunit_case macsmc_ac_test_cases[] = { + KUNIT_CASE(macsmc_ac_power_now_test), + {} +}; + +static struct kunit_suite macsmc_ac_test_suite = { + .name = "macsmc-power-ac", + .init = macsmc_ac_test_init, + .test_cases = macsmc_ac_test_cases, +}; + +kunit_test_suites(&macsmc_power_test_suite, &macsmc_charge_test_suite, + &macsmc_ac_test_suite); diff --git a/drivers/power/supply/macsmc-power.c b/drivers/power/supply/macsmc-power.c index 5bd714eaf1b276..2e96a217c2c8e9 100644 --- a/drivers/power/supply/macsmc-power.c +++ b/drivers/power/supply/macsmc-power.c @@ -105,7 +105,11 @@ struct macsmc_power { /* * Where neither CHTE nor CH0C exists, inhibit-charge holds the charge * at the current level with CHLS_HOLD; the user's own CHLS limit is - * kept here meanwhile and restored when the hold ends. + * kept here meanwhile and restored when the hold ends. It is kept in + * RAM only: the SMC has no spare key for it. If the driver binds while + * a hold from an earlier boot or binding is still set, the earlier + * limit is unknown, so the end threshold reads 100 and ending the hold + * leaves no limit. Userspace that sets both should set the limit again. */ u8 chls_user_limit; /* Battery critical key (BCF0) is 1 byte (Modern firmware) */ @@ -560,7 +564,7 @@ static int macsmc_battery_set_charge_behaviour(struct macsmc_power *power, int v static int macsmc_battery_get_date(const char *s, int *out) { if (!isdigit(s[0]) || !isdigit(s[1])) - return -EOPNOTSUPP; + return -ENODATA; *out = (s[0] - '0') * 10 + s[1] - '0'; return 0; @@ -760,7 +764,8 @@ static int macsmc_battery_get_property(struct power_supply *psy, case POWER_SUPPLY_PROP_MANUFACTURE_YEAR: ret = macsmc_battery_get_date(&power->mfg_date[0], &val->intval); /* The SMC reports the manufacture year as an offset from 1992. */ - val->intval += 1992; + if (!ret) + val->intval += 1992; break; case POWER_SUPPLY_PROP_MANUFACTURE_MONTH: ret = macsmc_battery_get_date(&power->mfg_date[2], &val->intval); @@ -895,6 +900,16 @@ static const struct power_supply_desc macsmc_battery_desc_template = { .property_is_writeable = macsmc_battery_property_is_writeable, }; +/* + * PDTR is the power the system takes from the adapter (DC in) now, in watts. + * With ACPW (what the adapter may deliver) it tells how much of the adapter is + * in use; the battery's own power_now tells how much of that goes to charging. + */ +static int macsmc_ac_read_power_now(struct macsmc_power *power, int *uw) +{ + return apple_smc_read_f32_scaled(power->smc, SMC_KEY(PDTR), uw, 1000000); +} + static int macsmc_ac_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) @@ -921,6 +936,9 @@ static int macsmc_ac_get_property(struct power_supply *psy, ret = apple_smc_read_u32(power->smc, SMC_KEY(ACPW), &vu32); val->intval = vu32 * 1000; break; + case POWER_SUPPLY_PROP_POWER_NOW: + ret = macsmc_ac_read_power_now(power, &val->intval); + break; default: return -EINVAL; } @@ -1102,10 +1120,10 @@ static int macsmc_power_probe(struct platform_device *pdev) return ret; dev_set_drvdata(dev, power); - INIT_WORK(&power->critical_work, macsmc_power_critical_work); ret = devm_work_autocancel(dev, &power->critical_work, macsmc_power_critical_work); if (ret) return ret; + INIT_DELAYED_WORK(&power->dbg_log_work, macsmc_dbg_work); /* * Check for battery presence. @@ -1211,7 +1229,11 @@ static int macsmc_power_probe(struct platform_device *pdev) of_machine_is_compatible("apple,j700"); power->status_from_current = of_machine_is_compatible("apple,j700"); - /* Preserve firmware charge policy until userspace changes it. */ + /* + * Preserve firmware charge policy until userspace changes it: + * the inhibitors (CHTE, CH0C, CH0I) and CH0K/CH0B persist in the + * SMC, and binding the driver is not a request to reset them. + */ /* Detect charge limit method (CHWA vs CHLS) */ if (apple_smc_read_flag(power->smc, SMC_KEY(CHWA), &flag) == 0) power->has_chwa = true; @@ -1221,6 +1243,8 @@ static int macsmc_power_probe(struct platform_device *pdev) if (power->has_chls && (vu16 & CHLS_FORCE_DISCHARGE) && !macsmc_chls_has_limit(vu16)) dev_warn(dev, "CHLS force-discharge without a limit; select charge_behaviour=auto to clear\n"); + if (power->has_chls && macsmc_chls_holds(power, vu16)) + dev_info(dev, "CHLS holds the charge from an earlier boot; the charge limit before it is not known\n"); /* * CHLS carries auto-discharge, so a CHLS-only Mac can select auto @@ -1283,6 +1307,9 @@ static int macsmc_power_probe(struct platform_device *pdev) if (apple_smc_key_exists(power->smc, SMC_KEY(ACPW))) props[nprops++] = POWER_SUPPLY_PROP_INPUT_POWER_LIMIT; + if (apple_smc_key_exists(power->smc, SMC_KEY(PDTR))) + props[nprops++] = POWER_SUPPLY_PROP_POWER_NOW; + /* macOS 15.4+ firmware dropped legacy AC keys (AC-n, AC-i) */ if (apple_smc_read_u16(power->smc, SMC_KEY(AC-n), &vu16) >= 0) { props[nprops++] = POWER_SUPPLY_PROP_VOLTAGE_NOW; @@ -1308,12 +1335,10 @@ static int macsmc_power_probe(struct platform_device *pdev) if (!power->batt && !power->ac) return -ENODEV; + /* Both work items were set up above, before anything can queue them. */ power->nb.notifier_call = macsmc_power_event; blocking_notifier_chain_register(&smc->event_handlers, &power->nb); - INIT_WORK(&power->critical_work, macsmc_power_critical_work); - INIT_DELAYED_WORK(&power->dbg_log_work, macsmc_dbg_work); - g_power = power; if (log_power) @@ -1326,12 +1351,16 @@ static void macsmc_power_remove(struct platform_device *pdev) { struct macsmc_power *power = dev_get_drvdata(&pdev->dev); - cancel_work(&power->critical_work); - cancel_delayed_work(&power->dbg_log_work); - + /* + * Stop new work first: the notifier queues the critical work and the + * log_power parameter queues the log through g_power. The debug work + * re-arms itself, so disable it and wait, as devm frees power next. + */ + blocking_notifier_chain_unregister(&power->smc->event_handlers, &power->nb); g_power = NULL; - blocking_notifier_chain_unregister(&power->smc->event_handlers, &power->nb); + disable_delayed_work_sync(&power->dbg_log_work); + cancel_work_sync(&power->critical_work); } /* diff --git a/drivers/pwm/Kconfig b/drivers/pwm/Kconfig index 72977608687903..70fd31fbb06754 100644 --- a/drivers/pwm/Kconfig +++ b/drivers/pwm/Kconfig @@ -85,6 +85,19 @@ config PWM_APPLE To compile this driver as a module, choose M here: the module will be called pwm-apple. +config PWM_APPLE_KUNIT_TEST + bool "KUnit tests for the Apple SoC PWM" if !KUNIT_ALL_TESTS + depends on PWM_APPLE=y && KUNIT=y + default KUNIT_ALL_TESTS + help + Build tests for the Apple SoC PWM driver: the conversion of a + period and duty cycle to ON and OFF cycle counts at the clock + rate with its rounding and 32-bit saturation, the state read back + from the registers, the refusal of inverted polarity and the + runtime PM reference held for a running output. The chip is + registered on a KUnit device with its registers in kernel + memory, so the tests need no Apple hardware. + config PWM_ARGON_FAN_HAT tristate "Argon40 Fan HAT support" depends on I2C && OF diff --git a/drivers/pwm/pwm-apple-test.c b/drivers/pwm/pwm-apple-test.c new file mode 100644 index 00000000000000..b9a4fa71e7ccea --- /dev/null +++ b/drivers/pwm/pwm-apple-test.c @@ -0,0 +1,530 @@ +// SPDX-License-Identifier: GPL-2.0 OR MIT +/* + * KUnit tests for the Apple SoC PWM driver: the period and duty cycle to + * ON/OFF cycle register conversion, its readback and the power reference + * held for a running output. + * + * The chip is a real pwm_chip registered on a KUnit device and driven + * through the PWM core by a consumer found through a lookup table. Its + * registers are plain kernel memory and the clock rate is set directly, so + * the tests need no Apple hardware. + * + * Included by pwm-apple.c. + */ + +#include +#include +#include + +#define APPLE_PWM_TEST_REGS 0x20 +#define APPLE_PWM_TEST_RATE 24000000ULL +#define APPLE_PWM_TEST_CTRL_ON (APPLE_PWM_CTRL_ENABLE | \ + APPLE_PWM_CTRL_OUTPUT_ENABLE | \ + APPLE_PWM_CTRL_UPDATE) + +struct apple_pwm_test { + struct device *dev; + struct pwm_chip *chip; + struct apple_pwm *fpwm; + struct pwm_device *pwm; + struct pwm_lookup lookup; +}; + +static void apple_pwm_test_put(void *data) +{ + pwm_put(data); +} + +static void apple_pwm_test_remove_table(void *data) +{ + pwm_remove_table(data, 1); +} + +static void apple_pwm_test_remove_chip(void *data) +{ + pwmchip_remove(data); +} + +static void apple_pwm_test_pm_disable(void *data) +{ + pm_runtime_disable(data); +} + +static int apple_pwm_test_init(struct kunit *test) +{ + struct apple_pwm_test *ctx; + struct device *consumer; + void *regs; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->dev = kunit_device_register(test, "apple-pwm-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + consumer = kunit_device_register(test, "apple-pwm-test-consumer"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, consumer); + + ctx->chip = devm_pwmchip_alloc(ctx->dev, 1, sizeof(*ctx->fpwm)); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->chip); + ctx->fpwm = to_apple_pwm(ctx->chip); + + regs = kunit_kzalloc(test, APPLE_PWM_TEST_REGS, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, regs); + ctx->fpwm->base = (void __iomem __force *)regs; + ctx->fpwm->clkrate = APPLE_PWM_TEST_RATE; + ctx->chip->ops = &apple_pwm_ops; + dev_set_drvdata(ctx->dev, ctx->chip); + + KUNIT_ASSERT_EQ(test, pm_runtime_set_active(ctx->dev), 0); + pm_runtime_enable(ctx->dev); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, apple_pwm_test_pm_disable, + ctx->dev), 0); + + KUNIT_ASSERT_EQ(test, pwmchip_add(ctx->chip), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, apple_pwm_test_remove_chip, + ctx->chip), 0); + + ctx->lookup.provider = dev_name(ctx->dev); + ctx->lookup.dev_id = dev_name(consumer); + ctx->lookup.con_id = "test"; + ctx->lookup.polarity = PWM_POLARITY_NORMAL; + pwm_add_table(&ctx->lookup, 1); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, apple_pwm_test_remove_table, + &ctx->lookup), 0); + + ctx->pwm = pwm_get(consumer, "test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->pwm); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, apple_pwm_test_put, + ctx->pwm), 0); + + return 0; +} + +static u32 apple_pwm_test_reg(struct apple_pwm_test *ctx, unsigned int reg) +{ + return readl(ctx->fpwm->base + reg); +} + +static void apple_pwm_test_set_regs(struct apple_pwm_test *ctx, u32 ctrl, + u32 on_cycles, u32 off_cycles) +{ + writel(ctrl, ctx->fpwm->base + APPLE_PWM_CTRL); + writel(on_cycles, ctx->fpwm->base + APPLE_PWM_ON_CYCLES); + writel(off_cycles, ctx->fpwm->base + APPLE_PWM_OFF_CYCLES); +} + +static int apple_pwm_test_apply(struct apple_pwm_test *ctx, u64 period, + u64 duty_cycle, bool enabled) +{ + struct pwm_state state = { + .period = period, + .duty_cycle = duty_cycle, + .polarity = PWM_POLARITY_NORMAL, + .enabled = enabled, + }; + + return pwm_apply_might_sleep(ctx->pwm, &state); +} + +static int apple_pwm_test_usage(struct apple_pwm_test *ctx) +{ +#ifdef CONFIG_PM + return atomic_read(&ctx->dev->power.usage_count); +#else + return 0; +#endif +} + +struct apple_pwm_test_conv { + const char *name; + u64 clkrate; + u64 period; + u64 duty_cycle; + u32 on_cycles; + u32 off_cycles; +}; + +static const struct apple_pwm_test_conv apple_pwm_test_convs[] = { + { + .name = "24 MHz, 1 ms period, 25 % duty", + .clkrate = 24000000, .period = 1000000, .duty_cycle = 250000, + .on_cycles = 6000, .off_cycles = 18000, + }, { + /* 2.4 cycles of duty round down to 2, the period is exact */ + .name = "24 MHz, duty rounds down", + .clkrate = 24000000, .period = 1000, .duty_cycle = 100, + .on_cycles = 2, .off_cycles = 22, + }, { + /* 1999 ns are 47.976 cycles */ + .name = "24 MHz, period rounds down", + .clkrate = 24000000, .period = 1999, .duty_cycle = 1000, + .on_cycles = 24, .off_cycles = 23, + }, { + /* 41 ns are less than one cycle of 41.67 ns */ + .name = "24 MHz, period below one cycle", + .clkrate = 24000000, .period = 41, .duty_cycle = 41, + .on_cycles = 0, .off_cycles = 0, + }, { + .name = "24 MHz, no duty", + .clkrate = 24000000, .period = 1000000, .duty_cycle = 0, + .on_cycles = 0, .off_cycles = 24000, + }, { + .name = "24 MHz, full duty", + .clkrate = 24000000, .period = 1000000, .duty_cycle = 1000000, + .on_cycles = 24000, .off_cycles = 0, + }, { + /* 100 s and 150 s fit 32 bits each, their sum does not */ + .name = "24 MHz, period above 32 bits of cycles", + .clkrate = 24000000, .period = 250ULL * NSEC_PER_SEC, + .duty_cycle = 100ULL * NSEC_PER_SEC, + .on_cycles = 2400000000U, .off_cycles = 3600000000U, + }, { + /* 200 s of duty are 4.8e9 cycles: ON saturates, OFF keeps the rest */ + .name = "24 MHz, duty saturates, period kept", + .clkrate = 24000000, .period = 300ULL * NSEC_PER_SEC, + .duty_cycle = 200ULL * NSEC_PER_SEC, + .on_cycles = U32_MAX, .off_cycles = 2905032705U, + }, { + .name = "24 MHz, duty and period saturate", + .clkrate = 24000000, .period = 500ULL * NSEC_PER_SEC, + .duty_cycle = 400ULL * NSEC_PER_SEC, + .on_cycles = U32_MAX, .off_cycles = U32_MAX, + }, { + /* the period times the rate does not fit 64 bits */ + .name = "24 MHz, longest period", + .clkrate = 24000000, .period = U64_MAX, .duty_cycle = 1000000, + .on_cycles = 24000, .off_cycles = U32_MAX, + }, { + .name = "24 MHz, longest period and duty", + .clkrate = 24000000, .period = U64_MAX, .duty_cycle = U64_MAX, + .on_cycles = U32_MAX, .off_cycles = U32_MAX, + }, { + /* the fastest clock the probe accepts: one cycle per ns */ + .name = "1 GHz, one cycle per ns", + .clkrate = NSEC_PER_SEC, .period = 4000000000ULL, + .duty_cycle = 123456789, + .on_cycles = 123456789, .off_cycles = 3876543211U, + }, { + .name = "1 GHz, longest period and duty", + .clkrate = NSEC_PER_SEC, .period = U64_MAX, .duty_cycle = U64_MAX, + .on_cycles = U32_MAX, .off_cycles = U32_MAX, + }, { + /* 1 s is 32768 cycles, 100 us are 3.28 */ + .name = "32768 Hz", + .clkrate = 32768, .period = NSEC_PER_SEC, .duty_cycle = 100000, + .on_cycles = 3, .off_cycles = 32765, + }, +}; + +static void apple_pwm_test_conv_desc(const struct apple_pwm_test_conv *c, char *desc) +{ + strscpy(desc, c->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(apple_pwm_test_conv, apple_pwm_test_convs, apple_pwm_test_conv_desc); + +/* An enabled state is converted to ON and OFF cycles and latched. */ +static void apple_pwm_test_apply_cycles(struct kunit *test) +{ + const struct apple_pwm_test_conv *c = test->param_value; + struct apple_pwm_test *ctx = test->priv; + + ctx->fpwm->clkrate = c->clkrate; + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, c->period, c->duty_cycle, true), 0); + + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_ON_CYCLES), c->on_cycles); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_OFF_CYCLES), c->off_cycles); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_CTRL), APPLE_PWM_TEST_CTRL_ON); +} + +/* + * What the hardware reads back is never longer than what was asked for, is + * less than one clock cycle shorter unless a register saturated, and + * programs the same registers when it is applied again. + */ +static void apple_pwm_test_readback(struct kunit *test) +{ + const struct apple_pwm_test_conv *c = test->param_value; + struct apple_pwm_test *ctx = test->priv; + u64 cycle_ns = DIV64_U64_ROUND_UP(NSEC_PER_SEC, c->clkrate); + struct pwm_state hw; + + ctx->fpwm->clkrate = c->clkrate; + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, c->period, c->duty_cycle, true), 0); + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + + KUNIT_EXPECT_TRUE(test, hw.enabled); + KUNIT_EXPECT_EQ(test, hw.polarity, PWM_POLARITY_NORMAL); + KUNIT_EXPECT_LE(test, hw.duty_cycle, hw.period); + KUNIT_EXPECT_LE(test, hw.duty_cycle, c->duty_cycle); + KUNIT_EXPECT_LE(test, hw.period, c->period); + if (c->on_cycles != U32_MAX) + KUNIT_EXPECT_LT(test, c->duty_cycle - hw.duty_cycle, cycle_ns); + if (c->on_cycles != U32_MAX && c->off_cycles != U32_MAX) + KUNIT_EXPECT_LT(test, c->period - hw.period, cycle_ns); + + /* Scribble over the registers so that the second apply shows. */ + apple_pwm_test_set_regs(ctx, 0, ~c->on_cycles, ~c->off_cycles); + KUNIT_ASSERT_EQ(test, apple_pwm_apply(ctx->chip, ctx->pwm, &hw), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_ON_CYCLES), c->on_cycles); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_OFF_CYCLES), c->off_cycles); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_CTRL), APPLE_PWM_TEST_CTRL_ON); +} + +/* Readback rounds up to the next nanosecond, duty and period separately. */ +static void apple_pwm_test_get_state_rounds_up(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + struct pwm_state hw; + + /* 1 cycle is 41.67 ns, 2 are 83.33 ns, 3 are exactly 125 ns */ + apple_pwm_test_set_regs(ctx, APPLE_PWM_TEST_CTRL_ON, 1, 1); + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_EQ(test, hw.duty_cycle, 42); + KUNIT_EXPECT_EQ(test, hw.period, 84); + + apple_pwm_test_set_regs(ctx, APPLE_PWM_TEST_CTRL_ON, 3, 0); + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_EQ(test, hw.duty_cycle, 125); + KUNIT_EXPECT_EQ(test, hw.period, 125); +} + +/* Both registers at their maximum: the 33-bit sum must not be truncated. */ +static void apple_pwm_test_get_state_max(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + struct pwm_state hw; + + apple_pwm_test_set_regs(ctx, APPLE_PWM_TEST_CTRL_ON, U32_MAX, U32_MAX); + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_TRUE(test, hw.enabled); + KUNIT_EXPECT_EQ(test, hw.duty_cycle, 178956970625ULL); + KUNIT_EXPECT_EQ(test, hw.period, 357913941250ULL); + + /* The slowest clock: 2^33 - 2 cycles of one second each. */ + ctx->fpwm->clkrate = 1; + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_EQ(test, hw.duty_cycle, (u64)U32_MAX * NSEC_PER_SEC); + KUNIT_EXPECT_EQ(test, hw.period, 2ULL * U32_MAX * NSEC_PER_SEC); +} + +/* The output only runs with both the enable and the output enable bit. */ +static void apple_pwm_test_get_state_enabled(struct kunit *test) +{ + static const struct { + u32 ctrl; + bool enabled; + } cases[] = { + { 0, false }, + { APPLE_PWM_CTRL_ENABLE, false }, + { APPLE_PWM_CTRL_OUTPUT_ENABLE, false }, + { APPLE_PWM_CTRL_UPDATE, false }, + { APPLE_PWM_CTRL_ENABLE | APPLE_PWM_CTRL_OUTPUT_ENABLE, true }, + { APPLE_PWM_TEST_CTRL_ON, true }, + { ~(u32)APPLE_PWM_CTRL_ENABLE, false }, + { ~(u32)APPLE_PWM_CTRL_OUTPUT_ENABLE, false }, + }; + struct apple_pwm_test *ctx = test->priv; + struct pwm_state hw; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cases); i++) { + apple_pwm_test_set_regs(ctx, cases[i].ctrl, 6000, 18000); + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_EQ_MSG(test, hw.enabled, cases[i].enabled, + "ctrl %#x", cases[i].ctrl); + KUNIT_EXPECT_EQ(test, hw.polarity, PWM_POLARITY_NORMAL); + KUNIT_EXPECT_EQ(test, hw.duty_cycle, 250000); + KUNIT_EXPECT_EQ(test, hw.period, 1000000); + } +} + +/* Disabling clears the control register and leaves the cycle registers. */ +static void apple_pwm_test_disable(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + struct pwm_state hw; + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, true), 0); + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 2000000, 1000000, false), 0); + + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_CTRL), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_ON_CYCLES), 6000); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_OFF_CYCLES), 18000); + + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_FALSE(test, hw.enabled); +} + +/* A disabled state never has its period or duty cycle looked at. */ +static void apple_pwm_test_disable_ignores_timing(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + + apple_pwm_test_set_regs(ctx, APPLE_PWM_TEST_CTRL_ON, 11, 22); + /* duty above period, which is only valid while disabled */ + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 5, U64_MAX, false), 0); + + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_CTRL), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_ON_CYCLES), 11); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_OFF_CYCLES), 22); +} + +static void apple_pwm_test_expect_untouched(struct kunit *test, int usage) +{ + struct apple_pwm_test *ctx = test->priv; + + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_CTRL), APPLE_PWM_TEST_CTRL_ON); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_ON_CYCLES), 6000); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_OFF_CYCLES), 18000); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage); + KUNIT_EXPECT_TRUE(test, ctx->fpwm->enabled); +} + +/* The hardware cannot invert: refused before anything is written. */ +static void apple_pwm_test_inversed_refused(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + struct pwm_state state = { + .period = 2000000, + .duty_cycle = 500000, + .polarity = PWM_POLARITY_INVERSED, + .enabled = true, + }; + int usage; + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, true), 0); + usage = apple_pwm_test_usage(ctx); + + KUNIT_EXPECT_EQ(test, pwm_apply_might_sleep(ctx->pwm, &state), -EINVAL); + apple_pwm_test_expect_untouched(test, usage); + + /* Also when it is asked for together with a disable. */ + state.enabled = false; + KUNIT_EXPECT_EQ(test, pwm_apply_might_sleep(ctx->pwm, &state), -EINVAL); + apple_pwm_test_expect_untouched(test, usage); + + /* And when the driver is called without the core in front. */ + KUNIT_EXPECT_EQ(test, apple_pwm_apply(ctx->chip, ctx->pwm, &state), -EINVAL); + apple_pwm_test_expect_untouched(test, usage); +} + +/* A duty cycle above the period never reaches the registers. */ +static void apple_pwm_test_duty_above_period_refused(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + int usage; + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, true), 0); + usage = apple_pwm_test_usage(ctx); + + KUNIT_EXPECT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 1000001, true), -EINVAL); + apple_pwm_test_expect_untouched(test, usage); +} + +/* Nor does an enabled state without a period. */ +static void apple_pwm_test_zero_period_refused(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + int usage; + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, true), 0); + usage = apple_pwm_test_usage(ctx); + + KUNIT_EXPECT_EQ(test, apple_pwm_test_apply(ctx, 0, 0, true), -EINVAL); + apple_pwm_test_expect_untouched(test, usage); +} + +/* + * A running output holds exactly one runtime PM reference, however often it + * is reprogrammed, and gives it back when it is disabled. + */ +static void apple_pwm_test_enable_holds_power(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + struct pwm_state off = { .polarity = PWM_POLARITY_NORMAL }; + int usage = apple_pwm_test_usage(ctx); + + if (!IS_ENABLED(CONFIG_PM)) + kunit_skip(test, "needs CONFIG_PM"); + + KUNIT_EXPECT_FALSE(test, ctx->fpwm->enabled); + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, true), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage + 1); + KUNIT_EXPECT_TRUE(test, ctx->fpwm->enabled); + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 500000, true), 0); + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 2000000, 500000, true), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage + 1); + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 2000000, 500000, false), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage); + KUNIT_EXPECT_FALSE(test, ctx->fpwm->enabled); + + /* A second disable, which the core would filter, gives nothing back. */ + KUNIT_ASSERT_EQ(test, apple_pwm_apply(ctx->chip, ctx->pwm, &off), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage); + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, true), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage + 1); + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, false), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage); +} + +/* Reading the state back takes no lasting power reference. */ +static void apple_pwm_test_get_state_power_balanced(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + int usage = apple_pwm_test_usage(ctx); + struct pwm_state hw; + + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage); +} + +/* + * The power domain may drop the registers of a stopped PWM: runtime suspend + * saves all three and runtime resume writes them back. + */ +static void apple_pwm_test_runtime_pm_keeps_registers(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + + apple_pwm_test_set_regs(ctx, APPLE_PWM_CTRL_MODE, 0x12345678, 0x9abcdef0); + KUNIT_ASSERT_EQ(test, apple_pwm_runtime_suspend(ctx->dev), 0); + + apple_pwm_test_set_regs(ctx, 0, 0, 0); + KUNIT_ASSERT_EQ(test, apple_pwm_runtime_resume(ctx->dev), 0); + + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_CTRL), APPLE_PWM_CTRL_MODE); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_ON_CYCLES), 0x12345678); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_OFF_CYCLES), 0x9abcdef0); +} + +static struct kunit_case apple_pwm_test_cases[] = { + KUNIT_CASE_PARAM(apple_pwm_test_apply_cycles, apple_pwm_test_conv_gen_params), + KUNIT_CASE_PARAM(apple_pwm_test_readback, apple_pwm_test_conv_gen_params), + KUNIT_CASE(apple_pwm_test_get_state_rounds_up), + KUNIT_CASE(apple_pwm_test_get_state_max), + KUNIT_CASE(apple_pwm_test_get_state_enabled), + KUNIT_CASE(apple_pwm_test_disable), + KUNIT_CASE(apple_pwm_test_disable_ignores_timing), + KUNIT_CASE(apple_pwm_test_inversed_refused), + KUNIT_CASE(apple_pwm_test_duty_above_period_refused), + KUNIT_CASE(apple_pwm_test_zero_period_refused), + KUNIT_CASE(apple_pwm_test_enable_holds_power), + KUNIT_CASE(apple_pwm_test_get_state_power_balanced), + KUNIT_CASE(apple_pwm_test_runtime_pm_keeps_registers), + {} +}; + +static struct kunit_suite apple_pwm_test_suite = { + .name = "pwm-apple", + .init = apple_pwm_test_init, + .test_cases = apple_pwm_test_cases, +}; + +kunit_test_suite(apple_pwm_test_suite); diff --git a/drivers/pwm/pwm-apple.c b/drivers/pwm/pwm-apple.c index 2659f777fafbe8..b42e24e498ce1d 100644 --- a/drivers/pwm/pwm-apple.c +++ b/drivers/pwm/pwm-apple.c @@ -252,3 +252,7 @@ module_platform_driver(apple_pwm_driver); MODULE_DESCRIPTION("Apple SoC PWM driver"); MODULE_LICENSE("Dual MIT/GPL"); + +#if IS_ENABLED(CONFIG_PWM_APPLE_KUNIT_TEST) +#include "pwm-apple-test.c" +#endif diff --git a/drivers/pwm/pwm-apple.kunitconfig b/drivers/pwm/pwm-apple.kunitconfig new file mode 100644 index 00000000000000..bdeebf43bf5333 --- /dev/null +++ b/drivers/pwm/pwm-apple.kunitconfig @@ -0,0 +1,7 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/pwm/pwm-apple.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_PM=y +CONFIG_PWM=y +CONFIG_PWM_APPLE=y +CONFIG_PWM_APPLE_KUNIT_TEST=y diff --git a/drivers/reset/Kconfig b/drivers/reset/Kconfig index 9579dd0528c48a..c25fdcd70c6dc0 100644 --- a/drivers/reset/Kconfig +++ b/drivers/reset/Kconfig @@ -33,6 +33,18 @@ config RESET_APPLE_CIO before the USB4/Thunderbolt host routers inside them can be brought up by the thunderbolt driver. +config RESET_APPLE_CIO_KUNIT_TEST + bool "KUnit tests for the Apple CIO reset driver" if !KUNIT_ALL_TESTS + depends on RESET_APPLE_CIO=y && KUNIT=y && OF_DYNAMIC + default KUNIT_ALL_TESTS + help + Run the deassert sequence of every CIO register layout against a + modelled request/busy register, including busy waits, timeouts and + write errors. Also probe a pmgr-child controller from a test device + tree fragment and check that the reset core refuses reset ids past + the number of ports. No hardware is accessed; only useful for kernel + developers. + config RESET_ASPEED tristate "ASPEED Reset Driver" depends on ARCH_ASPEED || COMPILE_TEST diff --git a/drivers/reset/reset-apple-cio-test.c b/drivers/reset/reset-apple-cio-test.c new file mode 100644 index 00000000000000..fde5b48c40ee29 --- /dev/null +++ b/drivers/reset/reset-apple-cio-test.c @@ -0,0 +1,655 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple CIO reset controller + * + * The CIO request register is a regmap whose read and write callbacks model + * the request/busy handshake described at the top of reset-apple-cio.c, so + * the real deassert sequences run without touching MMIO. A small device tree + * fragment under a disabled container exercises the pmgr-child probe path, + * the reset core's translation of reset ids and its refusal of ids past + * nr_resets. + */ + +#include +#include +#include +#include + +/* Phandles well above the ones QEMU and the DT compilers hand out. */ +#define CIO_TEST_PH_PROBE 0x00c10001 +#define CIO_TEST_PH_CORE 0x00c10002 +#define CIO_TEST_PH_NOREG 0x00c10003 +#define CIO_TEST_T6000_REG 0x1a034 + +/* + * One register with up to two timed transitions: after @left reads the value + * becomes @next, then after @left2 more reads it becomes @next2. A write runs + * the model's response to the request that was stored. + */ +struct cio_model { + u32 reg; + u32 val; + unsigned int left, left2; + u32 next, next2; + bool stuck; /* the current value never changes */ + void (*respond)(struct cio_model *m, u32 req); + int write_err; + unsigned int busy_reads; /* settle delay the response uses */ + unsigned int reads, writes, stray; + u32 last_write; + u32 val_at_write; /* register value seen by the write */ +}; + +static int cio_model_read(void *ctx, unsigned int reg, unsigned int *val) +{ + struct cio_model *m = ctx; + + if (reg != m->reg) { + m->stray++; + *val = 0; + return 0; + } + m->reads++; + *val = m->val; + if (m->stuck || !m->left) + return 0; + if (--m->left == 0) { + m->val = m->next; + m->left = m->left2; + m->next = m->next2; + m->left2 = 0; + } + return 0; +} + +static int cio_model_write(void *ctx, unsigned int reg, unsigned int val) +{ + struct cio_model *m = ctx; + + if (reg != m->reg) { + m->stray++; + return 0; + } + if (m->write_err) + return m->write_err; + m->writes++; + m->last_write = val; + m->val_at_write = m->val; + m->stuck = false; + m->left2 = 0; + if (m->respond) + m->respond(m, val); + return 0; +} + +/* t8103: request clears itself, busy while it runs, then only done is set. */ +static void cio_t8103_respond(struct cio_model *m, u32 req) +{ + m->val = req | T8103_CIO_CTRL_INIT_BUSY; + m->left = m->busy_reads; + m->next = T8103_CIO_CTRL_INIT_DONE; +} + +/* t6000/t8142: request bit N raises its busy bit, both clear when done. */ +static void cio_t6000_respond(struct cio_model *m, u32 req) +{ + u32 busy = req << 16; + + m->val |= req | busy; + m->left = m->busy_reads; + m->next = m->val & ~(req | busy); +} + +static void cio_t8142_respond(struct cio_model *m, u32 req) +{ + u32 busy = req << 1; + + m->val |= req | busy; + m->left = m->busy_reads; + m->next = m->val & ~(req | busy); +} + +/* t6050: request alone, then request and done, then both clear. */ +static void cio_t6050_respond(struct cio_model *m, u32 req) +{ + m->val |= req; + m->left = m->busy_reads; + m->next = m->val | (req << 1); + m->left2 = m->busy_reads; + m->next2 = m->val & ~(req | (req << 1)); +} + +static const struct regmap_config cio_test_regmap_config = { + .reg_bits = 32, + .reg_stride = 4, + .val_bits = 32, + .reg_read = cio_model_read, + .reg_write = cio_model_write, +}; + +/* Model behind the syscon regmap of the DT fixture; reset by every case. */ +static struct cio_model cio_test_dt_model; +static struct regmap *cio_test_dt_regmap; +static struct of_changeset cio_test_cs; +static struct device_node *cio_test_pmgr, *cio_test_probe_np, *cio_test_core_np, + *cio_test_noreg_np, *cio_test_consumer; + +struct cio_test { + struct cio_model m; + struct device *dev; + struct apple_cio_reset priv; + struct platform_device *pdev; +}; + +static int cio_test_init(struct kunit *test) +{ + struct cio_test *t; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + if (!t) + return -ENOMEM; + t->dev = kunit_device_register(test, "apple-cio-reset-test"); + if (IS_ERR(t->dev)) + return PTR_ERR(t->dev); + t->priv.dev = t->dev; + t->priv.regmap = devm_regmap_init(t->dev, NULL, &t->m, &cio_test_regmap_config); + if (IS_ERR(t->priv.regmap)) + return PTR_ERR(t->priv.regmap); + mutex_init(&t->priv.lock); + t->priv.rcdev.ops = &apple_cio_reset_ops; + t->m.busy_reads = 3; + memset(&cio_test_dt_model, 0, sizeof(cio_test_dt_model)); + cio_test_dt_model.busy_reads = 3; + test->priv = t; + return 0; +} + +static void cio_test_exit(struct kunit *test) +{ + struct cio_test *t = test->priv; + + if (t && t->pdev) + of_platform_device_destroy(&t->pdev->dev, NULL); +} + +static void cio_test_setup(struct cio_test *t, const struct apple_cio_reset_variant *v, + u32 offset, u32 reg, + void (*respond)(struct cio_model *m, u32 req)) +{ + t->priv.variant = v; + t->priv.offset = offset; + t->priv.rcdev.nr_resets = v->nr_resets; + t->m.reg = reg; + t->m.respond = respond; +} + +static int cio_test_deassert(struct cio_test *t, unsigned long id) +{ + return t->priv.rcdev.ops->deassert(&t->priv.rcdev, id); +} + +static void cio_t8103_port_page_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + unsigned long id; + + for (id = 0; id < apple_t8103_cio_reset.nr_resets; id++) { + cio_test_setup(t, &apple_t8103_cio_reset, 0x84000, + 0x84000 + id * T8103_CIO_CTRL_STRIDE, cio_t8103_respond); + t->m.val = 0; + t->m.writes = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, id), 0); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + /* A plain store of the request, not a read-modify-write. */ + KUNIT_EXPECT_EQ(test, t->m.last_write, T8103_CIO_CTRL_INIT_REQ); + KUNIT_EXPECT_EQ(test, t->m.val, T8103_CIO_CTRL_INIT_DONE); + KUNIT_EXPECT_EQ(test, t->m.left, 0U); + } + KUNIT_EXPECT_EQ(test, t->m.stray, 0U); +} + +static void cio_t8103_plain_store_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t8103_cio_reset, 0x84000, 0x84000, cio_t8103_respond); + /* Unknown bits read back are not replayed into the request. */ + t->m.val = BIT(8) | BIT(31); + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), 0); + KUNIT_EXPECT_EQ(test, t->m.last_write, T8103_CIO_CTRL_INIT_REQ); +} + +static void cio_t8103_waits_busy_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t8103_cio_reset, 0x84000, 0x84000, cio_t8103_respond); + t->m.val = T8103_CIO_CTRL_INIT_BUSY; + t->m.left = 4; + t->m.next = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), 0); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + KUNIT_EXPECT_EQ(test, t->m.val_at_write & T8103_CIO_CTRL_INIT_BUSY, 0U); + KUNIT_EXPECT_EQ(test, t->m.val, T8103_CIO_CTRL_INIT_DONE); +} + +static void cio_t8103_busy_advisory_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + /* A reconfiguration that never finishes only warns before the request. */ + cio_test_setup(t, &apple_t8103_cio_reset, 0x84000, 0x84000, cio_t8103_respond); + t->m.val = T8103_CIO_CTRL_INIT_BUSY; + t->m.stuck = true; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), 0); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + KUNIT_EXPECT_EQ(test, t->m.val_at_write, T8103_CIO_CTRL_INIT_BUSY); +} + +static void cio_t8103_timeout_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t8103_cio_reset, 0x84000, 0x84000, cio_t8103_respond); + t->m.busy_reads = 0; /* the response never settles */ + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + + /* Done must be the only bit set; anything else is not complete. */ + t->m.respond = NULL; + t->m.val = T8103_CIO_CTRL_INIT_DONE | BIT(5); + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), -ETIMEDOUT); +} + +static void cio_t6000_ports_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + unsigned long id; + + cio_test_setup(t, &apple_t6000_cio_reset, CIO_TEST_T6000_REG, CIO_TEST_T6000_REG, + cio_t6000_respond); + for (id = 0; id < apple_t6000_cio_reset.nr_resets; id++) { + t->m.writes = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, id), 0); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(id)); + /* Returns only once request and busy cleared again. */ + KUNIT_EXPECT_EQ(test, t->m.val, 0U); + KUNIT_EXPECT_EQ(test, t->m.left, 0U); + } + KUNIT_EXPECT_EQ(test, t->m.stray, 0U); +} + +static void cio_t6000_own_busy_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t6000_cio_reset, CIO_TEST_T6000_REG, CIO_TEST_T6000_REG, + cio_t6000_respond); + t->m.val = BIT(16 + 2); + t->m.left = 4; + t->m.next = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 2), 0); + KUNIT_EXPECT_EQ(test, t->m.val_at_write, 0U); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(2)); + KUNIT_EXPECT_EQ(test, t->m.val, 0U); +} + +static void cio_t6000_other_busy_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + /* Another port's reconfiguration: store our request, keep its bits. */ + cio_test_setup(t, &apple_t6000_cio_reset, CIO_TEST_T6000_REG, CIO_TEST_T6000_REG, + cio_t6000_respond); + t->m.val = BIT(16 + 3); + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), 0); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(0)); + KUNIT_EXPECT_EQ(test, t->m.val_at_write, (u32)BIT(16 + 3)); + KUNIT_EXPECT_EQ(test, t->m.val, (u32)BIT(16 + 3)); +} + +static void cio_t6000_timeout_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t6000_cio_reset, CIO_TEST_T6000_REG, CIO_TEST_T6000_REG, + cio_t6000_respond); + t->m.busy_reads = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 1), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); +} + +static void cio_t6000_write_error_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t6000_cio_reset, CIO_TEST_T6000_REG, CIO_TEST_T6000_REG, + cio_t6000_respond); + t->m.write_err = -EIO; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 1), -EIO); + KUNIT_EXPECT_EQ(test, t->m.writes, 0U); + /* No polling for a request that was never stored. */ + KUNIT_EXPECT_EQ(test, t->m.reads, 1U); + KUNIT_EXPECT_FALSE(test, mutex_is_locked(&t->priv.lock)); +} + +static void cio_t8142_ports_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + unsigned long id; + + /* The variant's own register: the generic offset is not used. */ + cio_test_setup(t, &apple_t8142_cio_reset, 0x1000, T8142_CIO_CTRL, cio_t8142_respond); + for (id = 0; id < apple_t8142_cio_reset.nr_resets; id++) { + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, id), 0); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(2 * id)); + KUNIT_EXPECT_EQ(test, t->m.val, 0U); + KUNIT_EXPECT_EQ(test, t->m.left, 0U); + } + KUNIT_EXPECT_EQ(test, t->m.writes, 4U); + KUNIT_EXPECT_EQ(test, t->m.stray, 0U); +} + +static void cio_t8142_serializes_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + /* Any port busy holds back a request for every port. */ + cio_test_setup(t, &apple_t8142_cio_reset, 0, T8142_CIO_CTRL, cio_t8142_respond); + t->m.val = BIT(2 * 3) | BIT(2 * 3 + 1); + t->m.left = 4; + t->m.next = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), 0); + KUNIT_EXPECT_EQ(test, t->m.val_at_write, 0U); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(0)); +} + +static void cio_t8142_refuses_busy_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t8142_cio_reset, 0, T8142_CIO_CTRL, cio_t8142_respond); + t->m.val = BIT(2 * 1 + 1); + t->m.stuck = true; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 2), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, t->m.writes, 0U); + /* Request bits alone are not busy. */ + t->m.val = BIT(2 * 1); + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 2), 0); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(2 * 2)); +} + +static void cio_t6050_sequence_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + unsigned long id; + + cio_test_setup(t, &apple_t6050_cio_reset, 0, 0x60, cio_t6050_respond); + for (id = 0; id < apple_t6050_cio_reset.nr_resets; id++) { + t->m.reads = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, id), 0); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(2 * id)); + /* Both transitions were waited for: request alone, then done. */ + KUNIT_EXPECT_EQ(test, t->m.val, 0U); + KUNIT_EXPECT_EQ(test, t->m.left, 0U); + KUNIT_EXPECT_GE(test, t->m.reads, 1U + 2 * t->m.busy_reads); + } + KUNIT_EXPECT_EQ(test, t->m.stray, 0U); +} + +static void cio_t6050_port_mask_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t6050_cio_reset, 0, 0x60, cio_t6050_respond); + /* Own request still pending from before: wait for it to clear. */ + t->m.val = BIT(2 * 1) | BIT(2 * 1 + 1); + t->m.left = 3; + t->m.next = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 1), 0); + KUNIT_EXPECT_EQ(test, t->m.val_at_write, 0U); + + /* Another port's bits do not hold the request back. */ + t->m.val = BIT(2 * 3) | BIT(2 * 3 + 1); + t->m.writes = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), 0); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + KUNIT_EXPECT_EQ(test, t->m.val, (u32)(BIT(2 * 3) | BIT(2 * 3 + 1))); +} + +static void cio_t6050_no_done_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + /* The request is never taken: done never shows up. */ + cio_test_setup(t, &apple_t6050_cio_reset, 0, 0x60, cio_t6050_respond); + t->m.busy_reads = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + KUNIT_EXPECT_EQ(test, t->m.val, (u32)BIT(0)); +} + +static void cio_match_table_test(struct kunit *test) +{ + static const struct { + const char *compatible; + const struct apple_cio_reset_variant *v; + } rows[] = { + { "apple,t6050-cio-reset", &apple_t6050_cio_reset }, + { "apple,t8142-cio-reset", &apple_t8142_cio_reset }, + { "apple,t8103-cio-reset", &apple_t8103_cio_reset }, + { "apple,t6000-cio-reset", &apple_t6000_cio_reset }, + { "apple,t6030-cio-reset", &apple_t6000_cio_reset }, + }; + const struct of_device_id *id; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(rows); i++) { + for (id = apple_cio_reset_match; id->compatible[0]; id++) + if (!strcmp(id->compatible, rows[i].compatible)) + break; + KUNIT_EXPECT_PTR_EQ_MSG(test, id->data, rows[i].v, "%s", rows[i].compatible); + } + KUNIT_EXPECT_EQ(test, apple_t8103_cio_reset.nr_resets, 2U); + KUNIT_EXPECT_TRUE(test, apple_t6000_cio_reset.pmgr_child); + KUNIT_EXPECT_FALSE(test, apple_t8142_cio_reset.pmgr_child); + KUNIT_EXPECT_FALSE(test, apple_t6050_cio_reset.pmgr_child); + KUNIT_EXPECT_EQ(test, apple_t6050_cio_reset.ctrl, 0x60U); + /* Only deassert: asserting needs the power domain cut. */ + KUNIT_EXPECT_NULL(test, apple_cio_reset_ops.assert); + KUNIT_EXPECT_NULL(test, apple_cio_reset_ops.reset); +} + +/* resets = <&probe 0>, <&probe 1>, <&probe 4>, <&core 3>, <&core 4>, <&noreg 0> */ +static void cio_core_xlate_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + struct reset_control *rc; + + cio_test_setup(t, &apple_t8142_cio_reset, 0, T8142_CIO_CTRL, cio_t8142_respond); + t->priv.rcdev.of_node = cio_test_core_np; + t->priv.rcdev.dev = t->dev; + KUNIT_ASSERT_EQ(test, devm_reset_controller_register(t->dev, &t->priv.rcdev), 0); + + rc = of_reset_control_get_exclusive_by_index(cio_test_consumer, 3); + KUNIT_ASSERT_FALSE_MSG(test, IS_ERR(rc), "get: %ld", PTR_ERR(rc)); + KUNIT_EXPECT_EQ(test, reset_control_deassert(rc), 0); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(2 * 3)); + KUNIT_EXPECT_EQ(test, t->m.val, 0U); + /* No .assert op: an exclusive assert cannot be honoured. */ + KUNIT_EXPECT_EQ(test, reset_control_assert(rc), -ENOTSUPP); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + reset_control_put(rc); + + /* Id 4 is past the four ports. */ + rc = of_reset_control_get_exclusive_by_index(cio_test_consumer, 4); + KUNIT_EXPECT_PTR_EQ(test, rc, ERR_PTR(-EINVAL)); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); +} + +static void cio_probe_pmgr_child_test(struct kunit *test) +{ + struct cio_model *m = &cio_test_dt_model; + struct cio_test *t = test->priv; + struct reset_control *rc; + + m->reg = CIO_TEST_T6000_REG; + m->respond = cio_t6000_respond; + t->pdev = of_platform_device_create(cio_test_probe_np, NULL, NULL); + KUNIT_ASSERT_NOT_NULL(test, t->pdev); + KUNIT_ASSERT_TRUE(test, device_is_bound(&t->pdev->dev)); + + rc = of_reset_control_get_exclusive_by_index(cio_test_consumer, 1); + KUNIT_ASSERT_FALSE_MSG(test, IS_ERR(rc), "get: %ld", PTR_ERR(rc)); + KUNIT_EXPECT_EQ(test, reset_control_deassert(rc), 0); + /* The offset came from "reg", the register map from the parent. */ + KUNIT_EXPECT_EQ(test, m->writes, 1U); + KUNIT_EXPECT_EQ(test, m->last_write, (u32)BIT(1)); + KUNIT_EXPECT_EQ(test, m->val, 0U); + KUNIT_EXPECT_EQ(test, m->stray, 0U); + reset_control_put(rc); + + rc = of_reset_control_get_exclusive_by_index(cio_test_consumer, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(rc)); + KUNIT_EXPECT_EQ(test, reset_control_deassert(rc), 0); + KUNIT_EXPECT_EQ(test, m->last_write, (u32)BIT(0)); + reset_control_put(rc); + + rc = of_reset_control_get_exclusive_by_index(cio_test_consumer, 2); + KUNIT_EXPECT_PTR_EQ(test, rc, ERR_PTR(-EINVAL)); + KUNIT_EXPECT_EQ(test, m->writes, 2U); +} + +static void cio_probe_no_reg_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + struct reset_control *rc; + + t->pdev = of_platform_device_create(cio_test_noreg_np, NULL, NULL); + KUNIT_ASSERT_NOT_NULL(test, t->pdev); + KUNIT_EXPECT_FALSE(test, device_is_bound(&t->pdev->dev)); + /* No controller was registered for it. */ + rc = of_reset_control_get_exclusive_by_index(cio_test_consumer, 5); + KUNIT_EXPECT_PTR_EQ(test, rc, ERR_PTR(-EPROBE_DEFER)); + KUNIT_EXPECT_EQ(test, cio_test_dt_model.writes, 0U); +} + +static struct device_node *cio_test_node(struct device_node *parent, const char *name, + const char *compatible, u32 phandle) +{ + struct device_node *np = of_changeset_create_node(&cio_test_cs, parent, name); + + if (!np) + return NULL; + if (compatible && of_changeset_add_prop_string(&cio_test_cs, np, "compatible", + compatible)) + return NULL; + if (phandle && (of_changeset_add_prop_u32(&cio_test_cs, np, "phandle", phandle) || + of_changeset_add_prop_u32(&cio_test_cs, np, "#reset-cells", 1))) + return NULL; + return np; +} + +static int cio_test_suite_init(struct kunit_suite *suite) +{ + static const u32 resets[] = { + CIO_TEST_PH_PROBE, 0, CIO_TEST_PH_PROBE, 1, CIO_TEST_PH_PROBE, 4, + CIO_TEST_PH_CORE, 3, CIO_TEST_PH_CORE, 4, CIO_TEST_PH_NOREG, 0, + }; + struct device_node *box; + int ret; + + if (!of_root) + return -ENODEV; + cio_test_dt_regmap = regmap_init(NULL, NULL, &cio_test_dt_model, + &cio_test_regmap_config); + if (IS_ERR(cio_test_dt_regmap)) + return PTR_ERR(cio_test_dt_regmap); + + of_changeset_init(&cio_test_cs); + /* Disabled container: nothing below it is populated on its own. */ + box = cio_test_node(of_root, "kunit-apple-cio-reset", NULL, 0); + if (!box || of_changeset_add_prop_string(&cio_test_cs, box, "status", "disabled")) + goto nomem; + cio_test_pmgr = cio_test_node(box, "power-management", NULL, 0); + cio_test_probe_np = cio_test_node(cio_test_pmgr, "cio-reset@1a034", + "apple,t6000-cio-reset", CIO_TEST_PH_PROBE); + cio_test_noreg_np = cio_test_node(cio_test_pmgr, "cio-reset", + "apple,t6000-cio-reset", CIO_TEST_PH_NOREG); + cio_test_core_np = cio_test_node(box, "core-reset", NULL, CIO_TEST_PH_CORE); + cio_test_consumer = cio_test_node(box, "consumer", NULL, 0); + if (!cio_test_pmgr || !cio_test_probe_np || !cio_test_noreg_np || + !cio_test_core_np || !cio_test_consumer || + of_changeset_add_prop_u32(&cio_test_cs, cio_test_probe_np, "reg", + CIO_TEST_T6000_REG) || + of_changeset_add_prop_u32_array(&cio_test_cs, cio_test_consumer, "resets", + resets, ARRAY_SIZE(resets))) + goto nomem; + ret = of_changeset_apply(&cio_test_cs); + if (ret) + goto destroy; + /* + * A changeset attaches a node before adding its properties, so the + * "phandle" property is not picked up by the attach: set it here. + */ + cio_test_probe_np->phandle = CIO_TEST_PH_PROBE; + cio_test_noreg_np->phandle = CIO_TEST_PH_NOREG; + cio_test_core_np->phandle = CIO_TEST_PH_CORE; + /* + * A syscon entry cannot be removed, so the node it is keyed by keeps + * an extra reference and the register map stays: neither is freed. + */ + of_node_get(cio_test_pmgr); + ret = of_syscon_register_regmap(cio_test_pmgr, cio_test_dt_regmap); + if (ret) + of_changeset_revert(&cio_test_cs); + return ret; + +nomem: + ret = -ENOMEM; +destroy: + of_changeset_destroy(&cio_test_cs); + regmap_exit(cio_test_dt_regmap); + return ret; +} + +static void cio_test_suite_exit(struct kunit_suite *suite) +{ + of_changeset_revert(&cio_test_cs); +} + +static struct kunit_case apple_cio_reset_test_cases[] = { + KUNIT_CASE(cio_t8103_port_page_test), + KUNIT_CASE(cio_t8103_plain_store_test), + KUNIT_CASE(cio_t8103_waits_busy_test), + KUNIT_CASE(cio_t8103_busy_advisory_test), + KUNIT_CASE(cio_t8103_timeout_test), + KUNIT_CASE(cio_t6000_ports_test), + KUNIT_CASE(cio_t6000_own_busy_test), + KUNIT_CASE(cio_t6000_other_busy_test), + KUNIT_CASE(cio_t6000_timeout_test), + KUNIT_CASE(cio_t6000_write_error_test), + KUNIT_CASE(cio_t8142_ports_test), + KUNIT_CASE(cio_t8142_serializes_test), + KUNIT_CASE(cio_t8142_refuses_busy_test), + KUNIT_CASE(cio_t6050_sequence_test), + KUNIT_CASE(cio_t6050_port_mask_test), + KUNIT_CASE(cio_t6050_no_done_test), + KUNIT_CASE(cio_match_table_test), + KUNIT_CASE(cio_core_xlate_test), + KUNIT_CASE(cio_probe_pmgr_child_test), + KUNIT_CASE(cio_probe_no_reg_test), + {} +}; + +static struct kunit_suite apple_cio_reset_test_suite = { + .name = "apple-cio-reset", + .suite_init = cio_test_suite_init, + .suite_exit = cio_test_suite_exit, + .init = cio_test_init, + .exit = cio_test_exit, + .test_cases = apple_cio_reset_test_cases, +}; + +kunit_test_suite(apple_cio_reset_test_suite); diff --git a/drivers/reset/reset-apple-cio.c b/drivers/reset/reset-apple-cio.c index e5755ebb39affb..52e52662fd020a 100644 --- a/drivers/reset/reset-apple-cio.c +++ b/drivers/reset/reset-apple-cio.c @@ -77,6 +77,15 @@ #define T8142_CIO_CTRL_INIT_BUSY(port) BIT(2 * (port) + 1) #define T8142_CIO_CTRL_BUSY_MASK 0xaa +/* T8152: the request and its completion are in two registers, one bit per port. */ +#define T8152_CIO_INIT_REQ 0x68 +#define T8152_CIO_INIT_DONE 0x6c +/* A request waits until none of its port pair (0-1 or 2-3) is pending. */ +#define T8152_CIO_INIT_PAIR_MASK(port) ((port) < 2 ? GENMASK(1, 0) : GENMASK(3, 2)) +#define T8152_CIO_POLL_US 10 +/* As long as a t6050 reconfiguration. */ +#define T8152_CIO_TIMEOUT_US APPLE_CIO_RESET_T6050_TIMEOUT_US + struct apple_cio_reset; struct apple_cio_reset_variant { @@ -200,6 +209,34 @@ static int t8142_cio_deassert(struct apple_cio_reset *priv, unsigned long id) APPLE_CIO_RESET_TIMEOUT_US); } +static int t8152_cio_deassert(struct apple_cio_reset *priv, unsigned long id) +{ + u32 val; + int ret; + + guard(mutex)(&priv->lock); + ret = regmap_read_poll_timeout(priv->regmap, T8152_CIO_INIT_REQ, val, + !(val & T8152_CIO_INIT_PAIR_MASK(id)), + T8152_CIO_POLL_US, T8152_CIO_TIMEOUT_US); + if (ret) + return ret; + ret = regmap_write(priv->regmap, T8152_CIO_INIT_REQ, BIT(id)); + if (ret) + return ret; + ret = regmap_read_poll_timeout(priv->regmap, T8152_CIO_INIT_DONE, val, + val & BIT(id), T8152_CIO_POLL_US, + T8152_CIO_TIMEOUT_US); + if (ret) + return ret; + /* Acknowledge the completion. */ + return regmap_write(priv->regmap, T8152_CIO_INIT_DONE, BIT(id)); +} + +static const struct apple_cio_reset_variant apple_t8152_cio_reset = { + .nr_resets = 4, + .deassert = t8152_cio_deassert, +}; + static const struct apple_cio_reset_variant apple_t8142_cio_reset = { .nr_resets = 4, .ctrl = T8142_CIO_CTRL, @@ -330,6 +367,7 @@ static int apple_cio_reset_probe(struct platform_device *pdev) } static const struct of_device_id apple_cio_reset_match[] = { + { .compatible = "apple,t8152-cio-reset", .data = &apple_t8152_cio_reset }, { .compatible = "apple,t6050-cio-reset", .data = &apple_t6050_cio_reset, @@ -366,3 +404,7 @@ module_platform_driver(apple_cio_reset_driver); MODULE_AUTHOR("Sven Peter "); MODULE_DESCRIPTION("Apple SoC CIO block reset driver"); MODULE_LICENSE("Dual MIT/GPL"); + +#if IS_ENABLED(CONFIG_RESET_APPLE_CIO_KUNIT_TEST) +#include "reset-apple-cio-test.c" +#endif diff --git a/drivers/reset/reset-apple-cio.kunitconfig b/drivers/reset/reset-apple-cio.kunitconfig new file mode 100644 index 00000000000000..308c61595e8b1c --- /dev/null +++ b/drivers/reset/reset-apple-cio.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_OF_OVERLAY=y +CONFIG_RESET_CONTROLLER=y +CONFIG_RESET_APPLE_CIO=y +CONFIG_RESET_APPLE_CIO_KUNIT_TEST=y diff --git a/drivers/rtc/Kconfig b/drivers/rtc/Kconfig index a7e6eba6e7910d..243c4a563798a1 100644 --- a/drivers/rtc/Kconfig +++ b/drivers/rtc/Kconfig @@ -2121,6 +2121,19 @@ config RTC_DRV_MACSMC To compile this driver as a module, choose M here: the module will be called rtc-macsmc. +config RTC_DRV_MACSMC_KUNIT_TEST + bool "KUnit tests for the Apple SMC RTC" if !KUNIT_ALL_TESTS + depends on RTC_DRV_MACSMC=y && KUNIT=y + depends on MFD_MACSMC_KUNIT_TEST && NVMEM + default KUNIT_ALL_TESTS + help + Build tests for the Apple SMC RTC's time and alarm arithmetic: the + 48-bit tick offset with its sign extension and wrap, the 64-bit + seconds offset and its rounding, and the PMU alarm's value, mask + and control byte writes. A static stub replaces the SMC counter + read and a RAM-backed NVMEM device holds the offset and alarm + cells, so the tests need no Apple hardware. + config RTC_DRV_MSC313 tristate "MStar MSC313 RTC" depends on ARCH_MSTARV7 || COMPILE_TEST diff --git a/drivers/rtc/rtc-apple-pmu.c b/drivers/rtc/rtc-apple-pmu.c index dc5db42c5c0e2e..2388c2eafd7220 100644 --- a/drivers/rtc/rtc-apple-pmu.c +++ b/drivers/rtc/rtc-apple-pmu.c @@ -22,10 +22,13 @@ #define APPLE_PMU_RTC_MAX_DELAY 3600 /* - * Register addresses in the PMIC's SPMI space. The counter is six bytes - * at 65536 Hz; the comparator is four bytes of whole counter seconds. + * Register offsets within the PMIC's SPMI RTC block, plus the historical + * default block base for devicetrees that omit apple,rtc-base. The counter + * is six bytes at 65536 Hz; the comparator is four bytes of whole counter + * seconds. */ struct apple_pmu_rtc_hw { + u16 base; u16 control; u16 counter; u16 compare; @@ -40,11 +43,12 @@ struct apple_pmu_rtc_hw { }; static const struct apple_pmu_rtc_hw apple_pmu_rtc_baku = { - .control = 0xf800, - .counter = 0xf802, - .compare = 0xf808, - .mask = 0xf80e, - .event = 0xf80c, + .base = 0xf800, + .control = 0x00, + .counter = 0x02, + .compare = 0x08, + .mask = 0x0e, + .event = 0x0c, .event_bit = BIT(0), .offset_in_seconds = true, /* As far as the comparator reaches: macOS's own deep-sleep wakes use it. */ @@ -52,23 +56,29 @@ static const struct apple_pmu_rtc_hw apple_pmu_rtc_baku = { }; static const struct apple_pmu_rtc_hw apple_pmu_rtc_abbey = { - .control = 0x2000, - .counter = 0x2002, - .compare = 0x2008, - .mask = 0x200e, - .event = 0x2000, + .base = 0x2000, + .control = 0x00, + .counter = 0x02, + .compare = 0x08, + .mask = 0x0e, + .event = 0x00, .event_bit = BIT(1), .monitor_bit = BIT(0), .max_delay = APPLE_PMU_RTC_MAX_DELAY, }; -/* M2 (t8112): Baku's register block with the offset in 1/32768 s. */ +/* + * M2 (t8112, Stowe at 0xf800) and compatible blocks at a DT-specified base + * such as M1 (t8103, Sera at 0xd000): Baku's layout with the offset in + * 1/32768 s. + */ static const struct apple_pmu_rtc_hw apple_pmu_rtc_stowe = { - .control = 0xf800, - .counter = 0xf802, - .compare = 0xf808, - .mask = 0xf80e, - .event = 0xf80c, + .base = 0xf800, + .control = 0x00, + .counter = 0x02, + .compare = 0x08, + .mask = 0x0e, + .event = 0x0c, .event_bit = BIT(0), .monitor_bit = BIT(0), .max_delay = APPLE_PMU_RTC_MAX_DELAY, @@ -76,11 +86,12 @@ static const struct apple_pmu_rtc_hw apple_pmu_rtc_stowe = { /* M1 Pro, Max and Ultra (t600x), offset in 1/32768 s */ static const struct apple_pmu_rtc_hw apple_pmu_rtc_maverick = { - .control = 0x1401, - .counter = 0x1406, - .compare = 0x140c, - .mask = 0x14c2, - .event = 0x14c0, + .base = 0x1400, + .control = 0x01, + .counter = 0x06, + .compare = 0x0c, + .mask = 0xc2, + .event = 0xc0, .event_bit = BIT(0), .control_event_bit = BIT(1), .monitor_bit = BIT(0), @@ -89,6 +100,7 @@ static const struct apple_pmu_rtc_hw apple_pmu_rtc_maverick = { struct apple_pmu_rtc { const struct apple_pmu_rtc_hw *hw; + u16 base; struct regmap *map; struct nvmem_cell *offset; struct rtc_device *clock; @@ -98,12 +110,17 @@ struct apple_pmu_rtc { bool io_failed; }; +static u16 apple_pmu_rtc_reg(const struct apple_pmu_rtc *rtc, u16 offset) +{ + return rtc->base + offset; +} + static int apple_pmu_rtc_counter(struct apple_pmu_rtc *rtc, u64 *ticks) { u8 count[8] = {}; int error; - error = regmap_bulk_read(rtc->map, rtc->hw->counter, + error = regmap_bulk_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->counter), count, 6); if (error) return error; @@ -195,11 +212,11 @@ static int apple_pmu_rtc_ack_alarm(struct apple_pmu_rtc *rtc) * when acknowledging, rather than writing only the event bit. */ if (rtc->hw->event == rtc->hw->control) { - error = regmap_read(rtc->map, rtc->hw->event, &control); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->event), &control); if (error) return error; } - return regmap_write(rtc->map, rtc->hw->event, control | rtc->hw->event_bit); + return regmap_write(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->event), control | rtc->hw->event_bit); } static int apple_pmu_rtc_arm(struct apple_pmu_rtc *rtc, bool enable) @@ -207,7 +224,7 @@ static int apple_pmu_rtc_arm(struct apple_pmu_rtc *rtc, bool enable) unsigned int control; int error; - error = regmap_read(rtc->map, rtc->hw->control, &control); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->control), &control); if (error) return error; /* Do not acknowledge a shared W1C event as a side effect of RMW. */ @@ -219,14 +236,14 @@ static int apple_pmu_rtc_arm(struct apple_pmu_rtc *rtc, bool enable) if (enable) control |= APPLE_PMU_RTC_ARM; control |= rtc->hw->monitor_bit; - return regmap_write(rtc->map, rtc->hw->control, control); + return regmap_write(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->control), control); } static int apple_pmu_rtc_stop_alarm(struct apple_pmu_rtc *rtc) { int error; - error = regmap_update_bits(rtc->map, rtc->hw->mask, + error = regmap_update_bits(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->mask), APPLE_PMU_RTC_ALARM, APPLE_PMU_RTC_ALARM); if (error) return error; @@ -242,7 +259,7 @@ static int apple_pmu_rtc_start_alarm(struct apple_pmu_rtc *rtc) error = apple_pmu_rtc_ack_alarm(rtc); if (!error) - error = regmap_update_bits(rtc->map, rtc->hw->mask, + error = regmap_update_bits(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->mask), APPLE_PMU_RTC_ALARM, 0); if (!error) error = apple_pmu_rtc_arm(rtc, true); @@ -279,14 +296,14 @@ static int apple_pmu_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alarm error = apple_pmu_rtc_offset(rtc, &epoch); if (error) return error; - error = regmap_bulk_read(rtc->map, rtc->hw->compare, + error = regmap_bulk_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->compare), &comparator, sizeof(comparator)); if (!error) - error = regmap_read(rtc->map, rtc->hw->control, &control); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->control), &control); if (!error) - error = regmap_read(rtc->map, rtc->hw->event, &event); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->event), &event); if (!error) - error = regmap_read(rtc->map, rtc->hw->mask, &mask); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->mask), &mask); if (error) return error; rtc_time64_to_tm((epoch >> APPLE_PMU_RTC_HZ_SHIFT) + @@ -320,11 +337,11 @@ static int apple_pmu_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alarm) if (error) return error; comparator = cpu_to_le32(deadline); - error = regmap_bulk_write(rtc->map, rtc->hw->compare, + error = regmap_bulk_write(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->compare), &comparator, sizeof(comparator)); if (error) return error; - error = regmap_bulk_read(rtc->map, rtc->hw->compare, + error = regmap_bulk_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->compare), &readback, sizeof(readback)); if (error) return error; @@ -346,7 +363,7 @@ static int apple_pmu_rtc_alarm_enable(struct device *dev, unsigned int enable) return apple_pmu_rtc_stop_alarm(rtc); if (rtc->io_failed) return -EIO; - error = regmap_bulk_read(rtc->map, rtc->hw->compare, + error = regmap_bulk_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->compare), &comparator, sizeof(comparator)); if (error) return error; @@ -362,7 +379,7 @@ static irqreturn_t apple_pmu_rtc_interrupt(int irq, void *context) int error; mutex_lock(&rtc->transaction); - error = regmap_read(rtc->map, rtc->hw->event, &event); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->event), &event); if (!error && (event & rtc->hw->event_bit)) error = apple_pmu_rtc_stop_alarm(rtc); if (error) { @@ -395,11 +412,11 @@ static int apple_pmu_rtc_init_alarm(struct apple_pmu_rtc *rtc) __le32 comparator; int error; - error = regmap_read(rtc->map, rtc->hw->control, &control); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->control), &control); if (!error) - error = regmap_read(rtc->map, rtc->hw->mask, &mask); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->mask), &mask); if (!error) - error = regmap_bulk_read(rtc->map, rtc->hw->compare, + error = regmap_bulk_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->compare), &comparator, sizeof(comparator)); if (error) return error; @@ -461,6 +478,39 @@ static void apple_pmu_rtc_release(void *context) device_init_wakeup(dev, false); } +static u16 apple_pmu_rtc_span(const struct apple_pmu_rtc_hw *hw) +{ + u16 end = hw->control + 1; + + end = max_t(u16, end, hw->counter + 6); + end = max_t(u16, end, hw->compare + 4); + end = max_t(u16, end, hw->mask + 1); + end = max_t(u16, end, hw->event + 1); + return end; +} + +static int apple_pmu_rtc_parse_base(struct device *dev, struct apple_pmu_rtc *rtc) +{ + u32 base; + u16 span = apple_pmu_rtc_span(rtc->hw); + int error; + + error = of_property_read_u32(dev->of_node, "apple,rtc-base", &base); + if (!error) { + if (base > 0xffff || (u64)base + span > 0x10000) + return dev_err_probe(dev, -EINVAL, + "invalid apple,rtc-base %#x (span %#x)\n", + base, span); + rtc->base = base; + return 0; + } + if (error == -EINVAL) { + rtc->base = rtc->hw->base; + return 0; + } + return dev_err_probe(dev, error, "failed to read apple,rtc-base\n"); +} + static int apple_pmu_rtc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -473,6 +523,9 @@ static int apple_pmu_rtc_probe(struct platform_device *pdev) rtc->hw = of_device_get_match_data(dev); if (!rtc->hw) return -EINVAL; + error = apple_pmu_rtc_parse_base(dev, rtc); + if (error) + return error; rtc->map = dev_get_regmap(dev->parent, NULL); if (!rtc->map) return dev_err_probe(dev, -EPROBE_DEFER, "PMIC regmap unavailable\n"); diff --git a/drivers/rtc/rtc-macsmc-test.c b/drivers/rtc/rtc-macsmc-test.c new file mode 100644 index 00000000000000..a71c72a95a77bc --- /dev/null +++ b/drivers/rtc/rtc-macsmc-test.c @@ -0,0 +1,574 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SMC RTC driver: the 48-bit tick and 64-bit + * seconds offset arithmetic and the PMU alarm programming. + * + * The CLKM counter comes from a static stub on apple_smc_read() (see + * MFD_MACSMC_KUNIT_TEST). The offset and alarm cells are real NVMEM cells of + * a RAM-backed NVMEM device, found through a cell lookup table, so the cell + * sizes and byte layouts are checked by the NVMEM core as on hardware. + * + * Included by rtc-macsmc.c. + */ + +#include +#include +#include +#include + +#define RTC_TEST_OFFSET 0 +#define RTC_TEST_CTRL 8 +#define RTC_TEST_MASK 9 +#define RTC_TEST_ALARM 12 +#define RTC_TEST_NVMEM_SIZE 16 + +#define RTC_TEST_TICKS BIT_ULL(RTC_SEC_SHIFT) +#define RTC_TEST_MASK48 GENMASK_ULL(RTC_BITS - 1, 0) + +/* 2023-11-14 22:13:20 UTC */ +#define RTC_TEST_T 1700000000LL + +struct macsmc_rtc_test_write { + unsigned int offset; + size_t bytes; + u8 val[8]; +}; + +struct macsmc_rtc_test { + struct apple_smc smc; + struct macsmc_rtc rtc; + struct device *dev; + u8 nvmem[RTC_TEST_NVMEM_SIZE]; + /* CLKM: the free-running 32768 Hz counter, and what its read returns */ + u64 clkm; + int clkm_ret; + /* NVMEM writes, in order; a write at fail_offset fails */ + struct macsmc_rtc_test_write writes[8]; + unsigned int nr_writes; + int fail_offset; + struct nvmem_cell_lookup lookups[4]; +}; + +static int macsmc_rtc_test_read(struct apple_smc *smc, smc_key key, void *buf, + size_t size) +{ + struct macsmc_rtc_test *ctx = container_of(smc, struct macsmc_rtc_test, smc); + struct kunit *test = kunit_get_current_test(); + u8 le[8]; + + KUNIT_EXPECT_EQ(test, key, SMC_KEY(CLKM)); + KUNIT_EXPECT_EQ(test, size, RTC_BYTES); + if (ctx->clkm_ret < 0) + return ctx->clkm_ret; + + put_unaligned_le64(ctx->clkm, le); + memcpy(buf, le, min(size, sizeof(le))); + return ctx->clkm_ret ?: size; +} + +static int macsmc_rtc_test_reg_read(void *priv, unsigned int offset, void *val, + size_t bytes) +{ + struct macsmc_rtc_test *ctx = priv; + + memcpy(val, ctx->nvmem + offset, bytes); + return 0; +} + +static int macsmc_rtc_test_reg_write(void *priv, unsigned int offset, void *val, + size_t bytes) +{ + struct macsmc_rtc_test *ctx = priv; + struct macsmc_rtc_test_write *w; + + if (offset == ctx->fail_offset) + return -EIO; + + if (ctx->nr_writes < ARRAY_SIZE(ctx->writes)) { + w = &ctx->writes[ctx->nr_writes]; + w->offset = offset; + w->bytes = bytes; + memcpy(w->val, val, min(bytes, sizeof(w->val))); + } + ctx->nr_writes++; + memcpy(ctx->nvmem + offset, val, bytes); + return 0; +} + +static void macsmc_rtc_test_del_lookups(void *data) +{ + struct macsmc_rtc_test *ctx = data; + + nvmem_del_cell_lookups(ctx->lookups, ARRAY_SIZE(ctx->lookups)); +} + +KUNIT_DEFINE_ACTION_WRAPPER(macsmc_rtc_test_cell_put, nvmem_cell_put, + struct nvmem_cell *); + +static struct nvmem_cell *macsmc_rtc_test_cell(struct kunit *test, + struct macsmc_rtc_test *ctx, + const char *id) +{ + struct nvmem_cell *cell = nvmem_cell_get(ctx->dev, id); + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cell); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_rtc_test_cell_put, + cell), 0); + return cell; +} + +/* + * An RTC whose offset cell holds @offset_bytes bytes: 6 for a tick offset, + * 8 for a seconds offset. + */ +static struct macsmc_rtc_test *macsmc_rtc_test_setup(struct kunit *test, + bool offset_in_seconds, + unsigned int offset_bytes) +{ + static const char * const names[] = { + "rtc_offset", "rtc_ctrl", "rtc_alarm_mask", "rtc_alarm", + }; + const unsigned int offsets[] = { + RTC_TEST_OFFSET, RTC_TEST_CTRL, RTC_TEST_MASK, RTC_TEST_ALARM, + }; + const unsigned int sizes[] = { offset_bytes, 1, 1, 4 }; + struct nvmem_config config = {}; + struct nvmem_cell_info *cells; + struct macsmc_rtc_test *ctx; + struct nvmem_device *nvmem; + struct device *provider; + int i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + cells = kunit_kcalloc(test, ARRAY_SIZE(names), sizeof(*cells), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, cells); + ctx->fail_offset = -1; + mutex_init(&ctx->smc.mutex); + + for (i = 0; i < ARRAY_SIZE(names); i++) { + cells[i].name = names[i]; + cells[i].offset = offsets[i]; + cells[i].bytes = sizes[i]; + } + + provider = kunit_device_register(test, "nvmem"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, provider); + config.dev = provider; + config.name = "macsmc-rtc-test"; + config.id = NVMEM_DEVID_AUTO; + config.cells = cells; + config.ncells = ARRAY_SIZE(names); + config.ignore_wp = true; + config.reg_read = macsmc_rtc_test_reg_read; + config.reg_write = macsmc_rtc_test_reg_write; + config.size = RTC_TEST_NVMEM_SIZE; + config.priv = ctx; + nvmem = devm_nvmem_register(provider, &config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, nvmem); + + ctx->dev = kunit_device_register(test, "rtc"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + for (i = 0; i < ARRAY_SIZE(names); i++) { + ctx->lookups[i].nvmem_name = nvmem_dev_name(nvmem); + ctx->lookups[i].cell_name = names[i]; + ctx->lookups[i].dev_id = dev_name(ctx->dev); + ctx->lookups[i].con_id = names[i]; + } + nvmem_add_cell_lookups(ctx->lookups, ARRAY_SIZE(ctx->lookups)); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_rtc_test_del_lookups, + ctx), 0); + + ctx->rtc.dev = ctx->dev; + ctx->rtc.smc = &ctx->smc; + ctx->rtc.offset_in_seconds = offset_in_seconds; + mutex_init(&ctx->rtc.alarm_lock); + ctx->rtc.rtc_offset = macsmc_rtc_test_cell(test, ctx, "rtc_offset"); + ctx->rtc.alarm_ctrl = macsmc_rtc_test_cell(test, ctx, "rtc_ctrl"); + ctx->rtc.alarm_mask = macsmc_rtc_test_cell(test, ctx, "rtc_alarm_mask"); + ctx->rtc.alarm_value = macsmc_rtc_test_cell(test, ctx, "rtc_alarm"); + dev_set_drvdata(ctx->dev, &ctx->rtc); + + kunit_activate_static_stub(test, apple_smc_read, macsmc_rtc_test_read); + return ctx; +} + +static void macsmc_rtc_test_put_tick_offset(struct macsmc_rtc_test *ctx, u64 off) +{ + u8 le[8]; + + put_unaligned_le64(off & RTC_TEST_MASK48, le); + memcpy(ctx->nvmem + RTC_TEST_OFFSET, le, RTC_BYTES); +} + +static u64 macsmc_rtc_test_tick_offset(struct macsmc_rtc_test *ctx) +{ + u8 le[8] = {}; + + memcpy(le, ctx->nvmem + RTC_TEST_OFFSET, RTC_BYTES); + return get_unaligned_le64(le); +} + +static time64_t macsmc_rtc_test_now(struct kunit *test, struct macsmc_rtc_test *ctx) +{ + struct rtc_time tm = {}; + int ret; + + ret = macsmc_rtc_get_time(ctx->dev, &tm); + KUNIT_EXPECT_GE(test, ret, 0); + if (ret < 0) + return S64_MIN; + return rtc_tm_to_time64(&tm); +} + +static int macsmc_rtc_test_set(struct macsmc_rtc_test *ctx, time64_t t) +{ + struct rtc_time tm; + + rtc_time64_to_tm(t, &tm); + return macsmc_rtc_set_time(ctx->dev, &tm); +} + +static void macsmc_rtc_test_expect_write(struct kunit *test, + struct macsmc_rtc_test *ctx, + unsigned int idx, unsigned int offset, + size_t bytes, u64 val) +{ + struct macsmc_rtc_test_write *w = &ctx->writes[idx]; + u8 le[8]; + + KUNIT_ASSERT_LT(test, idx, ctx->nr_writes); + put_unaligned_le64(val, le); + KUNIT_EXPECT_EQ_MSG(test, w->offset, offset, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, w->bytes, bytes, "write %u", idx); + KUNIT_EXPECT_MEMEQ_MSG(test, w->val, le, bytes, "write %u", idx); +} + +/* Tick offset: time = sign_extend48(CLKM + offset) / 2^15, rounded down. */ +static void macsmc_rtc_test_tick_read(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + u64 ctr = 0x123456789abULL; + + ctx->clkm = ctr; + macsmc_rtc_test_put_tick_offset(ctx, (RTC_TEST_T << RTC_SEC_SHIFT) + 12345 - ctr); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); + + /* One tick before the next second, and the second itself. */ + ctx->clkm = ctr + RTC_TEST_TICKS - 12345 - 1; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); + ctx->clkm++; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T + 1); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* The sum is taken modulo 2^48: a carry out of bit 47 is not time. */ +static void macsmc_rtc_test_tick_wrap(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + + ctx->clkm = RTC_TEST_MASK48 + 1 - RTC_TEST_TICKS; + macsmc_rtc_test_put_tick_offset(ctx, (RTC_TEST_T << RTC_SEC_SHIFT) + RTC_TEST_TICKS); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); +} + +/* Set then read: the stored 6 bytes, and the set second starts at the set. */ +static void macsmc_rtc_test_tick_set(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + u64 ctr = 0x00ab12345678ULL; + + ctx->clkm = ctr; + /* .set_time returns 0, not the cell write's byte count. */ + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 1); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_OFFSET, RTC_BYTES, + ((RTC_TEST_T << RTC_SEC_SHIFT) - ctr) & RTC_TEST_MASK48); + + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); + ctx->clkm = ctr + RTC_TEST_TICKS - 1; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); + ctx->clkm = ctr + 3 * RTC_TEST_TICKS + 100; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T + 3); +} + +/* A time before 1970 is a negative 48-bit sum and must read back as such. */ +static void macsmc_rtc_test_tick_negative(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + struct rtc_time tm = {}; + + ctx->clkm = 1000 * RTC_TEST_TICKS + 5; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, -1), 0); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_tick_offset(ctx), + ((u64)-(1LL << RTC_SEC_SHIFT) - ctx->clkm) & RTC_TEST_MASK48); + + KUNIT_EXPECT_GE(test, macsmc_rtc_get_time(ctx->dev, &tm), 0); + KUNIT_EXPECT_EQ(test, tm.tm_year, 69); + KUNIT_EXPECT_EQ(test, tm.tm_mon, 11); + KUNIT_EXPECT_EQ(test, tm.tm_mday, 31); + KUNIT_EXPECT_EQ(test, tm.tm_hour, 23); + KUNIT_EXPECT_EQ(test, tm.tm_min, 59); + KUNIT_EXPECT_EQ(test, tm.tm_sec, 59); +} + +/* Seconds offset: time = CLKM / 2^15 + offset, offset a LE64 at the cell. */ +static void macsmc_rtc_test_secs_read(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + + put_unaligned_le64(RTC_TEST_T, ctx->nvmem + RTC_TEST_OFFSET); + ctx->clkm = 5 * RTC_TEST_TICKS + RTC_TEST_TICKS - 1; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T + 5); + + /* Bits above the counter's 48 are not read: CLKM is a 6-byte key. */ + ctx->clkm = BIT_ULL(RTC_BITS) | (7 * RTC_TEST_TICKS); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T + 7); +} + +/* An offset never written is not a time: reading it must fail. */ +static void macsmc_rtc_test_secs_unset(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_time tm; + + ctx->clkm = 1234 * RTC_TEST_TICKS; + KUNIT_EXPECT_EQ(test, macsmc_rtc_get_time(ctx->dev, &tm), -EINVAL); +} + +/* A seconds-mode offset cell shorter than 8 bytes is rejected, not half read. */ +static void macsmc_rtc_test_secs_short_cell(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, RTC_BYTES); + struct rtc_wkalrm alrm = { .enabled = 1 }; + struct rtc_time tm; + + memset(ctx->nvmem, 0x11, RTC_BYTES); + KUNIT_EXPECT_EQ(test, macsmc_rtc_get_time(ctx->dev, &tm), -EIO); + rtc_time64_to_tm(RTC_TEST_T, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -EIO); + KUNIT_EXPECT_EQ(test, macsmc_rtc_read_alarm(ctx->dev, &alrm), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* The seconds offset rounds the counter to the nearest second. */ +static void macsmc_rtc_test_secs_set(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + + ctx->clkm = 10 * RTC_TEST_TICKS + RTC_TEST_TICKS / 2 - 1; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), 0); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_OFFSET, 8, RTC_TEST_T - 10); + + ctx->clkm = 10 * RTC_TEST_TICKS + RTC_TEST_TICKS / 2; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), 0); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_OFFSET, 8, RTC_TEST_T - 11); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 2); + + /* Read back half a second later: at most half a second off. */ + ctx->clkm += RTC_TEST_TICKS / 2; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); +} + +/* CLKM failures and short replies fail the call and write nothing. */ +static void macsmc_rtc_test_clkm_errors(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + struct rtc_time tm; + + ctx->clkm_ret = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, macsmc_rtc_get_time(ctx->dev, &tm), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), -ETIMEDOUT); + + ctx->clkm_ret = 4; + KUNIT_EXPECT_EQ(test, macsmc_rtc_get_time(ctx->dev, &tm), -EIO); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), -EIO); + + ctx->rtc.offset_in_seconds = true; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* + * Arming: a latched event is cleared by writing it back, then the value + * (counter seconds, LE32), the mask and the control byte with EN | MONITOR. + * The PMU's other control bits are kept. + */ +static void macsmc_rtc_test_alarm_arm(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + struct rtc_wkalrm alrm = { .enabled = 1 }; + const s64 off = 1000000; + + /* A tick offset with a fraction: whole seconds are used. */ + macsmc_rtc_test_put_tick_offset(ctx, (off << RTC_SEC_SHIFT) + 1234); + ctx->nvmem[RTC_TEST_CTRL] = 0x80 | RTC_CTRL_ALARM_EVENT; + ctx->nvmem[RTC_TEST_MASK] = 1; + + rtc_time64_to_tm(off + 4321, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, ctx->rtc.alarm_secs, 4321); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 4); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_CTRL, 1, + 0x80 | RTC_CTRL_ALARM_EVENT); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_ALARM, 4, 4321); + macsmc_rtc_test_expect_write(test, ctx, 2, RTC_TEST_MASK, 1, 0); + macsmc_rtc_test_expect_write(test, ctx, 3, RTC_TEST_CTRL, 1, + 0x80 | RTC_CTRL_ALARM_EN | RTC_CTRL_MONITOR); +} + +/* A disabled alarm is remembered but disarms; enabling it arms the same second. */ +static void macsmc_rtc_test_alarm_disabled(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_wkalrm alrm = { .enabled = 0 }; + + put_unaligned_le64(RTC_TEST_T, ctx->nvmem + RTC_TEST_OFFSET); + /* Left armed by firmware, no event. */ + ctx->nvmem[RTC_TEST_CTRL] = RTC_CTRL_ALARM_EN | RTC_CTRL_MONITOR; + + rtc_time64_to_tm(RTC_TEST_T + 60, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, ctx->rtc.alarm_secs, 60); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_MASK, 1, 1); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_CTRL, 1, RTC_CTRL_MONITOR); + + ctx->nr_writes = 0; + KUNIT_EXPECT_EQ(test, macsmc_rtc_alarm_irq_enable(ctx->dev, 1), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 3); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_ALARM, 4, 60); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_MASK, 1, 0); + macsmc_rtc_test_expect_write(test, ctx, 2, RTC_TEST_CTRL, 1, + RTC_CTRL_ALARM_EN | RTC_CTRL_MONITOR); + + ctx->nr_writes = 0; + KUNIT_EXPECT_EQ(test, macsmc_rtc_alarm_irq_enable(ctx->dev, 0), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_CTRL, 1, RTC_CTRL_MONITOR); +} + +/* The 32-bit compare holds counter seconds 1..U32_MAX; others are refused. */ +static void macsmc_rtc_test_alarm_range(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_wkalrm alrm = { .enabled = 1 }; + const time64_t off = 86400; + + put_unaligned_le64(off, ctx->nvmem + RTC_TEST_OFFSET); + + rtc_time64_to_tm(off, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -ERANGE); + rtc_time64_to_tm(off - 5, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -ERANGE); + rtc_time64_to_tm(off + (time64_t)U32_MAX + 1, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -ERANGE); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); + + rtc_time64_to_tm(off + 1, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(ctx->nvmem + RTC_TEST_ALARM), 1); + rtc_time64_to_tm(off + U32_MAX, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(ctx->nvmem + RTC_TEST_ALARM), U32_MAX); +} + +/* A negative tick offset moves the alarm's counter second forward. */ +static void macsmc_rtc_test_alarm_negative_offset(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + struct rtc_wkalrm alrm = { .enabled = 1 }; + + macsmc_rtc_test_put_tick_offset(ctx, (u64)-(5LL << RTC_SEC_SHIFT)); + rtc_time64_to_tm(100, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(ctx->nvmem + RTC_TEST_ALARM), 105); + + memset(&alrm, 0, sizeof(alrm)); + KUNIT_EXPECT_EQ(test, macsmc_rtc_read_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, rtc_tm_to_time64(&alrm.time), 100); + KUNIT_EXPECT_TRUE(test, alrm.enabled); + KUNIT_EXPECT_FALSE(test, alrm.pending); +} + +/* Reading decodes the value against the offset and the EN/EVENT bits. */ +static void macsmc_rtc_test_alarm_read(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_wkalrm alrm = {}; + + put_unaligned_le64(RTC_TEST_T, ctx->nvmem + RTC_TEST_OFFSET); + put_unaligned_le32(777, ctx->nvmem + RTC_TEST_ALARM); + ctx->nvmem[RTC_TEST_CTRL] = RTC_CTRL_ALARM_EN | RTC_CTRL_ALARM_EVENT; + KUNIT_EXPECT_EQ(test, macsmc_rtc_read_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, rtc_tm_to_time64(&alrm.time), RTC_TEST_T + 777); + KUNIT_EXPECT_TRUE(test, alrm.enabled); + KUNIT_EXPECT_TRUE(test, alrm.pending); + + ctx->nvmem[RTC_TEST_CTRL] = RTC_CTRL_MONITOR; + KUNIT_EXPECT_EQ(test, macsmc_rtc_read_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_FALSE(test, alrm.enabled); + KUNIT_EXPECT_FALSE(test, alrm.pending); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* The interrupt is one-shot: an event clears and disarms; no event is not ours. */ +static void macsmc_rtc_test_alarm_irq(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + const u8 armed = RTC_CTRL_ALARM_EN | RTC_CTRL_MONITOR; + + ctx->nvmem[RTC_TEST_CTRL] = armed; + KUNIT_EXPECT_EQ(test, macsmc_rtc_alarm_irq(0, &ctx->rtc), IRQ_NONE); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); + + ctx->nvmem[RTC_TEST_CTRL] = armed | RTC_CTRL_ALARM_EVENT; + KUNIT_EXPECT_EQ(test, macsmc_rtc_alarm_irq(0, &ctx->rtc), IRQ_HANDLED); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 3); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_CTRL, 1, + armed | RTC_CTRL_ALARM_EVENT); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_MASK, 1, 1); + macsmc_rtc_test_expect_write(test, ctx, 2, RTC_TEST_CTRL, 1, RTC_CTRL_MONITOR); +} + +/* A failed mask write leaves the alarm unarmed and reports the error. */ +static void macsmc_rtc_test_alarm_write_error(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_wkalrm alrm = { .enabled = 1 }; + + put_unaligned_le64(RTC_TEST_T, ctx->nvmem + RTC_TEST_OFFSET); + ctx->fail_offset = RTC_TEST_MASK; + rtc_time64_to_tm(RTC_TEST_T + 10, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nvmem[RTC_TEST_CTRL], 0); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 1); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_ALARM, 4, 10); +} + +static struct kunit_case macsmc_rtc_test_cases[] = { + KUNIT_CASE(macsmc_rtc_test_tick_read), + KUNIT_CASE(macsmc_rtc_test_tick_wrap), + KUNIT_CASE(macsmc_rtc_test_tick_set), + KUNIT_CASE(macsmc_rtc_test_tick_negative), + KUNIT_CASE(macsmc_rtc_test_secs_read), + KUNIT_CASE(macsmc_rtc_test_secs_unset), + KUNIT_CASE(macsmc_rtc_test_secs_short_cell), + KUNIT_CASE(macsmc_rtc_test_secs_set), + KUNIT_CASE(macsmc_rtc_test_clkm_errors), + KUNIT_CASE(macsmc_rtc_test_alarm_arm), + KUNIT_CASE(macsmc_rtc_test_alarm_disabled), + KUNIT_CASE(macsmc_rtc_test_alarm_range), + KUNIT_CASE(macsmc_rtc_test_alarm_negative_offset), + KUNIT_CASE(macsmc_rtc_test_alarm_read), + KUNIT_CASE(macsmc_rtc_test_alarm_irq), + KUNIT_CASE(macsmc_rtc_test_alarm_write_error), + {} +}; + +static struct kunit_suite macsmc_rtc_test_suite = { + .name = "macsmc-rtc", + .test_cases = macsmc_rtc_test_cases, +}; + +kunit_test_suite(macsmc_rtc_test_suite); diff --git a/drivers/rtc/rtc-macsmc.c b/drivers/rtc/rtc-macsmc.c index 690a4a84ff90e5..634e3aa3fab238 100644 --- a/drivers/rtc/rtc-macsmc.c +++ b/drivers/rtc/rtc-macsmc.c @@ -149,7 +149,8 @@ static int macsmc_rtc_set_time(struct device *dev, struct rtc_time *tm) /* This sets the offset such that the set second begins now */ off = (rtc_tm_to_time64(tm) << RTC_SEC_SHIFT) - ctr; - return nvmem_cell_write(rtc->rtc_offset, &off, RTC_BYTES); + ret = nvmem_cell_write(rtc->rtc_offset, &off, RTC_BYTES); + return ret < 0 ? ret : 0; } @@ -482,3 +483,7 @@ module_platform_driver(macsmc_rtc_driver); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple SMC RTC driver"); MODULE_AUTHOR("Hector Martin "); + +#if IS_ENABLED(CONFIG_RTC_DRV_MACSMC_KUNIT_TEST) +#include "rtc-macsmc-test.c" +#endif diff --git a/drivers/rtc/rtc-macsmc.kunitconfig b/drivers/rtc/rtc-macsmc.kunitconfig new file mode 100644 index 00000000000000..08faff88f7bd88 --- /dev/null +++ b/drivers/rtc/rtc-macsmc.kunitconfig @@ -0,0 +1,13 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/rtc/rtc-macsmc.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_NVMEM=y +CONFIG_RTC_CLASS=y +CONFIG_RTC_DRV_MACSMC=y +CONFIG_RTC_DRV_MACSMC_KUNIT_TEST=y diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index a9cf80938dc4e1..00c137d065030e 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -25,6 +25,20 @@ config APPLE_DBGVIEW Say m here if you debug an Apple SoC. +config APPLE_DBGVIEW_KUNIT_TEST + tristate "KUnit tests for the Apple SoC debug register views" if !KUNIT_ALL_TESTS + depends on APPLE_DBGVIEW && KUNIT && PM + default KUNIT_ALL_TESTS + help + Read the regs and snapshot views of a register block that the + test backs with kernel memory: whole, partial, unaligned, short + and page-sized reads, end of block, runtime PM references and + failures, bad user buffers, the snapshot format and its size + parameter, and that no view writes the block. The tests touch no + hardware. + + If unsure, say N. + config APPLE_DOCKCHANNEL tristate "Apple DockChannel FIFO" depends on ARCH_APPLE || COMPILE_TEST @@ -34,6 +48,22 @@ config APPLE_DOCKCHANNEL Say 'y' here if you have an Apple SoC. +config APPLE_DOCKCHANNEL_KUNIT_TEST + bool "KUnit tests for the Apple DockChannel FIFO" if !KUNIT_ALL_TESTS + depends on APPLE_DOCKCHANNEL=y && KUNIT=y + select IRQ_SIM + default KUNIT_ALL_TESTS + help + Send and receive through a DockChannel FIFO that the test models + behind static stubs: whole words and tail bytes, a FIFO with + partial, exact or no room, the TX and RX thresholds and waits, + timeouts, a count register that reports more than the caller's + buffer, and the receive callback. The FIFO interrupts are + simulated interrupts and the interrupt controller registers are + kernel memory. The tests touch no hardware. + + If unsure, say N. + config APPLE_MAILBOX tristate "Apple SoC mailboxes" depends on PM @@ -46,18 +76,22 @@ config APPLE_MAILBOX Say Y here if you have an Apple SoC. +config APPLE_MCC_BOOT_DMA + bool + config APPLE_MCC - tristate "Apple T8140 and T6040 system level cache" + tristate "Apple T8140, T6040 and T6050 system level cache" + select APPLE_MCC_BOOT_DMA depends on ARCH_APPLE || COMPILE_TEST depends on OF default ARCH_APPLE help - The boot firmware of the Apple T8140 and T6040 SoCs enables the - system level cache without letting it allocate. This driver allows - allocation once the devices that took over DMA from the bootloader - are bound. + The boot firmware of the Apple T8140, T6040 and T6050 SoCs enables + the system level cache without letting it allocate. This driver + allows allocation once the devices that took over DMA from the + bootloader are bound. - Say 'y' or 'm' here if you have an Apple T8140 or T6040 SoC. + Say 'y' or 'm' here if you have an Apple T8140, T6040 or T6050 SoC. config APPLE_MCC_KUNIT_TEST bool "KUnit tests for Apple MCC allocation and unwind" if !KUNIT_ALL_TESTS @@ -90,6 +124,18 @@ config APPLE_PMGR_DCS_KUNIT_TEST Also verify that boot constraints and concurrent endpoints retain their votes, and that suspend restores the last confirmed request. +config APPLE_PMGR_FABRIC_KUNIT_TEST + bool "KUnit tests for the Apple PMGR fabric controls" if !KUNIT_ALL_TESTS + depends on KUNIT=y && APPLE_PMGR_MISC=y && OF_DYNAMIC && MFD_SYSCON + default KUNIT_ALL_TESTS + help + Test the fabric and DCS suspend and resume p-states with and + without PMP, the confirmed fabric raise and its timeout, fabric + holds, the idle fabric governor and its parameter, and the device + tree lookup of the governor's bandwidth voters, on simulated + registers and a test device tree fragment. No hardware is accessed; + only useful for kernel developers. + config APPLE_CLUSTER_PWRGATE bool "Apple SoC CPU cluster power gates" depends on OF @@ -113,9 +159,13 @@ config APPLE_SOC_SLEEP /chosen/aurora,s2r-mailbox. Only SoCs whose sleep has been measured and tested are supported, - each by its match data: today T8140, T8132 and T6050. On every other + each by its match data: today T8140, T8132, T6050 and T8103. On every other SoC the driver doesn't bind, and s2idle stays the only system sleep. + T6041 (M4 Max) has a driver of its own, t6041-sleep, which binds + to an "apple,t6041-sleep" node and uses this driver's coprocessor + stop. + config APPLE_SOC_SLEEP_KUNIT_TEST bool "KUnit tests for the Apple SoC sleep match data" if !KUNIT_ALL_TESTS depends on APPLE_SOC_SLEEP && KUNIT=y @@ -128,6 +178,17 @@ config APPLE_SOC_SLEEP_KUNIT_TEST If unsure, say N. +config APPLE_T6050_AOP_KUNIT_TEST + bool "KUnit tests for the T6050 AOP2 driver" if !KUNIT_ALL_TESTS + depends on APPLE_SOC_SLEEP && KUNIT=y + default KUNIT_ALL_TESTS + help + Checks that each AOP2 endpoint gets one ring buffer for as long as + its firmware runs, and that a ring is read only inside it. The tests + touch no hardware. + + If unsure, say N. + config APPLE_RTKIT tristate "Apple RTKit co-processor IPC protocol" depends on APPLE_MAILBOX @@ -140,6 +201,21 @@ config APPLE_RTKIT Say 'y' here if you have an Apple SoC. +config APPLE_RTKIT_KUNIT_TEST + bool "KUnit tests for the Apple RTKit IPC library" if !KUNIT_ALL_TESTS + depends on APPLE_RTKIT=y && KUNIT=y + default KUNIT_ALL_TESTS + help + Feed the RTKit receive handlers the messages a co-processor sends + (HELLO version negotiation, the endpoint map, power state ACKs, + buffer requests, syslog, ioreport, kdebug, CoreAnalytics and crash + reports) and check the replies, with the mailbox send replaced by a + static stub. Check that the crashlog parser follows containers to + the right log and never reads past a truncated or malformed + crashlog. The tests touch no hardware. + + If unsure, say N. + config APPLE_RTKIT_HELPER tristate "Apple Generic RTKit helper co-processor" depends on APPLE_RTKIT @@ -153,6 +229,22 @@ config APPLE_RTKIT_HELPER Say 'y' here if you have an Apple SoC. +config APPLE_RTKIT_HELPER_KUNIT_TEST + bool "KUnit tests for the Apple RTKit helper co-processor" if !KUNIT_ALL_TESTS + depends on APPLE_RTKIT_HELPER=y && KUNIT=y && SUSPEND + default KUNIT_ALL_TESTS + help + Hand the helper's shared memory callbacks the buffer requests a + co-processor sends (no address, addresses in and around the SRAM + region, zero, unaligned and wrapping sizes, repeats), parse the + buffer inventory of a handed over session from a device node built + by the test, and walk the AP power notices of a sleep: prepare, + suspend, resume and complete, unanswered and late answered idle + notices. The RTKit AP power call is a static stub and the ASC and + SRAM registers are kernel memory. The tests touch no hardware. + + If unsure, say N. + config APPLE_SART tristate "Apple SART DMA address filter" depends on ARCH_APPLE || COMPILE_TEST @@ -163,10 +255,39 @@ config APPLE_SART Say 'y' here if you have an Apple SoC. +config APPLE_SART_KUNIT_TEST + bool "KUnit tests for the Apple SART DMA address filter" if !KUNIT_ALL_TESTS + depends on APPLE_SART=y && KUNIT=y + depends on ARM64 && OF + default KUNIT_ALL_TESTS + help + Add and remove allowed regions on a SART whose registers are a + buffer of kernel memory, and check the register encoding of each + SART generation, the handling of a full table, of regions that are + not whole pages and of the bootloader's entries, and what a + firmware-driven sleep saves, restores and refuses. The tests touch + no hardware. + + If unsure, say N. + config APPLE_TUNABLE tristate depends on ARCH_APPLE || COMPILE_TEST +config APPLE_TUNABLE_KUNIT_TEST + tristate "KUnit tests for Apple Silicon hardware tunables" if !KUNIT_ALL_TESTS + depends on KUNIT && ARM64 && OF + depends on ARCH_APPLE || COMPILE_TEST + select APPLE_TUNABLE + default KUNIT_ALL_TESTS + help + Parse tunable properties from a device node built by the test and + apply them to a buffer of kernel memory: the triplet decoding, the + length, alignment and bounds checks, and the mask and value + arithmetic. The tests touch no hardware. + + If unsure, say N. + config RUST_APPLE_MAILBOX bool depends on PM @@ -197,6 +318,12 @@ config APPLE_AOP config APPLE_SEP_FV_INTERFACE bool +config APPLE_SEP_HDCP_INTERFACE + bool + help + The kernel interface through which the display driver runs HDCP 2.2 + authentication on the SEP. Selected by the SEP driver. + config APPLE_SEP tristate "Apple SEP (Secure Enclave Processor)" default m if ARCH_APPLE @@ -217,6 +344,7 @@ config APPLE_SEP select CRYPTO_GCM select CRYPTO_ECDH select APPLE_SEP_FV_INTERFACE + select APPLE_SEP_HDCP_INTERFACE select RUST_FW_LOADER_ABSTRACTIONS help Driver for the Apple SEP (Secure Enclave Processor) on Apple silicon. @@ -313,10 +441,23 @@ config APPLE_REGVIEW This is a development aid. If unsure, say 'n'. +config APPLE_REGVIEW_KUNIT_TEST + tristate "KUnit tests for the Apple SoC read-only register views" if !KUNIT_ALL_TESTS + depends on APPLE_REGVIEW && KUNIT + default KUNIT_ALL_TESTS + help + Check every built-in register list against the apertures it + needs, the bounds check for short, misnumbered, empty and + wrapping ranges, and the exact text of the views, on register + windows that the test backs with kernel memory. The tests touch + no hardware. + + If unsure, say N. + config APPLE_CLPC tristate "Apple host performance controller floors" depends on ARCH_APPLE || COMPILE_TEST - depends on APPLE_PMC && CPU_FREQ + depends on (APPLE_PMC || !APPLE_PMC) && CPU_FREQ depends on MFD_MACSMC || !MFD_MACSMC select ACPI_PLATFORM_PROFILE if ACPI default ARCH_APPLE @@ -324,9 +465,9 @@ config APPLE_CLPC Raises the DRAM controller and SoC fabric performance floors of the host's PMC voter agent while CPU clusters are busy, and releases them at idle. On SoCs with power modes it also offers them as - platform profiles. + platform profiles (with or without a PMC parent). - Say 'y' or 'm' here if you have an Apple SoC with a PMC. + Say 'y' or 'm' here if you have an Apple SoC. config APPLE_DISPLAY_GATE bool "Apple internal display enable gate" @@ -376,6 +517,15 @@ config APPLE_DISPLAY_GATE Say 'y' if you want the native display on M3 Pro, M3 Max, M3 and M4 Pro Macs. +config APPLE_T8122_GPU_PMP_LINK + bool + depends on APPLE_PMP_REPORT + default n + help + Let T8122 (M3 MacBook Air) GPU power commands wait for the display + request the PMP report acknowledges on the 14.8.3 firmware, as the + M3 runtime of DRM_ASAHI_M3_T8122 requires. + config APPLE_T6030_GPU_PMP_LINK bool depends on APPLE_DISPLAY_GATE diff --git a/drivers/soc/apple/Makefile b/drivers/soc/apple/Makefile index 233df860395b8c..216234e3aba5da 100644 --- a/drivers/soc/apple/Makefile +++ b/drivers/soc/apple/Makefile @@ -1,9 +1,12 @@ # SPDX-License-Identifier: GPL-2.0-only +obj-$(CONFIG_APPLE_MCC_BOOT_DMA) += mcc-boot-dma.o + obj-$(CONFIG_APPLE_J613_DISPLAY_SYNC) += j613-display.o obj-$(CONFIG_APPLE_DBGVIEW) += apple-dbgview.o apple-dbgview-y = dbgview.o +obj-$(CONFIG_APPLE_DBGVIEW_KUNIT_TEST) += dbgview-test.o obj-$(CONFIG_APPLE_DOCKCHANNEL) += apple-dockchannel.o apple-dockchannel-y = dockchannel.o @@ -17,7 +20,8 @@ obj-$(CONFIG_APPLE_CLUSTER_PWRGATE) += apple-cluster-pwrgate.o obj-$(CONFIG_APPLE_SOC_SLEEP) += apple-sleep.o obj-$(CONFIG_APPLE_SOC_SLEEP) += t6050-aop.o -apple-sleep-y = sleep.o +apple-sleep-y = sleep.o sleep-perf-step.o +obj-$(CONFIG_APPLE_SOC_SLEEP) += t6041-sleep.o obj-$(CONFIG_APPLE_RTKIT) += apple-rtkit.o apple-rtkit-y = rtkit.o rtkit-crashlog.o @@ -47,10 +51,12 @@ DTC_FLAGS_t6041-gate-test := -Wno-unit_address_vs_reg -Wno-avoid_unnecessary_add obj-$(CONFIG_APPLE_TUNABLE) += apple-tunable.o apple-tunable-y = tunable.o +obj-$(CONFIG_APPLE_TUNABLE_KUNIT_TEST) += tunable-test.o obj-$(CONFIG_APPLE_AOP) += aop.o obj-$(CONFIG_APPLE_SEP_FV_INTERFACE) += fv_shim.o +obj-$(CONFIG_APPLE_SEP_HDCP_INTERFACE) += hdcp_shim.o obj-$(CONFIG_APPLE_SEP) += apple-sep.o apple-sep-y := sep.o hwrng_shim.o store_shim.o bio_shim.o sha_shim.o \ @@ -69,5 +75,6 @@ obj-$(CONFIG_APPLE_CLPC) += clpc.o obj-$(CONFIG_APPLE_REGVIEW) += apple-regview.o apple-regview-y := regview.o +obj-$(CONFIG_APPLE_REGVIEW_KUNIT_TEST) += regview-test.o obj-$(CONFIG_APPLE_AURORA_BOOT_SECURITY) += aurora-boot-security.o diff --git a/drivers/soc/apple/aop.kunitconfig b/drivers/soc/apple/aop.kunitconfig new file mode 100644 index 00000000000000..ce8c3c6151b97a --- /dev/null +++ b/drivers/soc/apple/aop.kunitconfig @@ -0,0 +1,10 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_RUST=y +CONFIG_ARM64_16K_PAGES=y +CONFIG_IOMMU_SUPPORT=y +CONFIG_PM=y +CONFIG_APPLE_RTKIT=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_AOP=y diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 38cddac3a30e99..85123ea95d9aff 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -57,7 +57,10 @@ use kernel::{ self, ASC_CPU_CONTROL, // }, - str::CString, + str::{ + BStr, + CString, // + }, sync::{ aref::ARef, atomic::{ @@ -216,6 +219,7 @@ const ALS_SENSOR_BLOB_LEN: usize = 193; const ALS_SENSOR_MESSAGE_LEN: usize = 216; mod aop_ring; +mod aop_services; /// Index into the AFK endpoint tables for RTKit endpoint `ep`, if it is one /// of the endpoints this driver drives. @@ -1307,10 +1311,11 @@ struct AopData { epic_v4: bool, /// Runs the service registrations one at a time; drained on removal. registration_queue: OwnedQueue, - /// Serializes queueing a registration with the start of removal, so that - /// nothing is queued once the queue drains. Never held across a drain. + /// The services that have a device, registered or queued. Taken to queue + /// a registration and by the start of removal, so that nothing is queued + /// once the queue drains. Never held across a drain. #[pin] - registration_gate: Mutex<()>, + registration_gate: Mutex, /// Set once by the first teardown; later teardowns return at once. removing: Atomic, /// Set when the transport starts closing; no call is started after it. @@ -1351,6 +1356,8 @@ struct AopData { /// endpoint order. sleep_endpoints: KVec, wake_endpoints: KVec, + /// [`AopHwConfig::s2r_notice`] + s2r_notice: u8, /// No call starts until the system has resumed. sleeping: Atomic, /// RTKit reported the firmware crashed. Nothing restarts it short of a reboot. @@ -1432,11 +1439,13 @@ impl WorkItem for AopServiceRegisterWork { // transport, but nothing on that path takes this lock. let mut subdevices = this.data.subdevices.lock(); if subdevices.reserve(1, GFP_KERNEL).is_err() { + drop(subdevices); dev_err!( this.data.dev, "Failed to allocate the device slot for service {:?}", this.name ); + this.data.registration_gate.lock().release(this.service); return; } // SAFETY: `info` is a valid, fully initialized `platform_device_info` @@ -1445,12 +1454,14 @@ impl WorkItem for AopServiceRegisterWork { drop(fwnode); match pdev.and_then(|pdev| NonNull::new(pdev).ok_or(EINVAL)) { Err(e) => { + drop(subdevices); dev_err!( this.data.dev, "Failed to create device for service {:?}: {:?}", this.name, e ); + this.data.registration_gate.lock().release(this.service); } Ok(pdev) => { if let Err(child) = subdevices.push_within_capacity(ChildDevice(pdev)) { @@ -1500,7 +1511,11 @@ impl AopData { order.extend_from_slice(default, GFP_KERNEL)?; Ok(order) } - fn new(dev: &platform::Device>, cfg: &AopHwConfig) -> Result> { + fn new( + dev: &platform::Device>, + cfg: &AopHwConfig, + setup_port: bool, + ) -> Result> { let sleep_endpoints = Self::endpoint_order( dev.as_ref(), c_str!("apple,sleep-endpoints"), @@ -1512,18 +1527,19 @@ impl AopData { cfg.wake_endpoints, )?; let registration_queue = OwnedQueue::new_ordered(c_str!("apple-aop"))?; - let setup_queue = if cfg.setup_port { + let setup_queue = if setup_port { Some(OwnedQueue::new_ordered(c_str!("apple-aop-setup"))?) } else { None }; + let claims = aop_services::Claims::new()?; Arc::pin_init( pin_init!( AopData { dev: dev.as_ref().into(), epic_v4: cfg.epic_v4, registration_queue, - registration_gate <- new_mutex!(()), + registration_gate <- new_mutex!(claims), removing: Atomic::new(false), transport_closing: Atomic::new(false), cpu_started: Atomic::new(false), @@ -1544,6 +1560,7 @@ impl AopData { ep_shutdown <- pin_init::pin_init_array_from_fn(|_| FutureValue::pin_init()), ep_sleep <- pin_init::pin_init_array_from_fn(|_| FutureValue::pin_init()), sleep_endpoints, + s2r_notice: cfg.s2r_notice, wake_endpoints, sleeping: Atomic::new(false), crashed: Atomic::new(false), @@ -1591,9 +1608,14 @@ impl AopData { let mut init = ep_guard.start(rtk.as_mut()); if init == Err(ETIMEDOUT) { // The mailbox stayed full for the whole send timeout, - // so the request was never written. The firmware can - // still be busy finishing its own boot: send it once - // more, which checks the mailbox again first. + // so the request was never written and a resend is + // safe. The send already waits on the mailbox's + // send-empty interrupt, and the firmware sends no + // other event when it reads its inbound FIFO again. + // Seen on a J616s warm boot with a slow firmware + // start (#547); why the FIFO stays full after the + // power handshake is open (#2344). Resend once, + // logged, then fail the endpoint. dev_warn!( self.dev, "Endpoint {:#04x}: AFK init not sent (mailbox full); retrying", @@ -1640,29 +1662,41 @@ impl AopData { channel, endpoint: ep.index, }; - let dev_name = match name { - b"aop-audio" => c_str!("audio"), - b"las" => c_str!("las"), - b"als" => c_str!("als"), - b"accel" => c_str!("accel"), - b"gyro" => c_str!("gyro"), - b"devmotion6" => c_str!("devmotion6"), - b"als-temp" => c_str!("als-temp"), - _ => { - return Ok(()); - } - }; // The child's probe calls back into the transport, so it runs from a // work item with the endpoint lock dropped. The gate orders queueing // it against removal, which drains the queue after setting the flag. - let gate = self.registration_gate.lock(); + let mut claims = self.registration_gate.lock(); if self.removing.load(Acquire) { return Ok(()); } - let work = AopServiceRegisterWork::new(dev_name, self.clone(), svc)?; - self.registration_queue.enqueue(work); - drop(gate); - Ok(()) + let dev_name = match claims.claim(svc, name) { + Ok(Some(dev_name)) => dev_name, + Ok(None) => return Ok(()), + Err(e) => { + // Counted and logged as the endpoint's other dropped + // messages are, with what the firmware announced. + ep.drop_message( + &self.dev, + fmt!( + "service \"{}\" on channel {}: {:?} (its name or channel has a device)", + BStr::from_bytes(name), + channel, + e + ), + ); + return Ok(()); + } + }; + match AopServiceRegisterWork::new(dev_name, self.clone(), svc) { + Ok(work) => { + self.registration_queue.enqueue(work); + Ok(()) + } + Err(e) => { + claims.release(svc); + Err(e) + } + } } /// Hands a report to its listener; `Ok(false)` when there is none. @@ -1848,7 +1882,11 @@ impl AopData { } let mut result = Ok(()); - for endpoint in AfkOrder::new(&self.sleep_endpoints) { + let notice = self.s2r_notice; + // An empty order is every endpoint: without the stops, the loop doesn't run. + let stops = AfkOrder::new(&self.sleep_endpoints) + .take_while(|_| notice & AOP_S2R_ENDPOINTS != 0); + for endpoint in stops { let Some(index) = afk_endpoint_index(endpoint) else { continue; }; @@ -1864,7 +1902,7 @@ impl AopData { self.sleep_stopped .store(self.sleep_stopped.load(Relaxed) | (1 << index), Relaxed); } - if result.is_ok() { + if result.is_ok() && notice & AOP_S2R_AP_IDLE != 0 { // Set first: a notice without an answer may still have been taken. self.ap_idle.store(true, Relaxed); result = self.ap_power(false).inspect_err(|e| { @@ -3028,7 +3066,9 @@ struct AopHwConfig { required_endpoints: &'static [u8], /// The firmware runs segments from DRAM, which the bootloader reserves /// and lists in `memory-region`; check their IOMMU mappings before - /// starting it (T6040). + /// starting it (T6040). Other SoCs check them when the bootloader lists + /// them (`AopData::has_fw_regions`), as it does for the macOS 27.2 + /// firmware on T8112. fw_regions: bool, bootargs_word_access: bool, /// Halt the co-processor again when its start fails (T6040). @@ -3038,8 +3078,17 @@ struct AopHwConfig { /// left in DRAM are then neither reserved nor mapped, so it runs as its /// fallback compatible's block did (T8122: `apple,t6020-aop`). without_fw_regions: Option<&'static AopHwConfig>, + /// What it hears for a firmware-driven sleep: bit 0 its endpoints stop + /// ([`AOP_S2R_ENDPOINTS`]), bit 1 the AP's idle notice + /// ([`AOP_S2R_AP_IDLE`]). + s2r_notice: u8, } +/// [`AopHwConfig::s2r_notice`]: the endpoints stop and start around a sleep. +const AOP_S2R_ENDPOINTS: u8 = 1 << 0; +/// [`AopHwConfig::s2r_notice`]: the AP's idle and on notices around a sleep. +const AOP_S2R_AP_IDLE: u8 = 1 << 1; + impl AopHwConfig { /// The configuration to start the block with, given whether the /// bootloader reserved its firmware regions. @@ -3051,7 +3100,8 @@ impl AopHwConfig { } } -const HW_CFG_T8103: AopHwConfig = AopHwConfig { +/// T8103 (M1) with the 13.5 firmware: no firmware regions in DRAM. +const HW_CFG_T8103_DIRECT: AopHwConfig = AopHwConfig { ec0p: 0x020000, ncal: Some(0), aopt: 1, @@ -3069,6 +3119,17 @@ const HW_CFG_T8103: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + // Measured across real sleeps with its endpoints stopped only. + s2r_notice: AOP_S2R_ENDPOINTS, +}; +/// T8103 (M1): from firmware 27 on, the AOP runs its external code and data +/// from DRAM, which the bootloader reserves in `memory-region`, and stops +/// before its RTKit HELLO unless they are mapped and ED0p is written. A boot +/// with no regions reserved (firmware 13.5) starts it as before. +const HW_CFG_T8103: AopHwConfig = AopHwConfig { + fw_regions: true, + without_fw_regions: Some(&HW_CFG_T8103_DIRECT), + ..HW_CFG_T8103_DIRECT }; /// `nCal` keeps the firmware's own value, as on T6040: the J413 image carries 1, /// and with 0 the firmware never announces its accelerometer and gyroscope. @@ -3090,6 +3151,7 @@ const HW_CFG_T8112: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; /// `nCal` keeps the firmware's own value, as on T8112. const HW_CFG_T6000: AopHwConfig = AopHwConfig { @@ -3110,6 +3172,7 @@ const HW_CFG_T6000: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; const HW_CFG_T6020: AopHwConfig = AopHwConfig { ec0p: 0x0100_00000000, @@ -3129,6 +3192,7 @@ const HW_CFG_T6020: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; /// T6040 (J616s): the firmware's external code and log live in DRAM, mapped /// through the reserved regions the bootloader describes; the RTKit firmware @@ -3153,19 +3217,40 @@ const HW_CFG_T6040: AopHwConfig = AopHwConfig { bootargs_word_access: true, halt_on_failed_start: true, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, +}; +/// T6041 (J616C): as T6040, with the AFK sleep and wake order macOS 26.6.2 uses on the J616C +/// (trace, 8 Nov 2026: sleep to these endpoints in this order, then the AP idle notice). +const HW_CFG_T6041: AopHwConfig = AopHwConfig { + sleep_endpoints: &[0x2b, 0x2a, 0x24, 0x20, 0x27, 0x26, 0x28, 0x25, 0x21, 0x29, 0x23, 0x22], + wake_endpoints: &[0x22, 0x23, 0x29, 0x21, 0x25, 0x28, 0x26, 0x27, 0x20, 0x24, 0x2a, 0x2b], + ..HW_CFG_T6040 }; /// T8132 (J713): as T6040. The bootloader hands the AOP over the same way, with /// the DART's DAPF programmed and its windows reserved alongside the firmware /// segments. const HW_CFG_T8132: AopHwConfig = HW_CFG_T6040; -/// T8122 (M3): as T6040. iBoot leaves the AOP halted with its external code, -/// data and log in DRAM, which the bootloader reserves in `memory-region`; -/// the 27.2 firmware reads its `__EDATA` base from `ED0p`. A bootloader that -/// reserves none leaves it to start as `apple,t6020-aop`, as before. -const HW_CFG_T8122: AopHwConfig = AopHwConfig { +/// M3-family AOP without SoC-specific sleep endpoints (T6030 and T6031): as +/// T6040. iBoot leaves the AOP halted with its external code, data and log in +/// DRAM, which the bootloader reserves in `memory-region`; the 27.2 firmware +/// reads its `__EDATA` base from `ED0p`. A bootloader that reserves none leaves +/// it to start as `apple,t6020-aop`, as before. +const HW_CFG_T6030: AopHwConfig = AopHwConfig { without_fw_regions: Some(&HW_CFG_T6020), ..HW_CFG_T6040 }; +/// T8122 fallback when the bootloader supplies no firmware `memory-region`: +/// keeps the T6020 boot path while still stopping the T8122 sleep endpoints. +const HW_CFG_T8122_NO_FW_REGIONS: AopHwConfig = AopHwConfig { + sleep_endpoints: &[0x2b, 0x2a, 0x25, 0x27, 0x20, 0x23, 0x29, 0x24, 0x21, 0x28, 0x26, 0x22], + ..HW_CFG_T6020 +}; +/// T8122 (M3): as `HW_CFG_T6030`, plus T8122's twelve deep-sleep AFK endpoints. +const HW_CFG_T8122: AopHwConfig = AopHwConfig { + sleep_endpoints: &[0x2b, 0x2a, 0x25, 0x27, 0x20, 0x23, 0x29, 0x24, 0x21, 0x28, 0x26, 0x22], + without_fw_regions: Some(&HW_CFG_T8122_NO_FW_REGIONS), + ..HW_CFG_T6040 +}; /// T8140: the firmware is started with the boot arguments the bootloader /// left, boots through the setup port and speaks EPIC version 4. Of the /// advertised AFK endpoints, the application map is 0x20 misc, 0x21 @@ -3189,6 +3274,7 @@ const HW_CFG_T8140: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; /// T8152: like T8140, but the setup port (mailbox 1 of the AOP bank, and the /// ADT aop-exclave-mailbox) is not reachable from the AP: both bus-error. @@ -3210,6 +3296,7 @@ const HW_CFG_T8152: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; /// T8142 (M5): booted through a setup port as on T8140, at the ADT's @@ -3235,6 +3322,7 @@ const HW_CFG_T8142: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; /// T6050 (M5 Pro and Max): booted as T8142, through the setup port at /// AOP ASC + 0x4007c000. Its EPMAP also names system endpoint 4, which never @@ -3296,9 +3384,11 @@ kernel::of_device_table!( (of::DeviceId::new(c_str!("apple,t8112-aop")), &HW_CFG_T8112), (of::DeviceId::new(c_str!("apple,t6000-aop")), &HW_CFG_T6000), (of::DeviceId::new(c_str!("apple,t8122-aop")), &HW_CFG_T8122), + (of::DeviceId::new(c_str!("apple,t6030-aop")), &HW_CFG_T6030), + (of::DeviceId::new(c_str!("apple,t6031-aop")), &HW_CFG_T6030), (of::DeviceId::new(c_str!("apple,t6020-aop")), &HW_CFG_T6020), (of::DeviceId::new(c_str!("apple,t8140-aop")), &HW_CFG_T8140), - (of::DeviceId::new(c_str!("apple,t6041-aop")), &HW_CFG_T6040), + (of::DeviceId::new(c_str!("apple,t6041-aop")), &HW_CFG_T6041), (of::DeviceId::new(c_str!("apple,t8132-aop")), &HW_CFG_T8132), (of::DeviceId::new(c_str!("apple,t6050-aop")), &HW_CFG_T6050), (of::DeviceId::new(c_str!("apple,t8142-aop")), &HW_CFG_T8142), @@ -3343,7 +3433,7 @@ impl platform::Driver for AopDriver { let asc_mmio = asc_req.iomap_sized::()?; let asc_mmio = asc_mmio.as_view().relaxed(); let aop_mmio = aop_mmio.as_view(); - let ed0p = if cfg.fw_regions { + let ed0p = if cfg.fw_regions || AopData::has_fw_regions(pdev.as_ref()) { // Before anything is written to the AOP: no mapping, no start. let allow_ed0p = cfg.patch_bootargs && AopData::bootargs_has_ed0p(&aop_mmio, cfg.bootargs_word_access)?; @@ -3351,7 +3441,14 @@ impl platform::Driver for AopDriver { } else { None }; - let data = AopData::new(pdev, cfg)?; + // The setup-port boot opens the mailbox named "setup"; a device tree + // that gives the AOP no such mailbox gets the boot without it. + let setup_port = cfg.setup_port + && pdev.as_ref().fwnode().is_some_and(|node| { + node.property_match_string(c_str!("mbox-names"), c_str!("setup")) + .is_ok() + }); + let data = AopData::new(pdev, cfg, setup_port)?; // Whatever fails below leaves the AOP running and its children // registering; the same teardown as unbind's cleans that up. let probe_guard = ScopeGuard::new_with_data(data.clone(), |data| data.remove()); @@ -3377,12 +3474,12 @@ impl platform::Driver for AopDriver { rtkit::RtKit::::new(pdev.as_ref(), None, 0, data.clone())? }; data.rtkit.lock().as_mut().set(Some(rtkit)); - if cfg.setup_port { + if setup_port { AopData::setup_open(&data, pdev.as_ref())?; } asc_mmio.update(ASC_CPU_CONTROL, |r| r.with_const_cpu_run::<1>()); data.cpu_started.store(true, Release); - let started = if cfg.setup_port { + let started = if setup_port { // The RTKit handshake up to AP power on comes first, then the // setup port's own power state and endpoint buffers, and only // then the AFK endpoints. diff --git a/drivers/soc/apple/aop_services.rs b/drivers/soc/apple/aop_services.rs new file mode 100644 index 00000000000000..46157a1d6a443d --- /dev/null +++ b/drivers/soc/apple/aop_services.rs @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The services that get a child device, and the record of those that have one. +//! +//! The firmware announces each service it offers by name, with the channel +//! the service answers on. A service this driver knows gets one platform +//! device, named for it and described by the AOP's device-tree child of that +//! name. The record allows one device per known name and per service, so its +//! size is bounded by the table below, whatever the firmware announces. + +use kernel::{prelude::*, soc::apple::aop::EPICService}; + +/// The announced names of the services that get a device, and the device's +/// name. Each device name appears once. +const DEVICES: [(&[u8], &CStr); 7] = [ + (b"aop-audio", c"audio"), + (b"las", c"las"), + (b"als", c"als"), + (b"accel", c"accel"), + (b"gyro", c"gyro"), + (b"devmotion6", c"devmotion6"), + (b"als-temp", c"als-temp"), +]; + +/// The services that have a device, registered or queued for registration, +/// each with its entry in [`DEVICES`]. +pub(super) struct Claims(KVec<(EPICService, usize)>); + +impl Claims { + pub(super) fn new() -> Result { + Ok(Self(KVec::with_capacity(DEVICES.len(), GFP_KERNEL)?)) + } + + /// Claims the device for a service announced as `name`. Returns the name + /// of the device to register, or `None` when there is nothing to do: the + /// service has no device, or it was announced before as it is now. A + /// service whose name already has a device on another channel, or whose + /// channel already has one under another name, gets none (`EEXIST`). + pub(super) fn claim( + &mut self, + service: EPICService, + name: &[u8], + ) -> Result> { + let Some(index) = DEVICES.iter().position(|&(known, _)| known == name) else { + return Ok(None); + }; + for &(claimed, claimed_index) in self.0.iter() { + match (claimed == service, claimed_index == index) { + (true, true) => return Ok(None), + (false, false) => {} + _ => return Err(EEXIST), + } + } + // Each entry of the table is claimed at most once, so this stays + // within the capacity reserved for the whole table. + self.0.push_within_capacity((service, index)).map_err(|_| ENOSPC)?; + Ok(Some(DEVICES[index].1)) + } + + /// Gives up the claim of a service whose device could not be registered, + /// so that the next announcement of the service tries again. + pub(super) fn release(&mut self, service: EPICService) { + self.0.retain(|&mut (claimed, _)| claimed != service); + } +} + +#[kunit_tests(apple_aop_services)] +mod tests { + use super::*; + + fn svc(endpoint: u8, channel: u32) -> EPICService { + EPICService { channel, endpoint } + } + + #[test] + fn known_services_get_their_device() -> Result { + let mut claims = Claims::new()?; + assert_eq!(claims.claim(svc(0x21, 1), b"aop-audio")?, Some(c"audio")); + assert_eq!(claims.claim(svc(0x23, 1), b"als")?, Some(c"als")); + assert_eq!(claims.claim(svc(0x23, 2), b"als-temp")?, Some(c"als-temp")); + Ok(()) + } + + #[test] + fn unknown_services_get_nothing() -> Result { + let mut claims = Claims::new()?; + assert_eq!(claims.claim(svc(0x20, 1), b"misc")?, None); + assert_eq!(claims.claim(svc(0x20, 2), b"")?, None); + assert_eq!(claims.claim(svc(0x20, 3), b"als\0")?, None); + // The unknown announcements took no claim on the channel. + assert_eq!(claims.claim(svc(0x20, 1), b"als")?, Some(c"als")); + Ok(()) + } + + #[test] + fn an_unchanged_announcement_adds_no_device() -> Result { + let mut claims = Claims::new()?; + assert_eq!(claims.claim(svc(0x23, 1), b"als")?, Some(c"als")); + for _ in 0..100 { + assert_eq!(claims.claim(svc(0x23, 1), b"als")?, None); + } + Ok(()) + } + + #[test] + fn a_name_or_channel_with_a_device_is_refused() -> Result { + let mut claims = Claims::new()?; + assert_eq!(claims.claim(svc(0x23, 1), b"als")?, Some(c"als")); + // The same name on another channel or endpoint. + assert_eq!(claims.claim(svc(0x23, 2), b"als"), Err(EEXIST)); + assert_eq!(claims.claim(svc(0x24, 1), b"als"), Err(EEXIST)); + // The same channel under another name. + assert_eq!(claims.claim(svc(0x23, 1), b"las"), Err(EEXIST)); + // Other services are unaffected. + assert_eq!(claims.claim(svc(0x23, 2), b"las")?, Some(c"las")); + Ok(()) + } + + #[test] + fn devices_are_bounded_by_the_table() -> Result { + let mut claims = Claims::new()?; + let mut devices = 0; + for channel in 0..64 { + for &(name, _) in DEVICES.iter() { + if let Ok(Some(_)) = claims.claim(svc(0x20 + (channel % 8) as u8, channel), name) { + devices += 1; + } + } + } + assert_eq!(devices, DEVICES.len()); + assert_eq!(claims.0.len(), DEVICES.len()); + Ok(()) + } + + #[test] + fn a_released_service_can_be_claimed_again() -> Result { + let mut claims = Claims::new()?; + assert_eq!(claims.claim(svc(0x21, 1), b"aop-audio")?, Some(c"audio")); + assert_eq!(claims.claim(svc(0x23, 1), b"als")?, Some(c"als")); + claims.release(svc(0x21, 1)); + assert_eq!(claims.claim(svc(0x21, 1), b"aop-audio")?, Some(c"audio")); + assert_eq!(claims.claim(svc(0x23, 1), b"als")?, None); + Ok(()) + } +} diff --git a/drivers/soc/apple/apple-pmgr-fabric-test.c b/drivers/soc/apple/apple-pmgr-fabric-test.c new file mode 100644 index 00000000000000..85131e5923a34e --- /dev/null +++ b/drivers/soc/apple/apple-pmgr-fabric-test.c @@ -0,0 +1,760 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the PMGR misc fabric controls: suspend/resume p-states + * with and without PMP, the confirmed fabric raise, holds, the idle fabric + * governor and its parameter, and the device tree lookup of its bandwidth + * voters. The fabric and DCS controls are words in kernel memory and the + * voters a regmap on a buffer; nothing touches MMIO. + */ + +#include +#include +#include + +#define PF_DEFAULT 0xa5000077 /* desired 7, actual 7, unknown upper bits */ +#define PF_VOTE_IDLE 0x0f /* target on, hardware gated: idle */ +#define PF_VOTE_BUSY 0xff + +struct pf_test { + struct apple_pmgr_misc misc; /* first: test->priv is both */ + u32 *fabric, *dcs; + u32 *votes; + bool cpus_min; + bool published; + unsigned int saved_idle_pstate; +}; + +static const struct regmap_config pf_vote_regmap_config = { + .reg_bits = 32, + .reg_stride = 4, + .val_bits = 32, + .max_register = 0x1c, +}; + +static bool pf_fake_cpus_at_min(void) +{ + struct pf_test *f = kunit_get_current_test()->priv; + + return f->cpus_min; +} + +static int pf_test_init(struct kunit *test) +{ + struct apple_pmgr_misc *misc; + struct regmap *map; + struct pf_test *f; + unsigned int i; + + /* + * The cases drive the driver's single instance and its parameter. + * Where the driver runs on real hardware they would take both over. + */ + if (smp_load_acquire(&apple_pmgr_misc_inst)) + kunit_skip(test, "apple-pmgr-misc is bound on this system"); + + f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); + if (!f) + return -ENOMEM; + misc = &f->misc; + f->saved_idle_pstate = READ_ONCE(idle_fabric_pstate); + WRITE_ONCE(idle_fabric_pstate, 0); + f->fabric = kunit_kzalloc(test, sizeof(u32), GFP_KERNEL); + f->dcs = kunit_kzalloc(test, sizeof(u32), GFP_KERNEL); + f->votes = kunit_kzalloc(test, 8 * sizeof(u32), GFP_KERNEL); + if (!f->fabric || !f->dcs || !f->votes) + return -ENOMEM; + misc->dev = kunit_device_register(test, "pmgr-fabric-test"); + if (IS_ERR(misc->dev)) + return PTR_ERR(misc->dev); + map = devm_regmap_init_mmio(misc->dev, (void __iomem *)f->votes, + &pf_vote_regmap_config); + if (IS_ERR(map)) + return PTR_ERR(map); + + /* t602x layout: plain read-modify-write of both desired fields. */ + writel(PF_DEFAULT, f->fabric); + writel(0xa5000099, f->dcs); + misc->devices[DEV_FABRIC].base = (void __iomem *)f->fabric; + misc->devices[DEV_FABRIC].active_state = 7; + misc->devices[DEV_FABRIC].suspend_state = SYS_DEV_PSTATE_SUSPEND; + misc->devices[DEV_DCS].base = (void __iomem *)f->dcs; + misc->devices[DEV_DCS].active_state = 9; + misc->devices[DEV_DCS].suspend_state = SYS_DEV_PSTATE_SUSPEND; + mutex_init(&misc->lock); + misc->fabric_now = 7; + INIT_DEFERRABLE_WORK(&misc->idle_work, apple_pmgr_idle_work); + INIT_DELAYED_WORK(&misc->idle_work_prompt, apple_pmgr_idle_work_prompt); + for (i = 0; i < ARRAY_SIZE(misc->votes); i++) { + f->votes[i] = PF_VOTE_IDLE; + misc->votes[i].regmap = map; + misc->votes[i].reg = i * sizeof(u32); + } + misc->voters_ok = true; + dev_set_drvdata(misc->dev, misc); + f->cpus_min = true; + test->priv = f; + kunit_activate_static_stub(test, apple_pmgr_cpus_at_min, pf_fake_cpus_at_min); + return 0; +} + +static void pf_test_exit(struct kunit *test) +{ + struct pf_test *f = test->priv; + + if (!f) + return; + cancel_delayed_work_sync(&f->misc.idle_work); + cancel_delayed_work_sync(&f->misc.idle_work_prompt); + WRITE_ONCE(idle_fabric_pstate, f->saved_idle_pstate); + if (f->published) { + /* Pairs with the acquire in the driver's readers. */ + smp_store_release(&apple_pmgr_misc_inst, NULL); + } +} + +static void pf_publish(struct pf_test *f) +{ + f->published = true; + /* Pairs with the acquire in the driver's readers, as probe's release. */ + smp_store_release(&apple_pmgr_misc_inst, &f->misc); +} + +/* Fabric reported low by both fields, as after the governor lowered it. */ +static void pf_set_low(struct pf_test *f, u32 reg) +{ + writel(reg, f->fabric); + f->misc.fabric_now = 1; +} + +static void pf_suspend_resume_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_suspend_noirq(misc->dev), 0); + /* Only the desired field changes; readback and unknown bits stay. */ + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000071U); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000091U); + misc->fabric_now = 1; + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_resume_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000099U); + KUNIT_EXPECT_EQ(test, misc->fabric_now, 7U); +} + +static void pf_suspend_absent_control_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* A control the device tree does not describe is skipped. */ + misc->devices[DEV_DCS].base = NULL; + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_suspend_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000071U); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000099U); + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_resume_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); +} + +static void pf_pmp_suspend_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + misc->pmp_owned = true; + misc->pmp_sleep = true; + writel(0xa5000035, f->fabric); /* PMP chose fabric p-state 5 */ + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_suspend_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, misc->pmp_fabric, 5U); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000031U); + /* DCS is PMP's: not lowered. */ + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000099U); + + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_resume_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000035U); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000099U); + KUNIT_EXPECT_EQ(test, misc->fabric_now, 7U); +} + +static void pf_pmp_resume_new_choice_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + misc->pmp_owned = true; + misc->pmp_sleep = true; + misc->pmp_fabric = 5; + /* PMP moved the fabric since suspend: its choice is kept. */ + writel(0xa5000033, f->fabric); + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_resume_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000033U); + + /* Without a fabric control only the bookkeeping happens. */ + misc->devices[DEV_FABRIC].base = NULL; + KUNIT_EXPECT_EQ(test, apple_pmgr_misc_suspend_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, apple_pmgr_misc_resume_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000099U); +} + +static void pf_raise_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* Hardware already reports 7: the confirming poll succeeds at once. */ + pf_set_low(f, 0xa5000071); + scoped_guard(mutex, &misc->lock) + KUNIT_EXPECT_EQ(test, apple_pmgr_raise_fabric(misc), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + KUNIT_EXPECT_EQ(test, misc->fabric_now, 7U); +} + +static void pf_raise_timeout_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* Actual never follows: report it and leave the state unconfirmed. */ + pf_set_low(f, 0xa5000011); + scoped_guard(mutex, &misc->lock) + KUNIT_EXPECT_EQ(test, apple_pmgr_raise_fabric(misc), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000017U); + KUNIT_EXPECT_EQ(test, misc->fabric_now, U32_MAX); + + /* The next caller tries again rather than trusting fabric_now. */ + writel(0xa5000077, f->fabric); + scoped_guard(mutex, &misc->lock) + KUNIT_EXPECT_EQ(test, apple_pmgr_raise_fabric(misc), 0); + KUNIT_EXPECT_EQ(test, misc->fabric_now, 7U); +} + +static void pf_raise_skip_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* Already at the boot p-state: no write, no poll. */ + writel(0xa5000013, f->fabric); + scoped_guard(mutex, &misc->lock) + KUNIT_EXPECT_EQ(test, apple_pmgr_raise_fabric(misc), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000013U); + + /* PMP owns the fabric: delegate, never write. */ + pf_set_low(f, 0xa5000011); + misc->pmp_owned = true; + scoped_guard(mutex, &misc->lock) + KUNIT_EXPECT_EQ(test, apple_pmgr_raise_fabric(misc), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000011U); + KUNIT_EXPECT_EQ(test, misc->fabric_now, 1U); +} + +static void pf_hold_release_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* No instance yet: holds succeed and change nothing. */ + pf_set_low(f, 0xa5000071); + KUNIT_EXPECT_EQ(test, apple_pmgr_fabric_hold(), 0); + apple_pmgr_fabric_release(); + KUNIT_EXPECT_EQ(test, misc->holds, 0U); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000071U); + + pf_publish(f); + KUNIT_EXPECT_EQ(test, apple_pmgr_fabric_hold(), 0); + KUNIT_EXPECT_EQ(test, misc->holds, 1U); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + KUNIT_EXPECT_EQ(test, apple_pmgr_fabric_hold(), 0); + KUNIT_EXPECT_EQ(test, misc->holds, 2U); + apple_pmgr_fabric_release(); + apple_pmgr_fabric_release(); + KUNIT_EXPECT_EQ(test, misc->holds, 0U); + + /* An unconfirmed raise is reported, but the hold stands. */ + pf_set_low(f, 0xa5000011); + KUNIT_EXPECT_EQ(test, apple_pmgr_fabric_hold(), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, misc->holds, 1U); + apple_pmgr_fabric_release(); + KUNIT_EXPECT_EQ(test, misc->holds, 0U); +} + +static void pf_voters_active_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + unsigned int i; + + /* Target on but gated by hardware is idle: only actual counts. */ + KUNIT_EXPECT_FALSE(test, apple_pmgr_voters_active(misc)); + for (i = 0; i < ARRAY_SIZE(misc->votes); i++) { + f->votes[i] = PF_VOTE_BUSY; + KUNIT_EXPECT_TRUE_MSG(test, apple_pmgr_voters_active(misc), "voter %u", i); + f->votes[i] = 0xf0; + KUNIT_EXPECT_TRUE_MSG(test, apple_pmgr_voters_active(misc), "voter %u", i); + f->votes[i] = 0xe0 | PF_VOTE_IDLE; + KUNIT_EXPECT_FALSE_MSG(test, apple_pmgr_voters_active(misc), "voter %u", i); + f->votes[i] = PF_VOTE_IDLE; + } + /* An unreadable voter counts as busy. */ + misc->votes[2].reg = 0x100; + KUNIT_EXPECT_TRUE(test, apple_pmgr_voters_active(misc)); +} + +static void pf_idle_lowers_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + WRITE_ONCE(idle_fabric_pstate, 1); + apple_pmgr_idle_eval(misc); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000071U); + KUNIT_EXPECT_EQ(test, misc->fabric_now, 1U); + /* While low, the prompt timer watches for new load. */ + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&misc->idle_work_prompt)); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work)); + cancel_delayed_work_sync(&misc->idle_work_prompt); + + /* Already low: no second write. */ + writel(0xa5000011, f->fabric); + apple_pmgr_idle_eval(misc); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000011U); +} + +enum pf_blocker { + PF_HOLD, PF_DCS_BW, PF_VOTER, PF_CPU, PF_PMP, PF_NO_VOTERS, PF_IDLE_HIGH, + PF_BLOCKERS +}; + +static void pf_idle_blockers_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + unsigned int b; + + for (b = 0; b < PF_BLOCKERS; b++) { + WRITE_ONCE(idle_fabric_pstate, 1); + misc->holds = b == PF_HOLD; + misc->dcs_bw_active = b == PF_DCS_BW; + f->votes[1] = b == PF_VOTER ? PF_VOTE_BUSY : PF_VOTE_IDLE; + f->cpus_min = b != PF_CPU; + misc->pmp_owned = b == PF_PMP; + misc->voters_ok = b != PF_NO_VOTERS; + if (b == PF_IDLE_HIGH) + WRITE_ONCE(idle_fabric_pstate, 7); + pf_set_low(f, 0xa5000071); + + apple_pmgr_idle_eval(misc); + if (b == PF_PMP) { + /* PMP decides: neither lowered nor raised by us. */ + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000071U); + } else { + KUNIT_EXPECT_EQ_MSG(test, readl(f->fabric), PF_DEFAULT, "blocker %u", b); + KUNIT_EXPECT_EQ_MSG(test, misc->fabric_now, 7U, "blocker %u", b); + } + KUNIT_EXPECT_TRUE_MSG(test, delayed_work_pending(&misc->idle_work), + "blocker %u", b); + KUNIT_EXPECT_FALSE_MSG(test, delayed_work_pending(&misc->idle_work_prompt), + "blocker %u", b); + cancel_delayed_work_sync(&misc->idle_work); + } +} + +static void pf_idle_off_sleeping_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* Governor off: raise to the boot state, no timer. */ + pf_set_low(f, 0xa5000071); + apple_pmgr_idle_eval(misc); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work)); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work_prompt)); + + /* Sleeping: the evaluation stops without touching the fabric. */ + WRITE_ONCE(idle_fabric_pstate, 1); + misc->sleeping = true; + apple_pmgr_idle_eval(misc); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + pf_set_low(f, 0xa5000071); + apple_pmgr_idle_eval(misc); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000071U); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work)); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work_prompt)); +} + +static void pf_param_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("16", NULL), -EINVAL); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("one", NULL), -EINVAL); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate, 0U); + /* Before probe the value is only stored. */ + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("15", NULL), 0); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate, 15U); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("0", NULL), 0); + + pf_publish(f); + /* + * Setting it runs the governor at once. The worker runs outside the + * test, without the CPU stub, so only that it ran is checked. + */ + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("1", NULL), 0); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate, 1U); + KUNIT_EXPECT_TRUE(test, flush_delayed_work(&misc->idle_work)); + cancel_delayed_work_sync(&misc->idle_work); + cancel_delayed_work_sync(&misc->idle_work_prompt); + + /* Clearing it stops the governor and raises the fabric. */ + pf_set_low(f, 0xa5000071); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("0", NULL), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work)); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work_prompt)); + + /* With PMP owning the fabric the governor cannot be enabled. */ + misc->pmp_owned = true; + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("1", NULL), -EBUSY); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate, 0U); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("0", NULL), 0); +} + +static void pf_prepare_complete_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + WRITE_ONCE(idle_fabric_pstate, 1); + pf_set_low(f, 0xa5000071); + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_prepare(misc->dev), 0); + /* Raised before any device suspends, governor parked. */ + KUNIT_EXPECT_TRUE(test, misc->sleeping); + KUNIT_EXPECT_FALSE(test, misc->pmp_sleep); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work)); + + apple_pmgr_misc_complete(misc->dev); + KUNIT_EXPECT_FALSE(test, misc->sleeping); + /* The governor restarts at once. */ + KUNIT_EXPECT_TRUE(test, flush_delayed_work(&misc->idle_work)); + cancel_delayed_work_sync(&misc->idle_work); + cancel_delayed_work_sync(&misc->idle_work_prompt); + + /* No fabric control: nothing to gate. */ + misc->devices[DEV_FABRIC].base = NULL; + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_prepare(misc->dev), 0); + KUNIT_EXPECT_FALSE(test, misc->sleeping); + apple_pmgr_misc_complete(misc->dev); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work)); +} + +static void pf_match_data_test(struct kunit *test) +{ + const struct apple_pmgr_misc_hw *t600x = NULL, *t602x = NULL; + const struct of_device_id *id; + + for (id = apple_pmgr_misc_of_match; id->compatible[0]; id++) { + if (!strcmp(id->compatible, "apple,t6000-pmgr-misc")) + t600x = id->data; + else if (!strcmp(id->compatible, "apple,t6020-pmgr-misc")) + t602x = id->data; + } + KUNIT_ASSERT_NOT_NULL(test, t600x); + KUNIT_ASSERT_NOT_NULL(test, t602x); + KUNIT_EXPECT_EQ(test, t600x->dev_min_ps[DEV_FABRIC], 1U); + KUNIT_EXPECT_EQ(test, t600x->dev_min_ps[DEV_DCS], 7U); + KUNIT_EXPECT_EQ(test, t600x->dcs_valid_states, (u32)DCS_VALID_STATES_T600X); + KUNIT_EXPECT_EQ(test, t602x->dev_min_ps[DEV_FABRIC], 1U); + KUNIT_EXPECT_EQ(test, t602x->dev_min_ps[DEV_DCS], 1U); + /* No DCS state list: suspend uses the plain read-modify-write. */ + KUNIT_EXPECT_EQ(test, t602x->dcs_valid_states, 0U); +} + +/* + * Device tree voters. The pmgr node is created once and keeps a syscon + * entry for the whole boot (syscon entries cannot be removed), so it is + * never freed; each case adds and removes its own power-state children. + */ +static struct device_node *pf_dt_pmgr; + +/* + * The driver looks its voters and the PMP up in the whole tree. Nodes of + * the system's own devicetree would join the fixture's, so the devicetree + * cases only run where the fixture's are the only ones. + */ +static bool pf_dt_foreign(const char *compatible) +{ + struct device_node *np, *box = pf_dt_pmgr ? pf_dt_pmgr->parent : NULL; + + for_each_compatible_node(np, NULL, compatible) { + struct device_node *p; + bool ours = false; + + for (p = np->parent; p && box; p = p->parent) + if (p == box) { + ours = true; + break; + } + if (!ours) { + of_node_put(np); + return true; + } + } + return false; +} + +static void pf_dt_require_fixture_only(struct kunit *test) +{ + if (pf_dt_foreign("apple,pmgr-pwrstate") || + pf_dt_foreign("apple,t6000-pmp-v2")) + kunit_skip(test, "the system devicetree describes PMGR or PMP nodes"); +} +static u32 pf_dt_regs[0x50]; + +static const struct regmap_config pf_dt_regmap_config = { + .reg_bits = 32, + .reg_stride = 4, + .val_bits = 32, + .max_register = sizeof(pf_dt_regs) - sizeof(u32), +}; + +struct pf_dt_child { + const char *name; + const char *label; /* NULL: no label property */ + u32 reg; /* 0: no reg property */ + bool disabled; + const char *compatible; /* NULL: apple,pmgr-pwrstate */ +}; + +static void pf_dt_apply(struct kunit *test, struct of_changeset *cs, + const struct pf_dt_child *c, unsigned int n) +{ + unsigned int i; + + of_changeset_init(cs); + for (i = 0; i < n; i++) { + const char *compatible = c[i].compatible ?: "apple,pmgr-pwrstate"; + struct device_node *np = of_changeset_create_node(cs, pf_dt_pmgr, c[i].name); + + KUNIT_ASSERT_NOT_NULL(test, np); + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_string(cs, np, "compatible", + compatible), 0); + if (c[i].label) + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_string(cs, np, "label", + c[i].label), 0); + if (c[i].reg) + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_u32(cs, np, "reg", + c[i].reg), 0); + if (c[i].disabled) + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_string(cs, np, "status", + "disabled"), 0); + } + KUNIT_ASSERT_EQ(test, of_changeset_apply(cs), 0); +} + +static void pf_dt_revert(struct of_changeset *cs) +{ + of_changeset_revert(cs); + of_changeset_destroy(cs); +} + +static bool pf_dt_find(struct kunit *test, struct apple_pmgr_misc *misc, + const struct pf_dt_child *c, unsigned int n) +{ + struct of_changeset cs; + + memset(misc->votes, 0, sizeof(misc->votes)); + misc->voters_ok = false; + pf_dt_apply(test, &cs, c, n); + apple_pmgr_find_voters(misc); + pf_dt_revert(&cs); + return misc->voters_ok; +} + +static void pf_dt_voters_test(struct kunit *test) +{ + static const struct pf_dt_child c[] = { + { "power-controller@100", "gfx", 0x100 }, + { "power-controller@108", "disp0_sys", 0x108 }, + { "power-controller@110", "avd_sys", 0x110 }, + { "power-controller@118", "isp_sys", 0x118 }, + { "clock@120", "isp_sys", 0x120, false, "apple,t6000-clkgen" }, + }; + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + struct regmap *map = syscon_node_to_regmap(pf_dt_pmgr); + + pf_dt_require_fixture_only(test); + + KUNIT_ASSERT_FALSE(test, IS_ERR(map)); + KUNIT_EXPECT_TRUE(test, pf_dt_find(test, misc, c, ARRAY_SIZE(c))); + /* Matched by label, in the order of apple_pmgr_fabric_voters. */ + KUNIT_EXPECT_EQ(test, misc->votes[0].reg, 0x100U); + KUNIT_EXPECT_EQ(test, misc->votes[1].reg, 0x110U); + KUNIT_EXPECT_EQ(test, misc->votes[2].reg, 0x118U); + KUNIT_EXPECT_PTR_EQ(test, misc->votes[0].regmap, map); + KUNIT_EXPECT_PTR_EQ(test, misc->votes[1].regmap, map); + KUNIT_EXPECT_PTR_EQ(test, misc->votes[2].regmap, map); + + /* The voters read through the parent's register map. */ + pf_dt_regs[0x110 / 4] = PF_VOTE_IDLE; + pf_dt_regs[0x118 / 4] = PF_VOTE_IDLE; + pf_dt_regs[0x100 / 4] = PF_VOTE_BUSY; + KUNIT_EXPECT_TRUE(test, apple_pmgr_voters_active(misc)); + pf_dt_regs[0x100 / 4] = PF_VOTE_IDLE; + KUNIT_EXPECT_FALSE(test, apple_pmgr_voters_active(misc)); +} + +static void pf_dt_voters_missing_test(struct kunit *test) +{ + struct pf_dt_child c[] = { + { "power-controller@100", "gfx", 0x100 }, + { "power-controller@110", "avd_sys", 0x110 }, + { "power-controller@118", "isp_sys", 0x118 }, + }; + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + pf_dt_require_fixture_only(test); + + /* Desktop without ISP: the governor must never lower. */ + KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, 2)); + KUNIT_EXPECT_NULL(test, misc->votes[2].regmap); + + c[2].disabled = true; + KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, 3)); + c[2].disabled = false; + + c[2].reg = 0; + KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, 3)); + c[2].reg = 0x118; + + c[2].label = NULL; + KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, 3)); + c[2].label = "isp"; + KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, 3)); + c[2].label = "isp_sys"; + + KUNIT_EXPECT_TRUE(test, pf_dt_find(test, misc, c, 3)); + + /* With the voters missing the governor stays high. */ + misc->voters_ok = false; + WRITE_ONCE(idle_fabric_pstate, 1); + apple_pmgr_idle_eval(misc); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); +} + +static void pf_dt_voters_duplicate_test(struct kunit *test) +{ + static const struct pf_dt_child c[] = { + { "power-controller@100", "gfx", 0x100 }, + { "power-controller@108", "gfx", 0x108 }, + { "power-controller@110", "avd_sys", 0x110 }, + }; + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + pf_dt_require_fixture_only(test); + + /* A second gfx node must not stand in for the missing isp_sys. */ + KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, ARRAY_SIZE(c))); + KUNIT_EXPECT_NOT_NULL(test, misc->votes[0].regmap); + KUNIT_EXPECT_NULL(test, misc->votes[2].regmap); +} + +static void pf_dt_pmp_unbound_test(struct kunit *test) +{ + static const struct pf_dt_child c[] = { + { "pmp", NULL, 0, false, "apple,t6000-pmp-v2" }, + }; + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + struct of_changeset cs; + + pf_dt_require_fixture_only(test); + + /* PMP described but no driver bound: sleep takes the path without it. */ + misc->pmp_owned = true; + pf_dt_apply(test, &cs, c, ARRAY_SIZE(c)); + KUNIT_EXPECT_EQ(test, apple_pmgr_misc_prepare(misc->dev), 0); + pf_dt_revert(&cs); + KUNIT_EXPECT_FALSE(test, misc->pmp_sleep); + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_suspend_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000091U); + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_resume_noirq(misc->dev), 0); + apple_pmgr_misc_complete(misc->dev); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000099U); +} + +static int pf_suite_init(struct kunit_suite *suite) +{ + struct of_changeset cs; + struct device_node *box; + struct regmap *map; + int ret; + + if (!of_root) + return -ENODEV; + map = regmap_init_mmio(NULL, (void __iomem *)pf_dt_regs, &pf_dt_regmap_config); + if (IS_ERR(map)) + return PTR_ERR(map); + + /* + * Disabled container: nothing below it is populated as a device. The + * changeset is never reverted, see above. + */ + of_changeset_init(&cs); + box = of_changeset_create_node(&cs, of_root, "kunit-apple-pmgr-fabric"); + if (!box || of_changeset_add_prop_string(&cs, box, "status", "disabled")) + goto nomem; + pf_dt_pmgr = of_changeset_create_node(&cs, box, "power-management"); + if (!pf_dt_pmgr) + goto nomem; + ret = of_changeset_apply(&cs); + if (ret) + goto destroy; + return of_syscon_register_regmap(pf_dt_pmgr, map); + +nomem: + ret = -ENOMEM; +destroy: + of_changeset_destroy(&cs); + regmap_exit(map); + pf_dt_pmgr = NULL; + return ret; +} + +static struct kunit_case apple_pmgr_fabric_test_cases[] = { + KUNIT_CASE(pf_suspend_resume_test), + KUNIT_CASE(pf_suspend_absent_control_test), + KUNIT_CASE(pf_pmp_suspend_test), + KUNIT_CASE(pf_pmp_resume_new_choice_test), + KUNIT_CASE(pf_raise_test), + KUNIT_CASE(pf_raise_timeout_test), + KUNIT_CASE(pf_raise_skip_test), + KUNIT_CASE(pf_hold_release_test), + KUNIT_CASE(pf_voters_active_test), + KUNIT_CASE(pf_idle_lowers_test), + KUNIT_CASE(pf_idle_blockers_test), + KUNIT_CASE(pf_idle_off_sleeping_test), + KUNIT_CASE(pf_param_test), + KUNIT_CASE(pf_prepare_complete_test), + KUNIT_CASE(pf_match_data_test), + KUNIT_CASE(pf_dt_voters_test), + KUNIT_CASE(pf_dt_voters_missing_test), + KUNIT_CASE(pf_dt_voters_duplicate_test), + KUNIT_CASE(pf_dt_pmp_unbound_test), + {} +}; + +static struct kunit_suite apple_pmgr_fabric_test_suite = { + .name = "apple-pmgr-fabric", + .suite_init = pf_suite_init, + .init = pf_test_init, + .exit = pf_test_exit, + .test_cases = apple_pmgr_fabric_test_cases, +}; + +kunit_test_suite(apple_pmgr_fabric_test_suite); diff --git a/drivers/soc/apple/apple-pmgr-misc.c b/drivers/soc/apple/apple-pmgr-misc.c index 3912f45bb60d33..df0d63a111e4c3 100644 --- a/drivers/soc/apple/apple-pmgr-misc.c +++ b/drivers/soc/apple/apple-pmgr-misc.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -19,10 +20,11 @@ #include #include #include +#include #include #include #include -#if IS_ENABLED(CONFIG_APPLE_PMGR_DCS_KUNIT_TEST) +#if IS_ENABLED(CONFIG_APPLE_PMGR_DCS_KUNIT_TEST) || IS_ENABLED(CONFIG_APPLE_PMGR_FABRIC_KUNIT_TEST) #include #endif @@ -499,6 +501,9 @@ static bool apple_pmgr_cpus_at_min(void) unsigned int cpu; bool at_min = true; +#if IS_ENABLED(CONFIG_APPLE_PMGR_FABRIC_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(apple_pmgr_cpus_at_min); +#endif for_each_online_cpu(cpu) { policy = cpufreq_cpu_get(cpu); if (!policy) @@ -736,6 +741,37 @@ static int apple_pmgr_init_device(struct apple_pmgr_misc *misc, return 0; } +/* Read only: the whole clock-generator word of one system device (the desired state is bits 3:0, the actual state bits 7:4), no side effect. */ +static int apple_pmgr_misc_ps_show(struct seq_file *s, void *unused) +{ + const struct apple_pmgr_sys_device *d = s->private; + + seq_printf(s, "%#010x\n", readl_relaxed(d->base + APPLE_CLKGEN_PSTATE)); + return 0; +} +DEFINE_SHOW_ATTRIBUTE(apple_pmgr_misc_ps); + +static void apple_pmgr_misc_debugfs_remove(void *dir) +{ + debugfs_remove(dir); +} + +static void apple_pmgr_misc_debugfs_init(struct apple_pmgr_misc *misc) +{ + static const char * const names[DEV_MAX] = { "fabric_ps", "dcs_ps" }; + char *dirname = devm_kasprintf(misc->dev, GFP_KERNEL, "apple-pmgr-misc-%s", dev_name(misc->dev)); + struct dentry *dir; + int i; + + if (!dirname) + return; + dir = debugfs_create_dir(dirname, NULL); + for (i = 0; i < DEV_MAX; i++) + if (misc->devices[i].base) + debugfs_create_file(names[i], 0400, dir, &misc->devices[i], &apple_pmgr_misc_ps_fops); + devm_add_action_or_reset(misc->dev, apple_pmgr_misc_debugfs_remove, dir); +} + static int apple_pmgr_misc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -764,6 +800,8 @@ static int apple_pmgr_misc_probe(struct platform_device *pdev) platform_set_drvdata(pdev, misc); + apple_pmgr_misc_debugfs_init(misc); + /* * With PMP enabled its firmware owns the fabric and DCS p-states. * Writing them for suspend as well leaves the system unable to resume @@ -849,3 +887,7 @@ module_platform_driver(apple_pmgr_misc_driver); #if IS_ENABLED(CONFIG_APPLE_PMGR_DCS_KUNIT_TEST) #include "apple-pmgr-dcs-test.c" #endif + +#if IS_ENABLED(CONFIG_APPLE_PMGR_FABRIC_KUNIT_TEST) +#include "apple-pmgr-fabric-test.c" +#endif diff --git a/drivers/soc/apple/apple-pmgr-misc.kunitconfig b/drivers/soc/apple/apple-pmgr-misc.kunitconfig new file mode 100644 index 00000000000000..e97c8ec17a7e8d --- /dev/null +++ b/drivers/soc/apple/apple-pmgr-misc.kunitconfig @@ -0,0 +1,9 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_OF_OVERLAY=y +CONFIG_PM=y +CONFIG_MFD_SYSCON=y +CONFIG_APPLE_PMGR_MISC=y +CONFIG_APPLE_PMGR_DCS_KUNIT_TEST=y +CONFIG_APPLE_PMGR_FABRIC_KUNIT_TEST=y diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index 4bd3d6c7c0a950..d05149ff2ff579 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -20,10 +20,14 @@ * Copyright The Asahi Linux Contributors */ +#include +#include +#include #include #include #include #include +#include #include #include #include @@ -40,6 +44,8 @@ #include #include #include +#include +#include #include #include #include @@ -77,6 +83,9 @@ enum apple_clpc_rail { #define APPLE_CLPC_REASON_HOLD BIT(4) #define APPLE_CLPC_REASON_ANE BIT(5) +/* A lower GPU busy level must last this long; a higher one applies at once. */ +#define APPLE_CLPC_GPU_DOWN_MS 400 + /** * struct apple_clpc_hw - per-SoC CLPC parameters * @rail: PMC rail of the DCS and of the fabric @@ -90,6 +99,7 @@ enum apple_clpc_rail { * counts as streaming, see apple_clpc_gpu_streaming(); 0 counts it at once * @pmp_backoff: release that GPU floor while the PMP, voter agent * @pmp_agent, limits the DCS, see apple_clpc_gpu_limited() + * @pmp_agent: PMC floor voter agent of the PMP, read for @pmp_backoff * @gpu_dense: submissions per sampling period that make light GPU work * dense, see apple_clpc_gpu_dense(); 0 for none * @ane: state of each rail while ANE work is in flight; all zero disables input @@ -101,11 +111,24 @@ enum apple_clpc_rail { * measured on; SoCs sharing this CLPC without it get no cluster floor * @gpu_input: the GPU driver reports its work in flight through * apple_clpc_gpu_get(); while there is some, both rails go to the top - * of @map + * of @map (or @gpu where higher), or to @gpu_busy if enabled from the DT + * @gpu_busy: state of each rail for reported GPU work below @gpu_busy_mid, + * @gpu_busy_high and @gpu_busy_top and at or above it, from the node's + * apple,gpu-busy-memory-states and apple,gpu-busy-permille properties; + * a non-zero top DCS state enables the busy-share ladder, otherwise + * reported GPU work falls back to the top of @map (or @gpu where higher) + * @gpu_busy_mid: GPU busy share in permille (apple_clpc_gpu_set_busy()) + * from which reported GPU work gets the second column of @gpu_busy + * @gpu_busy_high: busy share from which it gets the third column + * @gpu_busy_top: busy share from which it gets the top column, as does a + * GPU that reports no share. The share is the busiest engine's time spent + * executing at whatever clock the GPU runs, not bandwidth: a scrolling + * browser reads a few percent, CS2 at 120 fps ~480-620 permille. * @idle_on_time: sample every period even with no vote held, instead of * from a deferrable timer * @low_power_khz: CPU frequency ceiling of the low-power platform profile, - * taken up to the next table frequency; 0 for no platform profile + * taken up to the next table frequency, for a node without + * apple,low-power-frequency-max-mhz; 0 for none * @low_power_mw: package power (the SMC's PHPC key) the low-power profile * holds the CPU clusters to; 0 for none * @high_power_machine: the machine compatible that had High Power mode from @@ -123,6 +146,10 @@ struct apple_clpc_hw { unsigned int pmp_agent; unsigned int gpu_dense; bool gpu_input; + u8 gpu_busy[APPLE_CLPC_RAILS][APPLE_CLPC_LEVELS]; + unsigned int gpu_busy_mid; + unsigned int gpu_busy_high; + unsigned int gpu_busy_top; u8 ane[APPLE_CLPC_RAILS]; unsigned int ane_cluster; unsigned int ane_cluster_khz; @@ -157,6 +184,11 @@ struct apple_clpc_gpu { bool active; u64 updated_ns; u64 sequence; + /* Busy share of the last window in permille, if the GPU reports one */ + unsigned int busy; + bool busy_valid; + unsigned int level; + unsigned long level_since; struct delayed_work *wake; }; @@ -172,14 +204,37 @@ struct apple_clpc_ane { struct delayed_work *wake; }; +struct apple_clpc; + +struct apple_clpc_idle_timer { + struct timer_list timer; + struct apple_clpc *clpc; + u64 last_idle; + u64 last_wall; +}; + struct apple_clpc { struct device *dev; struct device *pmc; const struct apple_clpc_hw *hw; + /* + * The board's states for a CPU cluster busy in the top quarter of its + * range (apple,cpu-busy-floor) outside the low-power profile, in place + * of the top of @hw->map; GPU and ANE demand still use @hw. Unset: + * @hw->map applies. + */ + u8 cpu_top[APPLE_CLPC_RAILS]; + bool cpu_top_set; unsigned int agent; - /* Samples while a vote is held; idle_work defers to busy CPUs. */ + /* Samples while a vote is held; idle_work or per-CPU idle_timers defer to busy CPUs. */ struct delayed_work work; struct delayed_work idle_work; + struct apple_clpc_idle_timer __percpu *idle_timers; + struct mutex idle_lock; + cpumask_t idle_online_cpus; + struct hlist_node cpuhp_node; + bool cpuhp_added; + atomic_t idle_armed; struct mutex sample_lock; bool stopped; struct apple_clpc_cluster clusters[APPLE_CLPC_MAX_CLUSTERS]; @@ -232,8 +287,12 @@ struct apple_clpc { unsigned long gpu_streaming_samples; unsigned long gpu_dense_samples; /* The platform profile and, for its power target, the SMC */ + bool has_pmc; enum platform_profile_option profile; bool low_power; + /* the DT ceiling, else hw->low_power_khz, else 0 */ + unsigned int low_power_khz; + unsigned int low_power_mw; struct device_node *smc_np; struct apple_smc *smc; /* The performance profile is sent to the SMC as High Power mode */ @@ -266,12 +325,35 @@ void apple_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active) if (active && !gpu->active && gpu->wake) mod_delayed_work(system_freezable_power_efficient_wq, gpu->wake, 0); gpu->active = active; + /* A new burst after idle starts from the top, not from an old share. */ + if (!active) + gpu->busy_valid = false; gpu->updated_ns = ktime_get_mono_fast_ns(); gpu->sequence++; spin_unlock_irqrestore(&gpu->lock, flags); } EXPORT_SYMBOL_GPL(apple_clpc_gpu_set_active); +/** + * apple_clpc_gpu_set_busy() - Report the GPU busy share of the last window + * @gpu: the GPU input, from apple_clpc_gpu_get() + * @permille: share of the window the GPU spent executing work, 0..1000 + * + * Scales the floor that reported GPU work gets, see &struct apple_clpc_hw.gpu_busy. + */ +void apple_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille) +{ + unsigned long flags; + + if (!gpu) + return; + spin_lock_irqsave(&gpu->lock, flags); + gpu->busy = min(permille, 1000U); + gpu->busy_valid = true; + spin_unlock_irqrestore(&gpu->lock, flags); +} +EXPORT_SYMBOL_GPL(apple_clpc_gpu_set_busy); + void apple_clpc_gpu_put(struct apple_clpc_gpu *gpu) { if (gpu) { @@ -310,10 +392,16 @@ int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu **out) !of_device_is_compatible(np, "apple,t6050-clpc") && !of_device_is_compatible(np, "apple,t8132-clpc") && !of_device_is_compatible(np, "apple,t8140-clpc") && - !of_device_is_compatible(np, "apple,t8142-clpc")) { + !of_device_is_compatible(np, "apple,t8142-clpc") && + !of_device_is_compatible(np, "apple,t8152-clpc")) { of_node_put(np); return -EINVAL; } + /* A disabled provider never probes: run without its input, do not defer. */ + if (!of_device_is_available(np)) { + of_node_put(np); + return 0; + } provider = of_find_device_by_node(np); of_node_put(np); if (!provider) @@ -340,6 +428,36 @@ int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu **out) } EXPORT_SYMBOL_GPL(apple_clpc_gpu_get); +/* + * The column of @hw->gpu_busy for reported GPU work, from its busy share. + * Called once per CLPC sample: a higher column applies at once, a lower one + * at the first sample at least APPLE_CLPC_GPU_DOWN_MS after the last one + * that asked for the current column or a higher one. + */ +static unsigned int apple_clpc_gpu_level(const struct apple_clpc_hw *hw, + struct apple_clpc_gpu *gpu) +{ + unsigned long flags; + unsigned int level; + + spin_lock_irqsave(&gpu->lock, flags); + if (!gpu->busy_valid || gpu->busy >= hw->gpu_busy_top) + level = APPLE_CLPC_LEVELS - 1; + else if (gpu->busy >= hw->gpu_busy_high) + level = 2; + else + level = gpu->busy >= hw->gpu_busy_mid ? 1 : 0; + if (level >= gpu->level || + time_after_eq(jiffies, gpu->level_since + + msecs_to_jiffies(APPLE_CLPC_GPU_DOWN_MS))) { + gpu->level = level; + gpu->level_since = jiffies; + } + level = gpu->level; + spin_unlock_irqrestore(&gpu->lock, flags); + return level; +} + static bool apple_clpc_gpu_active(struct apple_clpc_gpu *gpu, u64 *updated, u64 *sequence) { unsigned long flags; @@ -396,9 +514,11 @@ EXPORT_SYMBOL_GPL(apple_clpc_ane_put); /* SoCs whose CLPC takes ANE input; each SoC has exactly one CLPC. */ static const struct of_device_id apple_clpc_ane_providers[] = { + { .compatible = "apple,t6050-clpc" }, { .compatible = "apple,t6041-max-clpc" }, { .compatible = "apple,t6041-clpc" }, { .compatible = "apple,t8140-clpc" }, + { .compatible = "apple,t8142-clpc" }, {} }; @@ -505,12 +625,27 @@ static void apple_clpc_find_clusters(struct apple_clpc *clpc) cl = &clpc->clusters[i]; cpumask_set_cpu(cpu, cl->cpus); cpumask_set_cpu(cpu, clpc->covered); - clpc->idle[cpu] = get_cpu_idle_time(cpu, &clpc->wall[cpu], 0); + if (clpc->idle && clpc->wall) + clpc->idle[cpu] = get_cpu_idle_time(cpu, &clpc->wall[cpu], 0); } cpufreq_cpu_put(policy); } } +/* + * The state a busy CPU cluster in frequency quarter @q asks @rail for. + * The board's override applies outside the low-power platform profile, + * where macOS drops the single-thread busy floor. + */ +static unsigned int apple_clpc_cpu_state(const struct apple_clpc *clpc, + unsigned int rail, unsigned int q) +{ + if (clpc->cpu_top_set && q == APPLE_CLPC_LEVELS - 1 && + !READ_ONCE(clpc->low_power)) + return clpc->cpu_top[rail]; + return clpc->hw->map[rail][q]; +} + static void apple_clpc_sample_cluster(struct apple_clpc *clpc, struct apple_clpc_cluster *cl) { @@ -560,7 +695,7 @@ static void apple_clpc_sample_cluster(struct apple_clpc *clpc, for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) cl->request[rail] = busy >= APPLE_CLPC_BUSY_PCT && cl->streak >= clpc->hw->sustain ? - clpc->hw->map[rail][q] : 0; + apple_clpc_cpu_state(clpc, rail, q) : 0; } static unsigned int apple_clpc_vote(struct apple_clpc_vote *vote, @@ -589,17 +724,169 @@ static u32 apple_clpc_floor(struct apple_clpc *clpc, const unsigned int *state) return floor; } +static enum cpuhp_state apple_clpc_cpuhp_state; + +static unsigned long apple_clpc_idle_step(void) +{ + return max_t(unsigned long, msecs_to_jiffies(APPLE_CLPC_SAMPLE_MS), 2); +} + +static void apple_clpc_idle_timer_fn(struct timer_list *timer) +{ + struct apple_clpc_idle_timer *t = timer_container_of(t, timer, timer); + struct apple_clpc *clpc = t->clpc; + unsigned int cpu = smp_processor_id(); + unsigned long step = apple_clpc_idle_step(); + u64 wall, idle, dw, di; + + if (READ_ONCE(clpc->stopped) || !atomic_read(&clpc->idle_armed)) + return; + + idle = get_cpu_idle_time(cpu, &wall, 0); + if (wall < t->last_wall || idle < t->last_idle) { + t->last_wall = wall; + t->last_idle = idle; + mod_timer(&t->timer, jiffies + step); + return; + } + dw = wall - t->last_wall; + if (dw < APPLE_CLPC_SAMPLE_MS * 1000ULL) { + mod_timer(&t->timer, jiffies + step); + return; + } + di = idle - t->last_idle; + t->last_wall = wall; + t->last_idle = idle; + + /* + * A CPU that only woke briefly for an IRQ or short timer stayed mostly + * idle (or an out-of-order iowait/idle read yielded di > dw); re-arm + * its pinned deferrable timer without waking a kworker. + */ + if (di > dw || (dw - di) * 100 < dw * APPLE_CLPC_BUSY_PCT) { + mod_timer(&t->timer, jiffies + step); + return; + } + + if (atomic_cmpxchg(&clpc->idle_armed, 1, 0) == 1) + mod_delayed_work(system_freezable_power_efficient_wq, + &clpc->work, 0); +} + +static int apple_clpc_cpu_online(unsigned int cpu, struct hlist_node *node) +{ + struct apple_clpc *clpc = hlist_entry_safe(node, struct apple_clpc, + cpuhp_node); + struct apple_clpc_idle_timer *t; + + if (!clpc || !clpc->idle_timers) + return 0; + + guard(mutex)(&clpc->idle_lock); + cpumask_set_cpu(cpu, &clpc->idle_online_cpus); + if (READ_ONCE(clpc->stopped) || !atomic_read(&clpc->idle_armed)) + return 0; + + t = per_cpu_ptr(clpc->idle_timers, cpu); + timer_delete_sync(&t->timer); + t->last_idle = get_cpu_idle_time(cpu, &t->last_wall, 0); + t->timer.expires = jiffies + apple_clpc_idle_step(); + add_timer_on(&t->timer, cpu); + return 0; +} + +static int apple_clpc_cpu_down(unsigned int cpu, struct hlist_node *node) +{ + struct apple_clpc *clpc = hlist_entry_safe(node, struct apple_clpc, + cpuhp_node); + + if (!clpc || !clpc->idle_timers) + return 0; + + /* Delete before CPU teardown migrates the pinned timer elsewhere. */ + guard(mutex)(&clpc->idle_lock); + cpumask_clear_cpu(cpu, &clpc->idle_online_cpus); + timer_delete_sync(&per_cpu_ptr(clpc->idle_timers, cpu)->timer); + return 0; +} + +/* + * Arm a pinned deferrable timer on every online CPU. Idle CPUs stay asleep + * (TIMER_DEFERRABLE never sends an IPI or wakes a NO_HZ CPU), while any busy + * CPU runs the callback once its tick resumes and kicks active CLPC sampling. + */ +static void apple_clpc_arm_idle(struct apple_clpc *clpc) +{ + unsigned long expires = jiffies + apple_clpc_idle_step(); + unsigned int cpu; + + /* + * Serialize with CPU hotplug callbacks and halt via idle_lock (ordered + * strictly inside cpuhp and sample_lock) rather than taking + * cpus_read_lock() inside sample_lock. + */ + guard(mutex)(&clpc->idle_lock); + atomic_set(&clpc->idle_armed, 0); + smp_mb(); + for_each_possible_cpu(cpu) { + struct apple_clpc_idle_timer *t = per_cpu_ptr(clpc->idle_timers, cpu); + + timer_delete_sync(&t->timer); + } + + for_each_cpu(cpu, &clpc->idle_online_cpus) { + struct apple_clpc_idle_timer *t = per_cpu_ptr(clpc->idle_timers, cpu); + + t->last_idle = get_cpu_idle_time(cpu, &t->last_wall, 0); + } + atomic_set(&clpc->idle_armed, 1); + smp_mb(); + for_each_cpu(cpu, &clpc->idle_online_cpus) { + struct apple_clpc_idle_timer *t = per_cpu_ptr(clpc->idle_timers, cpu); + + t->timer.expires = expires; + add_timer_on(&t->timer, cpu); + } +} + static void apple_clpc_queue(struct apple_clpc *clpc, bool idle) { if (READ_ONCE(clpc->stopped)) return; + if (!clpc->has_pmc) { + unsigned long delay; + + cancel_delayed_work(&clpc->idle_work); + if (clpc->low_power_khz && clpc->low_power_mw && + READ_ONCE(clpc->low_power)) + delay = msecs_to_jiffies(APPLE_CLPC_POWER_MS); + else if (!cpumask_equal(clpc->covered, cpu_possible_mask)) + delay = HZ; + else + return; + mod_delayed_work(system_freezable_power_efficient_wq, &clpc->work, delay); + return; + } + /* * A held vote has to be sampled on time so that it drops once demand * stops; with no vote held, sampling can wait for a CPU that wakes up - * anyway rather than waking an idle one every period, unless the SoC - * samples on time (@idle_on_time). + * anyway rather than waking an idle one every period. On SoCs with + * @idle_on_time (and without nohz_full, which can stop ticks on busy + * CPUs), arm a per-CPU deferrable timer across online CPUs so an idle + * system takes zero CLPC wakeups. Preserve any fresh client demand + * already queued on clpc->work. */ + if (idle && clpc->idle_timers && !tick_nohz_full_enabled()) { + cancel_delayed_work(&clpc->idle_work); + if (delayed_work_pending(&clpc->work)) + return; + apple_clpc_arm_idle(clpc); + return; + } + + atomic_set(&clpc->idle_armed, 0); idle = idle && !clpc->hw->idle_on_time; /* A demand edge can queue work while the deferrable pass is pending. * Keep one sampling cadence once the serialized pass settles. @@ -724,22 +1011,30 @@ static void apple_clpc_gpu_floor_count(struct apple_clpc *clpc, bool released) /* * The GPU driver's input, where it drives demand instead of the GFX power - * state: every rail at the top of @map, or at @gpu where that is higher, - * while the driver reports work. + * state: while the driver reports work, every rail at @gpu_busy for the + * reported busy share when @gpu_busy has a non-zero top DCS state, or at the + * top of @map (or @gpu where that is higher) otherwise. */ static bool apple_clpc_gpu_input_demand(const struct apple_clpc_hw *hw, struct apple_clpc_gpu *gpu, unsigned int *demand) { + bool has_busy = hw->gpu_busy[APPLE_CLPC_DCS][APPLE_CLPC_LEVELS - 1]; u64 updated, sequence; - unsigned int rail; + unsigned int level = 0, rail; if (!gpu || hw->gpu_demand || !apple_clpc_gpu_active(gpu, &updated, &sequence)) return false; - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - demand[rail] = max(demand[rail], - max(hw->map[rail][APPLE_CLPC_LEVELS - 1], hw->gpu[rail])); + if (has_busy) + level = apple_clpc_gpu_level(hw, gpu); + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) { + unsigned int state = has_busy ? hw->gpu_busy[rail][level] : + max(hw->map[rail][APPLE_CLPC_LEVELS - 1], + hw->gpu[rail]); + + demand[rail] = max(demand[rail], state); + } return true; } @@ -784,6 +1079,8 @@ static unsigned int apple_clpc_step_khz(struct cpufreq_policy *policy, struct cpufreq_frequency_table *pos; unsigned int best = khz; + if (!policy->freq_table) + return khz; cpufreq_for_each_valid_entry(pos, policy->freq_table) { if (up ? pos->frequency > khz && (best == khz || pos->frequency < best) : pos->frequency < khz && (best == khz || pos->frequency > best)) @@ -792,7 +1089,29 @@ static unsigned int apple_clpc_step_khz(struct cpufreq_policy *policy, return best; } -/* The SMC of the apple,smc phandle, once its driver is bound; NULL before. */ +/* + * The low-power platform-profile frequency ceiling for @policy: the first + * table frequency at or above @low_power_khz (matching macOS Low Power Mode's + * round-up), or policy max if the cluster is slower or @low_power_khz is 0. + */ +static unsigned int apple_clpc_low_power_top_khz(struct cpufreq_policy *policy, + unsigned int low_power_khz) +{ + unsigned int top; + + if (!low_power_khz) + return policy->cpuinfo.max_freq; + top = apple_clpc_step_khz(policy, low_power_khz - 1, true); + if (top < low_power_khz) + top = policy->cpuinfo.max_freq; + return top; +} + +/* + * The SMC of the apple,smc phandle, once its driver is bound; NULL before. + * Callers test IS_ENABLED(CONFIG_MFD_MACSMC) first, so a kernel without the + * SMC driver links without the apple_smc_*() calls. + */ static struct apple_smc *apple_clpc_smc(struct apple_clpc *clpc) { struct platform_device *pdev; @@ -815,7 +1134,7 @@ static int apple_clpc_read_power(struct apple_clpc *clpc) u64 mw; u32 f; - if (!apple_clpc_smc(clpc)) + if (!IS_ENABLED(CONFIG_MFD_MACSMC) || !apple_clpc_smc(clpc)) return -ENODEV; ret = apple_smc_read_u32(clpc->smc, SMC_KEY(PHPC), &f); if (ret) @@ -845,9 +1164,9 @@ static bool apple_clpc_steps_first(unsigned int a_khz, unsigned int a_max, /* * The platform profile's ceilings. In the low-power profile every cluster - * stays at or below the first frequency at or above hw->low_power_khz. Each - * new package power reading above hw->low_power_mw takes one table step off - * one cluster, and each one below 90% of it puts one back, in the order of + * stays at or below apple_clpc_low_power_top_khz(). When @low_power_mw is set, + * each new package power reading above it takes one table step off one + * cluster, and each one below 90% of it puts one back, in the order of * apple_clpc_steps_first(). Elsewhere there is no ceiling. */ static void apple_clpc_profile_limit(struct apple_clpc *clpc) @@ -857,18 +1176,18 @@ static void apple_clpc_profile_limit(struct apple_clpc *clpc) unsigned int i, khz, pick_khz = 0; int mw, step = 0, pick = -1; - if (!clpc->hw->low_power_khz || time_before(jiffies, clpc->power_next)) + if (!clpc->low_power_khz || time_before(jiffies, clpc->power_next)) return; clpc->power_next = jiffies + msecs_to_jiffies(APPLE_CLPC_POWER_MS); - if (low && clpc->hw->low_power_mw) { + if (low && clpc->low_power_mw && clpc->smc_np) { mw = apple_clpc_read_power(clpc); clpc->power_reads++; /* The SMC updates the reading less often: act on a new one only. */ if (mw >= 0 && mw != clpc->power_mw) { clpc->power_updates++; - if (mw > (int)clpc->hw->low_power_mw) + if (mw > (int)clpc->low_power_mw) step = -1; - else if (mw < (int)clpc->hw->low_power_mw * 9 / 10) + else if (mw < (int)clpc->low_power_mw * 9 / 10) step = 1; } clpc->power_mw = mw; @@ -883,14 +1202,12 @@ static void apple_clpc_profile_limit(struct apple_clpc *clpc) freq_qos_add_request(&policy[i]->constraints, &cl->max_qos, FREQ_QOS_MAX, FREQ_QOS_MAX_DEFAULT_VALUE) < 0) clpc->update_errors++; - /* The top: the first table frequency at or above hw->low_power_khz */ - cl->top_khz = apple_clpc_step_khz(policy[i], - clpc->hw->low_power_khz - 1, true); - if (cl->top_khz < clpc->hw->low_power_khz) - cl->top_khz = policy[i]->cpuinfo.max_freq; + cl->top_khz = apple_clpc_low_power_top_khz(policy[i], + clpc->low_power_khz); if (!low) cl->max_khz = 0; - else if (!cl->max_khz) + else if (!cl->max_khz || !clpc->low_power_mw || + cl->max_khz > cl->top_khz) cl->max_khz = cl->top_khz; if (!step) continue; @@ -922,83 +1239,87 @@ static void apple_clpc_profile_limit(struct apple_clpc *clpc) static void apple_clpc_sample(struct apple_clpc *clpc) { unsigned int demand[APPLE_CLPC_RAILS] = {}; - unsigned int state[APPLE_CLPC_RAILS]; + unsigned int state[APPLE_CLPC_RAILS] = {}; unsigned long now = jiffies; unsigned int i, rail; - u32 reason = 0, floor; + u32 reason = 0, floor = 0; + atomic_set(&clpc->idle_armed, 0); clpc->samples++; if (!cpumask_equal(clpc->covered, cpu_possible_mask) && - time_after_eq(now, clpc->next_scan)) { + (!clpc->has_pmc || time_after_eq(now, clpc->next_scan))) { apple_clpc_find_clusters(clpc); clpc->next_scan = now + HZ; } - for (i = 0; i < clpc->nr_clusters; i++) { - struct apple_clpc_cluster *cl = &clpc->clusters[i]; + if (clpc->has_pmc) { + for (i = 0; i < clpc->nr_clusters; i++) { + struct apple_clpc_cluster *cl = &clpc->clusters[i]; - apple_clpc_sample_cluster(clpc, cl); + apple_clpc_sample_cluster(clpc, cl); + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + demand[rail] = max(demand[rail], cl->request[rail]); + } for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - demand[rail] = max(demand[rail], cl->request[rail]); - } - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - if (demand[rail]) - reason |= APPLE_CLPC_REASON_CPU; - if (apple_clpc_gpu_input_demand(clpc->hw, clpc->gpu, demand)) - reason |= APPLE_CLPC_REASON_HOST_GPU; - if (apple_clpc_ane_input_demand(clpc, demand)) - reason |= APPLE_CLPC_REASON_ANE; - apple_clpc_ane_cluster(clpc, reason & APPLE_CLPC_REASON_ANE, now); - if (clpc->gpu_pmgr) { - /* Both run every sample: each tracks state across samples. */ - bool late = time_after(now, clpc->gpu_sampled + - msecs_to_jiffies(2 * APPLE_CLPC_SAMPLE_MS)); - bool dense = apple_clpc_gpu_dense(clpc, late); - bool streaming = apple_clpc_gpu_streaming(clpc, now); - - if (streaming || dense) { - bool released = apple_clpc_gpu_limited(clpc, now); - - apple_clpc_gpu_floor_count(clpc, released); - if (!released) { - reason |= streaming ? APPLE_CLPC_REASON_STREAMING_GPU : - APPLE_CLPC_REASON_DENSE_GPU; - if (streaming) - clpc->gpu_streaming_samples++; - else - clpc->gpu_dense_samples++; - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - demand[rail] = max(demand[rail], - clpc->hw->gpu[rail]); + if (demand[rail]) + reason |= APPLE_CLPC_REASON_CPU; + if (apple_clpc_gpu_input_demand(clpc->hw, clpc->gpu, demand)) + reason |= APPLE_CLPC_REASON_HOST_GPU; + if (apple_clpc_ane_input_demand(clpc, demand)) + reason |= APPLE_CLPC_REASON_ANE; + apple_clpc_ane_cluster(clpc, reason & APPLE_CLPC_REASON_ANE, now); + if (clpc->gpu_pmgr) { + /* Both run every sample: each tracks state across samples. */ + bool late = time_after(now, clpc->gpu_sampled + + msecs_to_jiffies(2 * APPLE_CLPC_SAMPLE_MS)); + bool dense = apple_clpc_gpu_dense(clpc, late); + bool streaming = apple_clpc_gpu_streaming(clpc, now); + + if (streaming || dense) { + bool released = apple_clpc_gpu_limited(clpc, now); + + apple_clpc_gpu_floor_count(clpc, released); + if (!released) { + reason |= streaming ? APPLE_CLPC_REASON_STREAMING_GPU : + APPLE_CLPC_REASON_DENSE_GPU; + if (streaming) + clpc->gpu_streaming_samples++; + else + clpc->gpu_dense_samples++; + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + demand[rail] = max(demand[rail], + clpc->hw->gpu[rail]); + } } } - } - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - state[rail] = apple_clpc_vote(&clpc->vote[rail], demand[rail], - now); + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + state[rail] = apple_clpc_vote(&clpc->vote[rail], demand[rail], + now); - floor = apple_clpc_floor(clpc, state); - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - if (state[rail] > demand[rail]) - reason |= APPLE_CLPC_REASON_HOLD; - clpc->last_floor = floor; - clpc->last_reason = reason; - clpc->last_vote_ns = ktime_get_mono_fast_ns(); - if (apple_pmc_floor_update(clpc->pmc, clpc->agent, clpc->mask, floor)) - clpc->update_errors++; + floor = apple_clpc_floor(clpc, state); + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + if (state[rail] > demand[rail]) + reason |= APPLE_CLPC_REASON_HOLD; + clpc->last_floor = floor; + clpc->last_reason = reason; + clpc->last_vote_ns = ktime_get_mono_fast_ns(); + if (apple_pmc_floor_update(clpc->pmc, clpc->agent, clpc->mask, floor)) + clpc->update_errors++; + } apple_clpc_profile_limit(clpc); /* * Sample on time while graphics is powered, to see it power off, and in - * low power where it has a ceiling to keep. A profile with no low-power - * ceiling (High Power only) has nothing to do there, so it stays - * deferrable. + * low power when an SMC package power target is active. A static + * ceiling is applied synchronously on profile change and a High Power + * only profile has nothing to poll at idle, so both stay deferrable. */ - apple_clpc_queue(clpc, !apple_clpc_floor(clpc, state) && !clpc->gpu_on && + apple_clpc_queue(clpc, !floor && !clpc->gpu_on && !clpc->ane_qos_khz && - !(clpc->hw->low_power_khz && READ_ONCE(clpc->low_power))); + !(clpc->low_power_khz && clpc->low_power_mw && + READ_ONCE(clpc->low_power))); } static void apple_clpc_run(struct apple_clpc *clpc) @@ -1019,29 +1340,80 @@ static void apple_clpc_idle_work(struct work_struct *work) apple_clpc_run(container_of(to_delayed_work(work), struct apple_clpc, idle_work)); } +/* + * apple,cpu-busy-floor: the DCS and fabric states, in that order, for a CPU + * cluster busy in the top quarter of its frequency range outside the low-power + * profile, where the board's measurement differs from the SoC's table. A bad + * value costs the override, not the driver. + */ +static void apple_clpc_cpu_top_init(struct apple_clpc *clpc) +{ + u32 top[APPLE_CLPC_RAILS]; + unsigned int rail; + int ret; + + if (!of_property_present(clpc->dev->of_node, "apple,cpu-busy-floor")) + return; + ret = of_property_read_u32_array(clpc->dev->of_node, "apple,cpu-busy-floor", + top, APPLE_CLPC_RAILS); + for (rail = 0; !ret && rail < APPLE_CLPC_RAILS; rail++) + if (top[rail] > 0xf) + ret = -ERANGE; + if (ret || of_property_count_u32_elems(clpc->dev->of_node, + "apple,cpu-busy-floor") != APPLE_CLPC_RAILS) { + dev_warn(clpc->dev, "invalid apple,cpu-busy-floor; using the SoC's states\n"); + return; + } + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + clpc->cpu_top[rail] = top[rail]; + clpc->cpu_top_set = true; + dev_info(clpc->dev, "busy CPU floor: DCS %u, fabric %u\n", + clpc->cpu_top[APPLE_CLPC_DCS], clpc->cpu_top[APPLE_CLPC_SOC]); +} + static int apple_clpc_status_show(struct seq_file *s, void *unused) { struct apple_clpc *clpc = s->private; unsigned int i, rail; - seq_printf(s, "agent: %u floor: %#010x (saved %#010x)\n", clpc->agent, - apple_pmc_floor_read(clpc->pmc, clpc->agent), - clpc->saved_floor); - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - seq_printf(s, "%s: rail %u state %u enabled %u map %u,%u,%u,%u\n", - rail == APPLE_CLPC_DCS ? "dcs" : "soc", - clpc->hw->rail[rail], clpc->vote[rail].state, - apple_pmc_voter_enabled(clpc->pmc, clpc->agent, - clpc->hw->rail[rail]), - clpc->hw->map[rail][0], clpc->hw->map[rail][1], - clpc->hw->map[rail][2], clpc->hw->map[rail][3]); - seq_printf(s, "last_vote: %#x reason_bits %#x sampled_ns %llu (cpu=1 host_gpu=2 streaming_gpu=4 dense_gpu=8 hold=16 ane=32)\n", - READ_ONCE(clpc->last_floor), READ_ONCE(clpc->last_reason), - READ_ONCE(clpc->last_vote_ns)); + if (clpc->has_pmc) { + seq_printf(s, "agent: %u floor: %#010x (saved %#010x)\n", clpc->agent, + apple_pmc_floor_read(clpc->pmc, clpc->agent), + clpc->saved_floor); + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + seq_printf(s, "%s: rail %u state %u enabled %u map %u,%u,%u,%u\n", + rail == APPLE_CLPC_DCS ? "dcs" : "soc", + clpc->hw->rail[rail], clpc->vote[rail].state, + apple_pmc_voter_enabled(clpc->pmc, clpc->agent, + clpc->hw->rail[rail]), + apple_clpc_cpu_state(clpc, rail, 0), + apple_clpc_cpu_state(clpc, rail, 1), + apple_clpc_cpu_state(clpc, rail, 2), + apple_clpc_cpu_state(clpc, rail, 3)); + seq_printf(s, "last_vote: %#x reason_bits %#x sampled_ns %llu (cpu=1 host_gpu=2 streaming_gpu=4 dense_gpu=8 hold=16 ane=32)\n", + READ_ONCE(clpc->last_floor), READ_ONCE(clpc->last_reason), + READ_ONCE(clpc->last_vote_ns)); + } if (clpc->gpu) { + struct apple_clpc_gpu *gpu = clpc->gpu; + unsigned int busy, level; + unsigned long flags; u64 updated, sequence; - bool active = apple_clpc_gpu_active(clpc->gpu, &updated, &sequence); - + bool active = apple_clpc_gpu_active(gpu, &updated, &sequence); + bool busy_valid; + + /* Show the level the last sample chose; reading must not move it. */ + spin_lock_irqsave(&gpu->lock, flags); + busy = gpu->busy; + busy_valid = gpu->busy_valid; + level = gpu->level; + spin_unlock_irqrestore(&gpu->lock, flags); + if (clpc->hw->gpu_busy[APPLE_CLPC_DCS][APPLE_CLPC_LEVELS - 1]) + seq_printf(s, "host_gpu busy: %u permille (%s) level %u\n", + busy, busy_valid ? "reported" : "none", level); + else + seq_printf(s, "host_gpu busy: %u permille (%s)\n", + busy, busy_valid ? "reported" : "none"); seq_printf(s, "host_gpu: active %u request_ns %llu sequence %llu\n", active, updated, sequence); } @@ -1061,11 +1433,23 @@ static int apple_clpc_status_show(struct seq_file *s, void *unused) } seq_printf(s, "samples: %lu update errors: %lu\n", clpc->samples, clpc->update_errors); - if (clpc->hw->low_power_khz) { + if (clpc->low_power_khz) { + int power_mw = clpc->power_mw; + + if (!clpc->low_power_mw && clpc->smc_np) { + mutex_lock(&clpc->sample_lock); + if (!READ_ONCE(clpc->stopped)) { + int mw = apple_clpc_read_power(clpc); + + if (mw >= 0) + power_mw = mw; + } + mutex_unlock(&clpc->sample_lock); + } seq_printf(s, "profile: %s power %d mW (%lu new of %lu readings) ceilings (kHz):", clpc->profile == PLATFORM_PROFILE_LOW_POWER ? "low-power" : clpc->profile == PLATFORM_PROFILE_PERFORMANCE ? "performance" : - "balanced", clpc->power_mw, clpc->power_updates, clpc->power_reads); + "balanced", power_mw, clpc->power_updates, clpc->power_reads); for (i = 0; i < clpc->nr_clusters; i++) seq_printf(s, " cpu%u %u", clpc->clusters[i].policy_cpu, clpc->clusters[i].max_khz); @@ -1088,12 +1472,14 @@ static int apple_clpc_status_show(struct seq_file *s, void *unused) clpc->gpu_streaming_samples, clpc->gpu_dense_samples); seq_printf(s, "gpu read errors: %lu\n", clpc->gpu_read_errors); } - for (i = 0; i < clpc->nr_clusters; i++) - seq_printf(s, "cluster cpu%u: busy %u%% level %u%% -> dcs %u soc %u\n", - clpc->clusters[i].policy_cpu, clpc->clusters[i].busy, - clpc->clusters[i].level, - clpc->clusters[i].request[APPLE_CLPC_DCS], - clpc->clusters[i].request[APPLE_CLPC_SOC]); + if (clpc->has_pmc) { + for (i = 0; i < clpc->nr_clusters; i++) + seq_printf(s, "cluster cpu%u: busy %u%% level %u%% -> dcs %u soc %u\n", + clpc->clusters[i].policy_cpu, clpc->clusters[i].busy, + clpc->clusters[i].level, + clpc->clusters[i].request[APPLE_CLPC_DCS], + clpc->clusters[i].request[APPLE_CLPC_SOC]); + } return 0; } @@ -1168,20 +1554,34 @@ static void apple_clpc_free_clusters(struct apple_clpc *clpc) /* Stop sampling and give the floor back, before suspend and on removal. */ static void apple_clpc_halt(struct apple_clpc *clpc) { - unsigned int rail, i; + unsigned int rail, i, cpu; /* - * Each pass queues one of the two works unless stopped. A pass that - * began before the flag was set can still queue the other work once, - * which the second round cancels. + * Each pass queues one of the two works (or arms per-CPU deferrable + * timers) unless stopped. Cancel any in-flight pass first, drain every + * per-CPU idle timer so none can re-queue work, then cancel once more. */ WRITE_ONCE(clpc->stopped, true); + atomic_set(&clpc->idle_armed, 0); + cancel_delayed_work_sync(&clpc->work); + cancel_delayed_work_sync(&clpc->idle_work); + if (clpc->idle_timers) { + scoped_guard(mutex, &clpc->idle_lock) { + for_each_possible_cpu(cpu) { + struct apple_clpc_idle_timer *t = + per_cpu_ptr(clpc->idle_timers, cpu); + + timer_delete_sync(&t->timer); + } + } + } for (i = 0; i < 2; i++) { cancel_delayed_work_sync(&clpc->work); cancel_delayed_work_sync(&clpc->idle_work); } - apple_pmc_floor_update(clpc->pmc, clpc->agent, clpc->mask, - clpc->saved_floor); + if (clpc->has_pmc) + apple_pmc_floor_update(clpc->pmc, clpc->agent, clpc->mask, + clpc->saved_floor); for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) clpc->vote[rail].state = 0; if (clpc->ane_qos_khz && @@ -1209,6 +1609,13 @@ static void apple_clpc_stop(void *data) } apple_clpc_ane_detach(clpc->ane); debugfs_remove_recursive(clpc->debugfs); + WRITE_ONCE(clpc->stopped, true); + atomic_set(&clpc->idle_armed, 0); + if (clpc->cpuhp_added) { + cpuhp_state_remove_instance_nocalls(apple_clpc_cpuhp_state, + &clpc->cpuhp_node); + clpc->cpuhp_added = false; + } apple_clpc_halt(clpc); /* The SMC keeps this mode after the driver's profile state is gone. */ mutex_lock(&clpc->sample_lock); @@ -1222,7 +1629,6 @@ static void apple_clpc_stop(void *data) for (i = 0; i < clpc->nr_clusters; i++) if (freq_qos_request_active(&clpc->clusters[i].max_qos)) freq_qos_remove_request(&clpc->clusters[i].max_qos); - of_node_put(clpc->smc_np); apple_clpc_free_clusters(clpc); } @@ -1238,13 +1644,20 @@ static int apple_clpc_policy_notify(struct notifier_block *nb, unsigned long eve struct cpufreq_policy *policy = data; unsigned int i; + if (event == CPUFREQ_CREATE_POLICY) { + if (!READ_ONCE(clpc->stopped)) + mod_delayed_work(system_freezable_power_efficient_wq, &clpc->work, 0); + return NOTIFY_OK; + } if (event != CPUFREQ_REMOVE_POLICY) return NOTIFY_DONE; guard(mutex)(&clpc->sample_lock); for (i = 0; i < clpc->nr_clusters; i++) - if (cpumask_test_cpu(clpc->clusters[i].policy_cpu, policy->related_cpus) && - freq_qos_request_active(&clpc->clusters[i].max_qos)) - freq_qos_remove_request(&clpc->clusters[i].max_qos); + if (cpumask_test_cpu(clpc->clusters[i].policy_cpu, policy->related_cpus)) { + if (freq_qos_request_active(&clpc->clusters[i].max_qos)) + freq_qos_remove_request(&clpc->clusters[i].max_qos); + clpc->clusters[i].max_khz = 0; + } if (clpc->ane_cpu < 0 || !cpumask_test_cpu(clpc->ane_cpu, policy->related_cpus)) return NOTIFY_OK; if (freq_qos_request_active(&clpc->ane_qos)) @@ -1300,7 +1713,7 @@ static int apple_clpc_send_high_power(struct apple_clpc *clpc, bool on) u8 rec[APPLE_CLPC_ZETM_SIZE] = { APPLE_CLPC_ZETM_TYPE, APPLE_CLPC_ZETM_VERSION }; int ret; - if (!apple_clpc_smc(clpc)) + if (!IS_ENABLED(CONFIG_MFD_MACSMC) || !apple_clpc_smc(clpc)) return -ENODEV; rec[2] = ++clpc->high_power_seq; put_unaligned_le32(on ? APPLE_CLPC_FLOAT_ONE : 0, rec + APPLE_CLPC_ZETM_HIGH_POWER); @@ -1333,6 +1746,7 @@ static int apple_clpc_profile_set(struct device *dev, enum platform_profile_opti { struct apple_clpc *clpc = dev_get_drvdata(dev); bool high_power = profile == PLATFORM_PROFILE_PERFORMANCE; + bool need_work; mutex_lock(&clpc->sample_lock); /* Performance is macOS's High Power mode; the other two are its Automatic. */ @@ -1346,10 +1760,19 @@ static int apple_clpc_profile_set(struct device *dev, enum platform_profile_opti } WRITE_ONCE(clpc->profile, profile); WRITE_ONCE(clpc->low_power, profile == PLATFORM_PROFILE_LOW_POWER); - /* The next sample applies it. */ + /* Apply profile ceilings right away so userspace sees the change immediately. */ clpc->power_next = jiffies; + if (!READ_ONCE(clpc->stopped) && clpc->low_power_khz) { + if (!cpumask_equal(clpc->covered, cpu_possible_mask)) + apple_clpc_find_clusters(clpc); + apple_clpc_profile_limit(clpc); + } + need_work = clpc->has_pmc || + (clpc->low_power_khz && clpc->low_power_mw && + profile == PLATFORM_PROFILE_LOW_POWER) || + !cpumask_equal(clpc->covered, cpu_possible_mask); mutex_unlock(&clpc->sample_lock); - if (!READ_ONCE(clpc->stopped)) + if (!READ_ONCE(clpc->stopped) && need_work) mod_delayed_work(system_freezable_power_efficient_wq, &clpc->work, 0); return 0; } @@ -1360,13 +1783,130 @@ static const struct platform_profile_ops apple_clpc_profile_ops = { .profile_set = apple_clpc_profile_set, }; +/* + * Fills @hw->gpu_busy from a DT matrix: APPLE_CLPC_RAILS rows of + * APPLE_CLPC_LEVELS states, each bounded by the compatible table's rail + * maximum (and the 4-bit PMC state field). + */ +static int apple_clpc_dt_map(struct apple_clpc_hw *hw, const u32 *cells, int n) +{ + u8 states[APPLE_CLPC_RAILS][APPLE_CLPC_LEVELS]; + unsigned int rail, level; + + if (n != APPLE_CLPC_RAILS * APPLE_CLPC_LEVELS) + return -EINVAL; + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) { + u32 top = max(hw->map[rail][APPLE_CLPC_LEVELS - 1], + hw->gpu[rail]); + + for (level = 0; level < APPLE_CLPC_LEVELS; level++) { + u32 state = cells[rail * APPLE_CLPC_LEVELS + level]; + + if (state > top || state > 15) + return -EINVAL; + states[rail][level] = state; + } + } + memcpy(hw->gpu_busy, states, sizeof(states)); + return 0; +} + +/* The busy shares from which reported GPU work gets the 2nd, 3rd and top column. */ +static int apple_clpc_dt_busy(struct apple_clpc_hw *hw, const u32 *cells, int n) +{ + if (n != 3 || cells[0] > cells[1] || cells[1] > cells[2] || cells[2] > 1000) + return -EINVAL; + hw->gpu_busy_mid = cells[0]; + hw->gpu_busy_high = cells[1]; + hw->gpu_busy_top = cells[2]; + return 0; +} + +/* + * Applies parsed DT GPU busy-share cells onto a copy of @soc. Any error in + * either property warns and leaves @soc unchanged so a malformed optional + * ladder never aborts CLPC probe. + */ +static bool apple_clpc_dt_apply(struct device *dev, + const struct apple_clpc_hw *soc, + struct apple_clpc_hw *out, + const u32 *states, int n_states, + const u32 *busy, int n_busy) +{ + int err; + + *out = *soc; + err = n_states < 0 ? n_states : apple_clpc_dt_map(out, states, n_states); + if (!err) + err = n_busy < 0 ? n_busy : apple_clpc_dt_busy(out, busy, n_busy); + if (err) { + dev_warn(dev, + "ignoring invalid GPU busy-share states in the device tree (%d)\n", + err); + *out = *soc; + return false; + } + return true; +} + +/* Reads up to @max cells of @name; returns how many, or an error. */ +static int apple_clpc_dt_cells(struct device_node *np, const char *name, + u32 *cells, int max) +{ + int n = of_property_count_u32_elems(np, name); + + if (n < 0) + return n; + if (n > max) + return -EOVERFLOW; + return of_property_read_u32_array(np, name, cells, n) ?: n; +} + +/* + * The compatible's table, with the GPU busy-share memory states the node + * gives (apple,pmc.yaml). Without those properties, or if they are malformed, + * the compatible's own table applies unchanged. + */ +static const struct apple_clpc_hw *apple_clpc_dt_hw(struct device *dev, + const struct apple_clpc_hw *soc) +{ + u32 states[APPLE_CLPC_RAILS * APPLE_CLPC_LEVELS]; + u32 busy[3]; + struct device_node *np = dev->of_node; + struct apple_clpc_hw copy, *hw; + int n_states, n_busy; + + if (!of_property_present(np, "apple,gpu-busy-memory-states") && + !of_property_present(np, "apple,gpu-busy-permille")) + return soc; + n_states = apple_clpc_dt_cells(np, "apple,gpu-busy-memory-states", + states, ARRAY_SIZE(states)); + n_busy = apple_clpc_dt_cells(np, "apple,gpu-busy-permille", + busy, ARRAY_SIZE(busy)); + if (!apple_clpc_dt_apply(dev, soc, ©, states, n_states, + busy, n_busy)) + return soc; + hw = devm_kmemdup(dev, ©, sizeof(copy), GFP_KERNEL); + if (!hw) + return ERR_PTR(-ENOMEM); + return hw; +} + +static void apple_clpc_put_smc_np(void *data) +{ + struct apple_clpc *clpc = data; + + of_node_put(clpc->smc_np); +} + static int apple_clpc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct device_node *gpu = NULL; struct apple_clpc *clpc; unsigned int rail, i; - bool high_power; + bool high_power, has_profile; + u32 mhz, mw; int ret; clpc = devm_kzalloc(dev, sizeof(*clpc), GFP_KERNEL); @@ -1375,83 +1915,150 @@ static int apple_clpc_probe(struct platform_device *pdev) clpc->dev = dev; clpc->pmc = dev->parent; - clpc->hw = of_device_get_match_data(dev); - /* T6040 firmware keeps GFX powered for its whole lifetime. A separate - * host publication/idle input, not that supplier state, drives demand; - * the T8132 and M5 (T8142) GPU drivers report through the same input. - * On T8140 the same input counts submissions for dense light work. - */ - if (clpc->hw->gpu_input || clpc->hw->gpu_dense) { - clpc->gpu = kzalloc_obj(*clpc->gpu); - if (!clpc->gpu) - return -ENOMEM; - kref_init(&clpc->gpu->ref); - spin_lock_init(&clpc->gpu->lock); - ret = devm_add_action_or_reset(dev, apple_clpc_gpu_owner_put, clpc->gpu); - if (ret) - return ret; - } - if (clpc->hw->ane[APPLE_CLPC_DCS] || clpc->hw->ane[APPLE_CLPC_SOC]) { - clpc->ane = kzalloc_obj(*clpc->ane); - if (!clpc->ane) - return -ENOMEM; - kref_init(&clpc->ane->ref); - spin_lock_init(&clpc->ane->lock); - ret = devm_add_action_or_reset(dev, apple_clpc_ane_owner_put, clpc->ane); - if (ret) - return ret; - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - clpc->ane_states[rail] = clpc->hw->ane[rail]; - } + clpc->hw = apple_clpc_dt_hw(dev, of_device_get_match_data(dev)); + if (IS_ERR(clpc->hw)) + return PTR_ERR(clpc->hw); + + clpc->has_pmc = clpc->pmc && apple_pmc_rail_count(clpc->pmc) > 0; clpc->ane_cpu = -ENODEV; clpc->ane_until = jiffies; - if (clpc->ane && clpc->hw->ane_cluster_khz && - of_machine_is_compatible(clpc->hw->ane_cluster_machine)) { - clpc->ane_cpu = apple_clpc_cluster_cpu(clpc->hw->ane_cluster); - if (clpc->ane_cpu >= 0) { - clpc->policy_nb.notifier_call = apple_clpc_policy_notify; - if (!cpufreq_register_notifier(&clpc->policy_nb, - CPUFREQ_POLICY_NOTIFIER)) { - clpc->policy_nb_added = true; - clpc->ane_cluster_khz = clpc->hw->ane_cluster_khz; + + /* + * The boot loader copies the ADT's Low Power mode CPU ceiling + * (pmgr/clpc cpu-low-power-frequency-max) into the node. Without it, + * a SoC's own value applies where it has one; otherwise low-power + * ceiling stays unavailable until the machine supplies it. + */ + if (!of_property_read_u32(dev->of_node, "apple,low-power-frequency-max-mhz", &mhz)) + clpc->low_power_khz = mhz * 1000; + else + clpc->low_power_khz = clpc->hw->low_power_khz; + if (!of_property_read_u32(dev->of_node, "apple,low-power-mw", &mw)) + clpc->low_power_mw = mw; + else + clpc->low_power_mw = clpc->hw->low_power_mw; + /* + * The board DT says whether the machine has High Power mode: then the + * performance profile tells the SMC that it is on (the zETM record). + * A machine with High Power mode and no low-power ceiling still gets + * the platform profile, named "apple-smc" so that userspace keeps its + * own low-power CPU budget. + */ + high_power = of_property_read_bool(dev->of_node, "apple,high-power-mode"); + /* + * A DTB from before the property (the ESP copy can lag the kernel) + * keeps High Power mode where this table already gave it. + */ + if (!high_power && clpc->hw->high_power_machine) + high_power = of_machine_is_compatible(clpc->hw->high_power_machine); + if ((clpc->low_power_khz || high_power) && + IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE)) { + /* + * The SMC is optional: without it (no apple,smc phandle, or a + * kernel without the SMC driver) the low-power profile has only + * its ceiling and there is no High Power mode. + */ + if (IS_ENABLED(CONFIG_MFD_MACSMC)) { + clpc->smc_np = of_parse_phandle(dev->of_node, "apple,smc", 0); + if (clpc->smc_np) { + ret = devm_add_action_or_reset(dev, apple_clpc_put_smc_np, clpc); + if (ret) + return ret; } } - if (!clpc->ane_cluster_khz) - dev_dbg(dev, "no ANE cluster floor (cpu-map cluster%u)\n", - clpc->hw->ane_cluster); + clpc->high_power = clpc->smc_np && high_power; } - /* The property is optional: without it, CPU demand alone sets the floors. */ - if (clpc->hw->gpu_demand) - gpu = of_parse_phandle(dev->of_node, "apple,gpu-power-state", 0); - if (gpu) { - ret = of_property_read_u32(gpu, "reg", &clpc->gpu_offset); - clpc->gpu_pmgr = syscon_node_to_regmap(gpu->parent); - of_node_put(gpu); + /* High Power mode alone needs the SMC; without it there is no profile. */ + has_profile = (clpc->low_power_khz || clpc->high_power) && + IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE); + if (!clpc->has_pmc && !has_profile) + return dev_err_probe(dev, -ENODEV, + "parent is not a PMC and no platform profile is available\n"); + + if (clpc->has_pmc) { + apple_clpc_cpu_top_init(clpc); + /* T6040 firmware keeps GFX powered for its whole lifetime. A separate + * host publication/idle input, not that supplier state, drives demand; + * the T8132 and M5 (T8142) GPU drivers report through the same input. + * On T8140 the same input counts submissions for dense light work. + */ + if (clpc->hw->gpu_input || clpc->hw->gpu_dense) { + clpc->gpu = kzalloc_obj(*clpc->gpu); + if (!clpc->gpu) + return -ENOMEM; + kref_init(&clpc->gpu->ref); + spin_lock_init(&clpc->gpu->lock); + ret = devm_add_action_or_reset(dev, apple_clpc_gpu_owner_put, clpc->gpu); + if (ret) + return ret; + } + if (clpc->hw->ane[APPLE_CLPC_DCS] || clpc->hw->ane[APPLE_CLPC_SOC]) { + clpc->ane = kzalloc_obj(*clpc->ane); + if (!clpc->ane) + return -ENOMEM; + kref_init(&clpc->ane->ref); + spin_lock_init(&clpc->ane->lock); + ret = devm_add_action_or_reset(dev, apple_clpc_ane_owner_put, clpc->ane); + if (ret) + return ret; + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + clpc->ane_states[rail] = clpc->hw->ane[rail]; + } + if (clpc->ane && clpc->hw->ane_cluster_khz && + of_machine_is_compatible(clpc->hw->ane_cluster_machine)) { + clpc->ane_cpu = apple_clpc_cluster_cpu(clpc->hw->ane_cluster); + if (clpc->ane_cpu >= 0) { + clpc->policy_nb.notifier_call = apple_clpc_policy_notify; + if (!cpufreq_register_notifier(&clpc->policy_nb, + CPUFREQ_POLICY_NOTIFIER)) { + clpc->policy_nb_added = true; + clpc->ane_cluster_khz = clpc->hw->ane_cluster_khz; + } + } + if (!clpc->ane_cluster_khz) + dev_dbg(dev, "no ANE cluster floor (cpu-map cluster%u)\n", + clpc->hw->ane_cluster); + } + /* The property is optional: without it, CPU demand alone sets the floors. */ + if (clpc->hw->gpu_demand) + gpu = of_parse_phandle(dev->of_node, "apple,gpu-power-state", 0); + if (gpu) { + ret = of_property_read_u32(gpu, "reg", &clpc->gpu_offset); + clpc->gpu_pmgr = syscon_node_to_regmap(gpu->parent); + of_node_put(gpu); + if (ret) + return dev_err_probe(dev, ret, "graphics power state has no reg\n"); + if (IS_ERR(clpc->gpu_pmgr)) + return dev_err_probe(dev, PTR_ERR(clpc->gpu_pmgr), + "no regmap for the graphics power state\n"); + } + + ret = of_property_read_u32(dev->of_node, "reg", &clpc->agent); if (ret) - return dev_err_probe(dev, ret, "graphics power state has no reg\n"); - if (IS_ERR(clpc->gpu_pmgr)) - return dev_err_probe(dev, PTR_ERR(clpc->gpu_pmgr), - "no regmap for the graphics power state\n"); - } - if (!apple_pmc_rail_count(clpc->pmc)) - return dev_err_probe(dev, -ENODEV, "parent is not a PMC\n"); + return dev_err_probe(dev, ret, "missing voter agent\n"); - ret = of_property_read_u32(dev->of_node, "reg", &clpc->agent); - if (ret) - return dev_err_probe(dev, ret, "missing voter agent\n"); + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) { + if (clpc->hw->rail[rail] >= apple_pmc_rail_count(clpc->pmc)) + return -EINVAL; + clpc->mask |= APPLE_PMC_RAIL_MASK(clpc->hw->rail[rail]); + } - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) { - if (clpc->hw->rail[rail] >= apple_pmc_rail_count(clpc->pmc)) - return -EINVAL; - clpc->mask |= APPLE_PMC_RAIL_MASK(clpc->hw->rail[rail]); - } + clpc->idle = devm_kcalloc(dev, nr_cpu_ids, sizeof(*clpc->idle), + GFP_KERNEL); + clpc->wall = devm_kcalloc(dev, nr_cpu_ids, sizeof(*clpc->wall), + GFP_KERNEL); + if (!clpc->idle || !clpc->wall) + return -ENOMEM; - clpc->idle = devm_kcalloc(dev, nr_cpu_ids, sizeof(*clpc->idle), - GFP_KERNEL); - clpc->wall = devm_kcalloc(dev, nr_cpu_ids, sizeof(*clpc->wall), - GFP_KERNEL); - if (!clpc->idle || !clpc->wall) - return -ENOMEM; + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + if (!apple_pmc_voter_enabled(clpc->pmc, clpc->agent, + clpc->hw->rail[rail])) + dev_warn(dev, "voter agent %u is not enabled on rail %u\n", + clpc->agent, clpc->hw->rail[rail]); + + clpc->saved_floor = apple_pmc_floor_read(clpc->pmc, clpc->agent) & + clpc->mask; + } for (i = 0; i < APPLE_CLPC_MAX_CLUSTERS; i++) { if (!zalloc_cpumask_var(&clpc->clusters[i].cpus, GFP_KERNEL)) { @@ -1464,19 +2071,39 @@ static int apple_clpc_probe(struct platform_device *pdev) return -ENOMEM; } - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - if (!apple_pmc_voter_enabled(clpc->pmc, clpc->agent, - clpc->hw->rail[rail])) - dev_warn(dev, "voter agent %u is not enabled on rail %u\n", - clpc->agent, clpc->hw->rail[rail]); - - clpc->saved_floor = apple_pmc_floor_read(clpc->pmc, clpc->agent) & - clpc->mask; apple_clpc_find_clusters(clpc); clpc->next_scan = jiffies + HZ; mutex_init(&clpc->sample_lock); + mutex_init(&clpc->idle_lock); + cpumask_clear(&clpc->idle_online_cpus); INIT_DELAYED_WORK(&clpc->work, apple_clpc_work); INIT_DEFERRABLE_WORK(&clpc->idle_work, apple_clpc_idle_work); + if (clpc->has_pmc && clpc->hw->idle_on_time) { + unsigned int cpu; + + clpc->idle_timers = devm_alloc_percpu(dev, struct apple_clpc_idle_timer); + if (!clpc->idle_timers) { + apple_clpc_free_clusters(clpc); + return -ENOMEM; + } + for_each_possible_cpu(cpu) { + struct apple_clpc_idle_timer *t = + per_cpu_ptr(clpc->idle_timers, cpu); + + t->clpc = clpc; + timer_setup(&t->timer, apple_clpc_idle_timer_fn, + TIMER_DEFERRABLE | TIMER_PINNED); + } + if (apple_clpc_cpuhp_state > 0) { + ret = cpuhp_state_add_instance(apple_clpc_cpuhp_state, + &clpc->cpuhp_node); + if (ret) { + apple_clpc_free_clusters(clpc); + return ret; + } + clpc->cpuhp_added = true; + } + } /* Sample at a cold publication only where that publication is the demand. * Dense counting needs no extra sample, and one taken as each frame of a * frame-paced client starts finds its CPUs busy and votes their fabric. @@ -1504,30 +2131,10 @@ static int apple_clpc_probe(struct platform_device *pdev) clpc->profile = PLATFORM_PROFILE_BALANCED; clpc->power_next = jiffies; - /* - * The board DT says whether the machine has High Power mode: then the - * performance profile tells the SMC that it is on (the zETM record). - * A machine with High Power mode and no low-power ceiling still gets - * the platform profile, named "apple-smc" so that userspace keeps its - * own low-power CPU budget. - */ - high_power = of_property_read_bool(dev->of_node, "apple,high-power-mode"); - /* - * A DTB from before the property (the ESP copy can lag the kernel) - * keeps High Power mode where this table already gave it. - */ - if (!high_power && clpc->hw->high_power_machine) - high_power = of_machine_is_compatible(clpc->hw->high_power_machine); - if ((clpc->hw->low_power_khz || high_power) && IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE)) { - /* The SMC is optional: without it the low-power profile has only its ceiling. */ - clpc->smc_np = of_parse_phandle(dev->of_node, "apple,smc", 0); - clpc->high_power = clpc->smc_np && high_power; - } - /* High Power mode alone needs the SMC; without it there is no profile. */ - if ((clpc->hw->low_power_khz || clpc->high_power) && IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE)) { + if (has_profile) { struct device *ppdev; - if (clpc->hw->low_power_khz && !clpc->policy_nb_added) { + if (clpc->low_power_khz && !clpc->policy_nb_added) { clpc->policy_nb.notifier_call = apple_clpc_policy_notify; clpc->policy_nb_added = !cpufreq_register_notifier(&clpc->policy_nb, CPUFREQ_POLICY_NOTIFIER); @@ -1536,16 +2143,23 @@ static int apple_clpc_probe(struct platform_device *pdev) * "apple-clpc" budgets the low-power profile itself; "apple-smc" * only carries High Power mode, and userspace keeps the CPU budget. */ - ppdev = devm_platform_profile_register(dev, clpc->hw->low_power_khz ? "apple-clpc" : - "apple-smc", clpc, &apple_clpc_profile_ops); - if (IS_ERR(ppdev)) + ppdev = devm_platform_profile_register(dev, + clpc->low_power_khz ? + "apple-clpc" : "apple-smc", + clpc, &apple_clpc_profile_ops); + if (IS_ERR(ppdev)) { + if (!clpc->has_pmc) + return PTR_ERR(ppdev); dev_warn(dev, "no platform profile: %pe\n", ppdev); + } } mutex_lock(&apple_clpc_clients_lock); platform_set_drvdata(pdev, clpc); mutex_unlock(&apple_clpc_clients_lock); + mutex_lock(&clpc->sample_lock); apple_clpc_queue(clpc, true); + mutex_unlock(&clpc->sample_lock); return 0; } @@ -1565,10 +2179,14 @@ static int apple_clpc_resume(struct device *dev) struct apple_clpc *clpc = dev_get_drvdata(dev); unsigned int cpu; - for_each_possible_cpu(cpu) - clpc->wall[cpu] = 0; + mutex_lock(&clpc->sample_lock); + if (clpc->wall) + for_each_possible_cpu(cpu) + clpc->wall[cpu] = 0; + clpc->power_next = jiffies; WRITE_ONCE(clpc->stopped, false); apple_clpc_queue(clpc, true); + mutex_unlock(&clpc->sample_lock); return 0; } @@ -1734,8 +2352,40 @@ static const struct apple_clpc_hw apple_clpc_hw_t8142 = { [APPLE_CLPC_SOC] = { 1, 2, 3, 4 }, }, .gpu_input = true, + /* + * Measured ANE demand (J813, H17; J815/J704 share the compatible and + * are untested): DCS 7 is the top DCS state; fabric 3 is a measured + * policy choice below the top fabric state (4). With the CPU pinned at + * minimum frequency so ANE owns the floor, firmware time drops from + * (0, 0) -> (7, 2) -> (7, 3) across denoise-640 (16.5 -> 11.7 -> 10.3 + * ms; cold SLC 20.0 -> 11.7 -> 10.4 ms), unet-320 conv (3.94 -> 2.79 + * -> 2.46 ms), and mm-512x2048 GEMM (627 -> 493 -> 420 us; cold SLC + * 782 -> 560 -> 526 us). Fabric 4 gives no further speedup on any of + * them and adds 71-121 mW of system power (4.28 -> 4.41 W on + * denoise-640, 3.94 -> 4.04 W on unet-320, 3.95 -> 4.02 W on + * mm-512x2048). + */ + .ane = { [APPLE_CLPC_DCS] = 7, [APPLE_CLPC_SOC] = 3 }, + /* + * With the engine AXI2AF bridge tunables applied, pure ANE execution + * time on J813 also tracks the P-cluster frequency (cpu-map cluster1), + * independent of which cluster hosts the submitting thread (pinned to + * an E-core with DCS 7 / SOC 3, unet-320 firmware report_done drops + * from 660.5 us with no P-cluster floor to 350.7 us at 4176 MHz, + * 4.49 W, with no further gain at 4464 MHz, 5.31 W). + */ + .ane_cluster = 1, + .ane_cluster_khz = 4176000, + .ane_cluster_machine = "apple,t8142", }; +/* + * Standalone CLPC node without a PMC voter parent (for example T8112): no + * memory/fabric floor votes; platform profiles are registered only when the + * machine supplies apple,low-power-frequency-max-mhz or apple,high-power-mode. + */ +static const struct apple_clpc_hw apple_clpc_hw_generic = {}; + #if IS_BUILTIN(CONFIG_KUNIT) && !defined(MODULE) #include #include @@ -1932,6 +2582,8 @@ static void apple_clpc_t6041_policy_test(struct kunit *test) apple_clpc_gpu_put(gpu); } +static const struct apple_clpc_hw apple_clpc_hw_t6050; + static void apple_clpc_ane_demand_hold_test(struct kunit *test) { struct apple_clpc_ane ane = {}; @@ -1974,6 +2626,32 @@ static void apple_clpc_ane_demand_hold_test(struct kunit *test) /* T6040 holds its top qualified DCS and fabric states for the ANE. */ KUNIT_EXPECT_EQ(test, apple_clpc_hw_t6040.ane[APPLE_CLPC_DCS], 5); KUNIT_EXPECT_EQ(test, apple_clpc_hw_t6040.ane[APPLE_CLPC_SOC], 2); + /* T8142 holds DCS 7 and fabric 3 while ANE work is in flight. */ + KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8142.ane[APPLE_CLPC_DCS], 7); + KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8142.ane[APPLE_CLPC_SOC], 3); + clpc->hw = &apple_clpc_hw_t8142; + clpc->ane_states[APPLE_CLPC_DCS] = clpc->hw->ane[APPLE_CLPC_DCS]; + clpc->ane_states[APPLE_CLPC_SOC] = clpc->hw->ane[APPLE_CLPC_SOC]; + memset(demand, 0, sizeof(demand)); + apple_clpc_ane_set_active(&ane, true); + KUNIT_EXPECT_TRUE(test, apple_clpc_ane_input_demand(clpc, demand)); + KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_DCS], 7u); + KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_SOC], 3u); + apple_clpc_ane_set_active(&ane, false); + /* T6050 holds DCS 6 and fabric 2 while ANE work is in flight. */ + KUNIT_EXPECT_EQ(test, apple_clpc_hw_t6050.ane[APPLE_CLPC_DCS], 6); + KUNIT_EXPECT_EQ(test, apple_clpc_hw_t6050.ane[APPLE_CLPC_SOC], 2); + clpc->hw = &apple_clpc_hw_t6050; + clpc->ane_states[APPLE_CLPC_DCS] = clpc->hw->ane[APPLE_CLPC_DCS]; + clpc->ane_states[APPLE_CLPC_SOC] = clpc->hw->ane[APPLE_CLPC_SOC]; + memset(demand, 0, sizeof(demand)); + apple_clpc_ane_set_active(&ane, true); + KUNIT_EXPECT_TRUE(test, apple_clpc_ane_input_demand(clpc, demand)); + KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_DCS], 6u); + KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_SOC], 2u); + apple_clpc_ane_set_active(&ane, false); + memset(demand, 0, sizeof(demand)); + KUNIT_EXPECT_FALSE(test, apple_clpc_ane_input_demand(clpc, demand)); } static void apple_clpc_ane_cluster_test(struct kunit *test) @@ -1993,6 +2671,8 @@ static void apple_clpc_ane_cluster_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, time_before(now + msecs_to_jiffies(APPLE_CLPC_HOLD_MS), clpc->ane_until)); KUNIT_EXPECT_EQ(test, apple_clpc_hw_t6040.ane_cluster, 2u); + KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8142.ane_cluster, 1u); + KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8142.ane_cluster_khz, 4176000u); KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8140.ane_cluster_khz, 0u); } @@ -2037,7 +2717,6 @@ static void apple_clpc_ane_no_provider_test(struct kunit *test) KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_DCS], 0u); KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_SOC], 0u); KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8132.ane[APPLE_CLPC_DCS], 0); - KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8142.ane[APPLE_CLPC_DCS], 0); } static void apple_clpc_ane_wake_removal_test(struct kunit *test) @@ -2066,7 +2745,171 @@ static void apple_clpc_ane_wake_removal_test(struct kunit *test) apple_clpc_ane_put(ane); } +static void apple_clpc_cpu_busy_floor_test(struct kunit *test) +{ + struct apple_clpc *clpc = kunit_kzalloc(test, sizeof(*clpc), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, clpc); + clpc->hw = &apple_clpc_hw_t6050; + + /* Without the board override, the top quarter uses the SoC map. */ + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_DCS, 3), 5u); + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_SOC, 3), 2u); + + /* With the override active outside low-power, only the top quarter changes. */ + clpc->cpu_top[APPLE_CLPC_DCS] = 6; + clpc->cpu_top[APPLE_CLPC_SOC] = 3; + clpc->cpu_top_set = true; + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_DCS, 2), 5u); + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_SOC, 2), 2u); + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_DCS, 3), 6u); + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_SOC, 3), 3u); + + /* Under the low-power platform profile, fall back to the SoC map. */ + WRITE_ONCE(clpc->low_power, true); + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_DCS, 3), 5u); + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_SOC, 3), 2u); +} + +static void apple_clpc_low_power_roundup_test(struct kunit *test) +{ + /* M4 Pro P-cluster OPPs around the 2808 MHz ADT ceiling (J616s). */ + struct cpufreq_frequency_table p_table[] = { + { .frequency = 2592000 }, + { .frequency = 2868000 }, + { .frequency = 3132000 }, + { .frequency = 4512000 }, + { .frequency = CPUFREQ_TABLE_END }, + }; + struct cpufreq_frequency_table e_table[] = { + { .frequency = 1020000 }, + { .frequency = 2592000 }, + { .frequency = CPUFREQ_TABLE_END }, + }; + /* T8112 (J473/J413) E and P cluster OPPs around the 1960 MHz ADT ceiling. */ + struct cpufreq_frequency_table t8112_e_table[] = { + { .frequency = 600000 }, + { .frequency = 1752000 }, + { .frequency = 2004000 }, + { .frequency = 2424000 }, + { .frequency = CPUFREQ_TABLE_END }, + }; + struct cpufreq_frequency_table t8112_p_table[] = { + { .frequency = 660000 }, + { .frequency = 1704000 }, + { .frequency = 1968000 }, + { .frequency = 3204000 }, + { .frequency = CPUFREQ_TABLE_END }, + }; + struct cpufreq_policy p_pol = { + .freq_table = p_table, + .cpuinfo = { .min_freq = 2592000, .max_freq = 4512000 }, + }; + struct cpufreq_policy e_pol = { + .freq_table = e_table, + .cpuinfo = { .min_freq = 1020000, .max_freq = 2592000 }, + }; + struct cpufreq_policy t8112_e_pol = { + .freq_table = t8112_e_table, + .cpuinfo = { .min_freq = 600000, .max_freq = 2424000 }, + }; + struct cpufreq_policy t8112_p_pol = { + .freq_table = t8112_p_table, + .cpuinfo = { .min_freq = 660000, .max_freq = 3204000 }, + }; + struct cpufreq_policy no_table_pol = { + .freq_table = NULL, + .cpuinfo = { .min_freq = 660000, .max_freq = 3204000 }, + }; + + /* Explicit ceiling rounds UP to the first OPP >= 2808 MHz (2868 MHz). */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&p_pol, 2808000), + 2868000u); + /* Slower cluster below 2808 MHz stays at its max (2592 MHz). */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&e_pol, 2808000), + 2592000u); + /* T8112 1960 MHz ADT ceiling rounds up to 2004 MHz (E) and 1968 MHz (P). */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&t8112_e_pol, 1960000), + 2004000u); + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&t8112_p_pol, 1960000), + 1968000u); + /* Missing machine ceiling (0) must not invent a fallback cap. */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&t8112_p_pol, 0), + 3204000u); + /* NULL freq_table must not dereference NULL; stays at policy max. */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&no_table_pol, 1960000), + 3204000u); +} + +static void apple_clpc_profile_ops_test(struct kunit *test) +{ + struct apple_clpc *clpc = kunit_kzalloc(test, sizeof(*clpc), GFP_KERNEL); + struct device dev = {}; + unsigned long choices = 0; + enum platform_profile_option prof = PLATFORM_PROFILE_BALANCED; + + KUNIT_ASSERT_NOT_NULL(test, clpc); + KUNIT_ASSERT_TRUE(test, zalloc_cpumask_var(&clpc->covered, GFP_KERNEL)); + cpumask_copy(clpc->covered, cpu_possible_mask); + mutex_init(&clpc->sample_lock); + INIT_DELAYED_WORK(&clpc->work, apple_clpc_work); + INIT_DEFERRABLE_WORK(&clpc->idle_work, apple_clpc_idle_work); + clpc->hw = &apple_clpc_hw_generic; + clpc->low_power_khz = 1960000; + clpc->has_pmc = false; + clpc->stopped = true; + clpc->profile = PLATFORM_PROFILE_BALANCED; + dev_set_drvdata(&dev, clpc); + + /* Standalone generic table carries no hardcoded ceiling or power cap. */ + KUNIT_EXPECT_EQ(test, apple_clpc_hw_generic.low_power_khz, 0u); + KUNIT_EXPECT_EQ(test, apple_clpc_hw_generic.low_power_mw, 0u); + + KUNIT_EXPECT_EQ(test, apple_clpc_profile_probe(clpc, &choices), 0); + KUNIT_EXPECT_TRUE(test, test_bit(PLATFORM_PROFILE_LOW_POWER, &choices)); + KUNIT_EXPECT_TRUE(test, test_bit(PLATFORM_PROFILE_BALANCED, &choices)); + KUNIT_EXPECT_TRUE(test, test_bit(PLATFORM_PROFILE_PERFORMANCE, &choices)); + + KUNIT_EXPECT_EQ(test, apple_clpc_profile_set(&dev, PLATFORM_PROFILE_LOW_POWER), 0); + KUNIT_EXPECT_EQ(test, apple_clpc_profile_get(&dev, &prof), 0); + KUNIT_EXPECT_EQ(test, prof, PLATFORM_PROFILE_LOW_POWER); + KUNIT_EXPECT_TRUE(test, clpc->low_power); + + /* Static standalone ceiling (low_power_mw == 0) must not queue periodic work. */ + WRITE_ONCE(clpc->stopped, false); + apple_clpc_queue(clpc, true); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&clpc->work)); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&clpc->idle_work)); + + /* With a package power target, standalone low-power schedules 100 ms polling. */ + clpc->low_power_mw = 15000; + apple_clpc_queue(clpc, true); + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&clpc->work)); + WRITE_ONCE(clpc->stopped, true); + cancel_delayed_work_sync(&clpc->work); + clpc->low_power_mw = 0; + + KUNIT_EXPECT_EQ(test, apple_clpc_profile_set(&dev, PLATFORM_PROFILE_PERFORMANCE), 0); + KUNIT_EXPECT_EQ(test, apple_clpc_profile_get(&dev, &prof), 0); + KUNIT_EXPECT_EQ(test, prof, PLATFORM_PROFILE_PERFORMANCE); + KUNIT_EXPECT_FALSE(test, clpc->low_power); + + KUNIT_EXPECT_EQ(test, apple_clpc_profile_set(&dev, PLATFORM_PROFILE_BALANCED), 0); + KUNIT_EXPECT_EQ(test, apple_clpc_profile_get(&dev, &prof), 0); + KUNIT_EXPECT_EQ(test, prof, PLATFORM_PROFILE_BALANCED); + KUNIT_EXPECT_FALSE(test, clpc->low_power); + + free_cpumask_var(clpc->covered); +} + static struct kunit_case apple_clpc_cases[] = { + KUNIT_CASE(apple_clpc_cpu_busy_floor_test), KUNIT_CASE(apple_clpc_ane_demand_hold_test), KUNIT_CASE(apple_clpc_ane_states_test), KUNIT_CASE(apple_clpc_ane_cluster_test), @@ -2078,6 +2921,8 @@ static struct kunit_case apple_clpc_cases[] = { KUNIT_CASE(apple_clpc_gpu_cold_wake_test), KUNIT_CASE(apple_clpc_gpu_request_lifetime_test), KUNIT_CASE(apple_clpc_gpu_provider_removal_test), + KUNIT_CASE(apple_clpc_low_power_roundup_test), + KUNIT_CASE(apple_clpc_profile_ops_test), {} }; static struct kunit_suite apple_clpc_suite = { @@ -2085,15 +2930,167 @@ static struct kunit_suite apple_clpc_suite = { .test_cases = apple_clpc_cases, }; kunit_test_suite(apple_clpc_suite); + +/* A cpufreq table out of order, with an invalid entry, as a driver may give it. */ +static struct cpufreq_policy *apple_clpc_test_policy(struct kunit *test) +{ + static const unsigned int khz[] = { + 600000, CPUFREQ_ENTRY_INVALID, 1200000, 2000000, 1500000, + }; + struct cpufreq_frequency_table *table; + struct cpufreq_policy *policy; + unsigned int i; + + policy = kunit_kzalloc(test, sizeof(*policy), GFP_KERNEL); + table = kunit_kcalloc(test, ARRAY_SIZE(khz) + 1, sizeof(*table), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, policy); + KUNIT_ASSERT_NOT_NULL(test, table); + for (i = 0; i < ARRAY_SIZE(khz); i++) + table[i].frequency = khz[i]; + table[i].frequency = CPUFREQ_TABLE_END; + policy->freq_table = table; + policy->cpuinfo.max_freq = 2000000; + return policy; +} + +static void apple_clpc_step_khz_test(struct kunit *test) +{ + struct cpufreq_policy *policy = apple_clpc_test_policy(test); + + /* One table step either way, whatever the table order. */ + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1200000, true), 1500000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1500000, true), 2000000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1500000, false), 1200000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1200000, false), 600000u); + /* Off the table: the nearest entry in that direction. */ + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1300000, true), 1500000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1300000, false), 1200000u); + /* + * No step past either end: @khz back. The invalid entry sits above + * every real one, so these up steps are the ones that would pick it. + */ + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 2000000, true), 2000000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 600000, false), 600000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 2100000, true), 2100000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 0, false), 0u); + + /* + * The lookup apple_clpc_profile_limit() makes for the low-power top: the + * first entry at or above low_power_khz, so a value between two entries + * rounds up and an exact entry is kept. Its max_freq fallback is not + * covered here. + */ + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1400000 - 1, true), 1500000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1500000 - 1, true), 1500000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 600000 - 1, true), 600000u); + /* Above the table nothing is found and @khz comes back. */ + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 2100000 - 1, true), 2100000u - 1); +} + +static void apple_clpc_steps_first_test(struct kunit *test) +{ + /* Down: the higher ceiling first; on a tie, the faster cluster. */ + KUNIT_EXPECT_TRUE(test, apple_clpc_steps_first(2000000, 2000000, 1500000, 3000000, false)); + KUNIT_EXPECT_FALSE(test, apple_clpc_steps_first(1500000, 3000000, 2000000, 2000000, false)); + KUNIT_EXPECT_TRUE(test, apple_clpc_steps_first(1500000, 3000000, 1500000, 2000000, false)); + KUNIT_EXPECT_FALSE(test, apple_clpc_steps_first(1500000, 2000000, 1500000, 3000000, false)); + + /* Up: the lower ceiling first; on a tie, the slower cluster. */ + KUNIT_EXPECT_TRUE(test, apple_clpc_steps_first(1500000, 3000000, 2000000, 2000000, true)); + KUNIT_EXPECT_FALSE(test, apple_clpc_steps_first(2000000, 2000000, 1500000, 3000000, true)); + KUNIT_EXPECT_TRUE(test, apple_clpc_steps_first(1500000, 2000000, 1500000, 3000000, true)); + KUNIT_EXPECT_FALSE(test, apple_clpc_steps_first(1500000, 3000000, 1500000, 2000000, true)); + + /* Identical clusters: the one already picked keeps the step. */ + KUNIT_EXPECT_FALSE(test, apple_clpc_steps_first(1500000, 2000000, 1500000, 2000000, true)); + KUNIT_EXPECT_FALSE(test, apple_clpc_steps_first(1500000, 2000000, 1500000, 2000000, false)); +} + +static void apple_clpc_vote_test(struct kunit *test) +{ + unsigned long hold = msecs_to_jiffies(APPLE_CLPC_HOLD_MS); + /* + * Start so that the hold deadline wraps to 0 while its last held + * sample is still ULONG_MAX: a compare that is not wrap-safe drops + * the vote early there. + */ + unsigned long t0 = ULONG_MAX - (hold - 1); + struct apple_clpc_vote vote = {}; + + KUNIT_ASSERT_GT(test, hold, 1ul); + KUNIT_ASSERT_EQ(test, t0 + hold - 1, ULONG_MAX); + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 0, t0), 0u); + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 5, t0), 5u); + /* No demand: the state holds for APPLE_CLPC_HOLD_MS, then drops. */ + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 0, t0 + hold - 1), 5u); + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 0, t0 + hold), 0u); + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 0, t0 + 2 * hold), 0u); + + /* A new demand replaces the state at once, down as well as up. */ + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 7, t0 + 2 * hold), 7u); + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 2, t0 + 2 * hold + 1), 2u); + /* and restarts the hold. */ + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 0, t0 + 3 * hold), 2u); + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 0, t0 + 3 * hold + 1), 0u); +} + +static void apple_clpc_floor_test(struct kunit *test) +{ + struct apple_clpc *clpc = kunit_kzalloc(test, sizeof(*clpc), GFP_KERNEL); + struct apple_clpc_hw *hw = kunit_kzalloc(test, sizeof(*hw), GFP_KERNEL); + unsigned int state[APPLE_CLPC_RAILS] = {}; + + KUNIT_ASSERT_NOT_NULL(test, clpc); + KUNIT_ASSERT_NOT_NULL(test, hw); + clpc->hw = hw; + + /* Each rail's state in its own nibble of the PMC floor word. */ + hw->rail[APPLE_CLPC_DCS] = 0; + hw->rail[APPLE_CLPC_SOC] = 1; + KUNIT_EXPECT_EQ(test, apple_clpc_floor(clpc, state), 0u); + state[APPLE_CLPC_DCS] = 5; + state[APPLE_CLPC_SOC] = 3; + KUNIT_EXPECT_EQ(test, apple_clpc_floor(clpc, state), 0x35u); + + /* The rail numbers come from the table, not the rail order. */ + hw->rail[APPLE_CLPC_DCS] = 2; + hw->rail[APPLE_CLPC_SOC] = 0; + KUNIT_EXPECT_EQ(test, apple_clpc_floor(clpc, state), 0x503u); + + /* A state wider than a nibble cannot spill into another rail. */ + state[APPLE_CLPC_DCS] = 0x1f; + state[APPLE_CLPC_SOC] = 0x10; + KUNIT_EXPECT_EQ(test, apple_clpc_floor(clpc, state), 0xf00u); +} + +static struct kunit_case apple_clpc_policy_cases[] = { + KUNIT_CASE(apple_clpc_step_khz_test), + KUNIT_CASE(apple_clpc_steps_first_test), + KUNIT_CASE(apple_clpc_vote_test), + KUNIT_CASE(apple_clpc_floor_test), + {} +}; +static struct kunit_suite apple_clpc_policy_suite = { + .name = "apple-clpc-policy", + .test_cases = apple_clpc_policy_cases, +}; +kunit_test_suite(apple_clpc_policy_suite); #endif -/* T8152: DCS states 0-7 and fabric states 0-4. */ +/* + * T8152: DCS states 0-7 and fabric states 0-4. The G18 GPU driver reports its + * work in flight, as on T8142, and gets the top of the map while it has some. + * Without that input only busy CPU clusters raised the floor: on the J873g a + * GPU-bound render ran 34% faster with it (783 against 585 frames/s), and + * before, the GPU ran faster the more CPU time its own job waits used. + */ static const struct apple_clpc_hw apple_clpc_hw_t8152 = { .rail = { [APPLE_CLPC_DCS] = 0, [APPLE_CLPC_SOC] = 1 }, .map = { [APPLE_CLPC_DCS] = { 2, 4, 6, 7 }, [APPLE_CLPC_SOC] = { 1, 2, 3, 4 }, }, + .gpu_input = true, }; /* @@ -2130,6 +3127,14 @@ static const struct apple_clpc_hw apple_clpc_hw_t6050 = { [APPLE_CLPC_SOC] = { 1, 2, 2, 2 }, }, .gpu = { [APPLE_CLPC_DCS] = 6, [APPLE_CLPC_SOC] = 2 }, + /* + * ANE demand, measured on J775c (M5 Max, H17): DCS 6 and fabric 2, the + * top states this table already uses. unet-320 (8 tasks, 200 runs) + * host p50 is 5504 us with no ANE floor and 2551 us at (6, 2); (6, 3) + * measured 2536 us, the same within run-to-run spread, so fabric stays + * at 2. + */ + .ane = { [APPLE_CLPC_DCS] = 6, [APPLE_CLPC_SOC] = 2 }, .sustain = 3, .gpu_input = true, .idle_on_time = true, @@ -2150,6 +3155,7 @@ static const struct of_device_id apple_clpc_of_match[] = { { .compatible = "apple,t8152-clpc", .data = &apple_clpc_hw_t8152 }, { .compatible = "apple,t6041-max-clpc", .data = &apple_clpc_hw_t6041 }, { .compatible = "apple,t6041-clpc", .data = &apple_clpc_hw_t6040 }, + { .compatible = "apple,clpc", .data = &apple_clpc_hw_generic }, {} }; MODULE_DEVICE_TABLE(of, apple_clpc_of_match); @@ -2162,7 +3168,36 @@ static struct platform_driver apple_clpc_driver = { .pm = pm_sleep_ptr(&apple_clpc_pm_ops), }, }; -module_platform_driver(apple_clpc_driver); +static int __init apple_clpc_driver_init(void) +{ + int ret; + + ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, + "soc/apple/clpc:online", + apple_clpc_cpu_online, + apple_clpc_cpu_down); + if (ret < 0) + return ret; + apple_clpc_cpuhp_state = ret; + + ret = platform_driver_register(&apple_clpc_driver); + if (ret) { + cpuhp_remove_multi_state(apple_clpc_cpuhp_state); + apple_clpc_cpuhp_state = 0; + } + return ret; +} +module_init(apple_clpc_driver_init); + +static void __exit apple_clpc_driver_exit(void) +{ + platform_driver_unregister(&apple_clpc_driver); + if (apple_clpc_cpuhp_state > 0) { + cpuhp_remove_multi_state(apple_clpc_cpuhp_state); + apple_clpc_cpuhp_state = 0; + } +} +module_exit(apple_clpc_driver_exit); MODULE_DESCRIPTION("Apple SoC host performance controller floors"); MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/soc/apple/dbgview-internal.h b/drivers/soc/apple/dbgview-internal.h new file mode 100644 index 00000000000000..ff7ac30da309ff --- /dev/null +++ b/drivers/soc/apple/dbgview-internal.h @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _DBGVIEW_INTERNAL_H +#define _DBGVIEW_INTERNAL_H + +#include +#include + +struct dbgview { + struct device *dev; + void __iomem *base; + resource_size_t size; + struct dentry *dir; +}; + +#if IS_ENABLED(CONFIG_APPLE_DBGVIEW_KUNIT_TEST) +ssize_t dbgview_regs_read(struct file *file, char __user *ubuf, + size_t count, loff_t *ppos); +int dbgview_snapshot(struct seq_file *s, unsigned int bytes); +extern const struct file_operations dbgview_regs_fops; +const struct file_operations *dbgview_test_snapshot_fops(void); +#endif + +#endif diff --git a/drivers/soc/apple/dbgview-test.c b/drivers/soc/apple/dbgview-test.c new file mode 100644 index 00000000000000..213b1328742deb --- /dev/null +++ b/drivers/soc/apple/dbgview-test.c @@ -0,0 +1,473 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SoC read-only debug register views. + * + * The view under test is a struct dbgview whose register block is a buffer + * of kernel memory and whose device is a KUnit device with runtime PM and no + * callbacks. The tests call the driver's own read and snapshot handlers; the + * read handler copies to a KUnit user mapping. No device is probed and no + * MMIO is touched. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dbgview-internal.h" + +#define DBGVIEW_TEST_USER_SIZE (3 * PAGE_SIZE) +#define DBGVIEW_TEST_SEQ_SIZE (8 * 1024) + +struct dbgview_test_ctx { + struct dbgview dv; + struct file file; + __le32 *regs; + __le32 *copy; + char __user *ubuf; + u8 *kbuf; + char *seq_buf; +}; + +static u32 dbgview_test_word(size_t i) +{ + return 0xd0000000 | (i * 4); +} + +static struct dbgview_test_ctx *dbgview_test_setup(struct kunit *test, + resource_size_t size, + bool rpm) +{ + struct dbgview_test_ctx *ctx; + unsigned long uaddr; + struct device *dev; + size_t i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + + dev = kunit_device_register(test, "apple-dbgview-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + if (rpm) { + pm_runtime_no_callbacks(dev); + KUNIT_ASSERT_EQ(test, devm_pm_runtime_enable(dev), 0); + } + + /* One spare word past the end to catch a read beyond the block. */ + ctx->regs = kunit_kzalloc(test, size + 4, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->regs); + ctx->copy = kunit_kzalloc(test, size + 4, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->copy); + for (i = 0; i < size / 4 + 1; i++) + ctx->regs[i] = cpu_to_le32(dbgview_test_word(i)); + memcpy(ctx->copy, ctx->regs, size + 4); + + ctx->dv.dev = dev; + ctx->dv.base = (void __iomem __force *)ctx->regs; + ctx->dv.size = size; + ctx->file.private_data = &ctx->dv; + + uaddr = kunit_vm_mmap(test, NULL, 0, DBGVIEW_TEST_USER_SIZE, + PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0); + KUNIT_ASSERT_NE_MSG(test, uaddr, 0, "no user mapping"); + KUNIT_ASSERT_LT(test, uaddr, (unsigned long)TASK_SIZE); + ctx->ubuf = (char __user *)uaddr; + + ctx->kbuf = kunit_kzalloc(test, DBGVIEW_TEST_USER_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->kbuf); + + return ctx; +} + +/* Fill the user buffer with a marker so that untouched bytes show up. */ +static void dbgview_test_poison_user(struct kunit *test, + struct dbgview_test_ctx *ctx) +{ + memset(ctx->kbuf, 0xee, DBGVIEW_TEST_USER_SIZE); + KUNIT_ASSERT_EQ(test, copy_to_user(ctx->ubuf, ctx->kbuf, + DBGVIEW_TEST_USER_SIZE), 0); +} + +static void dbgview_test_fetch_user(struct kunit *test, + struct dbgview_test_ctx *ctx) +{ + KUNIT_ASSERT_EQ(test, copy_from_user(ctx->kbuf, ctx->ubuf, + DBGVIEW_TEST_USER_SIZE), 0); +} + +static ssize_t dbgview_test_read(struct dbgview_test_ctx *ctx, size_t count, + loff_t *pos) +{ + return dbgview_regs_read(&ctx->file, ctx->ubuf, count, pos); +} + +static int dbgview_test_usage(struct dbgview_test_ctx *ctx) +{ + return atomic_read(&ctx->dv.dev->power.usage_count); +} + +/* Bytes [0, len) of the user buffer are the registers from @pos on. */ +static void dbgview_test_compare_words(struct kunit *test, const u8 *buf, + size_t pos, size_t len) +{ + const u32 *words = (const u32 *)buf; + size_t i; + + for (i = 0; i < len / 4; i++) + KUNIT_EXPECT_EQ(test, words[i], dbgview_test_word(pos / 4 + i)); +} + +static void dbgview_test_expect_words(struct kunit *test, + struct dbgview_test_ctx *ctx, + loff_t pos, size_t len) +{ + dbgview_test_fetch_user(test, ctx); + dbgview_test_compare_words(test, ctx->kbuf, pos, len); + /* nothing past the returned length was written */ + KUNIT_EXPECT_EQ(test, ctx->kbuf[len], 0xee); +} + +static void dbgview_test_read_whole(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 0; + + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x100, &pos), 0x40); + KUNIT_EXPECT_EQ(test, pos, 0x40); + dbgview_test_expect_words(test, ctx, 0, 0x40); +} + +static void dbgview_test_read_offset(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 8; + + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 8, &pos), 8); + KUNIT_EXPECT_EQ(test, pos, 16); + dbgview_test_expect_words(test, ctx, 8, 8); + KUNIT_EXPECT_EQ(test, *(u32 *)ctx->kbuf, dbgview_test_word(2)); +} + +/* At or beyond the end of the block a read returns 0 and copies nothing. */ +static void dbgview_test_read_eof(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 0x40; + + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x10, &pos), 0); + KUNIT_EXPECT_EQ(test, pos, 0x40); + pos = 0x1000; + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x10, &pos), 0); + KUNIT_EXPECT_EQ(test, pos, 0x1000); + dbgview_test_fetch_user(test, ctx); + KUNIT_EXPECT_EQ(test, ctx->kbuf[0], 0xee); +} + +/* Only whole, aligned words are read. */ +static void dbgview_test_read_unaligned_pos(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos; + + for (pos = 1; pos < 4; pos++) { + loff_t p = pos; + + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x10, &p), -EINVAL); + KUNIT_EXPECT_EQ(test, p, pos); + } + pos = -4; + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x10, &pos), -EINVAL); + KUNIT_EXPECT_EQ(test, dbgview_test_usage(ctx), 0); +} + +static void dbgview_test_read_short_count(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 0; + size_t count; + + for (count = 0; count < 4; count++) { + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, count, &pos), -EINVAL); + KUNIT_EXPECT_EQ(test, pos, 0); + } + + /* A count that is not a whole number of words is rounded down. */ + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 7, &pos), 4); + KUNIT_EXPECT_EQ(test, pos, 4); + dbgview_test_expect_words(test, ctx, 0, 4); +} + +/* A read near the end stops at the end of the block. */ +static void dbgview_test_read_clamped(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 0x3c; + + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x10, &pos), 4); + KUNIT_EXPECT_EQ(test, pos, 0x40); + dbgview_test_expect_words(test, ctx, 0x3c, 4); + KUNIT_EXPECT_EQ(test, *(u32 *)ctx->kbuf, dbgview_test_word(0xf)); +} + +/* One read never covers more than a page. */ +static void dbgview_test_read_page_cap(struct kunit *test) +{ + resource_size_t size = 2 * PAGE_SIZE + 0x40; + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, size, true); + loff_t pos = 0; + + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, DBGVIEW_TEST_USER_SIZE, &pos), + PAGE_SIZE); + KUNIT_EXPECT_EQ(test, pos, PAGE_SIZE); + dbgview_test_expect_words(test, ctx, 0, PAGE_SIZE); +} + +/* Reading on until EOF returns every word once and nothing else. */ +static void dbgview_test_read_sequential(struct kunit *test) +{ + resource_size_t size = 2 * PAGE_SIZE + 0x40; + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, size, true); + u8 *all = kunit_kzalloc(test, size, GFP_KERNEL); + unsigned int reads = 0; + loff_t pos = 0; + ssize_t ret; + + KUNIT_ASSERT_NOT_NULL(test, all); + while ((ret = dbgview_test_read(ctx, 0x1000, &pos)) > 0) { + KUNIT_ASSERT_LE(test, pos, size); + KUNIT_ASSERT_EQ(test, copy_from_user(all + pos - ret, ctx->ubuf, ret), 0); + KUNIT_ASSERT_LT(test, ++reads, 1000); + } + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, pos, size); + dbgview_test_compare_words(test, all, 0, size); +} + +/* Every read takes and drops one runtime PM reference. */ +static void dbgview_test_read_rpm_balanced(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 0; + int i; + + for (i = 0; i < 4; i++) { + pos = 0; + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x40, &pos), 0x40); + KUNIT_EXPECT_EQ(test, dbgview_test_usage(ctx), 0); + } +} + +/* If the block cannot be powered, nothing is read or copied. */ +static void dbgview_test_read_rpm_error(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, false); + loff_t pos = 0; + + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x40, &pos), -EACCES); + KUNIT_EXPECT_EQ(test, pos, 0); + KUNIT_EXPECT_EQ(test, dbgview_test_usage(ctx), 0); + dbgview_test_fetch_user(test, ctx); + KUNIT_EXPECT_EQ(test, ctx->kbuf[0], 0xee); +} + +/* A bad user buffer fails the read and leaves the position alone. */ +static void dbgview_test_read_efault(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 0; + + KUNIT_EXPECT_EQ(test, dbgview_regs_read(&ctx->file, (char __user *)NULL, + 0x40, &pos), -EFAULT); + KUNIT_EXPECT_EQ(test, pos, 0); + KUNIT_EXPECT_EQ(test, dbgview_test_usage(ctx), 0); +} + +/* Reads never change the block, nor the word past its end. */ +static void dbgview_test_read_never_writes(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x80, true); + loff_t pos = 0; + + while (dbgview_test_read(ctx, 0x14, &pos) > 0) + ; + KUNIT_EXPECT_MEMEQ(test, ctx->regs, ctx->copy, 0x80 + 4); +} + +static bool dbgview_test_has(const struct dbgview_test_ctx *ctx, const char *want) +{ + return strstr(ctx->seq_buf, want); +} + +static bool dbgview_test_starts(const struct dbgview_test_ctx *ctx, const char *want) +{ + return str_has_prefix(ctx->seq_buf, want); +} + +static unsigned int dbgview_test_lines(const char *buf) +{ + unsigned int n = 0; + + for (; *buf; buf++) + if (*buf == '\n') + n++; + return n; +} + +static int dbgview_test_snapshot(struct kunit *test, + struct dbgview_test_ctx *ctx, unsigned int bytes) +{ + struct seq_file s = { }; + int ret; + + ctx->seq_buf = kunit_kzalloc(test, DBGVIEW_TEST_SEQ_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->seq_buf); + s.buf = ctx->seq_buf; + s.size = DBGVIEW_TEST_SEQ_SIZE - 1; + s.private = &ctx->dv; + + ret = dbgview_snapshot(&s, bytes); + KUNIT_EXPECT_FALSE(test, seq_has_overflowed(&s)); + ctx->seq_buf[s.count] = '\0'; + return ret; +} + +/* Counter, one line per word, counter, frequency. */ +static void dbgview_test_snapshot_format(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x100, true); + unsigned long long before, after; + unsigned int frq; + char line[32]; + int n; + const char *p; + size_t i; + + KUNIT_ASSERT_EQ(test, dbgview_test_snapshot(test, ctx, 0x40), 0); + + KUNIT_ASSERT_EQ(test, dbgview_test_lines(ctx->seq_buf), 16 + 3); + n = sscanf(ctx->seq_buf, "cntvct_before %16llx\n", &before); + KUNIT_ASSERT_EQ(test, n, 1); + KUNIT_EXPECT_EQ(test, ctx->seq_buf[strlen("cntvct_before ") + 16], '\n'); + + p = strchr(ctx->seq_buf, '\n') + 1; + for (i = 0; i < 16; i++) { + snprintf(line, sizeof(line), "%04zx %08x\n", i * 4, + dbgview_test_word(i)); + KUNIT_EXPECT_TRUE_MSG(test, str_has_prefix(p, line), "%s", line); + p = strchr(p, '\n') + 1; + } + n = sscanf(p, "cntvct_after %16llx\n", &after); + KUNIT_ASSERT_EQ(test, n, 1); + p = strchr(p, '\n') + 1; + n = sscanf(p, "cntfrq %u\n", &frq); + KUNIT_ASSERT_EQ(test, n, 1); + + KUNIT_EXPECT_LE(test, before, after); + KUNIT_EXPECT_NE(test, before, 0); + KUNIT_EXPECT_EQ(test, frq, arch_timer_get_cntfrq()); + KUNIT_EXPECT_EQ(test, dbgview_test_usage(ctx), 0); +} + +/* The snapshot covers snap_bytes, rounded down to words, within the block. */ +static void dbgview_test_snapshot_sizes(struct kunit *test) +{ + static const struct { + resource_size_t size; + unsigned int snap; + unsigned int words; + } cases[] = { + { 0x100, 0x40, 16 }, + { 0x10, 0x40, 4 }, /* clamped to the block */ + { 0x100, 8, 2 }, + { 0x100, 6, 1 }, /* partial word dropped */ + { 0x100, 3, 0 }, + { 0x100, 0, 0 }, + { 0x100, 0x100, 64 }, + { 0x40, 0xffffffff, 16 }, + }; + char last[32]; + size_t i; + + for (i = 0; i < ARRAY_SIZE(cases); i++) { + struct dbgview_test_ctx *ctx = + dbgview_test_setup(test, cases[i].size, true); + + KUNIT_ASSERT_EQ(test, dbgview_test_snapshot(test, ctx, cases[i].snap), 0); + KUNIT_EXPECT_EQ_MSG(test, dbgview_test_lines(ctx->seq_buf), + cases[i].words + 3, "case %zu", i); + if (cases[i].words) { + snprintf(last, sizeof(last), "\n%04x %08x\ncntvct_after ", + (cases[i].words - 1) * 4, + dbgview_test_word(cases[i].words - 1)); + KUNIT_EXPECT_NOT_NULL_MSG(test, strstr(ctx->seq_buf, last), + "case %zu", i); + } else { + KUNIT_EXPECT_TRUE(test, dbgview_test_has(ctx, "\ncntvct_after ")); + KUNIT_EXPECT_TRUE(test, dbgview_test_starts(ctx, "cntvct_before ")); + KUNIT_EXPECT_NULL(test, strstr(ctx->seq_buf, "\n0000 ")); + } + KUNIT_EXPECT_MEMEQ(test, ctx->regs, ctx->copy, cases[i].size + 4); + kunit_device_unregister(test, ctx->dv.dev); + } +} + +static void dbgview_test_snapshot_rpm_error(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, false); + + KUNIT_EXPECT_EQ(test, dbgview_test_snapshot(test, ctx, 0x40), -EACCES); + KUNIT_EXPECT_EQ(test, ctx->seq_buf[0], '\0'); + KUNIT_EXPECT_EQ(test, dbgview_test_usage(ctx), 0); +} + +/* Neither file has a write method. */ +static void dbgview_test_fops_read_only(struct kunit *test) +{ + const struct file_operations *snapshot = dbgview_test_snapshot_fops(); + + KUNIT_EXPECT_NULL(test, dbgview_regs_fops.write); + KUNIT_EXPECT_NULL(test, dbgview_regs_fops.write_iter); + KUNIT_EXPECT_TRUE(test, dbgview_regs_fops.read == dbgview_regs_read); + KUNIT_EXPECT_NULL(test, snapshot->write); + KUNIT_EXPECT_NULL(test, snapshot->write_iter); +} + +static struct kunit_case dbgview_test_cases[] = { + KUNIT_CASE(dbgview_test_read_whole), + KUNIT_CASE(dbgview_test_read_offset), + KUNIT_CASE(dbgview_test_read_eof), + KUNIT_CASE(dbgview_test_read_unaligned_pos), + KUNIT_CASE(dbgview_test_read_short_count), + KUNIT_CASE(dbgview_test_read_clamped), + KUNIT_CASE(dbgview_test_read_page_cap), + KUNIT_CASE(dbgview_test_read_sequential), + KUNIT_CASE(dbgview_test_read_rpm_balanced), + KUNIT_CASE(dbgview_test_read_rpm_error), + KUNIT_CASE(dbgview_test_read_efault), + KUNIT_CASE(dbgview_test_read_never_writes), + KUNIT_CASE(dbgview_test_snapshot_format), + KUNIT_CASE(dbgview_test_snapshot_sizes), + KUNIT_CASE(dbgview_test_snapshot_rpm_error), + KUNIT_CASE(dbgview_test_fops_read_only), + {} +}; + +static struct kunit_suite dbgview_test_suite = { + .name = "apple-dbgview", + .test_cases = dbgview_test_cases, +}; + +kunit_test_suite(dbgview_test_suite); + +MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING"); +MODULE_LICENSE("GPL"); diff --git a/drivers/soc/apple/dbgview.c b/drivers/soc/apple/dbgview.c index f0eb987112848d..17047858ae1b58 100644 --- a/drivers/soc/apple/dbgview.c +++ b/drivers/soc/apple/dbgview.c @@ -31,17 +31,19 @@ #include +#include "dbgview-internal.h" + +#if IS_ENABLED(CONFIG_APPLE_DBGVIEW_KUNIT_TEST) +#include +#else +#define VISIBLE_IF_KUNIT static +#define EXPORT_SYMBOL_IF_KUNIT(symbol) +#endif + static unsigned int snap_bytes = 0x40; module_param(snap_bytes, uint, 0444); MODULE_PARM_DESC(snap_bytes, "Bytes of an MMIO view read by its snapshot file"); -struct dbgview { - struct device *dev; - void __iomem *base; - resource_size_t size; - struct dentry *dir; -}; - static struct dentry *dbgview_root; static u64 dbgview_cntvct(void) @@ -49,7 +51,7 @@ static u64 dbgview_cntvct(void) return __arch_counter_get_cntvct_stable(); } -static ssize_t dbgview_regs_read(struct file *file, char __user *ubuf, +VISIBLE_IF_KUNIT ssize_t dbgview_regs_read(struct file *file, char __user *ubuf, size_t count, loff_t *ppos) { struct dbgview *dv = file->private_data; @@ -91,18 +93,20 @@ static ssize_t dbgview_regs_read(struct file *file, char __user *ubuf, *ppos = pos + len; return len; } +EXPORT_SYMBOL_IF_KUNIT(dbgview_regs_read); -static const struct file_operations dbgview_regs_fops = { +VISIBLE_IF_KUNIT const struct file_operations dbgview_regs_fops = { .owner = THIS_MODULE, .open = simple_open, .read = dbgview_regs_read, .llseek = default_llseek, }; +EXPORT_SYMBOL_IF_KUNIT(dbgview_regs_fops); -static int dbgview_snapshot_show(struct seq_file *s, void *unused) +VISIBLE_IF_KUNIT int dbgview_snapshot(struct seq_file *s, unsigned int bytes) { struct dbgview *dv = s->private; - size_t words = min_t(size_t, snap_bytes, dv->size) / 4; + size_t words = min_t(size_t, bytes, dv->size) / 4; unsigned long flags; u64 before, after; u32 *val; @@ -138,8 +142,21 @@ static int dbgview_snapshot_show(struct seq_file *s, void *unused) kfree(val); return 0; } +EXPORT_SYMBOL_IF_KUNIT(dbgview_snapshot); +static int dbgview_snapshot_show(struct seq_file *s, void *unused) +{ + return dbgview_snapshot(s, snap_bytes); +} DEFINE_SHOW_ATTRIBUTE(dbgview_snapshot); +#if IS_ENABLED(CONFIG_APPLE_DBGVIEW_KUNIT_TEST) +const struct file_operations *dbgview_test_snapshot_fops(void) +{ + return &dbgview_snapshot_fops; +} +EXPORT_SYMBOL_IF_KUNIT(dbgview_test_snapshot_fops); +#endif + static int dbgview_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; diff --git a/drivers/soc/apple/dbgview.kunitconfig b/drivers/soc/apple/dbgview.kunitconfig new file mode 100644 index 00000000000000..e77e9bdc8bd832 --- /dev/null +++ b/drivers/soc/apple/dbgview.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_PM=y +CONFIG_DEBUG_FS=y +CONFIG_APPLE_DBGVIEW=y +CONFIG_APPLE_DBGVIEW_KUNIT_TEST=y diff --git a/drivers/soc/apple/diag_shim.c b/drivers/soc/apple/diag_shim.c index 995abe149b0c50..51453c19297f0d 100644 --- a/drivers/soc/apple/diag_shim.c +++ b/drivers/soc/apple/diag_shim.c @@ -19,8 +19,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -118,8 +120,39 @@ static struct { atomic_t unhandled; atomic_t sleeps; atomic_t sleeping; + + struct kernfs_node *keystore_kn; + struct kernfs_node *touchid_kn; } sep_diag; +static DEFINE_SPINLOCK(sep_diag_kn_lock); + +static void sep_diag_put_kns(void *data) +{ + struct kernfs_node *keystore_kn, *touchid_kn; + unsigned long flags; + + spin_lock_irqsave(&sep_diag_kn_lock, flags); + keystore_kn = sep_diag.keystore_kn; + touchid_kn = sep_diag.touchid_kn; + sep_diag.keystore_kn = NULL; + sep_diag.touchid_kn = NULL; + spin_unlock_irqrestore(&sep_diag_kn_lock, flags); + + sysfs_put(keystore_kn); + sysfs_put(touchid_kn); +} + +static void sep_diag_notify_kn(struct kernfs_node **knp) +{ + unsigned long flags; + + spin_lock_irqsave(&sep_diag_kn_lock, flags); + if (*knp) + kernfs_notify(*knp); + spin_unlock_irqrestore(&sep_diag_kn_lock, flags); +} + /* Written once per probe, before pnon reads SEP_DIAG_PNON_READ. */ static u8 sep_diag_pnon_digest[SEP_DIAG_PNON_DIGEST_LEN]; @@ -735,6 +768,10 @@ static const struct attribute_group sep_diag_group = { int sep_diag_register(struct device *dev, const char *profile, size_t profile_len, bool cold, bool sepos13, bool xart) { + struct kernfs_node *diag_kn, *keystore_kn = NULL, *touchid_kn = NULL; + unsigned long flags; + int ret; + profile_len = min(profile_len, sizeof(sep_diag.profile) - 1); memcpy(sep_diag.profile, profile, profile_len); sep_diag.profile[profile_len] = '\0'; @@ -743,7 +780,23 @@ int sep_diag_register(struct device *dev, const char *profile, sep_diag.xart = xart; sep_diag.probe_ns = ktime_get_boottime_ns(); - return devm_device_add_group(dev, &sep_diag_group); + ret = devm_device_add_group(dev, &sep_diag_group); + if (ret) + return ret; + + diag_kn = sysfs_get_dirent(dev->kobj.sd, "diag"); + if (diag_kn) { + keystore_kn = sysfs_get_dirent(diag_kn, "keystore"); + touchid_kn = sysfs_get_dirent(diag_kn, "touchid"); + sysfs_put(diag_kn); + } + + spin_lock_irqsave(&sep_diag_kn_lock, flags); + sep_diag.keystore_kn = keystore_kn; + sep_diag.touchid_kn = touchid_kn; + spin_unlock_irqrestore(&sep_diag_kn_lock, flags); + + return devm_add_action_or_reset(dev, sep_diag_put_kns, NULL); } void sep_diag_set_attach(bool attached) @@ -867,7 +920,9 @@ void sep_diag_log_summary(struct device *dev) void sep_diag_set_keystore_open(void) { - atomic_set(&sep_diag.keystore, SEP_DIAG_KEYSTORE_OPEN); + if (atomic_xchg(&sep_diag.keystore, SEP_DIAG_KEYSTORE_OPEN) != + SEP_DIAG_KEYSTORE_OPEN) + sep_diag_notify_kn(&sep_diag.keystore_kn); } void sep_diag_set_keybag(int state) @@ -925,14 +980,18 @@ void sep_diag_set_sensor_result(unsigned int bind, bool online) */ void sep_diag_set_bio_published(void) { - atomic_cmpxchg(&sep_diag.touchid, SEP_DIAG_TOUCHID_PENDING, - SEP_DIAG_TOUCHID_PUBLISHED); + if (atomic_cmpxchg(&sep_diag.touchid, SEP_DIAG_TOUCHID_PENDING, + SEP_DIAG_TOUCHID_PUBLISHED) == + SEP_DIAG_TOUCHID_PENDING) + sep_diag_notify_kn(&sep_diag.touchid_kn); } void sep_diag_set_touchid(bool started) { - atomic_set(&sep_diag.touchid, - started ? SEP_DIAG_TOUCHID_STARTED : SEP_DIAG_TOUCHID_FAILED); + int state = started ? SEP_DIAG_TOUCHID_STARTED : SEP_DIAG_TOUCHID_FAILED; + + if (atomic_xchg(&sep_diag.touchid, state) != state) + sep_diag_notify_kn(&sep_diag.touchid_kn); } void sep_diag_set_sensor_attach(int state) @@ -978,13 +1037,17 @@ void sep_diag_set_xart(bool writable) void sep_diag_keystore_ended(void) { atomic64_cmpxchg(&sep_diag.ready_ns, 0, ktime_get_boottime_ns()); - atomic_cmpxchg(&sep_diag.keystore, SEP_DIAG_KEYSTORE_UNKNOWN, - SEP_DIAG_KEYSTORE_CLOSED); + if (atomic_cmpxchg(&sep_diag.keystore, SEP_DIAG_KEYSTORE_UNKNOWN, + SEP_DIAG_KEYSTORE_CLOSED) == + SEP_DIAG_KEYSTORE_UNKNOWN) + sep_diag_notify_kn(&sep_diag.keystore_kn); } void sep_diag_bringup_ended(void) { sep_diag_keystore_ended(); - atomic_cmpxchg(&sep_diag.touchid, SEP_DIAG_TOUCHID_PENDING, - SEP_DIAG_TOUCHID_UNAVAILABLE); + if (atomic_cmpxchg(&sep_diag.touchid, SEP_DIAG_TOUCHID_PENDING, + SEP_DIAG_TOUCHID_UNAVAILABLE) == + SEP_DIAG_TOUCHID_PENDING) + sep_diag_notify_kn(&sep_diag.touchid_kn); } diff --git a/drivers/soc/apple/display-gate-test.c b/drivers/soc/apple/display-gate-test.c index dbd534537e87ca..58e96acb602af6 100644 --- a/drivers/soc/apple/display-gate-test.c +++ b/drivers/soc/apple/display-gate-test.c @@ -14,7 +14,9 @@ * changed when a check fails. * - T8122 (t8122-gate-test.dtso): on by default, with the full handoff, * and nothing changed when a check of the handoff or of the reused PMP - * topology fails. + * topology fails. Its external processor (dcpext) starts on 14.7.0, and + * on the 27.2 image beside an internal DCP handed over on it, with the + * panel's DMA window on both of its DARTs; otherwise it stays disabled. * - T6041: no test tree; a PMP that binds after the deadline still * starts the external display power-up, and only a failed PMP or power-up * leaves the internal panel alone. @@ -158,6 +160,7 @@ struct gate_test { bool requested, t6031_requested; int t6031_switch; const char *t6031_board; + const char *pmp_uuid; /* the PMP image the values name: the fixture's unless set */ }; static struct device_node *__init gt_node(struct kunit *test, const char *path) @@ -181,6 +184,13 @@ static void __init gt_remove(struct kunit *test, const char *path, const char *n KUNIT_ASSERT_EQ(test, of_changeset_remove_property(&t->cs, np, prop), 0); } +static void __init gt_add_bool(struct kunit *test, const char *path, const char *name) +{ + struct gate_test *t = test->priv; + + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_bool(&t->cs, gt_node(test, path), name), 0); +} + static void __init gt_add_u32(struct kunit *test, const char *path, const char *name, u32 val) { struct gate_test *t = test->priv; @@ -333,7 +343,7 @@ static void __init gt_expect_enabled(struct kunit *test) KUNIT_EXPECT_TRUE(test, of_device_is_compatible(pmp, s->pmp_compat)); KUNIT_EXPECT_FALSE(test, of_device_is_available(pmp)); KUNIT_ASSERT_EQ(test, of_property_read_string(pmp, "apple,tunable-uuid", &uuid), 0); - KUNIT_EXPECT_STREQ(test, uuid, s->pmp_uuid); + KUNIT_EXPECT_STREQ(test, uuid, t->pmp_uuid); KUNIT_EXPECT_TRUE(test, of_property_present(pmp, "apple,tunable-test")); KUNIT_EXPECT_TRUE(test, of_property_present(pmp, "apple,board-id")); KUNIT_EXPECT_TRUE(test, of_property_present(pmp, "apple,dram-vendor-id")); @@ -404,6 +414,7 @@ static int __init gt_init(struct kunit *test, const struct gt_soc *s) return -ENOMEM; test->priv = t; t->s = s; + t->pmp_uuid = s->pmp_uuid; /* As the boot left them: the test kernel's command line sets neither. */ t->requested = gate_requested; t->t6031_requested = gate_t6031_requested; @@ -417,6 +428,7 @@ static int __init gt_init(struct kunit *test, const struct gt_soc *s) gate_requested = true; gate_t6031_requested = false; gate_t6031_switch = -1; + gate_t8122_dcpext_cs = NULL; if (gt_live_soc) kunit_skip(test, "the booted device tree has its own /soc"); return 0; @@ -441,6 +453,12 @@ static void __init gt_exit(struct kunit *test) { struct gate_test *t = test->priv; + /* The T8122 dcpext's changes build on the display's: reverted first. */ + if (gate_t8122_dcpext_cs) { + of_changeset_revert(gate_t8122_dcpext_cs); + gate_cs_free(gate_t8122_dcpext_cs); + gate_t8122_dcpext_cs = NULL; + } /* The gate leaves its changes applied only when it enabled the display. */ if (gate_pmp_ovcs) { of_changeset_revert(&gate_pmp_cs); @@ -779,6 +797,17 @@ static void __init gate_t6030_other_pmp_image(struct kunit *test) gt_expect_untouched(test); } +/* The 27.2 (26B123) T6030 PMP image is taken as well. */ +static void __init gate_t6030_pmp_image_27_2(struct kunit *test) +{ + struct gate_test *t = test->priv; + + t->pmp_uuid = "5D66805B-E4AD-335E-BDC3-26828C682AAC"; + gt_set_string(test, gt_t6030.values, "apple,tunable-uuid", t->pmp_uuid); + gt_run(test); + gt_expect_enabled(test); +} + static void __init gate_t6030_enabled_again(struct kunit *test) { gt_run(test); @@ -833,8 +862,10 @@ static void __init gate_t8122_t6031_pmp_image(struct kunit *test) /* The 27.2 (26B123) T8122 PMP image is taken as well. */ static void __init gate_t8122_pmp_image_27_2(struct kunit *test) { - gt_set_string(test, gt_t8122.values, "apple,tunable-uuid", - "C6CCB960-AC83-34A2-9493-C3131BD5AE4B"); + struct gate_test *t = test->priv; + + t->pmp_uuid = "C6CCB960-AC83-34A2-9493-C3131BD5AE4B"; + gt_set_string(test, gt_t8122.values, "apple,tunable-uuid", t->pmp_uuid); gt_run(test); gt_expect_enabled(test); } @@ -905,6 +936,290 @@ static void __init gate_t8122_enabled_again(struct kunit *test) gt_expect_enabled(test); } +/* T8122 external display processor (dcpext) */ + +#define GT_T8122_DCPEXT "/t8122-soc/dcp@31ac00000" +#define GT_T8122_DCPEXT_DART "/t8122-soc/iommu@31930c000" +#define GT_T8122_DISPEXT_DART "/t8122-soc/iommu@319304000" +#define GT_T8122_DCPEXT_MBOX "/t8122-soc/mailbox@31ac08000" +#define GT_T8122_DCPEXT_PS "/t8122-soc/power-management@2d0700000/power-controller@488" +#define GT_T8122_DCPEXT_ENTRY "/t8122-soc/pmp_report@2d03c0000/report@8" + +/* The device tree's 14.7 windows of the dcpext DARTs, and the panel's. */ +static const u64 gt_t8122_dcpext_window[2] __initconst = { 0x800000000, 0x7ffff0000 }; +static const u64 gt_t8122_dispext_window[2] __initconst = { 0x0, 0xfffff0000 }; +static const u64 gt_t8122_panel_window[2] __initconst = { 0x10000000000, 0x1000000000 }; + +static const u32 gt_v14_7[3] __initconst = { 14, 7, 0 }; +static const u32 gt_v27_0[3] __initconst = { 27, 0, 0 }; +static const u32 gt_v27_2[3] __initconst = { 27, 2, 0 }; + +/* Sets, or adds, the u32 array @name of @path. */ +static void __init gt_set_u32_array(struct kunit *test, const char *path, const char *name, + const u32 *val, size_t n) +{ + struct gate_test *t = test->priv; + struct device_node *np = gt_node(test, path); + + if (of_property_present(np, name)) + gt_remove(test, path, name); + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_u32_array(&t->cs, np, name, val, n), 0); +} + +/* The dcpext as the boot loader marks it, with these firmware versions. */ +static void __init gt_t8122_dcpext_firmware(struct kunit *test, const u32 version[3], + const u32 compat[3]) +{ + gt_add_u32(test, GT_T8122_DCPEXT, "apple,t8122-dcpext-firmware-ready", 1); + if (version) + gt_set_u32_array(test, GT_T8122_DCPEXT, "apple,firmware-version", version, 3); + gt_set_u32_array(test, GT_T8122_DCPEXT, "apple,firmware-compat", compat, 3); +} + +/* The internal DCP handed over on the 27.2 (26B123) image. */ +static void __init gt_t8122_dcp_v27_2(struct kunit *test) +{ + gt_set_string(test, gt_t8122.dcp, "apple,firmware-uuid", APPLE_T8122_DCP_26B123_UUID); + gt_set_u32_array(test, gt_t8122.dcp, "apple,firmware-version", gt_v27_2, 3); + gt_set_u32_array(test, gt_t8122.dcp, "apple,firmware-compat", gt_v27_2, 3); +} + +static void __init gt_expect_window(struct kunit *test, const char *path, const u64 want[2]) +{ + u64 window[2] = {}; + + KUNIT_ASSERT_EQ_MSG(test, of_property_read_u64_array(gt_node(test, path), + "apple,dma-range", window, 2), 0, + "%s", path); + KUNIT_EXPECT_EQ_MSG(test, window[0], want[0], "%s start", path); + KUNIT_EXPECT_EQ_MSG(test, window[1], want[1], "%s size", path); +} + +/* + * The panel as gt_expect_enabled() checks it, and the dcpext enabled or not + * with all it needs. When enabled, @shared says whether its scanout DART joins + * the display subsystem's domain (disabling fbdma) or stays out (leaving fbdma + * available for framebuffer mirroring). @window: the window both dcpext DARTs + * must have, NULL for the device tree's own. + */ +static void __init gt_expect_dcpext_mode(struct kunit *test, bool enabled, bool shared, + const u64 *window) +{ + struct device_node *display = gt_node(test, gt_t8122.display); + struct device_node *entry = gt_node(test, GT_T8122_DCPEXT_ENTRY); + struct of_phandle_args args; + + gt_expect_enabled(test); + KUNIT_EXPECT_EQ(test, gt_okay(test, GT_T8122_DCPEXT), enabled); + KUNIT_EXPECT_EQ(test, gt_okay(test, GT_T8122_DCPEXT_DART), enabled); + KUNIT_EXPECT_EQ(test, gt_okay(test, GT_T8122_DISPEXT_DART), enabled); + KUNIT_EXPECT_EQ(test, gt_okay(test, GT_T8122_DCPEXT_MBOX), enabled); + KUNIT_EXPECT_EQ(test, of_property_read_bool(entry, "apple,always-on"), enabled); + KUNIT_EXPECT_EQ(test, of_property_read_bool(entry, "apple,soc-device-record"), enabled); + KUNIT_EXPECT_EQ(test, of_property_read_bool(entry, "apple,defer-startup-ack"), enabled); + KUNIT_EXPECT_EQ(test, gt_u32(test, GT_T8122_DCPEXT_PS, "apple,min-state"), + enabled ? PMGR_PS_ACTIVE : 4); + KUNIT_EXPECT_EQ(test, of_count_phandle_with_args(display, "iommus", "#iommu-cells"), + (enabled && shared) ? 2 : 1); + if (enabled) { + if (shared) { + KUNIT_ASSERT_EQ(test, of_parse_phandle_with_args(display, "iommus", + "#iommu-cells", 1, &args), + 0); + KUNIT_EXPECT_PTR_EQ(test, args.np, gt_node(test, GT_T8122_DISPEXT_DART)); + of_node_put(args.np); + } + KUNIT_EXPECT_EQ(test, gt_okay(test, GT_T8122_DCPEXT "/fbdma"), !shared); + } + gt_expect_window(test, GT_T8122_DCPEXT_DART, window ?: gt_t8122_dcpext_window); + gt_expect_window(test, GT_T8122_DISPEXT_DART, window ?: gt_t8122_dispext_window); + /* The panel's own window stays as it is. */ + gt_expect_window(test, "/t8122-soc/iommu@28d30c000", gt_t8122_panel_window); +} + +static void __init gt_expect_dcpext(struct kunit *test, bool enabled, const u64 *window) +{ + gt_expect_dcpext_mode(test, enabled, enabled, window); +} + +static void __init gt_require_display_driver(struct kunit *test) +{ + if (!IS_ENABLED(CONFIG_DRM_APPLE)) + kunit_skip(test, "the gate keeps the dcpext off without the display driver"); +} + +/* Without the boot loader's firmware-ready mark the dcpext stays disabled. */ +static void __init gate_t8122_dcpext_not_ready(struct kunit *test) +{ + gt_set_u32_array(test, GT_T8122_DCPEXT, "apple,firmware-compat", gt_v14_7, 3); + gt_run(test); + gt_expect_dcpext(test, false, NULL); +} + +/* On 14.7.0 it starts with the device tree's windows. */ +static void __init gate_t8122_dcpext_v14_7(struct kunit *test) +{ + gt_require_display_driver(test); + gt_t8122_dcpext_firmware(test, gt_v14_7, gt_v14_7); + gt_run(test); + gt_expect_dcpext(test, true, NULL); + KUNIT_EXPECT_FALSE(test, apple_t8122_dcpext_v27_2(gt_node(test, GT_T8122_DCPEXT))); +} + +/* The boot loader's default marker (<2>) is accepted alongside <1>. */ +static void __init gate_t8122_dcpext_loader_default_marker(struct kunit *test) +{ + gt_require_display_driver(test); + gt_add_u32(test, GT_T8122_DCPEXT, "apple,t8122-dcpext-firmware-ready", 2); + gt_set_u32_array(test, GT_T8122_DCPEXT, "apple,firmware-version", gt_v14_7, 3); + gt_set_u32_array(test, GT_T8122_DCPEXT, "apple,firmware-compat", gt_v14_7, 3); + gt_add_bool(test, GT_T8122_DCPEXT, "apple,no-shared-display-dart"); + gt_run(test); + gt_expect_dcpext_mode(test, true, false, NULL); +} + +/* Any marker value other than 1 or 2 is refused. */ +static void __init gate_t8122_dcpext_other_marker(struct kunit *test) +{ + gt_add_u32(test, GT_T8122_DCPEXT, "apple,t8122-dcpext-firmware-ready", 3); + gt_set_u32_array(test, GT_T8122_DCPEXT, "apple,firmware-compat", gt_v14_7, 3); + gt_run(test); + gt_expect_dcpext(test, false, NULL); +} + +/* apple,no-shared-display-dart keeps dispext0_dart out and leaves fbdma on. */ +static void __init gate_t8122_dcpext_board_mirrors(struct kunit *test) +{ + gt_require_display_driver(test); + gt_t8122_dcpext_firmware(test, gt_v14_7, gt_v14_7); + gt_add_bool(test, GT_T8122_DCPEXT, "apple,no-shared-display-dart"); + gt_run(test); + gt_expect_dcpext_mode(test, true, false, NULL); +} + +/* apple,no-shared-display-dart without an fbdma child is refused. */ +static void __init gate_t8122_dcpext_board_no_fbdma(struct kunit *test) +{ + gt_t8122_dcpext_firmware(test, gt_v14_7, gt_v14_7); + gt_add_bool(test, GT_T8122_DCPEXT, "apple,no-shared-display-dart"); + gt_detach(test, GT_T8122_DCPEXT "/fbdma"); + gt_run(test); + gt_expect_dcpext(test, false, NULL); +} + +/* On 27.2 with apple,no-shared-display-dart, DARTs get the panel window and fbdma stays on. */ +static void __init gate_t8122_dcpext_v27_2_mirrors(struct kunit *test) +{ + gt_require_display_driver(test); + gt_t8122_dcp_v27_2(test); + gt_t8122_dcpext_firmware(test, gt_v27_2, gt_v27_2); + gt_add_bool(test, GT_T8122_DCPEXT, "apple,no-shared-display-dart"); + gt_run(test); + gt_expect_dcpext_mode(test, true, false, gt_t8122_panel_window); +} + +/* + * On the 27.2 image, beside an internal DCP handed over on it, it starts + * with the panel's window on both of its DARTs. + */ +static void __init gate_t8122_dcpext_v27_2(struct kunit *test) +{ + gt_require_display_driver(test); + gt_t8122_dcp_v27_2(test); + gt_t8122_dcpext_firmware(test, gt_v27_2, gt_v27_2); + gt_run(test); + gt_expect_dcpext(test, true, gt_t8122_panel_window); + KUNIT_EXPECT_TRUE(test, apple_t8122_dcpext_v27_2(gt_node(test, GT_T8122_DCPEXT))); + /* The internal DCP itself is not the external processor. */ + KUNIT_EXPECT_FALSE(test, apple_t8122_dcpext_v27_2(gt_node(test, gt_t8122.dcp))); + KUNIT_EXPECT_FALSE(test, apple_t8122_dcpext_v27_2(NULL)); +} + +/* 27.2.0 next to an internal DCP on its 14.x image is not the 27.2 image. */ +static void __init gate_t8122_dcpext_v27_2_internal_v14(struct kunit *test) +{ + gt_t8122_dcpext_firmware(test, gt_v27_2, gt_v27_2); + gt_run(test); + gt_expect_dcpext(test, false, NULL); + KUNIT_EXPECT_FALSE(test, apple_t8122_dcpext_v27_2(gt_node(test, GT_T8122_DCPEXT))); +} + +/* Both its version and its compatibility must be 27.2.0. */ +static void __init gate_t8122_dcpext_v27_2_other_version(struct kunit *test) +{ + gt_t8122_dcp_v27_2(test); + gt_t8122_dcpext_firmware(test, gt_v27_0, gt_v27_2); + gt_run(test); + gt_expect_dcpext(test, false, NULL); + KUNIT_EXPECT_FALSE(test, apple_t8122_dcpext_v27_2(gt_node(test, GT_T8122_DCPEXT))); +} + +static void __init gate_t8122_dcpext_v27_2_no_version(struct kunit *test) +{ + gt_t8122_dcp_v27_2(test); + gt_t8122_dcpext_firmware(test, NULL, gt_v27_2); + gt_run(test); + gt_expect_dcpext(test, false, NULL); +} + +static void __init gate_t8122_dcpext_other_firmware(struct kunit *test) +{ + gt_t8122_dcp_v27_2(test); + gt_t8122_dcpext_firmware(test, gt_v27_0, gt_v27_0); + gt_run(test); + gt_expect_dcpext(test, false, NULL); +} + +/* Without the panel's window there is none to give it: nothing changes. */ +static void __init gate_t8122_dcpext_v27_2_no_panel_window(struct kunit *test) +{ + gt_require_display_driver(test); + gt_t8122_dcp_v27_2(test); + gt_t8122_dcpext_firmware(test, gt_v27_2, gt_v27_2); + gt_remove(test, "/t8122-soc/iommu@28d30c000", "apple,dma-range"); + gt_run(test); + gt_expect_enabled(test); + KUNIT_EXPECT_FALSE(test, gt_okay(test, GT_T8122_DCPEXT)); + KUNIT_EXPECT_FALSE(test, gt_okay(test, GT_T8122_DCPEXT_DART)); + KUNIT_EXPECT_FALSE(test, gt_okay(test, GT_T8122_DISPEXT_DART)); + KUNIT_EXPECT_FALSE(test, of_property_read_bool(gt_node(test, GT_T8122_DCPEXT_ENTRY), + "apple,always-on")); + gt_expect_window(test, GT_T8122_DCPEXT_DART, gt_t8122_dcpext_window); + gt_expect_window(test, GT_T8122_DISPEXT_DART, gt_t8122_dispext_window); +} + +/* + * gate_t8122_dcpext_alias() alone: it copies one window (start and size) + * onto both DARTs, and takes nothing else. + */ +static void __init gate_t8122_dcpext_alias_window(struct kunit *test) +{ + struct device_node *dart = gt_node(test, GT_T8122_DCPEXT_DART); + struct device_node *disp_dart = gt_node(test, GT_T8122_DISPEXT_DART); + static const u32 short_window[2] __initconst = { 0x100, 0x0 }; + struct gate_test *t = test->priv; + struct of_changeset cs; + + of_changeset_init(&cs); + KUNIT_ASSERT_EQ(test, gate_t8122_dcpext_alias(&cs, dart, disp_dart), 0); + KUNIT_ASSERT_EQ(test, of_changeset_apply(&cs), 0); + gt_expect_window(test, GT_T8122_DCPEXT_DART, gt_t8122_panel_window); + gt_expect_window(test, GT_T8122_DISPEXT_DART, gt_t8122_panel_window); + KUNIT_EXPECT_EQ(test, of_changeset_revert(&cs), 0); + of_changeset_destroy(&cs); + gt_expect_window(test, GT_T8122_DCPEXT_DART, gt_t8122_dcpext_window); + gt_expect_window(test, GT_T8122_DISPEXT_DART, gt_t8122_dispext_window); + + /* A window that is not one start and one size is refused. */ + gt_set_u32_array(test, "/t8122-soc/iommu@28d30c000", "apple,dma-range", + short_window, ARRAY_SIZE(short_window)); + KUNIT_ASSERT_EQ(test, of_changeset_apply(&t->cs), 0); + of_changeset_init(&cs); + KUNIT_EXPECT_EQ(test, gate_t8122_dcpext_alias(&cs, dart, disp_dart), -ENODEV); + KUNIT_EXPECT_TRUE(test, list_empty(&cs.entries)); + of_changeset_destroy(&cs); +} + /* The case and suite structs outlive init: only the functions are init code. */ static struct kunit_case gate_t6031_cases[] __refdata = { KUNIT_CASE(gate_t6031_param), @@ -951,6 +1266,7 @@ static struct kunit_case gate_t6030_cases[] __refdata = { KUNIT_CASE(gate_t6030_no_marker), KUNIT_CASE(gate_t6030_t6031_power_layout), KUNIT_CASE(gate_t6030_other_pmp_image), + KUNIT_CASE(gate_t6030_pmp_image_27_2), KUNIT_CASE(gate_t6030_enabled_again), {} }; @@ -979,6 +1295,20 @@ static struct kunit_case gate_t8122_cases[] __refdata = { KUNIT_CASE(gate_t8122_disp_no_ack), KUNIT_CASE(gate_t8122_no_storage_request), KUNIT_CASE(gate_t8122_not_inherited_on), + KUNIT_CASE(gate_t8122_dcpext_not_ready), + KUNIT_CASE(gate_t8122_dcpext_v14_7), + KUNIT_CASE(gate_t8122_dcpext_loader_default_marker), + KUNIT_CASE(gate_t8122_dcpext_other_marker), + KUNIT_CASE(gate_t8122_dcpext_board_mirrors), + KUNIT_CASE(gate_t8122_dcpext_board_no_fbdma), + KUNIT_CASE(gate_t8122_dcpext_v27_2), + KUNIT_CASE(gate_t8122_dcpext_v27_2_mirrors), + KUNIT_CASE(gate_t8122_dcpext_v27_2_internal_v14), + KUNIT_CASE(gate_t8122_dcpext_v27_2_other_version), + KUNIT_CASE(gate_t8122_dcpext_v27_2_no_version), + KUNIT_CASE(gate_t8122_dcpext_other_firmware), + KUNIT_CASE(gate_t8122_dcpext_v27_2_no_panel_window), + KUNIT_CASE(gate_t8122_dcpext_alias_window), KUNIT_CASE(gate_t8122_enabled_again), {} }; @@ -1110,10 +1440,22 @@ static void __init gt_max_fill(struct kunit *test, unsigned int i) static void __init gt_max_expect_chain(struct kunit *test, unsigned int i, bool enabled) { const struct gate_staged *st = &t6041_max_stages[i]; - unsigned int n; + struct device_node *routes, *route; + unsigned int n, nr_routes = 0; for (n = 0; n < st->nr; n++) KUNIT_EXPECT_EQ_MSG(test, gt_okay(test, st->nodes[n]), enabled, "%s", st->nodes[n]); + if (!st->dt_routes) + return; + /* A chain that takes its routes from the tree has every one of them. */ + routes = staged_routes(st); + KUNIT_ASSERT_NOT_NULL(test, routes); + for_each_child_of_node(routes, route) { + KUNIT_EXPECT_EQ_MSG(test, of_device_is_available(route), enabled, "%pOF", route); + nr_routes++; + } + of_node_put(routes); + KUNIT_EXPECT_GT(test, nr_routes, 0); } /* @@ -1164,6 +1506,7 @@ static void __init gate_t6041_max_no_memory(struct kunit *test) gt_max_expect_chain(test, 0, false); gt_max_expect_chain(test, 1, false); gt_max_expect_chain(test, 2, false); + gt_max_expect_chain(test, 3, false); gt_max_expect_display(test, 0); } @@ -1177,9 +1520,84 @@ static void __init gate_t6041_max_second_usbc(struct kunit *test) gt_max_expect_chain(test, 0, true); gt_max_expect_chain(test, 1, true); gt_max_expect_chain(test, 2, true); + gt_max_expect_chain(test, 3, false); gt_max_expect_display(test, BIT(0) | BIT(1) | BIT(2)); } +/* With all four filled, every external chain comes up, dcpext3's last. */ +static void __init gate_t6041_max_all_externals(struct kunit *test) +{ + unsigned int i; + + for (i = 0; i < 4; i++) + gt_max_fill(test, i); + gt_max_run(test); + for (i = 0; i < 4; i++) + gt_max_expect_chain(test, i, true); + gt_max_expect_display(test, BIT(0) | BIT(1) | BIT(2) | BIT(3)); +} + +/* + * dcpext3 takes its routes from the tree: with a route to a fourth Type-C port, + * as the J575c has, that route comes up with the chain too. + */ +static void __init gate_t6041_max_dt_routes(struct kunit *test) +{ + struct gate_test *t = test->priv; + struct device_node *route; + + route = of_changeset_create_node(&t->cs, gt_node(test, "/dcp@306e00000/typec-routes"), + "route@3"); + KUNIT_ASSERT_NOT_NULL(test, route); + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_u32(&t->cs, route, "reg", 3), 0); + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_string(&t->cs, route, "status", "disabled"), 0); + gt_max_fill(test, 3); + gt_max_run(test); + gt_max_expect_chain(test, 3, true); + KUNIT_EXPECT_TRUE(test, gt_okay(test, "/dcp@306e00000/typec-routes/route@3")); + gt_max_expect_display(test, BIT(3)); +} + +static void __init gt_max_expect_dt_routes_refused(struct kunit *test) +{ + const struct gate_staged *st = &t6041_max_stages[3]; + struct device_node *display = gt_node(test, "/display-subsystem"); + unsigned int n; + + gt_max_fill(test, 3); + gt_max_run(test); + for (n = 0; n < st->nr; n++) + KUNIT_EXPECT_FALSE_MSG(test, gt_okay(test, st->nodes[n]), "%s", st->nodes[n]); + gt_max_expect_display(test, 0); + + /* Direct application refuses it too and leaves the changeset untouched. */ + if (gt_okay(test, st->nodes[st->nr - 1])) + return; + KUNIT_EXPECT_EQ(test, t6041_max_apply(3, display), -ENODEV); + for (n = 0; n < st->nr; n++) + KUNIT_EXPECT_FALSE_MSG(test, gt_okay(test, st->nodes[n]), "%s", st->nodes[n]); + gt_max_expect_display(test, 0); +} + +/* A dt_routes stage whose typec-routes container is missing stays off whole. */ +static void __init gate_t6041_max_dt_routes_missing(struct kunit *test) +{ + gt_detach(test, "/dcp@306e00000/typec-routes/route@0"); + gt_detach(test, "/dcp@306e00000/typec-routes/route@1"); + gt_detach(test, "/dcp@306e00000/typec-routes/route@2"); + gt_detach(test, "/dcp@306e00000/typec-routes"); + gt_max_expect_dt_routes_refused(test); +} + +/* A dt_routes stage whose typec-routes container has no routes stays off whole. */ +static void __init gate_t6041_max_dt_routes_empty(struct kunit *test) +{ + gt_detach(test, "/dcp@306e00000/typec-routes/route@0"); + gt_detach(test, "/dcp@306e00000/typec-routes/route@1"); + gt_detach(test, "/dcp@306e00000/typec-routes/route@2"); + gt_max_expect_dt_routes_refused(test); +} + /* The other processor's chain does not wait for one that was refused. */ static void __init gate_t6041_max_one_processor(struct kunit *test) { @@ -1300,6 +1718,10 @@ static struct kunit_case gate_t6041_max_cases[] __refdata = { KUNIT_CASE(gate_t6041_max_enabled), KUNIT_CASE(gate_t6041_max_no_memory), KUNIT_CASE(gate_t6041_max_second_usbc), + KUNIT_CASE(gate_t6041_max_all_externals), + KUNIT_CASE(gate_t6041_max_dt_routes), + KUNIT_CASE(gate_t6041_max_dt_routes_missing), + KUNIT_CASE(gate_t6041_max_dt_routes_empty), KUNIT_CASE(gate_t6041_max_one_processor), KUNIT_CASE(gate_t6041_max_partial_memory), KUNIT_CASE(gate_t6041_max_enabled_by_loader), diff --git a/drivers/soc/apple/display-gate.c b/drivers/soc/apple/display-gate.c index 2830a17ae6cafc..53c816e951523a 100644 --- a/drivers/soc/apple/display-gate.c +++ b/drivers/soc/apple/display-gate.c @@ -84,6 +84,15 @@ * display processor's firmware memory. The gate enables a chain once its * processor has that memory and the display subsystem is enabled, before any * device exists (see gate_t6041_max_run()). + * + * On T8132 (apple,t8132) off the M4 26.6.2 firmware path (first the Mac mini, + * J773g, on macOS 27.2), aura hands over external display processors as on the + * J575c: it fills their firmware memory, adds their firmware clocks, and + * enables the display subsystem on iBoot's boot framebuffer. For any + * apple,t8132-dcpext with a fixed dp-phy running the pinned 27.2 image, the + * gate derives the chain from its phandles and enables it in one changeset + * (see gate_t8132_run()). On the M4 26.6.2 firmware path (and on M4 Airs) the + * J713 dcpext routes below apply instead. */ #define pr_fmt(fmt) fmt @@ -108,6 +117,7 @@ #include #include #include +#include #include #include #include @@ -161,6 +171,14 @@ static struct device_node *gate_pmp_values __initdata; */ static const char gate_pmp_uuid[] __initconst = "2F4EB4C4-001B-3ACF-A9A0-68D8E42FC3A7"; +/* + * The T6030 PMP image of the 27.2 (26B123) system firmware, as the J516S ADT + * names it. Its soc-device records are those of the J516S overlay, and the PMP + * report driver checks the running image against the values the boot loader + * passes, so the same PMP support takes either image. + */ +static const char gate_t6030_pmp_uuid_27_2[] __initconst = "5D66805B-E4AD-335E-BDC3-26828C682AAC"; + /* The T8122 PMP image of the 14.x system firmware. */ static const char gate_t8122_pmp_uuid[] __initconst = "3B18C886-4C70-349B-B1C4-70F35DE2C5CD"; @@ -255,6 +273,7 @@ static const struct gate_soc gate_t6030 __initconst = { .dcp_full_name = "dcp@28ec00000", .pmp_values = "/chosen/asahi,t6030-pmp", .pmp_uuid = gate_pmp_uuid, + .pmp_uuid_alt = gate_t6030_pmp_uuid_27_2, .report_compat = "apple,t6030-pmp-v2-report", .disp_entry = "report@7", .pmp_dtbo = __dtbo_t6030_pmp_begin, @@ -362,12 +381,30 @@ static const struct gate_soc gate_t6041_max __initconst = { .run = gate_t6041_max_run, }; +static void __init gate_t8132_run(void); + +/* + * T8132 off the M4 26.6.2 firmware path (the Airs take + * gate_j713_dcpext_routes() before gate_socs[] is walked): enable any + * fixed-DP external display chain (phy-names = "dp-phy") running the pinned + * 27.2 image, as on the J575c. + */ +static const struct gate_soc gate_t8132 __initconst = { + .machine = "apple,t8132", + .prefix = "apple-t8132-display: ", + .name = "T8132", + .dcp_compat = "apple,t8132-dcp", + .display_compat = "apple,t8132-display-subsystem", + .run = gate_t8132_run, +}; + static const struct gate_soc *const gate_socs[] __initconst = { &gate_t6030, &gate_t8122, &gate_t6031, &gate_t6041, &gate_t6041_max, + &gate_t8132, }; /* The SoC this boot runs on, if the gate serves it. */ @@ -1828,6 +1865,8 @@ static void __init gate_describe(void) * alone. apple_t8122_display.dcpext=0 keeps them disabled too. */ static bool gate_t8122_dcpext_requested __initdata = true; +/* The changeset that enabled the dcpext; only the KUnit test reverts it. */ +static struct of_changeset *gate_t8122_dcpext_cs __initdata; static int __init gate_t8122_dcpext_setup(char *arg) { @@ -1883,16 +1922,80 @@ static bool __init gate_node_in(struct device_node *const *nodes, int n, return false; } +/* + * On the 27.2 image the T8122 external processor and its scanout use the + * panel's DMA window (the 1 TiB alias): the display subsystem takes the + * window all its display DARTs share, and the device tree's 14.7 windows for + * the external DARTs (from 0) share none with the panel's. Give @dart and + * @disp_dart the window of the internal processor's DART. + */ +static int __init gate_t8122_dcpext_alias(struct of_changeset *cs, + struct device_node *dart, + struct device_node *disp_dart) +{ + struct device_node *dcp, *panel_dart; + struct device_node *targets[] = { dart, disp_dart }; + const struct property *window; + int i, ret = 0; + + dcp = of_find_compatible_node(NULL, NULL, "apple,t8122-dcp"); + panel_dart = dcp ? of_parse_phandle(dcp, "iommus", 0) : NULL; + of_node_put(dcp); + window = panel_dart ? of_find_property(panel_dart, "apple,dma-range", NULL) : NULL; + /* One window: its start and its size, as the DART driver reads it. */ + if (!window || window->length != 2 * sizeof(u64)) { + of_node_put(panel_dart); + return -ENODEV; + } + + for (i = 0; i < ARRAY_SIZE(targets) && !ret; i++) { + /* Kept for good: the live tree refers to it once applied. */ + struct property *prop = kzalloc_obj(*prop); + void *value = kmemdup(window->value, window->length, GFP_KERNEL); + + if (!prop || !value) { + kfree(prop); + kfree(value); + ret = -ENOMEM; + break; + } + prop->name = "apple,dma-range"; + prop->length = window->length; + prop->value = value; + ret = of_changeset_update_property(cs, targets[i], prop); + if (ret) { + kfree(prop); + kfree(value); + } + } + of_node_put(panel_dart); + return ret; +} + +/* + * Does @np's display DART go into the display subsystem's domain? 1 or 0, + * or -ENODEV on a board that forbids it and has no @fbdma child to mirror + * framebuffers through: the dcpext then has no way to scan them out. + */ +static int __init gate_t8122_dcpext_shares_dart(struct device_node *np, + struct device_node *fbdma) +{ + if (!of_property_read_bool(np, "apple,no-shared-display-dart")) + return 1; + return fbdma ? 0 : -ENODEV; +} + static void __init gate_t8122_dcpext_one(struct device_node *np) { struct device_node *dart = NULL, *mbox = NULL, *piodma = NULL; struct device_node *disp_dart = NULL, *ps = NULL, *entry = NULL, *link; + struct device_node *fbdma = NULL; struct device_node *xbar[GATE_T8122_XBARS] = {}; struct device_node *common[GATE_T8122_XBARS] = {}; struct of_phandle_args args; struct of_changeset *cs; const char *label; - int ret, i, nxbar = 0; + int share_dart, ret, i, nxbar = 0; u32 ready; if (!gate_disabled(np)) { @@ -1900,18 +2003,25 @@ static void __init gate_t8122_dcpext_one(struct device_node *np) return; } if (of_property_read_u32(np, "apple,t8122-dcpext-firmware-ready", &ready) || - ready != 1) { + (ready != 1 && ready != 2)) { gate_ext_refuse(np, "the boot loader did not reserve its firmware"); return; } - if (!gate_ext_firmware_ok(np)) { - gate_ext_refuse(np, "its firmware-compat is not 14.7.0"); + if (!gate_ext_firmware_ok(np) && !apple_t8122_dcpext_v27_2(np)) { + gate_ext_refuse(np, "its firmware is neither 14.7.0 nor the 27.2 image"); return; } if (!of_property_present(np, "memory-region")) { gate_ext_refuse(np, "it has no firmware memory"); goto put; } + fbdma = of_get_available_child_by_name(np, "fbdma"); + share_dart = gate_t8122_dcpext_shares_dart(np, fbdma); + if (share_dart < 0) { + gate_ext_refuse(np, + "apple,no-shared-display-dart without an fbdma child to mirror framebuffers through"); + goto put; + } dart = gate_target(np, "iommus", "#iommu-cells", 1, 5, "apple,t8110-dart"); mbox = gate_target(np, "mboxes", "#mbox-cells", 0, 0, "apple,asc-mailbox-v4"); piodma = of_get_child_by_name(np, "piodma"); @@ -1987,6 +2097,8 @@ static void __init gate_t8122_dcpext_one(struct device_node *np) ret = gate_add_bool(cs, entry, "apple,soc-device-record"); if (!ret) ret = gate_add_bool(cs, entry, "apple,defer-startup-ack"); + if (!ret && apple_t8122_dcpext_v27_2(np)) + ret = gate_t8122_dcpext_alias(cs, dart, disp_dart); if (!ret) ret = of_changeset_update_prop_string(cs, dart, "status", "okay"); if (!ret) @@ -2005,8 +2117,18 @@ static void __init gate_t8122_dcpext_one(struct device_node *np) ret = of_changeset_update_prop_string(cs, np, "status", "okay"); if (!ret) ret = gate_ext_routes(cs, np, "okay"); - if (!ret) + if (!ret && share_dart) { ret = gate_display_add_dart(cs, disp_dart); + /* The shared domain maps what fbdma would, at the same addresses. */ + if (!ret && fbdma) { + ret = of_changeset_update_prop_string(cs, fbdma, "status", "disabled"); + gate_warn("%pOF: display DART %pOF shared with the display subsystem; %pOF disabled\n", + np, disp_dart, fbdma); + } + } else if (!ret) { + gate_info("%pOF: display DART %pOF kept out of the display subsystem; framebuffers are mirrored\n", + np, disp_dart); + } if (!ret) ret = of_changeset_apply(cs); if (ret) { @@ -2015,13 +2137,15 @@ static void __init gate_t8122_dcpext_one(struct device_node *np) gate_ext_refuse(np, "the gate could not enable it"); goto put; } - gate_info("enabled %pOF with its Type-C routes, DARTs, mailbox, %d display crossbar(s) with ATC common power kept on, display DART %pOF in the display subsystem, CPU power floor and PMP DISPEXT request; started by the display driver\n", - np, nxbar, disp_dart); + gate_t8122_dcpext_cs = cs; + gate_info("enabled %pOF with its Type-C routes, DARTs, mailbox, %d display crossbar(s) with ATC common power kept on, display DART %pOF %s the display subsystem, CPU power floor and PMP DISPEXT request; started by the display driver\n", + np, nxbar, disp_dart, share_dart ? "in" : "kept out of"); put: for (i = 0; i < GATE_T8122_XBARS; i++) { of_node_put(common[i]); of_node_put(xbar[i]); } + of_node_put(fbdma); of_node_put(entry); of_node_put(ps); of_node_put(disp_dart); @@ -2260,8 +2384,27 @@ struct gate_staged { const char *dart; /* display DART of this stage */ const char *const *nodes; unsigned int nr; + /* + * If set, the processor (the last of @nodes) whose typec-routes children + * belong to the chain too: one per Type-C port of the board, as its + * device tree describes them. + */ + bool dt_routes; }; +/* The typec-routes node of the processor that ends @st, or NULL. */ +static struct device_node *staged_routes(const struct gate_staged *st) +{ + struct device_node *dcp, *routes; + + if (!st->dt_routes) + return NULL; + dcp = of_find_node_by_path(st->nodes[st->nr - 1]); + routes = dcp ? of_get_child_by_name(dcp, "typec-routes") : NULL; + of_node_put(dcp); + return routes; +} + static const char *const t6041_hdmi_nodes[] = { /* ATC3 power, PMP DISPEXT0 request, DISPEXT0, AOP pins, PHY, crossbar, DARTs, mailbox, dcpext0 */ "/power-management@502800000/power-controller@408", @@ -2456,6 +2599,32 @@ static bool staged_ready(const struct gate_staged *st) } of_node_put(np); } + if (st->dt_routes) { + struct device_node *route; + unsigned int nr_routes = 0; + + np = staged_routes(st); + if (!np) { + staged_err("%s/typec-routes: no such node, nothing enabled\n", + st->nodes[st->nr - 1]); + return false; + } + for_each_child_of_node(np, route) { + if (of_device_is_available(route)) { + staged_err("%pOF: already enabled, nothing changed\n", route); + of_node_put(route); + of_node_put(np); + return false; + } + nr_routes++; + } + of_node_put(np); + if (!nr_routes) { + staged_err("%s/typec-routes: no routes, nothing enabled\n", + st->nodes[st->nr - 1]); + return false; + } + } return true; } @@ -3150,10 +3319,23 @@ static const char *const t6041_max_usbc2_nodes[] = { "/dcp@606e00000", }; +/* + * The third USB-C processor of the M4 Max boards, dcpext3, as dcpext2's chain. + * Its routes are the ones the device tree gives it, one per Type-C port: three + * on the J614c/J616c, four on the J575c. + */ +static const char *const t6041_max_usbc3_nodes[] = { + "/iommu@306340000", + "/iommu@306300000", + "/mailbox@306e08000", + "/dcp@306e00000", +}; + static const struct gate_staged t6041_max_stages[] = { { "/iommu@3a2300000", t6041_max_hdmi_nodes, ARRAY_SIZE(t6041_max_hdmi_nodes) }, { "/iommu@602300000", t6041_max_usbc_nodes, ARRAY_SIZE(t6041_max_usbc_nodes) }, { "/iommu@606300000", t6041_max_usbc2_nodes, ARRAY_SIZE(t6041_max_usbc2_nodes) }, + { "/iommu@306300000", t6041_max_usbc3_nodes, ARRAY_SIZE(t6041_max_usbc3_nodes), true }, }; /* @@ -3233,7 +3415,65 @@ static const struct gate_staged *t6041_max_stage(unsigned int i) /* Applied, they stay: the live tree refers to them. Only the KUnit test reverts them. */ static struct of_changeset t6041_max_cs[ARRAY_SIZE(t6041_max_stages)]; -/* Enable every node of stage @i and put its display DART into the display subsystem's iommus. */ +/* + * Whether @np needs a power domain that stays disabled: neither enabled nor one of the nodes + * stage @st enables. + */ +static bool __init t6041_max_needs_off_domain(const struct gate_staged *st, struct device_node *np) +{ + struct of_phandle_args args; + bool off = false; + unsigned int n; + int i; + + for (i = 0; !off && !of_parse_phandle_with_args(np, "power-domains", "#power-domain-cells", + i, &args); i++) { + off = !of_device_is_available(args.np); + for (n = 0; off && n < st->nr; n++) { + struct device_node *dn = of_find_node_by_path(st->nodes[n]); + + off = dn != args.np; + of_node_put(dn); + } + of_node_put(args.np); + } + return off; +} + +/* Enable each typec-routes child of @st's processor in @cs, if @st takes its routes from the DT. */ +static int __init t6041_max_enable_routes(struct of_changeset *cs, const struct gate_staged *st) +{ + struct device_node *routes, *route; + unsigned int nr_routes = 0; + int ret = 0; + + if (!st->dt_routes) + return 0; + routes = staged_routes(st); + if (!routes) + return -ENODEV; + for_each_child_of_node(routes, route) { + ret = of_changeset_update_prop_string(cs, route, "status", "okay"); + if (ret) { + of_node_put(route); + break; + } + nr_routes++; + } + of_node_put(routes); + if (!ret && !nr_routes) + return -ENODEV; + return ret; +} + +/* + * Enable every node of stage @i and put its display DART into the display subsystem's iommus. + * The in-tree trees give the chains no DISPEXT power domain: they are on as iBoot left them. A + * tree that does describe them (the J616c's bring-up EL2 tree: dispextN_fe, and PMP report + * entries above them, all disabled) loses the property on the chain's nodes here, or each + * device would wait for a domain provider that never comes and give up at the deferred probe + * timeout, and the display subsystem with them. + */ static int __init t6041_max_apply(unsigned int i, struct device_node *display) { const struct gate_staged *st = t6041_max_stage(i); @@ -3247,8 +3487,16 @@ static int __init t6041_max_apply(unsigned int i, struct device_node *display) ret = np ? gate_iommus_append(cs, display, np) : -ENODEV; of_node_put(np); for (n = 0; !ret && n < st->nr; n++) { + /* The routes go in just before their processor, the last node. */ + if (n == st->nr - 1) + ret = t6041_max_enable_routes(cs, st); + if (ret) + break; np = of_find_node_by_path(st->nodes[n]); ret = np ? of_changeset_update_prop_string(cs, np, "status", "okay") : -ENODEV; + if (!ret && t6041_max_needs_off_domain(st, np)) + ret = of_changeset_remove_property(cs, np, + of_find_property(np, "power-domains", NULL)); of_node_put(np); } if (!ret) @@ -3398,6 +3646,355 @@ static void __init gate_j713_dcpext_routes(void) gate_cs_free(cs); } +/* The display subsystem's iommus become <@dart 0>, whatever they were. */ +static int __init gate_iommus_set(struct of_changeset *cs, struct device_node *display, + struct device_node *dart) +{ + struct property *prop; + __be32 *value; + + if (!dart->phandle) + return -EINVAL; + prop = kzalloc_obj(*prop); + value = kmalloc(2 * sizeof(*value), GFP_KERNEL); + if (!prop || !value) { + kfree(prop); + kfree(value); + return -ENOMEM; + } + value[0] = cpu_to_be32(dart->phandle); + value[1] = cpu_to_be32(0); + prop->name = "iommus"; + prop->length = 2 * sizeof(*value); + prop->value = value; + return of_changeset_update_property(cs, display, prop); +} + +enum { + T8132_HDMI_PHY, + T8132_HDMI_FW_DART, + T8132_HDMI_DISP_DART, + T8132_HDMI_MBOX, + T8132_HDMI_PIODMA, + T8132_HDMI_DCP, + T8132_HDMI_NR, +}; + +/* + * Check that every memory-region of @np is an available apple,asc-mem node, + * as staged_firmware_memory() does for path-addressed stages. + */ +static bool __init staged_node_firmware_memory(struct device_node *np) +{ + struct device_node *chosen, *region; + int i, n; + u32 record[2]; + + n = of_count_phandle_with_args(np, "memory-region", NULL); + for (i = 0; i < n; i++) { + region = of_parse_phandle(np, "memory-region", i); + if (region && of_device_is_available(region) && + of_device_is_compatible(region, "apple,asc-mem")) { + of_node_put(region); + continue; + } + of_node_put(region); + n = -ENODEV; + break; + } + if (n > 0) + return true; + chosen = of_find_node_by_path("/chosen"); + if (chosen && !of_property_read_u32_array(chosen, "m4,dcpext", record, 2)) + staged_err("%pOF: no firmware memory (loader record <%u %u>), nothing enabled\n", + np, record[0], record[1]); + else + staged_err("%pOF: no firmware memory, nothing enabled\n", np); + of_node_put(chosen); + return false; +} + +/* + * A T8132 internal display processor handed over with the 27.2 (26B123) image + * and firmware-27 clock metadata (apple,clock-ids): present on a laptop with + * an internal panel (e.g. a 14-inch MacBook Pro), absent on a headless Mac + * mini whose main DCP is left running idle. + */ +static bool __init gate_t8132_dcp_v27_2(const struct device_node *np) +{ + return apple_dcp_image_v27_2(np, "apple,t8132-dcp", + APPLE_T8132_DCP_26B123_UUID) && + of_property_present(np, "apple,clock-ids"); +} + +static void __init gate_t8132_put_nodes(struct device_node *nodes[T8132_HDMI_NR]) +{ + unsigned int i; + + for (i = 0; i < T8132_HDMI_NR; i++) { + of_node_put(nodes[i]); + nodes[i] = NULL; + } +} + +/* + * Derive a fixed-DP T8132 dcpext's chain from its own DT phandles: the dp-phy + * PHY, firmware DART (iommus), display DART (piodma's iommus), mailbox + * (mboxes), piodma child, then the dcpext node itself. + */ +static int __init gate_t8132_resolve_fixed_dp(struct device_node *dcp, + int phy_idx, + struct device_node *nodes[T8132_HDMI_NR]) +{ + struct of_phandle_args args; + + memset(nodes, 0, T8132_HDMI_NR * sizeof(*nodes)); + + if (of_parse_phandle_with_args(dcp, "phys", "#phy-cells", phy_idx, &args)) + goto fail; + nodes[T8132_HDMI_PHY] = args.np; + + if (of_parse_phandle_with_args(dcp, "iommus", "#iommu-cells", 0, &args)) + goto fail; + nodes[T8132_HDMI_FW_DART] = args.np; + + if (of_parse_phandle_with_args(dcp, "mboxes", "#mbox-cells", 0, &args)) + goto fail; + nodes[T8132_HDMI_MBOX] = args.np; + + nodes[T8132_HDMI_PIODMA] = of_get_child_by_name(dcp, "piodma"); + if (!nodes[T8132_HDMI_PIODMA]) + goto fail; + + if (of_parse_phandle_with_args(nodes[T8132_HDMI_PIODMA], "iommus", + "#iommu-cells", 0, &args)) + goto fail; + nodes[T8132_HDMI_DISP_DART] = args.np; + + nodes[T8132_HDMI_DCP] = of_node_get(dcp); + return 0; + +fail: + gate_t8132_put_nodes(nodes); + return -EINVAL; +} + +/* Every node of @nodes is distinct and still disabled, and its processor has firmware memory. */ +static bool __init gate_t8132_fixed_dp_ready(struct device_node *nodes[T8132_HDMI_NR]) +{ + unsigned int i, j; + + if (!staged_node_firmware_memory(nodes[T8132_HDMI_DCP])) + return false; + for (i = 0; i < T8132_HDMI_NR; i++) { + if (!nodes[i]) + return false; + for (j = 0; j < i; j++) { + if (nodes[j] == nodes[i]) { + staged_err("%pOF: duplicate node in chain, nothing enabled\n", + nodes[i]); + return false; + } + } + if (of_device_is_available(nodes[i])) { + staged_err("%pOF: already enabled, nothing changed\n", nodes[i]); + return false; + } + } + /* + * The processor runs on through the handover, behind DARTs the boot + * loader leaves locked: adopting it needs apple-dart to keep their + * firmware roots. Off that, the firmware DART's probe fails (-EBUSY on + * the J773g), the processor and its PHY never probe, and the display + * subsystem never binds. + */ + if (!apple_dart_keeps_locked_roots(nodes[T8132_HDMI_FW_DART]) || + !apple_dart_keeps_locked_roots(nodes[T8132_HDMI_DISP_DART])) { + staged_info("%pOF: the firmware roots of %pOF and %pOF are not kept, HDMI left off\n", + nodes[T8132_HDMI_DCP], nodes[T8132_HDMI_FW_DART], + nodes[T8132_HDMI_DISP_DART]); + return false; + } + return true; +} + +/* + * A headless T8132 (no internal display processor handed over on 27.2) whose + * HDMI chain stays off: the display subsystem the boot loader enabled for it + * has no processor left to bind, since the main DCP is the M4 backend's on its + * firmware path only (apple_dcp_usable()). Left enabled it never registers, + * and the GPU, whose first start follows a handed-over display, waits for it + * for good. Disable it, as when the boot loader hands over no display: the + * boot framebuffer stays, and the GPU starts on it. Its DART (disp0's), which + * the boot loader enabled with it, goes too unless the main DCP, whose piodma + * also maps through it, is enabled. + */ +static void __init gate_t8132_display_off(void) +{ + struct device_node *display, *internal; + struct of_phandle_args args; + struct of_changeset *cs; + bool panel, internal_on; + int i, ret; + + display = of_find_node_by_path("disp0"); + if (!display) + display = of_find_compatible_node(NULL, NULL, gate_soc->display_compat); + if (!display || !of_device_is_compatible(display, gate_soc->display_compat) || + !of_device_is_available(display)) { + of_node_put(display); + return; + } + internal = of_find_node_by_path("dcp"); + if (!internal) + internal = of_find_compatible_node(NULL, NULL, gate_soc->dcp_compat); + panel = gate_t8132_dcp_v27_2(internal); + internal_on = of_device_is_available(internal); + of_node_put(internal); + if (panel) { + of_node_put(display); + return; + } + + cs = gate_cs_alloc(); + if (!cs) { + staged_err("%pOF: could not allocate changeset\n", display); + of_node_put(display); + return; + } + ret = of_changeset_update_prop_string(cs, display, "status", "disabled"); + for (i = 0; !ret && !internal_on && + !of_parse_phandle_with_args(display, "iommus", "#iommu-cells", i, &args); i++) { + if (of_device_is_available(args.np)) + ret = of_changeset_update_prop_string(cs, args.np, "status", "disabled"); + of_node_put(args.np); + } + if (!ret) + ret = of_changeset_apply(cs); + if (ret) { + gate_cs_free(cs); + staged_err("%pOF: could not disable it without HDMI: %d\n", display, ret); + } else { + staged_info("no HDMI chain and no internal display: %pOF disabled, boot framebuffer kept\n", + display); + } + of_node_put(display); +} + +/* + * T8132 on macOS 27.2 (off the M4 26.6.2 firmware path): any apple,t8132-dcpext + * wired to a fixed DP PHY (phy-names = "dp-phy", e.g. the J773g HDMI port) + * runs through the firmware-27 backend (apple_t8132_dcpext_v27_2()). Its chain + * is derived from its DT phandles and enabled in one changeset once aura has + * given it firmware memory and enabled the display subsystem, and only for the + * pinned 27.2 image. + * + * When the main DCP is also handed over on 27.2 (a T8132 laptop with an + * internal panel), dispext's display DART is appended to the display + * subsystem's iommus so the internal panel keeps its DART. When the main DCP + * is not handed over (a headless Mac mini), disp0's DART is left unprobed by + * apple-dart and would hold the display subsystem's probe forever, so iommus + * is replaced with dispext's DART instead. + * + * With no chain enabled (no handover, a refused one, or nomodeset), a headless + * T8132 boots as without this gate: see gate_t8132_display_off(). + */ +static void __init gate_t8132_run(void) +{ + struct device_node *display = NULL, *internal, *dcp; + struct device_node *nodes[T8132_HDMI_NR]; + bool append_dart = false; + bool display_checked = false; + bool enabled = false; + unsigned int i; + int phy_idx, ret; + + staged_prefix = gate_soc->prefix; + if (IS_ENABLED(CONFIG_VIDEO) && video_firmware_drivers_only()) { + gate_t8132_display_off(); + return; + } + + for_each_compatible_node(dcp, NULL, "apple,t8132-dcpext") { + struct of_changeset *cs; + + phy_idx = of_property_match_string(dcp, "phy-names", "dp-phy"); + if (phy_idx < 0) + continue; + + if (!apple_t8132_dcpext_v27_2(dcp)) { + if (of_property_present(dcp, "apple,firmware-compat")) + staged_info("%pOF: not the 27.2 (26B123) image, HDMI left off\n", + dcp); + continue; + } + + if (!display_checked) { + display_checked = true; + display = of_find_node_by_path("disp0"); + if (!display) + display = of_find_compatible_node(NULL, NULL, + gate_soc->display_compat); + if (!display || !of_device_is_compatible(display, + gate_soc->display_compat)) { + staged_err("no display subsystem, HDMI left off\n"); + of_node_put(display); + of_node_put(dcp); + return; + } + if (!of_device_is_available(display)) { + staged_info("display subsystem not enabled, HDMI left off\n"); + of_node_put(display); + of_node_put(dcp); + return; + } + internal = of_find_node_by_path("dcp"); + if (!internal) + internal = of_find_compatible_node(NULL, NULL, + gate_soc->dcp_compat); + append_dart = gate_t8132_dcp_v27_2(internal); + of_node_put(internal); + } + + if (gate_t8132_resolve_fixed_dp(dcp, phy_idx, nodes)) { + staged_err("%pOF: incomplete fixed-DP chain, HDMI left off\n", dcp); + continue; + } + if (!gate_t8132_fixed_dp_ready(nodes)) { + gate_t8132_put_nodes(nodes); + continue; + } + + cs = gate_cs_alloc(); + if (!cs) { + staged_err("%pOF: could not allocate changeset\n", dcp); + gate_t8132_put_nodes(nodes); + continue; + } + ret = append_dart ? + gate_iommus_append(cs, display, nodes[T8132_HDMI_DISP_DART]) : + gate_iommus_set(cs, display, nodes[T8132_HDMI_DISP_DART]); + for (i = 0; !ret && i < T8132_HDMI_NR; i++) + ret = of_changeset_update_prop_string(cs, nodes[i], "status", "okay"); + if (!ret) + ret = of_changeset_apply(cs); + if (ret) { + gate_cs_free(cs); + staged_err("%pOF: could not enable the HDMI chain: %d\n", dcp, ret); + } else { + staged_info("%pOF enabled for HDMI; display subsystem %s %pOF\n", dcp, + append_dart ? "appended" : "on", + nodes[T8132_HDMI_DISP_DART]); + append_dart = true; + enabled = true; + } + gate_t8132_put_nodes(nodes); + } + of_node_put(display); + if (!enabled) + gate_t8132_display_off(); +} + /* Runs before of_platform_default_populate_init() at arch_initcall_sync. */ static int __init apple_display_gate(void) { diff --git a/drivers/soc/apple/dockchannel-test.c b/drivers/soc/apple/dockchannel-test.c new file mode 100644 index 00000000000000..14cc35ae5d5003 --- /dev/null +++ b/drivers/soc/apple/dockchannel-test.c @@ -0,0 +1,894 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple DockChannel FIFO. + * + * Included at the end of dockchannel.c. The FIFO data and threshold + * registers are modelled behind static stubs on the register accessors: + * TX_FREE and RX_COUNT live in a buffer of kernel memory (so that the + * receive interrupt thread, which the stubs do not redirect, reads the same + * counts), the bytes written to the TX FIFO are logged and the RX FIFO is a + * queue of bytes. Writing a threshold register can add room or data and + * raise the FIFO's interrupt, which is a simulated interrupt handled by the + * driver's own handlers. The interrupt controller functions run on a buffer + * of kernel memory. Nothing touches hardware. + */ + +#include +#include +#include +#include +#include +#include + +#define DCT_FIFO_SIZE 16 +#define DCT_LOG 256 +#define DCT_STEPS 8 +#define DCT_GUARD 256 +#define DCT_POISON 0xee +/* Past this many model violations, abort the case: a runaway loop. */ +#define DCT_RUNAWAY 32 +/* No case reads a count register more often than this. */ +#define DCT_MAX_POLLS 64 + +struct dct_ctx { + struct dockchannel dc; + u8 *cfg; + u8 *data; + u8 *irqregs; + + struct fwnode_handle *fwnode; + struct irq_domain *domain; + struct task_struct *worker; + atomic_t fire_tx; + atomic_t fire_rx; + + /* TX FIFO: what was written, and how ('W' word, 'B' byte). */ + u8 tx_log[DCT_LOG]; + unsigned int tx_len; + char tx_ops[DCT_LOG + 1]; + unsigned int tx_nops; + unsigned int tx_free_reads; + /* Room added by each TX threshold write; each also raises the IRQ. */ + unsigned int tx_refill[DCT_STEPS]; + unsigned int tx_nrefill; + unsigned int tx_refill_pos; + u32 tx_thresh[DCT_STEPS]; + unsigned int tx_nthresh; + + /* RX FIFO: rx_q[rx_pos..rx_len) is queued, RX_COUNT of it visible. */ + u8 rx_q[DCT_LOG]; + unsigned int rx_len; + unsigned int rx_pos; + char rx_ops[DCT_LOG + 1]; + unsigned int rx_nops; + unsigned int rx_count_reads; + unsigned int rx_refill[DCT_STEPS]; + unsigned int rx_nrefill; + unsigned int rx_refill_pos; + u32 rx_thresh[DCT_STEPS]; + unsigned int rx_nthresh; + + /* Accesses the FIFO would not allow (write without room, etc.). */ + unsigned int violations; + + /* Receive callback (runs in the RX interrupt thread). */ + struct completion cb_done; + atomic_t cb_calls; + size_t cb_avail; + void *cb_cookie; + bool cb_recv; + u8 cb_buf[4]; + int cb_ret; +}; + +static u32 dct_reg(struct dct_ctx *ctx, unsigned int off) +{ + return READ_ONCE(*(u32 *)(ctx->data + off)); +} + +static void dct_set_reg(struct dct_ctx *ctx, unsigned int off, u32 val) +{ + WRITE_ONCE(*(u32 *)(ctx->data + off), val); +} + +/* Too many bad accesses: the driver is in a runaway loop, stop the case. */ +static void dct_violation(struct dct_ctx *ctx) +{ + if (++ctx->violations > DCT_RUNAWAY) + KUNIT_FAIL_AND_ABORT(kunit_get_current_test(), + "runaway FIFO access loop"); +} + +static u32 dct_rx_pop(struct dct_ctx *ctx, unsigned int n, char op) +{ + u32 avail = dct_reg(ctx, DATA_RX_COUNT); + u32 val = 0; + unsigned int i; + + if (avail < n || ctx->rx_pos + n > ctx->rx_len) { + dct_violation(ctx); + return 0xdeadbeef; + } + for (i = 0; i < n; i++) + val |= (u32)ctx->rx_q[ctx->rx_pos++] << (8 * i); + dct_set_reg(ctx, DATA_RX_COUNT, avail - n); + if (ctx->rx_nops < DCT_LOG) + ctx->rx_ops[ctx->rx_nops++] = op; + + return val; +} + +static u32 dct_readl(void __iomem *addr) +{ + struct dct_ctx *ctx = kunit_get_current_test()->priv; + long off = (u8 __force *)addr - ctx->data; + + switch (off) { + case DATA_TX_FREE: + if (++ctx->tx_free_reads > DCT_MAX_POLLS) + dct_violation(ctx); + return dct_reg(ctx, DATA_TX_FREE); + case DATA_RX_COUNT: + if (++ctx->rx_count_reads > DCT_MAX_POLLS) + dct_violation(ctx); + return dct_reg(ctx, DATA_RX_COUNT); + case DATA_RX32: + return dct_rx_pop(ctx, 4, 'W'); + case DATA_RX8: + /* The byte comes in bits [15:8]; fill the other bits with junk. */ + return 0x5a0000a5 | (dct_rx_pop(ctx, 1, 'B') & 0xff) << 8; + default: + ctx->violations++; + return 0; + } +} + +static void dct_tx_push(struct dct_ctx *ctx, u32 val, unsigned int n, char op) +{ + u32 room = dct_reg(ctx, DATA_TX_FREE); + unsigned int i; + + if (room < n || ctx->tx_len + n > DCT_LOG) { + dct_violation(ctx); + return; + } + for (i = 0; i < n; i++) + ctx->tx_log[ctx->tx_len++] = val >> (8 * i); + dct_set_reg(ctx, DATA_TX_FREE, room - n); + if (ctx->tx_nops < DCT_LOG) + ctx->tx_ops[ctx->tx_nops++] = op; +} + +static void dct_writel(u32 val, void __iomem *addr) +{ + struct dct_ctx *ctx = kunit_get_current_test()->priv; + u8 *p = (u8 __force *)addr; + + if (p == ctx->cfg + CONFIG_TX_THRESH) { + if (ctx->tx_nthresh < DCT_STEPS) + ctx->tx_thresh[ctx->tx_nthresh++] = val; + if (ctx->tx_refill_pos < ctx->tx_nrefill) { + dct_set_reg(ctx, DATA_TX_FREE, dct_reg(ctx, DATA_TX_FREE) + + ctx->tx_refill[ctx->tx_refill_pos++]); + atomic_set(&ctx->fire_tx, 1); + } + } else if (p == ctx->cfg + CONFIG_RX_THRESH) { + if (ctx->rx_nthresh < DCT_STEPS) + ctx->rx_thresh[ctx->rx_nthresh++] = val; + if (ctx->rx_refill_pos < ctx->rx_nrefill) { + dct_set_reg(ctx, DATA_RX_COUNT, dct_reg(ctx, DATA_RX_COUNT) + + ctx->rx_refill[ctx->rx_refill_pos++]); + atomic_set(&ctx->fire_rx, 1); + } + } else if (p == ctx->data + DATA_TX32) { + dct_tx_push(ctx, val, 4, 'W'); + } else { + ctx->violations++; + } +} + +static void dct_writeb(u8 val, void __iomem *addr) +{ + struct dct_ctx *ctx = kunit_get_current_test()->priv; + + if ((u8 __force *)addr == ctx->data + DATA_TX8) + dct_tx_push(ctx, val, 1, 'B'); + else + ctx->violations++; +} + +/* Raise a FIFO interrupt once the driver has enabled it. */ +static void dct_try_fire(atomic_t *fire, unsigned int virq) +{ + struct irq_data *d = irq_get_irq_data(virq); + + if (!atomic_read(fire) || irqd_irq_disabled(d) || irqd_irq_masked(d)) + return; + atomic_set(fire, 0); + irq_set_irqchip_state(virq, IRQCHIP_STATE_PENDING, true); +} + +static int dct_worker(void *arg) +{ + struct dct_ctx *ctx = arg; + + while (!kthread_should_stop()) { + dct_try_fire(&ctx->fire_tx, ctx->dc.tx_irq); + dct_try_fire(&ctx->fire_rx, ctx->dc.rx_irq); + usleep_range(200, 400); + } + + return 0; +} + +static void dct_fire_now(struct kunit *test, unsigned int virq) +{ + struct irq_data *d = irq_get_irq_data(virq); + + KUNIT_ASSERT_FALSE(test, irqd_irq_disabled(d)); + KUNIT_ASSERT_EQ(test, irq_set_irqchip_state(virq, IRQCHIP_STATE_PENDING, true), 0); +} + +static bool dct_irq_enabled(unsigned int virq) +{ + return !irqd_irq_disabled(irq_get_irq_data(virq)); +} + +static int dct_init(struct kunit *test) +{ + struct dct_ctx *ctx; + int irq, ret; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->cfg = kunit_kzalloc(test, 0x10, GFP_KERNEL); + ctx->data = kunit_kzalloc(test, 0x40, GFP_KERNEL); + ctx->irqregs = kunit_kzalloc(test, 0x10, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->cfg); + KUNIT_ASSERT_NOT_NULL(test, ctx->data); + KUNIT_ASSERT_NOT_NULL(test, ctx->irqregs); + + ctx->dc.config_base = (void __force __iomem *)ctx->cfg; + ctx->dc.data_base = (void __force __iomem *)ctx->data; + ctx->dc.fifo_size = DCT_FIFO_SIZE; + init_completion(&ctx->dc.tx_comp); + init_completion(&ctx->dc.rx_comp); + init_completion(&ctx->cb_done); + test->priv = ctx; + + ctx->fwnode = irq_domain_alloc_named_fwnode("dockchannel-kunit"); + KUNIT_ASSERT_NOT_NULL(test, ctx->fwnode); + ctx->domain = irq_domain_create_sim(ctx->fwnode, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(ctx->domain)); + + irq = irq_create_mapping(ctx->domain, 0); + KUNIT_ASSERT_GT(test, irq, 0); + ctx->dc.tx_irq = irq; + irq = irq_create_mapping(ctx->domain, 1); + KUNIT_ASSERT_GT(test, irq, 0); + ctx->dc.rx_irq = irq; + + /* As dockchannel_init() requests them. */ + ret = request_irq(ctx->dc.tx_irq, dockchannel_tx_irq, IRQF_NO_AUTOEN, + "dockchannel-kunit-tx", &ctx->dc); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = request_threaded_irq(ctx->dc.rx_irq, dockchannel_rx_irq, + dockchannel_rx_irq_thread, + IRQF_NO_AUTOEN | IRQF_NO_SUSPEND, + "dockchannel-kunit-rx", &ctx->dc); + if (ret) + free_irq(ctx->dc.tx_irq, &ctx->dc); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->worker = kthread_run(dct_worker, ctx, "dockchannel-kunit"); + KUNIT_ASSERT_FALSE(test, IS_ERR(ctx->worker)); + + kunit_activate_static_stub(test, dockchannel_readl, dct_readl); + kunit_activate_static_stub(test, dockchannel_writel, dct_writel); + kunit_activate_static_stub(test, dockchannel_writeb, dct_writeb); + + return 0; +} + +static void dct_exit(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + + if (!ctx || !ctx->domain || IS_ERR(ctx->domain)) + goto fwnode; + + if (ctx->worker && !IS_ERR(ctx->worker)) { + kthread_stop(ctx->worker); + free_irq(ctx->dc.rx_irq, &ctx->dc); + free_irq(ctx->dc.tx_irq, &ctx->dc); + } + if (ctx->dc.rx_irq > 0) + irq_dispose_mapping(ctx->dc.rx_irq); + if (ctx->dc.tx_irq > 0) + irq_dispose_mapping(ctx->dc.tx_irq); + irq_domain_remove_sim(ctx->domain); +fwnode: + if (ctx && ctx->fwnode) + irq_domain_free_fwnode(ctx->fwnode); +} + +static void dct_fill(u8 *buf, unsigned int len, u8 seed) +{ + unsigned int i; + + for (i = 0; i < len; i++) + buf[i] = seed + 7 * i; +} + +static void dct_queue_rx(struct dct_ctx *ctx, unsigned int len, unsigned int visible) +{ + dct_fill(ctx->rx_q, len, 0x31); + ctx->rx_len = len; + dct_set_reg(ctx, DATA_RX_COUNT, visible); +} + +static void dct_expect_guard(struct kunit *test, const u8 *guard, unsigned int len) +{ + unsigned int i, bad = 0; + + for (i = 0; i < len; i++) + bad += guard[i] != DCT_POISON; + KUNIT_EXPECT_EQ_MSG(test, bad, 0, "bytes written past the caller's buffer"); +} + +/* TX */ + +static void dct_send_whole_words(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[8]; + + dct_fill(buf, sizeof(buf), 1); + dct_set_reg(ctx, DATA_TX_FREE, 64); + + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 8); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "WW"); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 8); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 8); + KUNIT_EXPECT_EQ(test, dct_reg(ctx, DATA_TX_FREE), 56); + KUNIT_EXPECT_EQ(test, ctx->tx_nthresh, 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_tail_bytes(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[7]; + + dct_fill(buf, sizeof(buf), 0x80); + dct_set_reg(ctx, DATA_TX_FREE, 64); + + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 7); + /* One little-endian word, then the three tail bytes in order. */ + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "WBBB"); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 7); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 7); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_short(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[3] = { 0x10, 0x20, 0x30 }; + + dct_set_reg(ctx, DATA_TX_FREE, 64); + + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 3); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "BBB"); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 3); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 3); +} + +static void dct_send_unaligned_source(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[16]; + + dct_fill(buf, sizeof(buf), 0x42); + dct_set_reg(ctx, DATA_TX_FREE, 64); + + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf + 1, 9), 9); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "WWB"); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 9); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf + 1, 9); +} + +static void dct_send_exact_room(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[10]; + + dct_fill(buf, sizeof(buf), 3); + dct_set_reg(ctx, DATA_TX_FREE, sizeof(buf)); + + /* Exactly full: no wait, no threshold write. */ + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 10); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "WWBB"); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 10); + KUNIT_EXPECT_EQ(test, dct_reg(ctx, DATA_TX_FREE), 0); + KUNIT_EXPECT_EQ(test, ctx->tx_nthresh, 0); + KUNIT_EXPECT_EQ(test, ctx->tx_free_reads, 1); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_partial_room(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[10]; + + dct_fill(buf, sizeof(buf), 9); + dct_set_reg(ctx, DATA_TX_FREE, 6); + ctx->tx_refill[0] = 8; + ctx->tx_nrefill = 1; + + /* + * 6 bytes fit (a word and two bytes, never a word into 2 bytes of + * room), then the FIFO is full: wait for the 4 that are left. + */ + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 10); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "WBBW"); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 10); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 10); + KUNIT_ASSERT_EQ(test, ctx->tx_nthresh, 1); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[0], 4); + KUNIT_EXPECT_EQ(test, dct_reg(ctx, DATA_TX_FREE), 4); + KUNIT_EXPECT_FALSE(test, dct_irq_enabled(ctx->dc.tx_irq)); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_threshold(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[40]; + + dct_fill(buf, sizeof(buf), 0x11); + ctx->tx_refill[0] = 16; + ctx->tx_refill[1] = 20; + ctx->tx_refill[2] = 4; + ctx->tx_nrefill = 3; + + /* Half the FIFO while more is left, then exactly what is left. */ + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 40); + KUNIT_ASSERT_EQ(test, ctx->tx_nthresh, 3); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[0], DCT_FIFO_SIZE / 2); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[1], DCT_FIFO_SIZE / 2); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[2], 4); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 40); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 40); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_byte_room(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[4] = { 0xa1, 0xb2, 0xc3, 0xd4 }; + + /* Room for one byte at a time: never a word write. */ + dct_set_reg(ctx, DATA_TX_FREE, 1); + ctx->tx_refill[0] = 1; + ctx->tx_refill[1] = 1; + ctx->tx_refill[2] = 1; + ctx->tx_nrefill = 3; + + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 4); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "BBBB"); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 4); + KUNIT_ASSERT_EQ(test, ctx->tx_nthresh, 3); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[0], 3); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[1], 2); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[2], 1); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_spurious_wakeup(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[5]; + + dct_fill(buf, sizeof(buf), 0x55); + /* The first interrupt comes with no room: wait again. */ + ctx->tx_refill[0] = 0; + ctx->tx_refill[1] = 8; + ctx->tx_nrefill = 2; + + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 5); + KUNIT_ASSERT_EQ(test, ctx->tx_nthresh, 2); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[0], 5); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[1], 5); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "WB"); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 5); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_timeout(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[4] = { 1, 2, 3, 4 }; + + /* Nothing ever drains the FIFO. */ + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 0); + KUNIT_ASSERT_EQ(test, ctx->tx_nthresh, 1); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[0], 4); + KUNIT_EXPECT_FALSE(test, dct_irq_enabled(ctx->dc.tx_irq)); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_zero(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[1] = { 0 }; + + dct_set_reg(ctx, DATA_TX_FREE, 64); + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, 0), 0); + KUNIT_EXPECT_EQ(test, ctx->tx_free_reads, 0); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 0); + KUNIT_EXPECT_EQ(test, ctx->tx_nthresh, 0); +} + +/* RX */ + +static void dct_recv_words_and_tail(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 7 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 7 + DCT_GUARD); + dct_queue_rx(ctx, 7, 7); + + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 7), 7); + KUNIT_EXPECT_STREQ(test, ctx->rx_ops, "WBBB"); + /* Word unpacked little-endian, tail bytes taken from bits [15:8]. */ + KUNIT_EXPECT_MEMEQ(test, buf, ctx->rx_q, 7); + dct_expect_guard(test, buf + 7, DCT_GUARD); + KUNIT_EXPECT_EQ(test, dct_reg(ctx, DATA_RX_COUNT), 0); + KUNIT_EXPECT_EQ(test, ctx->rx_nthresh, 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_recv_count_exceeds_buffer(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 5 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 5 + DCT_GUARD); + dct_queue_rx(ctx, 64, 64); + + /* 64 bytes waiting, room for 5: take exactly 5, leave 59. */ + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 5), 5); + KUNIT_EXPECT_STREQ(test, ctx->rx_ops, "WB"); + KUNIT_EXPECT_MEMEQ(test, buf, ctx->rx_q, 5); + dct_expect_guard(test, buf + 5, DCT_GUARD); + KUNIT_EXPECT_EQ(test, ctx->rx_pos, 5); + KUNIT_EXPECT_EQ(test, dct_reg(ctx, DATA_RX_COUNT), 59); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_recv_all_ones_count(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 6 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 6 + DCT_GUARD); + /* A count register that reads all ones must not size the copy. */ + dct_queue_rx(ctx, 8, 0xffffffff); + + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 6), 6); + KUNIT_EXPECT_MEMEQ(test, buf, ctx->rx_q, 6); + dct_expect_guard(test, buf + 6, DCT_GUARD); + KUNIT_EXPECT_EQ(test, ctx->rx_pos, 6); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_recv_unaligned_dest(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 3 + 9 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 3 + 9 + DCT_GUARD); + dct_queue_rx(ctx, 9, 9); + + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf + 3, 9), 9); + KUNIT_EXPECT_STREQ(test, ctx->rx_ops, "WWB"); + dct_expect_guard(test, buf, 3); + KUNIT_EXPECT_MEMEQ(test, buf + 3, ctx->rx_q, 9); + dct_expect_guard(test, buf + 12, DCT_GUARD); +} + +static void dct_recv_partial_waits(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 9 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 9 + DCT_GUARD); + /* 3 of 9 bytes there; the rest comes with the threshold interrupt. */ + dct_queue_rx(ctx, 9, 3); + ctx->rx_refill[0] = 6; + ctx->rx_nrefill = 1; + + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 9), 9); + KUNIT_EXPECT_STREQ(test, ctx->rx_ops, "BBBWBB"); + KUNIT_EXPECT_MEMEQ(test, buf, ctx->rx_q, 9); + dct_expect_guard(test, buf + 9, DCT_GUARD); + KUNIT_ASSERT_EQ(test, ctx->rx_nthresh, 1); + KUNIT_EXPECT_EQ(test, ctx->rx_thresh[0], 6); + KUNIT_EXPECT_FALSE(test, dct_irq_enabled(ctx->dc.rx_irq)); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_recv_threshold(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 30 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 30 + DCT_GUARD); + dct_queue_rx(ctx, 30, 0); + ctx->rx_refill[0] = 12; + ctx->rx_refill[1] = 18; + ctx->rx_nrefill = 2; + + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 30), 30); + KUNIT_ASSERT_EQ(test, ctx->rx_nthresh, 2); + KUNIT_EXPECT_EQ(test, ctx->rx_thresh[0], DCT_FIFO_SIZE / 2); + KUNIT_EXPECT_EQ(test, ctx->rx_thresh[1], DCT_FIFO_SIZE / 2); + KUNIT_EXPECT_MEMEQ(test, buf, ctx->rx_q, 30); + dct_expect_guard(test, buf + 30, DCT_GUARD); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_recv_timeout(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 4 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 4 + DCT_GUARD); + + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 4), -ETIMEDOUT); + dct_expect_guard(test, buf, 4 + DCT_GUARD); + KUNIT_ASSERT_EQ(test, ctx->rx_nthresh, 1); + KUNIT_EXPECT_EQ(test, ctx->rx_thresh[0], 4); + KUNIT_EXPECT_FALSE(test, dct_irq_enabled(ctx->dc.rx_irq)); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_recv_zero(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[1] = { DCT_POISON }; + + dct_queue_rx(ctx, 8, 8); + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 0), 0); + KUNIT_EXPECT_EQ(test, ctx->rx_count_reads, 0); + KUNIT_EXPECT_EQ(test, ctx->rx_pos, 0); + KUNIT_EXPECT_EQ(test, buf[0], DCT_POISON); +} + +/* Await */ + +static void dct_callback(void *cookie, size_t avail) +{ + struct dct_ctx *ctx = cookie; + + ctx->cb_cookie = cookie; + ctx->cb_avail = avail; + if (ctx->cb_recv) + ctx->cb_ret = dockchannel_recv(&ctx->dc, ctx->cb_buf, sizeof(ctx->cb_buf)); + atomic_inc(&ctx->cb_calls); + complete(&ctx->cb_done); +} + +static void dct_await_threshold(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + + KUNIT_EXPECT_EQ(test, dockchannel_await(&ctx->dc, dct_callback, ctx, 4), 4); + KUNIT_ASSERT_EQ(test, ctx->rx_nthresh, 1); + KUNIT_EXPECT_EQ(test, ctx->rx_thresh[0], 4); + KUNIT_EXPECT_TRUE(test, ctx->dc.awaiting); + KUNIT_EXPECT_TRUE(test, dct_irq_enabled(ctx->dc.rx_irq)); + + /* A zero count disarms. */ + KUNIT_EXPECT_EQ(test, dockchannel_await(&ctx->dc, NULL, NULL, 0), 0); + KUNIT_EXPECT_FALSE(test, ctx->dc.awaiting); + KUNIT_EXPECT_FALSE(test, dct_irq_enabled(ctx->dc.rx_irq)); + KUNIT_EXPECT_EQ(test, ctx->rx_nthresh, 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->cb_calls), 0); +} + +static void dct_await_clamped(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + + /* A threshold above the FIFO size would never be reached. */ + KUNIT_EXPECT_EQ(test, dockchannel_await(&ctx->dc, dct_callback, ctx, 100), + DCT_FIFO_SIZE); + KUNIT_ASSERT_EQ(test, ctx->rx_nthresh, 1); + KUNIT_EXPECT_EQ(test, ctx->rx_thresh[0], DCT_FIFO_SIZE); + KUNIT_EXPECT_EQ(test, dockchannel_await(&ctx->dc, NULL, NULL, 0), 0); +} + +static void dct_await_callback(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, dockchannel_await(&ctx->dc, dct_callback, ctx, 4), 4); + dct_set_reg(ctx, DATA_RX_COUNT, 9); + dct_fire_now(test, ctx->dc.rx_irq); + + KUNIT_ASSERT_TRUE(test, wait_for_completion_timeout(&ctx->cb_done, + msecs_to_jiffies(2000))); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->cb_calls), 1); + KUNIT_EXPECT_PTR_EQ(test, ctx->cb_cookie, (void *)ctx); + /* The callback is told what RX_COUNT says, and is not re-armed. */ + KUNIT_EXPECT_EQ(test, ctx->cb_avail, 9); + KUNIT_EXPECT_FALSE(test, ctx->dc.awaiting); + KUNIT_EXPECT_FALSE(test, dct_irq_enabled(ctx->dc.rx_irq)); +} + +static void dct_await_recv_in_callback(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + static const u8 want[4] = { 0x78, 0x56, 0x34, 0x12 }; + + /* + * The interrupt thread is not the test thread, so the stubs do not + * apply there: it reads the register buffer as it is. + */ + dct_set_reg(ctx, DATA_RX32, 0x12345678); + ctx->cb_recv = true; + KUNIT_ASSERT_EQ(test, dockchannel_await(&ctx->dc, dct_callback, ctx, 4), 4); + dct_set_reg(ctx, DATA_RX_COUNT, 4); + dct_fire_now(test, ctx->dc.rx_irq); + + KUNIT_ASSERT_TRUE(test, wait_for_completion_timeout(&ctx->cb_done, + msecs_to_jiffies(2000))); + KUNIT_EXPECT_EQ(test, ctx->cb_ret, 4); + KUNIT_EXPECT_MEMEQ(test, ctx->cb_buf, want, 4); +} + +static void dct_await_rearm(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + int i; + + /* As the HID client does: every callback arms the next one. */ + for (i = 1; i <= 3; i++) { + reinit_completion(&ctx->cb_done); + KUNIT_ASSERT_EQ(test, dockchannel_await(&ctx->dc, dct_callback, ctx, 8), 8); + KUNIT_ASSERT_TRUE(test, dct_irq_enabled(ctx->dc.rx_irq)); + dct_set_reg(ctx, DATA_RX_COUNT, 8 + i); + dct_fire_now(test, ctx->dc.rx_irq); + KUNIT_ASSERT_TRUE(test, + wait_for_completion_timeout(&ctx->cb_done, + msecs_to_jiffies(2000))); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->cb_calls), i); + KUNIT_EXPECT_EQ(test, ctx->cb_avail, 8 + i); + } + KUNIT_EXPECT_EQ(test, ctx->rx_nthresh, 3); +} + +static void dct_recv_after_await(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[4]; + + /* + * Once disarmed, the receive interrupt wakes a waiting + * dockchannel_recv() and no longer calls the callback. + */ + KUNIT_ASSERT_EQ(test, dockchannel_await(&ctx->dc, dct_callback, ctx, 4), 4); + KUNIT_ASSERT_EQ(test, dockchannel_await(&ctx->dc, NULL, NULL, 0), 0); + + dct_queue_rx(ctx, 4, 0); + ctx->rx_refill[0] = 4; + ctx->rx_nrefill = 1; + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 4), 4); + KUNIT_EXPECT_MEMEQ(test, buf, ctx->rx_q, 4); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->cb_calls), 0); +} + +/* Interrupt controller */ + +static void dct_irqchip_mask_unmask(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + struct dockchannel_common dcc = { + .irq_base = (void __force __iomem *)ctx->irqregs, + }; + struct irq_data d = { .chip_data = &dcc }; + u32 *mask = (u32 *)(ctx->irqregs + IRQ_MASK); + u32 *flag = (u32 *)(ctx->irqregs + IRQ_FLAG); + + WRITE_ONCE(*mask, 0xa5a5a5a5); + WRITE_ONCE(*flag, 0x12345678); + + d.hwirq = 0; + dockchannel_irq_mask(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), 0xa5a5a5a4); + d.hwirq = 1; + dockchannel_irq_unmask(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), 0xa5a5a5a6); + d.hwirq = 31; + dockchannel_irq_mask(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), 0x25a5a5a6); + dockchannel_irq_unmask(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), 0xa5a5a5a6); + /* Unmasking an unmasked line changes nothing. */ + dockchannel_irq_unmask(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), 0xa5a5a5a6); + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), 0x12345678); +} + +static void dct_irqchip_ack(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + struct dockchannel_common dcc = { + .irq_base = (void __force __iomem *)ctx->irqregs, + }; + struct irq_data d = { .chip_data = &dcc, .hwirq = 5 }; + u32 *mask = (u32 *)(ctx->irqregs + IRQ_MASK); + u32 *flag = (u32 *)(ctx->irqregs + IRQ_FLAG); + + WRITE_ONCE(*mask, 0xffffffff); + WRITE_ONCE(*flag, 0); + + /* IRQ_FLAG is write-one-to-clear: write only this line's bit. */ + dockchannel_irq_ack(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), BIT(5)); + d.hwirq = 31; + dockchannel_irq_ack(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), BIT(31)); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), 0xffffffff); +} + +static struct kunit_case dockchannel_test_cases[] = { + KUNIT_CASE(dct_send_whole_words), + KUNIT_CASE(dct_send_tail_bytes), + KUNIT_CASE(dct_send_short), + KUNIT_CASE(dct_send_unaligned_source), + KUNIT_CASE(dct_send_exact_room), + KUNIT_CASE(dct_send_partial_room), + KUNIT_CASE(dct_send_threshold), + KUNIT_CASE(dct_send_byte_room), + KUNIT_CASE(dct_send_spurious_wakeup), + KUNIT_CASE(dct_send_timeout), + KUNIT_CASE(dct_send_zero), + KUNIT_CASE(dct_recv_words_and_tail), + KUNIT_CASE(dct_recv_count_exceeds_buffer), + KUNIT_CASE(dct_recv_all_ones_count), + KUNIT_CASE(dct_recv_unaligned_dest), + KUNIT_CASE(dct_recv_partial_waits), + KUNIT_CASE(dct_recv_threshold), + KUNIT_CASE(dct_recv_timeout), + KUNIT_CASE(dct_recv_zero), + KUNIT_CASE(dct_await_threshold), + KUNIT_CASE(dct_await_clamped), + KUNIT_CASE(dct_await_callback), + KUNIT_CASE(dct_await_recv_in_callback), + KUNIT_CASE(dct_await_rearm), + KUNIT_CASE(dct_recv_after_await), + KUNIT_CASE(dct_irqchip_mask_unmask), + KUNIT_CASE(dct_irqchip_ack), + {} +}; + +static struct kunit_suite dockchannel_test_suite = { + .name = "apple-dockchannel", + .init = dct_init, + .exit = dct_exit, + .test_cases = dockchannel_test_cases, +}; + +kunit_test_suite(dockchannel_test_suite); diff --git a/drivers/soc/apple/dockchannel.c b/drivers/soc/apple/dockchannel.c index 77dc01f8b43596..291d81d2df2fa8 100644 --- a/drivers/soc/apple/dockchannel.c +++ b/drivers/soc/apple/dockchannel.c @@ -18,6 +18,10 @@ #include #include +#if IS_ENABLED(CONFIG_APPLE_DOCKCHANNEL_KUNIT_TEST) +#include +#endif + #define DOCKCHANNEL_MAX_IRQ 32 #define DOCKCHANNEL_TX_TIMEOUT_MS 1000 @@ -68,6 +72,34 @@ struct dockchannel_common { void __iomem *irq_base; }; +/* + * FIFO register accesses. They are functions so that the KUnit test can model + * the FIFO behind them. + */ +static u32 dockchannel_readl(void __iomem *addr) +{ +#if IS_ENABLED(CONFIG_APPLE_DOCKCHANNEL_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(dockchannel_readl, addr); +#endif + return readl_relaxed(addr); +} + +static void dockchannel_writel(u32 val, void __iomem *addr) +{ +#if IS_ENABLED(CONFIG_APPLE_DOCKCHANNEL_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(dockchannel_writel, val, addr); +#endif + writel_relaxed(val, addr); +} + +static void dockchannel_writeb(u8 val, void __iomem *addr) +{ +#if IS_ENABLED(CONFIG_APPLE_DOCKCHANNEL_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(dockchannel_writeb, val, addr); +#endif + writeb_relaxed(val, addr); +} + /* Dockchannel FIFO functions */ static irqreturn_t dockchannel_tx_irq(int irq, void *data) @@ -97,7 +129,7 @@ static irqreturn_t dockchannel_rx_irq(int irq, void *data) static irqreturn_t dockchannel_rx_irq_thread(int irq, void *data) { struct dockchannel *dockchannel = data; - size_t avail = readl_relaxed(dockchannel->data_base + DATA_RX_COUNT); + size_t avail = dockchannel_readl(dockchannel->data_base + DATA_RX_COUNT); dockchannel->awaiting = false; dockchannel->data_available(dockchannel->cookie, avail); @@ -111,18 +143,18 @@ int dockchannel_send(struct dockchannel *dockchannel, const void *buf, size_t co const u8 *p = buf; while (left > 0) { - size_t avail = readl_relaxed(dockchannel->data_base + DATA_TX_FREE); + size_t avail = dockchannel_readl(dockchannel->data_base + DATA_TX_FREE); size_t block = min(left, avail); if (avail == 0) { size_t threshold = min((size_t)(dockchannel->fifo_size / 2), left); - writel_relaxed(threshold, dockchannel->config_base + CONFIG_TX_THRESH); + dockchannel_writel(threshold, dockchannel->config_base + CONFIG_TX_THRESH); reinit_completion(&dockchannel->tx_comp); enable_irq(dockchannel->tx_irq); if (!wait_for_completion_timeout(&dockchannel->tx_comp, - msecs_to_jiffies(DOCKCHANNEL_TX_TIMEOUT_MS))) { + msecs_to_jiffies(DOCKCHANNEL_TX_TIMEOUT_MS))) { disable_irq(dockchannel->tx_irq); return -ETIMEDOUT; } @@ -131,13 +163,14 @@ int dockchannel_send(struct dockchannel *dockchannel, const void *buf, size_t co } while (block >= 4) { - writel_relaxed(get_unaligned_le32(p), dockchannel->data_base + DATA_TX32); + dockchannel_writel(get_unaligned_le32(p), + dockchannel->data_base + DATA_TX32); p += 4; left -= 4; block -= 4; } while (block > 0) { - writeb_relaxed(*p++, dockchannel->data_base + DATA_TX8); + dockchannel_writeb(*p++, dockchannel->data_base + DATA_TX8); left--; block--; } @@ -153,18 +186,18 @@ int dockchannel_recv(struct dockchannel *dockchannel, void *buf, size_t count) u8 *p = buf; while (left > 0) { - size_t avail = readl_relaxed(dockchannel->data_base + DATA_RX_COUNT); + size_t avail = dockchannel_readl(dockchannel->data_base + DATA_RX_COUNT); size_t block = min(left, avail); if (avail == 0) { size_t threshold = min((size_t)(dockchannel->fifo_size / 2), left); - writel_relaxed(threshold, dockchannel->config_base + CONFIG_RX_THRESH); + dockchannel_writel(threshold, dockchannel->config_base + CONFIG_RX_THRESH); reinit_completion(&dockchannel->rx_comp); enable_irq(dockchannel->rx_irq); if (!wait_for_completion_timeout(&dockchannel->rx_comp, - msecs_to_jiffies(DOCKCHANNEL_RX_TIMEOUT_MS))) { + msecs_to_jiffies(DOCKCHANNEL_RX_TIMEOUT_MS))) { disable_irq(dockchannel->rx_irq); return -ETIMEDOUT; } @@ -173,13 +206,14 @@ int dockchannel_recv(struct dockchannel *dockchannel, void *buf, size_t count) } while (block >= 4) { - put_unaligned_le32(readl_relaxed(dockchannel->data_base + DATA_RX32), p); + put_unaligned_le32(dockchannel_readl(dockchannel->data_base + DATA_RX32), + p); p += 4; left -= 4; block -= 4; } while (block > 0) { - *p++ = readl_relaxed(dockchannel->data_base + DATA_RX8) >> 8; + *p++ = dockchannel_readl(dockchannel->data_base + DATA_RX8) >> 8; left--; block--; } @@ -204,7 +238,7 @@ int dockchannel_await(struct dockchannel *dockchannel, dockchannel->data_available = callback; dockchannel->cookie = cookie; dockchannel->awaiting = true; - writel_relaxed(threshold, dockchannel->config_base + CONFIG_RX_THRESH); + dockchannel_writel(threshold, dockchannel->config_base + CONFIG_RX_THRESH); enable_irq(dockchannel->rx_irq); return threshold; @@ -434,3 +468,7 @@ module_platform_driver(dockchannel_driver); MODULE_AUTHOR("Hector Martin "); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple DockChannel driver"); + +#if IS_ENABLED(CONFIG_APPLE_DOCKCHANNEL_KUNIT_TEST) +#include "dockchannel-test.c" +#endif diff --git a/drivers/soc/apple/dockchannel.kunitconfig b/drivers/soc/apple/dockchannel.kunitconfig new file mode 100644 index 00000000000000..ad45d22b946006 --- /dev/null +++ b/drivers/soc/apple/dockchannel.kunitconfig @@ -0,0 +1,6 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_ARM64_16K_PAGES=y +CONFIG_APPLE_DOCKCHANNEL=y +CONFIG_APPLE_DOCKCHANNEL_KUNIT_TEST=y diff --git a/drivers/soc/apple/dt.rs b/drivers/soc/apple/dt.rs index d6f83b55862351..02f68e36ea0ec5 100644 --- a/drivers/soc/apple/dt.rs +++ b/drivers/soc/apple/dt.rs @@ -11,6 +11,7 @@ use kernel::prelude::*; const SEP_COMPATIBLE: &CStr = c"apple,sep"; const IOMMUS_PROP: &CStr = c"iommus"; +const MBOXES_PROP: &CStr = c"mboxes"; const STATUS_PROP: &CStr = c"status"; const STATUS_OKAY: &CStr = c"okay"; @@ -185,6 +186,16 @@ pub(crate) fn preboot_uuid() -> Option<[u8; 16]> { Some(uuid.b) } +/// Enables the SEP and its DART for a warm attach, on boards whose device +/// tree describes a usable enclave. +/// +/// Most device trees leave the SEP node and its DART `disabled` for this +/// function to enable, so their status cannot say whether a board has a +/// usable enclave. The SEP mailbox's status does: the SEP cannot be reached +/// without it, and the device tree enables it (in the board file, or in the +/// SoC .dtsi for every board of that SoC) where the SEP is described for the +/// machine. A board that keeps the mailbox disabled is left untouched and the +/// module probes nothing. pub(crate) fn enable_sep_and_dart(window: &crate::profile::DartWindow) -> Result<()> { let sep = sep_node().ok_or_else(|| { pr_err!( @@ -194,6 +205,16 @@ pub(crate) fn enable_sep_and_dart(window: &crate::profile::DartWindow) -> Result ENODEV })?; + if !sep + .parse_phandle(MBOXES_PROP, 0) + .is_some_and(|mbox| mbox.is_available()) + { + pr_info!( + "apple_sep: the device tree leaves the SEP mailbox disabled on this board; the SEP stays disabled\n" + ); + return Ok(()); + } + let dart = sep.parse_phandle(IOMMUS_PROP, 0).ok_or_else(|| { pr_err!( "apple_sep: SEP node has no '{}' phandle; cannot find its DART\n", diff --git a/drivers/soc/apple/hdcp.rs b/drivers/soc/apple/hdcp.rs new file mode 100644 index 00000000000000..29d2aada55baca --- /dev/null +++ b/drivers/soc/apple/hdcp.rs @@ -0,0 +1,1995 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +// Copyright 2026 Ryan Murray + +//! The enclave's HDCP endpoint (`0x0e`): the HDCP 2.2 transmitter service. +//! +//! The AP runs the HDCP 2.2 transmitter protocol; the enclave holds the +//! transmitter's secrets and does every cryptographic step. The host gives +//! the enclave the fields the receiver sent and gets back the fields it must +//! send, one command at a time. Only fields that the protocol sends in the +//! clear cross the endpoint; km, ks and the device keys never do. +//! +//! ```text +//! TX 0x0000_0000_0000_270e query interface count +//! RX 0x0000_0009_0000_000e status 0, 9 interfaces +//! TX 0x0201_0000_0700_010e command 0x01, slot 7, argument 0x0201_0000 +//! RX 0x0000_0000_0000_000e status 0, no output +//! TX 0x0000_020a_0700_080e command 0x08, slot 7, 522 input bytes out of line +//! RX 0x0000_0000_0020_000e status 0, 32 output bytes out of line +//! ``` +//! +//! - Request: byte 1 is the command, byte 3 the slot (the HDCP interface +//! channel the session runs on). The upper word is the input length for a +//! command that takes input, otherwise its argument. +//! - Reply: byte 1 is the status, byte 2 the output length (except for +//! interface-count query `0x27`, whose upper word carries the count). A +//! reply carries no command or tag, so one request may be in flight on the +//! endpoint. Its second word is stale memory and is never read. +//! - Input is one flat segment at offset 0 of a persistent 16 KiB buffer; +//! output is at offset 0 of a second one. Both are registered once. +//! - Every input is a protocol field, or fields concatenated in the order the +//! HDCP 2.2 specification hashes them (H', V', M'). +//! +//! The command set is closed ([`SPECS`]) and a session sends it in protocol +//! order only ([`Session`]); anything else is refused before it reaches the +//! mailbox. The display driver reaches this through `hdcp_shim.c`. + +use super::*; +use crate::proto::*; +use kernel::prelude::*; +use kernel::soc::apple::mailbox::Message; + +pub(crate) const EP_HDCP: u8 = 0x0e; + +/// The endpoint's discovery name. +pub(crate) const HDCP_NAME: u32 = u32::from_be_bytes(*b"hdcp"); + +/// One enclave page, and each out-of-line buffer size. +pub(crate) const SEP_PAGE: usize = 0x4000; +pub(crate) const OOL_SIZE_HDCP: usize = SEP_PAGE; + +/// Maximum HDCP interface channels tracked per SEP; the actual count is +/// queried at runtime with command `0x27` (for example 9 on T8112, 15 on +/// T6040). +pub(crate) const MAX_CHANNELS: usize = 32; + +/// How long one command may take. The slowest, the RSA encryption of km, +/// takes about 90 ms. +pub(crate) const HDCP_TIMEOUT_MS: u32 = 1000; + +/// Locality check attempts per session (HDCP 2.2: at most 1024). +pub(crate) const LC_MAX_TRIES: u16 = 1024; + +/// Repeater stream-manage attempts per session (HDCP 2.2: initial + 1 retry). +pub(crate) const STREAM_MAX_TRIES: u8 = 2; + +/// Reply status of the stored-km query when no km is stored for the receiver. +pub(crate) const STATUS_NO_STORED_KM: u8 = 0x08; + +/// The arguments that ride in the upper word of a command without input. +/// Observed values; their byte meanings are not established. +pub(crate) const OPEN_ARG: u32 = (0x02 << 24) | (0x01 << 16); +pub(crate) const PREPARE_ARG: u32 = 0x02 << 16; +pub(crate) const FINISH_ARG: u32 = 0x01 << 16; +/// Command 0x21's argument: bit 16 set as encryption is turned on, clear as +/// it is turned off. +pub(crate) const ENCRYPTION_ON: u32 = 1 << 16; + +/// Per-channel descriptor size returned by command `0x28`. +pub(crate) const CHANNEL_INFO_LEN: usize = 8; + +/// HDCP 2.2 field sizes (public specification). +pub(crate) const RTX_LEN: usize = 8; +pub(crate) const RRX_LEN: usize = 8; +pub(crate) const RN_LEN: usize = 8; +pub(crate) const RIV_LEN: usize = 8; +pub(crate) const CERT_LEN: usize = 522; +pub(crate) const CAPS_LEN: usize = 3; +pub(crate) const H_PRIME_LEN: usize = 32; +pub(crate) const L_PRIME_LEN: usize = 32; +/// Ekh(km) and m, the body of AKE_Stored_km. +pub(crate) const STORED_KM_LEN: usize = 32; +pub(crate) const EKPUB_KM_LEN: usize = 128; +pub(crate) const EKH_KM_LEN: usize = 16; +pub(crate) const EKS_LEN: usize = 16; +pub(crate) const RECEIVER_ID_LEN: usize = 5; +pub(crate) const MAX_DEVICES: usize = 31; +pub(crate) const RXINFO_LEN: usize = 2; +pub(crate) const SEQ_NUM_LEN: usize = 3; +pub(crate) const V_PRIME_LEN: usize = 16; +pub(crate) const V_LEN: usize = 32; +pub(crate) const M_PRIME_LEN: usize = 32; +/// r_tx, then RxCaps, then TxCaps. +pub(crate) const H_CONTEXT_LEN: usize = RTX_LEN + 2 * CAPS_LEN; +/// Receiver ID list, RxInfo, seq_num_V. +pub(crate) const LIST_MIN: usize = RECEIVER_ID_LEN + RXINFO_LEN + SEQ_NUM_LEN; +pub(crate) const LIST_MAX: usize = MAX_DEVICES * RECEIVER_ID_LEN + RXINFO_LEN + SEQ_NUM_LEN; +/// StreamID, Type, seq_num_M. +pub(crate) const STREAM_LEN: usize = 2 + SEQ_NUM_LEN; + +/// Validates the endpoint's discovery buffer-layout word (min/max pages each +/// way, MSB to LSB: send_min, recv_min, send_max, recv_max). One page each +/// way must be permitted by the advertised range. +pub(crate) fn ool_sizes(word: u32) -> Option<(usize, usize)> { + let send_min = (word >> 24) as u8; + let recv_min = (word >> 16) as u8; + let send_max = (word >> 8) as u8; + let recv_max = word as u8; + if send_min == 0 || recv_min == 0 || send_min > 1 || recv_min > 1 { + return None; + } + if send_max < 1 || recv_max < 1 || send_min > send_max || recv_min > recv_max { + return None; + } + Some((OOL_SIZE_HDCP, OOL_SIZE_HDCP)) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Command { + QueryChannels, + GetChannelInfo, + Open, + Prepare, + Start, + GetRtx, + PutCert, + PutRrx, + QueryStoredKm, + GetEkpubKm, + PutHContext, + PutHPrime, + PutPairing, + GetRn, + LcStart, + PutLPrime, + GetEks, + GetRiv, + PutReceiverList, + PutVPrime, + GetV, + PutStream, + PutMPrime, + Finish, + SetEncryption, + Close, +} + +/// What a command looks like on the wire. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Spec { + pub(crate) command: Command, + pub(crate) id: u8, + /// Input bytes out of line (the upper word then carries the length). + /// A command with a list takes any length from `input` to `input_max` + /// in whole entries; for the others the two are equal. + pub(crate) input: usize, + pub(crate) input_max: usize, + /// Output bytes out of line; a successful reply's byte 2 must say this. + pub(crate) output: usize, + /// The enclave checks something the receiver sent: a refusal means the + /// receiver failed authentication, not that the enclave failed. + pub(crate) verifies: bool, +} + +const fn spec(command: Command, id: u8, input: usize, output: usize) -> Spec { + Spec { + command, + id, + input, + input_max: input, + output, + verifies: false, + } +} + +const fn verify(command: Command, id: u8, input: usize) -> Spec { + Spec { + command, + id, + input, + input_max: input, + output: 0, + verifies: true, + } +} + +/// Every command the driver may send. +pub(crate) const SPECS: [Spec; 26] = [ + spec(Command::QueryChannels, 0x27, 0, 0), + spec(Command::GetChannelInfo, 0x28, 0, CHANNEL_INFO_LEN), + spec(Command::Open, 0x01, 0, 0), + spec(Command::Prepare, 0x26, 0, 0), + spec(Command::Start, 0x22, 0, 0), + spec(Command::GetRtx, 0x04, 0, RTX_LEN), + verify(Command::PutCert, 0x08, CERT_LEN), + spec(Command::PutRrx, 0x05, RRX_LEN, 0), + spec(Command::QueryStoredKm, 0x09, 0, STORED_KM_LEN), + spec(Command::GetEkpubKm, 0x0c, 0, EKPUB_KM_LEN), + spec(Command::PutHContext, 0x0e, H_CONTEXT_LEN, 0), + verify(Command::PutHPrime, 0x0f, H_PRIME_LEN), + spec(Command::PutPairing, 0x16, EKH_KM_LEN, 0), + spec(Command::GetRn, 0x18, 0, RN_LEN), + spec(Command::LcStart, 0x1a, 0, 0), + verify(Command::PutLPrime, 0x1c, L_PRIME_LEN), + spec(Command::GetEks, 0x10, 0, EKS_LEN), + spec(Command::GetRiv, 0x12, 0, RIV_LEN), + Spec { + command: Command::PutReceiverList, + id: 0x1d, + input: LIST_MIN, + input_max: LIST_MAX, + output: 0, + verifies: true, + }, + verify(Command::PutVPrime, 0x1f, V_PRIME_LEN), + spec(Command::GetV, 0x1e, 0, V_LEN), + spec(Command::PutStream, 0x23, STREAM_LEN, 0), + verify(Command::PutMPrime, 0x25, M_PRIME_LEN), + spec(Command::Finish, 0x20, 0, 0), + spec(Command::SetEncryption, 0x21, 0, 0), + spec(Command::Close, 0x02, 0, 0), +]; + +static_assert!(LIST_MAX <= OOL_SIZE_HDCP && CERT_LEN <= OOL_SIZE_HDCP); +static_assert!(EKPUB_KM_LEN <= u8::MAX as usize); +static_assert!(MAX_CHANNELS <= u8::MAX as usize); + +pub(crate) fn spec_of(command: Command) -> Spec { + let mut i = 0; + while i < SPECS.len() { + if SPECS[i].command == command { + return SPECS[i]; + } + i += 1; + } + unreachable!() +} + +/// The request word: command, slot and the upper word (input length or +/// argument). +pub(crate) const fn request_word(id: u8, slot: u8, upper: u32) -> Message { + Message { + msg0: (EP_HDCP as u64) + | ((id as u64) << MSG_TAG_SHIFT) + | ((slot as u64) << MSG_PARAM_SHIFT) + | ((upper as u64) << MSG_DATA_SHIFT), + msg1: 0, + } +} + +fn input_len_ok(s: &Spec, len: usize) -> bool { + if s.input == s.input_max { + return len == s.input; + } + // A list: whole Receiver IDs ahead of the fixed fields. + len >= s.input && len <= s.input_max && (len - s.input) % RECEIVER_ID_LEN == 0 +} + +/// Builds the request for `command` on `slot`. `arg` is used only by commands +/// without input, `input_len` only by those with it, and must fit the spec. +pub(crate) fn request(command: Command, slot: u8, arg: u32, input_len: usize) -> Result { + let s = spec_of(command); + if usize::from(slot) >= MAX_CHANNELS { + return Err(EINVAL); + } + if command == Command::QueryChannels && slot != 0 { + return Err(EINVAL); + } + let upper = if s.input != 0 { + if arg != 0 || !input_len_ok(&s, input_len) { + return Err(EINVAL); + } + input_len as u32 + } else { + if input_len != 0 { + return Err(EINVAL); + } + let allowed = match command { + Command::Open => arg == OPEN_ARG, + Command::Prepare => arg == PREPARE_ARG, + Command::Finish => arg == FINISH_ARG, + Command::SetEncryption => arg == 0 || arg == ENCRYPTION_ON, + _ => arg == 0, + }; + if !allowed { + return Err(EINVAL); + } + arg + }; + Ok(request_word(s.id, slot, upper)) +} + +/// What a reply says about the command in flight. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Outcome { + /// Status 0, with this many output bytes (the expected count). + Done(usize), + /// Status 0 for `QueryChannels`: the enclave offers this many channels. + ChannelCount(u8), + /// The stored-km query found no km for this receiver: pair first. + NotStored, + /// The enclave refused the command with this status. + Refused(u8), + /// Not a reply this command gets. + Malformed, + /// No answer in time: the endpoint is quarantined until the driver + /// rebinds, since a late reply would be taken for the next command's. + NoReply, +} + +/// Judges a reply to `command` by its first word only. +pub(crate) fn check_reply(command: Command, msg: &Message) -> Outcome { + let f = decode(msg); + let s = spec_of(command); + if f.ep != EP_HDCP || f.param != 0 { + return Outcome::Malformed; + } + if command == Command::QueryChannels { + return match f.tag { + 0 if f.ty == 0 && f.data_lo >= 1 && (f.data_lo as usize) <= MAX_CHANNELS => { + Outcome::ChannelCount(f.data_lo as u8) + } + 0 => Outcome::Malformed, + status => Outcome::Refused(status), + }; + } + if f.data_lo != 0 { + return Outcome::Malformed; + } + match f.tag { + 0 if usize::from(f.ty) == s.output => Outcome::Done(s.output), + 0 => Outcome::Malformed, + STATUS_NO_STORED_KM if command == Command::QueryStoredKm => Outcome::NotStored, + status => Outcome::Refused(status), + } +} + +/// The errno a failed command reports to the display driver. +pub(crate) fn errno(command: Command, outcome: Outcome) -> Option { + match outcome { + Outcome::Done(_) | Outcome::ChannelCount(_) | Outcome::NotStored => None, + Outcome::Refused(_) if spec_of(command).verifies => Some(EACCES), + _ => Some(EIO), + } +} + +/// One session on one slot: which command may go next. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Session { + last: Option, + open: bool, + /// The stored-km query's answer, once asked. + stored: Option, + encrypting: bool, + failed: bool, + lc_tries: u16, + stream_tries: u8, + /// Set when the previous L' or M' verification was refused while retries + /// remain; allows only the corresponding retry (or teardown). + lc_retry: bool, + stream_retry: bool, + /// r_tx of this session, for the H' context. + pub(crate) rtx: [u8; RTX_LEN], +} + +impl Session { + pub(crate) const fn new() -> Session { + Session { + last: None, + open: false, + stored: None, + encrypting: false, + failed: false, + lc_tries: 0, + stream_tries: 0, + lc_retry: false, + stream_retry: false, + rtx: [0; RTX_LEN], + } + } + + /// The protocol order: `next` may follow `last`. + fn follows(&self, last: Command, next: Command) -> bool { + use Command::*; + if self.lc_retry { + return next == GetRn && self.lc_tries < LC_MAX_TRIES; + } + if self.stream_retry { + return next == PutStream && self.stream_tries < STREAM_MAX_TRIES; + } + let stored = self.stored == Some(true); + let fresh = self.stored == Some(false); + matches!( + (last, next), + (Open, Prepare) + | (Prepare, Start) + | (Start, GetRtx) + | (GetRtx, PutCert) + | (PutCert, PutRrx) + | (PutRrx, QueryStoredKm) + | (GetEkpubKm, PutHContext) + | (PutHContext, PutHPrime) + | (PutPairing, GetRn) + | (GetRn, LcStart) + | (LcStart, PutLPrime) + | (PutLPrime, GetEks) + | (GetEks, GetRiv) + | (GetRiv, PutReceiverList) + | (GetRiv, Finish) + | (PutReceiverList, PutVPrime) + | (PutVPrime, GetV) + | (GetV, PutStream) + | (PutStream, PutMPrime) + | (PutMPrime, Finish) + ) || match (last, next) { + (QueryStoredKm, GetEkpubKm) => fresh, + (QueryStoredKm, PutHContext) => stored, + (PutHPrime, PutPairing) => fresh, + (PutHPrime, GetRn) => stored, + // The receiver missed the locality check: try again with a new r_n. + (GetRn, GetRn) => self.lc_tries < LC_MAX_TRIES, + (Finish, SetEncryption) => true, + _ => false, + } + } + + /// Whether `command` may be sent now. + pub(crate) fn allows(&self, command: Command, arg: u32) -> bool { + if matches!(command, Command::QueryChannels | Command::GetChannelInfo) { + return false; + } + if !self.open { + return command == Command::Open; + } + match command { + Command::Open => false, + // Teardown: encryption off, then close, from any open state. + Command::SetEncryption if arg == 0 => true, + Command::Close => !self.encrypting, + _ if self.failed || self.encrypting => false, + Command::SetEncryption if arg != ENCRYPTION_ON => false, + _ => self.last.is_some_and(|last| self.follows(last, command)), + } + } + + /// Records the outcome of a command [`Session::allows`] let through; + /// `false` when the session cannot advance on this command. Anything other + /// than a bounded LC/stream verification retry fails the session so only + /// teardown is allowed after it. + pub(crate) fn record(&mut self, command: Command, arg: u32, outcome: Outcome) -> bool { + match outcome { + Outcome::Done(_) => { + if command == Command::QueryStoredKm { + self.stored = Some(true); + } + } + Outcome::NotStored if command == Command::QueryStoredKm => { + self.stored = Some(false); + } + Outcome::Refused(_) + if command == Command::PutLPrime && self.lc_tries < LC_MAX_TRIES => + { + self.lc_retry = true; + self.last = Some(command); + return false; + } + Outcome::Refused(_) + if command == Command::PutMPrime && self.stream_tries < STREAM_MAX_TRIES => + { + self.stream_retry = true; + self.last = Some(command); + return false; + } + _ => { + if command == Command::Close { + // The enclave refused to close, or never answered: + // nothing more goes to this slot from this session. + *self = Session::new(); + return false; + } + self.failed = true; + self.encrypting = false; + self.lc_retry = false; + self.stream_retry = false; + return false; + } + } + self.lc_retry = false; + self.stream_retry = false; + match command { + Command::Close => { + *self = Session::new(); + return true; + } + Command::Open => self.open = true, + Command::SetEncryption if arg == 0 => { + // No way back to encryption without a new session. + self.encrypting = false; + self.failed = true; + } + Command::SetEncryption => self.encrypting = true, + Command::GetRn => self.lc_tries += 1, + Command::PutStream => self.stream_tries += 1, + _ => {} + } + self.last = Some(command); + true + } + + /// Encryption is on: every step acknowledged, in order. + pub(crate) fn encrypting(&self) -> bool { + self.encrypting + } + + pub(crate) fn is_open(&self) -> bool { + self.open + } +} + +/// The endpoint: probed channel bitmask, a session per slot, and whether it is +/// quarantined. Channel IDs returned by command `0x28` may be sparse (e.g. an +/// absent channel ID with higher channel IDs above the interface count). +pub(crate) struct State { + pub(crate) channel_mask: Option, + pub(crate) sessions: [Session; MAX_CHANNELS], + pub(crate) quarantined: bool, +} + +impl State { + pub(crate) const fn new() -> State { + State { + channel_mask: None, + sessions: [Session::new(); MAX_CHANNELS], + quarantined: false, + } + } + + /// Whether `slot` is an enumerated HDCP channel on this enclave. + pub(crate) fn has_channel(&self, slot: u8) -> bool { + usize::from(slot) < MAX_CHANNELS + && self + .channel_mask + .is_some_and(|mask| (mask & (1u32 << slot)) != 0) + } +} + +/// The single exchange the endpoint can have in flight. +pub(crate) struct Exchange { + waiting: bool, + generation: u64, + reply: Option, +} + +impl Exchange { + pub(crate) const fn new() -> Exchange { + Exchange { + waiting: false, + generation: 0, + reply: None, + } + } + + pub(crate) fn begin(&mut self) -> u64 { + self.generation = self.generation.wrapping_add(1); + self.waiting = true; + self.reply = None; + self.generation + } + + /// Takes `msg` as the answer if an exchange waits and has none yet. + pub(crate) fn answer(&mut self, msg: Message) -> bool { + if !self.waiting || self.reply.is_some() { + return false; + } + self.reply = Some(msg); + true + } + + pub(crate) fn take(&mut self) -> Option { + let reply = self.reply.take(); + if reply.is_some() { + self.waiting = false; + } + reply + } + + pub(crate) fn end(&mut self) { + self.waiting = false; + self.reply = None; + } +} + +/// The steps the display driver asks for (`enum sep_hdcp_step` in shim.h). +/// Each is a fixed run of commands; inputs and outputs are flat. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u32)] +pub(crate) enum Step { + /// out: r_tx. + Open = 0, + /// in: cert, r_rx. out: 1 + Ekh(km) + m (stored), or 0 + Ekpub(km). + AkeCert = 1, + /// in: RxCaps, TxCaps, H'. + HPrime = 2, + /// in: Ekh(km). + Pairing = 3, + /// out: r_n. + LcInit = 4, + /// in: L'. + LPrime = 5, + /// out: Edkey(ks), r_iv. + Ske = 6, + /// in: Receiver IDs, RxInfo, seq_num_V, V'. out: V. + ReceiverList = 7, + /// in: StreamID, Type, seq_num_M, M'. + Stream = 8, + Finish = 9, + EncryptionOn = 10, + EncryptionOff = 11, +} + +pub(crate) const AKE_CERT_IN: usize = CERT_LEN + RRX_LEN; +pub(crate) const AKE_CERT_OUT: usize = 1 + EKPUB_KM_LEN; +pub(crate) const H_PRIME_IN: usize = 2 * CAPS_LEN + H_PRIME_LEN; +pub(crate) const SKE_OUT: usize = EKS_LEN + RIV_LEN; +pub(crate) const STREAM_IN: usize = STREAM_LEN + M_PRIME_LEN; + +impl Step { + fn from_raw(raw: u32) -> Option { + Some(match raw { + 0 => Step::Open, + 1 => Step::AkeCert, + 2 => Step::HPrime, + 3 => Step::Pairing, + 4 => Step::LcInit, + 5 => Step::LPrime, + 6 => Step::Ske, + 7 => Step::ReceiverList, + 8 => Step::Stream, + 9 => Step::Finish, + 10 => Step::EncryptionOn, + 11 => Step::EncryptionOff, + _ => return None, + }) + } + + /// Whether `inp` and `out` have this step's sizes. + pub(crate) fn sizes_ok(self, inp: usize, out: usize) -> bool { + match self { + Step::Open => inp == 0 && out == RTX_LEN, + Step::AkeCert => inp == AKE_CERT_IN && out == AKE_CERT_OUT, + Step::HPrime => inp == H_PRIME_IN && out == 0, + Step::Pairing => inp == EKH_KM_LEN && out == 0, + Step::LcInit => inp == 0 && out == RN_LEN, + Step::LPrime => inp == L_PRIME_LEN && out == 0, + Step::Ske => inp == 0 && out == SKE_OUT, + Step::ReceiverList => { + inp >= V_PRIME_LEN + && input_len_ok(&spec_of(Command::PutReceiverList), inp - V_PRIME_LEN) + && out == V_LEN + } + Step::Stream => inp == STREAM_IN && out == 0, + Step::Finish | Step::EncryptionOn | Step::EncryptionOff => inp == 0 && out == 0, + } + } +} + +/// Runs commands against the HDCP endpoint; the SEP side or a test double. +pub(crate) trait Transport { + /// Sends `command` with `arg` and `input`; on [`Outcome::Done`] with + /// output, the output bytes are copied to `out` (exactly its length). + fn exchange( + &self, + slot: u8, + command: Command, + arg: u32, + input: &[u8], + out: &mut [u8], + ) -> Result; + + /// Notified when the endpoint is quarantined after an unanswered command. + fn on_quarantine(&self, _slot: u8, _command: Command) {} +} + +/// Queries the enclave's HDCP interface count (`0x27`) and per-interface +/// descriptors (`0x28`), once per boot before any session opens. Returns the +/// bitmask of advertised channel IDs (`info[0]` per interface index). +pub(crate) fn enumerate(t: &T, state: &mut State) -> Result { + if state.quarantined { + return Err(EIO); + } + if let Some(mask) = state.channel_mask { + return Ok(mask); + } + let outcome = match t.exchange(0, Command::QueryChannels, 0, &[], &mut []) { + Ok(o) => o, + Err(e) => return Err(e), + }; + if outcome == Outcome::NoReply { + state.quarantined = true; + t.on_quarantine(0, Command::QueryChannels); + return Err(EIO); + } + let Outcome::ChannelCount(count) = outcome else { + return Err(EIO); + }; + let mut mask = 0u32; + for index in 0..count { + let mut info = [0u8; CHANNEL_INFO_LEN]; + let o = match t.exchange(index, Command::GetChannelInfo, 0, &[], &mut info) { + Ok(o) => o, + Err(e) => return Err(e), + }; + if o == Outcome::NoReply { + state.quarantined = true; + t.on_quarantine(index, Command::GetChannelInfo); + return Err(EIO); + } + let ch = info[0]; + if o != Outcome::Done(CHANNEL_INFO_LEN) || usize::from(ch) >= MAX_CHANNELS { + return Err(EIO); + } + mask |= 1u32 << ch; + } + if mask == 0 { + return Err(EIO); + } + state.channel_mask = Some(mask); + Ok(mask) +} + +/// Sends one session command on `slot` if the session allows it, and records +/// the outcome. +fn run( + t: &T, + state: &mut State, + slot: u8, + command: Command, + arg: u32, + input: &[u8], + out: &mut [u8], +) -> Result { + if state.quarantined { + return Err(EIO); + } + if !state.has_channel(slot) { + return Err(EINVAL); + } + let i = usize::from(slot); + if !state.sessions[i].allows(command, arg) { + return Err(EPROTO); + } + if out.len() != spec_of(command).output { + return Err(EINVAL); + } + let outcome = match t.exchange(slot, command, arg, input, out) { + Ok(o) => o, + Err(e) => { + // Not sent (sleep gate, shutdown): if the session is already open, + // only teardown is safe afterwards. + if state.sessions[i].is_open() { + state.sessions[i].record(command, arg, Outcome::Malformed); + } + return Err(if e == EINVAL || e == EAGAIN || e == ENODEV { + e + } else { + EIO + }); + } + }; + if outcome == Outcome::NoReply { + state.quarantined = true; + t.on_quarantine(slot, command); + } + state.sessions[i].record(command, arg, outcome); + match errno(command, outcome) { + Some(e) => Err(e), + None => Ok(outcome), + } +} + +/// Runs one display-driver step on `slot`. +pub(crate) fn step( + t: &T, + state: &mut State, + slot: u8, + step: Step, + inp: &[u8], + out: &mut [u8], +) -> Result { + if !step.sizes_ok(inp.len(), out.len()) { + return Err(EINVAL); + } + enumerate(t, state)?; + if !state.has_channel(slot) { + return Err(EINVAL); + } + let i = usize::from(slot); + let was_open = state.sessions[i].is_open(); + let r = step_inner(t, state, slot, step, inp, out); + if r.is_err() { + out.fill(0); + // Only tear down a session that this Open call started; never clobber + // an already-open session when a duplicate Open fails with -EPROTO. + if step == Step::Open && !was_open && state.sessions[i].is_open() { + close(t, state, slot); + } + } + r +} + +fn step_inner( + t: &T, + state: &mut State, + slot: u8, + step: Step, + inp: &[u8], + out: &mut [u8], +) -> Result { + use Command::*; + let none: &mut [u8] = &mut []; + match step { + Step::Open => { + run(t, state, slot, Open, OPEN_ARG, &[], &mut [])?; + run(t, state, slot, Prepare, PREPARE_ARG, &[], &mut [])?; + run(t, state, slot, Start, 0, &[], &mut [])?; + run(t, state, slot, GetRtx, 0, &[], out)?; + state.sessions[usize::from(slot)].rtx.copy_from_slice(out); + } + Step::AkeCert => { + run(t, state, slot, PutCert, 0, &inp[..CERT_LEN], none)?; + run(t, state, slot, PutRrx, 0, &inp[CERT_LEN..], none)?; + let (flag, rest) = out.split_at_mut(1); + let o = run( + t, + state, + slot, + QueryStoredKm, + 0, + &[], + &mut rest[..STORED_KM_LEN], + )?; + if o == Outcome::NotStored { + rest[..STORED_KM_LEN].fill(0); + flag[0] = 0; + run(t, state, slot, GetEkpubKm, 0, &[], rest)?; + } else { + flag[0] = 1; + } + } + Step::HPrime => { + let mut ctx = [0u8; H_CONTEXT_LEN]; + ctx[..RTX_LEN].copy_from_slice(&state.sessions[usize::from(slot)].rtx); + ctx[RTX_LEN..].copy_from_slice(&inp[..2 * CAPS_LEN]); + run(t, state, slot, PutHContext, 0, &ctx, none)?; + run(t, state, slot, PutHPrime, 0, &inp[2 * CAPS_LEN..], none)?; + } + Step::Pairing => { + run(t, state, slot, PutPairing, 0, inp, none)?; + } + Step::LcInit => { + run(t, state, slot, GetRn, 0, &[], out)?; + } + Step::LPrime => { + run(t, state, slot, LcStart, 0, &[], none)?; + run(t, state, slot, PutLPrime, 0, inp, none)?; + } + Step::Ske => { + let (eks, riv) = out.split_at_mut(EKS_LEN); + run(t, state, slot, GetEks, 0, &[], eks)?; + run(t, state, slot, GetRiv, 0, &[], riv)?; + } + Step::ReceiverList => { + let (list, v_prime) = inp.split_at(inp.len() - V_PRIME_LEN); + run(t, state, slot, PutReceiverList, 0, list, none)?; + run(t, state, slot, PutVPrime, 0, v_prime, none)?; + run(t, state, slot, GetV, 0, &[], out)?; + } + Step::Stream => { + run(t, state, slot, PutStream, 0, &inp[..STREAM_LEN], none)?; + run(t, state, slot, PutMPrime, 0, &inp[STREAM_LEN..], none)?; + } + Step::Finish => { + run(t, state, slot, Finish, FINISH_ARG, &[], none)?; + } + Step::EncryptionOn => { + run(t, state, slot, SetEncryption, ENCRYPTION_ON, &[], none)?; + } + Step::EncryptionOff => { + run(t, state, slot, SetEncryption, 0, &[], none)?; + } + } + Ok(()) +} + +/// Ends the session on `slot` from any state: encryption off, then close. +/// The local session is reset whatever the enclave answers. +pub(crate) fn close(t: &T, state: &mut State, slot: u8) { + if !state.has_channel(slot) { + return; + } + let i = usize::from(slot); + if !state.sessions[i].is_open() { + return; + } + if !state.quarantined { + if state.sessions[i].encrypting() { + let _ = run(t, state, slot, Command::SetEncryption, 0, &[], &mut []); + } + if !state.quarantined { + let _ = run(t, state, slot, Command::Close, 0, &[], &mut []); + } + } + state.sessions[i] = Session::new(); +} + +/// The mailbox side. +struct Mailbox<'a>(&'a SepData); + +impl Transport for Mailbox<'_> { + fn exchange( + &self, + slot: u8, + command: Command, + arg: u32, + input: &[u8], + out: &mut [u8], + ) -> Result { + let sep = self.0; + let msg = request(command, slot, arg, input.len())?; + if !input.is_empty() { + sep.ool_write(&sep.ool_hdcp, 0, input)?; + } + if !out.is_empty() { + // The last reply must not be taken for this one's. + sep.ool_repoison(&sep.ool_hdcp, 0, out.len()); + } + sep.hdcp_rx.lock().begin(); + if let Err(e) = sep.send(msg) { + sep.hdcp_rx.lock().end(); + sep.hdcp_scrub_buffers(input.len(), out.len()); + return Err(e); + } + let reply = match sep.hdcp_wait() { + Ok(Some(r)) => r, + Ok(None) => { + sep.hdcp_scrub_buffers(input.len(), 0); + return Ok(Outcome::NoReply); + } + Err(e) => { + sep.hdcp_scrub_buffers(input.len(), out.len()); + return Err(e); + } + }; + let outcome = check_reply(command, &reply); + let final_outcome = match outcome { + Outcome::Done(n) if n > 0 => { + if n != out.len() || !sep.ool_await_written(&sep.ool_hdcp, 0, n) { + Outcome::Malformed + } else { + match sep.ool_read(&sep.ool_hdcp, 0, n) { + Ok(bytes) => { + out.copy_from_slice(&bytes); + Outcome::Done(n) + } + Err(_) => Outcome::Malformed, + } + } + } + other => other, + }; + // Log non-success replies using only the mailbox word (status/len), + // never any out-of-line payload bytes. + match final_outcome { + Outcome::Done(_) | Outcome::NotStored | Outcome::ChannelCount(_) => {} + Outcome::Refused(_) if spec_of(command).verifies => { + dev_dbg!( + sep.dev, + "hdcp: command {:#04x} channel {}: verification refused (reply {:#018x})\n", + spec_of(command).id, + slot, + reply.msg0 + ); + } + other => { + dev_warn_ratelimited!( + sep.dev, + "hdcp: command {:#04x} channel {}: {:?} (reply {:#018x}, expected {} out)\n", + spec_of(command).id, + slot, + other, + reply.msg0, + out.len() + ); + } + } + sep.hdcp_scrub_buffers(input.len(), out.len()); + Ok(final_outcome) + } + + fn on_quarantine(&self, slot: u8, command: Command) { + self.0.hdcp_quarantined.store(true, Release); + dev_err_ratelimited!( + self.0.dev, + "hdcp: no reply to command {:#04x} on channel {}; endpoint quarantined until reset\n", + spec_of(command).id, + slot + ); + } +} + +impl SepData { + /// Records the discovery messages of the endpoint. + pub(crate) fn hdcp_discovered(&self, f: &Fields) { + if f.param != EP_HDCP { + return; + } + match f.ty { + DISCOVER_TYPE_DESCRIPTOR => self.hdcp_named.store(f.data_lo == HDCP_NAME, Relaxed), + DISCOVER_TYPE_CONFIG => self.hdcp_layout.store(f.data_lo, Relaxed), + _ => {} + } + } + + pub(crate) fn hdcp_offered(&self) -> bool { + self.endpoint_present(EP_HDCP) + && self.hdcp_named.load(Relaxed) + && ool_sizes(self.hdcp_layout.load(Relaxed)).is_some() + } + + fn hdcp_ready_state(&self) -> Result { + if self.shutting_down.load(Relaxed) { + return Err(ENODEV); + } + if self.phase.load(Relaxed) != PHASE_READY { + return Err(EAGAIN); + } + if !self.hdcp_offered() { + return Err(ENODEV); + } + match self.sleep_gate() { + pm::SleepGate::Open => Ok(()), + pm::SleepGate::Lost => Err(EIO), + _ => Err(EAGAIN), + } + } + + fn hdcp_available(&self) -> bool { + self.hdcp_ready_state().is_ok() && !self.hdcp_quarantined.load(Acquire) + } + + fn hdcp_scrub_buffers(&self, in_len: usize, out_len: usize) { + let guard = self.ool_hdcp.lock(); + let Some(buffers) = guard.as_ref() else { + return; + }; + let in_n = in_len.min(buffers.allocated); + let out_n = out_len.min(buffers.allocated); + // SAFETY: the exchange is finished (or never sent) under `hdcp_state`; + // no concurrent host accessor touches these slices. + unsafe { + if in_n > 0 { + buffers.inbound.as_mut()[..in_n].fill(0); + } + if out_n > 0 { + buffers.outbound.as_mut()[..out_n].fill(OOL_POISON_OUTBOUND); + } + } + } + + /// Waits for the reply to the exchange in flight; `None` on timeout. + fn hdcp_wait(&self) -> Result> { + let mut remaining = time::msecs_to_jiffies(HDCP_TIMEOUT_MS); + let mut guard = self.hdcp_rx.lock(); + loop { + if self.shutting_down.load(Relaxed) { + guard.end(); + return Err(ENODEV); + } + if let Some(reply) = guard.take() { + return Ok(Some(reply)); + } + if remaining == 0 { + guard.end(); + return Ok(None); + } + // Uninterruptible, as the other reply waits. + match self.hdcp_wq.wait_timeout(&mut guard, remaining) { + CondVarTimeoutResult::Woken { jiffies } => remaining = jiffies, + CondVarTimeoutResult::Signal { jiffies } => remaining = jiffies, + CondVarTimeoutResult::Timeout => remaining = 0, + } + } + } + + pub(crate) fn on_hdcp(&self, msg: Message) { + if self.hdcp_rx.lock().answer(msg) { + self.hdcp_wq.notify_all(); + } else if diag::unhandled() <= UNHANDLED_LOG_LIMIT { + dev_info_ratelimited!( + self.dev, + "hdcp: unexpected message (msg0 {:#018x})\n", + msg.msg0 + ); + } + } + + fn hdcp_ready(&self) -> Result { + self.hdcp_ready_state()?; + self.register_ool(&self.ool_hdcp).map_err(|e| { + dev_warn_ratelimited!( + self.dev, + "hdcp: out-of-line buffer registration failed ({:?})\n", + e + ); + if e == EAGAIN || e == ENODEV { + e + } else { + EIO + } + }) + } + + fn hdcp_step(&self, channel: u32, raw: u32, inp: &[u8], out: &mut [u8]) -> Result { + let slot = u8::try_from(channel).map_err(|_| EINVAL)?; + let step_id = Step::from_raw(raw).ok_or(EINVAL)?; + if let Err(e) = self.hdcp_ready() { + out.fill(0); + return Err(e); + } + let mut state = self.hdcp_state.lock(); + step(&Mailbox(self), &mut state, slot, step_id, inp, out) + } + + fn hdcp_close(&self, channel: u32) { + let Ok(slot) = u8::try_from(channel) else { + return; + }; + let mut state = self.hdcp_state.lock(); + close(&Mailbox(self), &mut state, slot); + } + + pub(crate) fn register_hdcp_kernel(&self) -> Result { + let context = core::ptr::from_ref(self).cast_mut().cast::(); + // SAFETY: `KERNEL_OPS` is static and `remove()` unregisters this + // pointer before the driver's `Arc` can be dropped. + kernel::error::to_result(unsafe { sep_hdcp_register(context, &KERNEL_OPS) }) + } + + pub(crate) fn unregister_hdcp_kernel(&self) { + let context = core::ptr::from_ref(self).cast_mut().cast::(); + // SAFETY: the pointer is the one passed to `sep_hdcp_register`. + unsafe { sep_hdcp_unregister(context) }; + } +} + +/// `struct sep_hdcp_ops` in shim.h. +#[repr(C)] +struct KernelOps { + available: unsafe extern "C" fn(*mut c_void) -> bool, + step: unsafe extern "C" fn(*mut c_void, u32, u32, *const u8, usize, *mut u8, usize) -> c_int, + close: unsafe extern "C" fn(*mut c_void, u32), +} + +extern "C" { + fn sep_hdcp_register(context: *mut c_void, ops: *const KernelOps) -> c_int; + fn sep_hdcp_unregister(context: *mut c_void); +} + +static KERNEL_OPS: KernelOps = KernelOps { + available: kernel_available, + step: kernel_step, + close: kernel_close, +}; + +/// # Safety +/// +/// `context` is the registered `SepData`; the shim holds its registration +/// lock, so it outlives the call. +unsafe extern "C" fn kernel_available(context: *mut c_void) -> bool { + // SAFETY: see the function's safety section. + let sep = unsafe { &*context.cast::() }; + sep.hdcp_available() +} + +/// # Safety +/// +/// As [`kernel_available`]; `inp`/`out` are valid for their lengths (or the +/// length is 0) and do not overlap. +unsafe extern "C" fn kernel_step( + context: *mut c_void, + channel: u32, + step: u32, + inp: *const u8, + inp_len: usize, + out: *mut u8, + out_len: usize, +) -> c_int { + // SAFETY: see the function's safety section. + let sep = unsafe { &*context.cast::() }; + let inp: &[u8] = if inp_len == 0 { + &[] + } else { + // SAFETY: see the function's safety section. + unsafe { core::slice::from_raw_parts(inp, inp_len) } + }; + let out: &mut [u8] = if out_len == 0 { + &mut [] + } else { + // SAFETY: see the function's safety section. + unsafe { core::slice::from_raw_parts_mut(out, out_len) } + }; + match sep.hdcp_step(channel, step, inp, out) { + Ok(()) => 0, + Err(e) => e.to_errno(), + } +} + +/// # Safety +/// +/// As [`kernel_available`]. +unsafe extern "C" fn kernel_close(context: *mut c_void, channel: u32) { + // SAFETY: see the function's safety section. + let sep = unsafe { &*context.cast::() }; + sep.hdcp_close(channel); +} + +#[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] +#[::kernel::macros::kunit_tests(apple_sep_hdcp)] +mod tests { + use super::*; + use core::cell::{Cell, RefCell}; + + // The request words of one first-pairing session to a repeater on slot 7, + // each with its reply word. The stored-km query answers status 0x08: no + // km stored. + const SLOT: u8 = 0x07; + const TRACE: [(Command, u32, usize, u64, u64); 23] = [ + ( + Command::Open, + OPEN_ARG, + 0, + 0x0201_0000_0700_010e, + 0x0000_0000_0000_000e, + ), + ( + Command::Prepare, + PREPARE_ARG, + 0, + 0x0002_0000_0700_260e, + 0x0000_0000_0000_000e, + ), + ( + Command::Start, + 0, + 0, + 0x0000_0000_0700_220e, + 0x0000_0000_0000_000e, + ), + ( + Command::GetRtx, + 0, + 0, + 0x0000_0000_0700_040e, + 0x0000_0000_0008_000e, + ), + ( + Command::PutCert, + 0, + 522, + 0x0000_020a_0700_080e, + 0x0000_0000_0000_000e, + ), + ( + Command::PutRrx, + 0, + 8, + 0x0000_0008_0700_050e, + 0x0000_0000_0000_000e, + ), + ( + Command::QueryStoredKm, + 0, + 0, + 0x0000_0000_0700_090e, + 0x0000_0000_0020_080e, + ), + ( + Command::GetEkpubKm, + 0, + 0, + 0x0000_0000_0700_0c0e, + 0x0000_0000_0080_000e, + ), + ( + Command::PutHContext, + 0, + 14, + 0x0000_000e_0700_0e0e, + 0x0000_0000_0000_000e, + ), + ( + Command::PutHPrime, + 0, + 32, + 0x0000_0020_0700_0f0e, + 0x0000_0000_0000_000e, + ), + ( + Command::PutPairing, + 0, + 16, + 0x0000_0010_0700_160e, + 0x0000_0000_0000_000e, + ), + ( + Command::GetRn, + 0, + 0, + 0x0000_0000_0700_180e, + 0x0000_0000_0008_000e, + ), + ( + Command::LcStart, + 0, + 0, + 0x0000_0000_0700_1a0e, + 0x0000_0000_0000_000e, + ), + ( + Command::PutLPrime, + 0, + 32, + 0x0000_0020_0700_1c0e, + 0x0000_0000_0000_000e, + ), + ( + Command::GetEks, + 0, + 0, + 0x0000_0000_0700_100e, + 0x0000_0000_0010_000e, + ), + ( + Command::GetRiv, + 0, + 0, + 0x0000_0000_0700_120e, + 0x0000_0000_0008_000e, + ), + ( + Command::PutReceiverList, + 0, + 10, + 0x0000_000a_0700_1d0e, + 0x0000_0000_0000_000e, + ), + ( + Command::PutVPrime, + 0, + 16, + 0x0000_0010_0700_1f0e, + 0x0000_0000_0000_000e, + ), + ( + Command::GetV, + 0, + 0, + 0x0000_0000_0700_1e0e, + 0x0000_0000_0020_000e, + ), + ( + Command::PutStream, + 0, + 5, + 0x0000_0005_0700_230e, + 0x0000_0000_0000_000e, + ), + ( + Command::PutMPrime, + 0, + 32, + 0x0000_0020_0700_250e, + 0x0000_0000_0000_000e, + ), + ( + Command::Finish, + FINISH_ARG, + 0, + 0x0001_0000_0700_200e, + 0x0000_0000_0000_000e, + ), + ( + Command::SetEncryption, + ENCRYPTION_ON, + 0, + 0x0001_0000_0700_210e, + 0x0000_0000_0000_000e, + ), + ]; + // Display power-off: encryption off, then close. + const TRACE_OFF: [(Command, u64); 2] = [ + (Command::SetEncryption, 0x0000_0000_0700_210e), + (Command::Close, 0x0000_0000_0700_020e), + ]; + + fn reply(w: u64) -> Message { + // The second word is stale memory; it must not matter. + Message { + msg0: w, + msg1: 0x0bad_f00d, + } + } + + /// A transport that answers from a script of reply words and logs what + /// was sent. + struct Fake { + replies: RefCell>, + channel_ids: RefCell>, + sent: RefCell>, + next: Cell, + quarantined: Cell, + } + + impl Fake { + fn new(replies: &[u64]) -> Fake { + let mut v = KVec::new(); + for r in replies { + v.push(*r, GFP_KERNEL).unwrap(); + } + Fake { + replies: RefCell::new(v), + channel_ids: RefCell::new(KVec::new()), + sent: RefCell::new(KVec::new()), + next: Cell::new(0), + quarantined: Cell::new(false), + } + } + + fn with_channel_ids(replies: &[u64], ids: &[u8]) -> Fake { + let f = Fake::new(replies); + for &id in ids { + f.channel_ids.borrow_mut().push(id, GFP_KERNEL).unwrap(); + } + f + } + + fn sent(&self) -> KVec { + let mut v = KVec::new(); + for s in self.sent.borrow().iter() { + v.push(s.0, GFP_KERNEL).unwrap(); + } + v + } + } + + impl Transport for Fake { + fn exchange( + &self, + slot: u8, + command: Command, + arg: u32, + input: &[u8], + out: &mut [u8], + ) -> Result { + request(command, slot, arg, input.len())?; + self.sent + .borrow_mut() + .push((command, slot, arg, input.len()), GFP_KERNEL)?; + let i = self.next.get(); + self.next.set(i + 1); + let Some(&w) = self.replies.borrow().get(i) else { + return Ok(Outcome::NoReply); + }; + let o = check_reply(command, &reply(w)); + if let Outcome::Done(n) = o { + if n != out.len() { + return Ok(Outcome::Malformed); + } + if command == Command::GetChannelInfo { + out.fill(0); + let ids = self.channel_ids.borrow(); + out[0] = ids.get(usize::from(slot)).copied().unwrap_or(slot); + } else { + out.fill(0x5c); + } + } + Ok(o) + } + + fn on_quarantine(&self, _slot: u8, _command: Command) { + self.quarantined.set(true); + } + } + + const OK: u64 = 0x0000_0000_0000_000e; + + fn ok_for(c: Command) -> u64 { + OK | ((spec_of(c).output as u64) << 16) + } + + fn state_with_channels(n: u8) -> State { + let mut st = State::new(); + st.channel_mask = Some((1u32 << n) - 1); + st + } + + #[test] + fn the_requests_match_the_recording() { + assert_eq!( + request(Command::QueryChannels, 0, 0, 0).unwrap().msg0, + 0x0000_0000_0000_270e + ); + assert_eq!( + request(Command::GetChannelInfo, SLOT, 0, 0).unwrap().msg0, + 0x0000_0000_0700_280e + ); + assert!(request(Command::QueryChannels, 1, 0, 0).is_err()); + for &(c, arg, len, tx, _) in TRACE.iter() { + assert_eq!(request(c, SLOT, arg, len).unwrap().msg0, tx); + } + assert_eq!( + request(Command::SetEncryption, SLOT, 0, 0).unwrap().msg0, + TRACE_OFF[0].1 + ); + assert_eq!( + request(Command::Close, SLOT, 0, 0).unwrap().msg0, + TRACE_OFF[1].1 + ); + } + + #[test] + fn discovery_layout_and_channel_enumeration_follow_hardware() -> Result { + assert_eq!(ool_sizes(0x0101_0101), Some((OOL_SIZE_HDCP, OOL_SIZE_HDCP))); + assert_eq!(ool_sizes(0x0101_0202), Some((OOL_SIZE_HDCP, OOL_SIZE_HDCP))); + assert_eq!(ool_sizes(0x0202_0202), None); + assert_eq!(ool_sizes(0), None); + + // Enclave advertises 9 contiguous channels (as on T8112); slot 8 ok, slot 9 EINVAL. + let mut replies = KVec::new(); + replies.push(0x0000_0009_0000_000e, GFP_KERNEL)?; + for _ in 0..9 { + replies.push(ok_for(Command::GetChannelInfo), GFP_KERNEL)?; + } + let t = Fake::new(&replies); + let mut st = State::new(); + assert_eq!(enumerate(&t, &mut st)?, 0x1ff); + assert!(st.has_channel(8)); + assert!(!st.has_channel(9)); + // Second enumeration is cached (no further mailbox traffic). + assert_eq!(enumerate(&t, &mut st)?, 0x1ff); + assert_eq!(t.sent().len(), 10); + assert_eq!( + step(&t, &mut st, 9, Step::Open, &[], &mut [0; RTX_LEN]), + Err(EINVAL) + ); + assert_eq!(t.sent().len(), 10); + + // Sparse channel table (14 interfaces: 0..=5 and 7..=14, skipping 6, + // as on T6040): channel 6 is refused, channels 7 and 14 are accepted. + let sparse_ids: [u8; 14] = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14]; + let mut sparse_replies = KVec::new(); + sparse_replies.push(0x0000_000e_0000_000e, GFP_KERNEL)?; + for _ in 0..14 { + sparse_replies.push(ok_for(Command::GetChannelInfo), GFP_KERNEL)?; + } + for c in [Command::Open, Command::Prepare, Command::Start, Command::GetRtx] { + sparse_replies.push(ok_for(c), GFP_KERNEL)?; + } + let ts = Fake::with_channel_ids(&sparse_replies, &sparse_ids); + let mut sts = State::new(); + let mask = enumerate(&ts, &mut sts)?; + assert!(!sts.has_channel(6)); + assert!(sts.has_channel(7)); + assert!(sts.has_channel(14)); + assert!(!sts.has_channel(15)); + assert_eq!(mask, 0x7fbf); + assert_eq!( + step(&ts, &mut sts, 6, Step::Open, &[], &mut [0; RTX_LEN]), + Err(EINVAL) + ); + step(&ts, &mut sts, 14, Step::Open, &[], &mut [0; RTX_LEN])?; + Ok(()) + } + + #[test] + fn the_recorded_session_runs_to_encryption_and_tears_down() { + let mut s = Session::new(); + for &(c, arg, _, _, rx) in TRACE.iter() { + assert!(s.allows(c, arg)); + let o = check_reply(c, &reply(rx)); + assert!(errno(c, o).is_none()); + assert!(s.record(c, arg, o)); + } + assert!(s.encrypting()); + assert!(!s.allows(Command::Close, 0)); + assert!(!s.allows(Command::GetRn, 0)); + assert!(s.allows(Command::SetEncryption, 0)); + assert!(s.record(Command::SetEncryption, 0, Outcome::Done(0))); + assert!(!s.encrypting()); + assert!(!s.allows(Command::SetEncryption, ENCRYPTION_ON)); + assert!(s.allows(Command::Close, 0)); + assert!(s.record(Command::Close, 0, Outcome::Done(0))); + assert!(!s.is_open()); + assert!(s.allows(Command::Open, OPEN_ARG)); + } + + #[test] + fn the_steps_send_the_first_pairing_repeater_order() -> Result { + let mut replies = KVec::new(); + for &(_, _, _, _, rx) in TRACE.iter() { + replies.push(rx, GFP_KERNEL)?; + } + replies.push(OK, GFP_KERNEL)?; + replies.push(OK, GFP_KERNEL)?; + let t = Fake::new(&replies); + let mut st = state_with_channels(9); + let mut rtx = [0u8; RTX_LEN]; + step(&t, &mut st, SLOT, Step::Open, &[], &mut rtx)?; + let mut cert_out = [0u8; AKE_CERT_OUT]; + step( + &t, + &mut st, + SLOT, + Step::AkeCert, + &[1; AKE_CERT_IN], + &mut cert_out, + )?; + assert_eq!(cert_out[0], 0); + step(&t, &mut st, SLOT, Step::HPrime, &[2; H_PRIME_IN], &mut [])?; + step(&t, &mut st, SLOT, Step::Pairing, &[3; EKH_KM_LEN], &mut [])?; + step(&t, &mut st, SLOT, Step::LcInit, &[], &mut [0; RN_LEN])?; + step(&t, &mut st, SLOT, Step::LPrime, &[4; L_PRIME_LEN], &mut [])?; + step(&t, &mut st, SLOT, Step::Ske, &[], &mut [0; SKE_OUT])?; + step( + &t, + &mut st, + SLOT, + Step::ReceiverList, + &[5; LIST_MIN + V_PRIME_LEN], + &mut [0; V_LEN], + )?; + step(&t, &mut st, SLOT, Step::Stream, &[6; STREAM_IN], &mut [])?; + step(&t, &mut st, SLOT, Step::Finish, &[], &mut [])?; + step(&t, &mut st, SLOT, Step::EncryptionOn, &[], &mut [])?; + assert!(st.sessions[SLOT as usize].encrypting()); + close(&t, &mut st, SLOT); + let sent = t.sent(); + assert_eq!(sent.len(), TRACE.len() + 2); + for (i, &(c, ..)) in TRACE.iter().enumerate() { + assert_eq!(sent[i], c); + } + assert_eq!(sent[TRACE.len()], Command::SetEncryption); + assert_eq!(sent[TRACE.len() + 1], Command::Close); + assert!(!st.sessions[SLOT as usize].is_open()); + Ok(()) + } + + #[test] + fn duplicate_open_does_not_clobber_active_session() -> Result { + use Command::*; + let mut replies = KVec::new(); + for c in [Open, Prepare, Start, GetRtx] { + replies.push(ok_for(c), GFP_KERNEL)?; + } + let t = Fake::new(&replies); + let mut st = state_with_channels(9); + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; RTX_LEN])?; + let sent_after_open = t.sent().len(); + assert_eq!( + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; RTX_LEN]), + Err(EPROTO) + ); + assert!(st.sessions[SLOT as usize].is_open()); + assert_eq!(t.sent().len(), sent_after_open); + Ok(()) + } + + #[test] + fn the_stored_km_path_skips_pairing() -> Result { + use Command::*; + let order = [ + Open, + Prepare, + Start, + GetRtx, + PutCert, + PutRrx, + QueryStoredKm, + PutHContext, + PutHPrime, + GetRn, + LcStart, + PutLPrime, + GetEks, + GetRiv, + Finish, + SetEncryption, + ]; + let mut replies = KVec::new(); + for c in order.iter() { + replies.push(ok_for(*c), GFP_KERNEL)?; + } + let t = Fake::new(&replies); + let mut st = state_with_channels(15); + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; RTX_LEN])?; + let mut cert_out = [0u8; AKE_CERT_OUT]; + step( + &t, + &mut st, + SLOT, + Step::AkeCert, + &[1; AKE_CERT_IN], + &mut cert_out, + )?; + assert_eq!(cert_out[0], 1); + step(&t, &mut st, SLOT, Step::HPrime, &[2; H_PRIME_IN], &mut [])?; + // No pairing after a stored km. + assert_eq!( + step(&t, &mut st, SLOT, Step::Pairing, &[3; EKH_KM_LEN], &mut []), + Err(EPROTO) + ); + Ok(()) + } + + #[test] + fn out_of_order_and_bad_sizes_are_refused() { + let t = Fake::new(&[]); + let mut st = state_with_channels(15); + // Nothing before open; nothing reaches the transport. + assert_eq!( + step(&t, &mut st, SLOT, Step::LcInit, &[], &mut [0; RN_LEN]), + Err(EPROTO) + ); + assert_eq!( + step(&t, &mut st, SLOT, Step::EncryptionOn, &[], &mut []), + Err(EPROTO) + ); + assert_eq!( + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; 7]), + Err(EINVAL) + ); + assert_eq!( + step(&t, &mut st, 15, Step::Open, &[], &mut [0; RTX_LEN]), + Err(EINVAL) + ); + // A list of no Receiver ID, of 32, or of a partial one. + for n in [ + V_PRIME_LEN + 5, + V_PRIME_LEN + LIST_MAX + 5, + V_PRIME_LEN + LIST_MIN + 3, + ] { + assert!(!Step::ReceiverList.sizes_ok(n, V_LEN)); + } + assert!(Step::ReceiverList.sizes_ok(V_PRIME_LEN + LIST_MAX, V_LEN)); + assert!(t.sent().is_empty()); + assert!(request(Command::PutCert, SLOT, 0, 521).is_err()); + assert!(request(Command::Open, SLOT, 0, 0).is_err()); + assert!(request(Command::GetRtx, SLOT, 0, 8).is_err()); + assert!(request(Command::SetEncryption, SLOT, 3, 0).is_err()); + } + + #[test] + fn a_refused_verification_is_eacces_and_fails_the_session() -> Result { + use Command::*; + let mut replies = KVec::new(); + for c in [ + Open, + Prepare, + Start, + GetRtx, + PutCert, + PutRrx, + QueryStoredKm, + PutHContext, + ] { + replies.push(ok_for(c), GFP_KERNEL)?; + } + // H' refused with some status. + replies.push(0x0000_0000_0000_030e, GFP_KERNEL)?; + replies.push(OK, GFP_KERNEL)?; + let t = Fake::new(&replies); + let mut st = state_with_channels(15); + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; RTX_LEN])?; + step( + &t, + &mut st, + SLOT, + Step::AkeCert, + &[1; AKE_CERT_IN], + &mut [0; AKE_CERT_OUT], + )?; + assert_eq!( + step(&t, &mut st, SLOT, Step::HPrime, &[2; H_PRIME_IN], &mut []), + Err(EACCES) + ); + assert_eq!( + step(&t, &mut st, SLOT, Step::LcInit, &[], &mut [0; RN_LEN]), + Err(EPROTO) + ); + close(&t, &mut st, SLOT); + assert_eq!(*t.sent().last().unwrap(), Close); + assert!(st.sessions[SLOT as usize].allows(Open, OPEN_ARG)); + // A refused non-verification command is EIO. + assert_eq!(errno(GetRtx, Outcome::Refused(1)), Some(EIO)); + assert_eq!(errno(PutMPrime, Outcome::Refused(1)), Some(EACCES)); + assert_eq!(errno(PutReceiverList, Outcome::Refused(1)), Some(EACCES)); + Ok(()) + } + + #[test] + fn stream_manage_allows_one_retry_after_refused_m_prime() -> Result { + use Command::*; + let mut replies = KVec::new(); + for c in [ + Open, + Prepare, + Start, + GetRtx, + PutCert, + PutRrx, + QueryStoredKm, + PutHContext, + PutHPrime, + GetRn, + LcStart, + PutLPrime, + GetEks, + GetRiv, + PutReceiverList, + PutVPrime, + GetV, + PutStream, + ] { + replies.push(ok_for(c), GFP_KERNEL)?; + } + // First M' refused, second attempt succeeds, then Finish succeeds. + replies.push(0x0000_0000_0000_030e, GFP_KERNEL)?; + replies.push(OK, GFP_KERNEL)?; + replies.push(OK, GFP_KERNEL)?; + replies.push(OK, GFP_KERNEL)?; + let t = Fake::new(&replies); + let mut st = state_with_channels(9); + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; RTX_LEN])?; + step( + &t, + &mut st, + SLOT, + Step::AkeCert, + &[1; AKE_CERT_IN], + &mut [0; AKE_CERT_OUT], + )?; + step(&t, &mut st, SLOT, Step::HPrime, &[2; H_PRIME_IN], &mut [])?; + step(&t, &mut st, SLOT, Step::LcInit, &[], &mut [0; RN_LEN])?; + step(&t, &mut st, SLOT, Step::LPrime, &[4; L_PRIME_LEN], &mut [])?; + step(&t, &mut st, SLOT, Step::Ske, &[], &mut [0; SKE_OUT])?; + step( + &t, + &mut st, + SLOT, + Step::ReceiverList, + &[5; LIST_MIN + V_PRIME_LEN], + &mut [0; V_LEN], + )?; + assert_eq!( + step(&t, &mut st, SLOT, Step::Stream, &[6; STREAM_IN], &mut []), + Err(EACCES) + ); + // Finish is refused while retry is pending. + assert_eq!(step(&t, &mut st, SLOT, Step::Finish, &[], &mut []), Err(EPROTO)); + // Retry succeeds, then Finish proceeds. + step(&t, &mut st, SLOT, Step::Stream, &[7; STREAM_IN], &mut [])?; + step(&t, &mut st, SLOT, Step::Finish, &[], &mut [])?; + Ok(()) + } + + #[test] + fn replies_are_judged_by_status_and_length() { + assert_eq!( + check_reply(Command::QueryChannels, &reply(0x0000_0009_0000_000e)), + Outcome::ChannelCount(9) + ); + assert_eq!( + check_reply(Command::QueryChannels, &reply(0x0000_0000_0000_000e)), + Outcome::Malformed + ); + assert_eq!( + check_reply(Command::QueryChannels, &reply(0x0000_0021_0000_000e)), + Outcome::Malformed + ); + assert_eq!( + check_reply(Command::GetRtx, &reply(0x0000_0000_0010_000e)), + Outcome::Malformed + ); + assert_eq!( + check_reply(Command::GetEkpubKm, &reply(0x0000_0000_0080_000e)), + Outcome::Done(128) + ); + assert_eq!( + check_reply(Command::QueryStoredKm, &reply(0x0000_0000_0020_080e)), + Outcome::NotStored + ); + // Status 0x08 means "not stored" for the query only. + assert_eq!( + check_reply(Command::GetRn, &reply(0x0000_0000_0000_080e)), + Outcome::Refused(8) + ); + for w in [ + 0x0000_0000_0000_000fu64, + 0x0000_0000_0100_000e, + 0x0000_0001_0000_000e, + ] { + assert_eq!(check_reply(Command::Start, &reply(w)), Outcome::Malformed); + } + } + + #[test] + fn silence_quarantines_every_slot() -> Result { + let t = Fake::new(&[OK]); + let mut st = state_with_channels(15); + // Open answered, Prepare never: the whole endpoint stops. + assert_eq!( + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; RTX_LEN]), + Err(EIO) + ); + assert!(st.quarantined); + assert!(t.quarantined.get()); + let n = t.sent().len(); + assert_eq!( + step(&t, &mut st, 5, Step::Open, &[], &mut [0; RTX_LEN]), + Err(EIO) + ); + close(&t, &mut st, SLOT); + assert_eq!(t.sent().len(), n); + assert!(!st.sessions[SLOT as usize].is_open()); + Ok(()) + } + + #[test] + fn the_locality_check_may_be_retried_a_bounded_number_of_times() { + use Command::*; + let mut s = Session::new(); + for c in [Open, Prepare, Start, GetRtx, PutCert, PutRrx] { + let arg = match c { + Open => OPEN_ARG, + Prepare => PREPARE_ARG, + _ => 0, + }; + assert!(s.record(c, arg, Outcome::Done(spec_of(c).output))); + } + assert!(s.record(QueryStoredKm, 0, Outcome::Done(32))); + for c in [PutHContext, PutHPrime] { + assert!(s.allows(c, 0)); + assert!(s.record(c, 0, Outcome::Done(0))); + } + // Refused L' allows retrying GetRn while retries remain. + assert!(s.allows(GetRn, 0)); + assert!(s.record(GetRn, 0, Outcome::Done(8))); + assert!(s.allows(LcStart, 0)); + assert!(s.record(LcStart, 0, Outcome::Done(0))); + assert!(s.allows(PutLPrime, 0)); + assert!(!s.record(PutLPrime, 0, Outcome::Refused(1))); + assert!(!s.allows(GetEks, 0)); + for _ in 1..LC_MAX_TRIES { + assert!(s.allows(GetRn, 0)); + assert!(s.record(GetRn, 0, Outcome::Done(8))); + } + assert!(!s.allows(GetRn, 0)); + assert!(s.allows(LcStart, 0)); + assert!(s.record(LcStart, 0, Outcome::Done(0))); + // Refused L' after the last attempt fails the session. + assert!(!s.record(PutLPrime, 0, Outcome::Refused(1))); + assert!(!s.allows(GetRn, 0)); + assert!(!s.allows(GetEks, 0)); + assert!(s.allows(Close, 0)); + } + + #[test] + fn the_table_is_closed_and_fits_the_buffers() { + for (i, a) in SPECS.iter().enumerate() { + assert!(a.input_max <= OOL_SIZE_HDCP && a.output <= u8::MAX as usize); + for b in SPECS[i + 1..].iter() { + assert!(a.id != b.id && a.command != b.command); + } + } + } +} diff --git a/drivers/soc/apple/hdcp_shim.c b/drivers/soc/apple/hdcp_shim.c new file mode 100644 index 00000000000000..2c0d48eb1947c6 --- /dev/null +++ b/drivers/soc/apple/hdcp_shim.c @@ -0,0 +1,297 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * The SEP HDCP 2.2 transmitter service for the display driver + * (include/linux/apple-sep-hdcp.h). The SEP driver registers its steps here; + * this file checks the arguments, flattens them in the order the SEP takes + * them and unpacks the results. It is built in, so the display driver links + * against it whether or not the SEP driver is loaded. + */ +#include +#include +#include +#include +#include +#include +#include + +#include "shim.h" + +static DECLARE_RWSEM(apple_sep_hdcp_registration_lock); +static DEFINE_MUTEX(apple_sep_hdcp_call_lock); +static struct sep_hdcp_ops apple_sep_hdcp_ops; +static void *apple_sep_hdcp_context; + +int sep_hdcp_register(void *context, const struct sep_hdcp_ops *ops) +{ + int ret = 0; + + if (!context || !ops || !ops->available || !ops->step || !ops->close) + return -EINVAL; + + down_write(&apple_sep_hdcp_registration_lock); + if (apple_sep_hdcp_context) { + ret = -EBUSY; + } else { + apple_sep_hdcp_ops = *ops; + apple_sep_hdcp_context = context; + } + up_write(&apple_sep_hdcp_registration_lock); + return ret; +} +EXPORT_SYMBOL_GPL(sep_hdcp_register); + +void sep_hdcp_unregister(void *context) +{ + down_write(&apple_sep_hdcp_registration_lock); + if (apple_sep_hdcp_context == context) { + apple_sep_hdcp_context = NULL; + memzero_explicit(&apple_sep_hdcp_ops, + sizeof(apple_sep_hdcp_ops)); + } + up_write(&apple_sep_hdcp_registration_lock); +} +EXPORT_SYMBOL_GPL(sep_hdcp_unregister); + +static int apple_sep_hdcp_step(u32 channel, enum sep_hdcp_step step, + const u8 *in, size_t in_len, u8 *out, + size_t out_len) +{ + int ret; + + down_read(&apple_sep_hdcp_registration_lock); + if (!apple_sep_hdcp_context) { + ret = -ENODEV; + goto out; + } + mutex_lock(&apple_sep_hdcp_call_lock); + ret = apple_sep_hdcp_ops.step(apple_sep_hdcp_context, channel, step, + in, in_len, out, out_len); + mutex_unlock(&apple_sep_hdcp_call_lock); +out: + up_read(&apple_sep_hdcp_registration_lock); + if (ret && out_len) + memzero_explicit(out, out_len); + return ret; +} + +bool apple_sep_hdcp_available(void) +{ + bool ret = false; + + down_read(&apple_sep_hdcp_registration_lock); + if (apple_sep_hdcp_context) + ret = apple_sep_hdcp_ops.available(apple_sep_hdcp_context); + up_read(&apple_sep_hdcp_registration_lock); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_available); + +int apple_sep_hdcp_open(u32 channel, u8 rtx[APPLE_SEP_HDCP_RTX_LEN]) +{ + if (!rtx) + return -EINVAL; + return apple_sep_hdcp_step(channel, SEP_HDCP_STEP_OPEN, NULL, 0, rtx, + APPLE_SEP_HDCP_RTX_LEN); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_open); + +#define AKE_CERT_IN (APPLE_SEP_HDCP_CERT_LEN + APPLE_SEP_HDCP_RRX_LEN) +#define AKE_CERT_OUT (1 + APPLE_SEP_HDCP_EKPUB_KM_LEN) + +int apple_sep_hdcp_ake_cert(u32 channel, + const u8 cert[APPLE_SEP_HDCP_CERT_LEN], + const u8 rrx[APPLE_SEP_HDCP_RRX_LEN], + bool *stored, struct apple_sep_hdcp_stored_km *km, + u8 ekpub_km[APPLE_SEP_HDCP_EKPUB_KM_LEN]) +{ + u8 *in, *out; + int ret; + + if (!cert || !rrx || !stored || !km || !ekpub_km) + return -EINVAL; + *stored = false; + memzero_explicit(km, sizeof(*km)); + memzero_explicit(ekpub_km, APPLE_SEP_HDCP_EKPUB_KM_LEN); + + in = kmalloc(AKE_CERT_IN + AKE_CERT_OUT, GFP_KERNEL); + if (!in) + return -ENOMEM; + out = in + AKE_CERT_IN; + memcpy(in, cert, APPLE_SEP_HDCP_CERT_LEN); + memcpy(in + APPLE_SEP_HDCP_CERT_LEN, rrx, APPLE_SEP_HDCP_RRX_LEN); + + ret = apple_sep_hdcp_step(channel, SEP_HDCP_STEP_AKE_CERT, in, + AKE_CERT_IN, out, AKE_CERT_OUT); + if (!ret) { + if (out[0]) { + *stored = true; + memcpy(km->ekh_km, out + 1, APPLE_SEP_HDCP_EKH_KM_LEN); + memcpy(km->m, out + 1 + APPLE_SEP_HDCP_EKH_KM_LEN, + APPLE_SEP_HDCP_M_LEN); + } else { + memcpy(ekpub_km, out + 1, APPLE_SEP_HDCP_EKPUB_KM_LEN); + } + } + kfree_sensitive(in); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_ake_cert); + +int apple_sep_hdcp_ake_h_prime(u32 channel, + const u8 rxcaps[APPLE_SEP_HDCP_CAPS_LEN], + const u8 txcaps[APPLE_SEP_HDCP_CAPS_LEN], + const u8 h_prime[APPLE_SEP_HDCP_H_PRIME_LEN]) +{ + u8 in[2 * APPLE_SEP_HDCP_CAPS_LEN + APPLE_SEP_HDCP_H_PRIME_LEN]; + int ret; + + if (!rxcaps || !txcaps || !h_prime) + return -EINVAL; + memcpy(in, rxcaps, APPLE_SEP_HDCP_CAPS_LEN); + memcpy(in + APPLE_SEP_HDCP_CAPS_LEN, txcaps, APPLE_SEP_HDCP_CAPS_LEN); + memcpy(in + 2 * APPLE_SEP_HDCP_CAPS_LEN, h_prime, + APPLE_SEP_HDCP_H_PRIME_LEN); + ret = apple_sep_hdcp_step(channel, SEP_HDCP_STEP_H_PRIME, in, + sizeof(in), NULL, 0); + memzero_explicit(in, sizeof(in)); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_ake_h_prime); + +int apple_sep_hdcp_ake_pairing(u32 channel, + const u8 ekh_km[APPLE_SEP_HDCP_EKH_KM_LEN]) +{ + if (!ekh_km) + return -EINVAL; + return apple_sep_hdcp_step(channel, SEP_HDCP_STEP_PAIRING, ekh_km, + APPLE_SEP_HDCP_EKH_KM_LEN, NULL, 0); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_ake_pairing); + +int apple_sep_hdcp_lc_init(u32 channel, u8 rn[APPLE_SEP_HDCP_RN_LEN]) +{ + if (!rn) + return -EINVAL; + return apple_sep_hdcp_step(channel, SEP_HDCP_STEP_LC_INIT, NULL, 0, rn, + APPLE_SEP_HDCP_RN_LEN); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_lc_init); + +int apple_sep_hdcp_lc_l_prime(u32 channel, + const u8 l_prime[APPLE_SEP_HDCP_L_PRIME_LEN]) +{ + if (!l_prime) + return -EINVAL; + return apple_sep_hdcp_step(channel, SEP_HDCP_STEP_L_PRIME, l_prime, + APPLE_SEP_HDCP_L_PRIME_LEN, NULL, 0); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_lc_l_prime); + +int apple_sep_hdcp_ske(u32 channel, + u8 edkey_ks[APPLE_SEP_HDCP_EDKEY_KS_LEN], + u8 riv[APPLE_SEP_HDCP_RIV_LEN]) +{ + u8 out[APPLE_SEP_HDCP_EDKEY_KS_LEN + APPLE_SEP_HDCP_RIV_LEN]; + int ret; + + if (!edkey_ks || !riv) + return -EINVAL; + ret = apple_sep_hdcp_step(channel, SEP_HDCP_STEP_SKE, NULL, 0, out, + sizeof(out)); + memcpy(edkey_ks, out, APPLE_SEP_HDCP_EDKEY_KS_LEN); + memcpy(riv, out + APPLE_SEP_HDCP_EDKEY_KS_LEN, APPLE_SEP_HDCP_RIV_LEN); + memzero_explicit(out, sizeof(out)); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_ske); + +#define LIST_IN_MAX (APPLE_SEP_HDCP_MAX_DEVICES * APPLE_SEP_HDCP_RECEIVER_ID_LEN + \ + APPLE_SEP_HDCP_RXINFO_LEN + APPLE_SEP_HDCP_SEQ_NUM_LEN + \ + APPLE_SEP_HDCP_V_PRIME_LEN) + +int apple_sep_hdcp_repeater_list(u32 channel, const u8 *ids, unsigned int count, + const u8 rxinfo[APPLE_SEP_HDCP_RXINFO_LEN], + const u8 seq_num_v[APPLE_SEP_HDCP_SEQ_NUM_LEN], + const u8 v_prime[APPLE_SEP_HDCP_V_PRIME_LEN], + u8 v[APPLE_SEP_HDCP_V_LEN]) +{ + u8 in[LIST_IN_MAX]; + size_t n; + int ret; + + if (!v) + return -EINVAL; + memzero_explicit(v, APPLE_SEP_HDCP_V_LEN); + if (!ids || !count || count > APPLE_SEP_HDCP_MAX_DEVICES || !rxinfo || + !seq_num_v || !v_prime) + return -EINVAL; + + /* The order V is computed over: the list, RxInfo, seq_num_V. */ + n = count * APPLE_SEP_HDCP_RECEIVER_ID_LEN; + memcpy(in, ids, n); + memcpy(in + n, rxinfo, APPLE_SEP_HDCP_RXINFO_LEN); + n += APPLE_SEP_HDCP_RXINFO_LEN; + memcpy(in + n, seq_num_v, APPLE_SEP_HDCP_SEQ_NUM_LEN); + n += APPLE_SEP_HDCP_SEQ_NUM_LEN; + memcpy(in + n, v_prime, APPLE_SEP_HDCP_V_PRIME_LEN); + n += APPLE_SEP_HDCP_V_PRIME_LEN; + ret = apple_sep_hdcp_step(channel, SEP_HDCP_STEP_RECEIVER_LIST, in, n, + v, APPLE_SEP_HDCP_V_LEN); + memzero_explicit(in, sizeof(in)); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_repeater_list); + +int apple_sep_hdcp_repeater_stream(u32 channel, u8 stream_id, u8 type, + const u8 seq_num_m[APPLE_SEP_HDCP_SEQ_NUM_LEN], + const u8 m_prime[APPLE_SEP_HDCP_M_PRIME_LEN]) +{ + u8 in[2 + APPLE_SEP_HDCP_SEQ_NUM_LEN + APPLE_SEP_HDCP_M_PRIME_LEN]; + int ret; + + if (type > 1 || !seq_num_m || !m_prime) + return -EINVAL; + /* The order M is computed over: StreamID_Type, then seq_num_M. */ + in[0] = stream_id; + in[1] = type; + memcpy(in + 2, seq_num_m, APPLE_SEP_HDCP_SEQ_NUM_LEN); + memcpy(in + 2 + APPLE_SEP_HDCP_SEQ_NUM_LEN, m_prime, + APPLE_SEP_HDCP_M_PRIME_LEN); + ret = apple_sep_hdcp_step(channel, SEP_HDCP_STEP_STREAM, in, + sizeof(in), NULL, 0); + memzero_explicit(in, sizeof(in)); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_repeater_stream); + +int apple_sep_hdcp_finish(u32 channel) +{ + return apple_sep_hdcp_step(channel, SEP_HDCP_STEP_FINISH, NULL, 0, + NULL, 0); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_finish); + +int apple_sep_hdcp_set_encryption(u32 channel, bool on) +{ + return apple_sep_hdcp_step(channel, + on ? SEP_HDCP_STEP_ENCRYPTION_ON : + SEP_HDCP_STEP_ENCRYPTION_OFF, + NULL, 0, NULL, 0); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_set_encryption); + +void apple_sep_hdcp_close(u32 channel) +{ + down_read(&apple_sep_hdcp_registration_lock); + if (apple_sep_hdcp_context) { + mutex_lock(&apple_sep_hdcp_call_lock); + apple_sep_hdcp_ops.close(apple_sep_hdcp_context, channel); + mutex_unlock(&apple_sep_hdcp_call_lock); + } + up_read(&apple_sep_hdcp_registration_lock); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_close); + +#if IS_BUILTIN(CONFIG_KUNIT) && IS_ENABLED(CONFIG_APPLE_SEP_KUNIT_TEST) +#include "hdcp_shim_test.c" +#endif diff --git a/drivers/soc/apple/hdcp_shim_test.c b/drivers/soc/apple/hdcp_shim_test.c new file mode 100644 index 00000000000000..def94210eaaa0c --- /dev/null +++ b/drivers/soc/apple/hdcp_shim_test.c @@ -0,0 +1,217 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the HDCP shim: argument checks, registration rules, the + * flat layouts handed to the SEP driver, and that outputs are zeroed on + * failure. Included from hdcp_shim.c. A stand-in SEP driver records each step. + */ +#include + +static struct { + u32 channel; + u32 step; + u8 in[256]; + size_t in_len; + size_t out_len; + int ret; + u8 fill; + int calls; + int closes; +} fake; + +static bool fake_available(void *context) +{ + return true; +} + +static int fake_step(void *context, u32 channel, u32 step, const u8 *in, + size_t in_len, u8 *out, size_t out_len) +{ + fake.calls++; + fake.channel = channel; + fake.step = step; + fake.in_len = in_len; + fake.out_len = out_len; + if (in_len <= sizeof(fake.in) && in_len) + memcpy(fake.in, in, in_len); + if (out_len) + memset(out, fake.fill, out_len); + return fake.ret; +} + +static void fake_close(void *context, u32 channel) +{ + fake.closes++; + fake.channel = channel; +} + +static const struct sep_hdcp_ops fake_ops = { + .available = fake_available, + .step = fake_step, + .close = fake_close, +}; + +static int fake_context; + +static int hdcp_shim_init(struct kunit *test) +{ + memset(&fake, 0, sizeof(fake)); + /* A real SEP driver owns the registration: leave it alone. */ + if (sep_hdcp_register(&fake_context, &fake_ops)) + kunit_skip(test, "a SEP driver is registered"); + return 0; +} + +static void hdcp_shim_exit(struct kunit *test) +{ + sep_hdcp_unregister(&fake_context); +} + +static void hdcp_shim_registration_rules(struct kunit *test) +{ + static int other_context; + struct sep_hdcp_ops incomplete = fake_ops; + + KUNIT_EXPECT_EQ(test, sep_hdcp_register(&other_context, &fake_ops), + -EBUSY); + KUNIT_EXPECT_EQ(test, sep_hdcp_register(NULL, &fake_ops), -EINVAL); + incomplete.close = NULL; + KUNIT_EXPECT_EQ(test, sep_hdcp_register(&other_context, &incomplete), + -EINVAL); + /* Unregistering the wrong context must leave the active one intact. */ + sep_hdcp_unregister(&other_context); + KUNIT_EXPECT_TRUE(test, apple_sep_hdcp_available()); +} + +static void hdcp_shim_unregistered_is_enodev(struct kunit *test) +{ + u8 rtx[APPLE_SEP_HDCP_RTX_LEN]; + + sep_hdcp_unregister(&fake_context); + memset(rtx, 0xee, sizeof(rtx)); + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_open(3, rtx), -ENODEV); + KUNIT_EXPECT_TRUE(test, !memchr_inv(rtx, 0, sizeof(rtx))); + KUNIT_EXPECT_FALSE(test, apple_sep_hdcp_available()); + apple_sep_hdcp_close(3); + KUNIT_EXPECT_EQ(test, fake.calls + fake.closes, 0); +} + +static void hdcp_shim_ake_cert_unpacks_both_answers(struct kunit *test) +{ + static u8 cert[APPLE_SEP_HDCP_CERT_LEN]; + u8 rrx[APPLE_SEP_HDCP_RRX_LEN] = { 1, 2, 3, 4, 5, 6, 7, 8 }; + u8 ekpub[APPLE_SEP_HDCP_EKPUB_KM_LEN]; + struct apple_sep_hdcp_stored_km km; + bool stored; + + /* The stand-in fills the whole output: flag 1 means a stored km. */ + fake.fill = 1; + KUNIT_ASSERT_EQ(test, apple_sep_hdcp_ake_cert(7, cert, rrx, &stored, + &km, ekpub), 0); + KUNIT_EXPECT_EQ(test, fake.step, (u32)SEP_HDCP_STEP_AKE_CERT); + KUNIT_EXPECT_EQ(test, fake.channel, 7u); + KUNIT_EXPECT_EQ(test, fake.out_len, + (size_t)(1 + APPLE_SEP_HDCP_EKPUB_KM_LEN)); + KUNIT_EXPECT_TRUE(test, stored); + KUNIT_EXPECT_EQ(test, km.ekh_km[0], 1); + KUNIT_EXPECT_TRUE(test, !memchr_inv(ekpub, 0, sizeof(ekpub))); + + fake.fill = 0; + KUNIT_ASSERT_EQ(test, apple_sep_hdcp_ake_cert(7, cert, rrx, &stored, + &km, ekpub), 0); + KUNIT_EXPECT_FALSE(test, stored); + KUNIT_EXPECT_TRUE(test, !memchr_inv(&km, 0, sizeof(km))); + + fake.fill = 0x77; + fake.ret = -EACCES; + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_ake_cert(7, cert, rrx, &stored, + &km, ekpub), -EACCES); + KUNIT_EXPECT_FALSE(test, stored); + KUNIT_EXPECT_TRUE(test, !memchr_inv(&km, 0, sizeof(km))); + KUNIT_EXPECT_TRUE(test, !memchr_inv(ekpub, 0, sizeof(ekpub))); +} + +static void hdcp_shim_receiver_list_layout_and_bounds(struct kunit *test) +{ + u8 ids[2 * APPLE_SEP_HDCP_RECEIVER_ID_LEN] = { + 0x10, 0x11, 0x12, 0x13, 0x14, 0x20, 0x21, 0x22, 0x23, 0x24 + }; + u8 rxinfo[2] = { 0x02, 0x20 }, seq[3] = { 0, 0, 1 }; + u8 vp[APPLE_SEP_HDCP_V_PRIME_LEN], v[APPLE_SEP_HDCP_V_LEN]; + + memset(vp, 0xab, sizeof(vp)); + KUNIT_ASSERT_EQ(test, apple_sep_hdcp_repeater_list(1, ids, 2, rxinfo, + seq, vp, v), 0); + KUNIT_EXPECT_EQ(test, fake.in_len, (size_t)(10 + 2 + 3 + 16)); + KUNIT_EXPECT_EQ(test, fake.in[5], 0x20); + KUNIT_EXPECT_EQ(test, fake.in[10], 0x02); + KUNIT_EXPECT_EQ(test, fake.in[14], 0x01); + KUNIT_EXPECT_EQ(test, fake.in[15], 0xab); + + fake.calls = 0; + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_repeater_list(1, ids, 0, rxinfo, + seq, vp, v), -EINVAL); + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_repeater_list(1, ids, 32, rxinfo, + seq, vp, v), -EINVAL); + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_repeater_list(1, NULL, 1, rxinfo, + seq, vp, v), -EINVAL); + KUNIT_EXPECT_EQ(test, fake.calls, 0); +} + +static void hdcp_shim_stream_layout_and_type(struct kunit *test) +{ + u8 seq[3] = { 0, 0, 2 }, mp[APPLE_SEP_HDCP_M_PRIME_LEN] = { 0x5a }; + + KUNIT_ASSERT_EQ(test, apple_sep_hdcp_repeater_stream(2, 0, 1, seq, mp), + 0); + KUNIT_EXPECT_EQ(test, fake.step, (u32)SEP_HDCP_STEP_STREAM); + KUNIT_EXPECT_EQ(test, fake.in_len, (size_t)37); + KUNIT_EXPECT_EQ(test, fake.in[0], 0); + KUNIT_EXPECT_EQ(test, fake.in[1], 1); + KUNIT_EXPECT_EQ(test, fake.in[4], 2); + KUNIT_EXPECT_EQ(test, fake.in[5], 0x5a); + fake.calls = 0; + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_repeater_stream(2, 0, 2, seq, mp), + -EINVAL); + KUNIT_EXPECT_EQ(test, fake.calls, 0); +} + +static void hdcp_shim_errors_zero_outputs(struct kunit *test) +{ + u8 rn[APPLE_SEP_HDCP_RN_LEN], eks[APPLE_SEP_HDCP_EDKEY_KS_LEN]; + u8 riv[APPLE_SEP_HDCP_RIV_LEN]; + + fake.fill = 0x99; + fake.ret = -EIO; + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_lc_init(0, rn), -EIO); + KUNIT_EXPECT_TRUE(test, !memchr_inv(rn, 0, sizeof(rn))); + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_ske(0, eks, riv), -EIO); + KUNIT_EXPECT_TRUE(test, !memchr_inv(eks, 0, sizeof(eks))); + KUNIT_EXPECT_TRUE(test, !memchr_inv(riv, 0, sizeof(riv))); + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_open(0, NULL), -EINVAL); + + fake.ret = 0; + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_set_encryption(4, false), 0); + KUNIT_EXPECT_EQ(test, fake.step, (u32)SEP_HDCP_STEP_ENCRYPTION_OFF); + apple_sep_hdcp_close(4); + KUNIT_EXPECT_EQ(test, fake.closes, 1); + KUNIT_EXPECT_TRUE(test, apple_sep_hdcp_available()); +} + +static struct kunit_case hdcp_shim_test_cases[] = { + KUNIT_CASE(hdcp_shim_registration_rules), + KUNIT_CASE(hdcp_shim_unregistered_is_enodev), + KUNIT_CASE(hdcp_shim_ake_cert_unpacks_both_answers), + KUNIT_CASE(hdcp_shim_receiver_list_layout_and_bounds), + KUNIT_CASE(hdcp_shim_stream_layout_and_type), + KUNIT_CASE(hdcp_shim_errors_zero_outputs), + {} +}; + +static struct kunit_suite hdcp_shim_test_suite = { + .name = "apple_sep_hdcp_shim", + .init = hdcp_shim_init, + .exit = hdcp_shim_exit, + .test_cases = hdcp_shim_test_cases, +}; + +kunit_test_suite(hdcp_shim_test_suite); diff --git a/drivers/soc/apple/key.rs b/drivers/soc/apple/key.rs index d227fd887f5382..e1a935bd04a129 100644 --- a/drivers/soc/apple/key.rs +++ b/drivers/soc/apple/key.rs @@ -139,6 +139,23 @@ pub(crate) fn create_policy(flags: u32) -> Result { /// none until this long has passed; one capture itself waits up to a minute. const TOUCH_WAIT_MS: u64 = 60_000; +/// Whether the capture a verify is waiting on is still wanted. +/// +/// While a touch-gated `/dev/sep-key` call owns the capture (`key_wait`), it +/// is wanted until that call ends (`key_ended`: `CANCEL`, a signal, the +/// driver going away) or `/dev/sep-bio` starts an enrolment or a verify of +/// its own (`bio_live`). The call holds the sensor lock, so that capture's +/// work item can only be queued behind it: the call gives the sensor up +/// rather than keep a login prompt waiting for the rest of its minute. +/// Otherwise the capture is `/dev/sep-bio`'s and lives as its session says. +pub(crate) fn touch_capture_wanted(key_wait: bool, key_ended: bool, bio_live: bool) -> bool { + if key_wait { + !key_ended && !bio_live + } else { + bio_live + } +} + const MAGIC: u32 = 0xB1; /// Handle header: `"SEPK"`, version, flags, reserved u16, blob length (LE u32). @@ -962,10 +979,25 @@ pub(crate) trait ContextDelete { impl ContextDelete for SepData { fn delete_context(&self, handle: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]) -> Result<()> { - self.delete_unlock_evaluation(handle) + let result = latch_failed_delete(&self.key_context_failed, self.delete_unlock_evaluation(handle)); + if result.is_err() { + dev_warn_ratelimited!(self.dev, "sep-key: a key context was not deleted; private key operations disabled until reboot\n"); + } + result } } +/// A key operation's context that could not be deleted may still authorize +/// the key it was opened for, so /dev/sep-key stops until reboot. A Touch ID +/// unlock evaluation that /dev/sep-bio fails to delete authorizes no key and +/// is only logged (`close_unlock_evaluation`). +fn latch_failed_delete(failed: &kernel::sync::atomic::Atomic, result: Result<()>) -> Result<()> { + if result.is_err() { + failed.store(true, Relaxed); + } + result +} + /// A credential context the kernel opened for one operation: deleted when /// this is dropped, on every path out of the code that owns it (success, /// error, cancel, timeout, signal). Its handle never leaves the kernel. @@ -1329,6 +1361,22 @@ mod tests { assert!(check_password(&pw).is_err()); } + #[test] + fn a_bio_capture_takes_the_sensor_from_a_key_touch_wait() { + // A touch-gated call waits alone: its capture is wanted. + assert!(touch_capture_wanted(true, false, false)); + // /dev/sep-bio starts a verify or an enrolment behind it: the call + // gives the sensor up at once. + assert!(!touch_capture_wanted(true, false, true)); + // CANCEL, a signal or shutdown ends the wait, also while a + // /dev/sep-bio capture is queued behind it. + assert!(!touch_capture_wanted(true, true, false)); + assert!(!touch_capture_wanted(true, true, true)); + // No touch-gated call: the capture is /dev/sep-bio's own. + assert!(touch_capture_wanted(false, false, true)); + assert!(!touch_capture_wanted(false, false, false)); + } + #[test] fn version_4_ioctls_have_their_sizes() { assert_eq!(IOC_CREATE_USER & 0xff, 0x28); @@ -1376,12 +1424,22 @@ impl SepData { /// touch-gated signature that owns it, or /dev/sep-bio's live session. /// A touch-gated call runs its capture in the caller's own thread, so a /// signal to the caller (or its death) ends the capture at once. + /// A capture `/dev/sep-bio` starts meanwhile ends it too (see + /// [`touch_capture_wanted`]). pub(crate) fn capture_live(&self) -> bool { - (self.key_touch_active.load(Relaxed) - && !self.key_touch_cancel.load(Relaxed) - && !self.shutting_down.load(Relaxed) - && !kernel::current!().signal_pending()) - || crate::bio::capture_is_live(&self.bio_session.lock(), self.capture_epoch.load(Relaxed)) + let key_wait = self.key_touch_active.load(Relaxed); + let key_ended = key_wait + && (self.key_touch_cancel.load(Relaxed) + || self.shutting_down.load(Relaxed) + || kernel::current!().signal_pending()); + touch_capture_wanted(key_wait, key_ended, self.bio_capture_live()) + } + + /// Whether `/dev/sep-bio` has an enrolment or a verify that has not + /// ended. During a touch-gated call, which holds the sensor lock, that + /// is one whose work item waits for the lock. + fn bio_capture_live(&self) -> bool { + crate::bio::capture_is_live(&self.bio_session.lock(), self.capture_epoch.load(Relaxed)) } fn key_bio_acl(&self, any: bool) -> Result { @@ -1583,7 +1641,8 @@ impl SepData { /// A touch-gated operation (see `key_sign_with_touch`). `CANCEL` ends /// the wait with `ECANCELED`, a signal to the caller (including its - /// death) with `EINTR`. + /// death) with `EINTR`, and an enrolment or a verify that `/dev/sep-bio` + /// starts meanwhile with `EBUSY`: the sensor goes to that prompt. fn key_touch_run( &self, blob: &[u8], @@ -1620,6 +1679,9 @@ impl SepData { if kernel::current!().signal_pending() { break Err(EINTR); } + if self.bio_capture_live() { + break Err(EBUSY); + } if !self.capture_begin() { break Err(EAGAIN); } @@ -1646,6 +1708,8 @@ impl SepData { } } Some(TouchOutcome::Failed(s)) if s == crate::ENROL_STATUS_LOCKOUT => break Err(EACCES), + // A capture given up for /dev/sep-bio ends as a failed one. + Some(TouchOutcome::Failed(_)) | None if self.bio_capture_live() => break Err(EBUSY), Some(TouchOutcome::Failed(_)) | None => break Err(EIO), } }; @@ -1694,7 +1758,7 @@ impl SepData { (out.reply.status == 0).then_some(()) })(); if ok.is_none() { - self.close_unlock_evaluation(&handle); + let _ = self.delete_context(&handle); return Err(EIO); } Ok(handle) @@ -1714,9 +1778,10 @@ impl SepData { } let (status, out) = self.scrd_command(&crate::scrd::scrd_context_create_tracked(uid)).ok_or(EIO)?; let ctx = crate::scrd::tracked_create_reference(&out).filter(|_| status == 0).ok_or(EIO)?; - let (status, _) = self.scrd_command(&crate::scrd::scrd_context_externalize(&ctx)).ok_or(EIO)?; - if status != 0 { - self.close_unlock_evaluation(&ctx); + // The context exists once created: an externalize that is refused or + // gets no reply still deletes it. + if !matches!(self.scrd_command(&crate::scrd::scrd_context_externalize(&ctx)), Some((0, _))) { + let _ = self.delete_context(&ctx); return Err(EIO); } let mut verify = 0; @@ -1766,7 +1831,7 @@ impl SepData { req.result2 = v; self.last_key_status.store(0, Relaxed); let r = self.user_key_sign_in_bag(user, &record, &[0x5a; DIGEST_LEN], Some(&ctx)); - self.close_unlock_evaluation(&ctx); + let _ = self.delete_context(&ctx); req.result = r.err().map(|e| e.to_errno()).unwrap_or(0); req.enclave_status = self.last_key_status.load(Relaxed) as i32; dev_info_ratelimited!( @@ -1842,12 +1907,12 @@ impl SepData { r[2] = sign(None); let (fresh, v) = self.key_context_for(designated_id(user), Some((user.special_handle(), &pw[..len])))?; r[3] = if v == 0 { sign(Some(&fresh)) } else { v }; - self.close_unlock_evaluation(&fresh); + let _ = self.delete_context(&fresh); self.userbag_unlock(user, &pw[..len])?; r[7] = self.userbag_lock_phase(user).map(|p| p as i32).unwrap_or(-1); let (fresh2, v2) = self.key_context_for(designated_id(user), Some((user.special_handle(), &pw[..len])))?; r[4] = if v2 == 0 { sign(Some(&fresh2)) } else { v2 }; - self.close_unlock_evaluation(&fresh2); + let _ = self.delete_context(&fresh2); Ok(r) })(); pw.fill(0); @@ -1909,7 +1974,7 @@ impl SepData { } }; (req.result, req.enclave_status) = sign(&ctx); - self.close_unlock_evaluation(&ctx); + let _ = self.delete_context(&ctx); let second = if req.mode == SELFTEST_USERBAG_KEY_SAME_BAG { self.key_context_for(designated_id(user), None) } else { @@ -1918,7 +1983,7 @@ impl SepData { pw.fill(0); let (ctx2, v2) = second?; (req.result2, req.enclave_status2) = sign(&ctx2); - self.close_unlock_evaluation(&ctx2); + let _ = self.delete_context(&ctx2); dev_info_ratelimited!( self.dev, "sep-key: self-test {}: key under uid {}'s bag: first ({}) verify {} -> {} ({}); second ({}) verify {} -> {} ({})\n", @@ -1966,7 +2031,7 @@ impl SepData { let r = self.user_key_sign(&blob, &digest, Some(&ctx)); req.result = r.err().map(|e| e.to_errno()).unwrap_or(0); req.enclave_status = self.last_key_status.load(Relaxed) as i32; - self.close_unlock_evaluation(&ctx); + let _ = self.delete_context(&ctx); dev_info_ratelimited!( self.dev, "sep-key: self-test presence key with a credential from uid {}'s bag: verify status {}, signature {} (enclave status {})\n", @@ -1989,11 +2054,11 @@ impl SepData { self.last_key_status.store(0, Relaxed); let ctx = self.passcode_context()?; (req.result, req.enclave_status) = record(self.user_key_sign(&blob, &digest, Some(&ctx)), self); - self.close_unlock_evaluation(&ctx); + let _ = self.delete_context(&ctx); self.last_key_status.store(0, Relaxed); let ctx = self.open_unlock_evaluation(user).ok_or(EIO)?; (req.result2, req.enclave_status2) = record(self.user_key_sign(&blob, &digest, Some(&ctx)), self); - self.close_unlock_evaluation(&ctx); + let _ = self.delete_context(&ctx); dev_info_ratelimited!( self.dev, "sep-key: self-test presence probe: bag-secret context {} (enclave status {}), unsatisfied context {} (enclave status {})\n", @@ -2189,7 +2254,7 @@ impl SepData { } SELFTEST_DELETED => { let ctx = self.open_unlock_evaluation(user).ok_or(EIO)?; - self.close_unlock_evaluation(&ctx); + let _ = self.delete_context(&ctx); record(self.user_key_sign(&owned, &digest, Some(&ctx)), self) } SELFTEST_TOUCH_THEN_DELETED => { @@ -2625,6 +2690,40 @@ mod one_op_tests { assert!(selftest_mode_built(mode)); } } + + // Only a key context's failed delete stops /dev/sep-key: an owned + // context whose delete is confirmed leaves it running, one whose delete + // fails (finished or dropped) stops it, and a later confirmed delete + // does not restart it. Kept below the host harness's slice, which has + // no kernel atomics. + #[test] + fn only_a_failed_key_context_delete_latches() { + struct Latching { + failed: kernel::sync::atomic::Atomic, + result: Cell>, + } + + impl ContextDelete for Latching { + fn delete_context(&self, _: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]) -> Result<()> { + latch_failed_delete(&self.failed, self.result.get()) + } + } + + let d = Latching { failed: kernel::sync::atomic::Atomic::new(false), result: Cell::new(Ok(())) }; + let h = [0x54; crate::scrd::SCRD_ACM_HANDLE_LEN]; + assert_eq!(OwnedContext::new(&d, h).finish(Ok(7)), Ok(7)); + drop(OwnedContext::new(&d, h)); + assert!(!d.failed.load(Relaxed)); + d.result.set(Err(EIO)); + assert_eq!(OwnedContext::new(&d, h).finish(Ok(7)), Err(EIO)); + assert!(d.failed.load(Relaxed)); + let d = Latching { failed: kernel::sync::atomic::Atomic::new(false), result: Cell::new(Err(EIO)) }; + drop(OwnedContext::new(&d, h)); + assert!(d.failed.load(Relaxed)); + d.result.set(Ok(())); + assert_eq!(OwnedContext::new(&d, h).finish(Ok(7)), Ok(7)); + assert!(d.failed.load(Relaxed)); + } } #[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] diff --git a/drivers/soc/apple/mailbox-g17-test.h b/drivers/soc/apple/mailbox-g17-test.h index 10690d1d27bf78..a7197d411c16dc 100644 --- a/drivers/soc/apple/mailbox-g17-test.h +++ b/drivers/soc/apple/mailbox-g17-test.h @@ -5,7 +5,7 @@ #include static void apple_g17_test_rx(struct apple_mbox *mbox, - struct apple_mbox_msg msg, void *cookie) + struct apple_mbox_msg msg, void *cookie) { unsigned int *count = cookie; @@ -93,8 +93,52 @@ static void apple_g17_rx_util_min_test(struct kunit *test) #endif } +static void apple_g17_rx_hardirq_dispatch_test(struct kunit *test) +{ + const struct apple_mbox_hw hw = { + .i2a_control = 0, .i2a_recv0 = 8, .i2a_recv1 = 16, + .control_empty = BIT(17), + }; + struct apple_mbox mbox = { .hw = &hw, .rx = apple_g17_test_rx }; + unsigned int count = 0; + void *regs = kunit_kzalloc(test, 32, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, regs); + mbox.regs = (void __iomem *)regs; + const struct apple_mbox_hw hw_v8 = { + .i2a_control = 0, .i2a_recv0 = 8, .i2a_recv1 = 16, + .control_empty = BIT(17), + .is_ascwrap_v8 = true, + }; + struct apple_mbox mbox_v8 = { .hw = &hw_v8 }; + + mbox.ascwrap_v6.role = APPLE_MBOX_ASCWRAP_V6_ROLE_GFX; + mbox.cookie = &count; + spin_lock_init(&mbox.rx_lock); + + /* ASCWrap v6 GFX/GFX1 use the hard-IRQ split; ASCWrap v8 stays excluded + * so apple_mbox_recv_irq() keeps running apple_mbox_v8_rx_irq_guard(). + */ + KUNIT_EXPECT_TRUE(test, apple_mbox_is_g17(&mbox)); + mbox_v8.ascwrap_v6.role = APPLE_MBOX_ASCWRAP_V6_ROLE_GFX; + KUNIT_EXPECT_FALSE(test, apple_mbox_is_g17(&mbox_v8)); + mbox_v8.ascwrap_v6.role = APPLE_MBOX_ASCWRAP_V6_ROLE_GFX1; + KUNIT_EXPECT_FALSE(test, apple_mbox_is_g17(&mbox_v8)); + + /* Empty FIFO finishes directly in hard IRQ without waking the thread. */ + writel(BIT(17), mbox.regs); + KUNIT_EXPECT_EQ(test, apple_mbox_g17_recv_irq(0, &mbox), IRQ_HANDLED); + KUNIT_EXPECT_EQ(test, count, 0U); + + /* Saturated budget wakes the oneshot throttle thread. */ + writel(0, mbox.regs); + KUNIT_EXPECT_EQ(test, apple_mbox_g17_recv_irq(0, &mbox), IRQ_WAKE_THREAD); + KUNIT_EXPECT_EQ(test, count, (unsigned int)APPLE_G17_MBOX_RX_BUDGET); +} + static struct kunit_case apple_g17_stall_cases[] = { KUNIT_CASE(apple_g17_rx_flood_bounded_test), + KUNIT_CASE(apple_g17_rx_hardirq_dispatch_test), KUNIT_CASE(apple_g17_tx_stall_bounded_test), KUNIT_CASE(apple_g17_rx_util_min_test), { } diff --git a/drivers/soc/apple/mailbox.c b/drivers/soc/apple/mailbox.c index 689d79858ab2b9..324d68077a665d 100644 --- a/drivers/soc/apple/mailbox.c +++ b/drivers/soc/apple/mailbox.c @@ -68,7 +68,6 @@ #define APPLE_T8140_GFX1_IOP_VBAR_BASE 0x482850000ULL #define APPLE_T6040_GFX_WRAPPER_BASE 0x28a600000ULL #define APPLE_T6040_GFX_IOP_VBAR_BASE 0x28a050000ULL -#define APPLE_T6050_ASCWRAP_BASE_DELTA 0x380000000ULL /* T8142 (M5) moves T8140's 0x4... GPU ASC bank to 0x5.... */ #define APPLE_T8142_ASCWRAP_BASE_DELTA 0x100000000ULL @@ -539,8 +538,9 @@ EXPORT_SYMBOL_GPL(apple_mbox_ascwrap_v6_cpu_stopped); static bool apple_mbox_is_g17(const struct apple_mbox *mbox) { - return mbox->ascwrap_v6.role == APPLE_MBOX_ASCWRAP_V6_ROLE_GFX || - mbox->ascwrap_v6.role == APPLE_MBOX_ASCWRAP_V6_ROLE_GFX1; + return (!mbox->hw || !mbox->hw->is_ascwrap_v8) && + (mbox->ascwrap_v6.role == APPLE_MBOX_ASCWRAP_V6_ROLE_GFX || + mbox->ascwrap_v6.role == APPLE_MBOX_ASCWRAP_V6_ROLE_GFX1); } int apple_mbox_ascwrap_v6_get_cpu_state(struct apple_mbox *mbox, u32 *control, u32 *status) @@ -912,9 +912,9 @@ static int apple_mbox_poll_locked(struct apple_mbox *mbox) } /* - * Threaded receive handler only: apply the consumer's minimum utilization to - * this thread. As an RT thread it otherwise runs with the RT default, which - * makes schedutil raise its CPU cluster to the top frequency on every message. + * Threaded receive handler only (woken on G17 budget saturation): apply the + * consumer's minimum utilization to this thread so flood throttling does not + * leave schedutil raising its CPU cluster to the top RT default frequency. */ static void apple_mbox_apply_rx_util_min(struct apple_mbox *mbox) { @@ -976,10 +976,6 @@ static irqreturn_t apple_mbox_recv_irq(int irq, void *data) unsigned long flags; int consumed = 0; - /* Only the G17 receive handler is threaded (see apple_mbox_probe()). */ - if (apple_mbox_is_g17(mbox)) - apple_mbox_apply_rx_util_min(mbox); - spin_lock_irqsave(&mbox->rx_lock, flags); if (likely(!READ_ONCE(mbox->removing))) consumed = apple_mbox_poll_locked(mbox); @@ -987,16 +983,41 @@ static irqreturn_t apple_mbox_recv_irq(int irq, void *data) apple_mbox_v8_rx_irq_guard(mbox, consumed); spin_unlock_irqrestore(&mbox->rx_lock, flags); - /* G17 uses a oneshot threaded IRQ. Leave it masked during this sleep - * so a firmware flood cannot monopolize a CPU at IRQ-thread priority. - * The level condition retriggers after return; no message is discarded. + return IRQ_HANDLED; +} + +static irqreturn_t apple_mbox_g17_recv_irq(int irq, void *data) +{ + struct apple_mbox *mbox = data; + unsigned long flags; + int consumed = 0; + + spin_lock_irqsave(&mbox->rx_lock, flags); + if (likely(!READ_ONCE(mbox->removing))) + consumed = apple_mbox_poll_locked(mbox); + spin_unlock_irqrestore(&mbox->rx_lock, flags); + + /* + * Normal completions drain completely in hard IRQ without waking the + * IRQ thread. Only a saturated budget hands off to the oneshot thread + * to sleep with the level line masked so a firmware flood cannot + * monopolize a CPU. */ - if (apple_mbox_is_g17(mbox) && consumed == APPLE_G17_MBOX_RX_BUDGET) - usleep_range(1000, 2000); + if (unlikely(consumed == APPLE_G17_MBOX_RX_BUDGET)) + return IRQ_WAKE_THREAD; return IRQ_HANDLED; } +static irqreturn_t apple_mbox_g17_recv_thread(int irq, void *data) +{ + struct apple_mbox *mbox = data; + + apple_mbox_apply_rx_util_min(mbox); + usleep_range(1000, 2000); + return IRQ_HANDLED; +} + bool apple_mbox_send_ready(struct apple_mbox *mbox) { return !(readl_relaxed(mbox->regs + mbox->hw->a2i_control) & mbox->hw->control_full); @@ -1339,14 +1360,14 @@ static void apple_mbox_quiesce(void *data) pm_runtime_barrier(mbox->dev); } -struct apple_mbox *apple_mbox_get(struct device *dev, int index) +struct apple_mbox *apple_mbox_get_prop(struct device *dev, const char *prop, int index) { struct of_phandle_args args; struct platform_device *pdev; struct apple_mbox *mbox; int ret; - ret = of_parse_phandle_with_args(dev->of_node, "mboxes", "#mbox-cells", + ret = of_parse_phandle_with_args(dev->of_node, prop, "#mbox-cells", index, &args); if (ret || !args.np) return ERR_PTR(ret); @@ -1373,6 +1394,12 @@ struct apple_mbox *apple_mbox_get(struct device *dev, int index) return mbox; } +EXPORT_SYMBOL(apple_mbox_get_prop); + +struct apple_mbox *apple_mbox_get(struct device *dev, int index) +{ + return apple_mbox_get_prop(dev, "mboxes", index); +} EXPORT_SYMBOL(apple_mbox_get); struct apple_mbox *apple_mbox_get_byname(struct device *dev, const char *name) @@ -1631,8 +1658,9 @@ static int apple_mbox_probe(struct platform_device *pdev) return -ENOMEM; if (apple_mbox_is_g17(mbox)) - ret = devm_request_threaded_irq(dev, mbox->irq_recv_not_empty, NULL, - apple_mbox_recv_irq, + ret = devm_request_threaded_irq(dev, mbox->irq_recv_not_empty, + apple_mbox_g17_recv_irq, + apple_mbox_g17_recv_thread, IRQF_ONESHOT | IRQF_NO_AUTOEN | IRQF_NO_SUSPEND, irqname, mbox); @@ -1881,19 +1909,9 @@ static const struct apple_mbox_hw apple_mbox_t8152_gfx_ascwrap_v8_hw = { static_assert(0x20 + sizeof(u32) <= APPLE_ASCWRAP_V8_MBOX_SIZE); -/* Retained T6050 wrapper/VBAR alias profile. */ -static const struct apple_mbox_ascwrap_v6_role_desc apple_mbox_t6050_ascwrap_v6_roles[] = { - { "GFX", APPLE_MBOX_ASCWRAP_V6_ROLE_GFX, - APPLE_T8140_GFX_WRAPPER_BASE + APPLE_T6050_ASCWRAP_BASE_DELTA, - APPLE_T8140_GFX_IOP_VBAR_BASE + APPLE_T6050_ASCWRAP_BASE_DELTA }, - { "GFX1", APPLE_MBOX_ASCWRAP_V6_ROLE_GFX1, - APPLE_T8140_GFX1_WRAPPER_BASE + APPLE_T6050_ASCWRAP_BASE_DELTA, - APPLE_T8140_GFX1_IOP_VBAR_BASE + APPLE_T6050_ASCWRAP_BASE_DELTA }, -}; - /* * T6050 at its physical addresses, with both roles in the GPU aperture at - * 0x2300000000 on die 0. The other T6050 profiles retain their alias windows. + * 0x2300000000 on die 0. */ static const struct apple_mbox_ascwrap_v6_role_desc apple_mbox_t6050_j775d_ascwrap_v6_roles[] = { { "GFX", APPLE_MBOX_ASCWRAP_V6_ROLE_GFX, @@ -1902,22 +1920,6 @@ static const struct apple_mbox_ascwrap_v6_role_desc apple_mbox_t6050_j775d_ascwr APPLE_J775D_GFX1_WRAPPER_BASE, APPLE_J775D_GFX1_IOP_VBAR_BASE }, }; -static const struct apple_mbox_hw apple_mbox_t6050_ascwrap_v6_hw = { - .reg_offset = APPLE_ASCWRAP_V6_MBOX_OFFSET, - .is_ascwrap_v6 = true, - .ascwrap_v6_roles = apple_mbox_t6050_ascwrap_v6_roles, - .num_ascwrap_v6_roles = ARRAY_SIZE(apple_mbox_t6050_ascwrap_v6_roles), - .control_full = APPLE_ASC_MBOX_CONTROL_FULL, - .control_empty = APPLE_ASC_MBOX_CONTROL_EMPTY, - .a2i_control = APPLE_ASC_MBOX_A2I_CONTROL, - .a2i_send0 = APPLE_ASC_MBOX_A2I_SEND0, - .a2i_send1 = APPLE_ASC_MBOX_A2I_SEND1, - .i2a_control = APPLE_ASC_MBOX_I2A_CONTROL, - .i2a_recv0 = APPLE_ASC_MBOX_I2A_RECV0, - .i2a_recv1 = APPLE_ASC_MBOX_I2A_RECV1, - .has_irq_controls = false, -}; - static const struct apple_mbox_hw apple_mbox_t6050_j775d_ascwrap_v6_hw = { .reg_offset = APPLE_ASCWRAP_V6_MBOX_OFFSET, .is_ascwrap_v6 = true, @@ -1953,14 +1955,14 @@ static const struct apple_mbox_hw apple_mbox_t8152_smc_hw = { static const struct of_device_id apple_mbox_of_match[] = { { .compatible = "apple,t8152-smc-mailbox", .data = &apple_mbox_t8152_smc_hw }, + /* The AOP's ASC wrapper mailbox has the SMC mailbox's counted FIFOs. */ + { .compatible = "apple,t8152-ascwrap-v8-mailbox", .data = &apple_mbox_t8152_smc_hw }, { .compatible = "apple,t6031-agx-asc-mailbox", .data = &apple_mbox_asc_hw }, { .compatible = "apple,t8122-agx-asc-mailbox", .data = &apple_mbox_asc_hw }, { .compatible = "apple,t8152-gfx-ascwrap-v8", .data = &apple_mbox_t8152_gfx_ascwrap_v8_hw }, { .compatible = "apple,t6040-ascwrap-v6", .data = &apple_mbox_t6040_ascwrap_v6_hw }, { .compatible = "apple,t8140-ascwrap-v6", .data = &apple_mbox_t8140_ascwrap_v6_hw }, { .compatible = "apple,t8142-ascwrap-v6", .data = &apple_mbox_t8142_ascwrap_v6_hw }, - { .compatible = "apple,t6050-ascwrap-v6", .data = &apple_mbox_t6050_ascwrap_v6_hw }, - { .compatible = "apple,t6050-x1n1-ascwrap-v6", .data = &apple_mbox_t6050_ascwrap_v6_hw }, { .compatible = "apple,t6050-j775d-ascwrap-v6", .data = &apple_mbox_t6050_j775d_ascwrap_v6_hw }, { .compatible = "apple,t8140-asc-mailbox", .data = &apple_mbox_t8140_asc_hw }, diff --git a/drivers/soc/apple/mcc-boot-dma.c b/drivers/soc/apple/mcc-boot-dma.c new file mode 100644 index 00000000000000..0dc303327468d5 --- /dev/null +++ b/drivers/soc/apple/mcc-boot-dma.c @@ -0,0 +1,304 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * A display controller can keep scanning out the boot loader's framebuffer + * after it binds, or with its node disabled. Its driver reserves a record + * while it tracks that boot scanout and marks it once a displayed swap of + * its own has retired it. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct apple_mcc_scanout { + struct list_head link; + struct device_node *supplier; + bool retired; +}; + +struct apple_mcc_scanout_waiter { + struct list_head link; + struct device_node *consumer; + struct device_node *supplier; +}; + +/* + * Retirement survives either driver's unbind and reprobe; records and + * waiters go when a node they name is detached. + */ +static DEFINE_MUTEX(boot_scanout_lock); +static LIST_HEAD(boot_scanouts); +static LIST_HEAD(waiting_consumers); +static LIST_HEAD(retry_consumers); +static LIST_HEAD(enabled_consumers); + +/* A node detached already: the notifier has dropped, or will drop, its entries. */ +static bool node_detached(struct device_node *np) +{ + return of_node_check_flag(np, OF_DETACHED); +} + +static struct apple_mcc_scanout *find_scanout_locked(struct device_node *supplier) +{ + struct apple_mcc_scanout *scanout; + + list_for_each_entry(scanout, &boot_scanouts, link) { + if (scanout->supplier == supplier) + return scanout; + } + return NULL; +} + +int apple_mcc_boot_scanout_reserve(struct device_node *supplier) +{ + struct apple_mcc_scanout *scanout; + int ret = 0; + + mutex_lock(&boot_scanout_lock); + if (node_detached(supplier)) { + ret = -ENODEV; + goto out_unlock; + } + /* A scanout retired before the supplier was rebound stays retired. */ + if (find_scanout_locked(supplier)) + goto out_unlock; + scanout = kzalloc_obj(*scanout); + if (!scanout) { + ret = -ENOMEM; + goto out_unlock; + } + scanout->supplier = of_node_get(supplier); + list_add_tail(&scanout->link, &boot_scanouts); + +out_unlock: + mutex_unlock(&boot_scanout_lock); + return ret; +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_scanout_reserve); + +/* + * Held across a cache controller's final check of its nodes and its + * allocation enable, and by the detach notifier. OF flags a node detached + * before it calls the notifier, so probe cannot hold a detach off; but the + * notifier always runs after the flag is set. Either probe sees the flag, + * or it enabled allocation and registered first, and the notifier then + * turns allocation off (apple_mcc_boot_dma_lost()). + */ +void apple_mcc_boot_dma_lock(void) +{ + mutex_lock(&boot_scanout_lock); +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_dma_lock); + +void apple_mcc_boot_dma_unlock(void) +{ + mutex_unlock(&boot_scanout_lock); +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_dma_unlock); + +/* Under apple_mcc_boot_dma_lock(), once allocation is enabled. */ +void apple_mcc_boot_dma_register_locked(struct apple_mcc_boot_dma_consumer *consumer) +{ + list_add_tail(&consumer->link, &enabled_consumers); +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_dma_register_locked); + +/* Before the consumer turns allocation off and goes. */ +void apple_mcc_boot_dma_unregister(struct apple_mcc_boot_dma_consumer *consumer) +{ + mutex_lock(&boot_scanout_lock); + list_del_init(&consumer->link); + mutex_unlock(&boot_scanout_lock); +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_dma_unregister); + +/* + * Whether detaching @np leaves @consumer's boot DMA unconfirmed: its own + * node, or a boot DMA supplier whose boot scanout has not retired. The + * detached node no longer resolves, so match its phandle. + */ +static bool consumer_loses_boot_dma_locked(struct apple_mcc_boot_dma_consumer *consumer, + struct device_node *np) +{ + struct device_node *node = consumer->dev->of_node; + struct apple_mcc_scanout *scanout; + u32 phandle; + int i, n; + + if (node == np) + return true; + if (!np->phandle) + return false; + n = of_property_count_u32_elems(node, "apple,boot-dma-devices"); + for (i = 0; i < n; i++) { + if (of_property_read_u32_index(node, "apple,boot-dma-devices", i, &phandle) || + phandle != np->phandle) + continue; + scanout = find_scanout_locked(np); + return !scanout || !scanout->retired; + } + return false; +} + +static void waiter_free(struct apple_mcc_scanout_waiter *waiter) +{ + of_node_put(waiter->consumer); + of_node_put(waiter->supplier); + kfree(waiter); +} + +int apple_mcc_boot_scanout_ready(struct device *dev, struct device_node *supplier) +{ + struct apple_mcc_scanout_waiter *waiter; + struct apple_mcc_scanout *scanout; + struct device_node *consumer = dev->of_node; + int ret = -EPROBE_DEFER; + + mutex_lock(&boot_scanout_lock); + if (node_detached(consumer) || node_detached(supplier)) { + ret = -ENODEV; + goto out_unlock; + } + scanout = find_scanout_locked(supplier); + if (scanout && scanout->retired) { + ret = 0; + goto out_unlock; + } + + list_for_each_entry(waiter, &waiting_consumers, link) { + if (waiter->consumer == consumer && waiter->supplier == supplier) + goto out_unlock; + } + waiter = kzalloc_obj(*waiter); + if (!waiter) { + ret = -ENOMEM; + goto out_unlock; + } + waiter->consumer = of_node_get(consumer); + waiter->supplier = of_node_get(supplier); + list_add_tail(&waiter->link, &waiting_consumers); + +out_unlock: + mutex_unlock(&boot_scanout_lock); + return ret; +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_scanout_ready); + +static void apple_mcc_retry(struct work_struct *work) +{ + struct apple_mcc_scanout_waiter *waiter, *tmp; + LIST_HEAD(pending); + + mutex_lock(&boot_scanout_lock); + list_splice_tail_init(&retry_consumers, &pending); + mutex_unlock(&boot_scanout_lock); + + list_for_each_entry_safe(waiter, tmp, &pending, link) { + struct platform_device *pdev = NULL; + + list_del(&waiter->link); + mutex_lock(&boot_scanout_lock); + if (!node_detached(waiter->consumer) && !node_detached(waiter->supplier)) + pdev = of_find_device_by_node(waiter->consumer); + mutex_unlock(&boot_scanout_lock); + if (pdev) { + device_initial_probe(&pdev->dev); + put_device(&pdev->dev); + } + waiter_free(waiter); + } +} + +static DECLARE_WORK(retry_work, apple_mcc_retry); + +void apple_mcc_boot_scanout_retired(struct device_node *supplier) +{ + struct apple_mcc_scanout_waiter *waiter, *tmp; + struct apple_mcc_scanout *scanout; + bool schedule = false; + + mutex_lock(&boot_scanout_lock); + /* Reserved by apple_mcc_boot_scanout_reserve(): marking it cannot fail. */ + scanout = find_scanout_locked(supplier); + if (scanout) + scanout->retired = true; + else + WARN_ON_ONCE(!node_detached(supplier)); + + list_for_each_entry_safe(waiter, tmp, &waiting_consumers, link) { + if (waiter->supplier == supplier) { + list_move_tail(&waiter->link, &retry_consumers); + schedule = true; + } + } + mutex_unlock(&boot_scanout_lock); + + if (schedule) + schedule_work(&retry_work); +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_scanout_retired); + +static void drop_waiters_locked(struct list_head *list, struct device_node *np) +{ + struct apple_mcc_scanout_waiter *waiter, *tmp; + + list_for_each_entry_safe(waiter, tmp, list, link) { + if (waiter->consumer == np || waiter->supplier == np) { + list_del(&waiter->link); + waiter_free(waiter); + } + } +} + +static int apple_mcc_of_notify(struct notifier_block *nb, unsigned long action, void *arg) +{ + struct apple_mcc_boot_dma_consumer *consumer, *next; + struct of_reconfig_data *rd = arg; + struct apple_mcc_scanout *scanout, *tmp; + + if (action != OF_RECONFIG_DETACH_NODE) + return NOTIFY_DONE; + + mutex_lock(&boot_scanout_lock); + /* Before the records go: a retired supplier may detach. */ + list_for_each_entry_safe(consumer, next, &enabled_consumers, link) { + if (consumer_loses_boot_dma_locked(consumer, rd->dn)) { + list_del_init(&consumer->link); + consumer->lost(consumer); + } + } + list_for_each_entry_safe(scanout, tmp, &boot_scanouts, link) { + if (scanout->supplier == rd->dn) { + list_del(&scanout->link); + of_node_put(scanout->supplier); + kfree(scanout); + } + } + drop_waiters_locked(&waiting_consumers, rd->dn); + drop_waiters_locked(&retry_consumers, rd->dn); + mutex_unlock(&boot_scanout_lock); + return NOTIFY_OK; +} + +static struct notifier_block apple_mcc_of_nb = { + .notifier_call = apple_mcc_of_notify, +}; + +static int __init apple_mcc_boot_dma_init(void) +{ + /* Without CONFIG_OF_DYNAMIC no node is ever detached. */ + if (IS_ENABLED(CONFIG_OF_DYNAMIC)) + return of_reconfig_notifier_register(&apple_mcc_of_nb); + return 0; +} +core_initcall(apple_mcc_boot_dma_init); diff --git a/drivers/soc/apple/mcc.c b/drivers/soc/apple/mcc.c index ae15c4ea54e1bb..d962b9f0de3285 100644 --- a/drivers/soc/apple/mcc.c +++ b/drivers/soc/apple/mcc.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #if IS_ENABLED(CONFIG_APPLE_MCC_KUNIT_TEST) @@ -33,7 +34,8 @@ #define MCC_CACHE_FLUSH 0x2844 #define MCC_CACHE_FLUSH_BUSY BIT(0) -#define MCC_MAX_PLANES 32 +/* T6050: eight AMCCs of four planes on each die, 64 planes on two dies. */ +#define MCC_MAX_PLANES 64 #define MCC_FLUSH_TIMEOUT_US 100000 struct apple_mcc { @@ -50,6 +52,7 @@ struct apple_mcc { u32 ways; /* Turned off for a deep sleep, to be turned back on after it. */ bool sleep_disabled; + struct apple_mcc_boot_dma_consumer boot_dma; }; static void apple_mcc_writel(struct apple_mcc *mcc, unsigned int plane, @@ -135,17 +138,76 @@ static int apple_mcc_enable_t8132(struct apple_mcc *mcc) return 0; } +/* An enabled boot framebuffer that names @supplier as its display hardware. */ +static bool apple_mcc_scans_boot_framebuffer(struct device_node *supplier) +{ + struct device_node *fb, *display; + + for_each_compatible_node(fb, NULL, "simple-framebuffer") { + if (!of_device_is_available(fb)) + continue; + display = of_parse_phandle(fb, "display", 0); + of_node_put(display); + if (display && display == supplier) { + of_node_put(fb); + return true; + } + } + return false; +} + static int apple_mcc_wait_boot_dma(struct device *dev) { struct of_phandle_iterator it; int ret; + /* A detached node's suppliers can no longer be confirmed. */ + if (of_node_check_flag(dev->of_node, OF_DETACHED)) + return -ENODEV; + of_for_each_phandle(&it, ret, dev->of_node, "apple,boot-dma-devices", NULL, 0) { - struct platform_device *pdev = of_find_device_by_node(it.node); - bool bound = pdev && device_is_bound(&pdev->dev); + struct platform_device *pdev; + bool bound; + + /* + * An empty entry names no device. A phandle that resolves to + * no node is a device tree error that a retry cannot fix, and + * leaves its boot DMA unconfirmed: keep allocation off. + */ + if (!it.node) { + if (!it.phandle) + continue; + return dev_err_probe(dev, -EINVAL, + "boot DMA supplier phandle %#x does not resolve\n", + it.phandle); + } + if (of_node_check_flag(it.node, OF_DETACHED)) { + of_node_put(it.node); + return -ENODEV; + } + + /* + * A display controller scanning out the boot framebuffer keeps + * that DMA running whether or not its node is enabled or bound, + * until its driver reports a displayed swap of its own. + */ + if (apple_mcc_scans_boot_framebuffer(it.node)) { + ret = apple_mcc_boot_scanout_ready(dev, it.node); + if (ret) { + ret = dev_err_probe(dev, ret, + "waiting for %pOF to retire boot scanout\n", + it.node); + of_node_put(it.node); + return ret; + } + } + + pdev = of_find_device_by_node(it.node); + bound = pdev && device_is_bound(&pdev->dev); if (pdev) put_device(&pdev->dev); + /* A disabled DT node can still have DMA left running. */ if (!bound) { ret = dev_err_probe(dev, -EPROBE_DEFER, "waiting for %pOF to bind\n", it.node); @@ -157,6 +219,29 @@ static int apple_mcc_wait_boot_dma(struct device *dev) return ret == -ENOENT ? 0 : ret; } +/* Under apple_mcc_boot_dma_lock(): the last check before allocation is enabled. */ +static bool apple_mcc_boot_dma_detached(struct device *dev) +{ + struct of_phandle_iterator it; + int ret; + + if (of_node_check_flag(dev->of_node, OF_DETACHED)) + return true; + of_for_each_phandle(&it, ret, dev->of_node, "apple,boot-dma-devices", NULL, 0) { + /* The first walk resolved it: a node that went is detached. */ + if (!it.node) { + if (it.phandle) + return true; + continue; + } + if (of_node_check_flag(it.node, OF_DETACHED)) { + of_node_put(it.node); + return true; + } + } + return false; +} + static bool apple_mcc_plane_ready(struct apple_mcc *mcc, unsigned int plane) { void __iomem *regs = mcc->planes[plane]; @@ -252,6 +337,32 @@ static void apple_mcc_quiesce(struct apple_mcc *mcc) mcc->enabled = false; } +/* Turn allocation off for good: removal, or a boot DMA node detached. */ +static void apple_mcc_turn_off(struct apple_mcc *mcc) +{ + /* Without this driver nothing writes T8132's cache back before a deep sleep. */ + if (mcc->retained) { + apple_mcc_disable_t8132(mcc); + mcc->enabled = false; + return; + } + apple_mcc_quiesce(mcc); +} + +/* + * The detach notifier, under the boot DMA lock. Only the disable and its + * write-back: marked not enabled, nothing later writes this cache back. + */ +static void apple_mcc_boot_dma_lost(struct apple_mcc_boot_dma_consumer *consumer) +{ + struct apple_mcc *mcc = container_of(consumer, struct apple_mcc, boot_dma); + + dev_warn(mcc->dev, "boot DMA node detached: system level cache allocation off\n"); + apple_mcc_turn_off(mcc); + /* Nor does a wake turn it back on. */ + mcc->sleep_disabled = false; +} + static int apple_mcc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -263,7 +374,11 @@ static int apple_mcc_probe(struct platform_device *pdev) return -ENOMEM; mcc->dev = dev; - mcc->retained = of_device_is_compatible(dev->of_node, "apple,t8132-mcc"); + INIT_LIST_HEAD(&mcc->boot_dma.link); + mcc->boot_dma.dev = dev; + mcc->boot_dma.lost = apple_mcc_boot_dma_lost; + mcc->retained = of_device_is_compatible(dev->of_node, "apple,t8122-mcc") || + of_device_is_compatible(dev->of_node, "apple,t8132-mcc"); mcc->ways_off = of_device_is_compatible(dev->of_node, "apple,t8142-mcc"); while (platform_get_resource(pdev, IORESOURCE_MEM, mcc->nr_planes)) { struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, mcc->nr_planes); @@ -286,14 +401,30 @@ static int apple_mcc_probe(struct platform_device *pdev) platform_set_drvdata(pdev, mcc); + /* + * A node detached after this check is flagged before, and notified + * after, the enable below: the notifier finds this controller + * registered and turns allocation off again. The lock is held across + * the enable, including a failed enable's write-back of the planes it + * reached (up to MCC_FLUSH_TIMEOUT_US each), which delays a detach. + */ + apple_mcc_boot_dma_lock(); + if (apple_mcc_boot_dma_detached(dev)) { + apple_mcc_boot_dma_unlock(); + return -ENODEV; + } /* Allocation is only a performance setting: leave a cache that is not ready alone. */ ret = mcc->retained ? apple_mcc_enable_t8132(mcc) : apple_mcc_enable(mcc); + if (!ret) { + mcc->enabled = true; + apple_mcc_boot_dma_register_locked(&mcc->boot_dma); + } + apple_mcc_boot_dma_unlock(); if (ret == -EBUSY) return 0; if (ret) return ret; - mcc->enabled = true; if (mcc->ways_off) mcc->ways = FIELD_GET(MCC_CACHE_WAYS_ENABLED, readl(mcc->planes[0] + MCC_CACHE_WAYS)); @@ -305,28 +436,27 @@ static void apple_mcc_remove(struct platform_device *pdev) { struct apple_mcc *mcc = platform_get_drvdata(pdev); - /* Without this driver nothing writes T8132's cache back before a deep sleep. */ - if (mcc->retained) { - apple_mcc_disable_t8132(mcc); - mcc->enabled = false; - return; - } - apple_mcc_quiesce(mcc); + /* After this, the detach notifier no longer reaches this controller. */ + apple_mcc_boot_dma_unregister(&mcc->boot_dma); + apple_mcc_turn_off(mcc); } static void apple_mcc_shutdown(struct platform_device *pdev) { struct apple_mcc *mcc = platform_get_drvdata(pdev); - if (mcc) - apple_mcc_quiesce(mcc); + if (!mcc) + return; + apple_mcc_boot_dma_lock(); + apple_mcc_quiesce(mcc); + apple_mcc_boot_dma_unlock(); } /* * A deep sleep takes the cache's power with the rest of the SoC: stop allocating and write it * back first, as at shutdown, and allocate again after. Suspend-to-idle keeps it. */ -static int apple_mcc_suspend_noirq(struct device *dev) +static int apple_mcc_suspend_locked(struct device *dev) { struct apple_mcc *mcc = dev_get_drvdata(dev); int ret; @@ -358,7 +488,7 @@ static int apple_mcc_suspend_noirq(struct device *dev) return 0; } -static int apple_mcc_resume_noirq(struct device *dev) +static int apple_mcc_resume_locked(struct device *dev) { struct apple_mcc *mcc = dev_get_drvdata(dev); int ret; @@ -379,14 +509,41 @@ static int apple_mcc_resume_noirq(struct device *dev) return 0; } +/* + * Serialized with the OF detach notifier, which may turn allocation off + * and cancel the enable after the wake. Noirq callbacks may sleep, and + * nothing taken under the lock takes it again. + */ +static int apple_mcc_suspend_noirq(struct device *dev) +{ + int ret; + + apple_mcc_boot_dma_lock(); + ret = apple_mcc_suspend_locked(dev); + apple_mcc_boot_dma_unlock(); + return ret; +} + +static int apple_mcc_resume_noirq(struct device *dev) +{ + int ret; + + apple_mcc_boot_dma_lock(); + ret = apple_mcc_resume_locked(dev); + apple_mcc_boot_dma_unlock(); + return ret; +} + static const struct dev_pm_ops apple_mcc_pm_ops = { NOIRQ_SYSTEM_SLEEP_PM_OPS(apple_mcc_suspend_noirq, apple_mcc_resume_noirq) }; static const struct of_device_id apple_mcc_of_match[] = { + { .compatible = "apple,t8122-mcc" }, { .compatible = "apple,t8132-mcc" }, { .compatible = "apple,t8140-mcc" }, { .compatible = "apple,t8142-mcc" }, + { .compatible = "apple,t6050-mcc" }, {} }; MODULE_DEVICE_TABLE(of, apple_mcc_of_match); diff --git a/drivers/soc/apple/pm.rs b/drivers/soc/apple/pm.rs index e18e84bb1986a3..d479bf866ae4c6 100644 --- a/drivers/soc/apple/pm.rs +++ b/drivers/soc/apple/pm.rs @@ -38,6 +38,9 @@ extern "C" { fn sep_pm_keep_domains(dev: *mut c_void) -> c_int; fn sep_pm_clear_dev_disable(dev: *mut c_void) -> c_int; fn sep_pm_dart_restore(dev: *mut c_void); + fn sep_pm_dart_prepare(dev: *mut c_void) -> c_int; + fn sep_pm_wait_gated(dev: *mut c_void, timeout_ms: c_uint) -> c_int; + fn sep_pm_platform_commit() -> bool; fn sep_pm_commit_prepare( dev: *mut c_void, mbox: *mut c_void, @@ -128,6 +131,31 @@ pub(crate) fn commit_finish(dev: &kernel::device::Device) -> Option { } /// Puts the enclave's DART back if it lost its state, before the doorbell. +/// How long the enclave gets to gate its domain once it has answered (told at suspend). +const GATE_TIMEOUT_MS: u32 = 5000; + +/// Whether a sleep core commit sends the staged SLEEP; if not, it is sent at device suspend. +pub(crate) fn platform_commit() -> bool { + // SAFETY: only reads the sleep core's state. + unsafe { sep_pm_platform_commit() } +} + +/// Whether the enclave gated itself within the bound. +pub(crate) fn wait_gated(dev: &kernel::device::Device) -> bool { + // SAFETY: `dev` is the bound SEP device. + unsafe { sep_pm_wait_gated(dev.as_raw().cast(), GATE_TIMEOUT_MS) == 0 } +} + +/// Saves the enclave's DART while it can be read, before the enclave is told. +pub(crate) fn dart_prepare(dev: &kernel::device::Device) -> Result<()> { + // SAFETY: `dev` is the bound SEP device. + let rc = unsafe { sep_pm_dart_prepare(dev.as_raw().cast()) }; + if rc != 0 { + return Err(Error::from_errno(rc)); + } + Ok(()) +} + pub(crate) fn dart_restore(dev: &kernel::device::Device) { // SAFETY: `dev` is the bound SEP device. unsafe { sep_pm_dart_restore(dev.as_raw().cast()) }; diff --git a/drivers/soc/apple/pm_shim.c b/drivers/soc/apple/pm_shim.c index c1d415c0bd7447..221634f03a3dbc 100644 --- a/drivers/soc/apple/pm_shim.c +++ b/drivers/soc/apple/pm_shim.c @@ -8,6 +8,7 @@ * read here. On T8140 at EL2 the sleep driver sends the request at the * irreversible commit boundary. Only errors before send may refuse. */ +#include #include #include #include @@ -36,6 +37,15 @@ #define SEP_PS_DEV_DISABLE BIT(10) #define SEP_PS_ACTUAL GENMASK(7, 4) +/* + * After its sleep request, the enclave has gone down: DEV_DISABLE where its firmware sets + * it, or its actual state at 0. The M1's enclave never sets DEV_DISABLE (measured on J313). + */ +static bool sep_ps_down(u32 state) +{ + return (state & SEP_PS_DEV_DISABLE) || !FIELD_GET(SEP_PS_ACTUAL, state); +} + /* One-shot precommit test: no SLEEP request or commit coprocessor stop. */ static bool sleep_refuse_before_send; module_param(sleep_refuse_before_send, bool, 0644); @@ -155,6 +165,39 @@ static struct device *sep_pm_dart(struct device *dev) return pdev ? &pdev->dev : NULL; } +/* + * Saves the enclave's DART while it can be read, before the enclave is told at suspend. Only + * a DART with apple,sleep-restore in its node is saved here and then left alone by its own + * callbacks. Without it, the DART's noirq suspend would read its registers after the enclave + * slept and its power domain went off, which hangs the suspend: refuse instead. + */ +int sep_pm_dart_prepare(void *ptr) +{ + struct device *dart = sep_pm_dart(ptr); + int ret; + + if (!dart) + return -ENODEV; + if (!apple_dart_sleep_listed(dart)) { + dev_err(dart, "no apple,sleep-restore list: the enclave can't sleep at suspend\n"); + put_device(dart); + return -EOPNOTSUPP; + } + ret = apple_dart_sleep_prepare(dart); + put_device(dart); + + return ret; +} + +/* + * Whether a sleep core commit sends the staged SLEEP (T8140). Without one, a firmware suspend + * (T6041's own sleep driver) tells the enclave at device suspend instead. + */ +bool sep_pm_platform_commit(void) +{ + return apple_sleep_commit_stops_coprocs(); +} + void sep_pm_dart_restore(void *ptr) { struct device *dart = sep_pm_dart(ptr); @@ -301,7 +344,7 @@ static int sep_pm_commit_stop(void *data) * the native contract, not proved atomic by the preceding PMGR sample. */ apple_mbox_set_recv_enabled(c->mbox, false); - c->gate_ret = readl_poll_timeout_atomic(c->ps, c->state, c->state & SEP_PS_DEV_DISABLE, + c->gate_ret = readl_poll_timeout_atomic(c->ps, c->state, sep_ps_down(c->state), SEP_PM_POLL_US, SEP_PM_TIMEOUT_US); c->gate_valid = true; if (c->gate_ret) diff --git a/drivers/soc/apple/pmp-telemetry.c b/drivers/soc/apple/pmp-telemetry.c index 529f9826e1635e..0e9e0d078fe8d8 100644 --- a/drivers/soc/apple/pmp-telemetry.c +++ b/drivers/soc/apple/pmp-telemetry.c @@ -12,14 +12,15 @@ #include #include #include +#include +#include #include #include #include -#include bool apple_pmp_telemetry_retained_board(void) { - return apple_t8132_firmware_path(); + return apple_pmp_t8132_retained_board(); } static LIST_HEAD(apple_pmp_telemetry_list); @@ -35,14 +36,82 @@ struct apple_pmp_telemetry { spinlock_t gpu_lock; struct apple_pmp_gpu_lease gpu; u64 generation; + size_t size; + /* Where the running firmware keeps each temperature record. */ + struct apple_pmp_temp_map temps; + struct delayed_work locate; + unsigned int locate_tries; }; +/* + * The RTKit header word at 0x234 gives the start of the firmware's data + * range in SRAM (0x3c000 on 26.6.2/25G83, 0x3d000 on 27.2/26B123, matching + * ADT segment-ranges). + */ +#define PMP_TEMP_DATA_START_HDR 0x234 +#define PMP_TEMP_LOCATE_MS 1000 +#define PMP_TEMP_LOCATE_TRIES 60 + static bool apple_pmp_telemetry_online(const struct apple_pmp_telemetry *sensors) { return READ_ONCE(sensors->online) && (readl(sensors->asc + 0x44) & BIT(4)); } +static bool apple_pmp_temps_at(struct apple_pmp_telemetry *sensors, + const struct apple_pmp_temp_map *map) +{ + u8 record[PMP_TEMP_RECORD_SIZE]; + unsigned int i; + + for (i = 0; i < PMP_TEMP_CHANNELS; i++) { + memcpy_fromio(record, sensors->sram + map->offset[i], sizeof(record)); + if (!apple_pmp_temp_record_plausible(record, apple_pmp_temp_records[i].name)) + return false; + } + return true; +} + +/* The firmware fills its records some time after it starts: look until they are there. */ +static void apple_pmp_temps_locate(struct work_struct *work) +{ + struct apple_pmp_telemetry *sensors = + container_of(to_delayed_work(work), struct apple_pmp_telemetry, locate); + struct apple_pmp_temp_map map; + size_t start = 0; + u32 data; + unsigned int i; + int ret; + + if (!apple_pmp_telemetry_online(sensors)) + return; + apple_pmp_temp_map_default(&map); + if (apple_pmp_temps_at(sensors, &map)) + return; + data = readl_relaxed(sensors->sram + PMP_TEMP_DATA_START_HDR); + if (!(data & 3) && data < sensors->size) + start = data; + ret = apple_pmp_temp_locate(sensors->sram, start, sensors->size, &map); + if (!apple_pmp_telemetry_online(sensors)) + return; + if (!ret) { + for (i = 0; i < PMP_TEMP_CHANNELS; i++) + WRITE_ONCE(sensors->temps.offset[i], map.offset[i]); + dev_info(sensors->dev, + "temperature records at %#x %#x %#x %#x %#x %#x (data from %#zx)\n", + map.offset[0], map.offset[1], map.offset[2], map.offset[3], + map.offset[4], map.offset[5], start); + return; + } + if (++sensors->locate_tries < PMP_TEMP_LOCATE_TRIES) { + queue_delayed_work(system_freezable_wq, &sensors->locate, + msecs_to_jiffies(PMP_TEMP_LOCATE_MS)); + return; + } + dev_warn(sensors->dev, "temperature records not found (%d, data from %#zx)\n", + ret, start); +} + int apple_pmp_telemetry_get_hotspot(const struct device_node *np, long *value) { struct apple_pmp_telemetry *sensors; @@ -58,7 +127,7 @@ int apple_pmp_telemetry_get_hotspot(const struct device_node *np, long *value) ret = -ENODEV; break; } - ret = apple_pmp_temp_hotspot(sensors->sram, value); + ret = apple_pmp_temp_hotspot_map(sensors->sram, &sensors->temps, value); /* A crash concurrent with the snapshot invalidates the result. */ if (!apple_pmp_telemetry_online(sensors)) ret = -ENODEV; @@ -189,7 +258,7 @@ static int apple_pmp_sensor_read(void *cookie, unsigned int channel, return -EINVAL; if (!apple_pmp_telemetry_online(sensors)) return -ENODEV; - ret = apple_pmp_temp_sample(sensors->sram, channel, value); + ret = apple_pmp_temp_sample_map(sensors->sram, &sensors->temps, channel, value); return apple_pmp_telemetry_online(sensors) ? ret : -ENODEV; } @@ -265,6 +334,7 @@ static void apple_pmp_telemetry_release(void *data) { struct apple_pmp_telemetry *sensors = data; + cancel_delayed_work_sync(&sensors->locate); mutex_lock(&apple_pmp_telemetry_lock); if (!list_empty(&sensors->list)) list_del_rcu(&sensors->list); @@ -290,6 +360,9 @@ int apple_pmp_telemetry_register(struct device *dev, void __iomem *sram, if (!sensors) return -ENOMEM; sensors->dev = dev; + sensors->size = size; + apple_pmp_temp_map_default(&sensors->temps); + INIT_DELAYED_WORK(&sensors->locate, apple_pmp_temps_locate); INIT_LIST_HEAD(&sensors->list); ret = devm_add_action_or_reset(dev, apple_pmp_telemetry_release, sensors); @@ -303,6 +376,7 @@ int apple_pmp_telemetry_register(struct device *dev, void __iomem *sram, mutex_lock(&apple_pmp_telemetry_lock); list_add_tail_rcu(&sensors->list, &apple_pmp_telemetry_list); mutex_unlock(&apple_pmp_telemetry_lock); + queue_delayed_work(system_freezable_wq, &sensors->locate, 0); if (IS_REACHABLE(CONFIG_HWMON)) { hwmon = devm_hwmon_device_register_with_info( dev, "apple_pmp", sensors, &apple_pmp_hwmon_chip, NULL); diff --git a/drivers/soc/apple/pmp.rs b/drivers/soc/apple/pmp.rs index afc8a973f77130..00795a75a035ef 100644 --- a/drivers/soc/apple/pmp.rs +++ b/drivers/soc/apple/pmp.rs @@ -11,8 +11,10 @@ use core::mem; use core::sync::atomic::{fence, AtomicI32, AtomicPtr, Ordering}; +mod pmp_alloc; mod pmp_bootargs; mod pmp_power; +use pmp_alloc::AllocBudget; use pmp_power::Command; use kernel::{ @@ -72,6 +74,12 @@ const BOOTARGS_UUID_VERSION: u32 = 5; const BOOTARGS_OFFSET: usize = 0x22c; const BOOTARGS_SIZE: usize = 0x230; const ASC_CPU_CONTROL_OFFSET: usize = 0x44; +/// The RTKit header word holding the SRAM offset of the firmware's data segment. +const SRAM_DATA_START: usize = 0x234; +/// How long the PMP's start waits for the firmware to acknowledge IOP power on by itself before +/// asking for it. On the M4 Mac mini (J773g) the 27.2 image's whole RTKit start, from its CPU +/// starting to its acknowledgment and the AP going on, takes 1.3 ms; this is 15 times that. +const PMP_SELF_ACK_MS: u32 = 20; const PMP_ENDPOINT: u8 = 0x20; const PM_COMMAND_MARKER: u64 = pmp_power::MARKER; const PM_COMMAND_SHIFT: u32 = pmp_power::SHIFT; @@ -85,7 +93,7 @@ const OPC_UPDATE_IOREG: u64 = 0x36; const OPC_CONFIRM_IOREG: u64 = 0x37; const OPC_ACK_MASK: u64 = 0x1; const OPC_SHIFT: u32 = 48; -const MALLOC_SIZE_MASK: u64 = 0xFFFFFF; +const MALLOC_SIZE_MASK: u64 = pmp_alloc::MALLOC_SIZE_MAX; const MSG_IOVA_MASK: u64 = 0xFFFFFFFFFFFF; const SET_IOREG_INDEX_MASK: u64 = 0xFFFF; const PIO_VM_BASE: u64 = 0xc0000000; @@ -130,8 +138,13 @@ struct SramCopy { struct PmpState { iova_table: Option>, allocs: KVec, + /// The number and total size of `allocs`. + alloc_budget: AllocBudget, value_buf: Option, ioreg_entries: KVec, + /// The firmware's own index of each entry in `ioreg_entries` (word 0x48 of its + /// REGISTER_IOREG buffer), by which UPDATE_IOREG names the entry. + ioreg_ids: KVec, /// Held from a system sleep's start until its end. sram: Option, } @@ -141,8 +154,10 @@ impl PmpState { Ok(PmpState { iova_table: None, allocs: KVec::with_capacity(10, GFP_KERNEL)?, + alloc_budget: AllocBudget::new(), value_buf: None, ioreg_entries: KVec::with_capacity(340, GFP_KERNEL)?, + ioreg_ids: KVec::with_capacity(340, GFP_KERNEL)?, sram: None, }) } @@ -181,6 +196,12 @@ struct PmpData { display_error: AtomicI32, /// See [`PmpHwConfig::sram_backup`]. sram_backup: Option<(usize, usize)>, + /// See [`PmpHwConfig::sram_backup_data`]. + sram_backup_data: bool, + /// See [`PmpHwConfig::self_ack_start`]. + self_ack_start: bool, + /// See [`PmpHwConfig::confirm_ioreg_len`]. + confirm_ioreg_len: bool, } impl PmpData { @@ -189,22 +210,18 @@ impl PmpData { let pmp_mmio = pmp_req.iomap_sized::()?.into_devres()?; let asc_req = dev.io_request_by_name(c"asc").ok_or(EINVAL)?; let asc_mmio = asc_req.iomap_sized::()?.into_devres()?; - // The SRAM range kept over a sleep, if the SoC's config has none: from the DT, where - // the boot loader puts it. - let sram_backup = match cfg.sram_backup { - Some(range) => Some(range), - None => { - let node = dev.as_ref().fwnode().ok_or(EIO)?; - let prop_name = c"apple,sram-keep"; - if node.property_present(prop_name) { - let v = node - .property_read_array_vec::(prop_name, 2)? - .required_by(dev.as_ref())?; - Some((v[0] as usize, v[1] as usize)) - } else { - None - } - } + // The SRAM range kept over a sleep: prefer the DT property (`apple,sram-keep`, where + // the boot loader supplies the exact offset and size from ADT segment-ranges) when + // present, otherwise fall back to the SoC's config. + let node = dev.as_ref().fwnode().ok_or(EIO)?; + let prop_name = c"apple,sram-keep"; + let (sram_backup, sram_backup_data) = if node.property_present(prop_name) { + let v = node + .property_read_array_vec::(prop_name, 2)? + .required_by(dev.as_ref())?; + (Some((v[0] as usize, v[1] as usize)), false) + } else { + (cfg.sram_backup, cfg.sram_backup_data) }; Arc::pin_init( try_pin_init!( @@ -219,6 +236,9 @@ impl PmpData { display: AtomicPtr::new(core::ptr::null_mut()), display_error: AtomicI32::new(0), sram_backup, + sram_backup_data, + self_ack_start: cfg.self_ack_start, + confirm_ioreg_len: cfg.confirm_ioreg_len, } ), GFP_KERNEL, @@ -227,7 +247,14 @@ impl PmpData { fn start(&self) -> Result<()> { let mut guard = self.rtkit.lock(); let mut rtk = guard.as_mut().as_pin_mut().unwrap(); - rtk.as_mut().wake()?; + // Some T8132 PMP images acknowledge IOP power on by themselves once they have reported in, + // and answer no request for it after that (macOS 27.2; macOS sends it none). Others wait + // to be asked. Only SoCs with `self_ack_start` wait for a self-acknowledgment first. + if self.self_ack_start { + rtk.as_mut().boot_or_wake(PMP_SELF_ACK_MS)?; + } else { + rtk.as_mut().wake()?; + } rtk.start_endpoint(PMP_ENDPOINT) } fn patch_bootargs( @@ -319,23 +346,42 @@ impl PmpData { fn malloc(&self, size: u64) -> Result { // SAFETY: TODO: ensure self.dev is bound let bound_dev = unsafe { self.dev.as_bound() }; - let iomem = Coherent::::zeroed_slice(bound_dev, size as usize, GFP_KERNEL)?; let mut state = self.state.lock(); + if !state.alloc_budget.claim(size) { + dev_err!( + self.dev, + "Refusing a {} byte allocation: {} held\n", + size, + state.allocs.len() + ); + return Err(ENOMEM); + } + let iomem = match Coherent::::zeroed_slice(bound_dev, size as usize, GFP_KERNEL) { + Ok(iomem) => iomem, + Err(e) => { + state.alloc_budget.release(size); + return Err(e); + } + }; let addr = iomem.dma_address(); let msg = (OPC_MALLOC | OPC_ACK_MASK) << OPC_SHIFT | addr; - state.allocs.push( + if let Err(e) = state.allocs.push( PmpAllocation { addr: addr, alloc: iomem, }, GFP_KERNEL, - )?; + ) { + state.alloc_budget.release(size); + return Err(e.into()); + } Ok(msg) } fn free(&self, addr: u64) -> Result { let mut state = self.state.lock(); if let Some(idx) = state.find_alloc(addr) { - state.allocs.swap_remove(idx); + let freed = state.allocs.swap_remove(idx); + state.alloc_budget.release(freed.alloc.size() as u64); } else { dev_err!( self.dev, @@ -370,6 +416,14 @@ impl PmpData { } fn register_ioreg(&self, addr: u64) -> Result { let mut state = self.state.lock(); + if !pmp_alloc::ioreg_fits(state.ioreg_entries.len()) { + dev_err!( + self.dev, + "Refusing register {}: no index left\n", + state.ioreg_entries.len() + 1 + ); + return Err(ENOSPC); + } let msg_buf = if let Some(s) = state.get_buf(addr) { s } else { @@ -384,6 +438,14 @@ impl PmpData { let mut size = u32::from_le_bytes(unsafe { <&[u8] as TryInto<[u8; 4]>>::try_into(&msg_buf.as_ref()[0x40..0x44]).unwrap() }); + let id = if msg_buf.size() >= 0x4c { + // SAFETY: TODO + u32::from_le_bytes(unsafe { + <&[u8] as TryInto<[u8; 4]>>::try_into(&msg_buf.as_ref()[0x48..0x4c]).unwrap() + }) + } else { + u32::MAX + }; if size == 0 { let mut name_vec = KVec::with_capacity(0x31, GFP_KERNEL)?; name_vec @@ -431,6 +493,7 @@ impl PmpData { } } state.ioreg_entries.push(size, GFP_KERNEL)?; + state.ioreg_ids.push(id, GFP_KERNEL)?; let index = state.ioreg_entries.len() as u64; let msg = (OPC_REGISTER_IOREG | OPC_ACK_MASK) << OPC_SHIFT | (index << 32) | size as u64; Ok(msg) @@ -484,14 +547,40 @@ impl PmpData { .wrapping_add(ASC_CPU_CONTROL_OFFSET) .cast()) } - /// Room for what SRAM needs kept, taken first so that running out refuses a sleep cleanly. - fn sram_alloc(&self, sram_size: usize) -> Result> { - let Some((offset, size)) = self.sram_backup else { + /// The SRAM range a system sleep keeps: with [`PmpHwConfig::sram_backup_data`], the + /// firmware's data segment, at the offset its header gives ([`SRAM_DATA_START`]) and on one + /// of its 4 KiB pages. An image whose header names no such segment is refused. + fn sram_range( + &self, + io: &Mmio<'_, Region>, + ) -> Result> { + let Some((mut offset, size)) = self.sram_backup else { return Ok(None); }; - if !pmp_bootargs::word_range_valid(offset, size, sram_size) { + if self.sram_backup_data { + let data = io.as_view().relaxed().read32(SRAM_DATA_START) as usize; + if data == 0 || data % 0x1000 != 0 { + dev_err!(self.dev, "firmware data segment at {:#x}\n", data); + return Err(EINVAL); + } + offset = data; + } + if !pmp_bootargs::word_range_valid(offset, size, io.size()) { + dev_err!( + self.dev, + "SRAM range {:#x}+{:#x} outside the SRAM\n", + offset, + size + ); return Err(EINVAL); } + Ok(Some((offset, size))) + } + /// Room for what SRAM needs kept, taken first so that running out refuses a sleep cleanly. + fn sram_alloc(&self, io: &Mmio<'_, Region>) -> Result> { + let Some((offset, size)) = self.sram_range(io)? else { + return Ok(None); + }; let mut words = KVVec::new(); words.resize(size / 4, 0u32, GFP_KERNEL)?; Ok(Some(SramCopy { offset, words })) @@ -502,7 +591,7 @@ impl PmpData { let bound_dev = unsafe { self.dev.as_bound() }; let pmp_mmio = self.pmp_mmio.access(bound_dev)?.as_view(); let io = pmp_mmio.as_view().relaxed(); - let mut copy = self.sram_alloc(io.size())?; + let mut copy = self.sram_alloc(&pmp_mmio)?; let rtk = self.rtkit_handle()?; let control = self.asc_cpu_control()?; // SAFETY: the handle stays valid until unbind, which can't run during a system sleep, @@ -529,8 +618,7 @@ impl PmpData { // SAFETY: the PM core only calls a bound device. let bound_dev = unsafe { self.dev.as_bound() }; let pmp_mmio = self.pmp_mmio.access(bound_dev)?.as_view(); - let size = pmp_mmio.as_view().relaxed().size(); - let mut copy = self.sram_alloc(size)?; + let mut copy = self.sram_alloc(&pmp_mmio)?; stop.rtk = self.rtkit_handle()?; stop.control = self.asc_cpu_control()?; stop.sram = core::ptr::null_mut(); @@ -574,6 +662,30 @@ impl PmpData { // and `control` is inside the ASC mapping held by `self`. to_result(unsafe { bindings::apple_rtkit_sleep_return(rtk, control) }) } + /// CONFIRM_IOREG's value for an UPDATE_IOREG: the length of the entry the firmware names by + /// its own index, as registered. macOS 27.2 answers so on the M4 Mac mini (J773g), 8 for each + /// of the four entries that image updates. An index that names no registered entry, which + /// macOS doesn't see, gets 0, the answer this driver gave before. + fn confirm_ioreg_value(&self, id: u64) -> u64 { + let state = self.state.lock(); + let found = state + .ioreg_ids + .iter() + .position(|&e| u64::from(e) == id) + .and_then(|i| state.ioreg_entries.get(i).copied()); + drop(state); + match found { + Some(len) => u64::from(len), + None => { + dev_warn!( + self.dev, + "UPDATE_IOREG {:#x} names no registered entry\n", + id + ); + 0 + } + } + } fn recv_message(&self, msg: u64) -> Result<()> { let pm_command = (msg >> PM_COMMAND_SHIFT) & 0xff; if msg & PM_COMMAND_MARKER != 0 && (pm_command == 0x0f || pm_command == 0x10) { @@ -601,8 +713,15 @@ impl PmpData { OPC_REGISTER_IOREG => self.register_ioreg(msg & MSG_IOVA_MASK)?, OPC_SET_IOREG => self.set_ioreg(msg & SET_IOREG_INDEX_MASK)?, // Firmware waits for this confirmation before publishing reports. - // Do not echo the registry index/payload or add a generic ACK bit. - OPC_UPDATE_IOREG => OPC_CONFIRM_IOREG << OPC_SHIFT, + // Do not echo the registry index or add a generic ACK bit. + OPC_UPDATE_IOREG => { + let value = if self.confirm_ioreg_len { + self.confirm_ioreg_value(msg & SET_IOREG_INDEX_MASK) + } else { + 0 + }; + OPC_CONFIRM_IOREG << OPC_SHIFT | value + } _ => { dev_err!(self.dev, "Got unknown message {}", msg); return Err(EIO); @@ -850,6 +969,14 @@ struct PmpHwConfig { /// The range of the firmware's SRAM, as (offset, size) in bytes, that a system sleep keeps /// and writes back. `None` where no sleep has been traced. sram_backup: Option<(usize, usize)>, + /// The range kept is the firmware's data segment: its offset comes from the firmware's + /// header ([`SRAM_DATA_START`]), and `sram_backup` gives its size. + sram_backup_data: bool, + /// Wait briefly for the firmware to acknowledge IOP power on by itself before sending + /// SET_IOP_PWR_STATE. + self_ack_start: bool, + /// Answer UPDATE_IOREG with the registered entry's length instead of 0. + confirm_ioreg_len: bool, } /// Whether a PMP firmware needs endpoint 7 to finish its RTKit boot. @@ -857,7 +984,7 @@ struct PmpHwConfig { enum Ep7 { /// Never started. No, - /// Only on the retained J713 board. + /// Only on T8132 boards with a retained, qualified PMP session. RetainedBoard, /// On every board with this SoC. Always, @@ -868,6 +995,9 @@ const HW_CFG_DEFAULT: PmpHwConfig = PmpHwConfig { check_bootargs_uuid: false, coreanalytics: Ep7::No, sram_backup: None, + sram_backup_data: false, + self_ack_start: false, + confirm_ioreg_len: false, }; /// T8140: the DART translates 42 bits and its DMA window starts at 1 TiB. @@ -876,6 +1006,9 @@ const HW_CFG_T8140: PmpHwConfig = PmpHwConfig { check_bootargs_uuid: false, coreanalytics: Ep7::No, sram_backup: Some((0x3c000, 0x5c000)), + sram_backup_data: false, + self_ack_start: false, + confirm_ioreg_len: false, }; /// T6041: the DART window starts at 1 TiB; the boot argument header is @@ -885,7 +1018,12 @@ const HW_CFG_T6041: PmpHwConfig = PmpHwConfig { dma_mask: Some(DmaMask::new::<42>()), check_bootargs_uuid: true, coreanalytics: Ep7::Always, - sram_backup: None, + // 26.6.2 firmware (J616C): __DATA at 0x500761000, 0x7d000 bytes; the 27.2 firmware has it at + // 0x62000. Kept across a real sleep. + sram_backup: Some((0x61000, 0x7d000)), + sram_backup_data: false, + self_ack_start: false, + confirm_ioreg_len: false, }; /// T8142: the DART window starts at 1 TiB as on T8140. Its registry-v2 @@ -896,6 +1034,9 @@ const HW_CFG_T8142: PmpHwConfig = PmpHwConfig { check_bootargs_uuid: false, coreanalytics: Ep7::Always, sram_backup: None, + sram_backup_data: false, + self_ack_start: false, + confirm_ioreg_len: false, }; /// T6050: the DART window starts at 1 TiB (ADT dart-pmp0 vm-base) and spans @@ -906,15 +1047,31 @@ const HW_CFG_T6050: PmpHwConfig = PmpHwConfig { check_bootargs_uuid: false, coreanalytics: Ep7::No, sram_backup: None, + sram_backup_data: false, + self_ack_start: false, + confirm_ioreg_len: false, +}; + +/// T8122: the sleep engine reloads `__TEXT` from DRAM at the wake, and only `__DATA` +/// (the ADT's second segment, offset 0x36000, size 0x47000) has to be kept. When the +/// boot loader supplies `apple,sram-keep`, both offset and size come from the DT instead. +const HW_CFG_T8122: PmpHwConfig = PmpHwConfig { + sram_backup: Some((0x36000, 0x47000)), + ..HW_CFG_DEFAULT }; -/// T8132: the sleep engine reloads `__TEXT` from DRAM at the wake, and only `__DATA` -/// (the ADT's second segment) has to be kept. +/// T8132: over a sleep only the ADT's second segment (0x68000 bytes, starting at 0x3c000 on +/// 26.6.2/25G83 and 0x3d000 on 27.2/26B123 per ADT `segment-ranges` and SRAM header word 0x234) +/// needs to be kept. When the boot loader supplies `apple,sram-keep`, both offset and size come +/// from the DT instead of this fallback. const HW_CFG_T8132: PmpHwConfig = PmpHwConfig { dma_mask: None, check_bootargs_uuid: false, coreanalytics: Ep7::RetainedBoard, sram_backup: Some((0x3c000, 0x68000)), + sram_backup_data: true, + self_ack_start: true, + confirm_ioreg_len: true, }; impl Drop for PmpDriver { @@ -928,6 +1085,7 @@ kernel::of_device_table!( OF_TABLE, ::IdInfo, [ + (of::DeviceId::new(c"apple,t8122-pmp-v2"), &HW_CFG_T8122), (of::DeviceId::new(c"apple,t8132-pmp-v2"), &HW_CFG_T8132), (of::DeviceId::new(c"apple,t8140-pmp-v2"), &HW_CFG_T8140), (of::DeviceId::new(c"apple,t8142-pmp-v2"), &HW_CFG_T8142), @@ -969,6 +1127,8 @@ impl platform::Driver for PmpDriver { let data = PmpData::new(pdev, cfg)?; let pmp_mmio = data.pmp_mmio.access(pdev.as_ref())?.as_view(); let asc_mmio = data.asc_mmio.access(pdev.as_ref())?.as_view(); + // The firmware's own header describes what a sleep keeps; refuse an image it doesn't. + data.sram_range(&pmp_mmio)?; let node = dev.fwnode().ok_or(EIO)?; let dvid = node .property_read(c"apple,dram-vendor-id") @@ -989,7 +1149,7 @@ impl platform::Driver for PmpDriver { } data.patch_bootargs(&pmp_mmio, &patches, cfg.check_bootargs_uuid)?; // EP7 is a startup dependency on every T6041 PMP, and on the - // retained J713 PMP among the T8132 boards. + // retained, qualified PMP session among the T8132 boards. let needs_coreanalytics = match cfg.coreanalytics { Ep7::No => false, Ep7::Always => true, diff --git a/drivers/soc/apple/pmp_alloc.rs b/drivers/soc/apple/pmp_alloc.rs new file mode 100644 index 00000000000000..f20addb55baa93 --- /dev/null +++ b/drivers/soc/apple/pmp_alloc.rs @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Bounds on the memory the PMP firmware asks the kernel to hold for it. + +/// The largest buffer one allocation request can ask for: its 24-bit size field, +/// which is also the mask the driver takes the size out of a request with. +pub(crate) const MALLOC_SIZE_MAX: u64 = 0xff_ffff; + +/// Live allocations held for the firmware at once. A normal boot makes about ten. +pub(crate) const MAX_ALLOCS: usize = 64; + +/// The total size of those allocations: four of the largest the firmware can ask for. +pub(crate) const MAX_ALLOC_BYTES: u64 = 4 * MALLOC_SIZE_MAX; + +/// The highest register index a reply can carry: 16 bits, below the opcode. +pub(crate) const IOREG_INDEX_MAX: usize = 0xffff; + +/// The firmware's live allocations: how many, and their total size. +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub(crate) struct AllocBudget { + count: usize, + bytes: u64, +} + +impl AllocBudget { + pub(crate) const fn new() -> Self { + Self { count: 0, bytes: 0 } + } + + /// Takes room for one more allocation of `size` bytes, or refuses it. + pub(crate) fn claim(&mut self, size: u64) -> bool { + if size > MALLOC_SIZE_MAX || self.count >= MAX_ALLOCS || size > MAX_ALLOC_BYTES - self.bytes + { + return false; + } + self.count += 1; + self.bytes += size; + true + } + + /// Gives back the room of an allocation that was freed or never made. + pub(crate) fn release(&mut self, size: u64) { + self.count = self.count.saturating_sub(1); + self.bytes = self.bytes.saturating_sub(size); + } +} + +/// Whether one more register, after `registered`, gets an index a reply can carry. +pub(crate) fn ioreg_fits(registered: usize) -> bool { + registered < IOREG_INDEX_MAX +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_normal_boot_fits() { + let mut budget = AllocBudget::new(); + for _ in 0..10 { + assert!(budget.claim(0x4000)); + } + assert!(budget.claim(MALLOC_SIZE_MAX)); + } + + #[test] + fn the_number_of_live_allocations_is_bounded() { + let mut budget = AllocBudget::new(); + let mut granted = 0; + for _ in 0..100_000 { + if budget.claim(0x40) { + granted += 1; + } + } + assert_eq!(granted, MAX_ALLOCS); + } + + #[test] + fn their_total_size_is_bounded() { + let mut budget = AllocBudget::new(); + let mut bytes = 0; + for _ in 0..MAX_ALLOCS { + if budget.claim(MALLOC_SIZE_MAX) { + bytes += MALLOC_SIZE_MAX; + } + } + assert_eq!(bytes, MAX_ALLOC_BYTES); + assert!(!budget.claim(1)); + assert!(!budget.claim(MALLOC_SIZE_MAX + 1)); + } + + #[test] + fn a_freed_allocation_makes_room_again() { + let mut budget = AllocBudget::new(); + for _ in 0..=MAX_ALLOCS { + budget.claim(MALLOC_SIZE_MAX); + } + assert!(!budget.claim(0x1000)); + budget.release(MALLOC_SIZE_MAX); + assert!(budget.claim(0x1000)); + assert!(!budget.claim(MALLOC_SIZE_MAX)); + } + + #[test] + fn a_register_index_fits_its_reply() { + assert!(ioreg_fits(0)); + assert!(ioreg_fits(340)); + assert!(ioreg_fits(IOREG_INDEX_MAX - 1)); + assert!(!ioreg_fits(IOREG_INDEX_MAX)); + assert!(!ioreg_fits(usize::MAX)); + // The index of the last one admitted stays below the opcode. + assert_eq!(((IOREG_INDEX_MAX as u64) << 32) >> 48, 0); + } +} diff --git a/drivers/soc/apple/profile.rs b/drivers/soc/apple/profile.rs index 29e74e2df0c57d..c3f3630e0b4d35 100644 --- a/drivers/soc/apple/profile.rs +++ b/drivers/soc/apple/profile.rs @@ -648,8 +648,12 @@ fn t6020_profile() -> &'static PlatformProfile { /// Select the profile for the running machine. An unsupported SoC is refused /// rather than guessed at, so the driver cannot run a handshake with the wrong -/// geometry. +/// geometry. A device tree that does not describe the SEP (no `apple,sep` +/// node) gets no profile either: there is nothing to enable or bind. pub(crate) fn detect() -> Result<&'static PlatformProfile> { + if crate::dt::sep_node().is_none() { + return Err(ENODEV); + } select(&machine_has, &t6020_profile) } @@ -692,30 +696,34 @@ fn select( if has(b"apple,t8112") { return Ok(&T8112); } - // Only the boards whose ADTs were read: the other T8122 Macs (J433, J434, - // J504) share the SoC but their sensor wiring is unchecked. - if has(b"apple,t8122") && (has(b"apple,j613") || has(b"apple,j615")) { + // Every profile below is SoC facts: the SEP, its DART window and + // handshake, and the SPI controller the SoC wires to the Touch ID + // sensor. They hold on every board with the SoC, as they do for the + // SoCs above. Whether a board has a built-in sensor is not decided here: + // a sensor node the board's device tree describes is used as it is, and + // a board without a sensor (a Mac mini, Studio or iMac) has nothing on + // that bus, so the sensor probe finds no part and the SEP runs without + // biometrics, as on the M1 and M2 Mac minis. Whether a board has an + // enclave to attach to is the board device tree's call: + // `dt::enable_sep_and_dart` leaves the SEP disabled where the board keeps + // the SEP mailbox disabled. + if has(b"apple,t8122") { return Ok(&T8122); } - // The T6040 profile is tested on J614s and J616s. - if has(b"apple,t6040") && (has(b"apple,j616s") || has(b"apple,j614s")) { + if has(b"apple,t6040") { return Ok(&T6040); } - if has(b"apple,t6041") && (has(b"apple,j616c") || has(b"apple,j614c")) { + if has(b"apple,t6041") { return Ok(&T6041); } - if has(b"apple,t6050") - && (has(b"apple,j714s") || has(b"apple,k116s") || has(b"apple,j716c")) - { + if has(b"apple,t6050") { return Ok(&T6050); } - // Only the M4 MacBook Airs: the other T8132 Macs are unread. - if has(b"apple,t8132") && (has(b"apple,j713") || has(b"apple,j715")) { + if has(b"apple,t8132") { return Ok(&T8132); } - // The J815 and the J813, whose ADTs were read: both have the sensor (mesa) on spi2 - // at 0x3a5108000. - if has(b"apple,t8142") && (has(b"apple,j815") || has(b"apple,j813")) { + // The J815 and J813 ADTs have the sensor (mesa) on spi2 at 0x3a5108000. + if has(b"apple,t8142") { return Ok(&T8142); } Err(ENODEV) @@ -732,9 +740,9 @@ mod tests { let cases: [(&[u8], &[u8], bool); 8] = [ (b"apple,t8142", b"apple,j813", true), (b"apple,t8142", b"apple,j815", true), - (b"apple,t8142", b"apple,j814", false), - (b"apple,t8142", b"apple,j704", false), - (b"apple,t8142", b"", false), + (b"apple,t8142", b"apple,j814", true), + (b"apple,t8142", b"apple,j704", true), + (b"apple,t8142", b"", true), (b"", b"apple,j813", false), (b"apple,t8132", b"apple,j813", false), (b"apple,t6050", b"apple,j815", false), @@ -742,11 +750,10 @@ mod tests { for (soc, board, admitted) in cases { let has = |c: &[u8]| c == soc || c == board; let selected = select(&has, &|| &T6020); - if admitted { - assert!(matches!(selected, Ok(profile) if profile.name == T8142.name)); - } else { - assert!(selected.is_err()); - } + assert_eq!( + matches!(selected, Ok(profile) if profile.name == T8142.name), + admitted + ); } } @@ -805,28 +812,49 @@ mod tests { select(&has, &|| &T6020).ok().map(|p| p.name) } + /// The profile follows the SoC compatible alone; the board compatible + /// next to it changes nothing. #[test] - fn t8132_selection_is_limited_to_the_m4_airs() { + fn selection_follows_the_soc() { assert_eq!(picked(&[b"apple,j713", b"apple,t8132"]), Some(T8132.name)); assert_eq!(picked(&[b"apple,j715", b"apple,t8132"]), Some(T8132.name)); - assert_eq!(picked(&[b"apple,j604", b"apple,t8132"]), None); - assert_eq!(picked(&[b"apple,t8132"]), None); - assert_eq!(picked(&[b"apple,j613", b"apple,t8132"]), None); - assert_eq!(picked(&[b"apple,j713", b"apple,t8122"]), None); + assert_eq!(picked(&[b"apple,j604", b"apple,t8132"]), Some(T8132.name)); + assert_eq!(picked(&[b"apple,j773g", b"apple,t8132"]), Some(T8132.name)); + assert_eq!(picked(&[b"apple,j613", b"apple,t8132"]), Some(T8132.name)); + assert_eq!(picked(&[b"apple,t8132"]), Some(T8132.name)); + assert_eq!(picked(&[b"apple,j713", b"apple,t8122"]), Some(T8122.name)); assert_eq!(picked(&[b"apple,j613", b"apple,t8122"]), Some(T8122.name)); + assert_eq!(picked(&[b"apple,j504", b"apple,t8122"]), Some(T8122.name)); assert_eq!(picked(&[b"apple,j700", b"apple,t8140"]), Some(T8140.name)); assert_eq!(picked(&[b"apple,j616s", b"apple,t6040"]), Some(T6040.name)); - assert_eq!(picked(&[b"apple,t6040"]), None); assert_eq!(picked(&[b"apple,j614s", b"apple,t6040"]), Some(T6040.name)); + assert_eq!(picked(&[b"apple,j773s", b"apple,t6040"]), Some(T6040.name)); + assert_eq!(picked(&[b"apple,t6040"]), Some(T6040.name)); assert_eq!(picked(&[b"apple,j616c", b"apple,t6041"]), Some(T6041.name)); assert_eq!(picked(&[b"apple,j614c", b"apple,t6041"]), Some(T6041.name)); - assert_eq!(picked(&[b"apple,t6041"]), None); - assert_eq!(picked(&[b"apple,j713", b"apple,t6041"]), None); + assert_eq!(picked(&[b"apple,j713", b"apple,t6041"]), Some(T6041.name)); assert_eq!(picked(&[b"apple,j714s", b"apple,t6050"]), Some(T6050.name)); assert_eq!(picked(&[b"apple,k116s", b"apple,t6050"]), Some(T6050.name)); assert_eq!(picked(&[b"apple,j716c", b"apple,t6050"]), Some(T6050.name)); - assert_eq!(picked(&[b"apple,j716c", b"apple,t6041"]), None); - assert_eq!(picked(&[b"apple,t6050"]), None); + assert_eq!(picked(&[b"apple,j716s", b"apple,t6050"]), Some(T6050.name)); + assert_eq!(picked(&[b"apple,k114s", b"apple,t6050"]), Some(T6050.name)); + assert_eq!(picked(&[b"apple,j716c", b"apple,t6041"]), Some(T6041.name)); + assert_eq!(picked(&[b"apple,j813", b"apple,t8142"]), Some(T8142.name)); + assert_eq!(picked(&[b"apple,j815", b"apple,t8142"]), Some(T8142.name)); + assert_eq!(picked(&[b"apple,j704", b"apple,t8142"]), Some(T8142.name)); + assert_eq!(picked(&[b"apple,j316s", b"apple,t6000"]), Some(T6000.name)); + assert_eq!(picked(&[b"apple,j413", b"apple,t8112"]), Some(T8112.name)); + assert_eq!(picked(&[b"apple,j713"]), None); + assert_eq!(picked(&[b"apple,t6002"]), None); + } + + /// SoCs without a profile are still refused, whatever the board. + #[test] + fn unprofiled_socs_are_refused() { + assert_eq!(picked(&[b"apple,j375d", b"apple,t6002"]), None); + assert_eq!(picked(&[b"apple,j514c", b"apple,t6031"]), None); + assert_eq!(picked(&[b"apple,j804", b"apple,t8152"]), None); + assert_eq!(picked(&[]), None); } /// Touch ID has one path for every Mac. The retry limits, the lock @@ -837,7 +865,7 @@ mod tests { /// profile naming one of the known Mesa revisions. #[test] fn every_touch_id_mac_gets_a_sensor_the_shared_path_decodes() { - let macs: [&[&[u8]]; 18] = [ + let macs: [&[&[u8]]; 25] = [ &[b"apple,j313", b"apple,t8103"], &[b"apple,j316s", b"apple,t6000"], &[b"apple,j316c", b"apple,t6001"], @@ -850,10 +878,17 @@ mod tests { &[b"apple,j614s", b"apple,t6040"], &[b"apple,j616s", b"apple,t6040"], &[b"apple,j616c", b"apple,t6041"], + &[b"apple,j504", b"apple,t8122"], + &[b"apple,j614c", b"apple,t6041"], &[b"apple,j713", b"apple,t8132"], + &[b"apple,j715", b"apple,t8132"], + &[b"apple,j604", b"apple,t8132"], &[b"apple,j700", b"apple,t8140"], &[b"apple,j714s", b"apple,t6050"], + &[b"apple,j716s", b"apple,t6050"], &[b"apple,j716c", b"apple,t6050"], + &[b"apple,k116s", b"apple,t6050"], + &[b"apple,j704", b"apple,t8142"], &[b"apple,j813", b"apple,t8142"], &[b"apple,j815", b"apple,t8142"], ]; diff --git a/drivers/soc/apple/regview-internal.h b/drivers/soc/apple/regview-internal.h new file mode 100644 index 00000000000000..93fa5c1745ab7d --- /dev/null +++ b/drivers/soc/apple/regview-internal.h @@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _REGVIEW_INTERNAL_H +#define _REGVIEW_INTERNAL_H + +#include +#include + +/* One run of 32-bit registers inside one DT reg entry. */ +struct apple_regview_range { + u8 reg; /* index into the node's reg property */ + u32 offset; /* byte offset from the start of that entry */ + u32 count; /* number of 32-bit registers */ + u32 stride; /* byte distance between registers; 0 means 4 */ + const char *name; +}; + +struct apple_regview_hw { + const struct apple_regview_range *ranges; + unsigned int nr_ranges; + unsigned int nr_regs; /* reg entries the node must have */ +}; + +struct apple_regview_map { + void __iomem *base; + resource_size_t size; +}; + +struct apple_regview { + struct device *dev; + const struct apple_regview_hw *hw; + struct apple_regview_map *maps; + struct dentry *dir; +}; + +#define MCC_TZ_BASE 0x6a0 +#define MCC_TZ_STRIDE 0x10 +#define MCC_TZ_REGIONS 4 + +#define MCC_PLANE_STRIDE 0x40000 +#define MCC_PLANE_CACHE_STATUS 0x1c04 +#define SPMI_SB_BUS_FAULTS 0x200 +#define SPMI_SB_NR_BUS_FAULTS 10 +#define SPMI_MON_COUNTERS 1 + +#if IS_ENABLED(CONFIG_APPLE_REGVIEW_KUNIT_TEST) +u32 apple_regview_stride(const struct apple_regview_range *r); +int apple_regview_check(const struct apple_regview *rv); +int apple_regview_show(struct seq_file *s, void *unused); +extern const struct of_device_id apple_regview_of_match[]; +const struct file_operations *apple_regview_test_fops(void); +#endif + +#endif diff --git a/drivers/soc/apple/regview-test.c b/drivers/soc/apple/regview-test.c new file mode 100644 index 00000000000000..e0a61732e092ef --- /dev/null +++ b/drivers/soc/apple/regview-test.c @@ -0,0 +1,614 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SoC read-only register views. + * + * The register windows under test are zeroed buffers of kernel memory that + * stand in for the mapped DT reg entries of a struct apple_regview. The tests + * call the driver's own bounds check and seq_file show routine on the + * driver's own register lists. No device is probed and no MMIO is touched. + */ +#include +#include +#include + +#include "regview-internal.h" + +#define REGVIEW_TEST_MAX_REGS 4 +#define REGVIEW_TEST_SEQ_SIZE (16 * 1024) + +struct regview_test_ctx { + struct apple_regview rv; + struct apple_regview_map maps[REGVIEW_TEST_MAX_REGS]; + void *buf[REGVIEW_TEST_MAX_REGS]; + char *seq_buf; + size_t seq_len; +}; + +KUNIT_DEFINE_ACTION_WRAPPER(regview_test_vfree, vfree, const void *); + +static const struct apple_regview_hw *regview_test_hw(const char *compatible) +{ + const struct of_device_id *id; + + for (id = apple_regview_of_match; id->compatible[0]; id++) + if (!strcmp(id->compatible, compatible)) + return id->data; + return NULL; +} + +/* Bytes of reg entry @reg that the list of @hw reaches. */ +static u64 regview_test_extent(const struct apple_regview_hw *hw, + unsigned int reg) +{ + u64 end = 0; + unsigned int i; + + for (i = 0; i < hw->nr_ranges; i++) { + const struct apple_regview_range *r = &hw->ranges[i]; + u32 stride = r->stride ? r->stride : 4; + u64 last; + + if (r->reg != reg) + continue; + last = r->offset + (u64)(r->count - 1) * stride + 4; + end = max(end, last); + } + + return end; +} + +/* Back every reg entry of @hw with a buffer of the size it needs plus @extra. */ +static struct regview_test_ctx *regview_test_setup(struct kunit *test, + const struct apple_regview_hw *hw, + s64 extra) +{ + struct regview_test_ctx *ctx; + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, hw); + KUNIT_ASSERT_LE(test, hw->nr_regs, REGVIEW_TEST_MAX_REGS); + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + + for (i = 0; i < hw->nr_regs; i++) { + u64 size = regview_test_extent(hw, i); + + /* An entry no range uses still gets a word of its own. */ + size = max_t(u64, size, 4); + ctx->buf[i] = vzalloc(size + max_t(s64, extra, 0) + 4); + KUNIT_ASSERT_NOT_NULL(test, ctx->buf[i]); + KUNIT_ASSERT_EQ(test, 0, + kunit_add_action_or_reset(test, regview_test_vfree, + ctx->buf[i])); + ctx->maps[i].base = (void __iomem __force *)ctx->buf[i]; + ctx->maps[i].size = size + extra; + } + + ctx->rv.hw = hw; + ctx->rv.maps = ctx->maps; + + return ctx; +} + +/* A value that names the reg entry and offset it was read from. */ +static u32 regview_test_tag(unsigned int reg, u32 off) +{ + return 0xa0000000 | (reg << 24) | off; +} + +static void regview_test_fill(struct regview_test_ctx *ctx) +{ + const struct apple_regview_hw *hw = ctx->rv.hw; + unsigned int i; + + for (i = 0; i < hw->nr_regs; i++) { + __le32 *w = ctx->buf[i]; + u64 off; + + for (off = 0; off + 4 <= ctx->maps[i].size; off += 4) + w[off / 4] = cpu_to_le32(regview_test_tag(i, off)); + } +} + +static void regview_test_show(struct kunit *test, struct regview_test_ctx *ctx) +{ + struct seq_file s = { }; + + ctx->seq_buf = kunit_kzalloc(test, REGVIEW_TEST_SEQ_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->seq_buf); + + s.buf = ctx->seq_buf; + s.size = REGVIEW_TEST_SEQ_SIZE - 1; + s.private = &ctx->rv; + + KUNIT_ASSERT_EQ(test, apple_regview_show(&s, NULL), 0); + KUNIT_ASSERT_FALSE(test, seq_has_overflowed(&s)); + ctx->seq_len = s.count; + ctx->seq_buf[s.count] = '\0'; +} + +static bool regview_test_has(const struct regview_test_ctx *ctx, const char *want) +{ + return strstr(ctx->seq_buf, want); +} + +static bool regview_test_starts(const struct regview_test_ctx *ctx, const char *want) +{ + return str_has_prefix(ctx->seq_buf, want); +} + +static unsigned int regview_test_lines(const char *buf) +{ + unsigned int n = 0; + + for (; *buf; buf++) + if (*buf == '\n') + n++; + return n; +} + +static unsigned int regview_test_nr_listed(const struct apple_regview_hw *hw) +{ + unsigned int i, n = 0; + + for (i = 0; i < hw->nr_ranges; i++) + n += hw->ranges[i].count; + return n; +} + +static void regview_test_stride_default(struct kunit *test) +{ + struct apple_regview_range r = { .stride = 0 }; + + KUNIT_EXPECT_EQ(test, apple_regview_stride(&r), 4); + r.stride = 0x10; + KUNIT_EXPECT_EQ(test, apple_regview_stride(&r), 0x10); + r.stride = MCC_PLANE_STRIDE; + KUNIT_EXPECT_EQ(test, apple_regview_stride(&r), MCC_PLANE_STRIDE); +} + +/* A run whose last word ends exactly at the end of the entry is accepted. */ +static void regview_test_check_exact_fit(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, 0x10, 4, 0, "a" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 1, .nr_regs = 1, + }; + struct apple_regview_map map = { .size = 0x20 }; + struct apple_regview rv = { .hw = &hw, .maps = &map }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), 0); + map.size = 0x1000; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), 0); +} + +/* One byte or one word short of the last register is refused. */ +static void regview_test_check_one_past(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, 0x10, 4, 0, "a" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 1, .nr_regs = 1, + }; + struct apple_regview_map map = { .size = 0x1c }; + struct apple_regview rv = { .hw = &hw, .maps = &map }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); + map.size = 0x1f; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); + map.size = 0; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); +} + +/* The stride, not 4, sets how far a strided run reaches. */ +static void regview_test_check_strided(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, MCC_PLANE_CACHE_STATUS, 4, MCC_PLANE_STRIDE, "s" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 1, .nr_regs = 1, + }; + const u64 need = MCC_PLANE_CACHE_STATUS + 3 * MCC_PLANE_STRIDE + 4; + struct apple_regview_map map = { .size = need }; + struct apple_regview rv = { .hw = &hw, .maps = &map }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), 0); + map.size = need - 4; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); + /* Large enough for four packed words but not for four planes. */ + map.size = MCC_PLANE_CACHE_STATUS + 16; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); +} + +/* A range naming a reg entry the node need not have is refused. */ +static void regview_test_check_bad_reg(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, 0, 1, 0, "a" }, + { 2, 0, 1, 0, "b" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 2, .nr_regs = 2, + }; + struct apple_regview_map maps[3] = { + { .size = 0x100 }, { .size = 0x100 }, { .size = 0x100 }, + }; + struct apple_regview rv = { .hw = &hw, .maps = maps }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); +} + +static void regview_test_check_zero_count(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, 0, 0, 0, "empty" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 1, .nr_regs = 1, + }; + struct apple_regview_map map = { .size = 0x100 }; + struct apple_regview rv = { .hw = &hw, .maps = &map }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); +} + +/* Offsets near 4 GiB must not wrap around into a small aperture. */ +static void regview_test_check_no_wrap(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, 0xfffffffc, 2, 0, "wrap" }, + }; + static const struct apple_regview_range ranges_stride[] = { + { 0, 0x10, 3, 0x80000000, "wrap" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 1, .nr_regs = 1, + }; + static const struct apple_regview_hw hw_stride = { + .ranges = ranges_stride, .nr_ranges = 1, .nr_regs = 1, + }; + struct apple_regview_map map = { .size = 0x1000 }; + struct apple_regview rv = { .hw = &hw, .maps = &map }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); + rv.hw = &hw_stride; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); +} + +/* Each range is checked against its own reg entry, every range is checked. */ +static void regview_test_check_per_entry(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, 0x0, 1, 0, "small" }, + { 1, 0x800, 1, 0, "big" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 2, .nr_regs = 2, + }; + struct apple_regview_map maps[2] = { + { .size = 0x1000 }, { .size = 0x804 }, + }; + struct apple_regview rv = { .hw = &hw, .maps = maps }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), 0); + /* reg 1 too small even though reg 0 is large */ + maps[1].size = 0x800; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); + /* the last range of the list fails, the first one fits */ + maps[1].size = 0x804; + maps[0].size = 0; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); +} + +/* + * Every built-in list fits the smallest apertures that hold it and is refused + * as soon as any entry it uses is a word smaller. + */ +static void regview_test_tables_fit(struct kunit *test) +{ + const struct of_device_id *id; + + for (id = apple_regview_of_match; id->compatible[0]; id++) { + const struct apple_regview_hw *hw = id->data; + struct regview_test_ctx *ctx = regview_test_setup(test, hw, 0); + unsigned int i; + + KUNIT_EXPECT_EQ_MSG(test, apple_regview_check(&ctx->rv), 0, + "%s", id->compatible); + for (i = 0; i < hw->nr_regs; i++) { + if (!regview_test_extent(hw, i)) + continue; + ctx->maps[i].size -= 4; + KUNIT_EXPECT_EQ_MSG(test, apple_regview_check(&ctx->rv), + -EINVAL, "%s reg %u", id->compatible, i); + ctx->maps[i].size += 4; + } + } +} + +/* Lists are word aligned and name each register at most once. */ +static void regview_test_tables_sane(struct kunit *test) +{ + const struct of_device_id *id; + + for (id = apple_regview_of_match; id->compatible[0]; id++) { + const struct apple_regview_hw *hw = id->data; + unsigned int i, j, a, b; + + KUNIT_ASSERT_NOT_NULL(test, hw); + KUNIT_EXPECT_GT(test, hw->nr_ranges, 0); + KUNIT_EXPECT_GT(test, hw->nr_regs, 0); + + for (i = 0; i < hw->nr_ranges; i++) { + const struct apple_regview_range *r = &hw->ranges[i]; + u32 sr = apple_regview_stride(r); + + KUNIT_EXPECT_LT_MSG(test, r->reg, hw->nr_regs, "%s %s", + id->compatible, r->name); + KUNIT_EXPECT_GT(test, r->count, 0); + KUNIT_EXPECT_EQ(test, r->offset % 4, 0); + KUNIT_EXPECT_EQ(test, sr % 4, 0); + KUNIT_EXPECT_NOT_NULL(test, r->name); + + for (j = i + 1; j < hw->nr_ranges; j++) { + const struct apple_regview_range *q = &hw->ranges[j]; + u32 sq = apple_regview_stride(q); + + if (q->reg != r->reg) + continue; + for (a = 0; a < r->count; a++) { + u32 ra = r->offset + a * sr; + + for (b = 0; b < q->count; b++) + KUNIT_EXPECT_NE_MSG(test, ra, q->offset + b * sq, + "%s: %s[%u] and %s[%u]", + id->compatible, r->name, + a, q->name, b); + } + } + } + } +} + +/* The number of registers each block exposes, as its comment describes. */ +static void regview_test_tables_counts(struct kunit *test) +{ + static const struct { + const char *compatible; + unsigned int regs; + unsigned int nr_regs; + } want[] = { + /* 4 regions x start/end/enable + 4 planes */ + { "apple,t8112-mcc", 16, 2 }, + /* the same on controller 0, plus 4 planes on the other three */ + { "apple,t6000-mcc", 28, 4 }, + /* ten bus fault and seven queue fault counters */ + { "apple,t8112-spmi-sideband", 17, 1 }, + /* sixteen fault counters of the primary bus */ + { "apple,t6000-spmi-monitor", 16, 2 }, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(want); i++) { + const struct apple_regview_hw *hw = regview_test_hw(want[i].compatible); + + KUNIT_ASSERT_NOT_NULL_MSG(test, hw, "%s", want[i].compatible); + KUNIT_EXPECT_EQ_MSG(test, regview_test_nr_listed(hw), want[i].regs, + "%s", want[i].compatible); + KUNIT_EXPECT_EQ_MSG(test, hw->nr_regs, want[i].nr_regs, + "%s", want[i].compatible); + } +} + +/* + * Reading the SPMI monitor fault queue (reg[0]) pops an entry, so its list + * must only name the counter window. + */ +static void regview_test_spmi_monitor_no_queue(struct kunit *test) +{ + const struct apple_regview_hw *hw = + regview_test_hw("apple,t6000-spmi-monitor"); + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, hw); + for (i = 0; i < hw->nr_ranges; i++) + KUNIT_EXPECT_EQ_MSG(test, hw->ranges[i].reg, SPMI_MON_COUNTERS, + "%s", hw->ranges[i].name); +} + +/* The T8112 MCC planes live in reg[1]; reg[0] is never read. */ +static void regview_test_t8112_mcc_layout(struct kunit *test) +{ + const struct apple_regview_hw *hw = regview_test_hw("apple,t8112-mcc"); + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, hw); + for (i = 0; i < hw->nr_ranges; i++) + KUNIT_EXPECT_EQ(test, hw->ranges[i].reg, 1); + KUNIT_EXPECT_EQ(test, regview_test_extent(hw, 1), + MCC_PLANE_CACHE_STATUS + 3 * MCC_PLANE_STRIDE + 4); +} + +/* Exact text of the sideband view: one line per register, in list order. */ +static void regview_test_show_format(struct kunit *test) +{ + const struct apple_regview_hw *hw = + regview_test_hw("apple,t8112-spmi-sideband"); + struct regview_test_ctx *ctx = regview_test_setup(test, hw, 0); + const char *tail, *want; + char line[64]; + unsigned int j; + + regview_test_fill(ctx); + regview_test_show(test, ctx); + + KUNIT_EXPECT_EQ(test, regview_test_lines(ctx->seq_buf), + regview_test_nr_listed(hw)); + want = "0+0x0000200 bus-fault-count[0]: 0xa0000200\n"; + KUNIT_EXPECT_TRUE(test, regview_test_starts(ctx, want)); + want = "\n0+0x0000224 bus-fault-count[9]: 0xa0000224\n" + "0+0x000025c queue-fault-count[0]: 0xa000025c\n"; + KUNIT_EXPECT_TRUE(test, regview_test_has(ctx, want)); + tail = "\n0+0x0000274 queue-fault-count[6]: 0xa0000274\n"; + KUNIT_ASSERT_GE(test, ctx->seq_len, strlen(tail)); + KUNIT_EXPECT_STREQ(test, ctx->seq_buf + ctx->seq_len - strlen(tail), tail); + /* The words between the two runs are not shown. */ + KUNIT_EXPECT_NULL(test, strstr(ctx->seq_buf, "0x0000228")); + KUNIT_EXPECT_NULL(test, strstr(ctx->seq_buf, "[10]")); + + for (j = 0; j < SPMI_SB_NR_BUS_FAULTS; j++) { + snprintf(line, sizeof(line), "0+0x%07x bus-fault-count[%u]: 0x%08x\n", + SPMI_SB_BUS_FAULTS + 4 * j, j, + regview_test_tag(0, SPMI_SB_BUS_FAULTS + 4 * j)); + KUNIT_EXPECT_NOT_NULL_MSG(test, strstr(ctx->seq_buf, line), "%s", line); + } +} + +/* Values are printed as full 8-digit words, including 0 and all-ones. */ +static void regview_test_show_values(struct kunit *test) +{ + const struct apple_regview_hw *hw = + regview_test_hw("apple,t8112-spmi-sideband"); + struct regview_test_ctx *ctx = regview_test_setup(test, hw, 0); + const char *want; + __le32 *w; + + w = ctx->buf[0]; + w[SPMI_SB_BUS_FAULTS / 4] = cpu_to_le32(U32_MAX); + w[SPMI_SB_BUS_FAULTS / 4 + 1] = cpu_to_le32(1); + regview_test_show(test, ctx); + + want = "0+0x0000200 bus-fault-count[0]: 0xffffffff\n" + "0+0x0000204 bus-fault-count[1]: 0x00000001\n" + "0+0x0000208 bus-fault-count[2]: 0x00000000\n"; + KUNIT_EXPECT_TRUE(test, regview_test_starts(ctx, want)); +} + +/* A strided run reads the word of each plane, not consecutive words. */ +static void regview_test_show_strided(struct kunit *test) +{ + const struct apple_regview_hw *hw = regview_test_hw("apple,t8112-mcc"); + struct regview_test_ctx *ctx = regview_test_setup(test, hw, 0); + const char *want; + char line[64]; + unsigned int j; + + regview_test_fill(ctx); + regview_test_show(test, ctx); + + KUNIT_EXPECT_EQ(test, regview_test_lines(ctx->seq_buf), 16); + want = "1+0x00006a0 tz-start[0]: 0xa10006a0\n" + "1+0x00006b0 tz-start[1]: 0xa10006b0\n"; + KUNIT_EXPECT_TRUE(test, regview_test_starts(ctx, want)); + for (j = 0; j < 4; j++) { + u32 off = MCC_PLANE_CACHE_STATUS + j * MCC_PLANE_STRIDE; + + snprintf(line, sizeof(line), "1+0x%07x cache-status[%u]: 0x%08x\n", + off, j, regview_test_tag(1, off)); + KUNIT_EXPECT_NOT_NULL_MSG(test, strstr(ctx->seq_buf, line), "%s", line); + } + KUNIT_EXPECT_TRUE(test, regview_test_has(ctx, "1+0x00006a8 tz-enable[0]: 0xa10006a8\n")); + KUNIT_EXPECT_TRUE(test, regview_test_has(ctx, "1+0x00c1c04 cache-status[3]: ")); +} + +/* Each range reads the window of its own reg entry. */ +static void regview_test_show_multi_entry(struct kunit *test) +{ + const struct apple_regview_hw *hw = regview_test_hw("apple,t6000-mcc"); + struct regview_test_ctx *ctx = regview_test_setup(test, hw, 0); + char line[64]; + unsigned int reg; + + regview_test_fill(ctx); + regview_test_show(test, ctx); + + KUNIT_EXPECT_EQ(test, regview_test_lines(ctx->seq_buf), 28); + for (reg = 0; reg < 4; reg++) { + u32 off = MCC_PLANE_CACHE_STATUS + 2 * MCC_PLANE_STRIDE; + + snprintf(line, sizeof(line), "%u+0x%07x cache-status[2]: 0x%08x\n", + reg, off, regview_test_tag(reg, off)); + KUNIT_EXPECT_NOT_NULL_MSG(test, strstr(ctx->seq_buf, line), "%s", line); + } + /* The carveouts are only listed for controller 0. */ + KUNIT_EXPECT_NULL(test, strstr(ctx->seq_buf, "1+0x00006a0")); +} + +/* Showing a view leaves every byte of every window as it was. */ +static void regview_test_show_never_writes(struct kunit *test) +{ + const struct of_device_id *id; + + for (id = apple_regview_of_match; id->compatible[0]; id++) { + struct regview_test_ctx *ctx = regview_test_setup(test, id->data, 0x100); + unsigned int i; + + regview_test_fill(ctx); + for (i = 0; i < ctx->rv.hw->nr_regs; i++) + memset(ctx->buf[i] + ctx->maps[i].size, 0x5a, 4); + + regview_test_show(test, ctx); + + for (i = 0; i < ctx->rv.hw->nr_regs; i++) { + __le32 *w = ctx->buf[i]; + u64 off; + u32 guard; + + for (off = 0; off + 4 <= ctx->maps[i].size; off += 4) + if (le32_to_cpu(w[off / 4]) != regview_test_tag(i, off)) + break; + KUNIT_EXPECT_EQ_MSG(test, off, (u64)ctx->maps[i].size, + "%s reg %u", id->compatible, i); + memcpy(&guard, ctx->buf[i] + ctx->maps[i].size, 4); + KUNIT_EXPECT_EQ(test, guard, 0x5a5a5a5a); + } + } +} + +/* The debugfs file has no write method. */ +static void regview_test_fops_read_only(struct kunit *test) +{ + const struct file_operations *fops = apple_regview_test_fops(); + + KUNIT_EXPECT_NULL(test, fops->write); + KUNIT_EXPECT_NULL(test, fops->write_iter); + KUNIT_EXPECT_NOT_NULL(test, fops->read); +} + +static struct kunit_case regview_test_cases[] = { + KUNIT_CASE(regview_test_stride_default), + KUNIT_CASE(regview_test_check_exact_fit), + KUNIT_CASE(regview_test_check_one_past), + KUNIT_CASE(regview_test_check_strided), + KUNIT_CASE(regview_test_check_bad_reg), + KUNIT_CASE(regview_test_check_zero_count), + KUNIT_CASE(regview_test_check_no_wrap), + KUNIT_CASE(regview_test_check_per_entry), + KUNIT_CASE(regview_test_tables_fit), + KUNIT_CASE(regview_test_tables_sane), + KUNIT_CASE(regview_test_tables_counts), + KUNIT_CASE(regview_test_spmi_monitor_no_queue), + KUNIT_CASE(regview_test_t8112_mcc_layout), + KUNIT_CASE(regview_test_show_format), + KUNIT_CASE(regview_test_show_values), + KUNIT_CASE(regview_test_show_strided), + KUNIT_CASE(regview_test_show_multi_entry), + KUNIT_CASE(regview_test_show_never_writes), + KUNIT_CASE(regview_test_fops_read_only), + {} +}; + +static struct kunit_suite regview_test_suite = { + .name = "apple-regview", + .test_cases = regview_test_cases, +}; + +kunit_test_suite(regview_test_suite); + +MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING"); +MODULE_LICENSE("GPL"); diff --git a/drivers/soc/apple/regview.c b/drivers/soc/apple/regview.c index 27f562c6d5d73f..09302eb0f78edf 100644 --- a/drivers/soc/apple/regview.c +++ b/drivers/soc/apple/regview.c @@ -31,41 +31,17 @@ #include #include -/* One run of 32-bit registers inside one DT reg entry. */ -struct apple_regview_range { - u8 reg; /* index into the node's reg property */ - u32 offset; /* byte offset from the start of that entry */ - u32 count; /* number of 32-bit registers */ - u32 stride; /* byte distance between registers; 0 means 4 */ - const char *name; -}; +#include "regview-internal.h" -struct apple_regview_hw { - const struct apple_regview_range *ranges; - unsigned int nr_ranges; - unsigned int nr_regs; /* reg entries the node must have */ -}; - -struct apple_regview_map { - void __iomem *base; - resource_size_t size; -}; +#if IS_ENABLED(CONFIG_APPLE_REGVIEW_KUNIT_TEST) +#include +#else +#define VISIBLE_IF_KUNIT static +#define EXPORT_SYMBOL_IF_KUNIT(symbol) +#endif static struct dentry *apple_regview_root; -struct apple_regview { - struct device *dev; - const struct apple_regview_hw *hw; - struct apple_regview_map *maps; - struct dentry *dir; -}; - -#define MCC_PLANE_STRIDE 0x40000 -#define MCC_PLANE_CACHE_STATUS 0x1c04 -#define MCC_TZ_BASE 0x6a0 -#define MCC_TZ_STRIDE 0x10 -#define MCC_TZ_REGIONS 4 - /* * Plane 0 carveout start, end and enable of each region, then the cache * status of each plane. @@ -107,8 +83,6 @@ static const struct apple_regview_hw apple_regview_t6000_mcc_hw = { * collisions) followed by seven queue and filter fault counters. Only the * counters are listed; how they wrap is not part of the interface. */ -#define SPMI_SB_BUS_FAULTS 0x200 -#define SPMI_SB_NR_BUS_FAULTS 10 #define SPMI_SB_QUEUE_FAULTS 0x25c #define SPMI_SB_NR_QUEUE_FAULTS 7 @@ -133,7 +107,6 @@ static const struct apple_regview_hw apple_regview_t8112_spmi_sb_hw = { * have no known meaning and are not read. reg[0] holds the fault queue, whose * data port pops an entry on every read, so nothing in reg[0] is listed. */ -#define SPMI_MON_COUNTERS 1 #define SPMI_MON_BUS_FAULTS 0x00 #define SPMI_MON_NR_BUS_FAULTS 3 #define SPMI_MON_PROTO_FAULTS 0x10 @@ -156,12 +129,13 @@ static const struct apple_regview_hw apple_regview_t6000_spmi_mon_hw = { .nr_regs = 2, }; -static u32 apple_regview_stride(const struct apple_regview_range *r) +VISIBLE_IF_KUNIT u32 apple_regview_stride(const struct apple_regview_range *r) { return r->stride ? r->stride : 4; } +EXPORT_SYMBOL_IF_KUNIT(apple_regview_stride); -static int apple_regview_check(const struct apple_regview *rv) +VISIBLE_IF_KUNIT int apple_regview_check(const struct apple_regview *rv) { const struct apple_regview_hw *hw = rv->hw; unsigned int i; @@ -179,8 +153,9 @@ static int apple_regview_check(const struct apple_regview *rv) return 0; } +EXPORT_SYMBOL_IF_KUNIT(apple_regview_check); -static int apple_regview_show(struct seq_file *s, void *unused) +VISIBLE_IF_KUNIT int apple_regview_show(struct seq_file *s, void *unused) { struct apple_regview *rv = s->private; const struct apple_regview_hw *hw = rv->hw; @@ -202,8 +177,17 @@ static int apple_regview_show(struct seq_file *s, void *unused) return 0; } +EXPORT_SYMBOL_IF_KUNIT(apple_regview_show); DEFINE_SHOW_ATTRIBUTE(apple_regview); +#if IS_ENABLED(CONFIG_APPLE_REGVIEW_KUNIT_TEST) +const struct file_operations *apple_regview_test_fops(void) +{ + return &apple_regview_fops; +} +EXPORT_SYMBOL_IF_KUNIT(apple_regview_test_fops); +#endif + static void apple_regview_remove_debugfs(void *data) { debugfs_remove_recursive(data); @@ -260,7 +244,7 @@ static int apple_regview_probe(struct platform_device *pdev) rv->dir); } -static const struct of_device_id apple_regview_of_match[] = { +VISIBLE_IF_KUNIT const struct of_device_id apple_regview_of_match[] = { { .compatible = "apple,t8112-mcc", .data = &apple_regview_t8112_mcc_hw }, { .compatible = "apple,t6000-mcc", .data = &apple_regview_t6000_mcc_hw }, { .compatible = "apple,t8112-spmi-sideband", @@ -269,6 +253,7 @@ static const struct of_device_id apple_regview_of_match[] = { .data = &apple_regview_t6000_spmi_mon_hw }, {} }; +EXPORT_SYMBOL_IF_KUNIT(apple_regview_of_match); MODULE_DEVICE_TABLE(of, apple_regview_of_match); static struct platform_driver apple_regview_driver = { diff --git a/drivers/soc/apple/regview.kunitconfig b/drivers/soc/apple/regview.kunitconfig new file mode 100644 index 00000000000000..ed7098ece9530b --- /dev/null +++ b/drivers/soc/apple/regview.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_PM=y +CONFIG_DEBUG_FS=y +CONFIG_APPLE_REGVIEW=y +CONFIG_APPLE_REGVIEW_KUNIT_TEST=y diff --git a/drivers/soc/apple/rtkit-crashlog-test.c b/drivers/soc/apple/rtkit-crashlog-test.c new file mode 100644 index 00000000000000..930f9b07d8b935 --- /dev/null +++ b/drivers/soc/apple/rtkit-crashlog-test.c @@ -0,0 +1,454 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the RTKit crashlog parser. Included by rtkit-crashlog.c. + * + * apple_rtkit_crashlog_locate() is checked for the offsets it returns. The + * dump tests place each log flush against the end of a vmalloc() area, so a + * read past the log runs into the guard page and fails the case. + */ +#include +#include +#include + +#define CL_TEST_AREA PAGE_SIZE +#define CL_TEST_ID_OUTER FOURCC('A', 'O', 'P', ' ') +#define CL_TEST_ID_INNER FOURCC('t', 's', 'k', '1') +#define CL_TEST_SECTION 16 + +struct cl_test_ctx { + struct apple_rtkit *rtk; + u8 *area; +}; + +static int cl_test_init(struct kunit *test) +{ + struct cl_test_ctx *ctx; + struct device *dev; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->rtk = kunit_kzalloc(test, sizeof(*ctx->rtk), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->rtk); + dev = kunit_device_register(test, "apple-rtkit-crashlog-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + ctx->rtk->dev = dev; + ctx->area = vzalloc(CL_TEST_AREA); + KUNIT_ASSERT_NOT_NULL(test, ctx->area); + test->priv = ctx; + return 0; +} + +static void cl_test_exit(struct kunit *test) +{ + struct cl_test_ctx *ctx = test->priv; + + vfree(ctx->area); +} + +/* A buffer of @size bytes that ends where the vmalloc guard page begins. */ +static u8 *cl_test_tail(struct kunit *test, size_t size) +{ + struct cl_test_ctx *ctx = test->priv; + + KUNIT_ASSERT_LE(test, size, CL_TEST_AREA); + memset(ctx->area, 0, CL_TEST_AREA); + return ctx->area + CL_TEST_AREA - size; +} + +static void cl_test_put32(u8 *p, u32 v) +{ + memcpy(p, &v, sizeof(v)); +} + +static void cl_test_put64(u8 *p, u64 v) +{ + memcpy(p, &v, sizeof(v)); +} + +static void cl_test_log(u8 *p, u32 size, u32 flags) +{ + struct apple_rtkit_crashlog_header h = { + .fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC, + .size = size, + .flags = flags, + }; + + memcpy(p, &h, sizeof(h)); +} + +static void cl_test_container(u8 *p, u32 size, u32 current_id, u32 count) +{ + struct apple_rtkit_crashlog_container c = { + .fourcc = APPLE_RTKIT_CRASHLOG_CONTAINER_FOURCC, + .version = APPLE_RTKIT_CRASHLOG_CONTAINER_VERSION << 8, + .size = size, + .current_id = current_id, + .count = count, + }; + + memcpy(p, &c, sizeof(c)); +} + +static void cl_test_record(u8 *container, u32 i, u64 id, u32 offset) +{ + struct apple_rtkit_crashlog_record r = { + .id = id, + .offset = offset, + }; + + memcpy(container + sizeof(struct apple_rtkit_crashlog_container) + i * sizeof(r), + &r, sizeof(r)); +} + +/* A section header: its fourcc and its size, which counts the header. */ +static u8 *cl_test_section(u8 *p, u32 fourcc, u32 size) +{ + cl_test_put32(p, fourcc); + cl_test_put32(p + 12, size); + return p + size; +} + +static int cl_test_locate(const u8 *bfr, size_t size, size_t *offset, u32 *id, + unsigned int *depth) +{ + *offset = ~0; + *id = ~0; + *depth = ~0; + return apple_rtkit_crashlog_locate(bfr, size, offset, id, depth); +} + +static void cl_test_locate_bare(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x100); + unsigned int depth; + size_t offset; + u32 id; + + cl_test_log(bfr, 0x100, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), 0); + KUNIT_EXPECT_EQ(test, offset, 0); + KUNIT_EXPECT_EQ(test, id, 0); + KUNIT_EXPECT_EQ(test, depth, 0); + + /* A bare log is taken as it is, even marked as still being written. */ + cl_test_log(bfr, 0x40, APPLE_RTKIT_CRASHLOG_INCOMPLETE); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), 0); +} + +static void cl_test_locate_bare_invalid(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x100); + unsigned int depth; + size_t offset; + u32 id; + + cl_test_log(bfr, 0x101, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_log(bfr, sizeof(struct apple_rtkit_crashlog_header) - 1, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_put32(bfr, FOURCC('C', 'L', 'H', 'F')); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + + /* Shorter than a header: nothing is read past the end. */ + bfr = cl_test_tail(test, sizeof(struct apple_rtkit_crashlog_header) - 1); + cl_test_put32(bfr, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x1f, &offset, &id, &depth), -EINVAL); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0, &offset, &id, &depth), -EINVAL); +} + +static void cl_test_locate_container(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x200); + unsigned int depth; + size_t offset; + u32 id; + + cl_test_container(bfr, 0x200, CL_TEST_ID_OUTER, 2); + cl_test_record(bfr, 0, FOURCC('o', 't', 'h', 'r'), 0x80); + cl_test_record(bfr, 1, CL_TEST_ID_OUTER, 0x100); + cl_test_log(bfr + 0x80, 0x40, 0); + cl_test_log(bfr + 0x100, 0x100, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x200, &offset, &id, &depth), 0); + KUNIT_EXPECT_EQ(test, offset, 0x100); + KUNIT_EXPECT_EQ(test, id, CL_TEST_ID_OUTER); + KUNIT_EXPECT_EQ(test, depth, 1); + + /* The selected log may fill the rest of the buffer, but no more. */ + cl_test_log(bfr + 0x100, 0x101, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x200, &offset, &id, &depth), -EINVAL); + + /* A log still being written is retried later. */ + cl_test_log(bfr + 0x100, 0x100, APPLE_RTKIT_CRASHLOG_INCOMPLETE); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x200, &offset, &id, &depth), -EAGAIN); +} + +static void cl_test_locate_nested(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x400); + unsigned int depth; + size_t offset; + u32 id; + + /* Per-coprocessor, then per-task: offsets are from each container. */ + cl_test_container(bfr, 0x400, CL_TEST_ID_OUTER, 1); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x100); + cl_test_container(bfr + 0x100, 0x300, CL_TEST_ID_INNER, 2); + cl_test_record(bfr + 0x100, 0, FOURCC('t', 's', 'k', '0'), 0x80); + cl_test_record(bfr + 0x100, 1, CL_TEST_ID_INNER, 0x200); + cl_test_log(bfr + 0x300, 0x100, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x400, &offset, &id, &depth), 0); + KUNIT_EXPECT_EQ(test, offset, 0x300); + KUNIT_EXPECT_EQ(test, id, CL_TEST_ID_INNER); + KUNIT_EXPECT_EQ(test, depth, 2); + + /* + * The inner log's size is checked against what follows it, not against + * the whole buffer: 0x180 fits the buffer but not the space left. + */ + cl_test_log(bfr + 0x300, 0x180, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x400, &offset, &id, &depth), -EINVAL); + + /* The same for an inner container claiming more than is left. */ + cl_test_log(bfr + 0x300, 0x100, 0); + cl_test_container(bfr + 0x100, 0x301, CL_TEST_ID_INNER, 2); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x400, &offset, &id, &depth), -EINVAL); +} + +static void cl_test_locate_bad_container(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x100); + unsigned int depth; + size_t offset; + u32 id; + +#define CL_TEST_RESET() do { \ + cl_test_container(bfr, 0x100, CL_TEST_ID_OUTER, 1); \ + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x80); \ + cl_test_log(bfr + 0x80, 0x80, 0); \ + } while (0) + + CL_TEST_RESET(); + KUNIT_ASSERT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), 0); + + /* Another container version. */ + cl_test_put32(bfr + 4, 3 << 8); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + CL_TEST_RESET(); + /* Larger than the buffer. */ + cl_test_container(bfr, 0x101, CL_TEST_ID_OUTER, 1); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + /* No records, or more than the buffer can hold. */ + cl_test_container(bfr, 0x100, CL_TEST_ID_OUTER, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_container(bfr, 0x100, CL_TEST_ID_OUTER, (0x100 - 0x14) / 0x18 + 1); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + /* No record has the current ID. */ + cl_test_container(bfr, 0x100, CL_TEST_ID_INNER, 1); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + /* A record pointing back into its container, at its end, or past it. */ + CL_TEST_RESET(); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x13); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x100); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0xffffffff); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + /* A record leading to too little for a header. */ + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0xf0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); +#undef CL_TEST_RESET +} + +static void cl_test_locate_depth(struct kunit *test) +{ + unsigned int max = APPLE_RTKIT_CRASHLOG_CONTAINER_MAX_DEPTH, depth, i; + size_t len = 0x40 * (max + 2), offset; + u8 *bfr = cl_test_tail(test, len); + u32 id; + + /* @max containers, each leading 0x40 bytes on, then a log. */ + for (i = 0; i < max; i++) { + cl_test_container(bfr + 0x40 * i, len - 0x40 * i, i + 1, 1); + cl_test_record(bfr + 0x40 * i, 0, i + 1, 0x40); + } + cl_test_log(bfr + 0x40 * max, 0x40, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, len, &offset, &id, &depth), 0); + KUNIT_EXPECT_EQ(test, depth, max); + KUNIT_EXPECT_EQ(test, offset, 0x40 * max); + KUNIT_EXPECT_EQ(test, id, max); + + /* One container more is too deep. */ + cl_test_container(bfr + 0x40 * max, len - 0x40 * max, max + 1, 1); + cl_test_record(bfr + 0x40 * max, 0, max + 1, 0x40); + cl_test_log(bfr + 0x40 * (max + 1), 0x40, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, len, &offset, &id, &depth), -EINVAL); +} + +/* Every decoder, ending with a footer. The dump must reach it in bounds. */ +static void cl_test_dump_full(struct kunit *test) +{ + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x20 + 0x30 + 0x30 + 0x18 + (28 + 2 * 24) + (16 + 0x350) + + APPLE_RTKIT_CRASHLOG_CL4_SECTION_SIZE + 0x30 + 0x10 + CL_TEST_SECTION; + u8 *bfr = cl_test_tail(test, len), *p; + + cl_test_log(bfr, len, 0); + p = bfr + 0x20; + memcpy(p + 20, "panic: test\nsecond line", 23); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_STR, 0x30); + memset(p + 16, 'v', 0x30 - 16); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_VERSION, 0x30); + cl_test_put64(p + 16, 1234); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_TIME, 0x18); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_MBOX, 28 + 2 * 24); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_REGS, 16 + 0x350); + cl_test_put32(p + APPLE_RTKIT_CRASHLOG_CL4_SIZE, APPLE_RTKIT_CRASHLOG_CL4_NOMINAL_SIZE); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_REGS_CL4, + APPLE_RTKIT_CRASHLOG_CL4_SECTION_SIZE); + p = cl_test_section(p, FOURCC('C', 'c', 's', 't'), 0x30); + /* An empty unknown section: a header only. */ + p = cl_test_section(p, FOURCC('C', 'x', 'y', 'z'), 0x10); + cl_test_section(p, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC, CL_TEST_SECTION); + KUNIT_ASSERT_PTR_EQ(test, p + CL_TEST_SECTION, bfr + len); + + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + KUNIT_SUCCEED(test); +} + +/* + * The last section of a log without a footer: its decoder could read 16 + * bytes past the log, so it is not decoded. + */ +static void cl_test_dump_no_footer(struct kunit *test) +{ + static const u32 fourccs[] = { + APPLE_RTKIT_CRASHLOG_STR, APPLE_RTKIT_CRASHLOG_VERSION, + APPLE_RTKIT_CRASHLOG_MBOX, APPLE_RTKIT_CRASHLOG_TIME, + FOURCC('C', 'c', 's', 't'), + }; + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x20 + 0x40; + u8 *bfr; + int i; + + for (i = 0; i < ARRAY_SIZE(fourccs); i++) { + bfr = cl_test_tail(test, len); + cl_test_log(bfr, len, 0); + /* No newline and no terminator: Cstr must stop at the section. */ + memset(bfr + 0x20 + 16, 'x', 0x40 - 16); + cl_test_section(bfr + 0x20, fourccs[i], 0x40); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + } + KUNIT_SUCCEED(test); +} + +static void cl_test_dump_bad_sizes(struct kunit *test) +{ + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x80; + u8 *bfr = cl_test_tail(test, len); + + /* A log claiming more than the buffer. */ + cl_test_log(bfr, len + 0x1000, 0); + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION, len - 0x20 + 0x800); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + + /* A section larger than what is left of the log. */ + cl_test_log(bfr, len, 0); + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION, len - 0x20 + 1); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + + /* Sizes that would never advance or underflow a decoder. */ + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION, 0); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION, 15); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + + /* A section header cut off by the end of the log. */ + bfr = cl_test_tail(test, 0x28); + cl_test_log(bfr, 0x28, 0); + cl_test_put32(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, 0x28); + + /* Too small for a header. */ + apple_rtkit_crashlog_dump(ctx->rtk, cl_test_tail(test, 0x1f), 0x1f); + KUNIT_SUCCEED(test); +} + +/* Sections too small for their decoders are skipped, not decoded. */ +static void cl_test_dump_small_sections(struct kunit *test) +{ + static const u32 fourccs[] = { + APPLE_RTKIT_CRASHLOG_MBOX, APPLE_RTKIT_CRASHLOG_REGS, + APPLE_RTKIT_CRASHLOG_REGS_CL4, APPLE_RTKIT_CRASHLOG_TIME, + }; + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x20 + 0x10 + CL_TEST_SECTION; + u8 *bfr; + int i; + + for (i = 0; i < ARRAY_SIZE(fourccs); i++) { + bfr = cl_test_tail(test, len); + cl_test_log(bfr, len, 0); + cl_test_section(bfr + 0x20, fourccs[i], 0x10); + cl_test_section(bfr + 0x30, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC, + CL_TEST_SECTION); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + } + + /* A Crl4 frame of another size is not decoded either. */ + len = 0x20 + APPLE_RTKIT_CRASHLOG_CL4_SECTION_SIZE + CL_TEST_SECTION; + bfr = cl_test_tail(test, len); + cl_test_log(bfr, len, 0); + cl_test_put32(bfr + 0x20 + APPLE_RTKIT_CRASHLOG_CL4_SIZE, 0xd0); + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_REGS_CL4, + APPLE_RTKIT_CRASHLOG_CL4_SECTION_SIZE); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + KUNIT_SUCCEED(test); +} + +static void cl_test_dump_container(struct kunit *test) +{ + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x100; + u8 *bfr = cl_test_tail(test, len); + + /* The selected log ends the buffer; its last section has no footer. */ + cl_test_container(bfr, len, CL_TEST_ID_OUTER, 1); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x80); + cl_test_log(bfr + 0x80, 0x80, 0); + memset(bfr + 0xa0 + 16, 'x', 0x60 - 16); + cl_test_section(bfr + 0xa0, APPLE_RTKIT_CRASHLOG_VERSION, 0x60); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + + /* A container whose record leads past the end is not followed. */ + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x1000); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + KUNIT_SUCCEED(test); +} + +static struct kunit_case apple_rtkit_crashlog_test_cases[] = { + KUNIT_CASE(cl_test_locate_bare), + KUNIT_CASE(cl_test_locate_bare_invalid), + KUNIT_CASE(cl_test_locate_container), + KUNIT_CASE(cl_test_locate_nested), + KUNIT_CASE(cl_test_locate_bad_container), + KUNIT_CASE(cl_test_locate_depth), + KUNIT_CASE(cl_test_dump_full), + KUNIT_CASE(cl_test_dump_no_footer), + KUNIT_CASE(cl_test_dump_bad_sizes), + KUNIT_CASE(cl_test_dump_small_sections), + KUNIT_CASE(cl_test_dump_container), + {} +}; + +static struct kunit_suite apple_rtkit_crashlog_test_suite = { + .name = "apple-rtkit-crashlog", + .init = cl_test_init, + .exit = cl_test_exit, + .test_cases = apple_rtkit_crashlog_test_cases, +}; + +kunit_test_suite(apple_rtkit_crashlog_test_suite); diff --git a/drivers/soc/apple/rtkit-crashlog.c b/drivers/soc/apple/rtkit-crashlog.c index 81c5af4e29fc04..f12a3f6fda8549 100644 --- a/drivers/soc/apple/rtkit-crashlog.c +++ b/drivers/soc/apple/rtkit-crashlog.c @@ -492,3 +492,7 @@ void apple_rtkit_crashlog_dump(struct apple_rtkit *rtk, u8 *bfr, size_t size) dev_warn(rtk->dev, "RTKit: End of crashlog reached but no footer present"); } + +#ifdef CONFIG_APPLE_RTKIT_KUNIT_TEST +#include "rtkit-crashlog-test.c" +#endif diff --git a/drivers/soc/apple/rtkit-helper-test.c b/drivers/soc/apple/rtkit-helper-test.c new file mode 100644 index 00000000000000..4e3aa1b0e07aa3 --- /dev/null +++ b/drivers/soc/apple/rtkit-helper-test.c @@ -0,0 +1,919 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple RTKit helper co-processor driver. + * + * Included at the end of rtkit-helper.c. The tests call the helper's own + * shared memory callbacks, its buffer inventory parser and its sleep + * callbacks directly. The RTKit AP power notice is a static stub, the RTKit + * state the helper reads is a zeroed struct apple_rtkit, and the ASC and SRAM + * registers are kernel memory. No hardware is touched. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "rtkit-internal.h" + +/* The RTKit power states the helper's checks look at (rtkit.c). */ +#define RTKH_TEST_PWR_IDLE 0x201 +#define RTKH_TEST_PWR_ON 0x20 + +/* An SRAM region well inside the 44 bit DMA mask. */ +#define RTKH_TEST_SRAM_START 0x210000000ULL +#define RTKH_TEST_SRAM_SIZE 0x10000 +#define RTKH_TEST_MAX_CALLS 8 + +struct rtkh_test { + struct apple_rtkit_helper helper; + struct apple_rtkit rtk; + struct device *dev; + struct resource sram; + void *sram_mem; + u32 *asc; + + struct device_node np; + struct property compat; + struct property inventory; + __be32 cells[2 * APPLE_RTKIT_HELPER_MAX_BUFFERS * APPLE_RTKIT_HELPER_BUFFER_CELLS]; + + /* The AP power notices the helper sent, and what each one returns. */ + unsigned int ncalls; + bool sent_on[RTKH_TEST_MAX_CALLS]; + int ret[RTKH_TEST_MAX_CALLS]; + + unsigned int saved_flags; + suspend_state_t saved_target; +}; + +static int rtkh_stub_send_ap_power(struct apple_rtkit_helper *helper, bool on) +{ + struct kunit *test = kunit_get_current_test(); + struct rtkh_test *ctx = test->priv; + unsigned int i = ctx->ncalls++; + int ret; + + KUNIT_ASSERT_PTR_EQ(test, helper, &ctx->helper); + KUNIT_ASSERT_LT(test, i, RTKH_TEST_MAX_CALLS); + ctx->sent_on[i] = on; + ret = ctx->ret[i]; + /* An answered notice moves RTKit's AP state, as its ACK handler does. */ + if (!ret) + ctx->rtk.ap_power_state = on ? RTKH_TEST_PWR_ON : RTKH_TEST_PWR_IDLE; + return ret; +} + +static void rtkh_set_run(struct rtkh_test *ctx, bool run) +{ + ctx->asc[APPLE_ASC_CPU_CONTROL / 4] = run ? APPLE_ASC_CPU_CONTROL_RUN : 0; +} + +static int rtkh_test_init(struct kunit *test) +{ + struct rtkh_test *ctx; + struct device *dev; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + dev = kunit_device_register(test, "rtkit-helper-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + ctx->dev = dev; + dev->coherent_dma_mask = DMA_BIT_MASK(44); + dev->dma_mask = &dev->coherent_dma_mask; + /* Coherent: dma-direct hands out pages of the linear map. */ + dev_set_dma_coherent(dev); + + ctx->asc = kunit_kzalloc(test, APPLE_ASC_CPU_CONTROL + 4, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->asc); + ctx->sram_mem = kunit_kzalloc(test, RTKH_TEST_SRAM_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->sram_mem); + ctx->sram = DEFINE_RES_MEM_NAMED(RTKH_TEST_SRAM_START, + RTKH_TEST_SRAM_SIZE, "sram"); + + ctx->rtk.dev = dev; + ctx->rtk.iop_power_state = RTKH_TEST_PWR_ON; + ctx->rtk.ap_power_state = RTKH_TEST_PWR_ON; + + ctx->helper.dev = dev; + ctx->helper.rtk = &ctx->rtk; + ctx->helper.asc_base = (__force void __iomem *)ctx->asc; + ctx->helper.sram = &ctx->sram; + ctx->helper.sram_base = (__force void __iomem *)ctx->sram_mem; + dev_set_drvdata(dev, &ctx->helper); + + ctx->saved_flags = pm_suspend_global_flags; + ctx->saved_target = pm_suspend_target_state; + pm_suspend_clear_flags(); + + kunit_activate_static_stub(test, apple_rtkit_helper_send_ap_power, + rtkh_stub_send_ap_power); + return 0; +} + +static void rtkh_test_exit(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + + /* The node is the test's: the device must not put it. */ + if (ctx->dev) + ctx->dev->of_node = NULL; + pm_suspend_global_flags = ctx->saved_flags; + pm_suspend_target_state = ctx->saved_target; +} + +/* shmem_setup / shmem_destroy */ + +static int rtkh_setup(struct rtkh_test *ctx, struct apple_rtkit_shmem *bfr, + u64 iova, size_t size) +{ + memset(bfr, 0, sizeof(*bfr)); + bfr->iova = iova; + bfr->size = size; + return apple_rtkit_helper_shmem_setup(&ctx->helper, bfr); +} + +static void rtkh_expect_refused(struct kunit *test, struct apple_rtkit_shmem *bfr, + int ret, int err) +{ + KUNIT_EXPECT_EQ(test, ret, err); + KUNIT_EXPECT_NULL(test, bfr->buffer); + KUNIT_EXPECT_NULL(test, bfr->iomem); + KUNIT_EXPECT_FALSE(test, bfr->is_mapped); +} + +static void rtkh_shmem_dma_alloc(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, 0, 0x4000), 0); + KUNIT_ASSERT_NOT_NULL(test, bfr.buffer); + KUNIT_EXPECT_NE(test, bfr.iova, 0); + KUNIT_EXPECT_EQ(test, bfr.iova & (PAGE_SIZE - 1), 0); + KUNIT_EXPECT_LE(test, bfr.iova + bfr.size - 1, DMA_BIT_MASK(44)); + KUNIT_EXPECT_NULL(test, bfr.iomem); + KUNIT_EXPECT_FALSE(test, bfr.is_mapped); + KUNIT_EXPECT_EQ(test, bfr.size, 0x4000); + memset(bfr.buffer, 0xa5, bfr.size); + + dma_free_coherent(ctx->dev, bfr.size, bfr.buffer, bfr.iova); +} + +static void rtkh_shmem_sram_inside(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START + 0x1000, + 0x2000), 0); + KUNIT_EXPECT_TRUE(test, bfr.is_mapped); + KUNIT_EXPECT_NULL(test, bfr.buffer); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)bfr.iomem, ctx->sram_mem + 0x1000); + KUNIT_EXPECT_EQ(test, bfr.iova, RTKH_TEST_SRAM_START + 0x1000); + KUNIT_EXPECT_EQ(test, bfr.size, 0x2000); +} + +static void rtkh_shmem_sram_whole(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, + RTKH_TEST_SRAM_SIZE), 0); + KUNIT_EXPECT_TRUE(test, bfr.is_mapped); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)bfr.iomem, ctx->sram_mem); +} + +/* Byte granular and unaligned: the SRAM offset is the IOVA's, not rounded. */ +static void rtkh_shmem_sram_unaligned_edges(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START + 0x123, + 0x10), 0); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)bfr.iomem, ctx->sram_mem + 0x123); + + /* The very last byte of the region. */ + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, ctx->sram.end, 1), 0); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)bfr.iomem, + ctx->sram_mem + RTKH_TEST_SRAM_SIZE - 1); + + /* Ends exactly at the end of the region. */ + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, ctx->sram.end + 1 - 0x801, + 0x801), 0); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)bfr.iomem, + ctx->sram_mem + RTKH_TEST_SRAM_SIZE - 0x801); +} + +static void rtkh_shmem_sram_outside(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + /* One byte past the end. */ + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, ctx->sram.end + 1 - 0x800, 0x801), + -EFAULT); + /* Straddles the end. */ + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, ctx->sram.end + 1 - 0x1000, 0x2000), + -EFAULT); + /* Starts one byte before the region. */ + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START - 1, 0x10), + -EFAULT); + /* Right after it. */ + rtkh_expect_refused(test, &bfr, rtkh_setup(ctx, &bfr, ctx->sram.end + 1, 1), + -EFAULT); + /* Somewhere else entirely, page aligned. */ + rtkh_expect_refused(test, &bfr, rtkh_setup(ctx, &bfr, 0x10000000, 0x4000), + -EFAULT); +} + +static void rtkh_shmem_sram_zero_size(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START + 0x1000, 0), + -EFAULT); +} + +static void rtkh_shmem_sram_huge(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, SZ_1G), + -EFAULT); + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, + RTKH_TEST_SRAM_SIZE + 1), + -EFAULT); +} + +/* iova + size wraps: the wrapped end lands back inside the region. */ +static void rtkh_shmem_sram_wrap(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START + 0x1000, + SIZE_MAX - 0x7ff), + -EFAULT); + rtkh_expect_refused(test, &bfr, rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, + SIZE_MAX), + -EFAULT); + rtkh_expect_refused(test, &bfr, rtkh_setup(ctx, &bfr, U64_MAX - 0xfff, 0x2000), + -EFAULT); +} + +static void rtkh_shmem_no_sram(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + ctx->helper.sram = NULL; + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, 0x1000), + -EFAULT); +} + +/* A strict adopted session refuses every new buffer, allocated or placed. */ +static void rtkh_shmem_adopted_strict(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + ctx->helper.adopted = true; + ctx->helper.strict_buffers = true; + rtkh_expect_refused(test, &bfr, rtkh_setup(ctx, &bfr, 0, 0x4000), -ENODATA); + KUNIT_EXPECT_EQ(test, bfr.iova, 0); + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, 0x1000), + -ENODATA); + + /* strict_buffers alone, without an adopted session, does not refuse. */ + ctx->helper.adopted = false; + KUNIT_EXPECT_EQ(test, rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, 0x1000), 0); +} + +/* A producer without an inventory (T8140) keeps mapping SRAM IOVAs. */ +static void rtkh_shmem_adopted_legacy(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + ctx->helper.adopted = true; + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START + 0x4000, + 0x4000), 0); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)bfr.iomem, ctx->sram_mem + 0x4000); + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, ctx->sram.end, 2), -EFAULT); +} + +/* Setting up the same request twice, and destroying twice, is harmless. */ +static void rtkh_shmem_double_setup_destroy(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem a, b; + + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &a, RTKH_TEST_SRAM_START + 0x2000, + 0x1000), 0); + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &b, RTKH_TEST_SRAM_START + 0x2000, + 0x1000), 0); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)a.iomem, (__force void *)b.iomem); + + /* Re-running setup on a mapped buffer re-maps it to the same place. */ + KUNIT_ASSERT_EQ(test, apple_rtkit_helper_shmem_setup(&ctx->helper, &a), 0); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)a.iomem, (__force void *)b.iomem); + + apple_rtkit_helper_shmem_destroy(&ctx->helper, &a); + apple_rtkit_helper_shmem_destroy(&ctx->helper, &a); + memset(&b, 0, sizeof(b)); + apple_rtkit_helper_shmem_destroy(&ctx->helper, &b); +} + +static void rtkh_ops(struct kunit *test) +{ + KUNIT_EXPECT_PTR_EQ(test, apple_rtkit_helper_ops.shmem_setup, + &apple_rtkit_helper_shmem_setup); + KUNIT_EXPECT_PTR_EQ(test, apple_rtkit_helper_ops.shmem_destroy, + &apple_rtkit_helper_shmem_destroy); + /* RTKit refuses ops with both setup flavours; the helper has one. */ + KUNIT_EXPECT_NULL(test, apple_rtkit_helper_ops.shmem_setup_ep); +} + +/* The buffer inventory of a handed over session (apple,rtkit-buffers) */ + +static void rtkh_node(struct rtkh_test *ctx, const char *compatible) +{ + ctx->np.full_name = "mtp"; + if (compatible) { + ctx->compat.name = "compatible"; + ctx->compat.value = (void *)compatible; + ctx->compat.length = strlen(compatible) + 1; + ctx->np.properties = &ctx->compat; + } + ctx->dev->of_node = &ctx->np; +} + +static void rtkh_inventory(struct rtkh_test *ctx, const u32 *cells, unsigned int n) +{ + unsigned int i; + + for (i = 0; i < n && i < ARRAY_SIZE(ctx->cells); i++) + ctx->cells[i] = cpu_to_be32(cells[i]); + ctx->inventory.name = "apple,rtkit-buffers"; + ctx->inventory.value = n ? ctx->cells : NULL; + ctx->inventory.length = n * sizeof(__be32); + ctx->inventory.next = ctx->np.properties; + ctx->np.properties = &ctx->inventory; +} + +#define RTKH_HI(a) ((u32)((u64)(a) >> 32)) +#define RTKH_LO(a) ((u32)(a)) + +static int rtkh_inherit(struct rtkh_test *ctx, struct apple_rtkit_inherited_buffer *b) +{ + memset(b, 0, sizeof(*b) * APPLE_RTKIT_HELPER_MAX_BUFFERS); + return apple_rtkit_helper_inherit_buffers(&ctx->helper, b); +} + +static void rtkh_inherit_no_inventory(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + + /* Older producers (T8140) hand over without an inventory. */ + rtkh_node(ctx, "apple,t8140-mtp"); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), 0); + + /* T8132 sessions must describe their buffers. */ + rtkh_node(ctx, "apple,t8132-mtp"); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), -EINVAL); +} + +static void rtkh_inherit_empty(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, NULL, 0); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), 0); +} + +static void rtkh_inherit_one_sram(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + const u64 iova = RTKH_TEST_SRAM_START + 0x1000; + const u32 cells[] = { 2, RTKH_HI(iova), RTKH_LO(iova), 0x2000, 0 }; + + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, cells, ARRAY_SIZE(cells)); + KUNIT_ASSERT_EQ(test, rtkh_inherit(ctx, b), 1); + KUNIT_EXPECT_EQ(test, b[0].endpoint, 2); + KUNIT_EXPECT_EQ(test, b[0].shmem.iova, iova); + KUNIT_EXPECT_EQ(test, b[0].shmem.size, 0x2000); + KUNIT_EXPECT_FALSE(test, b[0].shmem.is_mapped); + KUNIT_EXPECT_NULL(test, b[0].shmem.buffer); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)b[0].shmem.iomem, + ctx->sram_mem + 0x1000); +} + +static void rtkh_inherit_max(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + const u64 s = RTKH_TEST_SRAM_START; + const u32 cells[] = { + 1, RTKH_HI(s), RTKH_LO(s), 0x1000, 0, + 2, RTKH_HI(s + 0x1000), RTKH_LO(s + 0x1000), 0x1000, 1, + 4, RTKH_HI(s + 0x2000), RTKH_LO(s + 0x2000), 0x123, 0, + 8, RTKH_HI(s + 0xf000), RTKH_LO(s + 0xf000), 0x1000, 1, + }; + static const u8 eps[] = { 1, 2, 4, 8 }; + unsigned int i; + + rtkh_node(ctx, "apple,t8142-mtp"); + rtkh_inventory(ctx, cells, ARRAY_SIZE(cells)); + KUNIT_ASSERT_EQ(test, rtkh_inherit(ctx, b), 4); + for (i = 0; i < 4; i++) { + KUNIT_EXPECT_EQ(test, b[i].endpoint, eps[i]); + KUNIT_EXPECT_EQ(test, b[i].shmem.iova, ((u64)cells[i * 5 + 1] << 32) | + cells[i * 5 + 2]); + KUNIT_EXPECT_EQ(test, b[i].shmem.size, cells[i * 5 + 3]); + KUNIT_EXPECT_EQ(test, b[i].shmem.is_mapped, !!cells[i * 5 + 4]); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)b[i].shmem.iomem, + ctx->sram_mem + (b[i].shmem.iova - s)); + } +} + +static void rtkh_inherit_bad_count(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + u32 cells[ARRAY_SIZE(ctx->cells)]; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cells); i += 5) { + cells[i] = 1; + cells[i + 1] = RTKH_HI(RTKH_TEST_SRAM_START); + cells[i + 2] = RTKH_LO(RTKH_TEST_SRAM_START); + cells[i + 3] = 0x1000; + cells[i + 4] = 0; + } + + /* Five buffers: one more than the session may hold. */ + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, cells, 5 * (APPLE_RTKIT_HELPER_MAX_BUFFERS + 1)); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), -EINVAL); + + /* A partial tuple. */ + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, cells, 7); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), -EINVAL); + + /* Not even a whole cell. */ + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, cells, 1); + ctx->inventory.length = 3; + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), -EINVAL); +} + +static void rtkh_inherit_one_bad(struct kunit *test, u32 ep, u64 iova, u32 size, + u32 mapped) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + const u32 cells[] = { ep, RTKH_HI(iova), RTKH_LO(iova), size, mapped }; + + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, cells, ARRAY_SIZE(cells)); + KUNIT_EXPECT_EQ_MSG(test, rtkh_inherit(ctx, b), -EINVAL, + "ep %u iova %#llx size %#x mapped %u", ep, iova, size, + mapped); +} + +static void rtkh_inherit_bad_tuple(struct kunit *test) +{ + const u64 s = RTKH_TEST_SRAM_START; + + /* Not a system endpoint with a shared buffer. */ + rtkh_inherit_one_bad(test, 0, s, 0x1000, 0); + rtkh_inherit_one_bad(test, 3, s, 0x1000, 0); + rtkh_inherit_one_bad(test, 7, s, 0x1000, 0); + rtkh_inherit_one_bad(test, 0x20, s, 0x1000, 0); + /* No size. */ + rtkh_inherit_one_bad(test, 2, s, 0, 0); + /* is_mapped is a flag. */ + rtkh_inherit_one_bad(test, 2, s, 0x1000, 2); + /* Wraps past the top of the address space. */ + rtkh_inherit_one_bad(test, 2, U64_MAX - 0xfff, 0x2000, 0); + /* Above the 44 bit DMA mask. */ + rtkh_inherit_one_bad(test, 2, BIT_ULL(44), 0x1000, 0); + /* Outside SRAM, and no reserved memory region describes it. */ + rtkh_inherit_one_bad(test, 2, 0x10000000, 0x4000, 0); + rtkh_inherit_one_bad(test, 2, s + RTKH_TEST_SRAM_SIZE - 0x1000, 0x2000, 0); +} + +/* One bad tuple refuses the whole inventory. */ +static void rtkh_inherit_bad_second(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + const u64 s = RTKH_TEST_SRAM_START; + const u32 cells[] = { + 2, RTKH_HI(s), RTKH_LO(s), 0x1000, 0, + 4, RTKH_HI(s + 0x1000), RTKH_LO(s + 0x1000), 0x1000, 3, + }; + + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, cells, ARRAY_SIZE(cells)); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), -EINVAL); +} + +/* The 44 bit limit is inclusive: a buffer may end on its last byte. */ +static void rtkh_inherit_dma_mask_edge(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + const u64 top = DMA_BIT_MASK(44) + 1; + const u32 ok[] = { 8, RTKH_HI(top - 0x1000), RTKH_LO(top - 0x1000), 0x1000, 0 }; + const u32 over[] = { 8, RTKH_HI(top - 0x1000), RTKH_LO(top - 0x1000), 0x1001, 0 }; + + ctx->sram = DEFINE_RES_MEM_NAMED(top - RTKH_TEST_SRAM_SIZE, + RTKH_TEST_SRAM_SIZE + 0x1000, "sram"); + + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, ok, ARRAY_SIZE(ok)); + KUNIT_ASSERT_EQ(test, rtkh_inherit(ctx, b), 1); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)b[0].shmem.iomem, + ctx->sram_mem + RTKH_TEST_SRAM_SIZE - 0x1000); + + /* Inside this SRAM, but one byte past the DMA mask. */ + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, over, ARRAY_SIZE(over)); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), -EINVAL); +} + +/* Sleep: the AP power notices */ + +static void rtkh_expect_calls(struct kunit *test, const bool *on, unsigned int n) +{ + struct rtkh_test *ctx = test->priv; + unsigned int i; + + KUNIT_ASSERT_EQ(test, ctx->ncalls, n); + for (i = 0; i < n; i++) + KUNIT_EXPECT_EQ_MSG(test, ctx->sent_on[i], on[i], "notice %u", i); +} + +/* A firmware sleep sends one idle notice and one AP on, whichever callback. */ +static void rtkh_pm_fw_sleep_cycle(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true }; + + pm_set_suspend_via_firmware(); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_TRUE(test, ctx->helper.ap_idle); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend_late(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), 0); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 1); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); + apple_rtkit_helper_complete(dev); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_unanswered); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_pending); +} + +/* The M5 Pro's idle notice waits for .suspend_late. */ +static void rtkh_pm_idle_late(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true }; + + ctx->helper.idle_late = true; + pm_set_suspend_via_firmware(); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend_late(dev), 0); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 1); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), 0); + apple_rtkit_helper_complete(dev); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +/* A sleep the firmware does not finish tells the co-processor nothing. */ +static void rtkh_pm_no_fw_no_notice(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + + pm_suspend_target_state = PM_SUSPEND_MEM; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend_late(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); + apple_rtkit_helper_complete(dev); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_freeze(dev), 0); +} + +/* + * An unanswered idle notice fails .prepare; the PM notifier ends that sleep. + * Still no answer: nothing is sent, and the next sleep is refused without a + * second idle notice. + */ +static void rtkh_pm_unanswered_still_running(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false }; + + pm_set_suspend_via_firmware(); + ctx->ret[0] = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -ETIMEDOUT); + KUNIT_EXPECT_TRUE(test, ctx->helper.idle_unanswered); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); + + apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, PM_POST_SUSPEND, NULL); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_unanswered); + KUNIT_EXPECT_TRUE(test, ctx->helper.idle_pending); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); + + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -EBUSY); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), -EBUSY); + KUNIT_EXPECT_TRUE(test, ctx->helper.idle_pending); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +/* The answer came before the sleep ended: AP on goes out at its end. */ +static void rtkh_pm_unanswered_late_answer(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true, false }; + + pm_set_suspend_via_firmware(); + ctx->ret[0] = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -ETIMEDOUT); + ctx->rtk.ap_power_state = RTKH_TEST_PWR_IDLE; + + apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, PM_POST_SUSPEND, NULL); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_pending); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); + KUNIT_EXPECT_EQ(test, ctx->rtk.ap_power_state, RTKH_TEST_PWR_ON); + + /* The next sleep starts clean. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_TRUE(test, ctx->helper.ap_idle); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +/* A crashed co-processor is not running either: its idle is not pending. */ +static void rtkh_pm_unanswered_crashed(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + + pm_set_suspend_via_firmware(); + ctx->ret[0] = -ETIMEDOUT; + ctx->ret[1] = -ENODEV; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -ETIMEDOUT); + ctx->rtk.crashed = true; + apple_rtkit_helper_complete(dev); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_pending); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 2); + KUNIT_EXPECT_TRUE(test, ctx->sent_on[1]); + /* A failed AP on is not an unanswered idle notice. */ + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_unanswered); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); +} + +/* The answer came after the sleep ended: the next sleep sends AP on first. */ +static void rtkh_pm_pending_answered_later(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true, false, true }; + + pm_set_suspend_via_firmware(); + ctx->ret[0] = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -ETIMEDOUT); + apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, PM_POST_SUSPEND, NULL); + KUNIT_ASSERT_TRUE(test, ctx->helper.idle_pending); + + ctx->rtk.ap_power_state = RTKH_TEST_PWR_IDLE; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_pending); + KUNIT_EXPECT_TRUE(test, ctx->helper.ap_idle); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +static void rtkh_pm_pending_ap_on_fails(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true }; + + pm_set_suspend_via_firmware(); + ctx->ret[0] = -ETIMEDOUT; + ctx->ret[1] = -EIO; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -ETIMEDOUT); + apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, PM_POST_SUSPEND, NULL); + ctx->rtk.ap_power_state = RTKH_TEST_PWR_IDLE; + + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -EBUSY); + KUNIT_EXPECT_TRUE(test, ctx->helper.idle_pending); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +/* .complete and the PM notifier both end a sleep: only once. */ +static void rtkh_pm_complete_then_notify(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true }; + + ctx->helper.idle_late = true; + pm_set_suspend_via_firmware(); + ctx->ret[0] = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend_late(dev), -ETIMEDOUT); + ctx->rtk.ap_power_state = RTKH_TEST_PWR_IDLE; + apple_rtkit_helper_complete(dev); + apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, PM_POST_SUSPEND, NULL); + apple_rtkit_helper_complete(dev); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +static void rtkh_pm_notify_other_events(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + + ctx->helper.idle_unanswered = true; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, + PM_SUSPEND_PREPARE, NULL), + NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, + PM_POST_HIBERNATION, NULL), + NOTIFY_DONE); + KUNIT_EXPECT_TRUE(test, ctx->helper.idle_unanswered); + + ctx->helper.idle_unanswered = false; + apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, PM_POST_SUSPEND, NULL); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 0); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_pending); +} + +/* A failed AP on leaves nothing behind; the next sleep idles normally. */ +static void rtkh_pm_ap_on_fails(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true, false }; + + pm_set_suspend_via_firmware(); + ctx->ret[1] = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_unanswered); + apple_rtkit_helper_complete(dev); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +/* An adopted session survives s2idle only with its CPU still running. */ +static void rtkh_pm_adopted_s2idle(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + + ctx->helper.adopted = true; + pm_suspend_target_state = PM_SUSPEND_TO_IDLE; + + rtkh_set_run(ctx, true); + dev->power.wakeup_path = false; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), 0); + KUNIT_EXPECT_TRUE(test, device_awake_path(dev)); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); + + rtkh_set_run(ctx, false); + dev->power.wakeup_path = false; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), -EHOSTDOWN); + KUNIT_EXPECT_FALSE(test, device_awake_path(dev)); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), -EHOSTDOWN); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 0); +} + +static void rtkh_pm_adopted_refuses(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + + rtkh_set_run(ctx, true); + pm_suspend_target_state = PM_SUSPEND_MEM; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_freeze(dev), 0); + + ctx->helper.adopted = true; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), -EBUSY); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_freeze(dev), -EBUSY); + + /* Not adopted: a stopped CPU does not matter on resume. */ + ctx->helper.adopted = false; + rtkh_set_run(ctx, false); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); +} + +static void rtkh_preserves_input(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + + KUNIT_EXPECT_FALSE(test, apple_rtkit_helper_preserves_input(ctx->dev)); + ctx->helper.preserved = true; + KUNIT_EXPECT_TRUE(test, apple_rtkit_helper_preserves_input(ctx->dev)); + dev_set_drvdata(ctx->dev, NULL); + KUNIT_EXPECT_FALSE(test, apple_rtkit_helper_preserves_input(ctx->dev)); + dev_set_drvdata(ctx->dev, &ctx->helper); +} + +static void rtkh_pm_register(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, apple_rtkit_helper_pm_register(&ctx->helper), 0); + KUNIT_EXPECT_PTR_EQ(test, ctx->helper.pm_nb.notifier_call, + &apple_rtkit_helper_pm_notify); + /* The device's devres unregisters it when the test ends. */ +} + +static struct kunit_case apple_rtkit_helper_test_cases[] = { + KUNIT_CASE(rtkh_ops), + KUNIT_CASE(rtkh_shmem_dma_alloc), + KUNIT_CASE(rtkh_shmem_sram_inside), + KUNIT_CASE(rtkh_shmem_sram_whole), + KUNIT_CASE(rtkh_shmem_sram_unaligned_edges), + KUNIT_CASE(rtkh_shmem_sram_outside), + KUNIT_CASE(rtkh_shmem_sram_zero_size), + KUNIT_CASE(rtkh_shmem_sram_huge), + KUNIT_CASE(rtkh_shmem_sram_wrap), + KUNIT_CASE(rtkh_shmem_no_sram), + KUNIT_CASE(rtkh_shmem_adopted_strict), + KUNIT_CASE(rtkh_shmem_adopted_legacy), + KUNIT_CASE(rtkh_shmem_double_setup_destroy), + KUNIT_CASE(rtkh_inherit_no_inventory), + KUNIT_CASE(rtkh_inherit_empty), + KUNIT_CASE(rtkh_inherit_one_sram), + KUNIT_CASE(rtkh_inherit_max), + KUNIT_CASE(rtkh_inherit_bad_count), + KUNIT_CASE(rtkh_inherit_bad_tuple), + KUNIT_CASE(rtkh_inherit_bad_second), + KUNIT_CASE(rtkh_inherit_dma_mask_edge), + KUNIT_CASE(rtkh_pm_fw_sleep_cycle), + KUNIT_CASE(rtkh_pm_idle_late), + KUNIT_CASE(rtkh_pm_no_fw_no_notice), + KUNIT_CASE(rtkh_pm_unanswered_still_running), + KUNIT_CASE(rtkh_pm_unanswered_late_answer), + KUNIT_CASE(rtkh_pm_unanswered_crashed), + KUNIT_CASE(rtkh_pm_pending_answered_later), + KUNIT_CASE(rtkh_pm_pending_ap_on_fails), + KUNIT_CASE(rtkh_pm_complete_then_notify), + KUNIT_CASE(rtkh_pm_notify_other_events), + KUNIT_CASE(rtkh_pm_ap_on_fails), + KUNIT_CASE(rtkh_pm_adopted_s2idle), + KUNIT_CASE(rtkh_pm_adopted_refuses), + KUNIT_CASE(rtkh_preserves_input), + KUNIT_CASE(rtkh_pm_register), + {} +}; + +static struct kunit_suite apple_rtkit_helper_test_suite = { + .name = "apple-rtkit-helper", + .init = rtkh_test_init, + .exit = rtkh_test_exit, + .test_cases = apple_rtkit_helper_test_cases, +}; + +kunit_test_suite(apple_rtkit_helper_test_suite); diff --git a/drivers/soc/apple/rtkit-helper.c b/drivers/soc/apple/rtkit-helper.c index 4db46fe2970db3..2d0871dc5af5e5 100644 --- a/drivers/soc/apple/rtkit-helper.c +++ b/drivers/soc/apple/rtkit-helper.c @@ -20,6 +20,10 @@ #include #include +#if IS_ENABLED(CONFIG_APPLE_RTKIT_HELPER_KUNIT_TEST) +#include +#endif + #define APPLE_ASC_CPU_CONTROL 0x44 #define APPLE_ASC_CPU_CONTROL_RUN BIT(4) @@ -185,6 +189,20 @@ static bool apple_rtkit_helper_reserved(struct device_node *np, return false; } +/* + * The MTPs whose live handoff uses the retained form: the boot loader always + * publishes the buffer inventory with the session, and no buffer may be + * allocated after adoption. That form belongs to the MTP firmware, so it is + * keyed on the MTP's compatible: every T8132 MTP and every T6040/T6041 MTP + * (both use apple,t6041-mtp), whichever board it sits in. The boot loader + * picks the form by the same compatibles. + */ +static bool apple_rtkit_helper_retained_mtp(struct device_node *np) +{ + return of_device_is_compatible(np, "apple,t8132-mtp") || + of_device_is_compatible(np, "apple,t6041-mtp"); +} + static int apple_rtkit_helper_inherit_buffers( struct apple_rtkit_helper *helper, struct apple_rtkit_inherited_buffer *buffers) @@ -197,9 +215,7 @@ static int apple_rtkit_helper_inherit_buffers( /* T8140 producers predating the buffer inventory remain compatible. */ inventory = of_find_property(np, "apple,rtkit-buffers", &length); if (!inventory) { - if (of_device_is_compatible(np, "apple,t8132-mtp") || - (of_machine_is_compatible("apple,j614s") && - of_device_is_compatible(np, "apple,t6041-mtp"))) + if (apple_rtkit_helper_retained_mtp(np)) return -EINVAL; return 0; } @@ -293,8 +309,7 @@ static int apple_rtkit_helper_probe(struct platform_device *pdev) return dev_err_probe(dev, count, "Invalid inherited RTKit buffers\n"); if ((apple_t8132_live_mtp() && of_device_is_compatible(dev->of_node, "apple,t8132-mtp")) || - (of_machine_is_compatible("apple,j614s") && - of_device_is_compatible(dev->of_node, "apple,t6041-mtp")) || + of_device_is_compatible(dev->of_node, "apple,t6041-mtp") || of_device_is_compatible(dev->of_node, "apple,t8142-mtp")) helper->preserved = true; } @@ -341,9 +356,7 @@ static int apple_rtkit_helper_probe(struct platform_device *pdev) */ helper->adopted = true; helper->strict_buffers = count > 0 || - of_device_is_compatible(dev->of_node, "apple,t8132-mtp") || - (of_machine_is_compatible("apple,j614s") && - of_device_is_compatible(dev->of_node, "apple,t6041-mtp")); + apple_rtkit_helper_retained_mtp(dev->of_node); helper->rtk = apple_rtkit_init_adopted_with_buffers( dev, helper, NULL, 0, &apple_rtkit_helper_ops, buffers, count); if (IS_ERR(helper->rtk)) @@ -398,9 +411,18 @@ static void apple_rtkit_helper_remove(struct platform_device *pdev) writel_relaxed(0, helper->asc_base + APPLE_ASC_CPU_CONTROL); } +/* The AP power notice itself: the KUnit test replaces it with a static stub. */ +static int apple_rtkit_helper_send_ap_power(struct apple_rtkit_helper *helper, bool on) +{ +#if IS_ENABLED(CONFIG_APPLE_RTKIT_HELPER_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(apple_rtkit_helper_send_ap_power, helper, on); +#endif + return apple_rtkit_ap_power(helper->rtk, on); +} + static int apple_rtkit_helper_ap_power(struct apple_rtkit_helper *helper, bool on) { - int ret = apple_rtkit_ap_power(helper->rtk, on); + int ret = apple_rtkit_helper_send_ap_power(helper, on); if (ret) dev_err(helper->dev, "AP power notice (%s) not answered: %d\n", @@ -433,7 +455,7 @@ static int apple_rtkit_helper_ap_idle(struct apple_rtkit_helper *helper) } helper->idle_pending = false; dev_info(helper->dev, "the last AP idle notice was answered late, sending AP on first\n"); - if (apple_rtkit_ap_power(helper->rtk, true)) { + if (apple_rtkit_helper_send_ap_power(helper, true)) { dev_err(helper->dev, "AP on after the late answer not answered: no sleep\n"); helper->idle_pending = true; return -EBUSY; @@ -615,3 +637,7 @@ module_platform_driver(apple_rtkit_helper_driver); MODULE_AUTHOR("Hector Martin "); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple RTKit helper driver"); + +#if IS_ENABLED(CONFIG_APPLE_RTKIT_HELPER_KUNIT_TEST) +#include "rtkit-helper-test.c" +#endif diff --git a/drivers/soc/apple/rtkit-helper.kunitconfig b/drivers/soc/apple/rtkit-helper.kunitconfig new file mode 100644 index 00000000000000..2e7ff2826502a6 --- /dev/null +++ b/drivers/soc/apple/rtkit-helper.kunitconfig @@ -0,0 +1,10 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_ARM64_16K_PAGES=y +CONFIG_PM=y +CONFIG_SUSPEND=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_APPLE_RTKIT_HELPER=y +CONFIG_APPLE_RTKIT_HELPER_KUNIT_TEST=y diff --git a/drivers/soc/apple/rtkit-test.c b/drivers/soc/apple/rtkit-test.c new file mode 100644 index 00000000000000..aba873abbe37c1 --- /dev/null +++ b/drivers/soc/apple/rtkit-test.c @@ -0,0 +1,1035 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple RTKit IPC library. Included by rtkit.c. + * + * The tests drive the receive handlers with messages a co-processor would + * send and check the replies. apple_rtkit_send_message() is redirected to a + * static stub just before the mailbox write, so its crashed and running + * checks still run; shared buffers come from a fake shmem_setup_ep. No + * mailbox, IOMMU or MMIO is touched. + */ +#include +#include +#include + +#define RTK_TEST_MAX_SENT 32 +#define RTK_TEST_IOVA_BASE 0x10000000 + +struct rtk_test_msg { + u8 ep; + u64 msg; +}; + +struct rtk_test_ctx { + struct kunit *test; + struct apple_rtkit *rtk; + struct apple_rtkit_ops ops; + + struct rtk_test_msg sent[RTK_TEST_MAX_SENT]; + unsigned int n_sent; + + unsigned int n_setup; + u8 setup_ep; + struct apple_rtkit_shmem setup_req; + int setup_ret; + dma_addr_t next_iova; + /* Written to each new buffer, as a log the firmware already wrote. */ + const void *prefill; + size_t prefill_len; + + unsigned int n_crashed; + size_t crashed_size; + u32 crashed_fourcc; + + unsigned int n_syslog; + char syslog_ctx[24]; + char syslog_msg[64]; + + unsigned int n_recv; + u8 recv_ep; + u64 recv_msg; +}; + +static int rtk_test_send(struct apple_rtkit *rtk, u8 ep, u64 message, + struct completion *completion, bool atomic) +{ + struct rtk_test_ctx *ctx = rtk->cookie; + + if (ctx->n_sent < RTK_TEST_MAX_SENT) { + ctx->sent[ctx->n_sent].ep = ep; + ctx->sent[ctx->n_sent].msg = message; + } + ctx->n_sent++; + return 0; +} + +static int rtk_test_shmem_setup(void *cookie, u8 ep, struct apple_rtkit_shmem *bfr) +{ + struct rtk_test_ctx *ctx = cookie; + + ctx->n_setup++; + ctx->setup_ep = ep; + ctx->setup_req = *bfr; + if (ctx->setup_ret) + return ctx->setup_ret; + + bfr->buffer = kunit_kzalloc(ctx->test, bfr->size, GFP_KERNEL); + if (!bfr->buffer) + return -ENOMEM; + if (ctx->prefill) + memcpy(bfr->buffer, ctx->prefill, min(ctx->prefill_len, bfr->size)); + if (bfr->iova) { + /* A buffer the co-processor placed at its own address. */ + bfr->is_mapped = true; + } else { + bfr->iova = ctx->next_iova; + ctx->next_iova += SZ_1M; + } + return 0; +} + +static void rtk_test_shmem_destroy(void *cookie, struct apple_rtkit_shmem *bfr) +{ +} + +static void rtk_test_crashed(void *cookie, const void *crashlog, size_t size) +{ + struct rtk_test_ctx *ctx = cookie; + + ctx->n_crashed++; + ctx->crashed_size = size; + ctx->crashed_fourcc = 0; + if (crashlog && size >= sizeof(u32)) + memcpy(&ctx->crashed_fourcc, crashlog, sizeof(u32)); +} + +static bool rtk_test_syslog_is_debug(void *cookie, const char *context, + const char *message) +{ + struct rtk_test_ctx *ctx = cookie; + + ctx->n_syslog++; + strscpy(ctx->syslog_ctx, context, sizeof(ctx->syslog_ctx)); + strscpy(ctx->syslog_msg, message, sizeof(ctx->syslog_msg)); + return true; +} + +static void rtk_test_recv(void *cookie, u8 endpoint, u64 message) +{ + struct rtk_test_ctx *ctx = cookie; + + ctx->n_recv++; + ctx->recv_ep = endpoint; + ctx->recv_msg = message; +} + +static int rtk_test_init(struct kunit *test) +{ + struct rtk_test_ctx *ctx; + struct apple_rtkit *rtk; + struct device *dev; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + rtk = kunit_kzalloc(test, sizeof(*rtk), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, rtk); + dev = kunit_device_register(test, "apple-rtkit-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + + ctx->test = test; + ctx->rtk = rtk; + ctx->next_iova = RTK_TEST_IOVA_BASE; + ctx->ops.crashed = rtk_test_crashed; + ctx->ops.recv_message = rtk_test_recv; + ctx->ops.shmem_setup_ep = rtk_test_shmem_setup; + ctx->ops.shmem_destroy = rtk_test_shmem_destroy; + ctx->ops.syslog_is_debug = rtk_test_syslog_is_debug; + + rtk->dev = dev; + rtk->cookie = ctx; + rtk->ops = &ctx->ops; + rtk->handshake_timeout_ms = APPLE_RTKIT_HANDSHAKE_TIMEOUT_MS; + init_completion(&rtk->epmap_completion); + init_completion(&rtk->coreanalytics_completion); + init_completion(&rtk->iop_pwr_ack_completion); + init_completion(&rtk->ap_pwr_ack_completion); + init_completion(&rtk->strict_idle_done); + INIT_KFIFO(rtk->sync_ack_fifo); + INIT_KFIFO(rtk->m5_saved.deferred); + INIT_DELAYED_WORK(&rtk->crashlog_late_work, apple_rtkit_crashlog_late); + rtk->wq = alloc_ordered_workqueue("apple-rtkit-test", 0); + KUNIT_ASSERT_NOT_NULL(test, rtk->wq); + + kunit_activate_static_stub(test, apple_rtkit_send_message, rtk_test_send); + test->priv = ctx; + return 0; +} + +static void rtk_test_exit(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + cancel_delayed_work_sync(&rtk->crashlog_late_work); + destroy_workqueue(rtk->wq); + kfree(rtk->syslog_msg_buffer); +} + +static u64 rtk_test_mgmt(u8 type, u64 payload) +{ + return FIELD_PREP(APPLE_RTKIT_MGMT_TYPE, type) | payload; +} + +static u64 rtk_test_hello(unsigned int min_ver, unsigned int max_ver) +{ + return rtk_test_mgmt(APPLE_RTKIT_MGMT_HELLO, + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MINVER, min_ver) | + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MAXVER, max_ver)); +} + +static u64 rtk_test_epmap(u32 base, u32 bitmap, bool last) +{ + return rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP, + FIELD_PREP(APPLE_RTKIT_MGMT_EPMAP_BASE, base) | + FIELD_PREP(APPLE_RTKIT_MGMT_EPMAP_BITMAP, bitmap) | + (last ? APPLE_RTKIT_MGMT_EPMAP_LAST : 0)); +} + +static u64 rtk_test_startep(u8 ep) +{ + return rtk_test_mgmt(APPLE_RTKIT_MGMT_STARTEP, + FIELD_PREP(APPLE_RTKIT_MGMT_STARTEP_EP, ep) | + APPLE_RTKIT_MGMT_STARTEP_FLAG); +} + +static u64 rtk_test_buffer_request(u8 type, size_t size, u64 iova) +{ + return FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, type) | + FIELD_PREP(APPLE_RTKIT_BUFFER_REQUEST_SIZE, size >> 12) | + FIELD_PREP(APPLE_RTKIT_BUFFER_REQUEST_IOVA, iova); +} + +static void rtk_test_expect_sent(struct kunit *test, unsigned int i, u8 ep, u64 msg) +{ + struct rtk_test_ctx *ctx = test->priv; + + KUNIT_ASSERT_LT(test, i, ctx->n_sent); + KUNIT_ASSERT_LT(test, i, RTK_TEST_MAX_SENT); + KUNIT_EXPECT_EQ(test, ctx->sent[i].ep, ep); + KUNIT_EXPECT_EQ(test, ctx->sent[i].msg, msg); +} + +static void rtk_test_hello_accepts_supported(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 reply12 = rtk_test_mgmt(APPLE_RTKIT_MGMT_HELLO_REPLY, + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MINVER, 12) | + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MAXVER, 12)); + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(11, 12), false, 0); + KUNIT_EXPECT_EQ(test, rtk->version, 12); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, reply12); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->epmap_completion)); + + /* A newer remote maximum settles on the highest version supported here. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(11, 14), false, 0); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_MGMT, reply12); + + /* Both ends of the supported range are accepted alone. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(12, 12), false, 0); + rtk_test_expect_sent(test, 2, APPLE_RTKIT_EP_MGMT, reply12); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(1, 11), false, 0); + KUNIT_EXPECT_EQ(test, rtk->version, 11); + rtk_test_expect_sent(test, 3, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_HELLO_REPLY, + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MINVER, 11) | + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MAXVER, 11))); + KUNIT_EXPECT_EQ(test, rtk->boot_result, 0); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->epmap_completion)); +} + +static void rtk_test_hello_rejects_unsupported(struct kunit *test) +{ + static const struct { unsigned int min, max; } bad[] = { + { 13, 14 }, /* minimum too new */ + { 9, 10 }, /* maximum too old */ + }; + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + int i; + + for (i = 0; i < ARRAY_SIZE(bad); i++) { + reinit_completion(&rtk->epmap_completion); + rtk->boot_result = 0; + rtk->version = 0; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_hello(bad[i].min, bad[i].max), false, 0); + KUNIT_EXPECT_EQ_MSG(test, rtk->boot_result, -EINVAL, "range %u..%u", + bad[i].min, bad[i].max); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); + KUNIT_EXPECT_EQ(test, rtk->version, 0); + } + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_hello_client_version(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + ctx->ops.protocol_version = 11; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(11, 12), false, 0); + KUNIT_EXPECT_EQ(test, rtk->version, 11); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_HELLO_REPLY, + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MINVER, 11) | + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MAXVER, 11))); + + /* The client's exact version outside the remote range aborts the boot. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(12, 12), false, 0); + KUNIT_EXPECT_EQ(test, rtk->boot_result, -EINVAL); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); +} + +static void rtk_test_epmap_starts_system_endpoints(struct kunit *test) +{ + static const u8 started[] = { 1, 2, 3, 4, 8, 0xa }; + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + /* mgmt, crashlog, syslog, debug, ioreport, 5 (unknown), 7, oslog, tracekit */ + u32 bitmap = BIT(0) | BIT(1) | BIT(2) | BIT(3) | BIT(4) | BIT(5) | + BIT(7) | BIT(8) | BIT(0xa); + int i; + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_epmap(0, bitmap, true), + false, 0); + + for (i = 0; i < 32; i++) + KUNIT_EXPECT_EQ_MSG(test, apple_rtkit_has_endpoint(rtk, i), + !!(bitmap & BIT(i)), "endpoint %d", i); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1 + ARRAY_SIZE(started)); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + APPLE_RTKIT_MGMT_EPMAP_LAST)); + for (i = 0; i < ARRAY_SIZE(started); i++) { + rtk_test_expect_sent(test, 1 + i, APPLE_RTKIT_EP_MGMT, + rtk_test_startep(started[i])); + KUNIT_EXPECT_TRUE(test, apple_rtkit_endpoint_started(rtk, started[i])); + } + /* Neither management, an unknown system endpoint nor CoreAnalytics. */ + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 0)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 5)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 7)); + KUNIT_EXPECT_EQ(test, rtk->boot_result, 0); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); +} + +static void rtk_test_epmap_multipart(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(0, BIT(0) | BIT(2), false), false, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + APPLE_RTKIT_MGMT_EPMAP_REPLY_MORE)); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->epmap_completion)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 2)); + + /* The second part: endpoints 0x20 and 0x37 are application endpoints. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(1, BIT(0) | BIT(0x17), true), false, 0); + KUNIT_EXPECT_TRUE(test, apple_rtkit_has_endpoint(rtk, 0x20)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_has_endpoint(rtk, 0x37)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_has_endpoint(rtk, 1)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_has_endpoint(rtk, 0x17)); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 3); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + FIELD_PREP(APPLE_RTKIT_MGMT_EPMAP_BASE, 1) | + APPLE_RTKIT_MGMT_EPMAP_LAST)); + /* Only system endpoints are started by RTKit itself. */ + rtk_test_expect_sent(test, 2, APPLE_RTKIT_EP_MGMT, rtk_test_startep(2)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 0x20)); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); +} + +static void rtk_test_epmap_flags(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + ctx->ops.flags = APPLE_RTKIT_NEEDS_COREANALYTICS | APPLE_RTKIT_EARLY_CRASHLOG; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(0, BIT(0) | BIT(1) | BIT(7), true), false, 0); + + /* The crash log is started before the map is acknowledged, and only once. */ + KUNIT_ASSERT_EQ(test, ctx->n_sent, 3); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, rtk_test_startep(1)); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + APPLE_RTKIT_MGMT_EPMAP_LAST)); + rtk_test_expect_sent(test, 2, APPLE_RTKIT_EP_MGMT, rtk_test_startep(7)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_endpoint_started(rtk, 7)); +} + +static void rtk_test_epmap_retained(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + rtk->retained_wake = true; + set_bit(1, rtk->started); + set_bit(2, rtk->started); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(0, BIT(0) | BIT(1) | BIT(2) | BIT(4), true), + false, 0); + /* The started endpoints are echoed and nothing is started again. */ + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + BIT(1) | BIT(2) | APPLE_RTKIT_MGMT_EPMAP_LAST)); + KUNIT_EXPECT_EQ(test, rtk->boot_result, 0); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); + + /* A started endpoint missing from the map fails the wake. */ + reinit_completion(&rtk->epmap_completion); + set_bit(4 + 32, rtk->started); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(1, BIT(0), true), false, 0); + KUNIT_EXPECT_EQ(test, rtk->boot_result, -EPROTO); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); +} + +static void rtk_test_power_acks(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + KUNIT_EXPECT_FALSE(test, apple_rtkit_is_running(rtk)); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK, + APPLE_RTKIT_PWR_STATE_ON), false, 0); + KUNIT_EXPECT_EQ(test, rtk->iop_power_state, APPLE_RTKIT_PWR_STATE_ON); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->iop_pwr_ack_completion)); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->ap_pwr_ack_completion)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_is_running(rtk)); + + /* Bits above the 16-bit state field are not part of the state. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_SET_AP_PWR_STATE_ACK, + BIT_ULL(40) | APPLE_RTKIT_PWR_STATE_ON), + false, 0); + KUNIT_EXPECT_EQ(test, rtk->ap_power_state, APPLE_RTKIT_PWR_STATE_ON); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->ap_pwr_ack_completion)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_is_running(rtk)); + + rtk->crashed = true; + KUNIT_EXPECT_FALSE(test, apple_rtkit_is_running(rtk)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_is_crashed(rtk)); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_retained_quiesced(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 quiesced = rtk_test_mgmt(APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK, + APPLE_RTKIT_PWR_STATE_QUIESCED); + + rtk->retained_wake = true; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, quiesced, false, 0); + /* One ON request, and still waiting for ON. */ + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE, + APPLE_RTKIT_PWR_STATE_ON)); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->iop_pwr_ack_completion)); + + /* A second QUIESCED is not asked again: it fails the wake. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, quiesced, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); + KUNIT_EXPECT_EQ(test, rtk->boot_result, -EPROTO); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->iop_pwr_ack_completion)); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); +} + +static void rtk_test_idle_notify(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + rtk->strict_idle_waiting = true; + rtk->iop_power_state = APPLE_RTKIT_PWR_STATE_IDLE; + rtk->ap_power_state = APPLE_RTKIT_PWR_STATE_IDLE; + /* A nonzero argument is not the idle notification. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_IDLE_NOTIFY, 1), false, 0); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->strict_idle_done)); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_IDLE_NOTIFY, 0), false, 0); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->strict_idle_done)); + + /* Unknown management messages are dropped without a reply. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_mgmt(0x3f, 0), false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_send_checks(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + set_bit(0x20, rtk->endpoints); + /* Application endpoints need a running co-processor. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_send_message(rtk, 0x20, 0x1234, NULL, false), + -EINVAL); + KUNIT_EXPECT_EQ(test, apple_rtkit_start_ep(rtk, 0x20), -EINVAL); + /* An undiscovered endpoint cannot be started. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_start_ep(rtk, 2), -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); + + rtk->iop_power_state = APPLE_RTKIT_PWR_STATE_ON; + rtk->ap_power_state = APPLE_RTKIT_PWR_STATE_ON; + KUNIT_EXPECT_EQ(test, apple_rtkit_send_message(rtk, 0x20, 0x1234, NULL, false), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_start_ep(rtk, 0x20), 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + rtk_test_expect_sent(test, 0, 0x20, 0x1234); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_MGMT, rtk_test_startep(0x20)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_endpoint_started(rtk, 0x20)); + + /* Nothing is sent to a crashed co-processor, not even management. */ + rtk->crashed = true; + KUNIT_EXPECT_EQ(test, apple_rtkit_send_message(rtk, 0, 0, NULL, false), -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 2); +} + +static void rtk_test_app_endpoint_dispatch(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + apple_rtkit_rx_dispatch(rtk, 0x37, 0xdeadbeefcafeull, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_recv, 1); + KUNIT_EXPECT_EQ(test, ctx->recv_ep, 0x37); + KUNIT_EXPECT_EQ(test, ctx->recv_msg, 0xdeadbeefcafeull); + + /* Nothing is delivered once teardown has started. */ + rtk->shutting_down = true; + apple_rtkit_rx_dispatch(rtk, 0x37, 1, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_recv, 1); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_buffer_reply(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = rtk_test_buffer_request(APPLE_RTKIT_BUFFER_REQUEST, SZ_8K, 0); + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, req, false, 0); + KUNIT_ASSERT_EQ(test, ctx->n_setup, 1); + KUNIT_EXPECT_EQ(test, ctx->setup_ep, APPLE_RTKIT_EP_IOREPORT); + KUNIT_EXPECT_EQ(test, ctx->setup_req.size, SZ_8K); + KUNIT_EXPECT_EQ(test, ctx->setup_req.iova, 0); + KUNIT_EXPECT_EQ(test, rtk->ioreport_buffer.size, SZ_8K); + KUNIT_EXPECT_EQ(test, rtk->ioreport_buffer.iova, RTK_TEST_IOVA_BASE); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_IOREPORT, + rtk_test_buffer_request(APPLE_RTKIT_BUFFER_REQUEST, SZ_8K, + RTK_TEST_IOVA_BASE)); + + /* An identical request is answered again without a new buffer. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 1); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + KUNIT_EXPECT_EQ(test, ctx->sent[1].msg, ctx->sent[0].msg); + + /* A changed geometry is refused while the buffer is live. */ + req = rtk_test_buffer_request(1, SZ_16K, 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_common_rx_get_buffer(rtk, &rtk->ioreport_buffer, + APPLE_RTKIT_EP_IOREPORT, req), + -EBUSY); + KUNIT_EXPECT_EQ(test, rtk->ioreport_buffer.size, SZ_8K); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 1); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 2); + + /* ioreport's two unknown notifications are echoed, others dropped. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0x8) | 0x55, false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0xc), false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0x9), false, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 4); + rtk_test_expect_sent(test, 2, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0x8) | 0x55); + rtk_test_expect_sent(test, 3, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0xc)); +} + +static void rtk_test_buffer_request_invalid(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req; + + /* A zero size is never set up. */ + req = rtk_test_buffer_request(1, 0, 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_common_rx_get_buffer(rtk, &rtk->ioreport_buffer, + APPLE_RTKIT_EP_IOREPORT, req), + -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 0); + + /* A failed setup leaves no buffer behind and sends no reply. */ + ctx->setup_ret = -ENOMEM; + req = rtk_test_buffer_request(1, SZ_4K, 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_common_rx_get_buffer(rtk, &rtk->syslog_buffer, + APPLE_RTKIT_EP_SYSLOG, req), + -ENOMEM); + KUNIT_EXPECT_EQ(test, rtk->syslog_buffer.size, 0); + ctx->setup_ret = 0; + + /* Without a setup callback, a placed buffer cannot be mapped. */ + ctx->ops.shmem_setup_ep = NULL; + req = rtk_test_buffer_request(1, SZ_4K, 0x8000); + KUNIT_EXPECT_EQ(test, apple_rtkit_common_rx_get_buffer(rtk, &rtk->ioreport_buffer, + APPLE_RTKIT_EP_IOREPORT, req), + -EINVAL); + KUNIT_EXPECT_EQ(test, rtk->ioreport_buffer.size, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_placed_buffers(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = rtk_test_buffer_request(1, SZ_16K, 0xabc000); + + /* A placed buffer is acknowledged with its request, unchanged. */ + ctx->ops.flags = APPLE_RTKIT_COPROC_PLACES_BUFFERS; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->setup_req.iova, 0xabc000); + KUNIT_EXPECT_EQ(test, ctx->setup_req.size, SZ_16K); + KUNIT_EXPECT_TRUE(test, rtk->ioreport_buffer.is_mapped); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_IOREPORT, req); + + /* A firmware-owned log buffer is taken as it is, unmapped and unanswered. */ + ctx->ops.flags = APPLE_RTKIT_FIRMWARE_OWNED_LOGS; + req = rtk_test_buffer_request(1, SZ_8K, 0xdef000); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 1); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); + KUNIT_EXPECT_TRUE(test, rtk->syslog_buffer.is_mapped); + KUNIT_EXPECT_NULL(test, rtk->syslog_buffer.buffer); + KUNIT_EXPECT_EQ(test, rtk->syslog_buffer.iova, 0xdef000); + KUNIT_EXPECT_EQ(test, rtk->syslog_buffer.size, SZ_8K); + + /* Its records are still acknowledged, without being read. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG), + false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 2); + KUNIT_EXPECT_EQ(test, ctx->n_syslog, 0); +} + +static void rtk_test_oslog_buffer_request(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = FIELD_PREP(APPLE_RTKIT_OSLOG_TYPE, APPLE_RTKIT_OSLOG_BUFFER_REQUEST) | + FIELD_PREP(APPLE_RTKIT_OSLOG_SIZE, SZ_16K); + + /* oslog carries its size unshifted and its IOVA in 4 KiB pages. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_OSLOG, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->setup_ep, APPLE_RTKIT_EP_OSLOG); + KUNIT_EXPECT_EQ(test, ctx->setup_req.size, SZ_16K); + KUNIT_EXPECT_EQ(test, ctx->setup_req.iova, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_OSLOG, + FIELD_PREP(APPLE_RTKIT_OSLOG_TYPE, APPLE_RTKIT_OSLOG_BUFFER_REQUEST) | + FIELD_PREP(APPLE_RTKIT_OSLOG_SIZE, SZ_16K) | + FIELD_PREP(APPLE_RTKIT_OSLOG_IOVA, RTK_TEST_IOVA_BASE >> 12)); + + apple_rtkit_free_buffer(rtk, &rtk->oslog_buffer); + req = FIELD_PREP(APPLE_RTKIT_OSLOG_TYPE, APPLE_RTKIT_OSLOG_BUFFER_REQUEST) | + FIELD_PREP(APPLE_RTKIT_OSLOG_SIZE, SZ_8K) | + FIELD_PREP(APPLE_RTKIT_OSLOG_IOVA, 0x12345); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_OSLOG, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->setup_req.size, SZ_8K); + KUNIT_EXPECT_EQ(test, ctx->setup_req.iova, 0x12345000); + KUNIT_EXPECT_EQ(test, rtk->oslog_buffer.iova, 0x12345000); +} + +/* Builds a syslog ring of four entries with a 0x40-byte message each. */ +static void rtk_test_syslog_setup(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + size_t entry_size = 0x20 + 0x40; + u8 *entry; + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, + rtk_test_buffer_request(1, SZ_8K, 0), false, 0); + KUNIT_ASSERT_NOT_NULL(test, rtk->syslog_buffer.buffer); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_INIT) | + FIELD_PREP(APPLE_RTKIT_SYSLOG_N_ENTRIES, 4) | + FIELD_PREP(APPLE_RTKIT_SYSLOG_MSG_SIZE, 0x40), false, 0); + KUNIT_ASSERT_NOT_NULL(test, rtk->syslog_msg_buffer); + KUNIT_ASSERT_EQ(test, rtk->syslog_n_entries, 4); + KUNIT_ASSERT_EQ(test, rtk->syslog_msg_size, 0x40); + + entry = rtk->syslog_buffer.buffer + 1 * entry_size; + strscpy(entry + 8, "ctx", 24); + strscpy(entry + 8 + 24, "hello rtkit \r\n", 0x40); + /* Entry 4 is past the ring the firmware described, but inside the buffer. */ + entry = rtk->syslog_buffer.buffer + 4 * entry_size; + strscpy(entry + 8, "stale", 24); + strscpy(entry + 8 + 24, "not a record", 0x40); + ctx->n_sent = 0; +} + +static void rtk_test_syslog_log(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 log1 = FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG) | 1; + + rtk_test_syslog_setup(test); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log1, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_syslog, 1); + KUNIT_EXPECT_STREQ(test, ctx->syslog_ctx, "ctx"); + /* Trailing whitespace is cropped. */ + KUNIT_EXPECT_STREQ(test, ctx->syslog_msg, "hello rtkit"); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_SYSLOG, log1); +} + +static void rtk_test_syslog_index_range(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 log4 = FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG) | 4; + u64 log_ff = FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG) | 0xff; + + rtk_test_syslog_setup(test); + /* Records past the ring are not read, but still acknowledged. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log4, false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log_ff, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_syslog, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_SYSLOG, log4); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_SYSLOG, log_ff); +} + +static void rtk_test_syslog_no_geometry(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 log0 = FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG); + + rtk_test_syslog_setup(test); + /* A zero-sized INIT drops the message buffer rather than kzalloc(0). */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_INIT) | + FIELD_PREP(APPLE_RTKIT_SYSLOG_N_ENTRIES, 4), false, 0); + KUNIT_EXPECT_NULL(test, rtk->syslog_msg_buffer); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log0, false, 0); + + /* An inherited session cannot read the ring either. */ + rtk->syslog_inherited = true; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log0, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_syslog, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 2); +} + +static void rtk_test_kdebug(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 get = FIELD_PREP(APPLE_RTKIT_KDEBUG_TYPE, APPLE_RTKIT_KDEBUG_GET_BUFFER); + + rtk->sync_syslog_ack = true; + /* No entries, and more than the cap, are refused before any setup. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, get, false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, + get | FIELD_PREP(APPLE_RTKIT_KDEBUG_DATA, + APPLE_RTKIT_KDEBUG_BUF0_MAX / + APPLE_RTKIT_KDEBUG_ENTRY_SIZE + 1), false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, + get | APPLE_RTKIT_KDEBUG_DATA, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); + + /* 16 entries round up to one aligned buffer, plus the fixed second one. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, + get | FIELD_PREP(APPLE_RTKIT_KDEBUG_DATA, 16), false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 2); + KUNIT_EXPECT_EQ(test, rtk->kdebug_buffer0.size, APPLE_RTKIT_KDEBUG_BUF_ALIGN); + KUNIT_EXPECT_EQ(test, rtk->kdebug_buffer1.size, APPLE_RTKIT_KDEBUG_BUF1_SIZE); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_DEBUG, + FIELD_PREP(APPLE_RTKIT_KDEBUG_TYPE, APPLE_RTKIT_KDEBUG_SET_BUFFER0) | + RTK_TEST_IOVA_BASE); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_DEBUG, + FIELD_PREP(APPLE_RTKIT_KDEBUG_TYPE, APPLE_RTKIT_KDEBUG_SET_BUFFER1) | + (RTK_TEST_IOVA_BASE + SZ_1M)); + + /* A repeated request of the same size reuses both buffers. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, + get | FIELD_PREP(APPLE_RTKIT_KDEBUG_DATA, 16), false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 2); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 4); +} + +static void rtk_test_coreanalytics_encoding(struct kunit *test) +{ + u64 reply; + + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_size(APPLE_RTKIT_CA_UNIT_4K | + FIELD_PREP(APPLE_RTKIT_CA_COUNT, 3)), + 0x3000); + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_size(APPLE_RTKIT_CA_UNIT_1M | + FIELD_PREP(APPLE_RTKIT_CA_COUNT, 2)), + 0x200000); + /* Without a unit there is no size. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_size(FIELD_PREP(APPLE_RTKIT_CA_COUNT, 2)), + 0); + + KUNIT_ASSERT_EQ(test, apple_rtkit_coreanalytics_reply(0x3000, 0x40000, &reply), 0); + KUNIT_EXPECT_EQ(test, reply, + FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_BUFFER_REPLY) | + FIELD_PREP(APPLE_RTKIT_CA_COUNT, 3) | APPLE_RTKIT_CA_UNIT_4K | 0x40000); + /* A partial unit rounds up; a megabyte or more counts in megabytes. */ + KUNIT_ASSERT_EQ(test, apple_rtkit_coreanalytics_reply(0x2001, 0, &reply), 0); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_RTKIT_CA_COUNT, reply), 3); + KUNIT_ASSERT_EQ(test, apple_rtkit_coreanalytics_reply(0x180000, 0, &reply), 0); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_RTKIT_CA_COUNT, reply), 2); + KUNIT_EXPECT_TRUE(test, reply & APPLE_RTKIT_CA_UNIT_1M); + KUNIT_EXPECT_FALSE(test, reply & APPLE_RTKIT_CA_UNIT_4K); + + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_reply(0, 0, &reply), -EINVAL); + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_reply(0x1000, BIT_ULL(44), &reply), + -EINVAL); + /* 256 MiB needs a count of 256, which the 8-bit field cannot hold. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_reply(SZ_256M, 0, &reply), -EINVAL); +} + +static void rtk_test_coreanalytics_rx(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_BUFFER_REQUEST) | + APPLE_RTKIT_CA_UNIT_4K | FIELD_PREP(APPLE_RTKIT_CA_COUNT, 4); + u64 event = FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_EVENT) | + FIELD_PREP(APPLE_RTKIT_CA_EVENT_ID, 0x1234) | 0xff; + + /* A client that asks for CoreAnalytics, as the PMP does. */ + ctx->ops.flags = APPLE_RTKIT_NEEDS_COREANALYTICS; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_COREANALYTICS, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->setup_ep, APPLE_RTKIT_EP_COREANALYTICS); + KUNIT_EXPECT_EQ(test, rtk->coreanalytics_buffer.size, 0x4000); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->coreanalytics_completion)); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_COREANALYTICS, + FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_BUFFER_REPLY) | + APPLE_RTKIT_CA_UNIT_4K | FIELD_PREP(APPLE_RTKIT_CA_COUNT, 4) | + RTK_TEST_IOVA_BASE); + + /* A duplicate request never replaces the live buffer. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_COREANALYTICS, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 1); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); + + /* An event is acknowledged with its ID only. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_COREANALYTICS, event, false, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_COREANALYTICS, + FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_EVENT_ACK) | + FIELD_PREP(APPLE_RTKIT_CA_EVENT_ID, 0x1234)); +} + +static void rtk_test_crashlog_handshake_then_crash(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = rtk_test_buffer_request(APPLE_RTKIT_CRASHLOG_CRASH, SZ_4K, 0); + struct apple_rtkit_crashlog_header *hdr; + + set_bit(APPLE_RTKIT_EP_CRASHLOG, rtk->endpoints); + /* In a handshaked session the first message is the buffer request. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, req, false, 0); + KUNIT_EXPECT_FALSE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 0); + KUNIT_EXPECT_EQ(test, rtk->crashlog_buffer.size, SZ_4K); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_CRASHLOG, + rtk_test_buffer_request(APPLE_RTKIT_BUFFER_REQUEST, SZ_4K, + RTK_TEST_IOVA_BASE)); + + /* The firmware writes a log, then reports the crash. */ + hdr = rtk->crashlog_buffer.buffer; + hdr->fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC; + hdr->size = sizeof(*hdr); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, req, false, 0); + KUNIT_EXPECT_TRUE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, ctx->crashed_size, SZ_4K); + KUNIT_EXPECT_EQ(test, ctx->crashed_fourcc, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC); + + /* Unknown crashlog messages are ignored; a crashed IOP gets no messages. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 2), false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, apple_rtkit_send_message(rtk, APPLE_RTKIT_EP_MGMT, 0, NULL, false), + -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); +} + +static void rtk_test_crashlog_report_only(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + struct apple_rtkit_crashlog_header log = { + .fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC, + .size = sizeof(log), + }; + + /* + * An undiscovered crashlog endpoint only reports crashes; the client's + * setup maps the buffer, which already holds the log. + */ + ctx->prefill = &log; + ctx->prefill_len = sizeof(log); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, + rtk_test_buffer_request(1, SZ_4K, 0x7000), false, 0); + KUNIT_EXPECT_TRUE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, ctx->crashed_size, SZ_4K); + KUNIT_EXPECT_EQ(test, ctx->crashed_fourcc, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC); +} + +static void rtk_test_crashlog_unreadable(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + /* A buffer holding no log yet: the crash is reported without one. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, + rtk_test_buffer_request(1, SZ_4K, 0x7000), false, 0); + KUNIT_EXPECT_TRUE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, ctx->crashed_size, 0); + /* ...and the log is looked for again later. */ + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&rtk->crashlog_late_work)); + cancel_delayed_work_sync(&rtk->crashlog_late_work); +} + +static void rtk_test_crashlog_no_mapping(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + /* No setup callback and no IOMMU domain: the crash is still reported. */ + ctx->ops.shmem_setup_ep = NULL; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, + rtk_test_buffer_request(1, SZ_4K, 0x7000), false, 0); + KUNIT_EXPECT_TRUE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, ctx->crashed_size, 0); + KUNIT_EXPECT_EQ(test, rtk->crashlog_buffer.size, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_crashlog_header_valid(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + struct apple_rtkit_crashlog_header *hdr; + u32 *words; + + rtk->crashlog_buffer.size = 0x100; + rtk->crashlog_buffer.buffer = kunit_kzalloc(test, 0x100, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, rtk->crashlog_buffer.buffer); + hdr = rtk->crashlog_buffer.buffer; + + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + hdr->fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC; + hdr->size = 0x100; + KUNIT_EXPECT_TRUE(test, apple_rtkit_crashlog_header_valid(rtk)); + hdr->size = 0x101; + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + hdr->size = sizeof(*hdr) - 1; + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + + /* A container is valid when its current record leads to a log. */ + words = rtk->crashlog_buffer.buffer; + memset(words, 0, 0x100); + words[0] = APPLE_RTKIT_CRASHLOG_CONTAINER_FOURCC; + words[1] = 0x200; /* version 2 */ + words[2] = 0x100; /* size */ + words[3] = 0x41; /* current id */ + words[4] = 1; /* one record */ + /* record 0 at 0x14: id (u64), unknown (u64), offset (u32) */ + words[5] = 0x41; + words[9] = 0x80; + hdr = rtk->crashlog_buffer.buffer + 0x80; + hdr->fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC; + hdr->size = 0x80; + KUNIT_EXPECT_TRUE(test, apple_rtkit_crashlog_header_valid(rtk)); + words[3] = 0x42; + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + + /* Too small for a header at all. */ + rtk->crashlog_buffer.size = sizeof(*hdr) - 1; + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static struct kunit_case apple_rtkit_test_cases[] = { + KUNIT_CASE(rtk_test_hello_accepts_supported), + KUNIT_CASE(rtk_test_hello_rejects_unsupported), + KUNIT_CASE(rtk_test_hello_client_version), + KUNIT_CASE(rtk_test_epmap_starts_system_endpoints), + KUNIT_CASE(rtk_test_epmap_multipart), + KUNIT_CASE(rtk_test_epmap_flags), + KUNIT_CASE(rtk_test_epmap_retained), + KUNIT_CASE(rtk_test_power_acks), + KUNIT_CASE(rtk_test_retained_quiesced), + KUNIT_CASE(rtk_test_idle_notify), + KUNIT_CASE(rtk_test_send_checks), + KUNIT_CASE(rtk_test_app_endpoint_dispatch), + KUNIT_CASE(rtk_test_buffer_reply), + KUNIT_CASE(rtk_test_buffer_request_invalid), + KUNIT_CASE(rtk_test_placed_buffers), + KUNIT_CASE(rtk_test_oslog_buffer_request), + KUNIT_CASE(rtk_test_syslog_log), + KUNIT_CASE(rtk_test_syslog_index_range), + KUNIT_CASE(rtk_test_syslog_no_geometry), + KUNIT_CASE(rtk_test_kdebug), + KUNIT_CASE(rtk_test_coreanalytics_encoding), + KUNIT_CASE(rtk_test_coreanalytics_rx), + KUNIT_CASE(rtk_test_crashlog_handshake_then_crash), + KUNIT_CASE(rtk_test_crashlog_report_only), + KUNIT_CASE(rtk_test_crashlog_unreadable), + KUNIT_CASE(rtk_test_crashlog_no_mapping), + KUNIT_CASE(rtk_test_crashlog_header_valid), + {} +}; + +static struct kunit_suite apple_rtkit_test_suite = { + .name = "apple-rtkit", + .init = rtk_test_init, + .exit = rtk_test_exit, + .test_cases = apple_rtkit_test_cases, +}; + +kunit_test_suite(apple_rtkit_test_suite); diff --git a/drivers/soc/apple/rtkit-v27-late.inc b/drivers/soc/apple/rtkit-v27-late.inc index 6f3bfd84ab0a5f..26b4aa56b4cadf 100644 --- a/drivers/soc/apple/rtkit-v27-late.inc +++ b/drivers/soc/apple/rtkit-v27-late.inc @@ -7,8 +7,23 @@ struct apple_rtkit_v27_scope { DECLARE_KFIFO(deferred, struct apple_mbox_msg, 64); bool held, stopped, failed; int error; + /* + * Run once between the AP state's acknowledgment and the IOP request, interrupts off. + * An error fails the idle. + */ + int (*after_ap)(void *data); + void *after_ap_data; }; +void apple_rtkit_v27_set_after_ap(struct apple_rtkit_v27_scope *s, int (*fn)(void *), void *data) +{ + if (s) { + s->after_ap = fn; + s->after_ap_data = data; + } +} +EXPORT_SYMBOL_GPL(apple_rtkit_v27_set_after_ap); + bool apple_rtkit_v27_live(struct apple_rtkit *rtk) { return !rtk->crashed && !rtk->shutting_down && @@ -96,7 +111,11 @@ undo: } EXPORT_SYMBOL_GPL(apple_rtkit_v27_arm); -int apple_rtkit_v27_check(struct apple_rtkit_v27_scope *s) +/* + * Before the commit, a pending message refuses the sleep (it is kept for the disarm). After it, + * the stop that follows reads the mailbox itself: a message there is left to it. + */ +int apple_rtkit_v27_check(struct apple_rtkit_v27_scope *s, bool committed) { struct apple_mbox_msg msg; int ret; @@ -109,6 +128,8 @@ int apple_rtkit_v27_check(struct apple_rtkit_v27_scope *s) return -EBUSY; if (kfifo_is_full(&s->deferred)) return -ENOBUFS; + if (committed) + return 0; ret = apple_mbox_recv_nowait(s->rtk->mbox, &msg); if (ret > 0) { kfifo_put(&s->deferred, msg); @@ -118,6 +139,44 @@ int apple_rtkit_v27_check(struct apple_rtkit_v27_scope *s) } EXPORT_SYMBOL_GPL(apple_rtkit_v27_check); +/* + * A second port's AP idle with interrupts off: sent, and its acknowledgment awaited by polling + * the port's mailbox, for at most @us. The port's tracked state is not updated. + */ +int apple_rtkit_v27_port_ap_idle_atomic(struct apple_rtkit *rtk, unsigned int us) +{ + struct apple_mbox_msg msg = { + .msg0 = FIELD_PREP(APPLE_RTKIT_MGMT_TYPE, APPLE_RTKIT_MGMT_SET_AP_PWR_STATE) | + FIELD_PREP(APPLE_RTKIT_MGMT_PWR_STATE, APPLE_RTKIT_PWR_STATE_IDLE), + .msg1 = APPLE_RTKIT_EP_MGMT, + }; + unsigned int i, n = us / 10; + int ret = -ETIMEDOUT; + + for (i = 0; i < n; i++) { + ret = apple_mbox_send_nowait(rtk->mbox, msg); + if (ret != -EAGAIN && ret != -EBUSY) + break; + udelay(10); + } + if (ret) + return ret; + for (; i < n; i++) { + struct apple_mbox_msg in; + + ret = apple_mbox_recv_nowait(rtk->mbox, &in); + if (ret < 0 && ret != -EBUSY) + return ret; + if (ret > 0 && in.msg1 == APPLE_RTKIT_EP_MGMT && + FIELD_GET(APPLE_RTKIT_MGMT_TYPE, in.msg0) == APPLE_RTKIT_MGMT_SET_AP_PWR_STATE_ACK) + return FIELD_GET(APPLE_RTKIT_MGMT_PWR_STATE, in.msg0) == + APPLE_RTKIT_PWR_STATE_IDLE ? 0 : -EPROTO; + udelay(10); + } + return -ETIMEDOUT; +} +EXPORT_SYMBOL_GPL(apple_rtkit_v27_port_ap_idle_atomic); + int apple_rtkit_v27_idle_atomic(struct apple_rtkit_v27_scope *s) { struct apple_rtkit *rtk; @@ -180,6 +239,11 @@ int apple_rtkit_v27_idle_atomic(struct apple_rtkit_v27_scope *s) type == APPLE_RTKIT_MGMT_SET_AP_PWR_STATE_ACK && arg == APPLE_RTKIT_PWR_STATE_IDLE) { ap_ack = true; + if (s->after_ap) { + ret = s->after_ap(s->after_ap_data); + if (ret) + goto poison; + } } else if (msg.msg1 == APPLE_RTKIT_EP_MGMT && iop_sent && !iop_ack && type == APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK && arg == APPLE_RTKIT_PWR_STATE_IDLE) { @@ -187,13 +251,21 @@ int apple_rtkit_v27_idle_atomic(struct apple_rtkit_v27_scope *s) } else if (msg.msg1 == APPLE_RTKIT_EP_MGMT && iop_sent && !done && type == APPLE_RTKIT_MGMT_IDLE_NOTIFY && !arg) { done = true; - } else if (apple_rtkit_oslog_owed_msg(rtk, msg.msg1, msg.msg0)) { + } else if (msg.msg1 == APPLE_RTKIT_EP_MGMT || + msg.msg1 == APPLE_RTKIT_EP_CRASHLOG || + msg.msg1 >= APPLE_RTKIT_APP_ENDPOINT_START) { + /* A crash, unexpected handshake, or live application RPC. */ + kfifo_put(&s->deferred, msg); + ret = -EPROTO; + goto poison; + } else if (apple_rtkit_oslog_owed_msg(rtk, msg.msg1, msg.msg0) || + apple_rtkit_notification_msg(msg.msg1, msg.msg0)) { + /* Echo now. The ring entry can be reused after the echo. */ echo = msg; echo_pending = true; } else { + /* Other system messages are replayed on disarm. */ kfifo_put(&s->deferred, msg); - ret = -EPROTO; - goto poison; } } } diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index e529b4d4dd4c6e..4b873f1fdd4643 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -21,6 +21,10 @@ #include #include +#if IS_ENABLED(CONFIG_APPLE_RTKIT_KUNIT_TEST) +#include +#endif + enum { APPLE_RTKIT_PWR_STATE_OFF = 0x00, /* power off, cannot be restarted */ APPLE_RTKIT_PWR_STATE_SLEEP = 0x01, /* sleeping, can be restarted */ @@ -179,11 +183,35 @@ static bool apple_rtkit_needs_coreanalytics(struct apple_rtkit *rtk) return rtk->ops->flags & APPLE_RTKIT_NEEDS_COREANALYTICS; } +/* + * Endpoint 7 carries CoreAnalytics, or the auxiliary buffer of registry-v2 PMP + * firmware. The endpoint map starts it, and the dispatcher serves it, only then. + */ +static bool apple_rtkit_ep7_served(struct apple_rtkit *rtk) +{ + return rtk->pmp_registry_v2 || apple_rtkit_needs_coreanalytics(rtk); +} + static bool apple_rtkit_firmware_owns_crashlog(struct apple_rtkit *rtk) { return rtk->ops->flags & APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG; } +/* + * Whether RTKit maps a crash log the firmware placed at its own address: one rule for + * the buffer request on an endpoint the firmware announced and for the crash report on + * one it left out of its map. Not when the client says the firmware owns that buffer + * (taken unmapped) or sets placed buffers up itself (shmem_setup); otherwise it is + * mapped if apple_dart_fw_range() accepts it (apple_rtkit_crashlog_map()). + */ +static bool apple_rtkit_maps_placed_crashlog(struct apple_rtkit *rtk) +{ + return !apple_rtkit_firmware_owns_crashlog(rtk) && + !rtk->ops->shmem_setup && !rtk->ops->shmem_setup_ep; +} + +static int apple_rtkit_crashlog_map(struct apple_rtkit *rtk, u64 msg); + /* The crashlog endpoint is started while the endpoint map is handled. */ static bool apple_rtkit_early_crashlog(struct apple_rtkit *rtk) { @@ -426,7 +454,7 @@ static void apple_rtkit_management_rx_epmap(struct apple_rtkit *rtk, u64 msg) break; case APPLE_RTKIT_EP_COREANALYTICS: - if (!rtk->pmp_registry_v2 && !apple_rtkit_needs_coreanalytics(rtk)) + if (!apple_rtkit_ep7_served(rtk)) break; fallthrough; @@ -481,7 +509,7 @@ static void apple_rtkit_management_rx_iop_pwr_ack(struct apple_rtkit *rtk, dev_dbg(rtk->dev, "RTKit: IOP power state transition: 0x%x -> 0x%x\n", rtk->iop_power_state, new_state); - rtk->iop_power_state = new_state; + WRITE_ONCE(rtk->iop_power_state, new_state); /* * A retained wake: a co-processor may report QUIESCED when it starts @@ -551,18 +579,16 @@ static void apple_rtkit_management_rx(struct apple_rtkit *rtk, u64 msg) dev_dbg(rtk->dev, "RTKit: co-processor idle: 0x%llx\n", msg); break; default: - dev_warn( + dev_warn_ratelimited( rtk->dev, "RTKit: unknown management message: 0x%llx (type: 0x%02x)\n", msg, type); } } -static int apple_rtkit_alloc_shmem(struct apple_rtkit *rtk, u8 ep, - struct apple_rtkit_shmem *buffer) +static int apple_rtkit_alloc_first_shmem(struct apple_rtkit *rtk, u8 ep, + struct apple_rtkit_shmem *buffer) { - if (READ_ONCE(rtk->ans_hold)) - return apple_rtkit_ans_fail(rtk, -EBUSY); /* The crash log's buffer is asked for only at a crash: serve it after a strict restart too. */ if (READ_ONCE(rtk->strict_retained_buffers) && ep != APPLE_RTKIT_EP_CRASHLOG) return -EPROTO; @@ -577,6 +603,14 @@ static int apple_rtkit_alloc_shmem(struct apple_rtkit *rtk, u8 ep, return buffer->buffer ? 0 : -ENOMEM; } +static int apple_rtkit_alloc_shmem(struct apple_rtkit *rtk, u8 ep, + struct apple_rtkit_shmem *buffer) +{ + if (READ_ONCE(rtk->ans_hold)) + return apple_rtkit_ans_fail(rtk, -EBUSY); + return apple_rtkit_alloc_first_shmem(rtk, ep, buffer); +} + static int apple_rtkit_common_rx_get_buffer(struct apple_rtkit *rtk, struct apple_rtkit_shmem *buffer, u8 ep, u64 msg) @@ -636,6 +670,14 @@ static int apple_rtkit_common_rx_get_buffer(struct apple_rtkit *rtk, return apple_rtkit_send_message(rtk, ep, msg, NULL, false); } + if (ep == APPLE_RTKIT_EP_CRASHLOG && request.iova && + apple_rtkit_maps_placed_crashlog(rtk)) { + err = apple_rtkit_crashlog_map(rtk, msg); + if (err) + goto error; + return 0; + } + if ((rtk->ops->flags & APPLE_RTKIT_FIRMWARE_OWNED_LOGS) && request.iova && (ep == APPLE_RTKIT_EP_SYSLOG || ep == APPLE_RTKIT_EP_OSLOG)) { *buffer = request; @@ -650,7 +692,8 @@ static int apple_rtkit_common_rx_get_buffer(struct apple_rtkit *rtk, goto error; } - err = apple_rtkit_alloc_shmem(rtk, ep, &request); + /* The endpoint has no buffer yet: a first one replaces nothing the ANS hold protects */ + err = apple_rtkit_alloc_first_shmem(rtk, ep, &request); if (err) goto error; *buffer = request; @@ -911,7 +954,7 @@ static void apple_rtkit_coreanalytics_rx(struct apple_rtkit *rtk, u64 msg) reply, NULL, false); break; default: - dev_warn(rtk->dev, "RTKit: Unknown CoreAnalytics message: %llx\n", msg); + dev_warn_ratelimited(rtk->dev, "RTKit: Unknown CoreAnalytics message: %llx\n", msg); return; } if (ret) @@ -936,52 +979,32 @@ static void apple_rtkit_memcpy(struct apple_rtkit *rtk, void *dst, len, DMA_FROM_DEVICE); } -/* - * Where a DVA of the crash buffer lands: in a mapping Linux made, or else in one the - * firmware kept from the bootloader in a root its DART inherited (the T8140 AOP's own - * slot). 0 when neither translates it. - */ -static phys_addr_t apple_rtkit_crashlog_phys(struct apple_rtkit *rtk, - struct iommu_domain *domain, dma_addr_t iova) -{ - phys_addr_t phys = iommu_iova_to_phys(domain, iova); - - if (!phys && IS_REACHABLE(CONFIG_APPLE_DART) && - apple_dart_fw_remote(rtk->dev, iova, false, &phys)) - phys = 0; - - return phys; -} - /* * The buffer a crashing firmware placed at its own address, mapped if its IOMMU - * translates every page of it to one contiguous range, and acknowledged as a placed + * translates every page of it, through Linux's mappings or those the firmware kept + * from the boot loader (the T8140 AOP's own slot), to one contiguous range of DRAM + * that nothing else claims (apple_dart_fw_range()), and acknowledged as a placed * buffer is. The firmware doesn't run again until a reboot. + * + * Write-combined, not cacheable: the co-processor isn't coherent with the CPU's + * caches, and apple_rtkit_crashlog_late() polls the buffer for a log written after + * the request, with no cache maintenance for a placed buffer, so a cacheable + * mapping could keep returning the header it read first. */ static int apple_rtkit_crashlog_map(struct apple_rtkit *rtk, u64 msg) { struct apple_rtkit_shmem *bfr = &rtk->crashlog_buffer; - struct iommu_domain *domain = iommu_get_domain_for_dev(rtk->dev); dma_addr_t iova = FIELD_GET(APPLE_RTKIT_BUFFER_REQUEST_IOVA, msg); size_t size = FIELD_GET(APPLE_RTKIT_BUFFER_REQUEST_SIZE, msg) << 12; - phys_addr_t phys, page; - size_t off; + phys_addr_t phys; void *va; + int ret; - if (!domain || !iova || !size) - return -ENODEV; - phys = apple_rtkit_crashlog_phys(rtk, domain, iova); - for (off = 0; phys && off < size; off += PAGE_SIZE) { - page = apple_rtkit_crashlog_phys(rtk, domain, iova + off); - if (page != phys + off) { - dev_err(rtk->dev, "RTKit: crash log at %pad isn't contiguous at +%#zx\n", - &iova, off); - return -EINVAL; - } - } - if (!phys) - return -ENOENT; - va = memremap(phys, size, MEMREMAP_WB); + ret = apple_dart_fw_range(rtk->dev, iova, size, + APPLE_DART_FW_LINUX | APPLE_DART_FW_RETAINED, &phys); + if (ret) + return ret; + va = memremap(phys, size, MEMREMAP_WC); if (!va) return -ENOMEM; bfr->buffer = va; @@ -1071,8 +1094,8 @@ static void apple_rtkit_crashlog_rx(struct apple_rtkit *rtk, u64 msg) bool await_log = false; if (type != APPLE_RTKIT_CRASHLOG_CRASH) { - dev_warn(rtk->dev, "RTKit: Unknown crashlog message: %llx\n", - msg); + dev_warn_ratelimited(rtk->dev, "RTKit: Unknown crashlog message: %llx\n", + msg); return; } @@ -1080,10 +1103,11 @@ static void apple_rtkit_crashlog_rx(struct apple_rtkit *rtk, u64 msg) * A firmware that never announced this endpoint asks for its buffer only when * it crashes, so there's no handshake to take the request for. Report the * crash now, as the log may never come. A client that sets such a buffer up - * itself takes the path below, which also reads a log written later. + * itself, or whose firmware owns it, takes the path below, which also reads a + * log written later (apple_rtkit_maps_placed_crashlog()). */ if (!rtk->crashlog_buffer.size && !test_bit(APPLE_RTKIT_EP_CRASHLOG, rtk->endpoints) && - !rtk->ops->shmem_setup && !rtk->ops->shmem_setup_ep) { + apple_rtkit_maps_placed_crashlog(rtk)) { int ret = apple_rtkit_crashlog_map(rtk, msg); dev_err(rtk->dev, "RTKit: co-processor has crashed: crash log buffer at %#llx %s (%d)\n", @@ -1223,8 +1247,8 @@ static void apple_rtkit_ioreport_rx(struct apple_rtkit *rtk, u64 msg) NULL, false); break; default: - dev_warn(rtk->dev, "RTKit: Unknown ioreport message: %llx\n", - msg); + dev_warn_ratelimited(rtk->dev, "RTKit: Unknown ioreport message: %llx\n", + msg); } } @@ -1345,8 +1369,8 @@ static void apple_rtkit_syslog_rx(struct apple_rtkit *rtk, u64 msg) apple_rtkit_syslog_rx_log(rtk, msg); break; default: - dev_warn(rtk->dev, "RTKit: Unknown syslog message: %llx\n", - msg); + dev_warn_ratelimited(rtk->dev, "RTKit: Unknown syslog message: %llx\n", + msg); } } @@ -1397,7 +1421,8 @@ static void apple_rtkit_oslog_rx(struct apple_rtkit *rtk, u64 msg) if (apple_rtkit_oslog_unanswered(rtk)) dev_dbg(rtk->dev, "RTKit: oslog notification: %016llx\n", msg); else - dev_warn(rtk->dev, "RTKit: invalid oslog notification: %llx\n", msg); + dev_warn_ratelimited(rtk->dev, "RTKit: invalid oslog notification: %llx\n", + msg); return; } @@ -1429,8 +1454,8 @@ static void apple_rtkit_oslog_rx(struct apple_rtkit *rtk, u64 msg) dev_dbg(rtk->dev, "RTKit: oslog notification: %016llx\n", msg); break; default: - dev_warn(rtk->dev, "RTKit: Unknown oslog message: %llx\n", - msg); + dev_warn_ratelimited(rtk->dev, "RTKit: Unknown oslog message: %llx\n", + msg); } } @@ -1462,13 +1487,26 @@ static void apple_rtkit_pmp_aux_rx(struct apple_rtkit *rtk, u64 msg) msg != (FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_BUFFER_REQUEST) | FIELD_PREP(APPLE_RTKIT_BUFFER_REQUEST_SIZE, 2))) { - dev_err(rtk->dev, "RTKit: refused auxiliary buffer request\n"); + dev_err_ratelimited(rtk->dev, "RTKit: refused auxiliary buffer request\n"); return; } apple_rtkit_common_rx_get_buffer(rtk, &rtk->pmp_aux_buffer, APPLE_RTKIT_EP_PMP_AUX, msg); } +/* + * A message to an endpoint this client doesn't serve. How often one arrives is + * up to the firmware, which may send its events periodically, so the warning + * is rate-limited, as every warning the receive path prints for a firmware + * message is. + */ +static void apple_rtkit_unserved_ep_msg(struct apple_rtkit *rtk, u8 ep, u64 msg) +{ + dev_warn_ratelimited(rtk->dev, + "RTKit: message to unknown endpoint %02x: %llx\n", + ep, msg); +} + static void apple_rtkit_rx_dispatch(struct apple_rtkit *rtk, u8 ep, u64 msg, bool retained, u64 received_ns) { @@ -1498,12 +1536,12 @@ static void apple_rtkit_rx_dispatch(struct apple_rtkit *rtk, u8 ep, u64 msg, if (rtk->sync_syslog_ack) apple_rtkit_kdebug_rx(rtk, msg); else - dev_warn(rtk->dev, - "RTKit: message to unknown endpoint %02x: %llx\n", - ep, msg); + apple_rtkit_unserved_ep_msg(rtk, ep, msg); break; case APPLE_RTKIT_EP_COREANALYTICS: - if (rtk->pmp_registry_v2) + if (!apple_rtkit_ep7_served(rtk)) + apple_rtkit_unserved_ep_msg(rtk, ep, msg); + else if (rtk->pmp_registry_v2) apple_rtkit_pmp_aux_rx(rtk, msg); else apple_rtkit_coreanalytics_rx(rtk, msg); @@ -1520,15 +1558,13 @@ static void apple_rtkit_rx_dispatch(struct apple_rtkit *rtk, u8 ep, u64 msg, else if (rtk->ops->recv_message_timed) rtk->ops->recv_message_timed(rtk->cookie, ep, msg, 0); else - dev_warn( + dev_warn_ratelimited( rtk->dev, "Received unexpected message to EP%02d: %llx\n", ep, msg); break; default: - dev_warn(rtk->dev, - "RTKit: message to unknown endpoint %02x: %llx\n", - ep, msg); + apple_rtkit_unserved_ep_msg(rtk, ep, msg); } } @@ -1698,9 +1734,9 @@ static void apple_rtkit_rx(struct apple_mbox *mbox, struct apple_mbox_msg msg, * Warning about it here too reads as if the AP sent the message. */ if (!test_bit(ep, rtk->endpoints) && ep != APPLE_RTKIT_EP_CRASHLOG) - dev_warn(rtk->dev, - "RTKit: Message from undiscovered endpoint 0x%02x\n", - ep); + dev_warn_ratelimited(rtk->dev, + "RTKit: Message from undiscovered endpoint 0x%02x\n", + ep); if (ep >= APPLE_RTKIT_APP_ENDPOINT_START && rtk->ops->recv_message_early && @@ -1752,6 +1788,10 @@ int apple_rtkit_send_message(struct apple_rtkit *rtk, u8 ep, u64 message, */ dma_wmb(); +#if IS_ENABLED(CONFIG_APPLE_RTKIT_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(apple_rtkit_send_message, rtk, ep, message, + completion, atomic); +#endif return apple_mbox_send(rtk->mbox, msg, atomic); } EXPORT_SYMBOL_GPL(apple_rtkit_send_message); @@ -2125,6 +2165,18 @@ bool apple_rtkit_v27_rx_drained(struct apple_rtkit *rtk) } EXPORT_SYMBOL_GPL(apple_rtkit_v27_rx_drained); +/* + * A co-processor adopted from the bootloader has already sent its endpoint + * map. A client that starts one of its application endpoints by hand + * registers it here, so its messages are not reported as undiscovered. + */ +void apple_rtkit_adopt_ep(struct apple_rtkit *rtk, u8 ep) +{ + if (ep >= APPLE_RTKIT_APP_ENDPOINT_START) + set_bit(ep, rtk->endpoints); +} +EXPORT_SYMBOL_GPL(apple_rtkit_adopt_ep); + int apple_rtkit_start_ep(struct apple_rtkit *rtk, u8 endpoint) { u64 msg; @@ -2289,12 +2341,61 @@ static int apple_rtkit_inherit_buffers( return 0; } +/* + * The endpoint map the previous owner received for this session. Management + * is always present; system endpoints are limited to those RTKit implements + * here, so that an unknown one is not silently ignored. + */ +static int apple_rtkit_inherit_endpoints( + struct apple_rtkit *rtk, const struct apple_rtkit_adopted_session *session) +{ + static const u8 system_endpoints[] = { + APPLE_RTKIT_EP_MGMT, APPLE_RTKIT_EP_CRASHLOG, + APPLE_RTKIT_EP_SYSLOG, APPLE_RTKIT_EP_DEBUG, + APPLE_RTKIT_EP_IOREPORT, APPLE_RTKIT_EP_COREANALYTICS, + APPLE_RTKIT_EP_OSLOG, APPLE_RTKIT_EP_TRACEKIT, + }; + DECLARE_BITMAP(known, APPLE_RTKIT_APP_ENDPOINT_START) = {}; + DECLARE_BITMAP(map, APPLE_RTKIT_MAX_ENDPOINTS); + unsigned int i; + + BUILD_BUG_ON(APPLE_RTKIT_ADOPTED_EPMAP_WORDS * 32 != + APPLE_RTKIT_MAX_ENDPOINTS); + + if (session->protocol_version < APPLE_RTKIT_MIN_SUPPORTED_VERSION || + session->protocol_version > APPLE_RTKIT_MAX_SUPPORTED_VERSION || + (rtk->ops->protocol_version && + session->protocol_version != rtk->ops->protocol_version)) + return -EINVAL; + + bitmap_from_arr32(map, session->epmap, APPLE_RTKIT_MAX_ENDPOINTS); + for (i = 0; i < ARRAY_SIZE(system_endpoints); i++) + set_bit(system_endpoints[i], known); + if (!test_bit(APPLE_RTKIT_EP_MGMT, map)) + return -EINVAL; + for (i = 0; i < APPLE_RTKIT_APP_ENDPOINT_START; i++) + if (test_bit(i, map) && !test_bit(i, known)) + return -EINVAL; + /* A retained buffer belongs to an endpoint the session has. */ + if ((rtk->crashlog_buffer.size && !test_bit(APPLE_RTKIT_EP_CRASHLOG, map)) || + (rtk->syslog_buffer.size && !test_bit(APPLE_RTKIT_EP_SYSLOG, map)) || + (rtk->ioreport_buffer.size && !test_bit(APPLE_RTKIT_EP_IOREPORT, map)) || + (rtk->oslog_buffer.size && !test_bit(APPLE_RTKIT_EP_OSLOG, map))) + return -EINVAL; + + bitmap_copy(rtk->endpoints, map, APPLE_RTKIT_MAX_ENDPOINTS); + rtk->version = session->protocol_version; + return 0; +} + static struct apple_rtkit *__apple_rtkit_init(struct device *dev, void *cookie, + const char *mbox_prop, const char *mbox_name, int mbox_idx, const struct apple_rtkit_ops *ops, bool adopted, const struct apple_rtkit_inherited_buffer *buffers, - unsigned int count, bool track_saved) + unsigned int count, bool track_saved, + const struct apple_rtkit_adopted_session *session) { struct apple_rtkit *rtk; int ret; @@ -2340,8 +2441,7 @@ static struct apple_rtkit *__apple_rtkit_init(struct device *dev, void *cookie, goto free_rtk; rtk->pmp_registry_v2 = of_device_is_compatible(dev->of_node, "apple,t6050-pmp-v2"); - rtk->pmp_ca_event_ack = rtk->pmp_registry_v2 && - of_machine_is_compatible("apple,j714s"); + rtk->pmp_ca_event_ack = rtk->pmp_registry_v2; init_completion(&rtk->epmap_completion); init_completion(&rtk->coreanalytics_completion); @@ -2354,7 +2454,9 @@ static struct apple_rtkit *__apple_rtkit_init(struct device *dev, void *cookie, set_bit(APPLE_RTKIT_EP_MGMT, rtk->endpoints); set_bit(APPLE_RTKIT_EP_MGMT, rtk->started); - if (mbox_name) + if (mbox_prop) + rtk->mbox = apple_mbox_get_prop(dev, mbox_prop, 0); + else if (mbox_name) rtk->mbox = apple_mbox_get_byname(dev, mbox_name); else rtk->mbox = apple_mbox_get(dev, mbox_idx); @@ -2376,6 +2478,12 @@ static struct apple_rtkit *__apple_rtkit_init(struct device *dev, void *cookie, /* Inherited system traffic may arrive as soon as mailbox RX is armed. */ if (adopted) apple_rtkit_mark_running(rtk); + /* The firmware's own endpoint map replaces the assumed one. */ + if (session) { + ret = apple_rtkit_inherit_endpoints(rtk, session); + if (ret) + goto destroy_wq; + } ret = apple_rtkit_claim_rx(rtk); if (ret) @@ -2402,17 +2510,26 @@ struct apple_rtkit *apple_rtkit_init(struct device *dev, void *cookie, const char *mbox_name, int mbox_idx, const struct apple_rtkit_ops *ops) { - return __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, false, - NULL, 0, false); + return __apple_rtkit_init(dev, cookie, NULL, mbox_name, mbox_idx, ops, false, + NULL, 0, false, NULL); } EXPORT_SYMBOL_GPL(apple_rtkit_init); +struct apple_rtkit *apple_rtkit_init_mbox_prop(struct device *dev, void *cookie, + const char *mbox_prop, + const struct apple_rtkit_ops *ops) +{ + return __apple_rtkit_init(dev, cookie, mbox_prop, NULL, 0, ops, false, + NULL, 0, false, NULL); +} +EXPORT_SYMBOL_GPL(apple_rtkit_init_mbox_prop); + struct apple_rtkit *apple_rtkit_init_adopted(struct device *dev, void *cookie, const char *mbox_name, int mbox_idx, const struct apple_rtkit_ops *ops) { - return __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, true, - NULL, 0, false); + return __apple_rtkit_init(dev, cookie, NULL, mbox_name, mbox_idx, ops, true, + NULL, 0, false, NULL); } EXPORT_SYMBOL_GPL(apple_rtkit_init_adopted); @@ -2470,11 +2587,25 @@ struct apple_rtkit *apple_rtkit_init_adopted_with_buffers( const struct apple_rtkit_ops *ops, const struct apple_rtkit_inherited_buffer *buffers, unsigned int count) { - return __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, true, - buffers, count, false); + return __apple_rtkit_init(dev, cookie, NULL, mbox_name, mbox_idx, ops, true, + buffers, count, false, NULL); } EXPORT_SYMBOL_GPL(apple_rtkit_init_adopted_with_buffers); +struct apple_rtkit *apple_rtkit_init_adopted_with_session( + struct device *dev, void *cookie, const char *mbox_name, int mbox_idx, + const struct apple_rtkit_ops *ops, + const struct apple_rtkit_adopted_session *session) +{ + if (!session) + return ERR_PTR(-EINVAL); + + return __apple_rtkit_init(dev, cookie, NULL, mbox_name, mbox_idx, ops, true, + session->buffers, session->num_buffers, false, + session); +} +EXPORT_SYMBOL_GPL(apple_rtkit_init_adopted_with_session); + static int apple_rtkit_wait_for_completion(struct apple_rtkit *rtk, struct completion *c) { @@ -2843,6 +2974,16 @@ static int apple_rtkit_strict_idle_state(struct apple_rtkit *rtk, bool ap) } int apple_rtkit_idle_strict(struct apple_rtkit *rtk) +{ + return apple_rtkit_idle_strict_with(rtk, NULL, NULL); +} +EXPORT_SYMBOL_GPL(apple_rtkit_idle_strict); + +/* + * As apple_rtkit_idle_strict(), with a step between the AP state's and the IOP state's. + * A failed step fails the idle: the IOP state is not sent. + */ +int apple_rtkit_idle_strict_with(struct apple_rtkit *rtk, int (*after_ap)(void *data), void *data) { int ret; @@ -2853,6 +2994,8 @@ int apple_rtkit_idle_strict(struct apple_rtkit *rtk) reinit_completion(&rtk->strict_idle_done); WRITE_ONCE(rtk->strict_idle_waiting, true); ret = apple_rtkit_strict_idle_state(rtk, true); + if (!ret && after_ap) + ret = after_ap(data); if (!ret) ret = apple_rtkit_strict_idle_state(rtk, false); if (!ret && !wait_for_completion_timeout(&rtk->strict_idle_done, @@ -2865,7 +3008,7 @@ int apple_rtkit_idle_strict(struct apple_rtkit *rtk) rtk->strict_idle_poisoned = true; return ret; } -EXPORT_SYMBOL_GPL(apple_rtkit_idle_strict); +EXPORT_SYMBOL_GPL(apple_rtkit_idle_strict_with); int apple_rtkit_warm_restart_strict(struct apple_rtkit *rtk) { @@ -2974,7 +3117,8 @@ int apple_rtkit_quiesce(struct apple_rtkit *rtk) } EXPORT_SYMBOL_GPL(apple_rtkit_quiesce); -static int apple_rtkit_wake_common(struct apple_rtkit *rtk, bool early_ap_power) +static int apple_rtkit_wake_common(struct apple_rtkit *rtk, bool early_ap_power, + bool reinit_iop_ack) { u64 msg; int ret; @@ -2982,7 +3126,8 @@ static int apple_rtkit_wake_common(struct apple_rtkit *rtk, bool early_ap_power) if (apple_rtkit_is_running(rtk)) return -EINVAL; - reinit_completion(&rtk->iop_pwr_ack_completion); + if (reinit_iop_ack) + reinit_completion(&rtk->iop_pwr_ack_completion); /* * Use open-coded apple_rtkit_set_iop_power_state since apple_rtkit_boot @@ -2999,13 +3144,79 @@ static int apple_rtkit_wake_common(struct apple_rtkit *rtk, bool early_ap_power) int apple_rtkit_wake(struct apple_rtkit *rtk) { - return apple_rtkit_wake_common(rtk, false); + return apple_rtkit_wake_common(rtk, false, true); } EXPORT_SYMBOL_GPL(apple_rtkit_wake); +/* Wait up to @ms for @c, polling the mailbox where waits poll it: true once it is done. */ +static int apple_rtkit_done_within(struct apple_rtkit *rtk, struct completion *c, + unsigned int ms) +{ + unsigned long deadline = jiffies + msecs_to_jiffies(ms); + long t; + + do { + if ((rtk->sync_syslog_ack || rtk->poll_waits) && apple_rtkit_poll(rtk) < 0) + break; + t = apple_rtkit_wait_timeout(rtk, c, msecs_to_jiffies(1)); + if (t < 0) + return t; + if (t > 0) + return 1; + } while (time_before(jiffies, deadline)); + + return try_wait_for_completion(c); +} + +/* + * Some firmware reports in by itself once its CPU runs and then acknowledges + * IOP power on by itself, answering no request for it after that; other + * firmware waits to be asked. Give the firmware up to @self_ack_ms to report in + * (its endpoint map, and CoreAnalytics where the ops need it) and again to + * acknowledge IOP power on; ask for IOP power as apple_rtkit_wake() does if it + * does neither. + */ +int apple_rtkit_boot_or_wake(struct apple_rtkit *rtk, unsigned int self_ack_ms) +{ + int ret; + + if (apple_rtkit_is_running(rtk)) + return -EINVAL; + if (rtk->crashed) + return -EINVAL; + + ret = apple_rtkit_done_within(rtk, &rtk->epmap_completion, self_ack_ms); + if (ret < 0) + return ret; + if (!ret || rtk->boot_result) + return apple_rtkit_wake(rtk); + if (apple_rtkit_needs_coreanalytics(rtk) && + test_bit(APPLE_RTKIT_EP_COREANALYTICS, rtk->endpoints)) { + ret = apple_rtkit_wait_for_completion(rtk, &rtk->coreanalytics_completion); + if (ret) { + dev_err(rtk->dev, "RTKit: CoreAnalytics readiness failed: %d\n", ret); + return ret; + } + } + + ret = apple_rtkit_done_within(rtk, &rtk->iop_pwr_ack_completion, self_ack_ms); + if (ret < 0) + return ret; + if (READ_ONCE(rtk->iop_power_state) == APPLE_RTKIT_PWR_STATE_ON) { + dev_dbg(rtk->dev, "RTKit: the IOP acknowledged power on by itself\n"); + return apple_rtkit_boot(rtk); + } + /* + * When !ret, iop_pwr_ack_completion was not signaled; keep it intact so + * a late self-ACK arriving before SET_IOP_PWR_STATE is not lost. + */ + return apple_rtkit_wake_common(rtk, false, ret != 0); +} +EXPORT_SYMBOL_GPL(apple_rtkit_boot_or_wake); + int apple_rtkit_wake_early_ap(struct apple_rtkit *rtk) { - return apple_rtkit_wake_common(rtk, true); + return apple_rtkit_wake_common(rtk, true, true); } EXPORT_SYMBOL_GPL(apple_rtkit_wake_early_ap); @@ -3456,6 +3667,21 @@ int apple_rtkit_wake_retained(struct apple_rtkit *rtk, int (*start)(void *), voi } EXPORT_SYMBOL_GPL(apple_rtkit_wake_retained); +/* + * After a sleep that took the co-processor's power, its mailbox's enables are gone with + * it: set them again before the co-processor is started, or its messages never arrive. + * The receive enable is one the boot loader sets on M1, which Linux doesn't set otherwise. + */ +int apple_rtkit_mbox_restore(struct apple_rtkit *rtk) +{ + int ret = apple_mbox_restore(rtk->mbox); + + if (!ret) + apple_mbox_set_recv_enabled(rtk->mbox, true); + return ret; +} +EXPORT_SYMBOL_GPL(apple_rtkit_mbox_restore); + void apple_rtkit_free(struct apple_rtkit *rtk) { apple_rtkit_stop_rx(rtk); @@ -3527,8 +3753,8 @@ struct apple_rtkit *devm_apple_rtkit_init_m5_saved(struct device *dev, void *coo struct apple_rtkit *rtk; int ret; - rtk = __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, false, - NULL, 0, true); + rtk = __apple_rtkit_init(dev, cookie, NULL, mbox_name, mbox_idx, ops, false, + NULL, 0, true, NULL); if (IS_ERR(rtk)) return rtk; ret = devm_add_action_or_reset(dev, apple_rtkit_free_wrapper, rtk); @@ -3549,3 +3775,7 @@ MODULE_AUTHOR("Sven Peter "); MODULE_DESCRIPTION("Apple RTKit driver"); #include "rtkit-v27-late.inc" + +#if IS_ENABLED(CONFIG_APPLE_RTKIT_KUNIT_TEST) +#include "rtkit-test.c" +#endif diff --git a/drivers/soc/apple/rtkit.kunitconfig b/drivers/soc/apple/rtkit.kunitconfig new file mode 100644 index 00000000000000..40593c9ce46bb3 --- /dev/null +++ b/drivers/soc/apple/rtkit.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_ARM64_16K_PAGES=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_APPLE_RTKIT_KUNIT_TEST=y diff --git a/drivers/soc/apple/sart-test.c b/drivers/soc/apple/sart-test.c new file mode 100644 index 00000000000000..2095aaf7c2d973 --- /dev/null +++ b/drivers/soc/apple/sart-test.c @@ -0,0 +1,952 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the Apple SART driver. Included by sart.c. + * + * The SART under test is a struct apple_sart whose register block is a + * zeroed buffer of kernel memory, as large as the widest layout (SARTv4). + * The tests call the driver's own entry points and compare the whole block + * with a model that encodes each entry independently of the driver's + * macros, so a write to a wrong register shows up as well as a wrong value. + * No device is probed and no MMIO is touched. + */ +#include +#include +#include + +#define SART_TEST_REGS_SIZE 0x100 +#define SART_TEST_NREGS (SART_TEST_REGS_SIZE / 4) +#define SART_TEST_PG(n) ((phys_addr_t)(n) << 12) + +/* What the test expects of each register layout, in numbers of its own */ +struct sart_test_ver { + const char *name; + struct apple_sart_ops *ops; + unsigned int paddr_reg; + /* 0: the size shares the config register with the flags */ + unsigned int size_reg; + u8 allow; + /* in 4K pages */ + u32 size_max; +}; + +static const struct sart_test_ver sart_test_vers[] = { + { "v0", &sart_ops_v0, 0x40, 0, 0x0f, 0x7ffff }, + { "v2", &sart_ops_v2, 0x40, 0, 0xff, 0xffffff }, + { "v3", &sart_ops_v3, 0x40, 0x80, 0xff, 0x3fffffff }, + { "v4", &sart_ops_v4, 0x60, 0xc0, 0xff, 0x3fffffff }, +}; + +static void sart_test_ver_desc(const struct sart_test_ver *v, char *desc) +{ + strscpy(desc, v->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(sart_test_ver, sart_test_vers, sart_test_ver_desc); + +struct sart_test { + struct apple_sart sart; + const struct sart_test_ver *ver; + __le32 *regs; + u32 expect[SART_TEST_NREGS]; + suspend_state_t pm_state; + unsigned int pm_flags; +}; + +static struct sart_test *sart_test_new(struct kunit *test, + const struct sart_test_ver *ver) +{ + /* A case may set up several SARTs: test->priv counts them */ + unsigned long nr = (unsigned long)test->priv; + struct sart_test *t; + struct device *dev; + char name[16]; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t); + t->regs = kunit_kzalloc(test, SART_TEST_REGS_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->regs); + snprintf(name, sizeof(name), "sart-test%lu", nr); + test->priv = (void *)(nr + 1); + dev = kunit_device_register(test, name); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + + t->ver = ver; + t->sart.dev = dev; + t->sart.ops = ver->ops; + t->sart.regs = (void __iomem __force *)t->regs; + dev_set_drvdata(dev, &t->sart); + + return t; +} + +static u32 sart_test_rd(struct sart_test *t, unsigned int reg) +{ + return le32_to_cpu(t->regs[reg / 4]); +} + +static void __maybe_unused sart_test_wr(struct sart_test *t, unsigned int reg, u32 val) +{ + t->regs[reg / 4] = cpu_to_le32(val); +} + +/* The model: entry idx holds these flags, address and size (in pages) */ +static void sart_test_model(struct sart_test *t, int idx, u8 flags, + u32 paddr_pg, u32 size_pg) +{ + const struct sart_test_ver *v = t->ver; + + if (v->size_reg) { + t->expect[idx] = flags; + t->expect[v->size_reg / 4 + idx] = size_pg; + } else { + t->expect[idx] = (u32)flags << 24 | size_pg; + } + t->expect[v->paddr_reg / 4 + idx] = paddr_pg; +} + +/* An entry that is in the registers before the driver sees them */ +static void sart_test_preload(struct sart_test *t, int idx, u8 flags, + u32 paddr_pg, u32 size_pg) +{ + int i; + + sart_test_model(t, idx, flags, paddr_pg, size_pg); + for (i = 0; i < SART_TEST_NREGS; i++) + t->regs[i] = cpu_to_le32(t->expect[i]); +} + +static void sart_test_check(struct kunit *test, struct sart_test *t) +{ + int i; + + for (i = 0; i < SART_TEST_NREGS; i++) + KUNIT_EXPECT_EQ_MSG(test, le32_to_cpu(t->regs[i]), t->expect[i], + "register %#x", 4 * i); +} + +static unsigned int sart_test_nonzero(struct sart_test *t) +{ + unsigned int n = 0; + int i; + + for (i = 0; i < SART_TEST_NREGS; i++) + n += !!t->regs[i]; + return n; +} + +static struct sart_test *sart_test_two_regions(struct kunit *test, int ver) +{ + struct sart_test *t = sart_test_new(test, &sart_test_vers[ver]); + + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(&t->sart, 0x812345000ULL, 0x40000)); + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(&t->sart, 0x9abcd000, 0x1000)); + return t; +} + +/* The register values of two added regions, written out for each layout */ +static void sart_test_add_encoding(struct kunit *test) +{ + struct sart_test *t; + + /* SARTv0: 5 bits of flags over a 19-bit size, addresses at 0x40 */ + t = sart_test_two_regions(test, 0); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x00), 0x0f000040); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x40), 0x00812345); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x04), 0x0f000001); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x44), 0x0009abcd); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 4); + + /* SARTv2: 8 bits of flags over a 24-bit size, addresses at 0x40 */ + t = sart_test_two_regions(test, 1); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x00), 0xff000040); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x40), 0x00812345); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x04), 0xff000001); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x44), 0x0009abcd); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 4); + + /* SARTv3: flags, addresses at 0x40, sizes at 0x80 */ + t = sart_test_two_regions(test, 2); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x00), 0xff); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x40), 0x00812345); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x80), 0x40); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x04), 0xff); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x44), 0x0009abcd); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x84), 0x1); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 6); + + /* SARTv4: flags, addresses at 0x60, sizes at 0xc0 */ + t = sart_test_two_regions(test, 3); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x00), 0xff); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x60), 0x00812345); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0xc0), 0x40); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x04), 0xff); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x64), 0x0009abcd); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0xc4), 0x1); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 6); +} + +/* Sixteen regions take the sixteen entries in order; the next is refused */ +static void sart_test_add_fills_table(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + int i; + + for (i = 0; i < 16; i++) { + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(&t->sart, + SART_TEST_PG(0x100000 + 0x100 * i), + SART_TEST_PG(i + 1))); + sart_test_model(t, i, t->ver->allow, 0x100000 + 0x100 * i, i + 1); + sart_test_check(test, t); + } + KUNIT_EXPECT_EQ(test, t->sart.used_entries, 0xffff); + + KUNIT_EXPECT_EQ(test, -EBUSY, + apple_sart_add_allowed_region(&t->sart, SART_TEST_PG(0x200000), + SART_TEST_PG(1))); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, t->sart.used_entries, 0xffff); +} + +/* The bootloader's entries are neither reused nor rewritten */ +static void sart_test_add_skips_protected(struct kunit *test) +{ + static const int slots[] = { 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; + struct sart_test *t = sart_test_new(test, test->param_value); + int i; + + sart_test_preload(t, 0, t->ver->allow, 0x800000, 0x400); + sart_test_preload(t, 1, 0x01, 0x900000, 0x10); + sart_test_preload(t, 5, t->ver->allow, 0xa00000, 0x1); + t->sart.protected_entries = BIT(0) | BIT(1) | BIT(5); + + for (i = 0; i < ARRAY_SIZE(slots); i++) { + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(&t->sart, + SART_TEST_PG(0x100000 + i), + SART_TEST_PG(1))); + sart_test_model(t, slots[i], t->ver->allow, 0x100000 + i, 1); + sart_test_check(test, t); + } + KUNIT_EXPECT_EQ(test, t->sart.used_entries, 0xffff & ~0x23); + + KUNIT_EXPECT_EQ(test, -EBUSY, + apple_sart_add_allowed_region(&t->sart, SART_TEST_PG(0x200000), + SART_TEST_PG(1))); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, t->sart.protected_entries, 0x23); +} + +/* A region that is not whole pages is refused and costs no entry */ +static void sart_test_add_rejects_unaligned(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000) + 0x800, + SART_TEST_PG(1))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000) + 1, + SART_TEST_PG(1))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000) + 0xfff, + SART_TEST_PG(1))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000), 0x1800)); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000), 0xfff)); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000), + SART_TEST_PG(1) + 1)); + KUNIT_EXPECT_EQ(test, sart->used_entries, 0); + sart_test_check(test, t); + + /* The first entry is still the next one handed out */ + KUNIT_EXPECT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000), + SART_TEST_PG(1))); + sart_test_model(t, 0, t->ver->allow, 0x1000, 1); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->used_entries, BIT(0)); +} + +/* The largest size the layout's field holds is taken, one page more is not */ +static void sart_test_add_size_max(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + size_t max = (size_t)t->ver->size_max << 12; + phys_addr_t paddr; + size_t size; + u8 flags; + + KUNIT_EXPECT_EQ(test, 0, apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000), max)); + sart_test_model(t, 0, t->ver->allow, 0x1000, t->ver->size_max); + sart_test_check(test, t); + + /* A full size field must not spill into the flags */ + sart->ops->get_entry(sart, 0, &flags, &paddr, &size); + KUNIT_EXPECT_EQ(test, flags, t->ver->allow); + KUNIT_EXPECT_EQ(test, size, max); + KUNIT_EXPECT_EQ(test, paddr, SART_TEST_PG(0x1000)); + + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x2000), + max + SART_TEST_PG(1))); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->used_entries, BIT(0)); +} + +/* The highest address the 32-bit page register holds, there and back */ +static void sart_test_high_paddr(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + phys_addr_t paddr; + size_t size; + u8 flags; + + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0xffffffff), + SART_TEST_PG(1))); + sart_test_model(t, 0, t->ver->allow, 0xffffffff, 1); + sart_test_check(test, t); + + sart->ops->get_entry(sart, 0, &flags, &paddr, &size); + KUNIT_EXPECT_EQ(test, paddr, 0xffffffff000ULL); + KUNIT_EXPECT_EQ(test, size, 0x1000); + + KUNIT_EXPECT_EQ(test, 0, + apple_sart_remove_allowed_region(sart, 0xffffffff000ULL, 0x1000)); + sart_test_model(t, 0, 0, 0, 0); + sart_test_check(test, t); +} + +/* get_entry reads what a bootloader left in any entry, the last included */ +static void sart_test_get_entry(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + phys_addr_t paddr; + size_t size; + u8 flags; + + sart_test_preload(t, 7, 0x05, 0x1, 0x1); + sart_test_preload(t, 15, t->ver->allow, 0xfedcba98, t->ver->size_max); + + sart->ops->get_entry(sart, 7, &flags, &paddr, &size); + KUNIT_EXPECT_EQ(test, flags, 0x05); + KUNIT_EXPECT_EQ(test, paddr, 0x1000); + KUNIT_EXPECT_EQ(test, size, 0x1000); + + sart->ops->get_entry(sart, 15, &flags, &paddr, &size); + KUNIT_EXPECT_EQ(test, flags, t->ver->allow); + KUNIT_EXPECT_EQ(test, paddr, 0xfedcba98000ULL); + KUNIT_EXPECT_EQ(test, size, (size_t)t->ver->size_max << 12); + + sart->ops->get_entry(sart, 8, &flags, &paddr, &size); + KUNIT_EXPECT_EQ(test, flags, 0); + KUNIT_EXPECT_EQ(test, paddr, 0); + KUNIT_EXPECT_EQ(test, size, 0); + + /* Reading changes nothing */ + sart_test_check(test, t); +} + +/* A removed region's entry reads empty and is the next one handed out */ +static void sart_test_remove_frees_slot(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + int i; + + for (i = 0; i < 3; i++) { + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000 + i), + SART_TEST_PG(2 + i))); + sart_test_model(t, i, t->ver->allow, 0x4000 + i, 2 + i); + } + + KUNIT_EXPECT_EQ(test, 0, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4001), + SART_TEST_PG(3))); + sart_test_model(t, 1, 0, 0, 0); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->used_entries, BIT(0) | BIT(2)); + + KUNIT_EXPECT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x7000), + SART_TEST_PG(8))); + sart_test_model(t, 1, t->ver->allow, 0x7000, 8); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->used_entries, 0x7); +} + +/* Only the exact address and size that were added can be removed, once */ +static void sart_test_remove_nonexistent(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_model(t, 0, t->ver->allow, 0x4000, 4); + + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x9000), + SART_TEST_PG(4))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(5))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(3))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4001), + SART_TEST_PG(4))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4000) + 1, + SART_TEST_PG(4))); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->used_entries, BIT(0)); + + KUNIT_EXPECT_EQ(test, 0, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_model(t, 0, 0, 0, 0); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->used_entries, 0); + + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_check(test, t); +} + +/* A bootloader's entry can't be removed, whatever address and size are asked */ +static void sart_test_remove_protected(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + + sart_test_preload(t, 3, t->ver->allow, 0x800000, 0x400); + sart->protected_entries = BIT(3); + + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x800000), + SART_TEST_PG(0x400))); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->protected_entries, BIT(3)); +} + +static void sart_test_inherited_region(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + const phys_addr_t base = SART_TEST_PG(0x80000); + const size_t len = SART_TEST_PG(0x10); + + sart_test_preload(t, 2, t->ver->allow, 0x80000, 0x10); + /* Allowed, but not the bootloader's */ + sart_test_preload(t, 4, t->ver->allow, 0x90000, 0x10); + /* The bootloader's, but with other flags */ + sart_test_preload(t, 6, 0x01, 0xa0000, 0x10); + sart->protected_entries = BIT(2) | BIT(6); + + KUNIT_EXPECT_TRUE(test, apple_sart_is_inherited_region(sart, base, len)); + KUNIT_EXPECT_TRUE(test, apple_sart_is_inherited_region(sart, base, 0x1000)); + KUNIT_EXPECT_TRUE(test, apple_sart_is_inherited_region(sart, base + len - 0x1000, + 0x1000)); + KUNIT_EXPECT_TRUE(test, apple_sart_is_inherited_region(sart, base + 1, 1)); + KUNIT_EXPECT_TRUE(test, apple_sart_is_inherited_region(sart, base + len - 1, 1)); + KUNIT_EXPECT_TRUE(test, apple_sart_is_inherited_region(sart, base + 1, len - 1)); + + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base, len + 1)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base + 1, len)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base + len, 1)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base - 1, 1)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base - 0x1000, + len + 0x1000)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base + len - 0x1000, + 0x2000)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base, 0)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, PHYS_ADDR_MAX, 2)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base, SIZE_MAX)); + + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, SART_TEST_PG(0x90000), + len)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, SART_TEST_PG(0xa0000), + len)); + sart_test_check(test, t); +} + +/* Shutdown empties every entry but the bootloader's */ +static void sart_test_shutdown(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + struct platform_device *pdev; + int i; + + pdev = kunit_kzalloc(test, sizeof(*pdev), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, pdev); + platform_set_drvdata(pdev, sart); + + sart_test_preload(t, 0, t->ver->allow, 0x800000, 0x400); + sart_test_preload(t, 15, t->ver->allow, 0x900000, 0x10); + /* Not the bootloader's and not handed out either */ + sart_test_preload(t, 12, t->ver->allow, 0xa00000, 0x10); + sart->protected_entries = BIT(0) | BIT(15); + for (i = 0; i < 3; i++) + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000 + i), + SART_TEST_PG(1))); + KUNIT_ASSERT_EQ(test, sart->used_entries, BIT(1) | BIT(2) | BIT(3)); + KUNIT_ASSERT_NE(test, sart_test_rd(t, 0x04), 0); + + apple_sart_shutdown(pdev); + + sart_test_model(t, 12, 0, 0, 0); + sart_test_check(test, t); +} + +/* Each compatible selects the register layout of its SART generation */ +static void sart_test_of_match(struct kunit *test) +{ + static const struct { + const char *compat; + int len; + const struct apple_sart_ops *ops; + } cases[] = { + { "apple,t8015-sart", 17, &sart_ops_v0 }, + { "apple,t8103-sart", 17, &sart_ops_v2 }, + { "apple,t6000-sart", 17, &sart_ops_v3 }, + { "apple,t6050-sart", 17, &sart_ops_v4 }, + { "apple,t8152-sart", 17, &sart_ops_v4 }, + /* A newer SoC falls back to the generation it is compatible with */ + { "apple,t8112-sart\0apple,t6000-sart", 34, &sart_ops_v3 }, + { "apple,t6020-sart\0apple,t6000-sart", 34, &sart_ops_v3 }, + }; + const struct of_device_id *match; + struct device_node *np; + struct property *prop; + int i; + + np = kunit_kzalloc(test, sizeof(*np), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, np); + prop = kunit_kzalloc(test, sizeof(*prop), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, prop); + prop->name = (char *)"compatible"; + np->properties = prop; + + for (i = 0; i < ARRAY_SIZE(cases); i++) { + prop->value = (void *)cases[i].compat; + prop->length = cases[i].len; + match = of_match_node(apple_sart_of_match, np); + KUNIT_ASSERT_NOT_NULL_MSG(test, match, "%s", cases[i].compat); + KUNIT_EXPECT_PTR_EQ_MSG(test, match->data, cases[i].ops, "%s", + cases[i].compat); + } + + prop->value = (void *)"apple,t8103-dart"; + prop->length = 17; + KUNIT_EXPECT_NULL(test, of_match_node(apple_sart_of_match, np)); +} + +/* A consumer without an apple,sart phandle has no SART */ +static void sart_test_get_no_phandle(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, &sart_test_vers[1]); + struct device *dev = t->sart.dev; + struct device_node *np; + struct apple_sart *sart; + + sart = devm_apple_sart_get(dev); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(sart), -ENODEV); + + np = kunit_kzalloc(test, sizeof(*np), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, np); + dev->of_node = np; + sart = devm_apple_sart_get(dev); + dev->of_node = NULL; + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(sart), -ENODEV); +} + +#ifdef CONFIG_SUSPEND +static void sart_test_pm_restore(void *data) +{ + struct sart_test *t = data; + + pm_suspend_target_state = t->pm_state; + pm_suspend_global_flags = t->pm_flags; +} + +/* Pretend the system is in a suspend to RAM that the firmware carries out */ +static void sart_test_pm_firmware_sleep(struct kunit *test, struct sart_test *t) +{ + t->pm_state = pm_suspend_target_state; + t->pm_flags = pm_suspend_global_flags; + KUNIT_ASSERT_EQ(test, 0, kunit_add_action_or_reset(test, sart_test_pm_restore, t)); + + pm_suspend_target_state = PM_SUSPEND_MEM; + pm_suspend_clear_flags(); + pm_set_suspend_via_firmware(); +} + +static void sart_test_snapshot(struct kunit *test, struct sart_test *t) +{ + sart_test_pm_firmware_sleep(test, t); + KUNIT_ASSERT_EQ(test, 0, apple_sart_suspend_late(t->sart.dev)); + KUNIT_ASSERT_TRUE(test, t->sart.saved_valid); +} + +/* The SART's power domain went off: every register reads zero */ +static void sart_test_power_loss(struct sart_test *t) +{ + memset(t->regs, 0, SART_TEST_REGS_SIZE); +} + +/* Only a suspend to RAM carried out by the firmware is snapshotted */ +static void sart_test_suspend_not_firmware(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_pm_firmware_sleep(test, t); + + pm_suspend_clear_flags(); + sart->saved_valid = true; + sart->replay_valid = true; + KUNIT_EXPECT_EQ(test, 0, apple_sart_suspend_late(sart->dev)); + KUNIT_EXPECT_FALSE(test, sart->saved_valid); + KUNIT_EXPECT_FALSE(test, sart->replay_valid); + + pm_set_suspend_via_firmware(); + pm_suspend_target_state = PM_SUSPEND_TO_IDLE; + KUNIT_EXPECT_EQ(test, 0, apple_sart_suspend_late(sart->dev)); + KUNIT_EXPECT_FALSE(test, sart->saved_valid); + + /* Without a snapshot the wake writes nothing */ + sart_test_power_loss(t); + pm_set_resume_via_firmware(); + KUNIT_EXPECT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 0); + KUNIT_EXPECT_FALSE(test, sart->replay_valid); +} + +/* After a firmware sleep every entry is back, the bootloader's included */ +static void sart_test_suspend_resume(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + + sart_test_preload(t, 0, t->ver->allow, 0x800000, 0x400); + sart_test_preload(t, 15, t->ver->allow, 0xfedcba98, t->ver->size_max); + sart->protected_entries = BIT(0) | BIT(15); + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_model(t, 1, t->ver->allow, 0x4000, 4); + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x812345), + SART_TEST_PG(0x40))); + sart_test_model(t, 2, t->ver->allow, 0x812345, 0x40); + + sart_test_snapshot(test, t); + sart_test_check(test, t); + sart_test_power_loss(t); + + /* A wake that the firmware did not carry out leaves the SART alone */ + KUNIT_EXPECT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 0); + KUNIT_EXPECT_TRUE(test, sart->saved_valid); + + pm_set_resume_via_firmware(); + KUNIT_EXPECT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + sart_test_check(test, t); + KUNIT_EXPECT_FALSE(test, sart->saved_valid); + KUNIT_EXPECT_TRUE(test, sart->replay_valid); + KUNIT_EXPECT_EQ(test, sart->used_entries, BIT(1) | BIT(2)); + + /* The snapshot is used once */ + sart_test_power_loss(t); + KUNIT_EXPECT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 0); +} + +/* + * What the wake does with entries nobody uses that don't read empty after the + * sleep. Before SARTv4 they are left alone. SARTv4 empties them again, except + * the last one, which is only written when in use or whole in the snapshot. + */ +static void sart_test_resume_idle_entries(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + bool v4 = t->ver->ops == &sart_ops_v4; + + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_model(t, 0, t->ver->allow, 0x4000, 4); + sart_test_snapshot(test, t); + + sart_test_power_loss(t); + /* Left behind by the power-up in entries 5 and 15 */ + sart_test_wr(t, 0x14, t->ver->size_reg ? 0xff : 0xff000000); + sart_test_wr(t, t->ver->paddr_reg + 0x14, 0x1234); + sart_test_wr(t, 0x3c, t->ver->size_reg ? 0xff : 0xff000000); + if (!v4) { + t->expect[0x14 / 4] = sart_test_rd(t, 0x14); + t->expect[(t->ver->paddr_reg + 0x14) / 4] = 0x1234; + } + t->expect[0x3c / 4] = sart_test_rd(t, 0x3c); + + pm_set_resume_via_firmware(); + KUNIT_EXPECT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + sart_test_check(test, t); +} + +/* The last entry is written back like any other when a driver uses it */ +static void sart_test_resume_last_in_use(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + int i; + + for (i = 0; i < 16; i++) { + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000 + i), + SART_TEST_PG(1 + i))); + sart_test_model(t, i, t->ver->allow, 0x4000 + i, 1 + i); + } + sart_test_snapshot(test, t); + sart_test_power_loss(t); + sart_test_wr(t, 0x3c, t->ver->size_reg ? 0xff : 0xff000000); + + pm_set_resume_via_firmware(); + KUNIT_EXPECT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + sart_test_check(test, t); +} + +/* The replay before a coprocessor's run bit: SARTv3 and SARTv4, after a wake */ +static void sart_test_replay(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + bool v3 = t->ver->size_reg; + + sart_test_preload(t, 0, t->ver->allow, 0x800000, 0x400); + sart->protected_entries = BIT(0); + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x812345), + SART_TEST_PG(0x40))); + sart_test_model(t, 1, t->ver->allow, 0x812345, 0x40); + + /* No sleep yet: nothing to replay */ + KUNIT_EXPECT_EQ(test, -EOPNOTSUPP, apple_sart_replay(sart)); + + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, -EOPNOTSUPP, apple_sart_replay(sart)); + sart_test_power_loss(t); + pm_set_resume_via_firmware(); + KUNIT_ASSERT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + sart_test_check(test, t); + + /* The coprocessor's domain cycled once more after the wake */ + sart_test_power_loss(t); + if (!v3) { + KUNIT_EXPECT_EQ(test, -EOPNOTSUPP, apple_sart_replay(sart)); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 0); + return; + } + KUNIT_EXPECT_EQ(test, 0, apple_sart_replay(sart)); + sart_test_check(test, t); + + /* An entry that does not hold what was written is counted */ + sart->saved[1].paddr |= BIT_ULL(50); + KUNIT_EXPECT_EQ(test, 1, apple_sart_replay(sart)); + sart_test_check(test, t); +} + +/* The check before a sleep exists on SARTv4 only, and needs the snapshot */ +static void sart_test_sleep_validate_unsupported(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + bool v4 = t->ver->ops == &sart_ops_v4; + + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + KUNIT_EXPECT_EQ(test, -EOPNOTSUPP, apple_sart_sleep_validate(sart)); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, v4 ? 0 : -EOPNOTSUPP, apple_sart_sleep_validate(sart)); +} + +static struct sart_test *sart_test_validate_new(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, &sart_test_vers[3]); + struct apple_sart *sart = &t->sart; + + sart_test_preload(t, 0, 0xff, 0x800000, 0x400); + sart->protected_entries = BIT(0); + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_model(t, 1, 0xff, 0x4000, 4); + return t; +} + +/* Entries that moved after the snapshot refuse the sleep */ +static void sart_test_sleep_validate_changed(struct kunit *test) +{ + struct sart_test *t = sart_test_validate_new(test); + struct apple_sart *sart = &t->sart; + + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, 0, apple_sart_sleep_validate(sart)); + + /* Entry 1: address, size, flags; then an idle entry that appeared */ + sart_test_wr(t, 0x64, 0x4001); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + sart_test_wr(t, 0x64, 0x4000); + KUNIT_EXPECT_EQ(test, 0, apple_sart_sleep_validate(sart)); + + sart_test_wr(t, 0xc4, 5); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + sart_test_wr(t, 0xc4, 4); + + sart_test_wr(t, 0x04, 0x7f); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + sart_test_wr(t, 0x04, 0xff); + + sart_test_wr(t, 0x3c, 0xff); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + sart_test_wr(t, 0x3c, 0); + + KUNIT_EXPECT_EQ(test, 0, apple_sart_sleep_validate(sart)); + /* The check is read-only */ + sart_test_check(test, t); + KUNIT_EXPECT_TRUE(test, sart->saved_valid); +} + +/* Flags without a range: fine in an entry nobody uses, not in anyone's */ +static void sart_test_sleep_validate_flags_only(struct kunit *test) +{ + struct sart_test *t = sart_test_validate_new(test); + struct apple_sart *sart = &t->sart; + + sart_test_wr(t, 0x3c, 0xff); + sart_test_wr(t, 0x14, 0x01); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, 0, apple_sart_sleep_validate(sart)); + + /* The same in the bootloader's entry */ + sart->protected_entries |= BIT(15); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + sart->protected_entries &= ~BIT(15); + + /* The same in a driver's entry */ + sart->used_entries |= BIT(5); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + sart->used_entries &= ~BIT(5); + KUNIT_EXPECT_EQ(test, 0, apple_sart_sleep_validate(sart)); +} + +/* Half an entry refuses the sleep, whoever's it is */ +static void sart_test_sleep_validate_half_set(struct kunit *test) +{ + struct sart_test *t; + struct apple_sart *sart; + + /* Idle: flags and an address, no size */ + t = sart_test_validate_new(test); + sart = &t->sart; + sart_test_wr(t, 0x14, 0xff); + sart_test_wr(t, 0x74, 0x1234); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + + /* Idle: a range, no flags */ + t = sart_test_validate_new(test); + sart = &t->sart; + sart_test_wr(t, 0x74, 0x1234); + sart_test_wr(t, 0xd4, 0x10); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + + /* A driver's: flags, no size */ + t = sart_test_validate_new(test); + sart = &t->sart; + sart_test_wr(t, 0xc4, 0); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); +} + +/* An entry that is someone's and reads empty refuses the sleep */ +static void sart_test_sleep_validate_in_use_empty(struct kunit *test) +{ + struct sart_test *t; + struct apple_sart *sart; + + t = sart_test_validate_new(test); + sart = &t->sart; + sart_test_wr(t, 0x04, 0); + sart_test_wr(t, 0x64, 0); + sart_test_wr(t, 0xc4, 0); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + + t = sart_test_validate_new(test); + sart = &t->sart; + sart_test_wr(t, 0x00, 0); + sart_test_wr(t, 0x60, 0); + sart_test_wr(t, 0xc0, 0); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); +} +#endif /* CONFIG_SUSPEND */ + +static struct kunit_case sart_test_cases[] = { + KUNIT_CASE(sart_test_add_encoding), + KUNIT_CASE_PARAM(sart_test_add_fills_table, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_add_skips_protected, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_add_rejects_unaligned, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_add_size_max, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_high_paddr, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_get_entry, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_remove_frees_slot, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_remove_nonexistent, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_remove_protected, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_inherited_region, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_shutdown, sart_test_ver_gen_params), + KUNIT_CASE(sart_test_of_match), + KUNIT_CASE(sart_test_get_no_phandle), +#ifdef CONFIG_SUSPEND + KUNIT_CASE_PARAM(sart_test_suspend_not_firmware, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_suspend_resume, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_resume_idle_entries, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_resume_last_in_use, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_replay, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_sleep_validate_unsupported, sart_test_ver_gen_params), + KUNIT_CASE(sart_test_sleep_validate_changed), + KUNIT_CASE(sart_test_sleep_validate_flags_only), + KUNIT_CASE(sart_test_sleep_validate_half_set), + KUNIT_CASE(sart_test_sleep_validate_in_use_empty), +#endif + {} +}; + +static struct kunit_suite sart_test_suite = { + .name = "apple-sart", + .test_cases = sart_test_cases, +}; +kunit_test_suite(sart_test_suite); diff --git a/drivers/soc/apple/sart.c b/drivers/soc/apple/sart.c index 34ce3ac0e2bb2d..14c0e65d19cbbe 100644 --- a/drivers/soc/apple/sart.c +++ b/drivers/soc/apple/sart.c @@ -98,6 +98,10 @@ struct apple_sart { size_t size; } saved[APPLE_SART_MAX_ENTRIES]; bool saved_valid; + /* saved[] filled by apple_sart_save_now() for this sleep */ + bool saved_early; + /* ... and not written back yet: apple_sart_restore_early() */ + bool early_pending; /* saved[] still holds the last sleep's entries, for apple_sart_replay() */ bool replay_valid; }; @@ -430,6 +434,54 @@ static bool apple_sart_wake_writes(struct apple_sart *sart, int i) return sart->saved[i].size && sart->saved[i].flags; } +/* + * For a coprocessor that gates its SART itself as it powers down for the sleep: its + * driver saves the entries before that, and the late suspend keeps them. + */ +void apple_sart_save_now(struct apple_sart *sart) +{ + int i; + + for (i = 0; i < APPLE_SART_MAX_ENTRIES; i++) + sart->ops->get_entry(sart, i, &sart->saved[i].flags, + &sart->saved[i].paddr, &sart->saved[i].size); + sart->saved_early = true; + sart->early_pending = true; +} +EXPORT_SYMBOL_GPL(apple_sart_save_now); + +static unsigned int apple_sart_write_saved(struct apple_sart *sart) +{ + unsigned int restored = 0; + int i; + + for (i = 0; i < APPLE_SART_MAX_ENTRIES; i++) { + if (!apple_sart_wake_writes(sart, i)) + continue; + sart->ops->set_entry(sart, i, sart->saved[i].flags, + sart->saved[i].paddr >> sart->ops->paddr_shift, + sart->saved[i].size >> sart->ops->size_shift); + restored++; + } + return restored; +} + +/* + * After apple_sart_save_now(), when the sleep didn't happen: its coprocessor gated the SART + * all the same, so its driver writes the entries back once the SART answers again. Nothing + * to do when the wake has written them already. + */ +void apple_sart_restore_early(struct apple_sart *sart) +{ + sart->saved_early = false; + if (!sart->early_pending) + return; + sart->early_pending = false; + dev_info(sart->dev, "%u entries written back after a sleep that didn't happen\n", + apple_sart_write_saved(sart)); +} +EXPORT_SYMBOL_GPL(apple_sart_restore_early); + /* * A SART in a domain that a firmware-driven suspend powers off comes back empty, * and its coprocessor can't reach its firmware or buffers until the entries are @@ -440,6 +492,13 @@ static int apple_sart_suspend_late(struct device *dev) struct apple_sart *sart = dev_get_drvdata(dev); int i; + if (sart->saved_early) { + sart->saved_early = false; + sart->replay_valid = false; + sart->saved_valid = pm_suspend_target_state == PM_SUSPEND_MEM && + pm_suspend_via_firmware(); + return 0; + } sart->saved_valid = false; sart->replay_valid = false; if (pm_suspend_target_state != PM_SUSPEND_MEM || !pm_suspend_via_firmware()) @@ -456,21 +515,14 @@ static int apple_sart_suspend_late(struct device *dev) static int apple_sart_resume_noirq(struct device *dev) { struct apple_sart *sart = dev_get_drvdata(dev); - unsigned int restored = 0; - int i; + unsigned int restored; if (!sart->saved_valid || !pm_resume_via_firmware()) return 0; sart->saved_valid = false; + sart->early_pending = false; - for (i = 0; i < APPLE_SART_MAX_ENTRIES; i++) { - if (!apple_sart_wake_writes(sart, i)) - continue; - sart->ops->set_entry(sart, i, sart->saved[i].flags, - sart->saved[i].paddr >> sart->ops->paddr_shift, - sart->saved[i].size >> sart->ops->size_shift); - restored++; - } + restored = apple_sart_write_saved(sart); dev_dbg(dev, "%u entries restored after sleep\n", restored); sart->replay_valid = true; @@ -575,6 +627,10 @@ static const struct of_device_id apple_sart_of_match[] = { .compatible = "apple,t6050-sart", .data = &sart_ops_v4, }, + { + .compatible = "apple,t8152-sart", + .data = &sart_ops_v4, + }, { .compatible = "apple,t6000-sart", .data = &sart_ops_v3, @@ -605,3 +661,7 @@ module_platform_driver(apple_sart_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Sven Peter "); MODULE_DESCRIPTION("Apple SART driver"); + +#if IS_ENABLED(CONFIG_APPLE_SART_KUNIT_TEST) +#include "sart-test.c" +#endif diff --git a/drivers/soc/apple/sart.kunitconfig b/drivers/soc/apple/sart.kunitconfig new file mode 100644 index 00000000000000..88ab5d0cf2be34 --- /dev/null +++ b/drivers/soc/apple/sart.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_PM=y +CONFIG_SUSPEND=y +CONFIG_APPLE_SART=y +CONFIG_APPLE_SART_KUNIT_TEST=y diff --git a/drivers/soc/apple/sbio.rs b/drivers/soc/apple/sbio.rs index 358dd8864c7f2b..1ce3134a42653b 100644 --- a/drivers/soc/apple/sbio.rs +++ b/drivers/soc/apple/sbio.rs @@ -2552,11 +2552,11 @@ impl SepData { } /// Whether the verify this work item runs is still wanted: not cancelled, - /// not ended by a suspend and not closed. + /// not ended by a suspend and not closed, and, for a touch-gated + /// `/dev/sep-key` call, not given up for `/dev/sep-bio` (see + /// [`Self::capture_live`]). fn verify_wanted(&self) -> bool { - !self.shutting_down.load(Relaxed) - && ((self.key_touch_active.load(Relaxed) && !self.key_touch_cancel.load(Relaxed)) - || bio::verify_is_live(&self.bio_session.lock(), self.capture_epoch.load(Relaxed))) + !self.shutting_down.load(Relaxed) && self.capture_live() } // Every verify registers the sensor again. On a profile with a nonce @@ -3071,10 +3071,9 @@ impl SepData { return bio::VerifyOutcome::Failed(ENROL_STATUS_SENSOR); } CaptureWait::Abandon => { - // A cancelled verify also abandons; only a live one is a fault. - if self.key_touch_active.load(Relaxed) - || bio::verify_is_live(&self.bio_session.lock(), self.capture_epoch.load(Relaxed)) - { + // A cancelled or given-up capture also abandons; only one + // still wanted is a fault. + if self.capture_live() { dev_err_ratelimited!( self.dev, "verify: the sensor status became unreadable during the capture\n" diff --git a/drivers/soc/apple/sensor.rs b/drivers/soc/apple/sensor.rs index 5e6a96afb43ecd..19c157f0f3f0b5 100644 --- a/drivers/soc/apple/sensor.rs +++ b/drivers/soc/apple/sensor.rs @@ -842,6 +842,11 @@ pub(crate) fn read_capture(length: u32) -> core::result::Result core::result::Result, + /// Told at device suspend (no sleep core commit, T6041) rather than staged for the commit. + sleep_at_suspend: Atomic, + /// The enclave didn't answer a sleep request or a wake this boot: no deep sleep until a + /// reboot, as a commit over a running enclave resets the SoC. + sleep_unanswered: Atomic, #[pin] ool_xarm: Mutex>, @@ -822,6 +830,21 @@ struct SepData { stac_layout: Atomic, stac_absent_logged: Atomic, + // The HDCP endpoint (see `hdcp`): its buffers, the sessions per slot + // (held for a whole step, so one exchange is in flight), the reply wait, + // discovery state, and quarantine flag. + #[pin] + ool_hdcp: Mutex>, + #[pin] + hdcp_state: Mutex, + #[pin] + hdcp_rx: Mutex, + #[pin] + hdcp_wq: CondVar, + hdcp_named: Atomic, + hdcp_layout: Atomic, + hdcp_quarantined: Atomic, + // The boot-policy endpoint (see `pnon`): its buffers, its one // exchange, and what discovery said about it. #[pin] @@ -1080,6 +1103,12 @@ impl SepData { stac::OOL_SIZE_STAC, (stac::OOL_SIZE_STAC, stac::OOL_SIZE_STAC), )?; + let ool_hdcp = Self::alloc_ool( + dev, + hdcp::EP_HDCP, + hdcp::OOL_SIZE_HDCP, + (hdcp::OOL_SIZE_HDCP, hdcp::OOL_SIZE_HDCP), + )?; // Sized from the endpoint's layout before it is registered. let ool_pnon = Self::alloc_ool(dev, pnon::EP_PNON, pnon::OOL_SIZE_PNON, (0, 0))?; let dma_ring = dma::Coherent::::zeroed_slice(dev, DMA_RING_SIZE, GFP_KERNEL)?; @@ -1226,6 +1255,8 @@ impl SepData { phase: Atomic::new(PHASE_ATTACH), sleep_gate: Atomic::new(pm::SleepGate::Open as u32), sleep_rx_held: Atomic::new(false), + sleep_at_suspend: Atomic::new(false), + sleep_unanswered: Atomic::new(false), ool_xarm <- new_mutex!(Some(ool_xarm)), ool_sbio <- new_mutex!(Some(ool_sbio)), ool_sks <- new_mutex!(Some(ool_sks)), @@ -1242,6 +1273,13 @@ impl SepData { stac_named: Atomic::new(false), stac_layout: Atomic::new(0), stac_absent_logged: Atomic::new(false), + ool_hdcp <- new_mutex!(Some(ool_hdcp)), + hdcp_state <- new_mutex!(hdcp::State::new()), + hdcp_rx <- new_mutex!(hdcp::Exchange::new()), + hdcp_wq <- new_condvar!("SepData::hdcp_wq"), + hdcp_named: Atomic::new(false), + hdcp_layout: Atomic::new(0), + hdcp_quarantined: Atomic::new(false), ool_pnon <- new_mutex!(Some(ool_pnon)), pnon_rx <- new_mutex!(pnon::Exchange::new()), pnon_wq <- new_condvar!("SepData::pnon_wq"), @@ -1543,6 +1581,10 @@ impl SepData { /// Prepare a firmware-driven suspend without sending SLEEP. The platform /// owns the irreversible request, after every returnable refusal. pub(crate) fn sleep_enter(&self) -> Result<()> { + // T6041: its sleep driver has no sleep core commit, so the enclave is told now. + if !pm::platform_commit() { + return self.sleep_enter_at_suspend(); + } match self.sleep_gate() { // A failed earlier wake is not repaired by another precommit attempt. pm::SleepGate::Lost => return Err(EIO), @@ -1557,6 +1599,14 @@ impl SepData { ); return Err(EBUSY); } + // Refused here, at once, rather than at the commit after its send wait. + if !self.mailbox_drains() { + dev_err_ratelimited!( + self.dev, + "deep sleep refused: the enclave isn't taking messages (its mailbox stays full)\n" + ); + return Err(EBUSY); + } self.set_sleep_gate(pm::SleepGate::Draining); let idle = control::wait_idle( @@ -1586,6 +1636,195 @@ impl SepData { Ok(()) } + /// Without a sleep core commit (T6041): tell the enclave at device suspend, seconds before + /// the platform's commit, which answers, saves its state and gates its own domain (waited + /// for in suspend_noirq). A deep sleep commits only over an enclave that is asleep. + fn sleep_enter_at_suspend(&self) -> Result<()> { + if self.sleep_unanswered.load(Relaxed) { + dev_err_ratelimited!( + self.dev, + "deep sleep refused: the enclave did not answer a sleep request or wake earlier this boot\n" + ); + return Err(EBUSY); + } + match self.sleep_gate() { + // Gated already at an earlier, refused sleep: it stays asleep until a real wake. + pm::SleepGate::Lost if self.sleep_at_suspend.load(Relaxed) => return Ok(()), + pm::SleepGate::Lost => { + dev_err_ratelimited!( + self.dev, + "deep sleep refused: the enclave did not come back from a sleep earlier this boot\n" + ); + return Err(EBUSY); + } + pm::SleepGate::Open => {} + _ => return Err(EBUSY), + } + // One that didn't come up still runs: a commit over it resets the SoC. + if self.phase.load(Relaxed) != PHASE_READY || !self.endpoint_present(proto::EP_CONTROL) { + dev_err_ratelimited!( + self.dev, + "deep sleep refused: the enclave did not finish coming up, so it can't be put to sleep\n" + ); + return Err(EBUSY); + } + if !self.mailbox_drains() { + dev_err_ratelimited!( + self.dev, + "deep sleep refused: the enclave isn't taking messages (its mailbox stays full)\n" + ); + return Err(EBUSY); + } + + self.set_sleep_gate(pm::SleepGate::Draining); + let idle = control::wait_idle( + proto::CONTROL_TIMEOUT_MS, + 10, + || self.control.lock().requests_in_flight(), + |ms| kernel::time::delay::fsleep(kernel::time::Delta::from_millis(i64::from(ms))), + ); + if !idle { + dev_err_ratelimited!( + self.dev, + "sleep refused: a request is still waiting for its reply\n" + ); + self.set_sleep_gate(pm::SleepGate::Open); + return Err(EBUSY); + } + + if let Err(e) = pm::dart_prepare(&self.dev) { + dev_err_ratelimited!( + self.dev, + "sleep refused: its DART could not be saved ({:?})\n", + e + ); + self.set_sleep_gate(pm::SleepGate::Open); + return Err(e); + } + + self.sleep_at_suspend.store(true, Relaxed); + match self.sleep_request() { + Ok(()) => { + if let Some(mbox) = self.mbox.lock().as_ref() { + mbox.set_recv_enabled(false); + } + self.sleep_hold_rx(); + self.set_sleep_gate(pm::SleepGate::Told); + dev_dbg!(self.dev, "the enclave answered the sleep request\n"); + Ok(()) + } + Err(e) => { + dev_err_ratelimited!( + self.dev, + "sleep refused: no answer to the sleep request ({:?})\n", + e + ); + self.sleep_unanswered.store(true, Relaxed); + // A request that timed out may still have been taken. + self.set_sleep_gate(pm::SleepGate::Told); + self.sleep_exit(); + Err(e) + } + } + } + + /// Asks the enclave to go to sleep (told at suspend). The request is sent past the gate. + fn sleep_request(&self) -> Result<()> { + let op = proto::op_sleep(); + let tag = proto::TAG_SLEEP; + let idx = self.control.lock().alloc_sleep()?; + let msg = proto::encode_control(&op, tag); + + let sent = match self.mbox.lock().as_ref() { + Some(mbox) => Self::ring(mbox, msg), + None => Err(ENODEV), + }; + if let Err(e) = sent { + self.control.lock().abandon(idx); + return Err(e); + } + match self.control_wait(&op, idx, tag)? { + Some(_) => Ok(()), + None => Err(ETIMEDOUT), + } + } + + /// The wake of an enclave told at suspend: a real wake starts it, a refused sleep finds + /// it gated (it stays asleep until the next real sleep) or asks whether it still answers. + fn sleep_exit_at_suspend(&self) -> bool { + let gate = self.sleep_gate(); + if gate == pm::SleepGate::Draining { + self.set_sleep_gate(pm::SleepGate::Open); + return false; + } + if !gate.needs_wake() { + return false; + } + // SAFETY: only reads a flag. + let real = unsafe { bindings::pm_resume_via_firmware() }; + if !real && gate == pm::SleepGate::Lost { + return false; + } + let answered = if real { + self.sleep_kick() + } else if pm::wait_gated(&self.dev) { + self.sleep_hold_rx(); + self.set_sleep_gate(pm::SleepGate::Lost); + dev_warn_ratelimited!( + self.dev, + "the enclave stays asleep until the next real sleep or a reboot\n" + ); + return false; + } else { + dev_warn_ratelimited!(self.dev, "the enclave never gated its power domain\n"); + self.sleep_probe() + }; + match answered { + Ok(()) => { + self.sleep_at_suspend.store(false, Relaxed); + self.set_sleep_gate(pm::SleepGate::Open); + // One line per sleep it was told of: nothing else says it came back. + dev_info_ratelimited!(self.dev, "the enclave is back from its sleep request\n"); + true + } + Err(e) => { + dev_err_ratelimited!( + self.dev, + "the enclave did not come back ({:?}); it stays unused\n", + e + ); + self.sleep_unanswered.store(true, Relaxed); + self.sleep_hold_rx(); + self.set_sleep_gate(pm::SleepGate::Lost); + false + } + } + } + + /// Whether an enclave that was told and never gated still answers. + fn sleep_probe(&self) -> Result<()> { + pm::dart_restore(&self.dev); + self.sleep_release_rx(); + let op = proto::op_nop(0); + let (idx, tag) = self.control.lock().alloc()?; + let msg = proto::encode_control(&op, tag); + let sent = match self.mbox.lock().as_ref() { + Some(mbox) => { + mbox.set_recv_enabled(true); + Self::ring(mbox, msg) + } + None => Err(ENODEV), + }; + if let Err(e) = sent { + self.control.lock().abandon(idx); + return Err(e); + } + match self.control_wait(&op, idx, tag)? { + Some(_) => Ok(()), + None => Err(ETIMEDOUT), + } + } + /// Stage without sending; the platform's commit owns SLEEP with IRQs off. fn sleep_leave_for_commit(&self) -> Result<()> { let request = proto::encode_control(&proto::op_sleep(), proto::TAG_SLEEP); @@ -1604,6 +1843,20 @@ impl SepData { Ok(()) } + /// Whether the enclave takes messages: its receive FIFO drains within `MAILBOX_DRAIN_MS`. A + /// FIFO that stays full means it stopped reading, and a sleep request would only time out. + fn mailbox_drains(&self) -> bool { + for _ in 0..MAILBOX_DRAIN_MS / 5 { + match self.mbox.lock().as_ref() { + Some(mbox) if mbox.send_ready() => return true, + Some(_) => {} + None => return false, + } + kernel::time::delay::fsleep(kernel::time::Delta::from_millis(5)); + } + false + } + /// Holds off the receive interrupt, whose handler reads the mailbox. fn sleep_hold_rx(&self) { if !self.sleep_rx_held.xchg(true, Relaxed) { @@ -1625,6 +1878,9 @@ impl SepData { /// A sent request can be restarted only after actual physical sleep/wake. /// Returns whether the enclave came back from a sleep it was told of. pub(crate) fn sleep_exit(&self) -> bool { + if self.sleep_at_suspend.load(Relaxed) { + return self.sleep_exit_at_suspend(); + } // Staged only: an unsent refusal releases RX without a restart. match pm::commit_finish(&self.dev) { Some(true) => self.set_sleep_gate(pm::SleepGate::Told), @@ -2779,10 +3035,9 @@ impl SepData { match self.scrd_command(&crate::scrd::scrd_context_delete(handle)) { Some((0, _)) => Ok(()), other => { - self.key_context_failed.store(true, Relaxed); dev_warn_ratelimited!( self.dev, - "scrd: deleting the unlock evaluation answered {:?}; private key operations disabled until reboot\n", + "scrd: deleting the unlock evaluation answered {:?}\n", other.map(|(status, _)| status) ); Err(EIO) @@ -3140,6 +3395,8 @@ impl SepData { stac::EP_STAC => self.on_stac(msg), + hdcp::EP_HDCP => self.on_hdcp(msg), + pnon::EP_PNON => self.on_pnon(msg), sse::EP_SSE => self.on_sse(msg), @@ -3194,6 +3451,7 @@ impl SepData { proto::DISCOVER_TYPE_DESCRIPTOR | proto::DISCOVER_TYPE_CONFIG => { let _ = table.slot(f.param); self.stac_discovered(&f); + self.hdcp_discovered(&f); self.pnon_discovered(&f); self.sse_discovered(&f); self.hibe_discovered(&f); @@ -3232,12 +3490,14 @@ impl SepData { self.sbio_wq.notify_all(); self.sks_wq.notify_all(); self.scrd_wq.notify_all(); + self.hdcp_wq.notify_all(); pm::unregister(); // Release any capture start still held for a resume that will not be // reported now. self.sleep_finished(); trusted::unregister(); self.unregister_fv_kernel(); + self.unregister_hdcp_kernel(); let dev = self.bio_dev.lock().take(); drop(dev); @@ -3289,6 +3549,7 @@ impl SepData { &self.ool_sks, &self.ool_scrd, &self.ool_stac, + &self.ool_hdcp, &self.ool_pnon, ] { if let Some(buffers) = slot.lock().take() { @@ -3602,6 +3863,12 @@ impl platform::Driver for SepDriver { } } + // The display driver's HDCP 2.2 transmitter service. Nothing is sent + // to the endpoint until the display driver starts a session. + if let Err(e) = data.register_hdcp_kernel() { + dev_warn_ratelimited!(dev, "hdcp: could not register the kernel API: {:?}\n", e); + } + if module_parameters::trusted_keys.value() != 0 { if let Err(e) = trusted::register(data.clone()) { dev_warn_ratelimited!(data.dev, "trusted-keys: registration failed ({:?})\n", e); diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index 0cd4c6b9bd5ce7..86325f940adb56 100644 --- a/drivers/soc/apple/shim.h +++ b/drivers/soc/apple/shim.h @@ -33,6 +33,8 @@ int sep_pm_keep_domains(void *dev); int sep_pm_wait_gated(void *dev, unsigned int timeout_ms); int sep_pm_clear_dev_disable(void *dev); void sep_pm_dart_restore(void *dev); +int sep_pm_dart_prepare(void *dev); +bool sep_pm_platform_commit(void); int sep_pm_commit_prepare(void *dev, void *mbox, u64 msg0, u32 msg1, u64 reply, u64 mask); int sep_pm_commit_finish(void *dev); extern const struct dev_pm_ops sep_pm_ops; @@ -55,6 +57,7 @@ void *sep_store_open_trunc(const char *path); void *sep_store_open_writable_existing(const char *path); void *sep_store_open_ro(const char *path); void *sep_store_open_block(const char *path, int writable); +void *sep_store_open_internal_block(const char *path, int writable); void sep_store_close(void *handle); long long sep_store_size(void *handle); long sep_store_read(void *handle, long long off, void *buf, size_t len); @@ -304,11 +307,38 @@ unsigned int sep_tk_blob_len(const struct trusted_key_payload *p); void sep_tk_set_blob_len(struct trusted_key_payload *p, unsigned int n); +/* -- hdcp_shim.c ------------------------------------------------------- */ + +enum sep_hdcp_step { + SEP_HDCP_STEP_OPEN = 0, + SEP_HDCP_STEP_AKE_CERT = 1, + SEP_HDCP_STEP_H_PRIME = 2, + SEP_HDCP_STEP_PAIRING = 3, + SEP_HDCP_STEP_LC_INIT = 4, + SEP_HDCP_STEP_L_PRIME = 5, + SEP_HDCP_STEP_SKE = 6, + SEP_HDCP_STEP_RECEIVER_LIST = 7, + SEP_HDCP_STEP_STREAM = 8, + SEP_HDCP_STEP_FINISH = 9, + SEP_HDCP_STEP_ENCRYPTION_ON = 10, + SEP_HDCP_STEP_ENCRYPTION_OFF = 11, +}; + +struct sep_hdcp_ops { + bool (*available)(void *context); + int (*step)(void *context, u32 channel, u32 step, const u8 *in, + size_t in_len, u8 *out, size_t out_len); + void (*close)(void *context, u32 channel); +}; + +int sep_hdcp_register(void *context, const struct sep_hdcp_ops *ops); +void sep_hdcp_unregister(void *context); + /* Initrd attach and completion; sysfs removal drains the callback. */ bool sep_keystore_only(void); bool sep_keystore_user_bags(void); int sep_complete_attach_register(struct device *dev, void *ctx, - int (*complete)(void *ctx)); + int (*complete)(void *ctx)); void sep_complete_attach_unregister(struct device *dev); void sep_diag_keystore_ended(void); void sep_diag_set_xart(bool writable); diff --git a/drivers/soc/apple/shim.rs b/drivers/soc/apple/shim.rs index e370a91b4c4e88..0bab5cb1e47ae1 100644 --- a/drivers/soc/apple/shim.rs +++ b/drivers/soc/apple/shim.rs @@ -12,6 +12,7 @@ extern "C" { fn sep_store_open_writable_existing(path: *const c_char) -> *mut c_void; fn sep_store_open_ro(path: *const c_char) -> *mut c_void; fn sep_store_open_block(path: *const c_char, writable: c_int) -> *mut c_void; + fn sep_store_open_internal_block(path: *const c_char, writable: c_int) -> *mut c_void; fn sep_store_close(handle: *mut c_void); fn sep_store_size(handle: *mut c_void) -> i64; fn sep_store_read(handle: *mut c_void, off: i64, buf: *mut c_void, len: usize) -> c_long; @@ -104,6 +105,19 @@ impl StoreFile { Ok(StoreFile { handle }) } + /// As [`Self::open_block`], and the device must be on the internal NVMe + /// disk: `path` names the partition but does not identify the disk. + pub(crate) fn open_internal_block(path: &CStr, writable: bool) -> Result { + // SAFETY: `path` is NUL-terminated; as `open_block`, and the shim + // also rejects a device that is not below the embedded NVMe controller. + let handle = + unsafe { sep_store_open_internal_block(path.as_char_ptr(), c_int::from(writable)) }; + if handle.is_null() { + return Err(ENODEV); + } + Ok(StoreFile { handle }) + } + pub(crate) fn size(&self) -> Result { // SAFETY: `handle` is live per the type invariant. let n = unsafe { sep_store_size(self.handle) }; diff --git a/drivers/soc/apple/sleep-perf-step.S b/drivers/soc/apple/sleep-perf-step.S new file mode 100644 index 00000000000000..a50c9670fed166 --- /dev/null +++ b/drivers/soc/apple/sleep-perf-step.S @@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * One performance-state step of a PMGR clock-performance register, with no + * memory access between the write and the end of the transition: the whole + * routine sits in one cache line, so a memory-clock change can't stall its + * own instruction fetch half-way. + */ + +#include +#include + +/* + * u32 apple_sleep_perf_step(void __iomem *reg, u32 state) + * + * Writes @state into the target field (bits 3:0) and waits for the busy bit + * (31) to clear, about two seconds at most. Returns the last value read; bit + * 31 still set means the transition didn't finish. + */ + .balign 64 +SYM_FUNC_START(apple_sleep_perf_step) + ldr w2, [x0] + bfi w2, w1, #0, #4 + dsb sy + isb + str w2, [x0] + mov x3, #(1 << 22) +1: ldr w2, [x0] + tbz w2, #31, 2f + subs x3, x3, #1 + b.ne 1b +2: dsb sy + mov w0, w2 + ret +SYM_FUNC_END(apple_sleep_perf_step) diff --git a/drivers/soc/apple/sleep-t6050.h b/drivers/soc/apple/sleep-t6050.h index a4bf3fabcf375c..e57a42caa4e14a 100644 --- a/drivers/soc/apple/sleep-t6050.h +++ b/drivers/soc/apple/sleep-t6050.h @@ -3123,6 +3123,33 @@ static void t6050_clusters_down_first_report(struct apple_sleep *s) r->early_seq[1], r->early_us[1], r->early_ret[2]); } +static void t6050_sleep_commit_wdt(struct apple_sleep *s) +{ + struct apple_sleep_region_state *r = s->region; + + if (r && r->seq[T6050_SEQ_WDT].n) { + s->aon_wdt_saved = readl(s->wdt_aux + AON_WDT_SLEEP); + s->aon_wdt_marked = true; + } + t6050_seq(s, T6050_SEQ_WDT); + writel(0, s->wdt + WDT_WD0_CTL); + apple_sleep_set_wd2(s, T6050_WDT_COMMIT_SECS); + writel(0, s->wdt_aux + AON_AP_DEADLINE); +} + +static void t6050_sleep_wake_wdt(struct apple_sleep *s) +{ + writel(0, s->wdt + WDT_WD2_CTL); + writel(WDT_WD2_CTL_IRQ_STATUS, s->wdt + WDT_WD2_CTL); + (void)readl(s->wdt + WDT_WD2_CTL); + if (s->aon_wdt_marked) { + writel(s->aon_wdt_saved, s->wdt_aux + AON_WDT_SLEEP); + (void)readl(s->wdt_aux + AON_WDT_SLEEP); + s->aon_wdt_marked = false; + } + apple_sleep_set_wd2(s, WDT_SUSPEND_SECS); +} + /* * The commit window, each step at the DT schedule's time before the sleep timer: the MCC * requests released, the storage link's PHY parked and its words down, the watchdogs, the @@ -3175,10 +3202,7 @@ static void t6050_sleep_commit_regs(struct apple_sleep *s) } } t6050_step(s, T6050_STEP_WDT); - t6050_seq(s, T6050_SEQ_WDT); - writel(0, s->wdt + WDT_WD0_CTL); - apple_sleep_set_wd2(s, T6050_WDT_COMMIT_SECS); - writel(0, s->wdt_aux + 8); + t6050_sleep_commit_wdt(s); /* The memory floor's voter to 0, not read */ t6050_step(s, T6050_STEP_FLOOR); s->region->floor_changed |= BIT(1); @@ -3796,8 +3820,7 @@ static void t6050_sleep_wake_regs(struct apple_sleep *s) r->gfx_aic[2] = readl(r->aic_gfx + 0x14); } /* The complexes' requests back, in macOS's early wake order */ - writel(0, s->wdt + WDT_WD2_CTL); - apple_sleep_set_wd2(s, WDT_SUSPEND_SECS); + t6050_sleep_wake_wdt(s); for (i = 0; i < 3; i++) writel(r->cluster_saved[i], s->cluster + 4 * i); writel(PWRGATE_ON, s->pwrgate); diff --git a/drivers/soc/apple/sleep-t8103.h b/drivers/soc/apple/sleep-t8103.h new file mode 100644 index 00000000000000..f30b4b6a088f6b --- /dev/null +++ b/drivers/soc/apple/sleep-t8103.h @@ -0,0 +1,1755 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * T8103 (M1): suspend-to-RAM through the PMGR's S2R timer. Included by sleep.c after the + * other profiles, so every shared helper is in scope. + * + * At .prepare (0x87, after SEP's sleep and before the SMC's last keys) the coprocessors no + * driver stops are idled and stopped, and the domains Linux leaves on that the sleep needs + * off are lowered. The commit then steps the memory clock down, quiesces the memory + * controller and cache, arms the AOP wake mask, parks the SoC clock muxes, quiesces the CPU + * complexes, turns CPM power gating on, takes both CPU clusters' targets off, AUTO_ENABLE off + * on three always-on words, clears SEP's power-gate wait, arms the watchdog and the PMU RTC + * alarm's SPMI vector, and writes the S2R timer. The cores power down without retention + * through CYC_OVRD and ACC_OVRD, after writing back their caches, as on the other + * Firestorm/Icestorm SoCs. Based on the t6000 suspend-to-RAM reference by Andreas Fernandez. + * + * A timed wake is the PMU RTC's alarm (wake source 54), set by its RTC driver. + */ + +/* "wake": five mask words, then five status words */ +#define T8103_WAKE_MASK 0x08 +#define T8103_WAKE_STATUS 0x1c +#define T8103_WAKE_WORDS 5 + +/* "clk-mux": the SoC clock muxes, parked in this order */ +#define T8103_MUX_PARK_KEEP 0xf0ffffff +#define T8103_MUX_PARK_SET 0x80000000 +#define T8103_MUX_BUSY BIT(30) +#define T8103_MUX_TIMEOUT_US 192000 +/* The SoC clock muxes: 40 words from here in the clock block */ +#define T8103_MUX_SOC 0x40100 + +/* "ps": the CPM power gating, the CPU clusters and the SEP power-gate wait */ +#define T8103_CPM_GATING BIT(31) +#define T8103_CLUSTER_E 0x18000 +#define T8103_CLUSTER_P 0x18004 +#define T8103_CLUSTER_BUSY BIT(4) +#define T8103_SEP_PG 0x4c200 +#define T8103_SEP_PG_WAIT BIT(2) +/* SEP's own power state word, and how long it gets to gate after its sleep's answer */ +#define T8103_SEP_PS 0xc00 +#define T8103_SEP_GATE_US 500000 + +/* "ps-aon": the S2R timer, the commit */ +#define T8103_S2R_TIMER 0x44000 + +/* "spmi" (nub, gen 1): vector enable words from +0x20, the PMU RTC alarm is vector 2 */ +#define T8103_SPMI_VEC_ENABLE 0x20 +#define T8103_SPMI_VEC_RTC BIT(2) +#define T8103_SPMI_VEC_ACK 0x60 +/* + * The reply notification is vector 192 here, as on t6000: its enable and ack words are the + * seventh, not gen 1's ninth. + */ +#define T8103_SPMI_NOTIFY_ENABLE (0x20 + 4 * (192 / 32)) +#define T8103_SPMI_NOTIFY_ACK (0x60 + 4 * (192 / 32)) +#define T8103_SPMI_EXT_WRITEL 0x30 + +/* The PMU's boot-stage byte: 0x50 while the AP sleeps */ +#define T8103_PMU_USID 0xf +#define T8103_PMU_BOOT_STAGE 0x9f01 +#define T8103_PMU_STAGE_SLEEP 0x50 +/* The watchdog from the commit to the wake, and from the wake to .end */ +#define T8103_WDT_COMMIT_SECS 60 +#define T8103_WDT_RESUME_SECS 35 + +/* "wake": word 0 bit 0 keeps DRAM up through the sleep (SLP_DDR) */ +#define T8103_WAKE_SLP_DDR 0x00 +#define T8103_WAKE_SLP_DDR_ON BIT(0) + +/* Each core's external debug block: 1 MiB apart, the clusters 16 MiB apart */ +#define T8103_ED 0x210010000ULL +#define T8103_ED_CORE 0x100000ULL +#define T8103_ED_CLUSTER 0x1000000ULL + +/* Per-core power-down controls */ +#define T8103_CYC_OVRD sys_reg(3, 5, 15, 5, 0) +#define T8103_CYC_DISABLE_WFI_RET BIT_ULL(0) +#define T8103_CYC_FIQ_MODE GENMASK_ULL(21, 20) +#define T8103_CYC_IRQ_MODE GENMASK_ULL(23, 22) +#define T8103_CYC_WFI_MODE GENMASK_ULL(25, 24) +#define T8103_ACC_OVRD sys_reg(3, 5, 15, 6, 0) +#define T8103_PMCR0 sys_reg(3, 1, 15, 0, 0) +#define T8103_ACC_PWR_DN_SRM GENMASK_ULL(14, 13) +#define T8103_ACC_DIS_L2_FLUSH GENMASK_ULL(16, 15) +#define T8103_ACC_TRAIN_DOWN_LINK GENMASK_ULL(18, 17) +#define T8103_ACC_POWER_DOWN_CPM GENMASK_ULL(26, 25) +#define T8103_ACC_DISABLE_PIO_ON_WFI BIT_ULL(32) +#define T8103_ACC_DEEP_SLEEP BIT_ULL(34) + +/* The valid sources in each wake mask word */ +static const u32 t8103_wake_valid[T8103_WAKE_WORDS] = { + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x03ffffff, +}; + +/* + * The mask the platform keeps at every sleep, as macOS sets it (a set bit masks): the AOP, NUB + * (the wake timer, the watchdog, SPMI0 SW3), SMC and ATC port sources left on. + */ +static const u32 t8103_wake_platform[T8103_WAKE_WORDS] = { + 0xf3ffafff, 0xffb97eff, 0xfffdeffe, 0xffffffff, 0x03ffff87, +}; + +static const u32 t8103_mux_park[] = { 0x40140, 0x40144, 0x40148, 0x4014c, 0x40154 }; + +/* The always-on words whose AUTO_ENABLE goes off for the sleep, in this order */ +static const u32 t8103_auto_off[] = { 0x1c8, 0x1c0, 0x1d0 }; + +static const u32 t8103_cpm[] = { 0x1c080, 0x1c088 }; + +static const u32 t8103_cluster[] = { T8103_CLUSTER_E, T8103_CLUSTER_P }; + +/* + * The CPU complexes' and voltage monitors' quiesce, as macOS runs it between the mux park and + * CPM gating: per cluster the energy accumulator, the + * fixed-frequency PLL relock and three throttlers off; the DCS, GFX, DISP and SOC voltage + * monitors off, each waited idle; then each cluster's APSC off, waited. ACC blocks at + * 0x210e20000 (E) and 0x211e20000 (P). + */ +#define T8103_ACC_E 0x210e20000ULL +#define T8103_ACC_P 0x211e20000ULL +#define T8103_ACC_LEN 0x30000 +#define T8103_ACC_DVFS 0x00020 +#define T8103_ACC_DVFS_RELOCK BIT_ULL(42) +#define T8103_ACC_DVFS_APSC_OFF BIT_ULL(22) +#define T8103_ACC_DVFS_PENDING BIT_ULL(7) +#define T8103_ACC_AMX_THRTL 0x20250 +#define T8103_ACC_LLC_THRTL 0x20240 +#define T8103_ACC_PPT_THRTL 0x28400 +#define T8103_ACC_ENERGY 0x28080 +#define T8103_ACC_ENERGY_EN (BIT_ULL(63) | BIT_ULL(61)) +#define T8103_THRTL_EN BIT_ULL(63) +/* In "ps": DCS, GFX, DISP, SOC, in macOS's order; idle at +0x3e0 bit 1 */ +static const u32 t8103_tvm[] = { 0x48400, 0x48800, 0x48c00, 0x48000 }; +#define T8103_TVM_EN BIT(0) +#define T8103_TVM_IDLE_OFF 0x3e0 +#define T8103_TVM_BUSY BIT(1) +#define T8103_QUIESCE_US 10000 +static const u32 t8103_acc_thrtl[] = { T8103_ACC_AMX_THRTL, T8103_ACC_LLC_THRTL, + T8103_ACC_PPT_THRTL }; + +/* + * The PMP: the boot loader starts its firmware and no Linux driver owns it here, and a commit + * with it running resets the SoC (as T8140 found). Idled over its RTKit management endpoint, + * then its CPU stopped; its domains stay on. The SIO and the display coprocessors likewise. + */ +#define T8103_PMP_ASC 0x23bc00000ULL +#define T8103_PMP_MBOX 0x23bc08000ULL +#define T8103_SIO_ASC 0x236400000ULL +#define T8103_SIO_MBOX 0x236408000ULL +#define T8103_DCP_MBOX 0x231c08000ULL +#define T8103_DCPEXT_ASC 0x271c00000ULL +#define T8103_DCPEXT_MBOX 0x271c08000ULL +/* The display coprocessors' CPU power words, in "ps" */ +#define T8103_DISP0_CPU_PS 0x10018 +#define T8103_DISPEXT_CPU_PS 0x378 +#define T8103_ASC_CPU_CONTROL 0x44 +#define T8103_ASC_CPU_RUN BIT(4) +#define T8103_ASC_CPU_STATUS 0x48 +#define T8103_ASC_CPU_IDLE GENMASK(1, 0) +#define T8103_MBOX_A2I_CONTROL 0x110 +#define T8103_MBOX_I2A_CONTROL 0x114 +#define T8103_MBOX_FULL BIT(16) +#define T8103_MBOX_EMPTY BIT(17) +#define T8103_MBOX_RECV_ENABLE BIT(0) +#define T8103_MBOX_A2I_SEND0 0x800 +#define T8103_MBOX_A2I_SEND1 0x808 +#define T8103_MBOX_I2A_RECV0 0x830 +#define T8103_MBOX_I2A_RECV1 0x838 +#define T8103_RTKIT_TYPE GENMASK_ULL(59, 52) +#define T8103_RTKIT_SET_IOP_PWR 6 +#define T8103_RTKIT_IOP_PWR_ACK 7 +#define T8103_RTKIT_PWR GENMASK_ULL(15, 0) +#define T8103_RTKIT_PWR_IDLE 0x201 +#define T8103_PMP_ACK_US 200000 +#define T8103_PMP_IDLE_US 10000 + +/* AGX fabric tunables programmed by the boot loader; lost when ps_gfx powers off. */ +#define T8103_AGX_FABRIC 0x205000000ULL +static const u32 t8103_agx_regs[] = { 0x30, 0x34, 0x400, 0x600, 0x738, 0x798, 0x800 }; + +/* + * CLK_PERF_DCS (T8103_DCS_PERF) holds the memory clock's performance state: target in bits 3:0, + * busy in bit 31. Moving it by more than one state in a single write leaves memory unusable on + * this SoC, while single steps don't. The SoC's own sleep entry moves it to T8103_DCS_SLEEP in + * one write and its wake leaves it at T8103_DCS_WAKE, so it is stepped down to the sleep state + * before the commit and back up after the wake, one state at a time. + */ +#define T8103_DCS_PERF 0x23b05c000ULL +#define T8103_DCS_SLEEP 4 +#define T8103_DCS_WAKE 5 + +u32 apple_sleep_perf_step(void __iomem *reg, u32 state); + +/* Single steps to @target, each finished before the next. Returns false if one didn't finish. */ +static bool t8103_dcs_step_to(void __iomem *reg, unsigned int target, u32 *last) +{ + unsigned int cur = readl(reg) & 0xf; + u32 v = 0; + + while (cur != target) { + cur = cur < target ? cur + 1 : cur - 1; + v = apple_sleep_perf_step(reg, cur); + if (v & BIT(31)) { + *last = v; + return false; + } + } + *last = readl(reg); + return true; +} + +/* + * Domains genpd keeps on for an unbound consumer (sync_state) or stopped display/USB/PCIe blocks + * that macOS has off at its commit. Lowered children-before-parents after every stop. + */ +static const u32 t8103_commit_off[] = { + 0x3f8, /* 0: gfx */ + 0x10018, /* 1: disp0_cpu0 */ + 0x360, /* 2: disp0_fe */ + 0x378, /* 3: dispext_cpu0 */ + 0x368, /* 4: dispext_fe */ + 0x450, /* 5: atc1_pcie */ + 0x448, /* 6: atc1_common */ + 0x428, /* 7: atc0_pcie */ + 0x420, /* 8: atc0_common */ + 0x350, /* 9: rmx (parent of disp0_fe, dispext_fe) */ + 0x3d8, /* 10: pmp (parent of gfx, disp0_fe, dispext_fe) */ + 0x3e8, /* 11: apcie_gp */ + 0x348, /* 12: apcie (parent of apcie_gp) */ + 0x1a0, /* 13: pcie_ref (parent of apcie) */ + 0x130, /* 14: gpio (kept on through 0x85 for SEP, lowered after) */ +}; + +#define T8103_COMMIT_OFF_APCIE_START 11 +/* + * The display front ends' parents (pmp, rmx): genpd still counts them on after the wake, so + * nothing else raises them, and the DCP driver's power-up of DISP0 hangs without them. Put + * back as the commit found them, pmp first. + */ +#define T8103_COMMIT_OFF_GFX 0 +#define T8103_COMMIT_OFF_PMP 10 +#define T8103_COMMIT_OFF_RMX 9 + +/* The PMGR's fabric bridge blocks: +0x14=1, +0x2bc=1,2,4 before their domain powers off */ +static const struct { + u64 pa; + u32 ps_off; +} t8103_bridges[] = { + { 0x205008000ULL, 0x3f8 }, /* reg[40]: gfx */ + { 0x232008000ULL, 0x360 }, /* reg[39]: disp0_fe */ + { 0x272008000ULL, 0x368 }, /* reg[44]: dispext_fe */ + { 0x68c008000ULL, 0x348 }, /* reg[41]: apcie */ +}; + +#define T8103_BRIDGE_8014 0x014 +#define T8103_BRIDGE_82BC 0x2bc + +/* pmgr_mini (ps_aon) domains left on by USB/debug/msg that must go off */ +static const u32 t8103_aon_commit_off[] = { + 0x98, /* 0: atc0_usb */ + 0xa0, /* 1: atc1_usb */ + 0x88, /* 2: atc0_usb_aon */ + 0x90, /* 3: atc1_usb_aon */ + 0xb8, /* 4: debug_usb */ + 0xc0, /* 5: debug_auth */ + 0x58, /* 6: debug */ + 0x78, /* 7: msg */ +}; + +/* Clock-gated ps domains (0x244) Linux leaves at actual 4, lowered to 0 as macOS has them */ +static const u32 t8103_cg_commit_off[] = { + 0x118, /* 0: soc_spmi0 */ + 0x120, /* 1: soc_spmi1 */ + 0x128, /* 2: soc_spmi2 */ + 0x148, /* 3: pms_fpwm0 */ + 0x150, /* 4: pms_fpwm1 */ + 0x158, /* 5: pms_fpwm2 */ + 0x160, /* 6: pms_fpwm3 */ + 0x168, /* 7: pms_fpwm4 */ + 0x1a8, /* 8: aft0 */ + 0x1b0, /* 9: devc0_ivdmc */ + 0x1d8, /* 10: fpwm0 */ + 0x1e8, /* 11: fpwm2 */ +}; + +/* + * The memory cache (SLC): its ways off before the CPU complexes' quiesce, as macOS has it, + * and back on at the wake. Broadcast control at 0x200100000, the four planes + * at 0x200000000 + 0x40000 * p; each plane reports its ways at +0x1c04 bits 14:10 and 9:5. + */ +#define T8103_MCC_BCAST 0x200100000ULL +#define T8103_MCC_BCAST_LP 0x04 +#define T8103_MCC_BCAST_LP_BITS 0x30000000U +#define T8103_MCC_BCAST_A 0x0c +#define T8103_MCC_BCAST_B 0x14 +#define T8103_MCC_AMCNP_ERR 0x55000 +#define T8103_MCC_PLANES 0x200000000ULL +#define T8103_MCC_NPLANES 4 +#define T8103_MCC_STRIDE 0x40000 +#define T8103_MCC_WAYS 0x1c00 +#define T8103_MCC_WAYS_STATUS 0x1c04 +#define T8103_MCC_WAYS_A GENMASK(14, 10) +#define T8103_MCC_WAYS_B GENMASK(9, 5) +#define T8103_MCC_ERR_EN0 0x9000 +#define T8103_MCC_ERR_EN1 0x9008 +#define T8103_MCC_TIMEOUT_US 100000 + +/* + * DCS channels, 8 x 0x40000 from 0x200200000: dynamic clock and power gating (+0xc), error + * reporting (+0x7a0), write queue flush (+0xa30) + */ +#define T8103_DCS_BASE 0x200200000ULL +#define T8103_DCS_NCHAN 8 +#define T8103_DCS_STRIDE 0x40000 +#define T8103_DCS_CTL 0x00c +#define T8103_DCS_CTL_LP 0x1100 +#define T8103_DCS_ERR_EN 0x7a0 +#define T8103_DCS_WQ_FLUSH 0xa30 +#define T8103_DCS_FLUSH_US 330 + +/* + * NCO channels 0..4 clock the externally-clocked MCA PMGR domains (ps_mca0..5). The SoC sleep + * entry sequence writes and polls those domains; if a channel's enable bit was cleared after + * an audio stream closed, the PMGR transition hangs busy and resets the SoC. Enable any + * disabled channel across the commit and turn it back off on wake. + */ +#define T8103_NCO 0x23b044000ULL +#define T8103_NCO_CHANS 5 +#define T8103_NCO_STRIDE 0x4000 +#define T8103_NCO_CTRL_EN BIT(31) + +/* AIC: each CPU's IPI mask set at +0x5024 and its status at +0x5004, 0x80 per CPU */ +#define T8103_AIC_CPU 0x23b105000ULL +#define T8103_AIC_CPU_STRIDE 0x80 +#define T8103_AIC_CPU_STATUS 0x04 +#define T8103_AIC_CPU_MASK_SET 0x24 +#define T8103_AIC_CPU_MASK_CLR 0x28 +#define T8103_AIC_CPU_PENDING GENMASK(18, 16) +#define T8103_AIC_IPI_MASK 0x80000001 +#define T8103_AIC_CPUS 8 + +/* Always-on domains meant to run with AUTO_ENABLE that the boot loader leaves without it */ +static const u32 t8103_ps_boot_auto[] = { + 0x100, /* sbr */ + 0x138, /* pms_busif */ + 0x140, /* pms */ + 0x1b8, /* imx */ + 0x2f8, /* mcc */ + 0x300, /* dcs0 */ + 0x308, /* dcs2 */ + 0x310, /* dcs1 */ + 0x318, /* dcs3 */ + 0x320, /* dcs4 */ + 0x328, /* dcs6 */ + 0x330, /* dcs5 */ + 0x338, /* dcs7 */ + 0x340, /* smx */ + 0x3e0, /* pms_sram */ +}; + +static const u32 t8103_aon_boot_auto[] = { + 0x60, /* nub_spmi0 */ + 0x68, /* nub_spmi1 */ + 0x70, /* nub_aon */ + 0xa8, /* nub_fabric */ + 0xb0, /* nub_sram */ +}; + +static struct t8103_sleep { + void __iomem *mcc_bcast, *mcc_planes, *dcs, *aic_cpu, *nco; + void __iomem *bridges[ARRAY_SIZE(t8103_bridges)]; + u8 nco_forced; + /* The SoC clock muxes from T8103_MUX_SOC at the commit, and those the wake put back */ + u32 mux_snap[40]; + u64 mux_fixed; + u32 slc_ways, aic_ipi_mask[T8103_AIC_CPUS]; + u32 mcc_lp_saved, amcnp_err_saved; + u32 amcc_err0_saved[T8103_MCC_NPLANES], amcc_err1_saved[T8103_MCC_NPLANES]; + u32 dcs_ctl_saved[T8103_DCS_NCHAN], dcs_wq_saved[T8103_DCS_NCHAN]; + u32 dcs_err_saved[T8103_DCS_NCHAN]; + bool dcs_quiesced; + u8 slc_result, aic_result; + void __iomem *pmp_asc, *pmp_mbox, *sio_asc, *sio_mbox; + void __iomem *dcp_mbox, *dcpext_asc, *dcpext_mbox; + void __iomem *agx_fabric; + u32 agx_saved[ARRAY_SIZE(t8103_agx_regs)]; + bool agx_saved_valid; + int gfx_wake_err; + /* Each coprocessor's t8103_asc_stop() result */ + u8 pmp_result, sio_result, dcp_result, dcpext_result; + /* The t8103_commit_off and t8103_cg_commit_off words found or taken off */ + u16 commit_off, cg_commit_off; + /* The t8103_commit_off words this commit lowered, as it found them */ + u16 commit_lowered; + u32 commit_saved[ARRAY_SIZE(t8103_commit_off)]; + u8 aon_commit_off; + u32 cg_saved[ARRAY_SIZE(t8103_cg_commit_off)]; + /* The quiesce's blocks, what it found there, and whether it ran */ + void __iomem *acc[2]; + void __iomem *ed[2][4]; + u64 acc_dvfs[2], acc_energy[2], acc_thrtl[2][ARRAY_SIZE(t8103_acc_thrtl)]; + u32 tvm[ARRAY_SIZE(t8103_tvm)]; + bool quiesced; + unsigned int quiesce_timeouts; + /* The sources apple,wake-enable leaves on, by mask word */ + u32 wanted[T8103_WAKE_WORDS]; + struct platform_device *gpu; + + /* As prepare_regs found them, for the wake */ + bool saved; + u32 wake_mask[T8103_WAKE_WORDS]; + u32 wake_slp_ddr; + bool wake_slp_ddr_changed; + /* The AOP's driver is bound: DRAM stays up for it through the sleep (SLP_DDR) */ + bool aop_slp_ddr; + u32 mux[ARRAY_SIZE(t8103_mux_park)]; + void __iomem *dcs_perf; + u32 dcs_perf_saved; + u32 dcs_perf_down_val, dcs_perf_wake_val, dcs_perf_up_val; + bool dcs_perf_down, dcs_perf_down_ok, dcs_perf_up_ok; + u32 auto_word[ARRAY_SIZE(t8103_auto_off)]; + u32 cpm[ARRAY_SIZE(t8103_cpm)]; + u32 cluster[ARRAY_SIZE(t8103_cluster)]; + u32 sep_pg; + u32 spmi_vec; + + /* This attempt: the commit's results, read back at the wake and reported once */ + bool attempt, committed, sep_pg_cleared; + int sep_ps_gated; + u32 sep_ps; + u32 wake_entry[T8103_WAKE_WORDS]; + u8 mux_timeouts, cluster_timeouts; + int cluster_wake_ret[ARRAY_SIZE(t8103_cluster)]; + u8 mux_wake_timeouts; + /* Every interrupt line masked once for this commit (E14 before the timer) */ + bool aic_masked; +} t8103_sleep; + +/* + * A one-byte PMU write on nub-spmi0 by hand, in the commit, where nothing else talks SPMI: its + * reply notification masked, a stale reply read first, the command and its data, the reply + * checked, nothing left in the FIFO, the notification acknowledged and its enable put back. + */ +static int t8103_pmu_write(struct apple_sleep *s, u16 address, u8 val) +{ + u32 enable, status, reply, command = T8103_SPMI_EXT_WRITEL; + unsigned int i; + int ret = 0; + + enable = readl(s->spmi + T8103_SPMI_NOTIFY_ENABLE); + writel(enable & ~SPMI_NOTIFY_REPLY, s->spmi + T8103_SPMI_NOTIFY_ENABLE); + for (i = 0; i < SPMI_DRAIN_MAX && !(readl(s->spmi + SPMI_STATUS) & SPMI_STATUS_RX_EMPTY); + i++) + readl(s->spmi + SPMI_REPLY); + + writel(command | FIELD_PREP(SPMI_CMD_USID, T8103_PMU_USID) | (u32)address << 16 | + SPMI_CMD_ACTIVE, s->spmi + SPMI_CMD); + writel(val, s->spmi + SPMI_CMD); + + if (readl_poll_timeout_atomic(s->spmi + SPMI_STATUS, status, + !(status & SPMI_STATUS_RX_EMPTY), 1, 1000)) { + ret = -ETIMEDOUT; + goto out; + } + reply = readl(s->spmi + SPMI_REPLY); + if ((reply & 0xff) != command || ((reply >> 8) & 0x7f) != T8103_PMU_USID || + !(reply & SPMI_CMD_ACTIVE)) + ret = -EIO; +out: + if (ret) + udelay(SPMI_POLL_US / 10); + for (i = 0; i < SPMI_DRAIN_MAX && !(readl(s->spmi + SPMI_STATUS) & SPMI_STATUS_RX_EMPTY); + i++) + readl(s->spmi + SPMI_REPLY); + writel(1, s->spmi + T8103_SPMI_NOTIFY_ACK); + writel(enable, s->spmi + T8103_SPMI_NOTIFY_ENABLE); + return ret; +} + +static bool t8103_sleep_cpu_valid(u64 mpidr) +{ + /* E cores 0.0.n, P cores 1.1.n */ + return !(mpidr & ~MPIDR_HWID_BITMASK) && !MPIDR_AFFINITY_LEVEL(mpidr, 3) && + MPIDR_AFFINITY_LEVEL(mpidr, 1) == MPIDR_AFFINITY_LEVEL(mpidr, 2); +} + +/* Each core's power-down controls as Linux has them, back after a refusal or a reset */ +struct t8103_cpu_control { + u64 cyc, acc; + bool saved; +}; + +static DEFINE_PER_CPU(struct t8103_cpu_control, t8103_cpu_control); + +static int t8103_sleep_cpu_prepare(u64 mpidr) +{ + struct t8103_cpu_control *c = this_cpu_ptr(&t8103_cpu_control); + + if (!is_kernel_in_hyp_mode()) + return -EOPNOTSUPP; + if (!c->saved) { + c->cyc = read_sysreg_s(T8103_CYC_OVRD); + c->acc = read_sysreg_s(T8103_ACC_OVRD); + c->saved = true; + } + return 0; +} + +static void t8103_sleep_cpu_restore(u64 mpidr) +{ + struct t8103_cpu_control *c = this_cpu_ptr(&t8103_cpu_control); + + if (!c->saved) + return; + if (read_sysreg_s(T8103_ACC_OVRD) != c->acc) + write_sysreg_s(c->acc, T8103_ACC_OVRD); + if (read_sysreg_s(T8103_CYC_OVRD) != c->cyc) + write_sysreg_s(c->cyc, T8103_CYC_OVRD); + isb(); + c->saved = false; +} + +/* + * void t8103_cpu_off(u64 cyc_ovrd, u64 acc_ovrd): a core's last instructions. The data cache + * off, L1 written back and invalidated by set and way, then L2 written back by set and way (a + * cluster's L2 is not written back when it powers down), the timers off, the power-down + * controls written, then WFI until the power goes. Never returns. + */ +asm( +" .pushsection .text, \"ax\"\n" +" .type t8103_cpu_off, %function\n" +"t8103_cpu_off:\n" +" msr daifset, #0xf\n" +" mrs x3, sctlr_el1\n" +" bic x3, x3, #(1 << 2)\n" +" msr sctlr_el1, x3\n" +" isb\n" +" msr csselr_el1, xzr\n" +" isb\n" +" mrs x3, ccsidr_el1\n" +" and x4, x3, #7\n" +" add x4, x4, #4\n" +" ubfx x5, x3, #3, #10\n" +" ubfx x6, x3, #13, #15\n" +" clz w7, w5\n" +"1: mov x8, x6\n" +"2: lsl x9, x5, x7\n" +" lsl x10, x8, x4\n" +" orr x9, x9, x10\n" +" dc cisw, x9\n" +" subs x8, x8, #1\n" +" b.ge 2b\n" +" subs x5, x5, #1\n" +" b.ge 1b\n" +" dsb sy\n" +" isb\n" +/* L2 too: written back (clean only, others in the cluster may still run), set by way */ +" mov x3, #2\n" +" msr csselr_el1, x3\n" +" isb\n" +" mrs x3, ccsidr_el1\n" +" and x4, x3, #7\n" +" add x4, x4, #4\n" +" ubfx x5, x3, #3, #10\n" +" ubfx x6, x3, #13, #15\n" +" clz w7, w5\n" +" mov x11, #2\n" +"11: mov x8, x6\n" +"12: lsl x9, x5, x7\n" +" lsl x10, x8, x4\n" +" orr x9, x9, x10\n" +" orr x9, x9, x11\n" +" dc csw, x9\n" +" subs x8, x8, #1\n" +" b.ge 12b\n" +" subs x5, x5, #1\n" +" b.ge 11b\n" +" dsb sy\n" +" isb\n" +" msr cntp_ctl_el0, xzr\n" +" msr cntv_ctl_el0, xzr\n" +" mrs x3, CurrentEL\n" +" cmp x3, #(2 << 2)\n" +" b.ne 3f\n" +" msr s3_5_c14_c2_1, xzr\n" /* CNTP_CTL_EL02 */ +" msr s3_5_c14_c3_1, xzr\n" /* CNTV_CTL_EL02 */ +"3: msr s3_5_c15_c6_0, x1\n" /* ACC_OVRD */ +" msr s3_5_c15_c5_0, x0\n" /* CYC_OVRD */ +" isb\n" +" mov x9, #1\n" +"4: msr s3_5_c15_c1_1, x9\n" /* IPI_SR: a fast IPI ends WFI */ +" dsb sy\n" +" isb\n" +" wfi\n" +" b 4b\n" +" .size t8103_cpu_off, . - t8103_cpu_off\n" +" .popsection\n" +); +void t8103_cpu_off(u64 cyc_ovrd, u64 acc_ovrd); + +/* E10, on every core before its last WFI: power down without retention, woken by a reset. */ +static void t8103_deep_wfi_arm(void) +{ + u64 mpidr = read_cpuid_mpidr() & MPIDR_HWID_BITMASK; + unsigned int cluster = MPIDR_AFFINITY_LEVEL(mpidr, 2); + unsigned int core = MPIDR_AFFINITY_LEVEL(mpidr, 0); + u64 cyc = read_sysreg_s(T8103_CYC_OVRD), acc = read_sysreg_s(T8103_ACC_OVRD); + + /* + * The core's external debug block: unlocked, then its power-down request bits cleared, + * so a debugger's request doesn't hold the core's power on. + */ + if (cluster < 2 && core < 4 && t8103_sleep.ed[cluster][core]) { + writel_relaxed(0xc5acce55U, t8103_sleep.ed[cluster][core] + 0xfb0); + writel_relaxed(0, t8103_sleep.ed[cluster][core] + 0x310); + dsb(sy); + } + + /* The WFI mode and no retention, with the IRQ and FIQ modes cleared as t6000 has them */ + cyc &= ~(T8103_CYC_WFI_MODE | T8103_CYC_IRQ_MODE | T8103_CYC_FIQ_MODE); + cyc |= FIELD_PREP(T8103_CYC_WFI_MODE, 3) | T8103_CYC_DISABLE_WFI_RET; + /* The PMU counters and their interrupt off */ + write_sysreg_s(0, T8103_PMCR0); + acc &= ~(T8103_ACC_PWR_DN_SRM | T8103_ACC_DIS_L2_FLUSH | T8103_ACC_TRAIN_DOWN_LINK | + T8103_ACC_POWER_DOWN_CPM); + acc |= FIELD_PREP(T8103_ACC_PWR_DN_SRM, 3) | FIELD_PREP(T8103_ACC_DIS_L2_FLUSH, 2) | + FIELD_PREP(T8103_ACC_TRAIN_DOWN_LINK, 3) | FIELD_PREP(T8103_ACC_POWER_DOWN_CPM, 3) | + T8103_ACC_DISABLE_PIO_ON_WFI | T8103_ACC_DEEP_SLEEP; + t8103_cpu_off(cyc, acc); + unreachable(); +} + +/* + * The first thing Linux runs after a wake, MMU off and no stack: the PAC controls put back, + * then cpu_resume. + */ +asm( +" .pushsection .text, \"ax\"\n" +" .type t8103_resume_stub, %function\n" +"t8103_resume_stub:\n" +" adrp x0, t8103_pac_saved\n" +" add x0, x0, :lo12:t8103_pac_saved\n" +/* The PAC controls are back at their reset values: put back what the kernel signed with */ +" ldr x1, [x0, #16]\n" +" cbz x1, 8f\n" +" ldr x1, [x0]\n" +" msr s3_4_c15_c0_4, x1\n" +" ldr x1, [x0, #8]\n" +" msr s3_6_c15_c12_2, x1\n" +" isb\n" +"8:\n" +" b cpu_resume\n" +" .size t8103_resume_stub, . - t8103_resume_stub\n" +" .popsection\n" +); +void t8103_resume_stub(void); + +/* + * The cores' PAC control registers (APCTL_EL1, APCTL_EL2) come back from the core reset of a + * wake at their reset values, not the ones the kernel's return addresses were signed with. + * Saved here right before the commit; t8103_resume_stub puts them back, MMU off, before + * cpu_resume. [2] says they're valid. + */ +u64 t8103_pac_saved[3] __aligned(64); + +/* Right before the timer: the PAC controls, and this stack to the point of coherency */ +static void t8103_pre_commit(struct apple_sleep *s) +{ + t8103_pac_saved[0] = read_sysreg_s(sys_reg(3, 4, 15, 0, 4)); + t8103_pac_saved[1] = read_sysreg_s(sys_reg(3, 6, 15, 12, 2)); + t8103_pac_saved[2] = 1; + dcache_clean_poc((unsigned long)t8103_pac_saved, + (unsigned long)t8103_pac_saved + sizeof(t8103_pac_saved)); + dcache_clean_poc((unsigned long)task_stack_page(current), + (unsigned long)task_stack_page(current) + THREAD_SIZE); +} + +/* E14 once, before the timer: the shared commit's call after it then changes nothing. */ +static void t8103_aic_mask_all(void) +{ + if (t8103_sleep.aic_masked) + return; + aic_sleep_mask_all(); + t8103_sleep.aic_masked = true; +} + +static void t8103_aic_restore(void) +{ + if (!t8103_sleep.aic_masked) + return; + aic_sleep_restore(); + t8103_sleep.aic_masked = false; +} + +static void __iomem *t8103_map(struct apple_sleep *s, const char *name, resource_size_t min, + struct resource *res) +{ + struct device_node *np = s->dev->of_node; + int index = of_property_match_string(np, "reg-names", name); + + if (index < 0 || of_address_to_resource(np, index, res)) + return IOMEM_ERR_PTR(-ENODEV); + if (resource_size(res) < min) + return IOMEM_ERR_PTR(-EINVAL); + /* Shared with the drivers of these blocks, so not claimed. */ + return apple_sleep_map(s->dev, name); +} + +/* Mapped for good, non-posted (a posted write to these blocks is an SError), or NULL */ +static void __iomem *t8103_ioremap(struct apple_sleep *s, phys_addr_t pa, size_t len) +{ + void __iomem *base = ioremap_np(pa, len); + + if (base && devm_add_action_or_reset(s->dev, apple_sleep_iounmap, (void __force *)base)) + return NULL; + return base; +} + +static int t8103_sleep_map_regs(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + struct resource res; + struct device_node *np; + int i, c, ret; + + s->ps = t8103_map(s, "ps", T8103_SEP_PG + 4, &res); + s->ps_aon = t8103_map(s, "ps-aon", T8103_S2R_TIMER + 4, &res); + s->clk_mux = t8103_map(s, "clk-mux", T8103_MUX_SOC + 4 * ARRAY_SIZE(t->mux_snap), &res); + s->wake = t8103_map(s, "wake", T8103_WAKE_STATUS + 4 * T8103_WAKE_WORDS, &res); + s->cpu_start = t8103_map(s, "cpu-start", CPU_START_CLUSTER(1) + 4, &res); + s->wdt = t8103_map(s, "wdt", WDT_WD1_CTL + 4, &res); + s->spmi = t8103_map(s, "spmi", SPMI_NOTIFY_ACK + 4, &res); + if (IS_ERR(s->ps) || IS_ERR(s->ps_aon) || IS_ERR(s->clk_mux) || IS_ERR(s->wake) || + IS_ERR(s->cpu_start) || IS_ERR(s->wdt) || IS_ERR(s->spmi)) + return dev_err_probe(s->dev, -EINVAL, + "ps, ps-aon, clk-mux, wake, cpu-start, wdt and spmi must all be mapped\n"); + /* + * The CPU complexes' blocks and the cores' external debug blocks, the memory controller + * and cache, the AIC's per-CPU words, the memory clock's performance state, the + * coprocessors stopped at the commit and the fabric bridges: none of them in the sleep + * node's reg, each shared with its own driver where it has one, so not claimed. + */ + for (i = 0; i < 2; i++) { + t->acc[i] = t8103_ioremap(s, i ? T8103_ACC_P : T8103_ACC_E, T8103_ACC_LEN); + if (!t->acc[i]) + return dev_err_probe(s->dev, -ENOMEM, "ACC blocks not mapped\n"); + for (c = 0; c < 4; c++) + t->ed[i][c] = t8103_ioremap(s, T8103_ED + i * T8103_ED_CLUSTER + + c * T8103_ED_CORE, 0x1000); + } + t->mcc_bcast = t8103_ioremap(s, T8103_MCC_BCAST, 0x60000); + t->mcc_planes = t8103_ioremap(s, T8103_MCC_PLANES, T8103_MCC_NPLANES * T8103_MCC_STRIDE); + t->dcs = t8103_ioremap(s, T8103_DCS_BASE, T8103_DCS_NCHAN * T8103_DCS_STRIDE); + t->aic_cpu = t8103_ioremap(s, T8103_AIC_CPU, T8103_AIC_CPUS * T8103_AIC_CPU_STRIDE); + t->nco = t8103_ioremap(s, T8103_NCO, T8103_NCO_CHANS * T8103_NCO_STRIDE); + if (!t->mcc_bcast || !t->mcc_planes || !t->dcs || !t->aic_cpu || !t->nco) + return dev_err_probe(s->dev, -ENOMEM, + "MCC, DCS, AIC CPU or NCO block not mapped\n"); + t->dcs_perf = t8103_ioremap(s, T8103_DCS_PERF, 4); + t->pmp_asc = t8103_ioremap(s, T8103_PMP_ASC, 0x100); + t->pmp_mbox = t8103_ioremap(s, T8103_PMP_MBOX, 0x1000); + t->sio_asc = t8103_ioremap(s, T8103_SIO_ASC, 0x100); + t->sio_mbox = t8103_ioremap(s, T8103_SIO_MBOX, 0x1000); + t->dcp_mbox = t8103_ioremap(s, T8103_DCP_MBOX, 0x1000); + t->dcpext_asc = t8103_ioremap(s, T8103_DCPEXT_ASC, 0x100); + t->dcpext_mbox = t8103_ioremap(s, T8103_DCPEXT_MBOX, 0x1000); + for (i = 0; i < ARRAY_SIZE(t8103_bridges); i++) + t->bridges[i] = t8103_ioremap(s, t8103_bridges[i].pa, 0x1000); + t->agx_fabric = t8103_ioremap(s, T8103_AGX_FABRIC, 0x1000); + /* The commit word is the S2R timer, the clusters' words are in "ps". */ + s->commit = s->ps_aon + T8103_S2R_TIMER; + s->cluster = s->ps; + + ret = apple_sleep_read_wake_sources(s); + if (ret) + return ret; + for (i = 0; i < s->wake_enable_count; i++) { + u32 id = s->wake_enable[i]; + + if (id / 32 >= T8103_WAKE_WORDS || !(t8103_wake_valid[id / 32] & BIT(id % 32))) + return dev_err_probe(s->dev, -EINVAL, "wake source %u is not valid\n", id); + t->wanted[id / 32] |= BIT(id % 32); + } + + np = of_find_compatible_node(NULL, NULL, "apple,agx-t8103"); + if (np) { + t->gpu = of_find_device_by_node(np); + of_node_put(np); + } + if (t->gpu && + devm_add_action_or_reset(s->dev, apple_sleep_put_device, &t->gpu->dev)) + return -ENOMEM; + + /* + * The AP pins' controller stays powered through the noirq phase: SEP answers its sleep + * request at 0x85 only with the GPIO domain on, and the commit lowers it. + */ + np = of_parse_phandle(s->dev->of_node, "apple,pinctrl", 0); + if (np) { + struct platform_device *pctl = of_find_device_by_node(np); + + if (pctl) { + dev_pm_syscore_device(&pctl->dev, true); + put_device(&pctl->dev); + } + of_node_put(np); + } + + dev_info(s->dev, "T8103: wake sources %08x %08x %08x %08x %08x\n", t->wanted[0], + t->wanted[1], t->wanted[2], t->wanted[3], t->wanted[4]); + return 0; +} + +/* + * The AOP runs through the sleep and reaches DRAM: with its driver bound, the sleep keeps DRAM + * up for it (SLP_DDR), as for the USB host's vote. With it unbound, or after a coprocessor + * crash, or when this sleep was asked to go deep, DRAM goes down with the rest. + */ +static bool t8103_aop_bound(void) +{ + struct device_node *np = of_find_compatible_node(NULL, NULL, "apple,t8103-aop"); + struct platform_device *pdev = np ? of_find_device_by_node(np) : NULL; + bool bound = pdev && device_is_bound(&pdev->dev); + + if (pdev) + put_device(&pdev->dev); + of_node_put(np); + return bound; +} + +static int t8103_sleep_begin(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + + t->attempt = true; + t->committed = false; + t->saved = false; + t->aic_masked = false; + t->sep_pg_cleared = false; + t->mux_timeouts = 0; + t->cluster_timeouts = 0; + t->mux_wake_timeouts = 0; + t->gfx_wake_err = 0; + t->nco_forced = 0; + memset(t->cluster_wake_ret, 0, sizeof(t->cluster_wake_ret)); + t->aop_slp_ddr = t8103_aop_bound(); + if (t->aop_slp_ddr) + dev_info(s->dev, "T8103: AOP bound: DRAM stays up for it\n"); + return 0; +} + +/* The SoC's own refusals, before any other: nothing has been written yet. */ +static int t8103_sleep_check(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i, wanted = 0; + + /* Refuse a bound GPU driver unless it registered a commit stop and registers are mapped. */ + if (t->gpu && device_is_bound(&t->gpu->dev)) { + if (!apple_sleep_coproc_ready_node(t->gpu->dev.of_node)) { + dev_err(s->dev, "refused: the GPU's driver is bound\n"); + return -EBUSY; + } + if (!t->agx_fabric || !t->bridges[0]) { + dev_err(s->dev, "refused: GPU fabric or bridge registers not mapped\n"); + return -ENODEV; + } + } + + for (i = 0; i < T8103_WAKE_WORDS; i++) + wanted += hweight32(t->wanted[i] & t8103_wake_valid[i]); + if (!wanted) { + dev_err(s->dev, "refused: no wake source enabled\n"); + return -EINVAL; + } + return 0; +} + +/* + * A coprocessor CPU's registers answer while its domain is at full power, or asked for full + * power with AUTO_ENABLE, which brings an auto clock-gated one back on access (a running + * DCP reads actual 4 this way). Not once its driver has lowered it: target 0, no AUTO_ENABLE. + */ +static bool t8103_cpu_answers(struct apple_sleep *s, u32 ps) +{ + u32 v = readl(s->ps + ps); + + return FIELD_GET(PS_ACTUAL, v) == 0xf || + (FIELD_GET(PS_TARGET, v) == 0xf && (v & PS_AUTO_ENABLE)); +} + +/* + * Nothing here talks to the display coprocessor or lowers its domains: its driver stops it + * for the sleep where it can, and its state is only reported. + */ +static int t8103_sleep_display_off(struct apple_sleep *s) +{ + void __iomem *asc = s->display[0].asc; + bool answers = s->display[0].bound && asc && t8103_cpu_answers(s, T8103_DISP0_CPU_PS); + + dev_info(s->dev, "T8103: display coprocessor %s, CPU power %#x, control %#x; left as it is\n", + s->display[0].bound ? "bound" : "unbound", readl(s->ps + T8103_DISP0_CPU_PS), + answers ? readl(asc + ASC_CPU_CONTROL) : 0); + return 0; +} + +static void t8103_pre_smc_down(struct apple_sleep *s); + +/* Reversible: every word the commit and the wake write, saved. Nothing is written. */ +static void t8103_sleep_prepare_regs(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i; + + for (i = 0; i < T8103_WAKE_WORDS; i++) + t->wake_mask[i] = readl(s->wake + T8103_WAKE_MASK + 4 * i); + for (i = 0; i < ARRAY_SIZE(t8103_mux_park); i++) + t->mux[i] = readl(s->clk_mux + t8103_mux_park[i]); + for (i = 0; i < ARRAY_SIZE(t8103_auto_off); i++) + t->auto_word[i] = readl(s->ps + t8103_auto_off[i]); + for (i = 0; i < ARRAY_SIZE(t8103_cpm); i++) + t->cpm[i] = readl(s->ps + t8103_cpm[i]); + for (i = 0; i < ARRAY_SIZE(t8103_cluster); i++) + t->cluster[i] = readl(s->ps + t8103_cluster[i]); + t->sep_pg = readl(s->ps + T8103_SEP_PG); + t->spmi_vec = readl(s->spmi + T8103_SPMI_VEC_ENABLE); + t->saved = true; + if (s->entry_committed) + t8103_pre_smc_down(s); +} + +/* prepare_regs writes nothing, so neither does this. */ +static void t8103_sleep_undo_regs(struct apple_sleep *s) +{ + t8103_sleep.saved = false; +} + +/* + * A coprocessor's RTKit idled over its management endpoint, then its CPU stopped. In the + * commit, interrupts off, the boot core alone: nothing waits on it after. + * Returns bit 0 acked, 1 CPU idle, 2 stopped, 4 already stopped, 5 not mapped. + */ +static u8 t8103_asc_stop(void __iomem *asc, void __iomem *m) +{ + unsigned int us, n; + u8 result = 0; + u64 msg0; + u32 v; + + if (!asc || !m) + return BIT(5); + if (!(readl(asc + T8103_ASC_CPU_CONTROL) & T8103_ASC_CPU_RUN)) + return BIT(4); + for (n = 0; n < 64 && !(readl(m + T8103_MBOX_I2A_CONTROL) & T8103_MBOX_EMPTY); n++) { + readq(m + T8103_MBOX_I2A_RECV0); + readq(m + T8103_MBOX_I2A_RECV1); + } + for (us = 0; us < T8103_PMP_ACK_US && (readl(m + T8103_MBOX_A2I_CONTROL) & T8103_MBOX_FULL); + us += 10) + udelay(10); + writeq(FIELD_PREP(T8103_RTKIT_TYPE, T8103_RTKIT_SET_IOP_PWR) | + FIELD_PREP(T8103_RTKIT_PWR, T8103_RTKIT_PWR_IDLE), m + T8103_MBOX_A2I_SEND0); + writeq(0, m + T8103_MBOX_A2I_SEND1); + for (us = 0; us < T8103_PMP_ACK_US; us += 10) { + if (readl(m + T8103_MBOX_I2A_CONTROL) & T8103_MBOX_EMPTY) { + udelay(10); + continue; + } + msg0 = readq(m + T8103_MBOX_I2A_RECV0); + readq(m + T8103_MBOX_I2A_RECV1); + if (FIELD_GET(T8103_RTKIT_TYPE, msg0) == T8103_RTKIT_IOP_PWR_ACK && + FIELD_GET(T8103_RTKIT_PWR, msg0) == T8103_RTKIT_PWR_IDLE) { + result |= BIT(0); + break; + } + } + /* Its outbox off, then RUN cleared once it idles */ + writel(readl(m + T8103_MBOX_I2A_CONTROL) & ~T8103_MBOX_RECV_ENABLE, + m + T8103_MBOX_I2A_CONTROL); + if (!readl_poll_timeout_atomic(asc + T8103_ASC_CPU_STATUS, v, + (v & T8103_ASC_CPU_IDLE) == T8103_ASC_CPU_IDLE, 1, + T8103_PMP_IDLE_US)) + result |= BIT(1); + writel(readl(asc + T8103_ASC_CPU_CONTROL) & ~T8103_ASC_CPU_RUN, + asc + T8103_ASC_CPU_CONTROL); + return result | BIT(2); +} + +static void t8103_pmp_stop(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + + t->pmp_result = t8103_asc_stop(t->pmp_asc, t->pmp_mbox); + t->sio_result = 0; + if (FIELD_GET(PS_ACTUAL, readl(s->ps + 0x1d0))) + t->sio_result = t8103_asc_stop(t->sio_asc, t->sio_mbox); + /* + * Both display coprocessors: bound and running; drivers restart them at the wake. Not + * once a driver has lowered the CPU's domain itself: its registers don't answer then. + */ + t->dcp_result = 0; + if (s->display[0].bound && t8103_cpu_answers(s, T8103_DISP0_CPU_PS)) + t->dcp_result = t8103_asc_stop(s->display[0].asc, t->dcp_mbox); + t->dcpext_result = 0; + if (t8103_cpu_answers(s, T8103_DISPEXT_CPU_PS)) + t->dcpext_result = t8103_asc_stop(t->dcpext_asc, t->dcpext_mbox); +} + +/* + * The memory controller's platform error reporting off, its and the DCS channels' dynamic + * clock and power gating on, and the DCS write queues flushed, each as it was put back at the + * wake. + */ +static void t8103_dcs_quiesce(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int ch, p; + + t->amcnp_err_saved = readl(t->mcc_bcast + T8103_MCC_AMCNP_ERR); + writel(0, t->mcc_bcast + T8103_MCC_AMCNP_ERR); + for (p = 0; p < T8103_MCC_NPLANES; p++) { + void __iomem *base = t->mcc_planes + p * T8103_MCC_STRIDE; + + t->amcc_err0_saved[p] = readl(base + T8103_MCC_ERR_EN0); + t->amcc_err1_saved[p] = readl(base + T8103_MCC_ERR_EN1); + writel(0, base + T8103_MCC_ERR_EN1); + writel(0, base + T8103_MCC_ERR_EN0); + } + for (ch = 0; ch < T8103_DCS_NCHAN; ch++) { + void __iomem *reg = t->dcs + ch * T8103_DCS_STRIDE + T8103_DCS_ERR_EN; + + t->dcs_err_saved[ch] = readl(reg); + writel(0, reg); + } + t->mcc_lp_saved = readl(t->mcc_bcast + T8103_MCC_BCAST_LP); + writel(t->mcc_lp_saved | T8103_MCC_BCAST_LP_BITS, t->mcc_bcast + T8103_MCC_BCAST_LP); + for (ch = 0; ch < T8103_DCS_NCHAN; ch++) { + void __iomem *reg = t->dcs + ch * T8103_DCS_STRIDE + T8103_DCS_CTL; + + t->dcs_ctl_saved[ch] = readl(reg); + writel(t->dcs_ctl_saved[ch] | T8103_DCS_CTL_LP, reg); + } + for (ch = 0; ch < T8103_DCS_NCHAN; ch++) { + void __iomem *reg = t->dcs + ch * T8103_DCS_STRIDE + T8103_DCS_WQ_FLUSH; + + t->dcs_wq_saved[ch] = readl(reg); + writel(t->dcs_wq_saved[ch] & 0xffff0000U, reg); + } + /* The flush's time: the queues have no status to poll */ + udelay(T8103_DCS_FLUSH_US); + t->dcs_quiesced = true; +} + +static void t8103_dcs_restore(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int ch, p; + + if (!t->dcs_quiesced) + return; + t->dcs_quiesced = false; + for (ch = 0; ch < T8103_DCS_NCHAN; ch++) + writel(t->dcs_wq_saved[ch], t->dcs + ch * T8103_DCS_STRIDE + T8103_DCS_WQ_FLUSH); + for (ch = 0; ch < T8103_DCS_NCHAN; ch++) + writel(t->dcs_ctl_saved[ch], t->dcs + ch * T8103_DCS_STRIDE + T8103_DCS_CTL); + writel(t->mcc_lp_saved, t->mcc_bcast + T8103_MCC_BCAST_LP); + for (ch = 0; ch < T8103_DCS_NCHAN; ch++) + writel(t->dcs_err_saved[ch], t->dcs + ch * T8103_DCS_STRIDE + T8103_DCS_ERR_EN); + for (p = 0; p < T8103_MCC_NPLANES; p++) { + void __iomem *base = t->mcc_planes + p * T8103_MCC_STRIDE; + + writel(t->amcc_err1_saved[p], base + T8103_MCC_ERR_EN1); + writel(t->amcc_err0_saved[p], base + T8103_MCC_ERR_EN0); + } + writel(t->amcnp_err_saved, t->mcc_bcast + T8103_MCC_AMCNP_ERR); +} + +/* The ways set to @ways on every plane at once, then each plane waited for: 0 on success */ +static int t8103_slc_set(struct apple_sleep *s, u32 ways) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int p, bad = 0; + u32 v; + + writel(1, t->mcc_bcast + T8103_MCC_BCAST_A); + writel(1, t->mcc_bcast + T8103_MCC_BCAST_B); + writel(ways, t->mcc_planes + T8103_MCC_WAYS); + writel(0, t->mcc_bcast + T8103_MCC_BCAST_A); + writel(0, t->mcc_bcast + T8103_MCC_BCAST_B); + for (p = 0; p < T8103_MCC_NPLANES; p++) { + void __iomem *reg = t->mcc_planes + p * T8103_MCC_STRIDE + T8103_MCC_WAYS_STATUS; + + if (readl_poll_timeout_atomic(reg, v, FIELD_GET(T8103_MCC_WAYS_A, v) == ways, 1, + T8103_MCC_TIMEOUT_US) || + readl_poll_timeout_atomic(reg, v, FIELD_GET(T8103_MCC_WAYS_B, v) == ways, 1, + T8103_MCC_TIMEOUT_US)) + bad |= BIT(p); + } + return bad; +} + +/* The memory cache's ways off before the CPU complexes' quiesce, as macOS has it */ +static void t8103_slc_off(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + u32 v = readl(t->mcc_planes + T8103_MCC_WAYS_STATUS); + + t->slc_result = 0; + t->slc_ways = FIELD_GET(T8103_MCC_WAYS_B, v); + if (!t->slc_ways) + return; + t->slc_result = BIT(7) | t8103_slc_set(s, 0); +} + +static void t8103_slc_on(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + + if (!(t->slc_result & BIT(7))) + return; + t->slc_result = 0; + t8103_slc_set(s, t->slc_ways); +} + +/* After the AIC's mask: each CPU's IPIs masked and drained, as macOS has them */ +static void t8103_aic_ipi_quiesce(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i; + u32 v; + + t->aic_result = 0; + for (i = 0; i < T8103_AIC_CPUS; i++) { + void __iomem *c = t->aic_cpu + i * T8103_AIC_CPU_STRIDE; + + t->aic_ipi_mask[i] = readl(c + T8103_AIC_CPU_MASK_CLR); + writel(T8103_AIC_IPI_MASK, c + T8103_AIC_CPU_MASK_SET); + if (readl_poll_timeout_atomic(c + T8103_AIC_CPU_STATUS, v, + !(v & T8103_AIC_CPU_PENDING), 1, 10000)) + t->aic_result |= BIT(i); + } +} + +static void t8103_aic_ipi_restore(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i; + + for (i = 0; i < T8103_AIC_CPUS; i++) { + void __iomem *c = t->aic_cpu + i * T8103_AIC_CPU_STRIDE; + + writel(t->aic_ipi_mask[i], c + T8103_AIC_CPU_MASK_SET); + writel(~t->aic_ipi_mask[i], c + T8103_AIC_CPU_MASK_CLR); + } +} + +/* The quiesce, irreversible: in the commit, interrupts off, the boot core alone */ +static void t8103_quiesce(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int c, i; + u64 q; + u32 v; + + t->quiesced = false; + t->quiesce_timeouts = 0; + for (c = 0; c < 2; c++) { + t->acc_energy[c] = readq(t->acc[c] + T8103_ACC_ENERGY); + writeq(t->acc_energy[c] & ~T8103_ACC_ENERGY_EN, t->acc[c] + T8103_ACC_ENERGY); + } + for (c = 0; c < 2; c++) { + t->acc_dvfs[c] = readq(t->acc[c] + T8103_ACC_DVFS); + writeq(t->acc_dvfs[c] & ~T8103_ACC_DVFS_RELOCK, t->acc[c] + T8103_ACC_DVFS); + } + for (i = 0; i < ARRAY_SIZE(t8103_acc_thrtl); i++) + for (c = 0; c < 2; c++) { + void __iomem *reg = t->acc[c] + t8103_acc_thrtl[i]; + + t->acc_thrtl[c][i] = readq(reg); + writeq(t->acc_thrtl[c][i] & ~T8103_THRTL_EN, reg); + } + for (i = 0; i < ARRAY_SIZE(t8103_tvm); i++) { + t->tvm[i] = readl(s->ps + t8103_tvm[i]); + writel(t->tvm[i] & ~T8103_TVM_EN, s->ps + t8103_tvm[i]); + if (readl_poll_timeout_atomic(s->ps + t8103_tvm[i] + T8103_TVM_IDLE_OFF, v, + !(v & T8103_TVM_BUSY), 1, T8103_QUIESCE_US)) + t->quiesce_timeouts++; + } + for (c = 0; c < 2; c++) { + void __iomem *reg = t->acc[c] + T8103_ACC_DVFS; + + writeq(readq(reg) | T8103_ACC_DVFS_APSC_OFF, reg); + if (readq_poll_timeout_atomic(reg, q, !(q & T8103_ACC_DVFS_PENDING), 1, + T8103_QUIESCE_US)) + t->quiesce_timeouts++; + } + t->quiesced = true; +} + +/* At the wake, in reverse: only the bits the quiesce changed */ +static void t8103_unquiesce(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int c, i; + + if (!t->quiesced) + return; + t->quiesced = false; + for (c = 0; c < 2; c++) { + void __iomem *reg = t->acc[c] + T8103_ACC_DVFS; + u64 q; + + if (t->cluster_wake_ret[c]) + continue; + q = readq(reg); + q = (q & ~(T8103_ACC_DVFS_APSC_OFF | T8103_ACC_DVFS_RELOCK)) | + (t->acc_dvfs[c] & (T8103_ACC_DVFS_APSC_OFF | T8103_ACC_DVFS_RELOCK)); + writeq(q, reg); + } + for (i = 0; i < ARRAY_SIZE(t8103_tvm); i++) + if (t->tvm[i] & T8103_TVM_EN) + writel(readl(s->ps + t8103_tvm[i]) | T8103_TVM_EN, s->ps + t8103_tvm[i]); + for (i = 0; i < ARRAY_SIZE(t8103_acc_thrtl); i++) + for (c = 0; c < 2; c++) { + void __iomem *reg = t->acc[c] + t8103_acc_thrtl[i]; + + if (t->cluster_wake_ret[c]) + continue; + writeq(readq(reg) | (t->acc_thrtl[c][i] & T8103_THRTL_EN), reg); + } + for (c = 0; c < 2; c++) { + void __iomem *reg = t->acc[c] + T8103_ACC_ENERGY; + + if (!t->cluster_wake_ret[c]) + writeq(readq(reg) | (t->acc_energy[c] & T8103_ACC_ENERGY_EN), reg); + } +} + +/* + * At 0x87, after SEP's sleep and before the SMC's last keys, as t6000 has it: SEP's domain + * forced off (FORCE_NOACCESS, no minimum) and waited for, the PMP, SIO and both display + * coprocessors stopped, then the always-on PMGR's USB and debug domains and the main PMGR's + * stopped blocks lowered (gpio last, at the commit), with the fabric bridges' handshake + * first. The always-on domains that should come back by themselves get AUTO_ENABLE. + */ +static void t8103_pre_smc_down(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i; + u32 v; + + t->sep_ps_gated = -ENODATA; + if (apple_sleep_enclave.stop) { + v = readl(s->ps + T8103_SEP_PS); + writel((v & ~0x0f000700U) | BIT(10), s->ps + T8103_SEP_PS); + t->sep_ps_gated = readl_poll_timeout_atomic(s->ps + T8103_SEP_PS, v, + !FIELD_GET(PS_ACTUAL, v), 10, + T8103_SEP_GATE_US); + t->sep_ps = v; + } + t->commit_off = 0; + t->commit_lowered = 0; + t->agx_saved_valid = false; + if (t->gpu && device_is_bound(&t->gpu->dev)) { + struct apple_sleep_coproc *gc = apple_sleep_coproc_find(&t->gpu->dev); + + if (gc && gc->stop_ret) + panic("T8103 committed GPU stop failed: %d", gc->stop_ret); + } + /* + * Lower GFX (and save its fabric tunables) before stopping PMP, matching macOS and + * newer SoCs where GFX powers off while PMP is still running. + */ + if (!sleep_ps_on(s, t8103_commit_off[T8103_COMMIT_OFF_GFX])) { + t->commit_off |= BIT(T8103_COMMIT_OFF_GFX); + } else { + if (t->agx_fabric) { + for (i = 0; i < ARRAY_SIZE(t8103_agx_regs); i++) + t->agx_saved[i] = readl(t->agx_fabric + t8103_agx_regs[i]); + t->agx_saved_valid = true; + } + if (t->bridges[0]) { + writel(1, t->bridges[0] + T8103_BRIDGE_8014); + writel(1, t->bridges[0] + T8103_BRIDGE_82BC); + writel(2, t->bridges[0] + T8103_BRIDGE_82BC); + writel(4, t->bridges[0] + T8103_BRIDGE_82BC); + } + t->commit_saved[T8103_COMMIT_OFF_GFX] = + readl(s->ps + t8103_commit_off[T8103_COMMIT_OFF_GFX]); + t->commit_lowered |= BIT(T8103_COMMIT_OFF_GFX); + sleep_ps_lower(s, t8103_commit_off[T8103_COMMIT_OFF_GFX]); + if (sleep_ps_wait_off(s, t8103_commit_off[T8103_COMMIT_OFF_GFX])) + panic("T8103 committed GFX power-off timed out"); + t->commit_off |= BIT(T8103_COMMIT_OFF_GFX); + } + t8103_pmp_stop(s); + t->aon_commit_off = 0; + for (i = 0; i < ARRAY_SIZE(t8103_aon_commit_off); i++) { + void __iomem *reg = s->ps_aon + t8103_aon_commit_off[i]; + u32 av = readl(reg); + + if (!FIELD_GET(PS_ACTUAL, av)) { + t->aon_commit_off |= BIT(i); + continue; + } + writel((av & ~(PS_TARGET | PS_AUTO_ENABLE)) | BIT(8) | BIT(9), reg); + if (!readl_poll_timeout_atomic(reg, av, !FIELD_GET(PS_ACTUAL, av), 1, 10000)) + t->aon_commit_off |= BIT(i); + } + for (i = 1; i < ARRAY_SIZE(t8103_commit_off) - 1; i++) { + unsigned int b; + + if (!sleep_ps_on(s, t8103_commit_off[i])) { + t->commit_off |= BIT(i); + continue; + } + for (b = 0; b < ARRAY_SIZE(t8103_bridges); b++) { + if (t8103_bridges[b].ps_off != t8103_commit_off[i] || !t->bridges[b]) + continue; + writel(1, t->bridges[b] + T8103_BRIDGE_8014); + writel(1, t->bridges[b] + T8103_BRIDGE_82BC); + writel(2, t->bridges[b] + T8103_BRIDGE_82BC); + writel(4, t->bridges[b] + T8103_BRIDGE_82BC); + } + t->commit_saved[i] = readl(s->ps + t8103_commit_off[i]); + t->commit_lowered |= BIT(i); + sleep_ps_lower(s, t8103_commit_off[i]); + if (!sleep_ps_wait_off(s, t8103_commit_off[i])) + t->commit_off |= BIT(i); + } + t->cg_commit_off = 0; + for (i = 0; i < ARRAY_SIZE(t8103_cg_commit_off); i++) { + void __iomem *reg = s->ps + t8103_cg_commit_off[i]; + u32 cv = readl(reg); + + t->cg_saved[i] = cv; + if (!FIELD_GET(PS_ACTUAL, cv)) { + t->cg_commit_off |= BIT(i); + continue; + } + sleep_ps_lower(s, t8103_cg_commit_off[i]); + if (!sleep_ps_wait_off(s, t8103_cg_commit_off[i])) + t->cg_commit_off |= BIT(i); + } + for (i = 0; i < ARRAY_SIZE(t8103_ps_boot_auto); i++) { + void __iomem *reg = s->ps + t8103_ps_boot_auto[i]; + u32 bv = readl(reg); + + if ((bv & PS_AUTO_ENABLE) || !FIELD_GET(PS_TARGET, bv) || !FIELD_GET(PS_ACTUAL, bv)) + continue; + writel(bv & ~PS_FLAGS, reg); + readl(reg); + writel((bv & ~PS_FLAGS) | PS_AUTO_ENABLE, reg); + } + for (i = 0; i < ARRAY_SIZE(t8103_aon_boot_auto); i++) { + void __iomem *reg = s->ps_aon + t8103_aon_boot_auto[i]; + u32 bv = readl(reg); + + if ((bv & PS_AUTO_ENABLE) || !FIELD_GET(PS_TARGET, bv) || !FIELD_GET(PS_ACTUAL, bv)) + continue; + writel(bv & ~PS_FLAGS, reg); + readl(reg); + writel((bv & ~PS_FLAGS) | PS_AUTO_ENABLE, reg); + } +} + +/* + * The commit: the memory clock stepped down, the memory controller and cache quiesced, then + * the wake mask, the clock muxes, the CPU complexes' quiesce, CPM gating, the clusters, + * AUTO_ENABLE and SEP's power-gate wait in the order the hardware takes them, then the + * watchdog, the alarm's vector, the PMU's boot stage and the AIC. The shared commit then arms + * the mailbox and writes the S2R timer. Nothing printed, nothing can fail: a timeout is kept + * for the report. + */ +static void t8103_sleep_commit_regs(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i; + u32 v; + + t->committed = true; + /* A hang in the writes below still ends in a reset. */ + apple_sleep_set_wd2(s, T8103_WDT_COMMIT_SECS); + t->dcs_perf_down = false; + if (t->dcs_perf) { + /* The other cores are parked and the coprocessors that use memory are stopped. */ + t->dcs_perf_saved = readl(t->dcs_perf); + t->dcs_perf_down_ok = t8103_dcs_step_to(t->dcs_perf, T8103_DCS_SLEEP, + &t->dcs_perf_down_val); + t->dcs_perf_down = true; + } + /* gpio, the last of t8103_commit_off, once SEP and the SMC are done with it */ + i = ARRAY_SIZE(t8103_commit_off) - 1; + if (!sleep_ps_on(s, t8103_commit_off[i])) { + t->commit_off |= BIT(i); + } else { + sleep_ps_lower(s, t8103_commit_off[i]); + if (!sleep_ps_wait_off(s, t8103_commit_off[i])) + t->commit_off |= BIT(i); + } + t8103_dcs_quiesce(s); + t8103_slc_off(s); + + /* + * E1: DRAM kept up through the sleep for the AOP (SLP_DDR), unless it crashed or this + * sleep goes deep; else its vote cleared. Then every valid source masked but the wanted + * ones and those the platform always leaves on. + */ + t->wake_slp_ddr = readl(s->wake + T8103_WAKE_SLP_DDR); + t->wake_slp_ddr_changed = false; + if (t->aop_slp_ddr && !sleep_slp_ddr_crashed && !sleep_slp_ddr_deep_once) { + writel(t->wake_slp_ddr | T8103_WAKE_SLP_DDR_ON, s->wake + T8103_WAKE_SLP_DDR); + t->wake_slp_ddr_changed = true; + } else if (t->wake_slp_ddr & T8103_WAKE_SLP_DDR_ON) { + writel(t->wake_slp_ddr & ~T8103_WAKE_SLP_DDR_ON, s->wake + T8103_WAKE_SLP_DDR); + t->wake_slp_ddr_changed = true; + } + for (i = 0; i < T8103_WAKE_WORDS; i++) { + u32 mask = t8103_wake_platform[i] & ~t->wanted[i]; + + writel(mask, s->wake + T8103_WAKE_MASK + 4 * i); + s->wake_armed[i] = t8103_wake_valid[i] & ~mask; + } + /* E2: the latched sources cleared */ + for (i = 0; i < T8103_WAKE_WORDS; i++) { + v = readl(s->wake + T8103_WAKE_STATUS + 4 * i); + t->wake_entry[i] = v; + writel(v, s->wake + T8103_WAKE_STATUS + 4 * i); + } + /* E3: the SoC clock muxes parked, each waited for */ + for (i = 0; i < ARRAY_SIZE(t8103_mux_park); i++) { + void __iomem *reg = s->clk_mux + t8103_mux_park[i]; + + writel((readl(reg) & T8103_MUX_PARK_KEEP) | T8103_MUX_PARK_SET, reg); + if (readl_poll_timeout_atomic(reg, v, !(v & T8103_MUX_BUSY), 1, + T8103_MUX_TIMEOUT_US)) + t->mux_timeouts++; + } + /* + * Externally-clocked MCA power domains (ps_mca0..5) hang BUSY in the sleep sequencer + * if their NCO channel is disabled. Enable any disabled channel for the commit. + */ + t->nco_forced = 0; + for (i = 0; i < T8103_NCO_CHANS; i++) { + void __iomem *reg = t->nco + i * T8103_NCO_STRIDE; + + v = readl(reg); + if (!(v & T8103_NCO_CTRL_EN)) { + writel(v | T8103_NCO_CTRL_EN, reg); + t->nco_forced |= BIT(i); + } + } + for (i = 0; i < ARRAY_SIZE(t->mux_snap); i++) + t->mux_snap[i] = readl(s->clk_mux + T8103_MUX_SOC + i * 4); + /* E4: the CPU complexes' and voltage monitors' quiesce */ + t8103_quiesce(s); + /* E5: CPM power gating on */ + for (i = 0; i < ARRAY_SIZE(t8103_cpm); i++) + writel(readl(s->ps + t8103_cpm[i]) | T8103_CPM_GATING, s->ps + t8103_cpm[i]); + /* E6, E7: E cluster to 0 first, then P cluster to 0 */ + writel(readl(s->ps + T8103_CLUSTER_E) & ~PS_TARGET, s->ps + T8103_CLUSTER_E); + writel(readl(s->ps + T8103_CLUSTER_P) & ~PS_TARGET, s->ps + T8103_CLUSTER_P); + if (readl_poll_timeout_atomic(s->ps + T8103_CLUSTER_P, v, !(v & T8103_CLUSTER_BUSY), 1, + CLUSTER_TIMEOUT_US)) + t->cluster_timeouts++; + /* E8: AUTO_ENABLE off on the always-on words */ + for (i = 0; i < ARRAY_SIZE(t8103_auto_off); i++) + writel(readl(s->ps + t8103_auto_off[i]) & ~PS_AUTO_ENABLE, + s->ps + t8103_auto_off[i]); + /* + * E9: the S2R engine doesn't wait for SEP's power gate unless SEP was asked to sleep and + * gated, as the reference waits for before its last SMC step: an engine left waiting for + * a gate that never comes would stall with the watchdog standing still. + */ + t->sep_ps_gated = -ENODATA; + if (apple_sleep_enclave.stop) { + t->sep_ps_gated = readl_poll_timeout_atomic(s->ps + T8103_SEP_PS, v, + !FIELD_GET(PS_ACTUAL, v), 10, + T8103_SEP_GATE_US); + t->sep_ps = v; + } + if (!apple_sleep_enclave.stop || t->sep_ps_gated) { + writel(readl(s->ps + T8103_SEP_PG) & ~T8103_SEP_PG_WAIT, s->ps + T8103_SEP_PG); + t->sep_pg_cleared = true; + } + dsb(sy); + /* E11: the watchdog from here to the wake */ + apple_sleep_set_wd2(s, T8103_WDT_COMMIT_SECS); + /* + * E12: the PMU RTC alarm's SPMI vector acknowledged, then on, so an alarm its RTC driver + * set reaches the wake logic as source 54. + */ + writel(T8103_SPMI_VEC_RTC, s->spmi + T8103_SPMI_VEC_ACK); + writel(readl(s->spmi + T8103_SPMI_VEC_ENABLE) | T8103_SPMI_VEC_RTC, + s->spmi + T8103_SPMI_VEC_ENABLE); + /* E13: the PMU told the AP sleeps */ + t8103_pmu_write(s, T8103_PMU_BOOT_STAGE, T8103_PMU_STAGE_SLEEP); + /* E14: every interrupt line masked, then one already raised taken */ + t8103_aic_mask_all(); + aic_sleep_ack(); + t8103_aic_ipi_quiesce(s); + dsb(sy); +} + +/* After the timer and the AIC's mask, the timer once more, as macOS writes it again then */ +static void t8103_post_timer(struct apple_sleep *s) +{ + dsb(sy); + writel(1, s->commit); +} + +/* W3 to W7, on the boot core with the AIC restored, before any driver resumes */ +static void t8103_sleep_wake(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i; + int pmp_ret = 0; + u32 v; + + t8103_aic_ipi_restore(s); + t8103_slc_on(s); + t8103_dcs_restore(s); + if (t->dcs_perf_down && t->dcs_perf) { + /* The wake left it at T8103_DCS_WAKE, or the sleep never happened. */ + t->dcs_perf_wake_val = readl(t->dcs_perf); + t->dcs_perf_up_ok = t8103_dcs_step_to(t->dcs_perf, t->dcs_perf_saved & 0xf, + &t->dcs_perf_up_val); + t->dcs_perf_down = false; + } + + /* W3: the clusters back, E first */ + for (i = 0; i < ARRAY_SIZE(t8103_cluster); i++) { + void __iomem *reg = s->ps + t8103_cluster[i]; + + writel((readl(reg) & ~PS_TARGET) | CLUSTER_ON, reg); + t->cluster_wake_ret[i] = readl_poll_timeout_atomic(reg, v, + !(v & T8103_CLUSTER_BUSY), 1, + CLUSTER_TIMEOUT_US); + } + s->cluster_e_ret = t->cluster_wake_ret[0]; + s->cluster_p_ret = t->cluster_wake_ret[1]; + + /* W4: AUTO_ENABLE back where it was */ + for (i = 0; i < ARRAY_SIZE(t8103_auto_off); i++) + if (t->auto_word[i] & PS_AUTO_ENABLE) + writel(readl(s->ps + t8103_auto_off[i]) | PS_AUTO_ENABLE, + s->ps + t8103_auto_off[i]); + /* W5: CPM gating as it was */ + for (i = 0; i < ARRAY_SIZE(t8103_cpm); i++) + writel(t->cpm[i], s->ps + t8103_cpm[i]); + /* + * W6: the clock muxes as they were. The sleep's own sequence leaves some muxes the + * commit had enabled parked or off (storage's among them): every one that differs from + * the commit goes back, then the parked ones. + */ + t->mux_fixed = 0; + for (i = 0; i < ARRAY_SIZE(t->mux_snap); i++) { + void __iomem *reg = s->clk_mux + T8103_MUX_SOC + i * 4; + + if (readl(reg) == t->mux_snap[i] || !(t->mux_snap[i] & BIT(31))) + continue; + writel(t->mux_snap[i], reg); + if (readl_poll_timeout_atomic(reg, v, !(v & T8103_MUX_BUSY), 1, + T8103_MUX_TIMEOUT_US)) + t->mux_wake_timeouts++; + t->mux_fixed |= BIT_ULL(i); + } + for (i = 0; i < ARRAY_SIZE(t8103_mux_park); i++) { + void __iomem *reg = s->clk_mux + t8103_mux_park[i]; + + writel(t->mux[i], reg); + if (readl_poll_timeout_atomic(reg, v, !(v & T8103_MUX_BUSY), 1, + T8103_MUX_TIMEOUT_US)) + t->mux_wake_timeouts++; + } + /* Turn back off any NCO channel the commit enabled so clk-apple-nco state matches. */ + for (i = 0; i < T8103_NCO_CHANS; i++) { + void __iomem *reg = t->nco + i * T8103_NCO_STRIDE; + + if (t->nco_forced & BIT(i)) + writel(readl(reg) & ~T8103_NCO_CTRL_EN, reg); + } + t->nco_forced = 0; + /* + * A cluster's ACC answers only while the cluster is powered: after a real sleep both + * were off until W3, and an access before that is an external abort. + */ + t8103_unquiesce(s); + /* SEP's power-gate wait, the alarm's vector and the wake mask as they were */ + if (t->sep_pg_cleared) + writel(t->sep_pg, s->ps + T8103_SEP_PG); + if (apple_sleep_enclave.stop) { + v = readl(s->ps + T8103_SEP_PS); + writel((v & ~0x0f000700U) | (0xfU << 24) | BIT(9), s->ps + T8103_SEP_PS); + } + writel(t->spmi_vec, s->spmi + T8103_SPMI_VEC_ENABLE); + + /* The clock-gated domains the commit lowered */ + for (i = 0; i < ARRAY_SIZE(t8103_cg_commit_off); i++) { + if (t->cg_commit_off & BIT(i)) + sleep_ps_restore(s->ps + t8103_cg_commit_off[i], t->cg_saved[i]); + } + /* + * The apcie and gpio domains the commit found off or couldn't lower, parents first; the + * PMGR driver brings back the ones it lowered. + */ + for (i = ARRAY_SIZE(t8103_commit_off); i > T8103_COMMIT_OFF_APCIE_START; i--) { + unsigned int idx = i - 1; + + if (t->commit_off & BIT(idx)) + sleep_ps_restore(s->ps + t8103_commit_off[idx], 0xf); + } + if (t->commit_lowered & BIT(T8103_COMMIT_OFF_PMP)) + pmp_ret = sleep_ps_restore(s->ps + t8103_commit_off[T8103_COMMIT_OFF_PMP], + t->commit_saved[T8103_COMMIT_OFF_PMP]); + if (t->commit_lowered & BIT(T8103_COMMIT_OFF_RMX)) + sleep_ps_restore(s->ps + t8103_commit_off[T8103_COMMIT_OFF_RMX], + t->commit_saved[T8103_COMMIT_OFF_RMX]); + if (t->commit_lowered & BIT(T8103_COMMIT_OFF_GFX)) { + int gfx_ret = pmp_ret ? pmp_ret : + sleep_ps_restore(s->ps + t8103_commit_off[T8103_COMMIT_OFF_GFX], + t->commit_saved[T8103_COMMIT_OFF_GFX]); + + if (!gfx_ret && t->agx_saved_valid && t->agx_fabric) { + for (i = 0; i < ARRAY_SIZE(t8103_agx_regs); i++) + writel(t->agx_saved[i], t->agx_fabric + t8103_agx_regs[i]); + } + t->gfx_wake_err = gfx_ret; + if (gfx_ret && t->gpu) { + struct apple_sleep_coproc *gc = apple_sleep_coproc_find(&t->gpu->dev); + + if (gc) + gc->wake_err = gfx_ret; + } + } + t->commit_lowered = 0; + for (i = ARRAY_SIZE(t8103_aon_commit_off); i > 0; i--) { + unsigned int idx = i - 1; + + if (t->aon_commit_off & BIT(idx)) + sleep_ps_restore(s->ps_aon + t8103_aon_commit_off[idx], 0xf); + } + /* + * The sleep reset every AP pin with the gpio domain, and the pin controller's driver + * puts back only the ones it configured: all of them back now, before any device + * resumes (storage's link doesn't come up without them). + */ + s->pins_lost = s->pins_saved_valid; + apple_sleep_restore_pins(); + /* W7: what woke the SoC, for the report */ + for (i = 0; i < T8103_WAKE_WORDS; i++) + s->wake_status[i] = readl(s->wake + T8103_WAKE_STATUS + 4 * i); + for (i = 0; i < T8103_WAKE_WORDS; i++) + writel(t->wake_mask[i], s->wake + T8103_WAKE_MASK + 4 * i); + if (t->wake_slp_ddr_changed) { + writel(t->wake_slp_ddr, s->wake + T8103_WAKE_SLP_DDR); + t->wake_slp_ddr_changed = false; + } + + /* Device resume can take a while: the watchdog until .end puts apple_wdt's back. */ + apple_sleep_set_wd2(s, T8103_WDT_RESUME_SECS); +} + +/* At .wake and again at .end: the attempt's results, once */ +static void t8103_sleep_finish(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + + if (!t->attempt) + return; + t->attempt = false; + if (!t->committed) + return; + dev_info(s->dev, "T8103: commit: wake status at entry %08x %08x %08x %08x %08x, mux timeouts %u, cluster timeouts %u, SEP wait %s\n", + t->wake_entry[0], t->wake_entry[1], t->wake_entry[2], t->wake_entry[3], + t->wake_entry[4], t->mux_timeouts, t->cluster_timeouts, + t->sep_pg_cleared ? "cleared" : "kept"); + dev_info(s->dev, "T8103: SEP power state %#x at the commit (gate wait %d)\n", t->sep_ps, + t->sep_ps_gated); + dev_dbg(s->dev, "T8103: stopped PMP %#x SIO %#x DCP %#x DCPEXT %#x, memory cache %#x, quiesce timeouts %u, IPIs pending %#x\n", + t->pmp_result, t->sio_result, t->dcp_result, t->dcpext_result, t->slc_result, + t->quiesce_timeouts, t->aic_result); + if (t->dcs_perf && (!t->dcs_perf_down_ok || !t->dcs_perf_up_ok)) + dev_warn(s->dev, "T8103: DRAM perf state %#x, down to %#x (%s), %#x after the wake, back to %#x (%s)\n", + t->dcs_perf_saved, t->dcs_perf_down_val, + t->dcs_perf_down_ok ? "ok" : "stuck", t->dcs_perf_wake_val, + t->dcs_perf_up_val, t->dcs_perf_up_ok ? "ok" : "stuck"); + if (t->mux_fixed) + dev_info(s->dev, "T8103: clock muxes put back after the wake: %#llx\n", + t->mux_fixed); + if (t->gfx_wake_err) + dev_err(s->dev, "T8103: GFX power restore failed after wake: %d\n", + t->gfx_wake_err); + dev_info(s->dev, "T8103: wake status %08x %08x %08x %08x %08x, clusters %d %d, mux timeouts %u\n", + s->wake_status[0], s->wake_status[1], s->wake_status[2], s->wake_status[3], + s->wake_status[4], t->cluster_wake_ret[0], t->cluster_wake_ret[1], + t->mux_wake_timeouts); +} + +static const struct apple_sleep_wake_name t8103_wake_names[] = { + { 12, "AOP.GPIO.IRQ4" }, { 14, "AOP.GPIO.IRQ6" }, + { 54, "NUB.SPMI0Sw3IRQ" }, + { 76, "SMC.CPUWakeupAP" }, { 81, "SMC.OutboxNotEmpty" }, + { 133, "ATC0.USBWakeup" }, { 134, "ATC1.USBWakeup" }, +}; + +static const struct apple_sleep_ops t8103_sleep_ops = { + .deep_wfi_arm = t8103_deep_wfi_arm, + .resume = t8103_resume_stub, + .aic_mask_all = t8103_aic_mask_all, + .aic_ack = aic_sleep_ack, + .aic_restore = t8103_aic_restore, + .map_regs = t8103_sleep_map_regs, + .begin = t8103_sleep_begin, + .pre_commit = t8103_pre_commit, + .post_timer = t8103_post_timer, + .check = t8103_sleep_check, + .display_off = t8103_sleep_display_off, + .prepare_regs = t8103_sleep_prepare_regs, + .undo_regs = t8103_sleep_undo_regs, + .commit_regs = t8103_sleep_commit_regs, + .wake = t8103_sleep_wake, + .finish = t8103_sleep_finish, + .cpu_prepare = t8103_sleep_cpu_prepare, + .cpu_restore = t8103_sleep_cpu_restore, +}; + +static const struct apple_sleep_soc t8103_sleep_soc = { + .ops = &t8103_sleep_ops, + .early_context = true, + .early_cpu_wfi = true, + .boot_wfi_delay_ms = 3, + /* The wake mask is the AOP's global block, armed and read by the SoC's operations. */ + .own_wake = true, + .wdt_wd1 = true, + .smc_gen1_keys = true, + .boot_mpidr = 0x0, + .cpu_count = 8, + /* MPIDR affinity 2 is the cluster: E 0.0.n, P 1.1.n; start bits 4 * cluster + core */ + .cpu_cluster_affinity = 0, + .cpu_clusters = 2, + .cpu_cores_per_cluster = 4, + .cpu_start_stride = 4, + .cpu_valid = t8103_sleep_cpu_valid, + .cluster_cpu = { T8103_CLUSTER_E, T8103_CLUSTER_P }, + .ncluster_cpu = 2, + .ndisp = 1, + .pmu_usid = T8103_PMU_USID, + .wake_mask = T8103_WAKE_MASK, + .wake_status = T8103_WAKE_STATUS, + .wake_words = T8103_WAKE_WORDS, + .wake_last_word = 0x03ffffff, + .wake_names = t8103_wake_names, + .nwake_names = ARRAY_SIZE(t8103_wake_names), +}; diff --git a/drivers/soc/apple/sleep-t8122.h b/drivers/soc/apple/sleep-t8122.h new file mode 100644 index 00000000000000..957b4fc4b77444 --- /dev/null +++ b/drivers/soc/apple/sleep-t8122.h @@ -0,0 +1,1256 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * T8122 (Apple M3) system suspend-to-RAM support. + * + * Implements the T8122 sleep register map, display/APCIE/ATC/MCC shutdown and + * wake sequences, HID4/EHID4-unblocked PoP/PoC cache clean before deep sleep, + * and CYC_OVRD mode-3 EL1 deep WFI arming. + */ + +#define T8122_PS_GPIO 0x120 +#define T8122_PS_DISP_SYS 0x1d8 +#define T8122_PS_GFX 0x1e0 +#define T8122_PS_DISP_FE 0x208 +#define T8122_PS_SIO_CPU 0x210 +#define T8122_PS_APCIE 0x3f0 +#define T8122_PS_ANS 0x3f8 +#define T8122_PS_ATC0_COMMON 0x400 +#define T8122_PS_ATC1_COMMON 0x408 +#define T8122_PS_APCIE_GP 0x440 +#define T8122_PS_APCIE_ST 0x448 +#define T8122_PS_APCIE_PHY_SW 0x4a0 +#define T8122_PS_SEP 0xc00 +#define T8122_PS_DISP_CPU 0x10000 + +#define T8122_PS_AUTO_IDLE 0x1400000f + +#define T8122_AON_ATC0_USB_AON 0xb0 +#define T8122_AON_ATC1_USB_AON 0xb8 +#define T8122_AON_ATC0_USB 0xc0 +#define T8122_AON_ATC1_USB 0xc8 + +#define T8122_APCIE_PHY_CTRL_RESET BIT(7) +#define T8122_APCIE_PHY_CTRL_UP BIT(9) + +#define T8122_PWRGATE_E 0x80 +#define T8122_PWRGATE_P 0x88 +#define T8122_PWRGATE_DISP_A 0xcac +#define T8122_PWRGATE_DISP_B 0xcd0 +#define T8122_PWRGATE_DISP_C 0xcf0 + +#define T8122_CLUSTER_E 0x0 +#define T8122_CLUSTER_P 0x4 +#define T8122_CLLT_CTL 0x0 +#define T8122_CLLT_LAST 0x24 + +#define T8122_SYS_HID4 sys_reg(3, 0, 15, 4, 0) +#define T8122_SYS_EHID4 sys_reg(3, 0, 15, 4, 1) +#define T8122_HID4_DISABLE_DC_MVA BIT_ULL(11) +#define T8122_HID4_DISABLE_DC_SW_L2 BIT_ULL(44) +#define T8122_HID4_DC_MASK (T8122_HID4_DISABLE_DC_MVA | T8122_HID4_DISABLE_DC_SW_L2) +#define T8122_MPIDR_P_CORE BIT_ULL(16) + +#define T8122_SYS_CYC_OVRD sys_reg(3, 5, 15, 5, 0) +#define T8122_CYC_WFI_MODE GENMASK_ULL(25, 24) + +/* Every PMGR power-state word in the T8122 device tree. */ +static const u32 t8122_ps_all[] = { + 0x100, 0x108, 0x110, 0x118, 0x120, 0x128, 0x130, 0x138, 0x140, 0x148, + 0x150, 0x158, 0x160, 0x168, 0x170, 0x178, 0x180, 0x188, 0x190, 0x198, + 0x1a8, 0x1b0, 0x1b8, 0x1d8, 0x1e0, 0x1e8, 0x1f0, 0x200, 0x208, 0x210, + 0x218, 0x220, 0x228, 0x230, 0x238, 0x240, 0x248, 0x250, 0x258, 0x260, + 0x268, 0x270, 0x278, 0x280, 0x288, 0x290, 0x298, 0x2a0, 0x2a8, 0x2b0, + 0x2b8, 0x2c0, 0x2c8, 0x2d0, 0x2d8, 0x2e0, 0x2e8, 0x2f0, 0x2f8, 0x300, + 0x308, 0x310, 0x318, 0x330, 0x338, 0x340, 0x348, 0x358, 0x360, 0x368, + 0x370, 0x378, 0x380, 0x388, 0x390, 0x398, 0x3a0, 0x3a8, 0x3b0, 0x3b8, + 0x3c0, 0x3f0, 0x3f8, 0x400, 0x408, 0x410, 0x418, 0x420, 0x428, 0x430, + 0x438, 0x440, 0x448, 0x450, 0x458, 0x460, 0x468, 0x470, 0x478, 0x480, + 0x488, 0x490, 0x498, 0x4a0, 0x4a8, 0x4b0, 0x4b8, 0x4c0, 0xc00, 0x4000, + 0x4008, 0x4010, 0x4018, 0x4020, 0x4028, 0x4030, 0x4038, 0x4040, 0x4048, 0x4050, + 0x4058, 0x4060, 0x8000, 0x8008, 0x8010, 0x8018, 0x8020, 0x10000, +}; + +/* + * On at macOS's commit and off once Linux's drivers have suspended: + * DWI, GPIO, SOC_RC, SPI_P, UART_P, AUDIO_P, UART_N, UART0. Parents first. + */ +static const u32 t8122_ps_macos_on[] = { + 0x118, 0x120, 0x168, 0x278, 0x280, 0x288, 0x2d0, 0x2d8, +}; + +/* Off at macOS's commit and left clock-gated by the bootloader. */ +static const u32 t8122_ps_macos_off[] = { + 0x108, 0x138, 0x140, 0x148, 0x150, 0x158, 0x178, 0x228, 0x258, 0x260, + 0x268, 0x270, 0x2f8, 0x300, 0x308, 0x378, 0x380, 0x388, 0x390, 0x3b8, +}; + +static const u32 t8122_ps_aon_all[] = { + 0x0, 0x58, 0x60, 0x68, 0x70, 0x78, 0x80, 0x88, + 0x90, 0x98, 0xa0, 0xa8, 0xb0, 0xb8, 0xc0, 0xc8, +}; + +static const u32 t8122_ps_wake_order[] = { + 0xc00, 0x100, 0x110, 0x118, 0x120, 0x128, 0x130, 0x3f0, + 0x3f8, 0x440, 0x448, 0x450, 0x458, 0x4a0, 0x400, 0x408, +}; + +static const u32 t8122_ps_aon_wake_order[] = { 0x90 }; + +static const struct apple_sleep_word t8122_stray[] = { + { "isp_sys", 0x1e8 }, { "i2c1", 0x238 }, { "i2c2", 0x240 }, { "i2c3", 0x248 }, + { "spi2", 0x2a8 }, { "qspi", 0x2c8 }, { "sio_cpu", 0x210 }, { "apcie_phy_sw", 0x4a0 }, +}; + +static struct { + void __iomem *hpm_notify; + void __iomem *mcc[4]; + void __iomem *apcie_axi; + void __iomem *apcie_rc; + void __iomem *apcie_clkgen; + void __iomem *apcie_phy; + void __iomem *apcie_phy_ip; + void __iomem *apcie_port0; + u32 notify_saved[2]; + bool notify_staged; + bool matched; +} t8122; + +static __always_inline bool t8122_is_pcore(void) +{ + return !!(read_sysreg(mpidr_el1) & T8122_MPIDR_P_CORE); +} + +static __always_inline u64 t8122_read_hid4(bool pcore) +{ + return pcore ? read_sysreg_s(T8122_SYS_HID4) + : read_sysreg_s(T8122_SYS_EHID4); +} + +static __always_inline void t8122_write_hid4(bool pcore, u64 val) +{ + if (pcore) + write_sysreg_s(val, T8122_SYS_HID4); + else + write_sysreg_s(val, T8122_SYS_EHID4); + isb(); +} + +/* + * Clean [start, end) past T8122's L2 into SLC/DRAM via clean-only dc cvadp + * (FEAT_DPB2) or dc cvap (FEAT_DPB). Must run with HID4/EHID4 DISABLE_DC_MVA + * cleared so the maintenance instructions are not ignored as NOPs. + */ +static __always_inline void t8122_clean_range_slc(unsigned long start, unsigned long end) +{ + unsigned long line = 4UL << ((read_sysreg(ctr_el0) >> 16) & 0xf); + unsigned int dpb = read_sysreg(id_aa64isar1_el1) & 0xf; + unsigned long addr = start & ~(line - 1); + + if (dpb >= 2) { + for (; addr < end; addr += line) + asm volatile("sys #3, c7, c13, #1, %0" : : "r"(addr) : "memory"); + } else if (dpb >= 1) { + for (; addr < end; addr += line) + asm volatile("sys #3, c7, c12, #1, %0" : : "r"(addr) : "memory"); + } else { + for (; addr < end; addr += line) + asm volatile("dc civac, %0" : : "r"(addr) : "memory"); + } + dsb(sy); +} + +/* + * Register-only dc csw across all implemented data/unified cache levels + * (L1 + L2 on T8122). Must run with HID4/EHID4 DISABLE_DC_SW_L2 cleared and + * zero stack writes so L1/L2 stay clean through dsb(sy). + */ +static __always_inline void t8122_dcache_clean_all_levels(void) +{ + u64 r_clidr, r_ccidx, r_lvl, r_ctype, r_ccsidr, r_lshift; + u64 r_way, r_mset, r_wshift, r_set, r_tmp; + + asm volatile( + "dsb sy\n\t" + "mrs %[clidr], clidr_el1\n\t" + "mrs %[ccidx], id_aa64mmfr2_el1\n\t" + "ubfx %[ccidx], %[ccidx], #20, #4\n\t" + "mov %[lvl], #0\n\t" + "1:\n\t" + "cmp %[lvl], #7\n\t" + "b.hs 5f\n\t" + "add %[tmp], %[lvl], %[lvl], lsl #1\n\t" + "lsr %[ctype], %[clidr], %[tmp]\n\t" + "and %[ctype], %[ctype], #7\n\t" + "cbz %[ctype], 5f\n\t" + "cmp %[ctype], #2\n\t" + "b.lo 4f\n\t" + "cmp %[ctype], #4\n\t" + "b.hi 4f\n\t" + "lsl %[tmp], %[lvl], #1\n\t" + "msr csselr_el1, %[tmp]\n\t" + "isb\n\t" + "mrs %[ccsidr], ccsidr_el1\n\t" + "and %[lshift], %[ccsidr], #7\n\t" + "add %[lshift], %[lshift], #4\n\t" + "cbnz %[ccidx], 20f\n\t" + "ubfx %[way], %[ccsidr], #3, #10\n\t" + "ubfx %[mset], %[ccsidr], #13, #15\n\t" + "b 21f\n\t" + "20:\n\t" + "ubfx %[way], %[ccsidr], #3, #21\n\t" + "ubfx %[mset], %[ccsidr], #32, #24\n\t" + "21:\n\t" + "clz %w[wshift], %w[way]\n\t" + "2:\n\t" + "mov %[set], %[mset]\n\t" + "lsl %[ctype], %[way], %[wshift]\n\t" + "orr %[ctype], %[ctype], %[lvl], lsl #1\n\t" + "3:\n\t" + "lsl %[tmp], %[set], %[lshift]\n\t" + "orr %[tmp], %[ctype], %[tmp]\n\t" + "dc csw, %[tmp]\n\t" + "subs %[set], %[set], #1\n\t" + "b.ge 3b\n\t" + "subs %[way], %[way], #1\n\t" + "b.ge 2b\n\t" + "dsb sy\n\t" + "4:\n\t" + "add %[lvl], %[lvl], #1\n\t" + "b 1b\n\t" + "5:\n\t" + "msr csselr_el1, xzr\n\t" + "dsb sy\n\t" + "isb\n\t" + : [clidr] "=&r"(r_clidr), + [ccidx] "=&r"(r_ccidx), + [lvl] "=&r"(r_lvl), + [ctype] "=&r"(r_ctype), + [ccsidr] "=&r"(r_ccsidr), + [lshift] "=&r"(r_lshift), + [way] "=&r"(r_way), + [mset] "=&r"(r_mset), + [wshift] "=&r"(r_wshift), + [set] "=&r"(r_set), + [tmp] "=&r"(r_tmp) + : + : "cc", "memory"); +} + +static bool t8122_linear_va_valid(unsigned long addr) +{ + pgd_t *pgdp = pgd_offset_k(addr); + pgd_t pgd = READ_ONCE(*pgdp); + p4d_t *p4dp, p4d; + pud_t *pudp, pud; + pmd_t *pmdp, pmd; + pte_t *ptep; + + if (pgd_none(pgd) || pgd_bad(pgd)) + return false; + p4dp = p4d_offset(pgdp, addr); + p4d = READ_ONCE(*p4dp); + if (p4d_none(p4d) || p4d_bad(p4d)) + return false; + pudp = pud_offset(p4dp, addr); + pud = READ_ONCE(*pudp); + if (pud_none(pud)) + return false; + if (pud_leaf(pud)) + return pud_valid(pud); + if (pud_bad(pud)) + return false; + pmdp = pmd_offset(pudp, addr); + pmd = READ_ONCE(*pmdp); + if (pmd_none(pmd)) + return false; + if (pmd_leaf(pmd)) + return pmd_valid(pmd); + if (pmd_bad(pmd)) + return false; + ptep = pte_offset_kernel(pmdp, addr); + return ptep && pte_valid(READ_ONCE(*ptep)); +} + +static void t8122_clean_used_ram(void) +{ + struct memblock_region *reg; + + for_each_mem_region(reg) { + unsigned long pfn, end_pfn; + unsigned long run_start = 0, run_end = 0; + + if (memblock_is_nomap(reg)) + continue; + pfn = PFN_UP(reg->base); + end_pfn = PFN_DOWN(reg->base + reg->size); + while (pfn < end_pfn) { + struct page *page; + unsigned long va; + + if (!pfn_valid(pfn)) { + if (run_start) { + t8122_clean_range_slc(run_start, run_end); + run_start = 0; + } + pfn++; + continue; + } + page = pfn_to_page(pfn); + if (PageBuddy(page)) { + unsigned long order = page_private(page); + unsigned long nr = 1; + + if (order <= MAX_PAGE_ORDER && + !(pfn & ((1UL << order) - 1))) + nr = 1UL << order; + if (nr > end_pfn - pfn) + nr = end_pfn - pfn; + if (run_start) { + t8122_clean_range_slc(run_start, run_end); + run_start = 0; + } + pfn += nr; + continue; + } + if (PageOffline(page)) { + if (run_start) { + t8122_clean_range_slc(run_start, run_end); + run_start = 0; + } + pfn++; + continue; + } + va = (unsigned long)page_address(page); + if (va && t8122_linear_va_valid(va)) { + if (run_start && va == run_end) { + run_end += PAGE_SIZE; + } else { + if (run_start) + t8122_clean_range_slc(run_start, run_end); + run_start = va; + run_end = va + PAGE_SIZE; + } + } else if (run_start) { + t8122_clean_range_slc(run_start, run_end); + run_start = 0; + } + pfn++; + } + if (run_start) + t8122_clean_range_slc(run_start, run_end); + } + dsb(sy); +} + +/* + * Clean the mapped kernel image (_text.._end). Under CTR_EL0.IDC=1 and + * rodata=full, patched text/rodata aliases are unmapped in the linear map and + * must be cleaned via kernel VAs so DRAM matches patched code on wake. + */ +static void t8122_clean_kernel_image(void) +{ + unsigned long start = (unsigned long)_text & PAGE_MASK; + unsigned long end = PAGE_ALIGN((unsigned long)_end); + unsigned long va, run_start = 0, run_end = 0; + + for (va = start; va < end; va += PAGE_SIZE) { + if (t8122_linear_va_valid(va)) { + if (run_start && va == run_end) { + run_end += PAGE_SIZE; + } else { + if (run_start) + t8122_clean_range_slc(run_start, run_end); + run_start = va; + run_end = va + PAGE_SIZE; + } + } else if (run_start) { + t8122_clean_range_slc(run_start, run_end); + run_start = 0; + } + } + if (run_start) + t8122_clean_range_slc(run_start, run_end); + dsb(sy); +} + +static void t8122_clean_percpu_slc(void) +{ + unsigned int cpu; + + for_each_possible_cpu(cpu) { + unsigned long area = (unsigned long)__per_cpu_start + per_cpu_offset(cpu); + + t8122_clean_range_slc(area, area + (__per_cpu_end - __per_cpu_start)); + } +} + +static void t8122_clean_all_kptables(void) +{ + unsigned int i, j, k, l; + pgd_t *pgd_base = swapper_pg_dir; + + t8122_clean_range_slc((unsigned long)pgd_base, + (unsigned long)pgd_base + PAGE_SIZE); + for (i = 0; i < PTRS_PER_PGD; i++) { + pgd_t pgd = READ_ONCE(pgd_base[i]); + p4d_t *p4d_base; + + if (pgd_none(pgd) || pgd_bad(pgd) || pgd_leaf(pgd)) + continue; + p4d_base = p4d_offset(&pgd_base[i], 0); + if ((unsigned long)p4d_base != (unsigned long)&pgd_base[i]) + t8122_clean_range_slc((unsigned long)p4d_base, + (unsigned long)p4d_base + PAGE_SIZE); + for (j = 0; j < PTRS_PER_P4D; j++) { + p4d_t p4d = READ_ONCE(p4d_base[j]); + pud_t *pud_base; + + if (p4d_none(p4d) || p4d_bad(p4d) || p4d_leaf(p4d)) + continue; + pud_base = pud_offset(&p4d_base[j], 0); + if ((unsigned long)pud_base != (unsigned long)&p4d_base[j]) + t8122_clean_range_slc((unsigned long)pud_base, + (unsigned long)pud_base + PAGE_SIZE); + for (k = 0; k < PTRS_PER_PUD; k++) { + pud_t pud = READ_ONCE(pud_base[k]); + pmd_t *pmd_base; + + if (pud_none(pud) || pud_bad(pud) || pud_leaf(pud)) + continue; + pmd_base = pmd_offset(&pud_base[k], 0); + if ((unsigned long)pmd_base != (unsigned long)&pud_base[k]) + t8122_clean_range_slc((unsigned long)pmd_base, + (unsigned long)pmd_base + PAGE_SIZE); + for (l = 0; l < PTRS_PER_PMD; l++) { + pmd_t pmd = READ_ONCE(pmd_base[l]); + pte_t *pte_base; + + if (pmd_none(pmd) || pmd_bad(pmd) || pmd_leaf(pmd)) + continue; + pte_base = pte_offset_kernel(&pmd_base[l], 0); + if (pte_base) + t8122_clean_range_slc((unsigned long)pte_base, + (unsigned long)pte_base + PAGE_SIZE); + } + } + } + } + dsb(sy); +} + +static void t8122_clean_va_ptables(unsigned long start, unsigned long len) +{ + unsigned long addr = start & PAGE_MASK; + unsigned long end = PAGE_ALIGN(start + len); + + for (; addr < end; addr += PAGE_SIZE) { + pgd_t *pgdp = pgd_offset_k(addr); + p4d_t *p4dp; + pud_t *pudp; + pmd_t *pmdp; + pte_t *ptep; + + t8122_clean_range_slc((unsigned long)pgdp & PAGE_MASK, + ((unsigned long)pgdp & PAGE_MASK) + PAGE_SIZE); + if (pgd_none(*pgdp) || pgd_bad(*pgdp)) + continue; + p4dp = p4d_offset(pgdp, addr); + if ((unsigned long)p4dp != (unsigned long)pgdp) + t8122_clean_range_slc((unsigned long)p4dp & PAGE_MASK, + ((unsigned long)p4dp & PAGE_MASK) + PAGE_SIZE); + if (p4d_none(*p4dp) || p4d_bad(*p4dp)) + continue; + pudp = pud_offset(p4dp, addr); + t8122_clean_range_slc((unsigned long)pudp & PAGE_MASK, + ((unsigned long)pudp & PAGE_MASK) + PAGE_SIZE); + if (pud_none(*pudp) || pud_bad(*pudp) || pud_leaf(*pudp)) + continue; + pmdp = pmd_offset(pudp, addr); + t8122_clean_range_slc((unsigned long)pmdp & PAGE_MASK, + ((unsigned long)pmdp & PAGE_MASK) + PAGE_SIZE); + if (pmd_none(*pmdp) || pmd_bad(*pmdp) || pmd_leaf(*pmdp)) + continue; + ptep = pte_offset_kernel(pmdp, addr); + if (ptep) + t8122_clean_range_slc((unsigned long)ptep & PAGE_MASK, + ((unsigned long)ptep & PAGE_MASK) + PAGE_SIZE); + } +} + +static void t8122_clean_state_poc(struct apple_sleep *s) +{ + unsigned int i, stash_n = mpidr_hash_size(); + + t8122_clean_range_slc((unsigned long)swapper_pg_dir, + (unsigned long)swapper_pg_dir + PAGE_SIZE); + t8122_clean_range_slc((unsigned long)idmap_pg_dir, + (unsigned long)idmap_pg_dir + 3 * PAGE_SIZE); + t8122_clean_va_ptables((unsigned long)current, sizeof(*current)); + t8122_clean_va_ptables((unsigned long)task_stack_page(current), THREAD_SIZE); + t8122_clean_va_ptables((unsigned long)s, sizeof(*s)); + t8122_clean_va_ptables((unsigned long)&t8122, sizeof(t8122)); + if (sleep_save_stash) { + unsigned long base = (unsigned long)sleep_save_stash; + + t8122_clean_va_ptables(base, stash_n * sizeof(*sleep_save_stash)); + t8122_clean_range_slc(base, base + stash_n * sizeof(*sleep_save_stash)); + for (i = 0; i < stash_n; i++) { + unsigned long entry = READ_ONCE(sleep_save_stash[i]); + + if (entry) { + t8122_clean_va_ptables(entry, sizeof(struct sleep_stack_data)); + t8122_clean_range_slc(entry, entry + sizeof(struct sleep_stack_data)); + } + } + } + t8122_clean_range_slc((unsigned long)&mpidr_hash, + (unsigned long)(&mpidr_hash + 1)); + t8122_clean_range_slc((unsigned long)&sleep_save_stash, + (unsigned long)(&sleep_save_stash + 1)); + t8122_clean_range_slc((unsigned long)s, (unsigned long)(s + 1)); + t8122_clean_range_slc((unsigned long)&t8122, (unsigned long)(&t8122 + 1)); + if (s->mbox) + t8122_clean_range_slc((unsigned long)s->mbox, (unsigned long)(s->mbox + 1)); + if (s->ps_commit && s->soc->ps_all.count) + t8122_clean_range_slc((unsigned long)s->ps_commit, + (unsigned long)(s->ps_commit + s->soc->ps_all.count)); + if (s->ps_aon_commit && s->soc->ps_aon_all.count) + t8122_clean_range_slc((unsigned long)s->ps_aon_commit, + (unsigned long)(s->ps_aon_commit + s->soc->ps_aon_all.count)); + if (s->ps_on_saved && s->soc->ps_macos_on.count) + t8122_clean_range_slc((unsigned long)s->ps_on_saved, + (unsigned long)(s->ps_on_saved + s->soc->ps_macos_on.count)); + if (s->ps_off_saved && s->soc->ps_macos_off.count) + t8122_clean_range_slc((unsigned long)s->ps_off_saved, + (unsigned long)(s->ps_off_saved + s->soc->ps_macos_off.count)); + if (s->pins_saved && s->npins) + t8122_clean_range_slc((unsigned long)s->pins_saved, + (unsigned long)(s->pins_saved + s->npins)); + t8122_clean_range_slc((unsigned long)current, + (unsigned long)current + sizeof(*current)); + t8122_clean_range_slc((unsigned long)task_stack_page(current), + (unsigned long)task_stack_page(current) + THREAD_SIZE); + dsb(sy); +} + +static void __iomem *t8122_map(struct apple_sleep *s, const char *name, struct resource *out) +{ + struct device_node *np = s->dev->of_node; + struct resource res; + void __iomem *base; + int index; + + index = of_property_match_string(np, "reg-names", name); + if (index < 0) + return IOMEM_ERR_PTR(index); + if (of_address_to_resource(np, index, &res)) + return IOMEM_ERR_PTR(-EINVAL); + /* Never unmapped: the driver has no unbind, as the common map. */ + base = ioremap_np(res.start, resource_size(&res)); + if (!base) + return IOMEM_ERR_PTR(-ENOMEM); + if (out) + *out = res; + + return base; +} + +static int t8122_sleep_map_regs(struct apple_sleep *s) +{ + static const struct { + const char *name; + size_t offset; + } regs[] = { + { "pwrgate", offsetof(struct apple_sleep, pwrgate) }, + { "cpu-start", offsetof(struct apple_sleep, cpu_start) }, + { "cllt", offsetof(struct apple_sleep, cllt) }, + { "cluster", offsetof(struct apple_sleep, cluster) }, + { "commit", offsetof(struct apple_sleep, commit) }, + { "wdt", offsetof(struct apple_sleep, wdt) }, + { "spmi", offsetof(struct apple_sleep, spmi) }, + { "wake", offsetof(struct apple_sleep, wake) }, + }; + static const char *const mcc_names[4] = { "mcc-a", "mcc-b", "mcc-c", "mcc-d" }; + unsigned int i; + bool pcore; + u64 hid4_orig; + int ret; + + s->ps = t8122_map(s, "ps", &s->ps_res); + if (IS_ERR(s->ps)) + return dev_err_probe(s->dev, PTR_ERR(s->ps), "no ps registers\n"); + for (i = 0; i < ARRAY_SIZE(regs); i++) { + void __iomem **field = (void __iomem **)((u8 *)s + regs[i].offset); + + *field = t8122_map(s, regs[i].name, NULL); + if (IS_ERR(*field)) + return dev_err_probe(s->dev, PTR_ERR(*field), "no %s registers\n", + regs[i].name); + } + t8122.hpm_notify = t8122_map(s, "spmi-hpm", NULL); + if (IS_ERR(t8122.hpm_notify)) + return dev_err_probe(s->dev, PTR_ERR(t8122.hpm_notify), "no spmi-hpm registers\n"); + + s->ps_aon = t8122_map(s, "ps-aon", NULL); + if (IS_ERR(s->ps_aon)) { + dev_warn(s->dev, "no ps-aon registers: USB/debug domains will not be lowered\n"); + s->ps_aon = NULL; + } + + ret = apple_sleep_read_wake_sources(s); + if (ret) + return ret; + + for (i = 0; i < ARRAY_SIZE(mcc_names); i++) { + t8122.mcc[i] = t8122_map(s, mcc_names[i], NULL); + if (IS_ERR(t8122.mcc[i])) { + dev_warn(s->dev, "no %s registers: MCC channel step-down unavailable\n", + mcc_names[i]); + t8122.mcc[i] = NULL; + } + } + + { + static const struct { + const char *name; + void __iomem **slot; + } apcie_regs[] = { + { "apcie-axi", &t8122.apcie_axi }, + { "apcie-rc", &t8122.apcie_rc }, + { "apcie-clkgen", &t8122.apcie_clkgen }, + { "apcie-phy", &t8122.apcie_phy }, + { "apcie-phy-ip", &t8122.apcie_phy_ip }, + { "apcie-port0", &t8122.apcie_port0 }, + }; + + for (i = 0; i < ARRAY_SIZE(apcie_regs); i++) { + *apcie_regs[i].slot = t8122_map(s, apcie_regs[i].name, NULL); + if (IS_ERR(*apcie_regs[i].slot)) + return dev_err_probe(s->dev, PTR_ERR(*apcie_regs[i].slot), + "no %s registers\n", apcie_regs[i].name); + } + } + + /* Ensure the EL1 deep-WFI stub is clean in DRAM before secondary cores jump to it. */ + pcore = t8122_is_pcore(); + hid4_orig = t8122_read_hid4(pcore); + t8122_write_hid4(pcore, hid4_orig & ~T8122_HID4_DISABLE_DC_MVA); + t8122_clean_range_slc((unsigned long)t8142_el1_wfi_stub, + (unsigned long)t8142_el1_wfi_stub_end); + t8122_write_hid4(pcore, hid4_orig); + + s->driver_down = devm_bitmap_zalloc(s->dev, resource_size(&s->ps_res) / 4, GFP_KERNEL); + if (!s->driver_down) + return -ENOMEM; + if (apple_sleep_alloc_books(s)) + return -ENOMEM; + + return 0; +} + +static void t8122_ps_lower_if_on(struct apple_sleep *s, u32 off, u32 first, u32 second) +{ + if (!FIELD_GET(PS_ACTUAL, readl(s->ps + off))) + return; + if (first) + writel(first, s->ps + off); + writel(second, s->ps + off); +} + +static int t8122_sleep_display_off(struct apple_sleep *s) +{ + u64 start, hz = arch_timer_get_cntfrq(); + bool off = false; + + if (FIELD_GET(PS_ACTUAL, readl(s->ps + T8122_PS_DISP_CPU))) { + writel(0x0f0000ff, s->ps + T8122_PS_DISP_CPU); + writel(3, s->pwrgate + T8122_PWRGATE_DISP_A); + writel(0, s->pwrgate + T8122_PWRGATE_DISP_B); + writel(0, s->pwrgate + T8122_PWRGATE_DISP_C); + writel(0x0f0003f0, s->ps + T8122_PS_DISP_CPU); + } + t8122_ps_lower_if_on(s, T8122_PS_DISP_FE, 0, 0x23f0); + t8122_ps_lower_if_on(s, T8122_PS_DISP_SYS, 0, 0x23f0); + + start = read_sysreg(cntvct_el0); + while (read_sysreg(cntvct_el0) - start < hz / 10) { + if (!FIELD_GET(PS_ACTUAL, readl(s->ps + T8122_PS_DISP_CPU))) { + off = true; + break; + } + cpu_relax(); + } + if (!off) { + dev_err(s->dev, "refused: DISP_CPU stayed on: %#x\n", + readl(s->ps + T8122_PS_DISP_CPU)); + return -EBUSY; + } + + return 0; +} + +static void t8122_sleep_match(struct apple_sleep *s) +{ + const struct apple_sleep_soc *soc = s->soc; + int i; + + t8122.matched = true; + for (i = 0; i < soc->ps_macos_on.count; i++) { + u32 offset = soc->ps_macos_on.offset[i]; + + s->ps_on_saved[i] = readl(s->ps + offset); + if (FIELD_GET(PS_ACTUAL, s->ps_on_saved[i]) == 0xf) + continue; + sleep_ps_raise_start(s, offset); + } + for (i = 0; i < soc->ps_macos_off.count; i++) { + u32 offset = soc->ps_macos_off.offset[i]; + + s->ps_off_saved[i] = readl(s->ps + offset); + if (!sleep_ps_on(s, offset)) + continue; + sleep_ps_lower(s, offset); + } + for (i = 0; i < soc->ps_macos_off.count; i++) + sleep_ps_wait_off(s, soc->ps_macos_off.offset[i]); +} + +static void t8122_sleep_match_undo(struct apple_sleep *s) +{ + const struct apple_sleep_soc *soc = s->soc; + int i; + + if (!t8122.matched) + return; + t8122.matched = false; + if (s->returned) + return; + for (i = soc->ps_macos_off.count - 1; i >= 0; i--) + if (FIELD_GET(PS_ACTUAL, s->ps_off_saved[i])) + sleep_ps_raise(s, soc->ps_macos_off.offset[i]); + for (i = soc->ps_macos_on.count - 1; i >= 0; i--) { + u32 val = s->ps_on_saved[i]; + + if (!FIELD_GET(PS_ACTUAL, val)) + sleep_ps_lower(s, soc->ps_macos_on.offset[i]); + else if (FIELD_GET(PS_ACTUAL, val) != 0xf) + writel(val & ~PS_FLAGS, s->ps + soc->ps_macos_on.offset[i]); + } +} + +static void t8122_apcie_down(struct apple_sleep *s) +{ + void __iomem *axi600, *clk, *ctrl, *run, *phy0, *port0; + u32 val, b_phy0; + int ret; + + if (!t8122.apcie_axi || !t8122.apcie_clkgen || !t8122.apcie_phy || + !t8122.apcie_phy_ip || !t8122.apcie_port0) + return; + + ret = sleep_ps_raise_start(s, T8122_PS_APCIE); + ret |= sleep_ps_raise_start(s, T8122_PS_ANS); + ret |= sleep_ps_raise_start(s, T8122_PS_APCIE_GP); + ret |= sleep_ps_raise_start(s, T8122_PS_APCIE_ST); + ret |= sleep_ps_raise_start(s, T8122_PS_APCIE_PHY_SW); + if (ret) { + dev_warn(s->dev, "APCIE power-down raise failed: %d\n", ret); + return; + } + + axi600 = t8122.apcie_axi + 0x600; + clk = t8122.apcie_clkgen + APCIE_CLK_CTRL; + ctrl = t8122.apcie_phy + APCIE_PHY_CTRL; + run = t8122.apcie_phy + APCIE_PHY_RUN; + phy0 = t8122.apcie_phy + 0xc000; + port0 = t8122.apcie_port0; + + /* Port 0 PHY + PERST shutdown */ + b_phy0 = readl(phy0); + if (b_phy0 & 0xc0000603U) { + writel(b_phy0 & ~0xc0000000U, phy0); + writel(readl(axi600) & ~BIT(16), axi600); + writel(readl(port0 + 0x13c) | 0x100, port0 + 0x13c); + writel(0, port0 + APCIE_PORT_PERST); + writel(readl(port0 + 0x13c) & ~0x100, port0 + 0x13c); + writel(readl(phy0) & ~BIT(10), phy0); + writel(readl(phy0) & ~BIT(9), phy0); + writel(readl(phy0) | BIT(4), phy0); + writel(readl(phy0) & ~BIT(0), phy0); + readl_poll_timeout_atomic(phy0, val, !(val & BIT(2)), 1, APCIE_POLL_US); + writel(readl(phy0) & ~BIT(1), phy0); + readl_poll_timeout_atomic(phy0, val, !(val & BIT(3)), 1, APCIE_POLL_US); + writel(readl(port0 + APCIE_PORT_APPCLK) & ~BIT(0), port0 + APCIE_PORT_APPCLK); + writel(readl(axi600) | BIT(16), axi600); + } + + /* Common PHY + PHY IP + AXI + CIO3PLL shutdown */ + writel(readl(t8122.apcie_phy_ip + 0x6c) & ~0xcU, t8122.apcie_phy_ip + 0x6c); + writel(readl(t8122.apcie_phy_ip + 0x7c) | 0x0f000000U, t8122.apcie_phy_ip + 0x7c); + writel(readl(ctrl) | T8122_APCIE_PHY_CTRL_RESET, ctrl); + writel(readl(ctrl) & ~APCIE_PHY_CTRL_CLK1REQ, ctrl); + readl_poll_timeout_atomic(ctrl, val, !(val & APCIE_PHY_CTRL_CLK1ACK), 1, APCIE_POLL_US); + writel(readl(ctrl) & ~APCIE_PHY_CTRL_CLK0REQ, ctrl); + readl_poll_timeout_atomic(ctrl, val, !(val & APCIE_PHY_CTRL_CLK0ACK), 1, APCIE_POLL_US); + writel(readl(run) & ~APCIE_PHY_RUN_EN2, run); + writel(readl(run) & ~APCIE_PHY_RUN_EN, run); + writel(readl(axi600) & ~BIT(16), axi600); + writel(readl(clk) & ~APCIE_CLK_RUN, clk); + writel(readl(clk) | APCIE_CLK_OFF, clk); + writel(readl(clk) & ~APCIE_GEN4_CLK_EN, clk); + readl_poll_timeout_atomic(clk, val, !(val & APCIE_CLK_BUSY), 1, APCIE_POLL_US); + writel(readl(clk) | APCIE_CLK_OFF2, clk); + + writel(T8122_PS_AUTO_IDLE, s->ps + T8122_PS_APCIE_PHY_SW); + readl_poll_timeout_atomic(s->ps + T8122_PS_APCIE_PHY_SW, val, + FIELD_GET(PS_ACTUAL, val) == 4, 1, 5000); + sleep_ps_raise_finish(s, T8122_PS_APCIE); + sleep_ps_raise_finish(s, T8122_PS_ANS); + sleep_ps_raise_finish(s, T8122_PS_APCIE_GP); + sleep_ps_raise_finish(s, T8122_PS_APCIE_ST); +} + +static void t8122_sleep_prepare_regs(struct apple_sleep *s) +{ + t8122_sleep_match(s); + t8122_apcie_down(s); + apple_sleep_pmu_write(s->spmi, s->soc->pmu_usid, + s->soc->pmu_sleep_reg, s->soc->pmu_sleep_val); + t8122.notify_saved[0] = readl(s->spmi + SPMI_NOTIFY_ENABLE); + t8122.notify_saved[1] = readl(t8122.hpm_notify + SPMI_NOTIFY_ENABLE); + t8122.notify_staged = true; + writel(s->soc->spmi_notify_sleep, s->spmi + SPMI_NOTIFY_ENABLE); + writel(s->soc->spmi_notify_sleep, t8122.hpm_notify + SPMI_NOTIFY_ENABLE); +} + +static void t8122_sleep_undo_regs(struct apple_sleep *s) +{ + t8122_sleep_match_undo(s); + if (!t8122.notify_staged) + return; + writel(t8122.notify_saved[0], s->spmi + SPMI_NOTIFY_ENABLE); + writel(t8122.notify_saved[1], t8122.hpm_notify + SPMI_NOTIFY_ENABLE); + t8122.notify_staged = false; +} + +static void t8122_aon_lower(struct apple_sleep *s, u32 off) +{ + u32 val = readl(s->ps_aon + off); + + if (val & PS_AUTO_ENABLE) { + val &= ~(PS_AUTO_ENABLE | PS_FLAGS); + writel(val, s->ps_aon + off); + } + writel((val & ~PS_TARGET) | PS_FLAGS, s->ps_aon + off); +} + +static void t8122_sleep_atc_off(struct apple_sleep *s) +{ + static const struct { + u32 usb, usb_aon, common; + } port[] = { + { T8122_AON_ATC0_USB, T8122_AON_ATC0_USB_AON, T8122_PS_ATC0_COMMON }, + { T8122_AON_ATC1_USB, T8122_AON_ATC1_USB_AON, T8122_PS_ATC1_COMMON }, + }; + unsigned int i; + + if (!s->ps_aon) + return; + for (i = 0; i < ARRAY_SIZE(port); i++) { + t8122_aon_lower(s, port[i].usb); + t8122_aon_lower(s, port[i].usb_aon); + sleep_ps_lower(s, port[i].common); + sleep_ps_wait_off(s, port[i].common); + } +} + +/* + * Step down T8122 MCC channel enable/stage registers after SLC write-back + * (handled by drivers/soc/apple/mcc.c in suspend_noirq) and CPU cache clean. + */ +static const struct { u8 page; u16 off; bool wide; } t8122_mcc_words[] = { + { 2, 0x000, true }, { 0, 0x000, true }, { 1, 0x000, true }, { 2, 0x800, true }, + { 0, 0x800, true }, { 1, 0x800, true }, { 3, 0x584, false }, { 3, 0x588, false }, +}; +static const char t8122_mcc_order[] = + "ABABABABABABAAAAAAAAABABABAABABABABABABABACACCCCCCCCCCCCCCCDDDEDEDFDFDDGGGGGGGGGHH"; + +static void t8122_mcc_channel_stop(void) +{ + unsigned int i; + + if (!t8122.mcc[0] || !t8122.mcc[1] || !t8122.mcc[2] || !t8122.mcc[3]) + return; + for (i = 0; t8122_mcc_order[i]; i++) { + unsigned int w = t8122_mcc_order[i] - 'A'; + void __iomem *reg = t8122.mcc[t8122_mcc_words[w].page] + t8122_mcc_words[w].off; + + if (t8122_mcc_words[w].wide) { + u64 q = readq(reg); + + if (q) + writeq(q & (q - 1), reg); + } else { + u32 l = readl(reg); + + if (l) + writel(l & (l - 1), reg); + } + } +} + +static void t8122_sleep_commit_regs(struct apple_sleep *s) +{ + bool pcore; + u64 hid4_orig; + + sleep_ps_save(s); + t8122_sleep_atc_off(s); + writel(0, s->wdt + WDT_WD0_CTL); + + /* + * Mask and save AIC state before the full cache clean so the saved + * interrupt masks reach DRAM before the clusters power off. + */ + aic_sleep_mask_all(); + + if (s->mbox) { + s->resumes_before = READ_ONCE(s->mbox->resumes); + WRITE_ONCE(s->mbox->resume_pa, __pa_symbol(s->soc->ops->resume)); + } + + pcore = t8122_is_pcore(); + hid4_orig = t8122_read_hid4(pcore); + t8122_write_hid4(pcore, hid4_orig & ~T8122_HID4_DC_MASK); + t8122_clean_used_ram(); + t8122_clean_kernel_image(); + t8122_clean_percpu_slc(); + t8122_clean_all_kptables(); + t8122_clean_state_poc(s); + t8122_dcache_clean_all_levels(); + if (s->mbox) + t8122_clean_range_slc((unsigned long)s->mbox, + (unsigned long)(s->mbox + 1)); + t8122_clean_range_slc((unsigned long)current, + (unsigned long)current + sizeof(*current)); + t8122_clean_range_slc((unsigned long)task_stack_page(current), + (unsigned long)task_stack_page(current) + THREAD_SIZE); + dsb(sy); + t8122_write_hid4(pcore, hid4_orig); + + t8122_mcc_channel_stop(); + + writel(PWRGATE_ON, s->pwrgate + T8122_PWRGATE_E); + writel(PWRGATE_ON, s->pwrgate + T8122_PWRGATE_P); + writel(0, s->cluster + T8122_CLUSTER_E); + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntp_ctl_el0); + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntv_ctl_el0); + sysreg_clear_set_s(SYS_APL_DEEP_SLEEP, 0, DEEP_SLEEP_ENABLE); + writel(0, s->cluster + T8122_CLUSTER_P); + writel(0x2500, s->cllt + T8122_CLLT_CTL); + writel(0, s->cllt + T8122_CLLT_CTL); + writel(0x1c17, s->cllt + T8122_CLLT_LAST); +} + +/* + * Common apple_sleep_commit() writes s->mbox->resume_pa and calls + * dcache_clean_poc() right before pre_commit, which is a NOP on T8122 while + * HID4.DISABLE_DC_MVA is set. Clean s->mbox and s with DISABLE_DC_MVA cleared. + */ +static void t8122_sleep_pre_commit(struct apple_sleep *s) +{ + bool pcore = t8122_is_pcore(); + u64 hid4_orig = t8122_read_hid4(pcore); + + t8122_write_hid4(pcore, hid4_orig & ~T8122_HID4_DISABLE_DC_MVA); + if (s->mbox) + t8122_clean_range_slc((unsigned long)s->mbox, + (unsigned long)(s->mbox + 1)); + t8122_clean_range_slc((unsigned long)s, (unsigned long)(s + 1)); + dsb(sy); + t8122_write_hid4(pcore, hid4_orig); +} + +/* AIC was already masked and saved before the cache clean in commit_regs. */ +static void t8122_aic_mask_noop(void) +{ +} + +static void t8122_deep_wfi_arm(void) +{ + sysreg_clear_set_s(T8122_SYS_CYC_OVRD, 0, T8122_CYC_WFI_MODE); + isb(); + sysreg_clear_set_s(SYS_APL_DEEP_SLEEP, 0, DEEP_SLEEP_ENABLE); + isb(); + if (is_kernel_in_hyp_mode()) { + dsb(sy); + t8142_el1_wfi(); + } +} + +static int t8122_raise_apcie(struct apple_sleep *s) +{ + static const struct { u32 off, val; } axi[] = { + { 0x0034, 0x0000ffff }, { 0x0038, 0x0000ffff }, { 0x0000, 0x00000211 }, + { 0x000c, 0x00016800 }, { 0x0010, 0x0000b400 }, { 0x0108, 0x00100031 }, + { 0x010c, 0x00016800 }, { 0x0110, 0x0000b400 }, { 0x0600, 0xc0010001 }, + { 0x0c00, 0x01ffffff }, { 0x0d48, 0x00200000 }, { 0x0e58, 0x00800010 }, + { 0x1000, 0x00000101 }, + }; + static const struct { u32 off, val; } cio3pll[] = { + { 0x2200, 0x00081f55 }, { 0x2224, 0x00000818 }, { 0x2228, 0x00000b18 }, + { 0x224c, 0x1f800096 }, { 0x22e4, 0x01024201 }, { 0x22fc, 0x030b40b4 }, + }; + static const struct { u32 off, val; } phy_ip[] = { + { 0x0028, 0x00800800 }, { 0x006c, 0x0000004c }, { 0x0080, 0x80010001 }, { 0x0094, 0x00000001 }, + { 0x1204, 0x0000004c }, { 0x1000, 0x2a2383c8 }, { 0x102c, 0x04454447 }, { 0x5080, 0x294d8190 }, + { 0x5088, 0x00560800 }, { 0x508c, 0x294d8190 }, { 0x5094, 0x00060800 }, { 0x50a0, 0x00554800 }, + { 0x50ac, 0x00554800 }, { 0x50b8, 0x00554800 }, { 0x5200, 0x0008155e }, { 0x5224, 0x00000818 }, + { 0x5240, 0x04010f69 }, { 0x52b0, 0x10300811 }, { 0x52fc, 0x03078078 }, { 0x531c, 0x00000002 }, + { 0x608c, 0x65918280 }, { 0x6224, 0x00000818 }, { 0x6228, 0x00000b18 }, { 0x6230, 0x0001e80f }, + { 0x624c, 0x1f80009d }, { 0xa000, 0x080001aa }, { 0xa008, 0x0000000a }, { 0xa00c, 0x0000000a }, + { 0xa010, 0x0000000a }, { 0xa014, 0x0000000a }, { 0xa038, 0x00000271 }, { 0xa040, 0x000000c8 }, + { 0xa04c, 0x00000bff }, { 0xa050, 0x00000001 }, { 0xa068, 0x00000c41 }, { 0xa070, 0x55b00820 }, + { 0xa084, 0x3e8f4240 }, { 0xa088, 0x00000fff }, { 0xa10c, 0x000f4240 }, { 0xa11c, 0x000f30dc }, + { 0xa178, 0x00300000 }, { 0xa0c0, 0x14e051f8 }, { 0xa1a4, 0x00000901 }, { 0xa1b0, 0x00000000 }, + { 0xa1b8, 0x00000000 }, { 0xa1e8, 0x00100000 }, { 0x903c, 0x018c3509 }, { 0x90d8, 0x0102068d }, + { 0x90dc, 0x12004408 }, { 0x91e0, 0x00002008 }, { 0x9288, 0x0801172a }, { 0x9280, 0xcccccccc }, + { 0x9000, 0x1e000000 }, { 0x9280, 0xccc8ccc1 }, { 0x928c, 0x00000003 }, { 0xb02c, 0x01980062 }, + { 0xb098, 0x05028000 }, { 0xc01c, 0x000006a1 }, { 0xc080, 0x540c6831 }, { 0xc08c, 0x10be0c1f }, + { 0xc0a0, 0x021a1780 }, { 0xc0ec, 0x00000000 }, { 0xd008, 0x0000000c }, { 0xd014, 0x04840408 }, + }; + void __iomem *ctrl, *run, *ready, *common; + unsigned int i; + u32 val; + int ret; + + if (!t8122.apcie_axi || !t8122.apcie_rc || !t8122.apcie_clkgen || + !t8122.apcie_phy || !t8122.apcie_phy_ip) + return -ENODEV; + + ret = sleep_ps_raise_start(s, T8122_PS_APCIE); + ret |= sleep_ps_raise_start(s, T8122_PS_ANS); + ret |= sleep_ps_raise_start(s, T8122_PS_APCIE_GP); + ret |= sleep_ps_raise_start(s, T8122_PS_APCIE_ST); + ret |= sleep_ps_raise_start(s, T8122_PS_APCIE_PHY_SW); + if (ret) + return ret; + + for (i = 0; i < ARRAY_SIZE(axi); i++) + writel(axi[i].val, t8122.apcie_axi + axi[i].off); + + writel(0, t8122.apcie_rc + APCIE_RC_ZERO); + + writel(0x239, t8122.apcie_clkgen + APCIE_CLK_CTRL); + writel(0x80000030, t8122.apcie_clkgen + APCIE_CLK_START); + writel(0x80000239, t8122.apcie_clkgen + APCIE_CLK_CTRL); + ret = readl_poll_timeout_atomic(t8122.apcie_clkgen + APCIE_CLK_CTRL, val, + !(val & APCIE_CLK_BUSY), 1, APCIE_POLL_US); + if (ret) + return ret; + for (i = 0; i < ARRAY_SIZE(cio3pll); i++) + writel(cio3pll[i].val, t8122.apcie_clkgen + cio3pll[i].off); + writel(0x239, t8122.apcie_clkgen + APCIE_CLK_CTRL); + + ctrl = t8122.apcie_phy + APCIE_PHY_CTRL; + run = t8122.apcie_phy + APCIE_PHY_RUN; + ready = t8122.apcie_phy + APCIE_PHY_READY; + common = t8122.apcie_phy + APCIE_PHY_COMMON; + + writel(0x03010030, t8122.apcie_phy + 0x800c); + writel(0x0400c030, t8122.apcie_phy + 0x8010); + writel(readl(ctrl) | APCIE_PHY_CTRL_CLK0REQ, ctrl); + ret = readl_poll_timeout_atomic(ctrl, val, val & APCIE_PHY_CTRL_CLK0ACK, 1, APCIE_POLL_US); + if (ret) + return ret; + writel(readl(ctrl) | APCIE_PHY_CTRL_CLK1REQ, ctrl); + ret = readl_poll_timeout_atomic(ctrl, val, val & APCIE_PHY_CTRL_CLK1ACK, 1, APCIE_POLL_US); + if (ret) + return ret; + writel(readl(ctrl) & ~T8122_APCIE_PHY_CTRL_RESET, ctrl); + writel(readl(run) | APCIE_PHY_RUN_EN, run); + + for (i = 0; i < ARRAY_SIZE(phy_ip); i++) + writel(phy_ip[i].val, t8122.apcie_phy_ip + phy_ip[i].off); + + writel(readl(run) | APCIE_PHY_RUN_EN2, run); + ret = readl_poll_timeout_atomic(ready, val, val & BIT(0), 1, APCIE_POLL_US); + if (ret) + return ret; + writel(readl(common) | BIT(0), common); + writel(readl(ctrl) | T8122_APCIE_PHY_CTRL_UP, ctrl); + + writel(0x140, t8122.apcie_rc + APCIE_RC_READY_CFG); + writel(1, t8122.apcie_rc + APCIE_RC_READY_START); + return readl_poll_timeout_atomic(t8122.apcie_rc + APCIE_RC_READY_STAT, val, + val & BIT(0), 1, APCIE_POLL_US); +} + +static void t8122_port0_wake(struct apple_sleep *s) +{ + static const struct { u32 off, val; } port0_init[] = { + { 0x088, 0x00000110 }, { 0x100, 0xffffffff }, { 0x148, 0xffffffff }, + { 0x210, 0xffffffff }, { 0x080, 0x00000000 }, { 0x084, 0x00000000 }, + { 0x104, 0xfffffff0 }, { 0x124, 0x00000100 }, { 0x16c, 0x00000000 }, + { 0x13c, 0x00000010 }, { 0x800, 0x00100100 }, { 0x808, 0x001000ff }, + { 0x82c, 0x00000000 }, { 0x130, 0x03000000 }, { 0x140, 0x00000010 }, + { 0x144, 0x00253770 }, { 0x21c, 0x00000000 }, { 0x834, 0x00000000 }, + { 0x83c, 0x00000000 }, { 0x140, 0x00000011 }, { 0x8a4, 0x00002020 }, + }; + void __iomem *port = t8122.apcie_port0; + unsigned int i; + u32 val; + + writel(readl(t8122.apcie_axi + 0x600) & ~BIT(16), t8122.apcie_axi + 0x600); + + for (i = 0; i < ARRAY_SIZE(port0_init); i++) + writel(port0_init[i].val, port + port0_init[i].off); + + writel(0x00100101, port + APCIE_PORT_APPCLK); + writel(1, port + APCIE_PORT_PERST); + readl_poll_timeout_atomic(port + 0x804, val, val & BIT(0), 1, APCIE_POLL_US); + writel(0x00100001, port + APCIE_PORT_APPCLK); + writel(3, port + 0x4020); + + writel(readl(t8122.apcie_axi + 0x600) | BIT(16), t8122.apcie_axi + 0x600); + + sleep_apcie_port_clock(port, t8122.apcie_phy + 0xc000); +} + +static void t8122_sleep_wake(struct apple_sleep *s) +{ + u32 val; + + writel(CLUSTER_ON, s->cluster + T8122_CLUSTER_E); + s->cluster_e_ret = readl_poll_timeout_atomic(s->cluster + T8122_CLUSTER_E, val, + val & CLUSTER_E_READY, 1, + CLUSTER_TIMEOUT_US); + writel(CLUSTER_ON, s->cluster + T8122_CLUSTER_P); + + writel(PWRGATE_ON, s->pwrgate + s->soc->pwrgate_wake[0]); + writel(PWRGATE_ON, s->pwrgate + s->soc->pwrgate_wake[1]); + + if (s->ps_aon) + sleep_ps_rewake(s); + /* Ensure GPIO domain is on before apple_sleep_restore_pins(). */ + sleep_ps_raise(s, T8122_PS_GPIO); + s->pins_lost = s->pins_saved_valid; + + if (t8122.apcie_axi) { + if (!t8122_raise_apcie(s) && t8122.apcie_port0 && t8122.apcie_phy) + t8122_port0_wake(s); + sleep_ps_raise_finish(s, T8122_PS_APCIE); + sleep_ps_raise_finish(s, T8122_PS_ANS); + sleep_ps_raise_finish(s, T8122_PS_APCIE_GP); + sleep_ps_raise_finish(s, T8122_PS_APCIE_ST); + sleep_ps_raise_finish(s, T8122_PS_APCIE_PHY_SW); + } + + val = readl(s->ps + T8122_PS_SEP); + if (val & PS_DEV_DISABLE) + writel(val & ~PS_DEV_DISABLE, s->ps + T8122_PS_SEP); + + writel(PWRGATE_ON, s->pwrgate + T8122_PWRGATE_E); + writel(PWRGATE_ON, s->pwrgate + T8122_PWRGATE_P); +} + +static const struct apple_sleep_gate_coproc t8122_gate_coprocs[] = { + { "/soc/dcp@28ec00000", true, T8122_PS_DISP_CPU }, + { "/soc/pmp@2d0500000", true }, + { "/soc/gpu@292400000", true, T8122_PS_GFX }, + { "/soc/sep@29e400000" }, + { "/soc/nvme@30dcc0000" }, + { "/soc/smc@2ec400000" }, +}; + +static const struct apple_sleep_wake_name t8122_wake_names[] = { + { 3, "AOP.CPUWakeupAP" }, { 12, "AOP.GPIO.IRQ6" }, { 51, "AOP.OutboxNotEmpty" }, + { 74, "AOP.SPMI0.SW3" }, { 83, "AOP.SPMI1.SW3" }, { 87, "ATC0.CIOWakeup" }, + { 88, "ATC0.USBWakeup" }, { 89, "ATC1.CIOWakeup" }, { 90, "ATC1.USBWakeup" }, + { 100, "MTP.DOCK.CHANNELS.AP0.IRQ" }, { 107, "MTP.GPIO.IRQ4" }, { 109, "MTP.GPIO.IRQ6" }, + { 128, "NUB.APWakeupTime" }, { 129, "NUB.APWatchdog" }, { 143, "NUB.GPIO.IRQ6" }, + { 155, "NUB.SPMI0.SW3" }, { 165, "NUB.SPMI1.SW3" }, { 179, "NUB.WakeupAP" }, + { 184, "SMC.CPUWakeupAP" }, { 208, "SMC.OutboxNotEmpty" }, +}; + +static const u32 t8122_wake_required[] = { 155 }; + +static int t8122_sleep_cpu_prepare(u64 mpidr) +{ + return 0; +} + +static void t8122_sleep_cpu_restore(u64 mpidr) +{ +} + +static const struct apple_sleep_ops t8122_sleep_ops = { + .deep_wfi_arm = t8122_deep_wfi_arm, + .resume = cpu_resume, + .aic_mask_all = t8122_aic_mask_noop, + .aic_ack = aic_sleep_ack, + .aic_restore = aic_sleep_restore, + .map_regs = t8122_sleep_map_regs, + .display_off = t8122_sleep_display_off, + .prepare_regs = t8122_sleep_prepare_regs, + .undo_regs = t8122_sleep_undo_regs, + .commit_regs = t8122_sleep_commit_regs, + .pre_commit = t8122_sleep_pre_commit, + .wake = t8122_sleep_wake, + .cpu_prepare = t8122_sleep_cpu_prepare, + .cpu_restore = t8122_sleep_cpu_restore, +}; + +static const struct apple_sleep_soc t8122_sleep_soc = { + .ops = &t8122_sleep_ops, + .untested = true, + .pen_deep = true, + .el1_wfi = true, + .no_pmu_notes = true, + .display_no_restart = true, + .early_context = true, + .stray = t8122_stray, + .nstray = ARRAY_SIZE(t8122_stray), + .wake_mask = 0x08, + .wake_status = 0x24, + .wake_words = 7, + .wake_last_word = GENMASK(16, 0), + .wake_names = t8122_wake_names, + .nwake_names = ARRAY_SIZE(t8122_wake_names), + .no_wd2 = true, + .early_cpu_wfi = true, + .debug_cut_after_stops = true, + .boot_mpidr = 0x10100, + .cpu_count = 8, + .wake_required = t8122_wake_required, + .nwake_required = ARRAY_SIZE(t8122_wake_required), + .boot_wfi_delay_ms = 2, + .ndisp = 1, + .nmcc = 4, + .cluster_cpu = { T8122_CLUSTER_E, T8122_CLUSTER_P }, + .ncluster_cpu = 2, + .cpu_clusters = 2, + .cpu_cores_per_cluster = 4, + .cpu_start_stride = 4, + .pwrgate_wake = { 0x000, 0x040 }, + .pwrgate_cpm = { T8122_PWRGATE_E, T8122_PWRGATE_P }, + .pmu_usid = 0xe, + .pmu_sleep_reg = 0xf701, + .pmu_sleep_val = 0x50, + .spmi_notify_sleep = 0x2000001, + .ps_aon_debug_switch = 0xa8, + .ps = { + .disp = { { T8122_PS_DISP_CPU, T8122_PS_DISP_FE, T8122_PS_DISP_SYS } }, + .sep = T8122_PS_SEP, + .ans = T8122_PS_ANS, + .apcie_sys_gp = T8122_PS_ANS, + }, + .ps_all = SLEEP_WORDS(t8122_ps_all), + .ps_aon_all = SLEEP_WORDS(t8122_ps_aon_all), + .ps_wake_order = SLEEP_WORDS(t8122_ps_wake_order), + .ps_aon_wake_order = SLEEP_WORDS(t8122_ps_aon_wake_order), + .ps_macos_on = SLEEP_WORDS(t8122_ps_macos_on), + .ps_macos_off = SLEEP_WORDS(t8122_ps_macos_off), + .gate_coprocs = t8122_gate_coprocs, + .ngate_coprocs = ARRAY_SIZE(t8122_gate_coprocs), +}; diff --git a/drivers/soc/apple/sleep-test.c b/drivers/soc/apple/sleep-test.c index fff01f6447e5ad..ad445bdccacc52 100644 --- a/drivers/soc/apple/sleep-test.c +++ b/drivers/soc/apple/sleep-test.c @@ -12,8 +12,19 @@ static const char *const apple_sleep_test_profiles[] = { "apple,t8142-sleep", "apple,t6050-sleep", "apple,t6050-j716c-sleep", + "apple,t8103-sleep", + "apple,t8122-sleep", }; +/* + * Region-based profiles, and those whose operations drive every word themselves (T8103), + * keep their words in their own tables, not in the shared lists checked here. + */ +static bool apple_sleep_test_own_tables(const struct apple_sleep_soc *soc) +{ + return soc->regions || !soc->ps_all.count; +} + static bool apple_sleep_test_has(const struct apple_sleep_words *all, u32 offset) { return sleep_ps_find(all->offset, all->count, offset) >= 0; @@ -59,7 +70,8 @@ static void apple_sleep_test_known_profiles(struct kunit *test) KUNIT_EXPECT_NOT_NULL_MSG(test, id->data, "%s has no data", id->compatible); KUNIT_ASSERT_LT(test, n, ARRAY_SIZE(apple_sleep_test_profiles)); KUNIT_EXPECT_STREQ(test, id->compatible, apple_sleep_test_profiles[n]); - if (!strcmp(id->compatible, "apple,t8142-sleep")) { + if (!strcmp(id->compatible, "apple,t8142-sleep") || + !strcmp(id->compatible, "apple,t8122-sleep")) { const struct apple_sleep_soc *soc = id->data; KUNIT_ASSERT_NOT_NULL(test, soc); @@ -86,8 +98,7 @@ static void apple_sleep_test_words(struct kunit *test) }; int i; - /* Region-based profiles keep their words in their own tables */ - if (soc->regions) + if (apple_sleep_test_own_tables(soc)) continue; apple_sleep_test_full(test, c, "ps_all", all); apple_sleep_test_full(test, c, "ps_aon_all", aon); @@ -201,7 +212,8 @@ static void apple_sleep_test_layout(struct kunit *test) for (id = apple_sleep_of_match; id->compatible[0]; id++) { const struct apple_sleep_soc *soc = id->data; - if (soc->regions) + /* Its memory controller and NI words are its operations' own, too. */ + if (apple_sleep_test_own_tables(soc)) continue; KUNIT_EXPECT_GE(test, soc->ncluster_cpu, 1); KUNIT_EXPECT_LE(test, soc->ncluster_cpu, SLEEP_CPU_CLUSTERS_MAX); @@ -364,6 +376,136 @@ static void apple_sleep_test_region_rejects_bad_inventory(struct kunit *test) KUNIT_EXPECT_EQ(test, sleep_region_validate(&p), -EINVAL); } +struct apple_sleep_test_wdt_saved { + struct device *dev; + void (*restore)(void *data); + void *data; + bool owned; +}; + +struct apple_sleep_test_wdt_ctx { + u32 *wdt_regs; + int calls; + u32 ctl_at_restore; + bool owned_at_restore; +}; + +struct apple_sleep_test_wdt_state { + struct device dev1; + struct device dev2; + u32 fake_wdt[16]; + struct apple_sleep_test_wdt_saved saved; +}; + +static void apple_sleep_test_wdt_restore_global(void *data) +{ + struct apple_sleep_test_wdt_saved *saved = data; + unsigned long flags; + + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + apple_sleep_wdt_dev = saved->dev; + apple_sleep_wdt_restore = saved->restore; + apple_sleep_wdt_data = saved->data; + apple_sleep_wd2_owned = saved->owned; + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); +} + +static void apple_sleep_test_wdt_restore_cb(void *data) +{ + struct apple_sleep_test_wdt_ctx *ctx = data; + + ctx->calls++; + ctx->ctl_at_restore = ctx->wdt_regs[WDT_WD2_CTL / 4]; + ctx->owned_at_restore = apple_sleep_wd2_owned; +} + +static void apple_sleep_test_wdt_handoff(struct kunit *test) +{ + struct resource t6050_sleep_wdt = DEFINE_RES_MEM(0x28836c000ULL, 0x4000); + struct resource t6050_dev_wdt = DEFINE_RES_MEM(0x28836c000ULL, 0x4000); + struct resource t8142_sleep_wdt = DEFINE_RES_MEM(0x23d2b0000ULL, 0x30); + struct resource t8142_dev_wdt = DEFINE_RES_MEM(0x23d2b0000ULL, 0x4000); + struct resource die1_wdt = DEFINE_RES_MEM(0x228836c000ULL, 0x4000); + struct apple_sleep_test_wdt_state *st; + struct apple_sleep_test_wdt_ctx ctx; + unsigned long flags; + + st = kunit_kzalloc(test, sizeof(*st), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, st); + + /* Isolate global handoff state so a probed apple_wdt on J714S/J716C is untouched. */ + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + st->saved.dev = apple_sleep_wdt_dev; + st->saved.restore = apple_sleep_wdt_restore; + st->saved.data = apple_sleep_wdt_data; + st->saved.owned = apple_sleep_wd2_owned; + apple_sleep_wdt_dev = NULL; + apple_sleep_wdt_restore = NULL; + apple_sleep_wdt_data = NULL; + apple_sleep_wd2_owned = false; + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); + KUNIT_ASSERT_EQ(test, + kunit_add_action_or_reset(test, apple_sleep_test_wdt_restore_global, + &st->saved), 0); + + ctx = (struct apple_sleep_test_wdt_ctx){ .wdt_regs = st->fake_wdt }; + + /* Block matching compares resource start across differing map sizes. */ + KUNIT_EXPECT_TRUE(test, apple_sleep_wdt_same_block(&t6050_sleep_wdt, &t6050_dev_wdt)); + KUNIT_EXPECT_TRUE(test, apple_sleep_wdt_same_block(&t8142_sleep_wdt, &t8142_dev_wdt)); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_same_block(&t6050_sleep_wdt, &die1_wdt)); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_same_block(NULL, &t6050_dev_wdt)); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_same_block(&t6050_sleep_wdt, NULL)); + + /* Invalid arguments and unmatched watchdogs. */ + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(NULL, true, + apple_sleep_test_wdt_restore_cb, + &ctx), -EINVAL); + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev1, true, NULL, &ctx), + -EINVAL); + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev2, false, + apple_sleep_test_wdt_restore_cb, + &ctx), 0); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_active(&st->dev2)); + + /* Matching watchdog claims the single slot; a second claiming it gets -EBUSY. */ + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev1, true, + apple_sleep_test_wdt_restore_cb, + &ctx), 0); + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev2, true, + apple_sleep_test_wdt_restore_cb, + &ctx), -EBUSY); + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev2, false, + apple_sleep_test_wdt_restore_cb, + &ctx), 0); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_active(&st->dev1)); + + /* Ownership applies only to the registered watchdog; .end orders CTL=0, restore, clear. */ + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + apple_sleep_wd2_owned = true; + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); + KUNIT_EXPECT_TRUE(test, apple_sleep_wdt_active(&st->dev1)); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_active(&st->dev2)); + + st->fake_wdt[WDT_WD2_CTL / 4] = 1; + apple_sleep_wdt_end((void __iomem __force *)st->fake_wdt); + KUNIT_EXPECT_EQ(test, ctx.calls, 1); + KUNIT_EXPECT_EQ(test, ctx.ctl_at_restore, 0u); + KUNIT_EXPECT_TRUE(test, ctx.owned_at_restore); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_active(&st->dev1)); + + /* Unregistering a non-holder leaves the slot intact; unregistering the holder frees it. */ + apple_sleep_wdt_unregister(&st->dev2); + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev2, true, + apple_sleep_test_wdt_restore_cb, + &ctx), -EBUSY); + apple_sleep_wdt_unregister(&st->dev1); + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev2, true, + apple_sleep_test_wdt_restore_cb, + &ctx), 0); + apple_sleep_wdt_unregister(&st->dev2); +} + static struct kunit_case apple_sleep_test_cases[] = { KUNIT_CASE(apple_sleep_test_layout), KUNIT_CASE(apple_sleep_test_t6050), @@ -377,6 +519,7 @@ static struct kunit_case apple_sleep_test_cases[] = { KUNIT_CASE(apple_sleep_test_words), KUNIT_CASE(apple_sleep_test_books), KUNIT_CASE(apple_sleep_test_wake_names), + KUNIT_CASE(apple_sleep_test_wdt_handoff), {} }; diff --git a/drivers/soc/apple/sleep-v27-late.inc b/drivers/soc/apple/sleep-v27-late.inc index a130d3bd94d3a0..5adb3a10f261ba 100644 --- a/drivers/soc/apple/sleep-v27-late.inc +++ b/drivers/soc/apple/sleep-v27-late.inc @@ -141,7 +141,7 @@ static int sleep_v27_final_check(unsigned int i) if (!sleep_v27_held || i >= ARRAY_SIZE(sleep_v27) || !sleep_v27[i].armed || !READ_ONCE(sleep_v27[i].prepared)) return -EBUSY; - return sleep_v27[i].ops->check(sleep_v27[i].data); + return sleep_v27[i].ops->check(sleep_v27[i].data, apple_sleep->entry_committed); } static bool sleep_v27_gate_prepared(const struct device_node *np) diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 9cee856626f918..4c25f5fd21cbf6 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -44,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -51,6 +52,8 @@ #include #include #include +#include +#include #include #include #include @@ -58,7 +61,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -85,6 +90,7 @@ #include #include #include +#include #include #include #include @@ -137,9 +143,13 @@ struct aura_s2r_mailbox { #define WDT_WD0_COUNT 0x00 #define WDT_WD0_CTL 0x0c #define WDT_WD1_COUNT 0x10 +#define WDT_WD1_BITE 0x14 +#define WDT_WD1_CTL 0x1c +#define WDT_WD1_RESET_EN BIT(2) #define WDT_WD2_COUNT 0x20 #define WDT_WD2_ALARM 0x28 #define WDT_WD2_CTL 0x2c +#define WDT_WD2_CTL_IRQ_STATUS BIT(1) #define WDT_TICKS_PER_S 24000000 /* The sleep's own safety net: ADT /arm-io/wdt simple-reconfig-wdog-icc-time. */ #define WDT_SLEEP_SECS 5 @@ -148,9 +158,10 @@ struct aura_s2r_mailbox { #define AON_AP_DEADLINE 0x08 /* - * T8142: a word of the watchdog's second page (/arm-io/wdt + 0x802c). macOS's entry - * read-modify-writes it from 0 to 0x20 right before WD0's control and WD2 (26B131 trace, - * 11.1 ms before the S2R timer); XNU writes 0x10 there during boot. Meaning unknown. + * Simple-reconfig WD2 routing word (bits 5:4: 01 = run-time cold reset, 10 = sleep-commit + * routing). Lives at wdt-aux + 0x2c on T6050 and aon-misc + 0x2c (/arm-io/wdt + 0x802c) on + * T8142; sleep saves it before commit (T6050 DT sequence writes 0x20, T8142 ORs 0x20) and + * restores the saved value on wake. */ #define AON_WDT_SLEEP 0x2c @@ -374,6 +385,7 @@ static struct apple_sleep_coproc { bool stopped; u32 status; int stop_ret; + int wake_err; /* No ASC: its last stop takes it whole, power word @ps included, before the others. */ bool first; /* Between ANS and the others, whatever order they registered in. */ @@ -663,6 +675,19 @@ struct apple_sleep_soc { bool early_context; /* The SoC's operations arm and read its wake sources: none of the common wake words */ bool own_wake; + /* Secondary and boot cores drop to EL1 with MMU off for their final deep WFI. */ + bool el1_wfi; + /* WD2 is not this SoC's measured sleep safety net. */ + bool no_wd2; + /* Keep the debug link until the coprocessors have stopped. */ + bool debug_cut_after_stops; + /* The PMU scratch the step notes are written to is unmeasured on this SoC: none are. */ + bool no_pmu_notes; + /* + * The first display's driver stops its coprocessor cold for a sleep and can't restart + * it. A dry run leaves it running and doesn't count it among the refusals. + */ + bool display_no_restart; bool strict_gate_inventory; /* * No PMP runs and its report is disabled: the PTD entries the commit drops have no @@ -770,6 +795,12 @@ struct apple_sleep_soc { unsigned int nwake_names; /* The sources in the wake block's last word */ u32 wake_last_word; + /* + * Sources the tree's apple,wake-enable must name, or the sleep is refused: the ones a + * timed wake arrives on, so a sleep can't be entered that only a person can end. + */ + const u32 *wake_required; + unsigned int nwake_required; /* The encoders' system power words: their domains need the AVE complex up */ const u32 *ave_domains; unsigned int nave_domains; @@ -807,6 +838,13 @@ struct apple_sleep_soc { * the commit (apple_sleep.early_wfi): XNU's order (T8142, J813 ten-core trace). */ bool early_cpu_wfi; + /* + * The sleep's safety net is WD1 (count +0x10, bite +0x14, control +0x1c, reset enable + * bit 2), which apple_wdt also drives: the one it had is put back at .end. + */ + bool wdt_wd1; + /* The SMC gets pmVC and WKTP before slpa (gen 1, as t6000 has them) */ + bool smc_gen1_keys; }; struct apple_sleep { @@ -816,6 +854,7 @@ struct apple_sleep { void __iomem *ps; void __iomem *pwrgate; void __iomem *cpu_start; + unsigned int cpu_burst_n; /* cores the last wake's burst started */ void __iomem *cllt; void __iomem *cluster; void __iomem *commit; @@ -962,12 +1001,15 @@ struct apple_sleep { void __iomem *apcie_phy; void __iomem *apcie_rc; bool apcie_port_stopped; + bool apcie_port2_stopped; /* A real sleep left the radio's port down, until its host sets it up again */ bool apcie_port_down; void __iomem *apcie_port; void __iomem *apcie_port_phy; /* Ports no host sets up again after a real sleep: no managed radio contract */ bool apcie_ports_unowned; + /* The host has an available pci@2,0: the endpoint on port 2 is stopped at the commit */ + bool apcie_port2_enabled; void __iomem *apcie_port2; void __iomem *apcie_port2_phy; void __iomem *apcie_engine; @@ -1007,10 +1049,15 @@ struct apple_sleep { /* The radio port's PERST# among them, or -1 */ int radio_perst; bool radio_perst_low; + /* The PERST# of the endpoint on port 2, or -1 */ + int port2_perst; + bool port2_perst_low; bool returned; /* This wake came back down the deep path, not the DRAM-kept one. */ bool deep_ran; bool regs_staged, wake_masks_saved, entry_prepared, entry_committed; + /* An untested SoC's sleep that stops before the commit, as .begin found the switch. */ + bool dry_run; u64 smc_idle_sent, smc_idle_ack, timer_at; struct { struct device *dev; @@ -1065,9 +1112,6 @@ struct apple_sleep { void __iomem *acc_e; void __iomem *acc_p; int cluster_p_ret; - int perf_soc_ret; - int perf_dcs_ret; - unsigned int perf_dcs_from; /* With radio_retrain: the radio's PCIe host, and its port's blocks and tables */ struct device_node *radio_host_np; void __iomem *radio_port; @@ -1080,6 +1124,9 @@ struct apple_sleep { /* The radio's port stop at the commit (sleep_radio_port_stop()), and its first timeout */ int radio_stop_ret; const char *radio_stop_step; + /* With wdt_wd1: WD1's control and bite time at .begin, put back at .end */ + u32 wd1_saved_ctl, wd1_saved_bite; + bool wd1_saved; }; static struct apple_sleep *apple_sleep; @@ -1139,6 +1186,18 @@ module_param_named(untested_commit, sleep_untested_commit, bool, 0644); MODULE_PARM_DESC(untested_commit, "Untested SoC: let a deep sleep through to the commit (else a dry run that refuses)"); +/* + * Whether this sleep is an untested SoC's dry run. An early_context SoC's drivers ask the same + * answer in their .suspend, so it is the one .begin latched: the switch can't change under a + * sleep. The common entry reads the switch where it stops, as before. + */ +static bool apple_sleep_dry(const struct apple_sleep *s) +{ + if (!s->soc->untested) + return false; + return s->soc->early_context ? s->dry_run : !READ_ONCE(sleep_untested_commit); +} + /* * Untested SoCs: each step of a sleep in PMU scratch, readable after a reset. J815's ADT * pmu-main info-scrpad is 0x8000 + 0x2800; aurora-silicon/linux#1664 (T6041) notes its steps @@ -1637,6 +1696,8 @@ void apple_sleep_coproc_set_ready(struct device *dev, bool ready) return; c->ready = ready; c->stopped = false; + c->stop_ret = 0; + c->wake_err = 0; } EXPORT_SYMBOL_GPL(apple_sleep_coproc_set_ready); @@ -1650,12 +1711,40 @@ bool apple_sleep_coproc_stopped(struct device *dev) } EXPORT_SYMBOL_GPL(apple_sleep_coproc_stopped); +int apple_sleep_coproc_wake_error(struct device *dev) +{ + struct apple_sleep_coproc *c; + + guard(mutex)(&apple_sleep_coprocs_lock); + c = apple_sleep_coproc_find(dev); + return c ? c->wake_err : -ENODEV; +} +EXPORT_SYMBOL_GPL(apple_sleep_coproc_wake_error); + +static bool apple_sleep_external_commit; + +void apple_sleep_set_commit_stops_coprocs(bool enable) +{ + WRITE_ONCE(apple_sleep_external_commit, enable); +} +EXPORT_SYMBOL_GPL(apple_sleep_set_commit_stops_coprocs); + bool apple_sleep_commit_stops_coprocs(void) { - return READ_ONCE(apple_sleep) && pm_suspend_via_firmware(); + return (READ_ONCE(apple_sleep) || READ_ONCE(apple_sleep_external_commit)) && + pm_suspend_via_firmware(); } EXPORT_SYMBOL_GPL(apple_sleep_commit_stops_coprocs); +/* This firmware sleep stops before its commit: a driver must stop nothing it can't restart. */ +bool apple_sleep_dry_run(void) +{ + struct apple_sleep *s = READ_ONCE(apple_sleep); + + return s && pm_suspend_via_firmware() && apple_sleep_dry(s); +} +EXPORT_SYMBOL_GPL(apple_sleep_dry_run); + /* * The last thing that can fail on the way to the commit: no CPU but this one is up and * interrupts are off, so no lock can be held. A coprocessor stopped here comes back only @@ -1670,7 +1759,8 @@ static void apple_sleep_coproc_run_off(struct apple_sleep_coproc *c) c->stopped = true; return; } - if (!apple_sleep->soc->regions) + /* T6041's own sleep driver runs this without the sleep core. */ + if (!apple_sleep || !apple_sleep->soc->regions) c->status = readl(c->asc + ASC_CPU_STATUS); writel(readl(c->asc + ASC_CPU_CONTROL) & ~ASC_CPU_CONTROL_RUN, c->asc + ASC_CPU_CONTROL); writel(readl(c->asc + ASC_CPU_CONTROL) & ~ASC_CPU_CONTROL_RUN, c->asc + ASC_CPU_CONTROL); @@ -1789,6 +1879,87 @@ static void apple_sleep_coprocs_stop(struct apple_sleep *s, bool first) dsb(sy); } +/* + * For a SoC whose sleep has its own driver at EL2 (T6041): last refusal checks + * before any irreversible enclave or coprocessor stop. + */ +int apple_sleep_coprocs_check_all(void) +{ + int i, ret; + + for (i = 0; i < SLEEP_COPROCS; i++) { + struct apple_sleep_coproc *c = &apple_sleep_coprocs[i]; + + if (!c->dev || !c->ready || c->stopped || !c->last_check) + continue; + ret = c->last_check(c->data); + if (ret) { + dev_err(c->dev, "refused at sleep commit: %d\n", ret); + return ret; + } + } + + return 0; +} + +/* + * For a SoC whose sleep has its own driver at EL2 (T6041): run the enclave's + * irreversible sleep request with interrupts off. A nonzero return guarantees + * no SLEEP request was sent. + */ +int apple_sleep_enclave_stop_all(void) +{ + int ret; + + if (!apple_sleep_enclave.stop) + return 0; + ret = apple_sleep_enclave.stop(apple_sleep_enclave.data); + if (ret && apple_sleep_enclave.dev) + dev_err(apple_sleep_enclave.dev, + "refused before SEP SLEEP was sent: %d\n", ret); + + return ret; +} + +/* + * For a SoC whose sleep has its own driver at EL2 (T6041): both passes of the stop above, + * the coprocessors registered first, then the rest. Past the refusal boundary every ready + * coprocessor is still halted even if one @last_stop reports a negative error. + */ +int apple_sleep_coprocs_stop_all(void) +{ + int pass, i, ret, first_err = 0; + + for (pass = 1; pass >= 0; pass--) { + for (i = 0; i < SLEEP_COPROCS; i++) { + struct apple_sleep_coproc *c = &apple_sleep_coprocs[i]; + + if (!c->dev || !c->ready || c->first != pass || c->stopped) + continue; + if (c->last_stop) { + ret = c->last_stop(c->data); + if (ret < 0 && !first_err) + first_err = ret; + } + apple_sleep_coproc_run_off(c); + } + } + dsb(sy); + return first_err; +} + +/* For T6041: whether the coprocessor behind the storage PCIe link (ANS) was stopped. */ +bool apple_sleep_coprocs_ans_stopped(void) +{ + int i; + + for (i = 0; i < SLEEP_COPROCS; i++) + if (apple_sleep_coprocs[i].dev && apple_sleep_coprocs[i].pcie_ans && + apple_sleep_coprocs[i].stopped) + return true; + return false; +} + const struct apple_sleep_smc_policy *apple_sleep_smc_policy(void) { return apple_sleep && pm_suspend_via_firmware() ? apple_sleep->soc->smc_policy : NULL; @@ -1802,11 +1973,21 @@ MODULE_PARM_DESC(j813_smc_late, bool apple_sleep_smc_defer_notice(void) { - return apple_sleep && READ_ONCE(sleep_j813_smc_late) && - of_machine_is_compatible("apple,j813") && pm_suspend_via_firmware(); + if (!apple_sleep || !pm_suspend_via_firmware()) + return false; + /* Gen 1 (T8103): SEP sleeps before the SMC is told, as on macOS and t6000. */ + if (apple_sleep->soc->smc_gen1_keys) + return true; + return READ_ONCE(sleep_j813_smc_late) && of_machine_is_compatible("apple,j813"); } EXPORT_SYMBOL_GPL(apple_sleep_smc_defer_notice); +bool apple_sleep_smc_gen1_keys(void) +{ + return apple_sleep && apple_sleep->soc->smc_gen1_keys && pm_suspend_via_firmware(); +} +EXPORT_SYMBOL_GPL(apple_sleep_smc_gen1_keys); + int apple_sleep_smc_register(struct device *dev, int (*late_notice)(void *data, u64 *sent, u64 *ack), void *data) { @@ -1860,6 +2041,125 @@ void apple_sleep_smc_unregister(struct device *dev) } EXPORT_SYMBOL_GPL(apple_sleep_smc_unregister); +static const struct of_device_id apple_sleep_of_match[]; + +static DEFINE_SPINLOCK(apple_sleep_wdt_lock); +static struct device *apple_sleep_wdt_dev; +static void (*apple_sleep_wdt_restore)(void *data); +static void *apple_sleep_wdt_data; +static bool apple_sleep_wd2_owned; + +static bool apple_sleep_wdt_same_block(const struct resource *sleep_wdt, + const struct resource *wdt) +{ + if (!sleep_wdt || !wdt) + return false; + return sleep_wdt->start == wdt->start; +} + +static bool apple_sleep_dt_owns_wdt(const struct resource *wdt) +{ + struct device_node *np = NULL; + bool found = false; + + if (!wdt) + return false; + + for_each_matching_node(np, apple_sleep_of_match) { + struct resource res; + int idx; + + if (!of_device_is_available(np)) + continue; + idx = of_property_match_string(np, "reg-names", "wdt"); + if (idx < 0 || of_address_to_resource(np, idx, &res)) + continue; + if (apple_sleep_wdt_same_block(&res, wdt)) { + found = true; + of_node_put(np); + break; + } + } + + return found; +} + +static int apple_sleep_wdt_register_matched(struct device *dev, bool matched, + void (*restore)(void *data), void *data) +{ + unsigned long flags; + + if (!dev || !restore) + return -EINVAL; + if (!matched) + return 0; + + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + if (apple_sleep_wdt_dev && apple_sleep_wdt_dev != dev) { + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); + return -EBUSY; + } + apple_sleep_wdt_dev = dev; + apple_sleep_wdt_restore = restore; + apple_sleep_wdt_data = data; + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); + + return 0; +} + +int apple_sleep_wdt_register(struct device *dev, const struct resource *wdt, + void (*restore)(void *data), void *data) +{ + if (!dev || !wdt || !restore) + return -EINVAL; + + return apple_sleep_wdt_register_matched(dev, apple_sleep_dt_owns_wdt(wdt), + restore, data); +} +EXPORT_SYMBOL_GPL(apple_sleep_wdt_register); + +void apple_sleep_wdt_unregister(struct device *dev) +{ + unsigned long flags; + + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + if (apple_sleep_wdt_dev == dev) { + apple_sleep_wdt_dev = NULL; + apple_sleep_wdt_restore = NULL; + apple_sleep_wdt_data = NULL; + } + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); +} +EXPORT_SYMBOL_GPL(apple_sleep_wdt_unregister); + +bool apple_sleep_wdt_active(struct device *dev) +{ + unsigned long flags; + bool active; + + if (!dev) + return false; + + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + active = apple_sleep_wd2_owned && apple_sleep_wdt_dev == dev; + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); + + return active; +} +EXPORT_SYMBOL_GPL(apple_sleep_wdt_active); + +static void apple_sleep_wdt_end(void __iomem *wdt) +{ + unsigned long flags; + + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + writel(0, wdt + WDT_WD2_CTL); + if (apple_sleep_wdt_restore) + apple_sleep_wdt_restore(apple_sleep_wdt_data); + apple_sleep_wd2_owned = false; + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); +} + void apple_sleep_display_quiesced(struct device *dev, bool quiesced) { struct apple_sleep *s = apple_sleep; @@ -1916,10 +2216,10 @@ static int apple_sleep_validate_cpu_topology(struct apple_sleep *s) soc->cpu_cores_per_cluster > 32) return dev_err_probe(s->dev, -EINVAL, "invalid CPU-start geometry\n"); - if (soc->machine && (!of_machine_is_compatible(soc->machine) || - cpu_logical_map(0) != soc->boot_mpidr || - num_possible_cpus() != soc->cpu_count)) - return dev_err_probe(s->dev, -EINVAL, "unsupported board/CPU inventory\n"); + /* The node's compatible chose the profile: its machine is where it was measured */ + if (soc->machine && (cpu_logical_map(0) != soc->boot_mpidr || + num_possible_cpus() != soc->cpu_count)) + return dev_err_probe(s->dev, -EINVAL, "unsupported CPU inventory\n"); index = of_property_match_string(np, "reg-names", "cpu-start"); if (index < 0) @@ -2257,9 +2557,17 @@ MODULE_PARM_DESC(mem_restore, "T8142: put the memory side (AMCC, SoC NI, DCS) ba static bool sleep_clk_restore = true; module_param_named(clk_restore, sleep_clk_restore, bool, 0644); MODULE_PARM_DESC(clk_restore, "T8142: put the 126 PMGR clkgen slots and the memory clock word back at the wake as XNU does"); -static bool sleep_perf_down = true; -module_param_named(perf_down, sleep_perf_down, bool, 0644); -MODULE_PARM_DESC(perf_down, "T8142: SoC/DCS perf states down before the memory stop (macOS on J813 never writes them; A/B)"); +/* + * The cores' start after a T8142 wake. A traced macOS 27.2 run on J813 (boot, a 40 s sleep, the + * wake and three more entries) starts all nine other cores 16.5 ms after the wake, right after + * the memory side and the WD2 stop, in one 0.23 ms burst, three words each: +4 the core's bit, +8 + * the E core's bit or 0, +0xc the P core's bit or 0. The wake does the same for the cores that + * were online when the sleep began (t8142_cpu_burst()); they come up through the boot object + * into the kernel's holding pen and wait there, and each bring-up only releases its core. + */ +static struct cpumask sleep_cpus_burst; +/* The CPUs online at .begin: the ones the PM core brings back after the wake. */ +static struct cpumask sleep_cpus_awake; static u64 t8142_boot_mpidr = ~0ULL; extern char t8142_el1_wfi_stub[], t8142_el1_wfi_stub_end[]; @@ -2519,6 +2827,13 @@ static int sleep_cpu_on(u64 mpidr) bool trace; DEFINE_DYNAMIC_DEBUG_METADATA(cpu_on_trace, "apple-sleep: cpu start after a sleep\n"); + /* Started by the wake's burst: it waits in the pen; release it. */ + if (cpu >= 0 && cpumask_test_and_clear_cpu(cpu, &sleep_cpus_burst)) { + pr_debug("apple-sleep: cpu%d start %#llx: started in the wake burst (%u cores), released from the pen\n", + cpu, mpidr, s->cpu_burst_n); + return 0; + } + trace = DYNAMIC_DEBUG_BRANCH(cpu_on_trace) && s->soc->cpu_clusters >= 2; if (trace) { slot = sleep_cpu_slot_map(cpu); @@ -3145,6 +3460,10 @@ static bool apple_sleep_gate_failed(struct apple_sleep *s) /* Idled below full power, or stopped: its registers read only at full power. */ if (g->asc && g->ps && !sleep_asc_running(s, g->ps, g->asc)) continue; + /* Left running by a dry run, see apple_sleep_refuse(). */ + if (s->soc->display_no_restart && s->display[0].np && g->np == s->display[0].np && + apple_sleep_dry(s)) + continue; if (g->asc && g->ps && (g->allow_unstarted || s->soc->regions)) dev_err(s->dev, "%s didn't stop: control %#x\n", g->name, readl(g->asc + ASC_CPU_CONTROL)); @@ -3209,6 +3528,24 @@ static void sleep_wake_masks(struct apple_sleep *s, u32 *val) sleep_wake_unmask(s, val, s->wake_enable[i]); } +/* Every source the SoC requires is among the tree's. A SoC that requires none admits any. */ +static bool apple_sleep_wake_admitted(const struct apple_sleep_soc *soc, const u32 *enabled, + int count) +{ + unsigned int i; + int j; + + for (i = 0; i < soc->nwake_required; i++) { + for (j = 0; j < count; j++) + if (enabled[j] == soc->wake_required[i]) + break; + if (j >= count) + return false; + } + + return true; +} + /* The last checks, then the stray words lowered: what has stopped may not return until a wake. */ static int apple_sleep_refuse(struct apple_sleep *s) { @@ -3252,6 +3589,15 @@ static int apple_sleep_refuse(struct apple_sleep *s) dev_err(s->dev, "refused: no wake source enabled in the device tree\n"); refused = true; } + if (!apple_sleep_wake_admitted(s->soc, s->wake_enable, s->wake_enable_count)) { + dev_err(s->dev, "refused: the device tree doesn't enable the timed wake's source\n"); + refused = true; + } + /* A required source can be neither armed nor read back without its block. */ + if (s->soc->nwake_required && !s->wake) { + dev_err(s->dev, "refused: the wake block isn't mapped\n"); + refused = true; + } sleep_note(s, 0x21); /* Its first config access after the power loss would hang on the untrained link. */ @@ -3275,7 +3621,8 @@ static int apple_sleep_refuse(struct apple_sleep *s) } /* Only ANS's driver can stop it, and it doesn't come back without a real sleep. */ - if (!idled && (sleep_ps_on(s, d->ans) || sleep_ps_on(s, d->apcie_sys_gp))) { + if (!idled && ((d->ans && sleep_ps_on(s, d->ans)) || + (d->apcie_sys_gp && sleep_ps_on(s, d->apcie_sys_gp)))) { dev_err(s->dev, "refused: ANS or PCIe is on with no driver to stop it\n"); refused = true; } @@ -3305,6 +3652,11 @@ static int apple_sleep_refuse(struct apple_sleep *s) } if (s->display[i].bound && sleep_asc_running(s, ps, s->display[i].asc) && (!apple_sleep_v27_late() || sleep_v27_final_check(i))) { + /* Only a sleep that commits has its driver stop it: there is no restart. */ + if (i == 0 && s->soc->display_no_restart && apple_sleep_dry(s)) { + dev_info(s->dev, "dry run: the display coprocessor is left running; a sleep that commits stops it cold, until a reboot\n"); + continue; + } dev_err(s->dev, "refused: a bound display coprocessor is still running\n"); refused = true; } @@ -3319,7 +3671,7 @@ static int apple_sleep_refuse(struct apple_sleep *s) sleep_note(s, 0x28); /* A dry run, which stops right after this, writes no power word (as in b27). */ - return apple_sleep_lower_stray(s, s->soc->untested && !READ_ONCE(sleep_untested_commit)); + return apple_sleep_lower_stray(s, apple_sleep_dry(s)); } static void sleep_wake_arm(struct apple_sleep *s) @@ -3604,7 +3956,8 @@ static int sleep_hpm_sleep(struct apple_sleep *s) */ static int sleep_hpm_wait_contract(struct apple_sleep *s, int *gone_ms) { - ktime_t start = ktime_get(); + /* The raw counter: the late cut runs with timekeeping suspended. */ + u64 start = read_sysreg(cntvct_el0), hz = arch_timer_get_cntfrq(); bool wake = true, up; u32 val = 0; int ms, ret; @@ -3617,7 +3970,7 @@ static int sleep_hpm_wait_contract(struct apple_sleep *s, int *gone_ms) *gone_ms = -1; mdelay(HPM_RESET_FIRST_MS); for (;;) { - ms = ktime_ms_delta(ktime_get(), start); + ms = div64_u64((read_sysreg(cntvct_el0) - start) * 1000, hz); if (ms >= HPM_CONTRACT_MS) return -ETIMEDOUT; ret = wake ? sleep_hpm_cmd(s, SPMI_OP_WAKEUP, 0, NULL, NULL) : 0; @@ -3639,7 +3992,7 @@ static int sleep_hpm_wait_contract(struct apple_sleep *s, int *gone_ms) /* A live debug link holds the debug switch domain on. */ static bool sleep_debug_link_up(struct apple_sleep *s) { - return s->hpm_spmi && + return s->hpm_spmi && s->ps_aon && FIELD_GET(PS_ACTUAL, readl(s->ps_aon + s->soc->ps_aon_debug_switch)); } @@ -3663,7 +4016,9 @@ static bool apple_sleep_usb_down(struct apple_sleep *s) if (!sleep_debug_link_up(s)) return false; - dev_info(s->dev, "debug link: cutting it for the sleep\n"); + /* The late cut prints nothing after it: the console is the link. */ + dev_info(s->dev, "debug link: cutting it for the sleep%s\n", + s->soc->debug_cut_after_stops ? ", after the coprocessor stops" : ""); enable = readl(s->hpm_spmi + SPMI_NOTIFY_ENABLE); writel(enable & ~SPMI_NOTIFY_REPLY, s->hpm_spmi + SPMI_NOTIFY_ENABLE); /* A reset that the partner doesn't come back from is done again. */ @@ -3678,11 +4033,13 @@ static bool apple_sleep_usb_down(struct apple_sleep *s) WRITE_ONCE(sleep_debug_link_cut, true); ms = sleep_hpm_wait_contract(s, &gone); if (ms >= 0) { - dev_info(s->dev, "debug link: contract back %d ms after reset %d (gone at %d ms)\n", - ms, i, gone); + if (!s->soc->debug_cut_after_stops) + dev_info(s->dev, "debug link: contract back %d ms after reset %d (gone at %d ms)\n", + ms, i, gone); break; } - dev_warn(s->dev, "debug link: no contract with the partner after reset %d\n", i); + if (!s->soc->debug_cut_after_stops) + dev_warn(s->dev, "debug link: no contract with the partner after reset %d\n", i); } if (!ret) ret = sleep_hpm_sleep(s); @@ -3695,7 +4052,12 @@ static bool apple_sleep_usb_down(struct apple_sleep *s) bool apple_sleep_debug_link_cut(void) { - return apple_sleep ? apple_sleep_usb_down(apple_sleep) : false; + struct apple_sleep *s = apple_sleep; + + /* The entry cuts it itself, after its stops. */ + if (!s || s->soc->debug_cut_after_stops) + return false; + return apple_sleep_usb_down(s); } EXPORT_SYMBOL_GPL(apple_sleep_debug_link_cut); @@ -3703,7 +4065,7 @@ bool apple_sleep_debug_link_up(void) { struct apple_sleep *s = apple_sleep; - return s && !s->usb_down_ran && sleep_debug_link_up(s); + return s && !s->soc->debug_cut_after_stops && !s->usb_down_ran && sleep_debug_link_up(s); } EXPORT_SYMBOL_GPL(apple_sleep_debug_link_up); @@ -3790,10 +4152,9 @@ EXPORT_SYMBOL_GPL(apple_sleep_debug_link_cut_wake); * the link untouched. A link that's down or a radio that's gone only makes the poll time * out, and the power goes next either way. */ -static void sleep_apcie_port_stop(struct apple_sleep *s) +static void sleep_apcie_port_stop(struct apple_sleep *s, void __iomem *port, + void __iomem *phy, int perst, bool perst_low, bool radio) { - void __iomem *port = s->apcie_port; - void __iomem *phy = s->apcie_port_phy; u32 val; writel(readl(port + APCIE_PORT_INTMSK) | APCIE_PORT_INT_LINK, port + APCIE_PORT_INTMSK); @@ -3806,16 +4167,16 @@ static void sleep_apcie_port_stop(struct apple_sleep *s) readl_poll_timeout_atomic(port + APCIE_PORT_L2, val, !(val & APCIE_PORT_L2_BUSY), 10, APCIE_PORT_STOP_US); } - /* The radio keeps its power and firmware, in reset until its host releases it. */ - if (s->radio_perst >= 0 && sleep_ps_on(s, s->soc->ps.gpio)) { - void __iomem *reg = s->pins + PIN_REG(s->radio_perst); + /* The endpoint keeps its power, in reset until its host releases it. */ + if (perst >= 0 && sleep_ps_on(s, s->soc->ps.gpio)) { + void __iomem *reg = s->pins + PIN_REG(perst); val = readl(reg); - writel(s->radio_perst_low ? val & ~PIN_DATA : val | PIN_DATA, reg); + writel(perst_low ? val & ~PIN_DATA : val | PIN_DATA, reg); } writel(readl(phy) & ~APCIE_PORT_PHY_LINK, phy); - if (s->apcie_engine && s->apcie_fabric) { + if (radio && s->apcie_engine && s->apcie_fabric) { writel(0, s->apcie_engine + APCIE_ENGINE_IRQ_MASK); writel(3, s->apcie_fabric + APCIE_FABRIC_STOP); writel(readl(s->apcie_engine + APCIE_ENGINE_CTRL) | APCIE_ENGINE_STOP, @@ -3839,14 +4200,37 @@ static void sleep_apcie_port_stop(struct apple_sleep *s) writel(readl(port + APCIE_PORT_INTSTAT), port + APCIE_PORT_INTSTAT); } +/* + * The endpoint on port 2, stopped as the radio's port is, so that the block's power doesn't go + * with its link up while the endpoint's own rail stays on. Its host trains it again after the + * wake. Only a host that describes and enables port 2 has it stopped. A port with its link down + * or never clocked is left as it is: the power going takes nothing from it. + */ +static void sleep_apcie_port2_stop_once(struct apple_sleep *s) +{ + void __iomem *port = s->apcie_port2; + + if (s->apcie_port2_stopped || !s->apcie_port2_enabled || !port || !s->apcie_port2_phy) + return; + s->apcie_port2_stopped = true; + if (!(readl(port + APCIE_PORT_APPCLK) & APCIE_PORT_APPCLK_EN) || + !(readl(port + APCIE_PORT_LINKSTS) & APCIE_PORT_LINKSTS_UP)) + return; + sleep_apcie_port_stop(s, port, s->apcie_port2_phy, s->port2_perst, s->port2_perst_low, + false); +} + static void sleep_apcie_port_stop_once(struct apple_sleep *s) { + if (!sleep_ps_on(s, s->soc->ps.apcie_gp) || !sleep_ps_on(s, s->soc->ps.apcie_phy_sw)) + return; + sleep_apcie_port2_stop_once(s); /* Only with the port set up, by the loader or by its host after a wake, or it aborts. */ - if (s->apcie_port_stopped || s->apcie_port_down || !s->apcie_port || !s->apcie_port_phy || - !sleep_ps_on(s, s->soc->ps.apcie_gp) || !sleep_ps_on(s, s->soc->ps.apcie_phy_sw)) + if (s->apcie_port_stopped || s->apcie_port_down || !s->apcie_port || !s->apcie_port_phy) return; s->apcie_port_stopped = true; - sleep_apcie_port_stop(s); + sleep_apcie_port_stop(s, s->apcie_port, s->apcie_port_phy, s->radio_perst, + s->radio_perst_low, true); } /* @@ -4481,6 +4865,13 @@ static void apple_sleep_lower_io(struct apple_sleep *s) static void apple_sleep_set_wd2(struct apple_sleep *s, unsigned int secs) { + if (s->soc->wdt_wd1) { + writel(0, s->wdt + WDT_WD1_CTL); + writel(0, s->wdt + WDT_WD1_COUNT); + writel(secs * WDT_TICKS_PER_S, s->wdt + WDT_WD1_BITE); + writel(WDT_WD1_RESET_EN, s->wdt + WDT_WD1_CTL); + return; + } writel(0, s->wdt + WDT_WD2_CTL); writel(0, s->wdt + WDT_WD2_COUNT); writel(secs * WDT_TICKS_PER_S, s->wdt + WDT_WD2_ALARM); @@ -4842,7 +5233,8 @@ static void sleep_spmi_sources_report(struct apple_sleep *s) static bool sleep_notes_on(struct apple_sleep *s) { - return s && s->spmi && s->soc->untested && READ_ONCE(sleep_pmu_notes); + return s && s->spmi && s->soc->untested && !s->soc->no_pmu_notes && + READ_ONCE(sleep_pmu_notes); } /* @@ -5413,8 +5805,8 @@ static int apple_sleep_commit(unsigned long unused) early = s->soc->early_cpu_wfi && READ_ONCE(sleep_early_wfi); if (early) { /* Released before the stop: each core goes from its stop bit to its deep WFI. */ - spin_table_pen_deep_el1(s->soc->ops->deep_wfi_arm == t8142_deep_wfi_arm && - is_kernel_in_hyp_mode() && READ_ONCE(sleep_el1_wfi) >= 2); + spin_table_pen_deep_el1(s->soc->pen_deep && is_kernel_in_hyp_mode() && + (s->soc->el1_wfi || READ_ONCE(sleep_el1_wfi) >= 2)); spin_table_release_stopped(); } s->cpus_stop_ret = spin_table_stop_parked(); @@ -5456,8 +5848,8 @@ static int apple_sleep_commit(unsigned long unused) /* Each core's deep WFI comes after the commit, this one last. No SPMI from here on. */ if (!early) { - spin_table_pen_deep_el1(s->soc->ops->deep_wfi_arm == t8142_deep_wfi_arm && - is_kernel_in_hyp_mode() && READ_ONCE(sleep_el1_wfi) >= 2); + spin_table_pen_deep_el1(s->soc->pen_deep && is_kernel_in_hyp_mode() && + (s->soc->el1_wfi || READ_ONCE(sleep_el1_wfi) >= 2)); spin_table_release_stopped(); } if (s->soc->boot_wfi_delay_ms) @@ -5932,6 +6324,31 @@ static void apple_sleep_display_then_gpu(struct apple_sleep *s) apple_sleep_coprocs_stop(s, true); } +/* + * An untested SoC with early_context stops here unless asked, as the common entry does: the + * refusals have run and passed, no stray word was lowered, and no core is held, no display + * word lowered, no SMC notice sent from here and nothing stopped. What is left that can refuse + * without changing anything runs too, so the dry run reports it: each coprocessor's own last + * check and the SoC's final check. + */ +static int apple_sleep_enter_dry(struct apple_sleep *s) +{ + int ret = apple_sleep_coprocs_check(s); + + if (!ret && s->soc->ops->final_check) + ret = s->soc->ops->final_check(s); + if (!ret && pm_wakeup_pending()) + ret = -EBUSY; + apple_sleep_stray_restore(s); + if (ret) { + dev_info(s->dev, "dry run: refused at the last checks: %d\n", ret); + return ret; + } + dev_info(s->dev, + "dry run: every check passed; refusing before the first stop and the commit (untested SoC, apple_sleep.untested_commit=1 lets it through)\n"); + return -EAGAIN; +} + /* * The entry of a SoC with early_context, called with the boot core's context saved. All * returning checks precede enclave/final-stop. @@ -5952,6 +6369,8 @@ static int apple_sleep_enter_prepare(struct apple_sleep *s) ret = apple_sleep_refuse(s); if (ret) return ret; + if (apple_sleep_dry(s)) + return apple_sleep_enter_dry(s); ret = apple_sleep_cpus_hold(s); if (!ret) { step = "display prepare"; @@ -5968,7 +6387,13 @@ static int apple_sleep_enter_prepare(struct apple_sleep *s) step = "coprocessor checks"; ret = apple_sleep_coprocs_check(s); } - if (!ret && !s->soc->ops->commit_notice) { + if (!ret && !s->soc->ops->commit_notice && apple_sleep_smc_defer_notice()) { + /* The notice comes after SEP's stop, where it can't refuse: its lane is held. */ + step = "SMC scope"; + if (!s->smc.dev || !s->smc.late_notice || !s->smc.saved_ops || !s->smc.held) + ret = -EBUSY; + } + if (!ret && !s->soc->ops->commit_notice && !apple_sleep_smc_defer_notice()) { step = "SMC notice"; ret = apple_sleep_smc_late_notice(s); } @@ -6014,6 +6439,11 @@ static int apple_sleep_enter_prepare(struct apple_sleep *s) ret = s->soc->ops->commit_notice(s); if (ret) panic("Apple committed SMC notice failed after peer stop: %d", ret); + } else if (apple_sleep_smc_defer_notice()) { + /* Gen 1: the SMC hears last, after SEP and the other coprocessors stopped. */ + ret = apple_sleep_smc_late_notice(s); + if (ret) + panic("Apple SMC sleep notice failed after peer stop: %d", ret); } if (!s->soc->regions) apple_sleep_usb_down(s); @@ -6027,14 +6457,21 @@ static int apple_sleep_enter_prepare(struct apple_sleep *s) static int apple_sleep_enter_saved(unsigned long unused) { struct apple_sleep *s = apple_sleep; - int ret = s->soc->ops->cpu_prepare(s->mbox->boot_mpidr); + int ret; + /* + * cpu_suspend() calls its finisher with RCU not watching. Up to the commit this one + * takes locks, logs and looks at work items: RCU watches until then. + */ + ct_cpuidle_exit(); + ret = s->soc->ops->cpu_prepare(s->mbox->boot_mpidr); + if (!ret) + ret = apple_sleep_enter_prepare(s); + if (!ret) + pm_set_resume_via_firmware(); + ct_cpuidle_enter(); if (ret) return ret; - ret = apple_sleep_enter_prepare(s); - if (ret) - return ret; - pm_set_resume_via_firmware(); /* cpu_suspend has already saved boot context. Commit never returns. */ return apple_sleep_commit(0); } @@ -6445,11 +6882,15 @@ static int apple_sleep_begin(suspend_state_t state) /* The PM core also calls .begin for s2idle when no s2idle ops are installed. */ if (state != PM_SUSPEND_MEM) return 0; + /* Before the PM core takes the other CPUs down: the wake's burst starts only these. */ + cpumask_copy(&sleep_cpus_awake, cpu_online_mask); ret = apple_sleep_profile_check(apple_sleep); if (ret) return ret; + apple_sleep->dry_run = apple_sleep->soc->untested && !READ_ONCE(sleep_untested_commit); + if (apple_sleep->soc->ops->begin) { ret = apple_sleep->soc->ops->begin(apple_sleep); if (ret) @@ -6458,11 +6899,25 @@ static int apple_sleep_begin(suspend_state_t state) if (apple_sleep) { apple_sleep->apcie_port_stopped = false; + apple_sleep->apcie_port2_stopped = false; apple_sleep->usb_down_ran = false; apple_sleep->smc_woke_alone = false; sleep_pins_save(apple_sleep); } - apple_sleep_set_wd2(apple_sleep, WDT_SUSPEND_SECS); + /* Before apple_wdt's suspend stops it: what user space had, for .end */ + if (apple_sleep->soc->wdt_wd1 && !apple_sleep->wd1_saved) { + apple_sleep->wd1_saved_ctl = readl(apple_sleep->wdt + WDT_WD1_CTL); + apple_sleep->wd1_saved_bite = readl(apple_sleep->wdt + WDT_WD1_BITE); + apple_sleep->wd1_saved = true; + } + if (!apple_sleep->soc->no_wd2) { + unsigned long flags; + + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + apple_sleep_wd2_owned = true; + apple_sleep_set_wd2(apple_sleep, WDT_SUSPEND_SECS); + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); + } pm_set_suspend_via_firmware(); sleep_ans_late_open(); @@ -6479,8 +6934,23 @@ static void apple_sleep_end(void) /* Nothing left by now after a wake; the platform wake takes it */ if (pm_suspend_via_firmware() && apple_sleep->soc->ops->pmu_wake) apple_sleep->soc->ops->pmu_wake(apple_sleep); - if (pm_suspend_via_firmware()) - writel(0, apple_sleep->wdt + WDT_WD2_CTL); + if (pm_suspend_via_firmware() && apple_sleep->soc->wdt_wd1) { + unsigned long flags; + + /* After apple_wdt's resume: WD1 as user space had it before the sleep */ + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + if (apple_sleep->wd1_saved) { + writel(0, apple_sleep->wdt + WDT_WD1_CTL); + writel(0, apple_sleep->wdt + WDT_WD1_COUNT); + writel(apple_sleep->wd1_saved_bite, apple_sleep->wdt + WDT_WD1_BITE); + writel(apple_sleep->wd1_saved_ctl, apple_sleep->wdt + WDT_WD1_CTL); + apple_sleep->wd1_saved = false; + } + apple_sleep_wd2_owned = false; + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); + } else if (pm_suspend_via_firmware() && !apple_sleep->soc->no_wd2) { + apple_sleep_wdt_end(apple_sleep->wdt); + } } /* @@ -6778,6 +7248,12 @@ static int apple_sleep_prepare(void) /* Every device .suspend has run: no owner registers after this. */ sleep_ans_late_close(); + /* + * WD1 on its own (T8103): apple_wdt's .suspend stopped it, and nothing else would reset + * a hang between here and the commit, which arms it again. + */ + if (s && s->soc->wdt_wd1 && pm_suspend_via_firmware()) + apple_sleep_set_wd2(s, WDT_SUSPEND_SECS); sleep_note_at(s, 0, PMU_NOTE_MAGIC); sleep_note_at(s, 2, 0); sleep_note_at(s, 3, ++attempts); @@ -6890,9 +7366,6 @@ static void apple_sleep_report(void) s->soc->quiesce.offset[i]); if (s->cpus_stop_ret) dev_err(s->dev, "other CPUs did not stop: %d\n", s->cpus_stop_ret); - if (s->perf_soc_ret || s->perf_dcs_ret) - dev_warn(s->dev, "sleep perf states: SoC %d, DCS %d (DCS was %u)\n", s->perf_soc_ret, - s->perf_dcs_ret, s->perf_dcs_from); if (s->cluster_p_ret) dev_err(s->dev, "P complex did not come back on: %d\n", s->cluster_p_ret); if (s->radio_trainable && s->radio_stop_ret) @@ -6941,7 +7414,8 @@ static const struct platform_suspend_ops apple_sleep_ops = { /* For a SoC with early_context: the same, with the scopes its entry needs held */ static const struct platform_suspend_ops apple_sleep_early_ops = { - .valid = suspend_valid_only_mem, + /* An untested SoC's deep sleep is offered only with apple_sleep.deep=1. */ + .valid = apple_sleep_valid, .begin = apple_sleep_begin, .prepare = apple_sleep_prepare, .prepare_late = apple_sleep_late_scope_begin, @@ -6997,6 +7471,11 @@ static int apple_sleep_map_displays(struct apple_sleep *s) return 0; } +static void apple_sleep_iounmap(void *base) +{ + iounmap((void __iomem __force *)base); +} + static void __iomem *apple_sleep_map(struct device *dev, const char *name) { struct device_node *np = dev->of_node; @@ -7010,7 +7489,17 @@ static void __iomem *apple_sleep_map(struct device *dev, const char *name) if (of_address_to_resource(np, index, &res)) return IOMEM_ERR_PTR(-EINVAL); - /* Shared with the drivers of these blocks, so not claimed. */ + /* + * Shared with the drivers of these blocks, so not claimed. Non-posted where the bus says + * so: on T8103 a posted write to these blocks is an SError. + */ + if (res.flags & IORESOURCE_MEM_NONPOSTED) { + base = ioremap_np(res.start, resource_size(&res)); + if (!base || + devm_add_action_or_reset(dev, apple_sleep_iounmap, (void __force *)base)) + return IOMEM_ERR_PTR(-ENOMEM); + return base; + } base = devm_ioremap(dev, res.start, resource_size(&res)); if (!base) return IOMEM_ERR_PTR(-ENOMEM); @@ -7235,6 +7724,22 @@ static void __iomem *apple_sleep_apcie_block(struct apple_sleep *s, struct devic return of_iomap(np, idx); } +/* Whether the PCIe host @np describes and enables a port at device @slot (a pci@slot,0 child). */ +static bool apple_sleep_apcie_has_port(struct device_node *np, unsigned int slot) +{ + struct device_node *port; + int devfn; + + for_each_available_child_of_node(np, port) { + devfn = of_pci_get_devfn(port); + if (devfn >= 0 && PCI_SLOT(devfn) == slot) { + of_node_put(port); + return true; + } + } + return false; +} + /* * Its registers go with PCIe's node, which a test tree may have disabled, and a loader * publishes the tunables there. Missing ones only refuse a real sleep with ANS stopped. @@ -7284,6 +7789,7 @@ static void apple_sleep_map_apcie(struct apple_sleep *s) s->apcie_port2 = apple_sleep_apcie_block(s, np, "port2", NULL, NULL); s->apcie_port2_phy = apple_sleep_apcie_block(s, np, "phy2", NULL, NULL); s->apcie_ports_unowned = !of_property_present(np, "apple,managed-sids"); + s->apcie_port2_enabled = of_device_is_available(np) && apple_sleep_apcie_has_port(np, 2); engine = of_parse_phandle(np, "apple,piodma", 0); if (engine) { s->apcie_engine = apple_sleep_apcie_block(s, engine, "engine", NULL, NULL); @@ -7293,11 +7799,18 @@ static void apple_sleep_map_apcie(struct apple_sleep *s) of_node_put(np); } -/* The radio port's PERST# on the AP pins @np, from the ports of the SoC's enabled PCIe host. */ +/* + * The radio port's PERST# on the AP pins @np, from the radio's own port node (device 0) of the + * SoC's enabled PCIe host, and the one of the endpoint on port 2 from that port's node. A port + * without the line (released by the port's own PERST register) has none, whatever its sibling + * ports carry. + */ static void apple_sleep_find_radio_perst(struct apple_sleep *s, struct device_node *np) { struct device_node *host, *port; struct of_phandle_args args; + bool usable; + int devfn; host = of_parse_phandle(s->dev->of_node, "apple,apcie", 0); if (!host) @@ -7307,10 +7820,15 @@ static void apple_sleep_find_radio_perst(struct apple_sleep *s, struct device_no if (of_parse_phandle_with_args(port, "reset-gpios", "#gpio-cells", 0, &args)) continue; - if (args.np == np && args.args_count >= 2 && args.args[0] < s->npins && - !test_bit(args.args[0], s->pins_skip)) { + devfn = of_pci_get_devfn(port); + usable = args.np == np && args.args_count >= 2 && args.args[0] < s->npins && + !test_bit(args.args[0], s->pins_skip) && devfn >= 0; + if (usable && PCI_SLOT(devfn) == 0) { s->radio_perst = args.args[0]; s->radio_perst_low = args.args[1] & GPIO_ACTIVE_LOW; + } else if (usable && PCI_SLOT(devfn) == 2) { + s->port2_perst = args.args[0]; + s->port2_perst_low = args.args[1] & GPIO_ACTIVE_LOW; } of_node_put(args.np); } @@ -7326,6 +7844,7 @@ static void apple_sleep_map_pins(struct apple_sleep *s) int i, n; s->radio_perst = -1; + s->port2_perst = -1; if (!np) return; if (!of_device_is_available(np) || of_property_read_u32(np, "apple,npins", &npins) || @@ -7892,6 +8411,9 @@ static int apple_sleep_probe(struct platform_device *pdev) return dev_err_probe(dev, ret, "cannot control CPU power\n"); if (s->soc->pen_deep) spin_table_pen_deep_arm(true); + if (s->soc->el1_wfi) + dcache_clean_poc((unsigned long)t8142_el1_wfi_stub, + (unsigned long)t8142_el1_wfi_stub_end); /* Last: the exported helpers take it as a probed driver, and a failure frees s. */ apple_sleep = s; @@ -7912,13 +8434,15 @@ static int apple_sleep_probe(struct platform_device *pdev) READ_ONCE(sleep_el1_wfi) >= 2 ? "EL1 on every core" : "EL1 on the boot core", &(phys_addr_t){ __pa_symbol(t8142_el1_wfi_stub) }); } - dev_info(dev, "probe: pwrgate wake %#x %#x cpm %#x %#x, commit %#x, clusters %#x %#x\n", - readl(s->pwrgate + s->soc->pwrgate_wake[0]), - readl(s->pwrgate + s->soc->pwrgate_wake[1]), - readl(s->pwrgate + s->soc->pwrgate_cpm[0]), - readl(s->pwrgate + s->soc->pwrgate_cpm[1]), readl(s->commit), - readl(s->cluster + s->soc->cluster_cpu[0]), - readl(s->cluster + s->soc->cluster_cpu[1])); + /* The common layout's words: a SoC with its own map names none of them. */ + if (!s->soc->ops->map_regs && s->pwrgate) + dev_info(dev, "probe: pwrgate wake %#x %#x cpm %#x %#x, commit %#x, clusters %#x %#x\n", + readl(s->pwrgate + s->soc->pwrgate_wake[0]), + readl(s->pwrgate + s->soc->pwrgate_wake[1]), + readl(s->pwrgate + s->soc->pwrgate_cpm[0]), + readl(s->pwrgate + s->soc->pwrgate_cpm[1]), readl(s->commit), + readl(s->cluster + s->soc->cluster_cpu[0]), + readl(s->cluster + s->soc->cluster_cpu[1])); dev_warn(dev, "sleep data derived for this SoC, untested: deep sleep is %s, and %s\n", READ_ONCE(sleep_deep) ? "offered (apple_sleep.deep=1)" : "off (apple_sleep.deep=1 offers it)", READ_ONCE(sleep_untested_commit) ? "the commit is allowed" : @@ -8374,15 +8898,6 @@ static const struct apple_sleep_soc t8132_sleep_soc = { */ #define T8142_PMC_VOTER_AP (3 * PMC_VOTER_STRIDE) #define T8142_CLUSTER_BUSY BIT(4) -/* - * AppleT8142PMGR::setPerfState's words in PMGRCLKGEN_SOC_TOP (/arm-io/pmgr reg[2]): the SoC's - * at 0x24000, DCS's at 0x25000, each like T8132's: [3:0] asks, [11:8] has reached, bit 31 busy. - */ -#define T8142_PERF_REQ GENMASK(3, 0) -#define T8142_DCS_SLEEP_STATE 3 -#define T8142_DCS_STEP_STATE 5 -#define T8142_DCS_STEP_FROM 6 -#define T8142_DCS_MAX_STATE 10 /* * Every Linux access to the complexes' ACC word 0xe440f8 has hung J815 so far: a read at @@ -8395,32 +8910,6 @@ module_param_named(acc_wake, sleep_acc_wake, bool, 0644); MODULE_PARM_DESC(acc_wake, "T8142: write ACC 0xe440f8 = 1 per complex at a wake, as restoreHW does (default 0)"); -static int t8142_perf_request(void __iomem *reg, unsigned int state) -{ - writel((readl(reg) & ~T8142_PERF_REQ) | FIELD_PREP(T8142_PERF_REQ, state), reg); - return sleep_perf_wait(reg, state); -} - -/* - * AppleT8142PMGR::quiescePerfState, the PMGR's first sleep step: the SoC to Vmin (3), then DCS - * to 3, through 5 from 6..10. macOS waits on BUSY with no limit and panics on a DCS state - * above 10; here each wait is bounded, and such a state is left alone. - */ -static void t8142_perf_down(struct apple_sleep *s) -{ - unsigned int state = FIELD_GET(DCS_STATE, readl(s->dcs)); - - s->perf_dcs_from = state; - s->perf_soc_ret = t8142_perf_request(s->clk_perf + CLK_PERF_SOC, SOC_SLEEP_STATE); - if (state > T8142_DCS_MAX_STATE) { - s->perf_dcs_ret = -ERANGE; - return; - } - if (state >= T8142_DCS_STEP_FROM) - t8142_perf_request(s->dcs, T8142_DCS_STEP_STATE); - s->perf_dcs_ret = t8142_perf_request(s->dcs, T8142_DCS_SLEEP_STATE); -} - /* AppleT8142PMGR vtable 0xfa0: each complex's CPM gate word, read-modify-write. */ static void t8142_cpm_on(struct apple_sleep *s) { @@ -8523,16 +9012,18 @@ static void t8142_lower_io(struct apple_sleep *s) * read RTC_CTL, 0x43 if it had fired, the 4-byte compare at 0x2008, 0x200e <- 0, RTC_CTL <- * 0x41. T6050's post-timer step at the same addresses (apple,pmu-alarm-rearm 0x43 0x41). The * opcode carries the byte count (his follow-up fix). The compare and the counter are read here, - * before the cores' window, with the notes; the compare is now + apple_sleep.t8142_wake_s - * (0 keeps the PMU's own), which is also a wake source: J815 has no RTC device under Linux. + * before the cores' window, with the notes. The compare stays the PMU's own unless + * apple_sleep.t8142_wake_s asks for a timed wake that many seconds after the commit (a test + * knob: J815 has no RTC device under Linux, so nothing else arms one). By default a sleep + * lasts until a key, the trackpad, the lid or the power button wakes it. * J813 still resets with it (PMU took all four commands), so this is parity, not the fix. */ static bool sleep_pmu_alarm = true; module_param_named(pmu_alarm, sleep_pmu_alarm, bool, 0644); MODULE_PARM_DESC(pmu_alarm, "T8142: send the PMU's RTC alarm after the S2R timer, as macOS does (default Y)"); -static unsigned int t8142_wake_s = 30; +static unsigned int t8142_wake_s; module_param(t8142_wake_s, uint, 0644); -MODULE_PARM_DESC(t8142_wake_s, "T8142: the PMU RTC alarm this many s after the commit (0: keep the PMU's)"); +MODULE_PARM_DESC(t8142_wake_s, "T8142 test: wake this many s after the commit (default 0: no timed wake, the PMU's compare stays)"); static u8 t8142_alarm[4]; static bool t8142_alarm_ok; static int t8142_post_ret = -ENODATA; @@ -8725,10 +9216,7 @@ static void t8142_commit_note(struct apple_sleep *s) return; if (s->cpus_stop_ret) flags |= 0x01; - if (s->perf_soc_ret) - flags |= 0x02; - if (s->perf_dcs_ret) - flags |= 0x04; + /* 0x02 and 0x04 were the SoC and DCS perf-state steps, which are gone. */ for (i = 0; i < s->soc->wake_words; i++) { u32 pend = readl(s->wake + s->soc->wake_status + i * 4) & s->wake_armed[i]; @@ -9071,9 +9559,7 @@ static void t8142_last_mile(struct apple_sleep *s) const struct apple_sleep_soc *soc = s->soc; int i; - /* Not in macOS's J813 entry (its perf-state page is untouched in the whole trace): A/B. */ - if (READ_ONCE(sleep_perf_down)) - t8142_perf_down(s); + /* The SoC and DCS perf states stay: macOS's J813 entry never writes them. */ sleep_note(s, 0x64); /* T6050's commit window: the floor's voter to 0, not read, right before the memory stop */ @@ -9092,8 +9578,11 @@ static void t8142_last_mile(struct apple_sleep *s) t8142_commit_note(s); - for (i = 0; i < soc->ncluster_cpu; i++) - writel(0, s->cluster + soc->cluster_cpu[i]); + for (i = 0; i < soc->ncluster_cpu; i++) { + void __iomem *reg = s->cluster + soc->cluster_cpu[i]; + + writel(readl(reg) & ~CLUSTER_ON, reg); + } s->quiesce_still_on = 0; for (i = 0; i < soc->quiesce.count; i++) @@ -9215,6 +9704,35 @@ static int t8142_cluster_on(struct apple_sleep *s, u32 word, void __iomem *acc) return ret; } +/* The other cores started at once, three words each (see sleep_cpus_burst). */ +static void t8142_cpu_burst(struct apple_sleep *s) +{ + unsigned int cpu, n = 0, self = smp_processor_id(); + + cpumask_clear(&sleep_cpus_burst); + s->cpu_burst_n = 0; + /* T8142's data states no cpu_clusters (0): E = MPIDR cluster 0, P = 1, from the MPIDR. */ + if (!s->cpu_start) + return; + for_each_cpu(cpu, &sleep_cpus_awake) { + u64 mpidr = cpu_logical_map(cpu); + unsigned int cluster = sleep_cpu_cluster(s, mpidr), core = sleep_cpu_core(mpidr); + + if (cpu == self || cluster > 1) + continue; + writel(sleep_cpu_start_bit(s, mpidr), s->cpu_start + CPU_START_SYS); + writel(cluster == 0 ? BIT(core) : 0, s->cpu_start + CPU_START_CLUSTER(0)); + writel(cluster == 1 ? BIT(core) : 0, s->cpu_start + CPU_START_CLUSTER(1)); + cpumask_set_cpu(cpu, &sleep_cpus_burst); + n++; + } + s->cpu_burst_n = n; + pr_info("apple-sleep: wake: %u cores started in one burst; stop/sys/e/p now %x/%x/%x/%x\n", + n, readl(s->cpu_start + CPU_START_STOP), readl(s->cpu_start + CPU_START_SYS), + readl(s->cpu_start + CPU_START_CLUSTER(0)), + readl(s->cpu_start + CPU_START_CLUSTER(1))); +} + /* * AppleT8142PMGR::restoreHW: each complex on, pwrgate +0x0 and +0x60 read-modify-written, the * words back, the CPM gates, the ACC words once more. Its two "early wake hacks" (SEP's ps @@ -9275,6 +9793,7 @@ static void t8142_wake(struct apple_sleep *s) s->aon_wdt_marked = false; } apple_sleep_set_wd2(s, WDT_SUSPEND_SECS); + t8142_cpu_burst(s); if (s->pcie_ans_stopped) s->pcie_ans_on_ret = apple_sleep_raise_apcie(s); @@ -9622,10 +10141,13 @@ static const struct apple_sleep_soc t8142_sleep_soc = { .wake_last_word = GENMASK(11, 0), }; +#include "sleep-t8103.h" +#include "sleep-t8122.h" + /* * Qualified profiles expose system sleep. Inventory-only profiles match for a * precise refusal and cannot reach hardware preparation or suspend_set_ops(). - * T8142 remains opt-in and requires its separate physical-commit gate. + * T8142 and T8122 remain opt-in and require their separate physical-commit gate. */ static const struct of_device_id apple_sleep_of_match[] = { { .compatible = "apple,t8140-sleep", .data = &t8140_sleep_soc }, @@ -9633,6 +10155,8 @@ static const struct of_device_id apple_sleep_of_match[] = { { .compatible = "apple,t8142-sleep", .data = &t8142_sleep_soc }, { .compatible = "apple,t6050-sleep", .data = &t6050_sleep_soc }, { .compatible = "apple,t6050-j716c-sleep", .data = &t6050_j716c_sleep_soc }, + { .compatible = "apple,t8103-sleep", .data = &t8103_sleep_soc }, + { .compatible = "apple,t8122-sleep", .data = &t8122_sleep_soc }, { } }; diff --git a/drivers/soc/apple/store_shim.c b/drivers/soc/apple/store_shim.c index c1773fa2b64124..42d6ea2e6c5233 100644 --- a/drivers/soc/apple/store_shim.c +++ b/drivers/soc/apple/store_shim.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -112,6 +113,47 @@ void *sep_store_open_block(const char *path, int writable) return f; } +/* The platform driver of the SoC's embedded (ANS) NVMe controller. */ +#define SEP_STORE_ANS_DRIVER "nvme-apple" + +/* + * Whether @dev, a disk's device, sits below the embedded NVMe controller. The + * first platform-bus ancestor must be bound to the ANS driver: an NVMe + * namespace's parent is its controller, whose parent is the ANS platform + * device. A disk behind USB, PCIe/Thunderbolt or a loop device reaches a + * different platform device, or none, and is refused. + */ +static bool sep_store_dev_is_internal(const struct device *dev) +{ + for (dev = dev->parent; dev; dev = dev->parent) { + const struct device_driver *drv; + + if (!dev_is_platform(dev)) + continue; + drv = READ_ONCE(dev->driver); + return drv && !strcmp(drv->name, SEP_STORE_ANS_DRIVER); + } + return false; +} + +/* + * As sep_store_open_block(), for the enclave's own store: the path is only a + * name for the partition, so the device it resolves to must also be on the + * internal NVMe disk. + */ +void *sep_store_open_internal_block(const char *path, int writable) +{ + struct file *f = sep_store_open_block(path, writable); + + if (f && !sep_store_dev_is_internal(disk_to_dev(file_bdev(f)->bd_disk))) { + pr_warn_ratelimited("apple-sep: %s is not on the internal NVMe disk; not used\n", + path); + filp_close(f, NULL); + return NULL; + } + return f; +} + void sep_store_close(void *handle) { if (handle) @@ -180,3 +222,8 @@ int sep_store_sync_parent(void *handle) fput(dir); return ret; } + +/* Like the module's Rust tests, which need KUnit built in. */ +#if IS_ENABLED(CONFIG_APPLE_SEP_KUNIT_TEST) && IS_BUILTIN(CONFIG_KUNIT) +#include "store_shim_test.c" +#endif diff --git a/drivers/soc/apple/store_shim_test.c b/drivers/soc/apple/store_shim_test.c new file mode 100644 index 00000000000000..57b51c7c650c92 --- /dev/null +++ b/drivers/soc/apple/store_shim_test.c @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the check that the xART store's block device is on the + * internal NVMe disk. The device trees are built by hand and never registered. + */ + +#include + +static const struct device_driver sep_store_test_ans = { .name = "nvme-apple" }; +static const struct device_driver sep_store_test_usb = { .name = "xhci-hcd" }; +static const struct device_driver sep_store_test_pcie = { .name = "pcie-apple" }; + +/* + * disk -> controller -> @host, as for an NVMe namespace, plus two spare + * devices for the cases that insert a bridge or add a top level. Allocated, + * as struct device is too large for the stack. + */ +struct sep_store_test_chain { + struct device host, ctrl, disk, extra, top; +}; + +static struct sep_store_test_chain * +sep_store_test_chain(struct kunit *test, const struct device_driver *drv) +{ + struct sep_store_test_chain *c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, c); + c->host.bus = &platform_bus_type; + c->host.driver = (struct device_driver *)drv; + c->ctrl.parent = &c->host; + c->disk.parent = &c->ctrl; + return c; +} + +static void sep_store_accepts_the_embedded_nvme(struct kunit *test) +{ + struct sep_store_test_chain *c = sep_store_test_chain(test, &sep_store_test_ans); + + KUNIT_EXPECT_TRUE(test, sep_store_dev_is_internal(&c->disk)); +} + +static void sep_store_refuses_a_usb_disk(struct kunit *test) +{ + struct sep_store_test_chain *c = sep_store_test_chain(test, &sep_store_test_usb); + + /* disk -> SCSI host -> USB controller */ + c->extra.parent = &c->ctrl; + c->disk.parent = &c->extra; + KUNIT_EXPECT_FALSE(test, sep_store_dev_is_internal(&c->disk)); +} + +/* PCIe or Thunderbolt NVMe: the PCI function is not a platform device. */ +static void sep_store_refuses_a_pcie_nvme_disk(struct kunit *test) +{ + struct sep_store_test_chain *c = sep_store_test_chain(test, &sep_store_test_pcie); + + c->extra.parent = &c->host; + c->ctrl.parent = &c->extra; + KUNIT_EXPECT_FALSE(test, sep_store_dev_is_internal(&c->disk)); +} + +static void sep_store_refuses_an_unbound_controller(struct kunit *test) +{ + struct sep_store_test_chain *c = sep_store_test_chain(test, NULL); + + KUNIT_EXPECT_FALSE(test, sep_store_dev_is_internal(&c->disk)); +} + +/* A loop device, or any disk with no platform ancestor. */ +static void sep_store_refuses_a_disk_without_a_controller(struct kunit *test) +{ + struct sep_store_test_chain *c = sep_store_test_chain(test, NULL); + + c->ctrl.parent = NULL; + KUNIT_EXPECT_FALSE(test, sep_store_dev_is_internal(&c->disk)); + c->disk.parent = NULL; + KUNIT_EXPECT_FALSE(test, sep_store_dev_is_internal(&c->disk)); +} + +/* Only the nearest platform ancestor decides. */ +static void sep_store_checks_the_nearest_platform_device(struct kunit *test) +{ + struct sep_store_test_chain *c = sep_store_test_chain(test, &sep_store_test_usb); + + c->top.bus = &platform_bus_type; + c->top.driver = (struct device_driver *)&sep_store_test_ans; + c->host.parent = &c->top; + KUNIT_EXPECT_FALSE(test, sep_store_dev_is_internal(&c->disk)); +} + +static struct kunit_case sep_store_internal_cases[] = { + KUNIT_CASE(sep_store_accepts_the_embedded_nvme), + KUNIT_CASE(sep_store_refuses_a_usb_disk), + KUNIT_CASE(sep_store_refuses_a_pcie_nvme_disk), + KUNIT_CASE(sep_store_refuses_an_unbound_controller), + KUNIT_CASE(sep_store_refuses_a_disk_without_a_controller), + KUNIT_CASE(sep_store_checks_the_nearest_platform_device), + {} +}; + +static struct kunit_suite sep_store_internal_suite = { + .name = "apple_sep_store_internal", + .test_cases = sep_store_internal_cases, +}; + +kunit_test_suite(sep_store_internal_suite); diff --git a/drivers/soc/apple/t6041-gate-test.dtso b/drivers/soc/apple/t6041-gate-test.dtso index 094b4d10fecb8f..7c4a68d0a3aeb5 100644 --- a/drivers/soc/apple/t6041-gate-test.dtso +++ b/drivers/soc/apple/t6041-gate-test.dtso @@ -2,7 +2,8 @@ /* * Test device tree for the display gate KUnit test: the J616c's external * display chains at their real paths (t604x-extdisp.dtsi, - * t6041-j616c-hdmi.dtsi, t6041-j616c-usbc.dtsi, t6041-j616c-usbc-dcpext2.dtsi), + * t6041-j616c-hdmi.dtsi, t6041-j616c-usbc.dtsi, t6041-j616c-usbc-dcpext2.dtsi, + * t6041-j616c-usbc-dcpext3.dtsi), * disabled, and the display * subsystem with the internal display's DART. There is no PMP. The data and * heap regions of both processors are the boot loader's disabled @@ -63,6 +64,20 @@ compatible = "apple,asc-mem"; status = "disabled"; }; + + dcpext3_text: dcpext3-text { + compatible = "apple,asc-mem"; + }; + + dcpext3_data: dcpext3-data { + compatible = "apple,asc-mem"; + status = "disabled"; + }; + + dcpext3_heap: dcpext3-heap { + compatible = "apple,asc-mem"; + status = "disabled"; + }; }; power-management@502800000 { @@ -224,6 +239,45 @@ }; }; + dcpext3_dart: iommu@306340000 { + #iommu-cells = <1>; + status = "disabled"; + }; + + dispext3_dart: iommu@306300000 { + #iommu-cells = <1>; + status = "disabled"; + }; + + mailbox@306e08000 { + status = "disabled"; + }; + + dcp@306e00000 { + compatible = "apple,t6041-dcpext"; + iommus = <&dcpext3_dart 23>; + memory-region = <&dcpext3_data>, <&dcpext3_heap>, <&dcpext3_text>; + status = "disabled"; + + typec-routes { + route@0 { + status = "disabled"; + }; + + route@1 { + status = "disabled"; + }; + + route@2 { + status = "disabled"; + }; + }; + + piodma { + iommus = <&dispext3_dart 16>; + }; + }; + disp_dart: iommu@a00000000 { #iommu-cells = <1>; }; diff --git a/drivers/soc/apple/t6041-sleep.c b/drivers/soc/apple/t6041-sleep.c new file mode 100644 index 00000000000000..35259580fc6f08 --- /dev/null +++ b/drivers/soc/apple/t6041-sleep.c @@ -0,0 +1,2296 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Apple T6041 (M4 Max) system sleep, at EL2 with no monitor below. + * + * It runs macOS 26.6.2's last steps before the S2R commit, in macOS's order and + * with its values, as traced from macOS sleeping under aura's hypervisor, and + * commits; aura's S2R mailbox brings the boot core back to cpu_resume on the + * wake, and the driver restores what the sleep took. + * + * Needs the kernel at EL2 (CTXR window) and the "aurora,rvbar-spin-table" CPU + * enable method, so the other cores can leave the kernel. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SYS_APL_IPI_SR_EL1 sys_reg(3, 5, 15, 1, 1) +#define IPI_SR_PENDING BIT(0) +#define SYS_APL_SIQ_CFG_EL1 sys_reg(3, 4, 15, 10, 4) +#define SYS_APL_DEEP_SLEEP sys_reg(3, 5, 15, 6, 2) +#define DEEP_SLEEP_BITS (BIT(0) | BIT(63)) + +#define KA_WORDS 32 +#define KA_STRIDE 0x44 + +#define PS_AUTO_ENABLE BIT(28) +#define PS_AUTO_STATE GENMASK(27, 24) +#define PS_FLAGS GENMASK(9, 8) +#define PS_ACTUAL GENMASK(7, 4) +#define PS_TARGET GENMASK(3, 0) + +#define SPMI_STATUS 0x00 +#define SPMI_CMD 0x04 +#define SPMI_REPLY 0x08 +#define SPMI_RX_EMPTY BIT(24) +#define SPMI_TX_EMPTY BIT(8) +#define SPMI_IDLE (SPMI_RX_EMPTY | SPMI_TX_EMPTY) +#define SPMI_DRAIN_MAX 16 +#define SPMI_NOTIFY_MASK 0x40 +#define SPMI_IRQ_ACK 0x80 +#define PMU_SID 0xb + +#define PERF_BUSY BIT(31) +#define PERF_ACTUAL GENMASK(11, 8) + +#define AMCC_MAX_GROUPS 8 +#define AMCC_ERR_OFF 0x25000 +#define AMCC_PLANE_STRIDE 0x40000 +#define AMCC_MIN_SIZE 0x1c2848 + +#define DCS_CH_STRIDE 0x200000UL +#define DCS_CH_SIZE 0x40 + +#define PTD_SOC_DEV_REQ_READ 0x01e00 +#define PTD_SOC_DEV_REQ_WRITE 0x10f00 +#define PTD_CLUSTER_WRITE_0 0x10f80 +#define PTD_CLUSTER_WRITE_1 0x10f88 +#define PTD_CLUSTER_WRITE_2 0x10f90 +#define PTD_CLUSTER_WRITE_3 0x10fa0 +#define PTD_MIN_SIZE 0x10fa8 + +#define AOP_PS_WORDS 44 + +#define WAKE_WORDS 9 +#define WAKE_LAST_MASK 0x00003fffU +#define WAKE_MAX_ID (32 * (WAKE_WORDS - 1) + 14) +#define WAKE_SOURCES_MAX 64 + +#define AXI2AF_ATC_COUNT 4 +#define AXI2AF_DISP_FIRST 4 +#define AXI2AF_DISP_COUNT 5 +#define AXI2AF_REG_COUNT 10 +#define AXI2AF_COUNT 15 +#define AXI2AF_ANS 9 +#define AXI2AF_APCIE 14 + +#define T6041_CPU_COUNT 16 +#define T6041_CPM_COUNT 3 +#define T6041_COMMIT_SIO_COUNT 2 +#define T6041_COMMIT_PERIPH_COUNT 5 +#define T6041_FULL_DETECT_COUNT 2 +#define T6041_MAX_PMGR_BANKS 16 +#define T6041_PS_MAX_DEPTH 16 + +enum t6041_apcie_ps { + T6041_APCIE_ANS, + T6041_APCIE_GP, + T6041_APCIE_SYS_GP, + T6041_APCIE_ST0, + T6041_APCIE_SYS_ST0, + T6041_APCIE_ST1, + T6041_APCIE_SYS_ST1, + T6041_APCIE_PHY_SW, + T6041_APCIE_PS_COUNT, +}; + +/* aura's struct aura_s2r_mailbox (aura PR 117). */ +#define T6041_S2R_MAGIC 0x3152325341525541ULL /* "AURAS2R1" */ +struct t6041_s2r_mailbox { + u64 magic; + u64 boot_mpidr; + u64 resume_pa; + u64 resumes; +}; + +struct t6041_sleep { + struct device *dev; + struct t6041_s2r_mailbox *mbox; + /* PMGR power-state words resolved from DT phandles. */ + void __iomem **ps_off; + unsigned int n_off; + void __iomem **ps_atc_off; + unsigned int n_atc_off; + void __iomem **ps_auto; + unsigned long *ps_auto_mem; + unsigned int n_auto; + void __iomem **ps_auto_clkgate; + unsigned long *ps_auto_clkgate_mem; + unsigned int n_auto_clkgate; + void __iomem **ps_auto_active; + unsigned int n_auto_active; + void __iomem **ps_keep_on; + unsigned int n_keep_on; + void __iomem **ps_restore; + unsigned int n_restore; + void __iomem *ps_cpu[T6041_CPU_COUNT]; + void __iomem *ps_cpm[T6041_CPM_COUNT]; + void __iomem *ps_sep; + void __iomem *ps_spmi_a0; + void __iomem *ps_atc_common[AXI2AF_ATC_COUNT]; + void __iomem *ps_atc_fabric; + void __iomem *ps_atc_afi; + void __iomem *ps_apcie[T6041_APCIE_PS_COUNT]; + void __iomem *ps_commit_sio[T6041_COMMIT_SIO_COUNT]; + void __iomem *ps_commit_periph[T6041_COMMIT_PERIPH_COUNT]; + void __iomem *ps_axi2af[AXI2AF_COUNT]; + void __iomem *ps_full_detect[T6041_FULL_DETECT_COUNT]; + void __iomem *cluster; + void __iomem *pwrgate; + void __iomem *misc; + void __iomem *wdt; + void __iomem *aon; + void __iomem *commit; + void __iomem *clkgen; + void __iomem *spmi; + void __iomem *spmi_a0; + void __iomem *pmc; + void __iomem *ka[2]; /* keep-alive tables, 1 from iBoot, 0 at macOS's commit */ + unsigned int ngroups; /* AMCCs of four planes: 8 on full T6041, 6 on binned */ + void __iomem *dcs[4 * AMCC_MAX_GROUPS]; + void __iomem *amccb[AMCC_MAX_GROUPS]; + void __iomem *wake; /* SLP_DDR +0, wake masks +0x0c..+0x2c */ + void __iomem *perf; /* SoC perf +0, DCS perf +0x400 */ + void __iomem *axi2af[AXI2AF_COUNT]; + void __iomem *ptd; /* PTD read (+0x0) and write (+0x10000) pages */ + u32 wake_masks[WAKE_WORDS]; + int stop_ret; + int coproc_ret; + int apcie_ret; + unsigned int atc_late; + unsigned int off_late; + unsigned int dcs_late; + u32 cpu_off_late; + u32 cpm_off_late; + unsigned int spmi_late; + unsigned int ps_late; + unsigned int gp_late; + /* Saved as the commit starts, put back by t6041_sleep_return(). */ + u64 cntkctl; + u64 siq_cfg; + u32 *ps_pre; + u32 pre_perf[2]; + u32 pre_pmc[5]; + u32 pre_clk[4]; + u32 pre_mask[2]; + u32 pre_wake[WAKE_WORDS]; + u32 pre_votes[5]; + /* Each AMCC plane's cache ways (+0x2800) and status (+0x2804). */ + u32 pre_ways[4 * AMCC_MAX_GROUPS]; + u32 pre_cache[4 * AMCC_MAX_GROUPS]; + bool pre_a0; + /* GP PCIe ports 0/1: port block, PHY word, and saved state. */ + void __iomem *gp_port[2]; + void __iomem *gp_phy[2]; + u32 gp_phy_pre[2]; + u32 gp_app_pre[2]; + u32 gp_perst_pre[2]; + bool gp_saved; + /* ANS's storage PCIe block and bootloader-supplied tunables (apple,apcie). */ + void __iomem *ap_rc; + void __iomem *ap_phy; + void __iomem *ap_phy_ip; + void __iomem *ap_axi; + void __iomem *ap_cio3pll; + void __iomem *ap_clkgen; + struct apple_tunable *tun_axi2af; + struct apple_tunable *tun_cio3pll; + struct apple_tunable *tun_clkgen; + struct apple_tunable *tun_phy; + struct apple_tunable *tun_phy_ip_pll; + struct apple_tunable *tun_phy_ip_lanes; + bool apcie_ready; + bool ans_stopped; + /* The AOP island's 44 MiniPMGR power words (ps-aop). */ + void __iomem *aop_ps; + u32 aop_pre[AOP_PS_WORDS]; + /* AP GPIO block (apple,pinctrl), saved/restored across deep sleep. */ + void __iomem *gpio; + u32 npins; + u32 *gpio_pre; + unsigned long *gpio_skip; +}; + +static struct t6041_sleep *t6041_sleep; + +/* ADT cpu number: E 0-3, P0 4-9, P1 10-15. */ +static unsigned int t6041_cpu_id(u64 mpidr) +{ + unsigned int cl = MPIDR_AFFINITY_LEVEL(mpidr, 1); + unsigned int core = MPIDR_AFFINITY_LEVEL(mpidr, 0); + + return cl == 0 ? core : cl == 1 ? 4 + core : 10 + core; +} + +/* + * Pure counter + cpu_relax() busy-spin helpers for the sleep commit path. + * Never call udelay()/mdelay()/readl_poll_timeout_atomic() once CPU/CPM + * PS_TARGET = 0 or cluster power-down is armed: arm64's delay_loop uses + * WFIT/WFET, which lets the sleep hardware power-gate the boot core early. + */ +static void t6041_spin_us(u64 us) +{ + u64 t0 = arch_timer_read_counter(); + u64 ticks = DIV_ROUND_UP_ULL(us * arch_timer_get_cntfrq(), USEC_PER_SEC); + + while (arch_timer_read_counter() - t0 < ticks) + cpu_relax(); +} + +#define t6041_poll_until_us(addr, val, cond, timeout_us) ({ \ + u64 __t0 = arch_timer_read_counter(); \ + u64 __ticks = DIV_ROUND_UP_ULL((u64)(timeout_us) * \ + arch_timer_get_cntfrq(), USEC_PER_SEC); \ + bool __timed_out = false; \ + int __ret = 0; \ + \ + for (;;) { \ + (val) = readl(addr); \ + if (cond) \ + break; \ + if (__timed_out) { \ + __ret = -ETIMEDOUT; \ + break; \ + } \ + if (arch_timer_read_counter() - __t0 >= __ticks) \ + __timed_out = true; \ + else \ + cpu_relax(); \ + } \ + __ret; \ +}) + +/* + * A core's last WFI, as the Neo's and the Air's t8140_deep_wfi() and macOS's + * last-WFI routine with x0 = 1: timers masked, the deep-sleep bits (C6_2 bit 0 + * and 63) set, then WFI for good. (Not the runtime offline branch, which leaves + * C6_2 clear.) + */ +static void __noreturn t6041_offline_wfi(void) +{ + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntp_ctl_el0); + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntv_ctl_el0); + sysreg_clear_set_s(SYS_APL_DEEP_SLEEP, 0, DEEP_SLEEP_BITS); + isb(); + while (true) { + dsb(sy); + isb(); + wfi(); + aic_sleep_ack(); + write_sysreg_s(IPI_SR_PENDING, SYS_APL_IPI_SR_EL1); + } +} + +static void t6041_cpu_stop(u64 mpidr) +{ + writel(BIT(t6041_cpu_id(mpidr)), t6041_sleep->misc + 0x0); + dsb(sy); +} + +static int t6041_cpu_on(u64 mpidr) +{ + void __iomem *misc = t6041_sleep->misc; + unsigned int cl = MPIDR_AFFINITY_LEVEL(mpidr, 1); + + writel(BIT(t6041_cpu_id(mpidr)), misc + 0x4); + writel(BIT(MPIDR_AFFINITY_LEVEL(mpidr, 0)), misc + 0x8 + 4 * cl); + return 0; +} + +static void t6041_ps_lower(void __iomem *reg) +{ + u32 val = readl(reg); + + if (val & PS_AUTO_ENABLE) { + val &= ~(PS_AUTO_ENABLE | PS_FLAGS); + writel(val, reg); + } + writel((val & ~PS_TARGET) | PS_FLAGS, reg); +} + +/* One byte to a PMU register over nub-spmi0: command, then data. */ +static void t6041_pmu_write(struct t6041_sleep *s, u16 reg, u8 val) +{ + unsigned int i; + u32 status; + + /* Drain any stale reply before issuing our command. */ + for (i = 0; i < SPMI_DRAIN_MAX && !(readl(s->spmi + SPMI_STATUS) & SPMI_RX_EMPTY); i++) + readl(s->spmi + SPMI_REPLY); + writel((u32)reg << 16 | BIT(15) | PMU_SID << 8 | 0x30, s->spmi + SPMI_CMD); + writel(val, s->spmi + SPMI_CMD); + if (t6041_poll_until_us(s->spmi + SPMI_STATUS, status, + !(status & SPMI_RX_EMPTY), 1000)) + s->spmi_late++; + for (i = 0; i < SPMI_DRAIN_MAX && !(readl(s->spmi + SPMI_STATUS) & SPMI_RX_EMPTY); i++) + readl(s->spmi + SPMI_REPLY); + writel(1, s->spmi + SPMI_IRQ_ACK); +} + +static void cpm_gates(struct t6041_sleep *s) +{ + writel(0x80000000, s->pwrgate + 0x100); + writel(0x80000000, s->pwrgate + 0x108); + writel(0x80000000, s->pwrgate + 0x110); +} + +static void t6041_ps_match_list(void __iomem *const *regs, + const unsigned long *may_be_fused, + unsigned int count, u32 mask, u32 want) +{ + unsigned int i; + + for (i = 0; i < count; i++) { + u32 now = readl(regs[i]); + + if (may_be_fused && test_bit(i, may_be_fused) && + !(now & (PS_TARGET | PS_ACTUAL))) + continue; + if ((now & mask) != want) + writel((now & ~mask) | want, regs[i]); + } +} + +/* + * Put every matched PS word into its macOS commit mode: hardware AUTO (off, + * clock-gated, or active) or manual active. Only fused-off AMCC/DCS channel + * slices on 24-channel binned parts (reading 0 for both target and actual) + * are skipped; idle non-channel domains such as fab6_soc must still enter + * hardware AUTO. + */ +static void t6041_ps_match_all(struct t6041_sleep *s) +{ + const u32 auto_mask = PS_TARGET | PS_AUTO_ENABLE | PS_AUTO_STATE; + + t6041_ps_match_list(s->ps_auto, s->ps_auto_mem, s->n_auto, auto_mask, + PS_TARGET | PS_AUTO_ENABLE | FIELD_PREP(PS_AUTO_STATE, 0)); + t6041_ps_match_list(s->ps_auto_clkgate, s->ps_auto_clkgate_mem, + s->n_auto_clkgate, auto_mask, + PS_TARGET | PS_AUTO_ENABLE | FIELD_PREP(PS_AUTO_STATE, 4)); + t6041_ps_match_list(s->ps_auto_active, NULL, s->n_auto_active, auto_mask, + PS_TARGET | PS_AUTO_ENABLE | FIELD_PREP(PS_AUTO_STATE, 0xf)); + t6041_ps_match_list(s->ps_keep_on, NULL, s->n_keep_on, + PS_TARGET | PS_AUTO_ENABLE, PS_TARGET); +} + +static void t6041_cpu_off(u64 mpidr) +{ + t6041_offline_wfi(); +} + +static const struct spin_table_power_ops t6041_cpu_power_ops = { + .cpu_stop = t6041_cpu_stop, + .cpu_off = t6041_cpu_off, + .cpu_on = t6041_cpu_on, +}; + +static void __noreturn t6041_boot_wfi(struct t6041_sleep *s) +{ + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntp_ctl_el0); + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntv_ctl_el0); + sysreg_clear_set_s(SYS_APL_DEEP_SLEEP, 0, DEEP_SLEEP_BITS); + while (aic_sleep_ack()) + ; + while (true) { + dsb(sy); + isb(); + wfi(); + aic_sleep_ack(); + write_sysreg_s(IPI_SR_PENDING, SYS_APL_IPI_SR_EL1); + } +} + +/* + * Raise each present core and all three CPM PS words to on, then drop their + * targets to 0 so the hardware drops PS_ACTUAL when each core and cluster + * enters deep WFI. Clear any stray target/auto bits on absent/fused-off cores + * (e.g. pcpu0_5 / pcpu1_5 on 14-core binned parts) without raising them. + */ +static void t6041_cpu_ps_match(struct t6041_sleep *s) +{ + const u32 cpu_clear = PS_TARGET | PS_AUTO_ENABLE | PS_AUTO_STATE; + DECLARE_BITMAP(present, T6041_CPU_COUNT); + unsigned int cpu, i; + u32 v; + + bitmap_zero(present, T6041_CPU_COUNT); + for_each_present_cpu(cpu) { + unsigned int id = t6041_cpu_id(cpu_logical_map(cpu)); + void __iomem *reg = s->ps_cpu[id]; + + __set_bit(id, present); + v = readl(reg); + writel((v & ~cpu_clear) | PS_TARGET, reg); + t6041_poll_until_us(reg, v, FIELD_GET(PS_ACTUAL, v) == 0xf, 2000); + } + for (i = 0; i < T6041_CPM_COUNT; i++) { + void __iomem *reg = s->ps_cpm[i]; + + v = readl(reg); + writel((v & ~cpu_clear) | PS_TARGET, reg); + t6041_poll_until_us(reg, v, FIELD_GET(PS_ACTUAL, v) == 0xf, 2000); + } + for (i = 0; i < T6041_CPU_COUNT; i++) { + void __iomem *reg = s->ps_cpu[i]; + + if (test_bit(i, present)) { + writel(readl(reg) & ~PS_TARGET, reg); + } else { + v = readl(reg); + if (v & cpu_clear) + writel(v & ~cpu_clear, reg); + } + } + for (i = 0; i < T6041_CPM_COUNT; i++) { + void __iomem *reg = s->ps_cpm[i]; + + writel(readl(reg) & ~PS_TARGET, reg); + } +} + +/* + * Lower every USB-C port's power domains in macOS's deepest-first order + * (phymxwrap -> usb -> usb_aon -> common_dp, then cio/pcie -> common) and + * wait for each domain to reach PS_ACTUAL == 0, then hand fab2_soc and afi + * to hardware AUTO (forcing them off hangs T6041). + */ +static void t6041_atc_down(struct t6041_sleep *s) +{ + unsigned int i; + u32 v; + + for (i = 0; i < s->n_atc_off; i++) + t6041_ps_lower(s->ps_atc_off[i]); + for (i = 0; i < s->n_atc_off; i++) { + if (t6041_poll_until_us(s->ps_atc_off[i], v, + !FIELD_GET(PS_ACTUAL, v), 10000)) + s->atc_late++; + } + writel(readl(s->ps_atc_fabric) | PS_AUTO_ENABLE, s->ps_atc_fabric); + writel(readl(s->ps_atc_afi) | PS_AUTO_ENABLE, s->ps_atc_afi); +} + +/* + * Raise fab2_soc manually, raise all four atcN_common domains, then re-enable + * AUTO on fab2_soc so the sleep engine's ATC step never stalls on a gated + * parent fabric. + */ +static int t6041_ps_raise_start(void __iomem *reg) +{ + u32 v; + + writel((readl(reg) & ~(PS_AUTO_ENABLE | GENMASK(11, 0))) | PS_TARGET, reg); + return t6041_poll_until_us(reg, v, (v & PS_ACTUAL) == PS_ACTUAL, 5000); +} + +static void t6041_atc_commons_on(struct t6041_sleep *s) +{ + void __iomem *fab2 = s->ps_atc_fabric; + unsigned int i; + + t6041_ps_raise_start(fab2); + for (i = 0; i < AXI2AF_ATC_COUNT; i++) + t6041_ps_raise_start(s->ps_atc_common[i]); + writel((readl(fab2) & ~(PS_AUTO_ENABLE | GENMASK(11, 0))) | PS_TARGET | PS_AUTO_ENABLE, + fab2); +} + +/* + * Disable DSID age-out (word 0 bit 25) and unexpected RT hit (word 1 bit 8) + * error enables on every AMCC plane and clear any latched error status words. + */ +static void t6041_amcc_quiesce(struct t6041_sleep *s) +{ + unsigned int g, p, w; + + for (g = 0; g < s->ngroups; g++) { + for (p = 0; p < 4; p++) { + void __iomem *a = s->amccb[g] + AMCC_ERR_OFF + AMCC_PLANE_STRIDE * p; + + writel(readl(a + 0x0) & ~BIT(25), a + 0x0); + writel(readl(a + 0x8) & ~BIT(8), a + 0x8); + for (w = 0; w < 7; w++) { + u32 v = readl(a + 4 + 8 * w); + + if (v) + writel(v, a + 4 + 8 * w); + } + } + } + dsb(sy); +} + +/* + * Flush AMCC caches and enable DCS dynamic power gating on every enabled + * channel while the AMCC slices are still forced on. + */ +static void t6041_mcc_macos(struct t6041_sleep *s) +{ + unsigned int i, p; + u32 v; + + for (i = 0; i < s->ngroups; i++) { + /* +0x1c0000 is the AMCC all-planes write window; poll per plane. */ + writel(1, s->amccb[i] + 0x1c082c); + writel(1, s->amccb[i] + 0x1c2844); + for (p = 0; p < 4; p++) + t6041_poll_until_us(s->amccb[i] + AMCC_PLANE_STRIDE * p + 0x2844, + v, !(v & BIT(0)), 100000); + } + dsb(sy); + for (i = 0; i < 4 * s->ngroups; i++) + writel(readl(s->dcs[i] + 0x20) | 0x1100, s->dcs[i] + 0x20); + dsb(sy); +} + +static const char *const t6041_axi2af_names[AXI2AF_REG_COUNT] = { + "axi2af-disp", + "axi2af-dispext0", + "axi2af-dispext1", + "axi2af-dispext2", + "axi2af-dispext3", + "axi2af-ans", + "axi2af-avd", + "axi2af-venc0", + "axi2af-venc1", + "axi2af-jpg", +}; + +static void t6041_wake_sep(struct t6041_sleep *s) +{ + unsigned int i; + u32 v; + + if (readl(s->wake + 0x0)) + writel(0, s->wake + 0x0); + for (i = 0; i < WAKE_WORDS; i++) + writel(s->wake_masks[i], s->wake + 0xc + 4 * i); + + v = readl(s->ps_sep); + if (!(v & BIT(10))) + writel(v | BIT(10), s->ps_sep); + dsb(sy); +} + +/* A perf word: the low nibble asks, [11:8] is the state reached, bit 31 busy. */ +static bool t6041_perf_set(void __iomem *reg, u32 state) +{ + u32 v; + + if (FIELD_GET(PERF_ACTUAL, readl(reg)) == state) + return true; + writel((readl(reg) & ~0xf) | state, reg); + return !t6041_poll_until_us(reg, v, + !(v & PERF_BUSY) && FIELD_GET(PERF_ACTUAL, v) == state, + 5000); +} + +/* SoC to 3, voters 0, DCS to 6: macOS commits at DCS 6 (0x7666); the engine takes it to 4. */ +static void t6041_mem_down(struct t6041_sleep *s) +{ + unsigned int i; + + t6041_perf_set(s->perf + 0x0, 3); + for (i = 0; i < 4; i++) + writel(0, s->pmc + i * 0x4000); + t6041_perf_set(s->perf + 0x400, 6); +} + +/* + * Cluster power-control words: +0 E, +4 P0, +8 P1, +0xc and +0x10 the two AVE + * complexes. Clear bit 5 (CLUSTER_UP_DONE) and take both AVE complexes to 0. + */ +static void t6041_ave_off(struct t6041_sleep *s) +{ + static const u16 ave[] = { 0xc, 0x10 }; + unsigned int i; + u32 v; + + for (i = 0; i < ARRAY_SIZE(ave); i++) { + writel(BIT(5), s->cluster + ave[i]); + t6041_poll_until_us(s->cluster + ave[i], v, !v, 5000); + } + v = readl(s->cluster + 0x8); + if (v & BIT(5)) + writel((v & 0xf) | BIT(5), s->cluster + 0x8); +} + +static void t6041_save(struct t6041_sleep *s); + +/* + * Lower a domain with two writes (AUTO off with target still f, then + * target 0), only when it is currently on so bit 11 does not latch. + */ +static void t6041_ps_lower_pair(void __iomem *reg, u32 first, u32 second) +{ + u32 v = readl(reg); + + if (!FIELD_GET(PS_TARGET, v) && !FIELD_GET(PS_ACTUAL, v)) + return; + writel(first, reg); + writel(second, reg); +} + +/* + * Pulse bit 33 of SOC-DEV-PS-REQ (PTD write +0x10f00) after ANS lowers and + * before arming WD2, matching macOS's traced -10 ms to -4 ms pulse (~6 ms). + * PMP is already halted by apple_sleep_coprocs_stop_all() before commit, so + * its PTD report page provides no completion/ACK bit to poll; read back + * SOC-DEV-PS-REQ (+0x1e00) to post the write before holding the 5 ms pulse. + */ +static void t6041_ptd_soc_dev_pulse(struct t6041_sleep *s) +{ + writeq(0x200000800ULL, s->ptd + PTD_SOC_DEV_REQ_WRITE); + readq(s->ptd + PTD_SOC_DEV_REQ_READ); + t6041_spin_us(5000); + writeq(0x800ULL, s->ptd + PTD_SOC_DEV_REQ_WRITE); +} + +static int t6041_sleep_commit(unsigned long unused) +{ + struct t6041_sleep *s = t6041_sleep; + unsigned int i, cpu; + u32 v; + + t6041_save(s); + s->stop_ret = spin_table_stop_parked(); + t6041_ave_off(s); + /* While every AMCC slice is still on: a clock-gated plane faults. */ + t6041_amcc_quiesce(s); + t6041_mcc_macos(s); + /* + * Disarm AXI2AF bridges on powered blocks before lowering them so the + * power domain does not latch bit 11 on subsequent sleeps. + */ + for (i = 0; i < AXI2AF_COUNT; i++) { + if (!s->axi2af[i]) + continue; + if (FIELD_GET(PS_ACTUAL, readl(s->ps_axi2af[i])) != 0xf) + continue; + v = readl(s->axi2af[i] + 0x4); + if (!(v & 1) && !(readl(s->axi2af[i] + 0x8) & 1)) + continue; + writel(v & ~1U, s->axi2af[i] + 0x4); + writel(readl(s->axi2af[i] + 0x8) & ~1U, s->axi2af[i] + 0x8); + } + t6041_cpu_ps_match(s); + t6041_mem_down(s); + + /* + * Lower child-before-parent sorted domains and wait for each domain to + * reach PS_ACTUAL == 0 before moving on so no parent is ever lowered + * while a child is still powering off (which latches bit 11). + */ + for (i = 0; i < s->n_off; i++) { + t6041_ps_lower(s->ps_off[i]); + if (t6041_poll_until_us(s->ps_off[i], v, + !FIELD_GET(PS_ACTUAL, v), 5000)) + s->off_late++; + } + + t6041_ps_match_all(s); + /* Every PMC voter at 0, and the PMS word macOS holds at 0. */ + for (i = 0; i < 4; i++) + writel(0, s->pmc + i * 0x4000); + writel(0, s->pmc + 0xa9c18); + readl(s->pmc + 0xa9c18); + if (t6041_poll_until_us(s->perf + 0x400, v, + !(v & PERF_BUSY) && FIELD_GET(PERF_ACTUAL, v) <= 6, 20000) || + t6041_poll_until_us(s->perf + 0x0, v, + !(v & PERF_BUSY) && FIELD_GET(PERF_ACTUAL, v) <= 3, 20000)) + s->dcs_late++; + /* Cluster PTD votes, no demand. */ + writeq(0x2000000000000000ULL, s->ptd + PTD_CLUSTER_WRITE_0); + writeq(0x2000000000000000ULL, s->ptd + PTD_CLUSTER_WRITE_1); + writeq(0x2000000000000000ULL, s->ptd + PTD_CLUSTER_WRITE_2); + writeq(0x2000000000000000ULL, s->ptd + PTD_CLUSTER_WRITE_3); + t6041_atc_down(s); + t6041_wake_sep(s); + + writel(0xffef, s->misc + 0x0); + /* + * Mask AIC before releasing parked secondary cores into their final + * deep WFI, then poll each non-boot core and secondary CPM PS word + * until hardware drops PS_ACTUAL to 0. + */ + aic_sleep_mask_all(); + spin_table_release_stopped(); + for_each_present_cpu(cpu) { + unsigned int id; + + if (cpu == smp_processor_id()) + continue; + id = t6041_cpu_id(cpu_logical_map(cpu)); + if (t6041_poll_until_us(s->ps_cpu[id], v, + !FIELD_GET(PS_ACTUAL, v), 50000)) + s->cpu_off_late |= BIT(id); + } + for (i = 0; i < T6041_CPM_COUNT; i++) { + if (i == MPIDR_AFFINITY_LEVEL(cpu_logical_map(smp_processor_id()), 1)) + continue; + if (t6041_poll_until_us(s->ps_cpm[i], v, + !FIELD_GET(PS_ACTUAL, v), 50000)) + s->cpm_off_late |= BIT(i); + } + + writel(0x3f833ff1, s->spmi + SPMI_NOTIFY_MASK); + /* PMU boot stage to 0x50 (asleep). */ + t6041_pmu_write(s, 0xf801, 0x50); + writel(0x3f0, s->ps_commit_periph[0]); + writel(0x3f0, s->ps_commit_periph[1]); + writel(0x3f0, s->ps_commit_periph[2]); + writel(0x3f0, s->ps_commit_periph[3]); + writel(0x2000001, s->spmi + SPMI_NOTIFY_MASK); + if (FIELD_GET(PS_ACTUAL, readl(s->ps_spmi_a0))) + writel(0x2000001, s->spmi_a0 + SPMI_NOTIFY_MASK); + writel(0x3f0, s->ps_commit_periph[4]); + cpm_gates(s); + writel(0, s->cluster + 0x0); + cpm_gates(s); + writel(0, s->cluster + 0x8); + t6041_ps_lower_pair(s->ps_apcie[T6041_APCIE_PHY_SW], 0x400004f, 0x4000340); + t6041_ps_lower_pair(s->ps_apcie[T6041_APCIE_SYS_ST1], 0xf, 0x300); + writel(0x3f0, s->ps_apcie[T6041_APCIE_ST1]); + t6041_ps_lower_pair(s->ps_apcie[T6041_APCIE_SYS_ST0], 0xf0000ff, 0xf0003f0); + writel(0x3f0, s->ps_apcie[T6041_APCIE_ST0]); + t6041_ps_lower_pair(s->ps_apcie[T6041_APCIE_SYS_GP], 0xf, 0x300); + writel(0x3f0, s->ps_apcie[T6041_APCIE_GP]); + t6041_ps_lower_pair(s->ps_apcie[T6041_APCIE_ANS], 0xf0000ff, 0xf0003f0); + /* macOS -10 ms to -4 ms before arming WD2: pulse PTD SOC-DEV-PS-REQ bit 33. */ + t6041_ptd_soc_dev_pulse(s); + writel(0, s->wdt + 0x0c); + writel(0, s->wdt + 0x2c); + writel(0, s->wdt + 0x20); + writel(0x7270e00, s->wdt + 0x28); + writel(1, s->wdt + 0x2c); + writel(0, s->aon + 0x8); + cpm_gates(s); + cpm_gates(s); + cpm_gates(s); + writel(0x10, s->cluster + 0x00); + writel(0, s->cluster + 0x04); + writel(0x10, s->cluster + 0x08); + writel(0x20, s->cluster + 0x0c); + writel(0, s->cluster + 0x10); + writel(0x400024f, s->ps_commit_sio[0]); + writel(0x400024f, s->ps_commit_sio[1]); + writel(0xa0100000, s->clkgen + 0x60); + writel(0xa0100000, s->clkgen + 0x64); + writel(0xa0100000, s->clkgen + 0x54); + writel(0xa0100000, s->clkgen + 0x50); + /* aura reads this with the MMU off on the way back. */ + WRITE_ONCE(s->mbox->resume_pa, __pa_symbol(cpu_resume)); + dcache_clean_poc((unsigned long)s->mbox, (unsigned long)(s->mbox + 1)); + t6041_atc_commons_on(s); + /* + * Confirm the SPMI controller's TX and RX FIFOs are idle after the + * PMU boot-stage write before the sleep engine takes over SPMI. + */ + if (t6041_poll_until_us(s->spmi + SPMI_STATUS, v, + (v & SPMI_IDLE) == SPMI_IDLE, 5000)) + s->spmi_late++; + /* + * Keep SPMI quiet before clearing keep-alive tables and committing + * sleep, matching macOS and the sleep engine's bus handoff window. + */ + t6041_spin_us(20000); + /* Keep-alive tables off right before commit. */ + for (i = 0; i < KA_WORDS; i++) { + writel(0, s->ka[0] + i * KA_STRIDE); + writel(0, s->ka[1] + i * KA_STRIDE); + } + dsb(sy); + writel(1, s->commit); + dsb(sy); + /* + * Secondary cores and non-boot CPMs are already polled off in deep WFI. + * Mask AIC again and hold the 3 ms commit-to-boot-WFI gap (matching + * sleep.c's boot_wfi_delay_ms = 3 on T8132/T8142; no hardware status + * bit reports commit-armed, and pure counter spin avoids WFET early + * gating) before entering the boot core's final deep WFI. + */ + aic_sleep_mask_all(); + t6041_spin_us(3000); + t6041_boot_wfi(s); +} + +/* + * Display pipe PMC votes saved before commit and restored on wake (offsets into + * the PMC register block). + */ +static const u32 t6041_pmc_vote_off[5] = { 0xac028, 0xa4000, 0xac020, 0xa9c10, 0xa9c20 }; + +/* + * Restore AMCC cache mode after wake: write way count through the all-planes + * window, then poll each plane's status word. + */ +static void t6041_mcc_active(struct t6041_sleep *s) +{ + unsigned int i, p; + u32 v; + + for (i = 0; i < s->ngroups; i++) { + writel(s->pre_ways[4 * i], s->amccb[i] + 0x1c2800); + for (p = 0; p < 4; p++) + readl_poll_timeout_atomic(s->amccb[i] + AMCC_PLANE_STRIDE * p + 0x2804, v, + v == s->pre_cache[4 * i + p], 10, 100000); + } +} + +/* Restore display PMC votes; wait for the DVMR ack (+0x20). */ +static void t6041_pmc_votes(struct t6041_sleep *s) +{ + unsigned int i; + u32 v; + + for (i = 0; i < ARRAY_SIZE(t6041_pmc_vote_off); i++) { + void __iomem *reg = s->pmc + t6041_pmc_vote_off[i]; + + if (readl(reg) != s->pre_votes[i]) + writel(s->pre_votes[i], reg); + if (t6041_pmc_vote_off[i] == 0xa4000 && s->pre_votes[i]) + readl_poll_timeout_atomic(reg + 0x20, v, v & BIT(0), 1, 8000); + } +} + +static const u16 t6041_clk_mux[4] = { 0x50, 0x54, 0x64, 0x60 }; + +static void t6041_save(struct t6041_sleep *s) +{ + unsigned int i; + + for (i = 0; i < 4 * s->ngroups; i++) { + void __iomem *plane = s->amccb[i / 4] + AMCC_PLANE_STRIDE * (i % 4); + + s->pre_ways[i] = readl(plane + 0x2800); + s->pre_cache[i] = readl(plane + 0x2804); + } + for (i = 0; i < ARRAY_SIZE(t6041_pmc_vote_off); i++) + s->pre_votes[i] = readl(s->pmc + t6041_pmc_vote_off[i]); + s->cntkctl = read_sysreg(cntkctl_el1); + s->siq_cfg = read_sysreg_s(SYS_APL_SIQ_CFG_EL1); + for (i = 0; i < s->n_restore; i++) + s->ps_pre[i] = readl(s->ps_restore[i]); + s->pre_perf[0] = readl(s->perf + 0x0); + s->pre_perf[1] = readl(s->perf + 0x400); + for (i = 0; i < 4; i++) + s->pre_pmc[i] = readl(s->pmc + i * 0x4000); + s->pre_pmc[4] = readl(s->pmc + 0xa9c18); + for (i = 0; i < 4; i++) + s->pre_clk[i] = readl(s->clkgen + t6041_clk_mux[i]); + s->pre_mask[0] = readl(s->spmi + SPMI_NOTIFY_MASK); + s->pre_a0 = FIELD_GET(PS_ACTUAL, readl(s->ps_spmi_a0)) != 0; + if (s->pre_a0) + s->pre_mask[1] = readl(s->spmi_a0 + SPMI_NOTIFY_MASK); + for (i = 0; i < WAKE_WORDS; i++) + s->pre_wake[i] = readl(s->wake + 0xc + 4 * i); + for (i = 0; i < AOP_PS_WORDS; i++) + s->aop_pre[i] = readl(s->aop_ps + 8 * i); + for (i = 0; i < s->npins; i++) { + if (test_bit(i, s->gpio_skip)) + continue; + s->gpio_pre[i] = readl(s->gpio + 4 * i); + } + /* Only with the GP PCIe block on: apcie_gp and apcie_sys_gp. */ + s->gp_saved = s->gp_port[0] && s->gp_port[1] && s->gp_phy[0] && s->gp_phy[1] && + FIELD_GET(PS_ACTUAL, readl(s->ps_apcie[T6041_APCIE_GP])) == 0xf && + FIELD_GET(PS_ACTUAL, readl(s->ps_apcie[T6041_APCIE_SYS_GP])) == 0xf; + for (i = 0; i < 2 && s->gp_saved; i++) { + s->gp_phy_pre[i] = readl(s->gp_phy[i]); + s->gp_app_pre[i] = readl(s->gp_port[i] + 0x800); + s->gp_perst_pre[i] = readl(s->gp_port[i] + 0x82c); + } +} + +/* + * Restore all AP GPIO pin configurations lost across deep sleep, skipping pins + * listed in apple,pinctrl-skip-pins. + */ +static void t6041_gpio_restore(struct t6041_sleep *s) +{ + unsigned int i; + + for (i = 0; i < s->npins; i++) { + if (test_bit(i, s->gpio_skip)) + continue; + if (readl(s->gpio + 4 * i) != s->gpio_pre[i]) + writel(s->gpio_pre[i], s->gpio + 4 * i); + } +} + +/* + * AOP island MiniPMGR power words (ps-aop). Walked backwards (parents first) + * on wake so every previously-on domain returns to manual target f. + */ +static const u16 t6041_aop_ps_order[] = { + 0x0b0, 0x128, 0x120, 0x158, 0x150, 0x148, 0x140, 0x138, 0x130, 0x0c0, 0x0c8, + 0x0e8, 0x0f0, 0x0f8, 0x100, 0x108, 0x110, 0x118, 0x0e0, 0x0d8, 0x0d0, 0x0b8, 0x090, + 0x020, 0x098, 0x0a0, 0x0a8, 0x028, 0x030, 0x068, 0x070, 0x078, 0x080, 0x038, 0x040, + 0x048, 0x058, 0x060, 0x088, 0x050, 0x010, 0x018, 0x008, 0x000, +}; + +static_assert(ARRAY_SIZE(t6041_aop_ps_order) == AOP_PS_WORDS); + +static void t6041_aop_wake(struct t6041_sleep *s) +{ + int k; + u32 v; + + for (k = ARRAY_SIZE(t6041_aop_ps_order) - 1; k >= 0; k--) { + u16 off = t6041_aop_ps_order[k]; + void __iomem *r = s->aop_ps + off; + u32 now = readl(r); + + if (!FIELD_GET(PS_ACTUAL, s->aop_pre[off / 8])) + continue; + if (FIELD_GET(PS_ACTUAL, now) == 0xf && !(now & PS_AUTO_ENABLE)) + continue; + writel((now & ~(PS_AUTO_ENABLE | PS_TARGET)) | PS_TARGET, r); + readl_poll_timeout_atomic(r, v, FIELD_GET(PS_ACTUAL, v), 1, 2000); + } +} + +static int t6041_ps_raise(void __iomem *reg) +{ + int ret = t6041_ps_raise_start(reg); + + writel((readl(reg) & ~(PS_AUTO_ENABLE | GENMASK(11, 0))) | PS_TARGET | PS_AUTO_ENABLE, reg); + return ret; +} + +/* + * Bring ANS's storage PCIe link back from power-off using the DT-supplied + * apple,tunable-* tables from apple,apcie. Returns 0, or the step (1-8) that + * timed out. Runs only when the NVMe driver stopped ANS for this sleep. + */ +static int t6041_apcie_raise(struct t6041_sleep *s) +{ + void __iomem *ctrl = s->ap_phy + 0x8000; + void __iomem *run = s->ap_phy + 0x8004; + u32 v; + int ret; + + ret = t6041_ps_raise(s->ps_apcie[T6041_APCIE_ANS]); + if (!ret) { + writel(readl(s->axi2af[AXI2AF_ANS] + 0x4) | 1, s->axi2af[AXI2AF_ANS] + 0x4); + writel(readl(s->axi2af[AXI2AF_ANS] + 0x8) | 1, s->axi2af[AXI2AF_ANS] + 0x8); + } + ret |= t6041_ps_raise(s->ps_apcie[T6041_APCIE_GP]); + if (!ret) + ret = t6041_ps_raise_start(s->ps_apcie[T6041_APCIE_SYS_GP]); + if (!ret) { + writel(readl(s->ap_axi + 0x104) | 1, s->ap_axi + 0x104); + writel(readl(s->ap_axi + 0x108) | 1, s->ap_axi + 0x108); + } + ret |= t6041_ps_raise(s->ps_apcie[T6041_APCIE_ST0]); + ret |= t6041_ps_raise(s->ps_apcie[T6041_APCIE_SYS_ST0]); + ret |= t6041_ps_raise(s->ps_apcie[T6041_APCIE_ST1]); + ret |= t6041_ps_raise(s->ps_apcie[T6041_APCIE_SYS_ST1]); + if (ret) + return 1; + + apple_tunable_apply(s->ap_axi, s->tun_axi2af); + apple_tunable_apply(s->ap_cio3pll, s->tun_cio3pll); + apple_tunable_apply(s->ap_clkgen, s->tun_clkgen); + writel(readl(s->ap_clkgen + 0x4) | BIT(31), s->ap_clkgen + 0x4); + writel(readl(s->ap_clkgen + 0x0) & ~(BIT(2) | BIT(1)), s->ap_clkgen + 0x0); + if (readl_poll_timeout_atomic(s->ap_clkgen + 0x0, v, !(v & BIT(31)), 1, 50000)) + return 2; + if (t6041_ps_raise(s->ps_apcie[T6041_APCIE_PHY_SW])) + return 3; + apple_tunable_apply(s->ap_phy, s->tun_phy); + if (readl_poll_timeout_atomic(s->ap_phy + 0x4000, v, v & BIT(31), 1, 50000)) + return 4; + writel(readl(ctrl) | BIT(0), ctrl); + if (readl_poll_timeout_atomic(ctrl, v, v & BIT(2), 1, 50000)) + return 5; + writel(readl(ctrl) | BIT(1), ctrl); + if (readl_poll_timeout_atomic(ctrl, v, v & BIT(3), 1, 50000)) + return 6; + writel(readl(ctrl) & ~BIT(4), ctrl); + + writel(readl(run) | BIT(0), run); + apple_tunable_apply(s->ap_phy_ip, s->tun_phy_ip_pll); + apple_tunable_apply(s->ap_phy_ip, s->tun_phy_ip_lanes); + writel(readl(s->ap_phy_ip + 0x90) & ~BIT(16), s->ap_phy_ip + 0x90); + writel(readl(run) | BIT(4), run); + if (readl_poll_timeout_atomic(s->ap_phy + 0x8008, v, v & BIT(0), 1, 50000)) + return 7; + writel(readl(s->ap_phy + 0x4000) | BIT(0), s->ap_phy + 0x4000); + writel(readl(ctrl) | BIT(27), ctrl); + + writel(0, s->ap_rc + 0x04); + writel(0x140, s->ap_rc + 0x54); + writel(1, s->ap_rc + 0x50); + if (readl_poll_timeout_atomic(s->ap_rc + 0x58, v, v & BIT(0), 1, 50000)) + return 8; + return 0; +} + +/* + * Restore GP PCIe port 0/1 reference and app clocks after deep sleep so their + * DART blocks do not raise SErrors on resume. Returns a mask of late ports. + */ +static unsigned int t6041_gp_pcie_clk(struct t6041_sleep *s) +{ + unsigned int i, late = 0; + u32 v; + + for (i = 0; i < 2; i++) { + void __iomem *phy = s->gp_phy[i]; + void __iomem *port = s->gp_port[i]; + u32 cfg = s->gp_phy_pre[i]; + u32 app = s->gp_app_pre[i]; + + if (!s->gp_saved || + FIELD_GET(PS_ACTUAL, readl(s->ps_apcie[T6041_APCIE_GP])) != 0xf || + FIELD_GET(PS_ACTUAL, readl(s->ps_apcie[T6041_APCIE_SYS_GP])) != 0xf) + continue; + writel(readl(phy) | BIT(0), phy); + if (readl_poll_timeout_atomic(phy, v, v & BIT(2), 1, 50000)) + late |= BIT(i); + writel(readl(phy) | BIT(1), phy); + if (readl_poll_timeout_atomic(phy, v, v & BIT(3), 1, 50000)) + late |= BIT(i); + if (!(cfg & BIT(4))) { + writel(readl(phy) & ~BIT(4), phy); + /* T6020+ PHY refclk buffer settle before REFCLKEN (as in pcie-apple.c). */ + udelay(1); + } + writel(readl(phy) | (cfg & (BIT(9) | BIT(10))), phy); + writel(readl(phy) | (cfg & BIT(31)), phy); + writel((readl(port + 0x800) & ~(BIT(0) | BIT(8))) | (app & (BIT(0) | BIT(8))), + port + 0x800); + writel(readl(port + 0x13c) | BIT(8), port + 0x13c); + writel(s->gp_perst_pre[i], port + 0x82c); + writel(readl(port + 0x13c) & ~BIT(8), port + 0x13c); + if (readl_poll_timeout_atomic(port + 0x804, v, v & BIT(0), 1, 50000)) + late |= BIT(i); + } + return late; +} + +/* + * Restore every non-CPU/CPM PS word to its pre-commit target and AUTO state: + * raises parents first (0..n_restore-1), then lowers children first. + */ +static unsigned int t6041_ps_restore(struct t6041_sleep *s) +{ + const u32 keep = ~(u32)(PS_AUTO_ENABLE | PS_FLAGS | PS_TARGET); + unsigned int i, late = 0; + u32 v; + + for (i = 0; i < s->n_restore; i++) { + void __iomem *reg = s->ps_restore[i]; + u32 pre = s->ps_pre[i]; + u32 cur = readl(reg); + u32 pt = pre & PS_TARGET; + + if (!(pre & (PS_TARGET | PS_ACTUAL)) && !(cur & (PS_TARGET | PS_ACTUAL))) + continue; + if (pt > (cur & PS_TARGET)) { + writel((cur & keep) | pt, reg); + if (readl_poll_timeout_atomic(reg, v, FIELD_GET(PS_ACTUAL, v) == pt, + 1, 3000)) + late++; + cur = readl(reg); + } + if (pt == (cur & PS_TARGET) && ((pre ^ cur) & PS_AUTO_ENABLE)) + writel((cur & ~(PS_AUTO_ENABLE | PS_FLAGS)) | (pre & PS_AUTO_ENABLE), reg); + } + for (i = s->n_restore; i-- > 0;) { + void __iomem *reg = s->ps_restore[i]; + u32 pre = s->ps_pre[i]; + u32 cur = readl(reg); + u32 pt = pre & PS_TARGET; + + if (pt >= (cur & PS_TARGET)) + continue; + if (cur & PS_AUTO_ENABLE) { + cur &= ~(PS_AUTO_ENABLE | PS_FLAGS); + writel(cur, reg); + } + writel((cur & keep) | pt | PS_FLAGS, reg); + if (readl_poll_timeout_atomic(reg, v, FIELD_GET(PS_ACTUAL, v) == pt, 1, 3000)) + late++; + if (pre & PS_AUTO_ENABLE) + writel((readl(reg) & ~PS_FLAGS) | PS_AUTO_ENABLE, reg); + } + return late; +} + +static u64 t6041_ret_t0, t6041_ret_t1; + +/* + * Back on the boot core through aura's mailbox: clusters on, masks back, WD2 off. + * Hardware wake reset restores the boot CPU power state before return, so + * udelay()/readl_poll_timeout_atomic() are safe here and in its helpers. + */ +static void t6041_sleep_return(struct t6041_sleep *s) +{ + unsigned int i; + u32 v; + + t6041_ret_t0 = read_sysreg(cntpct_el0); + /* The reset left the timer control and the AIC's IRQ routing at their EL2 defaults. */ + write_sysreg(s->cntkctl, cntkctl_el1); + isb(); + write_sysreg_s(s->siq_cfg, SYS_APL_SIQ_CFG_EL1); + writel(0, s->wdt + 0x2c); + /* Keep-alive back on, as macOS on its way back and as iBoot leaves it. */ + for (i = 0; i < KA_WORDS; i++) { + writel(1, s->ka[0] + i * KA_STRIDE); + writel(1, s->ka[1] + i * KA_STRIDE); + } + spin_table_stop_finished(); + aic_sleep_restore(); + writel(0xf, s->cluster + 0x0); + writel(0xf, s->cluster + 0x4); + writel(0xf, s->cluster + 0x8); + /* The two wake gates, then the CPM voters. */ + writel(readl(s->pwrgate + 0x000) | BIT(31), s->pwrgate + 0x000); + writel(readl(s->pwrgate + 0x040) | BIT(31), s->pwrgate + 0x040); + cpm_gates(s); + /* SEP DEV_DISABLE off again, bit 11 polled clear; S2R request word; wake masks. */ + v = readl(s->ps_sep); + if (v & BIT(10)) + writel(v & ~BIT(10), s->ps_sep); + readl_poll_timeout_atomic(s->ps_sep, v, !(v & BIT(11)), 1, 5000); + writel(0, s->wake + 0x0); + for (i = 0; i < WAKE_WORDS; i++) + writel(s->pre_wake[i], s->wake + 0xc + 4 * i); + /* Before t6041_mcc_active() touches the AMCC/DCS planes. */ + s->ps_late = t6041_ps_restore(s); + t6041_mcc_active(s); + t6041_aop_wake(s); + t6041_gpio_restore(s); + /* Re-arm AXI2AF bridges whose blocks are back on. */ + for (i = 0; i < AXI2AF_COUNT; i++) { + if (!s->axi2af[i]) + continue; + v = readl(s->ps_axi2af[i]); + if ((v & PS_TARGET) != PS_TARGET || FIELD_GET(PS_ACTUAL, v) != 0xf) + continue; + writel(readl(s->axi2af[i] + 0x4) | 1, s->axi2af[i] + 0x4); + writel(readl(s->axi2af[i] + 0x8) | 1, s->axi2af[i] + 0x8); + } + s->apcie_ret = s->ans_stopped ? t6041_apcie_raise(s) : 0; + s->gp_late = t6041_gp_pcie_clk(s); + /* Restore parked clock muxes (last parked first), perf states, and PMC voters. */ + for (i = 4; i-- > 0;) + writel(s->pre_clk[i], s->clkgen + t6041_clk_mux[i]); + t6041_perf_set(s->perf + 0x400, s->pre_perf[1] & 0xf); + t6041_perf_set(s->perf + 0x0, s->pre_perf[0] & 0xf); + for (i = 0; i < 4; i++) + writel(s->pre_pmc[i], s->pmc + i * 0x4000); + writel(s->pre_pmc[4], s->pmc + 0xa9c18); + t6041_pmc_votes(s); + writel(s->pre_mask[0], s->spmi + SPMI_NOTIFY_MASK); + if (s->pre_a0 && FIELD_GET(PS_ACTUAL, readl(s->ps_spmi_a0))) + writel(s->pre_mask[1], s->spmi_a0 + SPMI_NOTIFY_MASK); + writel(0, s->wdt + 0x2c); + /* PMU boot stage back from 0x50 (asleep) to 0x30 (OS running). */ + t6041_pmu_write(s, 0xf801, 0x30); + t6041_ret_t1 = read_sysreg(cntpct_el0); +} + +static int t6041_sleep_enter(suspend_state_t state) +{ + struct t6041_sleep *s = t6041_sleep; + unsigned int i; + int ret; + + /* With no way back, a sleep would end in aura's boot flow over this kernel. */ + if (!s->mbox) + return -EOPNOTSUPP; + if (WARN_ON_ONCE(!s->apcie_ready)) + return -EOPNOTSUPP; + /* + * Display power chains require GAPF unprotect, child-first lowering, and + * fab6_soc hold (handled by apple-dcp); refuse sleep if any display block + * is still active (e.g., apple-drm unbound or nomodeset). + */ + for (i = 0; i < AXI2AF_DISP_COUNT; i++) { + u32 v = readl(s->ps_axi2af[AXI2AF_DISP_FIRST + i]); + + if (v & (PS_TARGET | PS_ACTUAL)) { + dev_err(s->dev, "refused: display domain %u still active (%#x)\n", i, v); + return -EBUSY; + } + } + /* + * Every parked CPU answers the hold while a refusal is still possible: at the commit + * only a held CPU stops, and one left awake there keeps the engine waiting until the + * watchdog resets the SoC. + */ + ret = spin_table_hold_parked(); + if (ret) { + dev_err(s->dev, "refused: a parked CPU didn't answer the hold: %d\n", ret); + return ret; + } + ret = apple_sleep_coprocs_check_all(); + if (ret) { + spin_table_unhold_parked(); + return ret; + } + if (pm_wakeup_pending()) { + spin_table_unhold_parked(); + return -EBUSY; + } + /* + * Send SEP SLEEP only after every refusal check has passed: a nonzero + * return here guarantees nothing was sent, while success gates the + * enclave and commits this sleep through physical wake. + */ + ret = apple_sleep_enclave_stop_all(); + if (ret) { + spin_table_unhold_parked(); + return ret; + } + s->stop_ret = 0; + s->apcie_ret = 0; + s->atc_late = 0; + s->off_late = 0; + s->dcs_late = 0; + s->cpu_off_late = 0; + s->cpm_off_late = 0; + s->spmi_late = 0; + s->ps_late = 0; + s->gp_late = 0; + /* macOS stops the PMP before its last steps; past this a refusal can't go back. */ + ret = apple_sleep_coprocs_stop_all(); + s->coproc_ret = ret; + s->ans_stopped = apple_sleep_coprocs_ans_stopped(); + pm_set_resume_via_firmware(); + ret = cpu_suspend(0, t6041_sleep_commit); + if (!ret) + t6041_sleep_return(s); + return ret; +} + +static void t6041_sleep_end(void) +{ + struct t6041_sleep *s = t6041_sleep; + + if (!s || !t6041_ret_t1) + return; + dev_dbg(s->dev, "back from deep sleep, return path %llu ms\n", + div64_u64((t6041_ret_t1 - t6041_ret_t0) * 1000, arch_timer_get_cntfrq())); + t6041_ret_t1 = 0; + if (s->coproc_ret < 0) + dev_warn(s->dev, "a coprocessor didn't stop for the sleep: %d\n", s->coproc_ret); + if (s->stop_ret) + dev_warn(s->dev, "the parked CPUs didn't all stop: %d\n", s->stop_ret); + if (s->atc_late) + dev_warn(s->dev, "%u ATC power domains did not reach off before commit\n", + s->atc_late); + if (s->off_late) + dev_warn(s->dev, "%u power domains did not reach off before commit\n", + s->off_late); + if (s->dcs_late) + dev_warn(s->dev, "DCS/SoC perf did not settle after clearing PMC voters\n"); + if (s->cpu_off_late) + dev_warn(s->dev, "secondary CPUs %#x did not reach off before commit\n", + s->cpu_off_late); + if (s->cpm_off_late) + dev_warn(s->dev, "secondary CPMs %#x did not reach off before commit\n", + s->cpm_off_late); + if (s->spmi_late) + dev_warn(s->dev, "%u SPMI waits timed out around sleep\n", s->spmi_late); + if (s->ps_late) + dev_dbg(s->dev, "%u power domains took more than 3 ms to come back\n", s->ps_late); + if (s->apcie_ret) + dev_warn(s->dev, "storage link raise timed out at step %d\n", s->apcie_ret); + if (s->gp_late) + dev_warn(s->dev, "GP PCIe ports %#x didn't come back\n", s->gp_late); +} + +static int t6041_sleep_begin(suspend_state_t state) +{ + /* The PM core also calls .begin for s2idle when no s2idle ops are installed. */ + if (state != PM_SUSPEND_MEM) + return 0; + pm_set_suspend_via_firmware(); + return 0; +} + +static const struct platform_suspend_ops t6041_sleep_ops = { + .valid = suspend_valid_only_mem, + .begin = t6041_sleep_begin, + .end = t6041_sleep_end, + .enter = t6041_sleep_enter, +}; + +static void t6041_iounmap(void *base) +{ + iounmap((void __iomem *)base); +} + +static void __iomem *t6041_map_idx(struct device *dev, struct device_node *np, + int idx, resource_size_t min_size, + resource_size_t *out_size) +{ + struct resource res; + void __iomem *base; + int ret; + + if (idx < 0 || of_address_to_resource(np, idx, &res)) + return IOMEM_ERR_PTR(-EINVAL); + if (resource_size(&res) < min_size) + return IOMEM_ERR_PTR(-EINVAL); + /* Shared with other drivers, so map without claiming the region. */ + base = of_iomap(np, idx); + if (!base) + return IOMEM_ERR_PTR(-ENOMEM); + ret = devm_add_action_or_reset(dev, t6041_iounmap, (void __force *)base); + if (ret) + return IOMEM_ERR_PTR(ret); + if (out_size) + *out_size = resource_size(&res); + return base; +} + +static void __iomem *t6041_map_name(struct device *dev, struct device_node *np, + const char *name, resource_size_t min_size, + resource_size_t *out_size) +{ + int idx = of_property_match_string(np, "reg-names", name); + + if (idx < 0) + return IOMEM_ERR_PTR(idx); + return t6041_map_idx(dev, np, idx, min_size, out_size); +} + +struct t6041_pmgr_bank { + struct device_node *np; + void __iomem *base; + resource_size_t size; +}; + +struct t6041_ps_resolver { + struct device *dev; + struct t6041_pmgr_bank banks[T6041_MAX_PMGR_BANKS]; + unsigned int nbanks; +}; + +static void t6041_ps_resolver_cleanup(struct t6041_ps_resolver *r) +{ + unsigned int i; + + for (i = 0; i < r->nbanks; i++) + of_node_put(r->banks[i].np); +} + +static void __iomem *t6041_resolve_ps_node(struct t6041_ps_resolver *r, + struct device_node *ps_np) +{ + struct t6041_pmgr_bank *bank = NULL; + struct device_node *parent; + unsigned int i; + u32 off; + + if (of_property_read_u32(ps_np, "reg", &off) || (off & 3)) { + dev_err(r->dev, "%pOF: invalid PMGR PS reg offset\n", ps_np); + return IOMEM_ERR_PTR(-EINVAL); + } + + parent = of_get_parent(ps_np); + if (!parent) + return IOMEM_ERR_PTR(-EINVAL); + + for (i = 0; i < r->nbanks; i++) { + if (r->banks[i].np == parent) { + bank = &r->banks[i]; + break; + } + } + + if (!bank) { + resource_size_t size; + void __iomem *base; + + if (r->nbanks >= T6041_MAX_PMGR_BANKS) { + of_node_put(parent); + return IOMEM_ERR_PTR(-ENOSPC); + } + base = t6041_map_idx(r->dev, parent, 0, 4, &size); + if (IS_ERR(base)) { + of_node_put(parent); + return base; + } + bank = &r->banks[r->nbanks++]; + bank->np = of_node_get(parent); + bank->base = base; + bank->size = size; + } + of_node_put(parent); + + if (off > bank->size || bank->size - off < 4) { + dev_err(r->dev, "%pOF: offset %#x exceeds parent size %pa\n", + ps_np, off, &bank->size); + return IOMEM_ERR_PTR(-EINVAL); + } + + return bank->base + off; +} + +static int t6041_parse_ps_fixed(struct t6041_ps_resolver *r, const char *prop, + void __iomem **out_regs, + struct device_node **out_nodes, + unsigned int expected) +{ + struct device_node *np = r->dev->of_node; + unsigned int i; + int count; + + count = of_count_phandle_with_args(np, prop, NULL); + if (count != expected) + return dev_err_probe(r->dev, -EINVAL, + "%s: expected %u phandles, got %d\n", + prop, expected, count); + + for (i = 0; i < expected; i++) { + struct device_node *ps_np; + void __iomem *reg; + + ps_np = of_parse_phandle(np, prop, i); + if (!ps_np) + return dev_err_probe(r->dev, -EINVAL, + "%s[%u]: unresolved phandle\n", + prop, i); + reg = t6041_resolve_ps_node(r, ps_np); + if (IS_ERR(reg)) { + of_node_put(ps_np); + return dev_err_probe(r->dev, PTR_ERR(reg), + "%s[%u]: cannot map PS register\n", + prop, i); + } + out_regs[i] = reg; + if (out_nodes) + out_nodes[i] = ps_np; + else + of_node_put(ps_np); + } + return 0; +} + +struct t6041_topo_ctx { + struct device *dev; + struct device_node *const *nodes; + unsigned int n; + unsigned int stride; + unsigned long *adj; + unsigned int *indeg; +}; + +static int t6041_topo_find(const struct t6041_topo_ctx *ctx, + const struct device_node *np) +{ + unsigned int i; + + for (i = 0; i < ctx->n; i++) + if (ctx->nodes[i] == np) + return i; + return -1; +} + +static int t6041_ps_parent(struct device_node *np, int index, + struct device_node **out) +{ + struct of_phandle_args args; + int ret; + + ret = of_parse_phandle_with_args(np, "power-domains", + "#power-domain-cells", index, &args); + if (ret) { + *out = NULL; + return ret; + } + *out = args.np; + return 0; +} + +static int t6041_topo_add_ancestors(struct t6041_topo_ctx *ctx, unsigned int src, + struct device_node *np, unsigned int depth) +{ + struct device_node *parent; + int k, ret; + + if (depth >= T6041_PS_MAX_DEPTH) { + dev_err(ctx->dev, "PMGR power-domain hierarchy too deep or cyclic at %pOF\n", np); + return -EINVAL; + } + + for (k = 0; ; k++) { + int idx; + + ret = t6041_ps_parent(np, k, &parent); + if (ret == -ENOENT) + break; + if (ret) + return ret; + + idx = t6041_topo_find(ctx, parent); + if (idx == (int)src) { + dev_err(ctx->dev, "PMGR power-domain cycle involving %pOF\n", parent); + of_node_put(parent); + return -EINVAL; + } + if (idx >= 0) { + if (!__test_and_set_bit(idx, ctx->adj + (size_t)src * ctx->stride)) + ctx->indeg[idx]++; + } else { + ret = t6041_topo_add_ancestors(ctx, src, parent, depth + 1); + if (ret) { + of_node_put(parent); + return ret; + } + } + of_node_put(parent); + } + return 0; +} + +/* + * Stable (input-order-preserving) Kahn's topological sort on DT power-domains + * edges (child -> parent). For child-first (shutdown), pick the lowest-index + * ready node forward; for parent-first (restore), run the same child-first + * pass in reverse index order and reverse the output so edge-free nodes later + * in the list (such as auto-managed DCS domains after AMCCs) stay after + * earlier nodes whose ancestors are resolved later. + */ +static int t6041_topo_sort(struct device *dev, struct device_node *const *nodes, + unsigned int n, unsigned int *order, bool child_first) +{ + struct t6041_topo_ctx ctx = { + .dev = dev, + .nodes = nodes, + .n = n, + .stride = BITS_TO_LONGS(n), + }; + unsigned long *emitted = NULL; + unsigned int i, step; + int ret = 0; + + if (!n) + return 0; + + ctx.adj = kcalloc((size_t)n * ctx.stride, sizeof(*ctx.adj), GFP_KERNEL); + ctx.indeg = kcalloc(n, sizeof(*ctx.indeg), GFP_KERNEL); + emitted = bitmap_zalloc(n, GFP_KERNEL); + if (!ctx.adj || !ctx.indeg || !emitted) { + ret = -ENOMEM; + goto out; + } + + for (i = 0; i < n; i++) { + ret = t6041_topo_add_ancestors(&ctx, i, nodes[i], 0); + if (ret) + goto out; + } + + for (step = 0; step < n; step++) { + unsigned int pick, next; + bool found = false; + + if (child_first) { + for (pick = 0; pick < n; pick++) { + if (!test_bit(pick, emitted) && !ctx.indeg[pick]) { + found = true; + break; + } + } + } else { + for (pick = n; pick-- > 0; ) { + if (!test_bit(pick, emitted) && !ctx.indeg[pick]) { + found = true; + break; + } + } + } + if (!found) { + dev_err(dev, "PMGR power-domain cycle detected\n"); + ret = -EINVAL; + goto out; + } + __set_bit(pick, emitted); + order[child_first ? step : n - 1 - step] = pick; + for_each_set_bit(next, ctx.adj + (size_t)pick * ctx.stride, n) + ctx.indeg[next]--; + } + +out: + bitmap_free(emitted); + kfree(ctx.indeg); + kfree(ctx.adj); + return ret; +} + +static bool t6041_node_in_list(struct device_node *const *list, unsigned int n, + const struct device_node *np) +{ + unsigned int i; + + for (i = 0; i < n; i++) + if (list[i] == np) + return true; + return false; +} + +struct t6041_restore_acc { + struct device_node **nodes; + void __iomem **regs; + unsigned int count; + struct device_node *const *exclude; + unsigned int n_exclude; +}; + +static bool t6041_ps_is_mem_channel(const struct device_node *np) +{ + const char *label; + + if (of_property_read_string(np, "label", &label)) + return false; + return str_has_prefix(label, "amcc") || str_has_prefix(label, "dcs_"); +} + +static int t6041_parse_ps_list(struct t6041_ps_resolver *r, const char *prop, + bool topo_child_first, + void __iomem ***out_regs, + unsigned int *out_count, + unsigned long **out_mem_mask, + struct t6041_restore_acc *acc) +{ + struct device *dev = r->dev; + struct device_node *np = dev->of_node; + struct device_node **nodes; + void __iomem **regs; + void __iomem **dst; + unsigned long *mem_mask = NULL; + unsigned int *order = NULL; + unsigned int i, uniq = 0; + int count, ret = 0; + + count = of_count_phandle_with_args(np, prop, NULL); + if (count <= 0) + return dev_err_probe(dev, -EINVAL, "%s: missing or empty phandle list\n", prop); + + nodes = kcalloc(count, sizeof(*nodes), GFP_KERNEL); + regs = kcalloc(count, sizeof(*regs), GFP_KERNEL); + if (!nodes || !regs) { + ret = -ENOMEM; + goto out_free; + } + + for (i = 0; i < count; i++) { + struct device_node *ps_np; + void __iomem *reg; + + ps_np = of_parse_phandle(np, prop, i); + if (!ps_np) { + ret = dev_err_probe(dev, -EINVAL, "%s[%u]: unresolved phandle\n", + prop, i); + goto out_put; + } + if (t6041_node_in_list(nodes, uniq, ps_np)) { + of_node_put(ps_np); + continue; + } + reg = t6041_resolve_ps_node(r, ps_np); + if (IS_ERR(reg)) { + of_node_put(ps_np); + ret = dev_err_probe(dev, PTR_ERR(reg), + "%s[%u]: cannot map PS register\n", prop, i); + goto out_put; + } + nodes[uniq] = ps_np; + regs[uniq] = reg; + uniq++; + } + + dst = devm_kcalloc(dev, uniq, sizeof(*dst), GFP_KERNEL); + if (!dst) { + ret = -ENOMEM; + goto out_put; + } + + if (topo_child_first) { + order = kcalloc(uniq, sizeof(*order), GFP_KERNEL); + if (!order) { + ret = -ENOMEM; + goto out_put; + } + ret = t6041_topo_sort(dev, nodes, uniq, order, true); + if (ret) + goto out_put; + for (i = 0; i < uniq; i++) + dst[i] = regs[order[i]]; + } else { + memcpy(dst, regs, uniq * sizeof(*dst)); + } + + if (out_mem_mask) { + mem_mask = devm_bitmap_zalloc(dev, uniq, GFP_KERNEL); + if (!mem_mask) { + ret = -ENOMEM; + goto out_put; + } + for (i = 0; i < uniq; i++) { + struct device_node *entry = topo_child_first ? nodes[order[i]] : nodes[i]; + + if (t6041_ps_is_mem_channel(entry)) + __set_bit(i, mem_mask); + } + } + + for (i = 0; i < uniq; i++) { + if (t6041_node_in_list(acc->exclude, acc->n_exclude, nodes[i])) + continue; + if (t6041_node_in_list(acc->nodes, acc->count, nodes[i])) + continue; + acc->nodes[acc->count] = of_node_get(nodes[i]); + acc->regs[acc->count] = regs[i]; + acc->count++; + } + + *out_regs = dst; + *out_count = uniq; + if (out_mem_mask) + *out_mem_mask = mem_mask; + +out_put: + kfree(order); + for (i = 0; i < uniq; i++) + of_node_put(nodes[i]); +out_free: + kfree(regs); + kfree(nodes); + return ret; +} + +static int t6041_map_ps_domains(struct t6041_sleep *s) +{ + static const char *const sleep_props[] = { + "apple,sleep-off-domains", + "apple,atc-off-domains", + "apple,sleep-auto-domains", + "apple,sleep-auto-clkgate-domains", + "apple,sleep-auto-active-domains", + "apple,sleep-keep-on-domains", + }; + struct device_node *cpu_cpm_nodes[T6041_CPU_COUNT + T6041_CPM_COUNT] = {}; + struct t6041_ps_resolver r = { .dev = s->dev }; + struct t6041_restore_acc acc = { + .exclude = cpu_cpm_nodes, + .n_exclude = ARRAY_SIZE(cpu_cpm_nodes), + }; + struct device *dev = s->dev; + struct device_node *np = dev->of_node; + unsigned int *order = NULL; + unsigned int max_restore = 0; + unsigned int i, cpu; + int ret; + + ret = t6041_parse_ps_fixed(&r, "apple,cpu-domains", s->ps_cpu, + cpu_cpm_nodes, T6041_CPU_COUNT); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,cpm-domains", s->ps_cpm, + cpu_cpm_nodes + T6041_CPU_COUNT, T6041_CPM_COUNT); + if (ret) + goto out; + + for_each_present_cpu(cpu) { + if (t6041_cpu_id(cpu_logical_map(cpu)) >= T6041_CPU_COUNT) { + ret = dev_err_probe(dev, -EINVAL, "CPU %u ID out of range\n", cpu); + goto out; + } + } + + ret = t6041_parse_ps_fixed(&r, "apple,sep-domain", &s->ps_sep, NULL, 1); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,spmi-a0-domain", &s->ps_spmi_a0, NULL, 1); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,atc-common-domains", s->ps_atc_common, + NULL, AXI2AF_ATC_COUNT); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,atc-fabric-domain", &s->ps_atc_fabric, NULL, 1); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,atc-afi-domain", &s->ps_atc_afi, NULL, 1); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,apcie-domains", s->ps_apcie, + NULL, T6041_APCIE_PS_COUNT); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,commit-sio-domains", s->ps_commit_sio, + NULL, T6041_COMMIT_SIO_COUNT); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,commit-periph-domains", s->ps_commit_periph, + NULL, T6041_COMMIT_PERIPH_COUNT); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,axi2af-domains", s->ps_axi2af, + NULL, AXI2AF_COUNT); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,full-part-detect-domains", s->ps_full_detect, + NULL, T6041_FULL_DETECT_COUNT); + if (ret) + goto out; + + for (i = 0; i < ARRAY_SIZE(sleep_props); i++) { + int n = of_count_phandle_with_args(np, sleep_props[i], NULL); + + if (n <= 0) { + ret = dev_err_probe(dev, -EINVAL, + "%s: missing or empty phandle list\n", + sleep_props[i]); + goto out; + } + max_restore += n; + } + + acc.nodes = kcalloc(max_restore, sizeof(*acc.nodes), GFP_KERNEL); + acc.regs = kcalloc(max_restore, sizeof(*acc.regs), GFP_KERNEL); + if (!acc.nodes || !acc.regs) { + ret = -ENOMEM; + goto out; + } + + /* + * Accumulate restore domains fabric- and controller-first before leaf + * and peripheral lists so hardware parents without DT power-domains + * edges (e.g. disabled AMCCs above auto-managed DCS nodes, or fab* + * fabrics above ATC/media blocks) are still ordered parent-first in + * ps_restore. + */ + ret = t6041_parse_ps_list(&r, "apple,sleep-auto-domains", false, + &s->ps_auto, &s->n_auto, &s->ps_auto_mem, &acc); + if (ret) + goto out; + ret = t6041_parse_ps_list(&r, "apple,sleep-auto-active-domains", false, + &s->ps_auto_active, &s->n_auto_active, NULL, &acc); + if (ret) + goto out; + ret = t6041_parse_ps_list(&r, "apple,sleep-auto-clkgate-domains", false, + &s->ps_auto_clkgate, &s->n_auto_clkgate, + &s->ps_auto_clkgate_mem, &acc); + if (ret) + goto out; + ret = t6041_parse_ps_list(&r, "apple,sleep-keep-on-domains", false, + &s->ps_keep_on, &s->n_keep_on, NULL, &acc); + if (ret) + goto out; + ret = t6041_parse_ps_list(&r, "apple,atc-off-domains", false, + &s->ps_atc_off, &s->n_atc_off, NULL, &acc); + if (ret) + goto out; + ret = t6041_parse_ps_list(&r, "apple,sleep-off-domains", true, + &s->ps_off, &s->n_off, NULL, &acc); + if (ret) + goto out; + + order = kcalloc(acc.count, sizeof(*order), GFP_KERNEL); + s->ps_restore = devm_kcalloc(dev, acc.count, sizeof(*s->ps_restore), GFP_KERNEL); + s->ps_pre = devm_kcalloc(dev, acc.count, sizeof(*s->ps_pre), GFP_KERNEL); + if (!order || !s->ps_restore || !s->ps_pre) { + ret = -ENOMEM; + goto out; + } + + ret = t6041_topo_sort(dev, acc.nodes, acc.count, order, false); + if (ret) + goto out; + + for (i = 0; i < acc.count; i++) + s->ps_restore[i] = acc.regs[order[i]]; + s->n_restore = acc.count; + +out: + kfree(order); + for (i = 0; i < acc.count; i++) + of_node_put(acc.nodes[i]); + kfree(acc.regs); + kfree(acc.nodes); + for (i = 0; i < ARRAY_SIZE(cpu_cpm_nodes); i++) + of_node_put(cpu_cpm_nodes[i]); + t6041_ps_resolver_cleanup(&r); + return ret; +} + +static struct apple_tunable *t6041_apcie_tunable(struct device *dev, + struct device_node *np, + const char *reg_name, + const char *prop) +{ + int idx = of_property_match_string(np, "reg-names", reg_name); + struct apple_tunable *t; + struct resource res; + + if (idx < 0 || of_address_to_resource(np, idx, &res)) + return NULL; + t = devm_apple_tunable_parse(dev, np, prop, &res); + return IS_ERR(t) ? NULL : t; +} + +static void __iomem *t6041_apcie_block(struct device *dev, struct device_node *np, + const char *reg_name, resource_size_t min_size, + const char *prop, struct apple_tunable **tunable) +{ + void __iomem *base; + + if (prop) { + *tunable = t6041_apcie_tunable(dev, np, reg_name, prop); + if (!*tunable) + return NULL; + } + base = t6041_map_name(dev, np, reg_name, min_size, NULL); + return IS_ERR(base) ? NULL : base; +} + +static void t6041_map_apcie(struct t6041_sleep *s) +{ + struct device *dev = s->dev; + struct device_node *np; + + np = of_parse_phandle(dev->of_node, "apple,apcie", 0); + if (!np) + return; + + s->ap_rc = t6041_apcie_block(dev, np, "rc", 0x5c, NULL, NULL); + s->ap_axi = t6041_apcie_block(dev, np, "axi2af", 0x110, + "apple,tunable-axi2af", &s->tun_axi2af); + s->ap_cio3pll = t6041_apcie_block(dev, np, "cio3pll", 0x4, + "apple,tunable-cio3pll", &s->tun_cio3pll); + s->ap_clkgen = t6041_apcie_block(dev, np, "clkgen", 0x8, + "apple,tunable-clkgen", &s->tun_clkgen); + s->ap_phy = t6041_apcie_block(dev, np, "phy-block", 0x800c, + "apple,tunable-phy", &s->tun_phy); + s->ap_phy_ip = t6041_apcie_block(dev, np, "phy-ip", 0x94, + "apple,tunable-phy-ip-pll", &s->tun_phy_ip_pll); + s->tun_phy_ip_lanes = t6041_apcie_tunable(dev, np, "phy-ip", + "apple,tunable-phy-ip-auspma"); + s->gp_port[0] = t6041_apcie_block(dev, np, "port0", 0x830, NULL, NULL); + s->gp_port[1] = t6041_apcie_block(dev, np, "port1", 0x830, NULL, NULL); + s->gp_phy[0] = t6041_apcie_block(dev, np, "phy0", 0x4, NULL, NULL); + s->gp_phy[1] = t6041_apcie_block(dev, np, "phy1", 0x4, NULL, NULL); + of_node_put(np); + + if (s->ap_axi) + s->axi2af[AXI2AF_APCIE] = s->ap_axi + 0x100; + + if (s->ap_rc && s->ap_axi && s->ap_cio3pll && s->ap_clkgen && + s->ap_phy && s->ap_phy_ip && s->tun_phy_ip_lanes && + s->gp_port[0] && s->gp_port[1] && s->gp_phy[0] && s->gp_phy[1]) + s->apcie_ready = true; +} + +static int t6041_map_pinctrl(struct t6041_sleep *s) +{ + struct device *dev = s->dev; + struct device_node *np = dev->of_node; + struct device_node *pin_np; + void __iomem *base; + u32 npins, pin; + int i, n; + + pin_np = of_parse_phandle(np, "apple,pinctrl", 0); + if (!pin_np) + return dev_err_probe(dev, -EINVAL, "missing apple,pinctrl\n"); + if (of_property_read_u32(pin_np, "apple,npins", &npins) || !npins || npins > 512) { + of_node_put(pin_np); + return dev_err_probe(dev, -EINVAL, "invalid apple,npins on pinctrl\n"); + } + base = t6041_map_idx(dev, pin_np, 0, (resource_size_t)npins * 4, NULL); + of_node_put(pin_np); + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), "cannot map apple,pinctrl\n"); + + s->gpio_pre = devm_kcalloc(dev, npins, sizeof(*s->gpio_pre), GFP_KERNEL); + s->gpio_skip = devm_bitmap_zalloc(dev, npins, GFP_KERNEL); + if (!s->gpio_pre || !s->gpio_skip) + return -ENOMEM; + + n = of_property_count_u32_elems(np, "apple,pinctrl-skip-pins"); + for (i = 0; i < n; i++) + if (!of_property_read_u32_index(np, "apple,pinctrl-skip-pins", i, &pin) && + pin < npins) + set_bit(pin, s->gpio_skip); + + s->gpio = base; + s->npins = npins; + return 0; +} + +static int t6041_map_spmi(struct t6041_sleep *s) +{ + struct device *dev = s->dev; + struct device_node *np = dev->of_node; + struct device_node *bus_np; + void __iomem *base; + + bus_np = of_parse_phandle(np, "apple,spmi-buses", 0); + if (!bus_np) + return dev_err_probe(dev, -EINVAL, "missing apple,spmi-buses[0]\n"); + base = t6041_map_idx(dev, bus_np, 0, 0x84, NULL); + of_node_put(bus_np); + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), "cannot map apple,spmi-buses[0]\n"); + s->spmi = base; + + bus_np = of_parse_phandle(np, "apple,spmi-buses", 1); + if (!bus_np) + return dev_err_probe(dev, -EINVAL, "missing apple,spmi-buses[1]\n"); + base = t6041_map_idx(dev, bus_np, 0, 0x84, NULL); + of_node_put(bus_np); + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), "cannot map apple,spmi-buses[1]\n"); + s->spmi_a0 = base; + return 0; +} + +static int t6041_map_axi2af(struct t6041_sleep *s) +{ + struct device *dev = s->dev; + struct device_node *np = dev->of_node; + unsigned int i; + + for (i = 0; i < AXI2AF_ATC_COUNT; i++) { + struct device_node *phy_np; + void __iomem *base; + + phy_np = of_parse_phandle(np, "apple,atc-phys", i); + if (!phy_np) + return dev_err_probe(dev, -EINVAL, "missing apple,atc-phys[%u]\n", i); + base = t6041_map_name(dev, phy_np, "axi2af", 0x110, NULL); + of_node_put(phy_np); + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), + "cannot map axi2af on apple,atc-phys[%u]\n", i); + s->axi2af[i] = base + 0x100; + } + + for (i = 0; i < AXI2AF_REG_COUNT; i++) { + void __iomem *base = t6041_map_name(dev, np, t6041_axi2af_names[i], 0xc, NULL); + + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), "cannot map %s\n", + t6041_axi2af_names[i]); + s->axi2af[AXI2AF_ATC_COUNT + i] = base; + } + return 0; +} + +static int t6041_map_mcc(struct t6041_sleep *s) +{ + struct device *dev = s->dev; + struct device_node *np = dev->of_node; + unsigned int g, p; + + for (g = 0; g < s->ngroups; g++) { + char name[16]; + struct resource res; + void __iomem *base; + int idx; + + snprintf(name, sizeof(name), "amcc%u", g); + base = t6041_map_name(dev, np, name, AMCC_MIN_SIZE, NULL); + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), "cannot map %s\n", name); + s->amccb[g] = base; + + snprintf(name, sizeof(name), "dcs%u", g); + idx = of_property_match_string(np, "reg-names", name); + if (idx < 0 || of_address_to_resource(np, idx, &res)) + return dev_err_probe(dev, -EINVAL, "missing %s\n", name); + for (p = 0; p < 4; p++) { + resource_size_t off = (resource_size_t)p * DCS_CH_STRIDE; + + if (off + DCS_CH_SIZE > resource_size(&res)) + return dev_err_probe(dev, -EINVAL, "%s too small\n", name); + s->dcs[4 * g + p] = devm_ioremap(dev, res.start + off, DCS_CH_SIZE); + if (!s->dcs[4 * g + p]) + return -ENOMEM; + } + } + return 0; +} + +static int t6041_parse_wake_sources(struct t6041_sleep *s) +{ + struct device *dev = s->dev; + u32 ids[WAKE_SOURCES_MAX]; + int i, n; + + n = of_property_read_variable_u32_array(dev->of_node, "apple,wake-enable", + ids, 1, WAKE_SOURCES_MAX); + if (n < 0) + return dev_err_probe(dev, n, "missing apple,wake-enable\n"); + + for (i = 0; i < WAKE_WORDS - 1; i++) + s->wake_masks[i] = U32_MAX; + s->wake_masks[WAKE_WORDS - 1] = WAKE_LAST_MASK; + + for (i = 0; i < n; i++) { + if (ids[i] >= WAKE_MAX_ID) + return dev_err_probe(dev, -EINVAL, + "wake source %u out of range\n", ids[i]); + s->wake_masks[ids[i] / 32] &= ~BIT(ids[i] % 32); + } + return 0; +} + +static const struct { + const char *name; + size_t field; + resource_size_t min_size; +} t6041_core_regs[] = { + { "ps-aop", offsetof(struct t6041_sleep, aop_ps), 8 * AOP_PS_WORDS }, + { "cluster", offsetof(struct t6041_sleep, cluster), 0x14 }, + { "pwrgate", offsetof(struct t6041_sleep, pwrgate), 0x114 }, + { "cpu-start", offsetof(struct t6041_sleep, misc), 0x14 }, + { "wdt", offsetof(struct t6041_sleep, wdt), 0x30 }, + { "aon-misc", offsetof(struct t6041_sleep, aon), 0xc }, + { "commit", offsetof(struct t6041_sleep, commit), 0x4 }, + { "clk-mux", offsetof(struct t6041_sleep, clkgen), 0x68 }, + { "ka-pmgr", offsetof(struct t6041_sleep, ka[0]), KA_WORDS * KA_STRIDE }, + { "ka-east", offsetof(struct t6041_sleep, ka[1]), KA_WORDS * KA_STRIDE }, + { "pmc", offsetof(struct t6041_sleep, pmc), 0xac02c }, + { "ptd", offsetof(struct t6041_sleep, ptd), PTD_MIN_SIZE }, + { "perf", offsetof(struct t6041_sleep, perf), 0x404 }, + { "wake", offsetof(struct t6041_sleep, wake), 0xc + 4 * WAKE_WORDS }, +}; + +static int t6041_sleep_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct device_node *np = dev->of_node; + struct t6041_sleep *s; + unsigned int i; + u64 pa; + int ret; + + if (!is_kernel_in_hyp_mode()) + return -ENODEV; + + s = devm_kzalloc(dev, sizeof(*s), GFP_KERNEL); + if (!s) + return -ENOMEM; + s->dev = dev; + + if (!of_property_read_u64(of_chosen, "aurora,s2r-mailbox", &pa)) { + s->mbox = devm_memremap(dev, pa, sizeof(*s->mbox), MEMREMAP_WB); + if (IS_ERR(s->mbox) || READ_ONCE(s->mbox->magic) != T6041_S2R_MAGIC) + s->mbox = NULL; + } + /* With no way back, a sleep would end in aura's boot flow over this kernel. */ + if (!s->mbox) { + dev_info(dev, "no aura S2R mailbox: no deep sleep\n"); + return -ENODEV; + } + + for (i = 0; i < ARRAY_SIZE(t6041_core_regs); i++) { + void __iomem *base = t6041_map_name(dev, np, t6041_core_regs[i].name, + t6041_core_regs[i].min_size, NULL); + + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), "cannot map %s\n", + t6041_core_regs[i].name); + *(void __iomem **)((char *)s + t6041_core_regs[i].field) = base; + } + + ret = t6041_map_ps_domains(s); + if (ret) + return ret; + ret = t6041_parse_wake_sources(s); + if (ret) + return ret; + ret = t6041_map_spmi(s); + if (ret) + return ret; + ret = t6041_map_axi2af(s); + if (ret) + return ret; + ret = t6041_map_pinctrl(s); + if (ret) + return ret; + + /* + * The full part: the two full-part detect words (amcc24, amcc28) are + * not both target and actual 0 as on the binned part, where those + * channels are fused off. + */ + s->ngroups = (readl(s->ps_full_detect[0]) & (PS_TARGET | PS_ACTUAL)) && + (readl(s->ps_full_detect[1]) & (PS_TARGET | PS_ACTUAL)) ? 8 : 6; + dev_info(dev, "%u memory channels\n", 4 * s->ngroups); + + ret = t6041_map_mcc(s); + if (ret) + return ret; + + t6041_map_apcie(s); + if (!s->apcie_ready) { + dev_info(dev, "no PCIe tunables for ANS: no deep sleep\n"); + return -ENODEV; + } + + t6041_sleep = s; + ret = spin_table_set_power_ops(&t6041_cpu_power_ops); + if (ret) { + t6041_sleep = NULL; + return dev_err_probe(dev, ret, "cannot control CPU power\n"); + } + apple_sleep_set_commit_stops_coprocs(true); + suspend_set_ops(&t6041_sleep_ops); + dev_info(dev, "T6041 deep sleep at EL2 through aura's S2R mailbox\n"); + return 0; +} + +static const struct of_device_id t6041_sleep_of_match[] = { + { .compatible = "apple,t6041-sleep" }, + { } +}; + +static struct platform_driver t6041_sleep_driver = { + .driver = { + .name = "t6041-sleep", + .of_match_table = t6041_sleep_of_match, + .suppress_bind_attrs = true, + }, + .probe = t6041_sleep_probe, +}; +builtin_platform_driver(t6041_sleep_driver); diff --git a/drivers/soc/apple/t6050-aop-test.c b/drivers/soc/apple/t6050-aop-test.c new file mode 100644 index 00000000000000..9e7d77dec28b58 --- /dev/null +++ b/drivers/soc/apple/t6050-aop-test.c @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by t6050-aop.c: an endpoint's buffer is the firmware's first GETBUF's, for as long as + * the firmware runs; a later GETBUF that fits in it gets it again. + */ +#include + +static void t6050_aop_test_first_getbuf_allocates(struct kunit *test) +{ + struct t6050_aop_ring r = {}; + + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_claim(&r, 0x4000), 0); + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_claim(&r, 0xffffUL << AFK_BLOCK_SHIFT), 0); +} + +static void t6050_aop_test_empty_getbuf_refused(struct kunit *test) +{ + static u8 mem[0x100]; + struct t6050_aop_ring r = {}; + + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_claim(&r, 0), 0); + r.buf = mem; + r.size = sizeof(mem); + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_claim(&r, 0), 0); +} + +static void t6050_aop_test_repeat_getbuf_reuses(struct kunit *test) +{ + static u8 mem[0x100]; + struct t6050_aop_ring r = { .buf = mem, .size = sizeof(mem), .iova = 0x1000 }; + int i; + + for (i = 0; i < 64; i++) + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_claim(&r, sizeof(mem)), 1); +} + +static void t6050_aop_test_smaller_getbuf_reuses(struct kunit *test) +{ + static u8 mem[0x100]; + struct t6050_aop_ring r = { .buf = mem, .size = sizeof(mem), .iova = 0x1000 }; + + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_claim(&r, sizeof(mem) / 2), 1); + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_claim(&r, 1), 1); +} + +static void t6050_aop_test_reused_getbuf_restarts_rings(struct kunit *test) +{ + static __le32 mem[0x400 / 4]; + struct t6050_aop_ring r = { .buf = mem, .size = sizeof(mem), .iova = 0x1000 }; + struct t6050_aop_view v; + u32 bufsz = 2 * AFK_QE_SLOT; + + mem[0] = cpu_to_le32(bufsz); + r.tx_off = 0; + r.tx_size = bufsz + 3 * 0x40; + r.tx_ready = true; + r.rx_off = 0; + r.rx_size = r.tx_size; + r.rx_ready = true; + r.seq = 5; + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, r.tx_off, r.tx_size, r.tx_ready, &v), 0); + + /* The firmware asks again: no ring until it announces them again. */ + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_claim(&r, sizeof(mem)), 1); + KUNIT_EXPECT_FALSE(test, r.tx_ready); + KUNIT_EXPECT_FALSE(test, r.rx_ready); + KUNIT_EXPECT_EQ(test, r.seq, 0); + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, r.tx_off, r.tx_size, r.tx_ready, &v), -EINVAL); + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, r.rx_off, r.rx_size, r.rx_ready, &v), -EINVAL); +} + +static void t6050_aop_test_refused_getbuf_keeps_rings(struct kunit *test) +{ + static u8 mem[0x100]; + struct t6050_aop_ring r = { .buf = mem, .size = sizeof(mem), .iova = 0x1000, + .tx_ready = true, .rx_ready = true, .seq = 5 }; + + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_claim(&r, sizeof(mem) + 1), 0); + KUNIT_EXPECT_TRUE(test, r.tx_ready); + KUNIT_EXPECT_TRUE(test, r.rx_ready); + KUNIT_EXPECT_EQ(test, r.seq, 5); +} + +static void t6050_aop_test_larger_getbuf_refused(struct kunit *test) +{ + static u8 mem[0x100]; + struct t6050_aop_ring r = { .buf = mem, .size = sizeof(mem), .iova = 0x1000 }; + + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_claim(&r, sizeof(mem) + 1), 0); + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_claim(&r, sizeof(mem) * 2), 0); + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_claim(&r, 0xffffUL << AFK_BLOCK_SHIFT), 0); +} + +static void t6050_aop_test_view_inside_buffer(struct kunit *test) +{ + static __le32 mem[0x400 / 4]; + struct t6050_aop_ring r = {}; + struct t6050_aop_view v; + u32 bufsz = 2 * AFK_QE_SLOT; + u32 size = bufsz + 3 * 0x40; + + mem[0] = cpu_to_le32(bufsz); + /* No buffer yet. */ + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, 0, size, true, &v), -EINVAL); + r.buf = mem; + r.size = sizeof(mem); + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, 0, size, true, &v), 0); + KUNIT_EXPECT_PTR_EQ(test, (void *)v.hdr, (void *)mem); + /* A ring that does not fit the buffer. */ + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, 0x400 - 0x40, size, true, &v), -EINVAL); + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, 0x440, 0x40, true, &v), -EINVAL); +} + +static struct kunit_case t6050_aop_test_cases[] = { + KUNIT_CASE(t6050_aop_test_first_getbuf_allocates), + KUNIT_CASE(t6050_aop_test_empty_getbuf_refused), + KUNIT_CASE(t6050_aop_test_repeat_getbuf_reuses), + KUNIT_CASE(t6050_aop_test_smaller_getbuf_reuses), + KUNIT_CASE(t6050_aop_test_larger_getbuf_refused), + KUNIT_CASE(t6050_aop_test_reused_getbuf_restarts_rings), + KUNIT_CASE(t6050_aop_test_refused_getbuf_keeps_rings), + KUNIT_CASE(t6050_aop_test_view_inside_buffer), + {} +}; + +static struct kunit_suite t6050_aop_test_suite = { + .name = "apple_t6050_aop", + .test_cases = t6050_aop_test_cases, +}; + +kunit_test_suite(t6050_aop_test_suite); diff --git a/drivers/soc/apple/t6050-aop.c b/drivers/soc/apple/t6050-aop.c index d7115b8c2c2f90..df00818ac506e5 100644 --- a/drivers/soc/apple/t6050-aop.c +++ b/drivers/soc/apple/t6050-aop.c @@ -77,8 +77,10 @@ #define AOP_EP_COUNT (AOP_EP_LAST - AOP_EP_FIRST + 1) struct t6050_aop_ring { + /* Set once, by the firmware's first GETBUF; published after its size and IOVA */ void *buf; size_t size; + dma_addr_t iova; u32 tx_off, tx_size; u32 rx_off, rx_size; bool tx_ready, rx_ready; @@ -139,21 +141,61 @@ static void t6050_aop_send(struct t6050_aop *aop, u8 ep, u64 msg) dev_err(aop->dev, "endpoint %#x: send %#llx: %d\n", ep, msg, ret); } +/* + * What a GETBUF gets: 0 a new buffer, 1 the endpoint's own again, as it fits in it, or -EINVAL for + * no size or more than the endpoint's buffer holds. An endpoint has one buffer for as long as the + * firmware runs: its rings are read from it at a sleep and a wake, by other threads. + * + * A GETBUF that is answered starts the endpoint's rings over: they are announced again after it, + * so the endpoint has none, and sends nothing, until then. + */ +static int t6050_aop_getbuf_claim(struct t6050_aop_ring *r, size_t size) +{ + int ret; + + if (!size) + return -EINVAL; + ret = !r->buf ? 0 : size <= r->size ? 1 : -EINVAL; + if (ret < 0) + return ret; + + WRITE_ONCE(r->tx_ready, false); + WRITE_ONCE(r->rx_ready, false); + r->seq = 0; + r->tx_rptr = 0; + r->tx_wptr = 0; + return ret; +} + static void t6050_aop_getbuf(struct t6050_aop *aop, u8 ep, u64 msg) { + struct t6050_aop_ring *r = &aop->ring[ep - AOP_EP_FIRST]; size_t size = (size_t)FIELD_GET(AFK_GETBUF_SIZE, msg) << AFK_BLOCK_SHIFT; - dma_addr_t iova; void *buf; + int ret; - buf = dmam_alloc_coherent(aop->dev, size, &iova, GFP_KERNEL); - if (!buf) { - dev_err(aop->dev, "endpoint %#x: no %#zx byte buffer\n", ep, size); + /* Only this endpoint's messages, in order, change its buffer. */ + ret = t6050_aop_getbuf_claim(r, size); + if (ret < 0) { + dev_err_ratelimited(aop->dev, "endpoint %#x: no buffer for a %#zx byte GETBUF (has %#zx)\n", + ep, size, r->buf ? r->size : 0); return; } - aop->ring[ep - AOP_EP_FIRST].buf = buf; - aop->ring[ep - AOP_EP_FIRST].size = size; + /* Open again once its rings start (AFK_START_ACK). */ + clear_bit(ep - AOP_EP_FIRST, &aop->opened); + if (!ret) { + buf = dmam_alloc_coherent(aop->dev, size, &r->iova, GFP_KERNEL); + if (!buf) { + dev_err_ratelimited(aop->dev, "endpoint %#x: no %#zx byte buffer\n", + ep, size); + return; + } + r->size = size; + /* A reader that finds the buffer finds its size. */ + smp_store_release(&r->buf, buf); + } t6050_aop_send(aop, ep, FIELD_PREP(AFK_TYPE, AFK_GETBUF_ACK) | - FIELD_PREP(AFK_GETBUF_IOVA, iova)); + FIELD_PREP(AFK_GETBUF_IOVA, r->iova)); } static int t6050_aop2_take(struct t6050_aop *aop, u8 ep, u32 old, u32 new); @@ -178,15 +220,17 @@ static void t6050_aop_recv(void *cookie, u8 ep, u64 msg) case AFK_INIT_TX: r->tx_off = FIELD_GET(AFK_RING_OFFSET, msg) << AFK_BLOCK_SHIFT; r->tx_size = FIELD_GET(AFK_RING_SIZE, msg) << AFK_BLOCK_SHIFT; - r->tx_ready = true; + WRITE_ONCE(r->tx_ready, true); break; case AFK_INIT_RX: r->rx_off = FIELD_GET(AFK_RING_OFFSET, msg) << AFK_BLOCK_SHIFT; r->rx_size = FIELD_GET(AFK_RING_SIZE, msg) << AFK_BLOCK_SHIFT; - r->rx_ready = true; + WRITE_ONCE(r->rx_ready, true); t6050_aop_send(aop, ep, FIELD_PREP(AFK_TYPE, AFK_START)); break; case AFK_START_ACK: + /* Started again from a GETBUF: no sleep element of the last setup is pending. */ + r->closed = false; set_bit(ep - AOP_EP_FIRST, &aop->opened); break; case AFK_RING: @@ -221,9 +265,12 @@ static const struct apple_rtkit_ops t6050_aop2_rtkit_ops = { static int t6050_aop2_view(struct t6050_aop_ring *r, u32 off, u32 size, bool ready, struct t6050_aop_view *v) { - if (!ready || !r->buf || size < sizeof(__le32) || off > r->size || size > r->size - off) + /* Pairs with t6050_aop_getbuf(): a buffer found here comes with its size. */ + u8 *buf = smp_load_acquire(&r->buf); + + if (!ready || !buf || size < sizeof(__le32) || off > r->size || size > r->size - off) return -EINVAL; - v->hdr = (u8 *)r->buf + off; + v->hdr = buf + off; v->bufsz = le32_to_cpu(READ_ONCE(*(__le32 *)v->hdr)); if (v->bufsz >= size || (size - v->bufsz) % 3 || v->bufsz < 2 * AFK_QE_SLOT || v->bufsz > AFK_RING_MAX) @@ -259,7 +306,7 @@ static int t6050_aop2_put(struct t6050_aop *aop, u8 ep, const u32 *msg, unsigned __le32 *qe; int ret; - ret = t6050_aop2_view(r, r->tx_off, r->tx_size, r->tx_ready, &v); + ret = t6050_aop2_view(r, r->tx_off, r->tx_size, READ_ONCE(r->tx_ready), &v); if (ret) return ret; dma_rmb(); @@ -316,7 +363,7 @@ static int t6050_aop2_rx_wptr(struct t6050_aop *aop, u8 ep) struct t6050_aop_view v; u32 wptr; - if (t6050_aop2_view(r, r->rx_off, r->rx_size, r->rx_ready, &v)) + if (t6050_aop2_view(r, r->rx_off, r->rx_size, READ_ONCE(r->rx_ready), &v)) return -EINVAL; dma_rmb(); wptr = t6050_aop2_ptr(&v, AFK_PTR_WRITE); @@ -351,8 +398,8 @@ static int t6050_aop2_take(struct t6050_aop *aop, u8 ep, u32 old, u32 new) struct t6050_aop_view v; int code; - if (t6050_aop2_view(r, r->rx_off, r->rx_size, r->rx_ready, &v) || old >= v.bufsz || - new >= v.bufsz) + if (t6050_aop2_view(r, r->rx_off, r->rx_size, READ_ONCE(r->rx_ready), &v) || + old >= v.bufsz || new >= v.bufsz) return -EINVAL; if (old == new) return -ENOMSG; @@ -746,3 +793,7 @@ static struct platform_driver t6050_aop_driver = { .probe = t6050_aop_probe, }; builtin_platform_driver(t6050_aop_driver); + +#if IS_ENABLED(CONFIG_APPLE_T6050_AOP_KUNIT_TEST) +#include "t6050-aop-test.c" +#endif diff --git a/drivers/soc/apple/t6050-aop.kunitconfig b/drivers/soc/apple/t6050-aop.kunitconfig new file mode 100644 index 00000000000000..e4da56c59ad8ef --- /dev/null +++ b/drivers/soc/apple/t6050-aop.kunitconfig @@ -0,0 +1,10 @@ +CONFIG_KUNIT=y +CONFIG_COMPILE_TEST=y +CONFIG_OF=y +CONFIG_PM=y +CONFIG_SUSPEND=y +CONFIG_HOTPLUG_CPU=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_APPLE_SOC_SLEEP=y +CONFIG_APPLE_T6050_AOP_KUNIT_TEST=y diff --git a/drivers/soc/apple/t8122-gate-test.dtso b/drivers/soc/apple/t8122-gate-test.dtso index beee48ab0afd9d..850f3cebb4a23e 100644 --- a/drivers/soc/apple/t8122-gate-test.dtso +++ b/drivers/soc/apple/t8122-gate-test.dtso @@ -4,7 +4,10 @@ * nodes of t8122-dcp.dtsi with the boot loader's handoff applied, the power * states they hang from, the PMP topology of t8122.dtsi that the gate * reuses, and PMP values. The values are made up: only their presence and - * the PMP image UUID matter to the gate. + * the PMP image UUID matter to the gate. The external display processor + * (dcpext) of t8122-dcp.dtsi is there too, with its DARTs' 14.7 windows, + * but without the boot loader's firmware-ready mark: the cases that start + * it add the mark and its firmware versions. * * The nodes live under their own disabled bus, not /soc, so that they do * not collide with the T6030 test tree (both SoCs put the DCP at @@ -88,6 +91,14 @@ apple,min-state = <4>; apple,inherited-on; }; + + t8122_ps_dispext_cpu: power-controller@488 { + compatible = "apple,t8122-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x488 4>; + #power-domain-cells = <0>; + label = "dispext_cpu"; + apple,min-state = <4>; + }; }; t8122_pmp_dart: iommu@2d0300000 { @@ -117,7 +128,7 @@ apple,always-on; }; - report@8 { + t8122_report_dispext: report@8 { compatible = "apple,t8122-pmp-v2-report-entry", "apple,t6000-pmp-v2-report-entry"; reg = <0x8>; @@ -176,6 +187,7 @@ interrupts = <0 750 4>; #iommu-cells = <1>; power-domains = <&t8122_ps_disp_cpu>; + apple,dma-range = <0x100 0x0 0x10 0x0>; status = "disabled"; }; @@ -186,6 +198,7 @@ interrupts = <0 750 4>; #iommu-cells = <1>; power-domains = <&t8122_ps_disp_cpu>; + apple,dma-range = <0x100 0x0 0x10 0x0>; status = "disabled"; }; @@ -209,6 +222,66 @@ }; }; + t8122_dispext0_dart: iommu@319304000 { + compatible = "apple,t8122-dart", "apple,t8110-dart"; + reg = <0x3 0x19304000 0x0 0x4000>; + interrupt-parent = <&t8122_aic>; + interrupts = <0 599 4>; + #iommu-cells = <1>; + apple,dma-range = <0x0 0x0 0xf 0xffff0000>; + power-domains = <&t8122_ps_dispext_cpu>; + status = "disabled"; + }; + + t8122_dcpext_dart: iommu@31930c000 { + compatible = "apple,t8122-dart", "apple,t8110-dart"; + reg = <0x3 0x1930c000 0x0 0x4000>; + interrupt-parent = <&t8122_aic>; + interrupts = <0 599 4>; + #iommu-cells = <1>; + apple,dma-range = <0x8 0x0 0x7 0xffff0000>; + power-domains = <&t8122_ps_dispext_cpu>; + status = "disabled"; + }; + + t8122_dcpext_mbox: mailbox@31ac08000 { + compatible = "apple,t8122-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x3 0x1ac08000 0x0 0x4000>; + interrupt-parent = <&t8122_aic>; + interrupts = <0 582 4>, <0 583 4>, <0 584 4>, <0 585 4>; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + power-domains = <&t8122_ps_dispext_cpu>; + status = "disabled"; + }; + + /* Stands in for the boot loader's firmware reservations. */ + t8122_dcpext_mem: dcpext-firmware { + }; + + dcp@31ac00000 { + compatible = "apple,t8122-dcpext", "apple,dcpext"; + mboxes = <&t8122_dcpext_mbox>; + mbox-names = "mbox"; + iommus = <&t8122_dcpext_dart 5>; + reg-names = "coproc"; + reg = <0x3 0x1ac00000 0x0 0x4000>; + power-domains = <&t8122_ps_dispext_cpu>; + apple,pmp-report = <&t8122_report_dispext>; + memory-region = <&t8122_dcpext_mem>; + status = "disabled"; + + piodma { + iommus = <&t8122_dispext0_dart 4>; + }; + + fbdma { + iommus = <&t8122_dispext0_dart 0>; + apple,dma-range = /bits/ 64 <0x10000000000 0x1000000000>; + }; + }; + display-subsystem { compatible = "apple,t8122-display-subsystem"; iommus = <&t8122_disp0_dart 0>; diff --git a/drivers/soc/apple/t8132-platform-data.dts b/drivers/soc/apple/t8132-platform-data.dts index 2f5e783a179cbd..06be8ecd1bb873 100644 --- a/drivers/soc/apple/t8132-platform-data.dts +++ b/drivers/soc/apple/t8132-platform-data.dts @@ -95,3 +95,11 @@ &ps_gfx { status = "okay"; }; + +&ps_sio_cpu { + status = "okay"; +}; + +&ps_dpa_p { + status = "okay"; +}; diff --git a/drivers/soc/apple/t8132-platform-handoff.c b/drivers/soc/apple/t8132-platform-handoff.c index c25a95d198d446..5a959c270477a3 100644 --- a/drivers/soc/apple/t8132-platform-handoff.c +++ b/drivers/soc/apple/t8132-platform-handoff.c @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* Supply missing platform descriptions for the original J713 loader ABI, - * which the J715 shares, and the M4 PMGR ownership policy on the qualified - * firmware for every M4 Mac. + * which the J715 shares, and apply the M4 PMGR ownership policy wherever + * the T8132 PMGR is described. * Keep the shared m1n1 payload usable by the stable kernel. Hardware control * remains in the ordinary MCC, PMC and CLPC drivers, with one DTS data source. * J713 PMGR ownership/status also comes from its board DTS, before any domain @@ -314,18 +314,33 @@ static struct device_node *__init t8132_find_gfx(void) static int __init t8132_platform_handoff(void) { const void *data = __dtb_t8132_platform_data_begin; - struct device_node *soc, *pmp = NULL, *gpu = NULL, *gfx = NULL; + struct device_node *soc = NULL, *pmp = NULL, *gpu = NULL, *gfx = NULL; struct of_changeset *cs; unsigned int added = 0, changed = 0; int root, node, ret; - if (!apple_t8132_firmware_path()) - return 0; - if (fdt_check_header(data)) - return -EINVAL; + /* + * The memory descriptions follow the PMP provider. PMGR ownership + * also applies to trees which describe the PMGR without a PMP. + */ + pmp = of_find_compatible_node(NULL, NULL, "apple,t8132-pmp-v2"); + if (!pmp) { + struct device_node *pmgr; + + pmgr = of_find_compatible_node(NULL, NULL, "apple,t8132-pmgr"); + if (!pmgr) + return 0; + of_node_put(pmgr); + } + if (fdt_check_header(data)) { + ret = -EINVAL; + goto out; + } soc = of_find_node_by_path("/soc"); - if (!soc) - return -ENODEV; + if (!soc) { + ret = -ENODEV; + goto out; + } cs = kzalloc_obj(*cs); if (!cs) { ret = -ENOMEM; @@ -336,12 +351,14 @@ static int __init t8132_platform_handoff(void) if (ret) goto destroy; - pmp = of_find_compatible_node(NULL, NULL, "apple,t8132-pmp-v2"); + if (!pmp) + goto apply; + gpu = of_find_compatible_node(NULL, NULL, "apple,agx-t8132"); gfx = gpu ? of_parse_phandle(gpu, "power-domains", 0) : NULL; if (!gfx) gfx = t8132_find_gfx(); - if (!pmp || !gfx || !pmp->phandle || !gfx->phandle) { + if (!gfx || !pmp->phandle || !gfx->phandle) { pr_warn("t8132-platform-handoff: memory compatibility requires PMP/GFX providers\n"); goto apply; } diff --git a/drivers/soc/apple/tunable-test.c b/drivers/soc/apple/tunable-test.c new file mode 100644 index 00000000000000..7fa59a771e39e4 --- /dev/null +++ b/drivers/soc/apple/tunable-test.c @@ -0,0 +1,372 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple Silicon hardware tunable library. + * + * The property a boot stage would pass comes from a device node built by + * the test, and the registers the tunable is applied to are a buffer of + * kernel memory. No device tree of the machine and no MMIO is touched. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#define TUNABLE_TEST_PROP "apple,tunable-test" +#define TUNABLE_TEST_NREGS 8 + +struct tunable_test { + struct device *dev; + struct device_node np; + struct property prop; + __le32 regs[TUNABLE_TEST_NREGS]; +}; + +static int tunable_test_init(struct kunit *test) +{ + struct tunable_test *t; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t); + t->dev = kunit_device_register(test, "tunable-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t->dev); + test->priv = t; + + return 0; +} + +/* Parse a property of len bytes holding the cells, for res_size bytes at start */ +static struct apple_tunable *tunable_test_parse_at(struct kunit *test, const u32 *cells, + size_t len, resource_size_t start, + resource_size_t res_size) +{ + struct tunable_test *t = test->priv; + struct resource res = DEFINE_RES_MEM(start, res_size); + __be32 *value; + size_t i; + + value = kunit_kzalloc(test, round_up(len, 4) + 4, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, value); + for (i = 0; i < DIV_ROUND_UP(len, 4); i++) + value[i] = cpu_to_be32(cells[i]); + + t->prop.name = (char *)TUNABLE_TEST_PROP; + t->prop.value = value; + t->prop.length = len; + t->np.properties = &t->prop; + + return devm_apple_tunable_parse(t->dev, &t->np, TUNABLE_TEST_PROP, &res); +} + +static struct apple_tunable *tunable_test_parse(struct kunit *test, const u32 *cells, + size_t len, resource_size_t res_size) +{ + return tunable_test_parse_at(test, cells, len, 0x2a0000000ULL, res_size); +} + +static u32 tunable_test_rd(struct tunable_test *t, unsigned int reg) +{ + return le32_to_cpu(t->regs[reg / 4]); +} + +static void tunable_test_apply(struct tunable_test *t, struct apple_tunable *tunable) +{ + apple_tunable_apply((void __iomem __force *)t->regs, tunable); +} + +/* Each [offset, mask, value] triplet of big-endian cells becomes one entry */ +static void tunable_test_parse_triplets(struct kunit *test) +{ + static const u32 cells[] = { + 0x00, 0x000000ff, 0x00000012, + 0x1c, 0xffff0000, 0xabcd0000, + 0x04, 0x80000001, 0x80000000, + }; + struct apple_tunable *tunable; + + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + KUNIT_ASSERT_EQ(test, tunable->sz, 3); + KUNIT_EXPECT_EQ(test, tunable->values[0].offset, 0x00); + KUNIT_EXPECT_EQ(test, tunable->values[0].mask, 0x000000ff); + KUNIT_EXPECT_EQ(test, tunable->values[0].value, 0x00000012); + KUNIT_EXPECT_EQ(test, tunable->values[1].offset, 0x1c); + KUNIT_EXPECT_EQ(test, tunable->values[1].mask, 0xffff0000); + KUNIT_EXPECT_EQ(test, tunable->values[1].value, 0xabcd0000); + KUNIT_EXPECT_EQ(test, tunable->values[2].offset, 0x04); + KUNIT_EXPECT_EQ(test, tunable->values[2].mask, 0x80000001); + KUNIT_EXPECT_EQ(test, tunable->values[2].value, 0x80000000); +} + +static void tunable_test_parse_missing(struct kunit *test) +{ + static const u32 cells[] = { 0x00, 0xff, 0x12 }; + struct tunable_test *t = test->priv; + struct resource res = DEFINE_RES_MEM(0x2a0000000ULL, 0x20); + struct apple_tunable *tunable; + + /* A node without properties */ + tunable = devm_apple_tunable_parse(t->dev, &t->np, TUNABLE_TEST_PROP, &res); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -ENOENT); + + /* A node with another one */ + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + tunable = devm_apple_tunable_parse(t->dev, &t->np, "apple,tunable-other", &res); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -ENOENT); +} + +/* A property that is not whole triplets is refused */ +static void tunable_test_parse_bad_length(struct kunit *test) +{ + static const u32 cells[] = { 0x00, 0xff, 0x12, 0x04, 0xff, 0x34 }; + static const size_t bad[] = { 1, 4, 8, 11, 13, 16, 20, 23 }; + struct apple_tunable *tunable; + int i; + + for (i = 0; i < ARRAY_SIZE(bad); i++) { + tunable = tunable_test_parse(test, cells, bad[i], 0x20); + KUNIT_EXPECT_EQ_MSG(test, PTR_ERR_OR_ZERO(tunable), -EINVAL, + "length %zu", bad[i]); + } + + tunable = tunable_test_parse(test, cells, 12, 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + KUNIT_EXPECT_EQ(test, tunable->sz, 1); + tunable = tunable_test_parse(test, cells, 24, 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + KUNIT_EXPECT_EQ(test, tunable->sz, 2); +} + +/* An empty property is a tunable with nothing to apply */ +static void tunable_test_parse_empty(struct kunit *test) +{ + static const u32 cells[] = { 0 }; + struct tunable_test *t = test->priv; + struct apple_tunable *tunable; + + tunable = tunable_test_parse(test, cells, 0, 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + KUNIT_EXPECT_EQ(test, tunable->sz, 0); + + t->regs[0] = cpu_to_le32(0x12345678); + tunable_test_apply(t, tunable); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0), 0x12345678); +} + +/* A resource without room for one register takes no tunable */ +static void tunable_test_parse_small_resource(struct kunit *test) +{ + static const u32 cells[] = { 0x00, 0xff, 0x12 }; + struct apple_tunable *tunable; + resource_size_t size; + + for (size = 0; size < 4; size++) { + tunable = tunable_test_parse(test, cells, sizeof(cells), size); + KUNIT_EXPECT_EQ_MSG(test, PTR_ERR_OR_ZERO(tunable), -EINVAL, + "resource of %llu bytes", (u64)size); + /* Not even an empty one */ + tunable = tunable_test_parse(test, cells, 0, size); + KUNIT_EXPECT_EQ_MSG(test, PTR_ERR_OR_ZERO(tunable), -EINVAL, + "resource of %llu bytes", (u64)size); + } + + tunable = tunable_test_parse(test, cells, sizeof(cells), 4); + KUNIT_EXPECT_FALSE(test, IS_ERR(tunable)); +} + +/* Registers are 32 bits wide: an offset between two of them is refused */ +static void tunable_test_parse_unaligned_offset(struct kunit *test) +{ + u32 cells[] = { + 0x00, 0xff, 0x12, + 0x00, 0xff, 0x34, + }; + struct apple_tunable *tunable; + u32 off; + + for (off = 1; off < 8; off++) { + if (off == 4) + continue; + /* In the first triplet, then in the last */ + cells[0] = off; + cells[3] = 0; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_EQ_MSG(test, PTR_ERR_OR_ZERO(tunable), -EINVAL, + "offset %u", off); + cells[0] = 0; + cells[3] = off; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_EQ_MSG(test, PTR_ERR_OR_ZERO(tunable), -EINVAL, + "offset %u", off); + } +} + +/* The last register of the resource is the last offset taken */ +static void tunable_test_parse_offset_bounds(struct kunit *test) +{ + u32 cells[] = { + 0x00, 0xff, 0x12, + 0x00, 0xff, 0x34, + }; + struct apple_tunable *tunable; + + cells[3] = 0x1c; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_FALSE(test, IS_ERR(tunable)); + + cells[3] = 0x20; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); + + cells[3] = 0x24; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); + + cells[3] = 0xfffffffc; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); + + /* In the first triplet too */ + cells[0] = 0x20; + cells[3] = 0; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); + cells[0] = 0; + + /* A register that only starts inside the resource is outside */ + cells[3] = 0x1c; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x1f); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); + cells[3] = 0x18; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x1f); + KUNIT_EXPECT_FALSE(test, IS_ERR(tunable)); + + /* One register */ + cells[3] = 0x04; + tunable = tunable_test_parse(test, cells, sizeof(cells), 4); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); +} + +/* Offsets count from the start of the resource, wherever that is */ +static void tunable_test_parse_resource_start(struct kunit *test) +{ + static const u32 cells[] = { 0x1c, 0xff, 0x12 }; + struct apple_tunable *tunable; + + tunable = tunable_test_parse_at(test, cells, sizeof(cells), 0, 0x20); + KUNIT_EXPECT_FALSE(test, IS_ERR(tunable)); + tunable = tunable_test_parse_at(test, cells, sizeof(cells), 0x10, 0x20); + KUNIT_EXPECT_FALSE(test, IS_ERR(tunable)); + tunable = tunable_test_parse_at(test, cells, sizeof(cells), 0x10, 0x1c); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); +} + +/* Applying clears the mask's bits and sets the value's, elsewhere nothing */ +static void tunable_test_apply_mask_value(struct kunit *test) +{ + static const u32 cells[] = { + 0x04, 0x00ff00ff, 0x00120034, + 0x1c, 0xffffffff, 0xdeadbeef, + 0x0c, 0x00000000, 0x00000000, + 0x10, 0xf0000000, 0x00000000, + }; + struct tunable_test *t = test->priv; + struct apple_tunable *tunable; + int i; + + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + + for (i = 0; i < TUNABLE_TEST_NREGS; i++) + t->regs[i] = cpu_to_le32(0xa5a5a500 + i); + tunable_test_apply(t, tunable); + + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x00), 0xa5a5a500); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x04), 0xa512a534); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x08), 0xa5a5a502); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x0c), 0xa5a5a503); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x10), 0x05a5a504); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x14), 0xa5a5a505); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x18), 0xa5a5a506); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x1c), 0xdeadbeef); + + /* Applying it again changes nothing */ + tunable_test_apply(t, tunable); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x04), 0xa512a534); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x10), 0x05a5a504); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x1c), 0xdeadbeef); +} + +/* Entries are applied in the property's order, each on the last one's result */ +static void tunable_test_apply_order(struct kunit *test) +{ + static const u32 cells[] = { + 0x08, 0x0000ffff, 0x00001111, + 0x08, 0x00000ff0, 0x00000220, + 0x08, 0xff000000, 0x33000000, + }; + struct tunable_test *t = test->priv; + struct apple_tunable *tunable; + + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + + t->regs[2] = cpu_to_le32(0xffffffff); + tunable_test_apply(t, tunable); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x08), 0x33ff1221); +} + +/* The value's bits are set as given, the mask only says what to clear first */ +static void tunable_test_apply_value_outside_mask(struct kunit *test) +{ + static const u32 cells[] = { 0x00, 0x0000000f, 0x00000105 }; + struct tunable_test *t = test->priv; + struct apple_tunable *tunable; + + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + + t->regs[0] = cpu_to_le32(0x0000f00a); + tunable_test_apply(t, tunable); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x00), 0x0000f105); +} + +/* A driver may apply a tunable that its device tree doesn't have */ +static void tunable_test_apply_null(struct kunit *test) +{ + struct tunable_test *t = test->priv; + + t->regs[0] = cpu_to_le32(0x12345678); + tunable_test_apply(t, NULL); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x00), 0x12345678); +} + +static struct kunit_case tunable_test_cases[] = { + KUNIT_CASE(tunable_test_parse_triplets), + KUNIT_CASE(tunable_test_parse_missing), + KUNIT_CASE(tunable_test_parse_bad_length), + KUNIT_CASE(tunable_test_parse_empty), + KUNIT_CASE(tunable_test_parse_small_resource), + KUNIT_CASE(tunable_test_parse_unaligned_offset), + KUNIT_CASE(tunable_test_parse_offset_bounds), + KUNIT_CASE(tunable_test_parse_resource_start), + KUNIT_CASE(tunable_test_apply_mask_value), + KUNIT_CASE(tunable_test_apply_order), + KUNIT_CASE(tunable_test_apply_value_outside_mask), + KUNIT_CASE(tunable_test_apply_null), + {} +}; + +static struct kunit_suite tunable_test_suite = { + .name = "apple-tunable", + .init = tunable_test_init, + .test_cases = tunable_test_cases, +}; +kunit_test_suite(tunable_test_suite); + +MODULE_LICENSE("Dual MIT/GPL"); +MODULE_DESCRIPTION("KUnit tests for Apple Silicon hardware tunable support"); diff --git a/drivers/soc/apple/tunable.kunitconfig b/drivers/soc/apple/tunable.kunitconfig new file mode 100644 index 00000000000000..fb06c16954cb22 --- /dev/null +++ b/drivers/soc/apple/tunable.kunitconfig @@ -0,0 +1,4 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_APPLE_TUNABLE_KUNIT_TEST=y diff --git a/drivers/soc/apple/xart_store.rs b/drivers/soc/apple/xart_store.rs index 1a52003a5dd796..75220de0f92942 100644 --- a/drivers/soc/apple/xart_store.rs +++ b/drivers/soc/apple/xart_store.rs @@ -12,7 +12,8 @@ use crate::shim; use kernel::prelude::*; /// The raw-extent owner opens this whole partition (the iBoot system container, -/// where the gigalocker lives) and serves the gigalocker window directly. +/// where the gigalocker lives) and serves the gigalocker window directly. The +/// name is only a hint: the opened device must be on the internal NVMe disk. pub(crate) const OWNER_PATH: &CStr = c"/dev/disk/by-partlabel/iBootSystemContainer"; const BLOCK_SIZE: usize = 0x1000; @@ -118,7 +119,7 @@ impl Store { /// an override of it. Writes additionally require a single-owner extent /// with no snapshots or pending revert, checked on the same block handle. pub(crate) fn open_owner(writes_enabled: bool, start_sector: u64) -> Result { - let file = shim::StoreFile::open_block(OWNER_PATH, writes_enabled)?; + let file = shim::StoreFile::open_internal_block(OWNER_PATH, writes_enabled)?; let base = crate::xart_apfs::locate(&file, writes_enabled)?; if start_sector != 0 { if start_sector.checked_mul(512).ok_or(EINVAL)? != base { diff --git a/drivers/spi/spi-apple-qspi-policy-test.c b/drivers/spi/spi-apple-qspi-policy-test.c index 5418c3a4d63ab3..0383e506b53382 100644 --- a/drivers/spi/spi-apple-qspi-policy-test.c +++ b/drivers/spi/spi-apple-qspi-policy-test.c @@ -5,6 +5,7 @@ */ #include +#include #include "spi-apple-qspi-policy.h" @@ -151,6 +152,8 @@ static void qspi_policy_status(struct kunit *test) /* Block protect only where the board allows it. */ KUNIT_EXPECT_FALSE(test, apple_qspi_status_allows_write(0x04, 0, 0, 0)); KUNIT_EXPECT_TRUE(test, apple_qspi_status_allows_write(0x04, 0x02, 0, 0x1c)); + /* The J813 W25Q64: QE and the SR3 drive strength, no block protection. */ + KUNIT_EXPECT_TRUE(test, apple_qspi_status_allows_write(0x00, 0x02, 0x60, 0)); /* CMP, SUS and WPS are refused everywhere. */ KUNIT_EXPECT_FALSE(test, apple_qspi_status_allows_write(0, 0x40, 0, 0x1c)); KUNIT_EXPECT_FALSE(test, apple_qspi_status_allows_write(0, 0x80, 0, 0x1c)); @@ -180,6 +183,8 @@ static void qspi_policy_gd_status(struct kunit *test) /* The J700 GD25UF16E part: QE is set for good and BP0 by iBoot. */ KUNIT_EXPECT_TRUE(test, apple_qspi_gd_status_allows_write(0x00, 0x02, 0x1c)); KUNIT_EXPECT_TRUE(test, apple_qspi_gd_status_allows_write(0x04, 0x02, 0x1c)); + /* The J775D GD25UF64E part: QE only, no block protection tolerated. */ + KUNIT_EXPECT_TRUE(test, apple_qspi_gd_status_allows_write(0x00, 0x02, 0)); KUNIT_EXPECT_FALSE(test, apple_qspi_gd_status_allows_write(0x04, 0x02, 0)); /* SRP0, SRP1 and LB1 to LB3 stay as found and do not block a write. */ KUNIT_EXPECT_TRUE(test, apple_qspi_gd_status_allows_write(0x80, 0x3b, 0x1c)); @@ -201,13 +206,193 @@ static void qspi_policy_part_status(struct kunit *test) KUNIT_EXPECT_TRUE(test, apple_qspi_part_status_allows_write(0xef, 0x20, 0, 0, 0x1c)); KUNIT_EXPECT_FALSE(test, apple_qspi_part_status_allows_write(0xc8, 0x20, 0, 0, 0x1c)); KUNIT_EXPECT_FALSE(test, apple_qspi_part_status_allows_write(0xef, 0, 0, 0x04, 0x1c)); - /* GigaDevice SR3 bit 2 is LPE, a power setting. */ + /* GigaDevice SR3 bit 2 is LPE, a power setting; J775D leaves SR3 0x20. */ KUNIT_EXPECT_TRUE(test, apple_qspi_part_status_allows_write(0xc8, 0, 0, 0x04, 0x1c)); + KUNIT_EXPECT_TRUE(test, apple_qspi_part_status_allows_write(0xc8, 0x00, 0x02, 0x20, 0)); + KUNIT_EXPECT_FALSE(test, apple_qspi_part_status_allows_write(0xc8, 0x04, 0x02, 0x20, 0)); KUNIT_EXPECT_TRUE(test, apple_qspi_part_status_allows_write(0xef, 0, 0x04, 0, 0x1c)); KUNIT_EXPECT_FALSE(test, apple_qspi_part_status_allows_write(0xc8, 0, 0x04, 0, 0x1c)); KUNIT_EXPECT_FALSE(test, apple_qspi_part_status_allows_write(0xc2, 0x20, 0, 0, 0x1c)); } +static void qspi_policy_window(struct kunit *test) +{ + /* The J813 and J700 partitions. */ + KUNIT_EXPECT_TRUE(test, apple_qspi_window_valid(1, 2, 0, 0x700000, 0x100000)); + KUNIT_EXPECT_TRUE(test, apple_qspi_window_valid(1, 2, 0, 0x24000, 0x1d0000)); + /* Two nvram labels, or none (a disabled one is not counted). */ + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(2, 2, 0, 0x700000, 0x100000)); + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(0, 2, 0, 0x700000, 0x100000)); + /* Marked read-only. */ + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 2, 1, 0x700000, 0x100000)); + /* Three reg cells, or none. */ + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 3, 0, 0x700000, 0x100000)); + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 0, 0, 0x700000, 0x100000)); + /* A misaligned start, a part of a bank, an empty partition. */ + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 2, 0, 0x700800, 0x100000)); + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 2, 0, 0x700000, 0xff000)); + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 2, 0, 0x700000, 0)); + /* Past three-byte addressing. */ + KUNIT_EXPECT_TRUE(test, apple_qspi_window_valid(1, 2, 0, 0xf00000, 0x100000)); + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 2, 0, 0xf10000, 0x100000)); + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 2, 0, 0xfffff000, 0x10000)); +} + +static void qspi_policy_bank_state(struct kunit *test) +{ + unsigned char h[24]; + + memset(h, 0xff, sizeof(h)); + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), 0); + memset(h, 0, sizeof(h)); + memcpy(h, "3VVN", 4); + h[5] = 0x40; /* store size 0x4000 */ + h[14] = 1; + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), 1); + h[14] = 2; /* another version */ + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), -1); + h[14] = 1; + h[5] = 0; + h[6] = 1; /* 0x10000: a full bank */ + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), 1); + h[4] = 1; /* past the bank */ + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), -1); + h[4] = 23; + h[6] = 0; /* smaller than the header */ + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), -1); + h[4] = 24; + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), 1); + h[0] = '2'; + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), -1); + /* Firmware, not NVRAM, and a half-erased bank. */ + memset(h, 0, sizeof(h)); + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), -1); + memset(h, 0xff, sizeof(h)); + h[23] = 0xfe; + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), -1); +} + +static void qspi_policy_parts(struct kunit *test) +{ + static const unsigned char known[][3] = { + { 0xef, 0x65, 0x17 }, { 0xc2, 0x2b, 0x27 }, + { 0xef, 0x65, 0x15 }, { 0xc8, 0x83, 0x15 }, + { 0xc8, 0x83, 0x17 }, + }; + static const unsigned int sizes[] = { 0x800000, 0x800000, 0x200000, 0x200000, + 0x800000 }; + static const unsigned char bp_ok[] = { 0, 0, 0x1c, 0x1c, 0 }; + static const unsigned char unknown[][3] = { + { 0xef, 0x65, 0x16 }, { 0xef, 0x40, 0x17 }, { 0xc2, 0x2b, 0x28 }, + { 0xc8, 0x60, 0x15 }, { 0xc8, 0x83, 0x16 }, { 0xc8, 0x83, 0x18 }, + { 0, 0, 0 }, { 0xff, 0xff, 0xff }, + }; + const struct apple_qspi_part *part; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(known); i++) { + part = apple_qspi_find_part(known[i]); + KUNIT_ASSERT_NOT_NULL(test, part); + KUNIT_EXPECT_EQ(test, part->size, sizes[i]); + KUNIT_EXPECT_EQ(test, part->bp_ok, bp_ok[i]); + } + for (i = 0; i < ARRAY_SIZE(unknown); i++) + KUNIT_EXPECT_NULL(test, apple_qspi_find_part(unknown[i])); + /* The size bounds the window: the J700's fits 2 MiB, the J813's does not. */ + part = apple_qspi_find_part(known[2]); + KUNIT_EXPECT_LE(test, 0x1f4000ULL, (unsigned long long)part->size); + KUNIT_EXPECT_GT(test, 0x800000ULL, (unsigned long long)part->size); +} + +static void qspi_policy_protected(struct kunit *test) +{ + unsigned long long s, e; + + KUNIT_EXPECT_EQ(test, apple_qspi_protected_range(0xef, 0, 0x200000, &s, &e), 0); + /* BP0 on the J700's parts: the top 64 KiB, inside the window's last bank. */ + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xef, 0x04, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0x1f0000ULL); + KUNIT_EXPECT_EQ(test, e, 0x200000ULL); + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xc8, 0x04, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0x1f0000ULL); + /* BP0+BP2: the top half; BP1+BP2: all of it. */ + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xef, 0x14, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0x100000ULL); + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xef, 0x18, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0ULL); + KUNIT_EXPECT_EQ(test, e, 0x200000ULL); + /* Winbond TB: the bottom 64 KiB, below the J700's window. */ + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xef, 0x24, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0ULL); + KUNIT_EXPECT_EQ(test, e, 0x10000ULL); + /* Winbond SEC: 4 KiB to 32 KiB. */ + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xef, 0x44, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0x1ff000ULL); + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xef, 0x54, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0x1f8000ULL); + /* GigaDevice SR1 bit 5 is BP3, not TB (the status policy refuses it). */ + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xc8, 0x24, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0x1f0000ULL); +} + +static void qspi_policy_unprotected_banks(struct kunit *test) +{ + unsigned long long s, e; + int ret; + + /* Nothing protected inside the window: all of it. */ + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0, 0x10000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, s, 0x24000ULL); + KUNIT_EXPECT_EQ(test, e, 0x1f4000ULL); + ret = apple_qspi_unprotected_banks(0x700000, 0x800000, 0, 0x700000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, s, 0x700000ULL); + /* BP0 on the J700: its last bank [0x1e4000, 0x1f4000) is a quarter covered, and dropped. */ + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0x1f0000, 0x200000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, s, 0x24000ULL); + KUNIT_EXPECT_EQ(test, e, 0x1e4000ULL); + /* TB with BP0+BP1: the bottom 256 KiB takes the first two banks. */ + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0, 0x40000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, s, 0x44000ULL); + KUNIT_EXPECT_EQ(test, e, 0x1f4000ULL); + /* A range ending on a bank boundary takes exactly those banks. */ + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0, 0x44000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, s, 0x44000ULL); + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0x1e4000, 0x200000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, e, 0x1e4000ULL); + /* The top half, or all of the part: nothing left. */ + ret = apple_qspi_unprotected_banks(0x700000, 0x800000, 0x400000, 0x800000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 0); + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0, 0x200000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 0); + /* A range inside the window. */ + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0x100000, 0x110000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 0); +} + +static void qspi_policy_sfdp(struct kunit *test) +{ + unsigned char h[16] = { 'S', 'F', 'D', 'P', 6, 1, 1, 0xff, + 0x00, 6, 1, 16, 0x30, 0, 0, 0xff }; + + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_basic_table(h), 0x30L); + h[3] = 'Q'; + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_basic_table(h), -1L); + h[3] = 'P'; + h[8] = 0x84; /* not the basic table */ + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_basic_table(h), -1L); + /* 64 Mbit and 16 Mbit as bit counts minus one, and as a power of two. */ + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_size(0x03ffffff), 0x800000ULL); + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_size(0x00ffffff), 0x200000ULL); + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_size(0x80000000 | 26), 0x800000ULL); + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_size(0x80000000 | 1), 0ULL); +} + static struct kunit_case apple_qspi_policy_cases[] = { KUNIT_CASE(qspi_policy_write_enable), KUNIT_CASE(qspi_policy_program), @@ -220,6 +405,12 @@ static struct kunit_case apple_qspi_policy_cases[] = { KUNIT_CASE(qspi_policy_mx_status), KUNIT_CASE(qspi_policy_gd_status), KUNIT_CASE(qspi_policy_part_status), + KUNIT_CASE(qspi_policy_window), + KUNIT_CASE(qspi_policy_bank_state), + KUNIT_CASE(qspi_policy_parts), + KUNIT_CASE(qspi_policy_protected), + KUNIT_CASE(qspi_policy_unprotected_banks), + KUNIT_CASE(qspi_policy_sfdp), {} }; diff --git a/drivers/spi/spi-apple-qspi-policy.h b/drivers/spi/spi-apple-qspi-policy.h index 361ecc689fca75..0a8e502cfcbb47 100644 --- a/drivers/spi/spi-apple-qspi-policy.h +++ b/drivers/spi/spi-apple-qspi-policy.h @@ -6,8 +6,8 @@ #define APPLE_QSPI_ERASE_SIZE 4096U /* - * [start, end) is the board's nvram partition. Subtraction avoids overflow; - * addr is not truncated to wire width first. + * [start, end) is the write window, the device tree's nvram partition. + * Subtraction avoids overflow; addr is not truncated to wire width first. */ static inline int apple_qspi_range_allowed(unsigned long long addr, unsigned int len, unsigned long long start, @@ -81,14 +81,14 @@ static inline int apple_qspi_mx_status_allows_write(unsigned int sr, #define APPLE_QSPI_MFR_GIGADEVICE 0xc8 /* - * GigaDevice GD25UF16E. SR1 holds WIP, WEL, five block-protect bits BP[4:0] - * at bits 6:2 and SRP0. SR2 holds SRP1, QE, SUS2 at bit 2, LB[3:1], CMP and - * SUS1 at bit 7. SR3 holds output drive, dummy-cycle and low-power settings - * and has no write-protect selection. BUSY and WEL, both suspend bits and - * CMP are always refused. BP[2:0] sit where they do on Winbond parts and - * are tolerated only where bp_ok allows them; BP3 and BP4 move or shrink - * the protected range and are refused unless bp_ok names them. SRP0, SRP1, - * QE and LB stay unchanged. + * GigaDevice GD25UF16E and GD25UF64E. SR1 holds WIP, WEL, five block-protect + * bits BP[4:0] at bits 6:2 and SRP0. SR2 holds SRP1, QE, SUS2 at bit 2, + * LB[3:1], CMP and SUS1 at bit 7. SR3 holds output drive, dummy-cycle and + * low-power settings and has no write-protect selection. BUSY and WEL, both + * suspend bits and CMP are always refused. BP[2:0] sit where they do on + * Winbond parts and are tolerated only where bp_ok allows them; BP3 and BP4 + * move or shrink the protected range and are refused unless bp_ok names them. + * SRP0, SRP1, QE and LB stay unchanged. */ static inline int apple_qspi_gd_status_allows_write(unsigned int sr1, unsigned int sr2, @@ -113,4 +113,178 @@ static inline int apple_qspi_part_status_allows_write(unsigned int mfr, return apple_qspi_status_allows_write(sr1, sr2, sr3, bp_ok); } } + +/* The size of one NVRAM v3 bank ("3VVN" store). */ +#define APPLE_QSPI_NVRAM_BANK 0x10000U + +/* + * Whether an nvram partition can be the write window: the only one with that + * label, one address and one size cell, not marked read-only, a whole number + * of NVRAM banks from a 4 KiB boundary, and within three-byte addressing. + */ +static inline int apple_qspi_window_valid(unsigned int found, + unsigned int reg_cells, int read_only, + unsigned long long start, + unsigned long long size) +{ + return found == 1 && reg_cells == 2 && !read_only && size && + !(start % APPLE_QSPI_ERASE_SIZE) && + !(size % APPLE_QSPI_NVRAM_BANK) && start + size <= 1ULL << 24; +} + +/* + * The first 24 bytes of an NVRAM bank: 1 for a v3 store header ("3VVN", + * version 1, a store size from the header itself up to the bank), 0 for a + * bank that may be erased (the caller checks the rest of it), -1 for + * anything else. The v3 header has no checksum of its own; each variable in + * the store carries a CRC32. + */ +static inline int apple_qspi_nvram_bank_state(const unsigned char h[24]) +{ + unsigned int size = h[4] | h[5] << 8 | h[6] << 16 | (unsigned int)h[7] << 24; + int i; + + for (i = 0; i < 24 && h[i] == 0xff; i++) + ; + if (i == 24) + return 0; + if (h[0] == '3' && h[1] == 'V' && h[2] == 'V' && h[3] == 'N' && + h[14] == 1 && size >= 24 && size <= APPLE_QSPI_NVRAM_BANK) + return 1; + return -1; +} + +/* + * The boot NOR parts whose nvram partition may be written: the JEDEC ID, the + * size, which bounds the window (a three-byte address past it wraps around) + * and must match the part's SFDP density, and the SR1 block-protect bits the + * part's firmware leaves set. Those stay set; apple_qspi_protected_range() + * says what they protect. + */ +struct apple_qspi_part { + unsigned char jedec[3]; + unsigned int size; + unsigned char bp_ok; +}; + +#define APPLE_QSPI_JEDEC_W25Q64 { 0xef, 0x65, 0x17 } +#define APPLE_QSPI_JEDEC_W25Q16 { 0xef, 0x65, 0x15 } +#define APPLE_QSPI_JEDEC_MX_2B27 { 0xc2, 0x2b, 0x27 } +#define APPLE_QSPI_JEDEC_GD25UF16E { 0xc8, 0x83, 0x15 } +#define APPLE_QSPI_JEDEC_GD25UF64E { 0xc8, 0x83, 0x17 } + +static const struct apple_qspi_part apple_qspi_parts[] = { + /* J613, J713, J813; also on the bus of some J616s */ + { APPLE_QSPI_JEDEC_W25Q64, 0x800000, 0 }, + /* J616s, the ID macOS reports */ + { APPLE_QSPI_JEDEC_MX_2B27, 0x800000, 0 }, + /* J700: iBoot leaves BP0 set, over the top 64 KiB */ + { APPLE_QSPI_JEDEC_W25Q16, 0x200000, 0x1c }, + /* Some J700s; BP0 covers the same range */ + { APPLE_QSPI_JEDEC_GD25UF16E, 0x200000, 0x1c }, + /* J775D (M5 Ultra): no block protection left set, SR1 0x00 */ + { APPLE_QSPI_JEDEC_GD25UF64E, 0x800000, 0 }, +}; + +static inline const struct apple_qspi_part * +apple_qspi_find_part(const unsigned char id[3]) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(apple_qspi_parts); i++) + if (id[0] == apple_qspi_parts[i].jedec[0] && + id[1] == apple_qspi_parts[i].jedec[1] && + id[2] == apple_qspi_parts[i].jedec[2]) + return &apple_qspi_parts[i]; + return NULL; +} + +/* + * What SR1 protects on a part that tolerates BP bits (the 2 MiB parts, whose + * status policy leaves BP0-BP2 and, on Winbond, TB and SEC as found; CMP, and + * BP3/BP4 on GigaDevice, are refused before this). BP0-BP2 of 1 to 5 protect + * 1/32 to 1/2 of the part, or with SEC 4 to 32 KiB; 6 and 7 protect all of it. + * TB puts the range at the bottom instead of the top. Sets [*start, *end) and + * returns 1, or returns 0 when nothing is protected. + */ +static inline int apple_qspi_protected_range(unsigned int mfr, unsigned int sr1, + unsigned long long size, + unsigned long long *start, + unsigned long long *end) +{ + unsigned int bp = (sr1 >> 2) & 7, shift; + int bottom = 0, sec = 0; + unsigned long long len; + + if (!bp) + return 0; + if (mfr != APPLE_QSPI_MFR_GIGADEVICE) { + bottom = !!(sr1 & 0x20); + sec = !!(sr1 & 0x40); + } + if (bp >= 6) { + len = size; + } else if (sec) { + shift = bp - 1 < 3 ? bp - 1 : 3; + len = 0x1000ULL << shift; + } else { + len = (size >> 5) << (bp - 1); + } + *start = bottom ? 0 : size - len; + *end = *start + len; + return 1; +} + +/* + * The banks of the window [start, end) that a protected range [ps, pe) does + * not reach, as [*wstart, *wend): a bank the range only partly covers is + * dropped whole, so an erase of it never stops halfway. The decoded range + * always reaches one end of the part, so it takes a run of banks from one + * end of the window. Returns 0 when no bank is left, or for a range inside + * the window with banks on both sides of it, which no decode produces. + */ +static inline int apple_qspi_unprotected_banks(unsigned long long start, + unsigned long long end, + unsigned long long ps, + unsigned long long pe, + unsigned long long *wstart, + unsigned long long *wend) +{ + unsigned long long bank = APPLE_QSPI_NVRAM_BANK; + + *wstart = start; + *wend = end; + if (pe <= start || ps >= end) + return 1; + if (ps <= start) + *wstart = start + (pe - start + bank - 1) / bank * bank; + else if (pe >= end) + *wend = start + (ps - start) / bank * bank; + else + return 0; + return *wstart < *wend; +} + +/* + * The JEDEC basic flash parameter table from the first 16 bytes of the SFDP + * space: "SFDP", then the first parameter header, which must be the basic + * table (ID 0x00, MSB 0xff). Returns the table's address, or -1. + */ +static inline long apple_qspi_sfdp_basic_table(const unsigned char h[16]) +{ + if (h[0] != 'S' || h[1] != 'F' || h[2] != 'D' || h[3] != 'P' || + h[8] != 0x00 || h[15] != 0xff || h[11] < 2) + return -1; + return h[12] | h[13] << 8 | h[14] << 16; +} + +/* The part size in bytes from the basic table's second DWORD, or 0. */ +static inline unsigned long long apple_qspi_sfdp_size(unsigned int dword2) +{ + unsigned int n = dword2 & 0x7fffffff; + + if (dword2 & 0x80000000) + return n >= 3 && n < 64 ? 1ULL << (n - 3) : 0; + return ((unsigned long long)dword2 + 1) / 8; +} #endif diff --git a/drivers/spi/spi-apple-qspi.c b/drivers/spi/spi-apple-qspi.c index 06e2d356dcbec3..9b1e1bcaf8954f 100644 --- a/drivers/spi/spi-apple-qspi.c +++ b/drivers/spi/spi-apple-qspi.c @@ -7,10 +7,10 @@ * command FIFO. This driver intentionally implements the PIO spi-mem path * only; that is sufficient for SPI NOR discovery and access. * - * The boot NOR starts read-only. On the qualified boards (J613, J713, - * J616s and the J700) root may opt in at runtime to bounded, verified - * programs and 4 KiB erases inside the nvram partition; everything else - * stays read-only. On T8140 data reads reach the whole NOR. + * The boot NOR starts read-only. Where the device tree describes its nvram + * partition and the flash is a part listed here, root may opt in at runtime + * to bounded, verified programs and 4 KiB erases inside that partition; + * everything else stays read-only. On T8140 data reads reach the whole NOR. */ #include @@ -25,9 +25,11 @@ #include #include #include +#include #include #include #include +#include #include "spi-apple-qspi-policy.h" @@ -97,61 +99,6 @@ struct apple_qspi_soc { bool runtime_pm; }; -/* - * A board whose NVRAM may be written: the controller compatible, the - * machine, the controller aperture, the nvram partition the device tree - * must describe, the boot NOR JEDEC ID, the SR1 block-protect bits its - * firmware leaves set at boot and the JEDEC ID of a second part, if any. - */ -struct apple_qspi_board { - const char *controller; - const char *machine; - resource_size_t base; - u32 nvram_start; - u32 nvram_size; - u8 jedec[3]; - u8 bp_ok; - u8 jedec_alt[3]; -}; - -#define APPLE_QSPI_JEDEC_W25Q64 { 0xef, 0x65, 0x17 } -#define APPLE_QSPI_JEDEC_W25Q16 { 0xef, 0x65, 0x15 } -#define APPLE_QSPI_JEDEC_MX_2B27 { 0xc2, 0x2b, 0x27 } -#define APPLE_QSPI_JEDEC_GD25UF16E { 0xc8, 0x83, 0x15 } - -static const struct apple_qspi_board apple_qspi_boards[] = { - { "apple,t8122-qspi", "apple,j613", 0x2a1118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - { "apple,t8132-qspi", "apple,j713", 0x3ad118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - /* The J715 ADT has the J713's nvram; its NOR part is assumed the same. */ - { "apple,t8132-qspi", "apple,j715", 0x3ad118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - /* - * The J773g ADT has the same nvram; the J604's dump omits it and the - * iMacs have no ADT yet. All are assumed to carry the J713's part. - */ - { "apple,t8132-qspi", "apple,j604", 0x3ad118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - { "apple,t8132-qspi", "apple,j623", 0x3ad118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - { "apple,t8132-qspi", "apple,j624", 0x3ad118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - { "apple,t8132-qspi", "apple,j773g", 0x3ad118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - /* Macronix is the ID macOS reports; a J616s also reads W25Q64 on the bus. */ - { "apple,t6041-qspi", "apple,j616s", 0x429118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_MX_2B27, 0, - APPLE_QSPI_JEDEC_W25Q64 }, - /* - * iBoot leaves BP0 set on the J700, over the top 64 KiB. Some J700s - * carry a GigaDevice GD25UF16E, where BP0 covers the same range. - */ - { "apple,t8140-qspi", "apple,j700", 0x385110000ULL, - 0x24000, 0x1d0000, APPLE_QSPI_JEDEC_W25Q16, 0x1c, - APPLE_QSPI_JEDEC_GD25UF16E }, -}; - static DEFINE_MUTEX(apple_qspi_policy_lock); static bool read_only = true; static bool runtime_ready; @@ -189,7 +136,7 @@ static const struct kernel_param_ops apple_qspi_read_only_ops = { .get = apple_qspi_get_read_only, }; module_param_cb(read_only, &apple_qspi_read_only_ops, &read_only, 0644); -MODULE_PARM_DESC(read_only, "Default true; root runtime opt-in for bounded NVRAM writes on qualified boards"); +MODULE_PARM_DESC(read_only, "Default true; root runtime opt-in for bounded NVRAM writes in the nvram partition of a known part"); static bool apple_qspi_opcode_is_read(u8 opcode) { @@ -220,11 +167,17 @@ struct apple_qspi { /* The nvram partition [window_start, window_end). */ u64 window_start; u64 window_end; - /* Expected JEDEC IDs and the SR1 block-protect bits left by firmware. */ - u8 jedec[3]; - u8 jedec_alt[3]; - u8 bp_ok; + /* The device tree describes a usable nvram partition. */ bool nvram_write_candidate; + /* + * The window checked against the flash before its first program or + * erase, then latched: 0 not yet, 1 passed, a negative errno refused. + */ + int qualified; + const char *qualify_denial; + /* Once qualified: the banks of the window no block protection reaches. */ + u64 write_start; + u64 write_end; bool write_fault; void __iomem *base; void __iomem *p; @@ -718,9 +671,125 @@ static int apple_qspi_status(struct spi_mem *mem, u8 mfr, u8 sr[3]) return 0; } -static int apple_qspi_nvram_modify(struct spi_mem *mem, const struct spi_mem_op *op) +static int apple_qspi_read_sfdp(struct spi_mem *mem, u32 addr, u8 *buf, u32 len) +{ + struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(0x5a, 1), + SPI_MEM_OP_ADDR(3, addr, 1), SPI_MEM_OP_DUMMY(1, 1), + SPI_MEM_OP_DATA_IN(len, buf, 1)); + + return apple_qspi_transfer_op(mem, &op); +} + +/* + * Before the first program or erase, check the window against the flash, + * and latch the result: the part's SFDP density must be the size the part + * table bounds the window with, and every bank of the window must start with + * a v3 NVRAM store header or be erased throughout, with at least one store. + * A device tree partition that is not the NVRAM, or a part of another size, + * admits nothing. Writes are then admitted only in the banks that the block + * protection found in SR1 does not reach, even in part. + */ +static int apple_qspi_qualify(struct spi_mem *mem, struct apple_qspi *qspi, + const struct apple_qspi_part *part, + const char **denial) +{ + unsigned long long ps, pe, ws, we; + u8 head[24], dword[8], sr[3]; + u8 *buf = NULL; + u64 bank, at; + long table; + int state, stores = 0, ret; + + if (qspi->qualified) { + *denial = qspi->qualify_denial; + return qspi->qualified < 0 ? qspi->qualified : 0; + } + ret = apple_qspi_read_sfdp(mem, 0, head, 16); + if (ret) + return ret; + table = apple_qspi_sfdp_basic_table(head); + if (table < 0) { + *denial = "sfdp"; + ret = -ENODEV; + goto latch; + } + ret = apple_qspi_read_sfdp(mem, table, dword, sizeof(dword)); + if (ret) + return ret; + if (apple_qspi_sfdp_size(get_unaligned_le32(&dword[4])) != part->size) { + *denial = "part-size"; + ret = -ENODEV; + goto latch; + } + for (bank = qspi->window_start; bank < qspi->window_end; + bank += APPLE_QSPI_NVRAM_BANK) { + ret = apple_qspi_read_array(mem, bank, head, sizeof(head)); + if (ret) + goto out; + state = apple_qspi_nvram_bank_state(head); + /* Blank where a header would be is not enough: all of it. */ + if (!state && !buf) { + buf = kmalloc(APPLE_QSPI_ERASE_SIZE, GFP_KERNEL); + if (!buf) { + ret = -ENOMEM; + goto out; + } + } + for (at = bank; !state && at < bank + APPLE_QSPI_NVRAM_BANK; + at += APPLE_QSPI_ERASE_SIZE) { + ret = apple_qspi_read_array(mem, at, buf, APPLE_QSPI_ERASE_SIZE); + if (ret) + goto out; + if (memchr_inv(buf, 0xff, APPLE_QSPI_ERASE_SIZE)) + state = -1; + } + if (state < 0) { + *denial = "window"; + ret = -EACCES; + goto latch; + } + stores += state; + } + if (!stores) { + *denial = "window"; + ret = -EACCES; + goto latch; + } + ret = apple_qspi_status(mem, part->jedec[0], sr); + if (ret) + goto out; + ws = qspi->window_start; + we = qspi->window_end; + if (part->bp_ok && + apple_qspi_protected_range(part->jedec[0], sr[0], part->size, &ps, &pe) && + !apple_qspi_unprotected_banks(qspi->window_start, qspi->window_end, + ps, pe, &ws, &we)) { + *denial = "protected"; + ret = -EACCES; + goto latch; + } + qspi->write_start = ws; + qspi->write_end = we; + qspi->qualified = 1; + dev_info(&mem->spi->dev, + "nvram window [%#llx, %#llx): %d stores, writes in [%#llx, %#llx), part %02x%02x%02x\n", + qspi->window_start, qspi->window_end, stores, ws, we, + part->jedec[0], part->jedec[1], part->jedec[2]); + goto out; +latch: + qspi->qualified = ret; + qspi->qualify_denial = *denial; +out: + kfree(buf); + return ret; +} + +static int apple_qspi_nvram_modify(struct spi_mem *mem, const struct spi_mem_op *op, + const char **denial) { struct apple_qspi *qspi = spi_controller_get_devdata(mem->spi->controller); + const struct apple_qspi_part *part; + unsigned long long ps, pe; unsigned long deadline; u8 id[3], before[3], after[3], sr1; u8 *verify; @@ -734,17 +803,37 @@ static int apple_qspi_nvram_modify(struct spi_mem *mem, const struct spi_mem_op ret = apple_qspi_read_register(mem, 0x9f, id, sizeof(id)); if (ret) goto out; - if (memcmp(id, qspi->jedec, sizeof(id)) && - (!qspi->jedec_alt[0] || memcmp(id, qspi->jedec_alt, sizeof(id)))) { + /* A known part, the partition within it, and checked against it. */ + part = apple_qspi_find_part(id); + if (!part || qspi->window_end > part->size) { + *denial = part ? "part-size" : "part"; ret = -ENODEV; goto out; } + ret = apple_qspi_qualify(mem, qspi, part, denial); + if (ret) + goto out; + /* Never into a bank the protection reaches, so none is left half erased. */ + if (op->addr.val < qspi->write_start || op->addr.val + len > qspi->write_end) { + *denial = "protected"; + ret = -EACCES; + goto out; + } ret = apple_qspi_status(mem, id[0], before); if (ret) goto out; /* No unlocking. Conservatively refuse BP/CMP/WPS, BUSY/WEL or suspend. */ if (!apple_qspi_part_status_allows_write(id[0], before[0], before[1], - before[2], qspi->bp_ok)) { + before[2], part->bp_ok)) { + *denial = "status"; + ret = -EACCES; + goto out; + } + /* The flash would ignore this one: refuse it rather than latch a fault. */ + if (part->bp_ok && + apple_qspi_protected_range(id[0], before[0], part->size, &ps, &pe) && + op->addr.val < pe && op->addr.val + len > ps) { + *denial = "protected"; ret = -EACCES; goto out; } @@ -884,9 +973,9 @@ static int apple_qspi_exec_op(struct spi_mem *mem, const struct spi_mem_op *op) ret = 0; goto out; } - ret = apple_qspi_nvram_modify(mem, op); + ret = apple_qspi_nvram_modify(mem, op, &denial); out: - if (ret == -EACCES) + if (ret == -EACCES || ret == -ENODEV) dev_warn_ratelimited(&mem->spi->dev, "NVRAM denied: reason=%s opcode=%02x addr=%#llx addr_bytes=%u len=%u width=%u addr_width=%u dummy=%u dir=%u ro=%u candidate=%u fault=%u\n", denial, op->cmd.opcode, (unsigned long long)op->addr.val, @@ -922,35 +1011,19 @@ static const struct spi_controller_mem_ops apple_qspi_mem_ops = { .exec_op = apple_qspi_mem_exec_op, }; -/* Keep write qualification tied to the board and its controller aperture. */ -static const struct apple_qspi_board * -apple_qspi_nvram_write_board(struct device_node *node, resource_size_t base) -{ - const struct apple_qspi_board *board; - unsigned int i; - - for (i = 0; i < ARRAY_SIZE(apple_qspi_boards); i++) { - board = &apple_qspi_boards[i]; - if (of_device_is_compatible(node, board->controller) && - of_machine_is_compatible(board->machine) && - base == board->base) - return board; - } - return NULL; -} - /* - * The one "nvram" partition of the flash on CS0, 4 KiB aligned and within - * three-byte addressing, since the policy only admits three-byte programs - * and erases. Without it, no program or erase is admitted. + * The one "nvram" partition of the flash on CS0 that apple_qspi_window_valid() + * accepts: not read-only, whole NVRAM banks from a 4 KiB boundary, within + * three-byte addressing, since the policy only admits three-byte programs and + * erases. Without it, no program or erase is admitted. */ static void apple_qspi_nvram_window(struct device *dev, struct apple_qspi *qspi) { struct device_node *flash, *parts, *part; const char *label; - u32 reg[2], cells[2], cs; + u32 reg[2] = { 0 }, cells[2], cs; u64 start = 0, end = 0; - int found = 0; + int found = 0, reg_cells = 0, ro = 0; flash = of_get_child_by_name(dev->of_node, "flash"); if (!flash) @@ -973,18 +1046,18 @@ static void apple_qspi_nvram_window(struct device *dev, struct apple_qspi *qspi) strcmp(label, "nvram")) continue; found++; - if (of_property_count_u32_elems(part, "reg") == 2 && - !of_property_read_u32_array(part, "reg", reg, 2)) { - start = reg[0]; - end = start + reg[1]; - } + ro = of_property_read_bool(part, "read-only"); + reg_cells = of_property_count_u32_elems(part, "reg"); + if (reg_cells != 2 || + of_property_read_u32_array(part, "reg", reg, 2)) + memset(reg, 0, sizeof(reg)); } } of_node_put(parts); - if (found != 1 || start >= end || end > 1ULL << 24 || - !IS_ALIGNED(start, APPLE_QSPI_ERASE_SIZE) || - !IS_ALIGNED(end, APPLE_QSPI_ERASE_SIZE)) - start = end = 0; + if (apple_qspi_window_valid(found, reg_cells, ro, reg[0], reg[1])) { + start = reg[0]; + end = start + reg[1]; + } out: qspi->window_start = start; qspi->window_end = end; @@ -997,7 +1070,6 @@ static void apple_qspi_nvram_window(struct device *dev, struct apple_qspi *qspi) static int apple_qspi_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; - const struct apple_qspi_board *board; const struct apple_qspi_soc *soc; struct spi_controller *ctlr; struct apple_qspi *qspi; @@ -1017,9 +1089,6 @@ static int apple_qspi_probe(struct platform_device *pdev) qspi->nvram_policy = true; qspi->nvram_window = soc->multi_io_reads; apple_qspi_nvram_window(dev, qspi); - if (of_device_is_compatible(dev->of_node, "apple,t8122-qspi") && - !of_machine_is_compatible("apple,j613")) - return -ENODEV; init_completion(&qspi->done); spin_lock_init(&qspi->lock); @@ -1028,15 +1097,11 @@ static int apple_qspi_probe(struct platform_device *pdev) return dev_err_probe(dev, -EINVAL, "QSPIMC aperture is too small\n"); - /* The device tree must describe exactly the board's nvram partition. */ - board = apple_qspi_nvram_write_board(dev->of_node, res->start); - if (board && qspi->window_start == board->nvram_start && - qspi->window_end == (u64)board->nvram_start + board->nvram_size) { - memcpy(qspi->jedec, board->jedec, sizeof(qspi->jedec)); - memcpy(qspi->jedec_alt, board->jedec_alt, sizeof(qspi->jedec_alt)); - qspi->bp_ok = board->bp_ok; - qspi->nvram_write_candidate = true; - } + /* + * The device tree's nvram partition is the write window. Each program + * or erase then checks the part and that the window lies within it. + */ + qspi->nvram_write_candidate = qspi->window_start < qspi->window_end; qspi->base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(qspi->base)) return PTR_ERR(qspi->base); diff --git a/drivers/spmi/spmi-apple-controller.c b/drivers/spmi/spmi-apple-controller.c index c5f8829cfeb455..1182e2e2daae3f 100644 --- a/drivers/spmi/spmi-apple-controller.c +++ b/drivers/spmi/spmi-apple-controller.c @@ -32,14 +32,14 @@ #include #include +#include "spmi-apple-irq.h" + /* SPMI Controller Registers */ #define SPMI_STATUS_REG 0 #define SPMI_CMD_REG 0x4 #define SPMI_RSP_REG 0x8 #define SPMI_ACT_REG 0xa4 -#define SPMI_IRQ_MASK_BASE 0x20 -#define SPMI_IRQ_ACK_BASE 0x60 /* * Peripheral interrupts come first. The RX FIFO notification sits right * after them, followed by the controller's own fault interrupts, so the @@ -61,8 +61,6 @@ * reply FIFO. macOS acks the controller's fault interrupt (source 263, after the 256 * peripheral sources; ack words from 0x600) and empties the queue when the controller starts. */ -#define SPMI_GEN4_IRQ_ACK_BASE 0x600 -#define SPMI_GEN4_FAULT_IRQ (SPMI_MAX_PERIPHERAL_IRQS + 7) #define SPMI_FAULT_QUEUE_MAX 64 /* More than the reply FIFO holds: the bound of a recovery's read-out. */ #define SPMI_GEN4_REPLY_DRAIN_MAX 64 @@ -77,6 +75,8 @@ struct apple_spmi_hw { u32 rx_empty; bool legacy_irqs; u32 num_irqs; + u32 irq_mask; + u32 irq_ack; }; static const struct apple_spmi_hw apple_spmi_gen1 = { @@ -86,6 +86,8 @@ static const struct apple_spmi_hw apple_spmi_gen1 = { .rx_empty = SPMI_RX_FIFO_EMPTY, .legacy_irqs = true, .num_irqs = 256, + .irq_mask = APPLE_SPMI_GEN1_IRQ_MASK, + .irq_ack = APPLE_SPMI_GEN1_IRQ_ACK, }; /* M1 Pro, Max and Ultra: 192 peripheral interrupts, notification at 192 */ @@ -96,6 +98,8 @@ static const struct apple_spmi_hw apple_spmi_t6000 = { .rx_empty = SPMI_RX_FIFO_EMPTY, .legacy_irqs = true, .num_irqs = 192, + .irq_mask = APPLE_SPMI_GEN1_IRQ_MASK, + .irq_ack = APPLE_SPMI_GEN1_IRQ_ACK, }; static const struct apple_spmi_hw apple_spmi_gen4 = { @@ -103,13 +107,18 @@ static const struct apple_spmi_hw apple_spmi_gen4 = { .command = 0x210, .reply = 0x220, .rx_empty = BIT(30), + .num_irqs = 256, + .irq_mask = APPLE_SPMI_GEN4_IRQ_MASK, + .irq_ack = APPLE_SPMI_GEN4_IRQ_ACK, }; struct apple_spmi { void __iomem *regs; void __iomem *faults; unsigned int nfaults; + struct device *dev; const struct apple_spmi_hw *hw; + u32 num_irqs; struct mutex fifo_lock; struct completion fifo_rx; struct irq_domain *irqd; @@ -125,21 +134,21 @@ struct apple_spmi { static void apple_spmi_irq_ack_raw(struct apple_spmi *spmi, u32 irq) { - u32 __iomem *reg = spmi->regs + SPMI_IRQ_ACK_BASE + (irq / 32) * 4; + u32 __iomem *reg = spmi->regs + spmi->hw->irq_ack + (irq / 32) * 4; writel(BIT(irq % 32), reg); } static void apple_spmi_irq_mask_raw(struct apple_spmi *spmi, u32 irq) { - u32 __iomem *reg = spmi->regs + SPMI_IRQ_MASK_BASE + (irq / 32) * 4; + u32 __iomem *reg = spmi->regs + spmi->hw->irq_mask + (irq / 32) * 4; writel(readl(reg) & ~BIT(irq % 32), reg); } static void apple_spmi_irq_unmask_raw(struct apple_spmi *spmi, u32 irq) { - u32 __iomem *reg = spmi->regs + SPMI_IRQ_MASK_BASE + (irq / 32) * 4; + u32 __iomem *reg = spmi->regs + spmi->hw->irq_mask + (irq / 32) * 4; writel(readl(reg) | BIT(irq % 32), reg); } @@ -181,8 +190,8 @@ static inline u32 apple_spmi_pack_cmd(u8 opc, u8 sid, u16 param) /* Ack the fault interrupt, then pop and log every queued fault record */ static void apple_spmi_drain_faults(struct device *dev, struct apple_spmi *spmi) { - void __iomem *ack = spmi->regs + SPMI_GEN4_IRQ_ACK_BASE + (SPMI_GEN4_FAULT_IRQ / 32) * 4; - u32 bit = BIT(SPMI_GEN4_FAULT_IRQ % 32), fault; + void __iomem *ack = spmi->regs + APPLE_SPMI_GEN4_IRQ_ACK + (APPLE_SPMI_GEN4_FAULT_IRQ / 32) * 4; + u32 bit = BIT(APPLE_SPMI_GEN4_FAULT_IRQ % 32), fault; int i; if (!spmi->faults) @@ -235,23 +244,13 @@ static int apple_spmi_wait_rx_not_empty(struct spmi_controller *ctrl) * late, or the stray one that was read in a reply's place, is read out instead: the bus gets a * command's whole timeout to finish, then the reply FIFO is read until it is empty. Nothing of * an old exchange can then answer a new command. A FIFO that does not empty keeps the failure. - * On the J714s, J716c, J813 and J815, whose deep sleep writes the PMU on this queue. - * Other generation 4 machines keep refusing later commands after a failed exchange. + * This is the controller's own reply FIFO, so it applies to every generation 4 controller + * (apple,t8142-spmi: T8142 and T6050), on every board. */ -static bool apple_spmi_gen4_recovers(void) -{ - return of_machine_is_compatible("apple,j714s") || - of_machine_is_compatible("apple,j716c") || - of_machine_is_compatible("apple,j813") || - of_machine_is_compatible("apple,j815"); -} - static int apple_spmi_gen4_recover(struct spmi_controller *ctrl, struct apple_spmi *spmi) { unsigned int i; - if (!apple_spmi_gen4_recovers()) - return -EIO; usleep_range(REG_POLL_TIMEOUT_US, 2 * REG_POLL_TIMEOUT_US); for (i = 0; i < SPMI_GEN4_REPLY_DRAIN_MAX; i++) { if (readl(spmi->regs + spmi->hw->status) & spmi->hw->rx_empty) { @@ -282,7 +281,7 @@ static int __spmi_raw_cmd(struct spmi_controller *ctrl, u8 opc, u8 sid, u16 para return ret; } else { writel(SPMI_ACT_FIFO_FLUSH, spmi->regs + SPMI_ACT_REG); - apple_spmi_irq_ack_raw(spmi, spmi->hw->num_irqs); + apple_spmi_irq_ack_raw(spmi, spmi->num_irqs); } spmi->prev_fail = false; } @@ -451,7 +450,7 @@ static int apple_spmi_irq_domain_translate(struct irq_domain *irqd, if (fwspec->param_count != 2) return -EINVAL; - if (args[0] >= spmi->hw->num_irqs) + if (args[0] >= spmi->num_irqs) return -EINVAL; *hwirq = args[0]; *type = args[1] & IRQ_TYPE_SENSE_MASK; @@ -471,7 +470,7 @@ static int apple_spmi_irq_domain_alloc(struct irq_domain *irqd, unsigned int vir if (ret) return ret; - if (hwirq + nr_irqs > spmi->hw->num_irqs) + if (hwirq + nr_irqs > spmi->num_irqs) return -EINVAL; for (i = 0; i < nr_irqs; i++) { @@ -508,12 +507,23 @@ static void apple_spmi_irq_handler(struct irq_desc *desc) { struct apple_spmi *spmi = irq_desc_get_handler_data(desc); struct irq_chip *chip = irq_desc_get_chip(desc); - u32 notify = spmi->hw->num_irqs; + u32 notify = spmi->num_irqs; bool handled = false, held = false, raw_pending = false; unsigned long val, offset, bit; chained_irq_enter(chip, desc); - val = readl(spmi->regs + SPMI_IRQ_ACK_BASE + (notify / 32) * 4); + val = readl(spmi->regs + spmi->hw->irq_ack + (notify / 32) * 4); + /* + * On gen4 the controller's own fault source shares this last ack word + * (0x620, bit 7). Its queued records must be read before the source is + * acked, or drain_faults() never sees them. + */ + if (!spmi->hw->legacy_irqs && spmi->faults && + (val & BIT(APPLE_SPMI_GEN4_FAULT_IRQ % 32))) { + apple_spmi_drain_faults(spmi->dev, spmi); + val &= ~BIT(APPLE_SPMI_GEN4_FAULT_IRQ % 32); + handled = true; + } raw_pending |= !!val; if (val & BIT(notify % 32)) { apple_spmi_irq_ack_raw(spmi, notify); @@ -522,14 +532,14 @@ static void apple_spmi_irq_handler(struct irq_desc *desc) } /* Other queues' responses, such as the sleep's own commands at the debug link's cut. */ if (val & ~BIT(notify % 32)) { - writel(val & ~BIT(notify % 32), spmi->regs + SPMI_IRQ_ACK_BASE + (notify / 32) * 4); + writel(val & ~BIT(notify % 32), spmi->regs + spmi->hw->irq_ack + (notify / 32) * 4); handled = true; } for (offset = 0; offset < notify / 8; offset += sizeof(val)) { unsigned long stray; - val = readq(spmi->regs + SPMI_IRQ_ACK_BASE + offset); + val = readq(spmi->regs + spmi->hw->irq_ack + offset); raw_pending |= !!val; /* * After a real sleep, sources no driver uses come up pending (on the Neo the @@ -540,8 +550,8 @@ static void apple_spmi_irq_handler(struct irq_desc *desc) */ stray = val & ~spmi->irq_used[offset / sizeof(val)]; if (stray) { - writel(lower_32_bits(stray), spmi->regs + SPMI_IRQ_ACK_BASE + offset); - writel(upper_32_bits(stray), spmi->regs + SPMI_IRQ_ACK_BASE + offset + 4); + writel(lower_32_bits(stray), spmi->regs + spmi->hw->irq_ack + offset); + writel(upper_32_bits(stray), spmi->regs + spmi->hw->irq_ack + offset + 4); handled = true; } if (val & spmi->irq_used[offset / sizeof(val)] & @@ -571,7 +581,7 @@ static void apple_spmi_irq_handler(struct irq_desc *desc) * unmasked, or it fires again for what was just cleared. */ if (handled) - readl(spmi->regs + SPMI_IRQ_ACK_BASE); + readl(spmi->regs + spmi->hw->irq_ack); chained_irq_exit(chip, desc); } @@ -579,8 +589,9 @@ static void apple_spmi_teardown_irq(void *data) { struct apple_spmi *spmi = data; - for (size_t offset = 0; offset < (spmi->hw->num_irqs + 32) / 8; offset += 4) - writel(0, spmi->regs + SPMI_IRQ_MASK_BASE + offset); + for (size_t offset = 0; offset < spmi->num_irqs / 8 + (spmi->hw->legacy_irqs ? 4 : 0); + offset += 4) + writel(0, spmi->regs + spmi->hw->irq_mask + offset); synchronize_irq(spmi->irq); irq_set_chained_handler_and_data(spmi->irq, NULL, NULL); @@ -599,9 +610,10 @@ static int apple_spmi_init_irq(struct platform_device *pdev, raw_spin_lock_init(&spmi->irq_mask_lock); - for (size_t offset = 0; offset < (spmi->hw->num_irqs + 32) / 8; offset += 4) { - writel(0, spmi->regs + SPMI_IRQ_MASK_BASE + offset); - writel(U32_MAX, spmi->regs + SPMI_IRQ_ACK_BASE + offset); + for (size_t offset = 0; offset < spmi->num_irqs / 8 + (spmi->hw->legacy_irqs ? 4 : 0); + offset += 4) { + writel(0, spmi->regs + spmi->hw->irq_mask + offset); + writel(U32_MAX, spmi->regs + spmi->hw->irq_ack + offset); } spmi->irqd = devm_irq_domain_instantiate(&pdev->dev, &info); @@ -613,8 +625,10 @@ static int apple_spmi_init_irq(struct platform_device *pdev, return ret; irq_set_chained_handler_and_data(spmi->irq, apple_spmi_irq_handler, spmi); - apple_spmi_irq_unmask_raw(spmi, spmi->hw->num_irqs); - spmi->notify_irq = true; + if (spmi->hw->legacy_irqs) { + apple_spmi_irq_unmask_raw(spmi, spmi->num_irqs); + spmi->notify_irq = true; + } return 0; } @@ -639,8 +653,8 @@ static int apple_spmi_suspend_noirq(struct device *dev) spmi->notify_irq = false; spmi->notify_parked = true; raw_spin_lock_irqsave(&spmi->irq_mask_lock, flags); - apple_spmi_irq_mask_raw(spmi, spmi->hw->num_irqs); - apple_spmi_irq_ack_raw(spmi, spmi->hw->num_irqs); + apple_spmi_irq_mask_raw(spmi, spmi->num_irqs); + apple_spmi_irq_ack_raw(spmi, spmi->num_irqs); raw_spin_unlock_irqrestore(&spmi->irq_mask_lock, flags); return 0; @@ -653,19 +667,45 @@ static int apple_spmi_resume_noirq(struct device *dev) unsigned long flags; size_t i; - if (!spmi->notify_parked) + if (!spmi->notify_parked) { + /* Gen 4 never parks the notification, but a firmware sleep entry writes the mask bank itself. */ + if (spmi->hw->legacy_irqs || !spmi->irqd || !pm_resume_via_firmware()) + return 0; + raw_spin_lock_irqsave(&spmi->irq_mask_lock, flags); + bitmap_to_arr32(words, spmi->irq_mask_cache, spmi->num_irqs); + for (i = 0; i < spmi->num_irqs / 32; i++) + writel(words[i], spmi->regs + spmi->hw->irq_mask + i * 4); + raw_spin_unlock_irqrestore(&spmi->irq_mask_lock, flags); return 0; + } guard(mutex)(&spmi->fifo_lock); + /* + * Firmware and the platform's sleep code use this queue while Linux is + * away. Every command of ours was answered before the suspend, so any + * reply waiting now is someone else's, and would be read as the reply + * to our next command. + */ + if (pm_resume_via_firmware()) { + unsigned int stale = 0; + + while (!(readl(spmi->regs + spmi->hw->status) & spmi->hw->rx_empty) && + stale < 64) { + readl(spmi->regs + spmi->hw->reply); + stale++; + } + if (stale) + dev_info(dev, "dropped %u stale reply words after the wake\n", stale); + } raw_spin_lock_irqsave(&spmi->irq_mask_lock, flags); /* Whether the enables survive a real sleep has not been measured. */ if (pm_resume_via_firmware()) { - bitmap_to_arr32(words, spmi->irq_mask_cache, spmi->hw->num_irqs); - for (i = 0; i < spmi->hw->num_irqs / 32; i++) - writel(words[i], spmi->regs + SPMI_IRQ_MASK_BASE + i * 4); + bitmap_to_arr32(words, spmi->irq_mask_cache, spmi->num_irqs); + for (i = 0; i < spmi->num_irqs / 32; i++) + writel(words[i], spmi->regs + spmi->hw->irq_mask + i * 4); } - apple_spmi_irq_ack_raw(spmi, spmi->hw->num_irqs); - apple_spmi_irq_unmask_raw(spmi, spmi->hw->num_irqs); + apple_spmi_irq_ack_raw(spmi, spmi->num_irqs); + apple_spmi_irq_unmask_raw(spmi, spmi->num_irqs); raw_spin_unlock_irqrestore(&spmi->irq_mask_lock, flags); spmi->notify_parked = false; spmi->notify_irq = true; @@ -687,9 +727,34 @@ static int apple_spmi_probe(struct platform_device *pdev) return -ENOMEM; spmi = spmi_controller_get_drvdata(ctrl); + spmi->dev = &pdev->dev; spmi->hw = device_get_match_data(&pdev->dev); if (!spmi->hw) return -EINVAL; + spmi->num_irqs = spmi->hw->num_irqs; + if (spmi->hw->legacy_irqs) { + u32 response_vector; + + ret = of_property_read_u32(pdev->dev.of_node, + "apple,response-vector", + &response_vector); + if (!ret) { + if (!response_vector || + response_vector > SPMI_MAX_PERIPHERAL_IRQS || + response_vector % 64) + return dev_err_probe(&pdev->dev, -EINVAL, + "invalid apple,response-vector %u\n", + response_vector); + spmi->num_irqs = response_vector; + } else if (ret != -EINVAL) { + return dev_err_probe(&pdev->dev, ret, + "failed to read apple,response-vector\n"); + } + } else if (of_property_present(pdev->dev.of_node, + "apple,response-vector")) { + dev_warn(&pdev->dev, + "ignoring apple,response-vector on generation 4 controller\n"); + } mutex_init(&spmi->fifo_lock); init_completion(&spmi->fifo_rx); platform_set_drvdata(pdev, spmi); @@ -715,9 +780,6 @@ static int apple_spmi_probe(struct platform_device *pdev) if (spmi->irq < 0 && spmi->irq != -ENXIO) return spmi->irq; if (spmi->irq >= 0) { - if (!spmi->hw->legacy_irqs) - return dev_err_probe(&pdev->dev, -EOPNOTSUPP, - "Generation 4 interrupt layout is not supported\n"); ret = apple_spmi_init_irq(pdev, spmi, spmi->irq); if (ret) return ret; diff --git a/drivers/spmi/spmi-apple-irq.h b/drivers/spmi/spmi-apple-irq.h new file mode 100644 index 00000000000000..4134ef37ff369b --- /dev/null +++ b/drivers/spmi/spmi-apple-irq.h @@ -0,0 +1,36 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * Apple SPMI controller interrupt register layout. + * + * Peripheral sources 0..255 come first, then the RX FIFO notification (256) and + * the controller's own fault sources. Source n sits in bit n % 32 of word n / 32 + * of both the mask bank and the ack/pending bank. + */ +#ifndef _SPMI_APPLE_IRQ_H +#define _SPMI_APPLE_IRQ_H + +/* Generation 1 (T8103, T6000) */ +#define APPLE_SPMI_GEN1_IRQ_MASK 0x20 +#define APPLE_SPMI_GEN1_IRQ_ACK 0x60 + +/* + * Generation 4 (T8142, T6050): ack and pending words from 0x600, the fault source + * 263 acked at 0x620 bit 7 (traced from macOS under the hypervisor). The mask bank + * is at 0x400 (see APPLE_SPMI_GEN4_IRQ_MASK). + */ +#define APPLE_SPMI_GEN4_IRQ_ACK 0x600 +#define APPLE_SPMI_GEN4_FAULT_IRQ (256 + 7) +/* Mask bank mirrors the ack bank 0x200 below; +0x400..0x41c toggle on K114c, +0x420 does not. */ +#define APPLE_SPMI_GEN4_IRQ_MASK 0x400 + +static inline u32 apple_spmi_irq_reg(u32 base, u32 irq) +{ + return base + (irq / 32) * 4; +} + +static inline u32 apple_spmi_irq_bit(u32 irq) +{ + return BIT(irq % 32); +} + +#endif /* _SPMI_APPLE_IRQ_H */ diff --git a/drivers/thermal/apple-pmp-policy-test.c b/drivers/thermal/apple-pmp-policy-test.c index b1786634b89f83..691af74c91e921 100644 --- a/drivers/thermal/apple-pmp-policy-test.c +++ b/drivers/thermal/apple-pmp-policy-test.c @@ -153,6 +153,95 @@ static void apple_pmp_test_gpu_attachment(struct kunit *test) KUNIT_EXPECT_EQ(test, state.level[2], 0U); } +static void apple_pmp_test_unbudgeted(struct kunit *test) +{ + struct apple_pmp_power_policy state; + u32 rails[3] = {20000, 4000, 12000}; + unsigned long long now = 0; + unsigned int i; + + apple_pmp_power_init_unbudgeted(&state); + apple_pmp_power_set_active(&state, 7); + /* A cool start grants no burst credit; restricted until confirmed. */ + for (i = 1; i <= 3; i++) + apple_pmp_power_sample(&state, now += 500000000ULL, rails, 50000, 0); + KUNIT_EXPECT_FALSE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.credit_mj, 0LL); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 23U); + /* Then one step per second, however hot and loaded. */ + for (i = 0; i < 20; i++) + apple_pmp_power_sample(&state, now += 500000000ULL, rails, 105000, 0); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 13U); + /* Sustained heavy load on a hot die never restricts again. */ + for (i = 0; i < 1200; i++) + apple_pmp_power_sample(&state, now += 500000000ULL, rails, 105000, 0); + KUNIT_EXPECT_EQ(test, state.total_mw, 36000); + KUNIT_EXPECT_EQ(test, state.level[0], 0U); + KUNIT_EXPECT_EQ(test, state.level[1], 0U); + KUNIT_EXPECT_EQ(test, state.level[2], 0U); + KUNIT_EXPECT_EQ(test, state.credit_mj, 0LL); + /* A rail fault still selects full protection. */ + apple_pmp_power_sample(&state, now += 500000000ULL, rails, 105000, -EIO); + KUNIT_EXPECT_TRUE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.level[0], 8U); + KUNIT_EXPECT_EQ(test, state.level[2], 8U); + /* Recovery: three good samples, then one step per second. */ + for (i = 0; i < 22; i++) + apple_pmp_power_sample(&state, now += 500000000ULL, rails, 105000, 0); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 14U); + for (i = 0; i < 38; i++) + apple_pmp_power_sample(&state, now += 500000000ULL, rails, 105000, 0); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 0U); + /* A telemetry gap also selects full protection. */ + apple_pmp_power_sample(&state, now += 2500000000ULL, rails, 105000, 0); + KUNIT_EXPECT_TRUE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.level[1], 8U); +} + +static void apple_pmp_test_unbudgeted_dark(struct kunit *test) +{ + struct apple_pmp_power_policy state, budgeted; + u32 rails[3] = {400, 200, 100}; + u32 load[3] = {15000, 3000, 0}; + unsigned long long now = 0; + unsigned int i; + + apple_pmp_power_init_unbudgeted(&state); + apple_pmp_power_set_active(&state, 7); + for (i = 0; i < 60; i++) + apple_pmp_power_sample(&state, now += 500000000ULL, load, 60000, 0); + KUNIT_EXPECT_FALSE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 0U); + /* A 10 s dark-sensor span keeps rail telemetry fresh without clamping. */ + for (i = 0; i < 20; i++) + apple_pmp_power_dark(&state, now += 500000000ULL, rails); + KUNIT_EXPECT_FALSE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.last_ns, now); + KUNIT_EXPECT_EQ(test, state.total_mw, 700); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 0U); + apple_pmp_power_sample(&state, now += 500000000ULL, load, 65000, 0); + KUNIT_EXPECT_FALSE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 0U); + /* A genuine >2 s gap while dark still fails closed. */ + apple_pmp_power_dark(&state, now += 2500000000ULL, rails); + KUNIT_EXPECT_TRUE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.level[0], 8U); + KUNIT_EXPECT_EQ(test, state.level[1], 8U); + KUNIT_EXPECT_EQ(test, state.level[2], 8U); + /* Dark samples never clear a latched fault or release levels. */ + for (i = 0; i < 10; i++) + apple_pmp_power_dark(&state, now += 500000000ULL, rails); + KUNIT_EXPECT_TRUE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 24U); + /* On a budgeted (Air) policy, apple_pmp_power_dark() is a no-op. */ + apple_pmp_power_init(&budgeted); + apple_pmp_power_set_active(&budgeted, 3); + apple_pmp_power_sample(&budgeted, 500000000ULL, load, 60000, 0); + apple_pmp_power_dark(&budgeted, 1000000000ULL, rails); + KUNIT_EXPECT_EQ(test, budgeted.last_ns, 500000000ULL); + KUNIT_EXPECT_EQ(test, budgeted.total_mw, 18000); +} + static struct kunit_case apple_pmp_policy_cases[] = { KUNIT_CASE(apple_pmp_test_fault_recovery), KUNIT_CASE(apple_pmp_test_poll_cadence), @@ -161,6 +250,8 @@ static struct kunit_case apple_pmp_policy_cases[] = { KUNIT_CASE(apple_pmp_test_gpu_budget_freshness), KUNIT_CASE(apple_pmp_test_shared_power_arbitration), KUNIT_CASE(apple_pmp_test_gpu_attachment), + KUNIT_CASE(apple_pmp_test_unbudgeted), + KUNIT_CASE(apple_pmp_test_unbudgeted_dark), {}, }; diff --git a/drivers/thermal/apple-pmp-thermal.c b/drivers/thermal/apple-pmp-thermal.c index 1801153f2bb1e7..67a29098206f65 100644 --- a/drivers/thermal/apple-pmp-thermal.c +++ b/drivers/thermal/apple-pmp-thermal.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -27,7 +28,6 @@ #include #include #include -#include #include #include #include @@ -98,11 +98,12 @@ static int apple_pmp_power_status(char *buffer, const struct kernel_param *kp) guard(mutex)(&pmp_thermal.lock); return scnprintf(buffer, PAGE_SIZE, - "ns=%llu p_mw=%u e_mw=%u gpu_mw=%u total_mw=%d sustainable_mw=%d allowed_mw=%d credit_mj=%lld filtered_mc=%d p_level=%u e_level=%u gpu_level=%u fault=%d error=%d\n", + "ns=%llu p_mw=%u e_mw=%u gpu_mw=%u total_mw=%d sustainable_mw=%d allowed_mw=%d credit_mj=%lld filtered_mc=%d p_level=%u e_level=%u gpu_level=%u fault=%d error=%d budget=%d\n", p->last_ns, pmp_thermal.rail_mw[0], pmp_thermal.rail_mw[1], pmp_thermal.rail_mw[2], p->total_mw, p->sustainable_mw, p->allowed_mw, p->credit_mj, p->filtered_mc, - p->level[0], p->level[1], p->level[2], p->fault, pmp_thermal.power_error); + p->level[0], p->level[1], p->level[2], p->fault, pmp_thermal.power_error, + !p->unbudgeted); } static const struct kernel_param_ops apple_pmp_power_status_ops = { .get = apple_pmp_power_status, @@ -183,7 +184,9 @@ static void apple_pmp_power_work(struct work_struct *work) u64 epoch = apple_pmp_gpu_epoch(pmp_thermal.sensors); bool dark = false; u64 now; - int ret = apple_pmp_power_read_rails(mw); + int ret; + + ret = apple_pmp_power_read_rails(mw); /* The running reader cannot read zero on both CPU rails. A firmware * reset/all-zero image must not refill the energy bucket; an idle * system may still draw well under 0.1 W on all three rails. @@ -226,8 +229,13 @@ static void apple_pmp_power_work(struct work_struct *work) /* * Nothing else restricts the GPU's budget while the sensors are * dark: a zero publication selects full protection, and the next - * real budget sample republishes its level at once. + * real budget sample republishes its level at once. On fan-cooled + * boards there is no temperature-driven energy budget, so keep + * rail freshness and hwmon totals current while dark instead of + * turning a >2 s dark span into a fault clamp on wake. */ + if (p->unbudgeted) + apple_pmp_power_dark(p, now, mw); apple_pmp_gpu_publish(pmp_thermal.sensors, epoch, 8, 0); } else { apple_pmp_power_sample(p, now, mw, pmp_thermal.cached_mc, ret); @@ -260,7 +268,8 @@ static int apple_pmp_power_read(struct device *dev, enum hwmon_sensor_types type if (pmp_thermal.power.fault || pmp_thermal.power_error || ktime_get_ns() - pmp_thermal.power.last_ns > APPLE_PMP_POWER_STALE_NS) return -EAGAIN; - *value = 1000L * (channel == 3 ? pmp_thermal.power.total_mw : pmp_thermal.rail_mw[channel]); + *value = 1000L * (channel == 3 ? pmp_thermal.power.total_mw : + pmp_thermal.rail_mw[channel]); return 0; } @@ -273,7 +282,8 @@ static int apple_pmp_power_label(struct device *dev, enum hwmon_sensor_types typ }; if (type != hwmon_power || channel < 0 || channel > 3) return -EINVAL; - *label = labels[channel]; + *label = channel == 3 && pmp_thermal.power.unbudgeted ? + "CPU/GPU rail sum" : labels[channel]; return 0; } static const struct hwmon_ops apple_pmp_power_ops = { @@ -398,9 +408,9 @@ static int apple_pmp_sample(void) if (!ret) { pmp_thermal.valid_ns = snapshot.finished_ns; pmp_thermal.valid_mc = value; - } else if (ret == -ENODATA && pmp_thermal.valid_ns && - snapshot.finished_ns - pmp_thermal.valid_ns < APPLE_PMP_GATED_HOLD_NS && - pmp_thermal.valid_mc < APPLE_PMP_GATED_HOLD_MC) { + } else if (ret == -ENODATA && + apple_pmp_hold_nodata(pmp_thermal.valid_ns, pmp_thermal.valid_mc, + snapshot.finished_ns, false)) { value = pmp_thermal.valid_mc; ret = 0; } @@ -674,21 +684,138 @@ static void apple_pmp_thermal_cleanup(void) pmp_thermal.ready = false; } -static int apple_pmp_add_cluster(unsigned int index, unsigned int cpu, - unsigned long members) +static int apple_pmp_policy_info(struct cpufreq_policy *policy, + u32 *capacity, unsigned int *max_freq) { - struct apple_pmp_cluster *c = &pmp_thermal.clusters[index]; unsigned int n; - int ret; + bool have_cap = false; + u32 cap = 0; - c->policy = cpufreq_cpu_get(cpu); - if (!c->policy) + guard(cpufreq_policy_read)(policy); + if (!policy->freq_table) return -EPROBE_DEFER; - guard(cpufreq_policy_read)(c->policy); - for_each_possible_cpu(n) - if (cpumask_test_cpu(n, c->policy->related_cpus) != - (n < BITS_PER_LONG && !!(members & BIT(n)))) + if (cpumask_empty(policy->related_cpus)) + return -EINVAL; + for_each_cpu(n, policy->related_cpus) { + struct device_node *np = of_cpu_device_node_get(n); + u32 cpu_cap; + int ret; + + if (!np) + return -ENODEV; + ret = of_property_read_u32(np, "capacity-dmips-mhz", &cpu_cap); + of_node_put(np); + if (ret || !cpu_cap) + return -EINVAL; + if (!have_cap) { + cap = cpu_cap; + have_cap = true; + } else if (cpu_cap != cap) { return -EINVAL; + } + } + *capacity = cap; + *max_freq = policy->cpuinfo.max_freq; + return 0; +} + +/* + * Logical CPU numbering follows the boot CPU and device-tree order, so + * cluster masks vary across boards and boot paths. Discover the two + * cpufreq policies from the live topology, verify they partition every + * possible CPU with uniform DT capacity per cluster, and order P before E + * so cluster indices match the PP0b (P) and PPbb (E) power rails. + */ +static int apple_pmp_discover_clusters(struct cpufreq_policy *ordered[2]) +{ + struct cpufreq_policy *found[2] = {}; + unsigned int max_freq[2] = {}; + u32 cap[2] = {}; + unsigned int cpu, count = 0, i; + bool cap_gt, freq_gt; + int ret; + + for_each_online_cpu(cpu) { + struct cpufreq_policy *policy; + bool seen = false; + + for (i = 0; i < count; i++) { + guard(cpufreq_policy_read)(found[i]); + if (cpumask_test_cpu(cpu, found[i]->related_cpus)) { + seen = true; + break; + } + } + if (seen) + continue; + + policy = cpufreq_cpu_get(cpu); + if (!policy) { + ret = -EPROBE_DEFER; + goto err; + } + for (i = 0; i < count; i++) { + if (found[i] == policy) { + cpufreq_cpu_put(policy); + seen = true; + break; + } + } + if (seen) + continue; + if (count >= ARRAY_SIZE(found)) { + cpufreq_cpu_put(policy); + ret = -EINVAL; + goto err; + } + ret = apple_pmp_policy_info(policy, &cap[count], &max_freq[count]); + if (ret) { + cpufreq_cpu_put(policy); + goto err; + } + found[count++] = policy; + } + + for_each_possible_cpu(cpu) { + unsigned int matches = 0; + + for (i = 0; i < count; i++) { + guard(cpufreq_policy_read)(found[i]); + if (cpumask_test_cpu(cpu, found[i]->related_cpus)) + matches++; + } + if (matches == 0) { + ret = -EPROBE_DEFER; + goto err; + } + if (matches != 1) { + ret = -EINVAL; + goto err; + } + } + cap_gt = cap[0] > cap[1]; + freq_gt = max_freq[0] > max_freq[1]; + if (count != ARRAY_SIZE(found) || cap[0] == cap[1] || + max_freq[0] == max_freq[1] || cap_gt != freq_gt) { + ret = -EINVAL; + goto err; + } + ordered[0] = cap_gt ? found[0] : found[1]; + ordered[1] = cap_gt ? found[1] : found[0]; + return 0; + +err: + for (i = 0; i < count; i++) + cpufreq_cpu_put(found[i]); + return ret; +} + +static int apple_pmp_add_cluster(unsigned int index) +{ + struct apple_pmp_cluster *c = &pmp_thermal.clusters[index]; + int ret; + + guard(cpufreq_policy_read)(c->policy); if (!c->policy->freq_table) return -EPROBE_DEFER; @@ -705,28 +832,47 @@ static int apple_pmp_add_cluster(unsigned int index, unsigned int cpu, return 0; } +/* + * A board whose available SMC hwmon node describes an available fan (a child + * with apple,fan-maximum) is fan cooled: the SMC appears to set the fan speed + * from the heat the SoC makes, so the fanless Airs' energy budget would + * starve the fan. The die guard below applies unchanged. + */ +static bool apple_pmp_unbudgeted(void) +{ + for_each_compatible_node_scoped(hwmon, NULL, "apple,smc-hwmon") { + if (!of_device_is_available(hwmon)) + continue; + for_each_available_child_of_node_scoped(hwmon, child) + if (of_property_present(child, "apple,fan-maximum")) + return true; + } + return false; +} + static int apple_pmp_thermal_setup(void) { + struct cpufreq_policy *policies[2]; struct thermal_zone_device *zone; - unsigned long p_members = BIT(0) | GENMASK(9, 7); - unsigned long e_members = GENMASK(6, 1); unsigned int i; int ret; - /* J773g numbers the four P cores 0,3-5 and the six E cores 1-2,6-9. */ - if (of_machine_is_compatible("apple,j773g")) { - p_members = BIT(0) | GENMASK(5, 3); - e_members = GENMASK(2, 1) | GENMASK(9, 6); - } - apple_pmp_power_init(&pmp_thermal.power); + ret = apple_pmp_discover_clusters(policies); + if (ret) + return ret; + for (i = 0; i < ARRAY_SIZE(pmp_thermal.clusters); i++) + pmp_thermal.clusters[i].policy = policies[i]; + if (apple_pmp_unbudgeted()) + apple_pmp_power_init_unbudgeted(&pmp_thermal.power); + else + apple_pmp_power_init(&pmp_thermal.power); apple_pmp_cooling_init(&pmp_thermal.cooling); pmp_thermal.guard_level = 8; - ret = apple_pmp_add_cluster(0, 0, p_members); - if (ret) - goto fail; - ret = apple_pmp_add_cluster(1, 1, e_members); - if (ret) - goto fail; + for (i = 0; i < ARRAY_SIZE(pmp_thermal.clusters); i++) { + ret = apple_pmp_add_cluster(i); + if (ret) + goto fail; + } zone = thermal_zone_device_register_with_trips("apple-pmp-die", apple_pmp_trips, ARRAY_SIZE(apple_pmp_trips), NULL, &apple_pmp_thermal_ops, &apple_pmp_params, @@ -767,7 +913,10 @@ static int apple_pmp_thermal_setup(void) if (ret) goto fail; } - pr_info("apple-pmp-thermal: T8132 provisional policy: CPU/GPU cooling from 106 C, target 110 C, full protection 115 C, three >=120 C samples for shutdown, 5 ms sampling from 95 C or while cooling (100 ms below), 100 ms governor, shared measured-rail power budget\n"); + pr_info("apple-pmp-thermal: T8132 provisional policy: CPU/GPU cooling from 106 C, target 110 C, full protection 115 C, three >=120 C samples for shutdown, 5 ms sampling from 95 C or while cooling (100 ms below), 100 ms governor, %s\n", + pmp_thermal.power.unbudgeted ? + "no power budget (fan cooled; rail faults still restrict)" : + "shared measured-rail power budget"); pmp_thermal.ready = true; return 0; fail: @@ -793,11 +942,11 @@ static int apple_pmp_thermal_probe(struct platform_device *pdev) { const struct apple_pmp_sensor_data *sensors = dev_get_platdata(&pdev->dev); - /* The M4 PMP sensor records and the Airs' fanless policy are qualified. */ - if (!apple_t8132_firmware_path()) - return -ENODEV; if (!sensors || !sensors->read || !sensors->dev) return -EINVAL; + /* The M4 PMP's sensor records, found by name in its own image. */ + if (!of_device_is_compatible(sensors->dev->of_node, "apple,t8132-pmp-v2")) + return -ENODEV; pmp_thermal.sensors = sensors; pmp_thermal.cached_error = -EAGAIN; pmp_thermal.power_error = -EAGAIN; @@ -842,9 +991,11 @@ static void apple_pmp_thermal_complete(struct device *dev) return; pmp_thermal.sleep_paused = false; scoped_guard(mutex, &pmp_thermal.lock) { + u64 now = ktime_get_ns(); + /* The sleep is no telemetry gap, nor cool time to refill the bucket. */ if (p->last_ns) - p->last_ns = ktime_get_ns(); + p->last_ns = now; if (p->active & BIT(2)) apple_pmp_gpu_publish(pmp_thermal.sensors, pmp_thermal.gpu_epoch, p->level[2], p->last_ns); @@ -867,9 +1018,24 @@ static void apple_pmp_thermal_remove(struct platform_device *pdev) apple_pmp_thermal_cleanup(); } +/* + * A reboot or power-off tells the SMC the system is going down and then puts it + * in atomic mode, which fails every ordinary read with -EIO. Left running, the + * power reader logs an error every 500 ms until the machine resets, burying + * whatever a stalled shutdown printed. Stop the reader. Its budgets go stale as + * they would after failed reads, so the CPU/GPU fall back to their minimum + * ceilings; the die sampler keeps running. + */ +static void apple_pmp_thermal_shutdown(struct platform_device *pdev) +{ + cancel_delayed_work_sync(&pmp_thermal.setup_work); + cancel_delayed_work_sync(&pmp_thermal.power_work); +} + static struct platform_driver apple_pmp_thermal_driver = { .probe = apple_pmp_thermal_probe, .remove = apple_pmp_thermal_remove, + .shutdown = apple_pmp_thermal_shutdown, .driver = { .name = "apple-pmp-thermal", .pm = pm_sleep_ptr(&apple_pmp_thermal_pm_ops), diff --git a/drivers/thermal/thermal_core.c b/drivers/thermal/thermal_core.c index 1bd642179e4fd3..77481eea5436e0 100644 --- a/drivers/thermal/thermal_core.c +++ b/drivers/thermal/thermal_core.c @@ -1726,9 +1726,11 @@ struct thermal_zone_device *thermal_zone_get_zone_by_name(const char *name) EXPORT_SYMBOL_GPL(thermal_zone_get_zone_by_name); /** - * thermal_zone_get_temp_by_name() - sample a uniquely named registered zone + * thermal_zone_get_temp_and_trips() - sample a uniquely named registered zone * @name: thermal zone name * @temp: destination for the temperature in millidegrees Celsius + * @cb: optional callback for each trip of the sampled zone, under the zone lock + * @data: private data passed to @cb * * Acquire the zone device reference under the registry lock, as in * thermal_zone_get_by_id(). Removal waits for device references before freeing @@ -1736,9 +1738,11 @@ EXPORT_SYMBOL_GPL(thermal_zone_get_zone_by_name); * No borrowed thermal-zone pointer escapes to the caller. * * Return: 0 on success, -EINVAL for invalid arguments, -ENODEV for no match, - * -EEXIST for duplicate names, or the temperature read error. + * -EEXIST for duplicate names, or the error from the temperature read or trip callback. */ -int thermal_zone_get_temp_by_name(const char *name, int *temp) +int thermal_zone_get_temp_and_trips(const char *name, int *temp, + int (*cb)(struct thermal_trip *, void *), + void *data) { struct thermal_zone_device *pos, *zone = NULL; int ret; @@ -1762,9 +1766,17 @@ int thermal_zone_get_temp_by_name(const char *name, int *temp) } ret = thermal_zone_get_temp(zone, temp); + if (!ret && cb) + ret = thermal_zone_for_each_trip(zone, cb, data); put_device(&zone->device); return ret; } +EXPORT_SYMBOL_GPL(thermal_zone_get_temp_and_trips); + +int thermal_zone_get_temp_by_name(const char *name, int *temp) +{ + return thermal_zone_get_temp_and_trips(name, temp, NULL, NULL); +} EXPORT_SYMBOL_GPL(thermal_zone_get_temp_by_name); static void thermal_zone_device_resume(struct work_struct *work) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index e21cf99212ebae..cb3a94977182ac 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -95,6 +95,7 @@ #include #include #include +#include #include #include #include @@ -171,10 +172,55 @@ struct apple_cio_hw { bool gen4_link_recovery; /* Leave the host router's TMU to its firmware; host TMU constants. */ bool host_tmu; + /* Drain PSD runtime power-off before the PHY is reset or reused. */ + bool psd_power_cycle; + /* Stop a started router before a reboot shuts its PCIe and DARTs down. */ + bool stop_at_reboot; + /* + * Put the host router into ACIO sleep before powering off its domains, + * and detach the RTKit mailbox before freeing it. + */ + bool sleep_router_on_stop; + /* Deep sleep removes the CIO domains, including an attached router. */ + bool sleep_removes_domains; + /* Start the router again at once after a wake. */ + bool restart_on_wake; + /* + * The PHY is shared with DWC3: release PCIe, or refuse the sleep, + * before DWC3's default-priority PM notifier queues its PHY shutdown. + */ + bool phy_shared_with_dwc3; const struct apple_dpin_policy *dp; }; +/* + * T8103 deep sleep removes the CIO power domains and shares the ATC PHY with + * DWC3. Tear down a connected router before tasks freeze (ahead of DWC3's PM + * notifier) and request fresh cable state immediately on wake; s2idle and + * freeze leave the port up. Put the host router into ACIO sleep before + * powering off the CIO power domain, and stop a started router before reboot. + */ static const struct apple_cio_hw apple_cio_t8103_hw = { + .sleep_removes_domains = true, + .restart_on_wake = true, + .phy_shared_with_dwc3 = true, + .psd_power_cycle = true, + .stop_at_reboot = true, + .sleep_router_on_stop = true, + .dp = &apple_dpin_m1, +}; + +/* + * T8122 shares the T8103 ACIO register layout and DP IN policy, while deep + * sleep removes the CIO power domains and shares the ATC PHY with DWC3. Tear + * down a connected router before tasks freeze (ahead of DWC3's PM notifier) + * and request fresh cable state immediately on wake; s2idle and freeze leave + * the port up. + */ +static const struct apple_cio_hw apple_cio_t8122_hw = { + .sleep_removes_domains = true, + .restart_on_wake = true, + .phy_shared_with_dwc3 = true, .dp = &apple_dpin_m1, }; @@ -206,9 +252,34 @@ static const struct apple_cio_hw apple_cio_t8132_hw = { .dp = &apple_dpin_m4, }; -/* Type 7 uses its existing ready-state check and has no qualified DP route. */ +/* MXWrap-v2p3 is started by reconfiguration, using its counted mailbox. */ +static const struct apple_cio_hw apple_cio_t8152_hw = { + .psd_power_cycle = true, + .stop_at_reboot = true, + .type7 = true, + .lstx_after_boot = true, + .strict_fw_ready = true, + .no_host_clx = true, + .no_asym = true, + .dp = &apple_dpin_disabled, +}; + +/* + * T8142 has a Type 7 router with an MxWrap CPU already running after CIO + * reset. Hand LSTX to firmware only after RTKit is ready. DP IN is not yet + * qualified; the connector's DisplayPort alternate mode is independent. + */ static const struct apple_cio_hw apple_cio_t8142_hw = { + .mxwrap = true, .type7 = true, + .lstx_explicit = true, + .skip_run = true, + .lstx_after_boot = true, + .strict_fw_ready = true, + .no_host_clx = true, + .sleep_removes_domains = true, + .restart_on_wake = true, + .phy_shared_with_dwc3 = true, .dp = &apple_dpin_disabled, }; @@ -245,7 +316,8 @@ static const struct apple_cio_hw apple_cio_t6040_hw = { .lstx_after_boot = true, .strict_fw_ready = true, .no_host_clx = true, - .dp = &apple_dpin_disabled, + /* The T8132 (M4) DP IN flow; the PHY's AUSPLL is the pixel clock. */ + .dp = &apple_dpin_m4, }; #define APPLE_CIO_NHI_HOP_COUNT 0x0 @@ -497,9 +569,10 @@ struct apple_cio { unsigned int start_gen; /* protected by lock: bumped by every start */ unsigned int link_lost_gen; /* start_gen when the peer went away */ unsigned int link_lost_cycles; /* protected by lock */ - u64 link_lost_cycle_activity; /* remote activity at the last cycle */ + u64 link_lost_cycle_activity; /* remote activity of this domain at the last cycle */ bool link_lost_restart; /* protected by lock: cycle requested */ struct notifier_block pm_notifier; + struct notifier_block reboot_notifier; /* * T6050: the displays behind this port go at the start of the sleep's entry, before any * port's power-off. @sleep_dp_paused: this entry closed the DP IN admission; @@ -630,6 +703,9 @@ static const struct of_device_id apple_dpin_qualified_soc[] = { { .compatible = "apple,t6021" }, { .compatible = "apple,t6030" }, { .compatible = "apple,t8132" }, + /* T6040/T6041 (M4 Pro/Max): M4 DP IN flow, PHY tunnel pixel clock */ + { .compatible = "apple,t6040" }, + { .compatible = "apple,t6041" }, /* T6050: t8103 DP IN handshake, M3 flow, four DP IN adapters */ { .compatible = "apple,t6050" }, {}, @@ -1305,10 +1381,12 @@ static void apple_cio_of_node_put(void *data) static bool apple_cio_pciec_eligible(const struct device_node *np) { - return of_device_is_compatible(np, "apple,t6040-pciec") || + return of_device_is_compatible(np, "apple,t8152-pciec") || + of_device_is_compatible(np, "apple,t6040-pciec") || of_device_is_compatible(np, "apple,t8103-pciec") || of_device_is_compatible(np, "apple,t6000-pciec") || - of_device_is_compatible(np, "apple,t6050-pciec"); + of_device_is_compatible(np, "apple,t6050-pciec") || + of_device_is_compatible(np, "apple,t8142-pciec"); } static bool @@ -1475,6 +1553,7 @@ struct apple_nhi { }; static int apple_nhi_cio_bind(struct apple_nhi *anhi); +static int apple_nhi_cio_router_sleep(struct tb_nhi *nhi); static int apple_nhi_cio_prepare(struct apple_nhi *anhi); static int apple_nhi_cio_suspend(struct apple_nhi *anhi); static int apple_nhi_cio_resume(struct apple_nhi *anhi); @@ -2015,13 +2094,16 @@ static int apple_nhi_pci_tunnel_post_activate(struct tb_nhi *nhi) return 0; } -static void apple_cio_stop_pcie_tunnel(struct apple_cio *acio) +/* Returns whether a tunnel was requested, for apple_cio_reopen_pcie_tunnel(). */ +static bool apple_cio_stop_pcie_tunnel(struct apple_cio *acio) { + bool requested; int ret; /* Block new requests before draining work, without nesting tb->lock. */ mutex_lock(&acio->pcie_tunnel_lock); acio->pcie_tunnel_stopping = true; + requested = READ_ONCE(acio->pcie_tunnel_requested); WRITE_ONCE(acio->pcie_tunnel_requested, false); mutex_unlock(&acio->pcie_tunnel_lock); cancel_delayed_work_sync(&acio->pcie_tunnel_work); @@ -2033,6 +2115,24 @@ static void apple_cio_stop_pcie_tunnel(struct apple_cio *acio) if (ret) dev_warn(acio->dev, "failed to quiesce PCIe-C before NHI shutdown: %d\n", ret); + return requested; +} + +/* + * Undo apple_cio_stop_pcie_tunnel() for a port that stays up with its NHI: + * reopen admission and bring a requested tunnel's hierarchy back, as after + * a tunnel teardown (apple_cio_activate_pcie_tunnel_locked()). + */ +static void apple_cio_reopen_pcie_tunnel(struct apple_cio *acio, bool requested) +{ + guard(mutex)(&acio->pcie_tunnel_lock); + acio->pcie_tunnel_stopping = false; + if (requested) { + WRITE_ONCE(acio->pcie_tunnel_requested, true); + acio->pcie_bind_retries = APPLE_CIO_PCIE_BIND_RETRIES; + } + if (acio->pcie_quiesce_pending || READ_ONCE(acio->pcie_tunnel_requested)) + mod_delayed_work(system_freezable_wq, &acio->pcie_tunnel_work, 0); } #define APPLE_DP_AUX_POLL_MS 500 @@ -2591,7 +2691,8 @@ static int apple_nhi_probe(struct platform_device *pdev) /* The T6050 router is the Type 7 one released by a RUN store. */ if (acio->type7 != - (of_device_is_compatible(pdev->dev.of_node, "apple,t8142-usb4-nhi") || + (of_device_is_compatible(pdev->dev.of_node, "apple,t8152-usb4-nhi") || + of_device_is_compatible(pdev->dev.of_node, "apple,t8142-usb4-nhi") || of_device_is_compatible(pdev->dev.of_node, "apple,t6040-usb4-nhi") || of_device_is_compatible(pdev->dev.of_node, "apple,t6050-usb4-nhi")) || acio->hw->run_store != @@ -2669,6 +2770,7 @@ static int apple_nhi_probe(struct platform_device *pdev) spin_lock_init(&anhi->nhi.lock); anhi->nhi.iommu_dma_protection = true; + anhi->nhi.use_dma_credit_preferences = true; /* * DP tunnel display support (and with it the host DP IN handling in * the connection manager) only where it is enabled and known to work. @@ -2696,7 +2798,7 @@ static int apple_nhi_probe(struct platform_device *pdev) anhi->nhi.ring_layout = &apple_nhi_ring_layout; anhi->nhi.iobase = anhi->nhi_base; anhi->nhi.quirks = QUIRK_NO_DMA_PORT | QUIRK_NO_USB3_BW_ALLOC | - QUIRK_TMU_HIFI_BI; + QUIRK_TMU_HIFI_BI | QUIRK_NO_RETIMER_SCAN; if (anhi->nhi.host_dp_policy) anhi->nhi.quirks |= QUIRK_HOST_DP_NFC_CREDITS; if (acio->hw->no_host_clx) @@ -2752,6 +2854,13 @@ static int apple_nhi_probe(struct platform_device *pdev) acio->pcie_pm_prepared = false; acio->pcie_resume_expected = false; } + /* + * A port restart rebuilds the domain, whose remote activity count starts + * again at zero. Compare the next link loss against that, not against + * the count of the domain that went away: any discovery on this domain + * then marks the restart as having worked. + */ + WRITE_ONCE(acio->link_lost_cycle_activity, 0); ret = tb_domain_add(anhi->tb, false); if (ret) { dev_err_probe(anhi->dev, ret, "failed to add TB domain\n"); @@ -3097,6 +3206,7 @@ static const struct of_device_id apple_nhi_match[] = { { .compatible = "apple,t6050-usb4-nhi", }, + { .compatible = "apple,t8152-usb4-nhi" }, { .compatible = "apple,t8142-usb4-nhi", }, @@ -3135,9 +3245,60 @@ static struct platform_device *apple_cio_find_pcie_tunnel(struct apple_cio *acio return pdev; } -static void apple_cio_remove_children(struct apple_cio *acio) +/* + * Returns 0 once the host router is asleep, or when no router was started + * (the unwind of a start whose NHI never came up). A started port whose NHI + * is gone cannot send the request: that is an error too. + */ +static int apple_cio_sleep_router_for_stop(struct apple_cio *acio) +{ + struct platform_device *nhi_pdev; + struct apple_nhi *anhi; + int ret = acio->current_cable_info ? -ENODEV : 0; + + lockdep_assert_held(&acio->lock); + nhi_pdev = READ_ONCE(acio->nhi_pdev); + if (!nhi_pdev) + return ret; + device_lock(&nhi_pdev->dev); + if (READ_ONCE(acio->nhi_pdev) == nhi_pdev) { + anhi = platform_get_drvdata(nhi_pdev); + if (anhi && anhi->tb && anhi->tb->root_switch) { + scoped_guard(mutex, &anhi->tb->lock) + ret = apple_nhi_cio_router_sleep(&anhi->nhi); + } + } + device_unlock(&nhi_pdev->dev); + if (ret) + dev_err(acio->dev, "CIO host router did not go to sleep: %d\n", ret); + return ret; +} + +/* + * What a stop does when a host router that must sleep before its domains go + * off (sleep_router_on_stop) does not go to sleep. + */ +enum apple_cio_awake { + /* The port stays up as it was and the error is returned. */ + APPLE_CIO_AWAKE_KEEP, + /* + * The children go, the co-processor and its domains stay powered: a + * reboot or power-off, which the platform reset or power-off ends. + */ + APPLE_CIO_AWAKE_HOLD, + /* + * Power off anyway: a start's unwind frees the co-processor, and a + * removed device detaches its domains. + */ + APPLE_CIO_AWAKE_FORCE, +}; + +static int apple_cio_remove_children(struct apple_cio *acio, + enum apple_cio_awake awake) { struct platform_device *nhi_pdev; + bool pcie; + int ret = 0; lockdep_assert_held(&acio->lock); @@ -3146,7 +3307,22 @@ static void apple_cio_remove_children(struct apple_cio *acio) * across domain removal: it takes tb->lock, which tunnel callbacks hold * when they acquire pcie_tunnel_lock. */ - apple_cio_stop_pcie_tunnel(acio); + pcie = apple_cio_stop_pcie_tunnel(acio); + + /* + * Put the host router firmware into ACIO sleep before tearing down the + * NHI and powering off the CIO power domain. On T8103, dropping the + * CIO domain while the firmware is still active triggers a SoC reset. + * If it does not sleep, a port that can stay up keeps everything: the + * NHI, PCIe-C admission and a tunnel that was requested come back. + */ + if (acio->hw->sleep_router_on_stop) { + ret = apple_cio_sleep_router_for_stop(acio); + if (ret && awake == APPLE_CIO_AWAKE_KEEP) { + apple_cio_reopen_pcie_tunnel(acio, pcie); + return ret; + } + } /* * The NHI is the tunnel control plane. Stop it while the tunneled PCIe @@ -3173,6 +3349,7 @@ static void apple_cio_remove_children(struct apple_cio *acio) acio->pcie_tunnel_populated = false; acio->pcie_quiesce_pending = false; } + return ret; } /* @@ -3307,28 +3484,66 @@ static void apple_cio_test_log_guards(struct apple_cio *acio) dev_info(acio->dev, "TEST sv6t7: ACIO stop, its domain links go next: PS_PROT%s\n", buf); } +static void apple_cio_release_domains(struct apple_cio *acio) +{ + int n, i, ret; + + for (n = 0; n < acio->pd_list->num_pds; n++) { + i = acio->hw->psd_power_cycle ? acio->pd_list->num_pds - 1 - n : n; + dev_pm_syscore_device(acio->pd_list->pd_devs[i], false); + if (!acio->pd_list->pd_links[i]) + continue; + device_link_del(acio->pd_list->pd_links[i]); + acio->pd_list->pd_links[i] = NULL; + if (!acio->hw->psd_power_cycle) + continue; + /* Link removal only queues idle; finish it before returning. */ + ret = pm_runtime_suspend(acio->pd_list->pd_devs[i]); + if (ret < 0) + dev_warn(acio->dev, "PSD domain %d failed to suspend: %d\n", i, ret); + } +} + /** * apple_cio_stop - Stop and power down the ACIO complex * @acio: ACIO complex to stop + * @awake: what to do if the host router must sleep first and does not * * Remove the NHI and DART children before shutting down the co-processor and * dropping the power-domain links. The Type-C PHY must remain configured * until this function returns. The caller must hold @acio->lock. + * + * Return: 0 once the complex is off; else the router's sleep error, with + * the port still up (APPLE_CIO_AWAKE_KEEP) or only its children removed + * (APPLE_CIO_AWAKE_HOLD). */ -static void apple_cio_stop(struct apple_cio *acio) +static int apple_cio_stop(struct apple_cio *acio, enum apple_cio_awake awake) { - int ret, i; + int ret; lockdep_assert_held(&acio->lock); if (!acio->current_cable_info) - return; - apple_cio_remove_children(acio); + return 0; + ret = apple_cio_remove_children(acio, awake); + if (ret && awake == APPLE_CIO_AWAKE_KEEP) { + dev_err(acio->dev, "the port stays up with its domains powered\n"); + return ret; + } + if (ret && awake == APPLE_CIO_AWAKE_HOLD) { + dev_err(acio->dev, + "the co-processor and its domains stay powered until the reset\n"); + return ret; + } + if (ret) + dev_err(acio->dev, "powering off its domains with the router awake\n"); /* Try to shut down and power off the co-processor gracefully */ ret = apple_rtkit_poweroff(acio->rtk); if (ret) dev_warn(acio->dev, "Failed to shutdown M3 RTKit, continuing ACIO shutdown anyway\n"); + if (acio->hw->sleep_router_on_stop) + apple_rtkit_mailbox_off(acio->rtk); apple_rtkit_free(acio->rtk); acio->rtk = NULL; apple_cio_cpu_halt(acio); @@ -3342,16 +3557,12 @@ static void apple_cio_stop(struct apple_cio *acio) apple_cio_test_log_guards(acio); /* Finally, remove the links to the PD domains to power everything off */ - for (i = 0; i < acio->pd_list->num_pds; i++) { - if (acio->pd_list->pd_links[i]) - device_link_del(acio->pd_list->pd_links[i]); - acio->pd_list->pd_links[i] = NULL; - dev_pm_syscore_device(acio->pd_list->pd_devs[i], false); - } + apple_cio_release_domains(acio); acio->current_cable_info = 0; acio->resume_link_failed = false; acio->link_lost_restart = false; + return 0; } /* @@ -3596,7 +3807,8 @@ static int apple_cio_start(struct apple_cio *acio) return 0; err_depopulate: - apple_cio_remove_children(acio); + /* A router this start brought up with its NHI goes with the co-processor. */ + apple_cio_remove_children(acio, APPLE_CIO_AWAKE_FORCE); err_shutdown_rtkit: /* Ignore errors here since we're about to cut power to the entire block anyway */ apple_rtkit_poweroff(acio->rtk); @@ -3608,12 +3820,7 @@ static int apple_cio_start(struct apple_cio *acio) acio->rtk = NULL; apple_cio_cpu_halt(acio); /* Cut power to reset the entire block */ - for (i = 0; i < acio->pd_list->num_pds; i++) { - if (acio->pd_list->pd_links[i]) - device_link_del(acio->pd_list->pd_links[i]); - acio->pd_list->pd_links[i] = NULL; - dev_pm_syscore_device(acio->pd_list->pd_devs[i], false); - } + apple_cio_release_domains(acio); return ret; } @@ -3950,7 +4157,7 @@ static int apple_cio_tbt_switch_set(struct typec_thunderbolt_switch_dev *sw, "Invalid cable transition from 0x%x to 0x%x, shutting down instead\n", acio->current_cable_info, acio->target_cable_info); acio->target_cable_info = 0; - apple_cio_stop(acio); + apple_cio_stop(acio, APPLE_CIO_AWAKE_KEEP); return -EINVAL; } @@ -3987,8 +4194,8 @@ static int apple_cio_tbt_switch_set(struct typec_thunderbolt_switch_dev *sw, return ret; } - apple_cio_stop(acio); - return 0; + /* A router that does not sleep keeps the port up until the next change. */ + return apple_cio_stop(acio, APPLE_CIO_AWAKE_KEEP); } /* The T6050 firmware sleep, selected by the sleep driver's profile and mem_sleep. */ @@ -4000,6 +4207,16 @@ static bool apple_cio_t6050_sleep(struct apple_cio *acio) apple_sleep_v27_late() && !pm_suspend_default_s2idle(); } +/* + * Deep sleep removes the CIO domains, including an attached router. A freeze + * does not, even with deep as the default. + */ +static bool apple_cio_sleep_removes_domains(struct apple_cio *acio) +{ + return acio->hw->sleep_removes_domains && !pm_suspend_default_s2idle() && + !pm_suspend_no_platform(); +} + /* The longest the displays behind a port may take to go before its router does. */ #define APPLE_CIO_SLEEP_DP_RELEASE_MS 3000 @@ -4077,8 +4294,8 @@ static int apple_cio_sleep_teardown(struct apple_cio *acio) { ktime_t start = ktime_get(), stop; const char *lstx = "not held"; - bool t6050; - int released; + bool t6050, peer_check, peer_wanted = false; + int released, ret; cancel_delayed_work_sync(&acio->resume_link_work); @@ -4102,16 +4319,17 @@ static int apple_cio_sleep_teardown(struct apple_cio *acio) scoped_guard(mutex, &acio->pcie_tunnel_lock) { if (READ_ONCE(acio->pcie_tunnel_requested) || acio->pcie_tunnel_populated) { struct platform_device *pcie; - int mode = READ_ONCE(t6050_sleep_pcie); - int ret = 0; + bool removes = apple_cio_sleep_removes_domains(acio); + int mode = removes ? 1 : READ_ONCE(t6050_sleep_pcie); + ret = 0; /* * The T6050 firmware sleep takes the router's power whatever is behind * it. The tunnelled functions go first and in order, while the tunnel * still carries them: only NVMe controllers, whose driver touches no * notifier chain on removal, and by default only with no disk in use. */ - if (!mode || !apple_cio_t6050_sleep(acio)) + if (!mode || (!removes && !apple_cio_t6050_sleep(acio))) return 0; pcie = apple_cio_find_pcie_tunnel(acio); if (pcie) { @@ -4122,7 +4340,8 @@ static int apple_cio_sleep_teardown(struct apple_cio *acio) dev_warn(acio->dev, "PCIe devices behind this port stay for the sleep (%d): the port is not powered off\n", ret); - return 0; + /* T8142 cannot retain this port through deep sleep. */ + return removes ? ret : 0; } } acio->pcie_tunnel_stopping = true; @@ -4131,16 +4350,30 @@ static int apple_cio_sleep_teardown(struct apple_cio *acio) dev_info(acio->dev, "powering off port for system sleep (cable info 0x%x)\n", acio->current_cable_info); t6050 = apple_cio_t6050_sleep(acio); - if (t6050) { + peer_check = t6050 || apple_cio_sleep_removes_domains(acio); + if (peer_check) { u64 activity; /* With no NHI the answer is "yes": then nothing is expected back. */ - acio->sleep_peer_wanted = READ_ONCE(acio->nhi_pdev) && - apple_cio_has_peer(acio, &activity); - acio->link_lost_cycles = 0; + peer_wanted = READ_ONCE(acio->nhi_pdev) && + apple_cio_has_peer(acio, &activity); } stop = ktime_get(); - apple_cio_stop(acio); + /* + * A router that does not go to sleep keeps the port up, its PCIe + * hierarchy coming back, and the sleep is refused: deep sleep would + * take the domains down with it. + */ + ret = apple_cio_stop(acio, APPLE_CIO_AWAKE_KEEP); + if (ret) { + dev_err(acio->dev, "refusing system sleep: the port cannot be powered off (%d)\n", + ret); + return ret; + } + if (peer_check) { + acio->sleep_peer_wanted = peer_wanted; + acio->link_lost_cycles = 0; + } acio->sleep_phase = APPLE_CIO_SLEEP_CLOSED; WRITE_ONCE(acio->sleep_restart_owed, true); /* Its displays come back with the port's restart. */ @@ -4199,7 +4432,7 @@ static void apple_cio_sleep_restart_work(struct work_struct *work) /* Is this port powered off for the sleep about to start? Asked at PM_SUSPEND_PREPARE. */ static bool apple_cio_sleep_tears_down(struct apple_cio *acio) { - if (READ_ONCE(s2idle_teardown)) + if (READ_ONCE(s2idle_teardown) || apple_cio_sleep_removes_domains(acio)) return true; /* A "freeze" is a suspend-to-idle with deep as the default too: the port stays up. */ if (pm_suspend_no_platform()) @@ -4229,7 +4462,7 @@ static int apple_cio_pm_notify(struct notifier_block *nb, unsigned long event, apple_cio_sleep_close_owed(acio); /* Before tasks freeze: tearing down the NHI needs unfrozen work. */ if (tears_down) { - /* Only the displays' release refuses, with the port as it was. */ + /* Refuse before powering off a port that cannot be released. */ ret = apple_cio_sleep_teardown(acio); if (ret) return notifier_from_errno(ret); @@ -4244,6 +4477,8 @@ static int apple_cio_pm_notify(struct notifier_block *nb, unsigned long event, } owed = acio->sleep_restart_owed; early = acio->sleep_aborted_early; + if (acio->hw->restart_on_wake) + delay = 0; /* TEST: macOS starts the router again straight after the wake. */ if (acio->sleep_t6050) { acio->sleep_t6050 = false; @@ -4472,6 +4707,26 @@ static int apple_cio_pcie_notify(struct notifier_block *nb, return NOTIFY_OK; } +/* + * A reboot or power-off shuts the PCIe-C host and the router's and the + * tunnel's DARTs down before this device, with the router still running + * over them. Stop a started router first, as the port driver does for an + * unplugged cable, and refuse a new start from then on. A router that must + * sleep first and does not loses only its children: its domains stay + * powered until the reset or power-off. + */ +static int apple_cio_reboot_notify(struct notifier_block *nb, unsigned long action, + void *data) +{ + struct apple_cio *acio = container_of(nb, struct apple_cio, reboot_notifier); + + guard(mutex)(&acio->lock); + acio->removing = true; + if (acio->current_cable_info) + apple_cio_stop(acio, APPLE_CIO_AWAKE_HOLD); + return NOTIFY_DONE; +} + static int apple_cio_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -4613,13 +4868,17 @@ static int apple_cio_probe(struct platform_device *pdev) acio->router_ap_fw_tunable = devm_apple_tunable_parse(dev, acio->np, "apple,tunable-router-ap-fw", ap_fw); - if (IS_ERR(acio->router_ap_fw_tunable)) { - if (PTR_ERR(acio->router_ap_fw_tunable) != -ENOENT) - return dev_err_probe(dev, - PTR_ERR(acio->router_ap_fw_tunable), - "Unable to load router AP firmware tunable\n"); - acio->router_ap_fw_tunable = NULL; - } + /* + * The bootloader copies this tuning from the machine. Without it + * the router would run untuned, so a loader that left it out fails + * the probe, like a missing RC tuning. + */ + if (PTR_ERR_OR_ZERO(acio->router_ap_fw_tunable) == -ENOENT) + return dev_err_probe(dev, -EINVAL, + "Missing bootloader router AP firmware tuning\n"); + if (IS_ERR(acio->router_ap_fw_tunable)) + return dev_err_probe(dev, PTR_ERR(acio->router_ap_fw_tunable), + "Unable to load router AP firmware tunable\n"); } } @@ -4728,11 +4987,18 @@ static int apple_cio_probe(struct platform_device *pdev) } acio->pm_notifier.notifier_call = apple_cio_pm_notify; + /* Before DWC3's default-priority notifier queues its PHY shutdown. */ + if (acio->hw->phy_shared_with_dwc3) + acio->pm_notifier.priority = 40; register_pm_notifier(&acio->pm_notifier); /* Before the notifiers of the default priority, after the port controllers' (30). */ acio->pm_notifier_dp.notifier_call = apple_cio_dp_pm_notify; acio->pm_notifier_dp.priority = 20; register_pm_notifier(&acio->pm_notifier_dp); + if (acio->hw->stop_at_reboot) { + acio->reboot_notifier.notifier_call = apple_cio_reboot_notify; + register_reboot_notifier(&acio->reboot_notifier); + } return 0; } @@ -4740,6 +5006,8 @@ static void apple_cio_remove(struct platform_device *pdev) { struct apple_cio *acio = platform_get_drvdata(pdev); + if (acio->hw->stop_at_reboot) + unregister_reboot_notifier(&acio->reboot_notifier); /* Refuse new activation before draining callbacks and workers. */ scoped_guard(mutex, &acio->lock) acio->removing = true; @@ -4758,7 +5026,7 @@ static void apple_cio_remove(struct platform_device *pdev) typec_thunderbolt_switch_unregister(acio->tbt_switch); guard(mutex)(&acio->lock); if (acio->current_cable_info) - apple_cio_stop(acio); + apple_cio_stop(acio, APPLE_CIO_AWAKE_FORCE); } @@ -4773,6 +5041,7 @@ static const struct of_device_id apple_acio_match[] = { .compatible = "apple,t6050-usb4-acio", .data = &apple_cio_t6050_hw, }, + { .compatible = "apple,t8152-usb4-acio", .data = &apple_cio_t8152_hw }, { .compatible = "apple,t8142-usb4-acio", .data = &apple_cio_t8142_hw, @@ -4785,6 +5054,10 @@ static const struct of_device_id apple_acio_match[] = { .compatible = "apple,t6030-usb4-acio", .data = &apple_cio_t6030_hw, }, + { + .compatible = "apple,t8122-usb4-acio", + .data = &apple_cio_t8122_hw, + }, { .compatible = "apple,t6020-usb4-acio", .data = &apple_cio_t6020_hw, diff --git a/drivers/thunderbolt/domain.c b/drivers/thunderbolt/domain.c index a06539264971c5..0f55d50331718d 100644 --- a/drivers/thunderbolt/domain.c +++ b/drivers/thunderbolt/domain.c @@ -11,9 +11,11 @@ #include #include #include +#include #include #include #include +#include #include "tb.h" @@ -333,11 +335,15 @@ const struct device_type tb_domain_type = { .release = tb_domain_release, }; -static bool tb_domain_event_cb(void *data, enum tb_cfg_pkg_type type, - const void *buf, size_t size) +VISIBLE_IF_KUNIT bool tb_domain_event_cb(void *data, enum tb_cfg_pkg_type type, + const void *buf, size_t size) { struct tb *tb = data; + /* During noirq only XDomain discovery requests can receive a reply. */ + if (READ_ONCE(tb->noirq_ctl_retained) && type != TB_CFG_PKG_XDOMAIN_REQ) + return true; + if (!tb->cm_ops->handle_event) { tb_warn(tb, "domain does not have event handler\n"); return true; @@ -528,11 +534,34 @@ void tb_domain_remove(struct tb *tb) } EXPORT_SYMBOL_FOR_MODULES(tb_domain_remove, "thunderbolt_apple"); +VISIBLE_IF_KUNIT bool tb_domain_retain_noirq_control(struct tb *tb) +{ + struct tb_port *port; + bool xdomain = false; + + lockdep_assert_held(&tb->lock); + + if (!pm_suspend_no_platform() || + !(tb->nhi->quirks & QUIRK_NO_SYSTEM_SLEEP) || + !tb->root_switch) + return false; + + tb_switch_for_each_port(tb->root_switch, port) { + if (tb_port_has_remote(port)) + return false; + if (port->xdomain) + xdomain = true; + } + + return xdomain; +} + /** * tb_domain_suspend_noirq() - Suspend a domain * @tb: Domain to suspend * - * Suspends all devices in the domain and stops the control channel. + * Suspends all devices in the domain. Stops the control channel unless + * an awake host router needs it for direct XDomain discovery. * * Return: %0 on success, negative errno otherwise. */ @@ -548,8 +577,14 @@ int tb_domain_suspend_noirq(struct tb *tb) mutex_lock(&tb->lock); if (tb->cm_ops->suspend_noirq) ret = tb->cm_ops->suspend_noirq(tb); - if (!ret) - tb_ctl_stop(tb->ctl); + if (!ret) { + if (tb_domain_retain_noirq_control(tb)) { + WRITE_ONCE(tb->noirq_ctl_retained, true); + tb_dbg(tb, "XDomain control channel retained for s2idle\n"); + } else { + tb_ctl_stop(tb->ctl); + } + } mutex_unlock(&tb->lock); return ret; @@ -570,7 +605,18 @@ int tb_domain_resume_noirq(struct tb *tb) int ret = 0; mutex_lock(&tb->lock); - tb_ctl_start(tb->ctl); + /* + * End the hold before resume_noirq(), where a stopped channel would be + * started: hotplug events and XDomain responses then reach the + * connection manager from the same point as without the hold. Requests + * still wait for tb->lock, which is held until the resume is done. + */ + if (tb->noirq_ctl_retained) { + WRITE_ONCE(tb->noirq_ctl_retained, false); + tb_dbg(tb, "XDomain control channel remained active\n"); + } else { + tb_ctl_start(tb->ctl); + } if (tb->cm_ops->resume_noirq) ret = tb->cm_ops->resume_noirq(tb); mutex_unlock(&tb->lock); diff --git a/drivers/thunderbolt/nhi.h b/drivers/thunderbolt/nhi.h index 56999164d072e5..f41a512c440902 100644 --- a/drivers/thunderbolt/nhi.h +++ b/drivers/thunderbolt/nhi.h @@ -258,6 +258,8 @@ struct tb_nhi_ops { #define QUIRK_CIO_MACOS_FRAMES BIT(14) /* Reinitialize device-router TMUs in bi-directional HiFi mode. */ #define QUIRK_TMU_HIFI_BI BIT(15) +/* Do not send USB4 retimer sideband scans on this domain's links. */ +#define QUIRK_NO_RETIMER_SCAN BIT(16) /* Host display policies are independent of which optional hooks are installed. */ #define TB_HOST_DP_NOTIFY BIT(0) diff --git a/drivers/thunderbolt/retimer.c b/drivers/thunderbolt/retimer.c index 39045b44a4a5a7..899979f3915623 100644 --- a/drivers/thunderbolt/retimer.c +++ b/drivers/thunderbolt/retimer.c @@ -8,7 +8,6 @@ */ #include -#include #include #include @@ -195,9 +194,9 @@ static ssize_t nvm_authenticate_show(struct device *dev, return ret; } -static void tb_retimer_nvm_authenticate_status(struct tb_port *port, u32 *status) +static int tb_retimer_nvm_authenticate_status(struct tb_port *port, u32 *status) { - int i; + int i, ret; tb_port_dbg(port, "reading NVM authentication status of retimers\n"); @@ -207,9 +206,15 @@ static void tb_retimer_nvm_authenticate_status(struct tb_port *port, u32 *status * device instance. */ for (i = 1; i <= TB_MAX_RETIMER_INDEX; i++) { - if (usb4_port_retimer_nvm_authenticate_status(port, i, &status[i])) + ret = usb4_port_retimer_nvm_authenticate_status(port, i, &status[i]); + if (ret) { + if (ret == -ETIMEDOUT || ret == -EBUSY) + return ret; break; + } } + + return 0; } static void tb_retimer_set_inbound_sbtx(struct tb_port *port) @@ -497,19 +502,15 @@ static struct tb_retimer *tb_port_find_retimer(struct tb_port *port, u8 index) } /* - * TEST (J714s, sv6u5): macOS sends no retimer sideband operation on the links of this machine's - * USB4 routers: no retimer enumeration and no access to a retimer index, only reads of the - * routers' own sideband registers (runs mxt6 and mxt6b, two wakes and two sleeps), and its host - * router firmware logs no retimer command timeout. The scan below makes that firmware time out - * a retimer command three times at each dock enumeration (every Linux run since sv6t4). Skip it - * here, as macOS does. + * Skip USB4 retimer sideband scanning on host routers that do not support it + * (macOS sends no retimer sideband operations on Apple USB4 host routers). */ static bool tb_retimer_scan_skip(struct tb_port *port) { - if (!(port->sw->tb->nhi->quirks & QUIRK_CIO_MACOS_FRAMES) || - !(of_machine_is_compatible("apple,j714s") || of_machine_is_compatible("apple,j716c"))) + if (!(port->sw->tb->nhi->quirks & QUIRK_NO_RETIMER_SCAN)) return false; - tb_port_info(port, "TEST sv6u5: no retimer scan on this link (macOS sends no retimer sideband operation)\n"); + + tb_port_dbg(port, "skipping retimer scan (QUIRK_NO_RETIMER_SCAN)\n"); return true; } @@ -545,7 +546,9 @@ int tb_retimer_scan(struct tb_port *port, bool add) * Immediately after sending enumerate retimers read the * authentication status of each retimer. */ - tb_retimer_nvm_authenticate_status(port, status); + ret = tb_retimer_nvm_authenticate_status(port, status); + if (ret) + return ret; /* * Enable sideband channel for each retimer. We can do this diff --git a/drivers/thunderbolt/tb.c b/drivers/thunderbolt/tb.c index b013696f0ff48a..41d9bdc44e8dfa 100644 --- a/drivers/thunderbolt/tb.c +++ b/drivers/thunderbolt/tb.c @@ -231,10 +231,6 @@ static int tb_enable_clx(struct tb_switch *sw) const struct tb_tunnel *tunnel; int ret; - /* Bi-directional HiFi does not support CL states. */ - if (sw->tb->nhi->quirks & QUIRK_TMU_HIFI_BI) - return 0; - /* * Currently only enable CLx for the first link. This is enough * to allow the CPU to save energy at least on Intel hardware @@ -251,6 +247,10 @@ static int tb_enable_clx(struct tb_switch *sw) if (tb_switch_depth(sw) != 1) return 0; + /* Bi-directional HiFi (non-USB4 routers, see tb_enable_tmu()) does not support CL states. */ + if ((sw->tb->nhi->quirks & QUIRK_TMU_HIFI_BI) && !tb_switch_is_usb4(sw)) + return 0; + /* * If we are re-enabling then check if there is an active DMA * tunnel and in that case bail out. @@ -367,7 +367,12 @@ static int tb_enable_tmu(struct tb_switch *sw) { int ret; - if ((sw->tb->nhi->quirks & QUIRK_TMU_HIFI_BI) && tb_route(sw)) { + /* + * Not for USB4 routers: a host router whose firmware runs its TMU applies a mode only + * on the enhanced uni-directional path below, and a dock's DP OUT has no clock without it. + */ + if ((sw->tb->nhi->quirks & QUIRK_TMU_HIFI_BI) && tb_route(sw) && + !tb_switch_is_usb4(sw)) { ret = tb_switch_clx_disable(sw); if (ret < 0) return ret; diff --git a/drivers/thunderbolt/tb.h b/drivers/thunderbolt/tb.h index 839468ed8def0b..70caebcf2b38be 100644 --- a/drivers/thunderbolt/tb.h +++ b/drivers/thunderbolt/tb.h @@ -773,6 +773,10 @@ int tb_consumed_dp_bandwidth(struct tb *tb, struct tb_port *src_port, int *consumed_up, int *consumed_down); u32 tb_dp_host_rate_limit(struct tb *tb); void tb_dp_host_tunnel_gone(struct tb *tb, unsigned int before); +bool tb_domain_event_cb(void *data, enum tb_cfg_pkg_type type, + const void *buf, size_t size); +bool tb_domain_retain_noirq_control(struct tb *tb); +bool tb_xdp_noirq_request(enum tb_xdp_type type); #endif #if IS_ENABLED(CONFIG_USB4_KUNIT_TEST) size_t tb_test_cm_size(void); diff --git a/drivers/thunderbolt/test.c b/drivers/thunderbolt/test.c index f8418132064afc..fbb318f17812dc 100644 --- a/drivers/thunderbolt/test.c +++ b/drivers/thunderbolt/test.c @@ -4316,6 +4316,337 @@ static void tb_test_dp_shared_rate_debounce_deferred(struct kunit *test) tb_test_dp_shared_rate_arrival(test, false, true); } +/* + * A domain as tb_domain_suspend_noirq() sees it on a host that keeps its + * router awake through suspend-to-idle (QUIRK_NO_SYSTEM_SLEEP): a host + * router and a connection manager that counts its calls. There is no + * control channel: the paths that keep it running must not touch it. + */ +struct tb_test_noirq { + struct tb_nhi nhi; + struct tb_cm_ops ops; + struct tb *tb; + struct tb_switch *host; + unsigned int saved_flags; + unsigned int suspends, resumes, events; + enum tb_cfg_pkg_type last_event; + int suspend_ret; + unsigned int handled; +}; + +static int tb_test_noirq_cm_suspend(struct tb *tb) +{ + struct tb_test_noirq *ctx = kunit_get_current_test()->priv; + + ctx->suspends++; + return ctx->suspend_ret; +} + +static int tb_test_noirq_cm_resume(struct tb *tb) +{ + struct tb_test_noirq *ctx = kunit_get_current_test()->priv; + + ctx->resumes++; + return 0; +} + +static void tb_test_noirq_cm_event(struct tb *tb, enum tb_cfg_pkg_type type, + const void *buf, size_t size) +{ + struct tb_test_noirq *ctx = kunit_get_current_test()->priv; + + ctx->events++; + ctx->last_event = type; +} + +/* The suspend in progress: to idle (the platform is not involved) or deeper. */ +#ifdef CONFIG_SUSPEND +static unsigned int tb_test_noirq_pm_flags(void) +{ + return pm_suspend_global_flags; +} + +static void tb_test_noirq_set_pm_flags(unsigned int flags) +{ + pm_suspend_global_flags = flags; +} + +static void tb_test_noirq_to_idle(bool to_idle) +{ + pm_suspend_clear_flags(); + if (to_idle) + pm_set_suspend_no_platform(); +} +#else +static unsigned int tb_test_noirq_pm_flags(void) +{ + return 0; +} + +static void tb_test_noirq_set_pm_flags(unsigned int flags) +{ +} + +static void tb_test_noirq_to_idle(bool to_idle) +{ +} +#endif + +static void tb_test_noirq_restore(void *data) +{ + struct tb_test_noirq *ctx = data; + + tb_test_noirq_set_pm_flags(ctx->saved_flags); + put_device(&ctx->tb->dev); +} + +/* The domain in a suspend-to-idle, with a host directly on port 1. */ +static struct tb_test_noirq *tb_test_noirq_alloc(struct kunit *test) +{ + struct tb_test_noirq *ctx; + struct tb_xdomain *xd; + struct tb *tb; + + if (!IS_ENABLED(CONFIG_SUSPEND)) + kunit_skip(test, "needs CONFIG_SUSPEND"); + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + tb = kunit_kzalloc(test, sizeof(*tb), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, tb); + xd = kunit_kzalloc(test, sizeof(*xd), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, xd); + ctx->host = alloc_host(test); + KUNIT_ASSERT_NOT_NULL(test, ctx->host); + + ctx->ops.suspend_noirq = tb_test_noirq_cm_suspend; + ctx->ops.resume_noirq = tb_test_noirq_cm_resume; + ctx->ops.handle_event = tb_test_noirq_cm_event; + ctx->nhi.quirks = QUIRK_NO_SYSTEM_SLEEP; + ctx->tb = tb; + tb->nhi = &ctx->nhi; + tb->cm_ops = &ctx->ops; + tb->root_switch = ctx->host; + ctx->host->tb = tb; + ctx->host->ports[1].xdomain = xd; + device_initialize(&tb->dev); + tb->dev.release = tb_test_dprx_release; + mutex_init(&tb->lock); + + ctx->saved_flags = tb_test_noirq_pm_flags(); + tb_test_noirq_to_idle(true); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, tb_test_noirq_restore, ctx), 0); + + test->priv = ctx; + return ctx; +} + +static bool tb_test_noirq_retain(struct tb_test_noirq *ctx) +{ + bool retain; + + mutex_lock(&ctx->tb->lock); + retain = tb_domain_retain_noirq_control(ctx->tb); + mutex_unlock(&ctx->tb->lock); + return retain; +} + +/* Only requests that read state are answered while the domain is suspended. */ +static void tb_test_noirq_xdp_request_types(struct kunit *test) +{ + unsigned int type; + + for (type = 0; type < 64; type++) { + bool discovery = type == UUID_REQUEST_OLD || type == UUID_REQUEST || + type == PROPERTIES_REQUEST || + type == LINK_STATE_STATUS_REQUEST; + + KUNIT_EXPECT_EQ_MSG(test, tb_xdp_noirq_request(type), discovery, + "XDomain packet type %u", type); + } +} + +/* + * The control channel stays up only for a suspend-to-idle of an awake host + * router whose every connection is another host. + */ +static void tb_test_noirq_retain_decision(struct kunit *test) +{ + struct tb_test_noirq *ctx = tb_test_noirq_alloc(test); + struct tb_port *ports = ctx->host->ports; + struct tb_xdomain *xd = ports[1].xdomain; + struct tb_port *remote; + + remote = kunit_kzalloc(test, sizeof(*remote), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, remote); + + KUNIT_EXPECT_TRUE(test, tb_test_noirq_retain(ctx)); + ports[3].xdomain = xd; + KUNIT_EXPECT_TRUE(test, tb_test_noirq_retain(ctx)); + + /* A router behind any port needs the full suspend of its tunnels. */ + ports[3].xdomain = NULL; + ports[3].remote = remote; + KUNIT_EXPECT_FALSE(test, tb_test_noirq_retain(ctx)); + ports[1].xdomain = NULL; + KUNIT_EXPECT_FALSE(test, tb_test_noirq_retain(ctx)); + + /* Nothing connected: nobody to answer. */ + ports[3].remote = NULL; + KUNIT_EXPECT_FALSE(test, tb_test_noirq_retain(ctx)); + ports[1].xdomain = xd; + KUNIT_EXPECT_TRUE(test, tb_test_noirq_retain(ctx)); + + /* A host router that sleeps with the system loses its rings. */ + ctx->nhi.quirks = 0; + KUNIT_EXPECT_FALSE(test, tb_test_noirq_retain(ctx)); + ctx->nhi.quirks = QUIRK_NO_SYSTEM_SLEEP; + + /* The platform may power the router down in a deeper sleep. */ + tb_test_noirq_to_idle(false); + KUNIT_EXPECT_FALSE(test, tb_test_noirq_retain(ctx)); + tb_test_noirq_to_idle(true); + + ctx->tb->root_switch = NULL; + KUNIT_EXPECT_FALSE(test, tb_test_noirq_retain(ctx)); +} + +/* + * A retained control channel is neither stopped nor started (the domain has + * none here), and its events are dropped until the domain has resumed. + */ +static void tb_test_noirq_suspend_resume_retained(struct kunit *test) +{ + struct tb_test_noirq *ctx = tb_test_noirq_alloc(test); + static const enum tb_cfg_pkg_type dropped[] = { + TB_CFG_PKG_ERROR, TB_CFG_PKG_NOTIFY_ACK, TB_CFG_PKG_EVENT, + TB_CFG_PKG_ICM_EVENT, + }; + struct tb *tb = ctx->tb; + u32 buf[4] = {}; + int i; + + KUNIT_EXPECT_TRUE(test, tb_domain_event_cb(tb, TB_CFG_PKG_EVENT, buf, sizeof(buf))); + KUNIT_EXPECT_EQ(test, ctx->events, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_event, TB_CFG_PKG_EVENT); + + /* The connection manager refused: nothing is retained. */ + ctx->suspend_ret = -EBUSY; + KUNIT_EXPECT_EQ(test, tb_domain_suspend_noirq(tb), -EBUSY); + KUNIT_EXPECT_FALSE(test, tb->noirq_ctl_retained); + ctx->suspend_ret = 0; + + KUNIT_ASSERT_EQ(test, tb_domain_suspend_noirq(tb), 0); + KUNIT_EXPECT_EQ(test, ctx->suspends, 2U); + KUNIT_ASSERT_TRUE(test, tb->noirq_ctl_retained); + + for (i = 0; i < ARRAY_SIZE(dropped); i++) + KUNIT_EXPECT_TRUE(test, tb_domain_event_cb(tb, dropped[i], buf, sizeof(buf))); + KUNIT_EXPECT_EQ(test, ctx->events, 1U); + + KUNIT_ASSERT_EQ(test, tb_domain_resume_noirq(tb), 0); + KUNIT_EXPECT_EQ(test, ctx->resumes, 1U); + KUNIT_EXPECT_FALSE(test, tb->noirq_ctl_retained); + + KUNIT_EXPECT_TRUE(test, tb_domain_event_cb(tb, TB_CFG_PKG_ERROR, buf, sizeof(buf))); + KUNIT_EXPECT_EQ(test, ctx->events, 2U); + KUNIT_EXPECT_EQ(test, ctx->last_event, TB_CFG_PKG_ERROR); +} + +/* The XDomain discovery protocol and a service protocol of the test's own. */ +static const uuid_t tb_test_xdp_uuid = + UUID_INIT(0xb638d70e, 0x42ff, 0x40bb, + 0x97, 0xc2, 0x90, 0xe2, 0xc0, 0xb2, 0xff, 0x07); +static const uuid_t tb_test_service_uuid = + UUID_INIT(0x4b756e69, 0x7420, 0x7465, + 0x73, 0x74, 0x20, 0x6e, 0x6f, 0x69, 0x72, 0x71); + +static int tb_test_noirq_service(const void *buf, size_t size, void *data) +{ + struct tb_test_noirq *ctx = data; + + ctx->handled++; + return 1; +} + +static void tb_test_noirq_unregister(void *data) +{ + tb_unregister_protocol_handler(data); +} + +static bool tb_test_noirq_packet(struct tb_test_noirq *ctx, const uuid_t *uuid, + enum tb_cfg_pkg_type pkg, u32 type) +{ + struct tb_xdp_header hdr = { + .xd_hdr.length_sn = (sizeof(hdr) - sizeof(hdr.xd_hdr)) / 4, + .uuid = *uuid, + .type = type, + }; + + return tb_xdomain_handle_request(ctx->tb, pkg, &hdr, sizeof(hdr)); +} + +/* + * While the control channel is retained nothing but a discovery request + * gets past the XDomain dispatch: no service protocol, no response, no + * discovery request that changes state. + */ +static void tb_test_noirq_xdomain_filter(struct kunit *test) +{ + static const u32 refused[] = { + 0, UUID_RESPONSE, PROPERTIES_RESPONSE, PROPERTIES_CHANGED_REQUEST, + PROPERTIES_CHANGED_RESPONSE, ERROR_RESPONSE, + LINK_STATE_STATUS_RESPONSE, LINK_STATE_CHANGE_REQUEST, + LINK_STATE_CHANGE_RESPONSE, 31, + }; + struct tb_test_noirq *ctx = tb_test_noirq_alloc(test); + struct tb_protocol_handler *handler; + struct tb *tb = ctx->tb; + int i; + + handler = kunit_kzalloc(test, sizeof(*handler), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, handler); + handler->uuid = &tb_test_service_uuid; + handler->callback = tb_test_noirq_service; + handler->data = ctx; + KUNIT_ASSERT_EQ(test, tb_register_protocol_handler(handler), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, tb_test_noirq_unregister, + handler), 0); + + /* Awake: the service sees its packets, a discovery response is not consumed. */ + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_service_uuid, + TB_CFG_PKG_XDOMAIN_REQ, UUID_REQUEST)); + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_service_uuid, + TB_CFG_PKG_XDOMAIN_RESP, UUID_RESPONSE)); + KUNIT_EXPECT_EQ(test, ctx->handled, 2U); + KUNIT_EXPECT_FALSE(test, tb_test_noirq_packet(ctx, &tb_test_xdp_uuid, + TB_CFG_PKG_XDOMAIN_RESP, UUID_RESPONSE)); + + WRITE_ONCE(tb->noirq_ctl_retained, true); + + /* A service packet is dropped, whatever sits where discovery has its type. */ + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_service_uuid, + TB_CFG_PKG_XDOMAIN_REQ, UUID_REQUEST)); + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_service_uuid, + TB_CFG_PKG_XDOMAIN_RESP, UUID_RESPONSE)); + KUNIT_EXPECT_EQ(test, ctx->handled, 2U); + + /* A discovery response is consumed: no request of ours waits for one. */ + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_xdp_uuid, + TB_CFG_PKG_XDOMAIN_RESP, UUID_RESPONSE)); + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_xdp_uuid, + TB_CFG_PKG_XDOMAIN_RESP, UUID_REQUEST)); + + /* Queueing a request takes a reference to the domain: none is queued. */ + for (i = 0; i < ARRAY_SIZE(refused); i++) { + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_xdp_uuid, + TB_CFG_PKG_XDOMAIN_REQ, + refused[i])); + KUNIT_EXPECT_EQ_MSG(test, kref_read(&tb->dev.kobj.kref), 1U, + "XDomain request %u was queued", refused[i]); + } +} + static struct kunit_case tb_test_cases[] = { KUNIT_CASE(tb_test_apple_right_dpin_wiring), KUNIT_CASE(tb_test_dp_reduce_bandwidth_shared), @@ -4339,6 +4670,10 @@ static struct kunit_case tb_test_cases[] = { KUNIT_CASE(tb_test_property_parse_u32_wrap), KUNIT_CASE(tb_test_property_parse_recursion), KUNIT_CASE(tb_test_property_parse_dir_len_underflow), + KUNIT_CASE(tb_test_noirq_xdp_request_types), + KUNIT_CASE(tb_test_noirq_retain_decision), + KUNIT_CASE(tb_test_noirq_suspend_resume_retained), + KUNIT_CASE(tb_test_noirq_xdomain_filter), KUNIT_CASE(tb_test_pci_host_teardown), KUNIT_CASE(tb_test_pci_host_daisy_chain), KUNIT_CASE(tb_test_tunnel_dp_host_credits), diff --git a/drivers/thunderbolt/tmu.c b/drivers/thunderbolt/tmu.c index ce494a044e4f03..151a60826c444d 100644 --- a/drivers/thunderbolt/tmu.c +++ b/drivers/thunderbolt/tmu.c @@ -720,6 +720,15 @@ static int tb_switch_tmu_enable_bidirectional(struct tb_switch *sw) up = tb_upstream_port(sw); down = tb_switch_downstream_port(sw); + /* The host's way: time sync off, on again below (see tb_switch_tmu_enable_enhanced()). */ + if (tb_switch_tmu_host_managed(sw)) { + ret = tb_port_tmu_time_sync_disable(up); + if (!ret) + ret = tb_port_tmu_time_sync_disable(down); + if (ret) + goto out; + } + ret = tb_port_tmu_unidirectional_disable(up); if (ret) return ret; diff --git a/drivers/thunderbolt/tunnel.c b/drivers/thunderbolt/tunnel.c index dac96ef66149ea..648ac16bc952a5 100644 --- a/drivers/thunderbolt/tunnel.c +++ b/drivers/thunderbolt/tunnel.c @@ -97,21 +97,16 @@ MODULE_PARM_DESC(dprx_timeout, "DPRX capability read timeout in ms, -1 waits forever (default: " __MODULE_STRING(TB_DPRX_TIMEOUT) ")"); -static unsigned int dma_credits = TB_DMA_CREDITS; +static unsigned int dma_credits; module_param(dma_credits, uint, 0444); -MODULE_PARM_DESC(dma_credits, "specify custom credits for DMA tunnels (default: " - __MODULE_STRING(TB_DMA_CREDITS) ")"); +MODULE_PARM_DESC(dma_credits, + "DMA tunnel credits (0: NHI policy, otherwise capped override)"); static bool bw_alloc_mode = true; module_param(bw_alloc_mode, bool, 0444); MODULE_PARM_DESC(bw_alloc_mode, "enable bandwidth allocation mode if supported (default: true)"); -static bool dp_video_counter; -module_param(dp_video_counter, bool, 0444); -MODULE_PARM_DESC(dp_video_counter, - "diagnostic: count packets on the DP video path's DP IN hop and its downstream (hub-side) hop (Apple M2 Pro/Max laptop right ACIO route only; read via debugfs port counters); default: false"); - static void tb_dp_dump_apple(struct tb_tunnel *tunnel); static int tb_apple_nhi_typec_index(struct tb_nhi *nhi); @@ -160,6 +155,28 @@ static inline unsigned int tb_usable_credits(const struct tb_port *port) return port->total_credits - port->ctl_credits; } +/* + * Preserve legacy defaults unless the NHI opts into router preferences. + * Only apply the host NHI opt-in to the host router itself so downstream + * routers keep their conservative DMA reservation, and cap at TB_MAX_CREDITS + * so reservations match what tb_tunnel_alloc_dma() can program into a hop. + */ +static unsigned int tb_dma_credits(const struct tb_switch *sw) +{ + unsigned int credits = dma_credits; + + if (!credits) { + if (!tb_route(sw) && sw->tb && sw->tb->nhi && + sw->tb->nhi->use_dma_credit_preferences) + credits = sw->max_dma_credits; + if (!credits) + credits = TB_DMA_CREDITS; + } + + credits = min_not_zero(credits, sw->max_dma_credits); + return min_t(unsigned int, credits, TB_MAX_CREDITS); +} + /** * tb_available_credits() - Available credits for PCIe and DMA * @port: Lane adapter to check @@ -179,7 +196,7 @@ static unsigned int tb_available_credits(const struct tb_port *port, pcie = tb_acpi_may_tunnel_pcie() ? sw->max_pcie_credits : 0; if (tb_acpi_is_xdomain_allowed()) { - spare = min_not_zero(sw->max_dma_credits, dma_credits); + spare = tb_dma_credits(sw); /* Add some credits for potential second DMA tunnel */ spare += TB_MIN_DMA_CREDITS; } else { @@ -192,7 +209,8 @@ static unsigned int tb_available_credits(const struct tb_port *port, * Maximum number of DP streams possible through the * lane adapter. */ - if (sw->min_dp_aux_credits + sw->min_dp_main_credits) + if (sw->min_dp_aux_credits + sw->min_dp_main_credits && + credits > usb3 + pcie + spare) ndp = (credits - (usb3 + pcie + spare)) / (sw->min_dp_aux_credits + sw->min_dp_main_credits); else @@ -2029,14 +2047,6 @@ static int tb_dp_init_video_credits(struct tb_path_hop *hop) return 0; } -static bool tb_dp_video_counter_wanted(const struct tb_path *path) -{ - if (!dp_video_counter || !path->path_length) - return false; - - return tb_dp_is_apple_t602x_right_dpin(path->hops[0].in_port); -} - static int tb_dp_init_video_path(struct tb_path *path, bool pm_support) { struct tb_path_hop *hop; @@ -2048,27 +2058,6 @@ static int tb_dp_init_video_path(struct tb_path *path, bool pm_support) path->priority = TB_DP_VIDEO_PRIORITY; path->weight = TB_DP_VIDEO_WEIGHT; - if (tb_dp_video_counter_wanted(path)) { - struct tb_path_hop *last = &path->hops[path->path_length - 1]; - - path->hops[0].in_counter_index = 0; - tb_port_dbg(path->hops[0].in_port, - "dp_video_counter: enabling counter 0 on DP IN hop\n"); - - /* - * Second checkpoint: the downstream router's ingress side of - * the same path (e.g. the hub's upstream link), so comparing - * its counter against the first checkpoint can show whether - * DP-IN traffic actually crosses into the far end, not just - * leaves the host. - */ - if (last != &path->hops[0]) { - last->in_counter_index = 0; - tb_port_dbg(last->in_port, - "dp_video_counter: enabling counter 0 on downstream hop\n"); - } - } - tb_path_for_each_hop(path, hop) { int ret; @@ -2549,12 +2538,7 @@ struct tb_tunnel *tb_tunnel_alloc_dma(struct tb *tb, struct tb_port *nhi, tunnel->dst_port = dst; tunnel->destroy = tb_dma_destroy; - credits = min_not_zero(dma_credits, nhi->sw->max_dma_credits); - if (credits > TB_MAX_CREDITS) { - tb_tunnel_dbg(tunnel, "%u credits do not fit a hop, using %u\n", - credits, TB_MAX_CREDITS); - credits = TB_MAX_CREDITS; - } + credits = tb_dma_credits(nhi->sw); if (receive_ring > 0) { path = tb_path_alloc(tb, dst, receive_path, nhi, receive_ring, 0, diff --git a/drivers/thunderbolt/usb4.c b/drivers/thunderbolt/usb4.c index 80701579107925..956fe28133c0aa 100644 --- a/drivers/thunderbolt/usb4.c +++ b/drivers/thunderbolt/usb4.c @@ -1343,6 +1343,28 @@ static int usb4_port_write_data(struct tb_port *port, const void *data, dwords); } +static int usb4_port_sb_wait_idle(struct tb_port *port) +{ + u32 val; + int ret; + + ret = tb_port_read(port, &val, TB_CFG_PORT, + port->cap_usb4 + PORT_CS_1, 1); + if (ret) + return ret; + if (!(val & PORT_CS_1_PND)) + return 0; + + ret = usb4_port_wait_for_bit(port, port->cap_usb4 + PORT_CS_1, + PORT_CS_1_PND, 0, 500, USB4_PORT_SB_DELAY); + if (ret) { + tb_port_warn(port, "sideband channel still busy (PND=1)\n"); + return -EBUSY; + } + + return 0; +} + /** * usb4_port_sb_read() - Read from sideband register * @port: USB4 port to read @@ -1366,6 +1388,10 @@ int usb4_port_sb_read(struct tb_port *port, enum usb4_sb_target target, u8 index if (!port->cap_usb4) return -EINVAL; + ret = usb4_port_sb_wait_idle(port); + if (ret) + return ret; + val = reg; val |= size << PORT_CS_1_LENGTH_SHIFT; val |= (target << PORT_CS_1_TARGET_SHIFT) & PORT_CS_1_TARGET_MASK; @@ -1419,6 +1445,10 @@ int usb4_port_sb_write(struct tb_port *port, enum usb4_sb_target target, if (!port->cap_usb4) return -EINVAL; + ret = usb4_port_sb_wait_idle(port); + if (ret) + return ret; + if (buf) { ret = usb4_port_write_data(port, buf, dwords); if (ret) diff --git a/drivers/thunderbolt/xdomain.c b/drivers/thunderbolt/xdomain.c index 857219a9ac8da8..cd60c717ab4c53 100644 --- a/drivers/thunderbolt/xdomain.c +++ b/drivers/thunderbolt/xdomain.c @@ -17,6 +17,7 @@ #include #include #include +#include #include "tb.h" @@ -759,6 +760,26 @@ static void stop_handshake(struct tb_xdomain *xd) __stop_handshake(xd); } +/* + * The XDomain discovery requests answered while the control channel is kept + * through s2idle (tb->noirq_ctl_retained). They change no state: UUID and + * properties are answered from memory, and LINK_STATE_STATUS_REQUEST reads + * the downstream port's registers, under tb->lock, from a host router that + * stays powered (QUIRK_NO_SYSTEM_SLEEP). + */ +VISIBLE_IF_KUNIT bool tb_xdp_noirq_request(enum tb_xdp_type type) +{ + switch (type) { + case UUID_REQUEST_OLD: + case UUID_REQUEST: + case PROPERTIES_REQUEST: + case LINK_STATE_STATUS_REQUEST: + return true; + default: + return false; + } +} + static void tb_xdp_handle_request(struct work_struct *work) { struct xdomain_request_work *xw = container_of(work, typeof(*xw), work); @@ -777,19 +798,28 @@ static void tb_xdp_handle_request(struct work_struct *work) sequence = xhdr->length_sn & TB_XDOMAIN_SN_MASK; sequence >>= TB_XDOMAIN_SN_SHIFT; + /* + * Handle the request under tb->lock. tb_domain_suspend_noirq() and + * tb_domain_resume_noirq() set and clear noirq_ctl_retained under it, + * so a request queued before the control channel was retained cannot + * run a non-discovery request (or touch a port) during noirq, and the + * port read below cannot overlap the domain's suspend or resume. + */ mutex_lock(&tb->lock); if (tb->root_switch) uuid = kmemdup(tb->root_switch->uuid, sizeof(*uuid), GFP_KERNEL); else uuid = NULL; - mutex_unlock(&tb->lock); - if (!uuid) { + if (!uuid || (READ_ONCE(tb->noirq_ctl_retained) && + !tb_xdp_noirq_request(pkg->type))) { tb_xdp_error_response(ctl, route, sequence, ERROR_NOT_READY); + mutex_unlock(&tb->lock); goto out; } - xd = tb_xdomain_find_by_route_locked(tb, route); + /* tb->lock is held: the _locked helper would take it again. */ + xd = tb_xdomain_find_by_route(tb, route); if (xd) update_property_block(xd); @@ -831,7 +861,8 @@ static void tb_xdp_handle_request(struct work_struct *work) * timing out, we will restart the handshake now that we * received UUID request from the remote host. */ - if (!ret && xd && xd->state == XDOMAIN_STATE_ERROR) { + if (!READ_ONCE(tb->noirq_ctl_retained) && !ret && xd && + xd->state == XDOMAIN_STATE_ERROR) { mutex_lock(&xd->lock); if (!xd->removing) { dev_dbg(&xd->dev, "restarting handshake\n"); @@ -925,6 +956,7 @@ static void tb_xdp_handle_request(struct work_struct *work) } tb_xdomain_put(xd); + mutex_unlock(&tb->lock); if (ret) { tb_warn(tb, "failed to send XDomain response for %#x\n", @@ -2666,6 +2698,14 @@ bool tb_xdomain_handle_request(struct tb *tb, enum tb_cfg_pkg_type type, if (length < sizeof(*hdr) / 4 - sizeof(hdr->xd_hdr) / 4) return true; + if (READ_ONCE(tb->noirq_ctl_retained)) { + if (type != TB_CFG_PKG_XDOMAIN_REQ || !uuid_equal(&hdr->uuid, &tb_xdp_uuid)) + return true; + if (!tb_xdp_noirq_request(hdr->type)) + return true; + tb_dbg(tb, "XDomain discovery request %#x during s2idle\n", hdr->type); + } + /* * Handle XDomain discovery protocol packets directly here. For * other protocols (based on their UUID) we call registered diff --git a/drivers/tty/serial/Kconfig b/drivers/tty/serial/Kconfig index 53819706c237dd..ab38a0d6e89f4e 100644 --- a/drivers/tty/serial/Kconfig +++ b/drivers/tty/serial/Kconfig @@ -121,6 +121,22 @@ config SERIAL_APPLE_DOCKCHANNEL whose firmware has configured this transport, including T8140. It can take over from the DockChannel early console during boot. +config SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST + bool "KUnit tests for the Apple DockChannel UART" if !KUNIT_ALL_TESTS + depends on SERIAL_APPLE_DOCKCHANNEL && KUNIT=y + select IRQ_SIM + default KUNIT_ALL_TESTS + help + Drive the DockChannel UART port through a FIFO that the test models + behind static stubs: RX draining with the per-pass FIFO size clamp, + TX limited by the room in the FIFO and dropped when no reader comes, + the interrupt mask bits of other channels, startup and shutdown, + termios, and the console output helpers. The UART interrupt is a + simulated interrupt and the other registers are kernel memory. The + tests touch no hardware and register no port. + + If unsure, say N. + config SERIAL_SB1250_DUART tristate "BCM1xxx on-chip DUART serial support" depends on SIBYTE_SB1xxx_SOC=y diff --git a/drivers/tty/serial/apple_dockchannel_uart-test.c b/drivers/tty/serial/apple_dockchannel_uart-test.c new file mode 100644 index 00000000000000..0556266de9628e --- /dev/null +++ b/drivers/tty/serial/apple_dockchannel_uart-test.c @@ -0,0 +1,856 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple DockChannel UART. + * + * Included at the end of apple_dockchannel_uart.c. The port is built by the + * test and never registered. The data FIFO accesses of the RX drain and TX + * paths go to a model behind static stubs; the interrupt and config + * registers, and the data registers as the console helpers in + * apple_dockchannel.h see them, are buffers of kernel memory. Received bytes + * are read back from the port's flip buffers. Nothing touches hardware. + */ + +#include +#include +#include + +#define DCUT_CHANNEL 3 +#define DCUT_OTHERS (BIT(0) | BIT(1) | BIT(9) | BIT(31)) +#define DCUT_LOG 4096 +#define DCUT_STEPS 8 +#define DCUT_POISON 0xee +#define DCUT_RUNAWAY 32 +#define DCUT_CON (MAX_PORTS - 1) + +struct dcut_ctx { + struct dcuart_port dcuart; + struct uart_state *state; + u8 *data; + u8 *cfg; + u8 *irqregs; + + struct fwnode_handle *fwnode; + struct irq_domain *domain; + int virq; + bool irq_requested; + bool con_slot; + + /* RX FIFO: rx_q[rx_pos..rx_len), rx_visible of it in RX_COUNT. */ + u8 rx_q[DCUT_LOG]; + unsigned int rx_len; + unsigned int rx_pos; + unsigned int rx_visible; + /* Bytes that arrive each time RX_COUNT is read while it is 0. */ + unsigned int rx_chunk[DCUT_STEPS]; + unsigned int rx_nchunk; + unsigned int rx_chunk_pos; + u32 rx_counts[DCUT_STEPS]; + unsigned int rx_ncounts; + + /* TX FIFO */ + unsigned int tx_room; + u8 tx_log[DCUT_LOG]; + unsigned int tx_len; + unsigned int tx_free_reads; + + unsigned int violations; +}; + +static u32 *dcut_reg(u8 *base, unsigned int off) +{ + return (u32 *)(base + off); +} + +/* + * The stubs are active for the test task, so an interrupt that runs a real + * DockChannel port on top of it lands here too: give that port its own + * registers, as the driver would. + */ +static u32 dcut_rx_readl(struct dcuart_port *dcuart, u32 reg) +{ + struct dcut_ctx *ctx = kunit_get_current_test()->priv; + u8 c; + + if (dcuart != &ctx->dcuart) + return readl_relaxed(dcuart->port.membase + reg); + + switch (reg) { + case DATA_RX_COUNT: + if (!ctx->rx_visible && ctx->rx_chunk_pos < ctx->rx_nchunk) + ctx->rx_visible = ctx->rx_chunk[ctx->rx_chunk_pos++]; + if (ctx->violations > DCUT_RUNAWAY) + ctx->rx_visible = 0; + if (ctx->rx_ncounts < DCUT_STEPS) + ctx->rx_counts[ctx->rx_ncounts++] = ctx->rx_visible; + return ctx->rx_visible; + case DATA_RX8: + if (!ctx->rx_visible || ctx->rx_pos >= ctx->rx_len) { + ctx->violations++; + return 0xdeadbeef; + } + ctx->rx_visible--; + c = ctx->rx_q[ctx->rx_pos++]; + /* The byte comes in bits [15:8]; fill the other bits with junk. */ + return 0x5a0000a5 | (u32)c << 8; + default: + ctx->violations++; + return 0; + } +} + +static u32 dcut_tx_free(struct dcuart_port *dcuart) +{ + struct dcut_ctx *ctx = kunit_get_current_test()->priv; + + if (dcuart != &ctx->dcuart) + return readl(dcuart->port.membase + DATA_TX_FREE); + + ctx->tx_free_reads++; + return ctx->tx_room; +} + +static void dcut_tx_put(struct dcuart_port *dcuart, u8 ch) +{ + struct dcut_ctx *ctx = kunit_get_current_test()->priv; + + if (dcuart != &ctx->dcuart) { + writel(ch, dcuart->port.membase + DATA_TX8); + return; + } + + if (!ctx->tx_room || ctx->tx_len >= DCUT_LOG) { + ctx->violations++; + return; + } + ctx->tx_room--; + ctx->tx_log[ctx->tx_len++] = ch; +} + +static int dcut_init(struct kunit *test) +{ + struct dcut_ctx *ctx; + struct uart_port *port; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->data = kunit_kzalloc(test, 0x40, GFP_KERNEL); + ctx->cfg = kunit_kzalloc(test, 0x10, GFP_KERNEL); + ctx->irqregs = kunit_kzalloc(test, 0x10, GFP_KERNEL); + ctx->state = kunit_kzalloc(test, sizeof(*ctx->state), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->data); + KUNIT_ASSERT_NOT_NULL(test, ctx->cfg); + KUNIT_ASSERT_NOT_NULL(test, ctx->irqregs); + KUNIT_ASSERT_NOT_NULL(test, ctx->state); + test->priv = ctx; + + tty_port_init(&ctx->state->port); + KUNIT_ASSERT_EQ(test, kfifo_alloc(&ctx->state->port.xmit_fifo, PAGE_SIZE, + GFP_KERNEL), 0); + + /* As dcuart_probe() sets the port up. */ + port = &ctx->dcuart.port; + port->ops = &dcuart_ops; + port->fifosize = FIFO_SIZE; + port->iotype = UPIO_MEM32; + port->type = PORT_GENERIC; + port->membase = (void __force __iomem *)ctx->data; + port->state = ctx->state; + ctx->state->uart_port = port; + spin_lock_init(&port->lock); + spin_lock_init(&ctx->dcuart.lock); + ctx->dcuart.irq_base = (void __force __iomem *)ctx->irqregs; + ctx->dcuart.config_base = (void __force __iomem *)ctx->cfg; + ctx->dcuart.irq_tx = IRQ_TX(DCUT_CHANNEL); + ctx->dcuart.irq_rx = IRQ_RX(DCUT_CHANNEL); + timer_setup(&ctx->dcuart.drain_timer, dcuart_drain_timer, 0); + + kunit_activate_static_stub(test, dcuart_rx_readl, dcut_rx_readl); + kunit_activate_static_stub(test, dcuart_tx_free, dcut_tx_free); + kunit_activate_static_stub(test, dcuart_tx_put, dcut_tx_put); + + return 0; +} + +static void dcut_exit(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + if (!ctx || !ctx->state) + return; + + timer_delete_sync(&ctx->dcuart.drain_timer); + if (ctx->con_slot) + dcuart_ports[DCUT_CON] = NULL; + if (ctx->irq_requested) + free_irq(ctx->virq, ctx); + if (ctx->virq > 0) + irq_dispose_mapping(ctx->virq); + if (ctx->domain && !IS_ERR(ctx->domain)) + irq_domain_remove_sim(ctx->domain); + if (ctx->fwnode) + irq_domain_free_fwnode(ctx->fwnode); + tty_port_destroy(&ctx->state->port); + kfifo_free(&ctx->state->port.xmit_fifo); +} + +/* Give the port a (simulated) interrupt line, as a non-sw-drain probe does. */ +static irqreturn_t dcut_irq_handler(int irq, void *data) +{ + return IRQ_HANDLED; +} + +static void dcut_setup_irq(struct kunit *test, struct dcut_ctx *ctx) +{ + ctx->fwnode = irq_domain_alloc_named_fwnode("dockchannel-uart-kunit"); + KUNIT_ASSERT_NOT_NULL(test, ctx->fwnode); + ctx->domain = irq_domain_create_sim(ctx->fwnode, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(ctx->domain)); + ctx->virq = irq_create_mapping(ctx->domain, 0); + KUNIT_ASSERT_GT(test, ctx->virq, 0); + KUNIT_ASSERT_EQ(test, request_irq(ctx->virq, dcut_irq_handler, IRQF_NO_AUTOEN, + "dockchannel-uart-kunit", ctx), 0); + ctx->irq_requested = true; + ctx->dcuart.port.irq = ctx->virq; +} + +static bool dcut_irq_enabled(struct dcut_ctx *ctx) +{ + return !irqd_irq_disabled(irq_get_irq_data(ctx->virq)); +} + +static void dcut_queue_rx(struct dcut_ctx *ctx, unsigned int len, unsigned int visible) +{ + unsigned int i; + + for (i = 0; i < len; i++) + ctx->rx_q[i] = 0x20 + (i * 13) % 0x5f; + ctx->rx_len = len; + ctx->rx_visible = visible; +} + +static unsigned int dcut_queue_tx(struct dcut_ctx *ctx, const char *s) +{ + return kfifo_in(&ctx->state->port.xmit_fifo, s, strlen(s)); +} + +/* What the port handed to the TTY layer (flip buffers not yet pushed). */ +static unsigned int dcut_flip_read(struct dcut_ctx *ctx, u8 *out, unsigned int max) +{ + struct tty_buffer *b; + unsigned int n = 0, i; + + for (b = ctx->state->port.buf.head; b; b = b->next) + for (i = b->read; i < b->used && n < max; i++) + out[n++] = *char_buf_ptr(b, i); + + return n; +} + +static unsigned int dcut_drain(struct dcut_ctx *ctx, bool *got) +{ + unsigned long flags; + + spin_lock_irqsave(&ctx->dcuart.lock, flags); + *got = dcuart_drain_rx(&ctx->dcuart); + spin_unlock_irqrestore(&ctx->dcuart.lock, flags); + + return ctx->dcuart.port.icount.rx; +} + +static unsigned int dcut_tx_chars(struct dcut_ctx *ctx, bool tick) +{ + unsigned long flags; + unsigned int pending; + + uart_port_lock_irqsave(&ctx->dcuart.port, &flags); + pending = dcuart_tx_chars(&ctx->dcuart, tick); + uart_port_unlock_irqrestore(&ctx->dcuart.port, flags); + + return pending; +} + +/* RX */ + +static void dcut_drain_rx_bytes(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + u8 out[16]; + bool got; + + dcut_queue_rx(ctx, 5, 5); + + KUNIT_EXPECT_EQ(test, dcut_drain(ctx, &got), 5); + KUNIT_EXPECT_TRUE(test, got); + /* Each byte taken from bits [15:8] of the byte FIFO register. */ + KUNIT_ASSERT_EQ(test, dcut_flip_read(ctx, out, sizeof(out)), 5); + KUNIT_EXPECT_MEMEQ(test, out, ctx->rx_q, 5); + KUNIT_ASSERT_EQ(test, ctx->rx_ncounts, 2); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[0], 5); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[1], 0); + KUNIT_EXPECT_EQ(test, ctx->dcuart.port.icount.buf_overrun, 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_drain_rx_empty(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + u8 out[4]; + bool got; + + KUNIT_EXPECT_EQ(test, dcut_drain(ctx, &got), 0); + KUNIT_EXPECT_FALSE(test, got); + KUNIT_EXPECT_EQ(test, ctx->rx_ncounts, 1); + KUNIT_EXPECT_EQ(test, dcut_flip_read(ctx, out, sizeof(out)), 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_drain_rx_clamps_pass(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + static u8 out[DCUT_LOG]; + bool got; + + /* More than a FIFO's worth: one FIFO_SIZE pass, then the rest. */ + dcut_queue_rx(ctx, 3000, 3000); + + KUNIT_EXPECT_EQ(test, dcut_drain(ctx, &got), 3000); + KUNIT_ASSERT_EQ(test, ctx->rx_ncounts, 3); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[0], 3000); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[1], 3000 - FIFO_SIZE); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[2], 0); + KUNIT_ASSERT_EQ(test, dcut_flip_read(ctx, out, sizeof(out)), 3000); + KUNIT_EXPECT_MEMEQ(test, out, ctx->rx_q, 3000); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_drain_rx_arrivals(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + u8 out[16]; + bool got; + + /* Data that arrives while draining is drained too. */ + dcut_queue_rx(ctx, 10, 3); + ctx->rx_chunk[0] = 4; + ctx->rx_chunk[1] = 3; + ctx->rx_nchunk = 2; + + KUNIT_EXPECT_EQ(test, dcut_drain(ctx, &got), 10); + KUNIT_ASSERT_EQ(test, ctx->rx_ncounts, 4); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[0], 3); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[1], 4); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[2], 3); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[3], 0); + KUNIT_ASSERT_EQ(test, dcut_flip_read(ctx, out, sizeof(out)), 10); + KUNIT_EXPECT_MEMEQ(test, out, ctx->rx_q, 10); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_interrupt_rx(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + u32 *flag = dcut_reg(ctx->irqregs, IRQ_FLAG); + + dcut_queue_rx(ctx, 4, 4); + WRITE_ONCE(*flag, ctx->dcuart.irq_rx | ctx->dcuart.irq_tx | DCUT_OTHERS); + + KUNIT_EXPECT_EQ(test, dcuart_interrupt(0, &ctx->dcuart), IRQ_HANDLED); + KUNIT_EXPECT_EQ(test, ctx->dcuart.port.icount.rx, 4); + KUNIT_EXPECT_EQ(test, ctx->rx_visible, 0); + /* Only this channel's RX flag is cleared (write-one-to-clear). */ + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), ctx->dcuart.irq_rx); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_interrupt_other_channel(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + u32 *flag = dcut_reg(ctx->irqregs, IRQ_FLAG); + + dcut_queue_rx(ctx, 4, 4); + WRITE_ONCE(*flag, DCUT_OTHERS | IRQ_RX(DCUT_CHANNEL + 1) | IRQ_TX(DCUT_CHANNEL - 1)); + + KUNIT_EXPECT_EQ(test, dcuart_interrupt(0, &ctx->dcuart), IRQ_NONE); + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), DCUT_OTHERS | IRQ_RX(DCUT_CHANNEL + 1) | + IRQ_TX(DCUT_CHANNEL - 1)); + KUNIT_EXPECT_EQ(test, ctx->rx_ncounts, 0); + KUNIT_EXPECT_EQ(test, ctx->dcuart.port.icount.rx, 0); +} + +/* Interrupt mask, startup and shutdown */ + +static void dcut_irq_bits_per_channel(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, IRQ_TX(0), BIT(0)); + KUNIT_EXPECT_EQ(test, IRQ_RX(0), BIT(1)); + KUNIT_EXPECT_EQ(test, IRQ_TX(3), BIT(6)); + KUNIT_EXPECT_EQ(test, IRQ_RX(3), BIT(7)); + KUNIT_EXPECT_EQ(test, IRQ_RX(MAX_CHANNELS - 1), BIT(31)); +} + +static void dcut_irq_mask_other_channels(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + u32 *mask = dcut_reg(ctx->irqregs, IRQ_MASK); + u32 *flag = dcut_reg(ctx->irqregs, IRQ_FLAG); + + WRITE_ONCE(*mask, DCUT_OTHERS); + WRITE_ONCE(*flag, 0); + + dcuart_irq_enable(dc, dc->irq_rx); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS | dc->irq_rx); + /* Stale latched flag cleared before the unmask. */ + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), dc->irq_rx); + + dcuart_irq_update(dc, dc->irq_tx, true); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS | dc->irq_rx | dc->irq_tx); + + dcuart_irq_disable(dc, dc->irq_tx | dc->irq_rx); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS); + dcuart_irq_disable(dc, dc->irq_rx); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS); +} + +static void dcut_startup_irq_mode(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + u32 *mask = dcut_reg(ctx->irqregs, IRQ_MASK); + u32 *flag = dcut_reg(ctx->irqregs, IRQ_FLAG); + + dcut_setup_irq(test, ctx); + WRITE_ONCE(*mask, DCUT_OTHERS | dc->irq_tx); + WRITE_ONCE(*flag, 0); + + KUNIT_EXPECT_EQ(test, dcuart_startup(&dc->port), 0); + KUNIT_EXPECT_EQ(test, READ_ONCE(*dcut_reg(ctx->cfg, CONFIG_RX_THRESH)), 1); + KUNIT_EXPECT_EQ(test, READ_ONCE(*dcut_reg(ctx->cfg, CONFIG_TX_THRESH)), FIFO_SIZE); + /* RX unmasked, TX masked, the other channels untouched. */ + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS | dc->irq_rx); + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), dc->irq_rx); + KUNIT_EXPECT_TRUE(test, dcut_irq_enabled(ctx)); + KUNIT_EXPECT_FALSE(test, timer_pending(&dc->drain_timer)); + KUNIT_EXPECT_NE(test, ctx->state->port.closing_wait, ASYNC_CLOSING_WAIT_NONE); + + dcuart_shutdown(&dc->port); + KUNIT_EXPECT_FALSE(test, dcut_irq_enabled(ctx)); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS); +} + +static void dcut_startup_sw_drain(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + u32 *mask = dcut_reg(ctx->irqregs, IRQ_MASK); + + dc->sw_drain = true; + WRITE_ONCE(*mask, DCUT_OTHERS | dc->irq_rx | dc->irq_tx); + + KUNIT_EXPECT_EQ(test, dcuart_startup(&dc->port), 0); + /* No RX interrupt: the drain timer polls the channel. */ + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS); + KUNIT_EXPECT_TRUE(test, timer_pending(&dc->drain_timer)); + + dcuart_shutdown(&dc->port); + KUNIT_EXPECT_FALSE(test, timer_pending(&dc->drain_timer)); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS); +} + +static void dcut_startup_never_wait(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + + dc->sw_drain = true; + dc->never_wait = true; + + /* A close must not wait for a reader that may never come. */ + KUNIT_EXPECT_EQ(test, dcuart_startup(&dc->port), 0); + KUNIT_EXPECT_EQ(test, ctx->state->port.closing_wait, ASYNC_CLOSING_WAIT_NONE); + dcuart_shutdown(&dc->port); + KUNIT_EXPECT_FALSE(test, timer_pending(&dc->drain_timer)); +} + +/* TX */ + +static void dcut_tx_chars_room_limits(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + ctx->dcuart.never_wait = true; + dcut_queue_tx(ctx, "abcdefgh"); + ctx->tx_room = 5; + + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, false), 3); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 5); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, "abcde", 5); + KUNIT_EXPECT_EQ(test, ctx->dcuart.port.icount.tx, 5); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 3); + KUNIT_EXPECT_EQ(test, ctx->dcuart.tx_stuck_ticks, 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); + + /* The rest when room appears. */ + ctx->tx_room = 64; + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, true), 0); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 8); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, "abcdefgh", 8); +} + +static void dcut_tx_chars_exact_room(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + ctx->dcuart.never_wait = true; + dcut_queue_tx(ctx, "12345678"); + ctx->tx_room = 8; + + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, false), 0); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 8); + KUNIT_EXPECT_EQ(test, ctx->tx_room, 0); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_tx_chars_nothing_queued(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + ctx->tx_room = 8; + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, true), 0); + /* Not even a room read. */ + KUNIT_EXPECT_EQ(test, ctx->tx_free_reads, 0); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 0); +} + +static void dcut_tx_chars_no_reader_drops(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + ctx->dcuart.never_wait = true; + dcut_queue_tx(ctx, "wxyz"); + ctx->tx_room = 0; + + /* Without a tick (start_tx), a full FIFO is not counted. */ + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, false), 4); + KUNIT_EXPECT_EQ(test, ctx->dcuart.tx_stuck_ticks, 0); + + /* TX_STUCK_TICKS ticks without room: the queue goes. */ + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, true), 4); + KUNIT_EXPECT_EQ(test, ctx->dcuart.tx_stuck_ticks, 1); + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, true), 0); + KUNIT_EXPECT_EQ(test, ctx->dcuart.tx_stuck_ticks, 0); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 0); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_tx_chars_progress_resets(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + ctx->dcuart.never_wait = true; + dcut_queue_tx(ctx, "abcd"); + ctx->dcuart.tx_stuck_ticks = 1; + ctx->tx_room = 2; + + /* Some room: progress, so the stuck count starts over. */ + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, true), 2); + KUNIT_EXPECT_EQ(test, ctx->dcuart.tx_stuck_ticks, 0); + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, true), 2); + KUNIT_EXPECT_EQ(test, ctx->dcuart.tx_stuck_ticks, 1); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 2); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, "ab", 2); +} + +static void dcut_tx_chars_x_char(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + ctx->dcuart.never_wait = true; + ctx->dcuart.port.x_char = 0x13; + ctx->tx_room = 1; + + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, false), 0); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 1); + KUNIT_EXPECT_EQ(test, ctx->tx_log[0], 0x13); + KUNIT_EXPECT_EQ(test, ctx->dcuart.port.x_char, 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_tx_empty(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct uart_port *port = &ctx->dcuart.port; + + ctx->tx_room = 0; + KUNIT_EXPECT_EQ(test, dcuart_tx_empty(port), 0); + ctx->tx_room = 1; + KUNIT_EXPECT_EQ(test, dcuart_tx_empty(port), TIOCSER_TEMT); + + /* Never waiting: always empty, whatever the FIFO says. */ + ctx->dcuart.never_wait = true; + ctx->tx_room = 0; + ctx->tx_free_reads = 0; + KUNIT_EXPECT_EQ(test, dcuart_tx_empty(port), TIOCSER_TEMT); + KUNIT_EXPECT_EQ(test, ctx->tx_free_reads, 0); +} + +static void dcut_start_tx_never_wait(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + + dc->never_wait = true; + dcut_queue_tx(ctx, "hello"); + ctx->tx_room = 2; + + /* What does not fit goes from the timer. */ + dcuart_start_tx(&dc->port); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 2); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 3); + KUNIT_EXPECT_TRUE(test, timer_pending(&dc->drain_timer)); + timer_delete_sync(&dc->drain_timer); +} + +static void dcut_start_tx_waiting(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + + /* + * Without never_wait every byte goes through dockchannel_wait_putc(), + * which reads the register buffer directly. + */ + WRITE_ONCE(*dcut_reg(ctx->data, DATA_TX_FREE), 1); + dcut_queue_tx(ctx, "xyz"); + + dcuart_start_tx(&dc->port); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 0); + KUNIT_EXPECT_EQ(test, dc->port.icount.tx, 3); + KUNIT_EXPECT_EQ(test, READ_ONCE(*dcut_reg(ctx->data, DATA_TX8)), 'z'); + KUNIT_EXPECT_FALSE(test, timer_pending(&dc->drain_timer)); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 0); +} + +static void dcut_drain_timer_sw_drain(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + + dc->never_wait = true; + dc->sw_drain = true; + dcut_queue_rx(ctx, 3, 3); + dcut_queue_tx(ctx, "ok"); + ctx->tx_room = 16; + + dcuart_drain_timer(&dc->drain_timer); + KUNIT_EXPECT_EQ(test, dc->port.icount.rx, 3); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 2); + /* A software-drained channel keeps polling. */ + KUNIT_EXPECT_TRUE(test, timer_pending(&dc->drain_timer)); + timer_delete_sync(&dc->drain_timer); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_drain_timer_no_reader(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + + dc->never_wait = true; + dcut_queue_tx(ctx, "abc"); + ctx->tx_room = 0; + + dcuart_drain_timer(&dc->drain_timer); + KUNIT_EXPECT_TRUE(test, timer_pending(&dc->drain_timer)); + timer_delete_sync(&dc->drain_timer); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 3); + + /* The second tick without room drops the queue and stops the timer. */ + dcuart_drain_timer(&dc->drain_timer); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 0); + KUNIT_EXPECT_FALSE(test, timer_pending(&dc->drain_timer)); + KUNIT_EXPECT_EQ(test, ctx->rx_ncounts, 0); +} + +/* termios and port ops */ + +static void dcut_set_termios(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct ktermios t = { + .c_cflag = B9600 | CS7 | PARENB | PARODD | CRTSCTS, + }; + + dcuart_set_termios(&ctx->dcuart.port, &t, NULL); + /* 8N1 at 115200, CLOCAL, whatever was asked. */ + KUNIT_EXPECT_EQ(test, t.c_cflag & CSIZE, CS8); + KUNIT_EXPECT_FALSE(test, t.c_cflag & PARENB); + KUNIT_EXPECT_TRUE(test, t.c_cflag & CLOCAL); + KUNIT_EXPECT_EQ(test, tty_termios_baud_rate(&t), 115200); + KUNIT_EXPECT_EQ(test, t.c_ispeed, 115200); + KUNIT_EXPECT_EQ(test, t.c_ospeed, 115200); + /* 10 bits a character at 115200 baud, rounded up. */ + KUNIT_EXPECT_EQ(test, ctx->dcuart.port.frame_time, 86806); +} + +static void dcut_port_ops(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct uart_port *port = &ctx->dcuart.port; + + KUNIT_EXPECT_EQ(test, dcuart_get_mctrl(port), TIOCM_CAR | TIOCM_DSR | TIOCM_CTS); + KUNIT_EXPECT_STREQ(test, dcuart_type(port), "Apple DockChannel UART"); + port->type = PORT_UNKNOWN; + KUNIT_EXPECT_NULL(test, dcuart_type(port)); + dcuart_config_port(port, 0); + KUNIT_EXPECT_EQ(test, port->type, PORT_UNKNOWN); + dcuart_config_port(port, UART_CONFIG_TYPE); + KUNIT_EXPECT_EQ(test, port->type, PORT_GENERIC); +} + +/* Console helpers (apple_dockchannel.h, shared with the earlycon) */ + +static void dcut_console_putc_room(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + void __iomem *data = ctx->dcuart.port.membase; + u32 *tx_free = dcut_reg(ctx->data, DATA_TX_FREE); + u32 *tx8 = dcut_reg(ctx->data, DATA_TX8); + struct dockchannel_tx tx; + + dockchannel_tx_begin(&tx); + WRITE_ONCE(*tx_free, 2); + dockchannel_console_putc(data, &tx, 'a'); + dockchannel_console_putc(data, &tx, 'b'); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), 'b'); + KUNIT_EXPECT_EQ(test, tx.room, 0); + + /* Room used up: read again; it reads 0, so the rest is dropped. */ + WRITE_ONCE(*tx_free, 0); + dockchannel_console_putc(data, &tx, 'c'); + KUNIT_EXPECT_TRUE(test, tx.full); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), 'b'); + /* ... without reading again in the same write. */ + WRITE_ONCE(*tx_free, 5); + dockchannel_console_putc(data, &tx, 'd'); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), 'b'); + + /* The next write starts over. */ + dockchannel_tx_begin(&tx); + dockchannel_console_putc(data, &tx, 'e'); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), 'e'); + KUNIT_EXPECT_EQ(test, tx.room, 4); + KUNIT_EXPECT_FALSE(test, tx.full); +} + +static void dcut_wait_putc_no_reader(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + void __iomem *data = ctx->dcuart.port.membase; + u32 *tx_free = dcut_reg(ctx->data, DATA_TX_FREE); + u32 *tx8 = dcut_reg(ctx->data, DATA_TX8); + bool no_reader = false; + + WRITE_ONCE(*tx8, DCUT_POISON); + WRITE_ONCE(*tx_free, 0); + dockchannel_wait_putc(data, &no_reader, 'q'); + KUNIT_EXPECT_TRUE(test, no_reader); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), DCUT_POISON); + dockchannel_wait_putc(data, &no_reader, 'r'); + KUNIT_EXPECT_TRUE(test, no_reader); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), DCUT_POISON); + + /* Room again: write, and wait normally from now on. */ + WRITE_ONCE(*tx_free, 1); + dockchannel_wait_putc(data, &no_reader, 's'); + KUNIT_EXPECT_FALSE(test, no_reader); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), 's'); +} + +static void dcut_console_setup(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct console co = dcuart_console; + + co.index = -1; + KUNIT_EXPECT_EQ(test, dcuart_console_setup(&co, NULL), -ENODEV); + co.index = MAX_PORTS; + KUNIT_EXPECT_EQ(test, dcuart_console_setup(&co, NULL), -ENODEV); + + if (dcuart_ports[DCUT_CON]) + kunit_skip(test, "port %d is in use", DCUT_CON); + co.index = DCUT_CON; + KUNIT_EXPECT_EQ(test, dcuart_console_setup(&co, NULL), -ENODEV); + dcuart_ports[DCUT_CON] = &ctx->dcuart; + ctx->con_slot = true; + KUNIT_EXPECT_EQ(test, dcuart_console_setup(&co, NULL), 0); +} + +static void dcut_console_write_never_wait(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct console co = dcuart_console; + u32 *tx_free = dcut_reg(ctx->data, DATA_TX_FREE); + u32 *tx8 = dcut_reg(ctx->data, DATA_TX8); + + if (dcuart_ports[DCUT_CON]) + kunit_skip(test, "port %d is in use", DCUT_CON); + dcuart_ports[DCUT_CON] = &ctx->dcuart; + ctx->con_slot = true; + ctx->dcuart.never_wait = true; + co.index = DCUT_CON; + + /* No room: nothing written, and the write returns. */ + WRITE_ONCE(*tx8, DCUT_POISON); + WRITE_ONCE(*tx_free, 0); + dcuart_write(&co, "hi\n", 3); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), DCUT_POISON); + + WRITE_ONCE(*tx_free, 64); + dcuart_write(&co, "hi\n", 3); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), '\n'); + KUNIT_EXPECT_EQ(test, ctx->dcuart.console_tx.room, 64 - 4); +} + +static struct kunit_case dcuart_test_cases[] = { + KUNIT_CASE(dcut_drain_rx_bytes), + KUNIT_CASE(dcut_drain_rx_empty), + KUNIT_CASE(dcut_drain_rx_clamps_pass), + KUNIT_CASE(dcut_drain_rx_arrivals), + KUNIT_CASE(dcut_interrupt_rx), + KUNIT_CASE(dcut_interrupt_other_channel), + KUNIT_CASE(dcut_irq_bits_per_channel), + KUNIT_CASE(dcut_irq_mask_other_channels), + KUNIT_CASE(dcut_startup_irq_mode), + KUNIT_CASE(dcut_startup_sw_drain), + KUNIT_CASE(dcut_startup_never_wait), + KUNIT_CASE(dcut_tx_chars_room_limits), + KUNIT_CASE(dcut_tx_chars_exact_room), + KUNIT_CASE(dcut_tx_chars_nothing_queued), + KUNIT_CASE(dcut_tx_chars_no_reader_drops), + KUNIT_CASE(dcut_tx_chars_progress_resets), + KUNIT_CASE(dcut_tx_chars_x_char), + KUNIT_CASE(dcut_tx_empty), + KUNIT_CASE(dcut_start_tx_never_wait), + KUNIT_CASE(dcut_start_tx_waiting), + KUNIT_CASE(dcut_drain_timer_sw_drain), + KUNIT_CASE(dcut_drain_timer_no_reader), + KUNIT_CASE(dcut_set_termios), + KUNIT_CASE(dcut_port_ops), + KUNIT_CASE(dcut_console_putc_room), + KUNIT_CASE(dcut_wait_putc_no_reader), + KUNIT_CASE(dcut_console_setup), + KUNIT_CASE(dcut_console_write_never_wait), + {} +}; + +static struct kunit_suite dcuart_test_suite = { + .name = "apple-dockchannel-uart", + .init = dcut_init, + .exit = dcut_exit, + .test_cases = dcuart_test_cases, +}; + +kunit_test_suite(dcuart_test_suite); diff --git a/drivers/tty/serial/apple_dockchannel_uart.c b/drivers/tty/serial/apple_dockchannel_uart.c index 7150cf1cca350e..1411e84708c0d0 100644 --- a/drivers/tty/serial/apple_dockchannel_uart.c +++ b/drivers/tty/serial/apple_dockchannel_uart.c @@ -18,6 +18,10 @@ #include "apple_dockchannel.h" +#if IS_ENABLED(CONFIG_SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST) +#include +#endif + #define FIFO_SIZE 0x800 #define IRQ_MASK 0x0 @@ -81,6 +85,34 @@ static inline struct dcuart_port *port_to_dc(struct uart_port *port) return container_of(port, struct dcuart_port, port); } +/* + * Data FIFO accesses of the RX drain and the TX paths. They are functions so + * that the KUnit test can model the FIFO behind them. + */ +static u32 dcuart_rx_readl(struct dcuart_port *dcuart, u32 reg) +{ +#if IS_ENABLED(CONFIG_SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(dcuart_rx_readl, dcuart, reg); +#endif + return readl_relaxed(dcuart->port.membase + reg); +} + +static u32 dcuart_tx_free(struct dcuart_port *dcuart) +{ +#if IS_ENABLED(CONFIG_SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(dcuart_tx_free, dcuart); +#endif + return readl(dcuart->port.membase + DATA_TX_FREE); +} + +static void dcuart_tx_put(struct dcuart_port *dcuart, u8 ch) +{ +#if IS_ENABLED(CONFIG_SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(dcuart_tx_put, dcuart, ch); +#endif + writel(ch, dcuart->port.membase + DATA_TX8); +} + static void dcuart_irq_update(struct dcuart_port *dcuart, u32 bits, bool enable) { @@ -186,7 +218,7 @@ static bool dcuart_drain_rx(struct dcuart_port *dcuart) bool got = false; int left; - while ((left = readl_relaxed(dcuart->port.membase + DATA_RX_COUNT))) { + while ((left = dcuart_rx_readl(dcuart, DATA_RX_COUNT))) { left = min_t(size_t, left, FIFO_SIZE); while (left) { /* @@ -195,7 +227,7 @@ static bool dcuart_drain_rx(struct dcuart_port *dcuart) */ char c; - c = readl_relaxed(dcuart->port.membase + DATA_RX8) >> 8; + c = dcuart_rx_readl(dcuart, DATA_RX8) >> 8; uart_insert_char(&dcuart->port, 0, 0, c, TTY_NORMAL); dcuart->port.icount.rx++; left--; @@ -246,8 +278,8 @@ static unsigned int dcuart_tx_chars(struct dcuart_port *dcuart, bool tick) if (!queued && !port->x_char) return 0; - pending = uart_port_tx_limited(port, ch, readl(port->membase + DATA_TX_FREE), - true, writel(ch, port->membase + DATA_TX8), ({})); + pending = uart_port_tx_limited(port, ch, dcuart_tx_free(dcuart), + true, dcuart_tx_put(dcuart, ch), ({})); if (!pending || pending < queued) { dcuart->tx_stuck_ticks = 0; return pending; @@ -309,7 +341,7 @@ static void dcuart_drain_timer(struct timer_list *t) static unsigned int dcuart_tx_empty(struct uart_port *port) { if (!port_to_dc(port)->never_wait) - return (readl(port->membase + DATA_TX_FREE) != 0) ? TIOCSER_TEMT : 0; + return (dcuart_tx_free(port_to_dc(port)) != 0) ? TIOCSER_TEMT : 0; return TIOCSER_TEMT; } @@ -567,3 +599,7 @@ device_initcall(dcuart_init); MODULE_AUTHOR("Yureka Lilian "); MODULE_DESCRIPTION("Apple DockChannel UART driver"); MODULE_LICENSE("Dual MIT/GPL"); + +#if IS_ENABLED(CONFIG_SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST) +#include "apple_dockchannel_uart-test.c" +#endif diff --git a/drivers/tty/serial/apple_dockchannel_uart.kunitconfig b/drivers/tty/serial/apple_dockchannel_uart.kunitconfig new file mode 100644 index 00000000000000..81879d1b311880 --- /dev/null +++ b/drivers/tty/serial/apple_dockchannel_uart.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_ARM64_16K_PAGES=y +CONFIG_TTY=y +CONFIG_SERIAL_APPLE_DOCKCHANNEL=y +CONFIG_SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST=y diff --git a/drivers/usb/core/hcd.c b/drivers/usb/core/hcd.c index 0ea6a9a729bc52..7a96c9f01ed56c 100644 --- a/drivers/usb/core/hcd.c +++ b/drivers/usb/core/hcd.c @@ -2814,10 +2814,10 @@ int usb_add_hcd(struct usb_hcd *hcd, struct usb_hcd *shared_hcd; int skip_phy_initialization; - if (usb_hcd_is_primary_hcd(hcd)) - skip_phy_initialization = hcd->skip_phy_initialization; - else - skip_phy_initialization = hcd->primary_hcd->skip_phy_initialization; + /* A shared HCD skips its PHYs when it or its primary HCD asks for it. */ + skip_phy_initialization = hcd->skip_phy_initialization; + if (!usb_hcd_is_primary_hcd(hcd)) + skip_phy_initialization |= hcd->primary_hcd->skip_phy_initialization; if (!skip_phy_initialization) { if (usb_hcd_is_primary_hcd(hcd)) { diff --git a/drivers/usb/dwc3/core.c b/drivers/usb/dwc3/core.c index 7f68eba95e1f1b..3566533dda5a27 100644 --- a/drivers/usb/dwc3/core.c +++ b/drivers/usb/dwc3/core.c @@ -2962,6 +2962,10 @@ static const struct of_device_id of_dwc3_match[] = { { .compatible = "synopsys,dwc3" }, + { + /* Handed over in host mode by the bootloader, see apple,dwc3.yaml */ + .compatible = "apple,t8152-dwc3" + }, { }, }; MODULE_DEVICE_TABLE(of, of_dwc3_match); diff --git a/drivers/usb/dwc3/core.h b/drivers/usb/dwc3/core.h index 7821ccb4686e53..2b665349277ec4 100644 --- a/drivers/usb/dwc3/core.h +++ b/drivers/usb/dwc3/core.h @@ -1004,11 +1004,15 @@ struct dwc3_scratchpad_array { * @pre_run_stop: Notify run stop enable/disable information to glue * @pre_host_resume: Before xHCI touches the core at a system resume; an error keeps it away, * and a positive value says the core lost its state and was set up again + * @usb3_host_route: Sets up the USB3 PHY for xHCI's SuperSpeed root hub, which then leaves + * that PHY alone; runs after xhci_reset(), before xhci_run() starts the + * host controller, and an error fails xHCI's probe */ struct dwc3_glue_ops { void (*pre_set_role)(struct dwc3 *dwc, enum usb_role role); void (*pre_run_stop)(struct dwc3 *dwc, bool is_on); int (*pre_host_resume)(struct dwc3 *dwc); + int (*usb3_host_route)(struct dwc3 *dwc); }; /** diff --git a/drivers/usb/dwc3/dwc3-apple-state-test.c b/drivers/usb/dwc3/dwc3-apple-state-test.c index 69abb0f32653ff..db43ac587ebdef 100644 --- a/drivers/usb/dwc3/dwc3-apple-state-test.c +++ b/drivers/usb/dwc3/dwc3-apple-state-test.c @@ -46,11 +46,46 @@ static void dwc3_apple_role_during_sleep_test(struct kunit *test) KUNIT_EXPECT_EQ(test, dwc3_apple_state_for_role(USB_ROLE_NONE), DWC3_APPLE_NO_CABLE); } +/* Host mode leaves USB3 PHY routing to xHCI's shared root hub unless a pre-xHCI reset runs. */ +static void dwc3_apple_usb3_host_left_to_xhci_test(struct kunit *test) +{ + enum phy_mode mode = PHY_MODE_USB_HOST; + + KUNIT_EXPECT_EQ(test, dwc3_apple_usb3_mode_before_start(DWC3_APPLE_HOST, false, &mode), 0); + KUNIT_EXPECT_EQ(test, mode, PHY_MODE_INVALID); + + KUNIT_EXPECT_EQ(test, dwc3_apple_usb3_mode_before_start(DWC3_APPLE_HOST, true, &mode), 0); + KUNIT_EXPECT_EQ(test, mode, PHY_MODE_USB_HOST); +} + +/* Device mode routes the USB3 PHY before gadget init; non-roles are rejected. */ +static void dwc3_apple_usb3_device_and_non_role_test(struct kunit *test) +{ + static const enum dwc3_apple_state states[] = { + DWC3_APPLE_PROBE_PENDING, DWC3_APPLE_NO_CABLE, + }; + enum phy_mode mode = PHY_MODE_INVALID; + int i; + + KUNIT_EXPECT_EQ(test, dwc3_apple_usb3_mode_before_start(DWC3_APPLE_DEVICE, false, &mode), + 0); + KUNIT_EXPECT_EQ(test, mode, PHY_MODE_USB_DEVICE); + + for (i = 0; i < ARRAY_SIZE(states); i++) { + mode = PHY_MODE_USB_HOST; + KUNIT_EXPECT_EQ(test, dwc3_apple_usb3_mode_before_start(states[i], false, &mode), + -EINVAL); + KUNIT_EXPECT_EQ(test, mode, PHY_MODE_INVALID); + } +} + static struct kunit_case dwc3_apple_state_test_cases[] = { KUNIT_CASE(dwc3_apple_host_left_to_xhci_test), KUNIT_CASE(dwc3_apple_device_selected_before_reset_test), KUNIT_CASE(dwc3_apple_non_role_test), KUNIT_CASE(dwc3_apple_role_during_sleep_test), + KUNIT_CASE(dwc3_apple_usb3_host_left_to_xhci_test), + KUNIT_CASE(dwc3_apple_usb3_device_and_non_role_test), {} }; diff --git a/drivers/usb/dwc3/dwc3-apple-state.h b/drivers/usb/dwc3/dwc3-apple-state.h index bb8d827fdec4c5..50cb05550bc006 100644 --- a/drivers/usb/dwc3/dwc3-apple-state.h +++ b/drivers/usb/dwc3/dwc3-apple-state.h @@ -48,6 +48,38 @@ static inline int dwc3_apple_usb2_mode_before_reset(enum dwc3_apple_state target } } +/** + * dwc3_apple_usb3_mode_before_start() - USB3 PHY mode to select before xHCI or gadget starts + * @target: the state the controller is brought up in + * @pipe_reset_before_host: true if the controller pulses PHYSOFTRST before xHCI starts + * @mode: set to the mode to select, or to PHY_MODE_INVALID to route a host once xHCI has reset + * + * Device mode routes the USB3 PHY before dwc3_gadget_init(). Host mode routes it while xHCI + * sets up its SuperSpeed root hub, after xhci_reset() (USBCMD.HCRST) has completed on the + * dummy PIPE producer and dwc3_xhci_plat_start() has enabled SUSPHY, and before xhci_run(): + * routing the live USB3 PHY before dwc3_host_init() exposes an ongoing SuperSpeed link + * handshake to HCRST and can leave a partner hub stuck in Rx.Detect. Controllers that must + * pulse GUSB3PIPECTL.PHYSOFTRST before xHCI starts still route the PHY beforehand. + * + * Return: 0, or -EINVAL if @target is not DWC3_APPLE_HOST or DWC3_APPLE_DEVICE. + */ +static inline int dwc3_apple_usb3_mode_before_start(enum dwc3_apple_state target, + bool pipe_reset_before_host, + enum phy_mode *mode) +{ + switch (target) { + case DWC3_APPLE_HOST: + *mode = pipe_reset_before_host ? PHY_MODE_USB_HOST : PHY_MODE_INVALID; + return 0; + case DWC3_APPLE_DEVICE: + *mode = PHY_MODE_USB_DEVICE; + return 0; + default: + *mode = PHY_MODE_INVALID; + return -EINVAL; + } +} + /** * dwc3_apple_state_for_role() - state a role asks for while the core is stopped for sleep * @role: the role asked for diff --git a/drivers/usb/dwc3/dwc3-apple.c b/drivers/usb/dwc3/dwc3-apple.c index c5740ee25d5329..eb9aff615bcb4b 100644 --- a/drivers/usb/dwc3/dwc3-apple.c +++ b/drivers/usb/dwc3/dwc3-apple.c @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -193,6 +194,14 @@ struct dwc3_apple { bool pre_core_rpm; bool dt_dis_u3_susphy; bool sleep_ddr; + /* + * A host's USB3 PHY is routed from xHCI's probe, see dwc3_apple_usb3_host_route(): the + * task that runs that probe under the glue lock, whether the routing is still owed, and + * its result (-EINPROGRESS until the SuperSpeed root hub was set up). + */ + struct task_struct *host_start_task; + bool usb3_host_owed; + int usb3_host_ret; struct notifier_block pm_nb; /* Kept through a deep sleep, with the PHY's hibernation, and the GUID it had. */ bool sleep_in_place; @@ -314,6 +323,10 @@ static inline void dwc3_apple_mask(struct dwc3_apple *appledwc, u32 offset, u32 * of 0xd. Without the enable the core's power management accepts a * D0/D3 request but saves and restores nothing, so the PHY's hibernation for a sleep * needs it. + * This stays on T8140: the power-down scale is the number of suspend clock periods + * in one 16 kHz period, so it follows the SoC's suspend clock rate, and T8140 is the + * only SoC whose value is known. Another SoC that keeps its core through a deep sleep + * needs its own scale before it can set the enable. */ #define DWC3_APPLE_T8140_PWRDNSCALE 0xd @@ -647,8 +660,11 @@ static int dwc3_apple_pre_host_resume(struct dwc3 *dwc) return ret; } +static int dwc3_apple_usb3_host_route(struct dwc3 *dwc); + static const struct dwc3_glue_ops dwc3_apple_glue_ops = { .pre_host_resume = dwc3_apple_pre_host_resume, + .usb3_host_route = dwc3_apple_usb3_host_route, }; static bool dwc3_apple_host_before_core_init(struct dwc3_apple *appledwc, @@ -714,7 +730,8 @@ static int dwc3_apple_core_probe(struct dwc3_apple *appledwc, enum dwc3_apple_st * dwc3_core_probe() enabled runtime PM with the device active and forbade it, for the * dwc3 platform driver's own callbacks, which this glue does not use. The core is being * brought up now, so take the glue's reference (see dwc3_apple_core_start()) and, where - * that is tested, allow runtime PM so the reference alone decides. + * the power domain may drop under an idle controller (see dwc3_apple_idle_rpm()), allow + * runtime PM so the reference alone decides. */ pm_runtime_get_noresume(appledwc->dev); appledwc->rpm_held = true; @@ -940,25 +957,18 @@ static void dwc3_apple_usb3_pipe_reset(struct dwc3_apple *appledwc) msleep(100); } -/* Select the role in the core and route the USB3 PHY, before xhci or the gadget is started */ -static int dwc3_apple_set_role(struct dwc3_apple *appledwc, enum dwc3_apple_state state) +/* + * Route the USB3 PHY for the role. This platform requires SUSPHY to be enabled already in order + * to properly configure the PHY and switch dwc3's PIPE interface to the USB3 PHY. + */ +static int dwc3_apple_route_usb3(struct dwc3_apple *appledwc, enum phy_mode mode) { - bool host = state == DWC3_APPLE_HOST; + bool host = mode == PHY_MODE_USB_HOST; int ret; lockdep_assert_held(&appledwc->lock); - appledwc->dwc.dr_mode = host ? USB_DR_MODE_HOST : USB_DR_MODE_PERIPHERAL; - dwc3_apple_set_ptrcap(appledwc, host ? DWC3_GCTL_PRTCAP_HOST : DWC3_GCTL_PRTCAP_DEVICE); - /* - * This platform requires SUSPHY to be enabled here already in order to properly - * configure the PHY and switch dwc3's PIPE interface to USB3 PHY. The USB2 PHY's - * device mode and the T8132 host role were selected in dwc3_apple_core_start(); - * other host roles are selected by the xHCI root hub as it starts. - */ - appledwc->dwc.dis_u3_susphy_quirk = appledwc->dt_dis_u3_susphy; - dwc3_enable_susphy(&appledwc->dwc, true); - ret = phy_set_mode(appledwc->usb3_phy, host ? PHY_MODE_USB_HOST : PHY_MODE_USB_DEVICE); + ret = phy_set_mode(appledwc->usb3_phy, mode); if (ret) { /* * A failed T8132 BIST or PIPE handoff must not start xHCI. Neither must a failed @@ -980,13 +990,113 @@ static int dwc3_apple_set_role(struct dwc3_apple *appledwc, enum dwc3_apple_stat */ appledwc->dwc.dis_u3_susphy_quirk = true; dwc3_enable_susphy(&appledwc->dwc, true); - } else if (appledwc->usb3_phy && + } else if (host && appledwc->usb3_phy && of_device_is_compatible(appledwc->dev->of_node, "apple,t6040-dwc3")) { dwc3_apple_usb3_pipe_reset(appledwc); } return 0; } +/* + * Select the role in the core, and route the USB3 PHY before the gadget or xHCI starts unless + * dwc3_apple_usb3_mode_before_start() leaves a host's routing to dwc3_apple_usb3_host_route(). + */ +static int dwc3_apple_set_role(struct dwc3_apple *appledwc, enum dwc3_apple_state state) +{ + bool host = state == DWC3_APPLE_HOST; + bool pipe_reset = host && appledwc->usb3_phy && + of_device_is_compatible(appledwc->dev->of_node, "apple,t6040-dwc3"); + enum phy_mode mode; + int ret; + + lockdep_assert_held(&appledwc->lock); + + ret = dwc3_apple_usb3_mode_before_start(state, pipe_reset, &mode); + if (ret) + return ret; + + appledwc->dwc.dr_mode = host ? USB_DR_MODE_HOST : USB_DR_MODE_PERIPHERAL; + dwc3_apple_set_ptrcap(appledwc, host ? DWC3_GCTL_PRTCAP_HOST : DWC3_GCTL_PRTCAP_DEVICE); + appledwc->dwc.dis_u3_susphy_quirk = appledwc->dt_dis_u3_susphy; + /* + * A routing left to xHCI keeps SUSPHY clear through xhci_reset() on the dummy PIPE: + * dwc3_xhci_plat_start() enables it once that reset has completed. + */ + appledwc->usb3_host_owed = host && mode == PHY_MODE_INVALID; + dwc3_enable_susphy(&appledwc->dwc, !appledwc->usb3_host_owed); + if (appledwc->usb3_host_owed) + return 0; + + return dwc3_apple_route_usb3(appledwc, mode); +} + +/* + * Runs from xHCI's probe as its SuperSpeed root hub is set up: after xhci_reset() (USBCMD.HCRST) + * has completed on the dummy PIPE, with SUSPHY enabled, and before xhci_run() starts the + * controller. The root hub leaves the USB3 PHY alone (see dwc3_host_init()), so routing the + * live PIPE here cannot expose a SuperSpeed link handshake to that reset, and an error both + * stops xHCI before it starts and reaches dwc3_apple_host_start(). Only the probe that + * dwc3_apple_host_start() runs under the glue lock routes; any other one, such as a probe + * the driver core ran asynchronously, is refused, and dwc3_apple_host_start() probes again. + */ +static int dwc3_apple_usb3_host_route(struct dwc3 *dwc) +{ + struct dwc3_apple *appledwc = to_dwc3_apple(dwc); + + if (READ_ONCE(appledwc->host_start_task) != current) + return -EBUSY; + + lockdep_assert_held(&appledwc->lock); + appledwc->usb3_host_ret = 0; + if (appledwc->usb3_host_owed) + appledwc->usb3_host_ret = dwc3_apple_route_usb3(appledwc, PHY_MODE_USB_HOST); + appledwc->usb3_host_owed = false; + + return appledwc->usb3_host_ret; +} + +/* + * Start xHCI, with its USB3 PHY routed. dwc3_host_init() does not report a failed xHCI probe + * (platform_device_add() ignores it), and the driver core may have left that probe to run + * asynchronously, or to a driver not registered yet: bind it here, so that the routing's + * result is known and nothing routes the PIPE later without the glue lock. A probe that has + * routed it is not repeated, as its xhci_reset() would then run on the live PIPE. + */ +static int dwc3_apple_host_start(struct dwc3_apple *appledwc) +{ + struct dwc3 *dwc = &appledwc->dwc; + bool bound = false; + int ret; + + lockdep_assert_held(&appledwc->lock); + + appledwc->usb3_host_ret = -EINPROGRESS; + WRITE_ONCE(appledwc->host_start_task, current); + ret = dwc3_host_init(dwc); + if (!ret) { + scoped_guard(device, &dwc->xhci->dev) + bound = device_is_bound(&dwc->xhci->dev); + if (!bound && appledwc->usb3_host_ret == -EINPROGRESS) + bound = device_attach(&dwc->xhci->dev) > 0; + } + WRITE_ONCE(appledwc->host_start_task, NULL); + if (ret) + return ret; + + ret = appledwc->usb3_host_ret; + /* No SuperSpeed root hub was set up: xHCI has none, or no driver has bound it yet. */ + if (ret == -EINPROGRESS) + ret = bound ? 0 : -EPROBE_DEFER; + else if (!ret && !bound) + ret = -ENODEV; + if (ret) { + /* dwc3_host_exit() lets the USB3 PHY into P3 for the PIPE handback */ + dwc->dis_u3_susphy_quirk = appledwc->dt_dis_u3_susphy; + dwc3_host_exit(dwc); + } + return ret; +} + /* * No device mode: the T6040 USB2 PHY (phy-apple-t6040-usb2) and the T6050 Type-C PHY implement * host mode only, and a kernel built without gadget support turns dwc3_gadget_init() into a stub @@ -1027,7 +1137,7 @@ static int dwc3_apple_init(struct dwc3_apple *appledwc, enum dwc3_apple_state st switch (state) { case DWC3_APPLE_HOST: - ret = dwc3_host_init(&appledwc->dwc); + ret = dwc3_apple_host_start(appledwc); if (ret) { dev_err(appledwc->dev, "Failed to initialize host, ret=%d\n", ret); goto core_exit; @@ -1109,12 +1219,12 @@ static void dwc3_apple_check_hub_later(struct dwc3_apple *appledwc) /* * Waiting for a Type-C PHY that is not started after sleep is specific to the T6050 boards - * whose port controllers take the sleep's power states (J714s, J716c). The notifier work - * and its admission rules apply to every board. + * whose port controllers take the sleep's power states: those whose device tree describes + * the sleep. The notifier work and its admission rules apply to every board. */ static bool dwc3_apple_sleep_board(void) { - return of_machine_is_compatible("apple,j714s") || of_machine_is_compatible("apple,j716c"); + return apple_t6050_sleep_described(); } /* @@ -2014,6 +2124,45 @@ static bool dwc3_apple_has_fixed_hub(struct device *dev, u32 *port) return hub; } +/* + * Whether an idle controller may runtime-suspend and let its power domain drop. Everything + * that keeps state in that domain must be known to it: + * - the controller itself, which has no state of its own while its core is down; + * - its DARTs, which save and restore their state in their runtime PM callbacks. They are + * resumed before the controller, so a DART outside any domain would be written while the + * controller's domain is still off and come back empty; + * - its PHYs, which hold the domain while they have state in it, or follow it and restore + * that state once it is on again. + * The device tree says this with power-domains on all of them. + */ +static bool dwc3_apple_idle_rpm(struct device_node *np) +{ + static const struct { + const char *list; + const char *cells; + } suppliers[] = { + { "iommus", "#iommu-cells" }, + { "phys", "#phy-cells" }, + }; + struct of_phandle_iterator it; + int i, err; + + if (!of_property_present(np, "power-domains")) + return false; + for (i = 0; i < ARRAY_SIZE(suppliers); i++) { + of_for_each_phandle(&it, err, np, suppliers[i].list, suppliers[i].cells, 0) { + if (!of_property_present(it.node, "power-domains")) { + of_node_put(it.node); + return false; + } + } + if (err != -ENOENT) + return false; + } + + return true; +} + static int dwc3_apple_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -2029,9 +2178,7 @@ static int dwc3_apple_probe(struct platform_device *pdev) appledwc->host_only = dwc3_apple_host_only(dev); appledwc->dt_dis_u3_susphy = device_property_read_bool(dev, "snps,dis_u3_susphy_quirk"); appledwc->sleep_ddr = device_property_read_bool(dev, "apple,sleep-ddr"); - /* The PHY driver and the DARTs follow runtime PM on these SoCs. */ - appledwc->idle_rpm = of_device_is_compatible(dev->of_node, "apple,t6040-dwc3") || - of_device_is_compatible(dev->of_node, "apple,t8132-dwc3"); + appledwc->idle_rpm = dwc3_apple_idle_rpm(dev->of_node); mutex_init(&appledwc->lock); spin_lock_init(&appledwc->sleep_pm_lock); /* A never-connected port has no generic core probe to publish this. */ @@ -2049,17 +2196,15 @@ static int dwc3_apple_probe(struct platform_device *pdev) "Failed to get the USB2 PHY\n"); /* - * Older T8132 device trees and the T6040 ports without a USB3 PHY - * expose only USB2; a NULL PHY is a no-op. + * A port whose device tree names no USB3 PHY (the USB2-only T6040 ports, older T8132 + * device trees) exposes only USB2; a NULL PHY is a no-op. */ - if (of_device_is_compatible(dev->of_node, "apple,t8132-dwc3") || - of_device_is_compatible(dev->of_node, "apple,t6040-dwc3")) - appledwc->usb3_phy = devm_phy_optional_get(dev, "usb3-phy"); - else - appledwc->usb3_phy = devm_phy_get(dev, "usb3-phy"); + appledwc->usb3_phy = devm_phy_optional_get(dev, "usb3-phy"); if (IS_ERR(appledwc->usb3_phy)) return dev_err_probe(dev, PTR_ERR(appledwc->usb3_phy), "Failed to get the USB3 PHY\n"); + if (!appledwc->usb3_phy) + dev_dbg(dev, "no USB3 PHY in the device tree: USB2 only\n"); ret = reset_control_assert(appledwc->reset); if (ret) { @@ -2122,11 +2267,9 @@ static int dwc3_apple_probe(struct platform_device *pdev) /* * Until the first cable there is no core to keep powered: let the controller * runtime-suspend, and its DARTs with it, so that its power domain can drop. - * Tested on T8132; on the T6041 (M4 Max) the never-plugged ports are the usual case. + * A fixed-hub host starts below, so it never waits for a cable. */ - if (appledwc->idle_rpm && !appledwc->fixed_hub && - (of_device_is_compatible(dev->of_node, "apple,t8132-dwc3") || - of_machine_is_compatible("apple,t6041"))) { + if (appledwc->idle_rpm && !appledwc->fixed_hub) { pm_runtime_set_active(dev); pm_runtime_enable(dev); appledwc->pre_core_rpm = true; @@ -2226,3 +2369,4 @@ module_platform_driver(dwc3_apple_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Sven Peter "); MODULE_DESCRIPTION("DesignWare DWC3 Apple Silicon Glue Driver"); +MODULE_SOFTDEP("pre: xhci_plat_hcd"); diff --git a/drivers/usb/dwc3/host.c b/drivers/usb/dwc3/host.c index 652942d3f6f4f9..358ce65772aa7a 100644 --- a/drivers/usb/dwc3/host.c +++ b/drivers/usb/dwc3/host.c @@ -79,6 +79,21 @@ static void dwc3_xhci_plat_start(struct usb_hcd *hcd) dwc3_enable_susphy(dwc, true); } +/* + * The SuperSpeed root hub is set up after xhci_reset() and dwc3_xhci_plat_start() on the + * primary HCD, and before xhci_run() starts the controller. + */ +static int dwc3_xhci_plat_init_quirk(struct usb_hcd *hcd) +{ + struct platform_device *pdev = to_platform_device(hcd->self.controller); + struct dwc3 *dwc = dev_get_drvdata(pdev->dev.parent); + + if (usb_hcd_is_primary_hcd(hcd) || !dwc->glue_ops || !dwc->glue_ops->usb3_host_route) + return 0; + + return dwc->glue_ops->usb3_host_route(dwc); +} + static int dwc3_xhci_plat_resume_quirk(struct usb_hcd *hcd) { struct platform_device *pdev = to_platform_device(hcd->self.controller); @@ -92,6 +107,7 @@ static int dwc3_xhci_plat_resume_quirk(struct usb_hcd *hcd) static const struct xhci_plat_priv dwc3_xhci_plat_quirk = { .plat_start = dwc3_xhci_plat_start, + .init_quirk = dwc3_xhci_plat_init_quirk, .resume_quirk = dwc3_xhci_plat_resume_quirk, }; @@ -190,6 +206,7 @@ EXPORT_SYMBOL_IF_KUNIT(dwc3_host_xhci_properties); int dwc3_host_init(struct dwc3 *dwc) { struct property_entry props[DWC3_XHCI_MAX_PROPERTIES + 1]; + struct xhci_plat_priv priv = dwc3_xhci_plat_quirk; struct platform_device *xhci; int ret, irq; int prop_idx = 0; @@ -231,8 +248,9 @@ int dwc3_host_init(struct dwc3 *dwc) } } - ret = platform_device_add_data(xhci, &dwc3_xhci_plat_quirk, - sizeof(struct xhci_plat_priv)); + /* A glue that sets up the USB3 PHY itself keeps it off the SuperSpeed root hub. */ + priv.skip_usb3_phy_init = dwc->glue_ops && dwc->glue_ops->usb3_host_route; + ret = platform_device_add_data(xhci, &priv, sizeof(priv)); if (ret) goto err; diff --git a/drivers/usb/host/pci-quirks.c b/drivers/usb/host/pci-quirks.c index 26bba2d42b1bbd..29f1e4ac0d09d7 100644 --- a/drivers/usb/host/pci-quirks.c +++ b/drivers/usb/host/pci-quirks.c @@ -1147,6 +1147,14 @@ void usb_disable_xhci_ports(struct pci_dev *xhci_pdev) } EXPORT_SYMBOL_GPL(usb_disable_xhci_ports); +/* + * The capability registers that every xHCI revision defines end with RTSOFF + * at offset 0x18 (xHCI 1.2, section 5.3), so the operational registers that + * CAPLENGTH points to start at 0x1c or later, on a dword boundary (section + * 5.4). + */ +#define XHCI_MIN_CAP_LENGTH 0x1c + /* * PCI Quirks for xHCI. * @@ -1227,11 +1235,11 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) /* * A dead or unprogrammed BAR reads as all-ones. The capability * length is then 0xff, and the operational-register read below is - * not 4-byte aligned and faults. A real xHCI length is at least - * 0x10 and dword-aligned. + * not 4-byte aligned and faults. A real xHCI length covers the + * capability registers and is dword-aligned, see XHCI_MIN_CAP_LENGTH. */ val = readl(base); - if (XHCI_HC_LENGTH(val) < 0x10 || (XHCI_HC_LENGTH(val) & 3)) { + if (XHCI_HC_LENGTH(val) < XHCI_MIN_CAP_LENGTH || (XHCI_HC_LENGTH(val) & 3)) { dev_warn(&pdev->dev, "xHCI capability length %#x unusable, skipping handoff\n", XHCI_HC_LENGTH(val)); diff --git a/drivers/usb/host/xhci-plat.c b/drivers/usb/host/xhci-plat.c index 5ded59ac0f54de..0f891d99527f6a 100644 --- a/drivers/usb/host/xhci-plat.c +++ b/drivers/usb/host/xhci-plat.c @@ -365,6 +365,8 @@ int xhci_plat_probe(struct platform_device *pdev, struct device *sysdev, const s } xhci->shared_hcd->tpl_support = hcd->tpl_support; + if (priv && priv->skip_usb3_phy_init) + xhci->shared_hcd->skip_phy_initialization = 1; } usb3_hcd = xhci_get_usb3_hcd(xhci); diff --git a/drivers/usb/host/xhci-plat.h b/drivers/usb/host/xhci-plat.h index 0c4affdb5236d0..6ddee6b064f922 100644 --- a/drivers/usb/host/xhci-plat.h +++ b/drivers/usb/host/xhci-plat.h @@ -17,6 +17,8 @@ struct xhci_plat_priv { unsigned long long quirks; bool power_lost; unsigned sideband_at_suspend:1; + /* The platform glue sets up the USB3 PHY: the SuperSpeed root hub leaves it alone. */ + unsigned skip_usb3_phy_init:1; void (*plat_start)(struct usb_hcd *); int (*init_quirk)(struct usb_hcd *); int (*suspend_quirk)(struct usb_hcd *); diff --git a/drivers/usb/typec/tipd/Kconfig b/drivers/usb/typec/tipd/Kconfig index 40e55777c62831..cbc177901c71e9 100644 --- a/drivers/usb/typec/tipd/Kconfig +++ b/drivers/usb/typec/tipd/Kconfig @@ -56,7 +56,7 @@ config TYPEC_TIPD_KUNIT_TEST Also test that interrupt events which could not be read or cleared are still acknowledged, however long that keeps failing, so that the controller keeps raising its interrupt. - Also test that a USB4/Thunderbolt router which never registers its + Also test that a USB4/Thunderbolt router which has not registered its switch does not keep the port from probing. Also test that a Type-C state which a mux provider with transient timeouts holds up is applied again until it goes through, for up to diff --git a/drivers/usb/typec/tipd/cd321x-tbt-test.c b/drivers/usb/typec/tipd/cd321x-tbt-test.c index 8e1d83d18546c5..ebf27926171df4 100644 --- a/drivers/usb/typec/tipd/cd321x-tbt-test.c +++ b/drivers/usb/typec/tipd/cd321x-tbt-test.c @@ -4,7 +4,6 @@ */ #include -#include #include #include #include @@ -100,21 +99,10 @@ static const struct software_node * const cd321x_test_nodes[] = { struct cd321x_tbt_test { struct device *dev; - bool keep_waiting; - unsigned int keep_waiting_calls; unsigned int set_calls; int last_state; }; -/* Stands in for the driver core's answer on whether to keep waiting. */ -static bool cd321x_tbt_test_keep_waiting(struct device *dev) -{ - struct cd321x_tbt_test *ctx = kunit_get_current_test()->priv; - - ctx->keep_waiting_calls++; - return ctx->keep_waiting; -} - static void cd321x_tbt_test_unregister_nodes(void *unused) { software_node_unregister_node_group(cd321x_test_nodes); @@ -137,9 +125,6 @@ static int cd321x_tbt_test_init(struct kunit *test) ctx->dev = kunit_device_register(test, "cd321x"); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); - - kunit_activate_static_stub(test, cd321x_tbt_switch_keep_waiting, - cd321x_tbt_test_keep_waiting); return 0; } @@ -170,7 +155,6 @@ static void cd321x_tbt_no_router_test(struct kunit *test) &late); KUNIT_EXPECT_NULL(test, sw); KUNIT_EXPECT_FALSE(test, late); - KUNIT_EXPECT_EQ(test, ctx->keep_waiting_calls, 0); } /* A router whose driver has registered its switch is used. */ @@ -203,44 +187,25 @@ static void cd321x_tbt_router_bound_test(struct kunit *test) &late); KUNIT_EXPECT_NOT_ERR_OR_NULL(test, sw); KUNIT_EXPECT_FALSE(test, late); - KUNIT_EXPECT_EQ(test, ctx->keep_waiting_calls, 0); typec_thunderbolt_switch_put(sw); } -/* A router that has not registered its switch yet defers the port. */ -static void cd321x_tbt_router_pending_test(struct kunit *test) -{ - struct cd321x_tbt_test *ctx = test->priv; - struct typec_thunderbolt_switch *sw; - bool late = true; - - ctx->keep_waiting = true; - sw = cd321x_tbt_switch_get(ctx->dev, - software_node_fwnode(&cd321x_test_connector), - &late); - KUNIT_EXPECT_PTR_EQ(test, sw, ERR_PTR(-EPROBE_DEFER)); - KUNIT_EXPECT_FALSE(test, late); - KUNIT_EXPECT_EQ(test, ctx->keep_waiting_calls, 1); -} - /* - * Once the driver core stops waiting for missing dependencies, a router that - * has not registered its switch no longer keeps the port from probing, and the - * port is told to take the router if it binds later. + * A router that has not registered its switch does not keep the port from + * probing, even while the driver core still waits for missing dependencies: + * the port is told to take the router when it binds. */ -static void cd321x_tbt_router_never_binds_test(struct kunit *test) +static void cd321x_tbt_router_pending_test(struct kunit *test) { struct cd321x_tbt_test *ctx = test->priv; struct typec_thunderbolt_switch *sw; bool late = false; - ctx->keep_waiting = false; sw = cd321x_tbt_switch_get(ctx->dev, software_node_fwnode(&cd321x_test_connector), &late); KUNIT_EXPECT_NULL(test, sw); KUNIT_EXPECT_TRUE(test, late); - KUNIT_EXPECT_EQ(test, ctx->keep_waiting_calls, 1); } static int cd321x_tbt_test_notify(struct notifier_block *nb, @@ -458,7 +423,6 @@ static struct kunit_case cd321x_tbt_cases[] = { KUNIT_CASE(cd321x_tbt_no_router_test), KUNIT_CASE(cd321x_tbt_router_bound_test), KUNIT_CASE(cd321x_tbt_router_pending_test), - KUNIT_CASE(cd321x_tbt_router_never_binds_test), KUNIT_CASE(cd321x_tbt_router_binds_late_test), KUNIT_CASE(cd321x_tbt_router_bound_before_watch_test), KUNIT_CASE(cd321x_tbt_other_router_binds_test), diff --git a/drivers/usb/typec/tipd/core.c b/drivers/usb/typec/tipd/core.c index 0294061aaaceba..d9ece372d36a4a 100644 --- a/drivers/usb/typec/tipd/core.c +++ b/drivers/usb/typec/tipd/core.c @@ -2846,21 +2846,13 @@ VISIBLE_IF_KUNIT int cd321x_reboot_notify(struct notifier_block *nb, } EXPORT_SYMBOL_IF_KUNIT(cd321x_reboot_notify); -/* Separate so that the KUnit tests can choose the driver core's answer. */ -VISIBLE_IF_KUNIT bool cd321x_tbt_switch_keep_waiting(struct device *dev) -{ - KUNIT_STATIC_STUB_REDIRECT(cd321x_tbt_switch_keep_waiting, dev); - - return driver_deferred_probe_check_state(dev) == -EPROBE_DEFER; -} -EXPORT_SYMBOL_IF_KUNIT(cd321x_tbt_switch_keep_waiting); - /* * The USB4/Thunderbolt router is only needed once a USB4 or Thunderbolt link * comes up. If its driver is not built or has not bound yet, do not leave power - * delivery, USB and DisplayPort on this port without a driver as well: stop - * waiting for the router when the driver core stops waiting for missing - * dependencies. The router can still bind later, so set @late to take it then. + * delivery, USB and DisplayPort on this port without a driver as well. The port + * takes the router whenever it binds (set @late), so it does not wait for it: + * waiting for the driver core to give up on a router that is not built delays + * every port by the deferred probe timeout. */ VISIBLE_IF_KUNIT struct typec_thunderbolt_switch * cd321x_tbt_switch_get(struct device *dev, struct fwnode_handle *fwnode, @@ -2870,7 +2862,7 @@ cd321x_tbt_switch_get(struct device *dev, struct fwnode_handle *fwnode, *late = false; sw = fwnode_typec_thunderbolt_switch_get(fwnode); - if (sw != ERR_PTR(-EPROBE_DEFER) || cd321x_tbt_switch_keep_waiting(dev)) + if (sw != ERR_PTR(-EPROBE_DEFER)) return sw; dev_info(dev, "USB4/Thunderbolt router unavailable, continuing without it until it binds\n"); @@ -2880,9 +2872,9 @@ cd321x_tbt_switch_get(struct device *dev, struct fwnode_handle *fwnode, EXPORT_SYMBOL_IF_KUNIT(cd321x_tbt_switch_get); /* - * Take a router that bound after the port gave up on it, or that unbound and - * bound again. An attached cable raises no new event, so reapply it through - * the router as after system sleep. + * Take a router that bound after the port probed without it, or that unbound + * and bound again. An attached cable raises no new event, so reapply it + * through the router as after system sleep. */ static void cd321x_tbt_attach_work(struct work_struct *work) { @@ -3589,33 +3581,38 @@ static int cd321x_remove(struct tps6598x *tps) } /* - * Boards whose inherited boot connection must be renegotiated. The port - * controller key is the reversed target identifier. - * - * J716c: the boot port keeps a USB2 repeater connection. - * J575c: a connection that was up before Linux keeps its Type-C retimer set up - * from before the host PHY ran, so SuperSpeed stays in RxDetect until the - * partner is replugged. Byte 7 of register 0x7e has bit 3 set once the - * controller has completed an attach with the OS running (after a replug, and - * under macOS) and bit 2 in the inherited state; renegotiate only without - * bit 3. A failure leaves the port as it was (USB2 only) instead of failing - * the probe. + * An SN201202x takes "DISC" unlocked with the key its DT gives it (apple,debug-lock-key, the board + * number reversed). */ -#define CD321X_ATTACH_STATE_REG 0x7e -#define CD321X_ATTACH_STATE_BYTE 7 -#define CD321X_ATTACH_STATE_DONE BIT(3) +static int tipd_replug_key(struct tps6598x *tps, u8 key[4]) +{ + const char *s; + if (!device_is_compatible(tps->dev, "apple,sn201202x") || + device_property_read_string(tps->dev, "apple,debug-lock-key", &s) || strlen(s) != 4) + return -EOPNOTSUPP; + memcpy(key, s, 4); + return 0; +} + +/* + * A connection that was up before Linux keeps state from the boot chain: a USB2 repeater + * connection on the J716c boot port, or on the J575c a Type-C retimer set up before the host PHY + * ran, so SuperSpeed stays in RxDetect until the partner is replugged. The controller reports + * nothing that tells such a connection apart from one that trains, so every one is renegotiated. + * + * The renegotiation's DISC takes the controller unlocked with the board's LOCK key, the board + * number reversed. A port whose DT gives it (apple,debug-lock-key) is left as it was if the + * renegotiation fails. The J716c's DT does not give it yet: its key is here, and a failure there + * fails the probe. + */ struct cd321x_inherited_board { const char *compatible; u8 key[4]; - bool check_attach_state; - bool best_effort; }; static const struct cd321x_inherited_board cd321x_inherited_boards[] = { { .compatible = "apple,j716c", .key = { '6', '1', '7', 'J' } }, - { .compatible = "apple,j575c", .key = { '5', '7', '5', 'J' }, - .check_attach_state = true, .best_effort = true }, }; static const struct cd321x_inherited_board *cd321x_inherited_board(void) @@ -3628,21 +3625,7 @@ static const struct cd321x_inherited_board *cd321x_inherited_board(void) return NULL; } -static int cd321x_attach_state_done(struct tps6598x *tps) -{ - u8 state[CD321X_ATTACH_STATE_BYTE + 1]; - int ret; - - ret = tps6598x_block_read(tps, CD321X_ATTACH_STATE_REG, state, sizeof(state)); - if (ret) - return ret; - dev_dbg(tps->dev, "inherited connection, attach state 0x%02x\n", - state[CD321X_ATTACH_STATE_BYTE]); - return !!(state[CD321X_ATTACH_STATE_BYTE] & CD321X_ATTACH_STATE_DONE); -} - -static int __cd321x_reset_inherited_connection(struct tps6598x *tps, - const struct cd321x_inherited_board *board, +static int __cd321x_reset_inherited_connection(struct tps6598x *tps, const u8 key[4], u32 *status) { static const u8 locked[4]; @@ -3653,15 +3636,9 @@ static int __cd321x_reset_inherited_connection(struct tps6598x *tps, mode = tps6598x_check_mode(tps); if (mode != TPS_MODE_APP && mode != TPS_MODE_APP1) return 0; - if (board->check_attach_state) { - ret = cd321x_attach_state_done(tps); - if (ret) - return ret < 0 ? ret : 0; - } /* All suppliers are available, but no USB or router session has started. */ - ret = tps6598x_exec_cmd(tps, "LOCK", sizeof(board->key), board->key, sizeof(result), - &result); + ret = tps6598x_exec_cmd(tps, "LOCK", 4, key, sizeof(result), &result); if (ret) return ret; if (result) { @@ -3704,6 +3681,8 @@ static int __cd321x_reset_inherited_connection(struct tps6598x *tps, static int cd321x_reset_inherited_connection(struct tps6598x *tps, u32 *status) { const struct cd321x_inherited_board *board; + bool best_effort = true; + u8 key[4]; int ret; if (!device_property_read_bool(tps->dev, "apple,reset-inherited-usb2-connection") || @@ -3711,12 +3690,19 @@ static int cd321x_reset_inherited_connection(struct tps6598x *tps, u32 *status) tps->dbma_at_probe || !(*status & TPS_STATUS_PLUG_PRESENT) || !TPS_STATUS_TO_TYPEC_DATAROLE(*status)) return 0; - board = cd321x_inherited_board(); - if (!board) - return 0; + if (tipd_replug_key(tps, key)) { + board = cd321x_inherited_board(); + if (!board) { + dev_warn(tps->dev, + "inherited connection not reinitialized: no apple,debug-lock-key\n"); + return 0; + } + memcpy(key, board->key, sizeof(key)); + best_effort = false; + } - ret = __cd321x_reset_inherited_connection(tps, board, status); - if (!ret || !board->best_effort) + ret = __cd321x_reset_inherited_connection(tps, key, status); + if (!ret || !best_effort) return ret; dev_warn(tps->dev, "inherited connection not reinitialized: %d\n", ret); @@ -3753,21 +3739,6 @@ static void tipd_port_list_del(struct tps6598x *tps) cancel_work_sync(&tps->replug_work); } -/* - * An SN201202x takes "DISC" unlocked with the key its DT gives it (apple,debug-lock-key, the board - * number reversed). - */ -static int tipd_replug_key(struct tps6598x *tps, u8 key[4]) -{ - const char *s; - - if (!device_is_compatible(tps->dev, "apple,sn201202x") || - device_property_read_string(tps->dev, "apple,debug-lock-key", &s) || strlen(s) != 4) - return -EOPNOTSUPP; - memcpy(key, s, 4); - return 0; -} - bool tipd_replug_supported(struct tps6598x *tps) { u8 key[4]; diff --git a/drivers/usb/typec/tipd/spmi.c b/drivers/usb/typec/tipd/spmi.c index 35314ddce15ea2..44e574400b6ec8 100644 --- a/drivers/usb/typec/tipd/spmi.c +++ b/drivers/usb/typec/tipd/spmi.c @@ -18,6 +18,13 @@ #define tps_to_sn(tps) container_of_const((tps), struct sn201202x, cd.tps) +/* How long a register selection may take to be confirmed. */ +#define SN201202X_SELECT_TIMEOUT_US 100000 +/* + * The same while the controller wakes up: a selection sent before it is + * awake is never confirmed, so sn201202x_wake_poll() retries after this. + */ +#define SN201202X_WAKE_SELECT_TIMEOUT_US 5000 /* A sleeping controller does not answer a select; give up on it sooner. */ #define SN201202X_ATOMIC_SELECT_MS 10 @@ -34,7 +41,8 @@ #define SN201202X_LDCM_RESULT GENMASK(5, 4) #define SN201202X_LDCM_RETRY_MS 500 -static int regmap_sn201202x_select_reg(struct spmi_device *sdev, u8 reg) +static int sn201202x_select_reg(struct spmi_device *sdev, u8 reg, + unsigned int timeout_us) { int err; u8 val; @@ -55,19 +63,23 @@ static int regmap_sn201202x_select_reg(struct spmi_device *sdev, u8 reg) if (sn->polled || sn->select_polled) { int poll_err; - if (sn->atomic) + if (sn->atomic) { + unsigned int atomic_us = min_t(unsigned int, timeout_us, + SN201202X_ATOMIC_SELECT_MS * 1000); + poll_err = read_poll_timeout_atomic(spmi_register_read, err, err || val == reg, 100, - SN201202X_ATOMIC_SELECT_MS * 1000, - false, sdev, 0, &val); - else + atomic_us, false, sdev, 0, &val); + } else { poll_err = read_poll_timeout(spmi_register_read, err, - err || val == reg, 100, 100000, + err || val == reg, 100, timeout_us, false, sdev, 0, &val); + } return err ?: poll_err; } - if (!wait_for_completion_timeout(&sn->select_completion, msecs_to_jiffies(100))) + if (!wait_for_completion_timeout(&sn->select_completion, + max(1UL, usecs_to_jiffies(timeout_us)))) return -ETIMEDOUT; while (--attempts) { @@ -91,6 +103,11 @@ static int regmap_sn201202x_select_reg(struct spmi_device *sdev, u8 reg) return -EIO; } +static int regmap_sn201202x_select_reg(struct spmi_device *sdev, u8 reg) +{ + return sn201202x_select_reg(sdev, reg, SN201202X_SELECT_TIMEOUT_US); +} + static int __regmap_sn201202x_read(void *context, const void *reg, size_t reg_size, void *val, size_t val_size) @@ -580,7 +597,12 @@ static int sn201202x_wake_poll(struct sn201202x *sn, bool poll) msecs_to_jiffies(100))) return 0; - /* A sleeping ACE3 ACKs commands but returns zeros until it is awake. */ + /* + * A sleeping ACE3 ACKs commands but returns zeros until it is awake, + * and does not confirm a register selection sent before then. Retry + * the selection after a few ms instead of waiting the full awake + * selection timeout on every polled wake. + */ deadline = jiffies + msecs_to_jiffies(500); do { if (++tries % 20 == 0) { @@ -588,9 +610,10 @@ static int sn201202x_wake_poll(struct sn201202x *sn, bool poll) if (ret) return ret; } - ret = regmap_sn201202x_select_reg(sn->sdev, TPS_REG_MODE); + ret = sn201202x_select_reg(sn->sdev, TPS_REG_MODE, + SN201202X_WAKE_SELECT_TIMEOUT_US); if (ret == -ETIMEDOUT) { - budget_ms -= SN201202X_ATOMIC_SELECT_MS; + budget_ms -= SN201202X_WAKE_SELECT_TIMEOUT_US / 1000; continue; } if (ret) diff --git a/drivers/usb/typec/tipd/tps6598x.h b/drivers/usb/typec/tipd/tps6598x.h index 4924bf7195b5c3..eb77f76379ca40 100644 --- a/drivers/usb/typec/tipd/tps6598x.h +++ b/drivers/usb/typec/tipd/tps6598x.h @@ -619,7 +619,6 @@ void cd321x_stop_work(struct cd321x *cd321x); int cd321x_reboot_close(struct cd321x *cd321x); int cd321x_reboot_notify(struct notifier_block *nb, unsigned long action, void *data); -bool cd321x_tbt_switch_keep_waiting(struct device *dev); struct typec_thunderbolt_switch * cd321x_tbt_switch_get(struct device *dev, struct fwnode_handle *fwnode, bool *late); diff --git a/drivers/video/backlight/Kconfig b/drivers/video/backlight/Kconfig index dbf4ca23a9b6d8..1868c84cc56fb2 100644 --- a/drivers/video/backlight/Kconfig +++ b/drivers/video/backlight/Kconfig @@ -336,6 +336,16 @@ config BACKLIGHT_APPLE_DWI To compile this driver as a module, choose M here: the module will be called apple_dwi_bl. +config BACKLIGHT_APPLE_DWI_KUNIT_TEST + bool "KUnit tests for the Apple DWI backlight driver" if !KUNIT_ALL_TESTS + depends on BACKLIGHT_APPLE_DWI=y && KUNIT=y + default KUNIT_ALL_TESTS + help + Build tests for the Apple DWI backlight driver: the brightness + command word and send bits, reading the level back, the maximum, + and blanking through bl_power and suspend/resume. The registers + are kernel memory, so the tests need no Apple hardware. + config BACKLIGHT_QCOM_WLED tristate "Qualcomm PMIC WLED Driver" select REGMAP diff --git a/drivers/video/backlight/apple_dwi_bl-test.c b/drivers/video/backlight/apple_dwi_bl-test.c new file mode 100644 index 00000000000000..778a883f506b75 --- /dev/null +++ b/drivers/video/backlight/apple_dwi_bl-test.c @@ -0,0 +1,267 @@ +// SPDX-License-Identifier: GPL-2.0 OR MIT +/* + * KUnit tests for the Apple DWI backlight driver: the brightness command + * encoding, the send bits, reading the brightness back from the command + * register, and blanking through bl_power and the backlight core's + * suspend/resume. + * + * A real backlight device is registered on a KUnit device with the driver's + * ops; its register block is kernel memory, so the tests need no Apple + * hardware. + * + * Included by apple_dwi_bl.c. + */ + +#include +#include + +#define DWI_BL_TEST_REGS 0x10 +/* What every register holds before the operation under test. */ +#define DWI_BL_TEST_FILL 0xdeadbeef +/* SEND1 | SEND2 | SEND3 | LE_DATA | SEND4 */ +#define DWI_BL_TEST_CTL_SEND 0x1071 + +struct dwi_bl_test { + struct apple_dwi_bl dwi_bl; + struct backlight_device *bl; + void *regs; +}; + +static u32 dwi_bl_test_reg(struct dwi_bl_test *ctx, unsigned int reg) +{ + return readl(ctx->dwi_bl.base + reg); +} + +static int dwi_bl_test_init(struct kunit *test) +{ + struct backlight_properties props = { + /* as dwi_bl_probe() */ + .type = BACKLIGHT_PLATFORM, + .max_brightness = DWI_BL_MAX_BRIGHTNESS, + .scale = BACKLIGHT_SCALE_LINEAR, + }; + struct dwi_bl_test *ctx; + struct device *dev; + unsigned int reg; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->regs = kunit_kzalloc(test, DWI_BL_TEST_REGS, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->regs); + ctx->dwi_bl.base = (void __iomem __force *)ctx->regs; + for (reg = 0; reg < DWI_BL_TEST_REGS; reg += sizeof(u32)) + writel(DWI_BL_TEST_FILL, ctx->dwi_bl.base + reg); + + dev = kunit_device_register(test, "apple-dwi-bl-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + + ctx->bl = devm_backlight_device_register(dev, "apple-dwi-bl-test", dev, + &ctx->dwi_bl, &dwi_bl_ops, + &props); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->bl); + + return 0; +} + +static u32 dwi_bl_test_cmd(u32 brightness) +{ + return 0xa0000000 | brightness; +} + +/* The command word for a brightness: type 0xa in [31:28], level in [10:0]. */ +static void dwi_bl_test_encode(struct kunit *test) +{ + static const u32 levels[] = { 1, 2, 0x155, 0x2aa, 1023, 1024, 2046 }; + struct dwi_bl_test *ctx = test->priv; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(levels); i++) { + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, levels[i]), 0); + KUNIT_EXPECT_EQ_MSG(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), + dwi_bl_test_cmd(levels[i]), "level %u", levels[i]); + } +} + +/* Every update sets all five send bits, SEND4 (bit 12) included. */ +static void dwi_bl_test_send_bits(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 100), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CTL), DWI_BL_TEST_CTL_SEND); +} + +/* An update writes CTL and CMD and nothing beyond them. */ +static void dwi_bl_test_other_regs_untouched(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 7), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, 0x8), DWI_BL_TEST_FILL); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, 0xc), DWI_BL_TEST_FILL); +} + +/* The maximum is the full 11-bit level field. */ +static void dwi_bl_test_max(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_EXPECT_EQ(test, DWI_BL_MAX_BRIGHTNESS, (int)FIELD_MAX(DWI_BL_CMD_DATA)); + KUNIT_EXPECT_EQ(test, ctx->bl->props.max_brightness, 2047); + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 2047), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(2047)); + KUNIT_EXPECT_EQ(test, dwi_bl_get_brightness(ctx->bl), 2047); +} + +/* The core refuses a level above the maximum and the hardware keeps the last one. */ +static void dwi_bl_test_over_max(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 500), 0); + KUNIT_EXPECT_EQ(test, backlight_device_set_brightness(ctx->bl, 2048), -EINVAL); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(500)); + KUNIT_EXPECT_EQ(test, ctx->bl->props.brightness, 500); +} + +/* Brightness 0 is a real command, not a skipped write. */ +static void dwi_bl_test_zero(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 0), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(0)); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CTL), DWI_BL_TEST_CTL_SEND); +} + +/* Every level written by update_status reads back through get_brightness. */ +static void dwi_bl_test_round_trip(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + u32 level; + + for (level = 0; level <= DWI_BL_MAX_BRIGHTNESS; level++) { + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, level), 0); + KUNIT_ASSERT_EQ_MSG(test, ctx->bl->ops->get_brightness(ctx->bl), level, + "level %u", level); + } +} + +/* get_brightness takes only the level field of the command register. */ +static void dwi_bl_test_get_masks_type(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + /* What the bootloader left: another type and junk above the field. */ + writel(0x5ffff800 | 0x3c4, ctx->dwi_bl.base + DWI_BL_CMD); + KUNIT_EXPECT_EQ(test, dwi_bl_get_brightness(ctx->bl), 0x3c4); + + writel(0xfffff800, ctx->dwi_bl.base + DWI_BL_CMD); + KUNIT_EXPECT_EQ(test, dwi_bl_get_brightness(ctx->bl), 0); + + writel(dwi_bl_test_cmd(2047), ctx->dwi_bl.base + DWI_BL_CMD); + KUNIT_EXPECT_EQ(test, dwi_bl_get_brightness(ctx->bl), 2047); +} + +/* A level above the field is truncated to it, never into the type nibble. */ +static void dwi_bl_test_field_overflow(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + /* Bypass the core's max check, as a caller writing props directly does. */ + ctx->bl->props.brightness = 0x800 | 0x12; + KUNIT_ASSERT_EQ(test, backlight_update_status(ctx->bl), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD) & DWI_BL_CMD_TYPE, + 0xa0000000); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD) & ~DWI_BL_CMD_TYPE, + 0x12); +} + +/* bl_power off sends level 0 and keeps the set level; on sends it again. */ +static void dwi_bl_test_power_off_on(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 1200), 0); + + KUNIT_ASSERT_EQ(test, backlight_disable(ctx->bl), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(0)); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CTL), DWI_BL_TEST_CTL_SEND); + KUNIT_EXPECT_EQ(test, ctx->bl->props.brightness, 1200); + + writel(0, ctx->dwi_bl.base + DWI_BL_CTL); + KUNIT_ASSERT_EQ(test, backlight_enable(ctx->bl), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(1200)); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CTL), DWI_BL_TEST_CTL_SEND); +} + +/* bl_power off alone (no fb blank state) also blanks. */ +static void dwi_bl_test_power_only(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 300), 0); + + mutex_lock(&ctx->bl->update_lock); + ctx->bl->props.power = BACKLIGHT_POWER_OFF; + mutex_unlock(&ctx->bl->update_lock); + KUNIT_ASSERT_EQ(test, backlight_update_status(ctx->bl), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(0)); + + /* A level set while off is kept but not sent. */ + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 400), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(0)); + + mutex_lock(&ctx->bl->update_lock); + ctx->bl->props.power = BACKLIGHT_POWER_ON; + mutex_unlock(&ctx->bl->update_lock); + KUNIT_ASSERT_EQ(test, backlight_update_status(ctx->bl), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(400)); +} + +/* The driver asks the core to blank on suspend and restore on resume. */ +static void dwi_bl_test_suspend_resume(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + const struct dev_pm_ops *pm = ctx->bl->dev.class->pm; + + KUNIT_EXPECT_TRUE(test, dwi_bl_ops.options & BL_CORE_SUSPENDRESUME); + + if (!IS_ENABLED(CONFIG_PM_SLEEP) || !pm || !pm->suspend || !pm->resume) + kunit_skip(test, "backlight class has no sleep ops (CONFIG_PM_SLEEP=n)"); + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 900), 0); + + KUNIT_ASSERT_EQ(test, pm->suspend(&ctx->bl->dev), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(0)); + + KUNIT_ASSERT_EQ(test, pm->resume(&ctx->bl->dev), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(900)); +} + +static struct kunit_case dwi_bl_test_cases[] = { + KUNIT_CASE(dwi_bl_test_encode), + KUNIT_CASE(dwi_bl_test_send_bits), + KUNIT_CASE(dwi_bl_test_other_regs_untouched), + KUNIT_CASE(dwi_bl_test_max), + KUNIT_CASE(dwi_bl_test_over_max), + KUNIT_CASE(dwi_bl_test_zero), + KUNIT_CASE(dwi_bl_test_round_trip), + KUNIT_CASE(dwi_bl_test_get_masks_type), + KUNIT_CASE(dwi_bl_test_field_overflow), + KUNIT_CASE(dwi_bl_test_power_off_on), + KUNIT_CASE(dwi_bl_test_power_only), + KUNIT_CASE(dwi_bl_test_suspend_resume), + {} +}; + +static struct kunit_suite dwi_bl_test_suite = { + .name = "apple-dwi-bl", + .init = dwi_bl_test_init, + .test_cases = dwi_bl_test_cases, +}; + +kunit_test_suite(dwi_bl_test_suite); diff --git a/drivers/video/backlight/apple_dwi_bl.c b/drivers/video/backlight/apple_dwi_bl.c index 93bd744972d60a..8a280ab3a70fbe 100644 --- a/drivers/video/backlight/apple_dwi_bl.c +++ b/drivers/video/backlight/apple_dwi_bl.c @@ -121,3 +121,7 @@ module_platform_driver(dwi_bl_driver); MODULE_DESCRIPTION("Apple DWI Backlight Driver"); MODULE_AUTHOR("Nick Chan "); MODULE_LICENSE("Dual MIT/GPL"); + +#if IS_ENABLED(CONFIG_BACKLIGHT_APPLE_DWI_KUNIT_TEST) +#include "apple_dwi_bl-test.c" +#endif diff --git a/drivers/video/backlight/apple_dwi_bl.kunitconfig b/drivers/video/backlight/apple_dwi_bl.kunitconfig new file mode 100644 index 00000000000000..06e86f8a5d051c --- /dev/null +++ b/drivers/video/backlight/apple_dwi_bl.kunitconfig @@ -0,0 +1,8 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/video/backlight/apple_dwi_bl.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_PM=y +CONFIG_SUSPEND=y +CONFIG_BACKLIGHT_CLASS_DEVICE=y +CONFIG_BACKLIGHT_APPLE_DWI=y +CONFIG_BACKLIGHT_APPLE_DWI_KUNIT_TEST=y diff --git a/drivers/watchdog/apple_wdt.c b/drivers/watchdog/apple_wdt.c index 3c867a3ce636e5..1300a00d5cd654 100644 --- a/drivers/watchdog/apple_wdt.c +++ b/drivers/watchdog/apple_wdt.c @@ -12,28 +12,32 @@ #include #include #include +#include #include #include #include +#include #include /* * Apple Watchdog MMIO registers * - * This HW block has three separate watchdogs. WD0 resets the machine - * to recovery mode and is not very useful for us. WD1 and WD2 trigger a normal - * machine reset. WD0 additionally supports a configurable interrupt. - * This information can be used to implement pretimeout support at a later time. + * This HW block has three separate watchdogs. WD0 resets the machine to + * recovery mode and is not used by Linux. On legacy wdt-version 2 platforms + * WD1 triggers a normal machine reset via APPLE_WDT_CTRL_RESET_EN when + * CUR_TIME >= BITE_TIME. + * + * On platforms that provide the optional "reconfig" routing register + * (simple-reconfig-wdog-support), WD1/WD2 hardware RESET_EN does not reset + * reliably; instead, setting bits 5:4 = 01 in the reconfig register routes + * WD2's bark interrupt (CUR_TIME >= BARK_TIME with APPLE_WDT_CTRL_IRQ_EN + * set and BITE_TIME = U32_MAX) to a clean cold reset. * * APPLE_WDT_WDx_CUR_TIME is a simple counter incremented for each tick of the * reference clock. It can also be overwritten to any value. - * Whenever APPLE_WDT_CTRL_RESET_EN is set in APPLE_WDT_WDx_CTRL and - * APPLE_WDT_WDx_CUR_TIME >= APPLE_WDT_WDx_BITE_TIME the entire machine is - * reset. - * Whenever APPLE_WDT_CTRL_IRQ_EN is set and APPLE_WDTx_WD1_CUR_TIME >= - * APPLE_WDTx_WD1_BARK_TIME an interrupt is triggered and - * APPLE_WDT_CTRL_IRQ_STATUS is set. The interrupt can be cleared by writing - * 1 to APPLE_WDT_CTRL_IRQ_STATUS. + * Whenever APPLE_WDT_CTRL_IRQ_EN is set and CUR_TIME >= BARK_TIME an interrupt + * is triggered and APPLE_WDT_CTRL_IRQ_STATUS is set. The interrupt can be + * cleared by writing 1 to APPLE_WDT_CTRL_IRQ_STATUS. */ #define APPLE_WDT_WD0_CUR_TIME 0x00 #define APPLE_WDT_WD0_BITE_TIME 0x04 @@ -46,17 +50,26 @@ #define APPLE_WDT_WD2_CUR_TIME 0x20 #define APPLE_WDT_WD2_BITE_TIME 0x24 +#define APPLE_WDT_WD2_BARK_TIME 0x28 #define APPLE_WDT_WD2_CTRL 0x2c #define APPLE_WDT_CTRL_IRQ_EN BIT(0) #define APPLE_WDT_CTRL_IRQ_STATUS BIT(1) #define APPLE_WDT_CTRL_RESET_EN BIT(2) +/* Optional "reconfig" register: bits 5:4 = 01 routes WD2 bark to cold reset */ +#define APPLE_WDT_RECONFIG_MASK GENMASK(5, 4) +#define APPLE_WDT_RECONFIG_WD2 BIT(4) + +/* ~40 ms bark delay before simple-reconfig cold reset */ +#define APPLE_WDT_REBOOT_DELAY_MS 40 + #define APPLE_WDT_TIMEOUT_DEFAULT 30 struct apple_wdt { struct watchdog_device wdd; void __iomem *regs; + void __iomem *reconfig; unsigned long clk_rate; }; @@ -65,10 +78,52 @@ static struct apple_wdt *to_apple_wdt(struct watchdog_device *wdd) return container_of(wdd, struct apple_wdt, wdd); } +static u32 apple_wdt_timeout_ticks(struct apple_wdt *wdt, unsigned int s) +{ + u32 actual = min(s, wdt->wdd.max_hw_heartbeat_ms / 1000); + + return wdt->clk_rate * actual; +} + +static void apple_wdt_enable_reconfig(struct apple_wdt *wdt) +{ + u32 val = readl_relaxed(wdt->reconfig); + + writel_relaxed((val & ~APPLE_WDT_RECONFIG_MASK) | APPLE_WDT_RECONFIG_WD2, + wdt->reconfig); + (void)readl(wdt->reconfig); +} + +static void apple_wdt_wd2_arm(struct apple_wdt *wdt, u32 bark_ticks) +{ + /* + * Disarm WD2, program safe BITE/CUR/BARK, and clear any latched + * IRQ_STATUS before routing WD2 bark to cold reset and enabling IRQ_EN. + * Read back WD2_CTRL to order the watchdog-block writes before touching + * the separate AON reconfig mapping; apple_wdt_enable_reconfig() reads + * back reconfig before the final IRQ_EN write. + */ + writel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CTRL); + writel_relaxed(U32_MAX, wdt->regs + APPLE_WDT_WD2_BITE_TIME); + writel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CUR_TIME); + writel_relaxed(bark_ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME); + writel_relaxed(APPLE_WDT_CTRL_IRQ_STATUS, + wdt->regs + APPLE_WDT_WD2_CTRL); + (void)readl(wdt->regs + APPLE_WDT_WD2_CTRL); + apple_wdt_enable_reconfig(wdt); + writel_relaxed(APPLE_WDT_CTRL_IRQ_EN, wdt->regs + APPLE_WDT_WD2_CTRL); +} + static int apple_wdt_start(struct watchdog_device *wdd) { struct apple_wdt *wdt = to_apple_wdt(wdd); + if (wdt->reconfig) { + apple_wdt_wd2_arm(wdt, + apple_wdt_timeout_ticks(wdt, wdd->timeout)); + return 0; + } + writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CUR_TIME); writel_relaxed(APPLE_WDT_CTRL_RESET_EN, wdt->regs + APPLE_WDT_WD1_CTRL); @@ -78,8 +133,9 @@ static int apple_wdt_start(struct watchdog_device *wdd) static int apple_wdt_stop(struct watchdog_device *wdd) { struct apple_wdt *wdt = to_apple_wdt(wdd); + u32 ctrl_off = wdt->reconfig ? APPLE_WDT_WD2_CTRL : APPLE_WDT_WD1_CTRL; - writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CTRL); + writel_relaxed(0, wdt->regs + ctrl_off); return 0; } @@ -87,8 +143,13 @@ static int apple_wdt_stop(struct watchdog_device *wdd) static int apple_wdt_ping(struct watchdog_device *wdd) { struct apple_wdt *wdt = to_apple_wdt(wdd); + u32 cur_off; - writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CUR_TIME); + if (wdt->reconfig && apple_sleep_wdt_active(wdd->parent)) + return 0; + + cur_off = wdt->reconfig ? APPLE_WDT_WD2_CUR_TIME : APPLE_WDT_WD1_CUR_TIME; + writel_relaxed(0, wdt->regs + cur_off); return 0; } @@ -96,12 +157,15 @@ static int apple_wdt_ping(struct watchdog_device *wdd) static int apple_wdt_set_timeout(struct watchdog_device *wdd, unsigned int s) { struct apple_wdt *wdt = to_apple_wdt(wdd); - u32 actual; - - writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CUR_TIME); - - actual = min(s, wdd->max_hw_heartbeat_ms / 1000); - writel_relaxed(wdt->clk_rate * actual, wdt->regs + APPLE_WDT_WD1_BITE_TIME); + u32 ticks = apple_wdt_timeout_ticks(wdt, s); + + if (wdt->reconfig) { + writel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CUR_TIME); + writel_relaxed(ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME); + } else { + writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CUR_TIME); + writel_relaxed(ticks, wdt->regs + APPLE_WDT_WD1_BITE_TIME); + } wdd->timeout = s; @@ -113,8 +177,16 @@ static unsigned int apple_wdt_get_timeleft(struct watchdog_device *wdd) struct apple_wdt *wdt = to_apple_wdt(wdd); u32 cur_time, reset_time; - cur_time = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CUR_TIME); - reset_time = readl_relaxed(wdt->regs + APPLE_WDT_WD1_BITE_TIME); + if (wdt->reconfig) { + cur_time = readl_relaxed(wdt->regs + APPLE_WDT_WD2_CUR_TIME); + reset_time = readl_relaxed(wdt->regs + APPLE_WDT_WD2_BARK_TIME); + } else { + cur_time = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CUR_TIME); + reset_time = readl_relaxed(wdt->regs + APPLE_WDT_WD1_BITE_TIME); + } + + if (cur_time >= reset_time) + return 0; return (reset_time - cur_time) / wdt->clk_rate; } @@ -124,6 +196,22 @@ static int apple_wdt_restart(struct watchdog_device *wdd, unsigned long mode, { struct apple_wdt *wdt = to_apple_wdt(wdd); + if (wdt->reconfig) { + u32 ticks = max_t(u32, 1, + div_u64((u64)wdt->clk_rate * APPLE_WDT_REBOOT_DELAY_MS, + MSEC_PER_SEC)); + + apple_wdt_wd2_arm(wdt, ticks); + + /* + * Flush writes and wait for the bark delay (~40 ms) plus SoC + * reset latency (~125 ms) before returning from restart. + */ + (void)readl(wdt->regs + APPLE_WDT_WD2_CUR_TIME); + mdelay(200); + return 0; + } + writel_relaxed(APPLE_WDT_CTRL_RESET_EN, wdt->regs + APPLE_WDT_WD1_CTRL); writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_BITE_TIME); writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CUR_TIME); @@ -155,21 +243,46 @@ static const struct watchdog_info apple_wdt_info = { .options = WDIOF_MAGICCLOSE | WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT, }; +static void apple_wdt_sleep_restore(void *data) +{ + struct apple_wdt *wdt = data; + + if (watchdog_active(&wdt->wdd) || watchdog_hw_running(&wdt->wdd)) + apple_wdt_start(&wdt->wdd); +} + +static void apple_wdt_sleep_unregister(void *data) +{ + apple_sleep_wdt_unregister(data); +} + static int apple_wdt_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; + struct resource *wdt_res, *reconfig_res; struct apple_wdt *wdt; struct clk *clk; u32 wdt_ctrl; + int ret; wdt = devm_kzalloc(dev, sizeof(*wdt), GFP_KERNEL); if (!wdt) return -ENOMEM; - wdt->regs = devm_platform_ioremap_resource(pdev, 0); + wdt->regs = devm_platform_get_and_ioremap_resource(pdev, 0, &wdt_res); if (IS_ERR(wdt->regs)) return PTR_ERR(wdt->regs); + reconfig_res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "reconfig"); + if (reconfig_res) { + if (resource_size(reconfig_res) < sizeof(u32)) + return -EINVAL; + wdt->reconfig = devm_ioremap(dev, reconfig_res->start, + resource_size(reconfig_res)); + if (!wdt->reconfig) + return -ENOMEM; + } + clk = devm_clk_get_enabled(dev, NULL); if (IS_ERR(clk)) return PTR_ERR(clk); @@ -185,13 +298,54 @@ static int apple_wdt_probe(struct platform_device *pdev) wdt->wdd.max_hw_heartbeat_ms = U32_MAX / wdt->clk_rate * 1000; wdt->wdd.timeout = APPLE_WDT_TIMEOUT_DEFAULT; - wdt_ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CTRL); - if ((wdt_ctrl & APPLE_WDT_CTRL_RESET_EN) && !is_kdump_kernel()) - set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); - watchdog_set_nowayout(&wdt->wdd, WATCHDOG_NOWAYOUT); watchdog_init_timeout(&wdt->wdd, 0, dev); - apple_wdt_set_timeout(&wdt->wdd, wdt->wdd.timeout); + + if (wdt->reconfig) { + u32 wd1_ctrl, wd2_ctrl; + bool armed; + + /* + * Register the sleep handoff before touching watchdog registers + * so a registration failure cannot leave WD2 armed, and so devm + * unwinds watchdog_unregister_device() before unregistering here. + */ + ret = apple_sleep_wdt_register(dev, wdt_res, + apple_wdt_sleep_restore, wdt); + if (ret) + return ret; + ret = devm_add_action_or_reset(dev, apple_wdt_sleep_unregister, dev); + if (ret) + return ret; + + wd1_ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CTRL); + wd2_ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD2_CTRL); + armed = (wd1_ctrl & APPLE_WDT_CTRL_RESET_EN) || + (wd2_ctrl & (APPLE_WDT_CTRL_IRQ_EN | APPLE_WDT_CTRL_RESET_EN)); + + if (wd1_ctrl) + writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CTRL); + + if (armed && !is_kdump_kernel()) { + if (wd1_ctrl & APPLE_WDT_CTRL_RESET_EN) + dev_info(dev, "taking over legacy WD1 watchdog as WD2 simple-reconfig\n"); + if (wd2_ctrl & APPLE_WDT_CTRL_RESET_EN) + dev_info(dev, "taking over WD2 RESET_EN watchdog as WD2 simple-reconfig\n"); + set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + apple_wdt_wd2_arm(wdt, + apple_wdt_timeout_ticks(wdt, wdt->wdd.timeout)); + } else { + if (wd2_ctrl) + writel_relaxed(APPLE_WDT_CTRL_IRQ_STATUS, + wdt->regs + APPLE_WDT_WD2_CTRL); + apple_wdt_set_timeout(&wdt->wdd, wdt->wdd.timeout); + } + } else { + wdt_ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CTRL); + if ((wdt_ctrl & APPLE_WDT_CTRL_RESET_EN) && !is_kdump_kernel()) + set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + apple_wdt_set_timeout(&wdt->wdd, wdt->wdd.timeout); + } /* * A crash kernel only saves the dump and restarts. If it stalls, the @@ -215,6 +369,9 @@ static int apple_wdt_resume(struct device *dev) { struct apple_wdt *wdt = dev_get_drvdata(dev); + if (wdt->reconfig && apple_sleep_wdt_active(dev)) + return 0; + if (watchdog_active(&wdt->wdd) || watchdog_hw_running(&wdt->wdd)) apple_wdt_start(&wdt->wdd); @@ -225,6 +382,9 @@ static int apple_wdt_suspend(struct device *dev) { struct apple_wdt *wdt = dev_get_drvdata(dev); + if (wdt->reconfig && apple_sleep_wdt_active(dev)) + return 0; + if (watchdog_active(&wdt->wdd) || watchdog_hw_running(&wdt->wdd)) apple_wdt_stop(&wdt->wdd); diff --git a/fs/aio.c b/fs/aio.c index d78acc69f48701..77bc01fd013353 100644 --- a/fs/aio.c +++ b/fs/aio.c @@ -142,6 +142,9 @@ struct kioctx { * We batch accesses to it with a percpu version. */ atomic_t reqs_available; + + /* Requests whose completion has yet to be posted. */ + atomic_t reqs_in_flight; } ____cacheline_aligned_in_smp; struct { @@ -847,6 +850,7 @@ static struct kioctx *ioctx_alloc(unsigned nr_events) goto err; atomic_set(&ctx->reqs_available, ctx->nr_events - 1); + atomic_set(&ctx->reqs_in_flight, 0); ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4); if (ctx->req_batch < 1) ctx->req_batch = 1; @@ -1118,6 +1122,7 @@ static inline struct aio_kiocb *aio_get_req(struct kioctx *ctx) } percpu_ref_get(&ctx->reqs); + atomic_inc(&ctx->reqs_in_flight); req->ki_ctx = ctx; INIT_LIST_HEAD(&req->ki_list); refcount_set(&req->ki_refcnt, 2); @@ -1206,6 +1211,7 @@ static void aio_complete(struct aio_kiocb *iocb) /* after flagging the request as done, we * must never even look at it again */ + atomic_dec(&ctx->reqs_in_flight); smp_wmb(); /* make event visible before updating tail */ ctx->tail = tail; @@ -1408,8 +1414,17 @@ static long read_events(struct kioctx *ctx, long min_nr, long nr, if (aio_read_events(ctx, min_nr, nr, event, &ret) || ret2) break; - if (nr_got == ret) - schedule(); + if (nr_got == ret) { + /* + * Mark the wait as iowait when this context has a + * request in flight, even if another thread submitted + * it. An idle event loop sleeps normally. + */ + if (atomic_read(&ctx->reqs_in_flight)) + io_schedule(); + else + schedule(); + } } finish_wait(&ctx->wait, &w.w); @@ -2114,6 +2129,7 @@ static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb, * means that we need to destroy req ourselves. */ if (unlikely(err)) { + atomic_dec(&ctx->reqs_in_flight); iocb_destroy(req); put_reqs_available(ctx, 1); } diff --git a/fs/btrfs/bio.c b/fs/btrfs/bio.c index 67856f90f8b988..00efb318aff8c7 100644 --- a/fs/btrfs/bio.c +++ b/fs/btrfs/bio.c @@ -133,9 +133,14 @@ void btrfs_bio_end_io(struct btrfs_bio *bbio, blk_status_t status) cmpxchg(&bbio->status, BLK_STS_OK, status); if (atomic_dec_and_test(&bbio->pending_ios)) { - /* Load split bio's error which might be set above. */ - if (status == BLK_STS_OK) - bbio->bio.bi_status = READ_ONCE(bbio->status); + /* + * Load the first error of all split bios. This must be done + * unconditionally: if the last completion is a split bio, the + * error passed in was only stored in the split bio, while the + * original bio's bi_status still holds the status of its own + * earlier (possibly successful) completion. + */ + bbio->bio.bi_status = READ_ONCE(bbio->status); if (bbio_has_ordered_extent(bbio)) { struct btrfs_ordered_extent *ordered = bbio->ordered; diff --git a/fs/btrfs/direct-io.c b/fs/btrfs/direct-io.c index c6c940eebfeb2c..1184da49acfd34 100644 --- a/fs/btrfs/direct-io.c +++ b/fs/btrfs/direct-io.c @@ -366,6 +366,59 @@ static int btrfs_get_blocks_direct_write(struct extent_map **map, return ret; } +/* + * Return true if a direct write to the range of @em allocates a new extent + * (COW): it is not a NOCOW write into an existing or preallocated extent and it + * does not fall back to buffered IO. + */ +static bool btrfs_dio_write_is_cow(const struct btrfs_inode *inode, + const struct extent_map *em) +{ + if (inode->flags & BTRFS_INODE_NODATACOW) + return false; + if (em->flags & EXTENT_FLAG_PREALLOC) + return false; + if (btrfs_extent_map_is_compressed(em) || + em->disk_bytenr == EXTENT_MAP_INLINE) + return false; + return true; +} + +/* + * A COW write replaces everything mapped in its range with one newly allocated + * extent, so the boundaries of the extents it overwrites do not matter. Extend + * the mapping [@start, @start + @len) over the following extent maps that a + * direct write would COW as well, within @length and the maximum extent size. + * Without this, a sequential rewrite of a fragmented range allocates one new + * extent (and ordered extent, file extent item and bio) per old extent. The + * file stays fragmented and the rewrite runs at small-write speed. + */ +static u64 btrfs_dio_cow_write_len(struct btrfs_inode *inode, u64 start, + u64 len, u64 length) +{ + const u64 limit = start + min(length, inode->root->fs_info->max_extent_size); + u64 end = start + len; + + while (end < limit) { + struct extent_map *em; + u64 em_end; + bool cow; + + em = btrfs_get_extent(inode, NULL, end, limit - end); + if (IS_ERR(em)) + break; + cow = btrfs_dio_write_is_cow(inode, em); + em_end = btrfs_extent_map_end(em); + btrfs_free_extent_map(em); + if (!cow) + break; + end = min(em_end, limit); + cond_resched(); + } + + return end - start; +} + static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start, loff_t length, unsigned int flags, struct iomap *iomap, struct iomap *srcmap) @@ -508,6 +561,9 @@ static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start, } len = min(len, em->len - (start - em->start)); + if (write && !(flags & IOMAP_NOWAIT) && + btrfs_dio_write_is_cow(BTRFS_I(inode), em)) + len = btrfs_dio_cow_write_len(BTRFS_I(inode), start, len, length); /* * If we have a NOWAIT request and the range contains multiple extents diff --git a/include/linux/apple-sep-hdcp.h b/include/linux/apple-sep-hdcp.h new file mode 100644 index 00000000000000..e01766d858ffb1 --- /dev/null +++ b/include/linux/apple-sep-hdcp.h @@ -0,0 +1,221 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * Apple SEP HDCP 2.2 transmitter service, for the display driver. + * + * The SEP holds the transmitter's device keys and does every HDCP 2.2 + * cryptographic step itself. The display driver builds the protocol + * messages from the fields below and relays them to the receiver through + * DCP. Only fields that the HDCP 2.2 protocol sends in the clear cross this + * interface. No call returns or takes km, ks, kd or a device key. + * + * Every call runs on one HDCP interface channel of the SEP (the display + * node's "apple,hdcp-channels" value). A session is opened with + * apple_sep_hdcp_open() and ends with apple_sep_hdcp_close(). The SEP + * driver enforces the protocol order per channel, so a call out of order + * fails with -EPROTO before the SEP sees it. Bounded verification retries + * permitted by HDCP 2.2 (locality check L' and repeater stream M') leave + * the session open for retry while attempts remain; any other SEP error + * leaves the session failed until it is closed. If the SEP does not answer, + * every channel fails with -EIO until the SEP is reset. + * + * All calls may sleep. They return 0 or a negative errno: -ENODEV when no + * SEP driver is bound or the endpoint is absent, -EAGAIN when the SEP is + * still finishing bring-up or transiently gated for system sleep, -EINVAL + * for a bad argument, -EPROTO for a call out of order, -EACCES when the + * SEP rejects a verification (certificate, H', L', ReceiverID list, V', M'), + * -EIO when the SEP fails or does not answer. + */ +#ifndef _LINUX_APPLE_SEP_HDCP_H +#define _LINUX_APPLE_SEP_HDCP_H + +#include +#include +#include + +#define APPLE_SEP_HDCP_RTX_LEN 8 +#define APPLE_SEP_HDCP_RRX_LEN 8 +#define APPLE_SEP_HDCP_CAPS_LEN 3 +#define APPLE_SEP_HDCP_CERT_LEN 522 +#define APPLE_SEP_HDCP_EKPUB_KM_LEN 128 +#define APPLE_SEP_HDCP_EKH_KM_LEN 16 +#define APPLE_SEP_HDCP_M_LEN 16 +#define APPLE_SEP_HDCP_H_PRIME_LEN 32 +#define APPLE_SEP_HDCP_RN_LEN 8 +#define APPLE_SEP_HDCP_L_PRIME_LEN 32 +#define APPLE_SEP_HDCP_EDKEY_KS_LEN 16 +#define APPLE_SEP_HDCP_RIV_LEN 8 +#define APPLE_SEP_HDCP_RXINFO_LEN 2 +#define APPLE_SEP_HDCP_SEQ_NUM_LEN 3 +#define APPLE_SEP_HDCP_RECEIVER_ID_LEN 5 +#define APPLE_SEP_HDCP_MAX_DEVICES 31 +#define APPLE_SEP_HDCP_V_PRIME_LEN 16 +#define APPLE_SEP_HDCP_V_LEN 32 +#define APPLE_SEP_HDCP_M_PRIME_LEN 32 + +/* The km the SEP has stored for this receiver, as AKE_Stored_km carries it. */ +struct apple_sep_hdcp_stored_km { + u8 ekh_km[APPLE_SEP_HDCP_EKH_KM_LEN]; + u8 m[APPLE_SEP_HDCP_M_LEN]; +}; + +#if IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE) + +/* Session start: the SEP draws r_tx for AKE_Init. */ +int apple_sep_hdcp_open(u32 channel, u8 rtx[APPLE_SEP_HDCP_RTX_LEN]); + +/* + * AKE_Send_Cert and r_rx. The SEP checks the certificate signature. + * On return *stored is true and @km holds AKE_Stored_km's body when the SEP + * has paired with this receiver before; otherwise @ekpub_km holds + * AKE_No_Stored_km's body. + */ +int apple_sep_hdcp_ake_cert(u32 channel, + const u8 cert[APPLE_SEP_HDCP_CERT_LEN], + const u8 rrx[APPLE_SEP_HDCP_RRX_LEN], + bool *stored, struct apple_sep_hdcp_stored_km *km, + u8 ekpub_km[APPLE_SEP_HDCP_EKPUB_KM_LEN]); + +/* AKE_Send_H_prime: the SEP checks H' over r_tx, RxCaps and TxCaps. */ +int apple_sep_hdcp_ake_h_prime(u32 channel, + const u8 rxcaps[APPLE_SEP_HDCP_CAPS_LEN], + const u8 txcaps[APPLE_SEP_HDCP_CAPS_LEN], + const u8 h_prime[APPLE_SEP_HDCP_H_PRIME_LEN]); + +/* AKE_Send_Pairing_Info (first pairing only): the SEP stores km. */ +int apple_sep_hdcp_ake_pairing(u32 channel, + const u8 ekh_km[APPLE_SEP_HDCP_EKH_KM_LEN]); + +/* LC_Init: r_n from the SEP. */ +int apple_sep_hdcp_lc_init(u32 channel, u8 rn[APPLE_SEP_HDCP_RN_LEN]); + +/* LC_Send_L_prime: the SEP checks L'. */ +int apple_sep_hdcp_lc_l_prime(u32 channel, + const u8 l_prime[APPLE_SEP_HDCP_L_PRIME_LEN]); + +/* SKE_Send_Eks: the SEP returns Edkey(ks) and r_iv for the receiver. */ +int apple_sep_hdcp_ske(u32 channel, + u8 edkey_ks[APPLE_SEP_HDCP_EDKEY_KS_LEN], + u8 riv[APPLE_SEP_HDCP_RIV_LEN]); + +/* + * RepeaterAuth_Send_ReceiverID_List: @ids holds @count Receiver IDs. The SEP + * checks V' and returns V; the transmitter sends its least significant + * 128 bits in RepeaterAuth_Send_Ack. + */ +int apple_sep_hdcp_repeater_list(u32 channel, const u8 *ids, unsigned int count, + const u8 rxinfo[APPLE_SEP_HDCP_RXINFO_LEN], + const u8 seq_num_v[APPLE_SEP_HDCP_SEQ_NUM_LEN], + const u8 v_prime[APPLE_SEP_HDCP_V_PRIME_LEN], + u8 v[APPLE_SEP_HDCP_V_LEN]); + +/* + * RepeaterAuth_Stream_Manage / Stream_Ready for one stream: the SEP checks + * M' over StreamID_Type and seq_num_M. @type is 0 or 1. + */ +int apple_sep_hdcp_repeater_stream(u32 channel, u8 stream_id, u8 type, + const u8 seq_num_m[APPLE_SEP_HDCP_SEQ_NUM_LEN], + const u8 m_prime[APPLE_SEP_HDCP_M_PRIME_LEN]); + +/* Authentication complete. The caller waits 200 ms before encryption. */ +int apple_sep_hdcp_finish(u32 channel); + +/* Link encryption on or off for this channel. */ +int apple_sep_hdcp_set_encryption(u32 channel, bool on); + +/* Ends the session from any state; safe to call when none is open. */ +void apple_sep_hdcp_close(u32 channel); + +/* True when a SEP driver with the HDCP service is bound and ready. */ +bool apple_sep_hdcp_available(void); + +#else /* !IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE) */ + +static inline int apple_sep_hdcp_open(u32 channel, + u8 rtx[APPLE_SEP_HDCP_RTX_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_ake_cert(u32 channel, + const u8 cert[APPLE_SEP_HDCP_CERT_LEN], + const u8 rrx[APPLE_SEP_HDCP_RRX_LEN], + bool *stored, + struct apple_sep_hdcp_stored_km *km, + u8 ekpub_km[APPLE_SEP_HDCP_EKPUB_KM_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_ake_h_prime(u32 channel, + const u8 rxcaps[APPLE_SEP_HDCP_CAPS_LEN], + const u8 txcaps[APPLE_SEP_HDCP_CAPS_LEN], + const u8 h_prime[APPLE_SEP_HDCP_H_PRIME_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_ake_pairing(u32 channel, + const u8 ekh_km[APPLE_SEP_HDCP_EKH_KM_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_lc_init(u32 channel, + u8 rn[APPLE_SEP_HDCP_RN_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_lc_l_prime(u32 channel, + const u8 l_prime[APPLE_SEP_HDCP_L_PRIME_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_ske(u32 channel, + u8 edkey_ks[APPLE_SEP_HDCP_EDKEY_KS_LEN], + u8 riv[APPLE_SEP_HDCP_RIV_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_repeater_list(u32 channel, const u8 *ids, + unsigned int count, + const u8 rxinfo[APPLE_SEP_HDCP_RXINFO_LEN], + const u8 seq_num_v[APPLE_SEP_HDCP_SEQ_NUM_LEN], + const u8 v_prime[APPLE_SEP_HDCP_V_PRIME_LEN], + u8 v[APPLE_SEP_HDCP_V_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_repeater_stream(u32 channel, u8 stream_id, + u8 type, + const u8 seq_num_m[APPLE_SEP_HDCP_SEQ_NUM_LEN], + const u8 m_prime[APPLE_SEP_HDCP_M_PRIME_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_finish(u32 channel) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_set_encryption(u32 channel, bool on) +{ + return -ENODEV; +} + +static inline void apple_sep_hdcp_close(u32 channel) +{ +} + +static inline bool apple_sep_hdcp_available(void) +{ + return false; +} + +#endif /* IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE) */ + +#endif /* _LINUX_APPLE_SEP_HDCP_H */ diff --git a/include/linux/mfd/macsmc.h b/include/linux/mfd/macsmc.h index 0bfd2079d0b969..47d4bc7c9b35df 100644 --- a/include/linux/mfd/macsmc.h +++ b/include/linux/mfd/macsmc.h @@ -123,6 +123,8 @@ struct apple_smc { const struct apple_sleep_smc_policy *sleep_policy; u64 sleep_warn_ack; bool sleep_pmvc_info; + /* WKTP (1-byte writable) supported: notify SMC on full wake. */ + bool has_wktp; /* The saved scope's pmVC after ANS, and when it was answered. */ bool saved_pmvc_sent; u64 saved_pmvc_at; @@ -131,6 +133,7 @@ struct apple_smc { * resolve only the matching pending ID; timeout never cancels SRAM use. */ bool saved_enabled, saved_blocked, saved_scope, saved_committed; + bool port_dark_wake; bool saved_pending, saved_recovery, saved_wake; int saved_fault, saved_notice_error, saved_restore_error; /* @@ -144,6 +147,13 @@ struct apple_smc { u8 wake_lid; int wake_lid_ret; u64 saved_unexpected; + /* WKTP left at its sleep value: written back once a wake is a full one. */ + bool wake_silent; + /* apple,sleep-wake-type: WKTP written at the sleep commit. */ + bool sleep_wake_type; + /* apple,sleep-pmvc: when set, the pmVC value written at the sleep commit. */ + bool sleep_pmvc_set; + u32 sleep_pmvc; /* To be told at the noirq suspend, after the debug link's cut. */ bool sleep_warn_late; /* In a noirq phase: replies are polled for. */ @@ -213,6 +223,55 @@ int apple_smc_write(struct apple_smc *smc, smc_key key, const void *buf, size_t */ int apple_smc_write_noirq(struct apple_smc *smc, smc_key key, const void *buf, size_t size); +struct device_node; +struct platform_device; + +#define APPLE_SMC_WARM_RESET_WRITES 4 + +/** + * struct apple_smc_warm_reset - a PCIe endpoint's reset through an SMC key + * @smc: the SMC's device (a reference, dropped by apple_smc_warm_reset_put()) + * @key: the key to write + * @count: how many writes + * @writes: per write, the key's value (its bytes from the cell's most significant down) + * and the wait after it in microseconds + * + * Read from a PCIe root port's "apple,function-warm-reset" and "apple,warm-reset-writes" + * (bindings/pci/apple,pcie.yaml). + */ +struct apple_smc_warm_reset { + struct platform_device *smc; + smc_key key; + unsigned int count; + u32 writes[2 * APPLE_SMC_WARM_RESET_WRITES]; +}; + +/** + * apple_smc_warm_reset_parse - read a root port's warm reset + * @np: the root port's node + * @wr: filled in on success + * + * Return: Zero on success, -ENODEV when the port describes none or its SMC has no device, + * -EINVAL when the writes are malformed. + */ +int apple_smc_warm_reset_parse(struct device_node *np, struct apple_smc_warm_reset *wr); + +/** + * apple_smc_warm_reset_put - drop the reference apple_smc_warm_reset_parse() took + * @wr: the parsed reset; cleared + */ +void apple_smc_warm_reset_put(struct apple_smc_warm_reset *wr); + +/** + * apple_smc_warm_reset - give a parsed warm reset + * @wr: the parsed reset + * @noirq: from another device's noirq callbacks: the replies are polled for and the waits + * busy-wait, as for apple_smc_write_noirq() + * + * Return: Zero on success, -ENODEV when the SMC isn't bound, or the first write's error. + */ +int apple_smc_warm_reset(const struct apple_smc_warm_reset *wr, bool noirq); + /** * apple_smc_enter_atomic - Enter atomic mode to be able to use apple_smc_write_atomic * @smc: Pointer to apple_smc struct @@ -330,6 +389,17 @@ APPLE_SMC_TYPE_OPS(s8) struct device; +/* + * Hotspot fan-assistance thresholds read from the machine's SMC hwmon device + * tree node (macsmc_soc_die active trip temperature, hysteresis-derived + * release temperature, and minimum hold time). + */ +struct macsmc_hwmon_fan_assist { + int trigger_mc; + int release_mc; + unsigned int hold_ms; +}; + /* * The SMC hwmon cell's fan control for a kernel thermal policy (a GPU * governor): see drivers/hwmon/macsmc-hwmon.c. @@ -337,12 +407,31 @@ struct device; #if IS_REACHABLE(CONFIG_SENSORS_MACSMC_HWMON) int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, unsigned int min_step_rpm); +int macsmc_hwmon_fans_request_manual(struct device *dev, unsigned int permille, + unsigned int min_step_rpm); +bool macsmc_hwmon_hotspot_assist_available(void); +int macsmc_hwmon_hotspot_assist_policy(struct device *dev, + struct macsmc_hwmon_fan_assist *policy); #else static inline int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, unsigned int min_step_rpm) { return -ENODEV; } +static inline int macsmc_hwmon_fans_request_manual(struct device *dev, unsigned int permille, + unsigned int min_step_rpm) +{ + return -ENODEV; +} +static inline bool macsmc_hwmon_hotspot_assist_available(void) +{ + return false; +} +static inline int macsmc_hwmon_hotspot_assist_policy(struct device *dev, + struct macsmc_hwmon_fan_assist *policy) +{ + return -ENODEV; +} #endif static inline int apple_smc_read_flag(struct apple_smc *smc, smc_key key, bool *flag) diff --git a/include/linux/nvmem-provider.h b/include/linux/nvmem-provider.h index 6063fe5b7784ac..c74e0fbb9d73ca 100644 --- a/include/linux/nvmem-provider.h +++ b/include/linux/nvmem-provider.h @@ -91,6 +91,9 @@ struct nvmem_cell_info { * @type: Type of the nvmem storage * @read_only: Device is read-only. * @root_only: Device is accessibly to root only. + * @sysfs_read_only: The device's whole-device sysfs file is read-only for + * good: force_ro cannot make it writable. Kernel consumers still + * write its cells. * @of_node: If given, this will be used instead of the parent's of_node. * @reg_read: Callback to read data; return zero if successful. * @reg_write: Callback to write data; return zero if successful. @@ -123,6 +126,7 @@ struct nvmem_config { enum nvmem_type type; bool read_only; bool root_only; + bool sysfs_read_only; bool ignore_wp; struct nvmem_layout *layout; struct device_node *of_node; diff --git a/include/linux/pci.h b/include/linux/pci.h index c0d76d93a78f50..eb2ccfc21b750f 100644 --- a/include/linux/pci.h +++ b/include/linux/pci.h @@ -676,6 +676,8 @@ struct pci_host_bridge { * Immutable after probing; driver-coordinated resets remain permitted. */ unsigned int reset_sensitive:1; + /* Keep firmware-assigned bus numbers on this host bridge hierarchy. */ + unsigned int no_reassign_bus:1; /* Resource alignment requirements */ resource_size_t (*align_resource)(struct pci_dev *dev, diff --git a/include/linux/phy/phy-dp.h b/include/linux/phy/phy-dp.h index 9cce5766bc0b89..bdedc2c3517a7d 100644 --- a/include/linux/phy/phy-dp.h +++ b/include/linux/phy/phy-dp.h @@ -93,6 +93,34 @@ struct phy_configure_opts_dp { * */ u8 set_voltages : 1; + + /** + * @set_tunnel_rate: + * + * Flag indicating, whether or not to start or stop the pixel clock + * of a DisplayPort tunnel, for a PHY in USB4 mode whose own PLL + * clocks the DP IN adapters of its USB4 router. Used alone: the + * other set_* flags must be clear. + * + */ + u8 set_tunnel_rate : 1; + + /** + * @tunnel_dpin: + * + * DP IN adapter of the router whose pixel clock @set_tunnel_rate + * starts or stops, as the display controller numbers them. + */ + unsigned int tunnel_dpin; + + /** + * @tunnel_rate: + * + * DP link rate code (DPCD LINK_BW_SET: 0x06 RBR, 0x0a HBR, 0x14 HBR2, + * 0x1e HBR3) of the stream tunnelled through @tunnel_dpin, or 0 to + * stop its pixel clock. + */ + u8 tunnel_rate; }; #endif /* __PHY_DP_H_ */ diff --git a/include/linux/sched.h b/include/linux/sched.h index 57ef9a060eb653..a6f978d4f3fe9f 100644 --- a/include/linux/sched.h +++ b/include/linux/sched.h @@ -598,6 +598,14 @@ struct sched_entity { u64 nr_migrations; + /* + * Run time between sleeps: sum_exec_runtime when the task last went + * to sleep, and the decaying average of the run time between two + * sleeps. See wake_short_local(). + */ + u64 prev_sleep_sum_runtime; + u64 burst_avg; + #ifdef CONFIG_FAIR_GROUP_SCHED int depth; struct sched_entity *parent; diff --git a/include/linux/soc/apple/actuator.h b/include/linux/soc/apple/actuator.h index 18e1bee0e266c5..2397d14e443948 100644 --- a/include/linux/soc/apple/actuator.h +++ b/include/linux/soc/apple/actuator.h @@ -22,6 +22,10 @@ static inline bool apple_taptic_is_actuator(struct hid_device *hdev) #if IS_ENABLED(CONFIG_HID_APPLE_MTP_HAPTIC) int apple_taptic_send(struct hid_device *hdev, u16 effect_type, u8 strength, u8 softness); int apple_taptic_switch_modes(struct hid_device *hdev, bool host_controlled); +int apple_taptic_get_waveform(struct hid_device *hdev, u16 effect_type, + u8 *body, size_t size); +int apple_taptic_send_waveform(struct hid_device *hdev, const u8 *body, + size_t len); #else static inline int apple_taptic_send(struct hid_device *hdev, u16 effect_type, @@ -35,5 +39,18 @@ static inline int apple_taptic_switch_modes(struct hid_device *hdev, { return -ENODEV; } + +static inline int apple_taptic_get_waveform(struct hid_device *hdev, + u16 effect_type, u8 *body, + size_t size) +{ + return -ENODEV; +} + +static inline int apple_taptic_send_waveform(struct hid_device *hdev, + const u8 *body, size_t len) +{ + return -ENODEV; +} #endif #endif /* __APPLE_MTP_ACTUATOR_H__ */ diff --git a/include/linux/soc/apple/clpc.h b/include/linux/soc/apple/clpc.h index 0a4c4f439ac565..5f83b2aedc609c 100644 --- a/include/linux/soc/apple/clpc.h +++ b/include/linux/soc/apple/clpc.h @@ -12,6 +12,7 @@ struct apple_clpc_ane; #if IS_REACHABLE(CONFIG_APPLE_CLPC) int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu **out); void apple_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active); +void apple_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille); void apple_clpc_gpu_put(struct apple_clpc_gpu *gpu); /* Optional, single-publisher input: success with NULL means no provider. */ int apple_clpc_ane_get(struct device *dev, struct apple_clpc_ane **out); @@ -24,6 +25,7 @@ static inline int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu * return device_property_present(dev, "apple,clpc") ? -ENODEV : 0; } static inline void apple_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active) {} +static inline void apple_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille) {} static inline void apple_clpc_gpu_put(struct apple_clpc_gpu *gpu) {} /* ANE remains usable when the optional floor provider is not reachable. */ diff --git a/include/linux/soc/apple/dart.h b/include/linux/soc/apple/dart.h index 0a7925025e6287..a541b326a4bdc7 100644 --- a/include/linux/soc/apple/dart.h +++ b/include/linux/soc/apple/dart.h @@ -2,14 +2,30 @@ #ifndef __LINUX_SOC_APPLE_DART_H__ #define __LINUX_SOC_APPLE_DART_H__ +#include #include #include #include +#include #include struct device; struct device_node; +/* + * Whether apple-dart keeps the firmware's root slots of a DART of @np's kind + * that the boot loader leaves locked (fw_mirror). Only then can a coprocessor + * the boot loader leaves running behind such a DART be adopted: on the plain + * locked path its firmware loses the mappings it runs on. + */ +static inline bool apple_dart_keeps_locked_roots(const struct device_node *np) +{ + return of_device_is_compatible(np, "apple,t6041-dart") || + of_device_is_compatible(np, "apple,t6050-dart") || + of_device_is_compatible(np, "apple,t8140-dart") || + of_device_is_compatible(np, "apple,t8142-dart"); +} + /* Retained internal-display ownership is qualified only with a built-in * DART provider. Other consumers, including modular DART, keep the APIs below. */ @@ -180,6 +196,24 @@ static inline int apple_dart_host_resume(struct device *dev) { return -EOPNOTSUP static inline int apple_dart_host_restart(struct device *dev) { return -EOPNOTSUPP; } #endif +/* + * The physical range behind a buffer a co-processor's firmware names, for a CPU mapping: + * contiguous over every IOMMU page it touches, in DRAM outside System RAM. The flags + * choose what resolves a DVA: Linux's own mappings, those the firmware kept, or both. + */ +#define APPLE_DART_FW_LINUX BIT(0) +#define APPLE_DART_FW_RETAINED BIT(1) +#if IS_REACHABLE(CONFIG_APPLE_DART) +int apple_dart_fw_range(struct device *dev, dma_addr_t iova, size_t size, + unsigned int flags, phys_addr_t *phys); +#else +static inline int apple_dart_fw_range(struct device *dev, dma_addr_t iova, size_t size, + unsigned int flags, phys_addr_t *phys) +{ + return -ENODEV; +} +#endif + /* For a consumer whose firmware gates itself around a firmware-driven suspend. */ #if IS_REACHABLE(CONFIG_APPLE_DART) bool apple_dart_sleep_listed(struct device *dev); @@ -187,10 +221,14 @@ int apple_dart_sleep_prepare(struct device *dev); void apple_dart_sleep_restore(struct device *dev); /* A display DART's streams around a display power cycle, see the DART driver. */ int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool flush); +/* The streams 0 to 31 a display DART has enabled; 0 if any stream above 31 is on. */ +u32 apple_dart_enabled_streams(struct device *dev); +/* A locked display DART's TCR and TTBR words kept across a real sleep (T6041). */ +int apple_dart_display_keep(struct device *dev, u32 streams, bool save); /* A GAPF slice released before its coprocessor's CPU domain comes up after a wake. */ int apple_dart_gapf_ready(struct device *dev); /* A display DART whose domain goes off at runtime while others still map into it. */ -void apple_dart_power_dark(struct device *dev, bool dark); +int apple_dart_power_dark(struct device *dev, bool dark); /* A DART's state kept across its consumer's own power cycle, outside a system sleep. */ int apple_dart_m5_restore(struct device *dev, struct device *owner); /* T6050: a display coprocessor's DART around its restart, the display pipe's around its domain's. */ @@ -221,13 +259,24 @@ static inline int apple_dart_display_streams(struct device *dev, u32 streams, bo return -ENODEV; } +static inline u32 apple_dart_enabled_streams(struct device *dev) +{ + return 0; +} + +static inline int apple_dart_display_keep(struct device *dev, u32 streams, bool save) +{ + return -ENODEV; +} + static inline int apple_dart_gapf_ready(struct device *dev) { return 0; } -static inline void apple_dart_power_dark(struct device *dev, bool dark) +static inline int apple_dart_power_dark(struct device *dev, bool dark) { + return 0; } static inline int apple_dart_m5_restore(struct device *dev, struct device *owner) diff --git a/include/linux/soc/apple/dcp-v27-sleep.h b/include/linux/soc/apple/dcp-v27-sleep.h index 5e56c401419036..186f5d58e849c3 100644 --- a/include/linux/soc/apple/dcp-v27-sleep.h +++ b/include/linux/soc/apple/dcp-v27-sleep.h @@ -16,7 +16,8 @@ struct apple_dart_v27_lease; */ struct apple_sleep_v27_ops { int (*arm)(void *data); - int (*check)(void *data); + /* committed: called after the sleep's commit, right before stop. */ + int (*check)(void *data, bool committed); int (*stop)(void *data); int (*disarm)(void *data, bool stopped); }; @@ -37,8 +38,10 @@ static inline void apple_sleep_v27_prepared(struct device *dev, bool prepared) { int apple_rtkit_v27_arm(struct apple_rtkit *, struct apple_rtkit_v27_scope **); bool apple_rtkit_v27_live(struct apple_rtkit *); -int apple_rtkit_v27_check(struct apple_rtkit_v27_scope *); +int apple_rtkit_v27_check(struct apple_rtkit_v27_scope *, bool committed); int apple_rtkit_v27_idle_atomic(struct apple_rtkit_v27_scope *); +int apple_rtkit_v27_port_ap_idle_atomic(struct apple_rtkit *rtk, unsigned int us); +void apple_rtkit_v27_set_after_ap(struct apple_rtkit_v27_scope *s, int (*fn)(void *), void *data); int apple_rtkit_v27_disarm(struct apple_rtkit_v27_scope *, bool stopped); int apple_dart_v27_claim(struct device *provider, struct device *firmware, diff --git a/include/linux/soc/apple/display.h b/include/linux/soc/apple/display.h index aa7266693ace87..9f252caabea758 100644 --- a/include/linux/soc/apple/display.h +++ b/include/linux/soc/apple/display.h @@ -11,6 +11,8 @@ struct device; /* Initial native display admission, before starting retained GPU firmware. */ +int apple_drm_link_device(struct device *consumer, + const struct device_node *display_node); int apple_drm_t6030_link_device(struct device *consumer); int apple_drm_t6031_link_device(struct device *consumer); int apple_drm_t8132_link_device(struct device *consumer); @@ -18,6 +20,12 @@ int apple_drm_t8132_link_device(struct device *consumer); /* T6041 DCP image shipped with macOS 27.2 (26B123). */ #define APPLE_T6041_DCP_26B123_UUID "964EDE5B-8F78-38C2-A727-519CC9F0AF27" +/* + * T8132 DCP image shipped with macOS 27.2 (26B123), as the J773g's 27.2 ADT + * names it for dcp, dcpext0 and dcpext1 alike (they share its __TEXT). + */ +#define APPLE_T8132_DCP_26B123_UUID "B3BA603C-3CA7-3E21-B393-44EB20BD2AEF" + /* * @np is a @compat_name display processor that the boot loader handed over * with the 27.2 (26B123) image @image_uuid: firmware version and @@ -44,6 +52,20 @@ static inline bool apple_dcp_image_v27_2(const struct device_node *np, compat[0] == 27 && compat[1] == 2 && compat[2] == 0; } +/* + * A T8132 internal display processor that the boot loader handed over with + * the 27.2 (26B123) image and the firmware-27 clock metadata (apple,clock-ids + * from the ADT's /arm-io/disp0): the firmware-27 backend's, not the M4 + * 26.6.2 one's. Keyed on the processor, the image and the handoff, so a main + * DCP a boot loader leaves running idle (a Mac mini's) is never adopted. + */ +static inline bool apple_t8132_dcp_v27_2(const struct device_node *np) +{ + return apple_dcp_image_v27_2(np, "apple,t8132-dcp", + APPLE_T8132_DCP_26B123_UUID) && + of_property_present(np, "apple,clock-ids"); +} + static inline bool apple_t6041_dcp_any_v27_2(const struct device_node *np, const char *compat_name) { @@ -86,4 +108,43 @@ static inline bool apple_t8122_dcp_v27_2(const struct device_node *np) APPLE_T8122_DCP_26B123_UUID); } +/* + * The T8122 external display processor on the 27.2 image. The boot loader + * publishes its firmware version and compatibility but no image UUID; it + * runs the internal processor's image (its text segment is the internal + * DCP's region). So it qualifies when both of its own are 27.2.0 and the + * internal DCP was handed over on the 27.2 image. + */ +static inline bool +apple_t8122_dcpext_v27_2_for_internal(const struct device_node *np, + const struct device_node *internal_dcp) +{ + u32 fw[3], compat[3]; + + if (!np || !of_device_is_compatible(np, "apple,t8122-dcpext") || + of_property_count_u32_elems(np, "apple,firmware-version") != 3 || + of_property_count_u32_elems(np, "apple,firmware-compat") != 3 || + of_property_read_u32_array(np, "apple,firmware-version", fw, 3) || + of_property_read_u32_array(np, "apple,firmware-compat", compat, 3) || + fw[0] != 27 || fw[1] != 2 || fw[2] != 0 || + compat[0] != 27 || compat[1] != 2 || compat[2] != 0) + return false; + + return apple_t8122_dcp_v27_2(internal_dcp); +} + +static inline bool apple_t8122_dcpext_v27_2(const struct device_node *np) +{ + struct device_node *dcp; + bool internal; + + if (!np || !of_device_is_compatible(np, "apple,t8122-dcpext")) + return false; + + dcp = of_find_compatible_node(NULL, NULL, "apple,t8122-dcp"); + internal = apple_t8122_dcpext_v27_2_for_internal(np, dcp); + of_node_put(dcp); + return internal; +} + #endif diff --git a/include/linux/soc/apple/mailbox.h b/include/linux/soc/apple/mailbox.h index 0159bbc356cfa1..65f04f556c2dfc 100644 --- a/include/linux/soc/apple/mailbox.h +++ b/include/linux/soc/apple/mailbox.h @@ -96,6 +96,8 @@ struct apple_mbox { }; struct apple_mbox *apple_mbox_get(struct device *dev, int index); +/* As apple_mbox_get(), for a mailbox named by a property other than mboxes */ +struct apple_mbox *apple_mbox_get_prop(struct device *dev, const char *prop, int index); struct apple_mbox *apple_mbox_get_byname(struct device *dev, const char *name); int apple_mbox_start(struct apple_mbox *mbox); @@ -125,9 +127,9 @@ void apple_mbox_set_recv_enabled(struct apple_mbox *mbox, bool enabled); void apple_mbox_hold_rx(struct apple_mbox *mbox); void apple_mbox_release_rx(struct apple_mbox *mbox); /* - * Set the minimum utilization (0..1024) the threaded receive handler runs with, - * or -1 to restore the scheduler's default; the handler applies it to itself - * when it next runs. Only mailboxes with a threaded receive handler support it. + * Set the minimum utilization (0..1024) the G17 flood-throttle receive thread + * runs with, or -1 to restore the scheduler's default; the thread applies it + * when it next wakes. Only mailboxes with a threaded receive handler support it. */ int apple_mbox_set_rx_util_min(struct apple_mbox *mbox, int util_min); int apple_mbox_send(struct apple_mbox *mbox, struct apple_mbox_msg msg, diff --git a/include/linux/soc/apple/mcc.h b/include/linux/soc/apple/mcc.h new file mode 100644 index 00000000000000..76e92ea270a3ba --- /dev/null +++ b/include/linux/soc/apple/mcc.h @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _LINUX_SOC_APPLE_MCC_H_ +#define _LINUX_SOC_APPLE_MCC_H_ + +#include +#include +#include + +struct device; +struct device_node; + +/* A cache controller with allocation enabled, for the OF detach notifier. */ +struct apple_mcc_boot_dma_consumer { + struct list_head link; + struct device *dev; + /* Under the boot DMA lock: turn allocation off. */ + void (*lost)(struct apple_mcc_boot_dma_consumer *consumer); +}; + +#if IS_ENABLED(CONFIG_APPLE_MCC_BOOT_DMA) +int apple_mcc_boot_scanout_reserve(struct device_node *supplier); +void apple_mcc_boot_scanout_retired(struct device_node *supplier); +int apple_mcc_boot_scanout_ready(struct device *dev, struct device_node *supplier); +void apple_mcc_boot_dma_lock(void); +void apple_mcc_boot_dma_unlock(void); +void apple_mcc_boot_dma_register_locked(struct apple_mcc_boot_dma_consumer *consumer); +void apple_mcc_boot_dma_unregister(struct apple_mcc_boot_dma_consumer *consumer); +#else +static inline int apple_mcc_boot_scanout_reserve(struct device_node *supplier) +{ + return 0; +} + +static inline void apple_mcc_boot_scanout_retired(struct device_node *supplier) { } +#endif + +#endif diff --git a/include/linux/soc/apple/pmp-cooling.h b/include/linux/soc/apple/pmp-cooling.h index 6a53d9e87ef780..6f65811188fe55 100644 --- a/include/linux/soc/apple/pmp-cooling.h +++ b/include/linux/soc/apple/pmp-cooling.h @@ -23,15 +23,30 @@ /* * The firmware publishes a die sensor only while its cluster has power, so an idle * machine can have none valid for a moment (0.46 s the longest measured). Go on from the - * last reading for this long, if it was this cool. Longer or hotter is a failed sensor. + * last reading for this long, if it was this cool. Longer or hotter is a failed sensor, + * except for a single transient PMP SRAM refresh glitch below passive throttling. */ #define APPLE_PMP_GATED_HOLD_NS 2000000000ULL -#define APPLE_PMP_GATED_HOLD_MC 90000 +#define APPLE_PMP_GATED_HOLD_MC 100000 +#define APPLE_PMP_TRANSIENT_HOLD_NS 100000000ULL /* Below this hotspot, with no fault, recovery or cooling in force, nothing * acts until prediction starts at 105 C, so the slow cadence is enough. */ #define APPLE_PMP_FAST_POLL_MC 95000 +static inline bool apple_pmp_hold_nodata(unsigned long long valid_ns, + long valid_mc, + unsigned long long now, bool idle) +{ + if (!valid_ns || now < valid_ns) + return false; + if (valid_mc < APPLE_PMP_GATED_HOLD_MC && + (idle || now - valid_ns < APPLE_PMP_GATED_HOLD_NS)) + return true; + return valid_mc < APPLE_PMP_PASSIVE_MC && + now - valid_ns <= APPLE_PMP_TRANSIENT_HOLD_NS; +} + struct apple_pmp_cooling { unsigned long long last_ns, good_ns, anchor_ns, release_ns; unsigned long long dt_ns; diff --git a/include/linux/soc/apple/pmp-display.h b/include/linux/soc/apple/pmp-display.h index e65effb337aa82..a532b1c25864e6 100644 --- a/include/linux/soc/apple/pmp-display.h +++ b/include/linux/soc/apple/pmp-display.h @@ -3,13 +3,28 @@ #define _LINUX_SOC_APPLE_PMP_DISPLAY_H #include -#include #include -/* The retained M4 bridge and raw thermal records: the M4 firmware path. */ +/* + * Detect the retained T8132 PMP power-vote bridge from the device tree's own + * `pmp` node and tunable table property rather than a board list, SoC machine + * compatible, or OS firmware version string. + */ +static inline bool apple_pmp_t8132_retained_board(void) +{ + struct device_node *np = of_find_node_by_path("pmp"); + bool match = np && of_device_is_available(np) && + of_device_is_compatible(np, "apple,t8132-pmp-v2") && + of_property_present(np, "apple,tunable-soc-device"); + + of_node_put(np); + return match; +} + +/* The retained M4 bridge and raw thermal records. */ static inline bool apple_pmp_j713_board(void) { - return apple_t8132_firmware_path() && of_machine_is_compatible("apple,t8132"); + return apple_pmp_t8132_retained_board(); } struct device; diff --git a/include/linux/soc/apple/pmp-power-policy.h b/include/linux/soc/apple/pmp-power-policy.h index faef838ea24126..bbd5699b1114df 100644 --- a/include/linux/soc/apple/pmp-power-policy.h +++ b/include/linux/soc/apple/pmp-power-policy.h @@ -19,7 +19,7 @@ struct apple_pmp_power_policy { int sustainable_mw, allowed_mw, total_mw, filtered_mc; unsigned int level[3], next_release, good; unsigned int active; - bool initialized, fault; + bool initialized, fault, unbudgeted; }; /* SMC little-endian IEEE binary32 Watts -> mW. Reject NaN/Inf, negative, @@ -53,6 +53,20 @@ static inline void apple_pmp_power_init(struct apple_pmp_power_policy *s) }; } +/* A Mac whose fan the SMC appears to run on the heat the SoC makes: the + * energy budget above is the fanless Airs' and takes that heat away, so the + * fan stops and power stays near the floor. Such a board keeps the die guard as its + * limit; the rails are still read, and a fault or a gap in them still selects + * full protection and recovers one step per second, as on the Airs. + */ +static inline void apple_pmp_power_init_unbudgeted(struct apple_pmp_power_policy *s) +{ + apple_pmp_power_init(s); + s->sustainable_mw = 0; + s->allowed_mw = 0; + s->unbudgeted = true; +} + /* A newly attached consumer starts restricted. An absent consumer cannot * absorb releases or be selected as a way to reduce measured consumption. */ @@ -76,6 +90,59 @@ static inline void apple_pmp_power_fail(struct apple_pmp_power_policy *s) s->good = 0; } +/* Release the largest weighted restriction, round-robin on ties. */ +static inline void apple_pmp_power_release(struct apple_pmp_power_policy *s, + unsigned long long now, + const unsigned int weight[3]) +{ + unsigned int i, chosen = 3; + + for (i = 0; i < 3; i++) { + unsigned int candidate = (s->next_release + i) % 3; + + if ((s->active & (1U << candidate)) && s->level[candidate] && + (chosen == 3 || + s->level[candidate] * weight[candidate] > + s->level[chosen] * weight[chosen])) + chosen = candidate; + } + if (chosen < 3) { + s->level[chosen]--; + s->next_release = (chosen + 1) % 3; + } + s->change_ns = now; +} + +/* On an unbudgeted board die temperature does not drive an energy bucket. + * While every die sensor is dark (-ENODATA) and the SMC rails were read, keep + * the rail sum and sample timestamp current so a >2 s idle dark span does not + * trip the gap fault on the next valid die reading. A genuine >2 s telemetry + * gap still fails closed, and any prior fault stays latched until valid die + * samples confirm recovery. + */ +static inline void apple_pmp_power_dark(struct apple_pmp_power_policy *s, + unsigned long long now, + const unsigned int mw[3]) +{ + unsigned long long dt = s->last_ns ? now - s->last_ns : 0; + unsigned int i; + + if (!s->unbudgeted) + return; + if (dt > 2000000000ULL) { + apple_pmp_power_fail(s); + s->last_ns = now; + return; + } + if (s->last_ns && dt < 400000000ULL) + return; + s->last_ns = now; + s->total_mw = 0; + for (i = 0; i < 3; i++) + if (s->active & (1U << i)) + s->total_mw += mw[i]; +} + static inline void apple_pmp_power_sample(struct apple_pmp_power_policy *s, unsigned long long now, const unsigned int mw[3], int mc, int error) { @@ -104,7 +171,7 @@ static inline void apple_pmp_power_sample(struct apple_pmp_power_policy *s, s->total_mw += mw[i]; if (!s->initialized) { s->initialized = true; - s->credit_mj = mc < 75000 ? APPLE_PMP_BURST_MJ : 0; + s->credit_mj = mc < 75000 && !s->unbudgeted ? APPLE_PMP_BURST_MJ : 0; s->filtered_mc = mc; s->tune_ns = now; } @@ -114,6 +181,12 @@ static inline void apple_pmp_power_sample(struct apple_pmp_power_policy *s, return; s->fault = false; s->filtered_mc += (mc - s->filtered_mc) * (long long)ms / (long long)(5000 + ms); + if (s->unbudgeted) { + /* Release one step per second; nothing restricts again. */ + if (now - s->change_ns >= 1000000000ULL) + apple_pmp_power_release(s, now, weight); + return; + } if (s->total_mw > s->sustainable_mw) s->credit_mj -= (s->total_mw - s->sustainable_mw) * (long long)ms / 1000; else if (mc < 75000) @@ -163,20 +236,7 @@ static inline void apple_pmp_power_sample(struct apple_pmp_power_policy *s, * This restores graphics headroom before spending it on CPU stress. * Fault recovery still restores only one step per elapsed interval. */ - for (i = 0; i < 3; i++) { - unsigned int candidate = (s->next_release + i) % 3; - - if ((s->active & (1U << candidate)) && s->level[candidate] && - (chosen == 3 || - s->level[candidate] * weight[candidate] > - s->level[chosen] * weight[chosen])) - chosen = candidate; - } - if (chosen < 3) { - s->level[chosen]--; - s->next_release = (chosen + 1) % 3; - } - s->change_ns = now; + apple_pmp_power_release(s, now, weight); } } diff --git a/include/linux/soc/apple/pmp-temps.h b/include/linux/soc/apple/pmp-temps.h index fe9bf8faf03bbc..a81e666a35f81a 100644 --- a/include/linux/soc/apple/pmp-temps.h +++ b/include/linux/soc/apple/pmp-temps.h @@ -48,16 +48,106 @@ static inline int apple_pmp_temp_decode(const u8 *record, const char *name, long return 0; } -static inline int apple_pmp_temp_sample(void __iomem *sram, unsigned int index, - long *value) +/* + * The temperature record offsets in SRAM vary across firmware builds: the + * defaults above are those observed on the 26.6.2 (25G83) firmware. A map + * holds each record's offset for the running firmware. + */ +struct apple_pmp_temp_map { + u32 offset[PMP_TEMP_CHANNELS]; +}; + +static inline void apple_pmp_temp_map_default(struct apple_pmp_temp_map *map) +{ + unsigned int i; + + for (i = 0; i < PMP_TEMP_CHANNELS; i++) + map->offset[i] = apple_pmp_temp_records[i].offset; +} + +/* Distance between consecutive records in the 25G83 firmware's array. */ +#define PMP_TEMP_RECORD_STRIDE 0xa4 + +/* A record with this name and a validity word of 0 or 1. */ +static inline bool apple_pmp_temp_record_plausible(const u8 *record, const char *name) +{ + return !memcmp(record, name, strlen(name) + 1) && + get_unaligned_le32(record + PMP_TEMP_VALID_OFFSET) <= 1; +} + +/** + * apple_pmp_temp_locate() - find the temperature records of the running firmware + * @sram: the PMP SRAM + * @start: first byte to search, 4-byte aligned + * @end: end of the search, at most the size of the SRAM mapping + * @map: filled with the offsets found + * + * Every record starts with its NUL-terminated name. Each name must appear at + * exactly one plausible record; where it appears at several, the one in step + * with a unique first record (PMP_TEMP_RECORD_STRIDE apart) is taken. + * + * Context: process context; reads up to @end - @start bytes of SRAM. + * Return: 0 with @map filled, -ENOENT if a record is missing, -EEXIST if one + * is ambiguous, -EINVAL for a bad range. @map is written only on success. + */ +static inline int apple_pmp_temp_locate(void __iomem *sram, size_t start, size_t end, + struct apple_pmp_temp_map *map) +{ + u32 found[PMP_TEMP_CHANNELS][4]; + unsigned int count[PMP_TEMP_CHANNELS] = {}; + struct apple_pmp_temp_map result; + u8 record[PMP_TEMP_RECORD_SIZE]; + unsigned int i, j; + size_t off; + + if ((start & 3) || end < PMP_TEMP_RECORD_SIZE || start > end - PMP_TEMP_RECORD_SIZE) + return -EINVAL; + for (off = start; off <= end - PMP_TEMP_RECORD_SIZE; off += 4) { + u32 word = readl_relaxed(sram + off); + + for (i = 0; i < PMP_TEMP_CHANNELS; i++) { + const char *name = apple_pmp_temp_records[i].name; + + if (word != get_unaligned_le32(name)) + continue; + memcpy_fromio(record, sram + off, sizeof(record)); + if (apple_pmp_temp_record_plausible(record, name) && + count[i] < ARRAY_SIZE(found[i])) + found[i][count[i]++] = off; + } + } + for (i = 0; i < PMP_TEMP_CHANNELS; i++) { + if (!count[i]) + return -ENOENT; + if (count[i] == 1) { + result.offset[i] = found[i][0]; + continue; + } + if (!i || count[0] != 1) + return -EEXIST; + for (j = 0; j < count[i]; j++) + if (found[i][j] == result.offset[0] + i * PMP_TEMP_RECORD_STRIDE) + break; + if (j == count[i]) + return -EEXIST; + result.offset[i] = found[i][j]; + } + *map = result; + return 0; +} + +static inline int apple_pmp_temp_sample_map(void __iomem *sram, + const struct apple_pmp_temp_map *map, + unsigned int index, long *value) { const struct apple_pmp_temp_record *record = &apple_pmp_temp_records[index]; + u32 offset = READ_ONCE(map->offset[index]); u8 first[PMP_TEMP_RECORD_SIZE], second[PMP_TEMP_RECORD_SIZE]; unsigned int attempt; for (attempt = 0; attempt < PMP_TEMP_READ_ATTEMPTS; attempt++) { - memcpy_fromio(first, sram + record->offset, sizeof(first)); - memcpy_fromio(second, sram + record->offset, sizeof(second)); + memcpy_fromio(first, sram + offset, sizeof(first)); + memcpy_fromio(second, sram + offset, sizeof(second)); if (!memcmp(first, second, sizeof(first))) return apple_pmp_temp_decode(first, record->name, value); } @@ -65,8 +155,18 @@ static inline int apple_pmp_temp_sample(void __iomem *sram, unsigned int index, return -EAGAIN; } -static inline int apple_pmp_temp_hotspot_channel(void __iomem *sram, long *value, - int *channel) +static inline int apple_pmp_temp_sample(void __iomem *sram, unsigned int index, + long *value) +{ + struct apple_pmp_temp_map map; + + apple_pmp_temp_map_default(&map); + return apple_pmp_temp_sample_map(sram, &map, index, value); +} + +static inline int apple_pmp_temp_hotspot_channel_map(void __iomem *sram, + const struct apple_pmp_temp_map *map, + long *value, int *channel) { bool found = false; long hottest = 0, sample; @@ -75,7 +175,7 @@ static inline int apple_pmp_temp_hotspot_channel(void __iomem *sram, long *value *channel = -1; for (i = 0; i < ARRAY_SIZE(apple_pmp_temp_records); i++) { - ret = apple_pmp_temp_sample(sram, i, &sample); + ret = apple_pmp_temp_sample_map(sram, map, i, &sample); if (ret == -ENODATA) continue; if (ret) @@ -93,6 +193,24 @@ static inline int apple_pmp_temp_hotspot_channel(void __iomem *sram, long *value return 0; } +static inline int apple_pmp_temp_hotspot_channel(void __iomem *sram, long *value, + int *channel) +{ + struct apple_pmp_temp_map map; + + apple_pmp_temp_map_default(&map); + return apple_pmp_temp_hotspot_channel_map(sram, &map, value, channel); +} + +static inline int apple_pmp_temp_hotspot_map(void __iomem *sram, + const struct apple_pmp_temp_map *map, + long *value) +{ + int channel; + + return apple_pmp_temp_hotspot_channel_map(sram, map, value, &channel); +} + static inline int apple_pmp_temp_hotspot(void __iomem *sram, long *value) { int channel; diff --git a/include/linux/soc/apple/rtkit.h b/include/linux/soc/apple/rtkit.h index 4db916bb89f09d..b0edf3d2b9ec1f 100644 --- a/include/linux/soc/apple/rtkit.h +++ b/include/linux/soc/apple/rtkit.h @@ -164,6 +164,11 @@ struct apple_rtkit *apple_rtkit_init(struct device *dev, void *cookie, const char *mbox_name, int mbox_idx, const struct apple_rtkit_ops *ops); +/* As apple_rtkit_init(), with the mailbox named by @mbox_prop instead of mboxes. */ +struct apple_rtkit *apple_rtkit_init_mbox_prop(struct device *dev, void *cookie, + const char *mbox_prop, + const struct apple_rtkit_ops *ops); + /* * Initialize an instance for a co-processor that the bootloader left running * and that cannot be reset. No HELLO/EPMAP handshake takes place: the system @@ -186,6 +191,28 @@ struct apple_rtkit *apple_rtkit_init_adopted_with_buffers( const struct apple_rtkit_ops *ops, const struct apple_rtkit_inherited_buffer *buffers, unsigned int count); +#define APPLE_RTKIT_ADOPTED_EPMAP_WORDS 8 + +/* + * Negotiated state from the previous owner of a running session: the + * protocol version, the endpoint map the firmware advertised (word i holds + * endpoints 32i..32i+31) and the retained system buffers. The parent driver + * verifies that the co-processor runs and the backing of each buffer. + * Application endpoints in the map each need a start from the new owner. + * Everything is copied before mailbox RX starts. + */ +struct apple_rtkit_adopted_session { + const struct apple_rtkit_inherited_buffer *buffers; + unsigned int num_buffers; + u32 epmap[APPLE_RTKIT_ADOPTED_EPMAP_WORDS]; + u16 protocol_version; +}; + +struct apple_rtkit *apple_rtkit_init_adopted_with_session( + struct device *dev, void *cookie, const char *mbox_name, int mbox_idx, + const struct apple_rtkit_ops *ops, + const struct apple_rtkit_adopted_session *session); + /* * Free an instance of apple_rtkit. */ @@ -248,6 +275,14 @@ int apple_rtkit_quiesce(struct apple_rtkit *rtk); */ int apple_rtkit_wake(struct apple_rtkit *rtk); +/* + * Start a co-processor whose firmware may acknowledge IOP power on by itself + * once it has reported in: take that acknowledgment if it comes within + * @self_ack_ms, else ask for IOP power as apple_rtkit_wake() does. Call it + * after the co-processor's CPU has been started. + */ +int apple_rtkit_boot_or_wake(struct apple_rtkit *rtk, unsigned int self_ack_ms); + /* Wake helpers which require AP readiness before their IOP power acknowledgment. */ int apple_rtkit_wake_early_ap(struct apple_rtkit *rtk); @@ -270,6 +305,7 @@ int apple_rtkit_shutdown(struct apple_rtkit *rtk); */ int apple_rtkit_poweroff(struct apple_rtkit *rtk); +int apple_rtkit_mbox_restore(struct apple_rtkit *rtk); /* * After poweroff and a power cycle: start a fresh session, let @start start the @@ -285,6 +321,7 @@ int apple_rtkit_idle(struct apple_rtkit *rtk); /* The mailbox's receive-enable bit (I2A_CONTROL bit 0): off once a slept firmware has answered its idle. */ void apple_rtkit_set_recv_enabled(struct apple_rtkit *rtk, bool enabled); int apple_rtkit_idle_strict(struct apple_rtkit *rtk); +int apple_rtkit_idle_strict_with(struct apple_rtkit *rtk, int (*after_ap)(void *data), void *data); int apple_rtkit_warm_restart_strict(struct apple_rtkit *rtk); int apple_rtkit_warm_restart_stopped(struct apple_rtkit *rtk); @@ -512,4 +549,14 @@ struct apple_rtkit *devm_apple_rtkit_init_m5_saved(struct device *dev, void *coo const char *mbox_name, int mbox_idx, const struct apple_rtkit_ops *ops); +/* + * Registers an application endpoint the client started itself on a + * co-processor whose endpoint map the bootloader consumed, so that its + * messages are not reported as undiscovered + * + * @rtk: RTKit reference + * @ep: endpoint to register + */ +void apple_rtkit_adopt_ep(struct apple_rtkit *rtk, u8 ep); + #endif /* _LINUX_APPLE_RTKIT_H_ */ diff --git a/include/linux/soc/apple/sart.h b/include/linux/soc/apple/sart.h index 5bfa06041dc7dc..e101f4fa19edf0 100644 --- a/include/linux/soc/apple/sart.h +++ b/include/linux/soc/apple/sart.h @@ -26,6 +26,8 @@ struct apple_sart; * apple_sart_add_allowed_region and apple_sart_remove_allowed_region. */ struct apple_sart *devm_apple_sart_get(struct device *dev); +void apple_sart_save_now(struct apple_sart *sart); +void apple_sart_restore_early(struct apple_sart *sart); /* * Adds the region [paddr, paddr+size] to the DMA allow list. diff --git a/include/linux/soc/apple/sleep.h b/include/linux/soc/apple/sleep.h index db4337d663b818..9b7d29e3ef8d94 100644 --- a/include/linux/soc/apple/sleep.h +++ b/include/linux/soc/apple/sleep.h @@ -9,10 +9,34 @@ #include #include #include +#include #include struct device; -struct device_node; +struct resource; + +/* + * A T6050 machine whose device tree describes the firmware-driven sleep. What a + * driver does for that sleep follows the description, not a list of boards. + * With @prop: the description also has that property. + */ +static inline bool apple_t6050_sleep_property(const char *prop) +{ + struct device_node *np; + bool ret; + + if (!of_machine_is_compatible("apple,t6050")) + return false; + np = of_find_compatible_node(NULL, NULL, "apple,t6050-sleep"); + ret = np && of_device_is_available(np) && (!prop || of_property_read_bool(np, prop)); + of_node_put(np); + return ret; +} + +static inline bool apple_t6050_sleep_described(void) +{ + return apple_t6050_sleep_property(NULL); +} /* The SMC's sleep messages: the pmVC value and the spacings between them, used as floors */ struct apple_sleep_smc_policy { @@ -45,6 +69,8 @@ struct apple_sleep_smc_saved_ops { const struct apple_sleep_smc_policy *apple_sleep_smc_policy(void); /* J813 experiment: send the final SMC notice after the peer idle handshakes. */ bool apple_sleep_smc_defer_notice(void); +/* Gen 1 (T8103): the SMC gets WKTP between slpw and slpa */ +bool apple_sleep_smc_gen1_keys(void); int apple_sleep_smc_register(struct device *dev, int (*late_notice)(void *data, u64 *sent, u64 *ack), void *data); int apple_sleep_smc_register_saved(struct device *dev, @@ -71,6 +97,17 @@ int apple_sleep_m5_dispext_power(struct device *dev, bool on); int apple_sleep_coproc_register(struct device *dev, void __iomem *asc, bool pcie_ans, int (*last_stop)(void *data), void *data); +/* + * For a SoC sleep driver of its own (T6041): advertise commit-time stop + * support and run the refusal checks, enclave stop, and coprocessor stops + * with interrupts off. + */ +void apple_sleep_set_commit_stops_coprocs(bool enable); +int apple_sleep_coprocs_check_all(void); +int apple_sleep_enclave_stop_all(void); +int apple_sleep_coprocs_stop_all(void); +bool apple_sleep_coprocs_ans_stopped(void); + /* * The same with no ASC to clear: @last_stop clears its own run bits and lowers its own power * domain, and runs before every other coprocessor's. The refusal checks leave that domain on. @@ -109,12 +146,18 @@ void apple_sleep_coproc_set_early(struct device *dev); /* Whether the last step stopped it: after a refused sleep, false means it still runs. */ bool apple_sleep_coproc_stopped(struct device *dev); +/* Platform wake error for a stopped coprocessor (0 if its power domain and fabric restored). */ +int apple_sleep_coproc_wake_error(struct device *dev); + /* * Whether this sleep's commit stops the registered coprocessors. Then one that can't be * registered refuses the sleep: stopped any earlier, a later refusal would strand it. */ bool apple_sleep_commit_stops_coprocs(void); +/* This firmware sleep stops before its commit: a driver must stop nothing it can't restart. */ +bool apple_sleep_dry_run(void); + /* * Untested SoCs: a coprocessor's last stop notes its own step in PMU scratch (kept across a * WD2 reset), next to the sleep driver's step and the coprocessor's slot. @@ -256,9 +299,22 @@ void apple_sleep_restore_pins(void); * sleep engine's PMGR reset of its own domains, its DARTs kept. The caller starts it after. */ int apple_sleep_engine_reset(struct device *dev); + +/* + * Watchdog handoff over a firmware-driven suspend. Between .begin and .end the + * sleep driver owns WD2 as its suspend/resume safety net; at .end it clears WD2 + * and invokes @restore so a watchdog driver sharing that WD2 block can re-arm + * its active timer. Registration matches @wdt against any available sleep node's + * "wdt" region; watchdogs without a matching sleep node return 0 without registering. + */ +int apple_sleep_wdt_register(struct device *dev, const struct resource *wdt, + void (*restore)(void *data), void *data); +void apple_sleep_wdt_unregister(struct device *dev); +bool apple_sleep_wdt_active(struct device *dev); #else static inline const struct apple_sleep_smc_policy *apple_sleep_smc_policy(void) { return NULL; } static inline bool apple_sleep_smc_defer_notice(void) { return false; } +static inline bool apple_sleep_smc_gen1_keys(void) { return false; } static inline int apple_sleep_smc_register(struct device *dev, int (*late_notice)(void *data, u64 *sent, u64 *ack), void *data) { return -EOPNOTSUPP; } static inline int apple_sleep_smc_register_saved(struct device *dev, @@ -324,13 +380,47 @@ static inline bool apple_sleep_coproc_stopped(struct device *dev) return false; } +static inline int apple_sleep_coproc_wake_error(struct device *dev) +{ + return -ENODEV; +} + static inline void apple_sleep_note_sub(u8 step) {} +static inline void apple_sleep_set_commit_stops_coprocs(bool enable) +{ +} + +static inline int apple_sleep_coprocs_check_all(void) +{ + return 0; +} + +static inline int apple_sleep_enclave_stop_all(void) +{ + return 0; +} + +static inline int apple_sleep_coprocs_stop_all(void) +{ + return 0; +} + +static inline bool apple_sleep_coprocs_ans_stopped(void) +{ + return false; +} + static inline bool apple_sleep_commit_stops_coprocs(void) { return false; } +static inline bool apple_sleep_dry_run(void) +{ + return false; +} + static inline void apple_sleep_usb_set_asleep(bool asleep) { } @@ -463,6 +553,21 @@ static inline int apple_sleep_engine_reset(struct device *dev) { return -EOPNOTSUPP; } + +static inline int apple_sleep_wdt_register(struct device *dev, const struct resource *wdt, + void (*restore)(void *data), void *data) +{ + return 0; +} + +static inline void apple_sleep_wdt_unregister(struct device *dev) +{ +} + +static inline bool apple_sleep_wdt_active(struct device *dev) +{ + return false; +} #endif #endif diff --git a/include/linux/soc/apple/t8132.h b/include/linux/soc/apple/t8132.h index ec91e8faaa9b5d..72ece899b148a8 100644 --- a/include/linux/soc/apple/t8132.h +++ b/include/linux/soc/apple/t8132.h @@ -3,6 +3,7 @@ #define _LINUX_SOC_APPLE_T8132_H #include +#include #include #include @@ -54,6 +55,20 @@ static inline bool apple_t8132_firmware_path(void) return apple_t8132_air() || apple_t8132_qualified_firmware(); } +/* + * A T8132 external display processor handed over with the 27.2 image + * (first on the Mac mini, J773g): it runs the firmware-27 backend + * (iomfb_v27.c), not the M4 26.6.2 one (iomfb_m4.c). The firmware + * interface belongs to the processor and the image it runs, so both are + * checked and the board is not; what differs between boards (the HDMI + * port, its PHY, rails and hot-plug line) comes from the device tree. + */ +static inline bool apple_t8132_dcpext_v27_2(const struct device_node *np) +{ + return apple_dcp_image_v27_2(np, "apple,t8132-dcpext", + APPLE_T8132_DCP_26B123_UUID); +} + /* * The radio port the Airs have: reg-on on the SMC's gP13 with the same * template, and the radio's two ordinary streams managed on port 0 of the diff --git a/include/linux/thermal.h b/include/linux/thermal.h index 426dc182924065..9f603074c3b438 100644 --- a/include/linux/thermal.h +++ b/include/linux/thermal.h @@ -314,6 +314,9 @@ void thermal_cooling_device_unregister(struct thermal_cooling_device *); struct thermal_zone_device *thermal_zone_get_zone_by_name(const char *name); int thermal_zone_get_temp(struct thermal_zone_device *tz, int *temp); int thermal_zone_get_temp_by_name(const char *name, int *temp); +int thermal_zone_get_temp_and_trips(const char *name, int *temp, + int (*cb)(struct thermal_trip *, void *), + void *data); int thermal_zone_get_slope(struct thermal_zone_device *tz); int thermal_zone_get_offset(struct thermal_zone_device *tz); bool thermal_trip_is_bound_to_cdev(struct thermal_zone_device *tz, @@ -371,6 +374,13 @@ static inline int thermal_zone_get_temp( { return -ENODEV; } static inline int thermal_zone_get_temp_by_name(const char *name, int *temp) { return -ENODEV; } +static inline int +thermal_zone_get_temp_and_trips(const char *name, int *temp, + int (*cb)(struct thermal_trip *, void *), + void *data) +{ + return -ENODEV; +} static inline int thermal_zone_get_slope( struct thermal_zone_device *tz) { return -ENODEV; } diff --git a/include/linux/thunderbolt.h b/include/linux/thunderbolt.h index acd1668ed93d74..41496caea46e3f 100644 --- a/include/linux/thunderbolt.h +++ b/include/linux/thunderbolt.h @@ -74,6 +74,7 @@ enum tb_security_level { * @remote_activity: Successful stock remote discovery exchanges * @nhi: Pointer to the NHI structure * @ctl: Control channel for this domain + * @noirq_ctl_retained: Control rings stayed active during noirq suspend * @wq: Ordered workqueue for all domain specific work * @root_switch: Root switch of this domain * @cm_ops: Connection manager specific operations vector @@ -88,6 +89,7 @@ struct tb { atomic64_t remote_activity; struct tb_nhi *nhi; struct tb_ctl *ctl; + bool noirq_ctl_retained; struct workqueue_struct *wq; struct tb_switch *root_switch; const struct tb_cm_ops *cm_ops; @@ -517,6 +519,7 @@ void tb_service_properties_changed(struct tb_service *svc); * @iommu_dma_protection: An IOMMU will isolate external-facing ports. * @interrupt_work: Work scheduled to handle ring interrupt when no * MSI-X is used. + * @use_dma_credit_preferences: Use the router preferred DMA credit allocation * @hop_count: Number of rings (end point hops) supported by NHI. * @quirks: NHI specific quirks if any * @host_dp_policy: Host display tunnel policies supplied by the NHI glue @@ -540,6 +543,7 @@ struct tb_nhi { bool iommu_dma_protection; struct work_struct interrupt_work; u32 hop_count; + bool use_dma_credit_preferences; unsigned long quirks; unsigned long host_dp_policy; bool host_dp_dual_stream; diff --git a/include/uapi/drm/ane_accel.h b/include/uapi/drm/ane_accel.h index d0c226d131290c..69974af244f1e9 100644 --- a/include/uapi/drm/ane_accel.h +++ b/include/uapi/drm/ane_accel.h @@ -157,7 +157,12 @@ struct drm_ane_bo_free { * @pad: Must be zero. * * A successful SUBMIT returns after the engine completed the work, with the - * output buffers visible to the CPU. + * output buffers visible to the CPU. While it runs, the engine reaches only + * the buffers in @handles and @btsp_handle. The driver reports an error + * if it handles an address fault. On devices where the IOMMU handles the + * fault separately, SUBMIT may still return success. The buffers are put + * into the device address space by the SUBMIT that names them. A SUBMIT + * can also fail with -ENOMEM when there is no memory to map them. */ struct drm_ane_submit { __u64 tsk_size; diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 95ff9a15ffdb29..fb91658169745d 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -333,7 +333,7 @@ enum drm_asahi_feature { DRM_ASAHI_FEATURE_COMPUTE_WIDE_VISIBILITY = (1UL) << 8, /* - * Bits 10 to 15 are reported only by the G17P runtime. + * Bits 10 to 16 are the HAL200/G16/G17P command-stream features. */ /** @@ -543,6 +543,76 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_ASYNC_SUBMIT ((1ULL) << 39) +/* + * DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE: the render-start VDM barrier at the + * root of a render's VDM stream may set the USC cache invalidate (bit 3). + * Reported on every GPU: the kernel's stream checks admit the barrier word + * with or without it. A feature bit like those of enum drm_asahi_feature, + * defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE ((1ULL) << 40) + +/* + * DRM_ASAHI_FEATURE_COMPUTE_ONLY: the device runs compute commands only. + * DRM_ASAHI_CMD_RENDER is refused, so the device cannot serve graphics APIs; + * userspace should not offer it for them. Compute commands, the VM and GEM + * interfaces are unaffected. A feature bit like those of enum + * drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_COMPUTE_ONLY ((1ULL) << 41) + +/* + * DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL: the kernel itself runs the + * independent compute commands of one queue on several firmware compute + * queues of its context, so that they overlap. Userspace needs no further + * queues of its own for that. A feature bit like those of enum + * drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL ((1ULL) << 42) + +/* + * DRM_ASAHI_FEATURE_USERPTR_NO_MEMLOCK: DRM_IOCTL_ASAHI_GEM_USERPTR does not + * charge its pins to the caller's RLIMIT_MEMLOCK; only the GPU memory limits + * bound them (see struct drm_asahi_gem_userptr). Kernels that report + * DRM_ASAHI_FEATURE_USERPTR without it refuse with ENOMEM a range that + * exceeds that limit, unless the caller has CAP_IPC_LOCK, so userspace can + * check the limit before it offers imports of arbitrary size. Bit 42 is + * reserved for DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL. A feature bit like + * those of enum drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_USERPTR_NO_MEMLOCK ((1ULL) << 43) + +/* + * DRM_ASAHI_FEATURE_ORDERED_FRAGMENT_BARRIERS: a render command that sets + * DRM_ASAHI_RENDER_FRAGMENT_BARRIERS still waits for the earlier renders its + * barriers name: the fragment half waits for them to finish before it + * starts. Kernels that report DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS without + * this bit may drop that wait, so userspace that uses the flag to order a + * render after earlier ones must check for this bit. A feature bit like + * those of enum drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_ORDERED_FRAGMENT_BARRIERS ((1ULL) << 44) + +/* + * DRM_ASAHI_FEATURE_ORDERED_PARTIAL_RENDERS: every fragment pass of a render + * command, including partial renders the firmware runs when the tiler heap + * fills, starts only after the fragment work its fragment half is ordered + * after has completed: the earlier fragment work of its physical queue and + * the renders named by its fragment barriers. Userspace may then order a + * render's attachment loads and stores against an earlier render with + * fragment-stage ordering alone, without a tiling-half wait. A feature bit + * like those of enum drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_ORDERED_PARTIAL_RENDERS ((1ULL) << 45) + +/* + * DRM_ASAHI_FEATURE_TILE_BUFFER_48K: render commands on this GPU accept tile + * buffers of up to 48 KiB (sample_size_B * utile_width_px * utile_height_px * + * samples <= 49152). Without it, 32 KiB is the portable limit. A feature bit + * like those of enum drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_TILE_BUFFER_48K ((1ULL) << 46) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 @@ -774,12 +844,12 @@ struct drm_asahi_gem_create { * object stays the parent's memory. The CPU and GPU views are coherent * without cache maintenance. * - * The pinned pages count against the caller's RLIMIT_MEMLOCK, together with - * its other long-term pins, unless it has CAP_IPC_LOCK (ENOMEM otherwise), - * and their size against the client and device limits of + * The size of the object counts against the client and device limits of * drm_asahi_params_global::client_memory_limit and - * drm_asahi_params_global::memory_limit (ENOMEM). They are never released by - * memory-pressure reclaim. + * drm_asahi_params_global::memory_limit (ENOMEM), as that of a + * DRM_IOCTL_ASAHI_GEM_CREATE object does. The pinned pages are shown in the + * caller's VmPin (mm->pinned_vm) but are not limited by its RLIMIT_MEMLOCK. + * They are never released by memory-pressure reclaim. * * Without DRM_ASAHI_GEM_USERPTR_READ_ONLY, the whole range must be mapped * writable, and not be a shared mapping of a file whose filesystem tracks @@ -2283,10 +2353,12 @@ enum drm_asahi_compute_flags { DRM_ASAHI_COMPUTE_USES_MATRIX = (1L << 16), /** - * @DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS: The command neither copies nor - * resets queries, so it cannot observe timestamps the kernel publishes - * for earlier commands and need not wait for that publication. Requires - * DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS. + * @DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS: The command reads and writes no + * timestamp or availability word whose host publication by the kernel + * is still pending for an earlier command, so it need not wait for that + * publication. The command may copy or reset queries whose words are + * all already published, or were never bound for host timestamps. + * Requires DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS. */ DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS = (1L << 17), diff --git a/include/uapi/linux/apple-sep.h b/include/uapi/linux/apple-sep.h index 2b949a8c895974..2c7ef1f6941a2b 100644 --- a/include/uapi/linux/apple-sep.h +++ b/include/uapi/linux/apple-sep.h @@ -207,9 +207,14 @@ struct sep_bio_lockout { #define SEP_BIO_LOCKOUT_STATE _IOR(SEP_BIO_IOC_MAGIC, 0x0e, struct sep_bio_lockout) /* * Ends a lockout. Call it only once the user's password has been verified: - * the password is used once to unwrap the Linux-owned FV re-arm record and is - * wiped after the request. Needs CAP_SYS_ADMIN. Without a lockout it clears - * the failed attempts (see SEP_BIO_LOCKOUT_FLAG_EVERY_PASSWORD). + * the kernel does not check the password. 'secret' is copied in and wiped + * after the request without being used; the enclave's lockout is ended with + * the stored secret of the configured user's key bag. The failed attempts, + * the lockout and the wait for the first password since boot + * (SEP_BIO_REQUIRE_PASSWORD) are kept once for the whole machine, not per + * account, and one call clears them for every enrolled finger. Needs + * CAP_SYS_ADMIN. Without a lockout it clears the failed attempts (see + * SEP_BIO_LOCKOUT_FLAG_EVERY_PASSWORD). */ #define SEP_BIO_REARM_SECRET_MAX 1024 struct sep_bio_rearm { @@ -301,8 +306,10 @@ struct sep_bio_rearm { * install, or an access-control list not satisfied), EACCES when the touch * did not match (or Touch ID is locked out), ETIMEDOUT when no finger came, * ENODEV while the key store or Touch ID is not up, EOPNOTSUPP for a - * reserved policy, ECANCELED after SEP_KEY_CANCEL, EIO for any other - * enclave failure. + * reserved policy, ECANCELED after SEP_KEY_CANCEL, EBUSY when a Touch ID + * verify or enrolment on /dev/sep-bio wants the sensor during the wait (try + * again later, backing off: a verify such as a lock screen's can stay open + * for a long time), EIO for any other enclave failure. */ #define SEP_KEY_IFACE_VERSION 4 #define SEP_KEY_FEATURE_CANCEL 0x1 diff --git a/kernel/sched/core.c b/kernel/sched/core.c index c481404713aaa5..2b30a9901e0c2d 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -1590,6 +1590,17 @@ static unsigned int __maybe_unused sysctl_sched_uclamp_util_max = SCHED_CAPACITY */ unsigned int sysctl_sched_uclamp_util_min_rt_default = SCHED_CAPACITY_SCALE; +/* + * On asymmetric CPU capacity systems, cap SCHED_IDLE tasks (both uclamp.min + * and uclamp.max) at the smallest active asymmetric CPU's capacity so EAS + * keeps them on efficiency cores and schedutil keeps bigger clusters' clocks + * down when they spill over. The cap wins over task and group requests. + * Enabled by default (1); set to 0 to opt out. Symmetric systems are + * unaffected. + */ +static int sysctl_sched_uclamp_util_background = 1; +static unsigned int uclamp_background_cap = SCHED_CAPACITY_SCALE; + /* All clamps are required to be less or equal than these values */ static struct uclamp_se uclamp_default[UCLAMP_CNT]; @@ -1744,7 +1755,17 @@ uclamp_eff_get(struct task_struct *p, enum uclamp_id clamp_id) /* System default restrictions always apply */ if (unlikely(uc_req.value > uc_max.value)) - return uc_max; + uc_req = uc_max; + + if (sched_asym_cpucap_active() && + unlikely(p->policy == SCHED_IDLE) && + !rt_or_dl_task(p) && + READ_ONCE(sysctl_sched_uclamp_util_background)) { + unsigned int bg = READ_ONCE(uclamp_background_cap); + + if (uc_req.value > bg) + uclamp_se_set(&uc_req, bg, false); + } return uc_req; } @@ -2041,6 +2062,16 @@ uclamp_update_active_tasks(struct cgroup_subsys_state *css) static void cpu_util_update_eff(struct cgroup_subsys_state *css); #endif +void uclamp_update_background_cap(unsigned int cap) +{ + lockdep_assert_held(&sched_domains_mutex); + + WRITE_ONCE(uclamp_background_cap, cap); + if (cap < SCHED_CAPACITY_SCALE && + READ_ONCE(sysctl_sched_uclamp_util_background)) + sched_uclamp_enable_cpuslocked(); +} + #ifdef CONFIG_SYSCTL #ifdef CONFIG_UCLAMP_TASK_GROUP static void uclamp_update_root_tg(void) @@ -2146,6 +2177,43 @@ static int sysctl_sched_uclamp_handler(const struct ctl_table *table, int write, sysctl_sched_uclamp_util_min_rt_default = old_min_rt; return result; } + +static int sysctl_sched_uclamp_background_handler(const struct ctl_table *table, + int write, void *buffer, + size_t *lenp, loff_t *ppos) +{ + int val = READ_ONCE(sysctl_sched_uclamp_util_background); + const struct ctl_table t = { + .procname = table->procname, + .data = &val, + .maxlen = sizeof(val), + .extra1 = table->extra1, + .extra2 = table->extra2, + }; + int result; + + if (write && !capable(CAP_SYS_ADMIN)) + return -EPERM; + + result = proc_dointvec_minmax(&t, write, buffer, lenp, ppos); + if (result || !write) + return result; + + /* + * Tasks pick up the new setting at their next enqueue; a CPU-bound + * task that never sleeps keeps its previous effective clamp until then. + */ + cpus_read_lock(); + sched_domains_mutex_lock(); + WRITE_ONCE(sysctl_sched_uclamp_util_background, val); + if (val && sched_asym_cpucap_active() && + uclamp_background_cap < SCHED_CAPACITY_SCALE) + sched_uclamp_enable_cpuslocked(); + sched_domains_mutex_unlock(); + cpus_read_unlock(); + + return 0; +} #endif /* CONFIG_SYSCTL */ static void uclamp_fork(struct task_struct *p) @@ -4666,6 +4734,8 @@ static void __sched_fork(u64 clone_flags, struct task_struct *p) p->se.sum_exec_runtime = 0; p->misfit_runtime = 0; p->se.prev_sum_exec_runtime = 0; + p->se.prev_sleep_sum_runtime = 0; + p->se.burst_avg = 0; p->se.nr_migrations = 0; p->se.vruntime = 0; p->se.vlag = 0; @@ -4874,6 +4944,15 @@ static const struct ctl_table sched_core_sysctls[] = { .mode = 0644, .proc_handler = sysctl_sched_uclamp_handler, }, + { + .procname = "sched_util_clamp_background", + .data = NULL, + .maxlen = sizeof(int), + .mode = 0644, + .proc_handler = sysctl_sched_uclamp_background_handler, + .extra1 = SYSCTL_ZERO, + .extra2 = SYSCTL_ONE, + }, #endif /* CONFIG_UCLAMP_TASK */ #ifdef CONFIG_NUMA_BALANCING { diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index 5c8f84186e2cc5..95eb408358bb67 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -8414,6 +8414,15 @@ static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags) return true; } +/* Account the run time since @p last slept, as it goes to sleep again. */ +static inline void update_burst_avg(struct task_struct *p) +{ + u64 burst = p->se.sum_exec_runtime - p->se.prev_sleep_sum_runtime; + + p->se.prev_sleep_sum_runtime = p->se.sum_exec_runtime; + update_avg(&p->se.burst_avg, burst); +} + /* * The dequeue_task method is called before nr_running is * decreased. We remove the task from the rbtree and @@ -8421,16 +8430,29 @@ static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags) */ static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) { + bool sleep = (flags & (DEQUEUE_SLEEP | DEQUEUE_DELAYED)) == DEQUEUE_SLEEP; + if (task_is_throttled(p)) { dequeue_throttled_task(p, flags); + if (sleep) + update_burst_avg(p); return true; } if (!p->se.sched_delayed) util_est_dequeue(&rq->cfs, p); - if (!__dequeue_task(rq, p, flags)) + /* + * After the dequeue, which updated sum_exec_runtime. Without + * DEQUEUE_DELAYED, @p is the task going to sleep and stays valid. + */ + if (!__dequeue_task(rq, p, flags)) { + if (sleep) + update_burst_avg(p); return false; + } + if (sleep) + update_burst_avg(p); /* * Must not reference @p after __dequeue_task(DEQUEUE_DELAYED). @@ -9916,6 +9938,100 @@ static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu) return target; } +/* + * Wake @p on @cpu, the waking CPU, rather than on an idle CPU, when @p and the + * waker both run only briefly between sleeps and the waker is alone on @cpu. + * + * Such a pair takes turns: one wakes the other and soon sleeps, as in a pipe + * or futex ping-pong, or a thread waking the thread that joins it. On an idle + * CPU every turn costs an IPI and the wake-up of a sleeping core, several + * microseconds on Apple cores, whose WFI lets the hardware power them down, + * and each CPU stays so lightly loaded that schedutil keeps the cluster at a + * low clock. On the waking CPU the wakee runs as soon as the waker sleeps, + * and the pair keeps one CPU busy at a high clock. + * + * Only brief runs qualify, so a task that keeps running after a wake-up does + * not hold up its wakee for longer than that; and only a waker alone on its + * CPU, so at most one wakee is stacked on it. Tasks that wake many others are + * spread by wake_wide() before this is considered. + */ +static bool wake_short_local(struct task_struct *p, int cpu) +{ + u64 limit = sysctl_sched_migration_cost / 8; + struct task_struct *waker = current; + struct rq *rq = cpu_rq(cpu); + struct rq_flags rf; + bool brief = false; + + if (!in_task() || waker->sched_class != &fair_sched_class) + return false; + if (p->se.burst_avg > limit || waker->se.burst_avg > limit) + return false; + if (sched_asym_cpucap_active() && !task_fits_cpu(p, cpu)) + return false; + + /* + * The wakeup path has IRQs disabled and holds p->pi_lock. Skip this + * heuristic if the local rq lock is already held or contended. + */ + if (!raw_spin_rq_trylock(rq)) + return false; + rq_pin_lock(rq, &rf); + + if (rq->nr_running - cfs_h_nr_delayed(rq) == 1 && + task_current_donor(rq, waker) && + sched_cpu_cookie_match(rq, p)) { + u64 burst = waker->se.sum_exec_runtime - waker->se.prev_sleep_sum_runtime; + s64 delta; + + update_rq_clock(rq); + delta = rq_clock_task(rq) - waker->se.exec_start; + if (delta > 0) + burst += delta; + brief = burst <= limit; + } + rq_unlock(rq, &rf); + + return brief; +} + +/* + * Returns an idle CPU sharing the last-level cache with @cpu, the CPU creating + * the thread @p, or -1. + * + * Fork balancing otherwise starts @p in the idlest group of the widest domain, + * which on a system of several clusters is usually another cluster: the + * thread then starts on a core of a cold, often clocked-down cluster, misses + * in a cache that does not hold its parent's data, and the wake-ups between + * it and its parent cross clusters. A thread that runs for long is spread by + * load balancing anyway; most short-lived threads are done before then. + * + * A new process gets the same start: most new processes exec at once, and + * exec balancing still places the program they run in the idlest group; + * until then the child shares its parent's pages and cache. + */ +static int fork_local_idle_cpu(struct sched_domain *sd, + struct task_struct *p, int cpu) +{ + struct sched_domain *llc_sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); + int i; + + if (!llc_sd || !(llc_sd->flags & SD_BALANCE_FORK)) + return -1; + for_each_cpu(i, sched_domain_span(llc_sd)) { + if (i == cpu || !cpumask_test_cpu(i, sched_domain_span(sd)) || + !cpumask_test_cpu(i, p->cpus_ptr)) + continue; + if (!sched_core_cookie_match(cpu_rq(i), p)) + continue; + if (sched_asym_cpucap_active() && !task_fits_cpu(p, i)) + continue; + if (choose_idle_cpu(i, p)) + return i; + } + return -1; +} + /* * select_task_rq_fair: Select target runqueue for the waking task in domains * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE, @@ -9956,6 +10072,11 @@ select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags) } want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr); + + /* Preserve a placement selected by EAS above. */ + if (sched_feat(WAKE_SHORT_LOCAL) && want_affine && + wake_short_local(p, cpu)) + return cpu; } for_each_domain(cpu, tmp) { @@ -9984,8 +10105,15 @@ select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags) } /* Slow path */ - if (unlikely(sd)) + if (unlikely(sd)) { + if (sched_feat(FORK_LOCAL) && (wake_flags & WF_FORK) && p->mm) { + int i = fork_local_idle_cpu(sd, p, cpu); + + if (i >= 0) + return i; + } return sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag); + } /* Fast path */ if (wake_flags & WF_TTWU) @@ -15653,6 +15781,7 @@ static void switched_to_fair(struct rq *rq, struct task_struct *p) WARN_ON_ONCE(p->se.sched_delayed); attach_task_cfs_rq(p); + p->se.prev_sleep_sum_runtime = p->se.sum_exec_runtime; set_task_max_allowed_capacity(p); diff --git a/kernel/sched/features.h b/kernel/sched/features.h index 07132f33d1e4a3..a6def9a19c001e 100644 --- a/kernel/sched/features.h +++ b/kernel/sched/features.h @@ -94,6 +94,20 @@ SCHED_FEAT(TTWU_QUEUE, true) */ SCHED_FEAT(SIS_UTIL, true) +/* + * Wake a task that runs only briefly between sleeps on the waking CPU when + * the waker also runs briefly and is alone there, instead of on an idle CPU. + * See wake_short_local(). + */ +SCHED_FEAT(WAKE_SHORT_LOCAL, true) + +/* + * Start a new thread or process on an idle CPU that shares the last-level + * cache with the task creating it, before looking further. See + * fork_local_idle_cpu(). + */ +SCHED_FEAT(FORK_LOCAL, true) + /* * Issue a WARN when we do multiple update_rq_clock() calls * in a single rq->lock section. Default disabled because the diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index 9dd8c6e6f73b5c..78640a29b0fbc2 100644 --- a/kernel/sched/sched.h +++ b/kernel/sched/sched.h @@ -3691,6 +3691,14 @@ static inline void sched_uclamp_enable(void) static_branch_enable(&sched_uclamp_used); } +static inline void sched_uclamp_enable_cpuslocked(void) +{ + if (!uclamp_is_used()) + static_branch_enable_cpuslocked(&sched_uclamp_used); +} + +void uclamp_update_background_cap(unsigned int cap); + static inline unsigned long uclamp_rq_get(struct rq *rq, enum uclamp_id clamp_id) { @@ -3771,6 +3779,8 @@ static inline bool uclamp_is_used(void) } static inline void sched_uclamp_enable(void) {} +static inline void sched_uclamp_enable_cpuslocked(void) {} +static inline void uclamp_update_background_cap(unsigned int cap) {} static inline unsigned long uclamp_rq_get(struct rq *rq, enum uclamp_id clamp_id) diff --git a/kernel/sched/topology.c b/kernel/sched/topology.c index 3dab0253976fb4..f3f702d7b23760 100644 --- a/kernel/sched/topology.c +++ b/kernel/sched/topology.c @@ -3279,6 +3279,24 @@ void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms) kfree(doms); } +static void sched_uclamp_background_update(void) +{ + unsigned long cap = SCHED_CAPACITY_SCALE; + int cpu; + + if (!IS_ENABLED(CONFIG_UCLAMP_TASK)) + return; + + if (sched_asym_cpucap_active()) { + for_each_cpu(cpu, cpu_active_mask) { + if (rcu_access_pointer(per_cpu(sd_asym_cpucapacity, cpu))) + cap = min(cap, arch_scale_cpu_capacity(cpu)); + } + } + + uclamp_update_background_cap(cap); +} + /* * Set up scheduler domains and groups. For now this just excludes isolated * CPUs, but could be used to exclude other special cases in the future. @@ -3301,8 +3319,10 @@ int __init sched_init_domains(const struct cpumask *cpu_map) doms_cur = &fallback_doms; cpumask_and(doms_cur[0], cpu_map, housekeeping_cpumask(HK_TYPE_DOMAIN)); err = build_sched_domains(doms_cur[0], NULL, &multi_llcs); - if (!err) + if (!err) { sched_cache_set(multi_llcs); + sched_uclamp_background_update(); + } return err; } @@ -3460,6 +3480,7 @@ static void partition_sched_domains_locked(int ndoms_new, cpumask_var_t doms_new ; } sched_cache_set(has_multi_llcs); + sched_uclamp_background_update(); #if defined(CONFIG_ENERGY_MODEL) && defined(CONFIG_CPU_FREQ_GOV_SCHEDUTIL) /* Build perf domains: */ diff --git a/rust/kernel/drm/gpuvm/mod.rs b/rust/kernel/drm/gpuvm/mod.rs index 66adaf99e0859d..7f834933311c02 100644 --- a/rust/kernel/drm/gpuvm/mod.rs +++ b/rust/kernel/drm/gpuvm/mod.rs @@ -731,6 +731,43 @@ pub struct GpuVmInnerGuard<'a, T: DriverGpuVm> { } impl GpuVmInnerGuard<'_, T> { + /// Whether `addr..addr + range` lies strictly inside a single driver GPUVA satisfying + /// `matches` (so unmapping it would split that GPUVA into two surviving pieces, net +1 node). + pub fn range_strictly_inside_va( + &self, + addr: u64, + range: u64, + matches: impl FnOnce(&GpuVa) -> bool, + ) -> bool { + let Some(end) = addr.checked_add(range) else { + return false; + }; + if range == 0 { + return false; + } + // SAFETY: This guard owns the VM's shared reservation, serializing VA tree mutation. + let raw = unsafe { bindings::drm_gpuva_find_first(self.gpuvm.as_raw(), addr, range) }; + if raw.is_null() { + return false; + } + // SAFETY: `raw` stays linked and alive while this guard is held. + let va = unsafe { &*raw }; + if va.gem.obj.is_null() || va.vm_bo.is_null() { + return false; + } + if !va + .va + .addr + .checked_add(va.va.range) + .is_some_and(|va_end| va.va.addr < addr && end < va_end) + { + return false; + } + // SAFETY: Driver-owned mappings are `GpuVa`; the kernel cutout has no GEM object + // and was skipped above. + matches(unsafe { GpuVa::::from_raw(raw) }) + } + /// Run immediate-mode unmap steps without allocating an exec context. /// /// # Safety diff --git a/rust/kernel/of.rs b/rust/kernel/of.rs index cacbc55c28dc5c..04f04496633c75 100644 --- a/rust/kernel/of.rs +++ b/rust/kernel/of.rs @@ -536,21 +536,6 @@ pub fn stdout() -> Option { } } -#[allow(unused_variables)] -/// Looks up a node in the device tree by phandle. -pub fn find_node_by_phandle(handle: PHandle) -> Option { - #[cfg(not(CONFIG_OF))] - { - None - } - #[cfg(CONFIG_OF)] - // SAFETY: bindings::of_find_node_by_phandle always returns a valid pointer or NULL - unsafe { - #[allow(dead_code)] - Node::from_raw(bindings::of_find_node_by_phandle(handle)) - } -} - impl Clone for Node { fn clone(&self) -> Node { // SAFETY: `raw_node` is valid and non-NULL per the type invariant, diff --git a/rust/kernel/soc/apple/mailbox.rs b/rust/kernel/soc/apple/mailbox.rs index e0c4be586801d7..9d39fc87262948 100644 --- a/rust/kernel/soc/apple/mailbox.rs +++ b/rust/kernel/soc/apple/mailbox.rs @@ -102,6 +102,12 @@ impl Mailbox { to_result(unsafe { bindings::apple_mbox_send(self.mbox, msg, atomic) }) } + /// Whether the firmware has room for another message (its receive FIFO isn't full). + pub fn send_ready(&self) -> bool { + // SAFETY: Calling the c function, `mbox` is a valid pointer + unsafe { bindings::apple_mbox_send_ready(self.mbox) } + } + /// Sets bit 0 of the receive control word, for firmware that powers itself down. pub fn set_recv_enabled(&self, enabled: bool) { // SAFETY: Calling the c function, `mbox` is a valid pointer diff --git a/rust/kernel/soc/apple/rtkit.rs b/rust/kernel/soc/apple/rtkit.rs index f6ae2c60da979c..22d0bf9bbcfc3e 100644 --- a/rust/kernel/soc/apple/rtkit.rs +++ b/rust/kernel/soc/apple/rtkit.rs @@ -368,6 +368,14 @@ impl RtKit { to_result(unsafe { bindings::apple_rtkit_wake(self.rtk) }) } + /// Starts a coprocessor whose firmware may acknowledge IOP power on by itself once it has + /// reported in: takes that acknowledgment if it comes within `self_ack_ms`, and asks for IOP + /// power as [`Self::wake`] does otherwise. + pub fn boot_or_wake(self: Pin<&mut Self>, self_ack_ms: u32) -> Result { + // SAFETY: `rtk` is valid per the type invariant. + to_result(unsafe { bindings::apple_rtkit_boot_or_wake(self.rtk, self_ack_ms) }) + } + /// Waits for the RTKit coprocessor to finish booting. pub fn boot(self: Pin<&mut Self>) -> Result { // SAFETY: `rtk` is valid per the type invariant. @@ -380,13 +388,6 @@ impl RtKit { to_result(unsafe { bindings::apple_rtkit_idle(self.rtk) }) } - /// Turns the mailbox off for a coprocessor that has acknowledged idle, before its run bit and - /// power state go. Only [`Self::warm_restart`] follows this. - pub fn mailbox_off(self: Pin<&mut Self>) { - // SAFETY: `rtk` is valid per the type invariant. - unsafe { bindings::apple_rtkit_mailbox_off(self.rtk) }; - } - /// Prepares for HELLO from firmware restarting warm, which keeps its buffers and rings. The /// caller then sets the run bit and calls [`Self::boot`]. pub fn warm_restart(self: Pin<&mut Self>) -> Result { diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 3e4d97583073ab..c2c63df64fc637 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -484,7 +484,21 @@ impl OwnedQueue { Self::ordered(name, bindings::wq_flags_WQ_MEM_RECLAIM) } + /// Allocates an ordered high-priority workqueue named `name` that may be used on the memory + /// reclaim path (`WQ_MEM_RECLAIM | WQ_HIGHPRI`). + pub fn new_ordered_highpri_reclaim(name: &CStr) -> Result { + Self::ordered_flags( + name, + bindings::wq_flags_WQ_MEM_RECLAIM | bindings::wq_flags_WQ_HIGHPRI, + true, + ) + } + fn ordered(name: &CStr, flags: u32) -> Result { + Self::ordered_flags(name, flags, false) + } + + fn ordered_flags(name: &CStr, flags: u32, highpri: bool) -> Result { // SAFETY: `name` is a valid NUL-terminated string; the C side copies it. let ptr = unsafe { bindings::alloc_ordered_workqueue(name.as_char_ptr(), flags) }; @@ -493,17 +507,10 @@ impl OwnedQueue { queue: NonNull::new(ptr).ok_or(ENOMEM)?, ordered: true, unbound: true, - highpri: false, + highpri, }) } - /// Allocates an unbound workqueue named `name`, with high-priority workers if `highpri`. - /// - /// Its work items run concurrently, each in the affinity pod of the CPU it is queued for. - pub fn new_unbound(name: &CStr, highpri: bool) -> Result { - Self::flags(name, true, highpri, 0) - } - /// Allocates an unbound workqueue named `name` that may be used on the memory reclaim path /// (`WQ_MEM_RECLAIM`), with high-priority workers if `highpri`. pub fn new_unbound_reclaim(name: &CStr, highpri: bool) -> Result { diff --git a/rust/macros/versions.rs b/rust/macros/versions.rs index b13a5d55c0e17b..21a6d5985332cc 100644 --- a/rust/macros/versions.rs +++ b/rust/macros/versions.rs @@ -93,7 +93,7 @@ static AGX_VERSIONS: VersionConfig = VersionConfig { fields: &["G", "V"], enums: &[ &["G13", "G14", "G14X"], - &["V12_3", "V12_4", "V13_0B4", "V13_2", "V13_3", "V13_5"], + &["V12_3", "V12_4", "V13_0B4", "V13_2", "V13_3", "V13_5", "V27_2"], ], versions: &[ &["G13", "V12_3"], @@ -276,8 +276,11 @@ fn filter_versions( } pub(crate) fn versions(attr: TokenStream, item: TokenStream) -> TokenStream { - let config = match attr.to_string().as_str() { - "AGX" => &AGX_VERSIONS, + // AGX_V27_2 is AGX plus G14/V27_2: only the firmware 27.2 root and hardware-data layouts + // are instantiated for that version. + let group = attr.to_string(); + let config = match group.as_str() { + "AGX" | "AGX_V27_2" => &AGX_VERSIONS, _ => panic!("Unknown version group {}", attr), }; @@ -321,7 +324,8 @@ pub(crate) fn versions(attr: TokenStream, item: TokenStream) -> TokenStream { body.extend(it); - for ver in config.versions { + let candidate = (group == "AGX_V27_2").then_some(&["G14", "V27_2"][..]); + for ver in config.versions.iter().copied().chain(candidate) { let tag = ver.join(""); let mut ver_num = Vec::::new(); for (i, comp) in ver.iter().enumerate() { diff --git a/scripts/checkpatch.pl b/scripts/checkpatch.pl index 8a7787d228a63d..c9840f5219c2a9 100755 --- a/scripts/checkpatch.pl +++ b/scripts/checkpatch.pl @@ -655,7 +655,6 @@ sub hash_show_words { Reviewed-by:| Reported-by:| Suggested-by:| - Assisted-by:| To:| Cc: )}; @@ -3124,16 +3123,6 @@ sub process { } } - # Assisted-by uses a free-form value (e.g. "LLM"), not an - # email address, so skip the email format checks below. - if ($sign_off =~ /^Assisted-by:/i) { - if ($email =~ /^\s*$/) { - WARN("BAD_SIGN_OFF", - "Assisted-by requires a value\n" . $herecurr); - } - next; - } - my ($email_name, $name_comment, $email_address, $comment) = parse_email($email); my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment)); if ($suggested_email eq "") { diff --git a/scripts/dtc/apple-dart-pd-check-test.py b/scripts/dtc/apple-dart-pd-check-test.py index adab86a6e6657b..00737ba3444cf9 100755 --- a/scripts/dtc/apple-dart-pd-check-test.py +++ b/scripts/dtc/apple-dart-pd-check-test.py @@ -174,6 +174,49 @@ def test_disabled_dart_of_an_enabled_user_fails(self): self.assertIn("t8112-j413 /soc/iommu@5000 dart_x apple,t8110-dart disabled: " "power domain /soc/power-controller@3000 is disabled (new)", result.stdout) + ROUTER = ('acio@5000 { compatible = "apple,t8103-usb4-acio"; %s ' + '#address-cells = <1>; #size-cells = <0>; ' + 'dart_x: iommu@a00 { compatible = "apple,t8110-dart"; #iommu-cells = <1>; }; ' + 'nhi@b00 { iommus = <&dart_x 0>; }; };') + + def test_dart_inside_a_powered_device_is_exempt(self): + # A USB4 router's DART: its driver populates it after powering its domains. + router = self.ROUTER % "power-domains = <&ps_x>;" + self.dtb(self.head, "t8112-j413", dts("j413", "t8112", DOMAIN, GAP, router)) + result = self.check() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("new: 0", result.stderr) + report = self.check("--report") + self.assertIn("/soc/acio@5000/iommu@a00 dart_x apple,t8110-dart okay: " + "exempt (inside /soc/acio@5000)", report.stdout) + + def test_dart_inside_a_device_without_domains_fails(self): + router = self.ROUTER % "" + self.dtb(self.head, "t8112-j413", dts("j413", "t8112", DOMAIN, GAP, router)) + result = self.check() + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("/soc/acio@5000/iommu@a00 dart_x apple,t8110-dart okay: " + "no power-domains (new)", result.stdout) + + def test_dart_inside_a_device_on_a_disabled_domain_fails(self): + disabled = DOMAIN.replace("{", '{ status = "disabled";') + router = self.ROUTER % "power-domains = <&ps_x>;" + self.dtb(self.head, "t8112-j413", dts("j413", "t8112", disabled, GAP, router)) + result = self.check() + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("/soc/acio@5000/iommu@a00 dart_x apple,t8110-dart okay: " + "parent's power domain /soc/power-controller@3000 is disabled (new)", + result.stdout) + + def test_dart_inside_a_powered_bus_is_not_exempt(self): + # A simple-bus is populated by platform code, not by a driver. + bus = self.ROUTER.replace('"apple,t8103-usb4-acio"', '"simple-bus"') % \ + "power-domains = <&ps_x>;" + self.dtb(self.head, "t8112-j413", dts("j413", "t8112", DOMAIN, GAP, bus)) + result = self.check() + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("no power-domains (new)", result.stdout) + def test_without_baseline_every_gap_fails(self): result = subprocess.run([sys.executable, str(CHECKER), "--dtb-dir", str(self.head)], text=True, capture_output=True) diff --git a/scripts/dtc/apple-dart-pd-check.py b/scripts/dtc/apple-dart-pd-check.py index 59aa7e64947a03..18d50c87985f1f 100755 --- a/scripts/dtc/apple-dart-pd-check.py +++ b/scripts/dtc/apple-dart-pd-check.py @@ -14,7 +14,11 @@ block is off as a whole, which is consistent. Exempt: the DARTs of the SEP and of the AOP. Those coprocessors run from -before the handoff on states the AP never switches off. +before the handoff on states the AP never switches off. Also exempt: a DART +that is a child of a device node (not a bus) with power-domains of its own, +such as a USB4 router's. Its parent's driver populates it after powering the +parent's domains, so it is covered by them; the parent's domains must then be +enabled. Install python3-libfdt (or pylibfdt) to read DTBs. Labels are shown when the DTBs were built with DTC_FLAGS=-@. @@ -36,6 +40,7 @@ DART = re.compile(r"apple,.*dart") SOC = re.compile(r"apple,[st]\d{4}$") +BUSES = ("simple-bus", "simple-pm-bus", "simple-mfd", "isa") EXEMPT = ( (re.compile(r"apple,sep$"), "SEP"), (re.compile(r"apple,(t\d+-)?aop$"), "AOP"), @@ -115,6 +120,28 @@ def iommu_cells(offset): consumers.setdefault(phandles[spec[i + 1]], []).append(offset) i += 3 + iommu_cells(phandles[spec[i + 1]]) + def domain_providers(offset): + domains = cells(prop(offset, "power-domains")) + i = 0 + while i < len(domains): + provider = phandles.get(domains[i]) + if provider is None: + break + yield provider + n = cells(prop(provider, "#power-domain-cells")) + i += 1 + (n[0] if n else 0) + + def disabled_domains(offset): + return [nodes[p] for p in domain_providers(offset) if status(p) != "okay"] + + def powered_device(offset): + """A device node (not a bus) with power domains of its own: platform + code does not populate its children, its driver does.""" + compatible = strings(prop(offset, "compatible")) + return (offset != 0 and bool(compatible) and + not any(c in BUSES for c in compatible) and + bool(cells(prop(offset, "power-domains")))) + for offset, path in nodes.items(): compatible = strings(prop(offset, "compatible")) if not any(DART.match(c) for c in compatible): @@ -130,6 +157,13 @@ def iommu_cells(offset): for c in strings(prop(o, "compatible"))] why = [name for pattern, name in EXEMPT if any(pattern.match(c) for c in users)] problem = "exempt (%s)" % why[0] if why else "no power-domains" + parent = offsets[path.rsplit("/", 1)[0] or "/"] + if not why and powered_device(parent): + # The parent device's driver populates this DART once it has + # powered its own domains; it is never probed on its own. + bad = disabled_domains(parent) + problem = ("parent's power domain %s is disabled" % bad[0] if bad else + "exempt (inside %s)" % nodes[parent]) yield path, label, compatible[0], status(offset), problem continue i = 0 diff --git a/scripts/dtc/apple-dt-check.sh b/scripts/dtc/apple-dt-check.sh index 3942cd776c974a..38e8badcb9e46e 100755 --- a/scripts/dtc/apple-dt-check.sh +++ b/scripts/dtc/apple-dt-check.sh @@ -4,39 +4,213 @@ # and fail when HEAD has a warning BASE does not. Also runs dt_binding_check on every binding HEAD # changes. Phandle values in the messages are masked, so renumbering is not a new warning, and so # is the pattern list of a "does not match any of the regexes" message, which grows with every -# vendor prefix the bindings add. A firmware-profile variant (a .dts that includes another board's +# vendor prefix the bindings add. Upstream dtschema's chosen.yaml sets additionalProperties: false, +# so properties documented in in-tree bindings/chosen/*.yaml are subtracted from "chosen: ... +# do(es) not match any of the regexes:" lines emitted by http://devicetree.org/schemas/chosen.yaml# +# while preserving warnings from any other schema, warnings for any undocumented properties, and +# all schema type/value checks. A firmware-profile variant (a .dts that includes another board's # .dts, such as t8122-j613-25g83) is reported under its base board's name, so the base's existing # warnings are not new warnings of the variant; anything the variant adds still is. -# Needs dtschema (dt-validate), clang/lld (LLVM=1), flex, bison. Prints a summary. +# Needs dtschema (dt-validate), clang/lld (LLVM=1), flex, bison, python3. Prints a summary. set -u BASE=$1 HEAD=$2 W=$3 export ARCH=arm64 LLVM=1 +# sort and comm must agree on the order: some UTF-8 locales collate these lines differently. +export LC_ALL=C mkdir -p "$W" -warnings() { # rev tag - local t=$W/src-$2 o=$W/out-$2 - git worktree add -q --detach "$t" "$1" || return 1 - make -s -C "$t" O="$o" defconfig >/dev/null || return 1 - local dtbs; dtbs=$(cd "$t/arch/arm64/boot/dts" && ls apple/*.dts | sed 's/dts$/dtb/') - make -C "$t" O="$o" -j"$(nproc)" CHECK_DTBS=y $dtbs > "$W/$2.log" 2>&1 - local rc=$? +filter_documented_chosen() { # chosen_bindings_dir + python3 -c ' +import glob, os, re, sys + +CHOSEN_SCHEMA_ID = "http://devicetree.org/schemas/chosen.yaml#" + +def get_yaml_loader(): + try: + import yaml + return yaml.safe_load + except ImportError: + pass + try: + from ruamel.yaml import YAML + loader = YAML(typ="safe") + return loader.load + except ImportError: + sys.stderr.write( + "apple-dt-check.sh: neither PyYAML nor ruamel.yaml is available " + "to parse bindings/chosen/*.yaml\n" + ) + sys.exit(1) + +load_yaml = get_yaml_loader() +chosen_dir = sys.argv[1] +documented = set() +for path in sorted(glob.glob(os.path.join(chosen_dir, "*.yaml"))): + with open(path, encoding="utf-8") as f: + doc = load_yaml(f) + if not isinstance(doc, dict): + continue + props = doc.get("properties") + if not isinstance(props, dict): + continue + for key, val in props.items(): + if isinstance(key, str) and not key.startswith("$") and val is not False: + documented.add(key) + +pat = re.compile( + r"^(?P[^\s\n][^\n]*\.dtb: chosen: )" + r"(?P\x27[^\x27]+\x27(?:, \x27[^\x27]+\x27)*)" + r" (?:does|do) not match any of the regexes:(?P.*)$" +) +inline_schema_re = re.compile(r"\s+from schema \$id:\s*(\S+)\s*$") +hint_line_re = re.compile(r"^[ \t]+hint: ") +schema_line_re = re.compile(r"^[ \t]+from schema \$id:\s*(\S+)\s*$") + +lines = sys.stdin.readlines() +i = 0 +n = len(lines) +while i < n: + raw = lines[i] + line = raw.rstrip("\r\n") + m = pat.match(line) + if not m: + sys.stdout.write(raw) + i += 1 + continue + + cont = [] + schema_id = None + m_inline = inline_schema_re.search(m.group("tail")) + if m_inline: + schema_id = m_inline.group(1) + i += 1 + else: + j = i + 1 + while j < n and hint_line_re.match(lines[j]): + cont.append(lines[j]) + j += 1 + if j < n: + m_schema = schema_line_re.match(lines[j].rstrip("\r\n")) + if m_schema: + schema_id = m_schema.group(1) + cont.append(lines[j]) + j += 1 + i = j + + if schema_id != CHOSEN_SCHEMA_ID: + sys.stdout.write(raw) + for c in cont: + sys.stdout.write(c) + continue + + props = re.findall(r"\x27([^\x27]+)\x27", m.group("props")) + remaining = [p for p in props if p not in documented] + if not remaining: + continue + verb = "does" if len(remaining) == 1 else "do" + joined = ", ".join(f"\x27{p}\x27" for p in remaining) + prefix = m.group("prefix") + tail = m.group("tail") + sys.stdout.write(f"{prefix}{joined} {verb} not match any of the regexes:{tail}\n") + for c in cont: + sys.stdout.write(c) +' "$1" +} +extract_warnings() { # src_dir out_dir log_file out_warn tag + local t=$1 o=$2 log=$3 out=$4 tag=$5 + local filtered=$W/$tag.filtered.log + rm -f "$filtered" "$out" + if ! filter_documented_chosen "$t/Documentation/devicetree/bindings/chosen" < "$log" > "$filtered"; then + rm -f "$filtered" "$out" + echo "apple-dt-check.sh: $tag: failed to filter documented /chosen warnings" >&2 + filter_failed=1 + return 1 + fi local variants; variants=$(cd "$t/arch/arm64/boot/dts" && grep -l '^#include "[^"]*\.dts"' apple/*.dts 2>/dev/null | while read -r v; do sed -nE 's#^\#include "([^"]*)\.dts".*#s|^'"${v%.dts}"'\\.dtb: |apple/\1.dtb: |;#p' "$v" | head -1 done) - grep -E '\.dtb: |[Ww]arning|rror' "$W/$2.log" | grep -v '^ ' | + grep -E '\.dtb: |[Ww]arning|rror' "$filtered" | grep -v '^ ' | sed -E "s#$t/##g; s#$o/##g" | sed -E "s#arch/arm64/boot/dts/##; $variants" | sed -E 's#^apple/#arch/arm64/boot/dts/apple/#' | - perl -pe 's{(\[\[[^:]*?\]\])}{(my $x = $1) =~ s/\d+/N/g; $x}ge; s{b\x27(?:\\.|[^\x27])*\x27}{b\x27N\x27}g; s{( not match any of the regexes): .*}{$1: ...}' | - sort -u > "$W/$2.warn" + perl -pe 's{(\[\[[^:]*?\]\])}{(my $x = $1) =~ s/\d+/N/g; $x}ge; s{(?:^|(?<=[\s\[(=]))b\x27(?:\\.|[^\x27])*\x27}{b\x27N\x27}g; s{( not match any of the regexes): .*}{$1: ...}' | + sort -u > "$out" + local ps=("${PIPESTATUS[@]}") + if [ "${ps[0]}" -gt 1 ] || [ "${ps[1]}" -gt 1 ] || [ "${ps[2]}" -ne 0 ] || [ "${ps[3]}" -ne 0 ] || [ "${ps[4]}" -ne 0 ] || [ "${ps[5]}" -ne 0 ] || [ "${ps[6]}" -ne 0 ]; then + rm -f "$out" + echo "apple-dt-check.sh: $tag: warning extraction pipeline failed (status: ${ps[*]})" >&2 + filter_failed=1 + return 1 + fi + # One line per undocumented property, so documenting one of a node's properties does not + # turn that node's remaining ones into a "new" warning. + python3 -c ' +import re, sys +pat = re.compile(r"^(.*?: )(\x27[^\x27]+\x27(?:, \x27[^\x27]+\x27)*) do(?:es)? not match any of the regexes:(.*)$") +for line in open(sys.argv[1]): + line = line.rstrip("\n") + m = pat.match(line) + if not m: + print(line) + continue + prefix, props, tail = m.groups() + for prop in re.findall(r"\x27[^\x27]+\x27", props): + print(prefix + prop + " does not match any of the regexes:" + tail) +' "$out" | sort -u > "$out.split" + local sp=("${PIPESTATUS[@]}") + if [ "${sp[0]}" -ne 0 ] || [ "${sp[1]}" -ne 0 ]; then + rm -f "$out" "$out.split" + echo "apple-dt-check.sh: $tag: splitting property warnings failed" >&2 + filter_failed=1 + return 1 + fi + mv "$out.split" "$out" +} +warnings() { # rev tag + local t=$W/src-$2 o=$W/out-$2 + filter_failed=0 + rm -f "$W/$2.warn" "$W/$2.filtered.log" + git worktree add -q --detach "$t" "$1" || return 1 + make -s -C "$t" O="$o" defconfig >/dev/null || return 1 + local dtbs; dtbs=$(cd "$t/arch/arm64/boot/dts" && ls apple/*.dts | sed 's/dts$/dtb/') + make -C "$t" O="$o" -j"$(nproc)" -Otarget CHECK_DTBS=y $dtbs > "$W/$2.log" 2>&1 + local rc=$? + extract_warnings "$t" "$o" "$W/$2.log" "$W/$2.warn" "$2" || return 1 echo "$2: make rc=$rc, $(wc -l < "$W/$2.warn") warning lines, $(echo $dtbs | wc -w) DTBs" return $rc } -warnings "$BASE" base || echo "base build failed (its warnings still count)" +cleanup() { + git worktree remove --force "$W/src-base" 2>/dev/null || true +} +trap cleanup EXIT +fail=0 +filter_failed=0 +warnings "$BASE" base; brc=$? +if [ "$filter_failed" -ne 0 ]; then + echo "apple-dt-check.sh: BASE $BASE warning filtering failed" >&2 + exit 1 +fi +if [ "$brc" -ne 0 ]; then + echo "base build failed (its warnings still count)" +fi +if [ ! -f "$W/base.warn" ]; then + # No list to compare against: every HEAD warning counts as new. + echo "BASE $BASE could not be checked out or configured" + : > "$W/base.warn" + fail=1 +fi +filter_failed=0 warnings "$HEAD" head; hrc=$? +if [ "$filter_failed" -ne 0 ]; then + echo "apple-dt-check.sh: HEAD $HEAD warning filtering failed" >&2 + exit 1 +fi +if [ ! -f "$W/head.warn" ]; then + echo "apple-dt-check.sh: HEAD $HEAD could not be checked out or configured" >&2 + exit 1 +fi comm -13 "$W/base.warn" "$W/head.warn" > "$W/new.warn" comm -23 "$W/base.warn" "$W/head.warn" > "$W/gone.warn" echo "new warnings: $(wc -l < "$W/new.warn"), removed: $(wc -l < "$W/gone.warn")" -fail=0 [ $hrc = 0 ] || { echo "HEAD device trees do not build"; fail=1; } if [ -s "$W/new.warn" ]; then echo "--- new CHECK_DTBS warnings"; cat "$W/new.warn"; fail=1; fi b=$(git diff --name-only --diff-filter=AM "$BASE" "$HEAD" -- 'Documentation/devicetree/bindings/*.yaml') @@ -48,5 +222,4 @@ for f in $b; do echo "--- binding check failed: $f"; cat "$W/binding.log"; fail=1 fi done -git worktree remove --force "$W/src-base" 2>/dev/null; true exit $fail diff --git a/scripts/dtc/apple-sibling-drift-test.py b/scripts/dtc/apple-sibling-drift-test.py new file mode 100755 index 00000000000000..7aa003876fb591 --- /dev/null +++ b/scripts/dtc/apple-sibling-drift-test.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Exercise apple-sibling-drift.py with synthetic DTS fixtures; needs dtc + pylibfdt.""" + +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +CHECKER = Path(__file__).with_name("apple-sibling-drift.py") + + +def dts(board, *props): + return '''/dts-v1/; + / { compatible = "apple,%s", "apple,t8112", "apple,arm-platform"; + #address-cells = <1>; #size-cells = <0>; + dcp@1000 { reg = <0x1000>; %s }; + }; + ''' % (board, " ".join(props)) + + +class SiblingDriftTest(unittest.TestCase): + def setUp(self): + self.work = tempfile.TemporaryDirectory(prefix="drift-test-", dir=Path.cwd()) + self.addCleanup(self.work.cleanup) + self.root = Path(self.work.name) + self.base = self.root / "base" + self.head = self.root / "head" + self.base.mkdir() + self.head.mkdir() + # The J473's HDMI GPIO is right drift: the baseline has it. + for directory in (self.base, self.head): + self.dtb(directory, "t8112-j413", dts("j413", "shared;")) + self.dtb(directory, "t8112-j473", dts("j473", "shared;", "hdmi-gpios = <1>;")) + + def dtb(self, directory, name, source): + path = self.root / (name + ".dts") + path.write_text(source) + subprocess.run(["dtc", "-q", "-I", "dts", "-O", "dtb", "-o", + str(directory / (name + ".dtb")), str(path)], check=True) + + def check(self, *args): + return subprocess.run([sys.executable, str(CHECKER), "--dtb-dir", str(self.head), + "--baseline-dtb-dir", str(self.base), *args], + text=True, capture_output=True) + + def test_unchanged_is_quiet(self): + result = self.check() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(result.stdout, "") + self.assertIn("drift 1, new 0, resolved 0", result.stderr) + + def test_one_board_fix_warns(self): + self.dtb(self.head, "t8112-j473", + dts("j473", "shared;", "hdmi-gpios = <1>;", "apple,fix;")) + result = self.check() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("t8112 /dcp@1000 apple,fix: only on j473; j413 have the node without it", + result.stdout) + self.assertNotIn("hdmi-gpios", result.stdout) + self.assertEqual(self.check("--strict").returncode, 1) + + def test_fix_on_every_board_is_quiet(self): + self.dtb(self.head, "t8112-j413", dts("j413", "shared;", "apple,fix;")) + self.dtb(self.head, "t8112-j473", + dts("j473", "shared;", "hdmi-gpios = <1>;", "apple,fix;")) + result = self.check("--strict") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(result.stdout, "") + + def test_dropping_a_shared_property_from_one_board_warns(self): + self.dtb(self.head, "t8112-j413", dts("j413")) + result = self.check() + self.assertIn("t8112 /dcp@1000 shared: only on j473; j413", result.stdout) + + def test_resolved_drift_is_counted_and_variants_are_ignored(self): + self.dtb(self.head, "t8112-j413", dts("j413", "shared;", "hdmi-gpios = <1>;")) + self.dtb(self.head, "t8112-j413-fw27", dts("j413", "apple,variant-only;")) + result = self.check("--strict") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("drift 0, new 0, resolved 1", result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/dtc/apple-sibling-drift.py b/scripts/dtc/apple-sibling-drift.py new file mode 100755 index 00000000000000..37d7fea6dfb4cd --- /dev/null +++ b/scripts/dtc/apple-sibling-drift.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Warn when a change gives one board a property its sibling boards lack. + +Boards of one SoC (t8112-j413, t8112-j415, t8112-j473, t8112-j493) share most of +their device tree through the SoC's .dtsi files. A fix written for one Mac and put +in that Mac's .dts leaves its siblings without it, although they have the same +block. For every SoC with two or more boards, this looks at the nodes all of its +boards have and lists each property that only some of them carry ("drift"). + +Much drift is right (a desktop's HDMI port, a laptop's lid), so the existing drift +is the baseline: with --baseline-dtb-dir only drift the change adds is reported, +as a warning that names the boards with and without the property. Drift the change +removes is counted as resolved. Only board trees (-.dtb) are compared; +variants such as t8112-j413-fw27 are left out. --strict makes new drift fail. + +Install python3-libfdt (or pylibfdt) to read DTBs. +""" + +import argparse +from pathlib import Path +import re +import sys + +try: + import libfdt +except ImportError: + sys.exit("apple-sibling-drift: needs python3-libfdt (pylibfdt)") + +BOARD = re.compile(r"^(t\d{4})-(j\d+[a-z]*)\.dtb$") +SKIP_NODES = ("/aliases", "/chosen", "/memory", "/__symbols__", "/__fixups__", + "/__local_fixups__") +SKIP_PROPS = {"status", "phandle", "linux,phandle"} + + +def node_props(path): + fdt = libfdt.Fdt(path.read_bytes()) + nodes = {} + + def walk(offset, name): + props = set() + prop = fdt.first_property_offset(offset, libfdt.QUIET_NOTFOUND) + while prop >= 0: + props.add(fdt.get_property_by_offset(prop).name) + prop = fdt.next_property_offset(prop, libfdt.QUIET_NOTFOUND) + nodes[name] = props + child = fdt.first_subnode(offset, libfdt.QUIET_NOTFOUND) + while child >= 0: + walk(child, name.rstrip("/") + "/" + fdt.get_name(child)) + child = fdt.next_subnode(child, libfdt.QUIET_NOTFOUND) + + walk(0, "/") + return nodes + + +def drift(directory): + socs = {} + for path in sorted(Path(directory).glob("*.dtb")): + match = BOARD.match(path.name) + if match: + socs.setdefault(match.group(1), {})[match.group(2)] = node_props(path) + found = {} + for soc, boards in socs.items(): + if len(boards) < 2: + continue + common = set.intersection(*(set(nodes) for nodes in boards.values())) + for node in common: + if node.startswith(SKIP_NODES): + continue + for prop in set.union(*(boards[b][node] for b in boards)) - SKIP_PROPS: + have = frozenset(b for b in boards if prop in boards[b][node]) + if len(have) < len(boards): + found[(soc, node, prop)] = (have, frozenset(boards)) + return found + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--dtb-dir", required=True) + parser.add_argument("--baseline-dtb-dir") + parser.add_argument("--strict", action="store_true", help="fail on new drift") + parser.add_argument("--report", action="store_true", help="list all drift") + args = parser.parse_args() + + head = drift(args.dtb_dir) + base = drift(args.baseline_dtb_dir) if args.baseline_dtb_dir else {} + new = [] + for key, (have, boards) in sorted(head.items()): + old = base.get(key) + # New when the baseline had no drift here, or fewer boards carried it then. + if args.report or (args.baseline_dtb_dir and (old is None or not have <= old[0])): + new.append((key, have, boards)) + for (soc, node, prop), have, boards in new: + lack = sorted(boards - have) + print(f"::warning title=Sibling drift::{soc} {node} {prop}: only on " + f"{', '.join(sorted(have))}; {', '.join(lack)} have the node without it. " + f"Same block on every board: put it in the shared .dtsi; board-specific: " + f"nothing to do.") + resolved = sum(1 for key in base if key not in head) + print(f"apple-sibling-drift: drift {len(head)}, new {len(new) if not args.report else '-'}" + f", resolved {resolved}", file=sys.stderr) + return 1 if args.strict and new and not args.report else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/security/keys/trusted-keys/tests/.kunitconfig b/security/keys/trusted-keys/tests/.kunitconfig new file mode 100644 index 00000000000000..3b5f98f28758fa --- /dev/null +++ b/security/keys/trusted-keys/tests/.kunitconfig @@ -0,0 +1,4 @@ +CONFIG_KUNIT=y +CONFIG_KEYS=y +CONFIG_TRUSTED_KEYS=y +CONFIG_TRUSTED_SOURCE_KUNIT_TEST=y diff --git a/sound/soc/apple/aop_audio.rs b/sound/soc/apple/aop_audio.rs index 113b0ea6db869e..e52a22c1518658 100644 --- a/sound/soc/apple/aop_audio.rs +++ b/sound/soc/apple/aop_audio.rs @@ -540,8 +540,8 @@ struct SndSocAopHwConfig { bytes_per_sample: u32, hf_decimator: bool, // The T6040 firmware takes the microphone setup macOS sends. LPAI property 301 is the - // read-only stream description; the channel masks are property 300 (12 bytes). A refusal of - // any of the configuration steps is logged and not fatal, so the next step's answer is seen. + // read-only stream description; the channel masks are property 300 (12 bytes). A refused + // step leaves out the microphones it sets up (see the probe), not the speaker or jack. t6040_flow: bool, } @@ -695,8 +695,12 @@ impl SndSocAopData { }; let msg = AudioSetDeviceProp::new(AUDIO_DEV_LPAI, 300, ctl); let ret = self.epic_wrapped_call(&msg)?; - dev_dbg!(self.dev, "lpai channel control (prop 300): {:#x}\n", ret); if ret != 0 { + dev_err!( + self.dev, + "Unable to set lpai channel masks, return code {:#x}\n", + ret + ); return Err(EIO); } Ok(()) @@ -1176,6 +1180,23 @@ impl platform::Driver for AopAudio { } impl SndSocAopDriver { + /// Registers only the speaker and jack streams the node lists, for a + /// machine whose microphones are absent or could not be set up; `err` + /// when it lists none either. + fn without_microphones(data: Arc, streams: bool, err: Error) -> Result { + if !streams { + return Err(err); + } + let mut this = SndSocAopDriver { + card: ptr::null_mut(), + mic: aop_lid::MicLid::new()?, + spkr: None, + lpai: None, + }; + this.spkr = Some(aop_spkr::SpeakerComponent::register(data)?); + Ok(this) + } + fn probe( pdev: &platform::Device>, info: &'static SndSocAopHwConfig, @@ -1213,17 +1234,7 @@ impl SndSocAopDriver { // channel: its firmware has no PDM devices, so attach only the // speaker and jack streams. if info.t6040_flow && !listed(c_str!("dma")) { - if !streams { - return Err(ENODEV); - } - let mut this = SndSocAopDriver { - card: ptr::null_mut(), - mic: aop_lid::MicLid::new()?, - spkr: None, - lpai: None, - }; - this.spkr = Some(aop_spkr::SpeakerComponent::register(data)?); - return Ok(this); + return Self::without_microphones(data, streams, ENODEV); } for dev in [AUDIO_DEV_PDM0, AUDIO_DEV_HPAI, AUDIO_DEV_LPAI] { data.audio_attach_device(dev)?; @@ -1233,20 +1244,37 @@ impl SndSocAopDriver { } if info.t6040_flow { // Property 301 is the read-only stream description on this firmware (writing it - // returns 0xE00002CF, kIOReturnNotWritable). Follow macOS: channel masks are property - // 300. A refusal is reported and does not stop the probe. - if data.set_lpai_channel_control().is_err() { - dev_warn!(data.dev, "lpai channel control refused, continuing\n"); - } - if data.set_pdm_config().is_err() { - dev_warn!(data.dev, "pdm config refused, continuing\n"); - } - if data.set_decimator_config_hf().is_err() { - dev_warn!(data.dev, "decimator config refused, continuing\n"); + // returns 0xE00002CF, kIOReturnNotWritable); the channel masks are property 300. + // The masks are the low-power microphone's: without them the card offers the + // array alone. Without the PDM and decimator setup the array would capture + // from whatever the firmware held, so no microphone is offered; the speaker + // and jack streams do not depend on it and are still registered. + let lpai_masks = data + .set_lpai_channel_control() + .inspect_err(|e| { + dev_err!( + data.dev, + "lpai channel masks not set ({:?}): no low-power microphone\n", + e + ); + }) + .is_ok(); + if let Err(e) = data + .set_pdm_config() + .and_then(|()| data.set_decimator_config_hf()) + { + dev_err!( + data.dev, + "microphone setup failed ({:?}): no microphones\n", + e + ); + return Self::without_microphones(data, streams, e); } // The low-power microphone's ring goes through the audio node's // own DART stream; a node without one has the array only. - let lpai = if data.fwnode.property_present(c_str!("iommus")) { + let lpai = if !lpai_masks { + None + } else if data.fwnode.property_present(c_str!("iommus")) { // SAFETY: no DMA is in flight on this device yet. unsafe { pdev.dma_set_mask_and_coherent(DmaMask::new::<42>())? }; aop_lpai::LpaiCapture::new_ring( diff --git a/sound/soc/apple/aop_lpai.rs b/sound/soc/apple/aop_lpai.rs index d218570a8b9992..d72627ecfac521 100644 --- a/sound/soc/apple/aop_lpai.rs +++ b/sound/soc/apple/aop_lpai.rs @@ -118,6 +118,14 @@ const PERIOD_MS_MIN: u32 = 10; const PERIOD_BYTES_MAX: usize = 0x10000; const BUFFER_BYTES_MAX: usize = 512 * 1024; const PERIODS_MIN: u32 = 2; +/// T6041: the longest host ring the driver allocates, in seconds of the +/// ring's own format. The firmware describes four seconds; the limit leaves +/// four times that, at any rate and channel count. +const RING_SECONDS_MAX: u64 = 16; +/// T6041: a ceiling on the ring whatever the format, above four seconds of +/// the fastest format the PCM offers ([`PERIOD_BYTES_MAX`] per +/// [`PERIOD_MS_MIN`]). +const RING_BYTES_MAX: usize = 64 << 20; /// Warning classes, one message per class and driver instance. const WARN_MALFORMED: usize = 0; @@ -319,6 +327,8 @@ impl StreamFormat { return None; } fmt.alsa_format()?; + // The PCM's period range must exist for the format. + fmt.period_bytes_min()?; Some(fmt) } @@ -326,6 +336,18 @@ impl StreamFormat { (self.channels * self.bytes_per_channel) as usize } + /// The bytes of the shortest period, [`PERIOD_MS_MIN`] of whole frames; + /// `None` when that is no frame at all or more than the longest period + /// ([`PERIOD_BYTES_MAX`]), so that the PCM would have no valid period. + fn period_bytes_min(&self) -> Option { + let frames = u64::from(self.rate).checked_mul(u64::from(PERIOD_MS_MIN))? / 1000; + let frame = self.channels.checked_mul(self.bytes_per_channel)?; + let bytes = frames.checked_mul(u64::from(frame))?; + usize::try_from(bytes) + .ok() + .filter(|b| (1..=PERIOD_BYTES_MAX).contains(b)) + } + /// Signed little-endian PCM of the container width. fn alsa_format(&self) -> Option { match self.bytes_per_channel { @@ -406,6 +428,26 @@ pub(crate) enum RingStep { Copy(usize), } +/// The bytes of a host ring of `frames` frames of `format` that reports its +/// producer every `quantum` frames; `None` for a geometry the driver does not +/// take: an empty ring, one longer than [`RING_SECONDS_MAX`] of the format or +/// larger than [`RING_BYTES_MAX`], or a report interval that is zero or more +/// than half the ring. +pub(crate) fn ring_geometry(format: &StreamFormat, frames: u64, quantum: u64) -> Option { + let frames_max = u64::from(format.rate).checked_mul(RING_SECONDS_MAX)?; + let frame_bytes = u64::try_from(format.frame_bytes()).ok()?; + let bytes = usize::try_from(frames.checked_mul(frame_bytes)?).ok()?; + if bytes == 0 + || frames > frames_max + || bytes > RING_BYTES_MAX + || quantum == 0 + || quantum > frames / 2 + { + return None; + } + Some(bytes) +} + pub(crate) fn ring_step(copied: Option, absolute: u64, ring_bytes: usize) -> RingStep { match copied { Some(c) if absolute >= c && ((absolute - c) as usize) < ring_bytes => { @@ -587,7 +629,8 @@ impl LpaiCapture { /// a node without one yields `Ok(None)`. /// /// The geometry is read before the binding so the ring has exactly the - /// size the firmware describes (frames times frame bytes). + /// size the firmware describes (frames times frame bytes); a ring beyond + /// [`ring_geometry`]'s limits is refused before anything is allocated. pub(crate) fn new_ring( bus: &device::Device, dev: &ARef, @@ -624,14 +667,10 @@ impl LpaiCapture { }; let frames = le_u64(&geo, GEOMETRY_RING_FRAMES).ok_or(EIO)?; let quantum = le_u64(&geo, GEOMETRY_REPORT_FRAMES).ok_or(EIO)?; - let ring_bytes = frames - .checked_mul(format.frame_bytes() as u64) - .filter(|b| *b > 0 && *b <= u64::from(u32::MAX)) - .ok_or(EIO)? as usize; - if quantum == 0 || quantum > frames / 2 { + let Some(ring_bytes) = ring_geometry(&format, frames, quantum) else { dev_err!(dev, "invalid lpai ring geometry: {} frames, {} per report\n", frames, quantum); return Err(EIO); - } + }; let ring = adata.bound_ring(bus, ring_bytes, &mut |iova, len| { let req = AudioSetDeviceProp::new( AUDIO_DEV_IO_BUFFER, @@ -784,8 +823,9 @@ impl LpaiCapture { } fn hw(&self) -> bindings::snd_pcm_hardware { - let frame = self.format.frame_bytes(); - let period_min = (self.format.rate * PERIOD_MS_MIN / 1000) as usize * frame; + // `StreamFormat::new` only yields formats with a minimum period in + // 1..=PERIOD_BYTES_MAX. + let period_min = self.format.period_bytes_min().unwrap_or(PERIOD_BYTES_MAX); bindings::snd_pcm_hardware { info: bindings::SNDRV_PCM_INFO_MMAP | bindings::SNDRV_PCM_INFO_MMAP_VALID @@ -1149,6 +1189,83 @@ mod tests { assert!(StreamFormat::parse(&p).is_none()); } + fn format(rate: u32, channels: u32, bytes: u32) -> [u8; 16] { + let mut p = [0u8; 16]; + p[0..4].copy_from_slice(&1u32.to_le_bytes()); + p[4..8].copy_from_slice(&rate.to_le_bytes()); + p[8..12].copy_from_slice(&channels.to_le_bytes()); + p[12..16].copy_from_slice(&bytes.to_le_bytes()); + p + } + + #[test] + fn a_format_without_a_valid_period_range_is_refused() { + let f = StreamFormat::parse(&format(16000, 3, 2)).unwrap(); + assert_eq!(f.period_bytes_min(), Some(160 * 6)); + let f = StreamFormat::parse_ring(&format(16000, 3, 3)).unwrap(); + assert_eq!(f.period_bytes_min(), Some(160 * 12)); + let f = StreamFormat::parse(&format(48000, 8, 4)).unwrap(); + assert_eq!(f.period_bytes_min(), Some(480 * 32)); + // The shortest period holds no frame. + assert!(StreamFormat::parse(&format(50, 3, 2)).is_none()); + assert!(StreamFormat::parse_ring(&format(50, 3, 3)).is_none()); + assert!(StreamFormat::parse(&format(99, 1, 2)).is_none()); + assert!(StreamFormat::parse(&format(100, 1, 2)).is_some()); + // The shortest period is longer than the longest. + assert!(StreamFormat::parse(&format(u32::MAX, 3, 2)).is_none()); + assert!(StreamFormat::parse_ring(&format(u32::MAX, 8, 3)).is_none()); + assert!(StreamFormat::parse(&format(0x2000_0000, 3, 2)).is_none()); + // Every period range the PCM offers is non-empty and in the buffer. + for rate in [100, 8000, 16000, 44100, 48000, 96000, 192000] { + for channels in 1..=8 { + for bytes in [2, 4] { + if let Some(f) = StreamFormat::parse(&format(rate, channels, bytes)) { + let min = f.period_bytes_min().unwrap(); + assert!(min >= f.frame_bytes() && min <= PERIOD_BYTES_MAX); + assert!(BUFFER_BYTES_MAX / min >= PERIODS_MIN as usize); + } + } + } + } + } + + #[test] + fn the_ring_geometry_is_bounded_by_its_format() { + // T6041: four seconds of 16 kHz, three 4-byte channels, 0.2 s reports. + let f = StreamFormat::parse_ring(&format(16000, 3, 4)).unwrap(); + assert_eq!(ring_geometry(&f, 64000, 3200), Some(768000)); + assert_eq!(ring_geometry(&f, 64000, 32000), Some(768000)); + assert_eq!(ring_geometry(&f, 64000, 32001), None); + assert_eq!(ring_geometry(&f, 64000, 0), None); + assert_eq!(ring_geometry(&f, 0, 0), None); + // Longer rings of the same format, up to the time limit. + assert_eq!(ring_geometry(&f, 16000 * 16, 3200), Some(16000 * 16 * 12)); + assert_eq!(ring_geometry(&f, 16000 * 16 + 1, 3200), None); + assert_eq!(ring_geometry(&f, 1 << 28, 3200), None); + assert_eq!(ring_geometry(&f, u64::from(u32::MAX) / 12, 3200), None); + assert_eq!(ring_geometry(&f, u64::MAX, 3200), None); + // Four seconds of other channel counts and rates are taken. + for rate in [8000, 16000, 24000, 32000, 44100, 48000, 96000, 192000] { + for channels in 1..=8 { + for bytes in [2, 3, 4] { + if let Some(f) = StreamFormat::parse_ring(&format(rate, channels, bytes)) { + let frames = u64::from(rate) * 4; + assert_eq!( + ring_geometry(&f, frames, frames / 20), + Some(frames as usize * f.frame_bytes()) + ); + } + } + } + } + // The byte ceiling holds near the fastest format the PCM offers. + let f = StreamFormat::parse_ring(&format(204800, 8, 4)).unwrap(); + assert!(ring_geometry(&f, 204800 * 10, 3200).is_some()); + assert_eq!(ring_geometry(&f, 204800 * 12, 3200), None); + // 10 ms of 204900 Hz is 2049 frames, a period above PERIOD_BYTES_MAX. + assert!(StreamFormat::parse_ring(&format(204900, 8, 4)).is_none()); + } + fn change(last_frame: u64, cursor: u64, property: u32) -> [u8; CHANGE_REPORT_MIN] { let mut r = [0u8; CHANGE_REPORT_MIN]; r[CHANGE_MAGIC..CHANGE_MAGIC + 4].copy_from_slice(&PROPERTY_CHANGE_MAGIC.to_le_bytes()); diff --git a/sound/soc/apple/aop_t8140.rs b/sound/soc/apple/aop_t8140.rs index 751cde0c4eb8ed..b58896f348719e 100644 --- a/sound/soc/apple/aop_t8140.rs +++ b/sound/soc/apple/aop_t8140.rs @@ -130,9 +130,9 @@ const AUDIO_RET_BUSY: u32 = 0xe00002d5; const SPKR_POWER_STATE_PW0: u32 = from_fourcc(b"pw0 "); const SPKR_POWER_STATE_PWRD: u32 = from_fourcc(b"pwrd"); -/// Leaf power-up retries while the firmware raises the fabric (see `PowerDomain::get`). -/// Blind attempts before the fabric is raised, and attempts while it rises. -const PD_GET_ATTEMPTS: u32 = 3; +/// Leaf power-up attempts with the fabric raised (see `PowerDomain::get`): a +/// fallback, since the low-power microphone's first report already proves +/// the fabric up. Any retry is logged with the attempts it took. const PD_GET_RAISED_ATTEMPTS: u32 = 60; const PD_GET_RETRY_MS: i64 = 10; /// The fabric comes up some tens to hundreds of milliseconds after the @@ -359,14 +359,15 @@ impl PowerDomain { /// the PMGR driver's poll window with the parent still coming up. A /// failed resume leaves the virtual domain device in the runtime-PM error /// state, where every later request fails with EINVAL; clear that state - /// and retry a bounded number of times before giving up. - fn get(&self, attempts: u32) -> Result<()> { + /// and retry a bounded number of times before giving up. Returns the + /// attempts the domain took. + fn get(&self, attempts: u32) -> Result { let mut rc = 0; for attempt in 0..attempts { // SAFETY: the domain device stays attached for the lifetime of `self`. rc = unsafe { bindings::pm_runtime_get_sync(self.dev.as_ptr()) }; if rc >= 0 { - return Ok(()); + return Ok(attempt + 1); } // SAFETY: as above; a failed resume still took the usage count. unsafe { bindings::pm_runtime_put_noidle(self.dev.as_ptr()) }; @@ -803,8 +804,20 @@ impl SndSocT8140AopData { self.power_down(&pds[..i]); return Err(ENODEV); }; - if let Err(e) = pd.get(attempts) { - if e != ETIMEDOUT || attempts > PD_GET_ATTEMPTS { + match pd.get(attempts) { + Ok(1) => {} + Ok(n) => { + // The fabric was not up after the low-power + // microphone's report: the retry hid a slow fabric. + dev_warn!( + self.dev, + "{}: power domain {} up after {} attempts\n", + name, + pd.name, + n + ); + } + Err(e) => { dev_err!( self.dev, "{}: power domain {} did not power up: {:?}\n", @@ -812,9 +825,9 @@ impl SndSocT8140AopData { pd.name, e ); + self.power_down(&pds[..i]); + return Err(e); } - self.power_down(&pds[..i]); - return Err(e); } } Ok(()) diff --git a/sound/soc/apple/macaudio-admission-test.h b/sound/soc/apple/macaudio-admission-test.h index fa5e9f4df00c75..cabae2ad79561e 100644 --- a/sound/soc/apple/macaudio-admission-test.h +++ b/sound/soc/apple/macaudio-admission-test.h @@ -11,12 +11,16 @@ static void macaudio_admission_needs_a_safe_level(struct kunit *test) KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&macaudio_j45x_cfg)); KUNIT_EXPECT_TRUE(test, macaudio_speakers_allowed(&macaudio_j413_cfg)); KUNIT_EXPECT_TRUE(test, macaudio_speakers_allowed(&macaudio_j700_cfg)); - /* The AOP-fed machines: J714 and J813 with their safe level, J873 without one */ + /* The AOP-fed machines: J714 and J813 with their safe level, J873 and J704 without one */ KUNIT_EXPECT_TRUE(test, macaudio_speakers_allowed(&macaudio_j714_cfg)); KUNIT_EXPECT_TRUE(test, macaudio_speakers_allowed(&macaudio_j813_cfg)); KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&macaudio_j873_cfg)); /* The Mac Studio M5: no sense and no protection owner yet, speaker off */ KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&macaudio_j775_cfg)); + /* J704: speakers off until their slots and protection are verified */ + KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&macaudio_j704_cfg)); + /* K114: the J714 amps and frame, but no safe level for the chassis */ + KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&macaudio_k114_cfg)); cfg = macaudio_j413_cfg; cfg.safe_vol = 0; KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&cfg)); @@ -32,8 +36,28 @@ static void macaudio_admission_needs_a_safe_level(struct kunit *test) KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&cfg)); } +/* Without sense, only a lease lifts the amps, and only to safe_vol */ +static void macaudio_admission_fixed_ceiling_is_lease_only(struct kunit *test) +{ + struct macaudio_platform_cfg cfg = macaudio_j813_cfg; + + /* A protection daemon unlocks the J813's amps to 0 dB */ + KUNIT_EXPECT_FALSE(test, macaudio_spk_lease_only(&cfg)); + KUNIT_EXPECT_EQ(test, macaudio_sn012776_vlimit(&cfg, false, false), 1); + KUNIT_EXPECT_EQ(test, macaudio_sn012776_vlimit(&cfg, true, false), SN012776_0DB); + + cfg.safe_vol = -16; + cfg.spk_fixed_ceiling = true; + KUNIT_EXPECT_TRUE(test, macaudio_spk_lease_only(&cfg)); + KUNIT_EXPECT_EQ(test, macaudio_sn012776_vlimit(&cfg, false, false), 1); + KUNIT_EXPECT_EQ(test, macaudio_sn012776_vlimit(&cfg, true, false), 1); + KUNIT_EXPECT_EQ(test, macaudio_sn012776_vlimit(&cfg, false, true), 1); + KUNIT_EXPECT_EQ(test, macaudio_sn012776_vlimit(&cfg, true, true), SN012776_DB(-16)); +} + static struct kunit_case macaudio_admission_cases[] = { KUNIT_CASE(macaudio_admission_needs_a_safe_level), + KUNIT_CASE(macaudio_admission_fixed_ceiling_is_lease_only), {} }; diff --git a/sound/soc/apple/macaudio-amp-level-test.h b/sound/soc/apple/macaudio-amp-level-test.h index 40130b1134f952..b97939e10c672c 100644 --- a/sound/soc/apple/macaudio-amp-level-test.h +++ b/sound/soc/apple/macaudio-amp-level-test.h @@ -2,7 +2,8 @@ /* * KUnit tests of the SN012776 amp levels: each amp's level is the second byte * of its apple,speaker-config, which the boot loader copies from the Mac's - * ADT, and the speakers stay off when any amp lacks it. + * ADT, and the speakers stay off when any amp lacks it, or under a fixed + * ceiling when any amp has another level than the ceiling was computed for. */ #include #include @@ -16,6 +17,14 @@ static struct device_node *macaudio_level_test_node(struct kunit *test, const ch return np; } +/* Whether the speakers of the codec node @name would run under @cfg */ +static bool macaudio_level_test_present(struct kunit *test, struct device *dev, + const struct macaudio_platform_cfg *cfg, + const char *name) +{ + return macaudio_sn012776_levels_present(dev, cfg, macaudio_level_test_node(test, name)); +} + /* The level is the row's second byte, its low five bits */ static void macaudio_level_from_row(struct kunit *test) { @@ -41,13 +50,41 @@ static void macaudio_levels_every_amp(struct kunit *test) { struct device *dev = kunit_kzalloc(test, sizeof(*dev), GFP_KERNEL); + const struct macaudio_platform_cfg *cfg = &macaudio_j316_cfg; + + KUNIT_ASSERT_NOT_NULL(test, dev); + KUNIT_EXPECT_TRUE(test, macaudio_level_test_present(test, dev, cfg, + "macaudio-kunit-codec-good")); + KUNIT_EXPECT_FALSE(test, macaudio_level_test_present(test, dev, cfg, + "macaudio-kunit-codec-one-missing")); + KUNIT_EXPECT_FALSE(test, macaudio_level_test_present(test, dev, cfg, + "macaudio-kunit-codec-one-high")); +} + +/* A fixed ceiling, here computed at level 15, holds only at that level */ +static const struct macaudio_platform_cfg macaudio_level_ceiling_cfg = { + .amp = AMP_SN012776, + .spk_fixed_ceiling = true, + .spk_ceiling_level = 15, +}; + +static void macaudio_levels_fixed_ceiling(struct kunit *test) +{ + struct device *dev = kunit_kzalloc(test, sizeof(*dev), GFP_KERNEL); + + const struct macaudio_platform_cfg *cfg = &macaudio_level_ceiling_cfg; + KUNIT_ASSERT_NOT_NULL(test, dev); - KUNIT_EXPECT_TRUE(test, macaudio_sn012776_levels_present(dev, - macaudio_level_test_node(test, "macaudio-kunit-codec-good"))); - KUNIT_EXPECT_FALSE(test, macaudio_sn012776_levels_present(dev, - macaudio_level_test_node(test, "macaudio-kunit-codec-one-missing"))); - KUNIT_EXPECT_FALSE(test, macaudio_sn012776_levels_present(dev, - macaudio_level_test_node(test, "macaudio-kunit-codec-one-high"))); + /* One amp at 0x0f */ + KUNIT_EXPECT_TRUE(test, macaudio_level_test_present(test, dev, cfg, + "macaudio-kunit-codec-level-15")); + /* 0x0f and 0x07: the second amp's level is not the ceiling's */ + KUNIT_EXPECT_FALSE(test, macaudio_level_test_present(test, dev, cfg, + "macaudio-kunit-codec-good")); + KUNIT_EXPECT_FALSE(test, macaudio_level_test_present(test, dev, cfg, + "macaudio-kunit-codec-one-missing")); + KUNIT_EXPECT_FALSE(test, macaudio_sn012776_level_allowed(cfg, 14)); + KUNIT_EXPECT_FALSE(test, macaudio_sn012776_level_allowed(cfg, 16)); } /* No board table carries an SN012776 gain any more */ @@ -59,7 +96,7 @@ static void macaudio_level_no_table(struct kunit *test) &macaudio_j493_cfg, &macaudio_j575c_j773_cfg, &macaudio_j604_cfg, &macaudio_j614_cfg, &macaudio_j616_cfg, &macaudio_j713_cfg, &macaudio_j714_cfg, &macaudio_j715_cfg, &macaudio_j813_cfg, - &macaudio_j775_cfg, &macaudio_j873_cfg, + &macaudio_j775_cfg, &macaudio_j873_cfg, &macaudio_k114_cfg, }; unsigned int i; @@ -78,6 +115,7 @@ static struct kunit_case macaudio_level_cases[] = { KUNIT_CASE(macaudio_level_from_row), KUNIT_CASE(macaudio_level_rejects), KUNIT_CASE(macaudio_levels_every_amp), + KUNIT_CASE(macaudio_levels_fixed_ceiling), KUNIT_CASE(macaudio_level_no_table), {} }; diff --git a/sound/soc/apple/macaudio-kunit.dtso b/sound/soc/apple/macaudio-kunit.dtso index 57e001d8b15bfc..724cf4fb965d2d 100644 --- a/sound/soc/apple/macaudio-kunit.dtso +++ b/sound/soc/apple/macaudio-kunit.dtso @@ -47,4 +47,8 @@ macaudio-kunit-codec-one-high { sound-dai = <&ma_amp_high>, <&ma_amp_a>; }; + + macaudio-kunit-codec-level-15 { + sound-dai = <&ma_amp_a>; + }; }; diff --git a/sound/soc/apple/macaudio-protection-test.h b/sound/soc/apple/macaudio-protection-test.h index d8ef1db227eb5b..1f6cd5ddb987d7 100644 --- a/sound/soc/apple/macaudio-protection-test.h +++ b/sound/soc/apple/macaudio-protection-test.h @@ -1028,7 +1028,10 @@ static void macaudio_spk_j700_does_not_ramp(struct kunit *test) KUNIT_EXPECT_EQ(test, macaudio_test_vol(t.vols[0])->hist[0], (long)MAX98360A_DB(-20)); } -/* A fixed ceiling: the grant runs the amps at it, the ramp starts below it */ +/* + * A fixed ceiling: an unlock leaves the amps at the floor, the lease's grant + * runs them at the ceiling, the ramp starts below it. + */ static void macaudio_spk_fixed_ceiling(struct kunit *test) { struct macaudio_platform_cfg *cfg = kunit_kzalloc(test, sizeof(*cfg), GFP_KERNEL); @@ -1043,6 +1046,15 @@ static void macaudio_spk_fixed_ceiling(struct kunit *test) cfg->spk_fixed_ceiling = true; macaudio_test_spk_card(test, &t, cfg, SN012776_0DB); + /* "Speaker Volume Unlock" lifts nothing: the limit stays at the floor */ + mutex_lock(&t.ma->volume_lock_mutex); + WRITE_ONCE(t.ma->spk_iface, MACAUDIO_SPK_IFACE_UNLOCK); + macaudio_vlimit_unlock(t.ma, true); + WRITE_ONCE(t.ma->spk_iface, MACAUDIO_SPK_IFACE_LEASE); + mutex_unlock(&t.ma->volume_lock_mutex); + for (i = 0; i < MACAUDIO_TEST_NR_SPK; i++) + KUNIT_EXPECT_EQ(test, (long)macaudio_test_vol(t.vols[i])->mc.platform_max, 1L); + /* The limit the lease leaves on the volumes (macaudio_spk_enter_lease()) */ mutex_lock(&t.ma->volume_lock_mutex); macaudio_vlimit_unlock(t.ma, true); diff --git a/sound/soc/apple/macaudio-vlimit-test.h b/sound/soc/apple/macaudio-vlimit-test.h new file mode 100644 index 00000000000000..26b8764805a65e --- /dev/null +++ b/sound/soc/apple/macaudio-vlimit-test.h @@ -0,0 +1,251 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* + * The "Speaker Volume Unlock" lease: the speaker volumes leave the safe + * ceiling only while one process holds the lock control and every speaker + * volume, and pings within SPEAKER_LOCK_TIMEOUT ms while speaker playback + * runs. Built on the card of macaudio-pm-volumes-test.h. + */ +#include +#include + +static int macaudio_vlt_put(struct kunit *test, struct macaudio_pmt_pm *t, long val) +{ + struct snd_ctl_elem_value *uval = kunit_kzalloc(test, sizeof(*uval), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, uval); + uval->value.integer.value[0] = val; + return macaudio_slk_put(t->slk, uval); +} + +static long macaudio_vlt_get(struct kunit *test, struct macaudio_pmt_pm *t) +{ + struct snd_ctl_elem_value *uval = kunit_kzalloc(test, sizeof(*uval), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, uval); + KUNIT_EXPECT_EQ(test, macaudio_slk_get(t->slk, uval), 0); + return uval->value.integer.value[0]; +} + +/* Speaker playback runs (or stops): the ping deadline is armed (or held). */ +static void macaudio_vlt_playing(struct macaudio_pmt_pm *t, bool playing) +{ + if (playing) + macaudio_vlimit_enable_timeout(t->ma); + else + macaudio_vlimit_disable_timeout(t->ma); +} + +/* Saved mixer states hold 0 or 1: restoring one is a no-op, nothing else is. */ +static void macaudio_vlimit_restore_values_are_noops(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, 0), 0); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, 1), 0); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, 2), -EINVAL); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, SPEAKER_MAGIC_VALUE + 1), -EINVAL); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_vlt_get(test, &t), 0L); + + /* Even for the owner */ + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, 1), 0); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); +} + +/* A ping without the lock is refused and unlocks nothing. */ +static void macaudio_vlimit_ping_needs_the_lock(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), -EPERM); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_vlt_get(test, &t), 0L); +} + +/* The lock alone is not enough: every speaker volume must be the owner's. */ +static void macaudio_vlimit_needs_every_volume(struct kunit *test) +{ + struct snd_ctl_file *other = kunit_kzalloc(test, sizeof(*other), GFP_KERNEL); + struct macaudio_pmt_pm t; + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, other); + for (i = 0; i < MACAUDIO_PMT_NR_VOLS - 1; i++) { + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + t.vols[i]->vd[0].owner = other; + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_FALSE_MSG(test, t.ma->speaker_volume_unlocked, + "%s held by another file", macaudio_pmt_vol_names[i]); + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + t.vols[i]->vd[0].owner = NULL; + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_FALSE_MSG(test, t.ma->speaker_volume_unlocked, + "%s not locked", macaudio_pmt_vol_names[i]); + } + + /* A volume that is not a speaker volume does not count */ + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + t.vols[MACAUDIO_PMT_NR_VOLS - 1]->vd[0].owner = other; + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); +} + +/* Closing the lock relocks at once and clips the speaker volumes only. */ +static void macaudio_vlimit_unlock_clips(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_vlt_get(test, &t), 1L); + macaudio_pmt_expect_vols(test, &t, false); + + macaudio_slk_unlock(t.slk); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_vlt_get(test, &t), 0L); + macaudio_pmt_expect_vols(test, &t, true); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), -EPERM); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); +} + +/* + * While playback runs the lease ends SPEAKER_LOCK_TIMEOUT ms after the last + * ping. The owner's next ping reports the loss with -ETIMEDOUT and unlocks + * nothing; only the ping after it starts a new lease. + */ +static void macaudio_vlimit_lease_expires_while_playing(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + macaudio_vlt_playing(&t, true); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + + msleep(SPEAKER_LOCK_TIMEOUT * 2); + flush_delayed_work(&t.ma->lock_timeout_work); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + macaudio_pmt_expect_vols(test, &t, true); + + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), -ETIMEDOUT); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + macaudio_vlt_playing(&t, false); +} + +/* + * Each ping moves the deadline to SPEAKER_LOCK_TIMEOUT ms after itself and + * re-arms the expiry. Checked on the deadline, not by racing the clock. + */ +static void macaudio_vlimit_pings_keep_the_lease(struct kunit *test) +{ + struct macaudio_pmt_pm t; + ktime_t before, deadline; + unsigned int i; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + macaudio_vlt_playing(&t, true); + deadline = t.ma->speaker_lock_timeout; + for (i = 0; i < 3; i++) { + usleep_range(1000, 2000); + before = ktime_get(); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_GT(test, t.ma->speaker_lock_timeout, deadline); + KUNIT_EXPECT_GE(test, t.ma->speaker_lock_timeout, + ktime_add_ms(before, SPEAKER_LOCK_TIMEOUT)); + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&t.ma->lock_timeout_work)); + deadline = t.ma->speaker_lock_timeout; + } + macaudio_vlt_playing(&t, false); +} + +/* + * Without playback the deadline is held: an idle owner keeps its lease, and + * the time it had left runs on when playback starts again. + */ +static void macaudio_vlimit_idle_holds_the_lease(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + msleep(SPEAKER_LOCK_TIMEOUT * 2); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, t.ma->speaker_lock_remain, ms_to_ktime(SPEAKER_LOCK_TIMEOUT)); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&t.ma->lock_timeout_work)); + + /* The time left runs from the start of playback and then ends */ + macaudio_vlt_playing(&t, true); + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&t.ma->lock_timeout_work)); + msleep(SPEAKER_LOCK_TIMEOUT * 2); + flush_delayed_work(&t.ma->lock_timeout_work); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + macaudio_vlt_playing(&t, false); +} + +/* A new owner never inherits the previous owner's lease. */ +static void macaudio_vlimit_new_owner_pings_first(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_LE(test, t.ma->speaker_lock_remain, 0); + /* The relock was the switch of owners, not a lost lease */ + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); +} + +/* A card without speaker safety never touches its volumes. */ +static void macaudio_vlimit_without_safety(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + t.ma->has_safety = false; + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + macaudio_slk_unlock(t.slk); + macaudio_pmt_expect_vols(test, &t, false); +} + +static struct kunit_case macaudio_vlimit_cases[] = { + KUNIT_CASE(macaudio_vlimit_restore_values_are_noops), + KUNIT_CASE(macaudio_vlimit_ping_needs_the_lock), + KUNIT_CASE(macaudio_vlimit_needs_every_volume), + KUNIT_CASE(macaudio_vlimit_unlock_clips), + KUNIT_CASE_SLOW(macaudio_vlimit_lease_expires_while_playing), + KUNIT_CASE(macaudio_vlimit_pings_keep_the_lease), + KUNIT_CASE_SLOW(macaudio_vlimit_idle_holds_the_lease), + KUNIT_CASE(macaudio_vlimit_new_owner_pings_first), + KUNIT_CASE(macaudio_vlimit_without_safety), + {} +}; + +static struct kunit_suite macaudio_vlimit_suite = { + .name = "apple-speaker-volume-unlock", + .test_cases = macaudio_vlimit_cases, +}; + +kunit_test_suite(macaudio_vlimit_suite); diff --git a/sound/soc/apple/macaudio.c b/sound/soc/apple/macaudio.c index b05d60bc0451a0..b641b455dd7f4c 100644 --- a/sound/soc/apple/macaudio.c +++ b/sound/soc/apple/macaudio.c @@ -185,11 +185,19 @@ struct macaudio_platform_cfg { bool spk_secondary_only; /* * No voltage or current sense reaches the AP, so no protection daemon - * can govern the speakers: their SN012776 volumes stay under safe_vol, - * locked, unlocked or granted alike, and there is no sense PCM. A - * granted lease runs them at safe_vol, its operating gain. + * can govern the speakers, and there is no sense PCM. "Speaker Volume + * Unlock" does not apply: the SN012776 volumes stay at the floor until + * the interface is on the "Speaker Protection" lease, and playback + * starts only after a grant, which runs them at safe_vol, its + * operating gain and their ceiling. */ bool spk_fixed_ceiling; + /* + * With spk_fixed_ceiling: the amp level safe_vol was computed for. At + * any other level the same volume drives the speaker differently, so + * the speakers stay off. + */ + int spk_ceiling_level; }; static const char *volume_control_names[] = { @@ -408,6 +416,26 @@ static bool macaudio_spk_leased(const struct macaudio_snd_data *ma) return READ_ONCE(ma->spk_iface) == MACAUDIO_SPK_IFACE_LEASE; } +/* Only a "Speaker Protection" lease may lift these speakers (spk_fixed_ceiling) */ +static bool macaudio_spk_lease_only(const struct macaudio_platform_cfg *cfg) +{ + return cfg->spk_fixed_ceiling; +} + +/* + * The SN012776 volumes' limit: the floor while locked; unlocked, 0 dB, or + * on a lease-only machine safe_vol, and there only under the lease. + */ +static int macaudio_sn012776_vlimit(const struct macaudio_platform_cfg *cfg, + bool unlock, bool leased) +{ + if (macaudio_spk_lease_only(cfg)) + return unlock && leased ? SN012776_DB(cfg->safe_vol) : 1; + if (unlock) + return SN012776_0DB; + return 1; //SN012776_DB(cfg->safe_vol); +} + SND_SOC_DAILINK_DEFS(primary, DAILINK_COMP_ARRAY(COMP_CPU("mca-pcm-0")), // CPU @@ -534,12 +562,7 @@ static void macaudio_vlimit_unlock(struct macaudio_snd_data *ma, bool unlock) max = 1; //TAS5770_DB(ma->cfg->safe_vol); break; case AMP_SN012776: - if (ma->cfg->spk_fixed_ceiling) - max = SN012776_DB(ma->cfg->safe_vol); - else if (unlock) - max = SN012776_0DB; - else - max = 1; //SN012776_DB(ma->cfg->safe_vol); + max = macaudio_sn012776_vlimit(ma->cfg, unlock, macaudio_spk_leased(ma)); break; case AMP_SSM3515: if (unlock) @@ -768,6 +791,10 @@ static void macaudio_vlimit_update(struct macaudio_snd_data *ma) if (macaudio_spk_leased(ma)) return; + /* No protection daemon can hold these speakers: nothing to unlock */ + if (macaudio_spk_lease_only(ma->cfg)) + return; + /* Check that someone is holding the main lock */ if (!ma->speaker_lock_owner) { reason = "Main control not locked"; @@ -2405,11 +2432,22 @@ static int macaudio_sn012776_level(struct device_node *amp) return level <= SN012776_LEVEL_MAX ? level : -ERANGE; } +/* + * A fixed ceiling holds only at the amp level it was computed for. + */ +static bool macaudio_sn012776_level_allowed(const struct macaudio_platform_cfg *cfg, + int level) +{ + return level >= 0 && (!cfg->spk_fixed_ceiling || level == cfg->spk_ceiling_level); +} + /* * Speakers on SN012776 amps run only when every amp has its level from the - * Mac; a boot loader that does not pass it leaves them off. + * Mac, and under a fixed ceiling only at the level that ceiling was computed + * for; otherwise they stay off. */ static bool macaudio_sn012776_levels_present(struct device *dev, + const struct macaudio_platform_cfg *cfg, struct device_node *codec) { struct of_phandle_args args; @@ -2424,8 +2462,13 @@ static bool macaudio_sn012776_levels_present(struct device *dev, if (level < 0) dev_err(dev, "%pOF: %s amp level from the boot loader\n", args.np, level == -ENOENT ? "no" : "out-of-range"); + else if (!macaudio_sn012776_level_allowed(cfg, level)) + dev_err(dev, "%pOF: amp level %d, the fixed ceiling holds only at %d\n", + args.np, level, cfg->spk_ceiling_level); + else if (cfg->spk_fixed_ceiling) + dev_info(dev, "%pOF: amp level %d from the boot loader\n", args.np, level); of_node_put(args.np); - if (level < 0) + if (!macaudio_sn012776_level_allowed(cfg, level)) return false; } return n > 0; @@ -2665,11 +2708,12 @@ static int macaudio_parse_of(struct macaudio_snd_data *ma) if (ma->cfg->amp == AMP_SN012776) { struct device_node *spk_codec = of_get_child_by_name(np, "codec"); bool levels = spk_codec && - macaudio_sn012776_levels_present(card->dev, spk_codec); + macaudio_sn012776_levels_present(card->dev, ma->cfg, + spk_codec); of_node_put(spk_codec); if (!levels) { - dev_err(card->dev, "the boot loader passed no amp levels, disabling speakers\n"); + dev_err(card->dev, "no usable amp levels from the boot loader, disabling speakers\n"); continue; } } @@ -4124,6 +4168,27 @@ struct macaudio_platform_cfg macaudio_j813_cfg = { .spk_secondary_only = true, }; +/* + * J704 (T8142, MacBook Pro 14" M5): J813's audio fabric (the AOP firmware, + * the T8152-style AOP audio driver, the CS42L84 jack on "cout"). The + * speakers are six SN012776 (two woofers and a tweeter per side) in an + * order of their own; they stay off until their slots and a protection + * profile are verified: no safe level, so macaudio_speakers_allowed() keeps + * any speaker link unbound. The jack is unaffected. + */ +struct macaudio_platform_cfg macaudio_j704_cfg = { + .enable_speakers = false, + .amp = AMP_SN012776, + .speakers = SPKR_2W1T, + .stereo = true, + .safe_vol = 0, + .fe_dai_names = { "j873-pcm-0", "j873-pcm-1", "j873-pcm-2" }, + .dai_fmt = SND_SOC_DAIFMT_DSP_A | SND_SOC_DAIFMT_CBC_CFC | SND_SOC_DAIFMT_IB_NF, + .spk_dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_CBC_CFC | + SND_SOC_DAIFMT_GATED | SND_SOC_DAIFMT_NB_IF, + .spk_secondary_only = true, +}; + /* * J714s (T6050, MacBook Pro 14" M5 Pro): as on J813, the AOP firmware owns * the audio fabric and the CPU component is the T8152-style AOP audio @@ -4147,6 +4212,27 @@ struct macaudio_platform_cfg macaudio_j714_cfg = { .tweeter_hpf_granted = true, }; +/* + * K114s (T6050, MacBook Pro 14" M5 Pro): the J714s's AOP-fed card for the + * headphone jack only. Its ADT describes the same jack codec, AOP audio + * service and six SN012776 as the J714s's, but no speaker protection data + * exists for this chassis, so the speakers stay off as on the J873: no safe + * level and speakers disabled, so macaudio_speakers_allowed() refuses a + * speaker link however the DT is written. The jack frame is the J714s's. + */ +struct macaudio_platform_cfg macaudio_k114_cfg = { + .enable_speakers = false, + .amp = AMP_SN012776, + .speakers = SPKR_2W1T, + .stereo = true, + .safe_vol = 0, + .fe_dai_names = { "j873-pcm-0", "j873-pcm-1", "j873-pcm-2" }, + .dai_fmt = SND_SOC_DAIFMT_DSP_A | SND_SOC_DAIFMT_CBC_CFC | SND_SOC_DAIFMT_IB_NF, + .spk_dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_CBC_CFC | + SND_SOC_DAIFMT_GATED | SND_SOC_DAIFMT_NB_IF, + .spk_secondary_only = true, +}; + /* * J815 (T8142, MacBook Air M5 15"): J813's AOP-fed card with six SN012776, * two woofers and a tweeter per side, in ADT speaker-config order (left @@ -4458,6 +4544,8 @@ static const struct of_device_id macaudio_snd_device_id[] = { { .compatible = "apple,j714-macaudio", .data = &macaudio_j714_cfg }, /* k116 - sn012776 15 2x 2W+1T (AOP-fed, V/I sense; the 16" PROLED chassis, J714's amps and frame) */ { .compatible = "apple,k116-macaudio", .data = &macaudio_j714_cfg }, + /* k114 - sn012776 - 2x 2W+1T (AOP-fed; jack only, speakers off) */ + { .compatible = "apple,k114-macaudio", .data = &macaudio_k114_cfg }, /* j713 - sn012776 15 2x 1W+1T (AOP-fed, one serializer) */ { .compatible = "apple,j713-macaudio", .data = &macaudio_j713_cfg }, /* The J713 jack runs on the AOP like the J616s one. */ @@ -4475,6 +4563,8 @@ static const struct of_device_id macaudio_snd_device_id[] = { { .compatible = "apple,j775c-macaudio", .data = &macaudio_j775_cfg }, /* j775d - sn012776 - 1x 1W (AOP-fed, no sense: speaker off) */ { .compatible = "apple,j775d-macaudio", .data = &macaudio_j775_cfg }, + /* j704 - sn012776 - 2x 2W+1T (AOP-fed; speakers off until bring-up) */ + { .compatible = "apple,j704-macaudio", .data = &macaudio_j704_cfg }, /* j813 AID? sn012776 15 2x 1W+1T (AOP-fed, V/I sense) */ { .compatible = "apple,j813-macaudio", .data = &macaudio_j813_cfg }, /* j815 AID43 sn012776 15 2x 2W+1T (AOP-fed, V/I sense) */ @@ -4623,6 +4713,7 @@ MODULE_LICENSE("GPL"); #include "macaudio-protection-test.h" #include "macaudio-hpf-test.h" #include "macaudio-pm-volumes-test.h" +#include "macaudio-vlimit-test.h" #include "macaudio-iface-test.h" #if IS_ENABLED(CONFIG_OF_OVERLAY) #include "macaudio-amp-level-test.h" diff --git a/sound/soc/apple/t8152_aop_audio.rs b/sound/soc/apple/t8152_aop_audio.rs index b3286d1f014194..4180507b619fb8 100644 --- a/sound/soc/apple/t8152_aop_audio.rs +++ b/sound/soc/apple/t8152_aop_audio.rs @@ -19,28 +19,36 @@ //! `pw0 ` (which also brings up the audio fabric), prepare requests `pwrd` //! (the firmware then runs the serializer and its clocks) and shutdown goes //! back to `pw0 `. On T8152 and T8142 the serializer (MCA) leaves are the -//! AP's to power; on T6050 the firmware powers them itself. The -//! front-end PCMs are plain dmaengine PCMs on the base-ns channels; macaudio -//! links them to the codecs. +//! AP's to power; on T6050 the firmware powers them itself. The front-end PCMs +//! are plain dmaengine PCMs on the base-ns channels except for speaker V/I +//! sense on multi-amp streams, which is served from a driver-owned cyclic ring +//! (`SenseRing`) armed on the stopped serializer before every `pwrd` so sense +//! capture starts and restarts stay frame-aligned. Macaudio links them to the +//! codecs. //! //! Copyright (C) The Asahi Linux Contributors //! Copyright (C) 2026 The Aurora Silicon Contributors -use core::{mem, ptr, slice}; +use core::{ + ffi::c_void, + mem, ptr, slice, + sync::atomic::{ + fence, AtomicBool, AtomicI32, AtomicI64, AtomicPtr, AtomicU64, AtomicUsize, Ordering, + }, +}; use kernel::{ - bindings, c_str, - device, + bindings, c_str, device, device::Core, error::from_err_ptr, - module_platform_driver, of, platform, + module_platform_driver, new_mutex, of, platform, prelude::*, soc::apple::aop::{from_fourcc, EPICService, AOP}, str::CString, sync::{ aref::ARef, atomic::{Atomic, AtomicFlag, Relaxed}, - Arc, ArcBorrow, + Arc, ArcBorrow, Mutex, }, types::{ForeignOwnable, Opaque}, workqueue::{self, impl_has_work, new_work, Work, WorkItem}, @@ -227,6 +235,569 @@ impl Service { } } +/// Serialized power state of the speaker back-end (`spkr`). +struct SpkrState { + open: bool, + running: bool, + /// True only after `pw0 ` has been verified and before any `pwrd` + /// transition attempt. `SenseRing` may only be armed while + /// `!running && pw0_verified`. + pw0_verified: bool, + resume_run: bool, +} + +impl SpkrState { + const fn new() -> Self { + Self { + open: false, + running: false, + pw0_verified: false, + resume_run: false, + } + } + + fn ensure_pw0( + &mut self, + spkr_running: &AtomicFlag, + set_pw0: impl FnOnce() -> Result<()>, + ) -> Result<()> { + if self.running || (self.open && !self.pw0_verified) { + self.pw0_verified = false; + set_pw0()?; + self.running = false; + self.pw0_verified = true; + spkr_running.store(false, Relaxed); + } + Ok(()) + } + + fn start_with_ring( + &mut self, + spkr_running: &AtomicFlag, + ring_stop: impl Fn(), + ring_start: impl FnOnce() -> Result<()>, + set_pwrd: impl FnOnce() -> Result<()>, + ) -> Result<()> { + if self.running || !self.pw0_verified { + return Err(EIO); + } + ring_stop(); + ring_start()?; + self.pw0_verified = false; + if let Err(e) = set_pwrd() { + ring_stop(); + return Err(e); + } + self.running = true; + spkr_running.store(true, Relaxed); + Ok(()) + } + + fn stop( + &mut self, + spkr_running: &AtomicFlag, + has_ring: bool, + set_pw0: impl FnOnce() -> Result<()>, + ring_stop: impl FnOnce(), + ) -> Result<()> { + self.ensure_pw0(spkr_running, set_pw0)?; + if has_ring { + ring_stop(); + } + Ok(()) + } + + fn prepare_with_ring( + &mut self, + spkr_running: &AtomicFlag, + quiesce: impl FnOnce() -> Result<()>, + set_pw0: impl FnOnce() -> Result<()>, + ring_stop: impl Fn(), + ring_start: impl FnOnce() -> Result<()>, + set_pwrd: impl FnOnce() -> Result<()>, + ) -> Result<()> { + if self.running || !self.pw0_verified { + quiesce()?; + self.pw0_verified = false; + set_pw0()?; + self.running = false; + self.pw0_verified = true; + spkr_running.store(false, Relaxed); + } + self.start_with_ring(spkr_running, ring_stop, ring_start, set_pwrd) + } + + fn suspend( + &mut self, + spkr_running: &AtomicFlag, + has_ring: bool, + set_pw0: impl FnOnce() -> Result<()>, + ring_stop: impl FnOnce(), + ) -> Result<()> { + let was_running = self.running; + let res = self.ensure_pw0(spkr_running, set_pw0); + if has_ring { + ring_stop(); + } + self.resume_run = was_running; + res + } + + fn resume_with_ring( + &mut self, + spkr_running: &AtomicFlag, + set_pw0: impl FnOnce() -> Result<()>, + ring_stop: impl Fn(), + ring_start: impl FnOnce() -> Result<()>, + set_pwrd: impl FnOnce() -> Result<()>, + ) -> Result<()> { + if !mem::take(&mut self.resume_run) || !self.open { + return Ok(()); + } + self.ensure_pw0(spkr_running, set_pw0)?; + self.start_with_ring(spkr_running, ring_stop, ring_start, set_pwrd) + } +} + +const SENSE_RATE: u64 = 48000; +const NSEC_PER_SEC: u64 = 1_000_000_000; +/// 2.5 ms periods (120 frames at 48 kHz), 32 of them: an 80 ms ring, delivered +/// in whole-frame chunks small enough that a 512-frame front-end period +/// completes well within its headroom. Both 8-channel (16 B/frame -> 1920 B) +/// and 12-channel (24 B/frame -> 2880 B) periods stay aligned to whole frames +/// and to the ADMAC's 48-byte RX FIFO threshold. +const SENSE_RING_PERIOD_FRAMES: usize = 120; +const SENSE_RING_PERIODS: usize = 32; +const SENSE_RING_FRAMES: usize = SENSE_RING_PERIOD_FRAMES * SENSE_RING_PERIODS; +const SENSE_RING_NS: u64 = SENSE_RING_FRAMES as u64 * NSEC_PER_SEC / SENSE_RATE; +const SENSE_RING_PERIOD_NS: u64 = SENSE_RING_PERIOD_FRAMES as u64 * NSEC_PER_SEC / SENSE_RATE; +/// SNDRV_PCM_STATE_RUNNING and _XRUN (cast macros the bindings do not carry). +const PCM_STATE_RUNNING: bindings::snd_pcm_state_t = 3; +const PCM_STATE_XRUN: bindings::snd_pcm_state_t = 4; + +/// The ring may have gone round once or more in `elapsed_ns` since the last +/// callback: its position alone cannot tell a lap from no advance, or two laps +/// from one. The DMA runs at the sense rate and its reported position lags it +/// by less than a ring period, so a lap needs at least the ring's time less a +/// period. +fn sense_ring_may_lap(elapsed_ns: i64) -> bool { + elapsed_ns < 0 || elapsed_ns as u64 + SENSE_RING_PERIOD_NS >= SENSE_RING_NS +} + +/// Returns whether `incoming` frames fit strictly inside the capture front-end +/// ring buffer of `buffer_frames` without overwriting unread frames +/// (`unread_alsa`) or frames already copied since the last pointer sync +/// (`pending`), and without advancing the modulo pointer back to the same +/// position (an exact full-buffer advance is ambiguous to ALSA's pointer check). +fn sense_ring_has_fe_space( + buffer_frames: usize, + unread_alsa: usize, + pending: usize, + incoming: usize, +) -> bool { + unread_alsa + .checked_add(pending) + .and_then(|used| used.checked_add(incoming)) + .is_some_and(|total| total < buffer_frames) +} + +/// The driver-owned speaker sense capture (base-ns ADMAC RX): a cyclic ring +/// armed on the stopped serializer before every `pwrd`, so ring offset 0 is +/// slot 0 of a frame and every whole-frame offset is a frame start. The sense +/// front-end copies whole frames out of this ring instead of starting or +/// stopping the ADMAC channel while the serializer runs, which otherwise slips +/// the V/I sense slots modulo the channel count. +/// +/// The ring fields change only with the channel stopped and synchronized (no +/// callback runs); `start` publishes them before the channel starts. +struct SenseRing { + frame_bytes: usize, + chan: AtomicPtr, + cpu: AtomicPtr, + handle: AtomicU64, + cookie: AtomicI32, + /// Ring offset (a whole frame) up to which the callback has consumed the data. + done: AtomicUsize, + /// When `done` was last moved (or the ring started), CLOCK_MONOTONIC ns. + done_at: AtomicI64, + /// True while a cyclic transfer is active; cleared before terminating the + /// channel so `sense_ring_done` never consumes a terminated channel's + /// zero-residue status. + active: AtomicBool, + /// The attached sense front-end, or null; cleared under that front-end's + /// stream lock, which the callback holds while it uses the front-end. + sub: AtomicPtr, + /// Frames delivered to the front-end since its start; changed under its + /// stream lock. + fe_pos: AtomicUsize, + /// The front-end runs (its trigger sets this under the stream lock). + fe_running: AtomicBool, +} + +impl SenseRing { + fn new(frame_bytes: usize) -> Self { + Self { + frame_bytes, + chan: AtomicPtr::new(ptr::null_mut()), + cpu: AtomicPtr::new(ptr::null_mut()), + handle: AtomicU64::new(0), + cookie: AtomicI32::new(0), + done: AtomicUsize::new(0), + done_at: AtomicI64::new(0), + active: AtomicBool::new(false), + sub: AtomicPtr::new(ptr::null_mut()), + fe_pos: AtomicUsize::new(0), + fe_running: AtomicBool::new(false), + } + } + + fn period_bytes(&self) -> usize { + SENSE_RING_PERIOD_FRAMES * self.frame_bytes + } + + fn ring_bytes(&self) -> usize { + SENSE_RING_FRAMES * self.frame_bytes + } + + /// Requests the channel and the ring (once per speaker session) and starts + /// the cyclic transfer. The caller holds `spkr_state` with the fabric + /// powered and the serializer stopped (`pw0 `). + fn start(&self, dev: &device::Device) -> Result<()> { + let ring_bytes = self.ring_bytes(); + let period_bytes = self.period_bytes(); + let mut chan = self.chan.load(Ordering::Acquire); + if chan.is_null() { + // SAFETY: the device is live and the name is NUL-terminated. + chan = from_err_ptr(unsafe { + bindings::dma_request_chan(dev.as_raw(), c"sense".as_char_ptr()) + })?; + let mut handle: bindings::dma_addr_t = 0; + // SAFETY: the channel's device is the ADMAC; it outlives the ring, + // which `release` frees before releasing the channel. + let cpu = unsafe { + bindings::dma_alloc_attrs( + (*(*chan).device).dev, + ring_bytes, + &mut handle, + bindings::GFP_KERNEL, + 0, + ) + }; + if cpu.is_null() { + // SAFETY: requested above, unused. + unsafe { bindings::dma_release_channel(chan) }; + return Err(ENOMEM); + } + self.cpu.store(cpu.cast(), Ordering::Release); + self.handle.store(handle as u64, Ordering::Release); + self.chan.store(chan, Ordering::Release); + } + let handle = self.handle.load(Ordering::Acquire) as bindings::dma_addr_t; + let mut cfg = bindings::dma_slave_config::default(); + cfg.direction = bindings::dma_transfer_direction_DMA_DEV_TO_MEM; + cfg.src_addr_width = bindings::dma_slave_buswidth_DMA_SLAVE_BUSWIDTH_2_BYTES; + cfg.src_port_window_size = 4; + // SAFETY: `chan` is our live, stopped channel; the descriptor is ours + // until submitted. + unsafe { + let dma = (*chan).device; + let ret = match (*dma).device_config { + Some(f) => f(chan, &mut cfg), + None => ENOSYS.to_errno(), + }; + if ret < 0 { + return Err(Error::from_errno(ret)); + } + let prep = (*dma).device_prep_dma_cyclic.ok_or(ENOSYS)?; + let desc = prep( + chan, + handle, + ring_bytes, + period_bytes, + bindings::dma_transfer_direction_DMA_DEV_TO_MEM, + bindings::dma_ctrl_flags_DMA_PREP_INTERRUPT as _, + ); + if desc.is_null() { + return Err(EIO); + } + (*desc).callback = Some(sense_ring_done); + (*desc).callback_param = ptr::from_ref(self).cast_mut().cast(); + self.done.store(0, Ordering::Release); + // SAFETY: no preconditions. + self.done_at.store(bindings::ktime_get(), Ordering::Release); + let cookie = ((*desc).tx_submit.ok_or(EIO)?)(desc); + if cookie < 0 { + return Err(Error::from_errno(cookie)); + } + self.cookie.store(cookie, Ordering::Release); + if let Some(f) = (*dma).device_issue_pending { + self.active.store(true, Ordering::Release); + f(chan); + } + } + Ok(()) + } + + /// Stops the transfer and waits for its callback; a no-op without a channel. + fn stop(&self) { + self.active.store(false, Ordering::Release); + let chan = self.chan.load(Ordering::Acquire); + if chan.is_null() { + return; + } + // SAFETY: our live channel; terminate and synchronize are valid on an + // idle channel too. + unsafe { + let dma = (*chan).device; + if let Some(f) = (*dma).device_terminate_all { + f(chan); + } + if let Some(f) = (*dma).device_synchronize { + f(chan); + } + } + } + + /// Stops, then frees the ring and releases the channel (with the fabric + /// still powered). + fn release(&self) { + self.stop(); + let chan = self.chan.swap(ptr::null_mut(), Ordering::AcqRel); + if chan.is_null() { + return; + } + // SAFETY: the transfer is stopped and synchronized; the ring was + // allocated on this channel's device in `start`. + unsafe { + bindings::dma_free_attrs( + (*(*chan).device).dev, + self.ring_bytes(), + self.cpu.swap(ptr::null_mut(), Ordering::AcqRel).cast(), + self.handle.load(Ordering::Acquire) as bindings::dma_addr_t, + 0, + ); + bindings::dma_release_channel(chan); + } + } + + fn attach(&self, substream: *mut bindings::snd_pcm_substream) { + self.fe_running.store(false, Ordering::Relaxed); + self.fe_pos.store(0, Ordering::Relaxed); + self.sub.store(substream, Ordering::Release); + } + + /// Detaches the front-end under its stream lock: a callback that read the + /// pointer before takes the same lock, sees the front-end gone and leaves + /// it alone. + /// + /// # Safety + /// + /// `substream` must be the attached front-end, in its close. + unsafe fn detach(&self, substream: *mut bindings::snd_pcm_substream) { + // SAFETY: by the caller's contract. + unsafe { + let flags = bindings::_snd_pcm_stream_lock_irqsave(substream); + self.sub.store(ptr::null_mut(), Ordering::Release); + self.fe_running.store(false, Ordering::Relaxed); + bindings::snd_pcm_stream_unlock_irqrestore(substream, flags); + } + } + + /// Copies `bytes` (whole frames) from ring offset `from` into a running + /// front-end's buffer. + /// + /// # Safety + /// + /// `sub` must be a substream this ring had attached. The substream itself + /// belongs to the PCM and outlives the ring's use of it: the ring stops + /// and synchronizes with this callback before the card can go away. + unsafe fn deliver( + &self, + sub: *mut bindings::snd_pcm_substream, + from: usize, + bytes: usize, + last_ns: i64, + ) { + let frame_bytes = self.frame_bytes; + let ring_bytes = self.ring_bytes(); + // SAFETY: by the caller's contract; the stream lock orders this with + // the trigger, the pointer callback and `detach`. + let flags = unsafe { bindings::_snd_pcm_stream_lock_irqsave(sub) }; + let rt = if self.sub.load(Ordering::Acquire) == sub { + // SAFETY: still attached under the lock; the runtime lives until + // after the front-end's close. + unsafe { (*sub).runtime } + } else { + ptr::null_mut() + }; + // SAFETY: an attached front-end's runtime (see above). + if !rt.is_null() + && self.fe_running.load(Ordering::Relaxed) + && unsafe { (*rt).state } == PCM_STATE_RUNNING + && unsafe { (*rt).frame_bits } as usize == frame_bytes * 8 + { + // SAFETY: no preconditions. + if sense_ring_may_lap(unsafe { bindings::ktime_get() } - last_ns) { + // SAFETY: a running front-end, under its stream lock. + unsafe { bindings::snd_pcm_stop(sub, PCM_STATE_XRUN) }; + } else { + // SAFETY: as above; status and control are valid while running. + let (area, frames, period, hw_ptr, appl_ptr, boundary) = unsafe { + ( + (*rt).dma_area, + (*rt).buffer_size as usize, + (*rt).period_size as usize, + (*(*rt).status).hw_ptr as usize, + (*(*rt).control).appl_ptr as usize, + (*rt).boundary as usize, + ) + }; + let ring = self.cpu.load(Ordering::Acquire); + let incoming = bytes / frame_bytes; + if !area.is_null() && !ring.is_null() && frames > 0 && incoming > 0 { + let mut pos = self.fe_pos.load(Ordering::Relaxed); + let unread_alsa = if hw_ptr >= appl_ptr { + hw_ptr - appl_ptr + } else if boundary > 0 { + hw_ptr + boundary - appl_ptr + } else { + frames + }; + let pending = (pos % frames + frames - hw_ptr % frames) % frames; + if !sense_ring_has_fe_space(frames, unread_alsa, pending, incoming) { + // SAFETY: a running front-end, under its stream lock. + unsafe { bindings::snd_pcm_stop(sub, PCM_STATE_XRUN) }; + } else { + let first = pos; + let mut src = from; + let mut left = incoming; + while left > 0 { + let off = pos % frames; + let n = left.min(frames - off).min((ring_bytes - src) / frame_bytes); + // SAFETY: `n` frames fit at `off` in the front-end + // buffer and at `src` in the ring; post-copy lap + // validation below rejects the batch if DMA could + // have reached `from` before the copy finished. + unsafe { + ptr::copy_nonoverlapping( + ring.add(src), + area.add(off * frame_bytes), + n * frame_bytes, + ) + }; + pos += n; + left -= n; + src = (src + n * frame_bytes) % ring_bytes; + } + fence(Ordering::Acquire); + // SAFETY: no preconditions. + if sense_ring_may_lap(unsafe { bindings::ktime_get() } - last_ns) { + // SAFETY: a running front-end, under its stream lock. + unsafe { bindings::snd_pcm_stop(sub, PCM_STATE_XRUN) }; + } else { + self.fe_pos.store(pos, Ordering::Relaxed); + if first / period.max(1) != pos / period.max(1) { + // SAFETY: a running, attached front-end, under its stream lock. + unsafe { bindings::snd_pcm_period_elapsed_under_stream_lock(sub) }; + } + } + } + } + } + } + // SAFETY: locked above. + unsafe { bindings::snd_pcm_stream_unlock_irqrestore(sub, flags) }; + } + + /// The ring may have lapped since the last callback: stop a running + /// front-end with an XRUN rather than delivering frames shifted in time + /// against playback. + /// + /// # Safety + /// + /// As for [`SenseRing::deliver`]. + unsafe fn lost(&self, sub: *mut bindings::snd_pcm_substream) { + // SAFETY: as in `deliver`. + let flags = unsafe { bindings::_snd_pcm_stream_lock_irqsave(sub) }; + if self.sub.load(Ordering::Acquire) == sub && self.fe_running.load(Ordering::Relaxed) { + // SAFETY: an attached front-end, under its stream lock; its + // runtime lives until after its close. + let rt = unsafe { (*sub).runtime }; + // SAFETY: as above. + if !rt.is_null() && unsafe { (*rt).state } == PCM_STATE_RUNNING { + // SAFETY: a running front-end, under its stream lock. + unsafe { bindings::snd_pcm_stop(sub, PCM_STATE_XRUN) }; + } + } + // SAFETY: locked above. + unsafe { bindings::snd_pcm_stream_unlock_irqrestore(sub, flags) }; + } +} + +/// The ring's period callback (the ADMAC tasklet): hands the whole frames +/// written since the last call to a running sense front-end, or drops them. +/// +/// # Safety +/// +/// `param` is the `SenseRing` that set up the transfer; `stop` synchronizes +/// with this callback before the ring changes or goes away. +unsafe extern "C" fn sense_ring_done(param: *mut c_void) { + // SAFETY: by the function's contract. + let ring = unsafe { &*param.cast::() }; + if !ring.active.load(Ordering::Acquire) { + return; + } + let chan = ring.chan.load(Ordering::Acquire); + if chan.is_null() { + return; + } + let mut state = bindings::dma_tx_state { + last: 0, + used: 0, + residue: 0, + in_flight_bytes: 0, + }; + // SAFETY: our live channel and cookie. + let status = unsafe { + match (*(*chan).device).device_tx_status { + Some(f) => f(chan, ring.cookie.load(Ordering::Acquire), &mut state), + None => return, + } + }; + if !ring.active.load(Ordering::Acquire) { + return; + } + // SAFETY: no preconditions. + let now_ns = unsafe { bindings::ktime_get() }; + let ring_bytes = ring.ring_bytes(); + let frame_bytes = ring.frame_bytes; + let residue = state.residue as usize; + if status == bindings::dma_status_DMA_ERROR || residue > ring_bytes { + return; + } + // The device wrote everything up to here before it reported the residue. + fence(Ordering::SeqCst); + let now = (ring_bytes - residue) % ring_bytes / frame_bytes * frame_bytes; + let from = ring.done.swap(now, Ordering::AcqRel); + let last_ns = ring.done_at.swap(now_ns, Ordering::AcqRel); + let sub = ring.sub.load(Ordering::Acquire); + if sense_ring_may_lap(now_ns - last_ns) { + if !sub.is_null() { + // SAFETY: a substream the ring had attached (`lost` re-checks under its lock). + unsafe { ring.lost(sub) }; + } + return; + } + let bytes = (now + ring_bytes - from) % ring_bytes; + if bytes == 0 { + return; + } + if !sub.is_null() { + // SAFETY: a substream the ring had attached (`deliver` re-checks under its lock). + unsafe { ring.deliver(sub, from, bytes, last_ns) }; + } +} + #[pin_data] struct T8152AopAudio { dev: ARef, @@ -235,10 +806,12 @@ struct T8152AopAudio { cout: Service, cin: Service, spkr: Service, + #[pin] + spkr_state: Mutex, + /// Driver-owned cyclic sense ring when the speaker stream returns V/I sense. + sense_ring: Option, mca: KVec, cfg: &'static HwConfig, - /// The open sense capture front-end, if any. - sense: Atomic<*mut bindings::snd_pcm_substream>, hpai: Service, /// The microphone array's leaves (`LEAP_NAMES`); empty without one. leap: KVec, @@ -404,66 +977,137 @@ impl T8152AopAudio { Ok(()) } - /// The sense capture's back-end. Its front-end requests the ADMAC - /// channel next, and the ADMAC only answers while the firmware holds - /// the audio fabric up, which it does while a service is in `pw0 ` or - /// `pwrd`. Opening the sense before any other stream since boot (as - /// speakersafetyd does) otherwise faults the bus (SError). Shutdown - /// leaves the service in `pw0 `, as the other streams do. + /// The sense capture's back-end. Opening the sense before any other stream + /// since boot attaches `spkr` and raises `pw0 ` so the audio fabric is up + /// without disturbing an already-running speaker stream. fn sense_startup(&self) -> Result<()> { + let mut st = self.spkr_state.lock(); self.attach(&self.spkr)?; - if !self.spkr.running.load(Relaxed) { + if !st.running { + st.pw0_verified = false; self.set_power(&self.spkr, POWER_STATE_PW0)?; + st.pw0_verified = true; } Ok(()) } - /// `pwrd`: the firmware starts the serializer clocks and the stream. - fn run(&self, svc: &Service) -> Result<()> { - if svc.running.load(Relaxed) { - return Ok(()); - } - if ptr::eq(svc, &self.spkr) && self.cfg.realign_sense { - self.realign_sense(); + fn spkr_startup(&self) -> Result<()> { + let mut st = self.spkr_state.lock(); + self.attach(&self.spkr)?; + st.pw0_verified = false; + self.set_power(&self.spkr, POWER_STATE_PW0)?; + if let Err(e) = self.mca_up() { + let _ = self.set_power(&self.spkr, POWER_STATE_PW0); + return Err(e); } - self.set_power(svc, POWER_STATE_PWRD)?; - svc.running.store(true, Relaxed); + st.open = true; + st.running = false; + st.pw0_verified = true; + st.resume_run = false; + self.spkr.running.store(false, Relaxed); Ok(()) } - /// Before the speaker's serializer starts, restart a running sense - /// capture at a frame boundary. The sense words are the serializer's RX, - /// which the firmware stops anywhere in a frame; a capture that stays - /// open across speaker streams (speakersafetyd keeps it) would carry - /// the partial frame forward and attribute one amplifier's voltage and - /// current to another. Nothing flows while the serializer is stopped, - /// so this loses no data; the partial frame reads as zeros. - fn realign_sense(&self) { - let ss = self.sense.load(Relaxed); - if ss.is_null() { - return; + /// Speaker prepare: when a sense ring is in use, every playback prepare + /// starts a fresh serializer with the ring armed first so offset 0 is slot + /// 0 of a frame. If the serializer was still running or its `pw0 ` state is + /// unconfirmed (re-prepare after an underrun, failed stop, or resume), + /// `quiesce` mutes the amps before stopping the clock. + fn spkr_prepare(&self, quiesce: impl FnOnce() -> Result<()>) -> Result<()> { + let mut st = self.spkr_state.lock(); + let Some(ring) = &self.sense_ring else { + if !st.running { + st.pw0_verified = false; + self.set_power(&self.spkr, POWER_STATE_PWRD)?; + st.running = true; + self.spkr.running.store(true, Relaxed); + } + return Ok(()); + }; + st.prepare_with_ring( + &self.spkr.running, + quiesce, + || self.set_power(&self.spkr, POWER_STATE_PW0), + || ring.stop(), + || ring.start(&self.dev), + || self.set_power(&self.spkr, POWER_STATE_PWRD), + ) + } + + fn spkr_pw0(&self) -> Result<()> { + if let Err(e) = self.set_power(&self.spkr, POWER_STATE_PW0) { + dev_err!(self.dev, "spkr: pw0 failed: {:?}\n", e); + return Err(e); } - // SAFETY: the sense front-end's open and close and this back-end's - // prepare all run under the card's DPCM mutex, so `ss` is live; its - // stream lock orders this against the front-end's trigger. - unsafe { - bindings::snd_pcm_stream_lock_irq(ss); - let rt = (*ss).runtime; - if !rt.is_null() && (*rt).state == SNDRV_PCM_STATE_RUNNING { - let chan = bindings::snd_dmaengine_pcm_get_chan(ss); - let ops = &*(*chan).device; - if let (Some(pause), Some(resume)) = (ops.device_pause, ops.device_resume) { - pause(chan); - let frame = ((*rt).frame_bits / 8) as usize; - let pos = bindings::snd_dmaengine_pcm_pointer(ss) as usize; - if frame != 0 && pos < (*rt).buffer_size as usize && !(*rt).dma_area.is_null() { - ptr::write_bytes((*rt).dma_area.add(pos * frame), 0, frame); - } - resume(chan); + Ok(()) + } + + fn spkr_stop_locked(&self, st: &mut SpkrState) -> Result<()> { + st.stop( + &self.spkr.running, + self.sense_ring.is_some(), + || self.spkr_pw0(), + || { + if let Some(ring) = &self.sense_ring { + ring.stop(); } + }, + ) + } + + fn spkr_hw_free(&self) -> Result<()> { + if self.sense_ring.is_none() { + return Ok(()); + } + let mut st = self.spkr_state.lock(); + self.spkr_stop_locked(&mut st) + } + + fn spkr_shutdown(&self) { + { + let mut st = self.spkr_state.lock(); + let _ = self.spkr_stop_locked(&mut st); + st.open = false; + st.resume_run = false; + // Release the ring and its ADMAC channel while the fabric is still + // powered (`pw0 `) and before the MCA leaves power down. + if let Some(ring) = &self.sense_ring { + ring.release(); } - bindings::snd_pcm_stream_unlock_irq(ss); } + self.mca_down(); + } + + fn spkr_suspend(&self) -> Result<()> { + let Some(ring) = &self.sense_ring else { + return Ok(()); + }; + let mut st = self.spkr_state.lock(); + st.suspend(&self.spkr.running, true, || self.spkr_pw0(), || ring.stop()) + } + + fn spkr_resume(&self) -> Result<()> { + let Some(ring) = &self.sense_ring else { + return Ok(()); + }; + let mut st = self.spkr_state.lock(); + st.resume_with_ring( + &self.spkr.running, + || self.spkr_pw0(), + || ring.stop(), + || ring.start(&self.dev), + || self.set_power(&self.spkr, POWER_STATE_PWRD), + ) + } + + /// `pwrd`: the firmware starts the serializer clocks and the stream. + fn run(&self, svc: &Service) -> Result<()> { + if svc.running.load(Relaxed) { + return Ok(()); + } + self.set_power(svc, POWER_STATE_PWRD)?; + svc.running.store(true, Relaxed); + Ok(()) } /// The clocks run from prepare on: the codecs see a bit clock as soon @@ -550,8 +1194,6 @@ const FORMATS: u64 = bindings::BINDINGS_SNDRV_PCM_FMTBIT_S24_LE; /// SNDRV_PCM_FMTBIT_S16_LE (1 << SNDRV_PCM_FORMAT_S16_LE), which the /// bindings do not export. const FMTBIT_S16_LE: u64 = 1 << 2; -/// SNDRV_PCM_STATE_RUNNING, likewise. -const SNDRV_PCM_STATE_RUNNING: bindings::snd_pcm_state_t = 3; /// What differs between the machines: the shape of the firmware's `spkr` /// stream (ADT iop-audio-controller/audio-speaker). @@ -561,9 +1203,9 @@ struct HwConfig { /// Words the amplifiers send back on the stream's RX side (V/I sense). sense_channels: u32, sense_formats: u64, - /// The sense capture is the speaker stream's RX: restart it at a frame - /// boundary whenever the speaker starts (see `realign_sense`). - realign_sense: bool, + /// The sense capture is the speaker stream's RX: serve it from a + /// driver-owned cyclic ring armed before every `pwrd` (see `SenseRing`). + sense_ring: bool, /// The AP powers the serializer (MCA) leaves. ap_mca: bool, /// The AP powers the microphone array's LEAP leaves. Without it the @@ -577,7 +1219,7 @@ static HW_CFG_T8152: HwConfig = HwConfig { spkr_channels: 1, sense_channels: 2, sense_formats: FORMATS, - realign_sense: false, + sense_ring: false, ap_mca: true, ap_leap: true, }; @@ -589,19 +1231,19 @@ static HW_CFG_T8142: HwConfig = HwConfig { spkr_channels: 4, sense_channels: 8, sense_formats: FMTBIT_S16_LE, - realign_sense: true, + sense_ring: true, ap_mca: true, ap_leap: true, }; -/// J714s: six amplifiers in 32-bit slots 0-5, their voltage and current -/// sense back as twelve 16-bit slots on the stream's RX, as on J813. The -/// MCA and LEAP leaves have no AP power state: the firmware powers them. +/// J714s / J716c: six amplifiers in 32-bit slots 0-5, their voltage and +/// current sense back as twelve 16-bit slots on the stream's RX, as on J813. +/// The MCA and LEAP leaves have no AP power state: the firmware powers them. static HW_CFG_T6050: HwConfig = HwConfig { spkr_channels: 6, sense_channels: 12, sense_formats: FMTBIT_S16_LE, - realign_sense: true, + sense_ring: true, ap_mca: false, ap_leap: false, }; @@ -615,7 +1257,7 @@ static HW_CFG_T8142_6AMP: HwConfig = HwConfig { spkr_channels: 6, sense_channels: 12, sense_formats: FMTBIT_S16_LE, - realign_sense: true, + sense_ring: true, ap_mca: true, ap_leap: true, }; @@ -749,6 +1391,67 @@ unsafe fn dmaengine_open( } } +/// The sense ring behind a front-end substream, `None` for every other stream. +/// +/// # Safety +/// +/// `component` must be this driver's live registered component and `substream` +/// a live substream of one of its links. +unsafe fn sense_ring<'a>( + component: *mut bindings::snd_soc_component, + substream: *mut bindings::snd_pcm_substream, +) -> Option<&'a SenseRing> { + // SAFETY: by the caller's contract. + let (data, rtd) = unsafe { (component_data(component), substream_rtd(substream)) }; + // SAFETY: as above. + if unsafe { rtd_is_be(rtd) || is_playback(substream) } { + return None; + } + // SAFETY: as above. + if unsafe { fe_index(rtd) } != Some(2) { + return None; + } + data.sense_ring.as_ref() +} + +/// Hardware description for the VMALLOC sense front-end: require at least one +/// ring period per ALSA period so even the minimum two-period buffer holds +/// incoming ring batches without XRUNning on the first callback. +fn sense_pcm_hw(formats: u64, ring_period_bytes: usize) -> bindings::snd_pcm_hardware { + let mut hw = pcm_hw(); + hw.info |= bindings::SNDRV_PCM_INFO_BLOCK_TRANSFER | bindings::SNDRV_PCM_INFO_BATCH; + hw.formats = formats; + hw.period_bytes_min = hw.period_bytes_min.max(ring_period_bytes); + hw.periods_max = (hw.buffer_bytes_max / hw.period_bytes_min) as u32; + hw +} + +/// The sense front-end's buffer: plain memory the ring callback copies whole +/// frames into. +fn sense_open( + substream: *mut bindings::snd_pcm_substream, + formats: u64, + ring_period_bytes: usize, +) -> i32 { + // SAFETY: a live substream in its open. + unsafe { + if (*substream).dma_buffer.dev.type_ == bindings::SNDRV_DMA_TYPE_UNKNOWN as i32 { + let ret = bindings::snd_pcm_set_managed_buffer( + substream, + bindings::SNDRV_DMA_TYPE_VMALLOC as i32, + ptr::null_mut(), + 0, + 0, + ); + if ret < 0 { + return ret; + } + } + (*(*substream).runtime).hw = sense_pcm_hw(formats, ring_period_bytes); + } + 0 +} + /// # Safety /// /// Called by ASoC on this driver's component with live arguments. @@ -773,6 +1476,16 @@ unsafe extern "C" fn asoc_pcm_open( let Some(name) = FE_DMA_NAMES[fe][usize::from(!playback)] else { return ENODEV.to_errno(); }; + if fe == 2 && !playback { + if let Some(ring) = &data.sense_ring { + let ret = sense_open(substream, data.cfg.sense_formats, ring.period_bytes()); + if ret < 0 { + return ret; + } + ring.attach(substream); + return 0; + } + } // SAFETY: the device is live and the name is NUL-terminated. let chan = match from_err_ptr(unsafe { bindings::dma_request_chan(data.dev.as_raw(), name.as_char_ptr()) @@ -789,8 +1502,14 @@ unsafe extern "C" fn asoc_pcm_open( if ret < 0 { // SAFETY: the open failed, so the channel is still ours. unsafe { bindings::dma_release_channel(chan) }; - } else if fe == 2 && !playback { - data.sense.store(substream, Relaxed); + } else if fe == 1 && playback && data.sense_ring.is_some() { + // The playback slots line up only when prepare starts a fresh + // serializer: a paused DMA restarted mid-frame would shift them. + // SAFETY: `dmaengine_open` initialized the runtime above. + unsafe { + (*(*substream).runtime).hw.info &= + !(bindings::SNDRV_PCM_INFO_PAUSE | bindings::SNDRV_PCM_INFO_RESUME); + } } ret } @@ -807,9 +1526,10 @@ unsafe extern "C" fn asoc_pcm_close( return 0; } // SAFETY: as above. - let data = unsafe { component_data(component) }; - if data.sense.load(Relaxed) == substream { - data.sense.store(ptr::null_mut(), Relaxed); + if let Some(ring) = unsafe { sense_ring(component, substream) } { + // SAFETY: the attached sense front-end, in its close. + unsafe { ring.detach(substream) }; + return 0; } // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. unsafe { bindings::snd_dmaengine_pcm_close_release_chan(substream) } @@ -824,7 +1544,8 @@ unsafe extern "C" fn asoc_pcm_hw_params( params: *mut bindings::snd_pcm_hw_params, ) -> i32 { // SAFETY: by the caller's contract. - if unsafe { rtd_is_be(substream_rtd(substream)) } { + if unsafe { rtd_is_be(substream_rtd(substream)) || sense_ring(component, substream).is_some() } + { return 0; } // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. @@ -849,15 +1570,6 @@ unsafe extern "C" fn asoc_pcm_hw_params( } else { cfg.src_port_window_size = window; } - // The sense capture: the frame size its channel restarts aligned to - // (apple-admac reads a u32 here; see `realign_sense`). - // SAFETY: by the caller's contract. - let data = unsafe { component_data(component) }; - let mut frame_bytes = channels * cfg.src_addr_width as u32; - if ptr::eq(substream, data.sense.load(Relaxed)) && data.cfg.realign_sense { - cfg.peripheral_config = ptr::from_mut(&mut frame_bytes).cast(); - cfg.peripheral_size = mem::size_of::(); - } // SAFETY: `chan` is the live channel behind the substream. unsafe { match (*(*chan).device).device_config { @@ -871,7 +1583,7 @@ unsafe extern "C" fn asoc_pcm_hw_params( /// /// Called by ASoC on this driver's component with live arguments. unsafe extern "C" fn asoc_pcm_trigger( - _component: *mut bindings::snd_soc_component, + component: *mut bindings::snd_soc_component, substream: *mut bindings::snd_pcm_substream, cmd: i32, ) -> i32 { @@ -879,6 +1591,27 @@ unsafe extern "C" fn asoc_pcm_trigger( if unsafe { rtd_is_be(substream_rtd(substream)) } { return 0; } + // The sense attaches to the ring at its next whole frame; ALSA holds the + // stream lock, which the ring callback takes too. + // SAFETY: as above. + if let Some(ring) = unsafe { sense_ring(component, substream) } { + match cmd as u32 { + bindings::SNDRV_PCM_TRIGGER_START => { + ring.fe_pos.store(0, Ordering::Relaxed); + ring.fe_running.store(true, Ordering::Relaxed); + } + bindings::SNDRV_PCM_TRIGGER_RESUME | bindings::SNDRV_PCM_TRIGGER_PAUSE_RELEASE => { + ring.fe_running.store(true, Ordering::Relaxed); + } + bindings::SNDRV_PCM_TRIGGER_STOP + | bindings::SNDRV_PCM_TRIGGER_SUSPEND + | bindings::SNDRV_PCM_TRIGGER_PAUSE_PUSH => { + ring.fe_running.store(false, Ordering::Relaxed); + } + _ => return EINVAL.to_errno(), + } + return 0; + } // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. unsafe { bindings::snd_dmaengine_pcm_trigger(substream, cmd) } } @@ -889,11 +1622,12 @@ unsafe extern "C" fn asoc_pcm_trigger( /// /// Called by ASoC on this driver's component with a live substream. unsafe extern "C" fn asoc_pcm_sync_stop( - _component: *mut bindings::snd_soc_component, + component: *mut bindings::snd_soc_component, substream: *mut bindings::snd_pcm_substream, ) -> i32 { // SAFETY: by the caller's contract. - if unsafe { rtd_is_be(substream_rtd(substream)) } { + if unsafe { rtd_is_be(substream_rtd(substream)) || sense_ring(component, substream).is_some() } + { return 0; } // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. @@ -904,13 +1638,20 @@ unsafe extern "C" fn asoc_pcm_sync_stop( /// /// Called by ASoC on this driver's component with live arguments. unsafe extern "C" fn asoc_pcm_pointer( - _component: *mut bindings::snd_soc_component, + component: *mut bindings::snd_soc_component, substream: *mut bindings::snd_pcm_substream, ) -> bindings::snd_pcm_uframes_t { // SAFETY: by the caller's contract. if unsafe { rtd_is_be(substream_rtd(substream)) } { return (-i64::from(bindings::ENOTSUPP)) as bindings::snd_pcm_uframes_t; } + // SAFETY: as above; ALSA calls this under the stream lock with a live runtime. + if let Some(ring) = unsafe { sense_ring(component, substream) } { + // SAFETY: as above. + let frames = unsafe { (*(*substream).runtime).buffer_size } as usize; + return (ring.fe_pos.load(Ordering::Relaxed) % frames.max(1)) + as bindings::snd_pcm_uframes_t; + } // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. unsafe { bindings::snd_dmaengine_pcm_pointer(substream) } } @@ -976,6 +1717,31 @@ unsafe fn be_service<'a>( Some((data, svc)) } +/// Mutes a back-end's codecs (the amps); `__soc_pcm_prepare` unmutes them right +/// after `be_prepare`. +/// +/// # Safety +/// +/// `rtd` must be a live back-end runtime, in its prepare. +unsafe fn mute_codecs(rtd: *mut bindings::snd_soc_pcm_runtime) -> Result<()> { + // SAFETY: by the caller's contract; the codec DAIs follow the CPU DAIs in `dais`. + unsafe { + let link = (*rtd).dai_link; + let cpus = (*link).num_cpus as usize; + for i in 0..(*link).num_codecs as usize { + let ret = bindings::snd_soc_dai_digital_mute( + *(*rtd).dais.add(cpus + i), + 1, + bindings::SNDRV_PCM_STREAM_PLAYBACK as i32, + ); + if ret < 0 { + return Err(Error::from_errno(ret)); + } + } + } + Ok(()) +} + /// # Safety /// /// Called by ASoC with a live DAI of this component and a live substream. @@ -995,7 +1761,12 @@ unsafe extern "C" fn be_startup( } return 0; }; - match data.startup(svc) { + let res = if ptr::eq(svc, &data.spkr) { + data.spkr_startup() + } else { + data.startup(svc) + }; + match res { Ok(()) => 0, Err(e) => e.to_errno(), } @@ -1012,12 +1783,36 @@ unsafe extern "C" fn be_prepare( let Some((data, svc)) = (unsafe { be_service(dai, substream) }) else { return 0; }; - match data.prepare(svc) { + let res = if ptr::eq(svc, &data.spkr) { + // SAFETY: the back-end runtime of this substream is live for the call. + data.spkr_prepare(|| unsafe { mute_codecs(substream_rtd(substream)) }) + } else { + data.prepare(svc) + }; + match res { Ok(()) => 0, Err(e) => e.to_errno(), } } +/// # Safety +/// +/// Called by ASoC with a live DAI of this component and a live substream. +unsafe extern "C" fn be_hw_free( + substream: *mut bindings::snd_pcm_substream, + dai: *mut bindings::snd_soc_dai, +) -> i32 { + // SAFETY: by the caller's contract. + if let Some((data, svc)) = unsafe { be_service(dai, substream) } { + if ptr::eq(svc, &data.spkr) { + if let Err(e) = data.spkr_hw_free() { + return e.to_errno(); + } + } + } + 0 +} + /// # Safety /// /// Called by ASoC with a live DAI of this component and a live substream. @@ -1027,7 +1822,33 @@ unsafe extern "C" fn be_shutdown( ) { // SAFETY: by the caller's contract. if let Some((data, svc)) = unsafe { be_service(dai, substream) } { - data.shutdown(svc); + if ptr::eq(svc, &data.spkr) { + data.spkr_shutdown(); + } else { + data.shutdown(svc); + } + } +} + +/// # Safety +/// +/// Called by ASoC on this driver's registered component. +unsafe extern "C" fn asoc_suspend(component: *mut bindings::snd_soc_component) -> i32 { + // SAFETY: by the caller's contract. + match unsafe { component_data(component) }.spkr_suspend() { + Ok(()) => 0, + Err(e) => e.to_errno(), + } +} + +/// # Safety +/// +/// Called by ASoC on this driver's registered component. +unsafe extern "C" fn asoc_resume(component: *mut bindings::snd_soc_component) -> i32 { + // SAFETY: by the caller's contract. + match unsafe { component_data(component) }.spkr_resume() { + Ok(()) => 0, + Err(e) => e.to_errno(), } } @@ -1049,6 +1870,7 @@ impl DaiOps { be: bindings::snd_soc_dai_ops { startup: Some(be_startup), prepare: Some(be_prepare), + hw_free: Some(be_hw_free), shutdown: Some(be_shutdown), ..fe }, @@ -1133,6 +1955,8 @@ impl AsocContext { let dais = KBox::new(Opaque::new(dai_drivers(&ops, data.cfg)), GFP_KERNEL)?; let component = bindings::snd_soc_component_driver { name: c"t8152-aop-audio".as_char_ptr(), + suspend: Some(asoc_suspend), + resume: Some(asoc_resume), open: Some(asoc_pcm_open), close: Some(asoc_pcm_close), hw_params: Some(asoc_pcm_hw_params), @@ -1530,6 +2354,9 @@ impl platform::Driver for T8152AopAudioDriver { .is_some_and(|node| node.property_match_string(c"dma-names", c"hpai").is_ok()) }; + let sense_ring = cfg + .sense_ring + .then(|| SenseRing::new(cfg.sense_channels as usize * 2)); let data_dev = dev.clone(); let data = Arc::pin_init( pin_init!(T8152AopAudio { @@ -1539,9 +2366,10 @@ impl platform::Driver for T8152AopAudioDriver { cout: Service::new(from_fourcc(b"cout"), "cout", true), cin: Service::new(from_fourcc(b"cin "), "cin", true), spkr: Service::new(from_fourcc(b"spkr"), "spkr", false), + spkr_state <- new_mutex!(SpkrState::new()), + sense_ring, mca, cfg, - sense: Atomic::new(ptr::null_mut()), hpai: Service::new(from_fourcc(b"hpai"), "hpai", false), leap, hpai_want_run: AtomicFlag::new(false), @@ -1597,6 +2425,9 @@ impl platform::Driver for T8152AopAudioDriver { fn unbind(_dev: &platform::Device>, this: Pin<&Self>) { this.unregister(); + if let Some(ring) = &this.asoc.data.sense_ring { + ring.release(); + } } } @@ -1606,3 +2437,427 @@ module_platform_driver! { description: "Apple T8152 AOP audio: headphone jack, speakers and microphones", license: "Dual MIT/GPL", } + +#[kunit_tests(snd_soc_apple_t8152_aop_audio)] +mod tests { + use super::*; + + const fn frames_ns(frames: u64) -> i64 { + (frames * NSEC_PER_SEC / SENSE_RATE) as i64 + } + + #[test] + fn sense_ring_lap_detection() { + let ring_frames = SENSE_RING_FRAMES as u64; + let period_frames = SENSE_RING_PERIOD_FRAMES as u64; + + assert!(!sense_ring_may_lap(0)); + assert!(!sense_ring_may_lap(frames_ns(period_frames))); + assert!(!sense_ring_may_lap(frames_ns(ring_frames / 2))); + assert!(!sense_ring_may_lap( + frames_ns(ring_frames - period_frames) - 1 + )); + + assert!(sense_ring_may_lap(frames_ns(ring_frames - period_frames))); + assert!(sense_ring_may_lap(frames_ns(ring_frames))); + assert!(sense_ring_may_lap(frames_ns( + 2 * ring_frames + period_frames + ))); + assert!(sense_ring_may_lap(-1)); + } + + #[test] + fn sense_ring_geometry_covers_8ch_and_12ch() { + assert_eq!(SENSE_RING_NS, 80_000_000); + assert_eq!(SENSE_RING_PERIOD_NS, 2_500_000); + + // T8142 4-amp (8ch S16_LE = 16 B/frame) and T8142 6-amp / T6050 (12ch S16_LE = 24 B/frame) + for ch in [HW_CFG_T8142.sense_channels, HW_CFG_T6050.sense_channels] { + let frame = ch as usize * 2; + let ring = SenseRing::new(frame); + assert_eq!(ring.period_bytes() % frame, 0); + assert_eq!(ring.ring_bytes() % ring.period_bytes(), 0); + // Whole multiples of the ADMAC RX FIFO threshold (0x18 * 2 = 48 B) + assert_eq!(ring.period_bytes() % 48, 0); + } + } + + #[test] + fn sense_ring_fe_space_guards_overrun() { + // Every supported multi-amp geometry constrains ALSA negotiation so the + // smallest admitted buffer (2 periods of period_bytes_min) exceeds one + // 120-frame ring batch and cannot XRUN on an empty capture buffer. + for cfg in [&HW_CFG_T8142, &HW_CFG_T8142_6AMP, &HW_CFG_T6050] { + let frame = cfg.sense_channels as usize * 2; + let ring = SenseRing::new(frame); + let hw = sense_pcm_hw(cfg.sense_formats, ring.period_bytes()); + assert_eq!(hw.period_bytes_min, ring.period_bytes()); + assert!(hw.period_bytes_min <= hw.period_bytes_max); + assert_eq!(hw.periods_min, 2); + assert!(hw.periods_min <= hw.periods_max); + let min_period_frames = hw.period_bytes_min / frame; + let min_buffer_frames = hw.periods_min as usize * min_period_frames; + assert_eq!(min_period_frames, SENSE_RING_PERIOD_FRAMES); + assert_eq!(min_buffer_frames, 2 * SENSE_RING_PERIOD_FRAMES); + assert!(sense_ring_has_fe_space( + min_buffer_frames, + 0, + 0, + SENSE_RING_PERIOD_FRAMES + )); + assert!(!sense_ring_has_fe_space( + min_buffer_frames, + SENSE_RING_PERIOD_FRAMES, + 0, + SENSE_RING_PERIOD_FRAMES + )); + } + + // Exact full-buffer advance (e.g. 120 frames into a 120-frame buffer) wraps the + // modulo pointer back to the same offset, so it must trigger XRUN; strictly less fits. + assert!(!sense_ring_has_fe_space(120, 0, 0, 120)); + assert!(sense_ring_has_fe_space(121, 0, 0, 120)); + assert!(!sense_ring_has_fe_space(121, 1, 0, 120)); + assert!(!sense_ring_has_fe_space(121, 0, 1, 120)); + // Coalesced callbacks exceeding remaining space after unread + pending frames trigger XRUN + assert!(sense_ring_has_fe_space(1024, 512, 120, 240)); + assert!(!sense_ring_has_fe_space(1024, 512, 240, 360)); + // Overflow in unread + pending + incoming fails closed + assert!(!sense_ring_has_fe_space(1024, usize::MAX, 0, 1)); + } + + #[test] + fn spkr_state_requires_verified_pw0_before_rearm() { + use core::cell::Cell; + + let spkr_running = AtomicFlag::new(false); + let ring_starts = Cell::new(0u32); + let ring_stops = Cell::new(0u32); + let pw0_calls = Cell::new(0u32); + let quiesce_calls = Cell::new(0u32); + + let mut st = SpkrState { + open: true, + running: false, + pw0_verified: true, + resume_run: false, + }; + + // Initial prepare arms ring and enters running (`pw0_verified` clears). + assert!(st + .prepare_with_ring( + &spkr_running, + || { + quiesce_calls.set(quiesce_calls.get() + 1); + Ok(()) + }, + || { + pw0_calls.set(pw0_calls.get() + 1); + Ok(()) + }, + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Ok(()), + ) + .is_ok()); + assert!(st.running); + assert!(!st.pw0_verified); + assert!(spkr_running.load(Relaxed)); + assert_eq!(ring_starts.get(), 1); + assert_eq!(pw0_calls.get(), 0); + + // If AOP rejects `pw0 ` on stop (`hw_free` / `suspend`), running stays + // true, `pw0_verified` stays false, and DMA is not stopped. + let stops_before = ring_stops.get(); + assert_eq!( + st.stop( + &spkr_running, + true, + || Err(EIO), + || ring_stops.set(ring_stops.get() + 1), + ), + Err(EIO) + ); + assert!(st.running); + assert!(!st.pw0_verified); + assert!(spkr_running.load(Relaxed)); + assert_eq!(ring_stops.get(), stops_before); + + // Next prepare fails closed if `pw0 ` still fails, without rearming RX. + assert_eq!( + st.prepare_with_ring( + &spkr_running, + || { + quiesce_calls.set(quiesce_calls.get() + 1); + Ok(()) + }, + || Err(EIO), + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Ok(()), + ), + Err(EIO) + ); + assert_eq!(quiesce_calls.get(), 1); + assert_eq!(ring_starts.get(), 1); + assert!(st.running); + + // Even if `resume_run` were set while `pw0 ` is unverified and `pw0 ` + // still fails on resume, resume fails closed without arming RX. + st.resume_run = true; + assert_eq!( + st.resume_with_ring( + &spkr_running, + || Err(EIO), + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Ok(()), + ), + Err(EIO) + ); + assert_eq!(ring_starts.get(), 1); + + // Once `pw0 ` succeeds, prepare verifies it and rearms the ring cleanly. + assert!(st + .prepare_with_ring( + &spkr_running, + || { + quiesce_calls.set(quiesce_calls.get() + 1); + Ok(()) + }, + || { + pw0_calls.set(pw0_calls.get() + 1); + Ok(()) + }, + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Ok(()), + ) + .is_ok()); + assert_eq!(pw0_calls.get(), 1); + assert_eq!(ring_starts.get(), 2); + assert!(st.running); + + // Suspend with failed `pw0 ` stops RX and records restart intent so + // resume must verify `pw0 ` before rearming. + let stops_before = ring_stops.get(); + assert_eq!( + st.suspend( + &spkr_running, + true, + || Err(EIO), + || ring_stops.set(ring_stops.get() + 1), + ), + Err(EIO) + ); + assert_eq!(ring_stops.get(), stops_before + 1); + assert!(st.resume_run); + assert!(st.running); + assert!(!st.pw0_verified); + + // Suspend with verified `pw0 ` stops DMA, then resume restarts cleanly + // without an extra `pw0 ` call. + assert!(st + .suspend( + &spkr_running, + true, + || Ok(()), + || ring_stops.set(ring_stops.get() + 1), + ) + .is_ok()); + assert!(!st.running); + assert!(st.pw0_verified); + assert!(st.resume_run); + assert!(st + .resume_with_ring( + &spkr_running, + || { + pw0_calls.set(pw0_calls.get() + 1); + Ok(()) + }, + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Ok(()), + ) + .is_ok()); + assert_eq!(pw0_calls.get(), 1); + assert_eq!(ring_starts.get(), 3); + assert!(st.running); + + // An unconfirmed `pwrd` transition clears `pw0_verified` so the next + // prepare re-verifies `pw0 ` before arming RX again. + assert!(st + .stop( + &spkr_running, + true, + || Ok(()), + || ring_stops.set(ring_stops.get() + 1), + ) + .is_ok()); + assert_eq!( + st.prepare_with_ring( + &spkr_running, + || Ok(()), + || Ok(()), + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Err(EIO), + ), + Err(EIO) + ); + assert!(!st.running); + assert!(!st.pw0_verified); + assert_eq!(ring_starts.get(), 4); + assert!(st + .prepare_with_ring( + &spkr_running, + || { + quiesce_calls.set(quiesce_calls.get() + 1); + Ok(()) + }, + || { + pw0_calls.set(pw0_calls.get() + 1); + Ok(()) + }, + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Ok(()), + ) + .is_ok()); + assert_eq!(pw0_calls.get(), 2); + assert_eq!(ring_starts.get(), 5); + } + + #[test] + fn spkr_state_suspend_pw0_failure_and_resume() { + use core::cell::Cell; + + let spkr_running = AtomicFlag::new(true); + let ring_stops = Cell::new(0u32); + let ring_starts = Cell::new(0u32); + let pw0_calls = Cell::new(0u32); + let pwrd_calls = Cell::new(0u32); + + let mut st = SpkrState { + open: true, + running: true, + pw0_verified: false, + resume_run: false, + }; + + // Failed `pw0 ` during suspend still stops/synchronizes RX and records + // restart intent so resume verifies `pw0 ` before rearming. + assert_eq!( + st.suspend( + &spkr_running, + true, + || { + pw0_calls.set(pw0_calls.get() + 1); + Err(EIO) + }, + || ring_stops.set(ring_stops.get() + 1), + ), + Err(EIO) + ); + assert_eq!(pw0_calls.get(), 1); + assert_eq!(ring_stops.get(), 1); + assert!(st.running); + assert!(!st.pw0_verified); + assert!(st.resume_run); + assert!(spkr_running.load(Relaxed)); + + // Resume fails closed without rearming RX if retry `pw0 ` still fails. + assert_eq!( + st.resume_with_ring( + &spkr_running, + || { + pw0_calls.set(pw0_calls.get() + 1); + Err(EIO) + }, + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || { + pwrd_calls.set(pwrd_calls.get() + 1); + Ok(()) + }, + ), + Err(EIO) + ); + assert_eq!(pw0_calls.get(), 2); + assert_eq!(ring_starts.get(), 0); + assert_eq!(pwrd_calls.get(), 0); + assert!(st.running); + assert!(!st.pw0_verified); + assert!(!st.resume_run); + assert!(spkr_running.load(Relaxed)); + + // Another suspend with `pw0 ` failing still stops RX and records intent; + // when retry `pw0 ` succeeds on resume, RX is cleanly rearmed before `pwrd`. + assert_eq!( + st.suspend( + &spkr_running, + true, + || { + pw0_calls.set(pw0_calls.get() + 1); + Err(EIO) + }, + || ring_stops.set(ring_stops.get() + 1), + ), + Err(EIO) + ); + assert_eq!(pw0_calls.get(), 3); + assert_eq!(ring_stops.get(), 2); + assert!(st.resume_run); + + assert!(st + .resume_with_ring( + &spkr_running, + || { + pw0_calls.set(pw0_calls.get() + 1); + Ok(()) + }, + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || { + pwrd_calls.set(pwrd_calls.get() + 1); + Ok(()) + }, + ) + .is_ok()); + assert_eq!(pw0_calls.get(), 4); + assert_eq!(ring_stops.get(), 3); + assert_eq!(ring_starts.get(), 1); + assert_eq!(pwrd_calls.get(), 1); + assert!(st.running); + assert!(!st.pw0_verified); + assert!(!st.resume_run); + assert!(spkr_running.load(Relaxed)); + } +} diff --git a/sound/soc/codecs/Kconfig b/sound/soc/codecs/Kconfig index cd02d72f1e4eb0..e0be5ba78fb43e 100644 --- a/sound/soc/codecs/Kconfig +++ b/sound/soc/codecs/Kconfig @@ -1067,7 +1067,8 @@ config SND_SOC_CS42L84_TEST help This builds KUnit tests for the clock switching that the Cirrus Logic cs42l84 codec driver does when a stream is - muted or unmuted. The tests are built into the cs42l84 + muted or unmuted, and for how it writes its registers back + after a firmware sleep. The tests are built into the cs42l84 driver and run when it is loaded. For more information on KUnit and unit tests in general, diff --git a/sound/soc/codecs/cs42l84-test.c b/sound/soc/codecs/cs42l84-test.c index 4d4952a33c8485..a8c6e0b1654bf3 100644 --- a/sound/soc/codecs/cs42l84-test.c +++ b/sound/soc/codecs/cs42l84-test.c @@ -1,10 +1,11 @@ // SPDX-License-Identifier: GPL-2.0-only // -// KUnit tests for the clock switching in cs42l84_mute_stream(). +// KUnit tests for the clock switching in cs42l84_mute_stream(), and for +// writing the registers back after a firmware sleep. // // This file is included at the end of cs42l84.c when // CONFIG_SND_SOC_CS42L84_TEST is enabled, so the tests can reach the -// driver's static DAI ops and PLL configuration. +// driver's static DAI ops, PLL configuration and register write-back. // // The codec runs from its internal oscillator (RCO) while no stream is // active. Unmuting the first stream moves it onto BCLK, through the PLL @@ -517,4 +518,261 @@ static struct kunit_suite cs42l84_test_suite = { .test_cases = cs42l84_test_cases, }; -kunit_test_suite(cs42l84_test_suite); +/* + * Writing the registers back after a firmware sleep, in + * cs42l84_restore_regs(), runs on the driver's own regmap configuration: + * its cache and its volatile registers. Every bus access is logged, reads + * too, so the order of writes and status reads can be checked. + */ + +#define CS42L84_TEST_MAX_ACCESSES 128 + +struct cs42l84_test_access { + bool write; + unsigned int reg; +}; + +struct cs42l84_sleep_test_priv { + struct kunit *test; + + struct cs42l84_private cs42l84; + + /* Register contents seen by the driver */ + u8 *regs; + + /* Every bus access made by the driver, in order */ + struct cs42l84_test_access accesses[CS42L84_TEST_MAX_ACCESSES]; + unsigned int num_accesses; + + /* The codec stops answering at the first write to fail_reg */ + unsigned int fail_reg; + bool dead; + unsigned int num_dead_accesses; +}; + +static int cs42l84_sleep_test_access(struct cs42l84_sleep_test_priv *priv, + bool write, unsigned int reg) +{ + if (reg >= CS42L84_TEST_NUM_REGS) + return -EINVAL; + + if (priv->dead) { + priv->num_dead_accesses++; + return -ETIME; + } + if (write && reg == priv->fail_reg) { + priv->dead = true; + return -ETIME; + } + + if (priv->num_accesses < ARRAY_SIZE(priv->accesses)) { + priv->accesses[priv->num_accesses].write = write; + priv->accesses[priv->num_accesses].reg = reg; + priv->num_accesses++; + } else { + KUNIT_FAIL(priv->test, "access log full at reg %#x", reg); + } + + return 0; +} + +static int cs42l84_sleep_test_reg_read(void *context, unsigned int reg, unsigned int *val) +{ + struct cs42l84_sleep_test_priv *priv = context; + int ret; + + ret = cs42l84_sleep_test_access(priv, false, reg); + if (ret) + return ret; + + *val = priv->regs[reg]; + + return 0; +} + +static int cs42l84_sleep_test_reg_write(void *context, unsigned int reg, unsigned int val) +{ + struct cs42l84_sleep_test_priv *priv = context; + int ret; + + ret = cs42l84_sleep_test_access(priv, true, reg); + if (ret) + return ret; + + priv->regs[reg] = val; + + return 0; +} + +/* Set the codec up as the probe does, and some registers around plug detection */ +static void cs42l84_sleep_test_probe(struct cs42l84_sleep_test_priv *priv) +{ + struct cs42l84_private *cs42l84 = &priv->cs42l84; + + cs42l84_setup_plug_detect(cs42l84); + cs42l84_set_interrupt_masks(cs42l84, CS42L84_RS_PLUG | CS42L84_RS_UNPLUG); + + /* HSBIAS on, as a headset with a mic leaves it */ + regmap_write(cs42l84->regmap, CS42L84_MISC_DET_CTL, + FIELD_PREP(CS42L84_MISC_DET_CTL_HSBIAS_CTL, 3) | + FIELD_PREP(CS42L84_MISC_DET_CTL_DETECT_MODE, 3) | + CS42L84_MISC_DET_CTL_PDN_MIC_LVL_DET); + regmap_write(cs42l84->regmap, CS42L84_DAC_CTL1, CS42L84_DAC_CTL1_UNMUTE); +} + +/* The suspend before a firmware sleep, then the reset the codec wakes up from */ +static void cs42l84_sleep_test_sleep(struct cs42l84_sleep_test_priv *priv) +{ + struct regmap *regmap = priv->cs42l84.regmap; + + regcache_cache_only(regmap, true); + regcache_mark_dirty(regmap); + + memset(priv->regs, 0, CS42L84_TEST_NUM_REGS); + + regcache_cache_only(regmap, false); + priv->num_accesses = 0; +} + +static void cs42l84_sleep_test_expect_status_read(struct kunit *test, unsigned int i) +{ + struct cs42l84_sleep_test_priv *priv = test->priv; + + KUNIT_ASSERT_LT(test, i, priv->num_accesses); + KUNIT_EXPECT_FALSE(test, priv->accesses[i].write); + KUNIT_EXPECT_EQ(test, priv->accesses[i].reg, CS42L84_TSRS_PLUG_INT_STATUS); +} + +/* + * Plug detection goes back first, in the order cs42l84_setup_plug_detect() + * turns it on, then the remote button status is read once, then every other + * register the cache holds is written once, in address order. Each write is + * followed by a read of the plug interrupt status, and the codec ends up with + * the registers it had before the sleep. + */ +static void cs42l84_test_restore_order(struct kunit *test) +{ + struct cs42l84_sleep_test_priv *priv = test->priv; + const unsigned int n = ARRAY_SIZE(cs42l84_plug_detect_regs); + unsigned int i, reg, num_setup = 0, mismatches = 0; + u8 *before; + + cs42l84_sleep_test_probe(priv); + + /* The list is what the probe writes before it reads the tip sense */ + for (i = 0; i < priv->num_accesses; i++) { + if (!priv->accesses[i].write && + priv->accesses[i].reg == CS42L84_TSRS_PLUG_STATUS) + break; + if (!priv->accesses[i].write) + continue; + KUNIT_ASSERT_LT(test, num_setup, n); + KUNIT_EXPECT_EQ(test, priv->accesses[i].reg, + cs42l84_plug_detect_regs[num_setup]); + num_setup++; + } + KUNIT_EXPECT_EQ(test, num_setup, n); + + before = kunit_kmalloc(test, CS42L84_TEST_NUM_REGS, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, before); + memcpy(before, priv->regs, CS42L84_TEST_NUM_REGS); + + cs42l84_sleep_test_sleep(priv); + KUNIT_ASSERT_EQ(test, cs42l84_restore_regs(&priv->cs42l84), 0); + + for (i = 0; i < n; i++) { + KUNIT_ASSERT_LT(test, 2 * i, priv->num_accesses); + KUNIT_EXPECT_TRUE(test, priv->accesses[2 * i].write); + KUNIT_EXPECT_EQ(test, priv->accesses[2 * i].reg, cs42l84_plug_detect_regs[i]); + cs42l84_sleep_test_expect_status_read(test, 2 * i + 1); + } + + KUNIT_ASSERT_LT(test, 2 * n, priv->num_accesses); + KUNIT_EXPECT_FALSE(test, priv->accesses[2 * n].write); + KUNIT_EXPECT_EQ(test, priv->accesses[2 * n].reg, CS42L84_REMOTE_BUTTON_STATUS1); + + /* Registers below the plug detection ones too */ + KUNIT_ASSERT_LT(test, 2 * n + 1, priv->num_accesses); + KUNIT_EXPECT_LT(test, priv->accesses[2 * n + 1].reg, CS42L84_RING_SENSE_CTL); + + for (i = 2 * n + 1; i < priv->num_accesses; i += 2) { + reg = priv->accesses[i].reg; + KUNIT_EXPECT_TRUE(test, priv->accesses[i].write); + KUNIT_EXPECT_FALSE(test, cs42l84_is_plug_detect_reg(reg)); + KUNIT_EXPECT_FALSE(test, cs42l84_volatile_register(NULL, reg)); + if (i > 2 * n + 1) + KUNIT_EXPECT_GT(test, reg, priv->accesses[i - 2].reg); + cs42l84_sleep_test_expect_status_read(test, i + 1); + } + + for (reg = 0; reg < CS42L84_TEST_NUM_REGS; reg++) { + if (!cs42l84_volatile_register(NULL, reg) && priv->regs[reg] != before[reg]) + mismatches++; + } + KUNIT_EXPECT_EQ(test, mismatches, 0); +} + +/* A codec that stops answering ends the write-back with the bus error */ +static void cs42l84_test_restore_stops_at_error(struct kunit *test) +{ + struct cs42l84_sleep_test_priv *priv = test->priv; + + cs42l84_sleep_test_probe(priv); + cs42l84_sleep_test_sleep(priv); + + priv->fail_reg = CS42L84_HS_SWITCH_CTL; + KUNIT_EXPECT_EQ(test, cs42l84_restore_regs(&priv->cs42l84), -ETIME); + KUNIT_EXPECT_TRUE(test, priv->dead); + KUNIT_EXPECT_EQ(test, priv->num_dead_accesses, 0); +} + +static int cs42l84_sleep_test_case_init(struct kunit *test) +{ + /* The driver's cache and volatile registers, on the logging bus */ + const struct regmap_config config = { + .reg_bits = cs42l84_regmap.reg_bits, + .val_bits = cs42l84_regmap.val_bits, + .volatile_reg = cs42l84_regmap.volatile_reg, + .max_register = cs42l84_regmap.max_register, + .cache_type = cs42l84_regmap.cache_type, + .reg_read = cs42l84_sleep_test_reg_read, + .reg_write = cs42l84_sleep_test_reg_write, + }; + struct cs42l84_sleep_test_priv *priv; + struct regmap *regmap; + struct device *dev; + + priv = kunit_kzalloc(test, sizeof(*priv), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, priv); + priv->test = test; + priv->fail_reg = UINT_MAX; + test->priv = priv; + + priv->regs = kunit_kzalloc(test, CS42L84_TEST_NUM_REGS, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, priv->regs); + + dev = kunit_device_register(test, "cs42l84_sleep_test_drv"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + + regmap = devm_regmap_init(dev, NULL, priv, &config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, regmap); + + priv->cs42l84.dev = dev; + priv->cs42l84.regmap = regmap; + + return 0; +} + +static struct kunit_case cs42l84_sleep_test_cases[] = { + KUNIT_CASE(cs42l84_test_restore_order), + KUNIT_CASE(cs42l84_test_restore_stops_at_error), + { } /* terminator */ +}; + +static struct kunit_suite cs42l84_sleep_test_suite = { + .name = "snd-soc-cs42l84-sleep-test", + .init = cs42l84_sleep_test_case_init, + .test_cases = cs42l84_sleep_test_cases, +}; + +kunit_test_suites(&cs42l84_test_suite, &cs42l84_sleep_test_suite); diff --git a/sound/soc/codecs/cs42l84.c b/sound/soc/codecs/cs42l84.c index 37a8c1bf92a797..12fed85fd3e4f9 100644 --- a/sound/soc/codecs/cs42l84.c +++ b/sound/soc/codecs/cs42l84.c @@ -1128,7 +1128,7 @@ static void cs42l84_setup_plug_detect(struct cs42l84_private *cs42l84) { unsigned int reg; - /* Set up plug detection */ + /* Set up plug detection, as cs42l84_plug_detect_regs[] lists it */ regmap_update_bits(cs42l84->regmap, CS42L84_MIC_DET_CTL4, CS42L84_MIC_DET_CTL4_LATCH_TO_VP, CS42L84_MIC_DET_CTL4_LATCH_TO_VP); @@ -1394,6 +1394,77 @@ static void cs42l84_i2c_remove(struct i2c_client *i2c_client) gpiod_set_value_cansleep(cs42l84->reset_gpio, 0); } +/* + * The registers cs42l84_setup_plug_detect() turns plug detection on with, in + * its order. After a firmware sleep they are written back first, in this + * order, so the two must stay in step. + */ +static const unsigned int cs42l84_plug_detect_regs[] = { + CS42L84_MIC_DET_CTL4, + CS42L84_TIP_SENSE_CTL2, + CS42L84_RING_SENSE_CTL, + CS42L84_TIP_SENSE_CTL, + CS42L84_MSM_BLOCK_EN3, +}; + +static bool cs42l84_is_plug_detect_reg(unsigned int reg) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cs42l84_plug_detect_regs); i++) { + if (cs42l84_plug_detect_regs[i] == reg) + return true; + } + return false; +} + +/* Write one cached register back, then clear what the write latched. */ +static int cs42l84_restore_reg(struct cs42l84_private *cs42l84, unsigned int reg) +{ + unsigned int status; + int ret; + + ret = regcache_sync_region(cs42l84->regmap, reg, reg); + if (ret) + return ret; + return regmap_read(cs42l84->regmap, CS42L84_TSRS_PLUG_INT_STATUS, &status); +} + +/* + * Write the cache back after the codec's reset. Turning tip and ring sensing + * on latches plug events at once, and so do some of the other writes; the + * remote button sources also come up latched. With the interrupt off, nothing + * reads them, and a codec left with a latched event stops answering the bus a + * write or two later. So plug detection goes first, in the probe's order, then + * every other register the cache holds, one at a time, with the status read + * after each write to clear what it latched, as the interrupt thread does. + */ +static int cs42l84_restore_regs(struct cs42l84_private *cs42l84) +{ + unsigned int i, reg, val, max = regmap_get_max_register(cs42l84->regmap); + int ret; + + for (i = 0; i < ARRAY_SIZE(cs42l84_plug_detect_regs); i++) { + ret = cs42l84_restore_reg(cs42l84, cs42l84_plug_detect_regs[i]); + if (ret) + return ret; + } + ret = regmap_read(cs42l84->regmap, CS42L84_REMOTE_BUTTON_STATUS1, &val); + if (ret) + return ret; + + for (reg = 0; reg <= max; reg++) { + /* Plug detection is back already */ + if (cs42l84_is_plug_detect_reg(reg) || + !regcache_reg_cached(cs42l84->regmap, reg)) + continue; + ret = cs42l84_restore_reg(cs42l84, reg); + if (ret) + return ret; + } + return 0; +} + /* * A firmware-driven system sleep holds the codec in reset, so it comes back * with none of its registers and answers nothing until the reset is released. @@ -1478,7 +1549,7 @@ static int cs42l84_resume(struct device *dev) goto err; } - ret = regcache_sync(cs42l84->regmap); + ret = cs42l84_restore_regs(cs42l84); if (ret) goto err; @@ -1500,6 +1571,8 @@ static int cs42l84_resume(struct device *dev) cs42l84_detect_hs(cs42l84); } else { cs42l84->tip_state = CS42L84_UNPLUG; + /* As on an unplug: the cache may hold a headset's bias */ + cs42l84_revert_hs(cs42l84); cs42l84->hs_type = 0; snd_soc_jack_report(cs42l84->jack, 0, SND_JACK_HEADSET); } @@ -1509,6 +1582,8 @@ static int cs42l84_resume(struct device *dev) cs42l84_set_interrupt_masks(cs42l84, 0); } else { cs42l84->ring_state = CS42L84_UNPLUG; + /* As on an unplug: the cache may hold a headset's bias */ + cs42l84_revert_hs(cs42l84); cs42l84->hs_type = 0; snd_soc_jack_report(cs42l84->jack, 0, SND_JACK_HEADSET); cs42l84_set_interrupt_masks(cs42l84, diff --git a/sound/soc/codecs/tas2764.c b/sound/soc/codecs/tas2764.c index 23f9edf4664dfc..d1f9e3994cbbf3 100644 --- a/sound/soc/codecs/tas2764.c +++ b/sound/soc/codecs/tas2764.c @@ -1058,6 +1058,13 @@ static int tas2764_read_die_temp(struct tas2764_priv *tas2764, long *result) int ret, reg; ret = regmap_read(tas2764->regmap, TAS2764_TEMP, ®); + /* + * The regmap is cache-only while the amp cannot be reached (SDZ low + * before the component probe and after its removal, system sleep): + * there is no reading then, as in software shutdown below. + */ + if (ret == -EBUSY) + return -ENODATA; if (ret) return ret; /* @@ -1185,6 +1192,9 @@ static int tas2764_codec_probe(struct snd_soc_component *component) usleep_range(1000, 2000); + /* SDZ is high: the amp answers on the bus from here on */ + regcache_cache_only(tas2764->regmap, false); + tas2764_reset(tas2764); regmap_reinit_cache(tas2764->regmap, &tas2764_i2c_regmap); @@ -1307,6 +1317,7 @@ static int tas2764_codec_probe(struct snd_soc_component *component) err_sdz: /* Undo the power-up: ASoC doesn't call the remove after a failed probe */ + regcache_cache_only(tas2764->regmap, true); if (tas2764->sdz_gpio) gpiod_set_value_cansleep(tas2764->sdz_gpio, 0); /* As in the remove: no supply to drop with a GPIO SDZ, none left in a failed group */ @@ -1326,6 +1337,9 @@ static void tas2764_codec_remove(struct snd_soc_component *component) tas2764_flush_shutdown(tas2764); + /* As before the probe: nothing reaches the amp once its SDZ vote is gone */ + regcache_cache_only(tas2764->regmap, true); + /* A failed group's supply was forced off: there is no enable left to balance. */ if (tas2764_group_failed(tas2764)) return; @@ -1735,6 +1749,14 @@ static int tas2764_i2c_probe(struct i2c_client *client) return result; } + /* + * The amp is held in hardware shutdown (SDZ low) until the component + * probe and does not acknowledge its address: keep everything that can + * run before that, such as a read of the hwmon device registered below, + * off the bus. + */ + regcache_cache_only(tas2764->regmap, true); + if (client->dev.of_node) { result = tas2764_parse_dt(&client->dev, tas2764); if (result) diff --git a/tools/asahi/ane-tm-transient-fault-tests.py b/tools/asahi/ane-tm-transient-fault-tests.py index d095abcb1471c7..0ae1d6c896f15e 100755 --- a/tools/asahi/ane-tm-transient-fault-tests.py +++ b/tools/asahi/ane-tm-transient-fault-tests.py @@ -101,13 +101,18 @@ static void ane_dart_mask(struct ane_device *ane) { (void)ane; } static void ane_dart_unmask(struct ane_device *ane) { (void)ane; } static void ane_tm_push_tq(struct ane_device *ane, struct ane_request *req) { (void)ane; (void)req; } -static int ane_dart_drain_fault(struct ane_device *ane, u64 iova, struct ane_dart_scratch *s, int *pages) +#ifdef ANE_DRAIN_TAKES_SCRATCH +static int ane_dart_drain_fault(struct ane_device *ane, u64 iova, + struct ane_dart_scratch *scratch, int *pages) +#else +static int ane_dart_drain_fault(struct ane_device *ane, u64 iova) +#endif { - (void)iova; (void)s; + (void)iova; drains++; if (scenario == 4 && drains == 2) return -ENOMEM; - ane->scratch_pages = ++*pages; + ane->scratch_pages++; return 0; } static void ane_dart_release_scratch(struct ane_device *ane, struct ane_dart_scratch *s, int pages) @@ -254,7 +259,11 @@ def build(text, header, work): else: start = min(start, text.index('static int ane_tm_poll_step(')) end = text.index('\n/*\n * Recovery runs', start) - (work / 'tm.c').write_text(HARNESS + helper(header) + text[start:end] + MAIN) + execute = text[start:end] + signature = '' + if 'ane_dart_drain_fault(ane, fault_iova,' in execute: + signature = '#define ANE_DRAIN_TAKES_SCRATCH\n' + (work / 'tm.c').write_text(signature + HARNESS + helper(header) + execute + MAIN) subprocess.run(['cc', '-std=gnu11', '-Wall', '-Werror', str(work / 'tm.c'), '-o', str(work / 'tm')], check=True) return subprocess.run([str(work / 'tm')], capture_output=True, text=True) diff --git a/tools/asahi/aop-bootargs-tests.py b/tools/asahi/aop-bootargs-tests.py index 08d39e512c89a0..683b0e9602551e 100644 --- a/tools/asahi/aop-bootargs-tests.py +++ b/tools/asahi/aop-bootargs-tests.py @@ -82,7 +82,15 @@ assert!(!std::ptr::eq(alt,t8122),"T8122 without regions takes its fallback"); assert!(!alt.fw_regions&&alt.without_fw_regions.is_none(),"the fallback needs no regions"); assert!(alt.ncal==HW_CFG_T6020.ncal&&alt.ec0p==HW_CFG_T6020.ec0p&&alt.quiesce_on_unbind==HW_CFG_T6020.quiesce_on_unbind&&alt.bootargs_word_access==HW_CFG_T6020.bootargs_word_access&&alt.halt_on_failed_start==HW_CFG_T6020.halt_on_failed_start,"T8122 fallback is T6020's"); - let others:[(&str,&'static AopHwConfig);10]=[("T8103",&HW_CFG_T8103),("T8112",&HW_CFG_T8112),("T6000",&HW_CFG_T6000),("T6020",&HW_CFG_T6020),("T6040",&HW_CFG_T6040),("T8132",&HW_CFG_T8132),("T8140",&HW_CFG_T8140),("T8152",&HW_CFG_T8152),("T8142",&HW_CFG_T8142),("T6050",&HW_CFG_T6050)]; + // A T8103 AOP the bootloader reserved no regions for (firmware 13.5) starts as before. + let t8103:&'static AopHwConfig=&HW_CFG_T8103; + assert!(t8103.fw_regions,"T8103 checks its firmware regions"); + assert!(std::ptr::eq(t8103.for_regions(true),t8103),"T8103 with regions keeps its own configuration"); + let direct=t8103.for_regions(false); + assert!(!std::ptr::eq(direct,t8103),"T8103 without regions takes its direct start"); + assert!(!direct.fw_regions&&direct.without_fw_regions.is_none(),"the direct start needs no regions"); + assert!(direct.ncal==t8103.ncal&&direct.ec0p==t8103.ec0p&&direct.aopt==t8103.aopt,"the direct start is the same AOP"); + let others:[(&str,&'static AopHwConfig);9]=[("T8112",&HW_CFG_T8112),("T6000",&HW_CFG_T6000),("T6020",&HW_CFG_T6020),("T6040",&HW_CFG_T6040),("T8132",&HW_CFG_T8132),("T8140",&HW_CFG_T8140),("T8152",&HW_CFG_T8152),("T8142",&HW_CFG_T8142),("T6050",&HW_CFG_T6050)]; for (name,cfg) in others { assert!(cfg.without_fw_regions.is_none(),"{} names no fallback",name); for regions in [true,false] {assert!(std::ptr::eq(cfg.for_regions(regions),cfg),"{} keeps its configuration (regions {})",name,regions);} @@ -140,7 +148,8 @@ def method(source): def configs(source): - """struct AopHwConfig and the HW_CFG_* constants, each with its doc comment. + """struct AopHwConfig, the HW_CFG_* constants and the AOP_S2R_* flags they use, each with its + doc comment. Other items between them (the sleep's PM callbacks) use kernel bindings the harness doesn't have. @@ -153,7 +162,8 @@ def configs(source): if not line.strip() or line.startswith(('//', '#[')): pending.append(line) continue - keep = line.startswith(('struct AopHwConfig', 'impl AopHwConfig', 'const HW_CFG_')) + keep = line.startswith(('struct AopHwConfig', 'impl AopHwConfig', 'const HW_CFG_', + 'const AOP_S2R_')) item, pending, depth = pending + [line], [], 0 else: item.append(line) diff --git a/tools/asahi/aop-service-tests.py b/tools/asahi/aop-service-tests.py new file mode 100644 index 00000000000000..735c27dcb1c36c --- /dev/null +++ b/tools/asahi/aop-service-tests.py @@ -0,0 +1,506 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the production AOP service registration against host mocks. + +Each check announces services to AopData::register_service and runs +AopServiceRegisterWork::run to count the child-device registrations it queues +and completes. A service gets one device however often, and under whatever +other channel or name, it is announced again, and any registration failure +releases the claim so the next announcement tries again. +""" +import argparse +from pathlib import Path +import os +import shlex +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +AOP = 'drivers/soc/apple/aop.rs' +SERVICES = 'drivers/soc/apple/aop_services.rs' + +MUTATIONS = { + 'no-work-release': ( + 'register', + 'claims.release(svc);', + 0, + ['work-item allocation failure releases the claim'], + ), + 'no-slot-release': ( + 'run', + 'this.data.registration_gate.lock().release(this.service);', + 0, + ['subdevice slot allocation failure releases the claim'], + ), + 'no-register-release': ( + 'run', + 'this.data.registration_gate.lock().release(this.service);', + 1, + [ + 'platform device registration error releases the claim', + 'null platform device return releases the claim', + ], + ), +} + + +def read(ref, path): + if ref is None: + file = ROOT / path + return file.read_text() if file.is_file() else None + probe = subprocess.run(['git', 'cat-file', '-e', f'{ref}:{path}'], cwd=ROOT, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + if probe.returncode: + return None + return subprocess.check_output(['git', 'show', f'{ref}:{path}'], cwd=ROOT, text=True) + + +def block(source, marker): + start = source.index(marker) + brace = source.index('{', source.index(')', start)) + depth = 1 + end = brace + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def drop_occurrence(source, needle, which, expected_count): + positions = [] + pos = 0 + while True: + idx = source.find(needle, pos) + if idx < 0: + break + positions.append(idx) + pos = idx + len(needle) + if len(positions) != expected_count: + raise SystemExit( + f'mutation target {needle!r}: found {len(positions)} occurrences, expected {expected_count}' + ) + idx = positions[which] + return source[:idx] + source[idx + len(needle):] + + +def program(ref, mutation=None): + aop = read(ref, AOP) + services = read(ref, SERVICES) + parts = [STUBS] + if services is None: + parts.append('type Gate = ();\nfn gate() -> Gate {}\n') + else: + body = services[:services.index('#[kunit_tests')] + body = '\n'.join(line for line in body.splitlines() + if not line.startswith(('use kernel', '//!'))) + parts.append('mod aop_services {\nuse super::*;\n' + body + '\n}\n') + parts.append('type Gate = aop_services::Claims;\n' + 'fn gate() -> Gate { aop_services::Claims::new().unwrap() }\n') + reg_fn = block(aop, ' fn register_service(') + run_fn = block(aop, ' fn run(this: Pin>)') + if mutation is not None: + target, needle, which, _ = MUTATIONS[mutation] + if target == 'register': + reg_fn = drop_occurrence(reg_fn, needle, which, 1) + else: + run_fn = drop_occurrence(run_fn, needle, which, 2) + parts.append('impl AopServiceRegisterWork {\n' + run_fn + '\n}\n') + parts.append('impl AopData {\n' + reg_fn + '\n}\n') + parts.append(CHECKS) + return '\n'.join(parts) + + +STUBS = r''' +#![allow(dead_code, non_camel_case_types, unused_imports, unused_macros)] +use std::collections::VecDeque; +use std::ffi::{c_char, c_void, CStr}; +use std::mem; +use std::ops::{Deref, DerefMut}; +use std::pin::Pin; +use std::ptr::{self, NonNull}; +use std::sync::atomic::{ + AtomicBool, AtomicUsize, + Ordering::{Acquire, SeqCst}, +}; +use std::sync::Arc; +type KBox = Box; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Error(i32); +const ENOMEM: Error = Error(-12); +const EEXIST: Error = Error(-17); +const EINVAL: Error = Error(-22); +const ENOSPC: Error = Error(-28); +type Result = std::result::Result; +const GFP_KERNEL: u32 = 0; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EPICService { pub channel: u32, pub endpoint: u8 } +pub struct PushError(pub T); +static FAIL_WORK_NEW: AtomicUsize = AtomicUsize::new(0); +static FAIL_SUBDEV_RESERVE: AtomicUsize = AtomicUsize::new(0); +static REGISTER_CALLS: AtomicUsize = AtomicUsize::new(0); +static NEXT_PDEV: AtomicUsize = AtomicUsize::new(1); +static UNREGISTER_CALLS: AtomicUsize = AtomicUsize::new(0); +static SUBDEVICES_LOCKED: AtomicBool = AtomicBool::new(false); +#[derive(Clone, Copy)] +enum RegisterOutcome { Ok, ErrPtr(i32), Null } +static REGISTER_OUTCOMES: std::sync::Mutex> = + std::sync::Mutex::new(VecDeque::new()); +static DEV_ERRS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +fn take_fail(counter: &AtomicUsize) -> bool { + let mut cur = counter.load(SeqCst); + while cur > 0 { + match counter.compare_exchange(cur, cur - 1, SeqCst, SeqCst) { + Ok(_) => return true, + Err(next) => cur = next, + } + } + false +} +fn push_register_outcome(outcome: RegisterOutcome) { + REGISTER_OUTCOMES.lock().unwrap().push_back(outcome); +} +pub struct KVec { items: Vec, cap: usize } +impl KVec { + fn new() -> Self { Self { items: Vec::new(), cap: 0 } } + fn with_capacity(cap: usize, _flags: u32) -> Result { Ok(Self { items: Vec::new(), cap }) } + fn reserve(&mut self, additional: usize, _flags: u32) -> Result<()> { + if take_fail(&FAIL_SUBDEV_RESERVE) { + return Err(ENOMEM); + } + self.cap = self.cap.max(self.items.len() + additional); + Ok(()) + } + fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), PushError> { + if self.items.len() < self.cap { self.items.push(v); Ok(()) } else { Err(PushError(v)) } + } + fn iter(&self) -> std::slice::Iter<'_, T> { self.items.iter() } + fn retain(&mut self, f: impl FnMut(&mut T) -> bool) { self.items.retain_mut(f) } + fn len(&self) -> usize { self.items.len() } +} +macro_rules! c_str { + ($s:literal) => { + match CStr::from_bytes_with_nul(concat!($s, "\0").as_bytes()) { Ok(c) => c, Err(_) => panic!() } + }; +} +macro_rules! dev_err { + ($dev:expr, $($arg:tt)+) => {{ + let _ = &$dev; + DEV_ERRS.lock().unwrap().push(format!($($arg)+)); + }}; +} +trait CStrExt { fn as_char_ptr(&self) -> *const c_char; } +impl CStrExt for CStr { fn as_char_ptr(&self) -> *const c_char { self.as_ptr() } } +struct GateMutex(std::sync::Mutex); +impl GateMutex { + fn lock(&self) -> std::sync::MutexGuard<'_, T> { + assert!(!SUBDEVICES_LOCKED.load(SeqCst), "registration_gate locked while holding subdevices"); + self.0.lock().unwrap() + } +} +struct SubdevGuard<'a, T>(std::sync::MutexGuard<'a, T>); +impl Deref for SubdevGuard<'_, T> { + type Target = T; + fn deref(&self) -> &T { &self.0 } +} +impl DerefMut for SubdevGuard<'_, T> { + fn deref_mut(&mut self) -> &mut T { &mut self.0 } +} +impl Drop for SubdevGuard<'_, T> { + fn drop(&mut self) { SUBDEVICES_LOCKED.store(false, SeqCst); } +} +struct SubdevMutex(std::sync::Mutex); +impl SubdevMutex { + fn lock(&self) -> SubdevGuard<'_, T> { + let g = self.0.lock().unwrap(); + SUBDEVICES_LOCKED.store(true, SeqCst); + SubdevGuard(g) + } +} +struct Atomic(std::sync::Mutex); +impl Atomic { fn load(&self, _: std::sync::atomic::Ordering) -> T { *self.0.lock().unwrap() } } +mod bindings { + use super::*; + pub const PLATFORM_DEVID_AUTO: i32 = -2; + pub struct device; + pub struct platform_device; + pub struct platform_device_info { + pub parent: *mut device, + pub name: *const c_char, + pub id: i32, + pub res: *mut c_void, + pub num_res: u32, + pub data: *const c_void, + pub size_data: usize, + pub dma_mask: u64, + pub fwnode: *mut c_void, + pub swnode: *mut c_void, + pub properties: *mut c_void, + pub of_node_reused: bool, + } + pub unsafe fn platform_device_register_full( + _info: *const platform_device_info, + ) -> *mut platform_device { + REGISTER_CALLS.fetch_add(1, SeqCst); + match REGISTER_OUTCOMES.lock().unwrap().pop_front().unwrap_or(RegisterOutcome::Ok) { + RegisterOutcome::Ok => (NEXT_PDEV.fetch_add(1, SeqCst) * 16) as *mut platform_device, + RegisterOutcome::ErrPtr(errno) => (errno as isize) as *mut platform_device, + RegisterOutcome::Null => ptr::null_mut(), + } + } +} +fn from_err_ptr(p: *mut T) -> Result<*mut T> { + let addr = p as usize as isize; + if (-4095..=-1).contains(&addr) { + Err(Error(addr as i32)) + } else { + Ok(p) + } +} +struct ChildDevice(NonNull); +impl ChildDevice { + fn unregister(self) { UNREGISTER_CALLS.fetch_add(1, SeqCst); } +} +struct FwNode; +impl FwNode { + fn get_child_by_name(&self, _name: &CStr) -> Option { None } + fn as_raw(&self) -> *mut c_void { ptr::null_mut() } +} +struct Queue(std::sync::Mutex>>>); +impl Queue { + fn enqueue(&self, work: Pin>) { + self.0.lock().unwrap().push(work); + } + fn drain(&self) { + loop { + let items: Vec<_> = { + let mut q = self.0.lock().unwrap(); + if q.is_empty() { break; } + q.drain(..).collect() + }; + for work in items { + AopServiceRegisterWork::run(work); + } + } + } +} +struct AopServiceRegisterWork { name: &'static CStr, data: Arc, service: EPICService } +impl AopServiceRegisterWork { + fn new(name: &'static CStr, data: Arc, service: EPICService) -> Result>> { + if take_fail(&FAIL_WORK_NEW) { + return Err(ENOMEM); + } + Ok(Box::pin(Self { name, data, service })) + } +} +macro_rules! fmt { ($($t:tt)*) => { format_args!($($t)*) }; } +struct BStr<'a>(&'a [u8]); +impl<'a> BStr<'a> { fn from_bytes(b: &'a [u8]) -> Self { BStr(b) } } +impl std::fmt::Display for BStr<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&String::from_utf8_lossy(self.0)) } +} +struct Device; +impl Device { + fn fwnode(&self) -> Option { None } + fn as_raw(&self) -> *mut bindings::device { ptr::null_mut() } +} +struct AFKEndpoint { index: u8, dropped: Vec } +impl AFKEndpoint { + fn drop_message(&mut self, _dev: &Device, why: std::fmt::Arguments<'_>) { self.dropped.push(why.to_string()); } +} +struct AopData { + dev: Device, + registration_gate: GateMutex, + removing: Atomic, + registration_queue: Queue, + subdevices: SubdevMutex>, +} +''' + +CHECKS = r''' +const NAMES: [&[u8]; 7] = [b"aop-audio", b"las", b"als", b"accel", b"gyro", b"devmotion6", b"als-temp"]; +fn data(removing: bool) -> Arc { + Arc::new(AopData { + dev: Device, + registration_gate: GateMutex(std::sync::Mutex::new(gate())), + removing: Atomic(std::sync::Mutex::new(removing)), + registration_queue: Queue(std::sync::Mutex::new(Vec::new())), + subdevices: SubdevMutex(std::sync::Mutex::new(KVec::new())), + }) +} +fn announce_result(d: &Arc, endpoint: u8, channel: u32, name: &[u8]) -> (Result<()>, Vec) { + let mut ep = AFKEndpoint { index: endpoint, dropped: Vec::new() }; + let res = d.clone().register_service(&mut ep, channel, name); + (res, ep.dropped) +} +fn announce_logged(d: &Arc, endpoint: u8, channel: u32, name: &[u8]) -> Vec { + announce_result(d, endpoint, channel, name).1 +} +fn announce(d: &Arc, endpoint: u8, channel: u32, name: &[u8]) { announce_logged(d, endpoint, channel, name); } +fn queued(d: &Arc) -> usize { d.registration_queue.0.lock().unwrap().len() } +fn drain(d: &Arc) { d.registration_queue.drain(); } +fn registered(d: &Arc) -> usize { d.subdevices.lock().len() } +fn main() { + let mut fixed = Vec::new(); + let mut control = Vec::new(); + let d = data(false); + for _ in 0..5 { announce(&d, 0x23, 1, b"als"); } + fixed.push(("an unchanged announcement repeated 5 times", queued(&d), 1)); + let d = data(false); + announce(&d, 0x23, 1, b"als"); + announce(&d, 0x23, 2, b"als"); + announce(&d, 0x24, 1, b"als"); + fixed.push(("a name announced again on another channel and endpoint", queued(&d), 1)); + let d = data(false); + announce(&d, 0x21, 1, b"aop-audio"); + announce(&d, 0x21, 1, b"als"); + fixed.push(("a channel announced again under another name", queued(&d), 1)); + let d = data(false); + announce(&d, 0x23, 1, b"als"); + let log = announce_logged(&d, 0x23, 2, b"als"); + let named = log.len() == 1 && log[0].contains("\"als\"") && log[0].contains("channel 2"); + fixed.push(("a refused announcement logged once as a dropped message, with its name and channel", named as usize, 1)); + let d = data(false); + announce(&d, 0x23, 1, b"als"); + let quiet = announce_logged(&d, 0x23, 1, b"als").len(); + control.push(("an unchanged repeat logs nothing", quiet, 0)); + let d = data(false); + for channel in 0..64u32 { + for name in NAMES { announce(&d, 0x20 + (channel % 8) as u8, channel, name); } + } + fixed.push(("every known name on 64 channels", queued(&d), NAMES.len())); + let d = data(false); + for (i, name) in NAMES.iter().enumerate() { announce(&d, 0x20 + i as u8, i as u32, name); } + control.push(("each known service once", queued(&d), NAMES.len())); + let d = data(false); + announce(&d, 0x20, 1, b"misc"); + announce(&d, 0x20, 2, b"aop-audio\0x"); + control.push(("unknown services", queued(&d), 0)); + let d = data(true); + announce(&d, 0x23, 1, b"als"); + control.push(("an announcement during removal", queued(&d), 0)); + + // Claim-release path 1 (register_service): work-item allocation fails once. + let d = data(false); + announce(&d, 0x21, 1, b"aop-audio"); + FAIL_WORK_NEW.store(1, SeqCst); + let (first, _) = announce_result(&d, 0x23, 1, b"als"); + let (retry, _) = announce_result(&d, 0x23, 1, b"als"); + drain(&d); + let ok_work = first == Err(ENOMEM) && retry.is_ok() && registered(&d) == 2; + control.push(("work-item allocation failure releases the claim", ok_work as usize, 1)); + + // Claim-release path 2 (AopServiceRegisterWork::run): subdevice slot reserve fails once. + let d = data(false); + announce(&d, 0x21, 1, b"aop-audio"); + drain(&d); + let calls_before = REGISTER_CALLS.load(SeqCst); + announce(&d, 0x23, 1, b"als"); + FAIL_SUBDEV_RESERVE.store(1, SeqCst); + drain(&d); + let skipped_reg = REGISTER_CALLS.load(SeqCst) == calls_before && registered(&d) == 1; + announce(&d, 0x23, 1, b"als"); + drain(&d); + let ok_slot = skipped_reg && registered(&d) == 2; + control.push(("subdevice slot allocation failure releases the claim", ok_slot as usize, 1)); + + // Claim-release path 3a (AopServiceRegisterWork::run): platform_device_register_full returns ERR_PTR. + let d = data(false); + announce(&d, 0x21, 1, b"aop-audio"); + drain(&d); + announce(&d, 0x23, 1, b"als"); + push_register_outcome(RegisterOutcome::ErrPtr(-12)); + drain(&d); + let after_err = registered(&d) == 1; + announce(&d, 0x23, 1, b"als"); + drain(&d); + let ok_err = after_err && registered(&d) == 2; + control.push(("platform device registration error releases the claim", ok_err as usize, 1)); + + // Claim-release path 3b (AopServiceRegisterWork::run): platform_device_register_full returns NULL. + let d = data(false); + announce(&d, 0x23, 1, b"als"); + push_register_outcome(RegisterOutcome::Null); + drain(&d); + let after_null = registered(&d) == 0; + announce(&d, 0x23, 1, b"als"); + drain(&d); + let ok_null = after_null && registered(&d) == 1; + control.push(("null platform device return releases the claim", ok_null as usize, 1)); + + // After failing through all three paths and succeeding on retry, repeats stay refused + // and previously registered services keep their claims. + let d = data(false); + announce(&d, 0x21, 1, b"aop-audio"); + drain(&d); + FAIL_WORK_NEW.store(1, SeqCst); + announce(&d, 0x23, 1, b"als"); + announce(&d, 0x23, 1, b"als"); + FAIL_SUBDEV_RESERVE.store(1, SeqCst); + drain(&d); + announce(&d, 0x23, 1, b"als"); + push_register_outcome(RegisterOutcome::ErrPtr(-12)); + drain(&d); + announce(&d, 0x23, 1, b"als"); + drain(&d); + announce(&d, 0x21, 1, b"aop-audio"); + announce(&d, 0x23, 1, b"als"); + announce(&d, 0x23, 2, b"als"); + drain(&d); + fixed.push(("repeats stay refused after failed registrations retry and succeed", registered(&d), 2)); + + let mut out = String::new(); + let mut fixed_failed = 0; + let mut control_failed = 0; + for (kind, list) in [("check", &fixed), ("control", &control)] { + for (what, got, want) in list.iter() { + let ok = got == want; + if !ok { if kind == "check" { fixed_failed += 1 } else { control_failed += 1 } } + out += &format!("{} {}: {}: got {}, expected {}\n", if ok { "ok" } else { "FAIL" }, kind, what, got, want); + } + } + print!("{}", out); + println!("checks failed {} of {}, controls failed {} of {}", fixed_failed, fixed.len(), control_failed, control.len()); + std::process::exit(if control_failed > 0 { 3 } else if fixed_failed > 0 { 1 } else { 0 }); +} +''' + + +def run(ref, tmp, mutation=None): + prefix = f'mut-{mutation}-' if mutation else ('old-' if ref else '') + source = Path(tmp) / (prefix + 'aop-service.rs') + binary = source.with_suffix('') + source.write_text(program(ref, mutation)) + subprocess.run(shlex.split(os.environ.get('RUSTC', 'rustc')) + + ['--edition=2021', '-Dwarnings', str(source), '-o', str(binary)], check=True) + res = subprocess.run([str(binary)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + sys.stdout.write(res.stdout) + return res.returncode, res.stdout + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + group = ap.add_mutually_exclusive_group() + group.add_argument('--old-ref', help='require this older revision to fail the checks and pass the controls') + group.add_argument('--mutation', choices=sorted(MUTATIONS), + help='drop one claim-release call and require its control to fail') + args = ap.parse_args() + with tempfile.TemporaryDirectory(prefix='aop-service-') as tmp: + rc, out = run(args.old_ref, tmp, args.mutation) + if args.old_ref: + if rc == 1: + print(f'{args.old_ref} fails the checks, as expected') + return 0 + raise SystemExit(f'{args.old_ref}: rc {rc}; the test does not catch the original code') + if args.mutation: + expected = MUTATIONS[args.mutation][3] + missing = [name for name in expected if f'FAIL control: {name}:' not in out] + if rc == 3 and not missing: + print(f'mutation {args.mutation} fails its control, as expected') + return 0 + raise SystemExit(f'mutation {args.mutation}: rc {rc}, missing failures {missing}') + return rc + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/apple-dart-fw-tests.py b/tools/asahi/apple-dart-fw-tests.py index 4541dc295bd4e1..aaa5247fee7673 100644 --- a/tools/asahi/apple-dart-fw-tests.py +++ b/tools/asahi/apple-dart-fw-tests.py @@ -5,7 +5,7 @@ import argparse, hashlib, json, re, subprocess ROOT=Path(__file__).resolve().parents[2] NAMES=('apple_dart_fw_handoff_enabled','apple_dart_pte_to_paddr','apple_dart_fw_table_page','apple_dart_fw_table_ram','apple_dart_fw_table_pte','apple_dart_fw_table_decode','apple_dart_fw_tree_table','apple_dart_fw_slot_owned','apple_dart_fw_leaf_decode','apple_dart_fw_mapping_matches','apple_dart_fw_page_matches','apple_dart_fw_slot_mirrors','apple_dart_publish_root','apple_dart_retire_root','apple_dart_free_fw_root','apple_dart_snapshot_fw_root','apple_dart_free_fw_tree','apple_dart_fw_tree_phys','apple_dart_fw_slot_foreign','apple_dart_domain_uses_fw','apple_dart_check_fw_map','apple_dart_inherited_phys_prot','apple_dart_inherited_phys','apple_dart_fw_slot_range','apple_dart_get_fw_resv_regions','apple_dart_fw_invalidate','apple_dart_hw_unmap_locked_ttbr','apple_dart_retire_error','apple_dart_t8110_hw_invalidate_tlb','apple_dart_release_device','apple_dart_domain_free') -CASES=("legacy-map-match","legacy-map-mismatch","legacy-lookup","legacy-snapshot",'mirror','changed-leaf','wrong-permission','wrong-physical','malformed-leaf','vacant','changed-owner','retire','reserved-ram','unreserved','mmio','misalignment','address-width','root-encoding','leaf-as-table','snapshot','snapshot-malformed','snapshot-unreserved','snapshot-root-change','snapshot-map-failure','snapshot-allocation-failure','range-three','range-offset','range-width','range-overflow','range-underflow','range-four','range-four-last','map-firmware','map-hole','map-host','map-owned','map-unmatched','map-attached','map-wrong-physical','map-wrong-permission','map-changed-root','map-four','lookup-inherited','lookup-changed-leaf','lookup-changed-root','lookup-unmatched','reserve-firmware','reserve-teardown','reserve-unmatched','reserve-owned','invalidate-three','invalidate-four','invalidate-changed-root','invalidate-error','core-inherited','core-hole','core-changed-leaf','core-second-dart','snapshot-unmatched','snapshot-four','range-four-width','range-three-last','handoff-matched','handoff-missing','handoff-duplicate','handoff-zero','handoff-unlocked','handoff-other-soc','retire-free','retire-free-timeout','retire-release','retire-release-timeout','retire-rollback-timeout','retire-repeat-timeout','tree-lookup','tree-changed-root','tree-changed-mid','tree-unrecorded','tree-reserve','tree-mirror-only','subtree-free-partial','subtree-table-reserved','subtree-table-unclaimed','subtree-table-claimed','subtree-table-ram','subtree-table-misalignment') +CASES=("legacy-map-match","legacy-map-mismatch","legacy-lookup","legacy-snapshot",'mirror','changed-leaf','wrong-permission','wrong-physical','malformed-leaf','vacant','changed-owner','retire','reserved-ram','unreserved','mmio','misalignment','address-width','root-encoding','leaf-as-table','snapshot','snapshot-malformed','snapshot-unreserved','snapshot-root-change','snapshot-map-failure','snapshot-allocation-failure','range-three','range-offset','range-width','range-overflow','range-underflow','range-four','range-four-last','map-firmware','map-hole','map-host','map-owned','map-unmatched','map-attached','map-wrong-physical','map-wrong-permission','map-changed-root','map-four','lookup-inherited','lookup-changed-leaf','lookup-changed-root','lookup-unmatched','reserve-firmware','reserve-teardown','reserve-unmatched','reserve-owned','invalidate-three','invalidate-four','invalidate-changed-root','invalidate-error','core-inherited','core-hole','core-changed-leaf','core-second-dart','snapshot-unmatched','snapshot-four','range-four-width','range-three-last','handoff-matched','handoff-missing','handoff-duplicate','handoff-zero','handoff-unlocked','handoff-dart1-format','handoff-unversioned','handoff-version-0201','retire-free','retire-free-timeout','retire-release','retire-release-timeout','retire-rollback-timeout','retire-repeat-timeout','tree-lookup','tree-changed-root','tree-changed-mid','tree-unrecorded','tree-reserve','tree-mirror-only','subtree-free-partial','subtree-table-reserved','subtree-table-unclaimed','subtree-table-claimed','subtree-table-ram','subtree-table-misalignment') def function(s,name): match=re.search(r'^static[^;{}]*\b'+re.escape(name)+r'\([^;{}]*\)\s*\{',s,re.M) if not match:return None diff --git a/tools/asahi/apple-dart-fw/fixture.c b/tools/asahi/apple-dart-fw/fixture.c index f8fd490ddc306c..ccab85f7fab1d0 100644 --- a/tools/asahi/apple-dart-fw/fixture.c +++ b/tools/asahi/apple-dart-fw/fixture.c @@ -14,6 +14,7 @@ typedef uint8_t u8;typedef uint32_t u32;typedef uint64_t u64;typedef uint64_t ph #define IOMMU_WRITE 2 #define IOMMU_CACHE 4 #define APPLE_DART_PTE_VALID 1 +#define APPLE_DART 1 #define APPLE_DART2 2 #define GFP_KERNEL 0 #define MEMREMAP_WB 0 @@ -83,9 +84,8 @@ static int commands,command_error;static u64 command_start[8],command_end[8]; static int apple_dart_t8110_hw_tlb_command_range(struct apple_dart_stream_map*m,int op,bool range,u64 lo,u64 hi){assert(op==1&&range&&commands<8);command_start[commands]=lo;command_end[commands++]=hi;return command_error;} struct list_head {int count;}; struct iommu_resv_region {u64 start,length,dva;int prot,type;struct list_head list;}; -struct device_node {int count;u32 value;bool t8140;}; +struct device_node {int count;u32 value;}; struct iommu_device;struct device {struct device_node*of_node;struct apple_dart_master_cfg*cfg;struct iommu_device*iommu;}; -static int of_device_is_compatible(struct device_node*np,const char*s){assert(!strcmp(s,"apple,t8140-dart"));return np->t8140;} static int of_property_count_u32_elems(struct device_node*np,const char*s){assert(!strcmp(s,"apple,firmware-root-handoff"));return np->count;} static int of_property_read_u32(struct device_node*np,const char*s,u32*v){assert(!strcmp(s,"apple,firmware-root-handoff"));*v=np->value;return np->count<1?-EINVAL:0;} #define dev_iommu_priv_get(d) ((d)->cfg) @@ -188,7 +188,7 @@ int main(int argc,char**argv){ firmware_leaf[0]=leaf(0x8000);ours_leaf[0]=leaf(0x8000);phys_addr_t phys; struct apple_dart_domain domain={0};domain.stream_maps[0].dart=&d;domain.fw_sidmap[0][0]=1; struct apple_dart_master_cfg cfg={0};cfg.stream_maps[0].dart=&d;cfg.stream_maps[0].sidmap[0]=1; - struct iommu_device io={0};struct device_node node={1,1,true};struct device dev={&node,&cfg,&io};d.dev=&dev;struct list_head head={0}; + struct iommu_device io={0};struct device_node node={1,1};struct device dev={&node,&cfg,&io};d.dev=&dev;struct list_head head={0}; d.locked_ttbr[0][0]=root;static u64 shadow[2048];d.locked_owned[0][0]=shadow;d.locked_fw[0][0]=&fw; if(!strncmp(c,"legacy-",7)){ d.fw_handoff=0;d.fw_mirror=1;root[0]=0x1401; @@ -203,11 +203,15 @@ int main(int argc,char**argv){ }else abort(); } else if(!strncmp(c,"handoff-",8)){ + d.version=0x0202; if(!strcmp(c,"handoff-missing"))node.count=-EINVAL; if(!strcmp(c,"handoff-duplicate"))node.count=2; if(!strcmp(c,"handoff-zero"))node.value=0; if(!strcmp(c,"handoff-unlocked"))d.locked=0; - if(!strcmp(c,"handoff-other-soc"))node.t8140=false; + if(!strcmp(c,"handoff-dart1-format"))hw.fmt=APPLE_DART; + /* A T6000 DART has the APPLE_DART2 layout but reports no version. */ + if(!strcmp(c,"handoff-unversioned"))d.version=0; + if(!strcmp(c,"handoff-version-0201"))d.version=0x0201; assert(apple_dart_fw_handoff_enabled(&d)==!strcmp(c,"handoff-matched")); } else if(!strncmp(c,"core-",5)){ diff --git a/tools/asahi/apple-dart-range-tests.py b/tools/asahi/apple-dart-range-tests.py index edebda6eb6a9d9..f8c5d0f07d2175 100644 --- a/tools/asahi/apple-dart-range-tests.py +++ b/tools/asahi/apple-dart-range-tests.py @@ -38,14 +38,16 @@ def main(): #define dev_err_ratelimited(...) ((void)0) #define READ_ONCE(x) (x) #define WRITE_ONCE(x, v) ((x) = (v)) +#define spin_lock_irqsave(lock, flags) do { assert(!*(lock)); *(lock) = true; (flags) = 0; } while (0) +#define spin_unlock_irqrestore(lock, flags) do { assert(*(lock)); *(lock) = false; (void)(flags); } while (0) #define DART_T8110_TLB_CMD_OP_FLUSH_SID 1 struct io_pgtable_cfg { int unused; }; struct io_pgtable { struct io_pgtable_cfg cfg; }; #define io_pgtable_ops_to_pgtable(x) ((struct io_pgtable *)(x)) struct apple_dart; struct apple_dart_stream_map { struct apple_dart *dart; unsigned long sidmap[1]; }; -struct apple_dart_hw { int (*invalidate_tlb)(struct apple_dart_stream_map *); }; -struct apple_dart { int num_streams, locked, version; bool fw_mirror, fw_handoff, managed_sids, display_dark, display_tlb_stale; void *dev; struct apple_dart_hw *hw; }; +struct apple_dart_hw { int (*invalidate_tlb)(struct apple_dart_stream_map *); bool gen3; }; +struct apple_dart { int num_streams, locked, version; bool fw_mirror, fw_handoff, managed_sids, managed_lock, display_dark, display_tlb_stale; unsigned int display_writers, display_dark_writers; void *dev; struct apple_dart_hw *hw; }; struct apple_dart_atomic_stream_map { struct apple_dart *dart; unsigned long sidmap[1]; }; struct apple_dart_domain { void *pgtbl_ops; bool dcp; struct apple_dart_atomic_stream_map streams[2]; int count; diff --git a/tools/asahi/apple-dart-tlb-stall-tests.py b/tools/asahi/apple-dart-tlb-stall-tests.py index cc6e3582c07d5a..706ad2ab7e83d6 100644 --- a/tools/asahi/apple-dart-tlb-stall-tests.py +++ b/tools/asahi/apple-dart-tlb-stall-tests.py @@ -34,7 +34,7 @@ 'DART_T8110_FLUSH_STALL_TIMEOUT', 'DART_T8110_FLUSH_STALL_POLL', 'DART_T8110_TLB_CMD_STREAM', 'DART_T8110_CTC_FLUSH') OPTIONAL_DEFINES = {'DART_T8110_FLUSH_STALL_TIMEOUT', 'DART_T8110_FLUSH_STALL_POLL'} -CASES = ('fast', 'stall-after', 'stall-before', 'stuck', 'not-handoff', 'not-scanout', +CASES = ('fast', 'stall-after', 'stall-before', 'stuck', 'no-handoff', 'not-scanout', 'not-range', 'ctc-flush', 'sleep-listed', 'superseded', 'gated', 'two-streams') J700 = 'arch/arm64/boot/dts/apple/t8140-j700.dts' # What the J700 display subsystem scans out through: disp0 and dispext0. @@ -342,18 +342,22 @@ assert(now >= DART_T8110_FLUSH_STALL_TIMEOUT); assert(now <= DART_T8110_FLUSH_STALL_TIMEOUT + 2 * DART_T8110_FLUSH_BUSY_TIMEOUT + 100); assert(!dart.lock); - } else if (!strcmp(c, "not-handoff")) { - /* Other DARTs keep failing after the short wait, lock held throughout. */ + } else if (!strcmp(c, "no-handoff")) { + /* + * The J815 display: locked by the loader without the root handoff, + * the same 40 ms stall is waited out too. + */ reset(false); durations[0] = 40000; ndurations = 1; - assert(range() == -ETIMEDOUT); - assert(commands == 1 && errors_logged == 1 && lock_drops == 1); - assert(now <= DART_T8110_FLUSH_BUSY_TIMEOUT + 10); + assert(!range()); + assert(commands == 1 && !errors_logged && infos_logged == 1); + assert(info_us >= 38000 && info_us <= 41000); + check_range_command(0, 0); } else if (!strcmp(c, "not-scanout")) { /* - * A handed-off DART no display subsystem scans out through, such as - * the DCP's own: the same stall fails after the short wait, lock held. + * A DART no display subsystem scans out through, such as the DCP's + * own: the same stall fails after the short wait, lock held. */ dart.display_scanout = false; durations[0] = 40000; @@ -583,8 +587,8 @@ def main(): parser.add_argument('--source', type=Path, help='an apple-dart.c to test (default: this tree)') parser.add_argument('--ref', help='test drivers/iommu/apple-dart.c of this revision instead') parser.add_argument('--case', action='append') - parser.add_argument('--mutation', choices=('every-handoff',), - help='every-handoff: wait on every handed-off DART, not just the scan-out ones') + parser.add_argument('--mutation', choices=('every-dart',), + help='every-dart: wait on every locked DART, not just the scan-out ones') parser.add_argument('--dtc', help="this kernel's built scripts/dtc/dtc: also check the J700 tree") args = parser.parse_args() if args.ref: @@ -592,11 +596,11 @@ def main(): args.ref + ':drivers/iommu/apple-dart.c'], text=True) else: text = (args.source or ROOT / 'drivers/iommu/apple-dart.c').read_text() - if args.mutation == 'every-handoff': + if args.mutation == 'every-dart': cut = ' !dart->display_scanout ||' if text.count(cut) != 1: # Not a kill: the harness counts a traceback as a broken run. - raise RuntimeError('every-handoff: no display_scanout check to remove') + raise RuntimeError('every-dart: no display_scanout check to remove') text = text.replace(cut, '') defines = [] diff --git a/tools/asahi/apple-wdt-tests.py b/tools/asahi/apple-wdt-tests.py new file mode 100755 index 00000000000000..f6f8cf01dd2d62 --- /dev/null +++ b/tools/asahi/apple-wdt-tests.py @@ -0,0 +1,1017 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Check Apple SoC Watchdog probe, ops, PM, sleep handoff and T6050 wake WDT helpers. + +The full production driver body from drivers/watchdog/apple_wdt.c (ops, probe, +suspend, resume, and sleep restore) and the T6050 commit/wake WDT helpers from +drivers/soc/apple/sleep-t6050.h are compiled unchanged under ASan and UBSan +against an in-memory MMIO register model with write-order and barrier tracking. + +- Without a "reconfig" MMIO resource (legacy wdt-version 2): probe adopts + WD1_CTRL RESET_EN, start/stop/ping/set_timeout/get_timeleft/suspend/resume/ + restart drive WD1 unchanged and leave WD2 untouched. +- With a "reconfig" MMIO resource (simple-reconfig-wdog-support): + - Probe rejects undersized (< 4 B) reconfig resources with -EINVAL. + - Probe registers the sleep handoff before touching watchdog registers so a + registration failure (-EBUSY) writes zero registers, and devm unregisters + the watchdog before unregistering the sleep handoff. + - Probe clears any pre-armed WD1_CTRL and unifies pre-probe takeover: any + armed WD1 (RESET_EN) or WD2 (IRQ_EN or RESET_EN) sets WDOG_HW_RUNNING + before the first WD2 write and re-arms WD2 safely through apple_wdt_wd2_arm(). + - start/stop/ping/set_timeout/get_timeleft/restart drive WD2 bark-IRQ with + clock-derived reboot delay, write-order and readl() barrier checks, and + underflow guard. + - resume without apple_sleep reprograms reconfig, WD2_BITE and WD2_BARK even + if register state was lost across suspend. + - suspend/ping/resume during firmware-driven apple_sleep leave sleep's WD2 + safety net intact only for the device owning the sleep slot; non-matching + devices keep operating normally. + - kdump probe skips takeover (both WD1 and WD2) and arms WD2 at max_hw_heartbeat_ms. + - T6050 sleep commit/wake WDT helpers save wdt-aux + AON_WDT_SLEEP before + t6050_seq(T6050_SEQ_WDT) and restore it on wake after CTL=0, W1C IRQ_STATUS + clear, and a readl() barrier, followed by a readl() barrier before re-arming. + +--old-ref REV compiles and runs apple_wdt.c from REV and expects failure. +--mutation NAME mutates the driver/helper source and expects failure. +""" +import argparse +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +DRIVER = 'drivers/watchdog/apple_wdt.c' +SLEEP_T6050 = 'drivers/soc/apple/sleep-t6050.h' + + +def show(ref, path): + if not ref: + return (ROOT / path).read_text() + return subprocess.run(['git', '-C', str(ROOT), 'show', f'{ref}:{path}'], check=True, + capture_output=True, text=True).stdout + + +def extract_body(source): + start = source.index('#define APPLE_WDT_WD0_CUR_TIME') + end = source.index('static DEFINE_SIMPLE_DEV_PM_OPS') + return source[start:end] + + +def extract_t6050_wdt_helpers(source): + start = source.index('static void t6050_sleep_commit_wdt(') + end = source.index('/*\n * The commit window,') + return source[start:end] + + +def apply_mutation(body, t6050_helpers, mutation): + if not mutation: + return body, t6050_helpers + if mutation == 'ignore-sleep-handoff': + needle = 'if (wdt->reconfig && apple_sleep_wdt_active(wdd->parent))\n\t\treturn 0;' + if needle not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + return body.replace(needle, 'if (0)\n\t\treturn 0;'), t6050_helpers + if mutation == 'no-bark-in-start': + needle = '\twritel_relaxed(bark_ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME);' + if needle not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + return body.replace(needle, '\t/* omitted BARK write */'), t6050_helpers + if mutation == 'no-status-clear': + needle = '\twritel_relaxed(APPLE_WDT_CTRL_IRQ_STATUS,\n\t\t wdt->regs + APPLE_WDT_WD2_CTRL);' + if needle not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + return body.replace(needle, '\t/* omitted IRQ_STATUS clear */'), t6050_helpers + if mutation == 'reconfig-before-bark': + old = ('\twritel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CTRL);\n' + '\twritel_relaxed(U32_MAX, wdt->regs + APPLE_WDT_WD2_BITE_TIME);\n' + '\twritel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CUR_TIME);\n' + '\twritel_relaxed(bark_ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME);\n' + '\twritel_relaxed(APPLE_WDT_CTRL_IRQ_STATUS,\n' + '\t\t wdt->regs + APPLE_WDT_WD2_CTRL);\n' + '\t(void)readl(wdt->regs + APPLE_WDT_WD2_CTRL);\n' + '\tapple_wdt_enable_reconfig(wdt);') + if old not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + new = ('\tapple_wdt_enable_reconfig(wdt);\n' + '\twritel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CTRL);\n' + '\twritel_relaxed(U32_MAX, wdt->regs + APPLE_WDT_WD2_BITE_TIME);\n' + '\twritel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CUR_TIME);\n' + '\twritel_relaxed(bark_ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME);\n' + '\twritel_relaxed(APPLE_WDT_CTRL_IRQ_STATUS,\n' + '\t\t wdt->regs + APPLE_WDT_WD2_CTRL);\n' + '\t(void)readl(wdt->regs + APPLE_WDT_WD2_CTRL);') + return body.replace(old, new), t6050_helpers + if mutation == 'register-after-arm': + reg_block = ('\t\tret = apple_sleep_wdt_register(dev, wdt_res,\n' + '\t\t\t\t\t apple_wdt_sleep_restore, wdt);\n' + '\t\tif (ret)\n' + '\t\t\treturn ret;\n' + '\t\tret = devm_add_action_or_reset(dev, apple_wdt_sleep_unregister, dev);\n' + '\t\tif (ret)\n' + '\t\t\treturn ret;\n') + tail = '\treturn devm_watchdog_register_device(dev, &wdt->wdd);' + if reg_block not in body or tail not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + mut = body.replace(reg_block, '') + mut = mut.replace(tail, + '\tret = devm_watchdog_register_device(dev, &wdt->wdd);\n' + '\tif (ret)\n\t\treturn ret;\n' + '\tif (wdt->reconfig) {\n' + reg_block + '\t}\n\treturn 0;') + return mut, t6050_helpers + if mutation == 'hwrunning-after-arm': + old = ('\t\t\tset_bit(WDOG_HW_RUNNING, &wdt->wdd.status);\n' + '\t\t\tapple_wdt_wd2_arm(wdt,\n' + '\t\t\t\t\t apple_wdt_timeout_ticks(wdt, wdt->wdd.timeout));') + if old not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + new = ('\t\t\tapple_wdt_wd2_arm(wdt,\n' + '\t\t\t\t\t apple_wdt_timeout_ticks(wdt, wdt->wdd.timeout));\n' + '\t\t\tset_bit(WDOG_HW_RUNNING, &wdt->wdd.status);') + return body.replace(old, new), t6050_helpers + if mutation == 'no-wd1-adopt': + old = ('\t\tarmed = (wd1_ctrl & APPLE_WDT_CTRL_RESET_EN) ||\n' + '\t\t\t(wd2_ctrl & (APPLE_WDT_CTRL_IRQ_EN | APPLE_WDT_CTRL_RESET_EN));') + if old not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + new = '\t\tarmed = !!(wd2_ctrl & (APPLE_WDT_CTRL_IRQ_EN | APPLE_WDT_CTRL_RESET_EN));' + return body.replace(old, new), t6050_helpers + if mutation == 'no-t6050-wake-restore': + old = ('\tif (s->aon_wdt_marked) {\n' + '\t\twritel(s->aon_wdt_saved, s->wdt_aux + AON_WDT_SLEEP);\n' + '\t\t(void)readl(s->wdt_aux + AON_WDT_SLEEP);\n' + '\t\ts->aon_wdt_marked = false;\n' + '\t}') + if old not in t6050_helpers: + raise SystemExit(f'mutation {mutation}: target pattern not found') + return body, t6050_helpers.replace(old, '\t/* omitted wake restore */') + raise SystemExit(f'unknown mutation: {mutation}') + + +PREFIX = r''' +#include +#include +#include +#include +#include +#include +#include +#include + +typedef uint32_t u32; +typedef uint64_t u64; +typedef uintptr_t resource_size_t; + +#define BIT(x) (1u << (x)) +#define GENMASK(h, l) (((~0u) << (l)) & (~0u >> (31 - (h)))) +#define U32_MAX 0xffffffffu +#define MSEC_PER_SEC 1000u +#define __iomem +#define GFP_KERNEL 0 +#define THIS_MODULE NULL +#define IORESOURCE_MEM 0x00000200u +#define WATCHDOG_NOWAYOUT 0 +#define WDIOF_MAGICCLOSE 0x0100u +#define WDIOF_KEEPALIVEPING 0x8000u +#define WDIOF_SETTIMEOUT 0x0080u + +#define WDOG_ACTIVE 0 +#define WDOG_HW_RUNNING 1 + +#define min(a, b) ((a) < (b) ? (a) : (b)) +#define max_t(type, a, b) ((type)(a) > (type)(b) ? (type)(a) : (type)(b)) +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - offsetof(type, member))) + +static inline u64 div_u64(u64 dividend, u32 divisor) +{ + return dividend / divisor; +} + +static inline void set_bit(unsigned int nr, volatile unsigned long *addr) +{ + *addr |= (1UL << nr); +} + +static inline bool test_bit(unsigned int nr, const volatile unsigned long *addr) +{ + return (*addr & (1UL << nr)) != 0; +} + +static inline bool IS_ERR(const void *ptr) +{ + return (uintptr_t)ptr >= (uintptr_t)-4095L; +} + +static inline long PTR_ERR(const void *ptr) +{ + return (long)(intptr_t)ptr; +} + +struct device { + void *drvdata; +}; + +struct platform_device { + struct device dev; +}; + +struct resource { + resource_size_t start; + resource_size_t end; +}; + +static inline resource_size_t resource_size(const struct resource *res) +{ + return res->end - res->start + 1; +} + +struct clk { + unsigned long rate; +}; + +struct watchdog_device; + +struct watchdog_ops { + void *owner; + int (*start)(struct watchdog_device *); + int (*stop)(struct watchdog_device *); + int (*ping)(struct watchdog_device *); + int (*set_timeout)(struct watchdog_device *, unsigned int); + unsigned int (*get_timeleft)(struct watchdog_device *); + int (*restart)(struct watchdog_device *, unsigned long, void *); +}; + +struct watchdog_info { + const char *identity; + unsigned int options; +}; + +struct watchdog_device { + struct device *parent; + const struct watchdog_ops *ops; + const struct watchdog_info *info; + unsigned int timeout; + unsigned int max_hw_heartbeat_ms; + unsigned long status; +}; + +static inline bool watchdog_active(struct watchdog_device *wdd) +{ + return test_bit(WDOG_ACTIVE, &wdd->status); +} + +static inline bool watchdog_hw_running(struct watchdog_device *wdd) +{ + return test_bit(WDOG_HW_RUNNING, &wdd->status); +} + +/* Mock hardware + write log */ +#define MMIO_WORDS 16 +static u32 mmio_regs[MMIO_WORDS]; +static u32 wdt_aux_regs[MMIO_WORDS]; +#define reconfig_reg (wdt_aux_regs[0x2c / 4]) + +struct mmio_event { + bool is_reconfig; + u32 off; + u32 val; +}; + +static struct mmio_event write_log[256]; +static unsigned int write_log_len; + +static unsigned int mdelay_total_ms; +static bool mock_has_reconfig; +static resource_size_t mock_reconfig_size = 4; +static struct resource mock_wdt_res; +static struct resource mock_reconfig_res; +static struct clk mock_clk = { .rate = 24000000UL }; +static bool mock_kdump; +static unsigned int mock_warns; +static unsigned int mock_infos; +static unsigned int mock_dt_timeout; +static bool wdt_ctrl_read_since_write; +static bool reconfig_read_since_write; +static struct watchdog_device *registered_wdd; +static struct watchdog_device *current_probe_wdd; +static bool expect_hw_running_before_wd2_write; +static bool mock_sleep_active; +static int mock_sleep_reg_ret; +static struct device *mock_sleep_owner; +static const struct resource *mock_sleep_reg_res; +static void (*mock_sleep_restore)(void *); +static void *mock_sleep_data; +static void *mock_devm_alloc; + +/* Devm LIFO stack to verify teardown order (watchdog unregister before sleep unregister) */ +enum devm_kind { DEVM_ACTION = 1, DEVM_WDT = 2 }; +struct devm_entry { + enum devm_kind kind; + void (*action)(void *); + void *data; +}; +static struct devm_entry devm_stack[16]; +static unsigned int devm_stack_len; +static enum devm_kind teardown_order[16]; +static unsigned int teardown_order_len; + +static void record_write(const volatile void *addr, u32 val) +{ + assert(write_log_len < 256); + if (addr == (const volatile void *)&reconfig_reg) { + if ((val & GENMASK(5, 4)) == BIT(4)) { + /* + * Routing WD2 bark to cold reset must never occur while + * IRQ_EN is set, IRQ_STATUS is latched, BITE is short, + * CUR >= BARK, or without a readl() barrier on the + * separate watchdog register block first. + */ + assert((mmio_regs[0x2c / 4] & (BIT(0) | BIT(1))) == 0); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x20 / 4] < mmio_regs[0x28 / 4]); + assert(wdt_ctrl_read_since_write); + } + reconfig_read_since_write = false; + write_log[write_log_len++] = (struct mmio_event){ true, 0x2c, val }; + } else if (addr >= (const volatile void *)wdt_aux_regs && + addr < (const volatile void *)(wdt_aux_regs + MMIO_WORDS)) { + uintptr_t base = (uintptr_t)wdt_aux_regs; + uintptr_t p = (uintptr_t)addr; + write_log[write_log_len++] = (struct mmio_event){ true, (u32)(p - base), val }; + } else { + uintptr_t base = (uintptr_t)mmio_regs; + uintptr_t p = (uintptr_t)addr; + u32 off = (u32)(p - base); + assert(p >= base && p < base + sizeof(mmio_regs)); + if (expect_hw_running_before_wd2_write && off >= 0x20 && off <= 0x2c) + assert(current_probe_wdd && watchdog_hw_running(current_probe_wdd)); + /* Enabling WD2 IRQ_EN under simple-reconfig requires a readl(reconfig) first */ + if (off == 0x2c && (val & BIT(0)) && (reconfig_reg & GENMASK(5, 4)) == BIT(4)) + assert(reconfig_read_since_write); + wdt_ctrl_read_since_write = false; + write_log[write_log_len++] = (struct mmio_event){ false, off, val }; + } +} + +static u32 readl_relaxed(const volatile void *addr) +{ + return *(const volatile u32 *)addr; +} + +static u32 readl(const volatile void *addr) +{ + if (addr == (const volatile void *)&mmio_regs[0x2c / 4]) + wdt_ctrl_read_since_write = true; + if (addr == (const volatile void *)&reconfig_reg) + reconfig_read_since_write = true; + return *(const volatile u32 *)addr; +} + +static void writel_relaxed(u32 val, volatile void *addr) +{ + if (addr == (volatile void *)&mmio_regs[0x2c / 4]) { + /* Model W1C semantics on APPLE_WDT_CTRL_IRQ_STATUS (BIT(1)) */ + u32 latched = mmio_regs[0x2c / 4] & BIT(1); + if (val & BIT(1)) + latched = 0; + mmio_regs[0x2c / 4] = (val & ~BIT(1)) | latched; + } else { + *(volatile u32 *)addr = val; + } + record_write(addr, val); +} + +static void writel(u32 val, volatile void *addr) +{ + writel_relaxed(val, addr); +} + +static void mdelay(unsigned int ms) +{ + mdelay_total_ms += ms; +} + +static void *devm_kzalloc(struct device *dev, size_t size, int gfp) +{ + assert(!mock_devm_alloc); + mock_devm_alloc = calloc(1, size); + return mock_devm_alloc; +} + +static void __iomem *devm_platform_ioremap_resource(struct platform_device *pdev, + unsigned int index) +{ + assert(index == 0); + return (void __iomem *)mmio_regs; +} + +static void __iomem *devm_platform_get_and_ioremap_resource(struct platform_device *pdev, + unsigned int index, + struct resource **res) +{ + assert(index == 0); + mock_wdt_res.start = 0x28836c000ULL; + mock_wdt_res.end = 0x28836c000ULL + 0x4000 - 1; + if (res) + *res = &mock_wdt_res; + return (void __iomem *)mmio_regs; +} + +static struct resource *platform_get_resource_byname(struct platform_device *pdev, + unsigned int type, const char *name) +{ + assert(type == IORESOURCE_MEM); + if (mock_has_reconfig && strcmp(name, "reconfig") == 0) { + mock_reconfig_res.start = (resource_size_t)(uintptr_t)&reconfig_reg; + mock_reconfig_res.end = mock_reconfig_res.start + mock_reconfig_size - 1; + return &mock_reconfig_res; + } + return NULL; +} + +static void __iomem *devm_ioremap(struct device *dev, resource_size_t offset, + resource_size_t size) +{ + return (void __iomem *)(uintptr_t)offset; +} + +static struct clk *devm_clk_get_enabled(struct device *dev, const char *id) +{ + return &mock_clk; +} + +static unsigned long clk_get_rate(struct clk *clk) +{ + return clk->rate; +} + +static void platform_set_drvdata(struct platform_device *pdev, void *data) +{ + pdev->dev.drvdata = data; +} + +static void *dev_get_drvdata(struct device *dev) +{ + return dev->drvdata; +} + +static bool is_kdump_kernel(void) +{ + return mock_kdump; +} + +static void watchdog_set_nowayout(struct watchdog_device *wdd, bool nowayout) {} +static int watchdog_init_timeout(struct watchdog_device *wdd, unsigned int t, struct device *dev) +{ + current_probe_wdd = wdd; + if (mock_dt_timeout) + wdd->timeout = mock_dt_timeout; + return 0; +} +static void watchdog_stop_on_unregister(struct watchdog_device *wdd) {} +static void watchdog_set_restart_priority(struct watchdog_device *wdd, int prio) {} + +static int devm_watchdog_register_device(struct device *dev, struct watchdog_device *wdd) +{ + registered_wdd = wdd; + assert(devm_stack_len < 16); + devm_stack[devm_stack_len++] = (struct devm_entry){ DEVM_WDT, NULL, wdd }; + return 0; +} + +static int devm_add_action_or_reset(struct device *dev, void (*action)(void *), void *data) +{ + assert(devm_stack_len < 16); + devm_stack[devm_stack_len++] = (struct devm_entry){ DEVM_ACTION, action, data }; + return 0; +} + +static int apple_sleep_wdt_register(struct device *dev, const struct resource *wdt, + void (*restore)(void *), void *data) +{ + if (mock_sleep_reg_ret) + return mock_sleep_reg_ret; + mock_sleep_owner = dev; + mock_sleep_reg_res = wdt; + mock_sleep_restore = restore; + mock_sleep_data = data; + return 0; +} + +static void apple_sleep_wdt_unregister(struct device *dev) +{ + if (mock_sleep_owner == dev) { + mock_sleep_owner = NULL; + mock_sleep_reg_res = NULL; + mock_sleep_restore = NULL; + mock_sleep_data = NULL; + } +} + +static bool apple_sleep_wdt_active(struct device *dev) +{ + return mock_sleep_active && mock_sleep_owner == dev; +} + +#define dev_warn(dev, fmt, ...) do { mock_warns++; } while (0) +#define dev_info(dev, fmt, ...) do { mock_infos++; } while (0) +''' + +T6050_PRELUDE = r''' +/* Minimal harness for T6050 sleep commit/wake WDT helpers extracted from sleep-t6050.h */ +#define WDT_WD0_CTL 0x0c +#define WDT_WD2_COUNT 0x20 +#define WDT_WD2_ALARM 0x28 +#define WDT_WD2_CTL 0x2c +#define WDT_WD2_CTL_IRQ_STATUS BIT(1) +#define WDT_TICKS_PER_S 24000000u +#define WDT_SUSPEND_SECS 120u +#define T6050_WDT_COMMIT_SECS 13u +#define AON_AP_DEADLINE 0x08 +#define AON_WDT_SLEEP 0x2c +#define T6050_SEQ_WDT 2 +#define T6050_SEQS 6 + +struct t6050_ops { + const u32 *op; + unsigned int n; +}; + +struct apple_sleep_region_state { + struct t6050_ops seq[T6050_SEQS]; +}; + +struct apple_sleep { + void __iomem *wdt; + void __iomem *wdt_aux; + struct apple_sleep_region_state *region; + u32 aon_wdt_saved; + bool aon_wdt_marked; +}; + +static bool mock_t6050_seq_saw_saved; +static u32 mock_t6050_seq_saved_val; +static bool mock_t6050_wake_armed_after_readback; + +static void t6050_seq(struct apple_sleep *s, int which) +{ + assert(which == T6050_SEQ_WDT); + if (s->region && s->region->seq[T6050_SEQ_WDT].n) { + mock_t6050_seq_saw_saved = s->aon_wdt_marked; + mock_t6050_seq_saved_val = s->aon_wdt_saved; + writel(0x20u, s->wdt_aux + AON_WDT_SLEEP); + } +} + +static void apple_sleep_set_wd2(struct apple_sleep *s, unsigned int secs) +{ + if (secs == WDT_SUSPEND_SECS) { + /* Before re-arming during wake, status must be clear and reconfig read back */ + assert((mmio_regs[0x2c / 4] & BIT(1)) == 0); + mock_t6050_wake_armed_after_readback = reconfig_read_since_write; + } + writel(0, s->wdt + WDT_WD2_CTL); + writel(0, s->wdt + WDT_WD2_COUNT); + writel(secs * WDT_TICKS_PER_S, s->wdt + WDT_WD2_ALARM); + writel(1, s->wdt + WDT_WD2_CTL); +} +''' + +MAIN = r''' +static void reset_hw(bool has_reconfig, unsigned long clk_rate, bool kdump) +{ + memset(mmio_regs, 0, sizeof(mmio_regs)); + memset(wdt_aux_regs, 0, sizeof(wdt_aux_regs)); + write_log_len = 0; + mdelay_total_ms = 0; + mock_has_reconfig = has_reconfig; + mock_reconfig_size = 4; + mock_clk.rate = clk_rate; + mock_kdump = kdump; + mock_warns = 0; + mock_infos = 0; + mock_dt_timeout = 0; + wdt_ctrl_read_since_write = false; + reconfig_read_since_write = false; + registered_wdd = NULL; + current_probe_wdd = NULL; + expect_hw_running_before_wd2_write = false; + mock_sleep_active = false; + mock_sleep_reg_ret = 0; + mock_sleep_owner = NULL; + mock_sleep_reg_res = NULL; + mock_sleep_restore = NULL; + mock_sleep_data = NULL; + devm_stack_len = 0; + teardown_order_len = 0; +} + +static int find_write(bool is_reconfig, u32 off, u32 val, int from) +{ + for (int i = from; i < (int)write_log_len; i++) { + if (write_log[i].is_reconfig == is_reconfig && + write_log[i].off == off && + write_log[i].val == val) + return i; + } + return -1; +} + +static void teardown_pdev(struct platform_device *pdev) +{ + teardown_order_len = 0; + while (devm_stack_len > 0) { + struct devm_entry e = devm_stack[--devm_stack_len]; + teardown_order[teardown_order_len++] = e.kind; + if (e.kind == DEVM_ACTION && e.action) + e.action(e.data); + } + free(mock_devm_alloc); + mock_devm_alloc = NULL; + pdev->dev.drvdata = NULL; +} + +int main(void) +{ + struct platform_device pdev = {}; + struct device other_dev = {}; + struct watchdog_device *wdd; + + /* 1. Legacy WD1 path (no reconfig): unchanged behaviour, WD2 untouched */ + reset_hw(false, 24000000UL, false); + mmio_regs[0x1c / 4] = BIT(2); /* WD1_CTRL = RESET_EN armed by bootloader */ + assert(apple_wdt_probe(&pdev) == 0); + wdd = registered_wdd; + assert(wdd != NULL); + assert(watchdog_hw_running(wdd)); + assert(mmio_regs[0x14 / 4] == 30u * 24000000u); + assert(mmio_regs[0x2c / 4] == 0); + + assert(wdd->ops->start(wdd) == 0); + assert(mmio_regs[0x1c / 4] == BIT(2)); + assert(mmio_regs[0x2c / 4] == 0); + + mmio_regs[0x10 / 4] = 10u * 24000000u; + assert(wdd->ops->get_timeleft(wdd) == 20u); + assert(wdd->ops->ping(wdd) == 0); + assert(mmio_regs[0x10 / 4] == 0); + + /* Underflow guard when counter reaches or passes bite (catches old driver) */ + mmio_regs[0x10 / 4] = 35u * 24000000u; + assert(wdd->ops->get_timeleft(wdd) == 0); + + assert(wdd->ops->stop(wdd) == 0); + assert(mmio_regs[0x1c / 4] == 0); + + assert(wdd->ops->restart(wdd, 0, NULL) == 0); + assert(mmio_regs[0x1c / 4] == BIT(2)); + assert(mmio_regs[0x14 / 4] == 0); + assert(mmio_regs[0x2c / 4] == 0); + assert(mdelay_total_ms == 150); + teardown_pdev(&pdev); + + /* 2. Simple-reconfig WD2: undersized reconfig resource rejected with 0 writes */ + reset_hw(true, 24000000UL, false); + mock_reconfig_size = 2; + assert(apple_wdt_probe(&pdev) == -EINVAL); + assert(write_log_len == 0); + teardown_pdev(&pdev); + + /* 2b. Failed sleep handoff registration returns -EBUSY with 0 register writes */ + reset_hw(true, 24000000UL, false); + mock_sleep_reg_ret = -EBUSY; + mmio_regs[0x1c / 4] = BIT(2); + mmio_regs[0x2c / 4] = BIT(0); + assert(apple_wdt_probe(&pdev) == -EBUSY); + assert(write_log_len == 0); + assert(registered_wdd == NULL); + teardown_pdev(&pdev); + + /* 3. Simple-reconfig WD2: probe clears armed WD1 and safely takes over hazardous WD2 */ + reset_hw(true, 24000000UL, false); + mock_dt_timeout = 20; /* verify watchdog_init_timeout() runs before takeover */ + expect_hw_running_before_wd2_write = true; + reconfig_reg = 0x000000a5u; /* unrelated bits must be preserved */ + mmio_regs[0x1c / 4] = BIT(2); /* legacy WD1 armed before probe */ + mmio_regs[0x20 / 4] = 500u; /* hazardous: CUR >= BARK */ + mmio_regs[0x24 / 4] = 1000u; /* stale short WD2_BITE */ + mmio_regs[0x28 / 4] = 100u; /* stale short WD2_BARK */ + mmio_regs[0x2c / 4] = BIT(0) | BIT(1) | BIT(2); /* IRQ_EN + latched IRQ_STATUS + RESET_EN */ + assert(apple_wdt_probe(&pdev) == 0); + expect_hw_running_before_wd2_write = false; + wdd = registered_wdd; + assert(mock_sleep_reg_res == &mock_wdt_res); + assert(mock_infos == 2); /* both legacy WD1 and WD2 RESET_EN takeover logged */ + assert(mmio_regs[0x1c / 4] == 0); /* WD1 cleared */ + assert(watchdog_hw_running(wdd)); + assert(reconfig_reg == 0x00000095u); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x2c / 4] == BIT(0)); + assert(mmio_regs[0x28 / 4] == 20u * 24000000u); + assert(mmio_regs[0x20 / 4] == 0); + + /* Verify unified arming write order: CTRL=0, BITE=U32_MAX, CUR=0, BARK, CTRL=IRQ_STATUS, reconfig, CTRL=IRQ_EN */ + { + int i_stop = find_write(false, 0x2c, 0, 0); + int i_bite = find_write(false, 0x24, U32_MAX, i_stop); + int i_cur = find_write(false, 0x20, 0, i_bite); + int i_bark = find_write(false, 0x28, 20u * 24000000u, i_cur); + int i_clr = find_write(false, 0x2c, BIT(1), i_bark); + int i_reconfig = find_write(true, 0x2c, 0x00000095u, i_clr); + int i_en = find_write(false, 0x2c, BIT(0), i_reconfig); + assert(i_stop >= 0 && i_bite > i_stop && i_cur > i_bite && i_bark > i_cur); + assert(i_clr > i_bark && i_reconfig > i_clr && i_en > i_reconfig); + } + + /* 4. WD2 start / ping / set_timeout / get_timeleft / underflow / stop */ + write_log_len = 0; + assert(wdd->ops->set_timeout(wdd, 15) == 0); + assert(mmio_regs[0x28 / 4] == 15u * 24000000u); + assert(mmio_regs[0x2c / 4] == BIT(0)); + { + int i_cur = find_write(false, 0x20, 0, 0); + int i_bark = find_write(false, 0x28, 15u * 24000000u, 0); + assert(i_cur >= 0 && i_bark > i_cur); + } + + mmio_regs[0x20 / 4] = 5u * 24000000u; + assert(wdd->ops->get_timeleft(wdd) == 10u); + assert(wdd->ops->ping(wdd) == 0); + assert(mmio_regs[0x20 / 4] == 0); + mmio_regs[0x20 / 4] = 20u * 24000000u; + assert(wdd->ops->get_timeleft(wdd) == 0); + + /* 5. Suspend/resume WITHOUT apple_sleep: resume reprograms lost BARK and reconfig */ + set_bit(WDOG_ACTIVE, &wdd->status); + assert(apple_wdt_suspend(&pdev.dev) == 0); + assert(mmio_regs[0x2c / 4] == 0); + /* Simulate power loss clearing BARK, BITE and reconfig across suspend */ + mmio_regs[0x24 / 4] = 0; + mmio_regs[0x28 / 4] = 0; + reconfig_reg = 0; + write_log_len = 0; + assert(apple_wdt_resume(&pdev.dev) == 0); + assert(reconfig_reg == BIT(4)); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x28 / 4] == 15u * 24000000u); + assert(mmio_regs[0x20 / 4] == 0); + assert(mmio_regs[0x2c / 4] == BIT(0)); + { + int i_stop = find_write(false, 0x2c, 0, 0); + int i_bite = find_write(false, 0x24, U32_MAX, i_stop); + int i_cur = find_write(false, 0x20, 0, i_bite); + int i_bark = find_write(false, 0x28, 15u * 24000000u, i_cur); + int i_clr = find_write(false, 0x2c, BIT(1), i_bark); + int i_reconfig = find_write(true, 0x2c, BIT(4), i_clr); + int i_en = find_write(false, 0x2c, BIT(0), i_reconfig); + assert(i_stop >= 0 && i_bite > i_stop && i_cur > i_bite && i_bark > i_cur); + assert(i_clr > i_bark && i_reconfig > i_clr && i_en > i_reconfig); + } + + /* 6. Suspend/resume WITH apple_sleep active: sleep owns WD2 from .begin to .end */ + assert(mock_sleep_restore != NULL); + mock_sleep_active = true; + /* apple_sleep_begin() armed WD2 for 120 s */ + mmio_regs[0x20 / 4] = 1000u; + mmio_regs[0x28 / 4] = 120u * 24000000u; + mmio_regs[0x2c / 4] = BIT(0); + assert(apple_wdt_suspend(&pdev.dev) == 0); + /* Must NOT stop sleep's 120 s safety net */ + assert(mmio_regs[0x2c / 4] == BIT(0)); + assert(mmio_regs[0x28 / 4] == 120u * 24000000u); + /* Keepalive ping during sleep must NOT zero sleep's counter */ + assert(wdd->ops->ping(wdd) == 0); + assert(mmio_regs[0x20 / 4] == 1000u); + /* Sleep commit switched reconfig to 0x20 and wake armed 120 s */ + reconfig_reg = 0x20u; + assert(apple_wdt_resume(&pdev.dev) == 0); + /* Must NOT clobber sleep's resume safety net before .end */ + assert(reconfig_reg == 0x20u); + assert(mmio_regs[0x28 / 4] == 120u * 24000000u); + /* apple_sleep_end() clears WD2_CTL and invokes restore callback */ + mmio_regs[0x2c / 4] = 0; + mock_sleep_restore(mock_sleep_data); + mock_sleep_active = false; + assert(reconfig_reg == BIT(4)); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x28 / 4] == 15u * 24000000u); + assert(mmio_regs[0x20 / 4] == 0); + assert(mmio_regs[0x2c / 4] == BIT(0)); + + /* 6b. Per-device active(): a non-owner device still pings/suspends during sleep */ + mock_sleep_active = true; + mock_sleep_owner = &other_dev; + mmio_regs[0x20 / 4] = 1000u; + assert(wdd->ops->ping(wdd) == 0); + assert(mmio_regs[0x20 / 4] == 0); + assert(apple_wdt_suspend(&pdev.dev) == 0); + assert(mmio_regs[0x2c / 4] == 0); + assert(apple_wdt_resume(&pdev.dev) == 0); + assert(mmio_regs[0x2c / 4] == BIT(0)); + mock_sleep_owner = &pdev.dev; + mock_sleep_active = false; + + /* When watchdog is stopped, sleep .end restore must leave WD2 off */ + wdd->status = 0; + assert(wdd->ops->stop(wdd) == 0); + mock_sleep_active = true; + mmio_regs[0x2c / 4] = 0; + mock_sleep_restore(mock_sleep_data); + mock_sleep_active = false; + assert(mmio_regs[0x2c / 4] == 0); + + /* 7. Restart uses clock-derived bark delay (40 ms) and WD2, never WD1 */ + reconfig_reg = 0; + mdelay_total_ms = 0; + write_log_len = 0; + assert(wdd->ops->restart(wdd, 0, NULL) == 0); + assert(reconfig_reg == BIT(4)); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x28 / 4] == 24000000u * 40u / 1000u); + assert(mmio_regs[0x2c / 4] == BIT(0)); + assert(mmio_regs[0x1c / 4] == 0); + assert(mdelay_total_ms >= 200); + { + int i_stop = find_write(false, 0x2c, 0, 0); + int i_bite = find_write(false, 0x24, U32_MAX, i_stop); + int i_cur = find_write(false, 0x20, 0, i_bite); + int i_bark = find_write(false, 0x28, 24000000u * 40u / 1000u, i_cur); + int i_clr = find_write(false, 0x2c, BIT(1), i_bark); + int i_reconfig = find_write(true, 0x2c, BIT(4), i_clr); + int i_en = find_write(false, 0x2c, BIT(0), i_reconfig); + assert(i_stop >= 0 && i_bite > i_stop && i_cur > i_bite && i_bark > i_cur); + assert(i_clr > i_bark && i_reconfig > i_clr && i_en > i_reconfig); + } + teardown_pdev(&pdev); + /* Verify devm unwinds watchdog before sleep handoff */ + assert(teardown_order_len == 2); + assert(teardown_order[0] == DEVM_WDT); + assert(teardown_order[1] == DEVM_ACTION); + assert(mock_sleep_restore == NULL); + + /* 7b. Pre-probe legacy WD1 alone is adopted as WD2 simple-reconfig with HW_RUNNING */ + reset_hw(true, 24000000UL, false); + expect_hw_running_before_wd2_write = true; + mmio_regs[0x1c / 4] = BIT(2); /* published Aura trial-boot WD1 */ + assert(apple_wdt_probe(&pdev) == 0); + expect_hw_running_before_wd2_write = false; + wdd = registered_wdd; + assert(mock_infos == 1); + assert(mmio_regs[0x1c / 4] == 0); + assert(watchdog_hw_running(wdd)); + assert(reconfig_reg == BIT(4)); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x28 / 4] == 30u * 24000000u); + assert(mmio_regs[0x2c / 4] == BIT(0)); + teardown_pdev(&pdev); + + /* 7c. Pre-probe WD2 RESET_EN alone is adopted as WD2 simple-reconfig with HW_RUNNING */ + reset_hw(true, 24000000UL, false); + expect_hw_running_before_wd2_write = true; + mmio_regs[0x2c / 4] = BIT(2); + assert(apple_wdt_probe(&pdev) == 0); + expect_hw_running_before_wd2_write = false; + wdd = registered_wdd; + assert(mock_infos == 1); + assert(watchdog_hw_running(wdd)); + assert(reconfig_reg == BIT(4)); + assert(mmio_regs[0x2c / 4] == BIT(0)); + teardown_pdev(&pdev); + + /* 7d. Idle pre-probe with only stale latched IRQ_STATUS clears status and stays stopped */ + reset_hw(true, 24000000UL, false); + mmio_regs[0x2c / 4] = BIT(1); + assert(apple_wdt_probe(&pdev) == 0); + wdd = registered_wdd; + assert(!watchdog_hw_running(wdd)); + assert(mmio_regs[0x2c / 4] == 0); + assert(reconfig_reg == 0); + teardown_pdev(&pdev); + + /* 8. Restart bark delay scales with clk_rate (non-24 MHz) */ + reset_hw(true, 12000000UL, false); + assert(apple_wdt_probe(&pdev) == 0); + wdd = registered_wdd; + assert(wdd->ops->restart(wdd, 0, NULL) == 0); + assert(mmio_regs[0x28 / 4] == 12000000u * 40u / 1000u); + teardown_pdev(&pdev); + + /* 9. Crash kernel skips takeover (WD1 and WD2) and arms WD2 at max_hw_heartbeat_ms */ + reset_hw(true, 24000000UL, true); + mmio_regs[0x1c / 4] = BIT(2); + mmio_regs[0x2c / 4] = BIT(0); + assert(apple_wdt_probe(&pdev) == 0); + wdd = registered_wdd; + assert(!watchdog_hw_running(wdd)); + assert(mmio_regs[0x1c / 4] == 0); + assert(reconfig_reg == BIT(4)); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x28 / 4] == (U32_MAX / 24000000u) * 24000000u); + assert(mmio_regs[0x2c / 4] == BIT(0)); + teardown_pdev(&pdev); + +#ifndef SKIP_T6050_SLEEP_HELPERS + /* 10. T6050 sleep commit/wake WDT helpers save and restore wdt-aux + AON_WDT_SLEEP */ + { + struct apple_sleep_region_state reg = { .seq = { [T6050_SEQ_WDT] = { .n = 1 } } }; + struct apple_sleep s = { + .wdt = (void __iomem *)mmio_regs, + .wdt_aux = (void __iomem *)wdt_aux_regs, + .region = ®, + }; + + reset_hw(true, 24000000UL, false); + reconfig_reg = 0x00000095u; /* 0x10 routing + unrelated bits */ + reconfig_read_since_write = true; /* already settled before commit */ + mmio_regs[0x24 / 4] = U32_MAX; + mmio_regs[0x28 / 4] = 30u * 24000000u; + mmio_regs[0x2c / 4] = BIT(0); + mock_t6050_seq_saw_saved = false; + mock_t6050_seq_saved_val = 0; + + t6050_sleep_commit_wdt(&s); + assert(mock_t6050_seq_saw_saved); + assert(mock_t6050_seq_saved_val == 0x00000095u); + assert(s.aon_wdt_marked); + assert(reconfig_reg == 0x20u); + assert(mmio_regs[0x2c / 4] == BIT(0)); + assert(mmio_regs[0x28 / 4] == T6050_WDT_COMMIT_SECS * WDT_TICKS_PER_S); + + /* Wake: simulate latched IRQ_STATUS and verify CTL=0 -> clear -> readl -> restore -> readl -> set_wd2 */ + mmio_regs[0x2c / 4] = BIT(0) | BIT(1); + write_log_len = 0; + mock_t6050_wake_armed_after_readback = false; + t6050_sleep_wake_wdt(&s); + assert(!s.aon_wdt_marked); + assert(reconfig_reg == 0x00000095u); + assert(mock_t6050_wake_armed_after_readback); + assert(mmio_regs[0x2c / 4] == BIT(0)); + assert(mmio_regs[0x28 / 4] == WDT_SUSPEND_SECS * WDT_TICKS_PER_S); + { + int i_stop = find_write(false, 0x2c, 0, 0); + int i_clr = find_write(false, 0x2c, BIT(1), i_stop); + int i_rest = find_write(true, 0x2c, 0x00000095u, i_clr); + int i_arm = find_write(false, 0x2c, BIT(0), i_rest); + assert(i_stop >= 0 && i_clr > i_stop && i_rest > i_clr && i_arm > i_rest); + } + + /* When seq[T6050_SEQ_WDT] is empty, aon_wdt_marked stays false and wake leaves reconfig alone */ + reg.seq[T6050_SEQ_WDT].n = 0; + reconfig_reg = 0x10u; + reconfig_read_since_write = true; + write_log_len = 0; + t6050_sleep_commit_wdt(&s); + assert(!s.aon_wdt_marked); + write_log_len = 0; + t6050_sleep_wake_wdt(&s); + assert(find_write(true, 0x2c, 0x10u, 0) < 0); + assert(reconfig_reg == 0x10u); + } +#endif + + puts("PASS apple_wdt legacy WD1, simple-reconfig WD2, sleep handoff, and T6050 wake"); + return 0; +} +''' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--out', type=Path, help='keep build and result files here') + parser.add_argument('--cc', default='cc') + parser.add_argument('--old-ref', help='compile and run apple_wdt.c from this revision') + parser.add_argument('--mutation', help='apply a named mutation and expect failure') + args = parser.parse_args() + + source = show(args.old_ref, DRIVER) + body = extract_body(source) + if args.old_ref: + t6050_part = '#define SKIP_T6050_SLEEP_HELPERS 1\n' + else: + t6050_src = show(None, SLEEP_T6050) + t6050_helpers = extract_t6050_wdt_helpers(t6050_src) + body, t6050_helpers = apply_mutation(body, t6050_helpers, args.mutation) + t6050_part = T6050_PRELUDE + t6050_helpers + + code = PREFIX + body + t6050_part + MAIN + + def run(out): + out.mkdir(parents=True, exist_ok=True) + cfile, exe = out / 'apple-wdt.c', out / 'apple-wdt' + cfile.write_text(code) + subprocess.run([args.cc, '-std=gnu11', '-O1', '-g', '-Wall', '-Wextra', '-Werror', + '-Wno-unused-parameter', '-Wno-unused-function', + '-fsanitize=address,undefined', '-fno-sanitize-recover=all', + str(cfile), '-o', str(exe)], check=True) + res = subprocess.run([str(exe)], capture_output=True, text=True) + print(res.stdout + res.stderr, end='') + return res.returncode + + if args.out: + return run(args.out) + with tempfile.TemporaryDirectory(prefix='apple-wdt-') as out: + return run(Path(out)) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/asahi/atc-dp-drive-tests.py b/tools/asahi/atc-dp-drive-tests.py new file mode 100755 index 00000000000000..be0c0e23bf710e --- /dev/null +++ b/tools/asahi/atc-dp-drive-tests.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""How the ATC PHY answers a DP drive level request, and what the firmware-27 drive call does with it. + +Builds the production atcphy_dpphy_configure() against stubs and runs it over +PHY generation, DP state and the request's set_voltages/set_rate/set_lanes. A +PHY without drive level control (the T8103 generation: T8103, T8112, T600x, +T602x) accepts a drive-only request and keeps the levels its tunables set, as +the T8132 branch does; a drive request together with a rate or lane change is +refused. The firmware-27 SetDriveSettings handler passes every PHY error back +to DCP (no errno is special), so a real failure still fails the call. + +--mutation names a change to the production source that the matrix must kill. +""" +import argparse +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +MUTATIONS = { + # The PR's first version: a drive-only request answered -EOPNOTSUPP. + 'eopnotsupp': ('\t\treturn 0;\n\t}\n\tif (opts->set_voltages || opts->set_lanes)', + '\t\treturn -EOPNOTSUPP;\n\t}\n\tif (opts->set_voltages || opts->set_lanes)'), + # Accept drive levels that come with a rate change. + 'accept-with-rate': ('opts->set_voltages && !opts->set_rate && !opts->set_lanes', + 'opts->set_voltages && !opts->set_lanes'), + # The pre-PR refusal of every drive request. + 'refuse-drive': ('opts->set_voltages && !opts->set_rate && !opts->set_lanes', '0'), +} + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--mutation', choices=sorted(MUTATIONS)) +args = parser.parse_args() + +root = Path(__file__).resolve().parents[2] +atc_c = (root / 'drivers/phy/apple/atc.c').read_text() +drive_inc = (root / 'drivers/gpu/drm/apple/dptx-drive-v27.inc').read_text() + + +def function(source, marker): + start = source.index(marker) + opening = source.index('{', start) + end, depth = opening + 1, 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +configure = function(atc_c, 'static int atcphy_dpphy_configure(struct phy *phy,') +# Selected by the PHY's generation and hardware flags, never by a compatible. +assert 'compatible' not in configure and 'of_machine' not in configure + +# The firmware-27 drive call returns every PHY error to DCP unchanged. +drive = function(drive_inc, 'static int dptxport_call_drive_v27(') +call = drive[drive.index('ret = phy_configure(dptx->atcphy, &opts);'):] +assert re.match(r'ret = phy_configure\(dptx->atcphy, &opts\);\s*if \(ret\)\s*return ret;', call), \ + 'dptxport_call_drive_v27() must pass every phy_configure() error back' +assert 'EOPNOTSUPP' not in drive + +if args.mutation: + old, new = MUTATIONS[args.mutation] + assert configure.count(old) == 1, args.mutation + configure = configure.replace(old, new) + +program = r''' +#include +#include +#include +#include +typedef unsigned int u32; +enum atcphy_dp_link_rate { ATCPHY_DP_LINK_RATE_RBR, ATCPHY_DP_LINK_RATE_HBR, ATCPHY_DP_LINK_RATE_HBR2, + ATCPHY_DP_LINK_RATE_HBR3 }; +enum { ATCPHY_GENERATION_T8103, ATCPHY_GENERATION_T8122, ATCPHY_GENERATION_T8132 }; +enum { APPLE_ATCPHY_MODE_OFF, APPLE_ATCPHY_MODE_DP, APPLE_ATCPHY_MODE_USB3_DP }; +struct phy_configure_opts_dp { u32 link_rate, lanes, voltage[4], pre[4]; bool set_rate, set_lanes, set_voltages; }; +union phy_configure_opts { struct phy_configure_opts_dp dp; }; +struct hw { int gen; bool has_t8140_dp, dp_t8122; }; +struct apple_atcphy { const struct hw *hw; void *dev; int mode; int lock; }; +struct phy { struct apple_atcphy *a; }; +static struct apple_atcphy *phy_get_drvdata(struct phy *p) { return p->a; } +static bool dp_on; +static int calls_rate, calls_other, last_rate = -1; +static bool atcphy_t8132_dp_on(struct apple_atcphy *a) { return dp_on; } +static int j700_dp_configure(struct apple_atcphy *a, struct phy_configure_opts_dp *o) { calls_other++; return 0; } +static int atcphy_dpphy_configure_t8122(struct apple_atcphy *a, struct phy_configure_opts_dp *o) { calls_other++; return 0; } +static void atcphy_restore_after_pd_off(struct apple_atcphy *a) { } +static int atcphy_dp_set_rate_t8122(struct apple_atcphy *a, u32 r) { calls_other++; return 0; } +static int atcphy_dp_configure(struct apple_atcphy *a, enum atcphy_dp_link_rate lr) { calls_rate++; last_rate = lr; return 0; } +#define guard(x) (void) +#define dev_dbg(...) do { } while (0) +#define dev_err(...) do { } while (0) +''' + configure + r''' +int main(void) +{ + static const struct hw t8103 = { ATCPHY_GENERATION_T8103 }; + struct apple_atcphy a = { .hw = &t8103, .mode = APPLE_ATCPHY_MODE_DP }; + struct phy p = { &a }; + unsigned cases = 0; + + for (unsigned v = 0; v < 2; v++) + for (unsigned r = 0; r < 2; r++) + for (unsigned l = 0; l < 2; l++) { + union phy_configure_opts o = { .dp = { .set_voltages = v, .set_rate = r, .set_lanes = l, + .link_rate = 5400, .voltage = { 2 }, .pre = { 1 } } }; + int ret; + + calls_rate = calls_other = 0; + ret = atcphy_dpphy_configure(&p, &o); + if (v && !r && !l) + /* A drive-only request: accepted, the PHY is not touched. */ + assert(ret == 0 && !calls_rate && !calls_other); + else if (v || l) + /* Drive levels with a rate or lanes, or lanes at all: refused, nothing done. */ + assert(ret == -EINVAL && !calls_rate && !calls_other); + else if (r) + assert(ret == 0 && calls_rate == 1 && last_rate == ATCPHY_DP_LINK_RATE_HBR2); + else + assert(ret == 0 && !calls_rate && !calls_other); + cases++; + } + /* An unknown rate is still refused. */ + union phy_configure_opts bad = { .dp = { .set_rate = true, .link_rate = 4321 } }; + assert(atcphy_dpphy_configure(&p, &bad) == -EINVAL); + + /* T8132 keeps its own answers: DP off is -EOPNOTSUPP, a drive-only request with DP on is 0. */ + static const struct hw t8132 = { ATCPHY_GENERATION_T8132 }; + a.hw = &t8132; + union phy_configure_opts drv = { .dp = { .set_voltages = true } }; + dp_on = false; + assert(atcphy_dpphy_configure(&p, &drv) == -EOPNOTSUPP); + dp_on = true; + assert(atcphy_dpphy_configure(&p, &drv) == 0); + /* T8122-class PHYs go to their own handler. */ + static const struct hw t8122 = { ATCPHY_GENERATION_T8122, .dp_t8122 = true }; + a.hw = &t8122; + calls_other = 0; + assert(atcphy_dpphy_configure(&p, &drv) == 0 && calls_other == 1); + printf("%u cases\n", cases); + return 0; +} +''' + +with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / 'test.c' + src.write_text(program) + exe = src.with_suffix('') + subprocess.run(['cc', '-Werror', '-Wall', '-Wno-unused-function', '-Wno-unused-value', + '-fsanitize=address,undefined', str(src), '-o', str(exe)], check=True) + run = subprocess.run([str(exe)]) + if run.returncode: + sys.exit(f'FAIL: the drive matrix exited {run.returncode}') +print('PASS ATC PHY without drive control accepts a drive-only DP request; firmware-27 drive call passes PHY errors back') diff --git a/tools/asahi/atc-usb3-tests.py b/tools/asahi/atc-usb3-tests.py index 3a7955197c9f9a..1ca35bd27ef046 100644 --- a/tools/asahi/atc-usb3-tests.py +++ b/tools/asahi/atc-usb3-tests.py @@ -9,7 +9,7 @@ T600x/T8112/T602x still match the T8103 PHY fallback but keep their previous single-poll/BIST/role behavior. OF compatible lookup is a modeled boundary. The DT-to-driver match contract is checked from the actual sources. -T8132 cases cover CIO ownership during USB host shutdown; its lane setup +CIO ownership during USB host shutdown is covered on T8103 and T8132; T8132 lane setup and electrical behavior are not modeled. Hardware qualification remains necessary. Run --mutations for sensitivity checks. """ @@ -62,7 +62,9 @@ def block(source, marker): static unsigned reports; #define dev_warn(...) ((void)reports++) #define dev_err(...) ((void)reports++) +#define dev_info(...) ((void)0) #define dev_dbg(...) ((void)0) +#define dev_info(...) ((void)0) #define lockdep_assert_held(...) ((void)0) #define guard(which) (void) #define IS_ENABLED(x) 0 @@ -78,7 +80,7 @@ def block(source, marker): STUBS = r''' struct atcphy_hw { enum atcphy_generation gen; bool has_t8140_dp, dp_t8122, has_usb4, park_pipe_unlocked, park_dummy_phy, usb2_only; - bool clear_boot_hold, dp_banked_tunables; }; + bool clear_boot_hold, dp_banked_tunables, pipe_lock_unacked; }; struct device_node { const char *const *compatible; unsigned int count; }; static bool of_device_is_compatible(const struct device_node *root, const char *compatible) { if (!root) return false; @@ -98,9 +100,11 @@ def block(source, marker): enum atcphy_pipehandler_state pipe_state; enum atcphy_mode typec_mode; bool pipe_pending, t8103_dummy_pending, t8103_usb3_retry, t8103_usb3_workaround, mode_dirty, usb_off_pending; - bool host_active, usb3_port_off, dp_only, ss_tunables, fixed_usb2, t8140_dp_tunables, dp_tunables; + bool host_active, usb3_port_off, dp_only, ss_tunables, fixed_usb2, fixed_usb3, t8140_dp_tunables, dp_tunables; /* T8132 ownership is tested without entering its lane-setup backend. */ bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; + /* T8132: SuperSpeed device mode is not supported by this driver; keep USB2. */ + bool t8132_device; struct { void *usb3_dp; } tunables; }; struct phy { struct apple_atcphy *data; }; @@ -113,14 +117,14 @@ def block(source, marker): static struct atcphy_hw hw; static struct apple_atcphy p; static struct phy phy; -static unsigned polls, sleeps, sets, clears, muxes, bist_old, bist_new; +static unsigned polls, sleeps, sets, clears, muxes, bist_old, bist_new, bist_t8132; static unsigned configure_calls, restore_calls, unlocks, warnings; static unsigned dummy_muxes, pending_seen_at_unlock; static unsigned usb2_power_off_calls; static unsigned ack_on; static int check_ret, bist_ret, unlock_ret, configure_ret; static bool concurrent_override_change; -static bool model_t8132_off; +static bool model_t8132_off, model_t8132_usb2, model_t8132_usb3, model_t8132_pipe; static u32 readl(const void *ptr) { u32 v; memcpy(&v, ptr, sizeof(v)); return v; } static void writel(u32 val, void *ptr) { memcpy(ptr, &val, sizeof(val)); } static void set32(void *ptr, u32 mask) { @@ -144,7 +148,7 @@ def block(source, marker): return ack_on && polls >= ack_on ? PIPEHANDLER_LOCK_EN : 0; } #define readl_poll_timeout(addr,val,cond,delay,timeout) \ - ({ assert((delay) == 10 && (timeout) == 1000); \ + ({ assert((delay) == 10 && (timeout) == (hw.gen == ATCPHY_GENERATION_T8132 ? 6000 : 1000)); \ (val) = poll_value(addr); (cond) ? 0 : -ETIMEDOUT; }) static void usleep_range(unsigned lo, unsigned hi) { assert(lo == 5000 && hi == 10000); sleeps++; @@ -177,13 +181,26 @@ def block(source, marker): static int atcphy_usb2_power_off(struct apple_atcphy *a) { (void)a; usb2_power_off_calls++; return 0; } -/* Only an explicitly expected T8132 OFF boundary is modeled, not lane setup. */ +/* Only explicitly expected T8132 mode boundaries are modeled, not lane setup. */ static int atcphy_configure_t8132(struct apple_atcphy *a, enum atcphy_mode mode) { - assert(model_t8132_off && mode == APPLE_ATCPHY_MODE_OFF); - configure_calls++;a->mode=mode;a->mode_dirty=false;return 0; + assert((model_t8132_off && mode == APPLE_ATCPHY_MODE_OFF) || + (model_t8132_usb2 && mode == APPLE_ATCPHY_MODE_USB2) || + (model_t8132_usb3 && mode == APPLE_ATCPHY_MODE_USB3)); + if (a->pipe_pending || a->pipe_state != ATCPHY_PIPEHANDLER_STATE_DUMMY) + return -EBUSY; + if (a->t8132_common_owned && a->host_active) + return -EBUSY; + configure_calls++; + if (configure_ret) { a->mode_dirty = true; return configure_ret; } + a->mode = mode; a->mode_dirty = false; return 0; } static int atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *a) { - (void)a; assert(!"T8132 PIPE setup reached"); return -EINVAL; + (void)a; + assert(model_t8132_pipe); + bist_t8132++; return bist_ret; +} +static int atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *a) { + (void)a; assert(!"T8152 PIPE setup reached"); return -EINVAL; } static void atcphy_usb2_power_on(struct apple_atcphy *a) { (void)a; assert(!"USB2-only power restore reached"); @@ -207,7 +224,7 @@ def block(source, marker): const struct device_node root = {compatibles, 1}; p.t8103_usb3_workaround = atcphy_has_t8103_usb3_workaround(&hw, &root); phy.data = &p; - polls = sleeps = sets = clears = muxes = bist_old = bist_new = 0; + polls = sleeps = sets = clears = muxes = bist_old = bist_new = bist_t8132 = 0; configure_calls = restore_calls = unlocks = warnings = reports = 0; dummy_muxes = pending_seen_at_unlock = 0; usb2_power_off_calls = 0; @@ -215,6 +232,9 @@ def block(source, marker): check_ret = bist_ret = unlock_ret = configure_ret = 0; concurrent_override_change = false; model_t8132_off = false; + model_t8132_usb2 = false; + model_t8132_usb3 = false; + model_t8132_pipe = false; } static void reset_machine(enum atcphy_generation generation, const char *machine) { reset(generation, false); @@ -398,14 +418,17 @@ def block(source, marker): assert(atcphy_usb3_power_off(&phy)==-ETIMEDOUT);assert(!configure_calls); unlock_ret=0;assert(!atcphy_usb3_power_off(&phy));assert(p.mode==APPLE_ATCPHY_MODE_USB3_DP&&!configure_calls&&!p.t8103_usb3_retry&&!p.t8103_dummy_pending); } -static void t8132_usb_stop_keeps_cio_until_mux_disconnect(void) { +static void usb_stop_keeps_cio_until_mux_disconnect(void) { const enum atcphy_mode modes[] = { APPLE_ATCPHY_MODE_TBT, APPLE_ATCPHY_MODE_USB4 }; - for (unsigned i=0;i<2;i++) { - reset(ATCPHY_GENERATION_T8132,false);p.mode=modes[i];p.typec_mode=modes[i];p.host_active=true; + /* Every generation: T8112 and T600x run the T8103 PHY sequence. */ + const enum atcphy_generation gens[] = { ATCPHY_GENERATION_T8103, ATCPHY_GENERATION_T8132 }; + for (unsigned g=0;g<2;g++) for (unsigned i=0;i<2;i++) { + reset(gens[g],false);p.mode=modes[i];p.typec_mode=modes[i];p.host_active=true; assert(!atcphy_usb3_power_off(&phy)); assert(!p.host_active&&p.mode==modes[i]&&!configure_calls&&atcphy_rpm_busy(&p)); assert(!atcphy_dwc3_reset_assert(&p.rcdev,0)); assert(p.mode==modes[i]&&!configure_calls&&atcphy_rpm_busy(&p)&&usb2_power_off_calls==1); + if (gens[g]!=ATCPHY_GENERATION_T8132) continue; /* the OFF lane setup is modeled for T8132 only */ model_t8132_off=true; assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_OFF)); assert(p.mode==APPLE_ATCPHY_MODE_OFF&&configure_calls==1&&!atcphy_rpm_busy(&p)); @@ -425,6 +448,70 @@ def block(source, marker): setup_legacy_usb3();p.t8103_dummy_pending=p.t8103_usb3_retry=true;p.pipe_pending=true; atcphy_setup_pipehandler(&p);assert(!p.t8103_dummy_pending&&!p.t8103_usb3_retry&&!p.pipe_pending&&p.pipe_state==ATCPHY_PIPEHANDLER_STATE_DUMMY); } +/* + * SuperSpeed device mode is not supported by this driver on T8132: a device + * role takes the lanes to USB2 while preserving typec_mode, survives SAFE + * bounces, clears on power_off or host swap, and restores USB3 on host swap. + */ +static void t8132_device_role_runs_usb2(void) { + struct typec_mux_state state={.mode=TYPEC_STATE_USB}; + reset(ATCPHY_GENERATION_T8132,false);p.t8132_ss=true;p.mode=APPLE_ATCPHY_MODE_USB3;p.typec_mode=APPLE_ATCPHY_MODE_USB3; + assert(atcphy_typec_target_mode(&p,&state)==APPLE_ATCPHY_MODE_USB3); + model_t8132_usb2=true; + assert(!atcphy_usb3_set_mode(&phy,PHY_MODE_USB_DEVICE,0)); + assert(p.t8132_device&&p.mode==APPLE_ATCPHY_MODE_USB2&&p.typec_mode==APPLE_ATCPHY_MODE_USB3); + assert(configure_calls==1&&!p.host_active&&p.pipe_state==ATCPHY_PIPEHANDLER_STATE_DUMMY); + /* A later USB3 request from the port controller stays on USB2 and keeps typec_mode. */ + assert(atcphy_typec_target_mode(&p,&state)==APPLE_ATCPHY_MODE_USB3); + assert(atcphy_mux_in_mode(&p,APPLE_ATCPHY_MODE_USB3)); + assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_USB3)); + assert(p.mode==APPLE_ATCPHY_MODE_USB2&&p.typec_mode==APPLE_ATCPHY_MODE_USB3&&configure_calls==1); + /* The device role again on USB2: nothing to change. */ + assert(!atcphy_usb3_set_mode(&phy,PHY_MODE_USB_DEVICE,0));assert(configure_calls==1); + /* Pin-D USB3+DP drops to USB2 unconditionally; 4-lane DP keeps USB2 on its own wires. */ + assert(atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_USB3_DP)==APPLE_ATCPHY_MODE_USB2); + p.t8132_dp_alt=true; + assert(atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_USB3_DP)==APPLE_ATCPHY_MODE_USB2); + assert(atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_DP)==APPLE_ATCPHY_MODE_DP); + assert(atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_OFF)==APPLE_ATCPHY_MODE_OFF); + p.t8132_dp_alt=false; + /* A SAFE/OFF mux bounce does not clear the active device role. */ + model_t8132_off=true; + assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_OFF)); + assert(p.t8132_device&&p.mode==APPLE_ATCPHY_MODE_OFF&&p.typec_mode==APPLE_ATCPHY_MODE_OFF); + assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_USB3)); + assert(p.t8132_device&&p.mode==APPLE_ATCPHY_MODE_USB2&&p.typec_mode==APPLE_ATCPHY_MODE_USB3); + /* Leaving the role via power_off clears t8132_device so the next partner gets USB3. */ + assert(!atcphy_usb3_power_off(&phy));assert(!p.t8132_device&&p.mode==APPLE_ATCPHY_MODE_OFF); + model_t8132_usb3=true; + assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_USB3)); + assert(p.mode==APPLE_ATCPHY_MODE_USB3&&p.typec_mode==APPLE_ATCPHY_MODE_USB3); + /* A failed device-role switch (e.g. host still owns common/PIPE) must not stick t8132_device. */ + reset(ATCPHY_GENERATION_T8132,false);p.t8132_ss=true;p.mode=APPLE_ATCPHY_MODE_USB3; + p.typec_mode=APPLE_ATCPHY_MODE_USB3;p.t8132_common_owned=true;p.host_active=true; + model_t8132_usb2=true; + assert(atcphy_usb3_set_mode(&phy,PHY_MODE_USB_DEVICE,0)==-EBUSY); + assert(!p.t8132_device&&p.host_active&&p.mode==APPLE_ATCPHY_MODE_USB3&&p.typec_mode==APPLE_ATCPHY_MODE_USB3); + /* A failed route after USB2 also must not stick t8132_device. */ + reset(ATCPHY_GENERATION_T8132,false);p.t8132_ss=true;p.mode=APPLE_ATCPHY_MODE_USB2; + p.typec_mode=APPLE_ATCPHY_MODE_USB3;p.mode_dirty=true; + assert(atcphy_usb3_set_mode(&phy,PHY_MODE_USB_DEVICE,0)==-EBUSY); + assert(!p.t8132_device); + /* Direct device -> host DR swap restores USB3 lanes before host_active and routes PIPE. */ + reset(ATCPHY_GENERATION_T8132,false);p.t8132_ss=true;p.mode=APPLE_ATCPHY_MODE_USB2; + p.typec_mode=APPLE_ATCPHY_MODE_USB3;p.t8132_device=true;p.t8132_common_owned=true; + model_t8132_usb3=true;model_t8132_pipe=true; + configure_ret=-EIO; + assert(atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0)==-EIO); + assert(p.t8132_device&&!p.host_active&&p.mode==APPLE_ATCPHY_MODE_USB2); + configure_ret=0;p.mode_dirty=false; + assert(!atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0)); + assert(!p.t8132_device&&p.host_active&&p.mode==APPLE_ATCPHY_MODE_USB3&&p.typec_mode==APPLE_ATCPHY_MODE_USB3); + assert(p.pipe_state==ATCPHY_PIPEHANDLER_STATE_USB3&&bist_t8132==1); + /* Without the SuperSpeed banks the port was USB2 already: no lane change. */ + reset(ATCPHY_GENERATION_T8132,false);p.mode=APPLE_ATCPHY_MODE_USB2; + assert(!atcphy_usb3_set_mode(&phy,PHY_MODE_USB_DEVICE,0));assert(!p.t8132_device&&!configure_calls); +} static void target_mode_table_and_dirty(void) { reset(ATCPHY_GENERATION_T8103,false);struct typec_mux_state state={.mode=TYPEC_DP_STATE_D};struct typec_altmode alt={.svid=USB_TYPEC_DP_SID};state.alt=&alt; assert(atcphy_typec_target_mode(&p,&state)==APPLE_ATCPHY_MODE_USB3_DP);state.mode=TYPEC_DP_STATE_C; @@ -602,6 +689,7 @@ def block(source, marker): } int main(void) { TEST(both_role_and_typec_orders_complete_usb3); + TEST(t8132_device_role_runs_usb2); TEST(nonusb3_commit_discharges_deferred_role); TEST(deferred_role_survives_configuration_failures); TEST(admission_requires_machine_and_generation); @@ -614,7 +702,7 @@ def block(source, marker): TEST(usb4_and_dead_parking_single_poll);TEST(early_host_and_device);TEST(early_admission_and_failure);TEST(later_off_and_bist_unchanged);TEST(success_only_all_generations); TEST(live_lock_failure_restores_masks);TEST(live_park_then_pending_completion);TEST(legacy_live_dispatch_and_generation);TEST(pending_blocks_lane_and_backend); TEST(canceled_lane_change_reconnects);TEST(role_finishes_pending);TEST(target_failure_preserves_reconnect);TEST(nonusb_commit_clears_retry);TEST(dp_assignment_d_retains_usb3);TEST(modern_safe_refusal_retained); - TEST(fixed_hub_host_dispatch);TEST(reset_release_retries_before_writes);TEST(reset_assert_failure_and_stop);TEST(power_off_preserves_dp_and_finishes_pending);TEST(t8132_usb_stop_keeps_cio_until_mux_disconnect);TEST(setup_known_reset_clears_obligations);TEST(target_mode_table_and_dirty); + TEST(fixed_hub_host_dispatch);TEST(reset_release_retries_before_writes);TEST(reset_assert_failure_and_stop);TEST(power_off_preserves_dp_and_finishes_pending);TEST(usb_stop_keeps_cio_until_mux_disconnect);TEST(setup_known_reset_clears_obligations);TEST(target_mode_table_and_dirty); TEST(lock_timeout_left_to_caller); printf("%u ATCPHY USB3 host cases passed\n",tests); } @@ -717,7 +805,10 @@ def harness(source): # The PIPE backend of a mode, which T8132 CIO keeps on the dummy one. helpers = [block(source, "static bool atcphy_mode_is_cio("), block(source, "static bool atcphy_t8132_dp_on("), - block(source, "static enum atcphy_pipehandler_state\natcphy_pipe_state_for(")] + block(source, "static enum atcphy_mode atcphy_t8132_device_mode("), + block(source, "static enum atcphy_pipehandler_state\natcphy_pipe_state_for("), + # atcphy_usb3_set_mode() moves a T8132 device role to USB2 through it. + "static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode target_mode);"] functions = "\n".join(helpers + [block(source, "static " + kind + " " + name + "(") for kind, name in function_specs]) configure = block(source, "static int atcphy_configure(") @@ -731,13 +822,35 @@ def harness(source): return PRELUDE + defines + "\n" + "\n".join(usb_defines) + "\n" + types + "\n" + table + stubs + functions + scope_c + TESTS -MUTATIONS = {'t8132-usb-stop-keeps-dirty-cio': ('atcphy_usb3_power_off', - '&&\n\t !atcphy->mode_dirty)', ')'), - 't8132-usb-stop-drops-cio': ('atcphy_usb3_power_off', - 'atcphy->hw->gen == ATCPHY_GENERATION_T8132 && atcphy_mode_is_cio(atcphy->mode)', 'false'), - 't8132-usb-stop-keeps-usb-too': ('atcphy_usb3_power_off', - 'atcphy->hw->gen == ATCPHY_GENERATION_T8132 && atcphy_mode_is_cio(atcphy->mode)', - 'atcphy->hw->gen == ATCPHY_GENERATION_T8132'), +MUTATIONS = {'usb-stop-keeps-dirty-cio': ('atcphy_usb3_power_off', + 'atcphy_mode_is_cio(atcphy->mode) && !atcphy->mode_dirty)', 'atcphy_mode_is_cio(atcphy->mode))'), + 'usb-stop-drops-cio': ('atcphy_usb3_power_off', + 'atcphy_mode_is_cio(atcphy->mode) && !atcphy->mode_dirty', 'false'), + 'usb-stop-keeps-usb-too': ('atcphy_usb3_power_off', + 'atcphy_mode_is_cio(atcphy->mode) && !atcphy->mode_dirty', '!atcphy->mode_dirty'), + 'usb-stop-keeps-cio-t8132-only': ('atcphy_usb3_power_off', + 'atcphy_mode_is_cio(atcphy->mode) && !atcphy->mode_dirty', + 'atcphy->hw->gen == ATCPHY_GENERATION_T8132 && atcphy_mode_is_cio(atcphy->mode) && !atcphy->mode_dirty'), +'t8132-device-role-refused': ('atcphy_usb3_set_mode', + 'if (atcphy->t8132_ss) {', + 'if (atcphy->t8132_ss) {\n\t\t\treturn -EOPNOTSUPP;'), + 't8132-device-role-not-remembered': ('atcphy_mux_switch', + 'if (atcphy->t8132_device)\n\t\ttarget_mode = atcphy_t8132_device_mode(target_mode);', + 'if (false)\n\t\ttarget_mode = atcphy_t8132_device_mode(target_mode);'), + 't8132-device-role-in-mode-ignores-flag': ('bool atcphy_mux_in_mode', + 'if (atcphy->t8132_device)\n\t\ttarget_mode = atcphy_t8132_device_mode(target_mode);', + 'if (false)\n\t\ttarget_mode = atcphy_t8132_device_mode(target_mode);'), + 't8132-device-role-sticks-after-poweroff': ('atcphy_usb3_power_off', + 'atcphy->t8132_device = false;', '(void)0;'), + 't8132-device-role-set-on-route-error': ('atcphy_usb3_set_mode', + 'if (!ret && atcphy->t8132_ss && mode == PHY_MODE_USB_DEVICE)\n\t\tatcphy->t8132_device = true;', + 'if (atcphy->t8132_ss && mode == PHY_MODE_USB_DEVICE)\n\t\tatcphy->t8132_device = true;'), + 't8132-device-to-host-stays-usb2': ('atcphy_usb3_set_mode', + 'if (atcphy->mode == APPLE_ATCPHY_MODE_USB2 &&\n\t\t\t atcphy_t8132_device_mode(target) != target) {', + 'if (false) {'), + 't8132-pin-d-keeps-dp': ('enum atcphy_mode atcphy_t8132_device_mode', + 'mode == APPLE_ATCPHY_MODE_USB3 || mode == APPLE_ATCPHY_MODE_USB3_DP', + 'mode == APPLE_ATCPHY_MODE_USB3'), 'no-live-retry': ('atcphy_pipehandler_lock_live', '? 10 : 1;', '? 1 : 1;'), 'retry-later-generations': ('atcphy_pipehandler_lock_live', '? 10 : 1;', '? 10 : 10;'), 'sleep-after-last': ('atcphy_pipehandler_lock_live', 'if (attempt + 1 < attempts)', 'if (true)'), diff --git a/tools/asahi/aurora-wake-output-tests.py b/tools/asahi/aurora-wake-output-tests.py new file mode 100755 index 00000000000000..3e3db15fe8487b --- /dev/null +++ b/tools/asahi/aurora-wake-output-tests.py @@ -0,0 +1,225 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Host tests of where the tools/aurora-wake Bluetooth wake diagnostics write. + +They run as root, so their evidence must go to a directory they create for +themselves: open_out() in bt-wake-cycle.sh and bt-wake-power.sh. The tests +extract that function, as test-s2idle-rtc-regression.sh does for its kernel log +collection, and check that: +- the default directory is a fresh private one, so files planted under the old + predictable /var/tmp/bt-wake paths, symlinked to victims, are never written; +- -o refuses relative, existing, symlinked and dangling paths, and parents that + others can change, and creates a new private directory otherwise; +- a directory renamed and replaced by a symlink after open_out() still takes + every write, and noclobber refuses an existing file; +- no script still names a fixed /var/tmp/bt-wake path, writes a kernel + attribute without >| or pipes evidence through a truncating tee. + +Usage: aurora-wake-output-tests.py --out DIR +""" +import argparse +import os +import re +import stat +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +WAKE = ROOT / 'tools/aurora-wake' +SCRIPTS = ['bt-wake-cycle.sh', 'bt-wake-power.sh'] +ALL = SCRIPTS + ['attended-bt-wake.sh', 'bt-wake-emulated.sh'] +BEGIN = '# --- private output directory' +END = '# --- end of private output directory' + +failures = [] + + +def check(ok, what): + print(('ok: ' if ok else 'FAIL line {}: '.format(sys._getframe(1).f_lineno)) + what) + if not ok: + failures.append(what) + + +def section(name): + text = (WAKE / name).read_text() + start = text.find(BEGIN) + end = text.find(END, start) + if start < 0 or end < 0: + return None + return text[start:end + len(END)] + '\n' + + +def bash(lib, script, cwd): + """Run `script` in bash with open_out() defined; returns (rc, stdout).""" + p = subprocess.run(['bash', '-c', 'set -u\n. "$1"\n' + script, 'test', str(lib)], + cwd=cwd, capture_output=True, text=True) + return p.returncode, p.stdout + p.stderr + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--out', required=True, type=Path) + work = ap.parse_args().out.resolve() + work.mkdir(parents=True, exist_ok=True) + + libs = {name: section(name) for name in SCRIPTS} + for name, text in libs.items(): + check(text is not None, f'{name} has an open_out() section') + check(len(set(libs.values())) == 1, 'bt-wake-cycle.sh and bt-wake-power.sh share one open_out()') + if None not in libs.values(): + lib = work / 'open_out.sh' + lib.write_text(libs[SCRIPTS[0]]) + behaviour(lib, work) + static() + + if failures: + print(f'{len(failures)} check(s) failed', file=sys.stderr) + return 1 + print('all checks passed') + return 0 + + +def behaviour(lib, work): + + # The issue's attack on the old default: someone owns the shared parent + # and has planted timestamped leaves whose outputs are symlinks to + # victims. The default directory is now a fresh one beside them. + base = work / 'var-tmp' + base.mkdir() + os.chmod(base, 0o1777) + victims = work / 'victims' + victims.mkdir() + planted = base / 'bt-wake' + names = ['results.txt', 'before.txt', 'dmesg.txt', 'after.txt', 'verdict.txt', 'suspending', + 'rtcwake.txt', 'hci.btsnoop', 'bad-lines.txt', 'device.txt'] + for leaf in ['cycle-20261126-120000', 'power-20261126-120000', 'attended-120000']: + (planted / leaf).mkdir(parents=True) + for n in names: + victim = victims / f'{leaf}-{n}' + victim.write_text('ORIGINAL\n') + (planted / leaf / n).symlink_to(victim) + for prefix in ['bt-wake-cycle', 'bt-wake-power']: + rc, log = bash(lib, f'''open_out "" "{base}" {prefix} || exit 9 + echo "$out"; echo header > results.txt; echo row | tee -a results.txt > /dev/null + dmesg_text=x; echo "$dmesg_text" > dmesg.txt; : > hci.btsnoop + echo verdict > verdict.txt; pwd -P''', work) + lines = log.split() + check(rc == 0 and len(lines) == 2 and lines[0] == lines[1], f'{prefix}: default directory opened and entered') + if rc == 0: + made = Path(lines[0]) + check(made.parent == base and made.name.startswith(prefix + '.') and made.name != prefix + '.XXXXXXXX', + f'{prefix}: default directory is a fresh name under the base, not under bt-wake/') + mode = made.stat() + check(stat.S_IMODE(mode.st_mode) == 0o700 and mode.st_uid == os.getuid(), f'{prefix}: it is private') + check((made / 'results.txt').read_text() == 'header\nrow\n', f'{prefix}: evidence written inside it') + check(all(v.read_text() == 'ORIGINAL\n' for v in victims.iterdir()), 'no planted symlink target was written') + + # -o refusals: nothing may be created or written through these. + private = work / 'private' + private.mkdir(mode=0o700) + existing = private / 'existing' + existing.mkdir() + (private / 'link').symlink_to(existing) + (private / 'dangling').symlink_to(private / 'nowhere') + (private / 'file').write_text('ORIGINAL\n') + open_dir = work / 'open' + open_dir.mkdir() + os.chmod(open_dir, 0o777) + group_dir = work / 'group' + group_dir.mkdir() + os.chmod(group_dir, 0o775) + under_open = private / 'inner-open' + under_open.mkdir() + os.chmod(under_open, 0o757) + refused = { + 'relative path': 'relative/out', + 'existing directory': str(existing), + 'symlink to a directory': str(private / 'link'), + 'dangling symlink': str(private / 'dangling'), + 'existing file': str(private / 'file'), + 'missing parent': str(private / 'missing' / 'out'), + 'world-writable parent': str(open_dir / 'out'), + 'group-writable parent': str(group_dir / 'out'), + 'writable ancestor': str(under_open / 'deeper' / 'out'), + 'dot leaf': str(private) + '/.', + 'dot-dot leaf': str(private) + '/..', + } + (under_open / 'deeper').mkdir() + for what, path in refused.items(): + before = sorted(p.name for p in private.iterdir()) + rc, log = bash(lib, f'open_out "{path}" "{base}" x || exit 9; echo opened', work) + check(rc == 9 and 'opened' not in log, f'-o {what} is refused') + check(sorted(p.name for p in private.iterdir()) == before, f'-o {what} creates nothing') + check((private / 'file').read_text() == 'ORIGINAL\n' and not (private / 'nowhere').exists(), + '-o refusals wrote through nothing') + check(not (open_dir / 'out').exists() and not (group_dir / 'out').exists() + and not (under_open / 'deeper' / 'out').exists(), '-o below a writable parent or ancestor creates nothing') + + # -o accepted: a new leaf below a private parent, and below a sticky one. + sticky = work / 'sticky' + sticky.mkdir() + os.chmod(sticky, 0o1777) + for what, path in {'private parent': private / 'new', 'sticky parent': sticky / 'new'}.items(): + rc, log = bash(lib, f'open_out "{path}" "{base}" x || exit 9; pwd -P; echo e > evidence.txt', work) + check(rc == 0 and log.split() == [str(path)], f'-o below a {what} opens the new directory') + check(path.is_dir() and stat.S_IMODE(path.stat().st_mode) == 0o700 and (path / 'evidence.txt').exists(), + f'-o below a {what}: private, with the evidence inside') + + # A directory renamed and replaced after open_out(): the script keeps + # writing into the directory it holds, never through the replacement. + swap_victim = work / 'swap-victim' + swap_victim.mkdir() + target = private / 'swap' + rc, log = bash(lib, f'''open_out "{target}" "{base}" x || exit 9 + echo first > before.txt + mv -- "{target}" "{target}.moved" && ln -s "{swap_victim}" "{target}" + echo later > dmesg.txt; echo verdict > verdict.txt''', work) + check(rc == 0 and (Path(f'{target}.moved') / 'dmesg.txt').read_text() == 'later\n', + 'writes after a swap land in the held directory') + check(not any(swap_victim.iterdir()), 'nothing is written through the swapped-in symlink') + + # noclobber: an existing file is never truncated, kernel attributes use >|. + attr = work / 'attribute' + attr.write_text('enabled\n') + rc, log = bash(lib, f'''open_out "{private / 'clobber'}" "{base}" x || exit 9 + echo old > results.txt + if (echo new > results.txt) 2> /dev/null; then exit 8; fi + echo disabled >| "{attr}" + cat results.txt''', work) + check(rc == 0 and log.strip() == 'old', 'noclobber refuses to overwrite an existing evidence file') + check(attr.read_text() == 'disabled\n', '>| still writes a kernel attribute') + + +def static(): + """The scripts themselves.""" + for name in ALL: + text = (WAKE / name).read_text() + code = '\n'.join(line for line in text.splitlines() if not line.lstrip().startswith('#')) + check('/var/tmp/bt-wake/' not in code and not re.search(r'=/var/tmp/bt-wake\b', code), + f'{name}: no fixed /var/tmp/bt-wake path') + check(not re.search(r'(?|])>\s*"?(\$dev|/sys/)', code), + f'{name}: kernel attributes are written with >|') + check(not re.search(r'mkdir -p "\$out"', code) or name == 'bt-wake-emulated.sh', + f'{name}: the evidence directory is not taken over with mkdir -p') + # The emulated run's own tee writes the emulator's control file over ssh, + # not evidence on the target. + for name in SCRIPTS + ['attended-bt-wake.sh']: + code = (WAKE / name).read_text() + check(not re.search(r'\btee\s+(?!-a\b)', code), f'{name}: no truncating tee') + for name in SCRIPTS: + code = (WAKE / name).read_text() + check(re.search(r'^open_out "\$out" /var/tmp bt-wake-', code, re.M) is not None, + f'{name}: opens its evidence directory with open_out()') + rest = code[code.find(END):] if END in code else code + check('"$out/' not in rest, f'{name}: writes relative to the held directory, not through $out') + attended = (WAKE / 'attended-bt-wake.sh').read_text() + check('mktemp -d /var/tmp/bt-wake-attended.' in attended and 'set -C' in attended, + 'attended-bt-wake.sh: a fresh private directory with noclobber') + emulated = (WAKE / 'bt-wake-emulated.sh').read_text() + check('mktemp -d /var/tmp/bt-wake-run.' in emulated and 'rm -rf $d' not in emulated, + 'bt-wake-emulated.sh: the target copy and evidence go to a fresh directory') + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/avd-av1-tail-tests.py b/tools/asahi/avd-av1-tail-tests.py index 6f1d5a98b8f3fd..df866290b8422f 100644 --- a/tools/asahi/avd-av1-tail-tests.py +++ b/tools/asahi/avd-av1-tail-tests.py @@ -15,7 +15,8 @@ def function(source, name): - match = re.search(r'^(?:static )?(?:int|void|u64)\s+' + name + r'\(', source, re.M) + # The return type may sit on the line before the name. + match = re.search(r'^(?:static |VISIBLE_IF_KUNIT )?(?:int|void|u64|enum \w+|struct \w+ \*)\s+' + name + r'\(', source, re.M) if not match: raise ValueError(name) start = match.start() @@ -55,6 +56,10 @@ def structure(source, name): #define WARN_ON(x) (x) #define DIV_ROUND_UP(n,d) (((n)+(d)-1)/(d)) #define dev_err_ratelimited(...) ((void)0) +#define VISIBLE_IF_KUNIT +#define GFP_KERNEL 0 +struct device; +enum avd_image_fmt { AVD_IMG_FMT_ANY, AVD_IMG_FMT_420_8BIT, AVD_IMG_FMT_420_10BIT }; @ALIGNMENT@ @CDF_HEADER@ @CDF_DEFAULTS@ @@ -67,10 +72,22 @@ def structure(source, name): struct avd_buf {void *cpu; dma_addr_t addr;}; struct avd_run {struct {struct vb2_v4l2_buffer *src,*dst;} bufs; dma_addr_t y_out; int setup_err;}; @RUN_STRUCT@ +/* The preamble only uses the stream's copies of the controls. */ +struct avd_av1_stream { + struct {struct v4l2_ctrl_av1_sequence seq; struct v4l2_ctrl_av1_frame frame; struct v4l2_ctrl_av1_film_grain grain;} params; +}; @CTX_STRUCT@ -struct v4l2_ctrl {unsigned int elems; struct {void *p;} p_cur;}; +struct v4l2_ctrl {unsigned int elems, elem_size; struct {void *p;} p_cur;}; +static void v4l2_ctrl_lock(struct v4l2_ctrl *c){(void)c;} +static void v4l2_ctrl_unlock(struct v4l2_ctrl *c){(void)c;} +/* avd_av1_run() frees the run's copy; these tests only run the preamble. */ +static struct v4l2_ctrl_av1_tile_group_entry tile_copy[4]; +static void *kmemdup_array(const void *p,size_t n,size_t size,int f){(void)f;assert(n*size<=sizeof(tile_copy));memcpy(tile_copy,p,n*size);return tile_copy;} +/* The run-time format check has its own KUnit suite (avd-fmt-test.c). */ +static int avd_check_run_image_fmt(void *ctx,enum avd_image_fmt f){(void)ctx;(void)f;return 0;} +struct avd_dev {struct device *dev;}; struct v4l2_pix_format_mplane {unsigned int width,height; struct {unsigned int sizeimage;} plane_fmt[1];}; -struct avd_ctx {void *priv; int ctrl_hdl; struct {struct {struct {unsigned int width,height;} pix_mp;} fmt;} decoded_fmt;}; +struct avd_ctx {struct avd_dev *dev; void *priv; int ctrl_hdl; struct {struct {struct {unsigned int width,height;} pix_mp;} fmt;} decoded_fmt;}; static struct avd_decoded_buffer *reference; static struct v4l2_ctrl_av1_frame frame; static struct v4l2_ctrl_av1_sequence sequence={.bit_depth=8,.flags=V4L2_AV1_SEQUENCE_FLAG_SUBSAMPLING_X|V4L2_AV1_SEQUENCE_FLAG_SUBSAMPLING_Y}; @@ -83,7 +100,9 @@ def structure(source, name): static dma_addr_t vb2_dma_contig_plane_dma_addr(struct vb2_buffer *b,unsigned int p){assert(p==0);return b->dma;} static struct avd_decoded_buffer *vb2_to_avd_decoded_buf(struct vb2_buffer *b){return (void *)b;} static struct avd_decoded_buffer *avd_get_ref_buf(struct avd_ctx *ctx,struct vb2_v4l2_buffer *dst,uint64_t timestamp){(void)ctx;(void)dst;assert(timestamp==1000);lookup_calls++;return reference;} -static void avd_run_preamble(struct avd_ctx *ctx,struct avd_run *run){(void)ctx;(void)run;preamble_calls++;} +/* Like the real one, this hands the run its OUTPUT buffer. */ +static struct vb2_v4l2_buffer fixture_src; +static void avd_run_preamble(struct avd_ctx *ctx,struct avd_run *run){(void)ctx;if(!run->bufs.src)run->bufs.src=&fixture_src;preamble_calls++;} static struct v4l2_ctrl *v4l2_ctrl_find(int *h,unsigned int id){ (void)h; if(id==V4L2_CID_STATELESS_AV1_SEQUENCE)return &controls[0]; @@ -92,13 +111,17 @@ def structure(source, name): if(id==V4L2_CID_STATELESS_AV1_FILM_GRAIN)return &controls[3]; return NULL; } +static int avd_ctrl_copy(struct avd_ctx *ctx,unsigned int id,void *dst,size_t size){ + struct v4l2_ctrl *c=v4l2_ctrl_find(&ctx->ctrl_hdl,id);if(!c)return -EINVAL;memcpy(dst,c->p_cur.p,size);return 0;} ''' TESTS = r''' static size_t aligned_cdf(size_t length,size_t color){return (length&~255UL)-((color+255)&~255UL)-9216;} /* 3 bits per 4x4 block over 128x128 superblocks, 256-byte aligned. */ static size_t seg_bytes(size_t w,size_t h){return ALIGN(ALIGN(w,128)*ALIGN(h,128)/128*3,256);} -static void set_frame_ctx(struct avd_ctx *ctx){ctx->decoded_fmt.fmt.pix_mp.width=1920;ctx->decoded_fmt.fmt.pix_mp.height=1080;controls[0].p_cur.p=&sequence;controls[1].p_cur.p=&frame;controls[2].p_cur.p=&tile;controls[3].p_cur.p=&grain;} +static struct avd_dev fixture_dev; +static struct avd_av1_stream fixture_stream; +static void set_frame_ctx(struct avd_ctx *ctx){ctx->dev=&fixture_dev;((struct avd_av1_ctx *)ctx->priv)->stream=&fixture_stream;ctx->decoded_fmt.fmt.pix_mp.width=1920;ctx->decoded_fmt.fmt.pix_mp.height=1080;controls[0].p_cur.p=&sequence;controls[1].p_cur.p=&frame;controls[2].p_cur.p=&tile;controls[3].p_cur.p=&grain;} static void read_exact(const char *path,void *data,size_t n){FILE *f=fopen(path,"rb");assert(f);assert(fread(data,1,n,f)==n);assert(fgetc(f)==EOF);assert(fclose(f)==0);} static void inheritance(unsigned int residue,unsigned int mode,const char *neighbors,bool check_addresses){ const size_t ref_len=6964992+residue,dst_len=7000064+(residue?((residue+79)%256):0); @@ -112,7 +135,7 @@ def structure(source, name): avd_av1_default_coeff_probs(47,&expected);avd_av1_set_default_cdfs(&expected); if(neighbors){unsigned char observation[9728];read_exact(neighbors,observation,sizeof(observation));assert(residue==64);memcpy(src.base.vb.vb2_buf.memory+6817344,observation,sizeof(observation));memcpy(&expected,observation+192,sizeof(expected));} else {expected.intra_inter_cdf[0]^=37;expected.coeff_base_cdf[0][0][0][0]^=59;memcpy(src.base.vb.vb2_buf.memory+ref_offset,&expected,sizeof(expected));} - memset(&frame,0,sizeof(frame));frame.frame_width_minus_1=1919;frame.frame_height_minus_1=1079;frame.quantization.base_q_idx=47; + memset(&frame,0,sizeof(frame));frame.frame_width_minus_1=1919;frame.upscaled_width=1920;frame.frame_height_minus_1=1079;frame.quantization.base_q_idx=47; frame.frame_type=V4L2_AV1_INTER_FRAME;frame.primary_ref_frame=0;frame.ref_frame_idx[0]=0;frame.reference_frame_ts[0]=1000; if(mode){frame.frame_type=mode==1?V4L2_AV1_KEY_FRAME:mode==2?V4L2_AV1_INTRA_ONLY_FRAME:V4L2_AV1_INTER_FRAME;if(mode==3)frame.flags=V4L2_AV1_FRAME_FLAG_ERROR_RESILIENT_MODE;if(mode==4)frame.primary_ref_frame=7;memset(&expected,0,sizeof(expected));avd_av1_default_coeff_probs(47,&expected);avd_av1_set_default_cdfs(&expected);} controls[0].p_cur.p=&sequence;controls[1].p_cur.p=&frame;controls[2].p_cur.p=&tile;controls[3].p_cur.p=&grain; @@ -141,7 +164,7 @@ def structure(source, name): static int preamble(unsigned int w,unsigned int h,unsigned char primary,signed char idx){ struct avd_decoded_buffer dst={0};struct avd_av1_ctx av1={0};struct avd_ctx ctx={.priv=&av1};struct avd_av1_run run={0};set_frame_ctx(&ctx); dst.base.vb.vb2_buf.planes[0].length=7000064;memset(&frame,0,sizeof(frame)); - frame.frame_width_minus_1=w-1;frame.frame_height_minus_1=h-1;frame.primary_ref_frame=primary;if(primary<7)frame.ref_frame_idx[primary]=idx; + frame.frame_width_minus_1=w-1;frame.upscaled_width=w;frame.frame_height_minus_1=h-1;frame.primary_ref_frame=primary;if(primary<7)frame.ref_frame_idx[primary]=idx; run.base.bufs.dst=&dst.base.vb;run.base.y_out=0x120000000UL;return avd_av1_run_preamble(&ctx,&run); } static void guards(void){ @@ -165,7 +188,7 @@ def structure(source, name): memset(dst.base.vb.vb2_buf.memory,0xa5,len);memset(src.base.vb.vb2_buf.memory,0x3c,ref_len); for(size_t i=0;i', 'UNALIGNED_SEG_OFFSET(dst->'), 'seg-any-size': ('avd_av1_set_seg', 'DIV_ROUND_UP(ref->av1.width + 1, 8)', 'DIV_ROUND_UP(frame->frame_width_minus_1 + 1, 8)'), 'ref-index-upper': ('avd_av1_run_preamble', 'idx < 0 || idx >= V4L2_AV1_TOTAL_REFS_PER_FRAME', 'idx < 0'), - 'frame-width-unchecked': ('avd_av1_run_preamble', 'run->frame->frame_width_minus_1 + 1 > ctx->decoded_fmt.fmt.pix_mp.width ||', '0 ||'), + # The upscaled width bound also covers the frame width, so drop the frame size check as a whole. + 'frame-width-unchecked': ('avd_av1_check_frame_size', 'frame->frame_width_minus_1 >= width ||\n\t frame->frame_height_minus_1 >= height', '0'), } if args.mutation: target, old, new = mutations[args.mutation] diff --git a/tools/asahi/bcm4377-completion-tests.py b/tools/asahi/bcm4377-completion-tests.py new file mode 100755 index 00000000000000..e38a2b35d8b37a --- /dev/null +++ b/tools/asahi/bcm4377-completion-tests.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the driver's completion poll against an in-memory producer.""" +from pathlib import Path +import subprocess +import tempfile + +DRIVER = Path(__file__).resolve().parents[2] / "drivers/bluetooth/hci_bcm4377.c" + +FIXTURE = r""" +#include +#include +#include +typedef uint16_t u16; +typedef uint16_t __le16; + +struct ring_state { + __le16 completion_ring_head[1], completion_ring_tail[1]; +}; +struct bcm4377_data { + struct ring_state *ring_state; +}; +struct bcm4377_completion_ring { + u16 ring_id, n_entries; + bool enabled; +}; + +#define READ_ONCE(x) (x) +#define dma_rmb() ((void)0) +#define le16_to_cpu(x) (x) +#define cpu_to_le16(x) (x) +#define dev_dbg(...) ((void)0) +#define dev_warn_ratelimited(...) ((void)0) + +static u16 slots[4]; +static unsigned int handled; +static bool advance_head; + +static void bcm4377_handle_completion(struct bcm4377_data *data, + struct bcm4377_completion_ring *ring, u16 tail) +{ + assert(handled < ring->n_entries); + slots[handled++] = tail; + if (advance_head) + data->ring_state->completion_ring_head[ring->ring_id] = 2; +} +""" + +CASES = r""" +int main(void) +{ + struct ring_state state = {}; + struct bcm4377_data data = { .ring_state = &state }; + struct bcm4377_completion_ring ring = { + .n_entries = sizeof(slots) / sizeof(slots[0]), .enabled = true, + }; + u16 invalid[] = { ring.n_entries, UINT16_MAX }; + u16 last = ring.n_entries - 1; + + state.completion_ring_tail[0] = last; + for (unsigned int i = 0; i < sizeof(invalid) / sizeof(invalid[0]); i++) { + state.completion_ring_head[0] = invalid[i]; + bcm4377_poll_completion_ring(&data, &ring); + assert(handled == 0 && state.completion_ring_tail[0] == last); + } + + state.completion_ring_head[0] = last; + bcm4377_poll_completion_ring(&data, &ring); + assert(handled == 0 && state.completion_ring_tail[0] == last); + + /* Wrap around. A completion added mid-poll belongs to the next poll. */ + state.completion_ring_head[0] = 1; + advance_head = true; + bcm4377_poll_completion_ring(&data, &ring); + assert(handled == 2 && slots[0] == last && slots[1] == 0); + assert(state.completion_ring_tail[0] == 1); + bcm4377_poll_completion_ring(&data, &ring); + assert(handled == 3 && slots[2] == 1 && state.completion_ring_tail[0] == 2); +} +""" + + +def main(): + source = DRIVER.read_text() + start = source.index("static void bcm4377_poll_completion_ring(") + end = source.index("\n}", start) + 2 + with tempfile.TemporaryDirectory() as directory: + binary = Path(directory) / "completion-test" + subprocess.run(["cc", "-std=gnu11", "-Wall", "-Wextra", "-Werror", + "-x", "c", "-", "-o", binary], check=True, + input=FIXTURE + source[start:end] + "\n" + CASES, text=True) + subprocess.run([binary], check=True, timeout=5) + + +if __name__ == "__main__": + main() diff --git a/tools/asahi/bcm4377-resume-tests.py b/tools/asahi/bcm4377-resume-tests.py index f8dfa488d50790..e415dc0a76350e 100755 --- a/tools/asahi/bcm4377-resume-tests.py +++ b/tools/asahi/bcm4377-resume-tests.py @@ -12,7 +12,7 @@ def extract(s,n): while depth:depth+=(s[b]=='{')-(s[b]=='}');b+=1 return s[m.start():b]+'\n' s=(r/'drivers/bluetooth/hci_bcm4377.c').read_text();core=(r/'net/bluetooth/hci_sync.c').read_text();core_hci=(r/'net/bluetooth/hci_core.c').read_text() -names=['bcm4377_setup_retry_allowed','bcm4377_queue_setup_retry','bcm4377_setup_retry_work','bcm4377_resume_recovery_supported','bcm4377_resume_recovery_allowed','bcm4377_resume_recovery_invalidate','bcm4377_resume_recovery_sync','bcm4377_resume_recovery_destroy','bcm4377_resume_recovery_work','bcm4377_hci_timeout','bcm4377_resume_recovery_stop','bcm4377_hci_open','bcm4377_hci_close','bcm4377_hci_setup_once','bcm4377_hci_setup','bcm4377_hci_post_init','bcm4377_hci_unregister_dev','bcm4377_sleep_finish','bcm4377_suspend','bcm4377_resume'] +names=['bcm4377_setup_retry_allowed','bcm4377_queue_setup_retry','bcm4377_setup_retry_work','bcm4377_resume_recovery_supported','bcm4377_resume_recovery_allowed','bcm4377_resume_recovery_invalidate','bcm4377_resume_recovery_sync','bcm4377_resume_recovery_destroy','bcm4377_resume_recovery_work','bcm4377_hci_timeout','bcm4377_resume_recovery_stop','bcm4377_hci_open','bcm4377_hci_close','bcm4377_hci_setup_once','bcm4377_hci_setup','bcm4377_clamp_acl_mtu','bcm4377_hci_post_init','bcm4377_hci_unregister_dev','bcm4377_sleep_finish','bcm4377_suspend','bcm4377_resume'] bodies={n:extract(s,n) for n in names};shared=[] if a.old_ref: old=subprocess.check_output(['git','show',a.old_ref+':drivers/bluetooth/hci_bcm4377.c'],cwd=r,text=True) diff --git a/tools/asahi/bcm4377-resume/fixture.h b/tools/asahi/bcm4377-resume/fixture.h index 5eece3476e65fe..ddd125e8764b3b 100644 --- a/tools/asahi/bcm4377-resume/fixture.h +++ b/tools/asahi/bcm4377-resume/fixture.h @@ -23,6 +23,7 @@ #define HCI_SETUP 1 #define HCI_AUTO_OFF 2 #define HCI_UNREGISTER 4 +#define HCI_MAX_ACL_SIZE 1024 #define HCI_USER_CHANNEL 8 #define HCI_RUNNING 16 #define HCI_UP 32 @@ -45,7 +46,7 @@ static void bacpy(bdaddr_t *a,const bdaddr_t *b) { *a=*b; } static int bacmp(const bdaddr_t *a,const bdaddr_t *b) { return memcmp(a,b,6); } struct bcm4377_data; struct firmware { const unsigned char *data; int size; }; -struct hci_dev { struct bcm4377_data *data; unsigned int flags; void *req_workqueue,*workqueue; struct work_struct power_on,cmd_sync_work,cmd_work; struct delayed_work cmd_timer,ncmd_timer; int req_lock,cmd_cnt,suspend_state,wake_reason,wake_addr_type; bdaddr_t wake_addr; int *req_skb; void (*reset)(struct hci_dev*); bdaddr_t setup_addr,public_addr,bdaddr; }; +struct hci_dev { struct bcm4377_data *data; unsigned int flags; unsigned short acl_mtu,le_mtu; void *req_workqueue,*workqueue; struct work_struct power_on,cmd_sync_work,cmd_work; struct delayed_work cmd_timer,ncmd_timer; int req_lock,cmd_cnt,suspend_state,wake_reason,wake_addr_type; bdaddr_t wake_addr; int *req_skb; void (*reset)(struct hci_dev*); bdaddr_t setup_addr,public_addr,bdaddr; }; struct ring { bool enabled; }; struct pci_dev { int irq, dev; @@ -63,6 +64,8 @@ struct bcm4377_data { pthread_mutex_t resume_lock; uint64_t resume_epoch, resume_pending; bool resume_armed, resume_blocked, resume_powered; + /* T6041 S2R: zero, so a real sleep's power loss rebinds (not modelled: see below). */ + uint64_t dma_window_base; bool resume_guarded, resume_recovering; struct work_struct resume_work; struct ring acl_d2h_ring,acl_h2d_ring,sco_d2h_ring,sco_h2d_ring,hci_d2h_ring,hci_h2d_ring,sco_event_ring,sco_ack_ring,hci_acl_event_ring,hci_acl_ack_ring; @@ -88,6 +91,7 @@ static int send_ptb(struct bcm4377_data *b,const struct firmware *f) { assert(f= static const struct firmware *bcm4377_request_blob(struct bcm4377_data *b,const char *suffix) { assert(!strcmp(suffix,"ptb"));return missing_blob?NULL:&fw; } static void release_firmware(const struct firmware *f) { assert(f==&fw); } static int bcm4377_check_bdaddr(struct bcm4377_data *b) { return 0; } +static int bcm4377_init_cfg(struct bcm4377_data *b) { (void)b; return 0; } static int bcm4377_destroy_transfer_ring(struct bcm4377_data *b,struct ring *r) { r->enabled=false;return close_error; } static int bcm4377_destroy_completion_ring(struct bcm4377_data *b,struct ring *r) { r->enabled=false;return close_error; } static int bcm4377_hci_set_bdaddr(struct hci_dev *h,const bdaddr_t *a) { addr_count++;if(addr_error)return addr_error;h->bdaddr=*a;return 0; } @@ -107,6 +111,14 @@ static pthread_t producer_thread; static void hci_cmd_timeout(struct work_struct *work); static struct bcm4377_data *active; static bool hdev_is_powered(struct hci_dev *h) {return (h->flags&HCI_UP) && !(h->flags&HCI_AUTO_OFF);} +/* The controls model resumes after s2idle; a real sleep's rebind path is not taken. */ +static bool pm_resume_via_firmware(void) { return false; } +struct bcm4377_data; +static void bcm4377_queue_rebind(struct bcm4377_data *b, const char *why) +{ + (void)b; (void)why; + assert(0); +} static bool of_machine_is_compatible(const char *s) {assert(!strcmp(s,"apple,j493"));return board_j493;} static void *kmalloc(size_t n,int flags) {return allocation_error?NULL:malloc(n);} static void kfree(void *p) {free(p);} diff --git a/tools/asahi/brcmf-recovery-tests.py b/tools/asahi/brcmf-recovery-tests.py index 9ca30ac20b28dc..ae13fca63052c9 100755 --- a/tools/asahi/brcmf-recovery-tests.py +++ b/tools/asahi/brcmf-recovery-tests.py @@ -13,7 +13,7 @@ def function(source, name): - match = re.search(r'^(?:static\s+)?(?:void|int|bool|s32)\s+' + name + + match = re.search(r'^(?:static\s+)?(?:inline\s+)?(?:void|int|bool|s32)\s+' + name + r'\([^;]*?\)\s*\{', source, re.M) if not match: raise ValueError('Missing function ' + name) @@ -66,7 +66,7 @@ def define(source, name): u32 scan_idx; u8 scan_line[8]; u8 scan_len; }; struct brcmf_pcie_shared_info { u32 tcm_base_address; struct brcmf_pcie_console console; }; struct brcmf_pciedev_info { enum brcmf_pcie_state state; struct pci_dev *pdev; - struct brcmf_pcie_shared_info shared; bool fw_dead, reset_wanted; u32 recoveries; unsigned long recovery_window; }; + size_t tcm_size; struct brcmf_pcie_shared_info shared; bool fw_dead, reset_wanted; u32 recoveries; unsigned long recovery_window; }; struct pcie_priv { struct brcmf_pciedev_info *devinfo; }; struct brcmf_bus { enum brcmf_bus_state state; struct device *dev; struct { struct pcie_priv *pcie; } bus_priv; }; struct brcmf_proto { void *pd; }; @@ -116,6 +116,7 @@ def define(source, name): { memset(tcm, 0, sizeof(tcm)); link_down = false; memset(&devinfo, 0, sizeof(devinfo)); devinfo.pdev = &pdev; devinfo.state = BRCMFMAC_PCIE_STATE_UP; + devinfo.tcm_size = sizeof(tcm); devinfo.shared.tcm_base_address = SHARED; put32(SHARED + BRCMF_SHARED_FLAGS_OFFSET, 0x10007); devinfo.shared.console.base_addr = CONS; devinfo.shared.console.buf_addr = BUF; devinfo.shared.console.bufsize = BUFSZ; put32(CONS + BRCMF_CONSOLE_WRITEIDX_OFFSET, 0); @@ -145,6 +146,9 @@ def define(source, name): /* Trap flag in shared RAM: dead at the first stall. */ reset(); put32(SHARED, 0x10007 | BRCMF_PCIE_SHARED_TRAP); put32(SHARED + BRCMF_SHARED_TRAP_ADDR_OFFSET, 0x800); put32(0x800, 4); put32(0x804, 0x1234); stall(1); assert(died("trap in shared RAM")); cases++; + /* A trap record outside the TCM is not read; the firmware is still dead. */ + reset(); put32(SHARED, 0x10007 | BRCMF_PCIE_SHARED_TRAP); + put32(SHARED + BRCMF_SHARED_TRAP_ADDR_OFFSET, sizeof(tcm) - 4); stall(1); assert(died("trap in shared RAM")); cases++; /* Assert only counts when the firmware was built with asserts. */ reset(); put32(SHARED, 0x10007 | BRCMF_PCIE_SHARED_ASSERT); stall(1); assert(!crashes); cases++; reset(); put32(SHARED, 0x10007 | BRCMF_PCIE_SHARED_ASSERT | BRCMF_PCIE_SHARED_ASSERT_BUILT); @@ -209,6 +213,7 @@ def define(source, name): 'wanted-over-limit': ('pcie', '\tif (xchg(&devinfo->fw_dead, true))\n\t\treturn;\n', '\tif (xchg(&devinfo->fw_dead, true))\n\t\treturn;\n' '\tWRITE_ONCE(devinfo->reset_wanted, true);\n'), + 'trap-bound': ('pcie', '\t\tif (brcmf_pcie_tcm_range_valid(devinfo->tcm_size, addr, 8))', '\t\tif (true)'), 'stall-reset': ('msgbuf', '\tmsgbuf->ctl_stalls = 0;\n', ''), 'ring-full': ('msgbuf', '\t\tif (err == -ENOMEM)\n', '\t\tif (false)\n'), } @@ -220,12 +225,13 @@ def main(): parser.add_argument('--mutation', choices=sorted(MUTATIONS)) args = parser.parse_args() sources = {name: (DRIVER / (name + '.c')).read_text() for name in ('pcie', 'msgbuf')} + sources['pcie.h'] = (DRIVER / 'pcie.h').read_text() defines = ''.join(define(sources['pcie'], n) for n in ( 'BRCMF_PCIE_SHARED_ASSERT_BUILT', 'BRCMF_PCIE_SHARED_ASSERT', 'BRCMF_PCIE_SHARED_TRAP', 'BRCMF_SHARED_FLAGS_OFFSET', 'BRCMF_SHARED_TRAP_ADDR_OFFSET', 'BRCMF_CONSOLE_WRITEIDX_OFFSET', 'BRCMF_PCIE_CTL_STALL_MAX', 'BRCMF_PCIE_RECOVERY_MAX', 'BRCMF_PCIE_RECOVERY_WINDOW_S')) bodies = { - 'pcie': ''.join(function(sources['pcie'], n) for n in ( + 'pcie': function(sources['pcie.h'], 'brcmf_pcie_tcm_range_valid') + ''.join(function(sources['pcie'], n) for n in ( 'brcmf_pcie_fw_died', 'brcmf_pcie_console_trapped', 'brcmf_pcie_ctl_stall')), 'msgbuf': function(sources['msgbuf'], 'brcmf_msgbuf_query_dcmd_len'), } diff --git a/tools/asahi/brcmf-shared-tcm-tests.py b/tools/asahi/brcmf-shared-tcm-tests.py new file mode 100755 index 00000000000000..bc9242bb14fd1b --- /dev/null +++ b/tools/asahi/brcmf-shared-tcm-tests.py @@ -0,0 +1,325 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the production brcmfmac PCIe shared RAM, ring and console setup against a fake TCM. + +Every TCM access of the fake asserts that it lies inside the mapping, so a firmware-supplied +address the driver does not check makes a control fail. Each --mutation drops one check. +""" +import argparse +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +DRIVER = ROOT / 'drivers/net/wireless/broadcom/brcm80211/brcmfmac' + + +def function(source, name): + match = re.search(r'^(?:static\s+)?(?:inline\s+)?(?:void|int|bool|s32|u16)\s+' + name + + r'\([^;]*?\)\s*\{', source, re.M) + if not match: + raise ValueError('Missing function ' + name) + end = source.index('{', match.start()) + 1 + depth = 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[match.start():end] + '\n' + + +def struct(source, name): + match = re.search(r'^struct ' + name + r' \{.*?^\};\n', source, re.M | re.S) + if not match: + raise ValueError('Missing struct ' + name) + return match.group(0) + + +def define(source, name): + match = re.search(r'^#define\s+' + name + r'\s+(.*)$', source, re.M) + if not match: + raise ValueError('Missing define ' + name) + return '#define %s %s\n' % (name, match.group(1)) + + +PREFIX = r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +typedef uint64_t u64; typedef uint32_t u32; typedef uint16_t u16; typedef uint8_t u8; +typedef uint32_t __le32; typedef uint16_t __le16; typedef uint64_t dma_addr_t; +#define le32_to_cpu(x) (x) +#define le16_to_cpu(x) (x) +#define cpu_to_le32(x) (x) +#define GFP_KERNEL 0 +#define brcmf_dbg(...) ((void)0) +#define pr_debug(...) ((void)0) +#define BRCMF_FWCON_ON() 1 +#define kzalloc_objs(obj, n) calloc((n), sizeof(obj)) +static unsigned errs; +static char last_err[256]; +static void brcmf_err(void *bus, const char *fmt, ...) +{ va_list ap; (void)bus; va_start(ap, fmt); vsnprintf(last_err, sizeof(last_err), fmt, ap); va_end(ap); errs++; } +static void __brcmf_err(void *bus, const char *func, const char *fmt, ...) { (void)bus; (void)func; (void)fmt; } +/* DEFINES */ +/* STRUCTS */ +struct device { int unused; }; +struct pci_dev { struct device dev; }; +struct brcmf_bus { int unused; }; +static struct brcmf_bus bus; +static struct brcmf_bus *dev_get_drvdata(struct device *dev) { (void)dev; return &bus; } +struct brcmf_commonring { u16 r_ptr, w_ptr, depth; }; +enum brcmf_pcie_state { BRCMFMAC_PCIE_STATE_DOWN, BRCMFMAC_PCIE_STATE_UP }; +struct brcmf_pciedev_info; +struct brcmf_pcie_ringbuf { struct brcmf_commonring commonring; struct brcmf_pciedev_info *devinfo; + u32 w_idx_addr, r_idx_addr; u16 id; }; +struct brcmf_pcie_console { u32 base_addr, buf_addr, bufsize, read_idx, log_idx; + u8 log_str[256]; u32 scan_idx; u8 scan_len; }; +struct brcmf_pcie_shared_info { u32 tcm_base_address, flags; struct brcmf_pcie_ringbuf *commonrings[5]; + struct brcmf_pcie_ringbuf *flowrings; u16 max_rxbufpost, max_flowrings, max_submissionrings, + max_completionrings; u32 rx_dataoffset, htod_mb_data_addr, dtoh_mb_data_addr, ring_info_addr; + struct brcmf_pcie_console console; u8 version; bool mb_via_ctl; u32 flags2, flags3; }; +struct brcmf_pciedev_info { enum brcmf_pcie_state state; struct pci_dev *pdev; u8 *tcm; size_t tcm_size; struct brcmf_pcie_shared_info shared; + u8 dma_idx_sz; void *idxbuf; u32 idxbuf_sz; dma_addr_t idxbuf_dmahandle; + u16 (*read_ptr)(struct brcmf_pciedev_info *devinfo, u32 mem_offset); + void (*write_ptr)(struct brcmf_pciedev_info *devinfo, u32 mem_offset, u16 value); }; + +/* Fake TCM: every access must lie inside the mapping. */ +#define TCM_SIZE 0x8000 +static u8 tcm[TCM_SIZE]; +static unsigned long reads; +static void in_tcm(struct brcmf_pciedev_info *d, u32 a, u32 n) +{ assert(d->tcm_size == TCM_SIZE); assert((u64)a + n <= TCM_SIZE); assert(++reads < 1000000); } +static u32 brcmf_pcie_read_tcm32(struct brcmf_pciedev_info *d, u32 a) { u32 v; in_tcm(d, a, 4); memcpy(&v, tcm + a, 4); return v; } +static u16 brcmf_pcie_read_tcm16(struct brcmf_pciedev_info *d, u32 a) { u16 v; in_tcm(d, a, 2); memcpy(&v, tcm + a, 2); return v; } +static u8 brcmf_pcie_read_tcm8(struct brcmf_pciedev_info *d, u32 a) { in_tcm(d, a, 1); return tcm[a]; } +static void brcmf_pcie_write_tcm32(struct brcmf_pciedev_info *d, u32 a, u32 v) { in_tcm(d, a, 4); memcpy(tcm + a, &v, 4); } +static void brcmf_pcie_write_tcm16(struct brcmf_pciedev_info *d, u32 a, u16 v) { in_tcm(d, a, 2); memcpy(tcm + a, &v, 2); } +static struct brcmf_pciedev_info devinfo; +static void memcpy_fromio(void *dst, const u8 *src, size_t n) +{ assert(src >= tcm); in_tcm(&devinfo, (u32)(src - tcm), (u32)n); memcpy(dst, src, n); } +static void memcpy_toio(u8 *dst, const void *src, size_t n) +{ assert(dst >= tcm); in_tcm(&devinfo, (u32)(dst - tcm), (u32)n); memcpy(dst, src, n); } +static void *dma_alloc_coherent(struct device *dev, size_t n, dma_addr_t *h, int gfp) +{ (void)dev; (void)gfp; *h = 0x10000000; return calloc(1, n); } +/* The real one reads the ring's size and writes its host address in its BRCMF_RING_MEM_SZ slot. */ +static struct brcmf_pcie_ringbuf rings_pool[5]; +static struct brcmf_pcie_ringbuf *brcmf_pcie_alloc_dma_and_ring(struct brcmf_pciedev_info *d, u32 id, u32 mem) +{ brcmf_pcie_read_tcm16(d, mem + BRCMF_RING_MAX_ITEM_OFFSET); brcmf_pcie_write_tcm32(d, mem + BRCMF_RING_MEM_BASE_ADDR_OFFSET + 4, 0); + return &rings_pool[id]; } +static void brcmf_pcie_release_ringbuffers(struct brcmf_pciedev_info *d) { (void)d; } +static void brcmf_pcie_ring_mb_ring_bell(void) {} +static void brcmf_pcie_ring_mb_write_rptr(void) {} +static void brcmf_pcie_ring_mb_write_wptr(void) {} +static int brcmf_pcie_ring_mb_update_rptr(void *ctx); +static int brcmf_pcie_ring_mb_update_wptr(void *ctx); +static void brcmf_commonring_register_cb(struct brcmf_commonring *c, void (*a)(void), int (*b)(void *), + int (*e)(void *), void (*f)(void), void (*g)(void), void *r) { (void)c; (void)a; (void)b; (void)e; (void)f; (void)g; (void)r; } +''' + +MAIN = r''' +#define SHARED 0x100 +#define CONS 0x200 +#define BUF 0x400 +#define RINGINFO 0x600 +#define RINGMEM 0x700 +#define IDX 0x800 +static struct pci_dev pdev; +static void put32(u32 a, u32 v) { memcpy(tcm + a, &v, 4); } +static void put16(u32 a, u16 v) { memcpy(tcm + a, &v, 2); } +/* A version 6 firmware with TCM ring indices, a console and two flowrings. */ +static void reset(void) +{ + free(devinfo.shared.flowrings); free(devinfo.idxbuf); + memset(tcm, 0, sizeof(tcm)); memset(&devinfo, 0, sizeof(devinfo)); memset(rings_pool, 0, sizeof(rings_pool)); + devinfo.pdev = &pdev; devinfo.tcm = tcm; devinfo.tcm_size = TCM_SIZE; errs = 0; reads = 0; + put32(SHARED + BRCMF_SHARED_FLAGS_OFFSET, 6); + put32(SHARED + BRCMF_SHARED_CONSOLE_ADDR_OFFSET, CONS); + put32(SHARED + BRCMF_SHARED_HTOD_MB_DATA_ADDR_OFFSET, 0xa00); + put32(SHARED + BRCMF_SHARED_DTOH_MB_DATA_ADDR_OFFSET, 0xa04); + put32(SHARED + BRCMF_SHARED_RING_INFO_ADDR_OFFSET, RINGINFO); + put32(CONS + BRCMF_CONSOLE_BUFADDR_OFFSET, BUF); put32(CONS + BRCMF_CONSOLE_BUFSIZE_OFFSET, 64); + put32(CONS + BRCMF_CONSOLE_WRITEIDX_OFFSET, 3); memcpy(tcm + BUF, "ok\n", 3); + struct brcmf_pcie_dhi_ringinfo *ri = (void *)(tcm + RINGINFO); + ri->ringmem = RINGMEM; ri->h2d_w_idx_ptr = IDX; ri->h2d_r_idx_ptr = IDX + 0x40; + ri->d2h_w_idx_ptr = IDX + 0x80; ri->d2h_r_idx_ptr = IDX + 0xc0; + ri->max_flowrings = 2; ri->max_submissionrings = 4; ri->max_completionrings = 3; +} +static int init(void) { return brcmf_pcie_init_share_ram_info(&devinfo, SHARED); } +static struct brcmf_pcie_dhi_ringinfo *ringinfo(void) { return (void *)(tcm + RINGINFO); } +/* Set up the rings, then touch every ring index as the data path does. */ +static int rings(void) +{ + int ret = brcmf_pcie_init_ringbuffers(&devinfo); + if (ret) + return ret; + for (int i = 0; i < 5; i++) { + devinfo.read_ptr(&devinfo, devinfo.shared.commonrings[i]->w_idx_addr); + devinfo.read_ptr(&devinfo, devinfo.shared.commonrings[i]->r_idx_addr); + } + for (int i = 0; i < devinfo.shared.max_flowrings; i++) { + devinfo.read_ptr(&devinfo, devinfo.shared.flowrings[i].w_idx_addr); + devinfo.read_ptr(&devinfo, devinfo.shared.flowrings[i].r_idx_addr); + } + return 0; +} +int main(void) +{ + unsigned cases = 0; + /* A well-formed firmware sets up and its console is read. */ + reset(); assert(!init() && devinfo.shared.console.bufsize == 64 && devinfo.shared.console.read_idx == 3); + assert(!rings() && !errs); cases++; + /* Shared RAM whose fields run past the TCM fails setup. */ + reset(); put32(TCM_SIZE - 8 + BRCMF_SHARED_FLAGS_OFFSET, 6); + assert(brcmf_pcie_init_share_ram_info(&devinfo, TCM_SIZE - 8) == -EINVAL); cases++; + /* Mailbox and ring info addresses outside the TCM fail setup. */ + reset(); put32(SHARED + BRCMF_SHARED_HTOD_MB_DATA_ADDR_OFFSET, TCM_SIZE - 2); assert(init() == -EINVAL); cases++; + reset(); put32(SHARED + BRCMF_SHARED_DTOH_MB_DATA_ADDR_OFFSET, 0xfffffffe); assert(init() == -EINVAL); cases++; + reset(); put32(SHARED + BRCMF_SHARED_RING_INFO_ADDR_OFFSET, TCM_SIZE - 8); assert(init() == -EINVAL); cases++; + /* So does ring memory or a ring index array outside the TCM. */ + reset(); assert(!init()); ringinfo()->ringmem = TCM_SIZE - 0x20; assert(rings() == -EINVAL); cases++; + reset(); assert(!init()); ringinfo()->h2d_w_idx_ptr = TCM_SIZE - 8; assert(rings() == -EINVAL); cases++; + reset(); assert(!init()); ringinfo()->h2d_r_idx_ptr = 0xfffffffc; assert(rings() == -EINVAL); cases++; + reset(); assert(!init()); ringinfo()->d2h_w_idx_ptr = TCM_SIZE - 4; assert(rings() == -EINVAL); cases++; + reset(); assert(!init()); ringinfo()->d2h_r_idx_ptr = TCM_SIZE; assert(rings() == -EINVAL); cases++; + /* The flowring indices count against the TCM too. */ + reset(); assert(!init()); ringinfo()->h2d_w_idx_ptr = TCM_SIZE - 4 * 4; ringinfo()->max_flowrings = 3; + assert(rings() == -EINVAL); cases++; + /* Host memory ring indices: one per ring the driver uses, in a buffer sized from the ring counts. */ + reset(); put32(SHARED + BRCMF_SHARED_FLAGS_OFFSET, 6 | BRCMF_PCIE_SHARED_DMA_INDEX | BRCMF_PCIE_SHARED_DMA_2B_IDX); + assert(!init() && devinfo.dma_idx_sz == 2 && !rings() && !errs); cases++; + /* Fewer submission or completion rings than the driver uses fail setup. */ + reset(); put32(SHARED + BRCMF_SHARED_FLAGS_OFFSET, 6 | BRCMF_PCIE_SHARED_DMA_INDEX); + assert(!init()); ringinfo()->max_submissionrings = 2; assert(rings() == -EINVAL); cases++; + reset(); put32(SHARED + BRCMF_SHARED_FLAGS_OFFSET, 6 | BRCMF_PCIE_SHARED_DMA_INDEX); + assert(!init()); ringinfo()->max_completionrings = 0; assert(rings() == -EINVAL); cases++; + /* Ring pointers from the dongle are taken only inside the ring; the last good one stays. */ + reset(); devinfo.state = BRCMFMAC_PCIE_STATE_UP; assert(!init() && !rings()); + struct brcmf_pcie_ringbuf *rb = devinfo.shared.commonrings[2]; rb->devinfo = &devinfo; rb->commonring.depth = 64; + put16(rb->r_idx_addr, 63); put16(rb->w_idx_addr, 10); + assert(!brcmf_pcie_ring_mb_update_rptr(rb) && !brcmf_pcie_ring_mb_update_wptr(rb)); + assert(rb->commonring.r_ptr == 63 && rb->commonring.w_ptr == 10); + put16(rb->r_idx_addr, 64); put16(rb->w_idx_addr, 0xffff); + assert(brcmf_pcie_ring_mb_update_rptr(rb) == -EIO && brcmf_pcie_ring_mb_update_wptr(rb) == -EIO); + assert(rb->commonring.r_ptr == 63 && rb->commonring.w_ptr == 10); cases++; + /* A console descriptor or buffer outside the TCM leaves the console off; setup goes on. */ + reset(); put32(SHARED + BRCMF_SHARED_CONSOLE_ADDR_OFFSET, TCM_SIZE - 4); + assert(!init() && !devinfo.shared.console.base_addr); cases++; + reset(); put32(CONS + BRCMF_CONSOLE_BUFADDR_OFFSET, TCM_SIZE - 16); + assert(!init() && !devinfo.shared.console.base_addr && !devinfo.shared.console.bufsize); cases++; + reset(); put32(CONS + BRCMF_CONSOLE_BUFSIZE_OFFSET, 0xffffffff); + assert(!init() && !devinfo.shared.console.base_addr); cases++; + /* No console reported: nothing is read at address 0, and a partial line is dropped. */ + reset(); assert(!init()); devinfo.shared.console.log_idx = 5; put32(SHARED + BRCMF_SHARED_CONSOLE_ADDR_OFFSET, 0); + reads = 0; brcmf_pcie_bus_console_init(&devinfo); + assert(reads == 1 && !devinfo.shared.console.base_addr && !devinfo.shared.console.log_idx); cases++; + /* A write index at or past the buffer size is not followed. */ + reset(); put32(CONS + BRCMF_CONSOLE_WRITEIDX_OFFSET, 64); assert(!init() && devinfo.shared.console.read_idx == 0); cases++; + reset(); put32(CONS + BRCMF_CONSOLE_WRITEIDX_OFFSET, 0x10000); assert(!init()); cases++; + /* A new firmware with a smaller console starts reading it from the beginning. */ + reset(); assert(!init()); devinfo.shared.console.read_idx = 60; put32(CONS + BRCMF_CONSOLE_BUFSIZE_OFFSET, 16); + put32(CONS + BRCMF_CONSOLE_WRITEIDX_OFFSET, 3); assert(!init() && devinfo.shared.console.read_idx == 3); cases++; + reset(); + printf("%u shared RAM bounds controls passed\n", cases); + return 0; +} +''' + +MUTATIONS = { + 'shared': ('\tif (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, sharedram_addr,\n' + '\t\t\t\t\tBRCMF_SHARED_SIZE)) {', '\tif (false) {'), + 'htod-mb': ('\tif (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\tshared->htod_mb_data_addr, 4) ||', + '\tif (false ||'), + 'dtoh-mb': ('\t !brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\tshared->dtoh_mb_data_addr, 4) ||', + '\t false ||'), + 'ring-info': ('\t !brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\tshared->ring_info_addr,\n' + '\t\t\t\t\tsizeof(struct brcmf_pcie_dhi_ringinfo))) {', '\t false) {'), + 'ring-mem': ('\tif (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\tle32_to_cpu(ringinfo.ringmem),', + '\tif (0 && !brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\tle32_to_cpu(ringinfo.ringmem),'), + 'ring-idx': ('\t\tif (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\t\th2d_w_idx_ptr, h2d_idx_len) ||', + '\t\tif (0 && !brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\t\th2d_w_idx_ptr, h2d_idx_len) ||'), + 'flowring-idx': ('\t\th2d_idx_len = (BRCMF_NROF_H2D_COMMON_MSGRINGS + max_flowrings) *', + '\t\th2d_idx_len = (BRCMF_NROF_H2D_COMMON_MSGRINGS) *'), + 'dma-counts': ('\t\tif (max_submissionrings <\n\t\t BRCMF_NROF_H2D_COMMON_MSGRINGS + max_flowrings ||\n' + '\t\t max_completionrings < BRCMF_NROF_D2H_COMMON_MSGRINGS) {', '\t\tif (false) {'), + 'rptr-depth': ('\tptr = devinfo->read_ptr(devinfo, ring->r_idx_addr);\n\tif (ptr >= commonring->depth) {', + '\tptr = devinfo->read_ptr(devinfo, ring->r_idx_addr);\n\tif (false) {'), + 'wptr-depth': ('\tptr = devinfo->read_ptr(devinfo, ring->w_idx_addr);\n\tif (ptr >= commonring->depth) {', + '\tptr = devinfo->read_ptr(devinfo, ring->w_idx_addr);\n\tif (false) {'), + 'console-desc': ('\t !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->base_addr,\n' + '\t\t\t\t\tBRCMF_CONSOLE_WRITEIDX_OFFSET + 4)) {', '\t false) {'), + 'console-none': ('\tif (!console->base_addr ||\n', '\tif (false ||\n'), + 'console-buf': ('\t !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->buf_addr,\n' + '\t\t\t\t\tconsole->bufsize)) {', '\t false) {'), + 'console-widx': ('\tif (newidx >= console->bufsize || console->read_idx >= console->bufsize)\n\t\treturn;\n', ''), + 'console-reinit': ('\tconsole->bufsize = 0;\n\tconsole->read_idx = 0;\n', '\tconsole->bufsize = 0;\n'), +} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--out', type=Path) + parser.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = parser.parse_args() + pcie = (DRIVER / 'pcie.c').read_text() + defines = ''.join(define(pcie, n) for n in ( + 'BRCMF_PCIE_SHARED_VERSION_7', 'BRCMF_PCIE_MIN_SHARED_VERSION', 'BRCMF_PCIE_MAX_SHARED_VERSION', 'BRCMF_PCIE_SHARED_VERSION_MASK', + 'BRCMF_PCIE_SHARED_DMA_INDEX', 'BRCMF_PCIE_SHARED_DMA_2B_IDX', 'BRCMF_PCIE_SHARED_USE_MAILBOX', + 'BRCMF_PCIE_SHARED_HOSTRDY_DB1', 'BRCMF_PCIE_SHARED_DAR', 'BRCMF_HOSTCAP_H2D_ENABLE_HOSTRDY', + 'BRCMF_HOSTCAP_H2D_DAR', 'BRCMF_HOSTCAP_DS_NO_OOB_DW', 'BRCMF_DEF_MAX_RXBUFPOST', + 'BRCMF_SHARED_FLAGS_OFFSET', 'BRCMF_SHARED_MAX_RXBUFPOST_OFFSET', 'BRCMF_SHARED_RX_DATAOFFSET_OFFSET', + 'BRCMF_SHARED_CONSOLE_ADDR_OFFSET', 'BRCMF_SHARED_HTOD_MB_DATA_ADDR_OFFSET', + 'BRCMF_SHARED_DTOH_MB_DATA_ADDR_OFFSET', 'BRCMF_SHARED_RING_INFO_ADDR_OFFSET', + 'BRCMF_SHARED_FLAGS2_OFFSET', 'BRCMF_SHARED_HOST_CAP_OFFSET', 'BRCMF_SHARED_FLAGS3_OFFSET', + 'BRCMF_SHARED_HOST_CAP2_OFFSET', 'BRCMF_SHARED_SIZE', 'BRCMF_CONSOLE_BUFADDR_OFFSET', + 'BRCMF_CONSOLE_BUFSIZE_OFFSET', 'BRCMF_CONSOLE_WRITEIDX_OFFSET', 'BRCMF_RING_MEM_SZ', + 'BRCMF_RING_MAX_ITEM_OFFSET', 'BRCMF_RING_MEM_BASE_ADDR_OFFSET')) + bus_h = (DRIVER / 'bus.h').read_text() + defines += ''.join(define(bus_h, n) for n in ( + 'BRCMF_H2D_MSGRING_FLOWRING_IDSTART', 'BRCMF_NROF_H2D_COMMON_MSGRINGS', 'BRCMF_NROF_D2H_COMMON_MSGRINGS')) + defines += '#define BRCMF_NROF_COMMON_MSGRINGS (BRCMF_NROF_H2D_COMMON_MSGRINGS + BRCMF_NROF_D2H_COMMON_MSGRINGS)\n' + structs = struct((DRIVER / 'msgbuf.h').read_text(), 'msgbuf_buf_addr') + struct(pcie, 'brcmf_pcie_dhi_ringinfo') + body = function((DRIVER / 'pcie.h').read_text(), 'brcmf_pcie_tcm_range_valid') + ''.join( + function(pcie, n) for n in ('brcmf_pcie_read_idx', 'brcmf_pcie_write_idx', + 'brcmf_pcie_ring_mb_update_rptr', 'brcmf_pcie_ring_mb_update_wptr', + 'brcmf_pcie_bus_console_init', 'brcmf_pcie_bus_console_read', + 'brcmf_pcie_init_ringbuffers', 'brcmf_pcie_init_share_ram_info')) + if args.mutation: + old, new = MUTATIONS[args.mutation] + if old not in body: + raise ValueError('mutation site missing: ' + args.mutation) + body = body.replace(old, new) + code = PREFIX.replace('/* DEFINES */', defines).replace('/* STRUCTS */', structs) + body + MAIN + + def run(out): + out.mkdir(parents=True, exist_ok=True) + source = out / 'controls.c' + source.write_text(code) + exe = out / 'controls' + subprocess.run(['clang', '-std=gnu11', '-O1', '-g', '-fsanitize=address,undefined', + '-fno-sanitize-recover=all', '-Wno-incompatible-function-pointer-types', + str(source), '-o', str(exe)], check=True) + env = dict(os.environ, ASAN_OPTIONS='abort_on_error=1') + result = subprocess.run([str(exe)], capture_output=True, text=True, timeout=60, env=env) + receipt = {'exit': result.returncode, 'stdout': result.stdout, 'stderr': result.stderr, + 'limits': 'Fake TCM and dongle tables; no firmware, PCIe link or DMA proof.'} + (out / 'results.json').write_text(json.dumps(receipt, indent=2) + '\n') + print(json.dumps(receipt)) + return result.returncode + + if args.out: + raise SystemExit(run(args.out)) + with tempfile.TemporaryDirectory(prefix='brcmf-shared-tcm-') as temp: + raise SystemExit(run(Path(temp))) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/brcmf-suspend-tests.py b/tools/asahi/brcmf-suspend-tests.py index e255d1ca0336b0..bccf1a63d40dd4 100644 --- a/tools/asahi/brcmf-suspend-tests.py +++ b/tools/asahi/brcmf-suspend-tests.py @@ -43,7 +43,7 @@ def function(source, name): #define smp_load_acquire(p) (*(p)) #define brcmf_dbg(...) ((void)0) #define bphy_err(...) ((void)drvr) -#define bphy_info_once(...) ((void)drvr) +#define bphy_info_once(d, ...) ((void)(d)) #define brcmf_info(...) ((void)0) #define brcmf_err(...) ((void)0) #define __brcmf_err(...) ((void)0) @@ -72,6 +72,7 @@ def function(source, name): struct { int intmask, mailboxmask; } *reginfo; }; struct pcie_priv { struct brcmf_pciedev_info *devinfo; }; struct brcmf_bus { enum brcmf_bus_state state; struct brcmf_pub *drvr; bool wowl_transport, wowl_wake; + bool wowl_s2idle_only; struct { struct pcie_priv *pcie; } bus_priv; }; struct brcmf_proto { void *pd; }; struct brcmf_pub { struct brcmf_bus *bus_if; struct brcmf_if *iflist[BRCMF_MAX_IFS]; @@ -209,7 +210,8 @@ def function(source, name): static struct net_device *cfg_to_ndev(struct brcmf_cfg80211_info *c) {return c->pub->iflist[0]->ndev;} static struct brcmf_if *netdev_priv(struct net_device *n) {return &ifp[n-ndev];} static bool check_vif_up(struct brcmf_cfg80211_vif *v) {(void)v;return vif_up;} -static bool brcmf_feat_is_enabled(struct brcmf_if *i,int f) {(void)i;(void)f;return false;} +static unsigned feats; +static bool brcmf_feat_is_enabled(struct brcmf_if *i,int f) {(void)i;return feats&BIT(f);} static void brcmf_report_wowl_wakeind(struct wiphy *w,struct brcmf_if *i) {(void)w;(void)i;can_command();} static void brcmf_fil_iovar_int_set(struct brcmf_if *i,const char *s,int n) {(void)i;(void)s;(void)n;can_command();} static void brcmf_config_wowl_pattern(struct brcmf_if *i,const char *s,void *p,int n,void *q,int t) {(void)i;(void)s;(void)p;(void)n;(void)q;(void)t;can_command();} @@ -219,11 +221,13 @@ def function(source, name): static void brcmf_fweh_unregister(struct brcmf_pub *p,int e) {(void)p;(void)e;} #define brcmf_fweh_register(p,e,f) ((void)(p),(void)(e)) static void brcmf_abort_scanning(struct brcmf_cfg80211_info *c) {(void)c;can_command();} -static void brcmf_bus_wowl_config(struct brcmf_bus *b,bool e) {(void)b;(void)e;} -static void brcmf_link_down(struct brcmf_cfg80211_vif *v,int r,bool b) {(void)v;(void)r;(void)b;can_command();} +static unsigned wowl_offs; +static void brcmf_bus_wowl_config(struct brcmf_bus *b,bool e) {(void)b;if(!e)wowl_offs++;} +static bool brcmf_link_down(struct brcmf_cfg80211_vif *v,int r,bool b) {(void)v;(void)r;(void)b;can_command();return true;} static void brcmf_delay(int t) {(void)t;} static void brcmf_set_mpc(struct brcmf_if *i,int v) {(void)i;(void)v;can_command();} -static int brcmf_configure_wowl(struct brcmf_cfg80211_info *c,struct brcmf_if *i,struct cfg80211_wowlan *w) {(void)c;(void)i;(void)w;can_command();return 0;} +static unsigned wowl_configs; +static int brcmf_configure_wowl(struct brcmf_cfg80211_info *c,struct brcmf_if *i,struct cfg80211_wowlan *w) {(void)c;(void)i;(void)w;can_command();wowl_configs++;return 0;} static void brcmf_keepalive_start(struct brcmf_if *i,int n) {(void)i;(void)n;can_command();} ''' @@ -240,7 +244,7 @@ def function(source, name): devinfo.state=BRCMFMAC_PCIE_STATE_UP;devinfo.intr=devinfo.ready=devinfo.timer=true; country_gets=sets=bands=txflows=creates=cancels=removes=probes=0; failure=translation=d0_error=probe_error=wake_error=save_error=0;ack=true;retain=1;d3_informs=d0_informs=0; - pm_suspend_target_state=PM_SUSPEND_TO_IDLE; + pm_suspend_target_state=PM_SUSPEND_TO_IDLE;feats=0; } static void hint(const char *a) { struct regulatory_request r={.alpha2={a[0],a[1]}};brcmf_cfg80211_reg_notifier(&wiphy,&r); @@ -351,6 +355,23 @@ def function(source, name): assert(msgbuf.flowring_work.queued && msgbuf.txflow_work.queued); assert(!d0_informs && !removes && !probes);cases++; } + /* WoWLAN over an in-band MSI only wakes from s2idle: a deeper target + * refuses WoWLAN like the other refusals (scan state cleared, return 1, + * nothing configured) so cfg80211 leaves every interface and suspends + * again without it; s2idle, and a bus with a real wake line, keep it. */ + for(int only=0;only<2;only++)for(int deep=0;deep<2;deep++) { + static struct cfg80211_wowlan magic={.magic_pkt=true}; + reset();vif_up=true;wowl_offs=wowl_configs=0;bus.wowl_s2idle_only=only;feats=BIT(BRCMF_FEAT_WOWL); + cfg.scan_status=BIT(BRCMF_SCAN_STATUS_BUSY); + pm_suspend_target_state=deep?PM_SUSPEND_ON:PM_SUSPEND_TO_IDLE; + int ret=brcmf_cfg80211_suspend(&wiphy,&magic); + assert(!cfg.scan_status); + if(only&&deep) { + assert(ret==1 && !cfg.suspended && !wowl_offs && !wowl_configs); + assert(!brcmf_cfg80211_suspend(&wiphy,NULL) && cfg.suspended && wowl_offs==1 && !wowl_configs); + } else assert(!ret && cfg.suspended && !wowl_offs && wowl_configs==1); + cases++; + } /* Outside s2idle (hibernation) Apple firmware still gets the D3 handshake. */ reset();devinfo.fwseed=true;pm_suspend_target_state=PM_SUSPEND_ON; assert(!brcmf_pcie_pm_enter_D3(&device) && d3_informs==1 && !devinfo.s2idle_d0); @@ -373,7 +394,7 @@ def main(): parser.add_argument('--out', type=Path) parser.add_argument('--mutation', choices=['country-gate', 'queue-reasons', 'worker-gate', 'resume-order', 'tx-drain', 'lpas-resume', - 's2idle-d3']) + 's2idle-d3', 'wowl-s2idle-only']) args = parser.parse_args() sources = {name: (DRIVER / (name + '.c')).read_text() for name in ('cfg80211', 'core', 'pcie', 'msgbuf')} @@ -407,6 +428,9 @@ def main(): elif args.mutation == 's2idle-d3': body = body.replace('if (devinfo->fwseed && pm_suspend_target_state == PM_SUSPEND_TO_IDLE)', 'if (false)') + elif args.mutation == 'wowl-s2idle-only': + body = body.replace('if (wowl && cfg->pub->bus_if->wowl_s2idle_only &&\n\t pm_suspend_target_state != PM_SUSPEND_TO_IDLE)', + 'if (false)') elif args.mutation == 'tx-drain': body = body.replace('netif_tx_disable(ifp->ndev);', '(void)ifp;') code = PREFIX.replace('/* STOP_REASONS */', reasons) + CALLBACK_STUBS + body + MAIN diff --git a/tools/asahi/centauri-bt-arena-tests.py b/tools/asahi/centauri-bt-arena-tests.py index c8272d0a9d239c..a8715ca8a8032a 100755 --- a/tools/asahi/centauri-bt-arena-tests.py +++ b/tools/asahi/centauri-bt-arena-tests.py @@ -49,7 +49,7 @@ def function(source, name): #define READ_ONCE(x) (x) #define WRITE_ONCE(x, v) ((x) = (v)) struct device { int dummy; }; -struct pci_dev { struct device dev; void *data; }; +struct pci_dev { struct device dev; void *data; bool state_saved; }; struct hci_dev { int dummy; }; struct cen_bt { struct pci_dev *pdev; @@ -67,7 +67,7 @@ def function(source, name): static int config_error, pending, command, saves, save_error, requests, recovery_error; static int unregisters, closes, hci_frees, arena_frees, irq_frees; static int owner_unregisters, handoffs, fallbacks, transport_sleeps, transport_wakes; -static int transport_sleep_error; +static int transport_sleep_error, transport_wake_error; static unsigned int bar_exec, bar_ipc; static void *handed_arena; static uintptr_t handed_dma; @@ -93,7 +93,7 @@ def function(source, name): return transport_sleep_error; } transport_wakes++; - return 0; + return transport_wake_error; } static void apple_centauri_sleep_mark_fallback(struct pci_dev *p) { assert(p == active->pdev); @@ -102,6 +102,7 @@ def function(source, name): static void *hci_get_drvdata(struct hci_dev *p) { assert(p); return active; } static void hci_unregister_dev(struct hci_dev *p) { assert(p && active->arena && active->quiescing); + assert(!active->transport_sleep_sent && !active->transport_paused); /* The arena must remain available through HCI's close barrier. */ unregisters++; } @@ -159,7 +160,7 @@ def function(source, name): handoffs++; } } -static int pci_save_state(struct pci_dev *p) { (void)p; saves++; return save_error; } +static int pci_save_state(struct pci_dev *p) { saves++; if (!save_error) p->state_saved = true; return save_error; } #define dev_warn(...) ((void)0) ''' @@ -169,6 +170,7 @@ def function(source, name): static struct cen_bt bt; static void reset(void) { memset(&bt, 0, sizeof(bt)); + dev.state_saved = false; active = &bt; bt.pdev = &dev; dev.data = &bt; bt.hdev = &hdev; bt.hci_registered = true; @@ -180,7 +182,7 @@ def function(source, name): config_error = saves = save_error = requests = recovery_error = 0; unregisters = closes = hci_frees = arena_frees = irq_frees = 0; owner_unregisters = handoffs = fallbacks = transport_sleeps = transport_wakes = 0; - transport_sleep_error = 0; + transport_sleep_error = transport_wake_error = 0; bar_exec = bar_ipc = 2; handed_arena = NULL; handed_dma = 0; sleep_reboot = true; @@ -258,7 +260,19 @@ def function(source, name): assert(cen_suspend(&dev.dev) == 0); assert(bt.transport_sleep_sent && !bt.asleep && bt.hdev == &hdev); assert(bt.arena && arena_frees == 0 && transport_sleeps == 1 && fallbacks == 0); - assert(saves == 1 && requests == 0); + assert(saves == 1 && requests == 0 && dev.state_saved && (command & PCI_COMMAND_MASTER)); + /* Control fallback quiesce after Beta keep-alive wakes Beta ACIPC first. */ + assert(cen_quiesce(&bt) == 0); + assert(!bt.transport_sleep_sent && !bt.transport_paused && bt.asleep && !bt.hdev); + assert(transport_wakes == 1 && unregisters == 1 && hci_frees == 1); + /* Fallback quiesce with failed Beta ACIPC wake clears running before unregister. */ + reset(); bt.bar = (void *)0x3000; + assert(cen_suspend(&dev.dev) == 0); + assert(bt.transport_sleep_sent && bt.transport_paused && bt.running); + transport_wake_error = -EIO; + assert(cen_quiesce(&bt) == 0); + assert(!bt.transport_sleep_sent && !bt.transport_paused && !bt.running && bt.asleep); + assert(transport_wakes == 1 && unregisters == 1 && hci_frees == 1); /* Keep-alive save failure unwinds ACIPC sleep and falls back to teardown. */ reset(); bt.bar = (void *)0x3000; save_error = -ENOMEM; assert(cen_suspend(&dev.dev) == -ENOMEM); @@ -270,7 +284,7 @@ def function(source, name): assert(cen_suspend(&dev.dev) == 0); assert(!bt.transport_sleep_sent && bt.asleep && bt.arena && !bt.hdev); assert(transport_sleeps == 1 && transport_wakes == 0 && fallbacks == 1); - assert(saves == 1 && requests == 0); + assert(saves == 1 && requests == 0 && dev.state_saved && !(command & PCI_COMMAND_MASTER)); /* A published arena cannot be reclaimed by a local-only detach. */ reset(); assert(cen_stop(&bt) == -EBUSY && bt.arena && arena_frees == 0); @@ -400,9 +414,9 @@ def function(source, name): def probe_stubs(): stubs = STUBS.replace('struct device { int dummy; };', 'struct device { struct device *parent; void *of_node; };') - stubs = stubs.replace('struct pci_dev { struct device dev; void *data; };', + stubs = stubs.replace('struct pci_dev { struct device dev; void *data; bool state_saved; };', 'struct pci_bus { int number; };\n' - 'struct pci_dev { struct device dev; void *data; struct pci_bus *bus; int devfn; };') + 'struct pci_dev { struct device dev; void *data; bool state_saved; struct pci_bus *bus; int devfn; };') stubs = stubs.replace('struct hci_dev { int dummy; };', 'struct sk_buff;\nstruct hci_dev {\n int bus;\n int (*open)(struct hci_dev *), (*close)(struct hci_dev *);\n int (*flush)(struct hci_dev *), (*setup)(struct hci_dev *);\n int (*post_init)(struct hci_dev *), (*reset_dup_filter)(struct hci_dev *);\n int (*send)(struct hci_dev *, struct sk_buff *);\n};') stubs = stubs.replace('static struct cen_bt *active;', 'static struct cen_bt *active;\nstatic bool probe_hci_registered;') @@ -472,12 +486,16 @@ def run(name, body, stubs=STUBS, tests=TESTS, flags=()): "missing-final-work-drain": ( "cancel_work_sync(&bt->io_work);\n\tskb_queue_purge(&bt->txq);", "if (false) cancel_work_sync(&bt->io_work);\n\tskb_queue_purge(&bt->txq);"), + "missing-quiesce-acipc-wake": ( + "if (bt->transport_sleep_sent) {", + "if (false && bt->transport_sleep_sent) {"), } failures = { 'lost-retained-tuple': 'bt.asleep && bt.arena && arena_frees == 0 && requests == 0', 'missing-pending-fence': 'cen_release(&bt) == -EBUSY', 'missing-save-recovery': 'bt.asleep && bt.arena && requests == 1 && recovery_error == -ENOMEM', 'missing-final-work-drain': 'p && !active->running && !active->io_work && !active->irq_count', + 'missing-quiesce-acipc-wake': '!active->transport_sleep_sent && !active->transport_paused', } for name, (old, new) in controls.items(): assert helpers.count(old) == 1, name diff --git a/tools/asahi/centauri-physical-recovery-tests.c b/tools/asahi/centauri-physical-recovery-tests.c index 4c765125fe7374..475edceb42ca8d 100644 --- a/tools/asahi/centauri-physical-recovery-tests.c +++ b/tools/asahi/centauri-physical-recovery-tests.c @@ -35,7 +35,7 @@ struct pci_dev { struct pci_bus *bus, *subordinate; void *drvdata; int devfn, refs, command, reads, writes; - bool visible, pending; + bool visible, pending, state_saved; }; struct work_struct { int unused; }; struct kref { int count; }; @@ -110,6 +110,8 @@ static void *pci_get_drvdata(struct pci_dev *p) { return p->drvdata; } static bool can_config(struct pci_dev *p) { return link_active && p->visible; } static void pci_clear_master(struct pci_dev *p) { p->reads++; p->writes++; if (can_config(p)) p->command &= ~PCI_COMMAND_MASTER; } +static int pci_save_state(struct pci_dev *p) +{ p->reads++; if (!can_config(p)) return -EIO; p->state_saved = true; return 0; } static int pci_read_config_word(struct pci_dev *p, int where, u16 *v) { (void)where; p->reads++; *v = can_config(p) ? p->command : 0xffff; return 0; } static int pcibios_err_to_errno(int x) { return x ? -EIO : 0; } diff --git a/tools/asahi/centauri-recovery-tests.py b/tools/asahi/centauri-recovery-tests.py index 0950b1edab6482..e46538f68384a6 100644 --- a/tools/asahi/centauri-recovery-tests.py +++ b/tools/asahi/centauri-recovery-tests.py @@ -46,7 +46,7 @@ def block(name): #define list_for_each_entry(v,h,n) for ((v)=owner; (v); (v)=NULL) struct device { int lock; void *data; }; struct pci_bus; -struct pci_dev { struct device dev; struct pci_bus *bus, *subordinate; unsigned devfn; }; +struct pci_dev { struct device dev; struct pci_bus *bus, *subordinate; unsigned devfn; bool state_saved; }; struct pci_bus { struct pci_dev *self; struct pci_bus *subordinate; }; struct kref { int refs; }; struct work_struct { int queued; }; @@ -72,9 +72,9 @@ def block(name): static bool cen_exiting, supported_sleep=true; static struct centauri_t6050_rewake *owner; static struct pci_dev *slots[3]; -static int events[100], nevents, stop_error, beta_error, release_error; -static int wifi_error, requested_error, requests, queues; -enum { STOP_BOOT=1, QUIESCE, WIFI_STOP, IRQ_STOP, CLEAR, FENCE, RELEASE, FREE, +static int events[100], nevents, stop_error, beta_error, release_error, save_error; +static int wifi_error, requested_error, requests, queues, saved_fns[3]; +enum { STOP_BOOT=1, QUIESCE, WIFI_STOP, IRQ_STOP, CLEAR, FENCE, SAVE, RELEASE, FREE, PM_ERROR, PM_COMPLETE, REQUEST }; static void event(int n) { assert(nevents < 100); events[nevents++]=n; } static void mutex_lock(int *p) { assert(!*p); *p=1; } @@ -90,6 +90,16 @@ def block(name): { assert(p); event(CLEAR); } static bool centauri_t6050_stop_dma(struct pci_dev *p) { assert(p); event(FENCE); return !stop_error; } +static int pci_save_state(struct pci_dev *p) +{ + assert(p && (p->devfn & 7) < 3); + event(SAVE); + if (save_error) + return save_error; + p->state_saved = true; + saved_fns[p->devfn & 7]++; + return 0; +} static bool centauri_t6050_ipc_fenced(struct centauri_t6050_ipc *p) { return !p || p->fenced; } static void cancel_delayed_work_sync(int *p) { (void)p; event(STOP_BOOT); } @@ -130,7 +140,8 @@ def block(name): rw->ref.refs=1; rw->generation=1; c->pdev=&fn[0]; c->recovery=rw; c->ready=true; fn[0].dev.data=c; - nevents=stop_error=beta_error=release_error=wifi_error=requests=queues=0; + nevents=stop_error=beta_error=release_error=save_error=wifi_error=requests=queues=0; + memset(saved_fns,0,sizeof(saved_fns)); cen_exiting=false; } static int count(int value) @@ -175,6 +186,34 @@ def block(name): reset(&c,&rw,fn,&bridge,&bus); slots[2]=NULL; assert(!centauri_t6050_domain_fence(&rw)); /* old-owner identity cannot vanish */ + /* Keep-alive saved PCI state on fn1/fn2 must be refreshed after fence, before release. */ + reset(&c,&rw,fn,&bridge,&bus); + ipc.fenced=true; + c.ipc=&ipc; c.firmware=&c; c.descriptor=&rw; + fn[0].state_saved=fn[1].state_saved=fn[2].state_saved=true; + assert(!centauri_t6050_quiesce(&c)); + assert(!saved_fns[0] && saved_fns[1]==1 && saved_fns[2]==1); + assert(fn[1].state_saved && fn[2].state_saved); + assert(first(SAVE)>first(FENCE) && first(RELEASE)>first(SAVE)); + + /* If re-save fails, clear stale state_saved so aborted resume cannot restore it. */ + reset(&c,&rw,fn,&bridge,&bus); + c.ipc=&ipc; c.firmware=&c; c.descriptor=&rw; + fn[1].state_saved=fn[2].state_saved=true; + save_error=-ENOMEM; + assert(!centauri_t6050_quiesce(&c)); + assert(!saved_fns[1] && !saved_fns[2]); + assert(!fn[1].state_saved && !fn[2].state_saved); + + /* Unreadable/gone function (stop_dma fails) must clear state_saved without saving 0xffff. */ + reset(&c,&rw,fn,&bridge,&bus); + c.ipc=&ipc; c.firmware=&c; c.descriptor=&rw; + fn[1].state_saved=fn[2].state_saved=true; + stop_error=1; + assert(centauri_t6050_quiesce(&c)==-EBUSY); + assert(!saved_fns[1] && !saved_fns[2]); + assert(!fn[1].state_saved && !fn[2].state_saved); + reset(&c,&rw,fn,&bridge,&bus); rw.beta_fallback=true; assert(!centauri_t6050_prepare(&fn[0].dev) && c.pm_prepared && !rw.beta_fallback); @@ -226,7 +265,7 @@ def block(name): struct module { int refs; }; struct device { int lock, leases, refs; }; struct pci_bus; -struct pci_dev { struct device dev; struct pci_bus *bus, *subordinate; unsigned devfn; }; +struct pci_dev { struct device dev; struct pci_bus *bus, *subordinate; unsigned devfn; bool state_saved; }; struct pci_bus { struct pci_dev *self; }; struct kref { int refs; }; struct apple_centauri_sleep_ops { @@ -484,6 +523,8 @@ def run(): variants = [('baseline', bodies), ('negative-skip-fence', bodies.replace('!centauri_t6050_domain_fence(c->recovery)', 'false')), ('negative-skip-release', bodies.replace('ret = centauri_t6050_beta_call(c->recovery, true);', 'ret = 0;')), + ('negative-stale-state-saved', bodies.replace('fn[i]->state_saved &&', 'false && fn[i]->state_saved &&')), + ('negative-save-unreadable-fn', bodies.replace('(!fn_stopped || pci_save_state(fn[i]))', 'pci_save_state(fn[i])')), ('negative-lost-pm-error', bodies.replace('error = centauri_t6050_wifi_pm_error(c);', 'error = 0;')), ('negative-drop-new-generation', bodies.replace('rw->rerun = true;', 'rw->rerun = false;'))] ownership = '\n'.join(block(name) for name in [ @@ -502,6 +543,8 @@ def run(): 'negative-unlock-before-tuples': '!remove_done && original->dev.locked && rw->control==original', 'negative-skip-fence': 'first(WIFI_STOP)first(FENCE) && first(FREE)>first(RELEASE)', + 'negative-stale-state-saved': '!saved_fns[0] && saved_fns[1]==1 && saved_fns[2]==1', + 'negative-save-unreadable-fn': '!saved_fns[1] && !saved_fns[2]', 'negative-lost-pm-error': '!c.pm_prepared && rw.active && rw.error==-ETIMEDOUT && queues==1', 'negative-drop-new-generation': 'rw.rerun && queues==1 && rw.ref.refs==2', 'negative-lost-orphan': '!rw.ops && !rw.data && rw.arena==arena && rw.beta==&fn', diff --git a/tools/asahi/centauri-scan-tests.py b/tools/asahi/centauri-scan-tests.py new file mode 100755 index 00000000000000..a095cb79c2b057 --- /dev/null +++ b/tools/asahi/centauri-scan-tests.py @@ -0,0 +1,874 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Host unit tests and negative controls for Centauri Wi-Fi/BT scanning.""" +import argparse +import os +from pathlib import Path +import re +import resource +import shlex +import signal +import subprocess +import tempfile + + +def extract_fn(source, name): + match = re.search( + r"^(?:static )?(?:int|void|bool) " + re.escape(name) + r"\([^;]*?\)\n\{", + source, + re.M, + ) + if not match: + raise RuntimeError(f"missing production function: {name}") + brace = source.index("{", match.start()) + depth, end = 1, brace + 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + return source[match.start():end] + + +WIFI_PRELUDE = r''' +#include +#include +#include +#include +#include +#include + +typedef uint8_t u8; +typedef int8_t s8; +typedef uint16_t u16; +typedef uint32_t u32; +typedef uint64_t u64; + +#define BIT(n) (1U << (n)) +#define BIT_ULL(n) (1ULL << (n)) +#define READ_ONCE(x) (x) +#define WRITE_ONCE(x, v) ((x) = (v)) +#define CEN_SCAN_CHANNELS_MAX 59 +#define SCAN_ACTIVE_MIN_MS 40 +#define SCAN_LISTEN_MS 110 +#define CHANNEL_PASSIVE BIT(4) +#define CHANNEL_RADAR BIT(6) +#define IEEE80211_CHAN_DISABLED BIT(0) +#define IEEE80211_CHAN_NO_IR BIT(1) +#define IEEE80211_CHAN_RADAR BIT(2) +#define HZ 1000 +#define msecs_to_jiffies(x) ((unsigned long)(x)) +#define time_before(a, b) ((long)((a) - (b)) < 0) +#define time_after_eq(a, b) (!time_before(a, b)) +#define max(a, b) ((a) > (b) ? (a) : (b)) +#define NL80211_BAND_2GHZ 0 +#define NL80211_BAND_5GHZ 1 +#define NL80211_BAND_6GHZ 2 +#define NL80211_STA_INFO_CONNECTED_TIME 0 +#define NL80211_STA_INFO_RX_BYTES64 1 +#define NL80211_STA_INFO_TX_BYTES64 2 +#define NL80211_STA_INFO_RX_PACKETS 3 +#define NL80211_STA_INFO_TX_PACKETS 4 +#define NL80211_STA_INFO_SIGNAL 5 +#define lockdep_assert_held(l) assert(*(l)) +#define dev_warn(...) ((void)0) + +struct device { int dummy; }; +struct pci_dev { struct device dev; }; +struct centauri_t6050 { struct pci_dev *pdev; }; +struct ieee80211_channel { int band; u32 center_freq; u32 flags; }; +struct cfg80211_ssid { u8 ssid[32]; u8 ssid_len; }; +struct cfg80211_scan_request { + u32 n_channels; + u32 n_ssids; + struct cfg80211_ssid *ssids; + struct ieee80211_channel *channels[8]; +}; +struct net_device_stats { + u64 rx_bytes, tx_bytes, rx_packets, tx_packets; +}; +struct net_device { struct net_device_stats stats; }; +struct station_info { + u64 filled; + u32 connected_time; + u64 rx_bytes, tx_bytes, rx_packets, tx_packets; + s8 signal; +}; +struct centauri_t6050_wifi { + struct centauri_t6050 *control; + struct { u8 *bar; } a; + struct net_device *netdev; + struct cfg80211_scan_request *scan_request; + int lock; + u32 scans_done; + u16 reply_status, scan_status; + u8 scan_sequence; + bool stopping, command_failed, host_sleep_sent, scan_abort; + s8 station_signal; + bool station_signal_valid; + unsigned long station_signal_at, connected_at; + struct net_device_stats station_start; +}; + +static unsigned long jiffies; +static unsigned int bar_reads, sleep_calls, link_queries, stop_commands; +static unsigned int stop_event_delay, complete_after_drains, drains_seen; +static unsigned int sleep_step_ms, sleep_sets_host_sleep_at; +static unsigned int sleep_completes_on_drain_at; +static bool stop_refuse_342, stop_refuse_other, sleep_sets_abort; +static bool sleep_sets_host_sleep, sleep_checks_station, station_ran_in_sleep; +static u32 bar_state; +static u8 fake_bar[32]; +static struct centauri_t6050_wifi *g_wifi; + +static void fill_station(struct centauri_t6050_wifi *wifi, + struct station_info *sinfo); + +static void mutex_lock(int *l) { assert(!*l); *l = 1; } +static void mutex_unlock(int *l) { assert(*l); *l = 0; } +static void put_unaligned_le16(u16 v, void *p) { memcpy(p, &v, 2); } +static u32 readl(void *addr) { (void)addr; bar_reads++; return bar_state; } +static int firmware_band(int band) { return band; } +static int ieee80211_frequency_to_channel(u32 freq) +{ + return freq == 2412 ? 1 : 36; +} +static void command_refused(struct centauri_t6050_wifi *w, const char *s, int r) +{ + (void)w; (void)s; (void)r; +} +static int query_link_status(struct centauri_t6050_wifi *wifi) +{ + assert(wifi->lock); + link_queries++; + wifi->station_signal = -52; + wifi->station_signal_valid = true; + wifi->station_signal_at = jiffies; + return 0; +} +static int command(struct centauri_t6050_wifi *wifi, u32 id, + const void *payload, size_t size) +{ + (void)payload; (void)size; + assert(wifi->lock); + if (id == 65537) { + stop_commands++; + if (stop_refuse_342) { + wifi->reply_status = 342; + return -EREMOTEIO; + } + if (stop_refuse_other) { + wifi->reply_status = 500; + return -EREMOTEIO; + } + wifi->reply_status = 0; + return 0; + } + return 0; +} +static void drain(struct centauri_t6050_wifi *wifi) +{ + assert(wifi->lock); + drains_seen++; + if (complete_after_drains && drains_seen >= complete_after_drains) { + wifi->scans_done++; + complete_after_drains = 0; + } + if (stop_commands && stop_event_delay) { + stop_event_delay--; + if (!stop_event_delay) + wifi->scans_done++; + } +} +static void usleep_range(unsigned long a, unsigned long b) +{ + (void)a; (void)b; + sleep_calls++; + jiffies += sleep_step_ms ? sleep_step_ms : 250; + /* Must not hold wifi->lock across scan wait sleeps. */ + assert(!g_wifi->lock); + if (sleep_checks_station && !station_ran_in_sleep) { + struct station_info sinfo = {}; + + mutex_lock(&g_wifi->lock); + fill_station(g_wifi, &sinfo); + mutex_unlock(&g_wifi->lock); + assert(link_queries == 0); + assert(sinfo.filled & BIT_ULL(NL80211_STA_INFO_SIGNAL)); + assert(sinfo.signal == -61); + station_ran_in_sleep = true; + } + if (sleep_sets_abort) { + g_wifi->scan_abort = true; + sleep_sets_abort = false; + } + if (sleep_sets_host_sleep) { + g_wifi->host_sleep_sent = true; + sleep_sets_host_sleep = false; + } + if (sleep_sets_host_sleep_at && sleep_calls == sleep_sets_host_sleep_at) + g_wifi->host_sleep_sent = true; + if (sleep_completes_on_drain_at && + sleep_calls == sleep_completes_on_drain_at) + complete_after_drains = drains_seen + 1; +} +''' + +WIFI_TESTS = r''' +static struct pci_dev pdev; +static struct centauri_t6050 ctrl = { .pdev = &pdev }; +static struct net_device ndev; +static struct centauri_t6050_wifi wifi; +static struct ieee80211_channel ch1 = { .band = NL80211_BAND_2GHZ, .center_freq = 2412 }; +static struct cfg80211_scan_request req; + +static void reset_wifi(void) +{ + memset(&wifi, 0, sizeof(wifi)); + memset(&ndev, 0, sizeof(ndev)); + memset(&req, 0, sizeof(req)); + wifi.control = &ctrl; + wifi.a.bar = fake_bar; + wifi.netdev = &ndev; + req.n_channels = 1; + req.channels[0] = &ch1; + wifi.scan_request = &req; + wifi.station_signal = -61; + wifi.station_signal_valid = true; + wifi.station_signal_at = 0; + g_wifi = &wifi; + jiffies = 2000; + bar_state = 2; + bar_reads = sleep_calls = link_queries = stop_commands = 0; + stop_event_delay = complete_after_drains = drains_seen = 0; + sleep_step_ms = sleep_sets_host_sleep_at = 0; + sleep_completes_on_drain_at = 0; + stop_refuse_342 = stop_refuse_other = false; + sleep_sets_abort = sleep_sets_host_sleep = false; + sleep_checks_station = station_ran_in_sleep = false; +} + +int main(void) +{ + /* 1. Normal scan unlocks during sleep; concurrent fill_station skips FW cmd 20. */ + reset_wifi(); + complete_after_drains = 3; + sleep_checks_station = true; + mutex_lock(&wifi.lock); + assert(scan_profile27(&wifi) == 0); + mutex_unlock(&wifi.lock); + assert(sleep_calls >= 1 && station_ran_in_sleep && link_queries == 0); + + /* Outside a scan, fill_station refreshes link status normally. */ + wifi.scan_request = NULL; + { + struct station_info sinfo = {}; + + mutex_lock(&wifi.lock); + fill_station(&wifi, &sinfo); + mutex_unlock(&wifi.lock); + assert(link_queries == 1 && sinfo.signal == -52); + } + + /* 2. Scan abort sends 65537 and waits for 0x80000005 completion. */ + reset_wifi(); + sleep_sets_abort = true; + stop_event_delay = 2; + mutex_lock(&wifi.lock); + assert(scan_profile27(&wifi) == -ECANCELED); + mutex_unlock(&wifi.lock); + assert(stop_commands == 1 && wifi.scans_done == 1); + + /* 3. Scan abort with firmware status 342 (already ended) returns cleanly. */ + reset_wifi(); + wifi.scan_abort = true; + stop_refuse_342 = true; + mutex_lock(&wifi.lock); + assert(scan_stop_chunk(&wifi, 0) == 0); + mutex_unlock(&wifi.lock); + assert(stop_commands == 1); + + /* 4. Scan timeout stops chunk and waits for 0x80000005 before returning. */ + reset_wifi(); + stop_event_delay = 2; + mutex_lock(&wifi.lock); + assert(scan_profile27(&wifi) == -ETIMEDOUT); + mutex_unlock(&wifi.lock); + assert(stop_commands == 1 && wifi.scans_done == 1); + + /* 5. Host sleep entered while unlocked aborts without BAR read or stop cmd. */ + reset_wifi(); + sleep_sets_host_sleep = true; + mutex_lock(&wifi.lock); + assert(scan_profile27(&wifi) == -EIO); + mutex_unlock(&wifi.lock); + assert(bar_reads == 2 && stop_commands == 0); + + /* 6. scan_stop_chunk() entry guard refuses to ring doorbell when stopped. */ + reset_wifi(); + wifi.host_sleep_sent = true; + mutex_lock(&wifi.lock); + assert(scan_stop_chunk(&wifi, 0) == -EIO); + mutex_unlock(&wifi.lock); + assert(stop_commands == 0 && bar_reads == 0); + + /* 7. Host sleep set during the final sleep as deadline expires skips 65537. */ + reset_wifi(); + sleep_step_ms = 9000; + sleep_sets_host_sleep_at = 1; + mutex_lock(&wifi.lock); + assert(scan_profile27(&wifi) == -EIO); + mutex_unlock(&wifi.lock); + assert(sleep_calls == 1 && stop_commands == 0); + + /* 8. Completion arriving during final sleep as deadline expires succeeds cleanly. */ + reset_wifi(); + sleep_step_ms = 9000; + sleep_completes_on_drain_at = 1; + mutex_lock(&wifi.lock); + assert(scan_profile27(&wifi) == 0); + mutex_unlock(&wifi.lock); + assert(sleep_calls == 1 && stop_commands == 0 && wifi.scans_done == 1); + + puts("PASS: Centauri T6050 Wi-Fi scan lock-release and stop synchronization"); + return 0; +} +''' + +SHARED_WIFI_PRELUDE = r''' +#include +#include +#include +#include +#include +#include + +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; + +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) +#define READ_ONCE(x) (x) +#define WRITE_ONCE(x, v) ((x) = (v)) +#define SCAN_PASSIVE_DWELL_MS 110 +#define msecs_to_jiffies(x) ((unsigned long)(x)) +#define time_before(a, b) ((long)((a) - (b)) < 0) +#define time_after(a, b) time_before(b, a) +#define max(a, b) ((a) > (b) ? (a) : (b)) +#define min_t(type, x, y) ((type)(x) < (type)(y) ? (type)(x) : (type)(y)) +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - __builtin_offsetof(type, member))) +static void dev_warn(void *d, const char *fmt, ...) { (void)d; (void)fmt; } +static void dev_info(void *d, const char *fmt, ...) { (void)d; (void)fmt; } +static void dev_dbg(void *d, const char *fmt, ...) { (void)d; (void)fmt; } + +static const u8 five_ghz[25] = { 0 }; + +struct device { int dummy; }; +struct pci_dev { struct device dev; }; +struct centauri { struct pci_dev *pdev; }; +struct work_struct { int dummy; }; +struct cfg80211_scan_request { int dummy; }; +struct cfg80211_scan_info { bool aborted; }; +struct centauri_wifi { + struct centauri *control; + struct { u8 *bar; } a; + struct work_struct scan_work; + struct cfg80211_scan_request *scan_request; + bool scan_abort; + int lock; + u16 reply_status; + u32 channels_seen, scans_done, beacons_seen; + bool stopping, transport_paused; +}; + +static unsigned long jiffies; +static unsigned int scan_commands, stop_commands, sleep_calls, drains_seen; +static unsigned int sleep_step_ms, sleep_sets_paused_at, sleep_sets_abort_at; +static unsigned int complete_on_stop_drain, channels_per_drain; +static bool stop_never_completes, last_scan_aborted, scan_done_called; +static bool pause_between_chunks; +static u32 bar_state; +static u8 fake_bar[32]; +static struct centauri_wifi *g_swifi; + +static void mutex_lock(int *l) { assert(!*l); *l = 1; } +static void mutex_unlock(int *l) { assert(*l); *l = 0; } +static u32 readl(void *addr) { (void)addr; return bar_state; } +static unsigned int recovery_requests; +static void centauri_recovery_request(struct centauri *c, const char *why) +{ + (void)c; (void)why; recovery_requests++; +} +static size_t build_scan(struct centauri_wifi *w, unsigned int c, u8 *b) +{ + (void)w; (void)c; (void)b; + return 14; +} +static void cfg80211_scan_done(struct cfg80211_scan_request *r, + struct cfg80211_scan_info *info) +{ + (void)r; + scan_done_called = true; + last_scan_aborted = info->aborted; +} +static int command(struct centauri_wifi *wifi, u32 id, + const void *payload, size_t size) +{ + (void)payload; (void)size; + assert(wifi->lock); + if (id == 65551) { + scan_commands++; + return 0; + } + if (id == 65537) { + stop_commands++; + wifi->reply_status = 0; + return 0; + } + return 0; +} +static void drain(struct centauri_wifi *wifi) +{ + assert(wifi->lock); + drains_seen++; + if (channels_per_drain) + wifi->channels_seen += channels_per_drain; + if (stop_commands && !stop_never_completes && complete_on_stop_drain) { + complete_on_stop_drain--; + if (!complete_on_stop_drain) { + wifi->scans_done++; + if (pause_between_chunks) + wifi->transport_paused = true; + } + } +} +static void usleep_range(unsigned long a, unsigned long b) +{ + (void)a; (void)b; + sleep_calls++; + jiffies += sleep_step_ms ? sleep_step_ms : 250; + assert(!g_swifi->lock); + if (sleep_sets_paused_at && sleep_calls == sleep_sets_paused_at) + g_swifi->transport_paused = true; + if (sleep_sets_abort_at && sleep_calls == sleep_sets_abort_at) + g_swifi->scan_abort = true; +} +''' + +SHARED_WIFI_TESTS = r''' +static struct pci_dev spdev; +static struct centauri sctrl = { .pdev = &spdev }; +static struct cfg80211_scan_request sreq; +static struct centauri_wifi swifi; + +static void reset_swifi(void) +{ + memset(&swifi, 0, sizeof(swifi)); + swifi.control = &sctrl; + swifi.a.bar = fake_bar; + swifi.scan_request = &sreq; + g_swifi = &swifi; + jiffies = 2000; + bar_state = 2; + scan_commands = stop_commands = sleep_calls = drains_seen = 0; + sleep_step_ms = sleep_sets_paused_at = sleep_sets_abort_at = 0; + complete_on_stop_drain = channels_per_drain = 0; + stop_never_completes = last_scan_aborted = scan_done_called = false; + pause_between_chunks = false; +} + +int main(void) +{ + /* 1. Entry guard in scan_stop_chunk() skips command(65537) when paused. */ + reset_swifi(); + swifi.transport_paused = true; + mutex_lock(&swifi.lock); + assert(scan_stop_chunk(&swifi, 0) == -EIO); + mutex_unlock(&swifi.lock); + assert(stop_commands == 0); + + /* 2. Transport paused during final sleep at deadline skips 65537 and next chunk. */ + reset_swifi(); + sleep_step_ms = 9000; + sleep_sets_paused_at = 1; + scan_worker(&swifi.scan_work); + assert(scan_done_called && last_scan_aborted); + assert(scan_commands == 1 && stop_commands == 0); + + /* 3. Timeout whose stop times out propagates error and does NOT start chunk 1. */ + reset_swifi(); + sleep_step_ms = 9000; + stop_never_completes = true; + scan_worker(&swifi.scan_work); + assert(scan_commands == 1 && stop_commands == 1); + assert(scan_done_called && last_scan_aborted); + + /* 4. Transport paused between chunks stops before starting chunk 1. */ + reset_swifi(); + sleep_step_ms = 9000; + complete_on_stop_drain = 1; + pause_between_chunks = true; + scan_worker(&swifi.scan_work); + assert(scan_done_called && last_scan_aborted); + assert(scan_commands == 1 && stop_commands == 1); + + /* 5. Abort arriving after 65537 already sent (stopped=true) still waits for 0x05. */ + reset_swifi(); + channels_per_drain = 13; + sleep_sets_abort_at = 1; + complete_on_stop_drain = 3; + scan_worker(&swifi.scan_work); + assert(scan_done_called && last_scan_aborted); + assert(scan_commands == 1 && stop_commands == 1 && swifi.scans_done == 1); + + puts("PASS: Centauri shared Wi-Fi scan stop/abort/chunk state checks"); + return 0; +} +''' + +BT_PRELUDE = r''' +#include +#include +#include +#include +#include +#include + +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; + +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +#define READ_ONCE(x) (x) +#define WRITE_ONCE(x, v) ((x) = (v)) +#define GFP_KERNEL 0 +#define CEN_RX 0x8000 +#define CEN_TX 0xa000 +#define CEN_FOOTER 260 +#define CEN_STRIDE (16 + CEN_FOOTER) +#define CEN_RX_SLOTS 17 +#define CEN_TX_SLOTS 5 +#define CEN_LE_RX 0xc000 +#define CEN_LE_TX 0xe000 +#define CEN_LE_FOOTER 256 +#define CEN_LE_STRIDE (16 + CEN_LE_FOOTER) +#define CEN_LE_SLOTS 17 +#define HCI_EVENT_HDR_SIZE 2U +#define HCI_EVENT_PKT 4 +#define HCI_EV_CMD_STATUS 0x0f +#define HCI_EV_CONN_COMPLETE 0x03 +#define HCI_OP_CREATE_CONN 0x0405 +#define CEN_OP_CREATE_CONN 0xff7b +#define ACL_LINK 1 +#define dma_rmb() ((void)0) +#define dev_err(...) ((void)0) +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - __builtin_offsetof(type, member))) + +struct hci_ev_conn_complete { u8 dummy[11]; }; +struct cen_aux_spec { u16 id, slots, footer; bool receive; }; +static const struct cen_aux_spec cen_aux_specs[] = { + { 2, 9, 2592, false }, { 8, 9, 2592, true }, +}; +struct cen_aux_state { u32 offset; u16 head, post; bool opened; }; +struct work_struct { int dummy; }; +struct sk_buff_head { unsigned int len; }; +struct sk_buff { u8 data[64]; u32 len; u8 pkt_type; }; +struct pci_dev { int dev; }; +struct hci_dev { struct { u32 byte_rx, err_rx; } stat; }; +struct cen_bt { + struct pci_dev *pdev; + struct hci_dev *hdev; + u8 *bar; + u8 *arena; + int lock; + struct work_struct io_work; + struct sk_buff_head txq, acl_txq, le_txq; + u16 acl_tx_head, le_tx_head; + u16 tx_head, rx_head, rx_post; + u16 le_rx_head, le_rx_post; + struct cen_aux_state aux[ARRAY_SIZE(cen_aux_specs)]; + bool running, transport_paused; + bool connection_command_supported, connection_status_pending; +}; + +static u16 mock_tail[16]; +static bool advance_rx_tail_on_post, advance_tx_tail_after_tx; +static unsigned int rx_frames, reschedules; +static struct sk_buff fake_skb; + +static void mutex_lock(int *l) { assert(!*l); *l = 1; } +static void mutex_unlock(int *l) { assert(*l); *l = 0; } +static u32 readl(void *p) { (void)p; return 2; } +static u16 get_unaligned_le16(const void *p) { u16 v; memcpy(&v, p, 2); return v; } +static u32 get_unaligned_le32(const void *p) { u32 v; memcpy(&v, p, 4); return v; } +static void put_unaligned_le16(u16 v, void *p) { memcpy(p, &v, 2); } +static bool skb_queue_empty(const struct sk_buff_head *q) { return q->len == 0; } +static void schedule_work(struct work_struct *w) { (void)w; reschedules++; } +static u16 cen_tail(struct cen_bt *bt, u16 ring) { (void)bt; return mock_tail[ring]; } +static int cen_aux_drain(struct cen_bt *bt, bool repost) { (void)bt; (void)repost; return 0; } +static int cen_receive_acl(struct cen_bt *bt, const u8 *d, u32 l) { (void)bt; (void)d; (void)l; return 0; } +static void cen_le_rx_buffer(struct cen_bt *bt, u16 slot) { (void)bt; (void)slot; } +static void cen_rx_buffer(struct cen_bt *bt, u16 slot) { (void)bt; (void)slot; } +static void cen_fixup_scan_response(u8 *e, size_t l) { (void)e; (void)l; } +static struct sk_buff *bt_skb_alloc(u32 len, int flags) +{ + (void)flags; + assert(len <= sizeof(fake_skb.data)); + fake_skb.len = 0; + return &fake_skb; +} +static void skb_put_data(struct sk_buff *skb, const void *d, u32 len) +{ + memcpy(skb->data, d, len); + skb->len = len; +} +#define hci_skb_pkt_type(skb) ((skb)->pkt_type) +static void hci_recv_frame(struct hci_dev *h, struct sk_buff *s) { (void)h; (void)s; rx_frames++; } +static void cen_post(struct cen_bt *bt, u16 ring, u16 val) +{ + (void)bt; (void)val; + if (ring == 7 && advance_rx_tail_on_post) { + advance_rx_tail_on_post = false; + mock_tail[7] = (mock_tail[7] + 1) % CEN_RX_SLOTS; + } +} +static int cen_transmit(struct cen_bt *bt, struct sk_buff_head *q, u16 ring, + u16 slots, u32 off, u16 footer, u16 *head) +{ + (void)bt; (void)off; (void)footer; + if (ring == 1 && advance_tx_tail_after_tx && q->len) { + /* Simulate ring momentarily full during transmit, then freed right after. */ + *head = (mock_tail[1] + slots - 1) % slots; + mock_tail[1] = (mock_tail[1] + 1) % slots; + advance_tx_tail_after_tx = false; + } + return 0; +} +''' + +BT_TESTS = r''' +static u8 arena[0x10000]; +static u8 fake_bar[32]; +static struct pci_dev pdev; +static struct hci_dev hdev; +static struct cen_bt bt; + +static void reset_bt(void) +{ + memset(&bt, 0, sizeof(bt)); + memset(arena, 0, sizeof(arena)); + memset(mock_tail, 0, sizeof(mock_tail)); + bt.pdev = &pdev; + bt.hdev = &hdev; + bt.bar = fake_bar; + bt.arena = arena; + bt.running = true; + bt.rx_post = CEN_RX_SLOTS - 1; + bt.le_rx_post = CEN_LE_SLOTS - 1; + advance_rx_tail_on_post = advance_tx_tail_after_tx = false; + rx_frames = reschedules = 0; +} + +static void put_rx_event(u16 slot) +{ + u8 *d = arena + CEN_RX + slot * CEN_STRIDE; + u32 hdr = 1 | (4U << 8); + + memcpy(d, &hdr, 4); + d[16] = 0x3e; + d[17] = 2; + d[18] = 0x0d; + d[19] = 0; +} + +int main(void) +{ + /* 1. Coalesced RX arrival during drain triggers io_work reschedule. */ + reset_bt(); + put_rx_event(0); + put_rx_event(1); + mock_tail[7] = 1; + advance_rx_tail_on_post = true; + cen_io_work(&bt.io_work); + assert(rx_frames == 1 && bt.rx_head == 1 && reschedules == 1); + + /* Second pass drains remaining event and stays idle (no spin). */ + reschedules = 0; + cen_io_work(&bt.io_work); + assert(rx_frames == 2 && bt.rx_head == 2 && reschedules == 0); + + /* 2. Pending TX queue with newly freed TX ring slot reschedules io_work. */ + reset_bt(); + bt.txq.len = 1; + advance_tx_tail_after_tx = true; + cen_io_work(&bt.io_work); + assert(reschedules == 1); + + /* 3. Idle rings do not reschedule. */ + reset_bt(); + cen_io_work(&bt.io_work); + assert(reschedules == 0); + + puts("PASS: Centauri Bluetooth RX/TX ring drain reschedule"); + return 0; +} +''' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", type=Path) + parser.add_argument("--negative-controls", action="store_true") + parser.add_argument("--source-root", type=Path) + args = parser.parse_args() + root = args.source_root or Path(__file__).resolve().parents[2] + wifi_src = ( + root / "drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c" + ).read_text() + shared_src = ( + root / "drivers/net/wireless/apple/centauri/centauri_wifi.c" + ).read_text() + bt_src = (root / "drivers/bluetooth/btcentauri_t6050.c").read_text() + + wifi_prod = "\n\n".join( + extract_fn(wifi_src, name) + for name in ( + "scan_transport_stopped", + "scan_stop_chunk", + "scan_profile27", + "fill_station", + ) + ) + shared_prod = "\n\n".join( + extract_fn(shared_src, name) + for name in ( + "scan_transport_stopped", + "scan_wait_stop", + "scan_stop_chunk", + "scan_worker", + ) + ) + bt_prod = "\n\n".join( + extract_fn(bt_src, name) + for name in ("cen_rx_pending", "cen_tx_ready", "cen_io_work") + ) + + wifi_variants = [("wifi-production", WIFI_PRELUDE + wifi_prod + WIFI_TESTS, 0, None)] + shared_variants = [ + ("shared-wifi-production", SHARED_WIFI_PRELUDE + shared_prod + SHARED_WIFI_TESTS, 0, None) + ] + bt_variants = [("bt-production", BT_PRELUDE + bt_prod + BT_TESTS, 0, None)] + + if args.negative_controls: + wifi_controls = [ + ( + "scan-holds-lock-in-sleep", + "\t\t\tmutex_unlock(&wifi->lock);\n\t\t\tusleep_range(1000, 2000);\n\t\t\tmutex_lock(&wifi->lock);", + "\t\t\tusleep_range(1000, 2000);", + "!g_wifi->lock", + ), + ( + "station-queries-fw-during-scan", + "if (!wifi->scan_request &&\n\t time_after_eq(jiffies, wifi->station_signal_at + HZ))", + "if (time_after_eq(jiffies, wifi->station_signal_at + HZ))", + "link_queries == 0", + ), + ( + "timeout-skips-stop-wait", + "\t\t\tret = scan_stop_chunk(wifi, done);\n\t\t\treturn ret == -EIO ? -EIO : -ETIMEDOUT;", + "\t\t\tcommand(wifi, 65537, NULL, 0);\n\t\t\treturn -ETIMEDOUT;", + "wifi.scans_done == 1", + ), + ( + "abort-ignores-342", + "if (ret == -EREMOTEIO && wifi->reply_status == 342)\n\t\treturn 0;", + "if (false && ret == -EREMOTEIO && wifi->reply_status == 342)\n\t\treturn 0;", + "scan_stop_chunk(&wifi, 0) == 0", + ), + ( + "t6050-stop-skips-entry-guard", + "\tlockdep_assert_held(&wifi->lock);\n\tif (scan_transport_stopped(wifi))\n\t\treturn -EIO;", + "\tlockdep_assert_held(&wifi->lock);", + "stop_commands == 0", + ), + ] + for name, old, new, expected_msg in wifi_controls: + if old not in wifi_prod: + raise RuntimeError(f"missing pattern for {name}") + wifi_variants.append( + (name, WIFI_PRELUDE + wifi_prod.replace(old, new, 1) + WIFI_TESTS, + -signal.SIGABRT, expected_msg) + ) + + shared_controls = [ + ( + "shared-timeout-drops-stop-ret", + "\t\t\t\t\tret = stopped ? -ETIMEDOUT :\n\t\t\t\t\t scan_stop_chunk(wifi, done);", + "\t\t\t\t\tif (!stopped)\n\t\t\t\t\t\tscan_stop_chunk(wifi, done);", + "scan_commands == 1", + ), + ( + "shared-abort-skips-inflight-stop-wait", + "\t\t\t\tint stop_ret = stopped ? scan_wait_stop(wifi, done) :\n\t\t\t\t\t scan_stop_chunk(wifi, done);", + "\t\t\t\tint stop_ret = stopped ? 0 :\n\t\t\t\t\t scan_stop_chunk(wifi, done);", + "swifi.scans_done == 1", + ), + ] + for name, old, new, expected_msg in shared_controls: + if old not in shared_prod: + raise RuntimeError(f"missing pattern for {name}") + shared_variants.append( + (name, SHARED_WIFI_PRELUDE + shared_prod.replace(old, new, 1) + SHARED_WIFI_TESTS, + -signal.SIGABRT, expected_msg) + ) + + bt_controls = [ + ( + "bt-drops-rx-reschedule", + "if (cen_rx_pending(bt) ||", + "if ((false && cen_rx_pending(bt)) ||", + "reschedules == 1", + ), + ( + "bt-drops-tx-reschedule", + "cen_tx_ready(bt, &bt->txq, 1, CEN_TX_SLOTS, bt->tx_head) ||", + "(false && cen_tx_ready(bt, &bt->txq, 1, CEN_TX_SLOTS, bt->tx_head)) ||", + "reschedules == 1", + ), + ] + for name, old, new, expected_msg in bt_controls: + if old not in bt_prod: + raise RuntimeError(f"missing pattern for {name}") + bt_variants.append( + (name, BT_PRELUDE + bt_prod.replace(old, new, 1) + BT_TESTS, + -signal.SIGABRT, expected_msg) + ) + + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + compiler = shlex.split(os.environ.get("CC", "cc")) + with tempfile.TemporaryDirectory(prefix="centauri-scan-test-") as directory: + out = args.out or Path(directory) + out.mkdir(parents=True, exist_ok=True) + for name, code, expected, msg in wifi_variants + shared_variants + bt_variants: + harness, binary = out / (name + ".c"), out / name + harness.write_text(code) + subprocess.run( + compiler + ["-std=gnu11", "-Wall", "-Wextra", "-Werror", + str(harness), "-o", str(binary)], + check=True, + ) + result = subprocess.run([str(binary)], capture_output=True, text=True) + (out / (name + ".log")).write_text(result.stdout + result.stderr) + if result.returncode != expected or ( + expected and ("Assertion" not in result.stderr or msg not in result.stderr) + ): + raise RuntimeError( + f"{name}: exit {result.returncode}, expected {expected}\n" + + result.stdout + result.stderr + ) + print(f"{name}: {'PASS' if expected == 0 else 'correctly rejected'}") + + +if __name__ == "__main__": + main() diff --git a/tools/asahi/centauri-wifi-avoid-tests.py b/tools/asahi/centauri-wifi-avoid-tests.py new file mode 100755 index 00000000000000..aa1f3b3ffb7938 --- /dev/null +++ b/tools/asahi/centauri-wifi-avoid-tests.py @@ -0,0 +1,254 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Execute the checkout's T6050 Wi-Fi 6 GHz avoid helper against a mock cfg80211 BSS list. + +The mock keeps cfg80211's set behaviour (unlinking any member of a beacon's +multiple-BSSID set unlinks the whole set), entries cfg80211 does not return +(expired) and entries it does not unlink. No kernel build or hardware is needed. +""" +import argparse +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +SRC = "drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c" + + +def block(source, kind, name): + """The production function (kind: bool, void) or struct `name`, braces balanced.""" + if kind == "struct": + match = re.search(r"^struct " + re.escape(name) + r" \{", source, re.M) + else: + match = re.search(r"^static " + kind + r" " + re.escape(name) + r"\(", source, re.M) + if not match: + raise RuntimeError(f"production {kind} {name} missing") + brace = source.index("{", match.start()) + depth, end = 1, brace + 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + if kind == "struct": + end = source.index(";", end) + 1 + return source[match.start():end] + + +PRELUDE = r''' +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; +#define ETH_ALEN 6 +#define IEEE80211_MAX_SSID_LEN 32 +#define WLAN_EID_SSID 0 +#define NL80211_BAND_5GHZ 1 +#define NL80211_BAND_6GHZ 3 +#define IEEE80211_BSS_TYPE_ANY 0 +#define IEEE80211_PRIVACY_ANY 0 +#define time_after(a, b) ((long)((b) - (a)) < 0) +#define rcu_read_lock() ((void)0) +#define rcu_read_unlock() ((void)0) +#define container_of(p, t, m) ((t *)((char *)(p) - offsetof(t, m))) +struct list_head { struct list_head *next, *prev; }; +#define list_for_each_entry(pos, head, member) \ + for (pos = container_of((head)->next, __typeof__(*pos), member); \ + &pos->member != (head); \ + pos = container_of(pos->member.next, __typeof__(*pos), member)) +static unsigned long jiffies = 1000; +struct ieee80211_channel { int band; int center_freq; }; +struct element { u8 id, datalen; u8 data[IEEE80211_MAX_SSID_LEN]; }; +struct cfg80211_bss { + u8 bssid[ETH_ALEN]; + struct ieee80211_channel *channel; + struct cfg80211_bss *transmitted_bss; + struct list_head nontrans_list; + /* the mock's own */ + struct element ssid; + bool linked, expired, sticky; +}; +struct wiphy { int unused; }; +struct centauri_t6050_wifi { + struct wiphy *wiphy; + bool connecting, connected, avoid_valid; + u8 ssid[IEEE80211_MAX_SSID_LEN], bssid[ETH_ALEN]; + size_t ssid_len; + u8 avoid_ssid[IEEE80211_MAX_SSID_LEN]; + size_t avoid_ssid_len; + unsigned long avoid_until; +}; +static bool ether_addr_equal(const u8 *a, const u8 *b) { return !memcmp(a, b, ETH_ALEN); } +static void ether_addr_copy(u8 *d, const u8 *s) { memcpy(d, s, ETH_ALEN); } + +#define MAX_BSS 16 +static struct cfg80211_bss bsses[MAX_BSS]; +static int n_bss, walks; +static const struct element *ieee80211_bss_get_elem(const struct cfg80211_bss *b, int id) +{ + return id == WLAN_EID_SSID ? &b->ssid : NULL; +} +static void cfg80211_bss_iter(struct wiphy *w, void *chandef, + void (*iter)(struct wiphy *, struct cfg80211_bss *, void *), void *data) +{ + walks++; + for (int i = 0; i < n_bss; i++) + if (bsses[i].linked) + iter(w, &bsses[i], data); +} +static struct cfg80211_bss *cfg80211_get_bss(struct wiphy *w, struct ieee80211_channel *ch, + const u8 *bssid, const u8 *ssid, size_t ssid_len, + int type, int privacy) +{ + for (int i = 0; i < n_bss; i++) { + struct cfg80211_bss *b = &bsses[i]; + if (b->linked && !b->expired && b->channel == ch && ether_addr_equal(b->bssid, bssid) && + (!ssid || (b->ssid.datalen == ssid_len && !memcmp(b->ssid.data, ssid, ssid_len)))) + return b; + } + return NULL; +} +/* As cfg80211: a member takes its whole set down; a sticky entry stays. */ +static void unlink_one(struct cfg80211_bss *b) { if (!b->sticky) b->linked = false; } +static void cfg80211_unlink_bss(struct wiphy *w, struct cfg80211_bss *b) +{ + struct cfg80211_bss *set = b->transmitted_bss ? b->transmitted_bss : b; + for (int i = 0; i < n_bss; i++) + if (&bsses[i] == set || bsses[i].transmitted_bss == set) + unlink_one(&bsses[i]); +} +static void cfg80211_put_bss(struct wiphy *w, struct cfg80211_bss *b) { (void)w; (void)b; } +''' + +TESTS = r''' +static struct ieee80211_channel c6a = { NL80211_BAND_6GHZ, 6135 }, c6b = { NL80211_BAND_6GHZ, 6455 }, + c5 = { NL80211_BAND_5GHZ, 5180 }; +static struct wiphy wiphy; +static struct centauri_t6050_wifi wifi; + +static void reset(const char *avoid) +{ + memset(bsses, 0, sizeof(bsses)); n_bss = 0; walks = 0; + memset(&wifi, 0, sizeof(wifi)); wifi.wiphy = &wiphy; + wifi.avoid_valid = true; wifi.avoid_until = jiffies + 120; + wifi.avoid_ssid_len = strlen(avoid); memcpy(wifi.avoid_ssid, avoid, wifi.avoid_ssid_len); +} +/* One entry; tx: its set's transmitting entry, or NULL when it transmits. */ +static struct cfg80211_bss *add(u8 last, struct ieee80211_channel *ch, const char *ssid, struct cfg80211_bss *tx) +{ + struct cfg80211_bss *b = &bsses[n_bss++]; + u8 a[ETH_ALEN] = { 2, 0, 0, 0, 0, last }; + memcpy(b->bssid, a, ETH_ALEN); b->channel = ch; b->linked = true; + b->ssid.datalen = strlen(ssid); memcpy(b->ssid.data, ssid, b->ssid.datalen); + b->nontrans_list.next = b->nontrans_list.prev = &b->nontrans_list; + b->transmitted_bss = tx; + if (tx) { /* list_add_tail(&b->nontrans_list, &tx->nontrans_list) */ + struct list_head *h = &tx->nontrans_list; + b->nontrans_list.prev = h->prev; b->nontrans_list.next = h; + h->prev->next = &b->nontrans_list; h->prev = &b->nontrans_list; + } + return b; +} +static int linked(void) { int n = 0; for (int i = 0; i < n_bss; i++) n += bsses[i].linked; return n; } + +int main(void) +{ + /* An avoided entry cfg80211 does not return, ahead of two that it does: both go. */ + reset("guest"); + struct cfg80211_bss *x = add(1, &c6a, "guest", NULL), *y = add(2, &c6b, "guest", NULL), + *z = add(3, &c6b, "guest", NULL); + x->expired = true; + avoid_unlink(&wifi, NULL); + assert(x->linked && !y->linked && !z->linked); + /* The same with one that cfg80211 does not unlink. */ + reset("guest"); + x = add(1, &c6a, "guest", NULL); y = add(2, &c6b, "guest", NULL); z = add(3, &c6b, "guest", NULL); + x->sticky = true; + avoid_unlink(&wifi, NULL); + assert(x->linked && !y->linked && !z->linked); + puts("PASS passed-over entries: each later avoided entry is still unlinked"); + + /* Two avoided entries, the first in the joined BSS's set: it stays, the second goes. */ + reset("guest"); + struct cfg80211_bss *t1 = add(0x10, &c6a, "main", NULL), *g1 = add(0x11, &c6a, "guest", t1), + *t2 = add(0x20, &c6b, "other", NULL), *g2 = add(0x21, &c6b, "guest", t2), + *g5 = add(0x30, &c5, "guest", NULL); + wifi.connected = true; memcpy(wifi.bssid, t1->bssid, ETH_ALEN); + memcpy(wifi.ssid, "guest", 5); wifi.ssid_len = 5; + avoid_unlink(&wifi, wifi.bssid); + assert(t1->linked && g1->linked && !t2->linked && !g2->linked && g5->linked); + puts("PASS keep: the joined BSS's set stays, another AP's set goes with its avoided profile, 5 GHz untouched"); + + /* The current network's set stays though it holds the avoided profile; others go. */ + reset("guest"); + t1 = add(0x10, &c6a, "main", NULL); g1 = add(0x11, &c6a, "guest", t1); + t2 = add(0x20, &c6b, "main", NULL); g2 = add(0x21, &c6b, "guest", t2); + struct cfg80211_bss *t3 = add(0x40, &c6b, "lab", NULL), *g3 = add(0x41, &c6b, "guest", t3); + wifi.connected = true; memcpy(wifi.bssid, (u8[]){ 2, 0, 0, 0, 0, 0x99 }, ETH_ALEN); + memcpy(wifi.ssid, "main", 4); wifi.ssid_len = 4; + avoid_unlink(&wifi, wifi.bssid); + assert(t1->linked && g1->linked && t2->linked && g2->linked && !t3->linked && !g3->linked); + /* Not connecting or connected: no current network, all three sets go. */ + reset("guest"); + t1 = add(0x10, &c6a, "main", NULL); g1 = add(0x11, &c6a, "guest", t1); + t2 = add(0x20, &c6b, "main", NULL); g2 = add(0x21, &c6b, "guest", t2); + memcpy(wifi.ssid, "main", 4); wifi.ssid_len = 4; + avoid_unlink(&wifi, NULL); + assert(!t1->linked && !g1->linked && !t2->linked && !g2->linked); + /* The avoided network as the current one keeps nothing but the joined BSS's set. */ + reset("guest"); + t1 = add(0x10, &c6a, "guest", NULL); t2 = add(0x20, &c6b, "guest", NULL); + wifi.connecting = true; memcpy(wifi.bssid, t1->bssid, ETH_ALEN); + memcpy(wifi.ssid, "guest", 5); wifi.ssid_len = 5; + avoid_unlink(&wifi, wifi.bssid); + assert(t1->linked && !t2->linked); + puts("PASS current network: its sets stay while connecting or connected, unless it is the avoided one"); + + /* The window over: nothing is unlinked. */ + reset("guest"); + t1 = add(0x10, &c6a, "guest", NULL); + jiffies += 1000; + avoid_unlink(&wifi, NULL); + assert(t1->linked && !wifi.avoid_valid && linked() == 1); + puts("PASS window: after it ends nothing is unlinked"); + return 0; +} +''' + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--root", default=str(Path(__file__).resolve().parents[2])) + ap.add_argument("--cc", default="cc") + ap.add_argument("--negative-control", action="store_true", + help="put back the loop that re-reads a passed-over entry: the first case must fail") + args = ap.parse_args() + source = (Path(args.root) / SRC).read_text() + parts = [block(source, "bool", "avoided"), block(source, "struct", "avoid_find"), + block(source, "bool", "avoid_keep_bss"), block(source, "bool", "avoid_keep_set"), + block(source, "void", "avoid_find_one"), block(source, "void", "avoid_unlink")] + if args.negative_control: + fixed = ("\t\tif (find.count < count)\n\t\t\tcontinue;\n" + "\t\t/* Not unlinked: pass it over and look up the entry after it. */\n" + "\t\tfind.skip++;\n\t\tfind.count = 0;\n" + "\t\tcfg80211_bss_iter(wifi->wiphy, NULL, avoid_find_one, &find);\n") + if fixed not in parts[-1]: + raise RuntimeError("negative control: the pass-over walk is not in avoid_unlink()") + parts[-1] = parts[-1].replace(fixed, "\t\tif (find.count >= count)\n\t\t\tfind.skip++;\n") + with tempfile.TemporaryDirectory() as tmp: + c = Path(tmp) / "avoid.c" + c.write_text(PRELUDE + "\n\n".join(parts) + "\n" + TESTS) + exe = Path(tmp) / "avoid" + subprocess.run([args.cc, "-std=gnu11", "-O1", "-g", "-Wall", "-Wextra", "-Werror", + "-Wno-unused-parameter", "-fsanitize=address,undefined", str(c), "-o", str(exe)], + check=True) + rc = subprocess.run([str(exe)], timeout=60).returncode + if rc: + print(f"FAIL: the helper broke a case above (exit {rc})") + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/tools/asahi/centauri-wifi-pm-tests.py b/tools/asahi/centauri-wifi-pm-tests.py index 56a259fd9c1ae7..4ae904a36d2056 100644 --- a/tools/asahi/centauri-wifi-pm-tests.py +++ b/tools/asahi/centauri-wifi-pm-tests.py @@ -17,7 +17,7 @@ def block(source, name): - match = re.search(r"^(?:static )?(?:int|void) " + re.escape(name) + r"\(", source, re.M) + match = re.search(r"^(?:static )?(?:int|void|bool) " + re.escape(name) + r"\(", source, re.M) if not match: raise RuntimeError(f"Production function {name} missing") brace = source.index("{", match.start()) @@ -39,25 +39,32 @@ def block(source, name): typedef uint16_t u16; typedef uint32_t u32; #define BIT(n) (1U << (n)) +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #define READ_ONCE(x) (x) #define WRITE_ONCE(x, v) ((x) = (v)) #define GFP_KERNEL 0 -#define BUFFER_SIZE 128 +#define BUFFER_SIZE 256 +#define DATA_TX_SLOTS 8 +#define CEN_HOST_EVENTS_LEGACY 85 +#define CEN_HOST_EVENTS_FULL 91 #define TX_BUFFER 2048 #define TR_BASE 0 #define dma_rmb() ((void)0) #define dma_wmb() ((void)0) #define dev_err(...) ((void)0) #define dev_dbg(...) ((void)0) +#define lockdep_assert_held(l) assert(*(l)) #define msecs_to_jiffies(x) (x) #define time_before(a, b) ((long)((a) - (b)) < 0) #define time_after_eq(a, b) (!time_before(a, b)) static unsigned long jiffies; struct centauri_t6050_wifi; -struct centauri_t6050 { struct centauri_t6050_wifi *wifi; bool removing; }; +struct pci_dev { int dev; }; +struct centauri_t6050 { struct pci_dev *pdev; struct centauri_t6050_wifi *wifi; bool removing; }; struct wiphy { struct centauri_t6050_wifi *wifi; }; struct net_device { int unused; }; struct cfg80211_wowlan { bool any; }; +struct regulatory_request { char alpha2[3]; }; ''' STUBS = r''' @@ -66,7 +73,14 @@ def block(source, name): struct { u8 *window, *bar; uint64_t window_dma; } a; int lock, connect_work, link_work, data_tx_queue; bool command_failed, stopping, connect_abort, disconnect_pending, connecting, connected; - bool reply_valid, pm_prepared; + bool reply_valid, pm_prepared, pm_wowlan_armed; + bool data_tx_busy[DATA_TX_SLOTS]; + bool host_events_fallback_logged; + bool configured, tx_paused, transport_paused, host_sleep_sent, transport_sleep_sent; + bool regulatory_deferred, station_signal_valid, disconnect_event; + u8 country_deferred[3], hw_channels[4]; + int hw_channels_blob, data_rings_open; + struct net_device *netdev; u16 command_head, sequence, reply_capture, reply_sequence, reply_status; u32 reply_command; u8 *reply_buffer; @@ -74,8 +88,15 @@ def block(source, name): struct centauri_wifi_disconnect_receipt pm_disconnect; }; static const u16 ring_size[5] = {0, 64}; -static unsigned int doorbells, drains, notifications, consumer; -static u16 firmware_status; +static unsigned int doorbells, drains, notifications, consumer, tx_drain_rounds, info_logs; +static unsigned int reads, index_reads, reports, applies; +static bool rtnl_held, fail_firmware_report; +#define ASSERT_RTNL() assert(rtnl_held) +static void dev_info(const void *dev, const char *fmt, ...) +{ (void)dev; (void)fmt; info_logs++; } +static u16 firmware_status, last_cmd6_tlv280_len, mock_fw_transient_status; +static u32 mock_reply_command = 131073; +static u8 mock_fw_max_events, last_cmd6_tlv280_count; static bool async_reply, async_event, wrong_reply; static bool *submission_probe; static bool private_access_forbidden; @@ -86,28 +107,67 @@ def block(source, name): static void *wiphy_priv(struct wiphy *wiphy) { assert(!private_access_forbidden); return &wiphy->wifi; } static void usleep_range(int a, int b) { (void)a; (void)b; jiffies += 100; } -static unsigned int readl(void *address) { (void)address; return transport_mode == LOST ? 0 : 2; } +static unsigned int readl(void *address) +{ (void)address; reads++; return transport_mode == LOST ? 0 : 2; } static void writel(unsigned int value, void *address) { (void)value; (void)address; doorbells++; } static u16 index_read(struct centauri_t6050_wifi *wifi, int array, int index) -{ assert(wifi->lock); (void)array; (void)index; return consumer; } +{ assert(wifi->lock); (void)array; (void)index; index_reads++; return consumer; } static void index_write(struct centauri_t6050_wifi *wifi, int array, int index, u16 value) { assert(wifi->lock); (void)array; (void)index; (void)value; if (submission_probe) assert(*submission_probe); } static void put_unaligned_le16(u16 value, void *p) { memcpy(p, &value, 2); } static void put_unaligned_le32(u32 value, void *p) { memcpy(p, &value, 4); } static void put_unaligned_le64(uint64_t value, void *p) { memcpy(p, &value, 8); } +static void append_tlv(u8 *buffer, size_t *size, u16 tag, const void *value, size_t len) +{ + put_unaligned_le16(tag, buffer + *size); + put_unaligned_le16(len, buffer + *size + 2); + memcpy(buffer + *size + 4, value, len); + *size += 4 + len; + if (tag == 280) { + last_cmd6_tlv280_len = len; + last_cmd6_tlv280_count = len ? ((const u8 *)value)[0] : 0; + } +} +static int command_reply(struct centauri_t6050_wifi *wifi, u32 id, + const void *payload, size_t size, void *reply, + size_t *reply_size, bool *submitted); +static int command(struct centauri_t6050_wifi *wifi, u32 id, const void *payload, + size_t size) +{ + return command_reply(wifi, id, payload, size, NULL, NULL, NULL); +} static void command_fault(struct centauri_t6050_wifi *wifi) { wifi->command_failed = true; } static void drain(struct centauri_t6050_wifi *wifi) { assert(wifi->lock); drains++; + if (tx_drain_rounds) { + tx_drain_rounds--; + if (!tx_drain_rounds) + memset(wifi->data_tx_busy, 0, sizeof(wifi->data_tx_busy)); + } if (transport_mode != REPLY) return; if (!wifi->reply_valid) { wifi->reply_valid = true; wifi->reply_sequence = wifi->reply_capture + wrong_reply; - wifi->reply_command = 131073 | (async_reply ? BIT(30) : 0); - wifi->reply_status = firmware_status; + const u8 *packet = wifi->a.window + TX_BUFFER + + ((wifi->command_head + ring_size[1] - 1) % ring_size[1]) * BUFFER_SIZE; + u32 command_id; + memcpy(&command_id, packet + 0x14, sizeof(command_id)); + wifi->reply_command = (mock_reply_command ? mock_reply_command : command_id) | + (async_reply ? BIT(30) : 0); + if (mock_reply_command == 6 && mock_fw_transient_status) { + wifi->reply_status = mock_fw_transient_status; + mock_fw_transient_status = 0; + } else if (mock_reply_command == 6 && mock_fw_max_events && + (last_cmd6_tlv280_len > 1 + mock_fw_max_events || + last_cmd6_tlv280_count > mock_fw_max_events)) { + wifi->reply_status = 1; + } else { + wifi->reply_status = firmware_status; + } } else if (async_event) { wifi->disconnect_pending = false; } @@ -121,26 +181,46 @@ def block(source, name): static void cfg80211_disconnected(struct net_device *netdev, u16 reason, void *ie, int size, bool local, int flags) { (void)netdev; (void)reason; (void)ie; (void)size; (void)local; (void)flags; notifications++; } +static int alpha_transport_state(struct centauri_t6050_wifi *wifi, bool asleep) +{ assert(wifi->lock && !asleep); return 0; } +static bool netif_running(struct net_device *netdev) { (void)netdev; return false; } +static void netif_wake_queue(struct net_device *netdev) { (void)netdev; } +static void schedule_work(int *work) { (void)work; } +static void firmware_report(struct centauri_t6050_wifi *wifi, u32 id, u8 *buffer, int *blob) +{ + assert(wifi->lock && rtnl_held && id == 19); + assert(buffer == wifi->hw_channels && blob == &wifi->hw_channels_blob); + reports++; + if (fail_firmware_report) + command_fault(wifi); +} +static void channels_apply(struct centauri_t6050_wifi *wifi) +{ assert(wifi->lock && rtnl_held); applies++; } ''' TESTS = r''' +static struct pci_dev pdev; static struct centauri_t6050 control; static struct centauri_t6050_wifi wifi; static struct wiphy wiphy; static struct net_device netdev; -static u8 window[16384], bar[8192]; +static u8 window[32768], bar[8192]; static void reset(void) { memset(&wifi, 0, sizeof(wifi)); memset(window, 0, sizeof(window)); - control = (struct centauri_t6050) { .wifi = &wifi }; + control = (struct centauri_t6050) { .pdev = &pdev, .wifi = &wifi }; wifi.control = &control; wifi.a.window = window; wifi.a.bar = bar; wifi.connected = true; wiphy.wifi = &wifi; - doorbells = drains = notifications = consumer = 0; - firmware_status = 0; + doorbells = drains = notifications = consumer = tx_drain_rounds = info_logs = 0; + reads = index_reads = reports = applies = 0; + rtnl_held = fail_firmware_report = false; + firmware_status = last_cmd6_tlv280_len = mock_fw_transient_status = 0; + mock_reply_command = 131073; + mock_fw_max_events = last_cmd6_tlv280_count = 0; async_reply = async_event = wrong_reply = false; transport_mode = REPLY; jiffies = 0; @@ -181,19 +261,93 @@ def block(source, name): } } +static void test_host_sleep_gate(void) +{ + bool published = true; + + reset(); + wifi.host_sleep_sent = true; + mutex_lock(&wifi.lock); + assert(command_reply(&wifi, 9, NULL, 0, NULL, NULL, &published) == -EHOSTDOWN); + mutex_unlock(&wifi.lock); + assert(!published && !index_reads && !doorbells && !drains && !reads); + assert(!wifi.sequence && !wifi.command_failed); +} + +static void test_deferred_regulatory(void) +{ + struct regulatory_request us = { .alpha2 = "US" }; + struct regulatory_request ca = { .alpha2 = "CA" }; + struct regulatory_request world = { .alpha2 = "00" }; + + reset(); + wifi.configured = true; + wifi.host_sleep_sent = wifi.transport_sleep_sent = true; + mock_reply_command = 0; + rtnl_held = true; + wifi_regulatory(&wiphy, &world); + wifi_regulatory(&wiphy, &ca); + wifi_regulatory(&wiphy, &us); + wifi_regulatory(&wiphy, &world); + assert(!index_reads && !doorbells && !drains && !reads && !reports && !applies && !wifi.lock); + assert(wifi.regulatory_deferred && !memcmp(wifi.country_deferred, "US\1", 3)); + + mutex_lock(&wifi.lock); + firmware_status = 1; + assert(alpha_resume_locked(&wifi) == -EREMOTEIO); + assert(wifi.host_sleep_sent && wifi.regulatory_deferred && !reports && !applies); + doorbells = 0; + firmware_status = 0; + assert(alpha_resume_locked(&wifi) == 0); + assert(!wifi.host_sleep_sent && !wifi.regulatory_deferred && !wifi.country_deferred[0]); + assert(doorbells == 2 && reports == 1 && applies == 1); + assert(!memcmp(wifi.a.window + TX_BUFFER + (wifi.command_head - 1) * BUFFER_SIZE + 24, + "US\1", 3)); + assert(alpha_resume_locked(&wifi) == 0); + assert(doorbells == 2 && reports == 1 && applies == 1); + mutex_unlock(&wifi.lock); + + wifi_regulatory(&wiphy, &ca); + assert(doorbells == 3 && reports == 2 && applies == 2); + wifi_regulatory(&wiphy, &world); + assert(doorbells == 3 && reports == 2 && applies == 3); + + wifi.host_sleep_sent = true; + wifi_regulatory(&wiphy, &world); + assert(wifi.regulatory_deferred && !wifi.country_deferred[0]); + mutex_lock(&wifi.lock); + assert(alpha_resume_locked(&wifi) == 0); + mutex_unlock(&wifi.lock); + assert(doorbells == 4 && reports == 2 && applies == 4); + + wifi.host_sleep_sent = wifi.transport_paused = wifi.tx_paused = true; + wifi_regulatory(&wiphy, &us); + fail_firmware_report = true; + mutex_lock(&wifi.lock); + assert(alpha_resume_locked(&wifi) == -EIO); + mutex_unlock(&wifi.lock); + assert(wifi.command_failed && wifi.transport_paused && wifi.tx_paused); +} + int main(void) { test_registered_pm_contract(); + test_host_sleep_gate(); + test_deferred_regulatory(); prepare(); assert(!wifi.pm_disconnect.seen); expect_error(0); /* Missing transaction remains missing. */ struct cfg80211_wowlan wowlan = {}; + assert(!centauri_t6050_wifi_wowlan_armed(&control)); assert(call_registered_suspend(&wiphy, &wowlan) == 1); + assert(!centauri_t6050_wifi_wowlan_armed(&control)); wowlan.any = true; assert(call_registered_suspend(&wiphy, &wowlan) == 0); - assert(!doorbells && !wifi.pm_disconnect.seen); + assert(centauri_t6050_wifi_wowlan_armed(&control)); + assert(!doorbells && !wifi.pm_disconnect.seen && !centauri_t6050_wifi_pm_disconnected(&control)); wifi.connected = false; assert(call_registered_suspend(&wiphy, &wowlan) == 1); + assert(!centauri_t6050_wifi_wowlan_armed(&control)); wifi.connected = true; wifi.connecting = true; assert(call_registered_suspend(&wiphy, &wowlan) == 1); @@ -204,8 +358,12 @@ def block(source, name): assert(!doorbells && !wifi.pm_disconnect.seen); firmware_status = 326; + wifi.data_tx_busy[0] = true; + tx_drain_rounds = 2; assert(disconnect() == 0); + assert(!data_tx_in_flight(&wifi)); assert(wifi.pm_disconnect.seen && wifi.pm_disconnect.submitted); + assert(centauri_t6050_wifi_pm_disconnected(&control)); assert(wifi.pm_disconnect.replied && wifi.pm_disconnect.status == 326); assert(wifi.pm_disconnect.command_error == -EREMOTEIO); expect_error(0); /* Keep the existing helper normalization. */ @@ -303,6 +461,66 @@ def block(source, name): mutex_unlock(&wifi.lock); assert(published); submission_probe = NULL; + + /* Failed keep-alive unwind marks Wi-Fi failed so teardown skips ACIPC. */ + prepare(); + wifi.data_tx_busy[0] = true; + centauri_t6050_wifi_mark_failed(&control); + assert(wifi.stopping && wifi.command_failed); + assert(disconnect() == 0); + assert(wifi.pm_disconnect.stopping_skip && !doorbells && !drains); + + /* + * Sleep sends legacy 86-byte TLV 280 without touching fallback state; + * legacy firmware refuses 91 events on wake (-EREMOTEIO), falls back to 85, + * and logs the fallback once via dev_info. + */ + prepare(); + mock_reply_command = 6; + mock_fw_max_events = 85; + mutex_lock(&wifi.lock); + assert(alpha_host_power(&wifi, true) == 0); + assert(!info_logs && last_cmd6_tlv280_len == 86 && + last_cmd6_tlv280_count == 9 && doorbells == 1); + assert(alpha_host_power(&wifi, false) == 0); + assert(info_logs == 1 && wifi.host_events_fallback_logged && + last_cmd6_tlv280_len == 86 && last_cmd6_tlv280_count == 85 && + doorbells == 3); + /* Subsequent wakes fall back without repeating the one-shot dev_info. */ + assert(alpha_host_power(&wifi, true) == 0); + assert(last_cmd6_tlv280_len == 86 && last_cmd6_tlv280_count == 9 && doorbells == 4); + assert(alpha_host_power(&wifi, false) == 0); + assert(info_logs == 1 && last_cmd6_tlv280_len == 86 && + last_cmd6_tlv280_count == 85 && doorbells == 6); + mutex_unlock(&wifi.lock); + + /* Transient unrelated -EREMOTEIO on wake does not permanently pin 85 events. */ + prepare(); + mock_reply_command = 6; + mock_fw_max_events = 91; + mock_fw_transient_status = 777; + mutex_lock(&wifi.lock); + assert(alpha_host_power(&wifi, false) == 0); + assert(info_logs == 1 && last_cmd6_tlv280_len == 86 && + last_cmd6_tlv280_count == 85 && doorbells == 2); + assert(alpha_host_power(&wifi, false) == 0); + assert(info_logs == 1 && last_cmd6_tlv280_len == 92 && + last_cmd6_tlv280_count == 91 && doorbells == 3); + mutex_unlock(&wifi.lock); + + /* Full-mask firmware keeps 86-byte sleep TLV and accepts 91 events on wake. */ + prepare(); + mock_reply_command = 6; + mock_fw_max_events = 91; + mutex_lock(&wifi.lock); + assert(alpha_host_power(&wifi, true) == 0); + assert(!info_logs && last_cmd6_tlv280_len == 86 && + last_cmd6_tlv280_count == 9 && doorbells == 1); + assert(alpha_host_power(&wifi, false) == 0); + assert(!info_logs && last_cmd6_tlv280_len == 92 && + last_cmd6_tlv280_count == 91 && doorbells == 2); + mutex_unlock(&wifi.lock); + puts("PASS: production disconnect/transport/PM callbacks and first-error retention"); return 0; } @@ -322,9 +540,13 @@ def main(): receipt = re.search(r"struct centauri_wifi_disconnect_receipt \{.*?\n\};", source, re.S) if not receipt: raise RuntimeError("Production receipt structure missing") - names = ["command_reply", "wait_disconnect", "wifi_disconnect", + names = ["command_reply", "wait_disconnect", "data_tx_in_flight", + "drain_tx_in_flight", "wifi_disconnect", "centauri_t6050_wifi_pm_prepare", "centauri_t6050_wifi_pm_error", - "centauri_t6050_wifi_pm_complete", "wifi_suspend"] + "centauri_t6050_wifi_pm_disconnected", "centauri_t6050_wifi_wowlan_armed", + "centauri_t6050_wifi_mark_failed", "centauri_t6050_wifi_pm_complete", + "alpha_host_power_send", "alpha_host_power", "country_set", + "alpha_resume_locked", "wifi_regulatory", "wifi_suspend"] has_resume = bool(re.search(r"^static int wifi_resume\(", source, re.M)) if has_resume: names.append("wifi_resume") @@ -378,12 +600,30 @@ def main(): ("stale-reply", "receipt.replied = receipt.submitted && (!ret || ret == -EREMOTEIO);", "receipt.replied = true;"), ("wowlan-ignores-trigger", "wowlan->any && ", ""), + ("sleep-uses-full-len", + "return alpha_host_power_send(wifi, true, CEN_HOST_EVENTS_LEGACY);", + "return alpha_host_power_send(wifi, true, CEN_HOST_EVENTS_FULL);"), + ("silent-fallback-log", + "if (!ret && !wifi->host_events_fallback_logged)", + "if (false && !ret && !wifi->host_events_fallback_logged)"), + ("host-sleep-command", "\tif (wifi->host_sleep_sent)\n\t\treturn -EHOSTDOWN;\n", ""), + ("regulatory-in-sleep", "if (wifi->host_sleep_sent) {\n\t\t/* Keep the last", + "if (false) {\n\t\t/* Keep the last"), + ("lost-deferred-country", "country_set(wifi, wifi->country_deferred);", "(void)wifi;"), + ("ignored-regulatory-transport-loss", + "if (wifi->command_failed)\n\t\t\treturn -EIO;", "if (false)\n\t\t\treturn -EIO;"), ] failures = { 'lost-suspend-error': 'centauri_t6050_wifi_pm_error(&control) == expected', 'overwritten-first-error': 'wifi.pm_disconnect.status == 777', 'stale-reply': '!wifi.pm_disconnect.submitted && !wifi.pm_disconnect.replied', 'wowlan-ignores-trigger': 'call_registered_suspend(&wiphy, &wowlan) == 1', + 'sleep-uses-full-len': 'alpha_host_power(&wifi, true) == 0', + 'silent-fallback-log': 'info_logs == 1', + 'host-sleep-command': 'command_reply(&wifi, 9, NULL, 0, NULL, NULL, &published) == -EHOSTDOWN', + 'regulatory-in-sleep': '!index_reads && !doorbells && !drains && !reads && !reports && !applies', + 'lost-deferred-country': 'doorbells == 2 && reports == 1 && applies == 1', + 'ignored-regulatory-transport-loss': 'alpha_resume_locked(&wifi) == -EIO', } for name, before, after in negative_controls if args.negative_controls else []: if before not in production: diff --git a/tools/asahi/clpc-gpu-demand-tests.py b/tools/asahi/clpc-gpu-demand-tests.py index ff36eb19c162cc..6e2650f1fd95f5 100644 --- a/tools/asahi/clpc-gpu-demand-tests.py +++ b/tools/asahi/clpc-gpu-demand-tests.py @@ -20,17 +20,217 @@ def item(text, signature): return text[start:end] +def test_g17_busy_share(): + """Compile and run production g17 BusyShare (power.rs) with negative controls. + + Returns the (t_ms, permille) reports emitted for the long-command-beside- + light-compositor scenario, and the (t_ms, permille or -1 for no report) + samples of a new burst after idle, so the C CLPC harness drives + apple_clpc_sample() with them end-to-end. + """ + power = (ROOT / 'drivers/gpu/drm/asahi/g17/power.rs').read_text() + consts = '\n'.join( + re.search(r'^pub\(super\) const ' + name + r': u64 = [^\n]+$', power, re.M).group(0) + for name in ('BUSY_WINDOW_NS', 'BUSY_WINDOW_MAX_NS', 'BUSY_LONG_COMMAND_NS')) + struct_def = item(power, 'pub(super) struct BusyShare {') + impl_def = item(power, 'impl BusyShare {') + prod = f'{consts}\n{struct_def}\n{impl_def}\n' + + harness = r''' +#![allow(dead_code)] +mod usage { + pub const NUM_ENGINES: usize = 3; +} +mod power { +''' + prod + r''' +} +use power::{BusyShare, BUSY_LONG_COMMAND_NS}; + +fn main() { + const MS: u64 = 1_000_000; + // Scenario 1: long 500 ms compute job running next to a light compositor. + // Light compositor runs 10 ms per 200 ms window (50 permille -> level 0). + let mut s = BusyShare::new(); + assert_eq!(s.sample(1000 * MS, [0, 0, 0], [0, 0, 0]), None); + let r0 = s.sample(1200 * MS, [2 * MS, 10 * MS, 0], [0, 0, 0]).unwrap(); + assert_eq!(r0, 50); + assert!(s.below_top()); + // Compute job (500 ms) starts at t=1650 ms (after CLPC has dropped to level 0 + // following its 400 ms down-step hold); compositor submits at t=1810 ms (210 ms + // after a 1600 ms window start). Must immediately report 1000 while still running. + let r1 = s.sample(1400 * MS, [4 * MS, 20 * MS, 0], [0, 0, 0]).unwrap(); + assert_eq!(r1, 50); + let r2 = s.sample(1600 * MS, [6 * MS, 30 * MS, 0], [0, 0, 0]).unwrap(); + assert_eq!(r2, 50); + let r3 = s.sample(1810 * MS, [8 * MS, 40 * MS, 0], [0, 0, 1650 * MS]).unwrap(); + assert_eq!(r3, 1000, "long in-flight compute next to light compositor must lift to 1000"); + assert!(!s.below_top()); + // Still running across the next 200 ms window at t=2010 ms: holds 1000. + let r4 = s.sample(2010 * MS, [10 * MS, 50 * MS, 0], [0, 0, 1650 * MS]).unwrap(); + assert_eq!(r4, 1000); + // Job retires at t=2150 ms (+500 ms retired). At t=2210 ms only the 140 ms in + // [2010, 2150] counts (700 permille), proving zero double-counting. + let r5 = s.sample(2210 * MS, [12 * MS, 60 * MS, 500 * MS], [0, 0, 0]).unwrap(); + assert_eq!(r5, 700, "post-retirement window must not double-count prior in-flight time"); + // Next window returns cleanly to compositor's 50 permille. + let r6 = s.sample(2410 * MS, [14 * MS, 70 * MS, 500 * MS], [0, 0, 0]).unwrap(); + assert_eq!(r6, 50); + + // Scenario 2: long command starting late in a window lifts mid-window at 50 ms. + let mut late = BusyShare::new(); + assert_eq!(late.sample(1000 * MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(late.sample(1200 * MS, [0, 10 * MS, 0], [0, 0, 0]), Some(50)); + assert_eq!(late.sample(1410 * MS, [0, 20 * MS, 0], [0, 0, 1390 * MS]), Some(95)); + assert!(late.below_top()); + assert_eq!(late.sample(1440 * MS, [0, 22 * MS, 0], [0, 0, 1390 * MS]), Some(1000)); + assert!(!late.below_top()); + assert_eq!(late.sample(1460 * MS, [0, 23 * MS, 0], [0, 0, 1390 * MS]), None); + assert_eq!(late.sample(1610 * MS, [0, 30 * MS, 100 * MS], [0, 0, 0]), Some(400)); + + // Scenario 3: solo long command driven by recheck_delay_for reaches 1000 and stops. + let mut solo = BusyShare::new(); + assert_eq!(solo.sample(1000 * MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(solo.sample(1200 * MS, [0, 10 * MS, 0], [0, 0, 0]), Some(50)); + let mut t = 1222 * MS; + let start = 1210 * MS; + let mut lifted = false; + let mut rechecks = 0; + for _ in 0..8 { + if let Some(p) = solo.sample(t, [0, 10 * MS, 0], [0, 0, start]) { + assert_eq!(p, 1000); + lifted = true; + break; + } + let delay = BusyShare::recheck_delay_for(t, start).unwrap(); + assert!(delay <= BUSY_LONG_COMMAND_NS); + t += delay; + rechecks += 1; + } + // One wake-up at the long-command age, not a train of short ones. + assert!(lifted && !solo.below_top() && t == start + BUSY_LONG_COMMAND_NS && rechecks == 1); + + // Scenario 4: short straddling command (no double count), multi-engine max, >2 s gaps. + let mut misc = BusyShare::new(); + assert_eq!(misc.sample(1000 * MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(misc.sample(1200 * MS, [0, 0, 0], [0, 0, 1170 * MS]), Some(150)); + assert_eq!(misc.sample(1400 * MS, [0, 0, 40 * MS], [0, 0, 0]), Some(50)); + assert_eq!(misc.sample(1600 * MS, [0, 120 * MS, 150 * MS], [0, 0, 0]), Some(600)); + assert_eq!(misc.sample(5000 * MS, [0, 120 * MS, 150 * MS], [0, 0, 5000 * MS]), None); + assert_eq!(misc.sample(8000 * MS, [0, 120 * MS, 150 * MS], [0, 0, 5000 * MS]), Some(1000)); + + // Scenario 5: steady 600 permille work until 1400 ms, idle (CLPC cleared), then a + // new burst at 2000 ms. Closing [1300, 2000] would report a diluted 85 permille + // (60 ms in 700 ms); the first submission re-baselines instead and nothing is + // reported until a fresh 200 ms window of the new burst completes. + let mut burst = BusyShare::new(); + assert_eq!(burst.sample(900 * MS, [0, 0, 0], [0, 0, 0]), None); + let mut idle_events = Vec::new(); + for (t, frag) in [(1100, 120), (1300, 240)] { + let p = burst.sample(t * MS, [0, frag * MS, 0], [0, 0, 0]); + assert_eq!(p, Some(600)); + idle_events.push((t, p)); + } + burst.clear_active(); + assert!(!burst.below_top()); + for (t, frag) in [(2000, 300), (2048, 328), (2100, 360), (2148, 388), (2196, 417), (2200, 420)] { + let p = burst.sample(t * MS, [0, frag * MS, 0], [0, 0, 0]); + assert_eq!(p, if t < 2200 { None } else { Some(600) }, + "new burst after idle must not report a window diluted by the idle gap"); + idle_events.push((t, p)); + } + assert!(burst.below_top()); + + println!("EVENTS:1200={r0},1400={r1},1600={r2},1810={r3},2010={r4},2210={r5},2410={r6}"); + let idle: Vec = + idle_events.iter().map(|(t, p)| format!("{t}={}", p.map_or(-1, i64::from))).collect(); + println!("IDLE:{}", idle.join(",")); +} +''' + rustc = os.environ.get('RUSTC', 'rustc') + events = idle_events = None + with tempfile.TemporaryDirectory(prefix='asahi-g17-busy-') as tmp: + root = Path(tmp) + for name, text in [ + ('fixed', harness), + ('g17-ignore-in-flight', + harness.replace('let long_in_flight = Self::is_long_in_flight(now_ns, oldest_in_flight);', + 'let _ = oldest_in_flight; let oldest_in_flight = [0; crate::usage::NUM_ENGINES];\n' + ' let long_in_flight = Self::is_long_in_flight(now_ns, oldest_in_flight);')), + ('g17-double-count-in-flight', + harness.replace('let busy = delta.saturating_add(age).saturating_sub(prev_age);', + 'let _ = prev_age; let busy = delta.saturating_add(age);')), + ('g17-no-early-lift', + harness.replace('if self.below_top && long_in_flight {', + 'if false && self.below_top && long_in_flight {')), + ('g17-long-idle-reports', + harness.replace('if elapsed > BUSY_WINDOW_MAX_NS && !long_in_flight {', + 'if false && elapsed > BUSY_WINDOW_MAX_NS && !long_in_flight {')), + ('g17-idle-keeps-window', + harness.replace('self.start_ns = None;\n self.in_flight_ns = [0; crate::usage::NUM_ENGINES];\n' + ' self.below_top = false;', + 'self.below_top = false;')), + ]: + assert name == 'fixed' or text != harness, 'stale mutation: ' + name + src = root / (name + '.rs') + src.write_text(text) + binary = src.with_suffix('') + subprocess.run([rustc, '--edition=2021', '-Dwarnings', str(src), '-o', str(binary)], + check=True) + run = subprocess.run([str(binary)], capture_output=True, text=True) + if name == 'fixed': + assert run.returncode == 0, run.stderr + lines = run.stdout.strip().splitlines() + assert len(lines) == 2 and lines[0].startswith('EVENTS:') \ + and lines[1].startswith('IDLE:'), lines + events = [tuple(int(x) for x in pair.split('=')) + for pair in lines[0].removeprefix('EVENTS:').split(',')] + idle_events = [tuple(int(x) for x in pair.split('=')) + for pair in lines[1].removeprefix('IDLE:').split(',')] + print('PASS: g17 BusyShare (in-flight long command, early lift, solo recheck, ' + 'non-double-counting, new burst after idle)') + else: + assert run.returncode != 0, name + print('PASS negative control:', name) + return events, idle_events + + def main(): + g17_events, g17_idle_events = test_g17_busy_share() source = (ROOT / 'drivers/soc/apple/clpc.c').read_text() header = (ROOT / 'include/linux/soc/apple/pmc.h').read_text() rail_shift = re.search(r'^#define APPLE_PMC_RAIL_SHIFT\(rail\).*$', header, re.M).group(0) dense_samples = re.search(r'^#define APPLE_CLPC_GPU_DENSE_SAMPLES\s.*$', source, re.M).group(0) reasons = '\n'.join(re.findall(r'^#define APPLE_CLPC_REASON_\w+\s.*$', source, re.M)) + gpu_down = re.search(r'^#define APPLE_CLPC_GPU_DOWN_MS\s.*$', source, re.M).group(0) types = '\n'.join(item(source, s) + ';' for s in [ 'struct apple_clpc_hw {', 'struct apple_clpc_vote {']) tables = '\n'.join(item(source, 'static const struct apple_clpc_hw ' + n + ' =') + ';' for n in ['apple_clpc_hw_t8132', 'apple_clpc_hw_t8140', - 'apple_clpc_hw_t6040', 'apple_clpc_hw_t6041']) + 'apple_clpc_hw_t6040', 'apple_clpc_hw_t6041', + 'apple_clpc_hw_t6050']) + # When t6041.dtsi supplies the GPU busy-share properties, parse and test them directly; + # otherwise exercise the DT parsers and ladder against the reference values. + dts = (ROOT / 'arch/arm64/boot/dts/apple/t6041.dtsi').read_text() + clpc_node = item(dts, '&clpc {') + + def cells(name): + match = re.search(r'\s' + re.escape(name) + r'\s*=\s*([^;]*);', clpc_node) + if not match: + return None + return [int(x, 0) for x in re.findall(r'0x[0-9a-fA-F]+|\d+', match.group(1))] + + dt_states = cells('apple,gpu-busy-memory-states') + dt_busy = cells('apple,gpu-busy-permille') + assert (dt_states is None) == (dt_busy is None) + gpu_states = dt_states or [1, 2, 4, 5, 0, 0, 0, 3] + gpu_busy = dt_busy or [160, 500, 800] + t6041_dt = ( + 'static const u32 t6041_gpu_states[] = {' + ', '.join(str(x) for x in gpu_states) + '};\n' + 'static const u32 t6041_gpu_busy[] = {' + ', '.join(str(x) for x in gpu_busy) + '};\n' + 'static const struct { unsigned long ms; unsigned int permille; } g17_long_events[] = {' + + ', '.join(f'{{{t}, {p}}}' for t, p in g17_events) + '};\n' + 'static const struct { unsigned long ms; int permille; } g17_idle_events[] = {' + + ', '.join(f'{{{t}, {p}}}' for t, p in g17_idle_events) + '};\n') methods = '\n'.join(item(source, s) for s in [ 'static unsigned int apple_clpc_vote(', 'static u32 apple_clpc_floor(', 'static bool apple_clpc_gpu_streaming(', @@ -38,6 +238,10 @@ def main(): 'static bool apple_clpc_gpu_dense(', 'static bool apple_clpc_gpu_limited(', 'static void apple_clpc_gpu_floor_count(', + 'static unsigned int apple_clpc_gpu_level(', + 'static int apple_clpc_dt_map(', + 'static int apple_clpc_dt_busy(', + 'static bool apple_clpc_dt_apply(', 'static bool apple_clpc_gpu_input_demand(', 'static bool apple_clpc_ane_input_demand(', 'static void apple_clpc_ane_cluster(', @@ -47,16 +251,21 @@ def main(): #include #include #include +#include #include typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; +typedef int atomic_t; +static void atomic_set(atomic_t *v, int i) { *v = i; } +struct device; #define APPLE_CLPC_LEVELS 4 #define APPLE_CLPC_HOLD_MS 32 #define APPLE_CLPC_SAMPLE_MS 4 #define APPLE_CLPC_GPU_BACKOFF_MS 100 #define HZ 1000 #define max(a,b) ((a) > (b) ? (a) : (b)) +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #define GENMASK(h,l) (((1u << ((h)-(l)+1))-1) << (l)) #define BIT(n) (1u << (n)) #define APPLE_PMC_RAIL_SHIFT(r) ((r)*8) @@ -64,11 +273,15 @@ def main(): #define time_after(a,b) ((long)((a)-(b)) > 0) #define time_before(a,b) ((long)((a)-(b)) < 0) #define msecs_to_jiffies(ms) (ms) -static int warned; +static int warned, dt_warned; #define dev_warn_once(d, ...) ((void)(d), warned++) +#define dev_warn(d, ...) ((void)(d), dt_warned++) enum apple_clpc_rail { APPLE_CLPC_DCS, APPLE_CLPC_SOC, APPLE_CLPC_RAILS }; ''' + types + r''' -struct apple_clpc_gpu { bool active; u64 sequence; }; +struct apple_clpc_gpu { + int lock; bool active; u64 sequence; + unsigned int busy; bool busy_valid; unsigned int level; unsigned long level_since; +}; struct apple_clpc_ane { int lock; bool active, pending; }; #define spin_lock_irqsave(l, f) ((void)(l), (f) = 0) #define spin_unlock_irqrestore(l, f) ((void)(l), (void)(f)) @@ -111,7 +324,11 @@ def main(): struct freq_qos_request ane_qos; unsigned int ane_qos_khz; unsigned long ane_until; + bool has_pmc; bool low_power; + unsigned int low_power_khz; + unsigned int low_power_mw; + atomic_t idle_armed; }; static unsigned long jiffies; static u64 ktime_get_mono_fast_ns(void) { return jiffies * 1000000ull; } @@ -135,12 +352,88 @@ def main(): static void apple_clpc_queue(struct apple_clpc *c, bool idle) { (void)c; queued_idle=idle; } #define READ_ONCE(x) (x) static void apple_clpc_profile_limit(struct apple_clpc *c) { (void)c; } -''' + dense_samples + '\n' + reasons + '\n' + tables + '\n' + methods + r''' +''' + dense_samples + '\n' + reasons + '\n' + gpu_down + '\n' + tables + '\n' + methods + '\n' + t6041_dt + r''' +// Apply DT GPU busy-share properties through the driver's parsers: the CPU map +// stays untouched, valid GPU states/thresholds populate the ladder, states +// above the compatible table's rail maximum are rejected, and any malformed +// optional ladder warns and falls back to the compatible's static table. +static struct apple_clpc_hw t6041_dt_hw; +static void t6041_from_dt(void) { + static const u8 cpu[2][4] = {{5, 5, 5, 5}, {3, 3, 3, 3}}, gpu[2][4] = {{1, 2, 4, 5}, {0, 0, 0, 3}}; + struct apple_clpc_hw out, bad = apple_clpc_hw_t6040; + u32 over_4bit[8] = {1, 2, 4, 5, 0, 0, 0, 16}; + u32 t6041_over_dcs[8] = {1, 2, 4, 7, 0, 0, 0, 3}; + u32 t6041_over_dcs6[8] = {1, 2, 4, 6, 0, 0, 0, 3}; + u32 t6041_over_soc[8] = {1, 2, 4, 5, 0, 0, 0, 4}; + u32 t6050_ok[8] = {1, 2, 4, 6, 0, 0, 0, 2}; + u32 t6050_over_dcs[8] = {1, 2, 4, 7, 0, 0, 0, 2}; + u32 t6050_over_soc[8] = {1, 2, 4, 6, 0, 0, 0, 3}; + u32 busy[3] = {500, 160, 800}; + + dt_warned = 0; + assert(apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &t6041_dt_hw, + t6041_gpu_states, ARRAY_SIZE(t6041_gpu_states), + t6041_gpu_busy, ARRAY_SIZE(t6041_gpu_busy))); + assert(dt_warned == 0); + for (int r = 0; r < 2; r++) + for (int l = 0; l < 4; l++) + assert(t6041_dt_hw.map[r][l] == cpu[r][l] && t6041_dt_hw.gpu_busy[r][l] == gpu[r][l]); + + // Direct parser bounds: 4-bit max, rail-specific compatible max, counts, thresholds. + assert(apple_clpc_dt_map(&bad, over_4bit, 8) == -EINVAL); + assert(apple_clpc_dt_map(&bad, over_4bit, 7) == -EINVAL); + assert(apple_clpc_dt_map(&bad, t6041_gpu_states, 8) == -EINVAL); // fabric 3 > T6040 max 2 + bad = apple_clpc_hw_t6041; + assert(apple_clpc_dt_map(&bad, t6041_over_dcs, 8) == -EINVAL); // DCS 7 > T6041 max 5 + assert(apple_clpc_dt_map(&bad, t6041_over_dcs6, 8) == -EINVAL); // DCS 6 > T6041 max 5 + assert(apple_clpc_dt_map(&bad, t6041_over_soc, 8) == -EINVAL); // fabric 4 > T6041 max 3 + // T6050 rail max uses max(map[rail][top], gpu[rail]): DCS 6 from gpu[DCS], fabric 2. + assert(apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6050, &out, + t6050_ok, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 0 && out.gpu_busy[APPLE_CLPC_DCS][3] == 6); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6050, &out, + t6050_over_dcs, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 1 && !memcmp(&out, &apple_clpc_hw_t6050, sizeof(out))); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6050, &out, + t6050_over_soc, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 2 && !memcmp(&out, &apple_clpc_hw_t6050, sizeof(out))); + + // Malformed optional DT properties warn and fall back to the static soc table unchanged. + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + t6041_over_dcs, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 3 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + t6041_over_soc, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 4 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + // Valid states paired with bad permille or missing partner must not leave partial ladder. + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + t6041_gpu_states, 8, busy, 3)); + assert(dt_warned == 5 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + t6041_gpu_states, 8, NULL, -EINVAL)); + assert(dt_warned == 6 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + NULL, -EINVAL, t6041_gpu_busy, 3)); + assert(dt_warned == 7 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + // Falling back keeps the compatible's full GPU floor even when a low busy share arrives. + { + struct apple_clpc_gpu g = {.active = true, .busy_valid = true, .busy = 100}; + struct apple_clpc c = {.hw = &out, .has_pmc = true, .agent = 1, .mask = 3, .gpu = &g}; + read_error = vote_error = 0; pmgr_status = 0xf0; pmp_floor = 0; jiffies = 2900; published = ~0u; + apple_clpc_sample(&c); + assert(published == 0x35 && c.last_reason == 2); + } + + assert(apple_clpc_dt_busy(&bad, busy, 3) == -EINVAL); + busy[0] = 160; busy[1] = 500; busy[2] = 1001; + assert(apple_clpc_dt_busy(&bad, busy, 3) == -EINVAL); + assert(apple_clpc_dt_busy(&bad, busy, 2) == -EINVAL); +} // T8140 ANE work holds its DRAM and fabric states while it runs, a request // shorter than one sample is still seen once, and the hold then expires. static void check_t8140_ane(void) { struct apple_clpc_ane ane={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.agent=1,.mask=3,.ane=&ane}; + struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.has_pmc=true,.agent=1,.mask=3,.ane=&ane}; c.ane_states[APPLE_CLPC_DCS]=c.hw->ane[APPLE_CLPC_DCS]; c.ane_states[APPLE_CLPC_SOC]=c.hw->ane[APPLE_CLPC_SOC]; read_error=vote_error=0; pmgr_status=0; pmp_floor=0; jiffies=1000; published=~0u; @@ -153,11 +446,29 @@ def main(): jiffies=1040; apple_clpc_sample(&c); assert(published==0 && queued_idle); } +// T6050 ANE work holds DCS 6 and fabric 2 while it runs (and keeps on-time +// idle sampling), sees a sub-sample request once, and releases after HOLD_MS. +static void check_t6050_ane(void) { + struct apple_clpc_ane ane={0}; + struct apple_clpc c={.hw=&apple_clpc_hw_t6050,.has_pmc=true,.agent=1,.mask=3,.ane=&ane}; + c.ane_states[APPLE_CLPC_DCS]=c.hw->ane[APPLE_CLPC_DCS]; + c.ane_states[APPLE_CLPC_SOC]=c.hw->ane[APPLE_CLPC_SOC]; + assert(c.hw->ane[APPLE_CLPC_DCS]==6 && c.hw->ane[APPLE_CLPC_SOC]==2 && c.hw->idle_on_time); + read_error=vote_error=0; pmgr_status=0; pmp_floor=0; jiffies=3000; published=~0u; + apple_clpc_sample(&c); assert(published==0 && c.last_reason==0); + ane.active=true; jiffies=3004; apple_clpc_sample(&c); + assert(published==0x26 && c.last_reason==32); + ane.active=false; ane.pending=true; jiffies=3008; apple_clpc_sample(&c); + assert(published==0x26 && c.last_reason==32 && !ane.pending); + jiffies=3012; apple_clpc_sample(&c); assert(published==0x26 && c.last_reason==16); + jiffies=3040; apple_clpc_sample(&c); assert(published==0 && c.last_reason==0 && queued_idle); +} + // T6040 ANE work also holds the second P cluster at its qualified frequency, // added on first use, for the vote hold after the last request, then drops it. static void check_t6040_ane(void) { struct apple_clpc_ane ane={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t6040,.agent=1,.mask=3,.ane=&ane}; + struct apple_clpc c={.hw=&apple_clpc_hw_t6040,.has_pmc=true,.agent=1,.mask=3,.ane=&ane}; c.ane_states[APPLE_CLPC_DCS]=c.hw->ane[APPLE_CLPC_DCS]; c.ane_states[APPLE_CLPC_SOC]=c.hw->ane[APPLE_CLPC_SOC]; c.ane_cpu=9; c.ane_cluster_khz=c.hw->ane_cluster_khz; @@ -172,11 +483,150 @@ def main(): ane.active=true; jiffies=2040; apple_clpc_sample(&c); assert(qos_adds==1 && qos_min==3756000); } +// DT GPU busy-share ladder: DCS 1, 2, 4 or 5 and fabric 0, 0, 0 or 3, split at +// 160, 500 and 800 permille. A higher level applies at once, a lower one at the +// first sample at least 400 ms after the last one that asked for the current +// level or more. A table without a non-zero top DCS state falls back to @map. +static void check_t6041_busy(void) { + struct apple_clpc_gpu gpu={0}; + struct apple_clpc c={.hw=&t6041_dt_hw,.has_pmc=true,.agent=1,.mask=3,.gpu=&gpu}; + struct apple_clpc_hw no_top = t6041_dt_hw; + assert(c.hw->gpu_busy_mid==160 && c.hw->gpu_busy_high==500 && c.hw->gpu_busy_top==800); + read_error=vote_error=0; pmgr_status=0xf0; pmp_floor=0; published=~0u; + // No share reported: the top of the ladder, as before the busy share. + gpu.active=true; jiffies=3000; apple_clpc_sample(&c); + assert(published==0x35 && c.last_reason==2 && gpu.level==3); + gpu.active=false; jiffies=3100; apple_clpc_sample(&c); assert(published==0); + // Below gpu_busy_mid: the lowest GPU state (after a long idle, at once). + gpu.active=true; gpu.busy_valid=true; gpu.busy=100; jiffies=3500; + apple_clpc_sample(&c); assert(published==0x01 && c.last_reason==2 && gpu.level==0); + // Between the thresholds, going up: each level applies at the next sample. + gpu.busy=160; jiffies=3504; apple_clpc_sample(&c); assert(published==0x02 && gpu.level==1); + gpu.busy=499; jiffies=3508; apple_clpc_sample(&c); assert(published==0x02 && gpu.level==1); + gpu.busy=500; jiffies=3512; apple_clpc_sample(&c); assert(published==0x04 && gpu.level==2); + gpu.busy=799; jiffies=3516; apple_clpc_sample(&c); assert(published==0x04 && gpu.level==2); + gpu.busy=800; jiffies=3520; apple_clpc_sample(&c); assert(published==0x35 && gpu.level==3); + // Going down waits 400 ms from the last sample at the top. + gpu.busy=100; + for (jiffies=3524; jiffies<3920; jiffies+=4) { + apple_clpc_sample(&c); assert(published==0x35 && gpu.level==3); + } + jiffies=3919; apple_clpc_sample(&c); assert(published==0x35 && gpu.level==3); + // At 400 ms the DCS drops at once; the fabric state keeps HOLD_MS. + jiffies=3920; apple_clpc_sample(&c); assert(published==0x31 && gpu.level==0); + jiffies=3952; apple_clpc_sample(&c); assert(published==0x01 && c.last_reason==2); + // A sample that asks for the current level again restarts the 400 ms. + gpu.busy=600; jiffies=4000; apple_clpc_sample(&c); assert(published==0x04 && gpu.level==2); + gpu.busy=100; jiffies=4200; apple_clpc_sample(&c); assert(gpu.level==2); + gpu.busy=550; jiffies=4300; apple_clpc_sample(&c); assert(gpu.level==2); + gpu.busy=100; jiffies=4699; apple_clpc_sample(&c); assert(published==0x04 && gpu.level==2); + jiffies=4700; apple_clpc_sample(&c); assert(published==0x01 && gpu.level==0); + gpu.active=false; jiffies=4800; apple_clpc_sample(&c); assert(published==0 && queued_idle); + // Without a non-zero top DCS state, even a low reported share keeps the map top. + no_top.gpu_busy[APPLE_CLPC_DCS][APPLE_CLPC_LEVELS - 1] = 0; + c.hw = &no_top; gpu.active=true; gpu.busy_valid=true; gpu.busy=100; jiffies=4900; + apple_clpc_sample(&c); assert(published==0x35 && c.last_reason==2); + // Same for a static table with no DT properties at all. + c.hw = &apple_clpc_hw_t6041; jiffies=4904; + apple_clpc_sample(&c); assert(published==0x35 && c.last_reason==2); + gpu.active=false; jiffies=5000; apple_clpc_sample(&c); assert(published==0 && queued_idle); +} + +// End-to-end: feed g17 BusyShare's actual reports for a 500 ms compute job +// running beside a light compositor into CLPC's T6041 ladder. CLPC drops to +// DCS 1 / fabric 0 during light compositing, lifts IMMEDIATELY to DCS 5 / +// fabric 3 (0x35) at t=1810 ms while the compute job is still in flight, holds +// 0x35 while it runs, and drops back to 0x01 after it finishes + 400 ms hold. +static void check_t6041_long_in_flight(void) { + struct apple_clpc_gpu gpu = {0}; + struct apple_clpc c = {.hw = &t6041_dt_hw, .has_pmc = true, .agent = 1, .mask = 3, .gpu = &gpu}; + read_error = vote_error = 0; pmgr_status = 0xf0; pmp_floor = 0; published = ~0u; + gpu.active = true; + // Initial burst starts at top (no share yet). + jiffies = 1000; apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + // Light compositor windows (1200, 1400, 1600 ms -> 50 permille) drop to DCS 1 / fabric 0. + assert(ARRAY_SIZE(g17_long_events) == 7); + for (size_t i = 0; i < 3; i++) { + gpu.busy = g17_long_events[i].permille; gpu.busy_valid = true; + jiffies = g17_long_events[i].ms; apple_clpc_sample(&c); + } + // After 400 ms down-step hold + 32 ms fabric hold, CLPC is at DCS 1 / fabric 0. + jiffies = 1640; apple_clpc_sample(&c); + assert(published == 0x01 && gpu.level == 0); + // At t=1810 ms (160 ms into the 500 ms compute job, still in flight!), BusyShare + // reports 1000 permille and CLPC lifts IMMEDIATELY to DCS 5 / fabric 3. + gpu.busy = g17_long_events[3].permille; gpu.busy_valid = true; + jiffies = g17_long_events[3].ms; apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + // Still running at t=2010 ms: stays at DCS 5 / fabric 3. + gpu.busy = g17_long_events[4].permille; gpu.busy_valid = true; + jiffies = g17_long_events[4].ms; apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + // Retires at t=2150 ms; window at t=2210 ms reports exact 700 (still in 400 ms hold). + gpu.busy = g17_long_events[5].permille; gpu.busy_valid = true; + for (jiffies = g17_long_events[5].ms; jiffies < g17_long_events[6].ms; jiffies += 4) { + apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + } + // Next light window at t=2410 ms (400 ms after last top request at 2010 ms): + // DCS drops immediately to 1, fabric keeps HOLD_MS (32 ms) from the 2406 ms sample. + gpu.busy = g17_long_events[6].permille; gpu.busy_valid = true; + jiffies = g17_long_events[6].ms; apple_clpc_sample(&c); + assert(published == 0x31 && gpu.level == 0); + jiffies = g17_long_events[6].ms + APPLE_CLPC_HOLD_MS; apple_clpc_sample(&c); + assert(published == 0x01 && gpu.level == 0); +} + +// End-to-end: g17 BusyShare's samples (-1: no report) for steady 600 permille +// work, an idle gap in which the GPU clears its activity (apple_clpc_gpu_set_active +// false also clears busy_valid), and a new burst 600 ms later. The new burst starts +// at the top (0x35) and stays there until a fresh 200 ms window reports; the +// diluted 85 permille a stale window would report drops it to 0x01 at once. +static void check_t6041_idle_burst(void) { + struct apple_clpc_gpu gpu = {0}; + struct apple_clpc c = {.hw = &t6041_dt_hw, .has_pmc = true, .agent = 1, .mask = 3, .gpu = &gpu}; + size_t i = 0, n = ARRAY_SIZE(g17_idle_events); + read_error = vote_error = 0; pmgr_status = 0xf0; pmp_floor = 0; published = ~0u; + assert(n == 8 && g17_idle_events[0].ms == 1100 && g17_idle_events[2].ms == 2000); + gpu.active = true; jiffies = 900; apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + for (; i < 2; i++) { + assert(g17_idle_events[i].permille == 600); + gpu.busy = g17_idle_events[i].permille; gpu.busy_valid = true; + jiffies = g17_idle_events[i].ms; apple_clpc_sample(&c); + } + assert(gpu.level == 2); + // Idle: the GPU clears its activity and CLPC forgets the share. + gpu.active = false; gpu.busy_valid = false; + for (jiffies = 1416; jiffies < 2000; jiffies += 4) + apple_clpc_sample(&c); + assert(published == 0); + gpu.active = true; + for (jiffies = 2000; jiffies <= 2200; jiffies += 4) { + if (i < n && g17_idle_events[i].ms == jiffies) { + if (g17_idle_events[i].permille >= 0) { + gpu.busy = g17_idle_events[i].permille; gpu.busy_valid = true; + } + i++; + } + assert(gpu.busy_valid == (jiffies >= 2200)); + apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + } + assert(i == n); + // The stale window's diluted share would have dropped the new burst at once. + gpu.active = false; gpu.busy_valid = false; jiffies = 2400; apple_clpc_sample(&c); + gpu.active = true; gpu.busy = 85; gpu.busy_valid = true; jiffies = 3000; + apple_clpc_sample(&c); assert(published == 0x01 && gpu.level == 0); + gpu.active = false; jiffies = 3100; apple_clpc_sample(&c); assert(published == 0); +} + // T8132's G16 firmware keeps graphics powered while the GPU idles: the // M5/F3 floor follows the work the GPU driver reports, as on T6040. static void check_t8132(void) { struct apple_clpc_gpu gpu={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t8132,.agent=1,.mask=3,.gpu=&gpu}; + struct apple_clpc c={.hw=&apple_clpc_hw_t8132,.has_pmc=true,.agent=1,.mask=3,.gpu=&gpu}; assert(!c.hw->gpu_demand); read_error=vote_error=0; pmgr_status=0xf0; pmp_floor=0; jiffies=0; published=~0u; apple_clpc_sample(&c); assert(published==0 && queued_idle && c.last_reason==0); @@ -190,10 +640,10 @@ def main(): // T6041 (M4 Max) votes DCS 5 / fabric 3 for CPU and host GPU demand without a // streak, samples on time while idle, preserves T6041's DCS 5 / fabric 2 ANE // floor, and carries the 2808 MHz Low Power ceiling. -static void check_t6041(void) { +static void check_t6041(const struct apple_clpc_hw *hw) { struct apple_clpc_gpu gpu={0}; struct apple_clpc_ane ane={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t6041,.agent=1,.mask=3,.gpu=&gpu,.ane=&ane}; + struct apple_clpc c={.hw=hw,.has_pmc=true,.agent=1,.mask=3,.gpu=&gpu,.ane=&ane}; c.ane_states[APPLE_CLPC_DCS]=c.hw->ane[APPLE_CLPC_DCS]; c.ane_states[APPLE_CLPC_SOC]=c.hw->ane[APPLE_CLPC_SOC]; assert(!c.hw->gpu_demand && c.hw->gpu_input && c.hw->sustain==0 && c.hw->idle_on_time); @@ -219,7 +669,7 @@ def main(): // A failed power-state read still protects an active graphics consumer. static void check_read_error(void) { - struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.agent=1,.mask=3,.gpu_pmgr=(void *)1}; + struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.has_pmc=true,.agent=1,.mask=3,.gpu_pmgr=(void *)1}; read_error=vote_error=0; pmp_floor=4; pmgr_status=0xf0; warned=0; for (jiffies=100; jiffies<=164; jiffies+=4) apple_clpc_sample(&c); assert(published==0x34 && c.last_reason==4); @@ -234,7 +684,7 @@ def main(): } static void check_t8140(void) { - struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.agent=1,.mask=3,.gpu_pmgr=(void *)1}; + struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.has_pmc=true,.agent=1,.mask=3,.gpu_pmgr=(void *)1}; read_error=vote_error=0; pmp_floor=4; pmgr_status=0xf0; for (jiffies=100; jiffies<=164; jiffies+=4) { apple_clpc_sample(&c); @@ -257,7 +707,7 @@ def main(): // streams, but 2+ submissions in each of 4 periods earn the GPU floor. static void check_t8140_dense(void) { struct apple_clpc_gpu gpu={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.agent=1,.mask=3,.gpu_pmgr=(void *)1,.gpu=&gpu}; + struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.has_pmc=true,.agent=1,.mask=3,.gpu_pmgr=(void *)1,.gpu=&gpu}; read_error=vote_error=0; pmp_floor=4; pmgr_status=0; published=~0u; jiffies=100; apple_clpc_sample(&c); assert(published==0 && queued_idle); for (jiffies=104; jiffies<=116; jiffies+=4) { @@ -276,24 +726,27 @@ def main(): assert(c.last_reason==16); } -// Low power samples on time only where it has a CPU ceiling to keep -// (low_power_khz); a High Power-only profile stays deferrable when idle. +// Low power samples on time only when a package power target (low_power_mw) +// is active; a static ceiling alone or High Power-only profile stays +// deferrable when idle. static void check_low_power(void) { struct apple_clpc_gpu gpu={0}; struct apple_clpc_hw lp=apple_clpc_hw_t6040; - struct apple_clpc c={.hw=&lp,.agent=1,.mask=3,.gpu=&gpu,.low_power=true}; + struct apple_clpc c={.hw=&lp,.has_pmc=true,.agent=1,.mask=3,.gpu=&gpu,.low_power=true}; read_error=vote_error=0; pmgr_status=0xf0; published=~0u; jiffies=3000; apple_clpc_sample(&c); assert(published==0 && queued_idle); - lp.low_power_khz=2808000; - jiffies=3004; apple_clpc_sample(&c); assert(published==0 && !queued_idle); + c.low_power_khz=2808000; + jiffies=3004; apple_clpc_sample(&c); assert(published==0 && queued_idle); + c.low_power_mw=15000; + jiffies=3008; apple_clpc_sample(&c); assert(published==0 && !queued_idle); c.low_power=false; - jiffies=3008; apple_clpc_sample(&c); assert(published==0 && queued_idle); + jiffies=3012; apple_clpc_sample(&c); assert(published==0 && queued_idle); } int main(void) { // T6040's supplier is always powered: it must NEVER substitute for work. struct apple_clpc_gpu gpu={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t6040,.agent=1,.mask=3,.gpu=&gpu}; + struct apple_clpc c={.hw=&apple_clpc_hw_t6040,.has_pmc=true,.agent=1,.mask=3,.gpu=&gpu}; assert(!c.hw->gpu_demand); jiffies=0; read_error=vote_error=0; pmgr_status=0xf0; published=~0u; apple_clpc_sample(&c); assert(published==0 && queued_idle && c.last_reason==0); @@ -313,15 +766,21 @@ def main(): assert(published==0x12 && c.last_reason==1); c.clusters[0].request[0]=c.clusters[0].request[1]=0; jiffies=264; apple_clpc_sample(&c); assert(published==0); + t6041_from_dt(); + check_t6041_busy(); + check_t6041_long_in_flight(); + check_t6041_idle_burst(); check_t8132(); - check_t6041(); + check_t6041(&apple_clpc_hw_t6041); + check_t6041(&t6041_dt_hw); check_read_error(); check_t8140(); check_t8140_dense(); check_t8140_ane(); + check_t6050_ane(); check_low_power(); check_t6040_ane(); - puts("PASS: T6040, T6041 and T8132 host demand; T8140/T604x ANE, streaming, dense work, read errors and PMP backoff; idle release"); + puts("PASS: T6040, T6041 and T8132 host demand; DT GPU busy share and down-step hold; T8140/T604x ANE, streaming, dense work, read errors and PMP backoff; idle release"); } ''' code = code.replace('#define APPLE_PMC_RAIL_SHIFT(r) ((r)*8)', rail_shift) @@ -346,7 +805,22 @@ def main(): ('omit-pmp-backoff', code.replace('bool released = apple_clpc_gpu_limited(clpc, now);', 'bool released = (apple_clpc_gpu_limited(clpc, now), false);')), ('release-too-early', code.replace('msecs_to_jiffies(APPLE_CLPC_HOLD_MS)', '0')), + ('gpu-down-at-once', code.replace('msecs_to_jiffies(APPLE_CLPC_GPU_DOWN_MS)', '0')), + ('gpu-busy-ignored', code.replace('if (!gpu->busy_valid || gpu->busy >= hw->gpu_busy_top)', + 'if (true || gpu->busy >= hw->gpu_busy_top)')), + ('gpu-no-share-uses-table', code.replace('if (!gpu->busy_valid || gpu->busy >= hw->gpu_busy_top)', + 'if (gpu->busy >= hw->gpu_busy_top)')), + ('gpu-busy-without-dt', code.replace('bool has_busy = hw->gpu_busy[APPLE_CLPC_DCS][APPLE_CLPC_LEVELS - 1];', + 'bool has_busy = true;')), ('retain-at-idle', code.replace('vote->state = 0;', '')), + ('dt-state-unchecked', code.replace('if (state > top || state > 15)', 'if ((void)top, false)')), + ('dt-rail-bound-unchecked', code.replace('if (state > top || state > 15)', 'if ((void)top, state > 15)')), + ('dt-gpu-rail-max-ignored', code.replace('max(hw->map[rail][APPLE_CLPC_LEVELS - 1],\n\t\t\t hw->gpu[rail])', + 'hw->map[rail][APPLE_CLPC_LEVELS - 1]')), + ('dt-fallback-keeps-partial', code.replace('\t\t*out = *soc;\n\t\treturn false;', '\t\treturn false;')), + ('dt-fallback-silent', code.replace('dev_warn(dev,\n\t\t\t "ignoring invalid GPU busy-share states in the device tree (%d)\\n",\n\t\t\t err);', + '(void)dev; (void)err;')), + ('dt-busy-unordered', code.replace('cells[0] > cells[1] || ', '')), ]: # A mutation that no longer matches the driver tests nothing. assert name == 'fixed' or text != code, 'stale mutation: ' + name diff --git a/tools/asahi/clpc-high-power-cleanup-tests.py b/tools/asahi/clpc-high-power-cleanup-tests.py index 709aed09ecf4f8..841289d9845e55 100755 --- a/tools/asahi/clpc-high-power-cleanup-tests.py +++ b/tools/asahi/clpc-high-power-cleanup-tests.py @@ -35,12 +35,25 @@ def function(source, name): #include #include typedef uint8_t u8; +typedef int atomic_t; +static void __attribute__((unused)) atomic_set(atomic_t *v, int i) { *v = i; } +struct hlist_node { int unused; }; +struct apple_clpc_idle_timer { int timer; }; +static int __attribute__((unused)) apple_clpc_cpuhp_state; +static void __attribute__((unused)) cpuhp_state_remove_instance_nocalls(int s, struct hlist_node *n) { (void)s; (void)n; } +static void __attribute__((unused)) timer_delete_sync(int *t) { (void)t; } +#define scoped_guard(kind, lock) for (int _once = (mutex_lock(lock), 1); _once; _once = (mutex_unlock(lock), 0)) +#define for_each_possible_cpu(cpu) for ((cpu) = 0; (cpu) < 1; (cpu)++) +#define per_cpu_ptr(ptr, cpu) (&(ptr)[cpu]) #define APPLE_CLPC_RAILS 2 #define FREQ_QOS_MIN_DEFAULT_VALUE 0 #define CPUFREQ_POLICY_NOTIFIER 1 #define READ_ONCE(x) (x) #define WRITE_ONCE(x, v) ((x) = (v)) #define SMC_KEY(x) 0x7a45544d +/* Model a kernel built with the SMC driver, so the SMC path runs. */ +#define CONFIG_MFD_MACSMC 1 +#define IS_ENABLED(option) (option) #define dev_warn(...) (warnings++) enum platform_profile_option { PLATFORM_PROFILE_BALANCED, PLATFORM_PROFILE_LOW_POWER, PLATFORM_PROFILE_PERFORMANCE }; @@ -60,19 +73,26 @@ def function(source, name): struct device_node *smc_np; struct apple_clpc_gpu *gpu; struct apple_clpc_ane *ane; - struct mutex sample_lock; + struct mutex sample_lock, idle_lock; struct delayed_work work, idle_work; - bool stopped, high_power, high_power_sent, policy_nb_added, low_power; + struct apple_clpc_idle_timer *idle_timers; + struct hlist_node cpuhp_node; + atomic_t idle_armed; + bool has_pmc, stopped, high_power, high_power_sent, policy_nb_added, low_power, cpuhp_added; u8 high_power_seq; enum platform_profile_option profile; unsigned long power_next, ane_until; - unsigned ane_qos_khz, nr_clusters, agent, mask, saved_floor; + unsigned low_power_khz, low_power_mw, ane_qos_khz, nr_clusters, agent, mask, saved_floor; struct freq_qos_request ane_qos; struct cluster clusters[2]; struct vote vote[APPLE_CLPC_RAILS]; - void *pmc, *debugfs; + void *pmc, *debugfs, *covered; int policy_nb; }; +static void __attribute__((unused)) *cpu_possible_mask; +static bool __attribute__((unused)) cpumask_equal(void *a, void *b) { return a == b; } +static void __attribute__((unused)) apple_clpc_find_clusters(struct apple_clpc *c) { (void)c; } +static void __attribute__((unused)) apple_clpc_profile_limit(struct apple_clpc *c) { (void)c; } static struct mutex apple_clpc_clients_lock; static unsigned long jiffies = 123; static int system_freezable_power_efficient_wq; @@ -102,7 +122,7 @@ def function(source, name): } static void apple_pmc_floor_update(void *p, unsigned a, unsigned mask, unsigned saved) { (void)p; (void)a; (void)mask; (void)saved; - assert(cancels == 4 && !active->work.pending && !active->idle_work.pending); + assert(cancels >= 4 && !active->work.pending && !active->idle_work.pending); floor_restored = true; } static int freq_qos_update_request(struct freq_qos_request *q, int value) { @@ -117,11 +137,11 @@ def function(source, name): (void)n; assert(kind == CPUFREQ_POLICY_NOTIFIER && floor_restored); assert(!active->sample_lock.held); notifier_removed = true; } -static void of_node_put(struct device_node *n) { +static void __attribute__((unused)) of_node_put(struct device_node *n) { (void)n; assert(notifier_removed && qos_removed == 3); node_put = true; } static void apple_clpc_free_clusters(struct apple_clpc *c) { - (void)c; assert(node_put); freed = true; + (void)c; assert(notifier_removed && qos_removed == 3); freed = true; } static bool apple_clpc_smc(struct apple_clpc *c) { return c->smc != NULL; } static void put_unaligned_le32(uint32_t v, u8 *p) { @@ -131,7 +151,7 @@ def function(source, name): assert(s && key == SMC_KEY(zETM) && size == sizeof(last_record)); assert(active->sample_lock.held && !node_put && !freed); if (cleanup) { - assert(detached && debug_removed && floor_restored && cancels == 4); + assert(detached && debug_removed && floor_restored && cancels >= 4); assert(!active->dev->data && !active->gpu->wake && !active->ane->wake); assert(active->stopped && !notifier_removed && !qos_removed); assert(active->vote[0].state == 0 && active->vote[1].state == 0); @@ -153,7 +173,7 @@ def function(source, name): static struct apple_clpc c; static void reset(void) { memset(&c, 0, sizeof(c)); memset(&gpu, 0, sizeof(gpu)); memset(&ane, 0, sizeof(ane)); - active = &c; dev.data = &c; c.dev = &dev; c.smc = &smc; + active = &c; dev.data = &c; c.dev = &dev; c.smc = &smc; c.has_pmc = true; c.gpu = &gpu; c.ane = &ane; gpu.wake = &c.work; ane.wake = &c.work; c.work.pending = c.idle_work.pending = true; c.policy_nb_added = c.ane_qos.active = true; @@ -173,9 +193,9 @@ def function(source, name): } static void stop(void) { cleanup = true; apple_clpc_stop(&c); - assert(freed && node_put && notifier_removed && qos_removed == 3); + assert(freed && notifier_removed && qos_removed == 3); assert(!c.sample_lock.held && !apple_clpc_clients_lock.held); - assert(c.stopped && cancels == 4 && floor_restored && !dev.data); + assert(c.stopped && cancels >= 4 && floor_restored && !dev.data); } int main(void) { /* A real successful performance callback sets the qualified sent state. */ diff --git a/tools/asahi/dart-sleep-writer-tests.py b/tools/asahi/dart-sleep-writer-tests.py index e07f0a68a386c4..4888e79e1bfe8a 100644 --- a/tools/asahi/dart-sleep-writer-tests.py +++ b/tools/asahi/dart-sleep-writer-tests.py @@ -52,8 +52,8 @@ def closed_branches_put(text): branches = closed_branches_put(driver) assert branches == 6, branches # Negative control: a branch that leaks its reference is caught. -leak = driver.replace("\t\t\tapple_dart_sleep_writer_put(stream.dart, gate);\n\t\t\terr = err ?: ret;\n\t\t\tcontinue;", - "\t\t\terr = err ?: ret;\n\t\t\tcontinue;", 1) +leak = driver.replace("\t\t\tapple_dart_sleep_writer_put(stream.dart, gate);\n\t\t\tspin_lock_irqsave(&stream.dart->managed_lock, flags);", + "\t\t\tspin_lock_irqsave(&stream.dart->managed_lock, flags);", 1) assert leak != driver try: closed_branches_put(leak) diff --git a/tools/asahi/dcp-hdmi-sleep-unplug-tests.py b/tools/asahi/dcp-hdmi-sleep-unplug-tests.py new file mode 100755 index 00000000000000..b1ef7a00daa235 --- /dev/null +++ b/tools/asahi/dcp-hdmi-sleep-unplug-tests.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the real HDMI sleep keep-link and the unplugged-in-sleep release. + +A DCP whose firmware runs through a sleep keeps an attached HDMI display's +link (dcp_platform_suspend()), so the display lights again on wake. Its HPD +IRQ is masked through the sleep, so a display unplugged during it makes no +edge anyone sees: dcp_hdmi_unplugged_in_sleep() releases it on resume, before +the IRQ comes back. A T6030 native output still releases the link at suspend, +because its resume sets the PHY and crossbar up again. + +The fixture compiles the HDMI block of dcp_platform_suspend() and the +fabric's dcp_hdmi_unplugged_in_sleep() against mocks. It checks which +outputs are released and that the fabric lock covers the resume release. +--mutation names a change to the production code that the matrix must kill. +""" +import argparse +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DCP = 'drivers/gpu/drm/apple/dcp.c' +FABRIC = 'drivers/gpu/drm/apple/dcp-fabric.c' +RESUME_CALL = '\tif (dcp->hdmi_hpd_irq)\n\t\tdcp_hdmi_unplugged_in_sleep(dcp);\n' + +MUTATIONS = { + # Keep a T6030 native output's link, which its resume reinit tears down. + 'keep-native': ('(dcp->external_native ||\n\t\t gpiod_get_value_cansleep(dcp->hdmi_hpd) <= 0)', + '(gpiod_get_value_cansleep(dcp->hdmi_hpd) <= 0)'), + # Release on a failed GPIO read, which cannot establish absence. + 'gpio-error': ('gpiod_get_value_cansleep(dcp->hdmi_hpd) != 0)\n\t\treturn;', + 'gpiod_get_value_cansleep(dcp->hdmi_hpd) > 0)\n\t\treturn;'), + # Release the HDMI connector while a Type-C display owns the pipeline. + 'ignore-borrowed': ('if (dcp->active_typec_route || !dcp->connector ||', + 'if (!dcp->connector ||'), + # Leave the hybrid fabric thinking HDMI is still there. + 'no-fabric': ('\tdcp_fabric_hdmi_unplugged_locked(dcp);\n', ''), + 'no-fabric-lock': ('\tguard(mutex)(&dcp_typec_fabric_lock);\n', ''), + # Never look for an unplug after the sleep. + 'no-resume-check': (RESUME_CALL, ''), +} + +def block(text, start): + opening = text.index('{', start) + depth = 0 + for end in range(opening, len(text)): + depth += text[end] == '{' + depth -= text[end] == '}' + if not depth: + return text[start:end + 1] + raise AssertionError('unbalanced production block') + +def function(text, name): + match = re.search(r'\n((?:static )?[^\n;]*\b' + name + r'\([^;{}]*\)\n)\{', text) + assert match, name + return block(text, match.start(1)) + +HARNESS = r''' +#include +#include +#include +#define READ_ONCE(x) (x) +#define dev_info(...) ((void)0) +struct device { int unused; }; +struct gpio_desc { int level; }; +struct apple_connector { bool connected; }; +struct apple_dcp { + struct device *dev; + void *active_typec_route; + struct apple_connector *connector; + struct gpio_desc *hdmi_hpd; + int hdmi_hpd_irq; + bool external_native; +}; +static unsigned hpd_events, disconnects, fabric_unplugs, irq_off; +static int gpiod_get_value_cansleep(struct gpio_desc *g) { return g->level; } +static void disable_irq(int irq) { irq_off++; } +static void disconnected_hpd_event(struct apple_connector *c) { c->connected = false; hpd_events++; } +static int dcp_dptx_disconnect(struct apple_dcp *d, int port) { disconnects++; return 0; } +static int dcp_typec_fabric_lock; +static int *hold_lock(int *lock) +{ + assert(!*lock); + *lock = 1; + return lock; +} +static void release_lock(int **lock) { **lock = 0; } +#define guard(kind) int *held_##kind __attribute__((cleanup(release_lock))) = hold_lock +static void dcp_hdmi_disconnect(struct apple_dcp *dcp) +{ + assert(dcp_typec_fabric_lock); + disconnected_hpd_event(dcp->connector); + dcp_dptx_disconnect(dcp, 0); +} +static void dcp_fabric_hdmi_unplugged_locked(struct apple_dcp *d) +{ + assert(dcp_typec_fabric_lock); + fabric_unplugs++; +} +static void reset(void) { hpd_events = disconnects = fabric_unplugs = irq_off = 0; } +''' + +CHECKS = r''' +static void suspend_hdmi(struct apple_dcp *dcp) { SUSPEND } + +static int failures; +#define CHECK(c) do { if (!(c)) { printf("FAIL line %d (%s: %s)\n", __LINE__, case_name, #c); failures++; } } while (0) + +int main(void) +{ + const char *case_name; + struct apple_connector con; + struct gpio_desc hpd; + struct apple_dcp dcp; + int route; + +#define SETUP(name, L, N) do { case_name = name; reset(); con.connected = true; \ + hpd.level = L; dcp = (struct apple_dcp){ .connector = &con, .hdmi_hpd = &hpd, \ + .hdmi_hpd_irq = 7, .external_native = N }; } while (0) + + /* Attached through the sleep: kept, lit again on wake. */ + SETUP("kept", 1, false); + suspend_hdmi(&dcp); + CHECK(irq_off == 1 && con.connected && !disconnects); + dcp_hdmi_unplugged_in_sleep(&dcp); + CHECK(con.connected && !disconnects && !fabric_unplugs); + + /* Unplugged during the sleep: released on resume, fabric told. */ + SETUP("unplugged-in-sleep", 1, false); + suspend_hdmi(&dcp); + hpd.level = 0; + dcp_hdmi_unplugged_in_sleep(&dcp); + CHECK(!con.connected && hpd_events == 1 && disconnects == 1 && fabric_unplugs == 1); + + /* Gone before the sleep: released at suspend, nothing on resume. */ + SETUP("gone-before", 0, false); + suspend_hdmi(&dcp); + CHECK(!con.connected && disconnects == 1); + dcp_hdmi_unplugged_in_sleep(&dcp); + CHECK(disconnects == 1 && hpd_events == 1 && !fabric_unplugs); + + /* A failed GPIO read cannot establish absence. */ + SETUP("gpio-error", 1, false); + suspend_hdmi(&dcp); + hpd.level = -5; + dcp_hdmi_unplugged_in_sleep(&dcp); + CHECK(con.connected && !disconnects); + + /* A Type-C display owns the pipeline: the HDMI side is not touched. */ + SETUP("borrowed", 0, false); + dcp.active_typec_route = &route; + suspend_hdmi(&dcp); + dcp_hdmi_unplugged_in_sleep(&dcp); + CHECK(con.connected && !disconnects && !hpd_events && !fabric_unplugs); + + /* T6030 native output: released at suspend even while attached. */ + SETUP("native", 1, true); + suspend_hdmi(&dcp); + CHECK(!con.connected && disconnects == 1); + dcp_hdmi_unplugged_in_sleep(&dcp); + CHECK(disconnects == 1); + + if (failures) + return 1; + puts("PASS HDMI sleep: attached kept, unplugged-in-sleep released on resume, " + "gone-before released at suspend, GPIO error and borrowed pipeline untouched, " + "T6030 native released"); + return 0; +} +''' + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = parser.parse_args() + + source = (ROOT / DCP).read_text() + unplug = function((ROOT / FABRIC).read_text(), 'dcp_hdmi_unplugged_in_sleep') + if args.mutation: + old, new = MUTATIONS[args.mutation] + if old in unplug: + assert unplug.count(old) == 1, args.mutation + unplug = unplug.replace(old, new) + else: + assert source.count(old) == 1, args.mutation + source = source.replace(old, new) + + resume = function(source, 'dcp_platform_resume') + # The release runs while the HPD IRQ is still masked: an edge from then + # on is replayed when dcp_fabric_run_resume() enables it. + if RESUME_CALL not in resume or \ + resume.index(RESUME_CALL) > resume.index('dcp_fabric_run_resume(&dcp_resume_ops, dcp)'): + print('FAIL line 0 (resume: no unplugged-in-sleep release before the HPD IRQ comes back)') + sys.exit(1) + + suspend = function(source, 'dcp_platform_suspend') + hdmi = block(suspend, suspend.index('\tif (dcp->hdmi_hpd_irq) {\n\t\tdisable_irq')) + code = HARNESS + unplug + CHECKS.replace('SUSPEND', hdmi) + + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'check.c' + path.write_text(code) + subprocess.run(['clang', '-std=gnu11', '-Wall', '-Werror', '-Wno-unused-function', + '-fsanitize=address,undefined', str(path), '-o', str(path.with_suffix(''))], + check=True) + sys.exit(subprocess.run([str(path.with_suffix(''))]).returncode) + +if __name__ == '__main__': + main() diff --git a/tools/asahi/dcp-peer-shown-tests.py b/tools/asahi/dcp-peer-shown-tests.py new file mode 100644 index 00000000000000..ccf7dfae223f39 --- /dev/null +++ b/tools/asahi/dcp-peer-shown-tests.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Paired firmware-27 completions carry the retired swap's displayed state to the owner.""" +from pathlib import Path +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +HEADER = (ROOT / 'drivers/gpu/drm/apple/dcp-peer-frames-v27.h').read_text() +SHOWN = ''' *shown = s->have_shown[0] && s->shown[0] == done && + s->have_shown[1] && s->shown[1] == done; +''' +assert HEADER.count(SHOWN) == 1 +if '--always-shown' in sys.argv: + HEADER = HEADER.replace(SHOWN, '\t*shown = true;\n') +if '--owner-only' in sys.argv: + HEADER = HEADER.replace(SHOWN, '\t*shown = s->have_shown[0] && s->shown[0] == done;\n') + +TEST = r''' +#include +#include +#include +typedef uint32_t u32; typedef int32_t s32; +''' + HEADER.replace('#include ', '') + r''' +static struct dcp_peer_frames_v27 paired(u32 first, u32 last) +{ + struct dcp_peer_frames_v27 s = { .active = true }; + + for (u32 id = first; id <= last; id++) + dcp_peer_frame_submit_v27(&s, id); + return s; +} + +int main(void) +{ + struct dcp_peer_frames_v27 s; + u32 w = 0; + bool shown = true; + + /* A new adaptive-sync minimum can reuse only the installed mode. */ + s = (struct dcp_peer_frames_v27){ .timing = 81, .color = 86, .active = true }; + assert(dcp_peer_vrr_only_v27(&s, 81, 86, 0x300000, false)); + assert(!dcp_peer_vrr_only_v27(&s, 81, 86, 0, false)); + assert(!dcp_peer_vrr_only_v27(&s, 80, 86, 0x300000, false)); + assert(!dcp_peer_vrr_only_v27(&s, 81, 85, 0x300000, false)); + assert(!dcp_peer_vrr_only_v27(&s, 81, 86, 0x300000, true)); + s.failed = true; + assert(!dcp_peer_vrr_only_v27(&s, 81, 86, 0x300000, false)); + s.failed = false; + s.active = false; + assert(!dcp_peer_vrr_only_v27(&s, 81, 86, 0x300000, false)); + + /* First modeset of a pair: both engines display swap 5. */ + s = paired(5, 5); + assert(!dcp_peer_frame_complete_v27(&s, 0, 5, true, &w, &shown)); + assert(dcp_peer_frame_complete_v27(&s, 1, 5, true, &w, &shown)); + assert(w == 5 && shown); + + /* The peer's half of swap 5 was not displayed. */ + s = paired(5, 5); + assert(!dcp_peer_frame_complete_v27(&s, 0, 5, true, &w, &shown)); + assert(dcp_peer_frame_complete_v27(&s, 1, 5, false, &w, &shown)); + assert(w == 5 && !shown); + + /* Neither half displayed (the owner's completion came second). */ + s = paired(5, 5); + assert(!dcp_peer_frame_complete_v27(&s, 1, 5, false, &w, &shown)); + assert(dcp_peer_frame_complete_v27(&s, 0, 5, false, &w, &shown)); + assert(w == 5 && !shown); + + /* + * Engines drift: the peer has shown 6 when the owner shows 5. The + * retired swap is 5, which the peer's shown 6 does not vouch for; + * swap 6 then retires shown. + */ + s = paired(5, 6); + assert(!dcp_peer_frame_complete_v27(&s, 1, 6, true, &w, &shown)); + assert(dcp_peer_frame_complete_v27(&s, 0, 5, true, &w, &shown)); + assert(w == 5 && !shown); + assert(dcp_peer_frame_complete_v27(&s, 0, 6, true, &w, &shown)); + assert(w == 6 && shown); + + /* A displayed earlier swap does not mark a later, undisplayed one. */ + s = paired(5, 6); + assert(!dcp_peer_frame_complete_v27(&s, 0, 5, true, &w, &shown)); + assert(!dcp_peer_frame_complete_v27(&s, 0, 6, false, &w, &shown)); + assert(dcp_peer_frame_complete_v27(&s, 1, 6, true, &w, &shown)); + assert(w == 6 && !shown); + + /* A stale or duplicate completion is not a retirement. */ + assert(!dcp_peer_frame_complete_v27(&s, 1, 6, true, &w, &shown)); + return 0; +} +''' + +with tempfile.TemporaryDirectory() as t: + src = Path(t) / 'peer.c' + src.write_text(TEST) + subprocess.run(['cc', '-std=gnu11', '-Wall', '-Werror', '-fsanitize=address,undefined', + str(src), '-o', str(src.with_suffix(''))], check=True) + if subprocess.run([str(src.with_suffix(''))]).returncode: + sys.exit(1) +print('PASS paired completion shown state: first modeset, undisplayed half, drift, stale shown, duplicate') diff --git a/tools/asahi/dcp-sleep-phy-hold-tests.py b/tools/asahi/dcp-sleep-phy-hold-tests.py new file mode 100755 index 00000000000000..b0cf23c94c5d1b --- /dev/null +++ b/tools/asahi/dcp-sleep-phy-hold-tests.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the actual DCP sleep PHY hold over every PHY topology. + +A DCP whose firmware keeps running through a sleep keeps driving the DP PHY +of its output. genpd powers the PHY's domain off at noirq unless the PHY's +device is on the wakeup path, and cutting it under the running firmware +resets the J473 (firmware 27.2) on s2idle. dcp_sleep_hold_phys() puts the +provider device of the DCP's own dp-phy and of its active Type-C route's PHY +on the wakeup path. The fixture builds the real dcp_phy_set_wakeup_path() and +dcp_sleep_hold_phys() from drivers/gpu/drm/apple/dcp-fabric.c against a small +driver-core model and checks which devices end up on the wakeup path. + +--mutation names a change to the production functions that the matrix must +kill. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DCP = "drivers/gpu/drm/apple/dcp-fabric.c" + +MUTATIONS = { + # Forget the Type-C route's PHY (the USB-C output of a primary DCP). + "no-route": ("\tif (route)\n\t\tdcp_phy_set_wakeup_path(route->phy);\n", ""), + # Forget the DCP's own dp-phy (the HDMI output of a dcpext). + "no-own-phy": ("\tdcp_phy_set_wakeup_path(dcp->phy);\n", ""), + # Mark the PHY class device instead of the provider genpd sees. + "class-device": ("device_set_wakeup_path(phy->dev.parent);", "device_set_wakeup_path(&phy->dev);"), + # Trust an error pointer. + "no-err-check": ("!IS_ERR_OR_NULL(phy) && ", "phy && "), +} + +HARNESS = r''' +#include +#include +#include +#include +#include +#include +static volatile int cur_line; +static bool dcp_typec_fabric_lock; +static bool *lock_acquire(bool *held) +{ + if (*held) + abort(); + *held = true; + return held; +} +static void lock_release(bool **held) { **held = false; } +#define guard(kind) bool *__attribute__((cleanup(lock_release))) held = lock_acquire +static void on_segv(int sig) { char b[64]; int n = snprintf(b, sizeof(b), "FAIL line %d (signal %d)\n", cur_line, sig); write(1, b, n); _exit(1); } +#define MAX_ERRNO 4095 +#define IS_ERR_VALUE(x) ((unsigned long)(void *)(x) >= (unsigned long)-MAX_ERRNO) +static inline bool IS_ERR_OR_NULL(const void *p) { return !p || IS_ERR_VALUE((unsigned long)p); } +struct device { struct device *parent; bool wakeup_path; }; +static void device_set_wakeup_path(struct device *dev) +{ + if (!dcp_typec_fabric_lock) { + printf("FAIL line %d wakeup mark without fabric lock\n", cur_line); + exit(1); + } + if (IS_ERR_VALUE((unsigned long)dev)) { printf("FAIL line %d error pointer\n", cur_line); exit(1); } + dev->wakeup_path = true; +} +struct phy { struct device dev; }; +struct apple_dcp_typec_route { struct phy *phy; }; +struct apple_dcp { struct phy *phy; struct apple_dcp_typec_route *active_typec_route; }; +@@FUNCS@@ +int main(void) +{ + struct device own_prov = {0}, route_prov = {0}, other_prov = {0}; + struct phy own = { .dev = { .parent = &own_prov } }; + struct phy rphy = { .dev = { .parent = &route_prov } }; + struct phy orphan = { .dev = { .parent = NULL } }; + struct apple_dcp_typec_route route = { .phy = &rphy }, noroute_phy = { .phy = NULL }; + struct apple_dcp d; + int fail = 0; + + signal(SIGSEGV, on_segv); +#define RESET() do { own_prov.wakeup_path = route_prov.wakeup_path = other_prov.wakeup_path = false; \ + own.dev.wakeup_path = rphy.dev.wakeup_path = orphan.dev.wakeup_path = false; } while (0) +#define CHECK(name, cond) do { if (!(cond)) { printf("FAIL line %d %s\n", __LINE__, name); fail++; } else printf("ok %s\n", name); } while (0) +#define HOLD(dcp) do { cur_line = __LINE__; fflush(stdout); dcp_sleep_hold_phys(dcp); } while (0) + /* dcpext: its own dp-phy, no Type-C route */ + RESET(); d.phy = &own; d.active_typec_route = NULL; HOLD(&d); + CHECK("dcpext dp-phy provider held", own_prov.wakeup_path && !own.dev.wakeup_path); + /* primary with a Type-C route and no own phy */ + RESET(); d.phy = NULL; d.active_typec_route = &route; HOLD(&d); + CHECK("route phy provider held", route_prov.wakeup_path && !rphy.dev.wakeup_path && !own_prov.wakeup_path); + /* both */ + RESET(); d.phy = &own; d.active_typec_route = &route; HOLD(&d); + CHECK("both held", own_prov.wakeup_path && route_prov.wakeup_path); + /* nothing to hold */ + RESET(); d.phy = NULL; d.active_typec_route = NULL; HOLD(&d); + CHECK("none", !own_prov.wakeup_path && !route_prov.wakeup_path && !other_prov.wakeup_path); + /* an optional phy lookup error and a route without a phy */ + RESET(); d.phy = (struct phy *)(intptr_t)-19; d.active_typec_route = &noroute_phy; HOLD(&d); + CHECK("error phy and phy-less route ignored", !own_prov.wakeup_path && !route_prov.wakeup_path); + /* a phy without a provider parent */ + RESET(); d.phy = &orphan; d.active_typec_route = NULL; HOLD(&d); + CHECK("parentless phy ignored", !orphan.dev.wakeup_path); + printf("%d failures\n", fail); + return fail != 0; +} +''' + +def extract(src, name): + m = re.search(r'^(?:static )?void %s\(.*?^}\n' % re.escape(name), src, re.S | re.M) + if not m: + sys.exit(f"{name} not found in {DCP}") + return m.group(0) + +def run(mutation): + src = (ROOT / DCP).read_text() + funcs = extract(src, "dcp_phy_set_wakeup_path") + "\n" + extract(src, "dcp_sleep_hold_phys") + if mutation: + old, new = MUTATIONS[mutation] + if funcs.count(old) != 1: + sys.exit(f"mutation {mutation} does not apply exactly once") + funcs = funcs.replace(old, new) + with tempfile.TemporaryDirectory() as tmp: + c = Path(tmp) / "t.c" + exe = Path(tmp) / "t" + c.write_text(HARNESS.replace("@@FUNCS@@", funcs)) + flags = ["-std=gnu11", "-Wall"] + ([] if mutation else ["-Werror"]) + subprocess.run([os.environ.get("CC", "cc"), *flags, "-o", exe, c], check=True) + r = subprocess.run([exe], capture_output=True, text=True) + out = r.stdout + r.stderr + bad = r.returncode != 0 + return bad, out + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--mutation", choices=sorted(MUTATIONS)) + a = ap.parse_args() + bad, out = run(a.mutation) + print(out, end="") + sys.exit(1 if bad else 0) + +if __name__ == "__main__": + main() diff --git a/tools/asahi/dcp-v27-dptx-layout-tests.py b/tools/asahi/dcp-v27-dptx-layout-tests.py index 03c130d0650fcc..1119c30a4acc92 100755 --- a/tools/asahi/dcp-v27-dptx-layout-tests.py +++ b/tools/asahi/dcp-v27-dptx-layout-tests.py @@ -1,12 +1,13 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only OR MIT -"""Where a firmware-27 dcpext opens its DPTX controller and ports. +"""Where a firmware-27 dcpext, or a DCP with Type-C routes, opens its DPTX controller and ports. Builds the production dcp_v27_dptx_layout() and dptxep_init()'s endpoint choice, and runs them over firmware, processor role, advertised endpoints and -hardware data. A firmware-27 dcpext whose firmware advertises both -DPTX_CONTROLLER_ENDPOINT (0x24) and DPTX_ENDPOINT (0x2a) gets the controller -and its ports there (J413 and J615 on 27.2); hardware data that names an +hardware data. A firmware-27 dcpext, or a firmware-27 DCP that the device tree +connects to Type-C display routes (the M2 Mac mini's primary), whose firmware +advertises both DPTX_CONTROLLER_ENDPOINT (0x24) and DPTX_ENDPOINT (0x2a) gets +the controller and its ports there (J413 and J615 on 27.2); hardware data that names an endpoint keeps it (T8142, T6050 and firmware-27 T6041 dcpexts); every other processor is unchanged. The selector must not test a compatible. @@ -24,9 +25,11 @@ 'ignore-advertisement': ('\tif (!apple_rtkit_has_endpoint(dcp->rtk, DPTX_CONTROLLER_ENDPOINT) ||\n' '\t !apple_rtkit_has_endpoint(dcp->rtk, DPTX_ENDPOINT))\n\t\treturn;\n', ''), # Override hardware data that already names an endpoint. - 'ignore-pinned': (' ||\n\t dcp->hw.dptx_endpoint)\n', ')\n'), - # Apply to internal processors too. - 'ignore-dcpext': (' || !dcp->dcpext', ''), + 'ignore-pinned': (' || dcp->hw.dptx_endpoint)\n', ')\n'), + # Apply to every processor, with or without Type-C routes. + 'ignore-dcpext': ('(!dcp->dcpext && !dcp->nr_typec_routes) || ', ''), + # Leave a DCP with Type-C routes on the default endpoints. + 'ignore-typec-routes': ('(!dcp->dcpext && !dcp->nr_typec_routes)', '!dcp->dcpext'), } parser = argparse.ArgumentParser(description=__doc__) @@ -93,7 +96,7 @@ def table(name): #define DPTX_CONTROLLER_ENDPOINT 0x24 #define DPTX_ENDPOINT 0x2a #define DPTX_ENDPOINT_V2 0x2c -struct apple_dcp { int fw_compat; bool dcpext, ext26; void *rtk, *dev; +struct apple_dcp { int fw_compat; bool dcpext, ext26; u32 nr_typec_routes; void *rtk, *dev; struct { u8 dptx_endpoint; bool dptx_controller; int iomfb_method_profile; } hw; }; static u32 advertised; static bool apple_rtkit_has_endpoint(void *rtk, int ep) { return advertised & (1u << (ep - 0x20)); } @@ -122,12 +125,13 @@ def table(name): for (unsigned ext = 0; ext < 2; ext++) for (unsigned m = 0; m < 6; m++) for (unsigned p = 0; p < 3; p++) - for (unsigned c = 0; c < 2; c++) { - struct apple_dcp d = { .fw_compat = fws[f], .dcpext = ext, + for (unsigned c = 0; c < 2; c++) + for (unsigned r = 0; r < 2; r++) { + struct apple_dcp d = { .fw_compat = fws[f], .dcpext = ext, .nr_typec_routes = 2 * r, .hw.dptx_endpoint = pins[p], .hw.dptx_controller = c }; struct apple_dcp before = d; bool both = (maps[m] & BIT(0x24)) && (maps[m] & BIT(0x2a)); - bool chosen = fws[f] == DCP_FIRMWARE_V_27_0 && ext && !pins[p] && both; + bool chosen = fws[f] == DCP_FIRMWARE_V_27_0 && (ext || r) && !pins[p] && both; advertised = maps[m]; info_lines = 0; @@ -175,4 +179,4 @@ def table(name): run = subprocess.run([str(exe)]) if run.returncode: sys.exit(f'FAIL: the layout matrix exited {run.returncode}') -print('PASS firmware-27 dcpext DPTX layout from its advertised endpoints; pinned and other processors unchanged') +print('PASS firmware-27 dcpext / Type-C-routed DCP DPTX layout from its advertised endpoints; pinned and other processors unchanged') diff --git a/tools/asahi/dcp14-panel-tests.py b/tools/asahi/dcp14-panel-tests.py index 0abcd1e89d3f93..8238ce559ebe69 100755 --- a/tools/asahi/dcp14-panel-tests.py +++ b/tools/asahi/dcp14-panel-tests.py @@ -32,12 +32,16 @@ #define IS_ERR(p) ((uintptr_t)(p) >= (uintptr_t)-4095) #define dev_err(...) ((void)0) #define MAX_NOTCH_HEIGHT 100 - struct device_node {const char *compatible;}; + struct device_node {const char *compatible;struct device_node *panel;}; + #define __free(x) struct device {struct device_node *of_node;}; static const char *machine; static bool of_device_is_compatible(const struct device_node *n,const char *c){return !strcmp(n->compatible,c);} static bool of_machine_is_compatible(const char*c){return !strcmp(machine,c);} - static struct device_node fb={"simple-framebuffer"},dcp={"apple,t8122-dcp"}; + /* The board DT's panel node under the DCP (compatible NULL: no panel node). */ + static struct device_node panel={NULL}; + static struct device_node fb={"simple-framebuffer"},dcp={"apple,t8122-dcp",&panel}; + static struct device_node *of_get_child_by_name(const struct device_node*n,const char*name){return strcmp(name,"panel")||!n->panel->compatible?NULL:n->panel;} static u32 width,height,stride,notch,marker_value=1; static const char *image_uuid; static int of_property_read_string(struct device_node*n,const char*k,const char**v){*v=image_uuid;return 0;} @@ -76,7 +80,12 @@ #ifdef OLD assert(IS_ERR(b));puts("old J615 board selection rejects: PASS");return 0; #else - assert(!IS_ERR(b) && b && b->panel_width==2880 && b->panel_height==1864); + assert(IS_ERR(b)); + panel.compatible="apple,panel-j615"; + b=iomfb_v14_7_board(&dev); + assert(!IS_ERR(b) && b && b->panel_width==2880 && b->panel_height==1864 && b->panel_nits); + machine="apple,other";assert(iomfb_v14_7_board(&dev)==b); + panel.compatible=NULL; assert(!strcmp(b->firmware_uuid,"90F849E1-B422-367E-B389-50246F8DEC47")); assert(!strcmp(b->handoff,"apple,t8122-handoff") && !b->promotion); image_uuid=b->firmware_uuid;assert(probe_gate(&dev,b)==0); @@ -87,7 +96,31 @@ machine="apple,j613";const struct dcp_v14_board*j=iomfb_v14_7_board(&dev); assert(!IS_ERR(j)&&j->panel_width==2560 && j->panel_height==1664); machine="apple,j700";assert(IS_ERR(iomfb_v14_7_board(&dev))); + /* J504 (14" M3 MacBook Pro): the J613 image, the J514 panel, 60 or 120 Hz. */ + /* Its record follows the panel node the J504 DT puts under the DCP, not the machine. */ machine="apple,j504";assert(IS_ERR(iomfb_v14_7_board(&dev))); + panel.compatible="apple,panel-j514";assert(IS_ERR(iomfb_v14_7_board(&dev))); + panel.compatible="apple,panel-j504";const struct dcp_v14_board*p14=iomfb_v14_7_board(&dev); + assert(!IS_ERR(p14)&&p14&&!strcmp(p14->name,"J504")&&!strcmp(p14->debugfs,"dcp-j504")); + assert(p14->panel_width==3024&&p14->panel_height==1964&&p14->promotion&&p14->log_bringup); + assert(!strcmp(p14->firmware_uuid,"90F849E1-B422-367E-B389-50246F8DEC47")); + assert(!strcmp(p14->handoff,"apple,t8122-handoff")&&p14->panel_nits&&!p14->swap_timestamps); + assert(p14->ctm_set==A(421)&&p14->ctm_get==A(420)); + image_uuid=p14->firmware_uuid;assert(probe_gate(&dev,p14)==0); + image_uuid="C042E95C-B9D8-3F0E-94B3-582A08AA6FDD";assert(probe_gate(&dev,p14)==-ENODEV); + image_uuid="F493F03E-CC40-3D89-9A08-5F259BA2B246";assert(probe_gate(&dev,p14)==-ENODEV); + image_uuid=NULL;assert(probe_gate(&dev,p14)==-ENODEV); + image_uuid=p14->firmware_uuid;marker_value=0;assert(probe_gate(&dev,p14)==-ENODEV);marker_value=1; + {struct apple_dcp_v14 q={.dev=&dev,.board=p14};width=3024;height=1890;stride=width*4;notch=74; + assert(dcp_v14_geometry(&q)==0&&q.panel_height==1964&&q.notch_rows==74); + height=1964;notch=0;assert(dcp_v14_geometry(&q)==0&&q.panel_height==1964); + width=2560;height=1600;stride=width*4;notch=64;assert(dcp_v14_geometry(&q)==-EINVAL);} + /* J613 keeps its machine record; J615 and J504 match the panel. */ + machine="apple,j613";assert(iomfb_v14_7_board(&dev)==j); + /* Other T8122 Macs (J433/J434 iMacs, no J504 panel) have no record. */ + panel.compatible=NULL; + machine="apple,j433";assert(IS_ERR(iomfb_v14_7_board(&dev))); + machine="apple,j434";assert(IS_ERR(iomfb_v14_7_board(&dev))); dcp.compatible="apple,t6030-dcp";machine="apple,j516s";assert(iomfb_v14_7_board(&dev)==&dcp_v14_board_t6030); dcp.compatible="apple,t8122-dcp"; struct apple_dcp_v14 v={.dev=&dev,.board=b};width=2880;height=1800;stride=width*4;notch=64; @@ -139,7 +172,7 @@ machine="apple,j613";assert(IS_ERR(iomfb_v14_7_board(&dev))); machine="apple,j516m";assert(IS_ERR(iomfb_v14_7_board(&dev))); dcp.compatible="apple,t6030-dcp";machine="apple,j516s";assert(iomfb_v14_7_board(&dev)==&dcp_v14_board_t6030); - puts("current J615/J613/T6030/J516C/J514C admission + hidden/full notch, wrong geometry controls: PASS"); + puts("current J615/J613/J504/T6030/J516C/J514C admission + hidden/full notch, wrong geometry controls: PASS"); #endif } ''' diff --git a/tools/asahi/dcpaud-open-fallback-tests.py b/tools/asahi/dcpaud-open-fallback-tests.py new file mode 100755 index 00000000000000..b2a5befe567bb2 --- /dev/null +++ b/tools/asahi/dcpaud-open-fallback-tests.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the real dcp_pcm_open() over plugged, unplugged, replaced and gone sinks. + +PipeWire and PulseAudio probe a PCM once when its card appears and drop the +output for good if the open fails. dcp_pcm_open() opens an unplugged sink +with a fixed hardware description for that reason. The firmware refuses +calls to an audio service instance it is replacing (it announces the service +again while the display link is set up again): the open then reads from the +successor. A service that is gone opens as unplugged with a cookie no +connection has, so no later stream op (hw_free, native start) takes the sink as +connected. Any other failure still fails the open. + +The fixture compiles dcp_pcm_open() from drivers/gpu/drm/apple/audio.c against +mocks of the ALSA and DMA calls. --mutation names a change to the production +function that the matrix must kill. +""" +import argparse +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +AUDIO = 'drivers/gpu/drm/apple/audio.c' + +MUTATIONS = { + # Fail the open when the instance is being replaced. + 'no-retry': ('\tif (ret == -EINVAL && dcp_audiosrv_replaced(dcpaud->dcp_dev, gen)) {', + '\tif (0 && gen) {'), + # Wait for a successor on any failure, not only a refusal. + 'wait-any': ('\tif (ret == -EINVAL && dcp_audiosrv_replaced(dcpaud->dcp_dev, gen)) {', + '\tif (ret < 0 && dcp_audiosrv_replaced(dcpaud->dcp_dev, gen)) {'), + # Fail the open when the service is gone. + 'gone-fails': ('\tif (ret == -ENODEV) {\n\t\t/*\n\t\t * No instance answers', + '\tif (0) {\n\t\t/*\n\t\t * No instance answers'), + # Keep the live cookie on a gone service: later ops take it as connected. + 'keep-cookie': ('\t\tdcpaud->open_cookie = dcpaud->connection_cookie - 1;\n', ''), + # Turn every failure into an unplugged open. + 'mask-all': ('\tif (ret == -ENODEV) {\n\t\t/*\n\t\t * No instance answers', + '\tif (ret < 0) {\n\t\t/*\n\t\t * No instance answers'), +} + +def block(text, start): + opening = text.index('{', start) + depth = 0 + for end in range(opening, len(text)): + depth += text[end] == '{' + depth -= text[end] == '}' + if not depth: + return text[start:end + 1] + raise AssertionError('unbalanced production block') + +def function(text, name): + match = re.search(r'\n(static [^\n;]*\b' + name + r'\([^;{}]*\)\n)\{', text) + assert match, name + return block(text, match.start(1)) + +HARNESS = r''' +#include +#include +#include +#include +#include +#define dev_dbg(...) ((void)0) +#define IS_ENABLED(x) 1 +typedef unsigned long long u64; +#define SNDRV_PCM_INFO_MMAP 1u +#define SNDRV_PCM_INFO_MMAP_VALID 2u +#define SNDRV_PCM_INFO_INTERLEAVED 4u +#define SNDRV_PCM_INFO_RESUME 8u +#define SNDRV_PCM_HW_PARAM_FORMAT 0 +#define SNDRV_PCM_HW_PARAM_CHANNELS 1 +#define SNDRV_PCM_HW_PARAM_RATE 2 +#define SND_DMAENGINE_PCM_DAI_FLAG_PACK 1 +#define DCPAUD_PERIODS_MAX 64 +#define UNPLUGGED_FORMATS 0x700u +#define PLUGGED_FORMATS 0x7u +struct device { int unused; }; +struct mutex { int held; }; +static void mutex_lock(struct mutex *m) { m->held++; } +static void mutex_unlock(struct mutex *m) { m->held--; } +struct snd_pcm_hardware { unsigned int info; unsigned long long formats; unsigned int channels_min, channels_max; + unsigned int periods_min, periods_max; size_t period_bytes_min, period_bytes_max, buffer_bytes_max, fifo_size; }; +struct snd_pcm_runtime { struct snd_pcm_hardware hw; }; +struct snd_pcm { void *private_data; }; +struct snd_pcm_substream { struct snd_pcm *pcm; struct snd_pcm_runtime *runtime; }; +struct snd_dmaengine_dai_dma_data { unsigned int flags; }; +struct dma_chan { int unused; }; +struct dcp_audio { struct device *dev, *dcp_dev; struct mutex data_lock; bool connected, open_unplugged; + unsigned int open_cookie, connection_cookie; struct dma_chan *chan; }; +static const struct snd_pcm_hardware dcp_pcm_hw = { .formats = PLUGGED_FORMATS }; +static const struct snd_pcm_hardware dcp_pcm_hw_unplugged = { .formats = UNPLUGGED_FORMATS }; +static int init_error, info_errors[2], reads, rules, dma_opens; +static bool replaced, successor_connected; +static struct dcp_audio *cur; +static int dcpaud_init_dma(struct dcp_audio *d) { return init_error; } +static int dcpaud_read_remote_info(struct dcp_audio *d) { return info_errors[reads++ ? 1 : 0]; } +static u64 dcp_audiosrv_instance(struct device *d) { return 4; } +static bool dcp_audiosrv_replaced(struct device *d, u64 gen) +{ + if (gen != 4) + return false; + if (replaced) { + /* the teardown reported the unplug, the successor its sink (or not yet) */ + cur->connected = successor_connected; + cur->connection_cookie += successor_connected ? 1 : 0; + } + return replaced; +} +static int dcpaud_rule_format(void *p, void *r) { return 0; } +static int dcpaud_rule_channels(void *p, void *r) { return 0; } +static int dcpaud_rule_rate(void *p, void *r) { return 0; } +static int snd_pcm_hw_rule_add(struct snd_pcm_runtime *r, unsigned int c, int v, void *f, void *p, ...) +{ rules++; return 0; } +static int snd_dmaengine_pcm_refine_runtime_hwparams(struct snd_pcm_substream *s, + struct snd_dmaengine_dai_dma_data *d, struct snd_pcm_hardware *h, struct dma_chan *c) { return 0; } +static int snd_dmaengine_pcm_open(struct snd_pcm_substream *s, struct dma_chan *c) { dma_opens++; return 0; } +''' + +CHECKS = r''' +static int failures; +#define CHECK(c) do { if (!(c)) { printf("FAIL line %d (%s: %s)\n", __LINE__, name, #c); failures++; } } while (0) + +static int run(bool connected, int ierr, int e0, int e1, bool repl, bool succ, + struct dcp_audio *d, struct snd_pcm_runtime *rt) +{ + static struct snd_pcm pcm; + struct snd_pcm_substream s = { .pcm = &pcm, .runtime = rt }; + + *d = (struct dcp_audio){ .connected = connected, .connection_cookie = 7 }; + *rt = (struct snd_pcm_runtime){ 0 }; + pcm.private_data = d; + cur = d; + init_error = ierr; info_errors[0] = e0; info_errors[1] = e1; + replaced = repl; successor_connected = succ; + reads = rules = dma_opens = 0; + return dcp_pcm_open(&s); +} + +int main(void) +{ + struct dcp_audio d; + struct snd_pcm_runtime rt; + const char *name; + + name = "plugged"; + CHECK(run(true, 0, 0, 0, false, false, &d, &rt) == 0); + CHECK(!d.open_unplugged && rules == 3 && dma_opens == 1 && reads == 1); + CHECK(rt.hw.formats == PLUGGED_FORMATS && dcpaud_connection_up(&d) && !d.data_lock.held); + + name = "unplugged"; + CHECK(run(false, 0, 0, 0, false, false, &d, &rt) == 0); + CHECK(d.open_unplugged && !rules && !reads && rt.hw.formats == UNPLUGGED_FORMATS); + CHECK(!dcpaud_connection_up(&d)); + + name = "replaced, successor plugged"; + CHECK(run(true, 0, -EINVAL, 0, true, true, &d, &rt) == 0); + CHECK(!d.open_unplugged && reads == 2 && rules == 3 && dma_opens == 1); + CHECK(rt.hw.formats == PLUGGED_FORMATS && dcpaud_connection_up(&d) && d.open_cookie == 8); + + name = "replaced, successor not yet plugged"; + CHECK(run(true, 0, -EINVAL, 0, true, false, &d, &rt) == 0); + CHECK(d.open_unplugged && reads == 1 && !rules && !dcpaud_connection_up(&d)); + + name = "replaced, successor refuses too"; + CHECK(run(true, 0, -EINVAL, -EINVAL, true, true, &d, &rt) == -EINVAL); + CHECK(!dma_opens); + + name = "stable service refuses"; + CHECK(run(true, 0, -EINVAL, 0, false, false, &d, &rt) == -EINVAL); + CHECK(!dma_opens && reads == 1); + + name = "persistent error"; + CHECK(run(true, 0, -ENOMEM, 0, false, false, &d, &rt) == -ENOMEM); + CHECK(!dma_opens); + + name = "no memory, a successor published: not waited for"; + CHECK(run(true, 0, -ENOMEM, 0, true, true, &d, &rt) == -ENOMEM); + CHECK(!dma_opens && reads == 1); + + name = "service gone"; + CHECK(run(true, 0, -ENODEV, 0, false, false, &d, &rt) == 0); + CHECK(d.open_unplugged && !rules && dma_opens == 1 && rt.hw.formats == UNPLUGGED_FORMATS); + /* hw_free and native start test only this: the sink is not this open's */ + CHECK(!dcpaud_connection_up(&d) && !d.data_lock.held); + + name = "no-dma"; + CHECK(run(true, -EPROBE_DEFER_, 0, 0, false, false, &d, &rt) == -EPROBE_DEFER_); + CHECK(!dma_opens && !d.data_lock.held); + + if (failures) + return 1; + puts("PASS dcp_pcm_open: plugged, unplugged, replaced instance (successor plugged, not yet, " + "refusing), stable refusal and persistent error fail, gone service opens unplugged " + "and never connected, DMA failure fails"); + return 0; +} +''' + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = parser.parse_args() + + source = (ROOT / AUDIO).read_text() + if args.mutation: + old, new = MUTATIONS[args.mutation] + assert source.count(old) == 1, args.mutation + source = source.replace(old, new) + + code = (HARNESS + '#define EPROBE_DEFER_ 517\n' + function(source, 'dcpaud_connection_up') + + function(source, 'dcp_pcm_open') + CHECKS) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'check.c' + path.write_text(code) + subprocess.run(['clang', '-std=gnu11', '-Wall', '-Werror', '-Wno-unused-function', + '-Wno-unreachable-code', '-fsanitize=address,undefined', str(path), + '-o', str(path.with_suffix(''))], check=True) + sys.exit(subprocess.run([str(path.with_suffix(''))]).returncode) + +if __name__ == '__main__': + main() diff --git a/tools/asahi/dcpaud-sleep-hold-tests.c b/tools/asahi/dcpaud-sleep-hold-tests.c new file mode 100644 index 00000000000000..640472dce91d11 --- /dev/null +++ b/tools/asahi/dcpaud-sleep-hold-tests.c @@ -0,0 +1,260 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * The actual dcp-dp-audio late sleep callback and dev_pm_ops, and the DCP's + * dcp_sleep_keeps_firmware(), against an OF graph and driver-core model that + * counts every node and device reference and checks the device lock. + */ +#include +#include +#include +#include +#include + +/* The harness builds with -Wno-unused-function. */ +#define __maybe_unused +#define pm_sleep_ptr(fn) (fn) +#define EXPORT_SYMBOL_GPL(sym) + +/* ACTUAL_PM_MACROS */ + +struct device_node { + int refs; + bool available; +}; + +struct device_driver { + int unused; +}; + +struct device { + struct device_node *of_node; + int refs; + const struct device_driver *driver; + void *drvdata; + bool locked, set_wakeup_path; +}; + +/* What the DCP's suspend left: see the sites setting it in dcp.c. */ +struct apple_dcp { + bool sleep_fw_runs; +}; + +struct platform_device { + struct device dev; +}; + +struct dev_pm_ops { + int (*prepare)(struct device *dev); + int (*suspend)(struct device *dev); + int (*resume)(struct device *dev); + int (*freeze)(struct device *dev); + int (*thaw)(struct device *dev); + int (*poweroff)(struct device *dev); + int (*restore)(struct device *dev); + int (*suspend_late)(struct device *dev); + int (*resume_early)(struct device *dev); + int (*freeze_late)(struct device *dev); + int (*thaw_early)(struct device *dev); + int (*poweroff_late)(struct device *dev); + int (*restore_early)(struct device *dev); + int (*runtime_suspend)(struct device *dev); + int (*runtime_resume)(struct device *dev); + int (*runtime_idle)(struct device *dev); +}; + +/* The model: the dpaudio node, its endpoint, the DCP node and device. */ +static struct device_node audio_node, endpoint_node, dcp_node; +static struct platform_device dcp_pdev; +static const struct device_driver dcp_driver; +static struct apple_dcp dcp_state; +static struct device audio_dev = { .of_node = &audio_node }; +static bool have_endpoint, have_remote, have_pdev; +static int force_suspend_ret, force_suspend_calls, find_calls; + +static void get_node(struct device_node *np) +{ + assert(np->refs >= 0); + np->refs++; +} + +static void of_node_put(struct device_node *np) +{ + if (!np) + return; + assert(np == &endpoint_node || np == &dcp_node); + assert(np->refs > 0); + np->refs--; +} + +static struct device_node *of_graph_get_endpoint_by_regs(const struct device_node *parent, + int port, int reg) +{ + assert(parent == &audio_node && port == 0 && reg == 0); + if (!have_endpoint) + return NULL; + get_node(&endpoint_node); + return &endpoint_node; +} + +static struct device_node *of_graph_get_remote_port_parent(const struct device_node *np) +{ + assert(np == &endpoint_node && endpoint_node.refs > 0); + if (!have_remote) + return NULL; + get_node(&dcp_node); + return &dcp_node; +} + +static bool of_device_is_available(const struct device_node *np) +{ + assert(np == &dcp_node && dcp_node.refs > 0); + return np->available; +} + +static struct platform_device *of_find_device_by_node(struct device_node *np) +{ + assert(np == &dcp_node && dcp_node.refs > 0); + find_calls++; + if (!have_pdev) + return NULL; + dcp_pdev.dev.refs++; + return &dcp_pdev; +} + +static void put_device(struct device *dev) +{ + assert(dev == &dcp_pdev.dev && dev->refs > 0); + dev->refs--; +} + +/* The driver core's contract: driver and driver data are read under the lock. */ +static void device_lock(struct device *dev) +{ + assert(dev == &dcp_pdev.dev && dev->refs > 0 && !dev->locked); + dev->locked = true; +} + +static void device_unlock(struct device *dev) +{ + assert(dev == &dcp_pdev.dev && dev->locked); + dev->locked = false; +} + +static void *dev_get_drvdata(const struct device *dev) +{ + assert(dev == &dcp_pdev.dev && dev->locked && dev->driver); + return dev->drvdata; +} + +static void device_set_wakeup_path(struct device *dev) +{ + assert(dev == &audio_dev); + dev->set_wakeup_path = true; +} + +static int pm_runtime_force_suspend(struct device *dev) +{ + assert(dev == &audio_dev); + force_suspend_calls++; + return force_suspend_ret; +} + +static int pm_runtime_force_resume(struct device *dev) +{ + (void)dev; + return 0; +} + +/* The rest of the driver's callbacks only have to be distinct symbols. */ +static int dcpaud_pm_prepare(struct device *dev) +{ + (void)dev; + return 1; +} + +static int dcpaud_system_suspend(struct device *dev) +{ + (void)dev; + return 2; +} + +static int dcpaud_suspend(struct device *dev) +{ + (void)dev; + return 3; +} + +static int dcpaud_resume(struct device *dev) +{ + (void)dev; + return 4; +} + +/* ACTUAL_DCP_FUNCTION */ + +/* ACTUAL_FUNCTION */ + +/* ACTUAL_PM_OPS */ + +int main(void) +{ + unsigned int cases = 0, held = 0; + + for (unsigned int bits = 0; bits < 128; bits++) { + bool expect; + int ret; + + have_endpoint = bits & 1; + have_remote = bits & 2; + dcp_node.available = bits & 4; + have_pdev = bits & 8; + dcp_pdev.dev.driver = bits & 16 ? &dcp_driver : NULL; + dcp_pdev.dev.drvdata = bits & 16 ? &dcp_state : NULL; + dcp_state.sleep_fw_runs = bits & 32; + dcp_pdev.dev.locked = false; + force_suspend_ret = bits & 64 ? -EBUSY : 0; + endpoint_node.refs = dcp_node.refs = dcp_pdev.dev.refs = 0; + audio_dev.set_wakeup_path = false; + force_suspend_calls = find_calls = 0; + + /* The PM core calls the late slot for every system sleep. */ + ret = dcpaud_pm_ops.suspend_late(&audio_dev); + + expect = have_endpoint && have_remote && dcp_node.available && have_pdev && + (!dcp_pdev.dev.driver || dcp_state.sleep_fw_runs); + if (audio_dev.set_wakeup_path != expect) + fprintf(stderr, "case %#x: wakeup path %d, expected %d\n", bits, + audio_dev.set_wakeup_path, expect); + assert(audio_dev.set_wakeup_path == expect); + /* Every reference taken is dropped, whatever the topology. */ + assert(!endpoint_node.refs && !dcp_node.refs && !dcp_pdev.dev.refs); + assert(!dcp_pdev.dev.locked); + /* An unavailable or missing DCP node is never looked up. */ + if (!(have_endpoint && have_remote && dcp_node.available)) + assert(!find_calls); + /* The runtime PM force-suspend always runs and its result is returned. */ + assert(force_suspend_calls == 1); + assert(ret == force_suspend_ret); + held += expect; + cases++; + } + + /* The wiring: late suspend and its siblings, then the rest unchanged. */ +#ifdef HAVE_SUSPEND_LATE + assert(dcpaud_pm_ops.suspend_late == dcpaud_suspend_late); + assert(dcpaud_pm_ops.freeze_late == dcpaud_suspend_late); + assert(dcpaud_pm_ops.poweroff_late == dcpaud_suspend_late); +#endif + assert(dcpaud_pm_ops.resume_early == pm_runtime_force_resume); + assert(dcpaud_pm_ops.thaw_early == pm_runtime_force_resume); + assert(dcpaud_pm_ops.restore_early == pm_runtime_force_resume); + assert(dcpaud_pm_ops.prepare == dcpaud_pm_prepare); + assert(dcpaud_pm_ops.suspend == dcpaud_system_suspend); + assert(!dcpaud_pm_ops.resume); + assert(dcpaud_pm_ops.runtime_suspend == dcpaud_suspend); + assert(dcpaud_pm_ops.runtime_resume == dcpaud_resume); + + printf("%u late-suspend cases passed, %u hold the dp-audio domain; pm ops wired\n", + cases, held); + return 0; +} diff --git a/tools/asahi/dcpaud-sleep-hold-tests.py b/tools/asahi/dcpaud-sleep-hold-tests.py new file mode 100755 index 00000000000000..142a69ccb941c3 --- /dev/null +++ b/tools/asahi/dcpaud-sleep-hold-tests.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the actual dcp-dp-audio late sleep callback over every DCP topology. + +genpd powers the dp-audio domain off at noirq unless the device is on the +wakeup path, and cutting it under running DCP firmware resets the J473 on +s2idle. dcpaud_suspend_late() puts dp-audio on the wakeup path when the DCP +linked by its OF graph exists and is unbound or kept its firmware running +through the sleep (dcp_sleep_keeps_firmware()); a DCP that stopped its +firmware (S2R, the 27.x sleep, an M4 stop) leaves the domain to genpd. The +fixture builds the real function and the real dcpaud_pm_ops (with the +kernel's PM_OPS macros) from drivers/gpu/drm/apple/audio.c, and the real +dcp_sleep_keeps_firmware() from dcp.c, against an OF graph and driver-core +model that counts every node and device reference and checks that the +DCP's driver data is read under its device lock. + +--mutation names a change to a production function that the matrix must +kill. --ref reads audio.c from an older revision: before the fix the late +slot was pm_runtime_force_suspend, which never holds the domain, so the +matrix fails (the old-code negative control). +""" +import argparse +import json +import os +import re +import resource +import subprocess +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +AUDIO = "drivers/gpu/drm/apple/audio.c" +DCP = "drivers/gpu/drm/apple/dcp.c" +PM = "include/linux/pm.h" + +# (file, old, new): each must apply exactly once and the matrix must kill it. +MUTATIONS = { + # Hold only for a bound DCP that kept its firmware; an unbound DCP loses the domain. + "bound-only": ("dcp", "runs = !dev->driver || (dcp && dcp->sleep_fw_runs);", + "runs = dcp && dcp->sleep_fw_runs;"), + # Hold for any bound DCP, also one that stopped its firmware for the sleep. + "stopped-holds": ("dcp", "(dcp && dcp->sleep_fw_runs)", "(dcp != NULL)"), + # Hold for a bound DCP that stopped its firmware, not for one that kept it. + "invert-runs": ("dcp", "(dcp && dcp->sleep_fw_runs)", "(dcp && !dcp->sleep_fw_runs)"), + # Read the driver data without the device lock. + "no-lock": ("dcp", "\tdevice_lock(dev);\n", ""), + # Leak the DCP device reference from of_find_device_by_node(). + "leak-device": ("audio", "\t\tput_device(&dcp_pdev->dev);\n", ""), + # Leak the DCP node reference from of_graph_get_remote_port_parent(). + "leak-node": ("audio", "\tof_node_put(dcp_node);\n", ""), + # Back to the wakeup-path test that also held for a stopped DCP. + "ignore-dcp": ("audio", "if (dcp_sleep_keeps_firmware(&dcp_pdev->dev))", "if (true)"), +} + + +def block(text, start): + begin = text.index("{", start) + depth, end = 1, begin + 1 + while depth: + depth += (text[end] == "{") - (text[end] == "}") + end += 1 + return end + + +def function(text, name): + match = re.search(r"^static [^\n;]*\bint " + name + r"\(struct device \*dev\)\n\{", + text, re.M) + if not match: + return None + return text[match.start():block(text, match.start())] + + +def dcp_function(text): + match = re.search(r"^bool dcp_sleep_keeps_firmware\(struct device \*dev\)\n\{", text, re.M) + if not match: + return None + return text[match.start():block(text, match.start())] + + +def pm_ops(text): + start = text.index("static const struct dev_pm_ops dcpaud_pm_ops = {") + return text[start:block(text, start)] + ";\n" + + +def macro(text, name): + match = re.search(r"^#define " + name + r"\(.*?[^\\]\n", text, re.M | re.S) + assert match, name + return match.group() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) + parser.add_argument("--ref", help="read audio.c from this revision") + parser.add_argument("--mutation", choices=sorted(MUTATIONS)) + parser.add_argument("--out", type=Path) + args = parser.parse_args() + + if args.ref: + audio, dcp = (subprocess.check_output(["git", "show", f"{args.ref}:{path}"], + cwd=ROOT, text=True) for path in (AUDIO, DCP)) + else: + audio, dcp = ((ROOT / path).read_text() for path in (AUDIO, DCP)) + pm = (ROOT / PM).read_text() + late = function(audio, "dcpaud_suspend_late") + keeps = dcp_function(dcp) + if args.mutation: + where, old, new = MUTATIONS[args.mutation] + body = late if where == "audio" else keeps + if not body or body.count(old) != 1: + raise RuntimeError(f"mutation {args.mutation} did not apply exactly once") + if where == "audio": + late = late.replace(old, new) + else: + keeps = keeps.replace(old, new) + + macros = "".join(macro(pm, name) for name in + ("SYSTEM_SLEEP_PM_OPS", "LATE_SYSTEM_SLEEP_PM_OPS", "RUNTIME_PM_OPS")) + code = (Path(__file__).with_suffix(".c").read_text() + .replace("/* ACTUAL_PM_MACROS */", macros) + .replace("/* ACTUAL_DCP_FUNCTION */", keeps or "") + .replace("/* ACTUAL_FUNCTION */", late or "") + .replace("/* ACTUAL_PM_OPS */", pm_ops(audio))) + + def run(out): + out.mkdir(parents=True, exist_ok=True) + source, binary = out / "dcpaud-sleep-hold.c", out / "dcpaud-sleep-hold" + source.write_text(code) + subprocess.run([os.environ.get("CC", "cc"), "-std=gnu11", "-O1", "-g", "-Wall", + "-Wextra", "-Werror", "-Wno-unused-function", + "-fsanitize=address,undefined", + "-fno-sanitize-recover=all"] + + (["-DHAVE_SUSPEND_LATE"] if late else []) + + [str(source), "-o", str(binary)], check=True) + result = subprocess.run([str(binary)], capture_output=True, text=True) + (out / "results.json").write_text(json.dumps({ + "exit": result.returncode, + "stdout": result.stdout, + "stderr": result.stderr, + "ref": args.ref, + "mutation": args.mutation, + "limits": "OF graph, driver core and runtime PM are host models; no genpd, no DCP.", + }, indent=2) + "\n") + print(result.stdout + result.stderr, end="") + return result.returncode != 0 + + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + if args.out: + return run(args.out.resolve()) + with tempfile.TemporaryDirectory(prefix="dcpaud-sleep-hold-") as out: + return run(Path(out)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/asahi/dcpext26-crossbar-union-tests.py b/tools/asahi/dcpext26-crossbar-union-tests.py index 9607ad8ee202e2..b6291bcf915531 100644 --- a/tools/asahi/dcpext26-crossbar-union-tests.py +++ b/tools/asahi/dcpext26-crossbar-union-tests.py @@ -44,7 +44,7 @@ def function(text, name): #include #include enum { DCP_FIRMWARE_V_27_0 = 27, DCP_IOMFB_METHODS_J613_EXT26 = 26 }; -struct device_node { const char *compatible; }; +struct device_node { const char *compatible; bool v27_2; }; struct device { struct device_node *of_node; }; struct mux_control { int id; }; struct apple_dcp_typec_route { @@ -68,6 +68,10 @@ def function(text, name): static bool of_device_is_compatible(const struct device_node *n, const char *name) { return !strcmp(n->compatible, name); } +/* The J773g's 27.2 (26B123) dcpext admission, include/linux/soc/apple/display.h. */ +static bool apple_t8132_dcpext_v27_2(const struct device_node *n) { + return of_device_is_compatible(n, "apple,t8132-dcpext") && n->v27_2; +} static void mock_guard(int *lock) { (void)lock; locks++; } #define guard(kind) mock_guard #define dev_warn(...) ((void)0) @@ -81,7 +85,7 @@ def function(text, name): cases = r''' static void reset(void) { links = v27 = locks = 0; last = NULL; last_up = false; fault = 0; } int main(void) { - struct device_node node = { "apple,other-dcp" }; + struct device_node node = { .compatible = "apple,other-dcp" }; struct device dev = { &node }; struct mux_control a = {1}, b = {2}; struct apple_dcp_typec_route route = { .xbar = &a, .selected = true }; @@ -128,16 +132,25 @@ def function(text, name): reset(); assert(dcp_direct_crossbar_link(&d, true) == 0); assert(v27 == 0 && links == 1 && locks == 1); } + /* A J773g dcpext on firmware 27.2 is no M4 dcpext: it links as a T6041 firmware-27 one. */ + machine = "apple,other"; node.compatible = "apple,t8132-dcpext"; node.v27_2 = true; + struct apple_dcp j773g = { .dev = &dev, .active_typec_route = &route, + .fw_compat = DCP_FIRMWARE_V_27_0, .desktop_external = true }; + assert(!dcp_is_t8132_ext(&j773g)); + reset(); assert(dcp_direct_crossbar_link(&j773g, true) == 0); + assert(v27 == 0 && links == 1 && locks == 1 && j773g.direct_xbar_up == &a); + node.v27_2 = false; machine = "apple,other"; node.compatible = "apple,other-dcp"; struct apple_dcp unrelated = { .dev = &dev, .active_typec_route = &route }; reset(); assert(dcp_direct_crossbar_link(&unrelated, true) == 0); assert(links == 0 && locks == 0); - puts("PASS production crossbar union, route/cache/error behavior, V27 precedence and unrelated exclusion"); + puts("PASS production crossbar union, route/cache/error behavior, V27 precedence, J773g 27.2 and unrelated exclusion"); return 0; } ''' unit = pre + function(header, 'dcp_is_ext26') + '\n' unit += function(source, 'dcp_t6041_ext_v27') + '\n' +unit += function(source, 'dcp_t8132_ext_m4_node') + '\n' unit += function(source, 'dcp_is_t8132_ext') + '\n' + link + '\n' + cases with tempfile.TemporaryDirectory() as tmp: c = Path(tmp) / 'crossbar.c' diff --git a/tools/asahi/dcpext26-parity-tests.py b/tools/asahi/dcpext26-parity-tests.py index 08e8fddb71e0ff..bbdff169ae2e9a 100644 --- a/tools/asahi/dcpext26-parity-tests.py +++ b/tools/asahi/dcpext26-parity-tests.py @@ -158,7 +158,8 @@ def run(name,code): struct apple_epic_service {bool pending_open,enabled;const struct apple_epic_service_ops *ops;const char *pending_name,*pending_class;int pending_unit;u32 channel;}; struct apple_dcp {bool ext26_services_open;struct apple_dcp_afkep *dptxep;}; static bool dptx_native_controllers_ready(struct apple_dcp *d){return true;} -struct apple_dcp_afkep {struct apple_dcp *dcp;unsigned num_channels;struct apple_epic_service services[2];}; +struct apple_dcp_afkep {struct apple_dcp *dcp;unsigned num_channels;struct apple_epic_service services[2];int service_wq;}; +#define wake_up_all(q) ((void)(q)) static bool dcp_is_ext26(struct apple_dcp *d){return true;} static unsigned sent,published,discarded,initialized;static int fault; static void afk_discard_pending_open(struct apple_epic_service *s){discarded++;s->pending_open=false;} diff --git a/tools/asahi/dcpext26-present-tests.py b/tools/asahi/dcpext26-present-tests.py index 56b3e26d73841c..bdc3accb16580b 100644 --- a/tools/asahi/dcpext26-present-tests.py +++ b/tools/asahi/dcpext26-present-tests.py @@ -26,7 +26,6 @@ def function(name): #define DCP_FW_VER 0 #define dev_err(...) ((void)0) #define trace_iomfb_swap_submit(...) ((void)0) -struct dc_swap_complete_resp { u32 swap_id; }; struct dcp_swap_submit_resp { u32 ret; }; struct dcp_swap_start_resp { u32 swap_id,ret; }; struct apple_dcp { bool native,crashed,ext26_blocked,ext26_early_complete;u32 ext26_early_id,started_swap_id; @@ -40,7 +39,13 @@ def function(name): static bool dcp_present_retires(struct apple_dcp *d) { (void)d;return true; } static void dcp_unarm_retained_framebuffers(struct apple_dcp *d,u32 id) { (void)d;(void)id; } static void dcp_drm_crtc_vblank(void *c) { (void)c;events++; } -static void dcpep_cb_swap_complete(struct apple_dcp *d,struct dc_swap_complete_resp *r) { assert(r->swap_id==d->swap.h17p.swap.swap_id);completed++;completion_time=d->ext26_rx_ns; } +static void dcp_swap_complete_id(struct apple_dcp *d, u32 id, bool shown) +{ + assert(id == d->swap.h17p.swap.swap_id); + assert(!shown); + completed++; + completion_time = d->ext26_rx_ns; +} static u64 ktime_get(void) { return 30; } static u64 dcp_swap_time(void) { return 40; } static void dcp_swap_watchdog_arm(struct apple_dcp *d) { (void)d;watchdogs++; } diff --git a/tools/asahi/dcpext26-queue-tests.py b/tools/asahi/dcpext26-queue-tests.py index 76a4cafd6899bc..983a57a65ee25a 100644 --- a/tools/asahi/dcpext26-queue-tests.py +++ b/tools/asahi/dcpext26-queue-tests.py @@ -55,11 +55,12 @@ def function(name): struct drm_framebuffer {struct obj *obj[1];int refs;}; static void drm_framebuffer_get(struct drm_framebuffer *f){assert(f->refs>0);f->refs++;} static void drm_framebuffer_put(struct drm_framebuffer *f){assert(f->refs>1);f->refs--;} -struct drm_crtc {int unused;}; struct drm_plane {unsigned iomfb_surf;}; +struct drm_crtc {struct drm_plane *primary;}; #define to_apple_plane(p) (p) struct drm_plane_state {struct drm_crtc *crtc;bool visible;struct drm_framebuffer *fb;}; struct drm_atomic_commit {int refs,count;struct drm_plane plane[4];struct drm_plane_state old[4],new[4];}; +static struct drm_plane_state *drm_atomic_get_new_plane_state(struct drm_atomic_commit *s,struct drm_plane *p){for(int i=0;icount;i++)if(&s->plane[i]==p)return &s->new[i];return NULL;} #define for_each_oldnew_plane_in_state(s,p,o,n,i) for(i=0;i<(s)->count&&((p)=&(s)->plane[i],(o)=&(s)->old[i],(n)=&(s)->new[i],1);i++) static struct drm_atomic_commit *drm_atomic_commit_get(struct drm_atomic_commit *s){s->refs++;return s;} static void drm_atomic_commit_put(struct drm_atomic_commit *s){assert(s->refs>1);s->refs--;} @@ -79,7 +80,7 @@ def function(name): struct {bool pending;} present_state_h17p;struct {bool valid;} mode_state;struct {bool connected;} *connector; struct {void *data;} chunks;bool native,crashed,ext26_control_pending,ext26_blanked,ext26_normal,ext26_early_complete; unsigned ext26_epochs;u64 ext26_retained_bytes;struct list_head ext26_retained; - int fw_compat;struct work_struct vblank_wq,bl_update_wq; + int fw_compat;bool boot_surface_pending;struct work_struct vblank_wq,bl_update_wq; }; static void iomfb_v27_sleep_start(struct apple_dcp *d, struct iomfb_transaction *t) { } #define DCP_FIRMWARE_V_27_0 27 diff --git a/tools/asahi/dcpext26-startup-tests.py b/tools/asahi/dcpext26-startup-tests.py index 0811ada7ce526c..6d2fba8014404f 100644 --- a/tools/asahi/dcpext26-startup-tests.py +++ b/tools/asahi/dcpext26-startup-tests.py @@ -59,6 +59,7 @@ def run(name,code,reject=False): #define kmalloc(n,f) malloc(n) #define kzalloc_obj(v) calloc(1,sizeof(v)) #define kfree(p) free((void *)(p)) +#define kstrdup(s,f) strdup(s) #define max(a,b) ((a)>(b)?(a):(b)) #define dev_info(...) ((void)0) #define dev_err(...) ((void)0) @@ -90,11 +91,12 @@ def run(name,code,reject=False): #define MAX_PENDING_CMDS 16 struct dcp_parse_ctx {void *dcp;const void *blob;u32 pos,len;}; struct apple_epic_service;struct apple_dcp_afkep; -struct apple_epic_service_ops {const char *name;bool reusable,optional,open_later;int (*prepare)(struct apple_epic_service *,const char *,const char *,s64);int (*revalidate)(struct apple_epic_service *,const char *,const char *,s64);void (*init)(struct apple_epic_service *,const char *,const char *,s64);void (*teardown)(struct apple_epic_service *);void (*init_props)(struct apple_epic_service *,s64,const void *,size_t);}; +struct apple_epic_service_ops {const char *name;bool reusable,optional,open_later,singleton;int (*prepare)(struct apple_epic_service *,const char *,const char *,s64);int (*revalidate)(struct apple_epic_service *,const char *,const char *,s64);void (*init)(struct apple_epic_service *,const char *,const char *,s64);void (*teardown)(struct apple_epic_service *);void (*init_props)(struct apple_epic_service *,s64,const void *,size_t);}; struct apple_epic_service {struct apple_dcp_afkep *ep;const struct apple_epic_service_ops *ops;bool enabled,torndown,pending_open,defer_start;unsigned users;int lock;u32 channel;void *cookie;const char *pending_name,*pending_class;s64 pending_unit;int cmd_map[1];}; struct dptx_port {struct apple_epic_service *service;s64 unit;bool enabled,connected;int enable_completion;}; -struct apple_dcp {const void *push_out_prefill;bool native,ext26_services_open,v27_j714s,v27_sleep_transport,dcpext;int fw_compat,index,dptx_controller_ready;struct {unsigned num_dptx_ports;int iomfb_method_profile,firmware_compat;} hw;struct dptx_port dptxport[2];void *dev;struct apple_dcp_afkep *systemep,*ibootep,*dptx_controller_ep,*dcpavservep,*dptxep,*ext26_aux[3];}; -struct apple_dcp_afkep {struct apple_dcp *dcp;u32 endpoint,num_channels;bool wire_v2,stopping,match_epic_name,compact;int lock;void *wq,*service_work;const struct apple_epic_service_ops *ops;struct apple_epic_service services[AFK_MAX_CHANNEL];}; +struct apple_dcp {const void *push_out_prefill;bool native,ext26_services_open,v27_j714s,v27_sleep_transport,dcpext;int fw_compat,index,dptx_controller_ready;struct {unsigned num_dptx_ports;int iomfb_method_profile,firmware_compat;bool afk_announced_names;} hw;struct dptx_port dptxport[2];void *dev;struct apple_dcp_afkep *systemep,*ibootep,*dptx_controller_ep,*dcpavservep,*dptxep,*ext26_aux[3];}; +struct apple_dcp_afkep {struct apple_dcp *dcp;u32 endpoint,num_channels;bool wire_v2,stopping,match_epic_name,compact;int lock;void *wq,*service_work;const struct apple_epic_service_ops *ops,*unmatched_ops;struct apple_epic_service services[AFK_MAX_CHANNEL];int service_wq;}; +#define wake_up_all(q) ((void)(q)) static bool dcp_is_ext26(struct apple_dcp *d){return d->native;} static bool dcp_fail_stop(struct apple_dcp *d){return d->native;} static bool dcp_is_v14_7_external(struct apple_dcp *d){return false;} @@ -106,6 +108,7 @@ def run(name,code,reject=False): static unsigned opened[256][16],queued,published; static int open_error; static void afk_populate_service_debugfs(struct apple_epic_service *s){} +static void afk_remove_service_debugfs(struct apple_epic_service *s){} static void afk_recv_handle_teardown(struct apple_dcp_afkep *e,u32 c){} static void afk_retry_service_init(struct apple_dcp_afkep *ep); void afk_service_retry(struct apple_dcp_afkep *ep); @@ -117,7 +120,7 @@ def run(name,code,reject=False): # Drop the audio-only helper region from the extracted prefix. identity=re.sub(r'#if IS_ENABLED\(CONFIG_DRM_APPLE_AUDIO\).*?#endif','',identity,flags=re.S) identity+=block(parser,'struct iterator {')+'\n'+fn(parser,'iterator_begin')+'\n'+fn(parser,'parse')+'\n'+fn(parser,'parse_epic_service_init')+'\n' -for name in ['afk_service_reclaimable','afk_service_reinit','afk_service_discard','afk_service_publish','afk_service_matches']: +for name in ['afk_service_reclaimable','afk_service_reinit','afk_service_discard','afk_service_publish','afk_service_matches','afk_service_supersede']: identity+=fn(h,name)+'\n' identity+=fn(dptx,'dptx_native_controllers_ready')+'\n'+fn(dptx,'dptx_native_controller_prepare')+'\n'+fn(dptx,'dptx_controller_service_init')+'\n' for name in ['afk_match_service','afk_epic_find_service','afk_discard_pending_open','afk_retry_service_init','afk_service_retry']: @@ -220,6 +223,11 @@ def run(name,code,reject=False): #define current ((void *)1) #define dma_wmb() ((void)0) #define dma_rmb() ((void)0) +#define smp_store_release(p,v) (*(p)=(v)) +#define smp_mb__before_atomic() ((void)0) +typedef int atomic_t; +#define atomic_inc(v) ((*(v))++) +#define atomic_dec(v) ((*(v))--) #define trace_iomfb_push(...) #define IOMFB_METHOD(t,n) [n]={#n,{t[0],t[1],t[2],t[3]},{0},{0}} #define IOMFB_METHOD_H17(t,h,n) [n]={#n,{t[0],t[1],t[2],t[3]},{h[0],h[1],h[2],h[3]},{0}} @@ -228,7 +236,7 @@ def run(name,code,reject=False): struct dcp_method_entry {const char *name;char tag[4],tag_h17g[4],tag_ext26[4];}; ''' transport+=block(ih,'enum dcp_context_id {')+'\n'+block(ih,'struct dcp_packet_header {')+'\n'+block(internal,'struct dcp_channel {')+'\n'+block(ih,'enum dcpep_method {')+r''' -struct apple_dcp {const void *push_out_prefill;void *dev;u8 *shmem;int fw_compat;bool native,crashed,quiescing,ext26_blocked,ext26_power_sent;u64 ext26_power_ns;struct {int iomfb_method_profile;}hw;struct {void *owner;} iomfb;struct dcp_channel ch_cb,ch_cmd,ch_oobcb,ch_oobcmd,ch_async,ch_oobasync;}; +struct apple_dcp {const void *push_out_prefill;void *dev;u8 *shmem;int fw_compat;bool native,crashed,quiescing,ext26_blocked,ext26_power_sent;u64 ext26_power_ns;struct {int iomfb_method_profile;}hw;struct {void *owner;} iomfb;struct dcp_channel ch_cb,ch_cmd,ch_oobcb,ch_oobcmd,ch_async,ch_oobasync;atomic_t pending_acks;}; static bool iomfb_uses_queue(struct apple_dcp *d){return true;} static bool dcp_is_ext26(struct apple_dcp *d){return d->native;} static bool dcp_fail_stop(struct apple_dcp *d){return d->native;} diff --git a/tools/asahi/dcpext26-suspend-route-tests.py b/tools/asahi/dcpext26-suspend-route-tests.py index 8067762a9fc1b6..5201f36841e497 100644 --- a/tools/asahi/dcpext26-suspend-route-tests.py +++ b/tools/asahi/dcpext26-suspend-route-tests.py @@ -58,7 +58,7 @@ def function(text, name): struct apple_dcp { struct { int iomfb_method_profile; } hw; void *coproc_reg; - bool crashed, ext26_blocked, external_suspended; + bool crashed, ext26_blocked, external_suspended, sleep_fw_runs; int external_error; }; static unsigned run=1, parks, unparks, wake_paths, disabled, enabled; @@ -70,6 +70,8 @@ def function(text, name): static void dcp_enable_typec_work(struct apple_dcp *d) { enabled++; } static int dcp_external_disconnect(struct apple_dcp *d,bool wait) { return disconnect_error; } static void device_set_wakeup_path(struct device *d) { wake_paths++; } +/* The DP PHY hold has its own test (dcp-sleep-phy-hold-tests.py). */ +static void dcp_sleep_hold_phys(struct apple_dcp *d) { (void)d; } static void reset_counts(void) { parks=unparks=wake_paths=disabled=enabled=0; } ''' code = pre + function(header, 'dcp_is_ext26') + '\n' + function(source, 'dcp_is_external_h17p') + '\n' + function(source, 'dcp_is_retained_external') @@ -81,19 +83,19 @@ def function(text, name): struct apple_dcp native={.hw.iomfb_method_profile=DCP_IOMFB_METHODS_J613_EXT26, .coproc_reg=(void *)0x1000,.external_suspended=true}; assert(suspend_path(&dev,&native)==0); - assert(parks==0 && disabled==0 && wake_paths==1); + assert(parks==0 && disabled==0 && wake_paths==1 && native.sleep_fw_runs); assert(resume_path(&dev,&native)==0 && unparks==0 && !native.external_suspended); - reset_counts();run=0; - assert(suspend_path(&dev,&native)==-EHOSTDOWN && parks==0 && wake_paths==0); + reset_counts();run=0;native.sleep_fw_runs=false; + assert(suspend_path(&dev,&native)==-EHOSTDOWN && parks==0 && wake_paths==0 && !native.sleep_fw_runs); assert(resume_path(&dev,&native)==-EHOSTDOWN && native.ext26_blocked && native.external_error==-EHOSTDOWN); run=1;reset_counts();disconnect_error=-EBUSY; assert(suspend_path(&dev,&native)==-EBUSY && parks==0 && wake_paths==0 && enabled==0); struct apple_dcp h17p={.hw.iomfb_method_profile=DCP_IOMFB_METHODS_H17P_EXTERNAL}; disconnect_error=0;reset_counts(); - assert(suspend_path(&dev,&h17p)==0 && parks==1 && disabled==1 && wake_paths==1); + assert(suspend_path(&dev,&h17p)==0 && parks==1 && disabled==1 && wake_paths==1 && h17p.sleep_fw_runs); assert(resume_path(&dev,&h17p)==0 && unparks==1); - reset_counts();disconnect_error=-EBUSY; - assert(suspend_path(&dev,&h17p)==-EBUSY && parks==0 && wake_paths==0 && disabled==1 && enabled==1); + reset_counts();disconnect_error=-EBUSY;h17p.sleep_fw_runs=false; + assert(suspend_path(&dev,&h17p)==-EBUSY && parks==0 && wake_paths==0 && disabled==1 && enabled==1 && !h17p.sleep_fw_runs); struct apple_dcp other={0};disconnect_error=0;reset_counts(); assert(suspend_path(&dev,&other)==0 && resume_path(&dev,&other)==0 && parks==0 && unparks==0); } @@ -106,4 +108,5 @@ def function(text, name): result = subprocess.run([str(path.with_suffix(''))]) if result.returncode: sys.exit(1) -print('PASS retained sleep: H17P park/unpark paired; native26 no park, RUN refusal; disconnect rollback preserved') +print('PASS retained sleep: H17P park/unpark paired; native26 no park, RUN refusal; disconnect rollback preserved; ' + 'firmware-runs flag set with the wakeup path only') diff --git a/tools/asahi/display-sleep-merge-tests.py b/tools/asahi/display-sleep-merge-tests.py index a0e9dc8e6f72ff..126a8e6de471c8 100644 --- a/tools/asahi/display-sleep-merge-tests.py +++ b/tools/asahi/display-sleep-merge-tests.py @@ -113,6 +113,7 @@ def run(name, code, negative=False, extra=()): #define READ_ONCE(x) (x) #define IS_ENABLED(x) 1 #define dev_warn(...) ((void)0) +#define dev_warn_ratelimited(...) ((void)0) #define dev_err(...) ((void)0) #define container_of(p,t,m) ((t *)((char *)(p)-offsetof(t,m))) #define APPLE_RTKIT_EP_MGMT 0 @@ -135,6 +136,8 @@ def run(name, code, negative=False, extra=()): STUB(apple_rtkit_management_rx) STUB(apple_rtkit_crashlog_rx) STUB(apple_rtkit_syslog_rx) STUB(apple_rtkit_ioreport_rx) STUB(apple_rtkit_kdebug_rx) STUB(apple_rtkit_pmp_aux_rx) STUB(apple_rtkit_coreanalytics_rx) STUB(apple_rtkit_oslog_rx) +static bool apple_rtkit_ep7_served(struct apple_rtkit *r) { return false; } +static void apple_rtkit_unserved_ep_msg(struct apple_rtkit *r,u8 e,u64 m) {} static void timed_cb(void *c,u8 e,u64 m,u64 ns) { assert(e==0x2a && m==0x1234); timed++; observed=ns; } static void legacy_cb(void *c,u8 e,u64 m) { assert(e==0x2a && m==0x1234); legacy++; } ''' diff --git a/tools/asahi/dpavserv-admission-tests.py b/tools/asahi/dpavserv-admission-tests.py new file mode 100755 index 00000000000000..22e200283b483c --- /dev/null +++ b/tools/asahi/dpavserv-admission-tests.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the actual DP AV service admission check over the output states. + +A DCP takes a DP AV service only while the attachment it was announced for +is current. Every sleep and DPMS cycle moves the DCP's generation on; a +Type-C output then waits for its cable again. A fixed output that no Type-C +display has borrowed (the M2 Mac mini's HDMI port) has no Type-C cable: once +the generation had moved, its converter's AV service was refused for good, +so HDMI lost its EDID and stayed dark after the first sleep. The fixture +builds the real dcpavserv_admission_current() from epic/dpavservep.c and the +real dcp_is_typec_output() from dcp-fabric.c against a small model. + +--mutation names a change to the production function that the matrix must +kill. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DPAV = "drivers/gpu/drm/apple/epic/dpavservep.c" +FABRIC = "drivers/gpu/drm/apple/dcp-fabric.c" + +MUTATIONS = { + # The old check: a fixed output waits for a Type-C cable it never gets. + "old-cable-wait": (DPAV, " || !dcp_is_typec_output(dcp))", ")"), + # Admit a stale announcement from before a sleep. + "ignore-generation": (DPAV, "generation == dcp->typec_generation &&", ""), + # Admit on a borrowed (Type-C) route without its cable. + "ignore-cable": (DPAV, "dcp->typec_cable_connected ||", "true ||"), + # Admit while the DCP is quiescing. + "ignore-quiescing": (DPAV, "!READ_ONCE(dcp->quiescing) && ", ""), +} + +HARNESS = r''' +#include +#include +#include +typedef uint64_t u64; +#define READ_ONCE(x) (x) +#define lockdep_assert_held(x) ((void)(x)) +#define DRM_MODE_CONNECTOR_HDMIA 11 +#define DRM_MODE_CONNECTOR_USB 20 +struct apple_dcp { + int hpd_mutex; + bool quiescing, external_physically_absent, typec_cable_connected; + u64 typec_generation; + void *active_typec_route; + int fixed_connector_type; +}; +@@FUNCS@@ +int main(void) +{ + int route, fail = 0; + struct apple_dcp d; +#define CASE(name, expect, ...) do { d = (struct apple_dcp){ __VA_ARGS__ }; \ + bool got = dcpavserv_admission_current(&d, d.typec_generation); \ + if (got != (expect)) { printf("FAIL line %d %s: got %d\n", __LINE__, name, got); fail++; } \ + else printf("ok %s\n", name); } while (0) +#define STALE(name, ...) do { d = (struct apple_dcp){ __VA_ARGS__ }; \ + bool got = dcpavserv_admission_current(&d, d.typec_generation - 1); \ + if (got) { printf("FAIL line %d %s: stale admitted\n", __LINE__, name); fail++; } \ + else printf("ok %s\n", name); } while (0) + CASE("hdmi at boot", true, .fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA); + CASE("hdmi after a sleep", true, .fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA, .typec_generation = 3); + STALE("hdmi stale announcement", .fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA, .typec_generation = 3); + CASE("hdmi quiescing", false, .fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA, .typec_generation = 3, .quiescing = true); + CASE("hdmi physically absent", false, .fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA, .external_physically_absent = true); + CASE("typec before first attach", true, .active_typec_route = &route); + CASE("typec unplugged", false, .active_typec_route = &route, .typec_generation = 2); + CASE("typec plugged", true, .active_typec_route = &route, .typec_generation = 2, .typec_cable_connected = true); + STALE("typec stale announcement", .active_typec_route = &route, .typec_generation = 2, .typec_cable_connected = true); + CASE("hdmi borrowed by typec, unplugged", false, .fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA, .active_typec_route = &route, .typec_generation = 2); + CASE("fixed usb-c output unplugged", false, .fixed_connector_type = DRM_MODE_CONNECTOR_USB, .typec_generation = 2); + printf("%d failures\n", fail); + return fail != 0; +} +''' + +def extract(path, sig): + src = (ROOT / path).read_text() + m = re.search(r'^%s\(struct apple_dcp \*dcp[^)]*\)\n\{.*?^\}\n' % re.escape(sig), src, re.S | re.M) + if not m: + sys.exit(f"{sig} not found in {path}") + return path, m.group(0) + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--mutation", choices=sorted(MUTATIONS)) + a = ap.parse_args() + parts = [extract(FABRIC, "bool dcp_is_typec_output"), + extract(DPAV, "static bool dcpavserv_admission_current")] + code = [] + for path, text in parts: + if a.mutation and MUTATIONS[a.mutation][0] == path: + old, new = MUTATIONS[a.mutation][1:] + if text.count(old) != 1: + sys.exit(f"mutation {a.mutation} does not apply exactly once") + text = text.replace(old, new) + code.append(text) + with tempfile.TemporaryDirectory() as tmp: + c = Path(tmp) / "t.c" + exe = Path(tmp) / "t" + c.write_text(HARNESS.replace("@@FUNCS@@", "\n".join(code))) + flags = ["-std=gnu11", "-Wall"] + ([] if a.mutation else ["-Werror"]) + subprocess.run([os.environ.get("CC", "cc"), *flags, "-o", exe, c], check=True) + r = subprocess.run([exe], capture_output=True, text=True) + print(r.stdout + r.stderr, end="") + sys.exit(r.returncode) + +if __name__ == "__main__": + main() diff --git a/tools/asahi/dptx-set-active-lane-count-tests.py b/tools/asahi/dptx-set-active-lane-count-tests.py new file mode 100755 index 00000000000000..8f8c5317082a4b --- /dev/null +++ b/tools/asahi/dptx-set-active-lane-count-tests.py @@ -0,0 +1,405 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Active lane-count validation in dptxport_call_set_active_lane_count(). + +Builds the production dptxport_call_set_active_lane_count() from +drivers/gpu/drm/apple/dptxep.c and verifies that fixed non-ATC-PHY outputs +(dcp->dptx_phy > 3, such as HDMI-A ports without an ATC PHY) and USB4 DP +tunnels do not trigger the ATC PHY "unexpected lane count" error when +firmware sets lanes before a max-lane query or after a link-down, while +standard ATC PHY outputs (dptx_phy <= 3) still flag unexpected counts and +invalid lane counts are rejected for all outputs. + +--mutation names a change to the production source that the matrix must kill. +""" +import argparse +import subprocess +import sys +import tempfile +from pathlib import Path + +MUTATIONS = { + # Revert the fixed non-ATC-PHY (dptx_phy > 3) exemption. + 'drop-fixed-phy': ( + ' && !dcp_is_usb4_output(dcp) &&\n\t\t dcp->dptx_phy <= 3)', + ' && !dcp_is_usb4_output(dcp))', + ), + # Suppress the ATC PHY unexpected-lane-count check altogether. + 'skip-all-unexpected': ( + 'dptx->lane_count < lane_count', + '0', + ), +} + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--mutation', choices=sorted(MUTATIONS)) +args = parser.parse_args() + +root = Path(__file__).resolve().parents[2] +dptx_c = (root / 'drivers/gpu/drm/apple/dptxep.c').read_text() + + +def extract_function(source, marker): + start = source.index(marker) + opening = source.index('{', start) + end, depth = opening + 1, 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +fn_src = extract_function( + dptx_c, + 'static int dptxport_call_set_active_lane_count(', +) + +if args.mutation: + old, new = MUTATIONS[args.mutation] + assert fn_src.count(old) == 1, args.mutation + fn_src = fn_src.replace(old, new) + +program = r''' +#include +#include +#include +#include +#include + +typedef uint8_t u8; +typedef uint32_t u32; +typedef unsigned long long u64; +typedef uint32_t __le32; +typedef unsigned long long __le64; + +static inline u64 le64_to_cpu(__le64 v) { return (u64)v; } +static inline __le64 cpu_to_le64(u64 v) { return (__le64)v; } +static inline __le32 cpu_to_le32(u32 v) { return (__le32)v; } +static inline u32 le32_to_cpu(__le32 v) { return (u32)v; } + +struct completion { + unsigned int done; +}; + +struct phy { + int dummy; +}; + +union phy_configure_opts { + struct { + u32 lanes; + bool set_lanes; + } dp; +}; + +struct dptxport_apcall_set_active_lane_count { + __le32 retcode; + u8 _unk0[12]; + __le64 lane_count; + u8 _unk1[8]; +} __attribute__((packed)); + +struct apple_dcp { + void *dev; + u32 dptx_phy; + bool external_h17p; + bool usb4_output; + bool t8132_ext; +}; + +struct apple_dcp_afkep { + struct apple_dcp *dcp; +}; + +struct dptx_port { + struct phy *atcphy; + union phy_configure_opts phy_ops; + u32 lane_count; + struct completion linkcfg_completion; +}; + +struct apple_epic_service { + struct apple_dcp_afkep *ep; + struct dptx_port *cookie; +}; + +static int unexpected_err_calls; +static int invalid_err_calls; +static int other_err_calls; +static int phy_configure_calls; +static int phy_configure_ret; +static int h17p_validate_calls; +static int h17p_validate_ret; +static int hotplug_calls; + +static void record_err(const char *fmt, ...) +{ + if (strstr(fmt, "unexpected lane")) + unexpected_err_calls++; + else if (strstr(fmt, "invalid lane count")) + invalid_err_calls++; + else + other_err_calls++; +} + +#define dev_err(dev, fmt, ...) record_err(fmt, ##__VA_ARGS__) +#define dev_dbg(dev, fmt, ...) do { (void)(dev); } while (0) + +static bool dcp_is_external_h17p(struct apple_dcp *dcp) +{ + return dcp->external_h17p; +} + +static bool dcp_is_usb4_output(struct apple_dcp *dcp) +{ + return dcp->usb4_output; +} + +static bool dcp_is_t8132_ext(struct apple_dcp *dcp) +{ + return dcp->t8132_ext; +} + +static int dptx_j700_validate_lanes(struct dptx_port *dptx, u64 lane_count) +{ + (void)dptx; + (void)lane_count; + h17p_validate_calls++; + return h17p_validate_ret; +} + +static int phy_configure(struct phy *phy, union phy_configure_opts *opts) +{ + (void)phy; + (void)opts; + phy_configure_calls++; + return phy_configure_ret; +} + +static void t8132_ext_drm_hotplug(void *dev) +{ + (void)dev; + hotplug_calls++; +} + +static void complete(struct completion *c) +{ + c->done++; +} + +''' + fn_src + r''' + +static void reset_counters(void) +{ + unexpected_err_calls = 0; + invalid_err_calls = 0; + other_err_calls = 0; + phy_configure_calls = 0; + phy_configure_ret = 0; + h17p_validate_calls = 0; + h17p_validate_ret = 0; + hotplug_calls = 0; +} + +static int call_set_lanes(struct apple_epic_service *svc, u64 lanes, + struct dptxport_apcall_set_active_lane_count *reply) +{ + struct dptxport_apcall_set_active_lane_count req = { + .lane_count = cpu_to_le64(lanes), + }; + + memset(reply, 0, sizeof(*reply)); + return dptxport_call_set_active_lane_count(svc, &req, sizeof(req), + reply, sizeof(*reply)); +} + +int main(void) +{ + struct phy dummy_phy = { 0 }; + struct dptxport_apcall_set_active_lane_count reply; + unsigned int cases = 0; + + /* + * 1. Fixed non-ATC-PHY outputs (dptx_phy > 3, e.g. HDMI-A with phy 4 or 5): + * bringing up 4 lanes from initial 0, dropping to 0, raising to 2 and 4 + * must never log "unexpected lane count" and must update dptx->lane_count. + */ + for (u32 phy_idx = 4; phy_idx <= 5; phy_idx++) { + struct apple_dcp dcp = { .dptx_phy = phy_idx }; + struct apple_dcp_afkep ep = { .dcp = &dcp }; + struct dptx_port port = { .atcphy = NULL, .lane_count = 0 }; + struct apple_epic_service svc = { .ep = &ep, .cookie = &port }; + const u64 seq[] = { 4, 0, 2, 4, 1, 4 }; + + for (size_t i = 0; i < sizeof(seq) / sizeof(seq[0]); i++) { + unsigned int prev_done = port.linkcfg_completion.done; + int ret; + + reset_counters(); + ret = call_set_lanes(&svc, seq[i], &reply); + assert(ret == 0); + assert(unexpected_err_calls == 0); + assert(invalid_err_calls == 0); + assert(other_err_calls == 0); + assert(phy_configure_calls == 0); + assert(hotplug_calls == 0); + assert(le32_to_cpu(reply.retcode) == 0); + assert(le64_to_cpu(reply.lane_count) == seq[i]); + assert(port.lane_count == seq[i]); + assert(port.linkcfg_completion.done == + prev_done + (seq[i] > 0 ? 1u : 0u)); + cases++; + } + } + + /* + * 2. Standard ATC PHY outputs (dptx_phy <= 3, non-USB4, non-H17P): + * requesting more lanes than dptx->lane_count must still emit the + * "unexpected lane count" error; requesting <= dptx->lane_count must not. + */ + for (u32 phy_idx = 0; phy_idx <= 3; phy_idx++) { + struct apple_dcp dcp = { .dptx_phy = phy_idx }; + struct apple_dcp_afkep ep = { .dcp = &dcp }; + struct dptx_port port = { .atcphy = &dummy_phy, .lane_count = 0 }; + struct apple_epic_service svc = { .ep = &ep, .cookie = &port }; + int ret; + + reset_counters(); + ret = call_set_lanes(&svc, 4, &reply); + assert(ret == 0); + assert(unexpected_err_calls == 1); + assert(invalid_err_calls == 0); + assert(phy_configure_calls == 0); + assert(port.lane_count == 0); + assert(le32_to_cpu(reply.retcode) == 0); + assert(le64_to_cpu(reply.lane_count) == 4); + cases++; + + port.lane_count = 4; + reset_counters(); + ret = call_set_lanes(&svc, 2, &reply); + assert(ret == 0); + assert(unexpected_err_calls == 0); + assert(invalid_err_calls == 0); + assert(port.lane_count == 4); + assert(le32_to_cpu(reply.retcode) == 0); + assert(le64_to_cpu(reply.lane_count) == 2); + cases++; + } + + /* + * 3. USB4 DP tunnels on any dptx_phy (0..3): + * no "unexpected lane count" error, updates dptx->lane_count, skips + * phy_configure(), and triggers T8132 hotplug only on lane changes. + */ + { + struct apple_dcp dcp = { + .dptx_phy = 1, + .usb4_output = true, + .t8132_ext = true, + }; + struct apple_dcp_afkep ep = { .dcp = &dcp }; + struct dptx_port port = { .atcphy = &dummy_phy, .lane_count = 0 }; + struct apple_epic_service svc = { .ep = &ep, .cookie = &port }; + int ret; + + reset_counters(); + ret = call_set_lanes(&svc, 4, &reply); + assert(ret == 0); + assert(unexpected_err_calls == 0); + assert(phy_configure_calls == 0); + assert(hotplug_calls == 1); + assert(port.lane_count == 4); + cases++; + + reset_counters(); + ret = call_set_lanes(&svc, 4, &reply); + assert(ret == 0); + assert(unexpected_err_calls == 0); + assert(hotplug_calls == 0); + assert(port.lane_count == 4); + cases++; + } + + /* + * 4. External H17P output: + * uses dptx_j700_validate_lanes() and configures ATC PHY when present. + */ + { + struct apple_dcp dcp = { .dptx_phy = 0, .external_h17p = true }; + struct apple_dcp_afkep ep = { .dcp = &dcp }; + struct dptx_port port = { .atcphy = &dummy_phy, .lane_count = 0 }; + struct apple_epic_service svc = { .ep = &ep, .cookie = &port }; + int ret; + + reset_counters(); + ret = call_set_lanes(&svc, 4, &reply); + assert(ret == 0); + assert(h17p_validate_calls == 1); + assert(unexpected_err_calls == 0); + assert(phy_configure_calls == 1); + assert(port.lane_count == 4); + cases++; + } + + /* + * 5. Invalid lane counts (3, 5, 8) are rejected even on dptx_phy > 3. + */ + { + struct apple_dcp dcp = { .dptx_phy = 4 }; + struct apple_dcp_afkep ep = { .dcp = &dcp }; + struct dptx_port port = { .atcphy = NULL, .lane_count = 4 }; + struct apple_epic_service svc = { .ep = &ep, .cookie = &port }; + const u64 bad[] = { 3, 5, 8 }; + + for (size_t i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) { + unsigned int prev_done = port.linkcfg_completion.done; + int ret; + + reset_counters(); + ret = call_set_lanes(&svc, bad[i], &reply); + assert(ret == 0); + assert(unexpected_err_calls == 0); + assert(invalid_err_calls == 1); + assert(le32_to_cpu(reply.retcode) == 1); + assert(le64_to_cpu(reply.lane_count) == 0); + assert(port.linkcfg_completion.done == prev_done); + cases++; + } + } + + /* + * 6. Truncated request or reply buffers fail with -1. + */ + { + struct apple_dcp dcp = { .dptx_phy = 4 }; + struct apple_dcp_afkep ep = { .dcp = &dcp }; + struct dptx_port port = { .atcphy = NULL, .lane_count = 0 }; + struct apple_epic_service svc = { .ep = &ep, .cookie = &port }; + struct dptxport_apcall_set_active_lane_count req = { 0 }; + + assert(dptxport_call_set_active_lane_count(&svc, &req, sizeof(req) - 1, + &reply, sizeof(reply)) == -1); + assert(dptxport_call_set_active_lane_count(&svc, &req, sizeof(req), + &reply, sizeof(reply) - 1) == -1); + cases += 2; + } + + printf("%u cases\n", cases); + return 0; +} +''' + +with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / 'test.c' + src.write_text(program) + exe = src.with_suffix('') + subprocess.run( + ['cc', '-Werror', '-Wall', '-Wno-unused-function', + '-fsanitize=address,undefined', str(src), '-o', str(exe)], + check=True, + ) + run = subprocess.run([str(exe)]) + if run.returncode: + sys.exit(f'FAIL: dptx set_active_lane_count matrix exited {run.returncode}') +print('PASS fixed non-ATC-PHY (dptx_phy > 3) and USB4 tunnels skip ATC PHY lane-count error; ATC PHY and invalid counts preserved') diff --git a/tools/asahi/g14-v27-2-abi-tests.rs b/tools/asahi/g14-v27-2-abi-tests.rs new file mode 100644 index 00000000000000..04ae20680f7ca6 --- /dev/null +++ b/tools/asahi/g14-v27-2-abi-tests.rs @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Host tests of the production G14 firmware 27.2 queue, event and recovery records. +#![allow(dead_code)] +#[path = "../../drivers/gpu/drm/asahi/g14_v27_2_abi.rs"] +mod g14_v27_2_abi; diff --git a/tools/asahi/g15-display-order-tests.py b/tools/asahi/g15-display-order-tests.py index f07ca470c4c92b..cd4323903e76ab 100644 --- a/tools/asahi/g15-display-order-tests.py +++ b/tools/asahi/g15-display-order-tests.py @@ -42,8 +42,10 @@ def c_source(root): if line in ("static DEFINE_MUTEX(apple_g15_display_lock);", "static struct device *apple_t6030_display;", "static struct device *apple_t6031_display;", - "static struct device *apple_t8132_display;")] - assert len(state) == 4, f"publication state not found: {state}" + "static struct device *apple_t8132_display;", + "#define APPLE_DRM_PUBLISHED_MAX 8", + "static struct device *apple_drm_published[APPLE_DRM_PUBLISHED_MAX];")] + assert len(state) == 6, f"publication state not found: {state}" bodies = [item(apple, marker) for marker in ( "\nstatic struct device **apple_g15_display_slot(struct device *dev)\n{", "\nstatic int apple_g15_display_publish(struct device *dev)\n{", @@ -52,9 +54,12 @@ def c_source(root): "\nint apple_drm_t6030_link_device(struct device *consumer)\n{", "\nint apple_drm_t6031_link_device(struct device *consumer)\n{", "\nint apple_drm_t8132_link_device(struct device *consumer)\n{", + "\nstatic int apple_drm_display_publish(struct device *dev)\n{", + "\nstatic void apple_drm_display_withdraw(struct device *dev)\n{", + "\nint apple_drm_link_device(", )] bodies.append(item(glue, "\nint asahi_g15_display_prepare(struct device *dev)\n{")) - bodies.append(item(glue16, "\nint asahi_g16_display_prepare(struct device *dev)\n{")) + bodies.append(item(glue16, "\nint asahi_g16_display_prepare(struct device *dev, const char *display_compat)\n{")) return "\n".join(state) + "\n\n" + "\n\n".join(bodies) + "\n" @@ -68,8 +73,10 @@ def c_source(root): #define ENODEV 19 #define EBUSY 16 #define EINVAL 22 +#define ENOSPC 28 #define EPROBE_DEFER 517 #define DL_FLAG_AUTOREMOVE_CONSUMER 1u +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #define EXPORT_SYMBOL_GPL(sym) extern int sym##_exported struct device_node { const char *compatible; bool available; int refs; }; @@ -131,14 +138,16 @@ def c_source(root): #define CHECK(c) do { if (!(c)) { fprintf(stderr, "%s:%d: %s\n", scenario, __LINE__, #c); exit(1); } } while (0) static struct device_node gpu31 = { "apple,agx-t6031", true }, gpu30 = { "apple,agx-t6030", true }; -static struct device_node gpu8132 = { "apple,agx-t8132", true }; +static struct device_node gpu8132 = { "apple,agx-t8132", true }, gpu8122 = { "apple,agx-t8122", true }; static struct device_node disp8132 = { "apple,t8132-display-subsystem", false }; +static struct device_node disp8122 = { "apple,t8122-display-subsystem", false }; static struct device_node disp31 = { "apple,t6031-display-subsystem", false }; static struct device_node disp30 = { "apple,t6030-display-subsystem", true }; static struct device_node other = { "apple,display-subsystem", true }; static struct device g31 = { &gpu31 }, g30 = { &gpu30 }, none = { NULL }; static struct device d31 = { &disp31 }, d31b = { &disp31 }, d30 = { &disp30 }, dother = { &other }; static struct device g8132 = { &gpu8132 }, d8132 = { &disp8132 }; +static struct device g8122 = { &gpu8122 }, d8122 = { &disp8122 }, d8122b = { &disp8122 }; static void machine(const char *soc, const char *board) { @@ -155,9 +164,11 @@ def c_source(root): static int link30(struct device *dev) { int ret = apple_drm_t6030_link_device(dev); clean(); return ret; } static int link31(struct device *dev) { int ret = apple_drm_t6031_link_device(dev); clean(); return ret; } static int link8132(struct device *dev) { int ret = apple_drm_t8132_link_device(dev); clean(); return ret; } -static int prepare16(struct device *dev) { int ret = asahi_g16_display_prepare(dev); clean(); return ret; } +static int prepare16(struct device *dev, const char *compat) { int ret = asahi_g16_display_prepare(dev, compat); clean(); return ret; } static int publish(struct device *dev) { int ret = apple_g15_display_publish(dev); clean(); return ret; } static void withdraw(struct device *dev) { apple_g15_display_withdraw(dev); clean(); } +static int publish_drm(struct device *dev) { int ret = apple_drm_display_publish(dev); clean(); return ret; } +static void withdraw_drm(struct device *dev) { apple_drm_display_withdraw(dev); clean(); } int main(int argc, char **argv) { @@ -216,30 +227,76 @@ def c_source(root): withdraw(&d30); CHECK(d30.refs == 0 && link30(&g30) == -EPROBE_DEFER); CHECK(link30(&g31) == -ENODEV); + } else if (!strcmp(scenario, "g16-t6030")) { + machine("apple,t6030", "apple,j516s"); + disp30.available = false; + CHECK(prepare16(&g30, "apple,t6030-display-subsystem") == 0 && links_made == 0); + nodes[2] = NULL; + CHECK(prepare16(&g30, "apple,t6030-display-subsystem") == 0 && links_made == 0); + nodes[2] = &disp30; + disp30.available = true; + CHECK(prepare16(&g30, "apple,t6030-display-subsystem") == -EPROBE_DEFER && links_made == 0); + CHECK(publish_drm(&d30) == 0 && d30.refs == 1); + CHECK(prepare16(&g30, "apple,t6030-display-subsystem") == 0 && links_made == 1 && last_link.supplier == &d30); + withdraw_drm(&d30); + CHECK(d30.refs == 0 && prepare16(&g30, "apple,t6030-display-subsystem") == -EPROBE_DEFER); } else if (!strcmp(scenario, "t8132")) { /* No handed-over display: G16 starts on the boot framebuffer, said once. */ machine("apple,t8132", "apple,j713"); nodes[0] = &gpu8132; nodes[1] = &disp8132; - CHECK(prepare16(&g8132) == 0 && infos == 1 && links_made == 0); + CHECK(prepare16(&g8132, "apple,t8132-display-subsystem") == 0 && infos == 1 && links_made == 0); nodes[1] = NULL; - CHECK(prepare16(&g8132) == 0 && infos == 1 && links_made == 0); + CHECK(prepare16(&g8132, "apple,t8132-display-subsystem") == 0 && infos == 1 && links_made == 0); nodes[1] = &disp8132; /* A handed-over display: wait for its own publication, said once, then link. */ disp8132.available = true; - CHECK(prepare16(&g8132) == -EPROBE_DEFER && infos == 2 && links_made == 0); - CHECK(publish(&d31) == 0 && prepare16(&g8132) == -EPROBE_DEFER && links_made == 0); - withdraw(&d31); - CHECK(publish(&d8132) == 0 && d8132.refs == 1); - CHECK(prepare16(&g8132) == 0 && links_made == 1); + CHECK(prepare16(&g8132, "apple,t8132-display-subsystem") == -EPROBE_DEFER && infos == 2 && links_made == 0); + CHECK(publish_drm(&d31) == 0 && prepare16(&g8132, "apple,t8132-display-subsystem") == -EPROBE_DEFER && links_made == 0); + withdraw_drm(&d31); + CHECK(publish_drm(&d8132) == 0 && d8132.refs == 1); + CHECK(prepare16(&g8132, "apple,t8132-display-subsystem") == 0 && links_made == 1); CHECK(last_link.consumer == &g8132 && last_link.supplier == &d8132 && last_link.flags == DL_FLAG_AUTOREMOVE_CONSUMER); + CHECK(publish(&d31) == 0 && link8132(&g8132) == -EPROBE_DEFER && links_made == 1); + withdraw(&d31); + CHECK(publish(&d8132) == 0 && d8132.refs == 2); + CHECK(link8132(&g8132) == 0 && links_made == 2 && last_link.supplier == &d8132); CHECK(link8132(&g31) == -ENODEV && link8132(&none) == -ENODEV); + withdraw_drm(&d8132); + CHECK(d8132.refs == 1 && prepare16(&g8132, "apple,t8132-display-subsystem") == -EPROBE_DEFER); withdraw(&d8132); - CHECK(d8132.refs == 0 && prepare16(&g8132) == -EPROBE_DEFER); + CHECK(d8132.refs == 0 && link8132(&g8132) == -EPROBE_DEFER); CHECK(publish(&d8132) == 0); machine("apple,t6031", "apple,j516c"); - CHECK(link8132(&g8132) == -ENODEV && prepare16(&g8132) == -ENODEV && links_made == 1); + CHECK(link8132(&g8132) == -ENODEV && links_made == 2); + } else if (!strcmp(scenario, "g16-other-row")) { + /* Another hardware row selects its display supplier from match data without probing branches. */ + machine("apple,t8122", "apple,j615"); + nodes[0] = &gpu8122; + nodes[1] = &disp8122; + CHECK(prepare16(&g8122, NULL) == -EINVAL && prepare16(&g8122, "") == -EINVAL); + CHECK(prepare16(&g8122, "apple,t8122-display-subsystem") == 0 && infos == 1 && links_made == 0); + nodes[1] = NULL; + CHECK(prepare16(&g8122, "apple,t8122-display-subsystem") == 0 && infos == 1 && links_made == 0); + nodes[1] = &disp8122; + disp8122.available = true; + CHECK(prepare16(&g8122, "apple,t8122-display-subsystem") == -EPROBE_DEFER && infos == 2 && links_made == 0); + CHECK(publish_drm(&d8132) == 0 && prepare16(&g8122, "apple,t8122-display-subsystem") == -EPROBE_DEFER && links_made == 0); + CHECK(publish_drm(&d8122) == 0 && d8122.refs == 1); + CHECK(publish_drm(&d8122) == 0 && d8122.refs == 1); + CHECK(publish_drm(&d8122b) == -EBUSY && d8122b.refs == 0); + withdraw_drm(&d8122b); + CHECK(prepare16(&none, "apple,t8122-display-subsystem") == -EINVAL && links_made == 0); + CHECK(prepare16(&g8122, "apple,t8122-display-subsystem") == 0 && links_made == 1); + CHECK(last_link.consumer == &g8122 && last_link.supplier == &d8122 && + last_link.flags == DL_FLAG_AUTOREMOVE_CONSUMER); + link_fail = 1; + CHECK(prepare16(&g8122, "apple,t8122-display-subsystem") == -EINVAL); + link_fail = 0; + withdraw_drm(&d8122); + CHECK(d8122.refs == 0 && prepare16(&g8122, "apple,t8122-display-subsystem") == -EPROBE_DEFER); + withdraw_drm(&d8132); } else { CHECK(!"unknown scenario"); } @@ -247,7 +304,7 @@ def c_source(root): } ''' -C_SCENARIOS = ["disabled", "absent", "pending", "ready", "isolation", "foreign", "t6030", "t8132"] +C_SCENARIOS = ["disabled", "absent", "pending", "ready", "isolation", "foreign", "t6030", "g16-t6030", "t8132", "g16-other-row"] C_MUTANTS = { "unpublished-succeeds": ("if (!*display)\n\t\treturn -EPROBE_DEFER;", "if (!*display)\n\t\treturn 0;"), @@ -258,8 +315,10 @@ def c_source(root): "t8132-reads-t6031-slot": ("&apple_t8132_display);", "&apple_t6031_display);"), "t8132-published-as-t6031": ("return &apple_t8132_display;", "return &apple_t6031_display;"), "g16-ignores-handed-over-display": ("handed_over = np && of_device_is_available(np);", "handed_over = false;"), - "g16-waits-without-display": ("\t\treturn 0;\n\t}\n\tret = apple_drm_t8132_link_device(dev);", - "\t\treturn -EPROBE_DEFER;\n\t}\n\tret = apple_drm_t8132_link_device(dev);"), + "g16-waits-without-display": ("\t\treturn 0;\n\t}\n\tret = apple_drm_link_device(dev, np);", + "\t\treturn -EPROBE_DEFER;\n\t}\n\tret = apple_drm_link_device(dev, np);"), + "drm-link-unpublished-succeeds": ("\t\t}\n\t}\n\treturn -EPROBE_DEFER;", "\t\t}\n\t}\n\treturn 0;"), + "drm-link-wrong-node": ("apple_drm_published[i]->of_node == display_node", "apple_drm_published[i]->of_node != NULL"), "no-machine-check": ("!of_machine_is_compatible(machine) ||", ""), "withdraw-keeps-display": ("*slot = NULL;", ";"), "publish-without-reference": ("*slot = get_device(dev);", "*slot = dev;"), @@ -461,9 +520,10 @@ def static_checks(root): assert compat.findall(autoload) == ["apple,agx-t6030", "apple,agx-t6031"], "autoload table" assert compat.findall(matched) == ["apple,agx-t6030", "apple,agx-t6031"], "match table" init = item(apple, "\nstatic int apple_drm_init(struct device *dev)\n{") - order = [init.index(s) for s in ("drm_dev_register(", "drm_client_setup_with_fourcc(", "apple_g15_display_publish(dev)")] + order = [init.index(s) for s in ("drm_dev_register(", "drm_client_setup_with_fourcc(", "apple_g15_display_publish(dev)", "apple_drm_display_publish(dev)")] assert order == sorted(order), "publication must follow DRM registration and client setup" uninit = item(apple, "\nstatic void apple_drm_uninit(struct device *dev)\n{") + assert uninit.index("apple_drm_display_withdraw(dev)") < uninit.index("component_unbind_all("), "withdraw before unbind" assert uninit.index("apple_g15_display_withdraw(dev)") < uninit.index("component_unbind_all("), "withdraw before unbind" assert "apple_t6030_display_publish" not in apple and "apple_t6030_display_withdraw" not in apple pmp = item(glue, "\nint asahi_g15_pmp_prepare(struct device *dev)\n{") diff --git a/tools/asahi/g15-maintained-handoff-tests.py b/tools/asahi/g15-maintained-handoff-tests.py index fdafd799645cb7..738facb331e521 100644 --- a/tools/asahi/g15-maintained-handoff-tests.py +++ b/tools/asahi/g15-maintained-handoff-tests.py @@ -137,12 +137,71 @@ def item(s, marker): OWNER_CALLS.set(0); let bytes = fixture(kind); assert!(parse(&dev, &Adt { data: &bytes }).is_err()); assert_eq!(OWNER_CALLS.get(), 0); } - assert_eq!(BUILDS.len(), 3, "maintained B0 firmware row must not require an absent profile symbol"); + assert_eq!(BUILDS.len(), 7, "maintained B0 firmware row must not require an absent profile symbol"); for (row, machine) in [(1, &b"apple,j516s"[..]), (2, &b"apple,j514s"[..])] { assert_eq!(BUILDS[row].machine.unwrap().to_bytes(), machine); assert_eq!((BUILDS[row].text_size, BUILDS[row].data_size, BUILDS[row].marker), (0x5c000, 0x114000, 0x58e88)); assert_eq!(BUILDS[row].text_sha256, [0xda,0x26,0xec,0xca,0xb1,0xf8,0x59,0x8d,0xa8,0x0c,0x85,0x5e,0xca,0x91,0x65,0x20,0x40,0x6d,0x1d,0x06,0x70,0xf1,0xd4,0x70,0xe7,0x9b,0xb9,0xb0,0x22,0x09,0xdb,0x53]); } + assert_eq!(BUILDS[4].machine.unwrap().to_bytes(), b"apple,j516s"); + assert_eq!((BUILDS[4].text_size, BUILDS[4].data_size, BUILDS[4].marker), (0x5c000, 0x114000, 0x58e88)); + assert_eq!(BUILDS[4].text_sha256, [0xcd,0x05,0xaf,0x6a,0x82,0x8b,0x52,0xe4,0xc2,0xfe,0xd2,0x00,0x86,0xd3,0xd1,0x8a,0x7d,0xb4,0x2e,0x03,0xa8,0xfd,0x6f,0x83,0x54,0xf9,0xf0,0x6e,0x0a,0x61,0x36,0x3e]); + // Issue #247: this J514S build must pin without the bring-up override. + use identity::lookup::{Measured, Verdict, verdict}; + let measured = Measured { + text_size: 0x5c000, data_size: 0x114000, marker: 0x58e88, + sha256: [0xcd,0x05,0xaf,0x6a,0x82,0x8b,0x52,0xe4, + 0xc2,0xfe,0xd2,0x00,0x86,0xd3,0xd1,0x8a, + 0x7d,0xb4,0x2e,0x03,0xa8,0xfd,0x6f,0x83, + 0x54,0xf9,0xf0,0x6e,0x0a,0x61,0x36,0x3e], + }; + let identify = |m: &Measured, machine: &[u8]| verdict(m, BUILDS.iter().map(|b| ( + Measured { text_size: b.text_size, data_size: b.data_size, + marker: b.marker, sha256: b.text_sha256 }, + b.machine.map_or(true, |board| board.to_bytes() == machine), + )), 0); + assert!(matches!(identify(&measured, b"apple,j514s"), Verdict::Pinned(3)), + "J514S cd05 firmware must pin without a prefix override"); + assert_eq!(identify(&measured, b"apple,j516s"), Verdict::Pinned(4)); + let mut changed = measured; + changed.sha256[31] ^= 1; + assert_eq!(identify(&changed, b"apple,j514s"), Verdict::Refused); + changed = measured; changed.text_size += 0x1000; + assert_eq!(identify(&changed, b"apple,j514s"), Verdict::Refused); + changed = measured; changed.data_size += 0x1000; + assert_eq!(identify(&changed, b"apple,j514s"), Verdict::Refused); + changed = measured; changed.marker += 8; + assert_eq!(identify(&changed, b"apple,j514s"), Verdict::Refused); + // Issue #247: the 4118 build pins on the J514S and the J516S, each to + // its own row, without the bring-up override. + let digest = [0x41,0x18,0x33,0xa7,0xde,0xd7,0x73,0xfe, + 0xea,0xc4,0xa1,0x81,0x55,0x2e,0x3f,0xf5, + 0x58,0x2e,0xaf,0x44,0x35,0xf2,0xdd,0x8f, + 0x62,0x0c,0x1e,0xd0,0xb3,0x1d,0xf1,0xb0]; + for (row, machine) in [(5, &b"apple,j514s"[..]), (6, &b"apple,j516s"[..])] { + assert_eq!(BUILDS[row].machine.unwrap().to_bytes(), machine); + assert_eq!((BUILDS[row].text_size, BUILDS[row].data_size, BUILDS[row].marker), (0x5c000, 0x114000, 0x58e88)); + assert_eq!(BUILDS[row].text_sha256, digest); + } + let measured = Measured { text_size: 0x5c000, data_size: 0x114000, marker: 0x58e88, sha256: digest }; + assert_eq!(identify(&measured, b"apple,j514s"), Verdict::Pinned(5), + "J514S 4118 firmware must pin without a prefix override"); + assert_eq!(identify(&measured, b"apple,j516s"), Verdict::Pinned(6), + "J516S 4118 firmware must pin without a prefix override"); + for other in [&b"apple,j514c"[..], b"apple,j516c", b"apple,j514m", b"apple,j516m", b"apple,t6030"] { + assert_eq!(identify(&measured, other), Verdict::Refused); + } + for machine in [&b"apple,j514s"[..], b"apple,j516s"] { + let mut changed = measured; + changed.sha256[31] ^= 1; + assert_eq!(identify(&changed, machine), Verdict::Refused); + changed = measured; changed.text_size += 0x1000; + assert_eq!(identify(&changed, machine), Verdict::Refused); + changed = measured; changed.data_size += 0x1000; + assert_eq!(identify(&changed, machine), Verdict::Refused); + changed = measured; changed.marker += 8; + assert_eq!(identify(&changed, machine), Verdict::Refused); + } for error in [0, -517, -12] { INIT_ERROR.set(error); let shared = Arc::new(Shared); let result = Rtkit::new(&dev, &shared); assert_eq!(result.is_ok(), error == 0); @@ -167,7 +226,8 @@ def main(): while depth: depth+=(hw[end]=='[')-(hw[end]==']'); end+=1 firmware='static BUILDS: &[FirmwareBuild] = &'+hw[start:end]+';\n'+item(hw,'pub(crate) struct FirmwareBuild') constructor=item(boot,' fn new(dev: &device::Device, shared: &Arc)') - source=PREFIX+'\nmod hw {\n'+constants+'\n}\nmod record {\n'+record_constants+'\n}\n'+helpers+'\n'+firmware+'\nimpl Rtkit {\n'+constructor+'\n}\n'+CASES + identity='mod identity {\n'+''.join(f'#[path = "{G15 / "identity" / (name + ".rs")}"] pub(crate) mod {name};\n' for name in ['matching', 'lookup'])+'}\n' + source=PREFIX+'\nmod hw {\n'+constants+'\n}\nmod record {\n'+record_constants+'\n}\n'+helpers+'\n'+firmware+'\nimpl Rtkit {\n'+constructor+'\n}\n'+identity+CASES variants={'actual':source} if a.mutations: variants['skip-owner-check']=source.replace('if !glue::reserved_uat(i as u32, r.start, r.end - r.start) {','if false {') diff --git a/tools/asahi/g15-probe-init-tests.py b/tools/asahi/g15-probe-init-tests.py index a7b9b900b7af5e..04e344f6f31445 100644 --- a/tools/asahi/g15-probe-init-tests.py +++ b/tools/asahi/g15-probe-init-tests.py @@ -66,6 +66,8 @@ def item(text, marker): const ENODEV: i32 = -19; const EPROBE_DEFER: i32 = -517; const GFP_KERNEL: u32 = 0; +#[allow(unused_macros)] +macro_rules! c_str { ($s:literal) => { $s }; } macro_rules! dev_info { ($($x:tt)*) => {{}}; } macro_rules! dev_err { ($($x:tt)*) => {{}}; } thread_local! { @@ -80,13 +82,20 @@ def item(text, marker): static BINDING_READY: Cell = const { Cell::new(false) }; static QUEUE_SHARE_READY: Cell = const { Cell::new(false) }; static EXEC_SHARE_READY: Cell = const { Cell::new(false) }; + static G17_READY: Cell = const { Cell::new(false) }; static ATTACH_ERROR: Cell = const { Cell::new(false) }; static PROBE_ERROR: Cell = const { Cell::new(0) }; + static PRE_ACTIVATION: Cell = const { Cell::new(0) }; } struct Core<'a>(PhantomData<&'a ()>); -struct Device { data: Cell<*mut core::ffi::c_void> } +struct Device { data: Cell<*mut core::ffi::c_void>, g16_handoff: bool } impl Device { fn as_raw(&self) -> *mut Device { self as *const Device as *mut Device } + fn of_node(&self) -> Option<&Self> { Some(self) } + fn get_opt_property(&self, name: &str) -> Result> { + assert_eq!(name, "apple,g16-handoff-version"); + Ok(self.g16_handoff.then(T::default)) + } // SET_DRVDATA } mod bindings { @@ -137,7 +146,7 @@ def item(text, marker): ) -> impl PinInit, Error> + 'bound; } } -struct Config { name: &'static str } +struct Config { name: &'static str, chip_id: u32 } pub struct ThisModule; pub trait ModuleMetadata { const NAME: &'static std::ffi::CStr; } pub trait InPlaceModule: Sized { @@ -154,6 +163,7 @@ def item(text, marker): } // So must the registry of execution contexts shared by a VM's G17P queues. mod g17 { + pub unsafe fn init() { crate::G17_READY.set(true); } pub mod exec_share { pub unsafe fn init() { crate::EXEC_SHARE_READY.set(true); } } @@ -175,6 +185,7 @@ def item(text, marker): assert!(BINDING_READY.get(), "adapter registered before binding registry init"); assert!(QUEUE_SHARE_READY.get(), "adapter registered before queue-share registry init"); assert!(EXEC_SHARE_READY.get(), "adapter registered before execution-context share registry init"); + assert!(G17_READY.get(), "adapter registered before g17 compute-waiter target registry init"); try_pin_init!(Self { stage: { let stage = match name.to_bytes() { @@ -184,7 +195,16 @@ def item(text, marker): }; // Model driver_attach and a late driver_add_groups failure. A deferred // worker can also retry G15 while the other registration is in progress. - let _ = callback::>(&PDEV, Some(&&CFG)); + let ready = MODULE_READY.load(Ordering::Acquire); + let started = PROBES.get(); + let result = callback::>(&PDEV, Some(&&CFG)); + // A probe that started firmware here is the readiness-gate failure, checked below. + if !ready && PROBES.get() == started { + // A deferral would keep the GPU in devices_deferred after a later + // terminal failure; before activation the probe must decline outright. + assert_eq!(result, Err(ENODEV), "pre-activation probe deferred instead of ENODEV"); + PRE_ACTIVATION.set(PRE_ACTIVATION.get() + 1); + } if FAIL_REGISTRATION.get() == stage { return Err(-5); } COMPLETED_REGISTRATION.set(stage); stage @@ -228,12 +248,13 @@ def item(text, marker): BINDING_READY.set(false); QUEUE_SHARE_READY.set(false); EXEC_SHARE_READY.set(false); + G17_READY.set(false); FAIL_ALLOC.set(fail_alloc); TOUCH.set(touch); PROBE_ERROR.set(error); RETAINED.set(false); ALLOCS.set(0); PROBES.set(0); } -static CFG: Config = Config { name: "test" }; +static CFG: Config = Config { name: "test", chip_id: 0x6030 }; static PDEV: platform::Device> = platform::Device { - base: Device { data: Cell::new(core::ptr::null_mut()) }, ctx: PhantomData, + base: Device { data: Cell::new(core::ptr::null_mut()), g16_handoff: false }, ctx: PhantomData, }; fn activation_reprobe() { let last = if cfg!(CONFIG_DRM_ASAHI_G16) { 3 } else { 2 }; @@ -252,7 +273,7 @@ def item(text, marker): PDEV.base.data.set(core::ptr::null_mut()); MODULE_READY.store(false, Ordering::Release); COMPLETED_REGISTRATION.set(0); FAIL_REGISTRATION.set(failure); - ACTIVATED.set(false); ATTACH_ERROR.set(failure == 0); + ACTIVATED.set(false); ATTACH_ERROR.set(failure == 0); PRE_ACTIVATION.set(0); let init = ::init(&MODULE); assert_eq!(PROBES.get(), 0, "module initializer eagerly started firmware"); let result = KBox::pin_init(init, GFP_KERNEL); @@ -269,6 +290,12 @@ def item(text, marker): assert!(!PDEV.base.data.get().is_null()); unsafe { drop(Box::from_raw(PDEV.base.data.get().cast::>())); } } + // Every probe before activation declined: one per completed or failing registration. + // The registrations run G15 (1), the generic driver (2), then G16 (3) where it is built. + let expected = if cfg!(CONFIG_DRM_ASAHI_G16) { + match failure { 1 => 1, 2 => 2, _ => 3 } + } else if failure == 1 { 1 } else { 2 }; + assert_eq!(PRE_ACTIVATION.get(), expected, "pre-activation probes"); println!("module-registration-{failure}: PASS"); } } @@ -283,7 +310,7 @@ def item(text, marker): ("successful-registration-binds", false, true, 0, Ok(0), true, 1), ] { reset(allocation_fails, touched, error); - let pdev = platform::Device { base: Device { data: Cell::new(core::ptr::null_mut()) }, ctx: PhantomData }; + let pdev = platform::Device { base: Device { data: Cell::new(core::ptr::null_mut()), g16_handoff: false }, ctx: PhantomData }; let result = callback::>(&pdev, Some(&cfg)); assert_eq!(result, expected, "{name}: callback result"); assert_eq!(PROBES.get(), calls, "{name}: firmware probe before drvdata allocation"); @@ -296,6 +323,14 @@ def item(text, marker): } println!("{name}: PASS"); } + reset(false, true, 0); + let pdev = platform::Device { + base: Device { data: Cell::new(core::ptr::null_mut()), g16_handoff: true }, + ctx: PhantomData, + }; + assert_eq!(callback::>(&pdev, Some(&cfg)), Err(ENODEV)); + assert_eq!(PROBES.get(), 0); + println!("g16-handoff-declined: PASS"); module_cases(); } ''' @@ -415,9 +450,10 @@ def main(): needle = " None\n" assert probe.count(needle) == 1 variants["retained-error-unbinds"] = (probe.replace(needle, " return Err(error);\n"), module_code) - gate = " if !MODULE_READY.load(Ordering::Acquire) {\n return Err(EPROBE_DEFER);\n }\n" + gate = " if !MODULE_READY.load(Ordering::Acquire) {\n return Err(ENODEV);\n }\n" assert probe.count(gate) == 1 variants["no-registration-readiness-gate"] = (probe.replace(gate, ""), module_code) + variants["pre-activation-defers"] = (probe.replace(gate, gate.replace("ENODEV", "EPROBE_DEFER")), module_code) late = " #[cfg(CONFIG_DRM_ASAHI_G15)]\n _g15_ready: g15::activate(),\n" assert module_code.count(late) == 1 early = module_code.replace(late, "").replace(" _driver <-", late + " _driver <-", 1) @@ -442,11 +478,11 @@ def main(): if name == "actual": receipt["g16_control" if enable_g16 else "control"] = result if r.returncode: raise SystemExit(r.stderr) - if r.stdout.count(": PASS\n") != (10 if enable_g16 else 9): raise SystemExit("control did not run every case") + if r.stdout.count(": PASS\n") != (11 if enable_g16 else 10): raise SystemExit("control did not run every case") else: receipt["mutants"][label] = result if r.returncode == 0: raise SystemExit("SURVIVED: " + name) - intended = {"eager-probe-before-allocation": "allocation-before-start: firmware probe before drvdata allocation", "retained-error-unbinds": "retained-start-failure-binds: callback result", "no-registration-readiness-gate": "late registration failure started firmware", "activation-before-last-registration": "activation before all registrations completed", "activation-before-g16-registration": "activation before all registrations completed"}[name] + intended = {"pre-activation-defers": "pre-activation probe deferred instead of ENODEV", "eager-probe-before-allocation": "allocation-before-start: firmware probe before drvdata allocation", "retained-error-unbinds": "retained-start-failure-binds: callback result", "no-registration-readiness-gate": "late registration failure started firmware", "activation-before-last-registration": "activation before all registrations completed", "activation-before-g16-registration": "activation before all registrations completed"}[name] result["intended_failure"] = intended in r.stderr if not result["intended_failure"]: raise SystemExit("INVALID unrelated failure: " + name + "\n" + r.stderr) (out / "result.json").write_text(json.dumps(receipt, indent=2) + "\n") diff --git a/tools/asahi/g15-zero-words-tests.py b/tools/asahi/g15-zero-words-tests.py index c6e32d76cb4158..f4d18bc9685ac0 100644 --- a/tools/asahi/g15-zero-words-tests.py +++ b/tools/asahi/g15-zero-words-tests.py @@ -15,12 +15,17 @@ (one #[cfg] line; the tables are unchanged), and when the initial PB posting and the idle reclaim became fixed tuning constants instead of module parameters (four constants; the tables are unchanged), and when the two stamp -renumbering margins became tuning constants (the tables are unchanged). Its T6030 +renumbering margins became tuning constants (the tables are unchanged), and when +the T6030/T6031 tables were gated on CONFIG_DRM_ASAHI_G15 for the T8122 runtime's +UAT adoption (two #[cfg] lines; the tables are unchanged). Its T6030 configuration module is independently pinned to the original bytes, -except for the J514S B0 FirmwareBuild row added to its firmware table: the -module is the original pinned bytes (0079ae08) plus that one 15-line row, and -the whole hw.rs pin was refreshed with it. prepare_board() is pinned too; +except for the J514S B0 FirmwareBuild row, the J514S cd05 and J516S cd05 +FirmwareBuild rows and the J514S 4118 and J516S 4118 FirmwareBuild rows added +to its firmware table: the module is the original pinned bytes (0079ae08) plus +those five rows, and the whole hw.rs pin was refreshed with each (with the 4118 +rows removed, both pins are their earlier values fb2118b6 and 2667963a; with +the cd05 rows also removed, e9b80be9 and cab592b5). prepare_board() is pinned too; it was refreshed for the same Board change (its T6030 arm is unchanged). """ @@ -37,11 +42,11 @@ GOLDEN_FILES = { "board/data.rs": "7c5ff1077ca3296cbfc9e7144294162b6dea78a3774c38eeed4b0f59a14d7a5c", "board/template.rs": "286872f5474a67534f214e83e659253299f85143f3dc59035fa80894022e2549", - "hw.rs": "c54a4f8342fb466f82f4b9cfed6a137ee1ca1f4d80ede4e1b7f397d39223558e", + "hw.rs": "9fa2d6e5f5d14127574448cafd6523d2151dab77c66d16e74500fafde21e8d92", "power/idle.rs": "4928ecf7699b3ca85ff5143eb6e996efd40d47321e29a238a02c8873bc9f102c", } GOLDEN_FUNCTIONS = { - ("hw.rs", "pub(crate) mod t6030 {"): "cab592b5d776be9ede93b96b1b0526c1d838ef2948a5e4a86caa4ec71f71c2ca", + ("hw.rs", "pub(crate) mod t6030 {"): "4016ec0d46831482382a92791b625e10fb2f6e4e28115a9498fdde0776f82e52", ("initdata.rs", "fn templates("): "c3115c9926d3d7d93317cb8510e93b04f30b0c256811d7137568e822dd93b8ee", ("initdata.rs", "pub(crate) fn prepare_board("): "ebef64ab87ef7b1f994eb7fa2a2424d05bc4fc9e88cbfbf18e51570bdfc4222d", ("board.rs", "pub(crate) fn from_adt("): "cecd0b28db5bd94d3b75c1bbb5f35204e8bf0699f74e5b3d08228c59025f6ac2", diff --git a/tools/asahi/g17-admission-deadline-tests.py b/tools/asahi/g17-admission-deadline-tests.py index 501c903b59f8ff..f7c6dc5c4361eb 100644 --- a/tools/asahi/g17-admission-deadline-tests.py +++ b/tools/asahi/g17-admission-deadline-tests.py @@ -27,7 +27,7 @@ def fixture(): source = (ROOT / 'queue/admission.rs').read_text() return r''' #![allow(dead_code)] -use std::sync::{Arc, Mutex, atomic::{AtomicU64, AtomicUsize, Ordering}}; +use std::sync::{Arc, Mutex, atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering}}; type Result = std::result::Result; const EBUSY:i32=-16;const EIO:i32=-5;const EINVAL:i32=-22; const ERESTARTSYS:i32=-512;const ECANCELED:i32=-125; @@ -41,13 +41,15 @@ def fixture(): const QUARANTINE_WAIT_MS:u32=1000; #[derive(Clone,Copy,PartialEq)] enum Plan {Any,Conflict} #[derive(Clone,Copy)] struct Request<'a>(&'a ()); -struct State {owners:[u64;cfg::RENDER_SLOTS],quarantined:u64,spared:u64,next_ticket:u64,waiters:usize,conflict:bool,ready:bool} +struct State {owners:[u64;cfg::RENDER_SLOTS],released:u64,quarantined:u64,spared:u64,next_ticket:u64,waiters:usize,conflict:bool,ready:bool} impl State { fn exhausted(&self)->bool {false} -''' + item(source, 'fn owner_quarantine(') + r''' +''' + item(source, 'fn owns_live(') + '\n' + item(source, 'fn owner_quarantine(') + r''' + fn owner_released(&self,_:u64)->bool {false} fn refusal(&self,_:u64)->Result {Ok(())} fn plan(&self,_:u64,_:Option>,_:Option)->Plan {if self.conflict {Plan::Conflict}else{Plan::Any}} fn pick(&mut self,_:u64,_:usize,_:Plan)->Option {if self.ready{Some(1)}else{None}} + fn pick_for(&mut self,owner:u64,pairs:usize,_:usize,plan:Plan)->Option {self.pick(owner,pairs,plan)} fn record(&mut self,_:u64,slot:Option,_:u64,_:Request<'_>)->Option {if slot.is_none(){self.waiters+=1;}Some(0)} fn forget_waiter(&mut self,t:Option){if t.is_some(){self.waiters-=1;}} } @@ -66,12 +68,12 @@ def fixture(): } } } -struct Pool {state:Lock,released:CondVar} +struct Pool {state:Lock,released:CondVar,queues:AtomicU32} struct RenderLease {pool:Arc,slot:u8,record:Option} ''' + item(source, 'fn wait_slice_ms(') + '\nimpl Pool {\n' + item(source, 'pub(crate) fn acquire_render(') + r''' } fn new_pool(conflict:bool,quarantined:u64)->Arc { - Arc::new(Pool{state:Lock(Mutex::new(State{owners:[0,1],quarantined,spared:0,next_ticket:1,waiters:0,conflict,ready:false})),released:CondVar}) + Arc::new(Pool{state:Lock(Mutex::new(State{owners:[0,1],released:0,quarantined,spared:0,next_ticket:1,waiters:0,conflict,ready:false})),released:CondVar,queues:AtomicU32::new(1)}) } fn reset(mode:usize){NOW.store(0,Ordering::SeqCst);WAITS.store(0,Ordering::SeqCst);MODE.store(mode,Ordering::SeqCst);} fn main(){ diff --git a/tools/asahi/g17-admission-order-tests.py b/tools/asahi/g17-admission-order-tests.py index 89c9dc15c809d0..b818075ec654e3 100644 --- a/tools/asahi/g17-admission-order-tests.py +++ b/tools/asahi/g17-admission-order-tests.py @@ -160,10 +160,15 @@ def held_fixture(): at = pairs.index('const SIBLING_BACKLOG') backlog = pairs[at:pairs.index('\n}\n', pairs.index('fn sibling_backlog', at)) + 3] state = '\n'.join(item(source, name) for name in [ - 'const fn new(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', - 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn reassign_unused_spare(', - 'fn cancel_empty_slot(', 'fn can_pick(', 'fn pick(', 'fn usable(', 'fn join(', 'fn release(', - 'fn set_held(', 'fn retained(', 'fn used(']) + 'const fn new(', 'fn owns_live(', 'fn has_live_owner(', 'fn exhausted(', 'fn owner_quarantine(', 'fn owner_released(', 'fn refusal(', 'fn advance(', + 'fn set_owner(', 'fn take_idle(', 'fn acquire(', 'fn acquire_for(', 'fn live_owners(', 'fn live_siblings(', + 'fn reclaimable_siblings_in(', 'fn reclaimable_siblings(', 'fn promotes_reclaimable_sibling(', + 'fn can_lease_slot(', 'fn unavailable_released(', 'fn total_pair_demand(', 'fn pair_demand(', + 'fn claim_sibling(', 'fn can_reassign_unused_spare(', 'fn reassign_unused_spare(', + 'fn cancel_empty_slot(', 'fn can_pick(', 'fn can_pick_for(', + 'fn wide(', 'fn mark_wide(', 'fn can_pick_render(', 'fn can_pick_render_for(', + 'fn pick(', 'fn pick_for(', 'fn usable(', 'fn join(', 'fn join_for(', + 'fn release(', 'fn set_held(', 'fn retained(', 'fn used(']) pool = '\n'.join(item(source, name) for name in [ 'pub(crate) fn set_held(', 'pub(crate) fn release_retained_owners_after_processor_stop(', 'pub(crate) fn killed_pair_free(']) @@ -229,8 +234,18 @@ def held_fixture(): assert_eq!(state.refusal(2), Err(ENOSPC), "a new owner facing only held slots is refused for capacity"); assert!(!state.can_pick(2, Plan::Any), "scheduler admission counts no held slot"); assert_eq!(state.pick(2, 1, Plan::Any), None, "a held slot goes to no new owner"); - state.claim_sibling(1, cfg::RENDER_PAIRS_MAX); + state.claim_sibling(1, cfg::RENDER_PAIRS_MAX, 0); assert_eq!(state.owners[5], 1005, "a sibling never comes from a held slot"); + // With pair capacity to spare a sibling is claimed, but from the next + // released slot: slot 5 is the oldest release and stays held. + let mut spare = crowded(&[5, 9, 2]); + assert!(!spare.set_held(5, true)); + spare.owners[9] = 1; + spare.released &= !bit(9); + spare.render_capacity = SLOTS; + spare.claim_sibling(1, cfg::RENDER_PAIRS_MAX, 0); + assert_eq!(spare.owners[5], 1005, "a sibling never comes from a held slot"); + assert_eq!(spare.owners[2], 1, "a sibling comes from a released, unheld slot"); assert!(!state.reassign_unused_spare(5, Some(1005), Some(3)), "a held slot is no spare for another owner"); assert!(!state.reassign_unused_spare(5, Some(1005), None), "a held slot is not freed for compute"); assert_eq!(state.owners[5], 1005); @@ -273,6 +288,11 @@ def held_fixture(): assert_eq!(state.acquire(8, 1), Some(13)); assert_eq!(state.refusal(9), Err(ENOSPC)); assert_eq!(state.acquire(9, 1), None, "a closed owner's held pair goes to no other owner"); + // The closed owner itself is refused too: the kernel may have closed it for a client whose + // early publication still asks (`try_render_early`). Retaking its idle pair would clear + // `released`, and nothing would release it again. + assert!(state.owner_released(7), "a released owner takes no pair back"); + assert!(!state.owner_released(8), "an owner that took a released pair is not closed"); } fn holds_and_stop() { @@ -318,6 +338,8 @@ def held_fixture(): 'no-held-wake': ('if cleared {\n self.returned();', 'if false {\n self.returned();'), 'wake-on-every-clear': ('was && !held', '!held'), 'no-held-stop': ('state.held = 0;', ''), + 'released-owner-retakes': ('.any(|slot| self.owners[slot] == owner && self.released & (1u64 << slot) != 0)', + '.any(|_| false)'), 'held-blocks-owner': ('&& (self.quarantined | self.kill_hold) & (1u64 << slot) == 0\n && self.refs[slot] < cfg::RENDER_DEPTH', '&& (self.quarantined | self.kill_hold | self.held) & (1u64 << slot) == 0\n && self.refs[slot] < cfg::RENDER_DEPTH'), } @@ -347,6 +369,7 @@ def release_fixture(): render_teardown = (ROOT / 'runtime/render/teardown.rs').read_text() backend = (ROOT / 'runtime/backend.rs').read_text() pair = (ROOT / 'queue/render.rs').read_text() + render_exit = (ROOT / 'runtime/render/exit.rs').read_text() hw = (ROOT.parent / 'hw/t8140.rs').read_text() constants = '\n'.join(re.search(r'pub\(crate\) const ' + name + r': [^;]+;', hw).group(0) for name in ['RENDER_SLOTS', 'RENDER_PAIRS_MAX', 'RENDER_DEPTH']) @@ -354,17 +377,28 @@ def release_fixture(): at = pairs.index('const SIBLING_BACKLOG') backlog = pairs[at:pairs.index('\n}\n', pairs.index('fn sibling_backlog', at)) + 3] state = '\n'.join(item(source, name) for name in [ - 'const fn new(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', - 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn usable(', 'fn set_held(', - 'fn sync_held(', 'fn retained(', 'fn used(']) + 'const fn new(', 'fn owns_live(', 'fn has_live_owner(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', + 'fn set_owner(', 'fn take_idle(', 'fn acquire(', 'fn acquire_for(', 'fn live_owners(', 'fn live_siblings(', + 'fn reclaimable_siblings_in(', 'fn reclaimable_siblings(', 'fn promotes_reclaimable_sibling(', + 'fn can_lease_slot(', 'fn unavailable_released(', 'fn total_pair_demand(', 'fn pair_demand(', + 'fn claim_sibling(', 'fn usable(', 'fn can_reassign_unused_spare(', 'fn reassign_unused_spare(', + 'fn release_unused_sibling(', 'fn hold_for_exit_kill(', 'fn set_held(', 'fn sync_held(', 'fn retained(', 'fn used(']) pool = '\n'.join(item(source, name) for name in [ + 'pub(crate) fn can_reassign_unused_spare(', 'pub(crate) fn reassign_unused_spare(', + 'pub(crate) fn release_unused_sibling(', 'pub(crate) fn owns_live_slot(', + 'pub(crate) fn is_wide(', 'pub(crate) fn hold_render_slots_for_exit_kill(', 'pub(crate) fn set_held(', 'pub(crate) fn sync_held(', 'pub(crate) fn release_owner(']) pending = '\n'.join(item(teardown, name) for name in [ 'pub(crate) fn new(', 'pub(crate) fn releasing(', 'fn find(', 'fn insert(', 'pub(crate) fn close(', 'pub(crate) fn take_consumed(']) runtime = '\n'.join(item(render, name) for name in [ + 'pub(super) fn reclaim_unused_render_spare(', 'pub(super) fn hold_render_slot(', 'pub(super) fn sync_render_holds(', - 'fn render_slot_held(']).replace('pub(super) fn', 'pub fn') + 'fn render_slot_held(']).replace('pub(super) fn', 'pub fn').replace('KBox::into_inner(pair).park()', '(*pair).park()') + render_state = '\n'.join(item(render_exit, name) for name in [ + 'pub(in crate::g17::runtime) fn exit_scope(', + 'pub(in crate::g17::runtime) fn slot_owner(', + 'pub(in crate::g17::runtime) fn qids_for_slot(']).replace('pub(in crate::g17::runtime) fn', 'pub fn') firmware = '\n'.join('pub ' + item(render, name) for name in ['fn with_render(', 'fn with_render_at(']) return r""" #![allow(dead_code, unused_macros, unused_imports, unused_variables)] @@ -375,16 +409,25 @@ def release_fixture(): const EIO: i32 = -5; const EBUSY: i32 = -16; const EINVAL: i32 = -22; +const ENOMEM: i32 = -12; #[derive(Clone, Copy)] struct Flags; const GFP_KERNEL: Flags = Flags; +/// The next `KVec::push` fails as an allocation would. +static FAIL_PUSH: AtomicBool = AtomicBool::new(false); /// The kernel vector's fallible push and remove. #[derive(Clone)] struct KVec(Vec); impl KVec { const fn new() -> Self { KVec(Vec::new()) } fn with_capacity(capacity: usize, _: Flags) -> Result { Ok(KVec(Vec::with_capacity(capacity))) } - fn push(&mut self, value: T, _: Flags) -> Result { self.0.push(value); Ok(()) } + fn push(&mut self, value: T, _: Flags) -> Result { + if FAIL_PUSH.swap(false, SeqCst) { + return Err(ENOMEM); + } + self.0.push(value); + Ok(()) + } fn remove(&mut self, index: usize) -> std::result::Result { if index < self.0.len() { Ok(self.0.remove(index)) } else { Err(()) } } @@ -403,10 +446,15 @@ def release_fixture(): """ + backlog + r""" } pub mod context { - pub struct Context { pub published: bool, pub scheduler: u64 } + pub struct Context { pub published: bool, pub scheduler: u64, pub closed: std::sync::atomic::AtomicBool } impl Context { pub fn is_published(&self) -> bool { self.published } pub fn scheduler_va(&self) -> u64 { self.scheduler } + pub fn note_closed(&self, _generation: u64) { + self.closed.store(true, std::sync::atomic::Ordering::Release); + } + pub fn is_closed(&self) -> bool { self.closed.load(std::sync::atomic::Ordering::Acquire) } + pub fn note_open_client(&self, _open: bool) {} } } pub mod teardown { @@ -452,27 +500,60 @@ def release_fixture(): """ + item(pair, 'pub(crate) fn unreusable_work(') + r""" pub fn context(&self) -> &Arc { &self.context } pub fn release_owner(&mut self) { self.owner = None; } + pub fn detachable(&self) -> Result { Ok(!self.quarantined && self.active.is_empty()) } + pub fn reusable(&self) -> Result { Ok(self.owner.is_none() && self.detachable()?) } + pub fn can_yield_unused(&self) -> Result { Ok(false) } + pub fn buffer_id(&self) -> u8 { 0 } + pub fn park(self) -> ((), ()) { ((), ()) } + } + #[derive(Clone, Copy)] + pub struct Qid(pub u8); + impl Qid { pub fn qid(self) -> u8 { self.0 } } + pub struct Qids; + impl Qids { + pub fn can_cancel_unpublished(&self, _: Qid) -> bool { false } + pub fn cancel_unpublished(&mut self, _: Qid) -> Result { Ok(()) } } - pub struct Reservation { pub owner: u64 } + pub struct Buffers; + impl Buffers { pub fn unreserve_owner(&mut self, _: u8) -> Result { Ok(()) } } + pub struct UnusedRenderSpare { _entry: Option, _binding: Option<()> } + pub struct Reservation { pub owner: u64, pub ids: [Qid; 2] } pub struct Entry { pub reservation: Reservation, pub context: Option>, pub pair: Option>, - pub parked: bool, + pub pool: Option<()>, + pub parked: Option<()>, pub preparing: Option<()>, + pub constructing: bool, pub growing: bool, pub pending_owner: Option, pub pending_owner_closed: bool, + pub pending_error: Option<()>, + pub pending_timeout: bool, pub closed: bool, } pub struct RenderState { pub entries: Vec> } - pub struct Registry { pub admission: Arc, pub render: RenderState, pub teardown: Pending } + impl RenderState { + pub fn collect_retired(&mut self, _: usize) -> Result { Ok(()) } +""" + render_state + r""" + } + pub struct Registry { + pub admission: Arc, + pub render: RenderState, + pub teardown: Pending, + pub qids: Qids, + pub buffers: Buffers, + } impl Registry { pub fn release_compute(&mut self, _: u64) -> Result { Ok(()) } + pub fn note_build_room(&self) {} """ + item(render_teardown, 'pub(in crate::g17::runtime) fn release_render(') + '\n' + runtime + r""" } """ + item(render, 'fn render_hold(') + r""" - pub struct Firmware { pub queues: Registry } + pub struct Recovery; + impl Recovery { pub fn generation(&self) -> u64 { 0 } } + pub struct Firmware { pub queues: Registry, pub recovery: Recovery } pub struct Host<'a> { firmware: &'a mut Firmware, registration_powered: bool, @@ -533,13 +614,15 @@ def release_fixture(): } use g17::context::Context; -use g17::runtime::{Active, Entry, Firmware, Pair, Registry, RenderState, Reservation}; +use g17::runtime::{Active, Buffers, Entry, Firmware, Pair, Qid, Qids, Recovery, Registry, RenderState, Reservation}; use g17::runtime::backend::{Backend, Channels, Lock as DeviceLock, Shared}; const SLOTS: usize = cfg::RENDER_SLOTS; const NEW: u64 = 5000; fn bit(slot: usize) -> u64 { 1u64 << slot } fn owner(slot: usize) -> u64 { 1000 + slot as u64 } -fn context(scheduler: u64) -> Arc { Arc::new(Context { published: true, scheduler }) } +fn context(scheduler: u64) -> Arc { + Arc::new(Context { published: true, scheduler, closed: std::sync::atomic::AtomicBool::new(false) }) +} /// Every slot is retained by an open owner and no new graph fits; `pairs` are installed. fn device(pairs: &[(usize, &Arc)]) -> Arc { let mut state = State::new(); @@ -557,7 +640,7 @@ def release_fixture(): let mut entries: Vec> = (0..SLOTS).map(|_| None).collect(); for (slot, context) in pairs { entries[*slot] = Some(Entry { - reservation: Reservation { owner: owner(*slot) }, + reservation: Reservation { owner: owner(*slot), ids: [Qid((*slot * 2) as u8), Qid((*slot * 2 + 1) as u8)] }, context: Some((*context).clone()), pair: Some(Box::new(Pair { quarantined: false, @@ -565,16 +648,26 @@ def release_fixture(): context: (*context).clone(), owner: Some(owner(*slot)), })), - parked: false, + pool: Some(()), + parked: None, preparing: None, + constructing: false, growing: false, pending_owner: None, pending_owner_closed: false, + pending_error: None, + pending_timeout: false, closed: false, }); } - let queues = Registry { admission, render: RenderState { entries }, teardown: g17::teardown::Pending::new().unwrap() }; - Arc::new(Shared { state: DeviceLock(Mutex::new(Some(Box::new(Firmware { queues })))), channels: Channels }) + let queues = Registry { + admission, + render: RenderState { entries }, + teardown: g17::teardown::Pending::new().unwrap(), + qids: Qids, + buffers: Buffers, + }; + Arc::new(Shared { state: DeviceLock(Mutex::new(Some(Box::new(Firmware { queues, recovery: Recovery })))), channels: Channels }) } fn backend(shared: &Arc, slot: usize, context: &Arc) -> Backend { Backend { closed: AtomicBool::new(false), shared: shared.clone(), context: context.clone(), owner: owner(slot) } @@ -599,7 +692,7 @@ def release_fixture(): for entry in self.render.entries.iter_mut().flatten() { if entry.pair.as_ref().is_some_and(|pair| Arc::ptr_eq(pair.context(), context)) { entry.pair = None; - entry.parked = true; + entry.parked = Some(()); } } Ok(()) @@ -685,6 +778,12 @@ def release_fixture(): assert_eq!(state.held & bit(31), 0, "a consumed release returns its parked pair's slot"); assert!(wakes(&shared) > before, "and wakes the publications waiting for render capacity"); assert_eq!(state.clone().acquire(NEW, 1), Some(31), "a new owner takes the parked pair, not the one whose release is pending"); + // A queue the kernel closed for its client (`Firmware::close_failed_owners`) is closed by that + // client later: its released scheduler gets no second teardown entry, its slot no new hold. + backend(&shared, 31, &healthy).release_queue().unwrap(); + with(&shared, |firmware| assert!(!firmware.queues.teardown.releasing(&healthy), + "a second close of a released context arms no second scheduler release")); + assert_eq!(admission(&shared).held & bit(31), 0, "and holds its parked pair's slot no more"); assert_ne!(state.held & bit(30), 0); // Once the stuck release is consumed too, its slot returns, as the older one. consume(&shared, &stuck, 9); @@ -696,6 +795,22 @@ def release_fixture(): assert!(!raced.iter().take(2).any(|got| *got == Some(30))); } +/// A close that cannot reserve its teardown entry does not count as the first close: the +/// next close (the client's, or `Firmware::close_failed_owners` again) does all of it. +fn failed_close_is_redone() { + let failed = context(0x14); + let shared = device(&[(14, &failed)]); + FAIL_PUSH.store(true, SeqCst); + assert_eq!(backend(&shared, 14, &failed).release_queue(), Err(ENOMEM)); + assert!(!failed.is_closed(), "a close that failed to reserve its teardown entry is not noted"); + assert_eq!(admission(&shared).released & bit(14), 0, "and releases nothing"); + backend(&shared, 14, &failed).release_queue().unwrap(); + assert!(failed.is_closed()); + with(&shared, |firmware| assert!(firmware.queues.teardown.releasing(&failed), + "the next close reserves the teardown entry")); + assert_ne!(admission(&shared).released & bit(14), 0, "and releases the owner"); +} + /// Quarantined and owed pairs are held by the same rule; a lent pair keeps its bit. fn work_and_lent_pairs() { let (open, other) = (context(0x12), context(0x20)); @@ -745,22 +860,80 @@ def release_fixture(): assert_eq!(admission(&shared).held, bit(20), "only the quarantined pair stays held"); } +/// Detaching an idle published sibling in `reclaim_unused_render_spare` must keep +/// `admission.owners[slot]` synced with `entry.reservation.owner`/`entry.context` in +/// `released` state so `exit_scope` + `hold_render_slots_for_exit_kill` still succeed if +/// the prior owner exits before the requester binds the slot. +fn spare_detach_keeps_exit_kill_ownership() { + let old_ctx = context(0x40); + let shared = device(&[(1, &old_ctx), (2, &old_ctx)]); + let old_owner = owner(1); + with(&shared, |firmware| { + let mut state = firmware.queues.admission.state.lock(); + state.owners[2] = old_owner; + state.refs[1] = 1; + state.active |= bit(1); + state.published |= bit(1) | bit(2); + let entry2 = firmware.queues.render.entries[2].as_mut().unwrap(); + entry2.reservation.owner = old_owner; + entry2.pair.as_mut().unwrap().owner = Some(old_owner); + }); + let spare = with(&shared, |firmware| { + firmware + .queues + .reclaim_unused_render_spare(Some(NEW), false) + .unwrap() + }); + assert!(spare.is_some()); + drop(spare); + let state = admission(&shared); + assert_eq!(state.owners[2], old_owner); + assert_ne!(state.released & bit(2), 0); + assert_eq!(state.published & bit(2), 0); + with(&shared, |firmware| { + { + let mut state = firmware.queues.admission.state.lock(); + state.refs[1] = 0; + state.active &= !bit(1); + } + let (own, _, slots) = firmware.queues.render.exit_scope(&old_ctx); + assert_ne!(slots & bit(2), 0); + assert_eq!(firmware.queues.render.slot_owner(2), Some(old_owner)); + let qids = own; + let hold = (0..SLOTS as u8) + .filter(|slot| slots & bit(usize::from(*slot)) != 0 + && firmware.queues.render.qids_for_slot(*slot) & qids != 0) + .fold(0u64, |acc, slot| acc | bit(usize::from(slot))); + firmware.queues.admission.release_owner(old_owner); + assert!(firmware.queues.admission.hold_render_slots_for_exit_kill(old_owner, hold, 0)); + }); +} + fn main() { closed_owner_release(); + failed_close_is_redone(); work_and_lent_pairs(); - println!("PASS release holds: a closed owner's idle pair is held from its close, before admission releases its slot, through retirement passes and resyncs, until its scheduler release is consumed and the pair parked; no new owner is given it meanwhile; quarantined and owed pairs are held by the same rule and their own owner keeps them; a lent pair keeps its bit and is held when its owner closes meanwhile; a missing or parked pair is never held"); + spare_detach_keeps_exit_kill_ownership(); + println!("PASS release holds: a closed owner's idle pair is held from its close, before admission releases its slot, through retirement passes and resyncs, until its scheduler release is consumed and the pair parked; no new owner is given it meanwhile; quarantined and owed pairs are held by the same rule and their own owner keeps them; a lent pair keeps its bit and is held when its owner closes meanwhile; a missing or parked pair is never held; detaching a published spare preserves exit-kill ownership"); } """ # Each drops one part of the runtime's hold rule. RELEASE_MUTATIONS = { + 'spare-detach-reassigns': ('let claimed = if detach {\n self.admission\n .release_unused_sibling(slot as u8, expected, true)\n } else {\n self.admission\n .reassign_unused_spare(slot as u8, expected, owner)\n };', + 'let claimed = self.admission.reassign_unused_spare(slot as u8, expected, owner);'), 'hold-ignores-release': ('pair.unreusable_work() || teardown.releasing(pair.context())', 'pair.unreusable_work()'), 'hold-ignores-work': ('pair.unreusable_work() || teardown.releasing(pair.context())', 'teardown.releasing(pair.context())'), - 'close-unheld': ('firmware.queues.sync_render_holds();\n firmware.queues.admission.release_owner(self.owner);', + 'close-unheld': ('firmware.queues.sync_render_holds();\n firmware.queues.admission.release_owner(self.owner);', 'firmware.queues.admission.release_owner(self.owner);'), - 'hold-after-release': ('firmware.queues.sync_render_holds();\n firmware.queues.admission.release_owner(self.owner);', - 'firmware.queues.admission.release_owner(self.owner);\n firmware.queues.sync_render_holds();'), + # The client's close after the kernel's repeats the firmware side. + 'close-twice': ('if !self.context.is_closed() {', 'if true {'), + # A close that fails to reserve its teardown entry still counts as the first. + 'latch-before-close': ('if !self.context.is_closed() {', + 'if !self.context.is_closed() && { self.context.note_closed(firmware.recovery.generation()); true } {'), + 'hold-after-release': ('firmware.queues.sync_render_holds();\n firmware.queues.admission.release_owner(self.owner);', + 'firmware.queues.admission.release_owner(self.owner);\n firmware.queues.sync_render_holds();'), 'put-back-own-work': ('self.queues.hold_render_slot(slot);\n result', 'let held = self.queues.render.entries[slot].as_ref().and_then(|entry| entry.pair.as_ref())' '.is_some_and(|pair| pair.unreusable_work());\n self.queues.admission.set_held(slot, held);\n result'), diff --git a/tools/asahi/g17-capacity-fault-tests.py b/tools/asahi/g17-capacity-fault-tests.py index 72f2552d781a49..46b6ec3c51438e 100644 --- a/tools/asahi/g17-capacity-fault-tests.py +++ b/tools/asahi/g17-capacity-fault-tests.py @@ -109,7 +109,8 @@ def fixture(): mod qos { pub type Owner = u64; } enum Deferred { Retired(Arc, Result<[u64; 4]>), Release(Arc) } struct Queue { - owner: Option, installed: bool, active: Fifo, quarantined: bool, + owner: Option, channel_index: u8, binding_noted: bool, + installed: bool, active: Fifo, quarantined: bool, previous: Option, unpublished_binding: bool, released: bool, graph: Graph, binding: Option, retirement_ready: bool, released_at: u64, growing: bool, pool_phase: PoolPhase, needs_fresh_backing: bool, exit: Option, replays: Fifo>, @@ -126,11 +127,24 @@ def fixture(): fn valid_ticket(&self, _: &Active, _: &Ticket) -> Result { Ok(()) } fn qos_owner(&self) -> u64 { 1 } fn context(&self) -> Option<&Arc> { self.binding.as_ref().map(|binding| &binding.context) } + fn clear_binding_note(&mut self) { + if self.binding_noted { + if let Some(binding) = &self.binding { binding.context.note_compute_binding(false); } + self.binding_noted = false; + } + } + fn clear_owner(&mut self, stamp_released_at: bool) { + self.clear_binding_note(); + self.owner = None; + self.channel_index = 0; + if stamp_released_at { self.released_at = now_ns(); } + } ''' + methods + r''' } fn idle(live: &Arc) -> Queue { Queue { - owner: Some(2), installed: true, active: Fifo::new(), quarantined: false, + owner: Some(2), channel_index: 0, binding_noted: false, + installed: true, active: Fifo::new(), quarantined: false, previous: None, unpublished_binding: false, released: false, graph: Graph { cursors: Cursors { count: 1280, producer: 4, consumer: 4 }, stamp: 7 << 8, fail: false, resets: 0, owner: 2, m5: false }, binding: Some(Binding { context: Context::new(2, live) }), retirement_ready: false, diff --git a/tools/asahi/g17-compute-deadline-tests.py b/tools/asahi/g17-compute-deadline-tests.py index a97a3b4021e746..fb3585ea7ec901 100644 --- a/tools/asahi/g17-compute-deadline-tests.py +++ b/tools/asahi/g17-compute-deadline-tests.py @@ -35,7 +35,8 @@ def fixture(): ('super::recovery::Memory', 'Memory'), ('super::fw::compute_pool::required_blocks', 'required_blocks'), ('super::freelist::ComputeCapacity', 'ComputeCapacity'), - ('super::preparation::QUEUE_WAIT_NS', 'QUEUE_WAIT_NS')]: + ('super::preparation::QUEUE_WAIT_NS', 'QUEUE_WAIT_NS'), + ('super::pairs::SIBLING_HEADROOM_BACKOFF_NS', 'SIBLING_HEADROOM_BACKOFF_NS')]: packet = packet.replace(old, new) ensure = ensure.replace(old, new) admission = (item(preparation, "pub(super) struct Admission<'a>") + '\n' + @@ -85,7 +86,8 @@ def fixture(): // A work-state node is taken per engine: compute admission must ask for a compute one. struct Work;impl Work{fn acquire(&self,engine:g17::job::Engine)->Result{assert_eq!(engine,g17::job::Engine::Compute,"compute admission takes a compute work state");if MODE.load(Ordering::SeqCst)==4{Err(EBUSY)}else{Ok(1)}}} struct Completion;impl Completion{fn status(&self)->Status{Status}fn work_state(&self)->Result{Ok(Work)}} -struct Packet{command:Validated,completion:Completion} +struct Order{wait_through:[Option;2]} +struct Packet{command:Validated,completion:Completion,order:Order} impl Packet{fn check_dependencies(&self)->Result{Ok(())}fn cancel_requested(&self)->bool{now_ns()>=CANCEL.load(Ordering::SeqCst)}fn is_published(&self)->bool{false}} struct DeferredBatch;impl DeferredBatch{fn publication()->Result{Ok(Self)}fn finish(&mut self){}} struct Recovery;impl Recovery{fn pending(&self)->bool{MODE.load(Ordering::SeqCst)==1}} @@ -98,7 +100,13 @@ def fixture(): fn compute(&self,_:u64)->Option<()>{if MODE.load(Ordering::SeqCst)==0{None}else{Some(())}} fn render_prefix(&self,_:u64,_:&Arc)->Result>{Ok(vec![])} fn release_compute_witness(&self,_:&Init,_:&(),_:u64,_:&mut DeferredBatch)->Result{Ok(MODE.load(Ordering::SeqCst)==2)} + fn wants_compute_sibling(&self,_:u64,_:&Context,_:u8,_:usize)->bool{false} + fn has_compute_sibling_headroom(&self,_:u64,_:&Context,_:usize)->bool{true} + fn bind_reusable_sibling(&mut self,_:u64,_:&Context,_:u8,_:usize)->Result>{Ok(None)} + fn compute_primary(&self,_:u64)->Option{None} } +struct Primary;impl Primary{fn sustained(&self)->bool{false}} +const SIBLING_HEADROOM_BACKOFF_NS:u64=10_000_000; struct Firmware{recovery:Recovery,init:Init,queues:Queues,port:()} // Mode 6: the publication itself refuses with EBUSY (no recovery): an immediate error, not a spent budget. impl Firmware{fn replay_compute(&mut self,_:&mut DeferredBatch)->Result{Ok(())}fn publish_compute(&mut self,_:u64,_:Arc,_:&[()],_:&mut DeferredBatch)->Result{if MODE.load(Ordering::SeqCst)==6{advance(5_000_000);Err(EBUSY)}else{Err(EAGAIN)}}} @@ -106,7 +114,7 @@ def fixture(): struct Available;impl Available{fn observe(&self)->u64{now_ns()}} struct Shared{preparations:Arc,state:State,crashed:AtomicBool,compute_blocks:usize,active_cores:u32,progress:Available}impl Shared{fn queue_events(&self){}} struct ComputeDemand;impl ComputeDemand{fn new(_:&Shared)->Self{Self}} -struct Backend{shared:Shared,owner:u64,context:Context} +struct Backend{shared:Shared,owner:u64,context:Context,compute_channels:u8,sibling_backoff_until:AtomicU64} fn required_blocks(_:usize,_:u32,_:u16)->Result{Ok(1)} type ComputeCapacity=usize; impl Backend{ @@ -118,6 +126,8 @@ def fixture(): fn compute_direct(&self,_:&Arc,_:usize,_:&mut DeferredBatch)->Option{None} fn sources_published(&self,_:&Arc)->Result{Ok(true)} fn remember_direct(&self,_:&Queues){} + fn try_add_compute_sibling(&self,_:usize,_:&Admission<'_>)->Result{Ok(false)} + fn fans_out(&self,_:&Packet,primary_sustained:impl FnOnce()->bool)->bool{self.compute_channels>1&&primary_sustained()} fn wait_release(&self,_:&Available,_:u64,admission:&Admission<'_>)->Result{ let _=admission.slice_ms()?; advance(1_000_000); @@ -140,8 +150,8 @@ def fixture(): ''' + ensure + '\n' + packet + r''' } fn main(){ - let b=Backend{owner:1,context:Context,shared:Shared{compute_blocks:21,active_cores:1,progress:Available,preparations:Arc::new(Gate{wait:Wait,changed:Changed}),state:State(Mutex::new(Some(Box::new(Firmware{recovery:Recovery,init:Init,queues:Queues,port:()})))),crashed:AtomicBool::new(false)}}; - let p=Arc::new(Packet{command:Validated::Compute{scratch:Scratch},completion:Completion}); + let b=Backend{owner:1,context:Context,compute_channels:1,sibling_backoff_until:AtomicU64::new(0),shared:Shared{compute_blocks:21,active_cores:1,progress:Available,preparations:Arc::new(Gate{wait:Wait,changed:Changed}),state:State(Mutex::new(Some(Box::new(Firmware{recovery:Recovery,init:Init,queues:Queues,port:()})))),crashed:AtomicBool::new(false)}}; + let p=Arc::new(Packet{command:Validated::Compute{scratch:Scratch},completion:Completion,order:Order{wait_through:[None,None]}}); for mode in 0..4 { MODE.store(mode,Ordering::SeqCst);NOW.store(0,Ordering::SeqCst);CALLS.store(0,Ordering::SeqCst);REPORTED.store(usize::MAX,Ordering::SeqCst); let r=b.compute_packet(&p,&mut DeferredBatch); diff --git a/tools/asahi/g17-compute-growth-deadline-tests.py b/tools/asahi/g17-compute-growth-deadline-tests.py index 1a29447f2f07e8..7ed4ca5c95277c 100644 --- a/tools/asahi/g17-compute-growth-deadline-tests.py +++ b/tools/asahi/g17-compute-growth-deadline-tests.py @@ -32,7 +32,11 @@ def fixture(): admission = ('#[derive(Clone,Copy,Debug,PartialEq)]\n' + item(prep, 'pub(super) enum AdmissionWait').replace('pub(super) ', '') + '\n' + next(line for line in prep.splitlines() if 'const ADMISSION_WAITS:' in line).replace('pub(super) ', '') + '\n' + admission) - methods = '\n'.join(item(runtime, sig) for sig in [' fn grow_compute(', ' fn finish_uninstalled_compute(']) + methods = '\n'.join(item(runtime, sig) for sig in [' fn grow_compute(', ' fn finish_uninstalled_compute(', + ' fn finish_retired_compute(']) + # The per-channel places growth hands drained siblings over in. + aliases = '\n'.join(next(line for line in runtime.splitlines() if line.startswith(prefix)) + for prefix in ('type Uninstalled =', 'type PerChannel =')).replace('super::pairs::', '') methods = (methods.replace('super::object::Allocator', 'Allocator').replace('super::freelist::Pages', 'Pages') .replace('super::freelist::ComputeCapacity', 'ComputeCapacity')) return r''' @@ -41,6 +45,7 @@ def fixture(): use std::sync::{Mutex,MutexGuard,atomic::{AtomicBool,AtomicU64,Ordering,fence}}; type Result = std::result::Result; type KBox = Box; +type KVec = Vec; const EIO:i32=-5;const EAGAIN:i32=-11;const ENODEV:i32=-19;const EBUSY:i32=-16;const ECANCELED:i32=-125; const RECOVERY_WAIT_MS:u32=26_000; static NOW:AtomicU64=AtomicU64::new(0);static ALIAS:AtomicBool=AtomicBool::new(false);static PAGES:AtomicBool=AtomicBool::new(false); @@ -74,8 +79,11 @@ def fixture(): impl Drop for Pages{fn drop(&mut self){PAGES.store(false,Ordering::SeqCst);}} impl Drop for Alias{fn drop(&mut self){ALIAS.store(false,Ordering::SeqCst);}} mod compute{pub(crate) use crate::Queue;} +const COMPUTE_CHANNELS_MAX:usize=3; +''' + aliases + r''' struct Queue{fresh:bool} impl Queue{ + fn owner(&self)->Option{Some(1)} fn pool_fits(&self,_:usize)->bool{false} fn begin_growth(&mut self,_:&(),_:usize)->Result{Ok(false)} fn growth_token(&self)->Option{Some(7)} @@ -89,6 +97,8 @@ def fixture(): impl Registry{ fn compute(&self,_:u64)->Option<&Queue>{self.compute[0].as_ref().unwrap().queue.as_deref()} fn compute_mut(&mut self,_:u64)->Option<&mut Queue>{self.compute[0].as_mut().unwrap().queue.as_deref_mut()} + fn compute_primary(&mut self,owner:u64)->Option<&mut Queue>{self.compute_mut(owner)} + fn drain_compute_siblings(&mut self,_:u64,_:&mut PerChannel)->Result{Ok(())} fn cancel_compute(&mut self,_:ComputeReservation)->Result{assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst));RESERVED.store(false,Ordering::SeqCst);Ok(())} } struct Primary;impl Primary{fn notify(&self,_:u32)->Result{Ok(())}} diff --git a/tools/asahi/g17-compute-multi-channel-feature-tests.py b/tools/asahi/g17-compute-multi-channel-feature-tests.py new file mode 100755 index 00000000000000..03de6b0ad3b7fb --- /dev/null +++ b/tools/asahi/g17-compute-multi-channel-feature-tests.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: G17 GET_PARAMS reports DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL exactly where the +kernel fans compute out itself. + +Compiles the production board selection of drivers/gpu/drm/asahi/g17/pairs.rs +(`select_board()`, `compute_channels_per_owner()`), `multi_channel()` of +g17/fw/m5/compute.rs, `Board::compute_channels()` and every board's +`compute_channels` value of g17/fw/m5/initdata.rs, `compute_channel_features()` +of g17/mod.rs and the feature constant of file.rs, the latter against every +DRM_ASAHI_FEATURE_* bit that include/uapi/drm/asahi_drm.h defines. It checks +that the bit is set exactly when a logical compute queue may hold more than one +physical compute channel: on the M5 Pro (J714), and neither on the M5 Max, +the M5 Ultra and the M5 (J716C, J775D, J813), whose boards run one firmware +compute queue per command queue, nor on GPUs that never select an M5 board +(G17P), so userspace keeps its own sibling queues there; that the decision reads +the board's channel count alone, never its encoding forms; that GET_PARAMS +reports it from the probed board's channel count on every G17; and that the bit +is distinct from every other feature bit. + +Each mutation drops one part of the rule and must fail an assertion of the +compiled harness. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +ASAHI = ROOT / 'drivers/gpu/drm/asahi' +G17 = ASAHI / 'g17' +UAPI = ROOT / 'include/uapi/drm/asahi_drm.h' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +REPORTED = ' | compute_channel_features(pairs::compute_channels_per_owner());\n' + +# name -> [(file, old, new)]: each must apply exactly once. +MUTATIONS = { + 'always-multi': [('mod', ' if channels > 1 {\n crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL', + ' if channels > 0 {\n crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL')], + 'never-multi': [('mod', ' if channels > 1 {\n crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL', + ' if false {\n crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL')], + 'not-reported': [('mod', ' | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT\n' + REPORTED, + ' | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT;\n')], + 'per-board-gate': [('mod', REPORTED, + ' | compute_channel_features(pairs::COMPUTE_CHANNELS_MAX as u8);\n')], + 'forms-gate': [('fw', ' board.compute_channels() > 1\n', + ' board.compute_channels() > 1 || !board.g17d_forms()\n')], + 'max-channels': [('pairs', ' COMPUTE_CHANNELS.store(board.compute_channels(), Relaxed);', + ' COMPUTE_CHANNELS.store(COMPUTE_CHANNELS_MAX as u8, Relaxed);')], + 'multi-channel-max': [('initdata', ' host_only_render_kicks: true,\n compute_channels: 1,\n', + ' host_only_render_kicks: true,\n compute_channels: 3,\n')], + 'colliding-bit': [('uapi', '#define DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL ((1ULL) << 42)', + '#define DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL ((1ULL) << 39)')], + 'unsynced-binding': [('file', ' uapi::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL as u64;', + ' uapi::DRM_ASAHI_FEATURE_ASYNC_SUBMIT as u64;')], +} + + +def build(mutation=None): + files = { + 'pairs': (G17 / 'pairs.rs').read_text(), + 'mod': (G17 / 'mod.rs').read_text(), + 'fw': (G17 / 'fw/m5/compute.rs').read_text(), + 'file': (ASAHI / 'file.rs').read_text(), + 'uapi': UAPI.read_text(), + 'initdata': (G17 / 'fw/m5/initdata.rs').read_text(), + } + for name, old, new in MUTATIONS.get(mutation, []): + assert files[name].count(old) == 1, (mutation, old) + files[name] = files[name].replace(old, new) + pairs, mod, fw, file, uapi, initdata = (files[k] for k in ('pairs', 'mod', 'fw', 'file', 'uapi', 'initdata')) + + # Every board's own channel count, following `..BASE` for a board that inherits it. + boards = {} + for name, body in re.findall(r'^pub\(crate\) const (\w+): Board = Board \{\n(.*?)^\};', initdata, re.M | re.S): + own = re.search(r'^ compute_channels: (\d+),$', body, re.M) + base = re.search(r'^ \.\.(\w+)$', body, re.M) + assert own or base, name + boards[name] = int(own.group(1)) if own else boards[base.group(1)] + assert set(boards) == {'J714', 'J716C', 'J775D', 'J813', 'J813_26B123'}, boards + board_table = ',\n'.join(f' ("{name}", {n})' for name, n in boards.items()) + channels_fn = item(initdata, 'pub(crate) const fn compute_channels(').replace('pub(crate) ', '') + + bits = re.findall(r'^\s*(DRM_ASAHI_FEATURE_\w+)\s*=\s*\(1U?L{0,2}\)\s*<<\s*(\d+),', uapi, re.M) + bits += re.findall(r'^#define\s+(DRM_ASAHI_FEATURE_\w+)\s+\(\(1ULL\)\s*<<\s*(\d+)\)', uapi, re.M) + names = [name for name, _ in bits] + uapi_mod = '\n'.join(f' pub const {name}: u64 = 1 << {bit};' for name, bit in bits) + table = ',\n'.join(f' ("{name}", 1u64 << {bit})' for name, bit in bits) + + pairs_code = '\n'.join([ + re.search(r'pub\(crate\) const COMPUTE_CHANNELS_MAX: usize = \d+;', pairs).group(0), + re.search(r'const MULTI_PAIRS: u8 = [^;]+;', pairs).group(0), + re.search(r'static PAIRS: AtomicU8 = AtomicU8::new\(\d+\);', pairs).group(0), + re.search(r'static COMPUTE_CHANNELS: AtomicU8 = AtomicU8::new\(\d+\);', pairs).group(0), + item(pairs, 'pub(crate) fn select_board('), + item(pairs, 'pub(crate) fn per_owner('), + item(pairs, 'pub(crate) fn compute_channels_per_owner('), + ]).replace('pub(crate) ', 'pub ').replace('crate::g17::fw::m5::initdata::Board', 'crate::Board') \ + .replace('crate::g17::fw::m5::compute::multi_channel', 'crate::multi_channel') \ + .replace('RENDER_PAIRS_MAX as u8', '2u8') + features = item(mod, 'fn compute_channel_features(') + multi = item(fw, 'pub(crate) fn multi_channel(').replace('pub(crate) ', '') + file_const = re.search(r'pub\(crate\) const DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL: u64 =\s*[^;]+;', file).group(0) + params = item(mod, 'fn get_params(&self, params: &mut uapi::drm_asahi_params_global)') + structure = { + 'GET_PARAMS reports the bit from the probed channel count on every G17': ordered_ok( + params, 'params.features |=', '| crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT', REPORTED.strip(), + 'let variant = self.shared.variant;'), + 'the UAPI header defines the bit': 'DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL' in names, + } + checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' for name, ok in structure.items()) + return (TEMPLATE.replace('@@UAPI@@', uapi_mod).replace('@@TABLE@@', table).replace('@@PAIRS@@', pairs_code) + .replace('@@FEATURES@@', features).replace('@@MULTI@@', multi).replace('@@FILE@@', file_const) + .replace('@@STRUCTURE@@', checks).replace('@@BOARDS@@', board_table) + .replace('@@CHANNELS@@', channels_fn)) + + +TEMPLATE = r''' +#![allow(dead_code)] +use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; + +mod uapi { +@@UAPI@@ +} +const FEATURES: &[(&str, u64)] = &[ +@@TABLE@@ +]; + +mod file { + use crate::uapi; + @@FILE@@ +} + +pub struct Board { g17d: bool, clusters: u32, compute_channels: u8 } +impl Board { + fn g17d_forms(&self) -> bool { self.g17d } + @@CHANNELS@@ +} +@@MULTI@@ + +/// The production boards and their `compute_channels`. +const BOARDS: &[(&str, u8)] = &[ +@@BOARDS@@ +]; + +mod pairs { + use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; + @@PAIRS@@ +} + +@@FEATURES@@ + +/// What GET_PARAMS reports, as get_params() computes it. +fn reported() -> u64 { compute_channel_features(pairs::compute_channels_per_owner()) } + +fn main() { +@@STRUCTURE@@ + + // The bit is the header's and no other feature has it. + let bit = file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL; + assert_eq!(bit, uapi::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL, "file.rs reports the header's bit"); + assert_eq!(bit.count_ones(), 1); + for (name, value) in FEATURES { + if *name != "DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL" { + assert_ne!(*value, bit, "{} shares the multi-channel bit", name); + } + } + + // A GPU that never selects an M5 board (G17P) has one channel per owner: no bit. + assert_eq!(pairs::compute_channels_per_owner(), 1); + assert_eq!(reported() & bit, 0, "single-channel G17P keeps its own sibling queues"); + // The production boards: only the M5 Pro holds several channels per owner, so only it + // reports the bit; the M5 Max, M5 Ultra and M5 run one firmware compute queue per queue. + for &(name, channels) in BOARDS { + let multi = name == "J714"; + assert!(channels >= 1 && usize::from(channels) <= pairs::COMPUTE_CHANNELS_MAX, "{}", name); + for (g17d, clusters) in [(false, 1), (false, 2), (true, 4), (true, 8)] { + let board = Board { g17d, clusters, compute_channels: channels }; + assert_eq!(multi_channel(&board), multi, "{}: multi_channel()", name); + pairs::select_board(&board); + assert_eq!(pairs::compute_channels_per_owner(), channels, "{}: channels per owner", name); + assert_eq!(reported() & bit, if multi { bit } else { 0 }, "{}: reported", name); + } + } + assert_eq!(BOARDS.iter().find(|b| b.0 == "J714").unwrap().1 as usize, pairs::COMPUTE_CHANNELS_MAX, + "the M5 Pro holds the most channels"); + // Set exactly when an owner may hold more than one channel, and nothing else. + for channels in 0..=u8::MAX { + assert_eq!(compute_channel_features(channels), if channels > 1 { bit } else { 0 }); + } + + println!("PASS g17-compute-multi-channel-feature: reported exactly where a queue holds several compute channels"); +} +''' + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + source = build(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-multi-channel-') as tmp: + path = Path(tmp) / 'feature.rs' + binary = path.with_suffix('') + path.write_text(source) + built = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', str(path), + '-o', str(binary)], capture_output=True, text=True) + if built.returncode: + sys.stderr.write(built.stderr) + return built.returncode + run = subprocess.run([str(binary)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-compute-owed-stamp-tests.py b/tools/asahi/g17-compute-owed-stamp-tests.py index c857199abad99e..76165e3cbbcd91 100644 --- a/tools/asahi/g17-compute-owed-stamp-tests.py +++ b/tools/asahi/g17-compute-owed-stamp-tests.py @@ -10,7 +10,9 @@ finished retires it on its record instead of failing its client; the commands behind it then retire past it; every retired command keeps its place and its descriptor until a stamp covers it; work that cannot retire that way is failed -as before. --mutation removes one part of that and must fail. +as before. Every retired kick with an exact execution record, and only those, +feeds its channel's run of heavy kicks once (g17/pairs.rs), which gates sibling +compute fan-out on M5 Pro. --mutation removes one part of that and must fail. """ from pathlib import Path import argparse @@ -79,6 +81,14 @@ def fixture(): 'pub(crate) fn owns_packet(', 'pub(crate) fn retired_held(', 'pub(crate) fn expire_stamp_wait(', 'pub(crate) fn timeout(', 'pub(crate) fn can_classify_timeout(']) + pairs = (G17 / 'pairs.rs').read_text() + hz = re.search(r'pub\(crate\) const COMMAND_TIMESTAMP_HZ: u64 = ([0-9_]+);', + (ROOT / 'hw/t8140.rs').read_text()).group(1) + gate = '\n'.join([f'pub(crate) const COMMAND_TIMESTAMP_HZ: u64 = {hz};'] + [ + re.search(r'(?:pub\(crate\) )?const ' + name + r': [^=]+= [^;]+;', pairs).group(0) + for name in ['SIBLING_EXECUTION_NS', 'SIBLING_EXECUTION_TICKS', 'SIBLING_SUSTAINED_KICKS']] + [ + item(pairs, 'pub(crate) fn heavy_run('), item(pairs, 'pub(crate) fn sustained(')] + ).replace('crate::hw::t8140::resources::', '') backend = '\n'.join([ item(control, 'pub(super) fn defer_compute_timeout(').replace('pub(super) ', '', 1), item(control, 'fn retire_on_record('), @@ -127,6 +137,9 @@ def fixture(): pub(crate) mod job { pub(crate) trait Backend { fn fail_vm(&self, error: crate::Error); } } + pub(crate) mod pairs { +''' + gate + r''' + } } mod module_parameters { pub(crate) struct Parameter(pub(crate) u32); @@ -235,6 +248,7 @@ def fixture(): released: bool, owner: Option, released_at: u64, + heavy_run: u8, terminal: Option<(Arc, Error)>, fault_stamp: Option, timed_out_at: u64, @@ -246,6 +260,10 @@ def fixture(): fn valid_ticket(&self, _: &Active, _: &Ticket) -> Result { Ok(()) } fn qos_owner(&self) -> qos::Owner { qos::Owner } fn classify(&self, _: &dyn Fn(&Arc) -> recovery::Class) {} + fn clear_owner(&mut self, stamp_released_at: bool) { + self.owner = None; + if stamp_released_at { self.released_at = now_ns(); } + } ''' + queue + r''' } @@ -259,6 +277,13 @@ def fixture(): .find(|queue| queue.owner() == Some(owner)) } fn compute_mut(&mut self, owner: u64) -> Option> { self.compute(owner) } + fn compute_for_packet(&self, owner: u64, packet: &Arc) -> Option> { + self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()) + .find(|queue| queue.owner() == Some(owner) && queue.owns_packet(packet)) + } + fn compute_for_packet_mut(&mut self, owner: u64, packet: &Arc) -> Option> { + self.compute_for_packet(owner, packet) + } /// Other VMs' heads, as render pairs and other queues give them. fn render_timeout_heads(&self) -> impl Iterator + '_ { self.render.iter().copied() @@ -308,7 +333,7 @@ def fixture(): retirement_proved: false, retired_by_teardown: false, spared_quarantine: false, spared_deferred: false, awaiting_witness: false, retire_pending: false, last_end: 0, previous: None, submitted: 0, retirement_ready: true, released: false, owner: Some(OWNER), - released_at: 0, terminal: None, fault_stamp: None, timed_out_at: 0, + released_at: 0, heavy_run: 0, terminal: None, fault_stamp: None, timed_out_at: 0, } } @@ -374,6 +399,60 @@ def fixture(): packet.completion.class.get() } + /// Execution record ticks of a kick lasting `us` microseconds. + fn ticks(us: u64) -> u64 { us * g17::pairs::COMMAND_TIMESTAMP_HZ / 1_000_000 } + + #[test] + fn only_exact_execution_records_feed_the_heavy_run() { + let heavy = ticks(g17::pairs::SIBLING_EXECUTION_NS / 1_000); + let mut q = queue(true); + let p1 = publish(&mut q, 0x10, true); + let p2 = publish(&mut q, 0x11, true); + let p3 = publish(&mut q, 0x12, true); + record(&mut q, &p1, [1_000, 1_000 + heavy]); + record(&mut q, &p2, [1_000 + heavy, 1_000 + 3 * heavy]); + // p3 retires without a record: its synthesized envelope measures nothing. + q.graph.stamp.set(stamp_of(0x12)); + let b = backend(q, vec![]); + scan(&b); + assert!(result(&p3).is_some_and(|result| result.is_ok())); + with_queue(&b, |q| { + assert_eq!(q.active.len, 0); + assert_eq!(q.heavy_run, 2, "two exact heavy records, nothing from the recordless kick"); + assert!(g17::pairs::sustained(q.heavy_run)); + }); + // One short record ends the run. + let p4 = with_queue(&b, |q| { + let p4 = publish(q, 0x13, true); + record(q, &p4, [9_000, 9_000 + ticks(3)]); + q.graph.stamp.set(stamp_of(0x13)); + p4 + }); + scan(&b); + assert!(result(&p4).is_some()); + with_queue(&b, |q| assert_eq!(q.heavy_run, 0, "a short kick closes the gate")); + } + + #[test] + fn a_kick_held_for_its_stamp_is_measured_once() { + let heavy = ticks(g17::pairs::SIBLING_EXECUTION_NS / 1_000); + let mut q = queue(false); + let p1 = publish(&mut q, 0x10, true); + let p2 = publish(&mut q, 0x11, true); + record(&mut q, &p1, [100, 100 + heavy]); + record(&mut q, &p2, [100 + heavy, 100 + 2 * heavy]); + let b = backend(q, vec![]); + // Late stamps: both retire on their records and stay held for their stamps. + advance(60 * MS); + scan(&b); + assert!(result(&p1).is_some() && result(&p2).is_some()); + with_queue(&b, |q| assert_eq!((q.active.len, q.heavy_run), (2, 2))); + with_queue(&b, |q| q.graph.stamp.set(stamp_of(0x11))); + scan(&b); + with_queue(&b, |q| assert_eq!((q.active.len, q.heavy_run), (0, 2), + "releasing a held descriptor measures nothing again")); + } + #[test] fn a_finished_head_whose_stamp_never_comes_retires_and_the_queue_moves_on() { let mut q = queue(false); @@ -654,7 +733,8 @@ def fixture(): MUTATIONS = { 'own-finished': [('_ if own.finished => Decision::Retire,', '_ if own.finished => Decision::Own,')], 'no-retire-glue': [('verdict.decision = self.retire_on_record(firmware, packet, &mut deferred)?;', '')], - 'retire-unchecked': [('if !firmware.queues.compute(self.owner).is_some_and(|queue| queue.retired_held(packet)) {', + 'retire-unchecked': [('if !firmware\n .queues\n .compute_for_packet(self.owner, packet)\n' + ' .is_some_and(|queue| queue.retired_held(packet))\n {', 'if false {')], 'no-expiry': [('if observed_at == Some(STAMP_WAIT_EXPIRED) {', 'if false {')], 'no-step-past': [('Ok(Some(_)) | Err(EAGAIN) if owed => at += 1,', 'Ok(Some(_)) | Err(EAGAIN) if owed => break,'), @@ -673,6 +753,13 @@ def fixture(): 'if !queue.owns_packet(packet) {')], 'no-owed-poll': [(' if at != 0 {\n // Owed stamps come without a completion event', ' if false {\n // Owed stamps come without a completion event')], + # A recordless retirement's synthesized envelope counts as an execution. + 'count-recordless': [('let execution = front.observed.map(|record| record.timestamps);', + 'let execution = Some(timestamps);')], + # Releasing a held descriptor measures the kick again. + 'count-owed-twice': [(' // The stamp now covers the held command: release its descriptor.\n', + ' // The stamp now covers the held command: release its descriptor.\n' + ' self.heavy_run = crate::g17::pairs::heavy_run(self.heavy_run, 0, u64::MAX);\n')], } diff --git a/tools/asahi/g17-compute-retired-tests.py b/tools/asahi/g17-compute-retired-tests.py new file mode 100755 index 00000000000000..900fdee4c47b4b --- /dev/null +++ b/tools/asahi/g17-compute-retired-tests.py @@ -0,0 +1,471 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: compute channels given up under the device mutex never leak a reservation. + +A logical compute queue holds up to `COMPUTE_CHANNELS_MAX` channels. When an +unpublished compute packet fails, `Backend::rollback_unpublished_compute()` +rolls back every channel of the owner, and before primary pool growth +`Registry::drain_compute_siblings()` releases every idle sibling. Both take +queues out of the registry under the device mutex. Each taken queue keeps an +empty registry entry, and so its QID, until it is dropped off-lock and its +reservation is cancelled (`finish_uninstalled_compute()`). An entry left empty +for good locks its owner out: `reserve_compute_channel()` refuses that owner +with `EINVAL`. + +This test compiles, against host stubs, the production code from +drivers/gpu/drm/asahi/g17/runtime.rs (`Registry::drain_compute_siblings()`, +`Registry::rollback_unpublished_compute()`, `Registry::reserve_compute_channel()`, +`Registry::reserved()`, `Registry::cancel_compute()`, +`Backend::finish_uninstalled_compute()`, `Backend::finish_retired_compute()`) +and from runtime/backend.rs (`Backend::rollback_unpublished_compute()`). It +checks, for an owner with all `COMPUTE_CHANNELS_MAX` channels, that: + +- nothing a channel gives up (queue or displaced binding) is dropped while the + device mutex is held; +- every cancelled or drained queue has its reservation cancelled, so the owner + can reserve channels again; +- this also holds when a later channel fails its rollback or is still busy in + the drain (`EAGAIN`), and when finishing one queue fails; +- an owner with more channels than places is refused before any extra channel + changes. + +Each mutation drops one part of that and must fail an assertion. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def line(source, prefix): + found = [text for text in source.splitlines() if text.startswith(prefix)] + assert len(found) == 1, prefix + return found[0] + + +def replace_once(text, old, new): + assert text.count(old) == 1, old + return text.replace(old, new) + + +def build_harness(mutation=None): + runtime = (G17 / 'runtime.rs').read_text() + backend = (G17 / 'runtime/backend.rs').read_text() + max_line = line((G17 / 'pairs.rs').read_text(), 'pub(crate) const COMPUTE_CHANNELS_MAX: usize') + + aliases = '\n'.join([ + line(runtime, 'type Uninstalled ='), + line(runtime, 'type PerChannel ='), + ]).replace('super::pairs::', '') + drain = item(runtime, ' fn drain_compute_siblings(') + rollback = item(runtime, ' fn rollback_unpublished_compute(\n') + reserve = item(runtime, ' pub(super) fn reserve_compute_channel(') + reserved = item(runtime, ' fn reserved(&mut self, reservation: ComputeReservation)') + cancel = item(runtime, ' pub(super) fn cancel_compute(') + finish_one = item(runtime, ' fn finish_uninstalled_compute(') + finish_all = item(runtime, ' fn finish_retired_compute(') + backend_rollback = item(backend, ' fn rollback_unpublished_compute(&self)') + + if mutation == 'queue-under-lock': + # A cancelled queue is dropped where it is taken, as when a push into an empty KVec failed. + rollback = replace_once(rollback, + '*place = entry.queue.take().map(|queue| (entry.reservation, queue));', + 'drop(entry.queue.take());') + elif mutation == 'binding-under-lock': + rollback = replace_once(rollback, '*binding = replaced;', 'drop(replaced);') + elif mutation == 'drain-under-lock': + drain = replace_once(drain, + '*place = entry.queue.take().map(|queue| (entry.reservation, queue));', + 'drop(entry.queue.take());') + elif mutation == 'drain-local-on-eagain': + # The old shape: collect locally and hand the queues over only on success. + drain = replace_once(drain, 'retired: &mut PerChannel,', 'outer: &mut PerChannel,') + drain = replace_once(drain, ' let mut channel = 0;\n', + ' let mut local: PerChannel = Default::default();\n' + ' let retired = &mut local;\n' + ' let mut channel = 0;\n') + drain = drain[:drain.rindex('Ok(())')] + 'core::mem::swap(outer, retired);\n Ok(())\n }' + elif mutation == 'finish-stops-at-error': + finish_all = ( + ' fn finish_retired_compute(&self, retired: &mut PerChannel) -> Result {\n' + ' for item in retired.iter_mut() {\n' + ' self.finish_uninstalled_compute(item.take())?;\n' + ' }\n' + ' Ok(())\n' + ' }') + elif mutation == 'early-return-skips-finish': + backend_rollback = replace_once(backend_rollback, 'let result = firmware.queues', 'let result: Result = Ok(()); firmware.queues') + backend_rollback = replace_once(backend_rollback, '&mut retired, &mut bindings);', '&mut retired, &mut bindings)?;') + elif mutation == 'overwrite-full': + rollback = replace_once(rollback, 'bindings.get_mut(channel)', 'bindings.get_mut(channel % COMPUTE_CHANNELS_MAX)') + rollback = replace_once(rollback, 'retired.get_mut(channel).filter(|place| place.is_none())', + 'retired.get_mut(channel % COMPUTE_CHANNELS_MAX)') + + reserve = reserve.replace('crate::g17::capacity::', 'capacity::') + reserve, cancel = (text.replace('pub(super) ', '') for text in (reserve, cancel)) + + return r''' +#![allow(dead_code)] +use std::cell::{Cell, RefCell, RefMut}; +use std::ops::{Deref, DerefMut}; +use std::sync::Arc; + +type Error = i32; +type Result = core::result::Result; +type KBox = Box; +type KVec = Vec; +const EIO: Error = -5; +const ENODEV: Error = -19; +const EINVAL: Error = -22; +const EAGAIN: Error = -11; +const ENOSPC: Error = -28; +const FIRST_COMPUTE_QID: u8 = 8; +''' + max_line.replace('pub(crate) ', '') + r''' + +thread_local! { + static LOCKED: Cell = const { Cell::new(false) }; + static LOG: RefCell> = const { RefCell::new(Vec::new()) }; +} +fn locked() -> bool { LOCKED.with(Cell::get) } +fn log(text: String) { LOG.with(|log| log.borrow_mut().push(text)); } +fn take_log() -> Vec { LOG.with(|log| core::mem::take(&mut *log.borrow_mut())) } + +mod capacity { + pub(super) enum Site { ComputeSlots } + pub(super) fn refused(_: Site) -> i32 { super::ENOSPC } +} + +#[derive(Clone, Copy, PartialEq, Debug)] +struct Id { qid: u8, generation: u32 } +impl Id { fn qid(&self) -> u8 { self.qid } } +#[derive(Clone, Copy)] +enum DataMaster { Compute } + +struct Context; + +/// A displaced binding: its aliases must be torn down off the device mutex. +struct Binding(u8); +impl Drop for Binding { + fn drop(&mut self) { + assert!(!locked(), "binding of qid {} dropped under the device mutex", self.0); + log(format!("binding {}", self.0)); + } +} +mod compute { pub(super) use super::{Binding, Queue}; } + +#[derive(Clone, Copy, PartialEq)] +enum Rollback { Cancel, Displace, Keep, Fail } + +struct Queue { + qid: u8, + owner: Option, + primary: bool, + active: u32, + rollback: Rollback, + unpublished: bool, +} +impl Queue { + fn owner(&self) -> Option { self.owner } + fn is_primary(&self) -> bool { self.primary } + fn active_len(&self) -> u32 { self.active } + fn has_replays(&self) -> bool { false } + fn configuring(&self) -> bool { false } + fn release_owner(&mut self) -> Result { + self.owner = None; + Ok(self.unpublished) + } + fn rollback_unpublished(&mut self, owner: u64, _: &Arc) -> Result<(bool, Option)> { + assert_eq!(self.owner, Some(owner)); + log(format!("rollback {}", self.qid)); + match self.rollback { + Rollback::Cancel => { self.owner = None; Ok((true, None)) } + Rollback::Displace => Ok((false, Some(Binding(self.qid)))), + Rollback::Keep => Ok((false, None)), + Rollback::Fail => Err(EIO), + } + } +} +impl Drop for Queue { + fn drop(&mut self) { + assert!(!locked(), "queue {} dropped under the device mutex", self.qid); + log(format!("drop {}", self.qid)); + } +} + +/// Stands in for the cell-locked slot: a guard for the installed queue, or none. +struct ComputeSlot(RefCell>>); +impl ComputeSlot { + fn new() -> Result { Ok(Self(RefCell::new(None))) } + fn with(queue: Queue) -> Self { Self(RefCell::new(Some(Box::new(queue)))) } + fn as_deref(&self) -> Option> { + RefMut::filter_map(self.0.borrow_mut(), |queue| queue.as_deref_mut()).ok() + } + fn as_deref_mut(&mut self) -> Option> { self.as_deref() } + fn is_some(&self) -> bool { self.0.borrow().is_some() } + fn is_none(&self) -> bool { !self.is_some() } + fn take(&mut self) -> Option> { self.0.borrow_mut().take() } +} + +#[derive(Clone, Copy)] +struct ComputeReservation { slot: usize, id: Id, owner: u64 } +struct ComputeEntry { reservation: ComputeReservation, queue: ComputeSlot } +''' + aliases + r''' + +struct Identities(u64); +impl Identities { + fn reserve(&mut self, count: u64) -> Result> { + let start = self.0; + self.0 += count; + Ok(start..self.0) + } +} +struct Qids { next: u8, cancelled: Vec, refuse: Option } +impl Qids { + fn reserve_for(&mut self, _: u64, _: DataMaster, _: Option, _: usize) -> Result { + self.next += 1; + Ok(Id { qid: self.next, generation: 1 }) + } + fn render_pair_fits(&self) -> bool { true } + fn render_pair_capacity(&self) -> usize { 4 } + fn cancel_unpublished(&mut self, id: Id) -> Result { + if self.refuse == Some(id.qid) { return Err(EIO); } + self.cancelled.push(id.qid); + Ok(()) + } +} +struct Admission; +impl Admission { + fn reserve_compute_with_budget( + &self, _: u64, _: u64, reserve: impl FnOnce(usize) -> Result<(T, bool, usize)>, + ) -> Result { + reserve(0).map(|(id, _, _)| id) + } +} + +struct Registry { + compute: KVec>, + identities: Identities, + qids: Qids, + admission: Admission, +} +impl Registry { + fn reclaimable_render_slots(&self) -> Result<(u64, u64)> { Ok((0, 0)) } + fn compute_admission_error(&self, error: Error) -> Error { + if error == ENOSPC { EAGAIN } else { error } + } + fn note_build_room(&mut self) {} +''' + '\n'.join([drain, rollback, reserve, reserved, cancel]) + r''' +} + +struct Firmware { queues: Registry } +struct Guard<'a>(RefMut<'a, Option>>); +impl Deref for Guard<'_> { + type Target = Option>; + fn deref(&self) -> &Self::Target { &self.0 } +} +impl DerefMut for Guard<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } +} +impl Drop for Guard<'_> { + fn drop(&mut self) { LOCKED.with(|locked| locked.set(false)); } +} +struct State(RefCell>>); +impl State { + fn lock(&self) -> Guard<'_> { + assert!(!locked(), "device mutex taken twice"); + LOCKED.with(|locked| locked.set(true)); + Guard(self.0.borrow_mut()) + } +} +struct Lease; +impl Lease { fn is_current(&self) -> bool { true } } +struct Preparations; +impl Preparations { fn enter(&self, _: bool) -> Result { Ok(Lease) } } +struct Channels(Cell); +impl Channels { fn notify(&self) { self.0.set(self.0.get() + 1); } } +struct Shared { preparations: Preparations, state: State, channels: Channels } +impl Shared { fn queue_events(&self) {} } +struct Backend { owner: u64, context: Arc, shared: Shared } +impl Backend { +''' + '\n'.join([finish_one, finish_all, backend_rollback]) + r''' +} + +const OWNER: u64 = 1; + +/// The owner's channels in slots 0..: primary first, then siblings; slot `free` stays empty. +fn backend(channels: &[(Rollback, u32, bool)]) -> Backend { + let mut compute: KVec> = Vec::new(); + for (slot, &(rollback, active, unpublished)) in channels.iter().enumerate() { + let qid = 10 + slot as u8; + compute.push(Some(ComputeEntry { + reservation: ComputeReservation { slot, id: Id { qid, generation: 1 }, owner: OWNER }, + queue: ComputeSlot::with(Queue { + qid, owner: Some(OWNER), primary: slot == 0, active, rollback, unpublished, + }), + })); + } + for _ in 0..4 { + compute.push(None); + } + let queues = Registry { + compute, + identities: Identities(100), + qids: Qids { next: 40, cancelled: Vec::new(), refuse: None }, + admission: Admission, + }; + Backend { + owner: OWNER, + context: Arc::new(Context), + shared: Shared { + preparations: Preparations, + state: State(RefCell::new(Some(Box::new(Firmware { queues })))), + channels: Channels(Cell::new(0)), + }, + } +} + +fn installed(b: &Backend) -> Vec { + let state = b.shared.state.0.borrow(); + let queues = &state.as_ref().unwrap().queues; + queues.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref().map(|queue| queue.qid)).collect() +} + +fn empty_entries(b: &Backend) -> usize { + let state = b.shared.state.0.borrow(); + state.as_ref().unwrap().queues.compute.iter().flatten().filter(|entry| entry.queue.is_none()).count() +} + +fn cancelled(b: &Backend) -> Vec { + b.shared.state.0.borrow().as_ref().unwrap().queues.qids.cancelled.clone() +} + +/// The owner is not locked out: the production reservation grants it a channel again. +fn reserves_again(b: &Backend) { + let mut state = b.shared.state.0.borrow_mut(); + let queues = &mut state.as_mut().unwrap().queues; + let reservation = queues.reserve_compute_channel(OWNER, COMPUTE_CHANNELS_MAX as u8); + assert!(reservation.is_ok(), "owner locked out of reserve_compute_channel: {:?}", reservation.err()); + queues.cancel_compute(reservation.unwrap()).unwrap(); +} + +fn drain(b: &Backend) -> Result { + let mut retired: PerChannel = Default::default(); + let result = { + let mut state = b.shared.state.lock(); + let firmware = state.as_deref_mut().unwrap(); + firmware.queues.drain_compute_siblings(OWNER, &mut retired) + }; + let finished = b.finish_retired_compute(&mut retired); + assert!(retired.iter().all(Option::is_none), "drained queue left unfinished"); + result.and(finished) +} + +fn main() { + use Rollback::*; + assert_eq!(COMPUTE_CHANNELS_MAX, 3, "this test models three channels per owner"); + + // 1. Rollback cancels all three channels: siblings first, every reservation cancelled. + let b = backend(&[(Cancel, 0, false), (Cancel, 0, false), (Cancel, 0, false)]); + b.rollback_unpublished_compute().unwrap(); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "rollback 10", "drop 11", "drop 12", "drop 10"]); + assert_eq!(cancelled(&b), [11, 12, 10]); + assert!(installed(&b).is_empty() && empty_entries(&b) == 0, "rolled-back channel left in the registry"); + reserves_again(&b); + + // 2. Displaced bindings on all three channels are dropped off-lock; the queues stay. + let b = backend(&[(Displace, 0, false), (Displace, 0, false), (Displace, 0, false)]); + b.rollback_unpublished_compute().unwrap(); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "rollback 10", "binding 11", "binding 12", "binding 10"]); + assert_eq!(installed(&b), [10, 11, 12]); + assert!(cancelled(&b).is_empty()); + + // 3. A later channel fails its rollback: the channels taken before it are still finished. + let b = backend(&[(Keep, 0, false), (Cancel, 0, false), (Fail, 0, false)]); + assert_eq!(b.rollback_unpublished_compute(), Err(EIO)); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "drop 11"]); + assert_eq!(cancelled(&b), [11]); + assert_eq!(installed(&b), [10, 12]); + assert_eq!(empty_entries(&b), 0, "a failed rollback left an empty entry holding its QID"); + + // 4. The drain releases both idle siblings and finishes both; the primary stays. + let b = backend(&[(Keep, 0, true), (Keep, 0, true), (Keep, 0, true)]); + drain(&b).unwrap(); + assert_eq!(take_log(), ["drop 11", "drop 12"]); + assert_eq!(cancelled(&b), [11, 12]); + assert_eq!(installed(&b), [10]); + assert_eq!(empty_entries(&b), 0); + reserves_again(&b); + + // 5. A busy later sibling stops the drain (EAGAIN), and the sibling taken before it is + // still finished, so the owner is not locked out. + let b = backend(&[(Keep, 0, true), (Keep, 0, true), (Keep, 1, true)]); + assert_eq!(drain(&b), Err(EAGAIN)); + assert_eq!(take_log(), ["drop 11"]); + assert_eq!(cancelled(&b), [11]); + assert_eq!(installed(&b), [10, 12]); + assert_eq!(empty_entries(&b), 0, "EAGAIN left a drained sibling's entry empty"); + reserves_again(&b); + + // 6. Finishing goes on past a failed cancellation: the others' reservations still go. + let b = backend(&[(Cancel, 0, false), (Cancel, 0, false), (Cancel, 0, false)]); + b.shared.state.0.borrow_mut().as_mut().unwrap().queues.qids.refuse = Some(11); + assert_eq!(b.rollback_unpublished_compute(), Err(EIO)); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "rollback 10", "drop 11", "drop 12", "drop 10"]); + assert_eq!(cancelled(&b), [12, 10], "a failed cancellation stopped the others"); + + // 7. More channels than places (beyond the per-owner bound): refused before the extra + // channel changes; the three taken are finished and the extra one stays installed. + let b = backend(&[(Cancel, 0, false), (Cancel, 0, false), (Cancel, 0, false), (Cancel, 0, false)]); + assert_eq!(b.rollback_unpublished_compute(), Err(EIO)); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "rollback 13", "drop 11", "drop 12", "drop 13"]); + assert_eq!(cancelled(&b), [11, 12, 13]); + assert_eq!(installed(&b), [10]); + assert_eq!(empty_entries(&b), 0); + + println!("PASS g17-compute-retired: no reservation leaks across rollback and sibling drain"); +} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=[ + 'queue-under-lock', 'binding-under-lock', 'drain-under-lock', 'drain-local-on-eagain', + 'finish-stops-at-error', 'early-return-skips-finish', 'overwrite-full', + ]) + args = parser.parse_args() + source = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-retired-') as tmp: + rs = Path(tmp) / 'test.rs' + exe = Path(tmp) / 'test' + rs.write_text(source) + build = subprocess.run([rustc, '--edition=2021', '-O', str(rs), '-o', str(exe)], + capture_output=True, text=True) + if build.returncode != 0: + sys.stderr.write(build.stderr) + return build.returncode + run = subprocess.run([str(exe)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-firmware-selection-tests.py b/tools/asahi/g17-firmware-selection-tests.py index 6b9cc52d70ea7a..43335e4e3098b1 100644 --- a/tools/asahi/g17-firmware-selection-tests.py +++ b/tools/asahi/g17-firmware-selection-tests.py @@ -27,12 +27,13 @@ def method(source, signature): #![allow(dead_code)] type Result = std::result::Result; const ENODEV: i32 = -19; -macro_rules! dev_info { ($($t:tt)*) => { () }; } -macro_rules! dev_err { ($($t:tt)*) => { () }; } +// The device argument is dropped; the message and its arguments are still built. +macro_rules! dev_info { ($dev:expr, $($t:tt)*) => { { let _ = format!($($t)*); } }; } +macro_rules! dev_err { ($dev:expr, $($t:tt)*) => { { let _ = format!($($t)*); } }; } struct AsahiDrmDevice { version: Option<[u32; 3]>, image: u32, - checked: std::cell::RefCell>, + checked: std::rc::Rc>>, } struct CoreLayout { cores: Option<(u32, u32)>, @@ -41,6 +42,29 @@ def method(source, signature): id: u32, core_layout: CoreLayout, } +mod fwid { + pub struct FirmwareBuild { + pub name: &'static str, + pub image: u32, + pub text_sha256: [u8; 32], + } + // The loaded TEXT, modelled by its image number; records every image it is tried against. + pub struct Measured { + pub image: u32, + pub checked: std::rc::Rc>>, + } + impl Measured { + pub fn find(&mut self, builds: &'static [FirmwareBuild]) -> Option<&'static FirmwareBuild> { + builds.iter().find(|build| { + self.checked.borrow_mut().push(build.image); + build.image == self.image + }) + } + pub fn identity(&mut self, _: impl IntoIterator) -> u32 { + self.image + } + } +} mod fw { pub struct Variant(pub u32); pub mod variant { @@ -48,7 +72,7 @@ def method(source, signature): pub struct Build { pub os_version: [u32; 3], pub name: &'static str, - pub image: u32, + pub images: &'static [crate::fwid::FirmwareBuild], pub variant: &'static Variant, pub config: Option<&'static crate::Config>, } @@ -58,35 +82,36 @@ def method(source, signature): struct Gpu; impl Gpu { fn os_firmware_version(dev: &AsahiDrmDevice) -> Option<[u32; 3]> { dev.version } - fn identify_image(dev: &AsahiDrmDevice, build: &'static fw::variant::Build) -> Result { - dev.checked.borrow_mut().push(build.image); - if dev.image == build.image { Ok(()) } else { Err(ENODEV) } + fn measure_text(dev: &AsahiDrmDevice) -> Result { + Ok(fwid::Measured { image: dev.image, checked: dev.checked.clone() }) } ''' TESTS = r''' } +static IMAGE_1: [fwid::FirmwareBuild; 1] = [fwid::FirmwareBuild { name: "image 1", image: 1, text_sha256: [1; 32] }]; +static IMAGE_2: [fwid::FirmwareBuild; 1] = [fwid::FirmwareBuild { name: "image 2", image: 2, text_sha256: [2; 32] }]; static FIRST: fw::Variant = fw::Variant(1); static SECOND: fw::Variant = fw::Variant(2); static OWN: Config = Config { id: 7, core_layout: CoreLayout { cores: None } }; static BUILDS: [fw::variant::Build; 2] = [ - fw::variant::Build { os_version: [26,6,2], name: "first", image: 1, variant: &FIRST, config: None }, - fw::variant::Build { os_version: [27,0,0], name: "second", image: 2, variant: &SECOND, + fw::variant::Build { os_version: [26,6,2], name: "first", images: &IMAGE_1, variant: &FIRST, config: None }, + fw::variant::Build { os_version: [27,0,0], name: "second", images: &IMAGE_2, variant: &SECOND, config: Some(&OWN) }, ]; // One image admitted with the configurations of two core layouts, as T6041 25G83 is. static FORTY: Config = Config { id: 40, core_layout: CoreLayout { cores: Some((4, 40)) } }; static THIRTY_TWO: Config = Config { id: 32, core_layout: CoreLayout { cores: Some((4, 32)) } }; static SHARED: [fw::variant::Build; 3] = [ - fw::variant::Build { os_version: [26,5,2], name: "other", image: 1, variant: &FIRST, config: None }, - fw::variant::Build { os_version: [26,6,2], name: "40", image: 2, variant: &SECOND, + fw::variant::Build { os_version: [26,5,2], name: "other", images: &IMAGE_1, variant: &FIRST, config: None }, + fw::variant::Build { os_version: [26,6,2], name: "40", images: &IMAGE_2, variant: &SECOND, config: Some(&FORTY) }, - fw::variant::Build { os_version: [26,6,2], name: "32", image: 2, variant: &SECOND, + fw::variant::Build { os_version: [26,6,2], name: "32", images: &IMAGE_2, variant: &SECOND, config: Some(&THIRTY_TWO) }, ]; const CORES: (u32, u32) = (4, 40); fn device(version: Option<[u32; 3]>, image: u32) -> AsahiDrmDevice { - AsahiDrmDevice { version, image, checked: std::cell::RefCell::new(Vec::new()) } + AsahiDrmDevice { version, image, checked: Default::default() } } fn main() { use fw::variant::Firmware; diff --git a/tools/asahi/g17-freelist-lease-direct-tests.py b/tools/asahi/g17-freelist-lease-direct-tests.py new file mode 100755 index 00000000000000..6e7f4104614f58 --- /dev/null +++ b/tools/asahi/g17-freelist-lease-direct-tests.py @@ -0,0 +1,320 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Exercise production freelist Lease and rollback transitions under direct sibling loans. + +Compiles the production Owner, LeasePhase, Lease, control_consumed, +Pools::rollback, and Firmware::rollback_render_pool extracted from +drivers/gpu/drm/asahi/g17/ against host stubs. +""" +import argparse +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + start = source.index(signature) + opening = source.index('{', start) + depth = 1 + end = opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def check(cond, line, msg): + if not cond: + print(f'FAIL line {line}: {msg}', file=sys.stderr) + sys.exit(1) + + +def extract_code(mutation): + freelist = (ROOT / 'freelist.rs').read_text() + pools = (ROOT / 'runtime/render/pools.rs').read_text() + render = (ROOT / 'runtime/render.rs').read_text() + direct = (ROOT / 'runtime/render/direct.rs').read_text() + submit = (ROOT / 'runtime/render/submit.rs').read_text() + + check(direct.count('self.rollback_render_pool(preparation)') == 2, 43, + 'direct.rs must use rollback_render_pool at both rollback sites') + check(submit.count('self.rollback_render_pool(preparation)') == 1, 45, + 'submit.rs must use rollback_render_pool') + + owner = item(freelist, 'pub(crate) struct Owner') + phase = item(freelist, 'enum LeasePhase') + lease = item(freelist, 'pub(crate) struct Lease') + impl_lease = item(freelist, 'impl Lease {') + consumed = item(freelist, 'pub(crate) fn control_consumed(') + pools_rollback = item(pools, 'pub(super) fn rollback(').replace('pub(super) ', 'pub ') + fw_rollback = item(render, 'fn rollback_render_pool(').replace('pools::Preparation', 'Preparation') + + lease_code = '\n\n'.join([ + '#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n' + owner, + '#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n' + phase, + '#[derive(Copy, Clone, Debug)]\n' + lease, + impl_lease, + consumed, + ]) + lease_code = lease_code.replace('pub(crate) ', 'pub ') + lease_code = lease_code.replace('super::fw::channels::FreeListCompletion', 'FreeListCompletion') + lease_code = lease_code.replace('super::fw::channels::FreeListRelease', 'FreeListRelease') + lease_code = lease_code.replace('super::fw::channels::DEVICE_CONTROL_SLOTS', 'DEVICE_CONTROL_SLOTS') + lease_code = lease_code.replace('super::now_ns()', 'now_ns()') + + if mutation == 'reject-preparing-complete': + target = 'if self.phase != LeasePhase::Ready\n || !self.published' + replacement = 'if self.phase != LeasePhase::Ready\n || self.preparing != 0\n || !self.published' + check(target in lease_code, 71, 'vacuous mutation: reject-preparing-complete') + lease_code = lease_code.replace(target, replacement, 1) + elif mutation == 'snapshot-rollback': + target = 'Ok(lease.cancel_prepare()?.is_some())' + replacement = 'self.leases[preparation.slot] = preparation.snapshot; Ok(self.leases[preparation.slot].and_then(|l| l.pending_release()).is_some())' + check(target in pools_rollback, 76, 'vacuous mutation: snapshot-rollback') + pools_rollback = pools_rollback.replace(target, replacement, 1) + elif mutation == 'drop-pending-flush': + target = 'match self.release_render_lists()' + replacement = 'match Ok(())' + check(target in fw_rollback, 81, 'vacuous mutation: drop-pending-flush') + fw_rollback = fw_rollback.replace(target, replacement, 1) + elif mutation == 'drop-doorbell-loss': + target = 'self.primary.state.shared.lose_device_quietly();\n return Err(error);' + replacement = 'return Err(error);' + check(target in fw_rollback, 86, 'vacuous mutation: drop-doorbell-loss') + fw_rollback = fw_rollback.replace(target, replacement, 1) + + return lease_code, pools_rollback, fw_rollback + + +def build_harness(mutation): + lease_code, pools_rollback, fw_rollback = extract_code(mutation) + return f''' +#![allow(dead_code)] +type Error = i32; +type Result = std::result::Result; +const EINVAL: Error = -22; +const EIO: Error = -5; +const EAGAIN: Error = -11; +const EBUSY: Error = -16; +const ETIMEDOUT: Error = -110; +const EOVERFLOW: Error = -75; +const DEVICE_CONTROL_SLOTS: u32 = 256; + +#[derive(Copy, Clone, Debug)] +pub struct FreeListCompletion; + +// Match production FreeListRelease: intentionally does not derive PartialEq. +#[derive(Copy, Clone, Debug)] +pub struct FreeListRelease {{ + pub generation: u64, + pub buffer_slot: u32, +}} + +impl FreeListRelease {{ + pub fn new(generation: u64, buffer_slot: u32) -> Self {{ + Self {{ generation, buffer_slot }} + }} +}} + +fn now_ns() -> u64 {{ 1_000_000 }} + +{lease_code} + +struct Preparation {{ + slot: usize, + generation: u64, + snapshot: Option, +}} + +struct Pools {{ + leases: Vec>, +}} + +impl Pools {{ + fn new() -> Self {{ + Self {{ leases: vec![None; 256] }} + }} + fn prepare(&mut self, slot: usize, owner: Owner) -> Result {{ + let snapshot = self.leases[slot]; + let next = Lease::acquire(snapshot.as_ref(), owner)?; + let generation = next.generation(); + self.leases[slot] = Some(next); + Ok(Preparation {{ slot, generation, snapshot }}) + }} + {pools_rollback} +}} + +struct Shared {{ + events_queued: usize, + lost: bool, +}} +impl Shared {{ + fn queue_events(&mut self) {{ self.events_queued += 1; }} + fn lose_device_quietly(&mut self) {{ self.lost = true; }} +}} +struct PrimaryState {{ shared: Shared }} +struct Primary {{ state: PrimaryState }} +struct Render {{ pools: Pools }} +struct Queues {{ render: Render }} +struct Firmware {{ + queues: Queues, + primary: Primary, + release_calls: usize, + release_result: Result, +}} +impl Firmware {{ + fn new() -> Self {{ + Self {{ + queues: Queues {{ render: Render {{ pools: Pools::new() }} }}, + primary: Primary {{ state: PrimaryState {{ shared: Shared {{ events_queued: 0, lost: false }} }} }}, + release_calls: 0, + release_result: Ok(()), + }} + }} + fn release_render_lists(&mut self) -> Result {{ + self.release_calls += 1; + self.release_result + }} + {fw_rollback} +}} + +fn owner(slot: u32, serial: u64) -> Owner {{ + Owner {{ + serial, + epoch: 1, + buffer_slot: slot, + control_va: 0x1000, + ring_va: 0x2000, + cookie: 0x3000, + }} +}} + +fn main() {{ + let o = owner(129, 1); + + // 1. Sibling completion while direct preparation is lent off-lock. + let mut lease = Lease::acquire(None, o).unwrap(); + assert!(matches!(lease.complete_render(false), Err(EINVAL)), "unactivated prepare cannot complete"); + lease.retire_prepare().unwrap(); + + lease = Lease::acquire(Some(&lease), o).unwrap(); + assert_eq!(lease.generation(), 0); + assert!(lease.complete_render(false).expect("sibling must complete while direct prepare is lent").is_none()); + assert!(matches!(lease.complete_render(false), Err(EINVAL)), "no second published render yet"); + lease.retire_prepare().unwrap(); + let rel = lease.complete_render(false).unwrap().expect("final release"); + assert_eq!((rel.generation, rel.buffer_slot), (0, 129)); + lease.mark_release_sent(3).unwrap(); + lease.observe_releases(3, 3).unwrap(); + assert!(lease.released()); + + // 2. Production Pools::rollback + Firmware::rollback_render_pool after sibling completion. + let mut fw = Firmware::new(); + let _p0 = fw.queues.render.pools.prepare(129, o).unwrap(); + fw.queues.render.pools.leases[129].as_mut().unwrap().retire_prepare().unwrap(); + let p1 = fw.queues.render.pools.prepare(129, o).unwrap(); + assert!(fw.queues.render.pools.leases[129].as_mut().unwrap().complete_render(false).unwrap().is_none()); + fw.rollback_render_pool(p1).unwrap(); + let rel = fw.queues.render.pools.leases[129].unwrap().pending_release().expect("rollback after sibling completion must expose final release"); + assert_eq!((rel.generation, rel.buffer_slot), (0, 129)); + assert_eq!(fw.release_calls, 1, "rollback exposing final release must flush release_render_lists"); + assert!(!fw.primary.state.shared.lost); + + // 3. EAGAIN on release_render_lists queues events without losing device. + let mut fw = Firmware::new(); + fw.release_result = Err(EAGAIN); + let _p0 = fw.queues.render.pools.prepare(129, o).unwrap(); + fw.queues.render.pools.leases[129].as_mut().unwrap().retire_prepare().unwrap(); + let p1 = fw.queues.render.pools.prepare(129, o).unwrap(); + assert!(fw.queues.render.pools.leases[129].as_mut().unwrap().complete_render(false).unwrap().is_none()); + fw.rollback_render_pool(p1).unwrap(); + assert_eq!(fw.release_calls, 1); + assert_eq!(fw.primary.state.shared.events_queued, 1); + assert!(!fw.primary.state.shared.lost); + + // 4. Mailbox/transport error on release_render_lists loses the device so committed releases cannot strand. + let mut fw = Firmware::new(); + fw.release_result = Err(ETIMEDOUT); + let _p0 = fw.queues.render.pools.prepare(129, o).unwrap(); + fw.queues.render.pools.leases[129].as_mut().unwrap().retire_prepare().unwrap(); + let p1 = fw.queues.render.pools.prepare(129, o).unwrap(); + assert!(fw.queues.render.pools.leases[129].as_mut().unwrap().complete_render(false).unwrap().is_none()); + assert_eq!(fw.rollback_render_pool(p1), Err(ETIMEDOUT)); + assert!(fw.primary.state.shared.lost, "transport failure during rollback release must lose device"); + + // 5. Concurrent dual preparations with mixed activate/rollback and completions. + let mut lease = Lease::acquire(None, o).unwrap(); + lease.retire_prepare().unwrap(); + lease = Lease::acquire(Some(&lease), o).unwrap(); + lease = Lease::acquire(Some(&lease), o).unwrap(); + assert!(lease.complete_render(false).unwrap().is_none()); + assert!(matches!(lease.complete_render(false), Err(EINVAL))); + lease.retire_prepare().unwrap(); + assert!(lease.cancel_prepare().unwrap().is_none()); + let rel = lease.complete_render(false).unwrap().expect("final release"); + assert_eq!((rel.generation, rel.buffer_slot), (0, 129)); + + // 6. Rollback of unpublished fresh generation and reacquire over ReleaseSent. + let mut fresh = Lease::acquire(None, o).unwrap(); + assert!(fresh.cancel_prepare().unwrap().is_none()); + assert!(fresh.released()); + assert!(fresh.pending_release().is_none()); + + let mut sent = Lease::acquire(Some(&fresh), o).unwrap(); + sent.retire_prepare().unwrap(); + assert!(sent.complete_render(false).unwrap().is_some()); + sent.mark_release_sent(7).unwrap(); + + let mut unconsumed = Lease::acquire(Some(&sent), o).unwrap(); + assert!(unconsumed.cancel_prepare().unwrap().is_none()); + assert!(unconsumed.reacquirable()); + assert!(!unconsumed.released()); + assert_eq!(unconsumed.release_witness(), Some(7)); + + let mut consumed = Lease::acquire(Some(&sent), o).unwrap(); + consumed.observe_releases(8, 8).unwrap(); + assert!(consumed.cancel_prepare().unwrap().is_none()); + assert!(consumed.released()); + assert_eq!(consumed.release_witness(), None); + + // 7. Rollback after acquiring a lingering registration exposes its pending release. + let mut lingering = Lease::acquire(None, o).unwrap(); + lingering.retire_prepare().unwrap(); + assert!(lingering.complete_render(true).unwrap().is_none()); + assert!(lingering.lingering().is_some()); + let mut from_linger = Lease::acquire(Some(&lingering), o).unwrap(); + assert_eq!(from_linger.generation(), 0); + let rel = from_linger.cancel_prepare().unwrap().expect("linger rollback must release"); + assert_eq!((rel.generation, rel.buffer_slot), (0, 129)); + + println!("PASS freelist lease direct sibling completion, rollback release, doorbell loss, and witness preservation"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['reject-preparing-complete', 'snapshot-rollback', + 'drop-pending-flush', 'drop-doorbell-loss']) + args = parser.parse_args() + + code = build_harness(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-freelist-lease-') as tmp: + src = Path(tmp) / 'test.rs' + binary = Path(tmp) / 'test' + src.write_text(code) + subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', str(src), '-o', str(binary)], check=True) + result = subprocess.run([str(binary)], capture_output=True, text=True) + if result.stdout: + print(result.stdout.strip()) + if result.stderr: + print(result.stderr.strip(), file=sys.stderr) + sys.exit(result.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-growth-tests.py b/tools/asahi/g17-growth-tests.py index f26db9cfca578c..f763fd5b5ff803 100644 --- a/tools/asahi/g17-growth-tests.py +++ b/tools/asahi/g17-growth-tests.py @@ -35,18 +35,20 @@ def fixture(): impl Graph {fn set_owner(&mut self,_:&Context)->Result{Ok(())}} struct ReaderHint; impl ReaderHint {fn has_readers(&self,count:&AtomicU32)->bool{count.load(Ordering::Acquire)!=0}} struct Queue { - owner:Option,installed:bool,growing:bool,channel_error:bool,growth:Option,free_list_generation:u64,configuration:Option<()>,retained_owner:Option<()>, + owner:Option,channel_index:u8,binding_noted:bool,installed:bool,growing:bool,channel_error:bool,growth:Option,free_list_generation:u64,configuration:Option<()>,retained_owner:Option<()>, pool_phase:PoolPhase,release_sent_ns:Option,pool:Pool,binding:Option,previous:Option,graph:Graph, active:Fifo,replays:Fifo,quarantined:bool,released:bool,retirement_ready:bool, retired_by_teardown:bool,released_at:u64,exit:Option<()>,needs_fresh_backing:bool, source_hint:ReaderHint,source_readers:AtomicU32, } -fn idle(live:&Arc)->Queue{Queue{owner:Some(1),installed:true,growing:false,channel_error:false,growth:None, +fn idle(live:&Arc)->Queue{Queue{owner:Some(1),channel_index:0,binding_noted:false,installed:true,growing:false,channel_error:false,growth:None, free_list_generation:0,configuration:None,retained_owner:None,pool_phase:PoolPhase::Populated,release_sent_ns:None,pool:Pool{pages:Some(Pages(10,21)),fail:false}, binding:Some(Binding{context:Context::new(live),pool_alias:Some(1),descriptors:Some(2)}),previous:None,graph:Graph, active:Fifo{len:0},replays:Fifo{len:0},quarantined:false,released:false,retirement_ready:true, retired_by_teardown:false,released_at:0,exit:None,needs_fresh_backing:false,source_hint:ReaderHint,source_readers:AtomicU32::new(0)}} impl Queue { + fn clear_binding_note(&mut self){if self.binding_noted{if let Some(binding)=&self.binding{binding.context.note_compute_binding(false);}self.binding_noted=false;}} + fn clear_owner(&mut self,stamp:bool){self.clear_binding_note();self.owner=None;self.channel_index=0;if stamp{self.released_at=now_ns();}} ''' + item(source,'pub(crate) fn release_owner(') + item(source,'pub(crate) fn reusable(') + '\n}\n' methods = '\n'.join(item(source, sig) for sig in ['pub(crate) fn begin_growth(', 'pub(crate) fn finish_growth(', 'pub(crate) fn growth_token(', 'pub(crate) fn abort_growth(', 'pub(crate) fn observe_vacancy(']) replace = item((ROOT / 'freelist.rs').read_text(), 'pub(crate) fn replace_pages(') diff --git a/tools/asahi/g17-highpri-sched-wq-tests.py b/tools/asahi/g17-highpri-sched-wq-tests.py new file mode 100755 index 00000000000000..f579049c0655cf --- /dev/null +++ b/tools/asahi/g17-highpri-sched-wq-tests.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for G17 high-priority drm_sched submit workqueues. + +Compiles production `new_ordered_highpri_reclaim()` / `ordered_flags()` from +`rust/kernel/workqueue.rs` and verifies: +1. `new_ordered_highpri_reclaim()` sets both `WQ_MEM_RECLAIM` and `WQ_HIGHPRI` + and records `highpri: true` so `restrict()` preserves high priority. +2. `g17/job.rs::Scheduler::new()` allocates `new_ordered_highpri_reclaim()` + unconditionally (both single-die and multi-die) and calls `queue.restrict()` + only when `backend.creator_cluster_scheduling()` is true. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +WQ = ROOT / 'rust/kernel/workqueue.rs' +JOB = ROOT / 'drivers/gpu/drm/asahi/g17/job.rs' + +MUTATIONS = ['drop-highpri', 'drop-reclaim', 'drop-highpri-flag'] + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def build_harness(mutation=None): + wq_src = WQ.read_text() + job_src = JOB.read_text() + + hp_fn = item(wq_src, 'pub fn new_ordered_highpri_reclaim(') + ord_fn = item(wq_src, 'fn ordered_flags(') + sched_fn = item(job_src, 'pub(crate) fn new(dev: &AsahiDrmDevice,') + + if mutation == 'drop-highpri': + old = 'bindings::wq_flags_WQ_MEM_RECLAIM | bindings::wq_flags_WQ_HIGHPRI' + assert old in hp_fn + hp_fn = hp_fn.replace(old, 'bindings::wq_flags_WQ_MEM_RECLAIM', 1) + elif mutation == 'drop-reclaim': + old = 'bindings::wq_flags_WQ_MEM_RECLAIM | bindings::wq_flags_WQ_HIGHPRI' + assert old in hp_fn + hp_fn = hp_fn.replace(old, 'bindings::wq_flags_WQ_HIGHPRI', 1) + elif mutation == 'drop-highpri-flag': + old = 'true,\n )' + assert old in hp_fn + hp_fn = hp_fn.replace(old, 'false,\n )', 1) + + job_uses_hp = ( + 'let queue = workqueue::OwnedQueue::new_ordered_highpri_reclaim(name)?;' in sched_fn + and 'if backend.creator_cluster_scheduling() {' in sched_fn + and 'queue.restrict(cluster)?;' in sched_fn + and 'let submit = Some(queue);' in sched_fn + ) + + return f''' +use std::cell::Cell; +use std::ptr::NonNull; + +const ENOMEM: i32 = -12; +type Result = std::result::Result; + +struct CStr; +impl CStr {{ + fn as_char_ptr(&self) -> *const u8 {{ std::ptr::null() }} +}} + +thread_local! {{ + static LAST_FLAGS: Cell = const {{ Cell::new(0) }}; +}} + +mod bindings {{ + use super::LAST_FLAGS; + #[allow(non_upper_case_globals)] + pub const wq_flags_WQ_MEM_RECLAIM: u32 = 1 << 3; + #[allow(non_upper_case_globals)] + pub const wq_flags_WQ_HIGHPRI: u32 = 1 << 4; + + pub unsafe fn alloc_ordered_workqueue(_name: *const u8, flags: u32) -> *mut u8 {{ + LAST_FLAGS.with(|f| f.set(flags)); + 0x1000 as *mut u8 + }} +}} + +struct OwnedQueue {{ + #[allow(dead_code)] + queue: NonNull, + ordered: bool, + unbound: bool, + highpri: bool, +}} + +impl OwnedQueue {{ + {hp_fn} + {ord_fn} +}} + +fn main() {{ + assert!({str(job_uses_hp).lower()}, "g17 Scheduler::new must allocate highpri ordered reclaim queue"); + let q = OwnedQueue::new_ordered_highpri_reclaim(&CStr).unwrap(); + let flags = LAST_FLAGS.with(|f| f.get()); + assert!(flags & bindings::wq_flags_WQ_MEM_RECLAIM != 0, "must set WQ_MEM_RECLAIM"); + assert!(flags & bindings::wq_flags_WQ_HIGHPRI != 0, "must set WQ_HIGHPRI"); + assert!(q.ordered && q.unbound, "must stay ordered and unbound"); + assert!(q.highpri, "must record highpri=true for workqueue_restrict()"); + println!("PASS g17 highpri sched wq"); +}} +''' + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--mutation', choices=MUTATIONS) + args = ap.parse_args() + + src = build_harness(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-highpri-wq-') as tmp: + rs = os.path.join(tmp, 'harness.rs') + bin_path = os.path.join(tmp, 'harness') + Path(rs).write_text(src) + c = subprocess.run(['rustc', '--edition=2021', '-O', rs, '-o', bin_path], capture_output=True, text=True) + if c.returncode != 0: + sys.stderr.write(c.stderr) + return 2 + r = subprocess.run([bin_path], capture_output=True, text=True) + sys.stdout.write(r.stdout) + sys.stderr.write(r.stderr) + return r.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-kill-route-tests.py b/tools/asahi/g17-kill-route-tests.py index 7d01d0e878c357..36e3016d75ac35 100644 --- a/tools/asahi/g17-kill-route-tests.py +++ b/tools/asahi/g17-kill-route-tests.py @@ -62,12 +62,13 @@ def fixture(): item(control, 'enum KillRoute {', True), item(control, 'fn kill_route('), item(control, 'fn hold_owner('), + item(control, 'fn waits_as_failed('), '#[cfg(test)]\n' + item(control, 'mod render_kill_target_tests {'), ]) firmware = '\n'.join(item(control, signature) for signature in [ - 'fn kill_route_for(', 'fn kill_releases_executed_render(', 'fn kill_waits_as_failed(', + 'fn kill_route_for(', 'fn kill_releases_render(', 'fn kill_waits_as_failed(', 'fn render_kill_candidate(', 'fn foreign_compute_running(', 'fn compute_exit_pending(', - 'fn compute_failed(']) + 'fn compute_failed(', 'fn close_failed_owners(']) queue = '\n'.join([item(exit, signature) for signature in [ 'fn active_traversal(', 'pub(crate) fn exit_candidate(', 'fn holds_only_owed_stamp(', 'pub(crate) fn running_commands(', 'pub(crate) fn timed_out(', 'pub(crate) fn exit_published(']] @@ -84,6 +85,12 @@ def fixture(): pub struct Error(i32); pub const ETIMEDOUT: Error = Error(-110); pub const ECANCELED: Error = Error(-125); +pub const EIO: Error = Error(-5); +pub const ENOMEM: Error = Error(-12); +pub type Result = std::result::Result; +macro_rules! pr_err { ($($t:tt)*) => {} } +macro_rules! pr_warn { ($($t:tt)*) => {} } +mod hw { pub mod t8140 { pub mod queues { pub const RENDER_SLOTS: usize = 4; } } } const LIVENESS_NS: u64 = 5_000_000_000; const MS: u64 = 1_000_000; @@ -101,8 +108,14 @@ def fixture(): } } -pub struct Context { killed: Cell } -impl Context { fn kill_published(&self) -> bool { self.killed.get() } } +pub struct Context { killed: Cell, closed: Cell, open_client: Cell } +impl Context { + fn kill_published(&self) -> bool { self.killed.get() } + fn id(&self) -> u32 { 0 } + fn is_closed(&self) -> bool { self.closed.get() } + fn note_closed(&self, _generation: u64) { self.closed.set(true); } + fn note_open_client(&self, open: bool) { self.open_client.set(open); } +} pub struct Packet { command: g17::command::Validated, context: Arc } pub struct Active { packet: Arc, stamps_owed: bool } @@ -141,21 +154,55 @@ def fixture(): pub struct ComputeSlot(Option>); impl ComputeSlot { fn as_deref(&self) -> Option<&Queue> { self.0.as_deref() } } pub struct ComputeEntry { queue: ComputeSlot } -pub struct Render { executed: Vec<(Arc, u64)>, pools_released: Vec> } +pub struct Render { + executed: Vec<(Arc, u64)>, + guilty: Vec<(Arc, u64)>, + pools_released: Vec>, + /// (slot, owner, context) of each open owner whose VM a recovery failed as guilty. + failed: Vec<(usize, u64, Arc)>, +} +fn slots_of(pairs: &[(Arc, u64)], context: &Arc) -> u64 { + pairs.iter().filter(|(owner, _)| Arc::ptr_eq(owner, context)).fold(0, |slots, (_, slot)| slots | 1u64 << slot) +} impl Render { - fn executed_slots(&self, context: &Arc) -> u64 { - self.executed.iter().filter(|(owner, _)| Arc::ptr_eq(owner, context)).fold(0, |slots, (_, slot)| slots | 1u64 << slot) + fn executed_slots(&self, context: &Arc) -> u64 { slots_of(&self.executed, context) } + fn guilty_slots(&self, context: &Arc, _generation: u64) -> u64 { slots_of(&self.guilty, context) } + fn kill_slots(&self, context: &Arc, generation: u64) -> u64 { + self.executed_slots(context) | self.guilty_slots(context, generation) } fn teardown_pools_released(&self, context: &Arc) -> bool { self.pools_released.iter().any(|owner| Arc::ptr_eq(owner, context)) } + fn failed_open_owner(&self, slot: usize) -> Option<(u64, Arc)> { + self.failed.iter().find(|(at, ..)| *at == slot).map(|(_, owner, context)| (*owner, context.clone())) + } +} +/// `fail_close`: the next teardown entry cannot be allocated. +pub struct Teardown { render_kills: Vec, fail_close: bool, entries: usize } +impl Teardown { + fn render_kill_published(&self, index: usize) -> bool { self.render_kills[index] } + fn close(&mut self, _context: &Arc, _now: u64) -> Result { + if std::mem::take(&mut self.fail_close) { + return Err(ENOMEM); + } + self.entries += 1; + Ok(()) + } } -pub struct Teardown { render_kills: Vec } -impl Teardown { fn render_kill_published(&self, index: usize) -> bool { self.render_kills[index] } } +pub struct Admission { released: Vec } +impl Admission { fn release_owner(&mut self, owner: u64) { self.released.push(owner); } } pub struct Init { m5: bool } impl Init { fn is_m5(&self) -> bool { self.m5 } } -pub struct Queues { compute: Vec>, render: Render, teardown: Teardown } -pub struct Firmware { queues: Queues, init: Init } +/// `release_error`: what releasing the owner's compute queue returns. +pub struct Queues { compute: Vec>, render: Render, teardown: Teardown, admission: Admission, release_error: Option } +impl Queues { + fn release_compute(&mut self, _owner: u64) -> Result { self.release_error.map_or(Ok(()), Err) } + fn release_render(&mut self, _owner: u64) -> Result { Ok(()) } + fn sync_render_holds(&mut self) {} +} +pub struct Recovery; +impl Recovery { fn generation(&self) -> u64 { 1 } } +pub struct Firmware { queues: Queues, init: Init, recovery: Recovery } impl Firmware { ''' + firmware + r''' } @@ -165,7 +212,9 @@ def fixture(): mod tests { use super::*; - fn context() -> Arc { Arc::new(Context { killed: Cell::new(false) }) } + fn context() -> Arc { + Arc::new(Context { killed: Cell::new(false), closed: Cell::new(false), open_client: Cell::new(false) }) + } /// A queue bound to `context`, its owner open, holding no command. fn queue(context: &Arc) -> Queue { @@ -225,10 +274,13 @@ def fixture(): Firmware { queues: Queues { compute: queues.into_iter().map(|q| Some(ComputeEntry { queue: ComputeSlot(Some(Box::new(q))) })).collect(), - render: Render { executed: Vec::new(), pools_released: Vec::new() }, - teardown: Teardown { render_kills: vec![false; 4] }, + render: Render { executed: Vec::new(), guilty: Vec::new(), pools_released: Vec::new(), failed: Vec::new() }, + teardown: Teardown { render_kills: vec![false; 4], fail_close: false, entries: 0 }, + admission: Admission { released: Vec::new() }, + release_error: None, }, init: Init { m5: false }, + recovery: Recovery, } } @@ -296,7 +348,7 @@ def fixture(): fw.queues.render.executed.push((c.clone(), 32)); c.killed.set(true); assert!(fw.compute_exit_pending(&c)); - assert!(!fw.kill_releases_executed_render(&c)); + assert!(!fw.kill_releases_render(&c)); assert_eq!(fw.kill_route_for(0, &c, CLOSED), KillRoute::None); assert!(!fw.kill_waits_as_failed(&c)); } @@ -359,6 +411,60 @@ def fixture(): assert_eq!(fw.kill_route_for(0, &c, CLOSED), KillRoute::None); } + #[test] + fn a_closed_guilty_context_is_killed_at_once_without_waiting_for_foreign_render() { + // Render-only: a pair with a spinning group and never-started groups behind it, its VM + // guilty (not executed). Another client's compute runs. + let c = context(); + let other = context(); + let mut fw = firmware(vec![running(&other)]); + fw.queues.render.guilty.push((c.clone(), 13)); + assert_eq!(fw.kill_route_for(0, &c, 0), KillRoute::Render); + assert!(fw.kill_releases_render(&c)); + assert!(fw.kill_waits_as_failed(&c)); + // Once only, and never on M5. + c.killed.set(true); + assert_eq!(fw.kill_route_for(0, &c, CLOSED), KillRoute::None); + assert!(!fw.kill_releases_render(&c)); + let c = context(); + let mut fw = firmware(vec![running(&other)]); + fw.init.m5 = true; + fw.queues.render.guilty.push((c.clone(), 13)); + assert!(!fw.kill_releases_render(&c)); + } + + #[test] + fn a_failed_owner_close_is_retried_before_its_latch_and_fails_the_pass_after() { + // The first owner's teardown entry cannot be allocated: it stays open for the next pass, + // and the other failed owner is still closed in this one. + let (a, b) = (context(), context()); + let mut fw = firmware(vec![]); + fw.queues.render.failed = vec![(0, 100, a.clone()), (1, 101, b.clone())]; + fw.queues.teardown.fail_close = true; + assert_eq!(fw.close_failed_owners(0), Ok(())); + assert!(!a.is_closed() && !a.open_client.get()); + assert!(b.is_closed() && b.open_client.get()); + assert_eq!(fw.queues.admission.released, [101]); + assert_eq!(fw.close_failed_owners(0), Ok(())); + assert!(a.is_closed()); + assert_eq!((fw.queues.teardown.entries, &fw.queues.admission.released[..]), (2, &[101, 100][..])); + // Once latched, no later close releases the owner: a failed release fails the pass + // (the event service then stops the device) instead of leaking its slot and admission. + let c = context(); + let mut fw = firmware(vec![]); + fw.queues.render.failed = vec![(2, 102, c.clone())]; + fw.queues.release_error = Some(EIO); + assert_eq!(fw.close_failed_owners(0), Err(EIO)); + assert!(c.is_closed()); + assert!(fw.queues.admission.released.is_empty()); + // Never on M5. + let mut fw = firmware(vec![]); + fw.init.m5 = true; + fw.queues.render.failed = vec![(0, 103, context())]; + assert_eq!(fw.close_failed_owners(0), Ok(())); + assert_eq!(fw.queues.teardown.entries, 0); + } + #[test] fn a_kill_does_not_wait_for_another_closed_contexts_owed_compute() { let (c5, c11, live) = (context(), context(), context()); @@ -399,14 +505,25 @@ def fixture(): # The route before this change: a compute exit only for failed compute or released pools. 'no-executed-route': [(' if exit_pending && (failed || pools_released || executed) {', ' if exit_pending && (failed || pools_released) {')], - 'no-executed-input': [(' self.kill_releases_executed_render(context),\n', ' false,\n')], - 'kill-twice': [('!self.init.is_m5() && !context.kill_published() && self.queues.render.executed_slots(context) != 0', - '!self.init.is_m5() && self.queues.render.executed_slots(context) != 0')], - 'executed-on-m5': [('!self.init.is_m5() && !context.kill_published() && self.queues.render.executed_slots(context) != 0', - '!context.kill_published() && self.queues.render.executed_slots(context) != 0')], - 'unsafe-wait': [('self.compute_failed(context) || self.kill_releases_executed_render(context)', + 'no-executed-input': [(' self.kill_releases_render(context),\n', ' false,\n')], + 'kill-twice': [('!self.init.is_m5() && !context.kill_published() && self.queues.render.kill_slots(context, self.recovery.generation()) != 0', + '!self.init.is_m5() && self.queues.render.kill_slots(context, self.recovery.generation()) != 0')], + 'executed-on-m5': [('!self.init.is_m5() && !context.kill_published() && self.queues.render.kill_slots(context, self.recovery.generation()) != 0', + '!context.kill_published() && self.queues.render.kill_slots(context, self.recovery.generation()) != 0')], + 'unsafe-wait': [('waits_as_failed(self.compute_failed(context), self.kill_releases_render(context))', 'self.compute_failed(context)')], + # A guilty pair waits for the retirement delay like an executed one, or is not a candidate. + 'guilty-waits-delay': [('(guilty || (executed && age >= RENDER_KILL_DELAY_NS))', + '((guilty || executed) && age >= RENDER_KILL_DELAY_NS)')], + 'no-guilty-input': [(' self.queues.render.guilty_slots(context, self.recovery.generation()) != 0,\n', + ' false,\n')], 'owed-blocks-kill': [('queue.running_commands() && !queue.context()', 'queue.in_flight() && !queue.context()')], + # A failed release after the latch is logged and skipped: its slot and admission leak. + 'post-latch-swallowed': [(' self.queues.release_compute(owner)?;\n', + ' if self.queues.release_compute(owner).is_err() { continue; }\n')], + # A failed teardown reservation aborts the pass for the other failed owners. + 'reserve-fails-pass': [(' if let Err(error) = self.queues.teardown.close(&context, now) {', + ' if let Err(error) = self.queues.teardown.close(&context, now) {\n return Err(error);')], 'open-owed-skipped': [('self.in_flight() && !self.holds_only_owed_stamp()', 'self.in_flight() && !self.active.iter().all(|active| active.stamps_owed)')], } diff --git a/tools/asahi/g17-m5-cross-qid-direct-tests.py b/tools/asahi/g17-m5-cross-qid-direct-tests.py new file mode 100755 index 00000000000000..9f4d4d37c0739f --- /dev/null +++ b/tools/asahi/g17-m5-cross-qid-direct-tests.py @@ -0,0 +1,648 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for sync-input chain deduplication and lock-free M5 cross-QID compute publication. + +Tests both the real C `collect_leaf()` extracted from +`drivers/gpu/drm/asahi/g17/sync_input.c` and the real Rust `Hold`, +`ReaderHint`, and `resolve_direct_sources()` logic extracted from +`sync_input.rs` and `runtime.rs`: +1. Timeline chain deduplication (C): 8 unsignaled same-context leaves + collapse to the single latest seqno with zero refcount leaks; distinct + contexts stay distinct; failed earlier leaves (`status < 0`) are never + coalesced or dropped. +2. Lock-free `compute_direct()` cross-QID resolution (Rust): + - Resolves `PublishedSource` into a `Frontier` `KickDependency`, takes + `Hold::new(&readers)` which is immediately observed by + `ReaderHint::has_readers()` and blocks `reset_for_owner()` without + locking the producer queue, and marks `note_firmware_consumer()`. + - Safely falls back (`None`, zero leaked `Hold`s) on unpublished source, + epoch/generation mismatch, active recovery, cancelled/quarantined + source, and failed source fence; skips already-retired sources. +3. Structural verification of `runtime/backend.rs`, `runtime.rs`, + `queue/compute.rs`, `fence.rs`, `completion.rs`, and `job.rs`. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +def build_c_harness(mutation=None): + c_src = (G17 / 'sync_input.c').read_text() + collect_leaf = item(c_src, 'static int collect_leaf(') + if mutation == 'no-chain-dedup': + collect_leaf = collect_leaf.replace( + 'if (coalesce_contexts && status == 0 && leaf->context != 0 &&', + 'if (coalesce_contexts && 0 &&', + 1, + ) + elif mutation == 'coalesce-failed-leaf': + collect_leaf = collect_leaf.replace( + 'status == 0 && leaf->context != 0 &&\n\t\t out[i].status == 0 && ', + 'leaf->context != 0 &&\n\t\t ', + 1, + ) + + return f''' +#include +#include +#include +#include +#include +#include + +struct dma_fence {{ + uint64_t context; + uint64_t seqno; + int status; + int refs; +}}; + +struct asahi_g17_fence_leaf {{ + struct dma_fence *fence; + int status; +}}; + +static struct dma_fence *dma_fence_get(struct dma_fence *f) +{{ + f->refs++; + return f; +}} + +static void dma_fence_put(struct dma_fence *f) +{{ + assert(f->refs > 0); + f->refs--; +}} + +static int dma_fence_get_status(struct dma_fence *f) +{{ + return f->status; +}} + +static bool dma_fence_is_later(struct dma_fence *f1, struct dma_fence *f2) +{{ + assert(f1->context == f2->context); + return (int64_t)(f1->seqno - f2->seqno) > 0; +}} + +{collect_leaf} + +static void release_all(struct asahi_g17_fence_leaf *out, size_t count) +{{ + for (size_t i = 0; i < count; ++i) + dma_fence_put(out[i].fence); +}} + +int main(void) +{{ + /* 1. 8 unsignaled same-context timeline leaves (out of order) -> 1 newest leaf. */ + struct dma_fence chain[8]; + uint64_t order[8] = {{3, 7, 1, 8, 5, 2, 6, 4}}; + for (int i = 0; i < 8; ++i) {{ + chain[i].context = 10; + chain[i].seqno = order[i]; + chain[i].status = 0; + chain[i].refs = 1; + }} + struct asahi_g17_fence_leaf out[16]; + size_t count = 0; + for (int i = 0; i < 8; ++i) {{ + assert(collect_leaf(&chain[i], out, 16, &count, true) == 0); + }} + assert(count == 1); + assert(out[0].fence->context == 10); + assert(out[0].fence->seqno == 8); + assert(out[0].status == 0); + release_all(out, count); + for (int i = 0; i < 8; ++i) + assert(chain[i].refs == 1); + + /* 2. Failed earlier leaf + healthy later unsignaled leaf on same context -> BOTH kept. */ + struct dma_fence failed = {{ .context = 10, .seqno = 2, .status = -EIO, .refs = 1 }}; + struct dma_fence healthy = {{ .context = 10, .seqno = 9, .status = 0, .refs = 1 }}; + count = 0; + assert(collect_leaf(&failed, out, 16, &count, true) == 0); + assert(collect_leaf(&healthy, out, 16, &count, true) == 0); + assert(count == 2); + assert(out[0].status == -EIO && out[0].fence->seqno == 2); + assert(out[1].status == 0 && out[1].fence->seqno == 9); + release_all(out, count); + assert(failed.refs == 1 && healthy.refs == 1); + + /* 3. Two distinct contexts coalesce independently to 1 newest leaf each. */ + struct dma_fence q0[3] = {{ + {{ .context = 11, .seqno = 1, .status = 0, .refs = 1 }}, + {{ .context = 11, .seqno = 4, .status = 0, .refs = 1 }}, + {{ .context = 11, .seqno = 2, .status = 0, .refs = 1 }}, + }}; + struct dma_fence q1[2] = {{ + {{ .context = 22, .seqno = 10, .status = 0, .refs = 1 }}, + {{ .context = 22, .seqno = 12, .status = 0, .refs = 1 }}, + }}; + count = 0; + for (int i = 0; i < 3; ++i) + assert(collect_leaf(&q0[i], out, 16, &count, true) == 0); + for (int i = 0; i < 2; ++i) + assert(collect_leaf(&q1[i], out, 16, &count, true) == 0); + assert(count == 2); + assert(out[0].fence->context == 11 && out[0].fence->seqno == 4); + assert(out[1].fence->context == 22 && out[1].fence->seqno == 12); + release_all(out, count); + + /* 4. Context 0 leaves are never coalesced. */ + struct dma_fence z0 = {{ .context = 0, .seqno = 1, .status = 0, .refs = 1 }}; + struct dma_fence z1 = {{ .context = 0, .seqno = 2, .status = 0, .refs = 1 }}; + count = 0; + assert(collect_leaf(&z0, out, 16, &count, true) == 0); + assert(collect_leaf(&z1, out, 16, &count, true) == 0); + assert(count == 2); + release_all(out, count); + return 0; +}} +''' + + +def build_rust_harness(mutation=None): + sync_rs = (G17 / 'sync_input.rs').read_text() + backend_rs = (G17 / 'runtime/backend.rs').read_text() + runtime_rs = (G17 / 'runtime.rs').read_text() + compute_rs = (G17 / 'queue/compute.rs').read_text() + completion_rs = (G17 / 'completion.rs').read_text() + fence_rs = (G17 / 'fence.rs').read_text() + job_rs = (G17 / 'job.rs').read_text() + + hold_struct = 'pub struct Hold(Arc);' + hold_impl = item(sync_rs, 'impl Hold').replace('pub(super) ', 'pub ') + hold_drop = item(sync_rs, 'impl Drop for Hold') + hint_struct = item(sync_rs, 'pub(super) struct ReaderHint').replace('pub(super) ', 'pub ') + hint_impl = item(sync_rs, 'impl ReaderHint').replace('pub(super) ', 'pub ') + resolve_fn = item(runtime_rs, 'fn resolve_direct_sources(') + input_sources_fn = item(backend_rs, 'fn input_sources(') + compute_direct_fn = item(runtime_rs, 'fn compute_direct(') + sources_pub_fn = item(runtime_rs, 'fn sources_published(') + compute_host_impl = item(runtime_rs, 'impl compute::Host for ComputeHost<') + begin_replay_fn = item(completion_rs, 'pub(crate) fn begin_replay(') + submission_impl = item(fence_rs, 'impl Submission') + note_error_fn = item(submission_impl, 'fn note_error(') + same_vm_fn = item(submission_impl, 'pub(super) fn same_vm(') + has_pub_epoch_fn = item(submission_impl, 'pub(super) fn has_published_epoch(') + clear_pub_fn = item(submission_impl, 'pub(super) fn clear_published(') + cancel_fn = item(job_rs, 'pub(crate) fn request_cancel(') + + if mutation == 'hint-blind-spot': + hint_impl = hint_impl.replace( + 'count.load(Ordering::Acquire) != 0', + 'self.possible && count.load(Ordering::Acquire) != 0', + 1, + ) + elif mutation == 'skip-epoch-check': + resolve_fn = resolve_fn.replace( + 'source.submission.published_source(generation)?', + 'source.submission.published_source_unchecked()?', + 1, + ) + resolve_fn = resolve_fn.replace( + 'if !source.submission.has_published_epoch(generation) {\n return None;\n }', + '', + 2, + ) + elif mutation == 'skip-recovery-recheck': + resolve_fn = resolve_fn.replace( + 'if port.recovery_state().ok()? != 0 || port.generation() != generation {\n return None;\n }', + '', + 2, + ) + elif mutation == 'lock-per-leaf': + input_sources_fn = input_sources_fn.replace( + 'let published_fast =', + 'let _ = self.shared.state.lock(); let published_fast =', + 1, + ) + elif mutation == 'hold-m5-outer-compute-host': + compute_host_impl = compute_host_impl.replace( + 'self.m5_outer = None;', + '', + 1, + ) + elif mutation == 'same-qid-emits-barrier': + resolve_fn = resolve_fn.replace( + 'if published.dependency.qid() == target_qid {', + 'if false && published.dependency.qid() == target_qid {', + 1, + ) + elif mutation == 'lock-has-published-epoch': + has_pub_epoch_fn = has_pub_epoch_fn.replace( + 'self.published_epoch.load(Ordering::Acquire) == tag', + 'self.state.lock().published.as_ref().is_some_and(|s| s.epoch == epoch)', + 1, + ) + elif mutation == 'lock-same-vm': + same_vm_fn = same_vm_fn.replace( + 'self.vm_status', + 'self.state.lock().work', + 1, + ) + + # Structural checks on production sources. + collect_cap_ok = 'let mut capacity = 4;' in sync_rs + leaf_loop_start = input_sources_fn.index('for leaf in &leaves {') + unchecked_block_start = input_sources_fn.index('if !unchecked.is_empty() {') + leaf_loop = input_sources_fn[leaf_loop_start:unchecked_block_start] + input_sources_ok = ( + 'self.shared.state.lock()' not in leaf_loop + and ordered_ok( + input_sources_fn, + 'submission.has_published_epoch(epoch)', + 'if !unchecked.is_empty() {', + 'let state = self.shared.state.lock();', + 'for idx in unchecked {', + ) + ) + direct_sources_ok = ( + '(has_sources && !m5)' in compute_direct_fn + and ordered_ok( + compute_direct_fn, + 'let target_qid = cells[0].as_ref()?.qid()?;', + 'self.resolve_direct_sources(port, generation, target_qid, sources)?', + 'queue.qid() != target_qid', + 'queue.publish(', + 'direct_frontier.as_slice(),', + 'source.submission.note_firmware_consumer();', + 'sources.set_holds(direct_holds);', + 'drop(direct_holds);', + ) + ) + lockfree_submission_ok = ( + 'published_epoch: AtomicU64,' in fence_rs + and 'vm_status: Option>,' in fence_rs + and 'self.state.lock()' not in has_pub_epoch_fn + and 'self.published_epoch.load(Ordering::Acquire)' in has_pub_epoch_fn + and 'self.state.lock()' not in same_vm_fn + and 'self.vm_status' in same_vm_fn + and 'if self.published_epoch.swap(0, Ordering::AcqRel) == 0 {' in clear_pub_fn + ) + sources_published_ok = ordered_ok( + sources_pub_fn, + 'source.submission.has_published_epoch(generation)', + 'let state = self.shared.state.lock();', + ) + compute_host_ok = ordered_ok( + compute_host_impl, + 'note_m5_submission_history_locked(guard, 1)', + 'self.m5_outer = None;', + 'self.port.notify(message)', + ) + publish_invalidation_ok = ( + ordered_ok( + compute_rs, + 'host.notify((0x83 << 48) | 0x02 | u64::from(policy.priority()) << 2)?;', + 'packet.completion.note_source_published(', + 'if packet.cancel_requested() {', + 'packet.completion.clear_source_published();', + ) + and 'self.clear_published();' in note_error_fn + and 'self.clear_source_published();' in begin_replay_fn + and 'self.completion.clear_source_published();' in cancel_fn + ) + + # Adapt resolve_direct_sources() for host compilation. + host_resolve = resolve_fn + host_resolve = host_resolve.replace('super::port::Port', 'Port') + host_resolve = host_resolve.replace('super::sync_input::Sources', 'Sources') + host_resolve = host_resolve.replace('super::dependency::Frontier', 'Frontier') + host_resolve = host_resolve.replace('super::sync_input::Hold', 'Hold') + host_resolve = host_resolve.replace('KVec', 'Vec') + host_resolve = host_resolve.replace('KVec::new()', 'Vec::new()') + host_resolve = host_resolve.replace('holds.push(hold, GFP_KERNEL).ok()?;', 'holds.push(hold);') + + return f''' +use std::sync::{{Arc, Mutex, atomic::{{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}}}}; + +const EBUSY: i32 = -16; +const EIO: i32 = -5; +const EOVERFLOW: i32 = -75; +const PRODUCER_FAILED: i32 = -5; +type Result = std::result::Result; + +{hold_struct} +{hold_impl} +{hold_drop} + +{hint_struct} +{hint_impl} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct KickDependency {{ + qid: u8, + kick: u64, +}} +impl KickDependency {{ + fn qid(self) -> u8 {{ self.qid }} +}} + +#[derive(Clone)] +struct PublishedSource {{ + epoch: u64, + published: u64, + dependency: KickDependency, + readers: Arc, +}} + +struct Frontier {{ + items: Vec<(u64, KickDependency)>, +}} +impl Frontier {{ + fn new() -> Self {{ Self {{ items: Vec::new() }} }} + fn insert(&mut self, seq: u64, dep: KickDependency) -> Result {{ + if let Some(old) = self.items.iter_mut().find(|(_, d)| d.qid == dep.qid) {{ + if seq > old.0 {{ *old = (seq, dep); }} + }} else {{ + self.items.push((seq, dep)); + }} + Ok(()) + }} +}} + +struct Submission {{ + retired: AtomicBool, + error: AtomicI32, + published_epoch: AtomicU64, + firmware_consumer: AtomicBool, + state_locks: AtomicU32, + published: Mutex>, +}} + +impl Submission {{ + fn encode_epoch(epoch: u64) -> u64 {{ epoch.wrapping_add(1) }} + fn new() -> Arc {{ + Arc::new(Self {{ + retired: AtomicBool::new(false), + error: AtomicI32::new(0), + published_epoch: AtomicU64::new(0), + firmware_consumer: AtomicBool::new(false), + state_locks: AtomicU32::new(0), + published: Mutex::new(None), + }}) + }} + fn set_published(&self, src: PublishedSource) {{ + let tag = Self::encode_epoch(src.epoch); + self.state_locks.fetch_add(1, Ordering::Relaxed); + *self.published.lock().unwrap() = Some(src); + self.published_epoch.store(tag, Ordering::Release); + }} + fn clear_published(&self) {{ + if self.published_epoch.swap(0, Ordering::AcqRel) == 0 {{ + return; + }} + self.state_locks.fetch_add(1, Ordering::Relaxed); + *self.published.lock().unwrap() = None; + }} + fn source_status(&self) -> Result {{ + if self.error.load(Ordering::Acquire) != 0 {{ + return Err(PRODUCER_FAILED); + }} + Ok(self.retired.load(Ordering::Acquire)) + }} + fn published_source(&self, epoch: u64) -> Option {{ + if !self.has_published_epoch(epoch) {{ + return None; + }} + self.state_locks.fetch_add(1, Ordering::Relaxed); + self.published.lock().unwrap().as_ref().filter(|s| s.epoch == epoch).cloned() + }} + #[allow(dead_code)] + fn published_source_unchecked(&self) -> Option {{ + if self.published_epoch.load(Ordering::Acquire) == 0 {{ + return None; + }} + self.state_locks.fetch_add(1, Ordering::Relaxed); + self.published.lock().unwrap().clone() + }} + fn has_published_epoch(&self, epoch: u64) -> bool {{ + let tag = Self::encode_epoch(epoch); + tag != 0 && self.published_epoch.load(Ordering::Acquire) == tag + }} + fn note_firmware_consumer(&self) {{ + self.firmware_consumer.store(true, Ordering::Release); + }} +}} + +struct Source {{ submission: Arc }} +struct Sources {{ sources: Vec }} +impl Sources {{ + fn check(&self) -> Result {{ + for s in &self.sources {{ s.submission.source_status()?; }} + Ok(()) + }} +}} + +struct Port {{ + gen: AtomicU64, + rec: AtomicU32, + flip_rec_on_query: AtomicBool, +}} +impl Port {{ + fn generation(&self) -> u64 {{ self.gen.load(Ordering::Acquire) }} + fn recovery_state(&self) -> Result {{ + if self.flip_rec_on_query.swap(false, Ordering::AcqRel) {{ + self.rec.store(1, Ordering::Release); + }} + Ok(self.rec.load(Ordering::Acquire)) + }} +}} + +struct Backend; +impl Backend {{ + {host_resolve} +}} + +fn main() {{ + assert!({str(collect_cap_ok).lower()}, "sync_input::collect must start with capacity 4"); + assert!({str(input_sources_ok).lower()}, "input_sources must check PublishedSource lock-free and hoist state.lock outside leaf loop"); + assert!({str(direct_sources_ok).lower()}, "compute_direct must resolve M5 cross-QID sources lock-free and set holds + firmware_consumer"); + assert!({str(lockfree_submission_ok).lower()}, "Submission::has_published_epoch, same_vm, and empty clear_published must be lock-free"); + assert!({str(sources_published_ok).lower()}, "sources_published must check PublishedSource lock-free before state.lock"); + assert!({str(compute_host_ok).lower()}, "ComputeHost::notify must drop m5_outer before port.notify"); + assert!({str(publish_invalidation_ok).lower()}, "compute::Queue must publish after notify and invalidate on quarantine/replay/cancel"); + + let backend = Backend; + let port = Port {{ + gen: AtomicU64::new(7), + rec: AtomicU32::new(0), + flip_rec_on_query: AtomicBool::new(false), + }}; + let readers = Arc::new(AtomicU32::new(0)); + let mut hint = ReaderHint::new(); + + // 1. Happy path: published cross-QID source (qid 5 -> target_qid 9) resolves lock-free, + // Hold blocks ReaderHint::reset_for_owner even though ReaderHint::hold(&mut self) was never called. + let sub = Submission::new(); + // clear_published() on unpublished submission must take 0 state locks. + sub.clear_published(); + assert_eq!(sub.state_locks.load(Ordering::Relaxed), 0); + sub.set_published(PublishedSource {{ + epoch: 7, + published: 42, + dependency: KickDependency {{ qid: 5, kick: 100 }}, + readers: readers.clone(), + }}); + let locks_before = sub.state_locks.load(Ordering::Relaxed); + assert!(sub.has_published_epoch(7)); + assert!(!sub.has_published_epoch(8)); + assert_eq!(sub.state_locks.load(Ordering::Relaxed), locks_before, "has_published_epoch must be lock-free"); + let sources = Sources {{ sources: vec![Source {{ submission: sub.clone() }}] }}; + let (frontier, holds, mask) = backend.resolve_direct_sources(&port, 7, 9, &sources).unwrap(); + assert_eq!(frontier.items, vec![(42, KickDependency {{ qid: 5, kick: 100 }})]); + assert_eq!(holds.len(), 1); + assert_eq!(mask, 1); + assert_eq!(readers.load(Ordering::Acquire), 1); + assert!(hint.has_readers(&readers), "lock-free Hold::new must be visible to ReaderHint::has_readers"); + assert_eq!(hint.reset_for_owner(&readers), Err(EBUSY), "lock-free Hold must block owner reset"); + sub.note_firmware_consumer(); + assert!(sub.firmware_consumer.load(Ordering::Acquire)); + drop(holds); + assert_eq!(readers.load(Ordering::Acquire), 0); + assert!(!hint.has_readers(&readers)); + assert_eq!(hint.reset_for_owner(&readers), Ok(())); + + // 1b. Same-QID source (qid 5 -> target_qid 5): skipped cleanly (empty frontier, 0 holds, + // 0 readers, mask == 0) because the implicit parent already orders same-QID kicks. + let same_sub = Submission::new(); + same_sub.set_published(PublishedSource {{ + epoch: 7, + published: 43, + dependency: KickDependency {{ qid: 5, kick: 101 }}, + readers: readers.clone(), + }}); + let same_sources = Sources {{ sources: vec![Source {{ submission: same_sub.clone() }}] }}; + let (f_same, h_same, m_same) = backend.resolve_direct_sources(&port, 7, 5, &same_sources).unwrap(); + assert!(f_same.items.is_empty(), "same-QID source must not emit a duplicate explicit barrier"); + assert!(h_same.is_empty(), "same-QID source must not take a self-reader Hold"); + assert_eq!(m_same, 0, "same-QID source must not set cross_qid_mask"); + assert_eq!(readers.load(Ordering::Acquire), 0); + assert!(!same_sub.firmware_consumer.load(Ordering::Acquire)); + + // 1c. Same-QID failed producer MUST still return None so error propagates! + same_sub.error.store(EIO, Ordering::Release); + assert!(backend.resolve_direct_sources(&port, 7, 5, &same_sources).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + + // 2. Unpublished source -> clean None fallback. + let unpub = Submission::new(); + let s_unpub = Sources {{ sources: vec![Source {{ submission: unpub }}] }}; + assert!(backend.resolve_direct_sources(&port, 7, 9, &s_unpub).is_none()); + + // 3. Epoch/generation mismatch (port advanced to epoch 8 while source stays at epoch 7) + // -> clean None fallback, zero leaked Hold. + port.gen.store(8, Ordering::Release); + assert!(backend.resolve_direct_sources(&port, 8, 9, &sources).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + port.gen.store(7, Ordering::Release); + + // 4. Recovery starts concurrently right after Hold -> clean None fallback, zero leaked Hold. + port.flip_rec_on_query.store(true, Ordering::Release); + assert!(backend.resolve_direct_sources(&port, 7, 9, &sources).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + port.rec.store(0, Ordering::Release); + + // 5. Cancelled/quarantined source (clear_published) -> clean None fallback. + let cancelled = Submission::new(); + cancelled.set_published(PublishedSource {{ + epoch: 7, + published: 44, + dependency: KickDependency {{ qid: 5, kick: 102 }}, + readers: readers.clone(), + }}); + cancelled.clear_published(); + let s_can = Sources {{ sources: vec![Source {{ submission: cancelled }}] }}; + assert!(backend.resolve_direct_sources(&port, 7, 9, &s_can).is_none()); + + // 6. Failed producer -> clean None fallback (so slow path propagates PRODUCER_FAILED). + let failed = Submission::new(); + failed.set_published(PublishedSource {{ + epoch: 7, + published: 45, + dependency: KickDependency {{ qid: 5, kick: 103 }}, + readers: readers.clone(), + }}); + failed.error.store(EIO, Ordering::Release); + let s_fail = Sources {{ sources: vec![Source {{ submission: failed }}] }}; + assert!(backend.resolve_direct_sources(&port, 7, 9, &s_fail).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + + // 7. Already-retired source -> skipped cleanly with empty frontier and 0 holds. + let retired = Submission::new(); + retired.retired.store(true, Ordering::Release); + let s_ret = Sources {{ sources: vec![Source {{ submission: retired }}] }}; + let (f_ret, h_ret, m_ret) = backend.resolve_direct_sources(&port, 7, 9, &s_ret).unwrap(); + assert!(f_ret.items.is_empty()); + assert!(h_ret.is_empty()); + assert_eq!(m_ret, 0); + + println!("PASS g17-m5-cross-qid-direct-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['no-chain-dedup', + 'coalesce-failed-leaf', + 'hint-blind-spot', + 'skip-epoch-check', + 'skip-recovery-recheck', + 'lock-per-leaf', + 'hold-m5-outer-compute-host', + 'same-qid-emits-barrier', + 'lock-has-published-epoch', + 'lock-same-vm']) + args = parser.parse_args() + cc = os.environ.get('HOSTCC', 'cc') + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-xqid-') as td: + c_file = Path(td) / 'c_test.c' + c_exe = Path(td) / 'c_test' + c_file.write_text(build_c_harness(args.mutation)) + subprocess.run([cc, '-O2', '-Wall', '-Wextra', '-Werror', '-o', str(c_exe), str(c_file)], check=True) + res_c = subprocess.run([str(c_exe)]) + if res_c.returncode != 0: + sys.exit(res_c.returncode) + + rs_file = Path(td) / 'rs_test.rs' + rs_exe = Path(td) / 'rs_test' + rs_file.write_text(build_rust_harness(args.mutation)) + subprocess.run([rustc, '-O', '-o', str(rs_exe), str(rs_file)], check=True) + res_rs = subprocess.run([str(rs_exe)]) + sys.exit(res_rs.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-m5-direct-compute-tests.py b/tools/asahi/g17-m5-direct-compute-tests.py new file mode 100755 index 00000000000000..0f3f7cd50f60ad --- /dev/null +++ b/tools/asahi/g17-m5-direct-compute-tests.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for M5 direct compute outer-ring credits and post-signal report ordering. + +Compiles the real `Credits`, `OuterClaim`, `OuterScope`, and `free` implementation +from `drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs` on the host and tests: +1. Mixed render (2-slot) and compute (1-slot) reservations/consumptions across + `WORK_RING_SLOTS` ring wrap and exact capacity boundaries. +2. Queued claims held across a generation change and `OuterScope` (locked render / + recovery), verifying waiters wake on drop and direct consumption never debits + `OuterScope`'s `published[]` counter. +3. Multi-threaded contention between concurrent direct compute reservations/consumptions + and periodic locked `OuterScope` transitions. +4. Structural verification of `runtime_event_turn()` in `runtime/events.rs`: + completions signal (`batch.finish()`) before report drains, recovery drains + reports before `service_runtime_recovery()` regardless of `HOUSEKEEPING_NS`, + and steady-state passes throttle report drains without double-draining on recovery. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + if source.count(part) != 1: + return False + idx = source.index(part) + if idx <= at: + return False + at = idx + return True + + +def build_harness(mutation=None): + outer_src = (G17 / 'initdata/outer_credit.rs').read_text() + events_src = (G17 / 'runtime/events.rs').read_text() + + turn = item(events_src, 'fn runtime_event_turn(') + if mutation == 'no-pre-recovery-drain': + turn = turn.replace( + 'firmware.drain_reports();\n reports_drained = true;\n' + ' firmware.service_runtime_recovery(deferred)?;', + 'firmware.service_runtime_recovery(deferred)?;', + 1, + ) + + # Verify report-drain ordering contract in production runtime_event_turn(). + ordering_ok = ordered_ok( + turn, + 'deferred.finish();', + 'let mut reports_drained = false;', + 'firmware.drain_reports();\n reports_drained = true;', + 'firmware.service_runtime_recovery(deferred)?;', + 'if housekeeping {', + 'if !reports_drained {', + ) + + # Strip kernel imports, inner doc comments, and kunit module from outer_credit.rs for host compilation. + kunit_idx = outer_src.index('#[kernel::macros::kunit_tests(') + prod = outer_src[:kunit_idx] + prod = re.sub(r'^//!.*$', '', prod, flags=re.M) + prod = re.sub(r'^use crate::g17::.*$', '', prod, flags=re.M) + prod = re.sub(r'^use core::sync::atomic::.*$', '', prod, flags=re.M) + prod = re.sub(r'^use kernel::.*$', '', prod, flags=re.M) + prod = prod.replace('Arc::new(', 'HostArc::new(') + prod = prod.replace(', GFP_KERNEL)?', ')?') + prod = prod.replace('pub(crate)', 'pub') + prod = prod.replace('pub(super)', 'pub') + + if mutation == 'direct-debits-published': + prod = prod.replace( + 'self.reserved[claim.priority].fetch_sub(count, Ordering::AcqRel);', + 'self.reserved[claim.priority].fetch_sub(count, Ordering::AcqRel);\n' + ' self.published[claim.priority].fetch_add(u64::from(count), Ordering::AcqRel);', + 1, + ) + elif mutation == 'scope-allows-reserve': + prod = prod.replace( + 'if self.scoped.load(Ordering::Acquire) { return Err(EBUSY); }', + '', + 1, + ) + + return f''' +use std::sync::{{Arc, atomic::{{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}}}}; + +const EINVAL: i32 = -22; +const EBUSY: i32 = -16; +const EIO: i32 = -5; +const WORK_RING_SLOTS: u32 = 128; +type Result = std::result::Result; + +struct HostArc; +impl HostArc {{ + fn new(v: T) -> Result> {{ Ok(Arc::new(v)) }} +}} + +pub struct Availability {{ + waiters: AtomicUsize, + notifications: AtomicUsize, +}} +impl Availability {{ + pub fn new() -> Result> {{ + Ok(Arc::new(Self {{ + waiters: AtomicUsize::new(0), + notifications: AtomicUsize::new(0), + }})) + }} + pub fn has_waiters(&self) -> bool {{ self.waiters.load(Ordering::Acquire) != 0 }} + pub fn notify(&self) {{ self.notifications.fetch_add(1, Ordering::AcqRel); }} + pub fn notifications(&self) -> usize {{ self.notifications.load(Ordering::Acquire) }} +}} + +{prod} + +fn test_mixed_wrap_and_generation_change() {{ + let credits = Credits::new().unwrap(); + let n = WORK_RING_SLOTS; + let mut ca = n - 6; + let mut cb = n - 6; + let mut prod_idx = n - 2; + + let mut render_claim = credits.reserve(2, 2, [ca, cb, prod_idx]).unwrap(); + let mut comp_a = credits.reserve(2, 1, [ca, cb, prod_idx]).unwrap(); + credits.consume_direct(&mut comp_a).unwrap(); + prod_idx = (prod_idx + 1) % n; + + let mut comp_b = credits.reserve(2, 1, [ca, cb, prod_idx]).unwrap(); + credits.consume_direct(&mut comp_b).unwrap(); + prod_idx = (prod_idx + 1) % n; + assert_eq!(prod_idx, 0); + + let rem = credits.capacity(2, [ca, cb, prod_idx]).unwrap(); + let filler = credits.reserve(2, rem - 1, [ca, cb, prod_idx]).unwrap(); + assert_eq!(credits.capacity(2, [ca, cb, prod_idx]).unwrap(), 1); + assert_eq!(credits.reserve(2, 2, [ca, cb, prod_idx]).err(), Some(EBUSY)); + let mut edge = credits.reserve(2, 1, [ca, cb, prod_idx]).unwrap(); + credits.consume_direct(&mut edge).unwrap(); + prod_idx = (prod_idx + 1) % n; + assert_eq!(credits.capacity(2, [ca, cb, prod_idx]).unwrap(), 0); + drop(filler); + + ca = 1; + cb = 1; + let wrapped = [ca, cb, prod_idx]; + assert!(credits.progressed(2, wrapped).unwrap()); + + // Hold a queued compute claim across OuterScope + generation change. + let queued_comp = credits.reserve(2, 1, wrapped).unwrap(); + let mut pre_direct = credits.reserve(2, 1, wrapped).unwrap(); + let notes_before = credits.available().notifications(); + {{ + let _scope = credits.scope(&mut render_claim).unwrap(); + assert!(credits.is_scoped()); + assert_eq!(credits.reserve(2, 1, wrapped).err(), Some(EBUSY)); + // A direct compute claim already reserved before OuterScope must not debit OuterScope. + credits.consume_direct(&mut pre_direct).unwrap(); + }} + assert!(!credits.is_scoped()); + assert_eq!(render_claim.remaining(), 2, "direct compute must not debit OuterScope"); + assert_eq!(credits.counter(2).unwrap().load(Ordering::Acquire), 0); + + // Generation changed: dropping the queued compute claim restores its credit and wakes waiters. + drop(queued_comp); + assert!(credits.available().notifications() > notes_before); + drop(render_claim); + assert_eq!(credits.capacity(2, wrapped).unwrap(), n - 1); +}} + +fn test_concurrent_direct_and_scoped() {{ + let credits = Credits::new().unwrap(); + let stop = Arc::new(AtomicBool::new(false)); + let mut threads = Vec::new(); + for _ in 0..4 {{ + let c = credits.clone(); + let s = stop.clone(); + threads.push(std::thread::spawn(move || {{ + let mut iters = 0u32; + while !s.load(Ordering::Acquire) && iters < 2000 {{ + if let Ok(mut claim) = c.reserve(1, 1, [0, 0, 0]) {{ + if iters % 5 == 0 {{ + drop(claim); + }} else {{ + c.consume_direct(&mut claim).unwrap(); + }} + }} + iters += 1; + }} + }})); + }} + for _ in 0..200 {{ + if let Ok(mut render_claim) = credits.reserve(1, 2, [0, 0, 0]) {{ + let mut scoped = false; + if let Ok(scope) = credits.scope(&mut render_claim) {{ + assert_eq!(credits.reserve(1, 1, [0, 0, 0]).err(), Some(EBUSY)); + credits.counter(1).unwrap().fetch_add(2, Ordering::AcqRel); + drop(scope); + scoped = true; + }} + if scoped {{ + assert_eq!(render_claim.remaining(), 0); + }} + }} + }} + stop.store(true, Ordering::Release); + for t in threads {{ + t.join().unwrap(); + }} + assert_eq!(credits.capacity(1, [0, 0, 0]).unwrap(), WORK_RING_SLOTS - 1); +}} + +fn main() {{ + assert!({str(ordering_ok).lower()}, "runtime_event_turn must drain reports post-signal and pre-recovery"); + test_mixed_wrap_and_generation_change(); + test_concurrent_direct_and_scoped(); + println!("PASS g17-m5-direct-compute-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['no-pre-recovery-drain', + 'direct-debits-published', + 'scope-allows-reserve']) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-m5-dc-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-m5-effort-tests.py b/tools/asahi/g17-m5-effort-tests.py new file mode 100755 index 00000000000000..5cd73704e91c4c --- /dev/null +++ b/tools/asahi/g17-m5-effort-tests.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for M5 submission_effort() honoring BusyRuns::bound alongside waited. + +Extracts production `submission_effort()` from `drivers/gpu/drm/asahi/g17/initdata.rs` +and `Effort` / `BusyRuns` from `drivers/gpu/drm/asahi/g17/power.rs`, verifying: +1. M5 publishes FULL_EFFORT when a client is continuously GPU-bound (`bound == true`) + even when `waited == false` (pipelined submission loops). +2. M5 still publishes FULL_EFFORT when `waited == true` (submit-and-wait loops). +3. M5 publishes 0 when neither `waited` nor `bound` (paced work with idle gaps >= 2 ms) + and decays cleanly back to 0 after IDLE_HOLD_NS of idle. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def build_harness(mutation=None): + init_src = (G17 / 'initdata.rs').read_text() + power_src = (G17 / 'power.rs').read_text() + + sub_fn = item(init_src, 'pub(super) fn submission_effort(').replace('pub(super) ', '') + if mutation == 'm5-ignores-bound': + sub_fn = sub_fn.replace('if waited || bound', 'if waited', 1) + + effort_struct = item(power_src, 'pub(super) struct Effort') + effort_impl = item(power_src, 'impl Effort') + busy_struct = item(power_src, 'pub(super) struct BusyRuns') + busy_run_struct = item(power_src, 'struct BusyRun ') + busy_run_impl = item(power_src, 'impl BusyRun ') + busy_impl = item(power_src, 'impl BusyRuns') + + parts = '\n'.join([ + effort_struct, effort_impl, busy_run_struct, busy_run_impl, busy_struct, busy_impl, + ]).replace('pub(super) ', '') + + return f''' +const FULL_EFFORT: u32 = 0x10000; +const IDLE_HOLD_NS: u64 = 16_000_000; +const CLIENT_RUNS: usize = 16; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +enum IdleAction {{ None, Clear, Recheck(u64) }} + +{parts} + +struct MockInitData {{ + m5: bool, + active_effort: u32, +}} + +impl MockInitData {{ + {sub_fn} +}} + +fn main() {{ + let m5 = MockInitData {{ m5: true, active_effort: 0 }}; + let g17p = MockInitData {{ m5: false, active_effort: 0x5555 }}; + + // Direct policy matrix on M5 vs non-M5. + assert_eq!(m5.submission_effort(FULL_EFFORT, false, false, false), 0); + assert_eq!(m5.submission_effort(FULL_EFFORT, false, false, true), 0); + assert_eq!(m5.submission_effort(FULL_EFFORT, true, false, false), FULL_EFFORT); + assert_eq!(m5.submission_effort(FULL_EFFORT, false, true, false), FULL_EFFORT); + assert_eq!(m5.submission_effort(FULL_EFFORT, true, true, false), FULL_EFFORT); + assert_eq!(m5.submission_effort(0, true, true, true), 0); + + assert_eq!(g17p.submission_effort(FULL_EFFORT, false, false, false), 0x5555); + assert_eq!(g17p.submission_effort(FULL_EFFORT, false, true, false), FULL_EFFORT); + assert_eq!(g17p.submission_effort(FULL_EFFORT, false, false, true), FULL_EFFORT); + + // End-to-end pipelined compute loop on M5 without host waiters: + // 24 MHz clock -> idle_ticks = 2 ms = 48_000 ticks, hold_ticks = 16 ms = 384_000 ticks. + let idle_ticks = 48_000u64; + let hold_ticks = 384_000u64; + let mut runs = BusyRuns::new(); + let mut effort = Effort::new(); + + effort.submit(); + let mut tick = 100_000u64; + for _ in 0..500 {{ + // 40 us execution + 10 us gap (< 2 ms idle_ticks) -> sustained busy run (> 20 ms total). + runs.note(7, tick, tick + 960, idle_ticks); + tick += 1_200; + }} + assert!(runs.bound(tick, hold_ticks, idle_ticks)); + let changed = effort.note_bound(true); + assert!(changed); + assert_eq!( + m5.submission_effort( + FULL_EFFORT, + effort.waited(), + effort.bound(), + effort.compute_waited(), + ), + FULL_EFFORT, + "M5 must publish FULL_EFFORT when BusyRuns::bound is true even without a waiter", + ); + + // Idle decay clears streaming, bound, and effort cleanly back to 0. + assert_eq!(effort.idle(1_000_000, false), IdleAction::Recheck(IDLE_HOLD_NS)); + assert_eq!(effort.idle(1_000_000 + IDLE_HOLD_NS, false), IdleAction::Clear); + runs.end(); + assert!(!effort.bound()); + assert!(!runs.bound(tick, hold_ticks, idle_ticks)); + assert_eq!( + m5.submission_effort(0, effort.waited(), effort.bound(), effort.compute_waited()), + 0, + ); + + // Paced work with 5 ms idle gaps stays unbound and publishes 0 on M5. + let mut paced = 1_000_000u64; + for _ in 0..20 {{ + runs.note(9, paced, paced + 24_000, idle_ticks); + paced += 120_000; // 5 ms > 2 ms idle_ticks + }} + assert!(!runs.bound(paced, hold_ticks, idle_ticks)); + assert_eq!(m5.submission_effort(FULL_EFFORT, false, false, false), 0); + + println!("PASS g17-m5-effort-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['m5-ignores-bound']) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-m5-eff-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-m5-event-placement-tests.py b/tools/asahi/g17-m5-event-placement-tests.py new file mode 100755 index 00000000000000..6c8830257b4955 --- /dev/null +++ b/tools/asahi/g17-m5-event-placement-tests.py @@ -0,0 +1,514 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for where the G17 event work runs (`drivers/gpu/drm/asahi/g17/mod.rs`). + +Compiles the real `Shared::new_events_queue()`, `Shared::queue_event_records()`, +`Shared::note_submitter()` and `Shared::submitter()` on the host against a mock +workqueue that records each queue's kind and every enqueue. A model of the +kernel's placement then says which CPU the woken worker runs on: + +- a per-CPU queue runs `enqueue_on(cpu)` on `cpu` and `enqueue()` on the + queuing CPU (`queue_work_on()` on a bound pool); +- an unbound queue only takes the affinity pod (`WQ_AFFN_CACHE`, the CPUs + sharing an L2) from the CPU it is aimed at, and the scheduler wakes the + worker on an idle CPU of that pod (`select_idle_sibling()`), the aimed CPU + itself only when it is idle or the pod has no idle CPU. + +The event work has the higher priority, so a worker woken on the CPU of a +running submitter preempts it. If that submitter holds a lock the pass takes +(a compute cell in the middle of a publication), the worker cannot spin on an +owner that is not running: it sleeps until the unlock and preempts again, two +context switches of the submitter. + +`queue_event_records()` queues the event work where the completion is taken +when that CPU shares the last submitter's cluster (`Cpumask::cluster_of()`, +mocked from the test's topology), and aims it at the submitter otherwise. + +Checks: +1. M5: its queue is unbound, reclaim-safe and high priority; a completion taken + on the submitter's own CPU, on another cluster or on the other die runs in + the submitter's pod, never preempting a submitter that is publishing; the + worker follows a moved submitter; before the first publication the work is + queued locally. +2. Other G17 parts: the queue is per-CPU, as `system_highpri_wq`; the event + work runs on the CPU that queued it in the submitter's cluster, and on the + submitter's CPU from another cluster. +3. Structure: `Gpu::new()` builds the queue with `new_events_queue(m5)`, + `aurora_g17_events` is allocated only by `new_events_queue()`, and the + schedulers' timeout work still uses that queue. + +Mutations: `percpu-always` (a per-CPU queue on every part, as M5 had with the +per-CPU queue), `unbound-always`, `aim-local` (never aim at the submitter), +`record-never` (never record the submitter), `not-reclaim`, and `split-flag` +(the queue kind no longer follows `m5`). +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +MOD = ROOT / 'drivers/gpu/drm/asahi/g17/mod.rs' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def replace_once(text, old, new): + assert text.count(old) == 1, old + return text.replace(old, new, 1) + + +UNBOUND = 'workqueue::OwnedQueue::new_unbound_reclaim(c"aurora_g17_events", true)' +PERCPU = 'workqueue::OwnedQueue::new_percpu_reclaim(c"aurora_g17_events", true)' +CONSTRUCT = 'let events = Arc::new(Shared::new_events_queue(m5)?, GFP_KERNEL)?;' + + +def build_harness(mutation=None): + src = MOD.read_text() + + if mutation == 'split-flag': + src = replace_once(src, CONSTRUCT, + 'let events = Arc::new(Shared::new_events_queue(false)?, GFP_KERNEL)?;') + + new_queue = item(src, 'fn new_events_queue(') + queue_records = item(src, 'fn queue_event_records(') + note = item(src, 'fn note_submitter(') + submitter = item(src, 'fn submitter(') + + if mutation == 'percpu-always': + # The code before this change: a per-CPU queue on every part. + new_queue = replace_once(new_queue, UNBOUND, PERCPU) + elif mutation == 'unbound-always': + new_queue = replace_once(new_queue, PERCPU, UNBOUND) + elif mutation == 'not-reclaim': + new_queue = replace_once(new_queue, UNBOUND, + 'workqueue::OwnedQueue::new_unbound(c"aurora_g17_events", true)') + elif mutation == 'aim-local': + queue_records = replace_once( + queue_records, + 'self.events.enqueue_on::, EVENT_WORK>(cpu, self.clone())', + 'self.events.enqueue::, EVENT_WORK>(self.clone())') + elif mutation == 'record-never': + note = replace_once(note, 'if self.submitter.load(Ordering::Relaxed) != cpu {', 'if false {') + + # Gpu::new() builds the queue from `m5`, the value the harness's `Shared::build()` passes. + derive_ok = src.count(CONSTRUCT) == 1 + only_here = src.count('c"aurora_g17_events"') == new_queue.count('c"aurora_g17_events"') == 2 + fence_ok = 'self.events.clone()' in item(src, 'fn fence_queue(') + + return f''' +#![allow(dead_code)] +use std::sync::atomic::{{AtomicU32, Ordering}}; +use std::sync::Arc; + +type Result = core::result::Result; + +mod kernel {{ + pub mod cpumask {{ + use std::cell::RefCell; + thread_local! {{ pub static CLUSTERS: RefCell> = const {{ RefCell::new(Vec::new()) }}; }} + + /// The CPUs of one cluster (from the test's topology; each CPU its own without one). + pub struct Cpumask(Vec); + + impl Cpumask {{ + pub fn cluster_of(cpu: super::cpu::CpuId) -> Self {{ + let cpu = cpu.as_u32(); + CLUSTERS.with(|clusters| {{ + let clusters = clusters.borrow(); + match clusters.get(cpu as usize) {{ + Some(&cluster) => Cpumask( + (0..clusters.len() as u32) + .filter(|&c| clusters[c as usize] == cluster) + .collect(), + ), + None => Cpumask(vec![cpu]), + }} + }}) + }} + pub fn test(&self, cpu: super::cpu::CpuId) -> bool {{ + self.0.contains(&cpu.as_u32()) + }} + }} + }} + + pub mod cpu {{ + use std::cell::Cell; + thread_local! {{ pub static CURRENT: Cell = const {{ Cell::new(0) }}; }} + const NR_CPU_IDS: u32 = 64; + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct CpuId(u32); + + impl CpuId {{ + pub fn current() -> Self {{ + CpuId(CURRENT.with(|cpu| cpu.get())) + }} + pub fn from_u32(id: u32) -> Option {{ + (id < NR_CPU_IDS).then_some(CpuId(id)) + }} + pub fn as_u32(self) -> u32 {{ + self.0 + }} + }} + + pub fn run_on(cpu: u32, f: impl FnOnce() -> R) -> R {{ + let previous = CURRENT.with(|current| current.replace(cpu)); + let result = f(); + CURRENT.with(|current| current.set(previous)); + result + }} + }} +}} + +mod workqueue {{ + use super::Result; + use std::cell::RefCell; + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub enum Call {{ + /// `queue_work()`: on the queuing CPU (`WORK_CPU_UNBOUND`). + Local {{ queuer: u32 }}, + /// `queue_work_on(cpu)`. + On {{ cpu: u32 }}, + }} + + pub struct OwnedQueue {{ + pub unbound: bool, + pub highpri: bool, + pub reclaim: bool, + pub calls: RefCell>, + }} + + impl OwnedQueue {{ + fn make(unbound: bool, highpri: bool, reclaim: bool) -> Result {{ + Ok(Self {{ unbound, highpri, reclaim, calls: RefCell::new(Vec::new()) }}) + }} + pub fn new_unbound(_name: &core::ffi::CStr, highpri: bool) -> Result {{ + Self::make(true, highpri, false) + }} + pub fn new_unbound_reclaim(_name: &core::ffi::CStr, highpri: bool) -> Result {{ + Self::make(true, highpri, true) + }} + pub fn new_percpu_reclaim(_name: &core::ffi::CStr, highpri: bool) -> Result {{ + Self::make(false, highpri, true) + }} + pub fn enqueue(&self, _w: W) -> core::result::Result<(), W> {{ + let queuer = crate::kernel::cpu::CpuId::current().as_u32(); + self.calls.borrow_mut().push(Call::Local {{ queuer }}); + Ok(()) + }} + pub fn enqueue_on( + &self, + cpu: crate::kernel::cpu::CpuId, + _w: W, + ) -> core::result::Result<(), W> {{ + self.calls.borrow_mut().push(Call::On {{ cpu: cpu.as_u32() }}); + Ok(()) + }} + }} +}} + +use workqueue::Call; + +const EVENT_WORK: u64 = 0; + +struct Shared {{ + submission_enabled: bool, + events: Arc, + submitter: AtomicU32, +}} + +impl Shared {{ +{new_queue} + +{queue_records} + +{note} + +{submitter} +}} + +impl Shared {{ + /// As `Gpu::new()` builds it: the queue kind from `m5`. + fn build(m5: bool) -> Arc {{ + let events = Arc::new(Shared::new_events_queue(m5).expect("events queue")); + Arc::new(Shared {{ + submission_enabled: true, + events, + submitter: AtomicU32::new(u32::MAX), + }}) + }} + + /// The completion interrupt, taken on `cpu`, queues the event pass. + fn complete_on(self: &Arc, cpu: u32) -> Call {{ + kernel::cpu::run_on(cpu, || self.queue_event_records()); + *self.events.calls.borrow().last().expect("the event work was queued") + }} + + fn publish_on(&self, cpu: u32) {{ + kernel::cpu::run_on(cpu, || self.note_submitter()); + }} +}} + +/// CPUs grouped by die and by cluster (the L2, the unbound queue's affinity pod). +struct Topology {{ + cluster: Vec, + die: Vec, +}} + +impl Topology {{ + fn new(dies: u32, clusters_per_die: u32, cpus_per_cluster: u32) -> Self {{ + let mut cluster = Vec::new(); + let mut die = Vec::new(); + for d in 0..dies {{ + for c in 0..clusters_per_die {{ + for _ in 0..cpus_per_cluster {{ + cluster.push(d * clusters_per_die + c); + die.push(d); + }} + }} + }} + kernel::cpumask::CLUSTERS.with(|clusters| *clusters.borrow_mut() = cluster.clone()); + Self {{ cluster, die }} + }} + fn cpus(&self) -> u32 {{ + self.cluster.len() as u32 + }} +}} + +/// Which CPU the woken event worker runs on. +fn worker_cpu(topo: &Topology, queue: &workqueue::OwnedQueue, call: Call, busy: &[bool]) -> u32 {{ + match (queue.unbound, call) {{ + (false, Call::On {{ cpu }}) => cpu, + (false, Call::Local {{ queuer }}) => queuer, + (true, call) => {{ + let aim = match call {{ + Call::On {{ cpu }} => cpu, + Call::Local {{ queuer }} => queuer, + }}; + if !busy[aim as usize] {{ + return aim; + }} + (0..topo.cpus()) + .find(|&c| topo.cluster[c as usize] == topo.cluster[aim as usize] && !busy[c as usize]) + .unwrap_or(aim) + }} + }} +}} + +/// Context switches the completion costs a submitter publishing on `submitter` while +/// holding a lock the event pass takes. +fn submitter_switches(worker: u32, submitter: u32, busy: &[bool]) -> u32 {{ + if worker == submitter && busy[submitter as usize] {{ 2 }} else {{ 0 }} +}} + +fn busy(topo: &Topology, cpus: &[u32]) -> Vec {{ + let mut busy = vec![false; topo.cpus() as usize]; + for &cpu in cpus {{ + busy[cpu as usize] = true; + }} + busy +}} + +fn test_m5_queue_kind() {{ + let shared = Shared::build(true); + assert!(shared.events.unbound, "M5 event work aimed at the submitter needs an unbound queue"); + assert!(shared.events.reclaim, "the event work signals job fences: WQ_MEM_RECLAIM"); + assert!(shared.events.highpri, "the event work keeps system_highpri_wq's priority"); +}} + +fn test_other_queue_kind() {{ + let shared = Shared::build(false); + assert!(!shared.events.unbound, "other G17 parts keep a per-CPU event queue"); + assert!(shared.events.reclaim, "the event work signals job fences: WQ_MEM_RECLAIM"); + assert!(shared.events.highpri, "the event work keeps system_highpri_wq's priority"); +}} + +/// The measured case: the completion interrupt is taken on the CPU of the submitter, which +/// is in the middle of a publication. +fn test_m5_completion_on_submitter_cpu() {{ + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(true); + shared.publish_on(16); + let busy = busy(&topo, &[16]); + let call = shared.complete_on(16); + assert_eq!(call, Call::Local {{ queuer: 16 }}, "the submitter's cluster queues the event work locally"); + let worker = worker_cpu(&topo, &shared.events, call, &busy); + assert_ne!(worker, 16, "the event worker must not preempt the publishing submitter"); + assert_eq!(topo.cluster[worker as usize], topo.cluster[16], "the worker shares the submitter's L2"); + assert_eq!(submitter_switches(worker, 16, &busy), 0); +}} + +fn test_m5_completion_on_other_cluster() {{ + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(true); + shared.publish_on(16); + let busy = busy(&topo, &[16, 2]); + let call = shared.complete_on(2); + let worker = worker_cpu(&topo, &shared.events, call, &busy); + assert_eq!(topo.cluster[worker as usize], topo.cluster[16], + "the worker runs in the submitter's cluster, not the interrupt's"); + assert_ne!(worker, 16); + assert_eq!(submitter_switches(worker, 16, &busy), 0); +}} + +fn test_m5_two_dies() {{ + let topo = Topology::new(2, 2, 6); + let shared = Shared::build(true); + shared.publish_on(20); + let busy = busy(&topo, &[20, 3]); + let call = shared.complete_on(3); + let worker = worker_cpu(&topo, &shared.events, call, &busy); + assert_eq!(topo.die[worker as usize], topo.die[20], "completion processing stays on the submitter's die"); + assert_eq!(topo.cluster[worker as usize], topo.cluster[20]); + assert_ne!(worker, 20); +}} + +fn test_m5_idle_submitter() {{ + // A submitter waiting on a fence leaves its CPU idle: running there preempts nobody. + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(true); + shared.publish_on(16); + let busy = busy(&topo, &[]); + let call = shared.complete_on(3); + let worker = worker_cpu(&topo, &shared.events, call, &busy); + assert_eq!(topo.cluster[worker as usize], topo.cluster[16]); + assert_eq!(submitter_switches(worker, 16, &busy), 0); +}} + +fn test_m5_submitter_moves() {{ + // Two submitters on different clusters: the event work follows the last one, and never + // preempts either while it publishes. + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(true); + shared.publish_on(16); + shared.publish_on(7); + let busy = busy(&topo, &[16, 7]); + let call = shared.complete_on(16); + assert_eq!(call, Call::On {{ cpu: 7 }}); + let worker = worker_cpu(&topo, &shared.events, call, &busy); + assert_eq!(topo.cluster[worker as usize], topo.cluster[7]); + assert_eq!(submitter_switches(worker, 7, &busy) + submitter_switches(worker, 16, &busy), 0); +}} + +fn test_m5_before_first_publication() {{ + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(true); + assert!(shared.submitter().is_none()); + let call = shared.complete_on(4); + assert_eq!(call, Call::Local {{ queuer: 4 }}, "nothing published yet: queued locally"); + let worker = worker_cpu(&topo, &shared.events, call, &busy(&topo, &[4])); + assert_eq!(topo.cluster[worker as usize], topo.cluster[4]); +}} + +fn test_m5_completion_stream() {{ + // Every completion of a deep queue arrives while the submitter publishes the next job. + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(true); + let mut switches = 0; + for job in 0..64u32 {{ + shared.publish_on(16); + let busy = busy(&topo, &[16]); + let irq = if job % 2 == 0 {{ 16 }} else {{ 1 }}; + let call = shared.complete_on(irq); + let worker = worker_cpu(&topo, &shared.events, call, &busy); + assert_eq!(topo.cluster[worker as usize], topo.cluster[16]); + switches += submitter_switches(worker, 16, &busy); + }} + assert_eq!(switches, 0, "completions must not cost the submitter context switches"); +}} + +fn test_other_runs_on_queuer() {{ + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(false); + shared.publish_on(4); + assert_eq!(shared.submitter().map(|cpu| cpu.as_u32()), Some(4), "every G17 records the submitter"); + let busy = busy(&topo, &[3, 4]); + let call = shared.complete_on(3); + assert_eq!(call, Call::Local {{ queuer: 3 }}); + assert_eq!(worker_cpu(&topo, &shared.events, call, &busy), 3, + "in the submitter's cluster other G17 parts run the event work where it is queued"); +}} + +fn test_other_follows_submitter_cluster() {{ + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(false); + shared.publish_on(16); + let busy = busy(&topo, &[3]); + let call = shared.complete_on(3); + assert_eq!(call, Call::On {{ cpu: 16 }}, "from another cluster the event work is aimed at the submitter"); + assert_eq!(worker_cpu(&topo, &shared.events, call, &busy), 16); +}} + +fn test_disabled_submission() {{ + let shared = Shared::build(true); + let shared = Arc::new(Shared {{ + submission_enabled: false, + events: shared.events.clone(), + submitter: AtomicU32::new(u32::MAX), + }}); + shared.publish_on(16); + kernel::cpu::run_on(16, || shared.queue_event_records()); + assert!(shared.events.calls.borrow().is_empty(), "no event work without submission"); +}} + +fn main() {{ + assert!({str(derive_ok).lower()}, "Gpu::new() must build the events queue with new_events_queue(m5)"); + assert!({str(only_here).lower()}, "aurora_g17_events must be allocated only by Shared::new_events_queue()"); + assert!({str(fence_ok).lower()}, "the schedulers' timeout work must stay on the events queue"); + test_m5_completion_on_submitter_cpu(); + test_m5_completion_on_other_cluster(); + test_m5_two_dies(); + test_m5_idle_submitter(); + test_m5_submitter_moves(); + test_m5_before_first_publication(); + test_m5_completion_stream(); + test_other_runs_on_queuer(); + test_other_follows_submitter_cluster(); + test_disabled_submission(); + test_m5_queue_kind(); + test_other_queue_kind(); + println!("PASS g17-m5-event-placement-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + '--mutation', + choices=[ + 'percpu-always', + 'unbound-always', + 'aim-local', + 'record-never', + 'not-reclaim', + 'split-flag', + ], + ) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-m5-event-placement-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '--edition', '2021', '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-m5-idle-housekeeping-tests.py b/tools/asahi/g17-m5-idle-housekeeping-tests.py new file mode 100755 index 00000000000000..83caa5a7978bd4 --- /dev/null +++ b/tools/asahi/g17-m5-idle-housekeeping-tests.py @@ -0,0 +1,254 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for deferred idle housekeeping cadence in `runtime_event_turn()`. + +Compiles the real `HOUSEKEEPING_NS`, `housekeeping_due()`, and +`deferred_housekeeping_delay()` helpers from +`drivers/gpu/drm/asahi/g17/runtime/events.rs` on the host and tests: +1. Sparse completions where `in_flight` transiently drops to `false` within + `< HOUSEKEEPING_NS` take `fast_done`, do NOT run housekeeping/power MMIO, + pass actual `in_flight` to `idle_check(now, in_flight)`, and arm the + deferred housekeeping timer within `<= HOUSEKEEPING_NS`. +2. Once `HOUSEKEEPING_NS` elapses (or `requested`, `recover`, + `recovery_pending`, `teardown_pending`, or any capacity waiter is active), + housekeeping runs and `deferred_housekeeping_delay()` returns `None`. +3. While `in_flight` stays `true`, `fast_done` skips housekeeping without + arming the deferred housekeeping timer. +4. Structural verification of `runtime/events.rs`, `mod.rs`, and `sleep.rs`: + `HOUSEKEEPING_WORK` is cancelled on sleep and disabled on shutdown, and + `runtime_event_turn()` passes actual `in_flight` to `idle_check()` and + arms `queue_housekeeping()` whenever `!in_flight` defers housekeeping. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def build_harness(mutation=None): + events_src = (G17 / 'runtime/events.rs').read_text() + mod_src = (G17 / 'mod.rs').read_text() + sleep_src = (G17 / 'sleep.rs').read_text() + + hk_const = 'const HOUSEKEEPING_NS: u64 = 1_000_000;' + assert hk_const in events_src + hk_due = item(events_src, 'fn housekeeping_due(') + hk_delay = item(events_src, 'fn deferred_housekeeping_delay(') + turn = item(events_src, 'fn runtime_event_turn(') + + if mutation == 'idle-forces-housekeeping': + hk_due = hk_due.replace( + 'now.saturating_sub(last_housekeeping_ns) >= HOUSEKEEPING_NS', + 'true', + 1, + ) + elif mutation == 'no-deferred-timer': + hk_delay = hk_delay.replace( + 'if in_flight || housekeeping_ran {\n return None;\n }', + 'return None;', + 1, + ) + elif mutation == 'hardcode-in-flight-true': + turn = turn.replace( + 'firmware.idle_check(now, in_flight)?', + 'firmware.idle_check(now, true)?', + 1, + ) + elif mutation == 'skip-cadence-expiry': + hk_due = hk_due.replace( + '|| now.saturating_sub(last_housekeeping_ns) >= HOUSEKEEPING_NS', + '', + 1, + ) + + fast_idle_ok = ( + 'firmware.idle_check(now, in_flight)?' in turn + and 'firmware.idle_check(now, true)?' not in turn + ) + fast_timer_ok = turn.count('self.queue_housekeeping(delay);') == 2 + no_idle_force_ok = ( + '|| !in_flight' not in turn + and 'let no_housekeeping = in_flight' not in turn + ) + lifecycle_ok = ( + 'self.shared.disable_timer(&self.shared.housekeeping_timer);' in mod_src + and 'self.cancel_timer(&self.housekeeping_timer);' in sleep_src + and 'impl WorkItem for Shared' in mod_src + ) + + return f''' +{hk_const} + +{hk_due} + +{hk_delay} + +struct TurnCounters {{ + fast_done: usize, + housekeeping_runs: usize, + power_mmio_reads: usize, + idle_check_in_flight_false: usize, + deferred_timer_arms: usize, + last_deferred_delay_ns: Option, +}} + +struct MockEventLoop {{ + last_hk: u64, + counters: TurnCounters, +}} + +impl MockEventLoop {{ + fn new(last_hk: u64) -> Self {{ + Self {{ + last_hk, + counters: TurnCounters {{ + fast_done: 0, + housekeeping_runs: 0, + power_mmio_reads: 0, + idle_check_in_flight_false: 0, + deferred_timer_arms: 0, + last_deferred_delay_ns: None, + }}, + }} + }} + + fn run_compute_completion( + &mut self, + now: u64, + in_flight: bool, + requested: bool, + recover: bool, + recovery_pending: bool, + teardown_pending: bool, + has_waiters: bool, + ) {{ + let no_hk = !housekeeping_due( + requested, + recover, + recovery_pending, + teardown_pending, + has_waiters, + now, + self.last_hk, + ); + if !recover && !requested && no_hk {{ + if !in_flight {{ + self.counters.idle_check_in_flight_false += 1; + }} + if let Some(delay) = deferred_housekeeping_delay(in_flight, false, now, self.last_hk) {{ + self.counters.deferred_timer_arms += 1; + self.counters.last_deferred_delay_ns = Some(delay); + }} + self.counters.fast_done += 1; + return; + }} + let hk = housekeeping_due( + requested, + recover, + recovery_pending, + teardown_pending, + has_waiters, + now, + self.last_hk, + ); + if hk {{ + self.last_hk = now; + self.counters.housekeeping_runs += 1; + self.counters.power_mmio_reads += 3; + }} + if let Some(delay) = deferred_housekeeping_delay(in_flight, hk, now, self.last_hk) {{ + self.counters.deferred_timer_arms += 1; + self.counters.last_deferred_delay_ns = Some(delay); + }} + }} +}} + +fn main() {{ + assert!({str(fast_idle_ok).lower()}, "fast_done must pass actual in_flight to idle_check()"); + assert!({str(fast_timer_ok).lower()}, "both fast and slow paths must arm queue_housekeeping when !in_flight defers"); + assert!({str(no_idle_force_ok).lower()}, "transient !in_flight must not force immediate housekeeping"); + assert!({str(lifecycle_ok).lower()}, "housekeeping_timer must be wired to sleep cancel and shutdown disable"); + + // 1. Sparse !in_flight completions within < HOUSEKEEPING_NS hit fast_done with zero power MMIO + // and arm the deferred housekeeping timer within <= HOUSEKEEPING_NS. + let mut lp = MockEventLoop::new(10_000_000); + for step in 1..=10u64 {{ + lp.run_compute_completion(10_000_000 + step * 80_000, false, false, false, false, false, false); + }} + assert_eq!(lp.counters.fast_done, 10, "sparse !in_flight completions within 1 ms must hit fast_done"); + assert_eq!(lp.counters.housekeeping_runs, 0, "sparse !in_flight completions must not run housekeeping"); + assert_eq!(lp.counters.power_mmio_reads, 0, "sparse !in_flight completions must not read power MMIO"); + assert_eq!(lp.counters.idle_check_in_flight_false, 10); + assert_eq!(lp.counters.deferred_timer_arms, 10, "deferred !in_flight must arm housekeeping timer"); + assert_eq!(lp.counters.last_deferred_delay_ns, Some(200_000)); + + // 2. Once HOUSEKEEPING_NS elapses, housekeeping runs and clears the deferred timer requirement. + lp.run_compute_completion(11_000_000, false, false, false, false, false, false); + assert_eq!(lp.counters.housekeeping_runs, 1); + assert_eq!(lp.counters.power_mmio_reads, 3); + assert_eq!(lp.counters.deferred_timer_arms, 10, "running housekeeping must not re-arm deferred timer"); + + // 3. Explicit triggers run housekeeping immediately even within < HOUSEKEEPING_NS. + for (req, rec, rec_pend, tear, wait) in [ + (true, false, false, false, false), + (false, true, false, false, false), + (false, false, true, false, false), + (false, false, false, true, false), + (false, false, false, false, true), + ] {{ + assert!(housekeeping_due(req, rec, rec_pend, tear, wait, 11_050_000, 11_000_000)); + }} + + // 4. Busy in_flight completions within < HOUSEKEEPING_NS hit fast_done without arming deferred timer. + let mut busy = MockEventLoop::new(20_000_000); + busy.run_compute_completion(20_100_000, true, false, false, false, false, false); + assert_eq!(busy.counters.fast_done, 1); + assert_eq!(busy.counters.housekeeping_runs, 0); + assert_eq!(busy.counters.deferred_timer_arms, 0); + + // 5. Boundary: remaining delay is clamped to >= 1 ns even right at the threshold. + assert_eq!(deferred_housekeeping_delay(false, false, 21_000_000, 20_000_000), Some(1)); + assert_eq!(deferred_housekeeping_delay(false, true, 20_100_000, 20_000_000), None); + assert_eq!(deferred_housekeeping_delay(true, false, 20_100_000, 20_000_000), None); + + println!("PASS g17-m5-idle-housekeeping-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['idle-forces-housekeeping', + 'no-deferred-timer', + 'hardcode-in-flight-true', + 'skip-cadence-expiry']) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-hk-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-m5-multiqueue-contention-tests.py b/tools/asahi/g17-m5-multiqueue-contention-tests.py new file mode 100755 index 00000000000000..4d0a462dcc375d --- /dev/null +++ b/tools/asahi/g17-m5-multiqueue-contention-tests.py @@ -0,0 +1,401 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for M5 multi-queue cluster pinning and outer-credit locking. + +Compiles the real `Credits`, `OuterClaim`, `OuterScope`, and `free` implementation +from `drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs` on the host and tests: +1. Tight-ring multi-threaded serialization of `claim_outer()` (`reserve` under + `Port::m5_outer`), `PortOuterScope` (entry and `Drop` under `Port::m5_outer`), + and concurrent direct compute/render reservations and consumptions — verifying + zero ring overcommits, zero `EIO`, and exact credit accounting. +2. Structural verification of the production G17 M5 sources: + - `Shared::new()` leaves single-die M5 schedulers unrestricted + (`pin_scheduler_cluster: !m5 || id.num_dies > 1`). + - `Backend::claim_outer()` holds `firmware.port.m5_outer_lock()` around + `firmware.init.reserve_outer()`. + - `Backend::publish_claimed()` and `runtime/render/prepare.rs` enter + `OuterScope` via `firmware.port.outer_scope(&firmware.init, claim)`. + - `Port::outer_scope()` and `Drop for PortOuterScope` serialize both scope + entry and exit under `Port::m5_outer`. + - `Backend::compute_direct()` reuses a matching `self.outer_compute` claim and + restores any unspent claim back into `self.outer_compute` outside + `cell.lock()` when returning `None` to fall back to the device-mutex path. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + if source.count(part) != 1: + return False + idx = source.index(part) + if idx <= at: + return False + at = idx + return True + + +def build_harness(mutation=None): + outer_src = (G17 / 'initdata/outer_credit.rs').read_text() + port_src = (G17 / 'port.rs').read_text() + runtime_src = (G17 / 'runtime.rs').read_text() + prepare_src = (G17 / 'runtime/render/prepare.rs').read_text() + mod_src = (G17 / 'mod.rs').read_text() + backend_src = (G17 / 'runtime/backend.rs').read_text() + + claim_outer = item(runtime_src, 'fn claim_outer(') + publish_claimed = item(runtime_src, 'fn publish_claimed(') + compute_direct = item(runtime_src, 'fn compute_direct(') + port_outer_scope = item(port_src, 'pub(super) fn outer_scope<') + port_outer_scope_drop = item(port_src, 'impl Drop for PortOuterScope<') + creator_cluster = item(backend_src, 'fn creator_cluster_scheduling(') + + if mutation == 'unlocked-claim-outer': + claim_outer = claim_outer.replace( + 'let _m5_outer = firmware.port.m5_outer_lock();', + '', + 1, + ) + elif mutation == 'raw-compute-scope': + publish_claimed = publish_claimed.replace( + 'firmware.port.outer_scope(&firmware.init, claim)', + 'firmware.init.outer_scope(claim)', + 1, + ) + elif mutation == 'raw-render-scope': + prepare_src = prepare_src.replace( + 'firmware.port.outer_scope(&firmware.init, claim)', + 'firmware.init.outer_scope(claim)', + 1, + ) + elif mutation == 'unlocked-scope-drop': + port_outer_scope_drop = port_outer_scope_drop.replace( + 'let _m5_outer = self.port.m5_outer_lock();', + '', + 1, + ) + elif mutation == 'drop-direct-claim-on-fallback': + compute_direct = compute_direct.replace( + 'if outcome.is_none() && from_held {', + 'if false {', + 1, + ) + elif mutation == 'pin-single-die': + mod_src = mod_src.replace( + 'pin_scheduler_cluster: !m5 || id.num_dies > 1,', + 'pin_scheduler_cluster: true,', + 1, + ) + + claim_outer_ok = ordered_ok( + claim_outer, + 'let _m5_outer = firmware.port.m5_outer_lock();', + 'firmware.init.reserve_outer(', + ) + publish_claimed_ok = ( + 'firmware.port.outer_scope(&firmware.init, claim)' in publish_claimed + and 'firmware.init.outer_scope(' not in publish_claimed + ) + render_scope_ok = ( + 'firmware.port.outer_scope(&firmware.init, claim)' in prepare_src + and 'firmware.init.outer_scope(' not in prepare_src + ) + port_scope_ok = ( + ordered_ok( + port_outer_scope, + 'let _m5_outer = self.m5_outer.lock();', + 'init.outer_scope(claim)?', + ) + and ordered_ok( + port_outer_scope_drop, + 'let _m5_outer = self.port.m5_outer_lock();', + 'drop(scope);', + ) + ) + # Verify compute_direct reuses self.outer_compute before cell.lock() and restores any + # unspent held claim back into self.outer_compute AFTER the cell.lock() closure exits. + direct_restore_ok = ( + compute_direct.count('let mut held = self.outer_compute.lock();') == 2 + and ordered_ok( + compute_direct, + 'held.take()', + 'let result = (|| {', + '.lock()?;', + '})();', + 'if outcome.is_none() && from_held {', + '*held = Some(claim);', + ) + and compute_direct.index('let mut held = self.outer_compute.lock();') + < compute_direct.index('let result = (|| {') + and compute_direct.rindex('let mut held = self.outer_compute.lock();') + > compute_direct.index('if outcome.is_none() && from_held {') + ) + cluster_pin_ok = ( + 'pin_scheduler_cluster: !m5 || id.num_dies > 1,' in mod_src + and 'self.shared.pin_scheduler_cluster()' in creator_cluster + ) + + kunit_idx = outer_src.index('#[kernel::macros::kunit_tests(') + prod = outer_src[:kunit_idx] + prod = re.sub(r'^//!.*$', '', prod, flags=re.M) + prod = re.sub(r'^use crate::g17::.*$', '', prod, flags=re.M) + prod = re.sub(r'^use core::sync::atomic::.*$', '', prod, flags=re.M) + prod = re.sub(r'^use kernel::.*$', '', prod, flags=re.M) + prod = prod.replace('Arc::new(', 'HostArc::new(') + prod = prod.replace(', GFP_KERNEL)?', ')?') + prod = prod.replace('pub(crate)', 'pub') + prod = prod.replace('pub(super)', 'pub') + + return f''' +use std::sync::{{Arc, Mutex, atomic::{{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}}}}; + +const EINVAL: i32 = -22; +const EBUSY: i32 = -16; +const EIO: i32 = -5; +const WORK_RING_SLOTS: u32 = 128; +type Result = std::result::Result; + +struct HostArc; +impl HostArc {{ + fn new(v: T) -> Result> {{ Ok(Arc::new(v)) }} +}} + +pub struct Availability {{ + waiters: AtomicUsize, + notifications: AtomicUsize, +}} +impl Availability {{ + pub fn new() -> Result> {{ + Ok(Arc::new(Self {{ + waiters: AtomicUsize::new(0), + notifications: AtomicUsize::new(0), + }})) + }} + pub fn has_waiters(&self) -> bool {{ self.waiters.load(Ordering::Acquire) != 0 }} + pub fn notify(&self) {{ self.notifications.fetch_add(1, Ordering::AcqRel); }} + pub fn notifications(&self) -> usize {{ self.notifications.load(Ordering::Acquire) }} +}} + +{prod} + +struct RingState {{ + consumer: u32, + producer: u32, +}} + +impl RingState {{ + fn cursors(&self) -> [u32; 3] {{ + [self.consumer, self.consumer, self.producer] + }} + fn advance_producer(&mut self, count: u32) {{ + for _ in 0..count {{ + let next = (self.producer + 1) % WORK_RING_SLOTS; + assert_ne!(next, self.consumer, "outer ring overcommitted past consumer"); + self.producer = next; + }} + }} + fn consume_if_needed(&mut self, keep_free: u32) {{ + while free(self.cursors()).unwrap() < keep_free {{ + assert_ne!(self.consumer, self.producer); + self.consumer = (self.consumer + 1) % WORK_RING_SLOTS; + }} + }} +}} + +struct HostPortScope<'a> {{ + scope: Option>, + m5_outer: Arc>, +}} + +impl Drop for HostPortScope<'_> {{ + fn drop(&mut self) {{ + if let Some(scope) = self.scope.take() {{ + let _guard = self.m5_outer.lock().unwrap(); + drop(scope); + }} + }} +}} + +fn test_serialized_tight_ring_contention() {{ + let credits = Credits::new().unwrap(); + // Start with only 4 free slots so any race between claim_outer, reserve_m5_outer, + // and OuterScope entry/drop immediately overcommits or trips EIO. + let m5_outer = Arc::new(Mutex::new(RingState {{ + consumer: 5, + producer: 0, + }})); + let stop = Arc::new(AtomicBool::new(false)); + let mut threads = Vec::new(); + + for tid in 0..4u32 {{ + let c = credits.clone(); + let lock = m5_outer.clone(); + let s = stop.clone(); + threads.push(std::thread::spawn(move || {{ + let mut iters = 0u32; + while !s.load(Ordering::Acquire) && iters < 3000 {{ + let reserved = {{ + let mut ring = lock.lock().unwrap(); + ring.consume_if_needed(4); + if c.is_scoped() {{ + Err(EBUSY) + }} else {{ + c.reserve(1, 1, ring.cursors()) + }} + }}; + if let Ok(mut claim) = reserved {{ + if (iters + tid) % 4 == 0 {{ + // Simulate compute_direct fallback: drop unspent claim outside m5_outer. + drop(claim); + }} else {{ + let mut ring = lock.lock().unwrap(); + ring.advance_producer(1); + c.consume_direct(&mut claim).unwrap(); + }} + }} + iters += 1; + }} + }})); + }} + + // Device-mutex publisher: claim_outer() + PortOuterScope entry/drop all serialized on m5_outer. + for iter in 0..400u32 {{ + let claim = {{ + let mut ring = m5_outer.lock().unwrap(); + ring.consume_if_needed(4); + credits.reserve(1, 2, ring.cursors()) + }}; + if let Ok(mut render_claim) = claim {{ + let mut scoped = false; + {{ + let scope = {{ + let _guard = m5_outer.lock().unwrap(); + credits.scope(&mut render_claim).map(|scope| HostPortScope {{ + scope: Some(scope), + m5_outer: m5_outer.clone(), + }}) + }}; + if let Ok(scope) = scope {{ + if iter % 3 != 0 {{ + let mut ring = m5_outer.lock().unwrap(); + assert!(credits.capacity(1, ring.cursors()).unwrap() >= 2); + ring.advance_producer(2); + credits.counter(1).unwrap().fetch_add(2, Ordering::AcqRel); + }} + drop(scope); + scoped = true; + }} + }} + if scoped {{ + if iter % 3 != 0 {{ + assert_eq!(render_claim.remaining(), 0); + }} else {{ + assert_eq!(render_claim.remaining(), 2); + }} + }} + drop(render_claim); + }} + }} + + stop.store(true, Ordering::Release); + for t in threads {{ + t.join().unwrap(); + }} + let ring = m5_outer.lock().unwrap(); + let expected = free(ring.cursors()).unwrap(); + assert_eq!(credits.capacity(1, ring.cursors()).unwrap(), expected); +}} + +fn test_fallback_preserves_claim_without_spurious_notify() {{ + let credits = Credits::new().unwrap(); + let cursors = [0, 0, 0]; + let claim = credits.reserve(1, 1, cursors).unwrap(); + let notes_before = credits.available().notifications(); + + // Simulate compute_direct taking held claim and restoring it on None fallback. + let mut held: Option = Some(claim); + let mut m5_outer = held.take(); + assert!(held.is_none()); + let outcome: Option = None; + if outcome.is_none() {{ + if let Some(c) = m5_outer.take().filter(|c| c.remaining() != 0) {{ + if !held.as_ref().is_some_and(|e| e.remaining() != 0) {{ + held = Some(c); + }} + }} + }} + drop(m5_outer); + assert!(held.is_some()); + assert_eq!(held.as_ref().unwrap().remaining(), 1); + assert_eq!(credits.available().notifications(), notes_before); + + // Subsequent slow-path publication consumes the restored claim cleanly. + let mut c = held.take().unwrap(); + credits.consume_direct(&mut c).unwrap(); + assert_eq!(c.remaining(), 0); + drop(c); + assert_eq!(credits.available().notifications(), notes_before); +}} + +fn main() {{ + assert!({str(claim_outer_ok).lower()}, "claim_outer must hold Port::m5_outer around reserve_outer"); + assert!({str(publish_claimed_ok).lower()}, "publish_claimed must use Port::outer_scope"); + assert!({str(render_scope_ok).lower()}, "render/prepare.rs must use Port::outer_scope"); + assert!({str(port_scope_ok).lower()}, "Port::outer_scope and PortOuterScope::drop must hold Port::m5_outer"); + assert!({str(direct_restore_ok).lower()}, "compute_direct must restore unspent m5_outer claim on None fallback outside cell.lock()"); + assert!({str(cluster_pin_ok).lower()}, "single-die M5 must leave scheduler queues unrestricted"); + test_serialized_tight_ring_contention(); + test_fallback_preserves_claim_without_spurious_notify(); + println!("PASS g17-m5-multiqueue-contention-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + '--mutation', + choices=[ + 'unlocked-claim-outer', + 'raw-compute-scope', + 'raw-render-scope', + 'unlocked-scope-drop', + 'drop-direct-claim-on-fallback', + 'pin-single-die', + ], + ) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-m5-mq-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-m5-render-fast-done-tests.py b/tools/asahi/g17-m5-render-fast-done-tests.py new file mode 100755 index 00000000000000..f84dff058ee0dd --- /dev/null +++ b/tools/asahi/g17-m5-render-fast-done-tests.py @@ -0,0 +1,379 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for single-lock render completion fast path, doorbell lock release, and zero-waiter notifications. + +Verifies: +1. Lock-free zero-waiter `Availability::advance()` compiled from + `drivers/gpu/drm/asahi/g17/availability.rs`: zero mutex locks when no + waiter is registered, `generation` still advances on every `notify()`, + `notify_own()` works, and multi-threaded `observe -> wait` vs `notify` + suffers zero lost wakeups. +2. `DirectHost::notify_render()` (`runtime/render/direct.rs`) drops + `self.m5_outer` (after submission history) and `self.render` in strict + reverse acquisition order BEFORE calling `self.port.notify()`. +3. `runtime_event_turn()` (`runtime/events.rs`) + `try_fast_observe_render()` + (`runtime/render/observe.rs`): + - `fast_epoch` is taken before `state.lock()` and dropped before + `wait_drained_until()` (no recovery deadlock). + - Healthy single-slot render completions return `FastRenderOutcome::Done` + under one lock hold, while `pending_error`, `pending_timeout`, `closed`, + `growing`, `had_terminal`, `missed`, `render_needs_rescan()`, and + multi-slot pending work fall back to `observe_renders()`. + - Slow-path `observe_renders()` folds deferred-error drain and rescan + checks into `runtime_event_turn()`'s existing `state.lock()` holds. +4. `Shared::note_changed()` (`mod.rs`) gates `self.changed.notify_all()` on + `changed_waiters` and all `changed.wait_timeout` callers in `runtime.rs` + use `wait_changed_timeout()`. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + if source.count(part) != 1: + return False + idx = source.index(part) + if idx <= at: + return False + at = idx + return True + + +def build_harness(mutation=None): + avail_src = (G17 / 'availability.rs').read_text() + direct_src = (G17 / 'runtime/render/direct.rs').read_text() + observe_src = (G17 / 'runtime/render/observe.rs').read_text() + events_src = (G17 / 'runtime/events.rs').read_text() + mod_src = (G17 / 'mod.rs').read_text() + runtime_src = (G17 / 'runtime.rs').read_text() + + notify_render = item(direct_src, 'fn notify_render(') + try_fast_entry = item(observe_src, 'pub(in crate::g17::runtime) fn try_fast_observe_render(') + try_fast = item(observe_src, 'fn fast_observe_renders(') + observe_fn = item(observe_src, 'pub(in crate::g17) fn observe_renders(') + turn = item(events_src, 'fn runtime_event_turn(') + tracked_cv = item(mod_src, 'impl TrackedCondVar') + + avail_wait = item(avail_src, 'pub(crate) fn wait(') + avail_advance = item(avail_src, 'fn advance(') + + if mutation == 'hold-m5-outer-across-doorbell': + notify_render = notify_render.replace( + 'self.m5_outer = None;', + '', + 1, + ) + elif mutation == 'hold-render-lock-across-doorbell': + notify_render = notify_render.replace( + 'self.render = None;', + '', + 1, + ) + elif mutation == 'skip-pending-error-fallback': + try_fast = try_fast.replace( + 'entry.pending_error.is_some()\n || ', + '', + 1, + ) + elif mutation == 'single-slot-bailout': + try_fast = try_fast.replace( + 'for _ in 0..crate::hw::t8140::queues::RENDER_SLOTS {', + 'for _ in 0..1 {', + 1, + ) + elif mutation == 'skip-epoch-check': + turn = turn.replace( + 'fast_epoch.as_ref().is_some_and(|epoch| epoch.is_current())', + 'true', + 1, + ) + elif mutation == 'unconditional-changed-notify': + tracked_cv = tracked_cv.replace( + 'if self.waiters.load(Ordering::SeqCst) != 0 {', + 'if true {', + 1, + ) + elif mutation == 'skip-generation-bump': + avail_advance = avail_advance.replace( + 'let previous = self.generation.fetch_add(1, Ordering::SeqCst);\n' + ' if !self.has_waiters.load(Ordering::SeqCst) {\n' + ' return previous;\n' + ' }', + 'if !self.has_waiters.load(Ordering::SeqCst) {\n' + ' return self.generation.load(Ordering::Acquire);\n' + ' }\n' + ' let previous = self.generation.fetch_add(1, Ordering::SeqCst);', + 1, + ) + + doorbell_order_ok = ordered_ok( + notify_render, + 'note_m5_submission_history_locked(geometry, 2)', + 'self.m5_outer = None;', + 'self.render = None;', + 'self.port.notify(super::render_doorbell_message(m5, priority))', + ) + + fast_render_guards_ok = ( + 'entry.pending_error.is_some()' in try_fast + and 'entry.pending_timeout' in try_fast + and 'entry.closed' in try_fast + and 'entry.growing' in try_fast + and 'self.recovery.pending()' in try_fast + and 'self.queues.render.replay_parked()' in try_fast + and 'self.render_grow_pending()' in try_fast + and 'self.render_grow_ready()' in try_fast + and 'had_terminal' in try_fast + and 'self.queues.render_needs_rescan()' in try_fast + and 'for _ in 0..crate::hw::t8140::queues::RENDER_SLOTS {' in try_fast + and 'if !deferred.has_room(2)' in try_fast + and 'self.next_render_observation_in(start, end)?.is_some()' in try_fast + and 'self.fast_observe_renders(1, end, deferred)' in try_fast_entry + and 'FastRenderOutcome::Done' in try_fast + ) + + # Extract the real production loop bound from try_fast_observe_render() to drive a + # compiled multi-slot coalesced-completion test on the host. + loop_match = re.search(r'for _ in 0\.\.([^\s{]+)\s*\{', try_fast) + assert loop_match is not None, 'try_fast_observe_render loop missing' + loop_bound_expr = loop_match.group(1).replace('crate::hw::t8140::queues::RENDER_SLOTS', 'RENDER_SLOTS') + + turn_order_ok = ( + ordered_ok( + turn, + 'let fast_epoch = self.preparations.try_enter().ok();', + 'let (pending, masks, compute_scan) = firmware.service_runtime_events_scan(deferred)?;', + 'fast_epoch.as_ref().is_some_and(|epoch| epoch.is_current())', + 'firmware.try_fast_observe_render(deferred)?', + 'if render_changed {\n self.note_changed();\n }', + 'deferred.finish();', + 'if fast_done {\n return Ok(());\n }', + 'self.preparations\n .wait_drained_until(', + 'firmware.drain_render_deferred(masks, deferred)?;', + 'self.observe_renders(deferred)?;', + 'firmware.queues.render_needs_rescan()', + ) + # Slow-path observe_renders() must no longer acquire extra pre- or post-loop state locks. + and observe_fn.count('self.state.lock()') == 1 + ) + + changed_waiters_ok = ( + 'changed: TrackedCondVar,' in mod_src + and 'if self.waiters.load(Ordering::SeqCst) != 0 {' in tracked_cv + and 'self.condvar.notify_all();' in tracked_cv + and 'self.waiters.fetch_add(1, Ordering::SeqCst);' in tracked_cv + and 'self.0.fetch_sub(1, Ordering::Release);' in tracked_cv + ) + + # Adapt Availability::wait() and advance() for host compilation to test the real Dekker protocol. + host_wait = avail_wait.replace('pub(crate) ', '') + host_wait = host_wait.replace('Result>', 'Result>>') + host_wait = host_wait.replace('fence::independent(&self.fences)?', 'Ok::<_, i32>(Arc::new(AtomicBool::new(false)))?') + host_wait = host_wait.replace('KBox::new(', 'HostBox::new(') + host_wait = host_wait.replace(',\n GFP_KERNEL,\n )?', ')?') + host_wait = host_wait.replace('Fence::from_fence(&fence)', 'fence') + host_wait = host_wait.replace('self.state.lock()', 'self.lock_state()') + + host_advance = avail_advance.replace('self.state.lock()', 'self.lock_state()') + host_advance = host_advance.replace('entry.fence.signal();', 'entry.fence.store(true, Ordering::Release);') + + return f''' +use std::sync::{{Arc, Mutex, MutexGuard, atomic::{{AtomicBool, AtomicU64, AtomicUsize, Ordering}}}}; + +type Result = std::result::Result; + +struct HostBox; +impl HostBox {{ + fn new(v: T) -> Result> {{ Ok(Box::new(v)) }} +}} + +struct Entry {{ + fence: Arc, + next: Option>, +}} + +struct State {{ + waiters: Option>, +}} + +struct Availability {{ + generation: AtomicU64, + has_waiters: AtomicBool, + lock_trips: AtomicUsize, + state: Mutex, +}} + +impl Availability {{ + fn new() -> Arc {{ + Arc::new(Self {{ + generation: AtomicU64::new(0), + has_waiters: AtomicBool::new(false), + lock_trips: AtomicUsize::new(0), + state: Mutex::new(State {{ waiters: None }}), + }}) + }} + fn lock_state(&self) -> MutexGuard<'_, State> {{ + self.lock_trips.fetch_add(1, Ordering::Relaxed); + self.state.lock().unwrap() + }} + fn observe(&self) -> u64 {{ self.generation.load(Ordering::Acquire) }} + fn has_waiters(&self) -> bool {{ self.has_waiters.load(Ordering::Acquire) }} + fn notify(&self) {{ self.advance(); }} + fn notify_own(&self, observed: u64) -> u64 {{ + if self.advance() == observed {{ observed.wrapping_add(1) }} else {{ observed }} + }} + + {host_wait} + + {host_advance} +}} + +fn test_availability_zero_waiter_and_dekker_race() {{ + let a = Availability::new(); + let g0 = a.observe(); + assert!(!a.has_waiters()); + assert_eq!(a.lock_trips.load(Ordering::Relaxed), 0); + + // Zero-waiter notify() advances generation without taking the mutex. + a.notify(); + assert_eq!(a.observe(), g0 + 1, "notify() must bump generation even with zero waiters"); + assert_eq!(a.lock_trips.load(Ordering::Relaxed), 0, "zero-waiter notify must skip state mutex"); + + // A waiter holding the stale observation must retry immediately instead of sleeping. + assert!(a.wait(g0).unwrap().is_none()); + + // notify_own() distinguishes our own bump from a concurrent bump. + let g1 = a.observe(); + assert_eq!(a.notify_own(g1), g1 + 1); + assert_eq!(a.notify_own(g1), g1); + + // Multi-threaded Dekker stress test: every registered waiter MUST eventually be signalled. + let stop = Arc::new(AtomicBool::new(false)); + let a_not = a.clone(); + let s_not = stop.clone(); + let notifier = std::thread::spawn(move || {{ + while !s_not.load(Ordering::Acquire) {{ + a_not.notify(); + std::hint::spin_loop(); + }} + a_not.notify(); + }}); + + for _ in 0..4000 {{ + let obs = a.observe(); + if let Some(fence) = a.wait(obs).unwrap() {{ + while !fence.load(Ordering::Acquire) {{ + std::thread::yield_now(); + }} + }} + }} + stop.store(true, Ordering::Release); + notifier.join().unwrap(); +}} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum FastRenderOutcome {{ + Fallback, + Idle, + Done, +}} + +const RENDER_SLOTS: usize = 8; + +fn run_fast_render_loop(ready: &mut Vec, deferred_cap: usize) -> (FastRenderOutcome, usize) {{ + let mut deferred_len = 0usize; + let mut retired_any = false; + for _ in 0..{loop_bound_expr} {{ + let Some(_slot) = ready.first().copied() else {{ + return (if retired_any {{ FastRenderOutcome::Done }} else {{ FastRenderOutcome::Idle }}, deferred_len); + }}; + if deferred_cap.saturating_sub(deferred_len) < 2 {{ + return (FastRenderOutcome::Fallback, deferred_len); + }} + ready.remove(0); + deferred_len += 1; + retired_any = true; + }} + if !ready.is_empty() {{ + return (FastRenderOutcome::Fallback, deferred_len); + }} + (if retired_any {{ FastRenderOutcome::Done }} else {{ FastRenderOutcome::Idle }}, deferred_len) +}} + +fn test_multi_slot_fast_render() {{ + // 0 ready slots -> Idle. + let mut none = vec![]; + assert_eq!(run_fast_render_loop(&mut none, 16), (FastRenderOutcome::Idle, 0)); + + // 2 coalesced ready render slots must both retire in ONE lock hold (Done, not Fallback). + let mut two = vec![1, 2]; + assert_eq!(run_fast_render_loop(&mut two, 16), (FastRenderOutcome::Done, 2)); + assert!(two.is_empty()); + + // Bounded by deferred room: shortage before 2nd slot returns Fallback after retiring 1st. + let mut tight = vec![1, 2]; + assert_eq!(run_fast_render_loop(&mut tight, 2), (FastRenderOutcome::Fallback, 1)); + assert_eq!(tight, vec![2]); + + // Bounded by RENDER_SLOTS: > RENDER_SLOTS ready items fall back cleanly after the cap. + let mut burst: Vec = (1..=RENDER_SLOTS + 1).collect(); + assert_eq!(run_fast_render_loop(&mut burst, 64), (FastRenderOutcome::Fallback, RENDER_SLOTS)); + assert_eq!(burst.len(), 1); +}} + +fn main() {{ + assert!({str(doorbell_order_ok).lower()}, "DirectHost::notify_render must drop m5_outer then render before port.notify()"); + assert!({str(fast_render_guards_ok).lower()}, "try_fast_observe_render must guard all non-steady states"); + assert!({str(turn_order_ok).lower()}, "runtime_event_turn must scope fast_epoch and fold observe_renders locks"); + assert!({str(changed_waiters_ok).lower()}, "Shared::note_changed must gate condvar wake on changed_waiters"); + test_availability_zero_waiter_and_dekker_race(); + test_multi_slot_fast_render(); + println!("PASS g17-m5-render-fast-done-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['hold-m5-outer-across-doorbell', + 'hold-render-lock-across-doorbell', + 'skip-pending-error-fallback', + 'single-slot-bailout', + 'skip-epoch-check', + 'unconditional-changed-notify', + 'skip-generation-bump']) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-rfd-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-m5-sibling-compute-tests.py b/tools/asahi/g17-m5-sibling-compute-tests.py new file mode 100755 index 00000000000000..84f2ce51675aa1 --- /dev/null +++ b/tools/asahi/g17-m5-sibling-compute-tests.py @@ -0,0 +1,668 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for M5 Pro in-context sibling compute channels. + +Compiles production `Context::next_compute_identity()`, `multi_channel()`, +channel selection, sibling admission, release ordering, and multi-channel exit +acknowledgment logic extracted from the G17 driver against host stubs, and +checks structural invariants for dedicated per-sibling ComputePool, lock-free +primary-first `compute_direct()` routing, and recovery/quarantine interaction: +1. Per-context atomic monotonic `(predecessor_id, current_id)` in `object_ids` + and aligned 1-based `submit_sequence == completion_ordinal` (including + multi-threaded concurrency proving zero ID collisions across sibling QIDs). +2. Dedicated per-sibling `ComputePool` (no `PoolBorrow`, no shared `0x7c/0x80` + pool control contention): a warm reusable sibling requires a same-VM + populated fitting pool, a vacant or other-VM idle queue is re-armed with + fresh backing, and a fresh sibling allocates its own `PoolBacking::new` + + pool descriptor (g17-m5-sibling-rearm-tests.py runs the re-arm path). +3. Lock-free `ComputeCell` atomic `(configuring, active_len, last_published)` + mirror updated via `QueueGuard::drop()`, with primary-first routing in + `compute_direct()` so idle channel 0 never locks sibling cell mutexes. +4. `multi_channel()` board selection, lazy sibling acquisition (cap at 3), + `select_compute_channel()` spread & dependent-kick stickiness, + sibling-before-primary release/rollback/growth order, and multi-channel + exit acknowledgment + `compute_bound()` / `release_compute_witness()`. + +The fan-out gate (input sources and short kicks stay on the primary channel) has +its own test, g17-m5-sibling-gate-tests.py; here the primary runs sustained heavy +work so every sibling path is open. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +def build_harness(mutation=None): + freelist_src = (G17 / 'freelist.rs').read_text() + context_src = (G17 / 'context.rs').read_text() + fw_src = (G17 / 'fw/m5/compute.rs').read_text() + runtime_src = (G17 / 'runtime.rs').read_text() + backend_src = (G17 / 'runtime/backend.rs').read_text() + exit_src = (G17 / 'runtime/compute_exit.rs').read_text() + queue_src = (G17 / 'queue/compute.rs').read_text() + pairs_src = (G17 / 'pairs.rs').read_text() + min_in_flight = re.search(r'pub\(crate\) const SIBLING_MIN_IN_FLIGHT: usize = [0-9]+;', pairs_src).group(0) + overlaps_fn = (min_in_flight + '\n' + item(pairs_src, 'pub(crate) fn overlaps(')).replace('pub(crate) ', '') + + next_id_fn = item(context_src, 'pub(crate) fn next_compute_identity(').replace('pub(crate) ', 'pub ') + multi_fn = item(fw_src, 'pub(crate) fn multi_channel(').replace('pub(crate) ', '') + initdata_src = (G17 / 'fw/m5/initdata.rs').read_text() + channels_fn = item(initdata_src, 'pub(crate) const fn compute_channels(').replace('pub(crate) ', '') + + cell_struct = item(runtime_src, 'pub(super) struct ComputeCell') + cell_impl = item(runtime_src, 'impl ComputeCell') + guard_drop = item(runtime_src, 'impl Drop for QueueGuard<') + channels_of_fn = item(runtime_src, 'fn compute_channels_of(') + next_sib_fn = item(runtime_src, 'fn next_sibling_index(') + source_fn = item(runtime_src, 'fn sibling_source(') + source_enum = item(runtime_src, 'pub(super) enum SiblingSource').replace('pub(super) ', '') + headroom_fn = item(runtime_src, 'fn has_compute_sibling_headroom(') + wants_sib_fn = item(runtime_src, 'fn wants_compute_sibling(') + bind_sib_fn = item(runtime_src, 'fn bind_reusable_sibling(') + try_add_sib_fn = item(runtime_src, 'fn try_add_compute_sibling(') + select_fn = item(runtime_src, 'fn select_compute_channel(') + release_fn = item(runtime_src, 'pub(super) fn release_compute(') + ack_exit_fn = item(exit_src, 'pub(super) fn acknowledge_compute_exit(') + pub_exit_fn = item(exit_src, 'fn publish_compute_exit(') + rollback_fn = item(runtime_src, 'fn rollback_unpublished_compute(\n') + backend_rollback_fn = item(backend_src, 'fn rollback_unpublished_compute(&self)') + grow_fn = item(runtime_src, 'fn grow_compute(') + drain_sib_fn = item(runtime_src, 'fn drain_compute_siblings(') + direct_fn = item(runtime_src, 'fn compute_direct(') + readiness_fn = item(runtime_src, 'fn compute_readiness(&self, packet:') + remember_fn = item(runtime_src, 'fn remember_direct(') + claim_outer_fn = item(runtime_src, 'fn claim_outer(') + bound_fn = item(runtime_src, 'fn compute_bound(') + witness_fn = item(runtime_src, 'fn release_compute_witness(') + parent_pred_start = queue_src.index('let parent_retired = self.active.len == 0') + parent_pred_end = queue_src.index('let m5_args =', parent_pred_start) + parent_pred = queue_src[parent_pred_start:parent_pred_end] + m5_args_start = parent_pred_end + m5_args_end = queue_src.index('let mut m5_dependency_types =', m5_args_start) + m5_args_block = queue_src[m5_args_start:m5_args_end] + + if mutation == 'fixed-object-ids': + next_id_fn = ( + 'pub fn next_compute_identity(&self) -> (u32, u64) {\n' + ' let next = self.compute_ordinal.fetch_add(1, Ordering::AcqRel).wrapping_add(1);\n' + ' (next, 0x0000_0001_0000_0001)\n' + '}' + ) + elif mutation == 'primary-before-sibling': + release_fn = release_fn.replace('for primary_pass in [false, true]', + 'for primary_pass in [true, false]', 1) + elif mutation == 'exit-ack-stops-first': + ack_exit_fn = ack_exit_fn.replace( + 'matched |= queue.acknowledge_exit(cookie);', + 'if queue.acknowledge_exit(cookie) { return; }', + 1, + ) + elif mutation == 'direct-allows-multi-barrier': + direct_fn = direct_fn.replace( + ' || (bound_count > 1 && packet.order.wait_through[1].is_some())\n', '', 1) + elif mutation == 'direct-blocks-sibling': + direct_fn = direct_fn.replace( + ' } else if can_add_sibling && all_busy {\n' + ' return None;\n' + ' } else {\n', + ' } else {\n', + 1, + ) + elif mutation == 'direct-locks-sibling-when-idle': + direct_fn = direct_fn.replace( + 'let (configuring, active, last_published) = cell.load_hint();', + 'let queue = cell.lock()?; let (configuring, active, last_published) = (queue.configuring(), queue.active_len() as u32, queue.last_published());', + 1, + ) + elif mutation == 'direct-skips-multi': + direct_fn = direct_fn.replace( + 'bound_count > super::pairs::COMPUTE_CHANNELS_MAX', + 'bound_count > 1', + 1, + ) + elif mutation == 'same-qid-pipelined': + parent_pred = parent_pred.replace( + 'parent_dependency(board, parent_retired)', + 'parent_dependency(board, true)', + 1, + ) + + reg_methods = '\n'.join([ + channels_of_fn, + next_sib_fn, + source_fn, + headroom_fn, + wants_sib_fn, + select_fn, + release_fn, + ]) + reg_methods = reg_methods.replace('pub(super) ', 'pub ') + reg_methods = reg_methods.replace('super::job::Packet', 'Packet') + reg_methods = reg_methods.replace('super::freelist::ComputeCapacity', 'ComputeCapacity') + reg_methods = reg_methods.replace('super::pairs::', '') + + ack_code = ack_exit_fn.replace('pub(super) ', 'pub ') + ack_code = re.sub(r'crate::g17::trace::teardown\([^;]*\);', '', ack_code) + + # Structural invariant booleans compiled into the host binary so every check + # fails with a Rust assertion panic (exit 101) when violated. + dedicated_pool_ok = ( + 'PoolBorrow' not in freelist_src + and 'PoolBorrow' not in queue_src + and 'shared_pool' not in queue_src + and 'PoolBacking::new(' in try_add_sib_fn + and 'install_compute_pool(pool.pool_descriptor()?)' in try_add_sib_fn + and ordered_ok(source_fn, 'if queue.pool_vacant() {', '} else if queue.pool_serves(vm) {', + '!queue.pool_fits(required)', '&mut warm') + and 'let Some(SiblingSource::Warm(qid)) = self.sibling_source(owner, context, required) else' in bind_sib_fn + and 'qid,\n channel_index,\n required,' in try_add_sib_fn + ) + identity_wired_ok = ( + 'packet.context.next_compute_identity()' in parent_pred + and 'object_ids: m5_object_ids,' in m5_args_block + and 'submit_sequence: if board.completion_inputs() { u64::from(m5_ordinal) } else { 0 },' in m5_args_block + and 'completion_ordinal: crate::g17::fw::m5::compute::completion_ordinal(board, m5_ordinal),' in m5_args_block + and 'peek_compute_ordinal' not in queue_src + ) + cell_atomic_ok = ( + 'active_len: core::sync::atomic::AtomicU32' in cell_struct + and 'configuring: core::sync::atomic::AtomicBool' in cell_struct + and 'last_published: core::sync::atomic::AtomicU64' in cell_struct + and 'fn sync_stats(' in cell_impl + and 'fn load_hint(' in cell_impl + and 'self.cell.sync_stats(Some(queue));' in guard_drop + ) + rollback_order_ok = ordered_ok( + rollback_fn, + 'for primary_pass in [false, true]', + 'queue.is_primary() == primary_pass', + '.rollback_unpublished(owner, context)?', + ) and ordered_ok( + backend_rollback_fn, + 'firmware.queues.rollback_unpublished_compute(', + 'drop(state);', + 'self.finish_retired_compute(&mut retired)', + ) + grow_releases_siblings_ok = ( + ordered_ok( + drain_sib_fn, + 'queue.owner() == Some(owner) && !queue.is_primary()', + 'if busy {', + 'return Err(EAGAIN);', + '.release_owner()?', + 'entry.queue.take()', + ) + and ordered_ok( + grow_fn, + 'firmware.queues.drain_compute_siblings(self.owner, &mut retired_siblings)?;', + 'firmware.queues.compute_primary(self.owner)', + 'self.finish_retired_compute(&mut retired_siblings)?;', + ) + ) + exit_propagates_ok = ordered_ok( + pub_exit_fn, + 'if context.kill_published()', + 'queue.record_exit(cookie, now);', + 'if other.exit_candidate(context, age)', + 'other.record_exit(cookie, now);', + ) + # Lock-free primary-first selection: compute_direct must NEVER call cell.lock() during + # channel selection, must short-circuit to channel 0 when primary_active == 0 && !primary_configuring, + # and must only lock target_cell once. + select_section = direct_fn[:direct_fn.index('let target_cell =')] + direct_guards_ok = ( + 'cell.lock()' not in select_section + and ordered_ok( + direct_fn, + 'bound_count > super::pairs::COMPUTE_CHANNELS_MAX', + 'bound_count > 1 && packet.order.wait_through[1].is_some()', + 'let (primary_configuring, primary_active, _) = primary.load_hint();', + 'if primary_active == 0 && !primary_configuring', + 'let (configuring, active, last_published) = cell.load_hint();', + 'if can_add_sibling && all_busy', + 'self.outer_compute.lock()', + 'claim.remaining() != 0 && claim.priority() == usize::from(priority)', + 'queue.pool_fits(required)', + 'm5 && queue.outer_slots() != 1', + 'self.context.compute_binding_count() as usize != cached_count', + ) + and 'registry.compute_cells(self.owner)' in remember_fn + ) + readiness_and_outer_ok = ( + ordered_ok( + readiness_fn, + 'bound_count <= super::pairs::COMPUTE_CHANNELS_MAX', + 'cells[1..].iter().flatten()', + 'queue.pool_fits(required)', + 'queue.claim()', + 'self.claim_compute_outer_direct(outer_slots)', + ) + and '.map(|queue| queue.outer_slots())' in claim_outer_fn + and '.max()' in claim_outer_fn + ) + same_qid_serialized_ok = ( + 'parent_dependency(board, parent_retired)' in parent_pred + and 'same_context_independent' not in parent_pred + ) + multi_witness_and_bound_ok = ( + 'self.compute_primary(owner)' in bound_fn + and '!queue.is_primary()' in bound_fn + and 'queue.pool_fits(required)' in bound_fn + and 'pending |= queue.spared_pending();' in witness_fn + ) + + return f''' +#![allow(dead_code, unused_variables, unused_mut)] +use std::cell::RefCell; +use std::collections::HashSet; +use std::sync::{{Arc, atomic::{{AtomicU32, AtomicUsize, Ordering}}}}; + +const EINVAL: i32 = -22; +const EAGAIN: i32 = -11; +const EIO: i32 = -5; +const EOVERFLOW: i32 = -75; +type Result = std::result::Result; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct ComputeCapacity(u32); + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +{source_enum} + +{overlaps_fn} + +struct Board {{ + compute_channels: u8, +}} +impl Board {{ + {channels_fn} +}} + +{multi_fn} + +struct Order {{ + wait_through: [Option; 2], +}} +struct Completion {{ + sources: Option<()>, +}} +impl Completion {{ + fn sources(&self) -> Option<&()> {{ self.sources.as_ref() }} +}} +struct Packet {{ + order: Order, + completion: Completion, +}} + +struct Context {{ + id: u32, + vm_id: u32, + compute_ordinal: AtomicU32, +}} +impl Context {{ + fn new(id: u32, vm_id: u32) -> Arc {{ + Arc::new(Self {{ id, vm_id, compute_ordinal: AtomicU32::new(0) }}) + }} + fn vm(&self) -> u32 {{ self.vm_id }} + {next_id_fn} +}} + +struct Queue {{ + qid: u8, + owner: Option, + channel_index: u8, + active_len: usize, + replays: usize, + configuring: bool, + last_published: u64, + sustained: bool, + reusable: bool, + needs_fresh_backing: bool, + pool_vacant: bool, + pool_vm: u32, + pool_cap: u32, + has_ring: bool, + context: Option>, + exit_cookie: Option, + exit_acked: bool, + unpublished: bool, + released_log: Arc>>, +}} +impl Queue {{ + fn qid(&self) -> u8 {{ self.qid }} + fn owner(&self) -> Option {{ self.owner }} + fn channel_index(&self) -> u8 {{ self.channel_index }} + fn is_primary(&self) -> bool {{ self.channel_index == 0 }} + fn active_len(&self) -> usize {{ self.active_len }} + fn has_replays(&self) -> bool {{ self.replays != 0 }} + fn configuring(&self) -> bool {{ self.configuring }} + fn last_published(&self) -> u64 {{ self.last_published }} + fn sustained(&self) -> bool {{ self.sustained }} + fn reusable(&self) -> bool {{ self.reusable }} + fn needs_fresh_backing(&self) -> bool {{ self.needs_fresh_backing }} + fn pool_vacant(&self) -> bool {{ self.pool_vacant }} + fn pool_serves(&self, vm: u32) -> bool {{ self.pool_vm == vm }} + fn pool_fits(&self, req: ComputeCapacity) -> bool {{ self.pool_cap >= req.0 }} + fn has_ring(&self) -> bool {{ self.has_ring }} + fn context(&self) -> Option<&Arc> {{ self.context.as_ref() }} + fn rearm_open(&self, _owner: u64) -> bool {{ true }} + fn released_at(&self) -> u64 {{ self.last_published }} + fn vacancy_pending(&self) -> bool {{ false }} + fn release_owner(&mut self) -> Result {{ + self.released_log.borrow_mut().push((self.qid, self.channel_index)); + self.owner = None; + self.channel_index = 0; + Ok(self.unpublished) + }} + fn acknowledge_exit(&mut self, cookie: u64) -> bool {{ + if self.exit_cookie == Some(cookie) {{ + self.exit_acked = true; + true + }} else {{ + false + }} + }} +}} + +struct Slot(Option>); +impl Slot {{ + fn as_deref(&self) -> Option> {{ + self.0.as_ref().map(|q| q.borrow()) + }} + fn as_deref_mut(&mut self) -> Option> {{ + self.0.as_ref().map(|q| q.borrow_mut()) + }} +}} + +struct Entry {{ + reservation: Reservation, + queue: Slot, +}} +#[derive(Copy, Clone)] +struct Reservation {{ id: u8 }} + +struct Qids {{ fit: bool, cancelled: Vec }} +impl Qids {{ + fn compute_fits(&self, _queues: usize) -> bool {{ self.fit }} + fn cancel_unpublished(&mut self, id: u8) -> Result {{ + self.cancelled.push(id); + Ok(()) + }} +}} + +struct Admission {{ queues: u32 }} +impl Admission {{ + fn queues(&self) -> u32 {{ self.queues }} + fn render_demand(&self, extra: usize) -> usize {{ self.queues as usize + extra }} +}} + +struct Teardown {{ releasing_id: Option, render_acked: bool }} +impl Teardown {{ + fn releasing(&self, ctx: &Arc) -> bool {{ self.releasing_id == Some(ctx.id) }} + fn acknowledge_render_kill(&mut self, _cookie: u64) -> bool {{ + self.render_acked = true; + true + }} +}} + +static RENDER_KILLS: [AtomicUsize; 2] = [AtomicUsize::new(0), AtomicUsize::new(0)]; +const RENDER_KILL_ACKNOWLEDGED: usize = 0; + +struct Registry {{ + compute: Vec>, + qids: Qids, + admission: Admission, + teardown: Teardown, + build_room_noted: usize, +}} + +impl Registry {{ + fn note_build_room(&mut self) {{ self.build_room_noted += 1; }} + {reg_methods} + {ack_code} +}} + +fn make_entry(q: Queue) -> Option {{ + let qid = q.qid; + Some(Entry {{ + reservation: Reservation {{ id: qid }}, + queue: Slot(Some(RefCell::new(q))), + }}) +}} + +fn test_atomic_compute_identity() {{ + let ctx = Context::new(1, 100); + // Sequential check: 1-based ordinal with monotonic (predecessor_id << 32) | current_id. + assert_eq!(ctx.next_compute_identity(), (1, (1u64 << 32) | 1)); + assert_eq!(ctx.next_compute_identity(), (2, (1u64 << 32) | 2)); + assert_eq!(ctx.next_compute_identity(), (3, (2u64 << 32) | 3)); + assert_eq!(ctx.next_compute_identity(), (4, (3u64 << 32) | 4)); + + // Concurrent check across 4 threads simulating direct sibling compute kicks: + // every kick must receive a unique ordinal and a unique non-zero current_id. + let shared = Context::new(2, 200); + let mut threads = Vec::new(); + for _ in 0..4 {{ + let c = shared.clone(); + threads.push(std::thread::spawn(move || {{ + let mut out = Vec::with_capacity(500); + for _ in 0..500 {{ + out.push(c.next_compute_identity()); + }} + out + }})); + }} + let mut ordinals = HashSet::new(); + let mut current_ids = HashSet::new(); + for t in threads {{ + for (ord, ids) in t.join().unwrap() {{ + let pred = (ids >> 32) as u32; + let cur = ids as u32; + assert_ne!(pred, 0); + assert_ne!(cur, 0); + assert_eq!(cur, ord); + assert!(ordinals.insert(ord), "duplicate shared ordinal {{}}", ord); + assert!(current_ids.insert(cur), "duplicate object_ids current_id {{}}", cur); + }} + }} + assert_eq!(ordinals.len(), 2000); +}} + +fn main() {{ + // 1. Structural guards for dedicated pools, monotonic identities, lock-free ComputeCell hints, + // compute_direct primary-first routing, grow, rollback, and exit propagation. + assert!({str(dedicated_pool_ok).lower()}, "siblings must own dedicated ComputePools with no PoolBorrow"); + assert!({str(identity_wired_ok).lower()}, "multi-channel M5 compute must wire atomic next_compute_identity to object_ids, submit_sequence, and completion_ordinal"); + assert!({str(cell_atomic_ok).lower()}, "ComputeCell must mirror active_len/configuring/last_published atomically via QueueGuard::drop"); + assert!({str(rollback_order_ok).lower()}, "rollback_unpublished_compute must roll back siblings before primary"); + assert!({str(grow_releases_siblings_ok).lower()}, "grow_compute must drain and release siblings before primary growth"); + assert!({str(exit_propagates_ok).lower()}, "publish_compute_exit must propagate kill cookie across all channels of context"); + assert!({str(direct_guards_ok).lower()}, "compute_direct must use lock-free primary-first routing without locking sibling cells, guard barriers, reuse outer_compute, and yield when siblings can be added"); + assert!({str(readiness_and_outer_ok).lower()}, "compute_readiness/claim_outer must validate all bound channels and take max outer_slots"); + assert!({str(same_qid_serialized_ok).lower()}, "multi-channel M5 Pro must keep COMPLETION_DEPENDENCY while a physical QID has an active parent"); + assert!({str(multi_witness_and_bound_ok).lower()}, "compute_bound and release_compute_witness must inspect all channels of owner"); + + // 2. Per-context monotonic object_ids & aligned submit_sequence == completion_ordinal. + test_atomic_compute_identity(); + + // 3. multi_channel() board selection. + assert!(multi_channel(&Board {{ compute_channels: 3 }})); + assert!(multi_channel(&Board {{ compute_channels: 2 }})); + assert!(!multi_channel(&Board {{ compute_channels: 1 }})); + + // 4. Lazy sibling admission + dedicated-pool headroom + round-robin selection + release order. + let ctx = Context::new(1, 77); + let req = ComputeCapacity(16); + let log = Arc::new(RefCell::new(Vec::new())); + let mut reg = Registry {{ + compute: vec![ + make_entry(Queue {{ + qid: 10, owner: Some(1), channel_index: 0, active_len: 1, replays: 0, + configuring: false, last_published: 100, sustained: true, reusable: false, + needs_fresh_backing: false, pool_vacant: false, pool_vm: 77, pool_cap: 16, + has_ring: true, context: None, exit_cookie: Some(0xabc), exit_acked: false, + unpublished: false, released_log: log.clone(), + }}), + make_entry(Queue {{ + qid: 11, owner: Some(1), channel_index: 1, active_len: 1, replays: 0, + configuring: false, last_published: 101, sustained: false, reusable: false, + needs_fresh_backing: false, pool_vacant: false, pool_vm: 77, pool_cap: 16, + has_ring: true, context: None, exit_cookie: Some(0xabc), exit_acked: false, + unpublished: true, released_log: log.clone(), + }}), + ], + qids: Qids {{ fit: true, cancelled: Vec::new() }}, + admission: Admission {{ queues: 1 }}, + teardown: Teardown {{ releasing_id: None, render_acked: false }}, + build_room_noted: 0, + }}; + assert_eq!(reg.compute_channels_of(1), (2, 0b11)); + assert_eq!(reg.next_sibling_index(1, 3), Some(2)); + assert!(reg.wants_compute_sibling(1, &ctx, 3, req)); + + // When surplus QIDs are exhausted, a reusable queue must provide the sibling. + reg.qids.fit = false; + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + // An idle reusable queue still holding another VM's pool counts: it is given back and + // re-armed for this VM (no lockout once earlier clients took every QID). + reg.compute.push(make_entry(Queue {{ + qid: 13, owner: None, channel_index: 0, active_len: 0, replays: 0, + configuring: false, last_published: 10, sustained: false, reusable: true, + needs_fresh_backing: false, pool_vacant: false, pool_vm: 99, pool_cap: 16, + has_ring: true, context: None, exit_cookie: None, exit_acked: false, + unpublished: false, released_log: log.clone(), + }})); + assert!(reg.wants_compute_sibling(1, &ctx, 3, req)); + assert_eq!(reg.sibling_source(1, &ctx, req), Some(SiblingSource::Foreign(13))); + // So does a vacant one, before it. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().pool_vacant = true; + assert_eq!(reg.sibling_source(1, &ctx, req), Some(SiblingSource::Vacant(13))); + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().pool_vacant = false; + // A queue with an owner never does. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().reusable = false; + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().reusable = true; + // Same-VM fitting populated reusable queue DOES count, first. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().pool_vm = 77; + assert!(reg.wants_compute_sibling(1, &ctx, 3, req)); + assert_eq!(reg.sibling_source(1, &ctx, req), Some(SiblingSource::Warm(13))); + // Undersized same-VM pool does NOT count. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().pool_cap = 8; + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + reg.compute.pop(); + reg.qids.fit = true; + + // If a bound channel has pending replays, refuse new siblings. + reg.compute[1].as_mut().unwrap().queue.as_deref_mut().unwrap().replays = 1; + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + reg.compute[1].as_mut().unwrap().queue.as_deref_mut().unwrap().replays = 0; + + // Add 3rd channel (index 2): cap reached, wants_compute_sibling becomes false. + reg.compute.push(make_entry(Queue {{ + qid: 12, owner: Some(1), channel_index: 2, active_len: 0, replays: 0, + configuring: false, last_published: 50, sustained: false, reusable: false, + needs_fresh_backing: false, pool_vacant: false, pool_vm: 77, pool_cap: 16, + has_ring: true, context: None, exit_cookie: Some(0xabc), exit_acked: false, + unpublished: false, released_log: log.clone(), + }})); + assert_eq!(reg.next_sibling_index(1, 3), None); + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + + // Independent packet picks least-loaded idle sibling (qid 12). + let indep = Packet {{ order: Order {{ wait_through: [None, None] }}, completion: Completion {{ sources: None }} }}; + assert_eq!(reg.select_compute_channel(1, &indep), Some(12)); + + // When all 3 have equal active_len=1, oldest last_published (qid 12, lp=50) wins. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().active_len = 1; + assert_eq!(reg.select_compute_channel(1, &indep), Some(12)); + + // Dependent packet when only ONE channel is active stays on that sole active channel. + reg.compute[0].as_mut().unwrap().queue.as_deref_mut().unwrap().active_len = 0; + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().active_len = 0; + let dep = Packet {{ order: Order {{ wait_through: [None, Some(42)] }}, completion: Completion {{ sources: None }} }}; + assert_eq!(reg.select_compute_channel(1, &dep), Some(11)); + + // 5. Multi-channel exit acknowledgment must mark ALL channels sharing the cookie. + reg.acknowledge_compute_exit(0xabc); + for slot in 0..3 {{ + assert!(reg.compute[slot].as_ref().unwrap().queue.as_deref().unwrap().exit_acked, + "channel slot {{}} did not receive shared exit cookie ack", slot); + }} + assert!(!reg.teardown.render_acked); + + // 6. Sibling-before-primary release order. + reg.release_compute(1).unwrap(); + let entries = log.borrow(); + assert_eq!(entries.len(), 3); + assert_ne!(entries[0].1, 0, "first release must be a sibling"); + assert_ne!(entries[1].1, 0, "second release must be a sibling"); + assert_eq!(entries[2].1, 0, "primary must be released last"); + assert_eq!(reg.qids.cancelled, vec![11]); + assert!(reg.compute[1].is_none()); + + println!("PASS g17-m5-sibling-compute: all checks passed"); +}} +''' + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--mutation', choices=[ + 'fixed-object-ids', + 'primary-before-sibling', + 'exit-ack-stops-first', + 'direct-allows-multi-barrier', + 'direct-blocks-sibling', + 'direct-locks-sibling-when-idle', + 'direct-skips-multi', + 'same-qid-pipelined', + ]) + args = ap.parse_args() + + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-sib-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + cc = subprocess.run([rustc, '--edition=2021', '-O', str(rs), '-o', str(exe)], + capture_output=True, text=True) + if cc.returncode != 0: + sys.stderr.write(cc.stderr) + return cc.returncode + run = subprocess.run([str(exe)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-m5-sibling-gate-tests.py b/tools/asahi/g17-m5-sibling-gate-tests.py new file mode 100755 index 00000000000000..3068c820beb54d --- /dev/null +++ b/tools/asahi/g17-m5-sibling-gate-tests.py @@ -0,0 +1,530 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for the M5 Pro sibling compute fan-out gate. + +Compiles the production gate against host stubs: the heavy-kick run in +drivers/gpu/drm/asahi/g17/pairs.rs, `Backend::fans_out()`, the lock-free channel +selection section of `compute_direct()`, the `ComputeCell` hint mirror, and the +registry's `select_compute_channel()` / `wants_compute_sibling()`. It checks: + +a. A command with cross-queue input sources never leaves the primary channel and + never brings up a sibling, on the direct and the device-mutex paths, and the + direct path still resolves those sources before routing (published sources, + binding loans). +b. Kicks whose firmware execution records stay under the heavy threshold stream + down the primary ring: no sibling routing, no detour to the device-mutex path + to add one, no new sibling; one long kick among short ones does not open the + gate and one short kick closes it. +c. Sustained heavy kicks fan out onto an idle sibling (or ask for one when every + channel is busy) only once two kicks of the owner are already in flight, so a + kick queued behind one in flight stays on the primary ring; each sibling has + its own compute pool, with monotonic per-context ordinals and object ids, and + the gate is read through the primary cell's lock-free hint. +d. The sibling channels keep the published-source, binding-loan and idle + housekeeping paths of the queues they share a context with. + +Each mutation restores one old behaviour or drops one part of the rule, and must +fail an assertion of the compiled harness. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +ASAHI = ROOT / 'drivers/gpu/drm/asahi' +G17 = ASAHI / 'g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def const(source, name): + match = re.search(r'(?:pub\(crate\) )?const ' + name + r': [^=]+= [^;]+;', source, re.S) + assert match, name + return match.group(0).replace('pub(crate) ', '') + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +# name -> [(file, old, new)]: each must apply exactly once. +MUTATIONS = { + # (a) a command with sources fans out like any other. + 'sources-fan-out': [('runtime', ' && packet.completion.sources().is_none()\n && primary_sustained()', + ' && primary_sustained()')], + 'select-sources-anywhere': [('runtime', ' if let Some((qid, _)) = primary.filter(|_| packet.completion.sources().is_some()) {\n return Some(qid);\n }\n', '')], + # (b) short kicks fan out. + 'tiny-fans-out': [('pairs', 'if end.saturating_sub(start) >= SIBLING_EXECUTION_TICKS {', 'if end >= start {')], + 'no-sustain-run': [('pairs', 'run >= SIBLING_SUSTAINED_KICKS', 'run >= 1')], + 'short-keeps-run': [('pairs', ' } else {\n 0\n }\n}', ' } else {\n run\n }\n}')], + 'direct-ignores-gate': [('runtime', 'let target_idx = if cached_count == 1 || !fans_out {', 'let target_idx = if cached_count == 1 {')], + 'direct-can-add-ungated': [('runtime', ' let can_add_sibling = fans_out\n && cached_count', + ' let can_add_sibling = packet.order.wait_through[1].is_none()\n && cached_count')], + 'wants-ignores-sustained': [('runtime', 'if !sustained_primary || !all_busy', 'if !all_busy')], + 'select-ignores-sustained': [('runtime', ' if let Some((qid, false)) = primary {\n return Some(qid);\n }\n', '')], + # (c) the lock-free hint loses the gate, or the gate takes a lock first. + 'cell-drops-sustained': [('runtime', 'self.sustained.store(queue.sustained(), Ordering::Release);', + 'self.sustained.store(false, Ordering::Release);')], + 'fans-out-locks-first': [('runtime', ' self.compute_channels > 1\n && packet.order.wait_through[1].is_none()\n' + ' && packet.completion.sources().is_none()\n && primary_sustained()', + ' primary_sustained()\n && self.compute_channels > 1\n' + ' && packet.order.wait_through[1].is_none()\n && packet.completion.sources().is_none()')], + # (c) A kick overlaps the owner's work while only one kick is in flight. + 'overlap-at-one': [('pairs', 'in_flight >= SIBLING_MIN_IN_FLIGHT', 'in_flight >= 1')], + 'direct-ignores-in-flight': [('runtime', ' if !super::pairs::overlaps(in_flight) {\n 0\n } else if', + ' if false {\n 0\n } else if')], + 'select-ignores-in-flight': [('runtime', ' if let Some((qid, _)) = primary.filter(|_| !super::pairs::overlaps(in_flight)) {\n' + ' return Some(qid);\n }\n', '')], + 'wants-ignores-in-flight': [('runtime', ' || !super::pairs::overlaps(in_flight) {', ' {')], + 'detour-at-one': [('runtime', ' && super::pairs::overlaps(queue.active_len()))', + ' && (queue.active_len() != 0 || queue.configuring()))')], + # A reused channel keeps the previous owner's run of heavy kicks. + 'keep-run-across-owners': [('queue', ' self.channel_index = channel_index;\n self.heavy_run = 0;\n', + ' self.channel_index = channel_index;\n')], +} + + +def build(mutation=None): + files = { + 'pairs': (G17 / 'pairs.rs').read_text(), + 'runtime': (G17 / 'runtime.rs').read_text(), + 'queue': (G17 / 'queue/compute.rs').read_text(), + } + for name, old, new in MUTATIONS.get(mutation, []): + assert files[name].count(old) == 1, (mutation, old) + files[name] = files[name].replace(old, new) + pairs, runtime, queue = files['pairs'], files['runtime'], files['queue'] + context = (G17 / 'context.rs').read_text() + hw = (ASAHI / 'hw/t8140.rs').read_text() + events = (G17 / 'runtime/events.rs').read_text() + submit = (G17 / 'runtime/render/submit.rs').read_text() + + hz = const(hw, 'COMMAND_TIMESTAMP_HZ') + gate = '\n'.join([ + const(pairs, 'SIBLING_EXECUTION_NS'), + const(pairs, 'SIBLING_EXECUTION_TICKS').replace('crate::hw::t8140::resources::', ''), + const(pairs, 'SIBLING_SUSTAINED_KICKS'), + const(pairs, 'SIBLING_MIN_IN_FLIGHT'), + item(pairs, 'pub(crate) fn heavy_run('), + item(pairs, 'pub(crate) fn sustained('), + item(pairs, 'pub(crate) fn overlaps('), + ]).replace('pub(crate) ', '') + next_id = item(context, 'pub(crate) fn next_compute_identity(').replace('pub(crate) ', '') + queue_sustained = item(queue, 'pub(crate) fn sustained(&self)').replace('pub(crate) ', 'pub ') \ + .replace('crate::g17::pairs::sustained', 'crate::sustained') + sync_stats = item(runtime, 'fn sync_stats(') + load_hint = item(runtime, 'pub(super) fn load_hint(').replace('pub(super) ', '') + cell_sustained = item(runtime, 'pub(super) fn sustained(&self)').replace('pub(super) ', '') + fans_out = item(runtime, 'fn fans_out(').replace('super::job::Packet', 'Packet') + direct = item(runtime, 'fn compute_direct(') + select_start = direct.index(' let primary = cells[0].as_ref()?;') + select_end = direct.index(' let target_cell = cells[target_idx].as_ref()?;') + route = direct[select_start:select_end].replace('super::pairs::', '') + registry = '\n'.join(item(runtime, signature) for signature in [ + 'fn compute_channels_of(', 'fn next_sibling_index(', 'fn sibling_source(', + 'fn has_compute_sibling_headroom(', 'fn wants_compute_sibling(', 'fn select_compute_channel(', + ]).replace('super::job::Packet', 'Packet').replace('super::freelist::ComputeCapacity', 'ComputeCapacity') \ + .replace('super::pairs::', '') + sibling_source = item(runtime, 'pub(super) enum SiblingSource').replace('pub(super) ', '') + inline = item(runtime, 'fn compute_inline(') + packet_fn = item(runtime, ' fn compute_packet(') + readiness = item(runtime, 'fn compute_readiness(&self, packet:') + bind_owner = item(queue, 'fn bind_owner_channel(') + clear_owner = item(queue, 'fn clear_owner(') + publish = item(queue, 'pub(in crate::g17) fn publish_with_native_waits(') + retire_arm_start = queue.index('Ok(Some((timestamps, stampless))) => {') + retire_arm = queue[retire_arm_start:queue.index('Ok(None) | Err(EAGAIN) => {', retire_arm_start)] + render_deps = item(submit, 'fn render_dependencies(') + + # Structural rules that the compiled part cannot see, each a Rust assertion below. + structure = { + # (a) Both device-mutex paths ask the gate before any sibling work. + 'mutex paths ask fans_out before binding a sibling': ( + ordered_ok(inline, 'if self.fans_out(packet, || {', 'compute_primary(self.owner)', + '.is_some_and(|queue| queue.sustained())', 'wants_compute_sibling(', + 'bind_reusable_sibling(') + and ordered_ok(packet_fn, 'if !sibling_tried', '&& self.fans_out(packet, || {', + '.is_some_and(|queue| queue.sustained())', 'wants_compute_sibling(', + 'bind_reusable_sibling(', 'self.try_add_compute_sibling(required, &admission)?') + and 'packet.order.wait_through[1].is_none()\n {' not in packet_fn), + # (a, d) Direct sources still resolve lock-free from their PublishedSource snapshots with + # binding loans before any routing, and the holds follow the publication. + 'direct sources resolve before routing, holds follow publication': ordered_ok( + direct, 'if (has_sources && !m5)', 'let generation = port.generation();', + 'self.resolve_direct_sources(port, generation, target_qid, sources)?', + 'let fans_out = self.fans_out(packet, || primary.sustained());', + 'let target_cell = cells[target_idx].as_ref()?;', 'direct_frontier.as_slice()', + 'if packet.is_published() {', 'sources.set_holds(direct_holds);', 'drop(direct_holds);'), + 'readiness claims the primary for M5 sources': ordered_ok( + readiness, 'let sources_checked =', '(!sources_checked || self.context.is_m5())', + 'cells[1..].iter().flatten()', 'queue.claim()', 'self.hold_claim(Some(primary));'), + # (b, c) The direct path detours to the device-mutex path for a sibling only when it may + # add one: a busy single channel under a closed gate, or with a single kick in flight, + # keeps publishing directly. + 'direct detours only when it may add a sibling': ordered_ok( + direct, '(cached_count == 1\n && can_add_sibling\n' + ' && super::pairs::overlaps(queue.active_len()))'), + # (b, c) The run is measured on exact execution records only, once per retired kick, + # and starts over for every owner. + 'only exact records measure a kick': ordered_ok( + retire_arm, 'let execution = front.observed.map(|record| record.timestamps);', + 'defer(match producers {', 'self.retire_pending = false;', + 'if let Some([start, end]) = execution {', + 'self.heavy_run = crate::g17::pairs::heavy_run(self.heavy_run, start, end);'), + 'a new owner starts a new run': ( + 'self.heavy_run = 0;' in clear_owner + and ordered_ok(bind_owner, 'self.channel_index = channel_index;', 'self.heavy_run = 0;')), + # (d) A sibling's own QID and source readers are what its PublishedSource names; the + # shared context keeps one ordinal sequence across channels. + 'siblings publish their own QID as a source': ordered_ok( + publish, 'packet.context.next_compute_identity()', + 'crate::g17::fw::kick::KickDependency::new(qid, kick_timestamp)', + 'packet.completion.note_source_published(', 'readers: self.source_readers.clone(),'), + # (d) The deferred idle housekeeping counts every compute queue, siblings included, as + # in flight; renders wait on every compute channel of the owner. + 'idle housekeeping sees sibling work': ordered_ok( + events, '.compute', '.iter()', '.flatten()', '.filter_map(|entry| entry.queue.as_deref())', + '.any(|queue| queue.in_flight())', 'firmware.idle_check(now, in_flight)?'), + 'renders wait on every compute channel': ordered_ok( + render_deps, '.filter(|queue| queue.owner() == Some(owner))', '.compute_count', + 'dependencies.compute_count += 1;'), + } + checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' + for name, ok in structure.items()) + + return (TEMPLATE + .replace('@@HZ@@', hz) + .replace('@@GATE@@', gate) + .replace('@@NEXT_ID@@', next_id) + .replace('@@QUEUE_SUSTAINED@@', queue_sustained) + .replace('@@SYNC_STATS@@', sync_stats) + .replace('@@LOAD_HINT@@', load_hint) + .replace('@@CELL_SUSTAINED@@', cell_sustained) + .replace('@@FANS_OUT@@', fans_out) + .replace('@@ROUTE@@', route) + .replace('@@REGISTRY@@', registry) + .replace('@@SIBLING_SOURCE@@', sibling_source) + .replace('@@STRUCTURE@@', checks)) + + +TEMPLATE = r''' +#![allow(dead_code, unused_variables, unused_mut, unused_imports)] +use std::cell::{Cell, RefCell}; +use std::collections::HashSet; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; + +const EIO: i32 = -5; +type Result = std::result::Result; + +@@HZ@@ +@@GATE@@ + +thread_local! { static NOW: Cell = Cell::new(1_000_000_000); } +fn now_ns() -> u64 { NOW.with(|now| now.get()) } + +/// Ticks of an execution record lasting `us` microseconds. +fn ticks(us: u64) -> u64 { us * COMMAND_TIMESTAMP_HZ / 1_000_000 } + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct ComputeCapacity(u32); + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +@@SIBLING_SOURCE@@ + +struct Completion { sources: Option<()> } +impl Completion { fn sources(&self) -> Option<&()> { self.sources.as_ref() } } +struct Order { wait_through: [Option; 2] } +struct Packet { order: Order, completion: Completion } +fn packet(sources: bool, through: Option) -> Packet { + Packet { order: Order { wait_through: [None, through] }, + completion: Completion { sources: sources.then_some(()) } } +} + +struct Context { vm_id: u32, compute_ordinal: AtomicU32 } +impl Context { + fn new(vm_id: u32) -> Arc { Arc::new(Self { vm_id, compute_ordinal: AtomicU32::new(0) }) } + fn vm(&self) -> u32 { self.vm_id } + @@NEXT_ID@@ +} + +mod compute { + /// The routing-relevant state of one physical compute channel. + pub struct Queue { + pub qid: u8, pub owner: Option, pub channel_index: u8, pub active: usize, + pub replays: usize, pub configuring: bool, pub last_published: u64, pub heavy_run: u8, + pub reusable: bool, pub pool_vm: u32, pub pool_cap: u32, + } + impl Queue { + pub fn active_len(&self) -> usize { self.active } + pub fn configuring(&self) -> bool { self.configuring } + pub fn last_published(&self) -> u64 { self.last_published } + @@QUEUE_SUSTAINED@@ + } +} + +/// The hint fields of the production cell; the mutex-held queue is passed in. +struct ComputeCell { + active_len: AtomicU32, configuring: AtomicBool, last_published: AtomicU64, sustained: AtomicBool, +} +impl ComputeCell { + fn new() -> Arc { + Arc::new(Self { active_len: AtomicU32::new(0), configuring: AtomicBool::new(false), + last_published: AtomicU64::new(0), sustained: AtomicBool::new(false) }) + } + @@SYNC_STATS@@ + @@LOAD_HINT@@ + @@CELL_SUSTAINED@@ +} + +struct Backend { compute_channels: u8, sibling_backoff_until: AtomicU64, gate_asked: Cell } +impl Backend { + @@FANS_OUT@@ + /// compute_direct()'s lock-free channel selection: `None` sends the packet to the + /// device-mutex path, otherwise `(target channel, may add a sibling)`. + fn route(&self, packet: &Packet, cells: &[Option>; 3], cached_count: usize) + -> Option<(usize, bool)> + { +@@ROUTE@@ + Some((target_idx, can_add_sibling)) + } +} + +impl compute::Queue { + fn qid(&self) -> u8 { self.qid } + fn owner(&self) -> Option { self.owner } + fn channel_index(&self) -> u8 { self.channel_index } + fn is_primary(&self) -> bool { self.channel_index == 0 } + fn has_replays(&self) -> bool { self.replays != 0 } + fn reusable(&self) -> bool { self.reusable } + fn needs_fresh_backing(&self) -> bool { false } + fn pool_vacant(&self) -> bool { false } + fn rearm_open(&self, _: u64) -> bool { true } + fn released_at(&self) -> u64 { 0 } + fn vacancy_pending(&self) -> bool { false } + fn pool_serves(&self, vm: u32) -> bool { self.pool_vm == vm } + fn pool_fits(&self, required: ComputeCapacity) -> bool { self.pool_cap >= required.0 } + fn has_ring(&self) -> bool { true } + fn context(&self) -> Option<&Arc> { None } +} + +struct Slot(RefCell); +impl Slot { fn as_deref(&self) -> Option> { Some(self.0.borrow()) } } +struct Entry { queue: Slot } +struct Qids { fit: bool } +impl Qids { fn compute_fits(&self, _: usize) -> bool { self.fit } } +struct Admission; +impl Admission { + fn queues(&self) -> u32 { 1 } + fn render_demand(&self, extra: usize) -> usize { 1 + extra } +} +struct Teardown; +impl Teardown { fn releasing(&self, _: &Arc) -> bool { false } } +struct Registry { compute: Vec>, qids: Qids, admission: Admission, teardown: Teardown } +impl Registry { +@@REGISTRY@@ +} + +const OWNER: u64 = 7; + +fn channel(qid: u8, channel_index: u8, active: usize, heavy_run: u8) -> compute::Queue { + compute::Queue { qid, owner: Some(OWNER), channel_index, active, replays: 0, configuring: false, + last_published: u64::from(qid), heavy_run, reusable: false, pool_vm: 70, pool_cap: 16 } +} + +fn registry(queues: Vec) -> Registry { + Registry { compute: queues.into_iter().map(|queue| Some(Entry { queue: Slot(RefCell::new(queue)) })).collect(), + qids: Qids { fit: true }, admission: Admission, teardown: Teardown } +} + +/// The cells compute_direct() caches, each hint mirrored from its queue by the production +/// sync_stats(), as the queue guard does when it drops. +fn cells(queues: &[compute::Queue]) -> [Option>; 3] { + let mut cells = [None, None, None]; + for queue in queues { + let cell = ComputeCell::new(); + cell.sync_stats(Some(queue)); + cells[usize::from(queue.channel_index)] = Some(cell); + } + cells +} + +fn backend() -> Backend { + Backend { compute_channels: 3, sibling_backoff_until: AtomicU64::new(0), gate_asked: Cell::new(0) } +} + +fn run_of(records_us: &[u64]) -> u8 { + records_us.iter().fold(0, |run, &us| heavy_run(run, 5_000, 5_000 + ticks(us))) +} + +fn main() { +@@STRUCTURE@@ + + // The threshold, from the record's 24 MHz command timestamps. + assert_eq!(SIBLING_EXECUTION_TICKS, ticks(SIBLING_EXECUTION_NS / 1_000)); + assert_eq!(SIBLING_EXECUTION_TICKS, 2_400, "100 us at 24 MHz"); + + // (b) Short kicks never build a run; one long kick among short ones does not open the + // gate; a short kick closes it at once. + assert_eq!(run_of(&[3; 64]), 0, "a stream of 3 us kicks has no heavy run"); + assert_eq!(run_of(&[99]), 0, "just under the threshold is short"); + assert!(!sustained(run_of(&[3, 3, 900, 3, 3])), "one long kick does not fan a stream out"); + assert!(!sustained(run_of(&[270])), "one heavy kick is not yet sustained"); + assert!(sustained(run_of(&[100, 270])), "two consecutive heavy kicks are"); + assert!(sustained(run_of(&[490, 490, 490]))); + assert!(!sustained(run_of(&[490, 490, 490, 3])), "a short kick closes the gate"); + assert_eq!(run_of(&[490; 300]), u8::MAX, "the run saturates"); + assert_eq!(heavy_run(5, 9_000, 1_000), 0, "a backwards record measures nothing"); + + let b = backend(); + // (a, b) The gate: only independent commands without sources, and the primary's state is + // asked last so a command that cannot fan out never looks at (or locks) the primary. + let ask = |answer: bool| { b.gate_asked.set(b.gate_asked.get() + 1); answer }; + assert!(b.fans_out(&packet(false, None), || ask(true))); + assert!(!b.fans_out(&packet(false, None), || ask(false)), "a light primary keeps its kicks"); + let asked = b.gate_asked.get(); + assert!(!b.fans_out(&packet(true, None), || ask(true)), "sources never fan out"); + assert!(!b.fans_out(&packet(false, Some(4)), || ask(true)), "nor in-queue barriers"); + assert_eq!(b.gate_asked.get(), asked, "the primary is not asked for them"); + let single = Backend { compute_channels: 1, ..backend() }; + assert!(!single.fans_out(&packet(false, None), || ask(true)), "one channel per owner"); + + // (c) The lock-free mirror of the gate. + let heavy_primary = channel(10, 0, 1, 2); + let cell = ComputeCell::new(); + cell.sync_stats(Some(&heavy_primary)); + assert!(cell.sustained()); + assert_eq!(cell.load_hint(), (false, 1, 10)); + cell.sync_stats(None); + assert!(!cell.sustained(), "an emptied cell is not sustained"); + + let light = [channel(10, 0, 4, 0), channel(11, 1, 0, 0), channel(12, 2, 0, 0)]; + let heavy = [channel(10, 0, 2, 2), channel(11, 1, 0, 0), channel(12, 2, 0, 0)]; + let heavy_one = [channel(10, 0, 1, 2), channel(11, 1, 0, 0), channel(12, 2, 0, 0)]; + let heavy_busy = [channel(10, 0, 1, 2), channel(11, 1, 1, 0)]; + let indep = packet(false, None); + let sourced = packet(true, None); + + // (b) Short kicks stay on the busy primary ring even with idle siblings bound, and a lone + // busy primary does not detour to the device-mutex path to add a sibling. + assert_eq!(b.route(&indep, &cells(&light), 3), Some((0, false)), "short kicks stream down channel 0"); + assert_eq!(b.route(&indep, &cells(&light[..1]), 1), Some((0, false)), + "a busy light primary keeps publishing directly"); + // (a) A command with sources takes the primary even when it is busy and heavy. + assert_eq!(b.route(&sourced, &cells(&heavy), 3), Some((0, false)), "sources stay on channel 0"); + assert_eq!(b.route(&sourced, &cells(&heavy[..1]), 1), Some((0, false)), + "sources never ask for a sibling"); + // (c) Sustained heavy work fans out onto the least-loaded idle sibling, asks the + // device-mutex path for a sibling when every bound channel is busy, and a lone heavy + // busy primary may add one. + assert_eq!(b.route(&indep, &cells(&heavy), 3), Some((1, false)), "heavy kicks take an idle sibling"); + // (c) ... once two are in flight: behind a single kick the next one queues on channel 0. + assert_eq!(b.route(&indep, &cells(&heavy_one), 3), Some((0, false)), + "a kick queues behind a single kick in flight"); + assert_eq!(b.route(&indep, &cells(&[channel(10, 0, 1, 2), channel(11, 1, 0, 0)]), 2).map(|(idx, _)| idx), + Some(0), "also with an idle sibling bound"); + assert_eq!(b.route(&indep, &cells(&heavy_busy), 2), None, "all busy: bring up the third channel"); + assert_eq!(b.route(&indep, &cells(&heavy[..1]), 1), Some((0, true))); + b.sibling_backoff_until.store(now_ns() + 1, Ordering::Relaxed); + assert_eq!(b.route(&indep, &cells(&heavy_busy), 2), Some((0, false)), + "after a headroom miss the bound channels are used"); + b.sibling_backoff_until.store(0, Ordering::Relaxed); + let idle_heavy = [channel(10, 0, 0, 2), channel(11, 1, 1, 0)]; + assert_eq!(b.route(&indep, &cells(&idle_heavy), 2), Some((0, true)), + "an idle primary comes first; only a busy lone channel detours for a sibling"); + + // (c) Fanned-out kicks get one monotonic sequence of ordinals and object ids from their + // shared context, whichever channel publishes them. + let context = Context::new(70); + let mut seen = HashSet::new(); + let mut last = 0; + for kick in 0..64u32 { + let (ordinal, object_ids) = context.next_compute_identity(); + assert_eq!(ordinal, kick + 1); + assert!(ordinal > last && seen.insert(object_ids as u32)); + assert_eq!((object_ids >> 32) as u32, last.max(1), "each id names its predecessor"); + last = ordinal; + } + + // Device-mutex selection and sibling admission follow the same gate. + let req = ComputeCapacity(16); + let ctx = Context::new(70); + // (b) A light primary brings up no sibling though every channel is busy and QIDs are free. + let reg = registry(vec![channel(10, 0, 3, 0), channel(11, 1, 1, 0)]); + assert!(!reg.wants_compute_sibling(OWNER, &ctx, 3, req), "a light primary wants no sibling"); + // (c) A sustained heavy primary does. + let reg = registry(vec![channel(10, 0, 1, 2), channel(11, 1, 1, 0)]); + assert!(reg.wants_compute_sibling(OWNER, &ctx, 3, req)); + // ... only while every channel is busy. + let reg = registry(vec![channel(10, 0, 1, 2), channel(11, 1, 0, 0)]); + assert!(!reg.wants_compute_sibling(OWNER, &ctx, 3, req)); + // ... and two kicks are in flight: one kick behind which the next queues brings up none. + let reg = registry(vec![channel(10, 0, 1, 2)]); + assert!(!reg.wants_compute_sibling(OWNER, &ctx, 3, req), "one kick in flight wants no sibling"); + let reg = registry(vec![channel(10, 0, 2, 2)]); + assert!(reg.wants_compute_sibling(OWNER, &ctx, 3, req), "two kicks in flight do"); + + let reg = registry(light.into_iter().collect()); + assert_eq!(reg.select_compute_channel(OWNER, &indep), Some(10), "short kicks take the primary"); + let reg = registry(heavy.into_iter().collect()); + assert_eq!(reg.select_compute_channel(OWNER, &indep), Some(11), "heavy kicks spread"); + let reg = registry(heavy_one.into_iter().collect()); + assert_eq!(reg.select_compute_channel(OWNER, &indep), Some(10), + "behind a single kick in flight the next one queues on the primary"); + let reg = registry(vec![channel(10, 0, 2, 2), channel(11, 1, 0, 0), channel(12, 2, 0, 0)]); + assert_eq!(reg.select_compute_channel(OWNER, &sourced), Some(10), "sources take the primary"); + assert_eq!(reg.select_compute_channel(OWNER, &packet(true, Some(3))), Some(10), + "even when a dependency could stay on another channel"); + // A dependent command still follows the sole active channel (no cross-channel barrier). + let reg = registry(vec![channel(10, 0, 0, 2), channel(11, 1, 2, 0)]); + assert_eq!(reg.select_compute_channel(OWNER, &packet(false, Some(3))), Some(11)); + + // The threshold itself. + assert!(!overlaps(0) && !overlaps(1) && overlaps(2) && overlaps(3)); + + println!("PASS g17-m5-sibling-gate: sources, short kicks and a kick behind a single one stay on the primary ring, sustained heavy kicks fan out"); +} +''' + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + source = build(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-sibling-gate-') as tmp: + path = Path(tmp) / 'gate.rs' + binary = path.with_suffix('') + path.write_text(source) + built = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '-O', str(path), + '-o', str(binary)], capture_output=True, text=True) + if built.returncode: + sys.stderr.write(built.stderr) + return built.returncode + run = subprocess.run([str(binary)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-m5-sibling-rearm-tests.py b/tools/asahi/g17-m5-sibling-rearm-tests.py new file mode 100755 index 00000000000000..f690f4473cd179 --- /dev/null +++ b/tools/asahi/g17-m5-sibling-rearm-tests.py @@ -0,0 +1,649 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: M5 sibling compute channels come from vacant and other-VM idle queues too. + +Once earlier clients have taken compute QIDs up to the fresh-QID ceiling +(`compute_fits()` false), every idle compute queue is either vacant (its pool +given back after the idle expiry) or still holds the pool of a VM that is gone. +A sibling that could only bind a populated pool of its own VM, or a fresh QID, +then never came up again until the GPU slept. This test compiles the production +code that decides and performs the sibling's acquisition against host stubs: + +- the queue predicates of drivers/gpu/drm/asahi/g17/queue/compute.rs that say + which queue may change owner (`reusable`, `can_rearm`, `rearm_open`, + `shareable`, `recycled_pending`, `vacancy_pending`, `vacate_candidate`) and + the queue's pool give-back and re-arm transitions (`require_fresh_backing`, + `vacate`, `observe_vacancy`, `rearm`, `bind_sibling`); +- the registry's `sibling_source()`, `has_compute_sibling_headroom()`, + `wants_compute_sibling()`, `bind_reusable_sibling()`, `give_back_foreign()`, + `reserve_rearm()`, `rearm_compute()`, `bind_rearmed()` and the pool pass + `vacate_idle_pools()` from drivers/gpu/drm/asahi/g17/runtime.rs. + +It checks that with no fresh QID a new client still gets every sibling it +wants, first from vacant queues (re-armed with fresh backing, bound as sibling +channels) and then from other VMs' idle queues (given back one at a time, +vacated by the pool pass, re-armed), across clients that come and go; that a +queue with an owner or work, an open client's idle channel, a queue another +client is re-arming, one whose scheduler release is in flight and one whose +pool release is in flight are never taken; that a fresh QID comes before +another VM's pool is given back; and, structurally, that +`try_add_compute_sibling()` takes these sources through the primary's re-arm +path, lets an owner waiting for its first channel go first and that the primary +path gives back other VMs' queues through the same helper. + +Each mutation restores the old rule or drops one part of the new one and must +fail an assertion of the compiled harness. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +# The headroom rule before this change: a populated same-VM pool or a fresh QID only. +OLD_SOURCE = '''fn sibling_source( + &self, + owner: u64, + context: &Arc, + required: super::freelist::ComputeCapacity, + ) -> Option { + let teardown = &self.teardown; + let vm = context.vm(); + let warm = self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| { + queue.reusable() + && !queue.needs_fresh_backing() + && !queue.pool_vacant() + && queue.pool_serves(vm) + && queue.pool_fits(required) + && queue.has_ring() + && !queue.context().is_some_and(|bound| teardown.releasing(bound)) + }) + .map(|queue| (queue.released_at(), queue.qid())) + .min_by_key(|(key, _)| *key) + .map(|(_, qid)| SiblingSource::Warm(qid)); + warm.or_else(|| { + self.qids + .compute_fits(self.admission.queues() as usize) + .then_some(SiblingSource::Fresh) + }) + }''' + +# name -> [(file, old, new)]: each must apply exactly once. +MUTATIONS = { + # The old rule: no vacant and no other-VM queue is ever a sibling source. + 'old-headroom': [('source', None, OLD_SOURCE)], + 'no-vacant-sibling': [('runtime', ' if let Some((_, qid)) = vacant {\n', ' if let Some((_, qid)) = vacant.filter(|_| false) {\n')], + 'no-foreign-sibling': [('runtime', ' foreign.map(|(_, qid)| SiblingSource::Foreign(qid))\n', ' None\n')], + # Never steal: an open client's idle channel, a busy queue, a queue another client re-arms, + # a queue whose scheduler release is in flight. + 'steal-shareable': [('runtime', ' .filter(|queue| queue.reusable())\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {', + ' .filter(|queue| queue.reusable() || queue.shareable())\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {')], + 'steal-unowned': [('runtime', ' .filter(|queue| queue.reusable())\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {', + ' .filter(|queue| queue.owner() != Some(owner))\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {')], + 'ignore-rearm-reservation': [('runtime', ' if !queue.rearm_open(owner) {\n continue;\n' + ' }\n &mut vacant\n', ' &mut vacant\n')], + 'ignore-releasing': [('runtime', ' .filter(|queue| queue.reusable())\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {', + ' .filter(|queue| queue.reusable())\n' + ' {\n let best = if queue.pool_vacant() {')], + # Give back several other-VM pools at once. + 'parallel-give-back': [('runtime', ' .any(|queue| queue.vacancy_pending())\n {\n return None;\n }\n' + ' foreign.map(', ' .any(|queue| queue.vacancy_pending() && false)\n {\n' + ' return None;\n }\n foreign.map(')], + # Give another VM's pool back while a fresh QID fits. + 'foreign-before-fresh': [('runtime', ' if self.qids.compute_fits(self.admission.render_demand(0)) {\n' + ' return Some(SiblingSource::Fresh);\n }\n // A pool release', + ' if foreign.is_none() && self.qids.compute_fits(self.admission.render_demand(0)) {\n' + ' return Some(SiblingSource::Fresh);\n }\n // A pool release')], + # A re-armed sibling is bound as the owner's primary. + 'rearm-binds-primary': [('runtime', ' if channel_index == 0 {\n queue.bind_owner(owner, context.clone())', + ' if true {\n queue.bind_owner(owner, context.clone())')], + # Structural: try_add_compute_sibling() without the re-arm, the waiter rule, the shared give-back. + 'try-add-ignores-waiters': [('runtime', ' || self.shared.channels.has_waiters()\n', '')], + 'try-add-skips-rearm': [('runtime', ' firmware.queues.reserve_rearm(qid, self.owner)?;\n Err(qid)\n', + ' return Ok(false);\n')], + 'rearm-any-index': [('runtime', ' && (channel_index == 0\n || firmware.queues.next_sibling_index(self.owner, self.compute_channels)\n' + ' == Some(channel_index));\n', ';\n')], + 'primary-own-give-back': [('runtime', ' if let Some(qid) = foreign {\n self.give_back_foreign(qid)?;\n', + ' if let Some(qid) = foreign {\n self.compute_queue_mut(qid).ok_or(EIO)?.require_fresh_backing();\n')], +} + + +def build(mutation=None): + files = { + 'runtime': (G17 / 'runtime.rs').read_text(), + 'queue': (G17 / 'queue/compute.rs').read_text(), + 'pairs': (G17 / 'pairs.rs').read_text(), + 'freelist': (G17 / 'freelist.rs').read_text(), + } + old_source = False + for name, old, new in MUTATIONS.get(mutation, []): + if name == 'source': + old_source = True + continue + assert files[name].count(old) == 1, (mutation, old) + files[name] = files[name].replace(old, new) + runtime, queue, pairs, freelist = files['runtime'], files['queue'], files['pairs'], files['freelist'] + source_fn = item(runtime, 'fn sibling_source(') + if old_source: + runtime = runtime.replace(source_fn, OLD_SOURCE) + source_fn = OLD_SOURCE + + queue_fns = '\n'.join(item(queue, signature) for signature in [ + 'pub(crate) fn reusable(&self)', 'pub(crate) fn can_rearm(&self)', 'pub(crate) fn rearm_open(', + 'pub(crate) fn reserve_rearm(', 'pub(crate) fn release_rearm(', 'pub(crate) fn require_fresh_backing(', + 'pub(crate) fn needs_fresh_backing(', 'pub(crate) fn pool_vacant(', 'pub(crate) fn pool_serves(', + 'pub(crate) fn pool_fits(', 'pub(crate) fn recycled_pending(', 'pub(crate) fn vacancy_pending(', + 'pub(crate) fn pool_release_pending(', 'pub(crate) fn vacate_candidate(', 'pub(crate) fn released_at(', + 'pub(crate) fn has_ring(', 'pub(crate) fn rearm(\n', 'pub(crate) fn vacate(&mut self', + 'pub(crate) fn observe_vacancy(', 'pub(crate) fn shareable(', 'pub(crate) fn owner(&self)', + 'pub(crate) fn channel_index(&self)', 'pub(crate) fn is_primary(&self)', 'pub(crate) fn active_len(&self)', + 'pub(crate) fn has_replays(&self)', 'pub(crate) fn configuring(&self)', 'pub(crate) fn context(&self)', + 'pub(crate) fn bind_sibling(', 'pub(crate) fn bind_owner(&mut self', + ]).replace('pub(crate) ', 'pub ').replace('mmu::Vm', 'Vm') \ + .replace('crate::g17::freelist::Pages', 'Pages').replace('crate::g17::initdata::InitData', 'InitData') \ + .replace('crate::g17::now_ns()', 'now_ns()').replace('crate::g17::freelist::control_consumed', 'control_consumed') + pool_fns = '\n'.join(item(freelist, signature) for signature in [ + 'pub(crate) fn populated(&self)', 'pub(crate) fn serves(&self', 'pub(crate) fn take_pages(', + ]).replace('pub(crate) ', 'pub ').replace('mmu::Vm', 'Vm') + registry_fns = '\n'.join(item(runtime, signature) for signature in [ + 'fn compute_channels_of(', 'fn next_sibling_index(', 'fn has_compute_sibling_headroom(', + 'fn wants_compute_sibling(', 'fn bind_reusable_sibling(', 'fn compute_queue_mut(', + 'fn give_back_foreign(', 'fn reserve_rearm(&mut self, qid', 'pub(super) fn release_rearm(', + 'pub(super) fn rearm_compute(', 'pub(super) fn bind_rearmed(', 'pub(super) fn vacate_idle_pools(', + ] if True) + '\n' + source_fn + registry_fns = registry_fns.replace('pub(super) ', '').replace('super::freelist::ComputeCapacity', 'ComputeCapacity') \ + .replace('super::pairs::', '').replace('super::initdata::InitData', 'InitData') \ + .replace('crate::g17::freelist::Pages', 'Pages').replace('compute::DescriptorRing', 'DescriptorRing') \ + .replace('super::freelist::PoolDescriptor', 'PoolDescriptor').replace('compute::Vacated', 'Vacated') + enum = item(runtime, 'pub(super) enum SiblingSource').replace('pub(super) ', '') + pairs_fns = '\n'.join([ + 'const SIBLING_MIN_IN_FLIGHT: usize = ' + + pairs.split('pub(crate) const SIBLING_MIN_IN_FLIGHT: usize = ', 1)[1].split(';', 1)[0] + ';', + item(pairs, 'pub(crate) fn overlaps(').replace('pub(crate) ', ''), + ]) + + try_add = item(runtime, 'fn try_add_compute_sibling(') + rearm_vacant = item(runtime, 'fn rearm_vacant(') + rebind = item(runtime, 'pub(super) fn rebind_compute(') + build_compute = item(runtime, 'fn build_compute(') + structure = { + 'try_add takes every source through its own path': ordered_ok( + try_add, '|| self.shared.channels.has_waiters()', 'wants_compute_sibling(', + 'firmware.queues.sibling_source(self.owner, &self.context, required)', + 'Some(SiblingSource::Warm(_)) =>', 'bind_reusable_sibling(', + 'Some(SiblingSource::Foreign(qid)) =>', 'firmware.queues.give_back_foreign(qid)?;', + 'drop(state);', 'self.shared.queue_events();', 'return Ok(false);', + 'Some(SiblingSource::Vacant(qid)) =>', 'firmware.queues.reserve_rearm(qid, self.owner)?;', 'Err(qid)', + 'Some(SiblingSource::Fresh) =>', 'reserve_compute_channel(self.owner, self.compute_channels)', + 'Err(qid) => {', 'self.rearm_vacant(\n qid,\n channel_index,\n required,', + 'if !bound {', 'firmware.queues.release_rearm(qid, self.owner);', 'admission.check()?;', + 'return Ok(bound);', 'compute::PoolBacking::new('), + 'a re-arm binds the channel it was reserved for, through the primary path': ordered_ok( + rearm_vacant, 'crate::g17::freelist::Pages::for_compute(', 'compute::DescriptorRing::new(', + 'let mut state = self.shared.state.lock();', 'if !lease.is_current()', 'self.admission_open()', + 'queue.qid() == qid && queue.can_rearm() && queue.rearm_open(self.owner)', + '&& (channel_index == 0\n || firmware.queues.next_sibling_index(self.owner, self.compute_channels)\n' + ' == Some(channel_index));', + 'firmware.queues.rearm_compute(qid, pages, ring)', 'firmware.init.install_compute_pool(descriptor)?;', + 'firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)?;'), + 'the primary re-arms channel 0': 'self.rearm_vacant(qid, 0, required,' in build_compute, + 'the primary gives back other VMs\' queues through the same helper': ordered_ok( + rebind, '.filter(|queue| queue.reusable() && !queue.pool_vacant() && !queue.pool_serves(vm))', + 'if let Some(qid) = foreign {', 'self.give_back_foreign(qid)?;', 'return Err(ENOSPC);'), + } + checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' for name, ok in structure.items()) + return (TEMPLATE.replace('@@ENUM@@', enum).replace('@@PAIRS@@', pairs_fns).replace('@@QUEUE@@', queue_fns) + .replace('@@POOL@@', pool_fns).replace('@@REGISTRY@@', registry_fns).replace('@@STRUCTURE@@', checks)) + + +TEMPLATE = r''' +#![allow(dead_code, unused_variables, unused_mut, unused_imports, unreachable_code, unused_assignments)] +use std::cell::RefCell; +use std::sync::Arc; +use std::sync::atomic::{fence, AtomicU32, Ordering}; + +const EIO: i32 = -5; +const EAGAIN: i32 = -11; +const EBUSY: i32 = -16; +const EPERM: i32 = -1; +const ENOSPC: i32 = -28; +type Result = std::result::Result; +const GFP_KERNEL: () = (); +struct KVec(Vec); +impl KVec { + fn with_capacity(n: usize, _: ()) -> Result { Ok(Self(Vec::with_capacity(n))) } + fn push(&mut self, value: T, _: ()) -> Result { self.0.push(value); Ok(()) } +} +impl std::ops::Deref for KVec { type Target = Vec; fn deref(&self) -> &Vec { &self.0 } } +impl std::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } + +fn now_ns() -> u64 { 5_000_000_000 } + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct ComputeCapacity(u32); + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +@@ENUM@@ + +@@PAIRS@@ + +pub struct Vm(u32); +impl Vm { pub fn id(&self) -> u32 { self.0 } } +pub struct Context { id: u32, vm: Vm, current: bool } +impl Context { + fn new(id: u32, vm: u32) -> Arc { Arc::new(Self { id, vm: Vm(vm), current: true }) } + fn vm(&self) -> &Vm { &self.vm } + fn is_current(&self) -> bool { self.current } +} + +#[derive(Debug)] +pub struct Pages(u32); +pub struct DescriptorRing; +#[derive(Debug, PartialEq)] +pub struct PoolDescriptor(u32); +pub struct InitData { control_cursor: std::cell::Cell } +pub struct KernelMapping; +pub struct Vacated { _alias: Option, _pages: Option, _descriptors: Option, _ring: Option } +pub struct FreeListRelease; +enum ControlRecord { FreeListRelease(FreeListRelease) } +struct Rings; +impl Rings { + fn publish_control(init: &InitData, _: &ControlRecord) -> Result { + let cursor = init.control_cursor.get() + 1; + init.control_cursor.set(cursor); + Ok(cursor) + } +} +/// The firmware consumed every control record up to `consumer`. +fn control_consumed(consumer: u32, _producer: u32, cursor: u32) -> Result { Ok(consumer >= cursor) } + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum PoolPhase { Populated, ReleaseSent(u32), Vacant } +pub struct Fifo { len: usize } +pub struct SourceHint; +impl SourceHint { fn has_readers(&self, count: &AtomicU32) -> bool { count.load(Ordering::Acquire) != 0 } } +pub struct Graph { ring: Option, m5: bool } +impl Graph { + fn rearm_ring(&mut self, ring: DescriptorRing) -> Option { self.ring.replace(ring) } + fn vacate_ring(&mut self) -> Option { self.ring.take() } +} +pub struct Binding { context: Arc, pool_alias: Option, descriptors: Option } +pub struct Pool { id: u16, client_vm: u32, pages: Option, cap: u32 } +impl Pool { +@@POOL@@ + fn fits_capacity(&self, required: ComputeCapacity) -> bool { self.pages.is_some() && self.cap >= required.0 } + fn rearm(&mut self, pages: Pages) -> Result { if self.pages.is_some() { return Err(EBUSY); } self.pages = Some(pages); Ok(()) } + fn descriptor(&self) -> Result { Ok(PoolDescriptor(u32::from(self.id))) } + fn release_record(&self, _generation: u64) -> FreeListRelease { FreeListRelease } +} + +/// The owner-change state of one physical compute queue, with the production field names. +pub struct Queue { + qid: u8, growing: bool, channel_error: bool, installed: bool, configuration: Option<()>, + pool_phase: PoolPhase, needs_fresh_backing: bool, exit: Option<()>, owner: Option, + released: bool, retirement_ready: bool, quarantined: bool, active: Fifo, replays: Fifo, + previous: Option<()>, source_hint: SourceHint, source_readers: AtomicU32, rearm_for: Option, + pool: Pool, graph: Graph, binding: Option, release_sent_ns: Option, + free_list_generation: u64, released_at: u64, claims: u32, awaiting_witness: bool, + channel_index: u8, sustained: bool, +} +impl Queue { +@@QUEUE@@ + fn qid(&self) -> u8 { self.qid } + fn sustained(&self) -> bool { self.sustained } + /// The production entry check of bind_owner_channel(); the views of the new VM are not modelled. + fn bind_owner_channel(&mut self, owner: u64, context: Arc, channel_index: u8) -> Result { + if !self.reusable() { + return Err(EBUSY); + } + if !self.pool.serves(context.vm()) { + return Err(EPERM); + } + self.pool.client_vm = context.vm().id(); + self.binding = Some(Binding { context, pool_alias: None, descriptors: None }); + self.owner = Some(owner); + self.channel_index = channel_index; + self.rearm_for = None; + self.released = false; + self.retirement_ready = false; + Ok(()) + } +} + +type QueueGuard<'a> = std::cell::RefMut<'a, Queue>; +struct Slot(RefCell); +impl Slot { + fn as_deref(&self) -> Option> { Some(self.0.borrow()) } + fn as_deref_mut(&mut self) -> Option> { Some(self.0.borrow_mut()) } +} +struct Entry { queue: Slot } +struct Qids { fit: bool } +impl Qids { fn compute_fits(&self, _: usize) -> bool { self.fit } } +struct Admission; +impl Admission { + fn queues(&self) -> u32 { 4 } + fn render_demand(&self, extra: usize) -> usize { 4 + extra } +} +struct Teardown { releasing: Vec } +impl Teardown { fn releasing(&self, context: &Arc) -> bool { self.releasing.contains(&context.id) } } +struct Registry { compute: Vec>, qids: Qids, admission: Admission, teardown: Teardown } +impl Registry { + const POOL_RETRY_NS: u64 = 100_000_000; +@@REGISTRY@@ + fn queue(&self, qid: u8) -> std::cell::Ref<'_, Queue> { + self.compute.iter().flatten().map(|entry| entry.queue.0.borrow()).find(|queue| queue.qid == qid).unwrap() + } + fn queue_mut(&self, qid: u8) -> std::cell::RefMut<'_, Queue> { + self.compute.iter().flatten().map(|entry| entry.queue.0.borrow_mut()).find(|queue| queue.qid == qid).unwrap() + } + /// An event pass: the production pool pass gives back what must go, then the firmware + /// consumes the control ring and the release observation leaves those queues vacant. + fn pool_pass(&mut self, init: &InitData) { + vacate_idle_pools_pass(self, init); + let consumer = init.control_cursor.get(); + for entry in self.compute.iter_mut().flatten() { + let mut queue = entry.queue.0.borrow_mut(); + let _ = queue.observe_vacancy(consumer, consumer).unwrap(); + } + } + fn push(&mut self, queue: Queue) { self.compute.push(Some(Entry { queue: Slot(RefCell::new(queue)) })); } +} +fn vacate_idle_pools_pass(registry: &mut Registry, init: &InitData) { + // Idle pools stay warm (cap 3, no expiry): only queues given back are released. + registry.vacate_idle_pools(init, 3, now_ns(), u64::MAX).unwrap(); +} + +/// An installed queue owned by `owner` (channel 0) with `active` kicks in flight. +fn bound(qid: u8, owner: u64, context: &Arc, active: usize) -> Queue { + Queue { + qid, growing: false, channel_error: false, installed: true, configuration: None, + pool_phase: PoolPhase::Populated, needs_fresh_backing: false, exit: None, owner: Some(owner), + released: false, retirement_ready: true, quarantined: false, active: Fifo { len: active }, + replays: Fifo { len: 0 }, previous: None, source_hint: SourceHint, source_readers: AtomicU32::new(0), + rearm_for: None, pool: Pool { id: u16::from(qid), client_vm: context.vm().id(), pages: Some(Pages(1)), cap: 16 }, + graph: Graph { ring: Some(DescriptorRing), m5: true }, + binding: Some(Binding { context: context.clone(), pool_alias: None, descriptors: None }), + release_sent_ns: None, free_list_generation: 1, released_at: 0, claims: 0, awaiting_witness: false, + channel_index: 0, sustained: true, + } +} +/// An idle queue whose owner released it at `released_at`; its pool still serves `vm`. +fn released(qid: u8, vm: u32, released_at: u64) -> Queue { + let mut queue = bound(qid, 0, &Context::new(1000 + u32::from(qid), vm), 0); + queue.owner = None; + queue.released = true; + queue.released_at = released_at; + queue.sustained = false; + queue +} +/// The same, after its pool was given back (the idle expiry): vacant, without a ring. +fn vacant(qid: u8, released_at: u64) -> Queue { + let mut queue = released(qid, 0, released_at); + queue.pool_phase = PoolPhase::Vacant; + queue.pool.pages = None; + queue.pool.client_vm = 0; + queue.graph.ring = None; + queue +} + +/// try_add_compute_sibling()'s locked decision and the off-lock re-arm, through the production +/// registry calls in the order the backend makes them. Returns whether a sibling was bound. +fn add_sibling(reg: &mut Registry, init: &InitData, owner: u64, context: &Arc) -> Result { + let req = ComputeCapacity(16); + if !reg.wants_compute_sibling(owner, context, 3, req) { + return Ok(false); + } + let Some(channel_index) = reg.next_sibling_index(owner, 3) else { return Ok(false) }; + match reg.sibling_source(owner, context, req) { + None => Ok(false), + Some(SiblingSource::Warm(_)) => Ok(reg.bind_reusable_sibling(owner, context, 3, req)? == Some(true)), + Some(SiblingSource::Foreign(qid)) => { reg.give_back_foreign(qid)?; Ok(false) } + Some(SiblingSource::Fresh) => Ok(false), + Some(SiblingSource::Vacant(qid)) => { + reg.reserve_rearm(qid, owner)?; + // Off the device mutex: fresh pages and a descriptor ring; then, locked again, the + // production rearm_vacant() checks and steps. + let ready = { + let queue = reg.queue(qid); + queue.can_rearm() && queue.rearm_open(owner) + } && reg.next_sibling_index(owner, 3) == Some(channel_index); + if !ready { + reg.release_rearm(qid, owner); + return Ok(false); + } + let (descriptor, _vacated) = reg.rearm_compute(qid, Pages(2), DescriptorRing)?; + assert_eq!(descriptor, PoolDescriptor(u32::from(qid)), "the re-armed queue's row is written"); + reg.bind_rearmed(qid, owner, context, channel_index)?; + Ok(true) + } + } +} + +fn registry() -> Registry { + Registry { compute: Vec::new(), qids: Qids { fit: false }, admission: Admission, teardown: Teardown { releasing: Vec::new() } } +} + +const B: u64 = 2; +const C: u64 = 3; +const D: u64 = 4; +const OTHER: u64 = 9; + +fn main() { +@@STRUCTURE@@ + + let init = InitData { control_cursor: std::cell::Cell::new(0) }; + let req = ComputeCapacity(16); + let b = Context::new(20, 200); + let c = Context::new(30, 300); + let d = Context::new(40, 400); + let mut reg = registry(); + // B's primary runs sustained heavy work with two kicks in flight. No fresh QID fits. + reg.push(bound(10, B, &b, 2)); + // An exited client's queues: one given back at the idle expiry (vacant), one still holding + // the exited VM's pool. + reg.push(vacant(11, 5)); + reg.push(released(12, 999, 6)); + // Never to be taken: C's busy queue, D's idle channel (D is open), a vacant queue another + // client is re-arming and a queue whose scheduler release is in flight. + reg.push(bound(13, C, &c, 1)); + reg.push(bound(14, D, &d, 0)); + let mut reserved = vacant(15, 1); + reserved.rearm_for = Some(OTHER); + reg.push(reserved); + reg.push(released(16, 998, 2)); + reg.teardown.releasing.push(1016); + let untouchable = [13u8, 14, 15, 16]; + assert!(reg.queue(14).shareable(), "D's idle channel is shareable, so only a primary may take it"); + assert!(!reg.queue(14).reusable()); + + // No lockout: the sibling comes from the vacant queue, re-armed and bound as channel 1. + assert!(reg.has_compute_sibling_headroom(B, &b, req), "vacant and other-VM queues are headroom"); + assert!(reg.wants_compute_sibling(B, &b, 3, req)); + assert_eq!(reg.bind_reusable_sibling(B, &b, 3, req), Ok(Some(false)), "nothing warm to bind at once"); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Vacant(11))); + assert_eq!(add_sibling(&mut reg, &init, B, &b), Ok(true)); + { + let q = reg.queue(11); + assert_eq!((q.owner, q.channel_index, q.pool_phase), (Some(B), 1, PoolPhase::Populated)); + assert!(q.has_ring() && !q.needs_fresh_backing() && q.rearm_for.is_none()); + } + assert_eq!(reg.compute_channels_of(B), (2, 0b11)); + + // The third channel. While a pool release is in flight (it ends in a vacant queue) no other + // VM's pool is given back, and the releasing queue itself is not taken. + reg.queue_mut(11).active.len = 1; + let mut releasing = released(17, 997, 3); + releasing.pool_phase = PoolPhase::ReleaseSent(u32::MAX); + reg.push(releasing); + assert!(!reg.queue(17).reusable() && reg.queue(17).vacancy_pending()); + assert_eq!(reg.sibling_source(B, &b, req), None); + assert_eq!(add_sibling(&mut reg, &init, B, &b), Ok(false)); + assert!(!reg.queue(12).needs_fresh_backing(), "nothing given back meanwhile"); + reg.compute.pop(); + // Then no vacant queue is left, so the exited VM's queue is given back. + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Foreign(12))); + assert_eq!(add_sibling(&mut reg, &init, B, &b), Ok(false), "given back, not yet vacant"); + assert!(reg.queue(12).needs_fresh_backing() && reg.queue(12).vacancy_pending()); + assert!(!reg.queue(12).reusable(), "nobody binds its old pool meanwhile"); + // One give-back at a time: nothing else is offered while that release is pending. + assert_eq!(reg.sibling_source(B, &b, req), None); + assert!(!reg.wants_compute_sibling(B, &b, 3, req)); + // The pool pass releases it; once consumed the queue is vacant and is re-armed for B. + reg.pool_pass(&init); + assert_eq!(reg.queue(12).pool_phase, PoolPhase::Vacant); + assert!(reg.queue(12).pool_serves(b.vm()), "fresh backing serves any VM"); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Vacant(12))); + assert_eq!(add_sibling(&mut reg, &init, B, &b), Ok(true)); + assert_eq!((reg.queue(12).owner, reg.queue(12).channel_index), (Some(B), 2)); + assert_eq!(reg.compute_channels_of(B), (3, 0b111)); + assert!(!reg.wants_compute_sibling(B, &b, 3, req), "three channels at most"); + + // Nothing was stolen. + for qid in untouchable { + let q = reg.queue(qid); + assert_ne!(q.owner, Some(B), "queue {} was taken", qid); + assert!(!q.needs_fresh_backing(), "queue {} was given back", qid); + } + assert_eq!(reg.queue(13).owner, Some(C)); + assert_eq!(reg.queue(14).owner, Some(D)); + assert_eq!(reg.queue(15).rearm_for, Some(OTHER)); + + // Clients come and go: each new one gets its siblings back from what the last one left. + for round in 0..4u32 { + let vm = 500 + round; + let next = Context::new(50 + round, vm); + let owner = 100 + u64::from(round); + // The previous owner's channels (B's, then each round's) are released idle; their + // pools serve the exited VM. The newcomer's primary is one of them, rebound (modelled). + let mut freed: Vec = Vec::new(); + for entry in reg.compute.iter().flatten() { + let mut q = entry.queue.0.borrow_mut(); + if q.owner.is_some() && !untouchable.contains(&q.qid) { + q.owner = None; + q.released = true; + q.retirement_ready = true; + q.active.len = 0; + q.released_at = u64::from(round) * 10 + u64::from(q.qid); + freed.push(q.qid); + } + } + assert_eq!(freed.len(), 3, "round {}: three channels released", round); + let primary = freed[0]; + { + let mut q = reg.queue_mut(primary); + q.owner = Some(owner); + q.channel_index = 0; + q.released = false; + q.pool_phase = PoolPhase::Vacant; + q.pool.pages = Some(Pages(3)); + q.pool_phase = PoolPhase::Populated; + q.pool.client_vm = vm; + q.sustained = true; + q.active.len = 2; + } + let mut added = 0; + for _ in 0..8 { + if add_sibling(&mut reg, &init, owner, &next).unwrap() { + added += 1; + // Every bound channel stays busy. + for entry in reg.compute.iter().flatten() { + let mut q = entry.queue.0.borrow_mut(); + if q.owner == Some(owner) && q.active.len == 0 { + q.active.len = 1; + } + } + } else { + reg.pool_pass(&init); + } + } + assert_eq!(added, 2, "round {}: no lockout", round); + assert_eq!(reg.compute_channels_of(owner).0, 3); + for qid in untouchable { + assert_ne!(reg.queue(qid).owner, Some(owner)); + } + } + + // A fresh QID comes before another VM's pool is given back. + let mut reg = registry(); + reg.qids.fit = true; + reg.push(bound(10, B, &b, 2)); + reg.push(released(12, 999, 6)); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Fresh)); + // A warm same-VM queue comes before a vacant one. + reg.push(vacant(11, 1)); + reg.push(released(18, 200, 9)); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Warm(18))); + assert_eq!(reg.bind_reusable_sibling(B, &b, 3, req), Ok(Some(true))); + assert_eq!(reg.queue(18).channel_index, 1); + // ... and a vacant one before a fresh QID; the longest released first. + reg.push(vacant(19, 0)); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Vacant(19))); + + println!("PASS g17-m5-sibling-rearm: vacant and other-VM idle queues become siblings, nothing busy or open is taken"); +} +''' + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + source = build(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-sibling-rearm-') as tmp: + path = Path(tmp) / 'rearm.rs' + binary = path.with_suffix('') + path.write_text(source) + built = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '-O', str(path), + '-o', str(binary)], capture_output=True, text=True) + if built.returncode: + sys.stderr.write(built.stderr) + return built.returncode + run = subprocess.run([str(binary)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index d9a5b417f03220..fc672d2e8ce279 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -17,6 +17,10 @@ match the pool before linux#1978 (BASE) on the same random operations. - Source rules: every accessor that hands the address to the firmware marks it, and only the release path of `retain_linked_work` marks it released. +- Cache policy (linux#3170 and its G17P follow-up): records the host rewrites + in place (render queue records, the compute graph, M5 scheduler pages) stay + uncached on every G17; work nodes and compute descriptors are uncached on M5 + and keep their firmware-cached prefix on G17P. `--mutation` applies one known-bad change to the compiled copy; the run must then fail. @@ -47,6 +51,14 @@ 'node-unmarked': ('context', ' self.context.expose_work();\n', ''), # A consumed release with an empty list does not mark the work state. 'no-release': ('context', 'mark.released(super::channel::control_witnessed());', 'let _ = mark;'), + # M5 work nodes are firmware-cached again. + 'm5-cached-nodes': ('policy-context', 'if alloc.uat.is_m5() { 0 } else { UAT_PGSZ }', 'UAT_PGSZ'), + # M5 compute descriptors are firmware-cached again. + 'm5-cached-descriptors': ('policy-compute', 'if alloc.uat.is_m5() { 0 } else { size }', 'size'), + # Render queue records, which the host retargets in place, are firmware-cached again. + 'cached-queue-records': ('policy-memory', 'GRAPH_SIZE,\n 0,\n', 'GRAPH_SIZE,\n 0x8000,\n'), + # G17P work nodes lose their cached prefix (the linux#3170 light-submission cost). + 'uncached-g17p-nodes': ('policy-context', 'if alloc.uat.is_m5() { 0 } else { UAT_PGSZ }', '0'), } @@ -148,7 +160,10 @@ def context_source(text): pub struct KernelMapping { pub iova: u64 } impl KernelMapping { pub fn iova(&self) -> u64 { self.iova } - pub unsafe fn set_fw_cached_prefix(&self, _prefix: usize) -> (crate::Result<[u64; 2]>, bool) { (Ok([0; 2]), true) } + pub unsafe fn set_fw_cached_prefix(&self, prefix: usize) -> (crate::Result<[u64; 2]>, bool) { + assert!(prefix > 0, "set_fw_cached_prefix must not be called for prefix == 0"); + (Ok([0; 2]), true) + } } } @@ -357,6 +372,54 @@ def context_source(text): ["unseen=", "released=", "strict="].map(|key| crate::count(&s, "workstate_returns", key)) } + /// Uncached pooled objects (`prefix == 0`) skip `set_fw_cached_prefix` while keeping + /// their pool lease, fence, return mark, reuse zeroing and retention until stop. + pub fn uncached_pooled() { + for after_release in [true, false] { + let next = Cell::new(1); + let alloc = Allocator { next: &next }; + let pool = Pool::new(after_release).unwrap(); + crate::forget_unmapped(); + crate::channel::set(5, 3); + + let mut ws = pool.allocate(&alloc, Family::WorkState, WORK, 0, 0, CpuMap::WriteCombined).unwrap(); + assert!(ws.lease.is_some(), "prefix == 0 keeps a pool lease"); + assert_eq!(ws.return_mark().is_some(), after_release); + ws.bytes_mut()[0] = 0x42; + let ws_id = ws.id; + if let Some(mark) = ws.return_mark() { + mark.expose(); + } + drop(ws); + assert!(!unmapped(ws_id), "prefix == 0 stays mapped on drop"); + assert_eq!(fence(&pool, Family::WorkState, ws_id), Some(6)); + + // Still behind fence: a fresh object is allocated instead of reusing ws_id. + let fresh = pool.allocate(&alloc, Family::WorkState, WORK, 0, 0, CpuMap::WriteCombined).unwrap(); + assert_ne!(fresh.id, ws_id); + drop(fresh); + + // Once the fence is met, ws_id is reused and zeroed. + crate::channel::set(6, 6); + let reused = pool.allocate(&alloc, Family::WorkState, WORK, 0, 0, CpuMap::WriteCombined).unwrap(); + assert_eq!(reused.id, ws_id, "prefix == 0 is reused once its fence is met"); + assert_eq!(reused.bytes[0], 0, "reused prefix == 0 object is zeroed"); + drop(reused); + + // retain_until_stop keeps an uncached pooled object mapped until firmware stop. + let mut kept = pool.allocate(&alloc, Family::QueueState, mmu::UAT_PGSZ, 0, 0, CpuMap::WriteCombined).unwrap(); + assert!(kept.lease.is_some()); + let kept_id = kept.id; + kept.retain_until_stop(&pool); + drop(kept); + assert!(!unmapped(kept_id)); + pool.stop_after_firmware(); + assert!(unmapped(kept_id)); + assert!(unmapped(ws_id)); + } + println!("uncached pooled: prefix == 0 skips firmware caching while keeping fencing, reuse and retention"); + } + /// Each return class decides the fence; reuse never waits on a met fence. pub fn return_classes() { let next = Cell::new(1); @@ -708,6 +771,7 @@ def context_source(text): } fn main() { + now::uncached_pooled(); now::return_classes(); now::full_family(); let (mut allocations, mut uncached, mut overruns) = (0, 0, 0); @@ -767,6 +831,32 @@ def source_rules(context, observation, tree): print('source: records and commands mark the work state; only a consumed empty-list release releases it') +def cache_policy(context, compute, memory): + """The firmware-cached prefix each pooled G17 object family gets. Returns the failures.""" + failures = [] + + def need(text, pattern, what): + if not re.search(pattern, text): + failures.append(what) + + # Work nodes: uncached on M5, the node page cached on G17P; the counter page stays uncached. + need(context, r'pool\.allocate\(\s*alloc,\s*Family::WorkState,\s*2 \* UAT_PGSZ,\s*' + r'if alloc\.uat\.is_m5\(\) \{ 0 \} else \{ UAT_PGSZ \},', 'work nodes: M5 uncached, G17P node page cached') + # M5 scheduler pages, which are zeroed and reinitialised on reuse, stay uncached. + need(context, r'Family::Scheduler,\s*UAT_PGSZ,\s*0,', 'M5 scheduler pages uncached') + # Compute descriptors: uncached on M5, cached on G17P. + need(compute, r'Family::Descriptor,\s*size,\s*if alloc\.uat\.is_m5\(\) \{ 0 \} else \{ size \},', + 'compute descriptors: M5 uncached, G17P cached') + # The compute graph, whose queue record is rebound in place, is an ordinary uncached allocation. + need(compute, r'let mut graph = alloc\.kernel\(GRAPH_SIZE \+ mmu::UAT_PGSZ, page, prot, cpu\)\?;', + 'compute graph uncached') + if 'Family::QueueState' in compute: + failures.append('compute graph not pooled') + # Render queue records, retargeted and bound to work slots in place, stay uncached. + need(memory, r'Family::QueueState,\s*GRAPH_SIZE,\s*0,\s*prot,', 'render queue records uncached') + return failures + + def main(): ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) ap.add_argument('--mutation', choices=sorted(MUTATIONS)) @@ -780,6 +870,21 @@ def main(): check=True, capture_output=True, text=True).stdout source_rules(ctx, observation, DRIVER) + policy = {'context': ctx, 'compute': (DRIVER / 'g17/queue/compute.rs').read_text(), + 'memory': (DRIVER / 'g17/queue/render/memory.rs').read_text()} + if args.mutation and MUTATIONS[args.mutation][0].startswith('policy-'): + where, old, new = MUTATIONS[args.mutation] + policy[where[len('policy-'):]] = replace(policy[where[len('policy-'):]], old, new) + failures = cache_policy(policy['context'], policy['compute'], policy['memory']) + for failure in failures: + print(f'FAIL line 0: cache policy: {failure}') + if failures: + return 1 + print('cache policy: in-place rewritten records uncached everywhere; work nodes and compute descriptors ' + 'uncached on M5 and cached on G17P') + if args.mutation and MUTATIONS[args.mutation][0].startswith('policy-'): + return 0 + now = pool_source(obj) pages, methods, node = context_source(ctx) if args.mutation: diff --git a/tools/asahi/g17-owner-release-order-tests.py b/tools/asahi/g17-owner-release-order-tests.py index 517eda49370d43..1f6a1fc11587d8 100755 --- a/tools/asahi/g17-owner-release-order-tests.py +++ b/tools/asahi/g17-owner-release-order-tests.py @@ -106,6 +106,7 @@ def fixture(): # teardown_idle() is idle_for() without the release-time kill exception. idle = '\n'.join(item(render_teardown, name) for name in [ 'pub(in crate::g17::runtime) fn teardown_idle(', 'fn idle_for(']).replace('pub(in crate::g17::runtime) ', '') + counts_idle = item(render_teardown, 'fn counts_idle(') compute_switch = item((ROOT / 'queue/compute.rs').read_text(), 'pub(crate) fn switching_from(').replace('pub(crate) ', '') compute_idle = item((ROOT / 'runtime/teardown.rs').read_text(), 'fn compute_idle(') @@ -118,8 +119,8 @@ def fixture(): impl Context { fn scheduler_va(&self) -> u64 { self.scheduler } fn is_published(&self) -> bool { self.published } - // Reached only for a release-time check, which this fixture does not make. - fn kill_published(&self) -> bool { unreachable!() } + // This ordering fixture publishes no kill. + fn kill_published(&self) -> bool { false } } #[derive(Clone, Copy, PartialEq, Eq)] enum Phase { Deferred, Draining, Released(u32) } @@ -138,6 +139,9 @@ def fixture(): impl Pair { // This ordering fixture models no faulted/executed unstamped pair. fn executed_for_kill(&self, _: &Arc) -> bool { false } + // Nor a guilty pair of a killed context. + fn guilty_for_kill(&self, _: &Arc, _: u64) -> bool { false } + fn guilty_released(&self) -> bool { false } SWITCH /// Host stand-in for a successful publication of `ordinal` (stand-in, not production). fn publish(&mut self, packet: &Packet, ordinal: u64) { @@ -157,6 +161,7 @@ def fixture(): impl RenderState { IDLE } +COUNTS_FN struct Previous { context: Arc, publication: Option<(u64, u64)> } struct Queue { previous: Option, bound: Option> } impl Queue { @@ -206,23 +211,23 @@ def fixture(): let mut render = RenderState { entries: vec![Some(RenderEntry { context: Some(c.clone()), preparing: None, growing: false, pair: Some(Box::new(pair)), borrowed_switch: None, })] }; - assert!(!render.teardown_idle(&d).unwrap(), "release waits for the new owner's first command"); - assert!(render.teardown_idle(&b).unwrap(), "unrelated releases are not held"); + assert!(!render.teardown_idle(&d, 0).unwrap(), "release waits for the new owner's first command"); + assert!(render.teardown_idle(&b, 0).unwrap(), "unrelated releases are not held"); // A borrowed pair is judged by its snapshot; a stale snapshot outside a borrow is ignored. let borrowed = render.entries[0].as_mut().unwrap(); let pair = borrowed.pair.take().unwrap(); borrowed.borrowed_switch = pair.switch_in_flight(); borrowed.preparing = Some(()); - assert!(!render.teardown_idle(&d).unwrap(), "a borrowed switching pair still holds the release"); + assert!(!render.teardown_idle(&d, 0).unwrap(), "a borrowed switching pair still holds the release"); let entry = render.entries[0].as_mut().unwrap(); entry.preparing = None; entry.pair = Some(pair); entry.pair.as_mut().unwrap().active.clear(); - assert!(render.teardown_idle(&d).unwrap(), "retirement of the first command releases the hold"); + assert!(render.teardown_idle(&d, 0).unwrap(), "retirement of the first command releases the hold"); let entry = render.entries[0].as_mut().unwrap(); entry.pair.as_mut().unwrap().active.push(Active { ticket: Ticket { ordinal: 1 } }); entry.pair = None; - assert!(render.teardown_idle(&d).unwrap(), "a stale snapshot without a borrow holds nothing"); + assert!(render.teardown_idle(&d, 0).unwrap(), "a stale snapshot without a borrow holds nothing"); // Compute: only a published first command after the change holds the release. let mut service = Service { compute: vec![Some(ComputeEntry { queue: Some(Box::new(Queue { @@ -237,7 +242,7 @@ def fixture(): println!("PASS release table gate, pair switch hold, borrowed snapshot and compute switch hold"); } '''.replace('PENDING', pending).replace('SWITCH', switch_methods, 1).replace('RECORD', record) \ - .replace('IDLE', idle, 1).replace('COMPUTE_SWITCH', compute_switch).replace('COMPUTE_IDLE', compute_idle) + .replace('IDLE', idle, 1).replace('COMPUTE_SWITCH', compute_switch).replace('COMPUTE_IDLE', compute_idle).replace('COUNTS_FN', counts_idle) def main(): diff --git a/tools/asahi/g17-pool-release-tests.py b/tools/asahi/g17-pool-release-tests.py index 70004fe94ecf91..5bcae16787d35c 100644 --- a/tools/asahi/g17-pool-release-tests.py +++ b/tools/asahi/g17-pool-release-tests.py @@ -31,7 +31,8 @@ def fixture(): predicate = '.any(|queue| queue.retirement_polling() || queue.pool_release_pending())' assert events.count(predicate) == 1 methods = '\n'.join(item(runtime, name) for name in [ - 'fn compute_admission_error(', 'pub(super) fn reserve_compute(']).replace('pub(super) ', '').replace('queue: ComputeSlot::new()?', 'queue: None') + 'fn compute_admission_error(', 'pub(super) fn reserve_compute(', + 'pub(super) fn reserve_compute_channel(']).replace('pub(super) ', '').replace('queue: ComputeSlot::new()?', 'queue: None') pending = item(compute, 'pub(crate) fn pool_release_pending(') + '\n' + \ item(compute, 'pub(crate) fn release_settling(') return r''' @@ -74,7 +75,10 @@ def fixture(): struct ComputeReservation { slot: usize, id: Id, owner: u64 } type ComputeSlot = Option>; struct ComputeEntry { reservation: ComputeReservation, queue: ComputeSlot } -struct Admission; impl Admission {fn queues(&self)->u32{4}} +struct Admission; impl Admission {fn queues(&self)->u32{4} + fn reserve_compute_with_budget(&self, _: u64, _: u64, reserve: impl FnOnce(usize) -> Result<(T, bool, usize)>) -> Result { + reserve(self.queues() as usize).map(|(value, _, _)| value) + }} struct QueueIds { free: bool, fail: Option } impl QueueIds { fn reserve_for(&mut self, _: u64, _: DataMaster, preferred: Option, _: usize) -> Result { @@ -83,6 +87,8 @@ def fixture(): self.free = false; Ok(Id { qid: preferred.unwrap() }) } + fn render_pair_fits(&self) -> bool { true } + fn render_pair_capacity(&self) -> usize { 0 } } struct Identities { next: u64 } impl Identities { @@ -100,6 +106,7 @@ def fixture(): impl Registry { // Physical-QID capacity notification does not change this pool-release fixture. fn note_build_room(&self) {} + fn reclaimable_render_slots(&self) -> Result<(u64, u64)> { Ok((0, 0)) } METHODS fn poll(&self) -> bool { self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref())PREDICATE diff --git a/tools/asahi/g17-quarantine-drain-tests.py b/tools/asahi/g17-quarantine-drain-tests.py index 53204a179edd66..a86e6e957069bc 100644 --- a/tools/asahi/g17-quarantine-drain-tests.py +++ b/tools/asahi/g17-quarantine-drain-tests.py @@ -73,7 +73,7 @@ def fixture(): 'pair.retire(None, generation, state, host,', 'pair.fail_after_observation(packet, error, host,') # A first signal gives the lease back without ending a quarantine (the `complete` mock). ordered(item(completion, 'fn complete_with_compute('), - 'if self.signalled.swap(true, Ordering::AcqRel) {\n return;\n }', + 'if self.signalled.swap(true, Ordering::AcqRel) {\n return false;\n }', 'self.release_healthy();') # The drain release runs once the drain proof, event service and accounting passed. ordered(item(settle, 'fn drain_render_slot('), 'pair.firmware_drained(host)', 'self.service_runtime_events(deferred)', @@ -84,8 +84,11 @@ def fixture(): at = pairs.index('const SIBLING_BACKLOG') backlog = pairs[at:pairs.index('\n}\n', pairs.index('fn sibling_backlog', at)) + 3] state = '\n'.join(item(admission, name) for name in [ - 'const fn new(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', - 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn usable(', 'fn position(', 'fn release(', + 'const fn new(', 'fn owns_live(', 'fn has_live_owner(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', + 'fn set_owner(', 'fn take_idle(', 'fn acquire(', 'fn acquire_for(', 'fn live_owners(', 'fn live_siblings(', + 'fn reclaimable_siblings_in(', 'fn reclaimable_siblings(', 'fn promotes_reclaimable_sibling(', + 'fn can_lease_slot(', 'fn unavailable_released(', 'fn total_pair_demand(', 'fn pair_demand(', + 'fn claim_sibling(', 'fn usable(', 'fn position(', 'fn release(', 'fn rehabilitate(', 'fn pair_drained(&mut self', 'fn retained(', 'fn used(']) pool = '\n'.join(item(admission, name) for name in [ 'pub(crate) fn release_owner(', 'pub(crate) fn release_retained_owners_after_processor_stop(', @@ -103,6 +106,7 @@ def fixture(): #![allow(dead_code, unused_macros, unused_imports, unused_variables, unused_mut)] use std::collections::VecDeque; use std::sync::{Arc, atomic::{AtomicBool, AtomicUsize, Ordering, Ordering::SeqCst}}; +macro_rules! pr_warn { ($($arg:tt)*) => { eprint!($($arg)*) }; } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Error(i32); @@ -155,7 +159,7 @@ def fixture(): fn report_failure(&self, _: Error) {} } pub struct Output; -impl Output { fn finish(&self, _: Result<[u64; 4]>) {} } +impl Output { fn finish(&self, _: Result<[u64; 4]>, _: &Status) {} } pub struct Sources; impl Sources { fn release(&self) {} } @@ -175,6 +179,7 @@ def fixture(): sources: Option>, vm_job: Mutex>, render: Mutex>, + is_compute: bool, signalled: AtomicBool, accepted: AtomicBool, spared: AtomicBool, @@ -188,13 +193,14 @@ def fixture(): fn report(&self, _: Error) {} fn signal_terminal(&self, result: Result<[u64; 4]>) { *self.result.lock() = Some(result); } /// The lease handling of the real complete_with_compute (checked against it above). - fn complete(&self, result: Result<[u64; 4]>) { self.complete_with_compute(result, None) } - fn complete_with_compute(&self, result: Result<[u64; 4]>, _: Option<[u64; 2]>) { + fn complete(&self, result: Result<[u64; 4]>) -> bool { self.complete_with_compute(result, None) } + fn complete_with_compute(&self, result: Result<[u64; 4]>, _: Option<[u64; 2]>) -> bool { if self.signalled.swap(true, Ordering::AcqRel) { - return; + return false; } self.release_healthy(); self.signal_terminal(result); + true } ''' + command + '\n}\n' + item(completion, 'pub(crate) enum Deferred {') + '\n' + item(completion, 'impl Deferred {') + r''' @@ -222,7 +228,11 @@ def fixture(): impl Memory { fn retire(&mut self, ordinal: u64) -> Result { self.retired.push(ordinal); Ok(()) } } /// The firmware state behind `Pair::firmware_drained`: cursors done == write, free-list /// blocks returned, and stamps covering the last publication or the context's kill acknowledged. -pub trait Host { fn drained(&self) -> bool; } +pub trait Host { + fn drained(&self) -> bool; + /// No restart in progress (recovery generation, state). + fn epoch(&self) -> Result<(u64, u32)> { Ok((1, 0)) } +} pub struct FakeHost { drained: bool } impl Host for FakeHost { fn drained(&self) -> bool { self.drained } } pub struct Pair { @@ -232,9 +242,13 @@ def fixture(): memory: Memory, drain_failures: u32, drain_retry_at: u64, + guilty_released: bool, + slot: u8, } impl Pair { fn firmware_drained(&self, host: &impl Host) -> Result { Ok(host.drained()) } + // This fixture models no killed guilty context (`Pair::guilty_killed`). + fn guilty_killed(&self, _generation: u64, _state: u32) -> bool { false } fn resync(&mut self) {} // The cross-pair task-stage order is not modelled here (KUnit asahi_g17_render_cross_pair_order). fn release_task_order_if_held(&self) {} @@ -290,6 +304,7 @@ def fixture(): let completion = Arc::new(Completion { status: Arc::new(Status), output: Output, sources: Some(Arc::new(Sources)), vm_job: Mutex::new(Some(guard)), render: Mutex::new(Some(lease)), + is_compute: false, signalled: AtomicBool::new(false), accepted: AtomicBool::new(true), spared: AtomicBool::new(false), result: Mutex::new(None), }); @@ -302,7 +317,8 @@ def fixture(): stamps_owed: false, failed: false, flist_completed: false, drained_result: None, }).collect(); let pair = Pair { quarantined: false, active: Ring(active), terminal: None, memory: Memory { retired: Vec::new() }, - drain_failures: 0, drain_retry_at: 0 }; + drain_failures: 0, drain_retry_at: 0, guilty_released: false, + slot: 0 }; Firmware { queues: Queues { admission: pool.clone() }, pair: Some(Box::new(pair)), host: FakeHost { drained: false } } } fn batch() -> DeferredBatch { DeferredBatch { values: Vec::new() } } diff --git a/tools/asahi/g17-render-direct-recovery-tests.py b/tools/asahi/g17-render-direct-recovery-tests.py new file mode 100755 index 00000000000000..ef1bd4360769e0 --- /dev/null +++ b/tools/asahi/g17-render-direct-recovery-tests.py @@ -0,0 +1,293 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host lifecycle test for render_direct() recovery crossing publication and doorbell contract. + +Compiles production `render_doorbell_message()` (from `runtime/render.rs`) and +`finish_publication()` (from `runtime/backend.rs`), and drives the real +post-publication recovery check extracted from `render_direct()` +(`runtime/render/direct.rs`) through a full lifecycle harness: +1. Recovery starts while a render pair is lent and published (same generation, + `recovery_state != 0`): `render_direct()` returns `Ok(())`, `return_render()` + returns the published pair before `lease` drops, `queue_events()` runs, + `finish_publication()` does NOT fail the unrelated client's VM, and the + subsequent recovery pass settles the pair exactly once. +2. Generation changes mid-publication (`port.generation() != generation`): + `render_direct()` returns `Err(EIO)` and `finish_publication()` fails the VM. +3. Shared `render_doorbell_message()` contract: M5 (!J813_FORMS) uses pipe 2, + J813 (J813_FORMS) uses pipe 0, non-M5 uses pipe 0, and both render publishers + delegate to `render_doorbell_message()`. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def build_harness(mutation=None): + render_src = (G17 / 'runtime/render.rs').read_text() + direct_src = (G17 / 'runtime/render/direct.rs').read_text() + backend_src = (G17 / 'runtime/backend.rs').read_text() + + doorbell_fn = item(render_src, 'fn render_doorbell_message(') + direct_fn = item(direct_src, 'pub(in crate::g17::runtime) fn render_direct(') + finish_fn = item(backend_src, 'pub(super) fn finish_publication(').replace('pub(super) ', '') + + if mutation == 'wrong-j813-pipe': + doorbell_fn = doorbell_fn.replace( + 'if m5 && !crate::g17::J813_FORMS.load(core::sync::atomic::Ordering::Relaxed)', + 'if m5', + 1, + ) + + # Extract the exact post-publication check block from render_direct(). + check_start = direct_fn.index('result?;') + check_end = direct_fn.index('Ok(())\n })();', check_start) + len('Ok(())') + post_publish = direct_fn[check_start:check_end] + + if mutation == 'recovery-state-eio': + post_publish = post_publish.replace( + 'if port.recovery_state()? != 0 {\n recovery_started = true;\n }', + 'if port.recovery_state()? != 0 {\n return Err(EIO);\n }', + 1, + ) + elif mutation == 'drop-generation-check': + post_publish = post_publish.replace( + 'if port.generation() != generation {\n return Err(EIO);\n }', + '', + 1, + ) + + # Verify both locked and direct render publishers share render_doorbell_message() + # and that render_direct() returns the pair and drops lease before queueing events. + shared_contract = ( + 'notify(render_doorbell_message(m5, priority))' in render_src + and 'self.port.notify(super::render_doorbell_message(m5, priority))' in direct_src + and direct_src.count('J813_FORMS') == 0 + ) + order_tokens = [ + 'firmware.return_render(slot, &mut loan, activation, packet)', + 'self.shared.note_changed();', + 'drop(lease);', + 'if recovery_started {\n self.shared.queue_events();\n }', + ] + order_ok = True + pos = -1 + for tok in order_tokens: + if direct_fn.count(tok) != 1 or direct_fn.index(tok) <= pos: + order_ok = False + break + pos = direct_fn.index(tok) + + doorbell_host = doorbell_fn.replace('crate::g17::', 'g17_stub::') + + return f''' +use std::cell::Cell; +use std::sync::{{Arc, atomic::{{AtomicBool, AtomicUsize, Ordering}}}}; + +const EIO: i32 = -5; +const ETIMEDOUT: i32 = -110; +const ENODEV: i32 = -19; +type Result = std::result::Result; +type Fence = u8; + +mod g17_stub {{ + use std::sync::atomic::AtomicBool; + pub const MSG_TYPE_SHIFT: u32 = 48; + pub static J813_FORMS: AtomicBool = AtomicBool::new(false); +}} + +{doorbell_host} + +#[derive(PartialEq, Eq)] +enum Engine {{ Render, Compute }} + +struct Status(Cell); +impl Status {{ fn get(&self) -> i32 {{ self.0.get() }} }} + +struct Completion {{ + status: Status, + unpublished_fails: Cell, +}} +impl Completion {{ + fn status(&self) -> &Status {{ &self.status }} + fn fail_unpublished(&self, _: i32) {{ self.unpublished_fails.set(self.unpublished_fails.get() + 1); }} + fn scheduler_fence(&self) -> Fence {{ 1 }} +}} + +struct Packet {{ + published: Cell, + completion: Arc, +}} +impl Packet {{ + fn is_published(&self) -> bool {{ self.published.get() }} + fn engine(&self) -> Engine {{ Engine::Render }} +}} + +struct DeferredBatch {{ finished: usize }} +impl DeferredBatch {{ fn finish(&mut self) {{ self.finished += 1; }} }} + +mod job {{ + pub trait Backend {{ + fn fail_vm(&self, error: i32); + }} +}} + +struct Port {{ + gen: Cell, + rec_state: Cell, +}} +impl Port {{ + fn generation(&self) -> u64 {{ self.gen.get() }} + fn recovery_state(&self) -> Result {{ Ok(self.rec_state.get()) }} +}} + +struct RecoveryHarness {{ + vm_failed: Cell, + events_queued: Cell, + pair_returned_before_lease_drop: Cell, + lease_held: Cell, + pair_in_registry: Cell, + settlements: Cell, + stop_called: Cell, +}} + +impl job::Backend for RecoveryHarness {{ + fn fail_vm(&self, _error: i32) {{ + self.vm_failed.set(true); + }} +}} + +impl RecoveryHarness {{ + fn stop_after_error(&self) {{ self.stop_called.set(true); }} + fn rollback_unpublished_compute(&self) -> Result {{ Ok(()) }} + + {finish_fn} + + fn run_direct_publish_lifecycle(&self, port: &Port, generation: u64, packet: &Arc) -> Result {{ + self.lease_held.set(true); + self.pair_in_registry.set(false); + let mut recovery_started = false; + let result: Result = (|| {{ + let result: Result = Ok(()); + packet.published.set(true); + {post_publish} + }})(); + // return_render() places the published pair back while lease is still held. + self.pair_in_registry.set(true); + self.pair_returned_before_lease_drop.set(self.lease_held.get()); + self.lease_held.set(false); + if recovery_started {{ + self.events_queued.set(self.events_queued.get() + 1); + }} + let mut deferred = DeferredBatch {{ finished: 0 }}; + self.finish_publication(packet, result, &mut deferred) + }} + + fn run_recovery_pass(&self, port: &Port) {{ + // Recovery drains preparations (lease must already be dropped) and settles the returned pair once. + assert!(!self.lease_held.get(), "recovery must wait for lease drop"); + if self.pair_in_registry.get() && port.recovery_state().unwrap() != 0 {{ + self.settlements.set(self.settlements.get() + 1); + port.gen.set(port.gen.get() + 1); + port.rec_state.set(0); + self.pair_in_registry.set(false); + }} + }} +}} + +fn new_packet() -> Arc {{ + Arc::new(Packet {{ + published: Cell::new(false), + completion: Arc::new(Completion {{ + status: Status(Cell::new(0)), + unpublished_fails: Cell::new(0), + }}), + }}) +}} + +fn new_harness() -> RecoveryHarness {{ + RecoveryHarness {{ + vm_failed: Cell::new(false), + events_queued: Cell::new(0), + pair_returned_before_lease_drop: Cell::new(false), + lease_held: Cell::new(false), + pair_in_registry: Cell::new(false), + settlements: Cell::new(0), + stop_called: Cell::new(false), + }} +}} + +fn main() {{ + assert!({str(shared_contract).lower()}, "both render publishers must share render_doorbell_message"); + assert!({str(order_ok).lower()}, "render_direct must return pair before dropping lease and queueing events"); + + // 1. Doorbell pipe contract. + g17_stub::J813_FORMS.store(false, Ordering::Relaxed); + assert_eq!(render_doorbell_message(false, 2) & 3, 0); + assert_eq!(render_doorbell_message(true, 2) & 3, 2); + assert_eq!((render_doorbell_message(true, 3) >> 2) & 3, 3); + g17_stub::J813_FORMS.store(true, Ordering::Relaxed); + assert_eq!(render_doorbell_message(true, 2) & 3, 0); + g17_stub::J813_FORMS.store(false, Ordering::Relaxed); + + // 2. Recovery crosses publication (same generation, recovery_state != 0): + // unrelated client keeps its VM, pair is returned before lease drop, and settles once. + let h = new_harness(); + let port = Port {{ gen: Cell::new(7), rec_state: Cell::new(1) }}; + let pkt = new_packet(); + let fence = h.run_direct_publish_lifecycle(&port, 7, &pkt).unwrap(); + assert_eq!(fence, 1); + assert!(!h.vm_failed.get(), "unrelated client VM must survive recovery crossing publication"); + assert!(h.pair_returned_before_lease_drop.get()); + assert_eq!(h.events_queued.get(), 1); + h.run_recovery_pass(&port); + h.run_recovery_pass(&port); + assert_eq!(h.settlements.get(), 1, "published pair must settle exactly once"); + + // 3. Generation changed mid-publication: fails with EIO and fails VM. + let h2 = new_harness(); + let port2 = Port {{ gen: Cell::new(8), rec_state: Cell::new(0) }}; + let pkt2 = new_packet(); + assert_eq!(h2.run_direct_publish_lifecycle(&port2, 7, &pkt2).err(), Some(EIO)); + assert!(h2.vm_failed.get(), "generation mismatch must fail VM"); + + println!("PASS g17-render-direct-recovery-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['recovery-state-eio', + 'drop-generation-check', + 'wrong-j813-pipe']) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-rd-rec-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-render-return-observe-tests.py b/tools/asahi/g17-render-return-observe-tests.py new file mode 100755 index 00000000000000..3f8574c45ffd84 --- /dev/null +++ b/tools/asahi/g17-render-return-observe-tests.py @@ -0,0 +1,622 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: a lent render pair's completions are observed by the borrower that returns it. + +The direct render path lends an owner's pair out of the registry under the device mutex, +prepares and publishes into it without that mutex, and takes it back under the mutex again. +While it is lent, event passes skip it and record the completion for its borrower +(`missed_event`). This compiles the production code that keeps such a completion from waiting +for the end of the owner's run of publications against host stubs: + +- `retain_render_completions()`, `render_needs_rescan()`, `take_missed_event()`, `take_pair()` + and `return_pair()` from drivers/gpu/drm/asahi/g17/runtime/render.rs; +- `next_render_observation()`, `next_render_observation_in()`, `try_fast_observe_render()`, + `observe_returned_render()` and `fast_observe_renders()` from runtime/render/observe.rs, + with the production `FastRenderOutcome` and `completion_noted()`. + +It checks that + +a. an event pass that meets only completions owed to borrowers neither asks for a rescan nor + falls back to the multi-hold slow path, while a borrowed pair whose completion was noted + before it was lent still does; +b. the borrower's observation of the slot it returned retires every completion that arrived + during the loan (also several), in order, exactly once, touches no other slot, reports a + rescan while published work stays in flight, and leaves everything to the event worker in + any state the worker's fast path would not handle (another slot's error, timeout, close or + growth, a replay, recovery, a fault, no room in the collector); +c. with a publisher, an event worker and the GPU running on three threads, every command + retires exactly once and in order, and the publisher retires completions on return; +d. structurally, that `render_direct()` returns the missed flag from `return_render()`, + observes in the hold that put the pair back only with a live preparation lease and no + recovery, takes the collector with `try_lock()`, finishes it after the device mutex and + otherwise requests the event pass or, for a rescan, the poll; and that `runtime_event_turn()` + ends in its first hold a pass whose render completions are owed to borrowers or that leaves + only a rescan, arming the poll for it. + +Each mutation restores the old behaviour or drops one part of the rule, and must fail an +assertion of the compiled harness. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +# name -> [(file, old, new)]: each must apply exactly once. +MUTATIONS = { + # (a) The old rescan rule: a completion owed to the borrower still asks for a rescan. + 'rescan-owed': [('render', ' && entry.borrowed_active\n && !entry.missed_event,', + ' && entry.borrowed_active,')], + # (b) The returned slot's observation scans every slot, or ignores the steady-state gate. + 'observe-all-slots': [('observe', 'self.fast_observe_renders(slot, slot + 1, deferred)', + 'self.fast_observe_renders(1, self.queues.render.entries.len(), deferred)')], + 'observe-ignores-gate': [('observe', ' if entry.pending_error.is_some()\n || entry.pending_timeout\n' + ' || entry.closed\n || entry.growing\n', + ' if false\n')], + # (b) The old loop: it stops at the first retirement that leaves work in flight, or calls that + # a fallback. + 'rescan-in-loop-bail': [('observe', ' || self.render_grow_ready()\n {\n return Ok(FastRenderOutcome::Fallback);\n }\n' + ' // Work still in flight', + ' || self.render_grow_ready()\n || self.queues.render_needs_rescan()\n {\n' + ' return Ok(FastRenderOutcome::Fallback);\n }\n // Work still in flight')], + 'rescan-is-fallback': [('observe', ' if self.queues.render_needs_rescan() {\n return Ok(FastRenderOutcome::Rescan);\n }', + ' if self.queues.render_needs_rescan() {\n return Ok(FastRenderOutcome::Fallback);\n }'), + ('observe', ' return Ok(if self.queues.render_needs_rescan() {\n FastRenderOutcome::Rescan', + ' return Ok(if self.queues.render_needs_rescan() {\n FastRenderOutcome::Fallback')], + # (d) Structural: the borrower drops the missed flag, observes without the guards, blocks on the + # collector, signals under the device mutex, never requests the pass, or the event pass + # takes the slow path for owed completions. + 'missed-dropped': [('direct', ' Ok(missed)\n }', ' Ok(false)\n }')], + 'observe-in-recovery': [('direct', ' if !recovery_started\n && lease.is_current()\n' + ' && !self.shared.crashed.load(Ordering::Acquire)\n {\n', + ' if true {\n')], + 'collector-blocks': [('direct', 'collector = self.shared.render_collector.try_lock();', + 'collector = Some(self.shared.render_collector.lock());')], + 'finish-under-mutex': [('direct', ' drop(state);\n // Fences signal off the device mutex, before another borrower can collect.\n' + ' if let Some(batch) = collector.as_deref_mut() {\n batch.finish();\n }\n', + ' if let Some(batch) = collector.as_deref_mut() {\n batch.finish();\n }\n' + ' drop(state);\n')], + 'no-pass-requested': [('direct', 'FastRenderOutcome::Fallback => self.shared.queue_event_records(),', + 'FastRenderOutcome::Fallback => {}')], + 'rescan-no-poll': [('direct', 'FastRenderOutcome::Rescan => self.shared.queue_poll(),', 'FastRenderOutcome::Rescan => {}')], + 'worker-rescan-slow-path': [('events', ' rescan = true;\n true\n', + ' rescan = true;\n false\n')], + 'owed-slow-path': [('events', 'if render_clean && (compute_scan.is_some() || render_changed || masks != [0; 2]) {', + 'if render_clean && (compute_scan.is_some() || render_changed) {')], +} + + +def build(mutation=None): + files = { + 'render': (G17 / 'runtime/render.rs').read_text(), + 'observe': (G17 / 'runtime/render/observe.rs').read_text(), + 'direct': (G17 / 'runtime/render/direct.rs').read_text(), + 'events': (G17 / 'runtime/events.rs').read_text(), + 'queue': (G17 / 'queue/render.rs').read_text(), + } + for name, old, new in MUTATIONS.get(mutation, []): + assert files[name].count(old) == 1, (mutation, old) + files[name] = files[name].replace(old, new) + render, observe, direct, events, queue = (files[k] for k in ('render', 'observe', 'direct', 'events', 'queue')) + + def host(code): + return (code.replace('pub(in crate::g17::runtime) ', '').replace('pub(in crate::g17) ', '') + .replace('pub(super) ', '').replace('pub(crate) ', '') + .replace('crate::g17::recovery::Memory::recovery_state', 'Memory::recovery_state') + .replace('crate::g17::queue::render::completion_noted', 'completion_noted') + .replace('crate::hw::t8140::queues::RENDER_SLOTS', 'RENDER_SLOTS') + .replace('crate::g17::now_ns()', 'now_ns()').replace('kick::Id::qid', 'Id::qid') + .replace('KBox', 'Box')) + + outcome = host(item(observe, 'pub(in crate::g17::runtime) enum FastRenderOutcome')) + noted = host(item(queue, 'pub(crate) fn completion_noted(')) + state_fns = host('\n'.join(item(render, signature) for signature in [ + ' fn entry(&self, slot: u8)', ' fn entry_mut(&mut self, slot: u8)', 'fn take_missed_event(', + 'fn take_pair(&mut self, slot: u8', 'fn return_pair(&mut self, slot: u8', + ])) + registry_fns = host('\n'.join(item(render, signature) for signature in [ + 'pub(in crate::g17) fn render_needs_rescan(', 'pub(in crate::g17) fn retain_render_completions(', + ])) + firmware_fns = host('\n'.join(item(observe, signature) for signature in [ + 'fn next_render_observation(&mut self', 'fn next_render_observation_in(', + 'pub(in crate::g17::runtime) fn try_fast_observe_render(', 'pub(in crate::g17::runtime) fn observe_returned_render(', + 'fn fast_observe_renders(', + ])) + + render_direct = item(direct, 'pub(in crate::g17::runtime) fn render_direct(') + return_fn = item(direct, 'fn return_render(') + turn = item(events, 'fn runtime_event_turn(') + structure = { + 'return_render reports a completion missed during the loan': ordered_ok( + return_fn, ') -> Result {', 'self.queues.render.return_pair(slot, &mut loan.pair)?;', + 'let missed = self.queues.render.take_missed_event(slot);', 'Ok(missed)') + and 'queue_event_records' not in return_fn, + 'render_direct observes in the returning hold, signals after it': ordered_ok( + render_direct, 'let mut collector = None;', 'let mut state = self.shared.state.lock();', + 'let returned = firmware.return_render(slot, &mut loan, activation, packet);', + 'let returned = match returned {', 'Ok(true) => {', + 'if !recovery_started\n && lease.is_current()\n' + ' && !self.shared.crashed.load(Ordering::Acquire)\n {', + 'collector = self.shared.render_collector.try_lock();', + 'Some(batch) => firmware.observe_returned_render(slot, batch),', + 'None => Ok(FastRenderOutcome::Fallback),', + 'FastRenderOutcome::Fallback => self.shared.queue_event_records(),', + 'FastRenderOutcome::Rescan => self.shared.queue_poll(),', + 'FastRenderOutcome::Done | FastRenderOutcome::Idle => {}', 'Ok(false) => Ok(()),', + 'Err(error) => Err(error),', 'drop(state);', 'batch.finish();', 'drop(collector);', + 'self.shared.note_changed();', 'drop(lease);', 'if let Err(error) = returned {', + 'self.shared.lose_device_quietly();'), + 'the collector is never waited for': 'render_collector.lock()' not in render_direct, + 'an event pass whose completions are owed, or that leaves a rescan, ends in its first hold': + ordered_ok(turn, 'let mut rescan = false;', 'firmware.try_fast_observe_render(deferred)?', + 'FastRenderOutcome::Rescan => {', 'rescan = true;\n true\n', + 'if render_clean && (compute_scan.is_some() || render_changed || masks != [0; 2]) {', + 'rescan || scan.polling || firmware.non_compute_runtime_polling(now);', + 'if polling {\n self.queue_poll();', 'fast_done = true;'), + } + checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' for name, ok in structure.items()) + return (TEMPLATE.replace('@@OUTCOME@@', outcome).replace('@@NOTED@@', noted).replace('@@STATE@@', state_fns) + .replace('@@REGISTRY@@', registry_fns).replace('@@FIRMWARE@@', firmware_fns) + .replace('@@STRUCTURE@@', checks)) + + +TEMPLATE = r''' +#![allow(dead_code, unused_variables, unused_mut, unused_imports, unreachable_code)] +use std::collections::VecDeque; +use std::sync::atomic::{fence, AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +const EIO: i32 = -5; +const EAGAIN: i32 = -11; +const EBUSY: i32 = -16; +const EINVAL: i32 = -22; +type Result = std::result::Result; +const RENDER_SLOTS: usize = 64; +fn now_ns() -> u64 { 1 } + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +@@OUTCOME@@ + +@@NOTED@@ + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Id(u8); +impl Id { fn qid(self) -> u8 { self.0 } } +pub struct Context; +pub struct Packet { context: Arc, ordinal: u64 } +pub struct VmStatus; +#[derive(Clone, Copy)] +pub struct Dependencies; +#[derive(Clone, Copy)] +struct Reservation { slot: u8, ids: [Id; 2], owner: u64 } + +/// The production completion record a pair retires: the command's ordinal. +#[derive(Debug, PartialEq, Eq)] +pub enum Deferred { Retired(u64), Failed(u64) } +pub struct DeferredBatch { values: Vec, cap: usize } +impl DeferredBatch { + fn new(cap: usize) -> Self { Self { values: Vec::with_capacity(cap), cap } } + fn push(&mut self, value: Deferred) -> Result { + if self.values.len() == self.cap { return Err(EIO); } + self.values.push(value); + Ok(()) + } + fn has_room(&self, need: usize) -> bool { self.cap - self.values.len() >= need } + fn pending(&self) -> usize { self.values.len() } + fn finish(&mut self) -> Vec { std::mem::take(&mut self.values) } +} + +pub struct Observed { ordinal: u64 } +pub struct Host; +/// A render pair: its published commands in order and the fragment stamp the GPU writes. +pub struct Pair { + slot: u8, qids: [u8; 2], owner: u64, active: VecDeque, retired: Vec, + quarantined: bool, terminal: Option<(Arc, i32)>, fault_at: Option, +} +impl Pair { + fn slot(&self) -> u8 { self.slot } + fn qids(&self) -> [u8; 2] { self.qids } + fn owner(&self) -> Option { Some(self.owner) } + fn matches(&self, owner: u64, _: &Arc) -> Result { Ok(owner == self.owner) } + fn published_in_flight(&self) -> bool { !self.quarantined && !self.active.is_empty() } + fn in_flight(&self) -> bool { !self.active.is_empty() } + fn stamp_waiting(&self) -> bool { false } + fn dependency_snapshot(&self) -> Dependencies { Dependencies } + fn switch_in_flight(&self) -> Option { None } + /// The front is done once both stamps cover it. + fn observation_packet(&self, _masks: [u64; 2], stamps: [u32; 2], state: u32) -> Result> { + if self.quarantined || state != 0 { return Ok(None); } + Ok(self.active.front().copied().filter(|&ordinal| stamps.iter().all(|&s| u64::from(s) > ordinal))) + } + fn note_stamp_wait(&mut self, _: [u32; 2], _: u32, _: u64) -> Result { Ok(false) } + fn observe_front(&self) -> Result { Ok(Observed { ordinal: *self.active.front().ok_or(EIO)? }) } + fn retire_observed(&mut self, observed: Observed, _: u32, _: &mut Host, + defer: &mut impl FnMut(Deferred) -> Result) -> Result { + if self.active.front() != Some(&observed.ordinal) { return Err(EIO); } + if self.fault_at == Some(observed.ordinal) { + self.quarantined = true; + self.terminal = Some((Arc::new(VmStatus), EIO)); + for &ordinal in self.active.iter() { defer(Deferred::Failed(ordinal))?; } + self.active.clear(); + return Ok(true); + } + self.active.pop_front(); + self.retired.push(observed.ordinal); + defer(Deferred::Retired(observed.ordinal))?; + Ok(true) + } + fn take_terminal(&mut self) -> Option<(Arc, i32)> { self.terminal.take() } +} + +struct Entry { + reservation: Reservation, pair: Option>, preparing: Option>, + borrowed_active: bool, borrowed_dependencies: Option, borrowed_switch: Option, + event_masks: [u64; 2], missed_event: bool, closed: bool, + pending_error: Option<(Arc, i32)>, pending_timeout: bool, growing: bool, +} +pub struct RenderState { entries: Vec>, replay: bool } +impl RenderState { +@@STATE@@ + fn replay_parked(&self) -> bool { self.replay } + fn collect_retired(&mut self, _slot: usize) -> Result { Ok(()) } +} +pub struct Registry { render: RenderState } +impl Registry { +@@REGISTRY@@ +} +struct Recovery { pending: bool } +impl Recovery { fn pending(&self) -> bool { self.pending } } +struct Init { stamps: Vec, recovery_state: AtomicU32 } +impl Init { fn stamp(&self, qid: u8) -> Result<&AtomicU32> { self.stamps.get(usize::from(qid)).ok_or(EIO) } } +struct Memory; +impl Memory { fn recovery_state(init: &Init) -> Result { Ok(init.recovery_state.load(Ordering::Relaxed)) } } +struct SharedStub { event_records: AtomicUsize } +impl SharedStub { fn queue_event_records(&self) { self.event_records.fetch_add(1, Ordering::Relaxed); } } +struct StateStub { shared: SharedStub } +struct Primary { state: StateStub } +pub struct Firmware { recovery: Recovery, queues: Registry, init: Init, primary: Primary, grow: bool, settled: Vec } +impl Firmware { +@@FIRMWARE@@ + fn render_grow_pending(&self) -> bool { self.grow } + fn render_grow_ready(&self) -> bool { false } + fn release_render_lists(&mut self) -> Result { Ok(()) } + fn with_render(&mut self, slot: usize, operation: impl FnOnce(&mut Pair, &mut Host) -> Result) -> Result { + let pair = self.queues.render.entries[slot].as_mut().and_then(|entry| entry.pair.as_mut()).ok_or(EIO)?; + operation(pair, &mut Host) + } + /// The production settlement fans a terminal out to its VM; here it is recorded. + fn settle_render_terminal(&mut self, slot: usize, _deferred: &mut DeferredBatch) -> Result { + let terminal = self.queues.render.entries[slot].as_mut().and_then(|entry| entry.pair.as_mut()) + .and_then(|pair| pair.take_terminal()); + if terminal.is_some() { self.settled.push(slot); } + Ok(terminal.is_some()) + } +} + +const OWNER: u64 = 3; +const FRAGMENT_QID: u8 = 21; + +fn pair(slot: u8, qids: [u8; 2], ordinals: &[u64]) -> Box { + Box::new(Pair { slot, qids, owner: OWNER, active: ordinals.iter().copied().collect(), retired: Vec::new(), + quarantined: false, terminal: None, fault_at: None }) +} +fn entry(slot: u8, qids: [u8; 2], ordinals: &[u64]) -> Entry { + Entry { reservation: Reservation { slot, ids: [Id(qids[0]), Id(qids[1])], owner: OWNER }, + pair: Some(pair(slot, qids, ordinals)), preparing: None, borrowed_active: false, + borrowed_dependencies: None, borrowed_switch: None, event_masks: [0; 2], missed_event: false, + closed: false, pending_error: None, pending_timeout: false, growing: false } +} +fn firmware(entries: Vec>) -> Firmware { + Firmware { recovery: Recovery { pending: false }, queues: Registry { render: RenderState { entries, replay: false } }, + init: Init { stamps: (0..128).map(|_| AtomicU32::new(0)).collect(), recovery_state: AtomicU32::new(0) }, + primary: Primary { state: StateStub { shared: SharedStub { event_records: AtomicUsize::new(0) } } }, + grow: false, settled: Vec::new() } +} +/// The GPU finished every command below `through` on `qids`. +fn complete(fw: &Firmware, qids: [u8; 2], through: u32) { + for qid in qids { fw.init.stamp(qid).unwrap().store(through, Ordering::Release); } +} +fn mask(qid: u8) -> [u64; 2] { + let mut masks = [0u64; 2]; + masks[usize::from(qid) / 64] |= 1u64 << (qid % 64); + masks +} +fn retired(batch: &mut DeferredBatch) -> Vec { + batch.finish().into_iter().map(|d| match d { Deferred::Retired(o) => o, Deferred::Failed(o) => 1000 + o }).collect() +} +fn packet(ordinal: u64) -> Arc { Arc::new(Packet { context: Arc::new(Context), ordinal }) } +/// The direct path's loan: the production take_pair(), a publication, the production return_pair(). +fn lend(fw: &mut Firmware, slot: u8, ordinal: u64) -> Box { + fw.queues.render.take_pair(slot, OWNER, &packet(ordinal)).unwrap() +} +fn put_back(fw: &mut Firmware, slot: u8, mut lent: Box) -> bool { + let mut lent = Some(lent); + fw.queues.render.return_pair(slot, &mut lent).unwrap(); + fw.queues.render.take_missed_event(slot) +} + +fn main() { +@@STRUCTURE@@ + + let qids = [20u8, FRAGMENT_QID]; + // (a, b) One owner publishing a run of passes into slot 1 while the GPU finishes earlier ones. + let mut fw = firmware(vec![None, Some(entry(1, qids, &[0, 1, 2]))]); + let mut worker = DeferredBatch::new(64); + let mut collector = DeferredBatch::new(64); + let mut next = 3u64; + for done in 1..=3u32 { + let mut lent = lend(&mut fw, 1, next); + lent.active.push_back(next); + next += 1; + // The GPU finishes the front while the pair is lent; the event pass skips it and records + // the completion for its borrower. + complete(&fw, qids, done); + let matched = fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + assert_eq!(matched, mask(FRAGMENT_QID)); + assert!(!fw.queues.render_needs_rescan(), "a completion owed to the borrower needs no rescan"); + assert_eq!(fw.try_fast_observe_render(&mut worker), Ok(FastRenderOutcome::Idle), + "the event pass ends in its first hold"); + assert!(retired(&mut worker).is_empty()); + // The return observes it in the same hold: retired, in order; later passes stay in flight. + assert!(put_back(&mut fw, 1, lent), "the completion is owed"); + assert_eq!(fw.observe_returned_render(1, &mut collector), Ok(FastRenderOutcome::Rescan)); + assert_eq!(retired(&mut collector), vec![u64::from(done) - 1], "retired by the return of its loan"); + } + // Two completions during one loan are both retired by its return. + let mut lent = lend(&mut fw, 1, next); + lent.active.push_back(next); + complete(&fw, qids, 5); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + assert!(put_back(&mut fw, 1, lent)); + assert_eq!(fw.observe_returned_render(1, &mut collector), Ok(FastRenderOutcome::Rescan)); + assert_eq!(retired(&mut collector), vec![3, 4]); + // The GPU drains: the event worker retires the rest and clears the masks. + complete(&fw, qids, 7); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + assert_eq!(fw.try_fast_observe_render(&mut worker), Ok(FastRenderOutcome::Done)); + assert_eq!(retired(&mut worker), vec![5, 6]); + assert_eq!(fw.queues.render.entries[1].as_ref().unwrap().event_masks, [0; 2]); + assert_eq!(fw.queues.render.entries[1].as_ref().unwrap().pair.as_ref().unwrap().retired, (0..7).collect::>()); + // Nothing in flight, nothing missed. + let lent = lend(&mut fw, 1, 7); + assert!(!put_back(&mut fw, 1, lent)); + assert_eq!(fw.observe_returned_render(1, &mut collector), Ok(FastRenderOutcome::Idle)); + + // (a) A completion noted before the loan (no missed record) still asks for a rescan. + let mut fw = firmware(vec![None, Some(entry(1, qids, &[0]))]); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + let lent = lend(&mut fw, 1, 1); + assert!(fw.queues.render_needs_rescan(), "noted before the loan: the rescan stays"); + assert_eq!(fw.try_fast_observe_render(&mut worker), Ok(FastRenderOutcome::Rescan)); + put_back(&mut fw, 1, lent); + + // (b) The returned slot only: another owner's ready pair in slot 2 stays with the worker. + let other = [30u8, 31]; + let mut fw = firmware(vec![None, Some(entry(1, qids, &[0])), Some(entry(2, other, &[0]))]); + let lent = lend(&mut fw, 1, 1); + complete(&fw, qids, 1); + complete(&fw, other, 1); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + fw.queues.retain_render_completions(mask(31)); + assert!(put_back(&mut fw, 1, lent)); + assert_eq!(fw.observe_returned_render(1, &mut collector), Ok(FastRenderOutcome::Rescan)); + assert_eq!(retired(&mut collector), vec![0], "only the returned slot is observed"); + assert_eq!(fw.queues.render.entries[2].as_ref().unwrap().pair.as_ref().unwrap().active.len(), 1, + "the other slot is left to the event worker"); + assert_eq!(fw.try_fast_observe_render(&mut worker), Ok(FastRenderOutcome::Done)); + assert_eq!(retired(&mut worker), vec![0]); + + // (b) Every state the worker's fast path leaves to its full pass is left to it here too. + for case in 0..7 { + let mut fw = firmware(vec![None, Some(entry(1, qids, &[0, 1])), Some(entry(2, other, &[]))]); + let lent = lend(&mut fw, 1, 2); + complete(&fw, qids, 2); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + assert!(put_back(&mut fw, 1, lent)); + let mut room = 64; + { + let e2 = fw.queues.render.entries[2].as_mut().unwrap(); + match case { + 0 => e2.pending_error = Some((Arc::new(VmStatus), EIO)), + 1 => e2.pending_timeout = true, + 2 => e2.closed = true, + 3 => e2.growing = true, + 4 => fw.queues.render.replay = true, + 5 => fw.recovery.pending = true, + _ => room = 1, + } + } + let mut small = DeferredBatch::new(room); + assert_eq!(fw.observe_returned_render(1, &mut small), Ok(FastRenderOutcome::Fallback), "case {} falls back", case); + assert!(retired(&mut small).is_empty(), "case {} retires nothing", case); + } + // A fault is settled in the same hold, then left to the worker's full pass. + let mut fw = firmware(vec![None, Some(entry(1, qids, &[0, 1]))]); + let lent = lend(&mut fw, 1, 2); + complete(&fw, qids, 1); + fw.queues.render.entries[1].as_mut().unwrap().preparing.as_ref().unwrap(); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + let mut lent = lent; + lent.fault_at = Some(0); + assert!(put_back(&mut fw, 1, lent)); + assert_eq!(fw.observe_returned_render(1, &mut collector), Ok(FastRenderOutcome::Fallback)); + assert_eq!(fw.settled, vec![1], "the terminal is settled, not dropped"); + assert_eq!(retired(&mut collector), vec![1000, 1001]); + + // (c) Three threads: a publisher lending and returning slot 1, the event worker, the GPU. + const PASSES: u64 = 4000; + let fw = Arc::new(Mutex::new(firmware(vec![None, Some(entry(1, qids, &[]))]))); + let collector = Arc::new(Mutex::new(DeferredBatch::new(256))); + let published = Arc::new(AtomicU64::new(0)); + let events = Arc::new(AtomicU64::new(0)); + let stop = Arc::new(AtomicBool::new(false)); + let by_return = Arc::new(AtomicU64::new(0)); + let gpu_done = Arc::new(AtomicU64::new(0)); + let worker_seen = Arc::new(AtomicU64::new(0)); + let signalled = Arc::new(Mutex::new(Vec::::new())); + let gpu = { + let (fw, published, events, stop, gpu_done) = + (fw.clone(), published.clone(), events.clone(), stop.clone(), gpu_done.clone()); + std::thread::spawn(move || { + let mut done = 0u64; + while !stop.load(Ordering::Acquire) || done < published.load(Ordering::Acquire) { + let target = published.load(Ordering::Acquire); + if done < target { + done += 1; + complete(&fw.lock().unwrap(), qids, done as u32); + gpu_done.store(done, Ordering::Release); + events.fetch_add(1, Ordering::Release); + } + std::thread::yield_now(); + } + }) + }; + let worker = { + let (fw, events, stop, signalled, published, worker_seen) = + (fw.clone(), events.clone(), stop.clone(), signalled.clone(), published.clone(), worker_seen.clone()); + std::thread::spawn(move || { + let mut seen = 0u64; + let mut batch = DeferredBatch::new(256); + loop { + let pending = events.load(Ordering::Acquire); + let requested = { + let fw = fw.lock().unwrap(); + fw.primary.state.shared.event_records.swap(0, Ordering::AcqRel) + }; + if pending == seen && requested == 0 { + if stop.load(Ordering::Acquire) { + let fw = fw.lock().unwrap(); + let e = fw.queues.render.entries[1].as_ref().unwrap(); + if e.pair.as_ref().is_some_and(|p| p.active.is_empty()) { break; } + drop(fw); + events.fetch_add(1, Ordering::Release); + } + std::thread::yield_now(); + continue; + } + seen = pending; + // One hold of the pass; its fences signal after it, as the full pass's + // observe_renders() does per hold, and a ready observation left behind (a + // full collector) gets the next hold. + let again = { + let mut fw = fw.lock().unwrap(); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + match fw.try_fast_observe_render(&mut batch).unwrap() { + FastRenderOutcome::Fallback => fw.next_render_observation(1).unwrap().is_some(), + // The rescan poll requests another pass. + FastRenderOutcome::Rescan => { + fw.primary.state.shared.queue_event_records(); + false + } + _ => false, + } + }; + if again { + events.fetch_add(1, Ordering::Release); + } + worker_seen.store(seen, Ordering::Release); + signalled.lock().unwrap().extend(retired(&mut batch)); + } + }) + }; + { + let (fw, collector, published, signalled, by_return) = + (fw.clone(), collector.clone(), published.clone(), signalled.clone(), by_return.clone()); + for ordinal in 0..PASSES { + let mut lent = lend(&mut fw.lock().unwrap(), 1, ordinal); + lent.active.push_back(ordinal); + published.store(ordinal + 1, Ordering::Release); + for _ in 0..(ordinal % 7) { std::thread::yield_now(); } + if ordinal % 16 == 0 { + // Keep this loan until the GPU finished its command and the event pass met the + // lent pair: the return then owes, and makes, that observation. + while gpu_done.load(Ordering::Acquire) <= ordinal { std::thread::yield_now(); } + let event = events.load(Ordering::Acquire); + while worker_seen.load(Ordering::Acquire) < event { std::thread::yield_now(); } + } + let mut held = None; + { + let mut fw = fw.lock().unwrap(); + if put_back(&mut fw, 1, lent) { + held = collector.try_lock().ok(); + let outcome = match held.as_deref_mut() { + Some(batch) => fw.observe_returned_render(1, batch).unwrap(), + None => FastRenderOutcome::Fallback, + }; + // Fallback requests the pass, Rescan the poll that requests it. + if matches!(outcome, FastRenderOutcome::Fallback | FastRenderOutcome::Rescan) { + fw.primary.state.shared.queue_event_records(); + } + } + } + if let Some(batch) = held.as_deref_mut() { + let done = retired(batch); + by_return.fetch_add(done.len() as u64, Ordering::Relaxed); + signalled.lock().unwrap().extend(done); + } + } + } + stop.store(true, Ordering::Release); + gpu.join().unwrap(); + worker.join().unwrap(); + let fw = fw.lock().unwrap(); + let pair = fw.queues.render.entries[1].as_ref().unwrap().pair.as_ref().unwrap(); + assert_eq!(pair.retired, (0..PASSES).collect::>(), "every command retires once, in order"); + let mut all = signalled.lock().unwrap().clone(); + all.sort_unstable(); + assert_eq!(all, (0..PASSES).collect::>(), "every completion is signalled exactly once"); + assert!(by_return.load(Ordering::Relaxed) > 0, "returns retire what arrived during their loans"); + + println!("PASS g17-render-return-observe: completions of a lent pair are retired by its return"); +} +''' + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + source = build(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-render-return-') as tmp: + path = Path(tmp) / 'observe.rs' + binary = path.with_suffix('') + path.write_text(source) + built = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '-O', str(path), + '-o', str(binary)], capture_output=True, text=True) + if built.returncode: + sys.stderr.write(built.stderr) + return built.returncode + run = subprocess.run([str(binary)], capture_output=True, text=True, timeout=600) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-rescan-poll-tests.py b/tools/asahi/g17-rescan-poll-tests.py new file mode 100755 index 00000000000000..db85177a8af98e --- /dev/null +++ b/tools/asahi/g17-rescan-poll-tests.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: G17 event rescan uses a sub-ms hrtimer and never starves pending event rings. + +Verifies: +1. Compiled production `Shared::queue_poll()`, `Shared::cancel_rescan()`, + `Shared::disable_rescan()`, and `HrTimerCallback::run()` from + `drivers/gpu/drm/asahi/g17/mod.rs`: + - `queue_poll()` arms the hrtimer for a sub-millisecond delay (`<= 100 us`), + coalesces duplicate calls while the deadline is still in the future without + acquiring `rescan_handle`, and re-arms once expired or cleared; + - `HrTimerCallback::run()` clears `rescan_deadline_ns`, queues + `queue_event_records()` when active, skips queuing when sleeping, stopped, + or crashed, and returns `HrTimerRestart::NoRestart`; + - `cancel_rescan()` and `disable_rescan()` drop the handle and clear the + deadline, and `disable_rescan()` blocks any later `queue_poll()`. +2. Structural checks on `runtime/events.rs`, `mod.rs`, `sleep.rs`, and `runtime.rs`: + - Neither the fast path nor the slow path of `runtime_event_turn()` gates + `channel::Events::pending()` behind `!polling` / `else if`; + - Both paths still arm `queue_poll_after(1)` when `render_control_backpressured()` + is true so the 1 ms retry budget on `POLL_WORK` is preserved; + - `join_event_workers()`, `stop_runtime()`, and `shutdown()` cancel or disable + the rescan hrtimer. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +MUTATIONS = { + 'starve-fast-pending': [( + 'events', + ' if polling {\n' + ' self.queue_poll();\n' + ' if firmware.render_control_backpressured() {\n' + ' self.queue_poll_after(1);\n' + ' }\n' + ' }\n' + ' if channel::Events::pending(&firmware.init, Role::Primary)?', + ' if polling {\n' + ' self.queue_poll();\n' + ' if firmware.render_control_backpressured() {\n' + ' self.queue_poll_after(1);\n' + ' }\n' + ' } else if channel::Events::pending(&firmware.init, Role::Primary)?', + )], + 'starve-slow-pending': [( + 'events', + ' } else if !recover\n' + ' && (channel::Events::pending(&firmware.init, Role::Primary)?', + ' } else if !recover\n' + ' && !polling\n' + ' && (channel::Events::pending(&firmware.init, Role::Primary)?', + )], + 'jiffy-poll': [( + 'mod', + 'const RESCAN_POLL_US: i64 = 50;', + 'const RESCAN_POLL_US: i64 = 4_000;', + )], + 'skip-backpressure-poll': [( + 'events', + ' if firmware.render_control_backpressured() {\n' + ' self.queue_poll_after(1);\n' + ' }', + '', + )], + 'skip-sleep-cancel': [( + 'sleep', + ' self.cancel_rescan();\n', + '', + )], + 'skip-shutdown-disable': [( + 'mod', + ' self.shared.disable_rescan();\n', + '', + )], +} + + +def build_harness(mutation=None): + files = { + 'mod': (G17 / 'mod.rs').read_text(), + 'events': (G17 / 'runtime/events.rs').read_text(), + 'sleep': (G17 / 'sleep.rs').read_text(), + 'runtime': (G17 / 'runtime.rs').read_text(), + } + for name, old, new in MUTATIONS.get(mutation, []): + assert files[name].count(old) == 1, (mutation, name) + files[name] = files[name].replace(old, new, 1) + + mod_src = files['mod'] + events_src = files['events'] + sleep_src = files['sleep'] + runtime_src = files['runtime'] + + queue_poll_fn = item(mod_src, 'fn queue_poll(self: &Arc)') + cancel_fn = item(mod_src, 'fn cancel_rescan(&self)') + disable_fn = item(mod_src, 'fn disable_rescan(&self)') + hrtimer_cb = item(mod_src, 'impl HrTimerCallback for Shared') + turn_fn = item(events_src, 'fn runtime_event_turn(') + join_fn = item(sleep_src, 'fn join_event_workers(self: &Arc)') + stop_fn = item(runtime_src, 'pub(super) fn stop_runtime(&self)') + shutdown_fn = item(mod_src, 'pub(crate) fn shutdown(&self)') + + fast_pending_unblocked = ( + '} else if channel::Events::pending(&firmware.init, Role::Primary)?' not in turn_fn + and 'if channel::Events::pending(&firmware.init, Role::Primary)?' in turn_fn + ) + slow_pending_unblocked = ( + '&& !polling\n && (channel::Events::pending(&firmware.init, Role::Primary)?' + not in turn_fn + and '} else if !recover\n && (channel::Events::pending(&firmware.init, Role::Primary)?' + in turn_fn + ) + backpressure_preserved = ( + turn_fn.count('if firmware.render_control_backpressured() {\n') == 2 + and turn_fn.count('self.queue_poll_after(1);') == 2 + ) + lifecycle_ok = ( + 'self.cancel_rescan();' in join_fn + and 'self.disable_rescan();' in stop_fn + and 'self.shared.disable_rescan();' in shutdown_fn + ) + + host_queue_poll = queue_poll_fn.replace('self.rescan_handle.lock()', 'self.lock_handle()') + host_cancel = cancel_fn.replace('self.rescan_handle.lock()', 'self.lock_handle()') + + return f''' +#![allow(dead_code, unused_variables, unused_imports)] +use std::sync::{{Arc, Mutex, MutexGuard, atomic::{{AtomicBool, AtomicU64, AtomicUsize, Ordering}}}}; + +static NOW_NS: AtomicU64 = AtomicU64::new(1_000_000); +fn now_ns() -> u64 {{ NOW_NS.load(Ordering::Acquire) }} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Delta(i64); +impl Delta {{ + fn from_micros(us: i64) -> Self {{ Self(us) }} +}} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum HrTimerRestart {{ NoRestart, Restart }} + +struct ArcBorrow<'a, T>(&'a Arc); +impl<'a, T> From> for Arc {{ + fn from(b: ArcBorrow<'a, T>) -> Self {{ Arc::clone(b.0) }} +}} +struct HrTimerCallbackContext<'a, T>(std::marker::PhantomData<&'a T>); +trait HrTimerCallback {{ + type Pointer<'a>; + fn run(this: ArcBorrow<'_, Self>, ctx: HrTimerCallbackContext<'_, Self>) -> HrTimerRestart + where Self: Sized; +}} + +struct ArcHrTimerHandle {{ + shared: Arc, + delay_us: i64, + cancelled: Arc, +}} +impl Drop for ArcHrTimerHandle {{ + fn drop(&mut self) {{ + self.cancelled.fetch_add(1, Ordering::AcqRel); + }} +}} + +struct Shared {{ + submission_enabled: bool, + sleeping_flag: AtomicBool, + rescan_stopped: AtomicBool, + crashed: AtomicBool, + rescan_deadline_ns: AtomicU64, + rescan_handle: Mutex>>, + lock_trips: AtomicUsize, + starts: AtomicUsize, + last_delay_us: AtomicU64, + cancelled: Arc, + event_records: AtomicUsize, +}} + +impl Shared {{ + fn new() -> Arc {{ + Arc::new(Self {{ + submission_enabled: true, + sleeping_flag: AtomicBool::new(false), + rescan_stopped: AtomicBool::new(false), + crashed: AtomicBool::new(false), + rescan_deadline_ns: AtomicU64::new(0), + rescan_handle: Mutex::new(None), + lock_trips: AtomicUsize::new(0), + starts: AtomicUsize::new(0), + last_delay_us: AtomicU64::new(0), + cancelled: Arc::new(AtomicUsize::new(0)), + event_records: AtomicUsize::new(0), + }}) + }} + fn sleeping(&self) -> bool {{ self.sleeping_flag.load(Ordering::Acquire) }} + fn queue_event_records(self: &Arc) {{ + self.event_records.fetch_add(1, Ordering::AcqRel); + }} + fn lock_handle(&self) -> MutexGuard<'_, Option>> {{ + self.lock_trips.fetch_add(1, Ordering::AcqRel); + self.rescan_handle.lock().unwrap() + }} + fn start(self: Arc, delta: Delta) -> ArcHrTimerHandle {{ + self.starts.fetch_add(1, Ordering::AcqRel); + self.last_delay_us.store(delta.0 as u64, Ordering::Release); + let cancelled = Arc::clone(&self.cancelled); + ArcHrTimerHandle {{ shared: self, delay_us: delta.0, cancelled }} + }} + + {host_queue_poll} + + {host_cancel} + + {disable_fn} +}} + +{hrtimer_cb} + +fn main() {{ + assert!({str(fast_pending_unblocked).lower()}, "fast path starved pending events behind polling"); + assert!({str(slow_pending_unblocked).lower()}, "slow path starved pending events behind polling"); + assert!({str(backpressure_preserved).lower()}, "render_control_backpressured must still arm 1ms POLL_WORK"); + assert!({str(lifecycle_ok).lower()}, "sleep/stop/shutdown must cancel or disable rescan hrtimer"); + + let s = Shared::new(); + s.queue_poll(); + assert_eq!(s.starts.load(Ordering::Acquire), 1); + let delay = s.last_delay_us.load(Ordering::Acquire); + assert!(delay >= 10 && delay <= 100, "rescan hrtimer delay must be sub-ms (10..=100 us), got {{delay}}"); + assert_eq!(s.lock_trips.load(Ordering::Acquire), 1); + + // Coalescing while armed must skip rescan_handle lock completely. + NOW_NS.store(1_000_000 + delay * 500, Ordering::Release); + s.queue_poll(); + assert_eq!(s.starts.load(Ordering::Acquire), 1); + assert_eq!(s.lock_trips.load(Ordering::Acquire), 1); + + // Timer expiry clears deadline and queues event records without restarting. + let restart = Shared::run(ArcBorrow(&s), HrTimerCallbackContext(std::marker::PhantomData)); + assert_eq!(restart, HrTimerRestart::NoRestart); + assert_eq!(s.rescan_deadline_ns.load(Ordering::Acquire), 0); + assert_eq!(s.event_records.load(Ordering::Acquire), 1); + + // Re-arm after expiry succeeds and cancels old completed handle before starting. + s.queue_poll(); + assert_eq!(s.starts.load(Ordering::Acquire), 2); + assert_eq!(s.cancelled.load(Ordering::Acquire), 1); + + // Sleep cancels handle and prevents callback or queue_poll from arming. + s.sleeping_flag.store(true, Ordering::Release); + s.cancel_rescan(); + assert_eq!(s.cancelled.load(Ordering::Acquire), 2); + assert_eq!(s.rescan_deadline_ns.load(Ordering::Acquire), 0); + s.queue_poll(); + assert_eq!(s.starts.load(Ordering::Acquire), 2); + let _ = Shared::run(ArcBorrow(&s), HrTimerCallbackContext(std::marker::PhantomData)); + assert_eq!(s.event_records.load(Ordering::Acquire), 1); + + // Wake allows re-arming again. + s.sleeping_flag.store(false, Ordering::Release); + s.queue_poll(); + assert_eq!(s.starts.load(Ordering::Acquire), 3); + + // Shutdown disables permanently and breaks the Arc self-reference. + s.disable_rescan(); + assert_eq!(s.cancelled.load(Ordering::Acquire), 3); + assert_eq!(Arc::strong_count(&s), 1); + s.queue_poll(); + assert_eq!(s.starts.load(Ordering::Acquire), 3); + let _ = Shared::run(ArcBorrow(&s), HrTimerCallbackContext(std::marker::PhantomData)); + assert_eq!(s.event_records.load(Ordering::Acquire), 1); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = parser.parse_args() + src = build_harness(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-rescan-poll-') as tmp: + rs = Path(tmp) / 'test.rs' + exe = Path(tmp) / 'test' + rs.write_text(src) + subprocess.run(['rustc', '-O', str(rs), '-o', str(exe)], check=True) + res = subprocess.run([str(exe)], capture_output=True, text=True) + if res.returncode != 0: + sys.stderr.write(res.stdout + res.stderr) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-resource-tests.py b/tools/asahi/g17-resource-tests.py index 560f15a9b92da0..31d24d19afee27 100644 --- a/tools/asahi/g17-resource-tests.py +++ b/tools/asahi/g17-resource-tests.py @@ -21,8 +21,8 @@ def item(start): return s[at:end] constants='\n'.join(re.search(r'pub\(crate\) const '+name+r': [^;]+;',cfg).group(0) for name in ['RENDER_SLOTS','RENDER_PAIRS_MAX','RENDER_DEPTH']) pairs=(source/'g17/pairs.rs').read_text() - assert 'const G17D_PAIRS: u8 = RENDER_PAIRS_MAX as u8;' in pairs - assert 'PAIRS.store(if board.g17d_forms() { G17D_PAIRS } else { 1 }, Relaxed);' in pairs + assert 'const MULTI_PAIRS: u8 = RENDER_PAIRS_MAX as u8;' in pairs + assert 'if board.clusters >= 4 {' in pairs at=pairs.index('const SIBLING_BACKLOG');backlog=pairs[at:pairs.index('\n}\n',pairs.index('fn sibling_backlog',at))+3] mmu=(source/'mmu.rs').read_text() limits='\n'.join(re.search(r'const '+name+r': [^;]+;',mmu).group(0) for name in ['EXECUTION_CONTEXT_MASK','MAX_EXECUTION_CONTEXTS']) @@ -39,7 +39,7 @@ def item(start): macro_rules! resource_exhausted { ($s:literal)=>{ENOSPC}; } type KVec = Vec; struct InFlight; mod cfg {\n'''+constants+'}\n'+limits+'\n' - methods=['const fn new','fn exhausted','fn owner_quarantine','fn refusal','fn advance','fn take_idle','fn acquire','fn usable','fn claim_sibling','fn reassign_unused_spare','fn warmable_sibling','fn borrow_warm_sibling','fn cancel_empty_slot','fn release'] + methods=['const fn new','fn owns_live','fn has_live_owner','fn live_owners','fn live_siblings','fn reclaimable_siblings_in','fn reclaimable_siblings(','fn promotes_reclaimable_sibling','fn can_lease_slot','fn exhausted','fn owner_quarantine','fn refusal','fn advance','fn set_owner','fn take_idle','fn acquire(','fn acquire_for','fn unavailable_released','fn total_pair_demand','fn pair_demand','fn usable','fn claim_sibling','fn can_reassign_unused_spare','fn reassign_unused_spare','fn release_unused_sibling','fn reclaim_sibling','fn warmable_sibling','fn borrow_warm_sibling','fn cancel_empty_slot','fn release('] code=header+item('struct State')+'\nimpl State {\n'+re.search(r' const MASK: u64 = .*;',s).group(0)+'\n'+'\n'.join(item(n) for n in methods)+'\n}\n'+''' // A queue holds g17::pairs::per_owner() pairs (Backend::pairs): one, or // RENDER_PAIRS_MAX on G17D. Both admissions run. @@ -177,7 +177,7 @@ def item(s,start): #[derive(Clone,Copy,PartialEq,Eq,Debug)] enum DataMaster {Compute,Tiling,Fragment} #[derive(Clone,Copy,PartialEq,Eq,Debug)] struct Id {qid:u8,owner:u64,engine:DataMaster} #[derive(Clone,Copy)] struct Identity {id:Id,published:bool} - '''+constants+'\n'+item(s,'const fn render_reserve(')+'\n'+item(s,'pub(crate) struct QueueIds')+'\nimpl QueueIds {\n'+''.join(item(s,'pub(crate) fn '+name+'(')+'\n' for name in ['reserve_initial_render','reserve','reserve_for','publish','can_cancel_unpublished','cancel_unpublished'])+''.join(item(s, sig)+'\n' for sig in ['fn render_ids(', 'fn compute_room('])+'}\n' + '''+constants+'\n'+item(s,'const fn render_reserve(')+'\n'+item(s,'const fn queue_limit(')+'\n'+item(s,'pub(crate) struct QueueIds')+'\nimpl QueueIds {\n'+''.join(item(s,'pub(crate) fn '+name+'(')+'\n' for name in ['reserve_initial_render','reserve','reserve_for','publish','can_cancel_unpublished','cancel_unpublished'])+''.join(item(s, sig)+'\n' for sig in ['fn render_ids(', 'fn compute_room('])+'}\n' test=''' fn fresh()->QueueIds {QueueIds {entries:[None;QID_COUNT],initial_render:[None;2],leased:0,floor:0}} fn main(){ diff --git a/tools/asahi/g17-t6041-initdata-tests.py b/tools/asahi/g17-t6041-initdata-tests.py index f2459ce46bb7f2..f532332f7c6cfb 100644 --- a/tools/asahi/g17-t6041-initdata-tests.py +++ b/tools/asahi/g17-t6041-initdata-tests.py @@ -112,7 +112,8 @@ def item(source, start): "const CHIP_25G83: ", "const HW_DATA_WORDS: ", "const HW_DATA_WORDS_25G83: ", - "const POWER_CONFIG_WORDS", + "const POWER_CONFIG_WORDS: ", + "const POWER_CONFIG_WORDS_25G83: ", ] J616C_ITEMS = [ @@ -226,7 +227,15 @@ def aux(name, rows): let (hw_g83, power_g83, region_g83) = build(t6041::CHIP_ID, &t6041::REGISTER_WINDOWS_25G83, &[], &t6041::PERF, &T6041_OPPS, &T6041_AUX, &t6041::CHIP_25G83, &t6041::REGION_C, 40); println!("T6041 25G83 initialization objects built"); - assert_eq!(power_g83, power, "the register map changes only the hardware data"); + // The power configuration keeps the 25G83 starting values of the performance limiter. + let word = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()); + let changed = (0..power.len() / 4).map(|i| 4 * i) + .filter(|&at| word(&power, at) != word(&power_g83, at)).collect::>(); + assert_eq!(changed, [0x0, 0x44, 0x9c], "25G83 power configuration: only the limiter start"); + assert_eq!([word(&power, 0x0), word(&power, 0x44), word(&power, 0x9c)], [1, 0xc, 0x43a9_0000], + "25F84 limiter state"); + assert_eq!([word(&power_g83, 0x0), word(&power_g83, 0x44), word(&power_g83, 0x9c)], [0, 1, 0], + "25G83 limiter start"); assert_eq!(region_g83, region, "the register map changes only the hardware data"); let map = 0x640..0x640 + REGISTER_MAP_SLOTS * core::mem::size_of::(); let outside = |a: &[u8], b: &[u8]| a.iter().zip(b).enumerate() diff --git a/tools/asahi/g17-telemetry-integration-tests.py b/tools/asahi/g17-telemetry-integration-tests.py index 10bd7cb7d863e7..2522db9d5e076d 100755 --- a/tools/asahi/g17-telemetry-integration-tests.py +++ b/tools/asahi/g17-telemetry-integration-tests.py @@ -146,18 +146,30 @@ def item(source, signature): impl State { fn lock(&self)->std::sync::MutexGuard<'_,Option>> { self.0.lock().unwrap() } } - struct Variant { graph:fw::variant::InitGraph, m5_commands:bool } + struct Variant { graph:fw::variant::InitGraph, telemetry_protocol:telemetry::Protocol } struct Shared { state:State, dev:crate::device::Device, variant:Variant, crashed:std::sync::atomic::AtomicBool } mod reports; ''' RUST_TESTS = r''' - fn reader(graph:fw::variant::InitGraph)->stats::Reader { + fn default_protocol(graph:fw::variant::InitGraph)->telemetry::Protocol { + match graph { + fw::variant::InitGraph::G17P=>telemetry::Protocol::PSTATE_16MS, + fw::variant::InitGraph::V25G83=>telemetry::Protocol::NONE, + } + } + + fn reader_with(graph:fw::variant::InitGraph,protocol:telemetry::Protocol,frequencies:Option)->stats::Reader { + let max_pstate=frequencies.as_ref().map_or(0,stats::StateFrequencies::max_pstate); stats::Reader(std::sync::Arc::new(Shared { state:State(std::sync::Mutex::new(Some(Box::new(Firmware { - rings:channel::Rings::new(graph,false).unwrap(), + rings:channel::Rings::new(graph,protocol,max_pstate).unwrap(), init:initdata::InitData::new(),powered:true,epoch:0,recovery:Recovery(false), - })))),dev:crate::device::Device,variant:Variant { graph, m5_commands:false },crashed:false.into(), - }),None) + })))),dev:crate::device::Device,variant:Variant { graph, telemetry_protocol:protocol },crashed:false.into(), + }),frequencies) + } + + fn reader(graph:fw::variant::InitGraph)->stats::Reader { + reader_with(graph,default_protocol(graph),None) } #[test] @@ -254,14 +266,14 @@ def item(source, signature): fn captured_histograms_are_preserved_without_inventing_pstate() { use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; - for graph in [InitGraph::V25G83,InitGraph::G17P] { + for (graph,protocol,max_pstate) in [(InitGraph::V25G83,telemetry::Protocol::NONE,0),(InitGraph::V25G83,telemetry::Protocol::PSTATE_8MS,10),(InitGraph::G17P,telemetry::Protocol::PSTATE_16MS,10)] { let init=initdata::InitData::new(); - let mut rings=Rings::new(graph,false).unwrap(); + let mut rings=Rings::new(graph,protocol,max_pstate).unwrap(); for words in [HIST_IDLE,HIST_ACTIVE,HIST_OTHER,TRANSITION] { init.push(Secondary,words); rings.drain_statistics(&dev,&init,Secondary); - // 26A428 integrates busy time from its utilisation records; none arrived. - let busy=match graph { InitGraph::G17P=>telemetry::VALID, _=>telemetry::UNSUPPORTED }; + // Protocols with a utilisation period integrate busy time; none arrived. + let busy=if protocol.util_period_ticks != 0 { telemetry::VALID } else { telemetry::UNSUPPORTED }; assert_eq!(rings.read_statistics(1),telemetry::Readout { busy_status:busy,..Default::default() }); assert!(report(&rings).contains(&format!("words={:08x?}",words))); } @@ -274,7 +286,7 @@ def item(source, signature): let dev=crate::device::Device; for start in [0,5,7] { let init=initdata::InitData::new(); - let mut rings=Rings::new(InitGraph::G17P,false).unwrap(); + let mut rings=Rings::new(InitGraph::G17P,telemetry::Protocol::PSTATE_16MS,10).unwrap(); for &role in &[Primary,Secondary] { for cursor in &init.cursors[role as usize] { cursor.store(start,Ordering::Relaxed); } for words in [HIST_OTHER,HIST_ACTIVE,TRANSITION] { init.push(role,words); } @@ -298,8 +310,8 @@ def item(source, signature): use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; let init=initdata::InitData::new(); - // The decoder's tag 0x10 path: only a firmware without 26A428's state records decodes it. - let mut rings=Rings::new(InitGraph::V25G83,false).unwrap(); + // The decoder's tag 0x10 path: only a firmware without 0x19/0x1b state records decodes it. + let mut rings=Rings::new(InitGraph::V25G83,telemetry::Protocol::NONE,0).unwrap(); let util=[0x13,0,0,8,97,0,97,0,0,0,0,0,0,0,0,0,0,0]; let pstate=[0x10,0x2500,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0]; rings.observe_statistics_power(&dev,&init,&[Primary,Secondary],true,1); @@ -329,34 +341,97 @@ def item(source, signature): fn v25g83_reports_pstate_unsupported_and_keeps_utilisation() { use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; - // 26A428 reports its state on the A18 Pro and on M5; 25G83 never does. - assert!(!stats::reports_pstate(InitGraph::V25G83,false)); - assert!(stats::reports_pstate(InitGraph::G17P,false)); - assert!(stats::reports_pstate(InitGraph::G17P,true)); + // Protocols with reports_pstate emit tags 0x19/0x1b; Protocol::NONE does not. + assert!(!stats::reports_pstate(telemetry::Protocol::NONE)); + assert!(stats::reports_pstate(telemetry::Protocol::PSTATE_8MS)); + assert!(stats::reports_pstate(telemetry::Protocol::PSTATE_16MS)); let graph=InitGraph::V25G83; - let empty=stats::qualify(graph,false,telemetry::Readout::default()); + let empty=stats::qualify(telemetry::Protocol::NONE,telemetry::Readout::default()); assert_eq!((empty.util_status,empty.pstate_status),(telemetry::UNAVAILABLE,telemetry::UNSUPPORTED)); let init=initdata::InitData::new(); - let mut rings=Rings::new(graph,false).unwrap(); + let mut rings=Rings::new(graph,telemetry::Protocol::NONE,0).unwrap(); init.push(Primary,[0x13,0,0,8,97,0,97,0,0,0,0,0,0,0,0,0,0,0]); // Even a decodable tag 0x10 does not override the firmware's match data. init.push(Primary,[0x10,0x2500,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0]); rings.drain_statistics(&dev,&init,Primary); assert_eq!(rings.read_statistics(1).pstate_status,telemetry::VALID); - let view=stats::qualify(graph,false,rings.read_statistics(1)); + let view=stats::qualify(telemetry::Protocol::NONE,rings.read_statistics(1)); assert_eq!((view.util_status,view.device,view.pstate_status,view.pstate,view.pstate_timestamp), (telemetry::VALID,97,telemetry::UNSUPPORTED,0,0)); rings.invalidate_statistics(); - let view=stats::qualify(graph,false,rings.read_statistics(1)); + let view=stats::qualify(telemetry::Protocol::NONE,rings.read_statistics(1)); assert_eq!((view.util_status,view.pstate_status),(telemetry::STALE,telemetry::UNSUPPORTED)); } + #[test] + fn t6041_reports_its_state_and_busy_time_through_the_reader() { + use {fw::variant::InitGraph,Role::*}; + // J616C OPP frequencies mapped by PERF.states_a (states 0..=10). + let mhz=[0,338,618,796,924,1056,1182,1312,1380,1470,1578]; + let freqs=stats::StateFrequencies::new(mhz.into_iter()).unwrap(); + assert_eq!(freqs.max_pstate(),10); + let reader=reader_with(InitGraph::V25G83,telemetry::Protocol::PSTATE_8MS,Some(freqs)); + let push=|words|reader.0.state.lock().as_ref().unwrap().init.push(Primary,words); + // Safe fallback when no 0x1b arrives (e.g. a firmware that omits it): pstate unavailable, util still works. + push([0x13,100_000,0,20,40,0,50,0,0,0,0,0,0,0,0,0,0,0]); + let view=reader.read(); + assert_eq!((view.util_status,view.device,view.pstate_status,view.busy_status,view.busy_ns), + (telemetry::VALID,50,telemetry::UNAVAILABLE,telemetry::VALID,0)); + assert_eq!(reader.frequency(),Some((None,1_578_000_000))); + // 8 ms (192_000 ticks) at 50% -> 4 ms busy; 16 ms (384_000 ticks) at 100% -> +16 ms; after a + // >384_000 ticks gap only the record's own 8 ms period at 100% -> +8 ms. + push([0x13,100_000+192_000,0,20,40,0,50,0,0,0,0,0,0,0,0,0,0,0]); + push([0x13,100_000+192_000+384_000,0,100,100,0,100,0,0,0,0,0,0,0,0,0,0,0]); + push([0x13,100_000+192_000+384_000+384_001,0,100,100,0,100,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(reader.read().busy_ns,28_000_000); + // Tag 0x10 is ignored when Protocol::PSTATE_8MS is active. + push([0x10,0x2500,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(reader.read().pstate_status,telemetry::UNAVAILABLE); + // Tag 0x19 + 0x1b report state 10 -> 1578 MHz. + push([0x19,0x2000,0x40,0x1000,0x40,0,0,0,0,0,0,0,0,0,0,0,0,0]); + push([0x1b,10,0,10,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); + let view=reader.read(); + assert_eq!((view.pstate_status,view.pstate,view.pstate_timestamp,view.achieved_frequency_hz), + (telemetry::VALID,10,0x40_0000_2000,1_578_000_000)); + assert_eq!(reader.frequency(),Some((Some(1_578_000_000),1_578_000_000))); + // Mismatched words[1] != words[3], state 0, or state beyond derived max_pstate (10) -> UNAVAILABLE. + for (a,b) in [(4,10),(0,0),(11,11),(13,13)] { + push([0x1b,a,0,b,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(reader.read().pstate_status,telemetry::UNAVAILABLE); + assert_eq!(reader.frequency(),Some((None,1_578_000_000))); + } + // Recover to valid state 1 -> 338 MHz. + push([0x1b,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(reader.read().achieved_frequency_hz,338_000_000); + // Gated cores -> state 0, 0 Hz. + reader.0.state.lock().as_mut().unwrap().powered=false; + let view=reader.read(); + assert_eq!((view.pstate_status,view.pstate,view.achieved_frequency_hz),(telemetry::VALID,0,0)); + assert_eq!(reader.frequency(),Some((Some(0),1_578_000_000))); + // Power-up -> STALE until next report. + reader.0.state.lock().as_mut().unwrap().powered=true; + assert_eq!(reader.read().pstate_status,telemetry::STALE); + assert_eq!(reader.frequency(),Some((None,1_578_000_000))); + // Same Protocol::PSTATE_8MS with a 14-state table (M5) derives max_pstate 13; without a table it fails closed. + let m5_mhz=[0,338,492,618,740,860,980,1100,1200,1300,1400,1470,1540,1620]; + let m5_freqs=stats::StateFrequencies::new(m5_mhz.into_iter()).unwrap(); + assert_eq!(m5_freqs.max_pstate(),13); + let m5_reader=reader_with(InitGraph::G17P,telemetry::Protocol::PSTATE_8MS,Some(m5_freqs)); + m5_reader.0.state.lock().as_ref().unwrap().init.push(Primary,[0x1b,13,0,13,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(m5_reader.read().achieved_frequency_hz,1_620_000_000); + m5_reader.0.state.lock().as_ref().unwrap().init.push(Primary,[0x1b,14,0,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(m5_reader.read().pstate_status,telemetry::UNAVAILABLE); + let closed=reader_with(InitGraph::V25G83,telemetry::Protocol::PSTATE_8MS,None); + closed.0.state.lock().as_ref().unwrap().init.push(Primary,[0x1b,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(closed.read().pstate_status,telemetry::UNAVAILABLE); + } + #[test] fn a18_pro_reports_its_state_through_the_reader() { use {fw::variant::InitGraph,Role::*}; // States 0 to 10; an interval record, then the state in words 1 and 3. let mhz=[0,338,492,618,796,928,1056,1170,1278,1338,1470]; - let reader=stats::Reader(reader(InitGraph::G17P).0,stats::StateFrequencies::new(mhz.into_iter())); + let reader=reader_with(InitGraph::G17P,telemetry::Protocol::PSTATE_16MS,stats::StateFrequencies::new(mhz.into_iter())); let push=|words|reader.0.state.lock().as_ref().unwrap().init.push(Secondary,words); // Tag 0x10 is not this firmware's state report. push([0x10,0x2500,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0]); @@ -389,7 +464,7 @@ def item(source, signature): use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; let init=initdata::InitData::new(); - let mut rings=Rings::new(InitGraph::V25G83,false).unwrap(); + let mut rings=Rings::new(InitGraph::V25G83,telemetry::Protocol::NONE,0).unwrap(); let util=[0x13,0,0,8,97,0,97,0,0,0,0,0,0,0,0,0,0,0]; // Three 8 ms records per producer update, one update every 24 ms. for n in 0..3u64 { @@ -409,7 +484,7 @@ def item(source, signature): use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; let init=initdata::InitData::new(); - let mut rings=Rings::new(InitGraph::G17P,false).unwrap(); + let mut rings=Rings::new(InitGraph::G17P,telemetry::Protocol::PSTATE_16MS,10).unwrap(); rings.observe_statistics_power(&dev,&init,&[Primary,Secondary],false,0); init.push(Secondary,HIST_IDLE); rings.drain_statistics(&dev,&init,Secondary); @@ -429,13 +504,13 @@ def item(source, signature): let graph=InitGraph::G17P; let dev=crate::device::Device; let init=initdata::InitData::new(); - let mut rings=Rings::new(graph,false).unwrap(); + let mut rings=Rings::new(graph,telemetry::Protocol::PSTATE_16MS,10).unwrap(); init.push(Secondary,HIST_IDLE); rings.observe_statistics_power(&dev,&init,&[Primary,Secondary],true,1); init.push(Secondary,HIST_ACTIVE); let shared=std::sync::Arc::new(Shared { state:State(std::sync::Mutex::new(Some(Box::new(Firmware { rings,init:initdata::InitData::new(),powered:true,epoch:0,recovery:Recovery(false), - })))),dev,variant:Variant { graph, m5_commands:false },crashed:false.into() }); + })))),dev,variant:Variant { graph, telemetry_protocol:telemetry::Protocol::PSTATE_16MS },crashed:false.into() }); let view=reports::View(shared.clone()); struct View<'a>(&'a reports::View); impl std::fmt::Display for View<'_> { @@ -453,7 +528,7 @@ def item(source, signature): use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; let init=initdata::InitData::new(); - let mut rings=Rings::new(InitGraph::G17P,false).unwrap(); + let mut rings=Rings::new(InitGraph::G17P,telemetry::Protocol::PSTATE_16MS,10).unwrap(); let sample=|ta,render,device|[0x13,0,0,ta,render,0xdeadbeef,device,0,0,0,0,0,0,0,0,0,0,0]; init.push(Primary,sample(25,75,50)); init.push(Secondary,sample(35,85,65)); @@ -477,7 +552,7 @@ def item(source, signature): use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; let init=initdata::InitData::new(); - let mut rings=Rings::new(InitGraph::V25G83,false).unwrap(); + let mut rings=Rings::new(InitGraph::V25G83,telemetry::Protocol::NONE,0).unwrap(); let words=[0x13,0,0,25,75,0,50,0,0,0,0,0,0,0,0,0,0,0]; init.push(Primary,words); rings.drain_statistics(&dev,&init,Primary); @@ -502,11 +577,52 @@ def item(source, signature): } } #[test] + fn m5_busy_time_takes_records_a_power_boundary_kept_out() { + use {channel::Rings,fw::variant::InitGraph,Role::*}; + let dev=crate::device::Device; + let init=initdata::InitData::new(); + let mut rings=Rings::new(InitGraph::G17P,telemetry::Protocol::PSTATE_8MS,13).unwrap(); + // 8 ms windows at 100%, timestamps in words 1 and 2. + let util=|ticks:u32|[0x13,ticks,0x59,0,0,100,100,0,0,0,0,0,0,0,0,0,0,0]; + init.push(Primary,util(0)); + rings.drain_statistics(&dev,&init,Primary); + assert_eq!(rings.read_statistics(1).busy_ns,0); + // Queued at a gate: cut off from the average, still busy time. + init.push(Primary,util(192_000)); + rings.observe_statistics_power(&dev,&init,&[Primary,Secondary],false,1); + rings.drain_statistics(&dev,&init,Primary); + assert_eq!(rings.read_statistics(1).busy_ns,8_000_000); + // Drained while gated, from the other role: the same. + init.push(Secondary,util(384_000)); + rings.drain_statistics(&dev,&init,Secondary); + assert_eq!(rings.read_statistics(1).busy_ns,16_000_000); + // Powered again: one record per epoch keeps counting, a repeat does not. + rings.observe_statistics_power(&dev,&init,&[Primary,Secondary],true,2); + init.push(Primary,util(576_000)); + init.push(Secondary,util(576_000)); + rings.drain_statistics(&dev,&init,Primary); + rings.drain_statistics(&dev,&init,Secondary); + assert_eq!(rings.read_statistics(1).busy_ns,24_000_000); + assert_eq!(rings.read_statistics(1).busy_status,telemetry::VALID); + // Suspend's discard keeps queued records out. + init.push(Primary,util(768_000)); + rings.suspend_statistics(true); + rings.drain_statistics(&dev,&init,Primary); + rings.suspend_statistics(false); + rings.drain_statistics(&dev,&init,Primary); + assert_eq!(rings.read_statistics(1).busy_ns,24_000_000); + // Quarantine stops the total: it reads stale. + init.cursors[1][1].store(fw::channels::STATISTICS_SLOTS,Ordering::Relaxed); + rings.drain_statistics(&dev,&init,Secondary); + let view=rings.read_statistics(1); + assert_eq!((view.busy_status,view.busy_ns),(telemetry::STALE,24_000_000)); + } + #[test] fn pstate_uses_drain_order_without_role_deduplication() { use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; let init=initdata::InitData::new(); - let mut rings=Rings::new(InitGraph::V25G83,false).unwrap(); + let mut rings=Rings::new(InitGraph::V25G83,telemetry::Protocol::NONE,0).unwrap(); init.push(Primary,[0x10,0x1000,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0]); init.push(Secondary,[0x10,0x2500,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0]); rings.drain_statistics(&dev,&init,Primary); @@ -633,13 +749,16 @@ def item(source, signature): assert(strstr(now,"power_mw unsupported\n")); assert(strstr(now,"temperature_raw unsupported\n")); assert(strstr(now,"requested_frequency_hz unsupported\n")); - assert(strstr(now,"achieved_frequency_hz unsupported\n")); if(status==1) { + /* A valid state with no frequency in the board's table. */ + assert(strstr(now,"achieved_frequency_hz unsupported\n")); assert(strstr(now,"util_tiler_percent 30\nutil_renderer_percent 80\nutil_device_percent 57\n")); assert(strstr(now,"pstate 6\n")); } else { + /* Not valid: the pstate and its frequency say why. */ + assert(strstr(now,status==2?"pstate stale\n":"pstate unavailable\n")); + assert(strstr(now,status==2?"achieved_frequency_hz stale\n":"achieved_frequency_hz unavailable\n")); assert(strstr(now,"util_device_percent unsupported\n")); - assert(strstr(now,"pstate unsupported\n")); assert(strstr(now,status==2?"pstate_status stale\n":"pstate_status unavailable\n")); assert(strstr(now,status==2?"utilisation_status stale\n":"utilisation_status unavailable\n")); } @@ -653,7 +772,11 @@ def item(source, signature): assert(strstr(now,"pstate 0\nrequested_frequency_hz unsupported\nachieved_frequency_hz 0\n")); current.pstate_status=2; agx_stats_show(NULL,&stats.attr,now); - assert(strstr(now,"pstate unsupported\nrequested_frequency_hz unsupported\nachieved_frequency_hz unsupported\n")); + assert(strstr(now,"pstate stale\nrequested_frequency_hz unsupported\nachieved_frequency_hz stale\n")); + /* M5: a stopped busy total reads stale. */ + current=(struct asahi_qualified_stats){.util_status=1,.pstate_status=1,.pstate=6,.busy_status=2,.busy_ns=77}; + agx_stats_show(NULL,&stats.attr,now); + assert(strstr(now,"busy_ns stale\n") && !strstr(now,"busy_ns 77")); /* G16S: pstate unsupported by firmware, utilisation still valid. */ current=(struct asahi_qualified_stats){.util_status=1,.pstate_status=3,.tiler=30,.renderer=80,.device=57,.pstate=0, .util_samples=19,.util_host_ns=123}; @@ -718,6 +841,11 @@ def main(): # Compile the production transport and decoder; only MMIO/shared memory, # kernel logging and allocation adapters are replaced by host fixtures. channel = '\n'.join(line for line in channel.splitlines() if not line.startswith('//!')) + # The fixture's firmware ring has 8 slots (fw::channels below), so drop the kernel's + # check that the decoder's ring size matches the real 256-slot ring. + ring_check = 'const _: () = assert!(super::telemetry::STATISTICS_RING_RECORDS == STATISTICS_SLOTS);' + assert ring_check in channel + channel = channel.replace(ring_check, '', 1) (work / 'channel.rs').write_text(channel) reports = (DRIVER / 'g17/reports.rs').read_text() store = reports.split('/// The view owns the session')[0] @@ -758,7 +886,7 @@ def main(): assert 'for &role in firmware.roles()' in stats_rs stats_rs = stats_rs.replace('for &role in firmware.roles()', 'for &role in &[]', 1) policy = '\n'.join(item(stats_rs, signature) for signature in - ['pub(super) const fn max_age_ns', 'pub(super) const fn protocol(', 'pub(super) const fn reports_pstate', + ['pub(super) const fn max_age_ns', 'pub(super) const fn reports_pstate', 'pub(super) fn qualify(']) # The rings take the family's statistics tags and control power rule from # InitData; build those production methods into the fixture's InitData. diff --git a/tools/asahi/g18-client-handoff-tests.py b/tools/asahi/g18-client-handoff-tests.py new file mode 100644 index 00000000000000..13f55ea292f13c --- /dev/null +++ b/tools/asahi/g18-client-handoff-tests.py @@ -0,0 +1,483 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the G18 client hand-over of the application render and compute owners against a model. + +The harness extracts from drivers/gpu/drm/asahi/g18 ApplicationJob and ApplicationJob::prepare() +(runtime/graphics_job_application.rs), G18ParameterBuffer::application_aliases() and +clear_client_data() (queue/graphics_application.rs), G18UmaPoolMemory::application_aliases() +(buffer/pool_application.rs), compute_application_aliases() and clear_scratch_for() +(buffer/pool.rs) and replacement_shared_compute() (buffer/pool_shared_compute.rs), and compiles +them with host rustc against a model of the GEM objects and their GPU mappings. The model's GPU +work of a VM writes the VM's id through each of its writable views of the PB blocks, scene +scratch, discard page, render targets and pool scratch blocks. + +What it shows: +- when the render job goes to another VM, no live view of that VM reaches a byte another VM + wrote, PB blocks added by growth included, and the previous VM's views are gone first; +- the same VM again, and a target regrowth of the same VM, clear nothing; +- the client view of the command graph is read-only; +- the compute pool's scratch blocks are cleared when another VM is given them, also when a + replacement pool retains the old scratch objects, and not for the same VM; +- source checks: both owners refuse a job that has not retired before any of this, the session + aliases the render pool only after prepare(), and the compute attempt drops the previous + aliases before it aliases the pool. + +--mutations runs every mutant, including the code at c5e25e0925351 (before the fix), and +requires each to fail. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G18 = 'drivers/gpu/drm/asahi/g18/' +PREPARE = G18 + 'runtime/graphics_job_application.rs' +PB = G18 + 'queue/graphics_application.rs' +POOL = G18 + 'buffer/pool.rs' +POOL_APP = G18 + 'buffer/pool_application.rs' +POOL_SHARED = G18 + 'buffer/pool_shared_compute.rs' +SESSION = G18 + 'boot/session.rs' +COMPUTE = G18 + 'initdata/application_compute.rs' +BASE = 'c5e25e0925351' + + +def item(source, signature, optional=False): + if optional and signature not in source: + return '' + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +MODEL = r''' +#![allow(dead_code, unused_variables, unused_mut, unused_imports)] +use std::cell::RefCell; +use std::ops::Range; +use std::rc::Rc; +use std::sync::atomic::{fence, Ordering}; +type Result = std::result::Result; +const EBUSY: i32 = 16; const EINVAL: i32 = 22; const EOVERFLOW: i32 = 75; const EFAULT: i32 = 14; +const ENOENT: i32 = 2; +#[derive(Clone, Copy)] struct Flags; +const GFP_KERNEL: Flags = Flags; +type KBox = Box; +struct KVec(Vec); +impl KVec { + fn new() -> Self { KVec(Vec::new()) } + fn push(&mut self, v: T, _: Flags) -> Result { self.0.push(v); Ok(()) } + fn clear(&mut self) { self.0.clear() } + fn len(&self) -> usize { self.0.len() } + fn is_empty(&self) -> bool { self.0.is_empty() } + fn iter(&self) -> std::slice::Iter<'_, T> { self.0.iter() } + fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> { self.0.iter_mut() } +} +impl IntoIterator for KVec { + type Item = T; type IntoIter = std::vec::IntoIter; + fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } +} +#[macro_export] +macro_rules! g18_kick_info { ($($t:tt)*) => {}; } +struct AsahiDrmDevice; +impl AsahiDrmDevice { fn as_ref(&self) -> &Self { self } } + +type Data = Rc>>; +struct Live { key: usize, vm: u64, addr: u64, prot: mmu::Prot, data: Data } +thread_local! { + static LIVE: RefCell> = RefCell::new(Vec::new()); + static NEXT: RefCell = RefCell::new(0); + static CLEARS: RefCell = RefCell::new(0); +} +mod mmu { + use super::*; + #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Prot { Rw, Ro } + pub const PROT_GPU_SHARED_RW: Prot = Prot::Rw; + pub const PROT_GPU_SHARED_RO: Prot = Prot::Ro; + #[derive(Clone)] pub struct Vm { pub id: u64 } + impl Vm { + pub fn id(&self) -> u64 { self.id } + pub fn retain_t8140_job(&self) -> Result { Ok(T8140VmJobGuard) } + pub fn translate_iova(&self, a: u64) -> Result { Ok(a) } + } + pub struct T8140VmJobGuard; + pub struct Uat { pub lower: Vm } + impl Uat { pub fn kernel_lower_vm(&self) -> &Vm { &self.lower } } + pub struct KernelMapping { key: usize } + impl KernelMapping { + pub fn new(vm: &Vm, addr: u64, prot: Prot, data: &Data) -> Self { + let key = NEXT.with(|n| { let mut n = n.borrow_mut(); *n += 1; *n }); + LIVE.with(|l| { + let mut l = l.borrow_mut(); + assert!(!l.iter().any(|m| m.vm == vm.id && m.addr == addr), + "VA {:#x} mapped twice in VM {}: the previous views were not dropped", addr, vm.id); + l.push(Live { key, vm: vm.id, addr, prot, data: data.clone() }); + }); + KernelMapping { key } + } + } + impl Drop for KernelMapping { + fn drop(&mut self) { LIVE.with(|l| l.borrow_mut().retain(|m| m.key != self.key)); } + } +} +struct MappedObject { data: Data, iova: u64, logical_size: usize } +impl MappedObject { + fn new(iova: u64, size: usize) -> Self { + MappedObject { data: Rc::new(RefCell::new(vec![0; size])), iova, logical_size: size } + } + fn shared(&self, iova: u64) -> Self { MappedObject { data: self.data.clone(), iova, logical_size: self.logical_size } } + fn iova(&self) -> u64 { self.iova } + fn with_bytes_mut(&mut self, f: impl FnOnce(&mut [u8]) -> Result) -> Result { + let mut bytes = self.data.borrow_mut(); + let all_zero_before = bytes.iter().all(|&b| b == 0); + let r = f(&mut bytes[..]); + // Render targets are cleared every frame; count the hand-over clears only. + let target = (va::GRAPHICS_TARGET_OFFSET..va::GRAPHICS_TARGET_OFFSET + 0x30000).contains(&self.iova); + if !target && !all_zero_before && bytes.iter().all(|&b| b == 0) { CLEARS.with(|c| *c.borrow_mut() += 1); } + r + } + fn map_alias_at(&mut self, vm: &mmu::Vm, address: u64, prot: mmu::Prot) -> Result { + Ok(mmu::KernelMapping::new(vm, address, prot, &self.data)) + } + fn regrow_wc_at(&mut self, _: &AsahiDrmDevice, _: &mmu::Vm, _: u64, size: usize) -> Result { + if size > self.logical_size { *self.data.borrow_mut() = vec![0; size]; self.logical_size = size; } + Ok(()) + } +} +mod g18 { + pub mod address_map { pub const COMPACT_BIAS: u64 = 0x10_0000_0000; } + pub mod uapi { pub mod graphics_scratch { + #[derive(Clone, Copy)] pub struct G18RenderScratchSelection; + } } +} +mod va { + pub use crate::g18::address_map::COMPACT_BIAS; + pub const GRAPHICS_JOB_LOW: u64 = 0x70_1200_0000; + pub const GRAPHICS_TARGET_OFFSET: u64 = 0x0100_0000; +} +#[derive(Clone, Copy, Default)] +struct Params { + cycle: u64, record_index: u64, ta_hardware_buffer_id: u32, usc_flist_hardware_buffer_id: u32, + scissor_array: u64, depth_bias_array: u64, depth_buffer: u64, depth_aux_buffer: u64, + load_pipeline: u64, store_pipeline: u64, partial_load_pipeline: u64, partial_store_pipeline: u64, + target: usize, +} +#[derive(Clone, Copy, Default)] struct Controls; +struct RenderTarget { width: u32, height: u32 } +struct G18ApplicationRender { + parameters: Params, controls: Controls, + scratch: Option, + target: RenderTarget, vdm_base: u64, +} +mod assembly { + pub struct Plan { pub offsets: [u64; 3], pub sizes: [usize; 3] } + pub fn target_plan(p: &super::Params) -> Option { + Some(Plan { offsets: [0, 0x10000, 0x20000], sizes: [p.target; 3] }) + } + pub fn apply_target_plan(_: &mut super::Params, _: &Plan) {} + pub const TARGET_NAMES: [&str; 3] = ["a", "b", "c"]; +} +mod regs { pub fn initialize_g18_deflake(_: &mut [u8], _: u32, _: u32) -> Option<()> { Some(()) } } +#[derive(Clone, Copy)] struct Frame { generation: u32 } +impl Frame { fn new(generation: u32) -> Option { (generation != 0).then_some(Frame { generation }) } } +#[derive(Clone, Copy)] struct WalkKey; +struct Program { vm: mmu::Vm } +impl Program { + fn matches_vm(&self, vm: &mmu::Vm) -> bool { self.vm.id == vm.id } + fn rebind_retired(&mut self, vm: &mmu::Vm) -> Result { self.vm = vm.clone(); Ok(()) } +} +struct G18PbCommandFields { pb_slot: u32 } +#[derive(Clone, Copy)] +struct G18PbAddresses { page_list_low: u64, page_list_row: u64, metrics_low: u64, scene_scratch_low: u64, discard_low: u64 } +const PB_BLOCKS_LOW: u64 = 0x70_2000_0000; +const PB_BLOCK: u64 = 0x80000; +struct G18ParameterBuffer { + page_list: MappedObject, metrics: MappedObject, scene_scratch: MappedObject, + discard: MappedObject, blocks: KVec, addresses: G18PbAddresses, +} +impl G18ParameterBuffer { + fn application_scene(&mut self, _: Option<&[u8; 0x80]>) -> Result<[u8; 0x80]> { Ok([0; 0x80]) } + fn scene_cycle(&self) -> u64 { 0 } + fn metrics_record(&self) -> u64 { 0 } + fn command_fields(&self) -> G18PbCommandFields { G18PbCommandFields { pb_slot: 0 } } +@@PB@@ +} +struct G18GraphicsJob { + program: Program, targets: KVec, aliases: KVec, + graph: MappedObject, parameter_buffer: G18ParameterBuffer, parameters: Params, + controls: Controls, signals: MappedObject, encoded: Option<()>, +} +impl G18GraphicsJob { fn context_id(&self) -> u8 { 3 } } +@@JOB@@ +impl ApplicationJob { + fn encode_application(&mut self, _: &AsahiDrmDevice, _: Frame) -> Result { Ok(()) } + fn retired(&mut self) { self.retired = true; self.guard = None; } +@@PREPARE@@ +} +const DIRECTORY_BASE: u64 = 0x70_0200_0000; +const BLOCK_LIST_BASE: u64 = 0x70_0400_0000; +const BLOCK_DATA_BASE: u64 = 0x70_0500_0000; +const BLOCK_DATA_STRIDE: u64 = 0x20_0000; +const G18_COMPUTE_BLOCK_BYTES: u64 = 0x20_0000; +struct Layout; +impl Layout { fn page_offset(&self, i: u32) -> Option { Some(u64::from(i) * 0x4000) } } +#[derive(Clone, Copy)] struct G18ComputePlan; +struct G18UmaPoolMemory { + process_aliases: KVec, scratch: KVec, scratch_plan: Option<()>, + directory: KVec, block_list: MappedObject, layout: Layout, encoded: bool, + descriptor_loaded: bool, render: bool, low_bias: u64, hardware_slot: u32, client_vm: Option, +} +impl G18UmaPoolMemory { + fn model(render: bool, low_bias: u64, blocks: usize) -> Self { + let mut scratch = KVec::new(); + for i in 0..blocks { let _ = scratch.push(MappedObject::new(0x1000 * i as u64, 64), GFP_KERNEL); } + let mut directory = KVec::new(); + let _ = directory.push(MappedObject::new(0, 64), GFP_KERNEL); + G18UmaPoolMemory { process_aliases: KVec::new(), scratch, scratch_plan: Some(()), directory, + block_list: MappedObject::new(0, 64), layout: Layout, encoded: true, descriptor_loaded: true, + render, low_bias, hardware_slot: 1, client_vm: None } + } + // As the production constructor: a fresh pool has no client. + fn new_layout(_: &AsahiDrmDevice, _: &mmu::Uat, _: Range, _: u32, _: bool, _: bool, + low_bias: u64, _: u32, _: u64) -> Result { + let mut pool = Self::model(false, low_bias, 0); pool.scratch_plan = None; pool.encoded = false; + pool.descriptor_loaded = false; Ok(pool) + } + // The retained scratch objects are the same memory, plus one fresh block. + fn prepare_shared_compute_retaining(&mut self, _: &AsahiDrmDevice, _: &mmu::Uat, _: Range, + _: G18ComputePlan, retained: Option<&Self>) -> Result { + for (i, old) in retained.unwrap().scratch.iter().enumerate() { + self.scratch.push(old.shared(0x10_0000 + 0x1000 * i as u64), GFP_KERNEL)?; + } + self.scratch.push(MappedObject::new(0x20_0000, 64), GFP_KERNEL)?; + self.scratch_plan = Some(()); Ok(()) + } + fn alias_into_process(&mut self, _: &AsahiDrmDevice, _: &mmu::Uat, vm: &mmu::Vm) -> Result { + let mut aliases = KVec::new(); + for (i, block) in self.scratch.iter_mut().enumerate() { + aliases.push(block.map_alias_at(vm, BLOCK_DATA_BASE + self.low_bias + i as u64 * 0x30_0000, + mmu::PROT_GPU_SHARED_RW)?, GFP_KERNEL)?; + } + self.process_aliases = aliases; Ok(()) + } + fn audit_render_mappings(&self, _: &mmu::Uat, _: &mmu::Vm) -> Result { Ok(0) } +@@POOL@@ +} + +/// Kernel-only addresses: kept by design (they name the PB's and pool's own objects). +fn kept(addr: u64) -> bool { + let bias = va::COMPACT_BIAS; + [0x70_3000_0000u64, 0x70_3100_0000, DIRECTORY_BASE, BLOCK_LIST_BASE, va::GRAPHICS_JOB_LOW] + .iter().any(|&a| addr == a || addr == a + bias) +} +/// The GPU work of `vm` writes its id through each writable view it has. +fn gpu_work(vm: u64) { + LIVE.with(|l| for m in l.borrow().iter() { + if m.vm == vm && m.prot == mmu::Prot::Rw && !kept(m.addr) { m.data.borrow_mut().fill(vm as u8); } + }); +} +/// No live view of `vm` may reach a byte another VM wrote. +fn exposed(vm: u64, what: &str) { + LIVE.with(|l| for m in l.borrow().iter() { + if m.vm == vm { + let data = m.data.borrow(); + assert!(data.iter().all(|&b| b == 0 || b == vm as u8), + "{}: VM {} maps {:#x}, which holds VM {}'s data", what, vm, m.addr, + data.iter().find(|&&b| b != 0 && b != vm as u8).unwrap()); + } + }); +} +fn holds(object: &MappedObject, vm: u64) -> bool { object.data.borrow().iter().all(|&b| b == vm as u8) } +fn clears() -> usize { CLEARS.with(|c| *c.borrow()) } + +fn new_job() -> Box { + let mut blocks = KVec::new(); + for i in 0..2u64 { let _ = blocks.push(MappedObject::new(PB_BLOCKS_LOW + i * PB_BLOCK, 64), GFP_KERNEL); } + let pb = G18ParameterBuffer { + page_list: MappedObject::new(0x70_3000_0000, 64), metrics: MappedObject::new(0x70_3100_0000, 64), + scene_scratch: MappedObject::new(0x70_3200_0000, 64), discard: MappedObject::new(0x70_3300_0000, 64), + blocks, addresses: G18PbAddresses { page_list_low: 0x70_3000_0000, page_list_row: 0x70_3000_0000 + va::COMPACT_BIAS, + metrics_low: 0x70_3100_0000, scene_scratch_low: 0x70_3200_0000, discard_low: 0x70_3300_0000 }, + }; + let mut targets = KVec::new(); + for offset in [0u64, 0x10000, 0x20000] { + let _ = targets.push(MappedObject::new(va::GRAPHICS_TARGET_OFFSET + offset, 64), GFP_KERNEL); + } + let job = G18GraphicsJob { program: Program { vm: mmu::Vm { id: 100 } }, targets, aliases: KVec::new(), + graph: MappedObject::new(0xffff_0000, 64), parameter_buffer: pb, parameters: Params::default(), + controls: Controls, signals: MappedObject::new(0, 0xc020), encoded: None }; + Box::new(ApplicationJob { job: Box::new(job), storage: mmu::Vm { id: 100 }, user_aliases: KVec::new(), + pool_aliases: KVec::new(), guard: None, scene: [0; 0x80], generation: 0, retired: true, + client_frames: 0, scratch: None, walked: None }) +} +fn render(target: usize) -> G18ApplicationRender { + G18ApplicationRender { parameters: Params { target, ..Params::default() }, controls: Controls, + scratch: None, target: RenderTarget { width: 8, height: 8 }, vdm_base: 0 } +} +/// submit_application: prepare, the render pool once per remap, the frame, retirement. +fn frame(job: &mut ApplicationJob, pool: &mut G18UmaPoolMemory, uat: &mmu::Uat, vm: u64, target: usize) { + let vm = mmu::Vm { id: vm }; + job.prepare(&AsahiDrmDevice, uat, &vm, &render(target)).unwrap(); + if job.pool_aliases.is_empty() { job.pool_aliases = pool.application_aliases(uat, &vm).unwrap(); } + exposed(vm.id, "render hand-over"); + LIVE.with(|l| for m in l.borrow().iter() { + if m.vm == vm.id && (m.addr == va::GRAPHICS_JOB_LOW) { + assert_eq!(m.prot, mmu::Prot::Ro, "the client view of the command graph must be read-only"); + } + }); + gpu_work(vm.id); + job.retired(); +} + +fn main() { + let uat = mmu::Uat { lower: mmu::Vm { id: 0 } }; + let mut job = new_job(); + let mut pool = G18UmaPoolMemory::model(true, 0, 3); + frame(&mut job, &mut pool, &uat, 1, 64); + // A firmware TVB grow request backs a block for VM 1, aliased with its other PB views. + let mut grown = MappedObject::new(PB_BLOCKS_LOW + 2 * PB_BLOCK, 64); + for at in [grown.iova(), grown.iova() + va::COMPACT_BIAS] { + let alias = grown.map_alias_at(&mmu::Vm { id: 1 }, at, mmu::PROT_GPU_SHARED_RW).unwrap(); + job.user_aliases.push(alias, GFP_KERNEL).unwrap(); + } + job.job.parameter_buffer.blocks.push(grown, GFP_KERNEL).unwrap(); + gpu_work(1); + let before = clears(); + frame(&mut job, &mut pool, &uat, 1, 64); + frame(&mut job, &mut pool, &uat, 1, 128); + assert_eq!(clears(), before, "the same VM again (also with regrown targets) must not clear the PB or pool"); + assert!(job.job.parameter_buffer.blocks.iter().all(|b| holds(b, 1)) && pool.scratch.iter().all(|b| holds(b, 1)), + "the same VM's storage must be kept"); + for vm in [2, 2, 1, 3, 2] { frame(&mut job, &mut pool, &uat, vm, 128); } + println!("PASS render: 8 frames over 3 VMs, PB growth, target regrowth; no VM sees another's PB blocks, scene scratch, discard page or pool scratch; graph view read-only; same VM clears nothing"); + + let mut compute = G18UmaPoolMemory::model(false, 0x4000_0000, 2); + let mut owner = |pool: &mut G18UmaPoolMemory, vm: u64| { + let aliases = pool.compute_application_aliases(&AsahiDrmDevice, &uat, &mmu::Vm { id: vm }).unwrap(); + exposed(vm, "compute hand-over"); + gpu_work(vm); + aliases // the attempt keeps them until the next submission clears job.aliases + }; + let a = owner(&mut compute, 1); drop(a); + let before = clears(); + let a = owner(&mut compute, 1); drop(a); + assert_eq!(clears(), before, "the same VM's compute again must not clear the pool"); + assert!(compute.scratch.iter().all(|b| holds(b, 1))); + let a = owner(&mut compute, 2); drop(a); + let mut replacement = compute.replacement_shared_compute(&AsahiDrmDevice, &uat, 0..1, G18ComputePlan).unwrap(); + let a = owner(&mut replacement, 1); drop(a); + let a = owner(&mut replacement, 1); drop(a); + let a = owner(&mut replacement, 3); drop(a); + println!("PASS compute: 6 submissions over 3 VMs and a replacement pool retaining the scratch objects; no VM sees another's scratch; same VM clears nothing"); +} +''' + + +def build(read): + prepare_src = read(PREPARE) + pb_src = read(PB) + pool_src = read(POOL) + job = item(prepare_src, 'pub(crate) struct ApplicationJob {') + prepare = item(prepare_src, 'pub(crate) fn prepare(') + pb = (item(pb_src, 'pub(crate) fn application_aliases(&mut self, vm: &mmu::Vm)') + '\n' + + item(pb_src, 'pub(crate) fn clear_client_data(', optional=True)) + pool = (item(read(POOL_APP), 'pub(crate) fn application_aliases(&mut self, uat') + '\n' + + item(pool_src, 'pub(crate) fn compute_application_aliases(') + '\n' + + item(pool_src, 'fn clear_scratch_for(', optional=True) + '\n' + + item(read(POOL_SHARED), 'pub(crate) fn replacement_shared_compute(')) + return (MODEL.replace('@@JOB@@', job).replace('@@PREPARE@@', prepare) + .replace('@@PB@@', pb).replace('@@POOL@@', pool)) + + +def sub(old, new): + def apply(code): + assert old in code, 'mutation anchor missing: ' + old + return code.replace(old, new, 1) + return apply + + +MUTATIONS = { + 'pb-clear-dropped': sub('if new_client && self.generation!=0 {self.job.parameter_buffer.clear_client_data()?;}', ''), + 'pb-clear-every-remap': sub('if new_client && self.generation!=0 {', 'if self.generation!=0 {'), + 'pb-grown-blocks-kept': sub('for block in self.blocks.iter_mut() {\n clear(block)', 'for block in self.blocks.iter_mut().take(2) {\n clear(block)'), + 'pb-scene-scratch-kept': sub('clear(&mut self.scene_scratch)?;', ''), + 'pb-discard-kept': sub('clear(&mut self.discard)?;', ''), + 'graph-view-writable': sub('va::GRAPHICS_JOB_LOW,\n mmu::PROT_GPU_SHARED_RO)', 'va::GRAPHICS_JOB_LOW,\n mmu::PROT_GPU_SHARED_RW)'), + 'render-pool-clear-dropped': sub('{return Err(EINVAL);}\n self.clear_scratch_for(vm)?;', '{return Err(EINVAL);}'), + 'compute-pool-clear-dropped': sub(' self.clear_scratch_for(vm)?;\n self.alias_into_process(', ' self.alias_into_process('), + 'pool-clear-every-alias': sub('self.client_vm.is_some_and(|id| id != vm.id())', 'self.client_vm.is_some()'), + 'replacement-forgets-client': sub('pool.client_vm = self.client_vm;', ''), +} + + +def source_checks(read): + prepare = item(read(PREPARE), 'pub(crate) fn prepare(') + assert prepare.index('if !self.retired {return Err(EBUSY);}') < prepare.index('clear_client_data'), 'prepare: retired first' + submit = item(read(SESSION), 'fn submit_application(') + assert submit.index('job.prepare(') < submit.index('.application_aliases(vm)'), 'session: pool aliased after prepare' + attempt = item(read(COMPUTE), 'fn prepare_application_compute_attempt(') + retired = attempt.index('if !job.retired') + dropped = attempt.index('job.aliases.clear();') + aliased = attempt.index('pool.compute_application_aliases(') + assert retired < dropped < aliased, 'compute: retired, previous aliases dropped, then the pool aliased' + print('PASS source: retirement is checked first; previous views are dropped before the pools are aliased') + + +def compile_run(code, out, name, rustc): + path = out / (name + '.rs') + path.write_text(code) + binary = out / name + built = subprocess.run(rustc + ['--edition=2021', '-O', str(path), '-o', str(binary)], + capture_output=True, text=True) + if built.returncode != 0: + raise SystemExit(f'{name}: host build failed\n{built.stderr}') + return subprocess.run([str(binary)], capture_output=True, text=True) + + +def main(): + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument('--output', type=Path, help='Work directory (default: a temporary one)') + p.add_argument('--rustc', default=os.environ.get('HOSTRUSTC') or os.environ.get('RUSTC', 'rustc')) + p.add_argument('--mutations', action='store_true', + help=f'Also require every mutant and the code at {BASE} to fail') + a = p.parse_args() + out = (a.output or Path(tempfile.mkdtemp(prefix='g18-client-handoff-'))).resolve() + out.mkdir(parents=True, exist_ok=True) + rustc = [a.rustc] + + def tip(path): + return (ROOT / path).read_text() + + def base(path): + return subprocess.check_output(['git', 'show', f'{BASE}:{path}'], cwd=ROOT, text=True) + + source_checks(tip) + result = compile_run(build(tip), out, 'fixed', rustc) + if result.returncode != 0: + sys.exit('FAIL fixed code\n' + result.stderr) + print(result.stdout.strip()) + if not a.mutations: + return + unchecked = sub('assert_eq!(m.prot, mmu::Prot::Ro,', 'assert!(true || m.prot == mmu::Prot::Ro,') + mutants = [(BASE, build(base)), (BASE + '-data-only', unchecked(build(base)))] + for name, apply in MUTATIONS.items(): + code = build(tip) + mutants.append((name, apply(code))) + killed = 0 + for name, code in mutants: + result = compile_run(code, out, 'mutant-' + name, rustc) + if result.returncode == 0 or 'panicked at' not in result.stderr: + sys.exit(f'FAIL mutant {name} survived\n{result.stdout}{result.stderr}') + reason = next((l for l in result.stderr.splitlines() if l and 'panicked at' not in l and 'note:' not in l), '') + print(f'PASS mutant killed: {name}: {reason.strip()}') + killed += 1 + print(f'PASS {killed}/{len(mutants)} mutants killed') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g18-job-error-tests.py b/tools/asahi/g18-job-error-tests.py new file mode 100644 index 00000000000000..cbe7fe65eb5c5a --- /dev/null +++ b/tools/asahi/g18-job-error-tests.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the G18 session's job-error classification, actual bodies, against a model. + +The harness extracts from drivers/gpu/drm/asahi/g18 JobFailure, Failure and From for +Failure (boot/recovery.rs); ApplicationOwner::outcome(), decode(), finish(), JobOutcome and the +prepare step of G18Session::submit_application() (boot/session.rs); ApplicationJob, prepare() +and unpublished() (runtime/graphics_job_application.rs, with the PB and pool bodies the hand-over +test uses, through its model); and G18FirmwareMemory::application_compute_unpublished() +(initdata/application_compute.rs). They run against a model whose client VMs can have an address +unmapped, be closed, or ask for a target larger than an allocation admits. + +What it shows: +- a render refused from the client's own state (an unmapped address it names, its VM closed, a + target allocation that fails, also on the first frame) fails that job only: its errno reaches + the submitter, the session stays live, no path is quarantined, the client's VM is not + poisoned, the job stays retired with its generation unchanged, and the next render of any + client runs; +- a prepare on a job that did not retire, and any job error on a crashed firmware, still end + the session; +- the compute owner counts as unpublished only while no process, command, context, previous + pool or held VM exists, and before it exists only while its scheduler record is unarmed; +- source checks: the compute submission classifies a failed preparation by that state, and + nothing in the render submission reaches the firmware before prepare(). + +--mutations runs every mutant, including the code at c5e25e0925351, and requires each to fail. +""" +import argparse +import importlib.util +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +spec = importlib.util.spec_from_file_location('g18_handoff', HERE / 'g18-client-handoff-tests.py') +handoff = importlib.util.module_from_spec(spec) +spec.loader.exec_module(handoff) +item, ROOT, BASE, G18 = handoff.item, handoff.ROOT, handoff.BASE, handoff.G18 +RECOVERY = G18 + 'boot/recovery.rs' +SESSION = G18 + 'boot/session.rs' +COMPUTE_SESSION = G18 + 'boot/compute_session.rs' +COMPUTE = G18 + 'initdata/application_compute.rs' +PREPARE = handoff.PREPARE + +EXTRA = r''' +thread_local! { + static UNMAPPED: RefCell> = RefCell::new(Vec::new()); + static CLOSED: RefCell> = RefCell::new(Vec::new()); + static POISONED: RefCell> = RefCell::new(Vec::new()); + static STOPPED: RefCell = RefCell::new(false); +} +const ENOMEM: i32 = 12; const EIO: i32 = 5; +const ALLOC_LIMIT: usize = 0x10000; +type Error = i32; +trait Errno { fn to_errno(&self) -> i32; fn from_errno(errno: i32) -> Self; } +impl Errno for i32 { fn to_errno(&self) -> i32 { -*self } fn from_errno(errno: i32) -> Self { -errno } } +pub struct Status(u64); +impl Status { pub fn record(&self, _: Error) { POISONED.with(|p| p.borrow_mut().push(self.0)); } } +macro_rules! dev_err { ($($t:tt)*) => {}; } +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32}; +#[derive(Debug)] struct G18Recovery; +#[derive(Debug, Clone, Copy)] enum JobPath { Render, Compute } +impl JobPath { fn bit(&self) -> u32 { 1 << (*self as u32) } } +@@RECOVERY@@ +struct Mutex(std::sync::Mutex); +impl Mutex { fn lock(&self) -> std::sync::MutexGuard<'_, T> { self.0.lock().unwrap() } } +struct Retained(Option); +impl Retained { fn stop(&mut self, _: &str) -> Result { STOPPED.with(|s| *s.borrow_mut() = true); Ok(()) } } +struct Memory; +impl Memory { fn quarantine_application_compute(&mut self) {} fn log_trace_journal(&self, _: &AsahiDrmDevice) {} } +struct G18Session { dev: AsahiDrmDevice, uat: mmu::Uat, application_job: Option>, + memory: Option, crashed: bool } +impl G18Session { + fn any_crashed(&self) -> bool { self.crashed } + fn device(&self) -> &AsahiDrmDevice { &self.dev } + fn dump_fault_evidence(&self, _: &str) {} + fn submit_prepare(&mut self, vm: &mmu::Vm, render: &G18ApplicationRender) -> core::result::Result<(), Failure> { +@@SUBMIT@@ + Ok(()) + } +} +fn log_job_failure(_: &G18Session, _: &JobFailure) {} +const TICKET_RUNNING: i32 = 1; +@@OUTCOME_ENUM@@ +struct ApplicationOwner; +impl ApplicationOwner { +@@OWNER@@ +} + +struct ComputeMemory { process: bool } +impl ComputeMemory { fn unpublished_idle(&self) -> bool { !self.process } } +struct ApplicationCompute { retired: bool, guard: Option, aliases: KVec, + previous_pool: Option<()>, previous_binding: Option<()> } +struct Scheduler { armed: bool } +impl Scheduler { fn binding(&self, _: usize) -> Result<()> { if self.armed { Ok(()) } else { Err(EINVAL) } } } +struct G18FirmwareMemory { compute: ComputeMemory, application_compute: Option>, scheduler: Scheduler } +impl G18FirmwareMemory { +@@COMPUTE@@ +} + +struct Device { session: Mutex, failed: AtomicBool, quarantined: AtomicU32 } +impl Device { + fn job(&self, f: impl FnOnce(&mut ApplicationJob) -> R) -> R { + f(self.session.lock().0.as_mut().unwrap().application_job.as_mut().unwrap()) + } + /// One render through the ticket, as submit_render: prepare, then retire on success. + fn render(&self, vm: u64, scissor: u64, target: usize, retire: bool) -> Result { + let v = mmu::Vm { id: vm }; + let mut r = render(target); + r.parameters.scissor_array = scissor; + let code = ApplicationOwner::outcome(&self.session, &self.failed, &self.quarantined, |s| s.submit_prepare(&v, &r)); + let result = ApplicationOwner::finish(&v, ApplicationOwner::decode(code)); + if result.is_ok() && retire { self.job(|j| j.retired()); } + result + } + fn live(&self) -> bool { !self.failed.load(Ordering::Acquire) && !STOPPED.with(|s| *s.borrow()) } +} +fn device(crashed: bool) -> Device { + let session = G18Session { dev: AsahiDrmDevice, uat: mmu::Uat { lower: mmu::Vm { id: 0 } }, + application_job: Some(new_job()), memory: Some(Memory), crashed }; + STOPPED.with(|s| *s.borrow_mut() = false); + Device { session: Mutex(std::sync::Mutex::new(Retained(Some(session)))), failed: AtomicBool::new(false), + quarantined: AtomicU32::new(0) } +} +fn refused(d: &Device, result: Result, errno: i32, what: &str, generation: u32) { + assert_eq!(result, Err(errno), "{}: the submitter must get the job's own errno", what); + assert!(d.live(), "{}: a client's own error must not end the session", what); + assert_eq!(d.quarantined.load(Ordering::Acquire), 0, "{}: no path may be quarantined", what); + assert!(POISONED.with(|p| p.borrow().is_empty()), "{}: nothing ran, the client's VM stays usable", what); + assert!(d.job(|job| job.unpublished() && job.generation == generation), + "{}: the refused job must stay retired at generation {}", what, generation); +} +const SCISSOR: u64 = 0x5000; + +fn main() { + let d = device(false); + d.render(1, SCISSOR, 64, true).unwrap(); + d.render(1, SCISSOR, 64, true).unwrap(); + UNMAPPED.with(|u| u.borrow_mut().push((2, SCISSOR))); + let r = d.render(2, SCISSOR, 64, true); refused(&d, r, EFAULT, "unmapped scissor", 2); + UNMAPPED.with(|u| u.borrow_mut().clear()); + d.render(2, SCISSOR, 64, true).unwrap(); + CLOSED.with(|c| c.borrow_mut().push(3)); + let r = d.render(3, SCISSOR, 64, true); refused(&d, r, ENOENT, "closed VM", 3); + let r = d.render(1, SCISSOR, ALLOC_LIMIT * 2, true); refused(&d, r, ENOMEM, "target allocation", 3); + let r = d.render(2, SCISSOR, ALLOC_LIMIT * 2, true); refused(&d, r, ENOMEM, "target allocation, another VM", 3); + d.render(1, SCISSOR, 64, true).unwrap(); + assert_eq!(d.job(|j| j.generation), 4); + d.render(2, SCISSOR, ALLOC_LIMIT, true).unwrap(); + println!("PASS render: unmapped address, closed VM and failed target allocation fail their job only; the session, its path and the client VMs serve on"); + + drop(d); + let d = device(false); + UNMAPPED.with(|u| u.borrow_mut().push((1, SCISSOR))); + let r = d.render(1, SCISSOR, 64, true); refused(&d, r, EFAULT, "first frame", 0); + UNMAPPED.with(|u| u.borrow_mut().clear()); + d.render(1, SCISSOR, 64, true).unwrap(); + d.render(2, SCISSOR, 64, true).unwrap(); + println!("PASS render: a first frame refused after its kernel aliases were made is prepared again"); + + drop(d); + let d = device(false); + d.render(1, SCISSOR, 64, false).unwrap(); + assert!(d.render(1, SCISSOR, 64, true).is_err() && !d.live(), "a job that did not retire must still end the session"); + drop(d); + let d = device(true); + UNMAPPED.with(|u| u.borrow_mut().push((1, SCISSOR))); + assert!(d.render(1, SCISSOR, 64, true).is_err() && !d.live(), "a crashed firmware must still end the session"); + UNMAPPED.with(|u| u.borrow_mut().clear()); + println!("PASS render: an unretired job and a crashed firmware stay fatal"); + compute(); +} +''' + +COMPUTE_MAIN = r''' +fn compute() { + let idle = || ApplicationCompute { retired: true, guard: None, aliases: KVec::new(), previous_pool: None, previous_binding: None }; + let memory = |job: Option, process: bool, armed: bool| G18FirmwareMemory { + compute: ComputeMemory { process }, application_compute: job.map(Box::new), scheduler: Scheduler { armed } }; + assert!(memory(Some(idle()), false, true).application_compute_unpublished(), "a retired idle owner is unpublished"); + assert!(memory(None, false, false).application_compute_unpublished(), "before the owner exists nothing is armed"); + for (name, m) in [ + ("bound process", memory(Some(idle()), true, true)), + ("unretired", memory(Some(ApplicationCompute { retired: false, ..idle() }), false, true)), + ("held VM", memory(Some(ApplicationCompute { guard: Some(mmu::T8140VmJobGuard), ..idle() }), false, true)), + ("previous pool", memory(Some(ApplicationCompute { previous_pool: Some(()), ..idle() }), false, true)), + ("previous binding", memory(Some(ApplicationCompute { previous_binding: Some(()), ..idle() }), false, true)), + ("armed record without owner", memory(None, false, true)), + ] { + assert!(!m.application_compute_unpublished(), "compute owner with {} must stay fatal", name); + } + println!("PASS compute: only a retired, unbound owner (or an unarmed one not yet built) makes a failed preparation a job failure"); +} +''' + + +def build(read): + code = handoff.build(read).replace('fn main() {', 'fn handoff_main() {', 1) + for old, new in [ + ('pub fn retain_t8140_job(&self) -> Result { Ok(T8140VmJobGuard) }', + 'pub fn retain_t8140_job(&self) -> Result {\n' + ' if CLOSED.with(|c| c.borrow().contains(&self.id)) { Err(ENOENT) } else { Ok(T8140VmJobGuard) } }\n' + ' pub fn status(&self) -> Option { Some(Status(self.id)) }'), + ('pub fn translate_iova(&self, a: u64) -> Result { Ok(a) }', + 'pub fn translate_iova(&self, a: u64) -> Result {\n' + ' if UNMAPPED.with(|u| u.borrow().contains(&(self.id, a))) { Err(EFAULT) } else { Ok(a) } }'), + ('fn regrow_wc_at(&mut self, _: &AsahiDrmDevice, _: &mmu::Vm, _: u64, size: usize) -> Result {', + 'fn regrow_wc_at(&mut self, _: &AsahiDrmDevice, _: &mmu::Vm, _: u64, size: usize) -> Result {\n' + ' if size > ALLOC_LIMIT { return Err(ENOMEM); }'), + ('fn retired(&mut self) { self.retired = true; self.guard = None; }', + 'fn retired(&mut self) { self.retired = true; self.guard = None; }\n fn quarantine(&mut self) {}\n' + # The code before the fix has no such method; the model states the same property. + + (item(read(PREPARE), 'pub(crate) fn unpublished(', optional=True) + or 'fn unpublished(&self) -> bool { self.retired && self.guard.is_none() }')), + ]: + assert code.count(old) == 1, old + code = code.replace(old, new) + recovery = read(RECOVERY) + rec = '\n'.join(item(recovery, s).replace('pub(super) ', '') for s in + ('pub(super) enum JobFailure {', 'pub(super) enum Failure {', 'impl From for Failure {')) + session = read(SESSION) + submit = item(session, 'fn submit_application(') + start = submit.index('let job=self.application_job.as_mut().ok_or(EIO)?;') + end = submit.index('if job.pool_aliases.is_empty()') + owner = '\n'.join(item(session, s) for s in ('fn outcome(', 'fn decode(', 'fn finish(')) + compute = item(read(COMPUTE), 'pub(crate) fn application_compute_unpublished(', optional=True) + extra = (EXTRA.replace('@@RECOVERY@@', rec).replace('@@SUBMIT@@', submit[start:end]) + .replace('@@OUTCOME_ENUM@@', item(session, 'enum JobOutcome {')).replace('@@OWNER@@', owner) + .replace('@@COMPUTE@@', compute)) + extra += COMPUTE_MAIN if compute else 'fn compute() {}\n' + return code + extra + + +sub = handoff.sub +MUTATIONS = { + 'prepare-commits-early': lambda c: sub( + ' // Commit the frame only now: until here an error leaves the job\n' + ' // retired, and the next prepare() rebuilds whatever this one changed.\n' + ' self.guard=Some(guard);self.generation=frame.generation;self.retired=false;\n' + ' self.client_frames=if new_client {1} else {self.client_frames.saturating_add(1)};\n', '')( + sub(' self.job.program.rebind_retired(vm)?;\n', + ' self.job.program.rebind_retired(vm)?;\n' + ' self.guard=Some(guard);self.generation=frame.generation;self.retired=false;\n' + ' self.client_frames=if new_client {1} else {self.client_frames.saturating_add(1)};\n')(c)), + 'first-frame-alias-repeated': sub('if self.generation==0 && self.job.aliases.is_empty() {', 'if self.generation==0 {'), + 'refusal-always-fatal': sub('Failure::Job(JobFailure::Refused(error))} else {Failure::Fatal(error)}', + 'Failure::Fatal(error)} else {Failure::Fatal(error)}'), + 'refusal-ignores-state': sub('if job.unpublished() {Failure::Job', 'if true {Failure::Job'), + 'refusal-lost-in-ticket': sub(' code if code>JobOutcome::Refused as i32 =>', ' code if false =>'), + 'refusal-poisons-vm': sub('Err(Failure::Job(JobFailure::Refused(error))) => Err(error),', + 'Err(Failure::Job(JobFailure::Refused(error))) => {if let Some(status)=vm.status(){status.record(error);}Err(error)}'), + 'compute-ignores-process': sub('self.compute.unpublished_idle() && match', 'match'), + 'compute-unbuilt-always': sub('None => self.scheduler.binding(0).is_err(),', 'None => true,'), + 'compute-ignores-previous-pool': sub('&& job.previous_pool.is_none() ', ''), +} + + +def source_checks(read): + compute = item(read(COMPUTE_SESSION), 'pub(super) fn submit_application_compute(') + arm = compute[compute.index('.prepare_application_compute(&self.dev, vm, translated)'):] + arm = arm[:arm.index('if generation == 1')] + assert 'memory.application_compute_unpublished()' in arm and 'Failure::Job(JobFailure::Refused(error))' in arm \ + and 'Failure::Fatal(error)' in arm, arm + submit = item(read(SESSION), 'fn submit_application(') + before = submit[:submit.index('job.prepare(')] + for word in ('send_message', 'publish', 'install_records'): + assert word not in before, 'render submission reaches the firmware before prepare: ' + word + print('PASS source: compute classifies a failed preparation by the owner state; nothing of a render is published before prepare()') + + +def main(): + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument('--output', type=Path, help='Work directory (default: a temporary one)') + p.add_argument('--rustc', default=os.environ.get('HOSTRUSTC') or os.environ.get('RUSTC', 'rustc')) + p.add_argument('--mutations', action='store_true', + help=f'Also require every mutant and the code at {BASE} to fail') + a = p.parse_args() + out = (a.output or Path(tempfile.mkdtemp(prefix='g18-job-error-'))).resolve() + out.mkdir(parents=True, exist_ok=True) + rustc = [a.rustc] + + def tip(path): + return (ROOT / path).read_text() + + def base(path): + return subprocess.check_output(['git', 'show', f'{BASE}:{path}'], cwd=ROOT, text=True) + + source_checks(tip) + result = handoff.compile_run(build(tip), out, 'fixed', rustc) + if result.returncode != 0: + sys.exit('FAIL fixed code\n' + result.stdout + result.stderr) + print(result.stdout.strip()) + if not a.mutations: + return + # The code before the fix with only the hand-over test's read-only graph check relaxed. + unchecked = sub('assert_eq!(m.prot, mmu::Prot::Ro,', 'assert!(true || m.prot == mmu::Prot::Ro,') + mutants = [(BASE, unchecked(build(base)))] + mutants += [(name, apply(build(tip))) for name, apply in MUTATIONS.items()] + killed = 0 + for name, code in mutants: + result = handoff.compile_run(code, out, 'mutant-' + name, rustc) + if result.returncode == 0 or 'panicked at' not in result.stderr: + sys.exit(f'FAIL mutant {name} survived\n{result.stdout}{result.stderr}') + reason = next((l for l in result.stderr.splitlines() if l and 'panicked at' not in l and 'note:' not in l), '') + print(f'PASS mutant killed: {name}: {reason.strip()}') + killed += 1 + print(f'PASS {killed}/{len(mutants)} mutants killed') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/m3-packet-completion-tests.py b/tools/asahi/m3-packet-completion-tests.py new file mode 100644 index 00000000000000..1b58bba7f1d7d6 --- /dev/null +++ b/tools/asahi/m3-packet-completion-tests.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Build a host test of M3's production packet completion with mock fences and VM state.""" +import argparse +from pathlib import Path +import subprocess + + +def method(source, signature): + start = source.index(signature) + body = source.index("{", start) + depth = 1 + end = body + 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + return source[start:end] + + +MOCKS = r""" +use std::cell::Cell; +use std::sync::{Mutex, atomic::{AtomicBool, AtomicU8, Ordering}}; +#[derive(Clone, Copy, PartialEq, Eq)] +struct Error(i32); +impl Error { + fn to_errno(self) -> i32 { self.0 } +} +type Result = std::result::Result<(), Error>; +const EIO: Error = Error(-5); +const EBUSY: Error = Error(-16); +const ENODEV: Error = Error(-19); +const ETIMEDOUT: Error = Error(-110); +const ECANCELED: Error = Error(-125); + +#[derive(Default)] +struct Vm { + error: Cell, +} +impl Vm { + fn status(&self) -> Option<&Self> { Some(self) } + fn id(&self) -> u32 { 1 } + fn record(&self, error: Error) { + if self.error.get() == 0 { + self.error.set(error.0); + } + } + fn record_if_device_loss(&self, error: Error) { + if error == EIO || error == ETIMEDOUT || error == ENODEV { + self.record(error); + } + } + fn submit(&self) -> Result { + match self.error.get() { + 0 => Ok(()), + code => Err(Error(code)), + } + } +} +#[derive(Default)] +struct Fence { + error: Cell, + signals: Cell, +} +impl Fence { + fn set_error(&self, error: Error) { self.error.set(error.0); } + fn signal(&self) { self.signals.set(self.signals.get() + 1); } +} +#[derive(Default)] +struct Guard(Cell); +impl Guard { + fn quarantine(&self) { self.0.set(true); } +} +struct Packet<'a> { + vm: &'a Vm, + vm_job: JobGuard, + finish_state: AtomicU8, + guard_pinned: AtomicBool, + completion: Fence, + commands: [(); 1], +} +struct JobGuard(Mutex>); +impl JobGuard { + fn lock(&self) -> std::sync::MutexGuard<'_, Option> { self.0.lock().unwrap() } +} +macro_rules! pr_info { ($($arg:tt)*) => { let _ = format_args!($($arg)*); }; } +mod debug { + pub enum DebugFlags { M3PassTiming } + pub fn debug_enabled(_: DebugFlags) -> bool { false } +} +mod m3 { + pub mod agx_memory { pub fn publish() {} } + pub mod m3_runtime { pub fn physical_counter() -> u64 { 0 } } +} + +impl<'a> Packet<'a> { + fn new(vm: &'a Vm, guard: bool) -> Self { + Self { + vm, + vm_job: JobGuard(Mutex::new(guard.then(Guard::default))), + finish_state: AtomicU8::new(0), + guard_pinned: AtomicBool::new(false), + completion: Fence::default(), + commands: [()], + } + } + fn profile_id(&self) -> usize { 0 } +""" + +TESTS = r""" +} + +#[test] +fn direct_packet_rejection_leaves_vm_admissible() { + let guilty = Vm::default(); + let other = Vm::default(); + let faulty = Packet::new(&guilty, true); + let rejected = Packet::new(&other, false); + faulty.finish(Err(EIO)); + rejected.fail_packet(EBUSY); + assert_eq!(guilty.error.get(), -5); + assert!(faulty.vm_job.lock().as_ref().unwrap().0.get()); + assert_eq!(rejected.completion.error.get(), -16); + assert_eq!(other.error.get(), 0); + assert!(other.submit().is_ok()); + + let later = Packet::new(&other, true); + later.retired(); + assert_eq!(later.completion.error.get(), 0); + assert_eq!(later.completion.signals.get(), 1); + assert!(later.vm_job.lock().is_none()); +} + +#[test] +fn cancellation_preserves_live_guard_and_signals_once() { + let vm = Vm::default(); + let packet = Packet::new(&vm, true); + packet.fail_packet(ECANCELED); + assert_eq!(vm.error.get(), 0); + assert_eq!(packet.completion.error.get(), -125); + assert!(packet.vm_job.lock().as_ref().unwrap().0.get()); + packet.retired(); + assert!(packet.vm_job.lock().is_none()); + assert_eq!(packet.completion.signals.get(), 1); + assert_eq!(packet.completion.error.get(), -125); + // Clean retirement closes the state to TERMINAL: a racing post-retirement fault must not poison VmStatus. + packet.finish(Err(EIO)); + assert_eq!(vm.error.get(), 0); + assert_eq!(packet.completion.signals.get(), 1); +} + +#[test] +fn terminal_vm_error_remains_visible_and_blocks_the_same_vm() { + let vm = Vm::default(); + let faulty = Packet::new(&vm, true); + faulty.finish(Err(EIO)); + assert_eq!(vm.submit().unwrap_err().0, -5); + assert_eq!(faulty.completion.signals.get(), 1); + assert_eq!(faulty.completion.error.get(), -5); +} + +#[test] +fn cancel_before_terminal_fault_records_vm_error_without_resignaling() { + let vm = Vm::default(); + let packet = Packet::new(&vm, true); + packet.fail_packet(ECANCELED); + assert_eq!(vm.error.get(), 0); + assert_eq!(packet.completion.signals.get(), 1); + assert_eq!(packet.completion.error.get(), -125); + packet.finish(Err(EIO)); + assert_eq!(vm.error.get(), -5); + assert_eq!(packet.completion.signals.get(), 1); + assert_eq!(packet.completion.error.get(), -125); +} + +#[test] +fn fail_packet_records_device_loss_errors() { + for err in [EIO, ETIMEDOUT, ENODEV] { + let vm = Vm::default(); + let packet = Packet::new(&vm, false); + packet.fail_packet(err); + assert_eq!(vm.error.get(), err.0); + assert_eq!(packet.completion.error.get(), err.0); + assert_eq!(packet.completion.signals.get(), 1); + } +} + +#[test] +fn terminal_fault_pins_guard_against_release_guard() { + let vm = Vm::default(); + let packet = Packet::new(&vm, true); + packet.finish(Err(EIO)); + assert!(packet.vm_job.lock().as_ref().unwrap().0.get()); + // Subsequent fail_front() / withdraw() calls must not release a quarantined guard. + packet.release_guard(); + assert!(packet.vm_job.lock().is_some()); + assert!(packet.vm_job.lock().as_ref().unwrap().0.get()); +} + +#[test] +fn cancel_then_terminal_fault_pins_guard_against_release_guard() { + let vm = Vm::default(); + let packet = Packet::new(&vm, true); + packet.fail_packet(ECANCELED); + packet.finish(Err(EIO)); + packet.release_guard(); + assert!(packet.vm_job.lock().is_some()); + assert!(packet.vm_job.lock().as_ref().unwrap().0.get()); +} +""" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--static", action="store_true", help="link without guest libraries") + parser.add_argument("--mutate", action="store_true") + args = parser.parse_args() + repo = Path(__file__).resolve().parents[2] + path = repo / "drivers/gpu/drm/asahi/m3/m3_submit.rs" + source = path.read_text().split("impl Packet {", 1)[1] + if args.mutate: + source = source.replace( + "self.complete(Err(error), false);", "self.complete(Err(error), true);" + ) + methods = ("release_guard", "retired", "finish", "fail_packet", "complete") + extracted = [method(source, f"fn {name}(&self") for name in methods] + args.out.mkdir(parents=True, exist_ok=True) + program = args.out / "packet-completion.rs" + program.write_text(MOCKS + "\n".join(extracted) + TESTS) + binary = args.out.resolve() / "tests" + flags = ["-C", "target-feature=+crt-static"] if args.static else [] + subprocess.run( + ["rustc", "--test", "--edition=2021", *flags, str(program), "-o", str(binary)], + check=True, + ) + return subprocess.run([str(binary)], check=False).returncode + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/asahi/m3-recovery-tests.py b/tools/asahi/m3-recovery-tests.py new file mode 100755 index 00000000000000..b31929f9e64bc0 --- /dev/null +++ b/tools/asahi/m3-recovery-tests.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host tests for M3 Extended shared per-client GPU fault recovery logic.""" +import argparse +from pathlib import Path +import subprocess + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--static", action="store_true", help="link without guest libraries") + parser.add_argument("--mutate", action="store_true") + args = parser.parse_args() + repo = Path(__file__).resolve().parents[2] + src = repo / "drivers/gpu/drm/asahi/m3/m3_recovery.rs" + args.out.mkdir(parents=True, exist_ok=True) + entry = src + if args.mutate: + # Negative control: drop the cumulative quarantine budget limit. + text = src.read_text() + target = "Some(total) => total <= self.limit," + if target not in text: + raise RuntimeError("mutation target missing in m3_recovery.rs") + g16_logic = (repo / "drivers/gpu/drm/asahi/g16/recovery/logic.rs").resolve() + mutated = text.replace( + '#[path = "../g16/recovery/logic.rs"]', + f'#[path = "{g16_logic}"]', + ).replace(target, "Some(_) => true,") + entry = args.out / "m3_recovery_mut.rs" + entry.write_text(mutated) + binary = args.out.resolve() / "tests" + flags = ["-C", "target-feature=+crt-static"] if args.static else [] + subprocess.run( + ["rustc", "--test", "--edition=2021", *flags, str(entry), "-o", str(binary)], + check=True, + ) + return subprocess.run([str(binary)], check=False).returncode + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/asahi/m3-runtime-tests.rs b/tools/asahi/m3-runtime-tests.rs index 0d6d4e5841194f..5437c254e31d14 100644 --- a/tools/asahi/m3-runtime-tests.rs +++ b/tools/asahi/m3-runtime-tests.rs @@ -109,3 +109,6 @@ fn extended_parameter_aliases_are_gpu_only_and_legacy_is_unchanged() { #[path = "../../drivers/gpu/drm/asahi/m3/m3_completion_policy.rs"] mod m3_completion_policy; + +#[path = "../../drivers/gpu/drm/asahi/m3/m3_recovery.rs"] +mod m3_recovery; diff --git a/tools/asahi/m3-uapi-tests.rs b/tools/asahi/m3-uapi-tests.rs index 4dc6012f5213e7..dfbbdfe1c82ac1 100644 --- a/tools/asahi/m3-uapi-tests.rs +++ b/tools/asahi/m3-uapi-tests.rs @@ -750,6 +750,63 @@ fn attachment_validation_rejects_readonly_zero_and_wrapped_ranges() { } } +#[test] +fn helpers_are_empty_or_a_mapped_program_with_a_writable_argument_block() { + let queue = QueueUscWindow { + base: USC_WINDOW_SIZE, + user_start: 0x4000, + user_end: 2 * USC_WINDOW_SIZE, + }; + let mut region = Region { + start: queue.base + 8, + end: queue.base + 0x100, + writable: true, + }; + let none = UapiHelperProgram { + binary: 0, + config: 0, + data: 0, + }; + let helper = UapiHelperProgram { + binary: 9, + config: 0x40, + data: queue.base + 0x40, + }; + assert_eq!(validate_helper(queue, ®ion, none), Ok(())); + assert_eq!(validate_helper(queue, ®ion, helper), Ok(())); + // A configuration or argument block without a program. + for stray in [ + UapiHelperProgram { config: 0x40, ..none }, + UapiHelperProgram { data: helper.data, ..none }, + ] { + assert_eq!( + validate_helper(queue, ®ion, stray), + Err(UapiTranslateError::ProgramOffset) + ); + } + // A program outside the mapping, a misaligned, unmapped or missing argument block. + assert_eq!( + validate_helper(queue, ®ion, UapiHelperProgram { binary: 0x200, ..helper }), + Err(UapiTranslateError::AddressRange) + ); + assert_eq!( + validate_helper(queue, ®ion, UapiHelperProgram { data: helper.data + 4, ..helper }), + Err(UapiTranslateError::AddressAlignment) + ); + for data in [0, queue.base + 0x100, u64::MAX & !7] { + assert_eq!( + validate_helper(queue, ®ion, UapiHelperProgram { data, ..helper }), + Err(UapiTranslateError::AddressRange) + ); + } + // The argument block must be writable. + region.writable = false; + assert_eq!( + validate_helper(queue, ®ion, helper), + Err(UapiTranslateError::AddressRange) + ); +} + #[test] fn usc_windows_reject_misalignment_overflow_and_unmapped_programs() { let queue = QueueUscWindow { diff --git a/tools/asahi/m5-client-handoff-tests.py b/tools/asahi/m5-client-handoff-tests.py new file mode 100644 index 00000000000000..0ebd1c116441d0 --- /dev/null +++ b/tools/asahi/m5-client-handoff-tests.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Compile the production M5 render-job handoff with mock mappings. + +M5GraphicsJob::rebind_vm, M5GraphicsMemory::rebind and both pools' +alias_into must clear the data storage the previous VM used (USC blocks, +parameter-buffer blocks, scene scratch, discard page, compute storage) before +another VM maps it, keep the allocator and parameter-manager state the +firmware refers to (USC directory and free list, page list, metrics), clear +nothing for a same-VM resubmission and nothing before full retirement. + +--mutations also runs the unfixed source and each clear removed; every one +must be killed. +""" +from pathlib import Path +import os +import subprocess +import sys +import tempfile + +LINUX = Path(__file__).resolve().parents[2] +RESOURCES = 'drivers/gpu/drm/asahi/m5/resources/' +FILES = {'usc': 'graphics_usc.rs', 'pb': 'parameter_buffer.rs', + 'memory': 'graphics_memory.rs', 'job': 'graphics_job.rs'} +BASE = 'c5e25e0925351' + + +def item(source, signature): + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end].replace('pub(super) ', '') + + +def current(): + return {key: (LINUX / RESOURCES / name).read_text() for key, name in FILES.items()} + + +def original(): + return {key: subprocess.run(['git', '-C', str(LINUX), 'show', f'{BASE}:{RESOURCES}{name}'], + check=True, capture_output=True, text=True).stdout + for key, name in FILES.items()} + + +PRELUDE = r''' +#![allow(warnings)] +use std::cell::RefCell; +use std::sync::atomic::{fence, Ordering}; +type Error = i32; +type Result = core::result::Result; +const EINVAL: i32 = -22; const EOVERFLOW: i32 = -75; const ERANGE: i32 = -34; +const EFAULT: i32 = -14; const EBUSY: i32 = -16; const ENOTSUPP: i32 = -524; +const GFP_KERNEL: () = (); +macro_rules! dev_dbg { ($($t:tt)*) => {} } +struct KVec(Vec); +impl KVec { + fn new() -> Self { Self(Vec::new()) } + fn push(&mut self, value: T, _: ()) -> Result { self.0.push(value); Ok(()) } +} +impl core::ops::Deref for KVec { type Target = Vec; fn deref(&self) -> &Vec { &self.0 } } +impl core::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } +impl IntoIterator for KVec { + type Item = T; type IntoIter = std::vec::IntoIter; + fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } +} +mod mmu { + pub type Prot = u32; + pub const PROT_GPU_SHARED_RW: Prot = 3; + pub const UAT_PGSZ: usize = 0x4000; + pub struct KernelMapping(pub &'static str, pub u64); + pub struct VmJobGuard(pub u64); + #[derive(Clone)] + pub struct Vm(pub u64); + impl Vm { + pub fn id(&self) -> u64 { self.0 } + pub fn kernel_range(&self) -> core::ops::Range { 0x10_0000_0000..0x20_0000_0000 } + pub fn retain_job(&self) -> super::Result { Ok(VmJobGuard(self.0)) } + } + pub struct M5ExecutionContext { pub vm: Vm } + impl M5ExecutionContext { + pub fn rebind(&mut self, vm: &Vm) -> super::Result { self.vm = vm.clone(); Ok(()) } + pub fn vm(&self) -> &Vm { &self.vm } + pub fn context_id(&self) -> u8 { 3 } + pub fn roots(&self) -> [u64; 2] { [0, 0] } + } +} +mod m5 { pub mod vm_layout { + pub fn compact_range(r: &core::ops::Range) -> Option> { Some(r.clone()) } + pub fn auxiliary_range(r: &core::ops::Range) -> Option> { Some(r.clone()) } +} } +use m5::vm_layout; +struct AsahiDrmDevice; +impl AsahiDrmDevice { fn as_ref(&self) -> &Self { self } } +thread_local! { static MAPS: RefCell> = RefCell::new(Vec::new()); } +struct MappedObject { name: &'static str, bytes: Vec, iova: u64, logical_size: usize, home: u64 } +impl MappedObject { + fn new(name: &'static str, iova: u64, logical_size: usize) -> Self { + Self { name, bytes: vec![0; 256], iova, logical_size, home: 1 } + } + fn iova(&self) -> u64 { self.iova } + fn with_bytes_mut(&mut self, f: impl FnOnce(&mut [u8]) -> Result) -> Result { f(&mut self.bytes) } + fn map_alias_at_with_guards(&mut self, vm: &mmu::Vm, address: u64, _: mmu::Prot, _: usize) + -> Result> { + let zero = self.bytes.iter().all(|b| *b == 0); + MAPS.with(|m| m.borrow_mut().push((self.name, vm.id(), zero))); + if vm.id() == self.home { return if address == self.iova { Ok(None) } else { Err(EINVAL) }; } + Ok(Some(mmu::KernelMapping(self.name, vm.id()))) + } +} +// graphics_usc.rs +const DIRECTORY_ENTRIES: usize = 0x80000; +const BLOCK_BYTES: usize = 0x20_0000; +const BLOCK_COUNT: usize = 19; +struct M5GraphicsUsc { directory: MappedObject, freelist: MappedObject, blocks: KVec } +impl M5GraphicsUsc { + fn validate_mappings(&self, _: &mmu::Vm) -> Result { Ok(()) } +@@USC@@ +} +// parameter_buffer.rs +struct M5ParameterBuffer { blocks: [MappedObject; 3], page_list: MappedObject, metrics: MappedObject, + scene_scratch: MappedObject, discard: MappedObject } +impl M5ParameterBuffer { + fn validate(&self, _: &mmu::Vm) -> Result { Ok(()) } +@@PB@@ +} +// graphics_memory.rs +struct M5GraphicsMemory { context: mmu::M5ExecutionContext, user_mappings: Option, + pages: KVec, usc: M5GraphicsUsc, output_first: Option } +impl M5GraphicsMemory { + fn vm(&self) -> &mmu::Vm { self.context.vm() } +@@MEMORY@@ +} +// graphics_job.rs +struct M5GraphicsJob { program: M5GraphicsMemory, parameter_buffer: M5ParameterBuffer, + compute_storage: MappedObject, vm_aliases: KVec, generation: u32, + status: [u32; 2], stamps: [u32; 5] } +impl M5GraphicsJob { + fn scheduler_status(&mut self) -> Result<[u32; 2]> { Ok(self.status) } + fn progress(&mut self) -> Result<[u32; 5]> { Ok(self.stamps) } +@@OWNS@@ +@@JOB@@ +} +const DATA: [&str; 25] = ["usc0", "usc1", "usc2", "usc3", "usc4", "usc5", "usc6", "usc7", "usc8", + "usc9", "usc10", "usc11", "usc12", "usc13", "usc14", "usc15", "usc16", "usc17", "usc18", + "pb0", "pb1", "pb2", "scene", "discard", "compute"]; +const KEPT: [&str; 4] = ["directory", "freelist", "page_list", "metrics"]; +fn objects(job: &mut M5GraphicsJob) -> Vec<&mut MappedObject> { + let usc = &mut job.program.usc; + let pb = &mut job.parameter_buffer; + let mut out: Vec<&mut MappedObject> = vec![&mut usc.directory, &mut usc.freelist]; + out.extend(usc.blocks.0.iter_mut()); + out.extend(pb.blocks.iter_mut()); + out.extend([&mut pb.page_list, &mut pb.metrics, &mut pb.scene_scratch, &mut pb.discard, + &mut job.compute_storage]); + out +} +fn fill(job: &mut M5GraphicsJob, value: u8) { + for object in objects(job) { object.bytes.fill(value); } +} +fn snapshot(job: &mut M5GraphicsJob) -> Vec<(&'static str, Vec)> { + objects(job).into_iter().map(|o| (o.name, o.bytes.clone())).collect() +} +fn handoff(job: &mut M5GraphicsJob, vm: u64, value: u8) { + MAPS.with(|m| m.borrow_mut().clear()); + fill(job, value); + job.rebind_vm(&AsahiDrmDevice, &mmu::Vm(vm)).unwrap(); + let maps = MAPS.with(|m| m.borrow().clone()); + for name in DATA.iter() { + let entry = maps.iter().find(|(n, v, _)| n == name && *v == vm) + .unwrap_or_else(|| panic!("{} not mapped into vm {}", name, vm)); + assert!(entry.2, "{} still holds the previous VM data when vm {} maps it", name, vm); + } + for object in objects(job) { + if KEPT.contains(&object.name) { + assert!(object.bytes.iter().all(|b| *b == value), "{} allocator state must be kept", object.name); + } + } + assert!(job.owns_vm(&mmu::Vm(vm))); +} +fn main() { + let mut iova = 0x10_0000_0000u64; + let mut next = |size: usize| { let at = iova; iova += (size as u64 + 0xc000 + 0x7fff) & !0x7fff; at }; + let usc_blocks = (0..BLOCK_COUNT).map(|i| MappedObject::new(DATA[i], next(BLOCK_BYTES), BLOCK_BYTES)).collect(); + let usc = M5GraphicsUsc { + directory: MappedObject::new("directory", next(DIRECTORY_ENTRIES * 8), DIRECTORY_ENTRIES * 8), + freelist: MappedObject::new("freelist", next(0x4000), 0x4000), blocks: KVec(usc_blocks) }; + let pb = M5ParameterBuffer { + blocks: [MappedObject::new("pb0", next(0x80000), 0x80000), MappedObject::new("pb1", next(0x80000), 0x80000), + MappedObject::new("pb2", next(0x80000), 0x80000)], + page_list: MappedObject::new("page_list", next(0x1c000), 0x1c000), + metrics: MappedObject::new("metrics", next(0x4000), 0x4000), + scene_scratch: MappedObject::new("scene", next(0x4000), 0x4000), + discard: MappedObject::new("discard", next(0x8000), 0x8000) }; + let mut job = M5GraphicsJob { + program: M5GraphicsMemory { context: mmu::M5ExecutionContext { vm: mmu::Vm(1) }, + user_mappings: None, pages: KVec::new(), usc, output_first: None }, + parameter_buffer: pb, compute_storage: MappedObject::new("compute", next(0x28000), 0x28000), + vm_aliases: KVec::new(), generation: 7, status: [2, 0], stamps: [2, 0x700, 0, 0x700, 0] }; + // Client 1 (first owner) hands to client 2, which hands back, then to 3. + handoff(&mut job, 2, 0xa5); + assert_eq!(job.vm_aliases.len(), DATA.len() + KEPT.len(), "views of every pool object in vm 2"); + handoff(&mut job, 1, 0x5a); + assert!(job.vm_aliases.is_empty(), "the first owner keeps its own mappings"); + handoff(&mut job, 3, 0x3c); + // Same-VM resubmission: no clear. + fill(&mut job, 0x77); + let before = snapshot(&mut job); + job.rebind_vm(&AsahiDrmDevice, &mmu::Vm(3)).unwrap(); + assert!(before == snapshot(&mut job), "same-VM resubmission must not clear"); + // Not retired: nothing is cleared while firmware may still use the pools. + for (status, stamps) in [([1, 0], [2, 0x700, 0, 0x700, 0]), ([2, 0], [2, 0x600, 0, 0x700, 0]), + ([2, 0], [2, 0x700, 0, 0x600, 0]), ([2, 1], [2, 0x700, 0, 0x700, 0])] { + job.status = status; job.stamps = stamps; + assert_eq!(job.rebind_vm(&AsahiDrmDevice, &mmu::Vm(4)).err(), Some(EBUSY)); + assert!(before == snapshot(&mut job), "busy job storage must be untouched"); + } + println!("PASS 3 client handoffs clear 25 data objects before the next VM maps them; allocator state kept; same-VM and 4 unretired cases untouched"); +} +''' + + +def fixture(src): + return (PRELUDE.replace('@@USC@@', item(src['usc'], 'pub(super) fn alias_into(')) + .replace('@@PB@@', item(src['pb'], 'pub(super) fn alias_into(')) + .replace('@@MEMORY@@', item(src['memory'], 'pub(super) fn rebind(')) + .replace('@@OWNS@@', item(src['job'], 'pub(super) fn owns_vm(')) + .replace('@@JOB@@', item(src['job'], 'pub(super) fn rebind_vm('))) + + +def run(tmp, name, code): + path = Path(tmp) / (name + '.rs') + binary = path.with_suffix('') + path.write_text(code) + subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', str(path), '-o', str(binary)], + check=True) + return subprocess.run([str(binary)], capture_output=True, text=True) + + +def drop(src, key, text): + assert text in src[key], (key, text) + return {**src, key: src[key].replace(text, '')} + + +def main(): + src = current() + mutations = [ + ('unfixed-' + BASE, original), + ('no-usc-block-clear', lambda: drop(src, 'usc', 'block.with_bytes_mut(|out| { out.fill(0); Ok(()) })?;')), + ('no-parameter-buffer-clear', lambda: drop(src, 'pb', 'object.with_bytes_mut(|out| { out.fill(0); Ok(()) })?;')), + ('no-compute-storage-clear', lambda: drop(src, 'job', + 'self.compute_storage.with_bytes_mut(|out| { out.fill(0); Ok(()) })?;')), + ] + with tempfile.TemporaryDirectory(prefix='m5-client-handoff-') as tmp: + result = run(tmp, 'fixed', fixture(src)) + assert result.returncode == 0, result.stderr + print(result.stdout.strip()) + if '--mutations' not in sys.argv[1:]: + return + killed = 0 + for name, make in mutations: + result = run(tmp, name.replace('-', '_'), fixture(make())) + assert result.returncode != 0 and 'still holds the previous VM data' in result.stderr, \ + (name, result.stdout, result.stderr) + killed += 1 + print('PASS mutant killed:', name) + print(f'PASS {killed}/{len(mutations)} mutants killed') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/m5-hotspot-fans-dt-tests.py b/tools/asahi/m5-hotspot-fans-dt-tests.py new file mode 100644 index 00000000000000..91850204ac4558 --- /dev/null +++ b/tools/asahi/m5-hotspot-fans-dt-tests.py @@ -0,0 +1,917 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Check which device trees let the M5 hotspot fan assistance set fans. + +drivers/hwmon/macsmc-hwmon.c owns all apple,smc-hwmon DT binding knowledge: +- macsmc_hwmon_parse_fan_assist(): requires exactly one key in + apple,soc-die-keys (no hardcoded SMC key name) plus valid DT-supplied + apple,soc-die-fan-trip-millicelsius, apple,soc-die-fan-hysteresis-millicelsius, + and apple,soc-die-fan-hold-ms. +- macsmc_hwmon_hotspot_assist_available(): checks whether an available + apple,smc-hwmon node (with all parents available) carries that policy and + at least one settable fan with apple,fan-manual-control. +- macsmc_hwmon_fans_request_manual(): drives only fans marked with + apple,fan-manual-control, leaving closed siblings untouched. +- drivers/gpu/drm/asahi/g17/fans.c: asahi_fans_request_described() gates + boost requests on macsmc_hwmon_hotspot_assist_policy() and delegates to + macsmc_hwmon_fans_request_manual(). + +This compiles the real functions from drivers/hwmon/macsmc-hwmon.c and +drivers/gpu/drm/asahi/g17/fans.c against libfdt and runs them on synthetic +trees and the T6050 board trees, including J716c without #2208, with #2208 +alone (no trip properties -> must stay off), and with #2208 plus trip +properties, and also compiles FanBoost from drivers/gpu/drm/asahi/g17/thermal.rs +with rustc to test partial budget/hotspot request failure and handoff cleanup. +--mutation drops one condition, which a case must catch. +""" + +import argparse +import os +from pathlib import Path +import re +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[2] + +HWMON_FIRST = "static bool macsmc_hwmon_fan_settable(const struct device_node *fan)" +HWMON_LAST = "EXPORT_SYMBOL_GPL(macsmc_hwmon_hotspot_assist_available);" +FANS_FIRST = "int asahi_fans_request_described(struct device *dev, unsigned int permille," + +# Board trees: the exact fans the request may write there, or None when the tree +# does not select the assistance. +BOARDS = { + "t6050-j714s": None, + "t6050-j716s": None, + "t6050-j775d": None, +} +J716C_FANS = ["fan-F0Ac", "fan-F1Ac"] + +# J716c #2208 description without active trip properties (must stay off). +J716C_2208_NO_TRIP = """ +#include "hwmon-fan-dual.dtsi" +&smc_hwmon { + status = "okay"; + fan-F0Ac { apple,fan-mode = "F0md"; apple,fan-manual-control; }; + fan-F1Ac { apple,fan-mode = "F1md"; apple,fan-manual-control; }; +}; +""" + +# J716c #2208 description with active trip properties on macsmc_soc_die. +J716C_2208_WITH_TRIP = """ +#include "hwmon-fan-dual.dtsi" +&smc_hwmon { + status = "okay"; + apple,soc-die-fan-trip-millicelsius = <98000>; + apple,soc-die-fan-hysteresis-millicelsius = <16000>; + apple,soc-die-fan-hold-ms = <30000>; + fan-F0Ac { apple,fan-mode = "F0md"; apple,fan-manual-control; }; + fan-F1Ac { apple,fan-mode = "F1md"; apple,fan-manual-control; }; +}; +""" + +KEYS = ('apple,key-id = "F{n}Ac"; apple,fan-minimum = "F{n}Mn"; apple,fan-maximum = "F{n}Mx"; ' + 'apple,fan-target = "F{n}Tg"; ') +MODE = KEYS + 'apple,fan-mode = "F{n}md"; ' +MANUAL = "apple,fan-manual-control;" +TRIP = ('apple,soc-die-fan-trip-millicelsius = <98000>; ' + 'apple,soc-die-fan-hysteresis-millicelsius = <16000>; ' + 'apple,soc-die-fan-hold-ms = <30000>;') +DIE_TCMB = 'apple,soc-die-keys = "TCMb"; ' + TRIP +DIE_OTHER = 'apple,soc-die-keys = "Tg0D"; ' + TRIP + +# name: (hwmon properties, [per-fan properties], fans written or None, expected policy or None) +SYNTHETIC = { + "both": (DIE_TCMB, [MODE + MANUAL, MODE + MANUAL], ["fan-F0Ac", "fan-F1Ac"], (98000, 82000, 30000)), + "one-fan": (DIE_TCMB, [MODE + MANUAL], ["fan-F0Ac"], (98000, 82000, 30000)), + # Any single SoC die key works (no hardcoded TCMb key name in driver). + "other-single-die-key": (DIE_OTHER, [MODE + MANUAL], ["fan-F0Ac"], (98000, 82000, 30000)), + # Manual-only request writes only fans with apple,fan-manual-control; closed siblings stay untouched. + "manual-and-monitor-only": (DIE_TCMB, [MODE + MANUAL, KEYS], ["fan-F0Ac"], (98000, 82000, 30000)), + "second-fan-only": (DIE_TCMB, [MODE, MODE + MANUAL], ["fan-F1Ac"], (98000, 82000, 30000)), + "first-fan-only": (DIE_TCMB, [MODE + MANUAL, MODE], ["fan-F0Ac"], (98000, 82000, 30000)), + # Opened, but without the keys to set it: nothing the request could write. + "manual-without-keys": (DIE_TCMB, ['apple,fan-mode = "F{n}md"; ' + MANUAL], None, None), + "manual-without-mode": (DIE_TCMB, [KEYS + MANUAL], None, None), + "no-manual-fan": (DIE_TCMB, [MODE], None, None), + "no-fans": (DIE_TCMB, [], None, None), + # Missing or invalid SoC die key list. + "no-die-zone": (TRIP, [MODE + MANUAL], None, None), + "die-zone-of-several": ('apple,soc-die-keys = "TCMb", "Tg0D"; ' + TRIP, [MODE + MANUAL], None, None), + "temperature-node-only": (TRIP + ' temperature-TCMb { apple,key-id = "TCMb"; };', + [MODE + MANUAL], None, None), + # Missing or invalid DT trip / hysteresis / hold properties (must stay off, no hardcoded fallback). + "no-trip": ('apple,soc-die-keys = "TCMb";', [MODE + MANUAL], None, None), + "missing-hyst": ('apple,soc-die-keys = "TCMb"; apple,soc-die-fan-trip-millicelsius = <98000>; ' + 'apple,soc-die-fan-hold-ms = <30000>;', [MODE + MANUAL], None, None), + "missing-hold": ('apple,soc-die-keys = "TCMb"; apple,soc-die-fan-trip-millicelsius = <98000>; ' + 'apple,soc-die-fan-hysteresis-millicelsius = <16000>;', [MODE + MANUAL], None, None), + "zero-hyst": ('apple,soc-die-keys = "TCMb"; apple,soc-die-fan-trip-millicelsius = <98000>; ' + 'apple,soc-die-fan-hysteresis-millicelsius = <0>; apple,soc-die-fan-hold-ms = <30000>;', + [MODE + MANUAL], None, None), + "hyst-ge-trip": ('apple,soc-die-keys = "TCMb"; apple,soc-die-fan-trip-millicelsius = <98000>; ' + 'apple,soc-die-fan-hysteresis-millicelsius = <98000>; apple,soc-die-fan-hold-ms = <30000>;', + [MODE + MANUAL], None, None), + "trip-too-high": ('apple,soc-die-keys = "TCMb"; apple,soc-die-fan-trip-millicelsius = <160000>; ' + 'apple,soc-die-fan-hysteresis-millicelsius = <16000>; apple,soc-die-fan-hold-ms = <30000>;', + [MODE + MANUAL], None, None), + "zero-hold": ('apple,soc-die-keys = "TCMb"; apple,soc-die-fan-trip-millicelsius = <98000>; ' + 'apple,soc-die-fan-hysteresis-millicelsius = <16000>; apple,soc-die-fan-hold-ms = <0>;', + [MODE + MANUAL], None, None), +} + +HARNESS = r""" +#include +#include +#include +#include +#include +#include +#include "libfdt.h" + +typedef uint32_t u32; +#define MACSMC_DIE_MAX_MC 150000 +#define EXPORT_SYMBOL_GPL(sym) + +struct macsmc_hwmon_fan_assist { + int trigger_mc; + int release_mc; + unsigned int hold_ms; +}; + +static const void *blob; +struct device_node { int offset; }; +struct device { struct device_node *of_node; }; + +static void free_node(struct device_node **node) { free(*node); } +#define __free(kind) __attribute__((cleanup(free_node))) + +static struct device_node *node_at(int offset) +{ + struct device_node *node = malloc(sizeof(*node)); + if (!node) + abort(); + node->offset = offset; + return node; +} + +static struct device_node *of_node_get(struct device_node *np) +{ + return np ? node_at(np->offset) : NULL; +} + +static void of_node_put(struct device_node *np) +{ + free(np); +} + +static struct device_node *of_get_parent(const struct device_node *np) +{ + int offset = fdt_parent_offset(blob, np->offset); + + return offset < 0 ? NULL : node_at(offset); +} + +static struct device_node *of_get_next_child_with_prefix(const struct device_node *parent, + struct device_node *prev, const char *prefix) +{ + int offset = prev ? fdt_next_subnode(blob, prev->offset) + : fdt_first_subnode(blob, parent->offset); + free(prev); + for (; offset >= 0; offset = fdt_next_subnode(blob, offset)) + if (!strncmp(fdt_get_name(blob, offset, NULL), prefix, strlen(prefix))) + return node_at(offset); + return NULL; +} + +#define for_each_child_of_node_with_prefix(parent, child, prefix) \ + for (struct device_node *child __free(device_node) = \ + of_get_next_child_with_prefix(parent, NULL, prefix); \ + child != NULL; \ + child = of_get_next_child_with_prefix(parent, child, prefix)) + +static struct device_node *of_find_compatible_node(struct device_node *from, const char *type, + const char *compatible) +{ + int offset = fdt_node_offset_by_compatible(blob, from ? from->offset : -1, compatible); + + (void)type; + free(from); + return offset < 0 ? NULL : node_at(offset); +} + +#define for_each_compatible_node(dn, type, compatible) \ + for (dn = of_find_compatible_node(NULL, type, compatible); dn; \ + dn = of_find_compatible_node(dn, type, compatible)) + +static bool of_device_is_available(const struct device_node *np) +{ + const char *status = fdt_getprop(blob, np->offset, "status", NULL); + + return !status || !strcmp(status, "okay") || !strcmp(status, "ok"); +} + +static bool of_property_read_bool(const struct device_node *np, const char *name) +{ + return fdt_getprop(blob, np->offset, name, NULL) != NULL; +} + +static bool of_property_present(const struct device_node *np, const char *name) +{ + return of_property_read_bool(np, name); +} + +static int of_property_count_strings(const struct device_node *np, const char *name) +{ + return fdt_stringlist_count(blob, np->offset, name); +} + +static int of_property_read_u32(const struct device_node *np, const char *name, u32 *out) +{ + int len; + const fdt32_t *val = fdt_getprop(blob, np->offset, name, &len); + + if (!val || len != 4) + return -EINVAL; + *out = fdt32_to_cpu(*val); + return 0; +} + +HWMON_BODY + +static int macsmc_hwmon_hotspot_assist_policy(struct device *dev, + struct macsmc_hwmon_fan_assist *policy) +{ + if (!dev || !dev->of_node) + return -ENODEV; + return macsmc_hwmon_node_hotspot_assist(dev->of_node, policy) ? 0 : -ENODEV; +} + +/* + * Stand-in for macsmc_hwmon_fans_request_manual(): models the real manual_only + * filter in drivers/hwmon/macsmc-hwmon.c (verified by assertion in extract()). + */ +static int requests; +static int macsmc_hwmon_fans_request_manual(struct device *dev, unsigned int permille, + unsigned int min_step_rpm) +{ + int fan; + int count = 0; + + (void)permille; + (void)min_step_rpm; + requests++; + fdt_for_each_subnode(fan, blob, dev->of_node->offset) { + const char *name = fdt_get_name(blob, fan, NULL); + bool manual = fdt_getprop(blob, fan, "apple,fan-manual-control", NULL) != NULL; + + if (strncmp(name, "fan-", 4) || + !fdt_getprop(blob, fan, "apple,fan-mode", NULL) || + !fdt_getprop(blob, fan, "apple,fan-target", NULL) || + !fdt_getprop(blob, fan, "apple,fan-minimum", NULL) || + !fdt_getprop(blob, fan, "apple,fan-maximum", NULL)) + continue; + if (MANUAL_FILTER) + continue; + printf(" %s=%s", name, manual ? "manual" : "closed"); + count++; + } + return count ? 5000 : -ENODEV; +} + +FANS_BODY + +int main(int argc, char **argv) +{ + static char buffer[1 << 22]; + FILE *file = fopen(argv[1], "rb"); + int hwmon; + + if (argc != 2 || !file || fread(buffer, 1, sizeof(buffer), file) == 0) + return 2; + blob = buffer; + printf("%s\n", macsmc_hwmon_hotspot_assist_available() ? "governs" : "idle"); + for (hwmon = fdt_node_offset_by_compatible(blob, -1, "apple,smc-hwmon"); hwmon >= 0; + hwmon = fdt_node_offset_by_compatible(blob, hwmon, "apple,smc-hwmon")) { + char path[256]; + struct device_node node = { .offset = hwmon }; + struct device dev = { .of_node = &node }; + struct macsmc_hwmon_fan_assist policy = {}; + int pret, ret; + + fdt_get_path(blob, hwmon, path, sizeof(path)); + printf("%s", path); + pret = macsmc_hwmon_hotspot_assist_policy(&dev, &policy); + requests = 0; + ret = asahi_fans_request_described(&dev, 1000, 0); + if (ret < 0) + printf(" refused\n"); + else if (pret == 0) + printf(" policy=%d,%d,%u accepted\n", + policy.trigger_mc, policy.release_mc, policy.hold_ms); + else + printf(" policy=none accepted\n"); + } + return 0; +} +""" + + +def extract(tree, mutation): + hwmon_src = (tree / "drivers/hwmon/macsmc-hwmon.c").read_text() + fans_src = (tree / "drivers/gpu/drm/asahi/g17/fans.c").read_text() + + # Verify the GPU driver no longer hardcodes TCMb or walks macsmc-hwmon DT bindings. + assert '"TCMb"' not in fans_src, "fans.c must not name an SMC key" + assert '"apple,fan-manual-control"' not in fans_src, "fans.c must not walk macsmc-hwmon DT" + assert '"apple,soc-die-keys"' not in fans_src, "fans.c must not walk macsmc-hwmon DT" + # Verify macsmc-hwmon.c actually applies the manual_only filter in __macsmc_hwmon_fans_request. + assert "if (manual_only && !fan->manual_control)\n\t\t\tcontinue;" in hwmon_src + + h_start = hwmon_src.index(HWMON_FIRST) + h_end = hwmon_src.index(HWMON_LAST, h_start) + len(HWMON_LAST) + hwmon_body = hwmon_src[h_start:h_end] + + f_start = fans_src.index(FANS_FIRST) + f_end = fans_src.index("\n}\n", f_start) + 3 + fans_body = fans_src[f_start:f_end] + + manual_filter = "!manual" + + if mutation == "drop-fans": + hwmon_body, n = re.subn( + r'of_property_read_bool\(child, "apple,fan-manual-control"\)', + "true", + hwmon_body, + ) + assert n == 1, f"mutation {mutation} did not apply" + manual_filter = "false" + elif mutation == "drop-siblings": + manual_filter = "false" + elif mutation == "drop-hotspot": + hwmon_body, n = re.subn( + r'of_property_count_strings\(np, "apple,soc-die-keys"\) != 1', + "false", + hwmon_body, + ) + assert n == 1, f"mutation {mutation} did not apply" + elif mutation == "drop-trip": + hwmon_body, n = re.subn( + r'if \(of_property_read_u32\(np, "apple,soc-die-fan-trip-millicelsius", &trip\) \|\|\n' + r'\s*of_property_read_u32\(np, "apple,soc-die-fan-hysteresis-millicelsius", &hyst\) \|\|\n' + r'\s*of_property_read_u32\(np, "apple,soc-die-fan-hold-ms", &hold_ms\)\)\n' + r'\s*return false;', + "trip = 98000; hyst = 16000; hold_ms = 30000;", + hwmon_body, + ) + assert n == 1, f"mutation {mutation} did not apply" + elif mutation == "drop-settable": + hwmon_body, n = re.subn( + r'macsmc_hwmon_fan_settable\(child\)', + "true", + hwmon_body, + ) + assert n == 1, f"mutation {mutation} did not apply" + elif mutation == "drop-provider-check": + fans_body, n = re.subn( + r'if \(permille && macsmc_hwmon_hotspot_assist_policy\(dev, NULL\)\)\n\s*return -EPERM;\n', + "", + fans_body, + ) + assert n == 1, f"mutation {mutation} did not apply" + return hwmon_body, fans_body, manual_filter + + +RUST_HARNESS = r""" +#![allow(dead_code)] + +use std::sync::Mutex; + +const FAN_HOLD_NS: u64 = 30_000_000_000; +const FAN_CURVE_RELEASE_MC: i32 = 82_000; +const FAN_CURVE_STEP_RPM: u32 = 150; + +#[derive(Clone, Copy)] +struct HotspotPolicy { + trigger_mc: i32, + release_mc: i32, + hold_ns: u64, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum FanCall { + Budget(u32, u32), + Hotspot(u32, u32), +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum ReqMode { + Ok, + PartialFail, +} + +struct MockState { + enabled: bool, + hotspot_fans_only: bool, + fan_boost_enabled: bool, + fan_curve_enabled: bool, + budget_req: ReqMode, + budget_rel_ok: bool, + hotspot_req: ReqMode, + hotspot_rel_ok: bool, + budget_owned_mask: u32, + hotspot_owned_mask: u32, + calls: Vec, +} + +impl MockState { + const fn new() -> Self { + Self { + enabled: false, + hotspot_fans_only: false, + fan_boost_enabled: false, + fan_curve_enabled: true, + budget_req: ReqMode::Ok, + budget_rel_ok: true, + hotspot_req: ReqMode::Ok, + hotspot_rel_ok: true, + budget_owned_mask: 0, + hotspot_owned_mask: 0, + calls: Vec::new(), + } + } + + fn reset(&mut self) { + *self = Self::new(); + } +} + +static TEST_LOCK: Mutex<()> = Mutex::new(()); +static MOCK: Mutex = Mutex::new(MockState::new()); + +fn enabled() -> bool { + MOCK.lock().unwrap().enabled +} + +fn hotspot_fans_only() -> bool { + let s = MOCK.lock().unwrap(); + !s.enabled && s.hotspot_fans_only +} + +fn fan_boost_enabled() -> bool { + MOCK.lock().unwrap().fan_boost_enabled +} + +fn fan_curve_enabled() -> bool { + MOCK.lock().unwrap().fan_curve_enabled +} + +fn target_mc() -> i32 { + 90_000 +} + +fn fan_curve_permille(temp_mc: i32, target_mc: i32) -> i32 { + if temp_mc <= 70_000 { + 0 + } else if temp_mc <= target_mc { + (temp_mc - 70_000) * 660 / (target_mc - 70_000).max(1000) + } else { + 800 + } +} + +fn hotspot_assist_policy() -> Option { + Some(HotspotPolicy { + trigger_mc: 98_000, + release_mc: 82_000, + hold_ns: 30_000_000_000, + }) +} + +fn request_fans(permille: u32, min_step_rpm: u32) -> Option { + let mut s = MOCK.lock().unwrap(); + s.calls.push(FanCall::Budget(permille, min_step_rpm)); + if permille == 0 { + if s.budget_rel_ok { + s.budget_owned_mask = 0; + Some(0) + } else { + None + } + } else { + match s.budget_req { + ReqMode::Ok => { + s.budget_owned_mask = 0b11; + Some(5000) + } + ReqMode::PartialFail => { + s.budget_owned_mask |= 0b01; + None + } + } + } +} + +fn request_fans_described(permille: u32, min_step_rpm: u32) -> Option { + let mut s = MOCK.lock().unwrap(); + s.calls.push(FanCall::Hotspot(permille, min_step_rpm)); + if permille == 0 { + if s.hotspot_rel_ok { + s.hotspot_owned_mask = 0; + Some(0) + } else { + None + } + } else { + match s.hotspot_req { + ReqMode::Ok => { + s.hotspot_owned_mask = 0b11; + Some(5000) + } + ReqMode::PartialFail => { + s.hotspot_owned_mask |= 0b01; + None + } + } + } +} + +FAN_BOOST_BODY + +fn take_calls() -> Vec { + core::mem::take(&mut MOCK.lock().unwrap().calls) +} + +#[test] +fn partial_budget_boost_failure_cleans_up_and_blocks_handoff_until_released() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut s = MOCK.lock().unwrap(); + s.reset(); + s.enabled = true; + s.fan_boost_enabled = true; + s.hotspot_fans_only = true; + s.budget_req = ReqMode::PartialFail; + s.budget_rel_ok = true; + } + + let mut fans = FanBoost::new(); + fans.apply(true, Some(95_000), 1_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(1000, 0), FanCall::Budget(0, 0)]); + assert_eq!(MOCK.lock().unwrap().budget_owned_mask, 0); + assert!(!fans.boosted()); + + // Now fail both the partial budget boost and its immediate cleanup; verify + // handoff keeps retrying unrestricted cleanup and blocks hotspot assist until + // cleanup succeeds. + { + let mut s = MOCK.lock().unwrap(); + s.budget_rel_ok = false; + } + fans.apply(true, Some(95_000), 2_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(1000, 0), FanCall::Budget(0, 0)]); + assert_eq!(MOCK.lock().unwrap().budget_owned_mask, 0b01); + assert!(fans.boosted()); + + { + let mut s = MOCK.lock().unwrap(); + s.enabled = false; + } + fans.apply(true, Some(99_000), 3_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(0, 0)]); + { + let s = MOCK.lock().unwrap(); + assert_eq!(s.budget_owned_mask, 0b01); + assert_eq!(s.hotspot_owned_mask, 0); + } + assert!(fans.boosted()); + + { + let mut s = MOCK.lock().unwrap(); + s.budget_rel_ok = true; + } + fans.apply(true, Some(99_000), 4_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(0, 0), FanCall::Hotspot(1000, 0)]); + { + let s = MOCK.lock().unwrap(); + assert_eq!(s.budget_owned_mask, 0); + assert_eq!(s.hotspot_owned_mask, 0b11); + } + assert!(fans.boosted()); + fans.release(); +} + +#[test] +fn partial_first_curve_request_failure_cleans_up_and_blocks_handoff_until_released() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut s = MOCK.lock().unwrap(); + s.reset(); + s.enabled = true; + s.fan_boost_enabled = false; + s.fan_curve_enabled = true; + s.hotspot_fans_only = true; + s.budget_req = ReqMode::PartialFail; + s.budget_rel_ok = true; + } + + let mut fans = FanBoost::new(); + fans.apply(true, Some(95_000), 1_000_000_000); + let calls = take_calls(); + assert_eq!(calls.len(), 2); + assert!(matches!(calls[0], FanCall::Budget(p, 0) if p > 0)); + assert_eq!(calls[1], FanCall::Budget(0, 0)); + assert_eq!(MOCK.lock().unwrap().budget_owned_mask, 0); + assert!(!fans.boosted()); + + // Fail immediate cleanup after partial first curve request, then verify both + // a subsequent budget-mode step and handoff retry unrestricted cleanup first. + { + let mut s = MOCK.lock().unwrap(); + s.budget_rel_ok = false; + } + fans.apply(true, Some(95_000), 2_000_000_000); + let calls = take_calls(); + assert_eq!(calls.len(), 2); + assert!(matches!(calls[0], FanCall::Budget(p, 0) if p > 0)); + assert_eq!(calls[1], FanCall::Budget(0, 0)); + assert_eq!(MOCK.lock().unwrap().budget_owned_mask, 0b01); + assert!(fans.boosted()); + + fans.apply(true, Some(95_000), 3_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(0, 0)]); + assert_eq!(MOCK.lock().unwrap().budget_owned_mask, 0b01); + assert!(fans.boosted()); + + { + let mut s = MOCK.lock().unwrap(); + s.enabled = false; + } + fans.apply(true, Some(99_000), 4_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(0, 0)]); + { + let s = MOCK.lock().unwrap(); + assert_eq!(s.budget_owned_mask, 0b01); + assert_eq!(s.hotspot_owned_mask, 0); + } + assert!(fans.boosted()); + + { + let mut s = MOCK.lock().unwrap(); + s.budget_rel_ok = true; + } + fans.apply(true, Some(99_000), 5_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(0, 0), FanCall::Hotspot(1000, 0)]); + { + let s = MOCK.lock().unwrap(); + assert_eq!(s.budget_owned_mask, 0); + assert_eq!(s.hotspot_owned_mask, 0b11); + } + assert!(fans.boosted()); + fans.release(); +} + +#[test] +fn partial_hotspot_failure_blocks_budget_handoff_until_manual_cleanup_succeeds() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut s = MOCK.lock().unwrap(); + s.reset(); + s.enabled = false; + s.hotspot_fans_only = true; + s.hotspot_req = ReqMode::PartialFail; + s.hotspot_rel_ok = false; + } + + let mut fans = FanBoost::new(); + fans.apply(true, Some(99_000), 1_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Hotspot(1000, 0), FanCall::Hotspot(0, 0)]); + assert_eq!(MOCK.lock().unwrap().hotspot_owned_mask, 0b01); + assert!(fans.boosted()); + + { + let mut s = MOCK.lock().unwrap(); + s.enabled = true; + s.fan_boost_enabled = true; + } + fans.apply(true, Some(95_000), 2_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Hotspot(0, 0)]); + { + let s = MOCK.lock().unwrap(); + assert_eq!(s.hotspot_owned_mask, 0b01); + assert_eq!(s.budget_owned_mask, 0); + } + + { + let mut s = MOCK.lock().unwrap(); + s.hotspot_rel_ok = true; + } + fans.apply(true, Some(95_000), 3_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Hotspot(0, 0), FanCall::Budget(1000, 0)]); + { + let s = MOCK.lock().unwrap(); + assert_eq!(s.hotspot_owned_mask, 0); + assert_eq!(s.budget_owned_mask, 0b11); + } + fans.release(); +} +""" + + +def extract_fan_boost(tree, mutation): + thermal_src = (tree / "drivers/gpu/drm/asahi/g17/thermal.rs").read_text() + start = thermal_src.index("pub(crate) struct FanBoost {") + end_marker = "impl Drop for FanBoost {\n fn drop(&mut self) {\n self.release();\n }\n}" + end = thermal_src.index(end_marker, start) + len(end_marker) + body = thermal_src[start:end] + + if mutation == "drop-budget-release-pending": + body, n1 = re.subn( + r'if let Some\(rpm\) = self\.set_curve_if_moved\(permille\) \{\n' + r'\s*self\.curve_rpm = rpm;\n' + r'\s*self\.budget_release_pending = false;\n' + r'\s*\} else if self\.curve_rpm == 0 \{\n' + r'(?:\s*//[^\n]*\n)*' + r'\s*self\.budget_release_pending = !self\.set_budget\(false\);\n' + r'\s*\}', + 'if let Some(rpm) = self.set_curve_if_moved(permille) {\n self.curve_rpm = rpm;\n }', + body, + ) + assert n1 == 1, f"mutation {mutation} curve replace failed ({n1})" + body, n2 = re.subn( + r'if self\.budget_boosted \{\n' + r'\s*self\.budget_release_pending = false;\n' + r'\s*\} else \{\n' + r'(?:\s*//[^\n]*\n)*' + r'\s*self\.budget_release_pending = !self\.set_budget\(false\);\n' + r'\s*\}', + 'if self.budget_boosted {\n self.budget_release_pending = false;\n }', + body, + ) + assert n2 == 1, f"mutation {mutation} boost replace failed ({n2})" + return body + + +def run_fan_boost_tests(tree, output, mutation): + body = extract_fan_boost(tree, mutation) + src = output / "fan_boost_test.rs" + binary = output / "fan_boost_test" + src.write_text(RUST_HARNESS.replace("FAN_BOOST_BODY", body)) + rustc = os.environ.get("RUSTC", "rustc") + subprocess.run([rustc, "--edition=2021", "--test", "-Dwarnings", str(src), "-o", str(binary)], + check=True) + res = subprocess.run([str(binary)], capture_output=True, text=True) + if res.stdout: + print(res.stdout, end="") + if res.stderr: + print(res.stderr, end="", file=sys.stderr) + return res.returncode == 0 + + +def build(tree, output, mutation): + libfdt = tree / "scripts/dtc/libfdt" + hwmon_body, fans_body, manual_filter = extract(tree, mutation) + harness = output / "harness.c" + code = (HARNESS + .replace("HWMON_BODY", hwmon_body) + .replace("FANS_BODY", fans_body) + .replace("MANUAL_FILTER", manual_filter)) + harness.write_text(code) + binary = output / "harness" + sources = [libfdt / f for f in ("fdt.c", "fdt_ro.c", "fdt_strerror.c")] + subprocess.run(["cc", "-std=gnu11", "-Wall", "-Werror", "-Wno-unused-function", + "-I", str(libfdt), "-o", str(binary), str(harness)] + [str(s) for s in sources], + check=True) + return binary + + +def run(binary, dtb): + """Returns (governs, {provider path: (written fans, policy_str) or None when refused}).""" + lines = subprocess.check_output([str(binary), str(dtb)], text=True).splitlines() + providers = {} + for line in lines[1:]: + path, *rest = line.split() + verdict = rest[-1] + if verdict != "accepted": + providers[path] = None + else: + policy_tok = rest[-2] + assert policy_tok.startswith("policy="), line + providers[path] = (rest[:-2], policy_tok.split("=", 1)[1]) + return lines[0] == "governs", providers + + +def dtc_compile(dtc, source, dtb): + subprocess.run([dtc, "-q", "-I", "dts", "-O", "dtb", "-o", str(dtb)], input=source, check=True) + + +def compile_board(tree, output, dtc, board, extra="", suffix=""): + apple = tree / "arch/arm64/boot/dts/apple" + source = (apple / f"{board}.dts").read_text() + extra + command = ["cpp", "-nostdinc", "-undef", "-D__DTS__", + "-I", str(tree / "scripts/dtc/include-prefixes"), "-I", str(apple), + "-x", "assembler-with-cpp", "-"] + dtb = output / f"{board}{suffix}.dtb" + dtc_compile(dtc, subprocess.check_output(command, input=source.encode(), cwd=apple), dtb) + return dtb + + +def hwmon_node(name, zone, fans, status=""): + nodes = "".join(f"\t\tfan-F{n}Ac {{ {props.format(n=n)} }};\n" for n, props in enumerate(fans)) + return (f"\t{name} {{ {status} hwmon {{ compatible = \"apple,smc-hwmon\";\n" + f"\t\t{zone}\n{nodes}\t}}; }};\n") + + +def compile_synthetic(output, dtc, name, nodes): + dtb = output / f"synthetic-{name}.dtb" + dtc_compile(dtc, ("/dts-v1/;\n/ {\n" + nodes + "};\n").encode(), dtb) + return dtb + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--tree", type=Path, default=ROOT) + parser.add_argument("--dtc", required=True, help="this kernel's built scripts/dtc/dtc") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--mutation", choices=("drop-fans", "drop-siblings", "drop-hotspot", + "drop-trip", "drop-settable", "drop-provider-check", + "drop-budget-release-pending")) + args = parser.parse_args() + tree = args.tree.resolve() + args.output.mkdir(parents=True, exist_ok=True) + failures = 0 + + if args.mutation != "drop-budget-release-pending": + binary = build(tree, args.output, args.mutation) + + def check(label, dtb, want, want_policy=None, governs=None): + """want: {provider path suffix: exact fans written, or None when refused}.""" + nonlocal failures + got_governs, providers = run(binary, dtb) + if governs is None: + governs = any(fans for fans in want.values()) + problems = [] + if got_governs != governs: + problems.append(f"governs {got_governs}, expected {governs}") + for suffix in want: + if not any(path.endswith(suffix) for path in providers): + problems.append(f"no provider ending in {suffix} was reported") + for path, res in providers.items(): + expected = next((fans for suffix, fans in want.items() if path.endswith(suffix)), None) + written = None if res is None else res[0] + pol = None if res is None else res[1] + names = None if written is None else [w.split("=")[0] for w in written] + if written is not None and (not written or any(w.endswith("=closed") for w in written)): + problems.append(f"{path} accepted and writes {written or 'no fan'}") + if names != expected: + problems.append(f"{path} writes {names}, expected {expected}") + if want_policy is not None and expected is not None: + want_str = f"{want_policy[0]},{want_policy[1]},{want_policy[2]}" + if pol != want_str: + problems.append(f"{path} policy {pol}, expected {want_str}") + if problems: + failures += 1 + print(f"FAIL line {sys._getframe(1).f_lineno}: {label}: {'; '.join(problems)}") + else: + print(f"ok {label}: {'governs' if got_governs else 'idle'} {providers}") + + if args.mutation != "drop-budget-release-pending": + for name, (zone, fans, written, pol) in SYNTHETIC.items(): + check(f"synthetic {name}", + compile_synthetic(args.output, args.dtc, name, hwmon_node("smc", zone, fans)), + {"/smc/hwmon": written}, want_policy=pol) + check("synthetic opted-in-under-disabled-parent", + compile_synthetic(args.output, args.dtc, "disabled-parent", + hwmon_node("smc0", DIE_TCMB, [MODE + MANUAL], 'status = "disabled";') + + hwmon_node("smc1", DIE_TCMB, [MODE])), + {"/smc0/hwmon": ["fan-F0Ac"], "/smc1/hwmon": None}, governs=False) + check("synthetic disabled-hwmon-node", + compile_synthetic(args.output, args.dtc, "disabled-node", + hwmon_node("smc", DIE_TCMB + ' status = "disabled";', [MODE + MANUAL])), + {"/hwmon": ["fan-F0Ac"]}, governs=False) + for board, written in BOARDS.items(): + check(board, compile_board(tree, args.output, args.dtc, board), {"/hwmon": written}) + + j716c_dts = (tree / "arch/arm64/boot/dts/apple/t6050-j716c.dts").read_text() + has_2208 = "hwmon-fan-dual.dtsi" in j716c_dts + has_trip = "apple,soc-die-fan-trip-millicelsius" in j716c_dts + check("t6050-j716c (in-tree)", + compile_board(tree, args.output, args.dtc, "t6050-j716c"), + {"/hwmon": J716C_FANS if (has_2208 and has_trip) else None}) + if not has_2208: + check("t6050-j716c with #2208 (no trip -> stays off)", + compile_board(tree, args.output, args.dtc, "t6050-j716c", J716C_2208_NO_TRIP, "-2208-notrip"), + {"/hwmon": None}) + check("t6050-j716c with #2208 + DT trip", + compile_board(tree, args.output, args.dtc, "t6050-j716c", J716C_2208_WITH_TRIP, "-2208-trip"), + {"/hwmon": J716C_FANS}, want_policy=(98000, 82000, 30000)) + if args.mutation in (None, "drop-budget-release-pending"): + if not run_fan_boost_tests(tree, args.output, args.mutation): + failures += 1 + if failures: + raise SystemExit(1) + print("PASS") + + +if __name__ == "__main__": + main() diff --git a/tools/asahi/mcc-boot-dma-tests.py b/tools/asahi/mcc-boot-dma-tests.py new file mode 100644 index 00000000000000..d0400c29465b2d --- /dev/null +++ b/tools/asahi/mcc-boot-dma-tests.py @@ -0,0 +1,446 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run apple-mcc's boot DMA supplier walk against mock device tree nodes.""" +from pathlib import Path +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +SRC = (ROOT / 'drivers/soc/apple/mcc.c').read_text() + + +def function(name): + a = SRC.rfind('\n', 0, SRC.index(name + '(struct')) + 1 + b = SRC.index('\n}\n', a) + 3 + return SRC[a:b] + + +CODE = (function('apple_mcc_scans_boot_framebuffer') + function('apple_mcc_wait_boot_dma') + + function('apple_mcc_boot_dma_detached')) +UNRESOLVED = 'if (!it.node) {' +DETACHED = 'if (of_node_check_flag(it.node, OF_DETACHED)) {' +assert CODE.count(UNRESOLVED) == 2 and CODE.count(DETACHED) == 2 +if '--accept-unresolved' in sys.argv: + CODE = CODE.replace(UNRESOLVED, 'if (0) {', 1) +if '--final-skips-unresolved' in sys.argv: + a = CODE.index('apple_mcc_boot_dma_detached(') + CODE = CODE[:a] + CODE[a:].replace('return true;\n\t\t\tcontinue;', 'continue;\n\t\t\tcontinue;', 1) +if '--ignore-detached-supplier' in sys.argv: + CODE = CODE.replace(DETACHED, 'if (0) {', 1) + +PRE = r''' +#include +#include +#include +#include +#include +typedef uint32_t u32; +#define EPROBE_DEFER 517 +#define OF_DETACHED 3 +struct device_node { + const char *name; u32 phandle; bool detached, detach_on_lookup, available, fb, bound, retired; + struct device_node *display; u32 boot[4]; int nboot, refs; +}; +struct device { struct device_node *of_node; }; +struct platform_device { struct device dev; struct device_node *np; }; +static struct device_node *nodes[8]; +static int nnodes, readies; +static struct device_node *get(struct device_node *n) { if (n) n->refs++; return n; } +static void of_node_put(struct device_node *n) { if (n) { assert(n->refs > 0); n->refs--; } } +static bool of_node_check_flag(struct device_node *n, int f) { assert(n && f == OF_DETACHED); return n->detached; } +static bool of_device_is_available(struct device_node *n) { return n->available; } +static struct device_node *of_parse_phandle(struct device_node *n, const char *p, int i) +{ return get(n->display); } +static struct device_node *next_fb(struct device_node *from) +{ + int i = 0; + + if (from) { + while (nodes[i] != from) + i++; + of_node_put(from); + i++; + } + for (; i < nnodes; i++) + if (nodes[i]->fb) + return get(nodes[i]); + return NULL; +} +#define for_each_compatible_node(dn, type, compat) \ + for (dn = next_fb(NULL); dn; dn = next_fb(dn)) +struct of_phandle_iterator { struct device_node *node, *parent; u32 phandle; int i; }; +static struct device_node *by_phandle(u32 ph) +{ + /* A detached node has left the tree and its phandle cache. */ + for (int i = 0; i < nnodes; i++) + if (nodes[i]->phandle == ph && !nodes[i]->detached) { + /* Detached between lookup and use. */ + if (nodes[i]->detach_on_lookup) + nodes[i]->detached = true; + return get(nodes[i]); + } + return NULL; +} +static bool it_next(struct of_phandle_iterator *it, int *err) +{ + of_node_put(it->node); + it->node = NULL; + if (it->i >= it->parent->nboot) { + *err = -ENOENT; + return false; + } + it->phandle = it->parent->boot[it->i++]; + it->node = it->phandle ? by_phandle(it->phandle) : NULL; + return true; +} +#define of_for_each_phandle(it, err, np, name, cells, count) \ + for ((it)->node = NULL, (it)->parent = (np), (it)->i = 0; it_next((it), &(err));) +static struct platform_device pdevs[8]; +static struct platform_device *of_find_device_by_node(struct device_node *n) +{ + for (int i = 0; i < nnodes; i++) + if (nodes[i] == n) { + pdevs[i].np = get(n); + return &pdevs[i]; + } + return NULL; +} +static bool device_is_bound(struct device *d) { return container_of_pdev(d)->np->bound; } +'''.replace('container_of_pdev(d)', '((struct platform_device *)((char *)(d) - offsetof(struct platform_device, dev)))') + r''' +static void put_device(struct device *d) +{ of_node_put(((struct platform_device *)((char *)d - offsetof(struct platform_device, dev)))->np); } +#define dev_err_probe(dev, err, ...) (err) +static int apple_mcc_boot_scanout_ready(struct device *dev, struct device_node *supplier) +{ + assert(supplier && !supplier->detached); + readies++; + return supplier->retired ? 0 : -EPROBE_DEFER; +} +''' + +MAIN = r''' +static struct device_node mcc, dcp, disp, fb; +static struct device dev = { .of_node = &mcc }; + +static void reset(void) +{ + mcc = (struct device_node){ .name = "mcc", .phandle = 1, .available = true }; + dcp = (struct device_node){ .name = "dcp", .phandle = 2 }; + disp = (struct device_node){ .name = "disp", .phandle = 3, .available = true, .bound = true }; + fb = (struct device_node){ .name = "fb", .phandle = 4, .available = true, .fb = true }; + nodes[0] = &mcc; nodes[1] = &dcp; nodes[2] = &disp; nodes[3] = &fb; nnodes = 4; + readies = 0; +} + +static int walk(void) +{ + int ret = apple_mcc_wait_boot_dma(&dev); + + for (int i = 0; i < nnodes; i++) + assert(nodes[i]->refs == 0); + return ret; +} + +int main(void) +{ + /* Legacy supplier, bound: allocation allowed, no scanout wait. */ + reset(); mcc.boot[0] = 3; mcc.nboot = 1; + assert(walk() == 0 && !readies); + disp.bound = false; + assert(walk() == -EPROBE_DEFER); + + /* Empty entry: no device. */ + reset(); mcc.nboot = 1; + assert(walk() == 0); + + /* Unresolved phandle, and an enabled framebuffer naming no display. */ + reset(); mcc.boot[0] = 99; mcc.nboot = 1; + assert(walk() == -EINVAL && !readies); + /* Unresolved, then a legacy supplier: still refused. */ + reset(); mcc.boot[0] = 99; mcc.boot[1] = 3; mcc.nboot = 2; + assert(walk() == -EINVAL); + + /* A disabled DCP scanning the boot framebuffer keeps allocation off. */ + reset(); mcc.boot[0] = 2; mcc.nboot = 1; fb.display = &dcp; + assert(walk() == -EPROBE_DEFER && readies == 1); + /* A bound DCP scanning the boot framebuffer waits until scanout retires. */ + dcp.available = true; dcp.bound = true; + assert(walk() == -EPROBE_DEFER && readies == 2); + dcp.retired = true; + assert(walk() == 0 && readies == 3); + /* An unbound DCP still defers to bind even after scanout retired. */ + dcp.bound = false; + assert(walk() == -EPROBE_DEFER && readies == 4); + /* Disabled framebuffer: no scanout wait, and a disabled supplier still defers to bind. */ + reset(); mcc.boot[0] = 2; mcc.nboot = 1; fb.display = &dcp; fb.available = false; + assert(walk() == -EPROBE_DEFER && !readies); + dcp.available = true; dcp.bound = true; + assert(walk() == 0 && !readies); + + /* Detached consumer or supplier: cannot confirm. */ + reset(); mcc.boot[0] = 2; mcc.nboot = 1; fb.display = &dcp; dcp.retired = true; + mcc.detached = true; + assert(walk() == -ENODEV); + /* A detached supplier no longer resolves; one detached after its lookup. */ + mcc.detached = false; dcp.detached = true; + assert(walk() == -EINVAL && !readies); + dcp.detached = false; dcp.detach_on_lookup = true; + assert(walk() == -ENODEV && !readies); + + /* The final check under the lock, before allocation is enabled. */ + reset(); mcc.boot[0] = 3; mcc.boot[1] = 2; mcc.nboot = 2; + assert(!apple_mcc_boot_dma_detached(&dev)); + dcp.detached = true; + assert(apple_mcc_boot_dma_detached(&dev)); + dcp.detached = false; mcc.detached = true; + assert(apple_mcc_boot_dma_detached(&dev)); + /* A supplier that disappears between the two walks. */ + reset(); mcc.boot[0] = 3; mcc.boot[1] = 2; mcc.boot[2] = 0; mcc.nboot = 3; + fb.display = &dcp; dcp.retired = true; dcp.available = true; dcp.bound = true; + assert(walk() == 0); + dcp.detached = true; + assert(apple_mcc_boot_dma_detached(&dev)); + dcp.detached = false; + assert(!apple_mcc_boot_dma_detached(&dev)); + for (int i = 0; i < nnodes; i++) + assert(nodes[i]->refs == 0); + return 0; +} +''' + +# The detach notifier in mcc-boot-dma.c, against an enabled controller. +BOOT = (ROOT / 'drivers/soc/apple/mcc-boot-dma.c').read_text() +HDR = (ROOT / 'include/linux/soc/apple/mcc.h').read_text() +LOSES = 'return !scanout || !scanout->retired;' +assert BOOT.count(LOSES) == 1 +if '--detach-retired-only' in sys.argv: + BOOT = BOOT.replace(LOSES, 'return !scanout;') +strip = lambda text: '\n'.join(l for l in text.splitlines() if not l.startswith('#include')) +HDR = strip(HDR).replace('#if IS_ENABLED(CONFIG_APPLE_MCC_BOOT_DMA)', '#if 1') + +NPRE = r""" +#include +#include +#include +#include +#include +#include +typedef uint32_t u32; +#define EPROBE_DEFER 517 +#define OF_DETACHED 3 +#define __init +#define core_initcall(f) +#define EXPORT_SYMBOL_GPL(f) +#define IS_ENABLED(x) 1 +#define WARN_ON_ONCE(c) assert(!(c)) +#define container_of(p, t, m) ((t *)((char *)(p) - offsetof(t, m))) +struct list_head { struct list_head *next, *prev; }; +#define LIST_HEAD(n) struct list_head n = { &(n), &(n) } +static void INIT_LIST_HEAD(struct list_head *h) { h->next = h->prev = h; } +static bool list_empty(struct list_head *h) { return h->next == h; } +static void list_add_tail(struct list_head *n, struct list_head *h) +{ n->next = h; n->prev = h->prev; h->prev->next = n; h->prev = n; } +static void list_del(struct list_head *n) { n->prev->next = n->next; n->next->prev = n->prev; } +static void list_del_init(struct list_head *n) { list_del(n); INIT_LIST_HEAD(n); } +static void list_move_tail(struct list_head *n, struct list_head *h) { list_del(n); list_add_tail(n, h); } +static void list_splice_tail_init(struct list_head *n, struct list_head *h) +{ while (!list_empty(n)) list_move_tail(n->next, h); } +#define list_entry(p, t, m) container_of(p, t, m) +#define list_for_each_entry(p, h, m) \ + for (p = list_entry((h)->next, typeof(*p), m); &p->m != (h); p = list_entry(p->m.next, typeof(*p), m)) +#define list_for_each_entry_safe(p, n, h, m) \ + for (p = list_entry((h)->next, typeof(*p), m), n = list_entry(p->m.next, typeof(*p), m); \ + &p->m != (h); p = n, n = list_entry(n->m.next, typeof(*n), m)) +static int locked; +struct mutex { int unused; }; +#define DEFINE_MUTEX(n) struct mutex n +static void mutex_lock(struct mutex *m) { assert(!locked); locked = 1; } +static void mutex_unlock(struct mutex *m) { assert(locked); locked = 0; } +#define kzalloc_obj(x) calloc(1, sizeof(x)) +#define kfree free +struct device_node { u32 phandle; bool detached; u32 boot[4]; int nboot; int refs; }; +struct device { struct device_node *of_node; }; +struct platform_device { struct device dev; }; +static struct device_node *of_node_get(struct device_node *n) { if (n) n->refs++; return n; } +static void of_node_put(struct device_node *n) { if (n) { assert(n->refs > 0); n->refs--; } } +static bool of_node_check_flag(struct device_node *n, int f) { return n->detached; } +static int of_property_count_u32_elems(struct device_node *n, const char *p) { return n->nboot; } +static int of_property_read_u32_index(struct device_node *n, const char *p, int i, u32 *v) +{ *v = n->boot[i]; return 0; } +static struct platform_device *of_find_device_by_node(struct device_node *n) { return NULL; } +static void device_initial_probe(struct device *d) { } +static void put_device(struct device *d) { } +struct work_struct { int unused; }; +#define DECLARE_WORK(n, f) struct work_struct n +static void schedule_work(struct work_struct *w) { } +struct notifier_block { int (*notifier_call)(struct notifier_block *, unsigned long, void *); }; +#define NOTIFY_DONE 0 +#define NOTIFY_OK 1 +#define OF_RECONFIG_DETACH_NODE 2 +struct of_reconfig_data { struct device_node *dn; }; +static int of_reconfig_notifier_register(struct notifier_block *nb) { return 0; } +""" + +NMAIN = r""" +static int lost_calls; +static void lost(struct apple_mcc_boot_dma_consumer *c) +{ + assert(locked); + lost_calls++; +} + +static struct device_node mcc = { .phandle = 1, .boot = { 3, 2 }, .nboot = 2 }; +static struct device_node dcp = { .phandle = 2 }, disp = { .phandle = 3 }, other = { .phandle = 9 }; +static struct device dev = { .of_node = &mcc }; +static struct apple_mcc_boot_dma_consumer c = { .dev = &dev, .lost = lost }; + +static void enable(void) +{ + apple_mcc_boot_dma_lock(); + apple_mcc_boot_dma_register_locked(&c); + apple_mcc_boot_dma_unlock(); +} + +static int detach(struct device_node *n) +{ + struct of_reconfig_data rd = { .dn = n }; + int before = lost_calls; + + n->detached = true; + apple_mcc_of_notify(NULL, OF_RECONFIG_DETACH_NODE, &rd); + n->detached = false; + return lost_calls - before; +} + +int main(void) +{ + INIT_LIST_HEAD(&c.link); + enable(); + /* An unrelated node. */ + assert(detach(&other) == 0 && !list_empty(&c.link)); + /* Enabled, then a supplier still scanning out detaches: allocation off. */ + assert(apple_mcc_boot_scanout_reserve(&dcp) == 0); + assert(detach(&dcp) == 1 && list_empty(&c.link)); + /* Not registered any more: a second detach reaches nothing. */ + assert(detach(&mcc) == 0); + /* A supplier whose boot scanout retired may detach. */ + enable(); + assert(apple_mcc_boot_scanout_reserve(&dcp) == 0); + apple_mcc_boot_scanout_retired(&dcp); + assert(detach(&dcp) == 0 && !list_empty(&c.link)); + /* A supplier with no scanout record (bound only), and the controller's own node. */ + assert(detach(&disp) == 1); + enable(); + assert(detach(&mcc) == 1); + /* Removal unregisters first. */ + enable(); + apple_mcc_boot_dma_unregister(&c); + assert(detach(&dcp) == 0 && detach(&mcc) == 0); + assert(dcp.refs == 0 && mcc.refs == 0); + return 0; +} +""" + +# A deep sleep with a detach in between, through mcc.c's PM callbacks and the real notifier. +a = SRC.index('struct apple_mcc {') +MSTRUCT = SRC[a:SRC.index('\n};\n', a) + 4] +PMCODE = ''.join(function(n) for n in ('apple_mcc_turn_off', 'apple_mcc_boot_dma_lost', + 'apple_mcc_suspend_locked', 'apple_mcc_resume_locked', + 'apple_mcc_suspend_noirq', 'apple_mcc_resume_noirq')) +CLEAR = '\tmcc->sleep_disabled = false;\n}' +assert PMCODE.count(CLEAR) == 1 +if '--resume-after-detach' in sys.argv: + PMCODE = PMCODE.replace(CLEAR, '}') +MPRE = r""" +#define __iomem +#define MCC_MAX_PLANES 64 +#define MCC_CACHE_WAYS 0x2800 +#define FIELD_GET(m, v) (v) +#define dev_warn(...) ((void)0) +#define dev_info(...) ((void)0) +static u32 readl(void *p) { return 0; } +static bool alloc_on; +static bool pm_suspend_via_firmware(void) { return true; } +""" + MSTRUCT + r""" +static void *drvdata; +static void *dev_get_drvdata(struct device *d) { return drvdata; } +static void apple_mcc_quiesce(struct apple_mcc *mcc) +{ + assert(locked); + if (!mcc->enabled || mcc->retained) + return; + alloc_on = false; + mcc->enabled = false; +} +static int apple_mcc_disable_t8132(struct apple_mcc *mcc) { alloc_on = false; return 0; } +static int apple_mcc_enable(struct apple_mcc *mcc) { assert(locked); alloc_on = true; return 0; } +static int apple_mcc_enable_t8132(struct apple_mcc *mcc) { alloc_on = true; return 0; } +static int apple_mcc_set_ways(struct apple_mcc *mcc, u32 ways) { return 0; } +""" +PMAIN = r""" +static struct device_node pmcc = { .phandle = 1, .boot = { 2 }, .nboot = 1 }; +static struct device_node pdcp = { .phandle = 2 }; +static struct device pdev = { .of_node = &pmcc }; +static struct apple_mcc m; + +static void probe(void) +{ + m = (struct apple_mcc){ .dev = &pdev, .enabled = true }; + INIT_LIST_HEAD(&m.boot_dma.link); + m.boot_dma.dev = &pdev; + m.boot_dma.lost = apple_mcc_boot_dma_lost; + drvdata = &m; + alloc_on = true; + apple_mcc_boot_dma_lock(); + apple_mcc_boot_dma_register_locked(&m.boot_dma); + apple_mcc_boot_dma_unlock(); +} + +static void detach(struct device_node *n) +{ + struct of_reconfig_data rd = { .dn = n }; + + n->detached = true; + apple_mcc_of_notify(NULL, OF_RECONFIG_DETACH_NODE, &rd); + n->detached = false; +} + +int main(void) +{ + /* Suspend, a supplier still scanning out detaches, resume: allocation stays off. */ + assert(apple_mcc_boot_scanout_reserve(&pdcp) == 0); + probe(); + assert(apple_mcc_suspend_noirq(&pdev) == 0 && !alloc_on && m.sleep_disabled); + detach(&pdcp); + assert(!m.sleep_disabled && list_empty(&m.boot_dma.link)); + assert(apple_mcc_resume_noirq(&pdev) == 0 && !alloc_on && !m.enabled); + assert(!locked); + + /* The same with a retired supplier (the detach dropped its record): the wake turns allocation back on. */ + assert(apple_mcc_boot_scanout_reserve(&pdcp) == 0); + apple_mcc_boot_scanout_retired(&pdcp); + probe(); + assert(apple_mcc_suspend_noirq(&pdev) == 0 && !alloc_on); + detach(&pdcp); + assert(m.sleep_disabled && !list_empty(&m.boot_dma.link)); + assert(apple_mcc_resume_noirq(&pdev) == 0 && alloc_on && m.enabled); + assert(!locked); + return 0; +} +""" + +with tempfile.TemporaryDirectory() as t: + for name, text in (('mcc', PRE + CODE + MAIN), ('notify', NPRE + HDR + strip(BOOT) + NMAIN), + ('pm', NPRE + HDR + strip(BOOT) + MPRE + PMCODE + PMAIN)): + src = Path(t) / (name + '.c') + src.write_text(text) + subprocess.run(['cc', '-std=gnu11', '-Wall', '-Werror', '-Wno-unused-function', + '-Wno-unused-variable', '-fsanitize=address,undefined', str(src), + '-o', str(src.with_suffix(''))], check=True) + if subprocess.run([str(src.with_suffix(''))]).returncode: + sys.exit(1) +print('PASS boot DMA walk: legacy bound/unbound, empty entry, unresolved phandle, ' + 'disabled scanning DCP, disabled framebuffer, detached consumer/supplier, final detach check, supplier gone between walks; ' + 'enabled then supplier/own node detached, retired supplier, removal; ' + 'suspend-detach-resume stays off, retired supplier resumes') diff --git a/tools/asahi/mtp-pm-tests.py b/tools/asahi/mtp-pm-tests.py index 4846e41180ce48..ff78c0ac1e44b6 100644 --- a/tools/asahi/mtp-pm-tests.py +++ b/tools/asahi/mtp-pm-tests.py @@ -30,6 +30,7 @@ def function(source, name): #include #include #include +#include #define MAX_INTERFACES 16 #define PMSG_SUSPEND 1 #define HID_HAPTIC_MODE_DEVICE 0 @@ -66,6 +67,7 @@ def function(source, name): struct ff_effect { int id; struct { struct { u16 hid_usage, intensity; } haptic; } u; }; struct magicmouse_sc { struct hid_haptic_device *haptics; bool haptic_button_down, haptic_deep_down, haptic_suspended; int haptic_lock; + struct { bool read; u8 len, body[63]; } fw_click[2]; struct work_struct haptic_press_work, haptic_release_work, haptic_deep_work, haptic_deep_release_work; struct effect_job *haptic_effects; struct hid_device *hdev; struct delayed_work work; bool work_held; }; @@ -109,8 +111,6 @@ def function(source, name): switches++; switched_to = mode; return switch_error; } static bool magicmouse_effect_is_deep(struct ff_effect *e) { return e->u.haptic.hid_usage == APPLE_HP_WAVEFORMDEEPCLICK; } -static u8 magicmouse_haptic_strength(struct hid_device *h, bool deep) { (void)h; (void)deep; return 100; } -static u8 magicmouse_haptic_softness(struct hid_device *h, bool deep) { (void)h; (void)deep; return 100; } static int hid_driver_suspend(struct hid_device *h, int state) { assert(state == PMSG_SUSPEND && !transport->suspended); suspends[h->id]++; @@ -119,6 +119,18 @@ def function(source, name): return h->id == suspend_error_at ? -EBUSY : 0; } ''' +WAVEFORM = r''' +static void magicmouse_haptic_waveform(struct magicmouse_sc *m, struct hid_device *a, + u16 usage, u8 *strength, u8 *softness) { + assert(!transport->suspended); + *strength = *softness = 100; +} +''' +# Older sources used by --old-mouse predate the firmware waveform helper. +LEGACY_WAVEFORM = r''' +static u8 magicmouse_haptic_strength(struct hid_device *h, bool deep) { (void)h; (void)deep; return 100; } +static u8 magicmouse_haptic_softness(struct hid_device *h, bool deep) { (void)h; (void)deep; return 100; } +''' MIDDLE = r''' static int hid_driver_resume(struct hid_device *h) { assert(!transport->suspended); @@ -237,7 +249,8 @@ def main(): 'magicmouse_haptic_effects_loaded', 'magicmouse_haptic_click', 'magicmouse_haptic_suspend', 'magicmouse_haptic_resume', 'magicmouse_switch_mode', 'apple_upload_effects', 'apple_taptic_playback', 'apple_taptic_erase')) + '\n' - c.write_text(PREFIX.replace('static int hid_driver_suspend', haptics + function(mouse, 'magicmouse_suspend') + + waveform = WAVEFORM if 'static void magicmouse_haptic_waveform(' in mouse else LEGACY_WAVEFORM + c.write_text(PREFIX.replace('static int hid_driver_suspend', waveform + haptics + function(mouse, 'magicmouse_suspend') + '\nstatic int hid_driver_suspend', 1) + function(mouse, 'magicmouse_resume') + function(mouse, 'magicmouse_reset_resume') + MIDDLE + function(source, 'dockchannel_hid_suspend') + '\n' + diff --git a/tools/asahi/neo-stability-tests.py b/tools/asahi/neo-stability-tests.py index 34339436597466..530417adfd5c00 100644 --- a/tools/asahi/neo-stability-tests.py +++ b/tools/asahi/neo-stability-tests.py @@ -91,6 +91,8 @@ def function(source, name): static void pm_runtime_mark_last_busy(struct device*d){} static void pm_runtime_put_autosuspend(struct device*d){rpm_puts++;} static int dwc3_host_init(struct dwc3*d){return host_error;} +/* The xHCI start and its USB3 routing; atc-t8132-usb3 models them. */ +static int dwc3_apple_host_start(struct dwc3_apple*a){return dwc3_host_init(&a->dwc);} static int dwc3_gadget_init(struct dwc3*d){return gadget_error;} static void dwc3_host_exit(struct dwc3*d){role_exits++;} static void dwc3_gadget_exit(struct dwc3*d){role_exits++;} diff --git a/tools/asahi/pciec-policy-tests.py b/tools/asahi/pciec-policy-tests.py index ef1c5d8836c4c6..7093382b9c10d8 100644 --- a/tools/asahi/pciec-policy-tests.py +++ b/tools/asahi/pciec-policy-tests.py @@ -101,10 +101,11 @@ def function(source, name): int main(void) { struct device_node dart = { .tunables = true }; - const char *intr2axi[] = { "apple,t8112-pciec", "apple,t6000-pciec" }; - for (unsigned int i = 0; i < 2; i++) { + const char *intr2axi[] = { "apple,t8112-pciec", "apple,t6000-pciec", + "apple,t8142-pciec" }; + for (unsigned int i = 0; i < 3; i++) { /* M2 must win over its T8103 fallback, without a board allowlist. */ - struct device_node host = { .compat = { intr2axi[i], "apple,t8103-pciec" }, + struct device_node host = { .compat = { intr2axi[i], i < 2 ? "apple,t8103-pciec" : NULL }, .status = -1, .dart = &dart }; const struct of_device_id *id = of_match_node(apple_pcie_of_match, &host); assert(id && ((const struct hw_info *)id->data)->tunnel_intr2axi); @@ -133,7 +134,7 @@ def function(source, name): expect(®ular, false, false); regular.compat[0] = "apple,unknown-pciec"; expect(®ular, false, false); - puts("PASS: M1, M1 Pro, M2, firmware handoff, missing DART and DT opt-in"); + puts("PASS: M1, M1 Pro, M2, native T8142, firmware handoff, missing DART and DT opt-in"); return 0; } ''' @@ -146,6 +147,7 @@ def function(source, name): #include #include #include +typedef uint8_t u8; typedef uint32_t u32; #define BIT(n) (1U << (n)) #define GENMASK(h, l) ((~0U << (l)) & (~0U >> (31 - (h)))) @@ -187,24 +189,72 @@ def function(source, name): }; struct apple_dart_cio { int dummy; }; struct hw_info; +struct list_head { + struct list_head *next, *prev; +}; +#define list_for_each_entry(pos, head, member) for (pos = container_of((head)->next, typeof(*pos), member); &pos->member != (head); pos = container_of(pos->member.next, typeof(*pos), member)) +static void list_init(struct list_head *head) +{ + head->next = head; + head->prev = head; +} +static void list_add_tail(struct list_head *entry, struct list_head *head) +{ + entry->next = head; + entry->prev = head->prev; + head->prev->next = entry; + head->prev = entry; +} +struct apple_pcie_port { + struct list_head entry; + unsigned int idx; + bool link_failed; + u8 regs[0x900]; +}; struct apple_pcie { struct device *dev; const struct hw_info *hw; + u8 *base; + struct list_head ports; bool power_retained, kernel_init, tunnel_cold_init; bool bus_stopped, resume_failed, link_kept; struct apple_pcie_pd *pds; unsigned int num_pds, pd_held; struct apple_dart_cio *cio_dart; - bool cio_prepared; + bool cio_prepared, neo_sleep_armed, t6050_down; + unsigned int managed_sids; + void *t6050_port, *t6050_dart; + u32 t6050_parked; }; static bool s2idle_keep_link = true; static int pm_suspend_target_state = PM_SUSPEND_TO_IDLE; +static bool suspend_via_firmware; static bool link_healthy = true; static unsigned int radio_prepare_calls, warn_calls; +static u32 readl(const void *addr) +{ + u32 v; + + memcpy(&v, addr, sizeof(v)); + return v; +} +static void writel(u32 v, void *addr) +{ + memcpy(addr, &v, sizeof(v)); +} +static u32 apple_pcie_port_readl(struct apple_pcie_port *port, u32 reg) +{ + assert(reg + sizeof(u32) <= sizeof(port->regs)); + return readl(port->regs + reg); +} static bool pm_suspend_no_platform(void) { return pm_suspend_target_state == PM_SUSPEND_TO_IDLE; } +static bool pm_suspend_via_firmware(void) +{ + return suspend_via_firmware; +} static struct apple_pcie *apple_pcie_lookup(struct device *dev) { return dev ? dev->pcie : NULL; @@ -274,8 +324,10 @@ def function(source, name): pcie->pds = pd; pcie->num_pds = 1; pcie->cio_dart = cio_dart; + list_init(&pcie->ports); s2idle_keep_link = true; pm_suspend_target_state = PM_SUSPEND_TO_IDLE; + suspend_via_firmware = false; link_healthy = true; radio_prepare_calls = 0; warn_calls = 0; @@ -401,6 +453,98 @@ def function(source, name): assert(apple_pcie_prepare(&dev) == 0 && radio_prepare_calls == 1 && warn_calls == 0); assert(apple_pcie_keep_link(&pcie) && pcie.pd_held == 0 && dev.add_calls == 0); + /* Adopted T6050 host: s2idle and firmware-suspend refusals in prepare. */ + const struct hw_info *t6050_adopt = match_compat("apple,t6050-pcie"); + assert(t6050_adopt && t6050_adopt->adopt_link); + + u8 rc_regs[0x100]; + struct apple_pcie_port p0, p1; + int dummy_port = 1, dummy_dart = 1; + + #define RESET_ADOPTED() do { reset_host(&dev, &pcie, &pd, t6050_adopt, NULL); memset(rc_regs, 0, sizeof(rc_regs)); pcie.base = rc_regs; writel(CORE_RC_CTL_RUN, rc_regs + CORE_RC_CTL); writel(CORE_RC_STAT_READY, rc_regs + CORE_RC_STAT); memset(&p0, 0, sizeof(p0)); p0.idx = 0; writel(PORT_STATUS_READY, p0.regs + PORT_STATUS); writel(PORT_LINKSTS_UP, p0.regs + PORT_LINKSTS); list_add_tail(&p0.entry, &pcie.ports); memset(&p1, 0, sizeof(p1)); p1.idx = 1; writel(PORT_STATUS_READY, p1.regs + PORT_STATUS); writel(PORT_LINKSTS_UP, p1.regs + PORT_LINKSTS); list_add_tail(&p1.entry, &pcie.ports); } while (0) + + /* Healthy adopted host passes s2idle prepare. */ + RESET_ADOPTED(); + assert(apple_pcie_prepare(&dev) == 0 && radio_prepare_calls == 1 && warn_calls == 0); + + /* Non-s2idle without firmware suspend refuses with -EBUSY in prepare. */ + RESET_ADOPTED(); + pm_suspend_target_state = PM_SUSPEND_MEM; + assert(apple_pcie_prepare(&dev) == -EBUSY && radio_prepare_calls == 0 && warn_calls == 1); + + /* Root complex not running or not ready refuses with -ENOLINK. */ + RESET_ADOPTED(); + writel(0, rc_regs + CORE_RC_CTL); + assert(apple_pcie_prepare(&dev) == -ENOLINK && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + writel(0, rc_regs + CORE_RC_STAT); + assert(apple_pcie_prepare(&dev) == -ENOLINK && radio_prepare_calls == 0 && warn_calls == 1); + + /* Unparked port link_failed / not ready / link down / interrupt refuses with -ENOLINK. */ + RESET_ADOPTED(); + p1.link_failed = true; + assert(apple_pcie_prepare(&dev) == -ENOLINK && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + writel(0, p1.regs + PORT_STATUS); + assert(apple_pcie_prepare(&dev) == -ENOLINK && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + writel(PORT_LINKSTS_UP | PORT_LINKSTS_BUSY, p1.regs + PORT_LINKSTS); + assert(apple_pcie_prepare(&dev) == -ENOLINK && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + writel(BIT(PORT_INT_LINK_DOWN), p1.regs + PORT_INTSTAT); + assert(apple_pcie_prepare(&dev) == -ENOLINK && radio_prepare_calls == 0 && warn_calls == 1); + + /* Parked port with dead link registers is skipped and passes prepare. */ + RESET_ADOPTED(); + p1.link_failed = true; + writel(0, p1.regs + PORT_STATUS); + writel(0, p1.regs + PORT_LINKSTS); + writel(BIT(PORT_INT_LINK_DOWN), p1.regs + PORT_INTSTAT); + pcie.t6050_parked = BIT(p1.idx); + assert(apple_pcie_prepare(&dev) == 0 && radio_prepare_calls == 1 && warn_calls == 0); + + /* Firmware suspend refuses without both t6050_port and t6050_dart, passes with both. */ + RESET_ADOPTED(); + pm_suspend_target_state = PM_SUSPEND_MEM; + suspend_via_firmware = true; + assert(apple_pcie_prepare(&dev) == -EBUSY && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + pm_suspend_target_state = PM_SUSPEND_MEM; + suspend_via_firmware = true; + pcie.t6050_port = &dummy_port; + assert(apple_pcie_prepare(&dev) == -EBUSY && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + pm_suspend_target_state = PM_SUSPEND_MEM; + suspend_via_firmware = true; + pcie.t6050_dart = &dummy_dart; + assert(apple_pcie_prepare(&dev) == -EBUSY && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + pm_suspend_target_state = PM_SUSPEND_MEM; + suspend_via_firmware = true; + pcie.t6050_port = &dummy_port; + pcie.t6050_dart = &dummy_dart; + assert(apple_pcie_prepare(&dev) == 0 && radio_prepare_calls == 1 && warn_calls == 0); + + /* Already-down, managed-radio, or NEO/CIO-prepared adopted host bypasses adopted check. */ + RESET_ADOPTED(); + writel(0, rc_regs + CORE_RC_CTL); + pcie.t6050_down = true; + assert(apple_pcie_prepare(&dev) == 0 && radio_prepare_calls == 1 && warn_calls == 0); + + RESET_ADOPTED(); + writel(0, rc_regs + CORE_RC_CTL); + pcie.managed_sids = 1; + assert(apple_pcie_prepare(&dev) == 0 && radio_prepare_calls == 1 && warn_calls == 0); + + #undef RESET_ADOPTED + puts("PASS: T6050 PCIe-C s2idle domain hold, release, deep sleep and prepare refusal"); return 0; } @@ -426,6 +570,432 @@ def run_cases(out, cases, extra_flags=()): print('PASS negative control:', name) +def pm_registration(source, start, end): + first = source.index(start) + return source[first:source.index(end, first) + len(end)] + + +PM_FIXTURE = r''' +#include +#include +#include +struct notifier_block { int (*notifier_call)(void); int priority; }; +struct apple_cio_hw { bool phy_shared_with_dwc3; }; +struct apple_cio { const struct apple_cio_hw *hw; struct notifier_block pm_notifier; }; +struct dwc3_apple { struct notifier_block pm_nb; }; +static const struct apple_cio_hw apple_cio_t8142_hw = { .phy_shared_with_dwc3 = true }; +static struct notifier_block *chain[2]; +static int count; +static bool busy, phy_off, pci_off; +static int register_pm_notifier(struct notifier_block *nb) +{ + int i = count++; + assert(count <= 2); + while (i && chain[i - 1]->priority < nb->priority) { + chain[i] = chain[i - 1]; + i--; + } + chain[i] = nb; + return 0; +} +static int apple_cio_pm_notify(void) +{ + /* An open disk must be rejected while its PCIe link still works. */ + assert(!phy_off); + if (busy) + return 1; + pci_off = true; + return 0; +} +static int dwc3_apple_pm_notify(void) +{ + assert(pci_off); + phy_off = true; + return 0; +} +static void add_cio(struct apple_cio *acio) +{ + /* ACIO_REGISTRATION */ +} +static void add_dwc(struct dwc3_apple *appledwc) +{ + int ret; + /* DWC_REGISTRATION */ + assert(!ret); +} +int main(void) +{ + struct apple_cio acio = { .hw = &apple_cio_t8142_hw }; + struct dwc3_apple dwc = { 0 }; + /* DWC3 probes first on J813. Equal priority reproduces the failure. */ + add_dwc(&dwc); + add_cio(&acio); + for (int open = 0; open < 2; open++) { + busy = open; + phy_off = pci_off = false; + for (int i = 0; i < count; i++) + if (chain[i]->notifier_call()) + break; + assert(phy_off == !busy && pci_off == !busy); + } + puts("PASS: T8142 refuses an open disk before PHY shutdown; idle PCIe stops first"); + return 0; +} +''' + + +def test_pm_order(out, acio): + dwc = (ROOT / 'drivers/usb/dwc3/dwc3-apple.c').read_text() + code = PM_FIXTURE.replace('/* ACIO_REGISTRATION */', pm_registration( + acio, 'acio->pm_notifier.notifier_call = apple_cio_pm_notify;', + 'register_pm_notifier(&acio->pm_notifier);')) + code = code.replace('/* DWC_REGISTRATION */', pm_registration( + dwc, 'appledwc->pm_nb.notifier_call = dwc3_apple_pm_notify;', + 'ret = register_pm_notifier(&appledwc->pm_nb);')) + mutation = code.replace('acio->pm_notifier.priority = 40;', + 'acio->pm_notifier.priority = 0;') + assert mutation != code + for name, body in [('pm-order', code), ('phy-before-pcie', mutation)]: + source, binary = out / (name + '.c'), out / name + source.write_text(body) + subprocess.run(['cc', '-std=gnu11', '-Wall', '-Werror', str(source), + '-o', str(binary)], check=True) + run = subprocess.run([str(binary)], capture_output=True, text=True) + (out / (name + '.log')).write_text(run.stdout + run.stderr) + if name == 'pm-order': + assert run.returncode == 0, run.stderr + print(run.stdout, end='') + else: + assert run.returncode < 0 and 'Assertion' in run.stderr + print('PASS negative control:', name) + + +T8122_SLEEP_FIXTURE = r''' +#include +#include +#include +#include +#include +struct apple_dpin_policy { int unused; }; +static const struct apple_dpin_policy apple_dpin_m1, apple_dpin_m2; +struct apple_cio_hw { + bool sleep_removes_domains; + bool restart_on_wake; + bool phy_shared_with_dwc3; + bool psd_power_cycle; + bool stop_at_reboot; + bool sleep_router_on_stop; + const struct apple_dpin_policy *dp; +}; +struct notifier_block { int (*notifier_call)(void); int priority; }; +struct apple_cio { const struct apple_cio_hw *hw; struct notifier_block pm_notifier; }; +struct dwc3_apple { struct notifier_block pm_nb; }; +struct match_entry { const char *compatible; const struct apple_cio_hw *data; }; +static bool default_s2idle, no_platform; +static bool pm_suspend_default_s2idle(void) { return default_s2idle; } +static bool pm_suspend_no_platform(void) { return no_platform; } +/* PRODUCTION_HW */ +static const struct match_entry match_table[] = { +/* MATCH_ENTRIES */ + { NULL, NULL }, +}; +/* PRODUCTION_FN */ +static const struct apple_cio_hw *match_of(const char *const *compat) +{ + for (size_t i = 0; compat[i]; i++) + for (size_t j = 0; match_table[j].compatible; j++) + if (!strcmp(compat[i], match_table[j].compatible)) + return match_table[j].data; + return NULL; +} +static struct notifier_block *chain[2]; +static int count; +static bool phy_off, pci_off; +static int register_pm_notifier(struct notifier_block *nb) +{ + int i = count++; + assert(count <= 2); + while (i && chain[i - 1]->priority < nb->priority) { + chain[i] = chain[i - 1]; + i--; + } + chain[i] = nb; + return 0; +} +static int apple_cio_pm_notify(void) +{ + assert(!phy_off); + pci_off = true; + return 0; +} +static int dwc3_apple_pm_notify(void) +{ + assert(pci_off); + phy_off = true; + return 0; +} +static void add_cio(struct apple_cio *acio) +{ + /* ACIO_REGISTRATION */ +} +static void add_dwc(struct dwc3_apple *appledwc) +{ + int ret; + /* DWC_REGISTRATION */ + assert(!ret); +} +int main(void) +{ + static const char *const t8122_compat[] = { + "apple,t8122-usb4-acio", "apple,t8103-usb4-acio", NULL + }; + static const char *const t8103_compat[] = { + "apple,t8103-usb4-acio", NULL + }; + static const char *const t6020_compat[] = { + "apple,t6020-usb4-acio", "apple,t8103-usb4-acio", NULL + }; + const struct apple_cio_hw *t8122 = match_of(t8122_compat); + const struct apple_cio_hw *t8103 = match_of(t8103_compat); + const struct apple_cio_hw *t6020 = match_of(t6020_compat); + assert(t8122 == &apple_cio_t8122_hw); + assert(t8103 == &apple_cio_t8103_hw); + assert(t6020 == &apple_cio_t6020_hw); + assert(t8122->sleep_removes_domains && t8103->sleep_removes_domains); + assert(t8122->restart_on_wake && t8103->restart_on_wake); + assert(t8122->phy_shared_with_dwc3 && t8103->phy_shared_with_dwc3); + assert(t8103->psd_power_cycle && t8103->stop_at_reboot && t8103->sleep_router_on_stop); + assert(t8122->dp == &apple_dpin_m1 && t8103->dp == &apple_dpin_m1); + + struct apple_cio acio_t8122 = { .hw = t8122 }; + struct apple_cio acio_t8103 = { .hw = t8103 }; + struct apple_cio acio_t6020 = { .hw = t6020 }; + + /* mem_sleep=deep + mem tears down T8103 and T8122 ACIO, leaves T6020 unchanged. */ + default_s2idle = false; + no_platform = false; + assert(apple_cio_sleep_removes_domains(&acio_t8122)); + assert(apple_cio_sleep_removes_domains(&acio_t8103)); + assert(!apple_cio_sleep_removes_domains(&acio_t6020)); + + /* s2idle keeps the port up. */ + default_s2idle = true; + no_platform = false; + assert(!apple_cio_sleep_removes_domains(&acio_t8122)); + assert(!apple_cio_sleep_removes_domains(&acio_t8103)); + + /* freeze keeps the port up even when mem_sleep=deep is the default. */ + default_s2idle = false; + no_platform = true; + assert(!apple_cio_sleep_removes_domains(&acio_t8122)); + assert(!apple_cio_sleep_removes_domains(&acio_t8103)); + + /* Shared ATC PHY: ACIO PM notifier must run before DWC3's. */ + struct dwc3_apple dwc = { 0 }; + add_dwc(&dwc); + add_cio(&acio_t8122); + for (int i = 0; i < count; i++) + assert(!chain[i]->notifier_call()); + assert(pci_off && phy_off); + + puts("PASS: T8103/T8122 ACIO deep-sleep teardown, freeze/s2idle preservation, and DWC3 PM order"); + return 0; +} +''' + + +def test_t8122_cio_sleep(out, acio): + dwc = (ROOT / 'drivers/usb/dwc3/dwc3-apple.c').read_text() + hw_defs = [] + for sym in ('apple_cio_t8103_hw', 'apple_cio_t8122_hw', 'apple_cio_t6020_hw'): + m = re.search(r'^static const struct apple_cio_hw ' + sym + + r' = \{.*?\n\};', acio, re.M | re.S) + assert m, sym + hw_defs.append(m.group()) + match_block = re.search( + r'static const struct of_device_id apple_acio_match\[\] = \{.*?\n\};', + acio, re.S) + assert match_block + entries = re.findall( + r'\.compatible\s*=\s*"([^"]+)"\s*,\s*\.data\s*=\s*(&apple_cio_\w+_hw)', + match_block.group()) + match_lines = [f' {{ "{c}", {d} }},' for c, d in entries + if c in ('apple,t8122-usb4-acio', 'apple,t6020-usb4-acio', + 'apple,t8103-usb4-acio')] + assert len(match_lines) == 3, match_lines + code = T8122_SLEEP_FIXTURE + code = code.replace('/* PRODUCTION_HW */', '\n'.join(hw_defs)) + code = code.replace('/* MATCH_ENTRIES */', '\n'.join(match_lines)) + code = code.replace('/* PRODUCTION_FN */', + function(acio, 'apple_cio_sleep_removes_domains')) + code = code.replace('/* ACIO_REGISTRATION */', pm_registration( + acio, 'acio->pm_notifier.notifier_call = apple_cio_pm_notify;', + 'register_pm_notifier(&acio->pm_notifier);')) + code = code.replace('/* DWC_REGISTRATION */', pm_registration( + dwc, 'appledwc->pm_nb.notifier_call = dwc3_apple_pm_notify;', + 'ret = register_pm_notifier(&appledwc->pm_nb);')) + muts = { + 't8122-drop-match': (' { "apple,t8122-usb4-acio", &apple_cio_t8122_hw },', ''), + 't8103-drop-sleep-removes-domains': ( + 'static const struct apple_cio_hw apple_cio_t8103_hw = {\n' + '\t.sleep_removes_domains = true,\n', + 'static const struct apple_cio_hw apple_cio_t8103_hw = {\n'), + 't8122-drop-sleep-removes-domains': ( + 'static const struct apple_cio_hw apple_cio_t8122_hw = {\n' + '\t.sleep_removes_domains = true,\n', + 'static const struct apple_cio_hw apple_cio_t8122_hw = {\n'), + 't8122-drop-phy-shared': ( + 'static const struct apple_cio_hw apple_cio_t8122_hw = {\n' + '\t.sleep_removes_domains = true,\n' + '\t.restart_on_wake = true,\n' + '\t.phy_shared_with_dwc3 = true,\n', + 'static const struct apple_cio_hw apple_cio_t8122_hw = {\n' + '\t.sleep_removes_domains = true,\n' + '\t.restart_on_wake = true,\n'), + } + cases = {'t8122-cio-sleep': code} + for name, (old, new) in muts.items(): + assert code.count(old) == 1, name + cases[name] = code.replace(old, new) + for name, body in cases.items(): + source, binary = out / (name + '.c'), out / name + source.write_text(body) + subprocess.run(['cc', '-std=gnu11', '-Wall', '-Wextra', '-Werror', + str(source), '-o', str(binary)], check=True) + run = subprocess.run([str(binary)], capture_output=True, text=True) + (out / (name + '.log')).write_text(run.stdout + run.stderr) + if name == 't8122-cio-sleep': + assert run.returncode == 0, run.stderr + print(run.stdout, end='') + else: + assert run.returncode < 0 and 'Assertion' in run.stderr, ( + name, run.returncode, run.stderr) + print('PASS negative control:', name) + + +CIO_STOP_FIXTURE = r''' +#include +#include +#include +#include +#define ENODEV 19 +#define EIO 5 +#define READ_ONCE(x) (x) +#define lockdep_assert_held(l) ((void)(l)) +#define scoped_guard(type, lock) if ((void)(lock), 1) +#define dev_err(dev, ...) ((void)(dev), errs++) +#define dev_warn(dev, ...) ((void)(dev)) +#define readl(addr) ((void)(addr), 0u) +#define APPLE_CIO_M3_CTRL 0 +#define APPLE_CIO_LSTX_CTRL_LEVEL 1u +struct device { int unused; }; +struct platform_device { struct device dev; }; +struct apple_cio_hw { bool sleep_router_on_stop; bool lstx_after_boot; }; +struct apple_cio { + const struct apple_cio_hw *hw; + int lock, pcie_tunnel_lock, dp_wq; + struct device *dev; + struct platform_device *nhi_pdev; + unsigned int current_cable_info, target_cable_info; + bool pcie_tunnel_populated, pcie_quiesce_pending; + bool resume_link_failed, link_lost_restart; + void *rtk; + char *rc_base; +}; +static int errs, sleep_ret, sleeps, reopens, destroyed, depopulated; +static int poweroffs, freed, released; +static bool apple_cio_stop_pcie_tunnel(struct apple_cio *acio) { (void)acio; return true; } +static int apple_cio_sleep_router_for_stop(struct apple_cio *acio) { (void)acio; sleeps++; return sleep_ret; } +static void apple_cio_reopen_pcie_tunnel(struct apple_cio *acio, bool pcie) { (void)acio; assert(pcie); reopens++; } +static void of_platform_device_destroy(struct device *dev, void *data) { (void)dev; (void)data; destroyed++; } +static void flush_workqueue(int wq) { (void)wq; } +static void of_platform_depopulate(struct device *dev) { (void)dev; depopulated++; } +static int apple_rtkit_poweroff(void *rtk) { (void)rtk; poweroffs++; return 0; } +static void apple_rtkit_mailbox_off(void *rtk) { (void)rtk; } +static void apple_rtkit_free(void *rtk) { (void)rtk; freed++; } +static void apple_cio_cpu_halt(struct apple_cio *acio) { (void)acio; } +static void apple_cio_lstx_hold(struct apple_cio *acio, bool high) { (void)acio; (void)high; } +static void apple_cio_test_log_guards(struct apple_cio *acio) { (void)acio; } +static void apple_cio_release_domains(struct apple_cio *acio) { (void)acio; released++; } +/* PRODUCTION */ +static struct device dev; +static struct platform_device nhi; +static int rtk; +static int stop(const struct apple_cio_hw *hw, int ret, enum apple_cio_awake awake, + struct apple_cio *acio) +{ + *acio = (struct apple_cio){ .hw = hw, .dev = &dev, .nhi_pdev = &nhi, + .current_cable_info = 0x51, .rtk = &rtk }; + errs = sleeps = reopens = destroyed = depopulated = poweroffs = freed = released = 0; + sleep_ret = ret; + return apple_cio_stop(acio, awake); +} +int main(void) +{ + static const struct apple_cio_hw sleeps_first = { .sleep_router_on_stop = true }; + static const struct apple_cio_hw plain = { 0 }; + struct apple_cio acio; + + /* A router that sleeps: the complex goes off whatever the caller. */ + for (int awake = APPLE_CIO_AWAKE_KEEP; awake <= APPLE_CIO_AWAKE_FORCE; awake++) { + assert(stop(&sleeps_first, 0, awake, &acio) == 0); + assert(sleeps == 1 && destroyed == 1 && depopulated == 1 && !reopens); + assert(poweroffs == 1 && freed == 1 && released == 1 && !acio.current_cable_info); + } + /* No sleep needed: unchanged. */ + assert(stop(&plain, -EIO, APPLE_CIO_AWAKE_KEEP, &acio) == 0); + assert(!sleeps && destroyed == 1 && released == 1 && !acio.current_cable_info); + + /* Sleep or cable change: the port stays up with its NHI and domains. */ + assert(stop(&sleeps_first, -EIO, APPLE_CIO_AWAKE_KEEP, &acio) == -EIO); + assert(reopens == 1 && !destroyed && !depopulated && !poweroffs && !freed && !released); + assert(acio.current_cable_info == 0x51 && acio.rtk == &rtk && errs); + + /* Reboot: the children go, the co-processor and the domains stay. */ + assert(stop(&sleeps_first, -ENODEV, APPLE_CIO_AWAKE_HOLD, &acio) == -ENODEV); + assert(!reopens && destroyed == 1 && depopulated == 1); + assert(!poweroffs && !freed && !released && acio.rtk == &rtk && errs); + + /* Removal: the device and its domains go. */ + assert(stop(&sleeps_first, -EIO, APPLE_CIO_AWAKE_FORCE, &acio) == 0); + assert(!reopens && destroyed == 1 && released == 1 && freed == 1 && errs); + + puts("PASS: ACIO stop keeps the port or its domains up for a router that does not sleep"); + return 0; +} +''' + + +def test_cio_stop(out, acio): + enum = re.search(r'^enum apple_cio_awake \{.*?\n\};', acio, re.M | re.S) + assert enum + production = '\n'.join((enum.group(), + function(acio, 'apple_cio_remove_children'), + function(acio, 'apple_cio_stop'))) + code = CIO_STOP_FIXTURE.replace('/* PRODUCTION */', production) + muts = { + 'cio-stop-ignore-sleep-error': ( + 'ret = apple_cio_sleep_router_for_stop(acio);\n' + '\t\tif (ret && awake == APPLE_CIO_AWAKE_KEEP) {', + 'ret = apple_cio_sleep_router_for_stop(acio);\n' + '\t\tif (false) {'), + 'cio-stop-no-reopen': ( + 'apple_cio_reopen_pcie_tunnel(acio, pcie);', '(void)pcie;'), + 'cio-stop-hold-powers-off': ( + 'if (ret && awake == APPLE_CIO_AWAKE_HOLD) {', 'if (false) {'), + 'cio-stop-keep-powers-off': ( + 'if (ret && awake == APPLE_CIO_AWAKE_KEEP) {\n' + '\t\tdev_err(acio->dev, "the port stays up', + 'if (false) {\n' + '\t\tdev_err(acio->dev, "the port stays up'), + } + cases = {'cio-stop-production': code} + for name, (old, new) in muts.items(): + assert code.count(old) == 1, name + cases[name] = code.replace(old, new) + run_cases(out, cases, extra_flags=('-Wextra', '-Wno-unused-parameter')) + + def main(): parser = argparse.ArgumentParser() parser.add_argument('--out', type=Path) @@ -447,6 +1017,8 @@ def main(): 'apple_pcie_hold_domains', 'apple_pcie_can_keep_link', 'apple_pcie_keep_link', + 'apple_pcie_adopted_links_ready', + 'apple_pcie_adopted_sleep_host', 'apple_pcie_prepare')))) s2idle_code = S2IDLE_FIXTURE.replace('/* PRODUCTION */', s2idle_prod) t6050_old = '\t.mps_timers\t\t= true,\n\t.s2idle_hold_domain\t= true,\n' @@ -478,6 +1050,16 @@ def main(): 'dev_pm_genpd_remove_notifier(pd->dev);', '(void)pd;'), 'ignore-domain-off': ( 'if (!dev_pm_genpd_is_on(pd->dev)) {', 'if (false) {'), + 'drop-adopted-prepare-guard': ( + 'if (pcie && pm_suspend_target_state != PM_SUSPEND_ON &&\n' + '\t apple_pcie_adopted_sleep_host(pcie)) {', + 'if (false) {'), + 'drop-adopted-fw-sleep-guard': ( + 'ret = pcie->t6050_port && pcie->t6050_dart ? 0 : -EBUSY;', + 'ret = 0;'), + 'drop-adopted-parked-skip': ( + 'if (pcie->t6050_parked & BIT(port->idx))\n\t\t\tcontinue;', + 'if (false)\n\t\t\tcontinue;'), } s2idle_cases = {'s2idle-production': s2idle_code} for name, (old, new) in s2idle_muts.items(): @@ -486,10 +1068,15 @@ def main(): with tempfile.TemporaryDirectory(prefix='pciec-policy-') as tmp: out = args.out or Path(tmp) out.mkdir(parents=True, exist_ok=True) + test_pm_order(out, acio) + test_t8122_cio_sleep(out, acio) + test_cio_stop(out, acio) cases = { 'production': code, 'm2-fallback': code.replace( '{ .compatible = "apple,t8112-pciec",\t.data = &t8112_pciec_hw },', ''), + 't8142-admission': code.replace( + 'of_device_is_compatible(np, "apple,t8142-pciec")', 'false'), 'dart-bypass': code.replace( 'tunables = of_property_present(iommu_spec.np, "apple,tunable");', 'tunables = true;'), diff --git a/tools/asahi/pmp-alloc-tests.rs b/tools/asahi/pmp-alloc-tests.rs new file mode 100644 index 00000000000000..af8dedbe30a4d2 --- /dev/null +++ b/tools/asahi/pmp-alloc-tests.rs @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Host tests for the bounds on the PMP firmware's allocations and registers. +#[path = "../../drivers/soc/apple/pmp_alloc.rs"] +mod pmp_alloc; diff --git a/tools/asahi/pmu-rtc-tests.py b/tools/asahi/pmu-rtc-tests.py index 062597ca80b56f..b378c1c61b350f 100644 --- a/tools/asahi/pmu-rtc-tests.py +++ b/tools/asahi/pmu-rtc-tests.py @@ -3,7 +3,7 @@ """Execute the PMU RTC callbacks against a byte-addressed W1C regmap model. C bodies and match data are extracted from the driver. The hardware model has -independent Baku, Abbey, Stowe and Maverick addresses. This checks arithmetic, alarm transactions, +independent Baku, Abbey, Stowe, Sera (DT-rebased Stowe) and Maverick addresses. This checks arithmetic, alarm transactions, shared control preservation, stale events and I/O failures, not physical wake. """ import argparse @@ -19,12 +19,13 @@ 'offset-seconds': ('sign_extend64(offset, 47) * 2', '(s64)offset'), 'offset-sign': ('sign_extend64(offset, 47) * 2', '(s64)offset * 2'), 'event-bit': ('.event_bit = BIT(1)', '.event_bit = BIT(0)'), - 'wrong-control': ('.control = 0x2000', '.control = 0xf800'), - 'maverick-event': ('.event = 0x14c0', '.event = 0x140c'), + 'wrong-control': ('.base = 0x2000', '.base = 0xf800'), + 'maverick-event': ('.event = 0xc0', '.event = 0x0c'), 'control-event-clear': ('control &= ~rtc->hw->control_event_bit;', 'control |= rtc->hw->control_event_bit;'), 'stowe-offset': ('static const struct apple_pmu_rtc_hw apple_pmu_rtc_stowe = {', 'static const struct apple_pmu_rtc_hw apple_pmu_rtc_stowe = {\n\t.offset_in_seconds = true,'), + 'reg-base': ('return rtc->base + offset;', 'return rtc->hw->base + offset;'), 'baku-limit': ('.max_delay = U32_MAX,', '.max_delay = APPLE_PMU_RTC_MAX_DELAY,'), 'set-no-round': ('(counter + BIT(APPLE_PMU_RTC_HZ_SHIFT - 1))', '(counter)'), 'set-negative': ('if (offset < 0 || offset', 'if (offset'), @@ -153,7 +154,7 @@ static struct rtc_device clock_model; static struct apple_pmu_rtc rtc; static struct device dev; -enum { BAKU, ABBEY, STOWE, MAVERICK }; +enum { BAKU, ABBEY, STOWE, SERA, MAVERICK }; static bool abbey; /* offset in 1/32768 s and monitor bit */ static void set_counter(u64 ticks) { memcpy(map.bytes + map.counter, &ticks, 6); } static void set_offset(s64 ticks) { @@ -168,17 +169,20 @@ .event = 0x2000, .bit = 2}, [STOWE] = {.ctrl = 0xf800, .counter = 0xf802, .compare = 0xf808, .mask = 0xf80e, .event = 0xf80c, .bit = 1}, + [SERA] = {.ctrl = 0xd000, .counter = 0xd002, .compare = 0xd008, .mask = 0xd00e, + .event = 0xd00c, .bit = 1}, [MAVERICK] = {.ctrl = 0x1401, .counter = 0x1406, .compare = 0x140c, .mask = 0x14c2, .event = 0x14c0, .bit = 1, .control_event = 2}, }; static const struct apple_pmu_rtc_hw *hw[] = { [BAKU] = &apple_pmu_rtc_baku, [ABBEY] = &apple_pmu_rtc_abbey, - [STOWE] = &apple_pmu_rtc_stowe, [MAVERICK] = &apple_pmu_rtc_maverick, + [STOWE] = &apple_pmu_rtc_stowe, [SERA] = &apple_pmu_rtc_stowe, + [MAVERICK] = &apple_pmu_rtc_maverick, }; bool a = v != BAKU; variant = v; abbey = a; map = layout[v]; offset = (struct nvmem_cell){0}; clock_model = (struct rtc_device){0}; - rtc = (struct apple_pmu_rtc){.hw = hw[v], + rtc = (struct apple_pmu_rtc){.hw = hw[v], .base = v == SERA ? 0xd000 : hw[v]->base, .map = &map, .offset = &offset, .clock = &clock_model}; dev = (struct device){.data = &rtc, .wake = true}; disabled = 0; /* Keep an unrelated writable bit, and each variant's monitor bit. */ @@ -336,8 +340,9 @@ pm_suspend_target_state = PM_SUSPEND_TO_IDLE; } int main(void) { - run_variant(BAKU); run_variant(ABBEY); run_variant(STOWE); run_variant(MAVERICK); - puts("PMU RTC: Baku, Abbey, Stowe and Maverick arithmetic, W1C transactions, Baku clock setting and fault injection passed"); + run_variant(BAKU); run_variant(ABBEY); run_variant(STOWE); run_variant(SERA); + run_variant(MAVERICK); + puts("PMU RTC: Baku, Abbey, Stowe, Sera and Maverick arithmetic, W1C transactions, Baku clock setting and fault injection passed"); return 0; } ''' diff --git a/tools/asahi/qspi-nvram-tests.py b/tools/asahi/qspi-nvram-tests.py index 3e377466e9444b..b34f00178013c2 100644 --- a/tools/asahi/qspi-nvram-tests.py +++ b/tools/asahi/qspi-nvram-tests.py @@ -32,11 +32,8 @@ def function(source, signature): #include #include typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; -typedef uint64_t resource_size_t; -struct device_node { const char *compatible; }; -static const char *machine; -static bool of_device_is_compatible(struct device_node *node,const char *compat){return !strcmp(node->compatible,compat);} -static bool of_machine_is_compatible(const char *compat){return !strcmp(machine,compat);} +#define SZ_2M 0x200000 +#define SZ_8M 0x800000 #define EOPNOTSUPP 95 #define GFP_KERNEL 0 #define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0])) @@ -49,6 +46,10 @@ def function(source, signature): #define SPI_MEM_OP_ADDR(n,a,w) { .val=a,.nbytes=n,.buswidth=w } #define SPI_MEM_OP_NO_ADDR {0} #define SPI_MEM_OP_NO_DUMMY {0} +#define SPI_MEM_OP_DUMMY(n,w) { .nbytes=n,.buswidth=w } +#define get_unaligned_le32(p) ((u32)((const u8*)(p))[0]|(u32)((const u8*)(p))[1]<<8|(u32)((const u8*)(p))[2]<<16|(u32)((const u8*)(p))[3]<<24) +static int info_count; +#define dev_info(device,...) (info_count++) #define SPI_MEM_OP_DATA_IN(n,b,w) { .nbytes=n,.buf.in=b,.buswidth=w,.dir=SPI_MEM_DATA_IN } #define SPI_MEM_OP_NO_DATA {0} #define SPI_MEM_OP(c,a,d,v) { .cmd=c,.addr=a,.dummy=d,.data=v } @@ -68,10 +69,12 @@ def function(source, signature): static int param_get_bool(char*b,const struct kernel_param*p){b[0]=*(bool*)p->arg?'Y':'N';return 1;} struct apple_qspi { bool nvram_policy, nvram_write_candidate, write_fault, nvram_window; - u64 window_start, window_end; - u8 jedec[3]; u8 jedec_alt[3]; u8 bp_ok; + int qualified; const char *qualify_denial; + u64 window_start, window_end, write_start, write_end; int irq; }; +/* The flash model admits only the window, which the controls set. */ +static struct apple_qspi q; struct spi_controller; struct device { struct device *parent; struct spi_controller *controller; }; struct spi_controller { struct apple_qspi *q; bool auto_runtime_pm; struct device dev; }; @@ -92,7 +95,18 @@ def function(source, signature): static bool deny_alloc; static void *kmalloc(size_t n,int flags){return deny_alloc?NULL:malloc(n);} #define kfree free +static void *memchr_inv(const void*p,int c,size_t n){const u8*b=p;for(size_t i=0;i>8;sfdp[0x36]=dword2>>16;sfdp[0x37]=dword2>>24; +} +/* A v3 NVRAM store header at the start of a bank. */ +static void store_at(u64 at){memset(flash+at,0,24);memcpy(flash+at,"3VVN",4);flash[at+5]=0x40;flash[at+14]=1;} static unsigned int wire[4096],wire_count,fail_opcode; static bool corrupt_readback,stuck_busy,programmed; static unsigned int pm_refs,busy_calls,busy_wire; @@ -105,6 +119,8 @@ def function(source, signature): if(o->cmd.opcode==fail_opcode)return -EIO; switch(o->cmd.opcode){ case 0x9f:memcpy(o->data.buf.in,jedec,o->data.nbytes);break; + case 0x5a:assert(o->addr.nbytes==3&&o->dummy.nbytes==1&&o->addr.val+o->data.nbytes<=sizeof(sfdp)); + memcpy(o->data.buf.in,sfdp+o->addr.val,o->data.nbytes);sfdp_reads++;break; case 0x05:*(u8*)o->data.buf.in=sr[0]|(stuck_busy&&programmed?1:0);break; case 0x35:assert(jedec[0]!=0xc2);*(u8*)o->data.buf.in=sr[1];break; case 0x15:*(u8*)o->data.buf.in=sr[2];break; @@ -116,10 +132,10 @@ def function(source, signature): case 0x06:assert(!(sr[0]&3));sr[0]|=2;break; case 0x04:sr[0]&=~2;break; case 0x02: - assert(sr[0]&2);assert(o->addr.val>=0x700000&&o->addr.val+o->data.nbytes<=0x800000); + assert(sr[0]&2);assert(o->addr.val>=q.window_start&&o->addr.val+o->data.nbytes<=q.window_end); for(unsigned int i=0;idata.nbytes;i++)flash[o->addr.val+i]&=((const u8*)o->data.buf.out)[i]; sr[0]&=~2;programmed=true;break; - case 0x20:assert(sr[0]&2);assert(o->addr.val>=0x700000&&o->addr.val+4096<=0x800000); + case 0x20:assert(sr[0]&2);assert(o->addr.val>=q.window_start&&o->addr.val+4096<=q.window_end); memset(flash+o->addr.val,0xff,4096);sr[0]&=~2;programmed=true;break; default:assert(!"forbidden opcode reached the wire"); }return 0; @@ -134,13 +150,15 @@ def function(source, signature): static struct spi_mem mem={&spi}; static struct kernel_param parameter={&read_only}; static void reset(void){ - memset(flash,0xff,sizeof(flash));memset(sr,0,sizeof(sr));q=(struct apple_qspi){.nvram_policy=true,.nvram_write_candidate=true,.window_start=0x700000,.window_end=0x800000,.jedec={0xef,0x65,0x17}}; + memset(flash,0xff,sizeof(flash));memset(sr,0,sizeof(sr));q=(struct apple_qspi){.nvram_policy=true,.nvram_write_candidate=true,.window_start=0x700000,.window_end=0x800000,.write_start=0x700000,.write_end=0x800000,.qualified=1};sfdp_set(0x03ffffff);sfdp_reads=0;info_count=0; read_only=true;runtime_ready=false;write_fault_latched=false;wire_count=0;fail_opcode=0;spi.cs=0; corrupt_readback=false;stuck_busy=false;programmed=false;deny_alloc=false;jiffies=0; jedec[0]=0xef;jedec[1]=0x65;jedec[2]=0x17; ctl.auto_runtime_pm=false;ctl.dev.parent=&parent; pm_refs=busy_calls=busy_wire=0; } +/* A window already qualified with nothing protected, unless a test clears q.qualified. */ +static void window(u64 start,u64 end){q.window_start=q.write_start=start;q.window_end=q.write_end=end;} static struct spi_mem_op program(u64 addr,unsigned int n,const u8*b){ struct spi_mem_op o=SPI_MEM_OP(SPI_MEM_OP_CMD(0x02,1),SPI_MEM_OP_ADDR(3,addr,1),SPI_MEM_OP_NO_DUMMY,SPI_MEM_OP_NO_DATA); o.data.nbytes=n;o.data.dir=SPI_MEM_DATA_OUT;o.data.buswidth=1;o.data.buf.out=b;return o; @@ -149,49 +167,48 @@ def function(source, signature): static bool sent(unsigned int o){for(unsigned int i=0;isize==sizes[i]&&part->bp_ok==tolerated[i]); } - const struct apple_qspi_board *qb; - struct device_node t6041={"apple,t6041-qspi"},t8140={"apple,t8140-qspi"}; - machine="apple,j616s";qb=apple_qspi_nvram_write_board(&t6041,0x429118000ULL); - assert(qb&&qb->nvram_start==0x700000&&qb->nvram_size==0x100000&&qb->jedec[0]==0xc2&&qb->jedec[1]==0x2b&&qb->jedec[2]==0x27&&!qb->bp_ok); - assert(qb->jedec_alt[0]==0xef&&qb->jedec_alt[1]==0x65&&qb->jedec_alt[2]==0x17); - machine="apple,j700";qb=apple_qspi_nvram_write_board(&t8140,0x385110000ULL); - assert(qb&&qb->nvram_start==0x24000&&qb->nvram_size==0x1d0000&&qb->jedec[2]==0x15&&qb->bp_ok==0x1c); - assert(qb->jedec_alt[0]==0xc8&&qb->jedec_alt[1]==0x83&&qb->jedec_alt[2]==0x15); - puts("PASS J613/J713/J700/J616s board, controller and full-width aperture qualification (140 combinations)"); + const u8 unknown[][3]={{0xef,0x65,0x16},{0xef,0x65,0x18},{0xc2,0x2b,0x28},{0xc8,0x60,0x15},{0xef,0x40,0x17},{0,0,0},{0xff,0xff,0xff}}; + for(unsigned int i=0;icontroller) &&', ''), - ('board', 'of_machine_is_compatible(board->machine) &&', ''), - ('aperture', 'base == board->base', 'base != 0'), - ('j616s-aperture', '"apple,j616s", 0x429118000ULL', '"apple,j616s", 0x429118800ULL'), - ('j616s-partition', '"apple,j616s", 0x429118000ULL,\n\t 0x700000', '"apple,j616s", 0x429118000ULL,\n\t 0x680000'), + ('part-id', 'return &apple_qspi_parts[i];\n\treturn NULL;', 'return &apple_qspi_parts[i];\n\treturn &apple_qspi_parts[0];'), + ('part-size', '!part || qspi->window_end > part->size', '!part'), + ('part-bp', 'before[2], part->bp_ok)', 'before[2], 0x1c)'), + ('w25q16-size', '{ APPLE_QSPI_JEDEC_W25Q16, 0x200000, 0x1c }', '{ APPLE_QSPI_JEDEC_W25Q16, 0x800000, 0x1c }'), + ('protected', 'op->addr.val < pe && op->addr.val + len > ps', '0'), + ('bank-invalid', 'if (state < 0) {', 'if (0) {'), + ('bank-none', 'if (!stores) {', 'if (stores < 0) {'), + ('bank-latch', 'qspi->qualified = ret;', '(void)0;'), + ('bank-blank', 'if (memchr_inv(buf, 0xff, APPLE_QSPI_ERASE_SIZE))', 'if (0)'), + ('protected-bank', 'op->addr.val < qspi->write_start || op->addr.val + len > qspi->write_end', '0'), + ('protected-qualify', '!apple_qspi_unprotected_banks(', '0 && !apple_qspi_unprotected_banks('), + ('sfdp-size', '!= part->size) {', '!= part->size && 0) {'), + ('window-read-only', '!read_only && size &&', 'size &&'), + ('window-bank', '!(size % APPLE_QSPI_NVRAM_BANK) &&', ''), ('range', 'addr >= start &&', 'addr >= 1 &&'), ('bp-ok', '!(sr1 & 0x1c & ~bp_ok)', '1'), ('mx-bp3', '!(sr & 0x3c & ~bp_ok)', '!(sr & 0x1c & ~bp_ok)'), ('mx-eqio', 'opcode = macronix;', 'opcode = winbond;'), ('mx-eqio-read', '!ret && id[0] == APPLE_QSPI_MFR_MACRONIX', '0'), - ('jedec-alt', 'memcmp(id, qspi->jedec_alt, sizeof(id))', '1'), - ('jedec-alt-empty', '!qspi->jedec_alt[0] || ', ''), ('gd-dispatch', 'return apple_qspi_gd_status_allows_write(sr1, sr2, bp_ok);', 'return apple_qspi_status_allows_write(sr1, sr2, sr3, bp_ok);'), ('gd-bp34', '!(sr1 & 0x7c & ~bp_ok)', '!(sr1 & 0x1c & ~bp_ok)'), @@ -379,6 +487,8 @@ def main(): ('gd-cmp', '!(sr2 & 0xc4)', '!(sr2 & 0x84)'), ('j700-gd-id', 'APPLE_QSPI_JEDEC_GD25UF16E\t{ 0xc8, 0x83, 0x15 }', 'APPLE_QSPI_JEDEC_GD25UF16E\t{ 0xc8, 0x83, 0x16 }'), + ('j775d-gd-id', 'APPLE_QSPI_JEDEC_GD25UF64E\t{ 0xc8, 0x83, 0x17 }', + 'APPLE_QSPI_JEDEC_GD25UF64E\t{ 0xc8, 0x83, 0x18 }'), ('read-only', 'read_only || !qspi->nvram_write_candidate || qspi->write_fault', '!qspi->nvram_write_candidate || qspi->write_fault'), ('fault-latch', 'write_fault_latched = true;', 'write_fault_latched = false;'), diff --git a/tools/asahi/rtkit-adopted-session-tests.py b/tools/asahi/rtkit-adopted-session-tests.py new file mode 100755 index 00000000000000..a43f60b841bbad --- /dev/null +++ b/tools/asahi/rtkit-adopted-session-tests.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Check how RTKit imports the endpoint map of a session a boot stage handed over.""" +import argparse +from pathlib import Path +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +DRIVER = 'drivers/soc/apple/rtkit.c' +INTERNAL = 'drivers/soc/apple/rtkit-internal.h' +HEADER = 'include/linux/soc/apple/rtkit.h' + +# Each mutation drops one check; an assertion must then fail. +MUTATIONS = { + 'no-management': ('if (!test_bit(APPLE_RTKIT_EP_MGMT, map))', 'if (0)'), + 'any-system': ('if (test_bit(i, map) && !test_bit(i, known))', 'if (0)'), + 'any-version': ('session->protocol_version < APPLE_RTKIT_MIN_SUPPORTED_VERSION ||', '0 ||'), + 'ignore-ops-version': ('session->protocol_version != rtk->ops->protocol_version', '0'), + 'any-buffer-endpoint': ('rtk->ioreport_buffer.size && !test_bit(APPLE_RTKIT_EP_IOREPORT, map)', '0'), +} + + +def function(source, name): + match = re.search(r'^static int ' + name + r'\(', source, re.M) + assert match, name + opening = source.index('{', match.end()) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[match.start():end] + '\n' + + +PREFIX = r''' +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; +#define BUILD_BUG_ON(x) _Static_assert(!(x), #x) +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define DECLARE_BITMAP(n, bits) bool n[bits] +static void set_bit(unsigned int b, bool *m) { m[b] = true; } +static bool test_bit(unsigned int b, const bool *m) { return m[b]; } +static void bitmap_from_arr32(bool *m, const u32 *a, unsigned int bits) +{ for (unsigned int i = 0; i < bits; i++) m[i] = a[i / 32] >> (i % 32) & 1; } +static void bitmap_copy(bool *d, const bool *s, unsigned int bits) { memcpy(d, s, bits); } +struct apple_rtkit_inherited_buffer { int unused; }; +struct apple_rtkit_ops { u16 protocol_version; }; +''' + +TESTS = r''' +struct apple_rtkit_shmem { unsigned long size; }; +struct apple_rtkit { + const struct apple_rtkit_ops *ops; + bool endpoints[APPLE_RTKIT_MAX_ENDPOINTS]; + u16 version; + struct apple_rtkit_shmem crashlog_buffer, syslog_buffer, ioreport_buffer, oslog_buffer; +}; +''' + '%s' + r''' +static int run(u16 required, u16 version, const u32 *map, struct apple_rtkit *rtk) +{ + static struct apple_rtkit_ops ops; + struct apple_rtkit_adopted_session s = { .protocol_version = version }; + struct apple_rtkit_shmem crashlog = rtk->crashlog_buffer, syslog = rtk->syslog_buffer; + struct apple_rtkit_shmem ioreport = rtk->ioreport_buffer, oslog = rtk->oslog_buffer; + + ops.protocol_version = required; + memset(rtk, 0, sizeof(*rtk)); + rtk->ops = &ops; + /* The buffers the session retained, set by the caller. */ + rtk->crashlog_buffer = crashlog; + rtk->syslog_buffer = syslog; + rtk->ioreport_buffer = ioreport; + rtk->oslog_buffer = oslog; + memcpy(s.epmap, map, sizeof(s.epmap)); + return apple_rtkit_inherit_endpoints(rtk, &s); +} + +int main(void) +{ + /* + * An M2 Mac mini HDMI DCP on the 27.2 firmware, as its boot stage + * describes it: system endpoints 0-4 and 8, application endpoints + * 0x20-0x2c, 0x31 and 0x37. + */ + const u32 dcpext[8] = { 0x0000011f, 0x00821fff }; + struct apple_rtkit r = {}; + u32 m[8]; + int i; + + assert(run(0, 12, dcpext, &r) == 0); + for (i = 0; i < APPLE_RTKIT_MAX_ENDPOINTS; i++) { + bool want = i <= 4 || i == 8 || (i >= 0x20 && i <= 0x2c) || + i == 0x31 || i == 0x37; + assert(r.endpoints[i] == want); + } + assert(r.version == 12); + + /* A driver that needs one protocol version takes only that one. */ + assert(run(12, 12, dcpext, &r) == 0); + assert(run(11, 12, dcpext, &r) == -EINVAL); + /* Versions RTKit does not speak are refused. */ + assert(run(0, APPLE_RTKIT_MIN_SUPPORTED_VERSION - 1, dcpext, &r) == -EINVAL); + assert(run(0, APPLE_RTKIT_MAX_SUPPORTED_VERSION + 1, dcpext, &r) == -EINVAL); + + /* Without management there is no session to adopt. */ + memcpy(m, dcpext, sizeof(m)); + m[0] &= ~1u; + assert(run(0, 12, m, &r) == -EINVAL); + /* A system endpoint RTKit does not implement is not silently ignored. */ + memcpy(m, dcpext, sizeof(m)); + m[0] |= 1u << 5; + assert(run(0, 12, m, &r) == -EINVAL); + /* Tracekit (0xa) is one RTKit knows. */ + memcpy(m, dcpext, sizeof(m)); + m[0] |= 1u << 0xa; + assert(run(0, 12, m, &r) == 0 && r.endpoints[0xa]); + /* Every known system endpoint and every application endpoint. */ + for (i = 0; i < 8; i++) + m[i] = i ? ~0u : 0x59fu; + assert(run(0, 11, m, &r) == 0 && r.endpoints[0x20] && r.endpoints[0xff]); + /* Management alone. */ + memset(m, 0, sizeof(m)); + m[0] = 1; + assert(run(0, 12, m, &r) == 0 && r.endpoints[0] && !r.endpoints[0x37]); + + /* + * The J473 retains crashlog, syslog and ioreport buffers: all three + * endpoints are in its map. A buffer for an endpoint the map lacks + * is refused. + */ + memset(&r, 0, sizeof(r)); + r.crashlog_buffer.size = 0x10000; + r.syslog_buffer.size = 0x4000; + r.ioreport_buffer.size = 0x4000; + assert(run(0, 12, dcpext, &r) == 0); + memcpy(m, dcpext, sizeof(m)); + m[0] &= ~(1u << 4); + assert(run(0, 12, m, &r) == -EINVAL); + memset(&r, 0, sizeof(r)); + r.oslog_buffer.size = 0x4000; + assert(run(0, 12, dcpext, &r) == 0); + memcpy(m, dcpext, sizeof(m)); + m[0] &= ~(1u << 8); + assert(run(0, 12, m, &r) == -EINVAL); + + puts("PASS adopted session endpoint map, protocol version and system endpoints"); + return 0; +} +''' + + +def build_source(mutation): + driver = (ROOT / DRIVER).read_text() + internal = (ROOT / INTERNAL).read_text() + header = (ROOT / HEADER).read_text() + defines = re.findall(r'^#define APPLE_RTKIT_(?:MIN_SUPPORTED_VERSION|MAX_SUPPORTED_VERSION|' + r'APP_ENDPOINT_START|MAX_ENDPOINTS)\b.*$', driver + internal, re.M) + assert len(defines) == 4, defines + words = re.search(r'^#define APPLE_RTKIT_ADOPTED_EPMAP_WORDS.*$', header, re.M) + session = re.search(r'^struct apple_rtkit_adopted_session \{.*?^\};', header, re.M | re.S) + endpoints = re.search(r'enum \{\s*APPLE_RTKIT_EP_MGMT = 0,.*?\};', driver, re.S) + assert words and session and endpoints + imported = function(driver, 'apple_rtkit_inherit_endpoints') + if mutation: + old, new = MUTATIONS[mutation] + assert old in imported, mutation + imported = imported.replace(old, new) + # The firmware's map replaces the assumed one before RX can deliver + # traffic for its endpoints. + init = re.search(r'^static struct apple_rtkit \*__apple_rtkit_init\(.*?^\}', driver, re.M | re.S) + assert init + body = init.group(0) + assert (body.index('apple_rtkit_mark_running(rtk)') < + body.index('apple_rtkit_inherit_endpoints(') < + body.index('apple_rtkit_claim_rx(')) + return (PREFIX + '\n'.join(defines) + '\n' + words.group(0) + '\n' + endpoints.group(0) + + '\n' + session.group(0) + '\n' + TESTS % imported) + + +def run(out, cc, mutation): + source = out / 'rtkit-adopted-session.c' + binary = out / 'rtkit-adopted-session' + source.write_text(build_source(mutation)) + subprocess.run([cc, '-std=gnu11', '-Wall', '-Wextra', '-Werror', '-fsanitize=address,undefined', + str(source), '-o', str(binary)], check=True) + return subprocess.run([str(binary)]).returncode + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--out', type=Path, help='keep build and result files here') + parser.add_argument('--cc', default='cc') + parser.add_argument('--mutation', choices=sorted(MUTATIONS), + help='drop one check (the run must fail an assertion)') + args = parser.parse_args() + with tempfile.TemporaryDirectory() as tmp: + out = args.out or Path(tmp) + out.mkdir(parents=True, exist_ok=True) + status = run(out, args.cc, args.mutation) + raise SystemExit(status) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/rtkit-coreanalytics-tests.py b/tools/asahi/rtkit-coreanalytics-tests.py new file mode 100755 index 00000000000000..55b5a2f929adf3 --- /dev/null +++ b/tools/asahi/rtkit-coreanalytics-tests.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Check which co-processors' endpoint 7 messages RTKit serves. + +apple_rtkit_rx_dispatch() and the CoreAnalytics handlers are taken from +drivers/soc/apple/rtkit.c unchanged and built with ASan and UBSan. The +endpoint map starts endpoint 7 only for a client that asks for CoreAnalytics +(APPLE_RTKIT_NEEDS_COREANALYTICS) and for registry-v2 PMP firmware, so only +those get a buffer or an acknowledgment there: a buffer request from any +other co-processor, of any size, allocates nothing and is not answered, and +is reported through the rate-limited unknown-endpoint warning. + +--old-ref REV runs the same checks on the driver at REV and requires them to +fail there. +""" +import argparse +from pathlib import Path +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +DRIVER = 'drivers/soc/apple/rtkit.c' +HEADER = 'include/linux/soc/apple/rtkit.h' +INTERNAL = 'drivers/soc/apple/rtkit-internal.h' + + +def function(source, name, optional=False): + match = re.search(r'^(?:static )?(?:void|int|bool|size_t) ' + name + r'\(', source, re.M) + if not match and optional: + return '' + assert match, name + opening = source.index('{', match.end()) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[match.start():end] + '\n' + + +def constants(source, header, internal): + out = [line for line in source.splitlines() if re.match(r'#define APPLE_RTKIT_CA_\w+ ', line)] + out += [f'#define APPLE_RTKIT_{name} {value}' + for name, value in re.findall(r'^\tAPPLE_RTKIT_(EP_\w+) = (\w+),', source, re.M)] + out += [line for line in header.splitlines() + if re.match(r'#define APPLE_RTKIT_NEEDS_COREANALYTICS\b', line)] + out += [line for line in internal.splitlines() + if re.match(r'#define APPLE_RTKIT_APP_ENDPOINT_START\b', line)] + for name in ('NEEDS_COREANALYTICS', 'EP_COREANALYTICS', 'APP_ENDPOINT_START', 'CA_TYPE'): + assert any(name in line for line in out), name + return '\n'.join(out) + '\n' + + +PREFIX = r''' +#include +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; +typedef uint64_t dma_addr_t; +#define __iomem +#define BIT(n) (1UL << (n)) +#define BIT_ULL(n) (1ULL << (n)) +#define GENMASK_ULL(h,l) ((~0ULL << (l)) & (~0ULL >> (63-(h)))) +#define FIELD_GET(m,v) (((v) & (m)) >> __builtin_ctzll(m)) +#define FIELD_PREP(m,v) (((u64)(v) << __builtin_ctzll(m)) & (m)) +#define FIELD_FIT(m,v) (!((((u64)(v)) << __builtin_ctzll(m)) & ~(m))) +#define READ_ONCE(x) (x) +#define dev_warn(...) ((void)0) +#define dev_warn_ratelimited(...) ((void)warned++) +#define dev_err(...) ((void)0) +#define dev_dbg(...) ((void)0) + +struct apple_rtkit_shmem { + void *buffer; void *iomem; size_t size; dma_addr_t iova; + bool is_mapped, needs_dma_sync; void *private; +}; +struct apple_rtkit_ops { + unsigned int flags; + void (*recv_message)(void *, u8, u64); + void (*recv_message_timed)(void *, u8, u64, u64); + int (*shmem_setup)(void *, struct apple_rtkit_shmem *); + int (*shmem_setup_ep)(void *, u8, struct apple_rtkit_shmem *); +}; +struct apple_rtkit { + void *dev, *cookie; + const struct apple_rtkit_ops *ops; + bool shutting_down, sync_syslog_ack, pmp_registry_v2; + struct { int error; } m5_saved; + struct apple_rtkit_shmem coreanalytics_buffer; + int coreanalytics_completion; +}; + +static unsigned allocations, frees, sent, aux, warned; +static size_t allocated; +static char memory[64]; +static int apple_rtkit_alloc_shmem(struct apple_rtkit *rtk, u8 ep, struct apple_rtkit_shmem *b) +{ + (void)rtk; assert(ep == APPLE_RTKIT_EP_COREANALYTICS); + allocations++; allocated = b->size; + /* Only the bookkeeping matters here: the memset below gets a stand-in. */ + b->buffer = memory; b->iova = 0x10000; + return 0; +} +#define memset(p, c, n) ((void)(p), (void)(c), (void)(n)) +#define memset_io(p, c, n) ((void)(p), (void)(c), (void)(n)) +static void apple_rtkit_free_buffer(struct apple_rtkit *rtk, struct apple_rtkit_shmem *b) +{ + (void)rtk; (void)b; frees++; +} +static int apple_rtkit_send_message(struct apple_rtkit *rtk, u8 ep, u64 msg, void *c, bool a) +{ + (void)rtk; (void)msg; (void)c; (void)a; assert(ep == APPLE_RTKIT_EP_COREANALYTICS); sent++; return 0; +} +static void complete_all(int *c) { (*c)++; } +#define STUB(n) static void n(struct apple_rtkit *r, u64 m) { (void)r; (void)m; } +STUB(apple_rtkit_management_rx) STUB(apple_rtkit_crashlog_rx) STUB(apple_rtkit_syslog_rx) +STUB(apple_rtkit_ioreport_rx) STUB(apple_rtkit_kdebug_rx) STUB(apple_rtkit_oslog_rx) +static void apple_rtkit_pmp_aux_rx(struct apple_rtkit *r, u64 m) { (void)r; (void)m; aux++; } +''' + +MAIN = r''' +static u64 buffer_request(unsigned count, u64 unit) +{ + return FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_BUFFER_REQUEST) | + FIELD_PREP(APPLE_RTKIT_CA_COUNT, count) | unit; +} + +static void deliver_ep(const struct apple_rtkit_ops *ops, bool registry_v2, u8 ep, u64 msg) +{ + struct apple_rtkit rtk = { .ops = ops, .pmp_registry_v2 = registry_v2 }; + + allocations = frees = sent = aux = warned = 0; + allocated = 0; + apple_rtkit_rx_dispatch(&rtk, ep, msg, false, 0); +} + +static void deliver(const struct apple_rtkit_ops *ops, bool registry_v2, u64 msg) +{ + deliver_ep(ops, registry_v2, APPLE_RTKIT_EP_COREANALYTICS, msg); +} + +int main(void) +{ + const struct apple_rtkit_ops plain = { 0 }; + const struct apple_rtkit_ops asks = { .flags = APPLE_RTKIT_NEEDS_COREANALYTICS }; + u64 largest = buffer_request(255, APPLE_RTKIT_CA_UNIT_1M); + u64 small = buffer_request(4, APPLE_RTKIT_CA_UNIT_4K); + u64 event = FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_EVENT) | + FIELD_PREP(APPLE_RTKIT_CA_EVENT_ID, 9); + + /* A client that asked for CoreAnalytics gets its buffer and its acks. */ + deliver(&asks, false, small); + assert(allocations == 1 && allocated == 0x4000 && sent == 1 && frees == 0 && !warned); + deliver(&asks, false, event); + assert(allocations == 0 && sent == 1 && !warned); + + /* Registry-v2 PMP firmware's endpoint 7 is its auxiliary buffer. */ + deliver(&plain, true, small); + assert(aux == 1 && allocations == 0 && sent == 0 && !warned); + + /* + * Any other co-processor: nothing allocated, nothing answered, and the + * message reported through the rate-limited unknown-endpoint warning, + * since the firmware decides how often it arrives. + */ + deliver(&plain, false, small); + assert(allocations == 0 && sent == 0 && aux == 0 && warned == 1); + deliver(&plain, false, largest); + assert(allocations == 0 && sent == 0 && aux == 0 && warned == 1); + deliver(&plain, false, event); + assert(allocations == 0 && sent == 0 && aux == 0 && warned == 1); + + /* A system endpoint nobody serves takes the same warning. */ + deliver_ep(&asks, false, 0x10, small); + assert(allocations == 0 && sent == 0 && aux == 0 && warned == 1); + + puts("PASS endpoint 7 is served only for the clients the endpoint map starts it for"); + return 0; +} +''' + + +def read(ref, path): + if not ref: + return (ROOT / path).read_text() + return subprocess.run(['git', '-C', str(ROOT), 'show', f'{ref}:{path}'], check=True, + capture_output=True, text=True).stdout + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--out', type=Path, help='keep build and result files here') + parser.add_argument('--cc', default='cc') + parser.add_argument('--old-ref', help='require the driver at this revision to fail') + args = parser.parse_args() + source = read(args.old_ref, DRIVER) + code = constants(source, read(args.old_ref, HEADER), read(args.old_ref, INTERNAL)) + PREFIX + for name in ('apple_rtkit_needs_coreanalytics', 'apple_rtkit_coreanalytics_size', + 'apple_rtkit_coreanalytics_reply', 'apple_rtkit_coreanalytics_get_buffer', + 'apple_rtkit_coreanalytics_rx', 'apple_rtkit_rx_dispatch'): + code += function(source, name) + if name == 'apple_rtkit_needs_coreanalytics': + # The one predicate the endpoint map and the dispatcher share; absent before it. + code += function(source, 'apple_rtkit_ep7_served', optional=True) + # The one rate-limited warning for unserved endpoints; absent before it. + code += function(source, 'apple_rtkit_unserved_ep_msg', optional=True) + code += MAIN + + def run(out): + out.mkdir(parents=True, exist_ok=True) + cfile, exe = out / 'coreanalytics.c', out / 'coreanalytics' + cfile.write_text(code) + subprocess.run([args.cc, '-std=gnu11', '-O1', '-g', '-Wall', '-Wextra', '-Werror', + '-Wno-unused-parameter', '-Wno-unused-function', + '-fsanitize=address,undefined', '-fno-sanitize-recover=all', + str(cfile), '-o', str(exe)], check=True) + result = subprocess.run([str(exe)], capture_output=True, text=True) + if args.old_ref: + if result.returncode == 0: + raise SystemExit(f'{args.old_ref} passed; the test does not catch the original code') + print(result.stderr, end='') + print('old revision fails as required') + return 0 + print(result.stdout + result.stderr, end='') + return result.returncode + + if args.out: + return run(args.out) + with tempfile.TemporaryDirectory(prefix='rtkit-coreanalytics-') as out: + return run(Path(out)) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/asahi/rtkit-crashlog-map-tests.py b/tools/asahi/rtkit-crashlog-map-tests.py new file mode 100755 index 00000000000000..edebd17bc31e17 --- /dev/null +++ b/tools/asahi/rtkit-crashlog-map-tests.py @@ -0,0 +1,391 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Check which crash log buffers a co-processor places that RTKit maps. + +apple_rtkit_crashlog_map(), apple_rtkit_maps_placed_crashlog() from +drivers/soc/apple/rtkit.c and apple_dart_fw_range() with its two helpers from +drivers/iommu/apple-dart.c are taken unchanged and built with ASan and UBSan +against a stand-in IOMMU (4 KiB granularity) and a stand-in resource map. The +buffer is mapped only when every IOMMU page it touches, through Linux's paging +mappings or those the firmware kept, translates at the same offset as its first +byte, and the CPU-page-rounded range is DRAM that isn't the kernel's System RAM. +Identity domains never answer APPLE_DART_FW_LINUX and are refused. Every +memremap() is checked against the pages the test gave the device and must be +write-combined. + +--old-ref REV runs the same checks on the driver at REV (its own walk, where +apple-dart.c has no apple_dart_fw_range()) and requires them to fail there. +""" +import argparse +from pathlib import Path +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +DRIVER = 'drivers/soc/apple/rtkit.c' +DART = 'drivers/iommu/apple-dart.c' + + +def function(source, name): + """The definition of function name (a forward declaration is skipped).""" + pattern = r'^(?:static )?(?:void|int|bool|phys_addr_t)\s*\n?' + name + r'\(' + match = next((m for m in re.finditer(pattern, source, re.M) + if ';' not in source[m.end():source.index('{', m.end())]), None) + assert match, name + opening = source.index('{', match.end()) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[match.start():end] + '\n' + + +def constants(source): + out = [line for line in source.splitlines() + if re.match(r'#define APPLE_RTKIT_BUFFER_REQUEST_(SIZE|IOVA)\b', line)] + assert len(out) == 2, out + return '\n'.join(out) + '\n' + + +PREFIX = r''' +#include +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; +typedef uint64_t dma_addr_t; typedef uint64_t phys_addr_t; +#define GENMASK_ULL(h,l) ((~0ULL << (l)) & (~0ULL >> (63-(h)))) +#define FIELD_GET(m,v) (((v) & (m)) >> __builtin_ctzll(m)) +#define PAGE_SIZE 16384UL +#define ALIGN_DOWN(x, a) ((x) & ~((__typeof__(x))(a) - 1)) +#define ALIGN(x, a) (((x) + ((__typeof__(x))(a) - 1)) & ~((__typeof__(x))(a) - 1)) +#define __ffs(x) ((unsigned long)__builtin_ctzl(x)) +#define check_add_overflow(a, b, d) __builtin_add_overflow(a, b, d) +#define IS_REACHABLE(x) 1 +#define CONFIG_APPLE_DART 1 +#define MEMREMAP_WB 1 +#define MEMREMAP_WC 4 +#define dev_err(...) ((void)0) +#define APPLE_RTKIT_EP_CRASHLOG 2 +#define APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG (1u << 0) +#define APPLE_DART_FW_LINUX (1u << 0) +#define APPLE_DART_FW_RETAINED (1u << 1) +#define EXPORT_SYMBOL_GPL(x) +#define __IOMMU_DOMAIN_PAGING (1u << 1) +#define IOMMU_DOMAIN_IDENTITY (1u << 2) +#define IOMMU_DOMAIN_DMA (__IOMMU_DOMAIN_PAGING | (1u << 3)) + +struct device { int unused; }; +struct iommu_domain { unsigned type; unsigned long pgsize_bitmap; }; +struct apple_rtkit_ops { + unsigned flags; + void *shmem_setup; + void *shmem_setup_ep; +}; +struct apple_rtkit_shmem { void *buffer; size_t size; dma_addr_t iova; bool is_mapped; }; +struct apple_rtkit { + struct device *dev; + const struct apple_rtkit_ops *ops; + struct apple_rtkit_shmem crashlog_buffer; + bool crashlog_placed; +}; +static bool apple_rtkit_firmware_owns_crashlog(struct apple_rtkit *rtk) +{ + return rtk->ops && (rtk->ops->flags & APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG); +} + +/* + * The device's IOMMU at 4 KiB granularity (4 subpages per 16 KiB block), so a + * 4 KiB pgsize_bitmap check genuinely tests subpage discontinuities. + */ +#define IOMMU_PAGE 0x4000ULL +#define SUB_PAGE 0x1000ULL +#define DVA_BASE 0x100000000ULL +#define NPAGES 16 +#define NSUB (NPAGES * 4) +static phys_addr_t table[NSUB], kept[NSUB]; +static struct iommu_domain the_domain = { + .type = IOMMU_DOMAIN_DMA, + .pgsize_bitmap = 0x4000 | 0x2000000, +}; + +static void map16(phys_addr_t *t, int page16, phys_addr_t phys) +{ + for (int s = 0; s < 4; s++) + t[page16 * 4 + s] = phys ? phys + s * SUB_PAGE : 0; +} + +static struct iommu_domain *iommu_get_domain_for_dev(struct device *dev) +{ + (void)dev; return &the_domain; +} +static phys_addr_t lookup(phys_addr_t *t, dma_addr_t iova) +{ + if (iova < DVA_BASE || iova >= DVA_BASE + NSUB * SUB_PAGE) + return 0; + phys_addr_t page = t[(iova - DVA_BASE) / SUB_PAGE]; + return page ? page + (iova & (SUB_PAGE - 1)) : 0; +} +static phys_addr_t iommu_iova_to_phys(struct iommu_domain *d, dma_addr_t iova) +{ + if (d->type == IOMMU_DOMAIN_IDENTITY) + return iova; + return lookup(table, iova); +} +/* + * As the driver's: identity domains have no owner (-ENODEV), and a DVA Linux + * mapped itself is refused (-EACCES). + */ +static int apple_dart_fw_remote(struct device *dev, dma_addr_t iova, bool write, phys_addr_t *phys) +{ + (void)dev; (void)write; + if (the_domain.type == IOMMU_DOMAIN_IDENTITY) + return -ENODEV; + if (lookup(table, iova)) + return -EACCES; + *phys = lookup(kept, iova); + return *phys ? 0 : -ENXIO; +} + +/* + * The resource map: registers below 0x800000000, System RAM (the kernel's) at + * 0x800000000-0x87fffcfff (ending mid-16 KiB CPU page so CPU-page rounding is + * genuinely exercised), and above it DRAM the kernel doesn't use (carveouts). + */ +#define IORESOURCE_MEM 0x200 +#define IORESOURCE_SYSTEM_RAM 0x1200 +#define IORES_DESC_NONE 0 +enum { REGION_INTERSECTS, REGION_DISJOINT, REGION_MIXED }; +#define RAM_START 0x800000000ULL +#define RAM_END 0x87fffd000ULL +static int region_intersects(phys_addr_t start, size_t size, unsigned long flags, unsigned long desc) +{ + phys_addr_t end = start + size; + (void)desc; + assert(flags == IORESOURCE_SYSTEM_RAM); + return start < RAM_END && end > RAM_START ? REGION_INTERSECTS : REGION_DISJOINT; +} + +/* Is the physical byte range [pa, pa + len) inside pages the device was given? */ +static bool device_owns(phys_addr_t pa, size_t len) +{ + for (phys_addr_t p = pa & ~(SUB_PAGE - 1); p < pa + len; p += SUB_PAGE) { + bool found = false; + for (int i = 0; i < NSUB; i++) + found |= table[i] == p || kept[i] == p; + if (!found) + return false; + } + return true; +} +static unsigned remaps; +static char backing[1]; +static void *memremap(phys_addr_t pa, size_t len, unsigned long flags) +{ + remaps++; + if (!device_owns(pa, len) || ALIGN_DOWN(pa, PAGE_SIZE) < RAM_END) { + fprintf(stderr, "FAIL: memremap(%#llx, %#zx) covers memory the device may not share\n", + (unsigned long long)pa, len); + assert(0); + } + if (flags != MEMREMAP_WC) { + fprintf(stderr, "FAIL: memremap(%#llx, %#zx) not write-combined\n", + (unsigned long long)pa, len); + assert(0); + } + return backing; +} +static unsigned acks; +static int apple_rtkit_send_message(struct apple_rtkit *rtk, u8 ep, u64 msg, void *c, bool a) +{ + (void)rtk; (void)ep; (void)msg; (void)c; (void)a; acks++; return 0; +} +''' + +MAIN = r''' +static struct device dev; + +static u64 request(dma_addr_t iova, size_t size) +{ + return ((u64)(size >> 12) << 44) | iova; +} + +static int place(dma_addr_t iova, size_t size) +{ + struct apple_rtkit rtk = { .dev = &dev }; + int ret; + + remaps = acks = 0; + ret = apple_rtkit_crashlog_map(&rtk, request(iova, size)); + assert(ret || (remaps == 1 && acks == 1 && rtk.crashlog_placed && + rtk.crashlog_buffer.size == size && rtk.crashlog_buffer.iova == iova)); + assert(!ret || (remaps == 0 && acks == 0 && !rtk.crashlog_placed)); + return ret; +} + +int main(void) +{ + /* + * Linux's mappings: DVA pages 0-2 on contiguous physical pages, page 3 elsewhere, + * 4 unmapped; pages 6-7 straddle the end of System RAM; page 8 on registers. + */ + map16(table, 0, 0x900000000ULL); + map16(table, 1, 0x900004000ULL); + map16(table, 2, 0x900008000ULL); + map16(table, 3, 0x980000000ULL); + map16(table, 6, 0x87fffc000ULL); + map16(table, 7, 0x880000000ULL); + map16(table, 8, 0x200000000ULL); + /* The firmware's kept mappings: pages 10-11 contiguous, 12 elsewhere. */ + map16(kept, 10, 0xa00000000ULL); + map16(kept, 11, 0xa00004000ULL); + map16(kept, 12, 0xb00000000ULL); + + /* Aligned buffers on contiguous pages. */ + assert(place(DVA_BASE, 0x4000) == 0); + assert(place(DVA_BASE, 0xc000) == 0); + /* Unaligned, inside one page or across contiguous ones. */ + assert(place(DVA_BASE + 0x1000, 0x2000) == 0); + assert(place(DVA_BASE + 0x3000, 0x4000) == 0); + assert(place(DVA_BASE + 0x6000, 0x6000) == 0); + /* Through the firmware's kept mappings. */ + assert(place(DVA_BASE + 10 * IOMMU_PAGE + 0x2000, 0x4000) == 0); + + /* An aligned buffer whose second page lies elsewhere or isn't mapped. */ + assert(place(DVA_BASE + 0x8000, 0x8000) == -ERANGE); + assert(place(DVA_BASE + 0xc000, 0x8000) == -ERANGE); + assert(place(DVA_BASE + 11 * IOMMU_PAGE, 0x8000) == -ERANGE); + + /* + * Unaligned buffers whose last bytes are on a page that lies elsewhere + * or isn't mapped, including a last byte on byte 0 of the bad page + * (catches addr < last vs addr <= last). + */ + assert(place(DVA_BASE + 0x8001, 0x4000) == -ERANGE); + assert(place(DVA_BASE + 0xb000, 0x4000) == -ERANGE); + assert(place(DVA_BASE + 0xf000, 0x4000) == -ERANGE); + assert(place(DVA_BASE + 0x9000, 0x8000) == -ERANGE); + + /* Nothing at the first byte. */ + assert(place(DVA_BASE + 0x10000, 0x4000) == -ENOENT); + assert(place(DVA_BASE + 0x3c000, 0x1000) == -ENOENT); + + /* + * Contiguous, but reaching System RAM, wholly in it, sharing a 16 KiB + * CPU page with it (strictly past RAM_END), or on registers below DRAM; + * the first full CPU page past System RAM is a carveout and is mapped. + */ + assert(place(DVA_BASE + 6 * IOMMU_PAGE, 0x8000) == -EACCES); + assert(place(DVA_BASE + 6 * IOMMU_PAGE, 0x1000) == -EACCES); + assert(place(DVA_BASE + 6 * IOMMU_PAGE + 0x3000, 0x1000) == -EACCES); + assert(place(DVA_BASE + 8 * IOMMU_PAGE, 0x4000) == -EACCES); + assert(place(DVA_BASE + 7 * IOMMU_PAGE, 0x4000) == 0); + + /* A buffer that would wrap the DVA space. */ + assert(place(0xfffffffff000ULL, 0x2000) != 0); + + /* + * 4 KiB smallest IOMMU page: break only subpage 2 inside 16 KiB block 13. + * A 16 KiB walk misses it; the 4 KiB walk catches it. + */ + map16(table, 13, 0x910000000ULL); + table[13 * 4 + 2] = 0x920000000ULL; + the_domain.pgsize_bitmap = 0x1000 | 0x4000; + assert(place(DVA_BASE + 0x3000, 0x4000) == 0); + assert(place(DVA_BASE + 13 * IOMMU_PAGE, 0x4000) == -ERANGE); + /* + * 4 KiB carveout strictly past RAM_END (0x87fffd000) sharing a 16 KiB + * CPU page with System RAM is refused by CPU-page rounding. + */ + table[14 * 4 + 0] = 0x87ffff000ULL; + assert(place(DVA_BASE + 14 * IOMMU_PAGE, 0x1000) == -EACCES); + + /* + * Identity domain: APPLE_DART_FW_LINUX skips non-paging domains and + * apple_dart_fw_remote() returns -ENODEV on identity domains, so + * identity domains are refused. + */ + the_domain.type = IOMMU_DOMAIN_IDENTITY; + the_domain.pgsize_bitmap = 0x4000; + assert(place(0x900000000ULL, 0x4000) == -ENOENT); + assert(place(DVA_BASE + 10 * IOMMU_PAGE + 0x2000, 0x4000) == -ENOENT); + the_domain.type = IOMMU_DOMAIN_DMA; + +#ifdef HAVE_MAPS_PLACED_ROUTING + { + struct apple_rtkit_ops plain = {}; + struct apple_rtkit_ops fw_owned = { .flags = APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG }; + struct apple_rtkit_ops with_setup = { .shmem_setup = (void *)1 }; + struct apple_rtkit_ops with_setup_ep = { .shmem_setup_ep = (void *)1 }; + struct apple_rtkit r_plain = { .ops = &plain }; + struct apple_rtkit r_fw = { .ops = &fw_owned }; + struct apple_rtkit r_setup = { .ops = &with_setup }; + struct apple_rtkit r_setup_ep = { .ops = &with_setup_ep }; + + assert(apple_rtkit_maps_placed_crashlog(&r_plain)); + assert(!apple_rtkit_maps_placed_crashlog(&r_fw)); + assert(!apple_rtkit_maps_placed_crashlog(&r_setup)); + assert(!apple_rtkit_maps_placed_crashlog(&r_setup_ep)); + } +#endif + + puts("PASS crash log buffers are mapped, write-combined, only over pages that translate contiguously to DRAM outside System RAM"); + return 0; +} +''' + + +def show(ref, path): + if not ref: + return (ROOT / path).read_text() + return subprocess.run(['git', '-C', str(ROOT), 'show', f'{ref}:{path}'], check=True, + capture_output=True, text=True).stdout + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--out', type=Path, help='keep build and result files here') + parser.add_argument('--cc', default='cc') + parser.add_argument('--old-ref', help='require the driver at this revision to fail') + args = parser.parse_args() + source, dart = show(args.old_ref, DRIVER), show(args.old_ref, DART) + extra = '' + if 'int apple_dart_fw_range(' in dart: + walk = ''.join(function(dart, name) for name in + ('apple_dart_fw_phys_shareable', 'apple_dart_fw_range_page', 'apple_dart_fw_range')) + else: + walk = function(source, 'apple_rtkit_crashlog_phys') + if 'static bool apple_rtkit_maps_placed_crashlog(' in source: + extra = '#define HAVE_MAPS_PLACED_ROUTING 1\n' + function(source, 'apple_rtkit_maps_placed_crashlog') + code = PREFIX + constants(source) + walk + extra + function(source, 'apple_rtkit_crashlog_map') + MAIN + + def run(out): + out.mkdir(parents=True, exist_ok=True) + cfile, exe = out / 'crashlog-map.c', out / 'crashlog-map' + cfile.write_text(code) + subprocess.run([args.cc, '-std=gnu11', '-O1', '-g', '-Wall', '-Wextra', '-Werror', + '-Wno-unused-parameter', '-Wno-unused-function', + '-fsanitize=address,undefined', '-fno-sanitize-recover=all', + str(cfile), '-o', str(exe)], check=True) + result = subprocess.run([str(exe)], capture_output=True, text=True) + if args.old_ref: + if result.returncode == 0: + raise SystemExit(f'{args.old_ref} passed; the test does not catch the original code') + print(result.stderr, end='') + print('old revision fails as required') + return 0 + print(result.stdout + result.stderr, end='') + return result.returncode + + if args.out: + return run(args.out) + with tempfile.TemporaryDirectory(prefix='rtkit-crashlog-map-') as out: + return run(Path(out)) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/asahi/rtkit-oslog-tests.py b/tools/asahi/rtkit-oslog-tests.py index 0f1bbf7be90c4c..944e07c67b887d 100644 --- a/tools/asahi/rtkit-oslog-tests.py +++ b/tools/asahi/rtkit-oslog-tests.py @@ -74,6 +74,7 @@ def function(source, name): #define kfifo_reset(f) (*(f)=0) #define dev_dbg(...) ((void)0) #define dev_warn(...) (++warnings) +#define dev_warn_ratelimited(...) (++warnings) #define dev_err(...) (++errors) static void set_bit(unsigned n, unsigned long *b) { b[n/64] |= 1UL << (n%64); } static void bitmap_zero(unsigned long *b, unsigned n) { memset(b,0,n/8); } diff --git a/tools/asahi/rtkit-v27-late-tests.py b/tools/asahi/rtkit-v27-late-tests.py new file mode 100755 index 00000000000000..5fa65af5fbada6 --- /dev/null +++ b/tools/asahi/rtkit-v27-late-tests.py @@ -0,0 +1,283 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the firmware-27 late display stop's RTKit check and atomic idle against a fake mailbox. + +The bodies of apple_rtkit_v27_check() and apple_rtkit_v27_idle_atomic() are compiled from +drivers/soc/apple/rtkit-v27-late.inc, the RTKit constants and apple_rtkit_oslog_owed_msg() +and notification classifier from rtkit.c. The fake firmware answers the AP and IOP power-state requests and can put +system notifications or application traffic into the receive queue at any point. + +Cases: before the commit a pending message refuses (kept for the disarm); after the commit +the check leaves it in the mailbox and the stop completes; traffic during the stop's wait is +either acknowledged inline or deferred in order; unexpected management, crashlog and +application messages fail the stop; no answer still times out; a full FIFO still fails. + +Mutations: --consume-committed (the committed check consumes and refuses as before), +--fail-foreign (the stop fails on any foreign message as before). +""" +from pathlib import Path +import argparse +import re +import subprocess +import sys +import tempfile + +ap = argparse.ArgumentParser() +ap.add_argument('--out') +ap.add_argument('--consume-committed', action='store_true') +ap.add_argument('--fail-foreign', action='store_true') +args = ap.parse_args() + +root = Path(__file__).resolve().parents[2] +inc = (root / 'drivers/soc/apple/rtkit-v27-late.inc').read_text() +rtkit = (root / 'drivers/soc/apple/rtkit.c').read_text() + + +def function(src, sig): + a = src.index(sig) + a = src.rfind('\n', 0, a) + 1 + b = src.index('\n}', src.index('{', a)) + 2 + return src[a:b] + + +def scope_struct(): + a = inc.index('struct apple_rtkit_v27_scope {') + return inc[a:inc.index('};', a) + 2] + + +consts = [line for line in (root / "drivers/soc/apple/rtkit-internal.h").read_text().splitlines() + if line.startswith("#define APPLE_RTKIT_APP_ENDPOINT_START ")] +for name in ['APPLE_RTKIT_PWR_STATE_IDLE', 'APPLE_RTKIT_PWR_STATE_ON', 'APPLE_RTKIT_EP_MGMT', + 'APPLE_RTKIT_EP_CRASHLOG', 'APPLE_RTKIT_EP_SYSLOG', 'APPLE_RTKIT_EP_OSLOG', + 'APPLE_RTKIT_EP_IOREPORT', + 'APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE', 'APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK', + 'APPLE_RTKIT_MGMT_SET_AP_PWR_STATE', 'APPLE_RTKIT_MGMT_SET_AP_PWR_STATE_ACK', + 'APPLE_RTKIT_MGMT_IDLE_NOTIFY']: + m = re.search(r'\b' + name + r' = (0x[0-9a-fA-F]+|[0-9]+),', rtkit) + consts.append(f'#define {name} {m.group(1)}') +for name in ['APPLE_RTKIT_MGMT_TYPE', 'APPLE_RTKIT_MGMT_PWR_STATE', 'APPLE_RTKIT_SYSLOG_TYPE', + 'APPLE_RTKIT_SYSLOG_LOG', 'APPLE_RTKIT_OSLOG_TYPE', 'APPLE_RTKIT_OSLOG_LOG', + 'APPLE_RTKIT_IOREPORT_UNKNOWN1', 'APPLE_RTKIT_IOREPORT_UNKNOWN2']: + m = re.search(r'#define ' + name + r' (.+)', rtkit) + consts.append(f'#define {name} {m.group(1)}') + +check = function(inc, 'int apple_rtkit_v27_check(') +idle = function(inc, 'int apple_rtkit_v27_idle_atomic(') +if args.consume_committed: + old = '\tif (committed)\n\t\treturn 0;\n' + assert check.count(old) == 1 + check = check.replace(old, '') +if args.fail_foreign: + old = ('\t\t\t\t\t/* Other system messages are replayed on disarm. */\n' + '\t\t\t\t\tkfifo_put(&s->deferred, msg);\n') + assert idle.count(old) == 1 + idle = idle.replace(old, old + '\t\t\t\t\tret = -EPROTO;\n' + '\t\t\t\t\tgoto poison;\n') + +pre = r''' +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; +#define GENMASK_ULL(h, l) (((~0ULL) << (l)) & (~0ULL >> (63 - (h)))) +#define FIELD_PREP(m, v) ((((u64)(v)) << __builtin_ctzll(m)) & (m)) +#define FIELD_GET(m, v) ((((u64)(v)) & (m)) >> __builtin_ctzll(m)) +#define dma_wmb() ((void)0) +#define dma_rmb() ((void)0) +#define EXPORT_SYMBOL_GPL(x) +struct module; +struct apple_mbox_msg { u64 msg0; u32 msg1; }; +#define FIFO_N 64 +#define DECLARE_KFIFO(n, t, sz) struct { t buf[sz]; unsigned in, out; } n +#define INIT_KFIFO(f) ((f).in = (f).out = 0) +#define kfifo_is_full(f) ((f)->in - (f)->out == FIFO_N) +#define kfifo_len(f) ((f)->in - (f)->out) +#define kfifo_put(f, v) (kfifo_is_full(f) ? 0 : ((f)->buf[(f)->in++ % FIFO_N] = (v), 1)) +#define kfifo_get(f, p) ((f)->in == (f)->out ? 0 : (*(p) = (f)->buf[(f)->out++ % FIFO_N], 1)) +#define QN 256 +struct apple_mbox { + bool removing, active; + struct apple_mbox_msg rx[QN]; unsigned rx_in, rx_out; + struct apple_mbox_msg tx[QN]; unsigned tx_n; + bool recv_enabled; +}; +struct apple_rtkit { + struct apple_mbox *mbox; + bool crashed, shutting_down, strict_idle_poisoned, oslog_echo, silent; + unsigned ap_power_state, iop_power_state; + unsigned ticks, inject_at, injected; + struct apple_mbox_msg inject[8]; unsigned ninject; +}; +''' +consts_c = '\n'.join(consts) + '\n' +fake = r''' +static bool irqs_disabled(void) { return true; } +static struct apple_rtkit *cur; +static void push(struct apple_mbox *b, u32 ep, u64 msg0) +{ + b->rx[b->rx_in++ % QN] = (struct apple_mbox_msg){ .msg0 = msg0, .msg1 = ep }; +} +static void udelay(unsigned us) +{ + (void)us; + if (++cur->ticks == cur->inject_at) + for (unsigned i = 0; i < cur->ninject; i++, cur->injected++) + push(cur->mbox, cur->inject[i].msg1, cur->inject[i].msg0); +} +static bool apple_rtkit_v27_rx_drained(struct apple_rtkit *rtk) { return true; } +static void apple_mbox_set_recv_enabled(struct apple_mbox *b, bool on) { b->recv_enabled = on; } +static int apple_mbox_recv_nowait(struct apple_mbox *b, struct apple_mbox_msg *m) +{ + if (b->removing || !b->active) + return -ENODEV; + if (b->rx_in == b->rx_out) + return 0; + *m = b->rx[b->rx_out++ % QN]; + return 1; +} +/* The firmware: answers each power-state request, IOP idle followed by its notice. */ +static int apple_mbox_send_nowait(struct apple_mbox *b, struct apple_mbox_msg m) +{ + u8 type = FIELD_GET(APPLE_RTKIT_MGMT_TYPE, m.msg0); + u64 st = FIELD_GET(APPLE_RTKIT_MGMT_PWR_STATE, m.msg0); + + b->tx[b->tx_n++] = m; + if (cur->silent || m.msg1 != APPLE_RTKIT_EP_MGMT) + return 0; + if (type == APPLE_RTKIT_MGMT_SET_AP_PWR_STATE) + push(b, 0, FIELD_PREP(APPLE_RTKIT_MGMT_TYPE, APPLE_RTKIT_MGMT_SET_AP_PWR_STATE_ACK) | st); + if (type == APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE) { + push(b, 0, FIELD_PREP(APPLE_RTKIT_MGMT_TYPE, APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK) | st); + push(b, 0, FIELD_PREP(APPLE_RTKIT_MGMT_TYPE, APPLE_RTKIT_MGMT_IDLE_NOTIFY)); + } + return 0; +} +''' +owed = function(rtkit, 'static bool apple_rtkit_oslog_owed_msg(') + '\n' + \ + function(rtkit, 'static bool apple_rtkit_notification_msg(') + +main = r''' +static struct apple_mbox mb; +static struct apple_rtkit rk; +static struct apple_rtkit_v27_scope sc; +static void reset(void) +{ + memset(&mb, 0, sizeof(mb)); memset(&rk, 0, sizeof(rk)); memset(&sc, 0, sizeof(sc)); + mb.active = mb.recv_enabled = true; + rk.mbox = &mb; rk.ap_power_state = rk.iop_power_state = APPLE_RTKIT_PWR_STATE_ON; + sc.rtk = &rk; sc.held = true; INIT_KFIFO(sc.deferred); + cur = &rk; +} +#define SYSLOG_LINE (FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG) | 0x12) +#define APP_MSG 0x123456789aULL +static void stopped_ok(void) +{ + assert(sc.stopped && !sc.failed && !rk.strict_idle_poisoned && !mb.recv_enabled); + assert(rk.ap_power_state == APPLE_RTKIT_PWR_STATE_IDLE); + assert(rk.iop_power_state == APPLE_RTKIT_PWR_STATE_IDLE); +} +int main(void) +{ + struct apple_mbox_msg m; + + /* Before the commit: a pending log line refuses the sleep and is kept for the disarm. */ + reset(); push(&mb, APPLE_RTKIT_EP_SYSLOG, SYSLOG_LINE); + assert(apple_rtkit_v27_check(&sc, false) == -EAGAIN); + assert(kfifo_len(&sc.deferred) == 1 && mb.rx_in == mb.rx_out); + reset(); + assert(apple_rtkit_v27_check(&sc, false) == 0 && apple_rtkit_v27_check(&sc, true) == 0); + + /* After the commit: the log line stays in the mailbox and the stop answers it. */ + reset(); push(&mb, APPLE_RTKIT_EP_SYSLOG, SYSLOG_LINE); + assert(apple_rtkit_v27_check(&sc, true) == 0); + assert(kfifo_len(&sc.deferred) == 0 && mb.rx_in != mb.rx_out); + assert(apple_rtkit_v27_idle_atomic(&sc) == 0); + stopped_ok(); + assert(!kfifo_get(&sc.deferred, &m)); + { + unsigned echoes = 0; + for (unsigned i = 0; i < mb.tx_n; i++) + echoes += mb.tx[i].msg1 == APPLE_RTKIT_EP_SYSLOG && + mb.tx[i].msg0 == SYSLOG_LINE; + assert(echoes == 1); + } + + /* Other system messages are retained in FIFO order. */ + reset(); rk.inject_at = 1; rk.ninject = 2; + rk.inject[0] = (struct apple_mbox_msg){ .msg0 = 0, .msg1 = APPLE_RTKIT_EP_SYSLOG }; + rk.inject[1] = (struct apple_mbox_msg){ .msg0 = 0, .msg1 = APPLE_RTKIT_EP_IOREPORT }; + assert(apple_rtkit_v27_idle_atomic(&sc) == 0); + stopped_ok(); assert(rk.injected == 2); + assert(kfifo_get(&sc.deferred, &m) && m.msg1 == APPLE_RTKIT_EP_SYSLOG); + assert(kfifo_get(&sc.deferred, &m) && m.msg1 == APPLE_RTKIT_EP_IOREPORT); + assert(!kfifo_get(&sc.deferred, &m)); + + /* Application RPCs invalidate the stop. */ + reset(); push(&mb, APPLE_RTKIT_APP_ENDPOINT_START, APP_MSG); + assert(apple_rtkit_v27_idle_atomic(&sc) == -EPROTO); + assert(sc.failed && !sc.stopped && rk.strict_idle_poisoned); + + /* An owed OSLOG counter is still echoed, not deferred. */ + reset(); rk.oslog_echo = true; + push(&mb, APPLE_RTKIT_EP_OSLOG, FIELD_PREP(APPLE_RTKIT_OSLOG_TYPE, APPLE_RTKIT_OSLOG_LOG) | 7); + assert(apple_rtkit_v27_idle_atomic(&sc) == 0); + stopped_ok(); assert(kfifo_len(&sc.deferred) == 0); + { + bool echoed = false; + for (unsigned i = 0; i < mb.tx_n; i++) + echoed |= mb.tx[i].msg1 == APPLE_RTKIT_EP_OSLOG; + assert(echoed); + } + + /* A management message off the handshake, or a crashlog: still no stop. */ + reset(); push(&mb, APPLE_RTKIT_EP_MGMT, + FIELD_PREP(APPLE_RTKIT_MGMT_TYPE, APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK) | + APPLE_RTKIT_PWR_STATE_ON); + assert(apple_rtkit_v27_idle_atomic(&sc) == -EPROTO); + assert(sc.failed && !sc.stopped && rk.strict_idle_poisoned && kfifo_len(&sc.deferred) == 1); + reset(); push(&mb, APPLE_RTKIT_EP_CRASHLOG, 0x1ULL << 52); + assert(apple_rtkit_v27_idle_atomic(&sc) == -EPROTO); + assert(sc.failed && !sc.stopped && rk.strict_idle_poisoned); + + /* No answer: the 100 ms budget still ends in a failure. */ + reset(); rk.silent = true; + assert(apple_rtkit_v27_idle_atomic(&sc) == -ETIMEDOUT); + assert(sc.failed && !sc.stopped && rk.strict_idle_poisoned && mb.recv_enabled); + + /* A full FIFO: nothing more is consumed, the stop fails. */ + reset(); + for (unsigned i = 0; i < FIFO_N; i++) + push(&mb, APPLE_RTKIT_EP_SYSLOG, 0); + assert(apple_rtkit_v27_idle_atomic(&sc) == -ENOBUFS); + assert(sc.failed && !sc.stopped && kfifo_is_full(&sc.deferred)); + assert(apple_rtkit_v27_check(&sc, true) == -EBUSY); + return 0; +} +''' + +code = pre + consts_c + scope_struct() + '\n' + fake + owed + '\n' + check + '\n' + idle + '\n' + main + + +def build_and_run(out): + out.mkdir(parents=True, exist_ok=True) + c = out / 'rtkit-v27-late.c' + c.write_text(code) + exe = out / 'rtkit-v27-late' + subprocess.run(['clang', '-std=gnu11', '-Wall', '-Werror', '-Wno-unused-function', + '-fsanitize=address,undefined', str(c), '-o', str(exe)], check=True) + return subprocess.run([str(exe)]).returncode + + +if args.out: + rc = build_and_run(Path(args.out)) +else: + with tempfile.TemporaryDirectory() as t: + rc = build_and_run(Path(t)) +if rc: + sys.exit(1) +print('PASS rtkit v27 late stop: committed check leaves a message to the stop, ' + 'system traffic deferred in order, notification and OSLOG echoes, ' + 'MGMT/crashlog/application/timeout/full FIFO fail') diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290e..170f2ee9abc4d4 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -58,6 +58,7 @@ def mutations(flag, names, base, expect=KILL): # test file -> [(arguments, expectation)]. '{out}' is a fresh directory. ASAHI_TESTS = { + 'aurora-wake-output-tests.py': [(out(), PASS)], 'dcpext26-crossbar-union-tests.py': [([], PASS), (['--drop-native26'], KILL), (['--drop-t8132'], KILL)], 'dcpext26-suspend-route-tests.py': [([], PASS), (['--native-parks'], KILL), (['--drop-h17p-park'], KILL)], 'j613-mux-order-tests.py': [([], PASS), (['--negative-control'], KILL), @@ -66,7 +67,14 @@ def mutations(flag, names, base, expect=KILL): 'display-sleep-merge-tests.py': [(out(), PASS)], 'dcpext26-slot-unregister-tests.py': [(out(), PASS)], 'dcpext26-budget-tests.py': [([], PASS)], + 'mcc-boot-dma-tests.py': [([], PASS), (['--accept-unresolved'], KILL), (['--ignore-detached-supplier'], KILL), + (['--final-skips-unresolved'], KILL), + (['--detach-retired-only'], KILL), + (['--resume-after-detach'], KILL)], + 'dcp-peer-shown-tests.py': [([], PASS), (['--always-shown'], KILL), (['--owner-only'], KILL)], 'dcpext26-queue-tests.py': [([], PASS), (['--drop-v27-close'], KILL)], + 'rtkit-v27-late-tests.py': [(out(), PASS), (out() + ['--consume-committed'], KILL), + (out() + ['--fail-foreign'], KILL)], 'dcpext26-retrain-tests.py': [([], PASS), (['--negative-control'], KILL)], 'dcpext26-lifecycle-tests.py': [([], PASS)], 'dcpext26-modeset-tests.py': [([], PASS)], @@ -79,12 +87,19 @@ def mutations(flag, names, base, expect=KILL): 'dcpext26-startup-tests.py': [([], PASS)], 'iomfb-startup-tests.py': [([], PASS)], + 'atc-dp-drive-tests.py': [([], PASS)] + mutations( + '--mutation', ['eopnotsupp', 'accept-with-rate', 'refuse-drive'], []), 'dcp-v27-dptx-layout-tests.py': [([], PASS)] + mutations( - '--mutation', ['ignore-advertisement', 'ignore-pinned', 'ignore-dcpext'], []), + '--mutation', ['ignore-advertisement', 'ignore-pinned', 'ignore-dcpext', + 'ignore-typec-routes'], []), + 'dptx-set-active-lane-count-tests.py': [([], PASS)] + mutations( + '--mutation', ['drop-fixed-phy', 'skip-all-unexpected'], []), 'dcpext26-wire-tests.py': [([], PASS)], 'pmp-native26-tests.py': [([], PASS)], + 'm3-packet-completion-tests.py': [(out(), PASS), (out() + ['--mutate'], KILL)], + 'm3-recovery-tests.py': [(out(), PASS), (out() + ['--mutate'], KILL)], 'm3-stamp-admission-tests.py': [(out(), PASS), (out() + ['--mutation', 'live-reseed'], KILL)], 'hardware-defaults-tests.py': [([], PASS)], @@ -104,6 +119,10 @@ def mutations(flag, names, base, expect=KILL): 'aop-als-channel-tests.py': [([], PASS)], 'aop-als-calibration-tests.py': [([], PASS)], 'aop-bootargs-tests.py': [([], PASS)], + # 24dc422773c9 registers another child device for each repeated service announcement. + 'aop-service-tests.py': [([], PASS), + (['--old-ref', '24dc422773c9beb9e99ee9e1ab713e9d6abb1e7b'], PASS)] + + mutations('--mutation', ('no-work-release', 'no-slot-release', 'no-register-release'), [], PASS), 'mtp-pm-tests.py': [(out(), PASS), (out() + ['--old-transport', '4db3a5a22c43'], PASS), (out() + ['--old-mouse', '62d2045d8928'], PASS)], @@ -113,6 +132,13 @@ def mutations(flag, names, base, expect=KILL): 'binding-lifetime-tests.py': [(out(), PASS)] + mutations('--mutation', ('no-close', 'no-join'), out()), 'apple-pwm-pm-tests.py': [([], PASS), (['--negative-control'], PASS)], + # 70a00e583b032 underflows get_timeleft() on cur > bite and ignores the reconfig reg. + 'apple-wdt-tests.py': [(out(), PASS), + (out() + ['--old-ref', '70a00e583b032'], KILL)] + + mutations('--mutation', ('ignore-sleep-handoff', 'no-bark-in-start', 'no-status-clear', + 'reconfig-before-bark', 'register-after-arm', + 'hwrunning-after-arm', 'no-wd1-adopt', + 'no-t6050-wake-restore'), out()), 'apple-m4-pmu-tests.py': [([], PASS)] + mutations('--mutation', ('m1-layout', 'cycles-anywhere', 'expose-8-9', 'flags-in-event'), []), 'apple-dart-dapf-tests.py': [(out(), PASS)] @@ -121,11 +147,11 @@ def mutations(flag, names, base, expect=KILL): 'apple-dart-fw-harness-tests.py': [([], PASS)], 'apple-dart-range-tests.py': [([], PASS)], # 551b937502b5 gives up on a stalled J700 display invalidate after 2 ms; the - # every-handoff mutation waits it out on every handed-off DART, not just the display's. + # every-dart mutation waits it out on every locked DART, not just the display's. 'apple-dart-tlb-stall-tests.py': [(['--dtc', '{dtc}'], PASS), (['--ref', '551b937502b54b0d1eb250bba6d9442b3672a0fb'], KILL), - (['--dtc', '{dtc}', '--mutation', 'every-handoff'], + (['--dtc', '{dtc}', '--mutation', 'every-dart'], KILL)], 'apple-router-sleep-tests.py': [(out('--output'), PASS)], 'asahi-stats-raw-tests.py': [([], PASS)], @@ -137,6 +163,7 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('round-up', 'cpu-unaligned', 'seg-cpu-unaligned', 'seg-any-size', 'ref-index-upper', 'frame-width-unchecked'), out()), 'avd-codec-tail-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], + 'bcm4377-completion-tests.py': [([], PASS)], # The old revision is the one before the J493 hardware-table ID match. 'bcm4377-id-tests.py': [(out() + ['--old-ref', '87ddae1397f6f70817cb57df76477a86bdf96424'], PASS)], # These mutations are caught inside the test, which then exits 0. @@ -157,19 +184,27 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('narrow-stream', 'ignore-aperture', 'revision-wide'), out('--output')), 'brcmf-recovery-tests.py': [(out(), PASS)] + mutations('--mutation', ('stall-limit', 'trap-flag', 'console', 'line-start', 'once', - 'rate-limit', 'stall-reset', 'ring-full'), out()), + 'rate-limit', 'stall-reset', 'ring-full', 'trap-bound'), out()), 'brcmf-roam-tests.py': [(out(), PASS)], + 'brcmf-shared-tcm-tests.py': [(out(), PASS)] + + mutations('--mutation', ('shared', 'htod-mb', 'dtoh-mb', 'ring-info', 'ring-mem', 'ring-idx', + 'flowring-idx', 'dma-counts', 'rptr-depth', 'wptr-depth', + 'console-desc', 'console-none', + 'console-buf', 'console-widx', 'console-reinit'), out()), 'brcmf-sae-vendor-tests.py': [(out(), PASS)] + [(out() + ['--ref', '9260e1f021e075713931f3c23c0a5fa1da936b0b'], KILL)], 'brcmf-suspend-tests.py': [(out(), PASS)] + mutations('--mutation', ('country-gate', 'queue-reasons', 'worker-gate', - 'resume-order', 'tx-drain', 'lpas-resume'), out()), + 'resume-order', 'tx-drain', 'lpas-resume', + 'wowl-s2idle-only'), out()), 'brcmf-wowl-filter-tests.py': [(out(), PASS)] + mutations('--mutation', ('base-order', 'mask-last', 'totsize', 'no-track'), out()), 'brcmfmac-scan-timeout-tests.py': [(out('--output'), PASS)], 'brcmfmac-sleep-lifetime-tests.py': [([], PASS)], 'cio-native-tests.py': [(out('--output'), PASS)], 'centauri-wifi-pm-tests.py': [(out(), PASS), (out() + ['--negative-controls'], PASS)], + 'centauri-wifi-avoid-tests.py': [([], PASS), (['--negative-control'], KILL)], + 'centauri-scan-tests.py': [(out(), PASS), (out() + ['--negative-controls'], PASS)], 'centauri-bt-arena-tests.py': [(out(), PASS), (out() + ['--negative-controls'], PASS)], 'centauri-recovery-tests.py': [(out(), PASS), (out() + ['--negative-controls'], PASS)], 'centauri-physical-recovery-tests.py': [(out(), PASS)] @@ -177,6 +212,25 @@ def mutations(flag, names, base, expect=KILL): 'missing-control-firmware', 'missing-control-descriptor', 'missing-owner-ipc', 'missing-owner-firmware', 'missing-owner-descriptor', 'missing-owner-arena'), out()), + # A DP audio PCM open reads a replaced service's successor; a gone service opens unplugged. + 'dcpaud-open-fallback-tests.py': [([], PASS)] + mutations('--mutation', ('no-retry', 'wait-any', 'gone-fails', 'keep-cookie', 'mask-all'), []), + # a7638d51880c, the parent of the fix, ran pm_runtime_force_suspend in the late + # slot, so the dp-audio domain dropped under a running DCP. + 'dcpaud-sleep-hold-tests.py': [(out(), PASS)] + + mutations('--mutation', ('bound-only', 'stopped-holds', 'invert-runs', 'no-lock', + 'leak-device', 'leak-node', 'ignore-dcp'), out()) + + [(out() + ['--ref', 'a7638d51880ce077cfb3edfa7ff638de2be74c85'], KILL)], + # A DCP whose firmware runs through the sleep holds its DP PHYs' domains. + 'dcp-sleep-phy-hold-tests.py': [([], PASS)] + + mutations('--mutation', ('no-route', 'no-own-phy', 'class-device', 'no-err-check'), []), + # An HDMI display kept through a sleep but unplugged during it is released on resume. + 'dcp-hdmi-sleep-unplug-tests.py': [([], PASS)] + + mutations('--mutation', ('keep-native', 'gpio-error', 'ignore-borrowed', 'no-fabric', + 'no-fabric-lock', 'no-resume-check'), []), + # A fixed (non-Type-C) output takes its DP AV service again after a sleep. + 'dpavserv-admission-tests.py': [([], PASS)] + + mutations('--mutation', ('old-cable-wait', 'ignore-generation', 'ignore-cable', + 'ignore-quiescing'), []), 'dcp-bw-scratch-window-tests.py': [([], PASS)] + mutations('--mutation', ('old-check', 'start-only'), []), 'clpc-gpu-demand-tests.py': [([], PASS)], 'clpc-high-power-cleanup-tests.py': [(out(), PASS), @@ -206,6 +260,9 @@ def mutations(flag, names, base, expect=KILL): 'g15-retention-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-stats-drain-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-zero-words-tests.py': [([], PASS), (['--mutations'], PASS)], + 'g18-client-handoff-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], + 'g18-job-error-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], + 'm5-client-handoff-tests.py': [([], PASS), (['--mutations'], PASS)], 'g17-telemetry-integration-tests.py': [(out(), PASS)] + mutations('--mutation', ('fields', 'range', 'timestamp', 'age', 'delivery', 'quarantine', 'epoch', 'cutoff', 'whole-batch', 'legacy-format', 'read-drain'), out()), @@ -214,10 +271,11 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('no-held-free', 'no-held-sibling', 'no-held-refusal', 'no-held-pick', 'no-held-spare', 'no-held-other', 'no-held-cancel', 'no-held-killed', 'no-held-used', 'no-held-wake', 'wake-on-every-clear', 'no-held-stop', - 'held-blocks-owner', 'hold-ignores-release', 'hold-ignores-work', + 'held-blocks-owner', 'released-owner-retakes', 'hold-ignores-release', 'hold-ignores-work', 'close-unheld', 'hold-after-release', 'put-back-own-work', 'sync-skips-lent', 'lent-close-unheld', 'parked-stays-held', - 'sync-clobbers', 'sync-no-wake'), []), + 'sync-clobbers', 'sync-no-wake', 'close-twice', 'latch-before-close', + 'spare-detach-reassigns'), []), 'g17-capacity-backoff-tests.py': [([], PASS)], 'g17-capacity-fault-tests.py': [([], PASS)], 'g17-compute-constructor-tests.py': [([], PASS)], @@ -225,24 +283,107 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('own-finished', 'no-retire-glue', 'retire-unchecked', 'no-expiry', 'no-step-past', 'pop-owed', 'head-includes-owed', 'held-stamped-pops', 'crossed-behind-owed', 'owed-classified', 'rebind-check-entry', - 'timeout-fails-retired', 'no-owed-poll'), []), + 'timeout-fails-retired', 'no-owed-poll', 'count-recordless', + 'count-owed-twice'), []), 'g17-compute-deadline-tests.py': [([], PASS)], 'g17-compute-growth-deadline-tests.py': [([], PASS)], + 'g17-compute-retired-tests.py': [([], PASS)] + + mutations('--mutation', ('queue-under-lock', 'binding-under-lock', 'drain-under-lock', + 'drain-local-on-eagain', 'finish-stops-at-error', + 'early-return-skips-finish', 'overwrite-full'), []), 'g17-kill-route-tests.py': [([], PASS)] + mutations('--mutation', ('no-executed-route', 'no-executed-input', 'kill-twice', 'executed-on-m5', - 'unsafe-wait', 'owed-blocks-kill', 'open-owed-skipped'), []), + 'unsafe-wait', 'guilty-waits-delay', 'no-guilty-input', 'owed-blocks-kill', + 'open-owed-skipped', 'post-latch-swallowed', 'reserve-fails-pass'), []), + 'g17-m5-direct-compute-tests.py': [([], PASS)] + + mutations('--mutation', ('no-pre-recovery-drain', 'direct-debits-published', + 'scope-allows-reserve'), []), + 'g17-m5-multiqueue-contention-tests.py': [([], PASS)] + + mutations('--mutation', ('unlocked-claim-outer', 'raw-compute-scope', + 'raw-render-scope', 'unlocked-scope-drop', + 'drop-direct-claim-on-fallback', 'pin-single-die'), []), + 'g17-m5-idle-housekeeping-tests.py': [([], PASS)] + + mutations('--mutation', ('idle-forces-housekeeping', 'no-deferred-timer', + 'hardcode-in-flight-true', 'skip-cadence-expiry'), []), + 'g17-m5-event-placement-tests.py': [([], PASS)] + + mutations('--mutation', ('percpu-always', 'unbound-always', 'aim-local', + 'record-never', 'not-reclaim', 'split-flag'), []), + 'g17-m5-render-fast-done-tests.py': [([], PASS)] + + mutations('--mutation', ('hold-m5-outer-across-doorbell', + 'hold-render-lock-across-doorbell', + 'skip-pending-error-fallback', + 'single-slot-bailout', + 'skip-epoch-check', + 'unconditional-changed-notify', + 'skip-generation-bump'), []), + 'g17-m5-cross-qid-direct-tests.py': [([], PASS)] + + mutations('--mutation', ('no-chain-dedup', + 'coalesce-failed-leaf', + 'hint-blind-spot', + 'skip-epoch-check', + 'skip-recovery-recheck', + 'lock-per-leaf', + 'hold-m5-outer-compute-host', + 'same-qid-emits-barrier', + 'lock-has-published-epoch', + 'lock-same-vm'), []), + 'g17-m5-sibling-compute-tests.py': [([], PASS)] + + mutations('--mutation', ('fixed-object-ids', 'primary-before-sibling', + 'exit-ack-stops-first', 'direct-allows-multi-barrier', + 'direct-blocks-sibling', 'direct-locks-sibling-when-idle', + 'direct-skips-multi', 'same-qid-pipelined'), []), + 'g17-m5-sibling-gate-tests.py': [([], PASS)] + + mutations('--mutation', ('sources-fan-out', 'select-sources-anywhere', 'tiny-fans-out', + 'no-sustain-run', 'short-keeps-run', 'direct-ignores-gate', + 'direct-can-add-ungated', 'wants-ignores-sustained', + 'select-ignores-sustained', 'cell-drops-sustained', + 'fans-out-locks-first', 'keep-run-across-owners', 'overlap-at-one', + 'direct-ignores-in-flight', 'select-ignores-in-flight', + 'wants-ignores-in-flight', 'detour-at-one'), []), + 'g17-m5-sibling-rearm-tests.py': [([], PASS)] + + mutations('--mutation', ('old-headroom', 'no-vacant-sibling', 'no-foreign-sibling', + 'steal-shareable', 'steal-unowned', 'ignore-rearm-reservation', + 'ignore-releasing', 'parallel-give-back', 'foreign-before-fresh', + 'rearm-binds-primary', 'try-add-ignores-waiters', 'try-add-skips-rearm', + 'rearm-any-index', 'primary-own-give-back'), []), + 'g17-compute-multi-channel-feature-tests.py': [([], PASS)] + + mutations('--mutation', ('always-multi', 'never-multi', 'not-reported', 'per-board-gate', + 'colliding-bit', 'unsynced-binding', 'forms-gate', + 'max-channels', 'multi-channel-max'), []), + 'g17-m5-effort-tests.py': [([], PASS)] + + mutations('--mutation', ('m5-ignores-bound',), []), + 'g17-highpri-sched-wq-tests.py': [([], PASS)] + + mutations('--mutation', ('drop-highpri', 'drop-reclaim', 'drop-highpri-flag'), []), 'g17-firmware-selection-tests.py': [([], PASS)], + 'g17-freelist-lease-direct-tests.py': [([], PASS)] + + mutations('--mutation', ('reject-preparing-complete', 'snapshot-rollback', + 'drop-pending-flush', 'drop-doorbell-loss'), []), 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], 'g17-object-fence-tests.py': [([], PASS)] + mutations('--mutation', ('overrun-work-states', 'unseen-strict', 'retain-not-sticky', - 'node-unmarked', 'no-release'), []), + 'node-unmarked', 'no-release', 'm5-cached-nodes', + 'm5-cached-descriptors', 'cached-queue-records', + 'uncached-g17p-nodes'), []), 'g17-owner-release-order-tests.py': [([], PASS)], 'g17-pool-release-tests.py': [([], PASS)], # no-drain-release is the old rule: only a lease ends a slot's quarantine. 'g17-quarantine-drain-tests.py': [([], PASS)] + mutations('--mutation', ('no-drain-release', 'without-witness', 'ignore-leases', 'no-last-lease', 'witness-covers-later-failure', 'unquarantined-drain'), []), + 'g17-render-return-observe-tests.py': [([], PASS)] + + mutations('--mutation', ('rescan-owed', 'observe-all-slots', 'observe-ignores-gate', + 'rescan-in-loop-bail', 'rescan-is-fallback', 'missed-dropped', + 'observe-in-recovery', 'collector-blocks', 'finish-under-mutex', + 'no-pass-requested', 'rescan-no-poll', 'worker-rescan-slow-path', + 'owed-slow-path'), []), + 'g17-rescan-poll-tests.py': [([], PASS)] + + mutations('--mutation', ('starve-fast-pending', 'starve-slow-pending', 'jiffy-poll', + 'skip-backpressure-poll', 'skip-sleep-cancel', + 'skip-shutdown-disable'), []), + 'g17-render-direct-recovery-tests.py': [([], PASS)] + + mutations('--mutation', ('recovery-state-eio', 'drop-generation-check', + 'wrong-j813-pipe'), []), 'g17-resource-tests.py': [([], PASS)], 'g17-shared-pool-tests.py': [([], PASS)], 'g17-t6041-initdata-tests.py': [([], PASS)], @@ -251,6 +392,14 @@ def mutations(flag, names, base, expect=KILL): 'isp-preview-flow-tests.py': [([], PASS)], 'isp-preview-tests.py': [([], PASS)], 'isp-tests.py': [(['--suite', suite] + out(), PASS) for suite in ['session', 'buffers', 'receive', 'returns', 'queue']] + [(['--suite', suite, '--control', control] + out(), KILL) for suite, controls in [('session', ['send', 'overwrite', 'stop', 'reset']), ('buffers', ['rollback']), ('receive', ['drain']), ('returns', ['address', 'pool', 'duplicate', 'snapshot']), ('queue', ['queue-error'])] for control in controls], + 'm5-hotspot-fans-dt-tests.py': [(out('--output') + ['--dtc', '{dtc}'], PASS), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-fans'], KILL), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-siblings'], KILL), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-hotspot'], KILL), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-trip'], KILL), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-settable'], KILL), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-provider-check'], KILL), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-budget-release-pending'], KILL)], 'mt7932-association-events-tests.py': [(out(), PASS)], 'mt7932-connect-result-tests.py': [(out('--output'), PASS)], 'mt7932-owe-retry-tests.py': [(out(), PASS)], @@ -279,7 +428,7 @@ def mutations(flag, names, base, expect=KILL): 'pmu-rtc-tests.py': [(out(), PASS)] + mutations('--mutation', ('ack-clobber', 'arm-ack', 'offset-seconds', 'offset-sign', 'event-bit', 'wrong-control', - 'maverick-event', 'stowe-offset', 'baku-limit', + 'maverick-event', 'stowe-offset', 'reg-base', 'baku-limit', 'set-no-round', 'set-negative'), out()), 'perf-mmap-alias-lifecycle-tests.py': [([], PASS)], 'qspi-nvram-tests.py': [(out('--output'), PASS)], @@ -287,11 +436,20 @@ def mutations(flag, names, base, expect=KILL): 'radio-sleep-fence-tests.py': [([], PASS)], 'radio-sleep-power-tests.py': [([], PASS)], 'radio-sleep-snapshot-tests.py': [([], PASS)], + # cacf35543b4d serves endpoint 7 for every co-processor. + 'rtkit-coreanalytics-tests.py': [(out(), PASS), + (out() + ['--old-ref', 'cacf35543b4d534fccef3033bd2ddbb415a325b2'], PASS)], 'rtkit-crashlog-tests.py': [(out(), PASS)] + mutations('--mutation', ('buffer-header', 'section-header', 'section-size', 'footer-room', 'mailbox-minimum', 'version-string', 'message-string'), out()), + # cacf35543b4d steps from an unaligned crash log buffer by the page size and maps it cacheable, unchecked. + 'rtkit-crashlog-map-tests.py': [(out(), PASS), + (out() + ['--old-ref', 'cacf35543b4d534fccef3033bd2ddbb415a325b2'], PASS)], 'rtkit-oslog-tests.py': [(out(), PASS)] + mutations('--mutate', ('admission', 'channel', 'counter', 'reset', 'buffer'), out()), + 'rtkit-adopted-session-tests.py': [(out(), PASS)] + + mutations('--mutation', ('no-management', 'any-system', 'any-version', + 'ignore-ops-version', 'any-buffer-endpoint'), out()), 'rtkit-retained-tests.py': [(out(), PASS)], 't6030-clock-tests.py': [(out(), PASS)], 't6030-display-admission-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], @@ -304,6 +462,7 @@ def mutations(flag, names, base, expect=KILL): 't6040-calibration-tests.py': [([], PASS)], 't604x-cpu-order-tests.py': [(out('--output') + ['--dtc', '{dtc}'], PASS)], 't6050-combo-join-tests.py': [([], PASS)], + 't8132-display-gate-tests.py': [([], PASS)], 't8132-usb4-policy-tests.py': [(out('--output') + ['--dtc', '{dtc}'], PASS)], 'tb-cio-sleep-tests.py': [(out('--output'), PASS)], 'tb-dock-pm-tests.py': [(out('--output'), PASS)], @@ -322,6 +481,9 @@ def mutations(flag, names, base, expect=KILL): # Production G17 decoder vectors also build directly with rustc --test. ASAHI_RUST += ['g17-telemetry-tests.rs', 'legacy-frequency-tests.rs'] ASAHI_RUST.append('m3-firmware-tests.rs') +# G14 firmware 27.2 queue, event and recovery records (its KUnit suite, run on the host). +ASAHI_RUST.append('g14-v27-2-abi-tests.rs') +ASAHI_RUST.append('pmp-alloc-tests.rs') # Python that runs on the host but imports its neighbours, so it keeps the # script directory on sys.path (-E -s instead of -I). @@ -336,6 +498,8 @@ def mutations(flag, names, base, expect=KILL): # recovery code built against host boundaries. ('ave-host', AVE_TESTS, ['python3', '-I', '-B', 'run.py', '--build', '{out}']), ('ave-recovery', AVE_TESTS, ['python3', '-I', '-B', 'run-recovery.py']), + ('ave-input', AVE_TESTS, ['python3', '-I', '-B', 'run-input.py']), + ('ave-ipc', AVE_TESTS, ['python3', '-I', '-B', 'run-ipc.py']), ] # tools/testing/selftests/drivers/apple: the host-runnable harnesses build the diff --git a/tools/asahi/sep-suspend-errors-tests.py b/tools/asahi/sep-suspend-errors-tests.py index 2ae69ec2c32fcf..a6f28119dab5ea 100644 --- a/tools/asahi/sep-suspend-errors-tests.py +++ b/tools/asahi/sep-suspend-errors-tests.py @@ -104,6 +104,11 @@ def replace_once(source, before, after): typedef int64_t s64; typedef long long ktime_t; #define BIT(n) (1u << (n)) #define SEP_PS_DEV_DISABLE BIT(10) +#define GENMASK(h, l) ((~0u << (l)) & (~0u >> (31 - (h)))) +#define FIELD_GET(m, v) (((v) & (m)) / ((m) & -(m))) +/* The enclave's power word while it runs (target and actual 0xf), and gated without DEV_DISABLE */ +#define SEP_PS_RUNNING 0xffu +#define SEP_PS_ACTUAL_OFF 0x0fu #define USEC_PER_MSEC 1000 #define NSEC_PER_USEC 1000 #define READ_ONCE(x) (x) @@ -139,6 +144,7 @@ def replace_once(source, before, after): static struct apple_mbox mbox; static int apple_sleep_coprocs_lock; static void *apple_sleep; +static bool apple_sleep_external_commit; static struct { struct device *dev; int (*stop)(void *); void *data; } apple_sleep_enclave; @@ -148,7 +154,7 @@ def replace_once(source, before, after): static int gate_after, reads, put_refs, maps, unmaps, lookups, prepares, restores; static int prepare_error, send_error, bulk_error, one_error, sends, closes; static int mailbox_reads, message_reads, forwarded, lock_depth; -static int resource_bytes, close_gate, early_gate; +static int resource_bytes, close_gate, early_gate, actual_gate; static bool message_in_lock, matched_read; static struct apple_mbox_msg queue[4]; static unsigned queued, consumed; @@ -230,7 +236,9 @@ def replace_once(source, before, after): } static u32 readl(void *p) { // PMGR is the sole permitted query after the matched reply/receive close. - return early_gate || (closes && close_gate) ? SEP_PS_DEV_DISABLE : 0; + if (early_gate || (closes && close_gate)) + return SEP_PS_DEV_DISABLE; + return closes && actual_gate ? SEP_PS_ACTUAL_OFF : SEP_PS_RUNNING; } static jmp_buf fatal_env; static bool fatal_armed; @@ -251,13 +259,13 @@ def replace_once(source, before, after): memset(&hw, 0, sizeof(hw)); mbox = (struct apple_mbox){ .regs = &hw, .hw = &hw, .rx = foreign_rx, .cookie = &device }; config_enabled = hyp = sep_pm_suspending = dart_present = dart_ready = map_ok = true; - firmware = tx_ready = true; apple_sleep = &device; + firmware = tx_ready = true; apple_sleep = &device; apple_sleep_external_commit = false; real_wake = pending_wake = late_wake = sleep_refuse_before_send = false; domain_error = property_error = address_error = read_error = gate_after = reads = 0; put_refs = maps = unmaps = lookups = prepares = restores = sends = closes = 0; prepare_error = send_error = bulk_error = one_error = 0; mailbox_reads = message_reads = forwarded = lock_depth = 0; - resource_bytes = 4; close_gate = 1; early_gate = 0; read_error_after = 1; + resource_bytes = 4; close_gate = 1; early_gate = 0; actual_gate = 0; read_error_after = 1; queued = consumed = 0; message_in_lock = matched_read = false; now = 0; fatal_armed = false; fatal_message[0] = 0; sep_pm_told = yes; } @@ -276,6 +284,7 @@ def replace_once(source, before, after): case 19: apple_sleep_enclave.dev = value ? &device : NULL; break; case 20: sep_pm_commit.sent = value; break; case 21: firmware = value; break; case 22: sep_pm_told = value ? yes : NULL; break; + case 23: apple_sleep_external_commit = value; break; } } int counter(int which) { @@ -343,6 +352,14 @@ def replace_once(source, before, after): assert(sep_pm_commit.registered); assert(sep_pm_commit_finish(&device) == 0); assert(put_refs == 1 && unmaps == 1 && !apple_sleep_enclave.dev); assert(sep_pm_commit_finish(&device) == -ENOENT); + // An external EL2 sleep driver (T6041) advertises commit-stop without apple_sleep. + fixture(); apple_sleep = NULL; apple_sleep_external_commit = true; + assert(apple_sleep_commit_stops_coprocs()); + assert(stage() == 0); + assert(sep_pm_commit_finish(&device) == 0); + assert(put_refs == 1 && unmaps == 1 && !apple_sleep_enclave.dev); + firmware = false; + assert(!apple_sleep_commit_stops_coprocs()); } static void test_unsent(void) { for (int scenario = 0; scenario < 7; ++scenario) { @@ -387,6 +404,10 @@ def replace_once(source, before, after): fixture(); assert(stage() == 0); reply(0); close_gate = 0; expect_stop_fatal("did not gate after send: -110"); assert(closes == 1 && sep_pm_commit.gate_valid && sep_pm_commit.gate_ret == -ETIMEDOUT); + /* An enclave that gates without ever setting DEV_DISABLE (M1): its actual state at 0. */ + fixture(); assert(stage() == 0); reply(0); close_gate = 0; actual_gate = 1; + assert(sep_pm_commit_stop(&sep_pm_commit) == 0); + assert(closes == 1 && sep_pm_commit.gate_valid && !sep_pm_commit.gate_ret); fixture(); assert(stage() == 0); reply(0); assert(sep_pm_commit_stop(&sep_pm_commit) == 0); fatal_armed = true; @@ -446,7 +467,7 @@ def replace_once(source, before, after): #![allow(dead_code, unused_imports, unused_variables)] use std::cell::{Cell, RefCell, RefMut}; use std::ffi::{c_int, c_void}; -use std::sync::atomic::{AtomicU32, Ordering, Ordering::Relaxed}; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering, Ordering::Relaxed}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Error(i32); impl Error { fn from_errno(n: i32) -> Self { assert!(n < 0); Self(n) } } type Result = std::result::Result; @@ -529,17 +550,25 @@ def replace_once(source, before, after): struct SepData { dev: kernel::device::Device, phase: AtomicU32, control: Lock, mbox: Lock>, gate: Cell, sleep_rx_held: Flag, endpoint: Cell, control_wq: Wq, + // T6041's suspend-time path (no sleep core commit); never taken here. + sleep_at_suspend: AtomicBool, } impl SepData { fn new() -> Self { Self { dev: kernel::device::Device, phase: AtomicU32::new(PHASE_READY), control: Lock(RefCell::new(Control { busy: false, wake_ok: true })), mbox: Lock(RefCell::new(Some(Mbox))), gate: Cell::new(pm::SleepGate::Open), - sleep_rx_held: Flag(Cell::new(false)), endpoint: Cell::new(true), control_wq: Wq } + sleep_rx_held: Flag(Cell::new(false)), endpoint: Cell::new(true), control_wq: Wq, + sleep_at_suspend: AtomicBool::new(false) } } fn endpoint_present(&self, _: u32) -> bool { self.endpoint.get() } fn sleep_gate(&self) -> pm::SleepGate { self.gate.get() } fn set_sleep_gate(&self, g: pm::SleepGate) { self.gate.set(g); } + // T6041's suspend-time path and its mailbox check: the platform commits here, so the + // first is never reached, and the mailbox always drains. + fn sleep_enter_at_suspend(&self) -> Result<()> { unreachable!() } + fn sleep_exit_at_suspend(&self) -> bool { unreachable!() } + fn mailbox_drains(&self) -> bool { true } fn ring(_: &Mbox, msg: kernel::soc::apple::mailbox::Message) -> Result<()> { assert_eq!(msg.msg0, proto::WAKE_KICK.msg0); event(4); RING.with(|v|v.get()) } @@ -663,7 +692,7 @@ def sources(source, contracts, mutation): sleep = (source / 'drivers/soc/apple/sleep.c').read_text() iopoll = (contracts / 'include/linux/iopoll.h').read_text() names = { - 'shim': ['sep_pm_wait_gated', 'sep_pm_clear_dev_disable', 'sep_pm_dart_restore', + 'shim': ['sep_ps_down', 'sep_pm_wait_gated', 'sep_pm_clear_dev_disable', 'sep_pm_dart_restore', 'sep_pm_commit_rx', 'sep_pm_commit_take_rx', 'sep_pm_commit_stop', 'sep_pm_commit_prepare', 'sep_pm_commit_finish', 'sep_pm_suspend_noirq'], 'mailbox': ['apple_mbox_poll_one_supported', 'apple_mbox_poll_one'], @@ -682,7 +711,7 @@ def sources(source, contracts, mutation): 'read_poll_timeout_atomic', 'readx_poll_timeout_atomic', 'readl_poll_timeout_atomic'] c = C_PREFIX + '\n' + '\n'.join(macro(iopoll, n) for n in macros) c += '\n' + '\n'.join(re.search(r'^#define ' + n + r'\s+.*$', shim, re.M).group() - for n in ['SEP_PM_POLL_US', 'SEP_PM_TIMEOUT_US']) + for n in ['SEP_PM_POLL_US', 'SEP_PM_TIMEOUT_US', 'SEP_PS_ACTUAL']) start = shim.index('static struct sep_pm_commit {') c += '\n' + shim[start:shim.index('} sep_pm_commit;', start) + len('} sep_pm_commit;')] # Use the actual provider helper, with only removal/capability dependency state @@ -700,7 +729,9 @@ def sources(source, contracts, mutation): } ''' rust += pm[gate_start:gate_end] - rust += '\n'.join(bodies[n] for n in names['pm']) + '\n}\nimpl SepData {\n' + rust += '\n'.join(bodies[n] for n in names['pm']) + # T6041 has no sleep core commit; every platform modelled here has one. + rust += '\npub(crate) fn platform_commit() -> bool { true }\n}\nimpl SepData {\n' rust += '\n'.join(bodies[n] for n in names['sep']) + '\n}\n' + RUST_TESTS return c, rust diff --git a/tools/asahi/t6030-clock-tests.py b/tools/asahi/t6030-clock-tests.py index 1c26aee6b87182..9c8a326c582e2c 100644 --- a/tools/asahi/t6030-clock-tests.py +++ b/tools/asahi/t6030-clock-tests.py @@ -21,14 +21,14 @@ 'atc_t8122_tunnel_stop', 'atc_t8122_tunnel_pclk', 'atc_t8122_tunnel_start', 'apple_atc_dp_tunnel_rate_source'], 'drivers/gpu/drm/apple/dcp-fabric.c': [ - 'dcp_route_clock_rate', 'dcp_tunnel_set_rate'], + 'dcp_phy_clocks_tunnel', 'dcp_phy_tunnel_rate', 'dcp_route_clock_rate', 'dcp_tunnel_set_rate'], } CASES = ['dual-start', 'reverse-start', 'stop-second', 'same-rate', 'stale-owner', 'same-source', 'retune-one', 'busy-mode', 'busy-pll', 'invalid-source', 'invalid-rate', 'wrong-generation', 'failed-cleanup', 'failed-final-stop', 'stale-ack', 'unflagged-ack'] CASES += ['fail-start-' + str(i) for i in range(4)] -CASES += ['t6050-dpin-clocks'] +CASES += ['t6050-dpin-clocks', 't6040-tunnel-clock'] def function(source, name): match = re.search(r'^(?:static\s+)?(?:inline\s+)?(?:unsigned\s+)?(?:int|void|bool)\s+' + name + diff --git a/tools/asahi/t6030-clock/fixture.c b/tools/asahi/t6030-clock/fixture.c index 3efdc838fe8d18..638785049ddcaa 100644 --- a/tools/asahi/t6030-clock/fixture.c +++ b/tools/asahi/t6030-clock/fixture.c @@ -46,9 +46,28 @@ struct apple_atcphy { bool prepared, changed, restored; } cio_sleep; }; +struct device_node { + const char *compatible; +}; struct phy { const void *ops; struct apple_atcphy *data; + struct { + struct device_node *of_node; + } dev; +}; +static bool of_device_is_compatible(const struct device_node *np, const char *s) +{ + return np && !strcmp(np->compatible, s); +} +/* include/linux/phy/phy-dp.h: the DP tunnel options only. */ +struct phy_configure_opts_dp { + u8 set_rate : 1, set_lanes : 1, set_voltages : 1, set_tunnel_rate : 1; + unsigned int tunnel_dpin; + u8 tunnel_rate; +}; +union phy_configure_opts { + struct phy_configure_opts_dp dp; }; struct apple_dcp; struct apple_dcp_typec_route { @@ -139,8 +158,26 @@ static int apple_t6050_dp_tunnel_clock(struct phy *p, unsigned clock, u8 rate) return t6050_error; } /* - * Production: of_device_is_compatible(dcp->dev->of_node, "apple,t8132-dcpext"). - * These are T6030 DCPs: the T8132 dcpext paths must never be taken. + * T6040 ATC PHY (t6040-usb2.c): one pixel clock per DP IN adapter (0 or 1), + * set through phy_configure() with set_tunnel_rate alone, recorded. + */ +static unsigned t6040_calls, t6040_dpin; +static u8 t6040_rate; +static int t6040_error; +static int phy_configure(struct phy *p, union phy_configure_opts *opts) +{ + assert(of_device_is_compatible(p->dev.of_node, "apple,t6040-atcphy")); + assert(opts->dp.set_tunnel_rate && !opts->dp.set_rate && + !opts->dp.set_lanes && !opts->dp.set_voltages); + t6040_calls++; + t6040_dpin = opts->dp.tunnel_dpin; + t6040_rate = opts->dp.tunnel_rate; + return t6040_error; +} +/* + * Production: an apple,t8132-dcpext the M4 backend adopts (dcp_t8132_ext_m4_node(): + * not a J773g one on firmware 27.2). These are T6030 DCPs: the T8132 dcpext + * paths must never be taken. */ static bool dcp_is_t8132_ext(const struct apple_dcp *dcp) { @@ -275,6 +312,37 @@ int main(int argc, char **argv) printf("PASS %s: DP IN n on tunnel clock n + 1, rate kept only when set\n", name); return 0; } + if (!strcmp(name, "t6040-tunnel-clock")) { + /* + * The PHY's compatible picks the path, not the machine: a T6040 + * ATC PHY takes the rate through phy_configure() on T6040 and + * T6041 alike, and neither the ATC nor the T6050 provider is + * called. A T6030 machine with that PHY takes the same path. + */ + const char *const machines[] = { "apple,t6040", "apple,t6041", "apple,t6030" }; + struct device_node t6040_atcphy = { .compatible = "apple,t6040-atcphy" }; + u8 route_rate; + phy.dev.of_node = &t6040_atcphy; + for (unsigned m = 0; m < 3; m++) { + machine = machines[m]; + t6040_calls = 0; + t6040_error = 0; + for (unsigned dpin = 0; dpin < 2; dpin++) { + assert(!t6050_clock_call(&phy, dpin, 0x1e, &route_rate)); + assert(t6040_dpin == dpin && t6040_rate == 0x1e && route_rate == 0x1e); + assert(!t6050_clock_call(&phy, dpin, 0, &route_rate)); + assert(t6040_dpin == dpin && !t6040_rate && !route_rate); + } + assert(t6040_calls == 4); + /* A clock that failed to start leaves the route's rate alone. */ + t6040_error = -ETIMEDOUT; + assert(t6050_clock_call(&phy, 1, 0x14, &route_rate) == -ETIMEDOUT && + route_rate == 0x55); + } + assert(!t6050_calls && !writes && !polls && !crossbar_stops); + printf("PASS %s: T6040 ATC PHY tunnel clock through phy_configure\n", name); + return 0; + } if (!strcmp(name, "wrong-generation")) { hw.gen = ATCPHY_GENERATION_T8103; assert(clock_call(&phy, 0, 0, 0x14) == -EOPNOTSUPP && !writes); diff --git a/tools/asahi/t6030-pmp-graph-tests.c b/tools/asahi/t6030-pmp-graph-tests.c index 079e497499eef8..7b8ba9dab6bb3e 100644 --- a/tools/asahi/t6030-pmp-graph-tests.c +++ b/tools/asahi/t6030-pmp-graph-tests.c @@ -20,6 +20,7 @@ typedef uint8_t u8; #define BIT(n) (1U << (n)) #define IS_ENABLED(x) (x) #define CONFIG_APPLE_T6030_GPU_PMP_LINK 1 +#define CONFIG_APPLE_T8122_GPU_PMP_LINK 0 #define PMP_REPORT_READY 1 #define GFP_KERNEL 0 #define GENPD_FLAG_ACTIVE_WAKEUP 1 @@ -471,17 +472,6 @@ static bool of_machine_is_compatible(const char *s) { return !strcmp(s, "apple,t6030"); } -/* As in . */ -static inline bool apple_t8132_air(void) -{ - return of_machine_is_compatible("apple,j713") || - of_machine_is_compatible("apple,j715"); -} -/* The qualified-firmware term: these harnesses model no /chosen. */ -static inline bool apple_t8132_firmware_path(void) -{ - return apple_t8132_air(); -} static bool of_property_read_bool(const struct device_node *n, const char *p) { if (!strcmp(p, "apple,always-on")) diff --git a/tools/asahi/t6030-pmp-graph-tests.py b/tools/asahi/t6030-pmp-graph-tests.py index 1184bc9840c417..d7f2b8abe17c4c 100644 --- a/tools/asahi/t6030-pmp-graph-tests.py +++ b/tools/asahi/t6030-pmp-graph-tests.py @@ -60,6 +60,12 @@ def main(): 'static int apple_pmp_report_entry_resume_noirq('] offsets = re.search(r'static const struct apple_pmp_report_offsets apple_pmp_offsets_t6030 = \{.*?\n\};', source, re.S)[0] functions = '\n'.join(extract.function(source, n) for n in names) + # The T8122 14.x wait (CONFIG_APPLE_T8122_GPU_PMP_LINK=0 here) precedes the dispatch; it is + # added after the mutations are placed, so they target the T6030 path only. + t8122 = extract.function(source, 'static int apple_pmp_report_wait_t8122_14(') + '\n' + dispatch = 'int apple_pmp_report_wait_supplier_ready(' + def with_t8122(text): + return text.replace(dispatch, t8122 + dispatch, 1) validation = re.sub(r'^#include .*\n', '', (ROOT / 'drivers/pmdomain/apple/pmp-report-validation.h').read_text(), flags=re.M) dram_type = re.search(r'struct apple_pmp_dram \{.*?\n\};', (ROOT / 'drivers/pmdomain/apple/pmp-dram.h').read_text(), re.S)[0] @@ -78,7 +84,7 @@ def main(): '\n' + dram_attrs + '\n' + functions) # The actual overlay must still describe a halted supplier and disabled DMA/mailbox. assert overlay.count('status = \"disabled\";') >= 3 - (args.output / 'production.h').write_text(code) + (args.output / 'production.h').write_text(with_t8122(code)) (args.output / 'overlay.h').write_text('static const struct overlay_entry overlay_entries[] = {\n' + entry_data + '\n};\n') compiler = shlex.split(os.environ.get('CC', 'clang')) command = compiler + ['-std=gnu11', '-g', '-O1', '-Wall', '-Wextra', '-Werror', @@ -133,13 +139,13 @@ def main(): ] for name, old, new in controls: assert code.count(old) == 1, (name, code.count(old)) - (args.output / 'production.h').write_text(code.replace(old, new)) + (args.output / 'production.h').write_text(with_t8122(code.replace(old, new))) built = subprocess.run(command, capture_output=True, text=True) # A mutant must compile; compilation failure is not regression evidence. ran = subprocess.run([str(args.output / 'graph')], capture_output=True, text=True) if not built.returncode else None (args.output / (name + '.log')).write_text(built.stdout + built.stderr + (ran.stdout + ran.stderr if ran else '')) mutations.append({'name': name, 'build_rc': built.returncode, 'run_rc': ran.returncode if ran else None}) - (args.output / 'production.h').write_text(code) + (args.output / 'production.h').write_text(with_t8122(code)) assert all(m['build_rc'] == 0 and m['run_rc'] != 0 for m in mutations), mutations (args.output / 'receipt.json').write_text(json.dumps({'source_ref': args.ref, 'source_sha256': hashlib.sha256(code.encode()).hexdigest(), 'overlay_sha256': hashlib.sha256(overlay.encode()).hexdigest(), 'overlay_entries': entries, diff --git a/tools/asahi/t6030-pmp-supplier-tests.c b/tools/asahi/t6030-pmp-supplier-tests.c index 7c3a7020b52158..c32e373a0c7020 100644 --- a/tools/asahi/t6030-pmp-supplier-tests.c +++ b/tools/asahi/t6030-pmp-supplier-tests.c @@ -170,17 +170,6 @@ static bool of_machine_is_compatible(const char *name) { return !strcmp(machine, name); } -/* As in . */ -static inline bool apple_t8132_air(void) -{ - return of_machine_is_compatible("apple,j713") || - of_machine_is_compatible("apple,j715"); -} -/* The qualified-firmware term: these harnesses model no /chosen. */ -static inline bool apple_t8132_firmware_path(void) -{ - return apple_t8132_air(); -} static struct device_node *of_find_compatible_node(struct device_node *from, const char *type, const char *compat) @@ -498,6 +487,17 @@ static void reset(void) lockable = present_device = link_ok = 1; status_word = PMP_REPORT_READY; } +/* The T8122 (M3 Air) 14.x graph: the same report shape, with T8122 compatibles. */ +static void t8122(void) +{ + machine = "apple,t8122"; + gate_soc = &gate_t8122; + supplier_node.compatible = "apple,t8122-pmp-v2"; + other_node.compatible = "apple,t8122-pmp-v2"; + gpu.compatible = "apple,agx-t8122"; + report14.compatible = "apple,t8122-pmp-v2-report"; + apple_pmp_starts.first = &managed_start; +} static int power(void) { return apple_pmp_set_device_power(0x0f, 5, 1); @@ -527,6 +527,7 @@ int main(void) (void)gate_find_one; (void)apple_pmp_report_t6030_entry; (void)apple_pmp_report_wait_t6030_14; + (void)apple_pmp_report_wait_t8122_14; reset(); assert(apple_pmp_offsets_t6030.starts_pmp == !!CONFIG_APPLE_T6030_GPU_PMP_LINK); @@ -559,6 +560,7 @@ int main(void) RUN(machine = "apple,t6031", -ENODEV, 0, 0); RUN(machine = "apple,t8140", -ENODEV, 0, 0); RUN(supplier_node.compatible = "apple,t8122-pmp-v2", -ENODEV, 0, 0); + RUN(supplier_node.compatible = "apple,t6031-pmp-v2", -ENODEV, 0, 0); RUN(report14.compatible = NULL, -ENODEV, 0, 0); RUN(extra_report = report14, -ENODEV, 0, 0); RUN(extra_report = report14; @@ -583,9 +585,51 @@ int main(void) RUN((void)0, -ENODEV, 0, 0); assert(!find_calls); #endif - /* T8122 current14 remains unsupported by this supplier API. */ + /* A T8122 supplier never takes the T6030 report. */ RUN(machine = "apple,t8122"; supplier_node.compatible = "apple,t8122-pmp-v2", -ENODEV, 0, 0); +#if CONFIG_APPLE_T8122_GPU_PMP_LINK + /* The T8122 14.x wait: one available report linked to this PMP, DISP (reg 7) acked. */ + RUN(t8122(), 0, 0, 1); + RUN(t8122(); report14.child = &entry7; entry7.sibling = &entry17; + entry17.sibling = NULL, 0, 0, 1); + RUN(t8122(); apple_pmp_starts.first = NULL, -ENODEV, 0, 0); + RUN(t8122(); apple_pmp_starts.first = NULL; + apple_pmp_reports.first = NULL, -EPROBE_DEFER, 0, 0); + RUN(t8122(); managed_start.stopping = true, -ENODEV, 0, 0); + RUN(t8122(); ready_result = -ETIMEDOUT, -ETIMEDOUT, 0, 0); + RUN(t8122(); passive_words[apple_pmp_offsets_t6030.status / 8] = 0, -EIO, + 0, 0); + RUN(t8122(); passive_words[apple_pmp_offsets_t6030.actual / 8] = 0, -EIO, + 0, 0); + RUN(t8122(); power_result = -EIO, -EIO, 0, 1); + /* The PMP's compatible picks the wait, not the machine's. */ + RUN(t8122(); machine = "apple,t6030", 0, 0, 1); + RUN(t8122(); machine = "apple,t8112", 0, 0, 1); + RUN(t8122(); supplier_node.compatible = "apple,t6030-pmp-v2", -ENODEV, 0, + 0); + RUN(t8122(); report14.compatible = NULL, -ENODEV, 0, 0); + RUN(t8122(); report14.compatible = "apple,t6030-pmp-v2-report", -ENODEV, + 0, 0); + RUN(t8122(); extra_report = report14, -ENODEV, 0, 0); + RUN(t8122(); extra_report = report14; extra_report.available = false, + -ENODEV, 0, 0); + RUN(t8122(); report14.available = false, -ENODEV, 0, 0); + RUN(t8122(); report14.has_pmp = false, -ENODEV, 0, 0); + RUN(t8122(); report14.pmp_cells = 0, -ENODEV, 0, 0); + RUN(t8122(); report14.pmp_cells = 2, -ENODEV, 0, 0); + RUN(t8122(); report14.pmp = NULL, -ENODEV, 0, 0); + RUN(t8122(); report14.pmp = &other_node, -ENODEV, 0, 0); + RUN(t8122(); entry17.sibling = NULL, -ENODEV, 0, 0); + RUN(t8122(); entry7.reg = 8, -ENODEV, 0, 0); + RUN(t8122(); entry7.available = false, -ENODEV, 0, 0); + RUN(t8122(); entry7.compatible = "apple,other", -ENODEV, 0, 0); + RUN(t8122(); entry7.no_ack = true, -ENODEV, 0, 0); + RUN(t8122(); entry17.reg = 7, -ENODEV, 0, 0); +#else + /* Without APPLE_T8122_GPU_PMP_LINK, even a well-formed T8122 graph is refused. */ + RUN(t8122(), -ENODEV, 0, 0); +#endif /* A declared report, including malformed/unresolved data, never falls back. */ RUN(supplier_node.has_report = true; supplier_node.report_cells = 0, -ENODEV, 0, 0); @@ -725,7 +769,8 @@ int main(void) assert(apple_pmp_link_device(&consumer) == -EINVAL); balanced(); case_count++; - printf("PASS: %d T6030 PMP cases, config=%d; reference, lock and command boundaries checked\n", - case_count, CONFIG_APPLE_T6030_GPU_PMP_LINK); + printf("PASS: %d T6030/T8122 PMP cases, config=%d/%d; reference, lock and command boundaries checked\n", + case_count, CONFIG_APPLE_T6030_GPU_PMP_LINK, + CONFIG_APPLE_T8122_GPU_PMP_LINK); return 0; } diff --git a/tools/asahi/t6030-pmp-supplier-tests.py b/tools/asahi/t6030-pmp-supplier-tests.py index 269006b36aa4f3..a2e4f4209a61a6 100755 --- a/tools/asahi/t6030-pmp-supplier-tests.py +++ b/tools/asahi/t6030-pmp-supplier-tests.py @@ -46,16 +46,23 @@ def no_core(): resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) -def run(out, name, code, compiler, configs=(0, 1)): +# (CONFIG_APPLE_T6030_GPU_PMP_LINK, CONFIG_APPLE_T8122_GPU_PMP_LINK): off, G15 only, and G15 +# with the M3 runtime (DRM_ASAHI_M3_T8122 depends on DRM_ASAHI_G15). +CONFIGS = ((0, 0), (1, 0), (1, 1)) + + +def run(out, name, code, compiler, configs=CONFIGS): dest = out / name dest.mkdir() (dest / "t6030-pmp-production.h").write_text(code) results = [] - for config in configs: + for t6030, t8122 in configs: + config = f"{t6030}{t8122}" binary = dest / f"config-{config}" command = compiler + ["-std=gnu11", "-g", "-O1", "-Wall", "-Wextra", "-Werror", "-fsanitize=address,undefined", "-fno-omit-frame-pointer", - f"-DCONFIG_APPLE_T6030_GPU_PMP_LINK={config}", + f"-DCONFIG_APPLE_T6030_GPU_PMP_LINK={t6030}", + f"-DCONFIG_APPLE_T8122_GPU_PMP_LINK={t8122}", "-I", str(dest), str(ROOT / "tools/asahi/t6030-pmp-supplier-tests.c"), "-o", str(binary)] @@ -148,9 +155,42 @@ def main(): assert code.count(old) == 1, (name, code.count(old)) variants.append((name, code.replace(old, new))) variants.append(("control-after", code)) + # The T8122 14.x wait mirrors the T6030 one, so it is added to every variant after the + # T6030 mutations are placed; its own mutants change only its text. + dispatch = "int apple_pmp_report_wait_supplier_ready(" + t8122 = function(report, "static int apple_pmp_report_wait_t8122_14(") + "\n" + def with_t8122(source, text=t8122): + if dispatch not in source: + return source + return source.replace(dispatch, text + dispatch, 1) + variants = [(name, with_t8122(source)) for name, source in variants] + if args.mutations: + t8122_mutations = [ + ("t8122-config-scope", "if (!IS_ENABLED(CONFIG_APPLE_T8122_GPU_PMP_LINK))", "if (false)"), + ("t8122-report-compat", 'for_each_compatible_node(np, NULL, "apple,t8122-pmp-v2-report")', + 'for_each_compatible_node(np, NULL, "apple,t6030-pmp-v2-report")'), + ("t8122-duplicate-report", "\t\tif (report) {", "\t\tif (false) {"), + ("t8122-disabled-report", "!of_device_is_available(report) ||", "false ||"), + ("t8122-report-phandle-shape", 'of_property_count_u32_elems(report, "apple,pmp") != 1', "false"), + ("t8122-supplier-identity", "pmp == supplier->of_node && entry ?", "supplier && entry ?"), + ("t8122-readiness-error", "apple_pmp_report_wait_ready(entry, msecs_to_jiffies(timeout_ms)) : -ENODEV;", + "(apple_pmp_report_wait_ready(entry, msecs_to_jiffies(timeout_ms)), 0) : -ENODEV;"), + ("t8122-entry-reference", "\tof_node_put(entry);\n\tof_node_put(pmp);", "\tof_node_put(pmp);"), + ] + for name, old, new in t8122_mutations: + assert t8122.count(old) == 1, (name, t8122.count(old)) + variants.insert(-1, (name, with_t8122(code, t8122.replace(old, new)))) + # The dispatch picks the wait by the supplier's compatible: a T8122 PMP takes the T8122 + # wait, every other supplier the T6030 one (which checks its own compatible). + machine = 'if (of_device_is_compatible(supplier->of_node, "apple,t8122-pmp-v2"))' + assert code.count(machine) == 1 + for name, new in (("t8122-dispatch-never", "if (false)"), ("t8122-dispatch-always", "if (true)")): + variants.insert(-1, (name, with_t8122(code.replace(machine, new)))) + if baseline_code and "apple_pmp_report_wait_t8122_14(" in baseline_code: + baseline_code = with_t8122(baseline_code) results = [run(args.output, name, source, compiler) for name, source in variants] if baseline_code: - results.append(run(args.output, "control-prior-config-off", baseline_code, compiler, (0,))) + results.append(run(args.output, "control-prior-config-off", baseline_code, compiler, ((0, 0),))) valid = True for item in results: control = item["name"].startswith("control-") diff --git a/tools/asahi/t6050-combo-join-tests.py b/tools/asahi/t6050-combo-join-tests.py index c57fe3dfaaaa11..e10a951fd2449e 100755 --- a/tools/asahi/t6050-combo-join-tests.py +++ b/tools/asahi/t6050-combo-join-tests.py @@ -16,13 +16,14 @@ ('apple_t6050_usb3_init_reverse', 'mf_reverse_init'), ('apple_t6050_usb3_shutdown', 'mf_poweroff')) ROW = re.compile(r'\{\s*(T6050_\w+|ATC_\w+)\s*,\s*(\w+)\s*,\s*(\w+)\s*,\s*(\w+)\s*,\s*(\w+)' - r'\s*,\s*(\w+)(?:\s*,\s*("[^"]*"|0))?\s*\}') + r'\s*,\s*(\w+)(?:\s*,\s*("[^"]*"|0|NULL))?\s*\}') def table(text, name): m = re.search(r'\b' + re.escape(name) + r'\[\]\s*=\s*\{(.*?)\n\};', text, re.S) assert m, name - return [(r[0].split('_', 1)[1], *(int(x, 0) for x in r[1:6]), (r[6] or '').strip('"')) + return [(r[0].split('_', 1)[1], *(int(x, 0) for x in r[1:6]), + '' if r[6] in ('0', 'NULL') else r[6].strip('"')) for r in ROW.findall(m.group(1))] diff --git a/tools/asahi/t8132-display-gate-tests.py b/tools/asahi/t8132-display-gate-tests.py new file mode 100755 index 00000000000000..01fb832783e505 --- /dev/null +++ b/tools/asahi/t8132-display-gate-tests.py @@ -0,0 +1,900 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host tests for the T8132 fixed-DP display gate (drivers/soc/apple/display-gate.c).""" +import os +from pathlib import Path +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] + + +def extract_block(source, marker): + match = None + for cand in re.finditer(marker, source, re.M): + semi = source.find(';', cand.start()) + brace = source.find('{', cand.start()) + if brace >= 0 and (semi < 0 or brace < semi): + match = cand + break + assert match, f'missing marker: {marker}' + start = match.start() + brace = source.index('{', start) + depth = 1 + pos = brace + 1 + while depth: + depth += (source[pos] == '{') - (source[pos] == '}') + pos += 1 + if pos < len(source) and source[pos] == ';': + pos += 1 + return source[start:pos] + '\n' + + +def main(): + gate_src = (ROOT / 'drivers/soc/apple/display-gate.c').read_text() + disp_hdr = (ROOT / 'include/linux/soc/apple/display.h').read_text() + t8132_hdr = (ROOT / 'include/linux/soc/apple/t8132.h').read_text() + dart_hdr = (ROOT / 'include/linux/soc/apple/dart.h').read_text() + + # Enforce at source level that T8132 fixed-DP gate matches the SoC, not a board name, + # and carries no hard-coded board node paths. + soc_block = extract_block(gate_src, r'^static const struct gate_soc gate_t8132\b') + assert '.machine = "apple,t8132"' in soc_block, soc_block + assert 'j773g' not in soc_block, soc_block + assert 't8132_j773g_hdmi_nodes' not in gate_src + + uuid_lines = '\n'.join( + line for line in disp_hdr.splitlines() + if line.startswith('#define APPLE_T8132_DCP_26B123_UUID') + ) + helpers = '\n'.join([ + uuid_lines, + extract_block(disp_hdr, r'^static inline bool apple_dcp_image_v27_2\('), + extract_block(t8132_hdr, r'^static inline bool apple_t8132_dcpext_v27_2\('), + extract_block(dart_hdr, r'^static inline bool apple_dart_keeps_locked_roots\('), + extract_block(gate_src, r'^static int gate_iommus_append\('), + extract_block(gate_src, r'^static struct of_changeset \*__init gate_cs_alloc\('), + extract_block(gate_src, r'^static void __init gate_cs_free\('), + extract_block(gate_src, r'^static int __init gate_iommus_set\('), + extract_block(gate_src, r'^enum \{\n\tT8132_HDMI_PHY,'), + extract_block(gate_src, r'^static bool __init staged_node_firmware_memory\('), + extract_block(gate_src, r'^static bool __init gate_t8132_dcp_v27_2\('), + extract_block(gate_src, r'^static void __init gate_t8132_put_nodes\('), + extract_block(gate_src, r'^static int __init gate_t8132_resolve_fixed_dp\('), + extract_block(gate_src, r'^static bool __init gate_t8132_fixed_dp_ready\('), + extract_block(gate_src, r'^static void __init gate_t8132_display_off\('), + extract_block(gate_src, r'^static void __init gate_t8132_run\('), + ]) + + program = r''' +#include +#include +#include +#include +#include +#include +#include + +typedef uint32_t u32; +typedef uint32_t __be32; +#define __init +#define __initconst +#define GFP_KERNEL 0 +#define CONFIG_VIDEO 1 +#define IS_ENABLED(x) (x) +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +#define kzalloc_obj(x) calloc(1, sizeof(x)) +#define kmalloc(n, g) malloc(n) +#define kfree(p) free(p) + +static __be32 cpu_to_be32(u32 v) { return __builtin_bswap32(v); } +static u32 be32_to_cpu(__be32 v) { return __builtin_bswap32(v); } + +struct gate_soc { + const char *machine; + const char *prefix; + const char *name; + const char *dcp_compat; + const char *display_compat; +}; + +static const struct gate_soc test_soc = { + .machine = "apple,t8132", + .prefix = "apple-t8132-display: ", + .name = "T8132", + .dcp_compat = "apple,t8132-dcp", + .display_compat = "apple,t8132-display-subsystem", +}; +static const struct gate_soc *gate_soc = &test_soc; +static const char *staged_prefix; +static bool nomodeset; +static unsigned int err_count, info_count; + +#define staged_info(...) do { (void)staged_prefix; info_count++; } while (0) +#define staged_err(...) do { (void)staged_prefix; err_count++; } while (0) + +static bool video_firmware_drivers_only(void) { return nomodeset; } + +struct property { + const char *name; + void *value; + size_t length; +}; + +struct device_node { + const char *path; + const char *alias; + const char *name; + const char *compatible; + u32 phandle; + bool available; + int refcount; + + /* Firmware identity */ + const char *fw_uuid; + int fw_uuid_count; + u32 fw_ver[3]; + int fw_ver_cells; + u32 fw_compat[3]; + int fw_compat_cells; + bool has_clock_ids; + + /* Phandle references */ + const char *phy_names[4]; + int phy_name_count; + struct device_node *phys[4]; + + struct device_node *iommus[4]; + u32 iommu_args[4]; + int iommu_count; + struct property iommus_prop; + __be32 iommus_buf[8]; + + struct device_node *mboxes[2]; + int mbox_count; + + struct device_node *mem_regions[4]; + int mem_region_count; + + struct device_node *piodma_child; +}; + +struct of_phandle_args { + struct device_node *np; + int args_count; + u32 args[4]; +}; + +struct cs_op { + struct device_node *np; + bool is_status; + const char *status; + struct property *prop; +}; + +struct of_changeset { + struct cs_op ops[16]; + unsigned int nops; + bool applied; +}; + +#define MAX_NODES 32 +static struct device_node *all_nodes[MAX_NODES]; +static unsigned int nr_nodes; +static struct of_changeset *applied_cs[8]; +static unsigned int nr_applied_cs; + +static void sync_iommus_prop(struct device_node *np) +{ + int i; + + if (np->iommu_count <= 0) { + np->iommus_prop.name = NULL; + np->iommus_prop.value = NULL; + np->iommus_prop.length = 0; + return; + } + for (i = 0; i < np->iommu_count; i++) { + np->iommus_buf[2 * i] = cpu_to_be32(np->iommus[i]->phandle); + np->iommus_buf[2 * i + 1] = cpu_to_be32(np->iommu_args[i]); + } + np->iommus_prop.name = "iommus"; + np->iommus_prop.value = np->iommus_buf; + np->iommus_prop.length = (size_t)np->iommu_count * 2 * sizeof(__be32); +} + +static struct device_node *of_node_get(struct device_node *np) +{ + if (np) + np->refcount++; + return np; +} + +static void of_node_put(struct device_node *np) +{ + if (np) { + assert(np->refcount > 0); + np->refcount--; + } +} + +static bool of_device_is_compatible(const struct device_node *np, const char *compat) +{ + return np && np->compatible && !strcmp(np->compatible, compat); +} + +static bool of_device_is_available(const struct device_node *np) +{ + return np && np->available; +} + +static bool of_property_present(const struct device_node *np, const char *name) +{ + if (!np) + return false; + if (!strcmp(name, "apple,firmware-compat")) + return np->fw_compat_cells > 0; + if (!strcmp(name, "apple,clock-ids")) + return np->has_clock_ids; + return false; +} + +static int of_property_count_strings(const struct device_node *np, const char *name) +{ + assert(!strcmp(name, "apple,firmware-uuid")); + return np ? np->fw_uuid_count : -EINVAL; +} + +static int of_property_read_string(const struct device_node *np, const char *name, const char **out) +{ + assert(!strcmp(name, "apple,firmware-uuid")); + if (!np || np->fw_uuid_count < 1 || !np->fw_uuid) + return -EINVAL; + *out = np->fw_uuid; + return 0; +} + +static int of_property_count_u32_elems(const struct device_node *np, const char *name) +{ + if (!np) + return -EINVAL; + if (!strcmp(name, "apple,firmware-version")) + return np->fw_ver_cells; + if (!strcmp(name, "apple,firmware-compat")) + return np->fw_compat_cells; + return -EINVAL; +} + +static int of_property_read_u32_array(const struct device_node *np, const char *name, + u32 *out, size_t n) +{ + if (!np) + return -EINVAL; + if (!strcmp(name, "apple,firmware-version") && n == 3 && np->fw_ver_cells == 3) { + memcpy(out, np->fw_ver, 3 * sizeof(u32)); + return 0; + } + if (!strcmp(name, "apple,firmware-compat") && n == 3 && np->fw_compat_cells == 3) { + memcpy(out, np->fw_compat, 3 * sizeof(u32)); + return 0; + } + return -ENOENT; +} + +static int of_property_match_string(const struct device_node *np, const char *prop, const char *val) +{ + int i; + + assert(!strcmp(prop, "phy-names")); + if (!np) + return -EINVAL; + for (i = 0; i < np->phy_name_count; i++) { + if (np->phy_names[i] && !strcmp(np->phy_names[i], val)) + return i; + } + return -ENODATA; +} + +static struct property *of_find_property(struct device_node *np, const char *name, int *lenp) +{ + assert(!strcmp(name, "iommus")); + if (!np || !np->iommus_prop.name) + return NULL; + if (lenp) + *lenp = (int)np->iommus_prop.length; + return &np->iommus_prop; +} + +static int of_count_phandle_with_args(const struct device_node *np, const char *list, + const char *cells) +{ + (void)cells; + if (!np) + return -EINVAL; + if (!strcmp(list, "memory-region")) + return np->mem_region_count; + if (!strcmp(list, "iommus")) + return np->iommu_count; + return -EINVAL; +} + +static struct device_node *of_parse_phandle(const struct device_node *np, const char *name, int idx) +{ + assert(!strcmp(name, "memory-region")); + if (!np || idx < 0 || idx >= np->mem_region_count || !np->mem_regions[idx]) + return NULL; + return of_node_get(np->mem_regions[idx]); +} + +static int of_parse_phandle_with_args(const struct device_node *np, const char *list, + const char *cells, int idx, struct of_phandle_args *out) +{ + (void)cells; + if (!np || idx < 0) + return -EINVAL; + if (!strcmp(list, "phys")) { + if (idx >= np->phy_name_count || !np->phys[idx]) + return -ENOENT; + out->np = of_node_get(np->phys[idx]); + out->args_count = 0; + return 0; + } + if (!strcmp(list, "iommus")) { + if (idx >= np->iommu_count || !np->iommus[idx]) + return -ENOENT; + out->np = of_node_get(np->iommus[idx]); + out->args_count = 1; + out->args[0] = np->iommu_args[idx]; + return 0; + } + if (!strcmp(list, "mboxes")) { + if (idx >= np->mbox_count || !np->mboxes[idx]) + return -ENOENT; + out->np = of_node_get(np->mboxes[idx]); + out->args_count = 0; + return 0; + } + return -EINVAL; +} + +static struct device_node *of_get_child_by_name(const struct device_node *np, const char *name) +{ + assert(!strcmp(name, "piodma")); + return (np && np->piodma_child) ? of_node_get(np->piodma_child) : NULL; +} + +static struct device_node *of_find_node_by_path(const char *path) +{ + unsigned int i; + + for (i = 0; i < nr_nodes; i++) { + if ((all_nodes[i]->path && !strcmp(all_nodes[i]->path, path)) || + (all_nodes[i]->alias && !strcmp(all_nodes[i]->alias, path))) + return of_node_get(all_nodes[i]); + } + return NULL; +} + +static struct device_node *of_find_compatible_node(struct device_node *from, + const char *type, const char *compat) +{ + unsigned int i = 0; + + (void)type; + if (from) { + while (i < nr_nodes && all_nodes[i] != from) + i++; + if (i < nr_nodes) + i++; + of_node_put(from); + } + for (; i < nr_nodes; i++) { + if (of_device_is_compatible(all_nodes[i], compat)) + return of_node_get(all_nodes[i]); + } + return NULL; +} + +#define for_each_compatible_node(dn, type, compatible) \ + for (dn = of_find_compatible_node(NULL, type, compatible); dn; \ + dn = of_find_compatible_node(dn, type, compatible)) + +static struct device_node *find_by_phandle(u32 phandle) +{ + unsigned int i; + + for (i = 0; i < nr_nodes; i++) { + if (all_nodes[i]->phandle == phandle) + return all_nodes[i]; + } + return NULL; +} + +static void of_changeset_init(struct of_changeset *cs) +{ + memset(cs, 0, sizeof(*cs)); +} + +static void of_changeset_destroy(struct of_changeset *cs) +{ + unsigned int i; + + for (i = 0; i < cs->nops; i++) { + if (!cs->ops[i].is_status && cs->ops[i].prop) { + free(cs->ops[i].prop->value); + free(cs->ops[i].prop); + } + } + cs->nops = 0; +} + +static int of_changeset_update_property(struct of_changeset *cs, struct device_node *np, + struct property *prop) +{ + assert(cs->nops < ARRAY_SIZE(cs->ops)); + cs->ops[cs->nops++] = (struct cs_op){ .np = np, .is_status = false, .prop = prop }; + return 0; +} + +static int of_changeset_update_prop_string(struct of_changeset *cs, struct device_node *np, + const char *name, const char *val) +{ + assert(!strcmp(name, "status")); + assert(cs->nops < ARRAY_SIZE(cs->ops)); + cs->ops[cs->nops++] = (struct cs_op){ .np = np, .is_status = true, .status = val }; + return 0; +} + +static int of_changeset_apply(struct of_changeset *cs) +{ + unsigned int i; + + for (i = 0; i < cs->nops; i++) { + struct cs_op *op = &cs->ops[i]; + + if (op->is_status) { + op->np->available = !strcmp(op->status, "okay"); + } else { + const __be32 *vals = op->prop->value; + int n = (int)(op->prop->length / (2 * sizeof(__be32))); + int j; + + assert(!strcmp(op->prop->name, "iommus")); + assert(n >= 1 && n <= 4); + op->np->iommu_count = n; + for (j = 0; j < n; j++) { + op->np->iommus[j] = find_by_phandle(be32_to_cpu(vals[2 * j])); + assert(op->np->iommus[j]); + op->np->iommu_args[j] = be32_to_cpu(vals[2 * j + 1]); + } + sync_iommus_prop(op->np); + } + } + cs->applied = true; + assert(nr_applied_cs < ARRAY_SIZE(applied_cs)); + applied_cs[nr_applied_cs++] = cs; + return 0; +} +''' + helpers + r''' +/* + * A DART kind whose locked firmware roots apple-dart keeps + * (apple_dart_keeps_locked_roots()). The J773g's own, apple,t8132-dart, is not + * one in this tree: see j773g_darts(). + */ +#define KEPT_DART "apple,t6041-dart" + +struct fixture { + struct device_node display, disp0_dart, main_dcp; + struct device_node phy, fw_dart, disp_dart, mbox, piodma, dcpext0; + struct device_node mem_text, mem_data, mem_heap; + struct device_node dcpext1; +}; + +static void register_node(struct device_node *np) +{ + assert(nr_nodes < MAX_NODES); + all_nodes[nr_nodes++] = np; +} + +static void cleanup_applied(void) +{ + unsigned int i; + + for (i = 0; i < nr_applied_cs; i++) { + of_changeset_destroy(applied_cs[i]); + free(applied_cs[i]); + } + nr_applied_cs = 0; +} + +static void check_refs_zero(void) +{ + unsigned int i; + + for (i = 0; i < nr_nodes; i++) + assert(all_nodes[i]->refcount == 0); +} + +static void set_v27_2(struct device_node *np) +{ + np->fw_uuid = APPLE_T8132_DCP_26B123_UUID; + np->fw_uuid_count = 1; + np->fw_ver[0] = 27; np->fw_ver[1] = 2; np->fw_ver[2] = 0; + np->fw_ver_cells = 3; + np->fw_compat[0] = 27; np->fw_compat[1] = 2; np->fw_compat[2] = 0; + np->fw_compat_cells = 3; +} + +static void init_fixture(struct fixture *f) +{ + cleanup_applied(); + memset(f, 0, sizeof(*f)); + nr_nodes = 0; + nomodeset = false; + err_count = info_count = 0; + + /* Deliberately use non-J773g paths to prove resolution is phandle-driven. */ + f->disp0_dart = (struct device_node){ + .path = "/soc/iommu@111100000", .phandle = 10, .available = false, + }; + f->display = (struct device_node){ + .path = "/soc/display-subsystem", .alias = "disp0", + .compatible = "apple,t8132-display-subsystem", + .phandle = 11, .available = true, + .iommus = { &f->disp0_dart }, .iommu_args = { 0 }, .iommu_count = 1, + }; + sync_iommus_prop(&f->display); + + f->main_dcp = (struct device_node){ + .path = "/soc/dcp@111e00000", .alias = "dcp", + .compatible = "apple,t8132-dcp", .phandle = 12, .available = false, + }; + + f->phy = (struct device_node){ + .path = "/soc/phy@999700000", .phandle = 20, .available = false, + }; + f->fw_dart = (struct device_node){ + .path = "/soc/iommu@999340000", .compatible = KEPT_DART, + .phandle = 21, .available = false, + }; + f->disp_dart = (struct device_node){ + .path = "/soc/iommu@999300000", .compatible = KEPT_DART, + .phandle = 22, .available = false, + }; + f->mbox = (struct device_node){ + .path = "/soc/mailbox@999e08000", .phandle = 23, .available = false, + }; + f->piodma = (struct device_node){ + .path = "/soc/dcp@999e00000/piodma", .name = "piodma", + .phandle = 24, .available = false, + .iommus = { &f->disp_dart }, .iommu_args = { 16 }, .iommu_count = 1, + }; + sync_iommus_prop(&f->piodma); + + f->mem_text = (struct device_node){ + .path = "/reserved-memory/text", .compatible = "apple,asc-mem", .available = true, + }; + f->mem_data = (struct device_node){ + .path = "/reserved-memory/data", .compatible = "apple,asc-mem", .available = true, + }; + f->mem_heap = (struct device_node){ + .path = "/reserved-memory/heap", .compatible = "apple,asc-mem", .available = true, + }; + + f->dcpext0 = (struct device_node){ + .path = "/soc/dcp@999e00000", .compatible = "apple,t8132-dcpext", + .phandle = 25, .available = false, + .phy_names = { "dp-phy" }, .phy_name_count = 1, .phys = { &f->phy }, + .iommus = { &f->fw_dart }, .iommu_args = { 23 }, .iommu_count = 1, + .mboxes = { &f->mbox }, .mbox_count = 1, + .mem_regions = { &f->mem_text, &f->mem_data, &f->mem_heap }, + .mem_region_count = 3, + .piodma_child = &f->piodma, + }; + sync_iommus_prop(&f->dcpext0); + set_v27_2(&f->dcpext0); + + /* Second dcpext without dp-phy (Type-C only): must stay untouched. */ + f->dcpext1 = (struct device_node){ + .path = "/soc/dcp@888e00000", .compatible = "apple,t8132-dcpext", + .phandle = 30, .available = false, + .phy_names = { "typec0" }, .phy_name_count = 1, .phys = { &f->phy }, + }; + set_v27_2(&f->dcpext1); + + register_node(&f->disp0_dart); + register_node(&f->display); + register_node(&f->main_dcp); + register_node(&f->phy); + register_node(&f->fw_dart); + register_node(&f->disp_dart); + register_node(&f->mbox); + register_node(&f->piodma); + register_node(&f->mem_text); + register_node(&f->mem_data); + register_node(&f->mem_heap); + register_node(&f->dcpext0); + register_node(&f->dcpext1); +} + +/* The J773g's dcpext0 DARTs, which this tree's apple-dart does not keep the locked roots of. */ +static void j773g_darts(struct fixture *f) +{ + f->fw_dart.compatible = "apple,t8132-dart"; + f->disp_dart.compatible = "apple,t8132-dart"; +} + +/* Stage 2 published nothing for the dcpexts: no image, placeholders, no display. */ +static void no_handover(struct fixture *f) +{ + struct device_node *dcps[] = { &f->dcpext0, &f->dcpext1 }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(dcps); i++) { + dcps[i]->fw_uuid = NULL; + dcps[i]->fw_uuid_count = 0; + dcps[i]->fw_ver_cells = 0; + dcps[i]->fw_compat_cells = 0; + } + f->mem_text.available = f->mem_data.available = f->mem_heap.available = false; + f->display.available = false; +} + +struct snapshot { + bool available[MAX_NODES]; + int display_iommus; + struct device_node *display_iommu[4]; +}; + +static void take_snapshot(struct fixture *f, struct snapshot *snap) +{ + unsigned int i; + + for (i = 0; i < nr_nodes; i++) + snap->available[i] = all_nodes[i]->available; + snap->display_iommus = f->display.iommu_count; + memcpy(snap->display_iommu, f->display.iommus, sizeof(snap->display_iommu)); +} + +static void expect_unchanged(struct fixture *f, const struct snapshot *snap) +{ + unsigned int i; + + for (i = 0; i < nr_nodes; i++) + assert(all_nodes[i]->available == snap->available[i]); + assert(f->display.iommu_count == snap->display_iommus); + assert(!memcmp(f->display.iommus, snap->display_iommu, sizeof(snap->display_iommu))); + assert(nr_applied_cs == 0); +} + +/* + * What the GPU sees (asahi_g16_display_prepare()): with the display subsystem + * disabled it starts on the boot framebuffer instead of waiting for it. + */ +static void expect_gpu_on_boot_framebuffer(struct fixture *f) +{ + assert(!of_device_is_available(&f->display)); + assert(!f->disp0_dart.available); + assert(f->display.iommu_count == 1 && f->display.iommus[0] == &f->disp0_dart); +} + +static void expect_chain(struct fixture *f, bool enabled) +{ + assert(f->phy.available == enabled); + assert(f->fw_dart.available == enabled); + assert(f->disp_dart.available == enabled); + assert(f->mbox.available == enabled); + assert(f->piodma.available == enabled); + assert(f->dcpext0.available == enabled); + assert(!f->dcpext1.available); +} + +int main(void) +{ + struct snapshot snap; + struct fixture f; + + /* 1. Headless T8132 (J773g-like): phandle-derived chain enabled; disp0 iommus replaced. */ + init_fixture(&f); + gate_t8132_run(); + expect_chain(&f, true); + assert(f.display.iommu_count == 1); + assert(f.display.iommus[0] == &f.disp_dart && f.display.iommu_args[0] == 0); + check_refs_zero(); + + /* 2. Laptop T8132 (14" MBP-like): main DCP handed over on 27.2 -> disp0 iommus appended. */ + init_fixture(&f); + set_v27_2(&f.main_dcp); + f.main_dcp.has_clock_ids = true; + gate_t8132_run(); + expect_chain(&f, true); + assert(f.display.iommu_count == 2); + assert(f.display.iommus[0] == &f.disp0_dart && f.display.iommu_args[0] == 0); + assert(f.display.iommus[1] == &f.disp_dart && f.display.iommu_args[1] == 0); + check_refs_zero(); + + /* 3. Main DCP with 27.2 image but no apple,clock-ids (idle) -> replaced, not appended. */ + init_fixture(&f); + set_v27_2(&f.main_dcp); + f.main_dcp.has_clock_ids = false; + gate_t8132_run(); + expect_chain(&f, true); + assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp_dart); + check_refs_zero(); + + /* + * 4-7: a refused chain on a headless T8132 leaves the display subsystem the + * boot loader enabled, and its DART, disabled: the GPU starts on the boot + * framebuffer. + */ + /* 4. Unapproved firmware UUID on dcpext0 -> chain stays disabled, disp0 unchanged. */ + init_fixture(&f); + f.disp0_dart.available = true; + f.dcpext0.fw_uuid = "00000000-0000-0000-0000-000000000000"; + gate_t8132_run(); + expect_chain(&f, false); + expect_gpu_on_boot_framebuffer(&f); + check_refs_zero(); + + /* 5. Placeholder (disabled) memory-region -> refused whole. */ + init_fixture(&f); + f.disp0_dart.available = true; + f.mem_heap.available = false; + gate_t8132_run(); + expect_chain(&f, false); + expect_gpu_on_boot_framebuffer(&f); + check_refs_zero(); + + /* 6. Missing phandle (e.g. no piodma child) -> refused whole. */ + init_fixture(&f); + f.disp0_dart.available = true; + f.dcpext0.piodma_child = NULL; + gate_t8132_run(); + expect_chain(&f, false); + expect_gpu_on_boot_framebuffer(&f); + check_refs_zero(); + + /* 7. Any chain node already enabled -> refused whole, DART not modified. */ + init_fixture(&f); + f.disp0_dart.available = true; + f.phy.available = true; + gate_t8132_run(); + assert(f.phy.available); + assert(!f.fw_dart.available && !f.disp_dart.available && !f.mbox.available && + !f.piodma.available && !f.dcpext0.available); + expect_gpu_on_boot_framebuffer(&f); + check_refs_zero(); + + /* 8. Disabled display subsystem -> chain stays disabled. */ + init_fixture(&f); + f.display.available = false; + gate_t8132_run(); + expect_chain(&f, false); + assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp0_dart); + check_refs_zero(); + + /* + * 9. No fixed dp-phy on any dcpext -> no chain, no error; the display + * subsystem has nothing to bind and goes. + */ + init_fixture(&f); + f.disp0_dart.available = true; + f.dcpext0.phy_names[0] = "typec1"; + gate_t8132_run(); + expect_chain(&f, false); + expect_gpu_on_boot_framebuffer(&f); + assert(err_count == 0 && info_count == 1); + check_refs_zero(); + + /* 10. nomodeset -> no chain; drm/apple does not register, so neither does the display. */ + init_fixture(&f); + f.disp0_dart.available = true; + nomodeset = true; + gate_t8132_run(); + expect_chain(&f, false); + expect_gpu_on_boot_framebuffer(&f); + check_refs_zero(); + + /* + * 11. No handover (Stage 2 published nothing for the dcpexts): no change + * from a tree without this gate. Nothing is enabled or disabled, disp0's + * iommus stay, and nothing is logged. + */ + init_fixture(&f); + no_handover(&f); + take_snapshot(&f, &snap); + gate_t8132_run(); + expect_unchanged(&f, &snap); + assert(err_count == 0 && info_count == 0); + check_refs_zero(); + + /* 11b. The same with the J773g's DARTs, and under nomodeset. */ + init_fixture(&f); + no_handover(&f); + j773g_darts(&f); + take_snapshot(&f, &snap); + gate_t8132_run(); + expect_unchanged(&f, &snap); + nomodeset = true; + gate_t8132_run(); + expect_unchanged(&f, &snap); + check_refs_zero(); + + /* + * 12. The J773g on 27.2 with this tree: Stage 2 handed dcpext0 over and + * enabled the display subsystem and disp0's DART, but apple-dart keeps no + * locked roots of a T8132 DART. The chain stays off and the display goes, + * so the GPU starts on the boot framebuffer as without the handover. + */ + init_fixture(&f); + j773g_darts(&f); + f.disp0_dart.available = true; + gate_t8132_run(); + expect_chain(&f, false); + expect_gpu_on_boot_framebuffer(&f); + assert(err_count == 0); + check_refs_zero(); + + /* 13. Either DART of the chain alone not kept -> the same. */ + init_fixture(&f); + f.disp0_dart.available = true; + f.fw_dart.compatible = "apple,t8132-dart"; + gate_t8132_run(); + expect_chain(&f, false); + expect_gpu_on_boot_framebuffer(&f); + init_fixture(&f); + f.disp0_dart.available = true; + f.disp_dart.compatible = "apple,t8132-dart"; + gate_t8132_run(); + expect_chain(&f, false); + expect_gpu_on_boot_framebuffer(&f); + check_refs_zero(); + + /* 14. Laptop: main DCP handed over on 27.2 -> its display subsystem and DART stay. */ + init_fixture(&f); + j773g_darts(&f); + set_v27_2(&f.main_dcp); + f.main_dcp.has_clock_ids = true; + f.main_dcp.available = true; + f.disp0_dart.available = true; + take_snapshot(&f, &snap); + gate_t8132_run(); + expect_unchanged(&f, &snap); + check_refs_zero(); + + /* 15. Headless, but the main DCP enabled: the display goes, disp0's DART (its piodma's) stays. */ + init_fixture(&f); + j773g_darts(&f); + f.main_dcp.available = true; + f.disp0_dart.available = true; + gate_t8132_run(); + expect_chain(&f, false); + assert(!f.display.available && f.disp0_dart.available); + check_refs_zero(); + + cleanup_applied(); + puts("PASS T8132 fixed-DP display gate: phandle chain, replace vs append disp0 iommus, fail-closed controls"); + puts("PASS T8132 display gate: no handover or no kept DART roots boots as without the gate, GPU on the boot framebuffer"); + return 0; +} +''' + + with tempfile.TemporaryDirectory(prefix='t8132-display-gate-') as tmp: + src = Path(tmp) / 'test.c' + exe = Path(tmp) / 'test' + src.write_text(program) + subprocess.run( + [os.environ.get('CC', 'clang'), '-std=gnu11', '-Wall', '-Wextra', '-Werror', + '-fsanitize=address,undefined', str(src), '-o', str(exe)], + check=True, + ) + subprocess.run( + [str(exe)], + check=True, + env={**os.environ, 'ASAN_OPTIONS': 'detect_leaks=0'}, + ) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/tiled-split-tests.py b/tools/asahi/tiled-split-tests.py index 7ee72aa18bf5cd..8ee3749aa80baf 100644 --- a/tools/asahi/tiled-split-tests.py +++ b/tools/asahi/tiled-split-tests.py @@ -21,7 +21,8 @@ 'drivers/gpu/drm/apple/dcp-fabric-session.h': ['dcp_fabric_binding_request'], 'drivers/gpu/drm/apple/dcp-fabric-core.c': ['dcp_fabric_tunnel_slot'], 'drivers/gpu/drm/apple/dcp-fabric.c': [ - 'dcp_typec_route_no_dp_alt', 'dcp_is_t8132_ext', 'dcp_typec_port_untileable', + 'dcp_t8132_ext_m4_node', 'dcp_is_t8132_ext', 'dcp_typec_route_no_dp_alt', + 'dcp_typec_port_untileable', 'dcp_tb_slot', 'dcp_tb_split_locked', 'dcp_tb_dispatch_request'], } CASES = ['t6030-dpin1-alone', 't6030-dpin1-alone-before-services', diff --git a/tools/asahi/tiled-split/fixture.c b/tools/asahi/tiled-split/fixture.c index 30f4ca0a797265..a0a6974408071e 100644 --- a/tools/asahi/tiled-split/fixture.c +++ b/tools/asahi/tiled-split/fixture.c @@ -61,6 +61,13 @@ static bool of_property_read_bool(const struct device_node *np, const char *name return np && !strcmp(name, "apple,dp-alt-mode") && np->dp_alt_mode; } +/* No J773g firmware-27.2 dcpext here: every T8132 dcpext is the M4 backend's. */ +static bool apple_t8132_dcpext_v27_2(const struct device_node *np) +{ + (void)np; + return false; +} + #define IS_ERR_OR_NULL(ptr) (!(ptr)) struct phy { struct device dev; }; struct mux_chip; diff --git a/tools/asahi/tunnel-route/fixture.c b/tools/asahi/tunnel-route/fixture.c index 2bcb8e713e5bef..e95d06be8446c0 100644 --- a/tools/asahi/tunnel-route/fixture.c +++ b/tools/asahi/tunnel-route/fixture.c @@ -67,7 +67,7 @@ static bool of_machine_is_compatible(const char *compatible) assert(!strcmp(compatible, "apple,t6030")); return t6030; } -/* Production: of_device_is_compatible(dcp->dev->of_node, "apple,t8132-dcpext"). */ +/* Production: an M4-adopted apple,t8132-dcpext (dcp_t8132_ext_m4_node()). */ static bool dcp_is_t8132_ext(const struct apple_dcp *dcp) { return t8132_ext; diff --git a/tools/aurora-sep/README.md b/tools/aurora-sep/README.md index c422501e579baa..b408ac8f724139 100644 --- a/tools/aurora-sep/README.md +++ b/tools/aurora-sep/README.md @@ -338,10 +338,15 @@ suspend instead, so pressing while authenticating loses nothing and the next press wakes the machine, and holding the button for 5 s powers off cleanly. GNOME sessions and the GDM login screen handle a short press themselves (`power-button-action`, `suspend` by default); the setting covers consoles -and other desktops. It takes effect at the next boot. By hand: +and other desktops. It takes effect at the next boot. The packages install it +as `05-aurora-sep.conf`: logind sorts the drop-ins of `/etc` and `/usr/lib` by +file name and the last one wins, so it only replaces logind's own default, +and a distribution or administrator drop-in (`HandlePowerKey=ignore` where a +compositor shows its own power menu, for example) still takes precedence. By +hand: ```sh -install -Dm644 logind-aurora-sep.conf /etc/systemd/logind.conf.d/aurora-sep.conf +install -Dm644 logind-aurora-sep.conf /etc/systemd/logind.conf.d/05-aurora-sep.conf ``` GNOME Shell 51 offers fingerprint only on the lock screen, never on the diff --git a/tools/aurora-sep/air-gpu/air-gpu-collect.sh b/tools/aurora-sep/air-gpu/air-gpu-collect.sh index 4a3e92bb346f63..840354fca853b2 100755 --- a/tools/aurora-sep/air-gpu/air-gpu-collect.sh +++ b/tools/aurora-sep/air-gpu/air-gpu-collect.sh @@ -759,25 +759,25 @@ main() { mv "$d" "$dir/$base" summary=$dir/$base/summary.txt tar -C "$dir" -czf "$dir/out.tgz" "$base" - # The user (runu) can't read the root-only mktemp dir, so hand the tgz over through its own - # world-readable temp file (the tgz is meant for a public issue); the collection dir stays 0700. - local pub - pub=$(mktemp --tmpdir "air-gpu-collect.XXXXXX.tgz") - cp -f "$dir/out.tgz" "$pub" - chmod 0644 "$pub" - # Durable before this returns (fsync the tgz and its directory): a hard reset right after must - # not lose it. - # shellcheck disable=SC2016 # $1..$3 are expanded by that sh - if runu sh -c 'cp -f -- "$1" "$2" && sync -- "$2" && sync -- "$3"' _ "$pub" "$out.tgz" "$home" 2>/dev/null; then + # The user (runu) can't read the root-only mktemp dir, so the tgz goes to them through a pipe: + # their own process creates the file, theirs and 0600 (with --include-dumps it holds GPU + # memory), and no copy is left anywhere else. Durable before this returns (fsync the tgz and + # its directory): a hard reset right after must not lose it. + # shellcheck disable=SC2016 # $1..$2 are expanded by that sh + if runu sh -c 'umask 077 && rm -f -- "$1" && cat >"$1" && sync -- "$1" && sync -- "$2"' \ + _ "$out.tgz" "$home" <"$dir/out.tgz" 2>/dev/null; then say "wrote $out.tgz" else - # The user's home was not writable (a symlink, say): keep the temp copy, under a name - # mktemp chose, where root can reach it. - sync "$pub" 2>/dev/null || true - say "wrote $pub (could not write $user's home)" - pub="" + # The user's home was not writable (a symlink, say): keep it where only root can read it. + local keep + keep=$STATE_DIR/collect/$base.tgz + if (umask 077 && mkdir -p -- "$STATE_DIR/collect" && cp -- "$dir/out.tgz" "$keep" && + sync -- "$keep"); then + say "wrote $keep, readable by root only (could not write $user's home)" + else + say "could not write $user's home or $STATE_DIR/collect; nothing was kept" + fi fi - [[ -z $pub ]] || rm -f "$pub" sed -n '2,6p' "$summary" head -1 "$summary" } diff --git a/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh b/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh index 2231a78b2a3465..53069ff6a3cf98 100755 --- a/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh +++ b/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh @@ -91,8 +91,11 @@ BLI_GUID=4a67b082-0a4c-41cf-b6c7-440b29bb8c4f UBOOT_GUID=b2ac5fc9-92b7-4acd-aeac-11e818c3130c GLOBAL_GUID=8be4df61-93ca-11d2-aa0d-00e098032b8c # Omarchy's Limine tools take one of these before they touch the EFI partition (newer ones the -# first, older ones the second); maclab takes both in this order, and so does this script. -LOCKS="/run/lock/boot-partition.lock /tmp/limine-global.lock" +# first, older ones the second); maclab takes both in this order, and so does this script. The +# second is in world-writable /tmp, where any user could make or hold it first: it is created if +# missing, and anything there that is not root's own regular file makes the script refuse. +LOCKS="/run/lock/boot-partition.lock" +COMPAT_LOCKS="/tmp/limine-global.lock" STATE_DIR=/var/lib/air-gpu # limine-entry-tool's settings; ENABLE_ENROLL_LIMINE_CONFIG=yes there makes Limine check a hash # of limine.conf enrolled into its EFI binary, so an edited limine.conf would not boot. @@ -303,6 +306,42 @@ take_locks() { fi LOCK_FDS+=("$fd") done + for l in $COMPAT_LOCKS; do + if ! open_compat_lock "$l"; then + release_locks + refuse "$l is not root's own lock file (a link, another user's file or not a regular file); remove it and retry." + fi + fd=$COMPAT_FD + if ! flock -w 5 "$fd"; then + release_locks + refuse "$l is held by another tool (limine-snapper-sync?); try again in a moment." + fi + LOCK_FDS+=("$fd") + done +} +# Open the compatibility lock into COMPAT_FD; fails (and the caller refuses) unless it ends up +# a regular file owned by this user (root) at that very path. A missing one is created with +# noclobber, which opens with O_EXCL and so never follows a link. The test before the open +# keeps a FIFO or another user's file from being opened at all; in sticky /tmp nobody else can +# replace root's own file afterwards. The open descriptor is checked again (owner, type, and +# the path's own inode, so not a link's target). +COMPAT_FD= +open_compat_lock() { + local l=$1 fd owner inode type + COMPAT_FD= + [[ -e $l || -L $l ]] || (umask 077; set -C; : >"$l") 2>/dev/null || true + [[ -f $l && ! -L $l && -O $l ]] || return 1 + # In braces: a redirection on exec itself would stay on the script's stderr. + { exec {fd}<"$l"; } 2>/dev/null || return 1 + # stat inherits the descriptor: /proc/self/fd/N is the file that was opened. + read -r owner inode type < <(stat -L -c '%u %d:%i %F' "/proc/self/fd/$fd" 2>/dev/null) || true + if [[ $owner == "$EUID" && $type == regular* && + $inode == "$(stat -c '%d:%i' "$l" 2>/dev/null)" ]]; then + COMPAT_FD=$fd + return 0 + fi + exec {fd}<&- + return 1 } LOCK_FDS=() release_locks() { diff --git a/tools/aurora-sep/aurora-sep-policy-change b/tools/aurora-sep/aurora-sep-policy-change index fc9aab126e0d6b..d1948414af3a38 100755 --- a/tools/aurora-sep/aurora-sep-policy-change +++ b/tools/aurora-sep/aurora-sep-policy-change @@ -36,6 +36,7 @@ root, and never adds the record to Linux's list. See XART-SAFETY.md. """ import hashlib +import json import os import re import shutil @@ -57,8 +58,11 @@ HOST_FILES = ( ) FPRINT = "/var/lib/fprint" -REFUSED = re.compile(r"xART guard: refused to rewrite kind-([34]) record ([0-9a-f]{32})") -BASE = re.compile(r"xART: APFS-resolved \.gl extent \(base (0x[0-9a-f]+)\)") +# Matched at the start of the driver's own messages only (kernel_log): a line +# anyone can get into the kernel log (a USB product string, say) is not one. +REFUSED = re.compile(r"^xART guard: refused to rewrite kind-([34]) record ([0-9a-f]{32}),", re.M) +BASE = re.compile(r"^xART: APFS-resolved \.gl extent \(base (0x[0-9a-f]+)\);", re.M) +DRIVER = "apple_sep" def die(msg): @@ -70,13 +74,51 @@ def say(msg): print(f"aurora-sep-policy-change: {msg}") +def driver_message(entry): + """The text of one journal entry if the apple_sep driver logged it, else None. + + Its device messages carry the SEP platform device in the journal's + kernel fields and start "apple_sep : "; its messages without a + device start "apple_sep: ". The prefix is removed. + + The journal's kernel transport also carries what processes write to + /dev/kmsg; only the kernel's own messages have facility 0 there.""" + if not isinstance(entry, dict) or entry.get("_TRANSPORT") != "kernel": + return None + if entry.get("SYSLOG_FACILITY") != "0": + return None + msg = entry.get("MESSAGE") + if not isinstance(msg, str): + return None + device = entry.get("_KERNEL_DEVICE") + if device is None: + prefix = f"{DRIVER}: " + else: + if not isinstance(device, str) or not device.startswith("+platform:"): + return None + name = device[len("+platform:"):] + if entry.get("_KERNEL_SUBSYSTEM") != "platform" or not name.endswith(".sep"): + return None + prefix = f"{DRIVER} {name}: " + return msg[len(prefix):] if msg.startswith(prefix) else None + + def kernel_log(): + """This boot's apple_sep messages, one per line, without the driver prefix.""" out = subprocess.run( - ["journalctl", "-k", "-b", "-o", "cat", "--no-pager", "-g", "apple_sep|xART"], + ["journalctl", "-k", "-b", "-o", "json", "--no-pager", "-g", "apple_sep|xART"], capture_output=True, text=True, ) - return out.stdout + lines = [] + for raw in out.stdout.splitlines(): + try: + msg = driver_message(json.loads(raw)) + except ValueError: + continue + if msg is not None: + lines.append(msg.rstrip("\n")) + return "\n".join(lines) + ("\n" if lines else "") def entry(kind, uuid): @@ -174,7 +216,7 @@ def status(log): say(f"refused this boot: kind-{kind} record {uuid}") for line in log.splitlines(): if "one-time rewrite" in line or "one-time allowance" in line: - say("this boot: " + line.split("apple_sep: ")[-1]) + say("this boot: " + line) def main(argv): diff --git a/tools/aurora-sep/aurora-sep-ready b/tools/aurora-sep/aurora-sep-ready index d1043c26e29903..e7e97535430504 100644 --- a/tools/aurora-sep/aurora-sep-ready +++ b/tools/aurora-sep/aurora-sep-ready @@ -112,11 +112,29 @@ failed() { run_dir=${AURORA_SEP_RUN:-/run/aurora-sep} repair_checked= repair_started= +# This boot's kernel messages of the SEP device named by the diag directory +# (journal entries whose kernel fields are that device; dmesg without +# journald). The driver writes them as "apple_sep : ...". +sep_device=${diag%/diag} +sep_device=${sep_device##*/} +sep_kernel_log() { + [ -n "$sep_device" ] || return 0 + if command -v journalctl >/dev/null 2>&1; then + journalctl -k -b -o cat --no-pager _KERNEL_SUBSYSTEM=platform \ + "_KERNEL_DEVICE=+platform:$sep_device" 2>/dev/null + else + dmesg 2>/dev/null | sed 's/^\[[^]]*\] //' + fi +} repair_once() { [ -z "$repair_checked" ] || return 0 repair_checked=1 - line=$({ journalctl -k -b -o cat --no-pager 2>/dev/null || dmesg 2>/dev/null; } | - grep -m1 -E 'sensor: ((LOAD_CALIBRATION|SENSOR_ROOT_KEY) refused|calibration refused|calibration blob [^ ]+ could not be loaded|signed root-key container [^ ]+ unavailable)') + [ -n "$sep_device" ] || return 0 + # Only a line that starts with the driver's own prefix for this device: + # text that merely contains the words (a USB product string) is not one. + device_re=$(printf '%s' "$sep_device" | sed 's/[][\.*^$/]/\\&/g') + line=$(sep_kernel_log | + grep -m1 -E "^apple_sep $device_re: sensor: ((LOAD_CALIBRATION|SENSOR_ROOT_KEY) refused|calibration refused|calibration blob [^ ]+ could not be loaded|signed root-key container [^ ]+ unavailable)") [ -n "$line" ] || return 0 if [ -e "$run_dir/touchid-auto-rebuild" ]; then log "the enclave refused a Touch ID file again ($line); the automatic rebuild already ran this boot, so not again. Run 'sudo aurora-touchid-setup --check' for details" diff --git a/tools/aurora-sep/aurora-touchid/PKGBUILD b/tools/aurora-sep/aurora-touchid/PKGBUILD index ebad07307e9665..b96e1d891a3834 100644 --- a/tools/aurora-sep/aurora-touchid/PKGBUILD +++ b/tools/aurora-sep/aurora-touchid/PKGBUILD @@ -1,7 +1,7 @@ # Maintainer: Chris Kearney <303316+iconidentify@users.noreply.github.com> pkgname=aurora-touchid pkgver=20261003 -pkgrel=2 +pkgrel=3 pkgdesc="Touch ID for Omarchy on Apple Silicon (aurora kernel SEP driver)" arch=('any') url="https://github.com/iconidentify/aurora-linux" @@ -12,6 +12,7 @@ source=('aurora-touchid-setup' 'apple-sep.service' 'apple-sep.path' 'fprintd-aurora.conf' + 'aurora-touchid-device.service' 'aurora-touchid.sleep' 'wait-for-display' 'sddm-wait-display.conf') @@ -19,7 +20,8 @@ sha256sums=('406da23baf0127dd5ba116c2f83808fb10d979315a17227a78731c5d3081efe4' '15a878dcf382a22c5d807f0f2c754fe70d39baec88f65aea183b1fe56cf69441' '4f7b8a97e35e3511afa482ee8aedd019e960b1a67320675bd347f534feab49c3' '2f4b265a4c2180a9e0e4926c53ec77c3dbb074ddc3e083d7925d58db10a576b9' - 'e1b1152e576e9588cc134b09291b3a2306ac686d9a47be6f128670608da535fc' + '1ff4dc0bb2a731fc8ee7a65d270b86b51e0d11d7f68dcce0204a3e67570e58b1' + '6da30137e6e2408cab9b755af7a6c4b1e004057a79d857b0d528d5eaf08bfe5a' 'a87526383319cc7c1214082196d0d80ad9a6da09b5c30bf215f866e01443c611' '062f70bb84e4139baf75d4dbefff21478af28f67e5569ee095692734d764746b' '07edd06103f5d199e7d6dcca0b7fa8e10a912cb657973ffce764c6e2ef65fa40') @@ -30,6 +32,7 @@ package() { install -Dm644 apple-sep.service "$pkgdir/usr/lib/systemd/system/apple-sep.service" install -Dm644 apple-sep.path "$pkgdir/usr/lib/systemd/system/apple-sep.path" install -Dm644 fprintd-aurora.conf "$pkgdir/usr/lib/systemd/system/fprintd.service.d/aurora.conf" + install -Dm644 aurora-touchid-device.service "$pkgdir/usr/lib/systemd/system/aurora-touchid-device.service" install -Dm755 aurora-touchid.sleep "$pkgdir/usr/lib/systemd/system-sleep/aurora-touchid" install -Dm755 wait-for-display "$pkgdir/usr/lib/aurora-touchid/wait-for-display" install -Dm644 sddm-wait-display.conf "$pkgdir/usr/lib/systemd/system/sddm.service.d/50-aurora-wait-display.conf" diff --git a/tools/aurora-sep/aurora-touchid/aurora-touchid-device.service b/tools/aurora-sep/aurora-touchid/aurora-touchid-device.service new file mode 100644 index 00000000000000..cf112c29ec317c --- /dev/null +++ b/tools/aurora-sep/aurora-touchid/aurora-touchid-device.service @@ -0,0 +1,15 @@ +[Unit] +Description=Wait for the Touch ID device (/dev/sep-bio) +# apple-sep.service only runs modprobe; /dev/sep-bio appears a few seconds +# later, once the enclave is up. fprintd is ordered after this (its drop-in), +# so that it does not start, find no device and cache "No devices available" +# until it idles out, and so that its DeviceAllow=/dev/sep-bio finds the node. +After=apple-sep.service +Before=fprintd.service +ConditionPathExists=/dev/disk/by-partlabel/iBootSystemContainer + +[Service] +Type=oneshot +# At most 15 s; fprintd then starts without the node, and its next start +# (fprintd exits when idle) finds it. +ExecStart=/bin/sh -c 'i=0; while [ ! -e /dev/sep-bio ] && [ $i -lt 150 ]; do sleep 0.1; i=$((i+1)); done; exit 0' diff --git a/tools/aurora-sep/aurora-touchid/fprintd-aurora.conf b/tools/aurora-sep/aurora-touchid/fprintd-aurora.conf index bfa2385635b435..4a78939d5b7e44 100644 --- a/tools/aurora-sep/aurora-touchid/fprintd-aurora.conf +++ b/tools/aurora-sep/aurora-touchid/fprintd-aurora.conf @@ -1,12 +1,13 @@ [Unit] -After=apple-sep.service +# aurora-touchid-device.service waits for /dev/sep-bio before fprintd starts: +# a DeviceAllow= path is resolved to a device number when fprintd's cgroup is +# set up, before any ExecStartPre= runs, and is dropped if the node does not +# exist yet. aurora-sep-ready.service does the same where the aurora-sep +# package is installed. +Wants=aurora-touchid-device.service +After=apple-sep.service aurora-touchid-device.service aurora-sep-ready.service [Service] -# apple-sep.service only runs modprobe; /dev/sep-bio appears a few seconds -# later, once the enclave is up. Wait for it (at most 15 s) so fprintd does not -# start, find no device and cache "No devices available" until it idles out. -ExecStartPre=/bin/sh -c 'i=0; while [ ! -e /dev/sep-bio ] && [ $i -lt 150 ]; do sleep 0.1; i=$((i+1)); done; exit 0' -# Allow the misc class rather than the node: a path rule is resolved to a -# device number when the cgroup is set up, before ExecStartPre runs, and is -# dropped if /dev/sep-bio does not exist yet. -DeviceAllow=char-misc rw +# Only the Touch ID node, not the whole misc class (uinput, fuse, kvm, +# device-mapper control, ...). +DeviceAllow=/dev/sep-bio rw diff --git a/tools/aurora-sep/aurora_sep.fc b/tools/aurora-sep/aurora_sep.fc index 66e04fb5890441..45e11dbc682e7b 100644 --- a/tools/aurora-sep/aurora_sep.fc +++ b/tools/aurora-sep/aurora_sep.fc @@ -1,5 +1,6 @@ /dev/sep-bio -c gen_context(system_u:object_r:aurora_sep_device_t,s0) /var/lib/apple-sep-catacomb-(master|owner|user)\.bin -- gen_context(system_u:object_r:aurora_sep_state_t,s0) +/var/lib/\.apple-sep-catacomb-(master|owner|user)\.bin\.new -- gen_context(system_u:object_r:aurora_sep_state_t,s0) /var/lib/aurora-sep-keybag\.bin -- gen_context(system_u:object_r:aurora_sep_state_t,s0) /var/lib/aurora-sep-refkey(-v2)?\.bin -- gen_context(system_u:object_r:aurora_sep_state_t,s0) /var/lib/aurora-sep-host-state\.bin -- gen_context(system_u:object_r:aurora_sep_state_t,s0) diff --git a/tools/aurora-sep/aurora_sep.te b/tools/aurora-sep/aurora_sep.te index 55a33bea69b3f0..ff0189e4803238 100644 --- a/tools/aurora-sep/aurora_sep.te +++ b/tools/aurora-sep/aurora_sep.te @@ -1,4 +1,4 @@ -policy_module(aurora_sep, 1.3.0) +policy_module(aurora_sep, 1.4.0) ######################################## # @@ -39,10 +39,17 @@ gen_require(` # The driver opens its state files with kernel credentials (store_shim.c), so # the kernel creates them. Give each new file the state type by name: a file # that the kernel creates in /var/lib must never start out as var_lib_t. -allow kernel_t aurora_sep_state_t:file { create_file_perms rw_file_perms }; +allow kernel_t aurora_sep_state_t:file { create_file_perms rw_file_perms setattr_file_perms rename_file_perms delete_file_perms }; type_transition kernel_t var_lib_t:file aurora_sep_state_t "apple-sep-catacomb-master.bin"; type_transition kernel_t var_lib_t:file aurora_sep_state_t "apple-sep-catacomb-owner.bin"; type_transition kernel_t var_lib_t:file aurora_sep_state_t "apple-sep-catacomb-user.bin"; +# The driver publishes a catacomb by renaming a complete "..new" over it. +# Rename keeps the inode's label, so label the temporary too. The kernel resets +# the temporary's mode to 0600 when a caller's umask cleared bits from it, and +# unlinks a temporary left by an interrupted replacement. +type_transition kernel_t var_lib_t:file aurora_sep_state_t ".apple-sep-catacomb-master.bin.new"; +type_transition kernel_t var_lib_t:file aurora_sep_state_t ".apple-sep-catacomb-owner.bin.new"; +type_transition kernel_t var_lib_t:file aurora_sep_state_t ".apple-sep-catacomb-user.bin.new"; type_transition kernel_t var_lib_t:file aurora_sep_state_t "aurora-sep-keybag.bin"; type_transition kernel_t var_lib_t:file aurora_sep_state_t "aurora-sep-refkey.bin"; type_transition kernel_t var_lib_t:file aurora_sep_state_t "aurora-sep-refkey-v2.bin"; diff --git a/tools/aurora-sep/esp-history.py b/tools/aurora-sep/esp-history.py index 07fe588a531368..ed76460d8ea1b9 100644 --- a/tools/aurora-sep/esp-history.py +++ b/tools/aurora-sep/esp-history.py @@ -2,6 +2,7 @@ """Archive unreferenced EFI history while retaining boot and recovery entries.""" import argparse import contextlib +import errno import fcntl import hashlib import json @@ -87,8 +88,30 @@ def inventory(esp, state): return records +def compat_lock(path): + """fd of the compatibility lock older Omarchy Limine tools take (/tmp/limine-global.lock). + + It is created when missing (root's, 0600) and never followed through a + link. /tmp is world-writable, so anything else at that path (a file of + another user, a link, a FIFO, or a file fs.protected_regular will not let + root open) is refused: going on without the lock could let an older + Limine tool write the EFI partition at the same time.""" + try: + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, 0o600) + except OSError as error: + if error.errno in (errno.EACCES, errno.EPERM, errno.ELOOP, errno.ENXIO): + raise ValueError(f'{path} is not root\'s own lock file ({os.strerror(error.errno)}); ' + 'remove it and retry. Nothing was changed') from None + raise + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid(): + os.close(fd) + raise ValueError(f'{path} is not root\'s own lock file (a link, another user\'s file or ' + 'not a regular file); remove it and retry. Nothing was changed') + return fd + @contextlib.contextmanager -def lock(paths): +def lock(paths, compat=()): fds = [] try: for path in paths: @@ -98,19 +121,29 @@ def lock(paths): if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + for path in compat: + fd = compat_lock(path) + fds.append(fd) + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) yield finally: for fd in reversed(fds): os.close(fd) -def archive(esp, state, destination, lock_paths=None): +BOOT_LOCK = Path('/run/lock/boot-partition.lock') +COMPAT_LOCK = Path('/tmp/limine-global.lock') + + +def archive(esp, state, destination, lock_paths=None, compat_locks=None): esp, state, destination = esp.absolute(), state.absolute(), destination.absolute() destination.mkdir(parents=True, exist_ok=True) checked_tree(destination) if destination.resolve().is_relative_to(esp.resolve()) or os.stat(destination).st_dev == os.stat(esp).st_dev: raise ValueError('archive must be on a different filesystem from the EFI partition') - with lock(lock_paths or [Path('/run/lock/boot-partition.lock'), Path('/tmp/limine-global.lock')]): + if lock_paths is None: + lock_paths, compat_locks = [BOOT_LOCK], [COMPAT_LOCK] if compat_locks is None else compat_locks + with lock(lock_paths, compat_locks or ()): planned = inventory(esp, state) moved = [] for item in planned: diff --git a/tools/aurora-sep/install-aurora-sep.sh b/tools/aurora-sep/install-aurora-sep.sh index b27cad73b1aea5..32eb27b930998f 100755 --- a/tools/aurora-sep/install-aurora-sep.sh +++ b/tools/aurora-sep/install-aurora-sep.sh @@ -685,8 +685,8 @@ M3_PERSISTENT_TRANSACTION_ACTIVE=0 M3_PERSISTENT_MAIN_ARMED=0 M3_GPU_BIN=/usr/local/bin M3_GPU_SCRIPTS=( - "air-gpu-oneshot.sh d0259869b8519439a4dbcdae08ef1b0e17fdcaf84ac746fca61febf6a325f8aa" - "air-gpu-collect.sh face8fac811b59c31a8e98e6ca704a2cb33eceada8bc37986397cb393b050b30" + "air-gpu-oneshot.sh 30e9d5e96100412d144acb8064ddc63f1000a7a77081ded49072a092b8738b8f" + "air-gpu-collect.sh 6a457261dc9773401f2ec7e436839a5f0d3b2bccdd9a90f013f8e72878189879" "air-gpu-job.sh 9a0eb9aab52fd099488054e4ed4846c579b19fc9f78144245242b6975a40da1d" ) # The Mesa prefix air-gpu-job.sh runs with: mesa-m3's (12.4 on; it replaces the separate @@ -759,7 +759,7 @@ m3_pro_perf_activate() { $(cat /opt/mesa-m3/pro-vulkan/share/mesa-m3/profile) == t6030-pro-vulkan-legacy-hal ]] || die "paired Pro Mesa installation is incomplete" user=$(m3_pro_mesa_user) if [[ $user != root ]]; then - printf '%s' "$M3_PRO_PERF_MIGRATOR" | base64 -d > "$work/migrate-pro-session.py" + printf '%s' "$M3_PRO_PERF_MIGRATOR" | base64 -d | work_write "$work/migrate-pro-session.py" $sudo runuser -u "$user" -- python3 - "$user" < "$work/migrate-pro-session.py" || die "could not update the managed native Pro session" fi $sudo systemctl enable mesa-m3-pro-performance.service @@ -875,17 +875,23 @@ update_m1n1_frozen() { "$UPDATE_M1N1_CONF" >/dev/null 2>&1 } +# Write stdin to DEST as root: a new 0644 file of root's, renamed over DEST. What root installs +# as configuration is passed to it this way, from the shell that made it, and never by way of +# a temporary file of the invoking user's. +root_put() { # DEST + # shellcheck disable=SC2016 # expanded by that sh + $sudo sh -c 'umask 022 && mkdir -p "$(dirname "$1")" && t=$(mktemp "$1.XXXXXX") && { cat >"$t" && chmod 0644 "$t" && mv -f "$t" "$1" || { rm -f "$t"; exit 1; }; }' _ "$1" +} + m3_freeze() { - local tmp + local text if update_m1n1_frozen; then M3_FROZEN_BY=already return 0 fi - tmp=$(mktemp) - if [[ -f $UPDATE_M1N1_CONF ]]; then cat "$UPDATE_M1N1_CONF" >"$tmp"; fi - printf '%s\nM1N1_UPDATE_DISABLED=1\n%s\n' "$M3_FREEZE_BEGIN" "$M3_FREEZE_END" >>"$tmp" - $sudo install -m 644 "$tmp" "$UPDATE_M1N1_CONF" - rm -f "$tmp" + text=$({ if [[ -f $UPDATE_M1N1_CONF ]]; then cat "$UPDATE_M1N1_CONF"; fi; } && + printf '%s\nM1N1_UPDATE_DISABLED=1\n%s\nx' "$M3_FREEZE_BEGIN" "$M3_FREEZE_END") + printf '%s' "${text%x}" | root_put "$UPDATE_M1N1_CONF" update_m1n1_frozen || die "could not freeze update-m1n1 in $UPDATE_M1N1_CONF; nothing was installed" M3_FROZEN_BY=aurora-sep } @@ -900,16 +906,15 @@ m3_unfrozen() { # Lift only this script's freeze; a file that held nothing else goes. m3_unfreeze() { - local tmp + local text [[ -f $UPDATE_M1N1_CONF ]] && grep -qxF "$M3_FREEZE_BEGIN" "$UPDATE_M1N1_CONF" || return 0 - tmp=$(mktemp) - m3_unfrozen >"$tmp" - if grep -q '[^[:space:]]' "$tmp"; then - $sudo install -m 644 "$tmp" "$UPDATE_M1N1_CONF" + text=$(m3_unfrozen && printf x) + text=${text%x} + if [[ $text =~ [^[:space:]] ]]; then + printf '%s' "$text" | root_put "$UPDATE_M1N1_CONF" else $sudo rm -f "$UPDATE_M1N1_CONF" fi - rm -f "$tmp" } # m1n1's boot.bin on the EFI partition, where macOS can reach it. Omarchy @@ -1309,21 +1314,20 @@ update_m1n1_customised() { # Lift the M3 bring-up's freeze: only its own three lines, and its marker. # The original is kept so --uninstall can put the freeze back. m3gpu_unfreeze() { - local tmp + local text [[ -f $UPDATE_M1N1_CONF ]] && grep -qxF "${M3GPU_FREEZE[0]}" "$UPDATE_M1N1_CONF" || return 0 [[ -f $STATE/update-m1n1.m3gpu.saved ]] || $sudo cp -p "$UPDATE_M1N1_CONF" "$STATE/update-m1n1.m3gpu.saved" - tmp=$(mktemp) - m3gpu_unfrozen >"$tmp" + text=$(m3gpu_unfrozen && printf x) + text=${text%x} if [[ -e $M3GPU_MARKER ]]; then [[ -f $STATE/m3gpu-marker.saved ]] || $sudo touch "$STATE/m3gpu-marker.saved" $sudo rm -f "$M3GPU_MARKER" fi - if grep -q '[^[:space:]]' "$tmp"; then - $sudo install -m 644 "$tmp" "$UPDATE_M1N1_CONF" + if [[ $text =~ [^[:space:]] ]]; then + printf '%s' "$text" | root_put "$UPDATE_M1N1_CONF" else $sudo rm -f "$UPDATE_M1N1_CONF" fi - rm -f "$tmp" say "Lifted the M3 bring-up's freeze on update-m1n1 (from install-m3gpu.sh)" } @@ -1340,7 +1344,7 @@ m1n1_conf_without_switches() { } m3_switches_write() { - local tmp s begin=$M1N1_CONF_BEGIN end=$M1N1_CONF_END + local text s begin=$M1N1_CONF_BEGIN end=$M1N1_CONF_END if is_m3_air; then begin=$M1N1_CONF_AIR_BEGIN end=$M1N1_CONF_AIR_END @@ -1348,29 +1352,25 @@ m3_switches_write() { begin=$M1N1_CONF_MAX_BEGIN end=$M1N1_CONF_MAX_END fi - tmp=$(mktemp) - m1n1_conf_without_switches >"$tmp" - { + text=$(m1n1_conf_without_switches && { echo "$begin" for s in $(m3_switches); do echo "$s"; done echo "$end" - } >>"$tmp" - $sudo install -m 644 "$tmp" "$M1N1_CONF" - rm -f "$tmp" + } && printf x) + printf '%s' "${text%x}" | root_put "$M1N1_CONF" } m3_switches_remove() { - local tmp + local text [[ -f $M1N1_CONF ]] && grep -qxF -e "$M1N1_CONF_BEGIN" -e "$M1N1_CONF_AIR_BEGIN" -e "$M1N1_CONF_MAX_BEGIN" "$M1N1_CONF" || return 0 - tmp=$(mktemp) - m1n1_conf_without_switches >"$tmp" - if grep -q '[^[:space:]]' "$tmp"; then - $sudo install -m 644 "$tmp" "$M1N1_CONF" + text=$(m1n1_conf_without_switches && printf x) + text=${text%x} + if [[ $text =~ [^[:space:]] ]]; then + printf '%s' "$text" | root_put "$M1N1_CONF" else $sudo rm -f "$M1N1_CONF" fi - rm -f "$tmp" } # The M3 path an earlier install took, or nothing. @@ -2694,8 +2694,8 @@ m3_pro_mesa_set_aside() { local file file=$(m3_pro_mesa_file) [[ -n $M3_PRO_MESA_PACKAGE && -f $work/$file ]] || return 0 - mkdir -p "$work/m3-pro" - mv "$work/$file" "$work/m3-pro/" + $sudo mkdir -p "$work/m3-pro" + $sudo mv -- "$work/$file" "$work/m3-pro/" } # The M3_PRO_MESA_NEEDS entries this Mac does not satisfy, one "name version (needs min or @@ -3514,7 +3514,7 @@ EOF # version number, kept for the fallback entry) without the Touch ID sensor node. # Point it at whatever directory linux-aurora owns, now and after its updates. m1n1_update() { - local target conf=$UPDATE_M1N1_CONF tmp + local target conf=$UPDATE_M1N1_CONF text local -a drop=(-e '/^# aurora-sep: build m1n1/,/^DTBS=/d' -e '/^DTBS=/d') [[ -f $conf && ! -f $STATE/update-m1n1.default.saved ]] && $sudo cp "$conf" "$STATE/update-m1n1.default.saved" @@ -3527,11 +3527,7 @@ m1n1_update() { if is_neo && [[ $NEO_AURORA_M1N1 == 1 ]]; then drop+=(-e '/^[[:space:]]*\(export[[:space:]]\{1,\}\)\{0,1\}M1N1=/d') fi - tmp=$(mktemp) - if [[ -f $conf ]]; then - $sudo sed "${drop[@]}" "$conf" >"$tmp" - fi - cat >>"$tmp" <<'EOF' + text=$({ if [[ -f $conf ]]; then $sudo sed "${drop[@]}" "$conf"; fi; } && cat <<'EOF' # aurora-sep: build m1n1's stage 2 from the device trees the installed # linux-aurora package owns, which carry the Touch ID sensor node. # @@ -3543,9 +3539,10 @@ m1n1_update() { # $(...), so the pipeline must succeed even when grep matches nothing.) DTBS=$(pacman -Qlq linux-aurora 2>/dev/null | grep '/dtbs/[^/]*\.dtb$' || true) EOF - if ((NEO_GPU)); then echo "M1N1=/usr/lib/m1n1-neo/m1n1.bin" >>"$tmp"; fi - $sudo install -m 644 "$tmp" "$conf" - rm -f "$tmp" + ) + text+=$'\n' + if ((NEO_GPU)); then text+=$'M1N1=/usr/lib/m1n1-neo/m1n1.bin\n'; fi + printf '%s' "$text" | root_put "$conf" if [[ ! -f $STATE/boot.bin.saved ]] && target=$(esp_bootbin); then $sudo cp "$target" "$STATE/boot.bin.saved" fi @@ -3814,13 +3811,11 @@ neo_radio_notice() { # update-m1n1's configuration (without this script's own M3 freeze from 11.36), # or that there was none; the bring-up's freeze; and boot.bin itself. snapshot_boot_state() { - local tmp target + local text target if [[ ! -e $STATE/update-m1n1.default.saved && ! -e $STATE/update-m1n1.absent ]]; then if [[ -f $UPDATE_M1N1_CONF ]]; then - tmp=$(mktemp) - m3_unfrozen >"$tmp" - $sudo install -m 644 "$tmp" "$STATE/update-m1n1.default.saved" - rm -f "$tmp" + text=$(m3_unfrozen && printf x) + printf '%s' "${text%x}" | root_put "$STATE/update-m1n1.default.saved" else $sudo touch "$STATE/update-m1n1.absent" fi @@ -3875,7 +3870,7 @@ frozen_dependency_prepare() { for archive in "$@"; do args+=(--candidate "$archive"); done args+=(--allow-remove linux-asahi --allow-remove linux-asahi-headers --allow-remove m1n1 --allow-remove mesa-m3-g15g) - cat >"$work/frozen-dependencies.py" <<'FROZEN_DEPENDENCIES_PY' + work_write "$work/frozen-dependencies.py" <<'FROZEN_DEPENDENCIES_PY' #!/usr/bin/env python3 """Admit missing repository dependencies without changing installed packages.""" import argparse @@ -4209,7 +4204,7 @@ def main(): (work / "dependency-plan.json").write_text(json.dumps(receipt, indent=2) + "\n") hook.write_text("[Trigger]\nOperation = Install\nOperation = Upgrade\nOperation = Remove\n" "Type = Package\nTarget = *\n[Action]\nWhen = PreTransaction\n" - "Exec = /usr/bin/python3 " + str(helper) + " --verify-plan " + str(receipt_path) + + "Exec = /usr/bin/python3 -I " + str(helper) + " --verify-plan " + str(receipt_path) + " --plan-sha256 " + sha(receipt_path) + "\nAbortOnFail\n") print(json.dumps(receipt)) @@ -4222,7 +4217,7 @@ if __name__ == "__main__": sys.exit(1) FROZEN_DEPENDENCIES_PY say "Resolving only missing dependencies while preserving this image's package holds" - $sudo python3 "$work/frozen-dependencies.py" "${args[@]}" >"$work/dependency-result.json" || + $sudo python3 -I "$work/frozen-dependencies.py" "${args[@]}" | work_write "$work/dependency-result.json" || die "could not admit a missing-only dependency transaction. Nothing was installed. The package holds were preserved." FROZEN_TRANSACTION_CONFIG=$(python3 - "$work/dependency-result.json" <<'FROZEN_CONFIG_PY' import json, sys @@ -4230,7 +4225,7 @@ print(json.load(open(sys.argv[1]))['transaction_config']) FROZEN_CONFIG_PY ) $sudo test -f "$FROZEN_TRANSACTION_CONFIG" || die "missing admitted package transaction configuration" - python3 - "$work/dependency-result.json" >"$work/dependency-files" <<'FROZEN_FILES_PY' + python3 - "$work/dependency-result.json" <<'FROZEN_FILES_PY' | work_write "$work/dependency-files" import json, sys plan = json.load(open(sys.argv[1])) for filename in list(plan['candidate_sha256']) + [p['file'] for p in plan['dependencies']]: @@ -4270,6 +4265,46 @@ package_database_check() { Run 'omarchy update', reboot, then retry. Installing repository dependencies before a full update would be a partial upgrade. Nothing was installed." } +# The downloads were fetched and checked as the invoking user, in that user's own temporary +# directory, so another process of that user could still change them before root uses them. +# Under sudo, copy each listed file ("file sha256" lines on stdin) into a directory root owns +# (the user's shell opens the source, so root itself opens nothing the user named), check its +# sha256 again as root there, and use only that copy from then on: $work names it, and +# candidate_archives is rewritten to it. The directory is 0700 while files arrive and 0755 after +# (the user may read the packages, not change them). +# Until it is done, WORK_DOWNLOADS names the user's directory, so that the EXIT trap removes +# both directories when a copy or a check fails. +WORK_ROOT_OWNED=0 +WORK_DOWNLOADS="" +INSTALL_ARCHIVES=() +# Write stdin to FILE in $work. Under sudo that directory is root's, and the invoking user's +# side still reads these files: sudo keeps the user's umask, so set the mode here (0644), as +# work_to_root does. +work_write() { # FILE + $sudo sh -c 'umask 022 && cat >"$1"' _ "$1" +} +work_to_root() { + local old=$work new file sha + [[ -n $sudo ]] || return 0 + WORK_DOWNLOADS=$old + new=$($sudo mktemp -d) || die "could not make a work directory for root. Nothing was installed." + work=$new + WORK_ROOT_OWNED=1 + while read -r file sha; do + [[ -n $file ]] || continue + [[ $file != */* && $file != .* && $sha =~ ^[0-9a-f]{64}$ ]] || + die "unexpected release file entry '$file'. Nothing was installed." + $sudo sh -c 'umask 022 && cat >"$1"' _ "$new/$file" <"$old/$file" || + die "could not copy $file for root. Nothing was installed." + [[ $($sudo sha256sum -- "$new/$file" | cut -d' ' -f1) == "$sha" ]] || + die "$file changed after its checksum was checked. Nothing was installed." + done + $sudo chmod 0755 "$new" + candidate_archives=("${candidate_archives[@]/#"$old/"/"$new/"}") + rm -rf -- "$old" + WORK_DOWNLOADS="" +} + install_all() { local entry file sha kernel chain rc local -a entries candidate_archives=() @@ -4343,6 +4378,9 @@ install_all() { [[ -n $file ]] || continue candidate_archives+=("$work/$file") done < <(desktop_fixes_files) + # Root installs and runs only its own checked copy of what was downloaded (work_to_root). + work_to_root < <(printf '%s\n' "${entries[@]}"; desktop_fixes_files) + INSTALL_ARCHIVES=("${candidate_archives[@]}") if ((M3_GPU_PERSISTENT)); then m3_persistent_package_check "$work/${M3_PRO_MESA_PACKAGE%% *}"; fi m3_pro_perf_verify m3_pro_mesa_set_aside @@ -5040,6 +5078,39 @@ m3_adt_reader() { echo "$M3_WORK/$file" } +# Under sudo, root does not run the reader from where the invoking user's processes can write +# (the report's work directory, or a checkout): it runs a copy in a directory of its own +# (M3_ADT_ROOT), and checks that copy's sha256 against M3_ADT_READER's there, as root. The +# user's shell opens the source, so root opens nothing the user named. Sets M3_ADT_RUN to the +# reader to run; or, returning 1, M3_ADT_WHY to why there is none. Without sudo the reader is +# run where it is. +M3_ADT_ROOT="" M3_ADT_RUN="" M3_ADT_WHY="" +m3_adt_reader_root() { # READER + M3_ADT_RUN=$1 M3_ADT_WHY="" + [[ -n $sudo ]] || return 0 + m3_adt_reader_root_done + if ! M3_ADT_ROOT=$($sudo mktemp -d); then + M3_ADT_ROOT="" + M3_ADT_WHY="could not make a directory for root's copy of the ADT reader, so the ADT was not read" + return 1 + fi + M3_ADT_RUN=$M3_ADT_ROOT/${1##*/} + # shellcheck disable=SC2016 # expanded by that sh + if ! $sudo sh -c 'umask 022 && cat >"$1"' _ "$M3_ADT_RUN" <"$1"; then + M3_ADT_WHY="could not copy the ADT reader for root, so the ADT was not read" + return 1 + fi + if [[ -n $M3_ADT_READER && + $($sudo sha256sum -- "$M3_ADT_RUN" | cut -d' ' -f1) != "${M3_ADT_READER##* }" ]]; then + M3_ADT_WHY="${1##*/} changed after its checksum was checked, so the ADT was not read" + return 1 + fi +} +m3_adt_reader_root_done() { + if [[ -n $M3_ADT_ROOT ]]; then $sudo rm -rf -- "$M3_ADT_ROOT" || true; fi + M3_ADT_ROOT="" +} + # The largest adt region the report reads (an ADT is well under 1 MiB). M3_ADT_MAX_BYTES=$((16 * 1024 * 1024)) # The on-demand ADT read's state, for the traps: whether this run loaded phram, and the reader. @@ -5135,6 +5206,7 @@ m3_adt_unload() { # directory removed. m3_report_cleanup() { m3_adt_unload || true + m3_adt_reader_root_done if [[ -n $M3_PARTIAL ]]; then rm -f "$M3_PARTIAL"; fi if [[ -n $M3_WORK ]]; then rm -rf "$M3_WORK"; fi M3_WORK="" @@ -5205,11 +5277,13 @@ m3_report_adt() { # DIR for ((i = 0; i < 10; i++)); do [[ -e $dev ]] && break; sleep 0.5; done if [[ ! -e $dev ]]; then why="no read-only device node $dev, so the ADT was not read" - elif ! $sudo python3 "$reader" --check "$dev" >>"$log" 2>"$M3_WORK/adt.err"; then + elif ! m3_adt_reader_root "$reader"; then + why=$M3_ADT_WHY + elif ! $sudo python3 -I "$M3_ADT_RUN" --check "$dev" >>"$log" 2>"$M3_WORK/adt.err"; then why="the ADT reader's check refused $dev, so the ADT was not read: $(tail -1 "$M3_WORK/adt.err" 2>/dev/null | cut -c1-200 || true)" else echo "read: $dev with ${reader##*/}" >>"$log" - $sudo python3 "$reader" "$dev" >"$out" 2>"$M3_WORK/adt.err" & + $sudo python3 -I "$M3_ADT_RUN" "$dev" >"$out" 2>"$M3_WORK/adt.err" & M3_ADT_PID=$! wait "$M3_ADT_PID" || rc=$? M3_ADT_PID="" @@ -5218,7 +5292,7 @@ m3_report_adt() { # DIR else # Only after the ADT was read: phram made exactly the two regions' devices, and the adt # device matched its region, so the log device is its region's too. - m3_report_stage2_log "$1" "$reader" "$log" || true + m3_report_stage2_log "$1" "$M3_ADT_RUN" "$log" || true fi fi fi @@ -5237,6 +5311,7 @@ m3_report_adt() { # DIR echo "unload FAILED: phram stays loaded (in use after udev settled, twice; not forced)" >>"$log" fi fi + m3_adt_reader_root_done after=$(m3_mtd_inventory) printf '== after\n%s\n' "$after" >>"$log" if [[ $after == "$before" ]]; then @@ -5270,7 +5345,7 @@ m3_report_stage2_log() { # DIR READER LOG return 1 fi echo "log: $dev with ${reader##*/} --stage2-log" >>"$log" - $sudo python3 "$reader" --stage2-log "$dev" >"$out" 2>"$M3_WORK/log.err" & + $sudo python3 -I "$reader" --stage2-log "$dev" >"$out" 2>"$M3_WORK/log.err" & M3_ADT_PID=$! wait "$M3_ADT_PID" || rc=$? M3_ADT_PID="" @@ -5283,7 +5358,7 @@ m3_report_stage2_log() { # DIR READER LOG # And all 16 KiB of it, byte for byte but the same lines overwritten (a reader without --raw # leaves this file out). rc=0 - $sudo python3 "$reader" --stage2-log --raw "$dev" >"$1/m1n1-stage2-log.raw" 2>>"$M3_WORK/log.err" & + $sudo python3 -I "$reader" --stage2-log --raw "$dev" >"$1/m1n1-stage2-log.raw" 2>>"$M3_WORK/log.err" & M3_ADT_PID=$! wait "$M3_ADT_PID" || rc=$? M3_ADT_PID="" @@ -7093,6 +7168,7 @@ esp_history_builtin() { """Archive unreferenced EFI history while retaining boot and recovery entries.""" import argparse import contextlib +import errno import fcntl import hashlib import json @@ -7178,8 +7254,30 @@ def inventory(esp, state): return records +def compat_lock(path): + """fd of the compatibility lock older Omarchy Limine tools take (/tmp/limine-global.lock). + + It is created when missing (root's, 0600) and never followed through a + link. /tmp is world-writable, so anything else at that path (a file of + another user, a link, a FIFO, or a file fs.protected_regular will not let + root open) is refused: going on without the lock could let an older + Limine tool write the EFI partition at the same time.""" + try: + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, 0o600) + except OSError as error: + if error.errno in (errno.EACCES, errno.EPERM, errno.ELOOP, errno.ENXIO): + raise ValueError(f'{path} is not root\'s own lock file ({os.strerror(error.errno)}); ' + 'remove it and retry. Nothing was changed') from None + raise + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid(): + os.close(fd) + raise ValueError(f'{path} is not root\'s own lock file (a link, another user\'s file or ' + 'not a regular file); remove it and retry. Nothing was changed') + return fd + @contextlib.contextmanager -def lock(paths): +def lock(paths, compat=()): fds = [] try: for path in paths: @@ -7189,19 +7287,29 @@ def lock(paths): if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + for path in compat: + fd = compat_lock(path) + fds.append(fd) + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) yield finally: for fd in reversed(fds): os.close(fd) -def archive(esp, state, destination, lock_paths=None): +BOOT_LOCK = Path('/run/lock/boot-partition.lock') +COMPAT_LOCK = Path('/tmp/limine-global.lock') + + +def archive(esp, state, destination, lock_paths=None, compat_locks=None): esp, state, destination = esp.absolute(), state.absolute(), destination.absolute() destination.mkdir(parents=True, exist_ok=True) checked_tree(destination) if destination.resolve().is_relative_to(esp.resolve()) or os.stat(destination).st_dev == os.stat(esp).st_dev: raise ValueError('archive must be on a different filesystem from the EFI partition') - with lock(lock_paths or [Path('/run/lock/boot-partition.lock'), Path('/tmp/limine-global.lock')]): + if lock_paths is None: + lock_paths, compat_locks = [BOOT_LOCK], [COMPAT_LOCK] if compat_locks is None else compat_locks + with lock(lock_paths, compat_locks or ()): planned = inventory(esp, state) moved = [] for item in planned: @@ -7282,7 +7390,7 @@ esp_history_run() { [[ $(boot_chain) == limine ]] || die "EFI history archiving is available only with Limine" target=$(esp_bootbin) || die "could not find the mounted FAT boot partition" code=$(esp_history_builtin) - $sudo python3 -c "$code" "$1" --esp "${target%/m1n1/boot.bin}" --state "$STATE" \ + $sudo python3 -I -c "$code" "$1" --esp "${target%/m1n1/boot.bin}" --state "$STATE" \ --archive "$STATE/esp-history" || die "EFI history was retained where archive checks failed; retry after checking the error" } @@ -7320,8 +7428,9 @@ m3_install_cleanup() { fi fi fi - if ((FROZEN_PACKAGES)); then $sudo rm -rf "${work:-}" + if ((FROZEN_PACKAGES || WORK_ROOT_OWNED)); then $sudo rm -rf "${work:-}" else rm -rf "${work:-}"; fi + [[ -z $WORK_DOWNLOADS ]] || rm -rf -- "$WORK_DOWNLOADS" return "$status" } @@ -7329,7 +7438,7 @@ m3_persistent_transaction_begin() { local defaults=$M3_LIMINE_DEFAULTS target [[ $1 != grub ]] || defaults=$M3_GRUB_DEFAULTS target=$(esp_bootbin) || die "persistent GPU requires the mounted boot.bin" - $sudo python3 - "$STATE/m3-persistent-transaction.json" "$defaults" "$M1N1_CONF" "$target" \ + $sudo python3 -I - "$STATE/m3-persistent-transaction.json" "$defaults" "$M1N1_CONF" "$target" \ "$M3_GPU_OPTIN" "$M3_GPU_PROFILE_FILE" "$STATE/m3-gpu-persistent" "$STATE/m3-mode" \ "$M3_PROFILE_HOOK" "$M3_PROFILE_UPDATE" "$M3_GPU_CHECK" "$STATE/m3-gpu-check" <<'M3_TRANSACTION_BEGIN' import base64, json, os, stat, sys @@ -7351,7 +7460,7 @@ M3_TRANSACTION_BEGIN } m3_persistent_transaction_rollback() { - $sudo python3 - "$STATE/m3-persistent-transaction.json" <<'M3_TRANSACTION_ROLLBACK' + $sudo python3 -I - "$STATE/m3-persistent-transaction.json" <<'M3_TRANSACTION_ROLLBACK' import base64, json, os, stat, sys, tempfile from pathlib import Path snapshot=Path(sys.argv[1]) @@ -7392,7 +7501,16 @@ m3_install_packages() { M3_PRO_MESA_RESULT=installed fi else - $sudo pacman -U --noconfirm --ask 4 "$work"/*.pkg.tar.zst + # The checked archives (no glob over the directory), less a package set aside below it. + local archive + local -a archives=() + for archive in "${INSTALL_ARCHIVES[@]}"; do + [[ $archive == "$work"/*.pkg.tar.zst && -f $archive ]] && archives+=("$archive") + done + ((${#archives[@]})) || die "no checked package archives to install. Nothing was installed." + # In the order the directory listing gave them before. + mapfile -t archives < <(printf '%s\n' "${archives[@]}" | sort) + $sudo pacman -U --noconfirm --ask 4 "${archives[@]}" fi if ((M3_PRO_PERF_SELECTED)) && [[ -f $work/$(m3_pro_mesa_file) ]]; then M3_PRO_MESA_RESULT=installed; fi if ((M3_GPU_PERSISTENT)); then @@ -7419,7 +7537,7 @@ m3_persistent_cmdline() { if [[ $chain == grub ]]; then path=$M3_GRUB_DEFAULTS else path=$M3_LIMINE_DEFAULTS; fi [[ -f $STATE/m3-defaults.saved ]] || $sudo cp -p "$path" "$STATE/m3-defaults.saved" - $sudo python3 - "$path" "$chain" "$armed" "$M3_LIMINE_VENDOR_CONF" "$M3_PROCFS/cmdline" <<'M3_CMDLINE_PY' + $sudo python3 -I - "$path" "$chain" "$armed" "$M3_LIMINE_VENDOR_CONF" "$M3_PROCFS/cmdline" <<'M3_CMDLINE_PY' import os, re, sys, tempfile from pathlib import Path path, chain = Path(sys.argv[1]), sys.argv[2] @@ -7503,6 +7621,7 @@ m3_boot_profile_install() { """Retain the running Limine UKI and publish bounded experimental activation.""" import argparse import contextlib +import errno import fcntl import hashlib import json @@ -7539,16 +7658,42 @@ def atomic(path, data): finally: if os.path.exists(name): os.unlink(name) +def compat_lock(path): + """fd of the compatibility lock older Omarchy Limine tools take (/tmp/limine-global.lock). + + It is created when missing (root's, 0600) and never followed through a + link. /tmp is world-writable, so anything else at that path (a file of + another user, a link, a FIFO, or a file fs.protected_regular will not let + root open) is refused: going on without the lock could let an older + Limine tool write the EFI partition at the same time.""" + try: + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, 0o600) + except OSError as error: + if error.errno in (errno.EACCES, errno.EPERM, errno.ELOOP, errno.ENXIO): + raise ValueError(f'{path} is not root\'s own lock file ({os.strerror(error.errno)}); ' + 'remove it and retry. Nothing was changed') from None + raise + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid(): + os.close(fd) + raise ValueError(f'{path} is not root\'s own lock file (a link, another user\'s file or ' + 'not a regular file); remove it and retry. Nothing was changed') + return fd + @contextlib.contextmanager -def locks(paths, timeout=30.0): +def locks(paths, timeout=30.0, compat=()): deadline = time.monotonic() + timeout fds = [] try: - for path in paths: - path.parent.mkdir(parents=True, exist_ok=True) - fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) - fds.append(fd) - if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') + for path, required in [(p, True) for p in paths] + [(p, False) for p in compat]: + if required: + path.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) + fds.append(fd) + if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') + else: + fd = compat_lock(path) + fds.append(fd) while True: try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) @@ -7616,7 +7761,7 @@ def same_esp_path(left, right): return False def limine(args): - with locks(args.lock, args.lock_timeout): + with locks(args.lock, args.lock_timeout, args.compat_lock): loader = regular(args.esp / 'EFI/BOOT/BOOTAA64.EFI').read_bytes() if b'limine.conf' not in loader: raise ValueError('EFI loader is not Limine') sig = b'++CONFIG_B2SUM_SIGNATURE++' @@ -7739,11 +7884,16 @@ def main(): p.add_argument('--release', default=os.uname().release) p.add_argument('--modules', type=Path, default=Path('/usr/lib/modules')) p.add_argument('--lock', type=Path, action='append') + p.add_argument('--compat-lock', type=Path, action='append', + help='a lock in a shared directory: created if missing, refused unless a regular file of this user') p.add_argument('--lock-timeout', type=float, default=30.0, help='total boot-lock wait, in seconds (0..30)') args = p.parse_args() if not 0 <= args.lock_timeout <= 30: p.error('lock timeout must be between 0 and 30 seconds') - args.lock = args.lock or [Path('/run/lock/boot-partition.lock'), Path('/tmp/limine-global.lock')] + if not args.lock: + args.lock = [Path('/run/lock/boot-partition.lock')] + args.compat_lock = args.compat_lock or [Path('/tmp/limine-global.lock')] + args.compat_lock = args.compat_lock or [] try: limine(args) except (OSError, ValueError, KeyError) as e: p.exit(1, f'M3 boot profile refused: {e}\n') @@ -7771,7 +7921,7 @@ m3_limine_remove_check() { local target target=$(esp_bootbin) || die "cannot check the retained Limine entry without its mounted FAT boot partition; recovery state was kept" m3_boot_profile_install - $sudo python3 "$M3_BOOT_PROFILE_HELPER" "${1:-check-remove}" --esp "${target%/m1n1/boot.bin}" --state "$STATE" || + $sudo python3 -I "$M3_BOOT_PROFILE_HELPER" "${1:-check-remove}" --esp "${target%/m1n1/boot.bin}" --state "$STATE" || die "could not safely remove the retained Limine entry; its recovery state and modules were kept" if [[ ${1:-} == remove ]]; then $sudo rm -f "$M3_BOOT_PROFILE_HELPER"; fi } @@ -7781,7 +7931,7 @@ m3_keep_limine_entry() { target=$(esp_bootbin) || die "persistent GPU requires the mounted FAT boot partition" esp=${target%/m1n1/boot.bin} m3_boot_profile_install - $sudo python3 "$M3_BOOT_PROFILE_HELPER" "$1" --esp "$esp" --state "$STATE" --kernel "${kernel:-linux-aurora}" || + $sudo python3 -I "$M3_BOOT_PROFILE_HELPER" "$1" --esp "$esp" --state "$STATE" --kernel "${kernel:-linux-aurora}" || die "could not retain/publish the checked GPU-off Limine entry" if [[ $1 == retain ]]; then release=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["release"])' "$STATE/m3-known-entry.json") @@ -7811,7 +7961,7 @@ EOF } m3_grub_fallback_off() { - $sudo python3 - "$1" <<'M3_GRUB_OFF' + $sudo python3 -I - "$1" <<'M3_GRUB_OFF' from pathlib import Path import re, sys path=Path(sys.argv[1]);text=path.read_text() @@ -7842,7 +7992,7 @@ m3_persistent_cmdline_remove() { if [[ -f $path ]] && grep -qF '# >>> aurora-sep: M3 GPU cmdline' "$path"; then owned=1; fi done ((owned)) || return 0 - $sudo python3 - "$M3_GRUB_DEFAULTS" "$M3_LIMINE_DEFAULTS" <<'M3_REMOVE_CMDLINE' + $sudo python3 -I - "$M3_GRUB_DEFAULTS" "$M3_LIMINE_DEFAULTS" <<'M3_REMOVE_CMDLINE' from pathlib import Path import re, sys begin, end = '# >>> aurora-sep: M3 GPU cmdline', '# <<< aurora-sep: M3 GPU cmdline' @@ -7944,9 +8094,9 @@ m3_gpu_check_plan() { m3_gpu_check_install() { local sha m3_gpu_check_plan - m3_gpu_check_builtin >"$work/aurora-m3-gpu-check" + m3_gpu_check_builtin | work_write "$work/aurora-m3-gpu-check" sha=$(sha256sum "$work/aurora-m3-gpu-check" | cut -d' ' -f1) - $sudo python3 - "$work/aurora-m3-gpu-check" "$M3_GPU_CHECK" "$STATE/m3-gpu-check" "$sha" <<'M3_CHECK_INSTALL_PY' + $sudo python3 -I - "$work/aurora-m3-gpu-check" "$M3_GPU_CHECK" "$STATE/m3-gpu-check" "$sha" <<'M3_CHECK_INSTALL_PY' import hashlib, os, stat, sys, tempfile from pathlib import Path source, helper, record = map(Path, sys.argv[1:4]) @@ -8639,7 +8789,7 @@ neo_gpu_transaction_begin() { [[ $original_m1n1 == /* && -f $original_m1n1 && ! -L $original_m1n1 ]] || die "cannot preserve this Neo's original M1N1 binary: $original_m1n1" $sudo install -d "$STATE" - $sudo python3 - "$STATE/neo-transaction.json" "$UPDATE_M1N1_CONF" "$target" \ + $sudo python3 -I - "$STATE/neo-transaction.json" "$UPDATE_M1N1_CONF" "$target" \ "$NEO_GPU_CONFIG/profile" "$NEO_GPU_CONFIG/gpu-experiment" "$STATE/neo-gpu" "$original_m1n1" <<'NEO_SNAPSHOT' import base64,json,stat,sys from pathlib import Path @@ -8659,25 +8809,23 @@ NEO_SNAPSHOT } neo_gpu_boot_config() { - local tmp - tmp=$(mktemp) - if [[ -f $UPDATE_M1N1_CONF ]]; then - $sudo sed '/^# >>> aurora-sep: Neo stage2$/,/^# <<< aurora-sep: Neo stage2$/d' "$UPDATE_M1N1_CONF" > "$tmp" - fi - cat >>"$tmp" <<'NEO_BOOT_CONFIG' + local text + text=$({ if [[ -f $UPDATE_M1N1_CONF ]]; then + $sudo sed '/^# >>> aurora-sep: Neo stage2$/,/^# <<< aurora-sep: Neo stage2$/d' "$UPDATE_M1N1_CONF" + fi; } && cat <<'NEO_BOOT_CONFIG' # >>> aurora-sep: Neo stage2 M1N1=/usr/lib/m1n1-neo/m1n1.bin DTBS=$(pacman -Qlq linux-aurora 2>/dev/null | grep '/dtbs/[^/]*\.dtb$' || true) # <<< aurora-sep: Neo stage2 NEO_BOOT_CONFIG - $sudo install -Dm644 "$tmp" "$UPDATE_M1N1_CONF" - rm -f "$tmp" + ) + printf '%s\n' "$text" | root_put "$UPDATE_M1N1_CONF" } neo_gpu_restore() { local snapshot=$1 [[ -f $snapshot ]] || return 0 - $sudo python3 - "$snapshot" <<'NEO_RESTORE' + $sudo python3 -I - "$snapshot" <<'NEO_RESTORE' import base64,json,os,tempfile,sys from pathlib import Path for row in json.loads(Path(sys.argv[1]).read_text()): @@ -8738,20 +8886,19 @@ m3max_bootbin_record() { # one without the DTBS block m1n1_update wrote for the variant's rebuilds. Then frozen by this # script (m3_freeze), so no kernel or m1n1 update rebuilds the boot.bin that was put back. m3max_conf_kernel_only() { - local tmp + local text if [[ -f $STATE/update-m1n1.default.saved ]]; then $sudo install -m 644 "$STATE/update-m1n1.default.saved" "$UPDATE_M1N1_CONF" elif [[ -e $STATE/update-m1n1.absent ]]; then $sudo rm -f "$UPDATE_M1N1_CONF" elif [[ -f $UPDATE_M1N1_CONF ]]; then - tmp=$(mktemp) - $sudo sed -e '/^# aurora-sep: build m1n1/,/^DTBS=/d' -e '/^DTBS=/d' "$UPDATE_M1N1_CONF" >"$tmp" - if grep -q '[^[:space:]]' "$tmp"; then - $sudo install -m 644 "$tmp" "$UPDATE_M1N1_CONF" + text=$($sudo sed -e '/^# aurora-sep: build m1n1/,/^DTBS=/d' -e '/^DTBS=/d' "$UPDATE_M1N1_CONF" && printf x) + text=${text%x} + if [[ $text =~ [^[:space:]] ]]; then + printf '%s' "$text" | root_put "$UPDATE_M1N1_CONF" else $sudo rm -f "$UPDATE_M1N1_CONF" fi - rm -f "$tmp" fi m3_freeze } @@ -8867,7 +9014,8 @@ M3MAX_KIT_DEBUGFS=/sys/kernel/debug # arming script itself (the runner's copy; the setup's download before that). M3MAX_KIT_EFIVARS=/sys/firmware/efi/efivars M3MAX_KIT_CMDLINE=/proc/cmdline -M3MAX_KIT_LOCKS="/run/lock/boot-partition.lock /tmp/limine-global.lock" +M3MAX_KIT_LOCKS="/run/lock/boot-partition.lock" +M3MAX_KIT_COMPAT_LOCKS="/tmp/limine-global.lock" M3MAX_KIT_LIMINE_DEFAULTS=/etc/default/limine M3MAX_KIT_ONESHOT=$M3MAX_KIT_LIBEXEC/air-gpu-oneshot.sh M3MAX_KIT_JOB=$M3MAX_KIT_LIBEXEC/air-gpu-job.sh @@ -9181,6 +9329,7 @@ m3max_kit_oneshot_setup() { EFIVARS=$M3MAX_KIT_EFIVARS CMDLINE=$M3MAX_KIT_CMDLINE LOCKS=$M3MAX_KIT_LOCKS + COMPAT_LOCKS=$M3MAX_KIT_COMPAT_LOCKS LIMINE_DEFAULTS=$M3MAX_KIT_LIMINE_DEFAULTS check_board() { is_m3_max || refuse "this Mac ($(this_board), $(this_soc)) is not a 16-core M3 Max (t6031: $M3_MAX_BOARDS)." @@ -10580,16 +10729,20 @@ m3max_kit_identity() { # This script, on disk, into the work directory: the runner the kit installs. From a pipe # (curl ... | bash) it can't be read again, so this release's copy is downloaded, and it must # install exactly what this one does (m3max_kit_identity). +M3MAX_KIT_SELF_SHA="" m3max_kit_self() { local out=$M3MAX_KIT_WORK/install-aurora-sep.sh theirs rc=0 if [[ $SELF_SOURCE == file && -f $SELF_PATH ]]; then cp "$SELF_PATH" "$out" [[ $(sha256sum "$out" | cut -d' ' -f1) == "$SELF_SHA256" ]] || die "this script changed while it ran. Nothing was changed." + M3MAX_KIT_SELF_SHA=$SELF_SHA256 return 0 fi say "Downloading this release's install-aurora-sep.sh, for the kit's runner" fetch_release_file "$RELEASE_URL/install-aurora-sep.sh" "$out" || rc=$? ((rc == 0)) || die "could not download install-aurora-sep.sh from $TAG (curl exit $rc). Nothing was changed." + # The hash root's copy must have, taken before the identity check reads the file. + M3MAX_KIT_SELF_SHA=$(sha256sum "$out" | cut -d' ' -f1) # shellcheck disable=SC2016 # expanded by that bash theirs=$(bash -c 'AURORA_SEP_SOURCE_ONLY=1 source "$1" >/dev/null 2>&1 && m3max_kit_identity' _ "$out" 2>/dev/null) || theirs="" [[ -n $theirs && $theirs == "$(m3max_kit_identity)" ]] || @@ -10598,6 +10751,15 @@ m3max_kit_self() { chmod 0755 "$out" } +# As root, the kit's work directory must be root's own: its files are run and installed as root. +m3max_kit_work_is_root() { + local owner mode + [[ -d $M3MAX_KIT_WORK && ! -L $M3MAX_KIT_WORK ]] || die "the kit's work directory $M3MAX_KIT_WORK is missing. Nothing was changed." + read -r owner mode < <(stat -c '%u %a' "$M3MAX_KIT_WORK") + [[ $owner == "$EUID" ]] && (((8#$mode & 8#022) == 0)) || + die "the kit's work directory $M3MAX_KIT_WORK is not root's own (owner $owner, mode $mode). Nothing was changed." +} + # How many restarts the plan takes at most, and roughly how long, for the consent screen. m3max_kit_estimate() { local e max @@ -10726,15 +10888,64 @@ m3max_kit_setup() { # [--yes] [--kit-work DIR] if [[ -z $M3MAX_KIT_WORK ]]; then M3MAX_KIT_WORK=$(mktemp -d); fi M3MAX_KIT_USER_NAME=${SUDO_USER:-$(id -un)} # The kit runs as root from here (its state, its checks of the EFI variables, its runner), from - # this script's copy on disk. + # this script's copy on disk. Root does not run or install files from the invoking user's + # directory: it copies this + # script's checked copy into a directory of its own, opening it without following a link and + # only as a regular file of the invoking user's, checks the sha256 of its copy, and runs that + # copy with its own directory as the kit's work directory, where it downloads and checks the + # kit's other files itself. if [[ -n $sudo ]]; then m3max_kit_self say "The kit runs as root from here on (sudo may ask for your password)." a=() ((M3MAX_KIT_YES == 0)) || a=(--yes) - exec $sudo --preserve-env=AURORA_RELEASE_URL,AURORA_RELEASES_API bash "$M3MAX_KIT_WORK/install-aurora-sep.sh" \ - --m3max-kit --kit-work "$M3MAX_KIT_WORK" "${a[@]}" - fi + local rc=0 + # shellcheck disable=SC2016 # expanded by that bash + $sudo --preserve-env=AURORA_RELEASE_URL,AURORA_RELEASES_API bash -c ' + set -eu + d=$(mktemp -d) + if ! python3 -I - "$1" "$d/install-aurora-sep.sh" "$2" "$(id -u "$3")" <<"KIT_SELF_COPY_PY" +import hashlib, os, stat, sys +src, dst, want, uid = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4]) +fd = os.open(src, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) +st = os.fstat(fd) +if not stat.S_ISREG(st.st_mode) or st.st_uid != uid or st.st_size > 64 << 20: + sys.exit("not a regular file of the invoking user") +with os.fdopen(fd, "rb") as f: + data = f.read(64 << 20) +if hashlib.sha256(data).hexdigest() != want: + sys.exit("its sha256 differs from the checked one") +out = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC, 0o755) +os.fchmod(out, 0o755) +with os.fdopen(out, "wb") as f: + f.write(data) +KIT_SELF_COPY_PY + then + rm -rf "$d" + echo "install-aurora-sep: error: root could not take the kit script ($1) as checked. Nothing was changed." >&2 + exit 1 + fi + # The identity check again, on root'"'"'s own copy, which can no longer change: what is run + # is what was checked. The check sources the script, so it runs as the invoking user, on + # the descriptor root opened (the directory stays root'"'"'s alone). + as_user=() + [[ $(id -u) == "$(id -u "$3")" ]] || as_user=(runuser -u "$3" --) + theirs=$(${as_user[@]+"${as_user[@]}"} env AURORA_SEP_SOURCE_ONLY=1 \ + bash -c '"'"'source /dev/stdin >/dev/null 2>&1 && m3max_kit_identity'"'"' \ + <"$d/install-aurora-sep.sh" 2>/dev/null) || theirs="" + if [[ -z $theirs || $theirs != "$4" ]]; then + rm -rf "$d" + echo "install-aurora-sep: error: root'"'"'s copy of the kit script is not the script that runs now. Nothing was changed." >&2 + exit 1 + fi + shift 4 + exec bash "$d/install-aurora-sep.sh" --m3max-kit --kit-work "$d" "$@"' \ + _ "$M3MAX_KIT_WORK/install-aurora-sep.sh" "$M3MAX_KIT_SELF_SHA" "$(id -un)" "$(m3max_kit_identity)" \ + "${a[@]}" || rc=$? + rm -rf -- "$M3MAX_KIT_WORK" + exit "$rc" + fi + m3max_kit_work_is_root [[ -f $M3MAX_KIT_WORK/install-aurora-sep.sh ]] || m3max_kit_self m3max_kit_preflight m3max_kit_consent diff --git a/tools/aurora-sep/logind-aurora-sep.conf b/tools/aurora-sep/logind-aurora-sep.conf index a175c39f6ca73c..eb7d219ac7a259 100644 --- a/tools/aurora-sep/logind-aurora-sep.conf +++ b/tools/aurora-sep/logind-aurora-sep.conf @@ -6,6 +6,12 @@ # 5 s still powers off, cleanly. GNOME sessions and the GDM login screen # handle a short press themselves (power-button-action, suspend by default); # this covers everything else. +# +# Installed as 05-aurora-sep.conf. logind reads the drop-ins of /etc and +# /usr/lib in one list sorted by file name, and a later file wins, so this +# only replaces logind's built-in poweroff: a distribution's or an +# administrator's drop-in (HandlePowerKey=ignore for a compositor's power +# menu, for example) still decides. [Login] HandlePowerKey=suspend HandlePowerKeyLongPress=poweroff diff --git a/tools/aurora-sep/m3-boot-profile.py b/tools/aurora-sep/m3-boot-profile.py index ea681588c9ae7c..cefc808869f846 100644 --- a/tools/aurora-sep/m3-boot-profile.py +++ b/tools/aurora-sep/m3-boot-profile.py @@ -2,6 +2,7 @@ """Retain the running Limine UKI and publish bounded experimental activation.""" import argparse import contextlib +import errno import fcntl import hashlib import json @@ -38,16 +39,42 @@ def atomic(path, data): finally: if os.path.exists(name): os.unlink(name) +def compat_lock(path): + """fd of the compatibility lock older Omarchy Limine tools take (/tmp/limine-global.lock). + + It is created when missing (root's, 0600) and never followed through a + link. /tmp is world-writable, so anything else at that path (a file of + another user, a link, a FIFO, or a file fs.protected_regular will not let + root open) is refused: going on without the lock could let an older + Limine tool write the EFI partition at the same time.""" + try: + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, 0o600) + except OSError as error: + if error.errno in (errno.EACCES, errno.EPERM, errno.ELOOP, errno.ENXIO): + raise ValueError(f'{path} is not root\'s own lock file ({os.strerror(error.errno)}); ' + 'remove it and retry. Nothing was changed') from None + raise + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid(): + os.close(fd) + raise ValueError(f'{path} is not root\'s own lock file (a link, another user\'s file or ' + 'not a regular file); remove it and retry. Nothing was changed') + return fd + @contextlib.contextmanager -def locks(paths, timeout=30.0): +def locks(paths, timeout=30.0, compat=()): deadline = time.monotonic() + timeout fds = [] try: - for path in paths: - path.parent.mkdir(parents=True, exist_ok=True) - fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) - fds.append(fd) - if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') + for path, required in [(p, True) for p in paths] + [(p, False) for p in compat]: + if required: + path.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) + fds.append(fd) + if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') + else: + fd = compat_lock(path) + fds.append(fd) while True: try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) @@ -115,7 +142,7 @@ def same_esp_path(left, right): return False def limine(args): - with locks(args.lock, args.lock_timeout): + with locks(args.lock, args.lock_timeout, args.compat_lock): loader = regular(args.esp / 'EFI/BOOT/BOOTAA64.EFI').read_bytes() if b'limine.conf' not in loader: raise ValueError('EFI loader is not Limine') sig = b'++CONFIG_B2SUM_SIGNATURE++' @@ -238,11 +265,16 @@ def main(): p.add_argument('--release', default=os.uname().release) p.add_argument('--modules', type=Path, default=Path('/usr/lib/modules')) p.add_argument('--lock', type=Path, action='append') + p.add_argument('--compat-lock', type=Path, action='append', + help='a lock in a shared directory: created if missing, refused unless a regular file of this user') p.add_argument('--lock-timeout', type=float, default=30.0, help='total boot-lock wait, in seconds (0..30)') args = p.parse_args() if not 0 <= args.lock_timeout <= 30: p.error('lock timeout must be between 0 and 30 seconds') - args.lock = args.lock or [Path('/run/lock/boot-partition.lock'), Path('/tmp/limine-global.lock')] + if not args.lock: + args.lock = [Path('/run/lock/boot-partition.lock')] + args.compat_lock = args.compat_lock or [Path('/tmp/limine-global.lock')] + args.compat_lock = args.compat_lock or [] try: limine(args) except (OSError, ValueError, KeyError) as e: p.exit(1, f'M3 boot profile refused: {e}\n') diff --git a/tools/aurora-sep/packaging/arch/aurora-sep/PKGBUILD b/tools/aurora-sep/packaging/arch/aurora-sep/PKGBUILD index b9dc8bc9b33184..d9bc8e61c35303 100644 --- a/tools/aurora-sep/packaging/arch/aurora-sep/PKGBUILD +++ b/tools/aurora-sep/packaging/arch/aurora-sep/PKGBUILD @@ -7,7 +7,7 @@ pkgname=aurora-sep pkgver=1 -pkgrel=18 +pkgrel=19 pkgdesc="Loader and desktop integration for the Apple SEP (Touch ID) driver" url="https://github.com/aurora-silicon/linux/tree/aurora-wip/tools/aurora-sep" arch=(any) @@ -101,7 +101,7 @@ package() { sed 's|@FPRINTD@|/usr/lib/fprintd|' fprintd-no-timeout.conf.in \ >"$pkgdir/usr/lib/systemd/system/fprintd.service.d/50-aurora-sep-no-timeout.conf" install -Dm644 logind-aurora-sep.conf \ - "$pkgdir/usr/lib/systemd/logind.conf.d/50-aurora-sep.conf" + "$pkgdir/usr/lib/systemd/logind.conf.d/05-aurora-sep.conf" install -Dm755 sep-bio-identities "$pkgdir/usr/bin/sep-bio-identities" install -Dm755 aurora-sep "$pkgdir/usr/bin/aurora-sep" sed -i "s|^\(Exec[A-Za-z]*=\)/usr/local/sbin/|\1/usr/lib/aurora-sep/|" \ diff --git a/tools/aurora-sep/packaging/fedora/aurora-sep.spec b/tools/aurora-sep/packaging/fedora/aurora-sep.spec index 7a1ba80b0514d6..38f0aedd1ae574 100644 --- a/tools/aurora-sep/packaging/fedora/aurora-sep.spec +++ b/tools/aurora-sep/packaging/fedora/aurora-sep.spec @@ -8,7 +8,7 @@ Name: aurora-sep Version: 1 -Release: 13%{?dist} +Release: 15%{?dist} Summary: Loader and desktop integration for the Apple SEP fingerprint driver License: GPL-2.0-only @@ -108,7 +108,7 @@ grep -qx 'ExecStart=%{_libexecdir}/fprintd' %{_unitdir}/fprintd.service sed 's|@FPRINTD@|%{_libexecdir}/fprintd|' %{SOURCE7} \ >%{buildroot}%{_unitdir}/fprintd.service.d/50-aurora-sep-no-timeout.conf install -Dpm 0644 %{SOURCE8} \ - %{buildroot}%{_prefix}/lib/systemd/logind.conf.d/50-aurora-sep.conf + %{buildroot}%{_prefix}/lib/systemd/logind.conf.d/05-aurora-sep.conf install -Dpm 0755 %{SOURCE16} %{buildroot}%{_bindir}/sep-bio-identities install -Dpm 0755 %{SOURCE26} %{buildroot}%{_bindir}/aurora-sep sed -i "s|^\(Exec[A-Za-z]*=\)/usr/local/sbin/|\1%{_libexecdir}/|" \ @@ -189,7 +189,7 @@ fi %dir %{_unitdir}/fprintd.service.d %{_unitdir}/fprintd.service.d/aurora-sep.conf %{_unitdir}/fprintd.service.d/50-aurora-sep-no-timeout.conf -%{_prefix}/lib/systemd/logind.conf.d/50-aurora-sep.conf +%{_prefix}/lib/systemd/logind.conf.d/05-aurora-sep.conf %{_presetdir}/80-aurora-sep.preset %files selinux @@ -197,6 +197,16 @@ fi %ghost %verify(not md5 size mode mtime) %{_sharedstatedir}/selinux/%{selinuxtype}/active/modules/200/%{modulename} %changelog +* Wed Nov 25 2026 Matt - 1-15 +- aurora-sep-selinux 1.4.0: label the kernel's catacomb replacement files + (/var/lib/.apple-sep-catacomb-*.bin.new) as SEP state at creation, and let + the kernel set the mode of (setattr), rename and unlink state files. Install + it before a kernel that publishes catacombs by atomic replacement. + +* Sat Nov 21 2026 Ryan Murray - 1-14 +- Install the logind drop-in as 05-aurora-sep.conf, so that a distribution's + or an administrator's power key setting overrides it + * Fri Nov 20 2026 Diljit Singh - 1-13 - SEP writes are always on: aurora-sep-load runs modprobe apple_sep with no options, since the driver no longer has xart_writes or provision_keybag diff --git a/tools/aurora-sep/recipes/mesa-m3/72-mesa-m3-render-node.rules b/tools/aurora-sep/recipes/mesa-m3/72-mesa-m3-render-node.rules index e3e12617f58a0c..b31ca3e18a8860 100644 --- a/tools/aurora-sep/recipes/mesa-m3/72-mesa-m3-render-node.rules +++ b/tools/aurora-sep/recipes/mesa-m3/72-mesa-m3-render-node.rules @@ -6,6 +6,8 @@ # compositor started without the M3 Mesa that renders through an EGL device on # such a node, such as the SDDM greeter's Hyprland (user sddm), stops at start. # Without access to the node it renders in software. Other Apple GPUs are not -# matched. +# matched. Neither are the 7.3 kernels' "aurora" driver and the native G15 +# backend's "asahi-g15" and "aurora-g15": there the system Mesa is not +# refused, so the node stays as the kernel and system rules set it. SUBSYSTEM=="drm", KERNEL=="renderD*", DRIVERS=="asahi", ATTR{device/of_node/compatible}=="apple,agx-t6030", GROUP="render", MODE="0660" SUBSYSTEM=="drm", KERNEL=="renderD*", DRIVERS=="asahi", ATTR{device/of_node/compatible}=="apple,agx-t8122", GROUP="render", MODE="0660" diff --git a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD index e9ea066a21b461..a4d4e4ec12c3ee 100644 --- a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD +++ b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD @@ -10,7 +10,7 @@ # No profile selection substitutes another Mac's firmware or calibration. pkgname=mesa-m3 pkgver=26.1.4.m3.2 -pkgrel=5 +pkgrel=9 _commit=7ff89a4da387bd561b78efd5f09c98ca8ae18538 pkgdesc="Mesa in /opt/mesa-m3 for the M3 Pro (G15S) and M3 (G15G) GPUs; used by uwsm sessions on T6030, and on T8122 when opted in" arch=('aarch64') @@ -65,7 +65,8 @@ source=("mesa-m3-src-${_commit:0:11}.tar.zst" 72-mesa-m3-render-node.rules mesa-m3-session-confirm mesa-m3-session-confirm.service - mesa-m3-wlcheck.c) + mesa-m3-wlcheck.c + mesa-m3-system-check.c) sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '535e26266e1d173bfd2f73e63be07eccf32eb9cb329ea8955e32a4fa45278ce8' '9be098fc0a1ec38632678ece7d6d7b743d25df4a1af59ce3d17ba3a4eed34db7' @@ -84,18 +85,19 @@ sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '10abda78df16e650a77443f50cc46a15e418c42d4d9680c6a61616b232c9bdef' '6c98fab6f9d70449bd7f5258c34eac773836908e060ce5bef86dc5b0ce595e61' '826016665cd0424a614b67add921c0c79c3c698a4d104ea5712518449b75f27c' - '2b2eb627459f73aa596812503c48fc64331e925015bb7121e1888d18cac65b5e' + '93f93d2333ce273137e61be438914db84c9a970428efa6f7febae2c39ec50530' '6144af8b2e0f04ea615e8c4149e69c45ac49e630c46b2a58f0d1095d977798b2' '530948fc1a124de21c030a497e2ef5351742ba4ad4653484fe30fd1697ad7141' '644cf4a5ab57b7badec75843e2899b68d41490c4851d6885227180d6090c25ea' '9a26a232fd050b6207bd0d385035723f72ffd2b6b72a25d6ac92ae2f99ea5b66' '34f8bb3fa505718dab176b6283dde0d4de9cae4c3928922bca18e6052434bca7' - '7e7914877c5f1ccc85b985b071c838271608c78f858489d69b7a3ba64c4f51f0' - '8f19ebea2b8e669a764d7c4b40ecbc11e8234acfc3a2bfe7910e22de0b64a49d' - '9c7c3050d3ec15fce80a6e59d099567b396f1844a43695aa4377e02ac696f566' + '04fae9bf32a09a574b6ed9ab9d7afb97340df252b9269ed789303e8561a61a21' + '96c3101c15c73d26cd3086bc8ac4e8eb35d42300d495ca0ffd2bd03960ef3332' + '807be84fcaf6e68cb7f787886d070ac9778c778127c05267060872e6cfe3cf3b' '2a15cfdbc160b78e5a3a8e99d5898d40a54db28592f1a4ce04a600990a731f87' '7eaae7de828e15208fccc84db2b910f38bb1288176419f7af7f4675b5c542ce4' - 'c888e9dce99e8379aa21e9c5895cbe1b7e879a9319bca144193eddc66f9d4051') + 'c888e9dce99e8379aa21e9c5895cbe1b7e879a9319bca144193eddc66f9d4051' + '76f2661e715a96e3095168efa380c78d6303a84a4a11bbdfb573b09a22df65d6') # The qualified M3 Pro build's generated kernel files and libclc. build() stops # when one of ours differs. libagx_shaders.c is compared through kernel-digest.py: @@ -296,6 +298,8 @@ EOF ${CC:-cc} ${CFLAGS} -Wall -I. -o mesa-m3-probe mesa-m3-probe.c ${LDFLAGS} \ -lEGL -lGLESv2 -lvulkan -lwayland-client -lwayland-egl ${CC:-cc} ${CFLAGS} -Wall -o mesa-m3-loadcheck mesa-m3-loadcheck.c ${LDFLAGS} + ${CC:-cc} ${CFLAGS} -std=c11 -Wall -Wextra -Werror -I"$_src/include" \ + -o mesa-m3-system-check mesa-m3-system-check.c ${LDFLAGS} -ldl ${CC:-cc} ${CFLAGS} -Wall -I"$_src/include" $(pkg-config --cflags libdrm) \ -o mesa-m3-abi-check mesa-m3-abi-check.c ${LDFLAGS} $(pkg-config --libs libdrm) ${CC:-cc} ${CFLAGS} -Wall -DMESA_M3_GL_ONLY -I. -o mesa-m3-native-probe mesa-m3-probe.c ${LDFLAGS} \ @@ -341,6 +345,7 @@ package_mesa-m3() { install -Dm755 gpu-heat "${pkgdir}${_prefix}/bin/gpu-heat" install -Dm755 mesa-m3-probe "${pkgdir}${_prefix}/bin/mesa-m3-probe" install -Dm755 mesa-m3-loadcheck "${pkgdir}${_prefix}/libexec/mesa-m3-loadcheck" + install -Dm755 mesa-m3-system-check "${pkgdir}${_prefix}/libexec/mesa-m3-system-check" install -Dm644 mesa-m3-session-env "${pkgdir}${_prefix}/libexec/mesa-m3-session-env" install -Dm755 mesa-m3-user-setup "${pkgdir}${_prefix}/libexec/mesa-m3-user-setup" install -Dm644 user-setup.list "${pkgdir}${_prefix}/share/mesa-m3/user-setup.list" diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env index 5abbf89f8567f8..468ff75bfd4d4b 100644 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env @@ -59,15 +59,29 @@ # active all passed: the session uses /opt/mesa-m3 # M1, M2, the M3 Max and anything else are left alone. # -# When it does not use /opt/mesa-m3 but an M3 render node is there and this -# user can open it, the system Mesa would be refused by the kernel (it is not -# M3-aware), and a compositor that renders through an EGL device on that node -# (Hyprland) would stop at start. For every inactive reason except user-setup +# When it does not use /opt/mesa-m3 but an M3 render node of the pre-7.3 +# "asahi" driver is there and this user can open it, the system Mesa would be +# refused by the kernel (it is not M3-aware), and a compositor that renders +# through an EGL device on that node (Hyprland) would stop at start. On the +# 7.3 kernels' "aurora" driver, and on the native G15 backend's "asahi-g15" +# (7.2) or "aurora-g15" (7.3) driver that a kernel built with +# CONFIG_DRM_ASAHI_G15 binds to the T6030, the system Mesa is not refused, so +# none of this applies there: the session keeps it (fallback=none), whatever +# the reason. +# For every inactive reason on an "asahi" node except user-setup # it therefore exports LIBGL_ALWAYS_SOFTWARE=1 (and MESA_M3_FALLBACK=software, # which marks it as this hook's): the session renders in software. For # user-setup it exports nothing: the session's own Mesa setup, which it uses, # decides. The state file says which (fallback=software|none). # +# A file opt-out (/etc/mesa-m3/disable or the user's mesa-m3/disable) on a +# single-board T8122 or T6030 is the exception: when the same node, +# display, kernel-log, user-setup and same-boot attempt checks pass and +# mesa-m3-system-check admits /usr, the session keeps system Mesa +# (fallback=none, no new attempt). The whole check runs in its own sh and is +# refused after 20 seconds. mesa_m3=off stays on the software fallback (on an +# "asahi" node). +# # Each login writes /run/user//mesa-m3-session.state (atomically, 0644, # key=value lines, first line schema=aurora.mesa-m3-session/2) and logs one # journal line (tag mesa-m3) with the same decision, reason and login identity, @@ -133,16 +147,9 @@ mesa_m3_gate() { echo "no-gpu render node ${_mm3_node##*/} is not the $_mm3_name GPU (apple,agx-$_mm3_soc)"; return 1 fi - _mm3_dcp= - for _mm3_c in "$_mm3_root"/sys/class/drm/card*; do - case "${_mm3_c##*/}" in *-*) continue ;; esac - if tr '\0' '\n' 2>/dev/null < "$_mm3_c/device/of_node/compatible" | grep -qx "apple,$_mm3_soc-display-subsystem"; then - _mm3_dcp=${_mm3_c##*/} - fi - done - if [ -z "$_mm3_dcp" ]; then + _mm3_dcp=$(_mm3_native_display "$_mm3_root" "$_mm3_soc") || { echo "no-display no native display card (apple,$_mm3_soc-display-subsystem)"; return 1 - fi + } _mm3_dev="$_mm3_root/dev/dri/${_mm3_node##*/}" if [ ! -r "$_mm3_dev" ] || [ ! -w "$_mm3_dev" ]; then @@ -250,53 +257,19 @@ mesa_m3_gate() { echo "load-failed mesa-m3-loadcheck exit $_mm3_rc: ${_mm3_out:-no output}"; return 1 fi - # The kernel log of this boot must be readable (a user without journal - # access would otherwise see no faults) and must show no fault of the M3 - # GPU or of the display. journalctl exits 1 both for "no match" and for - # errors, so the log is read whole and searched with grep: a failed read, - # an empty log or a grep error refuses (fail closed). The failure state of - # the M3 GPU is sticky for the boot, so a fault means software rendering - # until reboot. - _mm3_out=$(journalctl -k -b -q --no-pager -o cat 2>/dev/null) - _mm3_rc=$? - if [ "$_mm3_rc" -ne 0 ] || [ -z "$_mm3_out" ]; then - echo "log-unreadable this user cannot read this boot's kernel log (only root and the wheel, adm and systemd-journal groups can), so GPU faults cannot be ruled out; to allow GPU acceleration, add the user to the adm group and log in again" - return 1 - fi - _mm3_faults=$(printf '%s\n' "$_mm3_out" | grep -E \ - -e 'M3 scheduler: execution failed|M3 G15[SG]: firmware crashed|M3 firmware error|M3 bank [0-9]|native DCP flip failed|DCP firmware crashed' \ - -e 'M3 G15G verdict: (firmware-running-check-failed|initdata-rejected|cap-violated|job-failed-before-wait|job-faulted|job-ran-completion-missed|job-accepted-never-dispatched|job-timed-out)') - _mm3_rc=$? - if [ "$_mm3_rc" -eq 0 ]; then - echo "gpu-fault the M3 GPU or the display failed this boot, so GPU acceleration is off until reboot: $(printf '%s\n' "$_mm3_faults" | tail -n 1 | tr -d '\r')" - return 1 - elif [ "$_mm3_rc" -ne 1 ]; then - echo "log-unreadable this boot's kernel log could not be searched (grep exit $_mm3_rc)"; return 1 - fi + # The kernel log of this boot must be readable and must show no fault of + # the M3 GPU or of the display. The same fail-closed read is what a file + # opt-out uses before it will leave the system Mesa in place. + _mm3_klog=$(_mm3_kernel_log) || { echo "$_mm3_klog"; return 1; } # A login that chose /opt/mesa-m3 earlier this boot must have a success # marker bound to it (same boot_id, session_id and hook_run_id), written by # mesa-m3-session-confirm.service only after its compositor was alive and # answering on its Wayland socket after the settle time. Otherwise this # login stays off it: no login loop when the compositor cannot run on it. - _mm3_att="$_mm3_root${XDG_STATE_HOME:-$HOME/.local/state}/mesa-m3/attempt" - _mm3_ok="$_mm3_root${XDG_STATE_HOME:-$HOME/.local/state}/mesa-m3/session-ok" - if [ -f "$_mm3_att" ]; then - _mm3_boot= - [ -r "$_mm3_root/proc/sys/kernel/random/boot_id" ] && - IFS= read -r _mm3_boot < "$_mm3_root/proc/sys/kernel/random/boot_id" - if [ "$(sed -n 's/^boot_id=//p' "$_mm3_att" 2>/dev/null | head -n 1)" = "$_mm3_boot" ]; then - _mm3_v=$(sed -n 's/^hook_run_id=//p' "$_mm3_att" 2>/dev/null | head -n 1) - _mm3_val=$(sed -n 's/^session_id=//p' "$_mm3_att" 2>/dev/null | head -n 1) - if [ -z "$_mm3_v" ] || [ ! -f "$_mm3_ok" ] || - [ "$(head -n 1 "$_mm3_ok" 2>/dev/null)" != schema=aurora.mesa-m3-session-ok/1 ] || - [ "$(sed -n 's/^boot_id=//p' "$_mm3_ok" 2>/dev/null | head -n 1)" != "$_mm3_boot" ] || - [ "$(sed -n 's/^hook_run_id=//p' "$_mm3_ok" 2>/dev/null | head -n 1)" != "$_mm3_v" ] || - [ "$(sed -n 's/^session_id=//p' "$_mm3_ok" 2>/dev/null | head -n 1)" != "$_mm3_val" ]; then - echo "previous-failed the last login with /opt/mesa-m3 this boot (hook_run_id ${_mm3_v:-unknown}) has no success marker: its compositor was not seen alive and answering, so this login renders in software; to try the GPU again: rm $_mm3_att, then log out and in (or reboot)" - return 1 - fi - fi + if ! _mm3_legacy_attempt_clear "$_mm3_root"; then + echo "previous-failed the last login with /opt/mesa-m3 this boot (hook_run_id ${_mm3_v:-unknown}) has no success marker: its compositor was not seen alive and answering, so this login renders in software; to try the GPU again: rm $_mm3_att, then log out and in (or reboot)" + return 1 fi if [ "${_mm3_ign:-0}" -gt 0 ]; then @@ -341,7 +314,10 @@ _mm3_25g83_board() { # _mm3_node_open ROOT: this is a T6030 or T8122 with a render node of its # asahi M3 GPU (among any others) that this user can open: the system Mesa -# would be refused on it. +# would be refused on it. Only the pre-7.3 "asahi" driver counts: on the +# 7.3 "aurora" driver and the G15 backend's "asahi-g15" and "aurora-g15" the +# system Mesa is not refused, so a session that does not use /opt/mesa-m3 +# keeps it instead of falling back to software. _mm3_node_open() { _mm3_soc=$(_mm3_soc_of "$1") [ -n "$_mm3_soc" ] || return 1 @@ -354,6 +330,157 @@ _mm3_node_open() { return 1 } +# _mm3_native_display ROOT SOC: the card name of this SoC's native display, +# or nothing. A connector name (card2-eDP-1) is not a card. The last match +# wins, as the gate's own walk did. +_mm3_native_display() { + _mm3_dcp= + for _mm3_c in "$1"/sys/class/drm/card*; do + case "${_mm3_c##*/}" in *-*) continue ;; esac + if tr '\0' '\n' 2>/dev/null < "$_mm3_c/device/of_node/compatible" | grep -qx "apple,$2-display-subsystem"; then + _mm3_dcp=${_mm3_c##*/} + fi + done + [ -n "$_mm3_dcp" ] || return 1 + printf '%s\n' "$_mm3_dcp" +} + +# Fail closed. Prints one "log-unreadable ..." or "gpu-fault ..." line and +# returns 1 unless this boot's kernel log was read and contains none of the +# M3 GPU or display faults. journalctl exits 1 both for "no match" and for +# errors, so the log is read whole and searched with grep. A failed read, an +# empty log or a grep error refuses. The GPU failure state is sticky for the +# boot. +_mm3_kernel_log() { + _mm3_out=$(journalctl -k -b -q --no-pager -o cat 2>/dev/null) + _mm3_rc=$? + if [ "$_mm3_rc" -ne 0 ] || [ -z "$_mm3_out" ]; then + echo "log-unreadable this user cannot read this boot's kernel log (only root and the wheel, adm and systemd-journal groups can), so GPU faults cannot be ruled out; to allow GPU acceleration, add the user to the adm group and log in again" + return 1 + fi + _mm3_faults=$(printf '%s\n' "$_mm3_out" | grep -E \ + -e 'M3 scheduler: execution failed|M3 G15[SG]: firmware crashed|M3 firmware error|M3 bank [0-9]|native DCP flip failed|DCP firmware crashed' \ + -e 'M3 G15G verdict: (firmware-running-check-failed|initdata-rejected|cap-violated|job-failed-before-wait|job-faulted|job-ran-completion-missed|job-accepted-never-dispatched|job-timed-out)') + _mm3_rc=$? + if [ "$_mm3_rc" -eq 0 ]; then + echo "gpu-fault the M3 GPU or the display failed this boot, so GPU acceleration is off until reboot: $(printf '%s\n' "$_mm3_faults" | tail -n 1 | tr -d '\r')" + return 1 + elif [ "$_mm3_rc" -ne 1 ]; then + echo "log-unreadable this boot's kernel log could not be searched (grep exit $_mm3_rc)"; return 1 + fi + return 0 +} + +# Return 0 when this boot has no unmatched /opt/mesa-m3 attempt. Return 1 +# when an attempt for this boot_id has no success marker bound to its +# hook_run_id and session_id. Never creates, deletes or rewrites either file. +# On failure, _mm3_att and _mm3_v are the attempt path and its hook_run_id. +_mm3_legacy_attempt_clear() { + _mm3_att="$1${XDG_STATE_HOME:-$HOME/.local/state}/mesa-m3/attempt" + _mm3_ok="$1${XDG_STATE_HOME:-$HOME/.local/state}/mesa-m3/session-ok" + [ -f "$_mm3_att" ] || return 0 + _mm3_boot= + [ -r "$1/proc/sys/kernel/random/boot_id" ] && + IFS= read -r _mm3_boot < "$1/proc/sys/kernel/random/boot_id" + [ "$(sed -n 's/^boot_id=//p' "$_mm3_att" 2>/dev/null | head -n 1)" = "$_mm3_boot" ] || return 0 + _mm3_v=$(sed -n 's/^hook_run_id=//p' "$_mm3_att" 2>/dev/null | head -n 1) + _mm3_val=$(sed -n 's/^session_id=//p' "$_mm3_att" 2>/dev/null | head -n 1) + if [ -z "$_mm3_v" ] || [ ! -f "$_mm3_ok" ] || + [ "$(head -n 1 "$_mm3_ok" 2>/dev/null)" != schema=aurora.mesa-m3-session-ok/1 ] || + [ "$(sed -n 's/^boot_id=//p' "$_mm3_ok" 2>/dev/null | head -n 1)" != "$_mm3_boot" ] || + [ "$(sed -n 's/^hook_run_id=//p' "$_mm3_ok" 2>/dev/null | head -n 1)" != "$_mm3_v" ] || + [ "$(sed -n 's/^session_id=//p' "$_mm3_ok" 2>/dev/null | head -n 1)" != "$_mm3_val" ]; then + return 1 + fi + return 0 +} + +# File opt-out on a single-board T8122 or T6030 may keep the system Mesa. Prints +# one detail line and returns 0 only when every check below passes. A helper +# exit of 0 is not enough on its own. Does not write an attempt or touch a +# marker. mesa_m3=off is not a file opt-out. +_mm3_system_admit() { + case ${XDG_CURRENT_DESKTOP:-} in Hyprland|hyprland) ;; *) return 1 ;; esac + _mm3_cmdline=$(cat "$1/proc/cmdline" 2>/dev/null) || return 1 + case " $_mm3_cmdline " in + *" mesa_m3=off "*|*" nomodeset "*) return 1 ;; + esac + if [ ! -e "$1/etc/mesa-m3/disable" ] && + [ ! -e "$1${XDG_CONFIG_HOME:-$HOME/.config}/mesa-m3/disable" ]; then + return 1 + fi + _mm3_dt=$(tr '\0' '\n' 2>/dev/null < "$1/proc/device-tree/compatible") + _mm3_soc=$(_mm3_soc_of "$1") + _mm3_chip= + _mm3_identity=$(printf '%s\n' "$_mm3_dt" | grep -E '^apple,j') + _mm3_socs=$(printf '%s\n' "$_mm3_dt" | grep -E '^apple,t') + # Any board of this SoC: exactly one board compatible, and exactly one SoC + # compatible, which is the SoC the GPU checks below are keyed on. + case "$_mm3_soc" in t8122|t6030) ;; *) return 1 ;; esac + [ "$_mm3_socs" = "apple,$_mm3_soc" ] || return 1 + [ -n "$_mm3_identity" ] && + [ "$(printf '%s\n' "$_mm3_identity" | wc -l)" -eq 1 ] || return 1 + _mm3_chip=$_mm3_soc + # Exactly one render node, and it is this SoC's asahi GPU, and this user + # can open it. An any-node match is not enough. + _mm3_nodes=0 + _mm3_node= + for _mm3_n in "$1"/sys/class/drm/renderD*; do + [ -e "$_mm3_n" ] || continue + _mm3_nodes=$((_mm3_nodes + 1)) + _mm3_node=$_mm3_n + done + [ "$_mm3_nodes" -eq 1 ] || return 1 + # The GPU's platform driver is "asahi" before 7.3 and "aurora" from 7.3 on + # (2d76bcead7cc; "asahi" is then only its module alias). A kernel built + # with the native G15 backend (CONFIG_DRM_ASAHI_G15) binds the T6030 to + # that backend's own driver instead: "asahi-g15" on 7.2, "aurora-g15" on + # 7.3. mesa-m3-system-check below still decides whether /usr drives it. + _mm3_drv=$(basename "$(readlink -f "$_mm3_node/device/driver" 2>/dev/null)" 2>/dev/null) + case "$_mm3_drv" in + aurora | aurora-g15 | asahi | asahi-g15) ;; + *) return 1 ;; + esac + tr '\0' '\n' 2>/dev/null < "$_mm3_node/device/of_node/compatible" | grep -qx "apple,agx-$_mm3_chip" || return 1 + _mm3_dev="$1/dev/dri/${_mm3_node##*/}" + [ -r "$_mm3_dev" ] && [ -w "$_mm3_dev" ] || return 1 + _mm3_dcp=$(_mm3_native_display "$1" "$_mm3_chip") || return 1 + _mm3_legacy_attempt_clear "$1" || return 1 + _mm3_klog=$(_mm3_kernel_log) || return 1 + if [ -n "$1" ]; then + _mm3_out=$("$1$_mm3_p/libexec/mesa-m3-user-setup" --home "$HOME" \ + --config-home "${XDG_CONFIG_HOME:-$HOME/.config}" --env --system-provider \ + --session-desktops "${XDG_CURRENT_DESKTOP:-}" --root "$1" 2>&1) + else + _mm3_out=$("$_mm3_p/libexec/mesa-m3-user-setup" --home "$HOME" \ + --config-home "${XDG_CONFIG_HOME:-$HOME/.config}" --env --system-provider \ + --session-desktops "${XDG_CURRENT_DESKTOP:-}" 2>&1) + fi + [ "$?" -eq 0 ] || return 1 + if [ -n "$1" ]; then + _mm3_helper=$1/opt/mesa-m3/libexec/mesa-m3-system-check + else + _mm3_helper=/opt/mesa-m3/libexec/mesa-m3-system-check + fi + [ -x "$_mm3_helper" ] || return 1 + # The helper sees a clean environment: a leaked GL preload or path must + # not decide /usr's renderer. Five seconds, then kill. + timeout -k 2 5 env -i PATH=/usr/bin:/bin "$_mm3_helper" \ + "/dev/dri/${_mm3_node##*/}" "$_mm3_chip" >/dev/null 2>&1 + [ "$?" -eq 0 ] || return 1 + printf '%s\n' "system Mesa on /usr admits /dev/dri/${_mm3_node##*/} ($_mm3_chip); /opt/mesa-m3 stays inactive" +} + +# _mm3_system_admit in its own sh, under one timeout for the whole check. A +# stalled journal, home directory or scanner would otherwise hold this login +# before any fallback is exported. A timeout refuses, as any failure does. +_mm3_system_admit_bounded() { + _mm3_self=${1:-}/opt/mesa-m3/libexec/mesa-m3-session-env + [ -r "$_mm3_self" ] || return 1 + timeout -k 2 20 sh -c 'MESA_M3_SESSION_ENV_NO_RUN=1 . "$1" && _mm3_p=$3 && _mm3_system_admit "$2"' \ + sh "$_mm3_self" "${1:-}" "$_mm3_p" +} + # _mm3_state ROOT DECISION REASON DETAIL FALLBACK: write the state file and the journal # line. A value holding a newline or carriage return is refused. _mm3_state() { @@ -455,23 +582,44 @@ mesa_m3_session_env() { _mm3_attempt "${1:-}" else # Never the system Mesa on an M3 render node it can open (Hyprland - # would stop at start), except where this session's own setup chose. + # would stop at start), except where this session's own setup chose, + # or a file opt-out whose system-Mesa handoff passed. _mm3_fb=none - if [ "${_mm3_decision%% *}" != user-setup ] && _mm3_node_open "${1:-}"; then + _mm3_detail=${_mm3_decision#* } + _mm3_admitted=0 + if [ "${_mm3_decision%% *}" = opt-out ]; then + _mm3_sys=$(_mm3_system_admit_bounded "${1:-}") + if [ "$?" -eq 0 ]; then + _mm3_admitted=1 + _mm3_detail="$_mm3_detail; $_mm3_sys" + # Only the pair this hook itself exports. Anything else in the + # environment, including a user's own LIBGL_ALWAYS_SOFTWARE + # without this marker, stays. + if [ "${LIBGL_ALWAYS_SOFTWARE:-}" = 1 ] && [ "${MESA_M3_FALLBACK:-}" = software ]; then + unset LIBGL_ALWAYS_SOFTWARE + unset MESA_M3_FALLBACK + fi + fi + fi + if [ "$_mm3_admitted" -eq 0 ] && [ "${_mm3_decision%% *}" != user-setup ] && _mm3_node_open "${1:-}"; then export LIBGL_ALWAYS_SOFTWARE=1 export MESA_M3_FALLBACK=software _mm3_fb=software fi - _mm3_state "${1:-}" inactive "${_mm3_decision%% *}" "${_mm3_decision#* }" "$_mm3_fb" + _mm3_state "${1:-}" inactive "${_mm3_decision%% *}" "$_mm3_detail" "$_mm3_fb" fi } if [ -z "${MESA_M3_SESSION_ENV_NO_RUN:-}" ]; then mesa_m3_session_env - unset -f mesa_m3_gate mesa_m3_session_env _mm3_init _mm3_state _mm3_node_open _mm3_attempt _mm3_soc_of _mm3_25g83_board + unset -f mesa_m3_gate mesa_m3_session_env _mm3_init _mm3_state _mm3_node_open _mm3_attempt \ + _mm3_soc_of _mm3_25g83_board _mm3_native_display _mm3_kernel_log \ + _mm3_legacy_attempt_clear _mm3_system_admit _mm3_system_admit_bounded fi unset _mm3_root _mm3_p _mm3_nodes _mm3_node _mm3_n _mm3_drv _mm3_dcp _mm3_c _mm3_dev _mm3_f _mm3_v \ _mm3_val _mm3_ifs _mm3_d _mm3_out _mm3_rc _mm3_decision _mm3_on \ _mm3_so _mm3_uid _mm3_sid _mm3_inv _mm3_ver _mm3_boot _mm3_cr _mm3_nl \ _mm3_body _mm3_kv _mm3_dir _mm3_tmp _mm3_fb _mm3_run _mm3_att _mm3_ok _mm3_faults _mm3_ign _mm3_igd \ - _mm3_soc _mm3_name _mm3_dt _mm3_base _mm3_profile _mm3_requested _mm3_files _mm3_gate_ifs _mm3_board _mm3_note + _mm3_soc _mm3_name _mm3_dt _mm3_base _mm3_profile _mm3_requested _mm3_files _mm3_gate_ifs _mm3_board _mm3_note \ + _mm3_klog _mm3_sys _mm3_admitted _mm3_detail _mm3_helper _mm3_chip _mm3_identity _mm3_socs _mm3_cmdline \ + _mm3_self diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-system-check.c b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-system-check.c new file mode 100644 index 00000000000000..10012e6c67945e --- /dev/null +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-system-check.c @@ -0,0 +1,243 @@ +/* SPDX-License-Identifier: MIT */ +/* Check system Mesa admission for one M3 render node, without drawing. + * This helper never selects /opt/mesa-m3 or enables an experimental GPU. + * The session hook invokes it with an empty environment and a timeout. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static bool +board_compat_matches(const char *bytes, size_t length, const char *soc) +{ + /* Any board of this SoC: one board compatible and one SoC compatible. */ + if (strcmp(soc, "t8122") && strcmp(soc, "t6030")) + return false; + if (!length || bytes[length - 1] != '\0') + return false; + unsigned boards = 0, socs = 0; + size_t offset = 0; + while (offset < length) { + size_t remaining = length - offset; + size_t size = strnlen(bytes + offset, remaining); + if (!size || size == remaining) + return false; + const char *value = bytes + offset; + if (!strncmp(value, "apple,j", 7)) { + boards++; + } else if (!strncmp(value, "apple,t", 7)) { + if (strncmp(value + 6, soc, strlen(soc) + 1)) + return false; + socs++; + } + offset += size + 1; + } + return boards == 1 && socs == 1; +} + +/* The asahi driver names its renderer "Apple ( )". + * Accept the chip and GPU of the admitted SoC with any stepping. The prefix + * already excludes software and layered renderers; refuse them by name too. + */ +static bool +native_renderer(const char *renderer, const char *soc) +{ + static const char *const refused[] = { + "llvmpipe", "softpipe", "swrast", "lavapipe", "zink", + }; + const char *prefix; + if (!strcmp(soc, "t8122")) + prefix = "Apple M3 (G15G "; + else if (!strcmp(soc, "t6030")) + prefix = "Apple M3 Pro (G15S "; + else + return false; + if (!renderer || strncmp(renderer, prefix, strlen(prefix))) + return false; + for (size_t i = 0; i < sizeof(refused) / sizeof(refused[0]); i++) { + if (strcasestr(renderer, refused[i])) + return false; + } + return true; +} + +static bool +qualified_board(const char *soc) +{ + FILE *file = fopen("/proc/device-tree/compatible", "rb"); + if (!file) + return false; + char bytes[4096]; + size_t length = fread(bytes, 1, sizeof(bytes), file); + bool complete = !ferror(file) && length < sizeof(bytes); + fclose(file); + return complete && board_compat_matches(bytes, length, soc); +} + +static bool +symbol(void *library, const char *name, void *destination, size_t size) +{ + void *address = dlsym(library, name); + if (!address || size != sizeof(address)) + return false; + memcpy(destination, &address, size); + return true; +} + +/* Check what actually loaded, rather than trusting a version or a package name. + * A role supplied through a legacy prefix, or a deleted implementation, fails. + */ +static bool +system_implementation(void) +{ + FILE *maps = fopen("/proc/self/maps", "r"); + if (!maps) + return false; + char line[8192]; + bool egl = false, gallium = false, invalid = false; + while (fgets(line, sizeof(line), maps)) { + char *path = strchr(line, '/'); + if (!path) + continue; + bool is_egl = strstr(path, "libEGL_mesa.so") != NULL; + bool is_gallium = strstr(path, "libgallium-") != NULL; + bool is_asahi = strstr(path, "/dri/asahi_dri.so") != NULL; + if (!is_egl && !is_gallium && !is_asahi) + continue; + if (strncmp(path, "/usr/lib/", 9) || strstr(path, " (deleted)")) + invalid = true; + egl |= is_egl; + gallium |= is_gallium || is_asahi; + } + bool complete = !ferror(maps); + fclose(maps); + return complete && !invalid && egl && gallium; +} + +int +main(int argc, char **argv) +{ + if (argc != 3) { + fprintf(stderr, "usage: mesa-m3-system-check /dev/dri/renderD t8122|t6030\n"); + return 2; + } + if (strcmp(argv[2], "t8122") && strcmp(argv[2], "t6030")) + return 2; + const char *node_prefix = "/dev/dri/renderD"; + size_t prefix_length = strlen(node_prefix); + if (strncmp(argv[1], node_prefix, prefix_length) || + !argv[1][prefix_length] || + strspn(argv[1] + prefix_length, "0123456789") != strlen(argv[1] + prefix_length)) + return 2; + if (!qualified_board(argv[2])) + return 1; + struct stat st; + if (lstat(argv[1], &st) || !S_ISCHR(st.st_mode)) + return 1; + + /* env -i at exec is also necessary: clearenv cannot undo LD_PRELOAD that + * the dynamic linker processed before main. Do not inherit opt-in flags. + */ + if (clearenv() || + setenv("__EGL_VENDOR_LIBRARY_FILENAMES", + "/usr/share/glvnd/egl_vendor.d/50_mesa.json", 1) || + setenv("LIBGL_DRIVERS_PATH", "/usr/lib/dri", 1) || + setenv("MESA_SHADER_CACHE_DISABLE", "true", 1)) + return 1; + alarm(8); + void *egl_library = dlopen("/usr/lib/libEGL.so.1", RTLD_NOW | RTLD_LOCAL); + void *gles_library = dlopen("/usr/lib/libGLESv2.so.2", RTLD_NOW | RTLD_LOCAL); + if (!egl_library || !gles_library) + return 1; + + PFNEGLGETPROCADDRESSPROC get_proc = NULL; + PFNEGLINITIALIZEPROC initialize = NULL; + PFNEGLBINDAPIPROC bind_api = NULL; + PFNEGLCHOOSECONFIGPROC choose_config = NULL; + PFNEGLCREATECONTEXTPROC create_context = NULL; + PFNEGLMAKECURRENTPROC make_current = NULL; + PFNEGLDESTROYCONTEXTPROC destroy_context = NULL; + PFNEGLTERMINATEPROC terminate = NULL; + const GLubyte *(*get_string)(GLenum) = NULL; +#define LOAD(library, function, name) \ + if (!symbol(library, name, &function, sizeof(function))) return 1 + LOAD(egl_library, get_proc, "eglGetProcAddress"); + LOAD(egl_library, initialize, "eglInitialize"); + LOAD(egl_library, bind_api, "eglBindAPI"); + LOAD(egl_library, choose_config, "eglChooseConfig"); + LOAD(egl_library, create_context, "eglCreateContext"); + LOAD(egl_library, make_current, "eglMakeCurrent"); + LOAD(egl_library, destroy_context, "eglDestroyContext"); + LOAD(egl_library, terminate, "eglTerminate"); + LOAD(gles_library, get_string, "glGetString"); +#undef LOAD + + PFNEGLQUERYDEVICESEXTPROC query_devices = NULL; + PFNEGLQUERYDEVICESTRINGEXTPROC device_string = NULL; + PFNEGLGETPLATFORMDISPLAYEXTPROC platform_display = NULL; +#define EXT(function, name) do { \ + __eglMustCastToProperFunctionPointerType address = get_proc(name); \ + if (!address || sizeof(address) != sizeof(function)) return 1; \ + memcpy(&function, &address, sizeof(function)); \ +} while (0) + EXT(query_devices, "eglQueryDevicesEXT"); + EXT(device_string, "eglQueryDeviceStringEXT"); + EXT(platform_display, "eglGetPlatformDisplayEXT"); +#undef EXT + EGLint count = 0; + EGLDeviceEXT devices[16]; + if (!query_devices(0, NULL, &count) || count < 1 || count > 16 || + !query_devices(count, devices, &count) || count < 1 || count > 16) + return 1; + EGLDeviceEXT selected = EGL_NO_DEVICE_EXT; + for (EGLint i = 0; i < count; ++i) { + const char *path = device_string(devices[i], EGL_DRM_RENDER_NODE_FILE_EXT); + if (path && !strcmp(path, argv[1])) { + if (selected != EGL_NO_DEVICE_EXT) + return 1; + selected = devices[i]; + } + } + if (selected == EGL_NO_DEVICE_EXT) + return 1; + + EGLDisplay display = platform_display(EGL_PLATFORM_DEVICE_EXT, selected, NULL); + if (display == EGL_NO_DISPLAY || !initialize(display, NULL, NULL)) + return 1; + EGLContext context = EGL_NO_CONTEXT; + bool accepted = false; + EGLConfig config; + EGLint matches = 0; + const EGLint attributes[] = { + EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT_KHR, + EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_NONE, + }; + const EGLint context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE }; + if (!bind_api(EGL_OPENGL_ES_API) || + !choose_config(display, attributes, &config, 1, &matches) || matches != 1) + goto done; + context = create_context(display, config, EGL_NO_CONTEXT, context_attributes); + if (context == EGL_NO_CONTEXT || + !make_current(display, EGL_NO_SURFACE, EGL_NO_SURFACE, context)) + goto done; + const char *renderer = (const char *)get_string(GL_RENDERER); + accepted = native_renderer(renderer, argv[2]) && system_implementation(); + if (accepted) + printf("system-mesa=available renderer=%s\n", renderer); +done: + make_current(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + if (context != EGL_NO_CONTEXT) + destroy_context(display, context); + terminate(display); + dlclose(gles_library); + dlclose(egl_library); + return accepted ? 0 : 1; +} diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup index a581853b1404d0..7291099ff7cb18 100755 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup @@ -4,6 +4,7 @@ mesa-m3-user-setup --home HOME [--config-home DIR] [--env | --environ FILE] [--session-desktops NAMES] [--list FILE] [--root DIR] + [--system-provider] The one definition of "the user's own M3 Mesa setup", used by the mesa-m3 session hook at every login and by the installer. What counts is listed in @@ -20,6 +21,13 @@ see the comments there. as in XDG_CURRENT_DESKTOP (uwsm exports them before it reads any environment file); empty or absent: unknown --root DIR prefix every path with DIR (tests) + --system-provider also refuse legacy /opt selectors and session flags when + checking whether the real desktop will use system Mesa; + an LD_LIBRARY_PATH entry then also counts when it holds + only libEGL, libGLESv2, libGL, libGLX, libglapi or libgbm; + entries split on ":" and ";", and a relative or empty + entry makes the result "unknown"; Bash += assignments + to tracked variables are unknown too Nothing is sourced or evaluated. Files are read as text and split into words the way a POSIX shell would (quotes, backslashes, comments, ";"), with no @@ -79,10 +87,14 @@ def fail(msg): def parse_args(argv): opts = {'home': None, 'config': None, 'env': False, 'environ': None, 'list': DEFAULT_LIST, 'root': '', - 'desktops': None} + 'desktops': None, 'system_provider': False} i = 0 while i < len(argv): a = argv[i] + if a == '--system-provider': + opts['system_provider'] = True + i += 1 + continue if a == '--env': opts['env'] = True i += 1 @@ -178,9 +190,11 @@ def shell_words(line): return words -def shell_assignments(line): +def shell_assignments(line, *, append_unknown=False): """The NAME=VALUE words of one line of shell, environment.d or - /etc/environment text. None when the line cannot be split.""" + /etc/environment text. None when the line cannot be split. With + append_unknown, a Bash NAME+=VALUE word is emitted with a None value, + since its resulting value depends on earlier assignments.""" words = shell_words(line) if words is None: return None @@ -189,6 +203,13 @@ def shell_assignments(line): m = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=(.*)$', w, re.S) if m: out.append((m.group(1), m.group(2))) + elif append_unknown: + # Arch's sh is Bash, which accepts += even in POSIX mode. Its + # value depends on earlier assignments; do not silently ignore + # a late provider override when admitting system Mesa. + m = re.match(r'([A-Za-z_][A-Za-z0-9_]*)\+=(.*)$', w, re.S) + if m: + out.append((m.group(1), None)) return out @@ -248,6 +269,18 @@ class Finder: for k, i in items: if k in ('variable', 'flag', 'prefix', 'ldpath'): self.kind[i] = k + if opts['system_provider']: + # These may be left over from an active legacy session. The + # admission helper's clean environment cannot prove that the + # real desktop will use /usr while these remain in its setup. + # The rest choose the desktop's GL/GBM provider or its version, + # which the clean-environment helper never sees. + for name in ('LD_PRELOAD', 'LD_AUDIT', 'MESA_M3_SESSION', 'MESA_M3_PROFILE', + 'ASAHI_M3_EXPERIMENTAL', 'AGX_MESA_DEBUG', 'HK_DEBUG_LOG', + 'VK_LOADER_LAYERS_DISABLE', 'QSG_RHI_BACKEND', + 'GBM_BACKEND', '__GLX_VENDOR_LIBRARY_NAME', 'MESA_GL_VERSION_OVERRIDE', + 'MESA_GLES_VERSION_OVERRIDE', 'MESA_GLSL_VERSION_OVERRIDE'): + self.kind[name] = 'flag' def real(self, p): return self.o['root'] + p @@ -297,11 +330,18 @@ class Finder: def ours(self, path): p = os.path.normpath(path) if path.startswith('/') else path - return p == PREFIX or p.startswith(PREFIX + '/') + # A system-Mesa handoff must also detect the old prefix. The normal + # legacy gate deliberately accepts it and keeps its original behavior. + return not self.o['system_provider'] and (p == PREFIX or p.startswith(PREFIX + '/')) def holds_mesa(self, d): r = self.real(d) pats = ('libgallium*', 'libEGL_mesa*', 'libvulkan_asahi*', 'dri/*_dri.so') + if self.o['system_provider']: + # Any of these replaces what the desktop loads from /usr, even + # without a Mesa driver of its own next to it. + pats += ('libEGL.so*', 'libEGL_*', 'libGLESv2.so*', 'libGL.so*', 'libGLX*', + 'libglapi.so*', 'libgbm.so*', 'gbm/*') return any(glob.glob(os.path.join(glob.escape(r), p)) for p in pats) def expand_home(self, s): @@ -335,15 +375,60 @@ class Finder: # while the other Mesa variables still point into the prefix. note(place, f'{label} replaces {name} (without ${name})') return - # Drop the references to the previous value (also ${NAME:+:$NAME}). - rest = re.sub(r'\$\{' + re.escape(name) + r'(?::?[-+=?][^}]*)?\}|\$' + re.escape(name) + r'(?![A-Za-z0-9_])', - '', value) - for comp in rest.split(':'): - comp = self.expand_home(comp.strip()) + n = re.escape(name) + strict = self.o['system_provider'] + if not strict: + # Drop the references to the previous value (also ${NAME:+:$NAME}). + rest = re.sub(r'\$\{' + n + r'(?::?[-+=?][^}]*)?\}|\$' + n + r'(?![A-Za-z0-9_])', '', value) + comps = rest.split(':') + elif place.startswith('environment:'): + # Already expanded: taken literally, as glibc does. + comps = re.split('[:;]', value) if value != '' else [] + else: + # The previous value may be empty here (unset, or cleared by an + # earlier file), and then "/a:$NAME" leaves "/a:", whose empty + # entry glibc's loader reads as the current directory. So a + # plain reference counts as empty, and ${NAME:+:$NAME} (which + # then adds nothing) is the safe form. A reference must stand + # alone between separators: "${NAME}/x" names a directory we + # cannot see. Anything else is unknown. glibc also splits on + # ";" and ignores a wholly empty value. + ref = (r'\$\{' + n + r':\+:\$\{' + n + r'\}\}|\$\{' + n + r'(?::?[-+=?][^}]*)?\}|\$' + n + + r'(?![A-Za-z0-9_])') + plain = ('$' + name, '${' + name + '}') + cond = tuple('${' + name + ':+:' + r + '}' for r in plain) + sep = (':', ';') + rest, at = '', 0 + for m in re.finditer(ref, value): + t, before, after = m.group(0), value[m.start() - 1:m.start()], value[m.end():m.end() + 1] + # A conditional append needs an entry before it, or it + # starts the value with an empty entry. + edge = ('',) + sep + alone = after in edge and ((before not in edge) if t in cond else (before in edge)) + rest += value[at:m.start()] + ('' if alone and t in plain + cond else '\0') + at = m.end() + rest += value[at:] + comps = re.split('[:;]', rest) if rest != '' else [] + for comp in comps: + if strict and '\0' in comp: + note(place, f'{label} uses {name} in a form whose result is not known', sure=False) + continue + if strict and comp == '': + note(place, f'{label} leaves an empty entry in {name} (the current directory)', sure=False) + continue + # glibc takes an entry as written, spaces included, and an + # environment value has no ~ or $HOME left to expand. + if not strict: + comp = self.expand_home(comp.strip()) + elif not place.startswith('environment:'): + comp = self.expand_home(comp) if comp == '': continue if '$' in comp or '`' in comp: note(place, f'{label} puts an unresolved entry in {name} ({comp})', sure=False) + elif not comp.startswith('/') and self.o['system_provider']: + # Resolved against whatever directory the desktop starts in. + note(place, f'{label} puts a relative entry in {name} ({comp})', sure=False) elif comp.startswith('/') and not self.ours(comp) and self.holds_mesa(os.path.normpath(comp)): note(place, f'{label} puts another Mesa in {name} ({os.path.normpath(comp)})') return @@ -448,7 +533,7 @@ class Finder: elif is_hypr: found = hyprlang_assignments(line) else: - found = shell_assignments(line) + found = shell_assignments(line, append_unknown=self.o['system_provider']) if found is None: if any(re.search(rf'(?&2; exit 1 ;; +stall) sleep 60; normal ;; esac exit 0 J @@ -665,5 +669,245 @@ echo j613-25g83-hal200 > "$J516S/etc/mesa-m3/t8122-profile" expect "$J516S" profile-mismatch J613 rm "$J516S/etc/mesa-m3/t8122-profile" + +# System Mesa handoff: opt-out must not strand a qualified native /usr +# installation in software rendering. Every failed admission retains recovery. +# The helper is a stub here; its real board/renderer/provenance tests are separate. +system_root() { + case "$2" in + air) _hd="apple,j613 apple,t8122"; _hg=$G15G ;; + *) _hd="apple,j516s apple,t6030"; _hg=$G15S ;; + esac + _hr=$(mkroot "handoff-$1" "$_hd" "$_hg" yes 1 yes "${3:-asahi}") + mkdir -p "$_hr/etc/mesa-m3" + : > "$_hr/etc/mesa-m3/disable" + cat > "$_hr/opt/mesa-m3/libexec/mesa-m3-system-check" <<'H' +#!/bin/sh +here=${0%/*} +printf '%s\n' "$@" > "$here/system-check.args" +env | sort > "$here/system-check.env" +[ ! -e "$here/system-check.sleep" ] || sleep 8 +[ ! -e "$here/system-check.fail" ] +H + chmod +x "$_hr/opt/mesa-m3/libexec/mesa-m3-system-check" + # The bounded admission sources the installed hook again in its own sh. + cp "$ENVFILE" "$_hr/opt/mesa-m3/libexec/mesa-m3-session-env" + echo "$_hr" +} +handoff() { # ROOT FALLBACK HELPER_CALLED [VAR=value...] + _hr=$1 _hfb=$2 _hc=$3 + shift 3 + rm -f "$_hr/opt/mesa-m3/libexec/system-check.args" + _ha="$_hr$T/home/.local/state/mesa-m3/attempt" + _hbefore=missing + [ ! -f "$_ha" ] || _hbefore=$(sha256sum "$_ha" | cut -d' ' -f1) + _ho=$(env -i PATH="$T/bin:/usr/bin:/bin" HOME="$T/home" FAKE_LOG="$T/log" \ + XDG_CURRENT_DESKTOP=Hyprland "$@" "$TSH" -c ' + MESA_M3_SESSION_ENV_NO_RUN=1 . "$1" + mesa_m3_session_env "$2" + printf "software=%s\nmarker=%s\nlegacy=%s\n" "${LIBGL_ALWAYS_SOFTWARE:-}" "${MESA_M3_FALLBACK:-}" "${MESA_M3_SESSION:-}" + cat "$2/run/user/$(id -u)/mesa-m3-session.state" + ' sh "$ENVFILE" "$_hr") + _hafter=missing + [ ! -f "$_ha" ] || _hafter=$(sha256sum "$_ha" | cut -d' ' -f1) + _hcalled=no + [ ! -e "$_hr/opt/mesa-m3/libexec/system-check.args" ] || _hcalled=yes + if printf '%s\n' "$_ho" | grep -qx "fallback=$_hfb" && + printf '%s\n' "$_ho" | grep -qx 'decision=inactive' && + printf '%s\n' "$_ho" | grep -qx 'reason=opt-out' && + printf '%s\n' "$_ho" | grep -qx 'legacy=' && + [ "$_hc" = "$_hcalled" ] && [ "$_hbefore" = "$_hafter" ]; then + echo "ok ${_hr##*/}: fallback=$_hfb helper=$_hc, legacy attempt unchanged" + else + echo "FAIL ${_hr##*/}: want fallback=$_hfb helper=$_hc; got helper=$_hcalled attempt=$_hbefore/$_hafter: $_ho" + fail=1 + fi + if [ "$_hfb" = none ]; then + if ! printf '%s\n' "$_ho" | grep -qx 'software=' || + ! printf '%s\n' "$_ho" | grep -qx 'marker=' || + ! printf '%s\n' "$_ho" | grep -q 'detail=.*system Mesa on /usr admits'; then + echo "FAIL ${_hr##*/}: system admission exports or state detail: $_ho"; fail=1 + fi + else + if ! printf '%s\n' "$_ho" | grep -qx 'software=1' || + ! printf '%s\n' "$_ho" | grep -qx 'marker=software' || + printf '%s\n' "$_ho" | grep -q 'detail=.*system Mesa on /usr admits'; then + echo "FAIL ${_hr##*/}: recovery exports or state detail: $_ho"; fail=1 + fi + fi +} +HRA=$(system_root user-optout air) +rm "$HRA/etc/mesa-m3/disable" +mkdir -p "$HRA$T/home/.config/mesa-m3" +: > "$HRA$T/home/.config/mesa-m3/disable" +handoff "$HRA" none yes +if [ "$(cat "$HRA/opt/mesa-m3/libexec/system-check.args")" = "$(printf '/dev/dri/renderD128\nt8122')" ] && + grep -qx 'PATH=/usr/bin:/bin' "$HRA/opt/mesa-m3/libexec/system-check.env" && + [ -z "$(grep -vE '^(PATH=/usr/bin:/bin|PWD=.*|SHLVL=[0-9]+|_=.*)$' "$HRA/opt/mesa-m3/libexec/system-check.env")" ]; then + echo 'ok handoff: helper receives exact device/SoC and empty selector environment' +else echo 'FAIL handoff: helper argv/environment'; fail=1; fi +HRP=$(system_root root-optout pro) +handoff "$HRP" none yes +# The 7.3 kernels name the GPU driver "aurora" ("asahi" is only a module alias). +# The admission accepts it on both SoCs. +for soc in air pro; do + HR=$(system_root "aurora-$soc" "$soc" aurora) + handoff "$HR" none yes +done +# On "aurora" the system Mesa is not refused, so no session falls back to +# software there: not a failed admission, not the default T8122 session +# (experimental), not a T6030 the /opt/mesa-m3 profile cannot use. A driver +# that only starts with "aurora" is not admitted. +aurora_state() { # NAME ROOT WANT_REASON + _ao=$(env -i PATH="$T/bin:/usr/bin:/bin" HOME="$T/home" FAKE_LOG="$T/log" \ + XDG_CURRENT_DESKTOP=Hyprland "$TSH" -c ' + MESA_M3_SESSION_ENV_NO_RUN=1 . "$1" + mesa_m3_session_env "$2" + printf "software=%s\nmarker=%s\n" "${LIBGL_ALWAYS_SOFTWARE:-}" "${MESA_M3_FALLBACK:-}" + cat "$2/run/user/$(id -u)/mesa-m3-session.state" + ' sh "$ENVFILE" "$2") + if printf '%s\n' "$_ao" | grep -qx 'fallback=none' && + printf '%s\n' "$_ao" | grep -qx 'software=' && + printf '%s\n' "$_ao" | grep -qx 'decision=inactive' && + printf '%s\n' "$_ao" | grep -qx "reason=$3" && + ! printf '%s\n' "$_ao" | grep -q 'detail=.*system Mesa on /usr admits'; then + echo "ok $1: reason=$3 fallback=none, nothing exported" + else + echo "FAIL $1: want reason=$3 fallback=none and no admission: $_ao"; fail=1 + fi +} +HR=$(system_root aurora-probe-fail pro aurora) +: > "$HR/opt/mesa-m3/libexec/system-check.fail" +aurora_state aurora-probe-fail "$HR" opt-out +HR=$(system_root aurora-x pro aurora-x) +aurora_state aurora-x "$HR" opt-out +HR=$(mkroot aurora-default-air "apple,j613 apple,t8122" "$G15G" yes 1 yes aurora) +aurora_state aurora-default-air "$HR" experimental +HR=$(mkroot aurora-default-pro "apple,j516s apple,t6030" "$G15S" yes 1 yes aurora) +aurora_state aurora-default-pro "$HR" no-gpu +# A kernel built with the native G15 backend binds the T6030 to that backend's +# own driver: "asahi-g15" on 7.2, "aurora-g15" on 7.3. The admission accepts +# both, a failed admission there does not fall back to software, and neither +# does the default session. A near-miss name is not admitted. +for drv in asahi-g15 aurora-g15; do + HR=$(system_root "$drv" pro "$drv") + handoff "$HR" none yes + HR=$(system_root "$drv-probe-fail" pro "$drv") + : > "$HR/opt/mesa-m3/libexec/system-check.fail" + aurora_state "$drv-probe-fail" "$HR" opt-out + HR=$(mkroot "$drv-default-pro" "apple,j516s apple,t6030" "$G15S" yes 1 yes "$drv") + aurora_state "$drv-default-pro" "$HR" no-gpu +done +HR=$(system_root asahi-g15x pro asahi-g15x) +aurora_state asahi-g15x "$HR" opt-out +handoff "$HRP" none yes LIBGL_ALWAYS_SOFTWARE=1 MESA_M3_FALLBACK=software +for mode in fail sleep; do + HR=$(system_root "probe-$mode" pro) + : > "$HR/opt/mesa-m3/libexec/system-check.$mode" + handoff "$HR" software yes +done +for mode in missing not-executable; do + HR=$(system_root "probe-$mode" pro) + if [ "$mode" = missing ]; then rm "$HR/opt/mesa-m3/libexec/mesa-m3-system-check"; + else chmod 600 "$HR/opt/mesa-m3/libexec/mesa-m3-system-check"; fi + handoff "$HR" software no +done +for mode in missing-cmdline missing-detector; do + HR=$(system_root "$mode" pro) + if [ "$mode" = missing-cmdline ]; then rm "$HR/proc/cmdline"; + else rm "$HR/opt/mesa-m3/libexec/mesa-m3-user-setup"; fi + handoff "$HR" software no +done +for flag in mesa_m3=off nomodeset; do + HR=$(system_root "kernel-$flag" pro) + echo "root=UUID=x rw $flag quiet" > "$HR/proc/cmdline" + handoff "$HR" software no +done +for journal in noperm error match bank dcp g15g verdict; do + HR=$(system_root "journal-$journal" pro) + handoff "$HR" software no FAKE_JOURNAL="$journal" +done +# Any single board of the SoC reaches the helper, which decides on the GPU. +HR=$(system_root board-j615 air) +nul apple,j615 apple,t8122 > "$HR/proc/device-tree/compatible" +handoff "$HR" none yes +HR=$(system_root board-j504 air) +nul apple,j504 apple,t8122 > "$HR/proc/device-tree/compatible" +handoff "$HR" none yes +HR=$(system_root board-j514s pro) +nul apple,j514s apple,t6030 > "$HR/proc/device-tree/compatible" +handoff "$HR" none yes +# Two boards, two SoCs or no board stay refused. Without a board table the +# hook cannot tell which SoC a board belongs to; the GPU and display checks +# are keyed on the SoC compatible instead. +for dt in 'apple,j613 apple,j615 apple,t8122' 'apple,t6030' \ + 'apple,j516s apple,t6030 apple,t8122'; do + HR=$(system_root "board-$(printf '%s' "$dt" | tr ' ,' '--')" pro) + nul $dt > "$HR/proc/device-tree/compatible" + # Match the GPU to the ambiguous board's first SoC so the old fallback + # remains observable; the system handoff must still refuse it. + case "$dt" in *t8122*) nul apple,agx-t8122 apple,agx-t6030 > "$HR/sys/devices/platform/gpu0/of_node/compatible" ;; esac + handoff "$HR" software no +done +HR=$(system_root no-display pro) +rm "$HR/sys/class/drm/card2/device" +handoff "$HR" software no +HR=$(system_root wrong-display pro) +nul apple,t8122-display-subsystem > "$HR/sys/devices/platform/display/of_node/compatible" +handoff "$HR" software no +HR=$(system_root two-nodes pro) +mkdir "$HR/sys/class/drm/renderD129" +handoff "$HR" software no +for variable in LIBGL_ALWAYS_SOFTWARE=1 \ + LD_LIBRARY_PATH=/opt/mesa-m3/lib \ + VK_DRIVER_FILES=/opt/mesa-m3/share/vulkan/icd.d/asahi_icd.aarch64.json \ + __EGL_VENDOR_LIBRARY_FILENAMES=/opt/mesa-m3/share/glvnd/egl_vendor.d/50_mesa.json \ + ASAHI_M3_EXPERIMENTAL=1 XDG_CURRENT_DESKTOP=chonkstep; do + HR=$(system_root "override-${variable%%=*}" pro) + handoff "$HR" software no "$variable" +done +for value in 'LIBGL_DRIVERS_PATH=/opt/mesa-m3/lib/dri' 'VK_DRIVER_FILES=$UNKNOWN' \ + 'export LIBGL_ALWAYS_SOFTWARE+=1' 'export LD_LIBRARY_PATH+=/opt/custom/lib'; do + HR=$(system_root "late-${value%%=*}" pro) + mkdir -p "$HR$T/home/.config/uwsm" + printf '%s\n' "$value" > "$HR$T/home/.config/uwsm/env" + handoff "$HR" software no +done +for variable in GBM_BACKEND=nvidia-drm MESA_GL_VERSION_OVERRIDE=4.6; do + HR=$(system_root "override-${variable%%=*}" pro) + handoff "$HR" software no "$variable" +done +HR=$(system_root no-installed-hook pro) +rm "$HR/opt/mesa-m3/libexec/mesa-m3-session-env" +handoff "$HR" software no +# A stalled journal or scanner refuses within the bound (20 s, then 2 s to +# kill) and keeps the software fallback, instead of holding the login. +HR=$(system_root stalled-journal pro) +_hstart=$(date +%s) +handoff "$HR" software no FAKE_JOURNAL=stall +_hspent=$(( $(date +%s) - _hstart )) +if [ "$_hspent" -le 30 ]; then echo "ok stalled-journal: refused after ${_hspent}s" +else echo "FAIL stalled-journal: took ${_hspent}s"; fail=1; fi +HR=$(system_root stalled-detector pro) +printf '#!/bin/sh\nsleep 60\n' > "$HR/opt/mesa-m3/libexec/mesa-m3-user-setup" +_hstart=$(date +%s) +handoff "$HR" software no +_hspent=$(( $(date +%s) - _hstart )) +if [ "$_hspent" -le 30 ]; then echo "ok stalled-detector: refused after ${_hspent}s" +else echo "FAIL stalled-detector: took ${_hspent}s"; fail=1; fi +HR=$(system_root failed-legacy-login pro) +HATT="$HR$T/home/.local/state/mesa-m3/attempt" +HOK="$HR$T/home/.local/state/mesa-m3/session-ok" +mkdir -p "${HATT%/*}" +printf 'schema=aurora.mesa-m3-attempt/2\nboot_id=boot-a\nsession_id=5\nhook_run_id=old-run\n' > "$HATT" +handoff "$HR" software no +printf 'schema=aurora.mesa-m3-session-ok/1\nboot_id=boot-a\nsession_id=wrong\nhook_run_id=old-run\n' > "$HOK" +handoff "$HR" software no +sed -i 's/session_id=wrong/session_id=5/' "$HOK" +handoff "$HR" none yes +rm "$HOK" +sed -i 's/boot_id=boot-a/boot_id=old-boot/' "$HATT" +handoff "$HR" none yes + [ "$fail" = 0 ] && echo "ALL PASS" || echo "SOME FAILED" exit "$fail" diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-board.c b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-board.c new file mode 100644 index 00000000000000..1832d2249ff7f5 --- /dev/null +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-board.c @@ -0,0 +1,55 @@ +/* SPDX-License-Identifier: MIT */ +/* Pure board-parser controls: no device opening or EGL calls. */ +#define main system_check_main +#include "../mesa-m3-system-check.c" +#undef main +#include + +#define CHECK(expected, soc, bytes) \ + assert(board_compat_matches(bytes, sizeof(bytes) - 1, soc) == (expected)) + +int main(void) +{ + CHECK(true, "t8122", "apple,j613\0apple,t8122\0apple,arm-platform\0"); + CHECK(true, "t6030", "apple,j516s\0apple,t6030\0apple,arm-platform\0"); + CHECK(true, "t6030", "apple,arm-platform\0apple,t6030\0apple,j516s\0"); + /* Any single board of the SoC, not a list of boards. */ + CHECK(true, "t8122", "apple,j615\0apple,t8122\0"); + CHECK(true, "t8122", "apple,j504\0apple,t8122\0"); + CHECK(true, "t6030", "apple,j514s\0apple,t6030\0"); + CHECK(false, "t6030", "apple,j516s\0apple,t6031\0"); + CHECK(false, "t8122", "apple,j613\0apple,j615\0apple,t8122\0"); + CHECK(false, "t8122", "apple,j613\0apple,j613\0apple,t8122\0"); + CHECK(false, "t6030", "apple,j516s\0apple,t6030\0apple,t6030\0"); + CHECK(false, "t6030", "apple,j516s\0apple,t6030\0apple,t8122\0"); + CHECK(false, "t8122", "apple,j613\0apple,t8122-extra\0"); + CHECK(false, "t8122", "apple,j613\0apple,t8122"); + CHECK(false, "t8122", "apple,j613\0\0apple,t8122\0"); + CHECK(false, "t6030", "apple,t6030\0"); + CHECK(false, "t6030", "apple,j516s\0"); + CHECK(false, "t8140", "apple,j516s\0apple,t6030\0"); + CHECK(false, "t6030", ""); + /* The admitted SoC's chip and GPU, with any stepping. */ + assert(native_renderer("Apple M3 (G15G C0)", "t8122")); + assert(native_renderer("Apple M3 (G15G B0)", "t8122")); + assert(native_renderer("Apple M3 Pro (G15S B1)", "t6030")); + assert(native_renderer("Apple M3 Pro (G15S C0)", "t6030")); + /* The other SoC's GPU, another chip, or a software renderer. */ + assert(!native_renderer("Apple M3 Pro (G15S B1)", "t8122")); + assert(!native_renderer("Apple M3 (G15G C0)", "t6030")); + assert(!native_renderer("Apple M2 (G14G B1)", "t8122")); + assert(!native_renderer("Apple M2 (G14G B1)", "t6030")); + assert(!native_renderer("Apple M3 Max (G15C C0)", "t6030")); + assert(!native_renderer("Apple M3 Unknown (G15X C0)", "t8122")); + assert(!native_renderer("Apple M3 (G15G", "t8122")); + assert(!native_renderer("Apple M3 (G15G C0)", "t6031")); + assert(!native_renderer(NULL, "t8122")); + assert(!native_renderer("", "t8122")); + assert(!native_renderer("llvmpipe (LLVM 21.1.0, 128 bits)", "t8122")); + assert(!native_renderer("softpipe", "t6030")); + assert(!native_renderer("zink Vulkan 1.4(Apple M3 (G15G C0) (MESA_ASAHI))", "t8122")); + assert(!native_renderer("Apple M3 (G15G llvmpipe)", "t8122")); + assert(!native_renderer("AppleM3", "t8122")); + puts("18 board parser and 19 renderer controls passed"); + return 0; +} diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py new file mode 100644 index 00000000000000..e528270b7c9444 --- /dev/null +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +"""The system-provider decision must see legacy selectors as overrides.""" +from pathlib import Path +import subprocess +import tempfile +import unittest + +RECIPE = Path(__file__).resolve().parents[1] + + +class SystemProviderTest(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.home = "/home/tester" + (self.root / "home/tester/.config").mkdir(parents=True) + prefix = self.root / "opt/mesa-m3/lib" + prefix.mkdir(parents=True) + (prefix / "libgallium-26.1.4.so").touch() + + def run_detector(self, environment=None, system=True): + command = [str(RECIPE / "mesa-m3-user-setup"), "--home", self.home, + "--root", str(self.root), "--list", str(RECIPE / "user-setup.list"), + "--session-desktops", "Hyprland", "--env"] + if system: + command.append("--system-provider") + return subprocess.run(command, env={"PATH": "/usr/bin:/bin", "HOME": self.home, + **(environment or {})}, + capture_output=True, text=True, timeout=10) + + def test_bash_append_cannot_override_system_admission_silently(self): + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir() + config = folder / "env" + cases = (("LIBGL_ALWAYS_SOFTWARE", "1"), + ("LD_LIBRARY_PATH", "/opt/custom/lib")) + for name, value in cases: + with self.subTest(variable=name): + config.write_text("export " + name + "+=" + value + "\n") + # The target's sh is Bash. This is a real assignment in + # POSIX mode, although the legacy parser ignores it. + shell = subprocess.run( + ["bash", "--posix", "-c", + 'unset LIBGL_ALWAYS_SOFTWARE LD_LIBRARY_PATH; . "$1"; ' + 'printf "%s" "${!2}"', "bash", str(config), name], + env={"PATH": "/usr/bin:/bin"}, capture_output=True, + text=True, timeout=10) + self.assertEqual(shell.returncode, 0, shell.stderr) + self.assertEqual(shell.stdout, value) + result = self.run_detector() + self.assertEqual(result.returncode, 3, result.stdout) + self.assertIn(name, result.stdout) + self.assertIn("user_setup=unknown", result.stdout) + # Keep the default legacy decision unchanged. + self.assertEqual(self.run_detector(system=False).returncode, 0) + + def test_unrelated_bash_append_is_not_a_mesa_choice(self): + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir() + (folder / "env").write_text("export MY_TOOLS_PATH+=/tools\n") + self.assertEqual(self.run_detector().returncode, 0) + + def test_clean_setup(self): + self.assertEqual(self.run_detector().returncode, 0) + + def test_legacy_path_default_stays_accepted(self): + value = {"VK_DRIVER_FILES": "/opt/mesa-m3/share/vulkan/icd.d/asahi.json"} + self.assertEqual(self.run_detector(value, system=False).returncode, 0) + self.assertEqual(self.run_detector(value).returncode, 1) + + def test_legacy_loader_path_is_not_system_mesa(self): + value = {"LD_LIBRARY_PATH": "/opt/mesa-m3/lib"} + self.assertEqual(self.run_detector(value, system=False).returncode, 0) + self.assertEqual(self.run_detector(value).returncode, 1) + + def test_later_config_can_reselect_legacy_mesa(self): + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir() + (folder / "env").write_text("export LIBGL_DRIVERS_PATH=/opt/mesa-m3/lib/dri\n") + self.assertEqual(self.run_detector(system=False).returncode, 0) + self.assertEqual(self.run_detector().returncode, 1) + + def test_explicit_software_choice(self): + self.assertEqual(self.run_detector({"LIBGL_ALWAYS_SOFTWARE": "1"}).returncode, 1) + + def test_only_owned_software_pair_is_ignored(self): + self.assertEqual(self.run_detector({"LIBGL_ALWAYS_SOFTWARE": "1", + "MESA_M3_FALLBACK": "software"}).returncode, 0) + + def test_preload_and_legacy_flags_are_not_clean_system_environment(self): + for variable in ("LD_PRELOAD", "LD_AUDIT", "MESA_M3_SESSION", + "ASAHI_M3_EXPERIMENTAL", "AGX_MESA_DEBUG"): + with self.subTest(variable=variable): + # File assignments avoid loading a preload into the test + # interpreter itself while exercising the same detector. + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir(exist_ok=True) + (folder / "env").write_text(variable + "=/opt/mesa-m3/choice\n") + self.assertEqual(self.run_detector().returncode, 1) + + def test_loader_only_directories_are_another_provider(self): + for library in ("libEGL.so.1", "libGLESv2.so.2", "libGL.so.1", "libGLX_mesa.so.0", + "libglapi.so.0", "libgbm.so.1", "gbm/dri_gbm.so"): + with self.subTest(library=library): + folder = self.root / "provider" / library.replace("/", "-") + (folder / library).parent.mkdir(parents=True, exist_ok=True) + (folder / library).touch() + value = {"LD_LIBRARY_PATH": "/provider/" + library.replace("/", "-")} + self.assertEqual(self.run_detector(value, system=False).returncode, 0) + self.assertEqual(self.run_detector(value).returncode, 1) + + def test_unrelated_library_directory_stays_clean(self): + (self.root / "provider/other").mkdir(parents=True) + (self.root / "provider/other/libfoo.so.1").touch() + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": "/provider/other"}).returncode, 0) + + def test_relative_loader_entry_is_unknown(self): + for value in ("lib", "./lib", "/usr/lib/extra:lib"): + with self.subTest(value=value): + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": value}, system=False).returncode, 0) + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": value}).returncode, 3) + + def test_loader_path_parsed_like_glibc(self): + (self.root / "provider/other").mkdir(parents=True) + (self.root / "provider/evil").mkdir(parents=True) + (self.root / "provider/evil/libEGL.so.1").touch() + for value, code in ((":", 3), ("/provider/other:", 3), (":/provider/other", 3), + ("/provider/other::/usr/lib/extra", 3), + ("/provider/other;/provider/evil", 1)): + with self.subTest(value=value): + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": value}).returncode, code) + + def test_previous_value_expands_like_the_shell(self): + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir(parents=True) + (self.root / "provider/other").mkdir(parents=True) + plain_after = "export LD_LIBRARY_PATH=/provider/other:$LD_LIBRARY_PATH\n" + plain_before = "export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/provider/other\n" + conditional = "export LD_LIBRARY_PATH=/provider/other${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}\n" + other_form = "export LD_LIBRARY_PATH=/provider/other:${LD_LIBRARY_PATH:-/x}\n" + nested = "export LD_LIBRARY_PATH=/provider/other${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}\n" + # An earlier file can clear the inherited value, so a plain reference + # counts as possibly empty even when the session inherits one. + for inherited in (None, "", "/usr/lib/extra"): + expect = {plain_after: 3, plain_before: 3, conditional: 0, nested: 0} + environment = {} if inherited is None else {"LD_LIBRARY_PATH": inherited} + for line, code in expect.items(): + with self.subTest(inherited=inherited, line=line): + (folder / "env").write_text(line) + self.assertEqual(self.run_detector(environment).returncode, code) + (folder / "env").write_text(other_form) + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": "/usr/lib/extra"}).returncode, 3) + (folder / "env").write_text(conditional) + self.assertEqual(self.run_detector(system=False).returncode, 0) + + def test_empty_inherited_value_is_no_entry(self): + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": ""}).returncode, 0) + + def test_reference_with_a_suffix_is_unknown(self): + (self.root / "provider/suffix").mkdir(parents=True) + (self.root / "provider/suffix/libEGL.so.1").touch() + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir(parents=True) + for line in ("export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}/suffix\n", + "export LD_LIBRARY_PATH=/a${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}/suffix\n", + "export LD_LIBRARY_PATH=/prefix$LD_LIBRARY_PATH\n"): + with self.subTest(line=line): + (folder / "env").write_text(line) + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": "/provider"}).returncode, 3) + + def test_environment_value_is_literal(self): + (self.root / "home/tester/provider").mkdir(parents=True) + (self.root / "home/tester/provider/libEGL.so.1").touch() + for value in ("$LD_LIBRARY_PATH", "$HOME/provider", "~/provider"): + with self.subTest(value=value): + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": value}).returncode, 3) + + def test_conditional_append_needs_an_entry_before_it(self): + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir(parents=True) + for line in ("export LD_LIBRARY_PATH=${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}\n", + "export LD_LIBRARY_PATH=${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}\n", + "export LD_LIBRARY_PATH=/x:${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}\n"): + with self.subTest(line=line): + (folder / "env").write_text(line) + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": "/usr/lib/extra"}).returncode, 3) + + def test_legacy_ldpath_rules_are_unchanged(self): + (self.root / "provider/mesa").mkdir(parents=True) + (self.root / "provider/mesa/libgallium-26.so").touch() + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir(parents=True) + for line, code in (("export LD_LIBRARY_PATH=/x:$LD_LIBRARY_PATH\n", 0), + ("export LD_LIBRARY_PATH=/provider/mesa:$LD_LIBRARY_PATH\n", 1), + ("export LD_LIBRARY_PATH=lib:$LD_LIBRARY_PATH\n", 0), + ("export LD_LIBRARY_PATH=/x::$LD_LIBRARY_PATH\n", 0)): + with self.subTest(line=line): + (folder / "env").write_text(line) + self.assertEqual(self.run_detector(system=False).returncode, code) + + def test_spaces_are_a_relative_entry(self): + for value in (" ", "/usr/lib/extra: "): + with self.subTest(value=value): + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": value}).returncode, 3) + + def test_provider_and_version_overrides(self): + for variable, value in (("GBM_BACKEND", "nvidia-drm"), + ("__GLX_VENDOR_LIBRARY_NAME", "nvidia"), + ("MESA_GL_VERSION_OVERRIDE", "4.6"), + ("MESA_GLES_VERSION_OVERRIDE", "3.2"), + ("MESA_GLSL_VERSION_OVERRIDE", "460")): + with self.subTest(variable=variable): + self.assertEqual(self.run_detector({variable: value}, system=False).returncode, 0) + self.assertEqual(self.run_detector({variable: value}).returncode, 1) + folder = self.root / "home/tester/.config/hypr" + folder.mkdir(parents=True, exist_ok=True) + (folder / "env.conf").write_text(f"env = {variable},{value}\n") + self.assertEqual(self.run_detector().returncode, 1) + (folder / "env.conf").unlink() + + def test_missing_file_does_not_mask_unresolved_choice(self): + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir() + (folder / "env").write_text("VK_DRIVER_FILES=$OTHER_MESA\n") + result = self.run_detector() + self.assertNotEqual(result.returncode, 0, result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/aurora-sep/recipes/mesa-m3/user-setup.list b/tools/aurora-sep/recipes/mesa-m3/user-setup.list index 0bd73c8f394f6c..31f55e501f0885 100644 --- a/tools/aurora-sep/recipes/mesa-m3/user-setup.list +++ b/tools/aurora-sep/recipes/mesa-m3/user-setup.list @@ -15,6 +15,12 @@ # file, for an assignment that replaces it (does not keep # $LD_LIBRARY_PATH), since that drops /opt/mesa-m3/lib after the # session hook ran. Unrelated entries added to it are no finding. +# With --system-provider, an entry holding libEGL, libGLESv2, libGL, +# libGLX, libglapi, libgbm or a gbm/ directory is a finding too; +# entries split on ":" and ";" as glibc does, and a relative or +# empty entry (the current directory) is unknown. A plain reference +# to the previous value counts as empty, since an earlier file can +# clear it; ${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} is the safe form. # envfile a file that sets session variables, searched for the variables # above. Shell, environment.d and /etc/environment lines are split # like a POSIX shell (quotes, comments, "export", ";"); Hyprland diff --git a/tools/aurora-sep/tests/capture-error-wipe/README.md b/tools/aurora-sep/tests/capture-error-wipe/README.md new file mode 100644 index 00000000000000..4e4d3d7880bb58 --- /dev/null +++ b/tools/aurora-sep/tests/capture-error-wipe/README.md @@ -0,0 +1,9 @@ +# Capture buffer cleanup regression + +Run `python3 tools/aurora-sep/tests/capture-error-wipe/run.py` from a kernel checkout. Set `RUSTC` if the host Rust compiler is not on PATH. This test needs Python 3 and a host Rust compiler; it does not compile a kernel, access a sensor, or need root. + +The runner extracts the actual `read_capture`, CRC implementation, `Capture` wrapper, and its destructor from the selected `sensor.rs`. Only the allocator and SPI call are synthetic. Fixture constants are checked against the selected production source. The fake allocator records initialized bytes at deallocation so each error path can establish whether the owner wiped the receive buffer. + +Nine cases cover short/oversized input, allocation and resize failures, SPI failures after partial/full writes, invalid CRC, and successful buffer ownership/cleanup. The unpatched production source reproduces three failures. To reproduce that control, save `git show HEAD:drivers/soc/apple/sensor.rs` before applying the patch and pass `--source /path/to/baseline-sensor.rs --expect-failures 3`. + +This is a source-level memory-lifetime regression, not physical capture or power-loss evidence. It observes the buffer before the allocator releases it and does not assert properties of the real allocator, SPI controller, or firmware. All simulated capture data is synthetic. diff --git a/tools/aurora-sep/tests/capture-error-wipe/cases.rs b/tools/aurora-sep/tests/capture-error-wipe/cases.rs new file mode 100644 index 00000000000000..13fe2c9ca05457 --- /dev/null +++ b/tools/aurora-sep/tests/capture-error-wipe/cases.rs @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +fn init() { + FREED.with(|v| v.borrow_mut().clear()); + FRAME.with(|v| *v.borrow_mut() = vec![7; 12]); + RC.with(|v| v.set(0)); + PARTIAL.with(|v| v.set(false)); + ALLOC_FAIL.with(|v| v.set(false)); + RESIZE_FAIL.with(|v| v.set(false)); + CALLS.with(|v| v.set(0)); +} +fn wiped() { + FREED.with(|v| { + let v = v.borrow(); + assert_eq!(v.len(), 1); + assert!( + v[0].iter().all(|b| *b == 0), + "image-bearing allocation freed without wiping: {:?}", + v[0] + ); + }); +} +#[test] +fn partial_bus_failure_wipes() { + init(); + RC.with(|v| v.set(-5)); + PARTIAL.with(|v| v.set(true)); + assert!(matches!( + read_capture(12), + Err(CaptureError::Bus(Error(-5))) + )); + wiped(); +} +#[test] +fn complete_bus_failure_wipes() { + init(); + RC.with(|v| v.set(-110)); + assert!(matches!( + read_capture(12), + Err(CaptureError::Bus(Error(-110))) + )); + wiped(); +} +#[test] +fn crc_rejection_wipes() { + init(); + assert!(matches!( + read_capture(12), + Err(CaptureError::Checksum { .. }) + )); + wiped(); +} +#[test] +fn success_preserves_until_owner_dropped() { + init(); + FRAME.with(|f| { + let mut f = f.borrow_mut(); + let crc = crc16_ansi(&f[..10]); + f[10..].copy_from_slice(&crc.to_le_bytes()); + }); + let c = match read_capture(12) { + Ok(c) => c, + Err(_) => panic!("unexpected error"), + }; + assert_eq!(&c.bytes()[..10], &[7; 10]); + FREED.with(|v| assert!(v.borrow().is_empty())); + drop(c); + wiped(); +} +#[test] +fn zero_length_no_io() { + init(); + assert!(matches!(read_capture(0), Err(CaptureError::Length(0)))); + CALLS.with(|v| assert_eq!(v.get(), 0)); +} +#[test] +fn crc_only_no_io() { + init(); + assert!(matches!(read_capture(2), Err(CaptureError::Length(2)))); + CALLS.with(|v| assert_eq!(v.get(), 0)); +} +#[test] +fn over_max_no_io() { + init(); + assert!(matches!( + read_capture(MAX_CAPTURE as u32 + 1), + Err(CaptureError::Length(_)) + )); + CALLS.with(|v| assert_eq!(v.get(), 0)); +} +#[test] +fn allocation_failure_no_io() { + init(); + ALLOC_FAIL.with(|v| v.set(true)); + assert!(matches!(read_capture(12), Err(CaptureError::NoMemory))); + CALLS.with(|v| assert_eq!(v.get(), 0)); + FREED.with(|v| assert!(v.borrow().is_empty())); +} +#[test] +fn resize_failure_no_image_written() { + init(); + RESIZE_FAIL.with(|v| v.set(true)); + assert!(matches!(read_capture(12), Err(CaptureError::NoMemory))); + CALLS.with(|v| assert_eq!(v.get(), 0)); + FREED.with(|v| assert_eq!(&*v.borrow(), &[Vec::::new()])); +} diff --git a/tools/aurora-sep/tests/capture-error-wipe/prefix.rs b/tools/aurora-sep/tests/capture-error-wipe/prefix.rs new file mode 100644 index 00000000000000..1a554a9e5d5713 --- /dev/null +++ b/tools/aurora-sep/tests/capture-error-wipe/prefix.rs @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#![allow(dead_code)] +use std::cell::{Cell, RefCell}; +use std::ops::{Deref, DerefMut}; +const GFP_KERNEL: u32 = 0; +const CRC_LEN: usize = 2; +const MAX_CAPTURE: usize = 0x10000; +const CMD_LEN: usize = 7; +const READ_CMD_LEN: usize = 11; +const CMD_READ_PREFIX: [u8; CMD_LEN] = [0x80, 0x13, 0x00, 0x0b, 0x00, 0x00, 0x00]; +#[derive(Debug)] +struct Error(i32); +impl Error { + fn from_errno(e: i32) -> Self { + Self(e) + } +} +thread_local! { + static FREED:RefCell>>=const{RefCell::new(Vec::new())}; + static FRAME:RefCell>=const{RefCell::new(Vec::new())}; + static RC:Cell=const{Cell::new(0)}; + static PARTIAL:Cell=const{Cell::new(false)}; + static ALLOC_FAIL:Cell=const{Cell::new(false)}; + static RESIZE_FAIL:Cell=const{Cell::new(false)}; + static CALLS:Cell=const{Cell::new(0)}; +} +struct KVec(Vec); +impl KVec { + fn with_capacity(n: usize, _f: u32) -> Result { + if ALLOC_FAIL.with(|v| v.get()) { + Err(Error(-12)) + } else { + Ok(Self(Vec::with_capacity(n))) + } + } + fn resize(&mut self, n: usize, b: u8, _f: u32) -> Result<(), Error> { + if RESIZE_FAIL.with(|v| v.get()) { + Err(Error(-12)) + } else { + self.0.resize(n, b); + Ok(()) + } + } +} +impl Deref for KVec { + type Target = [T]; + fn deref(&self) -> &[T] { + &self.0 + } +} +impl DerefMut for KVec { + fn deref_mut(&mut self) -> &mut [T] { + &mut self.0 + } +} +// Only u8 is instantiated; the generic hook records the raw initialized bytes. +impl Drop for KVec { + fn drop(&mut self) { + assert_eq!(std::mem::size_of::(), 1); + let b = unsafe { std::slice::from_raw_parts(self.0.as_ptr().cast::(), self.0.len()) }; + FREED.with(|v| v.borrow_mut().push(b.to_vec())); + } +} +unsafe fn sep_sensor_xfer2( + tx: *const std::ffi::c_void, + tn: usize, + rx: *mut std::ffi::c_void, + rn: usize, +) -> i32 { + CALLS.with(|v| v.set(v.get() + 1)); + assert_eq!(tn, READ_CMD_LEN); + let cmd = unsafe { std::slice::from_raw_parts(tx.cast::(), tn) }; + assert_eq!(&cmd[..CMD_LEN], &CMD_READ_PREFIX); + assert_eq!( + u32::from_le_bytes(cmd[CMD_LEN..].try_into().unwrap()), + rn as u32 + ); + FRAME.with(|f| { + let f = f.borrow(); + let n = if PARTIAL.with(|v| v.get()) { + rn / 2 + } else { + rn + }; + assert!(f.len() >= n); + unsafe { std::ptr::copy_nonoverlapping(f.as_ptr(), rx.cast::(), n) } + }); + RC.with(|v| v.get()) +} diff --git a/tools/aurora-sep/tests/capture-error-wipe/run.py b/tools/aurora-sep/tests/capture-error-wipe/run.py new file mode 100644 index 00000000000000..b40934ef456276 --- /dev/null +++ b/tools/aurora-sep/tests/capture-error-wipe/run.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the production capture owner/parser with synthetic SPI and allocation.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile + + +def function(text, signature): + start = text.index(signature) + brace = text.index('{', start) + depth = 1 + end = brace + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +def main(): + here = Path(__file__).resolve().parent + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source', type=Path, + default=here.parents[3] / 'drivers/soc/apple/sensor.rs') + parser.add_argument('--expect-failures', type=int, choices=(0, 3), default=0) + args = parser.parse_args() + text = args.source.read_text() + header = (here / 'prefix.rs').read_text() + for name in ('CMD_LEN', 'READ_CMD_LEN', 'CMD_READ_PREFIX', 'CRC_LEN', 'MAX_CAPTURE'): + pattern = r'(?:pub\(crate\) )?const ' + name + r'\s*:[^\n]+;' + real = re.search(pattern, text).group(0).replace('pub(crate) ', '') + fake = re.search(pattern, header).group(0) + if re.sub(r'\s+', '', real) != re.sub(r'\s+', '', fake): + raise SystemExit('Fixture constant differs from production: ' + name) + start = text.index('pub(crate) struct Capture(') + end = text.index('pub(crate) fn read_capture(', start) + production = (function(text, 'fn crc16_ansi(') + '\n' + text[start:end] + + function(text, 'pub(crate) fn read_capture(')) + harness = header + '\n' + production + '\n' + (here / 'cases.rs').read_text() + with tempfile.TemporaryDirectory(prefix='sep-capture-regression-') as name: + temp = Path(name) + source = temp / 'harness.rs' + binary = temp / 'tests' + source.write_text(harness) + subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '--test', + str(source), '-o', str(binary)], check=True, timeout=90) + result = subprocess.run([str(binary), '--test-threads=1'], text=True, + capture_output=True, timeout=90) + print(result.stdout, end='') + print(result.stderr, end='') + summary = re.search(r'test result: (\w+)\. (\d+) passed; (\d+) failed;', result.stdout) + if not summary: + raise SystemExit('Missing test summary') + passed, failed = int(summary[2]), int(summary[3]) + expected_code = 101 if args.expect_failures else 0 + if (passed, failed, result.returncode) != (9 - args.expect_failures, + args.expect_failures, expected_code): + raise SystemExit('Unexpected regression result') + print(json.dumps({'passed': passed, 'failed': failed, + 'expected_failures': args.expect_failures, + 'source_sha256': hashlib.sha256(text.encode()).hexdigest(), + 'production_excerpts_sha256': hashlib.sha256(production.encode()).hexdigest(), + 'hardware_access': False}, sort_keys=True)) + + +if __name__ == '__main__': + main() diff --git a/tools/aurora-sep/tests/test_air_gpu.py b/tools/aurora-sep/tests/test_air_gpu.py index 26cec8567230fd..b6ee6b1c4b9857 100644 --- a/tools/aurora-sep/tests/test_air_gpu.py +++ b/tools/aurora-sep/tests/test_air_gpu.py @@ -174,6 +174,7 @@ def prelude(self, script, root=True): STATE_DIR='{self.state}' CMDLINE='{self.cmdline}' LOCKS='{self.tmp}/run/boot-partition.lock {self.tmp}/run/limine-global.lock' +COMPAT_LOCKS='' LIMINE_DEFAULTS='{self.tmp}/etc/limine' KREL='{KREL}' is_root() {{ {'true' if root else 'false'}; }} diff --git a/tools/aurora-sep/tests/test_boot_locks.py b/tools/aurora-sep/tests/test_boot_locks.py new file mode 100644 index 00000000000000..8df961536bf8eb --- /dev/null +++ b/tools/aurora-sep/tests/test_boot_locks.py @@ -0,0 +1,246 @@ +"""The boot-partition tools' compatibility lock in /tmp: created when missing and locked, never +followed through a link, and anything at that path that is not a regular file of the tool's own +user (root) makes the tool refuse before it changes anything. The /run/lock lock is taken as +before.""" +from pathlib import Path +import fcntl +import importlib.util +import os +import shutil +import stat +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +TOOLS = Path(__file__).resolve().parents[1] +ONESHOT = TOOLS / 'air-gpu/air-gpu-oneshot.sh' +INSTALLER = TOOLS / 'install-aurora-sep.sh' + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +ESP = load('esp_history_locks', TOOLS / 'esp-history.py') +M3 = load('m3_boot_profile_locks', TOOLS / 'm3-boot-profile.py') + + +def held_by_someone(path): + """True when another open file description holds an exclusive flock on path.""" + fd = os.open(path, os.O_RDONLY) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return True + finally: + os.close(fd) + return False + + +class PythonLocks(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.boot = self.root / 'run/boot-partition.lock' + self.compat = self.root / 'tmp/limine-global.lock' + self.compat.parent.mkdir() + + def lockers(self): + return (('esp-history', lambda: ESP.lock([self.boot], [self.compat])), + ('m3-boot-profile', lambda: M3.locks([self.boot], 0.2, [self.compat]))) + + def test_defaults_name_the_compat_lock_separately(self): + self.assertEqual(ESP.BOOT_LOCK, Path('/run/lock/boot-partition.lock')) + self.assertEqual(ESP.COMPAT_LOCK, Path('/tmp/limine-global.lock')) + text = (TOOLS / 'm3-boot-profile.py').read_text() + self.assertIn("args.lock = [Path('/run/lock/boot-partition.lock')]", text) + self.assertIn("args.compat_lock = args.compat_lock or [Path('/tmp/limine-global.lock')]", text) + + def test_missing_compat_lock_is_created_and_locked(self): + for name, locker in self.lockers(): + with self.subTest(name): + with locker(): + self.assertTrue(held_by_someone(self.boot)) + self.assertTrue(held_by_someone(self.compat)) + st = self.compat.lstat() + self.assertTrue(stat.S_ISREG(st.st_mode)) + self.assertEqual(stat.S_IMODE(st.st_mode), 0o600) + self.compat.unlink() + + def assert_refused(self): + for name, locker in self.lockers(): + with self.subTest(name): + with self.assertRaises(ValueError) as e: + with locker(): + self.fail('ran without the compatibility lock') + self.assertIn('Nothing was changed', str(e.exception)) + self.assertFalse(held_by_someone(self.boot)) + + def test_symlinked_compat_lock_refuses(self): + target = self.root / 'victim' + self.compat.symlink_to(target) + self.assert_refused() + self.assertFalse(target.exists()) + target.write_text('x') + self.assert_refused() + self.assertFalse(held_by_someone(target)) + + def test_compat_lock_of_another_user_refuses(self): + self.compat.touch() + # The file belongs to someone else when the tool's own uid is another one. + with patch.object(os, 'geteuid', return_value=os.geteuid() + 1): + self.assert_refused() + + def test_open_refused_by_the_kernel_refuses(self): + # fs.protected_regular: root's O_CREAT open of another user's file in sticky /tmp. + real = os.open + + def protected(path, flags, *a): + if Path(path) == self.compat: + raise PermissionError(13, 'Permission denied') + return real(path, flags, *a) + for module in (ESP, M3): + with self.subTest(module.__name__), patch.object(module.os, 'open', side_effect=protected): + with self.assertRaises(ValueError): + with (ESP.lock([self.boot], [self.compat]) if module is ESP + else M3.locks([self.boot], 0.2, [self.compat])): + self.fail('ran without the compatibility lock') + + def test_own_compat_lock_is_taken_and_a_holder_still_blocks(self): + self.compat.touch() + os.chmod(self.compat, 0o600) + for name, locker in self.lockers(): + with self.subTest(name): + with locker(): + self.assertTrue(held_by_someone(self.compat)) + self.assertFalse(held_by_someone(self.compat)) + holder = os.open(self.compat, os.O_RDONLY) + self.addCleanup(os.close, holder) + fcntl.flock(holder, fcntl.LOCK_EX) + with self.assertRaises(BlockingIOError): + with ESP.lock([self.boot], [self.compat]): + pass + with self.assertRaises(TimeoutError): + with M3.locks([self.boot], 0.2, [self.compat]): + pass + + def test_a_fifo_refuses(self): + os.mkfifo(self.compat) + self.assert_refused() + + def test_installer_copies_match(self): + installer = INSTALLER.read_text() + for tag, path in (('ESP_HISTORY_PY', 'esp-history.py'), ('M3_BOOT_PROFILE_PY', 'm3-boot-profile.py')): + embedded = installer.split(f"<<'{tag}'\n", 1)[1].split(f'\n{tag}\n', 1)[0] + '\n' + self.assertEqual(embedded, (TOOLS / path).read_text(), path) + self.assertIn('M3MAX_KIT_LOCKS="/run/lock/boot-partition.lock"\n', installer) + self.assertIn('M3MAX_KIT_COMPAT_LOCKS="/tmp/limine-global.lock"\n', installer) + self.assertIn(' COMPAT_LOCKS=$M3MAX_KIT_COMPAT_LOCKS\n', installer) + + +@unittest.skipUnless(shutil.which('flock') and shutil.which('stat'), 'flock and stat are needed') +class ShellLocks(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.boot = self.root / 'run/boot-partition.lock' + self.compat = self.root / 'tmp/limine-global.lock' + self.compat.parent.mkdir() + + def take(self, then='true'): + """Source the one-shot script, take its locks, then run `then` while they are held.""" + script = f""" +set -euo pipefail +AIR_GPU_SOURCE_ONLY=1 source '{ONESHOT}' +LOCKS='{self.boot}' +COMPAT_LOCKS='{self.compat}' +refuse() {{ echo "REFUSED: $*"; exit 7; }} +take_locks +echo "held ${{#LOCK_FDS[@]}}" +{then} +""" + return subprocess.run(['bash', '-c', script], capture_output=True, text=True) + + def probe(self, path): + return f"flock -n '{path}' true && echo free || echo busy" + + def test_defaults(self): + text = ONESHOT.read_text() + self.assertIn('\nLOCKS="/run/lock/boot-partition.lock"\n', text) + self.assertIn('\nCOMPAT_LOCKS="/tmp/limine-global.lock"\n', text) + + def test_missing_compat_lock_is_created_and_held(self): + r = self.take(self.probe(self.compat)) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('held 2', r.stdout) + self.assertIn('busy', r.stdout) + self.assertTrue(self.compat.is_file() and not self.compat.is_symlink()) + + def test_symlinked_compat_lock_refuses(self): + target = self.root / 'victim' + target.write_text('x') + self.compat.symlink_to(target) + r = self.take(self.probe(target)) + self.assertEqual(r.returncode, 7, r.stdout + r.stderr) + self.assertIn("not root's own lock file", r.stdout) + self.compat.unlink() + self.compat.symlink_to(self.root / 'missing') + r = self.take() + self.assertEqual(r.returncode, 7, r.stdout + r.stderr) + self.assertFalse((self.root / 'missing').exists()) + + def test_own_regular_compat_lock_is_held(self): + self.compat.write_text('') + r = self.take(self.probe(self.compat)) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('held 2', r.stdout) + self.assertIn('busy', r.stdout) + + def test_created_compat_lock_is_private(self): + r = self.take() + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertEqual(stat.S_IMODE(self.compat.stat().st_mode) & 0o077, 0) + + def test_stderr_survives_the_compat_lock(self): + # Opening the compatibility lock must leave the script's stderr alone: what it + # prints afterwards (a refusal, say) still has to reach the operator. + self.compat.write_text('') + r = self.take('echo "after the locks" >&2') + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('after the locks', r.stderr) + + def test_held_compat_lock_refusal_is_printed(self): + self.compat.write_text('') + script = f""" +set -euo pipefail +AIR_GPU_SOURCE_ONLY=1 source '{ONESHOT}' +LOCKS='{self.boot}' +COMPAT_LOCKS='{self.compat}' +log() {{ :; }} +flock() {{ if [[ $1 == -w ]]; then command flock -n "${{@:3}}"; else command flock "$@"; fi; }} +take_locks +echo "held ${{#LOCK_FDS[@]}}" +""" + with open(self.compat) as holder: + fcntl.flock(holder, fcntl.LOCK_EX) + r = subprocess.run(['bash', '-c', script], capture_output=True, text=True) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertNotIn('held', r.stdout) + self.assertIn('is held by another tool', r.stderr) + self.assertIn('Nothing was changed.', r.stderr) + + def test_a_fifo_refuses(self): + os.mkfifo(self.compat) + r = self.take() + self.assertEqual(r.returncode, 7, r.stdout + r.stderr) + # The /run/lock lock was let go again. + self.assertFalse(held_by_someone(self.boot)) + +if __name__ == '__main__': + unittest.main() diff --git a/tools/aurora-sep/tests/test_collect_handover.py b/tools/aurora-sep/tests/test_collect_handover.py new file mode 100644 index 00000000000000..4b2d0c9d499081 --- /dev/null +++ b/tools/aurora-sep/tests/test_collect_handover.py @@ -0,0 +1,78 @@ +"""air-gpu-collect.sh hands its tgz to the user privately: the file is created by the user's own +process with mode 0600, and no copy is left in the temp directory (or anywhere world-readable) +when the user's home cannot be written.""" +import os +from pathlib import Path +import stat +import unittest + +import test_air_gpu as A +from test_air_gpu import ARMED, COLLECT, RUNNING, k1 + + +class CollectHandOverTest(unittest.TestCase): + def setUp(self): + # CollectRunTest's fake Mac, journal and home, without its tests. + rig = A.CollectRunTest("test_this_boot") + rig.setUp() + self.addCleanup(rig.doCleanups) + self.mac, self.home, self.statedir = rig.mac, rig.home, rig.statedir + self.rig = rig + self.tmpdir = self.mac.tmp / "tmpdir" + self.tmpdir.mkdir() + self.mac.cmdline.write_text(ARMED + "\n") + rig.journal(0, ARMED, RUNNING + k1("job-completed", ": the first compute job finished")) + + def collect(self): + t = self.mac.tmp + body = f""" +export FAKE='{self.rig.fake}' +export TMPDIR='{self.tmpdir}' +DEBUGFS='{t}/debug' +SYS='{t}/sys' +BOOT_ID='{self.rig.boot_id}' +STATE_DIR='{self.statedir}' +EXTRA_HOMES='' +user_home() {{ echo '{self.home}'; }} +main +""" + return self.mac.run(COLLECT, body, check=True) + + def leftovers(self): + return sorted(p.name for p in self.tmpdir.iterdir()) + + def test_the_tgz_is_private_and_nothing_is_left_behind(self): + old = os.umask(0o022) + try: + self.collect() + finally: + os.umask(old) + tgz = list(self.home.glob("air-gpu-collect-*.tgz")) + self.assertEqual(len(tgz), 1) + mode = stat.S_IMODE(tgz[0].stat().st_mode) + self.assertEqual(mode & 0o077, 0, oct(mode)) + self.assertEqual(tgz[0].stat().st_uid, os.getuid()) + self.assertEqual(self.leftovers(), []) + + def test_an_unwritable_home_keeps_a_root_only_copy(self): + os.chmod(self.home, 0o500) + self.addCleanup(os.chmod, self.home, 0o700) + if os.access(self.home, os.W_OK): + self.skipTest("running with DAC override (root)") + proc = self.collect() + self.assertEqual(list(self.home.glob("air-gpu-collect-*.tgz")), []) + self.assertEqual(self.leftovers(), []) + kept = list((self.statedir / "collect").glob("air-gpu-collect-*.tgz")) + self.assertEqual(len(kept), 1, proc.stdout) + self.assertEqual(stat.S_IMODE(kept[0].stat().st_mode) & 0o077, 0) + self.assertEqual(stat.S_IMODE((self.statedir / "collect").stat().st_mode) & 0o077, 0) + self.assertIn("readable by root only", proc.stdout) + + def test_no_world_readable_hand_over_in_the_script(self): + text = (Path(__file__).resolve().parents[1] / "air-gpu/air-gpu-collect.sh").read_text() + self.assertNotIn("chmod 0644", text) + self.assertNotIn("mktemp --tmpdir", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/aurora-sep/tests/test_diag_sensor.py b/tools/aurora-sep/tests/test_diag_sensor.py index a8a6a114447891..86b564752c0d8a 100644 --- a/tools/aurora-sep/tests/test_diag_sensor.py +++ b/tools/aurora-sep/tests/test_diag_sensor.py @@ -94,10 +94,31 @@ return (u64)now.tv_sec * 1000000000ULL + now.tv_nsec; } static inline u64 div_u64(u64 value, u32 divisor) { return value / divisor; } +''', + 'linux/kernfs.h': r''' +#include +struct kernfs_node { + const char *name; + struct kernfs_node *const *children; + unsigned int notifies; +}; +static inline void kernfs_notify(struct kernfs_node *kn) +{ + if (kn) + kn->notifies++; +} +''', + 'linux/spinlock.h': r''' +typedef struct { int unused; } spinlock_t; +#define DEFINE_SPINLOCK(x) spinlock_t x +#define spin_lock_irqsave(lock, flags) do { (void)(lock); (flags) = 0; } while (0) +#define spin_unlock_irqrestore(lock, flags) do { (void)(lock); (void)(flags); } while (0) ''', 'linux/device.h': r''' #include -struct device { int unused; }; +struct kernfs_node; +struct kobject { struct kernfs_node *sd; }; +struct device { struct kobject kobj; }; #define dev_info(dev, ...) ((void)(dev)) struct attribute { const char *name; umode_t mode; }; struct device_attribute { @@ -118,11 +139,32 @@ registered_group = grp; return 0; } +static inline int devm_add_action_or_reset(struct device *dev, + void (*action)(void *), void *data) +{ + (void)dev; + (void)action; + (void)data; + return 0; +} ''', 'linux/sysfs.h': r''' +#include #include #include #include +#include +static inline struct kernfs_node *sysfs_get_dirent(struct kernfs_node *parent, + const char *name) +{ + if (!parent || !parent->children) + return NULL; + for (struct kernfs_node *const *c = parent->children; *c; c++) + if (!strcmp((*c)->name, name)) + return *c; + return NULL; +} +static inline void sysfs_put(struct kernfs_node *kn) { (void)kn; } static inline int sysfs_emit(char *buf, const char *fmt, ...) { va_list args; @@ -160,6 +202,7 @@ #include #include #include +#include #include #include "shim.h" @@ -215,7 +258,13 @@ int main(int argc, char **argv) { - struct device dev; + struct kernfs_node keystore_kn = { .name = "keystore" }; + struct kernfs_node touchid_kn = { .name = "touchid" }; + struct kernfs_node *const diag_children[] = { &keystore_kn, &touchid_kn, NULL }; + struct kernfs_node diag_kn = { .name = "diag", .children = diag_children }; + struct kernfs_node *const root_children[] = { &diag_kn, NULL }; + struct kernfs_node root_kn = { .name = "root", .children = root_children }; + struct device dev = { .kobj = { .sd = &root_kn } }; unsigned int bind, stale; /* The Neo: warm attach, xART writable, no guard. */ @@ -245,6 +294,10 @@ expect("attach", "sensor_attach", "attached"); expect("attach", "restore", "restored"); expect("attach", "touchid", "ready"); + if (touchid_kn.notifies != 2) { + printf("FAIL attach: touchid notifies is %u, want 2\n", touchid_kn.notifies); + failures++; + } if (argc > 1) dump(argv[1]); @@ -285,6 +338,7 @@ #include #include #include +#include #include #include "shim.h" @@ -310,7 +364,7 @@ /* argv: level list matching-at-probe refusals matching-after-refusal */ int main(int argc, char **argv) { - struct device dev; + struct device dev = { 0 }; int refusals = atoi(argv[4]); sep_diag_set_xart_guard(atoi(argv[1]), atoi(argv[2]), atoi(argv[3])); diff --git a/tools/aurora-sep/tests/test_hdcp_client.py b/tools/aurora-sep/tests/test_hdcp_client.py new file mode 100644 index 00000000000000..29f09f3f38a885 --- /dev/null +++ b/tools/aurora-sep/tests/test_hdcp_client.py @@ -0,0 +1,54 @@ +# SPDX-License-Identifier: GPL-2.0-only +"""Host checks for the Apple SEP HDCP 2.2 transmitter client.""" +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[3] +APPLE = ROOT / "drivers/soc/apple" +HEADER = ROOT / "include/linux/apple-sep-hdcp.h" + + +class HdcpClientChecks(unittest.TestCase): + def test_header_has_disabled_stubs_for_every_declared_api(self): + text = HEADER.read_text() + self.assertIn("#if IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE)", text) + self.assertIn("#else /* !IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE) */", text) + enabled, disabled = text.split( + "#else /* !IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE) */", 1 + ) + decl_re = re.compile(r"\b(apple_sep_hdcp_\w+)\s*\(") + enabled_fns = set(decl_re.findall(enabled)) + disabled_fns = set(decl_re.findall(disabled)) + self.assertGreaterEqual(len(enabled_fns), 13) + self.assertEqual(enabled_fns, disabled_fns) + + def test_sep_wires_hdcp_lifecycle_and_forgets_registered_ool(self): + sep = (APPLE / "sep.rs").read_text() + self.assertIn("mod hdcp;", sep) + self.assertIn("hdcp::EP_HDCP => self.on_hdcp(msg),", sep) + self.assertIn("self.hdcp_discovered(&f);", sep) + self.assertIn("data.register_hdcp_kernel()", sep) + self.assertIn("self.unregister_hdcp_kernel();", sep) + remove_fn = sep[sep.index("fn remove(&self)"):] + self.assertIn("self.hdcp_wq.notify_all();", remove_fn) + self.assertIn("&self.ool_hdcp,", remove_fn) + + def test_hdcp_uses_runtime_enumeration_and_ool_sync(self): + hdcp = (APPLE / "hdcp.rs").read_text() + self.assertIn("Command::QueryChannels", hdcp) + self.assertIn("Command::GetChannelInfo", hdcp) + self.assertIn("ool_repoison(&sep.ool_hdcp", hdcp) + self.assertIn("ool_await_written(&sep.ool_hdcp", hdcp) + self.assertIn("hdcp_scrub_buffers", hdcp) + self.assertIn("PHASE_READY", hdcp) + self.assertIn("pm::SleepGate::Open", hdcp) + + def test_shim_scrubs_buffers(self): + shim = (APPLE / "hdcp_shim.c").read_text() + self.assertIn("kfree_sensitive(in);", shim) + self.assertIn("memzero_explicit(", shim) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/aurora-sep/tests/test_kernel_log_anchor.py b/tools/aurora-sep/tests/test_kernel_log_anchor.py new file mode 100644 index 00000000000000..deb1b08fd4d68b --- /dev/null +++ b/tools/aurora-sep/tests/test_kernel_log_anchor.py @@ -0,0 +1,172 @@ +# SPDX-License-Identifier: GPL-2.0-only +"""aurora-sep-policy-change and aurora-sep-ready act only on the apple_sep driver's own kernel +messages: a line that merely contains the driver's words (a USB product string, another device) +is not one.""" +from pathlib import Path +import importlib.machinery +import importlib.util +import json +import os +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +TOOLS = Path(__file__).resolve().parents[1] +UUID = '0123456789abcdef0123456789abcdef' +OTHER = 'fedcba9876543210fedcba9876543210' +DEVICE = '406600000.sep' + + +def load_policy_change(): + loader = importlib.machinery.SourceFileLoader('policy_change_anchor', + str(TOOLS / 'aurora-sep-policy-change')) + module = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader)) + loader.exec_module(module) + return module + + +M = load_policy_change() + + +def kernel(msg, device=None, subsystem='platform', transport='kernel', facility='0'): + e = {'MESSAGE': msg, '_TRANSPORT': transport} + if facility is not None: + e['SYSLOG_FACILITY'] = facility + if device is not None: + e['_KERNEL_DEVICE'] = device + e['_KERNEL_SUBSYSTEM'] = subsystem + return e + + +REAL_REFUSAL = kernel(f'apple_sep: xART guard: refused to rewrite kind-4 record {UUID}, ' + 'which this Linux install did not create') +REAL_BASE = kernel(f'apple_sep {DEVICE}: xART: APFS-resolved .gl extent (base 0x4d4000); 170 slots, ' + '10 live records, max revision 1765, 0 malformed, 0 duplicate, 0 repaired; writes ENABLED', + f'+platform:{DEVICE}') +FORGED = [ + # A USB device's product string. + kernel(f'usb 1-1: Product: xART guard: refused to rewrite kind-3 record {OTHER},', '+usb:1-1', 'usb'), + kernel('usb 1-1: Product: xART: APFS-resolved .gl extent (base 0x1000);', '+usb:1-1', 'usb'), + # Text that contains the driver's prefix somewhere else, without a device. + kernel(f'EXT4-fs: bad option apple_sep: xART guard: refused to rewrite kind-4 record {OTHER},'), + # The device prefix on another subsystem's or device's entry. + kernel(f'apple_sep {DEVICE}: xART: APFS-resolved .gl extent (base 0x2000);', f'+usb:{DEVICE}', 'usb'), + kernel('apple_sep 1-1: xART: APFS-resolved .gl extent (base 0x3000);', '+platform:1-1'), + # A _KERNEL_DEVICE that is not a string. + dict(kernel(f'apple_sep {DEVICE}: xART: APFS-resolved .gl extent (base 0x5000);'), _KERNEL_DEVICE=[1, 2], + _KERNEL_SUBSYSTEM='platform'), + {'MESSAGE': f'apple_sep {DEVICE}: xART: APFS-resolved .gl extent (base 0x6000);', '_TRANSPORT': 'kernel', + 'SYSLOG_FACILITY': '0', '_KERNEL_DEVICE': 7, '_KERNEL_SUBSYSTEM': 'platform'}, + # The kernel transport, but not the kernel's own facility (or none, or not a string). + kernel(f'apple_sep: xART guard: refused to rewrite kind-4 record {OTHER},', facility='1'), + kernel(f'apple_sep: xART guard: refused to rewrite kind-3 record {OTHER},', facility='3'), + kernel(f'apple_sep: xART guard: refused to rewrite kind-4 record {OTHER},', facility=None), + kernel(f'apple_sep: xART guard: refused to rewrite kind-4 record {OTHER},', facility=0), + kernel('apple_sep: xART: APFS-resolved .gl extent (base 0x7000);', facility='1'), + # Not from the kernel. + kernel(f'apple_sep: xART guard: refused to rewrite kind-4 record {OTHER},', transport='syslog'), +] + + +class PolicyChangeLog(unittest.TestCase): + def log(self, entries): + out = '\n'.join(json.dumps(e) for e in entries) + '\n' + done = subprocess.CompletedProcess([], 0, stdout=out, stderr='') + with patch.object(M.subprocess, 'run', return_value=done) as run: + text = M.kernel_log() + self.assertIn('json', run.call_args[0][0]) + return text + + def test_forged_lines_are_not_the_drivers(self): + text = self.log(FORGED) + self.assertEqual(M.REFUSED.findall(text), []) + self.assertIsNone(M.BASE.search(text)) + + def test_the_drivers_lines_are_read(self): + text = self.log(FORGED[:2] + [REAL_REFUSAL, REAL_BASE] + FORGED[2:]) + self.assertEqual(M.REFUSED.findall(text), [('4', UUID)]) + self.assertEqual(M.BASE.search(text).group(1), '0x4d4000') + + def test_patterns_are_anchored(self): + self.assertIsNone(M.REFUSED.search(f'Product: xART guard: refused to rewrite kind-4 record {UUID},')) + self.assertIsNone(M.BASE.search('Product: xART: APFS-resolved .gl extent (base 0x1);')) + + def test_one_forged_refusal_does_not_block_or_steer_main(self): + # A forged line next to no real refusal: nothing to allow. + text = self.log(FORGED + [REAL_BASE]) + with patch.object(M, 'kernel_log', return_value=text), \ + patch.object(M.os, 'geteuid', return_value=0), \ + patch.object(M, 'backup') as backup, patch.object(M, 'arm') as arm: + with self.assertRaises(SystemExit): + M.main(['aurora-sep-policy-change']) + backup.assert_not_called() + arm.assert_not_called() + # Next to a real refusal: the real record, not "more than one". + text = self.log(FORGED + [REAL_REFUSAL, REAL_BASE]) + with patch.object(M, 'kernel_log', return_value=text), \ + patch.object(M.os, 'geteuid', return_value=0), \ + patch.object(M, 'backup', return_value='/x') as backup, \ + patch.object(M, 'arm') as arm: + M.main(['aurora-sep-policy-change']) + arm.assert_called_once_with(M.entry(4, bytes.fromhex(UUID))) + + def test_arch_copy_is_the_same(self): + for name in ('aurora-sep-policy-change', 'aurora-sep-ready'): + self.assertEqual((TOOLS / 'packaging/arch/aurora-sep' / name).read_bytes(), + (TOOLS / name).read_bytes(), name) + + +class ReadyLog(unittest.TestCase): + """aurora-sep-ready's rebuild trigger.""" + + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + self.bin, self.run = self.root / 'bin', self.root / 'run' + self.bin.mkdir() + self.diag = self.root / 'devices' / DEVICE / 'diag' + self.diag.mkdir(parents=True) + self.calls = self.root / 'calls' + for tool in ('journalctl', 'systemctl', 'authselect'): + (self.bin / tool).write_text(f'#!/bin/sh\necho "{tool} $*" >>"{self.calls}"\n' + + ('cat "$KMSG"\n' if tool == 'journalctl' else '')) + (self.bin / tool).chmod(0o755) + self.kmsg = self.root / 'kmsg' + + def ready(self, kmsg): + for name, value in {'touchid': 'ready', 'sensor_attach': 'not-ready', 'restore': 'restored', + 'matching': 'usable', 'sensor': 'online'}.items(): + (self.diag / name).write_text(value + '\n') + self.kmsg.write_text(kmsg) + done = subprocess.run(['sh', str(TOOLS / 'aurora-sep-ready')], capture_output=True, text=True, env={ + **os.environ, 'PATH': f'{self.bin}:{os.environ["PATH"]}', 'KMSG': str(self.kmsg), + 'AURORA_SEP_DEV': '/dev/null', 'AURORA_SEP_SYSFS': str(self.root / 'devices'), + 'AURORA_SEP_READY_WAIT': '0', 'AURORA_SEP_RUN': str(self.run)}) + calls = self.calls.read_text() if self.calls.exists() else '' + self.calls.unlink(missing_ok=True) + return calls + + def test_reads_only_the_sep_devices_entries(self): + calls = self.ready('') + self.assertIn(f'_KERNEL_DEVICE=+platform:{DEVICE}', calls) + self.assertIn('_KERNEL_SUBSYSTEM=platform', calls) + + def test_a_refusal_in_another_line_starts_nothing(self): + for line in ('usb 1-1: Product: sensor: LOAD_CALIBRATION refused with status 0x1c', + f'usb 1-1: Product: apple_sep {DEVICE}: sensor: SENSOR_ROOT_KEY refused', + 'apple_sep 1-1: sensor: LOAD_CALIBRATION refused with status 0x1c', + 'apple_sep 406600000xsep: sensor: LOAD_CALIBRATION refused with status 0x1c'): + with self.subTest(line): + calls = self.ready(line + '\n') + self.assertNotIn('systemctl', calls) + self.assertFalse((self.run / 'calibration-refused').exists()) + + def test_the_drivers_refusal_starts_the_rebuild(self): + calls = self.ready(f'apple_sep {DEVICE}: sensor: LOAD_CALIBRATION refused with status 0x1c\n') + self.assertIn('systemctl start --no-block aurora-touchid-setup.service', calls) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/aurora-sep/tests/test_m3_flow.py b/tools/aurora-sep/tests/test_m3_flow.py index ed001d3562937a..1d203402771a8c 100644 --- a/tools/aurora-sep/tests/test_m3_flow.py +++ b/tools/aurora-sep/tests/test_m3_flow.py @@ -971,7 +971,8 @@ def test_frozen_preparation_binds_requirements_and_explicit_archive_list(self): mkdir -p "$work" touch "$work/$(m3_pro_mesa_file)" "$work/unrelated.pkg.tar.zst" "$work/transaction.conf" python3() { - if [[ $1 == "$work/frozen-dependencies.py" ]]; then + if [[ $1 == -I && $2 == "$work/frozen-dependencies.py" ]]; then + shift printf 'planner-arg:%s\\n' "$@" >>"$FAKE/log" printf '{"transaction_config":"%s/transaction.conf","candidate_sha256":{"%s/%s":"fixture"},"dependencies":[{"file":"%s/approved.pkg.tar.gz"}]}' "$work" "$work" "$(m3_pro_mesa_file)" "$work" else command python3 "$@"; fi diff --git a/tools/aurora-sep/tests/test_m3_persistent.py b/tools/aurora-sep/tests/test_m3_persistent.py index ecab5effcf8640..4074a4de9e14eb 100644 --- a/tools/aurora-sep/tests/test_m3_persistent.py +++ b/tools/aurora-sep/tests/test_m3_persistent.py @@ -255,6 +255,8 @@ def transaction_paths(self): return self.selection()+f''' chain=limine work="{work}" +# What install_all checked (m3_install_packages installs these by name). +INSTALL_ARCHIVES=("$work/matched.pkg.tar.zst") M3_LIMINE_DEFAULTS="{defaults}" M3_GRUB_DEFAULTS="{self.etc}/default/grub" M3_PROFILE_HOOK="{self.etc}/hooks/profile.hook" diff --git a/tools/aurora-sep/tests/test_m3_pro_mesa.py b/tools/aurora-sep/tests/test_m3_pro_mesa.py index f2ef380f777ade..4d708c64069fbc 100644 --- a/tools/aurora-sep/tests/test_m3_pro_mesa.py +++ b/tools/aurora-sep/tests/test_m3_pro_mesa.py @@ -102,6 +102,19 @@ def tree(tc): return out +WORK_TO_ROOT = re.compile(r'sudo (mktemp -d|sh -c umask 022 && cat >"\$1" _ /\S+|' + r'sha256sum -- /\S+|chmod 0755 |rm -rf )$') + + +# work_write: what 12.2 wrote with "sudo tee" now gets its mode set in root's shell. +WORK_WRITE = re.compile(r'^sudo sh -c umask 022 && cat >"\$1" _ (/(?:migrate-pro-session\.py|' + r'frozen-dependencies\.py|dependency-result\.json|dependency-files|aurora-m3-gpu-check))$') + +# root_put: what 12.2 installed from a temporary file is now passed to root's shell. +ROOT_PUT = re.compile(r'^sudo sh -c umask 022 && mkdir -p "\$\(dirname "\$1"\)" && t=\$\(mktemp "\$1\.XXXXXX"\) && ' + r'\{ cat >"\$t" && chmod 0644 "\$t" && mv -f "\$t" "\$1" \|\| \{ rm -f "\$t"; exit 1; \}; \} _ (\S+)$') + + def package_check_log(tc, text): lines = text.splitlines() queries = [i for i, line in enumerate(lines) if line == 'pacman -Qu --color never'] @@ -115,6 +128,12 @@ def package_check_log(tc, text): out = [] for line in lines: if line in ('pacman -Qu --color never', 'pacman -Sy --noconfirm', 'sudo pacman -Sy --noconfirm'): continue + line = WORK_WRITE.sub(r'sudo tee \1', line) + line = ROOT_PUT.sub(r'sudo install -m 644 \1', line) + # work_to_root: root's own checked copy of the downloads (not in 12.2). + if WORK_TO_ROOT.match(line): continue + # Root's Python runs isolated (-I) since 12.2. + line = line.replace('sudo python3 -I ', 'sudo python3 ') line = line.replace('pacman -Sy --noconfirm --ask 4 ', 'pacman -S --noconfirm --ask 4 ') out.append(line) return out @@ -1683,8 +1702,8 @@ def test_nothing_is_written_for_it_outside_the_package(self): 'rm -rf "$dir"', 'if $sudo gpasswd -a "$user" "$g" >/dev/null && m3_pro_mesa_in_group "$user" "$g"; then', 'if $sudo gpasswd -d "$u" "$g" >/dev/null; then', - 'mkdir -p "$work/m3-pro"', - 'mv "$work/$file" "$work/m3-pro/"', + '$sudo mkdir -p "$work/m3-pro"', + '$sudo mv -- "$work/$file" "$work/m3-pro/"', } # Commands in command position (line start, after a pipe, a list operator, if, then or $( ), # and redirections into a variable's path. diff --git a/tools/aurora-sep/tests/test_m3max_kit.py b/tools/aurora-sep/tests/test_m3max_kit.py index 019558e4c73bac..41a7f5ed760a8d 100644 --- a/tools/aurora-sep/tests/test_m3max_kit.py +++ b/tools/aurora-sep/tests/test_m3max_kit.py @@ -385,6 +385,7 @@ def kit_body(self): M3MAX_KIT_EFIVARS='{self.efivars}' M3MAX_KIT_CMDLINE='{t}/proc/cmdline' M3MAX_KIT_LOCKS='{t}/run/boot-partition.lock {t}/run/limine-global.lock' +M3MAX_KIT_COMPAT_LOCKS='' M3MAX_KIT_LIMINE_DEFAULTS='{t}/etc/limine' M3MAX_KIT_TTY='{self.tty}' M3MAX_KIT_SETTLE=0 diff --git a/tools/aurora-sep/tests/test_root_staging.py b/tools/aurora-sep/tests/test_root_staging.py new file mode 100644 index 00000000000000..1d660d4a377de9 --- /dev/null +++ b/tools/aurora-sep/tests/test_root_staging.py @@ -0,0 +1,521 @@ +# SPDX-License-Identifier: GPL-2.0-only +"""install-aurora-sep.sh: what root installs or runs comes from a directory root owns, checked +there as root, and pacman gets the checked archives by name (no glob over the directory). The +same for the M3 Max kit's root run of this script.""" +import hashlib +import os +from pathlib import Path +import re +import stat +import subprocess +import tempfile +import unittest + +INSTALLER = Path(__file__).resolve().parents[1] / 'install-aurora-sep.sh' + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +class Staging(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.bin = self.root / 'bin' + self.bin.mkdir() + self.log = self.root / 'log' + # Stands in for sudo: records the call and runs it (as this user). + (self.bin / 'fakesudo').write_text(f'#!/bin/sh\necho "sudo $*" >>"{self.log}"\nexec "$@"\n') + (self.bin / 'pacman').write_text(f'#!/bin/sh\necho "pacman $*" >>"{self.log}"\n') + for f in self.bin.iterdir(): + f.chmod(0o755) + self.tmpdir = self.root / 'tmp' + self.tmpdir.mkdir() + + def sh(self, body): + script = f""" +set -euo pipefail +AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' +export TMPDIR='{self.tmpdir}' +die() {{ echo "DIED: $*"; exit 9; }} +{body} +""" + env = {**os.environ, 'PATH': f'{self.bin}:{os.environ["PATH"]}'} + return subprocess.run(['bash', '-c', script], capture_output=True, text=True, env=env) + + def downloads(self, **files): + d = Path(tempfile.mkdtemp(dir=self.tmpdir)) + for name, data in files.items(): + (d / name).write_bytes(data) + return d + + def stage(self, d, entries, then=''): + lines = '\n'.join(entries) + return self.sh(f""" +sudo=fakesudo +work='{d}' +candidate_archives=('{d}/a.pkg.tar.zst') +work_to_root <<'EOF' +{lines} +EOF +echo "work=$work" +echo "cand=${{candidate_archives[*]}}" +{then} +""") + + def test_copies_and_checks_into_a_new_directory(self): + d = self.downloads(**{'a.pkg.tar.zst': b'A', 'tool.sh': b'T'}) + r = self.stage(d, [f'a.pkg.tar.zst {sha(b"A")}', f'tool.sh {sha(b"T")}']) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + work = Path(re.search(r'^work=(.*)$', r.stdout, re.M).group(1)) + self.assertNotEqual(work, d) + self.assertFalse(d.exists()) # the user's copy is gone + self.assertEqual((work / 'a.pkg.tar.zst').read_bytes(), b'A') + self.assertEqual((work / 'tool.sh').read_bytes(), b'T') + self.assertEqual(stat.S_IMODE(work.stat().st_mode), 0o755) + self.assertIn(f'cand={work}/a.pkg.tar.zst', r.stdout) + self.assertIn('sha256sum', self.log.read_text()) # checked by the root side + + def test_a_file_changed_after_the_check_is_refused(self): + d = self.downloads(**{'a.pkg.tar.zst': b'changed'}) + r = self.stage(d, [f'a.pkg.tar.zst {sha(b"A")}']) + self.assertEqual(r.returncode, 9) + self.assertIn('changed after its checksum was checked', r.stdout) + + def test_a_link_planted_in_place_of_a_download_is_refused(self): + target = self.root / 'secret' + target.write_bytes(b'S') + d = self.downloads() + (d / 'a.pkg.tar.zst').symlink_to(target) + r = self.stage(d, [f'a.pkg.tar.zst {sha(b"A")}']) + self.assertEqual(r.returncode, 9) + + def test_a_failed_copy_leaves_no_directory_behind(self): + d = self.downloads(**{'a.pkg.tar.zst': b'A', 'b.pkg.tar.zst': b'changed'}) + r = self.sh(f""" +sudo=fakesudo +work='{d}' +FROZEN_PACKAGES=0 NEO_GPU_PREPARED=0 M3_PERSISTENT_TRANSACTION_ACTIVE=0 +candidate_archives=() +trap 'm3_install_cleanup' EXIT +work_to_root <<'LIST' +a.pkg.tar.zst {sha(b"A")} +b.pkg.tar.zst {sha(b"B")} +LIST +""") + self.assertEqual(r.returncode, 9, r.stdout + r.stderr) + self.assertEqual(sorted(self.tmpdir.iterdir()), []) + + def test_root_files_stay_readable_under_a_private_umask(self): + # sudo keeps the invoking user's umask. What root writes into its work directory is + # read back by the user's side, so its mode must not depend on that umask. + d = self.downloads(**{'a.pkg.tar.zst': b'A'}) + state = self.root / 'state' + r = self.sh(f""" +umask 077 +sudo=fakesudo +work='{d}' +candidate_archives=() +work_to_root <<'LIST' +a.pkg.tar.zst {sha(b"A")} +LIST +echo text | work_write "$work/dependency-result.json" +m3_gpu_check_plan() {{ :; }} +STATE='{state}' M3_GPU_CHECK='{self.root}/sbin/aurora-m3-gpu-check' +m3_gpu_check_install +stat -c 'mode %a %n' "$work" "$work"/* +""") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + modes = {name: mode for mode, name in re.findall(r'^mode (\d+) \S*/([^/\n]+)$', r.stdout, re.M)} + self.assertEqual(modes.pop('a.pkg.tar.zst'), '644') + self.assertEqual(modes.pop('dependency-result.json'), '644') + self.assertEqual(modes.pop('aurora-m3-gpu-check'), '644') + self.assertEqual(list(modes.values()), ['755'], r.stdout) + self.assertEqual((self.root / 'sbin/aurora-m3-gpu-check').stat().st_mode & 0o777, 0o755) + + def test_root_writes_into_its_work_directory_set_the_mode(self): + text = INSTALLER.read_text() + self.assertEqual(re.findall(r'^[^#\n]*\btee "\$work/[^\n]*', text, re.M), []) + for name in ('migrate-pro-session.py', 'frozen-dependencies.py', 'dependency-result.json', + 'dependency-files', 'aurora-m3-gpu-check'): + self.assertRegex(text, rf'work_write "\$work/{re.escape(name)}"') + + def test_odd_names_are_refused(self): + d = self.downloads(**{'a.pkg.tar.zst': b'A'}) + for name in ('../a.pkg.tar.zst', '.hidden', 'x/y'): + with self.subTest(name): + r = self.stage(d, [f'{name} {sha(b"A")}']) + self.assertEqual(r.returncode, 9, r.stdout) + + def test_without_sudo_nothing_moves(self): + d = self.downloads(**{'a.pkg.tar.zst': b'A'}) + r = self.sh(f"sudo=''\nwork='{d}'\ncandidate_archives=()\nwork_to_root &|])>\s*"\$work/', line), f'{name}: {line}') + self.assertIsNone(re.search(r'^\s*(mkdir|mv|cp|cat)\b[^|]*"?\$work/', line), f'{name}: {line}') + install_all = body('install_all') + self.assertIn('work_to_root < <(', install_all) + self.assertLess(install_all.index('work_to_root'), install_all.index('frozen_dependency_prepare')) + self.assertLess(install_all.index('work_to_root'), install_all.index('m3_install_packages')) + + +class PythonIsolation(unittest.TestCase): + def test_every_root_python_is_isolated(self): + text = INSTALLER.read_text() + calls = re.findall(r'\$sudo python3\b[^\n]*', text) + self.assertGreater(len(calls), 10) + for call in calls: + self.assertTrue(call.startswith('$sudo python3 -I '), call) + self.assertIn('"Exec = /usr/bin/python3 -I "', text) + self.assertIn('python3 -I - "$1" "$d/install-aurora-sep.sh"', text) + + +class KitRootCopy(unittest.TestCase): + """--m3max-kit under sudo: root runs its own checked copy, from its own directory.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.bin = self.root / 'bin' + self.bin.mkdir() + (self.bin / 'fakesudo').write_text('#!/bin/sh\nwhile [ "${1#--}" != "$1" ]; do shift; done\nexec "$@"\n') + (self.bin / 'fakesudo').chmod(0o755) + self.tmpdir = self.root / 'tmp' + self.tmpdir.mkdir() + # The installer's own identity, and a stand-in copy that reports it when sourced + # (as the root side checks it) and says how it was run otherwise. + ident = subprocess.run(['bash', '-c', f"AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' && m3max_kit_identity"], + capture_output=True, text=True, check=True).stdout + (self.root / 'identity').write_text(ident) + (self.root / 'other-identity').write_text('another release|') + self.copy = self.root / 'copy.sh' + self.copy.write_text(self.stand_in('identity')) + + def stand_in(self, ident): + return (f"#!/bin/bash\nm3max_kit_identity() {{ cat '{self.root}/{ident}'; }}\n" + "if [[ ${AURORA_SEP_SOURCE_ONLY:-} == 1 ]]; then return 0; fi\n" + 'echo "ran $0 $*"\necho "mode $(stat -c %a "$0")"\n') + + def setup(self, tamper='', before=''): + script = f""" +set -euo pipefail +{before} +AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' +export TMPDIR='{self.tmpdir}' +die() {{ echo "DIED: $*"; exit 9; }} +sudo=fakesudo +release_source() {{ :; }} +require_supported_soc() {{ :; }} +is_m3_max() {{ true; }} +m3max_kit_self() {{ + cp '{self.copy}' "$M3MAX_KIT_WORK/install-aurora-sep.sh" + M3MAX_KIT_SELF_SHA=$(sha256sum "$M3MAX_KIT_WORK/install-aurora-sep.sh" | cut -d' ' -f1) + echo "user-work=$M3MAX_KIT_WORK" + {tamper} +}} +m3max_kit_setup --yes +""" + env = {**os.environ, 'PATH': f'{self.bin}:{os.environ["PATH"]}'} + return subprocess.run(['bash', '-c', script], capture_output=True, text=True, env=env) + + def test_root_runs_its_own_copy(self): + r = self.setup() + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + user = re.search(r'^user-work=(.*)$', r.stdout, re.M).group(1) + m = re.search(r'^ran (\S+)/install-aurora-sep\.sh --m3max-kit --kit-work (\S+) --yes$', r.stdout, re.M) + self.assertIsNotNone(m, r.stdout) + self.assertEqual(m.group(1), m.group(2)) + self.assertNotEqual(m.group(1), user) + self.assertFalse(Path(user).exists()) + + def test_a_changed_copy_is_not_run(self): + r = self.setup(tamper='echo "echo evil" >>"$M3MAX_KIT_WORK/install-aurora-sep.sh"') + self.assertNotEqual(r.returncode, 0) + self.assertNotIn('ran ', r.stdout) + self.assertIn('could not take the kit script', r.stderr) + + def test_root_checks_the_identity_of_its_own_copy(self): + # The user-side checks saw a script that passed; the file root copies (its sha256 taken + # on that same content) is another script. Root's own identity check refuses it. + self.copy.write_text(self.stand_in('other-identity')) + r = self.setup() + self.assertNotEqual(r.returncode, 0) + self.assertNotIn('ran ', r.stdout) + self.assertIn('is not the script that runs now', r.stderr) + + def test_the_identity_check_of_roots_copy_runs_as_the_invoking_user(self): + # The check sources the script. With root's id differing from the invoking user's, it + # is run through runuser for that user, reading root's copy from its standard input. + log = self.root / 'runuser.log' + (self.bin / 'id').write_text('#!/bin/sh\nif [ "$*" = "-u" ]; then echo 0; else exec /usr/bin/id "$@"; fi\n') + (self.bin / 'runuser').write_text( + f'#!/bin/sh\necho "$*" >>"{log}"\nreadlink /proc/self/fd/0 >>"{log}"\nshift 3\nexec "$@"\n') + for name in ('id', 'runuser'): + (self.bin / name).chmod(0o755) + r = self.setup() + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + m = re.search(r'^ran (\S+)/install-aurora-sep\.sh ', r.stdout, re.M) + self.assertIsNotNone(m, r.stdout) + call, stdin = log.read_text().splitlines() + user = subprocess.run(['/usr/bin/id', '-un'], capture_output=True, text=True).stdout.strip() + self.assertTrue(call.startswith(f'-u {user} -- env AURORA_SEP_SOURCE_ONLY=1 bash -c source /dev/stdin '), call) + self.assertEqual(stdin, f'{m.group(1)}/install-aurora-sep.sh') + + def test_the_installer_reports_its_identity_from_standard_input(self): + with open(INSTALLER) as f: + r = subprocess.run(['bash', '-c', 'AURORA_SEP_SOURCE_ONLY=1 source /dev/stdin >/dev/null 2>&1 && m3max_kit_identity'], + stdin=f, capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(r.stdout, (self.root / 'identity').read_text()) + self.assertGreater(r.stdout.count('|'), 8) + + def test_roots_copy_is_readable_under_a_private_umask(self): + r = self.setup(before='umask 077') + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('\nmode 755\n', r.stdout) + + def test_a_link_is_not_followed(self): + r = self.setup(tamper=f'cp "$M3MAX_KIT_WORK/install-aurora-sep.sh" "{self.root}/real"; ' + f'ln -sf "{self.root}/real" "$M3MAX_KIT_WORK/install-aurora-sep.sh"') + self.assertNotEqual(r.returncode, 0) + self.assertNotIn('ran ', r.stdout) + + def test_root_refuses_a_work_directory_it_does_not_own(self): + d = Path(tempfile.mkdtemp(dir=self.tmpdir)) + os.chmod(d, 0o777) + script = f""" +AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' +die() {{ echo "DIED: $*"; exit 9; }} +M3MAX_KIT_WORK='{d}' +m3max_kit_work_is_root +echo ok +""" + r = subprocess.run(['bash', '-c', script], capture_output=True, text=True) + self.assertIn("is not root's own", r.stdout) + os.chmod(d, 0o700) + r = subprocess.run(['bash', '-c', script], capture_output=True, text=True) + self.assertIn('ok', r.stdout) + + +class RootConfiguration(unittest.TestCase): + """What root installs as update-m1n1's or m1n1's configuration is passed to it by the shell + that made it, and does not sit in a temporary file of the invoking user's on the way.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.bin = self.root / 'bin' + self.bin.mkdir() + self.log = self.root / 'log' + (self.bin / 'fakesudo').write_text(f'#!/bin/sh\necho "sudo $*" >>"{self.log}"\nexec "$@"\n') + # An install that finds its source changed since the shell wrote it: any file under the + # temporary directory that root is asked to install by name has other content by then. + (self.bin / 'install').write_text( + '#!/bin/bash\nfor a in "$@"; do\n' + f' if [[ -f $a && $a == "{self.root}/tmp/"* ]]; then echo CHANGED=1 >"$a"; fi\n' + 'done\nexec /usr/bin/install "$@"\n') + for f in self.bin.iterdir(): + f.chmod(0o755) + (self.root / 'tmp').mkdir() + self.etc = self.root / 'etc' + self.etc.mkdir() + self.state = self.root / 'state' + self.state.mkdir() + self.conf = self.etc / 'update-m1n1' + self.m1n1 = self.etc / 'm1n1.conf' + + def sh(self, body): + script = f""" +set -euo pipefail +AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' +export TMPDIR='{self.root}/tmp' +die() {{ echo "DIED: $*"; exit 9; }} +umask 077 +sudo=fakesudo +UPDATE_M1N1_CONF='{self.conf}' M1N1_CONF='{self.m1n1}' STATE='{self.state}' +{body} +""" + env = {**os.environ, 'PATH': f'{self.bin}:{os.environ["PATH"]}'} + r = subprocess.run(['bash', '-c', script], capture_output=True, text=True, env=env) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + # Nothing of the user's is left in the temporary directory, and none in /etc. + self.assertEqual(list((self.root / 'tmp').iterdir()), []) + self.assertEqual(sorted(p.name for p in self.etc.iterdir() if '.' in p.name and p.name != 'm1n1.conf'), []) + return r + + def mode(self, path): + return stat.S_IMODE(path.stat().st_mode) + + def test_no_user_temporary_file_is_installed_as_root(self): + text = INSTALLER.read_text() + self.assertEqual(re.findall(r'^[^#\n]*\$sudo install\b[^\n]*"\$tmp"[^\n]*', text, re.M), []) + for dest in ('"$UPDATE_M1N1_CONF"', '"$M1N1_CONF"', '"$conf"', '"$STATE/update-m1n1.default.saved"'): + self.assertIn(f'| root_put {dest}', text) + + def test_freeze_and_unfreeze(self): + self.conf.write_text('KEEP=1\n\n') + self.sh('m3_freeze; echo "by=$M3_FROZEN_BY"') + text = self.conf.read_text() + self.assertTrue(text.startswith('KEEP=1\n\n# >>> aurora-sep: keep this M3'), text) + self.assertTrue(text.endswith('\nM1N1_UPDATE_DISABLED=1\n# <<< aurora-sep: keep this M3\'s boot.bin as it is\n'), text) + self.assertNotIn('CHANGED', text) + self.assertEqual(self.mode(self.conf), 0o644) + self.sh('m3_unfreeze') + self.assertEqual(self.conf.read_text(), 'KEEP=1\n\n') + self.assertEqual(self.mode(self.conf), 0o644) + + def test_unfreeze_removes_a_file_that_held_only_the_freeze(self): + self.sh('m3_freeze') + self.assertIn('M1N1_UPDATE_DISABLED=1', self.conf.read_text()) + self.sh('m3_unfreeze') + self.assertFalse(self.conf.exists()) + + def test_switches_write_and_remove(self): + self.m1n1.write_text('other=1\n') + stubs = 'is_m3_air() { false; }; is_m3_max() { false; }; m3_switches() { echo chosen.a=1 chosen.b=0; }\n' + self.sh(stubs + 'm3_switches_write') + lines = self.m1n1.read_text().splitlines() + self.assertEqual(lines[0], 'other=1') + self.assertEqual(lines[2:4], ['chosen.a=1', 'chosen.b=0']) + self.assertEqual(len(lines), 5) + self.assertEqual(self.mode(self.m1n1), 0o644) + self.sh(stubs + 'm3_switches_remove') + self.assertEqual(self.m1n1.read_text(), 'other=1\n') + + def test_boot_state_snapshot_and_neo_block(self): + self.conf.write_text('M1N1=/x/m1n1.bin\n') + self.sh('m3_freeze; snapshot_boot_state || true') + self.assertEqual((self.state / 'update-m1n1.default.saved').read_text(), 'M1N1=/x/m1n1.bin\n') + self.assertEqual(self.mode(self.state / 'update-m1n1.default.saved'), 0o644) + self.sh('m3_unfreeze; neo_gpu_boot_config; neo_gpu_boot_config') + text = self.conf.read_text() + self.assertTrue(text.startswith('M1N1=/x/m1n1.bin\n# >>> aurora-sep: Neo stage2\n'), text) + self.assertEqual(text.count('# >>> aurora-sep: Neo stage2'), 1) + self.assertTrue(text.endswith('# <<< aurora-sep: Neo stage2\n'), text) + self.assertNotIn('CHANGED', text) + + def test_a_failed_write_keeps_the_old_file(self): + self.conf.write_text('KEEP=1\n') + (self.bin / 'mv').write_text('#!/bin/sh\nexit 1\n') + (self.bin / 'mv').chmod(0o755) + script = f""" +AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' +sudo='' +echo new | root_put '{self.conf}' && echo put-ok +""" + env = {**os.environ, 'PATH': f'{self.bin}:{os.environ["PATH"]}'} + r = subprocess.run(['bash', '-c', script], capture_output=True, text=True, env=env) + self.assertNotIn('put-ok', r.stdout) + self.assertEqual(self.conf.read_text(), 'KEEP=1\n') + self.assertEqual([p.name for p in self.etc.iterdir()], ['update-m1n1']) + + +class AdtReaderRootCopy(unittest.TestCase): + """The report's ADT reader: under sudo root runs its own copy, checked as root.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.bin = self.root / 'bin' + self.bin.mkdir() + (self.bin / 'fakesudo').write_text('#!/bin/sh\nexec "$@"\n') + (self.bin / 'fakesudo').chmod(0o755) + (self.root / 'tmp').mkdir() + self.work = self.root / 'work' + self.work.mkdir() + self.reader = self.work / 'aurora-adt-extract.py' + self.reader.write_bytes(b'print("reader")\n') + + def sh(self, body, sudo='fakesudo', pin=None): + pin = sha(b'print("reader")\n') if pin is None else pin + script = f""" +set -euo pipefail +AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' +export TMPDIR='{self.root}/tmp' +umask 077 +sudo={sudo!r} +M3_ADT_READER={('aurora-adt-extract.py ' + pin) if pin else ''!r} +M3_WORK='{self.work}' +{body} +""" + env = {**os.environ, 'PATH': f'{self.bin}:{os.environ["PATH"]}'} + return subprocess.run(['bash', '-c', script], capture_output=True, text=True, env=env) + + def test_root_runs_its_own_checked_copy(self): + r = self.sh(f""" +m3_adt_reader_root '{self.reader}' +echo "run=$M3_ADT_RUN" +echo CHANGED >'{self.reader}' +python3 -I "$M3_ADT_RUN" +stat -c 'mode %a' "$M3_ADT_RUN" +m3_adt_reader_root_done +echo "root=[$M3_ADT_ROOT]" +""") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + run = Path(re.search(r'^run=(.*)$', r.stdout, re.M).group(1)) + self.assertEqual(run.name, 'aurora-adt-extract.py') + self.assertNotEqual(run.parent, self.work) + self.assertIn('\nreader\nmode 644\nroot=[]\n', r.stdout) + self.assertFalse(run.parent.exists()) + + def test_a_copy_that_differs_from_the_pinned_reader_is_refused(self): + r = self.sh(f""" +echo 'print("other")' >'{self.reader}' +if m3_adt_reader_root '{self.reader}'; then echo accepted; else echo "why=$M3_ADT_WHY"; fi +m3_report_cleanup +""") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertNotIn('accepted', r.stdout) + self.assertIn('why=aurora-adt-extract.py changed after its checksum was checked, so the ADT was not read', r.stdout) + self.assertEqual(list((self.root / 'tmp').iterdir()), []) + + def test_without_sudo_the_reader_runs_where_it_is(self): + r = self.sh(f"m3_adt_reader_root '{self.reader}'; echo \"run=$M3_ADT_RUN root=[$M3_ADT_ROOT]\"", sudo='') + self.assertIn(f'run={self.reader} root=[]', r.stdout) + + def test_the_report_runs_only_roots_copy(self): + text = INSTALLER.read_text() + for name in ('m3_report_adt', 'm3_report_stage2_log'): + body = text.split(f'\n{name}() {{', 1)[1].split('\n}\n', 1)[0] + runs = re.findall(r'\$sudo python3 -I "\$(\w+)"', body) + self.assertGreaterEqual(len(runs), 2, name) + adt = text.split('\nm3_report_adt() {', 1)[1].split('\n}\n', 1)[0] + self.assertEqual(set(re.findall(r'\$sudo python3 -I "\$(\w+)"', adt)), {'M3_ADT_RUN'}) + self.assertIn('m3_report_stage2_log "$1" "$M3_ADT_RUN" "$log"', adt) + self.assertLess(adt.index('m3_adt_reader_root "$reader"'), adt.index('$sudo python3 -I')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/aurora-sep/tests/test_sep_selinux_state.py b/tools/aurora-sep/tests/test_sep_selinux_state.py index 764b760e5845d0..b41a4d5acbc13e 100644 --- a/tools/aurora-sep/tests/test_sep_selinux_state.py +++ b/tools/aurora-sep/tests/test_sep_selinux_state.py @@ -19,6 +19,8 @@ 'aurora-sep-host-state.bin', 'aurora-sep-xart-owned.bin', 'aurora-sep-xart-allow-once.bin', 'aurora-sep-xart-policy-previous.bin', ] +# Temporary names the kernel renames over the catacombs. +TEMPORARY = ['.%s.new' % name for name in STATE[:3]] class SelinuxModuleTests(unittest.TestCase): @@ -52,6 +54,21 @@ def test_the_kernel_creates_each_file_with_the_state_type(self): 'type_transition kernel_t var_lib_t:file aurora_sep_state_t "%s";' % name, self.te) + def test_replacement_temporaries_get_the_state_type(self): + # Rename keeps the temporary inode's label, so it must be created with + # the state type, not var_lib_t. + for name in TEMPORARY: + hits = [c for r, k, c in self.contexts() if r.match('/var/lib/' + name)] + self.assertEqual(len(hits), 1, name) + self.assertIn(':aurora_sep_state_t,', hits[0], name) + self.assertIn( + 'type_transition kernel_t var_lib_t:file aurora_sep_state_t "%s";' % name, + self.te) + # The kernel fixes the temporary's mode after a restrictive umask + # (setattr), renames it over the catacomb, and unlinks a leftover. + self.assertRegex(self.te, r'allow kernel_t aurora_sep_state_t:file \{[^}]*' + r'setattr_file_perms rename_file_perms delete_file_perms \};') + def test_no_access_to_generic_var_lib(self): self.assertNotRegex(self.te, r'allow\s+\S+\s+var_lib_t') diff --git a/tools/aurora-sep/tests/test_t8122_sep.py b/tools/aurora-sep/tests/test_t8122_sep.py index f1588a962091cc..986e2d8c357107 100644 --- a/tools/aurora-sep/tests/test_t8122_sep.py +++ b/tools/aurora-sep/tests/test_t8122_sep.py @@ -22,9 +22,12 @@ BUS = "/soc/spi@2a1108000" SENSOR = BUS + "/fingerprint@0" PINCTRL_NUB = "/soc/pinctrl@2e41f0000" +PINCTRL_AP = "/soc/pinctrl@2c7100000" MBOX = "/soc/mbox@29e408000" # AIC_IRQ cells: , IRQ_TYPE_LEVEL_HIGH = 4. LEVEL_HIGH = 4 +# GPIO interrupt cells: , IRQ_TYPE_EDGE_RISING = 1. +EDGE_RISING = 1 @unittest.skipUnless(all(shutil.which(tool) for tool in ("cpp", DTC, "fdtget")), @@ -82,8 +85,10 @@ def test_air_boards_describe_sep_and_sensor(self): properties = self.props(dtb, SENSOR) self.assertIn("spi-cpha", properties) self.assertNotIn("spi-cpol", properties) - self.assertNotIn("interrupts", properties) - self.assertNotIn("interrupts-extended", properties) + # Data-ready on AP GPIO 199, rising edge, as on J713 and J616s. + ap = int(self.prop(dtb, PINCTRL_AP, "phandle")[0], 16) + self.assertEqual(self.cells(dtb, SENSOR, "interrupt-parent"), [ap]) + self.assertEqual(self.cells(dtb, SENSOR, "interrupts"), [199, EDGE_RISING]) self.assertNotIn("cs-gpios", self.props(dtb, BUS)) def cells(self, dtb, node, name): diff --git a/tools/aurora-sep/tests/test_touchid_package.py b/tools/aurora-sep/tests/test_touchid_package.py new file mode 100644 index 00000000000000..c276cbd38e7035 --- /dev/null +++ b/tools/aurora-sep/tests/test_touchid_package.py @@ -0,0 +1,79 @@ +# SPDX-License-Identifier: GPL-2.0-only +"""The aurora-touchid package (Omarchy): fprintd gets /dev/sep-bio only, not the whole misc +device class, and starts after the node exists; the PKGBUILD's checksums match its files.""" +import configparser +import hashlib +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + +PKG = Path(__file__).resolve().parents[1] / 'aurora-touchid' + + +def unit(path): + cp = configparser.ConfigParser(strict=False, interpolation=None) + cp.optionxform = str + cp.read_string(path.read_text()) + return cp + + +def words(cp, section, key): + return [w for line in cp.get(section, key, fallback='').splitlines() for w in line.split()] + + +class TouchIdPackageTest(unittest.TestCase): + def test_fprintd_gets_only_the_touch_id_node(self): + text = (PKG / 'fprintd-aurora.conf').read_text() + rules = [l.split('=', 1)[1].strip() for l in text.splitlines() if l.startswith('DeviceAllow=')] + self.assertEqual(rules, ['/dev/sep-bio rw']) + self.assertNotIn('char-misc', ''.join(rules)) + # No wait inside fprintd's own start: the path rule is resolved before ExecStartPre= runs. + self.assertFalse(any(l.startswith('ExecStartPre') for l in text.splitlines())) + + def test_fprintd_starts_after_the_node_is_there(self): + dropin = unit(PKG / 'fprintd-aurora.conf') + self.assertIn('aurora-touchid-device.service', words(dropin, 'Unit', 'After')) + self.assertIn('aurora-touchid-device.service', words(dropin, 'Unit', 'Wants')) + self.assertIn('aurora-sep-ready.service', words(dropin, 'Unit', 'After')) + wait = unit(PKG / 'aurora-touchid-device.service') + self.assertIn('fprintd.service', words(wait, 'Unit', 'Before')) + self.assertIn('apple-sep.service', words(wait, 'Unit', 'After')) + self.assertEqual(wait.get('Service', 'Type'), 'oneshot') + self.assertIn('/dev/sep-bio', wait.get('Service', 'ExecStart')) + + def test_the_wait_ends(self): + cmd = unit(PKG / 'aurora-touchid-device.service').get('Service', 'ExecStart') + script = re.match(r"/bin/sh -c '(.*)'$", cmd).group(1).replace('/dev/sep-bio', '/nonexistent/sep-bio') + script = script.replace('-lt 150', '-lt 3') + self.assertEqual(subprocess.run(['sh', '-c', script], timeout=10).returncode, 0) + + def test_pkgbuild_installs_and_checks_every_source(self): + text = (PKG / 'PKGBUILD').read_text() + sources = re.findall(r"'([^']+)'", text.split('source=(', 1)[1].split(')', 1)[0]) + sums = re.findall(r"'([0-9a-f]{64})'", text.split('sha256sums=(', 1)[1].split(')', 1)[0]) + self.assertEqual(len(sources), len(sums)) + for name, digest in zip(sources, sums): + self.assertEqual(hashlib.sha256((PKG / name).read_bytes()).hexdigest(), digest, name) + self.assertIn('aurora-touchid-device.service', sources) + self.assertIn('"$pkgdir/usr/lib/systemd/system/aurora-touchid-device.service"', text) + + @unittest.skipUnless(shutil.which('systemd-analyze'), 'systemd-analyze is needed') + def test_units_verify(self): + with tempfile.TemporaryDirectory() as d: + d = Path(d) + (d / 'fprintd.service.d').mkdir() + (d / 'fprintd.service').write_text('[Unit]\nDescription=stub\n[Service]\nExecStart=/bin/true\n') + shutil.copy(PKG / 'fprintd-aurora.conf', d / 'fprintd.service.d/aurora.conf') + shutil.copy(PKG / 'aurora-touchid-device.service', d) + r = subprocess.run(['systemd-analyze', 'verify', '--man=no', + str(d / 'aurora-touchid-device.service'), str(d / 'fprintd.service')], + capture_output=True, text=True, env={'SYSTEMD_UNIT_PATH': f'{d}:', 'PATH': '/usr/bin:/bin'}) + self.assertNotIn('aurora-touchid-device', r.stderr) + self.assertNotIn('aurora.conf', r.stderr) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/aurora-wake/attended-bt-wake.sh b/tools/aurora-wake/attended-bt-wake.sh index f8afc8ac872699..2bcd7fcd857f8f 100755 --- a/tools/aurora-wake/attended-bt-wake.sh +++ b/tools/aurora-wake/attended-bt-wake.sh @@ -15,13 +15,17 @@ addr=${1:-} [[ $addr =~ ^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$ ]] || { echo "usage: $0 " >&2; exit 2; } here=$(dirname "$(readlink -f "$0")") -out=/var/tmp/bt-wake/attended-$(date +%H%M%S) -mkdir -p "$out" +# A fresh private directory, worked in with noclobber set, so that a planted +# or swapped path cannot redirect what root writes (as in bt-wake-cycle.sh). +out=$(mktemp -d /var/tmp/bt-wake-attended.XXXXXXXX) || + { echo "cannot create an output directory" >&2; exit 2; } +cd -- "$out" || exit 2 +set -C -bluetoothctl info "$addr" > "$out/device.txt" 2>&1 || +bluetoothctl info "$addr" > device.txt 2>&1 || { echo "$addr is not known to BlueZ" >&2; exit 2; } -grep -E "Name|Paired|WakeAllowed|Connected" "$out/device.txt" -grep -q "WakeAllowed: yes" "$out/device.txt" || +grep -E "Name|Paired|WakeAllowed|Connected" device.txt +grep -q "WakeAllowed: yes" device.txt || { echo "wake is not allowed: bluetoothctl wake $addr on" >&2; exit 2; } echo ">>> Press a key on the Bluetooth keyboard so that it connects (60 s)." diff --git a/tools/aurora-wake/bt-wake-cycle.sh b/tools/aurora-wake/bt-wake-cycle.sh index 2eb419b3458230..687cc7d7eb2a5f 100755 --- a/tools/aurora-wake/bt-wake-cycle.sh +++ b/tools/aurora-wake/bt-wake-cycle.sh @@ -8,15 +8,57 @@ # emulated keyboard on another machine) is expected to make a wake-enabled # Bluetooth HID device reconnect while the system sleeps. # -# Usage: bt-wake-cycle.sh -w on|off [-s backstop-secs] [-r rtc] [-a bdaddr] [-o outdir] +# Usage: bt-wake-cycle.sh -w on|off [-s backstop-secs] [-r rtc] [-a bdaddr] [-o new-dir] # -w on expect a Bluetooth wake well before the backstop # -w off expect no wake: the RTC ends the sleep # -a Bluetooth address that must be connected again after resume +# -o a new directory for the evidence (default: a fresh +# /var/tmp/bt-wake-cycle.* directory) # The file /suspending appears right before the system suspends. # Exit status: 0 PASS, 1 FAIL, 2 setup error. set -u +# --- private output directory +# The evidence goes to a directory this script creates for itself, mode 0700: +# a fresh one under $2 by default, or the absolute path $1 given with -o, which +# must not exist yet, below parents that only root, this user or the sticky bit +# let others change. The script then works inside it with noclobber set, so a +# planted or swapped path cannot redirect what it writes as root. +open_out() { # $1: -o path or empty, $2: base directory, $3: name prefix + local leaf parent p owner mode + if [ -z "$1" ]; then + out=$(mktemp -d "$2/$3.XXXXXXXX") || + { echo "cannot create an output directory in $2" >&2; return 1; } + else + [[ $1 == /* ]] || + { echo "the output directory must be an absolute path: $1" >&2; return 1; } + leaf=$(basename -- "$1") + case $leaf in . | .. | /) echo "not a new directory: $1" >&2; return 1 ;; esac + parent=$(readlink -e -- "$(dirname -- "$1")") || + { echo "the parent of $1 does not exist" >&2; return 1; } + p=$parent + while :; do + read -r owner mode < <(stat -c '%u %a' -- "$p") || return 1 + if { [ "$owner" != 0 ] && [ "$owner" != "$(id -u)" ]; } || + { ((8#$mode & 8#022)) && ! ((8#$mode & 8#1000)); }; then + echo "others can change $p; not writing below it" >&2 + return 1 + fi + [ "$p" = / ] && break + p=$(dirname -- "$p") + done + out=${parent%/}/$leaf + mkdir -m 700 -- "$out" 2> /dev/null || + { echo "the output directory must not exist yet: $1" >&2; return 1; } + fi + cd -- "$out" || return 1 + [ "$(stat -c '%u %a' .)" = "$(id -u) 700" ] || + { echo "$out is not a private directory" >&2; return 1; } + set -C +} +# --- end of private output directory + # The PMU RTC, which can wake the system: rtc0 on J700, rtc1 on others. pmu_rtc() { local name @@ -33,7 +75,7 @@ mode= secs=120 rtc=$(pmu_rtc) addr= -out=/var/tmp/bt-wake/cycle-$(date +%Y%m%d-%H%M%S) +out= bdf=0000:01:00.1 while getopts "w:s:r:a:o:" opt; do @@ -54,7 +96,7 @@ esac dev=/sys/bus/pci/devices/$bdf [ -f "$dev/power/wakeup" ] || { echo "$bdf has no power/wakeup" >&2; exit 2; } -mkdir -p "$out" +open_out "$out" /var/tmp bt-wake-cycle || exit 2 irq=$(awk -F: '/mt7932-bt/ { gsub(/ /, "", $1); print $1; exit }' /proc/interrupts) [ -n "$irq" ] || { echo "no mt7932-bt interrupt" >&2; exit 2; } # Recorded only: a PME would arrive on the root port's PME interrupt. @@ -67,12 +109,13 @@ bt_irqs() { } orig_wakeup=$(cat "$dev/power/wakeup") -restore() { echo "$orig_wakeup" > "$dev/power/wakeup"; } +# Kernel attributes are the only files written with >|, past noclobber. +restore() { echo "$orig_wakeup" >| "$dev/power/wakeup"; } trap restore EXIT -[ "$mode" = on ] && echo enabled > "$dev/power/wakeup" || echo disabled > "$dev/power/wakeup" +[ "$mode" = on ] && echo enabled >| "$dev/power/wakeup" || echo disabled >| "$dev/power/wakeup" -echo 'module mt7932_bt_pcie +p' > /sys/kernel/debug/dynamic_debug/control 2> /dev/null -echo 1 > /sys/power/pm_debug_messages +echo 'module mt7932_bt_pcie +p' >| /sys/kernel/debug/dynamic_debug/control 2> /dev/null +echo 1 >| /sys/power/pm_debug_messages { echo "mode=$mode secs=$secs rtc=$rtc addr=$addr irq=$irq" @@ -83,18 +126,19 @@ echo 1 > /sys/power/pm_debug_messages echo "bt_irqs=$(bt_irqs)" bluetoothctl show | grep -E "Powered|PowerState" [ -n "$addr" ] && bluetoothctl info "$addr" | grep -E "Name|Connected|WakeAllowed" -} > "$out/before.txt" 2>&1 +} > before.txt 2>&1 fail_before=$(cat /sys/power/suspend_stats/fail) dmesg -C # HCI trace of the whole cycle: what the host sent at suspend, what woke it. -btmon -w "$out/hci.btsnoop" > /dev/null 2>&1 & +# btmon creates the capture itself, in this private directory. +btmon -w hci.btsnoop > /dev/null 2>&1 & btmon_pid=$! sleep 1 sync -date +%s.%N > "$out/suspending" +date +%s.%N > suspending t0=$(date +%s.%N) -rtcwake -d "$rtc" -m freeze -s "$secs" > "$out/rtcwake.txt" 2>&1 +rtcwake -d "$rtc" -m freeze -s "$secs" > rtcwake.txt 2>&1 rc=$? t1=$(date +%s.%N) slept=$(awk -v a="$t0" -v b="$t1" 'BEGIN { printf "%.1f", b - a }') @@ -119,20 +163,20 @@ fi powered=$(bluetoothctl show | awk '/Powered:/ { print $2 }') kill "$btmon_pid" 2> /dev/null -dmesg > "$out/dmesg.txt" +dmesg > dmesg.txt { echo "rc=$rc slept=${slept}s pm_wakeup_irq=$wirq ($wsrc) bt_irq=$irq pme_irq=$pme" echo "bt_irqs_after=$irqs_after wakeup_count=$(cat "$dev/power/wakeup_count" 2>/dev/null)" echo "irq_wakeup_after=$(cat /sys/kernel/irq/"$irq"/wakeup 2>/dev/null)" echo "reconnect=$reconnect powered=$powered" - grep -E "mt7932|Bluetooth|hci0" "$out/dmesg.txt" | grep -vE "Timekeeping|s2idle" | tail -20 -} > "$out/after.txt" + grep -E "mt7932|Bluetooth|hci0" dmesg.txt | grep -vE "Timekeeping|s2idle" | tail -20 +} > after.txt reasons=() [ $rc = 0 ] || reasons+=("rtcwake exited $rc") [ "$(cat /sys/power/suspend_stats/fail)" = "$fail_before" ] || reasons+=("suspend_stats fail count rose") -grep -q "system sleep with wakeup armed" "$out/dmesg.txt" +grep -q "system sleep with wakeup armed" dmesg.txt armed=$? if [ "$mode" = on ]; then [ $armed = 0 ] || reasons+=("driver did not report wakeup armed") @@ -150,18 +194,21 @@ fi [ "$powered" = yes ] || reasons+=("controller not powered after resume") [ "$reconnect" != timeout ] || reasons+=("$addr did not reconnect within 30 s") bad='WARNING:|BUG:|Oops|Call trace:|terminal transport fault|failed to (suspend|resume)' -grep -E "$bad" "$out/dmesg.txt" > "$out/bad-lines.txt" -[ -s "$out/bad-lines.txt" ] && - reasons+=("kernel log errors: $(head -2 "$out/bad-lines.txt" | tr '\n' ' ')") +grep -E "$bad" dmesg.txt > bad-lines.txt +[ -s bad-lines.txt ] && + reasons+=("kernel log errors: $(head -2 bad-lines.txt | tr '\n' ' ')") -if [ ${#reasons[@]} = 0 ]; then - echo "VERDICT wake=$mode: PASS slept=${slept}s pm_wakeup_irq=$wirq ($wsrc)" \ - "reconnect=$reconnect" | tee "$out/verdict.txt" - status=0 -else - echo "VERDICT wake=$mode: FAIL slept=${slept}s pm_wakeup_irq=$wirq" | tee "$out/verdict.txt" - printf ' - %s\n' "${reasons[@]}" | tee -a "$out/verdict.txt" - status=1 -fi -echo "evidence: $out" | tee -a "$out/verdict.txt" +# The verdict file appears complete: bt-wake-emulated.sh waits for it. +{ + if [ ${#reasons[@]} = 0 ]; then + echo "VERDICT wake=$mode: PASS slept=${slept}s pm_wakeup_irq=$wirq ($wsrc)" \ + "reconnect=$reconnect" + else + echo "VERDICT wake=$mode: FAIL slept=${slept}s pm_wakeup_irq=$wirq" + printf ' - %s\n' "${reasons[@]}" + fi + echo "evidence: $out" +} > verdict.txt +cat verdict.txt +[ ${#reasons[@]} = 0 ] && status=0 || status=1 exit $status diff --git a/tools/aurora-wake/bt-wake-emulated.sh b/tools/aurora-wake/bt-wake-emulated.sh index 64689be5bd7155..8c5dac8ba3b2a7 100755 --- a/tools/aurora-wake/bt-wake-emulated.sh +++ b/tools/aurora-wake/bt-wake-emulated.sh @@ -38,7 +38,6 @@ read -r -a target_args <<< "${TARGET_SSH_ARGS:-}" tgt() { ssh "${ssh_opts[@]}" "${target_args[@]}" "$TARGET_SSH" "$@"; } box() { ssh "${ssh_opts[@]}" "$EMU_SSH" "$@"; } CTL=/run/hogkb/ctl -TGT_DIR=/var/tmp/bt-wake BACKSTOP=120 TRIGGER_AFTER=20 out=${OUT:-./bt-wake-run-$(date +%Y%m%d-%H%M%S)} @@ -81,9 +80,14 @@ pair) run) n=${2:-5} emu_start - tgt "mkdir -p $TGT_DIR" && - scp -q "${target_args[@]}" "$(dirname "$0")/bt-wake-cycle.sh" \ - "$TARGET_SSH:$TGT_DIR/" + # A fresh private directory on the target holds the copied script and + # every cycle's evidence, so nothing root runs or writes there can be + # planted or swapped by another user. + TGT_DIR=$(tgt "mktemp -d /var/tmp/bt-wake-run.XXXXXXXX") + [[ $TGT_DIR =~ ^/var/tmp/bt-wake-run\.[A-Za-z0-9]+$ ]] || + { echo "cannot create a directory on the target" >&2; exit 2; } + scp -q "${target_args[@]}" "$(dirname "$0")/bt-wake-cycle.sh" \ + "$TARGET_SSH:$TGT_DIR/" || exit 2 pass=0 plan=() for _ in $(seq 1 "$n"); do plan+=(on); done @@ -96,7 +100,7 @@ run) emu key 0x2c 30 sleep 8 say "cycle $k wake=$mode: suspending the target (backstop ${BACKSTOP}s)" - tgt "rm -rf $d; setsid nohup $TGT_DIR/bt-wake-cycle.sh -w $mode -s $BACKSTOP \ + tgt "setsid nohup $TGT_DIR/bt-wake-cycle.sh -w $mode -s $BACKSTOP \ -a $EMU_ADDR -o $d > $d.log 2>&1 < /dev/null &" for _ in $(seq 1 30); do tgt "test -f $d/suspending" 2> /dev/null && break diff --git a/tools/aurora-wake/bt-wake-power.sh b/tools/aurora-wake/bt-wake-power.sh index be6d1eb06c8f60..91e46188f5f649 100755 --- a/tools/aurora-wake/bt-wake-power.sh +++ b/tools/aurora-wake/bt-wake-power.sh @@ -7,8 +7,50 @@ # - Bluetooth MSIs and all interrupts taken across the sleep, # - how often the s2idle loop was re-entered (pm_debug "Timekeeping suspended"), # - the battery energy used, when running on battery (energy_now). -# Usage: bt-wake-power.sh [-s secs] [-n pairs] [-o outdir] +# Usage: bt-wake-power.sh [-s secs] [-n pairs] [-o new-dir] +# -o a new directory for the evidence (default: a fresh +# /var/tmp/bt-wake-power.* directory) set -u + +# --- private output directory +# The evidence goes to a directory this script creates for itself, mode 0700: +# a fresh one under $2 by default, or the absolute path $1 given with -o, which +# must not exist yet, below parents that only root, this user or the sticky bit +# let others change. The script then works inside it with noclobber set, so a +# planted or swapped path cannot redirect what it writes as root. +open_out() { # $1: -o path or empty, $2: base directory, $3: name prefix + local leaf parent p owner mode + if [ -z "$1" ]; then + out=$(mktemp -d "$2/$3.XXXXXXXX") || + { echo "cannot create an output directory in $2" >&2; return 1; } + else + [[ $1 == /* ]] || + { echo "the output directory must be an absolute path: $1" >&2; return 1; } + leaf=$(basename -- "$1") + case $leaf in . | .. | /) echo "not a new directory: $1" >&2; return 1 ;; esac + parent=$(readlink -e -- "$(dirname -- "$1")") || + { echo "the parent of $1 does not exist" >&2; return 1; } + p=$parent + while :; do + read -r owner mode < <(stat -c '%u %a' -- "$p") || return 1 + if { [ "$owner" != 0 ] && [ "$owner" != "$(id -u)" ]; } || + { ((8#$mode & 8#022)) && ! ((8#$mode & 8#1000)); }; then + echo "others can change $p; not writing below it" >&2 + return 1 + fi + [ "$p" = / ] && break + p=$(dirname -- "$p") + done + out=${parent%/}/$leaf + mkdir -m 700 -- "$out" 2> /dev/null || + { echo "the output directory must not exist yet: $1" >&2; return 1; } + fi + cd -- "$out" || return 1 + [ "$(stat -c '%u %a' .)" = "$(id -u) 700" ] || + { echo "$out is not a private directory" >&2; return 1; } + set -C +} +# --- end of private output directory # The PMU RTC, which can wake the system: rtc0 on J700, rtc1 on others. pmu_rtc() { local name @@ -22,7 +64,7 @@ pmu_rtc() { } secs=300 pairs=2 -out=/var/tmp/bt-wake/power-$(date +%Y%m%d-%H%M%S) +out= while getopts "s:n:o:" opt; do case $opt in s) secs=$OPTARG ;; n) pairs=$OPTARG ;; o) out=$OPTARG ;; *) exit 2 ;; esac done @@ -31,11 +73,12 @@ dev=/sys/bus/pci/devices/0000:01:00.1 bat=/sys/class/power_supply/macsmc-battery irq=$(awk -F: '/mt7932-bt/ { gsub(/ /, "", $1); print $1; exit }' /proc/interrupts) rtc=$(pmu_rtc) -mkdir -p "$out" +open_out "$out" /var/tmp bt-wake-power || exit 2 orig=$(cat "$dev/power/wakeup") -trap 'echo "$orig" > "$dev/power/wakeup"' EXIT -echo 1 > /sys/power/pm_debug_messages -echo 'module mt7932_bt_pcie +p' > /sys/kernel/debug/dynamic_debug/control 2> /dev/null +# Kernel attributes are the only files written with >|, past noclobber. +trap 'echo "$orig" >| "$dev/power/wakeup"' EXIT +echo 1 >| /sys/power/pm_debug_messages +echo 'module mt7932_bt_pcie +p' >| /sys/kernel/debug/dynamic_debug/control 2> /dev/null irq_sum() { # $1: irq number or "all" awk -v i="$1" '$1 ~ /^[0-9]+:$/ && (i == "all" || $1 == i ":") { @@ -43,11 +86,11 @@ irq_sum() { # $1: irq number or "all" } END { print s + 0 }' /proc/interrupts } -echo "mode secs slept bt_msis all_irqs s2idle_entries energy_mWh status armed" | - tee "$out/results.txt" +echo "mode secs slept bt_msis all_irqs s2idle_entries energy_mWh status armed" > results.txt +cat results.txt for p in $(seq 1 "$pairs"); do for mode in disabled enabled; do - echo "$mode" > "$dev/power/wakeup" + echo "$mode" >| "$dev/power/wakeup" dmesg -C b0=$(irq_sum "$irq") a0=$(irq_sum all) @@ -57,12 +100,12 @@ for p in $(seq 1 "$pairs"); do rtcwake -d "$rtc" -m freeze -s "$secs" > /dev/null 2>&1 t1=$(date +%s.%N) b1=$(irq_sum "$irq"); a1=$(irq_sum all); e1=$(cat "$bat/energy_now") - dmesg > "$out/dmesg-$p-$mode.txt" - entries=$(grep -c "Timekeeping suspended" "$out/dmesg-$p-$mode.txt") - armed=$(grep -c "system sleep with wakeup armed" "$out/dmesg-$p-$mode.txt") + dmesg > "dmesg-$p-$mode.txt" + entries=$(grep -c "Timekeeping suspended" "dmesg-$p-$mode.txt") + armed=$(grep -c "system sleep with wakeup armed" "dmesg-$p-$mode.txt") slept=$(awk -v a="$t0" -v b="$t1" 'BEGIN { printf "%.1f", b - a }') echo "$mode $secs $slept $((b1 - b0)) $((a1 - a0)) $entries" \ - "$(((e0 - e1) / 1000)) $st $armed" | tee -a "$out/results.txt" + "$(((e0 - e1) / 1000)) $st $armed" | tee -a results.txt sleep 20 done done diff --git a/tools/media/apple-scaler/msr23_filters.py b/tools/media/apple-scaler/msr23_filters.py new file mode 100755 index 00000000000000..f67b9e52810535 --- /dev/null +++ b/tools/media/apple-scaler/msr23_filters.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Generate the MSR23 scaler's polyphase filter table (apple-scaler-msr23.c). + +The engine filters each axis with 9 taps and picks one of 8 coefficient sets +("bins") by the step, src/dst in Q19: a step uses the first bin whose ratio is +at least the step. Each set is one symmetric kernel h(x), sampled at 9 source +pixels around the output position with 32 sub-pixel phases per pixel. + +Design + Downscaling bins (ratio s > 1, s = 8/7, 4/3, 8/5, 2, 8/3, 4): + h(x) = sinc(x / s) * kaiser(x; R = 3.5 s, beta = 6.5) + A low-pass at the output's Nyquist frequency (cutoff 1/s of the source + rate), Kaiser-windowed over three and a half lobes of the scaled sinc. + Upscaling bin (steps below 1): + h(x) = sinc(x) * kaiser(x; R = 31/16, beta = 5) + An interpolating 4-tap kernel: h(0) = 1, h(+-1) = 0, nothing at |x| >= 2. + The 1:1 bin passes the source through: the centre tap is 1.0 in every + phase, and its extra word is 1.0. + Window: kaiser(x; R, beta) = I0(beta * sqrt(1 - (x/R)^2)) / I0(beta) for + |x| < R, else 0. + +Sampling and quantisation + Phase f = p/32 (p = 0..16) places the output f source pixels right of tap 4, + so tap k sits at x = k - 4 - f. Each phase is normalised to unit gain and + rounded to Q12 (4096 = 1.0); the rounding residual goes to the largest tap, + so every phase sums to exactly 4096. + +Storage (16 words per tap, index tap * 16 + phase) + Phases 1..15 are stored as they are, in columns 1..15. The kernel is + symmetric, so phases 17..31 are the mirror images of 15..1 and are not + stored. Column 0 holds two phases: its taps 4..8 are f = 0 (taps 0..3 are + their mirror), and its taps 0..3 hold taps 1..4 of f = 1/2. The per-bin + extra word is tap 0 of f = 1/2 (taps 5..8 are the mirror of 1..4). + +Against the coefficient set captured from the engine's own jobs (pass it +with --compare), every word is within 5/4096 and every phase's absolute +difference sums to at most 14/4096: under 0.9 of an 8-bit code value per +axis, so a scaled 8-bit sample differs by at most 2. + +Usage: msr23_filters.py print the C initializer + msr23_filters.py --check F exit 1 unless source file F holds exactly this table + msr23_filters.py --compare F per-bin differences against the table in F +""" +import math +import re +import sys + +PHASES = 32 +TAPS = 9 +ONE = 4096 +# Bin upper bounds, src/dst in Q19 (the 1:1 bin is exactly 1 << 19). +BINS = [ + ("up", (1 << 19) - 1), + ("one", 1 << 19), + ("down", 8 * (1 << 19) // 7), + ("down", 4 * (1 << 19) // 3), + ("down", 8 * (1 << 19) // 5), + ("down", 2 << 19), + ("down", 8 * (1 << 19) // 3), + ("down", 4 << 19), +] + + +def i0(x): + """Modified Bessel function of the first kind, order 0 (power series).""" + s, t, k = 1.0, 1.0, 1 + while t > 1e-17 * s: + t *= (x / (2 * k)) ** 2 + s += t + k += 1 + return s + + +def sinc(x): + return 1.0 if x == 0 else math.sin(math.pi * x) / (math.pi * x) + + +def kaiser(x, r, beta): + if abs(x) >= r: + return 0.0 + return i0(beta * math.sqrt(1.0 - (x / r) ** 2)) / i0(beta) + + +def kernel(kind, ratio): + s = ratio / (1 << 19) + if kind == "up": + return lambda x: sinc(x) * kaiser(x, 31 / 16, 5.0) + return lambda x: sinc(x / s) * kaiser(x, 3.5 * s, 6.5) + + +def phase(h, f): + w = [h(k - 4 - f) for k in range(TAPS)] + total = sum(w) + q = [w[k] / total * ONE for k in range(TAPS)] + r = [int(math.floor(v + 0.5)) if v >= 0 else -int(math.floor(-v + 0.5)) for v in q] + big = max(range(TAPS), key=lambda k: q[k]) + r[big] += ONE - sum(r) + return r + + +def bin_words(kind, ratio): + if kind == "one": + taps = [ONE if k == 4 else 0 for k in range(TAPS) for _ in range(16)] + return ONE, taps + h = kernel(kind, ratio) + cols = {p: phase(h, p / PHASES) for p in range(17)} + taps = [0] * (TAPS * 16) + for k in range(TAPS): + for p in range(1, 16): + taps[k * 16 + p] = cols[p][k] + for k in range(4, TAPS): + taps[k * 16] = cols[0][k] + for k in range(4): + taps[k * 16] = cols[16][k + 1] + return cols[16][0], taps + + +def table(): + return [(ratio,) + bin_words(kind, ratio) for kind, ratio in BINS] + + +def emit(): + out = [] + for ratio, extra, taps in table(): + out.append(f"\t{{ .ratio = 0x{ratio:x}, .extra = {extra}, .taps = {{") + for i in range(0, len(taps), 12): + out.append("\t\t" + ", ".join(str(v) for v in taps[i:i + 12]) + ",") + out.append("\t} },") + return "\n".join(out) + + +def parse(path): + src = open(path).read() + bins = re.findall(r"\.ratio = (0x[0-9a-f]+), \.extra = (-?\d+), \.taps = \{(.*?)\}", src, re.S) + return [(int(r, 16), int(e), [int(v) for v in re.findall(r"-?\d+", t)]) for r, e, t in bins] + + +def main(): + if len(sys.argv) == 3 and sys.argv[1] in ("--check", "--compare"): + ref = parse(sys.argv[2]) + worst = 0 + for (r0, e0, t0), (r1, e1, t1) in zip(table(), ref): + d = max([abs(a - b) for a, b in zip(t0, t1)] + [abs(e0 - e1)]) + n = sum(a != b for a, b in zip(t0, t1)) + (e0 != e1) + print(f"bin 0x{r0:x}: ratio {'ok' if r0 == r1 else 'DIFF'}, {n} words differ, max {d}") + worst = max(worst, d) + if sys.argv[1] == "--check": + sys.exit(0 if worst == 0 else 1) + return + print(emit()) + + +if __name__ == "__main__": + main() diff --git a/tools/testing/m4-pmgr-policy/harness.c b/tools/testing/m4-pmgr-policy/harness.c index fc952be25d75dd..60be1f4625c652 100644 --- a/tools/testing/m4-pmgr-policy/harness.c +++ b/tools/testing/m4-pmgr-policy/harness.c @@ -73,6 +73,11 @@ static bool of_property_present(const struct device_node *n, const char *name) return find_property(n, name) != NULL; } +static bool of_machine_is_compatible(const char *machine) +{ + return !strcmp(machine, "apple,j713"); +} + static int of_property_read_string(const struct device_node *n, const char *name, const char **s) { @@ -412,7 +417,7 @@ static unsigned int validate_policy(const char *name, unsigned int staged) enabled += available(n); owned += of_property_present(n, "apple,firmware-owned"); } - CHECK(domains == 129); + CHECK(domains == 145); printf("%s: staged=%u enabled=%u/%u firmware_owned=%u mismatches=%u\n", name, staged, enabled, domains, owned, mismatches); return mismatches; @@ -431,7 +436,7 @@ static unsigned int run_case(const char *name, const char *live_path, struct of_changeset cs = { 0 }; unsigned int changed = 0; - CHECK(t8132_pmgr_policy(&cs, &changed) == 0); + CHECK(t8132_pmgr_policy(&cs, &changed, !native) == 0); CHECK(changed == cs.count); unsigned int staged = cs.count; @@ -465,7 +470,7 @@ static void run_errors(const char *legacy) struct of_changeset cs = { 0 }; unsigned int changed = 0; - CHECK(t8132_pmgr_policy(&cs, &changed) == 0); + CHECK(t8132_pmgr_policy(&cs, &changed, true) == 0); total = cs.count; discard(&cs); free_fixture(); @@ -475,7 +480,7 @@ static void run_errors(const char *legacy) cs.fail_at = fail; changed = 0; - CHECK(t8132_pmgr_policy(&cs, &changed) == -ENOMEM); + CHECK(t8132_pmgr_policy(&cs, &changed, true) == -ENOMEM); CHECK(cs.count == fail - 1 && changed == cs.count); CHECK(state_hash() == before); /* Abort staging: caller must not apply it. */ @@ -496,7 +501,7 @@ static void run_errors(const char *legacy) free(parent->full_name); parent->full_name = strdup("power-management@deadbeef"); - CHECK(t8132_pmgr_policy(&cs, &changed) == -EINVAL); + CHECK(t8132_pmgr_policy(&cs, &changed, true) == -EINVAL); CHECK(state_hash() == before); if (i == 0) CHECK(cs.count == 0); @@ -515,7 +520,7 @@ static void run_errors(const char *legacy) const char compat[] = "apple,t8132-pmgr-pwrstate"; set_property(unknown, "compatible", compat, sizeof(compat)); - CHECK(t8132_pmgr_policy(&cs, &changed) == 0); + CHECK(t8132_pmgr_policy(&cs, &changed, true) == 0); apply(&cs); CHECK(!available(unknown)); CHECK(available(by_path( diff --git a/tools/testing/m4-pmgr-policy/run.py b/tools/testing/m4-pmgr-policy/run.py index b86c1faa892872..d16b3280aa07ea 100755 --- a/tools/testing/m4-pmgr-policy/run.py +++ b/tools/testing/m4-pmgr-policy/run.py @@ -63,6 +63,7 @@ def run(args, output): production = path.read_text() policy = block(production, "t8132_pmgr_policy") helper = block(production, "t8132_fdt_node_offset") + applies = block(production, "t8132_policy_applies") bad_lookup = "int parent = t8132_fdt_node_offset(data, pmgr);" if policy.count(bad_lookup) != 1: raise RuntimeError("Production PMGR lookup changed; update the negative control") @@ -95,7 +96,9 @@ def run(args, output): "source": str(path), "source_sha256": hashlib.sha256(production.encode()).hexdigest(), "legacy_fixture": str(args.legacy_dtb) if args.legacy_dtb else "synthesized from native DTB", } - for mode, code in [("negative-control", negative), ("production", helper + "\n" + policy)]: + helpers = helper + "\n" + applies + "\n" + for mode, code in [("negative-control", helpers + negative), + ("production", helpers + policy)]: c = output / (mode + ".c") binary = output / mode c.write_text(template.replace("/* PRODUCTION_CODE */", code)) diff --git a/tools/testing/selftests/arm64/user4k/uffd-wp-init.c b/tools/testing/selftests/arm64/user4k/uffd-wp-init.c index 78f43f1c0b9b7c..2246f8425cff92 100644 --- a/tools/testing/selftests/arm64/user4k/uffd-wp-init.c +++ b/tools/testing/selftests/arm64/user4k/uffd-wp-init.c @@ -466,6 +466,8 @@ static void marker_window(size_t ps, size_t native) CHECK(physical(a + i, ps) == start + i); CHECK(((pagemap(a + i, ps) >> 57) & 1) == (i != ps)); } + /* The neighbours the write populated read zero; a read keeps their WP bit. */ + CHECK(!a[2 * ps] && !a[3 * ps]); /* An async WP fault on a populated neighbour only clears its own bit. */ a[0] = 0xa5; for (size_t i = 0; i < native; i += ps) { diff --git a/tools/testing/selftests/drivers/apple/aop-motion.py b/tools/testing/selftests/drivers/apple/aop-motion.py index a66d26b77810ab..bed5ae1f9d4db3 100755 --- a/tools/testing/selftests/drivers/apple/aop-motion.py +++ b/tools/testing/selftests/drivers/apple/aop-motion.py @@ -27,11 +27,17 @@ def const(source, name): def main(): root = Path(__file__).resolve().parents[5] motion = (root / "drivers/iio/common/aop_sensors/aop_motion.rs").read_text() - parts = [const(motion, "REPORT_LEN"), const(motion, "XYZ_OFFSET"), + parts = ["#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nstruct Error(i32);", + const(motion, "REPORT_LEN"), const(motion, "XYZ_OFFSET"), + const(motion, "DIRECT_IDLE_MS"), block(motion, "fn decode("), block(motion, "fn le_u32("), block(motion, "fn location0_packet("), const(motion, "STATUS_UNSUPPORTED"), - block(motion, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum CalStatus"), block(motion, "fn cal_status("), r''' + block(motion, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum CalStatus"), block(motion, "fn cal_status("), + block(motion, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum SyncAction"), + block(motion, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum IdleStep"), + block(motion, "struct Stream"), + block(motion, "impl Stream"), r''' fn report(prefix: u8, xyz: [i32; 3], suffix: u8) -> Vec { let mut r = vec![prefix; 6]; for v in xyz { @@ -110,6 +116,222 @@ def main(): many[2] = 255; assert_eq!(location0_packet(&many), Some(&a[..])); } +#[test] +fn calibrates_once_and_reuses_direct_stream() { + let mut s = Stream::::new(); + assert!(!s.want()); + assert_eq!(s.next_action(), SyncAction::None); + + // Probe leaves calibration recorded and reports idle. + s.calibrated = true; + + // First direct read (X) starts reports without re-sending calibration. + s.direct_until = Some(2_000); + assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); + s.active = true; + + // Subsequent Y/Z and polling reads reuse the running stream with no RPCs. + s.direct_until = Some(2_010); + assert_eq!(s.next_action(), SyncAction::None); + assert_eq!(s.check_idle(10), IdleStep::RearmMs(10)); + assert_eq!(s.check_idle(DIRECT_IDLE_MS + 500), IdleStep::RearmMs(DIRECT_IDLE_MS as u32)); + assert!(s.direct_until.is_some()); + + // Once reads go quiet, idle expiry stops the reports. + assert_eq!(s.check_idle(0), IdleStep::Expire); + assert!(s.direct_until.is_none()); + assert_eq!(s.next_action(), SyncAction::Stop); + s.active = false; + assert_eq!(s.next_action(), SyncAction::None); + assert_eq!(s.check_idle(-1), IdleStep::Ignore); +} +#[test] +fn buffer_handoff_and_pm_calibration_policy() { + let mut s = Stream::::new(); + // Uncalibrated buffer start calibrates first. + s.buffer_on = true; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: true }); + s.calibrated = true; + s.active = true; + + // Suspend parks without clearing calibration; resume restarts interval only. + s.parked = true; + assert_eq!(s.next_action(), SyncAction::Stop); + s.active = false; + s.parked = false; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); + s.active = true; + + // Hibernation clears calibration so the next start sends it once. + s.parked = true; + assert_eq!(s.next_action(), SyncAction::Stop); + s.active = false; + s.parked = false; + s.calibrated = false; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: true }); + s.calibrated = true; + s.active = true; + + // Disabling buffer stops immediately. + s.buffer_on = false; + assert_eq!(s.next_action(), SyncAction::Stop); + s.active = false; + + // Direct hold handed off cleanly to buffer; stale idle callback is ignored. + s.direct_until = Some(5_000); + assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); + s.active = true; + s.buffer_on = true; + assert_eq!(s.check_idle(0), IdleStep::Ignore); + assert!(s.direct_until.is_none()); + assert_eq!(s.next_action(), SyncAction::None); + s.buffer_on = false; + assert_eq!(s.next_action(), SyncAction::Stop); +} +/// Counts the starts a sequence of direct reads tries on a failing service. +struct Service { + fail: Option, + starts: u32, +} + +/// One direct read at `now` ms, as `State::read_now()` does it. +fn read(s: &mut Stream, svc: &mut Service, now: i64) -> Result<(), Error> { + if let Some((until, _)) = s.failed_until { + if let Some(e) = s.check_backoff(until - now) { + return Err(e); + } + } + if !s.buffer_on { + s.direct_until = Some(now + DIRECT_IDLE_MS); + } + if let SyncAction::Start { .. } = s.next_action() { + svc.starts += 1; + if let Some(e) = svc.fail { + s.direct_until = None; + s.failed_until = Some((now + DIRECT_IDLE_MS, e)); + return Err(e); + } + s.calibrated = true; + s.active = true; + } + Ok(()) +} +#[test] +fn failed_start_backs_off_direct_reads() { + const EIO: Error = Error(5); + const ETIMEDOUT: Error = Error(110); + let mut s = Stream::::new(); + let mut svc = Service { fail: Some(EIO), starts: 0 }; + + // A 25 Hz poller on a failing service tries one start per idle window + // and gets the error of that start in between. + let mut now = 0; + while now < 10_000 { + assert_eq!(read(&mut s, &mut svc, now), Err(EIO)); + assert!(!s.want()); + now += 40; + } + assert_eq!(svc.starts, (10_000 / DIRECT_IDLE_MS) as u32); + + // The cached error is the one of the latest try. + svc.fail = Some(ETIMEDOUT); + assert_eq!(read(&mut s, &mut svc, 10_000), Err(ETIMEDOUT)); + assert_eq!(read(&mut s, &mut svc, 10_000 + DIRECT_IDLE_MS - 1), Err(ETIMEDOUT)); + assert_eq!(svc.starts, 6); + + // The first read after the window tries again; success ends the backoff. + svc.fail = None; + assert_eq!(read(&mut s, &mut svc, 10_000 + DIRECT_IDLE_MS), Ok(())); + assert_eq!(svc.starts, 7); + assert!(s.failed_until.is_none()); + assert!(s.active); + assert_eq!(read(&mut s, &mut svc, 10_040 + DIRECT_IDLE_MS), Ok(())); + assert_eq!(svc.starts, 7); + + // The deadline itself is the first moment of the next try. + assert_eq!(s.check_backoff(-1), None); + s.failed_until = Some((500, EIO)); + assert_eq!(s.check_backoff(1), Some(EIO)); + assert!(s.failed_until.is_some()); + assert_eq!(s.check_backoff(0), None); + assert!(s.failed_until.is_none()); +} +#[test] +fn buffer_and_sleep_end_the_backoff() { + const EIO: Error = Error(5); + let mut s = Stream::::new(); + let mut svc = Service { fail: Some(EIO), starts: 0 }; + assert_eq!(read(&mut s, &mut svc, 0), Err(EIO)); + assert_eq!(read(&mut s, &mut svc, 40), Err(EIO)); + assert_eq!(svc.starts, 1); + + // Enabling a buffer is a new request: it tries a start of its own, and + // a read under the running buffer is served, as `set_buffer()` does it. + svc.fail = None; + s.buffer_on = true; + s.direct_until = None; + s.failed_until = None; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: true }); + s.calibrated = true; + s.active = true; + assert_eq!(read(&mut s, &mut svc, 80), Ok(())); + assert_eq!(svc.starts, 1); + s.buffer_on = false; + s.active = false; + + // Sleep drops a backoff, as `set_parked()` does it, so the first read + // after resume tries at once. + svc.fail = Some(EIO); + assert_eq!(read(&mut s, &mut svc, 1_000), Err(EIO)); + assert_eq!(svc.starts, 2); + s.parked = true; + s.failed_until = None; + s.parked = false; + s.failed_until = None; + svc.fail = None; + assert_eq!(read(&mut s, &mut svc, 1_040), Ok(())); + assert_eq!(svc.starts, 3); +} +#[test] +fn failed_stop_keeps_active_until_reset_cal() { + let mut s = Stream::::new(); + s.calibrated = true; + s.buffer_on = true; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); + s.active = true; + + // A failed pre-sleep stop leaves `active` true instead of pretending the + // reports stopped, so an s2idle wake with no user retries stopping them. + s.parked = true; + assert_eq!(s.next_action(), SyncAction::Stop); + // Simulate stop_reports() returning Err: `active` stays true. + assert!(s.active); + + // After firmware suspend / hibernation (`reset_cal == true`), both + // `calibrated` and `active` are cleared so a running buffer cleanly + // recalibrates and restarts even if the pre-sleep stop failed. + s.parked = false; + s.calibrated = false; + s.active = false; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: true }); + s.calibrated = true; + s.active = true; + + // Same for a direct read after a failed stop + `reset_cal`: next read + // recalibrates and starts cleanly. + s.buffer_on = false; + assert_eq!(s.next_action(), SyncAction::Stop); + // Simulate failed stop leaving `active` true. + assert!(s.active); + s.parked = true; + s.direct_until = None; + s.parked = false; + s.calibrated = false; + s.active = false; + assert_eq!(s.next_action(), SyncAction::None); + s.direct_until = Some(2_000); + assert_eq!(s.next_action(), SyncAction::Start { calibrate: true }); +} '''] with tempfile.TemporaryDirectory(prefix="aop-motion-") as tmp: source = Path(tmp) / "test.rs" diff --git a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py index 7eeb90baf4385d..0c0883ef8dcb53 100755 --- a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py +++ b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py @@ -43,16 +43,19 @@ def defines(source): return "".join(result) -def run(tmp, name, program, expect_failure=False): +def run(tmp, name, program, expect_failure=False, expect=None): path = tmp / (name + ".c") path.write_text(program) binary = tmp / name subprocess.run(["cc", "-std=gnu11", "-Wall", "-Werror", "-Wno-unused-function", str(path), "-o", str(binary)], check=True) - result = subprocess.run([str(binary)], capture_output=expect_failure) + result = subprocess.run([str(binary)], capture_output=expect_failure, text=True) if expect_failure: if result.returncode == 0: raise RuntimeError(f"negative control passed: {name}") + # A control must fail on the check it is for, not on another one. + if expect and expect not in result.stderr: + raise RuntimeError(f"negative control failed elsewhere: {name}: {result.stderr.strip()}") else: result.check_returncode() @@ -92,7 +95,8 @@ def main(): ''' declarations = r''' struct apple_tunable { unsigned id; }; -struct atcphy_hw { int gen; bool usb2_only, has_usb2phy_reg, park_pipe_unlocked; u32 usb2phy_sig_host; }; +struct atcphy_hw { int gen; bool usb2_only, has_usb2phy_reg, park_pipe_unlocked; u32 usb2phy_sig_host; + u32 cfg_offset, sync_reset; }; enum suspend_state { PM_SUSPEND_TO_IDLE = 1, PM_SUSPEND_MEM = 3 }; static enum suspend_state pm_suspend_target_state; static bool rpm_suspended; @@ -106,7 +110,7 @@ def main(): bool t8132_ss, t8132_common_owned, t8132_suspended, t8132_failed, host_active; bool ss_tunables, mode_dirty, pipe_pending, swap_lanes; bool cio_tunables, t8132_dp_alt, fixed_usb2, hibernated, pd_was_off, idle_rpm; - bool t8103_dummy_pending, t8103_usb3_workaround; + bool t8103_dummy_pending, t8103_usb3_workaround, fixed_usb3, cio_only; unsigned tunnel_users; struct { bool prepared, changed, restored; } cio_sleep; int mode, pipe_state, lock; @@ -122,6 +126,8 @@ def main(): struct device { struct apple_atcphy *atc; }; static struct apple_atcphy *dev_get_drvdata(struct device *d) { return d->atc; } static struct apple_atcphy *phy_get_drvdata(struct phy *p) { return p->atc; } +/* T8152 only: these rows run T8132, which never reaches it. */ +static void atcphy_lanes_down_t8152(struct apple_atcphy *a) { (void)a; assert(0); } static u32 core[0x24000/4], usb2[0x4000/4], pipe_regs[0x4000/4]; static unsigned tunes[16], tune_count, reset_releases, bist_phase, writes, core_reads; static unsigned stall_power, stall_bist, expected_tunes, stall_sleep; @@ -215,7 +221,7 @@ def main(): } ''' names = ["atcphy_mode_is_cio", "atcphy_usb2_sig_host", "atcphy_t8132_dp_on", - "atcphy_usb2_power_off", "atcphy_power_off", "atcphy_usb2_power_on", + "atcphy_cfg", "atcphy_usb2_power_off", "atcphy_power_off", "atcphy_usb2_power_on", "atcphy_t8132_cold", "atcphy_t8132_common_start", "atcphy_t8132_phy_stop", "atcphy_t8132_full_stop", "atcphy_configure_t8132", "atcphy_usb2_set_mode", "atcphy_t8132_bist_pulse", @@ -364,61 +370,272 @@ def main(): role_program = r''' #include #include +#include #include #include #include -#define lockdep_assert_held(x) ((void)0) #define dev_warn(...) ((void)0) #define dev_err(...) ((void)0) +#define dev_info(...) ((void)0) #define WARN_ON_ONCE(x) ((void)(x)) +#define READ_ONCE(x) (x) +#define WRITE_ONCE(x, v) ((x) = (v)) +#define EPROBE_DEFER 517 +#define scoped_guard(type, lock) #define USB_DR_MODE_HOST 1 #define USB_DR_MODE_PERIPHERAL 2 #define DWC3_GCTL_PRTCAP_HOST 1 #define DWC3_GCTL_PRTCAP_DEVICE 2 -enum phy_mode { PHY_MODE_USB_HOST, PHY_MODE_USB_DEVICE }; -struct device { const char *of_node; }; -struct dwc3 { int dr_mode, current_dr_role; bool dis_u3_susphy_quirk; }; -struct dwc3_apple { struct dwc3 dwc; struct device *dev; void *usb2_phy, *usb3_phy; int lock, state; - bool dt_dis_u3_susphy, host_only, sleep_ddr; }; -static int phy_error, host_calls, gadget_calls, stops, syscore; +#define container_of(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member))) +enum phy_mode { PHY_MODE_INVALID, PHY_MODE_USB_HOST, PHY_MODE_USB_DEVICE }; +/* The task running the code: the glue's, or another one probing xHCI. */ +struct task_struct { int id; }; +static struct task_struct glue_task, other_task, *current_task = &glue_task, *lock_owner; +#define current current_task +#define lockdep_assert_held(x) assert(lock_owner == current) +struct device { const char *of_node; bool registered, bound; }; +struct platform_device { struct device dev; }; +struct dwc3 { int dr_mode, current_dr_role; bool dis_u3_susphy_quirk; struct platform_device *xhci; }; +struct dwc3_apple { struct dwc3 dwc; struct device *dev; void *usb2_phy, *usb3_phy, *role_sw; int lock, state; + bool dt_dis_u3_susphy, host_only, sleep_ddr, fixed_hub, sleep_phy_wait, sleep_phy_pending; + struct task_struct *host_start_task; bool usb3_host_owed; int usb3_host_ret; }; +#define to_dwc3_apple(d) container_of((d), struct dwc3_apple, dwc) +static struct platform_device xhci_pdev; +/* The xHCI model: its probe's progress, and what the PIPE and the controller do meanwhile. */ +static bool driver_registered = true, async_probe, async_race, hcrst_done, running, pipe_live, pipe_reset; +static int phy_error, phy_calls, pre_host_phy_calls, probes, refused, host_calls, host_exits, gadget_calls; +static int stops, syscore, pipe_resets, slp_votes, late_error; +static bool susphy_on; +/* The SuperSpeed root hub leaves the USB3 PHY to the glue, see dwc3_host_init(). */ +static const bool skip_usb3_phy_init = true; static bool of_device_is_compatible(const char *node, const char *name) { return !strcmp(node,name); } -static int phy_set_mode(void *phy, int mode) { (void)phy; (void)mode; return phy_error; } +static int phy_set_mode(void *phy, int mode) { + (void)phy; + assert(susphy_on); + /* A host's PIPE moves only after xHCI's reset and before it runs, under the glue lock. */ + if (mode == PHY_MODE_USB_HOST && xhci_pdev.dev.registered) + assert(hcrst_done && !running && lock_owner == current); + phy_calls++; + pipe_live = !phy_error; + return phy_error; +} static void dwc3_apple_set_ptrcap(struct dwc3_apple *a, int cap) { (void)a; (void)cap; } -static void dwc3_enable_susphy(struct dwc3 *d, bool on) { (void)d; assert(on); } -static int dwc3_host_init(struct dwc3 *d) { (void)d; host_calls++; return 0; } +static void dwc3_enable_susphy(struct dwc3 *d, bool on) { susphy_on = on && !d->dis_u3_susphy_quirk; } static int dwc3_gadget_init(struct dwc3 *d) { (void)d; gadget_calls++; return 0; } static int phy_reset(void *phy) { (void)phy; return 0; } -static void dwc3_host_exit(struct dwc3 *d) { (void)d; assert(0); } -static void apple_sleep_usb_slp_ddr(bool on) { (void)on; assert(0); } -static void dwc3_apple_usb3_pipe_reset(struct dwc3_apple *a) { (void)a; assert(0); } -''' + enum(states, "dwc3_apple_state") + r''' +static void apple_sleep_usb_slp_ddr(bool on) { slp_votes += on ? 1 : -1; } +/* T6040 resets the PIPE it routed before xHCI starts, see dwc3_apple_usb3_mode_before_start(). */ +static void dwc3_apple_usb3_pipe_reset(struct dwc3_apple *a) { (void)a; pipe_resets++; pipe_reset = true; } +static bool dwc3_apple_sleep_board(void) { return true; } +static void dwc3_apple_check_hub_later(struct dwc3_apple *a) { (void)a; } +''' + enum(states, "dwc3_apple_state") + function(states, "dwc3_apple_usb3_mode_before_start") + r''' static int dwc3_apple_core_start(struct dwc3_apple *a, enum dwc3_apple_state s) { (void)a; (void)s; return 0; } static int dwc3_apple_core_stop(struct dwc3_apple *a) { (void)a; stops++; return 0; } static void dwc3_apple_syscore(struct dwc3_apple *a, bool on) { (void)a; assert(on); syscore++; } -''' + function(dwc, "dwc3_apple_set_role") + function(dwc, "dwc3_apple_init") + r''' +static int dwc3_apple_usb3_host_route(struct dwc3 *dwc); +static struct dwc3 *xhci_parent; +/* + * xhci_plat_probe(): usb_add_hcd() on the primary HCD runs xhci_reset() (HCRST), which must not + * meet a live PIPE, and dwc3_xhci_plat_start() enables SUSPHY. usb_add_hcd() on the shared HCD + * then sets up its PHYs unless told to skip them, and runs dwc3_xhci_plat_init_quirk() before + * xhci_run(). Any failure tears both HCDs down, and the probe fails. + */ +static int xhci_plat_probe(void) +{ + int ret = 0; + + probes++; + assert(!pipe_live || pipe_reset); + hcrst_done = true; + dwc3_enable_susphy(xhci_parent, true); + if (!skip_usb3_phy_init) { + ret = phy_set_mode(to_dwc3_apple(xhci_parent)->usb3_phy, PHY_MODE_USB_HOST); + if (ret) + goto fail; + } + ret = dwc3_apple_usb3_host_route(xhci_parent); + if (ret == -EBUSY) + refused++; + if (!ret) + ret = late_error; + if (ret) + goto fail; + running = true; + xhci_pdev.dev.bound = true; + return 0; +fail: + /* xhci_stop() resets the controller on the teardown, wherever the PIPE is. */ + hcrst_done = false; + return ret; +} +/* platform_device_add(): its probe's result does not reach the caller. */ +static int dwc3_host_init(struct dwc3 *d) +{ + struct dwc3_apple *a = to_dwc3_apple(d); + + pre_host_phy_calls = phy_calls; + host_calls++; + if (!of_device_is_compatible(a->dev->of_node, "apple,t6040-dwc3")) { + assert(!susphy_on); + assert(!phy_calls); + } + memset(&xhci_pdev, 0, sizeof(xhci_pdev)); + xhci_pdev.dev.registered = true; + xhci_parent = d; + d->xhci = &xhci_pdev; + hcrst_done = running = false; + if (driver_registered && !async_probe) + (void)xhci_plat_probe(); + return 0; +} +static bool device_is_bound(struct device *dev) { return dev->bound; } +/* device_attach(): an asynchronous probe may run first, in its own task, then this one binds. */ +static int device_attach(struct device *dev) +{ + if (dev->bound) + return 1; + if (!driver_registered) + return 0; + if (async_race) { + current_task = &other_task; + (void)xhci_plat_probe(); + current_task = &glue_task; + } + return xhci_plat_probe() ? 0 : 1; +} +static void dwc3_host_exit(struct dwc3 *d) +{ + assert(d->xhci == &xhci_pdev && xhci_pdev.dev.registered); + host_exits++; + xhci_pdev.dev.registered = xhci_pdev.dev.bound = false; + running = hcrst_done = pipe_live = false; + d->xhci = NULL; +} +''' + "".join(function(dwc, name) for name in ( + "dwc3_apple_route_usb3", "dwc3_apple_set_role", "dwc3_apple_usb3_host_route", + "dwc3_apple_host_start", "dwc3_apple_init", "dwc3_apple_start_after_sleep")) + r''' +static void reset(struct dwc3_apple *a, const char *node, int error) +{ + a->dev->of_node = node; + a->state = DWC3_APPLE_NO_CABLE; + a->dwc.dis_u3_susphy_quirk = false; + phy_error = error; + phy_calls = pre_host_phy_calls = probes = refused = host_exits = 0; + pipe_live = running = hcrst_done = pipe_reset = false; + driver_registered = true; + async_probe = async_race = false; + late_error = 0; +} +/* A host that started: xHCI bound and running, both root hubs up. */ +static void started(struct dwc3_apple *a) +{ + assert(a->state == DWC3_APPLE_HOST && xhci_pdev.dev.bound && running && !host_exits); + a->state = DWC3_APPLE_NO_CABLE; + xhci_pdev.dev.registered = xhci_pdev.dev.bound = false; +} +/* A host that did not: no xHCI left behind, the core stopped, no host state recorded. */ +static void stopped(struct dwc3_apple *a, int s) +{ + assert(stops == s && host_exits == 1 && !xhci_pdev.dev.registered && !running); + assert(a->state == DWC3_APPLE_NO_CABLE && a->dwc.xhci == NULL); +} int main(void) { struct device dev = { "apple,t8132-dwc3" }; - struct dwc3_apple a = { .dev=&dev, .usb3_phy=&dev, .state=DWC3_APPLE_NO_CABLE }; - phy_error=-ETIMEDOUT; + struct dwc3_apple a = { .dev=&dev, .usb3_phy=&dev, .role_sw=&dev, .state=DWC3_APPLE_NO_CABLE }; + int s = 0, cores = 0; + + lock_owner = &glue_task; + /* T8132: routed once, after HCRST, out of P3 before xHCI runs. */ + reset(&a, "apple,t8132-dwc3", 0); + assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && syscore==++cores); + assert(probes==1 && phy_calls==1 && !pre_host_phy_calls); + assert(a.dwc.dis_u3_susphy_quirk && !susphy_on); + started(&a); + /* T6050 keeps SUSPHY. */ + reset(&a, "apple,t6050-dwc3", 0); + assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && syscore==++cores && phy_calls==1); + assert(!a.dwc.dis_u3_susphy_quirk && susphy_on); + started(&a); + /* T6040 routes and resets its PIPE before xHCI, which then leaves it alone. */ + reset(&a, "apple,t6040-dwc3", 0); + assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && syscore==++cores); + assert(pre_host_phy_calls==1 && phy_calls==1 && pipe_resets==1); + started(&a); + /* Older Type-C ports: a USB3 failure leaves both root hubs up, USB2 only. */ + reset(&a, "apple,t8103-dwc3", -ETIMEDOUT); + assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && syscore==++cores && stops==s); + assert(probes==1 && phy_calls==1 && !pipe_live && !a.dwc.dis_u3_susphy_quirk); + started(&a); + /* T8132: a BIST timeout fails xHCI before it runs and reaches dwc3_apple_init(). */ + reset(&a, "apple,t8132-dwc3", -ETIMEDOUT); assert(dwc3_apple_init(&a,DWC3_APPLE_HOST)==-ETIMEDOUT); - assert(!host_calls && !gadget_calls && stops==1 && a.state==DWC3_APPLE_NO_CABLE); - phy_error=-EOPNOTSUPP; + stopped(&a, ++s); + assert(probes==1 && phy_calls==1 && !pre_host_phy_calls && syscore==cores && !slp_votes); + /* T6050: a PIPE fault the same way. */ + reset(&a, "apple,t6050-dwc3", -EIO); a.sleep_ddr=true; + assert(dwc3_apple_init(&a,DWC3_APPLE_HOST)==-EIO); + stopped(&a, ++s); + assert(probes==1 && phy_calls==1 && syscore==cores && !slp_votes); + /* T6050 after a sleep: a PHY not started yet leaves the start to the role switch. */ + reset(&a, "apple,t6050-dwc3", -ENOLINK); + assert(!dwc3_apple_start_after_sleep(&a,DWC3_APPLE_HOST)); + stopped(&a, ++s); + assert(a.sleep_phy_pending && !a.sleep_phy_wait && syscore==cores && !slp_votes); + a.sleep_phy_pending=false; a.sleep_ddr=false; + /* An asynchronous probe from another task is refused; the glue's own one routes. */ + reset(&a, "apple,t6050-dwc3", 0); async_probe=async_race=true; + assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && syscore==++cores); + assert(probes==2 && refused==1 && phy_calls==1); + started(&a); + /* No xHCI driver yet: nothing routes the PIPE, and the probe is deferred. */ + reset(&a, "apple,t6050-dwc3", 0); driver_registered=false; + assert(dwc3_apple_init(&a,DWC3_APPLE_HOST)==-EPROBE_DEFER); + stopped(&a, ++s); + assert(!probes && !phy_calls); + /* xHCI failing after the PIPE moved is not probed again on the live PIPE. */ + reset(&a, "apple,t6050-dwc3", 0); late_error=-ENOMEM; + assert(dwc3_apple_init(&a,DWC3_APPLE_HOST)==-ENODEV); + stopped(&a, ++s); + assert(probes==1 && phy_calls==1); + /* A probe outside a host start, such as a rebind, is refused and routes nothing. */ + reset(&a, "apple,t6050-dwc3", 0); xhci_pdev.dev.registered=true; xhci_parent=&a.dwc; + current_task=&other_task; hcrst_done=false; + assert(xhci_plat_probe()==-EBUSY && !phy_calls && refused==1); + current_task=&glue_task; xhci_pdev.dev.registered=false; + /* Device mode routes before the gadget: T8132 refuses a failure, older ports warn. */ + reset(&a, "apple,t8132-dwc3", -EOPNOTSUPP); assert(dwc3_apple_init(&a,DWC3_APPLE_DEVICE)==-EOPNOTSUPP); - assert(!gadget_calls && stops==2); - phy_error=0; - assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST)); - assert(host_calls==1 && a.state==DWC3_APPLE_HOST && syscore==1); - /* A T8132 host keeps its USB3 PHY out of P3. */ - assert(a.dwc.dis_u3_susphy_quirk); - dev.of_node="apple,t8103-dwc3"; phy_error=-ETIMEDOUT; - assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && host_calls==2 && syscore==2); + assert(!gadget_calls && stops==++s && phy_calls==1); + reset(&a, "apple,t8103-dwc3", -ETIMEDOUT); + assert(!dwc3_apple_init(&a,DWC3_APPLE_DEVICE) && gadget_calls==1 && syscore==++cores); assert(!a.dwc.dis_u3_susphy_quirk); - puts("ok 7 - T8132 PHY failures stop before xHCI, older fallback preserved"); + puts("ok 7 - USB3 host routed between HCRST and xHCI start, errors reach dwc3_apple_init, USB2-only fallback"); return 0; } ''' run(Path(directory), "dwc3-t8132", role_program) + controls = { + # The PIPE routed before dwc3_host_init() would meet xhci_reset(). + "dwc3-usb3-before-host": ("*mode = pipe_reset_before_host ? PHY_MODE_USB_HOST : PHY_MODE_INVALID;", + "*mode = PHY_MODE_USB_HOST;", "dwc3_host_init: Assertion"), + # The SuperSpeed root hub routing the PHY too, as its failure tears USB2 down. + "dwc3-usb3-root-hub": ("static const bool skip_usb3_phy_init = true;", + "static const bool skip_usb3_phy_init = false;", "phy_calls==1"), + # A routing failure that no longer reaches dwc3_apple_init(). + "dwc3-usb3-error-lost": ("\tret = appledwc->usb3_host_ret;\n", "\tret = 0;\n", "==-ETIMEDOUT"), + # A probe repeated after the PIPE moved, whose xhci_reset() then meets the live PIPE. + "dwc3-usb3-reprobe-live": ("if (!bound && appledwc->usb3_host_ret == -EINPROGRESS)", + "if (!bound && (appledwc->usb3_host_ret == -EINPROGRESS || !appledwc->usb3_host_ret))", + "xhci_plat_probe: Assertion `!pipe_live"), + # An asynchronous probe that routes without the glue lock. + "dwc3-usb3-foreign-task": ("if (READ_ONCE(appledwc->host_start_task) != current)", + "if (!READ_ONCE(appledwc->host_start_task))", "lock_owner == current"), + } + for name, (old, new, expect) in controls.items(): + control = role_program.replace(old, new, 1) + assert control != role_program, name + run(Path(directory), name + "-negative-control", control, expect_failure=True, expect=expect) permissive = program.replace( "(!atcphy->host_active || pm_suspend_target_state != PM_SUSPEND_TO_IDLE)", "false", 1) assert permissive != program @@ -734,6 +951,7 @@ def main(): static void mutex_init(int *p) { *p=0; } static bool dwc3_apple_has_fixed_hub(struct device *d,unsigned *port) { (void)d;(void)port;return false; } static bool dwc3_apple_host_only(struct device *d) { (void)d;return false; } +static bool dwc3_apple_idle_rpm(const char *np) { (void)np;return false; } static bool device_property_read_bool(struct device *d,const char *name) { (void)d;(void)name;return false; } static void spin_lock_init(int *p) { *p=0; } static void publish_owner(struct platform_device *pdev,struct dwc3_apple *appledwc) diff --git a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py index 3d1026008cbd9f..e9ab0f3826b9da 100755 --- a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py +++ b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py @@ -36,13 +36,22 @@ def main(): typedef uint16_t u16; typedef uint8_t u8; typedef uint32_t u32; -typedef uint64_t u64; +typedef unsigned long long u64; typedef u64 phys_addr_t; typedef unsigned long atomic_long_t; #define BIT(n) (1UL << (n)) +#define BIT_ULL(n) (1ULL << (n)) +#define SZ_16K 16384 +#define GFP_KERNEL 0 +#define IOMMU_READ 1 +#define IOMMU_WRITE 2 +#define IOMMU_MMIO 4 +#define APPLE_DART2 1 +#define DART_T8110_DISABLE_STREAMS 0xc20 #define WRITE_ONCE(x,v) ((x) = (v)) #define READ_ONCE(x) (x) -#define dev_err(...) ((void)0) +#define dev_err(dev,...) do { (void)(dev); if (false) fprintf(stderr,__VA_ARGS__); } while (0) +#define dev_warn(dev,...) do { (void)(dev); if (false) fprintf(stderr,__VA_ARGS__); } while (0) #define dev_err_probe(dev, error, ...) (error) #define dev_err_ratelimited(...) ((void)0) #define dev_dbg(dev,...) do { (void)(dev); if (false) fprintf(stderr,__VA_ARGS__); } while (0) @@ -97,6 +106,7 @@ def main(): u32 tcr_enabled, tcr_4level, ttbr_shift, ttbr_addr_field_shift; void (*enable_remap)(struct apple_dart *, int, int); int (*invalidate_tlb)(struct apple_dart_stream_map *); + bool gen3; }; struct apple_dart { const struct apple_dart_hw *hw; @@ -105,31 +115,59 @@ def main(): bool four_level, per_stream, tunneled, fw_mirror, fw_handoff; bool pending, preserve_display; bool isp_host, cold_ane, live_mtp, display_dark, display_tlb_stale; + unsigned int display_writers, display_dark_writers; + bool cold_gen3, cold_gen3_pcie; + u32 cold_gen3_sids; void *tunables; unsigned long static_bypass[4]; void *dcp, *frontend[2]; struct { bool ready; } iommu; void *dev; - unsigned pgsize; + unsigned pgsize, oas; int num_streams; + u64 sid16_page; + struct io_pgtable_ops *sid16_ops; + u32 sid16_ttbr; + u32 sid16_init_tcr; + u32 sid16_init_ttbr; + bool sid16_init_enabled; u32 regs[0x5000/4]; }; struct apple_dart_stream_map { struct apple_dart *dart; unsigned long sidmap[4]; }; struct apple_dart_atomic_stream_map { struct apple_dart *dart; atomic_long_t sidmap[4]; }; static u32 apple_dart_readl(struct apple_dart *d, unsigned o) { return d->regs[o/4]; } -static unsigned enable_writes, all_writes, guard_calls, device_pins, noidle_puts; -static bool drop_bypass_write; +static unsigned enable_writes, disable_writes, all_writes, guard_calls, device_pins, noidle_puts; +static bool drop_bypass_write, drop_enable_write, drop_disable_write, drop_ttbr_write; +static bool tcr_clear_dapf, sid16_saw_translate; +static unsigned sid16_tcr_writes; +static u32 last_sid16_tcr_write; static int guard_result, apple_dart_radio_kexec; static int kexec_block(void *guard) { assert(guard==&apple_dart_radio_kexec); guard_calls++; return guard_result; } static void get_device(void *dev) { assert(dev); device_pins++; } -static u32 last_enable; +static u32 last_enable, last_disable; static void apple_dart_writel(struct apple_dart *d, u32 v, unsigned o) { all_writes++; + if (o == DART_TCR(d, 16)) { + sid16_tcr_writes++; + last_sid16_tcr_write = v; + if (v & DART_T8110_TCR_TRANSLATE_ENABLE) + sid16_saw_translate = true; + } if (drop_bypass_write && o==DART_TCR(d,16)) return; + if (drop_ttbr_write && o==DART_TTBR(d,16,0)) return; if (o >= d->hw->enable_streams && o < d->hw->enable_streams + 32) { - d->regs[o/4] |= v; enable_writes++; last_enable=v; + enable_writes++; last_enable=v; + if (!drop_enable_write) + d->regs[o/4] |= v; + } else if (o >= DART_T8110_DISABLE_STREAMS && o < DART_T8110_DISABLE_STREAMS + 32) { + unsigned en = d->hw->enable_streams + (o - DART_T8110_DISABLE_STREAMS); + disable_writes++; last_disable=v; + if (!drop_disable_write) + d->regs[en/4] &= ~v; + } else if (tcr_clear_dapf && o >= 0x1000 && o < 0x1000 + 4 * DART_MAX_STREAMS) { + d->regs[o/4] = v & ~DART_T8110_TCR_BYPASS_DAPF; } else d->regs[o/4]=v; } static void writel(u32 v, void *p) { (void)v; (void)p; abort(); } @@ -137,11 +175,71 @@ def main(): { int sid; for_each_set_bit(sid,p,max) return sid; return max; } static u64 virt_to_phys(void *p) { return (uintptr_t)p; } static int tlb_result; +static unsigned tlb_flushes; +static unsigned long last_tlb_sidmap; static int test_invalidate_tlb(struct apple_dart_stream_map *m) -{ assert(m->sidmap[0] && !(m->sidmap[0] & ~m->dart->managed_sids)); return tlb_result; } +{ + assert(m->sidmap[0] && !(m->sidmap[0] & ~(m->dart->managed_sids | BIT(16)))); + tlb_flushes++; + last_tlb_sidmap = m->sidmap[0]; + return tlb_result; +} struct io_pgtable_cfg { + unsigned pgsize_bitmap, ias, oas; + int coherent_walk; + void *iommu_dev; struct { int n_ttbrs, n_levels; void *ttbr[1]; } apple_dart_cfg; }; +struct io_pgtable_ops { + int (*map_pages)(struct io_pgtable_ops *ops, unsigned long iova, + phys_addr_t paddr, size_t pgsize, size_t pgcount, + int prot, int gfp, size_t *mapped); + phys_addr_t (*iova_to_phys)(struct io_pgtable_ops *ops, unsigned long iova); + u64 mapped_iova; + phys_addr_t mapped_phys; + size_t mapped_size; +}; +static u64 sid16_root_page[1]; +static unsigned sid16_allocs, sid16_frees; +static int test_sid16_map_pages(struct io_pgtable_ops *ops, unsigned long iova, + phys_addr_t paddr, size_t pgsize, size_t pgcount, + int prot, int gfp, size_t *mapped) +{ + (void)gfp; + assert(pgsize == SZ_16K && pgcount == 1); + assert(prot == (IOMMU_READ | IOMMU_WRITE | IOMMU_MMIO)); + ops->mapped_iova = iova; + ops->mapped_phys = paddr; + ops->mapped_size = pgsize * pgcount; + *mapped = ops->mapped_size; + return 0; +} +static phys_addr_t test_sid16_iova_to_phys(struct io_pgtable_ops *ops, unsigned long iova) +{ + return iova == ops->mapped_iova ? ops->mapped_phys : 0; +} +static struct io_pgtable_ops *alloc_io_pgtable_ops(int fmt, struct io_pgtable_cfg *cfg, void *cookie) +{ + (void)cookie; + assert(fmt == APPLE_DART2 && cfg->pgsize_bitmap == SZ_16K && cfg->ias == 36); + struct io_pgtable_ops *ops = calloc(1, sizeof(*ops)); + assert(ops); + ops->map_pages = test_sid16_map_pages; + ops->iova_to_phys = test_sid16_iova_to_phys; + cfg->apple_dart_cfg.n_ttbrs = 1; + cfg->apple_dart_cfg.n_levels = 3; + cfg->apple_dart_cfg.ttbr[0] = (void *)0x4000; + (void)sid16_root_page; + sid16_allocs++; + return ops; +} +static void free_io_pgtable_ops(struct io_pgtable_ops *ops) +{ + if (!ops) + return; + sid16_frees++; + free(ops); +} struct io_pgtable { struct io_pgtable_cfg cfg; }; #define io_pgtable_ops_to_pgtable(p) (p) struct iommu_domain { int unused; }; @@ -299,6 +397,9 @@ def main(): 'apple_dart_hw_enable_bypass(', 'static void apple_dart_hw_disable_dma(', 'static bool apple_dart_managed_static_bypass(', + 'static bool apple_dart_managed_sid16_narrowed(', + 'static int apple_dart_managed_narrow_sid16(', + 'static void apple_dart_managed_unnarrow_sid16(', 'static int apple_dart_managed_admit(', 'int apple_dart_radio_check_idle(', 'static void apple_dart_managed_quarantine_locked(', @@ -359,6 +460,219 @@ def main(): assert(noidle_puts==1 && !pm_refs); drop_bypass_write=false; guard_result=0; + + /* + * SID16 narrowing + error-path teardown preserves inherited TCR, TTBR, and + * ENABLE[16] state (with write-one-to-clear DISABLE_STREAMS and T8132 + * non-retained DAPF request modeling) and allows clean rebind without -EBUSY. + */ + const struct { + u32 init_tcr, init_ttbr; + bool init_enabled, clear_dapf; + } sid16_cases[] = { + { 0, 0, false, true }, + { 0, 0x123400, false, true }, + { 0, 0x123400, true, true }, + { 2, 0, false, true }, + { 2, 0x5678001, false, true }, + { 2, 0xabcd001, true, true }, + { 6, 0, false, false }, + { 6, 0xabcd001, false, false }, + { 6, 0xabcd001, true, false }, + }; + for (unsigned i=0; ienable_streams/4]=BIT(18)|(sid16_cases[i].init_enabled?BIT(16):0); + tlb_result=0; tlb_flushes=0; last_tlb_sidmap=0; + sid16_allocs=sid16_frees=disable_writes=0; pm_refs=1; guard_result=0; + assert(!test_probe_start(&narrow)); + assert(narrow.sid16_ops && narrow.regs[DART_TCR(&narrow,16)/4]==1); + assert(narrow.regs[DART_TTBR(&narrow,16,0)/4]==narrow.sid16_ttbr); + assert(narrow.regs[hw->enable_streams/4]==(BIT(1)|BIT(2)|BIT(16)|BIT(18))); + assert(tlb_flushes==1 && last_tlb_sidmap==BIT(16)); + assert(sid16_allocs==1 && !sid16_frees); + bool ib=false; + assert(!apple_dart_managed_admit(&narrow,&ib)); + narrow.regs[hw->enable_streams/4]&=~BIT(16); + assert(apple_dart_managed_admit(&narrow,&ib)==-EBUSY); + narrow.regs[hw->enable_streams/4]|=BIT(16); + + /* Simulated post-narrowing probe failure tears down and frees table. */ + tlb_flushes=0; last_tlb_sidmap=0; disable_writes=0; last_disable=0; + last_sid16_tcr_write=0; + apple_dart_managed_quarantine(&narrow); + apple_dart_managed_unnarrow_sid16(&narrow); + assert(!narrow.sid16_ops && !narrow.sid16_ttbr && sid16_frees==1); + assert(last_sid16_tcr_write== + (sid16_cases[i].init_tcr?hw->tcr_bypass:hw->tcr_disabled)); + assert(narrow.regs[DART_TCR(&narrow,16)/4]==sid16_cases[i].init_tcr); + assert(narrow.regs[DART_TTBR(&narrow,16,0)/4]==sid16_cases[i].init_ttbr); + assert(narrow.regs[hw->enable_streams/4]== + (BIT(1)|BIT(2)|BIT(18)|(sid16_cases[i].init_enabled?BIT(16):0))); + assert(disable_writes==(sid16_cases[i].init_enabled?0u:1u)); + if (!sid16_cases[i].init_enabled) + assert(last_disable==BIT(16)); + assert(tlb_flushes==1 && last_tlb_sidmap==BIT(16)); + + /* A fresh rebind sees the restored state and admits cleanly. */ + struct apple_dart rebind={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + memcpy(rebind.regs,narrow.regs,sizeof(rebind.regs)); + pm_refs=1; + assert(!test_probe_start(&rebind)); + assert(rebind.sid16_ops && rebind.regs[DART_TCR(&rebind,16)/4]==1); + free_io_pgtable_ops(rebind.sid16_ops); + pm_refs=0; + } + + /* Entry states that cannot be restored are rejected before narrowing. */ + tcr_clear_dapf=true; + struct apple_dart bad_entry={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=false,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + bad_entry.regs[DART_TCR(&bad_entry,16)/4]=2; + sid16_allocs=0; all_writes=0; + assert(apple_dart_managed_narrow_sid16(&bad_entry)==-EBUSY); + assert(!bad_entry.sid16_ops && !sid16_allocs && !all_writes); + bad_entry.supports_bypass=true; + bad_entry.regs[DART_TCR(&bad_entry,16)/4]=0; + bad_entry.regs[DART_TTBR(&bad_entry,16,0)/4]=hw->ttbr_valid|0x1000; + pm_refs=1; + assert(test_probe_start(&bad_entry)==-EBUSY && !pm_refs); + assert(apple_dart_managed_narrow_sid16(&bad_entry)==-EBUSY); + assert(!bad_entry.sid16_ops && !sid16_allocs && !all_writes); + bad_entry.regs[DART_TTBR(&bad_entry,16,0)/4]=0; + const u32 bad_tcrs[]={1,4,8,0x80}; + for (unsigned i=0; ienable_streams/4]=BIT(16); + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; noidle_puts=0; + sid16_saw_translate=false; sid16_tcr_writes=0; last_sid16_tcr_write=0; + drop_ttbr_write=true; + assert(test_probe_start(&drop_ttbr)==-EIO); + drop_ttbr_write=false; + assert(!sid16_saw_translate); + assert(drop_ttbr.retained && drop_ttbr.managed_failed && noidle_puts==1 && !pm_refs); + assert(!drop_ttbr.sid16_ops && !drop_ttbr.sid16_ttbr && sid16_allocs==1 && sid16_frees==1); + assert(drop_ttbr.regs[DART_TCR(&drop_ttbr,16)/4]==2); + assert(last_sid16_tcr_write==hw->tcr_bypass); + assert(drop_ttbr.regs[DART_TTBR(&drop_ttbr,16,0)/4]==0xabcd001); + assert((drop_ttbr.regs[hw->enable_streams/4]&(BIT(1)|BIT(2)|BIT(16)))==BIT(16)); + + /* Dropped ENABLE[16] write during narrowing fails probe and rolls back. */ + struct apple_dart drop_en={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + drop_en.regs[DART_TCR(&drop_en,16)/4]=2; + drop_en.regs[DART_TTBR(&drop_en,16,0)/4]=0xabcd001; + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; noidle_puts=0; + last_sid16_tcr_write=0; + drop_enable_write=true; + assert(test_probe_start(&drop_en)==-EIO); + drop_enable_write=false; + assert(drop_en.retained && drop_en.managed_failed && noidle_puts==1 && !pm_refs); + assert(!drop_en.sid16_ops && !drop_en.sid16_ttbr && sid16_allocs==1 && sid16_frees==1); + assert(last_sid16_tcr_write==hw->tcr_bypass); + assert(drop_en.regs[DART_TCR(&drop_en,16)/4]==2); + assert(drop_en.regs[DART_TTBR(&drop_en,16,0)/4]==0xabcd001); + assert(!(drop_en.regs[hw->enable_streams/4]&(BIT(1)|BIT(2)|BIT(16)))); + + /* Mismatched TCR readback on restore keeps table unfreed. */ + struct apple_dart mismatch_tcr={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + mismatch_tcr.regs[DART_TCR(&mismatch_tcr,16)/4]=6; + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; + assert(!test_probe_start(&mismatch_tcr)); + apple_dart_managed_unnarrow_sid16(&mismatch_tcr); + assert(mismatch_tcr.sid16_ops && sid16_frees==0); + assert(mismatch_tcr.regs[DART_TCR(&mismatch_tcr,16)/4]==2); + free_io_pgtable_ops(mismatch_tcr.sid16_ops); + pm_refs=0; + + /* Failed DISABLE_STREAMS clear refuses to restore bypass and keeps table unfreed. */ + struct apple_dart stuck_en={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + stuck_en.regs[DART_TCR(&stuck_en,16)/4]=2; + stuck_en.regs[DART_TTBR(&stuck_en,16,0)/4]=0xabcd001; + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; + assert(!test_probe_start(&stuck_en)); + drop_disable_write=true; + apple_dart_managed_unnarrow_sid16(&stuck_en); + assert(stuck_en.sid16_ops && sid16_frees==0); + assert(stuck_en.regs[DART_TCR(&stuck_en,16)/4]==1); + assert(stuck_en.regs[DART_TTBR(&stuck_en,16,0)/4]==stuck_en.sid16_ttbr); + drop_disable_write=false; + free_io_pgtable_ops(stuck_en.sid16_ops); + pm_refs=0; + + /* Failed TCR restore keeps TTBR intact and keeps table unfreed. */ + struct apple_dart stuck_tcr={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + stuck_tcr.regs[DART_TCR(&stuck_tcr,16)/4]=2; + stuck_tcr.regs[DART_TTBR(&stuck_tcr,16,0)/4]=0xabcd001; + stuck_tcr.regs[hw->enable_streams/4]=BIT(16); + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; + assert(!test_probe_start(&stuck_tcr)); + drop_bypass_write=true; + apple_dart_managed_unnarrow_sid16(&stuck_tcr); + assert(stuck_tcr.sid16_ops && sid16_frees==0); + assert(stuck_tcr.regs[DART_TCR(&stuck_tcr,16)/4]==1); + assert(stuck_tcr.regs[DART_TTBR(&stuck_tcr,16,0)/4]==stuck_tcr.sid16_ttbr); + drop_bypass_write=false; + free_io_pgtable_ops(stuck_tcr.sid16_ops); + pm_refs=0; + + /* Failed TTBR restore keeps table unfreed. */ + struct apple_dart stuck_ttbr={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + stuck_ttbr.regs[DART_TCR(&stuck_ttbr,16)/4]=2; + stuck_ttbr.regs[DART_TTBR(&stuck_ttbr,16,0)/4]=0xabcd001; + stuck_ttbr.regs[hw->enable_streams/4]=BIT(16); + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; + assert(!test_probe_start(&stuck_ttbr)); + drop_ttbr_write=true; + apple_dart_managed_unnarrow_sid16(&stuck_ttbr); + assert(stuck_ttbr.sid16_ops && sid16_frees==0); + assert(stuck_ttbr.regs[DART_TTBR(&stuck_ttbr,16,0)/4]==stuck_ttbr.sid16_ttbr); + drop_ttbr_write=false; + free_io_pgtable_ops(stuck_ttbr.sid16_ops); + pm_refs=0; + + /* Failed TLB flush during teardown keeps the page table unfreed. */ + struct apple_dart stuck={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + stuck.regs[DART_TCR(&stuck,16)/4]=2; + stuck.regs[hw->enable_streams/4]=BIT(16); + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; + assert(!test_probe_start(&stuck)); + tlb_result=-EIO; + apple_dart_managed_unnarrow_sid16(&stuck); + assert(stuck.sid16_ops && sid16_frees==0); + free_io_pgtable_ops(stuck.sid16_ops); + tlb_result=0; pm_refs=0; tcr_clear_dapf=false; } ''' code += r''' @@ -609,6 +923,16 @@ def main(): map_result[1]=-ENODEV; assert(apple_pcie_radio_check_cold(&port)==-ENODEV); map_result[1]=0; assert(!memcmp(before,d.regs,sizeof(before)) && !node_refs && !provider_refs); assert(!radio_provider.dev.locked && !d.managed_lock); + d.sid16_ops=(void *)1; d.sid16_ttbr=0x4001; + d.regs[DART_TCR(&d,16)/4]=1; d.regs[DART_TTBR(&d,16,0)/4]=0x4001; + assert(apple_pcie_radio_check_cold(&port)==0); + d.regs[hw.enable_streams/4]&=~BIT(16); + assert(apple_pcie_radio_check_cold(&port)==-EBUSY); + d.regs[hw.enable_streams/4]|=BIT(16); + assert(apple_pcie_radio_check_cold(&port)==0); + d.sid16_ops=NULL; d.sid16_ttbr=0; + d.regs[DART_TCR(&d,16)/4]=before[DART_TCR(&d,16)/4]; + d.regs[DART_TTBR(&d,16,0)/4]=before[DART_TTBR(&d,16,0)/4]; puts("radio normal SIDs: admission, scoped publication, foreign preservation, TLB failure rollback, quarantine, group merge and checked cold start PASS"); } ''' diff --git a/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py b/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py index f72da9d9558276..25884752bc6f0e 100755 --- a/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py +++ b/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py @@ -27,7 +27,7 @@ def recovery_program(source): unsigned long reset_pending, dma_window_base;struct pci_dev *pdev;struct hci_dev *hdev; const struct bcm4377_hw *hw;bool needs_reset,own_reset;unsigned bootstage,rti_status; struct ring_state *ring_state; - struct { unsigned generation,n_entries;unsigned long msgids[1];unsigned *events; } control_h2d_ring; + struct { unsigned generation,n_entries,head;unsigned long msgids[1];unsigned *events; } control_h2d_ring; struct { bool enabled; } control_ack_ring; }; struct hci_dev { struct bcm4377_data *data; bool setup; }; @@ -94,7 +94,9 @@ def recovery_program(source): assert(errors==1 && !pci_resets && !irq_disables && !irq_enables && !boots); assert(b.needs_reset && ring.value==99); b.dma_window_base=0;b.control_h2d_ring.n_entries=4; + b.control_h2d_ring.head=3; assert(!bcm4377_pci_reset(&b) && pci_resets==1 && irq_disables==1 && irq_enables==1); + assert(b.control_h2d_ring.head==0); assert(!b.own_reset); assert(!b.needs_reset && !ring.value && boots==1); reset_error=-EIO; diff --git a/tools/testing/selftests/drivers/apple/pmgr-inherited.py b/tools/testing/selftests/drivers/apple/pmgr-inherited.py index affc0312450b10..a2e036a1352b76 100755 --- a/tools/testing/selftests/drivers/apple/pmgr-inherited.py +++ b/tools/testing/selftests/drivers/apple/pmgr-inherited.py @@ -71,7 +71,7 @@ def main(): struct device_node { struct device_node *parent; const char *name, *conflict; - bool inherited, firmware; + bool inherited, firmware, status; }; struct device { struct device_node *of_node; }; struct platform_device { struct device dev; }; @@ -101,7 +101,10 @@ def main(): static int apple_pmgr_reset_ops; static int (*apple_pmgr_genpd_runtime_suspend)(struct device *dev); static unsigned parent_attach_count; -static bool apple_t8132_firmware_path(void) { return true; } +static bool platform_handoff, firmware_path; +#define CONFIG_APPLE_T8132_PLATFORM_HANDOFF platform_handoff +#define IS_ENABLED(option) (option) +static bool apple_t8132_firmware_path(void) { return firmware_path; } static bool apple_sleep_domain_is_down(struct device_node *n) { (void)n; return false; } static struct device_node *of_parse_phandle(struct device_node *n, const char *p, int i) { (void)n; (void)p; (void)i; return NULL; } @@ -109,7 +112,7 @@ def main(): { return n && !strcmp(p,"apple,t8132-pmgr-pwrstate"); } static bool of_machine_is_compatible(const char *p) { (void)p; return false; } static bool of_property_present(struct device_node *n, const char *p) -{ return !strcmp(p,"status") || (n->conflict && !strcmp(n->conflict,p)) || +{ return (n->status && !strcmp(p,"status")) || (n->conflict && !strcmp(n->conflict,p)) || (n->inherited && !strcmp(p,"apple,inherited-on")) || (n->firmware && !strcmp(p,"apple,firmware-owned")); } static bool of_property_read_bool(struct device_node *n, const char *p) @@ -183,7 +186,21 @@ def main(): { clean(value,error); struct platform_device p={ .dev.of_node=node }; return apple_pmgr_ps_probe(&p); } int main(void) { - struct device_node n={ .name="power-controller@428", .inherited=true }; + struct device_node n={ .name="power-controller@428", .inherited=true, .status=true }; + struct device_node missing=n; missing.status=false; + for (int handoff=0; handoff<=1; handoff++) { + for (int qualified=0; qualified<=1; qualified++) { + platform_handoff=handoff; + firmware_path=qualified; + if (handoff || qualified) { + assert(probe(&missing,0xff,0)==-ENODEV); + assert(!map.reads && !map.writes && !provider_count && !reset_count); + } else { + assert(!probe(&missing,0xff,0)); + assert(map.reads==1 && !map.writes && provider_count==1); + } + } + } assert(!probe(&n,0xff,0)); struct apple_pmgr_ps *ps=driver_data; assert(map.reads==1 && !map.writes && init_count==1 && provider_count==1 && reset_count==1); @@ -223,7 +240,7 @@ def main(): assert(apple_pmgr_ps_power_off(&ps->genpd)==-EBUSY && !map.writes); puts("ok 3 - read errors and lost inherited activity never request a transition"); const char *conflicts[]={"apple,firmware-owned","apple,sleep-retained","apple,always-on","apple,min-state", - "apple,force-disable","apple,force-reset","apple,externally-clocked"}; + "apple,force-disable","apple,force-reset","apple,externally-clocked","apple,auto-managed"}; for(unsigned i=0;i(b) ? (a) : (b)) #define read_poll_timeout_atomic read_poll_timeout -''' + function(source, "regmap_sn201202x_select_reg") + function(source, "__regmap_sn201202x_read") + r''' +''' + function(source, "sn201202x_select_reg") + function(source, "regmap_sn201202x_select_reg") + function(source, "__regmap_sn201202x_read") + r''' #define regmap_sn201202x_read __regmap_sn201202x_read static void clean(struct spmi_device *s) { diff --git a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-edid.py b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-edid.py index bcced2f684cfa5..54485550122637 100644 --- a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-edid.py @@ -27,6 +27,8 @@ def function(name): #include "epic/dpavserv-edid.h" #define GFP_KERNEL 0 #define kzalloc(n,f) calloc(1,n) +#define kvzalloc(n,f) calloc(1,n) +#define kvfree(p) free(p) #define cpu_to_le64(x) (x) #define le64_to_cpu(x) (x) #define READ_ONCE(x) (x) diff --git a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-hpd.py b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-hpd.py index bdfd0f2325ba52..ea3915f0de720c 100644 --- a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-hpd.py +++ b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-hpd.py @@ -36,6 +36,8 @@ def function(source, name): typedef u32 __le32; #define GFP_KERNEL 0 #define kzalloc(n,f) calloc(1,n) +#define kvzalloc(n,f) calloc(1,n) +#define kvfree(p) free(p) #define kfree(p) free(p) #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) diff --git a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-send.py b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-send.py index 191881806f58cb..65e51df3bfddc4 100644 --- a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-send.py +++ b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-send.py @@ -49,8 +49,8 @@ def function(pattern, what): #define kfree(p) free(p) #define READ_ONCE(x) (x) #define WRITE_ONCE(x,v) ((x)=(v)) -#define spin_lock_irqsave(l,f) ((void)(l),(f)=0) -#define spin_unlock_irqrestore(l,f) ((void)(l),(void)(f)) +#define spin_lock_irqsave(l,f) do { assert(!*(l)); *(l)=1; (f)=0; } while(0) +#define spin_unlock_irqrestore(l,f) do { assert(*(l)); *(l)=0; (void)(f); } while(0) #define dma_rmb() do {} while(0) #define dev_warn(...) do {} while(0) #define dev_err(...) do {} while(0) @@ -119,6 +119,7 @@ def function(pattern, what): static int afk_send_epic(struct apple_dcp_afkep *ep,u32 channel,u16 tag,int type,int category,u8 subtype,const void *payload,size_t length) { struct cmd_info *c=&active->cmds[0];struct afkv2_command parsed; + assert(!active->lock && !ep->lock); assert(channel==4 && type==3 && category==0x30 && subtype==0xc0); sends++; /* The payload-envelope mock bounds the command separately from its response. */ diff --git a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-service.py b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-service.py index 19381f919d7e85..4c0164dce1aefc 100644 --- a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-service.py +++ b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-service.py @@ -24,6 +24,8 @@ #define GFP_KERNEL 0 #define kzalloc(n,f) calloc(1,n) #define kfree(p) free(p) +#define kvzalloc(n,f) calloc(1,n) +#define kvfree(p) free(p) #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) #define cpu_to_le16(x) (x) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp-early-hpd.py b/tools/testing/selftests/drivers/gpu/apple-dcp-early-hpd.py new file mode 100755 index 00000000000000..577d6cb04c7573 --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/apple-dcp-early-hpd.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Compile the real early-HPD helper with GPIO/RemotePort leaves modelled. + +No kernel or hardware executes. Tests that an inherited HDMI link can receive +its training trigger before the waiter, plus detach/read/RPC failure behavior +and the existing Type-C, tunnel and late-HPD paths. +""" +import os +from pathlib import Path +import subprocess +import tempfile + +root = Path(__file__).resolve().parents[5] +source = Path(os.environ.get('DCP_SOURCE', root / 'drivers/gpu/drm/apple/dcp.c')).read_text() +a = source.index('static int dcp_assert_hpd_before_link_wait(') +b = source.index('\n}\n', a) + 3 +body = source[a:b] +prefix = r''' +#include +#include +#include +#include +#include +typedef uint32_t u32; +#define DRM_MODE_CONNECTOR_HDMIA 11 +struct apple_dcp { + int fixed_connector_type; void *hdmi_hpd; + bool typec, tunnel; struct {void *service;} dptxport[2]; +}; +static int level=1, rpc_error, samples, calls, timeout_ms; +static bool link_configured; +static bool dcp_is_typec_output(struct apple_dcp*d){return d->typec;} +static bool dcp_uses_t6020_tunnel_flow(struct apple_dcp*d){return d->tunnel;} +static int gpiod_get_value_cansleep(void*p){assert(p);samples++;return level;} +static int dptxport_set_hpd(void*p,bool high) +{assert(p==(void*)123&&high);calls++;if(!rpc_error)link_configured=true;return rpc_error;} +static int dptxport_set_hpd_timeout(void*p,bool high,unsigned ms) +{timeout_ms=ms;return dptxport_set_hpd(p,high);} +''' +cases = r''' +int main(void) +{ + struct apple_dcp d={.fixed_connector_type=DRM_MODE_CONNECTOR_HDMIA,.hdmi_hpd=(void*)1, + .dptxport={{(void*)123},{0}}}; + /* Model the observed inherited-display dependency: without AP HPD the + * request is accepted but the link waiter receives no training event. */ + assert(!link_configured);assert(!dcp_assert_hpd_before_link_wait(&d,0,false,false)); + assert(link_configured&&samples==1&&calls==1&&!timeout_ms); + calls=samples=0;link_configured=false;level=0; + assert(dcp_assert_hpd_before_link_wait(&d,0,false,false)==-ENOLINK); + assert(samples==1&&!calls&&!link_configured); + level=-EIO;samples=0; + assert(dcp_assert_hpd_before_link_wait(&d,0,false,false)==-EIO); + assert(samples==1&&!calls); + level=1;rpc_error=-ETIMEDOUT; + assert(dcp_assert_hpd_before_link_wait(&d,0,false,false)==-ETIMEDOUT); + assert(!link_configured);rpc_error=0; + calls=samples=0; + assert(!dcp_assert_hpd_before_link_wait(&d,0,true,false));assert(!calls&&!samples); + /* 13.5 DP2HDMI and adopted sessions keep their own HPD owner. */ + assert(!dcp_assert_hpd_before_link_wait(&d,0,false,true));assert(!calls&&!samples); + d.fixed_connector_type=0; + assert(!dcp_assert_hpd_before_link_wait(&d,0,false,false));assert(!calls&&!samples); + d.fixed_connector_type=DRM_MODE_CONNECTOR_HDMIA; + /* A borrowed Type-C route on an HDMI-capable pipe must not sample HDMI. */ + d.typec=true;level=0;calls=samples=0; + assert(!dcp_assert_hpd_before_link_wait(&d,0,false,true));assert(calls==1&&!samples); + d.tunnel=true;calls=timeout_ms=0; + assert(!dcp_assert_hpd_before_link_wait(&d,0,false,false));assert(calls==1&&timeout_ms==8000&&!samples); + d.typec=d.tunnel=false;d.hdmi_hpd=0;calls=0; + assert(!dcp_assert_hpd_before_link_wait(&d,0,false,false));assert(!calls&&!samples); + puts("early AP HPD: inherited HDMI trigger, errors, late-HPD, Type-C and tunnel regressions pass"); +} +''' +# Check real call ordering/error unwind in the production caller as well. +start = source.index('static int dcp_dptx_connect_raw(') +caller = source[start:source.index('\n}\n', start)] +request = caller.index('dptxport_request_display(') +hpd = caller.index('dcp_assert_hpd_before_link_wait(') +wait = caller.index('dcp_dptx_wait_linkcfg(') +assert request < hpd < wait +assert 'goto out_release;' in caller[hpd:wait] +with tempfile.TemporaryDirectory(prefix='dcp-hpd-') as tmp: + p=Path(tmp);(p/'test.c').write_text(prefix+body+cases) + for mode,flags in [('normal',[]),('sanitizer',['-fsanitize=address,undefined','-fno-sanitize-recover=all'])]: + exe=p/mode + subprocess.run([os.environ.get('CC','cc'),'-std=gnu11','-O1','-g','-Wall','-Wextra','-Werror',*flags,str(p/'test.c'),'-o',str(exe)],check=True) + subprocess.run([exe],check=True) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py b/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py index 39d02e69271dd4..d1d6e9f57c3e68 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py @@ -24,7 +24,7 @@ def reply_bounds(root): #define GFP_KERNEL 0 static void free_buffer(void *p) {free(*(void **)p);} #define __free(x) __attribute__((cleanup(free_buffer))) -static void *kzalloc(size_t n, int flags) {(void)flags;return calloc(1,n);} +static void *kvzalloc(size_t n, int flags) {(void)flags;return calloc(1,n);} #define cpu_to_le64(x) (x) #define le64_to_cpu(x) (x) struct apple_dcp_afkep {bool compact;}; @@ -124,6 +124,7 @@ def cec_only_endpoint(root): source = (root / 'drivers/gpu/drm/apple/av.c').read_text() prefix = r''' #include +#include #include #include #include @@ -134,18 +135,22 @@ def cec_only_endpoint(root): #define READ_ONCE(x) (x) #define WRITE_ONCE(x, v) ((x) = (v)) #define dev_info(d, ...) ((void)(d)) -#define dev_err(d, ...) ((void)(d)) +static unsigned errs, armed; +#define dev_err(d, ...) ((void)(d), errs++) +#define AV_AUDIOSRV_REPLACE_MS 1000 +static int system_wq; +static unsigned long msecs_to_jiffies(unsigned m) {return m;} +#define mod_delayed_work(wq, w, j) ((void)(wq), (void)(w), (void)(j), armed++) struct device {int unused;}; struct platform_device {int unused;}; struct lock {int held;}; static unsigned takes; static struct lock *lock_take(struct lock *l) {assert(!l->held); l->held = 1; takes++; return l;} static void lock_drop(struct lock **l) {if (*l) (*l)->held = 0;} +#define guard(type) struct lock *_g __attribute__((cleanup(lock_drop))) = lock_take #define scoped_guard(type, l) \ for (struct lock *_guard __attribute__((cleanup(lock_drop))) = lock_take(l), *_once = _guard; \ _once; _once = NULL) -static void mutex_lock(struct lock *l) {lock_take(l);} -static void mutex_unlock(struct lock *l) {l->held = 0;} struct apple_epic_service {bool torndown; unsigned pins;}; struct apple_dcp_afkep {int endpoint;}; struct audiosrv_data { @@ -155,9 +160,14 @@ def cec_only_endpoint(root): u64 gen, v27_boot_gen; struct platform_device *audio_dev; struct {u32 open, close;} cmds; + int open_check_wq, open_refused; + struct device *open_check_dev; }; struct apple_dcp {struct device *dev; struct apple_dcp_afkep *avep; struct audiosrv_data *audiosrv;}; static bool native, v27; +static int call_ret, hook; +static struct audiosrv_data *hook_asrv; +static struct apple_epic_service *hook_next; static unsigned calls, last_cmd, connects, disconnects, releases, closes, v27_starts; static bool dcp_audiosrv_native_link(struct device *dev) {(void)dev; return native;} static bool dcp_is_v14_7_external(const struct apple_dcp *dcp) {(void)dcp; return false;} @@ -176,10 +186,18 @@ def cec_only_endpoint(root): size_t pad, void *out, size_t room, size_t out_pad) { (void)group; (void)data; (void)len; (void)pad; (void)out; (void)room; (void)out_pad; - assert(s && s->pins); calls++; last_cmd = cmd; return 0; + assert(s && s->pins); calls++; last_cmd = cmd; + /* A successor published while the RPC runs (and, at a Close, opened) */ + if (hook) { + hook_asrv->srv = hook_next; + hook_asrv->is_open = hook == 2; + hook = 0; + } + return call_ret; } ''' - return prefix + block(source, 'void av_service_connect(') + '\n' + block( + return prefix + block(source, 'static bool av_audiosrv_published(') + '\n' + block( + source, 'void av_service_connect(') + '\n' + block( source, 'static void __av_service_disconnect(') + '\n' + block( source, 'void av_service_disconnect(') + r''' int main(void) @@ -224,6 +242,41 @@ def cec_only_endpoint(root): av_service_connect(&dcp); av_service_disconnect(&dcp); assert(connects == 3 && disconnects == 2 && calls == 2); + + /* + * Classic link, the firmware refuses the Open (an instance being + * replaced): judged later, not reported now; any other error is. + */ + native = v27 = false; + asrv.srv = &srv; + call_ret = -EINVAL; + av_service_connect(&dcp); + assert(calls == 3 && !asrv.is_open && armed == 1 && !errs && asrv.open_refused == -EINVAL && + connects == 3); + call_ret = -ETIMEDOUT; + av_service_connect(&dcp); + assert(calls == 4 && !asrv.is_open && armed == 1 && errs == 1); + call_ret = 0; + av_service_connect(&dcp); + assert(calls == 5 && asrv.is_open && connects == 4); + + /* A Close whose instance is replaced meanwhile leaves the successor's Open. */ + struct apple_epic_service next = {0}; + hook_asrv = &asrv; + hook_next = &next; + hook = 2; + av_service_disconnect(&dcp); + assert(calls == 6 && last_cmd == 5 && asrv.srv == &next && asrv.is_open); + + /* An Open whose instance is replaced meanwhile is not the successor's. */ + asrv.srv = &srv; + asrv.is_open = false; + hook_next = &next; + hook = 1; + av_service_connect(&dcp); + assert(calls == 7 && last_cmd == 4 && asrv.srv == &next && !asrv.is_open && connects == 4); + assert(!next.pins); + asrv.srv = &srv; assert(!srv.pins && !asrv.srv_rwsem.held && !asrv.plug_lock.held); return 0; } diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index b7ebb2fc9fc5ff..f796e7c437415b 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -36,6 +36,7 @@ def oslog(root): static bool neo, m5; #define of_machine_is_compatible(s) ((!strcmp(s,"apple,t8140") && neo) || (!strcmp(s,"apple,t8142") && m5)) #define dev_warn(dev,fmt,msg) do { (void)(dev); (void)(fmt); warnings++; observed=(msg); } while (0) +#define dev_warn_ratelimited(dev,fmt,msg) dev_warn(dev,fmt,msg) #define dev_dbg(dev,fmt,msg) do { (void)(dev); (void)(fmt); notifications++; observed=(msg); } while (0) #define dev_err(dev,fmt,msg) do { (void)(dev); (void)(fmt); (void)(msg); errors++; } while (0) static int __attribute__((unused)) apple_rtkit_send_message(struct apple_rtkit *rtk, u8 ep, u64 msg, void *completion, bool atomic) @@ -138,7 +139,11 @@ def syslog(root): { (void)rtk; assert(off + len <= b->size); copies++; memcpy(out, b->buffer+off, len); } static int apple_rtkit_send_message(struct apple_rtkit *rtk, u8 ep, u64 msg, void *c, bool atomic) { (void)rtk; assert(ep==2 && msg==0 && c==NULL && !atomic); acks++; return 0; } -''' + helper + '\n' + block(dcp, 'static bool dcp_rtk_syslog_is_debug(') + r''' +typedef uint32_t u32; +#define READ_ONCE(x) (x) +#define WRITE_ONCE(x, v) ((x) = (v)) +struct apple_dcp { struct { bool only_120hz_modes; } hw; u32 boot_rate; }; +''' + helper + '\n' + block(dcp, 'static void dcp_rtk_syslog_boot_rate(') + '\n' + block(dcp, 'static bool dcp_rtk_syslog_is_debug(') + r''' static bool policy(void *cookie, const char *context, const char *message) { calls++; return dcp_rtk_syslog_is_debug(cookie, context, message); } ''' + block(source, 'static bool should_crop_syslog_char(') + '\n' + block(source, 'static void apple_rtkit_syslog_rx_log(') + r''' @@ -153,7 +158,8 @@ def syslog(root): { unsigned char ring[288]; char decoded[256]; struct apple_rtkit_ops ops={.syslog_is_debug=policy}; - struct apple_rtkit rtk={.ops=&ops, .syslog_msg_buffer=decoded, + struct apple_dcp dcp={.hw={.only_120hz_modes=true}}; + struct apple_rtkit rtk={.ops=&ops, .cookie=&dcp, .syslog_msg_buffer=decoded, .syslog_msg_size=256, .syslog_n_entries=1, .syslog_buffer={.size=sizeof(ring),.buffer=ring}}; const char *messages[]={ @@ -190,55 +196,92 @@ def syslog(root): reset(); apple_rtkit_syslog_rx_log(&rtk,0); assert(warnings==1 && !calls && !copies && acks==1); puts("PASS default info, trimming, inherited and invalid records retain transport behavior"); + rtk.syslog_n_entries=1; + /* The rate iBoot left the T6050 panel at: the first one counts, the line stays at info. */ + record(&rtk,"PBlock_PDC_v17.cpp:1954","IOMFB update_rr_index syncrate 60"); + reset(); apple_rtkit_syslog_rx_log(&rtk,0); + assert(dcp.boot_rate==60 && infos==1 && !debugs && acks==1); + record(&rtk,"PBlock_PDC_v17.cpp:1954","IOMFB update_rr_index syncrate 120"); + reset(); apple_rtkit_syslog_rx_log(&rtk,0); + assert(dcp.boot_rate==60 && infos==1); + dcp.boot_rate=0; dcp.hw.only_120hz_modes=false; + reset(); apple_rtkit_syslog_rx_log(&rtk,0); + assert(dcp.boot_rate==0 && infos==1); + dcp.hw.only_120hz_modes=true; + record(&rtk,"PBlock_PDC_v17.cpp:1954","IOMFB update_rr_index syncrate 7"); + reset(); apple_rtkit_syslog_rx_log(&rtk,0); + assert(dcp.boot_rate==0 && infos==1); + puts("PASS T6050 boot rate: first rate latched, later and out-of-range rates ignored, other panels untouched"); return 0; } ''' -def t6041_v27_admission(root): +def _v27_prelude(root): + """Host stand-ins for OF and legacy board checks, then the live selector.""" display_h = (root / 'include/linux/soc/apple/display.h').read_text() uuid_defines = [line for line in display_h.splitlines() if line.startswith(('#define APPLE_T6041_DCP_26B123_UUID ', - '#define APPLE_T8122_DCP_26B123_UUID '))] - assert len(uuid_defines) == 2 - helper = '\n'.join((*uuid_defines, *( - block(display_h, 'static inline bool ' + name + '(') for name in ( - 'apple_dcp_image_v27_2', - 'apple_t6041_dcp_any_v27_2', 'apple_t6041_dcp_v27_2', - 'apple_t6041_dcpext_v27_2', 'apple_t8122_dcp_v27_2')))) + '#define APPLE_T8122_DCP_26B123_UUID ', + '#define APPLE_T8132_DCP_26B123_UUID '))] + assert len(uuid_defines) == 3 + helpers = ('static inline bool apple_dcp_image_v27_2(', + 'static inline bool apple_t8132_dcp_v27_2(', + 'static inline bool apple_t6041_dcp_any_v27_2(', + 'static inline bool apple_t6041_dcp_v27_2(', + 'static inline bool apple_t6041_dcpext_v27_2(', + 'static inline bool apple_t8122_dcp_v27_2(', + 'static inline bool\napple_t8122_dcpext_v27_2_for_internal(', + 'static inline bool apple_t8122_dcpext_v27_2(') + # The T8132 27.2 dcpext admission: by processor and image, never by board. No + # of_machine_is_compatible() exists in these units, so neither it nor the display.h + # helpers can depend on the machine. + t8132_h = (root / 'include/linux/soc/apple/t8132.h').read_text() + t8132_admission = block(t8132_h, 'static inline bool apple_t8132_dcpext_v27_2(') + assert 'of_machine_is_compatible' not in t8132_admission + helper = '\n'.join((*uuid_defines, *(block(display_h, marker) for marker in helpers), + t8132_admission)) iomfb_h = (root / 'drivers/gpu/drm/apple/iomfb.h').read_text() methods_decl = iomfb_h[iomfb_h.index('enum dcpep_method {'): iomfb_h.index('#define IOMFB_MAX_CB')] v27_c = (root / 'drivers/gpu/drm/apple/iomfb_v27.c').read_text() v27_tables = v27_c[v27_c.index('static const struct dcp_method_entry dcp_methods_27_0'): v27_c.index('/* The template\'s calls resolve through')] - dcp_c = (root / 'drivers/gpu/drm/apple/dcp.c').read_text() - method_table = block(dcp_c, 'static enum dcp_firmware_version dcp_v27_method_table(') - selector_full = block(dcp_c, 'static enum dcp_firmware_version dcp_check_firmware_version(') - cutoff = '\n\tret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str);\n\tif (ret < 0)' - selector = selector_full[:selector_full.index(cutoff)] + '\n\t(void)v14_board;\n\treturn DCP_FIRMWARE_UNKNOWN;\n}\n' + apple = root / 'drivers/gpu/drm/apple' + dcp_c = (apple / 'dcp.c').read_text() + version_defs = '\n'.join(line for line in dcp_c.splitlines() + if line.startswith('#define DCP_FW_VERSION_')) + version_enum = block((apple / 'version_utils.h').read_text(), + 'enum dcp_firmware_version {') + ';' + admission_enum = block((apple / 'dcp.h').read_text(), 'enum dcp_v27_admission {') + ';' + selector = '\n'.join(block(dcp_c, marker) for marker in ( + 'static int dcp_read_fw_version(', + 'static enum dcp_firmware_version dcp_v27_method_table(', + 'enum dcp_v27_admission dcp_v27_admission(', + 'static bool dcp_firmware_27(', + 'static enum dcp_firmware_version dcp_check_firmware_version(', + )) return r''' #include +#include #include #include #include #include +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) typedef uint32_t u32; -enum dcp_firmware_version { - DCP_FIRMWARE_UNKNOWN, - DCP_FIRMWARE_V_26_6_DESKTOP, - DCP_FIRMWARE_V_27_0, -}; +''' + version_defs + '\n' + version_enum + '\n' + admission_enum + r''' struct dcp_v14_board; struct apple_dcp_hw_data { enum dcp_firmware_version firmware_compat; }; struct device_node { const char *compatible; const char *uuid; int uuid_count; - u32 fw[3]; + u32 fw[DCP_FW_VERSION_MAX_LEN]; int fw_cells; - u32 compat[3]; + u32 compat[DCP_FW_VERSION_MAX_LEN]; int compat_cells; + bool clock_ids; }; struct device { struct device_node *of_node; @@ -248,6 +291,25 @@ def t6041_v27_admission(root): { return np && np->compatible && !strcmp(np->compatible, s); } +/* The tree's display processors, for of_find_compatible_node(). */ +static struct device_node *of_nodes[2]; +static int of_node_refs; +static struct device_node *of_find_compatible_node(struct device_node *from, + const char *type, const char *s) +{ + assert(!from && !type); + for (unsigned i = 0; i < 2; i++) + if (of_device_is_compatible(of_nodes[i], s)) { + of_node_refs++; + return of_nodes[i]; + } + return NULL; +} +static void of_node_put(struct device_node *np) +{ + if (np) + assert(of_node_refs-- > 0); +} static int of_property_count_strings(const struct device_node *np, const char *name) { assert(!strcmp(name, "apple,firmware-uuid")); @@ -271,29 +333,37 @@ def t6041_v27_admission(root): return np->compat_cells; return -1; } -static int of_property_read_u32_array(const struct device_node *np, const char *name, u32 *out, size_t n) +static int of_property_read_variable_u32_array(const struct device_node *np, const char *name, + u32 *out, int min, int max) { + int cells = of_property_count_u32_elems(np, name); const u32 *src; - int cells; - if (!np || n != 3) - return -1; - if (!strcmp(name, "apple,firmware-version")) { - src = np->fw; - cells = np->fw_cells; - } else if (!strcmp(name, "apple,firmware-compat")) { - src = np->compat; - cells = np->compat_cells; - } else { - return -1; - } - if (cells != 3) - return -1; - memcpy(out, src, 3 * sizeof(u32)); - return 0; + + if (cells < min || cells > max) + return -EINVAL; + src = !strcmp(name, "apple,firmware-version") ? np->fw : np->compat; + memcpy(out, src, cells * sizeof(*out)); + return cells; +} +static int of_property_read_u32_array(const struct device_node *np, const char *name, u32 *out, int n) +{ + int ret = of_property_read_variable_u32_array(np, name, out, n, n); + + return ret < 0 ? ret : 0; } -#define DCP_FW_VERSION_STR_LEN 32 +#define scnprintf snprintf +#define strscpy(dst, src, size) snprintf((dst), (size), "%s", (src)) #define GFP_KERNEL 0 -#define dev_err(...) ((void)0) +#define dev_warn(...) ((void)0) +#define IS_ERR(ptr) false +static void dev_err(struct device *dev, const char *format, ...) {} +#define dev_info(...) ((void)0) +/* linux/soc/apple/t8132.h: the M4 backend's 26.6.2 firmware path (or an Air) */ +static bool t8132_firmware_path; +static bool apple_t8132_firmware_path(void) +{ + return t8132_firmware_path; +} static void *devm_kmemdup(struct device *dev, const void *src, size_t len, unsigned int gfp) { (void)dev; (void)src; (void)len; (void)gfp; @@ -303,19 +373,123 @@ def t6041_v27_admission(root): { return dev->hw; } -static int dcp_read_fw_version(struct device *dev, const char *name, char *out) +/* No internal board profile is present in these fixtures; apple,clock-ids is the handoff flag. */ +static bool of_property_present(const struct device_node *np, const char *name) { - u32 v[3]; - if (of_property_count_u32_elems(dev->of_node, name) != 3 || - of_property_read_u32_array(dev->of_node, name, v, 3)) + if (!strcmp(name, "apple,clock-ids")) + return np && np->clock_ids; + assert(!strcmp(name, "apple,j613-25g83-profile")); + return false; +} +static bool apple_t8122_25g83_board(void) { return false; } +static int of_property_read_u32(struct device_node *np, const char *name, u32 *out) +{ + return -ENOENT; +} +static const struct dcp_v14_board *iomfb_v14_7_board(struct device *dev) { return NULL; } +static const char *iomfb_v14_7_board_name(const struct dcp_v14_board *board) { return ""; } +static bool ext26; +static bool dcp_ext26_admitted(struct device_node *np) { return ext26; } +''' + helper + '\n' + methods_decl + '\n' + v27_tables + '\n' + selector + '\n' + + +def v27_panel_handoff(root): + source = (root / 'drivers/gpu/drm/apple/dcp.c').read_text() + profiles = ('t6030', 't8122', 't6031', 't6041') + match = '\n'.join(block(source, f'static const struct apple_dcp_hw_data apple_dcp_hw_{soc} =') + + ';' for soc in profiles) + profile = block(source, 'static void dcp_apply_dt_profile(') + return r''' +#include +#include +#include +#include +typedef uint8_t u8; +typedef uint32_t u32; +enum { DCP_FIRMWARE_V_27_0 = 27 }; +struct device_node { + bool rtkit_handoff; + const char *marker; + u32 value; +}; +struct device { struct device_node *of_node; }; +struct apple_dcp_hw_data { + bool adopt_live_session; + const char *iboot_handoff; + unsigned num_dptx_ports; + u8 firmware_dma_bits; +}; +struct apple_dcp { + struct device *dev; + struct apple_dcp_hw_data hw; + int fw_compat; +}; +static bool of_property_present(struct device_node *np, const char *name) +{ + assert(!strcmp(name, "apple,rtkit-handoff")); + return np->rtkit_handoff; +} +static int of_property_read_variable_u32_array(struct device_node *np, const char *name, + u32 *value, int min, int max) +{ + assert(min == 1 && max == 1); + if (!np->marker || strcmp(name, np->marker)) return -1; - snprintf(out, DCP_FW_VERSION_STR_LEN, "%u.%u.%u", v[0], v[1], v[2]); - return 3; + *value = np->value; + return 1; +} +/* All probes see the same DART aperture and panel-only topology. */ +static u8 dcp_dart_dma_bits(struct device_node *np) { return 41; } +static bool dcp_is_internal_panel_only(struct apple_dcp *dcp) { return true; } +''' + match + '\n' + profile + r''' +static void check(struct apple_dcp_hw_data hw, struct device_node node, bool live) +{ + struct device dev = { .of_node = &node }; + struct apple_dcp dcp = { .dev = &dev, .hw = hw, .fw_compat = DCP_FIRMWARE_V_27_0 }; + + dcp_apply_dt_profile(&dcp); + assert(dcp.hw.adopt_live_session == live); + assert(dcp.hw.firmware_dma_bits == 41); + assert(dcp.hw.num_dptx_ports == 0); +} + +int main(void) +{ + const struct { + const struct apple_dcp_hw_data *hw; + const char *marker; + } panels[] = { + { &apple_dcp_hw_t6030, "apple,t6030-handoff" }, + { &apple_dcp_hw_t8122, "apple,t8122-handoff" }, + { &apple_dcp_hw_t6031, "apple,t6031-handoff" }, + { &apple_dcp_hw_t6041, "apple,t6041-handoff" }, + }; + + for (unsigned i = 0; i < sizeof(panels) / sizeof(panels[0]); i++) { + struct apple_dcp_hw_data hw = *panels[i].hw; + struct device_node node = {}; + + check(hw, node, false); + node.rtkit_handoff = true; + check(hw, node, true); + node.rtkit_handoff = false; + node.marker = panels[i].marker; + check(hw, node, false); + node.value = 1; + check(hw, node, true); + node.marker = panels[i ? 0 : 1].marker; + check(hw, node, false); + } + return 0; } -''' + helper + '\n' + methods_decl + '\n' + v27_tables + '\n' + method_table + '\n' + selector + r''' +''' + + +def t6041_v27_admission(root): + return _v27_prelude(root) + r''' static struct device_node node; -static struct apple_dcp_hw_data hw_t6041; -static struct device dev = { .of_node = &node, .hw = &hw_t6041 }; +static const struct apple_dcp_hw_data hw; +static struct device dev = { .of_node = &node, .hw = &hw }; static void reset_t6041_26b123(bool ext) { @@ -358,10 +532,14 @@ def t6041_v27_admission(root): assert(apple_t6041_dcpext_v27_2(&node)); assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_V_27_0); - for (unsigned ext = 0; ext < 2; ext++) { - /* Reject non-T6041 DCP compatibles. */ - reset_t6041_26b123(ext); node.compatible = "apple,t6031-dcp"; expect_rejected(); + /* A different SoC follows generic admission, without the T6041 UUID pin. */ + node.compatible = "apple,t6031-dcp"; + node.uuid_count = 0; + assert(!apple_t6041_dcp_v27_2(&node)); + assert(!apple_t6041_dcpext_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_V_27_0); + for (unsigned ext = 0; ext < 2; ext++) { /* Reject missing, multi-string, or non-26B123 firmware UUIDs (including 26B131). */ reset_t6041_26b123(ext); node.uuid_count = 0; expect_rejected(); reset_t6041_26b123(ext); node.uuid_count = 2; expect_rejected(); @@ -390,11 +568,9 @@ def t6041_v27_admission(root): } /* * The M3 Air's (T8122) internal DCP handed over with its 27.2 image runs - * the 27.2 table, on any T8122 board; its dcpext, another image, its - * 14.x image and other releases do not. + * the 27.2 table. The external processor needs the internal handoff, + * other firmware-27 images are refused and 14.7 stays on a legacy ABI. */ - static struct apple_dcp_hw_data hw_t8122; - dev.hw = &hw_t8122; reset_t6041_26b123(false); node.compatible = "apple,t8122-dcp"; node.uuid = APPLE_T8122_DCP_26B123_UUID; @@ -410,21 +586,383 @@ def t6041_v27_admission(root): assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); node.uuid = APPLE_T8122_DCP_26B123_UUID; node.uuid_count = 0; assert(!apple_t8122_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); node.uuid_count = 2; assert(!apple_t8122_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); node.uuid_count = 1; node.fw[0] = 14; node.fw[1] = 7; node.fw[2] = 0; node.compat[0] = 14; node.compat[1] = 7; node.compat[2] = 0; assert(!apple_t8122_dcp_v27_2(&node)); - assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_V_14_7_TEMPLATE); node.fw[0] = 27; node.fw[1] = 2; node.fw[2] = 1; node.compat[0] = 27; node.compat[1] = 2; node.compat[2] = 1; assert(!apple_t8122_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); node.fw[2] = 0; node.compat[2] = 0; assert(apple_t8122_dcp_v27_2(&node)); - dev.hw = &hw_t6041; + /* + * A T8132 processor of the M4 backend keeps it on the M4 firmware path + * only; off it (a Mac mini booted from 27.2) nobody adopts or touches it. + */ + static struct apple_dcp_hw_data hw_m4 = { .firmware_compat = DCP_FIRMWARE_M4 }; + dev.hw = &hw_m4; + for (unsigned ext = 0; ext < 2; ext++) { + reset_t6041_26b123(ext); + node.compatible = ext ? "apple,t8132-dcpext" : "apple,t8132-dcp"; + node.uuid = "other"; + t8132_firmware_path = true; + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_M4); + t8132_firmware_path = false; + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); + } + + /* + * A T8132 dcpext handed over with the T8132 27.2 image (first the Mac + * mini's, J773g) runs the 27.2 table, whatever the firmware path and on + * any board: the selection is by processor and image. + */ + reset_t6041_26b123(true); + node.compatible = "apple,t8132-dcpext"; + node.uuid = APPLE_T8132_DCP_26B123_UUID; + assert(!apple_t6041_dcpext_v27_2(&node)); + for (unsigned path = 0; path < 2; path++) { + t8132_firmware_path = path; + assert(apple_t8132_dcpext_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_V_27_0); + } + t8132_firmware_path = false; + /* The internal DCP is never admitted: macOS parks it; aura hands it to nobody. */ + node.compatible = "apple,t8132-dcp"; + assert(!apple_t8132_dcpext_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); + /* The T6041 image, a missing or second UUID, and other releases are refused. */ + node.compatible = "apple,t8132-dcpext"; + node.uuid = APPLE_T6041_DCP_26B123_UUID; + assert(!apple_t8132_dcpext_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); + node.uuid = APPLE_T8132_DCP_26B123_UUID; + node.uuid_count = 0; assert(!apple_t8132_dcpext_v27_2(&node)); + node.uuid_count = 2; assert(!apple_t8132_dcpext_v27_2(&node)); + node.uuid_count = 1; + node.compat[1] = 0; assert(!apple_t8132_dcpext_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); + node.compat[1] = 2; node.fw[2] = 1; assert(!apple_t8132_dcpext_v27_2(&node)); + node.fw[2] = 0; assert(apple_t8132_dcpext_v27_2(&node)); + + /* + * The internal DCP handed over with the T8132 27.2 image and its + * firmware-27 clocks (the M4 Air's on the 27.2 stub) runs the 27.2 + * table on any board and either firmware path; without the clocks it is + * the M4 backend's on its path and nobody's off it, as above. + */ + reset_t6041_26b123(false); + node.compatible = "apple,t8132-dcp"; + node.uuid = APPLE_T8132_DCP_26B123_UUID; + node.clock_ids = true; + for (unsigned path = 0; path < 2; path++) { + t8132_firmware_path = path; + assert(apple_t8132_dcp_v27_2(&node)); + assert(!apple_t8132_dcpext_v27_2(&node)); + assert(!apple_t6041_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_V_27_0); + node.clock_ids = false; + assert(!apple_t8132_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == (path ? DCP_FIRMWARE_M4 : DCP_FIRMWARE_UNKNOWN)); + node.clock_ids = true; + } + t8132_firmware_path = true; + /* Not on a dcpext, nor with the T6041 image, a missing UUID or another release. */ + node.compatible = "apple,t8132-dcpext"; assert(!apple_t8132_dcp_v27_2(&node)); + node.compatible = "apple,t8132-dcp"; + node.uuid = APPLE_T6041_DCP_26B123_UUID; assert(!apple_t8132_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_M4); + node.uuid = APPLE_T8132_DCP_26B123_UUID; + node.uuid_count = 0; assert(!apple_t8132_dcp_v27_2(&node)); + node.uuid_count = 1; + node.compat[1] = 0; assert(!apple_t8132_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_M4); + node.compat[1] = 2; assert(apple_t8132_dcp_v27_2(&node)); + node.clock_ids = false; + + dev.hw = &hw; puts("PASS T6041 26B123 v27.2 internal/external admission, refusal controls, and desktop 26.x preservation"); - puts("PASS T8122 internal DCP on its 27.2 image alone runs the 27.2 table"); + puts("PASS T8122 internal DCP needs its 27.2 image for the 27.2 table"); + puts("PASS T8132 M4 backend only on its firmware path; a T8132 dcpext on the 27.2 image runs the 27.2 table on any board"); + puts("PASS T8132 internal DCP with the 27.2 image and its firmware-27 clocks runs the 27.2 table; without them nothing changes"); + puts("PASS T8132 internal DCP on the 27.2 image joins the DRM device on any board; off the M4 path nothing else does"); + return 0; +} +''' + + +def t8122_dcpext_v27_admission(root): + return _v27_prelude(root) + r''' +static struct device_node dcp, dcpext; +static const struct apple_dcp_hw_data hw; +static struct device dev = { .of_node = &dcpext, .hw = &hw }; + +static void set(u32 *v, u32 a, u32 b, u32 c) { v[0] = a; v[1] = b; v[2] = c; } + +/* 27.2 on the J615: the internal DCP on 26B123, the dcpext with no image UUID. */ +static void reset(void) +{ + dcp = (struct device_node){ + .compatible = "apple,t8122-dcp", .uuid = APPLE_T8122_DCP_26B123_UUID, + .uuid_count = 1, .fw = { 27, 2, 0 }, .fw_cells = 3, + .compat = { 27, 2, 0 }, .compat_cells = 3, + }; + dcpext = (struct device_node){ + .compatible = "apple,t8122-dcpext", .fw = { 27, 2, 0 }, .fw_cells = 3, + .compat = { 27, 2, 0 }, .compat_cells = 3, + }; + of_nodes[0] = &dcp; + of_nodes[1] = &dcpext; + ext26 = false; +} + +static void expect(bool v27_2, enum dcp_firmware_version want) +{ + assert(apple_t8122_dcpext_v27_2(&dcpext) == v27_2); + assert(dcp_check_firmware_version(&dev) == want); + assert(!of_node_refs); +} + +int main(void) +{ + assert(!apple_t8122_dcpext_v27_2(NULL)); + + reset(); + expect(true, DCP_FIRMWARE_V_27_0); + /* The internal DCP is not the external one. */ + assert(!apple_t8122_dcpext_v27_2(&dcp)); + assert(!of_node_refs); + /* An image UUID on the dcpext changes nothing. */ + dcpext.uuid = APPLE_T8122_DCP_26B123_UUID; dcpext.uuid_count = 1; + expect(true, DCP_FIRMWARE_V_27_0); + puts("PASS T8122 dcpext on 27.2 beside the 26B123 internal DCP runs the 27.2 table"); + + /* Only beside an internal DCP handed over on the 27.2 image. */ + reset(); dcp.uuid = APPLE_T6041_DCP_26B123_UUID; expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); dcp.uuid_count = 0; expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); set(dcp.fw, 14, 7, 0); set(dcp.compat, 14, 7, 0); expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); of_nodes[0] = NULL; expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); dcp.compatible = "apple,t6041-dcp"; expect(false, DCP_FIRMWARE_UNKNOWN); + /* Another SoC's dcpext is not it. */ + reset(); dcpext.compatible = "apple,t6041-dcpext"; + assert(!apple_t8122_dcpext_v27_2(&dcpext)); + assert(!of_node_refs); + puts("PASS T8122 dcpext 27.2 needs the internal DCP's 26B123 handoff"); + + /* Its own version and compatibility: both 27.2.0, three cells each. */ + reset(); set(dcpext.fw, 27, 0, 0); expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); set(dcpext.compat, 27, 0, 0); expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); set(dcpext.fw, 27, 2, 1); set(dcpext.compat, 27, 2, 1); + expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); dcpext.fw_cells = 0; expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); dcpext.compat_cells = 4; expect(false, DCP_FIRMWARE_UNKNOWN); + /* A 27.x refusal is terminal even if the legacy gate would admit it. */ + reset(); ext26 = true; dcp.uuid_count = 0; expect(false, DCP_FIRMWARE_UNKNOWN); + puts("PASS T8122 dcpext 27.2 refuses other or malformed versions"); + + /* The 14.7 template and the native 26.x path are as before. */ + reset(); set(dcpext.fw, 14, 7, 0); set(dcpext.compat, 14, 7, 0); + expect(false, DCP_FIRMWARE_V_14_7_TEMPLATE); + reset(); set(dcpext.fw, 26, 6, 2); set(dcpext.compat, 26, 6, 2); + expect(false, DCP_FIRMWARE_UNKNOWN); + ext26 = true; expect(false, DCP_FIRMWARE_H17P); + puts("PASS T8122 dcpext 14.7.0 keeps the template, native 26.x keeps H17P"); + return 0; +} +''' + + +def v27_tag_translation(root): + iomfb_h = (root / 'drivers/gpu/drm/apple/iomfb.h').read_text() + methods_decl = iomfb_h[iomfb_h.index('enum dcpep_method {'): + iomfb_h.index('#define IOMFB_MAX_CB')] + v27_c = (root / 'drivers/gpu/drm/apple/iomfb_v27.c').read_text() + v27_tables = v27_c[v27_c.index('static const struct dcp_method_entry dcp_methods_27_0'): + v27_c.index('/* The template\'s calls resolve through')] + dcp_c = (root / 'drivers/gpu/drm/apple/dcp.c').read_text() + transport = block(dcp_c, 'static bool dcp_v27_sleep_transport_supported(') + return r''' +#include +#include +#include +#include +#include +#include +#include +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define CONFIG_APPLE_SOC_SLEEP 1 +#define IS_ENABLED(option) (option) +#define GFP_KERNEL 0 +enum dcp_firmware_version { + DCP_FIRMWARE_UNKNOWN, + DCP_FIRMWARE_V_27_0, +}; +enum dcp_iomfb_method_profile { + DCP_IOMFB_METHODS_DEFAULT, + DCP_IOMFB_METHODS_H17G, +}; +struct device_node { const char *compatible; }; +struct device { struct device_node *of_node; }; +struct apple_dcp_hw_data { + bool adopt_live_session; + enum dcp_iomfb_method_profile iomfb_method_profile; +}; +struct apple_dcp { + struct device *dev; + struct apple_dcp_hw_data hw; + enum dcp_firmware_version fw_compat; + const struct dcp_method_entry *v27_methods; +}; +static int of_device_is_compatible(const struct device_node *np, const char *s) +{ + return np && np->compatible && !strcmp(np->compatible, s); +} +static void *devm_kmemdup(struct device *dev, const void *src, size_t len, unsigned int gfp) +{ + void *copy = malloc(len); + (void)dev; (void)gfp; + if (copy) + memcpy(copy, src, len); + return copy; +} +''' + methods_decl + '\n' + v27_tables + '\n' + transport + r''' +static void expect_tag(const struct dcp_method_entry *methods, const char *in, const char *want) +{ + char out[4] = { 'X', 'X', 'X', 'X' }; + assert(iomfb_v27_tag(methods, in, out) == 0); + assert(memcmp(out, want, 4) == 0); +} + +static void expect_tag_fail(const struct dcp_method_entry *methods, const char *in) +{ + char out[4] = { 'X', 'X', 'X', 'X' }; + assert(iomfb_v27_tag(methods, in, out) == -EOPNOTSUPP); + assert(memcmp(out, "XXXX", 4) == 0); +} + +int main(void) +{ + struct device_node node = { .compatible = "apple,t6050-dcp" }; + struct device dev = { .of_node = &node }; + const struct dcp_method_entry *m27_0 = iomfb_v27_methods("27.0.0"); + const struct dcp_method_entry *m27_2 = iomfb_v27_methods("27.2.0"); + const struct dcp_method_entry *m27_3 = iomfb_v27_methods("27.3.0"); + const struct dcp_method_entry *j714s = iomfb_v27_methods_j714s(&dev, m27_0); + struct dcp_method_entry partial_27_2[dcpep_num_methods]; + unsigned int missing_count; + + assert(m27_0 && m27_2 && m27_3 && j714s); + assert(!iomfb_v27_methods_renumbered(NULL)); + assert(!iomfb_v27_methods_renumbered(m27_0)); + assert(!iomfb_v27_methods_renumbered(j714s)); + assert(iomfb_v27_methods_renumbered(m27_2)); + assert(iomfb_v27_methods_renumbered(m27_3)); + + /* NULL table fails closed. */ + expect_tag_fail(NULL, "A411"); + assert(!iomfb_v27_sleep_methods_complete(NULL)); + + /* 27.0 and J714s copy keep 27.0 IDs unchanged. */ + expect_tag(m27_0, "A411", "A411"); + expect_tag(m27_0, "A484", "A484"); + expect_tag(m27_0, "A500", "A500"); + expect_tag(m27_0, "A442", "A442"); + expect_tag(m27_0, "A449", "A449"); + expect_tag(m27_0, "A115", "A115"); + expect_tag(m27_0, "A364", "A364"); + expect_tag(j714s, "A411", "A411"); + expect_tag(j714s, "A408", "A408"); + expect_tag(j714s, "A500", "A500"); + assert(iomfb_v27_sleep_methods_complete(m27_0)); + assert(iomfb_v27_sleep_methods_complete(j714s)); + assert(!iomfb_v27_missing_method(m27_0, &missing_count) && missing_count == 0); + + /* 27.2 translates every recorded shifted and unchanged paired/sleep tag. */ + const struct { const char *in, *out; } map_27_2[] = { + { "A406", "A456" }, { "A408", "A458" }, { "A411", "A461" }, { "A412", "A462" }, + { "A413", "A463" }, { "A414", "A464" }, { "A423", "A473" }, { "A428", "A478" }, + { "A442", "A492" }, { "A449", "A499" }, { "A450", "A500" }, { "A453", "A503" }, + { "A484", "A534" }, { "A487", "A537" }, { "A489", "A539" }, { "A500", "A550" }, + { "A115", "A115" }, + { "A360", "A360" }, { "A361", "A361" }, { "A362", "A362" }, { "A364", "A364" }, + { "A365", "A365" }, { "A366", "A366" }, { "A367", "A367" }, { "A368", "A368" }, + { "A369", "A369" }, { "A370", "A370" }, { "A371", "A371" }, { "A372", "A372" }, + { "A373", "A373" }, + }; + for (unsigned int i = 0; i < ARRAY_SIZE(map_27_2); i++) + expect_tag(m27_2, map_27_2[i].in, map_27_2[i].out); + assert(iomfb_v27_sleep_methods_complete(m27_2)); + assert(!iomfb_v27_missing_method(m27_2, &missing_count) && missing_count == 0); + + /* Unrecorded tags on 27.2 fail closed (no +50 arithmetic, no 27.0 fallback). */ + expect_tag_fail(m27_2, "A495"); + expect_tag_fail(m27_2, "A499"); + expect_tag_fail(m27_2, "A375"); + expect_tag_fail(m27_2, "A999"); + + /* Incomplete renumbered table (27.3) translates recorded entries and fails closed on missing ones. */ + expect_tag(m27_3, "A453", "A503"); + const char *missing_27_3[] = { + "A411", "A413", "A484", "A500", "A442", "A449", "A115", "A364", "A367", + }; + for (unsigned int i = 0; i < ARRAY_SIZE(missing_27_3); i++) + expect_tag_fail(m27_3, missing_27_3[i]); + assert(!iomfb_v27_sleep_methods_complete(m27_3)); + assert(iomfb_v27_missing_method(m27_3, &missing_count) && missing_count > 0); + + /* Dropping an optional sleep/paired entry does not block basic boot admission, + * but does mark sleep incomplete when a sleep entry is missing, and any table + * other than 27.0 or the J714s copy fails closed as renumbered. */ + memcpy(partial_27_2, m27_2, sizeof(partial_27_2)); + partial_27_2[dcpep_v27_wake_a442].tag[0] = '\0'; + assert(iomfb_v27_methods_renumbered(partial_27_2)); + expect_tag_fail(partial_27_2, "A442"); + assert(!iomfb_v27_missing_method(partial_27_2, &missing_count) && missing_count == 0); + assert(!iomfb_v27_sleep_methods_complete(partial_27_2)); + + struct dcp_method_entry future_27_x[dcpep_num_methods]; + memcpy(future_27_x, m27_0, sizeof(future_27_x)); + memcpy(future_27_x[dcpep_start_signal].tag, "A501", 4); + future_27_x[dcpep_v27_wake_a442].tag[0] = '\0'; + assert(iomfb_v27_methods_renumbered(future_27_x)); + expect_tag_fail(future_27_x, "A442"); + + /* + * Sleep transport admission keys on T6050 DCP/DCPEXT and table completeness. + * No of_machine_is_compatible() stub exists in this translation unit, enforcing + * at compile time that admission does not gate on a board model. + */ + struct apple_dcp dcp = { + .dev = &dev, + .hw = { .adopt_live_session = true, .iomfb_method_profile = DCP_IOMFB_METHODS_DEFAULT }, + .fw_compat = DCP_FIRMWARE_V_27_0, + }; + const char *t6050_compats[] = { "apple,t6050-dcp", "apple,t6050-dcpext" }; + for (unsigned int i = 0; i < ARRAY_SIZE(t6050_compats); i++) { + node.compatible = t6050_compats[i]; + dcp.v27_methods = m27_0; assert(dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = j714s; assert(dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = m27_2; assert(dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = m27_3; assert(!dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = partial_27_2; assert(!dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = NULL; assert(!dcp_v27_sleep_transport_supported(&dcp)); + } + dcp.v27_methods = m27_2; + node.compatible = "apple,t6041-dcp"; assert(!dcp_v27_sleep_transport_supported(&dcp)); + node.compatible = "apple,t6050-dcp"; + dcp.hw.adopt_live_session = false; assert(!dcp_v27_sleep_transport_supported(&dcp)); + dcp.hw.adopt_live_session = true; + dcp.hw.iomfb_method_profile = DCP_IOMFB_METHODS_H17G; assert(!dcp_v27_sleep_transport_supported(&dcp)); + dcp.hw.iomfb_method_profile = DCP_IOMFB_METHODS_DEFAULT; + dcp.fw_compat = DCP_FIRMWARE_UNKNOWN; assert(!dcp_v27_sleep_transport_supported(&dcp)); + + free((void *)j714s); + puts("PASS v27 tag translation fail-closed and table-driven sleep transport admission"); return 0; } ''' diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/common.py b/tools/testing/selftests/drivers/gpu/apple-dcp/common.py index 980a7a8773b97f..bbc356e02bef7c 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/common.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/common.py @@ -176,24 +176,41 @@ def atc_function(source, name): def atc_cio_helpers(source): - """The PIPE backend of a mode, which T8132 CIO keeps on the dummy one, and - whether a T8132 port is wired for DP alt mode. + """The PIPE backend of a mode, which T8132 CIO keeps on the dummy one, + whether a T8132 port is wired for DP alt mode, and the T8132 device-role + mode mapping. The mux and PIPE functions call these; older sources have none: ''. """ result = '' for name in ('atcphy_mode_is_cio', 'atcphy_pipe_state_for', - 'atcphy_usb2_sig_host', 'atcphy_t8132_dp_on'): + 'atcphy_usb2_sig_host', 'atcphy_t8132_dp_on', + 'atcphy_t8132_device_mode'): marker = re.search(r'^static [^;{}()]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M) if marker: helper = block(source, marker.start()) if name == 'atcphy_usb2_sig_host': helper = helper.replace('static u32', 'static __attribute__((unused)) u32', 1) + elif name == 'atcphy_t8132_device_mode': + helper = helper.replace('static enum atcphy_mode', + 'static __attribute__((unused)) enum atcphy_mode', 1) result += helper + '\n' return result +def atc_cfg_helpers(source): + """Where the power and reset block sits and which bit swaps the lanes, both of + which T8152 moves; the power-up, power-down and lane functions call these. + + Marked unused, as a unit may extract only some of their callers. Older + sources have neither: ''. + """ + return ''.join(atc_function(source, name).replace( + 'static inline ', 'static inline __attribute__((unused)) ', 1) + for name in ('atcphy_cfg', 'atcphy_lane_swap')) + + def atc_restore_helpers(source): """What atcphy_restore_after_pd_off() needs beyond the parking helpers. @@ -223,6 +240,18 @@ def atc_mux_noop(source): return ''.join(atc_function(source, name) for name in ('atcphy_mux_in_mode', 'atcphy_mux_is_noop')) +def atc_set_mode_prototypes(source): + """Prototype atcphy_usb3_set_mode() needs ahead of the mux. + + It moves a T8132 device role to USB2 and restores SuperSpeed on a host swap + through atcphy_mux_switch(), which atc_mux_without_pm() emits with the mux, + after the role functions in some fixtures. + """ + if 'atcphy_mux_switch(' not in block(source, 'static int atcphy_usb3_set_mode('): + return '' + return 'static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode target_mode);\n' + + def atc_mux_without_pm(source): """Lane/teardown fixtures omit USB PM, keeping mode mapping and lane work real. diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/desktop.py b/tools/testing/selftests/drivers/gpu/apple-dcp/desktop.py index 1eb7f35674986c..a1d6f8f50294cd 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/desktop.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/desktop.py @@ -242,7 +242,7 @@ def brightness_takeover(root): struct backlight_properties {int type,brightness,max_brightness,scale,state;}; struct backlight_device {struct backlight_properties props;void *data;bool ops_lock;}; struct apple_dcp { - int fw_compat;bool quiescing; + int fw_compat;bool quiescing,crashed; struct {int iomfb_method_profile;} hw; struct {u32 maximum,nits,dac;bool update;struct backlight_device *bl_dev; u32 level,fade_from,fade_to;bool fading;unsigned long fade_start;int fade_work; @@ -351,6 +351,17 @@ def brightness_takeover(root): assert(dcp_get_brightness(&dac_bl)==0); dcp_backlight_presented(&dac,500); assert(dcp_get_brightness(&dac_bl)==500 && !dac.backlight.lock); + /* + * A crashed processor discards every present: no level is reported, and + * a new level is refused without changing the requested one. + */ + struct dcp_backlight_state before=d.backlight.state; + d.crashed=true;registered.props.brightness=200; + assert(dcp_get_brightness(®istered)==-EIO); + assert(dcp_set_brightness(®istered)==-EIO); + assert(!memcmp(&before,&d.backlight.state,sizeof(before)) && !d.backlight.lock); + d.crashed=false; + assert(!dcp_set_brightness(®istered) && d.backlight.state.target==200); return 0; } ''' @@ -441,6 +452,8 @@ def panel_identity(root, output=None): }; static unsigned notifications; static bool dcp_has_panel(struct apple_dcp *d) {return d->has_panel;} +/* 27 stands for DCP_FIRMWARE_V_27_0 here: its panel path has no PQ decode. */ +static bool dcp_fw_panel_decodes_pq(struct apple_dcp *d) {return d->fw_compat != 27;} static void dcp_queue_hotplug(void *con) {assert(con);notifications++;} ''' + helpers + dictionary + '\nstatic const u8 attributes[]={'+','.join(map(str,raw))+'};\n' + 'static const u8 product[]={'+','.join(map(str,product))+'};\n' + 'static const u8 minimal[]={'+','.join(map(str,minimal))+'};\n' + r''' int main(int argc, char **argv) @@ -468,6 +481,12 @@ def panel_identity(root, output=None): assert(!IS_ERR(hdr) && drm_edid_valid(hdr) && hdr->size==256); assert(!memcmp(hdr->cta,"\x02\x03\x0f\x00\xe3\x05\x80\x00\xe6\x06\x05\x01\xa0\xa0\x00",15)); drm_edid_free(hdr); + /* Firmware 27: no PQ decode, so no HDR block even with a peak. */ + d.fw_compat=27; + const struct drm_edid *nopq=dcp_panel_edid_snapshot(&d,modes,3,&generation); + assert(!IS_ERR(nopq) && drm_edid_valid(nopq) && nopq->size==128); + drm_edid_free(nopq); + d.fw_compat=5; d.panel.peak_nits=0; const struct drm_edid *fallback=dcp_panel_edid_snapshot(&d,modes,3,&generation); assert(!IS_ERR(fallback) && drm_edid_valid(fallback) && fallback->size==128); diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py index dc3a99fcaf6cae..e385105e186f53 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py @@ -475,7 +475,7 @@ def watchdog(root): struct work_struct {unsigned unused;}; struct delayed_work {struct work_struct work;}; struct apple_dcp { - int fw_compat;bool vrr_enabled,typec; + int fw_compat;bool vrr_enabled,typec,panel; struct {u32 present_id;bool present_pending,vrr_failed,takeover_adopted,mode_live;} *desktop; struct {bool valid;} mode_state; struct delayed_work swap_watchdog_wq; @@ -494,12 +494,13 @@ def watchdog(root): static void dcp_drm_crtc_vblank(void *c) {vblanks++;} static void dcp_queue_hotplug(void *c) {hotplugs++;} static bool dcp_is_typec_output(struct apple_dcp *d) {return d->typec;} +static bool dcp_has_panel(struct apple_dcp *d) {return d->panel;} static void mod_delayed_work(void *q,struct delayed_work *w,unsigned long delay) {assert(delay==1000);scheduled++;} static void cancel_delayed_work(struct delayed_work *w) {cancelled++;} ''' + definitions + '\n' + helpers + '\n' + production + r''' int main(void) { - struct apple_dcp d={.fw_compat=5,.vrr_enabled=true,.mode_state={true},.connector=(void *)1}; + struct apple_dcp d={.fw_compat=5,.vrr_enabled=true,.panel=true,.mode_state={true},.connector=(void *)1}; __typeof__(*d.desktop) state={.present_id=42,.present_pending=true};d.desktop=&state; dcp_swap_watchdog_arm(&d);assert(scheduled==1 && d.swap_watchdog_deadline==1000); jiffies=999;dcp_swap_watchdog(&d.swap_watchdog_wq.work); @@ -535,6 +536,11 @@ def watchdog(root): jiffies=d.swap_watchdog_deadline;unsigned hp=hotplugs; dcp_swap_watchdog(&d.swap_watchdog_wq.work); assert(!state.takeover_adopted && !state.mode_live && !d.mode_state.valid && hotplugs==hp+1); + /* Any external pipe is watched, not only Type-C: a fixed HDMI port + * (no panel, no Type-C route, no watched desktop swap) arms too. */ + d.fw_compat=1;d.typec=false;d.vrr_enabled=false;state.takeover_adopted=false; + before=scheduled;dcp_swap_watchdog_arm(&d);assert(scheduled==before); + d.panel=false;dcp_swap_watchdog_arm(&d);assert(scheduled==before+1); return 0; } ''' @@ -598,8 +604,10 @@ def brightness_commit(root): def hdr_metadata(root): - """HDR10 static metadata message for DCPAV selector 0x15, byte for byte.""" - header = (root / 'drivers/gpu/drm/apple/dcp-hdr-metadata.h').read_text() + """HDR10 metadata wire encoding and caching over the AV service (legacy and AFKv2).""" + apple = root / 'drivers/gpu/drm/apple' + header = (apple / 'dcp-hdr-metadata.h').read_text() + iomfb = (apple / 'iomfb.c').read_text() header = '\n'.join(line for line in header.splitlines() if not line.startswith('#include')) header = header.replace('static inline ', 'static inline __attribute__((unused)) ') @@ -655,6 +663,161 @@ def pad(raw): union { struct hdr_metadata_infoframe hdmi_metadata_type1; }; }; """ + header + r""" +typedef uint64_t u64; +#define HDMI_EOTF_TRADITIONAL_GAMMA_SDR 0 +#define HDMI_EOTF_SMPTE_ST2084 2 +#define EPIC_SUBTYPE_STD_SERVICE 0xc0 +#define READ_ONCE(x) (x) +#define scoped_guard(kind, lock) for (bool held = true; held; held = false) +#define lockdep_assert_held(lock) ((void)0) +#define dev_warn_ratelimited(...) ((void)0) +#define dev_warn(...) ((void)0) +#define dev_dbg(...) ((void)0) +struct apple_dcp_afkep { bool wire_v2; }; +struct apple_epic_service { struct apple_dcp_afkep *ep; unsigned int refs; }; +struct drm_crtc { int dcp; }; +struct drm_atomic_commit { int unused; }; +struct drm_connector_state { + struct { size_t length; const void *data; } *hdr_output_metadata; +}; +struct apple_dcp { + bool output_pq, output_hdr, crashed; + struct { + struct apple_epic_service *service; + u64 generation; + u8 sent[DCP_HDR_DATA_SIZE]; + bool sent_valid, infoframe; + } hdr; +}; +#define to_apple_crtc(crtc) (crtc) +#define dcp_hdr_metadata_live(pdev) true +static const struct drm_connector_state *test_connector; +static int transport_result; +static u32 dcp_status; +static size_t reply_length; +static unsigned int sends, v2_sends, legacy_sends, stop_sends; +static bool reset_during_send; +static struct apple_dcp test_dcp; +static const struct drm_connector_state *dcp_crtc_connector_state( + struct apple_dcp *dcp, struct drm_crtc *crtc, struct drm_atomic_commit *commit) +{ + (void)dcp; (void)crtc; (void)commit; + return test_connector; +} +static struct apple_epic_service *afk_service_get(struct apple_epic_service *service) +{ + if (service) + service->refs++; + return service; +} +static void afk_service_put(struct apple_epic_service *service) +{ + assert(service->refs == 1); + service->refs--; +} +""" + block(iomfb, 'static void dcp_hdr_reset_locked(') + r""" +static int mock_hdr_command(struct apple_epic_service *service, u8 type, + const void *msg, size_t msg_len, void *reply, size_t capacity, u32 *retcode, size_t *received) +{ + u32 selector = get_unaligned_le32((const u8 *)msg + 0x04); + + assert(service->refs == 1 && type == EPIC_SUBTYPE_STD_SERVICE); + if (selector == DCP_HDR_SELECTOR_SET_STATIC) { + assert(msg_len == DCP_HDR_MSG_SIZE && capacity == DCP_HDR_MSG_SIZE); + sends++; + } else { + assert(selector == DCP_HDR_SELECTOR_STOP_INFOFRAME); + assert(msg_len == DCP_HDR_STOP_SIZE && capacity == DCP_HDR_STOP_SIZE); + stop_sends++; + } + if (reset_during_send) + dcp_hdr_reset_locked(&test_dcp); + if (transport_result) + return transport_result; + *retcode = 0; + *received = reply_length; + if (selector == DCP_HDR_SELECTOR_SET_STATIC) + put_unaligned_le32(dcp_status, (u8 *)reply + DCP_HDR_MSG_STATUS); + else + put_unaligned_le32(dcp_status, (u8 *)reply + DCP_HDR_STOP_STATUS); + return 0; +} +static int afk_send_command_len(struct apple_epic_service *service, u8 type, + const void *msg, size_t msg_len, void *reply, size_t capacity, u32 *retcode, size_t *received) +{ + assert(service->ep->wire_v2); + v2_sends++; + return mock_hdr_command(service, type, msg, msg_len, reply, capacity, retcode, received); +} +static int afk_send_command_with_reply_len(struct apple_epic_service *service, u8 type, + const void *msg, size_t msg_len, void *reply, size_t capacity, u32 *retcode, size_t *received) +{ + assert(!service->ep->wire_v2); + legacy_sends++; + return mock_hdr_command(service, type, msg, msg_len, reply, capacity, retcode, received); +} +""" + block(iomfb, 'static int dcp_hdr_send(') + block(iomfb, 'static void dcp_hdr_infoframe_stop(') + block(iomfb, 'static void dcp_hdr_metadata_sync(') + r""" +static void test_metadata_cache(struct hdr_output_metadata hdr) +{ + struct apple_dcp_afkep ep = { .wire_v2 = false }; + struct apple_epic_service service = { .ep = &ep }; + struct drm_crtc crtc = {}; + struct drm_atomic_commit commit = {}; + struct drm_connector_state conn; + __typeof__(*conn.hdr_output_metadata) blob = { sizeof(hdr), &hdr }; + + conn.hdr_output_metadata = &blob; + test_connector = &conn; + test_dcp.output_pq = true; + test_dcp.output_hdr = true; + test_dcp.hdr.service = &service; + reply_length = DCP_HDR_MSG_SIZE; + transport_result = -EIO; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 1 && legacy_sends == 1 && !v2_sends && !test_dcp.hdr.sent_valid && !test_dcp.hdr.infoframe); + transport_result = 0; + reply_length = DCP_HDR_MSG_STATUS; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 2 && !test_dcp.hdr.sent_valid); + + reply_length = DCP_HDR_MSG_SIZE; + reset_during_send = true; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 3 && !test_dcp.hdr.sent_valid && !test_dcp.hdr.infoframe); + reset_during_send = false; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 4 && test_dcp.hdr.sent_valid && test_dcp.hdr.infoframe); + + dcp_hdr_reset_locked(&test_dcp); + dcp_status = 1; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 5 && test_dcp.hdr.sent_valid && !test_dcp.hdr.infoframe); + hdr.hdmi_metadata_type1.max_cll--; + dcp_status = 0; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 6 && test_dcp.hdr.infoframe && !service.refs); + hdr.hdmi_metadata_type1.max_cll++; + transport_result = -ETIMEDOUT; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 7 && !test_dcp.hdr.sent_valid && test_dcp.hdr.infoframe); + hdr.hdmi_metadata_type1.max_cll--; + transport_result = 0; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 8 && test_dcp.hdr.sent_valid && !service.refs); + + /* AFKv2 transport (fw 27 / H17P) uses afk_send_command_len for 0x15 and 0x14. */ + ep.wire_v2 = true; + dcp_hdr_reset_locked(&test_dcp); + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 9 && v2_sends == 1 && test_dcp.hdr.sent_valid && test_dcp.hdr.infoframe); + reply_length = DCP_HDR_STOP_SIZE; + dcp_hdr_infoframe_stop(&test_dcp); + assert(stop_sends == 1 && v2_sends == 2 && !test_dcp.hdr.infoframe && !service.refs); + puts("PASS: retry transport and short replies, discard stale replies, deduplicate completed commands, AFKv2 0x15/0x14"); +} + static const u8 expected[] = {""" + expected + r"""}; static const u8 expected_stop[] = {""" + expected_stop + r"""}; int main(void) @@ -675,6 +838,7 @@ def pad(raw): fprintf(stderr, "byte %#zx: %#x, expected %#x\n", i, msg[i], expected[i]); return 1; } + test_metadata_cache(hdr); /* Only static metadata Type 1 is sent. */ hdr.metadata_type = 1; assert(dcp_hdr_data(data, &hdr) == -EINVAL); @@ -709,3 +873,215 @@ def pad(raw): return 0; } """ + + +def color_selection(root): + """Full colour mode selection across RGB/YCbCr 444/422/420, 8/10/12 bpc, range, gamut, PQ/HLG.""" + apple = root / 'drivers/gpu/drm/apple' + parser_h = (apple / 'parser.h').read_text() + color_h = (apple / 'dcp-color.h').read_text() + # Extract enum + struct definitions from parser.h + p_start = parser_h.index('enum dcp_color_eotf {') + p_end = parser_h.index('struct dimension {') + parser_defs = parser_h[p_start:p_end] + color_defs = '\n'.join(line for line in color_h.splitlines() + if not line.startswith('#include')) + color_defs = color_defs.replace('static inline ', 'static inline __attribute__((unused)) ') + return r""" +#include +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; +typedef uint64_t u64; typedef int64_t s64; +struct drm_display_mode { int unused; }; +struct dcp_metadata_ticket { int unused; }; +enum hdmi_eotf { + HDMI_EOTF_TRADITIONAL_GAMMA_SDR = 0, + HDMI_EOTF_TRADITIONAL_GAMMA_HDR = 1, + HDMI_EOTF_SMPTE_ST2084 = 2, + HDMI_EOTF_BT_2100_HLG = 3, +}; +enum drm_colorspace { + DRM_MODE_COLORIMETRY_DEFAULT = 0, + DRM_MODE_COLORIMETRY_SMPTE_170M_YCC = 1, + DRM_MODE_COLORIMETRY_BT709_YCC = 2, + DRM_MODE_COLORIMETRY_XVYCC_601 = 3, + DRM_MODE_COLORIMETRY_XVYCC_709 = 4, + DRM_MODE_COLORIMETRY_SYCC_601 = 5, + DRM_MODE_COLORIMETRY_OPYCC_601 = 6, + DRM_MODE_COLORIMETRY_OPRGB = 7, + DRM_MODE_COLORIMETRY_BT2020_CYCC = 8, + DRM_MODE_COLORIMETRY_BT2020_RGB = 9, + DRM_MODE_COLORIMETRY_BT2020_YCC = 10, + DRM_MODE_COLORIMETRY_DCI_P3_RGB_D65 = 11, + DRM_MODE_COLORIMETRY_DCI_P3_RGB_THEATER = 12, + DRM_MODE_COLORIMETRY_RGB_WIDE_FIXED = 13, + DRM_MODE_COLORIMETRY_RGB_WIDE_FLOAT = 14, + DRM_MODE_COLORIMETRY_BT601_YCC = 15, +}; +enum drm_connector_color_format { + DRM_CONNECTOR_COLOR_FORMAT_AUTO = 0, + DRM_CONNECTOR_COLOR_FORMAT_RGB444 = 1, + DRM_CONNECTOR_COLOR_FORMAT_YCBCR444 = 2, + DRM_CONNECTOR_COLOR_FORMAT_YCBCR422 = 3, + DRM_CONNECTOR_COLOR_FORMAT_YCBCR420 = 4, +}; +enum drm_hdmi_broadcast_rgb { + DRM_HDMI_BROADCAST_RGB_AUTO = 0, + DRM_HDMI_BROADCAST_RGB_FULL = 1, + DRM_HDMI_BROADCAST_RGB_LIMITED = 2, +}; +""" + parser_defs + color_defs + r""" +static void add_entry(struct dcp_display_mode *m, u32 id, u8 eotf, u8 fmt, + u8 space, u8 range, u8 depth, u8 flags) +{ + assert(m->nr_colors < DCP_MAX_COLOR_ENTRIES); + m->colors[m->nr_colors++] = (struct dcp_color_entry) { + .id = id, .eotf = eotf, .format = fmt, .colorimetry = space, + .range = range, .depth = depth, .flags = flags, + }; +} + +int main(void) +{ + struct dcp_display_mode acer = { .sdr_rgb = { .score = 100, .id = 81, .eotf = DCP_EOTF_SDR_GAMMA, + .format = DCP_COLOR_FORMAT_RGB, .colorimetry = DCP_COLORIMETRY_SRGB, + .range = DCP_COLOR_YCBCR_RANGE_FULL, .depth = 8 }, + .pq = { .score = 200, .id = 113, .eotf = DCP_EOTF_ST_2084, + .format = DCP_COLOR_FORMAT_RGB, .colorimetry = DCP_COLORIMETRY_BT2020_RGB, + .range = DCP_COLOR_YCBCR_RANGE_FULL, .depth = 10 }, + .color_mode_id = 81 }; + struct dcp_color_request req; + struct dcp_color_mode out; + + /* Populate Acer 1080p60-shaped catalog (enc 3 = YCbCr444, enc 2 = YCbCr422) */ + add_entry(&acer, 81, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_FULL, 8, 0); + add_entry(&acer, 82, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); + add_entry(&acer, 86, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, 0); + add_entry(&acer, 85, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, 0); + add_entry(&acer, 84, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT709, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); + add_entry(&acer, 83, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT601, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); + add_entry(&acer, 90, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT709, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); + add_entry(&acer, 108, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); + add_entry(&acer, 110, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422_DP, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); + add_entry(&acer, 113, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, 0); + add_entry(&acer, 114, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); + add_entry(&acer, 116, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); + add_entry(&acer, 117, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 12, 0); + add_entry(&acer, 120, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); + add_entry(&acer, 121, DCP_EOTF_BT_2100, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); + add_entry(&acer, 122, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR420, DCP_COLORIMETRY_BT709, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); + + /* Default SDR fast path */ + req = (struct dcp_color_request){ .allow_hdr = true, .allow_dsc = true, .max_bpc = 12 }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 81); + + /* Default PQ fast path (Mutter sets BT2020_RGB + PQ) */ + req.eotf = HDMI_EOTF_SMPTE_ST2084; req.colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 113 && out.depth == 10); + + /* Explicit 12 bpc PQ RGB vs 10 bpc PQ RGB vs Limited range */ + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_RGB444; req.max_bpc = 12; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 117 && out.depth == 12); + req.max_bpc = 10; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 113 && out.depth == 10); + req.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_LIMITED; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 114 && out.range == DCP_COLOR_YCBCR_RANGE_LIMITED); + + /* Explicit YCbCr 4:4:4 (10b/12b) and 4:2:2 (plain outranks DP tunnel) PQ */ + req = (struct dcp_color_request){ .eotf = HDMI_EOTF_SMPTE_ST2084, .colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC, + .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR444, .max_bpc = 10, .allow_hdr = true }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 116 && out.depth == 10); + req.max_bpc = 12; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 120 && out.depth == 12); + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422; req.max_bpc = 12; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 108); /* plain 422 outranks 422_DP (110) */ + + /* HLG support */ + req = (struct dcp_color_request){ .eotf = HDMI_EOTF_BT_2100_HLG, .colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC, + .max_bpc = 12, .allow_hdr = true }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 121); + + /* SDR: RGB 8b Limited, RGB 10b wide-gamut BT.2020, YCbCr 4:4:4 BT.709/BT.601, YCbCr 4:2:0 */ + req = (struct dcp_color_request){ .broadcast_rgb = DRM_HDMI_BROADCAST_RGB_LIMITED, .max_bpc = 8 }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 82); + req = (struct dcp_color_request){ .colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB, .max_bpc = 10 }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 85); + req = (struct dcp_color_request){ .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR444, + .colorspace = DRM_MODE_COLORIMETRY_BT709_YCC, .max_bpc = 10 }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 90); + req.colorspace = DRM_MODE_COLORIMETRY_SMPTE_170M_YCC; req.max_bpc = 8; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 83); + req = (struct dcp_color_request){ .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR420, .max_bpc = 8 }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 122); + + /* MSI 1440p60-shaped timing: PQ RGB/444 unsafe, PQ 422 safe -> Mutter AUTO BT2020_RGB succeeds via 422 (105) */ + struct dcp_display_mode msi = { .sdr_rgb = acer.sdr_rgb, + .pq = { .score = 10, .id = 105, .eotf = DCP_EOTF_ST_2084, + .format = DCP_COLOR_FORMAT_YCBCR422, .colorimetry = DCP_COLORIMETRY_BT2020_YCC, + .range = DCP_COLOR_YCBCR_RANGE_LIMITED, .depth = 12 }, + .color_mode_id = 81 }; + add_entry(&msi, 105, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); + add_entry(&msi, 107, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422_DP, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); + add_entry(&msi, 113, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, DCP_COLOR_FLAG_UNSAFE); + req = (struct dcp_color_request){ .eotf = HDMI_EOTF_SMPTE_ST2084, .colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB, + .max_bpc = 12, .allow_hdr = true }; + assert(!dcp_select_color_mode(&msi, &req, &out) && out.id == 105); + /* Explicit PQ RGB on MSI 1440p60 MUST be rejected (only unsafe RGB exists) */ + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_RGB444; + assert(dcp_select_color_mode(&msi, &req, &out) == -EINVAL); + /* Explicit PQ 4:2:2 on MSI 1440p60 picks plain 4:2:2 (105) over DP tunnel (107) */ + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422; req.colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC; + assert(!dcp_select_color_mode(&msi, &req, &out) && out.id == 105); + + /* Unsafe-only >340 MHz HDMI 2.0 timing (e.g. 1080p180 / 1440p144): SDR already uses unsafe + * elements (sdr_usable=false, sdr_unsafe=true), so non-DSC unsafe PQ within sdr_unsafe_max_bpp + * is permitted, whereas safe timings (sdr_usable=true) strictly reject unsafe SDR and PQ. */ + struct dcp_display_mode msi144 = { .sdr_rgb = acer.sdr_rgb, .color_mode_id = 80, + .sdr_usable = false, .sdr_unsafe = true, .sdr_unsafe_max_bpp = 24, + .pq = { .score = 10, .id = 105, .eotf = DCP_EOTF_ST_2084, + .format = DCP_COLOR_FORMAT_YCBCR422, .colorimetry = DCP_COLORIMETRY_BT2020_YCC, + .range = DCP_COLOR_YCBCR_RANGE_LIMITED, .depth = 12 } }; + add_entry(&msi144, 80, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_FULL, 8, DCP_COLOR_FLAG_UNSAFE); + add_entry(&msi144, 113, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, DCP_COLOR_FLAG_UNSAFE | DCP_COLOR_FLAG_DSC); + add_entry(&msi144, 114, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, DCP_COLOR_FLAG_UNSAFE); + add_entry(&msi144, 105, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, DCP_COLOR_FLAG_UNSAFE); + req = (struct dcp_color_request){ .eotf = HDMI_EOTF_SMPTE_ST2084, .colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC, + .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422, .max_bpc = 12, + .allow_hdr = true, .allow_dsc = true, .allow_unsafe_sdr = true }; + assert(!dcp_select_color_mode(&msi144, &req, &out) && out.id == 105); + /* Non-DSC 30-bpp RGB PQ (114) exceeds 24-bpp unsafe SDR ceiling -> rejected; 30-bpp SDR admits it */ + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_RGB444; + req.colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB; + assert(dcp_select_color_mode(&msi144, &req, &out) == -EINVAL); + msi144.sdr_unsafe_max_bpp = 30; + assert(!dcp_select_color_mode(&msi144, &req, &out) && out.id == 114); + msi144.sdr_unsafe_max_bpp = 24; + /* DSC-required unsafe PQ (113) MUST be rejected even with allow_dsc=true and 30-bpp SDR */ + msi144.colors[2].flags |= DCP_COLOR_FLAG_DSC; + msi144.sdr_unsafe_max_bpp = 30; + assert(dcp_select_color_mode(&msi144, &req, &out) == -EINVAL); + /* Same unsafe entry on a timing with sdr_usable=true MUST be rejected (for both HDR and SDR) */ + msi144.sdr_usable = true; + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422; + req.colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC; + assert(dcp_select_color_mode(&msi144, &req, &out) == -EINVAL); + /* Explicit SDR request on a safe timing (e.g. 4K60 where only 4:2:0 is safe) MUST NOT fall through to unsafe SDR */ + struct dcp_display_mode k4 = { .color_mode_id = 119, .sdr_usable = true, .sdr_unsafe = true }; + add_entry(&k4, 80, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_FULL, 8, DCP_COLOR_FLAG_UNSAFE); + add_entry(&k4, 119, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT709, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, DCP_COLOR_FLAG_DOWNSTREAM_420); + req = (struct dcp_color_request){ .color_format = DRM_CONNECTOR_COLOR_FORMAT_RGB444, .max_bpc = 8, .allow_unsafe_sdr = true }; + assert(dcp_select_color_mode(&k4, &req, &out) == -EINVAL); + /* DownstreamFormat 4:2:0 matches YCBCR420 and reports wire YCbCr 4:2:0 while preserving upstream format */ + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR420; + assert(!dcp_select_color_mode(&k4, &req, &out) && out.id == 119 && out.format == DCP_COLOR_FORMAT_YCBCR420); + assert(k4.colors[1].format == DCP_COLOR_FORMAT_YCBCR444); + + puts("PASS: colour mode selection across RGB/YCbCr 444/422/420, 8/10/12 bpc, Full/Limited, wide gamut, PQ/HLG, and -EINVAL rejection"); + return 0; +} +""" diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c index cc3197c1b738a1..2d17d6ffe8e963 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c @@ -2,8 +2,8 @@ /* This fixture selects the original controller layout, not T8132. */ #define of_device_is_compatible(...) false struct apple_atcphy { - /* T8132-only paths are covered by drivers/apple/atc-t8132-usb3.py. */ - bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; + /* T8132-only paths are covered by drivers/apple/atc-t8132-usb3.py. */ + bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt, t8132_device; /* A CIO sleep is T8132's too, covered by tools/asahi/atc-cio-sleep-tests.py. */ struct { bool prepared; @@ -25,7 +25,7 @@ struct apple_atcphy { bool aux, pll; unsigned int pairs, rate; } dp_t8122; - bool fixed_usb2, host_active, mode_dirty, ss_tunables, dp_tunables, + bool fixed_usb2, fixed_usb3, cio_only, host_active, mode_dirty, ss_tunables, dp_tunables, aux_power_requested; unsigned int dp_owned_pmas, dp_idle_pmas; unsigned int dp_usb_context_valid, dp_usb_context_dirty; @@ -252,11 +252,15 @@ static void atcphy_restore_after_pd_off(struct apple_atcphy *p); static int atcphy_power_off(struct apple_atcphy *p); static int atcphy_configure(struct apple_atcphy *p, enum atcphy_mode mode); -/* These units exercise older PHY generations. Never accept a T8132 dispatch. */ +/* These units exercise older PHY generations. Never accept a T8132 or T8152 dispatch. */ static int __attribute__((unused)) atcphy_configure_t8132(struct apple_atcphy *p, enum atcphy_mode mode) { (void)p; (void)mode; assert(false); return -EOPNOTSUPP; } static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *p) { (void)p; assert(false); return -EOPNOTSUPP; } +static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); return -EOPNOTSUPP; } +static void __attribute__((unused)) atcphy_lanes_down_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); } /* Model the USB2 power-on boundary's running state. */ @@ -401,6 +405,12 @@ static int dwc3_host_init(struct dwc3 *d) } return host_init_error; } + +/* The xHCI start and its USB3 routing; atc-t8132-usb3 models them. */ +static int dwc3_apple_host_start(struct dwc3_apple *a) +{ + return dwc3_host_init(&a->dwc); +} static int dwc3_gadget_init(struct dwc3 *d) { (void)d; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/prefix.c b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/prefix.c index 8c0bfb426e8a05..d3b53b188e7a00 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/prefix.c +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/prefix.c @@ -28,8 +28,10 @@ static void warning(const char *message) generic_warnings++; } #define dev_warn(d, message, ...) warning(message) +#define dev_info(...) ((void)0) #define dev_err(...) ((void)0) #define dev_dbg(...) ((void)0) +#define dev_info(...) ((void)0) #define lockdep_assert_held(p) assert(*(p)) #define WARN_ON_ONCE(v) assert(!(v)) static void mutex_lock(int *m) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index 7b4df18396a6e5..021f328f0ea614 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -85,7 +85,7 @@ def function(file,signature): struct apple_dcp;struct apple_dcp_afkep;struct apple_epic_service; void afk_service_retry(struct apple_dcp_afkep *ep); /* open_later: a firmware 27 panel service that sends its own OPEN; none is here. */ -struct apple_epic_service_ops { char name[32];bool reusable,optional,open_later;void (*init)(struct apple_epic_service *,const char *,const char *,s64);int (*prepare)(struct apple_epic_service *,const char *,const char *,s64);int (*revalidate)(struct apple_epic_service *,const char *,const char *,s64);void (*init_props)(struct apple_epic_service *,s64,const void *,size_t);void (*teardown)(struct apple_epic_service *); }; +struct apple_epic_service_ops { char name[32];bool reusable,optional,open_later,singleton;void (*init)(struct apple_epic_service *,const char *,const char *,s64);int (*prepare)(struct apple_epic_service *,const char *,const char *,s64);int (*revalidate)(struct apple_epic_service *,const char *,const char *,s64);void (*init_props)(struct apple_epic_service *,s64,const void *,size_t);void (*teardown)(struct apple_epic_service *); }; struct epic_cmd_info { u16 tag;u8 type;size_t reply_length,reply_len;bool reply_len_valid;void *rxbuf,*txbuf;dma_addr_t rxbuf_dma,txbuf_dma;size_t rxlen,txlen;u32 retcode;bool done,free_on_ack;int *completion; }; struct apple_epic_service { struct apple_dcp_afkep *ep;const struct apple_epic_service_ops *ops; @@ -95,12 +95,14 @@ def function(file,signature): bool pending_open;const char *pending_name,*pending_class;s64 pending_unit; }; /* v27_closed_teardown: set only by a J714s firmware 27 sleep. */ -struct apple_dcp_afkep { u8 *command_tags;bool lock,stopping;void *wq;struct work_struct service_work;struct apple_dcp *dcp;const struct apple_epic_service_ops *ops;bool wire_v2,inline_v2,match_epic_name,v27_closed_teardown;u32 endpoint;unsigned int num_channels;struct apple_epic_service services[AFK_MAX_CHANNEL]; }; +struct apple_dcp_afkep { u8 *command_tags;bool lock,stopping;void *wq;struct work_struct service_work;struct apple_dcp *dcp;const struct apple_epic_service_ops *ops,*unmatched_ops;bool wire_v2,inline_v2,match_epic_name,v27_closed_teardown;u32 endpoint;unsigned int num_channels;int service_wq;struct apple_epic_service services[AFK_MAX_CHANNEL]; }; +#define wake_up_all(q) ((void)(q)) struct apple_connector { void *dcp;bool connected,edid_invalidation_pending;struct { int registration_state; } base;unsigned int hotplug_wq; }; struct apple_dcp { void *dev;int fw_compat;struct apple_dcp_afkep *dcpavservep;struct apple_connector *connector; + void *desktop; bool external_physically_absent,hpd_mutex,quiescing,typec_cable_connected;u64 typec_generation;unsigned int nr_modes; - struct { int iomfb_method_profile,firmware_compat; bool fw_14_7_endpoints; unsigned int num_dptx_ports; } hw; bool ext_dead,external_native; + struct { int iomfb_method_profile,firmware_compat; bool fw_14_7_endpoints,afk_announced_names; unsigned int num_dptx_ports; unsigned char dptx_endpoint; } hw; bool ext_dead,external_native; struct { bool lock,enabled;u64 epoch;int enable_completion;struct apple_epic_service *service,*opened; u64 opened_epoch,close_gen,terminated_epoch,close_epoch;bool opening;struct work_struct close_wq; } dcpavserv; /* A J714s firmware 27 processor's: this one is not. */ @@ -108,9 +110,13 @@ def function(file,signature): /* Not a dcpext: none of these scenarios is an external processor. */ bool dcpext; }; +#define DPTX_ENDPOINT_V2 0x2c '''+internal_inline(root,'dcp_fw_is_14_7')+internal_inline(root,'dcp_is_v14_7_external')+internal_inline(root,'dcp_is_v27_external')+r'''struct epic_cmd { u32 retcode;u64 rxbuf,txbuf;u32 rxlen,txlen; }; static unsigned int dma_frees,opens; +static void dcp_hdr_service_bind(struct apple_epic_service *s) { (void)s; } +static void dcp_hdr_service_unbind(struct apple_epic_service *s) { (void)s; } + static int open_error,open_action; void dpavservep_detach(struct apple_dcp *dcp); static void afk_recv_handle_teardown(struct apple_dcp_afkep *ep, u32 channel); @@ -146,6 +152,8 @@ def function(file,signature): struct dcp_parse_ctx { struct item *items;unsigned int count,index;bool key; }; struct iterator { struct dcp_parse_ctx *handle;unsigned int idx,len; }; #define kfree(p) free((void *)(p)) +#define GFP_KERNEL 0 +#define kstrdup(s,f) strdup(s) #define PTR_ERR(p) ((int)(intptr_t)(p)) static struct item announcement_items[3]; static int parse(u8 *p,size_t n,struct dcp_parse_ctx *ctx) @@ -169,13 +177,13 @@ def function(file,signature): function('afk.h','static inline bool afk_service_matches('),function('afk.h','static inline bool afk_service_reclaimable('), function('afk.h','static inline bool\nafk_service_reinit('),function('afk.h','static inline void afk_service_discard('), function('afk.h','static inline void afk_service_publish('), - function('epic/dpavservep.c','static void dcpavserv_notify_edid('),function('epic/dpavservep.c','static bool dcpavserv_identity('), - function('epic/dpavservep.c','static bool dcpavserv_admission_current('),function('epic/dpavservep.c','static int dcpavserv_prepare('), + function('epic/dpavservep.c','static void dcpavserv_notify_edid('),function('epic/dpavservep.c','static bool dcpavserv_hdr_class('),function('epic/dpavservep.c','static bool dcpavserv_identity('), + '/* These scenarios model a Type-C output (dcp-fabric.c decides it in the driver). */\nstatic bool dcp_is_typec_output(struct apple_dcp *d) { (void)d; return true; }\n'+function('epic/dpavservep.c','static bool dcpavserv_admission_current('),function('epic/dpavservep.c','static int dcpavserv_prepare('), function('epic/dpavservep.c','static int dcpavserv_revalidate('),function('epic/dpavservep.c','static void dcpavserv_init('),function('epic/dpavservep.c','static void dcpavserv_invalidate_edid('), function('epic/dpavservep.c','static void dcpavserv_teardown('),function('epic/dpavservep.c','void dpavservep_detach('), function('afk.c','static const struct apple_epic_service_ops *\nafk_match_service('), function('afk.c','static struct apple_epic_service *afk_epic_find_service('), - function('afk.h','static inline bool afk_service_retired('),function('afk.c','static bool afk_epic_channel_retired('), + function('afk.h','static inline bool afk_service_retired('),function('afk.h','static inline bool afk_service_supersede('),function('afk.c','static bool afk_epic_channel_retired('), function('afk.c','static void afk_discard_pending_open('),function('afk.c','static void afk_retry_service_init('),function('afk.c','static void afk_service_worker('),function('afk.c','static void afk_recv_handle_init('), function('epic/dpavservep.c','static int dcpdpserv_prepare('), function('epic/dpavservep.c','static void dcpdpserv_teardown('),function('afk.c','static void afk_recv_handle_teardown('), @@ -293,17 +301,19 @@ def function(file,signature): const char *forged[]={"DCPDP13ServiceExtra","dcpdp13service","AppleDCPDP2HDMIExtra","unrelated-provider"}; announce(13,name,forged[variant],13);assert(opens==before && !d.dcpavserv.service); } - /* AFKV2 on the classic DPAV endpoint: EPICUnit 0 with a dynamic interface-id. */ + /* + * AFKV2 on the classic DPAV endpoint: the M3/M4 Air external DCPs announce + * DCPDP13Service with EPICUnit 0 and a dynamic interface-id. Only that + * generic class (and the MCDP29xx converters) is admitted there. + */ ep.endpoint=0x28; - for(unsigned int variant=0;variant<2;variant++) { - const char *provider=variant?native_class:class; - assert(!prepare(1,1,name,provider));assert(!prepare(5,5,name,provider)); - assert(!prepare(0,0,name,provider));assert(!prepare(65536,0,name,provider)); - assert(!prepare(5,0,"dcpdp-service-epic",provider));assert(!prepare(5,0,name,"unrelated-provider")); - for(u32 channel=1;channel<=13;channel+=4) { - struct apple_epic_service *s=prepare(channel,0,name,provider); - assert(s && "EPICUnit-0 AV provider must be admitted");afk_service_discard(s); - } + assert(!prepare(1,1,name,native_class));assert(!prepare(5,5,name,native_class)); + assert(!prepare(0,0,name,native_class));assert(!prepare(65536,0,name,native_class)); + assert(!prepare(5,0,"dcpdp-service-epic",native_class));assert(!prepare(5,0,name,"unrelated-provider")); + for(u32 channel=1;channel<=13;channel+=4) { + struct apple_epic_service *s=prepare(channel,0,name,native_class); + assert(s && "EPICUnit-0 DCPDP13Service must be admitted");afk_service_discard(s); + assert(!prepare(channel,0,name,class) && "AppleDCPDP2HDMI stays refused on 0x28"); } ep.endpoint=0x2c;assert(!prepare(5,0,name,native_class));ep.endpoint=0x2a; assert(!prepare(5,0,name,native_class)); /* H17P keeps unit == interface-id. */ @@ -485,6 +495,45 @@ def function(file,signature): memset(ep.services,0,sizeof(ep.services));ep.num_channels=AFK_MAX_CHANNEL;ep.ops=announcement_ops; puts("PASS optional absence remains closed; required unsupported and genuine optional failures remain errors"); } +static struct apple_epic_service *singleton_owner; +/* As av_audiosrv_init(): the owner pins the new instance and lets go of the old one. */ +static void singleton_init(struct apple_epic_service *s,const char *n,const char *c,s64 u) +{ + struct apple_epic_service *old=singleton_owner; + singleton_owner=afk_service_get(s);assert(singleton_owner==s); + if(old) afk_service_put(old); +} +static int singleton_prepare(struct apple_epic_service *s,const char *n,const char *c,s64 u) { return 0; } +static void singleton_rejected_replacement(void) +{ + /* A classic AV singleton (no prepare): its replacement must not retire the + * instance it would replace before the replacement has a slot. */ + const struct apple_epic_service_ops single[]={{.name="dcpav-service-epic",.reusable=true,.singleton=true,.prepare=singleton_prepare,.init=singleton_init},{.name=""}}; + memset(ep.services,0,sizeof(ep.services));singleton_owner=NULL; + ep.ops=single;ep.match_epic_name=true;ep.num_channels=0;d.fw_compat=DCP_FIRMWARE_H17P; + announce(1,name,class,1);run_retries(); + struct apple_epic_service *a=singleton_owner; + assert(a && a->channel==1 && a->enabled && !a->torndown && a->users==1); + /* Every other slot is retired with a reply still owed: none is reclaimable. */ + for(unsigned i=0;iops=&single[0];o->torndown=true;o->enabled=false;o->channel=100+i;o->cmd_map[0]|=1; + } + ep.num_channels=AFK_MAX_CHANNEL;diagnostic_errors=0; + announce(5,name,class,5);run_retries(); + assert(diagnostic_errors>=1); + assert(singleton_owner==a && a->enabled && !a->torndown && a->users==1); + assert(afk_service_get(a)==a);afk_service_put(a); + /* A slot comes back: the replacement is admitted, and only then retires the previous instance. */ + ep.services[a==&ep.services[0]?1:0].cmd_map[0]&=~1UL; + announce(5,name,class,5);run_retries(); + assert(singleton_owner && singleton_owner!=a && singleton_owner->channel==5 && singleton_owner->enabled); + assert(a->torndown && !a->enabled && !a->users); + afk_service_put(singleton_owner);singleton_owner=NULL; + memset(ep.services,0,sizeof(ep.services));ep.num_channels=AFK_MAX_CHANNEL;ep.ops=announcement_ops; + puts("PASS a singleton replacement rejected for lack of a slot leaves the previous instance usable; an admitted one retires it"); +} int main(void) { d.hw.iomfb_method_profile=2;d.typec_cable_connected=true;d.typec_generation=1;d.nr_modes=1;d.connector=&con;d.dev=&d; @@ -561,6 +610,7 @@ def function(file,signature): assert(d.dcpavserv.service==pending && pending->users==1);dpavservep_detach(&d); assert(!pending->users && !d.hpd_mutex && !d.dcpavserv.lock); memset(&ep.services,0,sizeof(ep.services));ep.wire_v2=true;ep.endpoint=0x2a;d.hw.iomfb_method_profile=2; + singleton_rejected_replacement(); repeated_announcements(); deferred_announcements(); free(ep.command_tags);ep.command_tags=NULL; @@ -588,7 +638,7 @@ def function(file, signature): av = (base / 'epic/dpavservep.c').read_text() af = (base / 'afk.c').read_text() - announce = af[af.index('static void afk_recv_handle_init('):af.index('static void afk_recv_handle_init(') + 6500] + announce = af[af.index('static void afk_recv_handle_init('):af.index('static void afk_recv_handle_init(') + 7000] assert announce.index('ops->prepare(service,') < announce.index('EPIC_CAT_REPORT, AFKV2_OPEN') assert '.prepare = dcpavserv_prepare,' in av and '.prepare = dcpdpserv_prepare,' in av prefix = r''' @@ -674,10 +724,15 @@ def function(file, signature): '''+internal_inline(root,'dcp_is_v14_7_external')+r'''static unsigned int reads, allocations, legacy_reads, receives; static unsigned int event; static struct apple_dcp_afkep *received_ep; +static struct apple_epic_service *hdr_bound; static struct apple_epic_service *afk_service_get(struct apple_epic_service *s) { if(!s || !s->enabled || s->torndown) return NULL; s->users++; return s; } static void afk_service_put(struct apple_epic_service *s) { assert(s->users); s->users--; } +static void dcp_hdr_service_bind(struct apple_epic_service *s) +{ assert(!hdr_bound); hdr_bound=afk_service_get(s); } +static void dcp_hdr_service_unbind(struct apple_epic_service *s) +{ if(hdr_bound==s) { hdr_bound=NULL; afk_service_put(s); } } static void afk_service_retire(struct apple_epic_service *s) { s->enabled=false;s->torndown=true; } static void drm_edid_free(const struct drm_edid *e) { if(e) { assert(allocations); allocations--; free((void *)e); } } @@ -685,7 +740,7 @@ def function(file, signature): static const struct drm_edid *dcpavserv_read_edid_inline(struct apple_epic_service *s) { struct apple_dcp *d=s->ep->dcp; - assert(!d->hpd_mutex && !d->dcpavserv.lock && s->users==2); + assert(!d->hpd_mutex && !d->dcpavserv.lock && s->users==(hdr_bound==s ? 3U : 2U)); reads++; if(event==1 || event==2) { d->typec_generation++; d->typec_cable_connected=(event==2); } if(event==3) { s->enabled=false; dcpavserv_teardown(s); } @@ -708,8 +763,9 @@ def function(file, signature): function('epic/dpavservep.c', 'static void dcpavserv_teardown('), function('dcp.c', 'static struct apple_dcp_afkep *dcp_afkep('), function('dcp.c', 'static void dcp_recv_msg('), + function('epic/dpavservep.c', 'static bool dcpavserv_hdr_class('), function('epic/dpavservep.c', 'static bool dcpavserv_identity('), - function('epic/dpavservep.c', 'static bool dcpavserv_admission_current('), + '/* These scenarios model a Type-C output (dcp-fabric.c decides it in the driver). */\nstatic bool dcp_is_typec_output(struct apple_dcp *d) { (void)d; return true; }\n' + function('epic/dpavservep.c', 'static bool dcpavserv_admission_current('), function('epic/dpavservep.c', 'static int dcpavserv_prepare('), function('epic/dpavservep.c', 'static int dcpdpserv_prepare('), function('epic/dpavservep.c', 'static void dcpavserv_init('), @@ -764,16 +820,26 @@ def function(file, signature): assert(connector.edid_invalidation_pending && connector.hotplug_wq && d.dcpavserv.epoch==2); /* Same slot and physical generation: CLOSE/re-OPEN gets a fresh ticket. */ s.enabled=true; assert(!dcpavserv_prepare(&s,name,class,1)); dcpavserv_init(&s,name,class,1); - assert(d.dcpavserv.service==&s && s.users==1 && d.dcpavserv.epoch==3); + assert(d.dcpavserv.service==&s && hdr_bound==&s && s.users==2 && d.dcpavserv.epoch==3); mutex_lock(&d.dcpavserv.lock); assert(!dcpavserv_edid_service_current(&d,1) && dcpavserv_edid_service_current(&d,3)); mutex_unlock(&d.dcpavserv.lock); event=0; e=dcpavserv_copy_edid(&d,3,&epoch); assert(!IS_ERR(e) && epoch==3); /* Simulate retirement in the final validation-to-publication gap. */ - s.enabled=false; dcpavserv_teardown(&s); s.enabled=true; assert(!dcpavserv_prepare(&s,name,class,1)); dcpavserv_init(&s,name,class,1); + s.enabled=false; dcpavserv_teardown(&s); assert(!hdr_bound && !s.users); s.enabled=true; assert(!dcpavserv_prepare(&s,name,class,1)); dcpavserv_init(&s,name,class,1); mutex_lock(&d.dcpavserv.lock); assert(!dcpavserv_edid_service_current(&d,epoch)); mutex_unlock(&d.dcpavserv.lock); - drm_edid_free(e); assert(d.typec_generation==3 && d.dcpavserv.epoch==5 && s.users==1); - s.enabled=false; dcpavserv_teardown(&s); + drm_edid_free(e); assert(d.typec_generation==3 && d.dcpavserv.epoch==5 && hdr_bound==&s && s.users==2); + s.enabled=false; dcpavserv_teardown(&s); assert(!hdr_bound && !s.users); + /* Firmware 27 MCDP29xx / MCDP2900 AV services bind HDR metadata on EP 0x28 too. */ + av.endpoint=0x28; d.hw.iomfb_method_profile=0; s.enabled=true; + const char *v27_classes[] = {"AppleDCPMCDP29XX", "AppleDCPMCDP2900"}; + for (size_t i = 0; i < sizeof(v27_classes) / sizeof(v27_classes[0]); i++) { + assert(!dcpavserv_prepare(&s, name, v27_classes[i], 0)); + dcpavserv_init(&s, name, v27_classes[i], 0); + assert(hdr_bound == &s && s.users == 2); + dcpavserv_teardown(&s); + assert(!hdr_bound && !s.users); + } av.wire_v2=false; av.endpoint=0x28; d.hw.iomfb_method_profile=0; d.dcpavserv.enabled=false; assert(!dcpavserv_prepare(&s,name,NULL,0)); assert(dcpavserv_prepare(&s,name,class,1)==-ENODEV); @@ -783,8 +849,26 @@ def function(file, signature): assert(!IS_ERR(e) && legacy_reads==1 && s.users==1); drm_edid_free(e); d.hw.iomfb_method_profile=0;av.wire_v2=false;d.external_physically_absent=true; mutex_lock(&d.hpd_mutex);assert(dcpavserv_edid_current(&d,0));mutex_unlock(&d.hpd_mutex); + dcpavserv_teardown(&s); + + /* The legacy AV service owns HDR metadata on both DP and HDMI. */ + const char *legacy_classes[] = {"DCPDPService", "DCPDP13Service", "AppleDCPDP2HDMI"}; + for (size_t i = 0; i < sizeof(legacy_classes) / sizeof(legacy_classes[0]); i++) { + assert(!dcpavserv_prepare(&s, name, legacy_classes[i], 0)); + dcpavserv_init(&s, name, legacy_classes[i], 0); + assert(hdr_bound == &s && s.users == 2); + dcpavserv_teardown(&s); + assert(!hdr_bound && !s.users); + } + /* The desktop command binds through its own service lifecycle. */ + struct dcp_desktop_state desktop = {}; + d.desktop = &desktop; + assert(!dcpavserv_prepare(&s, name, class, 0)); + dcpavserv_init(&s, name, class, 0); + assert(d.dcpavserv.service == &s && !hdr_bound); + dcpavserv_teardown(&s); assert(!allocations && !d.hpd_mutex && !d.dcpavserv.lock); - puts("PASS: production old/new lookup and receive, exact service admission before OPEN, delayed disconnect/replug, service detach pins, legacy transport"); + puts("PASS: production old/new lookup and receive, exact service admission before OPEN, delayed disconnect/replug, service detach pins, legacy and AFKv2 HDR binding"); } ''' return prefix + '\n'.join(parts) + suffix diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/j616s.py b/tools/testing/selftests/drivers/gpu/apple-dcp/j616s.py index 77273dfacd1a23..f7f1b9a858b8d2 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/j616s.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/j616s.py @@ -14,6 +14,7 @@ def identity(root, output): typedef int32_t s32; #define ALIGN(x,n) (((x)+(n)-1)&~((n)-1)) #define SZ_16M (16U<<20) +#define __maybe_unused static u32 get_unaligned_le32(const void *p) {u32 n;memcpy(&n,p,4);return n;} ''' unit += block((base / 'dcp-panel-adt.h').read_text(), 'struct dcp_panel_adt {') + ';\n' diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index e41e10447eb224..3941f8bd0aebb5 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -3,7 +3,7 @@ """Actual disconnect authority, DWC3 teardown and firmware resource admission.""" from pathlib import Path import re -from common import block, apple_function, internal_inline, atc_mux_without_pm, source_defines, ATC_POST_TUNABLE, tipd_pm_header, firmware_lineage, atc_restore_helpers, atc_cio_helpers +from common import block, apple_function, atc_set_mode_prototypes, internal_inline, atc_mux_without_pm, source_defines, ATC_POST_TUNABLE, tipd_pm_header, firmware_lineage, atc_restore_helpers, atc_cio_helpers, atc_cfg_helpers def disconnect(root): # Copyright 2026 Ryan Murray @@ -595,7 +595,7 @@ def swap(old, new): ' struct { bool connected, closed, tile_hint; void *service, *atcphy; int linkcfg_completion; } dptxport[1];\n' ' void *phy, *dev, *active_typec_route;\n' ' int dptx_die, dptx_phy, dptx_dfp_port, connector_type;\n' - ' bool external, external_link_ready, crashed;\n' + ' bool external, external_link_ready, crashed, rtkit_adopted;\n' ' bool typec_work_enabled;' + ('' if '\n int fw_compat;' in unit else ' int fw_compat;') + ' struct { bool fw_14_7_endpoints; } hw;\n' ' struct { bool active; } split;\n' @@ -795,6 +795,15 @@ def swap(old, new): 'static bool dcp_tb_tunnel_withdrawn(struct apple_dcp *d, u32 port)\n' '{ (void)d; (void)port; assert(!"tunnel watch in an H17P scenario"); return false; }\n' + apple_function(root, 'dcp_dptx_wait_linkcfg')) + if 'dcp_assert_hpd_before_link_wait(' in raw: + # The HPD assertion before the link wait, as the driver has it. This scenario is a + # Type-C H17P link, so the fixed-HDMI branch is not taken. + swap(' bool hdmi_hpd;', + ' int fixed_connector_type; void *hdmi_hpd;') + firmware += ('static int __attribute__((unused)) gpiod_get_value_cansleep(void *gpio)\n' + '{ (void)gpio; assert(!"fixed HDMI GPIO in a Type-C scenario"); return 0; }\n' + '#ifndef DRM_MODE_CONNECTOR_HDMIA\n#define DRM_MODE_CONNECTOR_HDMIA 11\n#endif\n' + + apple_function(root, 'dcp_assert_hpd_before_link_wait')) # unless the update work already needed the clock clock = 'static unsigned jiffies_to_msecs(unsigned long t) { return t; }\n' if clock in unit: @@ -824,6 +833,9 @@ def poweroff_replug(root): #define fake_guard(x) ((void)(x)) #define scoped_guard(x, y) for (int once = ((void)(y), 1); once; once = 0) #define dev_dbg(...) ((void)0) +#ifndef dev_info +#define dev_info(...) ((void)0) +#endif #define dev_warn(...) ((void)0) #define dev_err(...) ((void)0) struct delayed_work { bool pending; }; @@ -1127,6 +1139,8 @@ def fn(n, name): m = re.search(r'^(?:static [^\n]*\b|(?:int|void) )' + name + r'\([^;{}]*\)\s*\{', s, re.M) assert m, (n, name) result = block(s, m.start()) + if n == 'atc' and name == 'atcphy_usb3_set_mode': + result = atc_set_mode_prototypes(s) + result return result decls = [] @@ -1182,7 +1196,7 @@ def fn(n, name): names = {n: tuple(name for name in group if re.search(r'^(?:static [^\n]*\b|(?:int|void) )' + name + r'\(', files[n], re.M)) for n, group in names.items()} context = (fn('atc', 'core_read32') + '\n' + fn('atc', 'atcphy_get_mode_config') + '\n' + fn('atc', 'j700_field_update') + '\n' + files['dp'][files['dp'].index('/* Masks are the union'):files['dp'].index('/* Retry only the idle operations')]) - functions = atc_cio_helpers(files['atc']) + '\n\n'.join(fn(n, name) for n, group in names.items() for name in group) + functions = atc_cio_helpers(files['atc']) + atc_cfg_helpers(files['atc']) + '\n\n'.join(fn(n, name) for n, group in names.items() for name in group) definitions = [] lines = iter(files['atc'].splitlines()) for line in lines: @@ -1544,7 +1558,6 @@ def function(source, marker): #define DRM_MODE_CONNECTOR_HDMIA 11 #define DRM_MODE_CONNECTOR_eDP 14 #define DRM_MODE_CONNECTOR_USB 20 -#define msleep(x) ((void)(x)) #define component_compare_of 0 #define apple_dcp_id_tbl 0 static int dcp_comp_ops; @@ -1579,6 +1592,13 @@ def function(source, marker): /* Nor a T6041 dcpext. */ static bool __attribute__((unused)) dcp_t6041_ext_enabled(void) { assert(!"T6041 dcpext in a J700 scenario"); return false; } +/* Nor a T8132 processor of either backend. */ +static bool __attribute__((unused)) apple_t8132_firmware_path(void) +{ assert(!"T8132 DCP in a J700 scenario"); return false; } +static bool __attribute__((unused)) apple_t8132_dcpext_v27_2(const struct device_node *n) +{ (void)n; assert(!"T8132 dcpext in a J700 scenario"); return false; } +static bool __attribute__((unused)) apple_t8132_dcp_v27_2(const struct device_node *n) +{ (void)n; assert(!"T8132 DCP in a J700 scenario"); return false; } static void __attribute__((unused)) iomfb_v14_7_external_refuse(struct apple_dcp *d, const char *why) { (void)d; (void)why; assert(!"T6030 external processor in a J700 scenario"); } struct drm_device { int unused; }; @@ -1595,10 +1615,21 @@ def function(source, marker): static struct component_match matches; static bool machine_supported, absent_external; static unsigned int references, released, node_puts, probes[2], bind_attempts, disables; +static unsigned int start_report_flushes; static int preflight_error, external_probe_error, bind_result; +static void apple_drm_flush_start_reports(struct drm_device *drm) +{ + assert(drm == &priv.drm); + start_report_flushes++; +} +/* The J700 readiness scenarios do not have a J713 panel. */ +#ifndef iomfb_is_m4 +static bool iomfb_is_m4(struct apple_dcp *dcp) { (void)dcp; return false; } +#endif static void try_bind(void); -static bool of_machine_is_compatible(const char *s) -{ assert(!strcmp(s,"apple,j700")); return machine_supported; } +/* The board must not enter into admission: any call fails the test. */ +static __attribute__((unused)) bool of_machine_is_compatible(const char *s) +{ (void)s; assert(false); return machine_supported; } static int of_property_read_variable_u32_array(struct device_node *n,const char *s,u32 *v,int min,int max) { assert(min==3 && max==3); @@ -1711,6 +1742,7 @@ def function(source, marker): } absent_external = false; references = released = node_puts = bind_attempts = disables = 0; + start_report_flushes = 0; preflight_error = external_probe_error = bind_result = 0; } static int match_providers(void) @@ -1722,10 +1754,11 @@ def function(source, marker): { assert(apple_dcp_external_bw_valid(0xbc000,0x28000,0x70000)); assert(apple_dcp_external_clock_window(0x302800000ULL,0xbc000,0x302800000ULL,0xbc000)); - /* No command line state: exact J700 firmware selects the external profile. */ + /* No command line state: the exact firmware selects the external profile. */ initial(true); assert(dcp_h17p_external_supported(&nodes[1])); + /* The board does not: the same node and firmware on any machine. */ machine_supported=false; - assert(!dcp_h17p_external_supported(&nodes[1]) && match_providers()==1); + assert(dcp_h17p_external_supported(&nodes[1])); for(unsigned i=0;i<3;i++) { initial(true); nodes[1].firmware[i]++; assert(!dcp_h17p_external_supported(&nodes[1]) && match_providers()==1); @@ -1745,16 +1778,19 @@ def function(source, marker): assert(!dcp_h17p_external_ready(&nodes[1]) && references == 0); try_bind(); assert(bind_attempts == 1 && bind_result == 0 && probes[0] == 1 && !probes[1]); + assert(start_report_flushes == 1); /* Delayed external provider remains in the match; the master must wait. */ initial(true); assert(match_providers() == 2 && matches.includes[1]); try_bind(); assert(bind_attempts == 0 && !probes[0] && !probes[1]); + assert(start_report_flushes == 0); /* Last provider is prepared, but driver core bound is still false here. */ assert(publish_provider(&devices[1], &dcps[1]) == 0); assert(dcps[1].external_prepared && !devices[1].bound); assert(bind_attempts == 1 && bind_result == 0 && probes[0] == 1 && probes[1] == 1); + assert(start_report_flushes == 1); devices[1].bound = true; /* Permanent preflight failure cannot silently drop a requested provider. */ @@ -1799,6 +1835,7 @@ def function(source, marker): dcps[1].external_prepared = true; if (failure) start_error[0] = -EIO; else ready_error[0] = -ETIMEDOUT; assert(apple_drm_init_dcp(&master) == -ENODEV); + assert(start_report_flushes == 0); /* A processor that did not start is not waited for. */ assert(starts[0] == 1 && waits[0] == (int)!failure && waits[1] == 1); } @@ -1807,10 +1844,12 @@ def function(source, marker): dcps[1].external_prepared = true; ready_error[1] = -ETIMEDOUT; assert(apple_drm_init_dcp(&master) == 0); + assert(start_report_flushes == 1); initial(true); dcps[1].external_prepared = true; start_error[1] = -EIO; assert(apple_drm_init_dcp(&master) == 0 && waits[1] == 0); + assert(start_report_flushes == 1); puts("PASS: automatic hardware/firmware matching, delayed/preflight-failed providers, synchronous publication, readiness rejection, boot framebuffer kept without the panel processor"); return 0; } @@ -1838,18 +1877,22 @@ def vrr(root): #define DCP_IOMFB_METHODS_H17P_EXTERNAL 2 #define READ_ONCE(x) (x) #define dev_dbg(...) ((void)0) +#ifndef dev_info +#define dev_info(...) ((void)0) +#endif struct apple_connector { bool connected; }; /* The native T6030 14.7 backend is never selected in these scenarios. */ enum dcp_firmware_version { DCP_FIRMWARE_UNKNOWN, DCP_FIRMWARE_V_12_3, DCP_FIRMWARE_V_13_5, DCP_FIRMWARE_V_14_7, DCP_FIRMWARE_V_14_7_TEMPLATE, DCP_FIRMWARE_V_26_6, DCP_FIRMWARE_V_26_6_DESKTOP, DCP_FIRMWARE_V_27_0 }; struct apple_dcp { - bool crashed, external, external_native, quiescing, main_display, panel; + bool crashed, external, external_native, quiescing, main_display, panel, iomfb_template_pq, vrr_enabled; int peer_check; /* what the firmware 27 paired-timing check answers */ unsigned int nr_typec_routes; enum dcp_firmware_version fw_compat; struct { int iomfb_method_profile; } hw; struct { bool valid; } mode_state; + struct { bool vrr_failed; } *desktop; struct apple_connector *connector; void *dev; }; @@ -1954,6 +1997,8 @@ def vrr(root): # VRR_ENABLED change must never become a mode set. The external # processors ignore a live minimum rate and still apply it with a mode set. desktop = r""" dcp.fw_compat = DCP_FIRMWARE_V_26_6_DESKTOP; + dcp.iomfb_template_pq = true; + dcp.vrr_enabled = true; dcp.hw.iomfb_method_profile = 0; dcp.mode_state.valid = true; dcp.connector = &connector; @@ -1978,13 +2023,35 @@ def vrr(root): } cases++; } + /* Adopted desktop 26.6 panel boot mode starts fixed (!dcp.vrr_enabled): + * enabling VRR_ENABLED triggers one modeset to arm adaptive sync unless vrr_failed. */ + { + __typeof__(*dcp.desktop) ds = { .vrr_failed = false }; + dcp.desktop = &ds; + dcp.main_display = true; + dcp.vrr_enabled = false; + state.crtc.enable = true; + state.no_old_crtc = false; + state.old_crtc.vrr_enabled = false; + state.crtc.vrr_enabled = true; + state.crtc.mode_changed = false; + assert(dcp_crtc_atomic_check(&crtc, &state) == 0 && state.crtc.mode_changed); + ds.vrr_failed = true; + state.crtc.mode_changed = false; + assert(dcp_crtc_atomic_check(&crtc, &state) == 0 && !state.crtc.mode_changed); + dcp.desktop = NULL; + cases += 2; + } dcp.main_display = false; + dcp.vrr_enabled = false; + dcp.iomfb_template_pq = false; dcp.fw_compat = DCP_FIRMWARE_UNKNOWN; """ # Firmware 27: its externals change adaptive sync with a full mode set, as # macOS switches between a timing's fixed and variable modes; the panel # does not. A paired timing the pair cannot take fails the check. fw27 = r""" dcp.fw_compat = DCP_FIRMWARE_V_27_0; + dcp.iomfb_template_pq = true; dcp.hw.iomfb_method_profile = 0; dcp.mode_state.valid = true; dcp.connector = &connector; @@ -2018,6 +2085,26 @@ def vrr(root): dcp.panel = false; dcp.peer_check = 0; dcp.fw_compat = DCP_FIRMWARE_UNKNOWN; + /* Template-driven 12.3/13.5/14.7_tpl DCPs program VRR inside iomfb_modeset(). */ + const enum dcp_firmware_version tpl_fws[] = { + DCP_FIRMWARE_V_12_3, DCP_FIRMWARE_V_13_5, DCP_FIRMWARE_V_14_7_TEMPLATE + }; + dcp.iomfb_template_pq = true; + for (unsigned int i = 0; i < 3; i++) { + dcp.fw_compat = tpl_fws[i]; + state.crtc.enable = true; + state.crtc.vrr_enabled = true; + state.crtc.mode_changed = false; + state.no_old_crtc = false; + state.old_crtc.vrr_enabled = false; + assert(dcp_crtc_atomic_check(&crtc, &state) == 0 && state.crtc.mode_changed); + state.crtc.mode_changed = false; + state.old_crtc.vrr_enabled = true; + assert(dcp_crtc_atomic_check(&crtc, &state) == 0 && !state.crtc.mode_changed); + cases += 2; + } + dcp.iomfb_template_pq = false; + dcp.fw_compat = DCP_FIRMWARE_UNKNOWN; """ return prefix + check + suffix.replace('DESKTOP_VRR', desktop, 1).replace('FW27_VRR', fw27, 1) @@ -2143,8 +2230,10 @@ def dispatcher(root): static struct dcp_channel *dcp_get_channel(struct apple_dcp *d, enum dcp_context_id c) { (void)c; return &d->channel; } static int dcp_parse_tag(char *p) { (void)p; return case_tag; } -static bool of_machine_is_compatible(const char *n) { (void)n; return machine; } -static bool of_device_is_compatible(struct device_node *n, const char *s) +/* Neither the board nor the node decides the D134 reply any more. */ +static __attribute__((unused)) bool of_machine_is_compatible(const char *n) +{ (void)n; return machine; } +static __attribute__((unused)) bool of_device_is_compatible(struct device_node *n, const char *s) { (void)s; return n->external; } static bool iomfb_check_callback_h17p(struct apple_dcp *d, int t, u32 i, u32 o) { (void)d; (void)t; (void)i; (void)o; return true; } @@ -2183,7 +2272,8 @@ def dispatcher(root): d.hw.iomfb_method_profile = 0; case_tag = tag; acks = 0; dcpep_handle_cb(&d, context, h, sizeof(*h) + in + out, 0); - bool accepted = scope == 7 && tag == 134 && context == 3 && !in && out == 4; + /* Only the H17P external method profile (scope bit 2) decides. */ + bool accepted = (scope & 4) && tag == 134 && context == 3 && !in && out == 4; if (scope & 4) { assert(acks == accepted && d.crashed != accepted); for (unsigned i = 0; i < out; i++) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py index 26c0f62dabb254..5ad5d341034f51 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py @@ -3,9 +3,9 @@ """Actual PHY parking, failure/retry, masked context and OFF controls.""" from pathlib import Path import re -from common import (block, source_defines, atc_mux_without_pm, ATC_POST_TUNABLE, +from common import (block, source_defines, atc_mux_without_pm, atc_set_mode_prototypes, ATC_POST_TUNABLE, atc_function, ATC_SPLIT, ATC_T8103_LIVE, atc_restore_helpers, atc_common_state_helpers, - atc_cio_helpers) + atc_cio_helpers, atc_cfg_helpers) def parking(root): @@ -16,6 +16,9 @@ def parking(root): def function(source, name): if name == 'atcphy_mux_set' and 'static int atcphy_mux_set_locked(' in source: return atc_mux_without_pm(source) + if name == 'atcphy_usb3_set_mode': + return atc_set_mode_prototypes(source) + block(source, re.search( + r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) if name in ATC_SPLIT + ATC_T8103_LIVE: return atc_function(source, name) return block(source, re.search(r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) @@ -34,7 +37,7 @@ def function(source, name): parts.append(r''' struct apple_atcphy { /* T8132-only paths are covered by drivers/apple/atc-t8132-usb3.py. */ - bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; + bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt, t8132_device; /* A CIO sleep is T8132's too, covered by tools/asahi/atc-cio-sleep-tests.py. */ struct { bool prepared; } cio_sleep; struct { void *usb3_dp, *dp_lioa, *dp_common_config; } tunables; @@ -46,7 +49,7 @@ def function(source, name): struct reset_controller_dev rcdev; void *dev; int lock, dp_link_rate; - bool fixed_usb2, host_active, swap_lanes, ss_tunables, dp_tunables; + bool fixed_usb2, fixed_usb3, cio_only, host_active, swap_lanes, ss_tunables, dp_tunables; bool aux_power_requested, mode_dirty, dp_spread_spectrum, dp_presets_valid[5]; u32 dp_presets[5][16]; unsigned int dp_idle_pmas, dp_owned_pmas; @@ -67,6 +70,7 @@ def function(source, name): start = atc.index('static const struct {\n\tconst struct atcphy_mode_configuration normal;') parts.append(atc[start:atc.index('\n};', start) + 3]) parts.append(atc_cio_helpers(atc)) + parts.append(atc_cfg_helpers(atc)) parts.append(r''' struct phy_configure_opts_dp { unsigned int link_rate, lanes, voltage[4], pre[4]; @@ -160,11 +164,15 @@ def function(source, name): static int atcphy_power_off(struct apple_atcphy *); static int atcphy_configure(struct apple_atcphy *, enum atcphy_mode); -/* These units exercise older PHY generations. Never accept a T8132 dispatch. */ +/* These units exercise older PHY generations. Never accept a T8132 or T8152 dispatch. */ static int __attribute__((unused)) atcphy_configure_t8132(struct apple_atcphy *p, enum atcphy_mode mode) { (void)p; (void)mode; assert(false); return -EOPNOTSUPP; } static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *p) { (void)p; assert(false); return -EOPNOTSUPP; } +static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); return -EOPNOTSUPP; } +static void __attribute__((unused)) atcphy_lanes_down_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); } ''') @@ -224,7 +232,11 @@ def function(source, name): #define hweight32(v) __builtin_popcount(v) #define dev_info_once(...) ((void)0) #define dev_dbg(...) ((void)0) +#ifndef dev_info +#define dev_info(...) ((void)0) +#endif #define dev_warn(...) ((void)0) +#define dev_info(...) ((void)0) static void report(void *dev, const char *fmt, ...) { (void)dev; (void)fmt; } #define dev_err report #define lockdep_assert_held(...) ((void)0) @@ -1901,6 +1913,9 @@ def usb_context(root): } #undef dev_dbg #define dev_dbg(dev, format, ...) record_debug(format, ##__VA_ARGS__) +#ifndef dev_info +#define dev_info(...) ((void)0) +#endif ''' return ns["prefix"] + logger + "#define PROPOSAL\n" + production + ns["suffix"].replace("int main(", "int original_fixture_main(", 1) + controls @@ -1923,6 +1938,9 @@ def block(marker): def function(name): if name == 'atcphy_mux_set' and 'static int atcphy_mux_set_locked(' in source: return atc_mux_without_pm(source) + if name == 'atcphy_usb3_set_mode': + return atc_set_mode_prototypes(source) + block(re.search( + r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) if name in ATC_SPLIT + ATC_T8103_LIVE: return atc_function(source, name) return block(re.search(r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) @@ -1936,7 +1954,7 @@ def function(name): parts.append(r''' struct apple_atcphy { /* T8132-only paths are covered by drivers/apple/atc-t8132-usb3.py. */ - bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; + bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt, t8132_device; /* A CIO sleep is T8132's too, covered by tools/asahi/atc-cio-sleep-tests.py. */ struct { bool prepared; } cio_sleep; struct { void *usb3_dp, *dp_lioa, *dp_common_config; } tunables; @@ -1948,7 +1966,7 @@ def function(name): struct { unsigned char *core, *pipehandler; } regs; void *dev; int lock; - bool fixed_usb2, host_active, ss_tunables, dp_tunables, mode_dirty; + bool fixed_usb2, fixed_usb3, cio_only, host_active, ss_tunables, dp_tunables, mode_dirty; unsigned int dp_owned_pmas, dp_idle_pmas; unsigned int dp_usb_context_valid, dp_usb_context_dirty; u32 dp_usb_context[2][27]; @@ -1993,11 +2011,13 @@ def function(name): static void __attribute__((unused)) atcphy_restore_after_pd_off(struct apple_atcphy *p) { assert(!p->pd_was_off); } static int atcphy_configure(struct apple_atcphy *p, enum atcphy_mode mode); -/* These units exercise older PHY generations. Never accept a T8132 dispatch. */ +/* These units exercise older PHY generations. Never accept a T8132 or T8152 dispatch. */ static int __attribute__((unused)) atcphy_configure_t8132(struct apple_atcphy *p, enum atcphy_mode mode) { (void)p; (void)mode; assert(false); return -EOPNOTSUPP; } static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *p) { (void)p; assert(false); return -EOPNOTSUPP; } +static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); return -EOPNOTSUPP; } ''') for name in ('core_read32', 'atcphy_get_mode_config'): @@ -2047,7 +2067,11 @@ def function(name): #define FIELD_GET(m, v) (((v) & (m)) >> __builtin_ctz(m)) #define field_prep FIELD_PREP #define dev_dbg(...) ((void)0) +#ifndef dev_info +#define dev_info(...) ((void)0) +#endif #define dev_warn(...) ((void)0) +#define dev_info(...) ((void)0) #define dev_err(...) ((void)0) #define lockdep_assert_held(...) ((void)0) #define WARN_ON_ONCE(v) assert(!(v)) @@ -2320,6 +2344,9 @@ def unwind(root): def function(source, name): if name == 'atcphy_mux_set' and 'static int atcphy_mux_set_locked(' in source: return atc_mux_without_pm(source) + if name == 'atcphy_usb3_set_mode': + return atc_set_mode_prototypes(source) + block(source, re.search( + r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) if name in ATC_SPLIT + ATC_T8103_LIVE: return atc_function(source, name) return block(source, re.search(r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) @@ -2336,7 +2363,7 @@ def function(source, name): parts.append(r''' struct apple_atcphy { /* T8132-only paths are covered by drivers/apple/atc-t8132-usb3.py. */ - bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; + bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt, t8132_device; /* A CIO sleep is T8132's too, covered by tools/asahi/atc-cio-sleep-tests.py. */ struct { bool prepared; } cio_sleep; struct { void *usb3_dp, *dp_lioa, *dp_common_config; } tunables; @@ -2348,7 +2375,7 @@ def function(source, name): struct { unsigned char *core, *lpdptx, *lioa; } regs; void *dev; int lock, dp_link_rate; - bool fixed_usb2, host_active, swap_lanes, ss_tunables, dp_tunables; + bool fixed_usb2, fixed_usb3, cio_only, host_active, swap_lanes, ss_tunables, dp_tunables; bool aux_power_requested, mode_dirty, dp_spread_spectrum, dp_presets_valid[5]; u32 dp_presets[5][16]; unsigned int dp_idle_pmas, dp_owned_pmas; @@ -2364,6 +2391,7 @@ def function(source, name): start = atc.index('static const struct {\n\tconst struct atcphy_mode_configuration normal;') parts.append(atc[start:atc.index('\n};', start) + 3]) parts.append(atc_cio_helpers(atc)) + parts.append(atc_cfg_helpers(atc)) parts.append(r''' struct phy_configure_opts_dp { unsigned int link_rate, lanes, voltage[4], pre[4]; @@ -2424,11 +2452,13 @@ def function(source, name): static int atcphy_power_off(struct apple_atcphy *); static int atcphy_configure(struct apple_atcphy *, enum atcphy_mode); -/* These units exercise older PHY generations. Never accept a T8132 dispatch. */ +/* These units exercise older PHY generations. Never accept a T8132 or T8152 dispatch. */ static int __attribute__((unused)) atcphy_configure_t8132(struct apple_atcphy *p, enum atcphy_mode mode) { (void)p; (void)mode; assert(false); return -EOPNOTSUPP; } static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *p) { (void)p; assert(false); return -EOPNOTSUPP; } +static void __attribute__((unused)) atcphy_lanes_down_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); } static int atcphy_park_pipehandler(struct apple_atcphy *p, bool keep_dp) @@ -2467,7 +2497,11 @@ def function(source, name): #define hweight32(v) __builtin_popcount(v) #define dev_info_once(...) ((void)0) #define dev_dbg(...) ((void)0) +#ifndef dev_info +#define dev_info(...) ((void)0) +#endif #define dev_warn(...) ((void)0) +#define dev_info(...) ((void)0) static void report(void *dev, const char *fmt, ...) { (void)dev; (void)fmt; } #define dev_err report #define lockdep_assert_held(...) ((void)0) @@ -2661,7 +2695,7 @@ def aux(root): #define BIT(n) (1U << (n)) struct apple_atcphy { /* T8132-only paths are covered by drivers/apple/atc-t8132-usb3.py. */ - bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; + bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt, t8132_device; /* A CIO sleep is T8132's too, covered by tools/asahi/atc-cio-sleep-tests.py. */ struct { bool prepared; } cio_sleep; struct { void *usb3_dp, *dp_lioa, *dp_common_config; } tunables; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/pm.py b/tools/testing/selftests/drivers/gpu/apple-dcp/pm.py index 0c403fa4e7c0d1..eacb1b3e40fcaf 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/pm.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/pm.py @@ -570,6 +570,7 @@ def function(text, name): ' struct notifier_block tbt_watch;\n bool tbt_watch_registered;\n', 1) mocks = mocks.replace('static void cd321x_stop_work(struct cd321x *c) {\n', r'''#define INIT_WORK(p,fn) ((p)->pending=false) #define dev_warn(...) ((void)0) +#define dev_info(...) ((void)0) static int watches, watch_error; /* Like the real watch, hold the port fwnode until the port is unregistered. */ static int cd321x_tbt_watch_late(struct cd321x *c,struct fwnode_handle *f) { @@ -783,6 +784,24 @@ def function(text, name): assert controls.count(probed) == 1 controls = controls.replace(probed, probed + ' assert(reboots==1&&c.reboot_nb_registered&&c.reboot_nb.notifier_call==cd321x_reboot_notify);\n', 1) + # Newer trees do not wait for the driver core to give up on a missing router. + if 'cd321x_tbt_switch_keep_waiting(' not in core: + assert late_watch + stub = 'static bool keep_waiting=true;\nstatic bool cd321x_tbt_switch_keep_waiting(struct device *d) { (void)d;return keep_waiting; }\n' + assert mocks.count(stub) == 1 + mocks = mocks.replace(stub, '', 1) + wait = r''' /* Missing router defers while suppliers may still bind, then is optional. */ + reset(&c);switch_error=-EPROBE_DEFER; + assert(cd321x_register_port(&c.tps,&connector)==-EPROBE_DEFER);balanced(); + reset(&c);switch_error=-EPROBE_DEFER;keep_waiting=false; +''' + assert controls.count(wait) == 1 + controls = controls.replace(wait, ''' /* A missing router is optional at once. */ + reset(&c);switch_error=-EPROBE_DEFER; +''', 1) + controls = controls.replace('keep_waiting=true;', '').replace('keep_waiting=false;', '') + assert 'keep_waiting' not in controls + return prefix + pm + mocks + production + '\n#define TEST_DEFER 1\n#define TEST_FWNODE 1\n' + controls diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/quiesce.py b/tools/testing/selftests/drivers/gpu/apple-dcp/quiesce.py index 9257b85dec643c..d78a19800b05bf 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/quiesce.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/quiesce.py @@ -158,7 +158,7 @@ def make_unit(source, parent=False, reference=None): void *dev; int lock; const struct atcphy_hw *hw; struct { void *usb2phy; } regs; - bool fixed_usb2,host_active,mode_dirty,pipe_pending,usb_off_pending,ss_tunables,dp_tunables,cio_tunables,t8132_dp_alt; + bool fixed_usb2,host_active,mode_dirty,pipe_pending,usb_off_pending,ss_tunables,dp_tunables,cio_tunables,t8132_dp_alt,t8132_device; bool usb3_port_off,park_owed,dp_only,pd_was_off; bool t8103_dummy_pending,t8103_usb3_retry,t8103_usb3_workaround; enum atcphy_mode mode,typec_mode; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py index 1df2c17f68a9a9..30eba776e8eee9 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py @@ -98,14 +98,55 @@ def color(i, score, depth, eotf, colorimetry, encoding=0, dynamic=0): pq_raw = bytearray(struct.pack('340 MHz timing (e.g. 1440p144): 8-bit SDR (24 bpp) + # caps non-DSC unsafe PQ to <=24 bpp (12-bit 4:2:2 id 105), rejecting both + # DSC-required PQ (113) and over-budget non-DSC 10-bit RGB PQ (114, 30 bpp). + unsafe_only_fixture = [dict(timing_fixture[0], ColorModes=[ + color(114, 20, 10, 2, 9), color(105, 5, 12, 2, 7, encoding=2), + color(113, 9, 10, 2, 9), color(80, 1, 8, 0, 10)], + UnsafeColorElementIDs=[80, 105, 113, 114], DSCRequiredColorElementIDs=[113])] + unsafe_only_raw = bytearray(struct.pack('340 MHz timing falls back to non-DSC unsafe PQ within + * sdr_unsafe_max_bpp: 24-bpp SDR picks 12-bit 4:2:2 (105) over 30-bpp + * non-DSC RGB (114) and DSC-required RGB (113); 30-bpp SDR picks 114. */ + for (unsigned int dsc = 0; dsc < 2; dsc++) { + assert(!parse(unsafe_only_blob, sizeof(unsafe_only_blob), &c)); + c.pq_dsc = dsc; + m = enumerate_modes(&c, &n, 600, 330, 0, false, false); + assert(!IS_ERR(m) && n == 1 && !m[0].sdr_usable && m[0].sdr_unsafe); + assert(m[0].sdr_unsafe_max_bpp == 24); + assert(m[0].pq.id == 105 && m[0].pq.depth == 12 && + m[0].pq.format == DCP_COLOR_FORMAT_YCBCR422); + free(m); + } + assert(!parse(unsafe_30bpp_blob, sizeof(unsafe_30bpp_blob), &c)); + m = enumerate_modes(&c, &n, 600, 330, 0, false, false); + assert(!IS_ERR(m) && n == 1 && m[0].sdr_unsafe_max_bpp == 30); + assert(m[0].pq.id == 114 && m[0].pq.depth == 10 && + m[0].pq.format == DCP_COLOR_FORMAT_RGB); + free(m); + /* DP-to-HDMI bridge 4K60 DownstreamFormat flags true wire YCbCr 4:2:0 + * (CE 119 SDR, CE 162 PQ) while keeping upstream format intact (CE 80 + * stays in sdr_rgb, CE 83 stays 4:4:4, CE 105 stays 4:2:2). */ + assert(!parse(ds420_blob, sizeof(ds420_blob), &c)); + m = enumerate_modes(&c, &n, 600, 330, 0, false, false); + assert(!IS_ERR(m) && n == 1 && m[0].sdr_usable && + m[0].sdr_rgb.id == 80 && m[0].sdr_rgb.format == DCP_COLOR_FORMAT_RGB && + m[0].sdr_444.id == 83); + { + unsigned int found_420_sdr = 0, found_420_pq = 0, found_444 = 0, found_422 = 0; + for (unsigned int j = 0; j < m[0].nr_colors; j++) { + if (m[0].colors[j].id == 119) { + assert(m[0].colors[j].format == DCP_COLOR_FORMAT_YCBCR444 && + (m[0].colors[j].flags & DCP_COLOR_FLAG_DOWNSTREAM_420) && + !(m[0].colors[j].flags & DCP_COLOR_FLAG_UNSAFE)); + found_420_sdr++; + } else if (m[0].colors[j].id == 162) { + assert(m[0].colors[j].format == DCP_COLOR_FORMAT_YCBCR422 && + (m[0].colors[j].flags & DCP_COLOR_FLAG_DOWNSTREAM_420) && + (m[0].colors[j].flags & DCP_COLOR_FLAG_UNSAFE)); + found_420_pq++; + } else if (m[0].colors[j].id == 83) { + assert(m[0].colors[j].format == DCP_COLOR_FORMAT_YCBCR444 && + !(m[0].colors[j].flags & DCP_COLOR_FLAG_DOWNSTREAM_420)); + found_444++; + } else if (m[0].colors[j].id == 105) { + assert(m[0].colors[j].format == DCP_COLOR_FORMAT_YCBCR422 && + !(m[0].colors[j].flags & DCP_COLOR_FLAG_DOWNSTREAM_420)); + found_422++; + } + } + assert(found_420_sdr == 1 && found_420_pq == 1 && found_444 == 1 && found_422 == 1); + } + free(m); /* The default modes; the timing ID that carries DRM_MODE_TYPE_PREFERRED. */ static const struct { const unsigned char *blob; size_t size; bool internal; u32 id; } d[] = { { default_acer, sizeof(default_acer), false, 2 }, @@ -601,7 +703,7 @@ def case(value, automatic=True, internal=False, external=True, admitted=True): u64 typec_generation; unsigned int nr_modes; struct dcp_display_mode *modes; struct { bool holding, stopped; } announce; - bool ext_backlight, has_panel; + bool ext_backlight, has_panel, iomfb_template_pq; /* External pipes carry no internal panel identity. */ void *panel_identity; }; @@ -769,6 +871,7 @@ def publication(root): state = state.replace(' struct work_struct hotplug_wq, bl_sync_wq;\n};', ' struct work_struct hotplug_wq, bl_sync_wq;\n bool edid_live; unsigned hotplug_reasons;\n};', 1) state = state.replace('u64 typec_generation; unsigned int nr_modes;', '''u64 typec_generation; unsigned int nr_modes; struct apple_epic *dcpavservep; + void *desktop; int fw_compat,width_mm,height_mm,fixed_connector_type; unsigned notch_height; bool modes_lock,modes_admitted,modes_provisional,placeholder_retried,external_native; int external_held; u64 modes_generation,dimensions_generation; struct work_struct dimensions_wq; @@ -826,11 +929,14 @@ def publication(root): static void reinit_completion(int *p) { *p=0; } static struct apple_epic_service *afk_service_get(struct apple_epic_service *s) { if(!s->enabled) return NULL; s->users++; return s; } static void afk_service_put(struct apple_epic_service *s) { assert(s->users); s->users--; } +static void dcp_hdr_service_bind(struct apple_epic_service *s) { (void)s; } +static void dcp_hdr_service_unbind(struct apple_epic_service *s) { (void)s; } static void afk_service_retire(struct apple_epic_service *s) { assert(!*hpd_lock); s->enabled=false; s->torndown=true; } /* These H17P scenarios never queue the native 14.7 Close worker. */ static bool cancel_work_sync(struct work_struct *w) { assert(!w->scheduled); return false; } /* Native audio is out of scope: reject entry instead of silently queueing it. */ static void dcp_external_audio_start(struct apple_dcp *d) { assert(!d->external_native); } +static void av_audio_sink_changed(struct apple_dcp *d) { (void)d; } /* The stubbed read always carries an EDID: nothing asks for a re-probe. */ static bool dcpavserv_edid_retry(struct apple_dcp *d,u64 e) { (void)d;(void)e;assert(0);return false; } static void dcpavserv_edid_retry_reset(struct apple_dcp *d) { assert(d->dcpavserv.lock); } @@ -914,12 +1020,17 @@ def publication(root): static int __attribute__((unused)) dcp_direct_crossbar_link(struct apple_dcp *d,bool up) { (void)d;(void)up;return 0; } ''' transport = '\n'.join(block(av,marker) for marker in [ - 'static void dcpavserv_notify_edid(', 'static bool dcpavserv_identity(', + 'static void dcpavserv_notify_edid(', 'static bool dcpavserv_hdr_class(', + 'static bool dcpavserv_identity(', 'static bool dcpavserv_admission_current(', 'static int dcpavserv_prepare(', 'static void dcpavserv_init(', 'static void dcpavserv_invalidate_edid(', 'static void dcpavserv_teardown(', 'void dpavservep_detach(', 'bool dcpavserv_edid_current(', 'bool dcpavserv_edid_service_current(', ]) + # dcp-fabric.c decides it in the driver; each scenario below defines it. + transport = transport.replace('static bool dcpavserv_admission_current(', + 'static bool dcp_is_typec_output(struct apple_dcp *d);\n' + 'static bool dcpavserv_admission_current(', 1) mode_helpers = iomfb[iomfb.index('static struct dcp_display_mode *dcp_modes_snapshot('):iomfb.index('int dcp_get_modes(')] # The link line of a processor whose hardware description asks for it # (hw.link_report, T6050's external ones): no processor here does. @@ -941,7 +1052,7 @@ def publication(root): + mode_helpers) # The desktop 26.6 VRR filter is gone once that firmware takes adaptive sync. vrr_filter = block(iomfb,'static bool dcp_mode_vrr_supported(')+'\n' if 'static bool dcp_mode_vrr_supported(' in iomfb else '' - publication = block(iomfb,'static void dcp_clear_connector_edid(')+'\n'+block(iomfb,'static void dcp_consume_edid_invalidation(')+mode_helpers+vrr_filter+block(iomfb,'int dcp_get_modes(')+block(iomfb,'bool lookup_mode(') + publication = block(iomfb,'static void dcp_clear_connector_edid(')+'\n'+block(iomfb,'static void dcp_consume_edid_invalidation(')+mode_helpers+vrr_filter+block(iomfb,'int dcp_get_modes(')+block(iomfb,'static const struct dcp_display_mode *\ndcp_find_mode(')+block(iomfb,'bool lookup_mode(') if 'dcp_edid_sdr(' in publication: # Keep extracting the real publication path, including its SDR helper. # Model only kernel allocation/DRM ownership at the host boundary. @@ -1251,8 +1362,10 @@ def panel_dimensions(root): puts("PASS: internal panel dimensions survive repeated EDID clears; firmware size and DT fallback; external EDID size preserved"); } """ + # The panel scenarios model a Type-C output, as the hotplug ones. unit = unit.replace('int main(int argc,char **argv) {', - checks + 'int main(int argc,char **argv) {') + 'static bool dcp_is_typec_output(struct apple_dcp *d) { (void)d; return true; }\n' + + checks + 'int main(int argc,char **argv) {') return unit.replace(' transport_edid=raw;', ' transport_edid=raw;panel_dimension_probes();', 1) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/recovery.py b/tools/testing/selftests/drivers/gpu/apple-dcp/recovery.py index d9c1391897279e..67e9c39e824480 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/recovery.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/recovery.py @@ -360,6 +360,8 @@ def run(name,text,cases): } ''' af=(root/'drivers/gpu/drm/apple/afk.c').read_text() + if 'mutex_lock(&afkep->tx_lock);' in af: + queued=queued.replace('bool lock,stopping;','bool lock,tx_lock,stopping;',1) if 'atomic_inc(&ep->sleep_jobs);' in af: # The receive jobs a firmware sleep waits for; nothing here waits. anchor='struct apple_dcp_afkep { u8 *command_tags;int started,stopped;' diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py index e97977c2e7860e..2d111c5bed9647 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py @@ -61,6 +61,7 @@ def main(): ('audio', 'cec-only-av-endpoint', audio.cec_only_endpoint, ((),), ()), ('display', 'desktop-gamma', desktop.gamma, ((),), ()), ('display', 'hdr-static-metadata', display.hdr_metadata, ((),), ()), + ('display', 'color-mode-selection', display.color_selection, ((),), ()), ('display', 'ctm-encoding', colorimetry.ctm, ((),), ()), ('lifecycle', 'desktop-modeset-unmap', desktop.modeset_unmap, ((),), ()), ('lifecycle', 'desktop-unknown-modeset-recovery', desktop.modeset_unknown, ((),), ()), @@ -91,7 +92,10 @@ def main(): ('m4', 'm4-panel-timing', m4.timing, ((),), ('-Wno-unused-function', '-Wno-unused-const-variable')), ('boot', 'oslog-events', boot.oslog, ((),), ()), ('boot', 'syslog-policy', boot.syslog, ((),), ()), + ('boot', 'v27-panel-handoff', boot.v27_panel_handoff, ((),), ()), ('boot', 't6041-v27-admission', boot.t6041_v27_admission, ((),), ()), + ('boot', 't8122-dcpext-v27-admission', boot.t8122_dcpext_v27_admission, ((),), ()), + ('boot', 'v27-tag-translation', boot.v27_tag_translation, ((),), ()), ('edid', 'dpavserv-start', edid.startup, ((),), ()), ('edid', 'service-rebind', edid.rebind, ((),), ()), ('edid', 'provider-admission', edid.admission, ((),), ()), @@ -175,6 +179,11 @@ def main(): # The T6050 PMP registry-v2 buffer shares endpoint 7. prefix += ('#define apple_rtkit_pmp_aux_rx(...) ' 'assert(!"The PMP auxiliary buffer is outside this ordered-display fixture")\n') + # A display co-processor doesn't take CoreAnalytics buffers. + prefix += '#define apple_rtkit_ep7_served(...) false\n' + # Nor does it receive messages for endpoints it doesn't serve. + prefix += ('#define apple_rtkit_unserved_ep_msg(...) ' + 'assert(!"No unserved endpoint is in this ordered-display fixture")\n') unit = prefix + unit if unit is not None: result['translation_unit_sha256'] = run_unit(name, unit, output, cases, includes if name == 'service-rebind' else (), flags) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/transaction.py b/tools/testing/selftests/drivers/gpu/apple-dcp/transaction.py index 1375b2683f4a44..7e980849060811 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/transaction.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/transaction.py @@ -104,8 +104,9 @@ def check(name, unit, cases=((),), negative=False, flags=()): static int dcp_dptx_connect_oob(void *dev,unsigned n) { (void)dev;(void)n;connect_calls++;display.external_cable=true;display.dptxport[0].connected=true;display.typec_cable_connected=true;connector.connected=true;return 0; } static void dcp_retrain_oob(struct connector *c) { (void)c; } static bool dcp_typec_sink_relink(struct apple_dcp *d) { (void)d;return false; } - /* An M1/M2 crossbar is not the T8142 layout, and an M1/M2 port has no fixed-CRTC connectors. */ + /* An M1/M2 crossbar is not the T8142 or T6041 layout, and an M1/M2 port has no fixed-CRTC connectors. */ static bool dcp_xbar_t8142(struct mux_control *m) { (void)m;return false; } + static bool dcp_xbar_t6041(struct mux_control *m) { (void)m;return false; } static bool dcp_typec_fixed_crtcs(void) { return false; } /* Deactivation retires queued DP IN events and drains their work. */ static int tb_event_cancels; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/usb-retention-control.py b/tools/testing/selftests/drivers/gpu/apple-dcp/usb-retention-control.py index ca9fb3f6e39a95..65e6b636468d34 100755 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/usb-retention-control.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/usb-retention-control.py @@ -19,7 +19,8 @@ def main(): parts = phy.parking(args.source) production = parts["production"] original = block(production, "static int atcphy_usb3_power_off(") - guard = "if (atcphy_modes[atcphy->mode].enable_dp_aux)\n\t\treturn 0;" + guard = ("if (atcphy_modes[atcphy->mode].enable_dp_aux &&\n" + "\t atcphy->hw->gen != ATCPHY_GENERATION_T8132)\n\t\treturn 0;") assert original.count(guard) == 1 mutant = original.replace(guard, "/* negative control: incorrectly cut a live DP link */") units = { diff --git a/tools/testing/selftests/drivers/gpu/asahi-g15/run.py b/tools/testing/selftests/drivers/gpu/asahi-g15/run.py index b0c3105235f7b8..e4c1e92126be8a 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-g15/run.py +++ b/tools/testing/selftests/drivers/gpu/asahi-g15/run.py @@ -114,7 +114,7 @@ pub const UAT_PGSZ: usize = 0x4000; pub const UAT_PGMSK: usize = UAT_PGSZ - 1; pub struct Vm(pub Vec); - pub type VmReadGuard = Vm; + pub type VmReadGuard<'a> = Vm; impl Vm { pub fn read_user(&self, va: u64, out: &mut [u8]) -> Result { let start = usize::try_from(va).map_err(|_| EFAULT)?; @@ -134,7 +134,7 @@ /// cover() calls: the page checks the walk made. pub static COVERS: Cell = Cell::new(0); } - pub fn cover(vm: &mut mmu::VmReadGuard, start: u64, end: u64, _: bool, _: bool) -> Result { + pub fn cover(vm: &mut mmu::VmReadGuard<'_>, start: u64, end: u64, _: bool, _: bool) -> Result { COVERS.with(|c| c.set(c.get() + 1)); if start >= SYNTHETIC { return Ok(()); @@ -260,13 +260,15 @@ def main(): with tempfile.TemporaryDirectory(prefix="asahi-g15-host-") as temp: temp = Path(temp) glue = (G15 / "glue.c").read_text() + # The UAT adoption's helpers, shared with the T8122 runtime. + uat_glue = (G15 / "uat_glue.c").read_text() functions = [] for signature in ["bool asahi_g15_ram_disjoint", "bool asahi_g15_ram_within", "unsigned int asahi_g15_memory_mode"]: marker = signature + "(u64 start, u64 size)\n{" - start = glue.index(marker) - end = glue.index("\n}", start) + 2 - functions.append(glue[start:end]) + start = uat_glue.index(marker) + end = uat_glue.index("\n}", start) + 2 + functions.append(uat_glue[start:end]) c_source = temp / "memory.c" c_source.write_text(MEMORY_PREFIX + "\n".join(functions) + MEMORY_CASES) subprocess.run([os.environ.get("HOSTCC", "cc"), "-std=gnu11", "-Wall", "-Wextra", diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs new file mode 100644 index 00000000000000..a06623ffaa9f2e --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs @@ -0,0 +1,645 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#![allow(dead_code,non_camel_case_types,non_snake_case,non_upper_case_globals,unused_imports)] +// Encodes the same InitData, work items and queue info for the 25G83 and 26B123 firmware +// ABIs with the production encoders, checks the layout catalog, and writes both encodings +// for test-abi-26b123.py's independent offset oracle. +extern crate self as kernel; +pub mod prelude { pub type Result = core::result::Result; pub const E2BIG:i32=7; } +mod uapi {include!("public-uapi.rs");} +mod hw { + pub enum GpuVariant {G, S} + pub mod engine {pub const COMPUTE_SEED:u32=0x100;} + pub mod client {pub const PB_HEAP_SIZE:u64=0x10000000;} + pub(crate) use super::backend_hw::FwAbi; +} +mod fwid { +@FWID_BUILD@ +} +mod adt { + #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/adt/perf.rs"] + pub mod perf; +} +mod board { + #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/board/data.rs"] + pub mod data; +} +#[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/hw.rs"] +mod backend_hw; +#[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/fw/mod.rs"] +mod fw; +#[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/encode.rs"] +mod encode; + +use backend_hw::{FwAbi, LoaderTable, PplMagic, FW_25G83, FW_26B123, PPL_MAGIC, UPPER}; +use fw::initdata::{self as wire, id}; +use fw::work::{compute, fs, ta}; + +const HOST: u64 = wire::HOST_START; + +/// An eleven-row (J773g-sized) table so the encoder fills every performance row. +fn input() -> wire::Input { + let mut p = wire::Performance { + count: 11, + frequency: [0; 11], + auxiliary: [0; 11], + voltage: [0; 11], + sram: [0; 11], + }; + for i in 0..11 { + p.frequency[i] = if i == 0 { 0 } else { 200 + 100 * i as u32 }; + p.auxiliary[i] = if i == 0 { 0 } else { 190 + 100 * i as u32 }; + p.voltage[i] = if i == 0 { 100 } else { 600 + 40 * i as u32 }; + p.sram[i] = 800 + 30 * i as u32; + } + wire::Input { + performance: p, + va: core::array::from_fn(|i| HOST + 0x100000 + i as u64 * 0x100000), + channel_state: core::array::from_fn(|i| HOST + 0x4000000 + i as u64 * 0x10000), + channel_ring: core::array::from_fn(|i| HOST + 0x4004000 + i as u64 * 0x10000), + loader_va: core::array::from_fn(|i| { + if wire::LOADERS[i].length != 0 { + HOST + 0x5000000 + i as u64 * 0x100000 + (wire::LOADERS[i].pa & 0x3fff) + } else { + 0 + } + }), + scratch: HOST + 0xa000000, + lower_uma: wire::BOOTSTRAP_START + 0x200000, + lower_parameter: wire::BOOTSTRAP_START + 0x240000, + ktrace_mask: 0x12345678, + progress_recovery: 1, + enabled_cores: 10, + // T8132 ADT sgx and pmgr/clpc power-sampling and low-peak limiter parameters (24 MHz). + power_sample_clks: 200_000, + power_sample_us: 8333, + power_sample_period_ms: 8, + timebase_khz: 24_000, + avg_power_filter_tc_ms: 248, + lowpeak_limiter_tc_ms: 16, + lowpeak_limiter_ki_q16: 134_217, + lowpeak_limiter_kp_q16: 33_554, + coredump_copy_size: 0x8000, + } +} + +fn initdata(layout: &wire::Layout, ceiling: u32) -> Result, ()> { + let mut buffers: [Vec; wire::OBJECT_COUNT] = + core::array::from_fn(|i| vec![0xa5u8; layout.object_size[i]]); + let mut slices = buffers.each_mut().map(|b| b.as_mut_slice()); + // As `build`: a record the ABI has no slot for is not mapped. + let mut input = input(); + for slot in 0..wire::LOADER_COUNT { + if layout.slot(slot).is_none() { + input.loader_va[slot] = 0; + } + } + wire::encode_for(layout, &mut slices, &input, ceiling)?; + Ok(buffers.into_iter().flatten().collect()) +} + +fn object<'a>(image: &'a [u8], layout: &wire::Layout, object: usize) -> &'a [u8] { + let start: usize = layout.object_size[..object].iter().sum(); + &image[start..start + layout.object_size[object]] +} + +fn r32(b: &[u8], at: usize) -> u32 { u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) } +fn r64(b: &[u8], at: usize) -> u64 { u64::from_le_bytes(b[at..at + 8].try_into().unwrap()) } + +fn render(out: &std::path::Path) { + let f = 0xfffffc2000000000u64; + let g = 0x1000000000u64; + let mut u = uapi::drm_asahi_cmd_render::default(); + u.width_px = 1919; u.height_px = 1079; u.layers = 3; u.samples = 2; + u.utile_width_px = 16; u.utile_height_px = 32; u.sample_size_B = 4; + u.flags = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_RSRC_SPEC_HI; + u.vdm_ctrl_stream_base = g + 0xa00000; + u.zls_ctrl = (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) + | (1 << 5) | (1 << 6) | (1 << 7) | (1 << 8) + | (1 << 14) | (1 << 15) | (1 << 18) | (1 << 19); + u.depth.base = g + 0xe00000; + u.depth.stride = (2 << 14) | 1; + u.depth.comp_base = g + 0xe80000; + u.depth.comp_stride = 3 << 14; + u.stencil.base = g + 0xf00000; + u.stencil.stride = (1 << 14) | 1; + u.stencil.comp_base = g + 0xf80000; + u.stencil.comp_stride = 2 << 14; + u.bg.usc = 0x10000; u.eot.usc = 0x20000; + let r = encode::RenderRefs { + notifier: f + 0x800000, qinfo: [f + 0xf00000, f + 0x1000000], + user_stamp: [f + 0x800620, f + 0x800630], fw_stamp: [f + 0x4000000, f + 0x4004000], + uma_mgr: [f + 0x300000, f + 0x300000], uma_aux: [f + 0x300100, f + 0x300200], + uma_gpu: g + 0x6000000, pb_mgr: f + 0x3000000, scene_list: g + 0x500000, + parameter_id: 3, generation: 254, activity: [f + 0x900004, f + 0xa00008], + counter: [4, 3], uma_submitted: 4, uuid: 0x123401, usc_base: 1 << 40, + ..Default::default() + }; + let p = encode::PassRefs { + ta_work: f + 0xb00000, ta_work_gva: g + 0x7000000, fs_work: f + 0xc00000, + fs_work_gva: g + 0x8000000, ta_seq: f + 0xd00000, fs_seq: f + 0xe00000, + scene: f + 0x100000, tpc_gva: g + 0x200000, tpc_fw: f + 0x3200000, + tilemap_gva: g + 0x100000, heap_gva: g + 0x300000, scene_user_gva: g + 0x900000, + scratch_fw: f + 0x200000, pre_gva: [g + 0x600000, g + 0x700000, g + 0x800000], + aux_gva: g + 0xb00000, ..Default::default() + }; + let geo = encode::Geometry::new(&u, p.heap_gva); + assert_eq!(geo.isp_control, 0xc000); + let mut u_few = u; + u_few.flags |= uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FEW_PRIMITIVES; + let geo_few = encode::Geometry::new(&u_few, p.heap_gva); + assert_eq!(geo_few.isp_control, 0xc001); + let mut u_few_dbias = u_few; + u_few_dbias.flags |= uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_DBIAS_IS_INT; + assert_eq!(encode::Geometry::new(&u_few_dbias, p.heap_gva).isp_control, 0x4c001); + let ts = [f + 0xffc000100, 0, 0, f + 0xffc000118]; + let mut images = Vec::new(); + for (ta_layout, fs_layout) in [(&ta::V25G83, &fs::V25G83), (&ta::V26B123, &fs::V26B123)] { + let mut tw = [0xa5; ta::WORK_SIZE]; let mut tq = [0xa5; ta::SEQ_SIZE]; + let mut fw_ = [0xa5; fs::WORK_SIZE]; let mut fq = [0xa5; fs::SEQ_SIZE]; + encode::encode_ta_for(ta_layout, &r, &p, &u, &ts, 7, 0x300, &geo, None, &mut tw, &mut tq); + encode::encode_fs_for(fs_layout, &r, &p, &u, &ts, 7, 1 << 40, 1, 0x300, &geo, &mut fw_, &mut fq); + // Verify FEW_PRIMITIVES sets bit 0 of ISP register 0x15021 (fs::SEL[21]). + let mut fw_few = [0xa5; fs::WORK_SIZE]; + let mut fq_few = [0xa5; fs::SEQ_SIZE]; + encode::encode_fs_for( + fs_layout, &r, &p, &u_few, &ts, 7, 1 << 40, 1, 0x300, &geo_few, + &mut fw_few, &mut fq_few, + ); + assert_eq!(r32(&fw_few, fs::REGS + 21 * 12), 0x15021); + assert_eq!(r64(&fw_few, fs::REGS + 21 * 12 + 4), 0xc001); + images.push((tw, tq, fw_, fq)); + } + // The 25G83 entry points are the 25G83 layouts. + let (mut tw, mut tq) = ([0; ta::WORK_SIZE], [0; ta::SEQ_SIZE]); + let (mut fw_, mut fq) = ([0; fs::WORK_SIZE], [0; fs::SEQ_SIZE]); + encode::encode_ta(&r, &p, &u, &ts, 7, 0x300, &geo, None, &mut tw, &mut tq); + encode::encode_fs(&r, &p, &u, &ts, 7, 1 << 40, 1, 0x300, &geo, &mut fw_, &mut fq); + assert!(tw == images[0].0 && tq == images[0].1 && fw_ == images[0].2 && fq == images[0].3); + let (ref tw, ref tq, ref fw_, ref fq) = images[1]; + assert_eq!(r64(tw, 0x917), 254, "TA generation is a u64 at 0x917"); + assert_eq!(r64(tq, ta::FINALIZE + 0x85), p.ta_work + 0x91f); + for record in [ta::TS_START, ta::TS_END] { + assert_eq!(r64(tq, record + 0x2c), p.ta_work + 0x92f); + } + assert_eq!(r64(fw_, 0xc5f), 254, "FS generation is a u64 at 0xc5f"); + assert_eq!((fw_[0xc84], fw_[0xc8b]), (0, 1), "FS flag moved to 0xc8b"); + assert_eq!(r64(fq, fs::FINALIZE + 0xa5), p.fs_work + 0xc67); + for record in [fs::TS_START, fs::TS_END] { + assert_eq!(r64(fq, record + 0x2c), p.fs_work + 0xc77); + } + // The 26B123 timestamp op stores two u64s after the completion target: host-free. + assert!(tw[0x927..0x937].iter().all(|&b| b == 0)); + assert!(fw_[0xc6f..0xc7f].iter().all(|&b| b == 0)); + // Compressed ZLS register records (fs::SEL[44..52]) and JobParameters3 mirrors. + let expected_zls_regs = [ + (44, 0x153c1u32, u.depth.comp_base), + (45, 0x15411, u64::from(u.depth.comp_stride)), + (46, 0x153c9, u.depth.comp_base), + (47, 0x15431, u64::from(u.depth.comp_stride)), + (48, 0x153d1, u.stencil.comp_base), + (49, 0x15419, u64::from(u.stencil.comp_stride)), + (50, 0x153d9, u.stencil.comp_base), + (51, 0x15439, u64::from(u.stencil.comp_stride)), + ]; + for (_, _, fw_img, _) in &images { + for &(slot, sel, val) in &expected_zls_regs { + let at = fs::REGS + slot * 12; + assert_eq!(r32(fw_img, at), sel); + assert_eq!(r64(fw_img, at + 4), val); + } + assert_eq!(r64(fw_img, 0x938), u.zls_ctrl); + assert_eq!(r64(fw_img, 0x958), u64::from(u.depth.comp_stride)); + assert_eq!(r64(fw_img, 0x970), u.depth.comp_base); + assert_eq!(r64(fw_img, 0x988), u64::from(u.stencil.comp_stride)); + assert_eq!(r64(fw_img, 0x9a0), u.stencil.comp_base); + } + // Clean same-VM reuse overwrites only 0..HEAD_ACTIVE_SIZE and TAIL_ACTIVE_START..WORK_SIZE; + // verify an uncompressed pass leaves no stale compressed ZLS register or mirror values. + let mut plain = u; + plain.zls_ctrl = 0; + plain.depth = Default::default(); + plain.stencil = Default::default(); + let mut plain_fw = [0xa5; fs::WORK_SIZE]; + let mut plain_fq = [0xa5; fs::SEQ_SIZE]; + encode::encode_fs_for( + &fs::V26B123, &r, &p, &plain, &ts, 7, 1 << 40, 2, 0x400, &geo, + &mut plain_fw, &mut plain_fq, + ); + let mut reused = *fw_; + reused[..fs::HEAD_ACTIVE_SIZE].copy_from_slice(&plain_fw[..fs::HEAD_ACTIVE_SIZE]); + reused[fs::TAIL_ACTIVE_START..].copy_from_slice(&plain_fw[fs::TAIL_ACTIVE_START..]); + for &(slot, sel, _) in &expected_zls_regs { + let at = fs::REGS + slot * 12; + assert_eq!(r32(&reused, at), sel); + assert_eq!(r64(&reused, at + 4), 0); + } + for off in [0x938usize, 0x958, 0x970, 0x988, 0x9a0] { + assert_eq!(r64(&reused, off), 0); + } + for (name, (tw, tq, fw_, fq)) in ["25g83", "26b123"].iter().zip(&images) { + let mut all = tw.to_vec(); all.extend(tq); all.extend(fw_); all.extend(fq); + std::fs::write(out.join(format!("render-{name}.bin")), all).unwrap(); + } +} + +fn compute_work(out: &std::path::Path) { + let f = 0xfffffc2000000000u64; + let g = 0x1000000000u64; + let r = encode::ComputeRefs { + notifier: f + 0x600400, qinfo: f + 0x200000, user_stamp: f + 0x600648, + fw_stamp: f + 0x600640, work: f + 0x100000, work_gva: g + 0x100000, seq: f + 0x100900, + descriptor_fw: 0, preempt_gva: g + 0x200000, its: f + 0x500040, stats_fw: f + 0x300000, + auxiliary_fw: f + 0x400000, auxiliary_gva: g + 0x400000, + context_store_gva: g + 0x500000, counter_fw: f + 0x500000, + pool_state_gva: g + 0x600000, page_list_gva: g + 0x700000, usc_base: 1 << 40, + record_fw: f + 0x700000, binding_generation: 200, uma_slot: 3, command_id: 9, + compute_index: 8, work_818: 0, target_stamp: 0x900, submitted: 5, event: compute::EVENT, + }; + let c = uapi::drm_asahi_cmd_compute { + cdm_ctrl_stream_base: g + 0x300000, cdm_ctrl_stream_end: g + 0x300200, + ..Default::default() + }; + let att = [uapi::drm_asahi_attachment { pointer: g + 0x50000000, size: 137, ..Default::default() }]; + let ts = [0xfffffc2ffc000100, 0]; + let mut images = Vec::new(); + for layout in [&compute::V25G83, &compute::V26B123] { + let mut w = [0xa5; compute::WORK_SIZE]; let mut q = [0xa5; compute::SEQ_SIZE]; + encode::encode_compute_for(layout, &r, &c, &att, &ts, 1, 1, 1, &mut w, &mut q).unwrap(); + images.push((w, q)); + } + let (mut w, mut q) = ([0; compute::WORK_SIZE], [0; compute::SEQ_SIZE]); + encode::encode_compute(&r, &c, &att, &ts, 1, 1, 1, &mut w, &mut q).unwrap(); + assert!(w == images[0].0 && q == images[0].1); + let (ref w, ref q) = images[1]; + assert_eq!(r64(w, 0x88b), 200, "compute generation is a u64 at 0x88b"); + assert_eq!(r64(q, 0x1a8), r.work + 0x8b3); + assert_eq!(r64(q, compute::FINALIZE + 0x69), r.work + 0x8b3); + assert_eq!(r64(q, compute::FINALIZE + 0x71), r.work + 0x893); + for record in [compute::TS_START, compute::TS_END] { + assert_eq!(r64(q, record + 0x2c), r.work + 0x8a3); + } + assert!(w[0x89b..0x8ab].iter().all(|&b| b == 0)); + assert!(w[0x8e0..compute::SEQ_EMBEDDED].iter().all(|&b| b == 0), "beyond the cached prefix"); + assert_eq!(&w[compute::SEQ_EMBEDDED..compute::SEQ_EMBEDDED + compute::SEQ_SIZE], &q[..]); + // Separate uncached descriptor_fw: work+0x86a and seq+0x160 point to descriptor_fw, + // compute_uma_manager_image matches the embedded descriptor layout, and displaced-reuse + // validation checks manager::INDEX against r.uma_slot. + let r_sep = encode::ComputeRefs { descriptor_fw: f + 0x580000, ..r }; + let (mut w_sep, mut q_sep) = ([0xa5; compute::WORK_SIZE], [0xa5; compute::SEQ_SIZE]); + encode::encode_compute_for( + &compute::V26B123, &r_sep, &c, &att, &ts, 1, 1, 1, &mut w_sep, &mut q_sep, + ).unwrap(); + assert_eq!(r64(&w_sep, 0x86a), r_sep.descriptor_fw, "work descriptor pointer at +0x86a"); + assert_eq!(r64(&q_sep, 0x160), r_sep.descriptor_fw, "seq descriptor pointer at +0x160"); + let mut desc = fw::buffer::compute_uma_manager_image( + r_sep.work, r_sep.uma_slot, r_sep.pool_state_gva, r_sep.page_list_gva, + r_sep.counter_fw, 8192, fw::graph::manager::UNK_1C_VALUE, + ); + assert_eq!(&desc[..], &w[compute::DESCRIPTOR..compute::DESCRIPTOR + compute::DESCRIPTOR_SIZE]); + desc[fw::graph::manager::COMPLETED..fw::graph::manager::COMPLETED + 8] + .copy_from_slice(&(r_sep.submitted - 1).to_le_bytes()); + assert_eq!( + encode::validate_compute_descriptor(&r_sep, &desc, r_sep.submitted - 1), + Ok(r_sep.submitted), + ); + let mut bad_idx = desc; + bad_idx[fw::graph::manager::INDEX..fw::graph::manager::INDEX + 4] + .copy_from_slice(&(r_sep.uma_slot + 1).to_le_bytes()); + assert!(encode::validate_compute_descriptor(&r_sep, &bad_idx, r_sep.submitted - 1).is_err()); + for (name, (w, q)) in ["25g83", "26b123"].iter().zip(&images) { + let mut all = w.to_vec(); all.extend(q); + std::fs::write(out.join(format!("compute-{name}.bin")), all).unwrap(); + } +} + +fn queues(out: &std::path::Path) { + let f = 0xfffffc2000000000u64; + let args = (f + 0x100000, f + 0x200000, f + 0x400000, f + 0x300000, f + 0x500000); + let v25 = fw::graph::queue_image_for(FwAbi::V25G83.qinfo(), args.0, args.1, args.2, args.3, args.4); + assert_eq!(v25, fw::graph::queue_image(args.0, args.1, args.2, args.3, args.4)); + let v26 = fw::graph::queue_image_for(FwAbi::V26B123.qinfo(), args.0, args.1, args.2, args.3, args.4); + assert_eq!(r64(&v26, 0x18), args.3 + 0x80, "scratch after the 0x80 header"); + assert_eq!((r32(&v26, 0x44), r32(&v26, 0x48)), (2, u32::MAX)); + assert_eq!(r64(&v26, 0x78), args.4, "aligned scheduling context"); + assert!(v26[0x80..].iter().all(|&b| b == 0)); + let mut all = v25.to_vec(); all.extend(v26); + std::fs::write(out.join("queue.bin"), all).unwrap(); +} + +mod ring_test { + use super::fw::{channels::STATE_READ, initdata::TxLayout}; + use std::sync::Arc; + + type Result = std::result::Result; + pub(crate) struct FwObject([u32; 5]); + impl FwObject { + fn r32(&self, offset: usize) -> Result { + self.0.get(offset / 4).copied().ok_or(()) + } + } + @RING@ + + pub(super) fn check(tx: TxLayout, submit: u32, control: u32) { + let state = Arc::new(FwObject([2, 0, 5, 0, 7])); + for (is_control, expected) in [(false, submit), (true, control)] { + let ring = Ring::new(state.clone(), state.clone(), tx, is_control); + assert_eq!(ring.completion(), Ok(expected)); + } + } +} + +fn g15s_26b123() { + let f = 0xfffffc2000000000u64; + let g = 0x1000000000u64; + // The word after the slot ID selects the hardware bank. + let pb = fw::buffer::pb_manager_image_for( + FwAbi::V26B123G15S.pb_manager(), + 3, + f + 0x400000, + g + 0x701a040000, + f + 0x500000, + f + 0x600000, + f + 0x700000, + 512, + ); + assert_eq!((r32(&pb, 0x08), r32(&pb, 0x0c)), (3, 0)); + assert_eq!(r64(&pb, 0x1c), f + 0x400000); + assert_eq!(r64(&pb, 0x24), g + 0x701a040000); + assert_eq!( + (r32(&pb, 0x2c), r32(&pb, 0x30), r32(&pb, 0x34), r32(&pb, 0x38)), + (0x8000, 2048, 4096, 512) + ); + assert_eq!((r64(&pb, 0x40), r64(&pb, 0x48)), (f + 0x500000, f + 0x600000)); + assert_eq!((r32(&pb, 0x50), r32(&pb, 0x54)), (2047, 0x20000)); + assert_eq!(r64(&pb, 0x60), f + 0x700000); + assert_eq!((r32(&pb, 0x78), r32(&pb, 0x7c)), (2048, 2048)); + + // QINFO: G15S 26B123 has 0x88 header with trailing u64 4 at +0x80. + let qi = fw::graph::queue_image_for( + FwAbi::V26B123G15S.qinfo(), + f + 0x100000, f + 0x200000, f + 0x400000, f + 0x300000, f + 0x500000, + ); + assert_eq!(r64(&qi, 0x18), f + 0x300088); + assert_eq!(r64(&qi, 0x78), f + 0x500000); + assert_eq!(r64(&qi, 0x80), 4); + + // 2-cluster G15S render geometry, 74-reg TA, 82-reg FS, and 0x340 FS microsequence. + let mut u = uapi::drm_asahi_cmd_render::default(); + u.width_px = 640; u.height_px = 480; u.layers = 1; u.samples = 1; + u.utile_width_px = 32; u.utile_height_px = 32; u.sample_size_B = 4; + u.vdm_ctrl_stream_base = g + 0xa00000; + u.isp_merge_upper_x = 0x3b213cfb; + u.isp_merge_upper_y = 0x3ba13cfb; + let r = encode::RenderRefs { + notifier: f + 0x800000, qinfo: [f + 0xf00000, f + 0x1000000], + user_stamp: [f + 0x800620, f + 0x800630], fw_stamp: [f + 0x4000000, f + 0x4004000], + uma_mgr: [f + 0x300000, f + 0x300000], uma_aux: [f + 0x300100, f + 0x300200], + uma_gpu: g + 0x6000000, pb_mgr: f + 0x3000000, scene_list: g + 0x500000, + pb_init_blocks: 512, parameter_id: 6, generation: 254, + activity: [f + 0x900004, f + 0xa00008], counter: [4, 3], uma_submitted: 4, + uuid: 0x123401, usc_base: 1 << 40, ..Default::default() + }; + let p = encode::PassRefs { + ta_work: f + 0xb00000, ta_work_gva: g + 0x7000000, fs_work: f + 0xc00000, + fs_work_gva: g + 0x8000000, ta_seq: f + 0xd00000, fs_seq: f + 0xe00000, + scene: f + 0x100000, tpc_gva: g + 0x200000, tpc_fw: f + 0x3200000, + tilemap_gva: g + 0x100000, heap_gva: g + 0x300000, scene_user_gva: g + 0x900000, + scratch_fw: f + 0x200000, pre_gva: [g + 0x600000, g + 0x700000, g + 0x800000], + aux_gva: g + 0xb00000, ..Default::default() + }; + let geo1 = encode::Geometry::new(&u, p.heap_gva); + let geo2 = encode::Geometry::new_for(&u, p.heap_gva, 2, 15); + assert_eq!(geo2.tpc_bytes, 2 * geo1.tpc_bytes); + assert_eq!(geo2.native_tiles & 0xfffff, 0x36011); + let (mut tw, mut tq) = ([0xa5; ta::WORK_SIZE], [0xa5; ta::SEQ_SIZE]); + let (mut fw_, mut fq) = ([0xa5; fs::WORK_SIZE], [0xa5; fs::SEQ_SIZE]); + encode::encode_ta_for( + FwAbi::V26B123G15S.ta(), &r, &p, &u, &[0; 4], 7, 0x300, &geo2, None, &mut tw, &mut tq, + ); + encode::encode_fs_for( + FwAbi::V26B123G15S.fs(), &r, &p, &u, &[0; 4], 7, 1 << 40, 1, 0x300, &geo2, &mut fw_, + &mut fq, + ); + let att = [uapi::drm_asahi_attachment { + pointer: g + 0x50000000, size: 128, ..Default::default() + }]; + encode::render_attachments_for(&mut fq[..], 1, FwAbi::V26B123G15S.fs().finalize, &att); + assert_eq!(u16::from_le_bytes(tw[0x748..0x74a].try_into().unwrap()), 74); + assert_eq!(r64(&tw, 0x760), p.tpc_gva); + assert_eq!(r32(&tw, ta::REGS + 52 * 12), 0x12099); + assert_eq!(r32(&tw, ta::REGS + 65 * 12), 0xa5a1); + assert_eq!(r64(&tw, ta::REGS + 65 * 12 + 4), 0x7f00400020); + assert_eq!(tq[ta::FINALIZE + 0x8d], 0); + assert_eq!(u16::from_le_bytes(fw_[0x788..0x78a].try_into().unwrap()), 82); + assert_eq!(r32(&fw_, 0x1c), 0x340); + assert_eq!( + (r32(&fw_, 0x48), r32(&fw_, 0x68), r32(&fw_, 0x6c)), + (0x88, u.isp_merge_upper_x, u.isp_merge_upper_y) + ); + assert_eq!(r32(&fw_, fs::REGS + 61 * 12), 0x120a1); + assert_eq!(r32(&fw_, fs::REGS + 77 * 12), 0xa5a9); + assert_eq!(r64(&fw_, fs::REGS + 77 * 12 + 4), 0x9f00400020); + assert_eq!(r64(&fq, 0x34), p.scene + 0x4c); + assert_eq!((r32(&fq, 0x1e4), r32(&fq, 0x230), r32(&fq, 0x234)), (0x80000003, 1, 3)); + assert_eq!(r32(&fq, 0x280), 8); + assert_eq!(fq[0x280 + 0xa4], 1); + assert_eq!(r64(&fq, 0x280 + 0xa5), p.fs_work + 0xc67); + assert_eq!((r32(&fq, 0x280 + 0xad), r32(&fq, 0x280 + 0xb4)), (0x71, 0x40000002)); + + // G15S 26B123 compute: 25 regs (+0x12091, no 0x10071), pre+0x1b80, 2-cluster context store. + let cr = encode::ComputeRefs { + notifier: f + 0x600400, qinfo: f + 0x200000, user_stamp: f + 0x600648, + fw_stamp: f + 0x600640, work: f + 0x100000, work_gva: g + 0x100000, seq: f + 0x100900, + descriptor_fw: 0, preempt_gva: g + 0x200000, its: f + 0x500040, stats_fw: f + 0x300000, + auxiliary_fw: f + 0x400000, auxiliary_gva: g + 0x400000, + context_store_gva: g + 0x500000, counter_fw: f + 0x500000, + pool_state_gva: g + 0x600000, page_list_gva: g + 0x700000, usc_base: 1 << 40, + record_fw: f + 0x700000, binding_generation: 200, uma_slot: 3, command_id: 9, + compute_index: 8, work_818: 0, target_stamp: 0x900, submitted: 5, event: compute::EVENT, + }; + let cc = uapi::drm_asahi_cmd_compute { + cdm_ctrl_stream_base: g + 0x300000, cdm_ctrl_stream_end: g + 0x300200, + ..Default::default() + }; + let (mut cw, mut cq) = ([0xa5; compute::WORK_SIZE], [0xa5; compute::SEQ_SIZE]); + encode::encode_compute_for( + FwAbi::V26B123G15S.compute(), &cr, &cc, &[], &[0; 2], 1, 1, 1, &mut cw, &mut cq, + ).unwrap(); + assert_eq!(u16::from_le_bytes(cw[0x728..0x72a].try_into().unwrap()), 25); + assert_eq!(r64(&cw, compute::REGS + 2 * 12 + 4), cr.preempt_gva + 0x1b80); + assert_eq!(r32(&cw, compute::REGS + 8 * 12), 0x12091); + assert_eq!(r32(&cw, compute::REGS + 9 * 12), 0x101d9); + assert_eq!(r32(&cw, compute::REGS + 24 * 12), 0xa351); + assert_eq!((r64(&cw, 0x873), r64(&cw, 0x87b)), (0x31cc000, 0x2308000)); + assert_eq!( + (r64(&cq, 0x188), r64(&cq, 0x190), r64(&cq, 0x198), r64(&cq, 0x1a0)), + ( + cr.context_store_gva, + cr.context_store_gva + 0x1e400, + cr.context_store_gva + 0x3c800, + cr.context_store_gva + 0x3d800, + ) + ); +} + +fn catalog() { + // Handoff selection and what a 26B123 start still needs. + assert!(FW_25G83.matches(1, &[UPPER, UPPER + 0x60000], &[1, 0])); + assert!(FW_26B123.matches(2, &[UPPER, UPPER + 0x64000, UPPER + 0x134000], &[1, 0x10, 0])); + assert!(!FW_25G83.matches(2, &[UPPER, UPPER + 0x64000, UPPER + 0x134000], &[1, 0x10, 0])); + assert!(!FW_26B123.matches(2, &[UPPER, UPPER + 0x64000], &[1, 0x10])); + assert_eq!((FW_25G83.abi, FW_26B123.abi), (FwAbi::V25G83, FwAbi::V26B123)); + assert_eq!(FW_25G83.unknown().count(), 0); + // Nothing known to be missing refuses a 26B123 start any more. + let unknown: Vec<_> = FW_26B123.unknown().collect(); + assert!(unknown.is_empty(), "{unknown:?}"); + assert_eq!(FW_25G83.loader_table, Some(LoaderTable::Host(0x1332f0))); + assert_eq!(FW_26B123.loader_table, Some(LoaderTable::Firmware)); + assert_eq!(PPL_MAGIC, 0x4b1d000000000002); + assert_eq!(FW_25G83.ppl_magic, Some(PplMagic { ap: PPL_MAGIC, firmware: PPL_MAGIC, answers: false })); + assert_eq!(FW_26B123.ppl_magic, Some(PplMagic { ap: 0x4b1d000000000003, firmware: 0x4b1d000000000003, answers: true })); + // The 26B123 firmware builds its own page-table tree: the boot loader builds no leaf. + assert_eq!(FW_25G83.leaves.map(|l| l.len()), Some(5)); + assert_eq!(FW_26B123.leaves.map(|l| l.len()), Some(0)); + // Device control. + let (a, b) = (FwAbi::V25G83.devctl(), FwAbi::V26B123.devctl()); + assert_eq!((a.import_globals, a.start, a.nop, a.grow_reply), (0x34, 0x0a, 0x1a, 7)); + assert_eq!((b.import_globals, b.start, b.nop, b.grow_reply), (0x35, 0x0a, 0x19, 7)); + // FirmwareData, selectors, register map. + let (v25, v26) = (FW_25G83.initdata, FW_26B123.initdata); + let (d25, d26) = (&v25.firmware_data, &v26.firmware_data); + assert_eq!((d25.fwctl, d25.generation, d25.phase, d25.scheduler, d25.snapshot), (0x4f88, 0x4fa0, 0x4fb0, 0x4fd4, 0x40b8)); + assert_eq!((d26.fwctl, d26.generation, d26.phase, d26.scheduler, d26.snapshot), (0x5168, 0x5180, 0x5190, 0x51b4, 0x4298)); + assert_eq!(d25.snapshot + d25.snapshot_entries * 8, 0x4eb8); + assert_eq!(v25.pstate_selectors, [0x88, 0x8c, 0x98]); + assert_eq!(v26.pstate_selectors, [0x8c, 0x90, 0x9c]); + for (i, &at) in v25.pstate_selectors.iter().enumerate() { + assert_eq!(wire::remap(v26.globals, at, 4), Ok(v26.pstate_selectors[i])); + } + assert_eq!((v25.loader_records(), v26.loader_records()), (42, 47)); + assert_eq!((v25.register_slots, v26.register_slots), (53, 60)); + assert_eq!((v25.power_config, v26.power_config), (0x469, 0x479)); + assert_eq!(v25.object_size, wire::OBJECT_SIZE); + // Words whose 26B123 position is not known are refused rather than guessed. + assert_eq!(wire::remap(v26.main, 0x25b8, 4), Err(())); + assert_eq!(wire::remap(v26.main, 0xebc, 4), Err(())); + assert_eq!(wire::remap(v26.main, 0x700, 4), Err(()), "the register map is slot-mapped"); + assert_eq!(wire::remap(v26.power_performance, 0x2e00, 4), Err(())); + assert_eq!(wire::remap(v26.power_performance, 0x62c8, 4), Err(())); + assert_eq!(wire::remap(v26.globals, 0x36, 4), Err(()), "a field may not straddle an insert"); + // A mapped record this ABI has no slot for refuses the encoding. + let mut no_slot = wire::Layout { name: "test", ..wire::V26B123 }; + no_slot.loader_slot[3] = None; + let mut buffers: [Vec; wire::OBJECT_COUNT] = + core::array::from_fn(|i| vec![0xa5u8; no_slot.object_size[i]]); + let mut slices = buffers.each_mut().map(|b| b.as_mut_slice()); + assert!(wire::encode_for(&no_slot, &mut slices, &input(), 10).is_err()); + // The protected power-transition block (logical 36) has no 26B123 slot: slot 41 stays empty. + let v26 = initdata(&wire::V26B123, 10).unwrap(); + let main = object(&v26, &wire::V26B123, id::MAIN); + assert!(main[0x640 + 41 * 0x28..0x640 + 42 * 0x28].iter().all(|&b| b == 0)); + let mut past_map = wire::Layout { name: "test", ..wire::V26B123 }; + past_map.loader_slot[41] = Some(60); + assert!(initdata(&past_map, 10).is_err()); + // Missing or zero ADT power-sampling / limiter / coredump inputs must fail closed without writing. + for bad_case in 0..10 { + let mut inp = input(); + for slot in 0..wire::LOADER_COUNT { + if wire::V26B123.slot(slot).is_none() { + inp.loader_va[slot] = 0; + } + } + match bad_case { + 0 => inp.power_sample_clks = 0, + 1 => inp.power_sample_us = 0, + 2 => inp.avg_power_filter_tc_ms = 0, + 3 => inp.power_sample_period_ms = 0, + 4 => inp.timebase_khz = 0, + 5 => inp.lowpeak_limiter_tc_ms = 0, + 6 => inp.lowpeak_limiter_ki_q16 = 0, + 7 => inp.lowpeak_limiter_kp_q16 = 0, + 8 => inp.coredump_copy_size = 0, + _ => inp.coredump_copy_size = 0x8001, + } + let mut buffers: [Vec; wire::OBJECT_COUNT] = + core::array::from_fn(|i| vec![0xa5u8; wire::V26B123.object_size[i]]); + let mut slices = buffers.each_mut().map(|b| b.as_mut_slice()); + assert!(wire::encode_for(&wire::V26B123, &mut slices, &inp, 10).is_err()); + assert!(buffers.iter().all(|b| b.iter().all(|&x| x == 0xa5))); + } + // Compile-time layout checker must reject policy words colliding with remapped 25G83 words, + // pstate selectors, or ADT-derived sampling/limiter slots. + assert!(wire::layout_fits(&wire::V25G83) && wire::layout_fits(&wire::V26B123)); + let mut bad_power = wire::Layout { name: "test", ..wire::V26B123 }; + bad_power.power_policy = &[(0x2a64, 1)]; // collides with remapped 25G83 0x2a3c ceiling word + assert!(!wire::layout_fits(&bad_power)); + bad_power.power_policy = &[(0x29e4, 1)]; // collides with power_sampling.filter[0] + assert!(!wire::layout_fits(&bad_power)); + bad_power.power_policy = &[(0xa80, 1)]; // collides with power_limiter.filter_periods_x4 + assert!(!wire::layout_fits(&bad_power)); + let mut bad_globals = wire::Layout { name: "test", ..wire::V26B123 }; + bad_globals.globals_policy = &[(0x8c, 1)]; // collides with pstate_selectors[0] + assert!(!wire::layout_fits(&bad_globals)); + bad_globals.globals_policy = &[(0x7c, 1)]; // collides with remapped 25G83 0x78 + assert!(!wire::layout_fits(&bad_globals)); + let mut bad_main = wire::Layout { name: "test", ..wire::V26B123 }; + bad_main.main_policy = &[(0xfa8, 1)]; // collides with coredump_copy + assert!(!wire::layout_fits(&bad_main)); + bad_main.main_policy = &[(0x640, 1)]; // collides with register map + assert!(!wire::layout_fits(&bad_main)); + bad_main.main_policy = &[(0x2778, 1)]; // collides with remapped 25G83 0x2654 + assert!(!wire::layout_fits(&bad_main)); + bad_main.main_policy = &[(0x2786, 1)]; // overflows MAIN (0x2788) + assert!(!wire::layout_fits(&bad_main)); +} + +fn main() { + let out = std::path::PathBuf::from(std::env::args().nth(1).unwrap()); + catalog(); + let v25 = initdata(&wire::V25G83, 10).unwrap(); + // The 25G83 entry point is the 25G83 layout. + let mut buffers = wire::OBJECT_SIZE.map(|size| vec![0xa5u8; size]); + let mut slices = buffers.each_mut().map(|b| b.as_mut_slice()); + wire::encode(&mut slices, &input(), 10).unwrap(); + assert_eq!(buffers.concat(), v25); + let v26 = initdata(&wire::V26B123, 10).unwrap(); + let l = &wire::V26B123; + assert_eq!(r64(object(&v26, l, id::ROOT), 0), 0x0c8a836f039204b8); + let runtime = object(&v26, l, id::RUNTIME); + assert_eq!(r64(runtime, 0x479), input().va[id::POWER_PERFORMANCE]); + assert!(runtime[0x469..0x479].iter().all(|&b| b == 0)); + let data = object(&v26, l, id::FIRMWARE_DATA); + assert_eq!((r64(data, 0x5168), r64(data, 0x5170), r32(data, 0x51b4)), + (input().va[id::FWCTL], input().va[id::FWCTL] + 0x40, 1)); + let main = object(&v26, l, id::MAIN); + // 26B123: no retention pointer in MAIN, the crash copy buffer size at 0xfa8, and the + // RETENTION object at RUNTIME +0x2c8. + assert_eq!(r64(main, 0xfa0), 0); + assert_eq!(r64(main, 0xfa8), input().coredump_copy_size); + assert_eq!(r32(main, 0x277e), 1); + assert_eq!(r64(object(&v26, l, id::RUNTIME), 0x2c8), input().va[id::RETENTION]); + // CRE (25G83 slot 28) is register-map slot 33 in 26B123. + assert_eq!(r64(main, 0x640 + 33 * 0x28), 0x300d58000); + assert!(main[0x640 + 28 * 0x28..0x640 + 29 * 0x28].iter().all(|&b| b == 0)); + let power = object(&v26, l, id::POWER_PERFORMANCE); + assert_eq!(r64(power, 0x3b98), input().va[id::TEMPERATURE]); + assert_eq!(r32(object(&v25, &wire::V25G83, id::GLOBALS), 0x9c8), 750); + assert_eq!(r32(object(&v26, l, id::GLOBALS), 0x9cc), 750); + assert_eq!(r32(object(&v25, &wire::V25G83, id::GLOBALS), 0x9cc), 800); + assert_eq!(r32(object(&v26, l, id::GLOBALS), 0x9d0), 800); + std::fs::write(out.join("initdata-25g83.bin"), &v25).unwrap(); + std::fs::write(out.join("initdata-26b123.bin"), &v26).unwrap(); + render(&out); + compute_work(&out); + queues(&out); + for layout in backend_hw::t8132::CONFIG.layouts { + ring_test::check(layout.initdata.tx, 7, 7); + let pb = fw::buffer::pb_manager_image_for(layout.abi.pb_manager(), 3, 0, 0, 0, 0, 0, 1); + assert_eq!((r32(&pb, 0x0c), r32(&pb, 0x10)), (3, 3)); + } + assert!(backend_hw::t8132::CONFIG.supports_render_scs); + assert!(!backend_hw::t6030::CONFIG.supports_render_scs); + ring_test::check(wire::G15S_26B123.tx, 2, 5); + g15s_26b123(); + println!("26B123 layout catalog, InitData ({} / {} bytes), TA/FS/compute work and queue info encode; 25G83 entry points equal the 25G83 layouts", v25.len(), v26.len()); +} diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-channels.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-channels.rs index 925fb72a499313..2ef3e8fd5fe7ae 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-channels.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-channels.rs @@ -1,5 +1,11 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -#![allow(dead_code)] +#![allow(dead_code, non_camel_case_types, non_snake_case, non_upper_case_globals)] +extern crate self as kernel; +mod uapi { include!("public-uapi.rs"); } +mod fw { + #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/fw/initdata.rs"] + pub mod initdata; +} #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/fw/channels.rs"] mod channels; #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/fw/graph.rs"] @@ -7,11 +13,14 @@ mod graph; mod fwid { @FWID_BUILD@ } -mod hw {pub enum GpuVariant {G}} -struct Config { - chip_id:u32,gpu_variant:hw::GpuVariant,gpu_revision:u32,uat_ias:u32,uat_oas:u32, - num_clusters:u32,num_cores_per_cluster:u32, - hw_ids:&'static[backend_hw::HwId],firmware:&'static[backend_hw::FirmwareBuild], +mod hw {pub enum GpuVariant {G, S}} +mod adt { + #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/adt/perf.rs"] + pub mod perf; +} +mod board { + #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/board/data.rs"] + pub mod data; } #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/hw.rs"] mod backend_hw; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs index 330b1ac2bd1466..4ae5a991b17a49 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs @@ -9,7 +9,10 @@ mod fw { } } #[allow(unused_imports)] -use fw::{graph::manager, work::compute}; +use fw::{ + graph::{manager, pools}, + work::compute, +}; mod uapi { #[derive(Default)] pub struct drm_asahi_cmd_compute {pub cdm_ctrl_stream_base:u64,pub cdm_ctrl_stream_end:u64} @@ -27,12 +30,13 @@ fn refs(variant:u64)->encode::ComputeRefs { let g=0x1000000000+variant*0x100000000; encode::ComputeRefs { notifier:f+0x600400,qinfo:f+0x200000,user_stamp:f+0x600648,fw_stamp:f+0x600640, - work:f+0x100000,work_gva:g+0x100000,seq:f+0x100900,preempt_gva:g+0x200000, + work:f+0x100000,work_gva:g+0x100000,seq:f+0x100900,descriptor_fw:0,preempt_gva:g+0x200000, its:if variant&2!=0{f+0x500040}else{f+0x1008c0},stats_fw:f+0x300000, auxiliary_fw:f+0x400000,auxiliary_gva:g+0x400000,context_store_gva:g+0x500000, counter_fw:f+0x500000,pool_state_gva:g+0x600000,page_list_gva:g+0x700000, usc_base:if variant&1!=0{1<<40}else{0},record_fw:if variant&1!=0{f+0x700000}else{0}, - binding_generation:1,uma_slot:1,command_id:1,compute_index:0,work_818:0,target_stamp:0x100,submitted:1, + binding_generation:1,uma_slot:1,command_id:1,compute_index:0,work_818:0, + target_stamp:0x100,submitted:1,event:compute::EVENT, } } @@ -85,6 +89,18 @@ fn main(){ assert_eq!(&q[0x3c..0x40],&opaque.to_le_bytes()); assert_eq!(&w[0x810..0x814],&target.to_le_bytes()); } + // Second concurrent compute pipe uses event 16 at w+0x814 and q+0x1b8. + { + let r_p1 = encode::ComputeRefs { event: compute::EVENTS[1], ..refs(0) }; + let c = uapi::drm_asahi_cmd_compute { + cdm_ctrl_stream_base: 0x1000300000, + cdm_ctrl_stream_end: 0x1000300200, + }; + let mut w=[0xa5;compute::WORK_SIZE];let mut q=[0x5a;compute::SEQ_SIZE]; + encode::encode_compute(&r_p1,&c,&[],&[0;2],1,1,1,&mut w,&mut q).unwrap(); + assert_eq!(&w[0x814..0x818],&compute::EVENTS[1].to_le_bytes()); + assert_eq!(&q[0x1b8..0x1bc],&compute::EVENTS[1].to_le_bytes()); + } let mut cases=0; let r=refs(0);let c=uapi::drm_asahi_cmd_compute {cdm_ctrl_stream_base:0x1000300000,cdm_ctrl_stream_end:0x1000300200}; let invalid:Vec<(encode::ComputeRefs,u32)>=vec![ @@ -93,6 +109,7 @@ fn main(){ (encode::ComputeRefs {uma_slot:0,..r},1),(encode::ComputeRefs {uma_slot:33,..r},1), (encode::ComputeRefs {target_stamp:0x101,..r},1), (encode::ComputeRefs {submitted:0,..r},1), + (encode::ComputeRefs {event:0,..r},1),(encode::ComputeRefs {event:128,..r},1), (encode::ComputeRefs {work:0xfffffc1ffffffff8,..r},1), (encode::ComputeRefs {work:0xfffffc2ffbfff000,..r},1), (encode::ComputeRefs {seq:0xfffffc2ffbffff00,..r},1), diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata-bounds.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata-bounds.rs index 29b51ee5cefafc..a39156b45d7b11 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata-bounds.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata-bounds.rs @@ -6,12 +6,13 @@ const HOST: u64 = wire::HOST_START; fn emit(out:&mut Vec, value:Result)->Option { out.push(u8::from(value.is_err()));value.ok() } fn input()->wire::Input { wire::Input { - // Independently pinned qualified C/J713 bin for this immutable byte fixture. + // J713 frequencies with synthetic voltage bins. performance: wire::Performance { - frequency: [0,338,618,796,928,1056,1170,1278,1338,1470], - auxiliary: [0,338,618,796,836,952,1053,1152,1204,1326], - voltage: [125,610,645,680,725,780,825,865,895,970], - sram: [780,780,780,780,780,780,825,865,895,970], + count: 10, + frequency: [0,338,618,796,928,1056,1170,1278,1338,1470,0], + auxiliary: [0,338,618,796,836,952,1053,1152,1204,1326,0], + voltage: [100,600,650,700,750,800,850,900,950,1000,0], + sram: [800,800,800,800,800,800,850,900,950,1000,0], }, va: core::array::from_fn(|i|HOST+0x100000+i as u64*0x100000), channel_state:core::array::from_fn(|i|HOST+0x4000000+i as u64*0x10000), @@ -19,6 +20,10 @@ fn input()->wire::Input { loader_va:core::array::from_fn(|i|if wire::LOADERS[i].length!=0 {HOST+0x5000000+i as u64*0x100000+(wire::LOADERS[i].pa&0x3fff)}else{0}), scratch:HOST+0xa000000,lower_uma:wire::BOOTSTRAP_START+0x200000, lower_parameter:wire::BOOTSTRAP_START+0x240000,ktrace_mask:0,progress_recovery:1, + enabled_cores: 10, + power_sample_clks:200_000,power_sample_us:8333,power_sample_period_ms:8, + timebase_khz:24_000,avg_power_filter_tc_ms:248,lowpeak_limiter_tc_ms:16, + lowpeak_limiter_ki_q16:134_217,lowpeak_limiter_kp_q16:33_554,coredump_copy_size:0x8000, } } fn init_result(buffers:&mut[Vec;wire::OBJECT_COUNT], input:&wire::Input, ceiling:u32)->Result<(),()> { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs index 97d526fbf504f8..72fdcb8c7df97a 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs @@ -7,12 +7,13 @@ fn input(variant: u64) -> initdata::Input { let start = 0xfffffc2000000000u64; let shift = variant * 0x100000000; let mut input = initdata::Input { - // Independently pinned qualified C/J713 bin for this immutable byte fixture. + // J713 frequencies with synthetic voltage bins. performance: initdata::Performance { - frequency: [0,338,618,796,928,1056,1170,1278,1338,1470], - auxiliary: [0,338,618,796,836,952,1053,1152,1204,1326], - voltage: [125,610,645,680,725,780,825,865,895,970], - sram: [780,780,780,780,780,780,825,865,895,970], + count: 10, + frequency: [0,338,618,796,928,1056,1170,1278,1338,1470,0], + auxiliary: [0,338,618,796,836,952,1053,1152,1204,1326,0], + voltage: [100,600,650,700,750,800,850,900,950,1000,0], + sram: [800,800,800,800,800,800,850,900,950,1000,0], }, va: core::array::from_fn(|i| start + shift + 0x100000 + i as u64 * 0x100000), channel_state: core::array::from_fn(|i| start + shift + 0x4000000 + i as u64 * 0x10000), @@ -23,6 +24,17 @@ fn input(variant: u64) -> initdata::Input { lower_parameter: 0x7000240000, ktrace_mask: [0, 0x12345678, 0xfedcba98][variant as usize], progress_recovery: u32::from(variant != 1), + enabled_cores: 10, + // T8132 ADT power-sampling ticks; 25G83 writes power_sample_clks to +4/+8. + power_sample_clks: 200_000, + power_sample_us: 8333, + power_sample_period_ms: 8, + timebase_khz: 24_000, + avg_power_filter_tc_ms: 248, + lowpeak_limiter_tc_ms: 16, + lowpeak_limiter_ki_q16: 134_217, + lowpeak_limiter_kp_q16: 33_554, + coredump_copy_size: 0x8000, }; for (i, loader) in initdata::LOADERS.iter().enumerate() { if loader.length != 0 { @@ -41,12 +53,30 @@ fn main() { let mut slices: [&mut [u8]; initdata::OBJECT_COUNT] = buffers.each_mut().map(|buffer| buffer.as_mut_slice()); initdata::encode(&mut slices, &input(variant as u64), ceiling).expect("valid C fixture rejected"); let got: Vec<_> = buffers.into_iter().flatten().collect(); - let expected = std::fs::read(directory.join(format!("initdata-{variant}.bin"))).unwrap(); + let mut expected = + std::fs::read(directory.join(format!("initdata-{variant}.bin"))).unwrap(); + // Substitute synthetic voltages in the immutable C golden before comparison. + let main: usize = initdata::OBJECT_SIZE[..initdata::id::MAIN].iter().sum(); + let perf = input(variant as u64).performance; + for i in 0..=ceiling as usize { for lane in 0..16 { + for (offset, value) in [(0x1008, perf.voltage[i]), (0x1408, perf.sram[i])] { + let at = main + offset + (i * 16 + lane) * 4; + expected[at..at+4].copy_from_slice(&value.to_le_bytes()); + } + }} + // Substitute calibrated DM2 compute watchdogs (40 -> 750, 50 -> 800) in the frozen C + // golden. + let globals: usize = initdata::OBJECT_SIZE[..initdata::id::GLOBALS].iter().sum(); + for (offset, old, new) in [(0x9c8usize, 40u32, 750u32), (0x9ccusize, 50u32, 800u32)] { + let wd = globals + offset; + assert_eq!(u32::from_le_bytes(expected[wd..wd+4].try_into().unwrap()), old); + expected[wd..wd+4].copy_from_slice(&new.to_le_bytes()); + } if let Some(offset) = got.iter().zip(&expected).position(|(a, b)| a != b) { panic!("initdata variant {variant} differs at {offset:#x}: C={:#x}, Rust={:#x}", expected[offset], got[offset]); } assert_eq!(got.len(), expected.len()); bytes_checked += got.len(); } - println!("3 initdata fixtures / {bytes_checked} output bytes match qualified C exactly"); + println!("3 initdata fixtures / {bytes_checked} bytes match C with synthetic voltages"); } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-render.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-render.rs index cbe759e73feb5a..d93aa65b30fee4 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-render.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-render.rs @@ -77,6 +77,17 @@ fn main() { for i in 0..ta.len(){if !(0x90f..0x917).contains(&i){assert_eq!(ta[i],ta_separate[i],"TA unrelated byte {i:#x}");}} for i in 0..fs.len(){if !(0xc57..0xc5f).contains(&i){assert_eq!(fs[i],fs_separate[i],"FS unrelated byte {i:#x}");}} assert_eq!(tq,tq_separate);assert_eq!(fq,fq_separate); + let mut p_sl=p;p_sl.scene_list=g+0x540000; + let mut ta_sl=[0xa5;fw::work::ta::WORK_SIZE];let mut fs_sl=[0xa5;fw::work::fs::WORK_SIZE]; + let mut tq_sl=[0xa5;fw::work::ta::SEQ_SIZE];let mut fq_sl=[0xa5;fw::work::fs::SEQ_SIZE]; + encode::encode_ta(&r,&p_sl,&u,&[0;4],ctx,target,&geo,None,&mut ta_sl,&mut tq_sl); + encode::encode_fs(&r,&p_sl,&u,&[0;4],ctx,1<<40,1,target,&geo,&mut fs_sl,&mut fq_sl); + let mut scene_r=vec![0xa5;fw::work::scene::SIZE]; + let mut scene_p=vec![0xa5;fw::work::scene::SIZE]; + encode::fill_scene(&r,&p,&mut scene_r);encode::fill_scene(&r,&p_sl,&mut scene_p); + assert_ne!(ta,ta_sl);assert_ne!(fs,fs_sl);assert_ne!(scene_r,scene_p); + assert_ne!(&scene_r[0x28..0x30],&scene_p[0x28..0x30]); + assert_eq!(tq,tq_sl);assert_eq!(fq,fq_sl); for engine in 0..2 { let att:Vec<_>=(0..counts[v][engine]).map(|i|uapi::drm_asahi_attachment {pointer:g+0x50000000+i as u64*0x10000+v as u64*13,size:(i as u64+1)*137,..Default::default()}).collect(); encode::render_attachments(if engine==0{&mut tq[..]}else{&mut fq[..]},engine,&att); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-policy.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-policy.rs index 6d01e7cfdb846e..400e8b1753e326 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-policy.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-policy.rs @@ -1,4 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/power/policy.rs"] mod policy; +#[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/feed/detector.rs"] +mod feed_detector; fn main() {} diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-sensor.c b/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-sensor.c index cc961c2aea325d..d2c2a33de278a1 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-sensor.c +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-sensor.c @@ -36,6 +36,52 @@ static void selftest(void) free(sram); } +/* Records moved in a later firmware are found by name. */ +static void locate_selftest(void) +{ + u8 *sram = calloc(1, PMP_TEMP_SRAM_SIZE); + struct apple_pmp_temp_map map, old; + const u32 shift = 0x1140; + long mc = 0; + int channel = -1; + + assert(sram); + apple_pmp_temp_map_default(&map); + assert(apple_pmp_temp_locate(sram, 0x3d000, PMP_TEMP_SRAM_SIZE, &map) == -ENOENT); + for (unsigned int i = 0; i < PMP_TEMP_CHANNELS; i++) { + u8 *record = sram + apple_pmp_temp_records[i].offset + shift; + + memcpy(record, apple_pmp_temp_records[i].name, 7); + store32(record + PMP_TEMP_SAMPLE_OFFSET, (80 + i) * 64); + store32(record + PMP_TEMP_VALID_OFFSET, 1); + } + /* The 25G83 offsets no longer hold the records. */ + assert(apple_pmp_temp_hotspot(sram, &mc) == -EIO); + assert(!apple_pmp_temp_locate(sram, 0x3d000, PMP_TEMP_SRAM_SIZE, &map)); + for (unsigned int i = 0; i < PMP_TEMP_CHANNELS; i++) + assert(map.offset[i] == apple_pmp_temp_records[i].offset + shift); + assert(!apple_pmp_temp_hotspot_channel_map(sram, &map, &mc, &channel)); + assert(mc == 85000 && channel == 5); + /* A name outside a plausible record (validity word > 1) is no candidate. */ + memcpy(sram + 0x40000, "te001m", 7); + store32(sram + 0x40000 + PMP_TEMP_VALID_OFFSET, 7); + old = map; + assert(!apple_pmp_temp_locate(sram, 0x3d000, PMP_TEMP_SRAM_SIZE, &map)); + assert(!memcmp(&map, &old, sizeof(map))); + /* A second plausible copy: the one in step with the first record wins. */ + store32(sram + 0x40000 + PMP_TEMP_VALID_OFFSET, 0); + assert(!apple_pmp_temp_locate(sram, 0x3d000, PMP_TEMP_SRAM_SIZE, &map)); + assert(map.offset[2] == apple_pmp_temp_records[2].offset + shift); + /* Two copies of the first record: ambiguous, and the map is kept. */ + memcpy(sram + 0x41000, "ta000m", 7); + assert(apple_pmp_temp_locate(sram, 0x3d000, PMP_TEMP_SRAM_SIZE, &map) == -EEXIST); + assert(map.offset[2] == apple_pmp_temp_records[2].offset + shift); + /* The search stays inside the range it is given. */ + assert(apple_pmp_temp_locate(sram, 0x69800, PMP_TEMP_SRAM_SIZE, &map) == -ENOENT); + assert(apple_pmp_temp_locate(sram, 0x3d001, PMP_TEMP_SRAM_SIZE, &map) == -EINVAL); + free(sram); +} + int main(int argc, char **argv) { int raw; @@ -45,7 +91,8 @@ int main(int argc, char **argv) (void)argv; if (argc > 1) { selftest(); - puts("Production PMP hotspot and missing-record checks passed"); + locate_selftest(); + puts("Production PMP hotspot, missing-record and record-location checks passed"); return 0; } while (scanf("%d %u %u %u", &raw, &valid, &actual, &expected) == 4) { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/run-host-tests.py b/tools/testing/selftests/drivers/gpu/asahi-m4/run-host-tests.py index ca3b57018a8ea3..37e1382a3230a5 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/run-host-tests.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/run-host-tests.py @@ -29,8 +29,16 @@ def main(): print(f'1..0 # SKIP missing host prerequisite: {variable}={executable}') return 4 verify_fixtures() - output = args.output or (Path(os.environ['ASAHI_M4_OUTPUT']) if os.environ.get('ASAHI_M4_OUTPUT') - else Path(tempfile.mkdtemp(prefix='asahi-m4-suite-'))) + # With no output directory given, the suite makes its own and removes it when every test + # passed. It goes under $TMPDIR when the caller set one (the umbrella runner does), else + # under the kernel tree's hidden .asahi-m4-suite/, never in a RAM-backed /tmp by default. + owned = not args.output and not os.environ.get('ASAHI_M4_OUTPUT') + if owned: + parent = Path(os.environ['TMPDIR']) if os.environ.get('TMPDIR') else root / '.asahi-m4-suite' + parent.mkdir(parents=True, exist_ok=True) + output = Path(tempfile.mkdtemp(prefix='asahi-m4-suite-', dir=parent)) + else: + output = args.output or Path(os.environ['ASAHI_M4_OUTPUT']) output = output.resolve() output.mkdir(parents=True, exist_ok=True) tests = sorted(HERE.glob('test-*.py')) @@ -44,6 +52,9 @@ def main(): environment['ASAHI_M4_OUTPUT'] = str(directory) environment['ASAHI_M4_KERNEL'] = str(root) environment['PYTHONDONTWRITEBYTECODE'] = '1' + # A test's own temporary files live in its output directory and go with it. + (directory / 'tmp').mkdir(exist_ok=True) + environment['TMPDIR'] = str(directory / 'tmp') command = [sys.executable, str(test)] # Resource allocator predates the shared output environment option. if test.name == 'test-resources.py': @@ -68,7 +79,11 @@ def main(): report = {'cpu_only': True, 'hardware_execution': False, 'passed': all(x['returncode'] in (0, 4) for x in results), 'kernel_source': str(root), 'fixture_manifest_sha256': sha(HERE / 'fixtures/manifest.json'), 'tests': results} (output / 'host-tests.json').write_text(json.dumps(report, indent=2)+'\n') - print('# Results: ' + str(output / 'host-tests.json'), flush=True) + if owned and report['passed']: + shutil.rmtree(output) + print('# All passed; removed ' + str(output), flush=True) + else: + print('# Results: ' + str(output / 'host-tests.json'), flush=True) return 0 if report['passed'] else 1 diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py new file mode 100755 index 00000000000000..839fccfaa58be1 --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""The 26B123 firmware ABI: production encoders against an independent offset oracle. + +check-abi-26b123.rs encodes the same InitData graph, TA/FS/compute work and queue info with +the production 25G83 and 26B123 layouts. This script rebuilds the expected 26B123 bytes from +the 25G83 bytes with explicit per-field tables (old offset -> new offset, written out +independently of the production offset runs) and requires an exact match, and that every +non-zero 25G83 byte is accounted for. CPU-only. +""" +import json +from pathlib import Path +import struct +import subprocess +import time +from common import HERE, frozen_bindings, kernel_root, output_dir, rustc, sha + +OBJECTS_25G83 = [ + 0xc8, 0x4000, 0x4b8, 0xe48, 0x20, 0xeaf0, 0x670, 0x4000, 0x2658, 0x6578, 0x88, 0xc18, 0x1248, + 0xe10, 0x60, 0x1b0, 0x28800, 0x79800, 0x4000, 0x30, 0x4000, 0x30, 0x9000, 0x30, 0x4800, 0x4, + 0x30, 0x4800, 0x4000, 0x4000, 0x4000] +# 26B123 grows GLOBALS (+4), FIRMWARE_DATA (+0x2e0), POWER, MAIN and POWER_PERFORMANCE. +OBJECTS_26B123 = list(OBJECTS_25G83) +OBJECTS_26B123[3] = 0xe4c +OBJECTS_26B123[5] = 0xedd0 +OBJECTS_26B123[6] = 0x698 +OBJECTS_26B123[8] = 0x2788 +OBJECTS_26B123[9] = 0x6c48 +ROOT, RUNTIME, GLOBALS, FIRMWARE_DATA, MAIN, POWER_PERFORMANCE = 0, 2, 3, 5, 8, 9 + + +def fields(pairs, width=4): + return [(old, new, width) for old, new in pairs] + + +# GLOBALS: one u32 inserted at 0x38; the words the host writes. +GLOBALS_MAP = fields([(0x24, 0x24), (0x78, 0x7c), (0x88, 0x8c), (0x8c, 0x90), (0x98, 0x9c), + (0x998, 0x99c), (0x99c, 0x9a0), (0x9a0, 0x9a4), (0x9b8, 0x9bc), + (0x9bc, 0x9c0), (0x9c0, 0x9c4), (0x9c8, 0x9cc), (0x9cc, 0x9d0), + (0xe28, 0xe2c)]) +# FirmwareData: FWCTL state/ring pointers and the scheduler word. +FIRMWARE_DATA_MAP = [(0x4f88, 0x5168, 8), (0x4f90, 0x5170, 8), (0x4fd4, 0x51b4, 4)] +# HW data: the G16-written words, then the register map slot renumbering. +MAIN_MAP = [(0x28, 0x28, 8), (0xf24, 0x1040, 8)] + fields([ + (0xea0, 0xfc0), (0xea4, 0xfc4), (0xeb8, 0xfd8), (0xed0, 0xfec), (0xed4, 0xff0), + (0xed8, 0xff4), (0xee0, 0xffc), (0xfc0, 0x10dc), (0xfc4, 0x10e0), (0x2544, 0x2660), + (0x2548, 0x2664), (0x254c, 0x2668), (0x2550, 0x266c), (0x2554, 0x2670), (0x2568, 0x2684), + (0x2570, 0x268c), (0x259c, 0x26b8)]) +MAIN_MAP += fields([(0xfc8 + 4 * i, 0x10e4 + 4 * i) for i in range(16)]) +MAIN_MAP += fields([(0x1808 + 4 * i, 0x1924 + 4 * i) for i in range(16)]) +MAIN_MAP += fields([(0x1008 + 4 * k, 0x1124 + 4 * k) for k in range(256)]) +MAIN_MAP += fields([(0x1408 + 4 * k, 0x1524 + 4 * k) for k in range(256)]) +SLOTS = {0: 0, 3: 3, 9: 9, 10: 10, 12: 12, 14: 14, 15: 15, 17: 17, 22: 22, 26: 31, 27: 32, + 28: 33, 29: 34, 31: 36, 32: 37, 39: 44, 40: 45, 41: 46} +MAIN_MAP += [(0x640 + old * 0x28, 0x640 + new * 0x28, 0x28) for old, new in SLOTS.items()] +# Logical 36 (the protected power-transition block, slot 41) stays empty on 26B123: its 25G83 +# bytes are accounted for without a 26B123 position. The retention pointer (25G83 MAIN 0xe88) +# leaves MAIN and moves to RUNTIME +0x2c8. +DROPPED = {MAIN: [(0x640 + 36 * 0x28, 0x28), (0xe88, 8)]} +# Power config: the words the host writes and the temperature pointer. +POWER_MAP = [(0x3b50, 0x3b98, 8)] + fields([ + (0x4, 0x4), (0x8, 0x8), (0x10, 0x10), (0x14, 0x14), (0x2c, 0x2c), (0x30, 0x30), + (0x9f0, 0xa00), (0x9f4, 0xa04), (0xa38, 0xa48), (0xaa8, 0xab8), (0xaac, 0xabc), + (0xaf0, 0xb00), (0xb78, 0xb88), (0xb7c, 0xb8c), (0xb80, 0xb90), (0xbc0, 0xbd0), + (0x2210, 0x2220), (0x22b0, 0x22c0), (0x22b4, 0x22c4), (0x22f8, 0x2308), (0x279e, 0x27ae), + (0x2870, 0x2880), (0x2a3c, 0x2a64), (0x2b84, 0x2bac), (0x2b88, 0x2bb0), (0x2b8c, 0x2bb4), + (0x2bcc, 0x2bf4), (0x2c40, 0x2c68), (0x2c44, 0x2c6c), (0x2c88, 0x2cb0)]) +# Words new in 26B123 that the host writes: u64 crash copy buffer size at HW data 0xfa8, +# and u32 USC shader-core progress monitoring enable at HW data 0x277e. +NEW_26B123 = {MAIN: [(0xfa8, 8, 0x8000), (0x277e, 4, 1)]} +MOVED = {GLOBALS: GLOBALS_MAP, FIRMWARE_DATA: FIRMWARE_DATA_MAP, MAIN: MAIN_MAP, + POWER_PERFORMANCE: POWER_MAP, + # Main config: only the power-config pointer moves (16 bytes later). + RUNTIME: [(0, 0, 0x469), (0x469, 0x479, 8)]} + + +def split(image, sizes): + out, at = [], 0 + for size in sizes: + out.append(image[at:at + size]) + at += size + assert at == len(image), (at, len(image)) + return out + + +def name_index(name): + return int(name.split()[1]) if name.startswith('object ') else -1 + + +def moved(old, size, table, name): + """New object of `size` bytes holding `old`'s fields at their new offsets; every non-zero + byte of `old` must belong to some field.""" + new, covered = bytearray(size), bytearray(len(old)) + for at, to, width in table: + new[to:to + width] = old[at:at + width] + covered[at:at + width] = b'\1' * width + for at, width in DROPPED.get(name_index(name), []): + covered[at:at + width] = b'\1' * width + stray = [hex(i) for i, (b, c) in enumerate(zip(old, covered)) if b and not c] + assert not stray, f'{name}: 25G83 bytes without a 26B123 position: {stray[:8]}' + return new + + +def expect_initdata(old_image): + old = split(old_image, OBJECTS_25G83) + new = [] + for index, (before, size) in enumerate(zip(old, OBJECTS_26B123)): + if index == ROOT: + assert struct.unpack_from(' = .*?;', g17, re.S)) +g17_constants = '\n'.join(re.findall(r'const (?:RENDER_BASE_SIZE|COMPUTE_BASE_SIZE|ATTACHMENT_KINDS): usize = .*?;|const (?:RENDER_TIMESTAMP_COPIES|COMPUTE_TIMESTAMP_COPIES): Range = .*?;', g17, re.S)) reader = (ROOT / 'drivers/gpu/drm/asahi/util.rs').read_text() reader = reader[reader.index('pub(crate) unsafe trait AnyBitPattern:'):] harness = r''' @@ -71,17 +97,34 @@ const EINVAL: i32 = -22; const EOVERFLOW: i32 = -75; const E2BIG: i32 = -7; +const GFP_KERNEL: u32 = 0; struct Error; impl Error { fn from_errno(error:i32)->i32 { error } } extern crate self as kernel; // The parser logs why it refuses a command; check the format arguments, print nothing. macro_rules! pr_warn { ($($arg:tt)*) => {{ let _ = format_args!($($arg)*); }}; } pub mod bindings { pub const EOPNOTSUPP:i32=95; } -pub mod prelude { pub type Result = core::result::Result; pub const E2BIG:i32=-7; } +pub mod prelude { pub type Result = core::result::Result; pub const EINVAL:i32=-22; pub const E2BIG:i32=-7; pub const EOVERFLOW:i32=-75; } +pub(crate) mod timestamp { + pub(crate) struct Destinations; + impl Destinations { pub(crate) const fn empty() -> Self { Self } } +} +pub(crate) struct KBox(Box); +impl KBox { fn new(v: T, _: u32) -> Result { Ok(Self(Box::new(v))) } } +impl core::ops::Deref for KBox { type Target = T; fn deref(&self) -> &T { &self.0 } } +pub(crate) struct KVec(Vec); +impl KVec { + fn new() -> Self { Self(Vec::new()) } + fn with_capacity(cap: usize, _: u32) -> Result { Ok(Self(Vec::with_capacity(cap))) } + fn push(&mut self, v: T, _: u32) -> Result { self.0.push(v); Ok(()) } + fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), T> { self.0.push(v); Ok(()) } +} +impl core::ops::Deref for KVec { type Target = [T]; fn deref(&self) -> &[T] { &self.0 } } +impl core::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut [T] { &mut self.0 } } mod uapi { include!("FULL_UAPI"); } mod file { pub const MAX_COMMANDS_PER_SUBMISSION: u32 = 64; } mod hw { pub const USER_RANGE: core::ops::Range = 0x4000..((1u64 << 42) - 0x8000); - pub mod sizes { pub const MAX_ATTACHMENTS: usize = 16; } + pub mod sizes { pub const MAX_ATTACHMENTS: usize = 16; pub const TA_LIGHT_TILEMAP_BYTES: u64 = 64 * 1024; } pub mod client { pub const PB_HEAP_SIZE:u64=0x10000000; CAPACITIES } } mod fw { @@ -89,16 +132,22 @@ #[path="FW_WORK"] pub mod work; } #[path="FULL_ENCODER"] mod encode; +#[path="RT_MOD"] mod rt; READER IMPLS PRODUCTION_CONSTANTS +PARSE_TYPES PRODUCTION_PARSER +fn check_stream(bytes: &[u8], early_tiling: bool) -> Result { + parse_stream(bytes, early_tiling).map(|_| ()) +} mod g17 { - use super::{uapi, AnyBitPattern, Reader, Result, EINVAL, size_of, offset_of, Range}; + use super::{uapi, AnyBitPattern, Reader, Result, EINVAL, size_of, Range}; G17_CONSTANTS const STAGE_PREFIXES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; const FRAGMENT_BARRIERS: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; const GFP_KERNEL: u32 = 0; + const GFP_KERNEL_ACCOUNT: u32 = 0; pub struct Arc(std::rc::Rc); impl Arc { fn new(value: T, _: u32) -> Result { Ok(Self(std::rc::Rc::new(value))) } } impl Clone for Arc { fn clone(&self) -> Self { Self(self.0.clone()) } } @@ -190,7 +239,7 @@ } #[test] fn ray_query_and_unknown_extension_bytes_are_refused() { - let mut r=render(); r.ray_query[0].scs_layout=1; + let mut r=render(); r.ray_query[0].scs_layout=0xffff_0000_ff00_ffff; assert!(check_stream(&entry(CMD_RENDER,&data(&r),[NONE;2]),false).is_err()); let mut raw=data(&compute()); raw.extend([0u8;8]); assert!(check_stream(&entry(CMD_COMPUTE,&raw,[NONE;2]),false).is_ok()); @@ -305,13 +354,99 @@ } } #[test] +fn g16_stage_prefixes_v2_framing_and_tiling_narrowing() { + let mut m5 = uapi::drm_asahi_cmd_render_m5 { legacy: render(), ..Default::default() }; + m5.legacy.flags = STAGE_PREFIXES; + m5.legacy.prior_vdm = 5; + m5.legacy.prior_cdm = 9; + m5.stage_prefixes.ta_vdm_barrier = NONE; + m5.stage_prefixes.ta_cdm_barrier = NONE; + m5.stage_prefixes.ta_prior_vdm = 3; + m5.stage_prefixes.ta_prior_cdm = 0; + + // Rejected when early_tiling is disabled; accepted when enabled. + let wire = entry(CMD_RENDER, &data(&m5), [NONE; 2]); + assert!(check_stream(&wire, false).is_err()); + assert!(check_stream(&wire, true).is_ok()); + + // Exact 480-byte payload, zero reserved fields, zero ray-query bytes, mutually exclusive with FRAGMENT_BARRIERS. + assert!(check_stream(&entry(CMD_RENDER, &data(&m5)[..448], [NONE; 2]), true).is_err()); + let mut over = data(&m5); + over.extend([0u8; 8]); + assert!(check_stream(&entry(CMD_RENDER, &over, [NONE; 2]), true).is_err()); + for field in 0..4 { + let mut bad = m5; + match field { + 0 => bad.stage_prefixes.reserved0 = 1, + 1 => bad.stage_prefixes.reserved1 = 1, + 2 => bad.stage_prefixes.reserved2 = 1, + _ => bad.stage_prefixes.reserved3 = 1, + } + assert!(check_stream(&entry(CMD_RENDER, &data(&bad), [NONE; 2]), true).is_err()); + } + let mut both = m5; + both.legacy.flags |= FRAGMENT_BARRIERS; + assert!(check_stream(&entry(CMD_RENDER, &data(&both), [NONE; 2]), true).is_err()); + let mut rq = m5; + rq.legacy.ray_query[0].scs_layout = 0xffff_0000_ff00_ffff; + assert!(check_stream(&entry(CMD_RENDER, &data(&rq), [NONE; 2]), true).is_err()); + + // Without STAGE_PREFIXES, nonzero trailing bytes past 448 are rejected; zero tail is accepted. + let mut plain = m5; + plain.legacy.flags = 0; + assert!(check_stream(&entry(CMD_RENDER, &data(&plain), [NONE; 2]), true).is_err()); + plain.stage_prefixes = Default::default(); + assert!(check_stream(&entry(CMD_RENDER, &data(&plain), [NONE; 2]), true).is_ok()); + + // Out-of-bounds in-stream ta_vdm_barrier / ta_cdm_barrier are rejected by check_stream. + let mut bad_bar = m5; + bad_bar.stage_prefixes.ta_vdm_barrier = 1; + assert!(check_stream(&entry(CMD_RENDER, &data(&bad_bar), [NONE; 2]), true).is_err()); + let mut bad_cdm = m5; + bad_cdm.stage_prefixes.ta_cdm_barrier = 1; + assert!(check_stream(&entry(CMD_RENDER, &data(&bad_cdm), [NONE; 2]), true).is_err()); + + // In-stream barriers following prior compute + render succeed in check_stream. + let mut seq = entry(CMD_COMPUTE, &data(&compute())[..64], [NONE; 2]); + seq.extend(entry(CMD_RENDER, &data(&render())[..256], [NONE; 2])); + let mut staged = m5; + staged.stage_prefixes.ta_vdm_barrier = 1; + staged.stage_prefixes.ta_cdm_barrier = 1; + seq.extend(entry(CMD_RENDER, &data(&staged), [1, 1])); + assert!(check_stream(&seq, true).is_ok()); + + // Order::narrow_tiling allows narrower TA prefixes (including TA-no-compute while FS waits) + // and rejects any TA prefix wider than the fragment prefix. + let mut full = Order::new([10, 20], [2, 1], [2, 1], [10, 20], RENDER).unwrap(); + assert_eq!(full.wait_through, [Some(12), Some(21)]); + assert_eq!(full.ta_wait_through, [Some(12), Some(21)]); + let ta_narrow = Order::new([10, 20], [2, 1], [1, NONE], [0, 0], RENDER).unwrap(); + assert_eq!(full.narrow_tiling(&ta_narrow), Ok(())); + assert_eq!(full.wait_through, [Some(12), Some(21)]); + assert_eq!(full.ta_wait_through, [Some(11), None]); + + let ta_too_wide_vdm = Order::new([10, 20], [2, 1], [2, NONE], [0, 0], RENDER).unwrap(); + let mut full_vdm1 = Order::new([10, 20], [2, 1], [1, 1], [0, 0], RENDER).unwrap(); + assert_eq!(full_vdm1.narrow_tiling(&ta_too_wide_vdm), Err(EINVAL)); + let ta_too_wide_cdm = Order::new([10, 20], [2, 1], [NONE, 1], [0, 0], RENDER).unwrap(); + let mut full_nocdm = Order::new([10, 20], [2, 1], [2, NONE], [0, 0], RENDER).unwrap(); + assert_eq!(full_nocdm.narrow_tiling(&ta_too_wide_cdm), Err(EINVAL)); +} +#[test] fn unsupported_flags_and_compute_fields() { - for flag in [1u32,4,1<<19,FRAGMENT_BARRIERS] { + for flag in [1u32,4,1<<21,FRAGMENT_BARRIERS] { let mut r=render(); r.flags=flag; assert!(check_stream(&entry(CMD_RENDER,&data(&r)[..256],[NONE;2]),false).is_err()); } let mut c=compute(); - c.scs_layout=1; + c.flags=COMPUTE_NO_QUERY_ACCESS; + assert!(check_stream(&entry(CMD_COMPUTE,&data(&c),[NONE;2]),false).is_ok()); + for bad in [1u32, 1<<16, 1<<18, COMPUTE_NO_QUERY_ACCESS | 1] { + c.flags=bad; + assert!(check_stream(&entry(CMD_COMPUTE,&data(&c),[NONE;2]),false).is_err()); + } + let mut c=compute(); + c.scs_layout=0xffff_0000_ff00_ffff; assert!(check_stream(&entry(CMD_COMPUTE,&data(&c),[NONE;2]),false).is_err()); c.scs_layout=0; c.cdm_auxiliary_allocation=8; assert!(check_stream(&entry(CMD_COMPUTE,&data(&c),[NONE;2]),false).is_err()); @@ -356,8 +491,23 @@ let order=Order::new([4,8],[2,1],[1,NONE],[3,7],RENDER).unwrap(); assert_eq!(order.sequence,7); assert_eq!(order.wait_through,[Some(5),Some(7)]); - assert!(!order.ready([6,6])); - assert!(order.ready([6,7])); + assert!(!order.ready([6,6],[6,6])); + assert!(order.ready([6,7],[6,7])); + // Same-engine and same-VM cross-engine commands may follow published predecessors + // (ordered on the hardware engine rings and cross-engine ring barriers). + let compute=Order::new([0,2],[0,0],[NONE,NONE],[0,2],COMPUTE).unwrap(); + assert!(!compute.ready([0,1],[0,1])); + assert!(compute.ready([0,1],[0,2])); + let render=Order::new([0,2],[0,0],[NONE,NONE],[0,2],RENDER).unwrap(); + assert!(!render.ready([0,1],[0,1])); + assert!(render.ready([0,1],[0,2])); + assert!(render.ready([0,2],[0,2])); + let compute_after_render=Order::new([2,0],[0,0],[NONE,NONE],[2,0],COMPUTE).unwrap(); + assert!(!compute_after_render.ready([1,0],[1,0])); + assert!(compute_after_render.ready([1,0],[2,0])); + let render_next=Order::new([2,0],[0,0],[NONE,NONE],[2,0],RENDER).unwrap(); + assert!(!render_next.ready([1,0],[1,0])); + assert!(render_next.ready([1,0],[2,0])); } #[test] fn geometry_capacity_boundary_uses_the_real_encoder() { @@ -393,12 +543,472 @@ assert_eq!(result,Err(E2BIG)); assert_eq!(publications,0,"a rejected render must prevent the earlier compute publishing"); } +mod inline_submit_containers { + use super::{Order, Result, COMPUTE, NONE, RENDER}; + use std::cell::Cell; + + const ENOMEM: i32 = -12; + const GFP_KERNEL: u32 = 0; + + std::thread_local! { + static ALLOCS: Cell = const { Cell::new(0) }; + static FAIL_NEXT: Cell = const { Cell::new(false) }; + } + + pub(crate) mod timestamp { + #[derive(Debug, PartialEq, Eq)] + pub(crate) struct Destinations(pub(crate) u32); + } + + #[derive(Debug, PartialEq, Eq)] + pub(crate) struct Command(pub(crate) u32); + + pub(crate) struct KVec(Vec); + impl KVec { + fn with_capacity(cap: usize, _flags: u32) -> Result { + if FAIL_NEXT.with(|f| f.replace(false)) { + return Err(ENOMEM); + } + ALLOCS.with(|a| a.set(a.get() + 1)); + Ok(Self(Vec::with_capacity(cap))) + } + fn push(&mut self, v: T, _flags: u32) -> Result { + if FAIL_NEXT.with(|f| f.replace(false)) { + return Err(ENOMEM); + } + self.0.push(v); + Ok(()) + } + fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), T> { + self.0.push(v); + Ok(()) + } + fn get_mut(&mut self, idx: usize) -> Option<&mut T> { + self.0.get_mut(idx) + } + } + impl core::ops::Deref for KVec { + type Target = [T]; + fn deref(&self) -> &[T] { &self.0 } + } + impl core::ops::DerefMut for KVec { + fn deref_mut(&mut self) -> &mut [T] { &mut self.0 } + } + + INLINE_CONTAINERS + + #[test] + fn inline_commands_and_orders_skip_heap_up_to_two_and_spill_safely() { + ALLOCS.with(|a| a.set(0)); + let mut cmds = Commands::new(); + let mut orders = Orders::new(); + let o0 = Order::new([0, 0], [0, 0], [NONE; 2], [0; 2], COMPUTE).unwrap(); + let o1 = Order::new([0, 0], [0, 1], [NONE; 2], [0; 2], RENDER).unwrap(); + let o2 = Order::new([0, 0], [1, 1], [NONE; 2], [0; 2], COMPUTE).unwrap(); + cmds.push(Command(1)).unwrap(); + cmds.push(Command(2)).unwrap(); + orders.push(o0).unwrap(); + orders.push(o1).unwrap(); + assert_eq!(ALLOCS.with(|a| a.get()), 0); + assert_eq!(&*cmds, &[Command(1), Command(2)]); + assert_eq!(&*orders, &[o0, o1]); + + // OOM on 2 -> 3 spill preserves inline entries. + FAIL_NEXT.with(|f| f.set(true)); + assert_eq!(cmds.push(Command(3)), Err(ENOMEM)); + assert_eq!(&*cmds, &[Command(1), Command(2)]); + FAIL_NEXT.with(|f| f.set(true)); + assert_eq!(orders.push(o2), Err(ENOMEM)); + assert_eq!(&*orders, &[o0, o1]); + assert_eq!(ALLOCS.with(|a| a.get()), 0); + + // Spill to heap preserves exact FIFO order across both containers. + cmds.push(Command(3)).unwrap(); + orders.push(o2).unwrap(); + assert_eq!(ALLOCS.with(|a| a.get()), 2); + assert_eq!(&*cmds, &[Command(1), Command(2), Command(3)]); + assert_eq!(&*orders, &[o0, o1, o2]); + } +} +mod render_admission_tests { + use super::{ + check_render_helpers, hw, uapi, Result, DBIAS_IS_INT, EINVAL, FEW_PRIMITIVES, + FRAGMENT_BARRIERS, MAX_DIMENSION, MAX_LAYERS, PROCESS_EMPTY_TILES, + RSRC_SPEC_HI, STAGE_PREFIXES, ZLS_METADATA_STRIDE, + }; + const ENOENT: i32 = -2; + const EACCES: i32 = -13; + + pub(crate) mod vm { + pub(crate) fn reserved_ranges() -> &'static [core::ops::Range] { + &[] + } + } + pub(crate) mod params { + pub(crate) fn early_tiling() -> bool { true } + } + pub(crate) mod gate { + use super::{mmu, Result}; + pub(crate) fn vdm(_vm: &mmu::Vm, _va: u64) -> Result { Ok(()) } + } + pub(crate) mod mmu { + pub(crate) const UAT_PGMSK: usize = 0x3fff; + pub(crate) struct VmReadGuard<'a>(&'a Vm); + impl VmReadGuard<'_> { + pub(crate) fn epoch(&self) -> Option { + self.0.epoch.get() + } + pub(crate) fn covers_range(&mut self, start: u64, size: u64, read: bool, write: bool) -> bool { + self.0.covers_range(start, size, read, write) + } + } + pub(crate) struct Vm { + pub(crate) maps: Vec<(u64, u64, bool, bool)>, + pub(crate) epoch: std::cell::Cell>, + pub(crate) batch_calls: std::cell::Cell, + pub(crate) cover_calls: std::cell::Cell, + pub(crate) batch_ranges: std::cell::Cell, + } + impl Vm { + pub(crate) fn read_lock(&self) -> super::Result> { + Ok(VmReadGuard(self)) + } + pub(crate) fn mapping_validation_epoch(&self) -> Option { + self.epoch.get() + } + pub(crate) fn covers_range(&self, start: u64, size: u64, read: bool, write: bool) -> bool { + self.cover_calls.set(self.cover_calls.get() + 1); + let Some(end) = start.checked_add(size) else { return false }; + self.maps.iter().any(|&(s, e, r, w)| { + start >= s && end <= e && (!read || r) && (!write || w) + }) + } + pub(crate) fn covers_ranges_batch(&self, ranges: &[(u64, u64, u8)]) -> (bool, Option) { + self.batch_calls.set(self.batch_calls.get() + 1); + self.batch_ranges.set(self.batch_ranges.get() + ranges.len()); + for &(start, size, acc) in ranges { + if !self.covers_range(start, size, acc & 1 != 0, acc & 2 != 0) { + return (false, self.epoch.get()); + } + } + (true, self.epoch.get()) + } + } + } + pub(crate) struct Context<'a> { + pub(crate) vm: &'a mmu::Vm, + pub(crate) usc_base: u64, + pub(crate) active_cores: u32, + pub(crate) render_scs: [u16; 2], + pub(crate) max_tile_buffer: u32, + } + use super::MAX_COMMANDS; + RENDER_ADMISSION + + fn check_render_one( + ctx: &Context<'_>, + cmd: &uapi::drm_asahi_cmd_render, + vertex: &[uapi::drm_asahi_attachment], + fragment: &[uapi::drm_asahi_attachment], + ) -> Result { + let mut batch = SpanBatch::new(); + check_render(&mut batch, ctx, cmd, vertex, fragment)?; + batch.flush(ctx.vm) + } + + const BASE_GVA: u64 = 0x10_0000_0000; + fn base_vm() -> mmu::Vm { + mmu::Vm { + maps: vec![ + (BASE_GVA, BASE_GVA + 0x10_0000, true, false), + (BASE_GVA + 0x20_0000, BASE_GVA + 0x40_0000, true, true), + (BASE_GVA + 0x50_0000, BASE_GVA + 0x51_0000, true, false), + ], + epoch: std::cell::Cell::new(Some(1)), + batch_calls: std::cell::Cell::new(0), + cover_calls: std::cell::Cell::new(0), + batch_ranges: std::cell::Cell::new(0), + } + } + fn base_cmd() -> uapi::drm_asahi_cmd_render { + uapi::drm_asahi_cmd_render { + width_px: 64, + height_px: 64, + layers: 1, + samples: 1, + utile_width_px: 32, + utile_height_px: 32, + sample_size_B: 8, + vdm_ctrl_stream_base: BASE_GVA, + isp_scissor_base: BASE_GVA + 0x100, + ..Default::default() + } + } + const Z_COMP: u64 = (1 << 1) | (1 << 2) | (1 << 5) | (1 << 6) | (1 << 15) | (1 << 19); + const S_COMP: u64 = (1 << 3) | (1 << 4) | (1 << 7) | (1 << 8) | (1 << 14) | (1 << 18); + + #[test] + fn compressed_zls_1x_layered_and_2x_accepted() { + let vm = base_vm(); + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; + // 1x compressed D32F depth + stencil. + let mut cmd = base_cmd(); + cmd.zls_ctrl = Z_COMP | S_COMP; + cmd.depth.base = BASE_GVA + 0x20_0000; + cmd.depth.comp_base = BASE_GVA + 0x24_0000; + cmd.stencil.base = BASE_GVA + 0x28_0000; + cmd.stencil.comp_base = BASE_GVA + 0x2c_0000; + assert_eq!(check_render_one(&ctx, &cmd, &[], &[]), Ok(())); + // 1x compressed D16 depth (Z Format = 2 at bits 25..26). + let mut d16 = base_cmd(); + d16.zls_ctrl = Z_COMP | (2 << 25); + d16.depth.base = BASE_GVA + 0x20_0000; + d16.depth.comp_base = BASE_GVA + 0x24_0000; + assert_eq!(check_render_one(&ctx, &d16, &[], &[]), Ok(())); + // 2x MSAA compressed depth. + let mut msaa2 = d16; + msaa2.samples = 2; + assert_eq!(check_render_one(&ctx, &msaa2, &[], &[]), Ok(())); + // Layered compressed depth/stencil with comp_stride == 0 (1 line = 0x80) and nonzero stride. + let mut layered = cmd; + layered.layers = 4; + layered.depth.stride = (1 << 14) | 1; + layered.stencil.stride = (1 << 14) | 1; + assert_eq!(check_render_one(&ctx, &layered, &[], &[]), Ok(())); + layered.depth.comp_stride = 3 << 14; + layered.stencil.comp_stride = 2 << 14; + assert_eq!(check_render_one(&ctx, &layered, &[], &[]), Ok(())); + } + + #[test] + fn tile_buffer_limit_follows_the_context() { + let vm = base_vm(); + let k32 = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; + let k48 = Context { max_tile_buffer: 48 * 1024, ..k32 }; + // 8 B x 32x32 x 4 samples = 32 KiB: accepted by both. + let mut k32_tile = base_cmd(); + k32_tile.samples = 4; + assert_eq!(check_render_one(&k32, &k32_tile, &[], &[]), Ok(())); + assert_eq!(check_render_one(&k48, &k32_tile, &[], &[]), Ok(())); + // 24 B x 32x16 x 4 samples = 48 KiB, the MSAA4 tile macOS programs on the M4. + let mut k48_tile = k32_tile; + k48_tile.utile_height_px = 16; + k48_tile.sample_size_B = 24; + assert_eq!(check_render_one(&k32, &k48_tile, &[], &[]), Err(EINVAL)); + assert_eq!(check_render_one(&k48, &k48_tile, &[], &[]), Ok(())); + // 28 B x 32x16 x 4 samples = 56 KiB: over both limits. + let mut over = k48_tile; + over.sample_size_B = 28; + assert_eq!(check_render_one(&k48, &over, &[], &[]), Err(EINVAL)); + } + + #[test] + fn compressed_zls_invalid_ctrl_alignment_and_vm_spans_rejected() { + let vm = base_vm(); + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; + let valid = || { + let mut cmd = base_cmd(); + cmd.zls_ctrl = Z_COMP | S_COMP; + cmd.depth.base = BASE_GVA + 0x20_0000; + cmd.depth.comp_base = BASE_GVA + 0x24_0000; + cmd.stencil.base = BASE_GVA + 0x28_0000; + cmd.stencil.comp_base = BASE_GVA + 0x2c_0000; + cmd + }; + // Asymmetric compress bits per plane. + for bit in [1u64 << 2, 1 << 6, 1 << 4, 1 << 8] { + let mut bad = valid(); + bad.zls_ctrl ^= bit; + assert_eq!(check_render_one(&ctx, &bad, &[], &[]), Err(EINVAL)); + } + // Unaligned comp_stride or comp_base. + for bad_stride in [1u32, 0x4001, 0x3fff] { + let mut bad = valid(); + bad.depth.comp_stride = bad_stride; + assert_eq!(check_render_one(&ctx, &bad, &[], &[]), Err(EINVAL)); + } + let mut bad = valid(); + bad.depth.comp_base += 2; + assert_eq!(check_render_one(&ctx, &bad, &[], &[]), Err(EINVAL)); + // comp_base without compress bits, compress bits without comp_base, stride without base. + let mut bad = valid(); + bad.zls_ctrl &= !((1 << 2) | (1 << 6)); + assert_eq!(check_render_one(&ctx, &bad, &[], &[]), Err(EINVAL)); + let mut bad = valid(); + bad.depth.comp_base = 0; + assert_eq!(check_render_one(&ctx, &bad, &[], &[]), Err(EINVAL)); + let mut bad = valid(); + bad.zls_ctrl = Z_COMP; + bad.stencil = Default::default(); + bad.stencil.comp_stride = 1 << 14; + assert_eq!(check_render_one(&ctx, &bad, &[], &[]), Err(EINVAL)); + // Unmapped comp_base -> ENOENT; read-only comp_base -> EACCES. + let mut unmapped = valid(); + unmapped.depth.comp_base = BASE_GVA + 0x60_0000; + assert_eq!(check_render_one(&ctx, &unmapped, &[], &[]), Err(ENOENT)); + let mut ro = valid(); + ro.depth.comp_base = BASE_GVA + 0x50_0000; + assert_eq!(check_render_one(&ctx, &ro, &[], &[]), Err(EACCES)); + // Layered metadata span extending past mapped range -> ENOENT. + let mut past_end = valid(); + past_end.layers = 4; + past_end.depth.stride = 1; + past_end.stencil.stride = 1; + past_end.depth.comp_base = BASE_GVA + 0x3f_c000; + past_end.depth.comp_stride = 0x100 << 14; + assert_eq!(check_render_one(&ctx, &past_end, &[], &[]), Err(ENOENT)); + } + + #[test] + fn submit_wide_span_batch_dedups_and_flushes_once_across_passes() { + let vm = base_vm(); + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; + let mut batch = SpanBatch::new(); + for pass in 0..4u64 { + let mut cmd = base_cmd(); + cmd.vdm_ctrl_stream_base = BASE_GVA + pass * 0x20; + cmd.zls_ctrl = Z_COMP; + cmd.depth.base = BASE_GVA + 0x20_0000 + pass * 0x4000; + cmd.depth.comp_base = BASE_GVA + 0x24_0000 + pass * 0x4000; + assert_eq!(check_render(&mut batch, &ctx, &cmd, &[], &[]), Ok(())); + } + assert_eq!(vm.batch_calls.get(), 0); + assert_eq!(batch.flush(&vm), Ok(())); + assert_eq!(vm.batch_calls.get(), 1); + let mut guard = vm.read_lock().unwrap(); + let mut proof = SpanProof::new(); + let epoch = guard.epoch(); + assert_eq!(check_render(&mut batch, &ctx, &base_cmd(), &[], &[]), Ok(())); + assert_eq!(batch.flush_locked_with_proof(&mut guard, epoch, &mut proof), Ok(())); + assert_eq!(vm.batch_calls.get(), 1); + drop(guard); + + // Unmapped or read-only span on a later pass still reports exact ENOENT / EACCES. + let mut bad_unmapped = base_cmd(); + bad_unmapped.zls_ctrl = Z_COMP; + bad_unmapped.depth.base = BASE_GVA + 0x20_0000; + bad_unmapped.depth.comp_base = BASE_GVA + 0x60_0000; + assert_eq!(check_render(&mut batch, &ctx, &base_cmd(), &[], &[]), Ok(())); + assert_eq!(check_render(&mut batch, &ctx, &bad_unmapped, &[], &[]), Ok(())); + assert_eq!(batch.flush(&vm), Err(ENOENT)); + + let mut bad_ro = bad_unmapped; + bad_ro.depth.comp_base = BASE_GVA + 0x50_0000; + assert_eq!(check_render(&mut batch, &ctx, &base_cmd(), &[], &[]), Ok(())); + assert_eq!(check_render(&mut batch, &ctx, &bad_ro, &[], &[]), Ok(())); + assert_eq!(batch.flush(&vm), Err(EACCES)); + } + + #[test] + fn few_primitives_flag_admitted_in_parse_and_render_check() { + let vm = base_vm(); + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; + let mut r = super::render(); + r.flags = FEW_PRIMITIVES; + assert!(super::check_stream( + &super::entry(super::CMD_RENDER, &super::data(&r)[..256], [super::NONE; 2]), + false, + ) + .is_ok()); + assert!(super::check_stream( + &super::entry(super::CMD_RENDER, &super::data(&r)[..256], [super::NONE; 2]), + true, + ) + .is_ok()); + r.flags = FEW_PRIMITIVES | DBIAS_IS_INT; + assert!(super::check_stream( + &super::entry(super::CMD_RENDER, &super::data(&r)[..256], [super::NONE; 2]), + false, + ) + .is_ok()); + let mut cmd = base_cmd(); + cmd.flags |= FEW_PRIMITIVES; + assert_eq!(check_render_one(&ctx, &cmd, &[], &[]), Ok(())); + cmd.isp_dbias_base = BASE_GVA + 0x200; + cmd.flags |= DBIAS_IS_INT; + assert_eq!(check_render_one(&ctx, &cmd, &[], &[]), Ok(())); + cmd.flags |= 1 << 21; + assert_eq!(check_render_one(&ctx, &cmd, &[], &[]), Err(EINVAL)); + } + + #[test] + fn span_proof_reuses_epoch_partial_walks_and_invalidates_on_unmap() { + let mut vm = base_vm(); + let mut proof = SpanProof::new(); + let cmd = base_cmd(); + + // First flush populates the proof for epoch 1. + let mut batch = SpanBatch::new(); + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; + check_render(&mut batch, &ctx, &cmd, &[], &[]).unwrap(); + assert_eq!(batch.flush_with_proof(&vm, &mut proof), Ok(())); + assert_eq!(vm.batch_calls.get(), 1); + + // Second flush at unchanged epoch hits the proof with zero VM walks. + let mut batch = SpanBatch::new(); + check_render(&mut batch, &ctx, &cmd, &[], &[]).unwrap(); + assert_eq!(batch.flush_with_proof(&vm, &mut proof), Ok(())); + assert_eq!(vm.batch_calls.get(), 1); + + // A new attachment triggers a partial walk of only the uncovered span. + let att = uapi::drm_asahi_attachment { + pointer: BASE_GVA + 0x20_0000, + size: 0x4000, + ..Default::default() + }; + let ranges_before = vm.batch_ranges.get(); + let mut batch = SpanBatch::new(); + check_render(&mut batch, &ctx, &cmd, &[att], &[]).unwrap(); + assert_eq!(batch.flush_with_proof(&vm, &mut proof), Ok(())); + assert_eq!(vm.batch_calls.get(), 2); + assert_eq!(vm.batch_ranges.get() - ranges_before, 1); + + // Locked flush under a held VmReadGuard also skips already-proven spans. + let covers_before = vm.cover_calls.get(); + let mut batch = SpanBatch::new(); + check_render(&mut batch, &ctx, &cmd, &[att], &[]).unwrap(); + let mut guard = vm.read_lock().unwrap(); + let epoch = guard.epoch(); + assert_eq!(batch.flush_locked_with_proof(&mut guard, epoch, &mut proof), Ok(())); + drop(guard); + assert_eq!(vm.cover_calls.get(), covers_before); + + // Adjacent read-only and read-write ranges never merge to grant write on RO memory. + let mut rw_batch = SpanBatch::new(); + rw_batch.push(&vm, BASE_GVA, BASE_GVA + 0x4000, true, true).unwrap(); + assert_eq!(rw_batch.flush_with_proof(&vm, &mut proof), Err(EACCES)); + + // Repopulate, then simulate an unmap that bumps the epoch: cached proof is invalidated. + let mut batch = SpanBatch::new(); + check_render(&mut batch, &ctx, &cmd, &[att], &[]).unwrap(); + assert_eq!(batch.flush_with_proof(&vm, &mut proof), Ok(())); + vm.maps.remove(1); + vm.epoch.set(Some(2)); + let mut batch = SpanBatch::new(); + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; + check_render(&mut batch, &ctx, &cmd, &[att], &[]).unwrap(); + assert_eq!(batch.flush_with_proof(&vm, &mut proof), Err(ENOENT)); + + // Epoch None (concurrent mutation) never serves a stale cached proof. + vm.epoch.set(None); + let mut batch = SpanBatch::new(); + check_render(&mut batch, &ctx, &cmd, &[], &[]).unwrap(); + let calls_before = vm.batch_calls.get(); + assert_eq!(batch.flush_with_proof(&vm, &mut proof), Ok(())); + assert_eq!(vm.batch_calls.get(), calls_before + 1); + } +} ''' replacements = {'FULL_UAPI': str(BINDINGS), 'READER': reader, 'CAPACITIES': capacities, 'FW_GRAPH': str(SOURCE.parent/'fw/graph.rs'), 'FW_WORK': str(SOURCE.parent/'fw/work.rs'), 'FULL_ENCODER': str(SOURCE.parent/'encode.rs'), + 'RT_MOD': str(SOURCE.parent/'rt.rs'), 'IMPLS': '\n'.join('unsafe impl AnyBitPattern for uapi::' + name + ' {}' for name in names), - 'PRODUCTION_CONSTANTS': constants, 'PRODUCTION_PARSER': parser.replace('super::encode::', 'encode::'), + 'PRODUCTION_CONSTANTS': constants, + 'PARSE_TYPES': parse_types.replace('super::rt::', 'rt::'), + 'PRODUCTION_PARSER': parser.replace('super::encode::', 'encode::').replace('super::rt::', 'rt::'), + 'INLINE_CONTAINERS': inline_containers.replace('crate::timestamp::', 'timestamp::'), + 'RENDER_ADMISSION': render_admission.replace('super::vm::', 'vm::').replace('super::params::', 'params::'), 'G17_CONSTANTS': g17_constants, 'G17_PARSER': g17_parser} for key in sorted(replacements,key=len,reverse=True): harness = harness.replace(key,replacements[key]) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py index c9863ae62a03f3..b985dad1a9ed52 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py @@ -1,9 +1,13 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only OR MIT -"""Exercise the production task-local DMA-fence lockdep guard with and without LOCKDEP.""" +"""Exercise production DMA-fence lockdep guard and Timeline off-pending signalling.""" from common import kernel_root, output_dir, rustc, sha import json +import os +import pathlib +import shlex import subprocess +import tempfile root = kernel_root() out = output_dir() @@ -65,8 +69,712 @@ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) (out / 'fence-signalling-not-send.log').write_text(result.stdout) assert result.returncode and 'E0277' in result.stdout and 'cannot be sent between threads safely' in result.stdout, result.stdout + +fence_source_path = root / 'drivers/gpu/drm/asahi/g16/fence.rs' +fence_source = fence_source_path.read_text() + + +def extract_function(text, name): + marker = text.index('fn ' + name + '(') + start = text.rfind('\n', 0, marker) + 1 + first = text.index('{', marker) + depth = 1 + at = first + 1 + while depth: + depth += (text[at] == '{') - (text[at] == '}') + at += 1 + return text[start:at] + + +signal_batch_line = [ + line for line in fence_source.splitlines() if line.startswith('const SIGNAL_BATCH:') +][0] +timeline_complete_fn = extract_function(fence_source, 'complete') +input_fences_src = fence_source[ + fence_source.index('/// Inline storage for the common 0-2 input fences'): + fence_source.index('/// Reads a retained dependency') +] +fw_waits_src = fence_source[ + fence_source.index('/// Maximum distinct cross-queue firmware waits'): + fence_source.index('/// Fence operations of G16 job fences.') +] +syncs_src = fence_source[ + fence_source.index('/// The syncs of one SUBMIT.'): +] + +timeline_harness = r''' +#![allow(dead_code)] +use std::sync::{Arc, Barrier, Mutex as StdMutex}; +use std::sync::atomic::{AtomicI32, AtomicU64, Ordering}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Error(i32); +const EIO: Error = Error(-5); +const ENOMEM: Error = Error(-12); +const ECANCELED: Error = Error(-125); +const GFP_KERNEL: u32 = 0; +type Result = std::result::Result; + +mod input_fences_test { + use super::{Result, ENOMEM, GFP_KERNEL}; + use std::cell::Cell; + + std::thread_local! { + static ALLOCS: Cell = const { Cell::new(0) }; + static FAIL_NEXT: Cell = const { Cell::new(false) }; + } + + #[derive(Clone, Debug, PartialEq, Eq)] + pub(crate) struct Fence(pub(crate) u32); + + pub(crate) struct KVec(Vec); + impl KVec { + fn with_capacity(cap: usize, _flags: u32) -> Result { + if FAIL_NEXT.with(|f| f.replace(false)) { + return Err(ENOMEM); + } + ALLOCS.with(|a| a.set(a.get() + 1)); + Ok(Self(Vec::with_capacity(cap))) + } + fn push(&mut self, v: T, _flags: u32) -> Result { + if FAIL_NEXT.with(|f| f.replace(false)) { + return Err(ENOMEM); + } + self.0.push(v); + Ok(()) + } + fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), T> { + self.0.push(v); + Ok(()) + } + } + impl core::ops::Deref for KVec { + type Target = [T]; + fn deref(&self) -> &[T] { &self.0 } + } + + INPUT_FENCES_SRC + + #[test] + fn input_fences_inline_zero_to_two_and_spill_safely() { + ALLOCS.with(|a| a.set(0)); + let mut inputs = InputFences::new(); + assert_eq!(&*inputs, &[]); + inputs.push(Fence(10)).unwrap(); + assert_eq!(&*inputs, &[Fence(10)]); + inputs.push(Fence(20)).unwrap(); + assert_eq!(&*inputs, &[Fence(10), Fence(20)]); + assert_eq!(ALLOCS.with(|a| a.get()), 0); + // OOM during 2 -> 3 spill preserves the 2 inline fences intact. + FAIL_NEXT.with(|f| f.set(true)); + assert_eq!(inputs.push(Fence(30)), Err(ENOMEM)); + assert_eq!(&*inputs, &[Fence(10), Fence(20)]); + assert_eq!(ALLOCS.with(|a| a.get()), 0); + // Spill succeeds with one allocation and keeps exact order. + inputs.push(Fence(30)).unwrap(); + inputs.push(Fence(40)).unwrap(); + assert_eq!(ALLOCS.with(|a| a.get()), 1); + assert_eq!(&*inputs, &[Fence(10), Fence(20), Fence(30), Fence(40)]); + } +} + +struct Mutex(StdMutex); +impl Mutex { + fn new(v: T) -> Self { Self(StdMutex::new(v)) } + fn lock(&self) -> std::sync::MutexGuard<'_, T> { self.0.lock().unwrap() } + fn try_lock(&self) -> std::sync::TryLockResult> { + self.0.try_lock() + } +} + +#[derive(Clone)] +struct JobFenceOps; +struct FenceInner { + seqno: u64, + error: AtomicI32, + log: Arc>>, + on_signal: Option>, +} +#[derive(Clone)] +struct UserFence(Arc, core::marker::PhantomData); +impl UserFence { + fn new( + seqno: u64, + log: Arc>>, + on_signal: Option>, + ) -> Self { + Self( + Arc::new(FenceInner { + seqno, + error: AtomicI32::new(0), + log, + on_signal, + }), + core::marker::PhantomData, + ) + } + fn raw(&self) -> *const FenceInner { Arc::as_ptr(&self.0) } + fn set_error(&self, error: Error) { self.0.error.store(error.0, Ordering::Release); } + fn signal(&self) { + if let Some(cb) = &self.0.on_signal { + cb(self.0.seqno); + } + self.0.log.lock().unwrap().push((self.0.seqno, self.0.error.load(Ordering::Acquire))); + } +} + +fn signal_fence(fence: &UserFence) { + fence.signal(); +} + +SIGNAL_BATCH_LINE + +struct Pending { + fence: UserFence, + result: Option, +} + +struct Timeline { + next_seq: AtomicU64, + signaller: Mutex<()>, + pending: Mutex>, + log: Arc>>, +} + +impl Timeline { + fn new() -> Arc { + Arc::new(Self { + next_seq: AtomicU64::new(1), + signaller: Mutex::new(()), + pending: Mutex::new(Vec::new()), + log: Arc::new(StdMutex::new(Vec::new())), + }) + } + + fn next(&self, on_signal: Option>) -> UserFence { + let seq = self.next_seq.fetch_add(1, Ordering::AcqRel); + let fence = UserFence::new(seq, self.log.clone(), on_signal); + self.pending.lock().push(Pending { fence: fence.clone(), result: None }); + fence + } + + TIMELINE_COMPLETE_FN +} + +#[test] +fn out_of_order_and_large_batches_signal_strictly_in_order() { + let tl = Timeline::new(); + let count = SIGNAL_BATCH * 3 + 2; + let fences: Vec<_> = (0..count).map(|_| tl.next(None)).collect(); + for i in (1..count).rev() { + let res = if i % 7 == 0 { Err(EIO) } else { Ok(()) }; + tl.complete(&fences[i], res); + } + assert!(tl.log.lock().unwrap().is_empty()); + tl.complete(&fences[1], Err(ECANCELED)); + tl.complete(&fences[0], Ok(())); + let log = tl.log.lock().unwrap().clone(); + assert_eq!(log.len(), count); + for (idx, (seq, err)) in log.iter().enumerate() { + assert_eq!(*seq, (idx + 1) as u64); + assert_eq!(*err, if idx != 0 && idx % 7 == 0 { EIO.0 } else { 0 }); + } + assert!(tl.pending.lock().is_empty()); + tl.complete(&fences[0], Err(EIO)); + assert_eq!(tl.log.lock().unwrap().len(), count); +} + +#[test] +fn signal_callbacks_do_not_hold_pending_lock_and_allow_next() { + let tl = Timeline::new(); + let tl_cb = tl.clone(); + let f1 = tl.next(Some(Arc::new(move |_| { + assert!(tl_cb.pending.try_lock().is_ok()); + let _f_nested = tl_cb.next(None); + }))); + tl.complete(&f1, Ok(())); + assert_eq!(tl.log.lock().unwrap().len(), 1); + assert_eq!(tl.pending.lock().len(), 1); +} + +#[test] +fn concurrent_completers_preserve_strict_fifo_signal_order() { + for _ in 0..64 { + let tl = Timeline::new(); + let n = 16usize; + let fences: Vec<_> = (0..n).map(|_| tl.next(None)).collect(); + let barrier = Arc::new(Barrier::new(n)); + let mut threads = Vec::with_capacity(n); + for (i, fence) in fences.into_iter().enumerate() { + let tl = tl.clone(); + let barrier = barrier.clone(); + threads.push(std::thread::spawn(move || { + barrier.wait(); + tl.complete(&fence, if i == 5 { Err(ECANCELED) } else { Ok(()) }); + })); + } + for t in threads { + t.join().unwrap(); + } + let log = tl.log.lock().unwrap().clone(); + assert_eq!(log.len(), n); + for (idx, (seq, err)) in log.iter().enumerate() { + assert_eq!(*seq, (idx + 1) as u64); + assert_eq!(*err, if idx == 5 { ECANCELED.0 } else { 0 }); + } + assert!(tl.pending.lock().is_empty()); + } +} + +mod cumulative_syncs_test { + use super::{Error, Result, EIO, ENOMEM}; + use std::cell::RefCell; + use std::rc::Rc; + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct Fence(pub(crate) i32); + + pub(crate) struct Timeline; + impl Timeline { + pub(crate) fn refused(&self, error: Error) -> Fence { + Fence(error.0) + } + } + + pub(crate) mod g17 { + pub(crate) mod sync_output { + use super::super::{Fence, Result, ENOMEM}; + use std::cell::RefCell; + use std::rc::Rc; + + #[derive(Default)] + pub(crate) struct BundleLog { + pub(crate) published: Vec, + pub(crate) compute_only: Vec, + pub(crate) failed: Vec, + pub(crate) fail_publish: bool, + } + + pub(crate) struct SignalBundle(pub(crate) Rc>); + impl SignalBundle { + pub(crate) fn publish(&mut self, fence: &Fence, compute_only: bool) -> Result { + assert!( + !compute_only, + "G16 must not trigger G17 compute-waiter effort accounting" + ); + let mut log = self.0.borrow_mut(); + log.compute_only.push(compute_only); + if log.fail_publish { + return Err(ENOMEM); + } + log.published.push(*fence); + Ok(()) + } + pub(crate) fn fail(&mut self, fence: &Fence) { + self.0.borrow_mut().failed.push(*fence); + } + } + } + } + + pub(crate) struct SyncItem { + pub(crate) installed: Rc>>, + pub(crate) cumulative: Option, + } + + pub(crate) type KVVec = Vec; + + fn install(outputs: impl Iterator, fence: &Fence) { + for sync in outputs { + sync.installed.borrow_mut().push(*fence); + } + } + + SYNCS_SRC + + #[test] + fn cumulative_bundle_publishes_and_handles_oom_refusal_cleanly() { + let log = Rc::new(RefCell::new(g17::sync_output::BundleLog::default())); + let out_log = Rc::new(RefCell::new(Vec::new())); + let items = vec![ + SyncItem { installed: out_log.clone(), cumulative: None }, + SyncItem { + installed: out_log.clone(), + cumulative: Some(g17::sync_output::SignalBundle(log.clone())), + }, + ]; + let mut syncs = Syncs::new(items, 1); + assert_eq!(syncs.inputs().len(), 1); + syncs.publish(&Fence(42)).unwrap(); + assert_eq!(log.borrow().published, vec![Fence(42)]); + assert!(log.borrow().failed.is_empty()); + assert!(out_log.borrow().is_empty()); + // Calling refuse() after successful publish() is a no-op. + syncs.refuse(&Timeline, EIO); + assert!(log.borrow().failed.is_empty()); + + // ENOMEM during publish() leaves bundle armed so refuse() installs error fence. + let log2 = Rc::new(RefCell::new(g17::sync_output::BundleLog { + fail_publish: true, + ..Default::default() + })); + let items2 = vec![SyncItem { + installed: out_log.clone(), + cumulative: Some(g17::sync_output::SignalBundle(log2.clone())), + }]; + let mut syncs2 = Syncs::new(items2, 0); + assert_eq!(syncs2.publish(&Fence(99)), Err(ENOMEM)); + assert!(log2.borrow().published.is_empty()); + syncs2.refuse(&Timeline, ENOMEM); + assert_eq!(log2.borrow().failed, vec![Fence(ENOMEM.0)]); + } +} + +mod fw_waits_test { + use super::{Error, Result, GFP_KERNEL}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Arc; + + const E2BIG: Error = Error(-7); + + pub(crate) struct QueueState(u32); + + pub(crate) struct KVec(Vec); + impl KVec { + fn with_capacity(cap: usize, _flags: u32) -> Result { + Ok(Self(Vec::with_capacity(cap))) + } + fn push(&mut self, v: T, _flags: u32) -> Result { + self.0.push(v); + Ok(()) + } + fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), T> { + self.0.push(v); + Ok(()) + } + } + impl core::ops::Deref for KVec { + type Target = [T]; + fn deref(&self) -> &[T] { &self.0 } + } + impl core::ops::DerefMut for KVec { + fn deref_mut(&mut self) -> &mut [T] { &mut self.0 } + } + + FW_WAITS_SRC + + #[test] + fn fw_waits_coalesces_deep_two_queue_timeline_chain_and_merges_engines() { + let q0 = Arc::new(QueueState(0)); + let q1 = Arc::new(QueueState(1)); + let mut waits = FwWaits::Empty; + // 64 alternating timeline hops across 2 queues coalesce to 2 per-queue entries. + for hop in 1..=64u64 { + let (q, r, c) = if hop % 2 == 1 { + (q0.clone(), Some((hop + 1) / 2), Some(hop)) + } else { + (q1.clone(), None, Some(hop / 2)) + }; + let origin = Arc::new(FenceOrigin::new(1, 7, q, [r, c])); + waits.push_unique(origin).unwrap(); + } + assert_eq!(waits.len(), 2); + let w0 = waits.iter().find(|w| Arc::ptr_eq(&w.queue, &q0)).unwrap(); + let w1 = waits.iter().find(|w| Arc::ptr_eq(&w.queue, &q1)).unwrap(); + assert_eq!(w0.last_ordinal, [Some(32), Some(63)]); + assert_eq!(w1.last_ordinal, [None, Some(32)]); + + // Merging an earlier render-only origin with a later compute-only origin on q1 keeps both. + waits + .push_unique(Arc::new(FenceOrigin::new(1, 7, q1.clone(), [Some(5), None]))) + .unwrap(); + let w1 = waits.iter().find(|w| Arc::ptr_eq(&w.queue, &q1)).unwrap(); + assert_eq!(w1.last_ordinal, [Some(5), Some(32)]); + } + + #[test] + fn fw_waits_caps_distinct_queues_at_max_fw_waits() { + let mut waits = FwWaits::Empty; + for idx in 0..MAX_FW_WAITS { + let q = Arc::new(QueueState(idx as u32)); + let origin = Arc::new(FenceOrigin::new(1, 7, q, [None, Some(1)])); + waits.push_unique(origin).unwrap(); + } + assert_eq!(waits.len(), MAX_FW_WAITS); + let extra = Arc::new(FenceOrigin::new( + 1, + 7, + Arc::new(QueueState(99)), + [None, Some(1)], + )); + assert_eq!(waits.push_unique(extra), Err(E2BIG)); + } +} +'''.replace('SIGNAL_BATCH_LINE', signal_batch_line).replace( + 'TIMELINE_COMPLETE_FN', timeline_complete_fn +).replace('INPUT_FENCES_SRC', input_fences_src).replace( + 'FW_WAITS_SRC', fw_waits_src +).replace( + 'SYNCS_SRC', syncs_src.replace('crate::g17::', 'g17::') +) + +with tempfile.TemporaryDirectory(prefix='m4-rust-timeline-') as directory: + directory = pathlib.Path(directory) + tl_unit = directory / 'timeline.rs' + tl_unit.write_text(timeline_harness) + tl_bin = directory / 'timeline' + for command in [ + rustc() + ['--edition=2021', '--test', '-Dwarnings', str(tl_unit), '-o', str(tl_bin)], + [str(tl_bin), '--nocapture'], + ]: + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + logs += result.stdout + print(result.stdout, end='') + (out / 'fence-signalling.log').write_text(logs) + if result.returncode: + raise SystemExit(result.returncode) + +# Exercise the actual production g17/sync_input.c collector against lightweight C dma_fence +# and dma_fence_chain shims to prove deep 2-queue timeline chains coalesce without -ENOSPC, +# skip signalled leaves, and preserve error leaves. +sync_input_c = root / 'drivers/gpu/drm/asahi/g17/sync_input.c' +sync_input_dir = sync_input_c.parent +c_harness = r''' +#include +#include +#include +#include +#include +#include +#include + +typedef uint64_t u64; +#define ASAHI_G17_SYNC_SCOPE_H 1 +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define GFP_KERNEL 0 + +struct dma_fence { + uint64_t context; + uint64_t seqno; + int status; + int refcount; + bool is_chain; + bool is_container; + struct dma_fence *chain_next; + struct dma_fence *chain_fence; +}; + +struct dma_fence_unwrap { + struct dma_fence *chain; + struct dma_fence *array; + unsigned int index; +}; + +static inline struct dma_fence *dma_fence_get(struct dma_fence *f) +{ + if (f) + ++f->refcount; + return f; +} + +static inline void dma_fence_put(struct dma_fence *f) +{ + if (f) { + assert(f->refcount > 0); + --f->refcount; + } +} + +static inline int dma_fence_get_status(struct dma_fence *f) +{ + return f ? f->status : 1; +} + +static inline bool dma_fence_is_later(struct dma_fence *f1, struct dma_fence *f2) +{ + return f1->seqno > f2->seqno; +} + +static inline bool dma_fence_is_container(struct dma_fence *f) +{ + return f && (f->is_chain || f->is_container); +} + +static inline struct dma_fence *dma_fence_unwrap_first(struct dma_fence *head, + struct dma_fence_unwrap *cursor) +{ + cursor->chain = NULL; + cursor->array = NULL; + cursor->index = 0; + if (!head) + return NULL; + if (head->is_chain) { + cursor->chain = dma_fence_get(head); + return head->chain_fence; + } + return head; +} + +static inline struct dma_fence *dma_fence_unwrap_next(struct dma_fence_unwrap *cursor) +{ + struct dma_fence *next; + + if (!cursor->chain) + return NULL; + next = cursor->chain->chain_next; + dma_fence_put(cursor->chain); + if (!next) { + cursor->chain = NULL; + return NULL; + } + cursor->chain = dma_fence_get(next); + return next->chain_fence; +} + +#define dma_fence_unwrap_for_each(fence, cursor, head) \ + for ((fence) = dma_fence_unwrap_first((head), (cursor)); (fence); \ + (fence) = dma_fence_unwrap_next((cursor))) + +static inline void *kmalloc_array(size_t n, size_t size, int flags) +{ + (void)flags; + return calloc(n, size); +} + +static inline void kfree(void *p) +{ + free(p); +} + +static inline struct dma_fence *__dma_fence_unwrap_merge(unsigned int n, + struct dma_fence **f, + struct dma_fence_unwrap *c) +{ + (void)n; + (void)f; + (void)c; + return NULL; +} + +static inline bool asahi_g17_is_scope(struct dma_fence *f) +{ + (void)f; + return false; +} + +static inline unsigned int asahi_g17_scope_children(struct dma_fence *f, + struct dma_fence *out[2]) +{ + (void)f; + (void)out; + return 0; +} + +#include "sync_input.h" +#include "sync_input.c" + +int main(void) +{ + enum { HOPS = 256 }; + struct dma_fence leaves[HOPS]; + struct dma_fence chains[HOPS]; + struct asahi_g17_fence_leaf out[4]; + int n, i; + + /* 256 alternating unsignalled hops across 2 contexts (10 and 20). */ + memset(leaves, 0, sizeof(leaves)); + memset(chains, 0, sizeof(chains)); + for (i = 0; i < HOPS; ++i) { + leaves[i].context = (i % 2 == 0) ? 10 : 20; + leaves[i].seqno = (uint64_t)(i / 2 + 1); + leaves[i].status = 0; + leaves[i].refcount = 1; + + chains[i].is_chain = true; + chains[i].refcount = 1; + chains[i].chain_fence = &leaves[i]; + chains[i].chain_next = (i > 0) ? &chains[i - 1] : NULL; + } + + /* Coalesced collector fits a 256-hop 2-queue timeline chain into capacity=4 with 2 leaves. */ + n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); + assert(n == 2); + assert((out[0].fence == &leaves[HOPS - 1] && out[1].fence == &leaves[HOPS - 2]) || + (out[1].fence == &leaves[HOPS - 1] && out[0].fence == &leaves[HOPS - 2])); + for (i = 0; i < n; ++i) { + assert(out[i].status == 0); + asahi_g17_put_fence(out[i].fence); + } + + /* Non-coalesced collector still sees distinct unsignalled leaves and hits -ENOSPC at cap=4. */ + n = asahi_g17_collect_fences(&chains[HOPS - 1], out, 4); + assert(n == -ENOSPC); + + /* Already-signalled leaves (status > 0) are skipped by both collectors. */ + for (i = 0; i < HOPS; ++i) + leaves[i].status = 1; + n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); + assert(n == 0); + n = asahi_g17_collect_fences(&chains[HOPS - 1], out, 4); + assert(n == 0); + + /* Error leaf (status < 0) is preserved even when a later same-context leaf is unsignalled. */ + leaves[5].status = -5; + leaves[HOPS - 1].status = 0; + leaves[HOPS - 2].status = 0; + n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); + assert(n == 3); + { + bool saw_err = false, saw_ctx10 = false, saw_ctx20 = false; + for (i = 0; i < n; ++i) { + if (out[i].fence == &leaves[5] && out[i].status == -5) + saw_err = true; + else if (out[i].fence == &leaves[HOPS - 2] && out[i].status == 0) + saw_ctx10 = true; + else if (out[i].fence == &leaves[HOPS - 1] && out[i].status == 0) + saw_ctx20 = true; + asahi_g17_put_fence(out[i].fence); + } + assert(saw_err && saw_ctx10 && saw_ctx20); + } + + /* Every refcount returns cleanly to 1 (no leaks or double puts). */ + for (i = 0; i < HOPS; ++i) { + assert(leaves[i].refcount == 1); + assert(chains[i].refcount == 1); + } + printf("sync_input C coalescing tests passed (256-hop chain -> 2 leaves, error preserved)\n"); + return 0; +} +''' + +with tempfile.TemporaryDirectory(prefix='m4-c-sync-input-') as directory: + directory = pathlib.Path(directory) + (directory / 'linux').mkdir() + for hdr in ('dma-fence.h', 'dma-fence-unwrap.h', 'slab.h', 'types.h'): + (directory / 'linux' / hdr).write_text('/* host shim */\n') + (directory / 'linux' / 'errno.h').write_text('#define ENOSPC 28\n#define EOPNOTSUPP 95\n') + (directory / 'sync_scope.h').write_text('/* host shim */\n') + c_unit = directory / 'test_sync_input.c' + c_unit.write_text(c_harness) + c_bin = directory / 'test_sync_input' + cc = shlex.split(os.environ.get('CC', 'cc')) + for command in [ + cc + ['-Wall', '-Wextra', '-Werror', '-I', str(directory), '-I', str(sync_input_dir), + str(c_unit), '-o', str(c_bin)], + [str(c_bin)], + ]: + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + logs += result.stdout + print(result.stdout, end='') + (out / 'fence-signalling.log').write_text(logs) + if result.returncode: + raise SystemExit(result.returncode) + (out / 'fence-signalling.json').write_text(json.dumps({ - 'passed': True, 'tests': 4, 'negative_compile_checks': 1, 'cpu_only': True, - 'scope': 'Production RAII annotation compiled in both CONFIG_LOCKDEP variants with task-cookie mock; does not exercise kernel lockdep or GPU lock ordering.', + 'passed': True, 'tests': 11, 'negative_compile_checks': 1, 'cpu_only': True, + 'scope': 'Production RAII annotation compiled in both CONFIG_LOCKDEP variants, g16 Timeline::complete() off-pending FIFO batch signalling, FwWaits per-queue coalescing, and g17/sync_input.c chain coalescing.', 'source_sha256': sha(production), + 'timeline_source_sha256': sha(fence_source_path), + 'sync_input_source_sha256': sha(sync_input_c), }, indent=2) + '\n') diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py index 62c21f5aad575e..fe6818252cc83d 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py @@ -18,8 +18,8 @@ queue_source = (SOURCE.parent / 'queue.rs').read_text() order_source = command_source[command_source.index('/// Exact queue-local command ordinal'):command_source.index('/// A validated render command.')] -def function(text, name): - marker = text.index('fn ' + name + '(') +def function_from(text, marker_text): + marker = text.index(marker_text) start = text.rfind('\n', 0, marker) + 1 first = text.index('{', marker) depth = 1 @@ -29,8 +29,12 @@ def function(text, name): at += 1 return text[start:at] -queue_methods = '\n'.join(function(queue_source, name) for name in ['cancel', 'check']) -methods = '\n'.join(function(source, name) for name in ['latch_failure', 'complete', 'finish', 'start', 'check_command_dependencies', 'command_retired', 'note_full_retirement', 'mark_terminal_retired']) +def function(text, name): + return function_from(text, 'fn ' + name + '(') + +queue_methods = '\n'.join(function(queue_source, name) for name in ['cancel', 'check', 'cancelled_through', 'is_compute_retired']) +methods = '\n'.join(function(source, name) for name in ['latch_failure', 'complete', 'finish', 'is_started', 'try_start_inline', 'start', 'check_command_dependencies', 'command_retired', 'note_full_retirement', 'mark_terminal_retired', 'waits_on_queue']) +push_method = function_from(source, 'pub(crate) fn push(&mut self, job: Arc') fence_methods = '\n'.join(function(fence_source, name) for name in ['dependency_status', 'check_dependencies', 'wait_dependencies']) harness = r''' #![allow(dead_code)] @@ -43,7 +47,7 @@ def function(text, name): type Result = core::result::Result; const EIO:Error=Error(-5); const ENODEV:Error=Error(-19); const ECANCELED:Error=Error(-125); const ETIMEDOUT:Error=Error(-110);const ENOMEM:Error=Error(-12);const EAGAIN:Error=Error(-11); const EINVAL:Error=Error(-22); -const EOVERFLOW:Error=Error(-75); const NONE:u16=u16::MAX; +const EOVERFLOW:Error=Error(-75); const NONE:u16=u16::MAX; const RENDER:usize=0; const COMPUTE:usize=1; ORDER_SOURCE pub mod task { pub const MAX_SCHEDULE_TIMEOUT:i64=i64::MAX; } struct InputState { status:AtomicI32,waits:AtomicUsize,interrupted:AtomicI64,gate:Mutex<()>,changed:Condvar } @@ -95,34 +99,101 @@ def function(text, name): self.signals.lock().unwrap().push((result,status)); } } -mod command { pub(crate) use super::Order; } -struct QueueState { completed:[AtomicU64;2],cancelled_at:[AtomicU64;2] } +mod command { pub(crate) use super::{Order, COMPUTE}; } +struct QueueState { completed:[AtomicU64;2],published:[AtomicU64;2],cancelled_at:[AtomicU64;2],compute_ooo:AtomicU64 } impl QueueState { QUEUE_METHODS } -struct Job { id:u64,vm:Vm,_guard:Guard,progress:Progress,started:AtomicBool,accepted:AtomicBool,fence:Fence,commands:Vec<()>,inputs:Vec,orders:Vec,queue:Arc,full_retired:AtomicU32,terminal_retired:AtomicBool } -struct Shared { crashed:AtomicBool,submitted:Mutex>,submit_result:Result } +struct FenceOrigin { queue:Arc, last_ordinal:[Option;2], failed:AtomicBool } +impl FenceOrigin { + fn new(queue:Arc, last_ordinal:[Option;2])->Arc { Arc::new(Self{queue,last_ordinal,failed:AtomicBool::new(false)}) } + fn mark_failed(&self) { self.failed.store(true,Ordering::Release); } + fn is_failed(&self)->bool { self.failed.load(Ordering::Acquire) } +} +struct Job { id:u64,vm:Vm,_guard:Guard,progress:Progress,started:AtomicBool,accepted:AtomicBool,fence:Fence,commands:Vec<()>,inputs:Vec,origin:Arc,fw_waits:Vec>,orders:Vec,queue:Arc,full_retired:AtomicU64,terminal_retired:AtomicBool } +struct Shared { crashed:AtomicBool,sleeping:AtomicBool,recovering:AtomicBool,contended:AtomicBool,submitted:Mutex>,submit_result:Result } impl Shared { fn new()->Arc { - Arc::new(Self{crashed:AtomicBool::new(false),submitted:Mutex::new(vec![]),submit_result:Ok(())}) + Arc::new(Self{crashed:AtomicBool::new(false),sleeping:AtomicBool::new(false),recovering:AtomicBool::new(false),contended:AtomicBool::new(false),submitted:Mutex::new(vec![]),submit_result:Ok(())}) } + fn note_submitter(&self) {} + fn wake_publish(&self) {} fn submit(&self,job:Arc)->Result { self.submitted.lock().unwrap().push(job.id); self.submit_result } + fn try_submit_inline(&self,job:Arc)->Option { + if self.contended.load(Ordering::Acquire) || self.sleeping.load(Ordering::Acquire) || self.recovering.load(Ordering::Acquire) { return None; } + Some(self.submit(job)) + } } impl Job { METHODS } +struct SchedJob { job:Arc, shared:Arc, pending_sched:Arc, counted:bool } +impl SchedJob { + fn finish_pending(&mut self) { + if self.counted { + self.counted = false; + self.pending_sched.fetch_sub(1, Ordering::AcqRel); + } + } + fn run(&mut self) { + self.job.start(&self.shared); + self.finish_pending(); + } +} +impl Drop for SchedJob { + fn drop(&mut self) { + self.finish_pending(); + } +} +struct ArmedJob { job:SchedJob, pushed:Arc>>, queue:Arc>> } +impl ArmedJob { + fn push(self) { + self.pushed.lock().unwrap().push(self.job.job.id); + self.queue.lock().unwrap().push(self.job); + } +} +struct PendingJob { job:SchedJob, deps:Vec, pushed:Arc>>, queue:Arc>>, fail_dep:bool } +impl PendingJob { + fn add_dependency(&mut self, fence:InputFence)->Result { + if self.fail_dep { return Err(ENOMEM); } + self.deps.push(fence); + Ok(()) + } + fn arm(self)->ArmedJob { ArmedJob { job:self.job, pushed:self.pushed, queue:self.queue } } +} +struct Entity { new_jobs:AtomicUsize, pushed:Arc>>, queue:Arc>>, fail_new:bool, fail_dep:bool } +impl Entity { + fn new()->Self { Self { new_jobs:AtomicUsize::new(0), pushed:Arc::new(Mutex::new(vec![])), queue:Arc::new(Mutex::new(vec![])), fail_new:false, fail_dep:false } } + fn new_job(&mut self, _credits:u32, job:SchedJob)->Result { + self.new_jobs.fetch_add(1, Ordering::AcqRel); + if self.fail_new { return Err(ENOMEM); } + Ok(PendingJob { job, deps:vec![], pushed:self.pushed.clone(), queue:self.queue.clone(), fail_dep:self.fail_dep }) + } + fn drain_run(&self) { + let mut jobs = core::mem::take(&mut *self.queue.lock().unwrap()); + for mut job in jobs.drain(..) { + job.run(); + } + } +} +struct Scheduler { entity:Entity, pending_sched:Arc } +impl Scheduler { + fn new()->Self { Self { entity:Entity::new(), pending_sched:Arc::new(AtomicUsize::new(0)) } } + PUSH_METHOD +} fn job(id:u64,status:Arc)->Arc { job_with_inputs(id,status,vec![]) } fn job_with_inputs(id:u64,status:Arc,inputs:Vec)->Arc { let orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap(),Order::new([0,0],[0,1],[NONE;2],[0;2],1).unwrap()]; - job_with_orders(id,status,inputs,orders,Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2]})) + job_with_orders(id,status,inputs,orders,Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)})) } fn job_with_orders(id:u64,status:Arc,inputs:Vec,orders:Vec,queue:Arc)->Arc { + let origin=FenceOrigin::new(queue.clone(),[None,Some(orders.len() as u64)]); Arc::new(Job{id,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), progress:Progress{signaled:AtomicBool::new(false),sent:AtomicU32::new(0),next:AtomicU32::new(0),pending:AtomicBool::new(false)},started:AtomicBool::new(false),accepted:AtomicBool::new(true), - fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![();orders.len()],inputs,orders,queue, - full_retired:AtomicU32::new(0),terminal_retired:AtomicBool::new(false)}) + fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![();orders.len()],inputs,origin,fw_waits:vec![],orders,queue, + full_retired:AtomicU64::new(0),terminal_retired:AtomicBool::new(false)}) } #[test] fn a_failed_vm_is_rejected_without_an_input_error() { @@ -278,7 +349,7 @@ def function(text, name): } #[test] fn cancellation_checks_both_command_ordinal_and_cross_engine_failed_prefix() { - let queue=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2]}); + let queue=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); let cutoff=Order::new([0,2],[0,0],[NONE;2],[0;2],1).unwrap();queue.cancel(&[cutoff],0); let earlier=Order::new([0,1],[0,0],[NONE;2],[0;2],1).unwrap(); let independent_render=Order::new([0,3],[0,0],[NONE;2],[0;2],0).unwrap(); @@ -292,7 +363,7 @@ def function(text, name): } #[test] fn exact_prefix_does_not_wait_for_the_aggregate_or_next_ordinal() { - let queue=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2]}); + let queue=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); let status=Arc::new(Status::new()); let old=job_with_orders(1,status.clone(),vec![],vec![ Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap(), @@ -370,7 +441,7 @@ def function(text, name): #[test] fn never_published_capacity_failure_closes_only_its_queue() { let status=Arc::new(Status::new());let failed=job(1,status.clone()); - let shared=Arc::new(Shared{crashed:AtomicBool::new(false),submitted:Mutex::new(vec![]),submit_result:Err(ENOMEM)}); + let shared=Arc::new(Shared{crashed:AtomicBool::new(false),sleeping:AtomicBool::new(false),recovering:AtomicBool::new(false),contended:AtomicBool::new(false),submitted:Mutex::new(vec![]),submit_result:Err(ENOMEM)}); failed.start(&shared); assert_eq!(failed.fence.signals.lock().unwrap()[0],(Err(ENOMEM),-12)); assert_eq!(failed.queue.check(&failed.orders[0]),Err(ECANCELED));assert_eq!(status.get(),0); @@ -379,19 +450,195 @@ def function(text, name): assert_eq!(*shared.submitted.lock().unwrap(),vec![2]);assert_eq!(status.get(),0); } #[test] -fn full_receipts_are_consecutive_bounded_and_once() { +fn full_receipts_are_unique_bounded_and_allow_cross_engine_order() { let queued=job(1,Arc::new(Status::new())); assert_eq!(queued.note_full_retirement(0,1),Err(EINVAL)); queued.progress.sent.store(2,Ordering::Release); assert_eq!(queued.note_full_retirement(0,0),Err(EINVAL)); + // Command 1 may retire before command 0 when compute and render run concurrently. + queued.note_full_retirement(1,1).unwrap(); assert_eq!(queued.note_full_retirement(1,1),Err(EIO)); + assert_eq!(queued.mark_terminal_retired(),Err(EIO)); queued.note_full_retirement(0,1).unwrap(); assert_eq!(queued.note_full_retirement(0,1),Err(EIO)); assert_eq!(queued.note_full_retirement(1,2),Err(EINVAL)); assert_eq!(queued.note_full_retirement(u32::MAX,1),Err(EOVERFLOW)); - queued.note_full_retirement(1,1).unwrap(); + queued.progress.next.store(2,Ordering::Release); + queued.mark_terminal_retired().unwrap(); +} +#[test] +fn inline_start_submits_once_and_falls_back_on_pending_input_or_contention() { + let status=Arc::new(Status::new()); + let shared=Shared::new(); + // Ready job with signalled input submits inline; subsequent drm_sched start() is a no-op. + let ready=job_with_inputs(10,status.clone(),vec![InputFence::new(1)]); + assert!(ready.try_start_inline(&shared)); + assert!(ready.is_started()); + assert_eq!(*shared.submitted.lock().unwrap(),vec![10]); + ready.start(&shared); + assert_eq!(*shared.submitted.lock().unwrap(),vec![10]); + // Unsignalled input defers to drm_sched without marking started. + let pending=job_with_inputs(11,status.clone(),vec![InputFence::new(0)]); + assert!(!pending.try_start_inline(&shared)); + assert!(!pending.is_started()); + assert_eq!(*shared.submitted.lock().unwrap(),vec![10]); + // Recovering device defers to drm_sched without blocking or marking started. + shared.recovering.store(true,Ordering::Release); + let rec=job(13,status.clone()); + assert!(!rec.try_start_inline(&shared)); + assert!(!rec.is_started()); + shared.recovering.store(false,Ordering::Release); + // Contended device mutex defers to drm_sched without blocking or marking started. + shared.contended.store(true,Ordering::Release); + let contended=job(12,status.clone()); + assert!(!contended.try_start_inline(&shared)); + assert!(!contended.is_started()); + assert_eq!(*shared.submitted.lock().unwrap(),vec![10]); + shared.contended.store(false,Ordering::Release); + contended.start(&shared); + assert!(contended.is_started()); + assert_eq!(*shared.submitted.lock().unwrap(),vec![10,12]); +} +#[test] +fn scheduler_push_bypasses_drm_sched_on_inline_start_and_rolls_back_on_fallback_enomem() { + let status=Arc::new(Status::new()); + let shared=Shared::new(); + let mut sched=Scheduler::new(); + // Ready jobs bypass entity.new_job() and armed.push() completely. + let j1=job_with_inputs(1,status.clone(),vec![InputFence::new(1)]); + j1.accepted.store(false,Ordering::Release); + sched.push(j1.clone(),shared.clone()).unwrap(); + assert!(j1.is_started()); + assert!(j1.accepted.load(Ordering::Acquire)); + assert_eq!(sched.entity.new_jobs.load(Ordering::Acquire),0); + assert!(sched.entity.pushed.lock().unwrap().is_empty()); + assert_eq!(*shared.submitted.lock().unwrap(),vec![1]); + // Second ready job also bypasses drm_sched because j1 is already started. + let j2=job(2,status.clone()); + sched.push(j2.clone(),shared.clone()).unwrap(); + assert!(j2.is_started()); + assert_eq!(sched.entity.new_jobs.load(Ordering::Acquire),0); + assert_eq!(*shared.submitted.lock().unwrap(),vec![1,2]); + // Unsignalled input falls back to drm_sched; subsequent job waits for predecessor start. + let f3=InputFence::new(0); + let j3=job_with_inputs(3,status.clone(),vec![f3.clone()]); + sched.push(j3.clone(),shared.clone()).unwrap(); + assert!(!j3.is_started()); + assert_eq!(sched.entity.new_jobs.load(Ordering::Acquire),1); + assert_eq!(*sched.entity.pushed.lock().unwrap(),vec![3]); + let j4=job(4,status.clone()); + sched.push(j4.clone(),shared.clone()).unwrap(); + assert!(!j4.is_started()); + assert_eq!(sched.entity.new_jobs.load(Ordering::Acquire),2); + assert_eq!(*sched.entity.pushed.lock().unwrap(),vec![3,4]); + // Fallback ENOMEM rolls back accepted and pending_sched without poisoning queue ordering. + f3.signal(1); + sched.entity.drain_run(); + assert_eq!(sched.pending_sched.load(Ordering::Acquire),0); + sched.entity.fail_new=true; + let j5=job_with_inputs(5,status.clone(),vec![InputFence::new(0)]); + j5.accepted.store(false,Ordering::Release); + assert_eq!(sched.push(j5.clone(),shared.clone()),Err(ENOMEM)); + assert!(!j5.accepted.load(Ordering::Acquire)); + assert!(!j5.is_started()); + assert_eq!(sched.pending_sched.load(Ordering::Acquire),0); + // Scheduler retains zero Arc references after inline or drm_sched completion. + let w1=Arc::downgrade(&j1); + let w3=Arc::downgrade(&j3); + let w4=Arc::downgrade(&j4); + drop((j1,j2,j3,j4,j5)); + assert!(w1.upgrade().is_none(), "inline job must not be retained by Scheduler"); + assert!(w3.upgrade().is_none(), "drm_sched job must not be retained by Scheduler after run"); + assert!(w4.upgrade().is_none(), "queued job must not be retained by Scheduler after run"); } -'''.replace('QUEUE_METHODS', queue_methods).replace('ORDER_SOURCE', order_source).replace('FENCE_METHODS', fence_methods).replace('METHODS', methods.replace('super::fence::','fence::')) +#[test] +fn compute_ooo_retirement_tracks_gaps_and_rejects_unpublished_or_duplicate() { + let queue=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[AtomicU64::new(0),AtomicU64::new(4)],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let orders=vec![ + Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap(), + Order::new([0,0],[0,1],[NONE;2],[0;2],1).unwrap(), + Order::new([0,0],[0,2],[NONE;2],[0;2],1).unwrap(), + Order::new([0,0],[0,3],[NONE;2],[0;2],1).unwrap(), + Order::new([0,0],[0,4],[NONE;2],[0;2],1).unwrap(), + ]; + let qjob=job_with_orders(1,Arc::new(Status::new()),vec![],orders,queue.clone()); + // Unpublished sequence 5 cannot retire OOO. + assert_eq!(qjob.command_retired(4),Err(EIO)); + // Sequences 2 and 4 retire OOO before 1 and 3. + qjob.command_retired(1).unwrap(); + qjob.command_retired(3).unwrap(); + assert_eq!(queue.completed[COMPUTE].load(Ordering::Acquire),0); + assert!(!queue.is_compute_retired(1)); + assert!(queue.is_compute_retired(2)); + assert!(!queue.is_compute_retired(3)); + assert!(queue.is_compute_retired(4)); + // Duplicate OOO retirement is rejected. + assert_eq!(qjob.command_retired(1),Err(EIO)); + assert_eq!(qjob.command_retired(3),Err(EIO)); + // Retiring 1 advances contiguous frontier to 2 and re-anchors bit 0 to seq 4! + qjob.command_retired(0).unwrap(); + assert_eq!(queue.completed[COMPUTE].load(Ordering::Acquire),2); + assert!(queue.is_compute_retired(1)); + assert!(queue.is_compute_retired(2)); + assert!(!queue.is_compute_retired(3)); + assert!(queue.is_compute_retired(4)); + assert_eq!(qjob.command_retired(3),Err(EIO)); + // Retiring 3 drains seq 4 as well, advancing contiguous frontier to 4 with clean bitmap. + qjob.command_retired(2).unwrap(); + assert_eq!(queue.completed[COMPUTE].load(Ordering::Acquire),4); + assert_eq!(queue.compute_ooo.load(Ordering::Acquire),0); +} +#[test] +fn fw_wait_defers_until_producer_queue_publishes_and_propagates_failure() { + let q1=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let q2=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let status=Arc::new(Status::new()); + let p_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let c_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let prod=job_with_orders(1,status.clone(),vec![],p_orders,q1.clone()); + let cons=Arc::new(Job{ + id:2,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), + progress:Progress{signaled:AtomicBool::new(false),sent:AtomicU32::new(0),next:AtomicU32::new(0),pending:AtomicBool::new(false)}, + started:AtomicBool::new(false),accepted:AtomicBool::new(true), + fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![()],inputs:vec![], + origin:FenceOrigin::new(q2.clone(),[None,Some(1)]), + fw_waits:vec![prod.origin.clone()],orders:c_orders,queue:q2.clone(), + full_retired:AtomicU64::new(0),terminal_retired:AtomicBool::new(false), + }); + assert!(cons.waits_on_queue(&q1)); + assert!(!cons.waits_on_queue(&q2)); + // Producer not yet published -> consumer defers with EAGAIN. + assert_eq!(cons.check_command_dependencies(0),Err(EAGAIN)); + // Once producer publishes ordinal 1, consumer is ready for firmware handoff. + q1.published[COMPUTE].store(1,Ordering::Release); + assert_eq!(cons.check_command_dependencies(0),Ok(())); + // Producer failure marks origin failed and cancels consumer with ECANCELED. + prod.latch_failure(ECANCELED); + assert!(prod.origin.is_failed()); + assert_eq!(cons.check_command_dependencies(0),Err(ECANCELED)); +} +#[test] +fn fw_wait_cancels_when_producer_queue_cancels_ordinal() { + let q1=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[AtomicU64::new(0),AtomicU64::new(1)],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let q2=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let status=Arc::new(Status::new()); + let p_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let c_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let prod=job_with_orders(1,status.clone(),vec![],p_orders.clone(),q1.clone()); + let cons=Arc::new(Job{ + id:2,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), + progress:Progress{signaled:AtomicBool::new(false),sent:AtomicU32::new(0),next:AtomicU32::new(0),pending:AtomicBool::new(false)}, + started:AtomicBool::new(false),accepted:AtomicBool::new(true), + fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![()],inputs:vec![], + origin:FenceOrigin::new(q2.clone(),[None,Some(1)]), + fw_waits:vec![prod.origin.clone()],orders:c_orders,queue:q2, + full_retired:AtomicU64::new(0),terminal_retired:AtomicBool::new(false), + }); + assert_eq!(cons.check_command_dependencies(0),Ok(())); + q1.cancel(&p_orders,0); + assert_eq!(cons.check_command_dependencies(0),Err(ECANCELED)); +} +'''.replace('QUEUE_METHODS', queue_methods).replace('ORDER_SOURCE', order_source).replace('FENCE_METHODS', fence_methods).replace('METHODS', methods.replace('super::fence::','fence::').replace('super::command::','command::')).replace('PUSH_METHOD', push_method) with tempfile.TemporaryDirectory(prefix='m4-rust-job-') as directory: directory=pathlib.Path(directory); test=directory/'test.rs'; test.write_text(harness) @@ -402,6 +649,6 @@ def function(text, name): (OUT/'job-failure-host.log').write_text(result.stdout+result.stderr) (OUT/'job-failure-host.json').write_text(json.dumps({ 'source':str(SOURCE),'sha256':hashlib.sha256(SOURCE.read_bytes()).hexdigest(), - 'result':'pass','test_groups':23, + 'result':'pass','test_groups':25, 'limitations':'Production Job methods with host VM/fence mocks; actual DRM scheduler and firmware publication gates require kernel and execution integration validation.' },indent=2)+'\n') diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py index 485241a5644636..8b39a4ce54783b 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py @@ -24,12 +24,12 @@ def body(source,marker): static TRIP_LOAD:AtomicUsize=AtomicUsize::new(0); struct AtomicBool(StdAtomicBool);impl AtomicBool{fn new(v:bool)->Self{Self(StdAtomicBool::new(v))}fn store(&self,v:bool,o:Ordering){self.0.store(v,o);}fn load(&self,o:Ordering)->bool{let n=TRIP_LOAD.load(Ordering::Relaxed);if n!=0&&TRIP_LOAD.fetch_sub(1,Ordering::Relaxed)==1{self.0.store(true,Ordering::Release);}self.0.load(o)}} const UAT_NUM_CTX:usize=64;const UAT_USER_CTX_START:usize=1;const TTBR_VALID:u64=1;const TTBR_ASID_SHIFT:usize=48;const UAT_PGSZ:usize=0x4000; -static NODE_DROPS:AtomicUsize=AtomicUsize::new(0);static MUTATIONS:AtomicUsize=AtomicUsize::new(0);static ROOT_FREES:AtomicUsize=AtomicUsize::new(0);static TREE_FREES:AtomicUsize=AtomicUsize::new(0);static FWCTL:AtomicUsize=AtomicUsize::new(0);static LEAF_CLEARS:AtomicUsize=AtomicUsize::new(0);static BARRIERS:AtomicUsize=AtomicUsize::new(0); +static NODE_DROPS:AtomicUsize=AtomicUsize::new(0);static MUTATIONS:AtomicUsize=AtomicUsize::new(0);static ROOT_FREES:AtomicUsize=AtomicUsize::new(0);static TREE_FREES:AtomicUsize=AtomicUsize::new(0);static FWCTL:AtomicUsize=AtomicUsize::new(0);static LEAF_CLEARS:AtomicUsize=AtomicUsize::new(0);static BARRIERS:AtomicUsize=AtomicUsize::new(0);static CLEANS:StdMutex>=StdMutex::new(Vec::new()); macro_rules! pr_err{($($t:tt)*)=>{()};}macro_rules! mod_pr_debug{($($t:tt)*)=>{()};}macro_rules! mod_dev_dbg{($($t:tt)*)=>{()};}macro_rules! dev_err{($($t:tt)*)=>{()};} struct MutexBackend;struct Mutex(StdMutex);implMutex{fn new(v:T)->Self{Self(StdMutex::new(v))}fn lock(&self)->Guard<'_,T,MutexBackend>{Guard(self.0.lock().unwrap(),std::marker::PhantomData)}} struct Guard<'a,T,M>(std::sync::MutexGuard<'a,T>,std::marker::PhantomData);implDeref for Guard<'_,T,M>{type Target=T;fn deref(&self)->&T{&self.0}}implDerefMut for Guard<'_,T,M>{fn deref_mut(&mut self)->&mut T{&mut self.0}} struct Monotonic;struct Delta;impl Delta{fn from_millis(n:u64)->u64{n}}struct Instant{n:std::cell::Cell,p:std::marker::PhantomData}implInstant{fn now()->Self{Self{n:std::cell::Cell::new(0),p:std::marker::PhantomData}}fn elapsed(&self)->u64{let n=self.n.get();self.n.set(n+1);n}} -mod pgtable{pub fn clean_poc(_p:*const u8,_n:usize){super::BARRIERS.fetch_add(1,super::Ordering::Relaxed);}pub fn poc_barrier(){super::BARRIERS.fetch_add(1,super::Ordering::Relaxed);}} +mod pgtable{pub fn clean_poc(p:*const u8,n:usize){super::CLEANS.lock().unwrap().push((p as usize,n));super::BARRIERS.fetch_add(1,super::Ordering::Relaxed);}pub fn poc_barrier(){super::BARRIERS.fetch_add(1,super::Ordering::Relaxed);}} mod mem{pub fn sync(){super::BARRIERS.fetch_add(1,super::Ordering::Relaxed);}pub fn tlbi_asid(_:u8){}} #[derive(Clone,Copy,PartialEq,Eq)]enum UatFirmware{Handoff,PublishedRoots} struct Handoff{lock_ap:AtomicU8,lock_fw:AtomicU8,turn:AtomicU32,cur_slot:AtomicU32}impl Handoff{fn new()->Self{Self{lock_ap:AtomicU8::new(0),lock_fw:AtomicU8::new(0),turn:AtomicU32::new(0),cur_slot:AtomicU32::new(0xffff)}} @@ -40,9 +40,9 @@ def body(source,marker): mid=r''' } struct Quirks{handoff_lock:bool,clean_tables:bool} -struct SlotTTBS{ttb0:AtomicU64,ttb1:AtomicU64}struct UatShared{handoff:Handoff,ttbs:[SlotTTBS;64],map_kernel_to_user:bool,kernel_ttb1:u64,binding_generations:[u64;64],binding_published:[bool;64],owned_user_roots:[u64;64],quirks:Quirks} +struct SlotTTBS{ttb0:AtomicU64,ttb1:AtomicU64}struct UatShared{handoff:Handoff,ttbs:[SlotTTBS;64],map_kernel_to_user:bool,kernel_ttb1:u64,binding_generations:[u64;64],binding_published:[bool;64],owned_user_roots:[u64;64],clean_poc:bool,quirks:Quirks} impl UatShared{fn handoff(&self)->&Handoff{&self.handoff}fn ttbs(&self)->&[SlotTTBS;64]{&self.ttbs}} -struct UatInner{firmware:UatFirmware,m4_adopted:bool,failed:AtomicBool,shared:Mutex} +struct UatInner{firmware:UatFirmware,m4_adopted:bool,clean_poc:bool,failed:AtomicBool,shared:Mutex} ''' mid=mid.replace('impl UatShared{','impl UatShared{'+''.join(body(mm,m) for m in ['fn handoff_lock(', 'fn handoff_unlock(', 'fn publish_slot('])) raii='#[path="'+str(ROOT/'drivers/gpu/drm/asahi/mmu/ppl.rs')+'"]mod ppl;\n'+'\n'.join(body(mm,m) for m in [ @@ -51,7 +51,8 @@ def body(source,marker): ]) inner='impl UatInner{\n'+'\n'.join(body(mm,m) for m in ['fn lock(&self) -> Guard', 'fn check_m4(', 'fn lock_handoff(', 'fn lock_m4_upper('])+'\n}\n' models=r''' -fn uat(m4:bool,firmware:UatFirmware)->Rc{Rc::new(UatInner{firmware,m4_adopted:m4,failed:AtomicBool::new(false),shared:Mutex::new(UatShared{handoff:Handoff::new(),ttbs:std::array::from_fn(|_|SlotTTBS{ttb0:AtomicU64::new(0),ttb1:AtomicU64::new(0)}),map_kernel_to_user:!m4,kernel_ttb1:0x800000000,binding_generations:[0;64],binding_published:[false;64],owned_user_roots:[0;64],quirks:Quirks{handoff_lock:true,clean_tables:false}})})} +fn uat(m4:bool,firmware:UatFirmware)->Rc{uat_with(m4,firmware,false,false)} +fn uat_with(m4:bool,firmware:UatFirmware,clean_poc:bool,clean_tables:bool)->Rc{Rc::new(UatInner{firmware,m4_adopted:m4,clean_poc,failed:AtomicBool::new(false),shared:Mutex::new(UatShared{handoff:Handoff::new(),ttbs:std::array::from_fn(|_|SlotTTBS{ttb0:AtomicU64::new(0),ttb1:AtomicU64::new(0)}),map_kernel_to_user:!m4,kernel_ttb1:0x800000000,binding_generations:[0;64],binding_published:[false;64],owned_user_roots:[0;64],clean_poc,quirks:Quirks{handoff_lock:true,clean_tables}})})} #[derive(Clone,Copy)]struct Prot{cached:bool}impl Prot{fn is_cached_noncoherent(&self)->bool{self.cached}} struct Mutation;impl Drop for Mutation{fn drop(&mut self){MUTATIONS.fetch_sub(1,Ordering::Relaxed);}} struct MapTable{fail:bool}impl MapTable{fn unmap_pages(&mut self,_r:Range)->Result{LEAF_CLEARS.fetch_add(1,Ordering::Relaxed);if self.fail{Err(EIO)}else{Ok(())}}} @@ -87,7 +88,7 @@ def body(source,marker): impl VmInner{fn ttb(&self)->u64{self.page_table.ttb}} '''+body(mm,'impl Drop for VmInner {') main=r''' -fn reset(){TRIP_LOAD.store(0,Ordering::Relaxed);for c in [&NODE_DROPS,&MUTATIONS,&ROOT_FREES,&TREE_FREES,&FWCTL,&LEAF_CLEARS,&BARRIERS]{c.store(0,Ordering::Relaxed);}} +fn reset(){TRIP_LOAD.store(0,Ordering::Relaxed);CLEANS.lock().unwrap().clear();for c in [&NODE_DROPS,&MUTATIONS,&ROOT_FREES,&TREE_FREES,&FWCTL,&LEAF_CLEARS,&BARRIERS]{c.store(0,Ordering::Relaxed);}} fn mapping(u:Rc,cached:bool,fail_unmap:bool)->(KernelMapping,Rc){let bo=Rc::new(PinBo);let n=Node{va:0xfffffc2000000000,inner:KernelMappingInner{owner:Rc::new(Owner(RefCell::new(OwnerState{dev:(),is_kernel:true,page_table:MapTable{fail:fail_unmap}}))),uat_inner:u,prot:Prot{cached},mapped_size:0x4000,_bo:bo.clone(),private:None}};(KernelMapping(ManuallyDrop::new(n)),bo)} fn mapping_tests(){ for (m4,firmware,cached,node_free,fwctl) in [(false,UatFirmware::Handoff,false,1,0),(false,UatFirmware::Handoff,true,1,1),(false,UatFirmware::PublishedRoots,true,1,0),(true,UatFirmware::Handoff,false,1,0),(true,UatFirmware::Handoff,true,0,0)]{reset();let u=uat(m4,firmware);let (m,bo)=mapping(u.clone(),cached,false);drop(m);assert_eq!(NODE_DROPS.load(Ordering::Relaxed),node_free);assert_eq!(FWCTL.load(Ordering::Relaxed),fwctl);assert_eq!(Rc::strong_count(&bo),if node_free==0{2}else{1});assert_eq!(u.failed.load(Ordering::Acquire),m4&&cached);assert_eq!(u.shared.lock().handoff.lock_ap.load(Ordering::Relaxed),0);} @@ -107,6 +108,35 @@ def body(source,marker): // A previously faulted M4 is refused before any new lock or TTBAT generation mutation. let u=uat(true,UatFirmware::Handoff);u.failed.store(true,Ordering::Release);let backend=Uat{inner:u.clone(),slots:Allocator};assert!(backend.bind(&Vm{id:9,binding:new_binding()}).is_err());assert_eq!(u.shared.lock().binding_generations[4],0); } +// A non-snooping walker sees the TTBAT slot written back exactly once on both bind and +// VmInner::drop through UatShared::publish_slot: for an adopted UAT without the clean_tables +// quirk (clean_poc only) and with the quirk. A coherent walker (neither) gets no clean. +fn ttbat_clean_tests(){ + for (clean_poc,clean_tables,cleaned) in [(false,false,false),(true,false,true),(false,true,true),(true,true,true)]{ + reset(); + let u=uat_with(false,UatFirmware::Handoff,clean_poc,clean_tables); + let backend=Uat{inner:u.clone(),slots:Allocator}; + let binding=new_binding(); + let bound=backend.bind(&Vm{id:9,binding:binding.clone()}).unwrap(); + assert_eq!(bound.1,4); + let slot={ + let s=u.shared.lock(); + let slot=(core::ptr::from_ref(&s.ttbs[4]) as usize,size_of::()); + assert_eq!(CLEANS.lock().unwrap().iter().filter(|c|**c==slot).count(),usize::from(cleaned)); + assert_eq!(s.ttbs[4].ttb0.load(Ordering::Relaxed),0x804000001|(4<<48)); + slot + }; + CLEANS.lock().unwrap().clear(); + binding.lock().active_users=0; + drop(bound); + drop(VmInner{id:9,binding,uat_inner:u.clone(),page_table:UatPageTable::new()}); + let s=u.shared.lock(); + assert_eq!(CLEANS.lock().unwrap().iter().filter(|c|**c==slot).count(),usize::from(cleaned)); + assert_eq!(s.ttbs[4].ttb0.load(Ordering::Relaxed),0); + assert_eq!(s.ttbs[4].ttb1.load(Ordering::Relaxed),0); + assert_eq!(s.owned_user_roots[4],0); + } +} fn generation_churn_test(){ let u=uat(true,UatFirmware::Handoff);let backend=Uat{inner:u.clone(),slots:Allocator}; let published=backend.bind(&Vm{id:1,binding:new_binding()}).unwrap();assert_eq!(published.0.binding.lock().generation,1); @@ -116,7 +146,7 @@ def body(source,marker): let next=backend.bind(&Vm{id:999,binding:new_binding()}).unwrap();assert_eq!(next.0.binding.lock().generation,3); } fn vm_drop_tests(){for (m4,blocked,pre_failed) in [(false,false,false),(true,false,false),(true,true,false),(true,false,true)]{reset();let u=uat(m4,UatFirmware::Handoff);let binding=new_binding();binding.lock().bind_token=Some(Token(3));let low=0x804000001|(4<<48);{let mut s=u.shared.lock();s.ttbs[4].ttb0.store(low,Ordering::Release);s.owned_user_roots[4]=low;s.handoff.lock_fw.store(u8::from(blocked),Ordering::Release);}u.failed.store(pre_failed,Ordering::Release);drop(VmInner{id:9,binding,uat_inner:u.clone(),page_table:UatPageTable::new()});let uncertain=blocked||pre_failed;assert_eq!(ROOT_FREES.load(Ordering::Relaxed),usize::from(!uncertain));assert_eq!(TREE_FREES.load(Ordering::Relaxed),usize::from(!uncertain));let s=u.shared.lock();assert_eq!(s.ttbs[4].ttb0.load(Ordering::Relaxed),if uncertain{low}else{0});assert_eq!(s.owned_user_roots[4],if uncertain{low}else{0});assert_eq!(s.handoff.lock_ap.load(Ordering::Relaxed),0);assert_eq!(u.failed.load(Ordering::Acquire),uncertain);}} -fn main(){generation_churn_test();mapping_tests();page_tests();bind_tests();vm_drop_tests();fail_stop_race_tests();println!("Shared Rust fault injection passed: G15/Neo normal and cached frees exactly once; M4 cached/timeout/partial-unmap retains node+backing+VA; guards released before free; M4 bind timeout changes no TTBAT/generation; VM-drop timeout retains physical tables/root; faulted M4 admission rejects before and after lock acquisition (mock hardware)");} +fn main(){ttbat_clean_tests();generation_churn_test();mapping_tests();page_tests();bind_tests();vm_drop_tests();fail_stop_race_tests();println!("Shared Rust fault injection passed: G15/Neo normal and cached frees exactly once; M4 cached/timeout/partial-unmap retains node+backing+VA; guards released before free; M4 bind timeout changes no TTBAT/generation; VM-drop timeout retains physical tables/root; faulted M4 admission rejects before and after lock acquisition; a non-snooping adopted UAT writes back the TTBAT slot once on bind and once on VM teardown (mock hardware)");} ''' source=pre+handoff+mid+raii+inner+models+map_drop+pages+bindings+helpers+bind+vm+main (OUT/'check-mmu-retention.rs').write_text(source) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py index 36574512d4298f..50785414007938 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py @@ -27,6 +27,23 @@ def node(props, children=()): image = node({'name': b'device-tree\0'}, [node({'name': b'arm-io\0'}, [node({'name': b'sgx\0', **properties})])]) blob = out / 'measured-perf.adt' blob.write_bytes(image) +clpc_props = { + 'cpu-avg-limiter-input-tc': struct.pack(' usize { data.windows(32).position(|value| value.starts_with(name) && value[name.len()..].iter().all(|&x| x==0)).unwrap() @@ -44,7 +62,7 @@ def node(props, children=()): fn set_cell(data: &mut [u8], name: &[u8], value: u32) { let at = property_offset(data, name) + 36; put32(data, at, value); } -fn source() -> perf::Source { perf::parse(MEASURED).unwrap() } +fn source() -> perf::Source { perf::parse(MEASURED, b"gpu,t8132").unwrap() } fn tables() -> wire::Performance { data::select(&source()).unwrap() } fn input(performance: wire::Performance) -> wire::Input { const HOST: u64 = wire::HOST_START; @@ -56,6 +74,10 @@ def node(props, children=()): loader_va: core::array::from_fn(|i| if wire::LOADERS[i].length==0 {0} else {HOST+0x5000000+i as u64*0x100000+(wire::LOADERS[i].pa&0x3fff)}), scratch: HOST+0xa000000, lower_uma: wire::BOOTSTRAP_START, lower_parameter: wire::BOOTSTRAP_START+0x8000, ktrace_mask:0, progress_recovery:1, + enabled_cores: 10, + power_sample_clks:200_000, power_sample_us:8333, power_sample_period_ms:8, + timebase_khz:24_000, avg_power_filter_tc_ms:248, lowpeak_limiter_tc_ms:16, + lowpeak_limiter_ki_q16:134_217, lowpeak_limiter_kp_q16:33_554, coredump_copy_size:0x8000, } } fn encode(performance: wire::Performance) -> Result<[Vec; wire::OBJECT_COUNT], ()> { @@ -66,11 +88,139 @@ def node(props, children=()): fn get32(bytes: &[u8], at: usize) -> u32 { u32::from_le_bytes(bytes[at..at+4].try_into().unwrap()) } #[test] fn measured_original_adt_produces_qualified_tables() { let s=source(); assert_eq!(s.count,16); - let p=tables(); - assert_eq!(p.frequency,[0,338,618,796,928,1056,1170,1278,1338,1470]); - assert_eq!(p.auxiliary,[0,338,618,796,836,952,1053,1152,1204,1326]); - assert_eq!(p.voltage,[125,610,645,680,725,780,825,865,895,970]); - assert_eq!(p.sram,[780,780,780,780,780,780,825,865,895,970]); + // Keep the original frequency layout but use synthetic voltage bins. + let mut s=s; + s.core_mv[..16].copy_from_slice(&[100,600,650,700,750,750,800,800,850,850,900,900,950,950,1000,1000]); + s.sram_mv[..16].copy_from_slice(&[800,800,800,800,800,800,800,800,850,850,900,900,950,950,1000,1000]); + let p=data::select(&s).unwrap(); assert_eq!(p.count,10); + assert_eq!(p.frequency,[0,338,618,796,928,1056,1170,1278,1338,1470,0]); + assert_eq!(p.auxiliary,[0,338,618,796,836,952,1053,1152,1204,1326,0]); + assert_eq!(p.voltage,[100,600,650,700,750,800,850,900,950,1000,0]); + assert_eq!(p.sram,[800,800,800,800,800,800,850,900,950,1000,0]); + assert_eq!(get32(&encode(p).unwrap()[wire::id::MAIN],0xfc0),10); +} +// J773g frequency layout with synthetic voltage bins, both with eleven groups. +fn j773g(core: [u32; 16], sram: [u32; 16]) -> perf::Source { + let mhz=[0,338,618,796,928,952,1056,1053,1170,1152,1278,1204,1338,1326,1470,1578]; + let mut s=source(); s.count=16; + s.frequency_mhz=[0;perf::MAX_STATES]; s.sram_frequency_mhz=[0;perf::MAX_STATES]; + s.core_mv=[0;perf::MAX_STATES]; s.sram_mv=[0;perf::MAX_STATES]; + s.frequency_mhz[..16].copy_from_slice(&mhz); s.sram_frequency_mhz[..16].copy_from_slice(&mhz); + s.core_mv[..16].copy_from_slice(&core); s.sram_mv[..16].copy_from_slice(&sram); + s +} +#[test] fn j773g_synthetic_bins_produce_eleven_rows_and_encode_all_of_them() { + for (core,sram,voltage,row_sram) in [ + ([100,600,620,660,700,750,750,800,800,850,850,900,900,950,950,1000], + [740,740,740,740,740,750,750,800,800,850,850,900,900,950,950,1000], + [100,600,620,660,700,750,800,850,900,950,1000], + [740,740,740,740,740,750,800,850,900,950,1000]), + ([100,590,630,650,690,730,730,790,790,840,840,890,890,940,940,990], + [760,760,760,760,760,760,760,790,790,840,840,890,890,940,940,990], + [100,590,630,650,690,730,790,840,890,940,990], + [760,760,760,760,760,760,790,840,890,940,990]), + ] { + let (p,name)=data::select_named(&j773g(core,sram)).unwrap(); + assert_eq!(name,"11-row"); assert_eq!(p.count,11); + assert_eq!(p.frequency,[0,338,618,796,928,1056,1170,1278,1338,1470,1578]); + assert_eq!(p.auxiliary,[0,338,618,796,928,952,1053,1152,1204,1326,1578]); + assert_eq!(p.voltage,voltage); assert_eq!(p.sram,row_sram); + let mut buffers=wire::OBJECT_SIZE.map(|size|vec![0xa5;size]); + wire::encode(&mut buffers.each_mut().map(|b|b.as_mut_slice()),&input(p.clone()),10).unwrap(); + let main=&buffers[wire::id::MAIN]; + assert_eq!(get32(main,0xfc0),11); assert_eq!(get32(main,0xfc4),10); + for i in 0..11 { + assert_eq!(get32(main,0xfc8+i*4),p.frequency[i]); + assert_eq!(get32(main,0x1808+i*4),p.auxiliary[i]); + assert_eq!(get32(main,0x1008+i*16*4),p.voltage[i]); + assert_eq!(get32(main,0x1408+(i*16+15)*4),p.sram[i]); + } + } +} +#[test] fn the_row_count_bounds_the_encoded_ceiling() { + let j713=tables(); let j773g=data::select_named(&j773g( + [100,600,620,660,700,750,750,800,800,850,850,900,900,950,950,1000], + [740,740,740,740,740,750,750,800,800,850,850,900,900,950,950,1000])).unwrap().0; + for (p,good,bad) in [(j713,[1,9],[0,10]),(j773g,[1,10],[0,11])] { + for ceiling in good { + let mut buffers=wire::OBJECT_SIZE.map(|size|vec![0xa5;size]); + assert!(wire::encode(&mut buffers.each_mut().map(|b|b.as_mut_slice()),&input(p.clone()),ceiling).is_ok()); + assert_eq!(get32(&buffers[wire::id::MAIN],0xfc0),p.count as u32); + } + for ceiling in bad { + let mut buffers=wire::OBJECT_SIZE.map(|size|vec![0xa5;size]); + assert!(wire::encode(&mut buffers.each_mut().map(|b|b.as_mut_slice()),&input(p.clone()),ceiling).is_err()); + assert!(buffers.iter().all(|buffer|buffer.iter().all(|&byte|byte==0xa5))); + } + } + // Rows past the count must stay zero, and the count must match the rows. + let mut p=tables(); p.frequency[10]=1500; assert!(!p.valid()); + let mut p=tables(); p.count=11; assert!(!p.valid()); +} +#[test] +fn g15s_power_config_uses_the_encoded_ceiling_and_machine_adt_limiter() { + let mut sgx = source(); + sgx.count = 14; + let (performance, shape) = data::select_named(&sgx).unwrap(); + assert_eq!((performance.count, shape), (9, "9-row")); + assert_eq!(performance.frequency[8], sgx.frequency_mhz[13]); + assert_eq!(performance.auxiliary[8], sgx.frequency_mhz[12]); + sgx.core_mv[12] += 1; + assert_eq!(data::select(&sgx), Err(perf::Error::Shape)); + + let layout = &wire::G15S_26B123; + let mut input = input(performance); + input.enabled_cores = 18; + // T6030 ADT /arm-io/pmgr/clpc & /arm-io/sgx limiter properties (24 MHz timebase). + input.avg_power_filter_tc_ms = 300; + input.lowpeak_limiter_tc_ms = 30; + input.lowpeak_limiter_ki_q16 = 171_128; + input.lowpeak_limiter_kp_q16 = 11_073; + for (i, loader) in layout.loaders.iter().enumerate() { + input.loader_va[i] = if loader.length != 0 && layout.slot(i).is_some() { + wire::HOST_START + 0x5000000 + i as u64 * 0x100000 + (loader.pa & 0x3fff) + } else { + 0 + }; + } + let mut buffers = layout.object_size.map(|size| vec![0; size]); + wire::encode_for(layout, &mut buffers.each_mut().map(|b| b.as_mut_slice()), &input, 8).unwrap(); + let power = &buffers[wire::id::POWER_PERFORMANCE]; + assert_eq!(get32(power, 0x04), 200_000); + assert_eq!(get32(power, 0x08), 200_000); + assert_eq!(get32(power, 0xb90), 800); + assert_eq!(get32(power, 0x2c), 8); + assert_eq!(get32(power, 0x30), 8); + // Average-power filter: (300 * 1000) / 8333 = 36 samples -> 144, 35/36, 1/36. + assert_eq!(get32(power, 0x29e4), 36 * 4); + assert_eq!(get32(power, 0x29f0), wire::f32_bits(35, 36)); + assert_eq!(get32(power, 0x29f8), wire::f32_bits(1, 36)); + // Low-peak limiter: 30 / 8 = 3 periods -> 12, 2/3, 1/3, ki*dt, kp, 30 ms, 576000 clks. + assert_eq!(get32(power, 0xa80), 3 * 4); + assert_eq!(get32(power, 0xa8c), wire::f32_bits(2, 3)); + assert_eq!(get32(power, 0xa94), wire::f32_bits(1, 3)); + assert_eq!(get32(power, 0xa9c), wire::f32_bits(171_128 * 8, 65536 * 1000)); + assert_eq!(get32(power, 0xaac), wire::f32_bits(11_073, 65536)); + assert_eq!(get32(power, 0xad8), 30); + assert_eq!(get32(power, 0xae0), 3 * 8 * 24_000); + + // Missing ADT power limiter / sampling inputs must fail closed on G15S as well. + for bad in 0..5 { + let mut bad_input = wire::Input { + performance: input.performance.clone(), + ..input + }; + match bad { + 0 => bad_input.avg_power_filter_tc_ms = 0, + 1 => bad_input.lowpeak_limiter_tc_ms = 0, + 2 => bad_input.lowpeak_limiter_ki_q16 = 0, + 3 => bad_input.lowpeak_limiter_kp_q16 = 0, + _ => bad_input.power_sample_period_ms = 0, + } + let mut out_bufs = layout.object_size.map(|size| vec![0xa5; size]); + assert!(wire::encode_for(layout, &mut out_bufs.each_mut().map(|b| b.as_mut_slice()), &bad_input, 8).is_err()); + assert!(out_bufs.iter().all(|b| b.iter().all(|&x| x == 0xa5))); + } } #[test] fn different_real_bin_values_reach_all_firmware_lanes() { let mut raw=MEASURED.to_vec(); @@ -82,7 +232,7 @@ def node(props, children=()): put32(&mut raw,at+i*8+4,mv+5); } } - let p=data::select(&perf::parse(&raw).unwrap()).unwrap(); + let p=data::select(&perf::parse(&raw, b"gpu,t8132").unwrap()).unwrap(); let encoded=encode(p.clone()).unwrap();let main=&encoded[wire::id::MAIN]; for i in 0..10 { assert_eq!(get32(main,0xfc8+i*4),p.frequency[i]); @@ -95,35 +245,35 @@ def node(props, children=()): assert_eq!(p.frequency[9],1471);assert_eq!(p.voltage[9],975); } #[test] fn truncations_and_overflowing_tree_headers_reject_without_panic() { - for end in 0..MEASURED.len() {assert!(perf::parse(&MEASURED[..end]).is_err());} + for end in 0..MEASURED.len() {assert!(perf::parse(&MEASURED[..end], b"gpu,t8132").is_err());} for at in [0,4,40,property_offset(MEASURED,b"perf-states")+32,property_offset(MEASURED,b"compatible")+32] { let mut bad=MEASURED.to_vec();put32(&mut bad,at,u32::MAX); - assert!(perf::parse(&bad).is_err()); + assert!(perf::parse(&bad, b"gpu,t8132").is_err()); } - assert!(perf::parse(&vec![0;0x20_0001]).is_err()); + assert!(perf::parse(&vec![0;0x20_0001], b"gpu,t8132").is_err()); let mut deep=Vec::new(); for _ in 0..34 {deep.extend_from_slice(&0u32.to_le_bytes());deep.extend_from_slice(&1u32.to_le_bytes());} - deep.extend_from_slice(&[0;8]);assert!(perf::parse(&deep).is_err()); - let mut padded=MEASURED.to_vec();padded.extend_from_slice(&[0;4096]);assert_eq!(perf::parse(&padded),Ok(source())); + deep.extend_from_slice(&[0;8]);assert!(perf::parse(&deep, b"gpu,t8132").is_err()); + let mut padded=MEASURED.to_vec();padded.extend_from_slice(&[0;4096]);assert_eq!(perf::parse(&padded, b"gpu,t8132"),Ok(source())); } #[test] fn missing_wrong_identity_and_duplicate_required_properties_reject() { for name in [b"compatible".as_slice(),b"perf-state-count",b"perf-states",b"perf-states-sram"] { let mut bad=MEASURED.to_vec();let at=property_offset(&bad,name);bad[at]=b'X'; - assert!(perf::parse(&bad).is_err()); + assert!(perf::parse(&bad, b"gpu,t8132").is_err()); } let mut bad=MEASURED.to_vec();let at=property_offset(&bad,b"compatible")+36;bad[at]=b'X'; - assert_eq!(perf::parse(&bad),Err(perf::Error::Identity)); + assert_eq!(perf::parse(&bad, b"gpu,t8132"),Err(perf::Error::Identity)); let mut bad=MEASURED.to_vec();let at=property_offset(&bad,b"perf-states-sram"); bad[at..at+32].fill(0);bad[at..at+11].copy_from_slice(b"perf-states"); - assert_eq!(perf::parse(&bad),Err(perf::Error::Duplicate)); + assert_eq!(perf::parse(&bad, b"gpu,t8132"),Err(perf::Error::Duplicate)); } #[test] fn metadata_shape_frequency_units_off_state_and_voltage_ranges_reject() { for (name,value) in [(b"perf-state-count".as_slice(),0),(b"perf-state-count",33),(b"perf-state-count",15),(b"perf-state-table-count",2),(b"gpu-num-perf-states",14)] { - let mut bad=MEASURED.to_vec();set_cell(&mut bad,name,value);assert!(perf::parse(&bad).is_err()); + let mut bad=MEASURED.to_vec();set_cell(&mut bad,name,value);assert!(perf::parse(&bad, b"gpu,t8132").is_err()); } let at=property_offset(MEASURED,b"perf-states")+36; for (offset,value) in [(0,1),(8,0),(8,338_000_001),(8,3_001_000_000),(12,99),(12,1101)] { - let mut bad=MEASURED.to_vec();put32(&mut bad,at+offset,value);assert!(perf::parse(&bad).is_err()); + let mut bad=MEASURED.to_vec();put32(&mut bad,at+offset,value);assert!(perf::parse(&bad, b"gpu,t8132").is_err()); } } #[test] fn unsupported_shape_pairs_and_ordering_reject_before_encoding() { @@ -134,11 +284,13 @@ def node(props, children=()): let mut s=source();s.frequency_mhz[4]=s.frequency_mhz[5]+1;s.sram_frequency_mhz[4]=s.frequency_mhz[4];assert!(data::select(&s).is_err()); let mut s=source();s.frequency_mhz[7]=s.frequency_mhz[5];s.sram_frequency_mhz[7]=s.frequency_mhz[7];assert!(data::select(&s).is_err()); let mut s=source();s.core_mv[14]=600;s.core_mv[15]=600;assert!(data::select(&s).is_err()); + // Three states at one voltage, and split pairs, match no layout. + let mut s=source();s.core_mv[6]=s.core_mv[5];s.sram_mv[6]=s.sram_mv[5];assert!(data::select(&s).is_err()); + let mut s=source();s.core_mv[4]-=1;s.core_mv[6]-=1;assert!(data::select(&s).is_err()); } -#[test] fn j604_shape_selects_its_own_layout_and_the_j713_keeps_its_own() { - assert_eq!(data::select_named(&source()).unwrap().1,"J713"); - // J604 shape: five low states, equal-voltage pairs 5/6 to 13/14, a single top state 15. - // Rows 0-3 and 5-15 are the J604's selected values; state 4 (left out) is synthetic. +#[test] fn eleven_row_shape_selects_all_eleven_rows_from_adt_without_board_check() { + assert_eq!(data::select_named(&source()).unwrap().1,"10-row"); + // 11-row shape (J604/J773g): five low states, equal-voltage pairs 5/6 to 13/14, single top 15. let mhz=[0,338,618,796,928,952,1056,1053,1170,1152,1278,1204,1338,1326,1470,1578]; let mv=[125,625,640,680,725,780,780,825,825,865,865,895,895,970,970,1045]; let mut s=source(); @@ -147,13 +299,14 @@ def node(props, children=()): s.core_mv[i]=mv[i];s.sram_mv[i]=mv[i].max(780); } let (p,name)=data::select_named(&s).unwrap(); - assert_eq!(name,"J604"); - assert_eq!(p.frequency,[0,338,618,796,1056,1170,1278,1338,1470,1578]); - assert_eq!(p.auxiliary,[0,338,618,796,952,1053,1152,1204,1326,1578]); - assert_eq!(p.voltage,[125,625,640,680,780,825,865,895,970,1045]); - assert_eq!(p.sram,[780,780,780,780,780,825,865,895,970,1045]); - assert!(encode(p).is_ok()); - // A J604 shape with one unequal pair matches neither layout. + assert_eq!(name,"11-row"); assert_eq!(p.count,11); + assert_eq!(p.frequency,[0,338,618,796,928,1056,1170,1278,1338,1470,1578]); + assert_eq!(p.auxiliary,[0,338,618,796,928,952,1053,1152,1204,1326,1578]); + assert_eq!(p.voltage,[125,625,640,680,725,780,825,865,895,970,1045]); + assert_eq!(p.sram,[780,780,780,780,780,780,825,865,895,970,1045]); + let mut buffers=wire::OBJECT_SIZE.map(|size|vec![0xa5;size]); + assert!(wire::encode(&mut buffers.each_mut().map(|b|b.as_mut_slice()),&input(p.clone()),10).is_ok()); + // An 11-row shape with one unequal pair matches no layout. let mut bad=s;bad.core_mv[9]+=1;bad.sram_mv[9]+=1; assert_eq!(data::select(&bad),Err(perf::Error::Shape)); } @@ -165,9 +318,39 @@ def node(props, children=()): assert!(buffers.iter().all(|buffer|buffer.iter().all(|&byte|byte==0xa5))); } } +#[test] fn clpc_and_sgx_power_limiter_properties_parse_and_reject_zero() { + let minimal = source(); + assert_eq!(minimal.avg_power_filter_tc_ms, None); + assert_eq!(minimal.lowpeak_limiter_tc_ms, None); + let full = perf::parse(MEASURED_CLPC, b"gpu,t8132").unwrap(); + assert_eq!(full.power_sample_clks, Some(200_000)); + assert_eq!(full.power_sample_period_ms, Some(8)); + assert_eq!(full.avg_power_filter_tc_ms, Some(248)); + assert_eq!(full.lowpeak_limiter_tc_ms, Some(16)); + assert_eq!(full.lowpeak_limiter_ki_q16, Some(134_217)); + assert_eq!(full.lowpeak_limiter_kp_q16, Some(33_554)); + assert_eq!(full.coredump_copy_size, Some(0x8000)); + for name in [ + b"gpu-pwr-sample-period-aic-clks".as_slice(), + b"gpu-power-sample-period", + b"cpu-avg-limiter-input-tc", + b"cpu-lowpeak-limiter-input-tc", + b"cpu-lowpeak-limiter-ki", + b"cpu-lowpeak-limiter-kp", + b"coredump-copy-buffer", + ] { + let mut bad = MEASURED_CLPC.to_vec(); + set_cell(&mut bad, name, 0); + assert_eq!(perf::parse(&bad, b"gpu,t8132"), Err(perf::Error::Range)); + } + let mut unaligned = MEASURED_CLPC.to_vec(); + set_cell(&mut unaligned, b"coredump-copy-buffer", 0x8001); + assert_eq!(perf::parse(&unaligned, b"gpu,t8132"), Err(perf::Error::Range)); +} ''' for marker, value in {'PARSER': backend / 'adt/perf.rs', 'ENCODER': backend / 'fw/initdata.rs', - 'SELECT': backend / 'board/data.rs', 'FIXTURE': blob}.items(): + 'SELECT': backend / 'board/data.rs', 'FIXTURE': blob, + 'FIXTURE_CLPC': blob_clpc}.items(): source = source.replace('@' + marker + '@', str(value)) path = out / 'perf.rs' path.write_text(source) @@ -177,7 +360,7 @@ def node(props, children=()): print(run.stdout, end='') print(run.stderr, end='') run.check_returncode() -report = {'passed': True, 'test_groups': 8, 'hardware_validated': False, +report = {'passed': True, 'test_groups': 12, 'hardware_validated': False, 'fixture_sha256': sha(fixture), 'original_adt_sha256': metadata['provenance']['source_sha256'], 'production_sha256': {str(p.relative_to(root)): sha(p) for p in [backend / 'adt.rs', backend / 'adt/perf.rs', backend / 'board.rs', backend / 'board/data.rs', backend / 'initdata.rs', backend / 'fw/initdata.rs']}} diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py new file mode 100755 index 00000000000000..227ba811a0bdc4 --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -0,0 +1,1887 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Execute production G16 inline submit retirement and EP 0x20 poll-step logic.""" +from common import kernel_root, output_dir, rustc, sha +import json +import subprocess + +production = kernel_root() / 'drivers/gpu/drm/asahi/g16/poll.rs' +queue_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/queue.rs').read_text() +event_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/event.rs').read_text() +mod_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/mod.rs').read_text() +sleep_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/sleep.rs').read_text() +core_source = (kernel_root() / 'drivers/gpu/drm/asahi/asahi_core.rs').read_text() +source = production.read_text() +output = output_dir() + +assert 'const EVENT_RETIRE_POLLS: u32 = 11;' in source, 'EVENT_RETIRE_POLLS expected to be 11' +assert 'const ACTIVE_HOUSEKEEPING_NS: u64 = 5_000_000;' in source, 'ACTIVE_HOUSEKEEPING_NS expected to be 5 ms' +assert 'const MAX_EVENT_RECHECKS: u32 = 8;' in source, 'MAX_EVENT_RECHECKS expected to be 8' +assert 'rechecks < MAX_EVENT_RECHECKS' in source, 'run_poll must loop-recheck evented completions' +assert 'self.idle_resnap();' in source, 'run_poll idle paths must use idle_resnap()' +assert 'g16_repoll_us: u32 {\n default: 8,' in core_source, 'g16_repoll_us default expected to be 8' +assert ( + 'OwnedQueue::new_percpu_reclaim(c_str!("aurora_g16_events"), true)' in mod_source +), 'aurora_g16_events must use new_percpu_reclaim(..., true)' +assert ( + 'pub(crate) usage: Arc' in queue_source +), 'QueueState::usage must reference the per-file usage::Client' +assert ( + '.add_union(engine, start, end, super::hw::COMMAND_TIMESTAMP_HZ as u32)' in source +), 'G16 poll retirement must deduplicate per-file intervals via Client::add_union' +assert ( + 'OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_events_unbound"), true)' in mod_source +), 'aurora_g16_events_unbound must use new_unbound_reclaim(..., true)' +assert ( + 'self.events_unbound.drain();' in sleep_source +), 'sleep.rs must drain events_unbound on suspend' +assert ( + 'self.cancel_resnap();' in sleep_source +), 'sleep.rs must still call unconditional cancel_resnap()' + + +def item(declaration, text=source): + start = text.index(declaration) + at = text.index('{', start) + depth, end = 1, at + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +harness = r''' +#![allow(dead_code, unused_variables)] +use std::cell::Cell; +use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +struct Error(i32); +type Result = std::result::Result; + +const HOUSEKEEPING_NS: u64 = 1_000_000; +const ACTIVE_HOUSEKEEPING_NS: u64 = 5_000_000; +const AUX_DRAIN_NS: u64 = 10_000_000; +const EVENT_RETIRE_POLLS: u32 = 11; +mod hw { + pub mod sizes { + pub const TA_WAVE_PASSES: usize = 4; + pub const TA_WAVE_PASSES_LIGHT: usize = 8; + pub const TA_WAVE_REFILL_HEADROOM: usize = 2; + pub const COMPUTE_PIPES: usize = 8; + pub const COALESCE_WINDOW_US: u32 = 18; + } +} + +thread_local! { + static CLOCK: Cell = const { Cell::new(0) }; +} +fn now_ns() -> u64 { + CLOCK.with(|c| c.get()) +} +fn rmb() {} +fn stamp_reached(obs: u32, own: u32, tail: u32) -> bool { + let diff = obs.wrapping_sub(own) as i32; + let span = tail.wrapping_sub(own) as i32; + diff >= 0 && diff <= span +} + +struct Job { + id: u32, +} +type Completions = Vec; + +struct Lap; +impl Lap { + fn start() -> Self { + Self + } + fn on(&self) -> bool { + false + } + fn lap(&mut self, _acc: &mut u64) {} +} + +struct Cell32 { + val: Cell, + reads: Cell, +} +impl Cell32 { + fn new(v: u32) -> Self { + Self { + val: Cell::new(v), + reads: Cell::new(0), + } + } + fn set(&self, v: u32) { + self.val.set(v); + } + fn r32(&self, _off: usize) -> Result { + self.reads.set(self.reads.get() + 1); + Ok(self.val.get()) + } +} + +struct ComputeGraph { + fw_stamp: Cell32, +} +struct RenderGraph { + fw_stamp: [Cell32; 2], +} +struct Graph { + compute: [ComputeGraph; hw::sizes::COMPUTE_PIPES], + render: RenderGraph, +} + +#[derive(Default)] +struct Stats { + idle_from_ns: u64, + starve_from_ns: u64, +} +#[derive(Default)] +struct Prof { + retire_ns: u64, + polls: u64, + poll_ns: u64, +} + +struct Flight { + computes: u32, + compute_pipe: u8, + renders: u32, + target: u32, + fs_target: u32, +} + +struct Engine { + shared: Option>, + flights: Vec, + pending: Vec>, + target: [u32; hw::sizes::COMPUTE_PIPES], + fs_target: u32, + chan_wait: bool, + slot_wait: bool, + ta_wave_wait: bool, + short_repoll: bool, + housekeeping_owed: bool, + held_wait: bool, + coalesce_deadline_ns: u64, + frozen: bool, + stats: Stats, + prof: Prof, +} +impl Engine { + fn oldest(&self) -> Option<&Flight> { + self.flights.first() + } +} + +#[derive(Default)] +struct Events { + stage_events: u32, + fs_events: u32, + compute_events: u32, +} + +#[derive(Default)] +struct Recovery { + receipt_fault: bool, + pending: bool, + failed: Option, +} +impl Recovery { + fn failed(&self) -> Option { + self.failed + } + fn needs_repoll(&self) -> bool { + self.pending + } +} + +struct Session; +impl Session { + fn transport(&self) -> Result { + Ok(()) + } + fn check(&self) -> Result { + Ok(()) + } +} +struct Objects; +impl Objects { + fn health(&self) -> Result { + Ok(()) + } +} + +struct Shared { + sleeping: AtomicBool, + evented: AtomicBool, + publish_wake: AtomicBool, + closed_vm_reclaim: AtomicBool, + rearmed: Cell, + idle_power_polls: Cell, + rearm_soon: Cell, + rearm_after_calls: Cell, + last_rearm_us: Cell, + poll_now_calls: Cell, +} +impl Shared { + fn new() -> Arc { + Arc::new(Self { + sleeping: AtomicBool::new(false), + evented: AtomicBool::new(false), + publish_wake: AtomicBool::new(false), + closed_vm_reclaim: AtomicBool::new(false), + rearmed: Cell::new(0), + idle_power_polls: Cell::new(0), + rearm_soon: Cell::new(0), + rearm_after_calls: Cell::new(0), + last_rearm_us: Cell::new(0), + poll_now_calls: Cell::new(0), + }) + } + fn rearm_us(&self, soon: bool) -> u32 { + if soon { 25 } else { 100 } + } + fn rearm_after(&self, us: u32) { + self.rearm_after_calls.set(self.rearm_after_calls.get() + 1); + self.last_rearm_us.set(us); + } + fn rearm(&self, soon: bool) { + self.rearmed.set(self.rearmed.get() + 1); + if soon { + self.rearm_soon.set(self.rearm_soon.get() + 1); + } + } + fn poll_now(&self) { + self.poll_now_calls.set(self.poll_now_calls.get() + 1); + } + fn arm_idle_power_poll(&self, _firmware: &Firmware) { + self.idle_power_polls.set(self.idle_power_polls.get() + 1); + } + fn fail_stop(&self, _e: Error) {} + __SUBMIT_LOCKED__ +} + +#[derive(Default)] +struct Power { + ramp: bool, + idle_reports: u32, +} +impl Power { + fn needs_ramp(&self, _now: u64) -> bool { + self.ramp + } + fn report_work(&mut self, in_flight: bool) { + if !in_flight { + self.idle_reports += 1; + } + } +} + +#[derive(Default)] +struct Pools { + reclaim_calls: u32, + reclaim_remaining: bool, + closed_vm_last: bool, +} +impl Pools { + fn reclaim_closed(&mut self) -> bool { + self.reclaim_calls += 1; + self.reclaim_remaining + } + fn take_closed_vm_last(&mut self) -> bool { + core::mem::take(&mut self.closed_vm_last) + } +} + +#[derive(Default)] +struct Slots { + scrub_woke: AtomicBool, + reclaim_calls: u32, + reclaim_remaining: bool, +} +impl Slots { + fn take_scrub_woke(&self) -> bool { + self.scrub_woke.swap(false, Ordering::AcqRel) + } + fn reclaim_closed(&mut self) -> bool { + self.reclaim_calls += 1; + self.reclaim_remaining + } +} + +struct Firmware { + session: Session, + objects: Objects, + graph: Graph, + engine: Engine, + events: Events, + recovery: Recovery, + power: Power, + pools: Pools, + slots: Slots, + last_housekeeping_ns: u64, + last_aux_drain_ns: u64, + // Test script knobs for retire_once / publish / housekeeping observation. + retire_on_call: bool, + unfreeze_on_hang_check: bool, + drain_stage_delta: u32, + drain_fs_delta: u32, + drain_compute_delta: u32, + ta_pending: usize, + ta_wave_cap: usize, + coalesce_us: Option, + publish_waits: Option<(bool, bool, bool)>, + retire_calls: u32, + publish_full_calls: u32, + publish_checked_calls: u32, + housekeeping_calls: u32, + aux_drain_calls: u32, + power_calls: u32, + hot_drain_calls: u32, +} + +impl Firmware { + fn new() -> Self { + Self { + session: Session, + objects: Objects, + graph: Graph { + compute: core::array::from_fn(|_| ComputeGraph { + fw_stamp: Cell32::new(0), + }), + render: RenderGraph { + fw_stamp: [Cell32::new(0), Cell32::new(0)], + }, + }, + engine: Engine { + shared: None, + flights: vec![], + pending: vec![], + target: [0; hw::sizes::COMPUTE_PIPES], + fs_target: 0, + chan_wait: false, + slot_wait: false, + ta_wave_wait: false, + short_repoll: false, + housekeeping_owed: false, + held_wait: false, + coalesce_deadline_ns: 0, + frozen: false, + stats: Stats::default(), + prof: Prof::default(), + }, + events: Events::default(), + recovery: Recovery::default(), + power: Power::default(), + pools: Pools::default(), + slots: Slots::default(), + last_housekeeping_ns: 0, + last_aux_drain_ns: 0, + retire_on_call: false, + unfreeze_on_hang_check: false, + drain_stage_delta: 0, + drain_fs_delta: 0, + drain_compute_delta: 0, + ta_pending: 0, + ta_wave_cap: hw::sizes::TA_WAVE_PASSES, + coalesce_us: None, + publish_waits: None, + retire_calls: 0, + publish_full_calls: 0, + publish_checked_calls: 0, + housekeeping_calls: 0, + aux_drain_calls: 0, + power_calls: 0, + hot_drain_calls: 0, + } + } + + fn enqueue(&mut self, job: Arc) -> Result { + self.engine.pending.push(job); + Ok(()) + } + fn recovery_pending(&self) -> Result { + Ok(self.recovery.pending) + } + fn recovery_idle(&mut self) -> Result { + Ok(!self.recovery.pending) + } + fn service_power(&mut self) -> Result { + self.power_calls += 1; + Ok(()) + } + fn drain_rings(&mut self) -> Result { + Ok(()) + } + fn drain_events_and_stats(&mut self) -> Result { + self.hot_drain_calls += 1; + Ok(()) + } + fn drain_auxiliary_rings(&mut self) -> Result { + self.aux_drain_calls += 1; + Ok(()) + } + fn answer_growth(&mut self) -> Result { + Ok(()) + } + fn check_hangs(&mut self, _done: &mut Completions) -> Result { + if self.unfreeze_on_hang_check { + self.engine.frozen = false; + self.recovery.pending = false; + } + Ok(()) + } + fn fail_stop(&mut self, error: Error, _done: &mut Completions) { + self.recovery.failed = Some(error); + } + __RUN_HOUSEKEEPING__ + fn retire_once(&mut self, done: &mut Completions) -> Result { + self.retire_calls += 1; + self.events.stage_events += self.drain_stage_delta; + self.events.fs_events += self.drain_fs_delta; + self.events.compute_events += self.drain_compute_delta; + if self.retire_on_call && !self.engine.flights.is_empty() { + self.engine.flights.remove(0); + done.push(1); + return Ok(true); + } + Ok(false) + } + fn publish(&mut self, _done: &mut Completions) -> Result { + self.publish_full_calls += 1; + Ok(()) + } + fn publish_checked(&mut self, _done: &mut Completions) -> Result { + self.engine.coalesce_deadline_ns = 0; + if let Some((slot_wait, ta_wave_wait, held_wait)) = self.publish_waits { + self.engine.slot_wait = slot_wait; + self.engine.ta_wave_wait = ta_wave_wait; + self.engine.held_wait = held_wait; + } + self.publish_checked_calls += 1; + Ok(()) + } + fn defer_busy_coalesce(&mut self, _now: u64) -> Option { + self.coalesce_us + } + fn ta_pending_passes(&self) -> usize { + self.ta_pending + } + fn active_ta_wave_cap(&self) -> usize { + self.ta_wave_cap + } + + __RECLAIM_CLOSED_VM_SLOTS__ + __POLL_STEP__ + __OLDEST_TERMINAL_EVENTS__ + __TA_WAVE_READY__ + __OLDEST_STAMP_REACHED__ +} + +#[test] +fn idle_poll_step_runs_full_housekeeping_only_on_its_cadence() { + let mut fw = Firmware::new(); + let (mut retry_tail, mut hk_deferred, mut done) = (false, false, vec![]); + let mut idle_pass = |fw: &mut Firmware, now: u64| { + CLOCK.with(|c| c.set(now)); + fw.poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap() + }; + // Due: the full idle housekeeping runs and owes nothing. + assert!(!idle_pass(&mut fw, 2_000_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (1, 0)); + assert_eq!(fw.last_housekeeping_ns, 2_000_000); + assert!(!fw.engine.housekeeping_owed); + // Inside the cadence: only the event and statistics rings drain; the rest is owed. + assert!(!idle_pass(&mut fw, 2_300_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (1, 1)); + assert_eq!(fw.last_housekeeping_ns, 2_000_000); + assert!(fw.engine.housekeeping_owed); + // A recovery found by that drain runs the full pass inside the cadence. + fw.recovery.pending = true; + assert!(idle_pass(&mut fw, 2_400_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (2, 2)); + assert_eq!(fw.last_housekeeping_ns, 2_400_000); + assert!(!fw.engine.housekeeping_owed); + fw.recovery.pending = false; + // So does a receipt fault, without a hot drain first. + fw.recovery.receipt_fault = true; + assert!(!idle_pass(&mut fw, 2_500_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (3, 2)); + fw.recovery.receipt_fault = false; + assert!(!idle_pass(&mut fw, 2_600_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (3, 3)); + assert!(fw.engine.housekeeping_owed); + // Once the cadence elapses the owed housekeeping runs. + assert!(!idle_pass(&mut fw, 3_500_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (4, 3)); + assert!(!fw.engine.housekeeping_owed); + // Periodic housekeeping also settles what an idle pass owed. + assert!(!idle_pass(&mut fw, 3_600_000)); + assert!(fw.engine.housekeeping_owed); + CLOCK.with(|c| c.set(4_600_000)); + fw.run_housekeeping(&mut done).unwrap(); + assert!(!fw.engine.housekeeping_owed); +} + +#[test] +fn idle_poll_step_reclaims_closed_vm_slots_and_rearms_while_remaining() { + CLOCK.with(|c| c.set(1_000_000)); + let shared = Shared::new(); + let mut fw = Firmware::new(); + fw.engine.shared = Some(shared.clone()); + shared.closed_vm_reclaim.store(true, Ordering::Release); + shared.publish_wake.store(true, Ordering::Release); + fw.pools.reclaim_remaining = true; + + let (mut retry_tail, mut hk_deferred, mut done) = (false, false, vec![]); + let busy = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert!(!busy); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (1, 1)); + assert!(!shared.publish_wake.load(Ordering::Acquire)); + assert!( + shared.closed_vm_reclaim.load(Ordering::Acquire), + "remaining undisplaced closed VM keeps reclaim armed" + ); + + // Once remaining clears, idle poll clears closed_vm_reclaim and later polls skip scans. + fw.pools.reclaim_remaining = false; + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (2, 2)); + assert!(!shared.closed_vm_reclaim.load(Ordering::Acquire)); + + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (2, 2)); + + // Idle submit_locked also reclaims before publish_checked when armed. + shared.closed_vm_reclaim.store(true, Ordering::Release); + shared + .submit_locked(&mut fw, Arc::new(Job { id: 9 }), &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (3, 3)); + assert!(!shared.closed_vm_reclaim.load(Ordering::Acquire)); + + // A closed VM's render retired after the flag cleared and recorded its last PB epoch: + // the next pass reclaims once without the flag, then scans stop again. + fw.pools.closed_vm_last = true; + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (4, 4)); + assert!(!shared.closed_vm_reclaim.load(Ordering::Acquire)); + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (4, 4)); +} + +#[test] +fn submit_locked_retires_inline_on_reached_stamp_without_full_housekeeping() { + CLOCK.with(|c| c.set(100_000)); + let shared = Shared::new(); + shared.evented.store(true, Ordering::Release); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 1, + compute_pipe: 0, + renders: 0, + target: 0x100, + fs_target: 0, + }); + fw.engine.target[0] = 0x100; + fw.graph.compute[0].fw_stamp.set(0x100); + fw.retire_on_call = true; + + let mut done = vec![]; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 2 }), &mut done) + .unwrap(); + assert_eq!(fw.retire_calls, 1); + assert_eq!(done, vec![1]); + assert_eq!(fw.publish_checked_calls, 1); + assert_eq!(fw.publish_full_calls, 0); + assert!(!shared.evented.load(Ordering::Acquire)); +} + +#[test] +fn submit_locked_preserves_evented_when_irq_precedes_receipt() { + CLOCK.with(|c| c.set(100_000)); + let shared = Shared::new(); + shared.evented.store(true, Ordering::Release); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw.engine.fs_target = 0x100; + + let mut done = vec![]; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 2 }), &mut done) + .unwrap(); + assert_eq!(fw.retire_calls, 1); + assert!(shared.evented.load(Ordering::Acquire)); + assert_eq!(shared.rearm_soon.get(), 1); + assert_eq!(shared.poll_now_calls.get(), 1); + + // TA-only non-terminal event must NOT restore evented, arm short repoll, or kick poll_now. + let shared_ta = Shared::new(); + shared_ta.evented.store(true, Ordering::Release); + let mut fw_ta = Firmware::new(); + fw_ta.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw_ta.engine.fs_target = 0x100; + fw_ta.drain_stage_delta = 1; + fw_ta.drain_fs_delta = 0; + shared_ta + .submit_locked(&mut fw_ta, Arc::new(Job { id: 3 }), &mut done) + .unwrap(); + assert!(!shared_ta.evented.load(Ordering::Acquire)); + assert_eq!(shared_ta.rearm_soon.get(), 0); + assert_eq!(shared_ta.poll_now_calls.get(), 0); +} + +#[test] +fn submit_locked_defers_housekeeping_and_arms_short_repoll_on_coalesced_event() { + // Active bursts hold housekeeping at ACTIVE_HOUSEKEEPING_NS (5 ms): at 4 ms (< 5 ms), + // submit_locked skips poll_now(); at 5 ms, it calls publish_checked() and kicks poll_now() + // so housekeeping runs off SUBMIT. + CLOCK.with(|c| c.set(5_000_000)); + let shared = Shared::new(); + let mut fw = Firmware::new(); + fw.last_housekeeping_ns = 1_000_000; + fw.engine.flights.push(Flight { + computes: 1, + compute_pipe: 0, + renders: 0, + target: 0x100, + fs_target: 0, + }); + fw.engine.flights.push(Flight { + computes: 1, + compute_pipe: 0, + renders: 0, + target: 0x200, + fs_target: 0, + }); + fw.engine.target[0] = 0x200; + + let mut done = vec![]; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 3 }), &mut done) + .unwrap(); + assert_eq!(fw.publish_full_calls, 0); + assert_eq!(fw.publish_checked_calls, 1); + assert_eq!(fw.retire_calls, 0); + assert_eq!(shared.poll_now_calls.get(), 0); + assert_eq!(shared.rearm_soon.get(), 0); + + // At 5 ms (>= ACTIVE_HOUSEKEEPING_NS), submit_locked defers housekeeping via poll_now(). + CLOCK.with(|c| c.set(6_000_000)); + shared + .submit_locked(&mut fw, Arc::new(Job { id: 4 }), &mut done) + .unwrap(); + assert_eq!(fw.publish_full_calls, 0); + assert_eq!(fw.publish_checked_calls, 2); + assert_eq!(shared.poll_now_calls.get(), 1); + assert_eq!(shared.rearm_soon.get(), 0); + + // Coalesced EP 0x20 event retires flight 0 while flight 1 stays active -> short repoll. + shared.evented.store(true, Ordering::Release); + fw.retire_on_call = true; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 5 }), &mut done) + .unwrap(); + assert_eq!(fw.retire_calls, 1); + assert_eq!(fw.engine.flights.len(), 1); + assert_eq!(shared.rearm_soon.get(), 1); +} + +#[test] +fn poll_step_defers_active_housekeeping_until_five_ms_and_off_hot_lock() { + let mut fw = Firmware::new(); + fw.last_housekeeping_ns = 1_000_000; + fw.engine.flights.push(Flight { + computes: 1, + compute_pipe: 0, + renders: 0, + target: 0x100, + fs_target: 0, + }); + fw.engine.target[0] = 0x100; + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + + // At 4 ms (< 5 ms) while busy: housekeeping neither runs inline nor defers. + CLOCK.with(|c| c.set(5_000_000)); + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!deferred); + assert_eq!(fw.last_housekeeping_ns, 1_000_000); + + // At 5 ms (>= 5 ms) while busy: defers off the hot poll_step lock instead of running inline. + CLOCK.with(|c| c.set(6_000_000)); + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(deferred); + assert_eq!(fw.last_housekeeping_ns, 1_000_000); +} + +#[test] +fn run_housekeeping_throttles_auxiliary_ring_drain_while_flights_active() { + CLOCK.with(|c| c.set(1_000_000)); + let mut fw = Firmware::new(); + fw.last_aux_drain_ns = 1_000_000; + fw.engine.flights.push(Flight { + computes: 1, + compute_pipe: 0, + renders: 0, + target: 0x100, + fs_target: 0, + }); + let mut done = vec![]; + + // Within AUX_DRAIN_NS (10 ms) while busy: skip auxiliary ring drain. + CLOCK.with(|c| c.set(5_000_000)); + fw.run_housekeeping(&mut done).unwrap(); + assert_eq!(fw.aux_drain_calls, 0); + + // Past AUX_DRAIN_NS while busy: drain once and advance timestamp. + CLOCK.with(|c| c.set(11_000_000)); + fw.run_housekeeping(&mut done).unwrap(); + assert_eq!(fw.aux_drain_calls, 1); + + // Recovery pending bypasses throttle immediately. + CLOCK.with(|c| c.set(12_000_000)); + fw.recovery.pending = true; + fw.run_housekeeping(&mut done).unwrap(); + assert_eq!(fw.aux_drain_calls, 2); + + // Idle bypasses throttle immediately. + CLOCK.with(|c| c.set(13_000_000)); + fw.recovery.pending = false; + fw.engine.flights.clear(); + fw.run_housekeeping(&mut done).unwrap(); + assert_eq!(fw.aux_drain_calls, 3); +} + +#[test] +fn ta_only_event_does_not_spin_or_arm_short_repoll() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw.engine.fs_target = 0x100; + // Simulate draining a TA (0x70) stage event with no FS (0x71) event and FS stamp unreached. + fw.drain_stage_delta = 1; + fw.drain_fs_delta = 0; + + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + let active = fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap(); + assert!(active); + assert!(!retry_tail); + assert!(!fw.engine.short_repoll); +} + +#[test] +fn fs_event_without_settled_receipt_still_polls_tail_and_sets_short_repoll() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw.engine.fs_target = 0x100; + fw.drain_stage_delta = 1; + fw.drain_fs_delta = 1; + + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + let active = fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap(); + assert!(active); + assert!(retry_tail); + + retry_tail = false; + let active = fw + .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap(); + assert!(active); + assert!(!retry_tail); + assert!(fw.engine.short_repoll); +} + +#[test] +fn concurrent_compute_completion_behind_pending_render_wakes_submit_retire() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 1, + target: 0, + fs_target: 0x200, + }); + fw.engine.flights.push(Flight { + computes: 1, + compute_pipe: 0, + renders: 0, + target: 0x100, + fs_target: 0, + }); + fw.engine.fs_target = 0x200; + fw.engine.target[0] = 0x100; + // Render still running, compute reached its stamp. + fw.graph.render.fw_stamp[1].set(0x100); + fw.graph.compute[0].fw_stamp.set(0x100); + assert!(fw.oldest_stamp_reached()); + assert_eq!(fw.graph.compute[0].fw_stamp.reads.get(), 1); + assert_eq!(fw.graph.render.fw_stamp[1].reads.get(), 0); + assert_eq!(fw.oldest_terminal_events(), Some((Some(0), Some(0)))); + + // Pipe 1 reaching its stamp behind a pending pipe 0 flight also wakes inline retirement. + let mut fw2 = Firmware::new(); + fw2.engine.flights.push(Flight { + computes: 1, + compute_pipe: 0, + renders: 0, + target: 0x200, + fs_target: 0, + }); + fw2.engine.flights.push(Flight { + computes: 1, + compute_pipe: 1, + renders: 0, + target: 0x100, + fs_target: 0, + }); + fw2.engine.target[0] = 0x200; + fw2.engine.target[1] = 0x100; + fw2.graph.compute[0].fw_stamp.set(0x100); + fw2.graph.compute[1].fw_stamp.set(0x100); + assert!(fw2.oldest_stamp_reached()); + assert_eq!(fw2.graph.compute[0].fw_stamp.reads.get(), 1); + assert_eq!(fw2.graph.compute[1].fw_stamp.reads.get(), 1); + assert_eq!(fw2.graph.render.fw_stamp[1].reads.get(), 0); +} + +#[test] +fn oldest_stamp_reached_skips_inactive_class_wc_reads() { + // Compute-only workload never reads render fw_stamp or idle compute pipe 1. + let mut fc = Firmware::new(); + fc.engine.flights.push(Flight { + computes: 1, + compute_pipe: 0, + renders: 0, + target: 0x200, + fs_target: 0, + }); + fc.engine.target[0] = 0x200; + fc.graph.compute[0].fw_stamp.set(0x100); + assert!(!fc.oldest_stamp_reached()); + assert_eq!(fc.graph.compute[0].fw_stamp.reads.get(), 1); + assert_eq!(fc.graph.compute[1].fw_stamp.reads.get(), 0); + assert_eq!(fc.graph.render.fw_stamp[0].reads.get(), 0); + assert_eq!(fc.graph.render.fw_stamp[1].reads.get(), 0); + + // Render-only workload never reads compute fw_stamp. + let mut fr = Firmware::new(); + fr.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 1, + target: 0, + fs_target: 0x200, + }); + fr.engine.fs_target = 0x200; + fr.graph.render.fw_stamp[1].set(0x100); + assert!(!fr.oldest_stamp_reached()); + assert_eq!(fr.graph.compute[0].fw_stamp.reads.get(), 0); + assert_eq!(fr.graph.compute[1].fw_stamp.reads.get(), 0); + assert_eq!(fr.graph.render.fw_stamp[0].reads.get(), 0); + assert_eq!(fr.graph.render.fw_stamp[1].reads.get(), 1); +} + +#[test] +fn poll_step_skips_publish_when_pending_blocked_and_nothing_retired() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw.engine.pending.push(Arc::new(Job { id: 2 })); + fw.engine.fs_target = 0x100; + fw.drain_stage_delta = 1; + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 0); + + // Waking via scrub_woke triggers publish_checked once. + fw.slots.scrub_woke.store(true, Ordering::Release); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 1); + + // Waking via chan_wait triggers publish_checked. + fw.engine.chan_wait = true; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 2); + fw.engine.chan_wait = false; + + // Waking via unfreeze triggers publish_checked. + fw.engine.frozen = true; + fw.recovery.pending = true; + fw.unfreeze_on_hang_check = true; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 3); + + // Waking via external publish_wake (e.g. VM close or unstarted queue cancel) triggers + // publish_checked once while flights remain active, then skips again on the next busy poll. + let shared = Shared::new(); + fw.engine.shared = Some(shared.clone()); + shared.publish_wake.store(true, Ordering::Release); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 4); + assert!(!shared.publish_wake.load(Ordering::Acquire)); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 4); + + // Waking via retirement triggers publish_checked (and returns false since flights drained). + fw.retire_on_call = true; + assert!(!fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 5); +} + +#[test] +fn pending_slot_wait_arms_short_repoll_without_breaking_ta_only_or_frozen() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 11, + target: 0, + fs_target: 0x100, + }); + fw.engine.fs_target = 0x100; + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + + // No pending work on a timer poll -> keep normal resnap_us interval. + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!fw.engine.short_repoll); + + // Pending job NOT blocked on slot headroom (e.g. external fence / cross-VM / InitBM) -> + // keep normal resnap_us interval without arming short_repoll. + fw.engine.pending.push(Arc::new(Job { id: 2 })); + fw.engine.slot_wait = false; + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!fw.engine.short_repoll); + + // Pending job waiting on slot headroom on a non-event poll -> arm short_repoll. + fw.engine.slot_wait = true; + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(fw.engine.short_repoll); + + // TA-only EP 0x20 event still suppresses short_repoll. + fw.drain_stage_delta = 1; + fw.drain_fs_delta = 0; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!fw.engine.short_repoll); + fw.drain_stage_delta = 0; + + // Frozen engine suppresses short_repoll even with pending work. + fw.engine.frozen = true; + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!fw.engine.short_repoll); +} + +#[test] +fn held_wait_spins_stage_events_and_repolls_soon_until_a_retirement() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 2, + target: 0, + fs_target: 0x200, + }); + fw.engine.fs_target = 0x200; + fw.engine.pending.push(Arc::new(Job { id: 2 })); + fw.drain_stage_delta = 1; + let (mut retry_tail, mut deferred, mut done) = (false, false, vec![]); + // Nothing held: a stage-only event is non-terminal, with no tail spin and no short repoll. + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!retry_tail); + assert!(!fw.engine.short_repoll); + // A ready job held behind its own VM's flights spins the receipt tail on the same event... + fw.engine.held_wait = true; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(retry_tail); + // ...and a timer pass repolls at repoll_us while the hold lasts, without publishing. + retry_tail = false; + fw.drain_stage_delta = 0; + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(fw.engine.short_repoll); + assert_eq!(fw.publish_checked_calls, 0); + // The retirement that can release it reaches publish_checked(). + fw.retire_on_call = true; + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap(); + assert_eq!(fw.publish_checked_calls, 1); +} + +#[test] +fn ta_only_irq_wakes_ta_wave_wait_with_hysteresis_and_short_repoll() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 4, + target: 0, + fs_target: 0x400, + }); + fw.engine.fs_target = 0x400; + fw.engine.pending.push(Arc::new(Job { id: 2 })); + fw.engine.ta_wave_wait = true; + fw.ta_pending = 4; + fw.drain_stage_delta = 1; + fw.drain_fs_delta = 0; + + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + // TA still full (4 > TA_WAVE_REFILL=2): no publish_checked wakeup yet, but ta_wave_wait + // keeps non_terminal_only false so a 0x70 IRQ retries tail. + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 0); + assert!(retry_tail); + + // TA drops to 3 (> TA_WAVE_REFILL=2): hysteresis avoids 1-pass stub drip, while + // tail == 0 arms short_repoll because ta_wave_wait is active. + fw.ta_pending = 3; + retry_tail = false; + assert!(fw + .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 0); + assert!(!retry_tail); + assert!(fw.engine.short_repoll); + + // TA drains to 2 (<= cap - TA_WAVE_REFILL_HEADROOM): immediately wakes publish_checked(). + fw.ta_pending = 2; + assert!(fw + .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 1); + assert!(fw.engine.short_repoll); + + // Light TA wave cap (8): stays paused at 7 (> 8 - 2), wakes at 6 (<= 6). + fw.ta_wave_cap = hw::sizes::TA_WAVE_PASSES_LIGHT; + fw.ta_pending = 7; + assert!(fw + .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 1); + fw.ta_pending = 6; + assert!(fw + .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 2); + + // Once ta_wave_wait clears, a TA-only 0x70 IRQ stays non_terminal_only (no spin/short_repoll). + fw.engine.ta_wave_wait = false; + retry_tail = false; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!retry_tail); + assert!(!fw.engine.short_repoll); +} + +#[test] +fn submit_locked_repolls_soon_when_its_publication_leaves_a_paced_job() { + // publish_checked() leaves a ready job on TA wave or slot headroom: SUBMIT arms the same + // short repoll poll_step() arms for it, unless the engine is frozen. + CLOCK.with(|c| c.set(100_000)); + for (slot_wait, ta_wave_wait, held_wait, frozen, soon) in [ + (false, false, false, false, 0), + (true, false, false, false, 1), + (false, true, false, false, 1), + (false, false, true, false, 1), + (false, true, false, true, 0), + ] { + let shared = Shared::new(); + let mut fw = Firmware::new(); + fw.last_housekeeping_ns = 100_000; + fw.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw.engine.fs_target = 0x100; + fw.engine.frozen = frozen; + fw.publish_waits = Some((slot_wait, ta_wave_wait, held_wait)); + let mut done = vec![]; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 2 }), &mut done) + .unwrap(); + assert_eq!(fw.retire_calls, 0); + assert_eq!(fw.publish_checked_calls, 1); + assert_eq!(shared.rearmed.get(), 1); + assert_eq!(shared.rearm_soon.get(), soon); + assert_eq!(shared.poll_now_calls.get(), 0); + } +} + +#[test] +fn submit_locked_and_poll_step_micro_coalesce_busy_horizons() { + CLOCK.with(|c| c.set(100_000)); + let shared = Shared::new(); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 2, + compute_pipe: 0, + renders: 0, + target: 0x200, + fs_target: 0, + }); + fw.engine.target[0] = 0x200; + fw.coalesce_us = Some(18); + fw.engine.coalesce_deadline_ns = 118_000; + + // submit_locked skips publish_checked and arms rearm_after(18) when defer_busy_coalesce fires. + let mut done = vec![]; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 3 }), &mut done) + .unwrap(); + assert_eq!(fw.publish_checked_calls, 0); + assert_eq!(shared.rearm_after_calls.get(), 1); + assert_eq!(shared.last_rearm_us.get(), 18); + assert_eq!(shared.rearmed.get(), 0); + + // An early non-retiring event poll before the deadline does not flush prematurely. + CLOCK.with(|c| c.set(105_000)); + let (mut retry_tail, mut deferred) = (false, false); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 0); + + // Reaching the deadline on an event poll flushes immediately. + CLOCK.with(|c| c.set(118_000)); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 1); + assert_eq!(fw.engine.coalesce_deadline_ns, 0); + + // A timer poll (!evented) with an active coalesce deadline also flushes immediately. + fw.engine.coalesce_deadline_ns = 136_000; + CLOCK.with(|c| c.set(125_000)); + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 2); + assert_eq!(fw.engine.coalesce_deadline_ns, 0); +} + +mod boot { + pub fn eproto() -> super::Error { + super::Error(-71) + } +} + +mod event_drain_test { + use super::{Error, Result}; + use std::cell::{Cell, RefCell}; + + const EIO: Error = Error(-5); + const STATE_READ: usize = 0; + const STATE_WRITE: usize = 0x40; + const RING_SLOTS: u32 = 128; + const RECORD_WORDS: usize = 18; + const COMPUTE_PIPES: usize = 8; + const STAGE_COUNT: usize = 2 + COMPUTE_PIPES; + mod compute { + pub const EVENT: u32 = 15; + } + const COMPUTE_EVENT_MASK: u32 = ((1u32 << COMPUTE_PIPES) - 1) << compute::EVENT; + mod rings { + pub const EVENT_RECORD: usize = 0x48; + } + mod bindings { + pub unsafe fn ktime_get() -> i64 { + 12345 + } + } + mod device { + pub struct Device; + } + macro_rules! dev_warn { ($dev:expr, $($arg:tt)*) => {{ let _ = ($dev, format_args!($($arg)*)); }}; } + macro_rules! dev_err { ($dev:expr, $($arg:tt)*) => {{ let _ = ($dev, format_args!($($arg)*)); }}; } + fn rmb() {} + fn wmb() {} + fn mb() {} + + struct Mem { + words: RefCell>, + reads: Cell, + writes: Cell, + fail_at_offset: Cell>, + } + impl Mem { + fn new(n_words: usize) -> Self { + Self { + words: RefCell::new(vec![0u32; n_words]), + reads: Cell::new(0), + writes: Cell::new(0), + fail_at_offset: Cell::new(None), + } + } + fn r32(&self, off: usize) -> Result { + self.reads.set(self.reads.get() + 1); + if self.fail_at_offset.get() == Some(off) { + return Err(EIO); + } + Ok(self.words.borrow()[off / 4]) + } + fn w32(&self, off: usize, val: u32) -> Result { + self.writes.set(self.writes.get() + 1); + self.words.borrow_mut()[off / 4] = val; + Ok(()) + } + } + + struct Ring { + state: Mem, + ring: Mem, + } + impl Ring { + fn new() -> Self { + Self { + state: Mem::new(0x40), + ring: Mem::new(RING_SLOTS as usize * RECORD_WORDS), + } + } + fn put_record(&self, slot: u32, words: &[u32]) { + let mut buf = self.ring.words.borrow_mut(); + let base = slot as usize * RECORD_WORDS; + for (i, &w) in words.iter().enumerate() { + buf[base + i] = w; + } + } + fn set_indices(&self, read: u32, write: u32) { + let mut st = self.state.words.borrow_mut(); + st[STATE_READ / 4] = read; + st[STATE_WRITE / 4] = write; + } + fn read_idx(&self) -> u32 { + self.state.words.borrow()[STATE_READ / 4] + } + } + + #[derive(Clone, Copy)] + struct ErrorEvent { + kind: u32, + slot: i32, + raw: [u32; RECORD_WORDS], + } + + #[derive(Default)] + struct Events { + stage_events: u32, + ta_events: u32, + fs_events: u32, + compute_events: u32, + event_ns: [u64; STAGE_COUNT], + errors: u32, + channel_errors: u32, + recovery_started_ns: Option, + last_error: Option, + last_statistics: Option<[u32; RECORD_WORDS]>, + recovery_statistics: u32, + } + + impl Events { + fn indices(ring: &Ring) -> Result<(u32, u32)> { + let read = ring.state.r32(STATE_READ)?; + let producer = ring.state.r32(STATE_WRITE)?; + if read >= RING_SLOTS || producer >= RING_SLOTS { + return Err(EIO); + } + rmb(); + Ok((read, producer)) + } + fn words(ring: &Ring, slot: u32) -> Result<[u32; RECORD_WORDS]> { + let base = slot as usize * rings::EVENT_RECORD; + let mut out = [0u32; RECORD_WORDS]; + for (i, word) in out.iter_mut().enumerate() { + *word = ring.ring.r32(base + i * 4)?; + } + Ok(out) + } + __EVENT_DRAIN__ + __EVENT_DRAIN_STATS__ + } + + #[test] + fn event_drain_batches_state_read_and_minimizes_wc_reads() { + let ring = Ring::new(); + // 5 consecutive type-1 stage events: TA (0x70 -> word 4 bit 16), FS (0x71 -> word 4 bit 17), + // Compute pipe 0 (15 -> word 1 bit 15), Compute pipe 1 (16 -> word 1 bit 16), + // and Compute pipe 7 (22 -> word 1 bit 22, event_ns[9]). + let mut r0 = [0u32; RECORD_WORDS]; + r0[0] = 1; + r0[4] = 1 << 16; + let mut r1 = [0u32; RECORD_WORDS]; + r1[0] = 1; + r1[4] = 1 << 17; + let mut r2 = [0u32; RECORD_WORDS]; + r2[0] = 1; + r2[1] = 1 << 15; + let mut r3 = [0u32; RECORD_WORDS]; + r3[0] = 1; + r3[1] = 1 << 16; + let mut r4 = [0u32; RECORD_WORDS]; + r4[0] = 1; + r4[1] = 1 << 22; + ring.put_record(0, &r0); + ring.put_record(1, &r1); + ring.put_record(2, &r2); + ring.put_record(3, &r3); + ring.put_record(4, &r4); + ring.set_indices(0, 5); + + let mut ev = Events::default(); + ev.drain(&device::Device, &ring).unwrap(); + assert_eq!(ev.event_ns[0], 12345); + assert_eq!(ev.event_ns[1], 12345); + assert_eq!(ev.event_ns[2], 12345); + assert_eq!(ev.event_ns[3], 12345); + assert_eq!(ev.event_ns[9], 12345); + assert_eq!(ev.fs_events, 1); + assert_eq!(ev.compute_events, 3); + assert_eq!(ev.stage_events, 5); + assert_eq!(ring.read_idx(), 5); + // Exactly ONE STATE_READ write for all 5 records! + assert_eq!(ring.state.writes.get(), 1); + // Exactly 3 WC reads per type-1 record (kind, word 1, word 4) = 15 reads (not 90)! + assert_eq!(ring.ring.reads.get(), 15); + } + + #[test] + fn event_drain_flushes_progress_on_mid_burst_error() { + let ring = Ring::new(); + let mut r0 = [0u32; RECORD_WORDS]; + r0[0] = 1; + r0[4] = 1 << 17; + ring.put_record(0, &r0); + ring.set_indices(0, 2); + // Fail reading record 1's kind word. + ring.ring.fail_at_offset.set(Some(rings::EVENT_RECORD)); + let mut ev = Events::default(); + assert_eq!(ev.drain(&device::Device, &ring), Err(EIO)); + // Record 0 progress must still have been flushed to STATE_READ = 1. + assert_eq!(ring.read_idx(), 1); + assert_eq!(ring.state.writes.get(), 1); + assert_eq!(ev.fs_events, 1); + } + + #[test] + fn stats_drain_batches_state_read_and_reads_single_word_for_non_recovery() { + let ring = Ring::new(); + let mut r0 = [0u32; RECORD_WORDS]; + r0[0] = 0x10; + let mut r1 = [0u32; RECORD_WORDS]; + r1[0] = 0x11; + let mut r2 = [0u32; RECORD_WORDS]; + r2[0] = 0x16; + ring.put_record(0, &r0); + ring.put_record(1, &r1); + ring.put_record(2, &r2); + ring.set_indices(0, 3); + + let mut ev = Events::default(); + ev.drain_statistics(&device::Device, &ring).unwrap(); + assert_eq!(ev.recovery_statistics, 1); + assert!(ev.last_statistics.is_some()); + assert_eq!(ring.read_idx(), 3); + assert_eq!(ring.state.writes.get(), 1); + // 1 read each for r0, r1 + 1 (kind) + 18 (full words) for r2 = 21 reads (vs 54). + assert_eq!(ring.ring.reads.get(), 21); + } +} + +mod resnap_sync_test { + use std::sync::{ + Arc, Barrier, Mutex, + atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}, + }; + + const BACKUP_REARM_NS: u64 = 1_000_000; + static CLOCK: AtomicU64 = AtomicU64::new(0); + fn now_ns() -> u64 { + CLOCK.load(Ordering::Acquire) + } + + mod params { + pub fn resnap_us() -> u32 { + 100 + } + pub fn repoll_us() -> u32 { + 25 + } + } + #[allow(non_upper_case_globals)] + mod module_parameters { + pub struct Param(u32); + impl Param { + pub fn value(&self) -> u32 { + self.0 + } + } + pub static g16_repoll_us: Param = Param(25); + } + + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + struct Delta(i64); + impl Delta { + fn from_micros(us: i64) -> Self { + Self(us) + } + } + + struct Handle { + drops: Arc, + } + impl Drop for Handle { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::AcqRel); + } + } + + struct Lock(Mutex); + impl Lock { + fn new(v: T) -> Self { + Self(Mutex::new(v)) + } + fn lock(&self) -> std::sync::MutexGuard<'_, T> { + self.0.lock().unwrap() + } + } + + struct Shared { + sleeping: AtomicBool, + ewma_flight_us: AtomicU32, + resnap_deadline_ns: AtomicU64, + backup_deadline_ns: AtomicU64, + resnap_handle: Lock>, + starts: AtomicU32, + drops: Arc, + mod_polls: AtomicU32, + } + + impl Shared { + fn new() -> Arc { + Arc::new(Self { + sleeping: AtomicBool::new(false), + ewma_flight_us: AtomicU32::new(0), + resnap_deadline_ns: AtomicU64::new(0), + backup_deadline_ns: AtomicU64::new(0), + resnap_handle: Lock::new(None), + starts: AtomicU32::new(0), + drops: Arc::new(AtomicU32::new(0)), + mod_polls: AtomicU32::new(0), + }) + } + fn start(self: Arc, _delta: Delta) -> Handle { + self.starts.fetch_add(1, Ordering::AcqRel); + Handle { + drops: self.drops.clone(), + } + } + fn mod_poll(self: &Arc, _delay: u64) { + self.mod_polls.fetch_add(1, Ordering::AcqRel); + } + + __CANCEL_RESNAP__ + __IDLE_RESNAP__ + __REARM_US__ + __REARM__ + __REARM_AFTER__ + __NOTE_FLIGHT_US__ + } + + #[test] + fn idle_resnap_avoids_churn_for_short_armed_timer_while_cancelling_long_or_stale() { + CLOCK.store(100_000, Ordering::Release); + let shared = Shared::new(); + // Unarmed idle: no-op without dropping anything. + shared.idle_resnap(); + assert_eq!(shared.drops.load(Ordering::Acquire), 0); + + // Short armed timer (<= resnap_us = 100 us): preserved across brief d=1 idle gap. + shared.rearm(false); + assert_eq!(shared.starts.load(Ordering::Acquire), 1); + CLOCK.store(120_000, Ordering::Release); + shared.idle_resnap(); + assert_eq!(shared.drops.load(Ordering::Acquire), 0); + assert!(shared.resnap_handle.lock().is_some()); + + // Next submission arriving within window reuses the armed timer without restart. + shared.rearm(false); + assert_eq!(shared.starts.load(Ordering::Acquire), 1); + assert_eq!(shared.drops.load(Ordering::Acquire), 0); + + // Overdue or > resnap_us timer falls back to unconditional cancel_resnap(). + CLOCK.store(200_000, Ordering::Release); + shared.idle_resnap(); + assert_eq!(shared.drops.load(Ordering::Acquire), 1); + assert!(shared.resnap_handle.lock().is_none()); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 0); + } + + #[test] + fn note_flight_us_decays_rapidly_downward_for_burst_transitions() { + let shared = Shared::new(); + shared.note_flight_us(260); + assert_eq!(shared.ewma_flight_us.load(Ordering::Relaxed), 260); + // Three 20 us flights decay rapidly below 2 * resnap_us (200 -> 140 -> 80 -> 50). + shared.note_flight_us(20); + assert_eq!(shared.ewma_flight_us.load(Ordering::Relaxed), 140); + shared.note_flight_us(20); + assert_eq!(shared.ewma_flight_us.load(Ordering::Relaxed), 80); + shared.note_flight_us(20); + assert_eq!(shared.ewma_flight_us.load(Ordering::Relaxed), 50); + assert_eq!(shared.rearm_us(false), 25); + } + + #[test] + fn adaptive_rearm_us_scales_with_short_flight_ewma() { + let shared = Shared::new(); + assert_eq!(shared.rearm_us(false), 100); + assert_eq!(shared.rearm_us(true), 25); + + // Very short 30 us flights clamp to repoll_us (25 us). + shared.ewma_flight_us.store(30, Ordering::Relaxed); + assert_eq!(shared.rearm_us(false), 25); + + // 100 us flights halve to 50 us. + shared.ewma_flight_us.store(100, Ordering::Relaxed); + assert_eq!(shared.rearm_us(false), 50); + + // Heavy 250+ us flights stay at full resnap_us (100 us). + shared.ewma_flight_us.store(250, Ordering::Relaxed); + assert_eq!(shared.rearm_us(false), 100); + } + + #[test] + fn resnap_rearm_coalesces_and_cancel_disarms_unconditionally() { + CLOCK.store(100_000, Ordering::Release); + let shared = Shared::new(); + shared.rearm(false); + assert_eq!(shared.starts.load(Ordering::Acquire), 1); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 200_000); + assert!(shared.resnap_handle.lock().is_some()); + + // Same-window rearm coalesces without cancelling/restarting the handle. + CLOCK.store(102_000, Ordering::Release); + shared.rearm(false); + assert_eq!(shared.starts.load(Ordering::Acquire), 1); + assert_eq!(shared.drops.load(Ordering::Acquire), 0); + + // Sooner repoll (>5 us earlier) replaces the handle cleanly. + shared.rearm(true); + assert_eq!(shared.starts.load(Ordering::Acquire), 2); + assert_eq!(shared.drops.load(Ordering::Acquire), 1); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 127_000); + + // Coalesce rearm_after(18) pulls in a 25 us timer (>5 us earlier) and coalesces within 5 us. + shared.rearm_after(18); + assert_eq!(shared.starts.load(Ordering::Acquire), 3); + assert_eq!(shared.drops.load(Ordering::Acquire), 2); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 120_000); + CLOCK.store(106_000, Ordering::Release); + shared.rearm_after(14); + assert_eq!(shared.starts.load(Ordering::Acquire), 3); + assert_eq!(shared.drops.load(Ordering::Acquire), 2); + + // cancel_resnap unconditionally clears deadline and drops handle. + shared.cancel_resnap(); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 0); + assert!(shared.resnap_handle.lock().is_none()); + assert_eq!(shared.drops.load(Ordering::Acquire), 3); + } + + #[test] + fn sleep_cancel_resnap_never_leaves_handle_armed_under_concurrent_rearm() { + CLOCK.store(1_000_000, Ordering::Release); + for _ in 0..200 { + let shared = Shared::new(); + shared.rearm(false); + let start = Arc::new(Barrier::new(2)); + let s1 = shared.clone(); + let b1 = start.clone(); + let t = std::thread::spawn(move || { + b1.wait(); + for _ in 0..32 { + s1.rearm(true); + } + }); + start.wait(); + // Exact sleep_down() + join_workers() sequence: sleeping = true, then cancel_resnap(). + shared.sleeping.store(true, Ordering::Release); + shared.cancel_resnap(); + t.join().unwrap(); + assert!( + shared.resnap_handle.lock().is_none(), + "rearm leaked an hrtimer handle past sleep_down() + cancel_resnap()" + ); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 0); + } + } +} + +#[path = "__USAGE_PATH__"] +mod usage; + +#[test] +fn per_file_usage_union_deduplicates_pipelined_and_dual_pipe_siblings() { + let client = Arc::new(usage::Client::new()); + const HZ: u32 = 24_000_000; + // Two pipelined renders whose TA and FS intervals overlap across flights. + client.add_union(usage::Engine::Vertex, 24_000, 48_000, HZ); + client.add_union(usage::Engine::Fragment, 40_000, 88_000, HZ); + client.add_union(usage::Engine::Vertex, 36_000, 72_000, HZ); + client.add_union(usage::Engine::Fragment, 64_000, 120_000, HZ); + // Two sibling queues on the same DRM file overlapping across dual CDM pipes. + client.add_union(usage::Engine::Compute, 100_000, 124_000, HZ); + client.add_union(usage::Engine::Compute, 106_000, 130_000, HZ); + let [v_ns, f_ns, c_ns] = client.snapshot(); + // Vertex union: [24k, 72k] = 48k ticks = 2_000_000 ns (not 60k ticks = 2.5 ms). + assert_eq!(v_ns, 2_000_000); + // Fragment union: [40k, 120k] = 80k ticks = 3_333_333 ns (distinct from Vertex). + assert_eq!(f_ns, 3_333_333); + assert_ne!(v_ns, f_ns); + // Compute union: [100k, 130k] = 30k ticks = 1_250_000 ns (not 48k ticks = 2.0 ms). + assert_eq!(c_ns, 1_250_000); +} + +mod poll_placement_test { + use std::sync::{ + Arc, Mutex, + atomic::{AtomicU32, Ordering}, + }; + + const FAST_POLL_WORK: u64 = 1; + const UNBOUND_POLL_WORK: u64 = 4; + + #[derive(Default)] + struct Queue { + calls: Mutex, u64)>>, + } + impl Queue { + fn enqueue(&self, _item: P) -> Result<(), ()> { + self.calls.lock().unwrap().push((None, ID)); + Ok(()) + } + fn enqueue_on(&self, cpu: u32, _item: P) -> Result<(), ()> { + self.calls.lock().unwrap().push((Some(cpu), ID)); + Ok(()) + } + fn take(&self) -> Vec<(Option, u64)> { + std::mem::take(&mut *self.calls.lock().unwrap()) + } + } + + struct Shared { + active_flights: AtomicU32, + submitter: AtomicU32, + events: Queue, + events_unbound: Queue, + } + impl Shared { + fn new() -> Arc { + Arc::new(Self { + active_flights: AtomicU32::new(0), + submitter: AtomicU32::new(u32::MAX), + events: Queue::default(), + events_unbound: Queue::default(), + }) + } + fn submitter_cpu(&self) -> Option { + let v = self.submitter.load(Ordering::Relaxed); + (v != u32::MAX).then_some(v) + } + __POLL_NOW__ + } + + #[test] + fn poll_now_pins_single_flight_and_routes_pipelined_flights_unbound() { + let shared = Shared::new(); + shared.submitter.store(3, Ordering::Relaxed); + + // d=0 and d=1 pin FAST_POLL_WORK onto the submitting CPU. + shared.active_flights.store(0, Ordering::Release); + shared.poll_now(); + assert_eq!(shared.events.take(), vec![(Some(3), FAST_POLL_WORK)]); + assert!(shared.events_unbound.take().is_empty()); + + shared.active_flights.store(1, Ordering::Release); + shared.poll_now(); + assert_eq!(shared.events.take(), vec![(Some(3), FAST_POLL_WORK)]); + assert!(shared.events_unbound.take().is_empty()); + + // Without a recorded submitter CPU, d=1 falls back to events.enqueue(). + shared.submitter.store(u32::MAX, Ordering::Relaxed); + shared.poll_now(); + assert_eq!(shared.events.take(), vec![(None, FAST_POLL_WORK)]); + assert!(shared.events_unbound.take().is_empty()); + + // d>=2 routes UNBOUND_POLL_WORK onto events_unbound even with a valid submitter CPU. + shared.submitter.store(3, Ordering::Relaxed); + for depth in [2u32, 4, 16] { + shared.active_flights.store(depth, Ordering::Release); + shared.poll_now(); + assert!(shared.events.take().is_empty()); + assert_eq!( + shared.events_unbound.take(), + vec![(None, UNBOUND_POLL_WORK)] + ); + } + } +} +''' + +harness = harness.replace( + '__USAGE_PATH__', str(kernel_root() / 'drivers/gpu/drm/asahi/usage.rs') +) + +for token, decl in { + '__SUBMIT_LOCKED__': 'fn submit_locked(', + '__RECLAIM_CLOSED_VM_SLOTS__': 'pub(crate) fn reclaim_closed_vm_slots(', + '__POLL_STEP__': 'pub(crate) fn poll_step(', + '__RUN_HOUSEKEEPING__': 'pub(crate) fn run_housekeeping(', + '__OLDEST_TERMINAL_EVENTS__': 'fn oldest_terminal_events(', + '__TA_WAVE_READY__': 'fn ta_wave_ready(', + '__OLDEST_STAMP_REACHED__': 'fn oldest_stamp_reached(', + '__CANCEL_RESNAP__': 'pub(crate) fn cancel_resnap(', + '__IDLE_RESNAP__': 'pub(crate) fn idle_resnap(', + '__REARM_US__': 'pub(crate) fn rearm_us(', + '__REARM__': 'pub(crate) fn rearm(', + '__REARM_AFTER__': 'pub(crate) fn rearm_after(', + '__POLL_NOW__': 'pub(crate) fn poll_now(', +}.items(): + harness = harness.replace(token, item(decl).replace('super::hw::', 'hw::')) +harness = harness.replace('__NOTE_FLIGHT_US__', item('pub(crate) fn note_flight_us(', mod_source)) +for token, decl in { + '__EVENT_DRAIN__': 'pub(crate) fn drain(', + '__EVENT_DRAIN_STATS__': 'pub(crate) fn drain_statistics(', +}.items(): + harness = harness.replace(token, item(decl, event_source)) + +unit = output / 'poll-retire.rs' +unit.write_text(harness) +log = '' +for command in [ + rustc() + ['--edition=2021', '--test', str(unit), '-o', str(output / 'poll-retire')], + [str(output / 'poll-retire'), '--nocapture'], +]: + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + log += result.stdout + print(result.stdout, end='') + (output / 'poll-retire.log').write_text(log) + if result.returncode: + raise SystemExit(result.returncode) +(output / 'poll-retire.json').write_text( + json.dumps( + { + 'passed': True, + 'tests': 25, + 'cpu_only': True, + 'hardware_execution': False, + 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', + 'source_sha256': sha(production), + }, + indent=2, + ) + + '\n' +) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py index f73ba928dc4914..19ebbe49508af7 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py @@ -4,47 +4,227 @@ from common import kernel_root, output_dir, rustc, sha import subprocess,json root=kernel_root();out=output_dir();backend=root/'drivers/gpu/drm/asahi/g16' -source=(backend/'poll.rs').read_text();engine=(backend/'engine.rs').read_text() +source=(backend/'poll.rs').read_text();engine=(backend/'engine.rs').read_text();recovery_src=(backend/'recovery.rs').read_text() def function(text,name): marker=text.index('fn '+name+'(');start=text.rfind('\n',0,marker)+1;at=text.index('{',marker);depth,end=1,at+1 while depth:depth+=(text[end]=='{')-(text[end]=='}');end+=1 return text[start:end] -option='progress: [Option; 3]' in engine +option='progress: [Option; sizes::COMPUTE_PIPES + 2]' in engine harness=r''' #![allow(dead_code)] use std::cell::Cell; #[path="__LOGIC__"]mod logic; use logic::stamp_reached; -struct Object(Cell);impl Object{fn r32(&self,_off:usize)->Result{Ok(self.0.get())}} -struct Compute{fw_stamp:Object}struct Render{fw_stamp:[Object;2]}struct Graph{compute:Compute,render:Render} -struct Flight{computes:u32,renders:u32,target:u32,ta_target:u32,fs_target:u32,published_ns:u64} -struct Engine{flight:Flight,target:u32,ta_target:u32,fs_target:u32,progress_flight:u64,progress:[__TYPE__;3]} -impl Engine{fn oldest(&self)->Option<&Flight>{Some(&self.flight)}} -struct Firmware{graph:Graph,engine:Engine,renewed:u32} -impl Firmware{fn renew_deadlines(&mut self){self.renewed+=1;} __PROGRESS__ } +#[derive(Copy,Clone,Debug,PartialEq,Eq)]struct Error(i32); +const EIO:Error=Error(5);const ETIMEDOUT:Error=Error(110); +type Result=core::result::Result; +mod hw{pub mod sizes{pub const COMPUTE_PIPES:usize=8;}} +mod command{pub const RENDER:usize=0;pub const COMPUTE:usize=1;} +mod params{ + pub fn recovery()->bool{true} + pub fn deadline_ms()->u32{1000} + pub fn compute_deadline_ms()->u32{5000} +} +thread_local!{static CLOCK:Cell=const{Cell::new(0)};} +fn now_ns()->u64{CLOCK.with(|c|c.get())} +fn set_now_ns(v:u64){CLOCK.with(|c|c.set(v));} +macro_rules! dev_warn{($($tt:tt)*)=>{};} +macro_rules! dev_err{($($tt:tt)*)=>{};} +struct Object(Cell);impl Object{fn r32(&self,_off:usize)->core::result::Result{Ok(self.0.get())}} +struct Compute{fw_stamp:Object}struct Render{fw_stamp:[Object;2]}struct Graph{compute:[Compute;hw::sizes::COMPUTE_PIPES],render:Render} +struct Job{long:bool} +impl Job{fn long(&self)->bool{self.long}} +struct Flight{job:Job,computes:u32,compute_pipe:u8,renders:u32,target:u32,ta_target:u32,fs_target:u32,published_ns:u64} +struct Engine{flights:Vec,target:[u32;hw::sizes::COMPUTE_PIPES],ta_target:u32,fs_target:u32,progress_flight:[u64;hw::sizes::COMPUTE_PIPES+1],progress:[__TYPE__;hw::sizes::COMPUTE_PIPES+2]} +impl Engine{fn oldest(&self)->Option<&Flight>{self.flights.first()}} +struct Recovery{deadlines:logic::Deadlines,compute_deadlines:[logic::Deadlines;hw::sizes::COMPUTE_PIPES],warning_deadline_ns:[u64;2],compute_warning_deadline_ns:[u64;hw::sizes::COMPUTE_PIPES],long_commands:u64,receipt_fault:bool,failed:Option} +struct Firmware{graph:Graph,engine:Engine,recovery:Recovery,render_renewed:u32,compute_renewed:u32,pipe_renewed:[u32;hw::sizes::COMPUTE_PIPES],fail_stops:Vec} +impl Firmware{ + fn dev(&self){} + fn transport_error(&self)->Option{None} + fn recovery_pending(&self)->Result{Ok(false)} + fn recover(&mut self)->Result{Ok(())} + fn fail_stop(&mut self,error:Error,_done:&mut ()){self.recovery.failed=Some(error);self.fail_stops.push(error);} + fn renew_render_deadline(&mut self){ + let now=now_ns(); + let renewed=logic::Deadlines::renew(now,params::deadline_ms(),0); + self.recovery.deadlines.any=renewed.any; + self.recovery.deadlines.long_any=renewed.long_any; + self.recovery.warning_deadline_ns[command::RENDER]=now.saturating_add(5_000_000_000); + self.render_renewed+=1; + } + fn renew_compute_pipe_deadline(&mut self,pipe:usize){ + let pipe=pipe.min(hw::sizes::COMPUTE_PIPES-1); + let now=now_ns(); + let renewed=logic::Deadlines::renew(now,0,params::compute_deadline_ms()); + self.recovery.compute_deadlines[pipe].compute=renewed.compute; + self.recovery.compute_deadlines[pipe].long_compute=renewed.long_compute; + self.recovery.compute_warning_deadline_ns[pipe]=now.saturating_add(5_000_000_000); + self.pipe_renewed[pipe]+=1; + self.compute_renewed+=1; + } + fn renew_compute_deadline(&mut self){ + for pipe in 0..hw::sizes::COMPUTE_PIPES{ + self.renew_compute_pipe_deadline(pipe); + } + } + __PROGRESS__ + __CHECK_HANGS__ +} +type Completions=(); fn firmware(render:bool,target:u32,previous:u32)->Firmware{ - Firmware{graph:Graph{compute:Compute{fw_stamp:Object(Cell::new(previous))},render:Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]}}, - engine:Engine{flight:Flight{computes:u32::from(!render),renders:u32::from(render),target,ta_target:target,fs_target:target,published_ns:1},target,ta_target:target,fs_target:target,progress_flight:0,progress:[__ZERO__;3]},renewed:0} + set_now_ns(1_000_000_000); + let mut t=[0u32;hw::sizes::COMPUTE_PIPES];t[0]=target; + let mut f=Firmware{graph:Graph{compute:core::array::from_fn(|_|Compute{fw_stamp:Object(Cell::new(previous))}),render:Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]}}, + engine:Engine{flights:vec![Flight{job:Job{long:false},computes:u32::from(!render),compute_pipe:0,renders:u32::from(render),target,ta_target:target,fs_target:target,published_ns:1}],target:t,ta_target:target,fs_target:target,progress_flight:[0;hw::sizes::COMPUTE_PIPES+1],progress:[__ZERO__;hw::sizes::COMPUTE_PIPES+2]}, + recovery:Recovery{deadlines:logic::Deadlines::EXPIRED,compute_deadlines:[logic::Deadlines::EXPIRED;hw::sizes::COMPUTE_PIPES],warning_deadline_ns:[u64::MAX;2],compute_warning_deadline_ns:[u64::MAX;hw::sizes::COMPUTE_PIPES],long_commands:0,receipt_fault:false,failed:None}, + render_renewed:0,compute_renewed:0,pipe_renewed:[0;hw::sizes::COMPUTE_PIPES],fail_stops:vec![]}; + f.renew_render_deadline();f.renew_compute_deadline();f.render_renewed=0;f.compute_renewed=0;f.pipe_renewed=[0;hw::sizes::COMPUTE_PIPES];f } #[test]fn pending_native_zero_and_reached_are_distinct_progress_states(){ - let mut f=firmware(false,0x100,0);f.progress();assert_eq!(f.renewed,0);f.progress();assert_eq!(f.renewed,0); - f.graph.compute.fw_stamp.0.set(0x100);f.progress();assert_eq!(f.renewed,1,"completion following real wire zero renews deadline before retirement check"); - f.progress();assert_eq!(f.renewed,1,"repeated completed stamp is not new progress"); + let mut f=firmware(false,0x100,0);f.progress();assert_eq!(f.compute_renewed,0);f.progress();assert_eq!(f.compute_renewed,0); + f.graph.compute[0].fw_stamp.0.set(0x100);f.progress();assert_eq!(f.compute_renewed,1,"completion following real wire zero renews deadline before retirement check"); + assert_eq!(f.render_renewed,0); + f.progress();assert_eq!(f.compute_renewed,1,"repeated completed stamp is not new progress"); } #[test]fn paired_ta_fs_zero_each_renews_once_without_lending_other_engine_progress(){ let mut f=firmware(true,0x100,0);f.progress(); - f.graph.compute.fw_stamp.0.set(0x100);f.progress();assert_eq!(f.renewed,0); - f.graph.render.fw_stamp[0].0.set(0x100);f.progress();assert_eq!(f.renewed,1); - f.graph.render.fw_stamp[1].0.set(0x100);f.progress();assert_eq!(f.renewed,2);f.progress();assert_eq!(f.renewed,2); + f.graph.compute[0].fw_stamp.0.set(0x100);f.progress();assert_eq!(f.render_renewed,0);assert_eq!(f.compute_renewed,0); + f.graph.render.fw_stamp[0].0.set(0x100);f.progress();assert_eq!(f.render_renewed,1);assert_eq!(f.compute_renewed,0); + f.graph.render.fw_stamp[1].0.set(0x100);f.progress();assert_eq!(f.render_renewed,2);assert_eq!(f.compute_renewed,0); + f.progress();assert_eq!(f.render_renewed,2); } #[test]fn before_at_and_after_zero_completions_have_the_same_progress_contract(){ for target in [0x7fffff00u32,0x80000000,0xffffff00,0,0x100]{ - let mut f=firmware(false,target,target.wrapping_sub(0x100));f.progress();assert_eq!(f.renewed,0); - f.graph.compute.fw_stamp.0.set(target);f.progress();assert_eq!(f.renewed,1); - f.engine.flight.published_ns=2;f.progress();assert_eq!(f.renewed,1,"new flight first sample is not forward progress"); + let mut f=firmware(false,target,target.wrapping_sub(0x100));f.progress();assert_eq!(f.compute_renewed,0); + f.graph.compute[0].fw_stamp.0.set(target);f.progress();assert_eq!(f.compute_renewed,1); + f.engine.flights[0].published_ns=2;f.progress();assert_eq!(f.compute_renewed,1,"new flight first sample is not forward progress"); + } +} +#[test]fn concurrent_compute_and_render_renew_deadlines_independently(){ + let mut f=firmware(true,0x200,0x100); + f.engine.flights.push(Flight{job:Job{long:false},computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.target[0]=0x300; + f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,0)); + f.graph.compute[0].fw_stamp.0.set(0x300);f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,1)); + f.graph.render.fw_stamp[0].0.set(0x200);f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(1,1)); +} +#[test]fn two_concurrent_compute_pipes_sample_progress_independently(){ + let mut f=firmware(false,0x200,0x100); + f.engine.flights.push(Flight{job:Job{long:false},computes:1,compute_pipe:1,renders:0,target:0x200,ta_target:0,fs_target:0,published_ns:2}); + f.engine.target[0]=0x200;f.engine.target[1]=0x200; + f.progress();assert_eq!(f.compute_renewed,0); + // Pipe 1 advances while pipe 0 stays pending -> renews compute deadline once. + f.graph.compute[1].fw_stamp.0.set(0x200); + f.progress();assert_eq!(f.compute_renewed,1); + f.progress();assert_eq!(f.compute_renewed,1); + // Pipe 0 advances independently -> renews compute deadline a second time. + f.graph.compute[0].fw_stamp.0.set(0x200); + f.progress();assert_eq!(f.compute_renewed,2); +} +#[test]fn stuck_render_times_out_while_compute_keeps_advancing_and_retiring(){ + let mut f=firmware(true,0x200,0x100); + f.engine.flights.push(Flight{job:Job{long:false},computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.target[0]=0x300; + let mut done=(); + assert_eq!(f.check_hangs(&mut done),Ok(())); + // Compute keeps advancing and retiring every 400 ms across 1.2 s while render stays stuck at 0x100. + for step in 1u64..=3 { + set_now_ns(1_000_000_000 + step * 400_000_000); + let next_target = 0x300 + (step as u32) * 0x100; + f.graph.compute[0].fw_stamp.0.set(next_target - 0x100); + f.engine.flights[1].target = next_target; + f.engine.flights[1].published_ns = 2 + step; + f.engine.target[0] = next_target; + f.renew_compute_deadline(); + let res = f.check_hangs(&mut done); + if step < 3 { + assert_eq!(res, Ok(()), "render deadline (1s) not yet expired at step {step}"); + assert_eq!(f.render_renewed, 0, "compute progress/retirement must never renew render deadline"); + } else { + assert_eq!(res, Err(ETIMEDOUT), "stuck render must fail-stop at 1.2s despite active compute"); + assert_eq!(f.fail_stops, [ETIMEDOUT]); + } + } +} +#[test]fn stuck_compute_times_out_while_render_keeps_advancing_and_retiring(){ + let mut f=firmware(false,0x200,0x100); + f.engine.flights.push(Flight{job:Job{long:false},computes:0,compute_pipe:0,renders:1,target:0,ta_target:0x300,fs_target:0x300,published_ns:2}); + f.engine.ta_target=0x300;f.engine.fs_target=0x300; + let mut done=(); + assert_eq!(f.check_hangs(&mut done),Ok(())); + // Render keeps advancing and retiring every 2 s across 6 s while compute stays stuck at 0x100. + for step in 1u64..=3 { + set_now_ns(1_000_000_000 + step * 2_000_000_000); + let next_target = 0x300 + (step as u32) * 0x100; + f.graph.render.fw_stamp[0].0.set(next_target - 0x100); + f.graph.render.fw_stamp[1].0.set(next_target - 0x100); + f.engine.flights[1].ta_target = next_target; + f.engine.flights[1].fs_target = next_target; + f.engine.flights[1].published_ns = 2 + step; + f.engine.ta_target = next_target; + f.engine.fs_target = next_target; + f.renew_render_deadline(); + let res = f.check_hangs(&mut done); + if step < 3 { + assert_eq!(res, Ok(()), "compute deadline (5s) not yet expired at step {step}"); + assert_eq!(f.compute_renewed, 0, "render progress/retirement must never renew compute deadline"); + } else { + assert_eq!(res, Err(ETIMEDOUT), "stuck compute must fail-stop at 6s despite active render"); + assert_eq!(f.fail_stops, [ETIMEDOUT]); + } } } -'''.replace('__LOGIC__',str(backend/'recovery/logic.rs')).replace('__PROGRESS__',function(source,'progress')).replace('__TYPE__','Option' if option else 'u32').replace('__ZERO__','None' if option else '0') +#[test]fn stuck_compute_pipe_times_out_while_other_compute_pipe_advances_and_retires(){ + // Pipe 0 has a normal flight stuck at 0x100 (5s deadline); pipe 1 runs a long job that + // keeps advancing and retiring every 2s across 6s. Pipe 1 progress/retirement must never + // renew pipe 0's deadline or grant pipe 0 the 10s long-job allowance. + let mut f=firmware(false,0x200,0x100); + f.engine.flights.push(Flight{job:Job{long:true},computes:1,compute_pipe:1,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.target[1]=0x300; + let mut done=(); + assert_eq!(f.check_hangs(&mut done),Ok(())); + for step in 1u64..=3 { + set_now_ns(1_000_000_000 + step * 2_000_000_000); + let next_target = 0x300 + (step as u32) * 0x100; + f.graph.compute[1].fw_stamp.0.set(next_target - 0x100); + f.engine.flights[1].target = next_target; + f.engine.flights[1].published_ns = 2 + step; + f.engine.target[1] = next_target; + f.renew_compute_pipe_deadline(1); + let res = f.check_hangs(&mut done); + if step < 3 { + assert_eq!(res, Ok(()), "pipe 0 deadline (5s) not yet expired at step {step}"); + assert_eq!(f.pipe_renewed[0], 0, "pipe 1 activity must never renew pipe 0 deadline"); + assert!(f.pipe_renewed[1] > 0); + } else { + assert_eq!(res, Err(ETIMEDOUT), "stuck pipe 0 must fail-stop at 6s despite active long pipe 1"); + assert_eq!(f.fail_stops, [ETIMEDOUT]); + } + } +} +#[test]fn younger_long_job_on_same_compute_pipe_does_not_extend_stalled_normal_head(){ + // Pipe 0 has a normal flight at index 0 (5s deadline) and a younger long flight at index 1 + // on the same pipe (10s allowance). Only the oldest active flight on a pipe selects its + // deadline, so the stalled normal head still times out at 6s instead of inheriting 10s. + let mut f=firmware(false,0x200,0x100); + f.engine.flights.push(Flight{job:Job{long:true},computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.target[0]=0x300; + let mut done=(); + set_now_ns(1_000_000_000 + 6_000_000_000); + assert_eq!(f.check_hangs(&mut done), Err(ETIMEDOUT)); + assert_eq!(f.fail_stops, [ETIMEDOUT]); + // Conversely, when the oldest flight on pipe 0 IS a long job and a younger normal job is + // queued behind it on the same pipe, pipe 0 keeps its 10s long-job allowance at 6s. + let mut fl=firmware(false,0x200,0x100); + fl.engine.flights[0].job.long=true; + fl.engine.flights.push(Flight{job:Job{long:false},computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + fl.engine.target[0]=0x300; + set_now_ns(1_000_000_000 + 6_000_000_000); + assert_eq!(fl.check_hangs(&mut done), Ok(())); + assert!(fl.fail_stops.is_empty()); +} +'''.replace('__LOGIC__',str(backend/'recovery/logic.rs')).replace('__PROGRESS__',function(source,'progress').replace('super::hw::','hw::')).replace('__CHECK_HANGS__',function(recovery_src,'check_hangs').replace('super::command::','command::').replace('super::hw::','hw::')).replace('__TYPE__','Option' if option else 'u32').replace('__ZERO__','None' if option else '0') unit=out/'progress-wrap.rs';unit.write_text(harness);log='' for command in [rustc()+['--edition=2021','--test',str(unit),'-o',str(out/'progress-wrap')],[str(out/'progress-wrap'),'--nocapture']]: result=subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True);log+=result.stdout;print(result.stdout,end='');(out/'progress-wrap.log').write_text(log) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index 6f388b4693fd41..373b2285d46690 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -7,21 +7,101 @@ production = kernel_root() / 'drivers/gpu/drm/asahi/g16/engine.rs' source = production.read_text() +params_src = (production.parent / 'params.rs').read_text() +queue_src = (production.parent / 'queue.rs').read_text() +job_src = (production.parent / 'job.rs').read_text() +mod_src = (production.parent / 'mod.rs').read_text() +hw_src = (production.parent / 'hw.rs').read_text() +gpu_src = (production.parent.parent / 'gpu.rs').read_text() output = output_dir() -def item(declaration): - start = source.index(declaration) - at = source.index('{', start) +def item_in(src, declaration): + start = src.index(declaration) + at = src.index('{', start) depth, end = 1, at + 1 while depth: - depth += (source[end] == '{') - (source[end] == '}') + depth += (src[end] == '{') - (src[end] == '}') end += 1 - return source[start:end] + return src[start:end] + + +def item(declaration): + return item_in(source, declaration) + + +# Verify Queue struct declares `_credit: QueueCredit` after `scheduler: Scheduler`. +queue_struct = item_in(queue_src, 'pub(crate) struct Queue {') +sched_pos = queue_struct.index('scheduler: Scheduler') +credit_pos = queue_struct.index('_credit: QueueCredit') +assert sched_pos < credit_pos, 'QueueCredit must drop after Scheduler' +assert queue_struct[credit_pos:].strip().endswith('}'), '_credit must be last Queue field' +gpu_limits_fn = item_in(mod_src, 'fn queue_limits(&self) -> Option') +assert 'Some(params::queue_limits())' in gpu_limits_fn, gpu_limits_fn +assert 'DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES' in gpu_src +max_queues_line = next(line for line in hw_src.splitlines() if 'const MAX_QUEUES:' in line) +flights_line = next(line for line in hw_src.splitlines() if 'const FLIGHTS:' in line) +assert 'const COMPUTE_SLOTS: usize = COMPUTE_UNITS;' in hw_src +assert 'const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32;' in hw_src +prefix_render_fn = item('fn prefix_render(') +prefix_compute_fn = item('fn prefix_compute(') +can_queue_behind_fn = item('fn can_queue_behind_with_ta(') +assert 'let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer);' in prefix_render_fn +assert ( + prefix_render_fn.index('let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer);') + < prefix_render_fn.index('if plan.ta_prev_wait') +), 'render_bar must be hoisted ahead of barrier emission' +assert prefix_render_fn.count('render_bar,') == 5, prefix_render_fn +assert 'p.prev_barrier.write(0, &prev)?;' in prefix_render_fn +# The VM mark waits for visibility: an unpublished prefix never marks its VM. +assert 'note_msaa_render' not in prefix_render_fn +assert 'f.msaa |= cmd.is_multisampled();' in prefix_render_fn +assert 'p.ta_fs_barrier.write(0, &ta_fs)?;' in prefix_render_fn +assert 'p.fs_dep.write(0, &dep)?;' in prefix_render_fn +assert 'p.compute_barrier.write(off, &cbar)?;' in prefix_render_fn +assert 'p.fs_compute_barrier.write(off, &fcbar)?;' in prefix_render_fn +c2ta_slice = prefix_render_fn[ + prefix_render_fn.index('plan.ta_compute_wait'):prefix_render_fn.index('p.compute_barrier.write') +] +c2fs_slice = prefix_render_fn[ + prefix_render_fn.index('plan.fs_compute_wait'):prefix_render_fn.index('p.fs_compute_barrier.write') +] +fs2c_slice = prefix_compute_fn[ + prefix_compute_fn.index('wait_render'):prefix_compute_fn.index('s.barrier.write') +] +assert 'work::compute::EVENTS[pipe]' in prefix_compute_fn +assert 'work::compute::EVENTS[p_idx]' in c2ta_slice +assert 'work::compute::EVENTS[p_idx]' in c2fs_slice +assert 'render_bar,' in c2ta_slice and 'BarrierType::Hold' not in c2ta_slice +assert 'render_bar,' in c2fs_slice and 'BarrierType::Hold' not in c2fs_slice +assert 'BarrierType::Stamp,' in prefix_render_fn[prefix_render_fn.index('let own = encode::barrier'):prefix_render_fn.index('p.own_barrier.write')] +assert 'cross_engine_barrier_type(producer_initbm, false)' in fs2c_slice +assert 'bar_type,' in fs2c_slice and 'BarrierType::Hold' not in fs2c_slice +assert 'let waits_for_timestamps = c.query_access' in can_queue_behind_fn +assert 'DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2' in params_src +publish_prefix_body_fn = item('fn publish_prefix_body(') +assert 'self.graph.render.threshold.w32(0, prefix.draw as u32)?;' in publish_prefix_body_fn +_visible = publish_prefix_body_fn.index('*visible = true;') +assert publish_prefix_body_fn.count('job.vm.note_msaa_render();') == 1 +assert publish_prefix_body_fn.index('job.vm.note_msaa_render();') > _visible +# Both render fold paths check each member before claiming its pass slot. +_same = publish_prefix_body_fn.index('while more_renders > 0 && end < job.progress.count()') +_horizon = publish_prefix_body_fn.index('// Cross-job render horizon') +assert publish_prefix_body_fn.count('self.msaa_member_allowed(&job.vm, r2)') == 2 +_m1 = publish_prefix_body_fn.index('self.msaa_member_allowed(&job.vm, r2)', _same) +assert _m1 < publish_prefix_body_fn.index('pick_pass_in_for(', _same) < _horizon +_m2 = publish_prefix_body_fn.index('self.msaa_member_allowed(&job.vm, r2)', _horizon) +assert _m2 < publish_prefix_body_fn.index('pick_pass_in_for(', _horizon) +assert 'let msaa_conflict = !self.msaa_member_allowed(&job.vm, r);' in can_queue_behind_fn +assert 'self.graph.render.threshold.w32(8, prefix.draw as u32)?;' in publish_prefix_body_fn +assert 'earliest_unfinished_ta_draw' not in source and 'rearm_ta_threshold' not in source +assert 'let pipe_fold_cap = if heavy_compute && c_waits == [None; sizes::COMPUTE_PIPES]' in publish_prefix_body_fn, 'pipe_fold_cap must only apply to heavy barrier-free compute' harness = r''' #![allow(dead_code, unused_variables)] +#[path = "__USAGE__"] +mod usage; use std::sync::{Arc, atomic::{AtomicU32,AtomicU64,AtomicBool,Ordering}}; use std::collections::VecDeque; #[derive(Copy,Clone,Debug,PartialEq,Eq)] struct Error(i32); @@ -29,17 +109,40 @@ def item(declaration): type Result = std::result::Result; macro_rules! dev_err {($($argument:tt)*)=>{()};} __PUBLICATION_ERROR__ -#[derive(Copy,Clone)]enum Command { Compute(()), Render(()) } +#[derive(Copy,Clone,Debug,PartialEq,Eq)]enum Channel { Ta = 0, Fs = 1, Compute = 2 } +#[derive(Copy,Clone)]struct ComputeCommand { query_access: bool, rt: bool } +impl ComputeCommand { fn is_rt(&self) -> bool { self.rt } } +#[derive(Copy,Clone)]struct RenderCommand { heavy_ta: bool, msaa: bool } +impl RenderCommand { fn is_heavy_ta(&self) -> bool { self.heavy_ta } fn is_multisampled(&self) -> bool { self.msaa } } +const R_LIGHT: RenderCommand = RenderCommand { heavy_ta: false, msaa: false }; +const R_HEAVY: RenderCommand = RenderCommand { heavy_ta: true, msaa: false }; +const R_MSAA: RenderCommand = RenderCommand { heavy_ta: false, msaa: true }; +#[derive(Copy,Clone)]enum Command { Compute(ComputeCommand), Render(RenderCommand) } struct Status(AtomicU32);impl Status{fn get(&self)->u32{self.0.load(Ordering::Relaxed)}} -struct Vm { status:Status, slot:u32 } -struct Queue { turn:AtomicU64, priority:u32 } +struct Vm { id:u64, status:Status, slot:u32, msaa:AtomicBool } +impl Vm { fn renders_msaa(&self)->bool{self.msaa.load(Ordering::Relaxed)} fn note_msaa_render(&self){self.msaa.store(true,Ordering::Relaxed)} } +struct Queue { turn:AtomicU64, priority:u32, completed:[AtomicU64;2], compute_ooo:AtomicU64, compute_ewma_us:AtomicU32 } +impl Queue { + fn new(turn:u64, priority:u32)->Arc{ + Arc::new(Self{turn:AtomicU64::new(turn),priority,completed:[AtomicU64::new(0),AtomicU64::new(0)],compute_ooo:AtomicU64::new(0),compute_ewma_us:AtomicU32::new(0)}) + } + __NOTE_COMPUTE_US__ + fn is_compute_retired(&self, seq:u64)->bool{ + let c=self.completed[command::COMPUTE].load(Ordering::Acquire); + if seq<=c { return true; } + let off=seq-c-1; + if off==0 || off>64 { return false; } + (self.compute_ooo.load(Ordering::Acquire) & (1u64 << (off-1))) != 0 + } +} struct Progress { sent:AtomicU32,count:u32,pending:AtomicBool } impl Progress { fn sent(&self)->u32{self.sent.load(Ordering::Relaxed)} fn count(&self)->u32{self.count} fn set_pending(&self,v:bool){self.pending.store(v,Ordering::Relaxed)} } -struct Job { id:u32,vm:Vm,queue:Queue,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool } +struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(24)}fn compute_slot_mask(&self)->Result{Ok((1u32 << 24) - 1)}fn compute_scs(&self)->bool{false}fn render_passes(&self)->Result{Ok(8)}fn render_scs(&self)->bool{false}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} +struct Job { id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool,resources:Resources } impl Job { fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} fn mark_terminal_retired(&self)->Result{assert!(!self.progress.pending.load(Ordering::Relaxed));self.terminal_marked.store(true,Ordering::Relaxed);Ok(())} @@ -47,32 +150,62 @@ def item(declaration): fn command(job:&Job,k:u32)->Option<&Command>{job.commands.get(k as usize)} type Completions=Vec<(u32,Result)>; fn complete(done:&mut Completions,job:&Arc,result:Result){done.push((job.id,result));} -#[derive(Default)]struct Stats{hold:[u64;3]} +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +__HOLD_CAUSE__ +__HOLD_CAUSE_IMPL__ +#[derive(Default)]struct Stats{hold:[u64;3],hold_causes:[u64;HoldCause::COUNT],grouped:u64} struct Claims; -struct Flight{claims:Claims,group:Vec>} -impl Flight{fn new(_job:Arc)->Self{Self{claims:Claims,group:vec![]}}} -struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool} +struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,doomed:bool,recovery_suspect:bool,initbm:bool,heavy_render:bool} +impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,doomed:false,recovery_suspect:false,initbm:false,heavy_render:false}}} +__SCS_COMPUTE_CONFLICT__ +__MSAA_RENDER_CONFLICT__ +struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool,held_wait:bool,handoff_avoid_pipes:u32,coalesce_deadline_ns:u64} impl Engine { __PICK__ __UNPEND__ } struct Checks;impl Checks{fn check(&self)->Result{Ok(())}fn health(&self)->Result{Ok(())}} struct Shared{sleeping:AtomicBool} -struct Session{shared:Shared}impl Session{fn check(&self)->Result{Ok(())}} +struct Session{shared:Shared,rings:Vec,ring_fail:bool,checks:AtomicU32,transports:AtomicU32} +impl Session{ + fn check(&self)->Result{self.checks.fetch_add(1,Ordering::Relaxed);Ok(())} + fn transport(&self)->Result{self.transports.fetch_add(1,Ordering::Relaxed);Ok(())} + fn ring(&mut self,channel:Channel)->Result{ + if self.ring_fail{return Err(EIO);} + self.rings.push(channel); + Ok(()) + } +} struct Recovery{error:Option,publication_wait_deadline:Option}impl Recovery{fn failed(&self)->Option{self.error}} struct Slots{compute_exhausted:bool,render_exhausted:bool,releases:u32,quarantines:u32} impl Slots{ fn compute_exhausted(&self)->bool{self.compute_exhausted} fn render_exhausted(&self)->bool{self.render_exhausted} + fn compute_exhausted_within(&self,_units:usize)->bool{self.compute_exhausted}fn compute_exhausted_in_mask(&self,_mask:u32)->bool{self.compute_exhausted} + fn render_exhausted_within(&self,_passes:usize)->bool{self.render_exhausted} fn release(&mut self,_claims:&mut Claims){self.releases+=1;} fn quarantine(&mut self,_claims:&mut Claims){self.quarantines+=1;} } +struct Pools{exhausted:bool,exhausted_vm:Option,block_pipeline_vm:Option} +impl Pools{ + fn exhausted(&self)->bool{self.exhausted} + fn exhausted_for(&self,vm:&Vm)->bool{self.exhausted_vm==Some(vm.slot)} + fn exhausted_for_within(&self,vm:&Vm,_limit:usize)->bool{self.exhausted_for(vm)} + fn exhausted_for_within_mode(&self,vm:&Vm,limit:usize,_scs:bool)->bool{self.exhausted_for_within(vm,limit)} + fn exhausted_for_mask_mode(&self,vm:&Vm,_mask:u32,_home:usize,_scs:bool)->bool{self.exhausted_for(vm)} + fn can_pipeline(&self,vm:&Arc)->bool{self.block_pipeline_vm!=Some(vm.slot)} + fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} + fn can_pipeline_within_blocks(&self,vm:&Arc,limit:usize,_min_blocks:u32)->bool{self.can_pipeline_within(vm,limit)} + fn can_pipeline_within_blocks_mode(&self,vm:&Arc,limit:usize,min_blocks:u32,_scs:bool)->bool{self.can_pipeline_within_blocks(vm,limit,min_blocks)} + fn can_pipeline_in_mask_blocks_mode(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32,_scs:bool)->bool{self.can_pipeline(vm)} +} mod encode { pub struct ComputeRefs{pub invalid:bool} // Fault injection replaces the descriptor reader, while the actual production // containment branch below decides whether the unit becomes claimable again. - pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} + pub fn validate_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64)->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } +mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_PASSES_LIGHT:usize=8; pub const TA_LIGHT_TILEMAP_BYTES:u64=64*1024; pub const TA_WAVE_REFILL_HEADROOM:usize=2; pub const COMPUTE_PIPES:usize=8; pub const MAX_VM_COMPUTE_PIPES:usize=2; pub const COMPUTE_UNITS:usize=24; pub const PIPE1_COMPUTE_START:usize=6; pub const COMPUTE_SLOTS:usize=24; pub const RENDER_SLOTS:usize=48; pub const COALESCE_MAX_CMDS:usize=6; pub const COALESCE_WINDOW_US:u32=18; pub const COALESCE_WINDOW_NS:u64=18_000; pub const COMPUTE_HEAVY_EMA_US:u32=200; pub const COMPUTE_HEAVY_INFLIGHT_NS:u64=180_000; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -109,11 +242,45 @@ def item(declaration): #[derive(Default)]struct Power{work:Vec} impl Power{fn report_work(&mut self,in_flight:bool){self.work.push(in_flight);}} struct Firmware{ - session:Session,objects:Checks,recovery:Recovery,engine:Engine,slots:Slots,power:Power, + session:Session,objects:Checks,recovery:Recovery,engine:Engine,slots:Slots,pools:Pools,power:Power, unavailable:Vec<(usize,Error)>,stages:VecDeque,retained:Vec,attempted:Vec,fail_stops:u32, + allow_behind:bool,block_render_behind:bool,block_compute_behind:bool, + ta_pending_calls:std::cell::Cell, } impl Firmware { fn mark_class_unavailable(&mut self,class:usize,error:Error){self.unavailable.push((class,error));} + fn sync_quarantine_hints(&self){} + fn compute_handoff_pipe(&self,_job:&Arc)->Option{None} + __NEEDS_ENGINE_DRAIN__ + __RENDER_CAN_PIPELINE__ + __HOLD_CAUSE_FN__ + __NOTE_HOLD__ + __TA_WAVE_CAP_FOR__ + __ACTIVE_TA_WAVE_CAP__ + fn blocked_on_slot_headroom(&self,job:&Arc)->bool{ + if self.engine.flights.is_empty()||self.needs_engine_drain(job){return false;} + if job.check_command_dependencies(job.progress.sent()).is_err(){return false;} + (self.block_render_behind&&matches!(command(job,job.progress.sent()),Some(Command::Render(_)))) + ||(self.block_compute_behind&&matches!(command(job,job.progress.sent()),Some(Command::Compute(_)))) + } + fn ta_pending_passes(&self)->usize{ + self.ta_pending_calls.set(self.ta_pending_calls.get()+1); + self.engine.flights.iter().map(|f|f.renders as usize).sum() + } + fn can_queue_behind(&self,job:&Arc)->bool{ + let mut ta_pending=None; + self.can_queue_behind_with_ta(job,&mut ta_pending) + } + fn can_queue_behind_with_ta(&self,job:&Arc,ta_pending:&mut Option)->bool{ + if !self.allow_behind{return false;} + if self.needs_engine_drain(job){return false;} + if let Some(Command::Render(r))=command(job,job.progress.sent()){ + let cap=self.ta_wave_cap_for(r.is_heavy_ta()); + if self.block_render_behind||*ta_pending.get_or_insert_with(||self.ta_pending_passes())>=cap{return false;} + } + if self.block_compute_behind&&matches!(command(job,job.progress.sent()),Some(Command::Compute(_))){return false;} + true + } fn service_power(&self)->Result{Ok(())} fn drain_rings(&mut self)->Result{Ok(())} fn check_hangs(&mut self,_done:&mut Completions)->Result{Ok(())} @@ -127,31 +294,52 @@ def item(declaration): } // The wire encoder/transport is replaced only at this boundary. The production wrapper, // dependency selection and error isolation execute verbatim above and below it. - fn publish_prefix_into(&mut self,job:&Arc,_flight:&mut Flight,visible:&mut bool)->Result{ + fn publish_prefix_into(&mut self,job:&Arc,_flight:&mut Flight,visible:&mut bool,pending_rings:&mut u8)->Result{ self.attempted.push(job.id); let stage=self.stages.pop_front().expect("unexpected hardware publication"); *visible=stage.visible; if stage.result.is_ok(){ - assert!(stage.visible);job.progress.sent.fetch_add(1,Ordering::Relaxed); - self.engine.flights.push(Flight::new(job.clone())); + assert!(stage.visible); + let idx=job.progress.sent.fetch_add(1,Ordering::Relaxed); + let mut fl=Flight::new(job.clone()); + match command(job,idx){ + Some(Command::Render(r))=>{ + *pending_rings|=(1<<(Channel::Fs as u8))|(1<<(Channel::Ta as u8)); + fl.renders=1; + fl.heavy_render=r.is_heavy_ta(); + fl.initbm=!self.pools.can_pipeline(&job.vm); + } + _=>{*pending_rings|=1<<(Channel::Compute as u8);fl.computes=1;} + } + self.engine.flights.push(fl); } stage.result } + __FLUSH_DOORBELLS__ __PUBLISH_PREFIX__ __PUBLISH__ + __PUBLISH_CHECKED__ } -fn job(id:u32,render:bool,sent:u32,dependency:Result)->Arc{ - Arc::new(Job{id,vm:Vm{status:Status(AtomicU32::new(0)),slot:id}, - queue:Queue{turn:AtomicU64::new(0),priority:0}, +fn mk_vm(slot:u32)->Arc{Arc::new(Vm{id:u64::from(slot),status:Status(AtomicU32::new(0)),slot,msaa:AtomicBool::new(false)})} +fn job_on_vm_mode(id:u32,vm:Arc,render:bool,heavy:bool,sent:u32,dependency:Result)->Arc{ + Arc::new(Job{id,vm, + queue:Queue::new(0,0), progress:Progress{sent:AtomicU32::new(sent),count:sent+1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(())};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false)}) + commands:vec![if render{Command::Render(RenderCommand{heavy_ta:heavy,msaa:false})}else{Command::Compute(ComputeCommand{query_access:true,rt:false})};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) +} +fn job_on_vm(id:u32,vm:Arc,render:bool,sent:u32,dependency:Result)->Arc{ + job_on_vm_mode(id,vm,render,false,sent,dependency) +} +fn job(id:u32,render:bool,sent:u32,dependency:Result)->Arc{ + job_on_vm(id,mk_vm(id),render,sent,dependency) } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ - Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)}},objects:Checks,recovery:Recovery{error:None,publication_wait_deadline:None}, - engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false}, - slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},power:Power::default(), + Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)},rings:vec![],ring_fail:false,checks:AtomicU32::new(0),transports:AtomicU32::new(0)},objects:Checks,recovery:Recovery{error:None,publication_wait_deadline:None}, + engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,ta_wave_wait:false,held_wait:false,handoff_avoid_pipes:0,coalesce_deadline_ns:0}, + slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None,block_pipeline_vm:None},power:Power::default(), unavailable:vec![],stages:stages.into_iter().map(|(result,visible)|Stage{result,visible}).collect(), - retained:vec![],attempted:vec![],fail_stops:0} + retained:vec![],attempted:vec![],fail_stops:0,allow_behind:false,block_render_behind:false,block_compute_behind:false, + ta_pending_calls:std::cell::Cell::new(0)} } #[cfg(test)]mod tests{ use super::*; @@ -180,6 +368,21 @@ def item(declaration): let mut f=firmware(vec![job(1,true,0,Ok(())),job(2,false,0,Ok(()))],vec![(Ok(()),true)]);f.slots.render_exhausted=true; let mut done=vec![];assert_eq!(f.publish(&mut done),Ok(()));assert_eq!(done,[(1,Err(ECANCELED))]);assert_eq!(f.attempted,[2]);assert_eq!(f.fail_stops,0); } + #[test]fn exhausted_render_pools_cancels_render_and_allows_compute(){ + let mut f=firmware(vec![job(1,true,0,Ok(())),job(2,false,0,Ok(()))],vec![(Ok(()),true)]);f.pools.exhausted=true; + let mut done=vec![];assert_eq!(f.publish(&mut done),Ok(()));assert_eq!(done,[(1,Err(ECANCELED))]); + assert_eq!(f.unavailable,[(command::RENDER,EIO)]);assert_eq!(f.attempted,[2]);assert_eq!(f.fail_stops,0); + } + #[test]fn per_vm_exhausted_render_pools_cancels_only_blocked_vm_without_stalling_compute(){ + let mut f=firmware(vec![job(1,true,0,Ok(())),job(2,false,0,Ok(()))],vec![(Ok(()),true)]); + f.pools.exhausted_vm=Some(1); + let mut done=vec![];assert_eq!(f.publish(&mut done),Ok(())); + assert_eq!(done,[(1,Err(ECANCELED))]); + assert!(f.unavailable.is_empty()); + assert!(!f.engine.chan_wait); + assert_eq!(f.recovery.publication_wait_deadline,None); + assert_eq!(f.attempted,[2]);assert_eq!(f.fail_stops,0); + } #[test]fn logical_u64_overflow_is_explicit_and_class_local(){ let mut f=firmware(vec![job(1,false,0,Ok(())),job(2,true,0,Ok(()))],vec![(Ok(()),true)]); f.engine.ordinal=u64::MAX; @@ -229,20 +432,2961 @@ def item(declaration): assert!(done.is_empty());assert!(f.attempted.is_empty());assert_eq!(f.engine.pending.len(),1);assert!(f.power.work.is_empty()); f.session.shared.sleeping.store(false,Ordering::Relaxed);assert_eq!(f.publish(&mut done),Ok(()));assert_eq!(f.attempted,[1]); } + #[test]fn batched_compute_publications_coalesce_to_one_doorbell(){ + let vm1=mk_vm(1); + let mut f=firmware( + vec![job_on_vm(1,vm1.clone(),false,0,Ok(())),job_on_vm(2,vm1.clone(),false,0,Ok(())),job_on_vm(3,vm1,false,0,Ok(()))], + vec![(Ok(()),true),(Ok(()),true),(Ok(()),true)], + ); + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish(&mut done),Ok(())); + assert_eq!(f.attempted,[1,2,3]); + assert_eq!(f.session.rings,[Channel::Compute]); + assert_eq!(f.engine.stats.grouped,2); + } + #[test]fn batched_render_publications_coalesce_in_fs_then_ta_order(){ + let vm1=mk_vm(1); + let mut f=firmware( + vec![job_on_vm(1,vm1.clone(),true,0,Ok(())),job_on_vm(2,vm1,true,0,Ok(()))], + vec![(Ok(()),true),(Ok(()),true)], + ); + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish(&mut done),Ok(())); + assert_eq!(f.attempted,[1,2]); + assert_eq!(f.session.rings,[Channel::Fs,Channel::Ta]); + assert_eq!(f.engine.stats.grouped,1); + } + #[test]fn batched_doorbell_flushes_after_later_deferral_and_fail_stops_on_ring_error(){ + let vm1=mk_vm(1); + let mut f=firmware( + vec![job_on_vm(1,vm1.clone(),false,0,Ok(())),job_on_vm(2,vm1,false,0,Ok(()))], + vec![(Ok(()),true),(Err(EAGAIN),false)], + ); + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish(&mut done),Ok(())); + assert_eq!(f.attempted,[1,2]); + assert_eq!(f.session.rings,[Channel::Compute]); + assert_eq!(f.fail_stops,0); + + let mut f=firmware(vec![job(1,false,0,Ok(()))],vec![(Ok(()),true)]); + f.session.ring_fail=true; + let mut done=vec![]; + assert_eq!(f.publish(&mut done),Err(EIO)); + assert_eq!(f.fail_stops,1); + } + #[test]fn alt_class_fallback_prefers_higher_priority_smaller_value(){ + let vm1=mk_vm(1); + let mk_prio=|id:u32,render:bool,priority:u32|Arc::new(Job{ + id,vm:vm1.clone(), + queue:Queue::new(0,priority), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, + }); + // Head render (prio 2) is blocked behind active render flight; alt-class fallback + // must select prio 2 (MEDIUM) compute ahead of prio 3 (LOW) compute. + let r_head=mk_prio(1,true,2); + let c_low=mk_prio(2,false,3); + let c_med=mk_prio(3,false,2); + let mut f=firmware(vec![r_head.clone(),c_low,c_med],vec![(Ok(()),true),(Ok(()),true)]); + f.engine.flights.push(Flight::new(r_head)); + f.allow_behind=true; + f.block_render_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[3,2]); + assert_eq!(f.engine.pending.len(),1); + } + #[test]fn alt_bypass_does_not_starve_same_vm_initbm_render(){ + let vm1=mk_vm(1); + let c_active=job_on_vm(1,vm1.clone(),false,0,Ok(())); + let r_initbm=job_on_vm(2,vm1.clone(),true,0,Ok(())); + let c_pending=job_on_vm(3,vm1.clone(),false,0,Ok(())); + c_pending.queue.turn.store(5,Ordering::Relaxed); + let mut f=firmware(vec![r_initbm,c_pending],vec![(Ok(()),true),(Ok(()),true)]); + f.engine.flights.push(Flight::new(c_active)); + f.allow_behind=true; + f.pools.block_pipeline_vm=Some(vm1.slot); + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert!(f.attempted.is_empty()); + assert_eq!(f.engine.stats.hold[0],1); + assert_eq!(f.engine.pending.len(),2); + f.engine.flights.clear(); + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[2]); + assert_eq!(f.engine.pending.len(),1); + f.engine.flights.clear(); + f.pools.block_pipeline_vm=None; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[2,3]); + } + #[test]fn hold_causes_split_hold0_by_the_gate_that_stopped_publication(){ + let vm1=mk_vm(1); + let vm2=mk_vm(2); + // One held publication pass per case: (in-flight job and kind, its flags, held job, + // host knobs) -> exactly one hold[0] of the expected cause. + let run=|flight:Arc,renders:u32,initbm:bool,doomed:bool,held:Arc, + allow_behind:bool,block_pipeline:Option,block_render:bool,expect:HoldCause, + held_wait:bool|{ + let mut f=firmware(vec![held],vec![]); + let mut fl=Flight::new(flight); + if renders==0{fl.computes=1;}else{fl.renders=renders;} + fl.initbm=initbm; + fl.doomed=doomed; + f.engine.flights.push(fl); + f.allow_behind=allow_behind; + f.pools.block_pipeline_vm=block_pipeline; + f.block_render_behind=block_render; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert!(f.attempted.is_empty(),"{:?}",expect); + assert_eq!(f.engine.stats.hold[0],1,"{:?}",expect); + let mut want=[0u64;HoldCause::COUNT]; + want[expect as usize]=1; + assert_eq!(f.engine.stats.hold_causes,want,"{:?}",expect); + // Only a hold behind the job's own VM's flights asks for the short repoll. + assert_eq!(f.engine.held_wait,held_wait,"{:?}",expect); + }; + let r=|id:u32,vm:&Arc,dep:Result|job_on_vm(id,vm.clone(),true,0,dep); + // A warm same-VM render whose allocator cannot pipeline waits for an empty engine. + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),true,Some(vm1.slot),false,HoldCause::DrainPb,true); + // A cold InitBM flight drains first. + run(r(1,&vm1,Ok(())),1,true,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainInitbm,true); + // Another VM's compute in flight: no cross-VM render/compute overlap. + run(job_on_vm(1,vm2.clone(),false,0,Ok(())),0,false,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainCross,false); + // A doomed flight drains first. + run(r(1,&vm1,Ok(())),1,false,true,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainFailed,false); + // A full light TA wave (8 renders) pauses the next light render. + run(r(1,&vm1,Ok(())),8,false,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::TaWave,true); + // Pass, flight or unit headroom. + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),true,None,true,HoldCause::Slot,true); + // A failed dependency (pick() skips jobs still waiting for one). + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Err(ECANCELED)),false,None,false,HoldCause::Dependency,false); + // Any other refusal. + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),false,None,false,HoldCause::Other,true); + // Behind another VM's render (warm cross-VM renders overlap): counted, but no short repoll. + run(r(1,&vm2,Ok(())),1,false,false,r(2,&vm1,Ok(())),false,None,false,HoldCause::Other,false); + assert_eq!(HoldCause::NAMES.len(),HoldCause::COUNT); + assert_eq!(HoldCause::Other as usize,HoldCause::COUNT-1); + } + #[test]fn alt_bypass_does_not_starve_cold_cross_vm_initbm_while_warm_overlaps(){ + let vm1=mk_vm(1); + let vm2=mk_vm(2); + let vm1_active=job_on_vm(1,vm1.clone(),false,0,Ok(())); + let vm2_cold_render=job_on_vm(2,vm2.clone(),true,0,Ok(())); + let vm1_pending=job_on_vm(3,vm1.clone(),false,0,Ok(())); + vm1_pending.queue.turn.store(5,Ordering::Relaxed); + let mut f=firmware(vec![vm2_cold_render,vm1_pending],vec![(Ok(()),true),(Ok(()),true)]); + f.engine.flights.push(Flight::new(vm1_active)); + f.allow_behind=true; + // Cold cross-VM render (requires InitBM) must drain without starvation. + f.pools.block_pipeline_vm=Some(vm2.slot); + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert!(f.attempted.is_empty()); + assert_eq!(f.engine.stats.hold[0],1); + assert_eq!(f.engine.pending.len(),2); + f.engine.flights.clear(); + assert_eq!(f.publish_checked(&mut done),Ok(())); + // Once drained, VM2's InitBM render publishes (fl.initbm=true blocks vm1_pending behind it). + assert_eq!(f.attempted,[2]); + assert_eq!(f.engine.pending.len(),1); + + // Warm cross-VM render queues directly behind another VM's active render with zero hold[0]. + let vm1_r=job_on_vm(10,vm1.clone(),true,0,Ok(())); + let vm2_warm_r=job_on_vm(11,vm2.clone(),true,0,Ok(())); + let mut fw=firmware(vec![vm2_warm_r],vec![(Ok(()),true)]); + let mut fl=Flight::new(vm1_r); + fl.renders=1; + fw.engine.flights.push(fl); + fw.allow_behind=true; + assert_eq!(fw.publish_checked(&mut done),Ok(())); + assert_eq!(fw.attempted,[11]); + assert_eq!(fw.engine.stats.hold[0],0); + + // Cross-VM non-SCS compute queues behind another VM's active compute on a disjoint pipe. + let vm1_c=job_on_vm(12,vm1.clone(),false,0,Ok(())); + let vm2_c=job_on_vm(13,vm2.clone(),false,0,Ok(())); + let mut fc=firmware(vec![vm2_c],vec![(Ok(()),true)]); + let mut flc=Flight::new(vm1_c); + flc.computes=1; + fc.engine.flights.push(flc); + fc.allow_behind=true; + assert_eq!(fc.publish_checked(&mut done),Ok(())); + assert_eq!(fc.attempted,[13]); + assert_eq!(fc.engine.stats.hold[0],0); + + // Cross-VM compute drains behind another VM's active render (no cross-VM R<->C overlap). + let vm1_r2=job_on_vm(14,vm1.clone(),true,0,Ok(())); + let vm2_c2=job_on_vm(15,vm2.clone(),false,0,Ok(())); + let mut fcr=firmware(vec![vm2_c2],vec![(Ok(()),true)]); + let mut flr=Flight::new(vm1_r2); + flr.renders=1; + fcr.engine.flights.push(flr); + fcr.allow_behind=true; + assert_eq!(fcr.publish_checked(&mut done),Ok(())); + assert!(fcr.attempted.is_empty()); + assert_eq!(fcr.engine.stats.hold[0],1); + + // Symmetrically, warm cross-VM render drains behind another VM's active compute. + let vm1_c2=job_on_vm(16,vm1,false,0,Ok(())); + let vm2_r2=job_on_vm(17,vm2,true,0,Ok(())); + let mut frc=firmware(vec![vm2_r2],vec![(Ok(()),true)]); + let mut flc2=Flight::new(vm1_c2); + flc2.computes=1; + frc.engine.flights.push(flc2); + frc.allow_behind=true; + assert_eq!(frc.publish_checked(&mut done),Ok(())); + assert!(frc.attempted.is_empty()); + assert_eq!(frc.engine.stats.hold[0],1); + } + #[test]fn alt_bypass_preserves_per_queue_fifo_order(){ + let vm1=mk_vm(1); + let q1=Queue::new(0,0); + let q2=Queue::new(1,0); + let mk_q=|id:u32,q:Arc,render:bool|Arc::new(Job{ + id,vm:vm1.clone(),queue:q, + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, + }); + // q1 has blocked render job 1 followed by compute job 2 on the SAME queue q1; + // q2 has ready compute job 3. alt-bypass must NOT jump q1's job 2 ahead of job 1, + // and must select q2's job 3 instead. + let q1_r1=mk_q(1,q1.clone(),true); + let q1_c2=mk_q(2,q1,false); + let q2_c3=mk_q(3,q2,false); + let mut f=firmware(vec![q1_r1.clone(),q1_c2,q2_c3],vec![(Ok(()),true)]); + f.engine.flights.push(Flight::new(q1_r1)); + f.allow_behind=true; + f.block_render_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[3]); + assert_eq!(f.engine.pending.len(),2); + } + #[test]fn alt_bypass_still_allows_same_vm_class_cap_overlap(){ + let vm1=mk_vm(1); + let c_active=job_on_vm(1,vm1.clone(),false,0,Ok(())); + let c_head=job_on_vm(2,vm1.clone(),false,0,Ok(())); + let r_pipelined=job_on_vm(3,vm1,true,0,Ok(())); + r_pipelined.queue.turn.store(5,Ordering::Relaxed); + let mut f=firmware(vec![c_head,r_pipelined],vec![(Ok(()),true)]); + f.engine.flights.push(Flight::new(c_active)); + f.allow_behind=true; + f.block_compute_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[3]); + assert_eq!(f.engine.pending.len(),1); + } + #[test]fn deferred_eagain_does_not_burn_queue_turn(){ + let j1=job(1,false,0,Ok(())); + let j2=job(2,false,0,Ok(())); + j1.queue.turn.store(1,Ordering::Relaxed); + j2.queue.turn.store(2,Ordering::Relaxed); + let mut f=firmware(vec![j1.clone(),j2.clone()],vec![(Err(EAGAIN),false),(Ok(()),true)]); + f.engine.turn=10; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[1]); + assert_eq!(j1.queue.turn.load(Ordering::Relaxed),1); + assert_eq!(f.engine.turn,10); + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[1,1]); + assert_eq!(j1.queue.turn.load(Ordering::Relaxed),11); + assert_eq!(f.engine.turn,11); + } + #[test]fn mixed_compute_and_render_batch_rings_compute_before_fs_and_ta(){ + let vm1=mk_vm(1); + let mut f=firmware( + vec![job_on_vm(1,vm1.clone(),true,0,Ok(())),job_on_vm(2,vm1,false,0,Ok(()))], + vec![(Ok(()),true),(Ok(()),true)], + ); + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish(&mut done),Ok(())); + assert_eq!(f.attempted,[1,2]); + assert_eq!(f.session.rings,[Channel::Compute,Channel::Fs,Channel::Ta]); + } + #[test]fn ta_wave_pacing_flushes_doorbell_at_four_passes_and_arms_ta_wave_wait(){ + // Heavy renders fill TA_WAVE_PASSES (4) and ring FS+TA immediately; pass 5 pauses. + let vm1=mk_vm(1); + let mut jobs:Vec>=(1..=5).map(|id|job_on_vm_mode(id,vm1.clone(),true,true,0,Ok(()))).collect(); + jobs.push(job_on_vm(6,vm1.clone(),false,0,Ok(()))); + let stages=vec![(Ok(()),true);5]; + let mut f=firmware(jobs,stages); + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[1,2,3,4,6]); + assert_eq!(f.session.rings,[Channel::Fs,Channel::Ta,Channel::Compute]); + assert!(f.engine.ta_wave_wait); + assert!(!f.engine.slot_wait); + assert_eq!(f.engine.pending.len(),1); + + // Light renders fill TA_WAVE_PASSES_LIGHT (8) and ring FS+TA immediately; pass 9 pauses. + let mut light_jobs:Vec>=(1..=9).map(|id|job_on_vm_mode(id,vm1.clone(),true,false,0,Ok(()))).collect(); + light_jobs.push(job_on_vm(10,vm1,false,0,Ok(()))); + let mut fl=firmware(light_jobs,vec![(Ok(()),true);9]); + fl.allow_behind=true; + assert_eq!(fl.publish_checked(&mut done),Ok(())); + assert_eq!(fl.attempted,[1,2,3,4,5,6,7,8,10]); + assert_eq!(fl.session.rings,[Channel::Fs,Channel::Ta,Channel::Compute]); + assert!(fl.engine.ta_wave_wait); + assert!(!fl.engine.slot_wait); + assert_eq!(fl.engine.pending.len(),1); + } + #[test]fn publish_checked_d64_blocked_single_queue_hoists_ta_pending_and_skips_same_queue_in_o1(){ + let vm1=mk_vm(1); + let q1=Queue::new(0,0); + let mk=|id:u32|Arc::new(Job{ + id,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT)], + dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, + }); + let pending:Vec>=(9..=68).map(mk).collect(); + let mut f=firmware(pending,vec![]); + for id in 1..=8 { + let mut fl=Flight::new(mk(id)); + fl.renders=1; + f.engine.flights.push(fl); + } + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert!(f.attempted.is_empty()); + assert!(f.engine.ta_wave_wait); + assert_eq!(f.engine.pending.len(),60); + // Hoisted ta_pending + O(1) same-queue skip reads TA stamp at most once across 60 jobs. + assert_eq!(f.ta_pending_calls.get(),1); + } + #[test]fn same_queue_independent_compute_bypasses_ta_wave_paused_render_only(){ + let vm1=mk_vm(1); + let q1=Queue::new(0,0); + let mk=|id:u32,render:bool,query_access:bool,dep:Result|Arc::new(Job{ + id,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(R_HEAVY)}else{Command::Compute(ComputeCommand{query_access,rt:false})}], + dependency:dep,terminal_marked:AtomicBool::new(false),resources:Resources, + }); + // Seed 4 active heavy TA passes so TA wave pacing is active. + let mut active_flights=Vec::new(); + for id in 1..=4 { + let mut fl=Flight::new(mk(id,true,false,Ok(()))); + fl.renders=1; + fl.heavy_render=true; + active_flights.push(fl); + } + // On q1: render 9 is TA-wave paused; independent !query_access compute 10 bypasses it. + let r9=mk(9,true,false,Ok(())); + let c10=mk(10,false,false,Ok(())); + let mut f=firmware(vec![r9,c10],vec![(Ok(()),true)]); + f.engine.flights=active_flights; + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[10]); + assert_eq!(f.engine.pending.len(),1); + assert!(f.engine.ta_wave_wait); + + // query_access compute on the same queue must NOT bypass TA-wave-paused render. + let mut f_q=firmware(vec![mk(11,true,false,Ok(())),mk(12,false,true,Ok(()))],vec![]); + for id in 1..=4 { + let mut fl=Flight::new(mk(id,true,false,Ok(()))); + fl.renders=1; + f_q.engine.flights.push(fl); + } + f_q.allow_behind=true; + assert_eq!(f_q.publish_checked(&mut done),Ok(())); + assert!(f_q.attempted.is_empty()); + + // Dependent compute (dependency Err(EAGAIN)) must NOT bypass TA-wave-paused render. + let mut f_dep=firmware(vec![mk(13,true,false,Ok(())),mk(14,false,false,Err(EAGAIN))],vec![]); + for id in 1..=4 { + let mut fl=Flight::new(mk(id,true,false,Ok(()))); + fl.renders=1; + f_dep.engine.flights.push(fl); + } + f_dep.allow_behind=true; + assert_eq!(f_dep.publish_checked(&mut done),Ok(())); + assert!(f_dep.attempted.is_empty()); + + // Later compute must NEVER jump an earlier pending compute on the same queue. + let mut f_cc=firmware( + vec![mk(15,true,false,Ok(())),mk(16,false,true,Ok(())),mk(17,false,false,Ok(()))], + vec![], + ); + for id in 1..=4 { + let mut fl=Flight::new(mk(id,true,false,Ok(()))); + fl.renders=1; + f_cc.engine.flights.push(fl); + } + f_cc.allow_behind=true; + f_cc.block_compute_behind=false; + // Job 16 is query_access (cannot bypass render 15); job 17 sits behind compute 16 so it must also wait. + assert_eq!(f_cc.publish_checked(&mut done),Ok(())); + assert!(f_cc.attempted.is_empty()); + } } +mod fence { + pub const MAX_FW_WAITS: usize = 8; + pub struct FwWait { + pub queue: std::sync::Arc, + pub last_ordinal: [Option; 2], + } +} +#[derive(Copy,Clone)]struct Order{engine:usize,sequence:u64,wait_through:[Option;2]} +struct QueueBehindJob{id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,order:Order,extra_orders:Vec,dependency:Result,resources:Resources,fw_waits:Vec} +impl QueueBehindJob{ + fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} + fn command_order(&self,index:u32)->Option{ + if !self.extra_orders.is_empty() { + self.extra_orders.get(index as usize).copied() + } else { + Some(self.order) + } + } +} +struct QueueBehindStamp{val:std::cell::Cell,reads:std::cell::Cell} +impl QueueBehindStamp{ + fn new(v:u32)->Self{Self{val:std::cell::Cell::new(v),reads:std::cell::Cell::new(0)}} + fn r32(&self,_off:usize)->Result{self.reads.set(self.reads.get()+1);Ok(self.val.get())} +} +struct QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp;2]} +struct QueueBehindGraph{render:QueueBehindRenderGraph} +impl QueueBehindGraph{fn new()->Self{Self{render:QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp::new(0),QueueBehindStamp::new(0)]}}}} +struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,heavy_render:bool,published_ns:u64,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} +struct QueueBehindEngine{ordinal:u64,draw:u64,ta_target:u32,next_compute_pipe:u8,pipe_last_vm:[Option;hw::sizes::COMPUTE_PIPES],pipe_last_used:[u64;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:u32,flights:Vec} +struct QueueBehindSlots{compute_exhausted:bool,render_exhausted:bool,compute_available:bool,pass_available:bool} +impl QueueBehindSlots{ + fn compute_exhausted(&self)->bool{self.compute_exhausted} + fn compute_exhausted_in_mask(&self,mask:u32)->bool{self.compute_exhausted||mask==0} + fn render_exhausted(&self)->bool{self.render_exhausted} + fn compute_available(&self,_n:usize)->bool{self.compute_available} + fn compute_available_in_mask(&self,_mask:u32)->bool{self.compute_available} + fn compute_available_in_mask_for_pipe(&self,mask:u32,pipe:usize)->bool{ + let allowed = if pipe == 0 { mask } else { mask & !((1u32 << hw::sizes::PIPE1_COMPUTE_START) - 1) }; + self.compute_available && allowed != 0 + } + fn compute_available_for_pipe(&self,n:usize,pipe:usize)->bool{ + self.compute_available && (pipe == 0 || n > hw::sizes::PIPE1_COMPUTE_START) + } + fn pass_available(&self,_n:usize)->bool{self.pass_available} +} +mod resources { pub const BASE_COMPUTE_UNITS: usize = 2; } +struct QueueBehindPools{exhausted:bool,can_pipeline:bool,block_pipeline_vm:Option} +impl QueueBehindPools{ + fn exhausted(&self)->bool{self.exhausted} + fn can_pipeline(&self,vm:&Arc)->bool{self.can_pipeline&&self.block_pipeline_vm!=Some(vm.slot)} + fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} + fn can_pipeline_within_blocks(&self,vm:&Arc,limit:usize,_min_blocks:u32)->bool{self.can_pipeline_within(vm,limit)} + fn can_pipeline_within_blocks_mode(&self,vm:&Arc,limit:usize,min_blocks:u32,_scs:bool)->bool{self.can_pipeline_within_blocks(vm,limit,min_blocks)} + fn can_pipeline_in_mask_blocks_mode(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32,_scs:bool)->bool{self.can_pipeline(vm)} +} +struct QueueBehindHost{graph:QueueBehindGraph,engine:QueueBehindEngine,slots:QueueBehindSlots,pools:QueueBehindPools} +mod queue_behind_scope { + use super::*; + use crate::hw::sizes; + type Job = QueueBehindJob; + type Flight = QueueBehindFlight; + fn command(job:&Job,k:u32)->Option<&Command>{job.commands.get(k as usize)} + mod params { pub fn compute_flights()->usize{16} pub fn render_flights()->usize{47} } + #[allow(non_upper_case_globals)] + mod kernel { + pub mod uapi { + pub const drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS: u32 = 1 << 20; + pub const drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES: u32 = 1 << 23; + } + } + #[derive(Copy, Clone, Debug, PartialEq, Eq)] + enum BarrierType { + Stamp = 0, + Hold = 1, + } + impl BarrierType { + const fn from_stamp_only(stamp_only: bool) -> Self { + if stamp_only { Self::Stamp } else { Self::Hold } + } + } + #[derive(Copy, Clone, Debug, PartialEq, Eq)] + __WAIT_TARGET__ + __CROSS_ENGINE_BARRIER_TYPE__ + #[derive(Copy, Clone, Debug, PartialEq, Eq)] + __RENDER_BARRIER_PLAN__ + __PLAN_RENDER_BARRIERS__ + __SCS_COMPUTE_CONFLICT__ + __MSAA_RENDER_CONFLICT__ + impl QueueBehindHost { + __NEEDS_ENGINE_DRAIN__ + __RENDER_CAN_PIPELINE__ + __BLOCKED_ON_SLOT_HEADROOM__ + __TA_PENDING_PASSES__ + __TA_WAVE_CAP_FOR__ + __CAN_QUEUE_BEHIND__ + __CAN_QUEUE_BEHIND_WITH_TA__ + __MSAA_MEMBER_ALLOWED__ + __WAIT_STAMP_FOR_WITH__ + __WAIT_STAMP_FOR__ + __CROSS_ENGINE_WAIT__ + __WAIT_COMPUTE_STAMPS_FOR__ + __COMPUTE_QUEUE_IS_HEAVY__ + __COMPUTE_HANDOFF_PIPE__ + __HAS_COMPUTE_PIPE_FOR_VM__ + __CHOOSE_COMPUTE_PIPE__ + } + #[test]fn timed_compute_queues_behind_same_vm_and_coexists_with_render(){ + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,0); + let mk=|id:u32,vm:Arc,queue:Arc,render:bool|Arc::new(QueueBehindJob{ + id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:true,rt:false})}], + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let j1=mk(1,vm1.clone(),q1.clone(),false); + let j2=mk(2,vm1.clone(),q1.clone(),false); + let j_other_vm=mk(3,vm2.clone(),q1.clone(),false); + let j_render=mk(4,vm1.clone(),q1.clone(),true); + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + assert!(p.can_queue_behind(&j2)); + // Cross-VM non-SCS compute queues on a disjoint compute pipe without draining. + assert!(p.can_queue_behind(&j_other_vm)); + assert!(!p.needs_engine_drain(&j_other_vm)); + assert!(p.can_queue_behind(&j_render)); + p.engine.flights[0].doomed=true; + assert!(!p.can_queue_behind(&j2)); + assert!(!p.can_queue_behind(&j_other_vm)); + p.engine.flights[0].doomed=false; + p.engine.flights[0].renders=1; + p.engine.flights[0].computes=0; + assert!(p.can_queue_behind(&j2)); + assert!(!p.can_queue_behind(&j_other_vm)); + assert!(p.needs_engine_drain(&j_other_vm)); + p.engine.flights[0].initbm=true; + assert!(!p.can_queue_behind(&j2)); + assert!(!p.can_queue_behind(&j_other_vm)); + p.engine.flights[0].initbm=false; + p.engine.flights[0].renders=0; + p.engine.flights[0].computes=1; + p.slots.compute_available=false; + assert!(!p.can_queue_behind(&j2)); + } + #[test]fn scs_compute_shares_the_compute_engine_only_with_scs_compute_of_its_vm(){ + // gpubench compute.long: a ray-query lane (vm1) beside a long-ALU lane (vm2). The + // ray-query dispatch was reported complete with its results unwritten whenever the + // other lane's compute ran with it, and its stores then faulted in its closed VM. + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,0); + let q2=Queue::new(0,0); + let mk=|id:u32,vm:Arc,queue:Arc,rt:bool|Arc::new(QueueBehindJob{ + id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt})], + order:Order{engine:command::COMPUTE,sequence:u64::from(id),wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let flight=|job:Arc,rt_compute:bool,compute_pipe:u8|QueueBehindFlight{job,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe,rt_compute,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}; + let rq=mk(1,vm1.clone(),q1.clone(),true); + let rq_next=mk(2,vm1.clone(),q1.clone(),true); + let rq_post=mk(3,vm1.clone(),q1.clone(),false); + let alu=mk(4,vm2.clone(),q2.clone(),false); + let rq_vm2=mk(5,vm2.clone(),q2.clone(),true); + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![flight(rq.clone(),true,0)]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Behind an SCS flight only SCS compute of its own VM queues, so one ray-query + // queue keeps pipelining. + assert!(p.can_queue_behind(&rq_next)); + assert!(!p.needs_engine_drain(&rq_next)); + for j in [&alu,&rq_post,&rq_vm2] { + assert!(!p.can_queue_behind(j)); + assert!(p.needs_engine_drain(j)); + } + // SCS compute does not start beside non-SCS compute on any pipe; non-SCS cross-VM + // compute runs concurrently on disjoint compute pipes without draining. + for pipe in [0u8,1] { + p.engine.flights=vec![flight(alu.clone(),false,pipe)]; + assert!(!p.can_queue_behind(&rq)); + assert!(p.needs_engine_drain(&rq)); + assert!(p.can_queue_behind(&rq_post)); + assert!(!p.needs_engine_drain(&rq_post)); + p.engine.flights=vec![flight(rq_post.clone(),false,pipe)]; + assert!(!p.can_queue_behind(&rq)); + assert!(p.needs_engine_drain(&rq)); + } + // A render flight of its own VM does not hold it; once SCS compute is gone, the rest + // overlaps as before. + let mut render=flight(mk(6,vm1.clone(),q1.clone(),false),false,0); + render.computes=0; + render.renders=1; + p.engine.flights=vec![render]; + assert!(!p.needs_engine_drain(&rq)); + assert!(p.can_queue_behind(&rq)); + p.engine.flights=vec![flight(rq_post.clone(),false,0)]; + assert!(p.can_queue_behind(&rq_post)); + assert!(!p.needs_engine_drain(&rq_post)); + assert!(p.can_queue_behind(&alu)); + assert!(!p.needs_engine_drain(&alu)); + } + #[test]fn compute_query_access_waits_for_timed_predecessor_unless_no_query_access(){ + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,0); + let q2=Queue::new(0,0); + let mk=|id:u32,queue:Arc,query_access:bool,wait_vdm:Option,wait_cdm:Option|Arc::new(QueueBehindJob{ + id,vm:vm1.clone(),queue, + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access,rt:false})], + order:Order{engine:command::COMPUTE,sequence:u64::from(id),wait_through:[wait_vdm,wait_cdm]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let timed=mk(1,q1.clone(),true,None,None); + let query_copy=mk(2,q1.clone(),true,None,Some(1)); + let no_query=mk(2,q1.clone(),false,None,Some(1)); + let no_barrier=mk(2,q1.clone(),true,None,None); + let other_queue=mk(2,q2.clone(),true,None,Some(1)); + let p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + assert!(!p.can_queue_behind(&query_copy)); + assert!(p.can_queue_behind(&no_query)); + assert!(p.can_queue_behind(&no_barrier)); + assert!(p.can_queue_behind(&other_queue)); + // Cross-engine render timestamp predecessor also blocks query_access compute. + let timed_render=Arc::new(QueueBehindJob{ + id:1,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT)], + order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let pr=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + assert!(!pr.can_queue_behind(&mk(2,q1.clone(),true,Some(1),None))); + assert!(pr.can_queue_behind(&mk(2,q1.clone(),false,Some(1),None))); + assert!(pr.can_queue_behind(&mk(2,q1.clone(),true,None,None))); + } + #[test]fn render_queues_behind_same_vm_and_coexists_with_compute_while_blocking_initbm(){ + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,0); + let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ + id,vm,queue:q1.clone(),progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:true,rt:false})}], + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let r1=mk(1,vm1.clone(),true); + let r2=mk(2,vm1.clone(),true); + let r_other_vm=mk(3,vm2.clone(),true); + let c1=mk(4,vm1.clone(),false); + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + assert!(p.can_queue_behind(&r2)); + // Warm cross-VM render queues behind healthy non-InitBM render; cold InitBM VM drains. + assert!(p.can_queue_behind(&r_other_vm)); + p.pools.block_pipeline_vm=Some(vm2.slot); + assert!(!p.can_queue_behind(&r_other_vm)); + assert!(p.needs_engine_drain(&r_other_vm)); + p.pools.block_pipeline_vm=None; + assert!(p.can_queue_behind(&c1)); + p.engine.flights[0].initbm=true; + assert!(!p.can_queue_behind(&r2)); + assert!(!p.can_queue_behind(&r_other_vm)); + assert!(!p.can_queue_behind(&c1)); + p.engine.flights[0].initbm=false; + p.pools.can_pipeline=false; + assert!(!p.can_queue_behind(&r2)); + assert!(p.can_queue_behind(&c1)); + p.pools.can_pipeline=true; + p.slots.pass_available=false; + assert!(!p.can_queue_behind(&r2)); + p.slots.pass_available=true; + p.engine.flights[0].recovery_suspect=true; + assert!(!p.can_queue_behind(&r2)); + assert!(!p.can_queue_behind(&c1)); + } + #[test]fn cross_vm_render_compute_overlap_matrix(){ + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,0); + let q2=Queue::new(0,0); + let mk=|id:u32,vm:Arc,queue:Arc,render:bool|Arc::new(QueueBehindJob{ + id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let vm1_r=mk(1,vm1.clone(),q1.clone(),true); + let vm1_c=mk(2,vm1.clone(),q1.clone(),false); + let vm2_r=mk(3,vm2.clone(),q2.clone(),true); + let vm2_c=mk(4,vm2.clone(),q2.clone(),false); + let mk_flight=|job:Arc,c:u32,r:u32|QueueBehindFlight{ + job,group:vec![],first:0,count:1,computes:c,renders:r,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0, + target:if c!=0{0x100}else{0},cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a}, + fs_target:if r!=0{0x200}else{0},initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }; + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![mk_flight(vm1_r.clone(),0,1)]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Active VM1 Render: same-VM R & C allowed; cross-VM R allowed; cross-VM C blocked + drains. + assert!(p.can_queue_behind(&vm1_r) && !p.needs_engine_drain(&vm1_r)); + assert!(p.can_queue_behind(&vm1_c) && !p.needs_engine_drain(&vm1_c)); + assert!(p.can_queue_behind(&vm2_r) && !p.needs_engine_drain(&vm2_r)); + assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); + // Active VM1 Compute: same-VM R & C allowed; cross-VM non-SCS C allowed on a disjoint + // pipe; cross-VM R blocked + drains. + p.engine.flights=vec![mk_flight(vm1_c.clone(),1,0)]; + assert!(p.can_queue_behind(&vm1_r) && !p.needs_engine_drain(&vm1_r)); + assert!(p.can_queue_behind(&vm1_c) && !p.needs_engine_drain(&vm1_c)); + assert!(p.can_queue_behind(&vm2_c) && !p.needs_engine_drain(&vm2_c)); + assert!(!p.can_queue_behind(&vm2_r) && p.needs_engine_drain(&vm2_r)); + // Mixed active VM1 Render + VM1 Compute: both cross-VM R and cross-VM C blocked + drain. + p.engine.flights=vec![mk_flight(vm1_r.clone(),0,1),mk_flight(vm1_c.clone(),1,0)]; + assert!(!p.can_queue_behind(&vm2_r) && p.needs_engine_drain(&vm2_r)); + assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); + // Once a VM renders multisampled, none of its renders shares the TA/FS queues with + // another VM's render, in either order; its own renders still queue behind each other. + let mk_msaa=|id:u32,vm:Arc,queue:Arc|Arc::new(QueueBehindJob{ + id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_MSAA)], + order:Order{engine:command::RENDER,sequence:u64::from(id),wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let vm2_ms=mk_msaa(6,vm2.clone(),q2.clone()); + // Neither VM has rendered multisampled: only a multisampled render is held. + p.engine.flights=vec![mk_flight(vm1_r.clone(),0,1)]; + assert!(p.can_queue_behind(&vm2_r) && !p.needs_engine_drain(&vm2_r)); + assert!(!p.can_queue_behind(&vm2_ms) && p.needs_engine_drain(&vm2_ms)); + // VM1 has rendered multisampled: VM2's single-sampled render is held behind any VM1 + // render flight, VM1's own renders are not. + vm1.note_msaa_render(); + let vm1_ms=mk_msaa(5,vm1.clone(),q1.clone()); + assert!(p.can_queue_behind(&vm1_r) && !p.needs_engine_drain(&vm1_r)); + assert!(p.can_queue_behind(&vm1_ms) && !p.needs_engine_drain(&vm1_ms)); + assert!(!p.can_queue_behind(&vm2_r) && p.needs_engine_drain(&vm2_r)); + assert!(!p.can_queue_behind(&vm2_ms) && p.needs_engine_drain(&vm2_ms)); + // ...and VM1's single-sampled render is held behind any VM2 render flight. + p.engine.flights=vec![mk_flight(vm2_r.clone(),0,1)]; + assert!(!p.can_queue_behind(&vm1_r) && p.needs_engine_drain(&vm1_r)); + assert!(p.can_queue_behind(&vm2_r) && !p.needs_engine_drain(&vm2_r)); + // Compute flights carry no render: the existing cross-VM compute rule applies. + p.engine.flights=vec![mk_flight(vm2_c.clone(),1,0)]; + assert!(!p.can_queue_behind(&vm1_ms) && p.needs_engine_drain(&vm1_ms)); + assert!(p.can_queue_behind(&vm2_r) && !p.needs_engine_drain(&vm2_r)); + assert!(p.msaa_member_allowed(&vm1,&R_MSAA)); + } + #[test]fn render_fold_members_obey_cross_vm_msaa_rule(){ + // The same-submit fold and the cross-job horizon fold ask msaa_member_allowed() for + // every candidate member (source-order asserts above): a single-sampled lead of an + // unmarked VM may be admitted beside another VM's render, but a multisampled member + // after it splits the same-submit fold and declines the horizon fold. + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); + let q2=Queue::new(0,0); + let lead=Arc::new(QueueBehindJob{ + id:1,vm:vm1.clone(),queue:Queue::new(0,0),progress:Progress{sent:AtomicU32::new(0),count:2,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT),Command::Render(R_MSAA)], + order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let other=Arc::new(QueueBehindJob{ + id:2,vm:vm2.clone(),queue:q2,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT)], + order:Order{engine:command::RENDER,sequence:2,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let in_flight=QueueBehindFlight{ + job:other,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0, + target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a}, + fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }; + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![in_flight]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // The lead (command 0) is admitted; the multisampled member (command 1) is refused. + assert!(p.can_queue_behind(&lead) && !p.needs_engine_drain(&lead)); + assert!(p.msaa_member_allowed(&vm1,&R_LIGHT)); + assert!(!p.msaa_member_allowed(&vm1,&R_MSAA)); + // Once VM2 is marked, no member of VM1 may join beside it. + vm2.note_msaa_render(); + assert!(!p.msaa_member_allowed(&vm1,&R_LIGHT)); + assert!(!p.can_queue_behind(&lead) && p.needs_engine_drain(&lead)); + // With nothing of another VM in flight every member may join. + p.engine.flights.clear(); + assert!(p.msaa_member_allowed(&vm1,&R_MSAA)); + assert!(!vm1.renders_msaa()); + } + #[test]fn cross_engine_wait_resolves_barriers_and_skips_no_barrier_or_retired(){ + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,0); + let q2=Queue::new(0,0); + let mk=|id:u32,queue:Arc,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ + id,vm:vm1.clone(),queue, + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let r1=mk(1,q1.clone(),true,1,[None,None]); + let c1=mk(2,q1.clone(),false,1,[Some(1),None]); + let c_nobarrier=mk(3,q1.clone(),false,2,[None,None]); + let r2_after_c1=mk(4,q1.clone(),true,2,[Some(1),Some(1)]); + let c_other_q=mk(5,q2.clone(),false,1,[None,None]); + let p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![ + QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + ]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Same-queue FS -> CDM barrier resolves render's fs_target; CDM -> TA resolves compute's target. + assert_eq!(p.cross_engine_wait(&c1,0,command::RENDER),Ok(Some(WaitTarget{stamp:0x500,initbm:false}))); + assert_eq!(p.cross_engine_wait(&r2_after_c1,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x700,initbm:false}))); + // No-barrier / independent-queue submits emit no cross-engine barrier. + assert_eq!(p.cross_engine_wait(&c_nobarrier,0,command::RENDER),Ok(None)); + assert_eq!(p.cross_engine_wait(&c_other_q,0,command::RENDER),Ok(None)); + // Already-retired cross-engine prefix emits no barrier. + q1.completed[command::RENDER].store(1,Ordering::Release); + assert_eq!(p.cross_engine_wait(&c1,0,command::RENDER),Ok(None)); + // Multi-command same-job compute flight resolves non-first member's exact cstamp + // and defers with EAGAIN if an unretired predecessor is missing. + let multi_c=Arc::new(QueueBehindJob{ + id:6,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:3,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false});3], + order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, + extra_orders:vec![ + Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, + Order{engine:command::COMPUTE,sequence:2,wait_through:[None,None]}, + Order{engine:command::COMPUTE,sequence:3,wait_through:[None,None]}, + ], + dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let r_wait_c2=mk(7,q1.clone(),true,3,[None,Some(2)]); + let r_wait_c3=mk(8,q1.clone(),true,4,[None,Some(3)]); + let r_wait_missing=mk(9,q1.clone(),true,5,[None,Some(99)]); + let mut cstamp=[0u32;16]; + cstamp[0]=0x100;cstamp[1]=0x200;cstamp[2]=0x300; + let pm=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:3,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![ + QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + ]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + assert_eq!(pm.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); + assert_eq!(pm.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x300,initbm:false}))); + assert_eq!(pm.cross_engine_wait(&r_wait_missing,0,command::COMPUTE),Err(EAGAIN)); + } + #[test]fn cross_engine_barrier_keeps_hold_when_producer_or_consumer_carries_initbm(){ + // Healthy same-VM non-InitBM handoffs downgrade to BarrierType::Stamp (type 0). + assert_eq!(cross_engine_barrier_type(false, false), BarrierType::Stamp); + // Any InitBM on either producer (including FS -> CDM) or consumer keeps BarrierType::Hold. + assert_eq!(cross_engine_barrier_type(true, false), BarrierType::Hold); + assert_eq!(cross_engine_barrier_type(false, true), BarrierType::Hold); + assert_eq!(cross_engine_barrier_type(true, true), BarrierType::Hold); + + // Verify wait_stamp_for_with / cross_engine_wait propagate producer flight.initbm. + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,0); + let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ + id,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let r_initbm=mk(1,true,1,[None,None]); + let c_after_r=mk(2,false,1,[Some(1),None]); + let r_after_r=mk(3,true,2,[Some(1),None]); + let host=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{ + job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0, + cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x900;a},fs_target:0x900, + initbm:true,has_timestamps:false,doomed:false,recovery_suspect:false, + }]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + let fs2c = host.cross_engine_wait(&c_after_r, 0, command::RENDER).unwrap().unwrap(); + assert_eq!(fs2c, WaitTarget { stamp: 0x900, initbm: true }); + assert_eq!(cross_engine_barrier_type(fs2c.initbm, false), BarrierType::Hold); + let r2r = host.wait_stamp_for(&r_after_r, command::RENDER, Some(1)).unwrap().unwrap(); + assert_eq!(r2r, WaitTarget { stamp: 0x900, initbm: true }); + assert_eq!(cross_engine_barrier_type(r2r.initbm, false), BarrierType::Hold); + } + #[test]fn publish_checked_uses_transport_without_repeating_session_check(){ + let mut fw=firmware(vec![job(1,false,0,Ok(()))],vec![(Ok(()),true)]); + let mut done=vec![]; + fw.publish_checked(&mut done).unwrap(); + assert_eq!(fw.session.checks.load(Ordering::Relaxed),0); + assert_eq!(fw.session.transports.load(Ordering::Relaxed),1); + let mut fw2=firmware(vec![job(2,false,0,Ok(()))],vec![(Ok(()),true)]); + fw2.publish(&mut done).unwrap(); + assert_eq!(fw2.session.checks.load(Ordering::Relaxed),1); + assert_eq!(fw2.session.transports.load(Ordering::Relaxed),1); + } + #[test]fn multi_queue_concurrent_compute_and_render_on_same_vm(){ + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let q_comp=Queue::new(0,2); + let q_rend=Queue::new(0,2); + let c_job=Arc::new(QueueBehindJob{ + id:1,vm:vm1.clone(),queue:q_comp.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], + order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let r_job=Arc::new(QueueBehindJob{ + id:2,vm:vm1.clone(),queue:q_rend.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT)], + order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:0,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{ + job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Queue 1 render queues directly behind Queue 0 compute on the same VM with no cross-engine barrier. + assert!(p.can_queue_behind(&r_job)); + assert_eq!(p.cross_engine_wait(&r_job,0,command::COMPUTE),Ok(None)); + // Symmetrically, Queue 0 compute queues directly behind Queue 1 render on the same VM. + p.engine.flights[0]=QueueBehindFlight{ + job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }; + assert!(p.can_queue_behind(&c_job)); + assert_eq!(p.cross_engine_wait(&c_job,0,command::RENDER),Ok(None)); + } + #[test]fn cross_engine_wait_and_compute_flight_cap_account_for_batched_horizon_members(){ + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,2); + let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ + id,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let c1=mk(1,false,1,[None,None]); + let c2=mk(2,false,2,[None,None]); + let c3=mk(3,false,3,[None,None]); + let r_wait_c2=mk(4,true,1,[None,Some(2)]); + let r_wait_c3=mk(5,true,2,[None,Some(3)]); + let c4=mk(6,false,4,[None,None]); + let mut cstamp=[0u32;16]; + cstamp[0]=0x100;cstamp[1]=0x200;cstamp[2]=0x300; + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:3,draw:0,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{ + job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + assert_eq!(p.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); + assert_eq!(p.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x300,initbm:false}))); + // Active computes sum flight.computes: 16 batched computes saturates compute_flights(). + assert!(p.can_queue_behind(&c4)); + p.engine.flights[0].computes=16; + assert!(!p.can_queue_behind(&c4)); + } + #[test]fn multi_pass_render_flight_wait_stamp_and_render_cap(){ + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,2); + let multi=Arc::new(QueueBehindJob{ + id:1,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:3,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT),Command::Render(R_LIGHT),Command::Render(R_LIGHT)], + order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, + extra_orders:vec![ + Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, + Order{engine:command::RENDER,sequence:2,wait_through:[Some(1),None]}, + Order{engine:command::RENDER,sequence:3,wait_through:[Some(2),None]}, + ], + dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let next_r=Arc::new(QueueBehindJob{ + id:2,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT)], + order:Order{engine:command::RENDER,sequence:4,wait_through:[Some(3),None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let mut r_fs=[0u32;16]; + r_fs[0]=0x100;r_fs[1]=0x200;r_fs[2]=0x300; + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:0,draw:3,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{ + job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Lookup into published multi-pass render flight resolves interior and tail passes. + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(1)),Ok(Some(WaitTarget{stamp:0x100,initbm:false}))); + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(2)),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(3)),Ok(Some(WaitTarget{stamp:0x300,initbm:false}))); + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(4)),Err(EAGAIN)); + // Lookup against an in-progress same-batch flight resolves earlier pass before publish. + let mut cur_fs=[0u32;16]; + cur_fs[0]=0x400; + let cur=QueueBehindFlight{ + job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }; + assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); + // Cross-job render horizon flight resolves folded flight.group member stamps too. + let r_fold_a=Arc::new(QueueBehindJob{ + id:10,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT)], + order:Order{engine:command::RENDER,sequence:5,wait_through:[Some(4),None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let r_fold_b=Arc::new(QueueBehindJob{ + id:11,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT)], + order:Order{engine:command::RENDER,sequence:6,wait_through:[Some(5),None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let mut grp_fs=[0u32;16]; + grp_fs[0]=0x400;grp_fs[1]=0x500;grp_fs[2]=0x600; + let cur_grp=QueueBehindFlight{ + job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }; + assert_eq!(p.wait_stamp_for_with(&r_fold_b,command::RENDER,Some(4),Some(&cur_grp)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); + assert_eq!(p.wait_stamp_for_with(&r_fold_b,command::RENDER,Some(5),Some(&cur_grp)),Ok(Some(WaitTarget{stamp:0x500,initbm:false}))); + assert_eq!(p.wait_stamp_for_with(&r_fold_b,command::RENDER,Some(6),Some(&cur_grp)),Ok(Some(WaitTarget{stamp:0x600,initbm:false}))); + // Active renders sum flight.renders: 44 passes (4x11-pass postfx) still pipelines + // behind once TA has finished, while 47 batched renders saturates render_flights(). + assert!(p.can_queue_behind(&next_r)); + p.engine.flights[0].renders=44; + assert!(p.can_queue_behind(&next_r)); + p.engine.flights[0].renders=47; + assert!(!p.can_queue_behind(&next_r)); + } + #[test]fn ta_pending_passes_paces_unfinished_ta_waves_without_throttling_finished_ta(){ + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,2); + let mk=|id:u32,heavy:bool|Arc::new(QueueBehindJob{ + id,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(RenderCommand{heavy_ta:heavy,msaa:false})], + order:Order{engine:command::RENDER,sequence:u64::from(id),wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let r_live=mk(1,false); + let next_light=mk(2,false); + let next_heavy=mk(3,true); + let mut r_ta=[0u32;16]; + for i in 0..8 { + r_ta[i]=(i as u32 + 1)*0x100; + } + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:0,draw:8,ta_target:0x800,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{ + job:r_live,group:vec![],first:0,count:8,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16], + r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x800, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Below TA_WAVE_PASSES (3 < 4): zero WC fw_stamp reads. + assert_eq!(p.ta_pending_passes(),3); + assert_eq!(p.graph.render.fw_stamp[0].reads.get(),0); + assert!(p.can_queue_behind(&next_light)); + assert!(p.can_queue_behind(&next_heavy)); + // 4 unfinished TA passes: heavy render pauses at 4, light render keeps pipelining up to 8. + p.engine.flights[0].renders=4; + assert_eq!(p.ta_pending_passes(),4); + assert!(p.graph.render.fw_stamp[0].reads.get()>0); + assert!(!p.can_queue_behind(&next_heavy)); + assert!(p.can_queue_behind(&next_light)); + // Heavy active flight also enforces conservative cap 4 on light followers. + p.engine.flights[0].heavy_render=true; + assert!(!p.can_queue_behind(&next_light)); + p.engine.flights[0].heavy_render=false; + // 8 unfinished light TA passes pauses light renders until TA advances. + p.engine.flights[0].renders=8; + assert_eq!(p.ta_pending_passes(),8); + assert!(!p.can_queue_behind(&next_light)); + // Once pass 0 finishes TA (obs=0x100) while FS is still running, ta_pending drops to 7. + p.graph.render.fw_stamp[0].val.set(0x100); + assert_eq!(p.ta_pending_passes(),7); + assert!(p.can_queue_behind(&next_light)); + // Even with 16 active FS passes, finished TA (obs=0x800) leaves single-pass pipelining unthrottled. + p.graph.render.fw_stamp[0].val.set(0x800); + p.engine.flights[0].renders=16; + assert_eq!(p.ta_pending_passes(),0); + assert!(p.can_queue_behind(&next_light)); + assert!(p.can_queue_behind(&next_heavy)); + } + #[test]fn slot_wait_arms_only_for_same_vm_slot_or_flight_headroom_blocks(){ + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,0); + let mk=|id:u32,vm:Arc,render:bool,dep:Result,query_access:bool,wait:[Option;2]|Arc::new(QueueBehindJob{ + id,vm,queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access,rt:false})}], + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:wait}, + extra_orders:vec![],dependency:dep,resources:Resources,fw_waits:vec![], + }); + let r_live=mk(1,vm1.clone(),true,Ok(()),false,[None,None]); + let r_same=mk(2,vm1.clone(),true,Ok(()),false,[None,None]); + let r_cross_vm=mk(3,vm2.clone(),true,Ok(()),false,[None,None]); + let r_ext_fence=mk(4,vm1.clone(),true,Err(EAGAIN),false,[None,None]); + let c_ts_wait=mk(5,vm1.clone(),false,Ok(()),true,[Some(1),None]); + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{ + job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16], + r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x100;a},fs_target:0x100, + initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, + }]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Not blocked on slots when pass_available is true and render_flights has headroom. + assert!(!p.blocked_on_slot_headroom(&r_same)); + // Waiting on CPU timestamp publish (query_access) is NOT a slot-headroom block. + assert!(!p.can_queue_behind(&c_ts_wait)); + assert!(!p.blocked_on_slot_headroom(&c_ts_wait)); + // Render pass slot exhaustion IS a slot-headroom block for ready same-VM and warm cross-VM renders... + p.slots.pass_available=false; + assert!(p.blocked_on_slot_headroom(&r_same)); + assert!(p.blocked_on_slot_headroom(&r_cross_vm)); + // ...but NOT for cold InitBM cross-VM, external-fence, or live-InitBM jobs. + p.pools.block_pipeline_vm=Some(vm2.slot); + assert!(!p.blocked_on_slot_headroom(&r_cross_vm)); + p.pools.block_pipeline_vm=None; + assert!(!p.blocked_on_slot_headroom(&r_ext_fence)); + p.pools.can_pipeline=false; + assert!(!p.blocked_on_slot_headroom(&r_same)); + p.pools.can_pipeline=true; + p.engine.flights[0].initbm=true; + assert!(!p.blocked_on_slot_headroom(&r_same)); + p.engine.flights[0].initbm=false; + // Render flight cap (47) also counts as a slot-headroom block. + p.slots.pass_available=true; + p.engine.flights[0].renders=47; + assert!(p.blocked_on_slot_headroom(&r_same)); + + // End-to-end publish_checked: cold InitBM cross-VM drain leaves slot_wait=false; + // warm render slot block sets slot_wait=true. + let v1=mk_vm(1); + let v2=mk_vm(2); + let mut fc=firmware(vec![job_on_vm(2,v2.clone(),true,0,Ok(()))],vec![]); + fc.engine.flights.push(super::Flight::new(job_on_vm(1,v1.clone(),true,0,Ok(())))); + fc.allow_behind=true; + fc.pools.block_pipeline_vm=Some(v2.slot); + let mut done=vec![]; + assert_eq!(fc.publish_checked(&mut done),Ok(())); + assert!(!fc.engine.slot_wait); + + let mut fs=firmware(vec![job_on_vm(2,v1.clone(),true,0,Ok(()))],vec![]); + fs.engine.flights.push(super::Flight::new(job_on_vm(1,v1,true,0,Ok(())))); + fs.allow_behind=true; + fs.block_render_behind=true; + assert_eq!(fs.publish_checked(&mut done),Ok(())); + assert!(fs.engine.slot_wait); + } + #[test]fn staged_render_barriers_split_ta_and_fs_compute_and_render_waits(){ + const FRAG: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; + const STAGED: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; + const NO_C1: [Option; sizes::COMPUTE_PIPES] = [None; sizes::COMPUTE_PIPES]; + const NO_C: [[Option; sizes::COMPUTE_PIPES]; 2] = [NO_C1; 2]; + let c8 = |a: Option, b: Option| -> [Option; sizes::COMPUTE_PIPES] { + let mut arr = [None; sizes::COMPUTE_PIPES]; + arr[0] = a; + arr[1] = b; + arr + }; + // 1. Cold InitBM / empty render pipe (`class_behind = false`): zero render barriers, + // compute->FS-only wait routes directly to fs_compute_barrier. + assert_eq!( + plan_render_barriers(STAGED, false, true, 0, None, None, [NO_C1, c8(Some(0x700), None)], false), + RenderBarrierPlan { + early: false, + ta_prev_wait: false, + ta_fs_wait: None, + fs_render_wait: None, + ta_compute_wait: NO_C1, + fs_compute_wait: c8(Some(0x700), None), + } + ); + // 2. Independent multi-pass render (`fs_wait_render = None`, e.g. compress.bw array / + // render.shadow or already-retired predecessor): overlaps early while keeping + // TA(N-1)->TA(N) `prev_barrier` on the shared PB/UMA epoch, with ZERO FS->TA and + // ZERO FS->FS barriers (only own_barrier on FS). + for flags in [0u32, FRAG, STAGED] { + assert_eq!( + plan_render_barriers(flags, true, true, 0x200, None, None, NO_C, false), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: None, + fs_render_wait: None, + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, + } + ); + } + // 3. Same compute target on TA and FS: only TA waits (FS is ordered via own_barrier); + // shared-PB TA->TA `prev_barrier` is kept and dependent FS wait on 0x200 emits fs_dep. + assert_eq!( + plan_render_barriers( + STAGED, + true, + true, + 0x200, + Some(0x200), + None, + [c8(Some(0x700), None), c8(Some(0x700), None)], + false, + ), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: None, + fs_render_wait: Some(0x200), + ta_compute_wait: c8(Some(0x700), None), + fs_compute_wait: NO_C1, + } + ); + // 4. Different compute targets on TA (0x600) vs FS (0x700) with no FS render dep: + // TA waits on prev_ta and 0x600, FS waits on 0x700, zero FS->FS render barriers. + assert_eq!( + plan_render_barriers( + STAGED, + true, + true, + 0x200, + None, + None, + [c8(Some(0x600), None), c8(Some(0x700), None)], + false, + ), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: None, + fs_render_wait: None, + ta_compute_wait: c8(Some(0x600), None), + fs_compute_wait: c8(Some(0x700), None), + } + ); + // 4b. Two-pipe compute waits deduplicate per pipe independently: pipe 0 shared by TA+FS + // (0x600) stays on TA only, while pipe 1 FS-only wait (0x700) routes to FS pipe 1. + assert_eq!( + plan_render_barriers( + STAGED, + true, + true, + 0x200, + None, + None, + [c8(Some(0x600), None), c8(Some(0x600), Some(0x700))], + false, + ), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: None, + fs_render_wait: None, + ta_compute_wait: c8(Some(0x600), None), + fs_compute_wait: c8(None, Some(0x700)), + } + ); + // 5. Staged render whose TA waits on an older in-flight FS (0x100 != prev_fs 0x200) + // while FS depends on 0x200: TA waits on prev_ta and 0x100, FS waits on 0x200. + assert_eq!( + plan_render_barriers( + STAGED, + true, + true, + 0x200, + Some(0x200), + Some(0x100), + NO_C, + false, + ), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: Some(0x100), + fs_render_wait: Some(0x200), + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, + } + ); + // 6. Staged render where TA and FS wait on the same older in-flight FS (0x100): + // TA still waits on prev_ta for the shared PB, and TA wait dominates FS wait via + // own_barrier so fs_render_wait is omitted. + assert_eq!( + plan_render_barriers( + STAGED, + true, + true, + 0x200, + Some(0x100), + Some(0x100), + NO_C, + false, + ), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: Some(0x100), + fs_render_wait: None, + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, + } + ); + // 7. Staged render whose TA explicitly waits on the newest in-flight FS (0x200 == prev_fs): + // no early overlap; TA waits on 0x200 directly (which dominates prev_ta) and omits both + // prev_barrier and fs_dep. + assert_eq!( + plan_render_barriers( + STAGED, + true, + true, + 0x200, + Some(0x200), + Some(0x200), + NO_C, + false, + ), + RenderBarrierPlan { + early: false, + ta_prev_wait: false, + ta_fs_wait: Some(0x200), + fs_render_wait: None, + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, + } + ); + // 8. Dependent FRAGMENT_BARRIERS render (e.g. render.postfx): TA runs early with + // shared-PB prev_barrier; FS waits on exact fs_wait_render (0x200). + assert_eq!( + plan_render_barriers( + FRAG, + true, + true, + 0x200, + Some(0x200), + None, + [c8(Some(0x700), None), c8(Some(0x700), None)], + false, + ), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: None, + fs_render_wait: Some(0x200), + ta_compute_wait: c8(Some(0x700), None), + fs_compute_wait: NO_C1, + } + ); + // 9. Legacy dependent render (flags = 0, fs_wait_render = Some(0x200)): + // TA waits on 0x200 (FS->TA, dominating prev_ta); prev_barrier and fs_dep omitted. + assert_eq!( + plan_render_barriers(0, true, true, 0x200, Some(0x200), None, NO_C, false), + RenderBarrierPlan { + early: false, + ta_prev_wait: false, + ta_fs_wait: Some(0x200), + fs_render_wait: None, + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, + } + ); + // 10. Legacy dependent render waiting on an older FS (0x100 != prev_fs 0x200): + // TA still needs prev_barrier on the shared PB in addition to ta_fs_wait(0x100). + assert_eq!( + plan_render_barriers(0, true, true, 0x200, Some(0x100), None, NO_C, false), + RenderBarrierPlan { + early: false, + ta_prev_wait: true, + ta_fs_wait: Some(0x100), + fs_render_wait: None, + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, + } + ); + // 11. Conservative `early_tiling = false` serializes TA behind prev_fs even when + // fs_wait_render is None, dominating prev_ta and omitting fs_dep. + assert_eq!( + plan_render_barriers(FRAG, true, false, 0x200, None, None, NO_C, false), + RenderBarrierPlan { + early: false, + ta_prev_wait: false, + ta_fs_wait: Some(0x200), + fs_render_wait: None, + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, + } + ); + // 12. Cross-VM warm render behind another VM's render (`cross_vm_prev = true`, no + // own-queue render barrier): TA runs early behind prev_ta (overlapping VM A's FS) + // for all flag styles (legacy/FRAG/STAGED) while FS ALWAYS waits on prev_fs (0x200). + for flags in [0u32, FRAG, STAGED] { + assert_eq!( + plan_render_barriers(flags, true, true, 0x200, None, None, NO_C, true), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: None, + fs_render_wait: Some(0x200), + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, + } + ); + } + // 13. Cross-VM legacy render that also has an own-queue barrier on an older FS (0x100): + // TA waits on own older FS (0x100) and prev_ta, while FS still waits on cross-VM + // prev_fs (0x200) so two VMs' FS/PB teardowns never overlap. + assert_eq!( + plan_render_barriers(0, true, true, 0x200, Some(0x100), None, NO_C, true), + RenderBarrierPlan { + early: false, + ta_prev_wait: true, + ta_fs_wait: Some(0x100), + fs_render_wait: Some(0x200), + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, + } + ); + // 14. Cross-VM with `early_tiling = false`: TA already waits on prev_fs, so fs_dep + // is dominated and omitted. + assert_eq!( + plan_render_barriers(STAGED, true, false, 0x200, None, None, NO_C, true), + RenderBarrierPlan { + early: false, + ta_prev_wait: false, + ta_fs_wait: Some(0x200), + fs_render_wait: None, + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, + } + ); + } + #[test]fn two_pipe_concurrent_compute_dispatch_and_fw_timestamp_safety(){ + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,2); + let q2=Queue::new(0,2); + let mk=|id:u32,vm:Arc,queue:Arc,seq:u64|Arc::new(QueueBehindJob{ + id,vm,queue, + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], + order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let c1=mk(1,vm1.clone(),q1.clone(),1); + let c2=mk(2,vm1.clone(),q1.clone(),2); + let c_vm2=mk(3,vm2.clone(),q2.clone(),1); + let q3=Queue::new(0,2); + let mut host=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:0,draw:0,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Empty engine starts on pipe 0. + let no_w = [None; sizes::COMPUTE_PIPES]; + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(0)); + host.engine.flights.push(QueueBehindFlight{ + job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, + cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, + has_timestamps:false,doomed:false,recovery_suspect:false, + }); + // Cold-start heavy probe: sole single-command compute flight becomes heavy at >= 180 us. + assert!(!host.compute_queue_is_heavy(&q1, 1_179_999)); + assert!(host.compute_queue_is_heavy(&q1, 1_180_000)); + // Folded multi-command light flight does not trigger the cold-start probe. + host.engine.flights[0].computes = 3; + assert!(!host.compute_queue_is_heavy(&q1, 2_000_000)); + host.engine.flights[0].computes = 1; + // Per-queue retired hardware CDM EWMA transitions cleanly at 200 us. + q1.note_compute_us(30); + assert!(!host.compute_queue_is_heavy(&q1, 1_050_000)); + q1.note_compute_us(500); + assert!(host.compute_queue_is_heavy(&q1, 1_050_000)); + q1.note_compute_us(20); + assert!(!host.compute_queue_is_heavy(&q1, 1_050_000)); + q1.compute_ewma_us.store(0, Ordering::Relaxed); + // Light single-queue barrier-free compute stays affine to its active pipe (pipe 0), + // while heavy single-queue compute and a second independent queue balance onto idle pipe 1. + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(0)); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, true), Some(1)); + assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(1)); + // Cross-VM compute leases its own disjoint pipe (never shares VM1's active pipe 0). + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, (1u32 << 24) - 1, false, false), Some(1)); + // Base-only VM2 (only units 0..2, cannot use secondary pipes) waits when pipe 0 is busy by VM1. + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, 0b11, false, false), None); + assert!(!host.has_compute_pipe_for_vm(&vm2, 0b11, false)); + // RT/SCS compute on same VM stays pinned to pipe 0; other VM RT returns None while pipe 0 busy. + assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, (1u32 << 24) - 1, true, true), Some(0)); + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, (1u32 << 24) - 1, true, true), None); + // A 2-unit base-only or SCS same-VM stays pinned to pipe 0. + assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, 0b11, false, true), Some(0)); + assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, 0b110, false, true), Some(0)); + assert!(host.can_queue_behind(&c2)); + // Add second concurrent flight on pipe 1 from VM2 (q2): VM1 stays on pipe 0 (or expands to + // pipe 2 for heavy compute, capped at MAX_VM_COMPUTE_PIPES=2), VM2 stays on pipe 1. + host.engine.flights.push(QueueBehindFlight{ + job:c_vm2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, + cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, + has_timestamps:false,doomed:false,recovery_suspect:false, + }); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(0)); + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, (1u32 << 24) - 1, false, false), Some(1)); + // Heavy VM1 picks idle pipe 2 (never VM2's active pipe 1). + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, true), Some(2)); + assert_eq!(host.choose_compute_pipe(&q3, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(2)); + // Once VM1 has 2 active pipes (0 and 2), MAX_VM_COMPUTE_PIPES=2 keeps VM1 on {0, 2}. + host.engine.flights.push(QueueBehindFlight{ + job:c2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:2,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, + cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, + has_timestamps:false,doomed:false,recovery_suspect:false, + }); + host.engine.next_compute_pipe = 2; + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, true), Some(2)); + host.engine.next_compute_pipe = 0; + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, true), Some(0)); + // Cross-VM non-SCS compute queues on disjoint pipes without draining. + assert!(host.can_queue_behind(&c_vm2)); + assert!(host.can_queue_behind(&c2)); + // When all COMPUTE_PIPES are occupied by distinct VMs, a 9th VM has no free pipe. + host.engine.flights.clear(); + for p in 0..sizes::COMPUTE_PIPES { + let vp = mk_vm((p + 10) as u32); + let qp = Queue::new(0, 2); + let jp = mk((p + 10) as u32, vp, qp, 1); + host.engine.flights.push(QueueBehindFlight{ + job:jp,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:p as u8,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, + cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, + has_timestamps:false,doomed:false,recovery_suspect:false, + }); + } + assert!(!host.can_queue_behind(&c_vm2)); + assert!(host.blocked_on_slot_headroom(&c_vm2)); + assert!(!host.needs_engine_drain(&c_vm2)); + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, (1u32 << 24) - 1, false, false), None); + // Starvation handoff: when all 8 pipes are occupied by other VMs, compute_handoff_pipe + // picks one compatible pipe (0) to drain so the remaining 7 pipes keep dispatching while + // pipe 0 drains for the waiting 9th VM. + assert_eq!(host.compute_handoff_pipe(&c_vm2), Some(0)); + host.engine.handoff_avoid_pipes = 1u32 << 0; + let vm10 = host.engine.flights[0].job.vm.clone(); + let q10 = host.engine.flights[0].job.queue.clone(); + let vm11 = host.engine.flights[1].job.vm.clone(); + let q11 = host.engine.flights[1].job.queue.clone(); + // Pipe 0 incumbent stops refilling pipe 0 while pipe 1 incumbent keeps dispatching on pipe 1. + assert_eq!(host.choose_compute_pipe(&q10, &vm10, no_w, (1u32 << 24) - 1, false, false), None); + assert_eq!(host.choose_compute_pipe(&q11, &vm11, no_w, (1u32 << 24) - 1, false, false), Some(1)); + // Base-only VM2 (only units 0..2, limited to pipe 0) waiting while extension VM1 refills + // pipe 0: avoiding pipe 0 moves VM1 onto pipe 1 while pipe 0 drains, then VM2 gets pipe 0! + host.engine.handoff_avoid_pipes = 0; + host.engine.flights.clear(); + host.engine.flights.push(QueueBehindFlight{ + job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, + cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, + has_timestamps:false,doomed:false,recovery_suspect:false, + }); + // Base-only mask 0b11 cannot use pipes 1..7, so VM2 has no pipe while VM1 holds pipe 0. + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, 0b11, false, false), None); + host.engine.handoff_avoid_pipes = 1u32 << 0; + // Extension VM1 continues dispatching on secondary pipe 1 instead of refilling pipe 0. + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(1)); + // A base-only VM1 incumbent stops refilling pipe 0 so pipe 0 drains for handoff. + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, 0b11, false, false), None); + assert!(!host.has_compute_pipe_for_vm(&vm1, 0b11, false)); + // Once pipe 0 drains (VM1 moved to pipe 1), clearing handoff_avoid_pipes gives VM2 pipe 0. + host.engine.flights[0].compute_pipe = 1; + host.engine.handoff_avoid_pipes = 0; + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, 0b11, false, false), Some(0)); + } + #[test]fn two_pipe_compute_barriers_reuse_single_pipe_and_serialize_across_both_pipes(){ + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,2); + let mk=|id:u32,seq:u64,wait_c:Option|Arc::new(QueueBehindJob{ + id,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], + order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,wait_c]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let c1=mk(1,1,None); + let c2=mk(2,2,None); + let c3=mk(3,3,Some(1)); + let c4=mk(4,4,Some(2)); + let mut host=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:2,draw:0,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![ + QueueBehindFlight{ + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100, + cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }, + QueueBehindFlight{ + job:c2,group:vec![],first:0,count:1,computes:2,renders:0,compute_pipe:1,rt_compute:false,heavy_render:false,published_ns:0,target:0x200, + cstamp:{let mut a=[0;16];a[0]=0x200;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }, + ]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Barrier-free compute resolves all None. + let mut exp1 = [None; sizes::COMPUTE_PIPES]; + exp1[0] = Some(WaitTarget{stamp:0x100,initbm:false}); + let mut exp2 = exp1; + exp2[1] = Some(WaitTarget{stamp:0x200,initbm:false}); + assert_eq!(host.wait_compute_stamps_for(&c3, None), Ok([None; sizes::COMPUTE_PIPES])); + // Waiting on seq 1 (pipe 0 only) returns [Some(0x100), None..] and reuses pipe 0 (zero c2c barrier). + let w1 = host.wait_compute_stamps_for(&c3, Some(1)).unwrap(); + assert_eq!(w1, exp1); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, w1, (1u32 << 24) - 1, false, true), Some(0)); + // Waiting on seq 2 (both pipe 0 seq 1 and pipe 1 seq 2 <= 2) returns both stamps and + // selects the least-loaded pipe (pipe 0 has 1 active vs pipe 1 has 2 -> picks pipe 0, + // so prefix_compute emits one cross-pipe c2c barrier on pipe 1's 0x200). + let w2 = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); + assert_eq!(w2, exp2); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, w2, (1u32 << 24) - 1, false, false), Some(0)); + // Unpublished seq 3 returns Err(EAGAIN). + assert_eq!(host.wait_compute_stamps_for(&c4, Some(3)), Err(EAGAIN)); + // If seq 2 retired out-of-order on pipe 1 while seq 1 is still active on pipe 0, + // compute_ooo bit 0 marks seq 2 retired so wait_compute_stamps_for(Some(2)) succeeds + // and still waits on pipe 0's active seq 1 (0x100)! + host.engine.flights.remove(1); + q1.compute_ooo.store(1u64 << 0, Ordering::Release); + assert!(q1.is_compute_retired(2)); + let w2_ooo = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); + assert_eq!(w2_ooo, exp1); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, w2_ooo, (1u32 << 24) - 1, false, true), Some(0)); + // Once contiguous completed[COMPUTE] reaches 2, wait_compute_stamps_for returns all None. + q1.completed[command::COMPUTE].store(2, Ordering::Release); + q1.compute_ooo.store(0, Ordering::Release); + assert_eq!(host.wait_compute_stamps_for(&c4, Some(2)), Ok([None; sizes::COMPUTE_PIPES])); + } + #[test]fn cross_queue_fw_waits_resolve_stamps_reuse_compute_pipe_and_guard_timestamps(){ + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let q1=Queue::new(0,2); + let q2=Queue::new(0,2); + let c1=Arc::new(QueueBehindJob{ + id:1,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], + order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let r1=Arc::new(QueueBehindJob{ + id:2,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT)], + order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let c2_wait_q1=Arc::new(QueueBehindJob{ + id:3,vm:vm1.clone(),queue:q2.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], + order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + fw_waits:vec![fence::FwWait{queue:q1.clone(),last_ordinal:[Some(1),Some(1)]}], + }); + let c2_query_wait_q1=Arc::new(QueueBehindJob{ + id:4,vm:vm1.clone(),queue:q2.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:true,rt:false})], + order:Order{engine:command::COMPUTE,sequence:2,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + fw_waits:vec![fence::FwWait{queue:q1.clone(),last_ordinal:[None,Some(1)]}], + }); + let host=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![ + QueueBehindFlight{ + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100, + cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, + }, + QueueBehindFlight{ + job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0, + cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }, + ]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Cross-queue compute wait resolves pipe 0 stamp 0x100 and keeps q2 on pipe 0 (zero c2c). + let mut exp_cw = [None; sizes::COMPUTE_PIPES]; + exp_cw[0] = Some(WaitTarget{stamp:0x100,initbm:false}); + let cw=host.wait_compute_stamps_for(&c2_wait_q1,None).unwrap(); + assert_eq!(cw,exp_cw); + assert_eq!(host.choose_compute_pipe(&q2,&vm1,cw,(1u32<<24)-1,false,false),Some(0)); + // Cross-queue render wait resolves q1's FS stamp 0x200. + assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); + // query_access compute waiting via fw_waits on a timestamped q1 flight must wait to retire; + // non-query compute queues directly behind q1 in firmware. + assert!(!host.can_queue_behind(&c2_query_wait_q1)); + assert!(host.can_queue_behind(&c2_wait_q1)); + // Once q1 retires, fw_waits resolves to no barriers. + q1.completed[command::COMPUTE].store(1,Ordering::Release); + q1.completed[command::RENDER].store(1,Ordering::Release); + assert_eq!(host.wait_compute_stamps_for(&c2_wait_q1,None),Ok([None;sizes::COMPUTE_PIPES])); + assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(None)); + } +} +#[allow(non_camel_case_types, deprecated)] +mod queue_limits_scope { + use std::sync::Arc; + #[derive(Copy, Clone, Debug, PartialEq, Eq)] + struct Error(i32); + const ENOSPC: Error = Error(28); + type Result = std::result::Result; + mod uapi { + pub const DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES: u64 = 1 << 2; + #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] + pub struct drm_asahi_queue_limits { + pub max_queues: u32, + pub max_in_flight_per_queue: u32, + pub flags: u32, + pub pad: u32, + } + } + mod hw { + pub mod sizes { + __FLIGHTS_LINE__ + __MAX_QUEUES_LINE__ + } + } + mod params { + use super::{hw, uapi}; + __QUEUE_LIMITS_FN__ + } + struct Gpu; + impl Gpu { __GPU_QUEUE_LIMITS_FN__ } + __QUEUE_CREDIT_STRUCT__ + __QUEUE_CREDIT_IMPL__ + __QUEUE_CREDIT_DROP__ + #[test] + fn queue_limits_and_independent_queues_feature_match_g16_bounds() { + let gpu = Gpu; + let limits = gpu.queue_limits().expect("G16 must expose queue_limits"); + assert_eq!(limits.max_queues, 58); + assert_eq!(limits.max_in_flight_per_queue, 32); + assert_eq!(limits.flags, 0); + assert_eq!(limits.pad, 0); + let mut features = 0u64; + if gpu.queue_limits().is_some() { + features |= uapi::DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES; + } + assert_ne!(features & uapi::DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES, 0); + } + #[test] + fn queue_credit_enforces_per_file_max_queues_without_starving_other_clients() { + let client_a = Arc::new(crate::usage::Client::new()); + let client_b = Arc::new(crate::usage::Client::new()); + let mut held_a = Vec::new(); + for i in 0..hw::sizes::MAX_QUEUES { + held_a.push(QueueCredit::acquire(&client_a).expect("credit within MAX_QUEUES")); + assert_eq!(client_a.queues(), i + 1); + } + assert_eq!(QueueCredit::acquire(&client_a).err(), Some(ENOSPC)); + assert_eq!(client_a.queues(), hw::sizes::MAX_QUEUES); + // A second DRM file (e.g. a compositor) keeps its own queue budget. + let compositor = QueueCredit::acquire(&client_b) + .expect("client A hitting MAX_QUEUES must not starve client B"); + assert_eq!(client_b.queues(), 1); + drop(held_a.pop()); + assert_eq!(client_a.queues(), hw::sizes::MAX_QUEUES - 1); + let reused = QueueCredit::acquire(&client_a).expect("dropped credit reusable"); + assert_eq!(QueueCredit::acquire(&client_a).err(), Some(ENOSPC)); + drop(compositor); + assert_eq!(client_b.queues(), 0); + drop(reused); + drop(held_a); + assert_eq!(client_a.queues(), 0); + } +} +mod compute_horizon_scope { + use super::{Error, Result, EAGAIN, now_ns}; + const ENOENT: Error = Error(2); + const ERANGE: Error = Error(34); + use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; + mod command { pub const RENDER: usize = 0; pub const COMPUTE: usize = 1; } + #[derive(Copy, Clone)] + struct Order { engine: usize, sequence: u64, wait_through: [Option; 2] } + impl Order { + fn ready(&self, completed: [u64; 2], published: [u64; 2]) -> bool { + let mut i = 0; + while i < 2 { + if let Some(last) = self.wait_through[i] { + if completed[i].max(published[i]) < last { + return false; + } + } + i += 1; + } + true + } + } + #[derive(Copy, Clone)] + enum Command { Compute(()), Render(()) } + mod fence { + use super::{Result, EAGAIN}; + pub fn check_dependencies(inputs: &[bool]) -> Result { + if inputs.iter().all(|&ready| ready) { Ok(()) } else { Err(EAGAIN) } + } + } + struct Status(AtomicU32); + impl Status { fn get(&self) -> u32 { self.0.load(Ordering::Relaxed) } } + struct Vm { status: Status } + struct Queue { + cancelled_compute: u64, + completed: [AtomicU64; 2], + published: [AtomicU64; 2], + } + impl Queue { + fn check(&self, order: &Order) -> Result { + if self.cancelled_compute != 0 && order.sequence >= self.cancelled_compute { + Err(Error(125)) + } else { + Ok(()) + } + } + } + struct Progress { sent: u32, count: u32 } + impl Progress { + fn sent(&self) -> u32 { self.sent } + fn count(&self) -> u32 { self.count } + } + struct Job { + vm: Vm, + queue: Queue, + progress: Progress, + commands: Vec, + orders: Vec, + inputs: Vec, + fw_waits: Vec<()>, + terminal_retired: AtomicBool, + } + impl Job { + __CAN_FOLD_CMD__ + __CAN_FOLD_JOB__ + __CAN_FOLD_RENDER_CMD__ + __CAN_FOLD_RENDER_JOB__ + } + #[test] + fn compute_horizon_eligibility_rejects_barriers_renders_unready_fences_and_gaps() { + let mk = |cmds: Vec, orders: Vec, inputs: Vec, cancelled: u64| Job { + vm: Vm { status: Status(AtomicU32::new(0)) }, + queue: Queue { + cancelled_compute: cancelled, + completed: [AtomicU64::new(0), AtomicU64::new(0)], + published: [AtomicU64::new(0), AtomicU64::new(0)], + }, + progress: Progress { sent: 0, count: cmds.len() as u32 }, + commands: cmds, + orders, + inputs, + fw_waits: vec![], + terminal_retired: AtomicBool::new(false), + }; + let ok_job = mk( + vec![Command::Compute(()), Command::Compute(())], + vec![ + Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, None] }, + Order { engine: command::COMPUTE, sequence: 3, wait_through: [None, None] }, + ], + vec![true], + 0, + ); + assert!(ok_job.can_fold_horizon_cmd(0, 2)); + assert!(ok_job.can_fold_horizon_cmd(1, 3)); + assert!(!ok_job.can_fold_horizon_cmd(0, 5)); + assert!(ok_job.can_fold_horizon_job(2)); + assert!(!ok_job.can_fold_horizon_job(3)); + + // Render barrier or compute barrier breaks the batch. + let r_bar = mk( + vec![Command::Compute(())], + vec![Order { engine: command::COMPUTE, sequence: 2, wait_through: [Some(1), None] }], + vec![], + 0, + ); + assert!(!r_bar.can_fold_horizon_job(2)); + let c_bar = mk( + vec![Command::Compute(())], + vec![Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, Some(1)] }], + vec![], + 0, + ); + assert!(!c_bar.can_fold_horizon_job(2)); + + // Render interleaved breaks the batch. + let mixed = mk( + vec![Command::Compute(()), Command::Render(())], + vec![ + Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, None] }, + Order { engine: command::RENDER, sequence: 1, wait_through: [None, None] }, + ], + vec![], + 0, + ); + assert!(!mixed.can_fold_horizon_job(2)); + + // Pending input fence or cancelled queue breaks the batch. + let unready = mk( + vec![Command::Compute(())], + vec![Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, None] }], + vec![false], + 0, + ); + assert!(!unready.can_fold_horizon_job(2)); + let cancelled = mk( + vec![Command::Compute(())], + vec![Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, None] }], + vec![], + 2, + ); + assert!(!cancelled.can_fold_horizon_job(2)); + let mut with_fw_wait = mk( + vec![Command::Compute(())], + vec![Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, None] }], + vec![], + 0, + ); + with_fw_wait.fw_waits.push(()); + assert!(!with_fw_wait.can_fold_horizon_cmd(0, 2)); + assert!(!with_fw_wait.can_fold_horizon_job(2)); + } + + #[test] + fn can_fold_render_cmd_accepts_same_batch_render_dep_and_rejects_unready_compute() { + let mk = |cmds: Vec, orders: Vec, inputs: Vec, pub_c: u64| Job { + vm: Vm { status: Status(AtomicU32::new(0)) }, + queue: Queue { + cancelled_compute: 0, + completed: [AtomicU64::new(0), AtomicU64::new(0)], + published: [AtomicU64::new(0), AtomicU64::new(pub_c)], + }, + progress: Progress { sent: 0, count: cmds.len() as u32 }, + commands: cmds, + orders, + inputs, + fw_waits: vec![], + terminal_retired: AtomicBool::new(false), + }; + let multi = mk( + vec![Command::Render(()), Command::Render(()), Command::Render(())], + vec![ + Order { engine: command::RENDER, sequence: 1, wait_through: [None, None] }, + Order { engine: command::RENDER, sequence: 2, wait_through: [Some(1), None] }, + Order { engine: command::RENDER, sequence: 3, wait_through: [Some(2), Some(5)] }, + ], + vec![true], + 4, + ); + // Pass 1 waits on pass 0 (not yet globally published): foldable at expected=2. + assert!(multi.can_fold_render_cmd(1, 2)); + // Wrong sequence is rejected. + assert!(!multi.can_fold_render_cmd(1, 3)); + // Pass 2 waits on unpublished compute 5 (published=4): rejected until compute 5 publishes. + assert!(!multi.can_fold_render_cmd(2, 3)); + multi.queue.published[command::COMPUTE].store(5, Ordering::Release); + assert!(multi.can_fold_render_cmd(2, 3)); + // Unready input fence blocks folding. + let unready = mk( + vec![Command::Render(()), Command::Render(())], + vec![ + Order { engine: command::RENDER, sequence: 1, wait_through: [None, None] }, + Order { engine: command::RENDER, sequence: 2, wait_through: [Some(1), None] }, + ], + vec![false], + 0, + ); + assert!(!unready.can_fold_render_cmd(1, 2)); + } + + #[test] + fn can_fold_render_horizon_job_accepts_render_only_jobs_and_rejects_mixed_or_unready() { + let mk = |cmds: Vec, orders: Vec, inputs: Vec, pub_c: u64| Job { + vm: Vm { status: Status(AtomicU32::new(0)) }, + queue: Queue { + cancelled_compute: 0, + completed: [AtomicU64::new(0), AtomicU64::new(0)], + published: [AtomicU64::new(0), AtomicU64::new(pub_c)], + }, + progress: Progress { sent: 0, count: cmds.len() as u32 }, + commands: cmds, + orders, + inputs, + fw_waits: vec![], + terminal_retired: AtomicBool::new(false), + }; + // Two-pass render job waiting on primary flight pass 1 and its own pass 2. + let r_job = mk( + vec![Command::Render(()), Command::Render(())], + vec![ + Order { engine: command::RENDER, sequence: 2, wait_through: [Some(1), None] }, + Order { engine: command::RENDER, sequence: 3, wait_through: [Some(2), Some(5)] }, + ], + vec![true], + 4, + ); + // Compute dep 5 not yet published (published=4) -> rejected. + assert!(!r_job.can_fold_render_horizon_job(2)); + r_job.queue.published[command::COMPUTE].store(5, Ordering::Release); + assert!(r_job.can_fold_render_horizon_job(2)); + // Wrong sequence is rejected. + assert!(!r_job.can_fold_render_horizon_job(3)); + // Mixed compute+render job is rejected. + let mixed = mk( + vec![Command::Render(()), Command::Compute(())], + vec![ + Order { engine: command::RENDER, sequence: 2, wait_through: [None, None] }, + Order { engine: command::COMPUTE, sequence: 1, wait_through: [None, None] }, + ], + vec![true], + 5, + ); + assert!(!mixed.can_fold_render_horizon_job(2)); + // Pending input fence is rejected. + let unready = mk( + vec![Command::Render(())], + vec![Order { engine: command::RENDER, sequence: 2, wait_through: [Some(1), None] }], + vec![false], + 5, + ); + assert!(!unready.can_fold_render_horizon_job(2)); + } + + use crate::hw::sizes; + mod recovery { + pub(crate) mod logic { + pub(crate) use crate::recovery::logic::{stamp_reached, RetiredStamps}; + } + } + mod poll { + pub fn stamp_reached(obs: u32, own: u32, _tail: u32) -> bool { obs >= own } + } + mod work { + pub mod ta { pub const TPC_BYTES: usize = 0; } + pub mod compute { + pub const fn pipe_of_event(event: u32) -> Option { + if event >= 15 && event < 15 + super::super::sizes::COMPUTE_PIPES as u32 { + Some((event - 15) as usize) + } else { + None + } + } + } + } + fn wmb() {} + struct PassBuf { + size: usize, + tpc_bytes: u64, + cleared: std::cell::Cell, + } + impl PassBuf { + fn r64(&self, _o: usize) -> Result { Ok(self.tpc_bytes) } + fn fill(&self, _o: usize, _v: u8, n: usize) -> Result { + self.cleared.set(self.cleared.get() + n); + Ok(()) + } + } + struct Pass { ta_work: PassBuf, tpc: PassBuf } + struct Resources { passes: Vec } + impl Resources { + fn render_pass(&self, k: usize) -> Result<&Pass> { + self.passes.get(k).ok_or(ENOENT) + } + } + struct RecVm { slot: u32 } + struct RecJob { vm: RecVm, resources: Resources } + struct RecClaims { pass: [u32; 16] } + struct RecFlight { + job: RecJob, + claims: RecClaims, + computes: u32, + renders: u32, + compute_pipe: u8, + target: u32, + ta_target: u32, + fs_target: u32, + cstamp: [u32; 16], + r_ta_stamp: [u32; 16], + r_fs_stamp: [u32; 16], + doomed: bool, + recovery_suspect: bool, + recovery_started_ns: u64, + gate_passed_ns: Option, + unsettled_polls: u32, + } + struct RecEngine { flights: Vec, target: [u32; sizes::COMPUTE_PIPES], ta_target: u32, fs_target: u32 } + struct RecState { last_retired: recovery::logic::RetiredStamps } + struct RecFirmware { engine: RecEngine, recovery: RecState } + fn st(ta: u32, fs: u32, c0: u32, c1: u32) -> [u32; 2 + sizes::COMPUTE_PIPES] { + let mut s = [0u32; 2 + sizes::COMPUTE_PIPES]; + s[0] = ta; + s[1] = fs; + s[2] = c0; + s[3] = c1; + s + } + impl RecFirmware { + __RECOVERY_PREPARE__ + __RECOVERY_PREPARE_SUSPECTS__ + } + #[test] + fn recovery_prepare_matches_interior_cstamp_in_batched_compute_horizon() { + let mut cstamp = [0u32; 16]; + cstamp[0] = 0x100; + cstamp[1] = 0x200; + cstamp[2] = 0x300; + let mut target = [0u32; sizes::COMPUTE_PIPES]; + target[0] = 0x300; + let mut fw = RecFirmware { + engine: RecEngine { + flights: vec![RecFlight { + job: RecJob { vm: RecVm { slot: 1 }, resources: Resources { passes: vec![] } }, + claims: RecClaims { pass: [0; 16] }, + computes: 3, + renders: 0, + compute_pipe: 0, + target: 0x300, + ta_target: 0, + fs_target: 0, + cstamp, + r_ta_stamp: [0; 16], + r_fs_stamp: [0; 16], + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, + }], + target, + ta_target: 0, + fs_target: 0, + }, + recovery: RecState { last_retired: recovery::logic::RetiredStamps::new() }, + }; + assert_eq!(fw.recovery_prepare(1, 15, 0x200, st(0, 0, 0x100, 0)), Ok(())); + assert!(fw.engine.flights[0].doomed); + assert!(fw.engine.flights[0].recovery_suspect); + assert_eq!(fw.recovery_prepare(1, 15, 0x400, st(0, 0, 0x100, 0)), Err(ENOENT)); + } + #[test] + fn recovery_prepare_matches_interior_render_stamps_and_cleans_only_unfinished_tpc() { + let mk_pass = |bytes: u64| Pass { + ta_work: PassBuf { size: 0x1000, tpc_bytes: bytes, cleared: std::cell::Cell::new(0) }, + tpc: PassBuf { size: 0x10000, tpc_bytes: 0, cleared: std::cell::Cell::new(0) }, + }; + let mut r_ta = [0u32; 16]; + let mut r_fs = [0u32; 16]; + r_ta[0] = 0x100; r_ta[1] = 0x200; r_ta[2] = 0x300; + r_fs[0] = 0x100; r_fs[1] = 0x200; r_fs[2] = 0x300; + let mut pass = [0u32; 16]; + pass[0] = 0; pass[1] = 1; pass[2] = 2; + let mut fw = RecFirmware { + engine: RecEngine { + flights: vec![RecFlight { + job: RecJob { + vm: RecVm { slot: 1 }, + resources: Resources { + passes: vec![mk_pass(0x1000), mk_pass(0x2000), mk_pass(0x3000)], + }, + }, + claims: RecClaims { pass }, + computes: 0, + renders: 3, + compute_pipe: 0, + target: 0, + ta_target: 0x300, + fs_target: 0x300, + cstamp: [0; 16], + r_ta_stamp: r_ta, + r_fs_stamp: r_fs, + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, + }], + target: [0; sizes::COMPUTE_PIPES], + ta_target: 0x300, + fs_target: 0x300, + }, + recovery: RecState { last_retired: recovery::logic::RetiredStamps::new() }, + }; + // Pass 0 TA finished (stage[0] == 0x100); interior TA target 0x200 matches and cleans + // TPC only for unfinished passes 1 and 2. + assert_eq!(fw.recovery_prepare(9, 0x70, 0x200, st(0x100, 0, 0, 0)), Ok(())); + assert!(fw.engine.flights[0].doomed); + assert_eq!(fw.engine.flights[0].job.resources.passes[0].tpc.cleared.get(), 0); + assert_eq!(fw.engine.flights[0].job.resources.passes[1].tpc.cleared.get(), 0x2000); + assert_eq!(fw.engine.flights[0].job.resources.passes[2].tpc.cleared.get(), 0x3000); + // Interior FS target 0x200 also matches; unrelated target 0x400 returns ENOENT. + assert_eq!(fw.recovery_prepare(1, 0x71, 0x200, st(0x300, 0x100, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare(1, 0x71, 0x400, st(0x300, 0x100, 0, 0)), Err(ENOENT)); + } + #[test] + fn cross_vm_recovery_prepare_isolates_blame_to_faulting_vm() { + let mut r_ta = [0u32; 16]; + let mut r_fs = [0u32; 16]; + r_ta[0] = 0x100; r_fs[0] = 0x100; + let mut cstamp = [0u32; 16]; + cstamp[0] = 0x500; + let mut target = [0u32; sizes::COMPUTE_PIPES]; + target[0] = 0x500; + let mut fw = RecFirmware { + engine: RecEngine { + flights: vec![ + RecFlight { + job: RecJob { vm: RecVm { slot: 1 }, resources: Resources { passes: vec![] } }, + claims: RecClaims { pass: [0; 16] }, + computes: 0, + renders: 1, + compute_pipe: 0, + target: 0, + ta_target: 0x100, + fs_target: 0x100, + cstamp: [0; 16], + r_ta_stamp: r_ta, + r_fs_stamp: r_fs, + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, + }, + RecFlight { + job: RecJob { vm: RecVm { slot: 2 }, resources: Resources { passes: vec![] } }, + claims: RecClaims { pass: [0; 16] }, + computes: 1, + renders: 0, + compute_pipe: 0, + target: 0x500, + ta_target: 0, + fs_target: 0, + cstamp, + r_ta_stamp: [0; 16], + r_fs_stamp: [0; 16], + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, + }, + ], + target, + ta_target: 0x100, + fs_target: 0x100, + }, + recovery: RecState { last_retired: recovery::logic::RetiredStamps::new() }, + }; + // VM 1 (ASID 1) faults on FS 0x100 while VM 2 (ASID 2) has co-resident compute 0x500. + assert_eq!(fw.recovery_prepare(1, 0x71, 0x100, st(0x100, 0, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare_suspects(st(0x100, 0, 0, 0), 0x71, Some(1)), Ok(())); + assert!(fw.engine.flights[0].doomed); + assert!(fw.engine.flights[0].recovery_suspect); + // VM 2's co-resident compute is suspect-only (checked via hardware ITS ticks), NEVER doomed! + assert!(!fw.engine.flights[1].doomed); + assert!(fw.engine.flights[1].recovery_suspect); + + // Two co-resident cross-VM renders: VM 1 faults on FS 0x100 while VM 2 has live render 0x200. + let mut r2_ta = [0u32; 16]; + let mut r2_fs = [0u32; 16]; + r2_ta[0] = 0x200; r2_fs[0] = 0x200; + fw.engine.flights[0].doomed = false; + fw.engine.flights[0].recovery_suspect = false; + fw.engine.flights[1] = RecFlight { + job: RecJob { vm: RecVm { slot: 2 }, resources: Resources { passes: vec![] } }, + claims: RecClaims { pass: [0; 16] }, + computes: 0, + renders: 1, + compute_pipe: 0, + target: 0, + ta_target: 0x200, + fs_target: 0x200, + cstamp: [0; 16], + r_ta_stamp: r2_ta, + r_fs_stamp: r2_fs, + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, + }; + fw.engine.ta_target = 0x200; + fw.engine.fs_target = 0x200; + assert_eq!(fw.recovery_prepare(1, 0x71, 0x100, st(0x200, 0, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare_suspects(st(0x200, 0, 0, 0), 0x71, Some(1)), Ok(())); + assert!(fw.engine.flights[0].doomed); + assert!(!fw.engine.flights[1].doomed); + assert!(fw.engine.flights[1].recovery_suspect); + } + #[test] + fn two_pipe_compute_recovery_isolates_faulting_pipe_and_event_targets() { + // Pipe 0 (VM 1, event 15) and Pipe 1 (VM 2, event 16) both hold identical per-pipe + // stamp 0x100. Faulting event 16 dooms ONLY pipe 1 (VM 2) while pipe 0 (VM 1) stays + // un-doomed suspect-only. + let mut cs = [0u32; 16]; + cs[0] = 0x100; + let mut last_retired = recovery::logic::RetiredStamps::new(); + last_retired.push(0, 0x300); + last_retired.push(1, 0x400); + last_retired.push(sizes::COMPUTE_PIPES - 1, 0x700); + let mut target = [0u32; sizes::COMPUTE_PIPES]; + target[0] = 0x100; + target[1] = 0x100; + let mut fw = RecFirmware { + engine: RecEngine { + flights: vec![ + RecFlight { + job: RecJob { vm: RecVm { slot: 1 }, resources: Resources { passes: vec![] } }, + claims: RecClaims { pass: [0; 16] }, + computes: 1, + renders: 0, + compute_pipe: 0, + target: 0x100, + ta_target: 0, + fs_target: 0, + cstamp: cs, + r_ta_stamp: [0; 16], + r_fs_stamp: [0; 16], + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, + }, + RecFlight { + job: RecJob { vm: RecVm { slot: 2 }, resources: Resources { passes: vec![] } }, + claims: RecClaims { pass: [0; 16] }, + computes: 1, + renders: 0, + compute_pipe: 1, + target: 0x100, + ta_target: 0, + fs_target: 0, + cstamp: cs, + r_ta_stamp: [0; 16], + r_fs_stamp: [0; 16], + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, + }, + ], + target, + ta_target: 0, + fs_target: 0, + }, + recovery: RecState { last_retired }, + }; + assert_eq!(fw.recovery_prepare(1, 16, 0x100, st(0, 0, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare_suspects(st(0, 0, 0, 0), 16, Some(2)), Ok(())); + assert!(!fw.engine.flights[0].doomed); + assert!(fw.engine.flights[0].recovery_suspect); + assert!(fw.engine.flights[1].doomed); + assert!(fw.engine.flights[1].recovery_suspect); + + // If pipe 0 already finished (stage[2] == 0x100) before recovery snapshot, pipe 0 is not + // even marked recovery_suspect while pipe 1 is. + fw.engine.flights[0].recovery_suspect = false; + fw.engine.flights[1].recovery_suspect = false; + fw.engine.flights[1].doomed = false; + assert_eq!(fw.recovery_prepare_suspects(st(0, 0, 0x100, 0), 16, Some(2)), Ok(())); + assert!(!fw.engine.flights[0].recovery_suspect); + assert!(fw.engine.flights[1].recovery_suspect); + assert!(fw.engine.flights[1].doomed); + + // last_retired_target distinguishes event 15 (slot 0), event 16 (slot 1), and event 22 (slot 7). + assert_eq!(fw.recovery_prepare(1, 15, 0x300, st(0, 0, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare(1, 16, 0x400, st(0, 0, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare(1, 15 + sizes::COMPUTE_PIPES as u32 - 1, 0x700, st(0, 0, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare(1, 15, 0x400, st(0, 0, 0, 0)), Err(ENOENT)); + assert_eq!(fw.recovery_prepare(1, 16, 0x300, st(0, 0, 0, 0)), Err(ENOENT)); + } +} +mod busy_coalesce_scope { + use super::{Arc, AtomicBool, AtomicU32, Command, ComputeCommand, Order, Ordering, Progress, Queue, Recovery, RenderCommand, Result, Status, Vm}; + use crate::hw::sizes; + mod params { + pub fn compute_flights() -> usize { 23 } + pub fn render_flights() -> usize { 47 } + } + struct Resources { units: usize, scs: bool } + impl Resources { + fn compute_slot_mask(&self) -> Result { + Ok(if self.units >= 32 { u32::MAX } else { (1u32 << self.units) - 1 }) + } + fn compute_scs(&self) -> bool { self.scs } + fn render_scs(&self) -> bool { self.scs } + } + struct Job { + vm: Arc, + queue: Arc, + progress: Progress, + commands: Vec, + orders: Vec, + fw_waits: Vec<()>, + resources: Resources, + is_long: bool, + foldable: bool, + } + impl Job { + fn long(&self) -> bool { self.is_long } + fn command_order(&self, idx: u32) -> Option { self.orders.get(idx as usize).copied() } + fn can_fold_horizon_cmd(&self, idx: u32, expected: u64) -> bool { + self.foldable + && self.orders.get(idx as usize).is_some_and(|o| o.engine == crate::command::COMPUTE && o.sequence == expected && o.wait_through == [None, None]) + } + fn can_fold_horizon_job(&self, first: u64) -> bool { + self.foldable + && self.orders.iter().enumerate().all(|(i, o)| o.engine == crate::command::COMPUTE && o.sequence == first + i as u64 && o.wait_through == [None, None]) + } + fn can_fold_render_cmd(&self, idx: u32, expected: u64) -> bool { + self.foldable + && self.orders.get(idx as usize).is_some_and(|o| o.engine == crate::command::RENDER && o.sequence == expected) + } + fn can_fold_render_horizon_job(&self, first: u64) -> bool { + self.foldable + && self.orders.iter().enumerate().all(|(i, o)| o.engine == crate::command::RENDER && o.sequence == first + i as u64) + } + } + fn command(job: &Job, k: u32) -> Option<&Command> { job.commands.get(k as usize) } + struct Flight { + job: Arc, + computes: u32, + renders: u32, + compute_pipe: u8, + published_ns: u64, + doomed: bool, + recovery_suspect: bool, + initbm: bool, + heavy_render: bool, + } + struct Engine { + flights: Vec, + pending: Vec>, + frozen: bool, + chan_wait: bool, + slot_wait: bool, + ta_wave_wait: bool, + held_wait: bool, + coalesce_deadline_ns: u64, + } + struct Slots { free_c: u32 } + impl Slots { + fn free_compute_in_mask_for_pipe(&self, _m: u32, _p: usize) -> u32 { self.free_c } + } + struct Host { + recovery: Recovery, + engine: Engine, + slots: Slots, + allow_behind: bool, + ta_pending: usize, + } + impl Host { + fn can_queue_behind(&self, _job: &Arc) -> bool { self.allow_behind } + fn choose_compute_pipe(&self, _q: &Arc, _vm: &Arc, _w: [Option<()>; crate::hw::sizes::COMPUTE_PIPES], _m: u32, _rt: bool, _heavy: bool) -> Option { Some(0) } + fn ta_pending_passes(&self) -> usize { self.ta_pending } + __COMPUTE_QUEUE_IS_HEAVY__ + __TA_WAVE_CAP_FOR__ + __CAN_DEFER_BUSY_COALESCE__ + __DEFER_BUSY_COALESCE__ + } + fn mk_job_mode(vm: &Arc, q: &Arc, render: bool, heavy: bool, seq: u64, wait: [Option; 2]) -> Arc { + Arc::new(Job { + vm: vm.clone(), + queue: q.clone(), + progress: Progress { sent: AtomicU32::new(0), count: 1, pending: AtomicBool::new(true) }, + commands: vec![if render { Command::Render(RenderCommand { heavy_ta: heavy, msaa: false }) } else { Command::Compute(ComputeCommand { query_access: false, rt: false }) }], + orders: vec![Order { engine: if render { crate::command::RENDER } else { crate::command::COMPUTE }, sequence: seq, wait_through: wait }], + fw_waits: vec![], + resources: Resources { units: 24, scs: false }, + is_long: false, + foldable: true, + }) + } + fn mk_job(vm: &Arc, q: &Arc, render: bool, seq: u64, wait: [Option; 2]) -> Arc { + mk_job_mode(vm, q, render, false, seq, wait) + } + #[test] + fn busy_coalesce_holds_deep_single_queue_bursts_and_never_delays_shallow_or_other_queues() { + let vm1 = Arc::new(Vm { id: 1, status: Status(AtomicU32::new(0)), slot: 1, msaa: AtomicBool::new(false) }); + let q1 = Queue::new(0, 2); + let q2 = Queue::new(0, 2); + let c1 = mk_job(&vm1, &q1, false, 1, [None, None]); + let mut h = Host { + recovery: Recovery { error: None, publication_wait_deadline: None }, + engine: Engine { + flights: vec![Flight { job: c1.clone(), computes: 1, renders: 0, compute_pipe: 0, published_ns: 90_000, doomed: false, recovery_suspect: false, initbm: false, heavy_render: false }], + pending: vec![mk_job(&vm1, &q1, false, 2, [None, None])], + frozen: false, + chan_wait: false, + slot_wait: false, + ta_wave_wait: false, + held_wait: false, + coalesce_deadline_ns: 0, + }, + slots: Slots { free_c: 20 }, + allow_behind: true, + ta_pending: 0, + }; + // d=2 (queue_active == 1 < 2): ZERO coalescing delay. + assert_eq!(h.defer_busy_coalesce(100_000), None); + + // Once queue_active >= 2, barrier-free compute holds up to 18 us and accumulates up to K=6. + h.engine.flights[0].computes = 2; + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; + assert_eq!(h.defer_busy_coalesce(100_000), Some(18)); + assert_eq!(h.engine.coalesce_deadline_ns, 118_000); + // Second job arrives 5 us later -> remaining 13 us. + h.engine.pending.push(mk_job(&vm1, &q1, false, 4, [None, None])); + assert_eq!(h.defer_busy_coalesce(105_000), Some(13)); + // Reaching K=6 pending commands flushes immediately. + for seq in 5..=8 { + h.engine.pending.push(mk_job(&vm1, &q1, false, seq, [None, None])); + } + assert_eq!(h.defer_busy_coalesce(110_000), None); + assert_eq!(h.engine.coalesce_deadline_ns, 0); + + // A job held behind the VM's own flights is never coalesced behind them. + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; + h.engine.held_wait = true; + assert_eq!(h.defer_busy_coalesce(150_000), None); + h.engine.held_wait = false; + + // Deadline expiry flushes even with 1 pending command. + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; + assert_eq!(h.defer_busy_coalesce(200_000), Some(18)); + assert_eq!(h.defer_busy_coalesce(218_000), None); + assert_eq!(h.engine.coalesce_deadline_ns, 0); + + // Another queue arriving in pending flushes immediately (no cross-queue head-of-line delay). + assert_eq!(h.defer_busy_coalesce(300_000), Some(18)); + h.engine.pending.push(mk_job(&vm1, &q2, false, 1, [None, None])); + assert_eq!(h.defer_busy_coalesce(302_000), None); + + // Barriered compute flushes immediately (0 delay). + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, Some(2)])]; + assert_eq!(h.defer_busy_coalesce(400_000), None); + + // Heavy compute queue (EWMA >= 200 us) bypasses busy coalescing so 2-pipe fanout runs immediately. + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; + q1.note_compute_us(500); + assert_eq!(h.defer_busy_coalesce(420_000), None); + q1.compute_ewma_us.store(25, Ordering::Relaxed); + assert_eq!(h.defer_busy_coalesce(420_000), Some(18)); + + // Active flight from another queue bypasses busy coalescing immediately (multi-queue/async_cr). + let r_other = mk_job(&vm1, &q2, true, 1, [None, None]); + h.engine.flights.push(Flight { job: r_other, computes: 0, renders: 1, compute_pipe: 0, published_ns: 410_000, doomed: false, recovery_suspect: false, initbm: false, heavy_render: false }); + assert_eq!(h.defer_busy_coalesce(425_000), None); + h.engine.flights.pop(); + + // Light render with queue_active == 2 and ta_pending == 2 (wave_cap 8 -> ta_room 6) + // coalesces up to K=6 passes before flushing. + let r1 = mk_job(&vm1, &q1, true, 1, [None, None]); + h.engine.flights = vec![Flight { job: r1, computes: 0, renders: 2, compute_pipe: 0, published_ns: 490_000, doomed: false, recovery_suspect: false, initbm: false, heavy_render: false }]; + h.ta_pending = 2; + h.engine.pending = vec![mk_job(&vm1, &q1, true, 3, [Some(2), None])]; + assert_eq!(h.defer_busy_coalesce(500_000), Some(18)); + for seq in 4..=7 { + h.engine.pending.push(mk_job(&vm1, &q1, true, seq, [Some(seq - 1), None])); + assert_eq!(h.defer_busy_coalesce(502_000), Some(16)); + } + h.engine.pending.push(mk_job(&vm1, &q1, true, 8, [Some(7), None])); + assert_eq!(h.defer_busy_coalesce(505_000), None); + + // Heavy render keeps conservative wave_cap 4 (ta_room == 2): holds 1 pass, flushes at 2. + h.engine.pending = vec![mk_job_mode(&vm1, &q1, true, true, 3, [Some(2), None])]; + assert_eq!(h.defer_busy_coalesce(600_000), Some(18)); + h.engine.pending.push(mk_job_mode(&vm1, &q1, true, true, 4, [Some(3), None])); + assert_eq!(h.defer_busy_coalesce(605_000), None); + } +} +// Production fold loops and publication prologue of publish_prefix_body, verbatim, around mock +// slots, waits and prefix_render: what they accept, refuse and mark is production behaviour. +mod msaa_fold_scope { + use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; + #[derive(Copy,Clone,Debug,PartialEq,Eq)] struct Error(i32); + const EINVAL: Error = Error(22); const EAGAIN: Error = Error(11); const EIO: Error = Error(5); + type Result = std::result::Result; + #[derive(Copy,Clone)] struct Gfp; const GFP_NOWAIT: Gfp = Gfp; + mod sizes { + pub const QUEUE_CAP: u32 = 256; pub const TA_WAVE_PASSES: usize = 4; pub const TA_WAVE_PASSES_LIGHT: usize = 8; + pub const HORIZON_JOBS: u32 = 8; pub const MAX_RENDER_RING_ENTRIES: usize = 5; + } + mod params { pub fn early_tiling() -> bool { true } } + #[allow(non_upper_case_globals)] + mod kernel { pub mod uapi { pub const drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES: u32 = 1 << 23; } } + mod super_vm { pub(super) type VmState = super::Vm; } + #[derive(Copy,Clone)] struct RenderCmd { flags: u32, samples: u16 } + #[derive(Copy,Clone)] struct RenderCommand { cmd: RenderCmd, heavy_ta: bool } + impl RenderCommand { + fn is_heavy_ta(&self) -> bool { self.heavy_ta } + __IS_MULTISAMPLED__ + } + const LIGHT: RenderCommand = RenderCommand { cmd: RenderCmd { flags: 0, samples: 1 }, heavy_ta: false }; + const MSAA: RenderCommand = RenderCommand { cmd: RenderCmd { flags: 0, samples: 4 }, heavy_ta: false }; + #[derive(Copy,Clone)] enum Command { Render(RenderCommand), #[allow(dead_code)] Compute } + struct Geometry; + impl Geometry { fn new_for(_c: &RenderCmd, _heap: u64, _clusters: u32, _generation: u32) -> Self { Geometry } } + struct Binding; impl Binding { fn mark_binding_published(&self) -> Result { Ok(()) } } + struct Vm { id: u64, renders_msaa: AtomicBool, vm: Binding } + impl Vm { + __RENDERS_MSAA__ + __NOTE_MSAA_RENDER__ + } + fn vm(id: u64) -> Arc { Arc::new(Vm { id, renders_msaa: AtomicBool::new(false), vm: Binding }) } + struct Queue; + #[derive(Copy,Clone)] struct Order { sequence: u64, wait_through: [Option; 2], ta_wait_through: [Option; 2] } + struct Progress { count: u32 } impl Progress { fn count(&self) -> u32 { self.count } } + struct Resources; + impl Resources { + fn render_scs(&self) -> bool { false } + fn pb_owner_arena(&self, _k: usize) -> u32 { 0 } + fn pb_uma_lease(&self, _k: usize) -> u32 { 0 } + } + struct Job { id: u32, vm: Arc, queue: Arc, commands: Vec, first_seq: u64, progress: Progress, resources: Resources } + impl Job { + fn long(&self) -> bool { false } + fn command_order(&self, k: u32) -> Option { + Some(Order { sequence: self.first_seq + u64::from(k), wait_through: [None, None], ta_wait_through: [None, None] }) + } + fn can_fold_render_cmd(&self, k: u32, seq: u64) -> bool { seq == self.first_seq + u64::from(k) } + fn can_fold_render_horizon_job(&self, first: u64) -> bool { first == self.first_seq } + } + fn job(id: u32, vm: &Arc, queue: &Arc, first_seq: u64, commands: &[RenderCommand]) -> Arc { + Arc::new(Job { id, vm: vm.clone(), queue: queue.clone(), commands: commands.iter().map(|r| Command::Render(*r)).collect(), + first_seq, progress: Progress { count: commands.len() as u32 }, resources: Resources }) + } + fn command(job: &Job, k: u32) -> Option<&Command> { job.commands.get(k as usize) } + struct Claims { pass: [u32; 48], pass_count: u32, pass_mask: u64 } + struct Group(Vec>); + impl Group { + fn len(&self) -> usize { self.0.len() } + fn reserve(&mut self, n: usize, _g: Gfp) -> std::result::Result<(), ()> { self.0.reserve(n); Ok(()) } + fn push_within_capacity(&mut self, j: Arc) -> std::result::Result<(), Arc> { self.0.push(j); Ok(()) } + } + struct Pb; impl Pb { fn check_assignment(&self, _k: usize) -> Result { Ok(()) } } + struct Flight { job: Arc, renders: u32, claims: Claims, count: usize, group: Group, msaa: bool, pb: Option, pb_slot: u32 } + fn flight(job: &Arc, renders: u32) -> Flight { + Flight { job: job.clone(), renders, claims: Claims { pass: [0; 48], pass_count: 1, pass_mask: 1 }, count: 1, + group: Group(vec![]), msaa: false, pb: Some(Pb), pb_slot: 0 } + } + __MSAA_RENDER_CONFLICT__ + struct Prefix { draw: u64, ta_head: u32, fs_head: u32, renders: u32 } + struct Cfg { num_clusters: u32, gpu_generation: u32 } + struct Slots { pass_busy: u64, publish_fails: bool } + impl Slots { + fn pick_pass_in_for(&self, _r: &Resources, _g: &Geometry, picked: u64, _vm: Option) -> Option { + (0..48).find(|k| (self.pass_busy | picked) & (1u64 << k) == 0) + } + fn verify_held(&self, _c: &Claims) -> Result { Ok(()) } + fn publish(&mut self, _c: &mut Claims) -> Result { if self.publish_fails { Err(EIO) } else { Ok(()) } } + } + struct Pools; impl Pools { fn hold_alloc(&mut self, _k: usize, _vm: &Arc, _a: u32, _l: u32) -> Result { Ok(()) } } + struct Engine { flights: Vec, pending: Vec> } + struct Host { cfg: Cfg, slots: Slots, pools: Pools, engine: Engine, prefixed: Vec<(u32, u32)> } + impl Host { + __MSAA_MEMBER_ALLOWED__ + fn recovery_pending(&self) -> Result { Ok(false) } + fn wait_compute_stamps_for(&self, _j: &Arc, _t: Option) -> Result { Ok(()) } + fn wait_stamp_for_with(&self, _j: &Arc, _c: usize, _t: Option, _f: Option<&Flight>) -> Result { Ok(()) } + #[allow(clippy::too_many_arguments)] + fn prefix_render(&mut self, job: &Arc, _r: &Resources, k: u32, cmd: &RenderCommand, _g: Geometry, + prefix: &mut Prefix, f: &mut Flight, _behind: bool, _class_behind: bool) -> Result { + self.prefixed.push((job.id, k)); + prefix.renders += 1; + prefix.draw += 1; + f.msaa |= cmd.is_multisampled(); + Ok(()) + } + /// The lead (command 0 of `job`) is already prefixed; returns the prefix's end command. + #[allow(unused_assignments, unused_variables, unused_mut)] + fn fold(&mut self, job: &Arc, f: &mut Flight, more: usize) -> Result { + let index = 0u32; + let mut end = 1u32; + let mut prefix = Prefix { draw: 1, ta_head: 0, fs_head: 0, renders: 1 }; + let (ta_read, fs_read) = (0u32, 0u32); + let (behind, class_behind) = (true, true); + let stage_prefix = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; + let mut last_seq = job.command_order(index).map(|o| o.sequence); + let ta_pending_before = 0usize; + let mut wave_heavy = false; + let mut more_renders = more; + __SAME_SUBMIT_FOLD__ + __HORIZON_FOLD__ + f.renders = prefix.renders; + Ok(end) + } + fn publish_prologue(&mut self, job: &Arc, f: &mut Flight, visible: &mut bool, fail_after: bool) -> Result { + let render = true; + __PUBLICATION_PROLOGUE__ + if fail_after { return Err(EIO); } + Ok(()) + } + } + fn host(flights: Vec, pending: Vec>) -> Host { + Host { cfg: Cfg { num_clusters: 1, gpu_generation: 16 }, slots: Slots { pass_busy: 1, publish_fails: false }, pools: Pools, + engine: Engine { flights, pending }, prefixed: vec![] } + } + #[test] fn same_submit_fold_splits_before_a_multisampled_member_beside_another_vm() { + let (vm1, vm2, q1, q2) = (vm(1), vm(2), Arc::new(Queue), Arc::new(Queue)); + let lead = job(1, &vm1, &q1, 10, &[LIGHT, LIGHT, MSAA, LIGHT]); + let other = job(2, &vm2, &q2, 1, &[LIGHT]); + // Beside another VM's render: the single-sampled member joins, the prefix ends at the + // multisampled one (command 2), which waits for its own publication. + let mut h = host(vec![flight(&other, 1)], vec![]); + let mut f = flight(&lead, 1); + assert_eq!(h.fold(&lead, &mut f, 8), Ok(2)); + assert_eq!(h.prefixed, [(1, 1)]); + assert!(!f.msaa); + // Nothing of another VM in flight: the whole submit folds. + let mut h = host(vec![], vec![]); + let mut f = flight(&lead, 1); + assert_eq!(h.fold(&lead, &mut f, 8), Ok(4)); + assert_eq!(h.prefixed, [(1, 1), (1, 2), (1, 3)]); + assert!(f.msaa); + } + #[test] fn cross_job_fold_takes_a_whole_job_or_none_of_it_beside_another_vm() { + let (vm1, vm2, q1, q2) = (vm(1), vm(2), Arc::new(Queue), Arc::new(Queue)); + let lead = job(1, &vm1, &q1, 10, &[LIGHT]); + let other = job(2, &vm2, &q2, 1, &[LIGHT]); + // A single-sampled job folds beside another VM's render. + let light = job(3, &vm1, &q1, 11, &[LIGHT, LIGHT]); + let mut h = host(vec![flight(&other, 1)], vec![lead.clone(), light.clone()]); + let mut f = flight(&lead, 1); + assert_eq!(h.fold(&lead, &mut f, 8), Ok(1)); + assert_eq!(h.prefixed, [(3, 0), (3, 1)]); + assert_eq!(f.group.len(), 1); + assert_eq!(f.renders, 3); + // A job with a multisampled member is declined whole: none of its members is prefixed. + let mixed = job(4, &vm1, &q1, 11, &[LIGHT, MSAA]); + let mut h = host(vec![flight(&other, 1)], vec![lead.clone(), mixed.clone()]); + let mut f = flight(&lead, 1); + assert_eq!(h.fold(&lead, &mut f, 8), Ok(1)); + assert!(h.prefixed.is_empty()); + assert_eq!(f.group.len(), 0); + assert_eq!(f.renders, 1); + // Without another VM in flight the same job folds. + let mut h = host(vec![], vec![lead.clone(), mixed.clone()]); + let mut f = flight(&lead, 1); + assert_eq!(h.fold(&lead, &mut f, 8), Ok(1)); + assert_eq!(h.prefixed, [(4, 0), (4, 1)]); + assert!(f.msaa); + } + #[test] fn only_a_visible_multisampled_prefix_marks_its_vm() { + let q = Arc::new(Queue); + // Refused before visibility: unpublished, the VM stays unmarked. + let v = vm(1); + let j = job(1, &v, &q, 1, &[MSAA]); + let mut h = host(vec![], vec![]); + h.slots.publish_fails = true; + let (mut f, mut visible) = (flight(&j, 1), false); + f.msaa = true; + assert_eq!(h.publish_prologue(&j, &mut f, &mut visible, false), Err(EIO)); + assert!(!visible && !v.renders_msaa()); + // Published: marked. + let mut h = host(vec![], vec![]); + let (mut f, mut visible) = (flight(&j, 1), false); + f.msaa = true; + assert_eq!(h.publish_prologue(&j, &mut f, &mut visible, false), Ok(())); + assert!(visible && v.renders_msaa()); + // Visible, then failed (uncertain, may run): marked. + let v2 = vm(2); + let j2 = job(2, &v2, &q, 1, &[MSAA]); + let mut h = host(vec![], vec![]); + let (mut f, mut visible) = (flight(&j2, 1), false); + f.msaa = true; + assert_eq!(h.publish_prologue(&j2, &mut f, &mut visible, true), Err(EIO)); + assert!(visible && v2.renders_msaa()); + // A published single-sampled prefix does not mark. + let v3 = vm(3); + let j3 = job(3, &v3, &q, 1, &[LIGHT]); + let mut h = host(vec![], vec![]); + let (mut f, mut visible) = (flight(&j3, 1), false); + assert_eq!(h.publish_prologue(&j3, &mut f, &mut visible, false), Ok(())); + assert!(visible && !v3.renders_msaa()); + let _ = (EAGAIN, EINVAL); + } +} + ''' harness = harness.replace('__LOGIC__', str(production.parent / 'recovery/logic.rs')) + +vm_src = (production.parent / 'vm.rs').read_text() +command_src = (production.parent / 'command.rs').read_text() +_same_fold = item('while more_renders > 0 && end < job.progress.count() {') +_horizon_fold = item('if end == job.progress.count() && more_renders > 0 {') +_prologue_start = source.index(' if self.recovery_pending()? {\n return Err(EAGAIN);\n }\n if render {\n f.pb.as_ref()') +_prologue_end = source.index(' let publication = (|| -> Result {', _prologue_start) +_prologue = source[_prologue_start:_prologue_end] +assert '*visible = true;' in _prologue and 'job.vm.note_msaa_render();' in _prologue +_scope_start = harness.index('mod msaa_fold_scope {') +_scope = harness[_scope_start:] +for token, text in { + '__SAME_SUBMIT_FOLD__': _same_fold, + '__HORIZON_FOLD__': _horizon_fold, + '__PUBLICATION_PROLOGUE__': _prologue, + '__IS_MULTISAMPLED__': item_in(command_src, 'pub(crate) fn is_multisampled('), + '__RENDERS_MSAA__': item_in(vm_src, 'pub(crate) fn renders_msaa('), + '__NOTE_MSAA_RENDER__': item_in(vm_src, 'pub(crate) fn note_msaa_render('), + '__MSAA_RENDER_CONFLICT__': item('fn msaa_render_conflict('), + '__MSAA_MEMBER_ALLOWED__': item('fn msaa_member_allowed('), +}.items(): + assert token in _scope, token + _scope = _scope.replace(token, text + .replace('super::recovery::', 'crate::recovery::') + .replace('super::command::', 'crate::command::') + .replace('super::vm::VmState', 'super_vm::VmState')) +harness = harness[:_scope_start] + _scope +harness = harness.replace('__USAGE__', str(production.parent.parent / 'usage.rs')) +harness = harness.replace('__FLIGHTS_LINE__', flights_line.strip()) +harness = harness.replace('__MAX_QUEUES_LINE__', max_queues_line.strip()) +harness = harness.replace('__QUEUE_LIMITS_FN__', item_in(params_src, 'pub(crate) fn queue_limits()')) +harness = harness.replace('__GPU_QUEUE_LIMITS_FN__', gpu_limits_fn) +harness = harness.replace('__QUEUE_CREDIT_STRUCT__', item_in(queue_src, 'struct QueueCredit {')) +harness = harness.replace('__QUEUE_CREDIT_IMPL__', item_in(queue_src, 'impl QueueCredit {')) +harness = harness.replace('__QUEUE_CREDIT_DROP__', item_in(queue_src, 'impl Drop for QueueCredit {')) +harness = harness.replace('__NOTE_COMPUTE_US__', item_in(queue_src, 'pub(crate) fn note_compute_us(')) +harness = harness.replace( + '__CAN_FOLD_CMD__', + item_in(job_src, 'pub(crate) fn can_fold_horizon_cmd(') + .replace('super::command::', 'command::') + .replace('super::fence::', 'fence::'), +) +harness = harness.replace( + '__CAN_FOLD_JOB__', + item_in(job_src, 'pub(crate) fn can_fold_horizon_job(') + .replace('super::command::', 'command::') + .replace('super::fence::', 'fence::'), +) +harness = harness.replace( + '__CAN_FOLD_RENDER_CMD__', + item_in(job_src, 'pub(crate) fn can_fold_render_cmd(') + .replace('super::command::', 'command::') + .replace('super::fence::', 'fence::'), +) +harness = harness.replace( + '__CAN_FOLD_RENDER_JOB__', + item_in(job_src, 'pub(crate) fn can_fold_render_horizon_job(') + .replace('super::command::', 'command::') + .replace('super::fence::', 'fence::'), +) +harness = harness.replace( + '__RECOVERY_PREPARE__', + item('pub(crate) fn recovery_prepare(') + .replace('super::recovery::', 'recovery::') + .replace('super::poll::', 'poll::'), +) +harness = harness.replace( + '__RECOVERY_PREPARE_SUSPECTS__', + item('pub(crate) fn recovery_prepare_suspects(') + .replace('super::recovery::', 'recovery::'), +) for token, declaration in { '__PUBLICATION_ERROR__': 'enum PublicationError {', '__PICK__': 'fn pick(&self)', '__UNPEND__': 'fn unpend(&mut self', + '__FLUSH_DOORBELLS__': 'fn flush_doorbells(', '__PUBLISH_PREFIX__': 'fn publish_prefix(', '__PUBLISH__': 'pub(crate) fn publish(&mut self', - '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', + '__PUBLISH_CHECKED__': 'pub(crate) fn publish_checked(&mut self', + '__NEEDS_ENGINE_DRAIN__': 'fn needs_engine_drain(', + '__RENDER_CAN_PIPELINE__': 'fn render_can_pipeline(', + '__HOLD_CAUSE__': 'enum HoldCause {', + '__HOLD_CAUSE_IMPL__': 'impl HoldCause {', + '__HOLD_CAUSE_FN__': 'fn hold_cause(', + '__NOTE_HOLD__': 'fn note_hold(', + '__BLOCKED_ON_SLOT_HEADROOM__': 'fn blocked_on_slot_headroom(', + '__DESCRIPTOR_CONTAINMENT__': 'if encode::validate_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(', + '__TA_PENDING_PASSES__': 'pub(crate) fn ta_pending_passes(', + '__TA_WAVE_CAP_FOR__': 'fn ta_wave_cap_for(', + '__ACTIVE_TA_WAVE_CAP__': 'pub(crate) fn active_ta_wave_cap(', + '__CAN_QUEUE_BEHIND__': 'fn can_queue_behind(', + '__CAN_QUEUE_BEHIND_WITH_TA__': 'fn can_queue_behind_with_ta(', + '__CAN_DEFER_BUSY_COALESCE__': 'fn can_defer_busy_coalesce(', + '__DEFER_BUSY_COALESCE__': 'pub(crate) fn defer_busy_coalesce(', + '__WAIT_STAMP_FOR_WITH__': 'fn wait_stamp_for_with(', + '__WAIT_STAMP_FOR__': 'fn wait_stamp_for(', + '__CROSS_ENGINE_WAIT__': 'fn cross_engine_wait(', + '__WAIT_COMPUTE_STAMPS_FOR__': 'fn wait_compute_stamps_for(', + '__COMPUTE_QUEUE_IS_HEAVY__': 'fn compute_queue_is_heavy(', + '__COMPUTE_HANDOFF_PIPE__': 'fn compute_handoff_pipe(', + '__HAS_COMPUTE_PIPE_FOR_VM__': 'fn has_compute_pipe_for_vm(', + '__CHOOSE_COMPUTE_PIPE__': 'fn choose_compute_pipe(', + '__SCS_COMPUTE_CONFLICT__': 'fn scs_compute_conflict(', + '__MSAA_RENDER_CONFLICT__': 'fn msaa_render_conflict(', + '__MSAA_MEMBER_ALLOWED__': 'fn msaa_member_allowed(', + '__WAIT_TARGET__': 'struct WaitTarget {', + '__CROSS_ENGINE_BARRIER_TYPE__': 'const fn cross_engine_barrier_type(', + '__RENDER_BARRIER_PLAN__': 'struct RenderBarrierPlan {', + '__PLAN_RENDER_BARRIERS__': 'fn plan_render_barriers(', }.items(): - harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::")) + harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::").replace("super::hw::", "crate::hw::").replace("super::resources::", "crate::resources::").replace("super::queue::QueueState", "crate::Queue").replace("super::vm::VmState", "crate::Vm").replace("super::fence::", "crate::fence::")) unit = output / 'publication.rs' unit.write_text(harness) log = '' @@ -255,7 +3399,7 @@ def item(declaration): if result.returncode: raise SystemExit(result.returncode) (output/'publication.json').write_text(json.dumps({ - 'passed': True, 'tests': 21, 'cpu_only': True, 'hardware_execution': False, + 'passed': True, 'tests': 70, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production publication wrapper, selection, error isolation and descriptor-error containment branch; wire encoder, descriptor failure injection and transport replaced by CPU recorders.', 'source_sha256': sha(production), }, indent=2)+'\n') diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py new file mode 100644 index 00000000000000..704e41f960058a --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py @@ -0,0 +1,633 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host-check the G16G ray-tracing command set (RENDER_RAY_QUERY, BOUNDED_AS_BUILD). + +Compiles the production g16/rt.rs, recovery/logic.rs and the TA/FS/compute encoders, plus the +command admission and engine conversion functions copied verbatim from command.rs and +engine.rs, against CPU-only stand-ins. No GPU, firmware or Mesa is involved. + +Failure modes this guards against (written before the code): + + 1. A non-RT command changes bytes: the engine's conversion of an empty ray state is not the + disabled word set, or the disabled set differs from the words G16G always wrote (the frozen + golden fixtures then cover the rest). + 2. RT words land in the wrong register record, the register counts change, a gated register + (0x1a141, render 0x017d9) is written while its gate is off, or a ray-query compute item is + not bracketed by 0x017e1 = 1 first and 0x017d9 = 1 last, or its tail is not 0x2c, as macOS + 27.2 writes them on the J773g; or a start command's SCS flag (StartCompute +0x40, StartTA + +0x60, StartFS +0x78) differs from whether the item's register list enables SCS, which + leaves a running ray-query dispatch exposed to the firmware's idle SCS teardown. + 3. The fragment window word loses bit 9; a render stage's tail word takes the auxiliary + intersection word (the M4 Pro's render programs use the scratch tail). + 4. SCS sizing differs from the M4 Pro's formula ((pages + pages/256 + 8) x cores pages), is not + rounded to whole 2-MiB rows, overflows silently, or admits a pool whose pages and freelist do + not fit an SCS pool window (E2BIG); zero cores is accepted. + 5. A render whose scratch exceeds its queue's reservation is accepted, or one within it + refused; an unmapped intersection pool or default program is accepted. + 6. The long allowance misses a ray/AS-build job, applies to plain work, re-enables a disabled + (zero) deadline, or shortens a deadline already longer than 10 s. + 7. A compute flag other than AS_BUILD is accepted; scratch alone counts as ray traversal. + 8. The feature word loses a bit or gains another than RENDER_RAY_QUERY and BOUNDED_AS_BUILD. + 9. A UMA manager image or compute descriptor reports seeds that are not whole rows inside the + freelist, a freelist (+0x1c) that does not hold its pool or is smaller than a base one, an + SCS pool's freelist other than macOS's 0x80000 records, or row words (+0x48) other than 8 + per valid row. +10. Mesa's G16G ray-query commands (layout 0x0130000060010070 on 10 cores, compute and either or + both render stages, and their QUEUE_CREATE reservations) are refused, which Mesa reports as + VK_ERROR_DEVICE_LOST; the render pools a queue creates cannot take a queue that later + reserves the other stage too; or a compute pool is created for fewer than two dispatches + where a window holds two. +""" +from common import kernel_root, output_dir, rustc, flat_bindings +import hashlib +import json +import os +import pathlib +import re +import shlex +import subprocess +import tempfile + +ROOT = kernel_root() +OUT = output_dir() +BACKEND = ROOT / 'drivers/gpu/drm/asahi/g16' +FLAT = flat_bindings() + + +def function(text, name): + marker = text.index('fn ' + name + '(') + start = text.rfind('\n', 0, marker) + 1 + at = text.index('{', marker) + depth, end = 1, at + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +def block(text, declaration): + start = text.index(declaration) + at = text.index('{', start) + depth, end = 1, at + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +command = (BACKEND / 'command.rs').read_text() +engine = (BACKEND / 'engine.rs').read_text() +admission = '\n'.join(function(command, name) for name in + ['check_intersection', 'check_render_ray', 'check_compute_ray']) +reserve = function((BACKEND / 'queue.rs').read_text(), 'reserve_render_scs') +conversion = '\n'.join(function(engine, name) for name in ['compute_rt', 'stage_rt']) +# The client address map, which bounds SCS pools (SCS_POOL_WINDOW). +client = block((BACKEND / 'hw.rs').read_text(), 'pub(crate) mod client {') +long = block(command, 'impl Command {') +for text in ('admission', 'conversion', 'long'): + globals()[text] = globals()[text].replace('super::rt::', 'rt::') + +# The feature word: the bits params.rs adds, from the real header, plus the shared +# VM_STATUS and VM_STATUS_MIRROR of file.rs. +params = (BACKEND / 'params.rs').read_text() +statement = params[params.index('params.features |='):] +statement = statement[:statement.index(';')] +names = re.findall(r'drm_asahi_feature_(DRM_ASAHI_FEATURE_\w+)', statement) +with tempfile.TemporaryDirectory(prefix='m4-rt-features-') as name: + directory = pathlib.Path(name) + source = directory / 'features.c' + header = ROOT / 'include/uapi/drm/asahi_drm.h' + source.write_text('#include \n#include ' + json.dumps(str(header)) + '\nint main(void){printf("%#llx\\n",' + '(unsigned long long)(' + ' | '.join(names + ['DRM_ASAHI_FEATURE_VM_STATUS', + 'DRM_ASAHI_FEATURE_VM_STATUS_MIRROR']) + '));return 0;}\n') + binary = directory / 'features' + subprocess.run(shlex.split(os.environ.get('CC', 'cc')) + ['-std=gnu11', '-Wall', '-Werror', '-D__user=', + '-idirafter', str(header.parents[1]), str(source), '-o', str(binary)], check=True) + features = int(subprocess.run([str(binary)], check=True, capture_output=True, text=True).stdout, 16) +assert features == 0x4001fc02, hex(features) +assert sorted(names) == sorted(['DRM_ASAHI_FEATURE_PER_COMMAND_INPUT_SYNCS', 'DRM_ASAHI_FEATURE_EXACT_PRIOR_BARRIERS', + 'DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS', 'DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS', + 'DRM_ASAHI_FEATURE_FEW_PRIMITIVES', 'DRM_ASAHI_FEATURE_RENDER_RAY_QUERY', + 'DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD']), names +print(f'feature word {features:#x} (RENDER_RAY_QUERY | BOUNDED_AS_BUILD added to G16G features)') + +harness = r''' +#![allow(dead_code, non_camel_case_types, non_snake_case, non_upper_case_globals, unused_imports)] +extern crate self as kernel; +pub mod prelude { + pub type Result = core::result::Result; + pub const EINVAL: i32 = -22; pub const E2BIG: i32 = -7; pub const EOVERFLOW: i32 = -75; +} +use prelude::*; +const ENOENT: i32 = -2; +mod uapi { include!("@FLAT@"); } +mod hw { + pub mod engine { pub const COMPUTE_SEED: u32 = 0x100; } + pub mod sizes { pub const BASE_RENDER_SLOTS: usize = 2; } + @CLIENT@ +} +mod fw { + #[path = "@BACKEND@/fw/graph.rs"] pub mod graph; + #[path = "@BACKEND@/fw/work.rs"] pub mod work; +} +#[path = "@BACKEND@/encode.rs"] mod encode; +#[path = "@BACKEND@/rt.rs"] mod rt; +#[path = "@BACKEND@/recovery/logic.rs"] mod logic; +use encode::{ComputeRt, StageRt}; +use fw::work::{compute, fs, ta}; + +mod mmu { pub struct Vm { pub mapped: Vec<(u64, u64)> } } +/// Readable mappings only; the production span rules have their own tests. +fn cover(vm: &mmu::Vm, start: u64, end: u64, _read: bool, _write: bool) -> Result { + if vm.mapped.iter().any(|&(a, b)| a <= start && end <= b) { Ok(()) } else { Err(ENOENT) } +} +struct SpanBatch; +impl SpanBatch { + fn push(&mut self, vm: &mmu::Vm, start: u64, end: u64, read: bool, write: bool) -> Result { + cover(vm, start, end, read, write) + } +} +struct Context<'a> { vm: &'a mmu::Vm, usc_base: u64, active_cores: u32, render_scs: [u16; 2] } +mod queue_test { + use super::*; + struct Config { supports_render_scs: bool } + struct Queue { cfg: Config, accepted: [u64; 2], active_cores: u32, render_scs: [u16; 2] } + const EBUSY: i32 = -16; + struct Error; + impl Error { fn from_errno(code: i32) -> i32 { code } } + impl Queue { @RESERVE@ } + + #[test] + fn reserve_scratch() { + let mut q = Queue { + cfg: Config { supports_render_scs: false }, + accepted: [0; 2], active_cores: 10, render_scs: [0; 2], + }; + let (layout, pages) = LAYOUTS[0]; + assert_eq!(q.reserve_render_scs([0, 0]), Ok(())); + for request in [[layout, 0], [0, layout]] { + assert_eq!(q.reserve_render_scs(request), Err(-95)); + assert_eq!(q.render_scs, [0, 0]); + } + q.cfg.supports_render_scs = true; + assert_eq!(q.reserve_render_scs([layout, 0]), Ok(())); + assert_eq!(q.render_scs, [pages, 0]); + q.accepted = [1, 0]; + assert_eq!(q.reserve_render_scs([0, 0]), Err(EBUSY)); + assert_eq!(q.render_scs, [pages, 0]); + } +} +pub mod bindings { pub const EOPNOTSUPP: u32 = 95; } +@ADMISSION@ +@CONVERSION@ +type KBox = Box; +struct RenderCommand { ray_query: [rt::RayQueryStage; 2], scs: rt::ScsSeeds } +struct ComputeCommand { ray: rt::ComputeRay, scs: rt::ScsSeeds, as_build: bool } +enum Command { Render(KBox), Compute(KBox) } +@LONG@ + +// Mesa's three T1 layouts: depth 112, 96 cliques, driver 40, 88 and 304 bytes. +const LAYOUTS: [(u64, u16); 3] = [(0x0028000060000070, 791), (0x0058000060010070, 827), (0x0130000060010070, 989)]; +const POOL: u64 = 0x10000; +fn tables() -> rt::IntersectionTables { + rt::IntersectionTables::new(POOL, 0x4000, 1, 112, 0x10010020000, 0x16000000000).unwrap() +} +fn ray(layout: u64) -> rt::ComputeRay { + rt::ComputeRay::new(layout, 0, 0, POOL, 0x4000, 1, 112, 0x10010020000, 0x16000000000).unwrap() +} +fn stage(layout: u64) -> rt::RayQueryStage { + rt::RayQueryStage { intersection: tables(), scratch: rt::ScratchRequest::new(layout).unwrap() } +} +fn records(w: &[u8], at: usize, count: usize) -> Vec<(u32, u64)> { + (0..count).map(|i| { + let r = &w[at + i * 12..at + i * 12 + 12]; + (u32::from_le_bytes(r[..4].try_into().unwrap()), u64::from_le_bytes(r[4..].try_into().unwrap())) + }).collect() +} +fn u16_at(w: &[u8], at: usize) -> usize { u16::from_le_bytes([w[at], w[at + 1]]) as usize } +fn u32_at(w: &[u8], at: usize) -> u32 { u32::from_le_bytes(w[at..at + 4].try_into().unwrap()) } + +#[test] +fn empty_ray_state_converts_to_the_words_g16g_always_wrote() { + assert_eq!(compute_rt(&rt::ComputeRay::NONE, 8192), ComputeRt::DISABLED); + assert_eq!(stage_rt(&rt::RayQueryStage::NONE), StageRt::DISABLED); + // Payload-free layouts and table-less commands are the same empty state. + let quiet = rt::ComputeRay::new(0x0000_0000_6000_0070, 0, 0, 0, 0, 0, 0, 0, 0).unwrap(); + assert_eq!(compute_rt(&quiet, 8192), ComputeRt::DISABLED); + assert_eq!(StageRt::DISABLED.window | 1 << 9, 0xff0200); + assert!(!encode::compute_encoder_gate()); +} + +fn compute_refs() -> encode::ComputeRefs { + let f = 0xfffffc2000000000u64; let g = 0x1000000000u64; + encode::ComputeRefs { + notifier: f + 0x600400, qinfo: f + 0x200000, user_stamp: f + 0x600648, fw_stamp: f + 0x600640, + work: f + 0x100000, work_gva: g + 0x100000, seq: f + 0x100900, descriptor_fw: 0, preempt_gva: g + 0x200000, + its: f + 0x1008c0, stats_fw: f + 0x300000, auxiliary_fw: f + 0x400000, auxiliary_gva: g + 0x400000, + context_store_gva: g + 0x500000, counter_fw: f + 0x500000, pool_state_gva: g + 0x600000, + page_list_gva: g + 0x700000, usc_base: 1 << 40, record_fw: f + 0x700000, binding_generation: 1, + uma_slot: 1, event: compute::EVENT, command_id: 1, compute_index: 0, work_818: 0, target_stamp: 0x100, submitted: 1, + } +} + +fn encode_compute(layout: &compute::Layout, rt_words: &ComputeRt) -> core::result::Result<[u8; compute::WORK_SIZE], encode::ComputeEncodeError> { + let c = uapi::drm_asahi_cmd_compute { cdm_ctrl_stream_base: 0x1000300000, cdm_ctrl_stream_end: 0x1000300200, ..Default::default() }; + let mut w = [0xa5; compute::WORK_SIZE]; let mut q = [0xa5; compute::SEQ_SIZE]; + encode::encode_compute_rt(layout, &compute_refs(), &c, &[], &[0; 2], 1, 1, 1, rt_words, &mut w, &mut q)?; + Ok(w) +} + +#[test] +fn compute_rt_words_land_in_the_25f84_register_slots_only() { + for layout in [&compute::V25G83, &compute::V26B123] { + let plain = encode_compute(layout, &ComputeRt::DISABLED).unwrap(); + assert_eq!(u16_at(&plain, 0x728), 25); + let plain_regs = records(&plain, compute::REGS, 25); + let d = compute::DESCRIPTOR; + // A base unit's descriptor: 16384 records, 8192 seeds, 16 rows x 8. + assert_eq!((u32_at(&plain, d + 0x1c), u32_at(&plain, d + 0x24), u32_at(&plain, d + 0x2c), u32_at(&plain, d + 0x48)), + (16384, 8192, 8192, 128)); + for (layout_word, pages) in LAYOUTS { + let words = compute_rt(&ray(layout_word), 28672); + let w = encode_compute(layout, &words).unwrap(); + // macOS 27.2 on the J773g: 0x017e1 = 1 first, 0x017d9 = 1 last. + assert_eq!((u16_at(&w, 0x728), u16_at(&w, 0x72a)), (27, 27 * 12)); + let got = records(&w, compute::REGS, 27); + assert_eq!((got[0], got[26]), ((0x017e1, 1), (0x017d9, 1))); + assert!(got.iter().all(|&(sel, _)| sel != 0x1a141), "gated register"); + let expect = |sel: u32| got.iter().find(|r| r.0 == sel).unwrap().1; + let mib = u64::from(pages).div_ceil(256); + assert_eq!(expect(0x101d1), u64::from(pages) | mib << 16); + assert_eq!((expect(0xd479), expect(0x1a0e9), expect(0x107a1)), (0x2c, 112, 1 << 24 | 0x60 << 16)); + assert_eq!([expect(0x1a089), expect(0x1a091), expect(0x1a059), expect(0x1a061), expect(0x1a0b9), expect(0x1a0c1)], + [POOL + 128, 0xc0003800, 0x6f00000000, 0x3feff, 0x10010020000, 0x16000000000]); + // An SCS pool's descriptor: the 0x80000-record freelist, 56 rows x 8. + assert_eq!((u32_at(&w, d + 0x1c), u32_at(&w, d + 0x24), u32_at(&w, d + 0x2c), u32_at(&w, d + 0x48)), + (0x80000, 28672, 28672, 448)); + // Between the two records the list is the plain one, only the ten RT words differ. + let rt_sels = [0x1a089, 0x1a091, 0x1a059, 0x1a061, 0x1a0b9, 0x1a0c1, 0x101d1, 0xd479, 0x1a0e9, 0x107a1]; + for (&(sel, value), &(plain_sel, plain_value)) in got[1..26].iter().zip(plain_regs.iter()) { + assert_eq!(sel, plain_sel); + assert!(value == plain_value || rt_sels.contains(&sel), "{sel:#x}"); + } + // The embedded StartCompute marks the slot as an SCS user, as macOS 27.2 does on + // every J773g compute item that opens with 0x017e1 (and on no other). + let flag = compute::SEQ_EMBEDDED + compute::START_SCS; + assert_eq!((u32_at(&plain, flag), u32_at(&w, flag)), (0, 1)); + // Nothing else moves: the register list, its count, the pool's descriptor words and + // the start command's SCS flag. + let regs = compute::REGS..compute::REGS + 27 * 12; + let pool_words = [0x1c, 0x24, 0x2c, 0x48]; + for (i, (a, b)) in plain.iter().zip(w.iter()).enumerate() { + if a != b { + assert!(regs.contains(&i) || (0x728..0x72c).contains(&i) || (flag..flag + 4).contains(&i) + || pool_words.iter().any(|&o| (d + o..d + o + 4).contains(&i)), "byte {i:#x}"); + } + } + } + // Seeds are whole rows within the freelist, which is never smaller than a base one. + for seeds in [0, 8191, 8704 + 64, 16896] { + let words = ComputeRt { seeds, ..ComputeRt::DISABLED }; + assert!(encode_compute(layout, &words).is_err(), "seeds {seeds}"); + } + assert!(encode_compute(layout, &ComputeRt { seeds: 8704, ..ComputeRt::DISABLED }).is_ok()); + assert!(encode_compute(layout, &ComputeRt { seeds: 8192, records: 8192, ..ComputeRt::DISABLED }).is_err()); + // The pool's size moves only its seed counts and row words. + let small = encode_compute(layout, &compute_rt(&ray(LAYOUTS[2].0), 18432)).unwrap(); + let large = encode_compute(layout, &compute_rt(&ray(LAYOUTS[2].0), rt::MAX_SCS_SEEDS)).unwrap(); + assert_eq!((u32_at(&small, d + 0x1c), u32_at(&small, d + 0x2c), u32_at(&small, d + 0x48)), (0x80000, 18432, 288)); + assert_eq!((u32_at(&large, d + 0x1c), u32_at(&large, d + 0x2c), u32_at(&large, d + 0x48)), (0x80000, 31744, 496)); + for (i, (a, b)) in small.iter().zip(large.iter()).enumerate() { + if a != b { assert!([0x24, 0x2c, 0x48].iter().any(|&o| (d + o..d + o + 4).contains(&i)), "byte {i:#x}"); } + } + } +} + +fn render_refs() -> (encode::RenderRefs, encode::PassRefs, uapi::drm_asahi_cmd_render) { + let f = 0xfffffc2000000000u64; let g = 0x1000000000u64; + let mut u = uapi::drm_asahi_cmd_render::default(); + u.width_px = 64; u.height_px = 64; u.layers = 1; u.samples = 1; u.utile_width_px = 32; u.utile_height_px = 32; + u.sample_size_B = 4; u.vdm_ctrl_stream_base = g + 0xa00000; u.isp_scissor_base = g + 0xb00000; + let r = encode::RenderRefs { + notifier: f + 0x800000, qinfo: [f + 0xf00000, f + 0x1000000], user_stamp: [f + 0x800620, f + 0x800630], + fw_stamp: [f + 0x4000000, f + 0x4004000], uma_mgr: [f + 0x300000; 2], uma_aux: [f + 0x300100, f + 0x300200], + uma_gpu: g + 0x6000000, pb_mgr: f + 0x3000000, scene_list: g + 0x500000, parameter_id: 1, generation: 1, + activity: [f + 0x900004, f + 0xa00008], counter: [2, 1], uma_submitted: 2, uuid: 0x123400, usc_base: 1 << 40, + ..Default::default() + }; + let p = encode::PassRefs { + ta_work: f + 0xb00000, ta_work_gva: g + 0x7000000, fs_work: f + 0xc00000, fs_work_gva: g + 0x8000000, + ta_seq: f + 0xd00000, fs_seq: f + 0xe00000, scene: f + 0x100000, tpc_gva: g + 0x200000, tpc_fw: f + 0x3200000, + tilemap_gva: g + 0x100000, heap_gva: g + 0x300000, scene_user_gva: g + 0x900000, scratch_fw: f + 0x200000, + pre_gva: [g + 0x600000, g + 0x700000, g + 0x800000], aux_gva: g + 0xb00000, ..Default::default() + }; + (r, p, u) +} + +#[test] +fn render_stage_words_land_in_the_ta_and_fs_register_slots_only() { + let (r, p, u) = render_refs(); + let geo = encode::Geometry::new(&u, p.heap_gva); + let ta_rt = |words: &StageRt, layout: &ta::Layout| { + let mut w = [0xa5; ta::WORK_SIZE]; let mut q = [0xa5; ta::SEQ_SIZE]; + encode::encode_ta_rt(layout, &r, &p, &u, &[0; 4], 1, 0x100, &geo, None, words, &mut w, &mut q); (w, q) + }; + let fs_rt = |words: &StageRt, layout: &fs::Layout| { + let mut w = [0xa5; fs::WORK_SIZE]; let mut q = [0xa5u8; fs::SEQ_SIZE]; + encode::encode_fs_rt(layout, &r, &p, &u, &[0; 4], 1, 1 << 40, 1, 0x100, &geo, words, &mut w, &mut q); (w, q) + }; + for (tl, fl) in [(&ta::V25G83, &fs::V25G83), (&ta::V26B123, &fs::V26B123)] { + let (ta_plain, taq_plain) = ta_rt(&StageRt::DISABLED, tl); + let (fs_plain, fsq_plain) = fs_rt(&StageRt::DISABLED, fl); + for (layout_word, pages) in LAYOUTS { + let mut s = stage(layout_word); + // The auxiliary word is validated, not written: the tail stays the scratch tail. + let mut wire = [0u8; 48]; + wire[0..4].copy_from_slice(&16u32.to_le_bytes()); + wire[8..16].copy_from_slice(&POOL.to_le_bytes()); wire[16..24].copy_from_slice(&0x4000u64.to_le_bytes()); + wire[24..28].copy_from_slice(&1u32.to_le_bytes()); wire[28..32].copy_from_slice(&112u32.to_le_bytes()); + wire[32..40].copy_from_slice(&0x10010020000u64.to_le_bytes()); wire[40..48].copy_from_slice(&0x16000000000u64.to_le_bytes()); + s.intersection = rt::IntersectionTables::parse(&wire).unwrap(); + let words = stage_rt(&s); + let size = u64::from(pages) | u64::from(pages).div_ceil(256) << 16; + let window = 1 << 24 | 0x60 << 16; + let ift = [POOL + 128, 0xc0003800, 0x6f00000000, 0x3feff, 0x10010020000, 0x16000000000]; + let (w, q) = ta_rt(&words, tl); + // StartTA marks the slot as an SCS user; nothing else in the sequence moves. + assert_eq!((u32_at(&taq_plain, ta::START_SCS), u32_at(&q, ta::START_SCS)), (0, 1)); + for (i, (a, b)) in taq_plain.iter().zip(q.iter()).enumerate() { + assert!(a == b || (ta::START_SCS..ta::START_SCS + 4).contains(&i), "TA seq byte {i:#x}"); + } + assert_eq!((u16_at(&w, 0x748), u16_at(&w, 0x74a)), (68, 68 * 12)); + let ta_plain_regs = records(&ta_plain, ta::REGS, 66); + let got = records(&w, ta::REGS, 68); + assert_eq!((got[0], got[67]), ((0x017e1, 1), (0x017d9, 1))); + let value = |got: &Vec<(u32, u64)>, sel: u32| got.iter().find(|r| r.0 == sel).unwrap().1; + let ta_rt_sels = [0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, 0x1a0d1, 0x101c9, 0xd471, 0x1a0f1, 0x10799]; + assert_eq!([0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, 0x1a0d1].map(|s| value(&got, s)), ift); + assert_eq!([0x101c9, 0xd471, 0x1a0f1, 0x10799].map(|s| value(&got, s)), [size, 0x2c, 112, window]); + for (&(sel, val), &(psel, pval)) in got[1..67].iter().zip(ta_plain_regs.iter()) { + assert_eq!(sel, psel); + assert!(val == pval || ta_rt_sels.contains(&sel), "TA {sel:#x}"); + } + for (i, (a, b)) in ta_plain.iter().zip(w.iter()).enumerate() { + if a != b { + assert!((ta::REGS..ta::REGS + 68 * 12).contains(&i) || (0x748..0x74c).contains(&i), "TA byte {i:#x}"); + } + } + let (w, q) = fs_rt(&words, fl); + // StartFS marks the slot as an SCS user; nothing else in the sequence moves. + assert_eq!((u32_at(&fsq_plain, fs::START_SCS), u32_at(&q, fs::START_SCS)), (0, 1)); + for (i, (a, b)) in fsq_plain.iter().zip(q.iter()).enumerate() { + assert!(a == b || (fs::START_SCS..fs::START_SCS + 4).contains(&i), "FS seq byte {i:#x}"); + } + assert_eq!((u16_at(&w, 0x788), u16_at(&w, 0x78a)), (84, 84 * 12)); + let fs_plain_regs = records(&fs_plain, fs::REGS, 82); + let got = records(&w, fs::REGS, 84); + assert_eq!((got[0].0, got[1], got[83]), (0x1739, (0x017e1, 1), (0x017d9, 1))); + let fs_rt_sels = [0x1a0a9, 0x1a0b1, 0x1a079, 0x1a081, 0x1a0d9, 0x1a0e1, 0x101c1, 0xd469, 0x1a0f9, 0x10791]; + assert_eq!([0x1a0a9, 0x1a0b1, 0x1a079, 0x1a081, 0x1a0d9, 0x1a0e1].map(|s| value(&got, s)), ift); + assert_eq!([0x101c1, 0xd469, 0x1a0f9, 0x10791].map(|s| value(&got, s)), [size, 0x2c, 112, window | 1 << 9]); + assert_eq!(got[0], fs_plain_regs[0]); + for (&(sel, val), &(psel, pval)) in got[2..83].iter().zip(fs_plain_regs[1..].iter()) { + assert_eq!(sel, psel); + assert!(val == pval || fs_rt_sels.contains(&sel), "FS {sel:#x}"); + } + for (i, (a, b)) in fs_plain.iter().zip(w.iter()).enumerate() { + if a != b { + assert!((fs::REGS..fs::REGS + 84 * 12).contains(&i) || (0x788..0x78c).contains(&i), "FS byte {i:#x}"); + } + } + } + } +} + +#[test] +fn scratch_requests_follow_the_gen1_section_model() { + for (layout, pages) in LAYOUTS { + let s = rt::ScratchRequest::new(layout).unwrap(); + assert_eq!(s.pages(), pages); + assert_eq!((s.tail_word(), s.stack_word(), s.window_word(), s.driver_word()), (0x2c, 112, 0x1600000, 0)); + // Both compute and render stages use macOS 27.2's J773g 0x2c tail reservation. + assert_eq!(s.compute_tail_word(), 0x2c); + } + assert_eq!(rt::ScratchRequest::NONE.compute_tail_word(), 0); + // Payload-free: no scratch even with depth and cliques. + assert_eq!(rt::ScratchRequest::new(0x0000_0000_ff00_ffff).unwrap(), rt::ScratchRequest::NONE); + // The smallest request is Apple's 89-page floor plus the guard page. + assert_eq!(rt::ScratchRequest::new(1 << 32).unwrap().pages(), 89); + // More than 2^16 pages, and a stack word that overflows, are refused. + assert_eq!(rt::ScratchRequest::new(0xffff_0000_ff00_ffff), Err(EINVAL)); + assert_eq!(rt::ScratchRequest::new(0x0000_ffff_ff00_0000), Err(EINVAL)); +} + +#[test] +fn scs_sizing_is_the_m4_pro_formula_in_whole_rows() { + // Per core: pages + ceil(pages / 256) + 8. + assert_eq!(rt::extra_pages(10, 791), Ok(10 * (791 + 4 + 8))); + assert_eq!(rt::extra_pages(10, 256), Ok(10 * (256 + 1 + 8))); + assert_eq!(rt::extra_pages(10, 257), Ok(10 * (257 + 2 + 8))); + assert_eq!(rt::extra_pages(10, 0), Ok(0)); + assert_eq!(rt::extra_pages(0, 791), Err(EINVAL)); + assert_eq!(rt::required_seeds(10, &[]), Ok(8192)); + assert_eq!(rt::required_seeds(10, &[0, 0]), Ok(8192)); + // Mesa's three T1 layouts on a 10-core M4: base 8192 + 10 x (pages + pages/256 + 8). + assert_eq!(rt::required_seeds(10, &[791]), Ok(16384)); + assert_eq!(rt::required_seeds(10, &[827]), Ok(16896)); + assert_eq!(rt::required_seeds(10, &[989]), Ok(18432)); + assert_eq!(rt::required_seeds(8, &[827]), Ok(15360)); + assert_eq!(rt::required_seeds(1, &[89]), Ok(8704)); + // Both stages of one render add up. + assert_eq!(rt::required_seeds(10, &[89, 89]), Ok(8192 + 2048)); + assert_eq!(rt::required_seeds(10, &[791, 89]), Ok(17408)); + assert_eq!(rt::required_seeds(10, &[989, 989]), Ok(28672)); + // Freelists: a base pool keeps 16384 records over 0x20000 bytes; an SCS pool gets the + // 0x80000 records over 4 MiB that macOS 27.2 writes on the J773g. + assert_eq!((rt::freelist_records(8192), rt::freelist_bytes(8192)), (16384, 0x20000)); + for seeds in [8704, 16384, 28672, rt::MAX_SCS_SEEDS] { + assert_eq!((rt::freelist_records(seeds), rt::freelist_bytes(seeds)), (0x80000, 0x400000)); + } + // The largest pool: 62 2-MiB rows, whose 124 MiB and 4-MiB freelist fill a 128 MiB window + // (63 rows and their freelist would not). + assert_eq!(rt::MAX_SCS_SEEDS, 62 * 512); + assert!(rt::window_bytes(rt::MAX_SCS_SEEDS) <= hw::client::SCS_POOL_WINDOW); + assert!(rt::window_bytes(rt::MAX_SCS_SEEDS + 512) > hw::client::SCS_POOL_WINDOW); + assert_eq!(rt::required_seeds(10, &[2337]), Ok(31744)); + assert_eq!(rt::required_seeds(10, &[2338]), Err(E2BIG)); + assert_eq!(rt::required_seeds(10, &[1164, 1164]), Ok(31744)); + assert_eq!(rt::required_seeds(10, &[1165, 1165]), Err(E2BIG)); + // Pools are created for two stages at the larger request, or the request if two do not fit. + assert_eq!(rt::pool_seeds(10, [791, 0]), Ok(24576)); + assert_eq!(rt::pool_seeds(10, [827, 0]), Ok(25088)); + assert_eq!(rt::pool_seeds(10, [0, 989]), rt::required_seeds(10, &[989, 989])); + assert_eq!(rt::pool_seeds(10, [2000, 0]), rt::required_seeds(10, &[2000])); + assert_eq!(rt::pool_seeds(10, [2338, 0]), Err(E2BIG)); + assert_eq!(rt::pool_seeds(10, [0, 0]), Ok(8192)); + // Extremes: refused, never wrapped (overflow checks are on). + assert_eq!(rt::required_seeds(u32::MAX, &[u16::MAX, u16::MAX]), Err(E2BIG)); + assert_eq!(rt::required_seeds(u32::MAX, &[u16::MAX; 64]), Err(E2BIG)); + assert_eq!(rt::required_seeds(0, &[1]), Err(EINVAL)); + for cores in 1..=10 { for pages in [89u16, 200, 500, 791, 1000] { + if let Ok(seeds) = rt::required_seeds(cores, &[pages]) { + assert_eq!(seeds % rt::SEEDS_PER_ROW, 0); + assert!(u64::from(seeds) >= 8192 + rt::extra_pages(cores, pages).unwrap() && seeds <= rt::MAX_SCS_SEEDS); + } + }} +} + +#[test] +fn ray_and_as_build_admission() { + let vm = mmu::Vm { mapped: vec![(POOL, POOL + 0x4000), (0x10010020000, 0x10010020040)] }; + let context = Context { vm: &vm, usc_base: 0, active_cores: 10, render_scs: [791, 0] }; + let scs = |needed, pool| rt::ScsSeeds { needed, pool }; + let mut b = SpanBatch; + // Admission returns the pool the command needs, and the one created for it: compute for two + // dispatches. + assert_eq!(check_compute_ray(&mut b, &context, &ray(LAYOUTS[0].0)), Ok(scs(16384, 24576))); + assert_eq!(check_compute_ray(&mut b, &context, &ray(LAYOUTS[1].0)), Ok(scs(16896, 25088))); + // 4 KiB of driver bytes per thread: 3833 pages per core, more than a window holds. + let huge = 0x1000_0000_6000_0070; + assert_eq!(rt::ScratchRequest::new(huge).unwrap().pages(), 3833); + assert_eq!(check_compute_ray(&mut b, &context, &ray(huge)), Err(E2BIG)); + let unmapped = mmu::Vm { mapped: vec![(POOL, POOL + 0x3000), (0x10010020000, 0x10010020040)] }; + let narrow = Context { vm: &unmapped, ..context }; + assert_eq!(check_compute_ray(&mut b, &narrow, &ray(LAYOUTS[0].0)), Err(ENOENT)); + let no_program = mmu::Vm { mapped: vec![(POOL, POOL + 0x4000)] }; + assert_eq!(check_compute_ray(&mut b, &Context { vm: &no_program, ..context }, &ray(LAYOUTS[0].0)), Err(ENOENT)); + let tables_only = rt::ComputeRay::new(0, 0, 0, POOL, 0x4000, 1, 112, 0, 0).unwrap(); + assert_eq!(check_compute_ray(&mut b, &Context { vm: &no_program, ..context }, &tables_only), Ok(rt::ScsSeeds::NONE)); + // Renders: within the queue's reservation, either stage; beyond it EINVAL. The pool created + // for them holds two stages of the reservation's larger one. + let none = rt::RayQueryStage::NONE; + let small = stage(1 << 32 | 0x6000_0000); + assert_eq!(check_render_ray(&mut b, &context, &[stage(LAYOUTS[0].0), none]), Ok(scs(16384, 24576))); + assert_eq!(check_render_ray(&mut b, &context, &[none, small]), Ok(scs(9216, 24576))); + assert_eq!(check_render_ray(&mut b, &Context { render_scs: [0, 0], ..context }, &[none, small]), Err(EINVAL)); + assert_eq!(check_render_ray(&mut b, &Context { render_scs: [89, 89], ..context }, &[small, small]), Ok(scs(10240, 10240))); + assert_eq!(check_render_ray(&mut b, &context, &[stage(LAYOUTS[1].0), none]), Err(EINVAL)); + assert_eq!(check_render_ray(&mut b, &Context { render_scs: [3833, 0], ..context }, &[stage(huge), none]), Err(E2BIG)); + assert_eq!(check_render_ray(&mut b, &Context { vm: &unmapped, ..context }, &[stage(LAYOUTS[0].0), none]), Err(ENOENT)); + assert_eq!(check_render_ray(&mut b, &Context { render_scs: [0, 0], ..context }, &[none, none]), Ok(rt::ScsSeeds::NONE)); + // Flags: AS_BUILD alone. + assert_eq!(rt::as_build(0), Some(false)); assert_eq!(rt::as_build(4), Some(true)); + for flag in [1, 2, 8, 1 << 16, 1 << 17, 1 << 20, 5, 6] { assert_eq!(rt::as_build(flag), None); } +} + +// The commands Mesa's G16G ray-query path (ASAHI_MESA_DEBUG=g16grt, mesa 3ff3d359) submits on a +// 10-core M4: hk_gen1_ray_query_scs_layout() is 0x0130000060010070 with the candidate profile, +// the intersection pool is one 16-KiB IFT (first 1, count 112), the default program +// 0x10010020000 with control 0x16000000000. dEQP-VK.ray_query.* compute, chit/ahit and +// dynamic-indexing cases submit the compute shape; .vert/.frag/.tesc cases reserve the render +// stage at QUEUE_CREATE (hk_queue_ensure_drm) and submit a render with it. Before SCS pools were +// sized from the request, every one of them was refused with E2BIG, which Mesa reports as +// VK_ERROR_DEVICE_LOST at vkQueueSubmit. +#[test] +fn mesa_g16grt_ray_query_commands_are_admitted() { + let mesa = LAYOUTS[2].0; + let vm = mmu::Vm { mapped: vec![(POOL, POOL + 0x4000), (0x10010020000, 0x10010020040)] }; + let pages = rt::ScratchRequest::new(mesa).unwrap().pages(); + assert_eq!(pages, 989); + // QUEUE_CREATE render_scs_layout: the vertex stage, the fragment stage, or both. The VM's + // SCS render pools a queue creates hold both stages, so a queue Mesa replaces to add the + // other stage still fits them. + for reservation in [[pages, 0], [0, pages], [pages, pages]] { + assert!(rt::required_seeds(10, &reservation).is_ok(), "QUEUE_CREATE {reservation:?}"); + assert_eq!(rt::pool_seeds(10, reservation), Ok(28672), "{reservation:?}"); + } + let context = Context { vm: &vm, usc_base: 0, active_cores: 10, render_scs: [pages, pages] }; + let scs = |needed, pool| rt::ScsSeeds { needed, pool }; + let mut b = SpanBatch; + // Compute: 18432 for one dispatch, a 56-row pool for two. + assert_eq!(check_compute_ray(&mut b, &context, &ray(mesa)), Ok(scs(18432, 28672))); + let none = rt::RayQueryStage::NONE; + for (stages, needed) in [([stage(mesa), none], 18432), ([none, stage(mesa)], 18432), ([stage(mesa), stage(mesa)], 28672)] { + assert_eq!(check_render_ray(&mut b, &context, &stages), Ok(scs(needed, 28672))); + // A queue that reserved one stage creates pools that take both. + let one = Context { render_scs: [pages, 0], ..context }; + assert_eq!(check_render_ray(&mut b, &one, &[stage(mesa), none]).map(|s| s.pool), Ok(28672)); + } + // Their pools fit an SCS window, freelist included. + assert_eq!(rt::freelist_records(28672), 0x80000); + assert!(rt::window_bytes(28672) <= hw::client::SCS_POOL_WINDOW); +} + +#[test] +fn long_allowance_follows_g17_select_per_job() { + let render = |stages: [rt::RayQueryStage; 2]| Command::Render(Box::new(RenderCommand { ray_query: stages, scs: rt::ScsSeeds::NONE })); + let compute = |ray: rt::ComputeRay, as_build: bool| Command::Compute(Box::new(ComputeCommand { ray, scs: rt::ScsSeeds::NONE, as_build })); + let none = rt::RayQueryStage::NONE; + assert!(render([stage(LAYOUTS[0].0), none]).long() && render([none, stage(LAYOUTS[0].0)]).long()); + assert!(!render([none, none]).long() && render([none, none]).scs() == rt::ScsSeeds::NONE); + assert!(compute(ray(LAYOUTS[0].0), false).long() && compute(rt::ComputeRay::NONE, true).long()); + assert!(!compute(rt::ComputeRay::NONE, false).long()); + // Scratch alone is not traversal (as on the M4 Pro), but it needs an SCS pool; tables + // alone do not. + let scratch = rt::ComputeRay::new(LAYOUTS[0].0, 0, 0, 0, 0, 0, 0, 0, 0).unwrap(); + let vm = mmu::Vm { mapped: vec![(POOL, POOL + 0x4000)] }; + let context = Context { vm: &vm, usc_base: 0, active_cores: 10, render_scs: [0, 0] }; + let admitted = rt::ScsSeeds { needed: 16384, pool: 24576 }; + let mut b = SpanBatch; + assert!(!compute(scratch, false).long() && check_compute_ray(&mut b, &context, &scratch) == Ok(admitted)); + let tables = rt::ComputeRay::new(0, 0, 0, POOL, 0x4000, 1, 112, 0, 0).unwrap(); + assert_eq!(check_compute_ray(&mut b, &context, &tables), Ok(rt::ScsSeeds::NONE)); + // A command's SCS pool is what admission recorded. + let command = Command::Compute(Box::new(ComputeCommand { ray: scratch, scs: admitted, as_build: false })); + assert_eq!((command.scs(), compute(rt::ComputeRay::NONE, false).scs()), (admitted, rt::ScsSeeds::NONE)); + // Deadlines: at least ten seconds for a long job, never re-enabling a disabled one. + assert_eq!(logic::long_deadline_ms(5000), 10_000); + assert_eq!(logic::long_deadline_ms(10_000), 10_000); + assert_eq!(logic::long_deadline_ms(30_000), 30_000); + assert_eq!(logic::long_deadline_ms(0), 0); + assert_eq!(logic::long_deadline_ms(1), 10_000); + let now = 1_000_000_000; + let d = logic::Deadlines::renew(now, 5000, 5000); + assert_eq!((d.select(false, false), d.select(true, false)), (now + 5_000_000_000, now + 5_000_000_000)); + assert_eq!((d.select(false, true), d.select(true, true)), (now + 10_000_000_000, now + 10_000_000_000)); + let d = logic::Deadlines::renew(now, 5000, 0); + assert_eq!((d.select(true, false), d.select(true, true)), (u64::MAX, u64::MAX)); + assert_eq!(d.select(false, true), now + 10_000_000_000); + let d = logic::Deadlines::renew(u64::MAX - 1, 20_000, 50); + assert_eq!((d.select(false, true), d.select(true, false), d.select(true, true)), (u64::MAX, u64::MAX, u64::MAX)); + let d = logic::Deadlines::renew(now, 50, 50); + assert_eq!((d.select(false, false), d.select(true, true)), (now + 100_000_000, now + 10_000_000_000)); + assert_eq!(logic::Deadlines::EXPIRED.select(true, true), logic::EXPIRED); +} +''' +encode_source = (BACKEND / 'encode.rs').read_text() +# The compute encoder's gates, visible to this harness only through a tiny accessor. +gates = '\npub(crate) fn compute_encoder_gate() -> bool { compute_encoder::COMPUTE_SCS_DRIVER_WORD }\n' \ + 'pub(crate) fn render_encoder_gate() -> bool { render_encoder::RENDER_SCS_ENABLE }\n' +with tempfile.TemporaryDirectory(prefix='m4-rust-rt-') as name: + directory = pathlib.Path(name) + staged = directory / 'g16' + staged.mkdir() + # Stage the encoder with the gate accessors appended; the other modules come from the tree. + (staged / 'encode').mkdir() + for part in ['compute.rs', 'render.rs']: + (staged / 'encode' / part).write_text((BACKEND / 'encode' / part).read_text()) + (staged / 'encode.rs').write_text(encode_source + gates) + source = harness + for key, value in {'@FLAT@': str(FLAT), '@ADMISSION@': admission, '@CONVERSION@': conversion, + '@RESERVE@': reserve, '@LONG@': long, '@CLIENT@': client}.items(): + source = source.replace(key, value) + source = source.replace('#[path = "@BACKEND@/encode.rs"]', '#[path = "' + str(staged / 'encode.rs') + '"]') + source = source.replace('@BACKEND@', str(BACKEND)) + source += '\n#[test] fn render_gate_is_on() { assert!(encode::render_encoder_gate()); }\n' + test = directory / 'test.rs' + test.write_text(source) + (OUT / 'ray-tracing-host.rs').write_text(source) + binary = directory / 'test' + subprocess.run(rustc() + ['--edition=2021', '-C', 'overflow-checks=yes', '--test', str(test), '-o', str(binary)], check=True) + result = subprocess.run([str(binary), '--nocapture'], text=True, capture_output=True) + print(result.stdout + result.stderr, end='') + (OUT / 'ray-tracing-host.log').write_text(result.stdout + result.stderr) + result.check_returncode() + tests = int(re.search(r'test result: ok\. (\d+) passed;', result.stdout)[1]) +(OUT / 'ray-tracing-host.json').write_text(json.dumps({ + 'result': 'pass', 'tests': tests, 'feature_word': hex(features), + 'scope': 'Production rt.rs, recovery/logic.rs and TA/FS/compute encoders, with command.rs admission and ' + 'engine.rs conversion copied verbatim; VM spans mocked. No GPU, firmware or Mesa.', + 'source_sha256': {name: hashlib.sha256((BACKEND / name).read_bytes()).hexdigest() for name in + ['rt.rs', 'recovery/logic.rs', 'command.rs', 'engine.rs', 'params.rs', 'encode.rs', 'hw.rs', + 'encode/compute.rs', 'encode/render.rs']}, +}, indent=2) + '\n') diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-recovery.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-recovery.py index 36f4cdeac268e4..4f6e79e6857594 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-recovery.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-recovery.py @@ -31,7 +31,7 @@ // This is the retirement policy used by poll.rs: an affected fence does not // erase the independently authenticated owner receipt. No synthetic receipt // is generated here; the hardware poller remains responsible for that proof. - fn finish(owners: &mut Lifetime, unit: usize, receipt: Retirement, affected: bool) -> bool { + fn finish(owners: &mut Lifetime, unit: usize, receipt: Retirement, affected: bool) -> bool { assert!(receipt.complete()); if receipt.owner_retired() { assert!(owners.retire(unit)); @@ -43,7 +43,7 @@ #[test] fn ten_thousand_affected_full_receipts_preserve_displacement() { - let mut owners = Lifetime::new(); + let mut owners = Lifetime::<2>::new(false); for number in 0..10_000 { let unit = number % 2; assert!(owners.claim(unit)); @@ -58,7 +58,7 @@ #[test] fn actual_abort_never_supplies_a_displacement_receipt() { - let mut owners = Lifetime::new(); + let mut owners = Lifetime::<2>::new(false); assert!(owners.claim(0)); assert!(owners.publish(0)); assert!(!finish(&mut owners, 0, Retirement::Full, false)); @@ -77,8 +77,8 @@ #[test] fn exhausted_compute_ledger_does_not_poison_render_ledger() { - let mut compute = Lifetime::new(); - let mut render = Lifetime::new(); + let mut compute = Lifetime::<2>::new(false); + let mut render = Lifetime::<2>::new(false); assert!(compute.claim(0)); assert!(compute.publish(0)); finish(&mut compute, 0, Retirement::Aborted, true); @@ -101,7 +101,7 @@ #[test] fn two_aborts_stay_bounded_and_cannot_be_reset_by_preparation_cancel() { - let mut owners = Lifetime::new(); + let mut owners = Lifetime::<2>::new(false); for unit in 0..2 { assert!(owners.claim(unit)); assert!(owners.publish(unit)); @@ -115,7 +115,7 @@ #[test] fn repeated_handshakes_and_storm_limit_preserve_owner_accounting() { - let mut owners = Lifetime::new(); + let mut owners = Lifetime::<2>::new(false); let (mut window, mut count) = (1, 0); for number in 0..logic::WINDOW_LIMIT { assert!(logic::admit(100, &mut window, &mut count)); @@ -133,6 +133,23 @@ assert_eq!(before.quarantined, 0); assert!(logic::admit(logic::WINDOW_NS + 2, &mut window, &mut count)); } + + #[test] + fn cross_vm_render_abort_isolates_innocent_flight_and_quarantines_only_aborted_slot() { + let mut owners = Lifetime::<6>::new(true); + // Client A claims slot 0; Client B concurrently claims slot 1. + assert!(owners.claim(0)); + assert!(owners.publish(0)); + assert!(owners.claim(1)); + assert!(owners.publish(1)); + // Client A aborts (affected=true) -> slot 0 quarantined, Client A fails. + assert!(finish(&mut owners, 0, Retirement::Aborted, true)); + // Client B retires Full (affected=false) -> slot 1 cleanly retired, Client B succeeds. + assert!(!finish(&mut owners, 1, Retirement::Full, false)); + assert!(!owners.exhausted()); + assert_eq!(owners.counts().quarantined, 1); + assert_eq!(owners.counts().retired, 1); + } } '''.replace('__ROOT__', str(production)) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index a048447b1436a7..cb84603adc5560 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -41,10 +41,29 @@ def module(text, name): #[derive(Copy,Clone,Debug,Eq,PartialEq)] pub struct Error(i32); pub const EINVAL:Error=Error(22); pub const EAGAIN:Error=Error(11); pub const E2BIG:Error=Error(7); pub const EBUSY:Error=Error(16); pub const EOVERFLOW:Error=Error(75); pub const EIO:Error=Error(5); +pub const ENOMEM:Error=Error(12); pub const ETIMEDOUT:Error=Error(110);pub const ERESTARTSYS:Error=Error(512); pub const GFP_KERNEL:u32=0; pub type Result = std::result::Result; -pub mod prelude {pub use crate::{Result,KVec,GFP_KERNEL,EINVAL,EAGAIN,E2BIG,EBUSY,EOVERFLOW,EIO,ETIMEDOUT,ERESTARTSYS};} +macro_rules! init { ($($tt:tt)*) => { $($tt)* }; } +pub mod prelude {pub use crate::{Result,KVec,KBox,GFP_KERNEL,EINVAL,EAGAIN,E2BIG,EBUSY,EOVERFLOW,EIO,ENOMEM,ETIMEDOUT,ERESTARTSYS};} +std::thread_local!{pub static FAIL_KBOX_UNINIT:std::cell::Cell=const{std::cell::Cell::new(false)};} +pub struct KBox(Box); +implKBox{ + pub fn new(x:T,_:u32)->Result{Ok(Self(Box::new(x)))} + pub fn init(x:T,_:u32)->Result{Ok(Self(Box::new(x)))} + pub fn new_uninit(_:u32)->Result>>{ + if FAIL_KBOX_UNINIT.with(|f|f.replace(false)){return Err(ENOMEM);} + Ok(KBox(Box::new(core::mem::MaybeUninit::uninit()))) + } + pub fn write(mut b:KBox>,x:T)->Self{ + b.0.write(x); + // SAFETY: `write` just initialized `b.0`. + Self(unsafe{Box::from_raw(Box::into_raw(b.0).cast::())}) + } +} +implstd::ops::Deref for KBox{type Target=T;fn deref(&self)->&T{&self.0}} +implstd::ops::DerefMut for KBox{fn deref_mut(&mut self)->&mut T{&mut self.0}} pub struct KVec(Vec); implKVec{pub fn new()->Self{Self(Vec::new())} pub fn with_capacity(n:usize,_:u32)->Result{Ok(Self(Vec::with_capacity(n)))} pub fn push(&mut self,x:T,_:u32)->Result{self.0.push(x);Ok(())}} implstd::ops::Deref for KVec{type Target=Vec;fn deref(&self)->&Vec{&self.0}} @@ -68,7 +87,7 @@ def module(text, name): } pub struct Arc{inner:std::sync::Arc} - implArc{pub fn new(v:T,_:u32)->crate::Result{Ok(Self{inner:std::sync::Arc::new(v)})}pub fn strong_count(v:&Self)->usize{std::sync::Arc::strong_count(&v.inner)}} + implArc{pub fn new(v:T,_:u32)->crate::Result{Ok(Self{inner:std::sync::Arc::new(v)})}pub fn strong_count(v:&Self)->usize{std::sync::Arc::strong_count(&v.inner)}pub fn ptr_eq(a:&Self,b:&Self)->bool{std::sync::Arc::ptr_eq(&a.inner,&b.inner)}} implClone for Arc{fn clone(&self)->Self{Self{inner:self.inner.clone()}}} implstd::ops::Deref for Arc{type Target=T;fn deref(&self)->&T{&self.inner}} pub mod aref {pub struct ARef(T);impl From<&crate::device::Device>for ARef{fn from(v:&crate::device::Device)->Self{Self(v.clone())}}} @@ -89,44 +108,148 @@ def module(text, name): } pub mod object { use crate::*;use crate::sync::Arc; - #[derive(Copy,Clone,Debug,Eq,PartialEq)]pub enum Class{Shared,Fw,FwCached,SharedCached,Mmio} + #[derive(Copy,Clone,Debug,Eq,PartialEq)]pub enum Class{Shared,Fw,FwCached,SharedCached,FwCoherent,Mmio} pub enum Placement{Anywhere} pub struct Request{pub size:usize,pub class:Class,pub placement:Placement,pub offset:usize,pub client:Option<(u64,u64)>,pub lower:Option,pub cpu:bool} - pub struct FwObject{pub class:Class,pub client_leaf:Option,pub va:u64,pub gva:Option,pub lower_gva:Option,pub lower_leaf:Option,pub size:usize,pub mapped:usize,pub offset:usize,pub data:std::sync::Arc>>,pub fills:std::sync::Mutex>,pub fail_fill:std::sync::atomic::AtomicBool} + pub struct FwObject{pub class:Class,pub client_leaf:Option,pub va:u64,pub gva:Option,pub lower_gva:Option,pub lower_leaf:Option,pub size:usize,pub mapped:usize,pub offset:usize,pub data:std::sync::Arc>>,pub fills:std::sync::Mutex>,pub fail_fill:std::sync::atomic::AtomicBool,pub write_bytes:std::sync::atomic::AtomicUsize} impl FwObject{ - pub fn view(o:&Arc,offset:usize,size:usize)->Result>{Arc::new(Self{class:o.class,client_leaf:None,va:o.va+offset as u64,gva:None,lower_gva:None,lower_leaf:None,size,mapped:o.mapped,offset:o.offset+offset,data:o.data.clone(),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false)},0)} - pub fn write(&self,o:usize,b:&[u8])->Result{let mut d=self.data.lock().unwrap();d[self.offset+o..self.offset+o+b.len()].copy_from_slice(b);Ok(())} + pub fn view(o:&Arc,offset:usize,size:usize)->Result>{Arc::new(Self{class:o.class,client_leaf:None,va:o.va+offset as u64,gva:None,lower_gva:None,lower_leaf:None,size,mapped:o.mapped,offset:o.offset+offset,data:o.data.clone(),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)} + pub fn write(&self,o:usize,b:&[u8])->Result{self.write_bytes.fetch_add(b.len(),std::sync::atomic::Ordering::Relaxed);let mut d=self.data.lock().unwrap();d[self.offset+o..self.offset+o+b.len()].copy_from_slice(b);Ok(())} pub fn fill(&self,o:usize,v:u8,n:usize)->Result{if self.fail_fill.swap(false,std::sync::atomic::Ordering::Relaxed){return Err(EIO);}self.fills.lock().unwrap().push((o,n));let mut d=self.data.lock().unwrap();d[self.offset+o..self.offset+o+n].fill(v);Ok(())} pub fn w32(&self,o:usize,v:u32)->Result{self.write(o,&v.to_le_bytes())} pub fn w64(&self,o:usize,v:u64)->Result{self.write(o,&v.to_le_bytes())} pub fn r32(&self,o:usize)->Result{let d=self.data.lock().unwrap();Ok(u32::from_le_bytes(d[self.offset+o..self.offset+o+4].try_into().unwrap()))} pub fn snapshot(&self)->Vec{self.data.lock().unwrap().clone()} } + pub struct FwLease(pub crate::cleanup::Deferred); + impl FwLease { + pub fn new(mut objects: Objects) -> Result> { + objects.finish_private()?; + Arc::new(Self(crate::cleanup::Deferred::new(objects)?), 0) + } + } pub struct Factory; - impl Factory{pub fn objects(&self,_:&())->Objects{Objects::new()}} - pub struct Objects{pub objects:Vec>,next:u64} + impl Factory{ + pub fn objects(&self,_:&super::vm::MockVm)->Objects{Objects::new()} + pub fn fw_objects(&self)->Objects{Objects::new()} + pub fn persistent_objects(&self)->Objects{Objects::persistent()} + pub fn persistent_objects_probe(&self)->Objects{Objects::persistent()} + } + pub static NEXT_VA: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0xfffffc2001000000); + std::thread_local!{pub static ALL_OBJECTS:std::cell::RefCell>>=const{std::cell::RefCell::new(Vec::new())};} + pub struct Window { + pub fail_once: std::sync::atomic::AtomicBool, + pub calls: std::sync::atomic::AtomicUsize, + pub ranges: std::sync::Mutex>>, + } + impl Window { + pub fn new() -> Self { + Self { + fail_once: std::sync::atomic::AtomicBool::new(false), + calls: std::sync::atomic::AtomicUsize::new(0), + ranges: std::sync::Mutex::new(Vec::new()), + } + } + pub fn sync_range(&self, _uat: &(), range: core::ops::Range) -> Result { + self.calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + self.ranges.lock().unwrap().push(range); + if self.fail_once.swap(false, std::sync::atomic::Ordering::AcqRel) { + return Err(EIO); + } + Ok(()) + } + } + pub struct Private { + pub pending: Option>, + } + pub struct Objects{pub objects:Vec>,pub persistent:bool,pub uat:(),pub window:Arc>,pub private:Option} + // Device-lifetime render and compute command records, per test thread (the production + // tables are resources::RenderCmds and resources::ComputeCmds): one never-dropped + // allocator owns them. + std::thread_local!{ + pub static PERSISTENT:std::cell::RefCell>=const{std::cell::RefCell::new(None)}; + pub static PASS_CMDS:std::cell::RefCell>=const{std::cell::RefCell::new(Vec::new())}; + pub static UNIT_CMDS:std::cell::RefCell>=const{std::cell::RefCell::new(Vec::new())}; + } + pub fn test_cmds(k:u64)->crate::g16::slots::PassCmds{ + if let Some(c)=PASS_CMDS.with(|p|p.borrow().iter().find(|e|e.0==k).map(|e|e.1.clone())){return c;} + let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::PassCmds::new(p.get_or_insert_with(Objects::persistent),k).unwrap()}); + PASS_CMDS.with(|p|p.borrow_mut().push((k,c.clone())));c + } + pub fn test_unit_cmds(k:u64)->crate::g16::slots::UnitCmds{ + if let Some(c)=UNIT_CMDS.with(|p|p.borrow().iter().find(|e|e.0==k).map(|e|e.1.clone())){return c;} + let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::UnitCmds::new(p.get_or_insert_with(Objects::persistent),k).unwrap()}); + UNIT_CMDS.with(|p|p.borrow_mut().push((k,c.clone())));c + } impl Objects{ - pub fn new()->Self{Self{objects:vec![],next:0xfffffc2001000000}} - pub fn finish_private(&mut self)->Result{Ok(())} + pub fn new()->Self{Self::with_window(false,Arc::new(crate::sync::Mutex::new(Window::new()),0).unwrap())} + pub fn persistent()->Self{Self::with_window(true,Arc::new(crate::sync::Mutex::new(Window::new()),0).unwrap())} + pub fn with_window(persistent:bool,window:Arc>)->Self{Self{objects:vec![],persistent,uat:(),window,private:Some(Private{pending:None})}} + __FINISH_PRIVATE__ pub fn alloc_dynamic_client(&mut self,size:usize)->Result>{self.alloc(Request{size,class:Class::Shared,placement:Placement::Anywhere,offset:0,client:Some((0x7040000000,super::hw::pte::LEAF_NC)),lower:None,cpu:true})} - pub fn alloc(&mut self,r:Request)->Result>{let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=self.next;self.next+=bytes as u64+0x4000;let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false)},0)?;self.objects.push(x.clone());Ok(x)} + pub fn alloc(&mut self,r:Request)->Result>{if r.class==Class::FwCoherent&&(!self.persistent||r.client.is_some()){return Err(EINVAL);}let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=NEXT_VA.fetch_add(bytes as u64+0x4000,std::sync::atomic::Ordering::Relaxed);let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;if let Some(p)=self.private.as_mut(){let end=va+bytes as u64;p.pending=Some(match p.pending.take(){Some(range)=>range.start.min(va)..range.end.max(end),None=>va..end});}self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} } } pub mod graph { use crate::*;use crate::sync::Arc;use super::object::*; - use super::hw::{pte,tuning}; + use super::fw::graph::{self, job_list, notifier_page, qinfo, qstate, sched_ctx}; + use super::hw::{pte, sizes, tuning}; + #[derive(Copy, Clone)] + pub(crate) struct FwAbi; + impl FwAbi { + pub(crate) fn qinfo(self) -> &'static graph::qinfo::Layout { + &graph::qinfo::V25G83 + } + } __CLIENT__ __CMD_CLASSES__ __ALLOC__ __ALLOC_WORK__ + __GRAPH_TYPES__ } pub mod encode { pub struct Geometry{pub tpc_bytes:u64,pub tilemap_bytes:u64} - pub struct PassRefs{pub ta_work:u64,pub ta_work_gva:u64,pub fs_work:u64,pub fs_work_gva:u64,pub ta_seq:u64,pub fs_seq:u64,pub scene:u64,pub tpc_gva:u64,pub tilemap_gva:u64,pub heap_gva:u64,pub scene_user_gva:u64,pub pre_gva:[u64;3],pub fs_scratch_gva:u64,pub aux_gva:u64,pub its:u64,pub ta_scratch:u64,pub tpc_fw:u64,pub scratch_fw:u64} + pub struct PassRefs{pub ta_work:u64,pub ta_work_gva:u64,pub fs_work:u64,pub fs_work_gva:u64,pub ta_seq:u64,pub fs_seq:u64,pub scene:u64,pub tpc_gva:u64,pub tilemap_gva:u64,pub heap_gva:u64,pub scene_user_gva:u64,pub scene_list:u64,pub pre_gva:[u64;3],pub fs_scratch_gva:u64,pub aux_gva:u64,pub its:u64,pub ta_scratch:u64,pub tpc_fw:u64,pub scratch_fw:u64} } pub mod vm { - use crate::{mmu,sync::Arc};use core::sync::atomic::Ordering; - pub struct VmState{pub id:u64,pub slot:u32,pub generation:u8,pub vm:()} + use crate::{mmu,sync::Arc}; + use core::sync::atomic::{AtomicBool,Ordering}; + use super::resources::reservations::Cache; + pub struct MockVm { + closed: AtomicBool, + unpublished: AtomicBool, + cache: Option>, + _live: Option>, + } + impl MockVm{ + pub fn new() -> Self { + Self { + closed: AtomicBool::new(false), + unpublished: AtomicBool::new(false), + cache: None, + _live: None, + } + } + pub fn tracked(cache: Arc) -> (Self, std::sync::Arc) { + let live = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(1)); + let released = std::sync::Arc::new(AtomicBool::new(false)); + let registry = Arc::new(Registry { live: live.clone() }, 0).unwrap(); + let bind = mmu::VmBind { live, released: released.clone() }; + let token = Arc::new(LiveToken { registry, bind: Some(bind), file_id: 0 }, 0).unwrap(); + (Self { cache: Some(cache), _live: Some(token), ..Self::new() }, released) + } + pub fn is_closed(&self)->bool{self.closed.load(Ordering::Acquire)} + pub fn close(&self){self.closed.store(true,Ordering::Release);} + // Accepted renders still unpublished (the VM cache's standby reservations). + pub fn set_unpublished(&self,v:bool){self.unpublished.store(v,Ordering::Release);} + } + pub struct VmState{pub id:u64,pub slot:u32,pub generation:u8,pub vm:MockVm} + impl VmState { + pub fn renders_unpublished(&self) -> bool { + self.vm.unpublished.load(Ordering::Acquire) + || self.vm.cache.as_ref().is_some_and(|cache| cache.renders_unpublished()) + } + } struct Registry{live:std::sync::Arc}impl Registry{fn release(&self,_file:u64){self.live.fetch_sub(1,Ordering::AcqRel);}} __LIVE_TOKEN__ __LIVE_DROP__ @@ -142,26 +265,301 @@ def module(text, name): } pub mod resources { use core::sync::atomic::{AtomicU64,Ordering};use crate::*; - pub struct ComputeArena{pub compute:KVec} - pub struct RenderArena{pub passes:KVec,pub tpc_dirty:[AtomicU64;2],pub tilemap_dirty:[AtomicU64;2]} + pub struct PassDirty<'a>{pub tpc:&'a AtomicU64,pub tilemap:&'a AtomicU64,pub tilemap_last:&'a AtomicU64,pub tilemap_clean:&'a AtomicU64,pub heap:&'a AtomicU64} + pub struct ComputeArena{pub compute:KVec,pub render:Option>,pub hw_slots:Option<[usize;super::hw::sizes::SCS_COMPUTE_UNITS]>} + // A job's compute units; here one arena. + pub type Prepared=ComputeArena; + #[derive(Clone)] + pub enum PassOwnerArena{Base(crate::sync::Arc)} + pub struct PoolExtArena; + #[derive(Clone)] + pub enum PbOwnerArena{Base(crate::sync::Arc),Ext(crate::sync::Arc,crate::sync::Arc)} + impl PassOwnerArena{ + pub fn pass_and_dirty(&self,k:usize)->Option<(&super::slots::PassSlot,PassDirty<'_>)>{ + match self{Self::Base(a)=>Some((a.passes.get(k)?,PassDirty{tpc:a.tpc_dirty.get(k)?,tilemap:a.tilemap_dirty.get(k)?,tilemap_last:a.tilemap_last.get(k)?,tilemap_clean:a.tilemap_clean.get(k)?,heap:a.heap_dirty.get(k)?}))} + } + } + std::thread_local!{ + pub static COMPUTE_OWNER_ARENA:std::cell::RefCell< + Option>, + >=const{std::cell::RefCell::new(None)}; + pub static COMPUTE_OWNER_ARENAS:std::cell::RefCell< + Option>>, + >=const{std::cell::RefCell::new(None)}; + } + impl ComputeArena{ + pub fn compute_units(&self)->Result{Ok(self.compute.len())} + pub fn compute_slot_mask(&self)->Result{ + if let Some(slots)=self.hw_slots { + let mut mask=0u32; + for slot in slots { mask |= 1u32 << slot; } + return Ok(mask); + } + let n=self.compute.len().min(super::hw::sizes::COMPUTE_UNITS); + Ok(if n>=32 { u32::MAX } else { (1u32 << n) - 1 }) + } + pub fn compute_unit(&self,k:usize)->Result<&super::slots::ComputeSlot>{ + if let Some(slots)=self.hw_slots { + let local=slots.iter().position(|&s|s==k).ok_or(EINVAL)?; + return self.compute.get(local).ok_or(EINVAL); + } + self.compute.get(k).ok_or(EINVAL) + } + pub fn compute_arena(&self,k:usize)->Option>{ + let idx=if let Some(slots)=self.hw_slots { + slots.iter().position(|&s|s==k)? + } else { k }; + COMPUTE_OWNER_ARENAS + .with(|a|a.borrow().as_ref().and_then(|v|v.get(idx).cloned())) + .or_else(||COMPUTE_OWNER_ARENA.with(|a|a.borrow().clone())) + } + pub fn render_arena(&self)->Option>{self.render.clone()} + pub fn render_passes(&self)->Result{self.render.as_deref().map(|r|r.passes.len()).ok_or(EINVAL)} + pub fn render_pass(&self,k:usize)->Result<&super::slots::PassSlot>{self.render.as_deref().and_then(|r|r.passes.get(k)).ok_or(EINVAL)} + pub fn render_pass_dirty(&self,k:usize)->Result>{let r=self.render.as_deref().ok_or(EINVAL)?;if k>=r.passes.len(){return Err(EINVAL);}Ok(PassDirty{tpc:&r.tpc_dirty[k],tilemap:&r.tilemap_dirty[k],tilemap_last:&r.tilemap_last[k],tilemap_clean:&r.tilemap_clean[k],heap:&r.heap_dirty[k]})} + pub fn set_pass_dirty(&self,k:usize,tpc:u64,tilemap:u64,heap:u64)->Result{let p=self.render_pass(k)?;if tpc>p.tpc.size as u64||tilemap>p.tilemap.size as u64||heap>p.heap.size as u64{return Err(E2BIG);}let d=self.render_pass_dirty(k)?;d.tpc.fetch_max(tpc,Ordering::Relaxed);d.tilemap.fetch_max(tilemap,Ordering::Relaxed);d.tilemap_last.store(tilemap,Ordering::Relaxed);d.tilemap_clean.store(0,Ordering::Relaxed);d.heap.fetch_max(heap,Ordering::Relaxed);Ok(())} + pub fn pass_owner_arena(&self,_k:usize)->Option{self.render.as_ref().map(|r|PassOwnerArena::Base(r.clone()))} + } + pub struct RenderArena{pub passes:KVec,pub tpc_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS],pub tilemap_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS],pub tilemap_last:[AtomicU64;super::hw::sizes::RENDER_SLOTS],pub tilemap_clean:[AtomicU64;super::hw::sizes::RENDER_SLOTS],pub heap_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS]} impl RenderArena{ __SET_DIRTY__ } + pub(crate) const BASE_COMPUTE_UNITS: usize = 2; + pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; + const BASE_PB_SLOTS: usize = super::hw::sizes::BASE_PB_SLOTS; + __RENDER_BURST__ + + pub(crate) mod reservations { + use super::{ComputeArena as ComputeUnitSet, PoolExtArena, RenderArena}; + use crate::{ + device::Device, + driver::AsahiDrmDevice, + g16::{budget::Budget, object::Factory, pools::{PbEpoch, Pools}, slots::Slots, vm::{MockVm, VmState}}, + sync::{Arc, CondVar, Mutex}, + KVec, + }; + use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + + #[derive(Default)] + pub(crate) struct Shared { + closed_vm_reclaim: AtomicBool, + publish_wake: AtomicBool, + started: AtomicBool, + sleeping: AtomicBool, + poll_queued: AtomicBool, + } + impl Shared { + __WAKE_PUBLISH__ + __WAKE_CLOSED_VM_RECLAIM__ + + fn poll_now(&self) { + self.poll_queued.store(true, Ordering::Release); + } + } + + __STANDBY__ + __SPARE_EPOCHS__ + struct RenderExtArena; + struct PbHeapExtArena; + const EXT_RENDER_TIERS: [(); 0] = []; + const PB_HEAP_EXT_TIERS: [(); 0] = []; + const EXT_PB_SLOTS: usize = 1; + + pub(crate) struct Cache { + standby: Mutex, + standby_available: CondVar, + closed: AtomicBool, + active_render_passes: AtomicU32, + shared: Arc, + } + impl Cache { + __RELEASE_RESERVED__ + __RELEASE_RENDER_PASSES__ + __RENDERS_UNPUBLISHED__ + } + + __PREPARED__ + __DROP_PREPARED__ + impl Prepared { + __COMMIT_RENDER__ + __DISCARD_UNPUBLISHED__ + } + + struct Engine { + shared: Option>, + } + struct Firmware { + engine: Engine, + pools: Pools, + slots: Slots, + } + impl Firmware { + __RECLAIM_CLOSED_VM_SLOTS__ + + fn idle_poll(&mut self) { + let shared = self.engine.shared.as_ref().unwrap(); + assert!(shared.poll_queued.swap(false, Ordering::AcqRel), "poll must be queued"); + self.reclaim_closed_vm_slots(); + } + } + + fn displaced_vm(credits: u32) -> ( + Firmware, Arc, Arc, Arc, std::sync::Arc, Prepared, + ) { + let shared = Arc::new(Shared::default(), 0).unwrap(); + shared.started.store(true, Ordering::Release); + let cache = Arc::new(Cache { + standby: Mutex::new(Standby { epochs: KVec::new(), reserved: credits, waiters: 0 }), + standby_available: CondVar::new(), + closed: AtomicBool::new(false), + active_render_passes: AtomicU32::new(credits), + shared: shared.clone(), + }, 0).unwrap(); + let (vm, released) = MockVm::tracked(cache.clone()); + let vm = Arc::new(VmState { id: 1, slot: 1, generation: 1, vm }, 0).unwrap(); + let replacement = crate::resources::vm(2); + let mut pools = Pools::new(&AsahiDrmDevice(Device)); + let budget = Budget::new().unwrap(); + for _ in 0..credits { + let credit = Budget::reserve(&budget, 1).unwrap().take().unwrap(); + cache.standby.lock().epochs.push(PbEpoch::new(&Factory, &vm, credit).unwrap(), 0).unwrap(); + } + let epoch = exposed_epoch(&budget, &vm, 0); + let newer = exposed_epoch(&budget, &replacement, 0); + for (owner, backing) in [(&vm, &epoch), (&replacement, &newer)] { + let binding = pools.bind(0, false); + pools.hold_alloc(0, owner, None, None).unwrap(); + pools.publish_flight(0); + pools.retire_flight(0, backing, binding, true).unwrap(); + } + let firmware = Firmware { + engine: Engine { shared: Some(shared) }, + pools, + slots: Slots::new().unwrap(), + }; + let prepared = Prepared { + active_renders: AtomicU32::new(credits), + unpublished_renders: AtomicU32::new(credits), + cache: Some(cache.clone()), + compute: None, + compute_ext: None, + compute_scs: false, + render: None, + render_scs: false, + render_ext: [], + pb_heap_ext: [], + pb_ext: [Some(Arc::new(PoolExtArena, 0).unwrap())], + }; + (firmware, cache, vm, epoch, released, prepared) + } + + fn exposed_epoch(budget: &Arc, vm: &Arc, slot: usize) -> Arc { + let credit = Budget::reserve(budget, 1).unwrap().take().unwrap(); + let e = PbEpoch::new(&Factory, vm, credit).unwrap(); + e.prepare(slot, crate::g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + e + } + + #[test] + fn cancel_last_unpublished_render_wakes_idle_reclaim_and_releases_asid() { + let (mut fw, cache, vm, epoch, released, job) = displaced_vm(1); + vm.vm.close(); + cache.closed.store(true, Ordering::Release); + cache.shared.wake_closed_vm_reclaim(); + fw.idle_poll(); + assert!(cache.shared.closed_vm_reclaim.load(Ordering::Acquire)); + assert_eq!(Arc::strong_count(&epoch), 2, "vm_last still holds the epoch"); + assert!(!cache.shared.poll_queued.load(Ordering::Acquire)); + drop(epoch); + drop(vm); + assert!(!released.load(Ordering::Acquire)); + + drop(job); + assert_eq!(cache.standby.lock().reserved, 0); + fw.idle_poll(); + assert!(!cache.shared.closed_vm_reclaim.load(Ordering::Acquire)); + assert!(released.load(Ordering::Acquire), "idle poll released the ASID and last PB epoch"); + } + + #[test] + fn passed_abort_returns_unpublished_credits_and_preserves_quarantine() { + let (mut fw, cache, vm, old_epoch, released, job) = displaced_vm(3); + let aborted = cache.standby.lock().epochs.pop().unwrap(); + aborted.prepare(1, crate::g16::hw::client::pb_heap(0), 512).unwrap(); + aborted.expose(); + fw.pools.bind(1, false); + fw.pools.hold_alloc(1, &vm, None, None).unwrap(); + fw.pools.publish_flight(1); + job.commit_render(1); + vm.vm.close(); + cache.closed.store(true, Ordering::Release); + cache.shared.wake_closed_vm_reclaim(); + fw.idle_poll(); + assert_eq!(Arc::strong_count(&old_epoch), 2); + assert_eq!(cache.standby.lock().reserved, 2); + + fw.pools.quarantine_flight(1, Some(aborted.clone())); + let retained = Arc::new(job, 0).unwrap(); + retained.discard_unpublished_renders(); + retained.discard_unpublished_renders(); + let reserved = cache.standby.lock().reserved; + assert_eq!(reserved, 0); + assert_eq!(cache.active_render_passes.load(Ordering::Acquire), 1); + fw.idle_poll(); + assert_eq!(Arc::strong_count(&old_epoch), 1, "vm_last released the displaced epoch"); + assert_eq!(fw.pools.quarantined_mask(), 1 << 1); + assert_eq!(Arc::strong_count(&aborted), 2); + assert!(retained.pb_ext[0].is_some(), "retained job still owns its arena"); + drop(old_epoch); + drop(aborted); + drop(vm); + assert!(!released.load(Ordering::Acquire), "quarantine pins the published ASID"); + drop(retained); + assert_eq!(cache.active_render_passes.load(Ordering::Acquire), 0); + } + } } pub mod boot {pub fn eproto()->crate::Error{crate::Error(71)}} + pub mod engine { + use core::sync::atomic::{AtomicU32, Ordering}; + pub static WMB_CALLS: AtomicU32 = AtomicU32::new(0); + pub fn wmb() { + WMB_CALLS.fetch_add(1, Ordering::SeqCst); + core::sync::atomic::fence(Ordering::SeqCst); + } + } + // Arenas here have the two base units. + pub mod params {pub fn compute_units()->usize{2}pub fn pb_heap_blocks()->u32{2048}pub fn pb_posted_blocks(heap:u32)->u32{heap}} pub struct Events{pub grow:crate::KVec<[u32;18]>} pub struct Firmware{pub pools:pools::Pools,pub events:Events} pub mod budget{__BUDGET__} + #[path="__ROOT__/rt.rs"]pub mod rt; #[path="__ROOT__/slots.rs"]pub mod slots; #[path="__ROOT__/pools.rs"]pub mod pools; } #[cfg(test)]mod resources { use super::*;use g16::{object::Objects,slots::{Slots,Claims},pools::PoolSet}; struct Arenas{compute:g16::resources::ComputeArena,render:g16::resources::RenderArena} + fn render_arena(passes:KVec)->g16::resources::RenderArena{ + g16::resources::RenderArena{ + passes, + tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + tilemap_last:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + tilemap_clean:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + heap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + } + } + fn find_va(va:u64)->sync::Arc{ + g16::object::ALL_OBJECTS.with(|a|a.borrow().iter().find(|obj|obj.va==va).unwrap().clone()) + } fn arenas(o:&mut Objects)->Arenas{ let mut compute=KVec::new();let mut passes=KVec::new(); - for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o,k,1).unwrap(),0).unwrap();} - Arenas{compute:g16::resources::ComputeArena{compute},render:g16::resources::RenderArena{passes,tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};2],tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};2]}} + let f=g16::object::Factory; + for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,&f,k,&crate::g16::object::test_unit_cmds(k)).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap();} + Arenas{compute:g16::resources::ComputeArena{compute,render:None,hw_slots:None},render:render_arena(passes)} } - fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<bool{let mut q=g16::slots::ScrubQueue::new();q.push_batch(batch);let mut wake=false;while let Some(mut item)=q.pop(){wake|=item.run_one();}wake} #[test]fn render_reuse_clears_only_previous_write_spans(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); s.claim_pass(&arena.render,0).unwrap(); @@ -206,16 +604,173 @@ def module(text, name): } #[test]fn production_allocations_are_aligned_disjoint_and_in_mesa_hole(){ let mut o=Objects::new();let slots=Slots::new().unwrap();let arena=arenas(&mut o); - let pools=PoolSet::new(&mut o).unwrap(); + let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); let mut aliases=Vec::new(); for a in &o.objects{if let Some(g)=a.gva{assert_eq!(a.client_leaf,Some(__PRIVATE_RW__),"private GPU alias must match qualified J713 NC RW PTE");let base=g-a.offset as u64;assert_eq!(base&0x3fff,0);assert_eq!(a.mapped&0x3fff,0);assert!(base>=0x7000000000);assert!(base+a.mapped as u64<=0x7100000000);aliases.push((base,base+a.mapped as u64));}} aliases.push((0x1000000000,0x1000010000)); // Per-VM context store. aliases.sort();for a in aliases.windows(2){assert!(a[0].1<=a[1].0,"overlap {:x?} {:x?}",a[0],a[1]);} for (k,s) in arena.compute.compute.iter().enumerate(){assert_eq!(s.work.lower_gva.unwrap()&0x3fff,0);assert_eq!(s.work.size,0x2000);assert_eq!(s.pool.size,0x2000000);assert_eq!(s.pool_state.size,0x20000);assert_eq!(s.page_list.size,0x4000);assert_eq!(s.context_store.size,0x40000);assert_eq!(s.pool_state.r32(0).unwrap()as u64 |((s.pool_state.r32(4).unwrap()as u64)<<32),s.pool.gva.unwrap());assert_eq!(pools.allocator_refs_for(k).unwrap().parameter_id,k as u32);} - assert_eq!(aliases.len(),43); + // One PB heap per VM, shared by both render allocators. + assert_eq!(aliases.len(),42); + } + #[test]fn firmware_cached_render_records_are_device_lifetime_and_never_owned_by_vm_arenas(){ + use g16::object::{Class,Placement,Request}; + let req=|class,client:Option<(u64,u64)>,lower:Option|Request{size:0x40,class,placement:Placement::Anywhere,offset:0,client,lower,cpu:true}; + // A per-VM arena cannot map a firmware-cached record (its teardown would unmap it), and + // a device-lifetime allocator cannot give one a client or lower alias. + let mut vm=Objects::new(); + assert!(matches!(vm.alloc(req(Class::FwCoherent,None,None)),Err(EINVAL))); + let mut dev=Objects::persistent(); + assert!(matches!(dev.alloc(req(Class::FwCoherent,Some((0x7040000000,g16::hw::pte::LEAF_NC)),None)),Err(EINVAL))); + assert!(dev.alloc(req(Class::FwCoherent,None,Some(0x70f1000000))).is_ok()); + // Two VMs' pass slot 3 share index 3's records; neither VM arena owns any of them. + let (mut a,mut b)=(Objects::new(),Objects::new()); + let pa=g16::slots::PassSlot::new(&mut a,3,1,&crate::g16::object::test_cmds(3)).unwrap(); + let pb=g16::slots::PassSlot::new(&mut b,3,1,&crate::g16::object::test_cmds(3)).unwrap(); + let records=|p:&g16::slots::PassSlot|[p.ta_seq.clone(),p.fs_seq.clone(),p.own_barrier.clone(),p.prev_barrier.clone(),p.ta_fs_barrier.clone(),p.fs_dep.clone(),p.compute_barrier.clone(),p.fs_compute_barrier.clone(),p.ta_work.clone(),p.fs_work.clone()]; + let (ra,rb)=(records(&pa),records(&pb)); + for (i,(x,y)) in ra.iter().zip(rb.iter()).enumerate(){ + assert!(crate::sync::Arc::ptr_eq(x,y)); + assert_eq!(x.class,Class::FwCoherent); + assert_eq!((x.gva,x.client_leaf),(None,None)); + // Only the work images have the (uncached) kernel GPU task lower alias. + assert_eq!(x.lower_gva.is_some(),i>=8); + } + assert!(ra[8..].iter().all(|o|o.lower_leaf==Some(g16::hw::pte::LOWER))); + assert_eq!((pa.refs().ta_work_gva,pa.refs().fs_work_gva),(pb.refs().ta_work_gva,pb.refs().fs_work_gva)); + assert_eq!((pa.refs().ta_work,pa.refs().ta_work_gva),(ra[8].va,ra[8].lower_gva.unwrap())); + assert!(a.objects.iter().chain(b.objects.iter()).all(|o|o.class!=Class::FwCoherent)); + assert!(a.objects.iter().chain(b.objects.iter()).all(|o|ra.iter().all(|r|!crate::sync::Arc::ptr_eq(o,r)))); + let pc=g16::slots::PassSlot::new(&mut b,4,1,&crate::g16::object::test_cmds(4)).unwrap(); + assert!(!crate::sync::Arc::ptr_eq(&pc.ta_seq,&pa.ta_seq)&&!crate::sync::Arc::ptr_eq(&pc.own_barrier,&pa.own_barrier)); + // Microsequences keep whole pages; the barrier records are disjoint 0x40-aligned + // records of one page; the encoders name the shared records. + assert_eq!((pa.ta_seq.va&0x3fff,pa.fs_seq.va&0x3fff),(0,0)); + let page=ra[2].va&!0x3fff; + let mut spans:Vec<(u64,u64)>=ra[2..8].iter().map(|o|(o.va,o.va+o.size as u64)).collect(); + spans.sort(); + assert!(spans.windows(2).all(|w|w[0].1<=w[1].0)); + assert!(ra[2..8].iter().all(|o|o.va&!0x3fff==page&&o.va%0x40==0&&o.va+o.size as u64<=page+0x4000)); + assert_eq!((pa.refs().ta_seq,pa.refs().fs_seq),(pb.refs().ta_seq,pb.refs().fs_seq)); + assert_eq!((pa.refs().ta_seq,pa.refs().fs_seq),(pa.ta_seq.va,pa.fs_seq.va)); + // Closing VM a drops its arena and pass slot: the device table still owns and hands + // out the same records, mapped by its never-dropped allocator. + drop(pa);drop(a); + let again=crate::g16::object::test_cmds(3); + assert!(crate::sync::Arc::ptr_eq(&again.ta_seq,&rb[0])&&crate::sync::Arc::ptr_eq(&again.fs_dep,&rb[5])); + crate::g16::object::PERSISTENT.with(|p|{ + let p=p.borrow();let owned=&p.as_ref().unwrap().objects; + assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[0]))); + assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[1]))); + assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[8]))); + assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[9]))); + assert!(owned.iter().all(|o|o.class==Class::FwCoherent)); + }); + drop(pb);drop(pc);drop(b); + } + #[test]fn firmware_cached_compute_records_and_work_rings_are_device_lifetime_and_never_owned_by_vm_arenas(){ + use g16::graph::{ComputeGraph, RenderGraph}; + use g16::object::{Class, Placement, Request}; + use g16::slots::{ComputeSlot, Placement as SlotPlacement, UnitCmds}; + let mut vm_a = Objects::new(); + let mut vm_b = Objects::new(); + let f = g16::object::Factory; + // Per-VM non-persistent allocator refuses UnitCmds (Class::FwCoherent). + assert!(matches!(UnitCmds::new(&mut vm_a, 3), Err(EINVAL))); + // Normal VM unit 3 and an SCS VM local unit 0 bound to hardware slot 3 share slot 3's + // device-lifetime work + seq + barrier records; neither VM arena owns any FwCoherent object. + let ca = ComputeSlot::new(&mut vm_a, &f, 3, &g16::object::test_unit_cmds(3)).unwrap(); + let cb = ComputeSlot::new_in( + &mut vm_b, + &f, + 0, + 3, + SlotPlacement::Scs { seeds: 8192 }, + &g16::object::test_unit_cmds(3), + ) + .unwrap(); + let ra = [ca.work.clone(), ca.seq.clone(), ca.barrier.clone()]; + let rb = [cb.work.clone(), cb.seq.clone(), cb.barrier.clone()]; + for (idx, (x, y)) in ra.iter().zip(rb.iter()).enumerate() { + assert!(crate::sync::Arc::ptr_eq(x, y)); + assert_eq!(x.class, Class::FwCoherent); + assert_eq!((x.gva, x.client_leaf), (None, None)); + assert_eq!(x.lower_gva.is_some(), idx == 0); + assert_eq!(x.va & 0x3fff, 0); + } + assert_ne!(ca.work.va, ca.seq.va); + assert_ne!(ca.seq.va, ca.barrier.va); + assert_eq!(ca.descriptor.class, Class::Fw); + assert_eq!(cb.descriptor.class, Class::Fw); + assert_ne!(ca.descriptor.va, cb.descriptor.va); + assert!(vm_a.objects.iter().chain(vm_b.objects.iter()).all(|o| o.class != Class::FwCoherent)); + assert!(vm_a + .objects + .iter() + .chain(vm_b.objects.iter()) + .all(|o| ra.iter().all(|r| !crate::sync::Arc::ptr_eq(o, r)))); + // Distinct hardware slot gets distinct UnitCmds. + let cc = ComputeSlot::new(&mut vm_b, &f, 4, &g16::object::test_unit_cmds(4)).unwrap(); + assert!(!crate::sync::Arc::ptr_eq(&cc.work, &ca.work)); + assert!(!crate::sync::Arc::ptr_eq(&cc.seq, &ca.seq)); + assert!(!crate::sync::Arc::ptr_eq(&cc.barrier, &ca.barrier)); + // Closing VM a leaves slot 3's UnitCmds owned by the device-lifetime allocator. + drop(ca); + drop(vm_a); + let again = g16::object::test_unit_cmds(3); + assert!(crate::sync::Arc::ptr_eq(&again.work, &rb[0])); + assert!(crate::sync::Arc::ptr_eq(&again.seq, &rb[1])); + assert!(crate::sync::Arc::ptr_eq(&again.barrier, &rb[2])); + g16::object::PERSISTENT.with(|p| { + let p = p.borrow(); + let owned = &p.as_ref().unwrap().objects; + assert!(owned.iter().any(|o| crate::sync::Arc::ptr_eq(o, &rb[0]))); + assert!(owned.iter().any(|o| crate::sync::Arc::ptr_eq(o, &rb[1]))); + assert!(owned.iter().any(|o| crate::sync::Arc::ptr_eq(o, &rb[2]))); + assert!(owned.iter().all(|o| o.class == Class::FwCoherent)); + }); + // Work rings require a device-lifetime persistent allocator and never live in session o. + let mut session = Objects::new(); + let mut non_persistent = Objects::new(); + let mut rings = Objects::persistent(); + let ctx = session + .alloc(Request { + size: 0x40, + class: Class::Fw, + placement: Placement::Anywhere, + offset: 0, + client: None, + lower: None, + cpu: true, + }) + .unwrap(); + assert!(matches!( + ComputeGraph::new(&mut session, &mut non_persistent, ctx.clone()), + Err(EINVAL) + )); + assert!(matches!( + RenderGraph::new(&mut session, &mut non_persistent, ctx.clone()), + Err(EINVAL) + )); + let cg0 = ComputeGraph::new(&mut session, &mut rings, ctx.clone()).unwrap(); + let cg1 = ComputeGraph::new(&mut session, &mut rings, ctx.clone()).unwrap(); + let rg = RenderGraph::new(&mut session, &mut rings, ctx).unwrap(); + let all_rings = [&cg0.ring, &cg1.ring, &rg.ring[0], &rg.ring[1]]; + assert_eq!(rings.objects.len(), 4); + for ring in all_rings { + assert_eq!(ring.class, Class::FwCoherent); + assert_eq!((ring.gva, ring.client_leaf, ring.lower_gva), (None, None, None)); + assert!(rings.objects.iter().any(|o| crate::sync::Arc::ptr_eq(o, ring))); + assert!(session.objects.iter().all(|o| !crate::sync::Arc::ptr_eq(o, ring))); + } + drop(cb); + drop(cc); + drop(vm_b); } #[test]fn work_has_kernel_lower_alias_without_application_alias(){ let mut o=Objects::new();let slots=Slots::new().unwrap();let arena=arenas(&mut o); + assert!(arena.compute.compute.iter().all(|s|s.work.class==g16::object::Class::FwCoherent)); + assert!(arena.render.passes.iter().all(|s|s.ta_work.class==g16::object::Class::FwCoherent&&s.fs_work.class==g16::object::Class::FwCoherent)); let work=arena.compute.compute.iter().map(|s|&s.work) .chain(arena.render.passes.iter().flat_map(|s|[&s.ta_work,&s.fs_work])); for object in work { @@ -223,7 +778,7 @@ def module(text, name): assert_eq!(object.client_leaf,None); assert!(object.lower_gva.is_some()); assert_eq!(object.lower_leaf,Some(0x00c0000000000c8b)); - assert_eq!(object.class,g16::object::Class::Shared); + assert!(object.class==g16::object::Class::Shared||object.class==g16::object::Class::FwCoherent); assert!(object.va>=0xfffffc2000000000); let lower=object.lower_gva.unwrap(); for client in &o.objects { @@ -240,21 +795,22 @@ def module(text, name): } } for s in arena.render.passes.iter() { - for object in [&s.tpc,&s.tilemap,&s.heap,&s.scene_user,&s.fs_scratch,&s.aux] { + for object in [&s.tpc,&s.tilemap,&s.heap,&s.scene_user,&s.scene_list,&s.fs_scratch,&s.aux] { assert_eq!(object.client_leaf,Some(0x00c0000000000c8b)); assert!(object.gva.is_some()); } let refs=s.refs(); assert_eq!(refs.ta_work_gva,s.ta_work.lower_gva.unwrap()); assert_eq!(refs.fs_work_gva,s.fs_work.lower_gva.unwrap()); + assert_eq!(refs.scene_list,s.scene_list.gva.unwrap()); } } #[test]fn allocator_metadata_is_firmware_only_and_shared_state_keeps_real_backing(){ - let mut o=Objects::new();let pools=PoolSet::new(&mut o).unwrap(); + let mut o=Objects::new();let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); let read64=|obj:&g16::object::FwObject,at:usize|->u64{obj.r32(at).unwrap()as u64|((obj.r32(at+4).unwrap()as u64)<<32)}; for k in 0..2 { let refs=pools.allocator_refs_for(k).unwrap(); - let descriptor=o.objects.iter().find(|obj|obj.va==refs.uma_mgr[0]).unwrap(); + let descriptor=find_va(refs.uma_mgr[0]); let auxiliary=o.objects.iter().find(|obj|obj.va+0x100==refs.uma_aux[0]).unwrap(); assert_eq!(descriptor.class,g16::object::Class::Fw); assert_eq!(descriptor.gva,None);assert_eq!(descriptor.client_leaf,None); @@ -277,8 +833,8 @@ def module(text, name): } assert_eq!(metadata,descriptor.snapshot()); // Freelist and pool-table pointers still select writable client mappings. - let state_va=read64(descriptor,g16::fw::graph::manager::FREELIST); - let list_va=read64(descriptor,g16::fw::graph::manager::POOL_TABLE); + let state_va=read64(&descriptor,g16::fw::graph::manager::FREELIST); + let list_va=read64(&descriptor,g16::fw::graph::manager::POOL_TABLE); for va in [list_va,state_va] { let shared=o.objects.iter().find(|obj|obj.gva==Some(va)).unwrap(); assert_eq!(shared.class,g16::object::Class::Shared); @@ -296,19 +852,19 @@ def module(text, name): arena.compute.compute[0].pool_state.w64(8,0xdeadbeef).unwrap(); arena.compute.compute[0].page_list.w64(0x1000,0xaabbccdd).unwrap(); let a=arena.compute.compute[0].pool_state.snapshot();let b=arena.compute.compute[0].page_list.snapshot(); - let mut c=Claims::new();assert_eq!(s.claim_compute(&arena.compute,&mut c,0).unwrap(),Some(0));s.publish(&c).unwrap();s.retire(&mut c).unwrap(); - assert_eq!(s.free_compute(),1);assert_eq!(s.claim_compute(&arena.compute,&mut c,0).unwrap(),Some(1));s.publish(&c).unwrap();s.retire(&mut c).unwrap(); + let mut c=Claims::new();assert_eq!(s.claim_compute(&arena.compute,&mut c,0).unwrap(),Some(0));s.publish(&mut c).unwrap();s.retire(&mut c).unwrap(); + assert_eq!(s.free_compute(),1);assert_eq!(s.claim_compute(&arena.compute,&mut c,0).unwrap(),Some(1));s.publish(&mut c).unwrap();s.retire(&mut c).unwrap(); arena.compute.compute[0].counter.w64(0,91).unwrap(); assert_eq!(s.claim_compute(&arena.compute,&mut c,0).unwrap(),Some(0)); assert_eq!(a,arena.compute.compute[0].pool_state.snapshot());assert_eq!(b,arena.compute.compute[0].page_list.snapshot());assert_eq!(arena.compute.compute[0].counter.r32(0).unwrap(),91); - s.publish(&c).unwrap();s.quarantine(&mut c);assert!(s.compute_exhausted()); + s.publish(&mut c).unwrap();s.quarantine(&mut c);assert!(s.compute_exhausted()); } #[test]fn production_render_descriptors_preserve_firmware_bytes_and_exact_counter(){ - let mut o=Objects::new();let mut pools=PoolSet::new(&mut o).unwrap(); + let mut o=Objects::new();let mut pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); let a=pools.prepare(0,1).unwrap();assert!(a.init_buffer);assert_eq!(a.uma_submitted,2); - assert!(!pools.retired(0).unwrap());pools.publish(0,2).unwrap(); - assert!(pools.publish(0,2).is_err());assert!(pools.prepare(0,2).is_err()); - let d=o.objects.iter().find(|o|o.va==a.uma_mgr[0]).unwrap(); + assert!(!pools.retired(0).unwrap());pools.publish_batch(0,2,1).unwrap(); + assert!(pools.publish_batch(0,2,1).is_err());assert!(pools.prepare(0,2).is_err()); + let d=find_va(a.uma_mgr[0]); d.w64(0x54,2).unwrap();d.w64(0x60,0x5a5aa5a5).unwrap(); let original=d.snapshot();assert!(pools.retired(0).unwrap()); let next=pools.prepare(0,2).unwrap();assert!(next.init_buffer);assert_eq!(next.uma_submitted,4); @@ -317,15 +873,21 @@ def module(text, name): #[test]fn cross_vm_evidence_counts_only_noted_publication(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); - let a=sync::Arc::new(g16::vm::VmState{id:100,slot:1,generation:1,vm:()},0).unwrap(); - let b=sync::Arc::new(g16::vm::VmState{id:101,slot:2,generation:1,vm:()},0).unwrap(); - let c=sync::Arc::new(g16::vm::VmState{id:102,slot:3,generation:9,vm:()},0).unwrap(); + let a=sync::Arc::new( + g16::vm::VmState{id:100,slot:1,generation:1,vm:g16::vm::MockVm::new()},0, + ).unwrap(); + let b=sync::Arc::new( + g16::vm::VmState{id:101,slot:2,generation:1,vm:g16::vm::MockVm::new()},0, + ).unwrap(); + let c=sync::Arc::new( + g16::vm::VmState{id:102,slot:3,generation:9,vm:g16::vm::MockVm::new()},0, + ).unwrap(); let mut claims=Claims::new(); - for vm in [&a,&b]{s.claim_compute(&arena.compute,&mut claims,0).unwrap().unwrap();s.hold_vm(&claims,vm).unwrap();s.publish(&claims).unwrap();s.note_published(&claims);s.retire(&mut claims).unwrap();} + for vm in [&a,&b]{s.claim_compute(&arena.compute,&mut claims,0).unwrap().unwrap();s.hold_vm(&claims,vm).unwrap();s.publish(&mut claims).unwrap();s.note_published(&claims);s.retire(&mut claims).unwrap();} assert_eq!(s.stats.cross_vm_retargets,[0,0]); assert_eq!(s.claim_compute(&arena.compute,&mut claims,0).unwrap(),Some(0)); s.hold_vm(&claims,&c).unwrap();assert_eq!(s.stats.cross_vm_retargets,[0,0]); - s.publish(&claims).unwrap();assert_eq!(s.stats.cross_vm_retargets,[0,0]); + s.publish(&mut claims).unwrap();assert_eq!(s.stats.cross_vm_retargets,[0,0]); s.note_published(&claims);assert_eq!(s.stats.cross_vm_retargets,[1,0]); let proof=s.stats.last_retarget[0]; assert_eq!((proof.unit,proof.old_vm,proof.new_vm),(0,100,102)); @@ -336,14 +898,18 @@ def module(text, name): s.release(&mut claims);s.note_published(&claims);assert_eq!(s.stats.cross_vm_retargets,[1,0]); } - fn vm(id:u64)->sync::Arc{sync::Arc::new(g16::vm::VmState{id,slot:id as u32,generation:1,vm:()},0).unwrap()} + pub(super) fn vm(id:u64)->sync::Arc{ + sync::Arc::new( + g16::vm::VmState{id,slot:id as u32,generation:1,vm:g16::vm::MockVm::new()},0, + ).unwrap() + } #[test]fn previous_vm_lease_survives_replacement_publication_until_full_retirement(){ let mut o=Objects::new();let arena=arenas(&mut o);let mut s=Slots::new().unwrap(); let a=vm(1);let b=vm(2);let c=vm(3);let mut claims=Claims::new(); - for owner in [&a,&b]{s.claim_compute(&arena.compute,&mut claims,0).unwrap().unwrap();s.hold_vm(&claims,owner).unwrap();s.publish(&claims).unwrap();s.retire(&mut claims).unwrap();} + for owner in [&a,&b]{s.claim_compute(&arena.compute,&mut claims,0).unwrap().unwrap();s.hold_vm(&claims,owner).unwrap();s.publish(&mut claims).unwrap();s.retire(&mut claims).unwrap();} assert_eq!(sync::Arc::strong_count(&a),2); assert_eq!(s.claim_compute(&arena.compute,&mut claims,0).unwrap(),Some(0)); - s.hold_vm(&claims,&c).unwrap();s.publish(&claims).unwrap();s.note_published(&claims); + s.hold_vm(&claims,&c).unwrap();s.publish(&mut claims).unwrap();s.note_published(&claims); assert_eq!(sync::Arc::strong_count(&a),2,"publication cannot release old ASID/backing"); assert_eq!(sync::Arc::strong_count(&c),2,"candidate must be held too"); s.retire(&mut claims).unwrap(); @@ -352,7 +918,7 @@ def module(text, name): #[test]fn cancel_releases_candidate_but_quarantine_preserves_both_vm_leases(){ let mut o=Objects::new();let arena=arenas(&mut o);let mut s=Slots::new().unwrap(); let a=vm(1);let b=vm(2);let c=vm(3);let mut claims=Claims::new(); - for owner in [&a,&b]{s.claim_compute(&arena.compute,&mut claims,0).unwrap().unwrap();s.hold_vm(&claims,owner).unwrap();s.publish(&claims).unwrap();s.retire(&mut claims).unwrap();} + for owner in [&a,&b]{s.claim_compute(&arena.compute,&mut claims,0).unwrap().unwrap();s.hold_vm(&claims,owner).unwrap();s.publish(&mut claims).unwrap();s.retire(&mut claims).unwrap();} s.claim_compute(&arena.compute,&mut claims,0).unwrap();s.hold_vm(&claims,&c).unwrap();s.release(&mut claims); assert_eq!(sync::Arc::strong_count(&a),2);assert_eq!(sync::Arc::strong_count(&c),1); s.claim_compute(&arena.compute,&mut claims,0).unwrap();s.hold_vm(&claims,&c).unwrap(); @@ -362,10 +928,10 @@ def module(text, name): #[test]fn pb_installations_are_fresh_and_exposed_records_cannot_be_reinitialized(){ let vm=vm(1);let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); let a=g16::pools::PbEpoch::new(&factory,&vm,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); - a.prepare(0,0x70c0000000).unwrap();a.check_assignment(0).unwrap();a.expose(); + a.prepare(0,0x70c0000000,2048).unwrap();a.check_assignment(0).unwrap();a.expose(); a.manager.w64(0xb0,0x123456789abcdef0).unwrap();let saved=a.manager.snapshot(); - assert_eq!(a.prepare(0,0x70c0000000),Err(EINVAL));assert_eq!(saved,a.manager.snapshot()); - let b=g16::pools::PbEpoch::new(&factory,&vm,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap();b.prepare(0,0x70c0000000).unwrap(); + assert_eq!(a.prepare(0,0x70c0000000,2048),Err(EINVAL));assert_eq!(saved,a.manager.snapshot()); + let b=g16::pools::PbEpoch::new(&factory,&vm,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap();b.prepare(0,0x70c0000000,2048).unwrap(); assert!(!std::ptr::eq(&a.manager.data,&b.manager.data)); assert_eq!(b.manager.class,g16::object::Class::Fw);assert_eq!(b.manager.gva,None); let mut slots=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); @@ -373,9 +939,2524 @@ def module(text, name): b.check_assignment(0).unwrap();b.expose();assert_eq!(sync::Arc::strong_count(&a),2); slots.retire_binding(0,&b).unwrap();assert_eq!(sync::Arc::strong_count(&a),1); } + #[test]fn pb_reuse_needs_the_same_binding_vm_and_a_completed_render_and_holds_nothing(){ + let one=vm(1);let two=vm(2);let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); + let a=g16::pools::PbEpoch::new(&factory,&one,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); + a.prepare(0,0x70c0000000,2048).unwrap();a.check_assignment(0).unwrap();a.expose(); + let mut p=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let n=p.bind(0,false);p.retire_binding(0,&a).unwrap();p.retire_epoch(0,n,true); + assert_eq!(sync::Arc::strong_count(&a),2,"only the owner lease"); + let r=p.reusable(0,&one).unwrap();assert!(sync::Arc::ptr_eq(&r,&a));drop(r); + assert_eq!(sync::Arc::strong_count(&a),2); + assert!(p.reusable(0,&two).is_none(),"another VM");assert!(p.reusable(1,&one).is_none(),"another slot"); + assert_eq!(p.bind(0,true),n);p.retire_epoch(0,n,true);assert!(p.reusable(0,&one).is_some()); + p.retire_epoch(0,n,false);assert!(p.reusable(0,&one).is_none(),"failed render"); + p.retire_epoch(0,n,true);p.forget(0);assert!(p.reusable(0,&one).is_none(),"aborted render"); + let m=p.bind(0,false);assert_ne!(m,n);p.retire_epoch(0,n,true); + assert!(p.reusable(0,&one).is_none(),"a stale binding after a fresh one"); + p.retire_epoch(0,m,true);assert!(p.reusable(0,&one).is_some()); + p.invalidate();assert!(p.reusable(0,&one).is_none(),"recovery"); + p.retire_epoch(0,m,true);assert!(p.reusable(0,&one).is_none(),"a render retiring after recovery"); + assert_eq!(p.bind(0,true),m.wrapping_add(1)); + assert_eq!(sync::Arc::strong_count(&a),2); + } + + #[test]fn standby_pool_reuses_epochs_at_depth_16_and_drains_on_close(){ + // Models Cache's Standby invariant: epochs.len() >= reserved while open or draining. + let one=vm(1);let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); + let mut epochs:Vec>=Vec::new(); + let mut reserved:u32=0; + let mut allocs:u32=0; + let prepare=|n:u32,epochs:&mut Vec>,reserved:&mut u32,allocs:&mut u32|{ + let deficit=reserved.checked_add(n).unwrap().saturating_sub(epochs.len() as u32); + if deficit!=0 { + let mut res=g16::budget::Budget::reserve(&budget,deficit).unwrap(); + for _ in 0..deficit { + epochs.push(g16::pools::PbEpoch::new(&factory,&one,res.take().unwrap()).unwrap()); + *allocs+=1; + } + } + *reserved+=n; + assert!(epochs.len()>=*reserved as usize); + }; + // Ramp to depth 16: allocates 16 standby epochs once. + for _ in 0..16 { prepare(1,&mut epochs,&mut reserved,&mut allocs); } + assert_eq!((allocs,epochs.len(),reserved),(16,16,16)); + // Steady-state d=16 with PB reuse: 64 more submits allocate zero new epochs. + for _ in 0..64 { + reserved-=1; // previous render committed with reused PB + prepare(1,&mut epochs,&mut reserved,&mut allocs); + } + assert_eq!((allocs,epochs.len(),reserved),(16,16,16)); + // One fresh InitBM consumes 1 standby epoch and commits 1 reservation; next submit refills 1. + let fresh=epochs.pop().unwrap(); + assert!(fresh.unexposed()); + fresh.prepare(0,0x70c0000000,2048).unwrap(); + fresh.expose(); + reserved-=1; + assert_eq!((epochs.len(),reserved),(15,15)); + prepare(1,&mut epochs,&mut reserved,&mut allocs); + assert_eq!((allocs,epochs.len(),reserved),(17,16,16)); + // Unpublished rollback returns the unexposed epoch without losing capacity. + let rolled=epochs.pop().unwrap(); + assert!(rolled.unexposed()); + epochs.push(rolled); + assert_eq!(epochs.len(),16); + // Closing trims surplus immediately while preserving reserved epochs until jobs finish. + reserved=2; + epochs.truncate(reserved as usize); + assert_eq!(epochs.len(),2); + reserved=0; + epochs.truncate(reserved as usize); + assert!(epochs.is_empty()); + drop(fresh); + assert_eq!(sync::Arc::strong_count(&one),1); + } + + #[test]fn compute_same_vm_reuse_skips_bulk_scrub_and_cross_vm_or_recovery_full_scrubs(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); + let a=vm(1);let b=vm(2);let mut c=Claims::new(); + // First use of units 0 and 1 runs full scrub (context_store + aux + preempt + seq + its). + for _ in 0..2 { + let k=s.claim_compute_for(&arena.compute,&mut c,Some(a.id)).unwrap().unwrap(); + assert_eq!(arena.compute.compute[k].context_store.fills.lock().unwrap().len(),1); + assert_eq!(arena.compute.compute[k].its.fills.lock().unwrap().len(),1); + s.hold_vm(&c,&a).unwrap();s.publish(&mut c).unwrap();s.retire(&mut c).unwrap(); + } + // Same-VM clean reuse of unit 0 clears ONLY its (16 B), skipping context_store/aux/preempt/seq. + let k=s.claim_compute_for(&arena.compute,&mut c,Some(a.id)).unwrap().unwrap(); + assert_eq!(k,0); + assert!(!s.compute_needs_full_work(0)); + assert_eq!(arena.compute.compute[0].its.fills.lock().unwrap().len(),2); + assert_eq!(arena.compute.compute[0].context_store.fills.lock().unwrap().len(),1); + assert_eq!(arena.compute.compute[0].preempt.fills.lock().unwrap().len(),1); + assert_eq!(arena.compute.compute[0].aux.fills.lock().unwrap().len(),1); + s.hold_vm(&c,&a).unwrap();s.publish(&mut c).unwrap();s.retire(&mut c).unwrap(); + // Cross-VM switch on unit 1 runs full scrub. + let k=s.claim_compute_for(&arena.compute,&mut c,Some(b.id)).unwrap().unwrap(); + assert_eq!(k,1); + assert!(s.compute_needs_full_work(1)); + assert_eq!(arena.compute.compute[1].context_store.fills.lock().unwrap().len(),2); + assert_eq!(arena.compute.compute[1].preempt.fills.lock().unwrap().len(),2); + s.hold_vm(&c,&b).unwrap();s.publish(&mut c).unwrap();s.retire(&mut c).unwrap(); + // Firmware recovery forces full scrub even for same VM. + s.invalidate_scrub(); + let k=s.claim_compute_for(&arena.compute,&mut c,Some(a.id)).unwrap().unwrap(); + assert_eq!(k,0); + assert!(s.compute_needs_full_work(0)); + assert_eq!(arena.compute.compute[0].context_store.fills.lock().unwrap().len(),2); + // Cancelled preparation forces full scrub on next claim. + s.release(&mut c); + let k=s.claim_compute_for(&arena.compute,&mut c,Some(a.id)).unwrap().unwrap(); + assert_eq!(k,0); + assert!(s.compute_needs_full_work(0)); + assert_eq!(arena.compute.compute[0].context_store.fills.lock().unwrap().len(),3); + s.hold_vm(&c,&a).unwrap();s.publish(&mut c).unwrap();s.retire(&mut c).unwrap(); + } + + #[test]fn pass_same_vm_reuse_skips_bulk_scrub_and_preserves_tpc_dirty_for_full_scrub(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); + let a=vm(1);let b=vm(2); + let retire=|s:&mut Slots,k:usize,owner:&sync::Arc|{ + let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1< MAX_CLIENT" + ); + } + let mut aliases=Vec::new(); + for a in &o.objects { + if let Some(g)=a.gva { + let base=g-a.offset as u64; + assert_eq!(base&0x3fff,0); + assert!(base>=0x7000000000 && base+a.mapped as u64<=0x7100000000); + // Must stay disjoint from the dynamic client range 0x7040000000..0x7080000000. + assert!(base+a.mapped as u64<=0x7040000000 || base>=0x7080000000, + "overlap with dynamic client range: {:#x}..{:#x}", base, base+a.mapped as u64); + aliases.push((base,base+a.mapped as u64)); + } + } + aliases.sort(); + for w in aliases.windows(2) { + assert!(w[0].1<=w[1].0,"overlap {:x?} {:x?}",w[0],w[1]); + } + } + + #[test]fn decoupled_pb_allocator_supports_same_vm_pipelining_cross_vm_displacement_and_abort(){ + let mut o=Objects::new();let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); + let vm1=vm(1);let vm2=vm(2);let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); + let e1=g16::pools::PbEpoch::new(&factory,&vm1,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); + e1.prepare(0,0x70c0000000,2048).unwrap();e1.check_assignment(0).unwrap();e1.expose(); + let e2=g16::pools::PbEpoch::new(&factory,&vm2,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); + e2.prepare(1,0x70c0000000,2048).unwrap();e2.check_assignment(1).unwrap();e2.expose(); + let mut p=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + // Priming render on slot 0 (VM1). + assert_eq!(p.pick_slot(&vm1,false),Some(0)); + let b1=p.bind(0,false); + let a1=pools.prepare_in_flight(0,1,false).unwrap(); + assert_eq!(a1.uma_submitted,2); + pools.publish_batch(0,2,1).unwrap();p.publish_flight(0); + let d0=find_va(a1.uma_mgr[0]); + d0.w64(0x54,2).unwrap(); + p.retire_flight(0,&e1,b1,true).unwrap(); + // Same-VM pipelining: 3 concurrent renders share slot 0 with cumulative uma_submitted (4, 6, 8). + assert!(p.can_pipeline(&vm1)); + assert!(!p.can_pipeline(&vm2)); + for draw in 2..=4u64 { + assert_eq!(p.pick_slot(&vm1,draw>2),Some(0)); + let refs=pools.prepare_in_flight(0,draw,draw>2).unwrap(); + assert_eq!(refs.uma_submitted,draw*2); + pools.publish_batch(0,refs.uma_submitted,1).unwrap(); + p.publish_flight(0); + } + assert!(!pools.retired_at(0,4).unwrap()); + d0.w64(0x54,4).unwrap(); + assert!(pools.retired_at(0,4).unwrap()); + assert!(!pools.retired_at(0,6).unwrap()); + p.retire_flight(0,&e1,b1,true).unwrap(); + d0.w64(0x54,6).unwrap(); + assert!(pools.retired_at(0,6).unwrap()); + p.retire_flight(0,&e1,b1,true).unwrap(); + d0.w64(0x54,8).unwrap(); + assert!(pools.retired(0).unwrap()); + p.retire_flight(0,&e1,b1,true).unwrap(); + // Cross-VM switch drains and switches to slot 1 (displacing slot 0 upon clean retirement). + assert_eq!(p.pick_slot(&vm2,false),Some(1)); + let b2=p.bind(1,false); + p.publish_flight(1); + p.retire_flight(1,&e2,b2,true).unwrap(); + assert!(!p.exhausted()); + assert_eq!(p.needed_slots(),g16::hw::sizes::BASE_PB_SLOTS); + // Normal cross-VM switch back to VM1 reuses displaced slot 0 rather than claiming slot 2. + assert_eq!(p.pick_slot(&vm1,false),Some(0)); + } + + #[test]fn render_allocators_use_distinct_uma_slots_within_firmware_window(){ + let mut o=Objects::new(); + let f=g16::object::Factory; + let pools=PoolSet::new_with_slots(&mut o,&f,[7,8]).unwrap(); + assert_eq!(pools.unit(0).unwrap().id(),7); + assert_eq!(pools.unit(1).unwrap().id(),8); + let scs=pools.scs(&mut o,&f,g16::hw::sizes::FREELIST_SEED + 512).unwrap(); + assert_eq!(scs.unit(0).unwrap().id(),7); + assert_eq!(scs.unit(1).unwrap().id(),8); + assert_eq!( + g16::pools::Allocator::new_at( + &mut o, + &f, + g16::hw::sizes::MAX_VM_PB_SLOTS as u64, + 0, + pools.heap(), + g16::slots::Placement::Base + ).err(), + Some(EINVAL) + ); + assert_eq!( + g16::pools::Allocator::new_at( + &mut o, + &f, + 0, + g16::hw::sizes::PB_SLOTS as u32, + pools.heap(), + g16::slots::Placement::Base + ).err(), + Some(EINVAL) + ); + let mut uma_slots=Vec::new(); + for k in 0..g16::hw::sizes::PB_SLOTS { + let local=(k % g16::hw::sizes::MAX_VM_PB_SLOTS) as u64; + let alloc=g16::pools::Allocator::new_at(&mut o,&f,local,k as u32,pools.heap(),g16::slots::Placement::Base).unwrap(); + let refs=alloc.prepare_in_flight(1,false).unwrap(); + assert_eq!(refs.parameter_id,k as u32); + let desc=find_va(refs.uma_mgr[0]); + let slot_id=desc.r32(8).unwrap(); + let expected=g16::hw::engine::RENDER_UMA_SLOT+k as u32; + assert_eq!(slot_id,expected); + assert!(slot_id>=33 && slot_id<=64); + assert!(!uma_slots.contains(&slot_id)); + uma_slots.push(slot_id); + // Tampering with the descriptor UMA slot ID is rejected before publication. + desc.write(8,&(expected+1).to_le_bytes()).unwrap(); + assert_eq!(alloc.prepare_in_flight(1,false).err(),Some(EINVAL)); + } + } + + #[test]fn multi_active_pools_allow_warm_cross_vm_reuse_and_gate_cold_initbm(){ + let vm1=vm(1);let vm2=vm(2);let vm3=vm(3); + let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); + let mk_epoch=|owner:&sync::Arc,slot:usize|{ + let e=g16::pools::PbEpoch::new(&factory,owner,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); + e.prepare(slot,0x70c0000000,2048).unwrap();e.check_assignment(slot).unwrap();e.expose(); + e + }; + let mut p=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + // Prime VM1 on slot 0 and VM2 on slot 1 (drained InitBM). + let e1=mk_epoch(&vm1,0); + assert_eq!(p.pick_slot_within(&vm1,false,2),Some(0)); + let b1=p.bind(0,false);p.publish_flight(0);p.retire_flight(0,&e1,b1,true).unwrap(); + let e2=mk_epoch(&vm2,1); + assert_eq!(p.pick_slot_within(&vm2,false,2),Some(1)); + let b2=p.bind(1,false);p.publish_flight(1);p.retire_flight(1,&e2,b2,true).unwrap(); + // VM1 starts a render on warm slot 0 (no InitBM). + assert_eq!(p.pick_slot_within(&vm1,false,2),Some(0)); + assert!(p.reusable(0,&vm1).is_some()); + let b1=p.bind(0,true);p.publish_flight(0); + assert_eq!(p.slot_inflight(0),1); + assert_eq!(p.slot_inflight(1),0); + // While VM1 is live on slot 0 (behind=true): + // - Warm VM2 pipelines onto its own slot 1 without InitBM or drain. + // - Cold VM3 has no warm slot and returns None so the engine drains before InitBM. + assert!(p.can_pipeline_within(&vm2,2)); + assert_eq!(p.pick_slot_within(&vm2,true,2),Some(1)); + assert!(!p.can_pipeline_within(&vm3,2)); + assert_eq!(p.pick_slot_within(&vm3,true,2),None); + // VM2 publishes on slot 1 concurrently with VM1 on slot 0. + let b2=p.bind(1,true);p.publish_flight(1); + assert_eq!(p.slot_inflight(0),1); + assert_eq!(p.slot_inflight(1),1); + // Neither in-flight slot is displaced while live. + assert!(!p.exhausted()); + // Both retire cleanly in order. + p.retire_flight(0,&e1,b1,true).unwrap(); + assert_eq!(p.slot_inflight(0),0); + assert_eq!(p.slot_inflight(1),1); + p.retire_flight(1,&e2,b2,true).unwrap(); + assert_eq!(p.slot_inflight(1),0); + // Recovery invalidation clears warm reuse for BOTH slots so both VMs drain for InitBM. + p.invalidate(); + assert!(!p.can_pipeline_within(&vm1,2)); + assert!(!p.can_pipeline_within(&vm2,2)); + } + + #[test]fn render_hang_after_cross_vm_use_recovers_via_lazy_pb_slot_and_displaces_survivor(){ + let vm1=vm(1);let vm2=vm(2);let vm3=vm(3);let vm4=vm(4); + let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); + let mk_epoch=|owner:&sync::Arc,slot:usize|{ + let e=g16::pools::PbEpoch::new(&factory,owner,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); + e.prepare(slot,0x70c0000000,2048).unwrap();e.check_assignment(slot).unwrap();e.expose(); + e + }; + let mut p=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + // Exact live cross-VM sequence: VM1 on slot 0 -> VM2 on slot 1 -> VM1 on slot 0. + let e1=mk_epoch(&vm1,0); + assert_eq!(p.pick_slot_within(&vm1,false,2),Some(0)); + let b=p.bind(0,false);p.publish_flight(0);p.retire_flight(0,&e1,b,true).unwrap(); + let e2=mk_epoch(&vm2,1); + assert_eq!(p.pick_slot_within(&vm2,false,2),Some(1)); + let b=p.bind(1,false);p.publish_flight(1);p.retire_flight(1,&e2,b,true).unwrap(); + let e1b=mk_epoch(&vm1,0); + assert_eq!(p.pick_slot_within(&vm1,false,2),Some(0)); + let b=p.bind(0,false);p.publish_flight(0);p.retire_flight(0,&e1b,b,true).unwrap(); + // VM3 switches to slot 1 with a fresh epoch and hangs: recovery invalidates epochs + // and quarantines slot 1 while retaining BOTH the prior owner (e2) and fresh epoch (e3). + let e3=mk_epoch(&vm3,1); + assert_eq!(p.pick_slot_within(&vm3,false,2),Some(1)); + let _=p.bind(1,false);p.publish_flight(1); + p.invalidate(); + p.quarantine_flight(1,Some(e3.clone())); + // e2 is slot 1's prior owner and VM2's last retired epoch. + assert_eq!(sync::Arc::strong_count(&e2),3,"prior slot owner epoch must stay mapped"); + assert_eq!(sync::Arc::strong_count(&e3),2,"aborted fresh epoch must stay mapped"); + // Render class must NOT wedge: slot 2 is fresh and needed_slots advances to 3. + assert!(!p.exhausted()); + assert_eq!(p.needed_slots(),3); + // Pre-hang job with only 2 prepared PB slots sees per-job exhaustion (no EAGAIN spin), + // while a post-hang job with 3 prepared PB slots claims recovery slot 2. + assert!(p.exhausted_for_within(&vm4,2)); + assert!(!p.exhausted_for_within(&vm4,3)); + assert_eq!(p.pick_slot_within(&vm4,false,3),Some(2)); + let e4=mk_epoch(&vm4,2); + let b=p.bind(2,false);p.publish_flight(2);p.retire_flight(2,&e4,b,true).unwrap(); + // Clean retirement on slot 2 displaces surviving slot 0 back to reusable! + assert!(!p.exhausted_for_within(&vm1,3)); + assert_eq!(p.pick_slot_within(&vm1,false,3),Some(0)); + let e1c=mk_epoch(&vm1,0); + let b=p.bind(0,false);p.publish_flight(0);p.retire_flight(0,&e1c,b,true).unwrap(); + // Subsequent cross-VM render reuses displaced slot 2 (does not consume slot 3). + assert_eq!(p.pick_slot_within(&vm2,false,3),Some(2)); + // An unrelated compute hang calling invalidate() does not wedge render either. + p.invalidate(); + assert!(!p.exhausted()); + assert_eq!(p.pick_slot_within(&vm2,false,3),Some(2)); + } + + #[test]fn pb_recovery_slots_survive_four_render_hangs_and_exhaust_cleanly_at_limit(){ + let vm1=vm(1);let vm2=vm(2);let vm3=vm(3); + let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); + let mk_epoch=|owner:&sync::Arc,slot:usize|{ + let e=g16::pools::PbEpoch::new(&factory,owner,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); + e.prepare(slot,0x70c0000000,2048).unwrap();e.check_assignment(slot).unwrap();e.expose(); + e + }; + let warm=g16::hw::sizes::WARM_PB_SLOTS; + let ext=g16::hw::sizes::EXT_PB_SLOTS; + let total=g16::hw::sizes::PB_SLOTS; + let mut p=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + // A VM bound to [0, 1] with all 4 recovery spares (16..20) survives 4 hangs cleanly + // and keeps 2 healthy slots (18, 19) for cross-VM switching. + let vm_mask:u32=(1u32<<0)|(1u32<<1)|(((1u32< global pool exhaustion. + q.invalidate(); + assert!(q.exhausted()); + assert!(q.exhausted_for(&vm2)); + } + + #[test]fn recovery_invalidate_scrub_survives_in_flight_retirement(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); + let a=vm(1); + // Prime unit 0 and unit 1 so unit 0 is clean for same-VM reuse. + let mut c0=Claims::new(); + assert_eq!(s.claim_compute_for(&arena.compute,&mut c0,Some(a.id)).unwrap(),Some(0)); + s.hold_vm(&c0,&a).unwrap();s.publish(&mut c0).unwrap(); + // Recovery fires while unit 0 is still in flight. + s.invalidate_scrub(); + s.retire(&mut c0).unwrap(); + // Displace unit 0 via unit 1 (published after recovery -> clean). + let mut c1=Claims::new(); + assert_eq!(s.claim_compute_for(&arena.compute,&mut c1,Some(a.id)).unwrap(),Some(1)); + s.hold_vm(&c1,&a).unwrap();s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); + // Next claim of unit 0 by the same VM must still perform a full scrub! + let k=s.claim_compute_for(&arena.compute,&mut c0,Some(a.id)).unwrap().unwrap(); + assert_eq!(k,0); + assert!(s.compute_needs_full_work(0)); + assert_eq!(arena.compute.compute[0].context_store.fills.lock().unwrap().len(),2); + s.hold_vm(&c0,&a).unwrap();s.publish(&mut c0).unwrap();s.retire(&mut c0).unwrap(); + // Same invariant for render pass slots in flight across recovery. + let mut r0=Claims::new();r0.pass[0]=0;r0.pass_mask=1; + s.claim_pass_for(&arena.render,0,Some(a.id)).unwrap(); + s.hold_vm(&r0,&a).unwrap();s.publish(&mut r0).unwrap(); + s.invalidate_scrub(); + s.retire(&mut r0).unwrap(); + let mut r1=Claims::new();r1.pass[0]=1;r1.pass_mask=2; + s.claim_pass_for(&arena.render,1,Some(a.id)).unwrap(); + s.hold_vm(&r1,&a).unwrap();s.publish(&mut r1).unwrap();s.retire(&mut r1).unwrap(); + s.claim_pass_for(&arena.render,0,Some(a.id)).unwrap(); + assert_eq!(arena.render.passes[0].scene.fills.lock().unwrap().len(),2); + } + + #[test]fn pipelined_render_pass_slots_keep_forty_seven_in_flight(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let mut passes=KVec::new(); + for k in 0..g16::hw::sizes::RENDER_SLOTS as u64 { + let pass=g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(); + if k < g16::hw::sizes::BASE_RENDER_SLOTS as u64 { + assert_eq!(pass.tpc.size as u64, g16::hw::client::TPC_SIZE); + assert_eq!(pass.tilemap.size as u64, g16::hw::client::TILEMAP_SIZE); + } else { + assert_eq!(pass.tpc.size as u64, g16::hw::client::TPC_SLOT_SIZE); + assert_eq!(pass.tilemap.size as u64, g16::hw::client::TILEMAP_SLOT_SIZE); + } + passes.push(pass,0).unwrap(); + } + let arena=render_arena(passes); + let a=vm(1); + let b=vm(2); + let mut live:Vec=Vec::new(); + // Publish 47 concurrent passes in flight (slots 0..47), covering 4x11-pass and 6x7-pass + // multi-pass bursts and exercising 64-bit pass_mask bits above bit 31. + for k in 0..47usize { + let mut c=Claims::new(); + c.pass[0]=k as u32;c.pass_mask=1u64< slot 0 is displaced and reusable while 45 others remain in flight. + s.retire(&mut live[0]).unwrap(); + assert!(!s.pass_available(47)); // slot 0 not displaced yet + s.retire(&mut live[1]).unwrap(); + assert!(s.pass_available(47)); // slot 0 displaced by slot 1! + // Claim and publish bit 47 (slot 47) explicitly to prove zero 64-bit mask overflow. + let mut c47=Claims::new(); + c47.pass[0]=47;c47.pass_count=1;c47.pass_mask=1u64<<47; + s.claim_pass_for(&arena,47,Some(a.id)).unwrap(); + s.hold_vm(&c47,&a).unwrap(); + s.publish(&mut c47).unwrap(); + // Clean same-VM reuse of displaced slot 0 does not need full work write. + s.claim_pass_for(&arena,0,Some(a.id)).unwrap(); + assert!(!s.render_needs_full_work(0)); + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.release(&mut c0); + // Cancelled preparation or cross-VM switch forces full work write again. + s.claim_pass_for(&arena,0,Some(b.id)).unwrap(); + assert!(s.render_needs_full_work(0)); + s.release(&mut c0); + for c in live.iter_mut().skip(2) { + s.retire(c).unwrap(); + } + s.retire(&mut c47).unwrap(); + assert_eq!(s.render_published(),0); + } + + #[test]fn offlock_scrub_cleans_displaced_slot_and_skips_sync_scrub_on_same_vm_claim(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); + let render=sync::Arc::new(arena.render,0).unwrap(); + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone()),hw_slots:None}; + let a=vm(1); + let geo=g16::encode::Geometry{tpc_bytes:0x2000,tilemap_bytes:0x4000}; + // Publish and retire slot 0: not displaced yet, so nothing is staged. + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.claim_pass_in(&prep,0,Some(a.id),0x4000).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap(); + render.set_dirty(0,0x2000,0x4000).unwrap(); + render.passes[0].tilemap.fill(0,0xab,0x4000).unwrap(); + render.passes[0].heap.fill(0,0xcd,0x200).unwrap(); + let its_before=render.passes[0].its.fills.lock().unwrap().len(); + let pre0_before=render.passes[0].pre[0].fills.lock().unwrap().len(); + s.retire(&mut c0).unwrap(); + s.stage_displaced_pass_scrubs(); + assert!(!s.scrubbing_active()); + assert!(!drain_scrubs(s.take_staged_scrubs())); + // Publish and retire slot 1: displaces slot 0, staging slot 0 for off-lock scrub. + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap(); + s.retire(&mut c1).unwrap(); + s.stage_displaced_pass_scrubs(); + assert!(s.scrubbing_active()); + // While slot 0 scrubs off-lock it cannot be picked or claimed, and waiter is recorded. + assert!(!s.pass_available(2)); + assert_eq!(s.pick_pass_in(&prep,&geo,0),None); + assert_eq!(s.claim_pass_in(&prep,0,Some(a.id),0x4000),Err(EBUSY)); + let batch=s.take_staged_scrubs(); + assert!(drain_scrubs(batch)); + assert!(!s.scrubbing_active()); + assert!(render.passes[0].tilemap.snapshot()[..0x4000].iter().all(|&b|b==0)); + assert!(render.passes[0].heap.snapshot()[..0x200].iter().all(|&b|b==0)); + assert_eq!(render.passes[0].its.fills.lock().unwrap().len(),its_before); + assert_eq!(render.passes[0].pre[0].fills.lock().unwrap().len(),pre0_before); + assert_eq!(render.tilemap_dirty[0].load(std::sync::atomic::Ordering::Acquire),0); + assert_eq!(render.heap_dirty[0].load(std::sync::atomic::Ordering::Acquire),0); + // Next same-VM claim picks pre-cleaned slot 0 and performs zero WC fills under lock. + let fills_before=render.passes[0].tilemap.fills.lock().unwrap().len(); + let heap_before=render.passes[0].heap.fills.lock().unwrap().len(); + assert_eq!(s.pick_pass_in(&prep,&geo,0),Some(0)); + s.claim_pass_in(&prep,0,Some(a.id),0x4000).unwrap(); + assert!(!s.render_needs_full_work(0)); + assert_eq!(render.passes[0].tilemap.fills.lock().unwrap().len(),fills_before); + assert_eq!(render.passes[0].heap.fills.lock().unwrap().len(),heap_before); + assert_eq!(render.passes[0].its.fills.lock().unwrap().len(),its_before); + assert_eq!(render.passes[0].pre[0].fills.lock().unwrap().len(),pre0_before); + } + + #[test]fn stage_displaced_pass_scrubs_prioritizes_pass_cursor_order(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let mut passes=KVec::new(); + for k in 0..20 { + passes.push(g16::slots::PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); + } + let render=sync::Arc::new(render_arena(passes), 0).unwrap(); + let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render.clone()),hw_slots:None}; + let a=vm(1); + // Publish and retire slots 0..20 in order so slots 0..19 are displaced dirty and + // slot 19 is the undisplaced newest retired slot. + for k in 0..20 { + let mut c=Claims::new();c.pass[0]=k as u32;c.pass_count=1;c.pass_mask=1u64<fills_before); + assert!(render.passes[0].tilemap.snapshot()[..0x2000].iter().all(|&b|b==0)); + // Cancel, re-displace, pre-scrub clean, then invalidate_scrub() or cross-VM forces full scrub. + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap();s.retire(&mut c0).unwrap(); + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); + s.stage_displaced_pass_scrubs(); + let _=drain_scrubs(s.take_staged_scrubs()); + s.invalidate_scrub(); + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + assert!(s.render_needs_full_work(0)); + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap();s.retire(&mut c0).unwrap(); + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); + s.stage_displaced_pass_scrubs(); + let _=drain_scrubs(s.take_staged_scrubs()); + s.claim_pass_in(&prep,0,Some(b.id),0x2000).unwrap(); + assert!(s.render_needs_full_work(0)); + } + #[test]fn post_publish_scrub_staging_does_not_block_immediate_slot_reuse(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); + let render=sync::Arc::new(arena.render,0).unwrap(); + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone()),hw_slots:None}; + let a=vm(1); + let geo=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x2000}; + // Prime slot 0, then displace it by retiring slot 1; record retirement without staging yet. + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap(); + render.set_dirty(0,0x1000,0x2000).unwrap(); + render.passes[0].tilemap.fill(0,0x77,0x2000).unwrap(); + s.retire(&mut c0).unwrap(); + s.note_render_retired(); + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap(); + s.retire(&mut c1).unwrap(); + s.note_render_retired(); + // Immediate publication in the same lock hold sees slot 0 available and NOT scrubbing. + assert!(!s.scrubbing_active()); + assert!(s.pass_available(2)); + assert_eq!(s.pick_pass_in(&prep,&geo,0),Some(0)); + // Disallowed staging (fail-stop / frozen) stages nothing and clears pending flag. + assert!(!drain_scrubs(s.stage_and_take_scrubs(false))); + assert!(!s.scrubbing_active()); + // Allowed staging after publication stages idle displaced slot 0 and scrubs it off-lock. + s.note_render_retired(); + let batch=s.stage_and_take_scrubs(true); + assert!(s.scrubbing_active()); + assert!(!drain_scrubs(batch)); + assert!(!s.scrubbing_active()); + assert!(render.passes[0].tilemap.snapshot()[..0x2000].iter().all(|&b|b==0)); + // Calling stage_and_take_scrubs again without a new render retirement is a no-op. + assert!(!drain_scrubs(s.stage_and_take_scrubs(true))); + assert!(!s.scrubbing_active()); + } + #[test]fn multi_unit_compute_horizon_claims_publish_retire_and_release(){ + use crate::g16::{hw, slots::ComputeSlot, resources::ComputeArena, vm}; + use crate::sync::Arc; + let mut o=Objects::new(); + let mut units=KVec::new(); + for k in 0..hw::sizes::COMPUTE_UNITS { + units.push(ComputeSlot::new(&mut o,&g16::object::Factory,k as u64,&crate::g16::object::test_unit_cmds(k as u64)).unwrap(),0).unwrap(); + } + let prep=ComputeArena{compute:units,render:None,hw_slots:None}; + let a=Arc::new( + vm::VmState{id:1,slot:1,generation:1,vm:vm::MockVm::new()},0, + ).unwrap(); + let mut s=Slots::new().unwrap(); + assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),hw::sizes::COMPUTE_UNITS as u32); + // Claim 4 units into one Claims for a compute horizon, publish, and retire in order. + let mut claims=Claims::new(); + for i in 0..4 { + let k=s.claim_compute_for(&prep,&mut claims,Some(a.id)).unwrap().expect("free unit"); + assert_eq!(k,i); + assert_eq!(claims.slot_count,(i+1) as u32); + assert_eq!(claims.slot[i],k as u32); + } + assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),(hw::sizes::COMPUTE_UNITS-4) as u32); + s.hold_vm(&claims,&a).unwrap(); + s.hold_arenas(&claims,&prep); + s.publish(&mut claims).unwrap(); + assert_eq!(s.compute_published(),4); + s.retire(&mut claims).unwrap(); + assert_eq!(s.compute_published(),0); + // Unit 3 (the newest retired) holds the displacement slot; 15 units remain free. + assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),(hw::sizes::COMPUTE_UNITS-1) as u32); + // Claiming all remaining free units then releasing restores availability cleanly. + let mut batch=Claims::new(); + while s.claim_compute_for(&prep,&mut batch,Some(a.id)).unwrap().is_some() {} + assert_eq!(batch.slot_count as usize,hw::sizes::COMPUTE_UNITS-1); + assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),0); + s.release(&mut batch); + assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),(hw::sizes::COMPUTE_UNITS-1) as u32); + } + + #[test]fn multi_pass_render_batch_claims_ordered_retirement_and_publish_batch(){ + use crate::g16::pools::PoolSet; + let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); + let mut passes=KVec::new(); + for k in 0..g16::hw::sizes::RENDER_SLOTS as u64 { + passes.push(g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap(); + } + let render=sync::Arc::new(render_arena(passes),0).unwrap(); + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render),hw_slots:None}; + let a=vm(1); + // Wrapped submission order [46, 47, 0]: retiring in order leaves slot 0 as last_retired + // while high slots 46 and 47 (bits above 31) are displaced and reusable immediately. + let order=[46usize,47,0]; + let mut c=Claims::new(); + for (i,&k) in order.iter().enumerate() { + s.claim_pass_in(&prep,k,Some(a.id),0x1000).unwrap(); + c.pass[i]=k as u32; + c.pass_count+=1; + c.pass_mask|=1u64< Tier 1 -> Tier 2 only as depth climbs. + let mut last = 0u64; + let mut burst = 0u32; + let mut backed = BASE_RENDER_SLOTS; + backed = target_render_slots(&mut last, &mut burst, 1_000_000, 1, 0, false, backed); + assert_eq!(backed, BASE_RENDER_SLOTS); + backed = target_render_slots(&mut last, &mut burst, 6_000_000, 1, 1, false, backed); + assert_eq!(backed, tier0_end); + backed = target_render_slots(&mut last, &mut burst, 22_600_000, 1, 6, false, backed); + assert_eq!(backed, tier0_end); // 6 + 1 + 1 == 8 fits in Tier 0 + backed = target_render_slots(&mut last, &mut burst, 39_200_000, 1, 7, false, backed); + assert_eq!(backed, tier1_end); // 7 + 1 + 1 == 9 grows to Tier 1 (18 slots) + backed = target_render_slots(&mut last, &mut burst, 55_800_000, 1, 16, false, backed); + assert_eq!(backed, tier1_end); // 16 + 1 + 1 == 18 fits in Tier 1 + backed = target_render_slots(&mut last, &mut burst, 72_400_000, 1, 17, false, backed); + assert_eq!(backed, tier2_end); // 17 + 1 + 1 == 19 grows to Tier 2 (32 slots) + backed = target_render_slots(&mut last, &mut burst, 89_000_000, 1, 30, false, backed); + assert_eq!(backed, tier2_end); // 30 + 1 + 1 == 32 fits in Tier 2 + backed = target_render_slots(&mut last, &mut burst, 105_600_000, 1, 31, false, backed); + assert_eq!(backed, full_end); // 31 + 1 + 1 == 33 grows to Tier 3 (48 slots) + + // Sub-2 ms back-to-back single-pass bursts grow only to Tier 0 after 3 consecutive gaps. + let mut last = 0u64; + let mut burst = 0u32; + assert_eq!(target_render_slots(&mut last, &mut burst, 1_000_000, 1, 0, false, BASE_RENDER_SLOTS), BASE_RENDER_SLOTS); + assert_eq!(target_render_slots(&mut last, &mut burst, 2_000_000, 1, 0, false, BASE_RENDER_SLOTS), BASE_RENDER_SLOTS); + assert_eq!(target_render_slots(&mut last, &mut burst, 3_000_000, 1, 0, false, BASE_RENDER_SLOTS), BASE_RENDER_SLOTS); + assert_eq!(target_render_slots(&mut last, &mut burst, 4_000_000, 1, 0, false, BASE_RENDER_SLOTS), tier0_end); + assert_eq!(burst, 3); + assert_eq!(target_render_slots(&mut last, &mut burst, 5_000_000, 1, 0, false, tier0_end), tier0_end); + + // Multi-pass pipelined workloads stop at Tier 2 (32 slots) for 20-31 pass demand and + // grow into Tier 3 (48 slots) only when live demand exceeds 32 slots: + // 11-pass render.postfx: depth 2 (23) -> Tier 2, depth 3 (34) -> Tier 3; + // 7-pass compress.bw array: depth 3 (22) -> Tier 2, depth 5 (36) -> Tier 3; + // 4-pass render.shadow: depth 5 (21) -> Tier 2, depth 8 (33) -> Tier 3. + let mut last = 0u64; + let mut burst = 0u32; + assert_eq!(target_render_slots(&mut last, &mut burst, 10_000_000, 11, 0, false, BASE_RENDER_SLOTS), tier1_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 15_000_000, 11, 11, false, tier1_end), tier2_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 18_000_000, 11, 22, false, tier2_end), full_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 20_000_000, 7, 7, false, tier1_end), tier1_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 25_000_000, 7, 14, false, tier1_end), tier2_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 28_000_000, 7, 28, false, tier2_end), full_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 30_000_000, 4, 12, false, tier1_end), tier1_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 35_000_000, 4, 16, false, tier1_end), tier2_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 38_000_000, 4, 28, false, tier2_end), full_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 40_000_000, 8, 0, false, BASE_RENDER_SLOTS), tier1_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 50_000_000, 20, 0, false, BASE_RENDER_SLOTS), tier2_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 60_000_000, 32, 0, false, BASE_RENDER_SLOTS), full_end); + + // Verify exact per-slot mapped backing bytes for Base vs Ext slots. + let mut o_base = Objects::new(); + g16::slots::PassSlot::new(&mut o_base, 0, 1, &crate::g16::object::test_cmds((0) as u64)).unwrap(); + let base_slot_bytes: usize = o_base.objects.iter().map(|obj| obj.mapped).sum(); + // Microsequences and barrier records are the device-lifetime records of the index. + assert_eq!(base_slot_bytes, (16 * 1024 + 8 * 1024 + 448) * 1024); + let mut o_ext = Objects::new(); + g16::slots::PassSlot::new(&mut o_ext, 2, 1, &crate::g16::object::test_cmds((2) as u64)).unwrap(); + let ext_slot_bytes: usize = o_ext.objects.iter().map(|obj| obj.mapped).sum(); + assert_eq!(ext_slot_bytes, (2 * 1024 + 1024 + 448) * 1024); + // Each index's device-lifetime records: two work image pages, two microsequence pages + // and one barrier page. + let indices = crate::g16::object::PASS_CMDS.with(|p| p.borrow().len()); + let device_bytes: usize = crate::g16::object::PERSISTENT + .with(|p| p.borrow().as_ref().unwrap().objects.iter().map(|obj| obj.mapped).sum()); + assert_eq!((indices, device_bytes), (2, 2 * 5 * 16 * 1024)); + // Cumulative extension backing across the 4 demand-grown tiers: + // Tier 0 (6 ext): 20.625 MiB, Tier 1 (16 ext): 55.00 MiB, + // Tier 2 (30 ext): 103.125 MiB, Tier 3 (46 ext): 158.125 MiB. + assert_eq!((tier0_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 21_120 * 1024); + assert_eq!((tier1_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 56_320 * 1024); + assert_eq!((tier2_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 105_600 * 1024); + assert_eq!((full_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 161_920 * 1024); + } + + #[test]fn base_compute_quarantine_expands_fresh_vm_and_recovers_displacement(){ + use crate::g16::resources::should_expand_compute_ext; + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let mut units=KVec::new(); + for k in 0..4u64 { + units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k,&crate::g16::object::test_unit_cmds(k)).unwrap(),0).unwrap(); + } + let prep_full=g16::resources::ComputeArena{compute:units,render:None,hw_slots:None}; + let a=vm(1);let b=vm(2); + // Retire base unit 0, then hang and quarantine base unit 1 (or vice versa): + // unit 0 is now retired-undisplaced and unit 1 is quarantined -> base [0..2] exhausted. + let mut c=Claims::new(); + assert_eq!(s.claim_compute_for(&prep_full,&mut c,Some(a.id)).unwrap(),Some(0)); + s.hold_vm(&c,&a).unwrap();s.publish(&mut c).unwrap();s.retire(&mut c).unwrap(); + assert_eq!(s.claim_compute_for(&prep_full,&mut c,Some(a.id)).unwrap(),Some(1)); + s.hold_vm(&c,&a).unwrap();s.publish(&mut c).unwrap();s.quarantine(&mut c); + assert!(s.base_compute_quarantined()); + assert!(s.compute_exhausted_within(2)); + assert!(!s.compute_exhausted_within(4)); + // Fresh single-command VM expands extension units immediately because a base unit is quarantined. + let mut last=0u64;let mut burst=0u32; + assert!(!should_expand_compute_ext(&mut last,&mut burst,10_000_000,1,false)); + let mut last=0u64;let mut burst=0u32; + assert!(should_expand_compute_ext(&mut last,&mut burst,10_000_000,1,s.base_compute_quarantined())); + // Expanded fresh VM claims unit 2, retires cleanly, and displaces base unit 0 back to reusable. + assert_eq!(s.claim_compute_for(&prep_full,&mut c,Some(b.id)).unwrap(),Some(2)); + s.hold_vm(&c,&b).unwrap();s.publish(&mut c).unwrap();s.retire(&mut c).unwrap(); + assert!(!s.compute_exhausted_within(2)); + assert!(s.compute_available(2)); + // A base-only (2-unit) VM can now claim displaced base unit 0 again. + let mut base_units=KVec::new(); + for k in 0..2u64 { + base_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k,&crate::g16::object::test_unit_cmds(k)).unwrap(),0).unwrap(); + } + let prep_base=g16::resources::ComputeArena{compute:base_units,render:None,hw_slots:None}; + assert_eq!(s.claim_compute_for(&prep_base,&mut c,Some(b.id)).unwrap(),Some(0)); + s.release(&mut c); + } + + #[test]fn two_pipe_compute_out_of_order_retire_and_base_unit_isolation(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let p1_start = g16::hw::sizes::PIPE1_COMPUTE_START; + let mut units=KVec::new(); + for k in 0..(p1_start + 2) as u64 { + units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k,&crate::g16::object::test_unit_cmds(k)).unwrap(),0).unwrap(); + } + let prep=g16::resources::ComputeArena{compute:units,render:None,hw_slots:None}; + let a=vm(1);let b=vm(2); + // Pipe 0 claims unit 0; pipe 1 stays out of 0..PIPE1_COMPUTE_START and claims PIPE1_COMPUTE_START. + let mut c0=Claims::new(); + let mut c1=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c0,Some(a.id),0).unwrap(),Some(0)); + assert_eq!(c0.compute_pipe,0); + s.hold_vm(&c0,&a).unwrap();s.publish(&mut c0).unwrap(); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1,Some(a.id),1).unwrap(),Some(p1_start)); + assert_eq!(c1.compute_pipe,1); + s.hold_vm(&c1,&a).unwrap();s.publish(&mut c1).unwrap(); + // Pipe 1 finishes ahead of still-running pipe 0: retire must succeed (no EINVAL). + assert_eq!(s.retire(&mut c1),Ok(())); + // Second pipe-1 flight claims PIPE1_COMPUTE_START + 1 and retires, displacing PIPE1_COMPUTE_START. + let mut c1b=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1b,Some(a.id),1).unwrap(),Some(p1_start + 1)); + s.hold_vm(&c1b,&a).unwrap();s.publish(&mut c1b).unwrap(); + assert_eq!(s.retire(&mut c1b),Ok(())); + assert!(s.compute_available_for_pipe(p1_start + 2,1)); + // Now pipe 0's unit 0 retires: pipe 1's newer retirement must NOT mark unit 0 reusable, + // while base unit 1 remains fresh so a 2-unit base-only VM is never exhausted! + assert_eq!(s.retire(&mut c0),Ok(())); + assert!(!s.compute_exhausted_within(2)); + assert!(s.compute_available(2)); + // Pipe 0 claims base unit 1 (not undisplaced unit 0), publishes, and retires -> unit 0 displaced! + let mut c0b=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c0b,Some(b.id),0).unwrap(),Some(1)); + s.hold_vm(&c0b,&b).unwrap();s.publish(&mut c0b).unwrap(); + assert_eq!(s.retire(&mut c0b),Ok(())); + assert!(!s.compute_exhausted_within(2)); + assert!(s.compute_available(2)); + // A 2-unit base-only VM can claim displaced base unit 0 on pipe 0, while pipe 1 + // reclaims displaced extension unit PIPE1_COMPUTE_START without touching 0..PIPE1_COMPUTE_START. + let mut base_units=KVec::new(); + for k in 0..2u64 { + base_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k,&crate::g16::object::test_unit_cmds(k)).unwrap(),0).unwrap(); + } + let prep_base=g16::resources::ComputeArena{compute:base_units,render:None,hw_slots:None}; + let mut c0c=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep_base,&mut c0c,Some(b.id),0).unwrap(),Some(0)); + let mut c1c=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1c,Some(b.id),1).unwrap(),Some(p1_start)); + s.release(&mut c0c); + s.release(&mut c1c); + } + + #[test]fn scs_compute_and_base_pb_route_around_quarantined_slots(){ + use crate::g16::resources::{pick_base_pb_slots, pick_scs_compute_slots}; + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let p1_start = g16::hw::sizes::PIPE1_COMPUTE_START; + let mut full_units=KVec::new(); + for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { + full_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k,&crate::g16::object::test_unit_cmds(k)).unwrap(),0).unwrap(); + } + let prep_full=g16::resources::ComputeArena{compute:full_units,render:None,hw_slots:None}; + let bad=vm(1);let fresh=vm(2);let other=vm(3); + // Exact dcp102b sequence: a prior process hangs and permanently quarantines compute unit 0. + let mut c=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep_full,&mut c,Some(bad.id),0).unwrap(),Some(0)); + s.hold_vm(&c,&bad).unwrap();s.publish(&mut c).unwrap();s.quarantine(&mut c); + assert_eq!(s.quarantined_compute_mask(), 1u32 << 0); + // Pipe 1 runs concurrent non-SCS compute on PIPE1_COMPUTE_START..COMPUTE_UNITS. + let mut c_p1=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep_full,&mut c_p1,Some(other.id),1).unwrap(),Some(p1_start)); + s.hold_vm(&c_p1,&other).unwrap();s.publish(&mut c_p1).unwrap();s.retire(&mut c_p1).unwrap(); + // Brand-new SCS compute VM skips quarantined unit 0 and binds [1, 2] (mask 0b110), both < PIPE1_COMPUTE_START. + let scs_slots = pick_scs_compute_slots(s.quarantined_compute_mask(), g16::hw::sizes::COMPUTE_UNITS); + assert_eq!(scs_slots, [1, 2]); + let mut scs_units=KVec::new(); + for (local, &hw_slot) in scs_slots.iter().enumerate() { + scs_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,local as u64,&crate::g16::object::test_unit_cmds(hw_slot as u64)).unwrap(),0).unwrap(); + } + let prep_scs=g16::resources::ComputeArena{compute:scs_units,render:None,hw_slots:Some(scs_slots)}; + let scs_mask = prep_scs.compute_slot_mask().unwrap(); + assert_eq!(scs_mask, (1u32 << 1) | (1u32 << 2)); + // Execute two back-to-back SCS compute commands (e.g. rt.scene p_rt + p_comp) repeatedly: + // must never hit compute_exhausted_in_mask and must ping-pong cleanly across [1, 2]. + for expected in [1usize, 2, 1, 2] { + assert!(!s.compute_exhausted_in_mask(scs_mask)); + assert!(s.compute_available_in_mask(scs_mask)); + let mut cs=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep_scs,&mut cs,Some(fresh.id),0).unwrap(),Some(expected)); + s.hold_vm(&cs,&fresh).unwrap();s.publish(&mut cs).unwrap();s.retire(&mut cs).unwrap(); + } + // Up to 4 quarantines in 0..PIPE1_COMPUTE_START stay inside pipe-0-exclusive 0..6; beyond that falls back cleanly. + assert_eq!(pick_scs_compute_slots(0b001111, g16::hw::sizes::COMPUTE_UNITS), [4, 5]); + assert_eq!(pick_scs_compute_slots(0b111111, g16::hw::sizes::COMPUTE_UNITS), [6, 7]); + // Twin fix: pick_base_pb_slots skips quarantined warm PB slots and falls back to EXT_PB_SLOTS. + assert_eq!(pick_base_pb_slots(0, 0), [0, 1]); + assert_eq!(pick_base_pb_slots(3, 1u32 << 3), [4, 5]); + assert_eq!(pick_base_pb_slots(3, (1u32 << 3) | (1u32 << 4)), [5, 6]); + let all_warm_but_one = ((1u32 << g16::hw::sizes::WARM_PB_SLOTS) - 1) & !(1u32 << 7); + assert_eq!(pick_base_pb_slots(0, all_warm_but_one), [7, g16::hw::sizes::WARM_PB_SLOTS]); + // Confirm Pools::exhausted_for_mask_mode stays false for render_scs with picked healthy slots. + let mut pools = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let bad_vm = vm(10); + let good_vm = vm(11); + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let ep = g16::pools::PbEpoch::new( + &factory, + &bad_vm, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ) + .unwrap(); + ep.prepare(3, 0x70c0000000, 2048).unwrap(); + ep.expose(); + pools.publish_flight(3); + pools.quarantine_flight(3, Some(ep)); + let picked = pick_base_pb_slots(3, pools.quarantined_mask()); + assert_eq!(picked, [4, 5]); + let pb_mask = (1u32 << picked[0]) | (1u32 << picked[1]); + assert!(!pools.exhausted_for_mask_mode(&good_vm, pb_mask, picked[0], true)); + } + + #[test]fn render_only_pb_routing_without_quarantine_matches_v29_for_any_boot_history(){ + use crate::g16::resources::pick_base_pb_slots; + let warm = g16::hw::sizes::WARM_PB_SLOTS; + // v29 (4310e041) gave a new render arena [start % WARM_PB_SLOTS, home + 1]. With nothing + // quarantined the quarantine-aware picker must be that exact pair for every start. + for start in 0..(4 * warm) { + assert_eq!(pick_base_pb_slots(start, 0), [start % warm, (start + 1) % warm]); + } + // render.light [procs] d=16 (dcp103a, dcp103b) makes WARM_PB_SLOTS render-only VMs. Earlier + // work in the same boot only moves `next_pb_slot`: whatever the start, every warm slot is + // the home of exactly one of them and the alternate of exactly one other. + for start in [0usize, 1, 7, 15, 16, 39, 1000] { + let mut home = [0u32; 32]; + let mut alt = [0u32; 32]; + for vm in 0..warm { + let [h, a] = pick_base_pb_slots(start + vm, 0); + assert_ne!(h, a); + home[h] += 1; + alt[a] += 1; + } + assert!(home[..warm].iter().all(|&n| n == 1), "start {start}: {home:?}"); + assert!(alt[..warm].iter().all(|&n| n == 1), "start {start}: {alt:?}"); + assert!(home[warm..].iter().chain(&alt[warm..]).all(|&n| n == 0)); + } + } + + #[test]fn base_render_quarantine_expands_fresh_vm_and_recovers_displacement(){ + use crate::g16::resources::{BASE_RENDER_SLOTS, EXT_RENDER_TIERS, target_render_slots}; + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let mut passes=KVec::new(); + for k in 0..4u64 { + passes.push(g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap(); + } + let render=sync::Arc::new(render_arena(passes),0).unwrap(); + let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render),hw_slots:None}; + let a=vm(1);let b=vm(2); + let geo=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x1000}; + // Retire base pass slot 0, then hang and quarantine base pass slot 1 -> base [0..2] exhausted. + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_count=1;c0.pass_mask=1<<0; + s.claim_pass_in(&prep,0,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.publish(&mut c0).unwrap();s.retire(&mut c0).unwrap(); + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_count=1;c1.pass_mask=1<<1; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.publish(&mut c1).unwrap();s.quarantine(&mut c1); + assert!(s.base_render_quarantined()); + assert!(s.render_exhausted_within(2)); + assert!(!s.render_exhausted_within(4)); + // Fresh single-pass VM expands Tier 0 RenderExtArena immediately because a base pass slot is quarantined. + let mut last=0u64;let mut burst=0u32; + assert_eq!( + target_render_slots(&mut last,&mut burst,10_000_000,1,0,s.base_render_quarantined(),BASE_RENDER_SLOTS), + EXT_RENDER_TIERS[0].1 + ); + // Expanded VM picks and retires pass slot 2, displacing base pass slot 0 back to reusable. + let k=s.pick_pass_in(&prep,&geo,0).unwrap(); + assert_eq!(k,2); + let mut c2=Claims::new();c2.pass[0]=k as u32;c2.pass_count=1;c2.pass_mask=1<wmb_before); + assert!(!s.scrubbing_active()); + assert!(s.take_scrub_woke()); + assert!(!s.take_scrub_woke()); + assert_eq!(s.pick_pass_in(&prep,&geo,0),Some(0)); + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + assert!(!s.render_needs_full_work(0)); + + // Re-displace slot 0, stage scrub, then simulate recovery invalidate_scrub() BEFORE + // the async scrub runs: it must clear scrubbing without marking clean, so next claim + // performs a full scrub. + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap();s.retire(&mut c0).unwrap(); + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); + s.stage_displaced_pass_scrubs(); + assert!(q.push_batch(s.take_staged_scrubs())); + assert!(s.scrubbing_active()); + s.invalidate_scrub(); + let mut stale=q.pop().expect("stale scrub"); + assert!(!stale.run_one()); + assert!(!s.scrubbing_active()); + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + assert!(s.render_needs_full_work(0)); + } + + #[test]fn lazy_tilemap_prefix_scrub_and_classed_slot_selection_avoid_overscrub(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let mut passes=KVec::new(); + for k in 0..3u64 { + passes.push(g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap(); + } + let render=sync::Arc::new(render_arena(passes),0).unwrap(); + let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render.clone()),hw_slots:None}; + let a=vm(1);let b=vm(2); + let pub_retire=|s:&mut Slots,k:usize,vm:&sync::Arc|{ + let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1u64< dirty=0x10000, last=0x2000. + s.claim_pass_in(&prep,0,Some(a.id),0x10000).unwrap(); + prep.set_pass_dirty(0,0x2000,0x10000,0x200).unwrap(); + render.passes[0].tilemap.fill(0,0x55,0x10000).unwrap(); + pub_retire(&mut s,0,&a); + s.claim_pass_in(&prep,1,Some(a.id),0x2000).unwrap(); + prep.set_pass_dirty(1,0x1000,0x2000,0x200).unwrap(); + pub_retire(&mut s,1,&a); + // Synchronous small claim on slot 0 only zeroes 0..0x2000 and leaves 0x2000..0x10000 dirty. + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + assert_eq!(render.passes[0].tilemap.fills.lock().unwrap().last(),Some(&(0,0x2000))); + assert_eq!(render.passes[0].tilemap.snapshot()[0x2000],0x55); + prep.set_pass_dirty(0,0x1000,0x2000,0x1000).unwrap(); // multi-layer heap=0x1000 + render.passes[0].tilemap.fill(0,0x66,0x2000).unwrap(); + render.passes[0].heap.fill(0,0x77,0x1000).unwrap(); + pub_retire(&mut s,0,&a); + // Slot 2 retires to displace slot 0; both slot 0 (partial) and slot 1 (fully clean) scrub off-lock. + s.claim_pass_in(&prep,2,Some(a.id),0x2000).unwrap(); + prep.set_pass_dirty(2,0x1000,0x2000,0x200).unwrap(); + pub_retire(&mut s,2,&a); + s.stage_displaced_pass_scrubs(); + let _=drain_scrubs(s.take_staged_scrubs()); + // Slot 0 off-lock scrubbed ONLY 0..0x2000 tilemap and 0..0x1000 heap; high-water 0x10000 preserved! + assert_eq!(render.tilemap_dirty[0].load(std::sync::atomic::Ordering::Acquire),0x10000); + assert_eq!(render.tilemap_clean[0].load(std::sync::atomic::Ordering::Acquire),0x2000); + assert_eq!(render.heap_dirty[0].load(std::sync::atomic::Ordering::Acquire),0); + assert!(render.passes[0].tilemap.snapshot()[..0x2000].iter().all(|&x|x==0)); + assert_eq!(render.passes[0].tilemap.snapshot()[0x2000],0x55); + assert!(render.passes[0].heap.snapshot()[..0x1000].iter().all(|&x|x==0)); + // Slot 1 off-lock scrubbed fully (dirty=0, clean=0). + assert_eq!(render.tilemap_dirty[1].load(std::sync::atomic::Ordering::Acquire),0); + assert_eq!(render.tilemap_clean[1].load(std::sync::atomic::Ordering::Acquire),0); + // Cursor starts at 0 (after slot 2): small pass (0x2000) picks slot 0 (exact clean prefix), + // while large pass (0x8000) prefers slot 1 (zero sync delta) over partial-clean slot 0! + let small=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x2000}; + let large=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x8000}; + assert_eq!(s.pick_pass_in(&prep,&small,0),Some(0)); + assert_eq!(s.pick_pass_in(&prep,&large,0),Some(1)); + // Claiming partial-clean slot 0 for a medium pass (0x6000) zeroes ONLY tail delta (0x2000, 0x4000) + // and performs zero heap fills. + let heap_before=render.passes[0].heap.fills.lock().unwrap().len(); + s.claim_pass_in(&prep,0,Some(a.id),0x6000).unwrap(); + assert_eq!(render.passes[0].tilemap.fills.lock().unwrap().last(),Some(&(0x2000,0x4000))); + assert_eq!(render.passes[0].heap.fills.lock().unwrap().len(),heap_before); + assert!(render.passes[0].tilemap.snapshot()[..0x6000].iter().all(|&x|x==0)); + assert_eq!(render.passes[0].tilemap.snapshot()[0x6000],0x55); + pub_retire(&mut s,0,&a); + // Cross-VM switch on slot 0 still full-scrubs the preserved high-water mark (0x10000) + full heap (0x4000). + s.claim_pass_in(&prep,1,Some(a.id),0x2000).unwrap(); + pub_retire(&mut s,1,&a); + s.claim_pass_in(&prep,0,Some(b.id),0x2000).unwrap(); + assert_eq!(render.passes[0].tilemap.fills.lock().unwrap().last(),Some(&(0,0x10000))); + assert_eq!(render.passes[0].heap.fills.lock().unwrap().last(),Some(&(0,0x4000))); + assert!(render.passes[0].tilemap.snapshot()[..0x10000].iter().all(|&x|x==0)); + } + #[test]fn queue_graph_objects_cache_only_firmware_owned_records(){ + use g16::object::Class; + use g16::graph::{ComputeGraph, FwAbi, RenderGraph, cmd_fw, cmd_shared, graph_fw, qinfo_cached}; + assert_eq!(graph_fw(), Class::FwCached); + assert!(qinfo_cached()); + assert_eq!(cmd_fw(), Class::Fw); + assert_eq!(cmd_shared(), Class::Shared); + let mut o = Objects::new(); + let mut rings = Objects::persistent(); + let ctx = o.alloc(g16::object::Request { + size: 0x40, + class: Class::Fw, + placement: g16::object::Placement::Anywhere, + offset: 0, + client: None, + lower: None, + cpu: true, + }).unwrap(); + let c = ComputeGraph::new(&mut o, &mut rings, ctx.clone()).unwrap(); + let c1 = ComputeGraph::new(&mut o, &mut rings, ctx.clone()).unwrap(); + let r = RenderGraph::new(&mut o, &mut rings, ctx).unwrap(); + c.init(FwAbi, true).unwrap(); + c1.init(FwAbi, false).unwrap(); + r.init(FwAbi).unwrap(); + assert_eq!(c.sched_ctx.va, c1.sched_ctx.va); + assert_ne!(c.qinfo.va, c1.qinfo.va); + assert_ne!(c.fw_stamp.va, c1.fw_stamp.va); + assert_eq!(c1.qinfo.class, Class::FwCached); + assert_eq!(c1.qstate.class, Class::Fw); + assert_eq!(c1.ring.class, Class::FwCoherent); + assert_eq!(c1.fw_stamp.class, Class::Shared); + assert_eq!(c.qinfo.class, Class::FwCached); + assert_eq!(c.qscratch.class, Class::FwCached); + assert_eq!(c.job_list.class, Class::FwCached); + assert_eq!(c.sched_ctx.class, Class::Fw); + assert_eq!(c.qstate.class, Class::Fw); + assert_eq!(c.notifier.class, Class::Fw); + assert_eq!(c.threshold.class, Class::Fw); + assert_eq!(c.ring.class, Class::FwCoherent); + assert_eq!(c.user_stamp.class, Class::Shared); + assert_eq!(c.fw_stamp.class, Class::Shared); + for stage in 0..2 { + assert_eq!(r.qinfo[stage].class, Class::FwCached); + assert_eq!(r.qscratch[stage].class, Class::FwCached); + assert_eq!(r.job_list[stage].class, Class::FwCached); + assert_eq!(r.qstate[stage].class, Class::Fw); + assert_eq!(r.ring[stage].class, Class::FwCoherent); + assert_eq!(r.user_stamp[stage].class, Class::Shared); + assert_eq!(r.fw_stamp[stage].class, Class::Shared); + } + assert_eq!(r.sched_ctx.class, Class::Fw); + assert_eq!(r.notifier.class, Class::Fw); + assert_eq!(r.threshold.class, Class::Fw); + assert_eq!(r.legacy_empty.class, Class::Shared); + assert_eq!(r.registration_barrier.class, Class::Fw); + } + + #[test]fn pb_heap_growth_rotates_to_expanded_epoch_and_falls_back_under_quarantine(){ + use g16::fw::buffer; + use g16::hw::client; + use g16::pools::{PbEpoch, Pools, alloc_pb_heap_chunk}; + + // Demand-grown PB heap chunks map contiguously right after the 64 MiB base heap + // inside PB_HEAP_SIZE (256 MiB) and reject out-of-range or zero-sized chunks. + let mut o = Objects::new(); + let tier0 = alloc_pb_heap_chunk(&mut o, 512, 512).unwrap(); + let tier1 = alloc_pb_heap_chunk(&mut o, 1024, 1024).unwrap(); + assert_eq!(tier0.gva, Some(client::pb_heap(0) + 512 * buffer::BLOCK_BYTES)); + assert_eq!(tier0.size, 512 * buffer::BLOCK_BYTES as usize); + assert_eq!(tier1.gva, Some(client::pb_heap(0) + 1024 * buffer::BLOCK_BYTES)); + assert_eq!(tier1.size, 1024 * buffer::BLOCK_BYTES as usize); + assert!(alloc_pb_heap_chunk(&mut o, 512, 0).is_err()); + assert!(alloc_pb_heap_chunk(&mut o, 1024, 1025).is_err()); + + // Start VM1 with a 512-block (64 MiB) warm epoch on slot 0. + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let vm1 = vm(1); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let e512 = PbEpoch::new(&factory, &vm1, g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap()).unwrap(); + e512.prepare(0, client::pb_heap(0), 512).unwrap(); + assert_eq!(e512.heap_blocks(), 512); + e512.expose(); + let b0 = p.bind(0, false); + p.publish_flight(0); + p.retire_flight(0, &e512, b0, true).unwrap(); + + // At 512 blocks VM1 pipelines cleanly on slot 0. + assert!(p.can_pipeline_within_blocks(&vm1, 2, 512)); + assert_eq!(p.pick_slot_within_blocks(&vm1, true, 2, 512), Some(0)); + + // Once VM1 expands its PB heap to 1024 blocks (128 MiB), slot 0's 512-block epoch + // refuses pipelining so the engine drains once and rotates onto displaced slot 1. + assert!(!p.can_pipeline_within_blocks(&vm1, 2, 1024)); + assert_eq!(p.pick_slot_within_blocks(&vm1, true, 2, 1024), None); + assert_eq!(p.pick_slot_within_blocks(&vm1, false, 2, 1024), Some(1)); + assert!(p.reusable_for_within(0, &vm1, 2, 1024).is_none()); + + let e1024 = PbEpoch::new(&factory, &vm1, g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap()).unwrap(); + e1024.prepare(1, client::pb_heap(0), 1024).unwrap(); + assert_eq!(e1024.heap_blocks(), 1024); + e1024.expose(); + let b1 = p.bind(1, false); + p.publish_flight(1); + p.retire_flight(1, &e1024, b1, true).unwrap(); + + // Slot 1 now pipelines at 1024 blocks; expanding to 2048 rotates cleanly back to displaced slot 0. + assert!(p.can_pipeline_within_blocks(&vm1, 2, 1024)); + assert_eq!(p.pick_slot_within_blocks(&vm1, true, 2, 1024), Some(1)); + assert!(!p.can_pipeline_within_blocks(&vm1, 2, 2048)); + assert_eq!(p.pick_slot_within_blocks(&vm1, false, 2, 2048), Some(0)); + + // Quarantine edge case: if slot 0 is quarantined so no displaced slot remains in 0..2, + // VM1 safely falls back to reusing its warm 1024-block slot 1 instead of deadlocking. + p.quarantine_flight(0, None); + assert!(p.can_pipeline_within_blocks(&vm1, 2, 2048)); + assert_eq!(p.pick_slot_within_blocks(&vm1, true, 2, 2048), Some(1)); + assert!(p.reusable_for_within(1, &vm1, 2, 2048).is_some()); + } + + #[test]fn vm_affine_compute_claiming_keeps_four_interleaved_vms_warm(){ + let mut o = Objects::new(); + let mut s = Slots::new().unwrap(); + let mut units = KVec::new(); + for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { + units.push(g16::slots::ComputeSlot::new(&mut o, &g16::object::Factory, k, &crate::g16::object::test_unit_cmds(k)).unwrap(), 0).unwrap(); + } + let prep = g16::resources::ComputeArena { compute: units, render: None, hw_slots: None }; + let vms = [vm(1), vm(2), vm(3), vm(4)]; + // Round 0 warms one unit per VM (4 units out of 24); VM2's retirement displaces VM1's + // unit immediately so from round 1 onward every sequential interleaved claim is warm. + for v in &vms { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + assert!(s.compute_needs_full_work(k)); + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + s.retire(&mut c).unwrap(); + } + assert_eq!(s.stats.cross_vm_retargets[0], 0); + for _round in 0..4 { + for v in &vms { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + assert!(!s.compute_needs_full_work(k)); + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + s.retire(&mut c).unwrap(); + } + } + assert_eq!(s.stats.cross_vm_retargets[0], 0); + // Pipelined depth-2 per VM across 4 concurrent VMs warms one additional unit per VM + // from the unowned pool and then reuses warm VM-owned units with zero cross-VM scrubs. + let mut live: Vec = Vec::new(); + for (idx, v) in vms.iter().enumerate() { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + if idx < 3 { + assert!(!s.compute_needs_full_work(k)); + } + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + live.push(c); + } + for _round in 0..4 { + for (idx, v) in vms.iter().enumerate() { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + if _round > 0 { + assert!(!s.compute_needs_full_work(k)); + } + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + let mut old = std::mem::replace(&mut live[idx], c); + s.retire(&mut old).unwrap(); + } + } + for mut c in live { + s.retire(&mut c).unwrap(); + } + assert_eq!(s.stats.cross_vm_retargets[0], 0); + } + + #[test]fn warm_pb_pool_keeps_sixteen_concurrent_vms_warm_and_handles_overflow(){ + let warm = g16::hw::sizes::WARM_PB_SLOTS; + assert_eq!(warm, 16); + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mk_epoch = |owner: &sync::Arc, slot: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + owner, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(slot, g16::hw::client::pb_heap(0), 512).unwrap(); + e.check_assignment(slot).unwrap(); + e.expose(); + e + }; + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let vms: Vec<_> = (0..20usize).map(|i| vm(100 + i as u64)).collect(); + let mask_for = |i: usize| -> (u32, usize) { + let home = i % warm; + let alt = (home + 1) % warm; + ((1u32 << home) | (1u32 << alt), home) + }; + // Prime 16 VMs arriving in scrambled (reverse) order: each claims its own home slot! + let mut epochs = Vec::new(); + for i in (0..warm).rev() { + let (mask, home) = mask_for(i); + let slot = p.pick_slot_in_mask_blocks_mode(&vms[i], false, mask, home, 512, false).unwrap(); + assert_eq!(slot, home, "VM {i} must claim its home slot {home} despite reverse arrival"); + let e = mk_epoch(&vms[i], slot); + let b = p.bind(slot, false); + p.publish_flight(slot); + p.retire_flight(slot, &e, b, true).unwrap(); + epochs.push((i, e)); + } + // All 16 VMs now pipeline concurrently (behind=true) on 16 disjoint warm slots with 0 InitBM. + let mut binds = Vec::new(); + for &(i, ref _e) in &epochs { + let (mask, home) = mask_for(i); + assert!(p.can_pipeline_in_mask_blocks_mode(&vms[i], mask, home, 512, false)); + let slot = p.pick_slot_in_mask_blocks_mode(&vms[i], true, mask, home, 512, false).unwrap(); + assert_eq!(slot, home); + assert!(p.reusable_for_mask_mode(slot, &vms[i], mask, 512, false).is_some()); + let b = p.bind(slot, true); + p.publish_flight(slot); + binds.push((i, slot, b)); + } + for (idx, (i, slot, b)) in binds.into_iter().enumerate() { + assert_eq!(p.slot_inflight(slot), 1); + p.retire_flight(slot, &epochs[idx].1, b, true).unwrap(); + assert_eq!(p.slot_inflight(slot), 0); + let _ = i; + } + // Overflow d=20: VMs 16..20 share warm slots [0..4] cleanly on drained displaced rotation. + for i in warm..20 { + let (mask, home) = mask_for(i); + assert!(!p.can_pipeline_in_mask_blocks_mode(&vms[i], mask, home, 512, false)); + let slot = p.pick_slot_in_mask_blocks_mode(&vms[i], false, mask, home, 512, false).unwrap(); + assert_ne!(mask & (1u32 << slot), 0); + let e = mk_epoch(&vms[i], slot); + let b = p.bind(slot, false); + p.publish_flight(slot); + p.retire_flight(slot, &e, b, true).unwrap(); + } + } + + #[test]fn vm_affine_render_pass_claiming_keeps_sixteen_vms_warm_and_scales_tier1(){ + use g16::resources::{BASE_RENDER_SLOTS, EXT_RENDER_TIERS, target_render_slots_for}; + // Steady 60 Hz depth-1 VM stays at BASE_RENDER_SLOTS even when 16 render VMs are active. + let (mut last, mut burst) = (0u64, 0u32); + let (eff, single) = target_render_slots_for(&mut last, &mut burst, 10_000_000, 1, 0, false, BASE_RENDER_SLOTS, BASE_RENDER_SLOTS, 16); + assert_eq!((eff, single), (BASE_RENDER_SLOTS, BASE_RENDER_SLOTS)); + // Bursting VM with 4 active render VMs stays at Tier 0 (8 slots). + for step in 1..=3u64 { + let (e, s) = target_render_slots_for(&mut last, &mut burst, 10_000_000 + step * 500_000, 1, 0, false, BASE_RENDER_SLOTS, BASE_RENDER_SLOTS, 4); + if step < 3 { + assert_eq!((e, s), (BASE_RENDER_SLOTS, BASE_RENDER_SLOTS)); + } else { + assert_eq!((e, s), (EXT_RENDER_TIERS[0].1, EXT_RENDER_TIERS[0].1)); + } + } + // Once active_render_vms reaches 8 or 16, a bursting VM expands effective target to Tier 1 + // (18 slots) while keeping single_vm_target at Tier 0 (8) so PB_HEAP_EXT_TIERS[1] stays off. + let (eff8, single8) = target_render_slots_for(&mut last, &mut burst, 12_000_000, 1, 0, false, EXT_RENDER_TIERS[0].1, EXT_RENDER_TIERS[0].1, 8); + assert_eq!((eff8, single8), (EXT_RENDER_TIERS[1].1, EXT_RENDER_TIERS[0].1)); + let (eff16, single16) = target_render_slots_for(&mut last, &mut burst, 12_500_000, 1, 0, false, eff8, single8, 16); + assert_eq!((eff16, single16), (EXT_RENDER_TIERS[1].1, EXT_RENDER_TIERS[0].1)); + // Heavy single-VM multi-pass (8 passes) still advances single_vm_target to Tier 1. + let (eff_heavy, single_heavy) = target_render_slots_for(&mut last, &mut burst, 13_000_000, 8, 0, false, eff16, single16, 16); + assert_eq!((eff_heavy, single_heavy), (EXT_RENDER_TIERS[1].1, EXT_RENDER_TIERS[1].1)); + + // 16 concurrent VMs across 18 pass slots stay on 16 disjoint warm pass slots with 0 cross-VM retargets. + let mut o = Objects::new(); + let mut s = Slots::new().unwrap(); + let mut passes = KVec::new(); + for k in 0..EXT_RENDER_TIERS[1].1 { + passes.push(g16::slots::PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); + } + let render = sync::Arc::new(render_arena(passes), 0).unwrap(); + let prep = g16::resources::ComputeArena { + compute: KVec::new(), + render: Some(render), + hw_slots: None, + }; + let geo = g16::encode::Geometry { tpc_bytes: 0x1000, tilemap_bytes: 0x2000 }; + let vms: Vec<_> = (0..16u64).map(|i| vm(200 + i)).collect(); + let mut vm_slots = [usize::MAX; 16]; + for (i, v) in vms.iter().enumerate() { + let k = s.pick_pass_in_for(&prep, &geo, 0, Some(v.id)).unwrap(); + s.claim_pass_in(&prep, k, Some(v.id), geo.tilemap_bytes).unwrap(); + assert!(s.render_needs_full_work(k)); + let mut c = Claims::new(); + c.pass[0] = k as u32; c.pass_count = 1; c.pass_mask = 1u64 << k; + s.hold_render_pass(k, v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + vm_slots[i] = k; + } + assert_eq!(s.stats.cross_vm_retargets[1], 0); + // Subsequent interleaved rounds across all 16 VMs hit their own warm pass slots every time! + for _round in 0..4 { + for (i, v) in vms.iter().enumerate() { + let k = s.pick_pass_in_for(&prep, &geo, 0, Some(v.id)).unwrap(); + assert_eq!(k, vm_slots[i], "VM {i} must stay on its warm pass slot"); + s.claim_pass_in(&prep, k, Some(v.id), geo.tilemap_bytes).unwrap(); + assert!(!s.render_needs_full_work(k)); + let mut c = Claims::new(); + c.pass[0] = k as u32; c.pass_count = 1; c.pass_mask = 1u64 << k; + s.hold_render_pass(k, v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + } + assert_eq!(s.stats.cross_vm_retargets[1], 0); + } + + #[test]fn pb_epoch_prepare_seeds_active_prefix_and_clears_shrink_tail(){ + use g16::fw::buffer; + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let v = vm(300); + g16::object::ALL_OBJECTS.with(|a| a.borrow_mut().clear()); + let e = g16::pools::PbEpoch::new( + &factory, + &v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + let (page_obj, block_obj) = g16::object::ALL_OBJECTS.with(|a| { + let objs = a.borrow(); + ( + objs.iter().find(|o| o.gva.is_some() && o.size == buffer::PAGE_LIST_SIZE).unwrap().clone(), + objs.iter().find(|o| o.gva.is_none() && o.size == buffer::BLOCK_LIST_SIZE).unwrap().clone(), + ) + }); + let heap = g16::hw::client::pb_heap(0); + // First prepare for 512 blocks writes ONLY 512*4*4 = 8192 page bytes and 512*8 = 4096 block bytes. + e.prepare(0, heap, 512).unwrap(); + assert_eq!(page_obj.write_bytes.load(std::sync::atomic::Ordering::Relaxed), 512 * 4 * 4); + assert_eq!(block_obj.write_bytes.load(std::sync::atomic::Ordering::Relaxed), 512 * 8); + assert_eq!(page_obj.r32(512 * 4 * 4).unwrap(), 0); + assert_eq!(block_obj.r32(512 * 8).unwrap(), 0); + // Grow unpublished epoch to 1024 blocks, then shrink retry back to 512 blocks: + // tail [512..1024] must be zeroed cleanly. + e.prepare(1, heap, 1024).unwrap(); + assert_ne!(page_obj.r32(512 * 4 * 4).unwrap(), 0); + assert_ne!(block_obj.r32(512 * 8).unwrap(), 0); + e.prepare(2, heap, 512).unwrap(); + assert_eq!(page_obj.r32(512 * 4 * 4).unwrap(), 0); + assert_eq!(block_obj.r32(512 * 8).unwrap(), 0); + assert_eq!(page_obj.r32(1023 * 4 * 4).unwrap(), 0); + assert_eq!(block_obj.r32(1023 * 8).unwrap(), 0); + } + + #[test]fn closed_vms_reclaim_displaced_pb_render_and_compute_slots(){ + use g16::hw::sizes::{COMPUTE_UNITS, WARM_PB_SLOTS}; + use g16::resources::{COMPUTE_OWNER_ARENA, ComputeArena, PbOwnerArena}; + use g16::slots::{ComputeSlot, PassSlot}; + + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let mut s = Slots::new().unwrap(); + let mut o = Objects::new(); + + let mut compute_slots = KVec::new(); + for k in 0..COMPUTE_UNITS { + compute_slots.push(ComputeSlot::new(&mut o, &g16::object::Factory, k as u64, &crate::g16::object::test_unit_cmds(k as u64)).unwrap(), 0).unwrap(); + } + let mut passes = KVec::new(); + for k in 0..18 { + passes.push(PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); + } + let shared_prep_compute = ComputeArena { compute: compute_slots, render: None, hw_slots: None }; + let geo = g16::encode::Geometry { tpc_bytes: 0x1000, tilemap_bytes: 0x2000 }; + + let mut vms = Vec::new(); + let mut epochs = Vec::new(); + let mut pb_arenas = Vec::new(); + let mut pass_arenas = Vec::new(); + let mut comp_arenas = Vec::new(); + + // Bind and retire 16 concurrent VMs across 16 PB slots, 16 render passes, and 16 compute units. + for i in 0..WARM_PB_SLOTS { + let v = vm(400 + i as u64); + let pb_arena = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let mut r_passes = KVec::new(); + for k in 0..18 { + r_passes.push(PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); + } + let r_arena = sync::Arc::new(render_arena(r_passes), 0).unwrap(); + let r_prep = ComputeArena { compute: KVec::new(), render: Some(r_arena.clone()), hw_slots: None }; + let c_arena = sync::Arc::new( + ComputeArena { compute: KVec::new(), render: None, hw_slots: None }, 0, + ).unwrap(); + + // 1) PB warm slot i + let mask = (1u32 << i) | (1u32 << ((i + 1) % WARM_PB_SLOTS)); + let pb_slot = p + .pick_slot_in_mask_blocks_mode(&v, false, mask, i, 512, false) + .unwrap(); + assert_eq!(pb_slot, i); + let e = g16::pools::PbEpoch::new( + &factory, + &v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(pb_slot, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + let b = p.bind(pb_slot, false); + p.hold_alloc(pb_slot, &v, Some(PbOwnerArena::Base(pb_arena.clone())), None).unwrap(); + p.publish_flight(pb_slot); + p.retire_flight(pb_slot, &e, b, true).unwrap(); + + // 2) Render pass slot i + let pk = s.pick_pass_in_for(&r_prep, &geo, 0, Some(v.id)).unwrap(); + s.claim_pass_in(&r_prep, pk, Some(v.id), geo.tilemap_bytes).unwrap(); + let mut rc = Claims::new(); + rc.pass[0] = pk as u32; + rc.pass_count = 1; + rc.pass_mask = 1u64 << pk; + s.hold_render_pass(pk, &v, &r_prep).unwrap(); + s.publish(&mut rc).unwrap(); + s.retire(&mut rc).unwrap(); + + // 3) Compute unit i + let mut cc = Claims::new(); + let ck = s + .claim_compute_for(&shared_prep_compute, &mut cc, Some(v.id)) + .unwrap() + .unwrap(); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = Some(c_arena.clone())); + s.hold_compute_slot(ck, &v, &shared_prep_compute).unwrap(); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = None); + s.publish(&mut cc).unwrap(); + s.retire(&mut cc).unwrap(); + + vms.push(v); + epochs.push(e); + pb_arenas.push(pb_arena); + pass_arenas.push(r_arena); + comp_arenas.push(c_arena); + } + + // Live VMs stay pinned and reusable across reclaim_closed(). + assert!(!p.reclaim_closed()); + assert!(!s.reclaim_closed()); + for i in 0..WARM_PB_SLOTS { + assert!(sync::Arc::strong_count(&pb_arenas[i]) > 1); + assert!(sync::Arc::strong_count(&pass_arenas[i]) > 1); + assert!(sync::Arc::strong_count(&comp_arenas[i]) > 1); + assert!(p.reusable(i, &vms[i]).is_some()); + } + + // Close all 16 VMs: displaced slots 0..15 reclaim immediately; undisplaced slot 15 stays. + for v in &vms { + v.vm.close(); + } + assert!(p.reclaim_closed(), "undisplaced PB slot 15 remains"); + assert!(s.reclaim_closed(), "undisplaced render/compute slot 15 remain"); + // Displaced pass scrubs must skip closed VMs. + s.stage_displaced_pass_scrubs(); + assert!(!s.scrubbing_active()); + + for i in 0..(WARM_PB_SLOTS - 1) { + assert_eq!(sync::Arc::strong_count(&pb_arenas[i]), 1, "PB arena {i} reclaimed"); + // pb_mgr_table[i] still names this epoch's manager: it stays until replaced. + assert_eq!(sync::Arc::strong_count(&epochs[i]), 2, "PB epoch {i} still bound"); + assert_eq!(sync::Arc::strong_count(&pass_arenas[i]), 1, "pass arena {i} reclaimed"); + assert_eq!(sync::Arc::strong_count(&comp_arenas[i]), 1, "compute arena {i} reclaimed"); + // Drop our local epoch ref to confirm VmState itself has only our Vec ref left. + assert_eq!(sync::Arc::strong_count(&vms[i]), 2); + } + // Final undisplaced slot 15 stays protected until displaced. + let last = WARM_PB_SLOTS - 1; + assert_eq!(sync::Arc::strong_count(&pb_arenas[last]), 2); + assert_eq!(sync::Arc::strong_count(&pass_arenas[last]), 2); + assert_eq!(sync::Arc::strong_count(&comp_arenas[last]), 2); + + // Live VM 17 runs 1 render + 1 compute, displacing slot 15 everywhere. + let live = vm(500); + let live_r_arena = sync::Arc::new(render_arena(passes), 0).unwrap(); + let live_r_prep = ComputeArena { compute: KVec::new(), render: Some(live_r_arena.clone()), hw_slots: None }; + let live_slot = p + .pick_slot_in_mask_blocks_mode(&live, false, 0b11, 0, 512, false) + .unwrap(); + assert_eq!(live_slot, 0); + let live_e = g16::pools::PbEpoch::new( + &factory, + &live, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + live_e.prepare(live_slot, g16::hw::client::pb_heap(0), 512).unwrap(); + live_e.expose(); + let lb = p.bind(live_slot, false); + p.hold_alloc(live_slot, &live, Some(PbOwnerArena::Base(live_r_arena.clone())), None).unwrap(); + p.publish_flight(live_slot); + p.retire_flight(live_slot, &live_e, lb, true).unwrap(); + + let lpk = s.pick_pass_in_for(&live_r_prep, &geo, 0, Some(live.id)).unwrap(); + s.claim_pass_in(&live_r_prep, lpk, Some(live.id), geo.tilemap_bytes).unwrap(); + let mut lrc = Claims::new(); + lrc.pass[0] = lpk as u32; + lrc.pass_count = 1; + lrc.pass_mask = 1u64 << lpk; + s.hold_render_pass(lpk, &live, &live_r_prep).unwrap(); + s.publish(&mut lrc).unwrap(); + s.retire(&mut lrc).unwrap(); + + let mut lcc = Claims::new(); + let lck = s + .claim_compute_for(&shared_prep_compute, &mut lcc, Some(live.id)) + .unwrap() + .unwrap(); + s.hold_compute_slot(lck, &live, &shared_prep_compute).unwrap(); + s.publish(&mut lcc).unwrap(); + s.retire(&mut lcc).unwrap(); + + // Now slot 15 is displaced -> reclaim_closed() evicts it and returns false (0 remaining). + assert!(!p.reclaim_closed()); + assert!(!s.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&pb_arenas[last]), 1); + assert_eq!(sync::Arc::strong_count(&pass_arenas[last]), 1); + assert_eq!(sync::Arc::strong_count(&comp_arenas[last]), 1); + // VM 17's epoch replaced slot 0's; the other slots keep their closed owners' epochs. + assert_eq!(sync::Arc::strong_count(&epochs[0]), 1, "replaced PB epoch 0 released"); + for i in 1..WARM_PB_SLOTS { + assert_eq!(sync::Arc::strong_count(&epochs[i]), 2, "PB epoch {i} still bound"); + } + // Each epoch is released once a newer epoch retires on its own slot. + for i in 1..WARM_PB_SLOTS { + let next = vm(520 + i as u64); + let e = g16::pools::PbEpoch::new( + &factory, + &next, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(i, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + let b = p.bind(i, false); + p.hold_alloc(i, &next, None, None).unwrap(); + p.publish_flight(i); + p.retire_flight(i, &e, b, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&epochs[i]), 1, "replaced PB epoch {i} released"); + } + assert!(!p.reclaim_closed()); + drop(epochs); + for (i, v) in vms.iter().enumerate() { + assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released"); + } + + // Active off-lock scrub on a closed VM's displaced pass slot waits for scrub completion. + let mut s2 = Slots::new().unwrap(); + let mut sc_passes = KVec::new(); + for k in 0..2 { + sc_passes.push(PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); + } + let sc_arena = sync::Arc::new(render_arena(sc_passes), 0).unwrap(); + let sc_prep = ComputeArena { compute: KVec::new(), render: Some(sc_arena.clone()), hw_slots: None }; + let va = vm(600); + let vb = vm(601); + for (k, owner) in [(0usize, &va), (1usize, &vb)] { + s2.claim_pass_in(&sc_prep, k, Some(owner.id), 0x2000).unwrap(); + sc_prep.set_pass_dirty(k, 0x1000, 0x2000, 0x200).unwrap(); + let mut c = Claims::new(); + c.pass[0] = k as u32; + c.pass_count = 1; + c.pass_mask = 1u64 << k; + s2.hold_render_pass(k, owner, &sc_prep).unwrap(); + s2.publish(&mut c).unwrap(); + s2.retire(&mut c).unwrap(); + } + // Stage off-lock scrub on displaced slot 0 while va is still open, then close va. + s2.stage_displaced_pass_scrubs(); + assert!(s2.scrubbing_active()); + let batch = s2.take_staged_scrubs(); + va.vm.close(); + assert!(s2.reclaim_closed(), "must not evict slot 0 mid-scrub"); + assert_eq!(sync::Arc::strong_count(&va), 2); + // Running the scrub wakes the reclaim waiter, then reclaim_closed() evicts slot 0. + assert!(drain_scrubs(batch)); + assert!(s2.take_scrub_woke()); + assert!(!s2.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&va), 1); + + // Quarantined closed-VM slots stay pinned forever AND do not keep reclaim_closed() armed. + let vq = vm(700); + let mut pq = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let eq = g16::pools::PbEpoch::new( + &factory, + &vq, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + pq.hold_alloc(0, &vq, Some(PbOwnerArena::Base(sc_arena.clone())), None).unwrap(); + pq.publish_flight(0); + pq.quarantine_flight(0, Some(eq.clone())); + let mut cq = Claims::new(); + let qk = s2.claim_compute_for(&shared_prep_compute, &mut cq, Some(vq.id)).unwrap().unwrap(); + s2.hold_compute_slot(qk, &vq, &shared_prep_compute).unwrap(); + s2.publish(&mut cq).unwrap(); + s2.quarantine(&mut cq); + vq.vm.close(); + assert!(!pq.reclaim_closed(), "quarantined PB slot must not spin reclaim"); + assert!(!s2.reclaim_closed(), "quarantined compute slot must not spin reclaim"); + assert!(sync::Arc::strong_count(&vq) > 1, "quarantined leases stay retained"); + } + + #[test]fn dual_pipe_closed_compute_vms_pin_only_one_unit_per_pipe(){ + use g16::hw::sizes::COMPUTE_UNITS; + use g16::resources::{COMPUTE_OWNER_ARENAS, ComputeArena}; + use g16::slots::ComputeSlot; + + let mut o = Objects::new(); + let mut s = Slots::new().unwrap(); + let mut compute_slots = KVec::new(); + for k in 0..COMPUTE_UNITS { + compute_slots.push(ComputeSlot::new(&mut o, &g16::object::Factory, k as u64, &crate::g16::object::test_unit_cmds(k as u64)).unwrap(), 0).unwrap(); + } + let prep = ComputeArena { compute: compute_slots, render: None, hw_slots: None }; + + // Simulate 8 compute VMs, each owning 24 independent per-unit ComputeArenas + // (matching production ComputeUnitSet), running across BOTH CDM pipes (0 and 1). + let mut vms = Vec::new(); + let mut vm_unit_arenas: Vec>> = Vec::new(); + for i in 0..8usize { + let v = vm(800 + i as u64); + let mut per_unit = Vec::with_capacity(COMPUTE_UNITS); + for _ in 0..COMPUTE_UNITS { + per_unit.push( + sync::Arc::new( + ComputeArena { compute: KVec::new(), render: None, hw_slots: None }, + 0, + ) + .unwrap(), + ); + } + COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = Some(per_unit.clone())); + for pipe in [0usize, 1usize] { + let mut c = Claims::new(); + let k = s.claim_compute_for_pipe(&prep, &mut c, Some(v.id), pipe).unwrap().unwrap(); + s.hold_compute_slot(k, &v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = None); + vms.push(v); + vm_unit_arenas.push(per_unit); + } + + // Close all 8 VMs and reclaim displaced leases: + // - Pipe 0 and pipe 1 each retain 1 undisplaced last-retired unit -> reusable == 22. + // - Out of 8 * 24 = 192 per-unit arenas, ONLY those 2 undisplaced units remain pinned + // (strong_count == 2); all 190 other units (including the other 23 units of each + // last-retired VM) drop immediately (strong_count == 1). + for v in &vms { + v.vm.close(); + } + assert!(s.reclaim_closed(), "two undisplaced dual-pipe units remain"); + assert_eq!(s.lifetime_counts()[0].reusable, (COMPUTE_UNITS - 2) as u32); + let pinned_units: usize = vm_unit_arenas + .iter() + .flat_map(|units| units.iter()) + .filter(|arena| sync::Arc::strong_count(arena) > 1) + .count(); + assert_eq!(pinned_units, 2, "must pin exactly 1 unit per CDM pipe, never a whole VM set"); + for (i, units) in vm_unit_arenas.iter().enumerate() { + let vm_pinned = units.iter().filter(|a| sync::Arc::strong_count(a) > 1).count(); + if i == 7 { + assert_eq!(vm_pinned, 2, "last VM holds only its 2 undisplaced units"); + } else { + assert_eq!(vm_pinned, 0, "displaced closed VM {i} holds 0 units"); + assert_eq!(sync::Arc::strong_count(&vms[i]), 1, "closed VM {i} fully released"); + } + } + + // Displace pipe 0 and pipe 1 with a live VM -> all 8 closed VMs and 192 units release. + let live = vm(900); + for pipe in [0usize, 1usize] { + let mut c = Claims::new(); + let k = s.claim_compute_for_pipe(&prep, &mut c, Some(live.id), pipe).unwrap().unwrap(); + s.hold_compute_slot(k, &live, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + assert!(!s.reclaim_closed(), "both dual-pipe closed leases displaced and reclaimed"); + let pinned_after: usize = vm_unit_arenas + .iter() + .flat_map(|units| units.iter()) + .filter(|arena| sync::Arc::strong_count(arena) > 1) + .count(); + assert_eq!(pinned_after, 0); + for (i, v) in vms.iter().enumerate() { + assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released after displacement"); + } + } + + #[test]fn closed_vm_reclaim_retains_firmware_pb_and_uma_leases_until_overwritten(){ + use g16::hw::sizes::{COMPUTE_UNITS, WARM_PB_SLOTS}; + use g16::resources::{COMPUTE_OWNER_ARENA, ComputeArena, PbOwnerArena}; + use g16::slots::ComputeSlot; + + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let mut s = Slots::new().unwrap(); + let mut o = Objects::new(); + + // VM1 primes PB/UMA slot 0 and compute unit 0; VM2 displaces both via slot 1 / unit 1. + let vm1 = vm(1001); + let vm2 = vm(1002); + let vm3 = vm(1003); + + let pools1 = PoolSet::new_with_slots(&mut o, &factory, [0, 1]).unwrap(); + let uma1 = pools1.unit(0).unwrap().uma_lease(); + let r_arena1 = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let e1 = g16::pools::PbEpoch::new( + &factory, + &vm1, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + let pb_lease1 = e1.records_lease(); + e1.prepare(0, g16::hw::client::pb_heap(0), 512).unwrap(); + e1.expose(); + let b1 = p.bind(0, false); + p.hold_alloc(0, &vm1, Some(PbOwnerArena::Base(r_arena1.clone())), Some(uma1.clone())).unwrap(); + p.publish_flight(0); + p.retire_flight(0, &e1, b1, true).unwrap(); + + let pools2 = PoolSet::new_with_slots(&mut o, &factory, [1, 2]).unwrap(); + let uma2 = pools2.unit(0).unwrap().uma_lease(); + let r_arena2 = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let e2 = g16::pools::PbEpoch::new( + &factory, + &vm2, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e2.prepare(1, g16::hw::client::pb_heap(0), 512).unwrap(); + e2.expose(); + let b2 = p.bind(1, false); + p.hold_alloc(1, &vm2, Some(PbOwnerArena::Base(r_arena2.clone())), Some(uma2.clone())).unwrap(); + p.publish_flight(1); + p.retire_flight(1, &e2, b2, true).unwrap(); + + // Compute unit 0 owned by VM1, displaced by VM2 on unit 1. + let mut units1 = KVec::new(); + for k in 0..COMPUTE_UNITS { + units1.push(ComputeSlot::new(&mut o, &factory, k as u64, &crate::g16::object::test_unit_cmds(k as u64)).unwrap(), 0).unwrap(); + } + let c_uma1 = units1[0].uma_lease(); + let prep1 = ComputeArena { compute: units1, render: None, hw_slots: None }; + let c_arena1 = sync::Arc::new( + ComputeArena { compute: KVec::new(), render: None, hw_slots: None }, + 0, + ) + .unwrap(); + let mut cc1 = Claims::new(); + assert_eq!(s.claim_compute_for(&prep1, &mut cc1, Some(vm1.id)).unwrap(), Some(0)); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = Some(c_arena1.clone())); + s.hold_compute_slot(0, &vm1, &prep1).unwrap(); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = None); + s.publish(&mut cc1).unwrap(); + s.retire(&mut cc1).unwrap(); + + let mut units2 = KVec::new(); + for k in 0..COMPUTE_UNITS { + units2.push(ComputeSlot::new(&mut o, &factory, k as u64, &crate::g16::object::test_unit_cmds(k as u64)).unwrap(), 0).unwrap(); + } + let prep2 = ComputeArena { compute: units2, render: None, hw_slots: None }; + let mut cc2 = Claims::new(); + assert_eq!(s.claim_compute_for(&prep2, &mut cc2, Some(vm2.id)).unwrap(), Some(1)); + s.hold_compute_slot(1, &vm2, &prep2).unwrap(); + s.publish(&mut cc2).unwrap(); + s.retire(&mut cc2).unwrap(); + + let mut units3 = KVec::new(); + units3.push(ComputeSlot::new(&mut o, &factory, 0, &crate::g16::object::test_unit_cmds(0)).unwrap(), 0).unwrap(); + let c_uma3 = units3[0].uma_lease(); + let prep3 = ComputeArena { compute: units3, render: None, hw_slots: None }; + + // Drop local arena/epoch/pool handles for VM1 and close VM1. + drop(e1); + drop(pools1); + drop(prep1); + vm1.vm.close(); + + // Reclaim evicts VM1's RenderArena and ComputeArena immediately and retains its + // firmware PB & UMA leases until overwritten. PB slot 0's epoch keeps VM1's VmState + // (TTBAT slot) and page list until a newer epoch retires on slot 0. + assert!(!p.reclaim_closed()); + assert!(!s.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&vm1), 2, "VM1 TTBAT slot stays with its PB epoch"); + assert_eq!(sync::Arc::strong_count(&r_arena1), 1, "VM1 RenderArena/PB heap must release"); + assert_eq!(sync::Arc::strong_count(&c_arena1), 1, "VM1 ComputeArena/32MiB pool must release"); + assert_eq!(sync::Arc::strong_count(&pb_lease1), 3, "pb_mgr_table[0] lease held by epoch + retained_pb"); + assert_eq!(sync::Arc::strong_count(&uma1), 2, "render uma_mgr_table[33] lease must stay mapped"); + assert_eq!(sync::Arc::strong_count(&c_uma1), 2, "compute uma_mgr_table[1] lease must stay mapped"); + + // Cancelling an unpublished replacement on slot 0 / unit 0 must NOT release VM1's leases. + let pools3 = PoolSet::new_with_slots(&mut o, &factory, [0, 2]).unwrap(); + let uma3 = pools3.unit(0).unwrap().uma_lease(); + let r_arena3 = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + p.hold_alloc(0, &vm3, Some(PbOwnerArena::Base(r_arena3.clone())), Some(uma3.clone())).unwrap(); + p.cancel_alloc(0); + assert_eq!(sync::Arc::strong_count(&uma1), 2); + assert_eq!(sync::Arc::strong_count(&uma3), 2); + assert_eq!(sync::Arc::strong_count(&vm1), 2); + + let mut cc3_cancel = Claims::new(); + assert_eq!(s.claim_compute_for(&prep3, &mut cc3_cancel, Some(vm3.id)).unwrap(), Some(0)); + s.hold_compute_slot(0, &vm3, &prep3).unwrap(); + s.release(&mut cc3_cancel); + assert_eq!(sync::Arc::strong_count(&c_uma1), 2); + + // Once VM3 retires on exact hardware slot 0 / unit 0, firmware tables are overwritten and + // VM1's old FwLeases drop cleanly while VM3's leases become retained. + let e3 = g16::pools::PbEpoch::new( + &factory, + &vm3, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + let pb_lease3 = e3.records_lease(); + e3.prepare(0, g16::hw::client::pb_heap(0), 512).unwrap(); + e3.expose(); + let b3 = p.bind(0, false); + p.hold_alloc(0, &vm3, Some(PbOwnerArena::Base(r_arena3)), Some(uma3.clone())).unwrap(); + p.publish_flight(0); + p.retire_flight(0, &e3, b3, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&pb_lease1), 1, "overwritten pb_mgr_table[0] lease dropped"); + assert_eq!(sync::Arc::strong_count(&vm1), 1, "replaced PB epoch releases VM1's TTBAT slot"); + assert_eq!(sync::Arc::strong_count(&uma1), 1, "overwritten render uma_mgr_table[33] lease dropped"); + assert_eq!(sync::Arc::strong_count(&pb_lease3), 3, "new PB lease held by epoch + retained_pb"); + assert_eq!(sync::Arc::strong_count(&uma3), 3, "new render UMA lease held by pool + retained_uma"); + + let mut cc3 = Claims::new(); + assert_eq!(s.claim_compute_for(&prep3, &mut cc3, Some(vm3.id)).unwrap(), Some(0)); + s.hold_compute_slot(0, &vm3, &prep3).unwrap(); + s.publish(&mut cc3).unwrap(); + s.retire(&mut cc3).unwrap(); + assert_eq!(sync::Arc::strong_count(&c_uma1), 1, "overwritten compute uma_mgr_table[1] lease dropped"); + assert_eq!(sync::Arc::strong_count(&c_uma3), 3, "new compute UMA lease held by unit + retained_uma"); + let _ = WARM_PB_SLOTS; + } + + + // A closed VM's PB slot 3 is displaced by slot 4 and reclaimed. pb_mgr_table[3] still names + // its epoch's manager; gPM_SP(0) wrote that manager's page list (DYNAMIC, 0x704000cb40) + // through ctx 46 after the epoch was gone: "write unmapped level 0 unit 0xe0 ctx 46". + #[test]fn closed_vm_pb_epoch_keeps_page_list_and_context_until_slot_replacement_retires(){ + use g16::resources::PbOwnerArena; + + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let epoch = |v: &sync::Arc, k: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(k, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + e + }; + + // VM X (ctx 46) runs and retires on PB slot 3; VM Y then retires on slot 4. + let x = vm(46); + let x_arena = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let ex = epoch(&x, 3); + let x_records = ex.records_lease(); + let bx = p.bind(3, false); + p.hold_alloc(3, &x, Some(PbOwnerArena::Base(x_arena.clone())), None).unwrap(); + p.publish_flight(3); + p.retire_flight(3, &ex, bx, true).unwrap(); + let y = vm(47); + let ey = epoch(&y, 4); + let by = p.bind(4, false); + p.hold_alloc(4, &y, None, None).unwrap(); + p.publish_flight(4); + p.retire_flight(4, &ey, by, true).unwrap(); + + // X closes. Its arena and PB heap go, but not the epoch firmware still names. + x.vm.close(); + assert!(!p.reclaim_closed(), "a retained owner epoch alone must not keep reclaim armed"); + assert!(!p.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&x_arena), 1, "closed VM's render arena reclaimed"); + assert_eq!(sync::Arc::strong_count(&ex), 2, "slot 3 epoch (page list) reclaimed early"); + assert_eq!(sync::Arc::strong_count(&x), 2, "ctx 46 released while its lists are named"); + assert!(sync::Arc::strong_count(&x_records) >= 2); + assert!(p.reusable(3, &x).is_none()); + + // A new VM's InitBM epoch rebinds slot 3. The old binding stays intact while that + // render is in flight and goes only with its full retirement. + let z = vm(48); + assert_eq!(p.pick_slot_in_mask_blocks_mode(&z, false, 0b11000, 3, 512, false), Some(3)); + let ez = epoch(&z, 3); + let bz = p.bind(3, false); + p.hold_alloc(3, &z, None, None).unwrap(); + p.publish_flight(3); + assert!(p.reclaim_closed(), "rebinding render still in flight"); + assert_eq!(sync::Arc::strong_count(&ex), 2); + assert_eq!(sync::Arc::strong_count(&x), 2); + p.retire_flight(3, &ez, bz, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&ex), 1, "replaced epoch released"); + drop(ex); + assert_eq!(sync::Arc::strong_count(&x), 1, "closed VM released after replacement"); + assert_eq!(sync::Arc::strong_count(&x_records), 1); + assert!(!p.reclaim_closed()); + } + + // Live cross-VM steal of a warm PB slot (display manager active: kwin, its helpers and 16 + // clients over 16 warm slots). VM A's epoch owns slot 3. VM B's fresh epoch rebinds slot 3 + // and retires, replacing owners[3] while A is still open. A's next render is a cold InitBM + // on slot 4, the only flight; gPM_SP(0) then writes the old epoch's page list through A's + // context: "write unmapped level 0 unit 0xe0 ctx 62 ... flights=1 live_vm=Some(108)". + #[test]fn live_vm_displaced_pb_epoch_keeps_page_list_until_its_next_render_retires(){ + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let epoch = |v: &sync::Arc, k: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(k, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + e + }; + let run = |p: &mut g16::pools::Pools, v: &sync::Arc, k: usize, + e: &sync::Arc, completed: bool| { + let b = p.bind(k, false); + p.hold_alloc(k, v, None, None).unwrap(); + p.publish_flight(k); + p.retire_flight(k, e, b, completed).unwrap(); + }; + + let a = vm(62); + let b = vm(5); + let ea1 = epoch(&a, 3); + run(&mut p, &a, 3, &ea1, true); + let eb = epoch(&b, 3); + run(&mut p, &b, 3, &eb, true); + assert!(p.reusable(3, &a).is_none(), "slot 3 is bound to B's epoch"); + assert_eq!(sync::Arc::strong_count(&ea1), 2, "A's page list unmapped while A is open"); + assert_eq!(p.stats.kept, 1); + + // A's next render binds slot 4 with InitBM. The old list stays while it is in flight + // and after a failed retirement, which need not have run the InitBM. + let ea2 = epoch(&a, 4); + let b2 = p.bind(4, false); + p.hold_alloc(4, &a, None, None).unwrap(); + p.publish_flight(4); + assert_eq!(sync::Arc::strong_count(&ea1), 2); + p.retire_flight(4, &ea2, b2, false).unwrap(); + assert_eq!(sync::Arc::strong_count(&ea1), 2, "a failed render released the old list"); + let ea3 = epoch(&a, 4); + run(&mut p, &a, 4, &ea3, true); + assert_eq!(sync::Arc::strong_count(&ea1), 1, "released after A's newer render retired"); + assert_eq!(sync::Arc::strong_count(&ea3), 3, "slot 4 owner and A's last epoch"); + assert_eq!(sync::Arc::strong_count(&eb), 3, "slot 3 owner and B's last epoch"); + // Warm reuse of the same epoch changes nothing. + run(&mut p, &b, 3, &eb, true); + assert_eq!(sync::Arc::strong_count(&eb), 3); + assert_eq!(p.stats.kept, 1); + // Open VMs never keep reclaim armed. + assert!(!p.take_closed_vm_last()); + assert!(!p.reclaim_closed()); + } + + // A closed VM keeps its last epoch while a render it accepted waits for publication or + // retirement, and loses it once none does, so its context and lists are not pinned. + #[test]fn closed_vm_last_pb_epoch_waits_for_its_accepted_renders(){ + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let epoch = |v: &sync::Arc, k: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(k, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + e + }; + let run = |p: &mut g16::pools::Pools, v: &sync::Arc, k: usize, + e: &sync::Arc| { + let b = p.bind(k, false); + p.hold_alloc(k, v, None, None).unwrap(); + p.publish_flight(k); + p.retire_flight(k, e, b, true).unwrap(); + }; + + let a = vm(20); + let b = vm(21); + let ea1 = epoch(&a, 3); + run(&mut p, &a, 3, &ea1); + let eb = epoch(&b, 3); + run(&mut p, &b, 3, &eb); + assert_eq!(sync::Arc::strong_count(&ea1), 2); + + // A closes with an accepted render not yet published. + a.vm.set_unpublished(true); + a.vm.close(); + assert!(p.reclaim_closed(), "accepted render of the closed VM still unpublished"); + assert_eq!(sync::Arc::strong_count(&ea1), 2); + // It publishes a fresh InitBM epoch on slot 4. + a.vm.set_unpublished(false); + let ea2 = epoch(&a, 4); + let b2 = p.bind(4, false); + p.hold_alloc(4, &a, None, None).unwrap(); + p.publish_flight(4); + assert!(p.reclaim_closed(), "render of the closed VM in flight"); + assert_eq!(sync::Arc::strong_count(&ea1), 2); + p.retire_flight(4, &ea2, b2, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&ea1), 1, "older epoch released after the InitBM"); + assert!(p.take_closed_vm_last(), "a closed VM's entry asks for another reclaim pass"); + assert!(!p.take_closed_vm_last()); + // B retires on slot 5, so slot 4 is displaced; nothing of A is pending any more. + let eb5 = epoch(&b, 5); + run(&mut p, &b, 5, &eb5); + assert!(!p.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&ea2), 2, "only slot 4's owner keeps A's last epoch"); + drop(ea1); + drop(ea2); + // Slot 4's owner holds A until a newer epoch retires there. + assert_eq!(sync::Arc::strong_count(&a), 2); + let eb4 = epoch(&b, 4); + run(&mut p, &b, 4, &eb4); + assert_eq!(sync::Arc::strong_count(&a), 1, "closed VM fully released"); + assert!(!p.reclaim_closed()); + } + + mod compute_cmds_retry { + use crate::*; + use crate::sync::{Arc, Mutex}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use crate::g16::object::{FwObject, Objects, Window}; + use crate::g16::slots::UnitCmds; + pub(super) mod hw { + pub(crate) use crate::g16::hw::sizes; + } + pub struct Factory { + window: Arc>, + persistent_calls: AtomicUsize, + } + impl Factory { + pub fn persistent_objects(&self) -> Objects { + self.persistent_calls.fetch_add(1, Ordering::Relaxed); + Objects::with_window(true, self.window.clone()) + } + } + __PERSISTENT_UNIT_CMDS__ + __COMPUTE_CMDS_STRUCT__ + impl ComputeCmds { + pub(crate) fn new() -> Result> { + Arc::new( + Self { + sets: Mutex::new([const { None }; hw::sizes::COMPUTE_UNITS]), + }, + GFP_KERNEL, + ) + } + __COMPUTE_CMDS_GET__ + } + #[test] + fn failed_finish_private_retries_sync_and_failed_kbox_skips_persistent_objects() { + let window = Arc::new(Mutex::new(Window::new()), GFP_KERNEL).unwrap(); + window.lock().fail_once.store(true, Ordering::Release); + let factory = Factory { + window: window.clone(), + persistent_calls: AtomicUsize::new(0), + }; + let cmds = ComputeCmds::new().unwrap(); + + // KBox::new_uninit OOM must fail before calling factory.persistent_objects(). + crate::FAIL_KBOX_UNINIT.with(|f| f.set(true)); + assert_eq!(cmds.get(&factory, 0).err(), Some(ENOMEM)); + assert_eq!(factory.persistent_calls.load(Ordering::Relaxed), 0); + + // First real call allocates work/seq/barrier (3 objects) and fails sync_range once. + let before = crate::g16::object::ALL_OBJECTS.with(|a| a.borrow().len()); + assert_eq!(cmds.get(&factory, 0).err(), Some(EIO)); + assert_eq!(factory.persistent_calls.load(Ordering::Relaxed), 1); + assert_eq!(crate::g16::object::ALL_OBJECTS.with(|a| a.borrow().len()) - before, 3); + assert_eq!(window.lock().calls.load(Ordering::Relaxed), 1); + + // Retry must NOT re-allocate work/seq/barrier AND MUST retry sync_range on the + // preserved pending range before marking finished = true. + let first = cmds.get(&factory, 0).unwrap(); + assert_eq!(factory.persistent_calls.load(Ordering::Relaxed), 1); + assert_eq!(crate::g16::object::ALL_OBJECTS.with(|a| a.borrow().len()) - before, 3); + assert_eq!(window.lock().calls.load(Ordering::Relaxed), 2); + { + let w = window.lock(); + let ranges = w.ranges.lock().unwrap(); + assert_eq!(ranges.len(), 2); + assert_eq!(ranges[0], ranges[1]); + } + + // Third call hits finished fast-path without calling sync_range again. + let second = cmds.get(&factory, 0).unwrap(); + assert_eq!(window.lock().calls.load(Ordering::Relaxed), 2); + assert!(Arc::ptr_eq(&first.work, &second.work)); + assert!(Arc::ptr_eq(&first.seq, &second.seq)); + assert!(Arc::ptr_eq(&first.barrier, &second.barrier)); + } + } } ''' +poll_source = (production/'poll.rs').read_text() +mod_source = (production/'mod.rs').read_text() +sleep_source = (production/'sleep.rs').read_text() +assert 'scrubs.run()' not in poll_source, 'poll.rs must hand scrubs off asynchronously via enqueue_scrubs' +assert 'while let Some(mut item) = self.scrub_queue.lock().pop()' not in poll_source, 'run_scrubs must drop scrub_queue spinlock before run_one()' +assert 'self.enqueue_scrubs(scrubs)' in poll_source, 'poll.rs must enqueue scrubs asynchronously' +assert 'OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)' in mod_source +assert 'self.scrub_wq.drain();' in sleep_source, 'sleep.rs::join_workers must drain scrub_wq' +assert 'closed_vm_reclaim' in mod_source +assert 'self.shared.wake_closed_vm_reclaim();' in item(mod_source, 'fn vm_closed(') +assert 'reclaim_closed_vm_slots' in poll_source +assert 'job.resources.discard_unpublished_renders();' in item(poll_source, 'if p.is_pending()') +lifetime_source = (production.parent / 'mmu' / 'lifetime.rs').read_text() +is_closed_fn = item(lifetime_source, 'pub(crate) fn is_closed(') +assert '.lock()' not in is_closed_fn, 'Vm::is_closed() must be lock-free' +assert 'lifetime.closed.load(Ordering::Acquire)' in is_closed_fn +unmap_fn = item(lifetime_source, 'pub(crate) fn unmap_user_ranges(') +assert 'lifetime.closed.store(true, Ordering::Release)' in unmap_fn budget=(production/'budget.rs').read_text() budget=budget.replace('new_condvar, new_mutex,','').replace('#[pin_data]','').replace(' #[pin]\n','') constructor=item(budget,'pub(crate) fn new()') @@ -401,9 +3482,97 @@ def module(text, name): ''' source=source.replace('__BUDGET__',budget.replace('//!','//')) source = source.replace('__LIVE_TOKEN__' ,item((production/'vm.rs').read_text(),'pub(crate) struct LiveToken')).replace('__LIVE_DROP__',item((production/'vm.rs').read_text(),'impl Drop for LiveToken')) -source = source.replace('__CMD_CLASSES__',item(graph_source,'pub(crate) const fn cmd_fw(')+'\n'+item(graph_source,'pub(crate) const fn cmd_shared(')).replace('__SET_DIRTY__',item((production/'resources.rs').read_text(),'pub(crate) fn set_dirty(')) +resources_source = (production/'resources.rs').read_text() +for placeholder, source_text, declaration in ( + ('__WAKE_PUBLISH__', mod_source, 'pub(crate) fn wake_publish('), + ('__WAKE_CLOSED_VM_RECLAIM__', mod_source, 'pub(crate) fn wake_closed_vm_reclaim('), + ('__STANDBY__', resources_source, 'struct Standby {'), + ('__RELEASE_RESERVED__', resources_source, 'fn release_reserved('), + ('__RELEASE_RENDER_PASSES__', resources_source, 'fn release_render_passes('), + ('__RENDERS_UNPUBLISHED__', resources_source, 'pub(crate) fn renders_unpublished('), + ('__PREPARED__', resources_source, 'pub(crate) struct Prepared {'), + ('__DROP_PREPARED__', resources_source, 'impl Drop for Prepared'), + ('__COMMIT_RENDER__', resources_source, 'pub(crate) fn commit_render('), + ('__DISCARD_UNPUBLISHED__', resources_source, 'pub(crate) fn discard_unpublished_renders('), + ('__RECLAIM_CLOSED_VM_SLOTS__', poll_source, 'pub(crate) fn reclaim_closed_vm_slots('), +): + method = item(source_text, declaration) + # The host Arc wrapper uses Deref without the kernel's arbitrary self types. + source = source.replace(placeholder, method.replace('self: &Arc', '&self')) +source = source.replace('__SPARE_EPOCHS__', next( + line for line in resources_source.splitlines() if line.startswith('const SPARE_EPOCHS:'))) +object_source = (production/'object.rs').read_text() +# A firmware-cached object with an uncached GPU lower alias is cleaned to the point of +# coherency after every host store; only that combination sets the flag. +stored_fn = item(object_source, 'fn stored(&self') +assert 'crate::pgtable::clean_poc(' in stored_fn and 'crate::pgtable::poc_barrier()' in stored_fn, 'FwObject::stored must clean and complete' +for store in ('pub(crate) fn write(', 'pub(crate) fn fill(', 'pub(crate) fn w32(', 'pub(crate) fn w64('): + assert 'self.stored(' in item(object_source, store), store + ' must clean firmware-cached GPU-aliased stores' +assert object_source.count('let clean = req.class == Class::FwCoherent && req.lower.is_some();') == 1, 'only FwCoherent work with a lower alias cleans its stores' +assert 'pub(crate) struct ComputeUnitSet {' in resources_source, 'resources.rs must split compute units into per-unit ComputeArenas' +assert 'pub(crate) struct ComputeCmds {' in resources_source, 'resources.rs must retain device-lifetime ComputeCmds' +assert 'let cmds = factory.compute_cmds(hw_slot)?;' in resources_source, 'ComputeArena::new must fetch hardware-slot UnitCmds' +assert 'ComputeArena::new(factory, bind, vm, live, k, k, placement)?' in resources_source, 'ComputeUnitSet::new must allocate one ComputeArena per unit' +assert 'for (local, &hw_slot) in hw_slots.iter().enumerate()' in resources_source, 'ComputeUnitSet::new_scs must bind UnitCmds by hw_slot' +assert 'compute_ext: Option>' in resources_source, 'compute_ext must use ComputeUnitSet so undisplaced slots pin only one unit' +assert 'base.arena(k)' in resources_source and 'ext.arena(k - base.len())' in resources_source, 'Prepared::compute_arena must return the per-unit ComputeArena' +engine_source = (production/'engine.rs').read_text() +prefix_compute_fn = item(engine_source, 'fn prefix_compute(') +assert 'seq: s.seq.va,' in prefix_compute_fn, 'prefix_compute must point ComputeRefs::seq at firmware-cached s.seq' +assert 's.seq.write(0, q)?;' in prefix_compute_fn, 'prefix_compute must write encoded sequence into s.seq' +assert '&w[work::compute::BODY_ACTIVE_START..work::compute::SEQ_EMBEDDED]' in prefix_compute_fn, 'clean compute reuse must skip embedded sequence copy into WC work' +graphs_finish_fn = item(graph_source, 'pub(crate) fn finish(') +assert 'core::mem::ManuallyDrop::new(factory.persistent_objects_probe())' in graphs_finish_fn, 'Graphs::finish must keep probe-time FwCoherent ring allocator in ManuallyDrop' +assert 'ring_objects.finish_private()?;' in graphs_finish_fn, 'Graphs::finish must publish persistent ring mappings' +alloc_private_in_fn = item(object_source, 'fn alloc_private_in(') +assert 'pub(crate) fn persistent_objects_probe(&self) -> Objects' in object_source, 'Factory must expose persistent_objects_probe for probe-time work rings' +assert 'if self.probe {' in alloc_private_in_fn and 'self.dev.registration_guard().ok_or(ENODEV)?' in alloc_private_in_fn, 'alloc_private_in must gate as_bound() on self.probe and keep registration_guard() otherwise' +assert alloc_private_in_fn.index('UniqueArc::::new_uninit(GFP_KERNEL)?') < alloc_private_in_fn.index('self.uat.kernel_vm().map_in_range('), 'alloc_private_in must pre-allocate UniqueArc before mapping firmware aperture' +assert alloc_private_in_fn.index('self.uat.kernel_lower_vm().map_in_range(') < alloc_private_in_fn.index('self.uat.kernel_vm().map_in_range('), 'alloc_private_in must map uncached aliases before firmware aperture' +assert alloc_private_in_fn.index('self.uat.kernel_vm().map_in_range(') < alloc_private_in_fn.index('self.mappings.push_within_capacity(firmware)'), 'alloc_private_in must commit mappings infallibly after firmware map' +source = (source + .replace('__FINISH_PRIVATE__', item(object_source, 'pub(crate) fn finish_private(')) + .replace('__PERSISTENT_UNIT_CMDS__', item(resources_source, 'struct PersistentUnitCmds {')) + .replace('__COMPUTE_CMDS_STRUCT__', item(resources_source, 'pub(crate) struct ComputeCmds {').replace('#[pin]\n', '').replace('super::hw::', 'hw::')) + .replace('__COMPUTE_CMDS_GET__', item(resources_source, 'pub(crate) fn get(&self, factory: &Factory, k: usize) -> Result {'))) +ext_tiers_start = resources_source.index('pub(crate) const EXT_RENDER_TIERS:') +ext_tiers_end = resources_source.index('];\n', ext_tiers_start) + 3 +render_burst_lines = ( + resources_source[ext_tiers_start:ext_tiers_end] + + '\n' + + '\n'.join( + line for line in resources_source.splitlines() + if line.startswith(('const BURST_SUBMITS:', 'const BURST_GAP_NS:', 'const BURST_COMMANDS:', 'const RENDER_BURST_COMMANDS:')) + ) + + '\npub(crate) ' + item(resources_source, 'fn pick_scs_compute_slots(') + + '\npub(crate) ' + item(resources_source, 'fn pick_base_pb_slots(') + + '\npub(crate) ' + item(resources_source, 'fn should_expand_compute_ext(') + + '\npub(crate) ' + item(resources_source, 'fn target_render_slots(') + + '\npub(crate) ' + item(resources_source, 'fn target_render_slots_for(') +) +source = source.replace('__CMD_CLASSES__', '\n'.join(item(graph_source, decl) for decl in ('pub(crate) const fn graph_fw(', 'pub(crate) const fn qinfo_cached(', 'pub(crate) const fn cmd_fw(', 'pub(crate) const fn cmd_shared('))).replace('__SET_DIRTY__',item(resources_source,'pub(crate) fn set_dirty(')).replace('__RENDER_BURST__', render_burst_lines) +graph_types = '\n'.join( + item(graph_source, decl) + for decl in ( + 'pub(crate) struct ComputeGraph {', + 'struct QueueSession {', + 'impl QueueSession {', + 'struct QueueObjects {', + 'impl QueueObjects {', + 'fn init_queue(', + 'fn init_notifier(', + 'struct ComputeGraphSession {', + 'impl ComputeGraphSession {', + 'impl ComputeGraph {', + 'pub(crate) struct RenderGraph {', + 'struct RenderGraphSession {', + 'impl RenderGraphSession {', + 'impl RenderGraph {', + ) +).replace('fn new(', 'pub(crate) fn new(').replace('fn init(', 'pub(crate) fn init(') +source = source.replace('__GRAPH_TYPES__', graph_types) source = source.replace('__ALLOC__',item(graph_source,'pub(crate) fn alloc(')).replace('__ALLOC_WORK__',item(graph_source,'pub(crate) fn alloc_work(')) -source = source.replace('__HW__','\n'.join(module(hw,n) for n in ('client','sizes','engine','tuning','pte'))).replace('__ROOT__',str(production)).replace('__PRIVATE_RW__',hex(private_rw)+'u64').replace('__CLIENT__', '#[derive(Copy,Clone)]\n'+item(graph_source, 'pub(crate) struct Client {')+'\n'+item(graph_source, 'impl Client {')) +source = source.replace('__HW__','\n'.join([module(hw,n) for n in ('client','sizes','engine','tuning','pte')] + [l for l in hw.splitlines() if l.startswith('pub(crate) const PAGE: u64')])).replace('__ROOT__',str(production)).replace('__PRIVATE_RW__',hex(private_rw)+'u64').replace('__CLIENT__', '#[derive(Copy,Clone)]\n'+item(graph_source, 'pub(crate) struct Client {')+'\n'+item(graph_source, 'impl Client {')) (out/'check-resources.rs').write_text(source) log = '' for command in [ @@ -416,9 +3585,10 @@ def module(text, name): (out/'resource-host.log').write_text(log) if result.returncode: raise SystemExit(result.returncode) -files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] +files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs', 'mod.rs', 'poll.rs', 'vm.rs'] +test_count = int(next(line.split()[3] for line in log.splitlines() if line.startswith('test result: ok.'))) (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 26, + 'result': 'pass', 'tests': test_count, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes', diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py index fc1682600f23f3..a06beb782943b1 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py @@ -21,62 +21,80 @@ def function(text, name): harness = r''' #![allow(dead_code)] +use std::cell::Cell; use std::collections::BTreeMap; #[derive(Copy,Clone,Debug,PartialEq,Eq)]struct Error(i32); const EINVAL:Error=Error(-22);const EAGAIN:Error=Error(-11);type Result = std::result::Result; #[path="__LOGIC__"]mod logic; -use logic::Retirement; +use logic::{Retirement, ABORT_GRACE_NS}; mod encode { __STAMP_SEED__ __STAMP__ } -struct Object{cells:BTreeMap,va:u64,unstable:bool} -impl Default for Object{fn default()->Self{Self{cells:BTreeMap::new(),va:0x1234,unstable:false}}} +mod hw { pub mod sizes { pub const COMPUTE_PIPES: usize = 8; } } +struct Object{cells:BTreeMap,va:u64,unstable:bool,reads:Cell} +impl Default for Object{fn default()->Self{Self{cells:BTreeMap::new(),va:0x1234,unstable:false,reads:Cell::new(0)}}} impl Object { - fn r32(&self,off:usize)->Result{Ok(*self.cells.get(&off).unwrap_or(&0) as u32)} - fn r64(&self,off:usize)->Result{if self.unstable{return Err(EAGAIN)}Ok(*self.cells.get(&off).unwrap_or(&0))} + fn r32(&self,off:usize)->Result{self.reads.set(self.reads.get()+1);Ok(*self.cells.get(&off).unwrap_or(&0) as u32)} + fn r64(&self,off:usize)->Result{self.reads.set(self.reads.get()+1);if self.unstable{return Err(EAGAIN)}Ok(*self.cells.get(&off).unwrap_or(&0))} fn set(&mut self,off:usize,v:u64){self.cells.insert(off,v);} + fn reset_reads(&self){self.reads.set(0);} } #[derive(Clone,Copy)]enum Channel{Compute,Ta,Fs} mod notifier_page {pub const COMPUTE_STAMP:usize=0;pub const COMPUTE_CONTEXT:usize=4;pub const TA_STAMP:usize=8;pub const FS_STAMP:usize=12;pub const FS_RECORD:usize=32;} mod notifier {pub const CONTEXT:usize=16;} -mod compute {pub const DESCRIPTOR_COMPLETED:usize=0;pub const DESCRIPTOR_COUNTER:usize=8;} -struct CGraph{fw_stamp:Object,qstate:Object,qinfo:Object,notifier:Object} +mod manager {pub const COUNTER:usize=0x4c;pub const COMPLETED:usize=0x54;} +#[derive(Default)]struct CGraph{fw_stamp:Object,qstate:Object,qinfo:Object,notifier:Object} struct RGraph{fw_stamp:[Object;2],qstate:[Object;2],qinfo:[Object;2],notifier:Object} -struct Graph{compute:CGraph,render:RGraph} +struct Graph{compute:[CGraph;hw::sizes::COMPUTE_PIPES],render:RGraph} struct Vm{slot:u32}struct Job{vm:Vm,resources:Resources} struct Resources{compute:Vec,passes:Vec,pools:Pools} -impl Resources{fn compute(&self)->Result<&Self>{Ok(self)}fn render(&self)->Result<&Self>{Ok(self)}} -struct Claims{slot:[u32;1],pass:[u32;1]} -struct Flight{computes:u32,renders:u32,target:u32,ta_target:u32,fs_target:u32,job:Job,claims:Claims,head:u32,ta_head:u32,fs_head:u32,rec:[u32;3],recovery_suspect:bool,recovery_started_ns:u64,doomed:bool} -struct Engine{flights:Vec} +impl Resources{fn compute(&self)->Result<&Self>{Ok(self)}fn render(&self)->Result<&Self>{Ok(self)}fn compute_unit(&self,k:usize)->Result<&CUnit>{self.compute.get(k).ok_or(EINVAL)}fn render_pass(&self,k:usize)->Result<&RUnit>{self.passes.get(k).ok_or(EINVAL)}fn pb_retired(&self,k:usize)->Result{self.pools.retired(k)}fn pb_retired_at(&self,k:usize,target:u64)->Result{self.pools.retired_at(k,target)}} +struct Claims{slot:[u32;16],slot_count:u32,pass:[u32;4]} +struct Flight{computes:u32,renders:u32,compute_pipe:u8,target:u32,ta_target:u32,fs_target:u32,job:Job,claims:Claims,head:u32,ta_head:u32,fs_head:u32,rec:[u32;3],chan_settled:bool,pb_slot:u32,uma_submitted:u64,csubmitted:[u64;16],recovery_suspect:bool,recovery_started_ns:u64,gate_passed_ns:Option,unsettled_polls:u32,doomed:bool} +struct Engine{flights:Vec,target:[u32;hw::sizes::COMPUTE_PIPES],ta_target:u32,fs_target:u32,retired_ticks:[u64;4]} +fn stamp_reached(observed:u32,own:u32,tail:u32)->bool{logic::stamp_reached(observed,own,tail)} impl Engine{fn oldest(&self)->Option<&Flight>{self.flights.first()}} -struct CUnit{counter:Object,its:Object,work:Object} +struct CUnit{counter:Object,descriptor:Object,its:Object,work:Object} struct RUnit{scene:Object} struct Scrub{compute:Vec,passes:Vec} struct Slots{scrub:Scrub} -struct Pools{full:bool} -impl Pools{fn retired(&self,_k:usize)->Result{Ok(self.full)}} -struct Firmware{graph:Graph,engine:Engine,slots:Slots,pools:Pools,queue_passed:bool} -fn rmb(){}fn now_ns()->u64{100_000_000} +struct Pools{full:bool,completed:u64} +impl Pools{fn retired(&self,_k:usize)->Result{Ok(self.full)}fn retired_at(&self,_k:usize,target:u64)->Result{Ok(self.full && target!=0 && self.completed>=target)}} +struct TopChannels{compute_producer:u32} +impl TopChannels{fn producer(&self,ch:Channel)->u32{match ch{Channel::Compute=>self.compute_producer,_=>1}}} +struct Firmware{graph:Graph,engine:Engine,slots:Slots,pools:Pools,channels:TopChannels,queue_passed:bool,last_chan_passed:Cell>} +thread_local! { static CLOCK: Cell = const { Cell::new(100_000_000) }; } +fn rmb(){}fn now_ns()->u64{CLOCK.with(|c|c.get())} impl Firmware{ + fn queue_ring_receipt(&self,_state:&Object,_info:&Object,_head:u32)->Result{Ok(self.queue_passed)} + fn queue_ring_passed(&self,_ch:Channel,_state:&Object,_info:&Object,_f:&Flight)->Result{Ok(self.queue_passed)} + fn channel_receipt(&self,_ch:Channel,_rec:u32,passed:bool)->Result{self.last_chan_passed.set(Some(passed));Ok(self.queue_passed)} fn queue_receipt(&self,_ch:Channel,_state:&Object,_info:&Object,_head:u32,_rec:u32)->Result{Ok(self.queue_passed)} + fn queue_passed(&self,_ch:Channel,_state:&Object,_info:&Object,_f:&Flight)->Result{Ok(self.queue_passed)} + // The ITS-pair ticks (25G83, and the first choice on 26B123): the receipt tests set them. + fn compute_ticks(&self,unit:&CUnit)->Result<(u64,u64)>{Ok((unit.its.r64(0)?,unit.its.r64(8)?))} __RETIRED__ + __RETIRED_AT__ + __RETIRED_FLIGHT__ + __RETIRED_FLIGHT_CLASSES__ __RETIRED_SNAPSHOT__ + __RETIRED_SNAPSHOT_AT__ } fn firmware(render:bool,ordinal:u64)->Firmware{ let target=encode::stamp(ordinal); + let mut target_arr=[0u32;hw::sizes::COMPUTE_PIPES];target_arr[0]=target; let mut f=Firmware{ - graph:Graph{compute:CGraph{fw_stamp:Object::default(),qstate:Object::default(),qinfo:Object::default(),notifier:Object::default()}, + graph:Graph{compute:core::array::from_fn(|_|CGraph::default()), render:RGraph{fw_stamp:Default::default(),qstate:Default::default(),qinfo:Default::default(),notifier:Object::default()}}, - engine:Engine{flights:vec![Flight{computes:u32::from(!render),renders:u32::from(render),target,ta_target:target,fs_target:target,job:Job{vm:Vm{slot:2},resources:Resources{compute:vec![CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}],pools:Pools{full:true}}},claims:Claims{slot:[0],pass:[0]},head:1,ta_head:1,fs_head:1,rec:[1;3],recovery_suspect:false,recovery_started_ns:0,doomed:false}]}, - slots:Slots{scrub:Scrub{compute:vec![CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}]}}, - pools:Pools{full:true},queue_passed:true, + engine:Engine{flights:vec![Flight{computes:u32::from(!render),renders:u32::from(render),compute_pipe:0,target,ta_target:target,fs_target:target,job:Job{vm:Vm{slot:2},resources:Resources{compute:vec![CUnit{counter:Object::default(),descriptor:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}],pools:Pools{full:true,completed:2}}},claims:Claims{slot:[0;16],slot_count:u32::from(!render),pass:[0;4]},head:1,ta_head:1,fs_head:1,rec:[1;3],chan_settled:false,pb_slot:0,uma_submitted:2,csubmitted:{let mut a=[0u64;16];if !render{a[0]=ordinal;}a},recovery_suspect:false,recovery_started_ns:0,gate_passed_ns:None,unsettled_polls:0,doomed:false}],target:target_arr,ta_target:target,fs_target:target,retired_ticks:[0;4]}, + slots:Slots{scrub:Scrub{compute:vec![CUnit{counter:Object::default(),descriptor:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}]}}, + pools:Pools{full:true,completed:2},channels:TopChannels{compute_producer:1},queue_passed:true,last_chan_passed:Cell::new(None), }; - f.graph.compute.fw_stamp.set(0,u64::from(target)); - f.graph.compute.notifier.set(notifier_page::COMPUTE_STAMP,u64::from(target)); - f.graph.compute.notifier.set(notifier_page::COMPUTE_CONTEXT,2); + f.graph.compute[0].fw_stamp.set(0,u64::from(target)); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(target)); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_CONTEXT,2); f.engine.flights[0].job.resources.compute[0].counter.set(0,ordinal); f.engine.flights[0].job.resources.compute[0].its.set(0,100);f.engine.flights[0].job.resources.compute[0].its.set(8,101); - f.engine.flights[0].job.resources.compute[0].work.set(compute::DESCRIPTOR_COMPLETED,ordinal); - f.engine.flights[0].job.resources.compute[0].work.set(compute::DESCRIPTOR_COUNTER,0x1234); + f.engine.flights[0].job.resources.compute[0].descriptor.set(manager::COMPLETED,ordinal); + f.engine.flights[0].job.resources.compute[0].descriptor.set(manager::COUNTER,0x1234); for stage in 0..2{f.graph.render.fw_stamp[stage].set(0,u64::from(target));} f.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(target)); f.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(target)); @@ -113,16 +131,569 @@ def function(text, name): } }} } +#[test]fn queued_compute_flight_retires_on_passed_receipts_in_order(){ + for n in [0x7fffff,0x800000,0xffffff,0x1000000,0x1000001]{ + let mut f=firmware(false,n); + let later=firmware(false,n+1).engine.flights.remove(0); + f.engine.flights.push(later);f.engine.target[0]=encode::stamp(n+1); + // The command behind it finished too: the shared stamp and notifier cells name it. + f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(n+1))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(n+1))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_CONTEXT,9); + assert_eq!(f.retired(),Ok(Retirement::Full)); + f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(n-1))); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(n))); + assert_eq!(f.retired(),Ok(Retirement::Full)); + f.queue_passed=false;assert_eq!(f.retired(),Ok(Retirement::Pending)); + f.queue_passed=true;f.engine.flights[0].job.resources.compute[0].descriptor.set(manager::COMPLETED,n-1); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + } +} +#[test]fn queued_render_flight_retires_on_passed_receipts_in_order(){ + for n in [0x7fffff,0x800000,0xffffff,0x1000000,0x1000001]{ + let mut f=firmware(true,n); + let mut later=firmware(true,n+1).engine.flights.remove(0); + later.uma_submitted=4; + f.engine.flights.push(later); + f.engine.ta_target=encode::stamp(n+1); + f.engine.fs_target=encode::stamp(n+1); + // The render behind it finished too: shared TA/FS stamps and notifier moved on. + for stage in 0..2 { f.graph.render.fw_stamp[stage].set(0,u64::from(encode::stamp(n+1))); } + f.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(encode::stamp(n+1))); + f.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(encode::stamp(n+1))); + f.graph.render.notifier.set(notifier::CONTEXT,9); + f.graph.render.notifier.set(notifier_page::FS_RECORD+notifier::CONTEXT,9); + f.engine.flights[0].job.resources.pools.completed=4; + assert_eq!(f.retired(),Ok(Retirement::Full)); + // Unreached FS stamp keeps it pending. + f.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(n-1))); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + f.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(n))); + assert_eq!(f.retired(),Ok(Retirement::Full)); + // Unreached UMA completion keeps it pending. + f.engine.flights[0].job.resources.pools.completed=1; + assert_eq!(f.retired(),Ok(Retirement::Pending)); + f.engine.flights[0].job.resources.pools.completed=2; + assert_eq!(f.retired(),Ok(Retirement::Full)); + // Unpassed TA/FS queue keeps it pending. + f.queue_passed=false; + assert_eq!(f.retired(),Ok(Retirement::Pending)); + } +} #[test]fn changing_packed_receipt_remains_pending_and_stable_retry_can_retire(){ let mut f=firmware(false,1);f.engine.flights[0].job.resources.compute[0].its.unstable=true; assert_eq!(f.retired(),Ok(Retirement::Pending)); f.engine.flights[0].job.resources.compute[0].its.unstable=false; assert_eq!(f.retired(),Ok(Retirement::Full)); + assert_eq!(f.engine.retired_ticks,[100,101,0,0]); + let mut r=firmware(true,1); + assert_eq!(r.retired(),Ok(Retirement::Full)); + assert_eq!(r.engine.retired_ticks,[100,101,102,103]); +} + +#[test]fn concurrent_compute_and_render_retire_independently_by_class(){ + // Render at index 0 (pending) + Compute at index 1 (complete): compute retires ahead of render. + let mut f=firmware(true,10); + let c=firmware(false,20).engine.flights.remove(0); + f.engine.flights.push(c); + f.engine.target[0]=encode::stamp(20); + f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(20))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(20))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_CONTEXT,2); + // Keep render FS stamp unreached so render at index 0 stays pending. + f.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(9))); + assert_eq!(f.retired_flight(),Ok(Some((1,Retirement::Full)))); + f.engine.flights.remove(1); + assert_eq!(f.retired_flight(),Ok(None)); + // Now finish render: render retires cleanly with exact single-class receipt. + f.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(10))); + assert_eq!(f.retired_flight(),Ok(Some((0,Retirement::Full)))); + // Reverse order: Compute at index 0 (pending) + Render at index 1 (complete). + let mut f2=firmware(false,30); + let r=firmware(true,40).engine.flights.remove(0); + f2.engine.flights.push(r); + f2.engine.ta_target=encode::stamp(40); + f2.engine.fs_target=encode::stamp(40); + for stage in 0..2 { f2.graph.render.fw_stamp[stage].set(0,u64::from(encode::stamp(40))); } + f2.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(encode::stamp(40))); + f2.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(encode::stamp(40))); + f2.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(29))); + assert_eq!(f2.retired_flight(),Ok(Some((1,Retirement::Full)))); +} +#[test]fn multi_compute_horizon_requires_every_claimed_unit_receipt(){ + let mut f=firmware(false,12); + let mk_unit=|sub:u64,start:u64,end:u64|{ + let mut u=CUnit{counter:Object::default(),descriptor:Object::default(),its:Object::default(),work:Object::default()}; + u.counter.set(0,sub); + u.its.set(0,start);u.its.set(8,end); + u.descriptor.set(manager::COMPLETED,sub); + u.descriptor.set(manager::COUNTER,0x1234); + u + }; + let fl=&mut f.engine.flights[0]; + fl.computes=3; + fl.claims.slot_count=3; + fl.claims.slot[0]=0;fl.claims.slot[1]=1;fl.claims.slot[2]=2; + fl.csubmitted[0]=10;fl.csubmitted[1]=11;fl.csubmitted[2]=12; + fl.job.resources.compute=vec![mk_unit(10,100,110),mk_unit(11,110,120),mk_unit(12,120,130)]; + assert_eq!(f.retired(),Ok(Retirement::Full)); + // Missing interior unit completion keeps the whole batched flight pending. + f.engine.flights[0].job.resources.compute[1].descriptor.set(manager::COMPLETED,10); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + f.engine.flights[0].job.resources.compute[1].descriptor.set(manager::COMPLETED,11); + // Missing tail unit ticks keeps the whole batched flight pending. + f.engine.flights[0].job.resources.compute[2].its.set(8,0); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + f.engine.flights[0].job.resources.compute[2].its.set(8,130); + assert_eq!(f.retired(),Ok(Retirement::Full)); +} +#[test]fn inactive_class_and_unreached_stage_skip_wc_reads(){ + // Compute-only retirement performs zero render WC reads. + let mut fc=firmware(false,5); + assert_eq!(fc.retired_flight(),Ok(Some((0,Retirement::Full)))); + assert_eq!(fc.graph.render.fw_stamp[0].reads.get(),0); + assert_eq!(fc.graph.render.fw_stamp[1].reads.get(),0); + assert_eq!(fc.graph.render.notifier.reads.get(),0); + // Render-only retirement performs zero compute WC reads. + let mut fr=firmware(true,5); + assert_eq!(fr.retired_flight(),Ok(Some((0,Retirement::Full)))); + assert_eq!(fr.graph.compute[0].fw_stamp.reads.get(),0); + assert_eq!(fr.graph.compute[0].notifier.reads.get(),0); + assert_eq!(fr.graph.compute[1].fw_stamp.reads.get(),0); + assert_eq!(fr.graph.compute[1].notifier.reads.get(),0); + // In-progress render (TA done, FS still running) fails fast on FS stamp without reading TA or scene. + let mut fp=firmware(true,7); + fp.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(6))); + assert_eq!(fp.retired_flight(),Ok(None)); + assert_eq!(fp.graph.render.fw_stamp[1].reads.get(),1); + assert_eq!(fp.graph.render.fw_stamp[0].reads.get(),0); + assert_eq!(fp.engine.flights[0].job.resources.passes[0].scene.reads.get(),0); + // Unsettled notifier skips scene WC timestamp reads. + fp.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(7))); + fp.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(encode::stamp(6))); + assert_eq!(fp.retired_flight(),Ok(None)); + assert_eq!(fp.engine.flights[0].job.resources.passes[0].scene.reads.get(),0); + // Mixed flight pending is polled once, not twice. + let mut fm=firmware(false,9); + fm.engine.flights[0].renders=1; + fm.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(8))); + assert_eq!(fm.retired_flight(),Ok(None)); + assert_eq!(fm.graph.compute[0].fw_stamp.reads.get(),1); + assert_eq!(fm.graph.render.fw_stamp[1].reads.get(),0); + // Pending compute class is not re-polled while retiring a burst of render flights. + let mut fmix=firmware(false,30); + let r1=firmware(true,40).engine.flights.remove(0); + let r2=firmware(true,41).engine.flights.remove(0); + fmix.engine.flights.push(r1); + fmix.engine.flights.push(r2); + fmix.engine.ta_target=encode::stamp(41); + fmix.engine.fs_target=encode::stamp(41); + for stage in 0..2 { fmix.graph.render.fw_stamp[stage].set(0,u64::from(encode::stamp(41))); } + fmix.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(encode::stamp(41))); + fmix.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(encode::stamp(41))); + fmix.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(29))); + let (mut check_c,mut check_r)=([true;hw::sizes::COMPUTE_PIPES],true); + assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(Some((1,Retirement::Full)))); + assert!(!check_c[0] && !check_c[1] && check_r); + fmix.engine.flights.remove(1); + assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(Some((1,Retirement::Full)))); + fmix.engine.flights.remove(1); + assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(None)); + assert_eq!(fmix.graph.compute[0].fw_stamp.reads.get(),1); +} +#[test]fn innocent_suspect_flight_does_not_false_abort_after_recovery_grace(){ + let mut f=firmware(true,15); + f.engine.flights[0].recovery_suspect=true; + f.engine.flights[0].recovery_started_ns=10_000_000; + // Long after recovery started (>20 ms), flight finishes its stage/queue gates while scene + // timestamps are briefly unsettled on the first poll. + CLOCK.with(|c| c.set(100_000_000)); + f.engine.flights[0].job.resources.passes[0].scene.set(0x628,0); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + assert!(!f.engine.flights[0].doomed); + assert_eq!(f.engine.flights[0].gate_passed_ns,Some(100_000_000)); + assert_eq!(f.engine.flights[0].unsettled_polls,1); + // Receipts settle before ABORT_GRACE_NS from gate_passed_ns -> full normal retirement. + CLOCK.with(|c| c.set(100_500_000)); + f.engine.flights[0].job.resources.passes[0].scene.set(0x628,103); + assert_eq!(f.retired(),Ok(Retirement::Full)); + assert!(!f.engine.flights[0].doomed); +} +#[test]fn truly_aborted_suspect_requires_two_polls_and_grace_from_gate_passed(){ + let mut f=firmware(false,22); + f.engine.flights[0].recovery_suspect=true; + f.engine.flights[0].recovery_started_ns=10_000_000; + f.engine.flights[0].job.resources.compute[0].its.set(8,0); + CLOCK.with(|c| c.set(100_000_000)); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + assert!(!f.engine.flights[0].doomed); + // Second poll before ABORT_GRACE_NS stays pending. + CLOCK.with(|c| c.set(100_000_000 + ABORT_GRACE_NS - 1)); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + assert!(!f.engine.flights[0].doomed); + // Once both >=2 polls and >=ABORT_GRACE_NS elapsed from gate_passed_ns, abort and doom. + CLOCK.with(|c| c.set(100_000_000 + ABORT_GRACE_NS)); + assert_eq!(f.retired(),Ok(Retirement::Aborted)); + assert!(f.engine.flights[0].doomed); +} +#[test]fn same_tick_stage_timestamps_retire_full_while_zero_or_reversed_stay_pending(){ + // 24 MHz (41.67 ns) stage timestamps can legitimately record end == start on tiny draws + // or dispatches; accept end >= start while still rejecting 0 or reversed intervals. + let mut r=firmware(true,50); + r.engine.flights[0].job.resources.passes[0].scene.set(0x600,100); + r.engine.flights[0].job.resources.passes[0].scene.set(0x608,100); + r.engine.flights[0].job.resources.passes[0].scene.set(0x620,200); + r.engine.flights[0].job.resources.passes[0].scene.set(0x628,200); + assert_eq!(r.retired(),Ok(Retirement::Full)); + assert_eq!(r.engine.retired_ticks,[100,100,200,200]); + + r.engine.flights[0].job.resources.passes[0].scene.set(0x608,0); + assert_eq!(r.retired(),Ok(Retirement::Pending)); + r.engine.flights[0].job.resources.passes[0].scene.set(0x608,99); + assert_eq!(r.retired(),Ok(Retirement::Pending)); + r.engine.flights[0].job.resources.passes[0].scene.set(0x608,100); + r.engine.flights[0].job.resources.passes[0].scene.set(0x628,199); + assert_eq!(r.retired(),Ok(Retirement::Pending)); + + let mut c=firmware(false,51); + c.engine.flights[0].job.resources.compute[0].its.set(0,300); + c.engine.flights[0].job.resources.compute[0].its.set(8,300); + assert_eq!(c.retired(),Ok(Retirement::Full)); + assert_eq!(c.engine.retired_ticks,[300,300,0,0]); + + c.engine.flights[0].job.resources.compute[0].its.set(8,0); + assert_eq!(c.retired(),Ok(Retirement::Pending)); + c.engine.flights[0].job.resources.compute[0].its.set(8,299); + assert_eq!(c.retired(),Ok(Retirement::Pending)); +} +#[test]fn cross_vm_render_hang_recovery_isolates_innocent_client_flight(){ + // VM A (slot 0, ASID 1) hangs/aborts on render n=30 while innocent VM B (slot 1, ASID 2) + // has a co-resident render n=31 with real TA/FS ticks and independent allocator slot + // completion. VM A aborts; VM B retires Full without blame or error. + CLOCK.with(|c|c.set(100_000_000)); + let mut f=firmware(true,30); + f.engine.flights[0].job.vm.slot=1; + f.engine.flights[0].pb_slot=0; + f.engine.flights[0].doomed=true; + f.engine.flights[0].recovery_suspect=true; + f.engine.flights[0].recovery_started_ns=90_000_000; + f.engine.flights[0].job.resources.passes[0].scene=Object::default(); + + let mut innocent=firmware(true,31).engine.flights.remove(0); + innocent.job.vm.slot=2; + innocent.pb_slot=1; + innocent.uma_submitted=2; + innocent.doomed=false; + innocent.recovery_suspect=true; + innocent.recovery_started_ns=90_000_000; + innocent.job.resources.pools=Pools{full:true,completed:2}; + innocent.job.resources.passes[0].scene=Object::default(); + innocent.job.resources.passes[0].scene.set(0x600,300); + innocent.job.resources.passes[0].scene.set(0x608,320); + innocent.job.resources.passes[0].scene.set(0x620,400); + innocent.job.resources.passes[0].scene.set(0x628,430); + f.engine.flights.push(innocent); + + let t31=encode::stamp(31); + f.engine.ta_target=t31; + f.engine.fs_target=t31; + for stage in 0..2 { f.graph.render.fw_stamp[stage].set(0,u64::from(t31)); } + f.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(t31)); + f.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(t31)); + f.graph.render.notifier.set(notifier::CONTEXT,2); + f.graph.render.notifier.set(notifier_page::FS_RECORD+notifier::CONTEXT,2); + + // First unsettled poll records gate_passed_ns on hanging VM A; after ABORT_GRACE_NS, VM A aborts. + assert_eq!(f.retired_flight(),Ok(None)); + CLOCK.with(|c|c.set(100_000_000 + ABORT_GRACE_NS)); + let (idx_a,ret_a)=f.retired_flight().unwrap().unwrap(); + assert_eq!((idx_a,ret_a),(0,Retirement::Aborted)); + assert!(ret_a.job_failed(f.engine.flights[0].doomed)); + f.engine.flights.remove(0); + + // Innocent VM B on slot 1 proves TA/FS execution via hardware ticks and retires Full. + let (idx_b,ret_b)=f.retired_flight().unwrap().unwrap(); + assert_eq!((idx_b,ret_b),(0,Retirement::Full)); + assert!(!f.engine.flights[0].doomed); + assert!(!ret_b.job_failed(f.engine.flights[0].doomed)); +} +#[test]fn two_compute_pipes_retire_out_of_order_independently(){ + // Pipe 0 flight at idx 0 (pending, rec=1) + Pipe 1 flight at idx 1 (complete, rec=2, + // shared Channel::Compute producer=2): pipe 1 retires Full ahead of pipe 0, and once + // pipe 0 settles afterwards it still uses passed channel_receipt because rec (1) != producer (2). + let mut f=firmware(false,10); + f.engine.flights[0].compute_pipe=0; + f.engine.flights[0].rec[2]=1; + let mut c1=firmware(false,11).engine.flights.remove(0); + c1.compute_pipe=1; + c1.rec[2]=2; + f.engine.flights.push(c1); + f.engine.target[0]=encode::stamp(10);f.engine.target[1]=encode::stamp(11); + f.channels.compute_producer=2; + f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(9))); + f.graph.compute[1].fw_stamp.set(0,u64::from(encode::stamp(11))); + f.graph.compute[1].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(11))); + f.graph.compute[1].notifier.set(notifier_page::COMPUTE_CONTEXT,2); + assert_eq!(f.retired_flight(),Ok(Some((1,Retirement::Full)))); + assert_eq!(f.last_chan_passed.get(),Some(true)); + f.engine.flights.remove(1); + assert_eq!(f.retired_flight(),Ok(None)); + // Now finish pipe 0: rec[2]=1 != producer=2 still sets chan_behind=true. + f.last_chan_passed.set(None); + f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(10))); + assert_eq!(f.retired_flight(),Ok(Some((0,Retirement::Full)))); + assert_eq!(f.last_chan_passed.get(),Some(true)); +} +#[test]fn two_pipe_cross_vm_compute_hang_recovery_isolates_innocent_pipe(){ + // Pipe 0 VM A (ASID 1) hangs/aborts while co-resident Pipe 1 VM B (ASID 2) proves CDM + // execution via hardware ITS ticks and retires Full immediately without blame or false abort. + CLOCK.with(|c|c.set(100_000_000)); + let mut f=firmware(false,40); + f.engine.flights[0].compute_pipe=0; + f.engine.flights[0].job.vm.slot=1; + f.engine.flights[0].rec[2]=1; + f.engine.flights[0].doomed=true; + f.engine.flights[0].recovery_suspect=true; + f.engine.flights[0].recovery_started_ns=90_000_000; + f.engine.flights[0].job.resources.compute[0].its=Object::default(); + + let mut innocent=firmware(false,41).engine.flights.remove(0); + innocent.compute_pipe=1; + innocent.job.vm.slot=2; + innocent.rec[2]=2; + innocent.doomed=false; + innocent.recovery_suspect=true; + innocent.recovery_started_ns=90_000_000; + innocent.job.resources.compute[0].its.set(0,500); + innocent.job.resources.compute[0].its.set(8,530); + f.engine.flights.push(innocent); + + f.engine.target[0]=encode::stamp(40);f.engine.target[1]=encode::stamp(41); + f.channels.compute_producer=2; + f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(40))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(40))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_CONTEXT,1); + f.graph.compute[1].fw_stamp.set(0,u64::from(encode::stamp(41))); + f.graph.compute[1].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(41))); + f.graph.compute[1].notifier.set(notifier_page::COMPUTE_CONTEXT,2); + + // Within grace: pipe 0 records gate_passed_ns while innocent pipe 1 retires Full immediately. + let (idx_b,ret_b)=f.retired_flight().unwrap().unwrap(); + assert_eq!((idx_b,ret_b),(1,Retirement::Full)); + assert!(!f.engine.flights[1].doomed); + assert!(!ret_b.job_failed(f.engine.flights[1].doomed)); + f.engine.flights.remove(1); + assert_eq!(f.retired_flight(),Ok(None)); + + // Past ABORT_GRACE_NS from gate_passed_ns: hanging pipe 0 aborts cleanly. + CLOCK.with(|c|c.set(100_000_000 + ABORT_GRACE_NS)); + let (idx_a,ret_a)=f.retired_flight().unwrap().unwrap(); + assert_eq!((idx_a,ret_a),(0,Retirement::Aborted)); + assert!(ret_a.job_failed(f.engine.flights[0].doomed)); +} + +mod queue_proof { + use super::{Channel, Object, Result, EINVAL}; + use super::logic::ring_passed; + pub(crate) mod object { + pub(crate) type FwObject = super::Object; + } + pub(crate) mod hw { + __HW_CLIENT__ + __HW_ENGINE__ + __HW_TUNING__ + __HW_SIZES__ + } + pub(crate) mod fw { + pub(crate) mod channels { + pub(crate) const RING_SLOTS: u32 = 256; + } + } + pub(crate) mod graph { + #[derive(Copy, Clone, Debug, PartialEq, Eq)] + pub(crate) enum Class { Fw, FwCached } + __GRAPH_FW__ + __QINFO_CACHED__ + } + mod qstate { + pub(crate) const READ: usize = 0x10; + pub(crate) const WRITE: usize = 0x14; + } + struct QInfoLayout { busy: usize } + struct Abi; + impl Abi { fn qinfo(&self) -> QInfoLayout { QInfoLayout { busy: 0x30 } } } + struct Init { abi: Abi } + struct Pipe { read: u32, completion: u32, write: u32 } + impl Pipe { + fn read(&self) -> Result { Ok(self.read) } + fn completion(&self) -> Result { Ok(self.completion) } + fn write(&self) -> Result { Ok(self.write) } + } + struct Channels { compute: Pipe, ta: Pipe, fs: Pipe } + impl Channels { + fn channel(&self, ch: Channel) -> &Pipe { + match ch { Channel::Compute => &self.compute, Channel::Ta => &self.ta, Channel::Fs => &self.fs } + } + fn producer(&self, ch: Channel) -> u32 { self.channel(ch).write } + } + struct Engine { head: [u32; hw::sizes::COMPUTE_PIPES], ta_head: u32, fs_head: u32, flights: Vec } + struct Flight { computes: u32, compute_pipe: u8, c_start: u32, head: u32, ta_start: u32, ta_head: u32, fs_start: u32, fs_head: u32, rec: [u32; 3], chan_settled: bool } + struct Firmware { init: Init, channels: Channels, engine: Engine } + mod inner { + use super::*; + impl Firmware { + __QUEUE_RING_RECEIPT__ + __QUEUE_RING_PASSED__ + __CHANNEL_RECEIPT__ + __LATCH_COMPUTE_CHANNEL_RECEIPTS__ + __QUEUE_RECEIPT__ + __QUEUE_PASSED__ + } + #[test] + fn cached_qinfo_skips_info_wc_reads_and_authenticates_on_nc_qstate_and_pipe() { + assert!(!hw::tuning::FW_CACHED); + assert!(graph::qinfo_cached()); + let mut fw = Firmware { + init: Init { abi: Abi }, + channels: Channels { + compute: Pipe { read: 5, completion: 5, write: 5 }, + ta: Pipe { read: 7, completion: 7, write: 7 }, + fs: Pipe { read: 9, completion: 9, write: 9 }, + }, + engine: Engine { head: { let mut h = [0u32; hw::sizes::COMPUTE_PIPES]; h[0] = 10; h[1] = 12; h }, ta_head: 20, fs_head: 30, flights: vec![] }, + }; + let mut state = Object::default(); + let mut info = Object::default(); + // Deliberately poison qinfo with stale consumer cursors and nonzero busy flag. + info.set(0x20, 0); + info.set(0x24, 0); + info.set(0x28, 0); + info.set(0x30, 1); + state.set(qstate::READ, 10); + state.set(qstate::WRITE, 10); + assert_eq!(fw.queue_receipt(Channel::Compute, &state, &info, 10, 5), Ok(true)); + assert_eq!(info.reads.get(), 0); + // Lagging NC qstate::READ or qstate::WRITE rejects receipt. + state.set(qstate::READ, 9); + assert_eq!(fw.queue_receipt(Channel::Compute, &state, &info, 10, 5), Ok(false)); + state.set(qstate::READ, 10); + state.set(qstate::WRITE, 11); + assert_eq!(fw.queue_receipt(Channel::Compute, &state, &info, 10, 5), Ok(false)); + state.set(qstate::WRITE, 10); + // Lagging submit pipe completion rejects receipt. + fw.channels.compute.completion = 4; + assert_eq!(fw.queue_receipt(Channel::Compute, &state, &info, 10, 5), Ok(false)); + fw.channels.compute.completion = 5; + assert_eq!(fw.queue_receipt(Channel::Compute, &state, &info, 256, 5), Err(EINVAL)); + assert_eq!(info.reads.get(), 0); + + // Split ring + channel receipts for 2-pipe OOO compute: pipe 1's own ring is exact + // (head=12) while shared Channel::Compute producer moved on to 6 (rec=5 -> passed=true). + fw.channels.compute = Pipe { read: 6, completion: 6, write: 6 }; + state.set(qstate::READ, 12); + state.set(qstate::WRITE, 12); + assert_eq!(fw.queue_ring_receipt(&state, &info, 12), Ok(true)); + assert_eq!(fw.channel_receipt(Channel::Compute, 5, false), Ok(false)); + assert_eq!(fw.channel_receipt(Channel::Compute, 5, true), Ok(true)); + let f_p1 = Flight { computes: 1, compute_pipe: 1, c_start: 10, head: 11, ta_start: 0, ta_head: 1, fs_start: 0, fs_head: 1, rec: [1, 1, 5], chan_settled: false }; + assert_eq!(fw.queue_ring_passed(Channel::Compute, &state, &info, &f_p1), Ok(true)); + state.set(qstate::READ, 10); + assert_eq!(fw.queue_ring_passed(Channel::Compute, &state, &info, &f_p1), Ok(false)); + assert_eq!(info.reads.get(), 0); + + // queue_passed with queued work behind flight (including wrap-around) never reads qinfo. + fw.engine.ta_head = 2; + fw.channels.ta = Pipe { read: 2, completion: 2, write: 3 }; + let f = Flight { computes: 0, compute_pipe: 0, c_start: 0, head: 10, ta_start: 254, ta_head: 0, fs_start: 0, fs_head: 1, rec: [1, 1, 5], chan_settled: false }; + state.set(qstate::READ, 1); + assert_eq!(fw.queue_passed(Channel::Ta, &state, &info, &f), Ok(true)); + assert_eq!(info.reads.get(), 0); + // Unpassed NC qstate::READ rejects queue_passed. + state.set(qstate::READ, 255); + assert_eq!(fw.queue_passed(Channel::Ta, &state, &info, &f), Ok(false)); + state.set(qstate::READ, 1); + // Unpassed pipe completion rejects queue_passed. + fw.channels.ta.completion = 0; + assert_eq!(fw.queue_passed(Channel::Ta, &state, &info, &f), Ok(false)); + assert_eq!(info.reads.get(), 0); + } + #[test] + fn cross_pipe_channel_wrap_latches_receipt_before_producer_laps_flight() { + // Pipe 0 submits compute record 1 while pipe 1 submits and retires 255 records, + // stopping at producer=0, read=0, completion=0. Raw ring_passed(0, 0, 1, 0, 256) + // would be false forever, but latch_compute_channel_receipts proves record 1 before + // the 256-entry submit channel wraps. + let mut fw = Firmware { + init: Init { abi: Abi }, + channels: Channels { + compute: Pipe { read: 1, completion: 1, write: 1 }, + ta: Pipe { read: 0, completion: 0, write: 0 }, + fs: Pipe { read: 0, completion: 0, write: 0 }, + }, + engine: Engine { + head: [0u32; hw::sizes::COMPUTE_PIPES], + ta_head: 0, + fs_head: 0, + flights: vec![Flight { + computes: 1, + compute_pipe: 0, + c_start: 0, + head: 1, + ta_start: 0, + ta_head: 0, + fs_start: 0, + fs_head: 0, + rec: [0, 0, 1], + chan_settled: false, + }], + }, + }; + // While firmware has not completed record 1 yet, latch stays false. + fw.channels.compute = Pipe { read: 1, completion: 0, write: 2 }; + fw.latch_compute_channel_receipts().unwrap(); + assert!(!fw.engine.flights[0].chan_settled); + // Out-of-range firmware cursors (>= RING_SLOTS, e.g. 257 which wraps mod 256 to 1) + // must be rejected before modular comparison in both passed receipts and latching. + for (read, completion) in [(257, 257), (257, 2), (2, 257)] { + fw.channels.compute = Pipe { read, completion, write: 2 }; + assert_eq!(fw.channel_receipt(Channel::Compute, 1, true), Ok(false)); + fw.latch_compute_channel_receipts().unwrap(); + assert!(!fw.engine.flights[0].chan_settled); + } + // Once read and completion pass record 1 before wrap, latch becomes true. + fw.channels.compute = Pipe { read: 2, completion: 2, write: 2 }; + fw.latch_compute_channel_receipts().unwrap(); + assert!(fw.engine.flights[0].chan_settled); + // Even after pipe 1 submits 254 more records and stops at producer=0 (where raw + // channel_receipt(Compute, 1, true) returns false), the latched proof persists. + fw.channels.compute = Pipe { read: 0, completion: 0, write: 0 }; + assert_eq!(fw.channel_receipt(Channel::Compute, 1, true), Ok(false)); + assert!(fw.engine.flights[0].chan_settled); + } + } } '''.replace('__LOGIC__', str(backend/'recovery/logic.rs')) -for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot')]: - harness=harness.replace(token,function((backend/path).read_text(),name)) +for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_FLIGHT_CLASSES__','poll.rs','retired_flight_classes'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at'),('__QUEUE_RING_RECEIPT__','poll.rs','queue_ring_receipt'),('__QUEUE_RING_PASSED__','poll.rs','queue_ring_passed'),('__CHANNEL_RECEIPT__','poll.rs','channel_receipt'),('__LATCH_COMPUTE_CHANNEL_RECEIPTS__','poll.rs','latch_compute_channel_receipts'),('__QUEUE_RECEIPT__','poll.rs','queue_receipt'),('__QUEUE_PASSED__','poll.rs','queue_passed'),('__GRAPH_FW__','graph.rs','graph_fw'),('__QINFO_CACHED__','graph.rs','qinfo_cached')]: + body = function((backend/path).read_text(),name) + if token in ('__RETIRED_FLIGHT__', '__RETIRED_FLIGHT_CLASSES__', '__RETIRED_SNAPSHOT_AT__'): + body = body.replace('super::hw::', 'hw::') + harness=harness.replace(token, body) +hw_text=(backend/'hw.rs').read_text() +def mod_block(text, name): + start=text.index('pub(crate) mod '+name+' {') + at=text.index('{',start) + depth,end=1,at+1 + while depth: + depth+=(text[end]=='{')-(text[end]=='}') + end+=1 + return text[start:end] +harness=(harness + .replace('__HW_CLIENT__',mod_block(hw_text,'client')) + .replace('__HW_ENGINE__',mod_block(hw_text,'engine')) + .replace('__HW_TUNING__',mod_block(hw_text,'tuning')) + .replace('__HW_SIZES__',mod_block(hw_text,'sizes'))) unit=out/'stamp-wrap.rs';unit.write_text(harness) log='' for command in [rustc()+['--edition=2021','--test',str(unit),'-o',str(out/'stamp-wrap')],[str(out/'stamp-wrap'),'--nocapture']]: diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py index c701dd84471fa3..eb48e6ce3ee651 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py @@ -46,7 +46,27 @@ pub const UAT_PGMSK: usize = UAT_PGSZ - 1; pub struct Region { pub base: u64, pub bytes: Vec, pub readable: bool } #[derive(Default)] - pub struct Vm { pub regions: Vec } + pub struct Vm { + pub regions: Vec, + pub epoch: std::cell::Cell>, + pub lock_calls: std::cell::Cell, + pub read_calls: std::cell::Cell, + pub last_read_len: std::cell::Cell, + } + pub struct VmReadGuard<'a>(&'a Vm); + impl VmReadGuard<'_> { + pub fn epoch(&self) -> Option { + self.0.epoch.get() + } + pub fn covers_range(&mut self, address: u64, size: u64, _read: bool, _write: bool) -> bool { + address + .checked_add(size) + .is_some_and(|end| self.0.contains(address, end)) + } + pub fn read_user(&mut self, va: u64, out: &mut [u8]) -> Result { + self.0.read_user(va, out) + } + } impl Vm { pub fn region(&mut self, base: u64, bytes: Vec) { self.regions.push(Region { base, bytes, readable: true }); @@ -55,7 +75,13 @@ self.regions.iter().any(|r| r.readable && va >= r.base && end >= va && end <= r.base + r.bytes.len() as u64) } + pub fn read_lock(&self) -> Result> { + self.lock_calls.set(self.lock_calls.get() + 1); + Ok(VmReadGuard(self)) + } pub fn read_user(&self, va: u64, out: &mut [u8]) -> Result { + self.read_calls.set(self.read_calls.get() + 1); + self.last_read_len.set(out.len()); let end = va.checked_add(out.len() as u64).ok_or(EFAULT)?; for r in &self.regions { if r.readable && va >= r.base && end <= r.base + r.bytes.len() as u64 { @@ -72,16 +98,78 @@ pub mod params { pub fn stream_gate() -> bool { true } } pub mod command { use crate::{mmu, kernel::prelude::*}; + use std::cell::Cell; pub const USC_WINDOW: u64 = 1 << 32; - pub fn cover(vm: &mmu::Vm, start: u64, end: u64, _read: bool, _write: bool) -> Result { + #[derive(Default)] + pub struct SpanProof { + epoch: Option, + ranges: Vec<(u64, u64, u8)>, + } + impl SpanProof { + pub fn new() -> Self { Self::default() } + pub fn covers_aligned(&self, epoch: Option, first: u64, size: u64, access: u8) -> bool { + self.epoch.is_some() + && self.epoch == epoch + && self.ranges.iter().any(|&(s, l, a)| { + (a & access) == access && first >= s && first + size <= s + l + }) + } + pub fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { + if epoch.is_none() { + self.invalidate(); + return; + } + if self.epoch != epoch { + self.epoch = epoch; + self.ranges.clear(); + } + self.ranges.push((first, size, access)); + } + pub fn invalidate(&mut self) { + self.epoch = None; + self.ranges.clear(); + } + } + std::thread_local! { + static COVER_CALLS: Cell = const { Cell::new(0) }; + } + pub fn reset_cover_calls() { COVER_CALLS.with(|c| c.set(0)); } + pub fn cover_calls() -> usize { COVER_CALLS.with(Cell::get) } + pub fn cover_locked( + guard: &mut mmu::VmReadGuard<'_>, + epoch: Option, + mut proof: Option<&mut SpanProof>, + start: u64, + end: u64, + read: bool, + write: bool, + ) -> Result { if end <= start || start < 0x4000 || end > (1u64 << 42) - 0x8000 { return Err(EINVAL); } + let first = start & !(mmu::UAT_PGMSK as u64); + let last = (end + mmu::UAT_PGMSK as u64) & !(mmu::UAT_PGMSK as u64); + let size = last - first; + let access = u8::from(read) | (u8::from(write) << 1); if start < 0x7100000000 && end > 0x7000000000 || start < 0x1000010000 && end > 0x1000000000 { return Err(EACCES); } - if vm.contains(start, end) { Ok(()) } else { Err(EFAULT) } + if proof.as_deref().is_some_and(|p| p.covers_aligned(epoch, first, size, access)) { + return Ok(()); + } + COVER_CALLS.with(|c| c.set(c.get() + 1)); + if guard.covers_range(start, end - start, read, write) { + if let Some(p) = proof.as_deref_mut() { + p.record_one(epoch, first, size, access); + } + Ok(()) + } else { + if let Some(p) = proof.as_deref_mut() { + p.invalidate(); + } + Err(EFAULT) + } } } #[path = "PRODUCTION_SOURCE"] pub mod gate; @@ -107,8 +195,13 @@ vm.region(BASE, stream); vm.region(USC, vec![0; 0x4000]); vm.region(0x400000000, vec![0; 0x4000]); vm } +fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> kernel::prelude::Result { + let mut guard = None; + let mut epoch = None; + g16::gate::cdm_locked(vm, &mut guard, &mut epoch, usc, base, end, None) +} fn run(words: &[u32]) -> bool { - g16::gate::cdm(&vm_for(words), USC, BASE, BASE + words.len() as u64 * 4).is_ok() + cdm(&vm_for(words), USC, BASE, BASE + words.len() as u64 * 4).is_ok() } #[test] fn direct_modes_and_program_split() { @@ -120,7 +213,7 @@ for usc in [0x3f00000000u64, 0x4000000000, 0x8100000000, 0x30000000000] { let mut words = launch(0, usc + 0x80, 0); words.push(0x40000000); let mut vm = vm_for(&words); vm.region(usc, vec![0; 0x4000]); - assert!(g16::gate::cdm(&vm, usc, BASE, BASE + words.len() as u64 * 4).is_ok()); + assert!(cdm(&vm, usc, BASE, BASE + words.len() as u64 * 4).is_ok()); } } #[test] @@ -145,7 +238,7 @@ let mut vm = vm_for(&words); let mut linked = bytes(&[0x60000160, 0x40000000]); linked.resize(0x4000, 0); vm.region(target, linked); - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_ok()); + assert!(cdm(&vm, USC, BASE, BASE + 8).is_ok()); assert!(!run(&[0x30000006, 0])); // Call/return form is not qualified. } #[test] @@ -174,11 +267,11 @@ assert!(!run(&words)); let mut words = launch(0, USC, 0); words.push(0x40000000); let mut vm = vm_for(&words); vm.regions[1].readable = false; - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 44).is_err()); + assert!(cdm(&vm, USC, BASE, BASE + 44).is_err()); let target = 0x7000000000u64; let words = [0x20000000 | (target >> 32) as u32, target as u32]; let mut vm = vm_for(&words); vm.region(target, vec![0; 0x4000]); - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_err()); + assert!(cdm(&vm, USC, BASE, BASE + 8).is_err()); } #[test] fn cycles_are_rejected() { @@ -186,7 +279,7 @@ let words = [0x20000000 | (b >> 32) as u32, b as u32]; let mut vm = vm_for(&words); vm.regions[0].bytes[0x100..0x108].copy_from_slice(&bytes(&[0x20000000 | (a >> 32) as u32, a as u32])); - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_err()); + assert!(cdm(&vm, USC, BASE, BASE + 8).is_err()); assert!(!run(&[0x20000000 | (a >> 32) as u32, a as u32])); // A loop beyond the old record budget must also be detected. let mut words = vec![0x60000160; 20000]; @@ -223,28 +316,188 @@ let mut data = bytes(&words); data.resize(0x4000, 0); vm.region(address, data); } - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_ok()); + assert!(cdm(&vm, USC, BASE, BASE + 8).is_ok()); let tail = vm.regions.last_mut().unwrap(); tail.bytes[..8].copy_from_slice(&bytes(&root)); - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_err()); + assert!(cdm(&vm, USC, BASE, BASE + 8).is_err()); +} +#[test] +fn cached_window_reuses_page_coverage_without_rechecking_every_record() { + let mut words = Vec::new(); + for _ in 0..5 { + words.extend(launch(0, USC, 0)); + } + words.push(0x40000000); + // 5 launches * 40B + 4B terminate = 204 bytes, all within one 256-byte window. + g16::command::reset_cover_calls(); + assert!(run(&words)); + // Expect 1 cover() call for the 256B stream window + 1 for the cached USC program page. + assert_eq!(g16::command::cover_calls(), 2); } #[test] fn pending_signal_interrupts_walk() { let words = [0x60000160, 0x40000000]; let vm = vm_for(&words); kernel::task::pending(true); - let result = g16::gate::cdm(&vm, USC, BASE, BASE + 8); + let result = cdm(&vm, USC, BASE, BASE + 8); kernel::task::pending(false); assert_eq!(result, Err(kernel::prelude::ERESTARTSYS)); - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_ok()); + assert!(cdm(&vm, USC, BASE, BASE + 8).is_ok()); +} +fn vdm_check(vm: &mmu::Vm, vas: &[u64]) -> kernel::prelude::Result { + let mut guard = vm.read_lock()?; + g16::gate::vdm_batch_locked(&mut guard, vas) } #[test] fn vdm_m4_root_barrier() { - assert!(g16::gate::vdm(&vm_for(&[0x21000960]), BASE).is_ok()); + for word in [0x21000960, 0x21000968] { + assert!(vdm_check(&vm_for(&[word]), &[BASE]).is_ok()); + } for word in [0, 0x21000964, 0x40000000] { - assert!(g16::gate::vdm(&vm_for(&[word]), BASE).is_err()); + assert!(vdm_check(&vm_for(&[word]), &[BASE]).is_err()); } } +#[test] +fn vdm_batch_shares_lock_caches_window_and_rejects_bad_root() { + let mut vm = mmu::Vm::default(); + let mut page0 = vec![0u8; 0x4000]; + let mut page1 = vec![0u8; 0x4000]; + let root = 0x21000960u32.to_le_bytes(); + for off in [0usize, 0x20, 0x40, 0x80, 0x3ffc] { + page0[off..off + 4].copy_from_slice(&root); + } + page1[0x10..0x14].copy_from_slice(&root); + vm.region(BASE, page0); + vm.region(BASE + 0x4000, page1); + + // Empty batch performs no reads. + assert!(vdm_check(&vm, &[]).is_ok()); + assert_eq!(vm.read_calls.get(), 0); + + // Four adjacent VDM roots within 256 bytes share one lock and one read_user. + vm.lock_calls.set(0); + assert!(vdm_check(&vm, &[BASE, BASE + 0x20, BASE + 0x40, BASE + 0x80]).is_ok()); + assert_eq!(vm.lock_calls.get(), 1); + assert_eq!(vm.read_calls.get(), 1); + + // A bad root inside the same cached 256-byte window is still rejected. + vm.regions[0].bytes[0x80..0x84].copy_from_slice(&0xdeadbeefu32.to_le_bytes()); + assert_eq!( + vdm_check(&vm, &[BASE, BASE + 0x20, BASE + 0x80]), + Err(kernel::prelude::EINVAL) + ); + vm.regions[0].bytes[0x80..0x84].copy_from_slice(&root); + + // Cross-page and end-of-page roots share one lock and never over-read past UAT_PGSZ. + vm.lock_calls.set(0); + vm.read_calls.set(0); + assert!(vdm_check(&vm, &[BASE, BASE + 0x3ffc, BASE + 0x4010]).is_ok()); + assert_eq!(vm.lock_calls.get(), 1); + assert_eq!(vm.read_calls.get(), 3); +} +#[test] +fn cdm_batches_vm_read_lock_and_releases_on_resched() { + let target = 0x600000000u64; + let mut root = Vec::new(); + root.extend(launch(0, USC, 0)); + root.extend(launch(1, USC + 0x80, 0x400000000)); + root.extend(launch(2, USC + 0x100, 0x400000040)); + root.extend([0x20000000 | (target >> 32) as u32, target as u32]); + let mut vm = vm_for(&root); + let mut linked_words = launch(0, USC + 0x4000, 0); + linked_words.push(0x40000000); + let mut linked = bytes(&linked_words); + linked.resize(0x4000, 0); + vm.region(target, linked); + vm.region(USC + 0x4000, vec![0; 0x4000]); + + // Multi-launch mode 0/1/2 + linked segment acquires the VM read lock only once. + assert!(cdm(&vm, USC, BASE, BASE + root.len() as u64 * 4).is_ok()); + assert_eq!(vm.lock_calls.get(), 1); + + // Streams longer than CDM_RESCHED_RECORDS (1024) drop and re-acquire the lock on each resched. + let mut long = vec![0x60000160; 2500]; + long.push(0x40000000); + let long_vm = vm_for(&long); + let sched_before = kernel::task::scheduled(); + assert!(cdm(&long_vm, USC, BASE, BASE + long.len() as u64 * 4).is_ok()); + let sched_delta = kernel::task::scheduled() - sched_before; + assert_eq!(sched_delta, 3); + assert_eq!(long_vm.lock_calls.get(), sched_delta); +} +#[test] +fn single_vdm_and_short_cdm_root_minimize_poc_read_len() { + let vm = vm_for(&[0x21000960]); + assert!(vdm_check(&vm, &[BASE]).is_ok()); + assert_eq!(vm.lock_calls.get(), 1); + assert_eq!(vm.read_calls.get(), 1); + assert_eq!(vm.last_read_len.get(), 4); + + let mut words = launch(0, USC, 0); + words.push(0x40000000); + let cdm_vm = vm_for(&words); + assert!(cdm(&cdm_vm, USC, BASE, BASE + words.len() as u64 * 4).is_ok()); + assert_eq!(cdm_vm.lock_calls.get(), 1); + assert_eq!(cdm_vm.read_calls.get(), 1); + assert_eq!(cdm_vm.last_read_len.get(), words.len() * 4); +} +#[test] +fn cdm_locked_shares_held_guard_and_hits_span_proof() { + let mut words = launch(1, USC + 0x80, 0x400000000); + words.push(0x40000000); + let vm = vm_for(&words); + vm.epoch.set(Some(7)); + let mut proof = g16::command::SpanProof::new(); + + // Caller holds one VmReadGuard across two cdm_locked walks; first pass populates proof, + // second pass hits proof with zero additional cover_locked walks and still 1 lock_calls. + let mut guard = Some(vm.read_lock().unwrap()); + let mut epoch = guard.as_ref().and_then(|g| g.epoch()); + g16::command::reset_cover_calls(); + assert!(g16::gate::cdm_locked( + &vm, + &mut guard, + &mut epoch, + USC, + BASE, + BASE + words.len() as u64 * 4, + Some(&mut proof), + ) + .is_ok()); + assert_eq!(vm.lock_calls.get(), 1); + assert_eq!(g16::command::cover_calls(), 3); + + assert!(g16::gate::cdm_locked( + &vm, + &mut guard, + &mut epoch, + USC, + BASE, + BASE + words.len() as u64 * 4, + Some(&mut proof), + ) + .is_ok()); + drop(guard); + assert_eq!(vm.lock_calls.get(), 1); + assert_eq!(g16::command::cover_calls(), 3); + + // Epoch bump invalidates the cached proof and forces cover_locked to re-verify spans. + vm.epoch.set(Some(8)); + let mut guard = Some(vm.read_lock().unwrap()); + let mut epoch = guard.as_ref().and_then(|g| g.epoch()); + assert!(g16::gate::cdm_locked( + &vm, + &mut guard, + &mut epoch, + USC, + BASE, + BASE + words.len() as u64 * 4, + Some(&mut proof), + ) + .is_ok()); + assert_eq!(vm.lock_calls.get(), 2); + assert_eq!(g16::command::cover_calls(), 6); +} ''' with tempfile.TemporaryDirectory(prefix='m4-rust-gate-') as directory: @@ -258,7 +511,7 @@ (OUT / 'stream-gate-host.log').write_text(result.stdout + result.stderr) (OUT / 'stream-gate-host.json').write_text(json.dumps({ 'source': str(SOURCE), 'sha256': hashlib.sha256(SOURCE.read_bytes()).hexdigest(), - 'result': 'pass', 'test_groups': 10, + 'result': 'pass', 'test_groups': 12, 'mesa_sources': ['src/asahi/genxml/agx3_cmdstream.h', 'src/asahi/lib/agx3_cdm_decode_core.c', 'src/asahi/lib/agx_vdm_barrier_core.c'], 'limitations': 'Host VM model validates parser, addresses, cycles and interruption; hardware and kernel cache behavior require target tests.' diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-submit-restart.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-submit-restart.py index a920eae57ee3aa..8bbd90ad88e2f8 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-submit-restart.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-submit-restart.py @@ -11,15 +11,15 @@ #![allow(dead_code,unused_variables)] use std::pin::Pin;use std::sync::atomic::{AtomicU32,Ordering}; type Result = std::result::Result;const ERESTARTSYS:i32=512;const EBUSY:i32=16; -type KVec=Vec;type KBox=Box; +type KVec=Vec;type KVVec=Vec;type KBox=Box; mod xarray{pub struct XArray(pub T);} mod file{pub struct SyncItem;pub struct Object;} mod driver{pub struct AsahiRegData<'a>(pub &'a ());} static ACCEPTED:AtomicU32=AtomicU32::new(0);static REFUSED:AtomicU32=AtomicU32::new(0); -struct Syncs;impl Syncs{fn new(_v:Vec,_n:usize)->Self{Self}fn accept(&self,_f:&u32){ACCEPTED.fetch_add(1,Ordering::SeqCst);}fn refuse(&self,_t:&(),error:i32){assert_ne!(error,ERESTARTSYS);REFUSED.fetch_add(1,Ordering::SeqCst);}} +struct Syncs;impl Syncs{fn new(_v:Vec,_n:usize)->Self{Self}fn publish(&mut self,_f:&u32)->Result{ACCEPTED.fetch_add(1,Ordering::SeqCst);Ok(())}fn refuse(&self,_t:&(),error:i32){assert_ne!(error,ERESTARTSYS);REFUSED.fetch_add(1,Ordering::SeqCst);}} struct Status;impl Status{fn record_if_device_loss(&self,_e:i32){}} struct Vm{status:Status}struct Queue{vm:Vm,timeline:(),next:Result} -impl Queue{fn submit_job(&self,_id:u64,_syncs:&Syncs,_count:usize,_raw:&[u8],_objects:Pin<&xarray::XArray>>)->Result{self.next} +impl Queue{fn submit_job(&self,_id:u64,syncs:&mut Syncs,_count:usize,_raw:&[u8],_objects:Pin<&xarray::XArray>>)->Result{let fence=self.next?;syncs.publish(&fence)} __SUBMIT__ } #[test]fn restart_has_no_output_fence_and_retry_accepts_once(){ diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py index 2df317430ea52f..9450a5d6a70019 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py @@ -199,12 +199,23 @@ def operation(op, now=0, mc=90000, error=0, gov=0, power=0, configured=9, cap=9, ('engine.rs', 'self.power.utilization.busy(now);'), ('poll.rs', 'self.power.utilization.idle(self.engine.stats.idle_from_ns);'), ('power.rs', '.govern(now, limit, !self.engine.flights.is_empty());'), - ('poll.rs', 'Ok(false)\n if firmware.recovery.failed().is_none()\n' - ' && firmware.power.utilization.decaying() =>\n' - ' {\n self.mod_poll('), + ('poll.rs', 'fn arm_idle_power_poll(self: &Arc, firmware: &Firmware)'), + ('poll.rs', 'if firmware.power.clpc_holding() {'), + ('poll.rs', 'else if firmware.power.utilization.decaying() {'), + ('power.rs', 'if idle && self.power.clpc_hold.expire(now) {'), + ('recovery.rs', 'self.power.release_clpc_now();'), + ('sleep.rs', 'firmware.power.release_clpc_now();'), + ('poll.rs', 'shared.feed.note_flight(f.published_ns, now);'), + ('mod.rs', 'self.feed.begin_shutdown();'), + ('sleep.rs', 'self.feed.pause();'), + ('sleep.rs', 'self.feed_wq.drain();'), + ('sleep.rs', 'self.feed.release_floor();'), ]: assert (G16/path).read_text().count(call) == 1, (path, call) -print('Governor connected at publication, drain, power service and idle re-arm') +assert (G16/'poll.rs').read_text().count('self.arm_idle_power_poll(firmware);') == 3 +assert (G16/'poll.rs').read_text().count('self.queue_feed();') == 3 +assert (G16/'sleep.rs').read_text().count('feed.resume();') == 3 +print('Governor and CPU feed actuator connected at publication, drain, power service, sleep and idle re-arm') print(json.dumps(report,indent=2)) # Read/reattach interleavings exercise the provider's actual epoch state helpers. @@ -244,3 +255,46 @@ def operation(op, now=0, mc=90000, error=0, gov=0, power=0, configured=9, cap=9, run(['cc','-std=gnu11','-Wall','-Wextra','-Werror','-fsanitize=undefined','-fno-sanitize-recover=all',str(lease_unit),'-o',str(OUT/'gpu-lease')]) run([str(OUT/'gpu-lease')]) print('GPU attach epochs reject stale worker publications and stale detach, begin restricted, expire budgets and never wrap') + +# Validate shared -ENODATA hold logic and its call sites in G16 glue and PMP thermal. +nodata_source = r''' +#include +#include +#include +int main(void) { + const unsigned long long t0 = 10000000000ULL; + /* Never hold without a prior valid timestamp or if time went backwards. */ + assert(!apple_pmp_hold_nodata(0, 50000, t0, true)); + assert(!apple_pmp_hold_nodata(0, 50000, t0, false)); + assert(!apple_pmp_hold_nodata(t0 + 1, 50000, t0, true)); + assert(!apple_pmp_hold_nodata(t0 + 1, 50000, t0, false)); + + /* Idle cool (<100 C) holds indefinitely; hot idle (>=100 C) uses transient window only. */ + assert(apple_pmp_hold_nodata(t0, 99999, t0 + 10000000000ULL, true)); + assert(apple_pmp_hold_nodata(t0, 100000, t0 + 100000000ULL, true)); + assert(!apple_pmp_hold_nodata(t0, 100000, t0 + 100000001ULL, true)); + + /* Active <100 C holds across the 2 s gated window, then fails closed. */ + assert(apple_pmp_hold_nodata(t0, 94000, t0 + APPLE_PMP_GATED_HOLD_NS - 1, false)); + assert(apple_pmp_hold_nodata(t0, 99999, t0 + APPLE_PMP_GATED_HOLD_NS - 1, false)); + assert(!apple_pmp_hold_nodata(t0, 99999, t0 + APPLE_PMP_GATED_HOLD_NS, false)); + + /* Active 100..105.999 C holds only a brief <=100 ms PMP SRAM refresh glitch. */ + assert(apple_pmp_hold_nodata(t0, 100000, t0 + APPLE_PMP_TRANSIENT_HOLD_NS, false)); + assert(apple_pmp_hold_nodata(t0, 105999, t0 + APPLE_PMP_TRANSIENT_HOLD_NS, false)); + assert(!apple_pmp_hold_nodata(t0, 100000, t0 + APPLE_PMP_TRANSIENT_HOLD_NS + 1, false)); + assert(!apple_pmp_hold_nodata(t0, 105999, t0 + APPLE_PMP_TRANSIENT_HOLD_NS + 1, false)); + + /* At or above passive throttling (106 C), -ENODATA always fails closed immediately. */ + assert(!apple_pmp_hold_nodata(t0, APPLE_PMP_PASSIVE_MC, t0, false)); + assert(!apple_pmp_hold_nodata(t0, APPLE_PMP_PASSIVE_MC, t0, true)); + assert(!apple_pmp_hold_nodata(t0, 110000, t0 + 1000000ULL, false)); + return 0; +} +''' +nodata_unit = OUT/'nodata-hold.c'; nodata_unit.write_text(nodata_source) +nodata_bin = build(ROOT, OUT, nodata_unit) +run([str(nodata_bin)]) +assert 'apple_pmp_hold_nodata(' in (G16/'glue.c').read_text() +assert 'apple_pmp_hold_nodata(' in (ROOT/'drivers/thermal/apple-pmp-thermal.c').read_text() +print('Shared -ENODATA hold masks brief PMP refresh glitches below passive trip and fails closed above') diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py index 9a159e849e86b5..78b33c7ac32b33 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py @@ -22,6 +22,7 @@ def function(source, marker): mmu = (backend / 'mmu.rs').read_text() shared = (backend / 'timestamp.rs').read_text() poll = (backend / 'g16/poll.rs').read_text() +obj = (backend / 'g16/object.rs').read_text() cache_policy = function((backend / 'gem.rs').read_text(), 'pub(crate) fn is_writeback(') store = function(mmu, 'pub(crate) fn write(&self, value: u64)') vmap_store = function(mmu, 'pub(crate) fn write(&self, offset: usize, value: u64)') @@ -29,6 +30,10 @@ def function(source, marker): checked_offset = function(shared, 'fn checked_offset(') publish = function(shared, 'pub(crate) fn publish(&self, ticks: [u64; 4], frequency_hz: u64)') retire = function(poll, 'fn publish_timestamps(&self, flight: &Flight, claims: &super::slots::Claims)') +compute_ticks = function(poll, 'fn compute_ticks(&self, unit: &super::slots::ComputeSlot)') +compute_ticks_with = function(poll, 'fn compute_ticks_with(') +fw_r64 = function(obj, 'pub(crate) fn r64(&self, offset: usize)') +fw_read = function(obj, 'pub(crate) fn read(&self, offset: usize, out: &mut [u8])') source = r''' #![allow(dead_code)] use core::sync::atomic::{AtomicU8, AtomicU64, Ordering, fence as barrier}; @@ -63,6 +68,7 @@ def function(source, marker): impl Destination { __WRITE__ } struct Destinations([Option;4]); impl Destinations { + fn is_empty(&self)->bool{self.0.iter().all(Option::is_none)} fn iter(&self)->core::slice::Iter<'_,Option>{self.0.iter()} __PUBLISH__ } @@ -147,38 +153,99 @@ def function(source, marker): mod backend { use super::*; pub mod hw{pub const COMMAND_TIMESTAMP_HZ:u64=24_000_000;} - pub mod slots{pub struct Claims{pub slot:[u8;2],pub slot_count:u32,pub pass:[u8;2]}} + pub mod slots{ + use super::*; + pub struct Claims{pub slot:[u8;16],pub slot_count:u32,pub pass:[u8;4]} + pub type ComputeSlot = Compute; + } pub mod command{ use super::*; pub struct Compute{pub timestamp_outputs:Destinations} pub struct Render{pub timestamp_outputs:Destinations} pub enum Command{Compute(Compute),Render(Render)} } - pub struct Cells(pub [u64;4]);impl Cells{pub fn r64(&self,offset:usize)->Result{ - match offset{0=>Ok(self.0[0]),8=>Ok(self.0[1]),0x600=>Ok(self.0[0]),0x608=>Ok(self.0[1]),0x620=>Ok(self.0[2]),0x628=>Ok(self.0[3]),_=>Err(EINVAL)} - }} - pub struct Compute{pub its:Cells}pub struct Pass{pub scene:Cells} + pub struct Cells { + pub vals: [u64; 4], + pub r64_calls: std::cell::Cell, + pub r32_calls: std::cell::Cell, + pub sync_calls: std::cell::Cell, + } + impl Cells { + pub fn new(vals: [u64; 4]) -> Self { + Self { + vals, + r64_calls: std::cell::Cell::new(0), + r32_calls: std::cell::Cell::new(0), + sync_calls: std::cell::Cell::new(0), + } + } + pub fn sync_for_cpu(&self, _offset: usize, _len: usize) -> Result { + self.sync_calls.set(self.sync_calls.get() + 1); + Ok(()) + } + pub fn r64(&self, offset: usize) -> Result { + self.r64_calls.set(self.r64_calls.get() + 1); + match offset { + 0 => Ok(self.vals[0]), + 8 => Ok(self.vals[1]), + 0x600 => Ok(self.vals[0]), + 0x608 => Ok(self.vals[1]), + 0x620 => Ok(self.vals[2]), + 0x628 => Ok(self.vals[3]), + _ => Err(EINVAL), + } + } + pub fn r32(&self, offset: usize) -> Result { + self.r32_calls.set(self.r32_calls.get() + 1); + let v = match offset { + 0x100 => self.vals[0], + 0x104 => self.vals[0] >> 32, + 0x108 => self.vals[1], + 0x10c => self.vals[1] >> 32, + _ => return Err(EINVAL), + }; + Ok(v as u32) + } + } + pub struct Compute{pub its:Cells,pub work:Cells}pub struct Pass{pub scene:Cells} + pub struct ComputeAbi{pub work_ticks:Option<(usize,usize)>} + pub struct Abi{pub compute:ComputeAbi} + impl Abi{pub fn compute(&self)->&ComputeAbi{&self.compute}} + pub struct Init{pub abi:Abi} pub struct Scrub{pub compute:Vec,pub passes:Vec} - pub struct Slots{pub scrub:Scrub}pub struct Firmware{pub slots:Slots} + pub struct Slots{pub scrub:Scrub}pub struct Firmware{pub slots:Slots,pub init:Init} pub struct Resources{pub compute:Vec,pub passes:Vec} - impl Resources{pub fn compute(&self)->Result<&Self>{Ok(self)}pub fn render(&self)->Result<&Self>{Ok(self)}} + impl Resources{pub fn compute(&self)->Result<&Self>{Ok(self)}pub fn render(&self)->Result<&Self>{Ok(self)}pub fn compute_unit(&self,k:usize)->Result<&Compute>{self.compute.get(k).ok_or(super::EINVAL)}pub fn render_pass(&self,k:usize)->Result<&Pass>{self.passes.get(k).ok_or(super::EINVAL)}} pub struct Job{pub commands:Vec,pub resources:Resources} - pub struct Flight{pub job:Job,pub first:usize,pub count:usize,pub renders:u32} - pub mod poll{use super::*;impl Firmware{ __RETIRE__ }} + pub struct Flight{pub job:Job,pub group:Vec,pub first:usize,pub count:usize,pub renders:u32} + pub mod poll{ + use super::*; + const EIO:i32=-5; + impl Firmware{ + __COMPUTE_TICKS__ + __COMPUTE_TICKS_WITH__ + __RETIRE__ + } + } } use backend::*; -fn firmware()->Firmware{Firmware{slots:Slots{scrub:Scrub{compute:vec![],passes:vec![]}}}} +fn firmware()->Firmware{Firmware{slots:Slots{scrub:Scrub{compute:vec![],passes:vec![]}},init:Init{abi:Abi{compute:ComputeAbi{work_ticks:None}}}}} fn resources()->Resources{Resources{ - compute:vec![Compute{its:Cells([10,20,0,0])},Compute{its:Cells([30,40,0,0])}], - passes:vec![Pass{scene:Cells([100,200,300,400])},Pass{scene:Cells([500,600,700,800])}] + compute:vec![ + Compute{its:Cells::new([10,20,0,0]),work:Cells::new([0,0,0,0])}, + Compute{its:Cells::new([30,40,0,0]),work:Cells::new([0,0,0,0])}, + Compute{its:Cells::new([50,60,0,0]),work:Cells::new([0,0,0,0])}, + ], + passes:vec![Pass{scene:Cells::new([100,200,300,400])},Pass{scene:Cells::new([500,600,700,800])},Pass{scene:Cells::new([900,1000,1100,1200])}] }} #[test]fn retirement_uses_claimed_hardware_cells_and_endpoint_order(){ let compute=backing();let render=backing(); let flight=Flight{job:Job{commands:vec![ command::Command::Compute(command::Compute{timestamp_outputs:outputs(&compute)}), command::Command::Render(command::Render{timestamp_outputs:outputs(&render)}) - ],resources:resources()},first:0,count:2,renders:1}; - let claims=slots::Claims{slot:[1,0],slot_count:1,pass:[1,0]}; + ],resources:resources()},group:vec![],first:0,count:2,renders:1}; + let mut slot=[0u8;16];slot[0]=1; + let claims=slots::Claims{slot,slot_count:1,pass:[1,0,0,0]}; firmware().publish_timestamps(&flight,&claims).unwrap(); assert_eq!(compute.words[0].load(Ordering::Relaxed),expected(30)); assert_eq!(compute.words[1].load(Ordering::Relaxed),expected(40)); @@ -186,18 +253,230 @@ def function(source, marker): assert_eq!(render.words[index].load(Ordering::Relaxed),expected(ticks)); } } +#[test]fn batched_compute_horizon_group_timestamps_publish_for_all_members(){ + let c0=backing();let c1=backing();let c2=backing(); + let flight=Flight{ + job:Job{commands:vec![command::Command::Compute(command::Compute{timestamp_outputs:outputs(&c0)})],resources:resources()}, + group:vec![ + Job{commands:vec![command::Command::Compute(command::Compute{timestamp_outputs:outputs(&c1)})],resources:Resources{compute:vec![],passes:vec![]}}, + Job{commands:vec![command::Command::Compute(command::Compute{timestamp_outputs:outputs(&c2)})],resources:Resources{compute:vec![],passes:vec![]}}, + ], + first:0,count:1,renders:0, + }; + let mut slot=[0u8;16];slot[0]=0;slot[1]=1;slot[2]=2; + let claims=slots::Claims{slot,slot_count:3,pass:[0,0,0,0]}; + firmware().publish_timestamps(&flight,&claims).unwrap(); + assert_eq!((c0.words[0].load(Ordering::Relaxed),c0.words[1].load(Ordering::Relaxed)),(expected(10),expected(20))); + assert_eq!((c1.words[0].load(Ordering::Relaxed),c1.words[1].load(Ordering::Relaxed)),(expected(30),expected(40))); + assert_eq!((c2.words[0].load(Ordering::Relaxed),c2.words[1].load(Ordering::Relaxed)),(expected(50),expected(60))); +} +#[test]fn batched_render_horizon_group_timestamps_publish_for_all_members(){ + let r0=backing();let r1=backing();let r2=backing(); + let flight=Flight{ + job:Job{commands:vec![command::Command::Render(command::Render{timestamp_outputs:outputs(&r0)})],resources:resources()}, + group:vec![ + Job{commands:vec![command::Command::Render(command::Render{timestamp_outputs:outputs(&r1)})],resources:Resources{compute:vec![],passes:vec![]}}, + Job{commands:vec![command::Command::Render(command::Render{timestamp_outputs:outputs(&r2)})],resources:Resources{compute:vec![],passes:vec![]}}, + ], + first:0,count:1,renders:3, + }; + let claims=slots::Claims{slot:[0;16],slot_count:0,pass:[0,1,2,0]}; + firmware().publish_timestamps(&flight,&claims).unwrap(); + for (buf, ticks) in [(&r0,[100,200,300,400]),(&r1,[500,600,700,800]),(&r2,[900,1000,1100,1200])] { + for (index, tick) in ticks.into_iter().enumerate() { + assert_eq!(buf.words[index].load(Ordering::Relaxed), expected(tick)); + } + } +} #[test]fn invalid_command_span_and_missing_claim_are_rejected(){ let memory=backing();let mut flight=Flight{job:Job{commands:vec![ command::Command::Compute(command::Compute{timestamp_outputs:outputs(&memory)}) - ],resources:resources()},first:usize::MAX,count:2,renders:0}; - let mut claims=slots::Claims{slot:[0,0],slot_count:1,pass:[0,0]}; + ],resources:resources()},group:vec![],first:usize::MAX,count:2,renders:0}; + let mut claims=slots::Claims{slot:[0;16],slot_count:1,pass:[0,0,0,0]}; assert_eq!(firmware().publish_timestamps(&flight,&claims),Err(EOVERFLOW)); flight.first=1;assert_eq!(firmware().publish_timestamps(&flight,&claims),Err(EINVAL)); flight.first=0;flight.count=1;claims.slot_count=0; assert_eq!(firmware().publish_timestamps(&flight,&claims),Err(EINVAL)); assert_eq!(memory.words[0].load(Ordering::Relaxed),u64::MAX); } -'''.replace('__CHECKED_OFFSET__', checked_offset).replace('__STORE__', store).replace('__VMAP_STORE__', vmap_store.replace('.timestamp_lock.lock()', '.timestamp_lock.lock().unwrap()')).replace('__CACHE_POLICY__', cache_policy).replace('__WRITE__', write).replace('__PUBLISH__', publish).replace('__RETIRE__', retire.replace('fn publish_timestamps', 'pub(crate) fn publish_timestamps')) +#[test]fn empty_timestamp_outputs_skip_hardware_cell_reads(){ + let flight=Flight{job:Job{commands:vec![ + command::Command::Compute(command::Compute{timestamp_outputs:Destinations(core::array::from_fn(|_|None))}), + command::Command::Render(command::Render{timestamp_outputs:Destinations(core::array::from_fn(|_|None))}), + ],resources:Resources{compute:vec![],passes:vec![]}},group:vec![],first:0,count:2,renders:1}; + let claims=slots::Claims{slot:[0;16],slot_count:1,pass:[0,0,0,0]}; + firmware().publish_timestamps(&flight,&claims).unwrap(); +} +#[test]fn work_ticks_fallback_publishes_compute_timestamps_for_26b123(){ + let c0=backing();let c1=backing(); + let mut fw=firmware(); + fw.init.abi.compute.work_ticks=Some((0x100,0x108)); + let res=Resources{ + compute:vec![ + Compute{its:Cells::new([0,0,0,0]),work:Cells::new([0x1_0000_0070,0x1_0000_0090,0,0])}, + Compute{its:Cells::new([0,0,0,0]),work:Cells::new([0x2_0000_0010,0x2_0000_0040,0,0])}, + ], + passes:vec![], + }; + let flight=Flight{ + job:Job{commands:vec![command::Command::Compute(command::Compute{timestamp_outputs:outputs(&c0)})],resources:res}, + group:vec![Job{commands:vec![command::Command::Compute(command::Compute{timestamp_outputs:outputs(&c1)})],resources:Resources{compute:vec![],passes:vec![]}}], + first:0,count:1,renders:0, + }; + let mut slot=[0u8;16];slot[0]=0;slot[1]=1; + let claims=slots::Claims{slot,slot_count:2,pass:[0,0,0,0]}; + fw.publish_timestamps(&flight,&claims).unwrap(); + assert_eq!((c0.words[0].load(Ordering::Relaxed),c0.words[1].load(Ordering::Relaxed)),(expected(0x1_0000_0070),expected(0x1_0000_0090))); + assert_eq!((c1.words[0].load(Ordering::Relaxed),c1.words[1].load(Ordering::Relaxed)),(expected(0x2_0000_0010),expected(0x2_0000_0040))); + // 26B123 work_ticks-first path invalidates cacheable FwCoherent work lines and skips ITS WC reads. + assert_eq!(flight.job.resources.compute[0].work.sync_calls.get(), 1); + assert_eq!(flight.job.resources.compute[1].work.sync_calls.get(), 1); + assert_eq!(flight.job.resources.compute[0].its.r64_calls.get(), 0); + assert_eq!(flight.job.resources.compute[1].its.r64_calls.get(), 0); + // When work_ticks holds no interval (0/0), fall back to ITS cleanly. + let fallback_unit = Compute { + its: Cells::new([0x300, 0x400, 0, 0]), + work: Cells::new([0, 0, 0, 0]), + }; + assert_eq!(fw.compute_ticks(&fallback_unit), Ok((0x300, 0x400))); + assert_eq!(fallback_unit.work.sync_calls.get(), 1); + assert_eq!(fallback_unit.its.r64_calls.get(), 2); + // 25G83 (work_ticks = None) reads ITS directly with zero work reads or syncs. + let fw25 = firmware(); + let unit25 = Compute { + its: Cells::new([0x500, 0x600, 0, 0]), + work: Cells::new([0x700, 0x800, 0, 0]), + }; + assert_eq!(fw25.compute_ticks(&unit25), Ok((0x500, 0x600))); + assert_eq!(unit25.its.r64_calls.get(), 2); + assert_eq!(unit25.work.r32_calls.get(), 0); + assert_eq!(unit25.work.sync_calls.get(), 0); +} +mod r64_scope { + use super::{Result, EINVAL}; + use std::cell::Cell; + use std::sync::atomic::{AtomicU32, Ordering}; + const EAGAIN: i32 = -11; + thread_local! { + static RMB_COUNT: Cell = const { Cell::new(0) }; + static MUTATE_HOOK: Cell> = const { Cell::new(None) }; + } + fn rmb() { + RMB_COUNT.with(|c| c.set(c.get() + 1)); + std::sync::atomic::fence(Ordering::SeqCst); + if let Some(hook) = MUTATE_HOOK.with(|h| h.get()) { + hook(); + } + } + #[repr(C, align(8))] + struct Buf([u8; 32]); + struct FwObject { + ptr: *mut u8, + len: usize, + read_calls: Cell, + } + impl FwObject { + fn ptr(&self, offset: usize, len: usize) -> Result<*mut u8> { + if offset.checked_add(len).is_none_or(|e| e > self.len) { + return Err(EINVAL); + } + Ok(unsafe { self.ptr.add(offset) }) + } + fn read_impl(&self, offset: usize, out: &mut [u8]) -> Result { + self.read_calls.set(self.read_calls.get() + 1); + self.read_prod(offset, out) + } + __FW_READ__ + __FW_R64__ + } + #[test] + fn r64_4byte_aligned_uses_word_pairs_handles_carry_and_rejects_churn() { + let mut buf = Buf([0u8; 32]); + let val_a: u64 = 0x1122_3344_5566_7788; + let val_b: u64 = 0x0123_4567_89ab_cdef; + let val_c: u64 = 0xfedc_ba98_7654_3210; + buf.0[0..8].copy_from_slice(&val_a.to_le_bytes()); + buf.0[4 + 8..4 + 16].copy_from_slice(&val_b.to_le_bytes()); + buf.0[21..29].copy_from_slice(&val_c.to_le_bytes()); + let obj = FwObject { + ptr: buf.0.as_mut_ptr(), + len: buf.0.len(), + read_calls: Cell::new(0), + }; + // 8-byte aligned: single volatile u64 + 1 rmb, never calls byte read(). + RMB_COUNT.with(|c| c.set(0)); + assert_eq!(obj.r64(0), Ok(val_a)); + assert_eq!(obj.read_calls.get(), 0); + assert_eq!(RMB_COUNT.with(|c| c.get()), 1); + // 4-byte aligned (matching compute::DESCRIPTOR_COUNTER 0xe4c / COMPLETED 0xe54): + // uses 32-bit word pairs (3 rmbs), never falls back to byte read(). + RMB_COUNT.with(|c| c.set(0)); + assert_eq!(obj.r64(12), Ok(val_b)); + assert_eq!(obj.read_calls.get(), 0); + assert_eq!(RMB_COUNT.with(|c| c.get()), 3); + // Unaligned (offset % 4 != 0): still uses read() double-snapshot fallback. + assert_eq!(obj.r64(21), Ok(val_c)); + assert_eq!(obj.read_calls.get(), 2); + // Actively mutating 4-byte-aligned receipt returns EAGAIN instead of a torn word. + static TARGET: std::sync::atomic::AtomicPtr = + std::sync::atomic::AtomicPtr::new(core::ptr::null_mut()); + static TICK: AtomicU32 = AtomicU32::new(0); + fn bump() { + let p = TARGET.load(Ordering::Relaxed); + if !p.is_null() { + let n = TICK.fetch_add(1, Ordering::Relaxed); + unsafe { p.write_volatile(n) }; + } + } + TARGET.store(unsafe { buf.0.as_mut_ptr().add(12).cast::() }, Ordering::Relaxed); + MUTATE_HOOK.with(|h| h.set(Some(bump))); + assert_eq!(obj.r64(12), Err(EAGAIN)); + MUTATE_HOOK.with(|h| h.set(None)); + TARGET.store(core::ptr::null_mut(), Ordering::Relaxed); + // Torn carry-wrap snapshot recovery: snapshot 1 sees LOW_WRAP, snapshot 2 sees torn + // (0xffff_ffff, 1), snapshots 3 & 4 see settled HIGH_WRAP -> returns HIGH_WRAP. + const LOW_WRAP: u64 = 0x0000_0000_ffff_ffff; + const HIGH_WRAP: u64 = 0x0000_0001_0000_0000; + static WRAP_PTR: std::sync::atomic::AtomicPtr = + std::sync::atomic::AtomicPtr::new(core::ptr::null_mut()); + static WRAP_STEP: AtomicU32 = AtomicU32::new(0); + fn step_wrap() { + let p = WRAP_PTR.load(Ordering::Relaxed); + if p.is_null() { + return; + } + match WRAP_STEP.fetch_add(1, Ordering::Relaxed) { + 0 => { + unsafe { + p.write_volatile(LOW_WRAP as u32); + p.add(1).write_volatile((LOW_WRAP >> 32) as u32); + } + } + 1 => { + // Torn intermediate across the 32-bit carry boundary. + unsafe { + p.write_volatile(0xffff_ffff); + p.add(1).write_volatile(1); + } + } + _ => { + unsafe { + p.write_volatile(HIGH_WRAP as u32); + p.add(1).write_volatile((HIGH_WRAP >> 32) as u32); + } + } + } + } + WRAP_STEP.store(0, Ordering::Relaxed); + WRAP_PTR.store(unsafe { buf.0.as_mut_ptr().add(12).cast::() }, Ordering::Relaxed); + MUTATE_HOOK.with(|h| h.set(Some(step_wrap))); + assert_eq!(obj.r64(12), Ok(HIGH_WRAP)); + MUTATE_HOOK.with(|h| h.set(None)); + WRAP_PTR.store(core::ptr::null_mut(), Ordering::Relaxed); + assert_eq!(obj.read_calls.get(), 2); + } +} +'''.replace('__CHECKED_OFFSET__', checked_offset).replace('__STORE__', store).replace('__VMAP_STORE__', vmap_store.replace('.timestamp_lock.lock()', '.timestamp_lock.lock().unwrap()')).replace('__CACHE_POLICY__', cache_policy).replace('__WRITE__', write).replace('__PUBLISH__', publish).replace('__COMPUTE_TICKS__', compute_ticks.replace('fn compute_ticks', 'pub(crate) fn compute_ticks')).replace('__COMPUTE_TICKS_WITH__', compute_ticks_with).replace('__RETIRE__', retire.replace('fn publish_timestamps', 'pub(crate) fn publish_timestamps')).replace('__FW_READ__', fw_read.replace('pub(crate) fn read(', 'fn read_prod(')).replace('__FW_R64__', fw_r64.replace('self.read(', 'self.read_impl(')) path = out / 'timestamps-host.rs' path.write_text(source) subprocess.run(rustc() + ['--edition=2021', '--test', str(path), '-o', str(out / 'timestamps-host')], check=True) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-uapi.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-uapi.py index a6c936f3c0b4aa..38bcec27ce8879 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-uapi.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-uapi.py @@ -5,8 +5,96 @@ import json import os from pathlib import Path +import re +import subprocess from abi import c_layout, differences, rust_layout -from common import FIXTURES, kernel_root, output_dir, verify_fixtures +from common import FIXTURES, kernel_root, output_dir, rustc, verify_fixtures + + +def item(text, declaration): + start = text.index(declaration) + at = text.index('{', start) + depth, end = 1, at + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +SOFT_FAULTS_HARNESS = r''' +#![allow(dead_code, non_upper_case_globals)] +mod uapi { __UAPI__ } +mod module_parameters { + pub struct Param(pub std::cell::Cell); + impl Param { pub fn value(&self) -> u32 { self.0.get() } } + std::thread_local! { + pub static FAULT_CONTROL: Param = const { Param(std::cell::Cell::new(0xb)) }; + } + pub struct FaultControl; + impl FaultControl { pub fn value(&self) -> u32 { FAULT_CONTROL.with(|p| p.value()) } } + pub static fault_control: FaultControl = FaultControl; +} +pub struct QueueLimits; +trait Backend { + fn backend_feature_flags(&self) -> u64 { 0 } + fn supports_vm_status(&self) -> bool { false } + fn queue_limits(&self) -> Option { None } + __SHARED__ +} +struct G16; +impl Backend for G16 { + fn supports_vm_status(&self) -> bool { true } + fn queue_limits(&self) -> Option { Some(QueueLimits) } + __OVERRIDE__ +} +const SOFT: u64 = uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_SOFT_FAULTS as u64; +#[test] +fn g16_advertises_soft_faults_until_fault_control_opts_out() { + let set = |v| module_parameters::FAULT_CONTROL.with(|p| p.0.set(v)); + set(0xb); + assert_eq!(G16.feature_flags() & SOFT, SOFT); + for other in [0, 1, 0xa, 0xf] { + set(other); + assert_eq!(G16.feature_flags() & SOFT, 0, "fault_control {other:#x}"); + } + set(0xb); + // The other shared bits are unchanged by the opt-out. + let rest = G16.feature_flags() & !SOFT; + set(0); + assert_eq!(G16.feature_flags(), rest); +} +''' + + +def soft_faults(kernel, header, out): + """The production G16 SOFT_FAULTS advertisement: the shared defaults with G16's override.""" + gpu = (kernel / 'drivers/gpu/drm/asahi/gpu.rs').read_text() + g16 = (kernel / 'drivers/gpu/drm/asahi/g16/mod.rs').read_text() + # G16 keeps the shared fault_control opt-out: it overrides soft_faults() only. + assert g16.count('fn soft_faults(&self) -> bool {') == 1 + assert 'fn supports_soft_faults(' not in g16 + text = header.read_text() + + def feature(name): + shift = re.search(r'\b' + name + r'\s*=\s*\(1UL\)\s*<<\s*(\d+)', text).group(1) + return f'pub const drm_asahi_feature_{name}: u32 = 1 << {shift};' + + names = ('SOFT_FAULTS', 'VM_STATUS', 'VM_STATUS_MIRROR', 'INDEPENDENT_QUEUES') + uapi = '\n'.join(feature('DRM_ASAHI_FEATURE_' + n) for n in names) + shared = '\n'.join(item(gpu, decl) for decl in ('fn supports_soft_faults(&self) -> bool {', + 'fn feature_flags(&self) -> u64 {', + 'fn soft_faults(&self) -> bool {')) + source = (SOFT_FAULTS_HARNESS.replace('__UAPI__', uapi).replace('__SHARED__', shared) + .replace('__OVERRIDE__', item(g16, 'fn soft_faults(&self) -> bool {'))) + (out / 'soft-faults.rs').write_text(source) + for command in [rustc() + ['--edition=2021', '--test', str(out / 'soft-faults.rs'), '-o', + str(out / 'soft-faults')], + [str(out / 'soft-faults')]]: + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True) + print(result.stdout, end='') + if result.returncode: + raise SystemExit(result.returncode) def main(): @@ -23,6 +111,7 @@ def main(): kernel = c_layout(header, bindings, out, 'kernel-layout') rust = rust_layout(bindings, out) errors = differences(kernel, rust) + soft_faults(args.kernel.resolve(), header, out) mesa = None if args.mesa: mesa = args.mesa.resolve() / 'include/drm-uapi/asahi_drm.h' @@ -31,7 +120,8 @@ def main(): 'kernel': str(header), 'bindings': str(bindings), 'comparisons': len(kernel), 'mesa': str(mesa) if mesa else None, 'mesa_comparison': 'performed' if mesa else 'not requested; set ASAHI_M4_MESA or --mesa', - 'errors': errors} + 'errors': errors, + 'soft_faults': 'G16 SOFT_FAULTS advertisement checked against fault_control'} if args.json: args.json.write_text(json.dumps(report, indent=2) + '\n') print(json.dumps(report, indent=2)) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py index add96b48bb3357..96d3238471635f 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py @@ -22,8 +22,9 @@ def item(marker): mod hw{pub mod sizes{pub const MAX_VMS:u32=63;}} mod module_parameters{pub struct Param;impl Param{pub fn value(&self)->u32{0}}pub static robust_isolation:Param=Param;} mod types{pub struct ScopeGuard(Option);implScopeGuard{pub fn new(f:F)->Self{Self(Some(f))}pub fn dismiss(mut self){self.0.take();}}implDrop for ScopeGuard{fn drop(&mut self){if let Some(f)=self.0.take(){f()}}}} -struct Handle;impl Handle{fn is_closed(&self)->bool{false}} -struct VmState{id:u64,vm:Handle,drops:Arc}impl Drop for VmState{fn drop(&mut self){self.drops.fetch_add(1,Ordering::AcqRel);}} +struct Handle(std::sync::atomic::AtomicBool);impl Handle{fn open()->Self{Self(std::sync::atomic::AtomicBool::new(false))}fn mark_closed(&self){self.0.store(true,Ordering::Release);}fn is_closed(&self)->bool{self.0.load(Ordering::Acquire)}} +struct Cache{closes:AtomicU32,spares:StdMutex>>}impl Cache{fn new()->Self{Self{closes:AtomicU32::new(0),spares:StdMutex::new(Vec::new())}}fn close(&self){self.closes.fetch_add(1,Ordering::AcqRel);let spares=std::mem::take(&mut *self.spares.lock().unwrap());drop(spares);}} +struct VmState{id:u64,vm:Handle,drops:Arc,resources:Option>}impl Drop for VmState{fn drop(&mut self){self.drops.fetch_add(1,Ordering::AcqRel);}} __REGISTRY__ struct Reservation<'a>(Option<&'a Registry>,u64); __RESERVATION_DROP__ @@ -46,12 +47,28 @@ def item(marker): } #[test]fn close_releases_registry_owner_without_another_vm_create(){ let r=Registry::new_test();let drops=Arc::new(AtomicU32::new(0)); - let state=Arc::new(VmState{id:1,vm:Handle,drops:drops.clone()});r.vms.lock().push(state.clone(),0).unwrap(); + let cache=Arc::new(Cache::new()); + let state=Arc::new(VmState{id:1,vm:Handle::open(),drops:drops.clone(),resources:Some(cache.clone())});r.vms.lock().push(state.clone(),0).unwrap(); r.close(1);assert!(r.vms.lock().is_empty());assert_eq!(drops.load(Ordering::Acquire),0); + // The client's close lets the VM's cache drop its arenas while other owners hold the VM. + assert_eq!(cache.closes.load(Ordering::Acquire),1); drop(state);assert_eq!(drops.load(Ordering::Acquire),1); - r.vms.lock().push(Arc::new(VmState{id:2,vm:Handle,drops:drops.clone()}),0).unwrap(); + r.vms.lock().push(Arc::new(VmState{id:2,vm:Handle::open(),drops:drops.clone(),resources:None}),0).unwrap(); r.close(2);assert_eq!(drops.load(Ordering::Acquire),2); } +#[test]fn prune_closes_cache_and_breaks_spare_epoch_cycle(){ + let r=Registry::new_test();let drops=Arc::new(AtomicU32::new(0)); + let cache=Arc::new(Cache::new()); + let state=Arc::new(VmState{id:1,vm:Handle::open(),drops:drops.clone(),resources:Some(cache.clone())}); + // Simulate a spare PB epoch inside Cache holding a strong reference back to VmState. + cache.spares.lock().unwrap().push(state.clone()); + state.vm.mark_closed(); + r.vms.lock().push(state,0).unwrap(); + r.prune(); + assert!(r.vms.lock().is_empty()); + assert_eq!(cache.closes.load(Ordering::Acquire),1); + assert_eq!(drops.load(Ordering::Acquire),1); +} ''' for tag,marker in [('REGISTRY','pub(crate) struct Registry'),('RESERVATION_DROP',"impl Drop for Reservation<'_>"),('RESERVE','fn reserve(&self, file_id:'),('RELEASE','fn release(&self, file_id:'),('CLOSE','pub(crate) fn close(&self, id:'),('PRUNE','fn prune(&self)')]: source=source.replace('__'+tag+'__',item(marker).replace(' #[pin]\n','')) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm.py index 2c98ab19a751af..0c859eca42aa71 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm.py @@ -20,11 +20,21 @@ def body(source, marker): i += 1 return source[start:i] uat = (ROOT/'drivers/gpu/drm/asahi/g16/uat.rs').read_text() +hw = (ROOT/'drivers/gpu/drm/asahi/g16/hw.rs').read_text() +# The production 25G83 firmware page-table leaves, admitted against the frozen C oracle below. +layout = hw[hw.index('pub(crate) const FW_25G83: FwLayout = FwLayout {'):] +leaves = layout[layout.index('leaves: Some(&[') + len('leaves: Some('):layout.index(']),') + 1] +hw_leaves = '\n'.join([body(hw, '#[derive(Clone, Copy, PartialEq, Eq, Debug)]\npub(crate) enum Segment {'), + body(hw, 'pub(crate) struct Leaves {'), + body(hw, '#[derive(Clone, Copy, PartialEq, Eq, Debug)]\npub(crate) enum FwAbi {'), + body(hw, 'impl FwAbi {'), + body(hw, '#[derive(Clone, Copy, PartialEq, Eq, Debug)]\npub(crate) struct PplMagic {'), + 'pub const LEAVES_25G83: &[Leaves] = ' + leaves + ';']) vm = (ROOT/'drivers/gpu/drm/asahi/g16/vm.rs').read_text() pt = (ROOT/'drivers/gpu/drm/asahi/pgtable.rs').read_text() methods = '\n'.join(body(uat, m) for m in [ - 'fn cold_snapshot(', 'fn admit_cold(', 'fn admit_table(', 'pub(crate) fn ttbat_is_clear(', - 'pub(crate) fn bootstrap(', + 'fn cold_snapshot(', 'fn admit_cold(', 'fn admit_table(', 'pub(crate) fn await_firmware_magic(', + 'pub(crate) fn ttbat_is_clear(', 'pub(crate) fn bootstrap(', 'fn verify_root(', 'fn shadow_l2(', 'pub(crate) fn sync_range(', 'fn sync_inner(', ]) prot_constants = pt[pt.index('const PTE_TYPE_BITS:'):pt.index('impl Prot {')] @@ -41,7 +51,9 @@ def body(source, marker): mod hw { pub const PAGE:u64=0x4000; pub const TABLES_SIZE:u64=0x40000; pub const UPPER:u64=0xfffffc0000000000; pub const HOST:u64=0xfffffc2000000000; pub const HOST_SIZE:u64=0x1000000000; pub const PPL_MAGIC:u64=0x4b1d000000000002; - pub const PA_MASK:u64=0x3ffffffc000; } + pub const PA_MASK:u64=0x3ffffffc000; + use std::ops::Range; + __HW_LEAVES__ } mod device { pub struct Device; } // The common PPL lease is modeled here; test-ppl.py executes its actual guard with // concurrency and timeout injection. This harness tests Window's graph operations. @@ -51,6 +63,7 @@ def body(source, marker): pub fn kernel_lower_root(&self)->u64 {self.lower} pub fn kernel_window_root(&self)->u64 {self.shadow} pub fn lock_m4_handoff(&self)->super::Result{super::note("ppl-lock");Ok(HandoffGuard)} } } macro_rules! dev_info {($($tt:tt)*)=>{()};} +macro_rules! dev_err {($($tt:tt)*)=>{()};} thread_local!{static TRACE:RefCell>=const{RefCell::new(Vec::new())};} fn note(s:impl Into){TRACE.with(|t|t.borrow_mut().push(s.into()));} fn take_trace()->Vec{TRACE.with(|t|std::mem::take(&mut *t.borrow_mut()))} @@ -64,9 +77,12 @@ def body(source, marker): fn try_write32(&self,v:u32,off:usize)->Result{self.data.borrow_mut().get_mut(off..off+4).ok_or(EINVAL)?.copy_from_slice(&v.to_le_bytes());note(format!("{}:{off:x}={v:x}",self.label));Ok(())} fn try_write64(&self,v:u64,off:usize)->Result{self.data.borrow_mut().get_mut(off..off+8).ok_or(EINVAL)?.copy_from_slice(&v.to_le_bytes());note(format!("{}:{off:x}={v:x}",self.label));Ok(())} } -struct Monotonic; struct Delta; impl Delta{fn from_millis(ms:u64)->u64{ms}} +struct Monotonic; +#[derive(Copy,Clone,PartialEq,Eq,PartialOrd,Ord)] struct Delta(u64); +impl Delta{fn from_millis(ms:u64)->Self{Self(ms)}fn as_micros_ceil(self)->u64{self.0*1000}} +fn fsleep(_:Delta){} struct Instant{n:std::cell::Cell,t:std::marker::PhantomData} -impl Instant{fn now()->Self{Self{n:std::cell::Cell::new(0),t:std::marker::PhantomData}}fn elapsed(&self)->u64{let n=self.n.get();self.n.set(n+1);n}} +impl Instant{fn now()->Self{Self{n:std::cell::Cell::new(0),t:std::marker::PhantomData}}fn elapsed(&self)->Delta{let n=self.n.get();self.n.set(n+500);Delta(n)}} fn mb(){note("mb");} fn wmb(){note("wmb");} fn rmb(){} mod mem{pub fn sync(){super::note("sync");}pub fn tlbi_range(asid:u8,va:usize,len:usize){super::note(format!("tlbi:{asid}:{va:x}:{len:x}"));}} fn tlbi_all(){note("tlbi_all");} fn clean_lower(_: &mmu::Uat)->Result{note("clean_lower");Ok(())} @@ -75,8 +91,8 @@ def body(source, marker): fn entry(pa:u64,index:usize)->Result{with_table(pa,index+1,|e|e[index].load(Ordering::Acquire))} fn clean_entries(pa:u64,first:usize,count:usize)->Result{with_table(pa,first+count,|_|())?;note(format!("clean:{pa:x}:{first}:{count}"));Ok(())} fn clean_page(pa:u64)->Result{clean_entries(pa,0,ENTRIES)} -struct Window{handoff:Mapping,ttbs:Mapping,root:Mapping,shared_l2:Mapping,image:Vec,snapshot:Vec,published:bool,firmware_root:[u64;2],text_pa:u64,data_pa:u64} -impl Window{fn blank()->Self{Self{handoff:Mapping::new(0x807000000,0x4000,"handoff"),ttbs:Mapping::new(0x808000000,0x4000,"ttbs"),root:Mapping::new(0x800000000,0x40000,"root"),shared_l2:Mapping::new(0x801000000,0x4000,"shared"),image:vec![0;2048],snapshot:vec![0;2048],published:false,firmware_root:[0;2],text_pa:0x802000000,data_pa:0x803000000}} +struct Window{abi:hw::FwAbi,handoff:Mapping,ttbs:Mapping,root:Mapping,shared_l2:Mapping,image:Vec,snapshot:Vec,published:bool,firmware_root:[u64;2],text_pa:u64,data_pa:u64,leaves:&'static [hw::Leaves],ppl:hw::PplMagic} +impl Window{fn blank()->Self{Self{abi:hw::FwAbi::V25G83,handoff:Mapping::new(0x807000000,0x4000,"handoff"),ttbs:Mapping::new(0x808000000,0x4000,"ttbs"),root:Mapping::new(0x800000000,0x40000,"root"),shared_l2:Mapping::new(0x801000000,0x4000,"shared"),image:vec![0;2048],snapshot:vec![0;2048],published:false,firmware_root:[0;2],text_pa:0x802000000,data_pa:0x803000000,leaves:hw::LEAVES_25G83,ppl:hw::PplMagic{ap:hw::PPL_MAGIC,firmware:hw::PPL_MAGIC,answers:false}}} ''' post = r''' } @@ -103,6 +119,54 @@ def body(source, marker): for i in 0..195{w.handoff.try_write64(1,0x20+i*8).unwrap();assert_eq!(w.admit_cold(),Err(EBUSY));w.handoff.try_write64(0,0x20+i*8).unwrap();} for i in 0..128{w.ttbs.try_write64(1,i*8).unwrap();assert_eq!(w.admit_cold(),Err(EBUSY));w.ttbs.try_write64(0,i*8).unwrap();} } +fn live_root_tests() { + for abi in [hw::FwAbi::V25G83, hw::FwAbi::V26B123, hw::FwAbi::V26B123G15S] { + let mut w = Window::blank(); + w.abi = abi; + let compact = abi == hw::FwAbi::V26B123G15S; + let g15_table = (w.root.pa + 3 * hw::PAGE) | 0x403; + let g16_table = (w.root.pa + 4 * hw::PAGE) | 0x00200000000004cb; + let (table, other) = if compact { (g15_table, g16_table) } else { (g16_table, g15_table) }; + w.root.try_write64(w.shared_l2.pa | 3, 16).unwrap(); + w.root.try_write64(other, 8).unwrap(); + assert_eq!(w.verify_root(), Err(EIO)); + w.root.try_write64(table, 8).unwrap(); + w.verify_root().unwrap(); + let flags = if compact { 0x403 } else { 0x00200000000004cb }; + let wrong_flags = if compact { 0x00200000000004cb } else { 0x403 }; + w.root.try_write64(w.shared_l2.pa | wrong_flags, 16).unwrap(); + assert_eq!(w.verify_root(), Err(EIO)); + w.root.try_write64(w.shared_l2.pa | flags, 16).unwrap(); + w.verify_root().unwrap(); + w.root.try_write64((w.shared_l2.pa + hw::PAGE) | flags, 16).unwrap(); + assert_eq!(w.verify_root(), Err(EIO)); + w.root.try_write64(w.shared_l2.pa | flags, 16).unwrap(); + w.root.try_write64(0, 8).unwrap(); + assert_eq!(w.verify_root(), Err(EIO)); + } +} +// 26B123: the firmware builds its own tree at start, so only an empty tree is admitted, and it +// leaves its own magic at +8 of the handoff page once it has run. +fn firmware_built_tree_tests(){ + live_root_tests(); + const FW:u64=0x4b1d000000000003; + let fresh=||{let mut w=Window::blank();w.leaves=&[];w.ppl=hw::PplMagic{ap:FW,firmware:FW,answers:true};w}; + assert!(fresh().admit_cold().is_ok()); + let mut built=seeded();built.leaves=&[];assert_eq!(built.admit_cold(),Err(EINVAL)); + let mut w=fresh();w.root.try_write64(fw_word(0,&w),0).unwrap();assert_eq!(w.admit_cold(),Err(EINVAL)); + let mut w=fresh(); + w.handoff.try_write64(FW,8).unwrap();assert!(w.admit_cold().is_ok()); + w.handoff.try_write64(hw::PPL_MAGIC,8).unwrap();assert_eq!(w.admit_cold(),Err(EBUSY)); + w.handoff.try_write64(0,8).unwrap();w.handoff.try_write64(hw::PPL_MAGIC,0).unwrap();assert_eq!(w.admit_cold(),Err(EBUSY)); + w.handoff.try_write64(FW,0).unwrap();assert!(w.admit_cold().is_ok()); + let uat=mmu::Uat{lower:0x804000000,shadow:0x805000000};let l2=0x805004000;let l3=0x805008000; + {let mut ram=RAM.lock().unwrap();for pa in [uat.shadow,l2,l3]{ram.insert(pa,(0..2048).map(|_|AtomicU64::new(0)).collect());}ram[&uat.shadow][2].store(l2|3,Ordering::Release);} + for firmware_magic in [0,FW]{let mut w=fresh();w.handoff.try_write64(firmware_magic,8).unwrap();w.bootstrap(&device::Device,&uat).unwrap(); + // Answering builds always clear +8 before RUN so a stale magic cannot satisfy the wait. + assert_eq!(w.handoff.try_read64(0).unwrap(),FW);assert_eq!(w.handoff.try_read64(8).unwrap(),0);assert_eq!(w.handoff.try_read8(0x638).unwrap(),1); + assert_eq!(w.await_firmware_magic(&device::Device),Err(ETIMEDOUT)); + w.handoff.try_write64(FW,8).unwrap();assert_eq!(w.await_firmware_magic(&device::Device),Ok(()));} +} fn publication_tests(){ let uat=mmu::Uat{lower:0x804000000,shadow:0x805000000};let l2=0x805004000;let l3=0x805008000; {let mut ram=RAM.lock().unwrap();for pa in [uat.shadow,l2,l3]{ram.insert(pa,(0..2048).map(|_|AtomicU64::new(0)).collect());}ram[&uat.shadow][2].store(l2|3,Ordering::Release);ram[&l2][4].store(l3|3,Ordering::Release);ram[&l3][0].store(0x806000000|0x00e000000000040b,Ordering::Release);} @@ -117,9 +181,9 @@ def body(source, marker): for p in [0x00c000000000044bu64,0x00e000000000040b,0x00c0000000000443,0x00e0000000000403,0x00c0000000000447,0x0080000000000447,0x00200000000004c7]{assert_eq!(Prot::from_pte(p).leaf_bits()|3,p);} let ranges=reserved_ranges();assert_eq!(ranges,[0x1000000000..0x1000010000,0x7000000000..0x7100000000]);assert_eq!(ranges[1].end-ranges[1].start,4u64<<30); } -fn main(){let args:Vec<_>=std::env::args().collect();for id in 0..12{assert_c_parity(&mutation(id),id,&args[1],&args[2]);}root_admission_tests();publication_tests();prot_and_va_tests();println!("12 C/Rust firmware-graph parity fixtures; 195 flush, 128 TTBAT ownership rejections; stopped publication ordering; live link ownership/global TLBI; exact M4 leaf classes/VA reservations passed (mock hardware; PPL lease mocked and tested separately)");} +fn main(){let args:Vec<_>=std::env::args().collect();for id in 0..12{assert_c_parity(&mutation(id),id,&args[1],&args[2]);}root_admission_tests();publication_tests();firmware_built_tree_tests();prot_and_va_tests();println!("12 C/Rust firmware-graph parity fixtures; 195 flush, 128 TTBAT ownership rejections; stopped publication ordering; live link ownership/global TLBI; exact M4 leaf classes/VA reservations; empty firmware-built tree and +8 firmware magic passed (mock hardware; PPL lease mocked and tested separately)");} ''' -harness = pre + methods + post + prot_constants + prot_impl + reserved +harness = pre.replace('__HW_LEAVES__', hw_leaves) + methods + post + prot_constants + prot_impl + reserved (OUT/'check-vm.rs').write_text(harness) golden = OUT/'golden' diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/thermal_host.py b/tools/testing/selftests/drivers/gpu/asahi-m4/thermal_host.py index 711c6ac37bc3c2..75d0c1c8e8daa7 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/thermal_host.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/thermal_host.py @@ -13,10 +13,13 @@ def build(root, out, source): 'types.h': '#pragma once\n#include \n#include \n' 'typedef uint8_t u8; typedef uint32_t u32;\n' 'typedef int32_t s32; typedef int64_t s64;\n', - 'io.h': '#pragma once\n#include \n#define __iomem\n' - '#define memcpy_fromio memcpy\n', + 'io.h': '#pragma once\n#include \n#include \n#define __iomem\n' + '#define memcpy_fromio memcpy\n' + 'static inline uint32_t readl_relaxed(const void *p) {\n' + ' uint32_t v; memcpy(&v, p, 4); return v; }\n', 'kernel.h': '#pragma once\n#include \n#include \n' '#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))\n' + '#define READ_ONCE(x) (*(const volatile __typeof__(x) *)&(x))\n' '#define DIV_ROUND_CLOSEST(x, d) ' '(((x) < 0 ? (x) - (d) / 2 : (x) + (d) / 2) / (d))\n', 'string.h': '#pragma once\n#include \n', diff --git a/tools/testing/selftests/drivers/gpu/asahi-userptr/userptr.c b/tools/testing/selftests/drivers/gpu/asahi-userptr/userptr.c index abb5ba2f5402cd..3f1d4d25d9d394 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-userptr/userptr.c +++ b/tools/testing/selftests/drivers/gpu/asahi-userptr/userptr.c @@ -3,9 +3,7 @@ * DRM_IOCTL_ASAHI_GEM_USERPTR on the GPU's render node: what it accepts and * refuses, and the accounting (VmPin in /proc/self/status, the client's * drm-total-system in its fdinfo). No GPU work is submitted. Skipped where - * the render node is not this driver's or lacks the feature, and where the - * caller has neither CAP_IPC_LOCK nor a RLIMIT_MEMLOCK hard limit with room - * for the four pages a test pins. + * the render node is not this driver's or lacks the feature. */ #include #include @@ -147,38 +145,9 @@ static int drop_cap_ipc_lock(void) return syscall(SYS_capset, &header, data) ? -errno : 0; } -/* The largest range a test binds, and the most one pins outside memlock_limit. */ +/* The largest range a test binds. */ #define BIND_MAX (4 * PAGE) -/* - * Whether this process may pin BIND_MAX more: it has CAP_IPC_LOCK, or - * RLIMIT_MEMLOCK has room for it, after raising the soft limit to the hard - * one if that takes it. - */ -static int memlock_room(void) -{ - struct __user_cap_header_struct header = { - .version = _LINUX_CAPABILITY_VERSION_3, - }; - struct __user_cap_data_struct data[_LINUX_CAPABILITY_U32S_3]; - long pin = vm_pin_kb(); - uint64_t need = (pin > 0 ? (uint64_t)pin << 10 : 0) + BIND_MAX; - struct rlimit lim; - - if (!syscall(SYS_capget, &header, data) && - (data[CAP_TO_INDEX(CAP_IPC_LOCK)].effective & - CAP_TO_MASK(CAP_IPC_LOCK))) - return 1; - if (getrlimit(RLIMIT_MEMLOCK, &lim)) - return 0; - if (lim.rlim_cur == RLIM_INFINITY || lim.rlim_cur >= need) - return 1; - if (lim.rlim_max != RLIM_INFINITY && lim.rlim_max < need) - return 0; - lim.rlim_cur = lim.rlim_max; - return !setrlimit(RLIMIT_MEMLOCK, &lim); -} - /* * A GPU address at which BIND_MAX bytes can be bound. The driver keeps * ranges of every VM for its own mappings, where a bind fails with EINVAL, @@ -221,9 +190,6 @@ FIXTURE_SETUP(asahi) ASSERT_EQ(0, ioc(self->fd, DRM_IOCTL_ASAHI_GET_PARAMS, &get)); if (!(self->params.features & DRM_ASAHI_FEATURE_USERPTR)) SKIP(return, "no DRM_ASAHI_FEATURE_USERPTR"); - if (!memlock_room()) - SKIP(return, "RLIMIT_MEMLOCK has no room for the %lu bytes a test pins", - BIND_MAX); uint64_t kernel = self->params.vm_kernel_min_size > (32ULL << 30) ? self->params.vm_kernel_min_size : 32ULL << 30; @@ -360,48 +326,36 @@ TEST_F(asahi, read_only_file_pages) } /* - * RLIMIT_MEMLOCK bounds the pages of a caller without CAP_IPC_LOCK. The test - * gives the capability up first (the harness runs each test in a process of - * its own), so a request above the limit has to fail whoever runs it. It - * lowers the soft limit to what the process has pinned already plus 16 pages, - * or as many as the hard limit has room for, and is skipped where that is - * less than two. + * RLIMIT_MEMLOCK does not bound the pages: the GPU memory limits do, as for + * GEM_CREATE objects. The test gives CAP_IPC_LOCK up first (the harness runs + * each test in a process of its own) and lowers the soft limit to 0, so a + * memlock check would refuse whoever runs it. The pages still show in VmPin. */ -TEST_F(asahi, memlock_limit) +TEST_F(asahi, memlock_does_not_bound) { + const uint64_t size = 64 * PAGE; struct rlimit old, lim; long pin0 = vm_pin_kb(); - uint64_t pinned = pin0 > 0 ? (uint64_t)pin0 << 10 : 0; - uint64_t pages = 16, size; + long long total0 = client_total(self->fd); uint32_t h = 0; void *mem; + /* The kernel says so, for userspace that checks before it imports. */ + EXPECT_TRUE(self->params.features & DRM_ASAHI_FEATURE_USERPTR_NO_MEMLOCK); ASSERT_EQ(0, drop_cap_ipc_lock()); ASSERT_EQ(0, getrlimit(RLIMIT_MEMLOCK, &old)); - if (old.rlim_max != RLIM_INFINITY) { - uint64_t room = old.rlim_max > pinned ? - (old.rlim_max - pinned) / PAGE : 0; - - if (room < pages) - pages = room; - } - if (pages < 2) - SKIP(return, "no room for two pages in the RLIMIT_MEMLOCK hard limit of %llu bytes", - (unsigned long long)old.rlim_max); - size = 4 * pages * PAGE; mem = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); ASSERT_NE(MAP_FAILED, mem); - lim.rlim_cur = pinned + pages * PAGE; + lim.rlim_cur = 0; lim.rlim_max = old.rlim_max; ASSERT_EQ(0, setrlimit(RLIMIT_MEMLOCK, &lim)); - ASSERT_EQ(-ENOMEM, userptr(self->fd, mem, size, 0, 0, &h)); - EXPECT_EQ(pin0, vm_pin_kb()); - EXPECT_EQ(0, userptr(self->fd, mem, pages / 2 * PAGE, 0, 0, &h)); - /* The pages already pinned count against the limit too. */ - EXPECT_EQ(-ENOMEM, userptr(self->fd, (char *)mem + pages / 2 * PAGE, - pages * PAGE, 0, 0, &h)); + ASSERT_EQ(0, userptr(self->fd, mem, size, 0, 0, &h)); + EXPECT_EQ(pin0 + (long)(size >> 10), vm_pin_kb()); + EXPECT_EQ(total0 + (long long)size, client_total(self->fd)); close_handle(self->fd, h); + EXPECT_EQ(pin0, vm_pin_kb()); + EXPECT_EQ(total0, client_total(self->fd)); setrlimit(RLIMIT_MEMLOCK, &old); munmap(mem, size); }